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` 的距离: - -![](./images/linked-list-cycle-ii.png) - -我们根据式子 ①②,得出 `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, 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 - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/lcci/17.11.Find Closest/README_EN.md b/lcci/17.11.Find Closest/README_EN.md index e0026b21d7766..e5aa89be6cce9 100644 --- a/lcci/17.11.Find Closest/README_EN.md +++ b/lcci/17.11.Find Closest/README_EN.md @@ -22,9 +22,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -39,26 +39,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) { @@ -77,31 +57,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 { @@ -122,24 +116,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 + + +### Solution 2 + + + +```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 @@ -164,30 +208,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{} @@ -219,34 +239,6 @@ func abs(x int) int { } ``` -### **Rust** - -```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 - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/lcci/17.12.BiNode/README.md b/lcci/17.12.BiNode/README.md index f3709acb8b79a..76329b25cce37 100644 --- a/lcci/17.12.BiNode/README.md +++ b/lcci/17.12.BiNode/README.md @@ -27,9 +27,7 @@ ## 解法 - - -**方法一:中序遍历** +### 方法一:中序遍历 中序遍历过程中改变指针指向。 @@ -39,10 +37,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -70,10 +64,6 @@ class Solution: return dummy.right ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -171,10 +157,6 @@ func convertBiNode(root *TreeNode) *TreeNode { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.12.BiNode/README_EN.md b/lcci/17.12.BiNode/README_EN.md index f64f6c6402248..51b5451834308 100644 --- a/lcci/17.12.BiNode/README_EN.md +++ b/lcci/17.12.BiNode/README_EN.md @@ -30,12 +30,10 @@ ## Solutions -Similar to [897. Increasing Order Search Tree](/solution/0800-0899/0897.Increasing%20Order%20Search%20Tree/README_EN.md). +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -63,8 +61,6 @@ class Solution: return dummy.right ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -132,8 +126,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -162,10 +154,6 @@ func convertBiNode(root *TreeNode) *TreeNode { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.13.Re-Space/README.md b/lcci/17.13.Re-Space/README.md index a7a0d9988bd2c..ec551c3356209 100644 --- a/lcci/17.13.Re-Space/README.md +++ b/lcci/17.13.Re-Space/README.md @@ -31,16 +31,10 @@ sentence = "jesslookedjustliketimherbrother" ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 -### **Python3** - - - ```python class Solution: def respace(self, dictionary: List[str], sentence: str) -> int: @@ -55,10 +49,6 @@ class Solution: return dp[-1] ``` -### **Java** - - - ```java class Solution { public int respace(String[] dictionary, String sentence) { @@ -78,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +88,6 @@ public: }; ``` -### **Go** - ```go func respace(dictionary []string, sentence string) int { s := map[string]bool{} @@ -122,10 +108,6 @@ func respace(dictionary []string, sentence string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.13.Re-Space/README_EN.md b/lcci/17.13.Re-Space/README_EN.md index ca4cfbab0d6b5..7e7fe5adb4504 100644 --- a/lcci/17.13.Re-Space/README_EN.md +++ b/lcci/17.13.Re-Space/README_EN.md @@ -36,9 +36,9 @@ sentence = "jesslookedjustliketimherbrother" ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return dp[-1] ``` -### **Java** - ```java class Solution { public int respace(String[] dictionary, String sentence) { @@ -75,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +93,6 @@ public: }; ``` -### **Go** - ```go func respace(dictionary []string, sentence string) int { s := map[string]bool{} @@ -119,10 +113,6 @@ func respace(dictionary []string, sentence string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.14.Smallest K/README.md b/lcci/17.14.Smallest K/README.md index fbcbe3fe4e70e..d24dd1b51eb2d 100644 --- a/lcci/17.14.Smallest K/README.md +++ b/lcci/17.14.Smallest K/README.md @@ -18,49 +18,20 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 直接排序,取前 k 个数即可。 时间复杂度 $O(n\log n)$。其中 $n$ 为数组长度。 -**方法二:优先队列(大根堆)** - -维护一个大小为 $k$ 的大根堆,遍历数组,将当前元素入堆,如果堆的大小超过 $k$,弹出堆顶元素。 - -遍历结束,将堆中元素的 $k$ 个元素取出即可。 - -时间复杂度 $O(n\log k)$。其中 $n$ 为数组长度。 - -### **Python3** - - - ```python class Solution: def smallestK(self, arr: List[int], k: int) -> List[int]: return sorted(arr)[:k] ``` -```python -class Solution: - def smallestK(self, arr: List[int], k: int) -> List[int]: - h = [] - for v in arr: - heappush(h, -v) - if len(h) > k: - heappop(h) - return [-v for v in h] -``` - -### **Java** - - - ```java class Solution { public int[] smallestK(int[] arr, int k) { @@ -74,6 +45,54 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector smallestK(vector& arr, int k) { + sort(arr.begin(), arr.end()); + vector ans(k); + for (int i = 0; i < k; ++i) { + ans[i] = arr[i]; + } + return ans; + } +}; +``` + +```go +func smallestK(arr []int, k int) []int { + sort.Ints(arr) + ans := make([]int, k) + for i, v := range arr[:k] { + ans[i] = v + } + return ans +} +``` + + + +### 方法二:优先队列(大根堆) + +维护一个大小为 $k$ 的大根堆,遍历数组,将当前元素入堆,如果堆的大小超过 $k$,弹出堆顶元素。 + +遍历结束,将堆中元素的 $k$ 个元素取出即可。 + +时间复杂度 $O(n\log k)$。其中 $n$ 为数组长度。 + + + +```python +class Solution: + def smallestK(self, arr: List[int], k: int) -> List[int]: + h = [] + for v in arr: + heappush(h, -v) + if len(h) > k: + heappop(h) + return [-v for v in h] +``` + ```java class Solution { public int[] smallestK(int[] arr, int k) { @@ -94,22 +113,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector smallestK(vector& arr, int k) { - sort(arr.begin(), arr.end()); - vector ans(k); - for (int i = 0; i < k; ++i) { - ans[i] = arr[i]; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -131,19 +134,6 @@ public: }; ``` -### **Go** - -```go -func smallestK(arr []int, k int) []int { - sort.Ints(arr) - ans := make([]int, k) - for i, v := range arr[:k] { - ans[i] = v - } - return ans -} -``` - ```go func smallestK(arr []int, k int) []int { q := hp{} @@ -172,10 +162,6 @@ func (h *hp) Pop() any { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.14.Smallest K/README_EN.md b/lcci/17.14.Smallest K/README_EN.md index 207c51fc97a36..2aba87db0e53f 100644 --- a/lcci/17.14.Smallest K/README_EN.md +++ b/lcci/17.14.Smallest K/README_EN.md @@ -21,9 +21,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -31,19 +31,6 @@ class Solution: return sorted(arr)[:k] ``` -```python -class Solution: - def smallestK(self, arr: List[int], k: int) -> List[int]: - h = [] - for v in arr: - heappush(h, -v) - if len(h) > k: - heappop(h) - return [-v for v in h] -``` - -### **Java** - ```java class Solution { public int[] smallestK(int[] arr, int k) { @@ -57,6 +44,48 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector smallestK(vector& arr, int k) { + sort(arr.begin(), arr.end()); + vector ans(k); + for (int i = 0; i < k; ++i) { + ans[i] = arr[i]; + } + return ans; + } +}; +``` + +```go +func smallestK(arr []int, k int) []int { + sort.Ints(arr) + ans := make([]int, k) + for i, v := range arr[:k] { + ans[i] = v + } + return ans +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def smallestK(self, arr: List[int], k: int) -> List[int]: + h = [] + for v in arr: + heappush(h, -v) + if len(h) > k: + heappop(h) + return [-v for v in h] +``` + ```java class Solution { public int[] smallestK(int[] arr, int k) { @@ -77,22 +106,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector smallestK(vector& arr, int k) { - sort(arr.begin(), arr.end()); - vector ans(k); - for (int i = 0; i < k; ++i) { - ans[i] = arr[i]; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -114,19 +127,6 @@ public: }; ``` -### **Go** - -```go -func smallestK(arr []int, k int) []int { - sort.Ints(arr) - ans := make([]int, k) - for i, v := range arr[:k] { - ans[i] = v - } - return ans -} -``` - ```go func smallestK(arr []int, k int) []int { q := hp{} @@ -155,10 +155,6 @@ func (h *hp) Pop() any { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.15.Longest Word/README.md b/lcci/17.15.Longest Word/README.md index 502113f1f6cf5..617447d48ffc2 100644 --- a/lcci/17.15.Longest Word/README.md +++ b/lcci/17.15.Longest Word/README.md @@ -19,16 +19,10 @@ ## 解法 - - -**方法一:前缀树 + DFS** +### 方法一:前缀树 + DFS -### **Python3** - - - ```python class Trie: def __init__(self): @@ -76,10 +70,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Trie { Trie[] children = new Trie[26]; @@ -144,8 +134,6 @@ class Solution { } ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -211,10 +199,6 @@ func longestWord(words []string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.15.Longest Word/README_EN.md b/lcci/17.15.Longest Word/README_EN.md index b882885a61fc1..28ad561bf3da9 100644 --- a/lcci/17.15.Longest Word/README_EN.md +++ b/lcci/17.15.Longest Word/README_EN.md @@ -27,9 +27,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -78,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java class Trie { Trie[] children = new Trie[26]; @@ -144,8 +142,6 @@ class Solution { } ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -211,10 +207,6 @@ func longestWord(words []string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.16.The Masseuse/README.md b/lcci/17.16.The Masseuse/README.md index f8a2476cda51b..196dd65e92c46 100644 --- a/lcci/17.16.The Masseuse/README.md +++ b/lcci/17.16.The Masseuse/README.md @@ -34,9 +34,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义状态 $f[i]$ 表示考虑前 $i$ 个预约,且第 $i$ 个预约被接受的情况下,最长的预约时长;定义状态 $g[i]$ 表示考虑前 $i$ 个预约,且第 $i$ 个预约被拒绝的情况下,最长的预约时长。 @@ -57,10 +55,6 @@ $$ -### **Python3** - - - ```python class Solution: def massage(self, nums: List[int]) -> int: @@ -70,10 +64,6 @@ class Solution: return max(f, g) ``` -### **Java** - - - ```java class Solution { public int massage(int[] nums) { @@ -89,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func massage(nums []int) int { f, g := 0, 0 @@ -119,8 +105,6 @@ func massage(nums []int) int { } ``` -### **TypeScript** - ```ts function massage(nums: number[]): number { let f = 0, @@ -135,10 +119,6 @@ function massage(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.16.The Masseuse/README_EN.md b/lcci/17.16.The Masseuse/README_EN.md index bbdf58b900052..63b5510be2d38 100644 --- a/lcci/17.16.The Masseuse/README_EN.md +++ b/lcci/17.16.The Masseuse/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return max(f, g) ``` -### **Java** - ```java class Solution { public int massage(int[] nums) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func massage(nums []int) int { f, g := 0, 0 @@ -108,8 +102,6 @@ func massage(nums []int) int { } ``` -### **TypeScript** - ```ts function massage(nums: number[]): number { let f = 0, @@ -124,10 +116,6 @@ function massage(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.17.Multi Search/README.md b/lcci/17.17.Multi Search/README.md index 9321f1c86ed7a..5223a7ecc7ee0 100644 --- a/lcci/17.17.Multi Search/README.md +++ b/lcci/17.17.Multi Search/README.md @@ -27,16 +27,10 @@ smalls = ["is","ppi","hi","sis","i& ## 解法 - - -**方法一:前缀树** +### 方法一:前缀树 -### **Python3** - - - ```python class Trie: def __init__(self): @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] multiSearch(String big, String[] smalls) { @@ -149,8 +139,6 @@ class Trie { } ``` -### **C++** - ```cpp class Trie { private: @@ -202,8 +190,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -260,10 +246,6 @@ func multiSearch(big string, smalls []string) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.17.Multi Search/README_EN.md b/lcci/17.17.Multi Search/README_EN.md index 17340a2cce46f..046e3639f1730 100644 --- a/lcci/17.17.Multi Search/README_EN.md +++ b/lcci/17.17.Multi Search/README_EN.md @@ -32,9 +32,9 @@ smalls = ["is","ppi","hi","sis","i& ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -78,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] multiSearch(String big, String[] smalls) { @@ -146,8 +144,6 @@ class Trie { } ``` -### **C++** - ```cpp class Trie { private: @@ -199,8 +195,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -257,10 +251,6 @@ func multiSearch(big string, smalls []string) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.18.Shortest Supersequence/README.md b/lcci/17.18.Shortest Supersequence/README.md index 624705166151e..60e46bd5b94c6 100644 --- a/lcci/17.18.Shortest Supersequence/README.md +++ b/lcci/17.18.Shortest Supersequence/README.md @@ -26,9 +26,7 @@ small = [4] ## 解法 - - -**方法一:哈希表 + 双指针** +### 方法一:哈希表 + 双指针 我们定义两个哈希表,其中哈希表 $need$ 用于存储数组 $small$ 中的元素及其出现次数,哈希表 $window$ 用于存储当前滑动窗口中的元素及其出现次数。另外,我们用变量 $cnt$ 记录当前未满足条件的元素个数,用变量 $mi$ 记录最短子数组的长度,用变量 $k$ 记录最短子数组的左端点。 @@ -38,10 +36,6 @@ small = [4] -### **Python3** - - - ```python class Solution: def shortestSeq(self, big: List[int], small: List[int]) -> List[int]: @@ -63,10 +57,6 @@ class Solution: return [] if k < 0 else [k, k + mi - 1] ``` -### **Java** - - - ```java class Solution { public int[] shortestSeq(int[] big, int[] small) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func shortestSeq(big []int, small []int) []int { cnt := len(small) @@ -170,8 +156,6 @@ func shortestSeq(big []int, small []int) []int { } ``` -### **TypeScript** - ```ts function shortestSeq(big: number[], small: number[]): number[] { let cnt = small.length; @@ -203,10 +187,6 @@ function shortestSeq(big: number[], small: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.18.Shortest Supersequence/README_EN.md b/lcci/17.18.Shortest Supersequence/README_EN.md index f266c9c473a2e..9a5847f4fba9e 100644 --- a/lcci/17.18.Shortest Supersequence/README_EN.md +++ b/lcci/17.18.Shortest Supersequence/README_EN.md @@ -36,9 +36,9 @@ small = [4] ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return [] if k < 0 else [k, k + mi - 1] ``` -### **Java** - ```java class Solution { public int[] shortestSeq(int[] big, int[] small) { @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +127,6 @@ public: }; ``` -### **Go** - ```go func shortestSeq(big []int, small []int) []int { cnt := len(small) @@ -166,8 +160,6 @@ func shortestSeq(big []int, small []int) []int { } ``` -### **TypeScript** - ```ts function shortestSeq(big: number[], small: number[]): number[] { let cnt = small.length; @@ -199,10 +191,6 @@ function shortestSeq(big: number[], small: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.19.Missing Two/README.md b/lcci/17.19.Missing Two/README.md index 12d4caa06c3b8..64ae1460d273d 100644 --- a/lcci/17.19.Missing Two/README.md +++ b/lcci/17.19.Missing Two/README.md @@ -27,9 +27,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 利用位运算的性质: @@ -45,10 +43,6 @@ -### **Python3** - - - ```python class Solution: def missingTwo(self, nums: List[int]) -> List[int]: @@ -71,10 +65,6 @@ class Solution: return [a, b] ``` -### **Java** - - - ```java class Solution { public int[] missingTwo(int[] nums) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func missingTwo(nums []int) []int { n := len(nums) + 2 @@ -156,10 +142,6 @@ func missingTwo(nums []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.19.Missing Two/README_EN.md b/lcci/17.19.Missing Two/README_EN.md index 67dd13c5a449c..31be29535a171 100644 --- a/lcci/17.19.Missing Two/README_EN.md +++ b/lcci/17.19.Missing Two/README_EN.md @@ -32,9 +32,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return [a, b] ``` -### **Java** - ```java class Solution { public int[] missingTwo(int[] nums) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func missingTwo(nums []int) []int { n := len(nums) + 2 @@ -141,10 +135,6 @@ func missingTwo(nums []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.20.Continuous Median/README.md b/lcci/17.20.Continuous Median/README.md index 38c6190d63ae4..41c5cc487a17f 100644 --- a/lcci/17.20.Continuous Median/README.md +++ b/lcci/17.20.Continuous Median/README.md @@ -33,9 +33,7 @@ findMedian() -> 2 ## 解法 - - -**方法一:优先队列(双堆)** +### 方法一:优先队列(双堆) 创建大根堆、小根堆,其中:大根堆存放较小的一半元素,小根堆存放较大的一半元素。 @@ -49,10 +47,6 @@ findMedian() -> 2 -### **Python3** - - - ```python class MedianFinder: def __init__(self): @@ -80,10 +74,6 @@ class MedianFinder: # param_2 = obj.findMedian() ``` -### **Java** - - - ```java class MedianFinder { private PriorityQueue q1 = new PriorityQueue<>(); @@ -117,8 +107,6 @@ class MedianFinder { */ ``` -### **C++** - ```cpp class MedianFinder { public: @@ -156,8 +144,6 @@ private: */ ``` -### **Go** - ```go type MedianFinder struct { q1 hp @@ -203,10 +189,6 @@ func (h *hp) Pop() any { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.20.Continuous Median/README_EN.md b/lcci/17.20.Continuous Median/README_EN.md index f0f0f0c21701a..36712289d28f6 100644 --- a/lcci/17.20.Continuous Median/README_EN.md +++ b/lcci/17.20.Continuous Median/README_EN.md @@ -39,9 +39,9 @@ findMedian() -> 2 ## Solutions - +### Solution 1 -### **Python3** + ```python class MedianFinder: @@ -70,8 +70,6 @@ class MedianFinder: # param_2 = obj.findMedian() ``` -### **Java** - ```java class MedianFinder { private PriorityQueue q1 = new PriorityQueue<>(); @@ -105,8 +103,6 @@ class MedianFinder { */ ``` -### **C++** - ```cpp class MedianFinder { public: @@ -144,8 +140,6 @@ private: */ ``` -### **Go** - ```go type MedianFinder struct { q1 hp @@ -191,10 +185,6 @@ func (h *hp) Pop() any { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.21.Volume of Histogram/README.md b/lcci/17.21.Volume of Histogram/README.md index 4da1df3443d26..944a4e428b5ac 100644 --- a/lcci/17.21.Volume of Histogram/README.md +++ b/lcci/17.21.Volume of Histogram/README.md @@ -18,9 +18,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $left[i]$ 表示下标 $i$ 位置及其左边的最高柱子的高度,定义 $right[i]$ 表示下标 $i$ 位置及其右边的最高柱子的高度。那么下标 $i$ 位置能接的雨水量为 $min(left[i], right[i]) - height[i]$。我们遍历数组,计算出 $left[i]$ 和 $right[i]$,最后答案为 $\sum_{i=0}^{n-1} min(left[i], right[i]) - height[i]$。 @@ -32,10 +30,6 @@ -### **Python3** - - - ```python class Solution: def trap(self, height: List[int]) -> int: @@ -50,10 +44,6 @@ class Solution: return sum(min(l, r) - h for l, r, h in zip(left, right, height)) ``` -### **Java** - - - ```java class Solution { public int trap(int[] height) { @@ -78,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +92,6 @@ public: }; ``` -### **Go** - ```go func trap(height []int) (ans int) { n := len(height) @@ -126,8 +112,6 @@ func trap(height []int) (ans int) { } ``` -### **TypeScript** - ```ts function trap(height: number[]): number { const n = height.length; @@ -148,8 +132,6 @@ function trap(height: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int Trap(int[] height) { @@ -174,10 +156,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.21.Volume of Histogram/README_EN.md b/lcci/17.21.Volume of Histogram/README_EN.md index 7e44b302423b1..a689c0cd479b2 100644 --- a/lcci/17.21.Volume of Histogram/README_EN.md +++ b/lcci/17.21.Volume of Histogram/README_EN.md @@ -20,9 +20,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -38,8 +38,6 @@ class Solution: return sum(min(l, r) - h for l, r, h in zip(left, right, height)) ``` -### **Java** - ```java class Solution { public int trap(int[] height) { @@ -64,8 +62,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,8 +86,6 @@ public: }; ``` -### **Go** - ```go func trap(height []int) (ans int) { n := len(height) @@ -112,8 +106,6 @@ func trap(height []int) (ans int) { } ``` -### **TypeScript** - ```ts function trap(height: number[]): number { const n = height.length; @@ -134,8 +126,6 @@ function trap(height: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int Trap(int[] height) { @@ -160,10 +150,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.22.Word Transformer/README.md b/lcci/17.22.Word Transformer/README.md index 842d14a1015bd..8fa326623a555 100644 --- a/lcci/17.22.Word Transformer/README.md +++ b/lcci/17.22.Word Transformer/README.md @@ -33,16 +33,10 @@ wordList = ["hot","dot","dog","lot",&quo ## 解法 - - -DFS。 +### 方法一 -### **Python3** - - - ```python class Solution: def findLadders( @@ -72,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List words; @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go func findLadders(beginWord string, endWord string, wordList []string) []string { var ans []string @@ -217,10 +203,6 @@ func findLadders(beginWord string, endWord string, wordList []string) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.22.Word Transformer/README_EN.md b/lcci/17.22.Word Transformer/README_EN.md index eb4df4ae3a9c6..7626fa1c9f906 100644 --- a/lcci/17.22.Word Transformer/README_EN.md +++ b/lcci/17.22.Word Transformer/README_EN.md @@ -50,12 +50,10 @@ wordList = ["hot","dot","dog","lot",&quo ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python class Solution: def findLadders( @@ -85,8 +83,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List words; @@ -137,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -180,8 +174,6 @@ public: }; ``` -### **Go** - ```go func findLadders(beginWord string, endWord string, wordList []string) []string { var ans []string @@ -228,10 +220,6 @@ func findLadders(beginWord string, endWord string, wordList []string) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.23.Max Black Square/README.md b/lcci/17.23.Max Black Square/README.md index 25ca0c0599a6e..78f51194a2505 100644 --- a/lcci/17.23.Max Black Square/README.md +++ b/lcci/17.23.Max Black Square/README.md @@ -33,9 +33,7 @@ ## 解法 - - -**方法一:预处理 + 枚举** +### 方法一:预处理 + 枚举 我们可以预处理出每个位置 $(i, j)$ 向下和向右的连续 $0$ (黑色像素)的个数,记为 $down[i][j]$ 和 $right[i][j]$。递推公式如下: @@ -71,10 +69,6 @@ $$ -### **Python3** - - - ```python class Solution: def findSquare(self, matrix: List[List[int]]) -> List[int]: @@ -99,10 +93,6 @@ class Solution: return [] ``` -### **Java** - - - ```java class Solution { public int[] findSquare(int[][] matrix) { @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -165,8 +153,6 @@ public: }; ``` -### **Go** - ```go func findSquare(matrix [][]int) []int { n := len(matrix) @@ -202,8 +188,6 @@ func findSquare(matrix [][]int) []int { } ``` -### **TypeScript** - ```ts function findSquare(matrix: number[][]): number[] { const n = matrix.length; @@ -235,10 +219,6 @@ function findSquare(matrix: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.23.Max Black Square/README_EN.md b/lcci/17.23.Max Black Square/README_EN.md index 00451c7bda35c..8024d13ebdc8f 100644 --- a/lcci/17.23.Max Black Square/README_EN.md +++ b/lcci/17.23.Max Black Square/README_EN.md @@ -51,9 +51,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,8 +79,6 @@ class Solution: return [] ``` -### **Java** - ```java class Solution { public int[] findSquare(int[][] matrix) { @@ -110,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +139,6 @@ public: }; ``` -### **Go** - ```go func findSquare(matrix [][]int) []int { n := len(matrix) @@ -180,8 +174,6 @@ func findSquare(matrix [][]int) []int { } ``` -### **TypeScript** - ```ts function findSquare(matrix: number[][]): number[] { const n = matrix.length; @@ -213,10 +205,6 @@ function findSquare(matrix: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.24.Max Submatrix/README.md b/lcci/17.24.Max Submatrix/README.md index 1f71119d44786..601d9c9680767 100644 --- a/lcci/17.24.Max Submatrix/README.md +++ b/lcci/17.24.Max Submatrix/README.md @@ -29,16 +29,10 @@ ## 解法 - - -双指针 i1, i2 遍历所有可能的“行对”,即子矩阵的上下两条边,这决定了矩阵的高,然后枚举 i1~i2 高度的每一列,看成一维数组的一项,求和最大的子数组即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def getMaxMatrix(self, matrix: List[List[int]]) -> List[int]: @@ -71,10 +65,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] getMaxMatrix(int[][] matrix) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func getMaxMatrix(matrix [][]int) []int { m, n := len(matrix), len(matrix[0]) @@ -198,10 +184,6 @@ func getMaxMatrix(matrix [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.24.Max Submatrix/README_EN.md b/lcci/17.24.Max Submatrix/README_EN.md index 6a2f8abbc3e51..39ab8dda6ad5d 100644 --- a/lcci/17.24.Max Submatrix/README_EN.md +++ b/lcci/17.24.Max Submatrix/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -45,6 +45,7 @@ class Solution: s = [[0] * n for _ in range(m + 1)] for i in range(m): for j in range(n): + # 构造列前缀和 s[i + 1][j] = s[i][j] + matrix[i][j] mx = matrix[0][0] @@ -69,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] getMaxMatrix(int[][] matrix) { @@ -110,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +149,6 @@ public: }; ``` -### **Go** - ```go func getMaxMatrix(matrix [][]int) []int { m, n := len(matrix), len(matrix[0]) @@ -194,10 +189,6 @@ func getMaxMatrix(matrix [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.25.Word Rectangle/README.md b/lcci/17.25.Word Rectangle/README.md index be64970e46afb..1b4243e3dc848 100644 --- a/lcci/17.25.Word Rectangle/README.md +++ b/lcci/17.25.Word Rectangle/README.md @@ -28,9 +28,7 @@ ## 解法 - - -**方法一:分组 + 回溯 + 字典树** +### 方法一:分组 + 回溯 + 字典树 我们注意到,构建单词矩阵时所用的单词长度是相同的,因此,我们可以将单词按照长度分组,记录在哈希表 $d$ 中。对于每个长度,我们只需要考虑该长度的单词即可。 @@ -40,10 +38,6 @@ -### **Python3** - - - ```python class Trie: def __init__(self): @@ -109,10 +103,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Trie { Trie[] children = new Trie[26]; @@ -193,8 +183,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -279,8 +267,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -357,10 +343,6 @@ func maxRectangle(words []string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.25.Word Rectangle/README_EN.md b/lcci/17.25.Word Rectangle/README_EN.md index c8a8e15f06b3a..197dac763450f 100644 --- a/lcci/17.25.Word Rectangle/README_EN.md +++ b/lcci/17.25.Word Rectangle/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -108,8 +108,6 @@ class Solution: return ans ``` -### **Java** - ```java class Trie { Trie[] children = new Trie[26]; @@ -190,8 +188,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -276,8 +272,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -354,10 +348,6 @@ func maxRectangle(words []string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.26.Sparse Similarity/README.md b/lcci/17.26.Sparse Similarity/README.md index c6fb284aeee2e..71fad1b00dc63 100644 --- a/lcci/17.26.Sparse Similarity/README.md +++ b/lcci/17.26.Sparse Similarity/README.md @@ -30,9 +30,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 用哈希表 $d$ 记录每个单词对应了哪些文档。 @@ -42,10 +40,6 @@ -### **Python3** - - - ```python class Solution: def computeSimilarities(self, docs: List[List[int]]) -> List[str]: @@ -68,10 +62,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List computeSimilarities(int[][] docs) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp using pii = pair; @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func computeSimilarities(docs [][]int) []string { d := map[int][]int{} @@ -176,10 +162,6 @@ func computeSimilarities(docs [][]int) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/lcci/17.26.Sparse Similarity/README_EN.md b/lcci/17.26.Sparse Similarity/README_EN.md index ad0df6fe508c0..a00cedce0dd9b 100644 --- a/lcci/17.26.Sparse Similarity/README_EN.md +++ b/lcci/17.26.Sparse Similarity/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List computeSimilarities(int[][] docs) { @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp using pii = pair; @@ -144,8 +140,6 @@ public: }; ``` -### **Go** - ```go func computeSimilarities(docs [][]int) []string { d := map[int][]int{} @@ -176,10 +170,6 @@ func computeSimilarities(docs [][]int) []string { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/README.md" index 329014e3f4bd5..5c17b6a3df375 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23003. \346\225\260\347\273\204\344\270\255\351\207\215\345\244\215\347\232\204\346\225\260\345\255\227/README.md" @@ -22,28 +22,14 @@ ## 解法 -**方法一:排序** +### 方法一:排序 我们可以先对数组 `nums` 进行排序,然后遍历排序后的数组,判断相邻的两个元素是否相等,如果相等,即找到了一个重复的数字,返回该数字即可。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组 `nums` 的长度。 -**方法二:哈希表** - -我们可以使用哈希表来解决这个问题,遍历数组 `nums`,对于遍历到的每个元素,判断哈希表中是否存在该元素,如果哈希表中存在该元素,即找到了一个重复的数字,返回该数字即可;如果哈希表中不存在该元素,将该元素加入哈希表中。继续遍历,直到找到一个重复的数字。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `nums` 的长度。 - -**方法三:原地交换** - -我们可以遍历数组 `nums`,对于遍历到的每个元素 `nums[i]`,判断 `nums[i]` 是否等于 `i`,如果是,则继续遍历下一个元素;如果不是,则将 `nums[i]` 与 `nums[nums[i]]` 进行交换,交换之后,`nums[i]` 的值和下标都发生了改变,如果 `nums[i]` 与 `nums[nums[i]]` 相等,即找到了一个重复的数字,返回该数字即可;如果 `nums[i]` 与 `nums[nums[i]]` 不相等,继续遍历,直到找到一个重复的数字。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是数组 `nums` 的长度。 - -### **Python3** - ```python class Solution: def findRepeatNumber(self, nums: List[int]) -> int: @@ -52,29 +38,6 @@ class Solution: return a ``` -```python -class Solution: - def findRepeatNumber(self, nums: List[int]) -> int: - vis = set() - for v in nums: - if v in vis: - return v - vis.add(v) -``` - -```python -class Solution: - def findRepeatNumber(self, nums: List[int]) -> int: - for i, v in enumerate(nums): - while v != i: - if nums[v] == v: - return v - nums[i], nums[v] = nums[v], nums[i] - v = nums[i] -``` - -### **Java** - ```java class Solution { public int findRepeatNumber(int[] nums) { @@ -88,39 +51,6 @@ class Solution { } ``` -```java -class Solution { - public int findRepeatNumber(int[] nums) { - Set vis = new HashSet<>(); - for (int i = 0;; ++i) { - if (!vis.add(nums[i])) { - return nums[i]; - } - } - } -} -``` - -```java -class Solution { - public int findRepeatNumber(int[] nums) { - for (int i = 0;; ++i) { - while (nums[i] != i) { - int j = nums[i]; - if (nums[j] == j) { - return j; - } - int t = nums[i]; - nums[i] = nums[j]; - nums[j] = t; - } - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -135,40 +65,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findRepeatNumber(vector& nums) { - unordered_set vis; - for (int i = 0;; ++i) { - if (vis.count(nums[i])) { - return nums[i]; - } - vis.insert(nums[i]); - } - } -}; -``` - -```cpp -class Solution { -public: - int findRepeatNumber(vector& nums) { - for (int i = 0;; ++i) { - while (nums[i] != i) { - int j = nums[i]; - if (nums[j] == j) { - return j; - } - swap(nums[i], nums[j]); - } - } - } -}; -``` - -### **Go** - ```go func findRepeatNumber(nums []int) int { sort.Ints(nums) @@ -180,54 +76,6 @@ func findRepeatNumber(nums []int) int { } ``` -```go -func findRepeatNumber(nums []int) int { - vis := map[int]bool{} - for i := 0; ; i++ { - if vis[nums[i]] { - return nums[i] - } - vis[nums[i]] = true - } -} -``` - -```go -func findRepeatNumber(nums []int) int { - for i := 0; ; i++ { - for nums[i] != i { - j := nums[i] - if nums[j] == j { - return j - } - nums[i], nums[j] = nums[j], nums[i] - } - } -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var findRepeatNumber = function (nums) { - for (let i = 0; ; ++i) { - while (nums[i] != i) { - const j = nums[i]; - if (nums[j] == j) { - return j; - } - [nums[i], nums[j]] = [nums[j], nums[i]]; - } - } -}; -``` - -### **TypeScript** - ```ts function findRepeatNumber(nums: number[]): number { for (let i = 0; ; ++i) { @@ -242,8 +90,6 @@ function findRepeatNumber(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn find_repeat_number(mut nums: Vec) -> i32 { @@ -261,7 +107,23 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findRepeatNumber = function (nums) { + for (let i = 0; ; ++i) { + while (nums[i] != i) { + const j = nums[i]; + if (nums[j] == j) { + return j; + } + [nums[i], nums[j]] = [nums[j], nums[i]]; + } + } +}; +``` ```cs public class Solution { @@ -281,8 +143,6 @@ public class Solution { } ``` -### **Kotlin** - ```kotlin class Solution { fun findRepeatNumber(nums: IntArray): Int { @@ -305,10 +165,136 @@ class Solution { } ``` -### **...** + + +### 方法二:哈希表 + +我们可以使用哈希表来解决这个问题,遍历数组 `nums`,对于遍历到的每个元素,判断哈希表中是否存在该元素,如果哈希表中存在该元素,即找到了一个重复的数字,返回该数字即可;如果哈希表中不存在该元素,将该元素加入哈希表中。继续遍历,直到找到一个重复的数字。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `nums` 的长度。 + + + +```python +class Solution: + def findRepeatNumber(self, nums: List[int]) -> int: + vis = set() + for v in nums: + if v in vis: + return v + vis.add(v) +``` +```java +class Solution { + public int findRepeatNumber(int[] nums) { + Set vis = new HashSet<>(); + for (int i = 0;; ++i) { + if (!vis.add(nums[i])) { + return nums[i]; + } + } + } +} ``` +```cpp +class Solution { +public: + int findRepeatNumber(vector& nums) { + unordered_set vis; + for (int i = 0;; ++i) { + if (vis.count(nums[i])) { + return nums[i]; + } + vis.insert(nums[i]); + } + } +}; +``` + +```go +func findRepeatNumber(nums []int) int { + vis := map[int]bool{} + for i := 0; ; i++ { + if vis[nums[i]] { + return nums[i] + } + vis[nums[i]] = true + } +} ``` + +### 方法三:原地交换 + +我们可以遍历数组 `nums`,对于遍历到的每个元素 `nums[i]`,判断 `nums[i]` 是否等于 `i`,如果是,则继续遍历下一个元素;如果不是,则将 `nums[i]` 与 `nums[nums[i]]` 进行交换,交换之后,`nums[i]` 的值和下标都发生了改变,如果 `nums[i]` 与 `nums[nums[i]]` 相等,即找到了一个重复的数字,返回该数字即可;如果 `nums[i]` 与 `nums[nums[i]]` 不相等,继续遍历,直到找到一个重复的数字。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是数组 `nums` 的长度。 + + + +```python +class Solution: + def findRepeatNumber(self, nums: List[int]) -> int: + for i, v in enumerate(nums): + while v != i: + if nums[v] == v: + return v + nums[i], nums[v] = nums[v], nums[i] + v = nums[i] +``` + +```java +class Solution { + public int findRepeatNumber(int[] nums) { + for (int i = 0;; ++i) { + while (nums[i] != i) { + int j = nums[i]; + if (nums[j] == j) { + return j; + } + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } + } + } +} +``` + +```cpp +class Solution { +public: + int findRepeatNumber(vector& nums) { + for (int i = 0;; ++i) { + while (nums[i] != i) { + int j = nums[i]; + if (nums[j] == j) { + return j; + } + swap(nums[i], nums[j]); + } + } + } +}; +``` + +```go +func findRepeatNumber(nums []int) int { + for i := 0; ; i++ { + for nums[i] != i { + j := nums[i] + if nums[j] == j { + return j + } + nums[i], nums[j] = nums[j], nums[i] + } + } +} +``` + + + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/README.md" index 7266ea868d6c4..0543b5894365a 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23004. \344\272\214\347\273\264\346\225\260\347\273\204\344\270\255\347\232\204\346\237\245\346\211\276/README.md" @@ -38,7 +38,7 @@ ## 解法 -**方法一:二分查找** +### 方法一:二分查找 由于每一行的所有元素升序排列,因此,对于每一行,我们可以使用二分查找找到第一个大于等于 `target` 的元素,然后判断该元素是否等于 `target`。如果等于 `target`,说明找到了目标值,直接返回 `true`。如果不等于 `target`,说明这一行的所有元素都小于 `target`,应该继续搜索下一行。 @@ -46,22 +46,8 @@ 时间复杂度 $O(m \times \log n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。 -**方法二:从左下角或右上角搜索** - -这里我们以左下角作为起始搜索点,往右上方向开始搜索,比较当前元素 `matrix[i][j]`与 `target` 的大小关系: - -- 若 `matrix[i][j] == target`,说明找到了目标值,直接返回 `true`。 -- 若 `matrix[i][j] > target`,说明这一行从当前位置开始往右的所有元素均大于 `target`,应该让 $i$ 指针往上移动,即 $i \leftarrow i - 1$。 -- 若 `matrix[i][j] < target`,说明这一列从当前位置开始往上的所有元素均小于 `target`,应该让 $j$ 指针往右移动,即 $j \leftarrow j + 1$。 - -若搜索结束依然找不到 `target`,返回 `false`。 - -时间复杂度 $O(m + n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。 - -### **Python3** - ```python class Solution: def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool: @@ -72,25 +58,6 @@ class Solution: return False ``` -```python -class Solution: - def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool: - if not matrix or not matrix[0]: - return False - m, n = len(matrix), len(matrix[0]) - i, j = m - 1, 0 - while i >= 0 and j < n: - if matrix[i][j] == target: - return True - if matrix[i][j] > target: - i -= 1 - else: - j += 1 - return False -``` - -### **Java** - ```java class Solution { public boolean findNumberIn2DArray(int[][] matrix, int target) { @@ -105,30 +72,6 @@ class Solution { } ``` -```java -class Solution { - public boolean findNumberIn2DArray(int[][] matrix, int target) { - if (matrix.length == 0 || matrix[0].length == 0) { - return false; - } - int m = matrix.length, n = matrix[0].length; - for (int i = m - 1, j = 0; i >= 0 && j < n;) { - if (matrix[i][j] == target) { - return true; - } - if (matrix[i][j] > target) { - --i; - } else { - ++j; - } - } - return false; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -144,31 +87,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool findNumberIn2DArray(vector>& matrix, int target) { - if (matrix.empty()) { - return false; - } - int m = matrix.size(), n = matrix[0].size(); - int i = 0, j = n - 1; - while (i < m && j >= 0) { - if (matrix[i][j] == target) { - return true; - } else if (matrix[i][j] < target) { - ++i; - } else { - --j; - } - } - return false; - } -}; -``` - -### **Go** - ```go func findNumberIn2DArray(matrix [][]int, target int) bool { for _, row := range matrix { @@ -181,56 +99,6 @@ func findNumberIn2DArray(matrix [][]int, target int) bool { } ``` -```go -func findNumberIn2DArray(matrix [][]int, target int) bool { - if len(matrix) == 0 { - return false - } - m, n := len(matrix), len(matrix[0]) - for i, j := 0, n-1; i < m && j >= 0; { - if matrix[i][j] == target { - return true - } - if matrix[i][j] < target { - i++ - } else { - j-- - } - } - return false -} -``` - -### **JavaScript** - -```js -/** - * @param {number[][]} matrix - * @param {number} target - * @return {boolean} - */ -var findNumberIn2DArray = function (matrix, target) { - if (matrix.length == 0 || matrix[0].length == 0) { - return false; - } - const m = matrix.length; - const n = matrix[0].length; - for (let i = 0, j = n - 1; i < m && j >= 0; ) { - if (matrix[i][j] == target) { - return true; - } - if (matrix[i][j] < target) { - ++i; - } else { - --j; - } - } - return false; -}; -``` - -### **TypeScript** - ```ts function findNumberIn2DArray(matrix: number[][], target: number): boolean { if (matrix.length == 0 || matrix[0].length == 0) { @@ -252,8 +120,6 @@ function findNumberIn2DArray(matrix: number[][], target: number): boolean { } ``` -### **Rust** - ```rust use std::cmp::Ordering; impl Solution { @@ -281,7 +147,31 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var findNumberIn2DArray = function (matrix, target) { + if (matrix.length == 0 || matrix[0].length == 0) { + return false; + } + const m = matrix.length; + const n = matrix[0].length; + for (let i = 0, j = n - 1; i < m && j >= 0; ) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] < target) { + ++i; + } else { + --j; + } + } + return false; +}; +``` ```cs public class Solution { @@ -304,10 +194,104 @@ public class Solution { } ``` -### **...** + + +### 方法二:从左下角或右上角搜索 + +这里我们以左下角作为起始搜索点,往右上方向开始搜索,比较当前元素 `matrix[i][j]`与 `target` 的大小关系: + +- 若 `matrix[i][j] == target`,说明找到了目标值,直接返回 `true`。 +- 若 `matrix[i][j] > target`,说明这一行从当前位置开始往右的所有元素均大于 `target`,应该让 $i$ 指针往上移动,即 $i \leftarrow i - 1$。 +- 若 `matrix[i][j] < target`,说明这一列从当前位置开始往上的所有元素均小于 `target`,应该让 $j$ 指针往右移动,即 $j \leftarrow j + 1$。 + +若搜索结束依然找不到 `target`,返回 `false`。 + +时间复杂度 $O(m + n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。 + + + +```python +class Solution: + def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool: + if not matrix or not matrix[0]: + return False + m, n = len(matrix), len(matrix[0]) + i, j = m - 1, 0 + while i >= 0 and j < n: + if matrix[i][j] == target: + return True + if matrix[i][j] > target: + i -= 1 + else: + j += 1 + return False +``` + +```java +class Solution { + public boolean findNumberIn2DArray(int[][] matrix, int target) { + if (matrix.length == 0 || matrix[0].length == 0) { + return false; + } + int m = matrix.length, n = matrix[0].length; + for (int i = m - 1, j = 0; i >= 0 && j < n;) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +} +``` +```cpp +class Solution { +public: + bool findNumberIn2DArray(vector>& matrix, int target) { + if (matrix.empty()) { + return false; + } + int m = matrix.size(), n = matrix[0].size(); + int i = 0, j = n - 1; + while (i < m && j >= 0) { + if (matrix[i][j] == target) { + return true; + } else if (matrix[i][j] < target) { + ++i; + } else { + --j; + } + } + return false; + } +}; ``` +```go +func findNumberIn2DArray(matrix [][]int, target int) bool { + if len(matrix) == 0 { + return false + } + m, n := len(matrix), len(matrix[0]) + for i, j := 0, n-1; i < m && j >= 0; { + if matrix[i][j] == target { + return true + } + if matrix[i][j] < target { + i++ + } else { + j-- + } + } + return false +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/README.md" index 838c146a632fb..24cef275f9440 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23005. \346\233\277\346\215\242\347\251\272\346\240\274/README.md" @@ -19,39 +19,20 @@ ## 解法 -**方法一:字符串内置方法** +### 方法一:字符串内置方法 使用 `replace()` 方法。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串长度。 -**方法二:遍历替换** - -我们直接遍历字符串,遇到空格就替换成 `%20` 即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串长度。 - -### **Python3** - ```python class Solution: def replaceSpace(self, s: str) -> str: return s.replace(' ', '%20') ``` -```python -class Solution: - def replaceSpace(self, s: str) -> str: - ans = [] - for c in s: - ans.append('%20' if c == ' ' else c) - return ''.join(ans) -``` - -### **Java** - ```java class Solution { public String replaceSpace(String s) { @@ -60,20 +41,6 @@ class Solution { } ``` -```java -class Solution { - public String replaceSpace(String s) { - StringBuilder ans = new StringBuilder(); - for (char c : s.toCharArray()) { - ans.append(c == ' ' ? "%20" : c); - } - return ans.toString(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -90,29 +57,25 @@ public: }; ``` -### **Go** - ```go func replaceSpace(s string) string { return strings.Replace(s, " ", "%20", -1) } ``` -```go -func replaceSpace(s string) string { - ans := strings.Builder{} - for _, c := range s { - if c == ' ' { - ans.WriteString("%20") - } else { - ans.WriteRune(c) - } - } - return ans.String() +```ts +function replaceSpace(s: string): string { + return s.replace(/\s/g, '%20'); } ``` -### **JavaScript** +```rust +impl Solution { + pub fn replace_space(s: String) -> String { + s.replace(' ', "%20") + } +} +``` ```js /** @@ -124,35 +87,76 @@ var replaceSpace = function (s) { }; ``` -```js -/** - * @param {string} s - * @return {string} - */ -var replaceSpace = function (s) { - return s.replace(/\s/g, '%20'); -}; +```cs +public class Solution { + public string ReplaceSpace(string s) { + return s.Replace(" ", "%20"); + } +} ``` -```js -/** - * @param {string} s - * @return {string} - */ -var replaceSpace = function (s) { - const ans = []; - for (const c of s) { - ans.push(c === ' ' ? '%20' : c); +```php +class Solution { + /** + * @param String $s + * @return String + */ + function replaceSpace($s) { + $rs = ''; + for ($i = 0; $i < strlen($s); $i++) { + if ($s[$i] === ' ') { + $rs = $rs . '%20'; + } else { + $rs = $rs . $s[$i]; + } + } + return $rs; } - return ans.join(''); -}; +} ``` -### **TypeScript** + -```ts -function replaceSpace(s: string): string { - return s.replace(/\s/g, '%20'); +### 方法二:遍历替换 + +我们直接遍历字符串,遇到空格就替换成 `%20` 即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串长度。 + + + +```python +class Solution: + def replaceSpace(self, s: str) -> str: + ans = [] + for c in s: + ans.append('%20' if c == ' ' else c) + return ''.join(ans) +``` + +```java +class Solution { + public String replaceSpace(String s) { + StringBuilder ans = new StringBuilder(); + for (char c : s.toCharArray()) { + ans.append(c == ' ' ? "%20" : c); + } + return ans.toString(); + } +} +``` + +```go +func replaceSpace(s string) string { + ans := strings.Builder{} + for _, c := range s { + if c == ' ' { + ans.WriteString("%20") + } else { + ans.WriteRune(c) + } + } + return ans.String() } ``` @@ -166,16 +170,6 @@ function replaceSpace(s: string): string { } ``` -### **Rust** - -```rust -impl Solution { - pub fn replace_space(s: String) -> String { - s.replace(' ', "%20") - } -} -``` - ```rust impl Solution { pub fn replace_space(s: String) -> String { @@ -192,14 +186,14 @@ impl Solution { } ``` -### **C#** - -```cs -public class Solution { - public string ReplaceSpace(string s) { - return s.Replace(" ", "%20"); - } -} +```js +/** + * @param {string} s + * @return {string} + */ +var replaceSpace = function (s) { + return s.replace(/\s/g, '%20'); +}; ``` ```cs @@ -218,32 +212,26 @@ public class Solution { } ``` -### **PHP** - -```php -class Solution { - /** - * @param String $s - * @return String - */ - function replaceSpace($s) { - $rs = ''; - for ($i = 0; $i < strlen($s); $i++) { - if ($s[$i] === ' ') { - $rs = $rs . '%20'; - } else { - $rs = $rs . $s[$i]; - } - } - return $rs; - } -} -``` + -### **...** +### 方法三 -``` + +```js +/** + * @param {string} s + * @return {string} + */ +var replaceSpace = function (s) { + const ans = []; + for (const c of s) { + ans.push(c === ' ' ? '%20' : c); + } + return ans.join(''); +}; ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/README.md" index 2536b3c1a80f7..29dad7ccc030f 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23006. \344\273\216\345\260\276\345\210\260\345\244\264\346\211\223\345\215\260\351\223\276\350\241\250/README.md" @@ -19,22 +19,14 @@ ## 解法 -**方法一:顺序遍历 + 反转** +### 方法一:顺序遍历 + 反转 我们可以顺序遍历链表,将每个节点的值存入数组中,然后将数组反转。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为链表的长度。 -**方法二:递归** - -我们可以使用递归的方式,先递归得到 `head` 之后的节点反过来的值列表,然后将 `head` 的值加到列表的末尾。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为链表的长度。 - -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -52,25 +44,6 @@ class Solution: return ans[::-1] ``` -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None - - -class Solution: - def reversePrint(self, head: ListNode) -> List[int]: - if head is None: - return [] - ans = self.reversePrint(head.next) - ans.append(head.val) - return ans -``` - -### **Java** - ```java /** * Definition for singly-linked list. @@ -95,34 +68,6 @@ class Solution { } ``` -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { val = x; } - * } - */ -class Solution { - public int[] reversePrint(ListNode head) { - int n = 0; - ListNode cur = head; - for (; cur != null; cur = cur.next) { - ++n; - } - int[] ans = new int[n]; - cur = head; - for (; cur != null; cur = cur.next) { - ans[--n] = cur.val; - } - return ans; - } -} -``` - -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -143,30 +88,6 @@ public: }; ``` -```cpp -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - vector reversePrint(ListNode* head) { - vector ans; - for (; head; head = head->next) { - ans.push_back(head->val); - } - reverse(ans.begin(), ans.end()); - return ans; - } -}; -``` - -### **Go** - ```go /** * Definition for singly-linked list. @@ -186,71 +107,6 @@ func reversePrint(head *ListNode) (ans []int) { } ``` -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -func reversePrint(head *ListNode) (ans []int) { - if head == nil { - return - } - ans = reversePrint(head.Next) - ans = append(ans, head.Val) - return -} -``` - -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val) { - * this.val = val; - * this.next = null; - * } - */ -/** - * @param {ListNode} head - * @return {number[]} - */ -var reversePrint = function (head) { - let ans = []; - for (; !!head; head = head.next) { - ans.unshift(head.val); - } - return ans; -}; -``` - -```js -/** - * Definition for singly-linked list. - * function ListNode(val) { - * this.val = val; - * this.next = null; - * } - */ -/** - * @param {ListNode} head - * @return {number[]} - */ -var reversePrint = function (head) { - if (!head) { - return []; - } - const ans = reversePrint(head.next); - ans.push(head.val); - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -273,8 +129,6 @@ function reversePrint(head: ListNode | null): number[] { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -306,6 +160,142 @@ impl Solution { } ``` +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {number[]} + */ +var reversePrint = function (head) { + let ans = []; + for (; !!head; head = head.next) { + ans.unshift(head.val); + } + return ans; +}; +``` + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int x) { val = x; } + * } + */ + public class Solution { + public int[] ReversePrint(ListNode head) { + List ans = new List(); + while (head != null) { + ans.Add(head.val); + head = head.next; + } + ans.Reverse(); + return ans.ToArray(); + } + } +``` + + + +### 方法二:递归 + +我们可以使用递归的方式,先递归得到 `head` 之后的节点反过来的值列表,然后将 `head` 的值加到列表的末尾。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为链表的长度。 + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + + +class Solution: + def reversePrint(self, head: ListNode) -> List[int]: + if head is None: + return [] + ans = self.reversePrint(head.next) + ans.append(head.val) + return ans +``` + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public int[] reversePrint(ListNode head) { + int n = 0; + ListNode cur = head; + for (; cur != null; cur = cur.next) { + ++n; + } + int[] ans = new int[n]; + cur = head; + for (; cur != null; cur = cur.next) { + ans[--n] = cur.val; + } + return ans; + } +} +``` + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + vector reversePrint(ListNode* head) { + vector ans; + for (; head; head = head->next) { + ans.push_back(head->val); + } + reverse(ans.begin(), ans.end()); + return ans; + } +}; +``` + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reversePrint(head *ListNode) (ans []int) { + if head == nil { + return + } + ans = reversePrint(head.Next) + ans = append(ans, head.Val) + return +} +``` + ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -344,34 +334,28 @@ impl Solution { } ``` -### **C#** - -```cs +```js /** * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int x) { val = x; } + * function ListNode(val) { + * this.val = val; + * this.next = null; * } */ - public class Solution { - public int[] ReversePrint(ListNode head) { - List ans = new List(); - while (head != null) { - ans.Add(head.val); - head = head.next; - } - ans.Reverse(); - return ans.ToArray(); - } - } -``` - -### **...** - -``` - +/** + * @param {ListNode} head + * @return {number[]} + */ +var reversePrint = function (head) { + if (!head) { + return []; + } + const ans = reversePrint(head.next); + ans.push(head.val); + return ans; +}; ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/README.md" index 27c0d6fa934ea..4def3159aa862 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23007. \351\207\215\345\273\272\344\272\214\345\217\211\346\240\221/README.md" @@ -34,7 +34,7 @@ ## 解法 -**方法一:哈希表 + 递归** +### 方法一:哈希表 + 递归 由于我们每一次都需要在中序序列中找到根节点的位置,因此我们可以使用哈希表 $d$ 来存储中序序列的值和索引,这样可以将查找的时间复杂度降低到 $O(1)$。 @@ -50,8 +50,6 @@ -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -77,8 +75,6 @@ class Solution: return dfs(0, 0, len(preorder)) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -118,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -154,8 +148,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -186,44 +178,6 @@ func buildTree(preorder []int, inorder []int) *TreeNode { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {number[]} preorder - * @param {number[]} inorder - * @return {TreeNode} - */ -var buildTree = function (preorder, inorder) { - const d = new Map(); - const n = inorder.length; - for (let i = 0; i < n; ++i) { - d.set(inorder[i], i); - } - const dfs = (i, j, n) => { - if (n < 1) { - return null; - } - const k = d.get(preorder[i]); - const l = k - j; - const root = new TreeNode(preorder[i]); - root.left = dfs(i + 1, j, l); - root.right = dfs(i + 1 + l, k + 1, n - l - 1); - return root; - }; - return dfs(0, 0, n); -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -260,37 +214,6 @@ function buildTree(preorder: number[], inorder: number[]): TreeNode | null { } ``` -```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 buildTree(preorder: number[], inorder: number[]): TreeNode | null { - if (inorder.length === 0) { - return null; - } - const val = preorder[0]; - const i = inorder.indexOf(val); - return new TreeNode( - val, - buildTree(preorder.slice(1, i + 1), inorder.slice(0, i)), - buildTree(preorder.slice(i + 1), inorder.slice(i + 1)), - ); -} -``` - -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -339,7 +262,39 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {number[]} preorder + * @param {number[]} inorder + * @return {TreeNode} + */ +var buildTree = function (preorder, inorder) { + const d = new Map(); + const n = inorder.length; + for (let i = 0; i < n; ++i) { + d.set(inorder[i], i); + } + const dfs = (i, j, n) => { + if (n < 1) { + return null; + } + const k = d.get(preorder[i]); + const l = k - j; + const root = new TreeNode(preorder[i]); + root.left = dfs(i + 1, j, l); + root.right = dfs(i + 1 + l, k + 1, n - l - 1); + return root; + }; + return dfs(0, 0, n); +}; +``` ```cs /** @@ -365,10 +320,41 @@ public class Solution { } ``` -### **...** + -``` +### 方法二 + + +```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 buildTree(preorder: number[], inorder: number[]): TreeNode | null { + if (inorder.length === 0) { + return null; + } + const val = preorder[0]; + const i = inorder.indexOf(val); + return new TreeNode( + val, + buildTree(preorder.slice(1, i + 1), inorder.slice(0, i)), + buildTree(preorder.slice(i + 1), inorder.slice(i + 1)), + ); +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23009. \347\224\250\344\270\244\344\270\252\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23009. \347\224\250\344\270\244\344\270\252\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227/README.md" index 9c426a127deec..bed42833bac9e 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23009. \347\224\250\344\270\244\344\270\252\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23009. \347\224\250\344\270\244\344\270\252\346\240\210\345\256\236\347\216\260\351\230\237\345\210\227/README.md" @@ -31,7 +31,7 @@ ## 解法 -**方法一:双栈** +### 方法一:双栈 我们可以使用两个栈来实现队列,其中一个栈 `stk1` 用来存储输入的元素,另一个栈 `stk2` 用来输出元素。 @@ -43,8 +43,6 @@ -### **Python3** - ```python class CQueue: def __init__(self): @@ -67,8 +65,6 @@ class CQueue: # param_2 = obj.deleteHead() ``` -### **Java** - ```java class CQueue { private Deque stk1 = new ArrayDeque<>(); @@ -99,8 +95,6 @@ class CQueue { */ ``` -### **C++** - ```cpp class CQueue { public: @@ -138,8 +132,6 @@ private: */ ``` -### **Go** - ```go type CQueue struct { stk1, stk2 []int @@ -176,44 +168,6 @@ func (this *CQueue) DeleteHead() int { */ ``` -### **JavaScript** - -```js -var CQueue = function () { - this.stk1 = []; - this.stk2 = []; -}; - -/** - * @param {number} value - * @return {void} - */ -CQueue.prototype.appendTail = function (value) { - this.stk1.push(value); -}; - -/** - * @return {number} - */ -CQueue.prototype.deleteHead = function () { - if (!this.stk2.length) { - while (this.stk1.length) { - this.stk2.push(this.stk1.pop()); - } - } - return this.stk2.length ? this.stk2.pop() : -1; -}; - -/** - * Your CQueue object will be instantiated and called as such: - * var obj = new CQueue() - * obj.appendTail(value) - * var param_2 = obj.deleteHead() - */ -``` - -### **TypeScript** - ```ts class CQueue { private stk1: number[]; @@ -246,8 +200,6 @@ class CQueue { */ ``` -### **Rust** - ```rust struct CQueue { s1: Vec, @@ -289,7 +241,39 @@ impl CQueue { */ ``` -### **C#** +```js +var CQueue = function () { + this.stk1 = []; + this.stk2 = []; +}; + +/** + * @param {number} value + * @return {void} + */ +CQueue.prototype.appendTail = function (value) { + this.stk1.push(value); +}; + +/** + * @return {number} + */ +CQueue.prototype.deleteHead = function () { + if (!this.stk2.length) { + while (this.stk1.length) { + this.stk2.push(this.stk1.pop()); + } + } + return this.stk2.length ? this.stk2.pop() : -1; +}; + +/** + * Your CQueue object will be instantiated and called as such: + * var obj = new CQueue() + * obj.appendTail(value) + * var param_2 = obj.deleteHead() + */ +``` ```cs public class CQueue { @@ -322,10 +306,6 @@ public class CQueue { */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23010- I. \346\226\220\346\263\242\351\202\243\345\245\221\346\225\260\345\210\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23010- I. \346\226\220\346\263\242\351\202\243\345\245\221\346\225\260\345\210\227/README.md" index 4ed93ee13aa17..acda0cdedb3c0 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23010- I. \346\226\220\346\263\242\351\202\243\345\245\221\346\225\260\345\210\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23010- I. \346\226\220\346\263\242\351\202\243\345\245\221\346\225\260\345\210\227/README.md" @@ -38,7 +38,7 @@ F(N) = F(N - 1) + F(N - 2), 其中 N > 1. ## 解法 -**方法一:递推** +### 方法一:递推 我们定义初始项 $a=0$, $b=1$,接下来执行 $n$ 次循环,每次循环中,计算 $c=a+b$,并更新 $a=b$, $b=c$,循环 $n$ 次后,答案即为 $a$。 @@ -46,8 +46,6 @@ F(N) = F(N - 1) + F(N - 2), 其中 N > 1. -### **Python3** - ```python class Solution: def fib(self, n: int) -> int: @@ -57,8 +55,6 @@ class Solution: return a ``` -### **Java** - ```java class Solution { public int fib(int n) { @@ -73,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,8 +84,6 @@ public: }; ``` -### **Go** - ```go func fib(n int) int { a, b := 0, 1 @@ -102,25 +94,6 @@ func fib(n int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number} - */ -var fib = function (n) { - let a = 0; - let b = 1; - while (n--) { - [a, b] = [b, (a + b) % (1e9 + 7)]; - } - return a; -}; -``` - -### **TypeScript** - ```ts function fib(n: number): number { let a: number = 0, @@ -133,8 +106,6 @@ function fib(n: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn fib(n: i32) -> i32 { @@ -147,7 +118,20 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number} n + * @return {number} + */ +var fib = function (n) { + let a = 0; + let b = 1; + while (n--) { + [a, b] = [b, (a + b) % (1e9 + 7)]; + } + return a; +}; +``` ```cs public class Solution { @@ -163,10 +147,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23010- II. \351\235\222\350\233\231\350\267\263\345\217\260\351\230\266\351\227\256\351\242\230/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23010- II. \351\235\222\350\233\231\350\267\263\345\217\260\351\230\266\351\227\256\351\242\230/README.md" index 5bd88e6ad9f76..ac022fd03de97 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23010- II. \351\235\222\350\233\231\350\267\263\345\217\260\351\230\266\351\227\256\351\242\230/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23010- II. \351\235\222\350\233\231\350\267\263\345\217\260\351\230\266\351\227\256\351\242\230/README.md" @@ -35,7 +35,7 @@ ## 解法 -**方法一:递推** +### 方法一:递推 青蛙想上第 $n$ 级台阶,可从第 $n-1$ 级台阶跳一级上去,也可从第 $n-2$ 级台阶跳两级上去,即 $f(n) = f(n-1) + f(n-2)$。这实际上可以转换为斐波那契数列的问题。 @@ -45,8 +45,6 @@ -### **Python3** - ```python class Solution: def numWays(self, n: int) -> int: @@ -56,8 +54,6 @@ class Solution: return a ``` -### **Java** - ```java class Solution { public int numWays(int n) { @@ -72,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,8 +83,6 @@ public: }; ``` -### **Go** - ```go func numWays(n int) int { a, b := 1, 1 @@ -101,24 +93,6 @@ func numWays(n int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number} - */ -var numWays = function (n) { - let a = (b = 1); - while (n--) { - [a, b] = [b, (a + b) % (1e9 + 7)]; - } - return a; -}; -``` - -### **TypeScript** - ```ts function numWays(n: number): number { let a = 0; @@ -130,8 +104,6 @@ function numWays(n: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn num_ways(n: i32) -> i32 { @@ -144,7 +116,19 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number} n + * @return {number} + */ +var numWays = function (n) { + let a = (b = 1); + while (n--) { + [a, b] = [b, (a + b) % (1e9 + 7)]; + } + return a; +}; +``` ```cs public class Solution { @@ -160,10 +144,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/README.md" index 1f6d15d41257f..5e3a875d877a9 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23011. \346\227\213\350\275\254\346\225\260\347\273\204\347\232\204\346\234\200\345\260\217\346\225\260\345\255\227/README.md" @@ -24,7 +24,7 @@ ## 解法 -**方法一:二分查找** +### 方法一:二分查找 二分查找的变种,需要考虑重复元素的情况。 @@ -42,8 +42,6 @@ -### **Python3** - ```python class Solution: def minArray(self, numbers: List[int]) -> int: @@ -59,25 +57,6 @@ class Solution: return numbers[l] ``` -```python -class Solution: - def minArray(self, numbers: List[int]) -> int: - l, r = 0, len(numbers) - 1 - while l < r: - if numbers[l] < numbers[r]: - return numbers[l] - mid = (l + r) >> 1 - if numbers[mid] > numbers[l]: - l = mid + 1 - elif numbers[mid] < numbers[l]: - r = mid - else: - l += 1 - return numbers[l] -``` - -### **Java** - ```java class Solution { public int minArray(int[] numbers) { @@ -97,30 +76,6 @@ class Solution { } ``` -```java -class Solution { - public int minArray(int[] numbers) { - int l = 0, r = numbers.length - 1; - while (l < r) { - if (numbers[l] < numbers[r]) { - break; - } - int m = (l + r) >>> 1; - if (numbers[m] > numbers[l]) { - l = m + 1; - } else if (numbers[m] < numbers[l]) { - r = m; - } else { - ++l; - } - } - return numbers[l]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -141,31 +96,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minArray(vector& numbers) { - int l = 0, r = numbers.size() - 1; - while (l < r) { - if (numbers[l] < numbers[r]) { - break; - } - int mid = (l + r) >> 1; - if (numbers[mid] > numbers[l]) { - l = mid + 1; - } else if (numbers[mid] < numbers[l]) { - r = mid; - } else { - ++l; - } - } - return numbers[l]; - } -}; -``` - -### **Go** - ```go func minArray(numbers []int) int { l, r := 0, len(numbers)-1 @@ -183,28 +113,30 @@ func minArray(numbers []int) int { } ``` -```go -func minArray(numbers []int) int { - l, r := 0, len(numbers)-1 - for l < r { - if numbers[l] < numbers[r] { - break - } - mid := (l + r) >> 1 - if numbers[mid] > numbers[l] { - l = mid + 1 - } else if numbers[mid] < numbers[l] { - r = mid - } else { - l++ - } - } - return numbers[l] +```rust +impl Solution { + pub fn min_array(numbers: Vec) -> i32 { + let mut l = 0; + let mut r = numbers.len() - 1; + while l < r { + let mid = (l + r) >> 1; + match numbers[mid].cmp(&numbers[r]) { + std::cmp::Ordering::Less => { + r = mid; + } + std::cmp::Ordering::Equal => { + r -= 1; + } + std::cmp::Ordering::Greater => { + l = mid + 1; + } + } + } + numbers[l] + } } ``` -### **JavaScript** - ```js /** * @param {number[]} numbers @@ -227,57 +159,113 @@ var minArray = function (numbers) { }; ``` -```js -/** - * @param {number[]} numbers - * @return {number} - */ -var minArray = function (numbers) { - let l = 0, - r = numbers.length - 1; - while (l < r) { - if (numbers[l] < numbers[r]) { - break; - } - let m = (l + r) >>> 1; - if (numbers[m] > numbers[l]) { - l = m + 1; - } else if (numbers[m] < numbers[l]) { - r = m; - } else { - ++l; +```cs +public class Solution { + public int MinArray(int[] numbers) { + int l = 0, r = numbers.Length - 1; + while (l < r) { + int m = (l + r) >> 1; + if (numbers[m] > numbers[r]) { + l = m + 1; + } else if (numbers[m] < numbers[r]) { + r = m; + } else { + --r; + } } + return numbers[l]; } - return numbers[l]; -}; +} ``` -### **Rust** + -```rust -impl Solution { - pub fn min_array(numbers: Vec) -> i32 { - let mut l = 0; - let mut r = numbers.len() - 1; - while l < r { - let mid = (l + r) >> 1; - match numbers[mid].cmp(&numbers[r]) { - std::cmp::Ordering::Less => { - r = mid; - } - std::cmp::Ordering::Equal => { - r -= 1; - } - std::cmp::Ordering::Greater => { - l = mid + 1; - } +### 方法二 + + + +```python +class Solution: + def minArray(self, numbers: List[int]) -> int: + l, r = 0, len(numbers) - 1 + while l < r: + if numbers[l] < numbers[r]: + return numbers[l] + mid = (l + r) >> 1 + if numbers[mid] > numbers[l]: + l = mid + 1 + elif numbers[mid] < numbers[l]: + r = mid + else: + l += 1 + return numbers[l] +``` + +```java +class Solution { + public int minArray(int[] numbers) { + int l = 0, r = numbers.length - 1; + while (l < r) { + if (numbers[l] < numbers[r]) { + break; + } + int m = (l + r) >>> 1; + if (numbers[m] > numbers[l]) { + l = m + 1; + } else if (numbers[m] < numbers[l]) { + r = m; + } else { + ++l; } } - numbers[l] + return numbers[l]; } } ``` +```cpp +class Solution { +public: + int minArray(vector& numbers) { + int l = 0, r = numbers.size() - 1; + while (l < r) { + if (numbers[l] < numbers[r]) { + break; + } + int mid = (l + r) >> 1; + if (numbers[mid] > numbers[l]) { + l = mid + 1; + } else if (numbers[mid] < numbers[l]) { + r = mid; + } else { + ++l; + } + } + return numbers[l]; + } +}; +``` + +```go +func minArray(numbers []int) int { + l, r := 0, len(numbers)-1 + for l < r { + if numbers[l] < numbers[r] { + break + } + mid := (l + r) >> 1 + if numbers[mid] > numbers[l] { + l = mid + 1 + } else if numbers[mid] < numbers[l] { + r = mid + } else { + l++ + } + } + return numbers[l] +} +``` + ```rust impl Solution { pub fn min_array(numbers: Vec) -> i32 { @@ -305,25 +293,29 @@ impl Solution { } ``` -### **C#** - -```cs -public class Solution { - public int MinArray(int[] numbers) { - int l = 0, r = numbers.Length - 1; - while (l < r) { - int m = (l + r) >> 1; - if (numbers[m] > numbers[r]) { - l = m + 1; - } else if (numbers[m] < numbers[r]) { - r = m; - } else { - --r; - } +```js +/** + * @param {number[]} numbers + * @return {number} + */ +var minArray = function (numbers) { + let l = 0, + r = numbers.length - 1; + while (l < r) { + if (numbers[l] < numbers[r]) { + break; + } + let m = (l + r) >>> 1; + if (numbers[m] > numbers[l]) { + l = m + 1; + } else if (numbers[m] < numbers[l]) { + r = m; + } else { + ++l; } - return numbers[l]; } -} + return numbers[l]; +}; ``` ```cs @@ -348,10 +340,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23012. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\257\345\276\204/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23012. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\257\345\276\204/README.md" index da567fd6f9555..8d400fd348d4f 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23012. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\257\345\276\204/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23012. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\257\345\276\204/README.md" @@ -44,7 +44,7 @@ ## 解法 -**方法一:枚举 + DFS** +### 方法一:枚举 + DFS 我们可以枚举矩阵的每个位置 $(i, j)$,以该位置为起点,采用深度优先搜索的方法寻找字符串 `word` 的路径。如果找到了一条路径,即可返回 `true`,否则在枚举完所有的位置后,返回 `false`。 @@ -60,8 +60,6 @@ -### **Python3** - ```python class Solution: def exist(self, board: List[List[str]], word: str) -> bool: @@ -80,8 +78,6 @@ class Solution: return any(dfs(i, j, 0) for i in range(m) for j in range(n)) ``` -### **Java** - ```java class Solution { private char[][] board; @@ -123,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +152,6 @@ public: }; ``` -### **Go** - ```go func exist(board [][]byte, word string) bool { m, n := len(board), len(board[0]) @@ -191,46 +183,6 @@ func exist(board [][]byte, word string) bool { } ``` -### **JavaScript** - -```js -/** - * @param {character[][]} board - * @param {string} word - * @return {boolean} - */ -var exist = function (board, word) { - const m = board.length; - const n = board[0].length; - const dirs = [-1, 0, 1, 0, -1]; - const dfs = (i, j, k) => { - if (k == word.length) { - return true; - } - if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[k]) { - return false; - } - board[i][j] = ' '; - let ans = false; - for (let l = 0; l < 4; ++l) { - ans = ans || dfs(i + dirs[l], j + dirs[l + 1], k + 1); - } - board[i][j] = word[k]; - return ans; - }; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (dfs(i, j, 0)) { - return true; - } - } - } - return false; -}; -``` - -### **TypeScript** - ```ts function exist(board: string[][], word: string): boolean { const m = board.length; @@ -261,8 +213,6 @@ function exist(board: string[][], word: string): boolean { } ``` -### **Rust** - ```rust impl Solution { fn dfs( @@ -309,7 +259,41 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {character[][]} board + * @param {string} word + * @return {boolean} + */ +var exist = function (board, word) { + const m = board.length; + const n = board[0].length; + const dirs = [-1, 0, 1, 0, -1]; + const dfs = (i, j, k) => { + if (k == word.length) { + return true; + } + if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[k]) { + return false; + } + board[i][j] = ' '; + let ans = false; + for (let l = 0; l < 4; ++l) { + ans = ans || dfs(i + dirs[l], j + dirs[l + 1], k + 1); + } + board[i][j] = word[k]; + return ans; + }; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (dfs(i, j, 0)) { + return true; + } + } + } + return false; +}; +``` ```cs public class Solution { @@ -352,10 +336,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/README.md" index 02008e6c0125a..da4a6a94b336d 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23013. \346\234\272\345\231\250\344\272\272\347\232\204\350\277\220\345\212\250\350\214\203\345\233\264/README.md" @@ -27,7 +27,7 @@ ## 解法 -**方法一:DFS + 哈希表** +### 方法一:DFS + 哈希表 由于部分单元格不可达,因此,我们不能直接枚举所有坐标点 $(i, j)$ 进行判断,而是应该从起点 $(0, 0)$ 出发,搜索所有可达的节点,记录答案。 @@ -37,8 +37,6 @@ -### **Python3** - ```python class Solution: def movingCount(self, m: int, n: int, k: int) -> int: @@ -65,28 +63,6 @@ class Solution: return ans ``` -```python -class Solution: - def movingCount(self, m: int, n: int, k: int) -> int: - def f(x): - s = 0 - while x: - s += x % 10 - x //= 10 - return s - - def dfs(i, j): - if not (0 <= i < m) or not (0 <= j < n) or f(i) + f(j) > k or (i, j) in vis: - return 0 - vis.add((i, j)) - return 1 + dfs(i + 1, j) + dfs(i, j + 1) - - vis = set() - return dfs(0, 0) -``` - -### **Java** - ```java class Solution { private boolean[][] vis; @@ -126,33 +102,6 @@ class Solution { } ``` -```java -class Solution { - private boolean[][] vis; - private int m; - private int n; - private int k; - - public int movingCount(int m, int n, int k) { - this.m = m; - this.n = n; - this.k = k; - vis = new boolean[m][n]; - return dfs(0, 0); - } - - private int dfs(int i, int j) { - if (i >= m || j >= n || vis[i][j] || (i % 10 + i / 10 + j % 10 + j / 10) > k) { - return 0; - } - vis[i][j] = true; - return 1 + dfs(i + 1, j) + dfs(i, j + 1); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -184,33 +133,6 @@ public: }; ``` -```cpp -class Solution { -public: - int movingCount(int m, int n, int k) { - bool vis[m][n]; - memset(vis, false, sizeof vis); - auto f = [](int x) { - int s = 0; - for (; x; x /= 10) { - s += x % 10; - } - return s; - }; - function dfs = [&](int i, int j) -> int { - if (i < 0 || i >= m || j < 0 || j >= n || vis[i][j] || f(i) + f(j) > k) { - return false; - } - vis[i][j] = true; - return 1 + dfs(i + 1, j) + dfs(i, j + 1); - }; - return dfs(0, 0); - } -}; -``` - -### **Go** - ```go func movingCount(m int, n int, k int) int { vis := make([][]bool, m) @@ -229,65 +151,6 @@ func movingCount(m int, n int, k int) int { } ``` -```go -func movingCount(m int, n int, k int) (ans int) { - f := func(x int) (s int) { - for ; x > 0; x /= 10 { - s += x % 10 - } - return - } - vis := make([][]bool, m) - for i := range vis { - vis[i] = make([]bool, n) - } - - dirs := [3]int{1, 0, 1} - var dfs func(i, j int) - dfs = func(i, j int) { - vis[i][j] = true - ans++ - for l := 0; l < 2; l++ { - x, y := i+dirs[l], j+dirs[l+1] - if x >= 0 && x < m && y >= 0 && y < n && f(x)+f(y) <= k && !vis[x][y] { - dfs(x, y) - } - } - } - dfs(0, 0) - return -} -``` - -### **JavaScript** - -```js -/** - * @param {number} m - * @param {number} n - * @param {number} k - * @return {number} - */ -var movingCount = function (m, n, k) { - const vis = new Array(m * n).fill(false); - let dfs = function (i, j) { - if ( - i >= m || - j >= n || - vis[i * n + j] || - (i % 10) + Math.floor(i / 10) + (j % 10) + Math.floor(j / 10) > k - ) { - return 0; - } - vis[i * n + j] = true; - return 1 + dfs(i + 1, j) + dfs(i, j + 1); - }; - return dfs(0, 0); -}; -``` - -### **TypeScript** - ```ts function movingCount(m: number, n: number, k: number): number { const set = new Set(); @@ -310,10 +173,6 @@ function movingCount(m: number, n: number, k: number): number { } ``` -### **Rust** - -循环: - ```rust use std::collections::{ HashSet, VecDeque }; impl Solution { @@ -344,32 +203,31 @@ impl Solution { } ``` -递归: - -```rust -impl Solution { - fn dfs(sign: &mut Vec>, k: usize, i: usize, j: usize) -> i32 { - if - i == sign.len() || - j == sign[0].len() || - sign[i][j] || - (j % 10) + ((j / 10) % 10) + (i % 10) + ((i / 10) % 10) > k - { +```js +/** + * @param {number} m + * @param {number} n + * @param {number} k + * @return {number} + */ +var movingCount = function (m, n, k) { + const vis = new Array(m * n).fill(false); + let dfs = function (i, j) { + if ( + i >= m || + j >= n || + vis[i * n + j] || + (i % 10) + Math.floor(i / 10) + (j % 10) + Math.floor(j / 10) > k + ) { return 0; } - sign[i][j] = true; - 1 + Self::dfs(sign, k, i + 1, j) + Self::dfs(sign, k, i, j + 1) - } - - pub fn moving_count(m: i32, n: i32, k: i32) -> i32 { - let mut sign = vec![vec![false; n as usize]; m as usize]; - Self::dfs(&mut sign, k as usize, 0, 0) - } -} + vis[i * n + j] = true; + return 1 + dfs(i + 1, j) + dfs(i, j + 1); + }; + return dfs(0, 0); +}; ``` -### **C#** - ```cs public class Solution { public int MovingCount(int m, int n, int k) { @@ -387,10 +245,134 @@ public class Solution { } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def movingCount(self, m: int, n: int, k: int) -> int: + def f(x): + s = 0 + while x: + s += x % 10 + x //= 10 + return s + + def dfs(i, j): + if not (0 <= i < m) or not (0 <= j < n) or f(i) + f(j) > k or (i, j) in vis: + return 0 + vis.add((i, j)) + return 1 + dfs(i + 1, j) + dfs(i, j + 1) + + vis = set() + return dfs(0, 0) +``` + +```java +class Solution { + private boolean[][] vis; + private int m; + private int n; + private int k; + + public int movingCount(int m, int n, int k) { + this.m = m; + this.n = n; + this.k = k; + vis = new boolean[m][n]; + return dfs(0, 0); + } + + private int dfs(int i, int j) { + if (i >= m || j >= n || vis[i][j] || (i % 10 + i / 10 + j % 10 + j / 10) > k) { + return 0; + } + vis[i][j] = true; + return 1 + dfs(i + 1, j) + dfs(i, j + 1); + } +} +``` + +```cpp +class Solution { +public: + int movingCount(int m, int n, int k) { + bool vis[m][n]; + memset(vis, false, sizeof vis); + auto f = [](int x) { + int s = 0; + for (; x; x /= 10) { + s += x % 10; + } + return s; + }; + function dfs = [&](int i, int j) -> int { + if (i < 0 || i >= m || j < 0 || j >= n || vis[i][j] || f(i) + f(j) > k) { + return false; + } + vis[i][j] = true; + return 1 + dfs(i + 1, j) + dfs(i, j + 1); + }; + return dfs(0, 0); + } +}; +``` + +```go +func movingCount(m int, n int, k int) (ans int) { + f := func(x int) (s int) { + for ; x > 0; x /= 10 { + s += x % 10 + } + return + } + vis := make([][]bool, m) + for i := range vis { + vis[i] = make([]bool, n) + } + dirs := [3]int{1, 0, 1} + var dfs func(i, j int) + dfs = func(i, j int) { + vis[i][j] = true + ans++ + for l := 0; l < 2; l++ { + x, y := i+dirs[l], j+dirs[l+1] + if x >= 0 && x < m && y >= 0 && y < n && f(x)+f(y) <= k && !vis[x][y] { + dfs(x, y) + } + } + } + dfs(0, 0) + return +} ``` +```rust +impl Solution { + fn dfs(sign: &mut Vec>, k: usize, i: usize, j: usize) -> i32 { + if + i == sign.len() || + j == sign[0].len() || + sign[i][j] || + (j % 10) + ((j / 10) % 10) + (i % 10) + ((i / 10) % 10) > k + { + return 0; + } + sign[i][j] = true; + 1 + Self::dfs(sign, k, i + 1, j) + Self::dfs(sign, k, i, j + 1) + } + + pub fn moving_count(m: i32, n: i32, k: i32) -> i32 { + let mut sign = vec![vec![false; n as usize]; m as usize]; + Self::dfs(&mut sign, k as usize, 0, 0) + } +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/README.md" index 6835a8a6c36d1..f8b40ad86b74e 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23014- I. \345\211\252\347\273\263\345\255\220/README.md" @@ -26,7 +26,7 @@ ## 解法 -**方法一:动态规划** +### 方法一:动态规划 我们定义 $dp[i]$ 表示正整数 $n$ 能获得的最大乘积,初始化 $dp[1] = 1$。答案即为 $dp[n]$。 @@ -38,16 +38,8 @@ $$ 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为正整数 $n$。 -**方法二:数学** - -当 $n \lt 4$,此时 $n$ 不能拆分成至少两个正整数的和,因此 $n - 1$ 是最大乘积。当 $n \ge 4$ 时,我们尽可能多地拆分 $3$,当剩下的最后一段为 $4$ 时,我们将其拆分为 $2 + 2$,这样乘积最大。 - -时间复杂度 $O(1)$,空间复杂度 $O(1)$。 - -### **Python3** - ```python class Solution: def cuttingRope(self, n: int) -> int: @@ -58,20 +50,6 @@ class Solution: return dp[n] ``` -```python -class Solution: - def cuttingRope(self, n: int) -> int: - if n < 4: - return n - 1 - if n % 3 == 0: - return pow(3, n // 3) - if n % 3 == 1: - return pow(3, n // 3 - 1) * 4 - return pow(3, n // 3) * 2 -``` - -### **Java** - ```java class Solution { public int cuttingRope(int n) { @@ -87,25 +65,6 @@ class Solution { } ``` -```java -class Solution { - public int cuttingRope(int n) { - if (n < 4) { - return n - 1; - } - if (n % 3 == 0) { - return (int) Math.pow(3, n / 3); - } - if (n % 3 == 1) { - return (int) Math.pow(3, n / 3 - 1) * 4; - } - return (int) Math.pow(3, n / 3) * 2; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -122,26 +81,6 @@ public: }; ``` -```cpp -class Solution { -public: - int cuttingRope(int n) { - if (n < 4) { - return n - 1; - } - if (n % 3 == 0) { - return pow(3, n / 3); - } - if (n % 3 == 1) { - return pow(3, n / 3 - 1) * 4; - } - return pow(3, n / 3) * 2; - } -}; -``` - -### **Go** - ```go func cuttingRope(n int) int { dp := make([]int, n+1) @@ -155,45 +94,6 @@ func cuttingRope(n int) int { } ``` -```go -func cuttingRope(n int) int { - if n < 4 { - return n - 1 - } - if n%3 == 0 { - return int(math.Pow(3, float64(n/3))) - } - if n%3 == 1 { - return int(math.Pow(3, float64(n/3-1))) * 4 - } - return int(math.Pow(3, float64(n/3))) * 2 -} -``` - -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number} - */ -var cuttingRope = function (n) { - if (n < 4) { - return n - 1; - } - const m = Math.floor(n / 3); - if (n % 3 == 0) { - return 3 ** m; - } - if (n % 3 == 1) { - return 3 ** (m - 1) * 4; - } - return 3 ** m * 2; -}; -``` - -### **TypeScript** - ```ts function cuttingRope(n: number): number { if (n < 4) { @@ -210,8 +110,6 @@ function cuttingRope(n: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn cutting_rope(n: i32) -> i32 { @@ -224,7 +122,25 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number} n + * @return {number} + */ +var cuttingRope = function (n) { + if (n < 4) { + return n - 1; + } + const m = Math.floor(n / 3); + if (n % 3 == 0) { + return 3 ** m; + } + if (n % 3 == 1) { + return 3 ** (m - 1) * 4; + } + return 3 ** m * 2; +}; +``` ```cs public class Solution { @@ -243,10 +159,78 @@ public class Solution { } ``` -### **...** + + +### 方法二:数学 + +当 $n \lt 4$,此时 $n$ 不能拆分成至少两个正整数的和,因此 $n - 1$ 是最大乘积。当 $n \ge 4$ 时,我们尽可能多地拆分 $3$,当剩下的最后一段为 $4$ 时,我们将其拆分为 $2 + 2$,这样乘积最大。 + +时间复杂度 $O(1)$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def cuttingRope(self, n: int) -> int: + if n < 4: + return n - 1 + if n % 3 == 0: + return pow(3, n // 3) + if n % 3 == 1: + return pow(3, n // 3 - 1) * 4 + return pow(3, n // 3) * 2 +``` + +```java +class Solution { + public int cuttingRope(int n) { + if (n < 4) { + return n - 1; + } + if (n % 3 == 0) { + return (int) Math.pow(3, n / 3); + } + if (n % 3 == 1) { + return (int) Math.pow(3, n / 3 - 1) * 4; + } + return (int) Math.pow(3, n / 3) * 2; + } +} +``` +```cpp +class Solution { +public: + int cuttingRope(int n) { + if (n < 4) { + return n - 1; + } + if (n % 3 == 0) { + return pow(3, n / 3); + } + if (n % 3 == 1) { + return pow(3, n / 3 - 1) * 4; + } + return pow(3, n / 3) * 2; + } +}; ``` +```go +func cuttingRope(n int) int { + if n < 4 { + return n - 1 + } + if n%3 == 0 { + return int(math.Pow(3, float64(n/3))) + } + if n%3 == 1 { + return int(math.Pow(3, float64(n/3-1))) * 4 + } + return int(math.Pow(3, float64(n/3))) * 2 +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/README.md" index ea8b727fae760..7a06a46066c1e 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23014- II. \345\211\252\347\273\263\345\255\220 II/README.md" @@ -32,7 +32,7 @@ ## 解法 -**方法一:数学(快速幂)** +### 方法一:数学(快速幂) 当 $n \lt 4$,此时 $n$ 不能拆分成至少两个正整数的和,因此 $n - 1$ 是最大乘积。当 $n \ge 4$ 时,我们尽可能多地拆分 $3$,当剩下的最后一段为 $4$ 时,我们将其拆分为 $2 + 2$,这样乘积最大。 @@ -40,8 +40,6 @@ -### **Python3** - ```python class Solution: def cuttingRope(self, n: int) -> int: @@ -55,8 +53,6 @@ class Solution: return pow(3, n // 3, mod) * 2 % mod ``` -### **Java** - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -87,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func cuttingRope(n int) int { if n < 4 { @@ -146,7 +138,21 @@ func cuttingRope(n int) int { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn cutting_rope(mut n: i32) -> i32 { + if n < 4 { + return n - 1; + } + let mut res = 1i64; + while n > 4 { + res = (res * 3) % 1000000007; + n -= 3; + } + ((res * (n as i64)) % 1000000007) as i32 + } +} +``` ```js /** @@ -179,26 +185,6 @@ var cuttingRope = function (n) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn cutting_rope(mut n: i32) -> i32 { - if n < 4 { - return n - 1; - } - let mut res = 1i64; - while n > 4 { - res = (res * 3) % 1000000007; - n -= 3; - } - ((res * (n as i64)) % 1000000007) as i32 - } -} -``` - -### **C#** - ```cs public class Solution { public int CuttingRope(int n) { @@ -218,10 +204,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/README.md" index 2fbffa4da8380..a3da6974c6c77 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23015. \344\272\214\350\277\233\345\210\266\344\270\2551\347\232\204\344\270\252\346\225\260/README.md" @@ -52,7 +52,7 @@ ## 解法 -**方法一:位运算** +### 方法一:位运算 由于 `n & (n - 1)` 会消除 $n$ 的二进制表示中的最后一个 $1$,因此对 $n$ 重复该操作,直到 $n$ 变成 $0$,此时的操作次数即为 $n$ 的二进制表示中的 $1$ 的个数。 @@ -62,36 +62,12 @@ -### **Python3** - ```python class Solution: def hammingWeight(self, n: int) -> int: return n.bit_count() ``` -```python -class Solution: - def hammingWeight(self, n: int) -> int: - ans = 0 - while n: - n &= n - 1 - ans += 1 - return ans -``` - -```python -class Solution: - def hammingWeight(self, n: int) -> int: - ans = 0 - while n: - n -= n & (-n) - ans += 1 - return ans -``` - -### **Java** - ```java public class Solution { // you need to treat n as an unsigned value @@ -106,22 +82,6 @@ public class Solution { } ``` -```java -public class Solution { - // you need to treat n as an unsigned value - public int hammingWeight(int n) { - int ans = 0; - while (n != 0) { - n -= n & -n; - ++ans; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -136,22 +96,6 @@ public: }; ``` -```cpp -class Solution { -public: - int hammingWeight(uint32_t n) { - int ans = 0; - while (n != 0) { - n -= n & -n; - ++ans; - } - return ans; - } -}; -``` - -### **Go** - ```go func hammingWeight(num uint32) (ans int) { for num != 0 { @@ -162,18 +106,6 @@ func hammingWeight(num uint32) (ans int) { } ``` -```go -func hammingWeight(num uint32) (ans int) { - for num != 0 { - num -= num & -num - ans++ - } - return -} -``` - -### **JavaScript** - ```js /** * @param {number} n - a positive integer @@ -189,8 +121,6 @@ var hammingWeight = function (n) { }; ``` -### **C#** - ```cs public class Solution { public int HammingWeight(uint n) { @@ -204,10 +134,76 @@ public class Solution { } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def hammingWeight(self, n: int) -> int: + ans = 0 + while n: + n &= n - 1 + ans += 1 + return ans +``` + +```java +public class Solution { + // you need to treat n as an unsigned value + public int hammingWeight(int n) { + int ans = 0; + while (n != 0) { + n -= n & -n; + ++ans; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int hammingWeight(uint32_t n) { + int ans = 0; + while (n != 0) { + n -= n & -n; + ++ans; + } + return ans; + } +}; +``` +```go +func hammingWeight(num uint32) (ans int) { + for num != 0 { + num -= num & -num + ans++ + } + return +} ``` + + +### 方法三 + + + +```python +class Solution: + def hammingWeight(self, n: int) -> int: + ans = 0 + while n: + n -= n & (-n) + ans += 1 + return ans ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/README.md" index 0c0687063abd1..7c43ea12b6429 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23016. \346\225\260\345\200\274\347\232\204\346\225\264\346\225\260\346\254\241\346\226\271/README.md" @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:数学(快速幂)** +### 方法一:数学(快速幂) 快速幂算法的核心思想是将幂指数 $n$ 拆分为若干个二进制位上的 $1$ 的和,然后将 $x$ 的 $n$ 次幂转化为 $x$ 的若干个幂的乘积。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def myPow(self, x: float, n: int) -> float: @@ -71,10 +65,6 @@ class Solution: return qpow(x, n) if n >= 0 else 1 / qpow(x, -n) ``` -### **Java** - - - ```java class Solution { public double myPow(double x, int n) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func myPow(x float64, n int) float64 { qpow := func(a float64, n int) float64 { @@ -136,31 +122,6 @@ func myPow(x float64, n int) float64 { } ``` -### **JavaScript** - -```js -/** - * @param {number} x - * @param {number} n - * @return {number} - */ -var myPow = function (x, n) { - const qpow = (a, n) => { - let ans = 1; - for (; n; n >>>= 1) { - if (n & 1) { - ans *= a; - } - a *= a; - } - return ans; - }; - return n >= 0 ? qpow(x, n) : 1 / qpow(x, -n); -}; -``` - -### **TypeScript** - ```ts function myPow(x: number, n: number): number { const qpow = (a: number, n: number): number => { @@ -177,29 +138,6 @@ function myPow(x: number, n: number): number { } ``` -### **C#** - -```cs -public class Solution { - public double MyPow(double x, int n) { - return n >= 0 ? qpow(x, n) : 1.0 / qpow(x, -(long)n); - } - - private double qpow(double a, long n) { - double ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans *= a; - } - a *= a; - } - return ans; - } -} -``` - -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -229,10 +167,46 @@ impl Solution { } ``` -### **...** - +```js +/** + * @param {number} x + * @param {number} n + * @return {number} + */ +var myPow = function (x, n) { + const qpow = (a, n) => { + let ans = 1; + for (; n; n >>>= 1) { + if (n & 1) { + ans *= a; + } + a *= a; + } + return ans; + }; + return n >= 0 ? qpow(x, n) : 1 / qpow(x, -n); +}; ``` +```cs +public class Solution { + public double MyPow(double x, int n) { + return n >= 0 ? qpow(x, n) : 1.0 / qpow(x, -(long)n); + } + + private double qpow(double a, long n) { + double ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans *= a; + } + a *= a; + } + return ans; + } +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23017. \346\211\223\345\215\260\344\273\2161\345\210\260\346\234\200\345\244\247\347\232\204n\344\275\215\346\225\260/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23017. \346\211\223\345\215\260\344\273\2161\345\210\260\346\234\200\345\244\247\347\232\204n\344\275\215\346\225\260/README.md" index e7dad2966672b..a499463fb0ad9 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23017. \346\211\223\345\215\260\344\273\2161\345\210\260\346\234\200\345\244\247\347\232\204n\344\275\215\346\225\260/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23017. \346\211\223\345\215\260\344\273\2161\345\210\260\346\234\200\345\244\247\347\232\204n\344\275\215\346\225\260/README.md" @@ -21,7 +21,7 @@ ## 解法 -**方法一:模拟** +### 方法一:模拟 直接根据题意模拟即可。 @@ -31,8 +31,6 @@ -### **Python3** - ```python class Solution: def printNumbers(self, n: int) -> List[int]: @@ -57,8 +55,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] printNumbers(int n) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +122,6 @@ public: }; ``` -### **Go** - ```go func printNumbers(n int) []int { n = int(math.Pow(10, float64(n))) - 1 @@ -167,8 +159,6 @@ func print(n int) []string { } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -183,8 +173,6 @@ var printNumbers = function (n) { }; ``` -### **C#** - ```cs public class Solution { public int[] PrintNumbers(int n) { @@ -198,10 +186,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23018. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\350\212\202\347\202\271/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23018. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\350\212\202\347\202\271/README.md" index 81b433f477d99..42b12ed6bea91 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23018. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\350\212\202\347\202\271/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23018. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\350\212\202\347\202\271/README.md" @@ -33,7 +33,7 @@ ## 解法 -**方法一:模拟** +### 方法一:模拟 我们先创建一个虚拟头节点 `dummy`,令 `dummy.next = head`,然后创建一个指针 `cur` 指向 `dummy`。 @@ -45,8 +45,6 @@ -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -64,8 +62,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -115,8 +109,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -137,35 +129,6 @@ func deleteNode(head *ListNode, val int) *ListNode { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val) { - * this.val = val; - * this.next = null; - * } - */ -/** - * @param {ListNode} head - * @param {number} val - * @return {ListNode} - */ -var deleteNode = function (head, val) { - const dummy = new ListNode(0, head); - for (let cur = dummy; cur.next; cur = cur.next) { - if (cur.next.val == val) { - cur.next = cur.next.next; - break; - } - } - return dummy.next; -}; -``` - -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -198,7 +161,30 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @param {number} val + * @return {ListNode} + */ +var deleteNode = function (head, val) { + const dummy = new ListNode(0, head); + for (let cur = dummy; cur.next; cur = cur.next) { + if (cur.next.val == val) { + cur.next = cur.next.next; + break; + } + } + return dummy.next; +}; +``` ```cs /** @@ -223,10 +209,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/README.md" index e1d96ec0b7a41..decd857296a80 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23019. \346\255\243\345\210\231\350\241\250\350\276\276\345\274\217\345\214\271\351\205\215/README.md" @@ -56,7 +56,7 @@ p = "mis*is*p*." ## 解法 -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j)$,表示从 $s$ 的第 $i$ 个字符开始,和 $p$ 的第 $j$ 个字符开始是否匹配。那么答案就是 $dfs(0, 0)$。 @@ -70,23 +70,8 @@ p = "mis*is*p*." 时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是 $s$ 和 $p$ 的长度。 -**方法二:动态规划** - -我们可以将方法一中的记忆化搜索转换为动态规划。 - -定义 $f[i][j]$ 表示字符串 $s$ 的前 $i$ 个字符和字符串 $p$ 的前 $j$ 个字符是否匹配。那么答案就是 $f[m][n]$。初始化 $f[0][0] = true$,表示空字符串和空正则表达式是匹配的。 - -与方法一类似,我们可以分情况来讨论。 - -- 如果 $p[j - 1]$ 是 `'*'`,那么我们可以选择匹配 $0$ 个 $s[i - 1]$ 字符,那么就是 $f[i][j] = f[i][j - 2]$。如果此时 $s[i - 1]$ 和 $p[j - 2]$ 匹配,那么我们可以选择匹配 $1$ 个 $s[i - 1]$ 字符,那么就是 $f[i][j] = f[i][j] \lor f[i - 1][j]$。 -- 如果 $p[j - 1]$ 不是 `'*'`,那么如果 $s[i - 1]$ 和 $p[j - 1]$ 匹配,那么就是 $f[i][j] = f[i - 1][j - 1]$。否则匹配失败。 - -时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是 $s$ 和 $p$ 的长度。 - -### **Python3** - ```python class Solution: def isMatch(self, s: str, p: str) -> bool: @@ -104,25 +89,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def isMatch(self, s: str, p: str) -> bool: - m, n = len(s), len(p) - f = [[False] * (n + 1) for _ in range(m + 1)] - f[0][0] = True - for i in range(m + 1): - for j in range(1, n + 1): - if p[j - 1] == "*": - f[i][j] = f[i][j - 2] - if i > 0 and (p[j - 2] == "." or s[i - 1] == p[j - 2]): - f[i][j] |= f[i - 1][j] - elif i > 0 and (p[j - 1] == "." or s[i - 1] == p[j - 1]): - f[i][j] = f[i - 1][j - 1] - return f[m][n] -``` - -### **Java** - ```java class Solution { private Boolean[][] f; @@ -159,32 +125,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isMatch(String s, String p) { - int m = s.length(), n = p.length(); - boolean[][] f = new boolean[m + 1][n + 1]; - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (p.charAt(j - 1) == '*') { - f[i][j] = f[i][j - 2]; - if (i > 0 && (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1))) { - f[i][j] |= f[i - 1][j]; - } - } else if (i > 0 - && (p.charAt(j - 1) == '.' || p.charAt(j - 1) == s.charAt(i - 1))) { - f[i][j] = f[i - 1][j - 1]; - } - } - } - return f[m][n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -215,33 +155,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool isMatch(string s, string p) { - int m = s.size(), n = p.size(); - bool f[m + 1][n + 1]; - memset(f, false, sizeof f); - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (p[j - 1] == '*') { - f[i][j] = f[i][j - 2]; - if (i && (p[j - 2] == '.' || p[j - 2] == s[i - 1])) { - f[i][j] |= f[i - 1][j]; - } - } else if (i && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { - f[i][j] = f[i - 1][j - 1]; - } - } - } - return f[m][n]; - } -}; -``` - -### **Go** - ```go func isMatch(s string, p string) bool { m, n := len(s), len(p) @@ -272,32 +185,6 @@ func isMatch(s string, p string) bool { } ``` -```go -func isMatch(s string, p string) bool { - m, n := len(s), len(p) - f := make([][]bool, m+1) - for i := range f { - f[i] = make([]bool, n+1) - } - f[0][0] = true - for i := 0; i <= m; i++ { - for j := 1; j <= n; j++ { - if p[j-1] == '*' { - f[i][j] = f[i][j-2] - if i > 0 && (p[j-2] == '.' || p[j-2] == s[i-1]) { - f[i][j] = f[i][j] || f[i-1][j] - } - } else if i > 0 && (p[j-1] == '.' || p[j-1] == s[i-1]) { - f[i][j] = f[i-1][j-1] - } - } - } - return f[m][n] -} -``` - -### **JavaScript** - ```js /** * @param {string} s @@ -330,35 +217,6 @@ var isMatch = function (s, p) { }; ``` -```js -/** - * @param {string} s - * @param {string} p - * @return {boolean} - */ -var isMatch = function (s, p) { - const m = s.length; - const n = p.length; - const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(false)); - f[0][0] = true; - for (let i = 0; i <= m; ++i) { - for (let j = 1; j <= n; ++j) { - if (p[j - 1] === '*') { - f[i][j] = f[i][j - 2]; - if (i && (p[j - 2] === '.' || p[j - 2] == s[i - 1])) { - f[i][j] |= f[i - 1][j]; - } - } else if (i && (p[j - 1] === '.' || p[j - 1] == s[i - 1])) { - f[i][j] = f[i - 1][j - 1]; - } - } - } - return f[m][n]; -}; -``` - -### **C#** - ```cs public class Solution { private string s; @@ -397,6 +255,140 @@ public class Solution { } ``` + + +### 方法二:动态规划 + +我们可以将方法一中的记忆化搜索转换为动态规划。 + +定义 $f[i][j]$ 表示字符串 $s$ 的前 $i$ 个字符和字符串 $p$ 的前 $j$ 个字符是否匹配。那么答案就是 $f[m][n]$。初始化 $f[0][0] = true$,表示空字符串和空正则表达式是匹配的。 + +与方法一类似,我们可以分情况来讨论。 + +- 如果 $p[j - 1]$ 是 `'*'`,那么我们可以选择匹配 $0$ 个 $s[i - 1]$ 字符,那么就是 $f[i][j] = f[i][j - 2]$。如果此时 $s[i - 1]$ 和 $p[j - 2]$ 匹配,那么我们可以选择匹配 $1$ 个 $s[i - 1]$ 字符,那么就是 $f[i][j] = f[i][j] \lor f[i - 1][j]$。 +- 如果 $p[j - 1]$ 不是 `'*'`,那么如果 $s[i - 1]$ 和 $p[j - 1]$ 匹配,那么就是 $f[i][j] = f[i - 1][j - 1]$。否则匹配失败。 + +时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是 $s$ 和 $p$ 的长度。 + + + +```python +class Solution: + def isMatch(self, s: str, p: str) -> bool: + m, n = len(s), len(p) + f = [[False] * (n + 1) for _ in range(m + 1)] + f[0][0] = True + for i in range(m + 1): + for j in range(1, n + 1): + if p[j - 1] == "*": + f[i][j] = f[i][j - 2] + if i > 0 and (p[j - 2] == "." or s[i - 1] == p[j - 2]): + f[i][j] |= f[i - 1][j] + elif i > 0 and (p[j - 1] == "." or s[i - 1] == p[j - 1]): + f[i][j] = f[i - 1][j - 1] + return f[m][n] +``` + +```java +class Solution { + public boolean isMatch(String s, String p) { + int m = s.length(), n = p.length(); + boolean[][] f = new boolean[m + 1][n + 1]; + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (p.charAt(j - 1) == '*') { + f[i][j] = f[i][j - 2]; + if (i > 0 && (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1))) { + f[i][j] |= f[i - 1][j]; + } + } else if (i > 0 + && (p.charAt(j - 1) == '.' || p.charAt(j - 1) == s.charAt(i - 1))) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; + } +} +``` + +```cpp +class Solution { +public: + bool isMatch(string s, string p) { + int m = s.size(), n = p.size(); + bool f[m + 1][n + 1]; + memset(f, false, sizeof f); + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (p[j - 1] == '*') { + f[i][j] = f[i][j - 2]; + if (i && (p[j - 2] == '.' || p[j - 2] == s[i - 1])) { + f[i][j] |= f[i - 1][j]; + } + } else if (i && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; + } +}; +``` + +```go +func isMatch(s string, p string) bool { + m, n := len(s), len(p) + f := make([][]bool, m+1) + for i := range f { + f[i] = make([]bool, n+1) + } + f[0][0] = true + for i := 0; i <= m; i++ { + for j := 1; j <= n; j++ { + if p[j-1] == '*' { + f[i][j] = f[i][j-2] + if i > 0 && (p[j-2] == '.' || p[j-2] == s[i-1]) { + f[i][j] = f[i][j] || f[i-1][j] + } + } else if i > 0 && (p[j-1] == '.' || p[j-1] == s[i-1]) { + f[i][j] = f[i-1][j-1] + } + } + } + return f[m][n] +} +``` + +```js +/** + * @param {string} s + * @param {string} p + * @return {boolean} + */ +var isMatch = function (s, p) { + const m = s.length; + const n = p.length; + const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(false)); + f[0][0] = true; + for (let i = 0; i <= m; ++i) { + for (let j = 1; j <= n; ++j) { + if (p[j - 1] === '*') { + f[i][j] = f[i][j - 2]; + if (i && (p[j - 2] === '.' || p[j - 2] == s[i - 1])) { + f[i][j] |= f[i - 1][j]; + } + } else if (i && (p[j - 1] === '.' || p[j - 1] == s[i - 1])) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; +}; +``` + ```cs public class Solution { public bool IsMatch(string s, string p) { @@ -420,10 +412,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23020. \350\241\250\347\244\272\346\225\260\345\200\274\347\232\204\345\255\227\347\254\246\344\270\262/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23020. \350\241\250\347\244\272\346\225\260\345\200\274\347\232\204\345\255\227\347\254\246\344\270\262/README.md" index eaad10f18b90a..9563d927672bc 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23020. \350\241\250\347\244\272\346\225\260\345\200\274\347\232\204\345\255\227\347\254\246\344\270\262/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23020. \350\241\250\347\244\272\346\225\260\345\200\274\347\232\204\345\255\227\347\254\246\344\270\262/README.md" @@ -87,9 +87,7 @@ ## 解法 - - -**方法一:分类讨论** +### 方法一:分类讨论 我们先去除字符串 $s$ 首尾的空格,此时 $i$ 和 $j$ 分别指向字符串 $s$ 的第一个非空格字符和最后一个非空格字符。 @@ -113,10 +111,6 @@ -### **Python3** - - - ```python class Solution: def isNumber(self, s: str) -> bool: @@ -148,10 +142,6 @@ class Solution: return digit ``` -### **Java** - - - ```java class Solution { public boolean isNumber(String s) { @@ -196,8 +186,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -240,8 +228,6 @@ public: }; ``` -### **Go** - ```go func isNumber(s string) bool { i, j := 0, len(s)-1 @@ -280,8 +266,6 @@ func isNumber(s string) bool { } ``` -### **C#** - ```cs public class Solution { public bool IsNumber(string s) { @@ -323,10 +307,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23021. \350\260\203\346\225\264\346\225\260\347\273\204\351\241\272\345\272\217\344\275\277\345\245\207\346\225\260\344\275\215\344\272\216\345\201\266\346\225\260\345\211\215\351\235\242/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23021. \350\260\203\346\225\264\346\225\260\347\273\204\351\241\272\345\272\217\344\275\277\345\245\207\346\225\260\344\275\215\344\272\216\345\201\266\346\225\260\345\211\215\351\235\242/README.md" index ce3f890959d3b..910643ea7a8e5 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23021. \350\260\203\346\225\264\346\225\260\347\273\204\351\241\272\345\272\217\344\275\277\345\245\207\346\225\260\344\275\215\344\272\216\345\201\266\346\225\260\345\211\215\351\235\242/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23021. \350\260\203\346\225\264\346\225\260\347\273\204\351\241\272\345\272\217\344\275\277\345\245\207\346\225\260\344\275\215\344\272\216\345\201\266\346\225\260\345\211\215\351\235\242/README.md" @@ -24,7 +24,7 @@ ## 解法 -**方法一:双指针** +### 方法一:双指针 我们定义两个指针 $i$ 和 $j$,其中指针 $i$ 指向当前元素,指针 $j$ 指向当前最后一个奇数的下一个位置。 @@ -34,8 +34,6 @@ -### **Python3** - ```python class Solution: def exchange(self, nums: List[int]) -> List[int]: @@ -47,8 +45,6 @@ class Solution: return nums ``` -### **Java** - ```java class Solution { public int[] exchange(int[] nums) { @@ -65,8 +61,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -82,8 +76,6 @@ public: }; ``` -### **Go** - ```go func exchange(nums []int) []int { j := 0 @@ -97,28 +89,6 @@ func exchange(nums []int) []int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var exchange = function (nums) { - let j = 0; - for (let i = 0; i < nums.length; ++i) { - if (nums[i] & 1) { - const t = nums[i]; - nums[i] = nums[j]; - nums[j++] = t; - } - } - return nums; -}; -``` - -### **TypeScript** - ```ts function exchange(nums: number[]): number[] { let j = 0; @@ -133,8 +103,6 @@ function exchange(nums: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn exchange(mut nums: Vec) -> Vec { @@ -150,7 +118,23 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var exchange = function (nums) { + let j = 0; + for (let i = 0; i < nums.length; ++i) { + if (nums[i] & 1) { + const t = nums[i]; + nums[i] = nums[j]; + nums[j++] = t; + } + } + return nums; +}; +``` ```cs public class Solution { @@ -168,10 +152,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23022. \351\223\276\350\241\250\344\270\255\345\200\222\346\225\260\347\254\254k\344\270\252\350\212\202\347\202\271/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23022. \351\223\276\350\241\250\344\270\255\345\200\222\346\225\260\347\254\254k\344\270\252\350\212\202\347\202\271/README.md" index 336209ad08b20..25631b3b4c081 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23022. \351\223\276\350\241\250\344\270\255\345\200\222\346\225\260\347\254\254k\344\270\252\350\212\202\347\202\271/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23022. \351\223\276\350\241\250\344\270\255\345\200\222\346\225\260\347\254\254k\344\270\252\350\212\202\347\202\271/README.md" @@ -17,7 +17,7 @@ ## 解法 -**方法一:快慢指针** +### 方法一:快慢指针 我们可以定义快慢指针 `fast` 和 `slow`,初始时均指向 `head`。 @@ -27,8 +27,6 @@ -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -47,8 +45,6 @@ class Solution: return slow ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -73,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -100,8 +94,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -122,37 +114,6 @@ func getKthFromEnd(head *ListNode, k int) *ListNode { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val) { - * this.val = val; - * this.next = null; - * } - */ -/** - * @param {ListNode} head - * @param {number} k - * @return {ListNode} - */ -var getKthFromEnd = function (head, k) { - let fast = head; - while (k--) { - fast = fast.next; - } - let slow = head; - while (fast) { - slow = slow.next; - fast = fast.next; - } - return slow; -}; -``` - -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -186,7 +147,32 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @param {number} k + * @return {ListNode} + */ +var getKthFromEnd = function (head, k) { + let fast = head; + while (k--) { + fast = fast.next; + } + let slow = head; + while (fast) { + slow = slow.next; + fast = fast.next; + } + return slow; +}; +``` ```cs /** @@ -212,10 +198,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/README.md" index 96a9ce4e05926..59255fafa44c2 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23024. \345\217\215\350\275\254\351\223\276\350\241\250/README.md" @@ -23,22 +23,14 @@ ## 解法 -**方法一:头插法** +### 方法一:头插法 创建虚拟头节点 $dummy$,遍历链表,将每个节点依次插入 $dummy$ 的下一个节点。遍历结束,返回 $dummy.next$。 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为链表的长度。 -**方法二:递归** - -递归反转链表的第二个节点到尾部的所有节点,然后 $head$ 插在反转后的链表的尾部。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为链表的长度。 - -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -59,26 +51,6 @@ class Solution: return dummy.next ``` -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None - - -class Solution: - def reverseList(self, head: ListNode) -> ListNode: - if head is None or head.next is None: - return head - ans = self.reverseList(head.next) - head.next.next = head - head.next = None - return ans -``` - -### **Java** - ```java /** * Definition for singly-linked list. @@ -103,30 +75,6 @@ class Solution { } ``` -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { val = x; } - * } - */ -class Solution { - public ListNode reverseList(ListNode head) { - if (head == null || head.next == null) { - return head; - } - ListNode ans = reverseList(head.next); - head.next.next = head; - head.next = null; - return ans; - } -} -``` - -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -152,31 +100,6 @@ public: }; ``` -```cpp -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* reverseList(ListNode* head) { - if (!head || !head->next) { - return head; - } - ListNode* ans = reverseList(head->next); - head->next->next = head; - head->next = nullptr; - return ans; - } -}; -``` - -### **Go** - ```go /** * Definition for singly-linked list. @@ -198,77 +121,6 @@ func reverseList(head *ListNode) *ListNode { } ``` -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -func reverseList(head *ListNode) *ListNode { - if head == nil || head.Next == nil { - return head - } - ans := reverseList(head.Next) - head.Next.Next = head - head.Next = nil - return ans -} -``` - -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val) { - * this.val = val; - * this.next = null; - * } - */ -/** - * @param {ListNode} head - * @return {ListNode} - */ -var reverseList = function (head) { - const dummy = new ListNode(0); - let curr = head; - while (curr) { - const next = curr.next; - curr.next = dummy.next; - dummy.next = curr; - curr = next; - } - return dummy.next; -}; -``` - -```js -/** - * Definition for singly-linked list. - * function ListNode(val) { - * this.val = val; - * this.next = null; - * } - */ -/** - * @param {ListNode} head - * @return {ListNode} - */ -var reverseList = function (head) { - if (!head || !head.next) { - return head; - } - const ans = reverseList(head.next); - head.next.next = head; - head.next = null; - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -295,32 +147,6 @@ function reverseList(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 reverseList(head: ListNode | null): ListNode | null { - if (!head || !head.next) { - return head; - } - const ans = reverseList(head.next); - head.next.next = head; - head.next = null; - return ans; -} -``` - -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -353,7 +179,30 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var reverseList = function (head) { + const dummy = new ListNode(0); + let curr = head; + while (curr) { + const next = curr.next; + curr.next = dummy.next; + dummy.next = curr; + curr = next; + } + return dummy.next; +}; +``` ```cs /** @@ -379,6 +228,145 @@ public class Solution { } ``` + + +### 方法二:递归 + +递归反转链表的第二个节点到尾部的所有节点,然后 $head$ 插在反转后的链表的尾部。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为链表的长度。 + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + + +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + if head is None or head.next is None: + return head + ans = self.reverseList(head.next) + head.next.next = head + head.next = None + return ans +``` + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode ans = reverseList(head.next); + head.next.next = head; + head.next = null; + return ans; + } +} +``` + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + if (!head || !head->next) { + return head; + } + ListNode* ans = reverseList(head->next); + head->next->next = head; + head->next = nullptr; + return ans; + } +}; +``` + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseList(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + ans := reverseList(head.Next) + head.Next.Next = head + head.Next = nil + return ans +} +``` + +```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 reverseList(head: ListNode | null): ListNode | null { + if (!head || !head.next) { + return head; + } + const ans = reverseList(head.next); + head.next.next = head; + head.next = null; + return ans; +} +``` + +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var reverseList = function (head) { + if (!head || !head.next) { + return head; + } + const ans = reverseList(head.next); + head.next.next = head; + head.next = null; + return ans; +}; +``` + ```cs /** * Definition for singly-linked list. @@ -401,10 +389,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/README.md" index 7512a2b908d28..9937b571184d1 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23025. \345\220\210\345\271\266\344\270\244\344\270\252\346\216\222\345\272\217\347\232\204\351\223\276\350\241\250/README.md" @@ -17,7 +17,7 @@ ## 解法 -**方法一:迭代** +### 方法一:迭代 我们先创建一个虚拟头结点 `dummy`,然后创建一个指针 `cur` 指向 `dummy`。 @@ -27,21 +27,8 @@ 时间复杂度 $O(m + n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别为两个链表的长度。 -**方法二:递归** - -我们先判断 `l1` 和 `l2` 中有没有一个为空,如果有一个为空,那么我们直接返回另一个链表即可。 - -接下来,我们比较 `l1` 和 `l2` 的值: - -- 如果 `l1` 的值小于等于 `l2` 的值,我们递归调用 `mergeTwoLists(l1.next, l2)`,并将 `l1.next` 指向返回的链表,然后返回 `l1`。 -- 如果 `l1` 的值大于 `l2` 的值,我们递归调用 `mergeTwoLists(l1, l2.next)`,并将 `l2.next` 指向返回的链表,然后返回 `l2`。 - -时间复杂度 $O(m + n)$,空间复杂度 $O(m + n)$。其中 $m$ 和 $n$ 分别为两个链表的长度。 - -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -65,28 +52,6 @@ class Solution: return dummy.next ``` -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None - - -class Solution: - def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: - if l1 is None or l2 is None: - return l1 or l2 - if l1.val <= l2.val: - l1.next = self.mergeTwoLists(l1.next, l2) - return l1 - else: - l2.next = self.mergeTwoLists(l1, l2.next) - return l2 -``` - -### **Java** - ```java /** * Definition for singly-linked list. @@ -116,36 +81,6 @@ class Solution { } ``` -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { val = x; } - * } - */ -class Solution { - public ListNode mergeTwoLists(ListNode l1, ListNode l2) { - if (l1 == null) { - return l2; - } - if (l2 == null) { - return l1; - } - if (l1.val <= l2.val) { - l1.next = mergeTwoLists(l1.next, l2); - return l1; - } else { - l2.next = mergeTwoLists(l1, l2.next); - return l2; - } - } -} -``` - -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -176,37 +111,6 @@ public: }; ``` -```cpp -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { -public: - ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { - if (!l1) { - return l2; - } - if (!l2) { - return l1; - } - if (l1->val <= l2->val) { - l1->next = mergeTwoLists(l1->next, l2); - return l1; - } else { - l2->next = mergeTwoLists(l1, l2->next); - return l2; - } - } -}; -``` - -### **Go** - ```go /** * Definition for singly-linked list. @@ -237,32 +141,85 @@ func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { } ``` -```go +```ts /** * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode + * 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) + * } * } */ -func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { - if l1 == nil { - return l2 - } - if l2 == nil { - return l1 - } - if l1.Val <= l2.Val { - l1.Next = mergeTwoLists(l1.Next, l2) - return l1 - } else { - l2.Next = mergeTwoLists(l1, l2.Next) - return l2 - } + +function mergeTwoLists(l1: ListNode | null, l2: ListNode | null): ListNode | null { + const dummy = new ListNode(0); + let cur = dummy; + while (l1 && l2) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 || l2; + return dummy.next; } ``` -### **JavaScript** +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn merge_two_lists( + mut l1: Option>, + mut l2: Option> + ) -> Option> { + match (l1.is_some(), l2.is_some()) { + (false, false) => None, + (true, false) => l1, + (false, true) => l2, + (true, true) => { + let mut dummy = Box::new(ListNode::new(0)); + let mut cur = &mut dummy; + while l1.is_some() && l2.is_some() { + cur.next = if l1.as_ref().unwrap().val < l2.as_ref().unwrap().val { + let mut res = l1.take(); + l1 = res.as_mut().unwrap().next.take(); + res + } else { + let mut res = l2.take(); + l2 = res.as_mut().unwrap().next.take(); + res + }; + cur = cur.next.as_mut().unwrap(); + } + cur.next = if l1.is_some() { l1.take() } else { l2.take() }; + dummy.next.take() + } + } + } +} +``` ```js /** @@ -295,63 +252,149 @@ var mergeTwoLists = function (l1, l2) { }; ``` -```js +```cs /** * Definition for singly-linked list. - * function ListNode(val) { - * this.val = val; - * this.next = null; + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int x) { val = x; } * } */ -/** - * @param {ListNode} l1 - * @param {ListNode} l2 - * @return {ListNode} - */ -var mergeTwoLists = function (l1, l2) { - if (!(l1 && l2)) { - return l1 || l2; - } - if (l1.val < l2.val) { - l1.next = mergeTwoLists(l1.next, l2); - return l1; - } else { - l2.next = mergeTwoLists(l2.next, l1); - return l2; +public class Solution { + public ListNode MergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + ListNode cur = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; } -}; +} ``` -### **TypeScript** + -```ts +### 方法二:递归 + +我们先判断 `l1` 和 `l2` 中有没有一个为空,如果有一个为空,那么我们直接返回另一个链表即可。 + +接下来,我们比较 `l1` 和 `l2` 的值: + +- 如果 `l1` 的值小于等于 `l2` 的值,我们递归调用 `mergeTwoLists(l1.next, l2)`,并将 `l1.next` 指向返回的链表,然后返回 `l1`。 +- 如果 `l1` 的值大于 `l2` 的值,我们递归调用 `mergeTwoLists(l1, l2.next)`,并将 `l2.next` 指向返回的链表,然后返回 `l2`。 + +时间复杂度 $O(m + n)$,空间复杂度 $O(m + n)$。其中 $m$ 和 $n$ 分别为两个链表的长度。 + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + + +class Solution: + def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: + if l1 is None or l2 is None: + return l1 or l2 + if l1.val <= l2.val: + l1.next = self.mergeTwoLists(l1.next, l2) + return l1 + else: + l2.next = self.mergeTwoLists(l1, l2.next) + return l2 +``` + +```java /** * 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) - * } + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } * } */ - -function mergeTwoLists(l1: ListNode | null, l2: ListNode | null): ListNode | null { - const dummy = new ListNode(0); - let cur = dummy; - while (l1 && l2) { +class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + if (l1 == null) { + return l2; + } + if (l2 == null) { + return l1; + } if (l1.val <= l2.val) { - cur.next = l1; - l1 = l1.next; + l1.next = mergeTwoLists(l1.next, l2); + return l1; } else { - cur.next = l2; - l2 = l2.next; + l2.next = mergeTwoLists(l1, l2.next); + return l2; } - cur = cur.next; } - cur.next = l1 || l2; - return dummy.next; +} +``` + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + if (!l1) { + return l2; + } + if (!l2) { + return l1; + } + if (l1->val <= l2->val) { + l1->next = mergeTwoLists(l1->next, l2); + return l1; + } else { + l2->next = mergeTwoLists(l1, l2->next); + return l2; + } + } +}; +``` + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { + if l1 == nil { + return l2 + } + if l2 == nil { + return l1 + } + if l1.Val <= l2.Val { + l1.Next = mergeTwoLists(l1.Next, l2) + return l1 + } else { + l2.Next = mergeTwoLists(l1, l2.Next) + return l2 + } } ``` @@ -381,57 +424,6 @@ function mergeTwoLists(l1: ListNode | null, l2: ListNode | null): ListNode | nul } ``` -### **Rust** - -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn merge_two_lists( - mut l1: Option>, - mut l2: Option> - ) -> Option> { - match (l1.is_some(), l2.is_some()) { - (false, false) => None, - (true, false) => l1, - (false, true) => l2, - (true, true) => { - let mut dummy = Box::new(ListNode::new(0)); - let mut cur = &mut dummy; - while l1.is_some() && l2.is_some() { - cur.next = if l1.as_ref().unwrap().val < l2.as_ref().unwrap().val { - let mut res = l1.take(); - l1 = res.as_mut().unwrap().next.take(); - res - } else { - let mut res = l2.take(); - l2 = res.as_mut().unwrap().next.take(); - res - }; - cur = cur.next.as_mut().unwrap(); - } - cur.next = if l1.is_some() { l1.take() } else { l2.take() }; - dummy.next.take() - } - } - } -} -``` - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -472,35 +464,31 @@ impl Solution { } ``` -### **C#** - -```cs +```js /** * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int x) { val = x; } + * function ListNode(val) { + * this.val = val; + * this.next = null; * } */ -public class Solution { - public ListNode MergeTwoLists(ListNode l1, ListNode l2) { - ListNode dummy = new ListNode(0); - ListNode cur = dummy; - while (l1 != null && l2 != null) { - if (l1.val <= l2.val) { - cur.next = l1; - l1 = l1.next; - } else { - cur.next = l2; - l2 = l2.next; - } - cur = cur.next; - } - cur.next = l1 == null ? l2 : l1; - return dummy.next; +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var mergeTwoLists = function (l1, l2) { + if (!(l1 && l2)) { + return l1 || l2; } -} + if (l1.val < l2.val) { + l1.next = mergeTwoLists(l1.next, l2); + return l1; + } else { + l2.next = mergeTwoLists(l2.next, l1); + return l2; + } +}; ``` ```cs @@ -531,10 +519,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23026. \346\240\221\347\232\204\345\255\220\347\273\223\346\236\204/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23026. \346\240\221\347\232\204\345\255\220\347\273\223\346\236\204/README.md" index a64c0aeac11cd..f1dc6d843fc99 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23026. \346\240\221\347\232\204\345\255\220\347\273\223\346\236\204/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23026. \346\240\221\347\232\204\345\255\220\347\273\223\346\236\204/README.md" @@ -38,25 +38,9 @@ ## 解法 - - -**方法一:DFS** - -我们先判断 `A` 或 `B` 是否为空,如果 `A` 或 `B` 为空,直接返回 `false`。 - -然后我们定义一个 `dfs(A, B)` 函数,用于判断从 `A` 的根节点开始,是否存在一棵子树和 `B` 的结构相同,如果存在,返回 `true`,否则返回 `false`。 - -在 `dfs` 函数中,我们首先判断 `B` 是否为空,如果 `B` 为空,说明 `A` 的子树和 `B` 的结构相同,返回 `true`。 - -然后我们判断 `A` 是否为空,或者 `A` 和 `B` 的根节点值是否相同,如果 `A` 为空,或者 `A` 和 `B` 的根节点值不相同,说明 `A` 的子树和 `B` 的结构不同,返回 `false`。 +### 方法一 -最后我们返回 `dfs(A.left, B.left) and dfs(A.right, B.right)`,即 `A` 的左子树和 `B` 的左子树是否相同,以及 `A` 的右子树和 `B` 的右子树是否相同。 - -最后我们返回 `dfs(A, B) or isSubStructure(A.left, B) or isSubStructure(A.right, B)`,即 `A` 的子树和 `B` 的结构是否相同,或者 `A` 的左子树和 `B` 的结构是否相同,或者 `A` 的右子树和 `B` 的结构是否相同。 - -时间复杂度 $O(m \times n)$,空间复杂度 $O(\max(m, n))$。其中 $m$ 和 $n$ 分别为树 `A` 和 `B` 的节点数。 - -### **Python3** + ```python # Definition for a binary tree node. @@ -83,8 +67,6 @@ class Solution: return self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -115,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -142,8 +122,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -171,40 +149,6 @@ func isSubStructure(A *TreeNode, B *TreeNode) bool { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} A - * @param {TreeNode} B - * @return {boolean} - */ -var isSubStructure = function (A, B) { - if (!A || !B) { - return false; - } - const dfs = (A, B) => { - if (!B) { - return true; - } - if (!A || A.val !== B.val) { - return false; - } - return dfs(A.left, B.left) && dfs(A.right, B.right); - }; - return dfs(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B); -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -237,8 +181,6 @@ function isSubStructure(A: TreeNode | null, B: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -295,7 +237,35 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} A + * @param {TreeNode} B + * @return {boolean} + */ +var isSubStructure = function (A, B) { + if (!A || !B) { + return false; + } + const dfs = (A, B) => { + if (!B) { + return true; + } + if (!A || A.val !== B.val) { + return false; + } + return dfs(A.left, B.left) && dfs(A.right, B.right); + }; + return dfs(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B); +}; +``` ```cs /** @@ -327,10 +297,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23027. \344\272\214\345\217\211\346\240\221\347\232\204\351\225\234\345\203\217/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23027. \344\272\214\345\217\211\346\240\221\347\232\204\351\225\234\345\203\217/README.md" index 56ca3db55ced6..027dea081393c 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23027. \344\272\214\345\217\211\346\240\221\347\232\204\351\225\234\345\203\217/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23027. \344\272\214\345\217\211\346\240\221\347\232\204\351\225\234\345\203\217/README.md" @@ -37,7 +37,7 @@ ## 解法 -**方法一:递归** +### 方法一:递归 我们先判断根节点是否为空,如果为空,直接返回空。如果不为空,我们交换根节点的左右子树,然后递归地交换左子树和右子树。 @@ -45,8 +45,6 @@ -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -66,28 +64,6 @@ class Solution: return root ``` -```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 mirrorTree(self, root: TreeNode) -> TreeNode: - if root is None: - return root - left = self.mirrorTree(root.left) - right = self.mirrorTree(root.right) - root.left = right - root.right = left - return root -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -113,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -139,8 +113,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -161,35 +133,6 @@ func mirrorTree(root *TreeNode) *TreeNode { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} root - * @return {TreeNode} - */ -var mirrorTree = function (root) { - if (!root) { - return null; - } - const { left, right } = root; - root.left = right; - root.right = left; - mirrorTree(left); - mirrorTree(right); - return root; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -218,8 +161,6 @@ function mirrorTree(root: TreeNode | null): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -260,7 +201,30 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {TreeNode} + */ +var mirrorTree = function (root) { + if (!root) { + return null; + } + const { left, right } = root; + root.left = right; + root.right = left; + mirrorTree(left); + mirrorTree(right); + return root; +}; +``` ```cs /** @@ -287,10 +251,32 @@ public class Solution { } ``` -### **...** + + +### 方法二 + + + +```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 mirrorTree(self, root: TreeNode) -> TreeNode: + if root is None: + return root + left = self.mirrorTree(root.left) + right = self.mirrorTree(root.right) + root.left = right + root.right = left + return root ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23028. \345\257\271\347\247\260\347\232\204\344\272\214\345\217\211\346\240\221/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23028. \345\257\271\347\247\260\347\232\204\344\272\214\345\217\211\346\240\221/README.md" index abe8b41b49e97..98d040c10a4b4 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23028. \345\257\271\347\247\260\347\232\204\344\272\214\345\217\211\346\240\221/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23028. \345\257\271\347\247\260\347\232\204\344\272\214\345\217\211\346\240\221/README.md" @@ -42,7 +42,7 @@ ## 解法 -**方法一:递归** +### 方法一:递归 我们设计一个递归函数 `dfs`,它接收两个参数 `a` 和 `b`,分别代表两棵树的根节点。我们可以对 `a` 和 `b` 进行如下判断: @@ -57,8 +57,6 @@ -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -80,8 +78,6 @@ class Solution: return dfs(root, root) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -138,8 +132,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -164,36 +156,6 @@ func isSymmetric(root *TreeNode) bool { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} root - * @return {boolean} - */ -var isSymmetric = function (root) { - const dfs = (a, b) => { - if (!a && !b) { - return true; - } - if (!a || !b || a.val != b.val) { - return false; - } - return dfs(a.left, b.right) && dfs(a.right, b.left); - }; - return dfs(root, root); -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -223,8 +185,6 @@ function isSymmetric(root: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -265,7 +225,31 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isSymmetric = function (root) { + const dfs = (a, b) => { + if (!a && !b) { + return true; + } + if (!a || !b || a.val != b.val) { + return false; + } + return dfs(a.left, b.right) && dfs(a.right, b.left); + }; + return dfs(root, root); +}; +``` ```cs /** @@ -294,10 +278,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/README.md" index 65c0d3469926a..bc0e957b05ba0 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/README.md" @@ -31,22 +31,14 @@ ## 解法 -**方法一:模拟** +### 方法一:模拟 我们用 $i$ 和 $j$ 分别表示当前访问到的元素的行和列,用 $k$ 表示当前的方向,用数组或哈希表 $vis$ 记录每个元素是否被访问过。每次我们访问到一个元素后,将其标记为已访问,然后按照当前的方向前进一步,如果前进一步后发现越界或者已经访问过,则改变方向继续前进,直到遍历完整个矩阵。 时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。 -**方法二:逐层模拟** - -从外往里一圈一圈遍历并存储矩阵元素即可。 - -时间复杂度 $O(m \times n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。 - -### **Python3** - ```python class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: @@ -68,26 +60,6 @@ class Solution: return ans ``` -```python -class Solution: - def spiralOrder(self, matrix: List[List[int]]) -> List[int]: - if not matrix or not matrix[0]: - return [] - m, n = len(matrix), len(matrix[0]) - ans = [] - top, bottom, left, right = 0, m - 1, 0, n - 1 - while left <= right and top <= bottom: - ans.extend([matrix[top][j] for j in range(left, right + 1)]) - ans.extend([matrix[i][right] for i in range(top + 1, bottom + 1)]) - if left < right and top < bottom: - ans.extend([matrix[bottom][j] for j in range(right - 1, left - 1, -1)]) - ans.extend([matrix[i][left] for i in range(bottom - 1, top, -1)]) - top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1 - return ans -``` - -### **Java** - ```java class Solution { public int[] spiralOrder(int[][] matrix) { @@ -116,43 +88,6 @@ class Solution { } ``` -```java -class Solution { - public int[] spiralOrder(int[][] matrix) { - if (matrix.length == 0 || matrix[0].length == 0) { - return new int[] {}; - } - int m = matrix.length, n = matrix[0].length; - int top = 0, bottom = m - 1, left = 0, right = n - 1; - int[] ans = new int[m * n]; - int k = 0; - while (left <= right && top <= bottom) { - for (int j = left; j <= right; ++j) { - ans[k++] = matrix[top][j]; - } - for (int i = top + 1; i <= bottom; ++i) { - ans[k++] = matrix[i][right]; - } - if (left < right && top < bottom) { - for (int j = right - 1; j >= left; --j) { - ans[k++] = matrix[bottom][j]; - } - for (int i = bottom - 1; i > top; --i) { - ans[k++] = matrix[i][left]; - } - } - ++top; - --bottom; - ++left; - --right; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -183,35 +118,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector spiralOrder(vector>& matrix) { - if (matrix.size() == 0 || matrix[0].size() == 0) { - return {}; - } - int m = matrix.size(), n = matrix[0].size(); - int top = 0, bottom = m - 1, left = 0, right = n - 1; - vector ans; - while (top <= bottom && left <= right) { - for (int j = left; j <= right; ++j) ans.push_back(matrix[top][j]); - for (int i = top + 1; i <= bottom; ++i) ans.push_back(matrix[i][right]); - if (left < right && top < bottom) { - for (int j = right - 1; j >= left; --j) ans.push_back(matrix[bottom][j]); - for (int i = bottom - 1; i > top; --i) ans.push_back(matrix[i][left]); - } - ++top; - --bottom; - ++left; - --right; - } - return ans; - } -}; -``` - -### **Go** - ```go func spiralOrder(matrix [][]int) []int { if len(matrix) == 0 || len(matrix[0]) == 0 { @@ -239,42 +145,80 @@ func spiralOrder(matrix [][]int) []int { } ``` -```go -func spiralOrder(matrix [][]int) []int { - if len(matrix) == 0 || len(matrix[0]) == 0 { - return []int{} - } - m, n := len(matrix), len(matrix[0]) - ans := make([]int, 0, m*n) - - top, bottom, left, right := 0, m-1, 0, n-1 - for left <= right && top <= bottom { - for i := left; i <= right; i++ { - ans = append(ans, matrix[top][i]) - } - for i := top + 1; i <= bottom; i++ { - ans = append(ans, matrix[i][right]) - } - if left < right && top < bottom { - for i := right - 1; i >= left; i-- { - ans = append(ans, matrix[bottom][i]) - } - for i := bottom - 1; i > top; i-- { - ans = append(ans, matrix[i][left]) - } - } - top++ - bottom-- - left++ - right-- - } +```ts +var spiralOrder = (matrix: number[][]): number[] => { + let ans: number[] = []; + if (matrix.length === 0) return ans; + let top = 0, + left = 0, + bottom = matrix.length - 1, + right = matrix[0].length - 1; + while (true) { + for (let i = left; i <= right; i++) ans.push(matrix[top][i]); + top++; + if (top > bottom) break; + for (let i = top; i <= bottom; i++) ans.push(matrix[i][right]); + right--; + if (right < left) break; + for (let i = right; i >= left; i--) ans.push(matrix[bottom][i]); + bottom--; + if (bottom < top) break; + for (let i = bottom; i >= top; i--) ans.push(matrix[i][left]); + left++; + if (left > right) break; + } + return ans; +}; +``` - return ans +```rust +impl Solution { + pub fn spiral_order(matrix: Vec>) -> Vec { + let mut ans = Vec::new(); + if matrix.len() == 0 { + return ans; + } + let (mut left, mut right, mut top, mut bottom) = ( + 0, + matrix[0].len() - 1, + 0, + matrix.len() - 1, + ); + loop { + for i in left..right + 1 { + ans.push(matrix[top][i]); + } + top += 1; + if (top as i32) > (bottom as i32) { + break; + } + for i in top..bottom + 1 { + ans.push(matrix[i][right]); + } + right -= 1; + if (right as i32) < (left as i32) { + break; + } + for i in (left..right + 1).rev() { + ans.push(matrix[bottom][i]); + } + bottom -= 1; + if (bottom as i32) < (top as i32) { + break; + } + for i in (top..bottom + 1).rev() { + ans.push(matrix[i][left]); + } + left += 1; + if (left as i32) > (right as i32) { + break; + } + } + ans + } } ``` -### **JavaScript** - ```js /** * @param {number[][]} matrix @@ -309,8 +253,6 @@ var spiralOrder = function (matrix) { }; ``` -### **C#** - ```cs public class Solution { public int[] SpiralOrder(int[][] matrix) { @@ -354,10 +296,130 @@ public class Solution { } ``` -### **...** + + +### 方法二:逐层模拟 + +从外往里一圈一圈遍历并存储矩阵元素即可。 + +时间复杂度 $O(m \times n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。 + + + +```python +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + if not matrix or not matrix[0]: + return [] + m, n = len(matrix), len(matrix[0]) + ans = [] + top, bottom, left, right = 0, m - 1, 0, n - 1 + while left <= right and top <= bottom: + ans.extend([matrix[top][j] for j in range(left, right + 1)]) + ans.extend([matrix[i][right] for i in range(top + 1, bottom + 1)]) + if left < right and top < bottom: + ans.extend([matrix[bottom][j] for j in range(right - 1, left - 1, -1)]) + ans.extend([matrix[i][left] for i in range(bottom - 1, top, -1)]) + top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1 + return ans +``` + +```java +class Solution { + public int[] spiralOrder(int[][] matrix) { + if (matrix.length == 0 || matrix[0].length == 0) { + return new int[] {}; + } + int m = matrix.length, n = matrix[0].length; + int top = 0, bottom = m - 1, left = 0, right = n - 1; + int[] ans = new int[m * n]; + int k = 0; + while (left <= right && top <= bottom) { + for (int j = left; j <= right; ++j) { + ans[k++] = matrix[top][j]; + } + for (int i = top + 1; i <= bottom; ++i) { + ans[k++] = matrix[i][right]; + } + if (left < right && top < bottom) { + for (int j = right - 1; j >= left; --j) { + ans[k++] = matrix[bottom][j]; + } + for (int i = bottom - 1; i > top; --i) { + ans[k++] = matrix[i][left]; + } + } + ++top; + --bottom; + ++left; + --right; + } + return ans; + } +} +``` +```cpp +class Solution { +public: + vector spiralOrder(vector>& matrix) { + if (matrix.size() == 0 || matrix[0].size() == 0) { + return {}; + } + int m = matrix.size(), n = matrix[0].size(); + int top = 0, bottom = m - 1, left = 0, right = n - 1; + vector ans; + while (top <= bottom && left <= right) { + for (int j = left; j <= right; ++j) ans.push_back(matrix[top][j]); + for (int i = top + 1; i <= bottom; ++i) ans.push_back(matrix[i][right]); + if (left < right && top < bottom) { + for (int j = right - 1; j >= left; --j) ans.push_back(matrix[bottom][j]); + for (int i = bottom - 1; i > top; --i) ans.push_back(matrix[i][left]); + } + ++top; + --bottom; + ++left; + --right; + } + return ans; + } +}; ``` +```go +func spiralOrder(matrix [][]int) []int { + if len(matrix) == 0 || len(matrix[0]) == 0 { + return []int{} + } + m, n := len(matrix), len(matrix[0]) + ans := make([]int, 0, m*n) + + top, bottom, left, right := 0, m-1, 0, n-1 + for left <= right && top <= bottom { + for i := left; i <= right; i++ { + ans = append(ans, matrix[top][i]) + } + for i := top + 1; i <= bottom; i++ { + ans = append(ans, matrix[i][right]) + } + if left < right && top < bottom { + for i := right - 1; i >= left; i-- { + ans = append(ans, matrix[bottom][i]) + } + for i := bottom - 1; i > top; i-- { + ans = append(ans, matrix[i][left]) + } + } + top++ + bottom-- + left++ + right-- + } + + return ans +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23030. \345\214\205\345\220\253min\345\207\275\346\225\260\347\232\204\346\240\210/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23030. \345\214\205\345\220\253min\345\207\275\346\225\260\347\232\204\346\240\210/README.md" index ea339d7be34ec..e0d41cb986b16 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23030. \345\214\205\345\220\253min\345\207\275\346\225\260\347\232\204\346\240\210/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23030. \345\214\205\345\220\253min\345\207\275\346\225\260\347\232\204\346\240\210/README.md" @@ -340,4 +340,338 @@ public class MinStack { ``` +## 解法 + +### 方法一 + + + +```python +class MinStack: + def __init__(self): + self.stk1 = [] + self.stk2 = [inf] + + def push(self, x: int) -> None: + self.stk1.append(x) + self.stk2.append(min(x, self.stk2[-1])) + + def pop(self) -> None: + self.stk1.pop() + self.stk2.pop() + + def top(self) -> int: + return self.stk1[-1] + + def getMin(self) -> int: + return self.stk2[-1] + + +# Your MinStack object will be instantiated and called as such: +# obj = MinStack() +# obj.push(x) +# obj.pop() +# param_3 = obj.top() +# param_4 = obj.getMin() +``` + +```java +class MinStack { + private Deque stk1 = new ArrayDeque<>(); + private Deque stk2 = new ArrayDeque<>(); + + /** initialize your data structure here. */ + public MinStack() { + stk2.push(Integer.MAX_VALUE); + } + + public void push(int x) { + stk1.push(x); + stk2.push(Math.min(x, stk2.peek())); + } + + public void pop() { + stk1.pop(); + stk2.pop(); + } + + public int top() { + return stk1.peek(); + } + + public int getMin() { + return stk2.peek(); + } +} + +/** + * Your MinStack object will be instantiated and called as such: + * MinStack obj = new MinStack(); + * obj.push(x); + * obj.pop(); + * int param_3 = obj.top(); + * int param_4 = obj.getMin(); + */ +``` + +```cpp +class MinStack { +public: + /** initialize your data structure here. */ + MinStack() { + stk2.push(INT_MAX); + } + + void push(int x) { + stk1.push(x); + stk2.push(min(x, stk2.top())); + } + + void pop() { + stk1.pop(); + stk2.pop(); + } + + int top() { + return stk1.top(); + } + + int getMin() { + return stk2.top(); + } + +private: + stack stk1; + stack stk2; +}; + +/** + * Your MinStack object will be instantiated and called as such: + * MinStack* obj = new MinStack(); + * obj->push(x); + * obj->pop(); + * int param_3 = obj->top(); + * int param_4 = obj->getMin(); + */ +``` + +```go +type MinStack struct { + stk1 []int + stk2 []int +} + +/** initialize your data structure here. */ +func Constructor() MinStack { + return MinStack{[]int{}, []int{math.MaxInt32}} +} + +func (this *MinStack) Push(x int) { + this.stk1 = append(this.stk1, x) + this.stk2 = append(this.stk2, min(x, this.stk2[len(this.stk2)-1])) +} + +func (this *MinStack) Pop() { + this.stk1 = this.stk1[:len(this.stk1)-1] + this.stk2 = this.stk2[:len(this.stk2)-1] +} + +func (this *MinStack) Top() int { + return this.stk1[len(this.stk1)-1] +} + +func (this *MinStack) GetMin() int { + return this.stk2[len(this.stk2)-1] +} + +/** + * Your MinStack object will be instantiated and called as such: + * obj := Constructor(); + * obj.Push(x); + * obj.Pop(); + * param_3 := obj.Top(); + * param_4 := obj.GetMin(); + */ +``` + +```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; +struct MinStack { + stack: VecDeque, + min_stack: VecDeque, +} + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl MinStack { + /** initialize your data structure here. */ + fn new() -> Self { + Self { stack: VecDeque::new(), min_stack: VecDeque::new() } + } + + fn push(&mut self, x: i32) { + self.stack.push_back(x); + if self.min_stack.is_empty() || *self.min_stack.back().unwrap() >= x { + self.min_stack.push_back(x); + } + } + + fn pop(&mut self) { + let val = self.stack.pop_back().unwrap(); + if *self.min_stack.back().unwrap() == val { + self.min_stack.pop_back(); + } + } + + fn top(&self) -> i32 { + *self.stack.back().unwrap() + } + + fn get_min(&self) -> i32 { + *self.min_stack.back().unwrap() + } +}/** + * Your MinStack object will be instantiated and called as such: + * let obj = MinStack::new(); + * obj.push(x); + * obj.pop(); + * let ret_3: i32 = obj.top(); + * let ret_4: i32 = obj.get_min(); + */ +``` + +```js +/** + * initialize your data structure here. + */ +var MinStack = function () { + this.stack = []; + this.minStack = []; +}; + +/** + * @param {number} x + * @return {void} + */ +MinStack.prototype.push = function (x) { + this.stack.unshift(x); + if (!this.minStack.length || this.minStack[0] >= x) { + this.minStack.unshift(x); + } +}; + +/** + * @return {void} + */ +MinStack.prototype.pop = function () { + if (this.stack.shift() === this.minStack[0]) { + this.minStack.shift(); + } +}; + +/** + * @return {number} + */ +MinStack.prototype.top = function () { + return this.stack[0]; +}; + +/** + * @return {number} + */ +MinStack.prototype.min = function () { + return this.minStack[0]; +}; + +/** + * 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.min() + */ +``` + +```cs +public class MinStack { + private Stack stk1 = new Stack(); + private Stack stk2 = new Stack(); + + /** initialize your data structure here. */ + public MinStack() { + stk2.Push(int.MaxValue); + } + + public void Push(int x) { + stk1.Push(x); + stk2.Push(Math.Min(x, GetMin())); + } + + public void Pop() { + stk1.Pop(); + stk2.Pop(); + } + + public int Top() { + return stk1.Peek(); + } + + public int GetMin() { + return stk2.Peek(); + } +} + +/** + * Your MinStack object will be instantiated and called as such: + * MinStack obj = new MinStack(); + * obj.Push(x); + * obj.Pop(); + * int param_3 = obj.Top(); + * int param_4 = obj.GetMin(); + */ +``` + + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23031. \346\240\210\347\232\204\345\216\213\345\205\245\343\200\201\345\274\271\345\207\272\345\272\217\345\210\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23031. \346\240\210\347\232\204\345\216\213\345\205\245\343\200\201\345\274\271\345\207\272\345\272\217\345\210\227/README.md" index 28e7630bac40e..ba5445ba30dc1 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23031. \346\240\210\347\232\204\345\216\213\345\205\245\343\200\201\345\274\271\345\207\272\345\272\217\345\210\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23031. \346\240\210\347\232\204\345\216\213\345\205\245\343\200\201\345\274\271\345\207\272\345\272\217\345\210\227/README.md" @@ -38,9 +38,7 @@ push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 ## 解法 - - -**方法一:栈模拟** +### 方法一:栈模拟 遍历 `pushed` 序列,将每个数 `v` 依次压入栈中,压入后检查这个数是不是 `popped` 序列中下一个要弹出的值,如果是就循环把栈顶元素弹出。 @@ -50,10 +48,6 @@ push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 -### **Python3** - - - ```python class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: @@ -66,10 +60,6 @@ class Solution: return j == len(pushed) ``` -### **Java** - - - ```java class Solution { public boolean validateStackSequences(int[] pushed, int[] popped) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func validateStackSequences(pushed []int, popped []int) bool { stk := []int{} @@ -124,8 +110,6 @@ func validateStackSequences(pushed []int, popped []int) bool { } ``` -### **TypeScript** - ```ts function validateStackSequences(pushed: number[], popped: number[]): boolean { const stk = []; @@ -141,28 +125,6 @@ function validateStackSequences(pushed: number[], popped: number[]): boolean { } ``` -### **C#** - -```cs -public class Solution { - public bool ValidateStackSequences(int[] pushed, int[] popped) { - Stack stk = new Stack(); - int j = 0; - foreach (int x in pushed) - { - stk.Push(x); - while (stk.Count != 0 && stk.Peek() == popped[j]) { - stk.Pop(); - ++j; - } - } - return stk.Count == 0; - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn validate_stack_sequences(pushed: Vec, popped: Vec) -> bool { @@ -180,8 +142,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[]} pushed @@ -202,10 +162,24 @@ var validateStackSequences = function (pushed, popped) { }; ``` -### **...** - -``` - +```cs +public class Solution { + public bool ValidateStackSequences(int[] pushed, int[] popped) { + Stack stk = new Stack(); + int j = 0; + foreach (int x in pushed) + { + stk.Push(x); + while (stk.Count != 0 && stk.Peek() == popped[j]) { + stk.Pop(); + ++j; + } + } + return stk.Count == 0; + } +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23032 - I. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23032 - I. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221/README.md" index 9bdc3965adf9f..f13cda61e446a 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23032 - I. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23032 - I. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221/README.md" @@ -31,7 +31,7 @@ ## 解法 -**方法一:BFS** +### 方法一:BFS 我们可以通过 BFS 遍历二叉树,将每一层的节点值存入数组中,最后返回数组即可。 @@ -39,8 +39,6 @@ -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -67,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -108,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -146,8 +140,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -179,40 +171,6 @@ func levelOrder(root *TreeNode) (ans []int) { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} root - * @return {number[]} - */ -var levelOrder = function (root) { - if (!root) { - return []; - } - const q = [root]; - const ans = []; - while (q.length) { - for (let n = q.length; n; --n) { - const { val, left, right } = q.shift(); - ans.push(val); - left && q.push(left); - right && q.push(right); - } - } - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -244,8 +202,6 @@ function levelOrder(root: TreeNode | null): number[] { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -290,7 +246,35 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var levelOrder = function (root) { + if (!root) { + return []; + } + const q = [root]; + const ans = []; + while (q.length) { + for (let n = q.length; n; --n) { + const { val, left, right } = q.shift(); + ans.push(val); + left && q.push(left); + right && q.push(right); + } + } + return ans; +}; +``` ```cs /** @@ -328,10 +312,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23032 - II. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 II/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23032 - II. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 II/README.md" index b67b36d2e9d92..ff43108fde8fc 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23032 - II. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 II/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23032 - II. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 II/README.md" @@ -37,7 +37,7 @@ ## 解法 -**方法一:BFS** +### 方法一:BFS 我们可以使用 BFS 的方法来解决这道题。首先将根节点入队,然后不断地进行以下操作,直到队列为空: @@ -50,8 +50,6 @@ -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -80,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -119,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -153,8 +147,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -188,42 +180,6 @@ func levelOrder(root *TreeNode) (ans [][]int) { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} root - * @return {number[][]} - */ -var levelOrder = function (root) { - let ans = []; - if (!root) { - return ans; - } - let q = [root]; - while (q.length) { - let t = []; - for (let n = q.length; n; --n) { - const { val, left, right } = q.shift(); - t.push(val); - left && q.push(left); - right && q.push(right); - } - ans.push(t); - } - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -260,8 +216,6 @@ function levelOrder(root: TreeNode | null): number[][] { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -313,7 +267,37 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var levelOrder = function (root) { + let ans = []; + if (!root) { + return ans; + } + let q = [root]; + while (q.length) { + let t = []; + for (let n = q.length; n; --n) { + const { val, left, right } = q.shift(); + t.push(val); + left && q.push(left); + right && q.push(right); + } + ans.push(t); + } + return ans; +}; +``` ```cs /** @@ -353,10 +337,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23032 - III. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 III/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23032 - III. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 III/README.md" index b725af69660cb..a43c493b8f219 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23032 - III. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 III/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23032 - III. \344\273\216\344\270\212\345\210\260\344\270\213\346\211\223\345\215\260\344\272\214\345\217\211\346\240\221 III/README.md" @@ -35,7 +35,7 @@ ## 解法 -**方法一:BFS** +### 方法一:BFS 为了实现锯齿形层序遍历,我们每次将当前层的节点添加到结果数组之前,先判断一下当前结果数组的长度,如果是奇数,就将当前层的节点反转一下。之后把当前层的节点添加到结果数组中即可。 @@ -43,8 +43,6 @@ -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -74,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -116,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -159,8 +153,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -199,45 +191,6 @@ func levelOrder(root *TreeNode) (ans [][]int) { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} root - * @return {number[][]} - */ -var levelOrder = function (root) { - const ans = []; - if (!root) { - return ans; - } - const q = [root]; - while (q.length) { - const t = []; - for (let n = q.length; n; --n) { - const { val, left, right } = q.shift(); - t.push(val); - left && q.push(left); - right && q.push(right); - } - if (ans.length & 1) { - t.reverse(); - } - ans.push(t); - } - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -276,8 +229,6 @@ function levelOrder(root: TreeNode | null): number[][] { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -334,7 +285,40 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var levelOrder = function (root) { + const ans = []; + if (!root) { + return ans; + } + const q = [root]; + while (q.length) { + const t = []; + for (let n = q.length; n; --n) { + const { val, left, right } = q.shift(); + t.push(val); + left && q.push(left); + right && q.push(right); + } + if (ans.length & 1) { + t.reverse(); + } + ans.push(t); + } + return ans; +}; +``` ```cs /** @@ -376,10 +360,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/README.md" index 328d12b08cc95..b0f272850bb5a 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23033. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\345\220\216\345\272\217\351\201\215\345\216\206\345\272\217\345\210\227/README.md" @@ -36,39 +36,14 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 后序遍历的最后一个元素为根节点,根据二叉搜索树的性质,根节点左边的元素都小于根节点,根节点右边的元素都大于根节点。因此,我们找到第一个大于根节点的位置 $i$,那么 $i$ 右边的元素都应该大于根节点,否则返回 `false`。然后递归判断左右子树。 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。 -**方法二:单调栈** - -后序遍历的顺序为“左、右、根”,如果我们从右往左遍历数组,那么顺序就变成“根、右、左”,根据二叉搜索树的性质,右子树所有节点值均大于根节点值。 - -因此,从右往左遍历数组,就是从根节点往右子树走,此时值逐渐变大,直到遇到一个递减的节点,此时的节点应该属于左子树节点。我们找到该节点的直接父节点,那么此后其它节点都应该小于该父节点,否则返回 `false`。然后继续遍历,直到遍历完整个数组。 - -此过程,我们借助栈来实现,具体步骤如下: - -我们首先初始化一个无穷大的父节点值 $mx$,然后初始化一个空栈。 - -接下来,我们从右往左遍历数组,对于每个遍历到的元素 $x$: - -- 如果 $x$ 大于 $mx$,说明当前节点不满足二叉搜索树的性质,返回 `false`。 -- 否则,如果当前栈不为空,且栈顶元素大于 $x$,说明当前节点为左子树节点,我们循环将栈顶元素出栈并赋值给 $mx$,直到栈为空或者栈顶元素小于等于 $x$,然后将 $x$ 入栈。 - -遍历结束后,返回 `true`。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。 - -### **Python3** - - - ```python class Solution: def verifyPostorder(self, postorder: List[int]) -> bool: @@ -86,24 +61,6 @@ class Solution: return dfs(0, len(postorder) - 1) ``` -```python -class Solution: - def verifyPostorder(self, postorder: List[int]) -> bool: - mx = inf - stk = [] - for x in postorder[::-1]: - if x > mx: - return False - while stk and stk[-1] > x: - mx = stk.pop() - stk.append(x) - return True -``` - -### **Java** - - - ```java class Solution { private int[] postorder; @@ -132,28 +89,6 @@ class Solution { } ``` -```java -class Solution { - public boolean verifyPostorder(int[] postorder) { - int mx = 1 << 30; - Deque stk = new ArrayDeque<>(); - for (int i = postorder.length - 1; i >= 0; --i) { - int x = postorder[i]; - if (x > mx) { - return false; - } - while (!stk.isEmpty() && stk.peek() > x) { - mx = stk.pop(); - } - stk.push(x); - } - return true; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -179,30 +114,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool verifyPostorder(vector& postorder) { - stack stk; - int mx = 1 << 30; - reverse(postorder.begin(), postorder.end()); - for (int& x : postorder) { - if (x > mx) { - return false; - } - while (!stk.empty() && stk.top() > x) { - mx = stk.top(); - stk.pop(); - } - stk.push(x); - } - return true; - } -}; -``` - -### **Go** - ```go func verifyPostorder(postorder []int) bool { var dfs func(l, r int) bool @@ -226,77 +137,6 @@ func verifyPostorder(postorder []int) bool { } ``` -```go -func verifyPostorder(postorder []int) bool { - mx := 1 << 30 - stk := []int{} - for i := len(postorder) - 1; i >= 0; i-- { - x := postorder[i] - if x > mx { - return false - } - for len(stk) > 0 && stk[len(stk)-1] > x { - mx = stk[len(stk)-1] - stk = stk[:len(stk)-1] - } - stk = append(stk, x) - } - return true -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} postorder - * @return {boolean} - */ -var verifyPostorder = function (postorder) { - const dfs = (l, r) => { - if (l >= r) { - return true; - } - const v = postorder[r]; - let i = l; - while (i < r && postorder[i] < v) { - ++i; - } - for (let j = i; j < r; ++j) { - if (postorder[j] < v) { - return false; - } - } - return dfs(l, i - 1) && dfs(i, r - 1); - }; - return dfs(0, postorder.length - 1); -}; -``` - -```js -/** - * @param {number[]} postorder - * @return {boolean} - */ -var verifyPostorder = function (postorder) { - let mx = 1 << 30; - const stk = []; - for (let i = postorder.length - 1; i >= 0; --i) { - const x = postorder[i]; - if (x > mx) { - return false; - } - while (stk.length && stk[stk.length - 1] > x) { - mx = stk.pop(); - } - stk.push(x); - } - return true; -}; -``` - -### **TypeScript** - ```ts function verifyPostorder(postorder: number[]): boolean { const dfs = (l: number, r: number): boolean => { @@ -319,26 +159,6 @@ function verifyPostorder(postorder: number[]): boolean { } ``` -```ts -function verifyPostorder(postorder: number[]): boolean { - let mx = 1 << 30; - const stk: number[] = []; - for (let i = postorder.length - 1; i >= 0; --i) { - const x = postorder[i]; - if (x > mx) { - return false; - } - while (stk.length && stk[stk.length - 1] > x) { - mx = stk.pop(); - } - stk.push(x); - } - return true; -} -``` - -### **Rust** - ```rust impl Solution { fn dfs(start: usize, end: usize, max_val: i32, postorder: &Vec) -> bool { @@ -367,7 +187,31 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number[]} postorder + * @return {boolean} + */ +var verifyPostorder = function (postorder) { + const dfs = (l, r) => { + if (l >= r) { + return true; + } + const v = postorder[r]; + let i = l; + while (i < r && postorder[i] < v) { + ++i; + } + for (let j = i; j < r; ++j) { + if (postorder[j] < v) { + return false; + } + } + return dfs(l, i - 1) && dfs(i, r - 1); + }; + return dfs(0, postorder.length - 1); +}; +``` ```cs public class Solution { @@ -397,10 +241,144 @@ public class Solution { } ``` -### **...** + + +### 方法二:单调栈 + +后序遍历的顺序为“左、右、根”,如果我们从右往左遍历数组,那么顺序就变成“根、右、左”,根据二叉搜索树的性质,右子树所有节点值均大于根节点值。 + +因此,从右往左遍历数组,就是从根节点往右子树走,此时值逐渐变大,直到遇到一个递减的节点,此时的节点应该属于左子树节点。我们找到该节点的直接父节点,那么此后其它节点都应该小于该父节点,否则返回 `false`。然后继续遍历,直到遍历完整个数组。 + +此过程,我们借助栈来实现,具体步骤如下: + +我们首先初始化一个无穷大的父节点值 $mx$,然后初始化一个空栈。 + +接下来,我们从右往左遍历数组,对于每个遍历到的元素 $x$: + +- 如果 $x$ 大于 $mx$,说明当前节点不满足二叉搜索树的性质,返回 `false`。 +- 否则,如果当前栈不为空,且栈顶元素大于 $x$,说明当前节点为左子树节点,我们循环将栈顶元素出栈并赋值给 $mx$,直到栈为空或者栈顶元素小于等于 $x$,然后将 $x$ 入栈。 + +遍历结束后,返回 `true`。 +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。 + + + +```python +class Solution: + def verifyPostorder(self, postorder: List[int]) -> bool: + mx = inf + stk = [] + for x in postorder[::-1]: + if x > mx: + return False + while stk and stk[-1] > x: + mx = stk.pop() + stk.append(x) + return True ``` +```java +class Solution { + public boolean verifyPostorder(int[] postorder) { + int mx = 1 << 30; + Deque stk = new ArrayDeque<>(); + for (int i = postorder.length - 1; i >= 0; --i) { + int x = postorder[i]; + if (x > mx) { + return false; + } + while (!stk.isEmpty() && stk.peek() > x) { + mx = stk.pop(); + } + stk.push(x); + } + return true; + } +} +``` + +```cpp +class Solution { +public: + bool verifyPostorder(vector& postorder) { + stack stk; + int mx = 1 << 30; + reverse(postorder.begin(), postorder.end()); + for (int& x : postorder) { + if (x > mx) { + return false; + } + while (!stk.empty() && stk.top() > x) { + mx = stk.top(); + stk.pop(); + } + stk.push(x); + } + return true; + } +}; +``` + +```go +func verifyPostorder(postorder []int) bool { + mx := 1 << 30 + stk := []int{} + for i := len(postorder) - 1; i >= 0; i-- { + x := postorder[i] + if x > mx { + return false + } + for len(stk) > 0 && stk[len(stk)-1] > x { + mx = stk[len(stk)-1] + stk = stk[:len(stk)-1] + } + stk = append(stk, x) + } + return true +} +``` + +```ts +function verifyPostorder(postorder: number[]): boolean { + let mx = 1 << 30; + const stk: number[] = []; + for (let i = postorder.length - 1; i >= 0; --i) { + const x = postorder[i]; + if (x > mx) { + return false; + } + while (stk.length && stk[stk.length - 1] > x) { + mx = stk.pop(); + } + stk.push(x); + } + return true; +} +``` + +```js +/** + * @param {number[]} postorder + * @return {boolean} + */ +var verifyPostorder = function (postorder) { + let mx = 1 << 30; + const stk = []; + for (let i = postorder.length - 1; i >= 0; --i) { + const x = postorder[i]; + if (x > mx) { + return false; + } + while (stk.length && stk[stk.length - 1] > x) { + mx = stk.pop(); + } + stk.push(x); + } + return true; +}; ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23034. \344\272\214\345\217\211\346\240\221\344\270\255\345\222\214\344\270\272\346\237\220\344\270\200\345\200\274\347\232\204\350\267\257\345\276\204/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23034. \344\272\214\345\217\211\346\240\221\344\270\255\345\222\214\344\270\272\346\237\220\344\270\200\345\200\274\347\232\204\350\267\257\345\276\204/README.md" index 3d7bfb705ffb3..c523e507a2045 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23034. \344\272\214\345\217\211\346\240\221\344\270\255\345\222\214\344\270\272\346\237\220\344\270\200\345\200\274\347\232\204\350\267\257\345\276\204/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23034. \344\272\214\345\217\211\346\240\221\344\270\255\345\222\214\344\270\272\346\237\220\344\270\200\345\200\274\347\232\204\350\267\257\345\276\204/README.md" @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 从根节点开始,递归遍历每个节点,每次递归时,将当前节点值加入到路径中,然后判断当前节点是否为叶子节点,如果是叶子节点并且路径和等于目标值,则将该路径加入到结果中。如果当前节点不是叶子节点,则递归遍历其左右子节点。递归遍历时,需要将当前节点从路径中移除,以确保返回父节点时路径刚好是从根节点到父节点。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -134,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -172,8 +160,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -204,45 +190,6 @@ func pathSum(root *TreeNode, target int) (ans [][]int) { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @param {number} target - * @return {number[][]} - */ -var pathSum = function (root, target) { - const ans = []; - const t = []; - const dfs = (root, s) => { - if (!root) { - return; - } - t.push(root.val); - s -= root.val; - if (!root.left && !root.right && !s) { - ans.push([...t]); - } - dfs(root.left, s); - dfs(root.right, s); - t.pop(); - }; - dfs(root, target); - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -282,8 +229,6 @@ function pathSum(root: TreeNode | null, target: number): number[][] { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -333,6 +278,86 @@ impl Solution { } ``` +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} target + * @return {number[][]} + */ +var pathSum = function (root, target) { + const ans = []; + const t = []; + const dfs = (root, s) => { + if (!root) { + return; + } + t.push(root.val); + s -= root.val; + if (!root.left && !root.right && !s) { + ans.push([...t]); + } + dfs(root.left, s); + dfs(root.right, s); + t.pop(); + }; + dfs(root, target); + return ans; +}; +``` + +```cs +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + private List> ans = new List>(); + private List t = new List(); + + public IList> PathSum(TreeNode root, int target) { + dfs(root, target); + return ans; + } + + private void dfs(TreeNode root, int s) { + if (root == null) { + return; + } + t.Add(root.val); + s -= root.val; + if (root.left == null && root.right == null && s == 0) { + ans.Add(new List(t)); + } + dfs(root.left, s); + dfs(root.right, s); + t.RemoveAt(t.Count - 1); + } +} +``` + + + +### 方法二 + + + ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -395,51 +420,6 @@ impl Solution { } ``` -### **C#** - -```cs -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -public class Solution { - private List> ans = new List>(); - private List t = new List(); - - public IList> PathSum(TreeNode root, int target) { - dfs(root, target); - return ans; - } - - private void dfs(TreeNode root, int s) { - if (root == null) { - return; - } - t.Add(root.val); - s -= root.val; - if (root.left == null && root.right == null && s == 0) { - ans.Add(new List(t)); - } - dfs(root.left, s); - dfs(root.right, s); - t.RemoveAt(t.Count - 1); - } -} -``` - -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/README.md" index af6103db4fef3..5d1394bd8dac9 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23035. \345\244\215\346\235\202\351\223\276\350\241\250\347\232\204\345\244\215\345\210\266/README.md" @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 遍历链表,将链表中的每个节点都复制一份,然后将原节点和复制节点的对应关系存储在哈希表中,同时连接好复制节点的 $next$ 指针。 @@ -67,22 +65,8 @@ 时间复杂度为 $O(n)$,空间复杂度为 $O(n)$。其中 $n$ 为链表的长度。 -**方法二:拼接 + 拆分** - -遍历链表,将链表中的每个节点都复制一份,然后将复制节点插入到原节点的后面。 - -接下来再遍历链表,根据原节点的 $random$ 指针,将复制节点的 $random$ 指针连接好。 - -最后再遍历链表,将链表拆分成原链表和复制链表。 - -时间复杂度为 $O(n)$,空间复杂度为 $O(1)$。其中 $n$ 为链表的长度。 - -### **Python3** - - - ```python """ # Definition for a Node. @@ -113,47 +97,6 @@ class Solution: return dummy.next ``` -```python -""" -# Definition for a Node. -class Node: - def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): - self.val = int(x) - self.next = next - self.random = random -""" - - -class Solution: - def copyRandomList(self, head: "Node") -> "Node": - if head is None: - return None - cur = head - while cur: - node = Node(cur.val, cur.next) - cur.next = node - cur = node.next - - cur = head - while cur: - if cur.random: - cur.next.random = cur.random.next - cur = cur.next.next - - ans = head.next - cur = head - while cur: - nxt = cur.next - if nxt: - cur.next = nxt.next - cur = nxt - return ans -``` - -### **Java** - - - ```java /* // Definition for a Node. @@ -189,51 +132,6 @@ class Solution { } ``` -```java -/* -// Definition for a Node. -class Node { - int val; - Node next; - Node random; - - public Node(int val) { - this.val = val; - this.next = null; - this.random = null; - } -} -*/ -class Solution { - public Node copyRandomList(Node head) { - if (head == null) { - return null; - } - for (Node cur = head; cur != null;) { - Node node = new Node(cur.val, cur.next); - cur.next = node; - cur = node.next; - } - for (Node cur = head; cur != null; cur = cur.next.next) { - if (cur.random != null) { - cur.next.random = cur.random.next; - } - } - Node ans = head.next; - for (Node cur = head; cur != null;) { - Node nxt = cur.next; - if (nxt != null) { - cur.next = nxt.next; - } - cur = nxt; - } - return ans; - } -} -``` - -### **C++** - ```cpp /* // Definition for a Node. @@ -271,54 +169,6 @@ public: }; ``` -```cpp -/* -// Definition for a Node. -class Node { -public: - int val; - Node* next; - Node* random; - - Node(int _val) { - val = _val; - next = NULL; - random = NULL; - } -}; -*/ -class Solution { -public: - Node* copyRandomList(Node* head) { - if (!head) { - return nullptr; - } - for (Node* cur = head; cur;) { - Node* node = new Node(cur->val); - node->next = cur->next; - cur->next = node; - cur = node->next; - } - for (Node* cur = head; cur; cur = cur->next->next) { - if (cur->random) { - cur->next->random = cur->random->next; - } - } - Node* ans = head->next; - for (Node* cur = head; cur;) { - Node* nxt = cur->next; - if (nxt) { - cur->next = nxt->next; - } - cur = nxt; - } - return ans; - } -}; -``` - -### **Go** - ```go /** * Definition for a Node. @@ -347,44 +197,38 @@ func copyRandomList(head *Node) *Node { } ``` -```go +```js /** - * Definition for a Node. - * type Node struct { - * Val int - * Next *Node - * Random *Node - * } + * // Definition for a Node. + * function Node(val, next, random) { + * this.val = val; + * this.next = next; + * this.random = random; + * }; */ -func copyRandomList(head *Node) *Node { - if head == nil { - return nil - } - for cur := head; cur != nil; { - node := &Node{cur.Val, cur.Next, nil} - cur.Next = node - cur = node.Next - } - for cur := head; cur != nil; cur = cur.Next.Next { - if cur.Random != nil { - cur.Next.Random = cur.Random.Next - } - } - ans := head.Next - for cur := head; cur != nil; { - nxt := cur.Next - if nxt != nil { - cur.Next = nxt.Next - } - cur = nxt - } - return ans -} +/** + * @param {Node} head + * @return {Node} + */ +var copyRandomList = function (head) { + const d = new Map(); + const dummy = new Node(0); + let tail = dummy; + for (let cur = head; cur; cur = cur.next) { + tail.next = new Node(cur.val); + tail = tail.next; + d.set(cur, tail); + } + tail = dummy.next; + for (let cur = head; cur; cur = cur.next) { + tail.random = d.get(cur.random); + tail = tail.next; + } + return dummy.next; +}; ``` -### **C#** - ```cs /* // Definition for a Node. @@ -421,28 +265,78 @@ public class Solution { } ``` -```cs + + +### 方法二:拼接 + 拆分 + +遍历链表,将链表中的每个节点都复制一份,然后将复制节点插入到原节点的后面。 + +接下来再遍历链表,根据原节点的 $random$ 指针,将复制节点的 $random$ 指针连接好。 + +最后再遍历链表,将链表拆分成原链表和复制链表。 + +时间复杂度为 $O(n)$,空间复杂度为 $O(1)$。其中 $n$ 为链表的长度。 + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): + self.val = int(x) + self.next = next + self.random = random +""" + + +class Solution: + def copyRandomList(self, head: "Node") -> "Node": + if head is None: + return None + cur = head + while cur: + node = Node(cur.val, cur.next) + cur.next = node + cur = node.next + + cur = head + while cur: + if cur.random: + cur.next.random = cur.random.next + cur = cur.next.next + + ans = head.next + cur = head + while cur: + nxt = cur.next + if nxt: + cur.next = nxt.next + cur = nxt + return ans +``` + +```java /* // Definition for a Node. -public class Node { - public int val; - public Node next; - public Node random; +class Node { + int val; + Node next; + Node random; - public Node(int _val) { - val = _val; - next = null; - random = null; + public Node(int val) { + this.val = val; + this.next = null; + this.random = null; } } */ - -public class Solution { - public Node CopyRandomList(Node head) { +class Solution { + public Node copyRandomList(Node head) { if (head == null) { return null; } - for (Node cur = head; cur != null; ) { + for (Node cur = head; cur != null;) { Node node = new Node(cur.val, cur.next); cur.next = node; cur = node.next; @@ -453,7 +347,7 @@ public class Solution { } } Node ans = head.next; - for (Node cur = head; cur != null; ) { + for (Node cur = head; cur != null;) { Node nxt = cur.next; if (nxt != null) { cur.next = nxt.next; @@ -465,40 +359,88 @@ public class Solution { } ``` -### **JavaScript** - -```js -/** - * // Definition for a Node. - * function Node(val, next, random) { - * this.val = val; - * this.next = next; - * this.random = random; - * }; - */ +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + Node* random; -/** - * @param {Node} head - * @return {Node} - */ -var copyRandomList = function (head) { - const d = new Map(); - const dummy = new Node(0); - let tail = dummy; - for (let cur = head; cur; cur = cur.next) { - tail.next = new Node(cur.val); - tail = tail.next; - d.set(cur, tail); + Node(int _val) { + val = _val; + next = NULL; + random = NULL; } - tail = dummy.next; - for (let cur = head; cur; cur = cur.next) { - tail.random = d.get(cur.random); - tail = tail.next; +}; +*/ +class Solution { +public: + Node* copyRandomList(Node* head) { + if (!head) { + return nullptr; + } + for (Node* cur = head; cur;) { + Node* node = new Node(cur->val); + node->next = cur->next; + cur->next = node; + cur = node->next; + } + for (Node* cur = head; cur; cur = cur->next->next) { + if (cur->random) { + cur->next->random = cur->random->next; + } + } + Node* ans = head->next; + for (Node* cur = head; cur;) { + Node* nxt = cur->next; + if (nxt) { + cur->next = nxt->next; + } + cur = nxt; + } + return ans; } - return dummy.next; }; ``` +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Next *Node + * Random *Node + * } + */ + +func copyRandomList(head *Node) *Node { + if head == nil { + return nil + } + for cur := head; cur != nil; { + node := &Node{cur.Val, cur.Next, nil} + cur.Next = node + cur = node.Next + } + for cur := head; cur != nil; cur = cur.Next.Next { + if cur.Random != nil { + cur.Next.Random = cur.Random.Next + } + } + ans := head.Next + for cur := head; cur != nil; { + nxt := cur.Next + if nxt != nil { + cur.Next = nxt.Next + } + cur = nxt + } + return ans +} +``` + ```js /** * // Definition for a Node. @@ -539,10 +481,50 @@ var copyRandomList = function (head) { }; ``` -### **...** +```cs +/* +// Definition for a Node. +public class Node { + public int val; + public Node next; + public Node random; -``` + public Node(int _val) { + val = _val; + next = null; + random = null; + } +} +*/ +public class Solution { + public Node CopyRandomList(Node head) { + if (head == null) { + return null; + } + for (Node cur = head; cur != null; ) { + Node node = new Node(cur.val, cur.next); + cur.next = node; + cur = node.next; + } + for (Node cur = head; cur != null; cur = cur.next.next) { + if (cur.random != null) { + cur.next.random = cur.random.next; + } + } + Node ans = head.next; + for (Node cur = head; cur != null; ) { + Node nxt = cur.next; + if (nxt != null) { + cur.next = nxt.next; + } + cur = nxt; + } + return ans; + } +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23036. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\216\345\217\214\345\220\221\351\223\276\350\241\250/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23036. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\216\345\217\214\345\220\221\351\223\276\350\241\250/README.md" index d1637e2a42888..fceb44f3789d3 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23036. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\216\345\217\214\345\220\221\351\223\276\350\241\250/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23036. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\216\345\217\214\345\220\221\351\223\276\350\241\250/README.md" @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:中序遍历** +### 方法一:中序遍历 二叉搜索树的中序遍历是有序序列,因此可以通过中序遍历得到有序序列,过程中构建双向链表。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python """ # Definition for a Node. @@ -87,10 +81,6 @@ class Solution: return head ``` -### **Java** - - - ```java /* // Definition for a Node. @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -200,8 +188,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -239,8 +225,6 @@ func treeToDoublyList(root *Node) *Node { } ``` -### **JavaScript** - ```js /** * // Definition for a Node. @@ -281,8 +265,6 @@ var treeToDoublyList = function (root) { }; ``` -### **C#** - ```cs /* // Definition for a Node. @@ -338,10 +320,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/README.md" index 3fe7e7918efb2..f391c401dfcee 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23037. \345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/README.md" @@ -25,9 +25,7 @@ ## 解法 - - -**方法一:层序遍历** +### 方法一:层序遍历 我们可以采用层序遍历的方式对二叉树进行序列化,即从根节点开始,依次将二叉树的节点按照从上到下、从左到右的顺序加入队列中,然后将队列中的节点依次出队。如果节点不为空,则将其值加入序列化字符串中,否则加入特殊字符 `#`。最后将序列化字符串返回即可。 @@ -35,26 +33,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。 -**方法二:前序遍历** - -当二叉树的前中后序列不包含叶子节点时需要前中、前后、中后三种组合方式之一才能确定一颗二叉树,但当前序和后序遍历序列中包含叶子节点时,可以仅通过前序或后序遍历序列构建一颗二叉树。 - -在前序遍历序列化时,我们以任意特殊字符表示叶子节点,返回序列化后的字符串;反序列化时对序列化字符串根据分隔符进行切分后使用列表的第一个元素作为二叉树的根节点,然后利用列表的其他元素递归生成左右子树即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。 - -**方法三:后序遍历** - -在后序遍历序列化时,我们以任意特殊字符表示叶子节点,返回序列化后的字符串;反序列化时对序列化字符串根据分隔符进行切分后使用列表的最后一个元素作为二叉树的根节点,然后利用列表的其他元素递归生成左右子树即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode(object): @@ -115,10 +95,6 @@ class Codec: # codec.deserialize(codec.serialize(root)) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -184,8 +160,6 @@ public class Codec { // codec.deserialize(codec.serialize(root)); ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -253,116 +227,6 @@ public: // codec.deserialize(codec.serialize(root)); ``` -```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 Codec { -public: - string empty = "#"; - string sep = ","; - // Encodes a tree to a single string. - string serialize(TreeNode* root) { - if (!root) return empty + sep; - string res = to_string(root->val) + sep; - res += serialize(root->left); - res += serialize(root->right); - return res; - } - - // Decodes your encoded data to tree. - TreeNode* deserialize(string data) { - list nodes; - size_t pos = 0; - string node; - while ((pos = data.find(sep)) != string::npos) { - node = data.substr(0, pos); - nodes.push_back(node); - data.erase(0, pos + sep.length()); - } - return deserialize(nodes); - } - - TreeNode* deserialize(list& data) { - if (data.empty()) return nullptr; - string first = data.front(); - data.pop_front(); - if (first == empty) return nullptr; - TreeNode* root = new TreeNode(stoi(first)); - root->left = deserialize(data); - root->right = deserialize(data); - return root; - } -}; - -// Your Codec object will be instantiated and called as such: -// Codec codec; -// codec.deserialize(codec.serialize(root)); -``` - -```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 Codec { -public: - string empty = "#"; - string sep = ","; - // Encodes a tree to a single string. - string serialize(TreeNode* root) { - if (!root) return empty + sep; - string res = ""; - res += serialize(root->left); - res += serialize(root->right); - res += to_string(root->val) + sep; - return res; - } - - // Decodes your encoded data to tree. - TreeNode* deserialize(string data) { - vector nodes; - size_t pos = 0; - string node; - while ((pos = data.find(sep)) != string::npos) { - node = data.substr(0, pos); - nodes.push_back(node); - data.erase(0, pos + sep.length()); - } - return deserialize(nodes); - } - - TreeNode* deserialize(vector& nodes) { - if (nodes.empty()) return nullptr; - string front = nodes.back(); - nodes.pop_back(); - if (front == empty) return nullptr; - TreeNode* root = new TreeNode(stoi(front)); - // 先构造右子树,后构造左子树 - root->right = deserialize(nodes); - root->left = deserialize(nodes); - return root; - } -}; - -// Your Codec object will be instantiated and called as such: -// Codec codec; -// codec.deserialize(codec.serialize(root)); -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -437,8 +301,6 @@ func (this *Codec) deserialize(data string) *TreeNode { */ ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -504,6 +366,123 @@ var deserialize = function (data) { */ ``` +```cs +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ +public class Codec { + public string serialize(TreeNode root) { + return rserialize(root, ""); + } + + public TreeNode deserialize(string data) { + string[] dataArray = data.Split(","); + LinkedList dataList = new LinkedList(dataArray.ToList()); + return rdeserialize(dataList); + } + + public string rserialize(TreeNode root, string str) { + if (root == null) { + str += "None,"; + } else { + str += root.val.ToString() + ","; + str = rserialize(root.left, str); + str = rserialize(root.right, str); + } + return str; + } + + public TreeNode rdeserialize(LinkedList dataList) { + if (dataList.First.Value.Equals("None")) { + dataList.RemoveFirst(); + return null; + } + + TreeNode root = new TreeNode(int.Parse(dataList.First.Value)); + dataList.RemoveFirst(); + root.left = rdeserialize(dataList); + root.right = rdeserialize(dataList); + + return root; + } +} + +// Your Codec object will be instantiated and called as such: +// Codec codec = new Codec(); +// codec.deserialize(codec.serialize(root)); +``` + + + +### 方法二:前序遍历 + +当二叉树的前中后序列不包含叶子节点时需要前中、前后、中后三种组合方式之一才能确定一颗二叉树,但当前序和后序遍历序列中包含叶子节点时,可以仅通过前序或后序遍历序列构建一颗二叉树。 + +在前序遍历序列化时,我们以任意特殊字符表示叶子节点,返回序列化后的字符串;反序列化时对序列化字符串根据分隔符进行切分后使用列表的第一个元素作为二叉树的根节点,然后利用列表的其他元素递归生成左右子树即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。 + + + +```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 Codec { +public: + string empty = "#"; + string sep = ","; + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + if (!root) return empty + sep; + string res = to_string(root->val) + sep; + res += serialize(root->left); + res += serialize(root->right); + return res; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + list nodes; + size_t pos = 0; + string node; + while ((pos = data.find(sep)) != string::npos) { + node = data.substr(0, pos); + nodes.push_back(node); + data.erase(0, pos + sep.length()); + } + return deserialize(nodes); + } + + TreeNode* deserialize(list& data) { + if (data.empty()) return nullptr; + string first = data.front(); + data.pop_front(); + if (first == empty) return nullptr; + TreeNode* root = new TreeNode(stoi(first)); + root->left = deserialize(data); + root->right = deserialize(data); + return root; + } +}; + +// Your Codec object will be instantiated and called as such: +// Codec codec; +// codec.deserialize(codec.serialize(root)); +``` + ```js /** * Definition for a binary tree node. @@ -555,64 +534,71 @@ var deserialize = function (data) { */ ``` -### **C#** + -```cs +### 方法三:后序遍历 + +在后序遍历序列化时,我们以任意特殊字符表示叶子节点,返回序列化后的字符串;反序列化时对序列化字符串根据分隔符进行切分后使用列表的最后一个元素作为二叉树的根节点,然后利用列表的其他元素递归生成左右子树即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。 + + + +```cpp /** * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int x) { val = x; } - * } + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; */ -public class Codec { - public string serialize(TreeNode root) { - return rserialize(root, ""); - } - - public TreeNode deserialize(string data) { - string[] dataArray = data.Split(","); - LinkedList dataList = new LinkedList(dataArray.ToList()); - return rdeserialize(dataList); +class Codec { +public: + string empty = "#"; + string sep = ","; + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + if (!root) return empty + sep; + string res = ""; + res += serialize(root->left); + res += serialize(root->right); + res += to_string(root->val) + sep; + return res; } - public string rserialize(TreeNode root, string str) { - if (root == null) { - str += "None,"; - } else { - str += root.val.ToString() + ","; - str = rserialize(root.left, str); - str = rserialize(root.right, str); + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + vector nodes; + size_t pos = 0; + string node; + while ((pos = data.find(sep)) != string::npos) { + node = data.substr(0, pos); + nodes.push_back(node); + data.erase(0, pos + sep.length()); } - return str; + return deserialize(nodes); } - public TreeNode rdeserialize(LinkedList dataList) { - if (dataList.First.Value.Equals("None")) { - dataList.RemoveFirst(); - return null; - } - - TreeNode root = new TreeNode(int.Parse(dataList.First.Value)); - dataList.RemoveFirst(); - root.left = rdeserialize(dataList); - root.right = rdeserialize(dataList); - + TreeNode* deserialize(vector& nodes) { + if (nodes.empty()) return nullptr; + string front = nodes.back(); + nodes.pop_back(); + if (front == empty) return nullptr; + TreeNode* root = new TreeNode(stoi(front)); + // 先构造右子树,后构造左子树 + root->right = deserialize(nodes); + root->left = deserialize(nodes); return root; } -} +}; // Your Codec object will be instantiated and called as such: -// Codec codec = new Codec(); +// Codec codec; // codec.deserialize(codec.serialize(root)); ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23038. \345\255\227\347\254\246\344\270\262\347\232\204\346\216\222\345\210\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23038. \345\255\227\347\254\246\344\270\262\347\232\204\346\216\222\345\210\227/README.md" index dcf1c4360994e..24f56dfd762a4 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23038. \345\255\227\347\254\246\344\270\262\347\232\204\346\216\222\345\210\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23038. \345\255\227\347\254\246\344\270\262\347\232\204\346\216\222\345\210\227/README.md" @@ -26,9 +26,7 @@ ## 解法 - - -**方法一:回溯 + 哈希表** +### 方法一:回溯 + 哈希表 我们设计一个函数 $dfs(i)$,表示当前排列到了第 $i$ 个位置,我们需要在第 $i$ 个位置上填入一个字符,这个字符可以从 $s[i..n-1]$ 中任意选择。 @@ -45,10 +43,6 @@ -### **Python3** - - - ```python class Solution: def permutation(self, s: str) -> List[str]: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List ans = new ArrayList<>(); @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func permutation(s string) (ans []string) { cs := []byte(s) @@ -162,39 +148,6 @@ func permutation(s string) (ans []string) { } ``` -### **JavaScript** - -```js -/** - * @param {string} s - * @return {string[]} - */ -var permutation = function (s) { - const cs = s.split(''); - const ans = []; - const n = s.length; - const dfs = i => { - if (i == n - 1) { - ans.push(cs.join('')); - return; - } - const vis = new Set(); - for (let j = i; j < n; ++j) { - if (!vis.has(cs[j])) { - vis.add(cs[j]); - [cs[i], cs[j]] = [cs[j], cs[i]]; - dfs(i + 1); - [cs[i], cs[j]] = [cs[j], cs[i]]; - } - } - }; - dfs(0); - return ans; -}; -``` - -### **TypeScript** - ```ts function permutation(s: string): string[] { const n = s.length; @@ -217,8 +170,6 @@ function permutation(s: string): string[] { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -247,7 +198,34 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {string} s + * @return {string[]} + */ +var permutation = function (s) { + const cs = s.split(''); + const ans = []; + const n = s.length; + const dfs = i => { + if (i == n - 1) { + ans.push(cs.join('')); + return; + } + const vis = new Set(); + for (let j = i; j < n; ++j) { + if (!vis.has(cs[j])) { + vis.add(cs[j]); + [cs[i], cs[j]] = [cs[j], cs[i]]; + dfs(i + 1); + [cs[i], cs[j]] = [cs[j], cs[i]]; + } + } + }; + dfs(0); + return ans; +}; +``` ```cs public class Solution { @@ -278,3 +256,5 @@ public class Solution { ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23039. \346\225\260\347\273\204\344\270\255\345\207\272\347\216\260\346\254\241\346\225\260\350\266\205\350\277\207\344\270\200\345\215\212\347\232\204\346\225\260\345\255\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23039. \346\225\260\347\273\204\344\270\255\345\207\272\347\216\260\346\254\241\346\225\260\350\266\205\350\277\207\344\270\200\345\215\212\347\232\204\346\225\260\345\255\227/README.md" index 1ae7e519cd5c9..1353732ce2544 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23039. \346\225\260\347\273\204\344\270\255\345\207\272\347\216\260\346\254\241\346\225\260\350\266\205\350\277\207\344\270\200\345\215\212\347\232\204\346\225\260\345\255\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23039. \346\225\260\347\273\204\344\270\255\345\207\272\347\216\260\346\254\241\346\225\260\350\266\205\350\277\207\344\270\200\345\215\212\347\232\204\346\225\260\345\255\227/README.md" @@ -29,9 +29,7 @@ ## 解法 - - -**方法一:摩尔投票法** +### 方法一:摩尔投票法 摩尔投票法的基本步骤如下: @@ -47,10 +45,6 @@ -### **Python3** - - - ```python class Solution: def majorityElement(self, nums: List[int]) -> int: @@ -63,10 +57,6 @@ class Solution: return m ``` -### **Java** - - - ```java class Solution { public int majorityElement(int[] nums) { @@ -84,30 +74,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; - } - } - return m; -}; -``` - -### **C++** - ```cpp class Solution { public: @@ -125,31 +91,6 @@ public: }; ``` -### **C#** - -```cs -public class Solution { - public int MajorityElement(int[] nums) { - int cnt = 0, m = 0; - foreach (int v in nums) - { - if (cnt == 0) - { - m = v; - cnt = 1; - } - else - { - cnt += m == v ? 1 : -1; - } - } - return m; - } -} -``` - -### **Go** - ```go func majorityElement(nums []int) int { cnt, m := 0, 0 @@ -168,8 +109,6 @@ func majorityElement(nums []int) int { } ``` -### **Rust** - ```rust impl Solution { pub fn majority_element(nums: Vec) -> i32 { @@ -188,10 +127,47 @@ impl Solution { } ``` -### **...** - +```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; + } + } + return m; +}; ``` +```cs +public class Solution { + public int MajorityElement(int[] nums) { + int cnt = 0, m = 0; + foreach (int v in nums) + { + if (cnt == 0) + { + m = v; + cnt = 1; + } + else + { + cnt += m == v ? 1 : -1; + } + } + return m; + } +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/README.md" index ad58f7eeb800d..d6462615f1013 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23040. \346\234\200\345\260\217\347\232\204k\344\270\252\346\225\260/README.md" @@ -28,37 +28,168 @@ ## 解法 -**方法一:排序** +### 方法一:排序 我们可以直接对数组 `arr` 按从小到大排序,然后取前 $k$ 个数即可。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 `arr` 的长度。 -**方法二:优先队列(大根堆)** + -我们可以用优先队列(大根堆)维护最小的 $k$ 个数。 +```python +class Solution: + def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: + arr.sort() + return arr[:k] +``` -遍历数组 `arr`,对于当前遍历到的数 $x$,我们先将其加入优先队列中,然后判断优先队列的大小是否超过 $k$,如果超过了,就将堆顶元素弹出。最后将优先队列中的数存入数组并返回即可。 +```java +class Solution { + public int[] getLeastNumbers(int[] arr, int k) { + Arrays.sort(arr); + int[] ans = new int[k]; + for (int i = 0; i < k; ++i) { + ans[i] = arr[i]; + } + return ans; + } +} +``` -时间复杂度 $O(n \times \log k)$,空间复杂度 $O(k)$。其中 $n$ 为数组 `arr` 的长度。 +```cpp +class Solution { +public: + vector getLeastNumbers(vector& arr, int k) { + sort(arr.begin(), arr.end()); + return vector(arr.begin(), arr.begin() + k); + } +}; +``` -**方法三:快排思想** +```go +func getLeastNumbers(arr []int, k int) []int { + sort.Ints(arr) + return arr[:k] +} +``` -我们可以利用快速排序的思想,每次划分后判断划分点的位置是否为 $k$,如果是,就直接返回划分点左边的数即可,否则根据划分点的位置决定下一步划分的区间。 +```ts +function getLeastNumbers(arr: number[], k: number): number[] { + let start = 0; + let end = arr.length; + while (start < end && end > k) { + const index = start + Math.floor(Math.random() * (end - start)); + [arr[start], arr[index]] = [arr[index], arr[start]]; + const num = arr[start]; + let mark = start; + for (let i = start + 1; i < end; i++) { + if (arr[i] < num) { + mark++; + [arr[i], arr[mark]] = [arr[mark], arr[i]]; + } + } + [arr[start], arr[mark]] = [arr[mark], arr[start]]; -时间复杂度 $O(n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 `arr` 的长度。 + if (mark >= k) { + end = mark; + } else { + start = mark + 1; + } + } + return arr.slice(0, k); +} +``` - +```rust +impl Solution { + pub fn get_least_numbers(mut arr: Vec, k: i32) -> Vec { + let k = k as usize; + let mut start = 0; + let mut end = arr.len(); + while start < end && end > k { + let num = arr[start]; + let mut mark = start; + for i in start + 1..end { + if arr[i] < num { + mark += 1; + arr.swap(i, mark); + } + } + arr.swap(start, mark); -### **Python3** + if mark <= k { + start = mark + 1; + } else { + end = mark; + } + } + arr[0..k].to_vec() + } +} +``` -```python -class Solution: - def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: - arr.sort() - return arr[:k] +```js +/** + * @param {number[]} arr + * @param {number} k + * @return {number[]} + */ +var getLeastNumbers = function (arr, k) { + // 排序 + // return arr.sort((a,b)=>a-b).slice(0,k) + // ========================================== + // 快排思想 + let left = 0; + let right = arr.length - 1; + while (left < right) { + let i = partition(left, right); + if (i <= k) { + left = i + 1; + } + if (i >= k) { + right = i - 1; + } + } + function partition(left, right) { + let pivot = arr[left]; + while (left < right) { + while (left < right && arr[right] >= pivot) { + right--; + } + arr[left] = arr[right]; + while (left < right && arr[left] <= pivot) { + left++; + } + arr[right] = arr[left]; + } + arr[left] = pivot; + return left; + } + return arr.slice(0, k); +}; +``` + +```cs +public class Solution { + public int[] GetLeastNumbers(int[] arr, int k) { + Array.Sort(arr); + return arr[..k]; + } +} ``` + + +### 方法二:优先队列(大根堆) + +我们可以用优先队列(大根堆)维护最小的 $k$ 个数。 + +遍历数组 `arr`,对于当前遍历到的数 $x$,我们先将其加入优先队列中,然后判断优先队列的大小是否超过 $k$,如果超过了,就将堆顶元素弹出。最后将优先队列中的数存入数组并返回即可。 + +时间复杂度 $O(n \times \log k)$,空间复杂度 $O(k)$。其中 $n$ 为数组 `arr` 的长度。 + + + ```python class Solution: def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: @@ -70,60 +201,105 @@ class Solution: return [-x for x in h] ``` -```python -class Solution: - def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: - def quick_sort(l, r): - i, j = l, r - while i < j: - while i < j and arr[j] >= arr[l]: - j -= 1 - while i < j and arr[i] <= arr[l]: - i += 1 - arr[i], arr[j] = arr[j], arr[i] - arr[i], arr[l] = arr[l], arr[i] - if k < i: - return quick_sort(l, i - 1) - if k > i: - return quick_sort(i + 1, r) - return arr[:k] - - n = len(arr) - return arr if k == n else quick_sort(0, n - 1) -``` - -### **Java** - ```java class Solution { public int[] getLeastNumbers(int[] arr, int k) { - Arrays.sort(arr); + PriorityQueue q = new PriorityQueue<>((a, b) -> b - a); + for (int x : arr) { + q.offer(x); + if (q.size() > k) { + q.poll(); + } + } int[] ans = new int[k]; for (int i = 0; i < k; ++i) { - ans[i] = arr[i]; + ans[i] = q.poll(); } return ans; } } ``` -```java +```cpp class Solution { - public int[] getLeastNumbers(int[] arr, int k) { - PriorityQueue q = new PriorityQueue<>((a, b) -> b - a); - for (int x : arr) { - q.offer(x); +public: + vector getLeastNumbers(vector& arr, int k) { + priority_queue q; + for (int& x : arr) { + q.push(x); if (q.size() > k) { - q.poll(); + q.pop(); } } - int[] ans = new int[k]; + vector ans(k); for (int i = 0; i < k; ++i) { - ans[i] = q.poll(); + ans[i] = q.top(); + q.pop(); } return ans; } +}; +``` + +```go +func getLeastNumbers(arr []int, k int) (ans []int) { + q := hp{} + for _, x := range arr { + heap.Push(&q, x) + if q.Len() > k { + heap.Pop(&q) + } + } + for i := 0; i < k; i++ { + ans = append(ans, heap.Pop(&q).(int)) + } + return +} + +type hp struct{ sort.IntSlice } + +func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } +func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } +func (h *hp) Pop() any { + a := h.IntSlice + v := a[len(a)-1] + h.IntSlice = a[:len(a)-1] + return v } +func (h *hp) push(v int) { heap.Push(h, v) } +func (h *hp) pop() int { return heap.Pop(h).(int) } +``` + + + +### 方法三:快排思想 + +我们可以利用快速排序的思想,每次划分后判断划分点的位置是否为 $k$,如果是,就直接返回划分点左边的数即可,否则根据划分点的位置决定下一步划分的区间。 + +时间复杂度 $O(n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 `arr` 的长度。 + + + +```python +class Solution: + def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: + def quick_sort(l, r): + i, j = l, r + while i < j: + while i < j and arr[j] >= arr[l]: + j -= 1 + while i < j and arr[i] <= arr[l]: + i += 1 + arr[i], arr[j] = arr[j], arr[i] + arr[i], arr[l] = arr[l], arr[i] + if k < i: + return quick_sort(l, i - 1) + if k > i: + return quick_sort(i + 1, r) + return arr[:k] + + n = len(arr) + return arr if k == n else quick_sort(0, n - 1) ``` ```java @@ -167,39 +343,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector getLeastNumbers(vector& arr, int k) { - sort(arr.begin(), arr.end()); - return vector(arr.begin(), arr.begin() + k); - } -}; -``` - -```cpp -class Solution { -public: - vector getLeastNumbers(vector& arr, int k) { - priority_queue q; - for (int& x : arr) { - q.push(x); - if (q.size() > k) { - q.pop(); - } - } - vector ans(k); - for (int i = 0; i < k; ++i) { - ans[i] = q.top(); - q.pop(); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -230,44 +373,6 @@ public: }; ``` -### **Go** - -```go -func getLeastNumbers(arr []int, k int) []int { - sort.Ints(arr) - return arr[:k] -} -``` - -```go -func getLeastNumbers(arr []int, k int) (ans []int) { - q := hp{} - for _, x := range arr { - heap.Push(&q, x) - if q.Len() > k { - heap.Pop(&q) - } - } - for i := 0; i < k; i++ { - ans = append(ans, heap.Pop(&q).(int)) - } - return -} - -type hp struct{ sort.IntSlice } - -func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } -func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } -func (h *hp) Pop() any { - a := h.IntSlice - v := a[len(a)-1] - h.IntSlice = a[:len(a)-1] - return v -} -func (h *hp) push(v int) { heap.Push(h, v) } -func (h *hp) pop() int { return heap.Pop(h).(int) } -``` - ```go func getLeastNumbers(arr []int, k int) []int { n := len(arr) @@ -299,123 +404,6 @@ func getLeastNumbers(arr []int, k int) []int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} arr - * @param {number} k - * @return {number[]} - */ -var getLeastNumbers = function (arr, k) { - // 排序 - // return arr.sort((a,b)=>a-b).slice(0,k) - // ========================================== - // 快排思想 - let left = 0; - let right = arr.length - 1; - while (left < right) { - let i = partition(left, right); - if (i <= k) { - left = i + 1; - } - if (i >= k) { - right = i - 1; - } - } - function partition(left, right) { - let pivot = arr[left]; - while (left < right) { - while (left < right && arr[right] >= pivot) { - right--; - } - arr[left] = arr[right]; - while (left < right && arr[left] <= pivot) { - left++; - } - arr[right] = arr[left]; - } - arr[left] = pivot; - return left; - } - return arr.slice(0, k); -}; -``` - -### **TypeScript** - -```ts -function getLeastNumbers(arr: number[], k: number): number[] { - let start = 0; - let end = arr.length; - while (start < end && end > k) { - const index = start + Math.floor(Math.random() * (end - start)); - [arr[start], arr[index]] = [arr[index], arr[start]]; - const num = arr[start]; - let mark = start; - for (let i = start + 1; i < end; i++) { - if (arr[i] < num) { - mark++; - [arr[i], arr[mark]] = [arr[mark], arr[i]]; - } - } - [arr[start], arr[mark]] = [arr[mark], arr[start]]; - - if (mark >= k) { - end = mark; - } else { - start = mark + 1; - } - } - return arr.slice(0, k); -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn get_least_numbers(mut arr: Vec, k: i32) -> Vec { - let k = k as usize; - let mut start = 0; - let mut end = arr.len(); - while start < end && end > k { - let num = arr[start]; - let mut mark = start; - for i in start + 1..end { - if arr[i] < num { - mark += 1; - arr.swap(i, mark); - } - } - arr.swap(start, mark); - - if mark <= k { - start = mark + 1; - } else { - end = mark; - } - } - arr[0..k].to_vec() - } -} -``` - -### **C#** - -```cs -public class Solution { - public int[] GetLeastNumbers(int[] arr, int k) { - Array.Sort(arr); - return arr[..k]; - } -} -``` - -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23041. \346\225\260\346\215\256\346\265\201\344\270\255\347\232\204\344\270\255\344\275\215\346\225\260/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23041. \346\225\260\346\215\256\346\265\201\344\270\255\347\232\204\344\270\255\344\275\215\346\225\260/README.md" index 1bf17ab921c10..f6f0932d8edc6 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23041. \346\225\260\346\215\256\346\265\201\344\270\255\347\232\204\344\270\255\344\275\215\346\225\260/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23041. \346\225\260\346\215\256\346\265\201\344\270\255\347\232\204\344\270\255\344\275\215\346\225\260/README.md" @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:优先队列(大小根堆)** +### 方法一:优先队列(大小根堆) 我们可以维护两个优先队列,一个大根堆,一个小根堆,大根堆存储较小的一半数,小根堆存储较大的一半数。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class MedianFinder: def __init__(self): @@ -91,37 +85,6 @@ class MedianFinder: # param_2 = obj.findMedian() ``` -```python -from sortedcontainers import SortedList - - -class MedianFinder: - def __init__(self): - """ - initialize your data structure here. - """ - self.sl = SortedList() - - def addNum(self, num: int) -> None: - self.sl.add(num) - - def findMedian(self) -> float: - n = len(self.sl) - if n & 1: - return self.sl[n // 2] - return (self.sl[(n - 1) // 2] + self.sl[n // 2]) / 2 - - -# Your MedianFinder object will be instantiated and called as such: -# obj = MedianFinder() -# obj.addNum(num) -# param_2 = obj.findMedian() -``` - -### **Java** - - - ```java class MedianFinder { private PriorityQueue q1 = new PriorityQueue<>(); @@ -157,8 +120,6 @@ class MedianFinder { */ ``` -### **C++** - ```cpp class MedianFinder { public: @@ -198,8 +159,6 @@ private: */ ``` -### **Go** - ```go type MedianFinder struct { q1, q2 hp @@ -246,45 +205,6 @@ func (h *hp) Pop() any { */ ``` -### **JavaScript** - -```js -/** - * initialize your data structure here. - */ -var MedianFinder = function () { - this.val = []; -}; - -/** - * @param {number} num - * @return {void} - */ -MedianFinder.prototype.addNum = function (num) { - let left = 0; - let right = this.val.length; - while (left < right) { - let mid = left + ~~((right - left) / 2); - if (num > this.val[mid]) { - left = mid + 1; - } else { - right = mid; - } - } - this.val.splice(left, 0, num); -}; - -/** - * @return {number} - */ -MedianFinder.prototype.findMedian = function () { - let mid = ~~(this.val.length / 2); - return this.val.length % 2 ? this.val[mid] : (this.val[mid - 1] + this.val[mid]) / 2; -}; -``` - -### **TypeScript** - ```ts class MedianFinder { private nums: number[]; @@ -326,8 +246,6 @@ class MedianFinder { */ ``` -### **Rust** - ```rust struct MedianFinder { nums: Vec, @@ -372,7 +290,40 @@ impl MedianFinder { */ ``` -### **C#** +```js +/** + * initialize your data structure here. + */ +var MedianFinder = function () { + this.val = []; +}; + +/** + * @param {number} num + * @return {void} + */ +MedianFinder.prototype.addNum = function (num) { + let left = 0; + let right = this.val.length; + while (left < right) { + let mid = left + ~~((right - left) / 2); + if (num > this.val[mid]) { + left = mid + 1; + } else { + right = mid; + } + } + this.val.splice(left, 0, num); +}; + +/** + * @return {number} + */ +MedianFinder.prototype.findMedian = function () { + let mid = ~~(this.val.length / 2); + return this.val.length % 2 ? this.val[mid] : (this.val[mid - 1] + this.val[mid]) / 2; +}; +``` ```cs public class MedianFinder { @@ -433,10 +384,39 @@ public class MedianFinder { */ ``` -### **...** + -``` +### 方法二 + + + +```python +from sortedcontainers import SortedList + + +class MedianFinder: + def __init__(self): + """ + initialize your data structure here. + """ + self.sl = SortedList() + + def addNum(self, num: int) -> None: + self.sl.add(num) + def findMedian(self) -> float: + n = len(self.sl) + if n & 1: + return self.sl[n // 2] + return (self.sl[(n - 1) // 2] + self.sl[n // 2]) / 2 + + +# Your MedianFinder object will be instantiated and called as such: +# obj = MedianFinder() +# obj.addNum(num) +# param_2 = obj.findMedian() ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23042. \350\277\236\347\273\255\345\255\220\346\225\260\347\273\204\347\232\204\346\234\200\345\244\247\345\222\214/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23042. \350\277\236\347\273\255\345\255\220\346\225\260\347\273\204\347\232\204\346\234\200\345\244\247\345\222\214/README.md" index b730984edf2c0..58df7e3f8a52c 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23042. \350\277\236\347\273\255\345\255\220\346\225\260\347\273\204\347\232\204\346\234\200\345\244\247\345\222\214/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23042. \350\277\236\347\273\255\345\255\220\346\225\260\347\273\204\347\232\204\346\234\200\345\244\247\345\222\214/README.md" @@ -29,7 +29,7 @@ ## 解法 -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示以第 $i$ 个数结尾的「连续子数组的最大和」,那么很显然我们要求的答案就是: @@ -55,8 +55,6 @@ $$ -### **Python3** - ```python class Solution: def maxSubArray(self, nums: List[int]) -> int: @@ -67,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxSubArray(int[] nums) { @@ -83,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +94,6 @@ public: }; ``` -### **Go** - ```go func maxSubArray(nums []int) int { ans, f := -1000000000, 0 @@ -113,26 +105,6 @@ func maxSubArray(nums []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var maxSubArray = function (nums) { - let ans = -1e10; - let f = 0; - for (const x of nums) { - f = Math.max(f, 0) + x; - ans = Math.max(ans, f); - } - return ans; -}; -``` - -### **TypeScript** - ```ts function maxSubArray(nums: number[]): number { let res = nums[0]; @@ -144,8 +116,6 @@ function maxSubArray(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_sub_array(mut nums: Vec) -> i32 { @@ -159,7 +129,21 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number[]} nums + * @return {number} + */ +var maxSubArray = function (nums) { + let ans = -1e10; + let f = 0; + for (const x of nums) { + f = Math.max(f, 0) + x; + ans = Math.max(ans, f); + } + return ans; +}; +``` ```cs public class Solution { @@ -175,10 +159,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23043. 1\357\275\236n\346\225\264\346\225\260\344\270\2551\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23043. 1\357\275\236n\346\225\264\346\225\260\344\270\2551\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/README.md" index bbdd8730191e7..57f5bd367fb25 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23043. 1\357\275\236n\346\225\264\346\225\260\344\270\2551\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23043. 1\357\275\236n\346\225\264\346\225\260\344\270\2551\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/README.md" @@ -35,9 +35,7 @@ ## 解法 - - -**方法一:数位 DP** +### 方法一:数位 DP 这道题实际上是求在给定区间 $[l,..r]$ 中,数字中出现 $1$ 个数。个数与数的位数以及每一位上的数字有关。我们可以用数位 DP 的思路来解决这道题。数位 DP 中,数的大小对复杂度的影响很小。 @@ -77,10 +75,6 @@ $$ -### **Python3** - - - ```python class Solution: def countDigitOne(self, n: int) -> int: @@ -101,10 +95,6 @@ class Solution: return dfs(len(a) - 1, 0, True) ``` -### **Java** - - - ```java class Solution { private int[] a = new int[12]; @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -208,8 +196,6 @@ func countDigitOne(n int) int { } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -238,8 +224,6 @@ var countDigitOne = function (n) { }; ``` -### **C#** - ```cs public class Solution { public int CountDigitOne(int n) { @@ -254,10 +238,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/README.md" index 341c4d7f9859a..ccb5bffaa1ef7 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23044. \346\225\260\345\255\227\345\272\217\345\210\227\344\270\255\346\237\220\344\270\200\344\275\215\347\232\204\346\225\260\345\255\227/README.md" @@ -33,9 +33,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 位数为 $k$ 的最小整数和最大整数分别为 $10^{k-1}$ 和 $10^k-1$,因此 $k$ 位数的总位数为 $k \times 9 \times 10^{k-1}$。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def findNthDigit(self, n: int) -> int: @@ -66,25 +60,6 @@ class Solution: return int(str(num)[idx]) ``` -```python -class Solution: - def findNthDigit(self, n: int) -> int: - if n < 10: - return n - n -= 10 - k, p = 2, 10 - while n >= 9 * k * p: - n -= 9 * k * p - k += 1 - p *= 10 - x = p + n // k - return int(str(x)[n % k]) -``` - -### **Java** - - - ```java class Solution { public int findNthDigit(int n) { @@ -101,27 +76,6 @@ class Solution { } ``` -```java -class Solution { - public int findNthDigit(int n) { - if (n < 10) { - return n; - } - n -= 10; - int k = 2, p = 10; - while (n >= (long) 9 * k * p) { - n -= 9 * k * p; - ++k; - p *= 10; - } - int x = p + n / k; - return String.valueOf(x).charAt(n % k) - '0'; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -139,28 +93,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findNthDigit(int n) { - if (n < 10) { - return n; - } - n -= 10; - int k = 2, p = 10; - while (n >= 9ll * k * p) { - n -= 9 * k * p; - ++k; - p *= 10; - } - int x = p + n / k; - return to_string(x)[n % k] - '0'; - } -}; -``` - -### **Go** - ```go func findNthDigit(n int) int { k, cnt := 1, 9 @@ -175,25 +107,6 @@ func findNthDigit(n int) int { } ``` -```go -func findNthDigit(n int) int { - if n < 10 { - return n - } - n -= 10 - k, p := 2, 10 - for n >= 9*k*p { - n -= 9 * k * p - k++ - p *= 10 - } - x := p + n/k - return int(strconv.Itoa(x)[n%k] - '0') -} -``` - -### **JavaScript** - ```js /** * @param {number} n @@ -213,8 +126,6 @@ var findNthDigit = function (n) { }; ``` -### **C#** - ```cs public class Solution { public int FindNthDigit(int n) { @@ -231,10 +142,83 @@ public class Solution { } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def findNthDigit(self, n: int) -> int: + if n < 10: + return n + n -= 10 + k, p = 2, 10 + while n >= 9 * k * p: + n -= 9 * k * p + k += 1 + p *= 10 + x = p + n // k + return int(str(x)[n % k]) +``` + +```java +class Solution { + public int findNthDigit(int n) { + if (n < 10) { + return n; + } + n -= 10; + int k = 2, p = 10; + while (n >= (long) 9 * k * p) { + n -= 9 * k * p; + ++k; + p *= 10; + } + int x = p + n / k; + return String.valueOf(x).charAt(n % k) - '0'; + } +} +``` +```cpp +class Solution { +public: + int findNthDigit(int n) { + if (n < 10) { + return n; + } + n -= 10; + int k = 2, p = 10; + while (n >= 9ll * k * p) { + n -= 9 * k * p; + ++k; + p *= 10; + } + int x = p + n / k; + return to_string(x)[n % k] - '0'; + } +}; ``` +```go +func findNthDigit(n int) int { + if n < 10 { + return n + } + n -= 10 + k, p := 2, 10 + for n >= 9*k*p { + n -= 9 * k * p + k++ + p *= 10 + } + x := p + n/k + return int(strconv.Itoa(x)[n%k] - '0') +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23045. \346\212\212\346\225\260\347\273\204\346\216\222\346\210\220\346\234\200\345\260\217\347\232\204\346\225\260/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23045. \346\212\212\346\225\260\347\273\204\346\216\222\346\210\220\346\234\200\345\260\217\347\232\204\346\225\260/README.md" index 3f0a8f7e9a2b4..acb2a7ee36013 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23045. \346\212\212\346\225\260\347\273\204\346\216\222\346\210\220\346\234\200\345\260\217\347\232\204\346\225\260/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23045. \346\212\212\346\225\260\347\273\204\346\216\222\346\210\220\346\234\200\345\260\217\347\232\204\346\225\260/README.md" @@ -35,9 +35,7 @@ ## 解法 - - -**方法一:自定义排序** +### 方法一:自定义排序 将数组中的数字转换为字符串,然后按照字符串拼接的大小进行排序。具体地,比较两个字符串 $a$ 和 $b$,如果 $a + b \lt b + a$,则 $a$ 小于 $b$,否则 $a$ 大于 $b$。 @@ -45,10 +43,6 @@ -### **Python3** - - - ```python class Solution: def minNumber(self, nums: List[int]) -> str: @@ -61,10 +55,6 @@ class Solution: return "".join(ans) ``` -### **Java** - - - ```java class Solution { public String minNumber(int[] nums) { @@ -77,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +87,6 @@ public: }; ``` -### **Go** - ```go func minNumber(nums []int) string { arr := []string{} @@ -112,33 +98,12 @@ func minNumber(nums []int) string { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {string} - */ -var minNumber = function (nums) { - nums.sort((a, b) => { - const x = a + '' + b; - const y = b + '' + a; - return x < y ? -1 : 1; - }); - return nums.join(''); -}; -``` - -### **TypeScript** - ```ts function minNumber(nums: number[]): string { return nums.sort((a, b) => Number(`${a}${b}`) - Number(`${b}${a}`)).join(''); } ``` -### **Rust** - ```rust impl Solution { pub fn min_number(mut nums: Vec) -> String { @@ -150,7 +115,20 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number[]} nums + * @return {string} + */ +var minNumber = function (nums) { + nums.sort((a, b) => { + const x = a + '' + b; + const y = b + '' + a; + return x < y ? -1 : 1; + }); + return nums.join(''); +}; +``` ```cs public class Solution { @@ -165,10 +143,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/README.md" index 4934af5171d63..232a827645bc5 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23046. \346\212\212\346\225\260\345\255\227\347\277\273\350\257\221\346\210\220\345\255\227\347\254\246\344\270\262/README.md" @@ -24,9 +24,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们先将数字 `num` 转为字符串 $s$,字符串 $s$ 的长度记为 $n$。 @@ -41,24 +39,8 @@ 时间复杂度 $O(\log num)$,空间复杂度 $O(\log num)$。其中 $num$ 为给定的数字。 -**方法二:动态规划** - -我们可以将方法一中的记忆化搜索改为动态规划。 - -定义 $f[i]$ 表示前 $i$ 个数字的不同翻译的数目,那么答案就是 $f[n]$。初始化 $f[0] = 1$, $f[1] = 1$。 - -我们可以从前往后计算 $f[i]$ 的值,对于每个 $i$,我们可以选择翻译第 $i$ 个数字,此时翻译方法数目为 $f[i - 1]$;如果第 $i-1$ 个数字和第 $i$ 个数字可以组成一个有效的字符(即 $s[i - 1] == 1$ 或者 $s[i - 1] == 2$ 且 $s[i] \lt 6$),那么我们还可以选择翻译第 $i - 1$ 和第 $i$ 个数字,此时翻译方法数目为 $f[i - 2]$。因此 $f[i] = f[i-1] + f[i-2]$。 - -由于 $f[i]$ 只与 $f[i - 1]$ 和 $f[i - 2]$ 有关,因此我们可以只用两个变量来存储 $f[i - 1]$ 和 $f[i - 2]$ 的值,从而省去数组 $f$ 的空间。 - -时间复杂度 $O(\log num)$,空间复杂度 $O(\log num)$。其中 $num$ 为给定的数字。 - -### **Python3** - - - ```python class Solution: def translateNum(self, num: int) -> int: @@ -76,24 +58,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def translateNum(self, num: int) -> int: - s = str(num) - n = len(s) - a = b = 1 - for i in range(1, n): - c = b - if s[i - 1] == '1' or (s[i - 1] == '2' and s[i] < '6'): - c += a - a, b = b, c - return b -``` - -### **Java** - - - ```java class Solution { private int n; @@ -123,27 +87,6 @@ class Solution { } ``` -```java -class Solution { - public int translateNum(int num) { - char[] s = String.valueOf(num).toCharArray(); - int n = s.length; - int a = 1, b = 1; - for (int i = 1; i < n; ++i) { - int c = b; - if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] < '6')) { - c += a; - } - a = b; - b = c; - } - return b; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -169,28 +112,6 @@ public: }; ``` -```cpp -class Solution { -public: - int translateNum(int num) { - string s = to_string(num); - int n = s.size(); - int a = 1, b = 1; - for (int i = 1; i < n; ++i) { - int c = b; - if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] < '6')) { - c += a; - } - a = b; - b = c; - } - return b; - } -}; -``` - -### **Go** - ```go func translateNum(num int) int { s := strconv.Itoa(num) @@ -215,34 +136,12 @@ func translateNum(num int) int { } ``` -```go -func translateNum(num int) int { - s := strconv.Itoa(num) - n := len(s) - a, b := 1, 1 - for i := 1; i < n; i++ { - c := b - if s[i-1] == '1' || (s[i-1] == '2' && s[i] < '6') { - c += a - } - a, b = b, c - } - return b -} -``` - -### **JavaScript** - -```js -/** - * @param {number} num - * @return {number} - */ -var translateNum = function (num) { +```ts +function translateNum(num: number): number { const s = num.toString(); const n = s.length; const f = new Array(n).fill(0); - const dfs = i => { + const dfs = (i: number): number => { if (i >= n - 1) { return 1; } @@ -257,7 +156,26 @@ var translateNum = function (num) { return ans; }; return dfs(0); -}; +} +``` + +```rust +impl Solution { + pub fn translate_num(num: i32) -> i32 { + let mut a = 1; + let mut b = 1; + let str = num.to_string(); + for i in 0..str.len() - 1 { + let c = a + b; + a = b; + let num = str[i..i + 2].parse::().unwrap(); + if num >= 10 && num < 26 { + b = c; + } + } + b + } +} ``` ```js @@ -266,30 +184,10 @@ var translateNum = function (num) { * @return {number} */ var translateNum = function (num) { - const s = num.toString(); - const n = s.length; - let a = 1; - let b = 1; - for (let i = 1; i < n; ++i) { - let c = b; - if (s[i - 1] === '1' || (s[i - 1] === '2' && s[i] < '6')) { - c += a; - } - a = b; - b = c; - } - return b; -}; -``` - -### **TypeScript** - -```ts -function translateNum(num: number): number { const s = num.toString(); const n = s.length; const f = new Array(n).fill(0); - const dfs = (i: number): number => { + const dfs = i => { if (i >= n - 1) { return 1; } @@ -304,6 +202,110 @@ function translateNum(num: number): number { return ans; }; return dfs(0); +}; +``` + +```cs +public class Solution { + public int TranslateNum(int num) { + var s = num.ToString(); + int n = s.Length; + int a = 1, b = 1; + for (int i = 1; i < n; ++i) { + int c = b; + if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] < '6')) { + c += a; + } + a = b; + b = c; + } + return b; + } +} +``` + + + +### 方法二:动态规划 + +我们可以将方法一中的记忆化搜索改为动态规划。 + +定义 $f[i]$ 表示前 $i$ 个数字的不同翻译的数目,那么答案就是 $f[n]$。初始化 $f[0] = 1$, $f[1] = 1$。 + +我们可以从前往后计算 $f[i]$ 的值,对于每个 $i$,我们可以选择翻译第 $i$ 个数字,此时翻译方法数目为 $f[i - 1]$;如果第 $i-1$ 个数字和第 $i$ 个数字可以组成一个有效的字符(即 $s[i - 1] == 1$ 或者 $s[i - 1] == 2$ 且 $s[i] \lt 6$),那么我们还可以选择翻译第 $i - 1$ 和第 $i$ 个数字,此时翻译方法数目为 $f[i - 2]$。因此 $f[i] = f[i-1] + f[i-2]$。 + +由于 $f[i]$ 只与 $f[i - 1]$ 和 $f[i - 2]$ 有关,因此我们可以只用两个变量来存储 $f[i - 1]$ 和 $f[i - 2]$ 的值,从而省去数组 $f$ 的空间。 + +时间复杂度 $O(\log num)$,空间复杂度 $O(\log num)$。其中 $num$ 为给定的数字。 + + + +```python +class Solution: + def translateNum(self, num: int) -> int: + s = str(num) + n = len(s) + a = b = 1 + for i in range(1, n): + c = b + if s[i - 1] == '1' or (s[i - 1] == '2' and s[i] < '6'): + c += a + a, b = b, c + return b +``` + +```java +class Solution { + public int translateNum(int num) { + char[] s = String.valueOf(num).toCharArray(); + int n = s.length; + int a = 1, b = 1; + for (int i = 1; i < n; ++i) { + int c = b; + if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] < '6')) { + c += a; + } + a = b; + b = c; + } + return b; + } +} +``` + +```cpp +class Solution { +public: + int translateNum(int num) { + string s = to_string(num); + int n = s.size(); + int a = 1, b = 1; + for (int i = 1; i < n; ++i) { + int c = b; + if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] < '6')) { + c += a; + } + a = b; + b = c; + } + return b; + } +}; +``` + +```go +func translateNum(num int) int { + s := strconv.Itoa(num) + n := len(s) + a, b := 1, 1 + for i := 1; i < n; i++ { + c := b + if s[i-1] == '1' || (s[i-1] == '2' && s[i] < '6') { + c += a + } + a, b = b, c + } + return b } ``` @@ -325,27 +327,6 @@ function translateNum(num: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn translate_num(num: i32) -> i32 { - let mut a = 1; - let mut b = 1; - let str = num.to_string(); - for i in 0..str.len() - 1 { - let c = a + b; - a = b; - let num = str[i..i + 2].parse::().unwrap(); - if num >= 10 && num < 26 { - b = c; - } - } - b - } -} -``` - ```rust impl Solution { fn dfs(s: &String, i: usize, res: &mut i32) { @@ -369,31 +350,28 @@ impl Solution { } ``` -### **C#** - -```cs -public class Solution { - public int TranslateNum(int num) { - var s = num.ToString(); - int n = s.Length; - int a = 1, b = 1; - for (int i = 1; i < n; ++i) { - int c = b; - if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] < '6')) { - c += a; - } - a = b; - b = c; +```js +/** + * @param {number} num + * @return {number} + */ +var translateNum = function (num) { + const s = num.toString(); + const n = s.length; + let a = 1; + let b = 1; + for (let i = 1; i < n; ++i) { + let c = b; + if (s[i - 1] === '1' || (s[i - 1] === '2' && s[i] < '6')) { + c += a; } - return b; + a = b; + b = c; } -} -``` - -### **...** - -``` - + return b; +}; ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/README.md" index 0008409190aa4..945bdf4a5f4b7 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23047. \347\244\274\347\211\251\347\232\204\346\234\200\345\244\247\344\273\267\345\200\274/README.md" @@ -28,7 +28,7 @@ ## 解法 -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 为从棋盘左上角走到 $(i-1, j-1)$ 的礼物最大累计价值,那么 $f[i][j]$ 的值由 $f[i-1][j]$ 和 $f[i][j-1]$ 决定,即从上方格子和左方格子走过来的两个方案中选择一个价值较大的方案。因此我们可以写出动态规划转移方程: @@ -44,8 +44,6 @@ $$ -### **Python3** - ```python class Solution: def maxValue(self, grid: List[List[int]]) -> int: @@ -57,19 +55,6 @@ class Solution: return f[m][n] ``` -```python -class Solution: - def maxValue(self, grid: List[List[int]]) -> int: - m, n = len(grid), len(grid[0]) - f = [[0] * (n + 1) for _ in range(2)] - for i, row in enumerate(grid, 1): - for j, v in enumerate(row, 1): - f[i & 1][j] = max(f[i & 1 ^ 1][j], f[i & 1][j - 1]) + v - return f[m & 1][n] -``` - -### **Java** - ```java class Solution { public int maxValue(int[][] grid) { @@ -85,23 +70,6 @@ class Solution { } ``` -```java -class Solution { - public int maxValue(int[][] grid) { - int m = grid.length, n = grid[0].length; - int[][] f = new int[2][n + 1]; - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - f[i & 1][j] = Math.max(f[i & 1 ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; - } - } - return f[m & 1][n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -118,24 +86,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxValue(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - vector> f(2, vector(n + 1, 0)); - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - f[i & 1][j] = max(f[i & 1 ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; - } - } - return f[m & 1][n]; - } -}; -``` - -### **Go** - ```go func maxValue(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -152,62 +102,6 @@ func maxValue(grid [][]int) int { } ``` -```go -func maxValue(grid [][]int) int { - m, n := len(grid), len(grid[0]) - f := make([][]int, 2) - for i := range f { - f[i] = make([]int, n+1) - } - for i := 1; i <= m; i++ { - for j := 1; j <= n; j++ { - f[i&1][j] = max(f[i&1^1][j], f[i&1][j-1]) + grid[i-1][j-1] - } - } - return f[m&1][n] -} -``` - -### **JavaScript** - -```js -/** - * @param {number[][]} grid - * @return {number} - */ -var maxValue = function (grid) { - const m = grid.length; - const n = grid[0].length; - const f = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); - for (let i = 1; i <= m; ++i) { - for (let j = 1; j <= n; ++j) { - f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]) + grid[i - 1][j - 1]; - } - } - return f[m][n]; -}; -``` - -```js -/** - * @param {number[][]} grid - * @return {number} - */ -var maxValue = function (grid) { - const m = grid.length; - const n = grid[0].length; - const f = new Array(2).fill(0).map(() => new Array(n + 1).fill(0)); - for (let i = 1; i <= m; ++i) { - for (let j = 1; j <= n; ++j) { - f[i & 1][j] = Math.max(f[(i & 1) ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; - } - } - return f[m & 1][n]; -}; -``` - -### **TypeScript** - ```ts function maxValue(grid: number[][]): number { const m = grid.length; @@ -222,22 +116,6 @@ function maxValue(grid: number[][]): number { } ``` -```ts -function maxValue(grid: number[][]): number { - const m = grid.length; - const n = grid[0].length; - const f = Array.from({ length: 2 }, _ => new Array(n + 1).fill(0)); - for (let i = 1; i <= m; ++i) { - for (let j = 1; j <= n; ++j) { - f[i & 1][j] = Math.max(f[(i & 1) ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; - } - } - return f[m & 1][n]; -} -``` - -### **Rust** - ```rust impl Solution { pub fn max_value(mut grid: Vec>) -> i32 { @@ -259,7 +137,23 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number[][]} grid + * @return {number} + */ +var maxValue = function (grid) { + const m = grid.length; + const n = grid[0].length; + const f = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); + for (let i = 1; i <= m; ++i) { + for (let j = 1; j <= n; ++j) { + f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]) + grid[i - 1][j - 1]; + } + } + return f[m][n]; +}; +``` ```cs public class Solution { @@ -276,10 +170,102 @@ public class Solution { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def maxValue(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + f = [[0] * (n + 1) for _ in range(2)] + for i, row in enumerate(grid, 1): + for j, v in enumerate(row, 1): + f[i & 1][j] = max(f[i & 1 ^ 1][j], f[i & 1][j - 1]) + v + return f[m & 1][n] ``` +```java +class Solution { + public int maxValue(int[][] grid) { + int m = grid.length, n = grid[0].length; + int[][] f = new int[2][n + 1]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + f[i & 1][j] = Math.max(f[i & 1 ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; + } + } + return f[m & 1][n]; + } +} +``` + +```cpp +class Solution { +public: + int maxValue(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector> f(2, vector(n + 1, 0)); + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + f[i & 1][j] = max(f[i & 1 ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; + } + } + return f[m & 1][n]; + } +}; +``` + +```go +func maxValue(grid [][]int) int { + m, n := len(grid), len(grid[0]) + f := make([][]int, 2) + for i := range f { + f[i] = make([]int, n+1) + } + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + f[i&1][j] = max(f[i&1^1][j], f[i&1][j-1]) + grid[i-1][j-1] + } + } + return f[m&1][n] +} +``` + +```ts +function maxValue(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const f = Array.from({ length: 2 }, _ => new Array(n + 1).fill(0)); + for (let i = 1; i <= m; ++i) { + for (let j = 1; j <= n; ++j) { + f[i & 1][j] = Math.max(f[(i & 1) ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; + } + } + return f[m & 1][n]; +} +``` + +```js +/** + * @param {number[][]} grid + * @return {number} + */ +var maxValue = function (grid) { + const m = grid.length; + const n = grid[0].length; + const f = new Array(2).fill(0).map(() => new Array(n + 1).fill(0)); + for (let i = 1; i <= m; ++i) { + for (let j = 1; j <= n; ++j) { + f[i & 1][j] = Math.max(f[(i & 1) ^ 1][j], f[i & 1][j - 1]) + grid[i - 1][j - 1]; + } + } + return f[m & 1][n]; +}; ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/README.md" index eed6506dd8ec8..935d4f6ab980c 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23048. \346\234\200\351\225\277\344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\345\255\220\345\255\227\347\254\246\344\270\262/README.md" @@ -40,7 +40,7 @@ ## 解法 -**方法一:双指针 + 哈希表** +### 方法一:双指针 + 哈希表 我们用双指针 $j$ 和 $i$ 分别表示子串的左右边界,其中 $j$ 是滑动窗口的左边界,$i$ 是滑动窗口的右边界,用哈希表 $vis$ 记录每个字符是否出现过。 @@ -52,8 +52,6 @@ -### **Python3** - ```python class Solution: def lengthOfLongestSubstring(self, s: str) -> int: @@ -68,22 +66,6 @@ class Solution: return ans ``` -```python -class Solution: - def lengthOfLongestSubstring(self, s: str) -> int: - vis = set() - ans = j = 0 - for i, c in enumerate(s): - while c in vis: - vis.remove(s[j]) - j += 1 - vis.add(c) - ans = max(ans, i - j + 1) - return ans -``` - -### **Java** - ```java class Solution { public int lengthOfLongestSubstring(String s) { @@ -101,27 +83,6 @@ class Solution { } ``` -```java -class Solution { - public int lengthOfLongestSubstring(String s) { - boolean[] ss = new boolean[128]; - int ans = 0, j = 0; - int n = s.length(); - for (int i = 0; i < n; ++i) { - char c = s.charAt(i); - while (ss[c]) { - ss[s.charAt(j++)] = false; - } - ans = Math.max(ans, i - j + 1); - ss[c] = true; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -140,27 +101,6 @@ public: }; ``` -```cpp -class Solution { -public: - int lengthOfLongestSubstring(string s) { - bool ss[128] = {false}; - int n = s.size(); - int ans = 0; - for (int i = 0, j = 0; i < n; ++i) { - while (ss[s[i]]) { - ss[s[j++]] = false; - } - ss[s[i]] = true; - ans = max(ans, i - j + 1); - } - return ans; - } -}; -``` - -### **Go** - ```go func lengthOfLongestSubstring(s string) (ans int) { vis := map[byte]bool{} @@ -177,23 +117,42 @@ func lengthOfLongestSubstring(s string) (ans int) { } ``` -```go -func lengthOfLongestSubstring(s string) (ans int) { - ss := make([]bool, 128) - j := 0 - for i, c := range s { - for ss[c] { - ss[s[j]] = false - j++ - } - ss[c] = true - ans = max(ans, i-j+1) - } - return +```ts +function lengthOfLongestSubstring(s: string): number { + let ans = 0; + const vis = new Set(); + for (let i = 0, j = 0; i < s.length; ++i) { + while (vis.has(s[i])) { + vis.delete(s[j++]); + } + vis.add(s[i]); + ans = Math.max(ans, i - j + 1); + } + return ans; } ``` -### **JavaScript** +```rust +use std::collections::HashSet; +impl Solution { + pub fn length_of_longest_substring(s: String) -> i32 { + let s = s.as_bytes(); + let n = s.len(); + let mut set = HashSet::new(); + let mut res = 0; + let mut i = 0; + for j in 0..n { + while set.contains(&s[j]) { + set.remove(&s[i]); + i += 1; + } + set.insert(s[j]); + res = res.max(set.len()); + } + res as i32 + } +} +``` ```js /** @@ -214,20 +173,94 @@ var lengthOfLongestSubstring = function (s) { }; ``` -### **TypeScript** +```cs +public class Solution { + public int LengthOfLongestSubstring(string s) { + var vis = new HashSet(); + int ans = 0; + for (int i = 0, j = 0; i < s.Length; ++i) { + while (vis.Contains(s[i])) { + vis.Remove(s[j++]); + } + vis.Add(s[i]); + ans = Math.Max(ans, i - j + 1); + } + return ans; + } +} +``` -```ts -function lengthOfLongestSubstring(s: string): number { - let ans = 0; - const vis = new Set(); - for (let i = 0, j = 0; i < s.length; ++i) { - while (vis.has(s[i])) { - vis.delete(s[j++]); + + +### 方法二 + + + +```python +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + vis = set() + ans = j = 0 + for i, c in enumerate(s): + while c in vis: + vis.remove(s[j]) + j += 1 + vis.add(c) + ans = max(ans, i - j + 1) + return ans +``` + +```java +class Solution { + public int lengthOfLongestSubstring(String s) { + boolean[] ss = new boolean[128]; + int ans = 0, j = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + char c = s.charAt(i); + while (ss[c]) { + ss[s.charAt(j++)] = false; + } + ans = Math.max(ans, i - j + 1); + ss[c] = true; } - vis.add(s[i]); - ans = Math.max(ans, i - j + 1); + return ans; } - return ans; +} +``` + +```cpp +class Solution { +public: + int lengthOfLongestSubstring(string s) { + bool ss[128] = {false}; + int n = s.size(); + int ans = 0; + for (int i = 0, j = 0; i < n; ++i) { + while (ss[s[i]]) { + ss[s[j++]] = false; + } + ss[s[i]] = true; + ans = max(ans, i - j + 1); + } + return ans; + } +}; +``` + +```go +func lengthOfLongestSubstring(s string) (ans int) { + ss := make([]bool, 128) + j := 0 + for i, c := range s { + for ss[c] { + ss[s[j]] = false + j++ + } + ss[c] = true + ans = max(ans, i-j+1) + } + return } ``` @@ -247,30 +280,6 @@ function lengthOfLongestSubstring(s: string): number { } ``` -### **Rust** - -```rust -use std::collections::HashSet; -impl Solution { - pub fn length_of_longest_substring(s: String) -> i32 { - let s = s.as_bytes(); - let n = s.len(); - let mut set = HashSet::new(); - let mut res = 0; - let mut i = 0; - for j in 0..n { - while set.contains(&s[j]) { - set.remove(&s[i]); - i += 1; - } - set.insert(s[j]); - res = res.max(set.len()); - } - res as i32 - } -} -``` - ```rust use std::collections::HashMap; impl Solution { @@ -294,29 +303,6 @@ impl Solution { } ``` -### **C#** - -```cs -public class Solution { - public int LengthOfLongestSubstring(string s) { - var vis = new HashSet(); - int ans = 0; - for (int i = 0, j = 0; i < s.Length; ++i) { - while (vis.Contains(s[i])) { - vis.Remove(s[j++]); - } - vis.Add(s[i]); - ans = Math.Max(ans, i - j + 1); - } - return ans; - } -} -``` - -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/README.md" index 19ea95d97e9ab..7c6adaadba005 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23049. \344\270\221\346\225\260/README.md" @@ -25,32 +25,14 @@ ## 解法 - - -**方法一:优先队列(最小堆)** +### 方法一:优先队列(最小堆) 初始时,将第一个丑数 $1$ 加入堆。每次取出堆顶元素 $x$,由于 $2x$, $3x$, $5x$ 也是丑数,因此将它们加入堆中。为了避免重复元素,可以用哈希表 $vis$ 去重。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。 -**方法二:动态规划** - -定义数组 $dp$,其中 $dp[i-1]$ 表示第 $i$ 个丑数,那么第 $n$ 个丑数就是 $dp[n - 1]$。最小的丑数是 $1$,所以 $dp[0]=1$。 - -定义 $3$ 个指针 $p_2$, $p_3$ 和 $p_5$,表示下一个丑数是当前指针指向的丑数乘以对应的质因数。初始时,三个指针的值都指向 $0$。 - -当 $i$ 在 $[1,2..n-1]$ 范围内,我们更新 $dp[i]=\min(dp[p_2] \times 2, dp[p_3] \times 3, dp[p_5] \times 5)$,然后分别比较 $dp[i]$ 与 $dp[p_2] \times 2$, $dp[p_3] \times 3$, $dp[p_5] \times 5$ 是否相等,若是,则对应的指针加 $1$。 - -最后返回 $dp[n - 1]$ 即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。 - -### **Python3** - - - ```python class Solution: def nthUglyNumber(self, n: int) -> int: @@ -67,27 +49,6 @@ class Solution: return ans ``` -```python -class Solution: - def nthUglyNumber(self, n: int) -> int: - dp = [1] * n - p2 = p3 = p5 = 0 - for i in range(1, n): - next2, next3, next5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 - dp[i] = min(next2, next3, next5) - if dp[i] == next2: - p2 += 1 - if dp[i] == next3: - p3 += 1 - if dp[i] == next5: - p5 += 1 - return dp[-1] -``` - -### **Java** - - - ```java class Solution { public int nthUglyNumber(int n) { @@ -111,26 +72,6 @@ class Solution { } ``` -```java -class Solution { - public int nthUglyNumber(int n) { - int[] dp = new int[n]; - dp[0] = 1; - int p2 = 0, p3 = 0, p5 = 0; - for (int i = 1; i < n; ++i) { - int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; - dp[i] = Math.min(next2, Math.min(next3, next5)); - if (dp[i] == next2) ++p2; - if (dp[i] == next3) ++p3; - if (dp[i] == next5) ++p5; - } - return dp[n - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -156,27 +97,6 @@ public: }; ``` -```cpp -class Solution { -public: - int nthUglyNumber(int n) { - vector dp(n); - dp[0] = 1; - int p2 = 0, p3 = 0, p5 = 0; - for (int i = 1; i < n; ++i) { - int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; - dp[i] = min(next2, min(next3, next5)); - if (dp[i] == next2) ++p2; - if (dp[i] == next3) ++p3; - if (dp[i] == next5) ++p5; - } - return dp[n - 1]; - } -}; -``` - -### **Go** - ```go func nthUglyNumber(n int) int { h := IntHeap([]int{1}) @@ -214,56 +134,6 @@ func (h *IntHeap) Pop() any { } ``` -```go -func nthUglyNumber(n int) int { - dp := make([]int, n) - dp[0] = 1 - p2, p3, p5 := 0, 0, 0 - for i := 1; i < n; i++ { - next2, next3, next5 := dp[p2]*2, dp[p3]*3, dp[p5]*5 - dp[i] = min(next2, min(next3, next5)) - if dp[i] == next2 { - p2++ - } - if dp[i] == next3 { - p3++ - } - if dp[i] == next5 { - p5++ - } - } - return dp[n-1] -} -``` - -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number} - */ -var nthUglyNumber = function (n) { - let dp = [1]; - let p2 = 0, - p3 = 0, - p5 = 0; - for (let i = 1; i < n; ++i) { - const next2 = dp[p2] * 2, - next3 = dp[p3] * 3, - next5 = dp[p5] * 5; - dp[i] = Math.min(next2, Math.min(next3, next5)); - if (dp[i] == next2) ++p2; - if (dp[i] == next3) ++p3; - if (dp[i] == next5) ++p5; - dp.push(dp[i]); - } - return dp[n - 1]; -}; -``` - -### **Rust** - ```rust impl Solution { pub fn nth_ugly_number(n: i32) -> i32 { @@ -293,7 +163,29 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number} n + * @return {number} + */ +var nthUglyNumber = function (n) { + let dp = [1]; + let p2 = 0, + p3 = 0, + p5 = 0; + for (let i = 1; i < n; ++i) { + const next2 = dp[p2] * 2, + next3 = dp[p3] * 3, + next5 = dp[p5] * 5; + dp[i] = Math.min(next2, Math.min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + dp.push(dp[i]); + } + return dp[n - 1]; +}; +``` ```cs public class Solution { @@ -319,10 +211,98 @@ public class Solution { } ``` -### **...** + + +### 方法二:动态规划 + +定义数组 $dp$,其中 $dp[i-1]$ 表示第 $i$ 个丑数,那么第 $n$ 个丑数就是 $dp[n - 1]$。最小的丑数是 $1$,所以 $dp[0]=1$。 + +定义 $3$ 个指针 $p_2$, $p_3$ 和 $p_5$,表示下一个丑数是当前指针指向的丑数乘以对应的质因数。初始时,三个指针的值都指向 $0$。 + +当 $i$ 在 $[1,2..n-1]$ 范围内,我们更新 $dp[i]=\min(dp[p_2] \times 2, dp[p_3] \times 3, dp[p_5] \times 5)$,然后分别比较 $dp[i]$ 与 $dp[p_2] \times 2$, $dp[p_3] \times 3$, $dp[p_5] \times 5$ 是否相等,若是,则对应的指针加 $1$。 +最后返回 $dp[n - 1]$ 即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。 + + + +```python +class Solution: + def nthUglyNumber(self, n: int) -> int: + dp = [1] * n + p2 = p3 = p5 = 0 + for i in range(1, n): + next2, next3, next5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 + dp[i] = min(next2, next3, next5) + if dp[i] == next2: + p2 += 1 + if dp[i] == next3: + p3 += 1 + if dp[i] == next5: + p5 += 1 + return dp[-1] ``` +```java +class Solution { + public int nthUglyNumber(int n) { + int[] dp = new int[n]; + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = Math.min(next2, Math.min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + } + return dp[n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int nthUglyNumber(int n) { + vector dp(n); + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = min(next2, min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + } + return dp[n - 1]; + } +}; +``` + +```go +func nthUglyNumber(n int) int { + dp := make([]int, n) + dp[0] = 1 + p2, p3, p5 := 0, 0, 0 + for i := 1; i < n; i++ { + next2, next3, next5 := dp[p2]*2, dp[p3]*3, dp[p5]*5 + dp[i] = min(next2, min(next3, next5)) + if dp[i] == next2 { + p2++ + } + if dp[i] == next3 { + p3++ + } + if dp[i] == next5 { + p5++ + } + } + return dp[n-1] +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23050. \347\254\254\344\270\200\344\270\252\345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\345\255\227\347\254\246/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23050. \347\254\254\344\270\200\344\270\252\345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\345\255\227\347\254\246/README.md" index 78d4f944c7551..fe62864fac5c8 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23050. \347\254\254\344\270\200\344\270\252\345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\345\255\227\347\254\246/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23050. \347\254\254\344\270\200\344\270\252\345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\345\255\227\347\254\246/README.md" @@ -26,7 +26,7 @@ ## 解法 -**方法一:数组或哈希表** +### 方法一:数组或哈希表 我们可以使用哈希表或数组来统计每个字符出现的次数,然后再遍历一遍字符串,找到第一个出现次数为 $1$ 的字符。 @@ -34,8 +34,6 @@ -### **Python3** - ```python class Solution: def firstUniqChar(self, s: str) -> str: @@ -46,8 +44,6 @@ class Solution: return " " ``` -### **Java** - ```java class Solution { public char firstUniqChar(String s) { @@ -66,8 +62,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -86,8 +80,6 @@ public: }; ``` -### **Go** - ```go func firstUniqChar(s string) byte { cnt := [26]int{} @@ -103,29 +95,6 @@ func firstUniqChar(s string) byte { } ``` -### **JavaScript** - -```js -/** - * @param {string} s - * @return {character} - */ -var firstUniqChar = function (s) { - const cnt = new Array(26).fill(0); - for (const c of s) { - cnt[c.charCodeAt(0) - 97]++; - } - for (const c of s) { - if (cnt[c.charCodeAt(0) - 97] === 1) { - return c; - } - } - return ' '; -}; -``` - -### **TypeScript** - ```ts function firstUniqChar(s: string): string { const map = new Map(); @@ -141,8 +110,6 @@ function firstUniqChar(s: string): string { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -161,7 +128,24 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {string} s + * @return {character} + */ +var firstUniqChar = function (s) { + const cnt = new Array(26).fill(0); + for (const c of s) { + cnt[c.charCodeAt(0) - 97]++; + } + for (const c of s) { + if (cnt[c.charCodeAt(0) - 97] === 1) { + return c; + } + } + return ' '; +}; +``` ```cs public class Solution { @@ -180,10 +164,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/README.md" index c6cda0c1b379e..f0d2ad99dedf3 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23051. \346\225\260\347\273\204\344\270\255\347\232\204\351\200\206\345\272\217\345\257\271/README.md" @@ -21,35 +21,14 @@ ## 解法 - - -**方法一:归并排序** +### 方法一:归并排序 归并排序的过程中,如果左边的数大于右边的数,则右边的数与左边的数之后的数都构成逆序对。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。 -**方法二:树状数组** - -树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作: - -1. **单点更新** `update(x, delta)`: 把序列 x 位置的数加上一个值 delta; -1. **前缀和查询** `query(x)`:查询序列 `[1,...x]` 区间的区间和,即位置 x 的前缀和。 - -这两个操作的时间复杂度均为 $O(\log n)$。 - -树状数组最基本的功能就是求比某点 x 小的点的个数(这里的比较是抽象的概念,可以是数的大小、坐标的大小、质量的大小等等)。 - -比如给定数组 `a[5] = {2, 5, 3, 4, 1}`,求 `b[i] = 位置 i 左边小于等于 a[i] 的数的个数`。对于此例,`b[5] = {0, 1, 1, 2, 0}`。 - -解决方案是直接遍历数组,每个位置先求出 `query(a[i])`,然后再修改树状数组 `update(a[i], 1)` 即可。当数的范围比较大时,需要进行离散化,即先进行去重并排序,然后对每个数字进行编号。 - -### **Python3** - - - ```python class Solution: def reversePairs(self, nums: List[int]) -> int: @@ -76,42 +55,6 @@ class Solution: return merge_sort(0, len(nums) - 1) ``` -```python -class BinaryIndexedTree: - def __init__(self, n): - self.n = n - self.c = [0] * (n + 1) - - def update(self, x, delta): - while x <= self.n: - self.c[x] += delta - x += x & -x - - def query(self, x): - s = 0 - while x: - s += self.c[x] - x -= x & -x - return s - - -class Solution: - def reversePairs(self, nums: List[int]) -> int: - alls = sorted(set(nums)) - m = len(alls) - tree = BinaryIndexedTree(m) - ans = 0 - for v in nums[::-1]: - x = bisect_left(alls, v) + 1 - ans += tree.query(x - 1) - tree.update(x, 1) - return ans -``` - -### **Java** - - - ```java class Solution { private int[] nums; @@ -153,58 +96,6 @@ class Solution { } ``` -```java -class Solution { - public int reversePairs(int[] nums) { - Set s = new TreeSet<>(); - for (int v : nums) { - s.add(v); - } - Map alls = new HashMap<>(); - int i = 1; - for (int v : s) { - alls.put(v, i++); - } - BinaryIndexedTree tree = new BinaryIndexedTree(s.size()); - int ans = 0; - for (i = nums.length - 1; i >= 0; --i) { - int x = alls.get(nums[i]); - ans += tree.query(x - 1); - tree.update(x, 1); - } - return ans; - } -} - -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += x & -x; - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= x & -x; - } - return s; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -245,53 +136,6 @@ public: }; ``` -```cpp -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += x & -x; - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= x & -x; - } - return s; - } -}; - -class Solution { -public: - int reversePairs(vector& nums) { - vector alls = nums; - sort(alls.begin(), alls.end()); - alls.erase(unique(alls.begin(), alls.end()), alls.end()); - BinaryIndexedTree tree(alls.size()); - int ans = 0; - for (int i = nums.size() - 1; ~i; --i) { - int x = lower_bound(alls.begin(), alls.end(), nums[i]) - alls.begin() + 1; - ans += tree.query(x - 1); - tree.update(x, 1); - } - return ans; - } -}; -``` - -### **Go** - ```go func reversePairs(nums []int) int { n := len(nums) @@ -329,62 +173,9 @@ func reversePairs(nums []int) int { } ``` -```go -func reversePairs(nums []int) (ans int) { - s := map[int]bool{} - for _, v := range nums { - s[v] = true - } - alls := []int{} - for v := range s { - alls = append(alls, v) - } - sort.Ints(alls) - tree := newBinaryIndexedTree(len(alls)) - for i := len(nums) - 1; i >= 0; i-- { - x := sort.SearchInts(alls, nums[i]) + 1 - ans += tree.query(x - 1) - tree.update(x, 1) - } - return -} - -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (this *BinaryIndexedTree) update(x, delta int) { - for x <= this.n { - this.c[x] += delta - x += x & -x - } -} - -func (this *BinaryIndexedTree) query(x int) int { - s := 0 - for x > 0 { - s += this.c[x] - x -= x & -x - } - return s -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var reversePairs = function (nums) { - const mergeSort = (l, r) => { +```ts +function reversePairs(nums: number[]): number { + const mergeSort = (l: number, r: number): number => { if (l >= r) { return 0; } @@ -392,7 +183,7 @@ var reversePairs = function (nums) { let ans = mergeSort(l, mid) + mergeSort(mid + 1, r); let i = l; let j = mid + 1; - let t = []; + const t: number[] = []; while (i <= mid && j <= r) { if (nums[i] <= nums[j]) { t.push(nums[i++]); @@ -413,14 +204,16 @@ var reversePairs = function (nums) { return ans; }; return mergeSort(0, nums.length - 1); -}; +} ``` -### **TypeScript** - -```ts -function reversePairs(nums: number[]): number { - const mergeSort = (l: number, r: number): number => { +```js +/** + * @param {number[]} nums + * @return {number} + */ +var reversePairs = function (nums) { + const mergeSort = (l, r) => { if (l >= r) { return 0; } @@ -428,7 +221,7 @@ function reversePairs(nums: number[]): number { let ans = mergeSort(l, mid) + mergeSort(mid + 1, r); let i = l; let j = mid + 1; - const t: number[] = []; + let t = []; while (i <= mid && j <= r) { if (nums[i] <= nums[j]) { t.push(nums[i++]); @@ -449,11 +242,9 @@ function reversePairs(nums: number[]): number { return ans; }; return mergeSort(0, nums.length - 1); -} +}; ``` -### **C#** - ```cs public class Solution { private int[] nums; @@ -495,10 +286,199 @@ public class Solution { } ``` -### **...** + + +### 方法二:树状数组 + +树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作: + +1. **单点更新** `update(x, delta)`: 把序列 x 位置的数加上一个值 delta; +1. **前缀和查询** `query(x)`:查询序列 `[1,...x]` 区间的区间和,即位置 x 的前缀和。 + +这两个操作的时间复杂度均为 $O(\log n)$。 + +树状数组最基本的功能就是求比某点 x 小的点的个数(这里的比较是抽象的概念,可以是数的大小、坐标的大小、质量的大小等等)。 + +比如给定数组 `a[5] = {2, 5, 3, 4, 1}`,求 `b[i] = 位置 i 左边小于等于 a[i] 的数的个数`。对于此例,`b[5] = {0, 1, 1, 2, 0}`。 + +解决方案是直接遍历数组,每个位置先求出 `query(a[i])`,然后再修改树状数组 `update(a[i], 1)` 即可。当数的范围比较大时,需要进行离散化,即先进行去重并排序,然后对每个数字进行编号。 + + + +```python +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += x & -x + + def query(self, x): + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s + +class Solution: + def reversePairs(self, nums: List[int]) -> int: + alls = sorted(set(nums)) + m = len(alls) + tree = BinaryIndexedTree(m) + ans = 0 + for v in nums[::-1]: + x = bisect_left(alls, v) + 1 + ans += tree.query(x - 1) + tree.update(x, 1) + return ans ``` +```java +class Solution { + public int reversePairs(int[] nums) { + Set s = new TreeSet<>(); + for (int v : nums) { + s.add(v); + } + Map alls = new HashMap<>(); + int i = 1; + for (int v : s) { + alls.put(v, i++); + } + BinaryIndexedTree tree = new BinaryIndexedTree(s.size()); + int ans = 0; + for (i = nums.length - 1; i >= 0; --i) { + int x = alls.get(nums[i]); + ans += tree.query(x - 1); + tree.update(x, 1); + } + return ans; + } +} + +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +} +``` + +```cpp +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +}; + +class Solution { +public: + int reversePairs(vector& nums) { + vector alls = nums; + sort(alls.begin(), alls.end()); + alls.erase(unique(alls.begin(), alls.end()), alls.end()); + BinaryIndexedTree tree(alls.size()); + int ans = 0; + for (int i = nums.size() - 1; ~i; --i) { + int x = lower_bound(alls.begin(), alls.end(), nums[i]) - alls.begin() + 1; + ans += tree.query(x - 1); + tree.update(x, 1); + } + return ans; + } +}; +``` + +```go +func reversePairs(nums []int) (ans int) { + s := map[int]bool{} + for _, v := range nums { + s[v] = true + } + alls := []int{} + for v := range s { + alls = append(alls, v) + } + sort.Ints(alls) + tree := newBinaryIndexedTree(len(alls)) + for i := len(nums) - 1; i >= 0; i-- { + x := sort.SearchInts(alls, nums[i]) + 1 + ans += tree.query(x - 1) + tree.update(x, 1) + } + return +} + +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += x & -x + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= x & -x + } + return s +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23052. \344\270\244\344\270\252\351\223\276\350\241\250\347\232\204\347\254\254\344\270\200\344\270\252\345\205\254\345\205\261\350\212\202\347\202\271/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23052. \344\270\244\344\270\252\351\223\276\350\241\250\347\232\204\347\254\254\344\270\200\344\270\252\345\205\254\345\205\261\350\212\202\347\202\271/README.md" index a614011c2371f..e89be8ad9bc82 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23052. \344\270\244\344\270\252\351\223\276\350\241\250\347\232\204\347\254\254\344\270\200\344\270\252\345\205\254\345\205\261\350\212\202\347\202\271/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23052. \344\270\244\344\270\252\351\223\276\350\241\250\347\232\204\347\254\254\344\270\200\344\270\252\345\205\254\345\205\261\350\212\202\347\202\271/README.md" @@ -58,7 +58,7 @@ ## 解法 -**方法一:双指针** +### 方法一:双指针 我们可以用两个指针 $a$ 和 $b$ 分别指向两个链表的头节点,然后同时分别向后遍历,当 $a$ 到达链表 $A$ 的末尾时,令 $a$ 指向链表 $B$ 的头节点;当 $b$ 到达链表 $B$ 的末尾时,令 $b$ 指向链表 $A$ 的头节点。这样,当它们相遇时,所指向的节点就是第一个公共节点。 @@ -66,8 +66,6 @@ -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -85,8 +83,6 @@ class Solution: return a ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -111,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -135,8 +129,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -163,23 +155,20 @@ func getIntersectionNode(headA, headB *ListNode) *ListNode { } ``` -### **JavaScript** - -```js +```ts /** * Definition for singly-linked list. - * function ListNode(val) { - * this.val = val; - * this.next = null; + * 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) + * } * } */ -/** - * @param {ListNode} headA - * @param {ListNode} headB - * @return {ListNode} - */ -var getIntersectionNode = function (headA, headB) { +function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null { let a = headA; let b = headB; while (a != b) { @@ -187,25 +176,24 @@ var getIntersectionNode = function (headA, headB) { b = b ? b.next : headA; } return a; -}; +} ``` -### **TypeScript** - -```ts +```js /** * 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 ListNode(val) { + * this.val = val; + * this.next = null; * } */ -function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null { +/** + * @param {ListNode} headA + * @param {ListNode} headB + * @return {ListNode} + */ +var getIntersectionNode = function (headA, headB) { let a = headA; let b = headB; while (a != b) { @@ -213,11 +201,9 @@ function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): Li b = b ? b.next : headA; } return a; -} +}; ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -239,10 +225,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/README.md" index eac2d75c38233..f0e9a736b9f63 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23053 - I. \345\234\250\346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\346\237\245\346\211\276\346\225\260\345\255\227 I/README.md" @@ -35,7 +35,7 @@ ## 解法 -**方法一:二分查找** +### 方法一:二分查找 由于数组 `nums` 已排好序,我们可以使用二分查找的方法找到数组中第一个大于等于 `target` 的元素的下标 $l$,以及第一个大于 `target` 的元素的下标 $r$,那么 `target` 的个数就是 $r - l$。 @@ -43,8 +43,6 @@ -### **Python3** - ```python class Solution: def search(self, nums: List[int], target: int) -> int: @@ -53,8 +51,6 @@ class Solution: return r - l ``` -### **Java** - ```java class Solution { public int search(int[] nums, int target) { @@ -78,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +85,6 @@ public: }; ``` -### **Go** - ```go func search(nums []int, target int) int { l := sort.Search(len(nums), func(i int) bool { return nums[i] >= target }) @@ -101,7 +93,26 @@ func search(nums []int, target int) int { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn search(nums: Vec, target: i32) -> i32 { + let search = |x| { + let mut l = 0; + let mut r = nums.len(); + while l < r { + let mid = l + (r - l) / 2; + if nums[mid] >= x { + r = mid; + } else { + l = mid + 1; + } + } + l as i32 + }; + search(target + 1) - search(target) + } +} +``` ```js /** @@ -129,31 +140,6 @@ var search = function (nums, target) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn search(nums: Vec, target: i32) -> i32 { - let search = |x| { - let mut l = 0; - let mut r = nums.len(); - while l < r { - let mid = l + (r - l) / 2; - if nums[mid] >= x { - r = mid; - } else { - l = mid + 1; - } - } - l as i32 - }; - search(target + 1) - search(target) - } -} -``` - -### **C#** - ```cs public class Solution { public int Search(int[] nums, int target) { @@ -177,10 +163,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/README.md" index 8d426cbca26b9..84bf69f67a1dd 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23053 - II. 0\357\275\236n-1\344\270\255\347\274\272\345\244\261\347\232\204\346\225\260\345\255\227/README.md" @@ -25,7 +25,7 @@ ## 解法 -**方法一:二分查找** +### 方法一:二分查找 我们可以使用二分查找的方法找到这个缺失的数字。初始化左边界 $l=0$,右边界 $r=n$,其中 $n$ 是数组的长度。 @@ -37,8 +37,6 @@ -### **Python3** - ```python class Solution: def missingNumber(self, nums: List[int]) -> int: @@ -52,8 +50,6 @@ class Solution: return l ``` -### **Java** - ```java class Solution { public int missingNumber(int[] nums) { @@ -71,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +85,6 @@ public: }; ``` -### **Go** - ```go func missingNumber(nums []int) int { l, r := 0, len(nums) @@ -108,7 +100,22 @@ func missingNumber(nums []int) int { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn missing_number(nums: Vec) -> i32 { + let (mut l, mut r) = (0, nums.len() as i32); + while l < r { + let mut mid = (l + r) >> 1; + if nums[mid as usize] > mid { + r = mid; + } else { + l = mid + 1; + } + } + l + } +} +``` ```js /** @@ -130,25 +137,29 @@ var missingNumber = function (nums) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn missing_number(nums: Vec) -> i32 { - let (mut l, mut r) = (0, nums.len() as i32); - while l < r { - let mut mid = (l + r) >> 1; - if nums[mid as usize] > mid { +```cs +public class Solution { + public int MissingNumber(int[] nums) { + int l = 0, r = nums.Length; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] > mid) { r = mid; } else { l = mid + 1; } } - l + return l; } } ``` + + +### 方法二 + + + ```rust impl Solution { pub fn missing_number(nums: Vec) -> i32 { @@ -162,29 +173,6 @@ impl Solution { } ``` -### **C#** - -```cs -public class Solution { - public int MissingNumber(int[] nums) { - int l = 0, r = nums.Length; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid] > mid) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } -} -``` - -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/README.md" index d3a103d5e903d..6ef26f444839e 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23054. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\347\254\254k\345\244\247\350\212\202\347\202\271/README.md" @@ -40,7 +40,7 @@ ## 解法 -**方法一:反序中序遍历** +### 方法一:反序中序遍历 由于二叉搜索树的中序遍历是升序的,因此可以反序中序遍历,即先递归遍历右子树,再访问根节点,最后递归遍历左子树。 @@ -50,8 +50,6 @@ -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -78,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -145,8 +139,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -174,75 +166,6 @@ func kthLargest(root *TreeNode, k int) (ans int) { } ``` -利用 Go 的特性,中序遍历“生产”的数字传到 `channel`,返回第 `k` 个。 - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func kthLargest(root *TreeNode, k int) int { - ch := make(chan int) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - go inorder(ctx, root, ch) - for ; k > 1; k-- { - <-ch - } - return <-ch -} - -func inorder(ctx context.Context, cur *TreeNode, ch chan<- int) { - if cur != nil { - inorder(ctx, cur.Right, ch) - select { - case ch <- cur.Val: - case <-ctx.Done(): - return - } - inorder(ctx, cur.Left, ch) - } -} -``` - -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} root - * @param {number} k - * @return {number} - */ -var kthLargest = function (root, k) { - let ans = 0; - const dfs = root => { - if (!root || !k) { - return; - } - dfs(root.right); - if (--k == 0) { - ans = root.val; - } - dfs(root.left); - }; - dfs(root); - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -276,8 +199,6 @@ function kthLargest(root: TreeNode | null, k: number): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -317,7 +238,35 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {number} k + * @return {number} + */ +var kthLargest = function (root, k) { + let ans = 0; + const dfs = root => { + if (!root || !k) { + return; + } + dfs(root.right); + if (--k == 0) { + ans = root.val; + } + dfs(root.left); + }; + dfs(root); + return ans; +}; +``` ```cs /** @@ -352,10 +301,45 @@ public class Solution { } ``` -### **...** + -``` +### 方法二 + + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func kthLargest(root *TreeNode, k int) int { + ch := make(chan int) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go inorder(ctx, root, ch) + for ; k > 1; k-- { + <-ch + } + return <-ch +} + +func inorder(ctx context.Context, cur *TreeNode, ch chan<- int) { + if cur != nil { + inorder(ctx, cur.Right, ch) + select { + case ch <- cur.Val: + case <-ctx.Done(): + return + } + inorder(ctx, cur.Left, ch) + } +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/README.md" index 5923600ea79de..823f8c3d5cf07 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23055 - I. \344\272\214\345\217\211\346\240\221\347\232\204\346\267\261\345\272\246/README.md" @@ -28,7 +28,7 @@ ## 解法 -**方法一:递归** +### 方法一:递归 我们可以用递归的方法来解决这道题。递归的终止条件是当前节点为空,此时深度为 $0$;如果当前节点不为空,则当前的深度为其左右子树深度的最大值加 $1$,递归计算当前节点的左右子节点的深度,然后返回它们的最大值加 $1$。 @@ -36,8 +36,6 @@ -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -54,28 +52,6 @@ class Solution: return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) ``` -```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 maxDepth(self, root: TreeNode) -> int: - def dfs(root): - if root is None: - return 0 - l, r = dfs(root.left), dfs(root.right) - return 1 + max(l, r) - - return dfs(root) -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -96,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -119,8 +93,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -142,30 +114,6 @@ func maxDepth(root *TreeNode) int { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} root - * @return {number} - */ -var maxDepth = function (root) { - if (!root) { - return 0; - } - return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); -}; -``` - -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -202,7 +150,25 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var maxDepth = function (root) { + if (!root) { + return 0; + } + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); +}; +``` ```cs /** @@ -224,10 +190,32 @@ public class Solution { } ``` -### **...** + + +### 方法二 -``` + + +```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 maxDepth(self, root: TreeNode) -> int: + def dfs(root): + if root is None: + return 0 + l, r = dfs(root.left), dfs(root.right) + return 1 + max(l, r) + + return dfs(root) ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/README.md" index 0656059d874ac..ae14a51ae4e45 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23055 - II. \345\271\263\350\241\241\344\272\214\345\217\211\346\240\221/README.md" @@ -49,7 +49,7 @@ ## 解法 -**方法一:递归** +### 方法一:递归 我们设计一个递归函数 $dfs(root)$,函数返回值为 $root$ 节点的深度,如果 $root$ 节点不平衡,返回值为 $-1$。 @@ -66,8 +66,6 @@ -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -90,32 +88,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): - if root is None: - return (True, 0) - l, ld = dfs(root.left) - r, rd = dfs(root.right) - d = max(ld, rd) + 1 - if l and r and abs(ld - rd) <= 1: - return (True, d) - return (False, d) - - return dfs(root)[0] -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -145,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -176,8 +146,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -210,38 +178,6 @@ func abs(x int) int { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} root - * @return {boolean} - */ -var isBalanced = function (root) { - const dfs = root => { - if (!root) { - return 0; - } - const l = dfs(root.left); - const r = dfs(root.right); - if (l === -1 || r == -1 || Math.abs(l - r) > 1) { - return -1; - } - return 1 + Math.max(l, r); - }; - return dfs(root) !== -1; -}; -``` - -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -288,7 +224,33 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isBalanced = function (root) { + const dfs = root => { + if (!root) { + return 0; + } + const l = dfs(root.left); + const r = dfs(root.right); + if (l === -1 || r == -1 || Math.abs(l - r) > 1) { + return -1; + } + return 1 + Math.max(l, r); + }; + return dfs(root) !== -1; +}; +``` ```cs /** @@ -319,10 +281,36 @@ public class Solution { } ``` -### **...** + + +### 方法二 + + + +```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): + if root is None: + return (True, 0) + l, ld = dfs(root.left) + r, rd = dfs(root.right) + d = max(ld, rd) + 1 + if l and r and abs(ld - rd) <= 1: + return (True, d) + return (False, d) + + return dfs(root)[0] ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23056 - I. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23056 - I. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/README.md" index 632939cb291fd..89f3e0a09b895 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23056 - I. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23056 - I. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260/README.md" @@ -29,7 +29,7 @@ ## 解法 -**方法一:位运算** +### 方法一:位运算 由于数组中除了两个数字之外,其他数字都出现了两次,因此对数组中的所有数字进行异或运算,得到的结果即为两个只出现一次的数字的异或结果。 @@ -41,8 +41,6 @@ -### **Python3** - ```python class Solution: def singleNumbers(self, nums: List[int]) -> List[int]: @@ -56,8 +54,6 @@ class Solution: return [a, b] ``` -### **Java** - ```java class Solution { public int[] singleNumbers(int[] nums) { @@ -78,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +95,6 @@ public: }; ``` -### **Go** - ```go func singleNumbers(nums []int) []int { xs := 0 @@ -121,7 +113,23 @@ func singleNumbers(nums []int) []int { } ``` -### **JavaScript** +```ts +function singleNumbers(nums: number[]): number[] { + let xs = 0; + for (const x of nums) { + xs ^= x; + } + const lb = xs & -xs; + let a = 0; + for (const x of nums) { + if (x & lb) { + a ^= x; + } + } + const b = xs ^ a; + return [a, b]; +} +``` ```js /** @@ -145,8 +153,6 @@ var singleNumbers = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public int[] SingleNumbers(int[] nums) { @@ -167,30 +173,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function singleNumbers(nums: number[]): number[] { - let xs = 0; - for (const x of nums) { - xs ^= x; - } - const lb = xs & -xs; - let a = 0; - for (const x of nums) { - if (x & lb) { - a ^= x; - } - } - const b = xs ^ a; - return [a, b]; -} -``` - -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23056 - II. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260 II/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23056 - II. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260 II/README.md" index e6713c888723e..005d71232950a 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23056 - II. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260 II/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23056 - II. \346\225\260\347\273\204\344\270\255\346\225\260\345\255\227\345\207\272\347\216\260\347\232\204\346\254\241\346\225\260 II/README.md" @@ -30,7 +30,7 @@ ## 解法 -**方法一:位运算** +### 方法一:位运算 我们用一个长度为 32 的数组 $cnt$ 来统计所有数字的每一位中 $1$ 的出现次数。如果某一位的 $1$ 的出现次数能被 $3$ 整除,那么那个只出现一次的数字二进制表示中对应的那一位也是 $0$;否则,那个只出现一次的数字二进制表示中对应的那一位是 $1$。 @@ -38,8 +38,6 @@ -### **Python3** - ```python class Solution: def singleNumber(self, nums: List[int]) -> int: @@ -51,8 +49,6 @@ class Solution: return sum(1 << i for i in range(32) if cnt[i] % 3) ``` -### **Java** - ```java class Solution { public int singleNumber(int[] nums) { @@ -74,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +92,6 @@ public: }; ``` -### **Go** - ```go func singleNumber(nums []int) (ans int) { cnt := [32]int{} @@ -118,7 +110,24 @@ func singleNumber(nums []int) (ans int) { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn single_number(nums: Vec) -> i32 { + let mut counts = [0; 32]; + for num in nums.iter() { + for i in 0..32 { + counts[i] += (num >> i) & 1; + } + } + let mut res = 0; + for count in counts.iter().rev() { + res <<= 1; + res |= count % 3; + } + res + } +} +``` ```js /** @@ -143,29 +152,6 @@ var singleNumber = function (nums) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn single_number(nums: Vec) -> i32 { - let mut counts = [0; 32]; - for num in nums.iter() { - for i in 0..32 { - counts[i] += (num >> i) & 1; - } - } - let mut res = 0; - for count in counts.iter().rev() { - res <<= 1; - res |= count % 3; - } - res - } -} -``` - -### **C#** - ```cs public class Solution { public int SingleNumber(int[] nums) { @@ -188,10 +174,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23057 - II. \345\222\214\344\270\272s\347\232\204\350\277\236\347\273\255\346\255\243\346\225\260\345\272\217\345\210\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23057 - II. \345\222\214\344\270\272s\347\232\204\350\277\236\347\273\255\346\255\243\346\225\260\345\272\217\345\210\227/README.md" index ab76d9698e879..39ff6b2175d97 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23057 - II. \345\222\214\344\270\272s\347\232\204\350\277\236\347\273\255\346\255\243\346\225\260\345\272\217\345\210\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23057 - II. \345\222\214\344\270\272s\347\232\204\350\277\236\347\273\255\346\255\243\346\225\260\345\272\217\345\210\227/README.md" @@ -36,7 +36,7 @@ ## 解法 -**方法一:双指针** +### 方法一:双指针 我们可以使用双指针的方法,维护一个区间 $[l,.. r]$,使得区间内的数之和 $s$ 为 target,如果区间内的数之和小于 target,则右指针 $l$ 右移,如果区间内的数之和大于 target,则左指针 $l$ 右移,直到左指针到达 target 的一半为止。 @@ -44,8 +44,6 @@ -### **Python3** - ```python class Solution: def findContinuousSequence(self, target: int) -> List[List[int]]: @@ -63,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] findContinuousSequence(int target) { @@ -90,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +110,6 @@ public: }; ``` -### **Go** - ```go func findContinuousSequence(target int) (ans [][]int) { l, r := 1, 2 @@ -140,8 +132,6 @@ func findContinuousSequence(target int) (ans [][]int) { } ``` -### **JavaScript** - ```js /** * @param {number} target @@ -170,8 +160,6 @@ var findContinuousSequence = function (target) { }; ``` -### **C#** - ```cs public class Solution { public int[][] FindContinuousSequence(int target) { @@ -197,10 +185,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23057. \345\222\214\344\270\272s\347\232\204\344\270\244\344\270\252\346\225\260\345\255\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23057. \345\222\214\344\270\272s\347\232\204\344\270\244\344\270\252\346\225\260\345\255\227/README.md" index 98bea443b94bb..ddc0fbdd61f4a 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23057. \345\222\214\344\270\272s\347\232\204\344\270\244\344\270\252\346\225\260\345\255\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23057. \345\222\214\344\270\272s\347\232\204\344\270\244\344\270\252\346\225\260\345\255\227/README.md" @@ -202,4 +202,157 @@ public class Solution { ``` +## 解法 + +### 方法一 + + + +```python +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + l, r = 0, len(nums) - 1 + while l < r: + if nums[l] + nums[r] == target: + return [nums[l], nums[r]] + if nums[l] + nums[r] > target: + r -= 1 + else: + l += 1 +``` + +```java +class Solution { + public int[] twoSum(int[] nums, int target) { + int l = 0, r = nums.length - 1; + while (true) { + if (nums[l] + nums[r] == target) { + return new int[] {nums[l], nums[r]}; + } + if (nums[l] + nums[r] > target) { + --r; + } else { + ++l; + } + } + } +} +``` + +```cpp +class Solution { +public: + vector twoSum(vector& nums, int target) { + int l = 0, r = nums.size() - 1; + while (1) { + if (nums[l] + nums[r] == target) { + return {nums[l], nums[r]}; + } + if (nums[l] + nums[r] > target) { + --r; + } else { + ++l; + } + } + } +}; +``` + +```go +func twoSum(nums []int, target int) []int { + l, r := 0, len(nums)-1 + for { + if nums[l]+nums[r] == target { + return []int{nums[l], nums[r]} + } + if nums[l]+nums[r] > target { + r-- + } else { + l++ + } + } +} +``` + +```ts +function twoSum(nums: number[], target: number): number[] { + let l = 0; + let r = nums.length - 1; + while (nums[l] + nums[r] !== target) { + if (nums[l] + nums[r] < target) { + l++; + } else { + r--; + } + } + return [nums[l], nums[r]]; +} +``` + +```rust +use std::cmp::Ordering; + +impl Solution { + pub fn two_sum(nums: Vec, target: i32) -> Vec { + let mut l = 0; + let mut r = nums.len() - 1; + loop { + match target.cmp(&(nums[l] + nums[r])) { + Ordering::Less => { + r -= 1; + } + Ordering::Greater => { + l += 1; + } + Ordering::Equal => { + break vec![nums[l], nums[r]]; + } + } + } + } +} +``` + +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function (nums, target) { + let l = 0; + let r = nums.length - 1; + while (1) { + if (nums[l] + nums[r] == target) { + return [nums[l], nums[r]]; + } + if (nums[l] + nums[r] > target) { + --r; + } else { + ++l; + } + } +}; +``` + +```cs +public class Solution { + public int[] TwoSum(int[] nums, int target) { + int l = 0, r = nums.Length - 1; + while (true) { + if (nums[l] + nums[r] == target) { + return new int[] {nums[l], nums[r]}; + } + if (nums[l] + nums[r] > target) { + --r; + } else { + ++l; + } + } + } +} +``` + + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/README.md" index 9380c65b6db6d..37eb631221819 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - I. \347\277\273\350\275\254\345\215\225\350\257\215\351\241\272\345\272\217/README.md" @@ -42,7 +42,7 @@ ## 解法 -**方法一:字符串分割 + 反转拼接** +### 方法一:字符串分割 + 反转拼接 我们先去除字符串首尾的空格,然后将字符串按照空格分割成数组,再将数组反转,最后将数组拼接成以空格分割的字符串即可。 @@ -50,16 +50,12 @@ -### **Python3** - ```python class Solution: def reverseWords(self, s: str) -> str: return " ".join(s.strip().split()[::-1]) ``` -### **Java** - ```java class Solution { public String reverseWords(String s) { @@ -75,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +94,6 @@ public: }; ``` -### **Go** - ```go func reverseWords(s string) string { s = strings.Trim(s, " ") @@ -123,7 +115,25 @@ func reverseWords(s string) string { } ``` -### **JavaScript** +```ts +function reverseWords(s: string): string { + return s.trim().split(/\s+/).reverse().join(' '); +} +``` + +```rust +impl Solution { + pub fn reverse_words(mut s: String) -> String { + let mut res = s.trim().split(' ').rev().collect::>(); + for i in (0..res.len()).rev() { + if res[i] == "" { + res.remove(i); + } + } + res.join(" ") + } +} +``` ```js /** @@ -139,17 +149,33 @@ var reverseWords = function (s) { }; ``` -### **TypeScript** +```cs +public class Solution { + public string ReverseWords(string s) { + string[] tmp = s.Split(' ', StringSplitOptions.RemoveEmptyEntries); + Stack ss = new Stack(); + string res = ""; -API: + foreach (var i in tmp) { + ss.Push(i); + } -```ts -function reverseWords(s: string): string { - return s.trim().split(/\s+/).reverse().join(' '); + while (ss.Count > 0) { + res += ss.Pop(); + if (ss.Count > 0) { + res += " "; + } + } + return res; + } } ``` -双指针: + + +### 方法二 + + ```ts function reverseWords(s: string): string { @@ -171,26 +197,6 @@ function reverseWords(s: string): string { } ``` -### **Rust** - -传统: - -```rust -impl Solution { - pub fn reverse_words(mut s: String) -> String { - let mut res = s.trim().split(' ').rev().collect::>(); - for i in (0..res.len()).rev() { - if res[i] == "" { - res.remove(i); - } - } - res.join(" ") - } -} -``` - -函数式: - ```rust impl Solution { pub fn reverse_words(s: String) -> String { @@ -203,7 +209,11 @@ impl Solution { } ``` -使用 `split_whitespace()`: + + +### 方法三 + + ```rust impl Solution { @@ -213,7 +223,11 @@ impl Solution { } ``` -双指针: + + +### 方法四 + + ```rust impl Solution { @@ -250,34 +264,6 @@ impl Solution { } ``` -### **C#** - -```cs -public class Solution { - public string ReverseWords(string s) { - string[] tmp = s.Split(' ', StringSplitOptions.RemoveEmptyEntries); - Stack ss = new Stack(); - string res = ""; - - foreach (var i in tmp) { - ss.Push(i); - } - - while (ss.Count > 0) { - res += ss.Pop(); - if (ss.Count > 0) { - res += " "; - } - } - return res; - } -} -``` - -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/README.md" index 5ad171b32cd47..16bc919d887b7 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23058 - II. \345\267\246\346\227\213\350\275\254\345\255\227\347\254\246\344\270\262/README.md" @@ -28,7 +28,7 @@ ## 解法 -**方法一:模拟** +### 方法一:模拟 我们可以将字符串分为两部分,分别对两部分进行翻转,然后再对整个字符串进行翻转,即可得到结果。或者直接截取两个子串,然后拼接起来。 @@ -36,16 +36,12 @@ -### **Python3** - ```python class Solution: def reverseLeftWords(self, s: str, n: int) -> str: return s[n:] + s[:n] ``` -### **Java** - ```java class Solution { public String reverseLeftWords(String s, int n) { @@ -54,8 +50,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -65,41 +59,12 @@ public: }; ``` -```cpp -class Solution { -public: - string reverseLeftWords(string s, int n) { - reverse(s.begin(), s.begin() + n); - reverse(s.begin() + n, s.end()); - reverse(s.begin(), s.end()); - return s; - } -}; -``` - -### **JavaScript** - -```js -/** - * @param {string} s - * @param {number} n - * @return {string} - */ -var reverseLeftWords = function (s, n) { - return s.substring(n) + s.substring(0, n); -}; -``` - -### **Go** - ```go func reverseLeftWords(s string, n int) string { return s[n:] + s[:n] } ``` -### **Rust** - ```rust impl Solution { pub fn reverse_left_words(s: String, n: i32) -> String { @@ -109,7 +74,16 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {string} s + * @param {number} n + * @return {string} + */ +var reverseLeftWords = function (s, n) { + return s.substring(n) + s.substring(0, n); +}; +``` ```cs public class Solution { @@ -119,10 +93,24 @@ public class Solution { } ``` -### **...** + -``` +### 方法二 + + +```cpp +class Solution { +public: + string reverseLeftWords(string s, int n) { + reverse(s.begin(), s.begin() + n); + reverse(s.begin() + n, s.end()); + reverse(s.begin(), s.end()); + return s; + } +}; ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23059 - I. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\346\234\200\345\244\247\345\200\274/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23059 - I. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\346\234\200\345\244\247\345\200\274/README.md" index fedafce644d42..8dd34caea429d 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23059 - I. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\346\234\200\345\244\247\345\200\274/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23059 - I. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\346\234\200\345\244\247\345\200\274/README.md" @@ -31,9 +31,7 @@ ## 解法 - - -**方法一:单调队列** +### 方法一:单调队列 单调队列常见模型:找出滑动窗口中的最大值/最小值。模板: @@ -52,10 +50,6 @@ for i in range(n): -### **Python3** - - - ```python class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: @@ -72,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] maxSlidingWindow(int[] nums, int k) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func maxSlidingWindow(nums []int, k int) (ans []int) { q := []int{} @@ -146,36 +132,6 @@ func maxSlidingWindow(nums []int, k int) (ans []int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} k - * @return {number[]} - */ -var maxSlidingWindow = function (nums, k) { - const q = []; - const n = nums.length; - const ans = []; - for (let i = 0; i < n; ++i) { - while (q.length && i - q[0] + 1 > k) { - q.shift(); - } - while (q.length && nums[q[q.length - 1]] <= nums[i]) { - q.pop(); - } - q.push(i); - if (i >= k - 1) { - ans.push(nums[q[0]]); - } - } - return ans; -}; -``` - -### **TypeScript** - ```ts function maxSlidingWindow(nums: number[], k: number): number[] { const q: number[] = []; @@ -197,8 +153,6 @@ function maxSlidingWindow(nums: number[], k: number): number[] { } ``` -### **Rust** - ```rust use std::collections::VecDeque; impl Solution { @@ -224,7 +178,31 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var maxSlidingWindow = function (nums, k) { + const q = []; + const n = nums.length; + const ans = []; + for (let i = 0; i < n; ++i) { + while (q.length && i - q[0] + 1 > k) { + q.shift(); + } + while (q.length && nums[q[q.length - 1]] <= nums[i]) { + q.pop(); + } + q.push(i); + if (i >= k - 1) { + ans.push(nums[q[0]]); + } + } + return ans; +}; +``` ```cs public class Solution { @@ -248,10 +226,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23059 - II. \351\230\237\345\210\227\347\232\204\346\234\200\345\244\247\345\200\274/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23059 - II. \351\230\237\345\210\227\347\232\204\346\234\200\345\244\247\345\200\274/README.md" index f7cb574e1a8be..aa1e4728635ed 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23059 - II. \351\230\237\345\210\227\347\232\204\346\234\200\345\244\247\345\200\274/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23059 - II. \351\230\237\345\210\227\347\232\204\346\234\200\345\244\247\345\200\274/README.md" @@ -35,9 +35,7 @@ ## 解法 - - -**方法一:双队列** +### 方法一:双队列 我们维护两个队列 $q_1$ 和 $q_2$,其中 $q_1$ 用于存储所有元素,而 $q_2$ 用于存储当前队列中的最大值。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class MaxQueue: def __init__(self): @@ -86,10 +80,6 @@ class MaxQueue: # param_3 = obj.pop_front() ``` -### **Java** - - - ```java class MaxQueue { private Deque q1 = new ArrayDeque<>(); @@ -131,8 +121,6 @@ class MaxQueue { */ ``` -### **C++** - ```cpp class MaxQueue { public: @@ -177,8 +165,6 @@ private: */ ``` -### **Go** - ```go type MaxQueue struct { q1, q2 []int @@ -224,58 +210,6 @@ func (this *MaxQueue) Pop_front() int { */ ``` -### **JavaScript** - -```js -var MaxQueue = function () { - this.q1 = []; - this.q2 = []; -}; - -/** - * @return {number} - */ -MaxQueue.prototype.max_value = function () { - return this.q2.length ? this.q2[0] : -1; -}; - -/** - * @param {number} value - * @return {void} - */ -MaxQueue.prototype.push_back = function (value) { - while (this.q2.length && this.q2[this.q2.length - 1] < value) { - this.q2.pop(); - } - this.q1.push(value); - this.q2.push(value); -}; - -/** - * @return {number} - */ -MaxQueue.prototype.pop_front = function () { - if (!this.q1.length) { - return -1; - } - const ans = this.q1.shift(); - if (this.q2[0] == ans) { - this.q2.shift(); - } - return ans; -}; - -/** - * Your MaxQueue object will be instantiated and called as such: - * var obj = new MaxQueue() - * var param_1 = obj.max_value() - * obj.push_back(value) - * var param_3 = obj.pop_front() - */ -``` - -### **TypeScript** - ```ts class MaxQueue { private queue: number[]; @@ -316,8 +250,6 @@ class MaxQueue { */ ``` -### **Rust** - ```rust use std::collections::VecDeque; struct MaxQueue { @@ -368,7 +300,53 @@ impl MaxQueue { */ ``` -### **C#** +```js +var MaxQueue = function () { + this.q1 = []; + this.q2 = []; +}; + +/** + * @return {number} + */ +MaxQueue.prototype.max_value = function () { + return this.q2.length ? this.q2[0] : -1; +}; + +/** + * @param {number} value + * @return {void} + */ +MaxQueue.prototype.push_back = function (value) { + while (this.q2.length && this.q2[this.q2.length - 1] < value) { + this.q2.pop(); + } + this.q1.push(value); + this.q2.push(value); +}; + +/** + * @return {number} + */ +MaxQueue.prototype.pop_front = function () { + if (!this.q1.length) { + return -1; + } + const ans = this.q1.shift(); + if (this.q2[0] == ans) { + this.q2.shift(); + } + return ans; +}; + +/** + * Your MaxQueue object will be instantiated and called as such: + * var obj = new MaxQueue() + * var param_1 = obj.max_value() + * obj.push_back(value) + * var param_3 = obj.pop_front() + */ +``` ```cs public class MaxQueue { @@ -416,10 +394,6 @@ public class MaxQueue { */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23060. n\344\270\252\351\252\260\345\255\220\347\232\204\347\202\271\346\225\260/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23060. n\344\270\252\351\252\260\345\255\220\347\232\204\347\202\271\346\225\260/README.md" index 506a3f04c2920..2a951d99e7e3e 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23060. n\344\270\252\351\252\260\345\255\220\347\232\204\347\202\271\346\225\260/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23060. n\344\270\252\351\252\260\345\255\220\347\232\204\347\202\271\346\225\260/README.md" @@ -31,9 +31,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示投掷 $i$ 个骰子,点数和为 $j$ 的方案数。那么我们可以写出状态转移方程: @@ -51,10 +49,6 @@ $$ -### **Python3** - - - ```python class Solution: def dicesProbability(self, n: int) -> List[float]: @@ -70,25 +64,6 @@ class Solution: return [f[n][i] / m for i in range(n, 6 * n + 1)] ``` -```python -class Solution: - def dicesProbability(self, n: int) -> List[float]: - f = [0] + [1] * 6 - for i in range(2, n + 1): - g = [0] * (6 * i + 1) - for j in range(i, 6 * i + 1): - for k in range(1, 7): - if 0 <= j - k < len(f): - g[j] += f[j - k] - f = g - m = pow(6, n) - return [f[j] / m for j in range(n, 6 * n + 1)] -``` - -### **Java** - - - ```java class Solution { public double[] dicesProbability(int n) { @@ -115,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +118,6 @@ public: }; ``` -### **Go** - ```go func dicesProbability(n int) (ans []float64) { f := make([][]int, n+1) @@ -173,28 +144,6 @@ func dicesProbability(n int) (ans []float64) { } ``` -```go -func dicesProbability(n int) []float64 { - dp := make([]float64, 7) - for i := 1; i <= 6; i++ { - dp[i] = 1.0 / 6.0 - } - for i := 2; i <= n; i++ { - n := len(dp) - tmp := make([]float64, 6*i+1) - for j := 0; j < n; j++ { - for k := 1; k <= 6; k++ { - tmp[j+k] += dp[j] / 6.0 - } - } - dp = tmp - } - return dp[n:] -} -``` - -### **JavaScript** - ```js /** * @param {number} n @@ -223,8 +172,6 @@ var dicesProbability = function (n) { }; ``` -### **C#** - ```cs public class Solution { public double[] DicesProbability(int n) { @@ -247,10 +194,47 @@ public class Solution { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def dicesProbability(self, n: int) -> List[float]: + f = [0] + [1] * 6 + for i in range(2, n + 1): + g = [0] * (6 * i + 1) + for j in range(i, 6 * i + 1): + for k in range(1, 7): + if 0 <= j - k < len(f): + g[j] += f[j - k] + f = g + m = pow(6, n) + return [f[j] / m for j in range(n, 6 * n + 1)] ``` +```go +func dicesProbability(n int) []float64 { + dp := make([]float64, 7) + for i := 1; i <= 6; i++ { + dp[i] = 1.0 / 6.0 + } + for i := 2; i <= n; i++ { + n := len(dp) + tmp := make([]float64, 6*i+1) + for j := 0; j < n; j++ { + for k := 1; k <= 6; k++ { + tmp[j+k] += dp[j] / 6.0 + } + } + dp = tmp + } + return dp[n:] +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23061. \346\211\221\345\205\213\347\211\214\344\270\255\347\232\204\351\241\272\345\255\220/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23061. \346\211\221\345\205\213\347\211\214\344\270\255\347\232\204\351\241\272\345\255\220/README.md" index 9436e3b57d91e..a07050b8ca3ea 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23061. \346\211\221\345\205\213\347\211\214\344\270\255\347\232\204\351\241\272\345\255\220/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23061. \346\211\221\345\205\213\347\211\214\344\270\255\347\232\204\351\241\272\345\255\220/README.md" @@ -32,9 +32,7 @@ ## 解法 - - -**方法一:遍历** +### 方法一:遍历 我们首先明确顺子不成立的核心条件: @@ -47,10 +45,6 @@ -### **Python3** - - - ```python class Solution: def isStraight(self, nums: List[int]) -> bool: @@ -67,10 +61,6 @@ class Solution: return mx - mi <= 4 ``` -### **Java** - - - ```java class Solution { public boolean isStraight(int[] nums) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func isStraight(nums []int) bool { vis := map[int]bool{} @@ -137,34 +123,6 @@ func isStraight(nums []int) bool { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {boolean} - */ -var isStraight = function (nums) { - const vis = new Array(14).fill(false); - let mi = 20; - let mx = -1; - for (const x of nums) { - if (x == 0) { - continue; - } - if (vis[x]) { - return false; - } - vis[x] = true; - mi = Math.min(mi, x); - mx = Math.max(mx, x); - } - return mx - mi <= 4; -}; -``` - -### **TypeScript** - ```ts function isStraight(nums: number[]): boolean { nums.sort((a, b) => a - b); @@ -180,8 +138,6 @@ function isStraight(nums: number[]): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_straight(mut nums: Vec) -> bool { @@ -199,7 +155,29 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number[]} nums + * @return {boolean} + */ +var isStraight = function (nums) { + const vis = new Array(14).fill(false); + let mi = 20; + let mx = -1; + for (const x of nums) { + if (x == 0) { + continue; + } + if (vis[x]) { + return false; + } + vis[x] = true; + mi = Math.min(mi, x); + mx = Math.max(mx, x); + } + return mx - mi <= 4; +}; +``` ```cs public class Solution { @@ -222,10 +200,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/README.md" index ca57b9542c885..e1a5d9c6a1033 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23062. \345\234\206\345\234\210\344\270\255\346\234\200\345\220\216\345\211\251\344\270\213\347\232\204\346\225\260\345\255\227/README.md" @@ -35,9 +35,7 @@ ## 解法 - - -**方法一:数学 + 递归(迭代)** +### 方法一:数学 + 递归(迭代) 我们不妨设 $f(n, m)$ 表示从 $n$ 个数中每次删除第 $m$ 个,最后剩下的是第几个数字。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def lastRemaining(self, n: int, m: int) -> int: @@ -69,19 +63,6 @@ class Solution: return f(n, m) ``` -```python -class Solution: - def lastRemaining(self, n: int, m: int) -> int: - f = 0 - for i in range(2, n + 1): - f = (f + m) % i - return f -``` - -### **Java** - - - ```java class Solution { public int lastRemaining(int n, int m) { @@ -98,20 +79,6 @@ class Solution { } ``` -```java -class Solution { - public int lastRemaining(int n, int m) { - int f = 0; - for (int i = 2; i <= n; ++i) { - f = (f + m) % i; - } - return f; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -129,21 +96,6 @@ public: }; ``` -```cpp -class Solution { -public: - int lastRemaining(int n, int m) { - int f = 0; - for (int i = 2; i <= n; ++i) { - f = (f + m) % i; - } - return f; - } -}; -``` - -### **Go** - ```go func lastRemaining(n int, m int) int { var f func(n, m int) int @@ -158,18 +110,6 @@ func lastRemaining(n int, m int) int { } ``` -```go -func lastRemaining(n int, m int) int { - f := 0 - for i := 2; i <= n; i++ { - f = (f + m) % i - } - return f -} -``` - -### **JavaScript** - ```js /** * @param {number} n @@ -185,8 +125,6 @@ var lastRemaining = function (n, m) { }; ``` -### **C#** - ```cs public class Solution { public int LastRemaining(int n, int m) { @@ -199,10 +137,56 @@ public class Solution { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def lastRemaining(self, n: int, m: int) -> int: + f = 0 + for i in range(2, n + 1): + f = (f + m) % i + return f ``` +```java +class Solution { + public int lastRemaining(int n, int m) { + int f = 0; + for (int i = 2; i <= n; ++i) { + f = (f + m) % i; + } + return f; + } +} +``` + +```cpp +class Solution { +public: + int lastRemaining(int n, int m) { + int f = 0; + for (int i = 2; i <= n; ++i) { + f = (f + m) % i; + } + return f; + } +}; +``` + +```go +func lastRemaining(n int, m int) int { + f := 0 + for i := 2; i <= n; i++ { + f = (f + m) % i + } + return f +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23063. \350\202\241\347\245\250\347\232\204\346\234\200\345\244\247\345\210\251\346\266\246/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23063. \350\202\241\347\245\250\347\232\204\346\234\200\345\244\247\345\210\251\346\266\246/README.md" index b596b6588e54d..7b0979d94267b 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23063. \350\202\241\347\245\250\347\232\204\346\234\200\345\244\247\345\210\251\346\266\246/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23063. \350\202\241\347\245\250\347\232\204\346\234\200\345\244\247\345\210\251\346\266\246/README.md" @@ -32,7 +32,7 @@ ## 解法 -**方法一:动态规划** +### 方法一:动态规划 我们可以枚举当前的股票价格作为卖出价格,那么买入价格就是在它之前的最低股票价格,此时的利润就是卖出价格减去买入价格。我们可以用一个变量 `mi` 记录之前的最低股票价格,用一个变量 `ans` 记录最大利润,找出最大利润即可。 @@ -40,8 +40,6 @@ -### **Python3** - ```python class Solution: def maxProfit(self, prices: List[int]) -> int: @@ -52,8 +50,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxProfit(int[] prices) { @@ -67,8 +63,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -83,8 +77,6 @@ public: }; ``` -### **Go** - ```go func maxProfit(prices []int) (ans int) { mi := 1 << 30 @@ -96,26 +88,6 @@ func maxProfit(prices []int) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} prices - * @return {number} - */ -var maxProfit = function (prices) { - let mi = 1 << 30; - let ans = 0; - for (const x of prices) { - ans = Math.max(ans, x - mi); - mi = Math.min(mi, x); - } - return ans; -}; -``` - -### **TypeScript** - ```ts function maxProfit(prices: number[]): number { let res = 0; @@ -128,8 +100,6 @@ function maxProfit(prices: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_profit(prices: Vec) -> i32 { @@ -144,7 +114,21 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function (prices) { + let mi = 1 << 30; + let ans = 0; + for (const x of prices) { + ans = Math.max(ans, x - mi); + mi = Math.min(mi, x); + } + return ans; +}; +``` ```cs public class Solution { @@ -160,10 +144,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23064. \346\261\2021+2+\342\200\246+n/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23064. \346\261\2021+2+\342\200\246+n/README.md" index 622634f52d1a6..a3bef330313c0 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23064. \346\261\2021+2+\342\200\246+n/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23064. \346\261\2021+2+\342\200\246+n/README.md" @@ -28,20 +28,16 @@ ## 解法 -递归,结合**逻辑与**短路运算符求解。 +### 方法一 -### **Python3** - ```python class Solution: def sumNums(self, n: int) -> int: return n and (n + self.sumNums(n - 1)) ``` -### **Java** - ```java class Solution { public int sumNums(int n) { @@ -52,8 +48,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -64,20 +58,6 @@ public: }; ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number} - */ -var sumNums = function (n) { - return (n ** 2 + n) >> 1; -}; -``` - -### **Go** - ```go func sumNums(n int) int { s := 0 @@ -91,16 +71,12 @@ func sumNums(n int) int { } ``` -### **TypeScript** - ```ts var sumNums = function (n: number): number { return n && n + sumNums(n - 1); }; ``` -### **Rust** - ```rust impl Solution { pub fn sum_nums(mut n: i32) -> i32 { @@ -116,7 +92,15 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number} n + * @return {number} + */ +var sumNums = function (n) { + return (n ** 2 + n) >> 1; +}; +``` ```cs public class Solution { @@ -131,13 +115,8 @@ public class Solution { return n == 0 || helper(n - 1); } } - -``` - -### **...** - -``` - ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23065. \344\270\215\347\224\250\345\212\240\345\207\217\344\271\230\351\231\244\345\201\232\345\212\240\346\263\225/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23065. \344\270\215\347\224\250\345\212\240\345\207\217\344\271\230\351\231\244\345\201\232\345\212\240\346\263\225/README.md" index e89bf729a1e2d..1d2a92c422e53 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23065. \344\270\215\347\224\250\345\212\240\345\207\217\344\271\230\351\231\244\345\201\232\345\212\240\346\263\225/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23065. \344\270\215\347\224\250\345\212\240\345\207\217\344\271\230\351\231\244\345\201\232\345\212\240\346\263\225/README.md" @@ -24,9 +24,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 两数字 $a$, $b$ 求和。 @@ -50,12 +48,6 @@ -### **Python3** - - - -由于 Python `int` 是无限长整型,左移不会自动溢出,因此需要特殊处理。 - ```python class Solution: def add(self, a: int, b: int) -> int: @@ -66,10 +58,6 @@ class Solution: return a if a < 0x80000000 else ~(a ^ 0xFFFFFFFF) ``` -### **Java** - - - ```java class Solution { public int add(int a, int b) { @@ -83,19 +71,6 @@ class Solution { } ``` -```java -class Solution { - public int add(int a, int b) { - if (b == 0) { - return a; - } - return add(a ^ b, (a & b) << 1); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -110,8 +85,6 @@ public: }; ``` -### **Go** - ```go func add(a int, b int) int { if b == 0 { @@ -121,7 +94,16 @@ func add(a int, b int) int { } ``` -### **JavaScript** +```ts +function add(a: number, b: number): number { + while (b) { + const c = (a & b) << 1; + a ^= b; + b = c; + } + return a; +} +``` ```js /** @@ -137,8 +119,6 @@ var add = function (a, b) { }; ``` -### **C#** - ```cs public class Solution { public int Add(int a, int b) { @@ -153,23 +133,23 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function add(a: number, b: number): number { - while (b) { - const c = (a & b) << 1; - a ^= b; - b = c; - } - return a; -} -``` + -### **...** +### 方法二 -``` + +```java +class Solution { + public int add(int a, int b) { + if (b == 0) { + return a; + } + return add(a ^ b, (a & b) << 1); + } +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23066. \346\236\204\345\273\272\344\271\230\347\247\257\346\225\260\347\273\204/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23066. \346\236\204\345\273\272\344\271\230\347\247\257\346\225\260\347\273\204/README.md" index 567ebad315cbf..a7a4ccdb5d916 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23066. \346\236\204\345\273\272\344\271\230\347\247\257\346\225\260\347\273\204/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23066. \346\236\204\345\273\272\344\271\230\347\247\257\346\225\260\347\273\204/README.md" @@ -25,9 +25,7 @@ ## 解法 - - -**方法一:两次遍历** +### 方法一:两次遍历 我们先创建一个长度为 $n$ 的答案数组 $ans$。 @@ -41,10 +39,6 @@ -### **Python3** - - - ```python class Solution: def constructArr(self, a: List[int]) -> List[int]: @@ -60,10 +54,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] constructArr(int[] a) { @@ -82,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +91,6 @@ public: }; ``` -### **Go** - ```go func constructArr(a []int) []int { n := len(a) @@ -121,8 +107,6 @@ func constructArr(a []int) []int { } ``` -### **TypeScript** - ```ts function constructArr(a: number[]): number[] { const n = a.length; @@ -139,8 +123,6 @@ function constructArr(a: number[]): number[] { } ``` -### **JavaScript** - ```js /** * @param {number[]} a @@ -161,8 +143,6 @@ var constructArr = function (a) { }; ``` -### **C#** - ```cs public class Solution { public int[] ConstructArr(int[] a) { @@ -182,10 +162,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/README.md" index 596469aeefe10..d3f273540e389 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23067. \346\212\212\345\255\227\347\254\246\344\270\262\350\275\254\346\215\242\346\210\220\346\225\264\346\225\260/README.md" @@ -64,18 +64,10 @@ ## 解法 - - -遍历字符串,注意做溢出处理。 - -同[字符串转换整数 (atoi)](/solution/0000-0099/0008.String%20to%20Integer%20%28atoi%29/README.md)。 +### 方法一 -### **Python3** - - - ```python class Solution: def strToInt(self, str: str) -> int: @@ -107,10 +99,6 @@ class Solution: return sign * res ``` -### **Java** - - - ```java class Solution { public int strToInt(String str) { @@ -139,37 +127,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {string} str - * @return {number} - */ -var strToInt = function (str) { - let res = ''; - let l = 1; - for (let i = 0; i < str.length; i++) { - if (l && str[i] === ' ') continue; - if (l && (str[i] === '+' || str[i] === '-')) { - l = 0; - res += str[i]; - continue; - } - if (str[i].match(/[0-9]/)) { - l = 0; - res += str[i]; - } else break; - } - res = isNaN(+res) ? 0 : +res; - if (res > 2147483647) return 2147483647; - if (res < -2147483648) return -2147483648; - return res; -}; -``` - -### **Go** - ```go func strToInt(str string) int { n, sign, i, x := len(str), 1, 0, 0 @@ -217,7 +174,32 @@ func strToInt(str string) int { } ``` -### **C#** +```js +/** + * @param {string} str + * @return {number} + */ +var strToInt = function (str) { + let res = ''; + let l = 1; + for (let i = 0; i < str.length; i++) { + if (l && str[i] === ' ') continue; + if (l && (str[i] === '+' || str[i] === '-')) { + l = 0; + res += str[i]; + continue; + } + if (str[i].match(/[0-9]/)) { + l = 0; + res += str[i]; + } else break; + } + res = isNaN(+res) ? 0 : +res; + if (res > 2147483647) return 2147483647; + if (res < -2147483648) return -2147483648; + return res; +}; +``` ```cs public class Solution { @@ -278,10 +260,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/README.md" index 74a8c34a44e2d..a88de5ad3b7dc 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23068 - I. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/README.md" @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 从上到下遍历二叉树,找到第一个值位于 $[p.val,.. q.val]$ 之间的结点即可。既可以用迭代实现,也可以用递归实现。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -76,30 +70,6 @@ class Solution: return root ``` -```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 lowestCommonAncestor( - self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode' - ) -> 'TreeNode': - if root.val < p.val and root.val < q.val: - return self.lowestCommonAncestor(root.right, p, q) - if root.val > p.val and root.val > q.val: - return self.lowestCommonAncestor(root.left, p, q) - return root -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -125,31 +95,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -class Solution { - public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { - if (root.val < p.val && root.val < q.val) { - return lowestCommonAncestor(root.right, p, q); - } - if (root.val > p.val && root.val > q.val) { - return lowestCommonAncestor(root.left, p, q); - } - return root; - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -174,34 +119,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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { - while (1) { - if (root->val < p->val && root->val < q->val) { - root = root->right; - } else if (root->val > p->val && root->val > q->val) { - root = root->left; - } else { - return root; - } - } - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -223,57 +140,6 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ - -func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { - for { - if root.Val < p.Val && root.Val < q.Val { - root = root.Right - } else if root.Val > p.Val && root.Val > q.Val { - root = root.Left - } else { - return root - } - } -} -``` - -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} root - * @param {TreeNode} p - * @param {TreeNode} q - * @return {TreeNode} - */ -var lowestCommonAncestor = function (root, p, q) { - if (root.val < p.val && root.val < q.val) { - return lowestCommonAncestor(root.right, p, q); - } else if (root.val > p.val && root.val > q.val) { - return lowestCommonAncestor(root.left, p, q); - } - return root; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -306,42 +172,6 @@ function lowestCommonAncestor( } ``` -```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 lowestCommonAncestor( - root: TreeNode | null, - p: TreeNode | null, - q: TreeNode | null, -): TreeNode | null { - if (root == null) { - return root; - } - while (true) { - if (root.val > p.val && root.val > q.val) { - root = root.left; - } else if (root.val < p.val && root.val < q.val) { - root = root.right; - } else { - return root; - } - } -} -``` - -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -390,10 +220,162 @@ impl Solution { } ``` -### **...** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} p + * @param {TreeNode} q + * @return {TreeNode} + */ +var lowestCommonAncestor = function (root, p, q) { + if (root.val < p.val && root.val < q.val) { + return lowestCommonAncestor(root.right, p, q); + } else if (root.val > p.val && root.val > q.val) { + return lowestCommonAncestor(root.left, p, q); + } + return root; +}; +``` + + + +### 方法二 + + + +```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 lowestCommonAncestor( + self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode' + ) -> 'TreeNode': + if root.val < p.val and root.val < q.val: + return self.lowestCommonAncestor(root.right, p, q) + if root.val > p.val and root.val > q.val: + return self.lowestCommonAncestor(root.left, p, q) + return root ``` +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root.val < p.val && root.val < q.val) { + return lowestCommonAncestor(root.right, p, q); + } + if (root.val > p.val && root.val > q.val) { + return lowestCommonAncestor(root.left, p, q); + } + return root; + } +} +``` + +```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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + while (1) { + if (root->val < p->val && root->val < q->val) { + root = root->right; + } else if (root->val > p->val && root->val > q->val) { + root = root->left; + } else { + return root; + } + } + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + for { + if root.Val < p.Val && root.Val < q.Val { + root = root.Right + } else if root.Val > p.Val && root.Val > q.Val { + root = root.Left + } else { + return root + } + } +} +``` + +```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 lowestCommonAncestor( + root: TreeNode | null, + p: TreeNode | null, + q: TreeNode | null, +): TreeNode | null { + if (root == null) { + return root; + } + while (true) { + if (root.val > p.val && root.val > q.val) { + root = root.left; + } else if (root.val < p.val && root.val < q.val) { + root = root.right; + } else { + return root; + } + } +} ``` + + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23068 - II. \344\272\214\345\217\211\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23068 - II. \344\272\214\345\217\211\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/README.md" index eee9071c533bc..5fa557eb52256 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23068 - II. \344\272\214\345\217\211\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23068 - II. \344\272\214\345\217\211\346\240\221\347\232\204\346\234\200\350\277\221\345\205\254\345\205\261\347\245\226\345\205\210/README.md" @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 根据“**最近公共祖先**”的定义,若 $root$ 是 $p$, $q$ 的最近公共祖先,则只可能为以下情况之一: @@ -62,10 +60,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -90,10 +84,6 @@ class Solution: return root ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -116,34 +106,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} root - * @param {TreeNode} p - * @param {TreeNode} q - * @return {TreeNode} - */ -var lowestCommonAncestor = function (root, p, q) { - if (!root || root == p || root == q) return root; - const left = lowestCommonAncestor(root.left, p, q); - const right = lowestCommonAncestor(root.right, p, q); - if (!left) return right; - if (!right) return left; - return root; -}; -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -179,8 +141,6 @@ public: }; ``` -### **Go** - ```go func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { if root == nil || root == p || root == q { @@ -198,8 +158,6 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -237,8 +195,6 @@ function lowestCommonAncestor( } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -289,10 +245,30 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} p + * @param {TreeNode} q + * @return {TreeNode} + */ +var lowestCommonAncestor = function (root, p, q) { + if (!root || root == p || root == q) return root; + const left = lowestCommonAncestor(root.left, p, q); + const right = lowestCommonAncestor(root.right, p, q); + if (!left) return right; + if (!right) return left; + return root; +}; ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/README.md" index 096962d11c763..26b88ccecbbb3 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 001. \346\225\264\346\225\260\351\231\244\346\263\225/README.md" @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:模拟 + 快速幂** +### 方法一:模拟 + 快速幂 除法本质上就是减法,题目要求我们计算出两个数相除之后的取整结果,其实就是计算被除数是多少个除数加上一个小于除数的数构成的。但是一次循环只能做一次减法,效率太低会导致超时,可借助快速幂的思想进行优化。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def divide(self, a: int, b: int) -> int: @@ -99,10 +93,6 @@ class Solution: return ans if sign else -ans ``` -### **Java** - - - ```java class Solution { public int divide(int a, int b) { @@ -131,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go func divide(a int, b int) int { if b == 1 { @@ -200,8 +186,6 @@ func divide(a int, b int) int { } ``` -### **TypeScript** - ```ts function divide(a: number, b: number): number { if (b === 1) { @@ -233,8 +217,6 @@ function divide(a: number, b: number): number { } ``` -### **C#** - ```cs public class Solution { public int Divide(int a, int b) { @@ -263,10 +245,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/README.md" index 4c1c8ee3535f0..58704df58a396 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 002. \344\272\214\350\277\233\345\210\266\345\212\240\346\263\225/README.md" @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们用一个变量 $carry$ 记录当前的进位,用两个指针 $i$ 和 $j$ 分别指向 $a$ 和 $b$ 的末尾,从末尾到开头逐位相加即可。 @@ -48,33 +46,12 @@ -### **Python3** - - - ```python class Solution: def addBinary(self, a: str, b: str) -> str: return bin(int(a, 2) + int(b, 2))[2:] ``` -```python -class Solution: - def addBinary(self, a: str, b: str) -> str: - ans = [] - i, j, carry = len(a) - 1, len(b) - 1, 0 - while i >= 0 or j >= 0 or carry: - carry += (0 if i < 0 else int(a[i])) + (0 if j < 0 else int(b[j])) - carry, v = divmod(carry, 2) - ans.append(str(v)) - i, j = i - 1, j - 1 - return ''.join(ans[::-1]) -``` - -### **Java** - - - ```java class Solution { public String addBinary(String a, String b) { @@ -90,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +84,6 @@ public: }; ``` -### **Go** - ```go func addBinary(a string, b string) string { i, j := len(a)-1, len(b)-1 @@ -132,31 +105,12 @@ func addBinary(a string, b string) string { } ``` -### **TypeScript** - ```ts function addBinary(a: string, b: string): string { return (BigInt('0b' + a) + BigInt('0b' + b)).toString(2); } ``` -```ts -function addBinary(a: string, b: string): string { - let i = a.length - 1; - let j = b.length - 1; - let ans: number[] = []; - for (let carry = 0; i >= 0 || j >= 0 || carry; --i, --j) { - carry += (i >= 0 ? a[i] : '0').charCodeAt(0) - '0'.charCodeAt(0); - carry += (j >= 0 ? b[j] : '0').charCodeAt(0) - '0'.charCodeAt(0); - ans.push(carry % 2); - carry >>= 1; - } - return ans.reverse().join(''); -} -``` - -### **Rust** - ```rust impl Solution { pub fn add_binary(a: String, b: String) -> String { @@ -183,10 +137,59 @@ impl Solution { } ``` -### **...** +```cs +public class Solution { + public string AddBinary(string a, string b) { + int i = a.Length - 1; + int j = b.Length - 1; + var sb = new StringBuilder(); + for (int carry = 0; i >= 0 || j >= 0 || carry > 0; --i, --j) { + carry += i >= 0 ? a[i] - '0' : 0; + carry += j >= 0 ? b[j] - '0' : 0; + sb.Append(carry % 2); + carry /= 2; + } + var ans = sb.ToString().ToCharArray(); + Array.Reverse(ans); + return new string(ans); + } +} +``` + + + +### 方法二 + + +```python +class Solution: + def addBinary(self, a: str, b: str) -> str: + ans = [] + i, j, carry = len(a) - 1, len(b) - 1, 0 + while i >= 0 or j >= 0 or carry: + carry += (0 if i < 0 else int(a[i])) + (0 if j < 0 else int(b[j])) + carry, v = divmod(carry, 2) + ans.append(str(v)) + i, j = i - 1, j - 1 + return ''.join(ans[::-1]) ``` +```ts +function addBinary(a: string, b: string): string { + let i = a.length - 1; + let j = b.length - 1; + let ans: number[] = []; + for (let carry = 0; i >= 0 || j >= 0 || carry; --i, --j) { + carry += (i >= 0 ? a[i] : '0').charCodeAt(0) - '0'.charCodeAt(0); + carry += (j >= 0 ? b[j] : '0').charCodeAt(0) - '0'.charCodeAt(0); + ans.push(carry % 2); + carry >>= 1; + } + return ans.reverse().join(''); +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/README.md" index e6aab0b7e107c..17f9eed6faba6 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 003. \345\211\215 n \344\270\252\346\225\260\345\255\227\344\272\214\350\277\233\345\210\266\344\270\255 1 \347\232\204\344\270\252\346\225\260/README.md" @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示整数 $i$ 的二进制表示中 $1$ 的个数。那么对于一个整数 $i$,它的二进制表示中 $1$ 的个数为 $f[i \wedge (i - 1)] + 1$,其中 $i \wedge (i - 1)$ 是将 $i$ 的二进制表示中的最低位的 $1$ 变成 $0$ 之后的数,显然 $i \wedge (i - 1) \lt i$,且 $f[i \wedge (i - 1)]$ 已经被计算出来了,因此我们可以得到状态转移方程: @@ -71,10 +69,6 @@ $$ -### **Python3** - - - ```python class Solution: def countBits(self, n: int) -> List[int]: @@ -84,10 +78,6 @@ class Solution: return f ``` -### **Java** - - - ```java class Solution { public int[] countBits(int n) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func countBits(n int) []int { f := make([]int, n+1) @@ -127,8 +113,6 @@ func countBits(n int) []int { } ``` -### **TypeScript** - ```ts function countBits(n: number): number[] { const f: number[] = Array(n + 1).fill(0); @@ -139,10 +123,6 @@ function countBits(n: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/README.md" index cf427e49bd507..11b4bf20d9498 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 004. \345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/README.md" @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 我们可以统计所有数字中每个位上出现的 $1$ 的个数,然后对 $3$ 取模。如果某一位上的出现的 $1$ 的个数无法被 $3$ 整除,说明只出现一次的数字在该位上是 $1$,否则是 $0$。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def singleNumber(self, nums: List[int]) -> int: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int singleNumber(int[] nums) { @@ -91,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +99,6 @@ public: }; ``` -### **Go** - ```go func singleNumber(nums []int) int { var ans int32 @@ -128,8 +114,6 @@ func singleNumber(nums []int) int { } ``` -### **TypeScript** - ```ts function singleNumber(nums: number[]): number { let ans = 0; @@ -145,10 +129,6 @@ function singleNumber(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/README.md" index d12e2222b995e..38685fe37ec45 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 005. \345\215\225\350\257\215\351\225\277\345\272\246\347\232\204\346\234\200\345\244\247\344\271\230\347\247\257/README.md" @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:位运算 + 枚举** +### 方法一:位运算 + 枚举 由于题目限定了字符串中只包含英语的小写字母,因此每个字符串可以用一个 $32$ 位整数表示,该整数的每个二进制位都是 $0$ 或 $1$,分别对应字符串的每个字母是否出现。这样一来,我们判断两个字符串是否含有相同字符,只需要将对应的整数进行按位与运算,即可得到一个新的整数,如果新的整数的二进制表示中的每一位都是 $0$,就说明两个字符串不含有相同的字符。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def maxProduct(self, words: List[str]) -> int: @@ -77,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxProduct(String[] words) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func maxProduct(words []string) (ans int) { n := len(words) @@ -153,8 +139,6 @@ func maxProduct(words []string) (ans int) { } ``` -### **TypeScript** - ```ts function maxProduct(words: string[]): number { const n = words.length; @@ -176,10 +160,6 @@ function maxProduct(words: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/README.md" index 504da786baeed..90c3f9dc2fac6 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 006. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\344\270\244\344\270\252\346\225\260\345\255\227\344\271\213\345\222\214/README.md" @@ -52,26 +52,14 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们注意到数组按照非递减顺序排列,因此对于每个 $numbers[i]$,可以通过二分查找的方式找到 $target - numbers[i]$ 的位置,如果存在,那么返回 $[i, j]$ 即可。 时间复杂度 $O(n \times \log n)$,其中 $n$ 为数组 $numbers$ 的长度。空间复杂度 $O(1)$。 -**方法二:双指针** - -我们定义两个指针 $i$ 和 $j$,分别指向数组的第一个元素和最后一个元素。每次计算 $numbers[i] + numbers[j]$,如果和等于目标值,那么返回 $[i, j]$ 即可。如果和小于目标值,那么将 $i$ 右移一位,如果和大于目标值,那么将 $j$ 左移一位。 - -时间复杂度 $O(n)$,其中 $n$ 为数组 $numbers$ 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: @@ -83,24 +71,6 @@ class Solution: return [i, j] ``` -```python -class Solution: - def twoSum(self, numbers: List[int], target: int) -> List[int]: - i, j = 0, len(numbers) - 1 - while i < j: - x = numbers[i] + numbers[j] - if x == target: - return [i, j] - if x < target: - i += 1 - else: - j -= 1 -``` - -### **Java** - - - ```java class Solution { public int[] twoSum(int[] numbers, int target) { @@ -123,26 +93,6 @@ class Solution { } ``` -```java -class Solution { - public int[] twoSum(int[] numbers, int target) { - for (int i = 0, j = numbers.length - 1;;) { - int x = numbers[i] + numbers[j]; - if (x == target) { - return new int[] {i, j}; - } - if (x < target) { - ++i; - } else { - --j; - } - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -158,27 +108,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector twoSum(vector& numbers, int target) { - for (int i = 0, j = numbers.size() - 1;;) { - int x = numbers[i] + numbers[j]; - if (x == target) { - return {i, j}; - } - if (x < target) { - ++i; - } else { - --j; - } - } - } -}; -``` - -### **Go** - ```go func twoSum(numbers []int, target int) []int { for i, n := 0, len(numbers); ; i++ { @@ -191,24 +120,6 @@ func twoSum(numbers []int, target int) []int { } ``` -```go -func twoSum(numbers []int, target int) []int { - for i, j := 0, len(numbers)-1; ; { - x := numbers[i] + numbers[j] - if x == target { - return []int{i, j} - } - if x < target { - i++ - } else { - j-- - } - } -} -``` - -### **TypeScript** - ```ts function twoSum(numbers: number[], target: number): number[] { const n = numbers.length; @@ -231,24 +142,6 @@ function twoSum(numbers: number[], target: number): number[] { } ``` -```ts -function twoSum(numbers: number[], target: number): number[] { - for (let i = 0, j = numbers.length - 1; ; ) { - const x = numbers[i] + numbers[j]; - if (x === target) { - return [i, j]; - } - if (x < target) { - ++i; - } else { - --j; - } - } -} -``` - -### **Rust** - ```rust use std::cmp::Ordering; @@ -275,6 +168,99 @@ impl Solution { } ``` + + +### 方法二:双指针 + +我们定义两个指针 $i$ 和 $j$,分别指向数组的第一个元素和最后一个元素。每次计算 $numbers[i] + numbers[j]$,如果和等于目标值,那么返回 $[i, j]$ 即可。如果和小于目标值,那么将 $i$ 右移一位,如果和大于目标值,那么将 $j$ 左移一位。 + +时间复杂度 $O(n)$,其中 $n$ 为数组 $numbers$ 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def twoSum(self, numbers: List[int], target: int) -> List[int]: + i, j = 0, len(numbers) - 1 + while i < j: + x = numbers[i] + numbers[j] + if x == target: + return [i, j] + if x < target: + i += 1 + else: + j -= 1 +``` + +```java +class Solution { + public int[] twoSum(int[] numbers, int target) { + for (int i = 0, j = numbers.length - 1;;) { + int x = numbers[i] + numbers[j]; + if (x == target) { + return new int[] {i, j}; + } + if (x < target) { + ++i; + } else { + --j; + } + } + } +} +``` + +```cpp +class Solution { +public: + vector twoSum(vector& numbers, int target) { + for (int i = 0, j = numbers.size() - 1;;) { + int x = numbers[i] + numbers[j]; + if (x == target) { + return {i, j}; + } + if (x < target) { + ++i; + } else { + --j; + } + } + } +}; +``` + +```go +func twoSum(numbers []int, target int) []int { + for i, j := 0, len(numbers)-1; ; { + x := numbers[i] + numbers[j] + if x == target { + return []int{i, j} + } + if x < target { + i++ + } else { + j-- + } + } +} +``` + +```ts +function twoSum(numbers: number[], target: number): number[] { + for (let i = 0, j = numbers.length - 1; ; ) { + const x = numbers[i] + numbers[j]; + if (x === target) { + return [i, j]; + } + if (x < target) { + ++i; + } else { + --j; + } + } +} +``` + ```rust use std::cmp::Ordering; @@ -305,10 +291,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 007. \346\225\260\347\273\204\344\270\255\345\222\214\344\270\272 0 \347\232\204\344\270\211\344\270\252\346\225\260/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 007. \346\225\260\347\273\204\344\270\255\345\222\214\344\270\272 0 \347\232\204\344\270\211\344\270\252\346\225\260/README.md" index 7151c2fcd5c7b..ebf6ea1f67b22 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 007. \346\225\260\347\273\204\344\270\255\345\222\214\344\270\272 0 \347\232\204\344\270\211\344\270\252\346\225\260/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 007. \346\225\260\347\273\204\344\270\255\345\222\214\344\270\272 0 \347\232\204\344\270\211\344\270\252\346\225\260/README.md" @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:排序 + 双指针** +### 方法一:排序 + 双指针 我们注意到,题目不要求我们按照顺序返回三元组,因此我们不妨先对数组进行排序,这样就可以方便地跳过重复的元素。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: @@ -102,10 +96,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> threeSum(int[] nums) { @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +163,6 @@ public: }; ``` -### **Go** - ```go func threeSum(nums []int) (ans [][]int) { sort.Ints(nums) @@ -208,8 +194,6 @@ func threeSum(nums []int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function threeSum(nums: number[]): number[][] { nums.sort((a, b) => a - b); @@ -242,7 +226,48 @@ function threeSum(nums: number[]): number[][] { } ``` -### **JavaScript** +```rust +use std::cmp::Ordering; + +impl Solution { + pub fn three_sum(mut nums: Vec) -> Vec> { + nums.sort(); + let n = nums.len(); + let mut res = vec![]; + let mut i = 0; + while i < n - 2 && nums[i] <= 0 { + let mut l = i + 1; + let mut r = n - 1; + while l < r { + match (nums[i] + nums[l] + nums[r]).cmp(&0) { + Ordering::Less => { + l += 1; + } + Ordering::Greater => { + r -= 1; + } + Ordering::Equal => { + res.push(vec![nums[i], nums[l], nums[r]]); + l += 1; + r -= 1; + while l < n && nums[l] == nums[l - 1] { + l += 1; + } + while r > 0 && nums[r] == nums[r + 1] { + r -= 1; + } + } + } + } + i += 1; + while i < n - 2 && nums[i] == nums[i - 1] { + i += 1; + } + } + res + } +} +``` ```js /** @@ -280,8 +305,6 @@ var threeSum = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public IList> ThreeSum(int[] nums) { @@ -315,8 +338,6 @@ public class Solution { } ``` -### **Ruby** - ```rb # @param {Integer[]} nums # @return {Integer[][]} @@ -348,55 +369,6 @@ def three_sum(nums) end ``` -### **Rust** - -```rust -use std::cmp::Ordering; - -impl Solution { - pub fn three_sum(mut nums: Vec) -> Vec> { - nums.sort(); - let n = nums.len(); - let mut res = vec![]; - let mut i = 0; - while i < n - 2 && nums[i] <= 0 { - let mut l = i + 1; - let mut r = n - 1; - while l < r { - match (nums[i] + nums[l] + nums[r]).cmp(&0) { - Ordering::Less => { - l += 1; - } - Ordering::Greater => { - r -= 1; - } - Ordering::Equal => { - res.push(vec![nums[i], nums[l], nums[r]]); - l += 1; - r -= 1; - while l < n && nums[l] == nums[l - 1] { - l += 1; - } - while r > 0 && nums[r] == nums[r + 1] { - r -= 1; - } - } - } - } - i += 1; - while i < n - 2 && nums[i] == nums[i - 1] { - i += 1; - } - } - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/README.md" index 36276f5df4bf8..9d9794f4bce64 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 008. \345\222\214\345\244\247\344\272\216\347\255\211\344\272\216 target \347\232\204\346\234\200\347\237\255\345\255\220\346\225\260\347\273\204/README.md" @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们使用双指针维护一个和小于 $target$ 的连续子数组。每次右边界 $j$ 向右移动一位,如果和大于等于 $target$,则更新答案的最小值,同时左边界 $i$ 向右移动,直到和小于 $target$。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: @@ -86,10 +80,6 @@ class Solution: return 0 if ans == inf else ans ``` -### **Java** - - - ```java class Solution { public int minSubArrayLen(int target, int[] nums) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func minSubArrayLen(target int, nums []int) int { const inf = 1 << 30 @@ -152,8 +138,6 @@ func minSubArrayLen(target int, nums []int) int { } ``` -### **TypeScript** - ```ts function minSubArrayLen(target: number, nums: number[]): number { const n = nums.length; @@ -171,10 +155,6 @@ function minSubArrayLen(target: number, nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/README.md" index 939c721952da1..fdf88cd7ce2a4 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/README.md" @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 我们使用滑动窗口维护一个乘积不超过 $k$ 的连续子数组。每次右边界 $j$ 向右移动一位,如果乘积超过了 $k$,则左边界 $i$ 向右移动,直到乘积小于 $k$。那么以右边界 $j$ 为结尾的子数组个数为 $j - i + 1$,我们将其累加到答案中。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: @@ -67,10 +61,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numSubarrayProductLessThanK(int[] nums, int k) { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +96,6 @@ public: }; ``` -### **Go** - ```go func numSubarrayProductLessThanK(nums []int, k int) int { s := 1 @@ -126,8 +112,6 @@ func numSubarrayProductLessThanK(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function numSubarrayProductLessThanK(nums: number[], k: number): number { let s = 1; @@ -144,10 +128,6 @@ function numSubarrayProductLessThanK(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/README.md" index 9ae9fa9c15820..d9d48c9315517 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 010. \345\222\214\344\270\272 k \347\232\204\345\255\220\346\225\260\347\273\204/README.md" @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:哈希表 + 前缀和** +### 方法一:哈希表 + 前缀和 由于数组中既有正数又有负数,无法使用双指针。我们可以使用哈希表记录每个前缀和出现的次数,从而在 $O(1)$ 的时间内得到以当前位置为右端点的子数组中和为 $k$ 的子数组个数。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def subarraySum(self, nums: List[int], k: int) -> int: @@ -67,10 +61,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int subarraySum(int[] nums, int k) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +94,6 @@ public: }; ``` -### **Go** - ```go func subarraySum(nums []int, k int) (ans int) { cnt := map[int]int{0: 1} @@ -121,8 +107,6 @@ func subarraySum(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function subarraySum(nums: number[], k: number): number { const cnt: Map = new Map(); @@ -138,10 +122,6 @@ function subarraySum(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/README.md" index faa59ca5f124f..4dcdd68b1c70d 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 011. 0 \345\222\214 1 \344\270\252\346\225\260\347\233\270\345\220\214\347\232\204\345\255\220\346\225\260\347\273\204/README.md" @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:哈希表 + 前缀和** +### 方法一:哈希表 + 前缀和 我们可以将数组中的 $0$ 视作 $-1$,那么可以将问题转化为求最长的连续子数组,其元素和为 $0$。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def findMaxLength(self, nums: List[int]) -> int: @@ -67,10 +61,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int findMaxLength(int[] nums) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func findMaxLength(nums []int) (ans int) { d := map[int]int{0: -1} @@ -135,8 +121,6 @@ func findMaxLength(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function findMaxLength(nums: number[]): number { const d: Map = new Map(); @@ -156,10 +140,6 @@ function findMaxLength(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/README.md" index 1aaad5f77f5cc..d422a1298b80f 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 012. \345\267\246\345\217\263\344\270\244\350\276\271\345\255\220\346\225\260\347\273\204\347\232\204\345\222\214\347\233\270\347\255\211/README.md" @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:前缀和** +### 方法一:前缀和 我们定义变量 $left$ 表示数组 $nums$ 中下标 $i$ 左侧元素之和,变量 $right$ 表示数组 $nums$ 中下标 $i$ 右侧元素之和。初始时 $left = 0$, $right = \sum_{i = 0}^{n - 1} nums[i]$。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def pivotIndex(self, nums: List[int]) -> int: @@ -93,10 +87,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int pivotIndex(int[] nums) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func pivotIndex(nums []int) int { left, right := 0, 0 @@ -157,8 +143,6 @@ func pivotIndex(nums []int) int { } ``` -### **TypeScript** - ```ts function pivotIndex(nums: number[]): number { let left = 0; @@ -175,8 +159,6 @@ function pivotIndex(nums: number[]): number { } ``` -### **PHP** - ```php class Solution { /** @@ -198,8 +180,6 @@ class Solution { } ``` -### **C** - ```c int pivotIndex(int* nums, int numsSize) { int left, right; @@ -221,10 +201,6 @@ int pivotIndex(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/README.md" index ebc80a68f0d2f..688263fb088bf 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 013. \344\272\214\347\273\264\345\255\220\347\237\251\351\230\265\347\232\204\345\222\214/README.md" @@ -57,9 +57,7 @@ numMatrix.sumRegion(1, 2, 2, 4); // return 12 (蓝色矩形框的元素总和) ## 解法 - - -**方法一:二维前缀和** +### 方法一:二维前缀和 我们可以用一个二维数组 $s$ 来保存矩阵 $matrix$ 的前缀和,其中 $s[i+1][j+1]$ 表示矩阵 $matrix$ 中以 $(0,0)$ 为左上角,$(i,j)$ 为右下角的子矩阵中所有元素的和。 @@ -89,10 +87,6 @@ $$ -### **Python3** - - - ```python class NumMatrix: def __init__(self, matrix: List[List[int]]): @@ -117,10 +111,6 @@ class NumMatrix: # param_1 = obj.sumRegion(row1,col1,row2,col2) ``` -### **Java** - - - ```java class NumMatrix { private int[][] s; @@ -148,8 +138,6 @@ class NumMatrix { */ ``` -### **C++** - ```cpp class NumMatrix { public: @@ -179,8 +167,6 @@ private: */ ``` -### **Go** - ```go type NumMatrix struct { s [][]int @@ -211,8 +197,6 @@ func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { */ ``` -### **TypeScript** - ```ts class NumMatrix { s: number[][]; @@ -249,10 +233,6 @@ class NumMatrix { */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/README.md" index 1939b4f6448fd..4dac651f6b850 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 014. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\345\217\230\344\275\215\350\257\215/README.md" @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 不妨记字符串 $s1$ 的长度为 $m$,字符串 $s2$ 的长度为 $n$。 @@ -54,18 +52,8 @@ 时间复杂度 $(m + n \times |\Sigma|)$,空间复杂度 $O(|\Sigma|)$。其中 $m$ 和 $n$ 分别为字符串 $s1$ 和 $s2$ 的长度;而 $|\Sigma|$ 为字符集的大小,本题中 $|\Sigma|=26$。 -**方法二:滑动窗口优化** - -在方法一中,我们每次加入和移除一个字符时,都需要比较两个哈希表或数组,时间复杂度较高。我们可以维护一个变量 $diff$,表示两个大小为 $m$ 的字符串中,有多少种字符出现的个数不同。当 $diff=0$ 时,说明两个字符串中的字符个数相同。 - -时间复杂度 $O(m + n + |\Sigma|)$,空间复杂度 $O(|\Sigma|)$。其中 $m$ 和 $n$ 分别为字符串 $s1$ 和 $s2$ 的长度;而 $|\Sigma|$ 为字符集的大小,本题中 $|\Sigma|=26$。 - -### **Python3** - - - ```python class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: @@ -84,6 +72,125 @@ class Solution: return False ``` +```java +class Solution { + public boolean checkInclusion(String s1, String s2) { + int m = s1.length(); + int n = s2.length(); + if (m > n) { + return false; + } + int[] cnt1 = new int[26]; + int[] cnt2 = new int[26]; + for (int i = 0; i < m; ++i) { + ++cnt1[s1.charAt(i) - 'a']; + ++cnt2[s2.charAt(i) - 'a']; + } + if (Arrays.equals(cnt1, cnt2)) { + return true; + } + for (int i = m; i < n; ++i) { + ++cnt2[s2.charAt(i) - 'a']; + --cnt2[s2.charAt(i - m) - 'a']; + if (Arrays.equals(cnt1, cnt2)) { + return true; + } + } + return false; + } +} +``` + +```cpp +class Solution { +public: + bool checkInclusion(string s1, string s2) { + int m = s1.size(), n = s2.size(); + if (m > n) { + return false; + } + vector cnt1(26), cnt2(26); + for (int i = 0; i < m; ++i) { + ++cnt1[s1[i] - 'a']; + ++cnt2[s2[i] - 'a']; + } + if (cnt1 == cnt2) { + return true; + } + for (int i = m; i < n; ++i) { + ++cnt2[s2[i] - 'a']; + --cnt2[s2[i - m] - 'a']; + if (cnt1 == cnt2) { + return true; + } + } + return false; + } +}; +``` + +```go +func checkInclusion(s1 string, s2 string) bool { + m, n := len(s1), len(s2) + if m > n { + return false + } + var cnt1, cnt2 [26]int + for i := 0; i < m; i++ { + cnt1[s1[i]-'a']++ + cnt2[s2[i]-'a']++ + } + if cnt1 == cnt2 { + return true + } + for i := m; i < n; i++ { + cnt2[s2[i]-'a']++ + cnt2[s2[i-m]-'a']-- + if cnt1 == cnt2 { + return true + } + } + return false +} +``` + +```ts +function checkInclusion(s1: string, s2: string): boolean { + const m = s1.length; + const n = s2.length; + if (m > n) { + return false; + } + const cnt1 = new Array(26).fill(0); + const cnt2 = new Array(26).fill(0); + for (let i = 0; i < m; ++i) { + ++cnt1[s1[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + ++cnt2[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + } + if (cnt1.toString() === cnt2.toString()) { + return true; + } + for (let i = m; i < n; ++i) { + ++cnt2[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + --cnt2[s2[i - m].charCodeAt(0) - 'a'.charCodeAt(0)]; + if (cnt1.toString() === cnt2.toString()) { + return true; + } + } + return false; +} +``` + + + +### 方法二:滑动窗口优化 + +在方法一中,我们每次加入和移除一个字符时,都需要比较两个哈希表或数组,时间复杂度较高。我们可以维护一个变量 $diff$,表示两个大小为 $m$ 的字符串中,有多少种字符出现的个数不同。当 $diff=0$ 时,说明两个字符串中的字符个数相同。 + +时间复杂度 $O(m + n + |\Sigma|)$,空间复杂度 $O(|\Sigma|)$。其中 $m$ 和 $n$ 分别为字符串 $s1$ 和 $s2$ 的长度;而 $|\Sigma|$ 为字符集的大小,本题中 $|\Sigma|=26$。 + + + ```python class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: @@ -114,39 +221,6 @@ class Solution: return False ``` -### **Java** - - - -```java -class Solution { - public boolean checkInclusion(String s1, String s2) { - int m = s1.length(); - int n = s2.length(); - if (m > n) { - return false; - } - int[] cnt1 = new int[26]; - int[] cnt2 = new int[26]; - for (int i = 0; i < m; ++i) { - ++cnt1[s1.charAt(i) - 'a']; - ++cnt2[s2.charAt(i) - 'a']; - } - if (Arrays.equals(cnt1, cnt2)) { - return true; - } - for (int i = m; i < n; ++i) { - ++cnt2[s2.charAt(i) - 'a']; - --cnt2[s2.charAt(i - m) - 'a']; - if (Arrays.equals(cnt1, cnt2)) { - return true; - } - } - return false; - } -} -``` - ```java class Solution { public boolean checkInclusion(String s1, String s2) { @@ -195,36 +269,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool checkInclusion(string s1, string s2) { - int m = s1.size(), n = s2.size(); - if (m > n) { - return false; - } - vector cnt1(26), cnt2(26); - for (int i = 0; i < m; ++i) { - ++cnt1[s1[i] - 'a']; - ++cnt2[s2[i] - 'a']; - } - if (cnt1 == cnt2) { - return true; - } - for (int i = m; i < n; ++i) { - ++cnt2[s2[i] - 'a']; - --cnt2[s2[i - m] - 'a']; - if (cnt1 == cnt2) { - return true; - } - } - return false; - } -}; -``` - ```cpp class Solution { public: @@ -273,33 +317,6 @@ public: }; ``` -### **Go** - -```go -func checkInclusion(s1 string, s2 string) bool { - m, n := len(s1), len(s2) - if m > n { - return false - } - var cnt1, cnt2 [26]int - for i := 0; i < m; i++ { - cnt1[s1[i]-'a']++ - cnt2[s2[i]-'a']++ - } - if cnt1 == cnt2 { - return true - } - for i := m; i < n; i++ { - cnt2[s2[i]-'a']++ - cnt2[s2[i-m]-'a']-- - if cnt1 == cnt2 { - return true - } - } - return false -} -``` - ```go func checkInclusion(s1 string, s2 string) bool { m, n := len(s1), len(s2) @@ -344,35 +361,6 @@ func checkInclusion(s1 string, s2 string) bool { } ``` -### **TypeScript** - -```ts -function checkInclusion(s1: string, s2: string): boolean { - const m = s1.length; - const n = s2.length; - if (m > n) { - return false; - } - const cnt1 = new Array(26).fill(0); - const cnt2 = new Array(26).fill(0); - for (let i = 0; i < m; ++i) { - ++cnt1[s1[i].charCodeAt(0) - 'a'.charCodeAt(0)]; - ++cnt2[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)]; - } - if (cnt1.toString() === cnt2.toString()) { - return true; - } - for (let i = m; i < n; ++i) { - ++cnt2[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)]; - --cnt2[s2[i - m].charCodeAt(0) - 'a'.charCodeAt(0)]; - if (cnt1.toString() === cnt2.toString()) { - return true; - } - } - return false; -} -``` - ```ts function checkInclusion(s1: string, s2: string): boolean { const m = s1.length; @@ -417,10 +405,6 @@ function checkInclusion(s1: string, s2: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/README.md" index 9d50a22ea03ac..dc3dc64060045 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 015. \345\255\227\347\254\246\344\270\262\344\270\255\347\232\204\346\211\200\346\234\211\345\217\230\344\275\215\350\257\215/README.md" @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 不妨记字符串 $s$ 的长度为 $m$,字符串 $p$ 的长度为 $n$。 @@ -60,18 +58,8 @@ 时间复杂度 $(m + n \times |\Sigma|)$,空间复杂度 $O(|\Sigma|)$。其中 $m$ 和 $n$ 分别为字符串 $s$ 和 $p$ 的长度;而 $|\Sigma|$ 为字符集的大小,本题中 $|\Sigma|=26$。 -**方法二:滑动窗口优化** - -在方法一中,我们每次加入和移除一个字符时,都需要比较两个哈希表或数组,时间复杂度较高。我们可以维护一个变量 $diff$,表示两个大小为 $n$ 的字符串中,有多少种字符出现的个数不同。当 $diff=0$ 时,说明两个字符串中的字符个数相同。 - -时间复杂度 $O(m + n + |\Sigma|)$,空间复杂度 $O(|\Sigma|)$。其中 $m$ 和 $n$ 分别为字符串 $s$ 和 $p$ 的长度;而 $|\Sigma|$ 为字符集的大小,本题中 $|\Sigma|=26$。 - -### **Python3** - - - ```python class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: @@ -91,6 +79,129 @@ class Solution: return ans ``` +```java +class Solution { + public List findAnagrams(String s, String p) { + int m = s.length(); + int n = p.length(); + List ans = new ArrayList<>(); + if (m < n) { + return ans; + } + int[] cnt1 = new int[26]; + int[] cnt2 = new int[26]; + for (int i = 0; i < n; ++i) { + ++cnt1[s.charAt(i) - 'a']; + ++cnt2[p.charAt(i) - 'a']; + } + if (Arrays.equals(cnt1, cnt2)) { + ans.add(0); + } + for (int i = n; i < m; ++i) { + ++cnt1[s.charAt(i) - 'a']; + --cnt1[s.charAt(i - n) - 'a']; + if (Arrays.equals(cnt1, cnt2)) { + ans.add(i - n + 1); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector findAnagrams(string s, string p) { + int m = s.size(); + int n = p.size(); + vector ans; + if (m < n) { + return ans; + } + vector cnt1(26), cnt2(26); + for (int i = 0; i < n; ++i) { + ++cnt1[s[i] - 'a']; + ++cnt2[p[i] - 'a']; + } + if (cnt1 == cnt2) { + ans.push_back(0); + } + for (int i = n; i < m; ++i) { + ++cnt1[s[i] - 'a']; + --cnt1[s[i - n] - 'a']; + if (cnt1 == cnt2) { + ans.push_back(i - n + 1); + } + } + return ans; + } +}; +``` + +```go +func findAnagrams(s string, p string) (ans []int) { + m, n := len(s), len(p) + if m < n { + return + } + var cnt1, cnt2 [26]int + for i, ch := range p { + cnt1[s[i]-'a']++ + cnt2[ch-'a']++ + } + if cnt1 == cnt2 { + ans = append(ans, 0) + } + for i := n; i < m; i++ { + cnt1[s[i]-'a']++ + cnt1[s[i-n]-'a']-- + if cnt1 == cnt2 { + ans = append(ans, i-n+1) + } + } + return +} +``` + +```ts +function findAnagrams(s: string, p: string): number[] { + const m = s.length; + const n = p.length; + const ans: number[] = []; + if (m < n) { + return ans; + } + const cnt1: number[] = new Array(26).fill(0); + const cnt2: number[] = new Array(26).fill(0); + for (let i = 0; i < n; ++i) { + ++cnt1[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + ++cnt2[p[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + } + if (cnt1.toString() === cnt2.toString()) { + ans.push(0); + } + for (let i = n; i < m; ++i) { + ++cnt1[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]; + --cnt1[s[i - n].charCodeAt(0) - 'a'.charCodeAt(0)]; + if (cnt1.toString() === cnt2.toString()) { + ans.push(i - n + 1); + } + } + return ans; +} +``` + + + +### 方法二:滑动窗口优化 + +在方法一中,我们每次加入和移除一个字符时,都需要比较两个哈希表或数组,时间复杂度较高。我们可以维护一个变量 $diff$,表示两个大小为 $n$ 的字符串中,有多少种字符出现的个数不同。当 $diff=0$ 时,说明两个字符串中的字符个数相同。 + +时间复杂度 $O(m + n + |\Sigma|)$,空间复杂度 $O(|\Sigma|)$。其中 $m$ 和 $n$ 分别为字符串 $s$ 和 $p$ 的长度;而 $|\Sigma|$ 为字符集的大小,本题中 $|\Sigma|=26$。 + + + ```python class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: @@ -122,40 +233,6 @@ class Solution: return ans ``` -### **Java** - - - -```java -class Solution { - public List findAnagrams(String s, String p) { - int m = s.length(); - int n = p.length(); - List ans = new ArrayList<>(); - if (m < n) { - return ans; - } - int[] cnt1 = new int[26]; - int[] cnt2 = new int[26]; - for (int i = 0; i < n; ++i) { - ++cnt1[s.charAt(i) - 'a']; - ++cnt2[p.charAt(i) - 'a']; - } - if (Arrays.equals(cnt1, cnt2)) { - ans.add(0); - } - for (int i = n; i < m; ++i) { - ++cnt1[s.charAt(i) - 'a']; - --cnt1[s.charAt(i - n) - 'a']; - if (Arrays.equals(cnt1, cnt2)) { - ans.add(i - n + 1); - } - } - return ans; - } -} -``` - ```java class Solution { public List findAnagrams(String s, String p) { @@ -205,38 +282,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector findAnagrams(string s, string p) { - int m = s.size(); - int n = p.size(); - vector ans; - if (m < n) { - return ans; - } - vector cnt1(26), cnt2(26); - for (int i = 0; i < n; ++i) { - ++cnt1[s[i] - 'a']; - ++cnt2[p[i] - 'a']; - } - if (cnt1 == cnt2) { - ans.push_back(0); - } - for (int i = n; i < m; ++i) { - ++cnt1[s[i] - 'a']; - --cnt1[s[i - n] - 'a']; - if (cnt1 == cnt2) { - ans.push_back(i - n + 1); - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -286,33 +331,6 @@ public: }; ``` -### **Go** - -```go -func findAnagrams(s string, p string) (ans []int) { - m, n := len(s), len(p) - if m < n { - return - } - var cnt1, cnt2 [26]int - for i, ch := range p { - cnt1[s[i]-'a']++ - cnt2[ch-'a']++ - } - if cnt1 == cnt2 { - ans = append(ans, 0) - } - for i := n; i < m; i++ { - cnt1[s[i]-'a']++ - cnt1[s[i-n]-'a']-- - if cnt1 == cnt2 { - ans = append(ans, i-n+1) - } - } - return -} -``` - ```go func findAnagrams(s string, p string) (ans []int) { m, n := len(s), len(p) @@ -357,36 +375,6 @@ func findAnagrams(s string, p string) (ans []int) { } ``` -### **TypeScript** - -```ts -function findAnagrams(s: string, p: string): number[] { - const m = s.length; - const n = p.length; - const ans: number[] = []; - if (m < n) { - return ans; - } - const cnt1: number[] = new Array(26).fill(0); - const cnt2: number[] = new Array(26).fill(0); - for (let i = 0; i < n; ++i) { - ++cnt1[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]; - ++cnt2[p[i].charCodeAt(0) - 'a'.charCodeAt(0)]; - } - if (cnt1.toString() === cnt2.toString()) { - ans.push(0); - } - for (let i = n; i < m; ++i) { - ++cnt1[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]; - --cnt1[s[i - n].charCodeAt(0) - 'a'.charCodeAt(0)]; - if (cnt1.toString() === cnt2.toString()) { - ans.push(i - n + 1); - } - } - return ans; -} -``` - ```ts function findAnagrams(s: string, p: string): number[] { const m = s.length; @@ -432,10 +420,6 @@ function findAnagrams(s: string, p: string): number[] { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/README.md" index 9e071e2a36284..9e8cbc179bfd7 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 016. \344\270\215\345\220\253\351\207\215\345\244\215\345\255\227\347\254\246\347\232\204\346\234\200\351\225\277\345\255\220\345\255\227\347\254\246\344\270\262/README.md" @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:双指针 + 哈希表** +### 方法一:双指针 + 哈希表 我们用两个指针 $j$ 和 $i$ 维护一个不包含重复字符的子串,其中 $j$ 为子串的左边界,$i$ 为子串的右边界,用一个哈希表或数组 $ss$ 记录窗口中所有出现过的字符。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def lengthOfLongestSubstring(self, s: str) -> int: @@ -85,10 +79,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int lengthOfLongestSubstring(String s) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func lengthOfLongestSubstring(s string) (ans int) { ss := make([]bool, 128) @@ -147,8 +133,6 @@ func lengthOfLongestSubstring(s string) (ans int) { } ``` -### **TypeScript** - ```ts function lengthOfLongestSubstring(s: string): number { let ans = 0; @@ -164,6 +148,12 @@ function lengthOfLongestSubstring(s: string): number { } ``` + + +### 方法二 + + + ```ts function lengthOfLongestSubstring(s: string): number { let ans = 0; @@ -180,10 +170,6 @@ function lengthOfLongestSubstring(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/README.md" index bff33cd2bac40..85d2d0d96820f 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 017. \345\220\253\346\234\211\346\211\200\346\234\211\345\255\227\347\254\246\347\232\204\346\234\200\347\237\255\345\255\227\347\254\246\344\270\262/README.md" @@ -54,18 +54,10 @@ ## 解法 - - -滑动窗口,当窗口包含全部需要的的字符后,进行收缩,以求得最小长度 - -进阶解法:利用 `count` 变量避免重复对 `need` 和 `window` 进行扫描 +### 方法一 -### **Python3** - - - ```python class Solution: def minWindow(self, s: str, t: str) -> str: @@ -95,46 +87,6 @@ class Solution: return True ``` -进阶解法 - -```python -class Solution: - def minWindow(self, s: str, t: str) -> str: - m, n = len(s), len(t) - if n > m: - return "" - need, window = defaultdict(int), defaultdict(int) - needCount, windowCount = 0, 0 - for c in t: - if need[c] == 0: - needCount += 1 - need[c] += 1 - start, minLen = 0, inf - left, right = 0, 0 - while right < m: - ch = s[right] - right += 1 - if ch in need: - window[ch] += 1 - if window[ch] == need[ch]: - windowCount += 1 - while windowCount == needCount: - if right - left < minLen: - minLen = right - left - start = left - ch = s[left] - left += 1 - if ch in need: - if window[ch] == need[ch]: - windowCount -= 1 - window[ch] -= 1 - return "" if minLen == inf else s[start : start + minLen] -``` - -### **Java** - - - ```java class Solution { public String minWindow(String s, String t) { @@ -173,7 +125,85 @@ class Solution { } ``` -进阶解法 +```go +func minWindow(s string, t string) string { + m, n := len(s), len(t) + if n > m { + return "" + } + need, window := make(map[byte]int), make(map[byte]int) + for _, r := range t { + need[byte(r)]++ + } + start, minLen := 0, math.MaxInt32 + left, right := 0, 0 + for right < m { + window[s[right]]++ + right++ + for check(need, window) { + if right-left < minLen { + minLen = right - left + start = left + } + window[s[left]]-- + left++ + } + } + if minLen == math.MaxInt32 { + return "" + } + return s[start : start+minLen] +} + +func check(need, window map[byte]int) bool { + for k, v := range need { + if window[k] < v { + return false + } + } + return true +} +``` + + + +### 方法二 + + + +```python +class Solution: + def minWindow(self, s: str, t: str) -> str: + m, n = len(s), len(t) + if n > m: + return "" + need, window = defaultdict(int), defaultdict(int) + needCount, windowCount = 0, 0 + for c in t: + if need[c] == 0: + needCount += 1 + need[c] += 1 + start, minLen = 0, inf + left, right = 0, 0 + while right < m: + ch = s[right] + right += 1 + if ch in need: + window[ch] += 1 + if window[ch] == need[ch]: + windowCount += 1 + while windowCount == needCount: + if right - left < minLen: + minLen = right - left + start = left + ch = s[left] + left += 1 + if ch in need: + if window[ch] == need[ch]: + windowCount -= 1 + window[ch] -= 1 + return "" if minLen == inf else s[start : start + minLen] +``` ```java class Solution { @@ -222,50 +252,6 @@ class Solution { } ``` -### **Go** - -```go -func minWindow(s string, t string) string { - m, n := len(s), len(t) - if n > m { - return "" - } - need, window := make(map[byte]int), make(map[byte]int) - for _, r := range t { - need[byte(r)]++ - } - start, minLen := 0, math.MaxInt32 - left, right := 0, 0 - for right < m { - window[s[right]]++ - right++ - for check(need, window) { - if right-left < minLen { - minLen = right - left - start = left - } - window[s[left]]-- - left++ - } - } - if minLen == math.MaxInt32 { - return "" - } - return s[start : start+minLen] -} - -func check(need, window map[byte]int) bool { - for k, v := range need { - if window[k] < v { - return false - } - } - return true -} -``` - -进阶解法 - ```go func minWindow(s string, t string) string { m, n := len(s), len(t) @@ -313,10 +299,6 @@ func minWindow(s string, t string) string { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/README.md" index ea1e2b8cad1a0..3ceb01c7e3782 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 018. \346\234\211\346\225\210\347\232\204\345\233\236\346\226\207/README.md" @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们定义两个指针 $i$ 和 $j$,初始时分别指向字符串的首尾位置,每次判断两个指针指向的字符是否为数字或字母,如果两个指针指向的字符都为数字或字母时,判断两个指针指向的字符是否相同(忽略大小写),如果不相同则返回 `false`,否则将两个指针向中间移动一位,直到两个指针相遇时返回 `true`。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def isPalindrome(self, s: str) -> bool: @@ -68,10 +62,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean isPalindrome(String s) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func isPalindrome(s string) bool { i, j := 0, len(s)-1 @@ -153,8 +139,6 @@ func isalnum(b byte) bool { } ``` -### **TypeScript** - ```ts function isPalindrome(s: string): boolean { const str = s.replace(/[^a-zA-Z0-9]/g, ''); @@ -171,10 +155,6 @@ function isPalindrome(s: string): boolean { } ``` -### **Rust** - -使用 `is_alphabetic()` 与 `is_numeric()` 过滤字符 - ```rust impl Solution { pub fn is_palindrome(s: String) -> bool { @@ -203,10 +183,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/README.md" index b6ec1b1399e50..849a4ddb79e8e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 019. \346\234\200\345\244\232\345\210\240\351\231\244\344\270\200\344\270\252\345\255\227\347\254\246\345\276\227\345\210\260\345\233\236\346\226\207/README.md" @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们用两个指针 $i$ 和 $j$ 分别指向字符串 $s$ 的第一个字符和最后一个字符,然后向中间移动指针,每次判断 $s[i]$ 和 $s[j]$ 是否相等: @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def validPalindrome(self, s: str) -> bool: @@ -79,10 +73,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { private String s; @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go func validPalindrome(s string) bool { check := func(i, j int) bool { @@ -153,8 +139,6 @@ func validPalindrome(s string) bool { } ``` -### **TypeScript** - ```ts function validPalindrome(s: string): boolean { const check = (i: number, j: number): boolean => { @@ -174,8 +158,6 @@ function validPalindrome(s: string): boolean { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -199,10 +181,6 @@ var validPalindrome = function (s) { }; ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/README.md" index a39a5f2f5e559..234fbc6bbf9a3 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 020. \345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262\347\232\204\344\270\252\346\225\260/README.md" @@ -40,26 +40,14 @@ ## 解法 - - -**方法一:从中心向两侧扩展回文串** +### 方法一:从中心向两侧扩展回文串 我们可以枚举回文串的中间点,然后向左右两边扩展,统计回文串的数量。注意,回文串可能包含奇数个字符,也可能不包含。因此这两种情况都要考虑。 时间复杂度 $O(n^2)$,其中 $n$ 是字符串 `s` 的长度。 -**方法二:Manacher 算法** - -在 Manacher 算法的计算过程中,用 $p[i]-1$ 表示以第 $i$ 位为中心的最大回文长度,以第 $i$ 位为中心的回文串数量为 $\left \lceil \frac{p[i]-1}{2} \right \rceil$。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 `s` 的长度。 - -### **Python3** - - - ```python class Solution: def countSubstrings(self, s: str) -> int: @@ -76,29 +64,6 @@ class Solution: return sum(f(i, i) + f(i, i + 1) for i in range(n)) ``` -```python -class Solution: - def countSubstrings(self, s: str) -> int: - t = '^#' + '#'.join(s) + '#$' - n = len(t) - p = [0 for _ in range(n)] - pos, maxRight = 0, 0 - ans = 0 - for i in range(1, n - 1): - p[i] = min(maxRight - i, p[2 * pos - i]) if maxRight > i else 1 - while t[i - p[i]] == t[i + p[i]]: - p[i] += 1 - if i + p[i] > maxRight: - maxRight = i + p[i] - pos = i - ans += p[i] // 2 - return ans -``` - -### **Java** - - - ```java class Solution { private String s; @@ -123,36 +88,6 @@ class Solution { } ``` -```java -class Solution { - public int countSubstrings(String s) { - StringBuilder sb = new StringBuilder("^#"); - for (char ch : s.toCharArray()) { - sb.append(ch).append('#'); - } - String t = sb.append('$').toString(); - int n = t.length(); - int[] p = new int[n]; - int pos = 0, maxRight = 0; - int ans = 0; - for (int i = 1; i < n - 1; i++) { - p[i] = maxRight > i ? Math.min(maxRight - i, p[2 * pos - i]) : 1; - while (t.charAt(i - p[i]) == t.charAt(i + p[i])) { - p[i]++; - } - if (i + p[i] > maxRight) { - maxRight = i + p[i]; - pos = i; - } - ans += p[i] / 2; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -174,8 +109,6 @@ public: }; ``` -### **Go** - ```go func countSubstrings(s string) (ans int) { n := len(s) @@ -193,10 +126,63 @@ func countSubstrings(s string) (ans int) { } ``` -### **...** + + +### 方法二:Manacher 算法 + +在 Manacher 算法的计算过程中,用 $p[i]-1$ 表示以第 $i$ 位为中心的最大回文长度,以第 $i$ 位为中心的回文串数量为 $\left \lceil \frac{p[i]-1}{2} \right \rceil$。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 `s` 的长度。 + + +```python +class Solution: + def countSubstrings(self, s: str) -> int: + t = '^#' + '#'.join(s) + '#$' + n = len(t) + p = [0 for _ in range(n)] + pos, maxRight = 0, 0 + ans = 0 + for i in range(1, n - 1): + p[i] = min(maxRight - i, p[2 * pos - i]) if maxRight > i else 1 + while t[i - p[i]] == t[i + p[i]]: + p[i] += 1 + if i + p[i] > maxRight: + maxRight = i + p[i] + pos = i + ans += p[i] // 2 + return ans ``` +```java +class Solution { + public int countSubstrings(String s) { + StringBuilder sb = new StringBuilder("^#"); + for (char ch : s.toCharArray()) { + sb.append(ch).append('#'); + } + String t = sb.append('$').toString(); + int n = t.length(); + int[] p = new int[n]; + int pos = 0, maxRight = 0; + int ans = 0; + for (int i = 1; i < n - 1; i++) { + p[i] = maxRight > i ? Math.min(maxRight - i, p[2 * pos - i]) : 1; + while (t.charAt(i - p[i]) == t.charAt(i + p[i])) { + p[i]++; + } + if (i + p[i] > maxRight) { + maxRight = i + p[i]; + pos = i; + } + ans += p[i] / 2; + } + return ans; + } +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 021. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254 n \344\270\252\347\273\223\347\202\271/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 021. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254 n \344\270\252\347\273\223\347\202\271/README.md" index 97a5519f8d4ff..dbf221dda9ad2 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 021. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254 n \344\270\252\347\273\223\347\202\271/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 021. \345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254 n \344\270\252\347\273\223\347\202\271/README.md" @@ -52,16 +52,10 @@ ## 解法 - - -利用快慢指针和虚拟头节点 +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -81,10 +75,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -172,8 +158,6 @@ func removeNthFromEnd(head *ListNode, n int) *ListNode { } ``` -### **JavaScript** - ```js /** * Definition for singly-linked list. @@ -203,8 +187,6 @@ var removeNthFromEnd = function (head, n) { }; ``` -### **Ruby** - ```rb # Definition for singly-linked list. # class ListNode @@ -233,10 +215,6 @@ def remove_nth_from_end(head, n) end ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 022. \351\223\276\350\241\250\344\270\255\347\216\257\347\232\204\345\205\245\345\217\243\350\212\202\347\202\271/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 022. \351\223\276\350\241\250\344\270\255\347\216\257\347\232\204\345\205\245\345\217\243\350\212\202\347\202\271/README.md" index edcea6aadda1a..4136f250b7ff1 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 022. \351\223\276\350\241\250\344\270\255\347\216\257\347\232\204\345\205\245\345\217\243\350\212\202\347\202\271/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 022. \351\223\276\350\241\250\344\270\255\347\216\257\347\232\204\345\205\245\345\217\243\350\212\202\347\202\271/README.md" @@ -65,28 +65,10 @@ ## 解法 - - -先利用快慢指针判断链表是否有环,没有环则直接返回 `null`。 - -若链表有环,我们分析快慢相遇时走过的距离。 - -对于慢指针(每次走 1 步),走过的距离为 `S=X+Y` ①;快指针(每次走 2 步)走过的距离为 `2S=X+Y+N(Y+Z)` ②。如下图所示,其中 `N` 表示快指针与慢指针相遇时在环中所走过的圈数,而我们要求的环入口,也即是 `X` 的距离: - -![](./images/linked-list-cycle-ii.png) - -我们根据式子 ①②,得出 `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: @@ -110,10 +92,6 @@ class Solution: return p ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -148,8 +126,6 @@ public class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -183,7 +159,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 /** @@ -219,38 +219,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/lcof2/\345\211\221\346\214\207 Offer II 023. \344\270\244\344\270\252\351\223\276\350\241\250\347\232\204\347\254\254\344\270\200\344\270\252\351\207\215\345\220\210\350\212\202\347\202\271/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 023. \344\270\244\344\270\252\351\223\276\350\241\250\347\232\204\347\254\254\344\270\200\344\270\252\351\207\215\345\220\210\350\212\202\347\202\271/README.md" index fbeeb77b054ec..16a275f1ff174 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 023. \344\270\244\344\270\252\351\223\276\350\241\250\347\232\204\347\254\254\344\270\200\344\270\252\351\207\215\345\220\210\350\212\202\347\202\271/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 023. \344\270\244\344\270\252\351\223\276\350\241\250\347\232\204\347\254\254\344\270\200\344\270\252\351\207\215\345\220\210\350\212\202\347\202\271/README.md" @@ -77,20 +77,10 @@ ## 解法 - - -使用两个指针 `cur1`, `cur2` 分别指向两个链表 `headA`, `headB`。 - -同时遍历链表,当 `cur1` 到达链表 `headA` 的末尾时,重新定位到链表 `headB` 的头节点;当 `cur2` 到达链表 `headB` 的末尾时,重新定位到链表 `headA` 的头节点。 - -若两指针相遇,所指向的结点就是第一个公共节点。若没相遇,说明两链表无公共节点,此时两个指针都指向 `null`。 +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -108,10 +98,6 @@ class Solution: return cur1 ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -136,8 +122,6 @@ public class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -161,35 +145,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. @@ -216,8 +171,6 @@ func getIntersectionNode(headA, headB *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -242,10 +195,31 @@ function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): Li } ``` -### **...** - -``` +```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/lcof2/\345\211\221\346\214\207 Offer II 024. \345\217\215\350\275\254\351\223\276\350\241\250/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 024. \345\217\215\350\275\254\351\223\276\350\241\250/README.md" index 79c40c3472167..ce1feb15a6368 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 024. \345\217\215\350\275\254\351\223\276\350\241\250/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 024. \345\217\215\350\275\254\351\223\276\350\241\250/README.md" @@ -52,16 +52,10 @@ ## 解法 -定义指针 `p`、`q` 分别指向头节点和下一个节点,`pre` 指向头节点的前一个节点。 - -遍历链表,改变指针 `p` 指向的节点的指向,将其指向 `pre` 指针指向的节点,即 `p.next = pre`。然后 `pre` 指针指向 `p`,`p`、`q` 指针往前走。 - -当遍历结束后,返回 `pre` 指针即可。 +### 方法一 -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -81,10 +75,6 @@ class Solution: return pre ``` -### **Java** - -迭代版本: - ```java /** * Definition for singly-linked list. @@ -108,58 +98,33 @@ class Solution { } ``` -递归版本: - -```java +```cpp /** * Definition for singly-linked list. - * public class ListNode { + * struct ListNode { * int val; - * ListNode next; - * ListNode(int x) { val = x; } - * } + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; */ class Solution { - public ListNode reverseList(ListNode head) { - if (head == null || head.next == null) { - return head; +public: + ListNode* reverseList(ListNode* head) { + ListNode* pre = nullptr; + ListNode* p = head; + while (p) { + ListNode* q = p->next; + p->next = pre; + pre = p; + p = q; } - ListNode res = reverseList(head.next); - head.next.next = head; - head.next = null; - return res; - } -} -``` - -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @return {ListNode} - */ -var reverseList = function (head) { - let pre = null; - for (let p = head; p; ) { - let q = p.next; - p.next = pre; - pre = p; - p = q; + return pre; } - return pre; }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -180,37 +145,30 @@ func reverseList(head *ListNode) *ListNode { } ``` -### **C++** - -```cpp +```js /** * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } */ -class Solution { -public: - ListNode* reverseList(ListNode* head) { - ListNode* pre = nullptr; - ListNode* p = head; - while (p) { - ListNode* q = p->next; - p->next = pre; - pre = p; - p = q; - } - return pre; +/** + * @param {ListNode} head + * @return {ListNode} + */ +var reverseList = function (head) { + let pre = null; + for (let p = head; p; ) { + let q = p.next; + p.next = pre; + pre = p; + p = q; } + return pre; }; ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -238,10 +196,34 @@ public class Solution { } ``` -### **...** + -``` +### 方法二 + + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode res = reverseList(head.next); + head.next.next = head; + head.next = null; + return res; + } +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 025. \351\223\276\350\241\250\344\270\255\347\232\204\344\270\244\346\225\260\347\233\270\345\212\240/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 025. \351\223\276\350\241\250\344\270\255\347\232\204\344\270\244\346\225\260\347\233\270\345\212\240/README.md" index ff52239e952fe..7d68fbdffe8c7 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 025. \351\223\276\350\241\250\344\270\255\347\232\204\344\270\244\346\225\260\347\233\270\345\212\240/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 025. \351\223\276\350\241\250\344\270\255\347\232\204\344\270\244\346\225\260\347\233\270\345\212\240/README.md" @@ -53,16 +53,10 @@ ## 解法 - - -利用栈将数字逆序。 +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -88,10 +82,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -166,8 +154,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -204,10 +190,6 @@ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 026. \351\207\215\346\216\222\351\223\276\350\241\250/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 026. \351\207\215\346\216\222\351\223\276\350\241\250/README.md" index 7a54425d9b4bd..e5d4e75088dd0 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 026. \351\207\215\346\216\222\351\223\276\350\241\250/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 026. \351\207\215\346\216\222\351\223\276\350\241\250/README.md" @@ -46,20 +46,10 @@ ## 解法 - - -相当于这 3 道问题,只需要 5 行代码将它们组合: - -- [链表的中间结点](/solution/0800-0899/0876.Middle%20of%20the%20Linked%20List/README.md) -- [反转链表](/solution/0200-0299/0206.Reverse%20Linked%20List/README.md) -- 合并两个链表 +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -104,10 +94,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -165,8 +151,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -227,8 +211,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -287,10 +269,6 @@ func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 027. \345\233\236\346\226\207\351\223\276\350\241\250/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 027. \345\233\236\346\226\207\351\223\276\350\241\250/README.md" index a8a6eb7057a8d..5d043e66862cc 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 027. \345\233\236\346\226\207\351\223\276\350\241\250/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 027. \345\233\236\346\226\207\351\223\276\350\241\250/README.md" @@ -46,16 +46,10 @@ ## 解法 - - -先用快慢指针找到链表的中点,接着反转右半部分的链表。然后同时遍历前后两段链表,若前后两段链表节点对应的值不等,说明不是回文链表,否则说明是回文链表。 +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -81,10 +75,6 @@ class Solution: return True ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -205,7 +191,47 @@ func isPalindrome(head *ListNode) bool { } ``` -### **JavaScript** +```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 /** @@ -249,8 +275,6 @@ var isPalindrome = function (head) { }; ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -300,54 +324,6 @@ 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; -} -``` - -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 028. \345\261\225\345\271\263\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 028. \345\261\225\345\271\263\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250/README.md" index db3ef548f981b..c940063c59b42 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 028. \345\261\225\345\271\263\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 028. \345\261\225\345\271\263\345\244\232\347\272\247\345\217\214\345\220\221\351\223\276\350\241\250/README.md" @@ -96,16 +96,10 @@ ## 解法 - - -仔细观察一下这个结构,不难发现其实就是前序遍历二叉树 +### 方法一 -### **Python3** - - - ```python """ # Definition for a Node. @@ -143,10 +137,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /* // Definition for a Node. @@ -187,8 +177,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -239,10 +227,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 029. \346\216\222\345\272\217\347\232\204\345\276\252\347\216\257\351\223\276\350\241\250/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 029. \346\216\222\345\272\217\347\232\204\345\276\252\347\216\257\351\223\276\350\241\250/README.md" index 3f02640ff608b..de43ac089b285 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 029. \346\216\222\345\272\217\347\232\204\345\276\252\347\216\257\351\223\276\350\241\250/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 029. \346\216\222\345\272\217\347\232\204\345\276\252\347\216\257\351\223\276\350\241\250/README.md" @@ -58,19 +58,10 @@ ## 解法 - - -1. 头节点如果为空,直接返回 `node` -2. 如果 `insertVal` 在链表的最小值和最大值之间,找到合适的位置插入 -3. 如果 `insertVal` 小于链表的最小值或大于链表的最大值,则在头节点和尾节点之间插入 -4. 链表的所有值和 `insertVal` 都相等,任意位置插入 +### 方法一 -### **Python3** - - - ```python """ # Definition for a Node. @@ -104,10 +95,6 @@ class Solution: return head ``` -### **Java** - - - ```java /* // Definition for a Node. @@ -151,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -196,8 +181,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -226,8 +209,6 @@ func insert(head *Node, x int) *Node { } ``` -### **TypeScript** - ```ts /** * Definition for node. @@ -272,10 +253,6 @@ function insert(head: Node | null, insertVal: number): Node | null { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 030. \346\217\222\345\205\245\343\200\201\345\210\240\351\231\244\345\222\214\351\232\217\346\234\272\350\256\277\351\227\256\351\203\275\346\230\257 O(1) \347\232\204\345\256\271\345\231\250/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 030. \346\217\222\345\205\245\343\200\201\345\210\240\351\231\244\345\222\214\351\232\217\346\234\272\350\256\277\351\227\256\351\203\275\346\230\257 O(1) \347\232\204\345\256\271\345\231\250/README.md" index 02da95f77ef7a..618161571c694 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 030. \346\217\222\345\205\245\343\200\201\345\210\240\351\231\244\345\222\214\351\232\217\346\234\272\350\256\277\351\227\256\351\203\275\346\230\257 O(1) \347\232\204\345\256\271\345\231\250/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 030. \346\217\222\345\205\245\343\200\201\345\210\240\351\231\244\345\222\214\351\232\217\346\234\272\350\256\277\351\227\256\351\203\275\346\230\257 O(1) \347\232\204\345\256\271\345\231\250/README.md" @@ -53,20 +53,10 @@ randomSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总 ## 解法 - - -“哈希表 + 动态列表”实现。 - -哈希表存放每个元素的值和对应的下标,而动态列表在每个下标位置存放每个元素。由动态列表实现元素的随机返回。 - -注意,在 `remove()` 实现上,将列表的最后一个元素设置到待删元素的位置上,然后删除最后一个元素,这样在删除元素的时候,不需要挪动一大批元素,从而实现 `O(1)` 时间内操作。 +### 方法一 -### **Python3** - - - ```python class RandomizedSet: def __init__(self): @@ -113,10 +103,6 @@ class RandomizedSet: # param_3 = obj.getRandom() ``` -### **Java** - - - ```java class RandomizedSet { private final Map m; @@ -169,20 +155,6 @@ class RandomizedSet { */ ``` -### **C++** - -1. 插入 - -每次添加新数值时,先使用哈希表判断该数值是否存在,存在则直接返回 false。不存在则进行插入操作,只要将该数值添加到数组尾部即可,并将该数值和其下标的映射存入哈希表。 - -2. 删除 - -删除同样需使用哈希表判断是否存在,若不存在则返回 false。存在则进行删除操作,在哈希表中删除时间复杂度为 O(1),但是在数值中删除比较麻烦。若只是直接删除,则为了保证数组内存连续性需将删除数值后面的数值均前移一位,时间复杂度为 O(n)。比较好的处理方式是,用数组的最后一个数值去填充需要删除的数值的内存,其他数值在数组中的位置保持不变,并将这个拿来填充的数值的下标更新即可,最后只要删除数组最后一个数值,同样可以保证时间复杂度为 O(1)。 - -3. 随机返回 - -只要随机生成数组下标范围内一个随机下标值,返回该数组下标内的数值即可。 - ```cpp class RandomizedSet { unordered_map mp; @@ -228,10 +200,6 @@ public: */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/README.md" index b55ec7e34051f..c2740714cb46b 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 031. \346\234\200\350\277\221\346\234\200\345\260\221\344\275\277\347\224\250\347\274\223\345\255\230/README.md" @@ -61,9 +61,7 @@ lRUCache.get(4); // 返回 4 ## 解法 - - -**方法一:哈希表 + 双向链表** +### 方法一:哈希表 + 双向链表 我们可以用“哈希表”和“双向链表”实现一个 LRU 缓存。 @@ -78,10 +76,6 @@ lRUCache.get(4); // 返回 4 -### **Python3** - - - ```python class Node: def __init__(self, key=0, val=0): @@ -149,10 +143,6 @@ class LRUCache: # obj.put(key,value) ``` -### **Java** - - - ```java class Node { int key; @@ -241,214 +231,6 @@ class LRUCache { */ ``` -### **Rust** - -```rust -use std::cell::RefCell; -use std::collections::HashMap; -use std::rc::Rc; - -struct Node { - key: i32, - value: i32, - prev: Option>>, - next: Option>>, -} - -impl Node { - #[inline] - fn new(key: i32, value: i32) -> Self { - Self { - key, - value, - prev: None, - next: None, - } - } -} - -struct LRUCache { - capacity: usize, - cache: HashMap>>, - head: Option>>, - tail: Option>>, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl LRUCache { - fn new(capacity: i32) -> Self { - Self { - capacity: capacity as usize, - cache: HashMap::new(), - head: None, - tail: None, - } - } - - fn get(&mut self, key: i32) -> i32 { - match self.cache.get(&key) { - Some(node) => { - let node = Rc::clone(node); - self.remove(&node); - self.push_front(&node); - let value = node.borrow().value; - value - } - None => -1, - } - } - - fn put(&mut self, key: i32, value: i32) { - match self.cache.get(&key) { - Some(node) => { - let node = Rc::clone(node); - node.borrow_mut().value = value; - self.remove(&node); - self.push_front(&node); - } - None => { - let node = Rc::new(RefCell::new(Node::new(key, value))); - self.cache.insert(key, Rc::clone(&node)); - self.push_front(&node); - if self.cache.len() > self.capacity { - let back_key = self.pop_back().unwrap().borrow().key; - self.cache.remove(&back_key); - } - } - }; - } - - fn push_front(&mut self, node: &Rc>) { - match self.head.take() { - Some(head) => { - head.borrow_mut().prev = Some(Rc::clone(node)); - node.borrow_mut().prev = None; - node.borrow_mut().next = Some(head); - self.head = Some(Rc::clone(node)); - } - None => { - self.head = Some(Rc::clone(node)); - self.tail = Some(Rc::clone(node)); - } - }; - } - - fn remove(&mut self, node: &Rc>) { - match (node.borrow().prev.as_ref(), node.borrow().next.as_ref()) { - (None, None) => { - self.head = None; - self.tail = None; - } - (None, Some(next)) => { - self.head = Some(Rc::clone(next)); - next.borrow_mut().prev = None; - } - (Some(prev), None) => { - self.tail = Some(Rc::clone(prev)); - prev.borrow_mut().next = None; - } - (Some(prev), Some(next)) => { - next.borrow_mut().prev = Some(Rc::clone(prev)); - prev.borrow_mut().next = Some(Rc::clone(next)); - } - }; - } - - fn pop_back(&mut self) -> Option>> { - match self.tail.take() { - Some(tail) => { - self.remove(&tail); - Some(tail) - } - None => None, - } - } -}/** - * Your LRUCache object will be instantiated and called as such: - * let obj = LRUCache::new(capacity); - * let ret_1: i32 = obj.get(key); - * obj.put(key, value); - */ -``` - -### **Go** - -```go -type node struct { - key, val int - prev, next *node -} - -type LRUCache struct { - capacity int - cache map[int]*node - head, tail *node -} - -func Constructor(capacity int) LRUCache { - head := new(node) - tail := new(node) - head.next = tail - tail.prev = head - return LRUCache{ - capacity: capacity, - cache: make(map[int]*node, capacity), - head: head, - tail: tail, - } -} - -func (this *LRUCache) Get(key int) int { - n, ok := this.cache[key] - if !ok { - return -1 - } - this.moveToFront(n) - return n.val -} - -func (this *LRUCache) Put(key int, value int) { - n, ok := this.cache[key] - if ok { - n.val = value - this.moveToFront(n) - return - } - if len(this.cache) == this.capacity { - back := this.tail.prev - this.remove(back) - delete(this.cache, back.key) - } - n = &node{key: key, val: value} - this.pushFront(n) - this.cache[key] = n -} - -func (this *LRUCache) moveToFront(n *node) { - this.remove(n) - this.pushFront(n) -} - -func (this *LRUCache) remove(n *node) { - n.prev.next = n.next - n.next.prev = n.prev - n.prev = nil - n.next = nil -} - -func (this *LRUCache) pushFront(n *node) { - n.prev = this.head - n.next = this.head.next - this.head.next.prev = n - this.head.next = n -} -``` - -### **C++** - ```cpp struct Node { int k; @@ -543,7 +325,76 @@ private: */ ``` -### **TypeScript** +```go +type node struct { + key, val int + prev, next *node +} + +type LRUCache struct { + capacity int + cache map[int]*node + head, tail *node +} + +func Constructor(capacity int) LRUCache { + head := new(node) + tail := new(node) + head.next = tail + tail.prev = head + return LRUCache{ + capacity: capacity, + cache: make(map[int]*node, capacity), + head: head, + tail: tail, + } +} + +func (this *LRUCache) Get(key int) int { + n, ok := this.cache[key] + if !ok { + return -1 + } + this.moveToFront(n) + return n.val +} + +func (this *LRUCache) Put(key int, value int) { + n, ok := this.cache[key] + if ok { + n.val = value + this.moveToFront(n) + return + } + if len(this.cache) == this.capacity { + back := this.tail.prev + this.remove(back) + delete(this.cache, back.key) + } + n = &node{key: key, val: value} + this.pushFront(n) + this.cache[key] = n +} + +func (this *LRUCache) moveToFront(n *node) { + this.remove(n) + this.pushFront(n) +} + +func (this *LRUCache) remove(n *node) { + n.prev.next = n.next + n.next.prev = n.prev + n.prev = nil + n.next = nil +} + +func (this *LRUCache) pushFront(n *node) { + n.prev = this.head + n.next = this.head.next + this.head.next.prev = n + this.head.next = n +} +``` ```ts class LRUCache { @@ -581,7 +432,136 @@ class LRUCache { */ ``` -### **C#** +```rust +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +struct Node { + key: i32, + value: i32, + prev: Option>>, + next: Option>>, +} + +impl Node { + #[inline] + fn new(key: i32, value: i32) -> Self { + Self { + key, + value, + prev: None, + next: None, + } + } +} + +struct LRUCache { + capacity: usize, + cache: HashMap>>, + head: Option>>, + tail: Option>>, +} + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl LRUCache { + fn new(capacity: i32) -> Self { + Self { + capacity: capacity as usize, + cache: HashMap::new(), + head: None, + tail: None, + } + } + + fn get(&mut self, key: i32) -> i32 { + match self.cache.get(&key) { + Some(node) => { + let node = Rc::clone(node); + self.remove(&node); + self.push_front(&node); + let value = node.borrow().value; + value + } + None => -1, + } + } + + fn put(&mut self, key: i32, value: i32) { + match self.cache.get(&key) { + Some(node) => { + let node = Rc::clone(node); + node.borrow_mut().value = value; + self.remove(&node); + self.push_front(&node); + } + None => { + let node = Rc::new(RefCell::new(Node::new(key, value))); + self.cache.insert(key, Rc::clone(&node)); + self.push_front(&node); + if self.cache.len() > self.capacity { + let back_key = self.pop_back().unwrap().borrow().key; + self.cache.remove(&back_key); + } + } + }; + } + + fn push_front(&mut self, node: &Rc>) { + match self.head.take() { + Some(head) => { + head.borrow_mut().prev = Some(Rc::clone(node)); + node.borrow_mut().prev = None; + node.borrow_mut().next = Some(head); + self.head = Some(Rc::clone(node)); + } + None => { + self.head = Some(Rc::clone(node)); + self.tail = Some(Rc::clone(node)); + } + }; + } + + fn remove(&mut self, node: &Rc>) { + match (node.borrow().prev.as_ref(), node.borrow().next.as_ref()) { + (None, None) => { + self.head = None; + self.tail = None; + } + (None, Some(next)) => { + self.head = Some(Rc::clone(next)); + next.borrow_mut().prev = None; + } + (Some(prev), None) => { + self.tail = Some(Rc::clone(prev)); + prev.borrow_mut().next = None; + } + (Some(prev), Some(next)) => { + next.borrow_mut().prev = Some(Rc::clone(prev)); + prev.borrow_mut().next = Some(Rc::clone(next)); + } + }; + } + + fn pop_back(&mut self) -> Option>> { + match self.tail.take() { + Some(tail) => { + self.remove(&tail); + Some(tail) + } + None => None, + } + } +}/** + * Your LRUCache object will be instantiated and called as such: + * let obj = LRUCache::new(capacity); + * let ret_1: i32 = obj.get(key); + * obj.put(key, value); + */ +``` ```cs public class LRUCache { @@ -662,10 +642,6 @@ public class LRUCache { */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/README.md" index 3d65d47c81c16..f7853df2152e0 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 032. \346\234\211\346\225\210\347\232\204\345\217\230\344\275\215\350\257\215/README.md" @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 如果字符串 $s$ 与字符串 $t$ 长度不相等,或者字符串 $s$ 与字符串 $t$ 完全相等,那么 $s$ 和 $t$ 一定不是变位词,返回 `false`。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def isAnagram(self, s: str, t: str) -> bool: @@ -72,10 +66,6 @@ class Solution: return Counter(s) == Counter(t) ``` -### **Java** - - - ```java class Solution { public boolean isAnagram(String s, String t) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func isAnagram(s string, t string) bool { m, n := len(s), len(t) @@ -147,8 +133,6 @@ func isAnagram(s string, t string) bool { } ``` -### **TypeScript** - ```ts function isAnagram(s: string, t: string): boolean { const m = s.length; @@ -165,10 +149,6 @@ function isAnagram(s: string, t: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/README.md" index f1ff81ec3eef7..4c233b13edf66 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 033. \345\217\230\344\275\215\350\257\215\347\273\204/README.md" @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 1. 遍历字符串,对每个字符串按照**字符字典序**排序,得到一个新的字符串。 2. 以新字符串为 `key`,`[str]` 为 `value`,存入哈希表当中(`HashMap>`)。 @@ -65,18 +63,8 @@ 时间复杂度 $O(n\times k\times \log k)$。其中 $n$ 和 $k$ 分别是字符串数组的长度和字符串的最大长度。 -**方法二:计数** - -我们也可以将方法一中的排序部分改为计数,也就是说,将每个字符串 $s$ 中的字符以及出现的次数作为 `key`,将字符串 $s$ 作为 `value` 存入哈希表当中。 - -时间复杂度 $O(n\times (k + C))$。其中 $n$ 和 $k$ 分别是字符串数组的长度和字符串的最大长度,而 $C$ 是字符集的大小,本题中 $C = 26$。 - -### **Python3** - - - ```python class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: @@ -87,22 +75,6 @@ class Solution: return list(d.values()) ``` -```python -class Solution: - def groupAnagrams(self, strs: List[str]) -> List[List[str]]: - d = defaultdict(list) - for s in strs: - cnt = [0] * 26 - for c in s: - cnt[ord(c) - ord('a')] += 1 - d[tuple(cnt)].append(s) - return list(d.values()) -``` - -### **Java** - - - ```java class Solution { public List> groupAnagrams(String[] strs) { @@ -118,6 +90,75 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map> d; + for (auto& s : strs) { + string k = s; + sort(k.begin(), k.end()); + d[k].emplace_back(s); + } + vector> ans; + for (auto& [_, v] : d) ans.emplace_back(v); + return ans; + } +}; +``` + +```go +func groupAnagrams(strs []string) (ans [][]string) { + d := map[string][]string{} + for _, s := range strs { + t := []byte(s) + sort.Slice(t, func(i, j int) bool { return t[i] < t[j] }) + k := string(t) + d[k] = append(d[k], s) + } + for _, v := range d { + ans = append(ans, v) + } + return +} +``` + +```ts +function groupAnagrams(strs: string[]): string[][] { + const d: Map = new Map(); + for (const s of strs) { + const k = s.split('').sort().join(''); + if (!d.has(k)) { + d.set(k, []); + } + d.get(k)!.push(s); + } + return Array.from(d.values()); +} +``` + + + +### 方法二:计数 + +我们也可以将方法一中的排序部分改为计数,也就是说,将每个字符串 $s$ 中的字符以及出现的次数作为 `key`,将字符串 $s$ 作为 `value` 存入哈希表当中。 + +时间复杂度 $O(n\times (k + C))$。其中 $n$ 和 $k$ 分别是字符串数组的长度和字符串的最大长度,而 $C$ 是字符集的大小,本题中 $C = 26$。 + + + +```python +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + d = defaultdict(list) + for s in strs: + cnt = [0] * 26 + for c in s: + cnt[ord(c) - ord('a')] += 1 + d[tuple(cnt)].append(s) + return list(d.values()) +``` + ```java class Solution { public List> groupAnagrams(String[] strs) { @@ -141,25 +182,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector> groupAnagrams(vector& strs) { - unordered_map> d; - for (auto& s : strs) { - string k = s; - sort(k.begin(), k.end()); - d[k].emplace_back(s); - } - vector> ans; - for (auto& [_, v] : d) ans.emplace_back(v); - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -184,24 +206,6 @@ public: }; ``` -### **Go** - -```go -func groupAnagrams(strs []string) (ans [][]string) { - d := map[string][]string{} - for _, s := range strs { - t := []byte(s) - sort.Slice(t, func(i, j int) bool { return t[i] < t[j] }) - k := string(t) - d[k] = append(d[k], s) - } - for _, v := range d { - ans = append(ans, v) - } - return -} -``` - ```go func groupAnagrams(strs []string) (ans [][]string) { d := map[[26]int][]string{} @@ -219,22 +223,6 @@ func groupAnagrams(strs []string) (ans [][]string) { } ``` -### **TypeScript** - -```ts -function groupAnagrams(strs: string[]): string[][] { - const d: Map = new Map(); - for (const s of strs) { - const k = s.split('').sort().join(''); - if (!d.has(k)) { - d.set(k, []); - } - d.get(k)!.push(s); - } - return Array.from(d.values()); -} -``` - ```ts function groupAnagrams(strs: string[]): string[][] { const map = new Map(); @@ -246,10 +234,6 @@ function groupAnagrams(strs: string[]): string[][] { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/README.md" index 03640aaae00b9..7f02fee43245f 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 034. \345\244\226\346\230\237\350\257\255\350\250\200\346\230\257\345\220\246\346\216\222\345\272\217/README.md" @@ -49,16 +49,10 @@ ## 解法 - - -用数组或哈希表存放字母顺序。依次遍历单词列表,检测相邻两单词是否满足字典序。 +### 方法一 -### **Python3** - - - ```python class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: @@ -81,10 +75,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean isAlienSorted(String[] words, String order) { @@ -114,32 +104,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function isAlienSorted(words: string[], order: string): boolean { - let charMap = new Map(); - for (let i = 0; i < order.length; i++) { - charMap.set(order[i], i); - } - function compare(str1: string, str2: string): boolean { - const n = Math.min(str1.length, str2.length); - for (let i = 0; i < n; i++) { - let k1 = str1[i], - k2 = str2[i]; - if (k1 != k2) return charMap.get(k1) < charMap.get(k2); - } - return n == str1.length; - } - for (let i = 1; i < words.length; i++) { - if (!compare(words[i - 1], words[i])) return false; - } - return true; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -165,8 +129,6 @@ public: }; ``` -### **Go** - ```go func isAlienSorted(words []string, order string) bool { index := make(map[byte]int) @@ -194,10 +156,28 @@ func isAlienSorted(words []string, order string) bool { } ``` -### **...** - -``` - +```ts +function isAlienSorted(words: string[], order: string): boolean { + let charMap = new Map(); + for (let i = 0; i < order.length; i++) { + charMap.set(order[i], i); + } + function compare(str1: string, str2: string): boolean { + const n = Math.min(str1.length, str2.length); + for (let i = 0; i < n; i++) { + let k1 = str1[i], + k2 = str2[i]; + if (k1 != k2) return charMap.get(k1) < charMap.get(k2); + } + return n == str1.length; + } + for (let i = 1; i < words.length; i++) { + if (!compare(words[i - 1], words[i])) return false; + } + return true; +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/README.md" index 4c2838b4a87b0..a0488dd2f064d 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 035. \346\234\200\345\260\217\346\227\266\351\227\264\345\267\256/README.md" @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们注意到,时间点最多只有 $24 \times 60$ 个,因此,当 $timePoints$ 长度超过 $24 \times 60$,说明有重复的时间点,提前返回 $0$。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def findMinDifference(self, timePoints: List[str]) -> int: @@ -67,10 +61,6 @@ class Solution: return min(b - a for a, b in pairwise(mins)) ``` -### **Java** - - - ```java class Solution { public int findMinDifference(List timePoints) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func findMinDifference(timePoints []string) int { if len(timePoints) > 24*60 { @@ -141,8 +127,6 @@ func findMinDifference(timePoints []string) int { } ``` -### **TypeScript** - ```ts function findMinDifference(timePoints: string[]): number { if (timePoints.length > 24 * 60) { @@ -162,10 +146,6 @@ function findMinDifference(timePoints: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 036. \345\220\216\347\274\200\350\241\250\350\276\276\345\274\217/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 036. \345\220\216\347\274\200\350\241\250\350\276\276\345\274\217/README.md" index e640f456646d3..5dbdecd9c282b 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 036. \345\220\216\347\274\200\350\241\250\350\276\276\345\274\217/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 036. \345\220\216\347\274\200\350\241\250\350\276\276\345\274\217/README.md" @@ -83,18 +83,10 @@ ## 解法 - - -利用栈存储运算数,每次遇到符号,对栈顶两个元素进行运算。 +### 方法一 -### **Python3** - - - -需要注意 Python 的整除对负数也是向下取整(例如:`6 // -132 = -1`),和答案对应不上,所以需要特殊处理。 - ```python class Solution: def evalRPN(self, tokens: List[str]) -> int: @@ -115,10 +107,6 @@ class Solution: return nums[0] ``` -### **Java** - - - ```java class Solution { public int evalRPN(String[] tokens) { @@ -150,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -180,8 +166,6 @@ public: }; ``` -### **Go** - ```go func evalRPN(tokens []string) int { // https://github.com/emirpasic/gods#arraystack @@ -214,10 +198,6 @@ func popInt(stack *arraystack.Stack) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/README.md" index c343705b2aca2..cb0d36c5fe8ac 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/README.md" @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 我们从左到右遍历每个小行星 $x$,由于每个小行星可能与之前的多个小行星发生碰撞,考虑用栈来存储。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def asteroidCollision(self, asteroids: List[int]) -> List[int]: @@ -92,10 +86,6 @@ class Solution: return stk ``` -### **Java** - - - ```java class Solution { public int[] asteroidCollision(int[] asteroids) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go func asteroidCollision(asteroids []int) (stk []int) { for _, x := range asteroids { @@ -167,8 +153,6 @@ func asteroidCollision(asteroids []int) (stk []int) { } ``` -### **TypeScript** - ```ts function asteroidCollision(asteroids: number[]): number[] { const stk: number[] = []; @@ -190,8 +174,6 @@ function asteroidCollision(asteroids: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -216,10 +198,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/README.md" index 10759b524ab28..7704747f52a89 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 038. \346\257\217\346\227\245\346\270\251\345\272\246/README.md" @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 单调栈常见模型:找出每个数左/右边**离它最近的**且**比它大/小的数**。模板: @@ -59,10 +57,6 @@ for i in range(n): -### **Python3** - - - ```python class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: @@ -76,25 +70,6 @@ class Solution: return ans ``` -```python -class Solution: - def dailyTemperatures(self, temperatures: List[int]) -> List[int]: - n = len(temperatures) - stk = [] - ans = [0] * n - for i in range(n - 1, -1, -1): - while stk and temperatures[stk[-1]] <= temperatures[i]: - stk.pop() - if stk: - ans[i] = stk[-1] - i - stk.append(i) - return ans -``` - -### **Java** - - - ```java class Solution { public int[] dailyTemperatures(int[] temperatures) { @@ -113,47 +88,114 @@ class Solution { } ``` -```java +```cpp class Solution { - public int[] dailyTemperatures(int[] temperatures) { - int n = temperatures.length; - Deque stk = new ArrayDeque<>(); - int[] ans = new int[n]; - for (int i = n - 1; i >= 0; --i) { - while (!stk.isEmpty() && temperatures[stk.peek()] <= temperatures[i]) { +public: + vector dailyTemperatures(vector& temperatures) { + int n = temperatures.size(); + vector ans(n); + stack stk; + for (int i = 0; i < n; ++i) { + while (!stk.empty() && temperatures[stk.top()] < temperatures[i]) { + ans[stk.top()] = i - stk.top(); stk.pop(); } - if (!stk.isEmpty()) { - ans[i] = stk.peek() - i; - } stk.push(i); } return ans; } +}; +``` + +```go +func dailyTemperatures(temperatures []int) []int { + ans := make([]int, len(temperatures)) + var stk []int + for i, t := range temperatures { + for len(stk) > 0 && temperatures[stk[len(stk)-1]] < t { + j := stk[len(stk)-1] + ans[j] = i - j + stk = stk[:len(stk)-1] + } + stk = append(stk, i) + } + return ans +} +``` + +```ts +function dailyTemperatures(temperatures: number[]): number[] { + const n = temperatures.length; + const res = new Array(n); + const stack = []; + for (let i = n - 1; i >= 0; i--) { + while (stack.length !== 0 && temperatures[stack[stack.length - 1]] <= temperatures[i]) { + stack.pop(); + } + res[i] = stack.length === 0 ? 0 : stack[stack.length - 1] - i; + stack.push(i); + } + return res; +} +``` + +```rust +impl Solution { + pub fn daily_temperatures(temperatures: Vec) -> Vec { + let n = temperatures.len(); + let mut res = vec![0; n]; + let mut stack = Vec::new(); + for i in (0..n).rev() { + while !stack.is_empty() && temperatures[*stack.last().unwrap()] <= temperatures[i] { + stack.pop(); + } + res[i] = if stack.is_empty() { 0 } else { (stack.last().unwrap() - i) as i32 }; + stack.push(i); + } + res + } } ``` -### **C++** + + +### 方法二 - + -```cpp +```python +class Solution: + def dailyTemperatures(self, temperatures: List[int]) -> List[int]: + n = len(temperatures) + stk = [] + ans = [0] * n + for i in range(n - 1, -1, -1): + while stk and temperatures[stk[-1]] <= temperatures[i]: + stk.pop() + if stk: + ans[i] = stk[-1] - i + stk.append(i) + return ans +``` + +```java class Solution { -public: - vector dailyTemperatures(vector& temperatures) { - int n = temperatures.size(); - vector ans(n); - stack stk; - for (int i = 0; i < n; ++i) { - while (!stk.empty() && temperatures[stk.top()] < temperatures[i]) { - ans[stk.top()] = i - stk.top(); + public int[] dailyTemperatures(int[] temperatures) { + int n = temperatures.length; + Deque stk = new ArrayDeque<>(); + int[] ans = new int[n]; + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && temperatures[stk.peek()] <= temperatures[i]) { stk.pop(); } + if (!stk.isEmpty()) { + ans[i] = stk.peek() - i; + } stk.push(i); } return ans; } -}; +} ``` ```cpp @@ -173,24 +215,6 @@ public: }; ``` -### **Go** - -```go -func dailyTemperatures(temperatures []int) []int { - ans := make([]int, len(temperatures)) - var stk []int - for i, t := range temperatures { - for len(stk) > 0 && temperatures[stk[len(stk)-1]] < t { - j := stk[len(stk)-1] - ans[j] = i - j - stk = stk[:len(stk)-1] - } - stk = append(stk, i) - } - return ans -} -``` - ```go func dailyTemperatures(temperatures []int) []int { n := len(temperatures) @@ -209,28 +233,6 @@ func dailyTemperatures(temperatures []int) []int { } ``` -### **TypeScript** - -倒序: - -```ts -function dailyTemperatures(temperatures: number[]): number[] { - const n = temperatures.length; - const res = new Array(n); - const stack = []; - for (let i = n - 1; i >= 0; i--) { - while (stack.length !== 0 && temperatures[stack[stack.length - 1]] <= temperatures[i]) { - stack.pop(); - } - res[i] = stack.length === 0 ? 0 : stack[stack.length - 1] - i; - stack.push(i); - } - return res; -} -``` - -正序: - ```ts function dailyTemperatures(temperatures: number[]): number[] { const n = temperatures.length; @@ -248,30 +250,6 @@ function dailyTemperatures(temperatures: number[]): number[] { } ``` -### **Rust** - -倒序: - -```rust -impl Solution { - pub fn daily_temperatures(temperatures: Vec) -> Vec { - let n = temperatures.len(); - let mut res = vec![0; n]; - let mut stack = Vec::new(); - for i in (0..n).rev() { - while !stack.is_empty() && temperatures[*stack.last().unwrap()] <= temperatures[i] { - stack.pop(); - } - res[i] = if stack.is_empty() { 0 } else { (stack.last().unwrap() - i) as i32 }; - stack.push(i); - } - res - } -} -``` - -正序: - ```rust impl Solution { pub fn daily_temperatures(temperatures: Vec) -> Vec { @@ -290,10 +268,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/README.md" index 547c42f94aa2e..11387562b3734 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 039. \347\233\264\346\226\271\345\233\276\346\234\200\345\244\247\347\237\251\345\275\242\351\235\242\347\247\257/README.md" @@ -30,9 +30,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 单调栈常见模型:找出每个数左/右边**离它最近的**且**比它大/小的数**。模板: @@ -50,10 +48,6 @@ for i in range(n): -### **Python3** - - - ```python class Solution: def largestRectangleArea(self, heights: List[int]) -> int: @@ -77,10 +71,6 @@ class Solution: return max(x * (r - l - 1) for x, l, r in zip(heights, left, right)) ``` -### **Java** - - - ```java class Solution { public int largestRectangleArea(int[] heights) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func largestRectangleArea(heights []int) (ans int) { n := len(heights) @@ -195,8 +181,6 @@ func largestRectangleArea(heights []int) (ans int) { } ``` -### **TypeScript** - ```ts function largestRectangleArea(heights: number[]): number { const n = heights.length; @@ -230,10 +214,6 @@ function largestRectangleArea(heights: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 040. \347\237\251\351\230\265\344\270\255\346\234\200\345\244\247\347\232\204\347\237\251\345\275\242/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 040. \347\237\251\351\230\265\344\270\255\346\234\200\345\244\247\347\232\204\347\237\251\345\275\242/README.md" index 013032023c864..12844cf252a60 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 040. \347\237\251\351\230\265\344\270\255\346\234\200\345\244\247\347\232\204\347\237\251\345\275\242/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 040. \347\237\251\351\230\265\344\270\255\346\234\200\345\244\247\347\232\204\347\237\251\345\275\242/README.md" @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 把每一行视为柱状图的底部,对每一行求柱状图的最大面积即可。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: @@ -117,10 +111,6 @@ class Solution: return max(h * (right[i] - left[i] - 1) for i, h in enumerate(heights)) ``` -### **Java** - - - ```java class Solution { public int maximalRectangle(String[] matrix) { @@ -164,13 +154,6 @@ class Solution { } ``` -### **C++** - -- 首先在柱状图中求最大矩形面积可以通过单调栈,维护每一列的左边第一个比它小的位置 $L$,和右边第一个比它小的位置 $R$,就能得到以这一列为高的最大矩形面积为 $(R-L-1)*h$。 -- 考虑每一行作为底边的柱状图中,能够得到的最大的矩形面积。再对每一行的最大面积取 $max$ 就是最终的答案。 -- 柱状图中每一列的高可以通过类似前缀和的方式去维护。 -- 假设矩阵大小为 $n*m$,那么时间复杂为 $O(nm)$,空间复杂度为 $O(m)$。 - ```cpp class Solution { public: @@ -205,48 +188,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maximalRectangle(vector& matrix) { - if (matrix.empty()) return 0; - int n = matrix[0].size(); - vector heights(n); - int ans = 0; - for (auto& row : matrix) { - for (int j = 0; j < n; ++j) { - if (row[j] == '1') - ++heights[j]; - else - heights[j] = 0; - } - ans = max(ans, largestRectangleArea(heights)); - } - return ans; - } - - int largestRectangleArea(vector& heights) { - int res = 0, n = heights.size(); - stack stk; - vector left(n, -1); - vector right(n, n); - for (int i = 0; i < n; ++i) { - while (!stk.empty() && heights[stk.top()] >= heights[i]) { - right[stk.top()] = i; - stk.pop(); - } - if (!stk.empty()) left[i] = stk.top(); - stk.push(i); - } - for (int i = 0; i < n; ++i) - res = max(res, heights[i] * (right[i] - left[i] - 1)); - return res; - } -}; -``` - -### **Go** - ```go func maximalRectangle(matrix []string) int { if len(matrix) == 0 { @@ -294,10 +235,52 @@ func largestRectangleArea(heights []int) int { } ``` -### **...** + + +### 方法二 -``` + +```cpp +class Solution { +public: + int maximalRectangle(vector& matrix) { + if (matrix.empty()) return 0; + int n = matrix[0].size(); + vector heights(n); + int ans = 0; + for (auto& row : matrix) { + for (int j = 0; j < n; ++j) { + if (row[j] == '1') + ++heights[j]; + else + heights[j] = 0; + } + ans = max(ans, largestRectangleArea(heights)); + } + return ans; + } + + int largestRectangleArea(vector& heights) { + int res = 0, n = heights.size(); + stack stk; + vector left(n, -1); + vector right(n, n); + for (int i = 0; i < n; ++i) { + while (!stk.empty() && heights[stk.top()] >= heights[i]) { + right[stk.top()] = i; + stk.pop(); + } + if (!stk.empty()) left[i] = stk.top(); + stk.push(i); + } + for (int i = 0; i < n; ++i) + res = max(res, heights[i] * (right[i] - left[i] - 1)); + return res; + } +}; ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/README.md" index dc3427a94b23f..ae88cce605154 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 041. \346\273\221\345\212\250\347\252\227\345\217\243\347\232\204\345\271\263\345\235\207\345\200\274/README.md" @@ -48,18 +48,10 @@ movingAverage.next(5); // 返回 6.0 = (10 + 3 + 5) / 3 ## 解法 - - -**方法一:循环数组** - -**方法二:队列** +### 方法一:循环数组 -### **Python3** - - - ```python class MovingAverage: def __init__(self, size: int): @@ -80,30 +72,6 @@ class MovingAverage: # param_1 = obj.next(val) ``` -```python -class MovingAverage: - def __init__(self, size: int): - self.n = size - self.s = 0 - self.q = deque() - - def next(self, val: int) -> float: - if len(self.q) == self.n: - self.s -= self.q.popleft() - self.q.append(val) - self.s += val - return self.s / len(self.q) - - -# Your MovingAverage object will be instantiated and called as such: -# obj = MovingAverage(size) -# param_1 = obj.next(val) -``` - -### **Java** - - - ```java class MovingAverage { private int[] arr; @@ -130,35 +98,6 @@ class MovingAverage { */ ``` -```java -class MovingAverage { - private Deque q = new ArrayDeque<>(); - private int n; - private int s; - - public MovingAverage(int size) { - n = size; - } - - public double next(int val) { - if (q.size() == n) { - s -= q.pollFirst(); - } - q.offer(val); - s += val; - return s * 1.0 / q.size(); - } -} - -/** - * Your MovingAverage object will be instantiated and called as such: - * MovingAverage obj = new MovingAverage(size); - * double param_1 = obj.next(val); - */ -``` - -### **C++** - ```cpp class MovingAverage { public: @@ -187,6 +126,86 @@ private: */ ``` +```go +type MovingAverage struct { + arr []int + cnt int + s int +} + +func Constructor(size int) MovingAverage { + arr := make([]int, size) + return MovingAverage{arr, 0, 0} +} + +func (this *MovingAverage) Next(val int) float64 { + idx := this.cnt % len(this.arr) + this.s += val - this.arr[idx] + this.arr[idx] = val + this.cnt++ + return float64(this.s) / float64(min(this.cnt, len(this.arr))) +} + +/** + * Your MovingAverage object will be instantiated and called as such: + * obj := Constructor(size); + * param_1 := obj.Next(val); + */ +``` + + + +### 方法二:队列 + + + +```python +class MovingAverage: + def __init__(self, size: int): + self.n = size + self.s = 0 + self.q = deque() + + def next(self, val: int) -> float: + if len(self.q) == self.n: + self.s -= self.q.popleft() + self.q.append(val) + self.s += val + return self.s / len(self.q) + + +# Your MovingAverage object will be instantiated and called as such: +# obj = MovingAverage(size) +# param_1 = obj.next(val) +``` + +```java +class MovingAverage { + private Deque q = new ArrayDeque<>(); + private int n; + private int s; + + public MovingAverage(int size) { + n = size; + } + + public double next(int val) { + if (q.size() == n) { + s -= q.pollFirst(); + } + q.offer(val); + s += val; + return s * 1.0 / q.size(); + } +} + +/** + * Your MovingAverage object will be instantiated and called as such: + * MovingAverage obj = new MovingAverage(size); + * double param_1 = obj.next(val); + */ +``` + ```cpp class MovingAverage { public: @@ -217,35 +236,6 @@ private: */ ``` -### **Go** - -```go -type MovingAverage struct { - arr []int - cnt int - s int -} - -func Constructor(size int) MovingAverage { - arr := make([]int, size) - return MovingAverage{arr, 0, 0} -} - -func (this *MovingAverage) Next(val int) float64 { - idx := this.cnt % len(this.arr) - this.s += val - this.arr[idx] - this.arr[idx] = val - this.cnt++ - return float64(this.s) / float64(min(this.cnt, len(this.arr))) -} - -/** - * Your MovingAverage object will be instantiated and called as such: - * obj := Constructor(size); - * param_1 := obj.Next(val); - */ -``` - ```go type MovingAverage struct { q []int @@ -274,10 +264,6 @@ func (this *MovingAverage) Next(val int) float64 { */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 042. \346\234\200\350\277\221\350\257\267\346\261\202\346\254\241\346\225\260/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 042. \346\234\200\350\277\221\350\257\267\346\261\202\346\254\241\346\225\260/README.md" index 0b913d67ccd55..5da729d01d6ae 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 042. \346\234\200\350\277\221\350\257\267\346\261\202\346\254\241\346\225\260/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 042. \346\234\200\350\277\221\350\257\267\346\261\202\346\254\241\346\225\260/README.md" @@ -50,18 +50,10 @@ recentCounter.ping(3002); // requests = [1, 100, 3001< ## 解法 - - -在第 1、100、3001、3002 这四个时间点分别进行了 ping 请求, 在 3001 秒的时候, 它前面的 3000 秒指的是区间 `[1,3001]`, 所以一共是有 `1、100、3001` 三个请求, t = 3002 的前 3000 秒指的是区间 `[2,3002]`, 所以有 `100、3001、3002` 三次请求。 - -可以用队列实现。每次将 t 进入队尾,同时从队头开始依次移除小于 `t-3000` 的元素。然后返回队列的大小 `q.size()` 即可。 +### 方法一 -### **Python3** - - - ```python class RecentCounter: def __init__(self): @@ -79,10 +71,6 @@ class RecentCounter: # param_1 = obj.ping(t) ``` -### **Java** - - - ```java class RecentCounter { private Deque q; @@ -107,8 +95,6 @@ class RecentCounter { */ ``` -### **C++** - ```cpp class RecentCounter { public: @@ -133,8 +119,6 @@ public: */ ``` -### **Go** - ```go type RecentCounter struct { q []int @@ -161,7 +145,26 @@ func (this *RecentCounter) Ping(t int) int { */ ``` -### **JavaScript** +```ts +class RecentCounter { + stack: Array; + cnt: number; + constructor() { + this.stack = []; + this.cnt = 0; + } + + ping(t: number): number { + while (this.stack.length && this.stack[0] + 3000 < t) { + this.cnt--; + this.stack.shift(); + } + this.cnt++; + this.stack.push(t); + return this.cnt; + } +} +``` ```js var RecentCounter = function () { @@ -187,10 +190,6 @@ RecentCounter.prototype.ping = function (t) { */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 043. \345\276\200\345\256\214\345\205\250\344\272\214\345\217\211\346\240\221\346\267\273\345\212\240\350\212\202\347\202\271/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 043. \345\276\200\345\256\214\345\205\250\344\272\214\345\217\211\346\240\221\346\267\273\345\212\240\350\212\202\347\202\271/README.md" index b5fe6e0a9c556..f028951f61603 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 043. \345\276\200\345\256\214\345\205\250\344\272\214\345\217\211\346\240\221\346\267\273\345\212\240\350\212\202\347\202\271/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 043. \345\276\200\345\256\214\345\205\250\344\272\214\345\217\211\346\240\221\346\267\273\345\212\240\350\212\202\347\202\271/README.md" @@ -49,14 +49,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -98,10 +94,6 @@ class CBTInserter: # param_2 = obj.get_root() ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -163,8 +155,6 @@ class CBTInserter { */ ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -217,8 +207,6 @@ public: */ ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -274,8 +262,6 @@ func (this *CBTInserter) Get_root() *TreeNode { */ ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -335,10 +321,6 @@ CBTInserter.prototype.get_root = function () { */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 044. \344\272\214\345\217\211\346\240\221\346\257\217\345\261\202\347\232\204\346\234\200\345\244\247\345\200\274/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 044. \344\272\214\345\217\211\346\240\221\346\257\217\345\261\202\347\232\204\346\234\200\345\244\247\345\200\274/README.md" index fdf23fb104032..1bdd2dffddce1 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 044. \344\272\214\345\217\211\346\240\221\346\257\217\345\261\202\347\232\204\346\234\200\345\244\247\345\200\274/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 044. \344\272\214\345\217\211\346\240\221\346\257\217\345\261\202\347\232\204\346\234\200\345\244\247\345\200\274/README.md" @@ -72,16 +72,10 @@ ## 解法 - - -“BFS 层次遍历”实现。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -108,10 +102,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -155,8 +145,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -191,8 +179,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -227,10 +213,6 @@ func largestValues(root *TreeNode) []int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 045. \344\272\214\345\217\211\346\240\221\346\234\200\345\272\225\345\261\202\346\234\200\345\267\246\350\276\271\347\232\204\345\200\274/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 045. \344\272\214\345\217\211\346\240\221\346\234\200\345\272\225\345\261\202\346\234\200\345\267\246\350\276\271\347\232\204\345\200\274/README.md" index 7d1483163c138..9bf536f6a1b3f 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 045. \344\272\214\345\217\211\346\240\221\346\234\200\345\272\225\345\261\202\346\234\200\345\267\246\350\276\271\347\232\204\345\200\274/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 045. \344\272\214\345\217\211\346\240\221\346\234\200\345\272\225\345\261\202\346\234\200\345\267\246\350\276\271\347\232\204\345\200\274/README.md" @@ -43,16 +43,10 @@ ## 解法 - - -“BFS 层次遍历”实现。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -77,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -189,10 +175,6 @@ func findBottomLeftValue(root *TreeNode) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 046. \344\272\214\345\217\211\346\240\221\347\232\204\345\217\263\344\276\247\350\247\206\345\233\276/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 046. \344\272\214\345\217\211\346\240\221\347\232\204\345\217\263\344\276\247\350\247\206\345\233\276/README.md" index e3c7419c2ea7e..971b94278f699 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 046. \344\272\214\345\217\211\346\240\221\347\232\204\345\217\263\344\276\247\350\247\206\345\233\276/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 046. \344\272\214\345\217\211\346\240\221\347\232\204\345\217\263\344\276\247\350\247\206\345\233\276/README.md" @@ -46,16 +46,10 @@ ## 解法 - - -层序遍历,取每层最后一个元素。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -195,10 +181,6 @@ func rightSideView(root *TreeNode) []int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 047. \344\272\214\345\217\211\346\240\221\345\211\252\346\236\235/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 047. \344\272\214\345\217\211\346\240\221\345\211\252\346\236\235/README.md" index ecf902ff997f0..8b71af953a23c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 047. \344\272\214\345\217\211\346\240\221\345\211\252\346\236\235/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 047. \344\272\214\345\217\211\346\240\221\345\211\252\346\236\235/README.md" @@ -57,14 +57,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -83,10 +79,6 @@ class Solution: return root ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -118,32 +110,6 @@ class Solution { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func pruneTree(root *TreeNode) *TreeNode { - if root == nil { - return nil - } - root.Left = pruneTree(root.Left) - root.Right = pruneTree(root.Right) - if root.Val == 0 && root.Left == nil && root.Right == nil { - return nil - } - return root -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -168,7 +134,27 @@ public: }; ``` -### **JavaScript** +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func pruneTree(root *TreeNode) *TreeNode { + if root == nil { + return nil + } + root.Left = pruneTree(root.Left) + root.Right = pruneTree(root.Right) + if root.Val == 0 && root.Left == nil && root.Right == nil { + return nil + } + return root +} +``` ```js /** @@ -194,10 +180,6 @@ var pruneTree = function (root) { }; ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 048. \345\272\217\345\210\227\345\214\226\344\270\216\345\217\215\345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 048. \345\272\217\345\210\227\345\214\226\344\270\216\345\217\215\345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/README.md" index d11f6700d97ff..d8d088a9b0fbe 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 048. \345\272\217\345\210\227\345\214\226\344\270\216\345\217\215\345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 048. \345\272\217\345\210\227\345\214\226\344\270\216\345\217\215\345\272\217\345\210\227\345\214\226\344\272\214\345\217\211\346\240\221/README.md" @@ -56,14 +56,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode(object): @@ -121,10 +117,6 @@ class Codec: # ans = deser.deserialize(ser.serialize(root)) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -189,8 +181,6 @@ public class Codec { // TreeNode ans = deser.deserialize(ser.serialize(root)); ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -244,8 +234,6 @@ public: // TreeNode* ans = deser.deserialize(ser.serialize(root)); ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -307,10 +295,6 @@ const rdeserialize = dataList => { */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 049. \344\273\216\346\240\271\350\212\202\347\202\271\345\210\260\345\217\266\350\212\202\347\202\271\347\232\204\350\267\257\345\276\204\346\225\260\345\255\227\344\271\213\345\222\214/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 049. \344\273\216\346\240\271\350\212\202\347\202\271\345\210\260\345\217\266\350\212\202\347\202\271\347\232\204\350\267\257\345\276\204\346\225\260\345\255\227\344\271\213\345\222\214/README.md" index 471913383b59d..4d91800ee5d7b 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 049. \344\273\216\346\240\271\350\212\202\347\202\271\345\210\260\345\217\266\350\212\202\347\202\271\347\232\204\350\267\257\345\276\204\346\225\260\345\255\227\344\271\213\345\222\214/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 049. \344\273\216\346\240\271\350\212\202\347\202\271\345\210\260\345\217\266\350\212\202\347\202\271\347\232\204\350\267\257\345\276\204\346\225\260\345\255\227\344\271\213\345\222\214/README.md" @@ -60,16 +60,10 @@ ## 解法 - - -DFS。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -90,10 +84,6 @@ class Solution: return dfs(root, 0) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -183,3 +169,7 @@ func sumNumbers(root *TreeNode) int { return dfs(root, 0) } ``` + + + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 050. \345\220\221\344\270\213\347\232\204\350\267\257\345\276\204\350\212\202\347\202\271\344\271\213\345\222\214/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 050. \345\220\221\344\270\213\347\232\204\350\267\257\345\276\204\350\212\202\347\202\271\344\271\213\345\222\214/README.md" index d97a4229bead0..5fbe65f8963b3 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 050. \345\220\221\344\270\213\347\232\204\350\267\257\345\276\204\350\212\202\347\202\271\344\271\213\345\222\214/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 050. \345\220\221\344\270\213\347\232\204\350\267\257\345\276\204\350\212\202\347\202\271\344\271\213\345\222\214/README.md" @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:哈希表 + 前缀和 + 递归** +### 方法一:哈希表 + 前缀和 + 递归 我们可以运用前缀和的思想,对二叉树进行递归遍历,同时用哈希表 $cnt$ 统计从根节点到当前节点的路径上各个前缀和出现的次数。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -93,10 +87,6 @@ class Solution: return dfs(root, 0) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -138,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -171,8 +159,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -200,8 +186,6 @@ func pathSum(root *TreeNode, targetSum int) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -236,10 +220,6 @@ function pathSum(root: TreeNode | null, targetSum: number): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/README.md" index 2dec89f03201a..eb7f81e8855b4 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 051. \350\212\202\347\202\271\344\271\213\345\222\214\346\234\200\345\244\247\347\232\204\350\267\257\345\276\204/README.md" @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们思考二叉树递归问题的经典套路: @@ -72,10 +70,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -99,10 +93,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -172,8 +160,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -200,8 +186,6 @@ func maxPathSum(root *TreeNode) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -233,7 +217,46 @@ function maxPathSum(root: TreeNode | null): number { } ``` -### **JavaScript** +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(root: &Option>>, res: &mut i32) -> i32 { + if root.is_none() { + return 0; + } + let node = root.as_ref().unwrap().borrow(); + let left = (0).max(Self::dfs(&node.left, res)); + let right = (0).max(Self::dfs(&node.right, res)); + *res = (node.val + left + right).max(*res); + node.val + left.max(right) + } + + pub fn max_path_sum(root: Option>>) -> i32 { + let mut res = -1000; + Self::dfs(&root, &mut res); + res + } +} +``` ```js /** @@ -264,8 +287,6 @@ var maxPathSum = function (root) { }; ``` -### **C#** - ```cs /** * Definition for a binary tree node. @@ -300,53 +321,6 @@ public class Solution { } ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(root: &Option>>, res: &mut i32) -> i32 { - if root.is_none() { - return 0; - } - let node = root.as_ref().unwrap().borrow(); - let left = (0).max(Self::dfs(&node.left, res)); - let right = (0).max(Self::dfs(&node.right, res)); - *res = (node.val + left + right).max(*res); - node.val + left.max(right) - } - - pub fn max_path_sum(root: Option>>) -> i32 { - let mut res = -1000; - Self::dfs(&root, &mut res); - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/README.md" index faaaad51d41ff..a9fd19c0b72e2 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 052. \345\261\225\345\271\263\344\272\214\345\217\211\346\220\234\347\264\242\346\240\221/README.md" @@ -41,16 +41,10 @@ ## 解法 - - -由于二叉搜索树的性质,可以利用中序遍历得到递增序列 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -78,37 +72,6 @@ class Solution: return head ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def increasingBST(self, root: TreeNode) -> TreeNode: - def dfs(root: TreeNode): - if root is None: - return - - dfs(root.left) - - nonlocal cur - cur.right = root - root.left = None - cur = cur.right - - dfs(root.right) - - cur = dummy = TreeNode() - dfs(root) - return dummy.right -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -150,110 +113,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private TreeNode cur; - - public TreeNode increasingBST(TreeNode root) { - TreeNode dummy = new TreeNode(); - cur = dummy; - dfs(root); - return dummy.right; - } - - private void dfs(TreeNode root) { - if (root == null) { - return; - } - dfs(root.left); - cur.right = root; - root.left = null; - cur = cur.right; - dfs(root.right); - } -} -``` - -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func increasingBST(root *TreeNode) *TreeNode { - var head, tail *TreeNode - stack := make([]*TreeNode, 0) - cur := root - for len(stack) > 0 || cur != nil { - for cur != nil { - stack = append(stack, cur) - cur = cur.Left - } - cur = stack[len(stack)-1] - stack = stack[:len(stack)-1] - if head == nil { - head = cur - } else { - tail.Right = cur - } - tail = cur - cur.Left = nil - cur = cur.Right - } - return head -} -``` - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func increasingBST(root *TreeNode) *TreeNode { - dummy := &TreeNode{} - cur := dummy - var dfs func(*TreeNode) - dfs = func(root *TreeNode) { - if root == nil { - return - } - dfs(root.Left) - root.Left = nil - cur.Right = root - cur = root - dfs(root.Right) - } - dfs(root) - return dummy.Right -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -293,41 +152,39 @@ public: }; ``` -```cpp +```go /** * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } */ -class Solution { -public: - TreeNode* increasingBST(TreeNode* root) { - TreeNode* dummy = new TreeNode(); - TreeNode* cur = dummy; - function dfs = [&](TreeNode* root) { - if (!root) { - return; - } - dfs(root->left); - cur->right = root; - root->left = nullptr; - cur = cur->right; - dfs(root->right); - }; - dfs(root); - return dummy->right; - } -}; +func increasingBST(root *TreeNode) *TreeNode { + var head, tail *TreeNode + stack := make([]*TreeNode, 0) + cur := root + for len(stack) > 0 || cur != nil { + for cur != nil { + stack = append(stack, cur) + cur = cur.Left + } + cur = stack[len(stack)-1] + stack = stack[:len(stack)-1] + if head == nil { + head = cur + } else { + tail.Right = cur + } + tail = cur + cur.Left = nil + cur = cur.Right + } + return head +} ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -360,8 +217,6 @@ function increasingBST(root: TreeNode | null): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -416,8 +271,6 @@ impl Solution { } ``` -### **C** - ```c /** * Definition for a binary tree node. @@ -448,10 +301,139 @@ struct TreeNode* increasingBST(struct TreeNode* root) { } ``` -### **...** + + +### 方法二 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def increasingBST(self, root: TreeNode) -> TreeNode: + def dfs(root: TreeNode): + if root is None: + return + + dfs(root.left) + + nonlocal cur + cur.right = root + root.left = None + cur = cur.right + + dfs(root.right) + + cur = dummy = TreeNode() + dfs(root) + return dummy.right +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private TreeNode cur; + + public TreeNode increasingBST(TreeNode root) { + TreeNode dummy = new TreeNode(); + cur = dummy; + dfs(root); + return dummy.right; + } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + dfs(root.left); + cur.right = root; + root.left = null; + cur = cur.right; + dfs(root.right); + } +} +``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* increasingBST(TreeNode* root) { + TreeNode* dummy = new TreeNode(); + TreeNode* cur = dummy; + function dfs = [&](TreeNode* root) { + if (!root) { + return; + } + dfs(root->left); + cur->right = root; + root->left = nullptr; + cur = cur->right; + dfs(root->right); + }; + dfs(root); + return dummy->right; + } +}; ``` +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func increasingBST(root *TreeNode) *TreeNode { + dummy := &TreeNode{} + cur := dummy + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return + } + dfs(root.Left) + root.Left = nil + cur.Right = root + cur = root + dfs(root.Right) + } + dfs(root) + return dummy.Right +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/README.md" index f4797b19000a9..64b0c826934c2 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 053. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\347\232\204\344\270\255\345\272\217\345\220\216\347\273\247/README.md" @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:二分搜索** +### 方法一:二分搜索 二叉搜索树的中序遍历是一个升序序列,因此可以使用二分搜索的方法。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -147,8 +135,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -171,8 +157,6 @@ func inorderSuccessor(root *TreeNode, p *TreeNode) (ans *TreeNode) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -202,10 +186,6 @@ function inorderSuccessor(root: TreeNode | null, p: TreeNode | null): TreeNode | } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/README.md" index b6332534200b7..dc1ead18e411f 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 054. \346\211\200\346\234\211\345\244\247\344\272\216\347\255\211\344\272\216\350\212\202\347\202\271\347\232\204\345\200\274\344\271\213\345\222\214/README.md" @@ -70,43 +70,14 @@ ## 解法 - - -**前言** - -二叉搜索树的中序遍历(左根右)结果是一个单调递增的有序序列,我们反序进行中序遍历(右根左),即可以得到一个单调递减的有序序列。通过累加单调递减的有序序列,我们可以得到大于等于 `node.val` 的新值,并重新赋值给 `node`。 - -关于反序中序遍历,有三种方法,一是递归遍历,二是栈实现非递归遍历,三是 Morris 遍历。 - -**方法一:递归** +### 方法一:递归 按照“右根左”的顺序,递归遍历二叉搜索树,累加遍历到的所有节点值到 $s$ 中,然后每次赋值给对应的 `node` 节点。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉搜索树的节点数。 -**方法二:Morris 遍历** - -Morris 遍历无需使用栈,时间复杂度 $O(n)$,空间复杂度为 $O(1)$。核心思想是: - -定义 s 表示二叉搜索树节点值累加和。遍历二叉树节点: - -1. 若当前节点 root 的右子树为空,**将当前节点值添加至 s** 中,更新当前节点值为 s,并将当前节点更新为 `root.left`。 -2. 若当前节点 root 的右子树不为空,找到右子树的最左节点 next(也即是 root 节点在中序遍历下的后继节点): - - 若后继节点 next 的左子树为空,将后继节点的左子树指向当前节点 root,并将当前节点更新为 `root.right`。 - - 若后继节点 next 的左子树不为空,**将当前节点值添加 s** 中,更新当前节点值为 s,然后将后继节点左子树指向空(即解除 next 与 root 的指向关系),并将当前节点更新为 `root.left`。 -3. 循环以上步骤,直至二叉树节点为空,遍历结束。 -4. 最后返回二叉搜索树根节点即可。 - -> Morris 反序中序遍历跟 Morris 中序遍历思路一致,只是将中序遍历的“左根右”变为“右根左”。 - -### **Python3** - - - -递归遍历: - ```python # Definition for a binary tree node. # class TreeNode: @@ -130,45 +101,6 @@ class Solution: return root ``` -Morris 遍历: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def convertBST(self, root: TreeNode) -> TreeNode: - s = 0 - node = root - while root: - if root.right is None: - s += root.val - root.val = s - root = root.left - else: - next = root.right - while next.left and next.left != root: - next = next.left - if next.left is None: - next.left = root - root = root.right - else: - s += root.val - root.val = s - next.left = None - root = root.left - return node -``` - -### **Java** - - - -递归遍历: - ```java /** * Definition for a binary tree node. @@ -205,58 +137,6 @@ class Solution { } ``` -Morris 遍历: - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public TreeNode convertBST(TreeNode root) { - int s = 0; - TreeNode node = root; - while (root != null) { - if (root.right == null) { - s += root.val; - root.val = s; - root = root.left; - } else { - TreeNode next = root.right; - while (next.left != null && next.left != root) { - next = next.left; - } - if (next.left == null) { - next.left = root; - root = root.right; - } else { - s += root.val; - root.val = s; - next.left = null; - root = root.left; - } - } - } - return node; - } -} -``` - -### **C++** - -递归遍历: - ```cpp /** * Definition for a binary tree node. @@ -288,55 +168,6 @@ public: }; ``` -Morris 遍历: - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* convertBST(TreeNode* root) { - int s = 0; - TreeNode* node = root; - while (root) { - if (root->right == nullptr) { - s += root->val; - root->val = s; - root = root->left; - } else { - TreeNode* next = root->right; - while (next->left && next->left != root) { - next = next->left; - } - if (next->left == nullptr) { - next->left = root; - root = root->right; - } else { - s += root->val; - root->val = s; - next->left = nullptr; - root = root->left; - } - } - } - return node; - } -}; -``` - -### **Go** - -递归遍历: - ```go /** * Definition for a binary tree node. @@ -363,78 +194,6 @@ func convertBST(root *TreeNode) *TreeNode { } ``` -Morris 遍历: - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func convertBST(root *TreeNode) *TreeNode { - s := 0 - node := root - for root != nil { - if root.Right == nil { - s += root.Val - root.Val = s - root = root.Left - } else { - next := root.Right - for next.Left != nil && next.Left != root { - next = next.Left - } - if next.Left == nil { - next.Left = root - root = root.Right - } else { - s += root.Val - root.Val = s - next.Left = nil - root = root.Left - } - } - } - return node -} -``` - -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {TreeNode} - */ -var convertBST = function (root) { - let s = 0; - function dfs(root) { - if (!root) { - return; - } - dfs(root.right); - s += root.val; - root.val = s; - dfs(root.left); - } - dfs(root); - return root; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -466,8 +225,6 @@ function convertBST(root: TreeNode | null): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -506,10 +263,211 @@ impl Solution { } ``` -### **...** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {TreeNode} + */ +var convertBST = function (root) { + let s = 0; + function dfs(root) { + if (!root) { + return; + } + dfs(root.right); + s += root.val; + root.val = s; + dfs(root.left); + } + dfs(root); + return root; +}; +``` + + + +### 方法二:Morris 遍历 + +Morris 遍历无需使用栈,时间复杂度 $O(n)$,空间复杂度为 $O(1)$。核心思想是: + +定义 s 表示二叉搜索树节点值累加和。遍历二叉树节点: + +1. 若当前节点 root 的右子树为空,**将当前节点值添加至 s** 中,更新当前节点值为 s,并将当前节点更新为 `root.left`。 +2. 若当前节点 root 的右子树不为空,找到右子树的最左节点 next(也即是 root 节点在中序遍历下的后继节点): + - 若后继节点 next 的左子树为空,将后继节点的左子树指向当前节点 root,并将当前节点更新为 `root.right`。 + - 若后继节点 next 的左子树不为空,**将当前节点值添加 s** 中,更新当前节点值为 s,然后将后继节点左子树指向空(即解除 next 与 root 的指向关系),并将当前节点更新为 `root.left`。 +3. 循环以上步骤,直至二叉树节点为空,遍历结束。 +4. 最后返回二叉搜索树根节点即可。 + +> Morris 反序中序遍历跟 Morris 中序遍历思路一致,只是将中序遍历的“左根右”变为“右根左”。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def convertBST(self, root: TreeNode) -> TreeNode: + s = 0 + node = root + while root: + if root.right is None: + s += root.val + root.val = s + root = root.left + else: + next = root.right + while next.left and next.left != root: + next = next.left + if next.left is None: + next.left = root + root = root.right + else: + s += root.val + root.val = s + next.left = None + root = root.left + return node +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode convertBST(TreeNode root) { + int s = 0; + TreeNode node = root; + while (root != null) { + if (root.right == null) { + s += root.val; + root.val = s; + root = root.left; + } else { + TreeNode next = root.right; + while (next.left != null && next.left != root) { + next = next.left; + } + if (next.left == null) { + next.left = root; + root = root.right; + } else { + s += root.val; + root.val = s; + next.left = null; + root = root.left; + } + } + } + return node; + } +} +``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* convertBST(TreeNode* root) { + int s = 0; + TreeNode* node = root; + while (root) { + if (root->right == nullptr) { + s += root->val; + root->val = s; + root = root->left; + } else { + TreeNode* next = root->right; + while (next->left && next->left != root) { + next = next->left; + } + if (next->left == nullptr) { + next->left = root; + root = root->right; + } else { + s += root->val; + root->val = s; + next->left = nullptr; + root = root->left; + } + } + } + return node; + } +}; ``` +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func convertBST(root *TreeNode) *TreeNode { + s := 0 + node := root + for root != nil { + if root.Right == nil { + s += root.Val + root.Val = s + root = root.Left + } else { + next := root.Right + for next.Left != nil && next.Left != root { + next = next.Left + } + if next.Left == nil { + next.Left = root + root = root.Right + } else { + s += root.Val + root.Val = s + next.Left = nil + root = root.Left + } + } + } + return node +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/README.md" index a52123ab656c9..45b40a08ffd06 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 055. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\350\277\255\344\273\243\345\231\250/README.md" @@ -70,26 +70,14 @@ bSTIterator.hasNext(); // 返回 False ## 解法 - - -**方法一:递归** +### 方法一:递归 初始化数据时,递归中序遍历,将二叉搜索树每个结点的值保存在列表 `vals` 中。用 `cur` 指针记录外部即将遍历的位置,初始化为 0。 调用 `next()` 时,返回 `vals[cur]`,同时 `cur` 指针自增。调用 `hasNext()` 时,判断 `cur` 指针是否已经达到 `len(vals)` 个数,若是,说明已经遍历结束,返回 false,否则返回 true。 -**方法二:栈迭代** - -初始化时,从根节点一路遍历所有左子节点,压入栈 `stack` 中。 - -调用 `next()`时,弹出栈顶元素 `cur`,获取 `cur` 的右子节点 `node`,若 `node` 不为空,一直循环压入左节点。最后返回 `cur.val` 即可。调用 `hasNext()` 时,判断 `stack` 是否为空,空则表示迭代结束。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -124,42 +112,6 @@ class BSTIterator: # param_2 = obj.hasNext() ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class BSTIterator: - def __init__(self, root: TreeNode): - self.stack = [] - while root: - self.stack.append(root) - root = root.left - - def next(self) -> int: - cur = self.stack.pop() - node = cur.right - while node: - self.stack.append(node) - node = node.left - return cur.val - - def hasNext(self) -> bool: - return len(self.stack) > 0 - - -# Your BSTIterator object will be instantiated and called as such: -# obj = BSTIterator(root) -# param_1 = obj.next() -# param_2 = obj.hasNext() -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -209,54 +161,6 @@ class BSTIterator { */ ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class BSTIterator { - private Deque stack = new LinkedList<>(); - - public BSTIterator(TreeNode root) { - for (; root != null; root = root.left) { - stack.offerLast(root); - } - } - - public int next() { - TreeNode cur = stack.pollLast(); - for (TreeNode node = cur.right; node != null; node = node.left) { - stack.offerLast(node); - } - return cur.val; - } - - public boolean hasNext() { - return !stack.isEmpty(); - } -} - -/** - * Your BSTIterator object will be instantiated and called as such: - * BSTIterator obj = new BSTIterator(root); - * int param_1 = obj.next(); - * boolean param_2 = obj.hasNext(); - */ -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -303,52 +207,6 @@ public: */ ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class BSTIterator { -public: - stack stack; - BSTIterator(TreeNode* root) { - for (; root != nullptr; root = root->left) { - stack.push(root); - } - } - - int next() { - TreeNode* cur = stack.top(); - stack.pop(); - TreeNode* node = cur->right; - for (; node != nullptr; node = node->left) { - stack.push(node); - } - return cur->val; - } - - bool hasNext() { - return !stack.empty(); - } -}; - -/** - * Your BSTIterator object will be instantiated and called as such: - * BSTIterator* obj = new BSTIterator(root); - * int param_1 = obj->next(); - * bool param_2 = obj->hasNext(); - */ -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -393,56 +251,6 @@ func (this *BSTIterator) HasNext() bool { */ ``` -## **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - */ -var BSTIterator = function (root) { - this.stack = []; - for (; root != null; root = root.left) { - this.stack.push(root); - } -}; - -/** - * @return {number} - */ -BSTIterator.prototype.next = function () { - let cur = this.stack.pop(); - let node = cur.right; - for (; node != null; node = node.left) { - this.stack.push(node); - } - return cur.val; -}; - -/** - * @return {boolean} - */ -BSTIterator.prototype.hasNext = function () { - return this.stack.length > 0; -}; - -/** - * Your BSTIterator object will be instantiated and called as such: - * var obj = new BSTIterator(root) - * var param_1 = obj.next() - * var param_2 = obj.hasNext() - */ -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -488,8 +296,6 @@ class BSTIterator { */ ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -554,10 +360,184 @@ impl BSTIterator { */ ``` -### **...** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + */ +var BSTIterator = function (root) { + this.stack = []; + for (; root != null; root = root.left) { + this.stack.push(root); + } +}; + +/** + * @return {number} + */ +BSTIterator.prototype.next = function () { + let cur = this.stack.pop(); + let node = cur.right; + for (; node != null; node = node.left) { + this.stack.push(node); + } + return cur.val; +}; + +/** + * @return {boolean} + */ +BSTIterator.prototype.hasNext = function () { + return this.stack.length > 0; +}; + +/** + * Your BSTIterator object will be instantiated and called as such: + * var obj = new BSTIterator(root) + * var param_1 = obj.next() + * var param_2 = obj.hasNext() + */ +``` + + + +### 方法二:栈迭代 + +初始化时,从根节点一路遍历所有左子节点,压入栈 `stack` 中。 + +调用 `next()`时,弹出栈顶元素 `cur`,获取 `cur` 的右子节点 `node`,若 `node` 不为空,一直循环压入左节点。最后返回 `cur.val` 即可。调用 `hasNext()` 时,判断 `stack` 是否为空,空则表示迭代结束。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class BSTIterator: + def __init__(self, root: TreeNode): + self.stack = [] + while root: + self.stack.append(root) + root = root.left + + def next(self) -> int: + cur = self.stack.pop() + node = cur.right + while node: + self.stack.append(node) + node = node.left + return cur.val + + def hasNext(self) -> bool: + return len(self.stack) > 0 + + +# Your BSTIterator object will be instantiated and called as such: +# obj = BSTIterator(root) +# param_1 = obj.next() +# param_2 = obj.hasNext() +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class BSTIterator { + private Deque stack = new LinkedList<>(); + public BSTIterator(TreeNode root) { + for (; root != null; root = root.left) { + stack.offerLast(root); + } + } + + public int next() { + TreeNode cur = stack.pollLast(); + for (TreeNode node = cur.right; node != null; node = node.left) { + stack.offerLast(node); + } + return cur.val; + } + + public boolean hasNext() { + return !stack.isEmpty(); + } +} + +/** + * Your BSTIterator object will be instantiated and called as such: + * BSTIterator obj = new BSTIterator(root); + * int param_1 = obj.next(); + * boolean param_2 = obj.hasNext(); + */ ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class BSTIterator { +public: + stack stack; + BSTIterator(TreeNode* root) { + for (; root != nullptr; root = root->left) { + stack.push(root); + } + } + + int next() { + TreeNode* cur = stack.top(); + stack.pop(); + TreeNode* node = cur->right; + for (; node != nullptr; node = node->left) { + stack.push(node); + } + return cur->val; + } + + bool hasNext() { + return !stack.empty(); + } +}; + +/** + * Your BSTIterator object will be instantiated and called as such: + * BSTIterator* obj = new BSTIterator(root); + * int param_1 = obj->next(); + * bool param_2 = obj->hasNext(); + */ ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 056. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\344\270\244\344\270\252\350\212\202\347\202\271\344\271\213\345\222\214/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 056. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\344\270\244\344\270\252\350\212\202\347\202\271\344\271\213\345\222\214/README.md" index 60dfd49f43841..822f3db4da58e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 056. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\344\270\244\344\270\252\350\212\202\347\202\271\344\271\213\345\222\214/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 056. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\344\270\255\344\270\244\344\270\252\350\212\202\347\202\271\344\271\213\345\222\214/README.md" @@ -41,16 +41,10 @@ ## 解法 - - -用哈希表记录访问过的节点。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -72,10 +66,6 @@ class Solution: return find(root) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -113,38 +103,6 @@ class Solution { } ``` -### **TypeScript** - -```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 findTarget(root: TreeNode | null, k: number): boolean { - let nodes: Set = new Set(); - return find(root, k, nodes); -} - -function find(root: TreeNode | null, k: number, nodes: Set): boolean { - if (!root) return false; - if (nodes.has(k - root.val)) return true; - nodes.add(root.val); - return find(root.left, k, nodes) || find(root.right, k, nodes); -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -174,8 +132,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -203,10 +159,34 @@ func findTarget(root *TreeNode, k int) bool { } ``` -### **...** +```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 findTarget(root: TreeNode | null, k: number): boolean { + let nodes: Set = new Set(); + return find(root, k, nodes); +} +function find(root: TreeNode | null, k: number, nodes: Set): boolean { + if (!root) return false; + if (nodes.has(k - root.val)) return true; + nodes.add(root.val); + return find(root.left, k, nodes) || find(root.right, k, nodes); +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 057. \345\200\274\345\222\214\344\270\213\346\240\207\344\271\213\345\267\256\351\203\275\345\234\250\347\273\231\345\256\232\347\232\204\350\214\203\345\233\264\345\206\205/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 057. \345\200\274\345\222\214\344\270\213\346\240\207\344\271\213\345\267\256\351\203\275\345\234\250\347\273\231\345\256\232\347\232\204\350\214\203\345\233\264\345\206\205/README.md" index f6a5ab6d737ed..bc6ddac8abb22 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 057. \345\200\274\345\222\214\344\270\213\346\240\207\344\271\213\345\267\256\351\203\275\345\234\250\347\273\231\345\256\232\347\232\204\350\214\203\345\233\264\345\206\205/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 057. \345\200\274\345\222\214\344\270\213\346\240\207\344\271\213\345\267\256\351\203\275\345\234\250\347\273\231\345\256\232\347\232\204\350\214\203\345\233\264\345\206\205/README.md" @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:滑动窗口 + 有序集合** +### 方法一:滑动窗口 + 有序集合 维护一个大小为 $k$ 的滑动窗口,窗口中的元素保持有序。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python from sortedcontainers import SortedSet @@ -78,10 +72,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { n := len(nums) @@ -145,8 +131,6 @@ func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { } ``` -### **TypeScript** - ```ts function containsNearbyAlmostDuplicate(nums: number[], k: number, t: number): boolean { const ts = new TreeSet(); @@ -804,10 +788,6 @@ class TreeMultiSet { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 058. \346\227\245\347\250\213\350\241\250/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 058. \346\227\245\347\250\213\350\241\250/README.md" index d3819e834eb0a..5c98dbc051fa1 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 058. \346\227\245\347\250\213\350\241\250/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 058. \346\227\245\347\250\213\350\241\250/README.md" @@ -47,14 +47,10 @@ MyCalendar.book(20, 30); // returns true ,第三个日程安排可以添加到 ## 解法 - +### 方法一 -### **Python3** - - - ```python from sortedcontainers import SortedDict @@ -77,10 +73,6 @@ class MyCalendar: # param_1 = obj.book(start,end) ``` -### **Java** - - - ```java import java.util.Map; import java.util.TreeMap; @@ -112,8 +104,6 @@ class MyCalendar { */ ``` -### **Go** - ```go type MyCalendar struct { rbt *redblacktree.Tree @@ -143,10 +133,6 @@ func (this *MyCalendar) Book(start int, end int) bool { */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 059. \346\225\260\346\215\256\346\265\201\347\232\204\347\254\254 K \345\244\247\346\225\260\345\200\274/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 059. \346\225\260\346\215\256\346\265\201\347\232\204\347\254\254 K \345\244\247\346\225\260\345\200\274/README.md" index 1ebfa76a93752..ced78dcd0c881 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 059. \346\225\260\346\215\256\346\265\201\347\232\204\347\254\254 K \345\244\247\346\225\260\345\200\274/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 059. \346\225\260\346\215\256\346\265\201\347\232\204\347\254\254 K \345\244\247\346\225\260\345\200\274/README.md" @@ -52,16 +52,10 @@ kthLargest.add(4); // return 8 ## 解法 - - -小根堆存放最大的 k 个元素,那么堆顶就是第 k 大的元素。 +### 方法一 -### **Python3** - - - ```python class KthLargest: def __init__(self, k: int, nums: List[int]): @@ -82,10 +76,6 @@ class KthLargest: # param_1 = obj.add(val) ``` -### **Java** - - - ```java class KthLargest { private PriorityQueue q; @@ -115,8 +105,6 @@ class KthLargest { */ ``` -### **C++** - ```cpp class KthLargest { public: @@ -142,8 +130,6 @@ public: */ ``` -### **Go** - ```go type KthLargest struct { h *IntHeap @@ -220,10 +206,6 @@ func (h *IntHeap) Top() int { */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/README.md" index 35ca1f394d03e..e1b248c5f6703 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 060. \345\207\272\347\216\260\351\242\221\347\216\207\346\234\200\351\253\230\347\232\204 k \344\270\252\346\225\260\345\255\227/README.md" @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:哈希表 + 优先队列(小根堆)** +### 方法一:哈希表 + 优先队列(小根堆) 使用哈希表统计每个元素出现的次数,然后使用优先队列(小根堆)维护前 $k$ 个出现次数最多的元素。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: @@ -62,22 +56,6 @@ class Solution: return [v[0] for v in cnt.most_common(k)] ``` -```python -class Solution: - def topKFrequent(self, nums: List[int], k: int) -> List[int]: - cnt = Counter(nums) - hp = [] - for num, freq in cnt.items(): - heappush(hp, (freq, num)) - if len(hp) > k: - heappop(hp) - return [v[1] for v in hp] -``` - -### **Java** - - - ```java class Solution { public int[] topKFrequent(int[] nums, int k) { @@ -95,72 +73,6 @@ class Solution { } ``` -```java -class Solution { - public int[] topKFrequent(int[] nums, int k) { - Map cnt = new HashMap<>(); - for (int v : nums) { - cnt.put(v, cnt.getOrDefault(v, 0) + 1); - } - PriorityQueue pq = new PriorityQueue<>((a, b) -> a[1] - b[1]); - for (var e : cnt.entrySet()) { - pq.offer(new int[] {e.getKey(), e.getValue()}); - if (pq.size() > k) { - pq.poll(); - } - } - int[] ans = new int[k]; - for (int i = 0; i < k; ++i) { - ans[i] = pq.poll()[0]; - } - return ans; - } -} -``` - -### **TypeScript** - -```ts -function topKFrequent(nums: number[], k: number): number[] { - let hashMap = new Map(); - for (let num of nums) { - hashMap.set(num, (hashMap.get(num) || 0) + 1); - } - let list = [...hashMap]; - list.sort((a, b) => b[1] - a[1]); - let ans = []; - for (let i = 0; i < k; i++) { - ans.push(list[i][0]); - } - return ans; -} -``` - -```ts -function topKFrequent(nums: number[], k: number): number[] { - const map = new Map(); - let maxCount = 0; - for (const num of nums) { - map.set(num, (map.get(num) ?? 0) + 1); - maxCount = Math.max(maxCount, map.get(num)); - } - - const res = []; - while (k > 0) { - for (const key of map.keys()) { - if (map.get(key) === maxCount) { - res.push(key); - k--; - } - } - maxCount--; - } - return res; -} -``` - -### **C++** - ```cpp using pii = pair; @@ -186,8 +98,6 @@ public: }; ``` -### **Go** - ```go func topKFrequent(nums []int, k int) []int { cnt := map[int]int{} @@ -218,7 +128,21 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **Rust** +```ts +function topKFrequent(nums: number[], k: number): number[] { + let hashMap = new Map(); + for (let num of nums) { + hashMap.set(num, (hashMap.get(num) || 0) + 1); + } + let list = [...hashMap]; + list.sort((a, b) => b[1] - a[1]); + let ans = []; + for (let i = 0; i < k; i++) { + ans.push(list[i][0]); + } + return ans; +} +``` ```rust use std::collections::HashMap; @@ -251,10 +175,70 @@ impl Solution { } ``` -### **...** + +### 方法二 + + + +```python +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + cnt = Counter(nums) + hp = [] + for num, freq in cnt.items(): + heappush(hp, (freq, num)) + if len(hp) > k: + heappop(hp) + return [v[1] for v in hp] +``` + +```java +class Solution { + public int[] topKFrequent(int[] nums, int k) { + Map cnt = new HashMap<>(); + for (int v : nums) { + cnt.put(v, cnt.getOrDefault(v, 0) + 1); + } + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[1] - b[1]); + for (var e : cnt.entrySet()) { + pq.offer(new int[] {e.getKey(), e.getValue()}); + if (pq.size() > k) { + pq.poll(); + } + } + int[] ans = new int[k]; + for (int i = 0; i < k; ++i) { + ans[i] = pq.poll()[0]; + } + return ans; + } +} ``` +```ts +function topKFrequent(nums: number[], k: number): number[] { + const map = new Map(); + let maxCount = 0; + for (const num of nums) { + map.set(num, (map.get(num) ?? 0) + 1); + maxCount = Math.max(maxCount, map.get(num)); + } + + const res = []; + while (k > 0) { + for (const key of map.keys()) { + if (map.get(key) === maxCount) { + res.push(key); + k--; + } + } + maxCount--; + } + return res; +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 061. \345\222\214\346\234\200\345\260\217\347\232\204 k \344\270\252\346\225\260\345\257\271/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 061. \345\222\214\346\234\200\345\260\217\347\232\204 k \344\270\252\346\225\260\345\257\271/README.md" index fafb7cef6c917..d1e86b5b4b4fc 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 061. \345\222\214\346\234\200\345\260\217\347\232\204 k \344\270\252\346\225\260\345\257\271/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 061. \345\222\214\346\234\200\345\260\217\347\232\204 k \344\270\252\346\225\260\345\257\271/README.md" @@ -55,16 +55,10 @@ ## 解法 - - -大顶堆 +### 方法一 -### **Python3** - - - ```python class Solution: def kSmallestPairs( @@ -79,10 +73,6 @@ class Solution: return [p for _, p in hp] ``` -### **Java** - - - ```java class Solution { public List> kSmallestPairs(int[] nums1, int[] nums2, int k) { @@ -101,33 +91,6 @@ class Solution { } ``` -### **Go** - -```go -type pairHeap [][]int - -func (a pairHeap) Len() int { return len(a) } -func (a pairHeap) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a pairHeap) Less(i, j int) bool { return a[i][0]+a[i][1] > a[j][0]+a[j][1] } -func (a *pairHeap) Push(x any) { *a = append(*a, x.([]int)) } -func (a *pairHeap) Pop() any { l := len(*a); tmp := (*a)[l-1]; *a = (*a)[:l-1]; return tmp } - -func kSmallestPairs(nums1 []int, nums2 []int, k int) [][]int { - var hp pairHeap - for _, x := range nums1[:min(k, len(nums1))] { - for _, y := range nums2[:min(k, len(nums2))] { - heap.Push(&hp, []int{x, y}) - if len(hp) > k { - heap.Pop(&hp) - } - } - } - return hp -} -``` - -### **C++** - ```cpp class Solution { public: @@ -152,10 +115,29 @@ public: }; ``` -### **...** +```go +type pairHeap [][]int -``` +func (a pairHeap) Len() int { return len(a) } +func (a pairHeap) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a pairHeap) Less(i, j int) bool { return a[i][0]+a[i][1] > a[j][0]+a[j][1] } +func (a *pairHeap) Push(x any) { *a = append(*a, x.([]int)) } +func (a *pairHeap) Pop() any { l := len(*a); tmp := (*a)[l-1]; *a = (*a)[:l-1]; return tmp } +func kSmallestPairs(nums1 []int, nums2 []int, k int) [][]int { + var hp pairHeap + for _, x := range nums1[:min(k, len(nums1))] { + for _, y := range nums2[:min(k, len(nums2))] { + heap.Push(&hp, []int{x, y}) + if len(hp) > k { + heap.Pop(&hp) + } + } + } + return hp +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 062. \345\256\236\347\216\260\345\211\215\347\274\200\346\240\221/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 062. \345\256\236\347\216\260\345\211\215\347\274\200\346\240\221/README.md" index 8d8c27e9a8c51..79ba572b86ce2 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 062. \345\256\236\347\216\260\345\211\215\347\274\200\346\240\221/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 062. \345\256\236\347\216\260\345\211\215\347\274\200\346\240\221/README.md" @@ -54,9 +54,7 @@ trie.search("app"); // 返回 True ## 解法 - - -**方法一:前缀树** +### 方法一:前缀树 前缀树每个节点包括两部分: @@ -85,10 +83,6 @@ trie.search("app"); // 返回 True -### **Python3** - - - ```python class Trie: def __init__(self): @@ -129,10 +123,6 @@ class Trie: # param_3 = obj.startsWith(prefix) ``` -### **Java** - - - ```java class Trie { private Trie[] children; @@ -186,71 +176,6 @@ class Trie { */ ``` -### **JavaScript** - -```js -/** - * Initialize your data structure here. - */ -var Trie = function () { - this.children = {}; -}; - -/** - * Inserts a word into the trie. - * @param {string} word - * @return {void} - */ -Trie.prototype.insert = function (word) { - let node = this.children; - for (let char of word) { - if (!node[char]) { - node[char] = {}; - } - node = node[char]; - } - node.isEnd = true; -}; - -/** - * Returns if the word is in the trie. - * @param {string} word - * @return {boolean} - */ -Trie.prototype.search = function (word) { - let node = this.searchPrefix(word); - return node != undefined && node.isEnd != undefined; -}; - -Trie.prototype.searchPrefix = function (prefix) { - let node = this.children; - for (let char of prefix) { - if (!node[char]) return false; - node = node[char]; - } - return node; -}; - -/** - * Returns if there is any word in the trie that starts with the given prefix. - * @param {string} prefix - * @return {boolean} - */ -Trie.prototype.startsWith = function (prefix) { - return this.searchPrefix(prefix); -}; - -/** - * Your Trie object will be instantiated and called as such: - * var obj = new Trie() - * obj.insert(word) - * var param_2 = obj.search(word) - * var param_3 = obj.startsWith(prefix) - */ -``` - -### **C++** - ```cpp class Trie { private: @@ -302,8 +227,6 @@ public: */ ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -357,7 +280,66 @@ func (this *Trie) SearchPrefix(s string) *Trie { */ ``` -### **C#** +```js +/** + * Initialize your data structure here. + */ +var Trie = function () { + this.children = {}; +}; + +/** + * Inserts a word into the trie. + * @param {string} word + * @return {void} + */ +Trie.prototype.insert = function (word) { + let node = this.children; + for (let char of word) { + if (!node[char]) { + node[char] = {}; + } + node = node[char]; + } + node.isEnd = true; +}; + +/** + * Returns if the word is in the trie. + * @param {string} word + * @return {boolean} + */ +Trie.prototype.search = function (word) { + let node = this.searchPrefix(word); + return node != undefined && node.isEnd != undefined; +}; + +Trie.prototype.searchPrefix = function (prefix) { + let node = this.children; + for (let char of prefix) { + if (!node[char]) return false; + node = node[char]; + } + return node; +}; + +/** + * Returns if there is any word in the trie that starts with the given prefix. + * @param {string} prefix + * @return {boolean} + */ +Trie.prototype.startsWith = function (prefix) { + return this.searchPrefix(prefix); +}; + +/** + * Your Trie object will be instantiated and called as such: + * var obj = new Trie() + * obj.insert(word) + * var param_2 = obj.search(word) + * var param_3 = obj.startsWith(prefix) + */ +``` ```cs public class Trie { @@ -413,10 +395,6 @@ public class Trie { */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/README.md" index d88ba3be93a17..6abb3e069d736 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 063. \346\233\277\346\215\242\345\215\225\350\257\215/README.md" @@ -69,18 +69,10 @@ ## 解法 - - -**方法一:哈希表** - -**方法二:前缀树** +### 方法一:哈希表 -### **Python3** - - - ```python class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: @@ -94,6 +86,79 @@ class Solution: return ' '.join(words) ``` +```java +class Solution { + public String replaceWords(List dictionary, String sentence) { + Set s = new HashSet<>(dictionary); + String[] words = sentence.split(" "); + for (int i = 0; i < words.length; ++i) { + String word = words[i]; + for (int j = 1; j <= word.length(); ++j) { + String t = word.substring(0, j); + if (s.contains(t)) { + words[i] = t; + break; + } + } + } + return String.join(" ", words); + } +} +``` + +```cpp +class Solution { +public: + string replaceWords(vector& dictionary, string sentence) { + unordered_set s(dictionary.begin(), dictionary.end()); + istringstream is(sentence); + vector words; + string ss; + while (is >> ss) words.push_back(ss); + for (int i = 0; i < words.size(); ++i) { + string word = words[i]; + for (int j = 1; j <= word.size(); ++j) { + string t = word.substr(0, j); + if (s.count(t)) { + words[i] = t; + break; + } + } + } + string ans = ""; + for (string& word : words) ans += word + " "; + ans.pop_back(); + return ans; + } +}; +``` + +```go +func replaceWords(dictionary []string, sentence string) string { + s := map[string]bool{} + for _, v := range dictionary { + s[v] = true + } + words := strings.Split(sentence, " ") + for i, word := range words { + for j := 1; j <= len(word); j++ { + t := word[:j] + if s[t] { + words[i] = t + break + } + } + } + return strings.Join(words, " ") +} +``` + + + +### 方法二:前缀树 + + + ```python class Trie: def __init__(self): @@ -129,30 +194,6 @@ class Solution: return ' '.join(trie.search(v) for v in sentence.split()) ``` -### **Java** - - - -```java -class Solution { - public String replaceWords(List dictionary, String sentence) { - Set s = new HashSet<>(dictionary); - String[] words = sentence.split(" "); - for (int i = 0; i < words.length; ++i) { - String word = words[i]; - for (int j = 1; j <= word.length(); ++j) { - String t = word.substring(0, j); - if (s.contains(t)) { - words[i] = t; - break; - } - } - } - return String.join(" ", words); - } -} -``` - ```java class Trie { Trie[] children = new Trie[26]; @@ -201,35 +242,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string replaceWords(vector& dictionary, string sentence) { - unordered_set s(dictionary.begin(), dictionary.end()); - istringstream is(sentence); - vector words; - string ss; - while (is >> ss) words.push_back(ss); - for (int i = 0; i < words.size(); ++i) { - string word = words[i]; - for (int j = 1; j <= word.size(); ++j) { - string t = word.substr(0, j); - if (s.count(t)) { - words[i] = t; - break; - } - } - } - string ans = ""; - for (string& word : words) ans += word + " "; - ans.pop_back(); - return ans; - } -}; -``` - ```cpp class Trie { public: @@ -278,28 +290,6 @@ public: }; ``` -### **Go** - -```go -func replaceWords(dictionary []string, sentence string) string { - s := map[string]bool{} - for _, v := range dictionary { - s[v] = true - } - words := strings.Split(sentence, " ") - for i, word := range words { - for j := 1; j <= len(word); j++ { - t := word[:j] - if s[t] { - words[i] = t - break - } - } - } - return strings.Join(words, " ") -} -``` - ```go type Trie struct { children [26]*Trie @@ -349,10 +339,6 @@ func replaceWords(dictionary []string, sentence string) string { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 064. \347\245\236\345\245\207\347\232\204\345\255\227\345\205\270/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 064. \347\245\236\345\245\207\347\232\204\345\255\227\345\205\270/README.md" index 53697b4b0d731..5581523436842 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 064. \347\245\236\345\245\207\347\232\204\345\255\227\345\205\270/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 064. \347\245\236\345\245\207\347\232\204\345\255\227\345\205\270/README.md" @@ -61,16 +61,10 @@ magicDictionary.search("leetcoded"); // 返回 False ## 解法 - - -哈希表实现。 +### 方法一 -### **Python3** - - - ```python class MagicDictionary: def __init__(self): @@ -100,10 +94,6 @@ class MagicDictionary: # param_2 = obj.search(searchWord) ``` -### **Java** - - - ```java class MagicDictionary { private Set words; @@ -155,8 +145,6 @@ class MagicDictionary { */ ``` -### **C++** - ```cpp class MagicDictionary { public: @@ -202,8 +190,6 @@ private: */ ``` -### **Go** - ```go type MagicDictionary struct { words map[string]bool @@ -252,10 +238,6 @@ func patterns(word string) []string { */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/README.md" index fbcd9d791432a..4d648241f813c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 065. \346\234\200\347\237\255\347\232\204\345\215\225\350\257\215\347\274\226\347\240\201/README.md" @@ -51,9 +51,7 @@ words[2] = "bell" ,s 开始于 indices[2] = 5 到下一个 '# ## 解法 - - -**方法一:前缀树** +### 方法一:前缀树 题目大意:充分利用重叠的后缀,使有效编码尽可能短。 @@ -61,10 +59,6 @@ words[2] = "bell" ,s 开始于 indices[2] = 5 到下一个 '# -### **Python3** - - - ```python class Trie: def __init__(self) -> None: @@ -94,34 +88,6 @@ class Solution: return ans ``` -```python -class Trie: - def __init__(self): - self.children = [None] * 26 - - def insert(self, w): - node = self - pref = True - for c in w: - idx = ord(c) - ord("a") - if node.children[idx] is None: - node.children[idx] = Trie() - pref = False - node = node.children[idx] - return 0 if pref else len(w) + 1 - - -class Solution: - def minimumLengthEncoding(self, words: List[str]) -> int: - words.sort(key=lambda x: -len(x)) - trie = Trie() - return sum(trie.insert(w[::-1]) for w in words) -``` - -### **Java** - - - ```java class Trie { Trie[] children = new Trie[26]; @@ -160,40 +126,45 @@ class Solution { } ``` -```java -class Trie { - Trie[] children = new Trie[26]; +```cpp +struct Trie { + Trie* children[26] = {nullptr}; +}; - int insert(String w) { - Trie node = this; - boolean pref = true; - for (int i = w.length() - 1; i >= 0; --i) { - int idx = w.charAt(i) - 'a'; - if (node.children[idx] == null) { - pref = false; - node.children[idx] = new Trie(); +class Solution { +public: + int minimumLengthEncoding(vector& words) { + auto root = new Trie(); + for (auto& w : words) { + auto cur = root; + for (int i = w.size() - 1; i >= 0; --i) { + if (cur->children[w[i] - 'a'] == nullptr) { + cur->children[w[i] - 'a'] = new Trie(); + } + cur = cur->children[w[i] - 'a']; } - node = node.children[idx]; } - return pref ? 0 : w.length() + 1; + return dfs(root, 1); } -} -class Solution { - public int minimumLengthEncoding(String[] words) { - Arrays.sort(words, (a, b) -> b.length() - a.length()); +private: + int dfs(Trie* cur, int l) { + bool isLeaf = true; int ans = 0; - Trie trie = new Trie(); - for (String w : words) { - ans += trie.insert(w); + for (int i = 0; i < 26; ++i) { + if (cur->children[i] != nullptr) { + isLeaf = false; + ans += dfs(cur->children[i], l + 1); + } + } + if (isLeaf) { + ans += l; } return ans; } -} +}; ``` -### **Go** - ```go type trie struct { children [26]*trie @@ -228,82 +199,66 @@ func dfs(cur *trie, l int) int { } ``` -```go -type Trie struct { - children [26]*Trie -} + -func newTrie() *Trie { - return &Trie{} -} +### 方法二 -func (this *Trie) insert(w string) int { - node := this - pref := true - for i := len(w) - 1; i >= 0; i-- { - idx := w[i] - 'a' - if node.children[idx] == nil { - pref = false - node.children[idx] = newTrie() - } - node = node.children[idx] - } - if pref { - return 0 - } - return len(w) + 1 -} + -func minimumLengthEncoding(words []string) int { - sort.Slice(words, func(i, j int) bool { return len(words[i]) > len(words[j]) }) - trie := newTrie() - ans := 0 - for _, w := range words { - ans += trie.insert(w) - } - return ans -} -``` +```python +class Trie: + def __init__(self): + self.children = [None] * 26 -### **C++** + def insert(self, w): + node = self + pref = True + for c in w: + idx = ord(c) - ord("a") + if node.children[idx] is None: + node.children[idx] = Trie() + pref = False + node = node.children[idx] + return 0 if pref else len(w) + 1 -```cpp -struct Trie { - Trie* children[26] = {nullptr}; -}; -class Solution { -public: - int minimumLengthEncoding(vector& words) { - auto root = new Trie(); - for (auto& w : words) { - auto cur = root; - for (int i = w.size() - 1; i >= 0; --i) { - if (cur->children[w[i] - 'a'] == nullptr) { - cur->children[w[i] - 'a'] = new Trie(); - } - cur = cur->children[w[i] - 'a']; +class Solution: + def minimumLengthEncoding(self, words: List[str]) -> int: + words.sort(key=lambda x: -len(x)) + trie = Trie() + return sum(trie.insert(w[::-1]) for w in words) +``` + +```java +class Trie { + Trie[] children = new Trie[26]; + + int insert(String w) { + Trie node = this; + boolean pref = true; + for (int i = w.length() - 1; i >= 0; --i) { + int idx = w.charAt(i) - 'a'; + if (node.children[idx] == null) { + pref = false; + node.children[idx] = new Trie(); } + node = node.children[idx]; } - return dfs(root, 1); + return pref ? 0 : w.length() + 1; } +} -private: - int dfs(Trie* cur, int l) { - bool isLeaf = true; +class Solution { + public int minimumLengthEncoding(String[] words) { + Arrays.sort(words, (a, b) -> b.length() - a.length()); int ans = 0; - for (int i = 0; i < 26; ++i) { - if (cur->children[i] != nullptr) { - isLeaf = false; - ans += dfs(cur->children[i], l + 1); - } - } - if (isLeaf) { - ans += l; + Trie trie = new Trie(); + for (String w : words) { + ans += trie.insert(w); } return ans; } -}; +} ``` ```cpp @@ -343,10 +298,43 @@ public: }; ``` -### **...** +```go +type Trie struct { + children [26]*Trie +} -``` +func newTrie() *Trie { + return &Trie{} +} +func (this *Trie) insert(w string) int { + node := this + pref := true + for i := len(w) - 1; i >= 0; i-- { + idx := w[i] - 'a' + if node.children[idx] == nil { + pref = false + node.children[idx] = newTrie() + } + node = node.children[idx] + } + if pref { + return 0 + } + return len(w) + 1 +} + +func minimumLengthEncoding(words []string) int { + sort.Slice(words, func(i, j int) bool { return len(words[i]) > len(words[j]) }) + trie := newTrie() + ans := 0 + for _, w := range words { + ans += trie.insert(w) + } + return ans +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 066. \345\215\225\350\257\215\344\271\213\345\222\214/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 066. \345\215\225\350\257\215\344\271\213\345\222\214/README.md" index 5e31d3b26455a..ec4b19a61ef9b 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 066. \345\215\225\350\257\215\344\271\213\345\222\214/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 066. \345\215\225\350\257\215\344\271\213\345\222\214/README.md" @@ -48,16 +48,10 @@ mapSum.sum("ap"); // return 5 (apple + app = 3 ## 解法 - - -利用哈希表存储每个键的所有前缀子串。 +### 方法一 -### **Python3** - - - ```python class MapSum: def __init__(self): @@ -83,10 +77,6 @@ class MapSum: # param_2 = obj.sum(prefix) ``` -### **Java** - - - ```java class MapSum { private Map data; @@ -120,8 +110,6 @@ class MapSum { */ ``` -### **C++** - ```cpp class MapSum { public: @@ -154,8 +142,6 @@ public: */ ``` -### **Go** - ```go type MapSum struct { data map[string]int @@ -191,10 +177,6 @@ func (this *MapSum) Sum(prefix string) int { */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/README.md" index 406f102ce1d79..bf9b71cf2d44f 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 067. \346\234\200\345\244\247\347\232\204\345\274\202\346\210\226/README.md" @@ -66,24 +66,10 @@ ## 解法 - - -**方法一:哈希表** - -**方法二:前缀树** - -题目是求两个元素的异或最大值,可以从最高位开始考虑。 - -我们把数组中的每个元素 $x$ 看作一个 $32$ 位的 $01$ 串,按二进制从高位到低位的顺序,插入前缀树(最低位为叶子节点)。 - -搜索 $x$ 时,尽量走相反的 $01$ 字符指针的策略,因为异或运算的法则是相同得 $0$,不同得 $1$,所以我们尽可能往与 $x$ 当前位相反的字符方向走,才能得到能和 $x$ 产生最大值的结果。 +### 方法一:哈希表 -### **Python3** - - - ```python class Solution: def findMaximumXOR(self, nums: List[int]) -> int: @@ -106,45 +92,6 @@ class Solution: return max ``` -```python -class Trie: - def __init__(self): - self.children = [None] * 2 - - def insert(self, x): - node = self - for i in range(30, -1, -1): - v = (x >> i) & 1 - if node.children[v] is None: - node.children[v] = Trie() - node = node.children[v] - - def search(self, x): - node = self - res = 0 - for i in range(30, -1, -1): - v = (x >> i) & 1 - if node.children[v ^ 1]: - res = res << 1 | 1 - node = node.children[v ^ 1] - else: - res <<= 1 - node = node.children[v] - return res - - -class Solution: - def findMaximumXOR(self, nums: List[int]) -> int: - trie = Trie() - for v in nums: - trie.insert(v) - return max(trie.search(v) for v in nums) -``` - -### **Java** - - - ```java class Solution { @@ -174,55 +121,6 @@ class Solution { } ``` -前缀树: - -```java -class Trie { - Trie[] children = new Trie[2]; - - void insert(int x) { - Trie node = this; - for (int i = 30; i >= 0; --i) { - int v = (x >> i) & 1; - if (node.children[v] == null) { - node.children[v] = new Trie(); - } - node = node.children[v]; - } - } - - int search(int x) { - Trie node = this; - int res = 0; - for (int i = 30; i >= 0; --i) { - int v = (x >> i) & 1; - if (node.children[v ^ 1] != null) { - res = res << 1 | 1; - node = node.children[v ^ 1]; - } else { - res <<= 1; - node = node.children[v]; - } - } - return res; - } -} - -class Solution { - public int findMaximumXOR(int[] nums) { - Trie trie = new Trie(); - int ans = 0; - for (int v : nums) { - trie.insert(v); - ans = Math.max(ans, trie.search(v)); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Trie { public: @@ -271,8 +169,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -320,10 +216,98 @@ func findMaximumXOR(nums []int) int { } ``` -### **...** + + +### 方法二:前缀树 + +题目是求两个元素的异或最大值,可以从最高位开始考虑。 + +我们把数组中的每个元素 $x$ 看作一个 $32$ 位的 $01$ 串,按二进制从高位到低位的顺序,插入前缀树(最低位为叶子节点)。 + +搜索 $x$ 时,尽量走相反的 $01$ 字符指针的策略,因为异或运算的法则是相同得 $0$,不同得 $1$,所以我们尽可能往与 $x$ 当前位相反的字符方向走,才能得到能和 $x$ 产生最大值的结果。 + + + +```python +class Trie: + def __init__(self): + self.children = [None] * 2 + + def insert(self, x): + node = self + for i in range(30, -1, -1): + v = (x >> i) & 1 + if node.children[v] is None: + node.children[v] = Trie() + node = node.children[v] + + def search(self, x): + node = self + res = 0 + for i in range(30, -1, -1): + v = (x >> i) & 1 + if node.children[v ^ 1]: + res = res << 1 | 1 + node = node.children[v ^ 1] + else: + res <<= 1 + node = node.children[v] + return res + +class Solution: + def findMaximumXOR(self, nums: List[int]) -> int: + trie = Trie() + for v in nums: + trie.insert(v) + return max(trie.search(v) for v in nums) ``` +```java +class Trie { + Trie[] children = new Trie[2]; + + void insert(int x) { + Trie node = this; + for (int i = 30; i >= 0; --i) { + int v = (x >> i) & 1; + if (node.children[v] == null) { + node.children[v] = new Trie(); + } + node = node.children[v]; + } + } + + int search(int x) { + Trie node = this; + int res = 0; + for (int i = 30; i >= 0; --i) { + int v = (x >> i) & 1; + if (node.children[v ^ 1] != null) { + res = res << 1 | 1; + node = node.children[v ^ 1]; + } else { + res <<= 1; + node = node.children[v]; + } + } + return res; + } +} + +class Solution { + public int findMaximumXOR(int[] nums) { + Trie trie = new Trie(); + int ans = 0; + for (int v : nums) { + trie.insert(v); + ans = Math.max(ans, trie.search(v)); + } + return ans; + } +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 068. \346\237\245\346\211\276\346\217\222\345\205\245\344\275\215\347\275\256/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 068. \346\237\245\346\211\276\346\217\222\345\205\245\344\275\215\347\275\256/README.md" index 0bfd09ae0073f..7f1d25349ff58 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 068. \346\237\245\346\211\276\346\217\222\345\205\245\344\275\215\347\275\256/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 068. \346\237\245\346\211\276\346\217\222\345\205\245\344\275\215\347\275\256/README.md" @@ -62,16 +62,10 @@ ## 解法 - - -二分查找。 +### 方法一 -### **Python3** - - - ```python class Solution: def searchInsert(self, nums: List[int], target: int) -> int: @@ -85,10 +79,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int searchInsert(int[] nums, int target) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func searchInsert(nums []int, target int) int { left, right := 0, len(nums) @@ -142,8 +128,6 @@ func searchInsert(nums []int, target int) int { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -165,10 +149,6 @@ var searchInsert = function (nums, target) { }; ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 069. \345\261\261\345\263\260\346\225\260\347\273\204\347\232\204\351\241\266\351\203\250/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 069. \345\261\261\345\263\260\346\225\260\347\273\204\347\232\204\351\241\266\351\203\250/README.md" index 092cce57b22a3..a40da277d7058 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 069. \345\261\261\345\263\260\346\225\260\347\273\204\347\232\204\351\241\266\351\203\250/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 069. \345\261\261\345\263\260\346\225\260\347\273\204\347\232\204\351\241\266\351\203\250/README.md" @@ -75,16 +75,10 @@ ## 解法 - - -二分查找。 +### 方法一 -### **Python3** - - - ```python class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: @@ -98,10 +92,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int peakIndexInMountainArray(int[] arr) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func peakIndexInMountainArray(arr []int) int { left, right := 1, len(arr)-2 @@ -155,8 +141,6 @@ func peakIndexInMountainArray(arr []int) int { } ``` -### **JavaScript** - ```js /** * @param {number[]} arr @@ -177,10 +161,6 @@ var peakIndexInMountainArray = function (arr) { }; ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 070. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 070. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/README.md" index de0564b80df33..38a427711daf6 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 070. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 070. \346\216\222\345\272\217\346\225\260\347\273\204\344\270\255\345\217\252\345\207\272\347\216\260\344\270\200\346\254\241\347\232\204\346\225\260\345\255\227/README.md" @@ -45,16 +45,10 @@ ## 解法 - - -二分查找。 +### 方法一 -### **Python3** - - - ```python class Solution: def singleNonDuplicate(self, nums: List[int]) -> int: @@ -69,10 +63,6 @@ class Solution: return nums[left] ``` -### **Java** - - - ```java class Solution { public int singleNonDuplicate(int[] nums) { @@ -92,26 +82,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function singleNonDuplicate(nums: number[]): number { - let left = 0, - right = nums.length - 1; - while (left < right) { - const mid = (left + right) >> 1; - if (nums[mid] != nums[mid ^ 1]) { - right = mid; - } else { - left = mid + 1; - } - } - return nums[left]; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -129,8 +99,6 @@ public: }; ``` -### **Go** - ```go func singleNonDuplicate(nums []int) int { left, right := 0, len(nums)-1 @@ -146,10 +114,22 @@ func singleNonDuplicate(nums []int) int { } ``` -### **...** - -``` - +```ts +function singleNonDuplicate(nums: number[]): number { + let left = 0, + right = nums.length - 1; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] != nums[mid ^ 1]) { + right = mid; + } else { + left = mid + 1; + } + } + return nums[left]; +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 071. \346\214\211\346\235\203\351\207\215\347\224\237\346\210\220\351\232\217\346\234\272\346\225\260/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 071. \346\214\211\346\235\203\351\207\215\347\224\237\346\210\220\351\232\217\346\234\272\346\225\260/README.md" index 0711f0723ab02..1fd0373c0403c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 071. \346\214\211\346\235\203\351\207\215\347\224\237\346\210\220\351\232\217\346\234\272\346\225\260/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 071. \346\214\211\346\235\203\351\207\215\347\224\237\346\210\220\351\232\217\346\234\272\346\225\260/README.md" @@ -69,16 +69,10 @@ solution.pickIndex(); // 返回 0,返回下标 0,返回该下标概率为 1/ ## 解法 - - -“前缀和 + 二分查找”。 +### 方法一 -### **Python3** - - - ```python class Solution: def __init__(self, w: List[int]): @@ -105,10 +99,6 @@ class Solution: # param_1 = obj.pickIndex() ``` -### **Java** - - - ```java class Solution { private int[] presum; @@ -144,8 +134,6 @@ class Solution { */ ``` -### **C++** - ```cpp class Solution { public: @@ -179,8 +167,6 @@ public: */ ``` -### **Go** - ```go type Solution struct { presum []int @@ -217,10 +203,6 @@ func (this *Solution) PickIndex() int { */ ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/README.md" index 7c998384a8faf..390be46101b99 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 072. \346\261\202\345\271\263\346\226\271\346\240\271/README.md" @@ -28,16 +28,10 @@ ## 解法 - - -二分查找。 +### 方法一 -### **Python3** - - - ```python class Solution: def mySqrt(self, x: int) -> int: @@ -52,10 +46,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int mySqrt(int x) { @@ -74,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +81,6 @@ public: }; ``` -### **Go** - ```go func mySqrt(x int) int { left, right := 0, x @@ -110,8 +96,6 @@ func mySqrt(x int) int { } ``` -### **JavaScript** - ```js /** * @param {number} x @@ -132,8 +116,6 @@ var mySqrt = function (x) { }; ``` -### **C#** - ```cs public class Solution { public int MySqrt(int x) { @@ -155,10 +137,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 073. \347\213\222\347\213\222\345\220\203\351\246\231\350\225\211/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 073. \347\213\222\347\213\222\345\220\203\351\246\231\350\225\211/README.md" index c643865cab289..ebad831e5f790 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 073. \347\213\222\347\213\222\345\220\203\351\246\231\350\225\211/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 073. \347\213\222\347\213\222\345\220\203\351\246\231\350\225\211/README.md" @@ -54,16 +54,10 @@ ## 解法 - - -二分查找。 +### 方法一 -### **Python3** - - - ```python class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: @@ -78,10 +72,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int minEatingSpeed(int[] piles, int h) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func minEatingSpeed(piles []int, h int) int { left, right := 1, slices.Max(piles) @@ -149,8 +135,6 @@ func minEatingSpeed(piles []int, h int) int { } ``` -### **C#** - ```cs public class Solution { public int MinEatingSpeed(int[] piles, int h) { @@ -177,10 +161,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 074. \345\220\210\345\271\266\345\214\272\351\227\264/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 074. \345\220\210\345\271\266\345\214\272\351\227\264/README.md" index 4969594115fe9..96dbf5950d9b2 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 074. \345\220\210\345\271\266\345\214\272\351\227\264/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 074. \345\220\210\345\271\266\345\214\272\351\227\264/README.md" @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:区间合并** +### 方法一:区间合并 区间合并,将所有存在交集的区间进行合并。方法是:先对区间**按照左端点升序排列**,然后遍历区间进行合并。 @@ -64,10 +62,6 @@ def merge(intervals): -### **Python3** - - - ```python class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] merge(int[][] intervals) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +121,6 @@ public: }; ``` -### **Go** - ```go func merge(intervals [][]int) [][]int { sort.Slice(intervals, func(i, j int) bool { @@ -155,8 +141,6 @@ func merge(intervals [][]int) [][]int { } ``` -### **C#** - ```cs public class Solution { public int[][] Merge(int[][] intervals) { @@ -183,10 +167,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 075. \346\225\260\347\273\204\347\233\270\345\257\271\346\216\222\345\272\217/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 075. \346\225\260\347\273\204\347\233\270\345\257\271\346\216\222\345\272\217/README.md" index 1236774e4c114..fc5726fe96254 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 075. \346\225\260\347\273\204\347\233\270\345\257\271\346\216\222\345\272\217/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 075. \346\225\260\347\273\204\347\233\270\345\257\271\346\216\222\345\272\217/README.md" @@ -39,20 +39,10 @@ ## 解法 - - -由于本题数据范围是 `[0, 1000]`,因此我们可以开辟一个长度为 1001 的数组 mp,记录 arr1 的元素以及出现的次数。 - -接着,遍历 arr2 中每个元素 x,若 `mp[x]` 大于 0,循环将 x 加入到答案数组 arr1 中,并且递减 `mp[x]`。遍历结束后,再从下标 `j = 0` 开始遍历 mp,若遇到 `mp[j]` 大于 0,将 `mp[j]` 个 j 加入到答案数组 arr1 中。 - -最后返回 arr1 即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: @@ -61,29 +51,6 @@ class Solution: return arr1 ``` -```python -class Solution: - def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: - mp = [0] * 1001 - for x in arr1: - mp[x] += 1 - i = 0 - for x in arr2: - while mp[x] > 0: - arr1[i] = x - mp[x] -= 1 - i += 1 - for x, cnt in enumerate(mp): - for _ in range(cnt): - arr1[i] = x - i += 1 - return arr1 -``` - -### **Java** - - - ```java class Solution { public int[] relativeSortArray(int[] arr1, int[] arr2) { @@ -107,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +92,6 @@ public: }; ``` -### **Go** - ```go func relativeSortArray(arr1 []int, arr2 []int) []int { mp := make([]int, 1001) @@ -154,10 +117,31 @@ func relativeSortArray(arr1 []int, arr2 []int) []int { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: + mp = [0] * 1001 + for x in arr1: + mp[x] += 1 + i = 0 + for x in arr2: + while mp[x] > 0: + arr1[i] = x + mp[x] -= 1 + i += 1 + for x, cnt in enumerate(mp): + for _ in range(cnt): + arr1[i] = x + i += 1 + return arr1 ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 076. \346\225\260\347\273\204\344\270\255\347\232\204\347\254\254 k \345\244\247\347\232\204\346\225\260\345\255\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 076. \346\225\260\347\273\204\344\270\255\347\232\204\347\254\254 k \345\244\247\347\232\204\346\225\260\345\255\227/README.md" index a02ab4a98f725..3eed2f7d2ed1e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 076. \346\225\260\347\273\204\344\270\255\347\232\204\347\254\254 k \345\244\247\347\232\204\346\225\260\345\255\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 076. \346\225\260\347\273\204\344\270\255\347\232\204\347\254\254 k \345\244\247\347\232\204\346\225\260\345\255\227/README.md" @@ -38,16 +38,10 @@ ## 解法 - - -快速排序 partition 实现。 +### 方法一 -### **Python3** - - - ```python class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: @@ -75,10 +69,6 @@ class Solution: return quick_sort(0, n - 1, n - k) ``` -### **Java** - - - ```java class Solution { public int findKthLargest(int[] nums, int k) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func findKthLargest(nums []int, k int) int { n := len(nums) @@ -175,10 +161,6 @@ func quickSort(nums []int, left, right, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 077. \351\223\276\350\241\250\346\216\222\345\272\217/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 077. \351\223\276\350\241\250\346\216\222\345\272\217/README.md" index 2a4ca936ac360..5008f97113984 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 077. \351\223\276\350\241\250\346\216\222\345\272\217/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 077. \351\223\276\350\241\250\346\216\222\345\272\217/README.md" @@ -55,16 +55,10 @@ ## 解法 - - -先用快慢指针找到链表中点,然后分成左右两个链表,递归排序左右链表。最后合并两个排序的链表即可。 +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -95,10 +89,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -142,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -187,8 +175,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -229,7 +215,49 @@ func sortList(head *ListNode) *ListNode { } ``` -### **JavaScript** +```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 sortList(head: ListNode | null): ListNode | null { + if (head == null || head.next == null) return head; + // 快慢指针定位中点 + let slow: ListNode = head, + fast: ListNode = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + // 归并排序 + let mid: ListNode = slow.next; + slow.next = null; + let l1: ListNode = sortList(head); + let l2: ListNode = sortList(mid); + let dummy: ListNode = new ListNode(); + let cur: ListNode = dummy; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; +} +``` ```js /** @@ -274,8 +302,6 @@ var sortList = function (head) { }; ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -326,56 +352,6 @@ 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 sortList(head: ListNode | null): ListNode | null { - if (head == null || head.next == null) return head; - // 快慢指针定位中点 - let slow: ListNode = head, - fast: ListNode = head.next; - while (fast != null && fast.next != null) { - slow = slow.next; - fast = fast.next.next; - } - // 归并排序 - let mid: ListNode = slow.next; - slow.next = null; - let l1: ListNode = sortList(head); - let l2: ListNode = sortList(mid); - let dummy: ListNode = new ListNode(); - let cur: ListNode = dummy; - while (l1 != null && l2 != null) { - if (l1.val <= l2.val) { - cur.next = l1; - l1 = l1.next; - } else { - cur.next = l2; - l2 = l2.next; - } - cur = cur.next; - } - cur.next = l1 == null ? l2 : l1; - return dummy.next; -} -``` - -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/README.md" index b51b15ed2524a..45b7593438652 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 078. \345\220\210\345\271\266\346\216\222\345\272\217\351\223\276\350\241\250/README.md" @@ -58,16 +58,10 @@ ## 解法 - - -合并前后两个链表,结果放在后一个链表位置上,依次循环下去。最后返回链表数组的最后一个元素。 +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -98,10 +92,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -186,8 +174,6 @@ private: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -229,8 +215,6 @@ func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { } ``` -### **JavaScript** - ```js /** * Definition for singly-linked list. @@ -272,49 +256,6 @@ function mergeTwoLists(l1, l2) { } ``` -### **Ruby** - -```rb -# Definition for singly-linked list. -# class ListNode -# attr_accessor :val, :next -# def initialize(val = 0, _next = nil) -# @val = val -# @next = _next -# end -# end -# @param {ListNode[]} lists -# @return {ListNode} -def merge_k_lists(lists) - n = lists.length - i = 1 - while i < n - lists[i] = merge_two_lists(lists[i - 1], lists[i]) - i += 1 - end - lists[n - 1] -end - -def merge_two_lists(l1, l2) - dummy = ListNode.new() - cur = dummy - while l1 && l2 - if l1.val <= l2.val - cur.next = l1 - l1 = l1.next - else - cur.next = l2 - l2 = l2.next - end - cur = cur.next - end - cur.next = l1 || l2 - dummy.next -end -``` - -### **C#** - ```cs /** * Definition for singly-linked list. @@ -358,10 +299,45 @@ public class Solution { } ``` -### **...** - -``` +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode[]} lists +# @return {ListNode} +def merge_k_lists(lists) + n = lists.length + i = 1 + while i < n + lists[i] = merge_two_lists(lists[i - 1], lists[i]) + i += 1 + end + lists[n - 1] +end +def merge_two_lists(l1, l2) + dummy = ListNode.new() + cur = dummy + while l1 && l2 + if l1.val <= l2.val + cur.next = l1 + l1 = l1.next + else + cur.next = l2 + l2 = l2.next + end + cur = cur.next + end + cur.next = l1 || l2 + dummy.next +end ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 079. \346\211\200\346\234\211\345\255\220\351\233\206/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 079. \346\211\200\346\234\211\345\255\220\351\233\206/README.md" index 5bdec237ee130..e09a567eb4b5a 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 079. \346\211\200\346\234\211\345\255\220\351\233\206/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 079. \346\211\200\346\234\211\345\255\220\351\233\206/README.md" @@ -40,31 +40,10 @@ ## 解法 - - -回溯法的基本模板: - -```py -res = [] -path = [] - -def backtrack(未探索区域, res, path): - if path 满足条件: - res.add(path) # 深度拷贝 - # return # 如果不用继续搜索需要 return - for 选择 in 未探索区域当前可能的选择: - if 当前选择符合要求: - path.add(当前选择) - backtrack(新的未探索区域, res, path) - path.pop() -``` +### 方法一 -### **Python3** - - - ```python class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: @@ -83,10 +62,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public List> subsets(int[] nums) { @@ -109,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +106,6 @@ public: }; ``` -### **Go** - ```go func subsets(nums []int) [][]int { var res [][]int @@ -156,8 +127,6 @@ func dfs(i int, nums, t []int, res *[][]int) { } ``` -### **TypeScipt** - ```ts function subsets(nums: number[]): number[][] { const n = nums.length; @@ -175,8 +144,6 @@ function subsets(nums: number[]): number[][] { } ``` -### **Rust** - ```rust impl Solution { fn dfs(mut i: usize, t: &mut Vec, ans: &mut Vec>, nums: &Vec) { @@ -198,10 +165,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 080. \345\220\253\346\234\211 k \344\270\252\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 080. \345\220\253\346\234\211 k \344\270\252\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/README.md" index c9b320813e7cf..71c43ca3e16fa 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 080. \345\220\253\346\234\211 k \344\270\252\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 080. \345\220\253\346\234\211 k \344\270\252\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/README.md" @@ -43,16 +43,10 @@ ## 解法 - - -深度优先搜索 DFS。 +### 方法一 -### **Python3** - - - ```python class Solution: def combine(self, n: int, k: int) -> List[List[int]]: @@ -71,10 +65,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public List> combine(int n, int k) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func combine(n int, k int) [][]int { var res [][]int @@ -146,10 +132,6 @@ func dfs(i, n, k int, t []int, res *[][]int) { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 081. \345\205\201\350\256\270\351\207\215\345\244\215\351\200\211\346\213\251\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 081. \345\205\201\350\256\270\351\207\215\345\244\215\351\200\211\346\213\251\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/README.md" index b7d67654521f7..537685674006e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 081. \345\205\201\350\256\270\351\207\215\345\244\215\351\200\211\346\213\251\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 081. \345\205\201\350\256\270\351\207\215\345\244\215\351\200\211\346\213\251\345\205\203\347\264\240\347\232\204\347\273\204\345\220\210/README.md" @@ -63,18 +63,10 @@ ## 解法 - - -DFS。 - -为了避免重复方案,需要定义一个搜索起点。 +### 方法一 -### **Python3** - - - ```python class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: @@ -97,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List> ans; @@ -133,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -166,8 +152,6 @@ public: }; ``` -### **Go** - ```go func combinationSum(candidates []int, target int) [][]int { var ans [][]int @@ -195,10 +179,64 @@ func combinationSum(candidates []int, target int) [][]int { } ``` -### **...** +```cs +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution +{ + public IList> CombinationSum(int[] candidates, int target) + { + Array.Sort(candidates); + candidates = candidates.Distinct().ToArray(); + + var paths = new List[target + 1]; + paths[0] = new List(); + foreach (var c in candidates) + { + for (var j = c; j <= target; ++j) + { + if (paths[j - c] != null) + { + if (paths[j] == null) + { + paths[j] = new List(); + } + paths[j].Add(c); + } + } + } -``` + var results = new List>(); + if (paths[target] != null) GenerateResults(results, new Stack(), paths, target, paths[target].Count - 1); + return results; + } + private void GenerateResults(IList> results, Stack result, List[] paths, int remaining, + int maxIndex) + { + if (remaining == 0) + { + results.Add(new List(result)); + return; + } + for (var i = maxIndex; i >= 0; --i) + { + var value = paths[remaining][i]; + result.Push(value); + var nextMaxIndex = paths[remaining - value].BinarySearch(value); + if (nextMaxIndex < 0) + { + nextMaxIndex = ~nextMaxIndex - 1; + } + GenerateResults(results, result, paths, remaining - value, nextMaxIndex); + result.Pop(); + } + } +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 082. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\347\273\204\345\220\210/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 082. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\347\273\204\345\220\210/README.md" index 82890959b19f3..7e5f6f4e7b5d8 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 082. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\347\273\204\345\220\210/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 082. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\347\273\204\345\220\210/README.md" @@ -48,23 +48,10 @@ ## 解法 -DFS 回溯法。需要先对 candidates 数组进行排序。 - -去重技巧: - -```python -if i > u and candidates[i] == candidates[i - 1]: - continue -``` - - +### 方法一 -### **Python3** - - - ```python class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: @@ -87,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List> ans; @@ -126,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +142,6 @@ public: }; ``` -### **Go** - ```go func combinationSum2(candidates []int, target int) [][]int { var ans [][]int @@ -192,10 +171,80 @@ func combinationSum2(candidates []int, target int) [][]int { } ``` -### **...** +```cs +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution +{ + public IList> CombinationSum2(int[] candidates, int target) + { + var dict = new SortedDictionary(candidates.GroupBy(c => c).ToDictionary(g => g.Key, g => g.Count())); + var paths = new List>[target + 1]; + paths[0] = new List>(); + foreach (var pair in dict) + { + for (var j = target; j >= 0; --j) + { + for (var k = 1; k <= pair.Value && j - pair.Key * k >= 0; ++k) + { + if (paths[j - pair.Key * k] != null) + { + if (paths[j] == null) + { + paths[j] = new List>(); + } + paths[j].Add(Tuple.Create(pair.Key, k)); + } + } + } + } -``` + var results = new List>(); + if (paths[target] != null) GenerateResults(results, new Stack(), paths, target, paths[target].Count - 1); + return results; + } + private void GenerateResults(IList> results, Stack result, List>[] paths, int remaining, + int maxIndex) + { + if (remaining == 0) + { + results.Add(new List(result)); + return; + } + for (var i = maxIndex; i >= 0; --i) + { + var path = paths[remaining][i]; + for (var j = 0; j < path.Item2; ++j) + { + result.Push(path.Item1); + } + var nextMaxIndex = paths[remaining - path.Item1 * path.Item2].BinarySearch(Tuple.Create(path.Item1, int.MinValue), Comparer.Instance); + nextMaxIndex = ~nextMaxIndex - 1; + GenerateResults(results, result, paths, remaining - path.Item1 * path.Item2, nextMaxIndex); + for (var j = 0; j < path.Item2; ++j) + { + result.Pop(); + } + } + } +} + +class Comparer : IComparer> +{ + public int Compare(Tuple x, Tuple y) + { + if (x.Item1 < y.Item1) return -1; + if (x.Item1 > y.Item1) return 1; + return x.Item2.CompareTo(y.Item2); + } + + public static Comparer Instance = new Comparer(); +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 083. \346\262\241\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\345\205\250\346\216\222\345\210\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 083. \346\262\241\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\345\205\250\346\216\222\345\210\227/README.md" index 5c7f1be4d840d..61b67e74a0ab9 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 083. \346\262\241\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\345\205\250\346\216\222\345\210\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 083. \346\262\241\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\345\205\250\346\216\222\345\210\227/README.md" @@ -45,16 +45,10 @@ ## 解法 - - -深度优先搜索。 +### 方法一 -### **Python3** - - - ```python class Solution: def permute(self, nums: List[int]) -> List[List[int]]: @@ -78,10 +72,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public List> permute(int[] nums) { @@ -112,41 +102,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number[][]} - */ -var permute = function (nums) { - const n = nums.length; - let res = []; - let path = []; - let used = new Array(n).fill(false); - dfs(0, n, nums, used, path, res); - return res; -}; - -function dfs(u, n, nums, used, path, res) { - if (u == n) { - res.push(path.slice()); - return; - } - for (let i = 0; i < n; ++i) { - if (!used[i]) { - path.push(nums[i]); - used[i] = true; - dfs(u + 1, n, nums, used, path, res); - used[i] = false; - path.pop(); - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -176,8 +131,6 @@ public: }; ``` -### **Go** - ```go func permute(nums []int) [][]int { n := len(nums) @@ -206,10 +159,71 @@ func dfs(u, n int, nums []int, used []bool, path []int, res *[][]int) { } ``` -### **...** +```js +/** + * @param {number[]} nums + * @return {number[][]} + */ +var permute = function (nums) { + const n = nums.length; + let res = []; + let path = []; + let used = new Array(n).fill(false); + dfs(0, n, nums, used, path, res); + return res; +}; +function dfs(u, n, nums, used, path, res) { + if (u == n) { + res.push(path.slice()); + return; + } + for (let i = 0; i < n; ++i) { + if (!used[i]) { + path.push(nums[i]); + used[i] = true; + dfs(u + 1, n, nums, used, path, res); + used[i] = false; + path.pop(); + } + } +} ``` +```cs +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public IList> Permute(int[] nums) { + var results = new List>(); + var temp = new List(); + var visited = new bool[nums.Length]; + Search(nums, visited, temp, results); + return results; + } + + private void Search(int[] nums, bool[] visited, IList temp, IList> results) + { + int count = 0; + for (var i = 0; i < nums.Length; ++i) + { + if (visited[i]) continue; + ++count; + temp.Add(nums[i]); + visited[i] = true; + Search(nums, visited, temp, results); + temp.RemoveAt(temp.Count - 1); + visited[i] = false; + } + if (count == 0 && temp.Any()) + { + results.Add(new List(temp)); + } + } +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 084. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\345\205\250\346\216\222\345\210\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 084. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\345\205\250\346\216\222\345\210\227/README.md" index 33b4e89275250..27dbc7342a82a 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 084. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\345\205\250\346\216\222\345\210\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 084. \345\220\253\346\234\211\351\207\215\345\244\215\345\205\203\347\264\240\351\233\206\345\220\210\347\232\204\345\205\250\346\216\222\345\210\227/README.md" @@ -40,16 +40,10 @@ ## 解法 - - -排序 + 深度优先搜索。 +### 方法一 -### **Python3** - - - ```python class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: @@ -75,10 +69,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public List> permuteUnique(int[] nums) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func permuteUnique(nums []int) [][]int { n := len(nums) @@ -174,10 +160,47 @@ func dfs(u, n int, nums []int, used []bool, path []int, res *[][]int) { } ``` -### **...** - -``` +```cs +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public IList> PermuteUnique(int[] nums) { + var results = new List>(); + var temp = new List(); + var count = nums.GroupBy(n => n).ToDictionary(g => g.Key, g => g.Count()); + Search(count, temp, results); + return results; + } + private void Search(Dictionary count, IList temp, IList> results) + { + if (!count.Any() && temp.Any()) + { + results.Add(new List(temp)); + return; + } + var keys = count.Keys.ToList(); + foreach (var key in keys) + { + temp.Add(key); + --count[key]; + if (count[key] == 0) count.Remove(key); + Search(count, temp, results); + temp.RemoveAt(temp.Count - 1); + if (count.ContainsKey(key)) + { + ++count[key]; + } + else + { + count[key] = 1; + } + } + } +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 085. \347\224\237\346\210\220\345\214\271\351\205\215\347\232\204\346\213\254\345\217\267/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 085. \347\224\237\346\210\220\345\214\271\351\205\215\347\232\204\346\213\254\345\217\267/README.md" index 52ecb82eabda9..41d130bc673c1 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 085. \347\224\237\346\210\220\345\214\271\351\205\215\347\232\204\346\213\254\345\217\267/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 085. \347\224\237\346\210\220\345\214\271\351\205\215\347\232\204\346\213\254\345\217\267/README.md" @@ -36,16 +36,10 @@ ## 解法 - - -深度优先搜索 DFS。 +### 方法一 -### **Python3** - - - ```python class Solution: def generateParenthesis(self, n: int) -> List[str]: @@ -63,10 +57,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List generateParenthesis(int n) { @@ -90,30 +80,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function generateParenthesis(n: number): string[] { - let ans = []; - let dfs = function (left, right, t) { - if (left == n && right == n) { - ans.push(t); - return; - } - if (left < n) { - dfs(left + 1, right, t + '('); - } - if (right < left) { - dfs(left, right + 1, t + ')'); - } - }; - dfs(0, 0, ''); - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -134,8 +100,6 @@ public: }; ``` -### **Go** - ```go func generateParenthesis(n int) []string { var ans []string @@ -157,7 +121,25 @@ func generateParenthesis(n int) []string { } ``` -### **JavaScript** +```ts +function generateParenthesis(n: number): string[] { + let ans = []; + let dfs = function (left, right, t) { + if (left == n && right == n) { + ans.push(t); + return; + } + if (left < n) { + dfs(left + 1, right, t + '('); + } + if (right < left) { + dfs(left, right + 1, t + ')'); + } + }; + dfs(0, 0, ''); + return ans; +} +``` ```js /** @@ -183,10 +165,6 @@ var generateParenthesis = function (n) { }; ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/README.md" index 1d2ed5fcf2470..e8b85fa13b3f4 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 086. \345\210\206\345\211\262\345\233\236\346\226\207\345\255\220\345\255\227\347\254\246\344\270\262/README.md" @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:预处理 + DFS(回溯)** +### 方法一:预处理 + DFS(回溯) 我们可以使用动态规划,预处理出字符串中的任意子串是否为回文串,即 $f[i][j]$ 表示子串 $s[i..j]$ 是否为回文串。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def partition(self, s: str) -> List[List[str]]: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int n; @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go func partition(s string) (ans [][]string) { n := len(s) @@ -205,8 +191,6 @@ func partition(s string) (ans [][]string) { } ``` -### **TypeScript** - ```ts function partition(s: string): string[][] { const n = s.length; @@ -236,8 +220,6 @@ function partition(s: string): string[][] { } ``` -### **C#** - ```cs public class Solution { private int n; @@ -280,10 +262,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/README.md" index 3e84a741434cc..7cc0399185d13 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 087. \345\244\215\345\216\237 IP/README.md" @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们定义一个函数 $dfs(i)$,表示从字符串 $s$ 的第 $i$ 位开始,搜索能够组成的 IP 地址列表。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def restoreIpAddresses(self, s: str) -> List[str]: @@ -109,10 +103,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int n; @@ -149,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -183,8 +171,6 @@ public: }; ``` -### **Go** - ```go func restoreIpAddresses(s string) (ans []string) { n := len(s) @@ -214,8 +200,6 @@ func restoreIpAddresses(s string) (ans []string) { } ``` -### **TypeScript** - ```ts function restoreIpAddresses(s: string): string[] { const n = s.length; @@ -245,8 +229,6 @@ function restoreIpAddresses(s: string): string[] { } ``` -### **C#** - ```cs public class Solution { private IList ans = new List(); @@ -283,10 +265,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/README.md" index 66645b6d16928..f0772e9945013 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 088. \347\210\254\346\245\274\346\242\257\347\232\204\346\234\200\345\260\221\346\210\220\346\234\254/README.md" @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 定义 `dp[i]` 表示到达第 `i` 个台阶的最小花费。可以得到状态转移方程: @@ -63,10 +61,6 @@ $$ -### **Python3** - - - ```python class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: @@ -77,19 +71,6 @@ class Solution: return dp[-1] ``` -```python -class Solution: - def minCostClimbingStairs(self, cost: List[int]) -> int: - a = b = 0 - for i in range(1, len(cost)): - a, b = b, min(a + cost[i - 1], b + cost[i]) - return b -``` - -### **Java** - - - ```java class Solution { public int minCostClimbingStairs(int[] cost) { @@ -103,21 +84,30 @@ class Solution { } ``` -```java +```cpp class Solution { - public int minCostClimbingStairs(int[] cost) { - int a = 0, b = 0; - for (int i = 1; i < cost.length; ++i) { - int c = Math.min(a + cost[i - 1], b + cost[i]); - a = b; - b = c; +public: + int minCostClimbingStairs(vector& cost) { + int n = cost.size(); + vector dp(n + 1); + for (int i = 2; i <= n; ++i) { + dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); } - return b; + return dp[n]; } -} +}; ``` -### **TypeScript** +```go +func minCostClimbingStairs(cost []int) int { + n := len(cost) + dp := make([]int, n+1) + for i := 2; i <= n; i++ { + dp[i] = min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2]) + } + return dp[n] +} +``` ```ts function minCostClimbingStairs(cost: number[]): number { @@ -130,31 +120,33 @@ function minCostClimbingStairs(cost: number[]): number { } ``` -```ts -function minCostClimbingStairs(cost: number[]): number { - let a = 0, - b = 0; - for (let i = 1; i < cost.length; ++i) { - [a, b] = [b, Math.min(a + cost[i - 1], b + cost[i])]; - } - return b; -} -``` + -### **C++** +### 方法二 -```cpp + + +```python +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: + a = b = 0 + for i in range(1, len(cost)): + a, b = b, min(a + cost[i - 1], b + cost[i]) + return b +``` + +```java class Solution { -public: - int minCostClimbingStairs(vector& cost) { - int n = cost.size(); - vector dp(n + 1); - for (int i = 2; i <= n; ++i) { - dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); + public int minCostClimbingStairs(int[] cost) { + int a = 0, b = 0; + for (int i = 1; i < cost.length; ++i) { + int c = Math.min(a + cost[i - 1], b + cost[i]); + a = b; + b = c; } - return dp[n]; + return b; } -}; +} ``` ```cpp @@ -172,19 +164,6 @@ public: }; ``` -### **Go** - -```go -func minCostClimbingStairs(cost []int) int { - n := len(cost) - dp := make([]int, n+1) - for i := 2; i <= n; i++ { - dp[i] = min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2]) - } - return dp[n] -} -``` - ```go func minCostClimbingStairs(cost []int) int { a, b := 0, 0 @@ -195,10 +174,17 @@ func minCostClimbingStairs(cost []int) int { } ``` -### **...** - -``` - +```ts +function minCostClimbingStairs(cost: number[]): number { + let a = 0, + b = 0; + for (let i = 1; i < cost.length; ++i) { + [a, b] = [b, Math.min(a + cost[i - 1], b + cost[i])]; + } + return b; +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/README.md" index f1a144afff175..d925a002c8513 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 089. \346\210\277\345\261\213\345\201\267\347\233\227/README.md" @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示前 $i$ 间房屋能偷窃到的最高总金额,初始时 $f[0]=0$, $f[1]=nums[0]$。 @@ -72,10 +70,6 @@ $$ -### **Python3** - - - ```python class Solution: def rob(self, nums: List[int]) -> int: @@ -87,19 +81,6 @@ class Solution: return f[n] ``` -```python -class Solution: - def rob(self, nums: List[int]) -> int: - f = g = 0 - for x in nums: - f, g = max(f, g), f + x - return max(f, g) -``` - -### **Java** - - - ```java class Solution { public int rob(int[] nums) { @@ -114,22 +95,6 @@ class Solution { } ``` -```java -class Solution { - public int rob(int[] nums) { - int f = 0, g = 0; - for (int x : nums) { - int ff = Math.max(f, g); - g = f + x; - f = ff; - } - return Math.max(f, g); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -146,23 +111,6 @@ public: }; ``` -```cpp -class Solution { -public: - int rob(vector& nums) { - int f = 0, g = 0; - for (int& x : nums) { - int ff = max(f, g); - g = f + x; - f = ff; - } - return max(f, g); - } -}; -``` - -### **Go** - ```go func rob(nums []int) int { n := len(nums) @@ -175,18 +123,6 @@ func rob(nums []int) int { } ``` -```go -func rob(nums []int) int { - f, g := 0, 0 - for _, x := range nums { - f, g = max(f, g), f+x - } - return max(f, g) -} -``` - -### **TypeScript** - ```ts function rob(nums: number[]): number { const n = nums.length; @@ -199,18 +135,6 @@ function rob(nums: number[]): number { } ``` -```ts -function rob(nums: number[]): number { - let [f, g] = [0, 0]; - for (const x of nums) { - [f, g] = [Math.max(f, g), f + x]; - } - return Math.max(f, g); -} -``` - -### **Rust** - ```rust impl Solution { pub fn rob(nums: Vec) -> i32 { @@ -223,10 +147,70 @@ impl Solution { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def rob(self, nums: List[int]) -> int: + f = g = 0 + for x in nums: + f, g = max(f, g), f + x + return max(f, g) ``` +```java +class Solution { + public int rob(int[] nums) { + int f = 0, g = 0; + for (int x : nums) { + int ff = Math.max(f, g); + g = f + x; + f = ff; + } + return Math.max(f, g); + } +} +``` + +```cpp +class Solution { +public: + int rob(vector& nums) { + int f = 0, g = 0; + for (int& x : nums) { + int ff = max(f, g); + g = f + x; + f = ff; + } + return max(f, g); + } +}; +``` + +```go +func rob(nums []int) int { + f, g := 0, 0 + for _, x := range nums { + f, g = max(f, g), f+x + } + return max(f, g) +} +``` + +```ts +function rob(nums: number[]): number { + let [f, g] = [0, 0]; + for (const x of nums) { + [f, g] = [Math.max(f, g), f + x]; + } + return Math.max(f, g); +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/README.md" index 0b93f047d0ba3..a0c7f501fe69e 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 090. \347\216\257\345\275\242\346\210\277\345\261\213\345\201\267\347\233\227/README.md" @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 环状排列意味着第一个房屋和最后一个房屋中最多只能选择一个偷窃,因此可以把此环状排列房间问题约化为两个单排排列房屋子问题。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def rob(self, nums: List[int]) -> int: @@ -76,10 +70,6 @@ class Solution: return max(_rob(nums[1:]), _rob(nums[:-1])) ``` -### **Java** - - - ```java class Solution { public int rob(int[] nums) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func rob(nums []int) int { n := len(nums) @@ -147,8 +133,6 @@ func robRange(nums []int, l, r int) int { } ``` -### **TypeScript** - ```ts function rob(nums: number[]): number { const n = nums.length; @@ -166,8 +150,6 @@ function rob(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn rob(nums: Vec) -> i32 { @@ -187,10 +169,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 091. \347\262\211\345\210\267\346\210\277\345\255\220/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 091. \347\262\211\345\210\267\346\210\277\345\255\220/README.md" index b2f6be1a3aeb2..37c7797665b94 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 091. \347\262\211\345\210\267\346\210\277\345\255\220/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 091. \347\262\211\345\210\267\346\210\277\345\255\220/README.md" @@ -47,14 +47,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minCost(self, costs: List[List[int]]) -> int: @@ -67,10 +63,6 @@ class Solution: return min(r, g, b) ``` -### **Java** - - - ```java class Solution { public int minCost(int[][] costs) { @@ -86,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +94,6 @@ public: }; ``` -### **Go** - ```go func minCost(costs [][]int) int { r, g, b := 0, 0, 0 @@ -119,8 +107,6 @@ func minCost(costs [][]int) int { } ``` -### **TypeScript** - ```ts function minCost(costs: number[][]): number { let [r, g, b] = [0, 0, 0]; @@ -131,8 +117,6 @@ function minCost(costs: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_cost(costs: Vec>) -> i32 { @@ -149,10 +133,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/README.md" index 97b73c95d0bc5..f5627595ff20a 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 092. \347\277\273\350\275\254\345\255\227\347\254\246/README.md" @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们先预处理得到右侧的 $0$ 的个数,记为 $right0$,初始化一个变量 $left0$,表示左侧的 $0$ 的个数。如果最终字符串变成全 `'0'` 或者全 `'1'`,那么答案为 $ans= \min(right0, n - right0)$。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def minFlipsMonoIncr(self, s: str) -> int: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minFlipsMonoIncr(String s) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func minFlipsMonoIncr(s string) int { n := len(s) @@ -155,8 +141,6 @@ func minFlipsMonoIncr(s string) int { } ``` -### **TypeScript** - ```ts function minFlipsMonoIncr(s: string): number { const n = s.length; @@ -175,10 +159,6 @@ function minFlipsMonoIncr(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 093. \346\234\200\351\225\277\346\226\220\346\263\242\351\202\243\345\245\221\346\225\260\345\210\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 093. \346\234\200\351\225\277\346\226\220\346\263\242\351\202\243\345\245\221\346\225\260\345\210\227/README.md" index 3ddcd983fa301..841d295cf851c 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 093. \346\234\200\351\225\277\346\226\220\346\263\242\351\202\243\345\245\221\346\225\260\345\210\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 093. \346\234\200\351\225\277\346\226\220\346\263\242\351\202\243\345\245\221\346\225\260\345\210\227/README.md" @@ -53,19 +53,10 @@ ## 解法 - - -动态规划。 - -- 状态表示:`dp[j][i]` 表示斐波那契式最后两项为 `arr[j]`, `arr[i]` 时的最大子序列长度。 -- 状态计算:`dp[j][i] = dp[k][j] + 1`(当且仅当 `k < j < i`,并且 `arr[k] + arr[j] == arr[i]`), `ans = max(ans, dp[j][i])`。 +### 方法一 -### **Python3** - - - ```python class Solution: def lenLongestFibSubseq(self, arr: List[int]) -> int: @@ -87,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int lenLongestFibSubseq(int[] arr) { @@ -123,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +140,6 @@ public: }; ``` -### **Go** - ```go func lenLongestFibSubseq(arr []int) int { n := len(arr) @@ -186,10 +169,6 @@ func lenLongestFibSubseq(arr []int) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/README.md" index d7b6095b37bd0..8194d7a177a3b 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 094. \346\234\200\345\260\221\345\233\236\346\226\207\345\210\206\345\211\262/README.md" @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们先预处理得到字符串 $s$ 的每一个子串 $s[i..j]$ 是否为回文串,记录在二维数组 $g[i][j]$ 中,其中 $g[i][j]$ 表示子串 $s[i..j]$ 是否为回文串。 @@ -71,10 +69,6 @@ $$ -### **Python3** - - - ```python class Solution: def minCut(self, s: str) -> int: @@ -91,10 +85,6 @@ class Solution: return f[-1] ``` -### **Java** - - - ```java class Solution { public int minCut(String s) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +140,6 @@ public: }; ``` -### **Go** - ```go func minCut(s string) int { n := len(s) @@ -186,8 +172,6 @@ func minCut(s string) int { } ``` -### **TypeScript** - ```ts function minCut(s: string): number { const n = s.length; @@ -213,8 +197,6 @@ function minCut(s: string): number { } ``` -### **C#** - ```cs public class Solution { public int MinCut(string s) { @@ -244,10 +226,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/README.md" index 711e5fa922535..a69d1418ff5ee 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 095. \346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227/README.md" @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示 $text1$ 的前 $i$ 个字符和 $text2$ 的前 $j$ 个字符的最长公共子序列的长度。那么答案为 $f[m][n]$,其中 $m$ 和 $n$ 分别为 $text1$ 和 $text2$ 的长度。 @@ -75,10 +73,6 @@ $$ -### **Python3** - - - ```python class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: @@ -93,10 +87,6 @@ class Solution: return f[-1][-1] ``` -### **Java** - - - ```java class Solution { public int longestCommonSubsequence(String text1, String text2) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func longestCommonSubsequence(text1 string, text2 string) int { m, n := len(text1), len(text2) @@ -160,18 +146,11 @@ func longestCommonSubsequence(text1 string, text2 string) int { } ``` -### **JavaScript** - -```js -/** - * @param {string} text1 - * @param {string} text2 - * @return {number} - */ -var longestCommonSubsequence = function (text1, text2) { +```ts +function longestCommonSubsequence(text1: string, text2: string): number { const m = text1.length; const n = text2.length; - const f = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); + const f: number[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); for (let i = 1; i <= m; ++i) { for (let j = 1; j <= n; ++j) { if (text1[i - 1] == text2[j - 1]) { @@ -182,16 +161,39 @@ var longestCommonSubsequence = function (text1, text2) { } } return f[m][n]; -}; +} ``` -### **TypeScript** +```rust +impl Solution { + pub fn longest_common_subsequence(text1: String, text2: String) -> i32 { + let (m, n) = (text1.len(), text2.len()); + let (text1, text2) = (text1.as_bytes(), text2.as_bytes()); + let mut f = vec![vec![0; n + 1]; m + 1]; + for i in 1..=m { + for j in 1..=n { + f[i][j] = if text1[i - 1] == text2[j - 1] { + f[i - 1][j - 1] + 1 + } else { + f[i - 1][j].max(f[i][j - 1]) + }; + } + } + f[m][n] + } +} +``` -```ts -function longestCommonSubsequence(text1: string, text2: string): number { +```js +/** + * @param {string} text1 + * @param {string} text2 + * @return {number} + */ +var longestCommonSubsequence = function (text1, text2) { const m = text1.length; const n = text2.length; - const f: number[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); + const f = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); for (let i = 1; i <= m; ++i) { for (let j = 1; j <= n; ++j) { if (text1[i - 1] == text2[j - 1]) { @@ -202,13 +204,48 @@ function longestCommonSubsequence(text1: string, text2: string): number { } } return f[m][n]; -} +}; ``` -### **...** - +```cs +public class Solution { + public int LongestCommonSubsequence(string text1, string text2) { + int m = text1.Length, n = text2.Length; + int[,] f = new int[m + 1, n + 1]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (text1[i - 1] == text2[j - 1]) { + f[i, j] = f[i - 1, j - 1] + 1; + } else { + f[i, j] = Math.Max(f[i - 1, j], f[i, j - 1]); + } + } + } + return f[m, n]; + } +} ``` +```kotlin +class Solution { + fun longestCommonSubsequence(text1: String, text2: String): Int { + val m = text1.length + val n = text2.length + val f = Array(m + 1) { IntArray(n + 1) } + for (i in 1..m) { + for (j in 1..n) { + if (text1[i - 1] == text2[j - 1]) { + f[i][j] = f[i - 1][j - 1] + 1 + } else { + f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]) + } + } + } + return f[m][n] + } +} ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/README.md" index e9a68414a60b9..bb378547f34de 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 096. \345\255\227\347\254\246\344\270\262\344\272\244\347\273\207/README.md" @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们记字符串 $s_1$ 的长度为 $m$,字符串 $s_2$ 的长度为 $n$,如果 $m + n \neq |s_3|$,那么 $s_3$ 一定不是 $s_1$ 和 $s_2$ 的交错字符串,返回 `false`。 @@ -80,34 +78,8 @@ 时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是字符串 $s_1$ 和 $s_2$ 的长度。 -**方法二:动态规划** - -我们可以将方法一中的记忆化搜索转化为动态规划。 - -定义 $f[i][j]$ 表示字符串 $s_1$ 的前 $i$ 个字符和字符串 $s_2$ 的前 $j$ 个字符是否能交错组成字符串 $s_3$ 的前 $i + j$ 个字符。在进行状态转移时,我们可以考虑当前字符是由 $s_1$ 的最后一个字符还是 $s_2$ 的最后一个字符得到的,因此有状态转移方程: - -$$ -f[i][j] = \begin{cases} -f[i - 1][j] & \text{if } s_1[i - 1] = s_3[i + j - 1] \\ -\text{or } f[i][j - 1] & \text{if } s_2[j - 1] = s_3[i + j - 1] \\ -\text{false} & \text{otherwise} -\end{cases} -$$ - -其中 $f[0][0] = \text{true}$ 表示空串是两个空串的交错字符串。 - -答案即为 $f[m][n]$。 - -时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是字符串 $s_1$ 和 $s_2$ 的长度。 - -我们注意到,状态 $f[i][j]$ 只和状态 $f[i - 1][j]$、$f[i][j - 1]$、$f[i - 1][j - 1]$ 有关,因此我们可以使用滚动数组优化空间复杂度,将空间复杂度优化到 $O(n)$。 - -### **Python3** - - - ```python class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: @@ -128,45 +100,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def isInterleave(self, s1: str, s2: str, s3: str) -> bool: - m, n = len(s1), len(s2) - if m + n != len(s3): - return False - f = [[False] * (n + 1) for _ in range(m + 1)] - f[0][0] = True - for i in range(m + 1): - for j in range(n + 1): - k = i + j - 1 - if i and s1[i - 1] == s3[k]: - f[i][j] = f[i - 1][j] - if j and s2[j - 1] == s3[k]: - f[i][j] |= f[i][j - 1] - return f[m][n] -``` - -```python -class Solution: - def isInterleave(self, s1: str, s2: str, s3: str) -> bool: - m, n = len(s1), len(s2) - if m + n != len(s3): - return False - f = [True] + [False] * n - for i in range(m + 1): - for j in range(n + 1): - k = i + j - 1 - if i: - f[j] &= s1[i - 1] == s3[k] - if j: - f[j] |= f[j - 1] and s2[j - 1] == s3[k] - return f[n] -``` - -### **Java** - - - ```java class Solution { private Map, Boolean> f = new HashMap<>(); @@ -210,58 +143,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isInterleave(String s1, String s2, String s3) { - int m = s1.length(), n = s2.length(); - if (m + n != s3.length()) { - return false; - } - boolean[][] f = new boolean[m + 1][n + 1]; - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i > 0 && s1.charAt(i - 1) == s3.charAt(k)) { - f[i][j] = f[i - 1][j]; - } - if (j > 0 && s2.charAt(j - 1) == s3.charAt(k)) { - f[i][j] |= f[i][j - 1]; - } - } - } - return f[m][n]; - } -} -``` - -```java -class Solution { - public boolean isInterleave(String s1, String s2, String s3) { - int m = s1.length(), n = s2.length(); - if (m + n != s3.length()) { - return false; - } - boolean[] f = new boolean[n + 1]; - f[0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i > 0) { - f[j] &= s1.charAt(i - 1) == s3.charAt(k); - } - if (j > 0) { - f[j] |= (f[j - 1] & s2.charAt(j - 1) == s3.charAt(k)); - } - } - } - return f[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -293,62 +174,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool isInterleave(string s1, string s2, string s3) { - int m = s1.size(), n = s2.size(); - if (m + n != s3.size()) { - return false; - } - bool f[m + 1][n + 1]; - memset(f, false, sizeof(f)); - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i > 0 && s1[i - 1] == s3[k]) { - f[i][j] = f[i - 1][j]; - } - if (j > 0 && s2[j - 1] == s3[k]) { - f[i][j] |= f[i][j - 1]; - } - } - } - return f[m][n]; - } -}; -``` - -```cpp -class Solution { -public: - bool isInterleave(string s1, string s2, string s3) { - int m = s1.size(), n = s2.size(); - if (m + n != s3.size()) { - return false; - } - bool f[n + 1]; - memset(f, false, sizeof(f)); - f[0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i) { - f[j] &= s1[i - 1] == s3[k]; - } - if (j) { - f[j] |= (s2[j - 1] == s3[k] && f[j - 1]); - } - } - } - return f[n]; - } -}; -``` - -### **Go** - ```go func isInterleave(s1 string, s2 string, s3 string) bool { m, n := len(s1), len(s2) @@ -373,57 +198,6 @@ func isInterleave(s1 string, s2 string, s3 string) bool { } ``` -```go -func isInterleave(s1 string, s2 string, s3 string) bool { - m, n := len(s1), len(s2) - if m+n != len(s3) { - return false - } - f := make([][]bool, m+1) - for i := range f { - f[i] = make([]bool, n+1) - } - f[0][0] = true - for i := 0; i <= m; i++ { - for j := 0; j <= n; j++ { - k := i + j - 1 - if i > 0 && s1[i-1] == s3[k] { - f[i][j] = f[i-1][j] - } - if j > 0 && s2[j-1] == s3[k] { - f[i][j] = (f[i][j] || f[i][j-1]) - } - } - } - return f[m][n] -} -``` - -```go -func isInterleave(s1 string, s2 string, s3 string) bool { - m, n := len(s1), len(s2) - if m+n != len(s3) { - return false - } - f := make([]bool, n+1) - f[0] = true - for i := 0; i <= m; i++ { - for j := 0; j <= n; j++ { - k := i + j - 1 - if i > 0 { - f[j] = (f[j] && s1[i-1] == s3[k]) - } - if j > 0 { - f[j] = (f[j] || (s2[j-1] == s3[k] && f[j-1])) - } - } - } - return f[n] -} -``` - -### **TypeScript** - ```ts function isInterleave(s1: string, s2: string, s3: string): boolean { const m = s1.length; @@ -452,28 +226,167 @@ function isInterleave(s1: string, s2: string, s3: string): boolean { } ``` -```ts -function isInterleave(s1: string, s2: string, s3: string): boolean { - const m = s1.length; - const n = s2.length; - if (m + n !== s3.length) { - return false; - } - const f: boolean[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(false)); - f[0][0] = true; - for (let i = 0; i <= m; ++i) { - for (let j = 0; j <= n; ++j) { - const k = i + j - 1; - if (i > 0 && s1[i - 1] === s3[k]) { - f[i][j] = f[i - 1][j]; - } - if (j > 0 && s2[j - 1] === s3[k]) { - f[i][j] = f[i][j] || f[i][j - 1]; - } +```cs +public class Solution { + private int m; + private int n; + private string s1; + private string s2; + private string s3; + private int[,] f; + + public bool IsInterleave(string s1, string s2, string s3) { + m = s1.Length; + n = s2.Length; + if (m + n != s3.Length) { + return false; } + this.s1 = s1; + this.s2 = s2; + this.s3 = s3; + f = new int[m + 1, n + 1]; + return dfs(0, 0); } - return f[m][n]; -} + + private bool dfs(int i, int j) { + if (i >= m && j >= n) { + return true; + } + if (f[i, j] != 0) { + return f[i, j] == 1; + } + f[i, j] = -1; + if (i < m && s1[i] == s3[i + j] && dfs(i + 1, j)) { + f[i, j] = 1; + } + if (f[i, j] == -1 && j < n && s2[j] == s3[i + j] && dfs(i, j + 1)) { + f[i, j] = 1; + } + return f[i, j] == 1; + } +} +``` + + + +### 方法二:动态规划 + +我们可以将方法一中的记忆化搜索转化为动态规划。 + +定义 $f[i][j]$ 表示字符串 $s_1$ 的前 $i$ 个字符和字符串 $s_2$ 的前 $j$ 个字符是否能交错组成字符串 $s_3$ 的前 $i + j$ 个字符。在进行状态转移时,我们可以考虑当前字符是由 $s_1$ 的最后一个字符还是 $s_2$ 的最后一个字符得到的,因此有状态转移方程: + +$$ +f[i][j] = \begin{cases} +f[i - 1][j] & \text{if } s_1[i - 1] = s_3[i + j - 1] \\ +\text{or } f[i][j - 1] & \text{if } s_2[j - 1] = s_3[i + j - 1] \\ +\text{false} & \text{otherwise} +\end{cases} +$$ + +其中 $f[0][0] = \text{true}$ 表示空串是两个空串的交错字符串。 + +答案即为 $f[m][n]$。 + +时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是字符串 $s_1$ 和 $s_2$ 的长度。 + +我们注意到,状态 $f[i][j]$ 只和状态 $f[i - 1][j]$、$f[i][j - 1]$、$f[i - 1][j - 1]$ 有关,因此我们可以使用滚动数组优化空间复杂度,将空间复杂度优化到 $O(n)$。 + + + +```python +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + m, n = len(s1), len(s2) + if m + n != len(s3): + return False + f = [[False] * (n + 1) for _ in range(m + 1)] + f[0][0] = True + for i in range(m + 1): + for j in range(n + 1): + k = i + j - 1 + if i and s1[i - 1] == s3[k]: + f[i][j] = f[i - 1][j] + if j and s2[j - 1] == s3[k]: + f[i][j] |= f[i][j - 1] + return f[m][n] +``` + +```java +class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + int m = s1.length(), n = s2.length(); + if (m + n != s3.length()) { + return false; + } + boolean[][] f = new boolean[m + 1][n + 1]; + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1.charAt(i - 1) == s3.charAt(k)) { + f[i][j] = f[i - 1][j]; + } + if (j > 0 && s2.charAt(j - 1) == s3.charAt(k)) { + f[i][j] |= f[i][j - 1]; + } + } + } + return f[m][n]; + } +} +``` + +```cpp +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + int m = s1.size(), n = s2.size(); + if (m + n != s3.size()) { + return false; + } + bool f[m + 1][n + 1]; + memset(f, false, sizeof(f)); + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1[i - 1] == s3[k]) { + f[i][j] = f[i - 1][j]; + } + if (j > 0 && s2[j - 1] == s3[k]) { + f[i][j] |= f[i][j - 1]; + } + } + } + return f[m][n]; + } +}; +``` + +```go +func isInterleave(s1 string, s2 string, s3 string) bool { + m, n := len(s1), len(s2) + if m+n != len(s3) { + return false + } + f := make([][]bool, m+1) + for i := range f { + f[i] = make([]bool, n+1) + } + f[0][0] = true + for i := 0; i <= m; i++ { + for j := 0; j <= n; j++ { + k := i + j - 1 + if i > 0 && s1[i-1] == s3[k] { + f[i][j] = f[i-1][j] + } + if j > 0 && s2[j-1] == s3[k] { + f[i][j] = (f[i][j] || f[i][j-1]) + } + } + } + return f[m][n] +} ``` ```ts @@ -483,88 +396,167 @@ function isInterleave(s1: string, s2: string, s3: string): boolean { if (m + n !== s3.length) { return false; } - const f: boolean[] = new Array(n + 1).fill(false); - f[0] = true; + const f: boolean[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(false)); + f[0][0] = true; for (let i = 0; i <= m; ++i) { for (let j = 0; j <= n; ++j) { const k = i + j - 1; - if (i) { - f[j] = f[j] && s1[i - 1] === s3[k]; + if (i > 0 && s1[i - 1] === s3[k]) { + f[i][j] = f[i - 1][j]; } - if (j) { - f[j] = f[j] || (f[j - 1] && s2[j - 1] === s3[k]); + if (j > 0 && s2[j - 1] === s3[k]) { + f[i][j] = f[i][j] || f[i][j - 1]; } } } - return f[n]; + return f[m][n]; } ``` -### **C#** - ```cs public class Solution { - private int m; - private int n; - private string s1; - private string s2; - private string s3; - private int[,] f; - public bool IsInterleave(string s1, string s2, string s3) { - m = s1.Length; - n = s2.Length; + int m = s1.Length, n = s2.Length; if (m + n != s3.Length) { return false; } - this.s1 = s1; - this.s2 = s2; - this.s3 = s3; - f = new int[m + 1, n + 1]; - return dfs(0, 0); + bool[,] f = new bool[m + 1, n + 1]; + f[0, 0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1[i - 1] == s3[k]) { + f[i, j] = f[i - 1, j]; + } + if (j > 0 && s2[j - 1] == s3[k]) { + f[i, j] |= f[i, j - 1]; + } + } + } + return f[m, n]; } +} +``` - private bool dfs(int i, int j) { - if (i >= m && j >= n) { - return true; - } - if (f[i, j] != 0) { - return f[i, j] == 1; - } - f[i, j] = -1; - if (i < m && s1[i] == s3[i + j] && dfs(i + 1, j)) { - f[i, j] = 1; + + +### 方法三 + + + +```python +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + m, n = len(s1), len(s2) + if m + n != len(s3): + return False + f = [True] + [False] * n + for i in range(m + 1): + for j in range(n + 1): + k = i + j - 1 + if i: + f[j] &= s1[i - 1] == s3[k] + if j: + f[j] |= f[j - 1] and s2[j - 1] == s3[k] + return f[n] +``` + +```java +class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + int m = s1.length(), n = s2.length(); + if (m + n != s3.length()) { + return false; } - if (f[i, j] == -1 && j < n && s2[j] == s3[i + j] && dfs(i, j + 1)) { - f[i, j] = 1; + boolean[] f = new boolean[n + 1]; + f[0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0) { + f[j] &= s1.charAt(i - 1) == s3.charAt(k); + } + if (j > 0) { + f[j] |= (f[j - 1] & s2.charAt(j - 1) == s3.charAt(k)); + } + } } - return f[i, j] == 1; + return f[n]; } } ``` -```cs -public class Solution { - public bool IsInterleave(string s1, string s2, string s3) { - int m = s1.Length, n = s2.Length; - if (m + n != s3.Length) { +```cpp +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + int m = s1.size(), n = s2.size(); + if (m + n != s3.size()) { return false; } - bool[,] f = new bool[m + 1, n + 1]; - f[0, 0] = true; + bool f[n + 1]; + memset(f, false, sizeof(f)); + f[0] = true; for (int i = 0; i <= m; ++i) { for (int j = 0; j <= n; ++j) { int k = i + j - 1; - if (i > 0 && s1[i - 1] == s3[k]) { - f[i, j] = f[i - 1, j]; + if (i) { + f[j] &= s1[i - 1] == s3[k]; } - if (j > 0 && s2[j - 1] == s3[k]) { - f[i, j] |= f[i, j - 1]; + if (j) { + f[j] |= (s2[j - 1] == s3[k] && f[j - 1]); } } } - return f[m, n]; + return f[n]; } +}; +``` + +```go +func isInterleave(s1 string, s2 string, s3 string) bool { + m, n := len(s1), len(s2) + if m+n != len(s3) { + return false + } + f := make([]bool, n+1) + f[0] = true + for i := 0; i <= m; i++ { + for j := 0; j <= n; j++ { + k := i + j - 1 + if i > 0 { + f[j] = (f[j] && s1[i-1] == s3[k]) + } + if j > 0 { + f[j] = (f[j] || (s2[j-1] == s3[k] && f[j-1])) + } + } + } + return f[n] +} +``` + +```ts +function isInterleave(s1: string, s2: string, s3: string): boolean { + const m = s1.length; + const n = s2.length; + if (m + n !== s3.length) { + return false; + } + const f: boolean[] = new Array(n + 1).fill(false); + f[0] = true; + for (let i = 0; i <= m; ++i) { + for (let j = 0; j <= n; ++j) { + const k = i + j - 1; + if (i) { + f[j] = f[j] && s1[i - 1] === s3[k]; + } + if (j) { + f[j] = f[j] || (f[j - 1] && s2[j - 1] === s3[k]); + } + } + } + return f[n]; } ``` @@ -593,10 +585,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/README.md" index 152248d13eed2..577ea0a2b5e72 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 097. \345\255\220\345\272\217\345\210\227\347\232\204\346\225\260\347\233\256/README.md" @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示字符串 $s$ 的前 $i$ 个字符中,子序列构成字符串 $t$ 的前 $j$ 个字符的方案数。初始时 $f[i][0]=1$,其中 $i \in [0,m]$。 @@ -82,10 +80,6 @@ $$ -### **Python3** - - - ```python class Solution: def numDistinct(self, s: str, t: str) -> int: @@ -101,22 +95,6 @@ class Solution: return f[m][n] ``` -```python -class Solution: - def numDistinct(self, s: str, t: str) -> int: - n = len(t) - f = [1] + [0] * n - for a in s: - for j in range(n, 0, -1): - if a == t[j - 1]: - f[j] += f[j - 1] - return f[n] -``` - -### **Java** - - - ```java class Solution { public int numDistinct(String s, String t) { @@ -138,27 +116,6 @@ class Solution { } ``` -```java -class Solution { - public int numDistinct(String s, String t) { - int n = t.length(); - int[] f = new int[n + 1]; - f[0] = 1; - for (char a : s.toCharArray()) { - for (int j = n; j > 0; --j) { - char b = t.charAt(j - 1); - if (a == b) { - f[j] += f[j - 1]; - } - } - } - return f[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -182,29 +139,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numDistinct(string s, string t) { - int n = t.size(); - unsigned long long f[n + 1]; - memset(f, 0, sizeof(f)); - f[0] = 1; - for (char& a : s) { - for (int j = n; j; --j) { - char b = t[j - 1]; - if (a == b) { - f[j] += f[j - 1]; - } - } - } - return f[n]; - } -}; -``` - -### **Go** - ```go func numDistinct(s string, t string) int { m, n := len(s), len(t) @@ -227,24 +161,6 @@ func numDistinct(s string, t string) int { } ``` -```go -func numDistinct(s string, t string) int { - n := len(t) - f := make([]int, n+1) - f[0] = 1 - for _, a := range s { - for j := n; j > 0; j-- { - if b := t[j-1]; byte(a) == b { - f[j] += f[j-1] - } - } - } - return f[n] -} -``` - -### **TypeScript** - ```ts function numDistinct(s: string, t: string): number { const m = s.length; @@ -265,6 +181,80 @@ function numDistinct(s: string, t: string): number { } ``` + + +### 方法二 + + + +```python +class Solution: + def numDistinct(self, s: str, t: str) -> int: + n = len(t) + f = [1] + [0] * n + for a in s: + for j in range(n, 0, -1): + if a == t[j - 1]: + f[j] += f[j - 1] + return f[n] +``` + +```java +class Solution { + public int numDistinct(String s, String t) { + int n = t.length(); + int[] f = new int[n + 1]; + f[0] = 1; + for (char a : s.toCharArray()) { + for (int j = n; j > 0; --j) { + char b = t.charAt(j - 1); + if (a == b) { + f[j] += f[j - 1]; + } + } + } + return f[n]; + } +} +``` + +```cpp +class Solution { +public: + int numDistinct(string s, string t) { + int n = t.size(); + unsigned long long f[n + 1]; + memset(f, 0, sizeof(f)); + f[0] = 1; + for (char& a : s) { + for (int j = n; j; --j) { + char b = t[j - 1]; + if (a == b) { + f[j] += f[j - 1]; + } + } + } + return f[n]; + } +}; +``` + +```go +func numDistinct(s string, t string) int { + n := len(t) + f := make([]int, n+1) + f[0] = 1 + for _, a := range s { + for j := n; j > 0; j-- { + if b := t[j-1]; byte(a) == b { + f[j] += f[j-1] + } + } + } + return f[n] +} +``` + ```ts function numDistinct(s: string, t: string): number { const n = t.length; @@ -282,10 +272,6 @@ function numDistinct(s: string, t: string): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/README.md" index 4a002ee116970..a608be1916cda 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 098. \350\267\257\345\276\204\347\232\204\346\225\260\347\233\256/README.md" @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示从左上角走到 $(i, j)$ 的路径数量,初始时 $f[0][0] = 1$,答案为 $f[m - 1][n - 1]$。 @@ -88,10 +86,6 @@ $$ -### **Python3** - - - ```python class Solution: def uniquePaths(self, m: int, n: int) -> int: @@ -106,30 +100,6 @@ class Solution: return f[-1][-1] ``` -```python -class Solution: - def uniquePaths(self, m: int, n: int) -> int: - f = [[1] * n for _ in range(m)] - for i in range(1, m): - for j in range(1, n): - f[i][j] = f[i - 1][j] + f[i][j - 1] - return f[-1][-1] -``` - -```python -class Solution: - def uniquePaths(self, m: int, n: int) -> int: - f = [1] * n - for _ in range(1, m): - for j in range(1, n): - f[j] += f[j - 1] - return f[-1] -``` - -### **Java** - - - ```java class Solution { public int uniquePaths(int m, int n) { @@ -150,40 +120,6 @@ class Solution { } ``` -```java -class Solution { - public int uniquePaths(int m, int n) { - var f = new int[m][n]; - for (var g : f) { - Arrays.fill(g, 1); - } - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; j++) { - f[i][j] = f[i - 1][j] + f[i][j - 1]; - } - } - return f[m - 1][n - 1]; - } -} -``` - -```java -class Solution { - public int uniquePaths(int m, int n) { - int[] f = new int[n]; - Arrays.fill(f, 1); - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[j] += f[j - 1]; - } - } - return f[n - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -205,38 +141,6 @@ public: }; ``` -```cpp -class Solution { -public: - int uniquePaths(int m, int n) { - vector> f(m, vector(n, 1)); - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[i][j] = f[i - 1][j] + f[i][j - 1]; - } - } - return f[m - 1][n - 1]; - } -}; -``` - -```cpp -class Solution { -public: - int uniquePaths(int m, int n) { - vector f(n, 1); - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[j] += f[j - 1]; - } - } - return f[n - 1]; - } -}; -``` - -### **Go** - ```go func uniquePaths(m int, n int) int { f := make([][]int, m) @@ -258,41 +162,6 @@ func uniquePaths(m int, n int) int { } ``` -```go -func uniquePaths(m int, n int) int { - f := make([][]int, m) - for i := range f { - f[i] = make([]int, n) - for j := range f[i] { - f[i][j] = 1 - } - } - for i := 1; i < m; i++ { - for j := 1; j < n; j++ { - f[i][j] = f[i-1][j] + f[i][j-1] - } - } - return f[m-1][n-1] -} -``` - -```go -func uniquePaths(m int, n int) int { - f := make([]int, n+1) - for i := range f { - f[i] = 1 - } - for i := 1; i < m; i++ { - for j := 1; j < n; j++ { - f[j] += f[j-1] - } - } - return f[n-1] -} -``` - -### **TypeScript** - ```ts function uniquePaths(m: number, n: number): number { const f: number[][] = Array(m) @@ -313,34 +182,21 @@ function uniquePaths(m: number, n: number): number { } ``` -```ts -function uniquePaths(m: number, n: number): number { - const f: number[][] = Array(m) - .fill(0) - .map(() => Array(n).fill(1)); - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { - f[i][j] = f[i - 1][j] + f[i][j - 1]; - } - } - return f[m - 1][n - 1]; -} -``` - -```ts -function uniquePaths(m: number, n: number): number { - const f: number[] = Array(n).fill(1); - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { - f[j] += f[j - 1]; +```rust +impl Solution { + pub fn unique_paths(m: i32, n: i32) -> i32 { + let (m, n) = (m as usize, n as usize); + let mut f = vec![1; n]; + for i in 1..m { + for j in 1..n { + f[j] += f[j - 1]; + } } + f[n - 1] } - return f[n - 1]; } ``` -### **JavaScript** - ```js /** * @param {number} m @@ -366,14 +222,75 @@ var uniquePaths = function (m, n) { }; ``` -```js -/** - * @param {number} m - * @param {number} n - * @return {number} - */ -var uniquePaths = function (m, n) { - const f = Array(m) + + +### 方法二 + + + +```python +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + f = [[1] * n for _ in range(m)] + for i in range(1, m): + for j in range(1, n): + f[i][j] = f[i - 1][j] + f[i][j - 1] + return f[-1][-1] +``` + +```java +class Solution { + public int uniquePaths(int m, int n) { + var f = new int[m][n]; + for (var g : f) { + Arrays.fill(g, 1); + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; j++) { + f[i][j] = f[i - 1][j] + f[i][j - 1]; + } + } + return f[m - 1][n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int uniquePaths(int m, int n) { + vector> f(m, vector(n, 1)); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[i][j] = f[i - 1][j] + f[i][j - 1]; + } + } + return f[m - 1][n - 1]; + } +}; +``` + +```go +func uniquePaths(m int, n int) int { + f := make([][]int, m) + for i := range f { + f[i] = make([]int, n) + for j := range f[i] { + f[i][j] = 1 + } + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + f[i][j] = f[i-1][j] + f[i][j-1] + } + } + return f[m-1][n-1] +} +``` + +```ts +function uniquePaths(m: number, n: number): number { + const f: number[][] = Array(m) .fill(0) .map(() => Array(n).fill(1)); for (let i = 1; i < m; ++i) { @@ -382,7 +299,7 @@ var uniquePaths = function (m, n) { } } return f[m - 1][n - 1]; -}; +} ``` ```js @@ -392,37 +309,108 @@ var uniquePaths = function (m, n) { * @return {number} */ var uniquePaths = function (m, n) { - const f = Array(n).fill(1); + const f = Array(m) + .fill(0) + .map(() => Array(n).fill(1)); for (let i = 1; i < m; ++i) { for (let j = 1; j < n; ++j) { - f[j] += f[j - 1]; + f[i][j] = f[i - 1][j] + f[i][j - 1]; } } - return f[n - 1]; + return f[m - 1][n - 1]; }; ``` -### **Rust** + -```rust -impl Solution { - pub fn unique_paths(m: i32, n: i32) -> i32 { - let (m, n) = (m as usize, n as usize); - let mut f = vec![1; n]; - for i in 1..m { - for j in 1..n { +### 方法三 + + + +```python +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + f = [1] * n + for _ in range(1, m): + for j in range(1, n): + f[j] += f[j - 1] + return f[-1] +``` + +```java +class Solution { + public int uniquePaths(int m, int n) { + int[] f = new int[n]; + Arrays.fill(f, 1); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { f[j] += f[j - 1]; } } - f[n - 1] + return f[n - 1]; } } ``` -### **...** +```cpp +class Solution { +public: + int uniquePaths(int m, int n) { + vector f(n, 1); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; + } +}; +``` +```go +func uniquePaths(m int, n int) int { + f := make([]int, n+1) + for i := range f { + f[i] = 1 + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + f[j] += f[j-1] + } + } + return f[n-1] +} +``` + +```ts +function uniquePaths(m: number, n: number): number { + const f: number[] = Array(n).fill(1); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; +} ``` +```js +/** + * @param {number} m + * @param {number} n + * @return {number} + */ +var uniquePaths = function (m, n) { + const f = Array(n).fill(1); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; +}; ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 099. \346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 099. \346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/README.md" index 8efb202dfa792..13a15686ad1be 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 099. \346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 099. \346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/README.md" @@ -44,18 +44,10 @@ ## 解法 - - -动态规划。假设 `dp[i][j]` 表示到达网格 `(i,j)` 的最小数字和,先初始化 dp 第一列和第一行的所有值,然后利用递推公式:`dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]` 求得 dp。 - -最后返回 `dp[m - 1][n - 1]` 即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def minPathSum(self, grid: List[List[int]]) -> int: @@ -71,10 +63,6 @@ class Solution: return dp[-1][-1] ``` -### **Java** - - - ```java class Solution { public int minPathSum(int[][] grid) { @@ -97,33 +85,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minPathSum(grid: number[][]): number { - let m = grid.length, - n = grid[0].length; - let dp = Array.from({ length: m }, v => new Array(n).fill(0)); - dp[0][0] = grid[0][0]; - for (let i = 1; i < m; ++i) { - dp[i][0] = dp[i - 1][0] + grid[i][0]; - } - for (let j = 1; j < n; ++j) { - dp[0][j] = dp[0][j - 1] + grid[0][j]; - } - // dp - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { - let cur = grid[i][j]; - dp[i][j] = cur + Math.min(dp[i - 1][j], dp[i][j - 1]); - } - } - return dp[m - 1][n - 1]; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -146,8 +107,6 @@ public: }; ``` -### **Go** - ```go func minPathSum(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -171,7 +130,28 @@ func minPathSum(grid [][]int) int { } ``` -### **C#** +```ts +function minPathSum(grid: number[][]): number { + let m = grid.length, + n = grid[0].length; + let dp = Array.from({ length: m }, v => new Array(n).fill(0)); + dp[0][0] = grid[0][0]; + for (let i = 1; i < m; ++i) { + dp[i][0] = dp[i - 1][0] + grid[i][0]; + } + for (let j = 1; j < n; ++j) { + dp[0][j] = dp[0][j - 1] + grid[0][j]; + } + // dp + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + let cur = grid[i][j]; + dp[i][j] = cur + Math.min(dp[i - 1][j], dp[i][j - 1]); + } + } + return dp[m - 1][n - 1]; +} +``` ```cs public class Solution { @@ -199,10 +179,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/README.md" index eee5e2c099fd5..9f3517e52733d 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 100. \344\270\211\350\247\222\345\275\242\344\270\255\346\234\200\345\260\217\350\267\257\345\276\204\344\271\213\345\222\214/README.md" @@ -55,16 +55,10 @@ ## 解法 - - -动态规划。自底向上。 +### 方法一 -### **Python3** - - - ```python class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: @@ -76,23 +70,6 @@ class Solution: return dp[0][0] ``` -空间优化: - -```python -class Solution: - def minimumTotal(self, triangle: List[List[int]]) -> int: - n = len(triangle) - dp = [0] * (n + 1) - for i in range(n - 1, -1, -1): - for j in range(i + 1): - dp[j] = min(dp[j], dp[j + 1]) + triangle[i][j] - return dp[0] -``` - -### **Java** - - - ```java class Solution { @@ -109,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +100,6 @@ public: }; ``` -### **Go** - ```go func minimumTotal(triangle [][]int) int { n := len(triangle) @@ -140,10 +113,23 @@ func minimumTotal(triangle [][]int) int { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + n = len(triangle) + dp = [0] * (n + 1) + for i in range(n - 1, -1, -1): + for j in range(i + 1): + dp[j] = min(dp[j], dp[j + 1]) + triangle[i][j] + return dp[0] ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/README.md" index 3219017caf5e5..ec759f2e777eb 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 101. \345\210\206\345\211\262\347\255\211\345\222\214\345\255\220\344\270\262/README.md" @@ -40,18 +40,10 @@ ## 解法 - - -题目可以转换为 `0-1` 背包问题,在 m 个数字中选出一些数字(每个数字只能使用一次),这些数字之和恰好等于 `s / 2`(s 表示所有数字之和)。 - -也可以用 DFS + 记忆化搜索。 +### 方法一 -### **Python3** - - - ```python class Solution: def canPartition(self, nums: List[int]) -> bool: @@ -74,53 +66,6 @@ class Solution: return dp[-1][-1] ``` -空间优化: - -```python -class Solution: - def canPartition(self, nums: List[int]) -> bool: - s = sum(nums) - if s % 2 != 0: - return False - - m, n = len(nums), (s >> 1) + 1 - dp = [False] * n - dp[0] = True - if nums[0] < n: - dp[nums[0]] = True - - for i in range(1, m): - for j in range(n - 1, nums[i] - 1, -1): - dp[j] = dp[j] or dp[j - nums[i]] - return dp[-1] -``` - -DFS + 记忆化搜索: - -```python -class Solution: - def canPartition(self, nums: List[int]) -> bool: - s = sum(nums) - if s % 2 != 0: - return False - target = s >> 1 - - @cache - def dfs(i, s): - nonlocal target - if s > target or i >= len(nums): - return False - if s == target: - return True - return dfs(i + 1, s) or dfs(i + 1, s + nums[i]) - - return dfs(0, 0) -``` - -### **Java** - - - ```java class Solution { public boolean canPartition(int[] nums) { @@ -147,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +113,6 @@ public: }; ``` -### **Go** - ```go func canPartition(nums []int) bool { s := 0 @@ -196,10 +137,57 @@ func canPartition(nums []int) bool { } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def canPartition(self, nums: List[int]) -> bool: + s = sum(nums) + if s % 2 != 0: + return False + + m, n = len(nums), (s >> 1) + 1 + dp = [False] * n + dp[0] = True + if nums[0] < n: + dp[nums[0]] = True + for i in range(1, m): + for j in range(n - 1, nums[i] - 1, -1): + dp[j] = dp[j] or dp[j - nums[i]] + return dp[-1] ``` + + +### 方法三 + + + +```python +class Solution: + def canPartition(self, nums: List[int]) -> bool: + s = sum(nums) + if s % 2 != 0: + return False + target = s >> 1 + + @cache + def dfs(i, s): + nonlocal target + if s > target or i >= len(nums): + return False + if s == target: + return True + return dfs(i + 1, s) or dfs(i + 1, s + nums[i]) + + return dfs(0, 0) ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/README.md" index d179c8b73a4cf..0216e36484380 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 102. \345\212\240\345\207\217\347\232\204\347\233\256\346\240\207\345\200\274/README.md" @@ -53,18 +53,10 @@ ## 解法 - - -题目可以转换为 `0-1` 背包问题,只不过下标可能会出现负数,需要特殊处理。 - -也可以用 DFS 记忆化搜索。 +### 方法一 -### **Python3** - -**0-1 背包** - ```python class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: @@ -82,65 +74,6 @@ class Solution: return dp[n - 1][target + 1000] ``` -设:添加 `-` 号的元素之和为 `x`,则添加 `+` 号的元素之和为 `s - x`,`s - x - x = target`,`2x = s - target`。需要满足 `s - target` 一定大于等于 0,并且能够被 2 整除。 - -```python -class Solution: - def findTargetSumWays(self, nums: List[int], target: int) -> int: - s = sum(nums) - if s - target < 0 or (s - target) % 2 != 0: - return 0 - target = (s - target) // 2 + 1 - n = len(nums) + 1 - dp = [[0] * target for _ in range(n)] - dp[0][0] = 1 - for i in range(1, n): - for j in range(target): - dp[i][j] = dp[i - 1][j] - if nums[i - 1] <= j: - dp[i][j] += dp[i - 1][j - nums[i - 1]] - return dp[-1][-1] -``` - -空间优化: - -```python -class Solution: - def findTargetSumWays(self, nums: List[int], target: int) -> int: - s = sum(nums) - if s - target < 0 or (s - target) % 2 != 0: - return 0 - target = (s - target) // 2 + 1 - n = len(nums) + 1 - dp = [0] * target - dp[0] = 1 - for i in range(1, n): - for j in range(target - 1, nums[i - 1] - 1, -1): - dp[j] += dp[j - nums[i - 1]] - return dp[-1] -``` - -**DFS** - -```python -class Solution: - def findTargetSumWays(self, nums: List[int], target: int) -> int: - @cache - def dfs(i, t): - if i == n: - if t == target: - return 1 - return 0 - return dfs(i + 1, t + nums[i]) + dfs(i + 1, t - nums[i]) - - ans, n = 0, len(nums) - return dfs(0, 0) -``` - -### **Java** - - - ```java class Solution { public int findTargetSumWays(int[] nums, int target) { @@ -167,35 +100,6 @@ class Solution { } ``` -空间优化: - -```java -class Solution { - public int findTargetSumWays(int[] nums, int target) { - int s = 0; - for (int x : nums) { - s += x; - } - if (s - target < 0 || (s - target) % 2 != 0) { - return 0; - } - target = (s - target) / 2 + 1; - int[] dp = new int[target]; - dp[0] = 1; - for (int i = 1; i < nums.length + 1; ++i) { - for (int j = target - 1; j >= nums[i - 1]; --j) { - dp[j] += dp[j - nums[i - 1]]; - } - } - return dp[target - 1]; - } -} -``` - -### **C++** - -空间优化: - ```cpp class Solution { public: @@ -216,10 +120,6 @@ public: }; ``` -### **Go** - - - ```go func findTargetSumWays(nums []int, target int) int { if target < -1000 || target > 1000 { @@ -244,7 +144,52 @@ func findTargetSumWays(nums []int, target int) int { } ``` -空间优化: + + +### 方法二 + + + +```python +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + s = sum(nums) + if s - target < 0 or (s - target) % 2 != 0: + return 0 + target = (s - target) // 2 + 1 + n = len(nums) + 1 + dp = [[0] * target for _ in range(n)] + dp[0][0] = 1 + for i in range(1, n): + for j in range(target): + dp[i][j] = dp[i - 1][j] + if nums[i - 1] <= j: + dp[i][j] += dp[i - 1][j - nums[i - 1]] + return dp[-1][-1] +``` + +```java +class Solution { + public int findTargetSumWays(int[] nums, int target) { + int s = 0; + for (int x : nums) { + s += x; + } + if (s - target < 0 || (s - target) % 2 != 0) { + return 0; + } + target = (s - target) / 2 + 1; + int[] dp = new int[target]; + dp[0] = 1; + for (int i = 1; i < nums.length + 1; ++i) { + for (int j = target - 1; j >= nums[i - 1]; --j) { + dp[j] += dp[j - nums[i - 1]]; + } + } + return dp[target - 1]; + } +} +``` ```go func findTargetSumWays(nums []int, target int) int { @@ -267,10 +212,49 @@ func findTargetSumWays(nums []int, target int) int { } ``` -### **...** + +### 方法三 + + + +```python +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + s = sum(nums) + if s - target < 0 or (s - target) % 2 != 0: + return 0 + target = (s - target) // 2 + 1 + n = len(nums) + 1 + dp = [0] * target + dp[0] = 1 + for i in range(1, n): + for j in range(target - 1, nums[i - 1] - 1, -1): + dp[j] += dp[j - nums[i - 1]] + return dp[-1] ``` + + +### 方法四 + + + +```python +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + @cache + def dfs(i, t): + if i == n: + if t == target: + return 1 + return 0 + return dfs(i + 1, t + nums[i]) + dfs(i + 1, t - nums[i]) + + ans, n = 0, len(nums) + return dfs(0, 0) ``` + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 103. \346\234\200\345\260\221\347\232\204\347\241\254\345\270\201\346\225\260\347\233\256/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 103. \346\234\200\345\260\221\347\232\204\347\241\254\345\270\201\346\225\260\347\233\256/README.md" index 0283693d9cd83..e894525ea4f43 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 103. \346\234\200\345\260\221\347\232\204\347\241\254\345\270\201\346\225\260\347\233\256/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 103. \346\234\200\345\260\221\347\232\204\347\241\254\345\270\201\346\225\260\347\233\256/README.md" @@ -60,18 +60,10 @@ ## 解法 - - -动态规划。 - -类似完全背包的思路,硬币数量不限,求凑成总金额所需的最少的硬币个数。 +### 方法一 -### **Python3** - - - ```python class Solution: def coinChange(self, coins: List[int], amount: int) -> int: @@ -83,10 +75,6 @@ class Solution: return -1 if dp[-1] > amount else dp[-1] ``` -### **Java** - - - ```java class Solution { @@ -110,14 +98,61 @@ class Solution { } ``` -下面对 k 这层循环进行优化: +```cpp +class Solution { +public: + int coinChange(vector& coins, int amount) { + vector dp(amount + 1, amount + 1); + dp[0] = 0; + for (auto& coin : coins) + for (int j = coin; j <= amount; ++j) + dp[j] = min(dp[j], dp[j - coin] + 1); + return dp[amount] > amount ? -1 : dp[amount]; + } +}; +``` + +```go +func coinChange(coins []int, amount int) int { + dp := make([]int, amount+1) + for i := 1; i <= amount; i++ { + dp[i] = amount + 1 + } + for _, coin := range coins { + for j := coin; j <= amount; j++ { + dp[j] = min(dp[j], dp[j-coin]+1) + } + } + if dp[amount] > amount { + return -1 + } + return dp[amount] +} +``` + +```js +/** + * @param {number[]} coins + * @param {number} amount + * @return {number} + */ +var coinChange = function (coins, amount) { + let dp = Array(amount + 1).fill(amount + 1); + dp[0] = 0; + for (const coin of coins) { + for (let j = coin; j <= amount; ++j) { + dp[j] = Math.min(dp[j], dp[j - coin] + 1); + } + } + return dp[amount] > amount ? -1 : dp[amount]; +}; +``` -由于: + -- `dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - v] + 1, dp[i - 1][j - 2v] + 2, ... , dp[i - 1][j - kv] + k)` -- `dp[i][j - v] = min( dp[i - 1][j - v], dp[i - 1][j - 2v] + 1, ... , dp[i - 1][j - kv] + k - 1)` +### 方法二 -因此 `dp[i][j] = min(dp[i - 1][j], dp[i][j - v] + 1)`。 + ```java class Solution { @@ -143,7 +178,11 @@ class Solution { } ``` -空间优化: + + +### 方法三 + + ```java class Solution { @@ -162,60 +201,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} coins - * @param {number} amount - * @return {number} - */ -var coinChange = function (coins, amount) { - let dp = Array(amount + 1).fill(amount + 1); - dp[0] = 0; - for (const coin of coins) { - for (let j = coin; j <= amount; ++j) { - dp[j] = Math.min(dp[j], dp[j - coin] + 1); - } - } - return dp[amount] > amount ? -1 : dp[amount]; -}; -``` - -### **C++** - -```cpp -class Solution { -public: - int coinChange(vector& coins, int amount) { - vector dp(amount + 1, amount + 1); - dp[0] = 0; - for (auto& coin : coins) - for (int j = coin; j <= amount; ++j) - dp[j] = min(dp[j], dp[j - coin] + 1); - return dp[amount] > amount ? -1 : dp[amount]; - } -}; -``` - -### **Go** - -```go -func coinChange(coins []int, amount int) int { - dp := make([]int, amount+1) - for i := 1; i <= amount; i++ { - dp[i] = amount + 1 - } - for _, coin := range coins { - for j := coin; j <= amount; j++ { - dp[j] = min(dp[j], dp[j-coin]+1) - } - } - if dp[amount] > amount { - return -1 - } - return dp[amount] -} -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 104. \346\216\222\345\210\227\347\232\204\346\225\260\347\233\256/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 104. \346\216\222\345\210\227\347\232\204\346\225\260\347\233\256/README.md" index 44be00d8b56c3..1f8e98547bfe8 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 104. \346\216\222\345\210\227\347\232\204\346\225\260\347\233\256/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 104. \346\216\222\345\210\227\347\232\204\346\225\260\347\233\256/README.md" @@ -55,16 +55,10 @@ ## 解法 - - -简单动态规划,`dp[i]` 表示总和为 `i` 的元素组合的个数。 +### 方法一 -### **Python3** - - - ```python class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: @@ -77,10 +71,6 @@ class Solution: return dp[-1] ``` -### **Java** - - - ```java class Solution { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func combinationSum4(nums []int, target int) int { dp := make([]int, target+1) @@ -136,10 +122,6 @@ func combinationSum4(nums []int, target int) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/README.md" index b0a437ea829dd..0461ab9f1985a 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 105. \345\262\233\345\261\277\347\232\204\346\234\200\345\244\247\351\235\242\347\247\257/README.md" @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们可以遍历每一个格子 $(i, j)$,从每个格子开始进行深度优先搜索,如果搜索到的格子是陆地,就将当前格子标记为已访问,并且继续搜索上、下、左、右四个方向的格子。搜索结束后,计算标记的陆地的数量,即为岛屿的面积。我们找出最大的岛屿面积即为答案。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: @@ -77,10 +71,6 @@ class Solution: return max(dfs(i, j) for i in range(m) for j in range(n)) ``` -### **Java** - - - ```java class Solution { private int m; @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go func maxAreaOfIsland(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -181,8 +167,6 @@ func maxAreaOfIsland(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function maxAreaOfIsland(grid: number[][]): number { const m = grid.length; @@ -212,8 +196,6 @@ function maxAreaOfIsland(grid: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { fn dfs(grid: &mut Vec>, i: usize, j: usize) -> i32 { @@ -245,10 +227,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 106. \344\272\214\345\210\206\345\233\276/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 106. \344\272\214\345\210\206\345\233\276/README.md" index 160b171972979..61898eb99bfb7 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 106. \344\272\214\345\210\206\345\233\276/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 106. \344\272\214\345\210\206\345\233\276/README.md" @@ -59,83 +59,10 @@ ## 解法 - - -并查集。 - -并查集模板: - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` - -对于本题,如果是二分图,那么图中每个顶点的所有邻接点都应该属于同一集合,且不与顶点处于同一集合,因此我们可以使用并查集。遍历图中每个顶点,如果发现存在当前顶点与对应的邻接点处于同一个集合,说明不是二分图。否则将当前节点的邻接点相互进行合并。 +### 方法一 -### **Python3** - - - ```python class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: @@ -154,10 +81,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -189,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -217,8 +138,6 @@ public: }; ``` -### **Go** - ```go func isBipartite(graph [][]int) bool { n := len(graph) @@ -245,10 +164,6 @@ func isBipartite(graph [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 107. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\235\347\246\273/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 107. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\235\347\246\273/README.md" index 098edccd6cda8..0248310483007 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 107. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\235\347\246\273/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 107. \347\237\251\351\230\265\344\270\255\347\232\204\350\267\235\347\246\273/README.md" @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:多源 BFS** +### 方法一:多源 BFS 初始化结果矩阵 ans,所有 0 的距离为 0,所以 1 的距离为 -1。初始化队列 q 存储 BFS 需要检查的位置,并将所有 0 的位置入队。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func updateMatrix(mat [][]int) [][]int { m, n := len(mat), len(mat[0]) @@ -195,10 +181,6 @@ func updateMatrix(mat [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 108. \345\215\225\350\257\215\346\274\224\345\217\230/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 108. \345\215\225\350\257\215\346\274\224\345\217\230/README.md" index 16a57fc931819..3484cf4ec1811 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 108. \345\215\225\350\257\215\346\274\224\345\217\230/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 108. \345\215\225\350\257\215\346\274\224\345\217\230/README.md" @@ -52,16 +52,10 @@ ## 解法 - - -BFS。 +### 方法一 -### **Python3** - - - ```python class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: @@ -89,10 +83,6 @@ class Solution: return 0 ``` -### **Java** - - - ```java class Solution { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go func ladderLength(beginWord string, endWord string, wordList []string) int { words := make(map[string]bool) @@ -199,10 +185,6 @@ func ladderLength(beginWord string, endWord string, wordList []string) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 109. \345\274\200\345\257\206\347\240\201\351\224\201/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 109. \345\274\200\345\257\206\347\240\201\351\224\201/README.md" index 407a770059ebe..b434f24e2e261 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 109. \345\274\200\345\257\206\347\240\201\351\224\201/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 109. \345\274\200\345\257\206\347\240\201\351\224\201/README.md" @@ -67,14 +67,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def openLock(self, deadends: List[str], target: str) -> int: @@ -116,10 +112,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int openLock(String[] deadends, String target) { @@ -177,8 +169,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -229,10 +219,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 110. \346\211\200\346\234\211\350\267\257\345\276\204/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 110. \346\211\200\346\234\211\350\267\257\345\276\204/README.md" index c2eb3086eb312..2ae91518b19ee 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 110. \346\211\200\346\234\211\350\267\257\345\276\204/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 110. \346\211\200\346\234\211\350\267\257\345\276\204/README.md" @@ -68,16 +68,10 @@ ## 解法 - - -DFS。 +### 方法一 -### **Python3** - - - ```python class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: @@ -96,10 +90,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List> ans; @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func allPathsSourceTarget(graph [][]int) [][]int { var path []int @@ -184,10 +170,6 @@ func allPathsSourceTarget(graph [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 111. \350\256\241\347\256\227\351\231\244\346\263\225/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 111. \350\256\241\347\256\227\351\231\244\346\263\225/README.md" index c1ab496205089..e28b1e7370009 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 111. \350\256\241\347\256\227\351\231\244\346\263\225/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 111. \350\256\241\347\256\227\351\231\244\346\263\225/README.md" @@ -61,81 +61,10 @@ ## 解法 - - -并查集。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` - -对于本题,具备等式关系的所有变量构成同一个集合,同时,需要维护一个权重数组 w,初始时 `w[i] = 1`。对于等式关系如 `a / b = 2`,令 `w[a] = 2`。在 `find()` 查找祖宗节点的时候,同时进行路径压缩,并更新节点权重。 +### 方法一 -### **Python3** - - - ```python class Solution: def calcEquation( @@ -179,10 +108,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -241,8 +166,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -292,8 +215,6 @@ public: }; ``` -### **Go** - ```go var p []int var w []float64 @@ -352,10 +273,6 @@ func find(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 112. \346\234\200\351\225\277\351\200\222\345\242\236\350\267\257\345\276\204/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 112. \346\234\200\351\225\277\351\200\222\345\242\236\350\267\257\345\276\204/README.md" index e0457d3a68ebb..266fb372b14ad 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 112. \346\234\200\351\225\277\351\200\222\345\242\236\350\267\257\345\276\204/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 112. \346\234\200\351\225\277\351\200\222\345\242\236\350\267\257\345\276\204/README.md" @@ -53,16 +53,10 @@ ## 解法 - - -记忆化搜索。 +### 方法一 -### **Python3** - - - ```python class Solution: def longestIncreasingPath(self, matrix: List[List[int]]) -> int: @@ -79,10 +73,6 @@ class Solution: return max(dfs(i, j) for i in range(m) for j in range(n)) ``` -### **Java** - - - ```java class Solution { private int[][] memo; @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go func longestIncreasingPath(matrix [][]int) int { m, n := len(matrix), len(matrix[0]) @@ -200,10 +186,6 @@ func longestIncreasingPath(matrix [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 113. \350\257\276\347\250\213\351\241\272\345\272\217/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 113. \350\257\276\347\250\213\351\241\272\345\272\217/README.md" index 9ddf016325ea2..c622ce03447e1 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 113. \350\257\276\347\250\213\351\241\272\345\272\217/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 113. \350\257\276\347\250\213\351\241\272\345\272\217/README.md" @@ -56,16 +56,10 @@ ## 解法 - - -拓扑排序,BFS 实现。 +### 方法一 -### **Python3** - - - ```python class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: @@ -86,10 +80,6 @@ class Solution: return ans if len(ans) == numCourses else [] ``` -### **Java** - - - ```java class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { @@ -123,38 +113,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function findOrder(numCourses: number, prerequisites: number[][]): number[] { - let g = Array.from({ length: numCourses }, () => []); - let indeg = new Array(numCourses).fill(0); - for (let [a, b] of prerequisites) { - g[b].push(a); - ++indeg[a]; - } - let q = []; - for (let i = 0; i < numCourses; ++i) { - if (!indeg[i]) { - q.push(i); - } - } - let ans = []; - while (q.length) { - const i = q.shift(); - ans.push(i); - for (let j of g[i]) { - if (--indeg[j] == 0) { - q.push(j); - } - } - } - return ans.length == numCourses ? ans : []; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -182,8 +140,6 @@ public: }; ``` -### **Go** - ```go func findOrder(numCourses int, prerequisites [][]int) []int { g := make([][]int, numCourses) @@ -218,7 +174,33 @@ func findOrder(numCourses int, prerequisites [][]int) []int { } ``` -### **C#** +```ts +function findOrder(numCourses: number, prerequisites: number[][]): number[] { + let g = Array.from({ length: numCourses }, () => []); + let indeg = new Array(numCourses).fill(0); + for (let [a, b] of prerequisites) { + g[b].push(a); + ++indeg[a]; + } + let q = []; + for (let i = 0; i < numCourses; ++i) { + if (!indeg[i]) { + q.push(i); + } + } + let ans = []; + while (q.length) { + const i = q.shift(); + ans.push(i); + for (let j of g[i]) { + if (--indeg[j] == 0) { + q.push(j); + } + } + } + return ans.length == numCourses ? ans : []; +} +``` ```cs public class Solution { @@ -256,10 +238,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 114. \345\244\226\346\230\237\346\226\207\345\255\227\345\205\270/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 114. \345\244\226\346\230\237\346\226\207\345\255\227\345\205\270/README.md" index 9e666d7e80529..59b2fa30f2b63 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 114. \345\244\226\346\230\237\346\226\207\345\255\227\345\205\270/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 114. \345\244\226\346\230\237\346\226\207\345\255\227\345\205\270/README.md" @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:拓扑排序 + BFS** +### 方法一:拓扑排序 + BFS 用数组 $g$ 记录在火星字典中的字母先后关系,$g[i][j] = true$ 表示字母 $i + 'a'$ 在字母 $j + 'a'$ 的前面;用数组 $s$ 记录当前字典出现过的字母,$cnt$ 表示出现过的字母数。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def alienOrder(self, words: List[str]) -> str: @@ -140,10 +134,6 @@ class Solution: return '' if len(ans) < cnt else ''.join(ans) ``` -### **Java** - - - ```java class Solution { @@ -221,8 +211,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -282,10 +270,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 115. \351\207\215\345\273\272\345\272\217\345\210\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 115. \351\207\215\345\273\272\345\272\217\345\210\227/README.md" index 0bf5ab2dd301d..ab3d2554490ea 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 115. \351\207\215\345\273\272\345\272\217\345\210\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 115. \351\207\215\345\273\272\345\272\217\345\210\227/README.md" @@ -71,18 +71,12 @@ ## 解法 - - -**方法一:拓扑排序** +### 方法一:拓扑排序 BFS 实现。 -### **Python3** - - - ```python class Solution: def sequenceReconstruction( @@ -106,10 +100,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean sequenceReconstruction(int[] nums, int[][] sequences) { @@ -146,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -177,8 +165,6 @@ public: }; ``` -### **Go** - ```go func sequenceReconstruction(nums []int, sequences [][]int) bool { n := len(nums) @@ -214,10 +200,6 @@ func sequenceReconstruction(nums []int, sequences [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/README.md" index cfac34ea7577b..2da30fa561737 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 116. \346\234\213\345\217\213\345\234\210/README.md" @@ -49,13 +49,119 @@ ## 解法 - - -**方法一:深度优先搜索** +### 方法一:深度优先搜索 判断城市之间是否属于同一个连通分量,最后连通分量的总数即为结果。 -**方法二:并查集** + + +```python +class Solution: + def findCircleNum(self, isConnected: List[List[int]]) -> int: + def dfs(i): + vis[i] = True + for j in range(n): + if not vis[j] and isConnected[i][j]: + dfs(j) + + n = len(isConnected) + vis = [False] * n + ans = 0 + for i in range(n): + if not vis[i]: + dfs(i) + ans += 1 + return ans +``` + +```java +class Solution { + private int[][] isConnected; + private boolean[] vis; + private int n; + + public int findCircleNum(int[][] isConnected) { + n = isConnected.length; + vis = new boolean[n]; + this.isConnected = isConnected; + int ans = 0; + for (int i = 0; i < n; ++i) { + if (!vis[i]) { + dfs(i); + ++ans; + } + } + return ans; + } + + private void dfs(int i) { + vis[i] = true; + for (int j = 0; j < n; ++j) { + if (!vis[j] && isConnected[i][j] == 1) { + dfs(j); + } + } + } +} +``` + +```cpp +class Solution { +public: + vector> isConnected; + vector vis; + int n; + + int findCircleNum(vector>& isConnected) { + n = isConnected.size(); + vis.resize(n); + this->isConnected = isConnected; + int ans = 0; + for (int i = 0; i < n; ++i) { + if (!vis[i]) { + dfs(i); + ++ans; + } + } + return ans; + } + + void dfs(int i) { + vis[i] = true; + for (int j = 0; j < n; ++j) + if (!vis[j] && isConnected[i][j]) + dfs(j); + } +}; +``` + +```go +func findCircleNum(isConnected [][]int) int { + n := len(isConnected) + vis := make([]bool, n) + var dfs func(i int) + dfs = func(i int) { + vis[i] = true + for j := 0; j < n; j++ { + if !vis[j] && isConnected[i][j] == 1 { + dfs(j) + } + } + } + ans := 0 + for i := 0; i < n; i++ { + if !vis[i] { + dfs(i) + ans++ + } + } + return ans +} +``` + + + +### 方法二:并查集 模板 1——朴素并查集: @@ -122,33 +228,6 @@ d[find(a)] = distance -### **Python3** - - - -深度优先搜索: - -```python -class Solution: - def findCircleNum(self, isConnected: List[List[int]]) -> int: - def dfs(i): - vis[i] = True - for j in range(n): - if not vis[j] and isConnected[i][j]: - dfs(j) - - n = len(isConnected) - vis = [False] * n - ans = 0 - for i in range(n): - if not vis[i]: - dfs(i) - ans += 1 - return ans -``` - -并查集: - ```python class Solution: def findCircleNum(self, isConnected: List[List[int]]) -> int: @@ -166,45 +245,6 @@ class Solution: return sum(i == v for i, v in enumerate(p)) ``` -### **Java** - - - -深度优先搜索: - -```java -class Solution { - private int[][] isConnected; - private boolean[] vis; - private int n; - - public int findCircleNum(int[][] isConnected) { - n = isConnected.length; - vis = new boolean[n]; - this.isConnected = isConnected; - int ans = 0; - for (int i = 0; i < n; ++i) { - if (!vis[i]) { - dfs(i); - ++ans; - } - } - return ans; - } - - private void dfs(int i) { - vis[i] = true; - for (int j = 0; j < n; ++j) { - if (!vis[j] && isConnected[i][j] == 1) { - dfs(j); - } - } - } -} -``` - -并查集: - ```java class Solution { private int[] p; @@ -240,42 +280,6 @@ class Solution { } ``` -### **C++** - -深度优先搜索: - -```cpp -class Solution { -public: - vector> isConnected; - vector vis; - int n; - - int findCircleNum(vector>& isConnected) { - n = isConnected.size(); - vis.resize(n); - this->isConnected = isConnected; - int ans = 0; - for (int i = 0; i < n; ++i) { - if (!vis[i]) { - dfs(i); - ++ans; - } - } - return ans; - } - - void dfs(int i) { - vis[i] = true; - for (int j = 0; j < n; ++j) - if (!vis[j] && isConnected[i][j]) - dfs(j); - } -}; -``` - -并查集: - ```cpp class Solution { public: @@ -303,36 +307,6 @@ public: }; ``` -### **Go** - -深度优先搜索: - -```go -func findCircleNum(isConnected [][]int) int { - n := len(isConnected) - vis := make([]bool, n) - var dfs func(i int) - dfs = func(i int) { - vis[i] = true - for j := 0; j < n; j++ { - if !vis[j] && isConnected[i][j] == 1 { - dfs(j) - } - } - } - ans := 0 - for i := 0; i < n; i++ { - if !vis[i] { - dfs(i) - ans++ - } - } - return ans -} -``` - -并查集: - ```go func findCircleNum(isConnected [][]int) int { n := len(isConnected) @@ -364,10 +338,6 @@ func findCircleNum(isConnected [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 117. \347\233\270\344\274\274\347\232\204\345\255\227\347\254\246\344\270\262/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 117. \347\233\270\344\274\274\347\232\204\345\255\227\347\254\246\344\270\262/README.md" index 785f0e868de21..ff4088dcb6a67 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 117. \347\233\270\344\274\274\347\232\204\345\255\227\347\254\246\344\270\262/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 117. \347\233\270\344\274\274\347\232\204\345\255\227\347\254\246\344\270\262/README.md" @@ -47,81 +47,10 @@ ## 解法 - - -并查集模板题。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` - -对于本题,先遍历所有字符串对,判断两字符串是否相似,若相似,则将两字符串合并到同一个集合中,从而形成并查集。最后统计集合的数量即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def numSimilarGroups(self, strs: List[str]) -> int: @@ -139,10 +68,6 @@ class Solution: return sum(i == find(i) for i in range(n)) ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -189,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -226,8 +149,6 @@ public: }; ``` -### **Go** - ```go func numSimilarGroups(strs []string) int { n := len(strs) @@ -268,10 +189,6 @@ func numSimilarGroups(strs []string) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 118. \345\244\232\344\275\231\347\232\204\350\276\271/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 118. \345\244\232\344\275\231\347\232\204\350\276\271/README.md" index eac65c952c226..f069e60fafdad 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 118. \345\244\232\344\275\231\347\232\204\350\276\271/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 118. \345\244\232\344\275\231\347\232\204\350\276\271/README.md" @@ -50,81 +50,10 @@ ## 解法 - - -并查集。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` - -对于本题,先遍历所有的边,如果边的两个节点已经属于同个集合,说明两个节点已经相连,若再将这条件加入集合中,就会出现环,因此可以直接返回这条边。 +### 方法一 -### **Python3** - - - ```python class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: @@ -141,10 +70,6 @@ class Solution: return [] ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -173,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -198,8 +121,6 @@ public: }; ``` -### **Go** - ```go func findRedundantConnection(edges [][]int) []int { p := make([]int, 1010) @@ -224,10 +145,6 @@ func findRedundantConnection(edges [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/README.md" index 363840bb1caee..0e201ba7717fa 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 119. \346\234\200\351\225\277\350\277\236\347\273\255\345\272\217\345\210\227/README.md" @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们先将数组排序,然后用一个变量 $t$ 记录当前连续序列的长度,用一个变量 $ans$ 记录最长连续序列的长度。 @@ -57,18 +55,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组的长度。 -**方法二:哈希表** - -我们用哈希表存储数组中的所有元素,然后遍历数组中的每个元素 $x$,如果当前元素的前驱 $x-1$ 不在哈希表中,那么我们以当前元素为起点,不断尝试匹配 $x+1, x+2, x+3, \dots$,直到匹配不到为止,此时的匹配长度即为以 $x$ 为起点的最长连续序列长度,我们更新答案即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组的长度。 - -### **Python3** - - - ```python class Solution: def longestConsecutive(self, nums: List[int]) -> int: @@ -88,24 +76,6 @@ class Solution: return ans ``` -```python -class Solution: - def longestConsecutive(self, nums: List[int]) -> int: - s = set(nums) - ans = 0 - for x in nums: - if x - 1 not in s: - y = x + 1 - while y in s: - y += 1 - ans = max(ans, y - x) - return ans -``` - -### **Java** - - - ```java class Solution { public int longestConsecutive(int[] nums) { @@ -130,30 +100,6 @@ class Solution { } ``` -```java -class Solution { - public int longestConsecutive(int[] nums) { - Set s = new HashSet<>(); - for (int x : nums) { - s.add(x); - } - int ans = 0; - for (int x : nums) { - if (!s.contains(x - 1)) { - int y = x + 1; - while (s.contains(y)) { - ++y; - } - ans = Math.max(ans, y - x); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -179,28 +125,6 @@ public: }; ``` -```cpp -class Solution { -public: - int longestConsecutive(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - int ans = 0; - for (int x : nums) { - if (!s.count(x - 1)) { - int y = x + 1; - while (s.count(y)) { - y++; - } - ans = max(ans, y - x); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func longestConsecutive(nums []int) int { n := len(nums) @@ -224,40 +148,15 @@ func longestConsecutive(nums []int) int { } ``` -```go -func longestConsecutive(nums []int) (ans int) { - s := map[int]bool{} - for _, x := range nums { - s[x] = true - } - for _, x := range nums { - if !s[x-1] { - y := x + 1 - for s[y] { - y++ - } - ans = max(ans, y-x) - } - } - return -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var longestConsecutive = function (nums) { +```ts +function longestConsecutive(nums: number[]): number { const n = nums.length; if (n < 2) { return n; } - nums.sort((a, b) => a - b); let ans = 1; let t = 1; + nums.sort((a, b) => a - b); for (let i = 1; i < n; ++i) { if (nums[i] === nums[i - 1]) { continue; @@ -269,7 +168,7 @@ var longestConsecutive = function (nums) { } } return ans; -}; +} ``` ```js @@ -278,32 +177,13 @@ var longestConsecutive = function (nums) { * @return {number} */ var longestConsecutive = function (nums) { - const s = new Set(nums); - let ans = 0; - for (const x of nums) { - if (!s.has(x - 1)) { - let y = x + 1; - while (s.has(y)) { - y++; - } - ans = Math.max(ans, y - x); - } - } - return ans; -}; -``` - -### **TypeScript** - -```ts -function longestConsecutive(nums: number[]): number { const n = nums.length; if (n < 2) { return n; } + nums.sort((a, b) => a - b); let ans = 1; let t = 1; - nums.sort((a, b) => a - b); for (let i = 1; i < n; ++i) { if (nums[i] === nums[i - 1]) { continue; @@ -315,6 +195,91 @@ function longestConsecutive(nums: number[]): number { } } return ans; +}; +``` + + + +### 方法二:哈希表 + +我们用哈希表存储数组中的所有元素,然后遍历数组中的每个元素 $x$,如果当前元素的前驱 $x-1$ 不在哈希表中,那么我们以当前元素为起点,不断尝试匹配 $x+1, x+2, x+3, \dots$,直到匹配不到为止,此时的匹配长度即为以 $x$ 为起点的最长连续序列长度,我们更新答案即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组的长度。 + + + +```python +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + s = set(nums) + ans = 0 + for x in nums: + if x - 1 not in s: + y = x + 1 + while y in s: + y += 1 + ans = max(ans, y - x) + return ans +``` + +```java +class Solution { + public int longestConsecutive(int[] nums) { + Set s = new HashSet<>(); + for (int x : nums) { + s.add(x); + } + int ans = 0; + for (int x : nums) { + if (!s.contains(x - 1)) { + int y = x + 1; + while (s.contains(y)) { + ++y; + } + ans = Math.max(ans, y - x); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int longestConsecutive(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + int ans = 0; + for (int x : nums) { + if (!s.count(x - 1)) { + int y = x + 1; + while (s.count(y)) { + y++; + } + ans = max(ans, y - x); + } + } + return ans; + } +}; +``` + +```go +func longestConsecutive(nums []int) (ans int) { + s := map[int]bool{} + for _, x := range nums { + s[x] = true + } + for _, x := range nums { + if !s[x-1] { + y := x + 1 + for s[y] { + y++ + } + ans = max(ans, y-x) + } + } + return } ``` @@ -335,10 +300,27 @@ function longestConsecutive(nums: number[]): number { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function (nums) { + const s = new Set(nums); + let ans = 0; + for (const x of nums) { + if (!s.has(x - 1)) { + let y = x + 1; + while (s.has(y)) { + y++; + } + ans = Math.max(ans, y - x); + } + } + return ans; +}; ``` + + diff --git "a/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/README.md" "b/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/README.md" index eca772d7e2439..4616d29b7e5c0 100644 --- "a/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/README.md" +++ "b/lcp/LCP 01. \347\214\234\346\225\260\345\255\227/README.md" @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:遍历** +### 方法一:遍历 我们同时遍历两个数组,如果对应位置的元素相等,那么答案加一。 @@ -47,20 +45,12 @@ -### **Python3** - - - ```python class Solution: def game(self, guess: List[int], answer: List[int]) -> int: return sum(a == b for a, b in zip(guess, answer)) ``` -### **Java** - - - ```java class Solution { public int game(int[] guess, int[] answer) { @@ -75,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,8 +78,6 @@ public: }; ``` -### **Go** - ```go func game(guess []int, answer []int) (ans int) { for i, a := range guess { @@ -103,8 +89,6 @@ func game(guess []int, answer []int) (ans int) { } ``` -### **TypeScript** - ```ts function game(guess: number[], answer: number[]): number { let ans = 0; @@ -117,14 +101,6 @@ function game(guess: number[], answer: number[]): number { } ``` -```ts -function game(guess: number[], answer: number[]): number { - return guess.reduce((acc, cur, index) => (cur === answer[index] ? acc + 1 : acc), 0); -} -``` - -### **JavaScript** - ```js /** * @param {number[]} guess @@ -142,8 +118,6 @@ var game = function (guess, answer) { }; ``` -### **C** - ```c int game(int* guess, int guessSize, int* answer, int answerSize) { int res = 0; @@ -156,10 +130,18 @@ int game(int* guess, int guessSize, int* answer, int answerSize) { } ``` -### **...** + -``` +### 方法二 + + +```ts +function game(guess: number[], answer: number[]): number { + return guess.reduce((acc, cur, index) => (cur === answer[index] ? acc + 1 : acc), 0); +} ``` + + diff --git "a/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/README.md" "b/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/README.md" index 45dd820b0d381..f1c3761c78fcd 100644 --- "a/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/README.md" +++ "b/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/README.md" @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:DFS + 数学** +### 方法一:DFS + 数学 我们设计一个函数 $dfs(i)$,表示从下标 $i$ 开始到最后一个元素的连分数的值,那么答案就是 $dfs(0)$。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def fraction(self, cont: List[int]) -> List[int]: @@ -77,10 +71,6 @@ class Solution: return dfs(0) ``` -### **Java** - - - ```java class Solution { private int[] cont; @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func fraction(cont []int) []int { var dfs func(i int) []int @@ -146,8 +132,6 @@ func fraction(cont []int) []int { } ``` -### **TypeScript** - ```ts function fraction(cont: number[]): number[] { const dfs = (i: number): number[] => { @@ -166,8 +150,6 @@ function fraction(cont: number[]): number[] { } ``` -### **JavaScript** - ```js /** * @param {number[]} cont @@ -190,10 +172,6 @@ var fraction = function (cont) { }; ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/README.md" "b/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/README.md" index 7fdda37718d7d..b7c5bca446bd3 100644 --- "a/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/README.md" +++ "b/lcp/LCP 03. \346\234\272\345\231\250\344\272\272\345\244\247\345\206\222\351\231\251/README.md" @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们用哈希表 $vis$ 记录机器人在一轮指令执行完毕后所能到达的所有位置。初始时,机器人位于原点 $(0, 0)$,因此 $vis$ 中只包含一个元素 $(0, 0)$。随后我们遍历指令 $command$ 中的每个字符 $c$,更新机器人的位置,加入哈希表 $vis$ 中。记第一轮执行完毕后,机器人所在的位置为 $(i, j)$。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def robot(self, command: str, obstacles: List[List[int]], x: int, y: int) -> bool: @@ -95,10 +89,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean robot(String command, int[][] obstacles, int x, int y) { @@ -131,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -166,8 +154,6 @@ public: }; ``` -### **Go** - ```go func robot(command string, obstacles [][]int, x int, y int) bool { type pair struct{ i, j int } @@ -199,8 +185,6 @@ func robot(command string, obstacles [][]int, x int, y int) bool { } ``` -### **TypeScript** - ```ts function robot(command: string, obstacles: number[][], x: number, y: number): boolean { const f = (i: number, j: number): number => { @@ -234,10 +218,6 @@ function robot(command: string, obstacles: number[][], x: number, y: number): bo } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 04. \350\246\206\347\233\226/README.md" "b/lcp/LCP 04. \350\246\206\347\233\226/README.md" index 4f1b2e0a3c4f2..67017bc18d527 100644 --- "a/lcp/LCP 04. \350\246\206\347\233\226/README.md" +++ "b/lcp/LCP 04. \350\246\206\347\233\226/README.md" @@ -45,30 +45,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 05. \345\217\221 LeetCoin/README.md" "b/lcp/LCP 05. \345\217\221 LeetCoin/README.md" index 771a1e13c206e..094670d6e6f18 100644 --- "a/lcp/LCP 05. \345\217\221 LeetCoin/README.md" +++ "b/lcp/LCP 05. \345\217\221 LeetCoin/README.md" @@ -70,9 +70,7 @@ ## 解法 - - -**方法一:线段树** +### 方法一:线段树 线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。区间修改时,需要使用**懒标记**保证效率。 @@ -83,10 +81,6 @@ -### **Python3** - - - ```python MOD = int(1e9 + 7) @@ -186,10 +180,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Node { Node left; @@ -324,8 +314,6 @@ class Solution { } ``` -### **C++** - ```cpp const int MOD = 1e9 + 7; @@ -444,10 +432,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/README.md" "b/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/README.md" index c1d6e93a234f9..e96313c4bcacc 100644 --- "a/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/README.md" +++ "b/lcp/LCP 06. \346\213\277\347\241\254\345\270\201/README.md" @@ -33,9 +33,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 我们可以发现,每堆力扣币拿完的最少次数,等于该堆力扣币数量除以 $2$ 向上取整的结果之和。 @@ -45,20 +43,12 @@ -### **Python3** - - - ```python class Solution: def minCount(self, coins: List[int]) -> int: return sum((x + 1) >> 1 for x in coins) ``` -### **Java** - - - ```java class Solution { public int minCount(int[] coins) { @@ -71,8 +61,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -86,8 +74,6 @@ public: }; ``` -### **Go** - ```go func minCount(coins []int) (ans int) { for _, x := range coins { @@ -97,8 +83,6 @@ func minCount(coins []int) (ans int) { } ``` -### **TypeScript** - ```ts function minCount(coins: number[]): number { let ans = 0; @@ -109,8 +93,6 @@ function minCount(coins: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_count(coins: Vec) -> i32 { @@ -122,20 +104,6 @@ impl Solution { } ``` -### **C** - -```c -int minCount(int* coins, int coinsSize) { - int ans = 0; - for (int i = 0; i < coinsSize; ++i) { - ans += (coins[i] + 1) >> 1; - } - return ans; -} -``` - -### **PHP** - ```php class Solution { /** @@ -152,10 +120,16 @@ class Solution { } ``` -### **...** - -``` - +```c +int minCount(int* coins, int coinsSize) { + int ans = 0; + for (int i = 0; i < coinsSize; ++i) { + ans += (coins[i] + 1) >> 1; + } + return ans; +} ``` + + diff --git "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/README.md" "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/README.md" index 4832e1bfe824d..932759be206b9 100644 --- "a/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/README.md" +++ "b/lcp/LCP 07. \344\274\240\351\200\222\344\277\241\346\201\257/README.md" @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示经过 $i$ 轮传递到编号 $j$ 的方案数,那么最终答案即为 $f[k][n-1]$。初始时 $f[0][0]=1$,其余均为 $0$。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def numWays(self, n: int, relation: List[List[int]], k: int) -> int: @@ -76,22 +70,6 @@ class Solution: return f[-1][-1] ``` -```python -class Solution: - def numWays(self, n: int, relation: List[List[int]], k: int) -> int: - f = [1] + [0] * (n - 1) - for _ in range(k): - g = [0] * n - for a, b in relation: - g[b] += f[a] - f = g - return f[-1] -``` - -### **Java** - - - ```java class Solution { public int numWays(int n, int[][] relation, int k) { @@ -108,26 +86,6 @@ class Solution { } ``` -```java -class Solution { - public int numWays(int n, int[][] relation, int k) { - int[] f = new int[n]; - f[0] = 1; - while (k-- > 0) { - int[] g = new int[n]; - for (int[] r : relation) { - int a = r[0], b = r[1]; - g[b] += f[a]; - } - f = g; - } - return f[n - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -146,6 +104,72 @@ public: }; ``` +```go +func numWays(n int, relation [][]int, k int) int { + f := make([][]int, k+1) + for i := range f { + f[i] = make([]int, n) + } + f[0][0] = 1 + for i := 1; i <= k; i++ { + for _, r := range relation { + a, b := r[0], r[1] + f[i][b] += f[i-1][a] + } + } + return f[k][n-1] +} +``` + +```ts +function numWays(n: number, relation: number[][], k: number): number { + const f: number[][] = new Array(k + 1).fill(0).map(() => new Array(n).fill(0)); + f[0][0] = 1; + for (let i = 1; i <= k; ++i) { + for (const [a, b] of relation) { + f[i][b] += f[i - 1][a]; + } + } + return f[k][n - 1]; +} +``` + + + +### 方法二 + + + +```python +class Solution: + def numWays(self, n: int, relation: List[List[int]], k: int) -> int: + f = [1] + [0] * (n - 1) + for _ in range(k): + g = [0] * n + for a, b in relation: + g[b] += f[a] + f = g + return f[-1] +``` + +```java +class Solution { + public int numWays(int n, int[][] relation, int k) { + int[] f = new int[n]; + f[0] = 1; + while (k-- > 0) { + int[] g = new int[n]; + for (int[] r : relation) { + int a = r[0], b = r[1]; + g[b] += f[a]; + } + f = g; + } + return f[n - 1]; + } +} +``` + ```cpp class Solution { public: @@ -165,25 +189,6 @@ public: }; ``` -### **Go** - -```go -func numWays(n int, relation [][]int, k int) int { - f := make([][]int, k+1) - for i := range f { - f[i] = make([]int, n) - } - f[0][0] = 1 - for i := 1; i <= k; i++ { - for _, r := range relation { - a, b := r[0], r[1] - f[i][b] += f[i-1][a] - } - } - return f[k][n-1] -} -``` - ```go func numWays(n int, relation [][]int, k int) int { f := make([]int, n) @@ -200,21 +205,6 @@ func numWays(n int, relation [][]int, k int) int { } ``` -### **TypeScript** - -```ts -function numWays(n: number, relation: number[][], k: number): number { - const f: number[][] = new Array(k + 1).fill(0).map(() => new Array(n).fill(0)); - f[0][0] = 1; - for (let i = 1; i <= k; ++i) { - for (const [a, b] of relation) { - f[i][b] += f[i - 1][a]; - } - } - return f[k][n - 1]; -} -``` - ```ts function numWays(n: number, relation: number[][], k: number): number { let f: number[] = new Array(n).fill(0); @@ -230,10 +220,6 @@ function numWays(n: number, relation: number[][], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 08. \345\211\247\346\203\205\350\247\246\345\217\221\346\227\266\351\227\264/README.md" "b/lcp/LCP 08. \345\211\247\346\203\205\350\247\246\345\217\221\346\227\266\351\227\264/README.md" index 9b1e9f86c33cb..a759b9e573d36 100644 --- "a/lcp/LCP 08. \345\211\247\346\203\205\350\247\246\345\217\221\346\227\266\351\227\264/README.md" +++ "b/lcp/LCP 08. \345\211\247\346\203\205\350\247\246\345\217\221\346\227\266\351\227\264/README.md" @@ -59,16 +59,10 @@ ## 解法 - - -**方法一:前缀和 + 二分查找** +### 方法一:前缀和 + 二分查找 -### **Python3** - - - ```python class Solution: def getTriggerTime( @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] getTriggerTime(int[][] increase, int[][] requirements) { @@ -135,10 +125,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 09. \346\234\200\345\260\217\350\267\263\350\267\203\346\254\241\346\225\260/README.md" "b/lcp/LCP 09. \346\234\200\345\260\217\350\267\263\350\267\203\346\254\241\346\225\260/README.md" index 54fb4adbdf397..a379b55bfbe6c 100644 --- "a/lcp/LCP 09. \346\234\200\345\260\217\350\267\263\350\267\203\346\254\241\346\225\260/README.md" +++ "b/lcp/LCP 09. \346\234\200\345\260\217\350\267\263\350\267\203\346\254\241\346\225\260/README.md" @@ -27,16 +27,10 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS -### **Python3** - - - ```python class Solution: def minJump(self, jump: List[int]) -> int: @@ -60,10 +54,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int minJump(int[] jump) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func minJump(jump []int) int { n := len(jump) @@ -173,10 +159,6 @@ func minJump(jump []int) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 10. \344\272\214\345\217\211\346\240\221\344\273\273\345\212\241\350\260\203\345\272\246/README.md" "b/lcp/LCP 10. \344\272\214\345\217\211\346\240\221\344\273\273\345\212\241\350\260\203\345\272\246/README.md" index bc4077d1e8105..8454d89128361 100644 --- "a/lcp/LCP 10. \344\272\214\345\217\211\346\240\221\344\273\273\345\212\241\350\260\203\345\272\246/README.md" +++ "b/lcp/LCP 10. \344\272\214\345\217\211\346\240\221\344\273\273\345\212\241\350\260\203\345\272\246/README.md" @@ -53,14 +53,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minimalExecTime(self, root: TreeNode) -> float: @@ -74,10 +70,6 @@ class Solution: return dfs(root)[1] ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -106,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -137,8 +127,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -165,8 +153,6 @@ func minimalExecTime(root *TreeNode) float64 { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -197,10 +183,6 @@ function minimalExecTime(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 11. \346\234\237\346\234\233\344\270\252\346\225\260\347\273\237\350\256\241/README.md" "b/lcp/LCP 11. \346\234\237\346\234\233\344\270\252\346\225\260\347\273\237\350\256\241/README.md" index f34e83330a833..9aeb99930d47e 100644 --- "a/lcp/LCP 11. \346\234\237\346\234\233\344\270\252\346\225\260\347\273\237\350\256\241/README.md" +++ "b/lcp/LCP 11. \346\234\237\346\234\233\344\270\252\346\225\260\347\273\237\350\256\241/README.md" @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 根据题目描述,我们可以得到如下结论: @@ -61,20 +59,12 @@ -### **Python3** - - - ```python class Solution: def expectNumber(self, scores: List[int]) -> int: return len(set(scores)) ``` -### **Java** - - - ```java class Solution { public int expectNumber(int[] scores) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +87,6 @@ public: }; ``` -### **Go** - ```go func expectNumber(scores []int) int { s := map[int]struct{}{} @@ -111,8 +97,6 @@ func expectNumber(scores []int) int { } ``` -### **TypeScript** - ```ts function expectNumber(scores: number[]): number { const s: Set = new Set(scores); @@ -120,10 +104,6 @@ function expectNumber(scores: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 12. \345\260\217\345\274\240\345\210\267\351\242\230\350\256\241\345\210\222/README.md" "b/lcp/LCP 12. \345\260\217\345\274\240\345\210\267\351\242\230\350\256\241\345\210\222/README.md" index 16f6b3259ed19..a7ec9f1c5810a 100644 --- "a/lcp/LCP 12. \345\260\217\345\274\240\345\210\267\351\242\230\350\256\241\345\210\222/README.md" +++ "b/lcp/LCP 12. \345\260\217\345\274\240\345\210\267\351\242\230\350\256\241\345\210\222/README.md" @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:贪心 + 二分查找** +### 方法一:贪心 + 二分查找 我们可以将题意转换为,将题目最多分成 $m$ 组,每一组去掉最大值后不超过 $T$ ,求最小的满足条件的 $T$。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def minTime(self, time: List[int], m: int) -> int: @@ -79,10 +73,6 @@ class Solution: return bisect_left(range(sum(time)), True, key=check) ``` -### **Java** - - - ```java class Solution { public int minTime(int[] time, int m) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func minTime(time []int, m int) int { right := 0 @@ -179,8 +165,6 @@ func minTime(time []int, m int) int { } ``` -### **TypeScript** - ```ts function minTime(time: number[], m: number): number { let left = 0; @@ -212,10 +196,6 @@ function minTime(time: number[], m: number): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 13. \345\257\273\345\256\235/README.md" "b/lcp/LCP 13. \345\257\273\345\256\235/README.md" index 461f66052fe40..041b967a27e6b 100644 --- "a/lcp/LCP 13. \345\257\273\345\256\235/README.md" +++ "b/lcp/LCP 13. \345\257\273\345\256\235/README.md" @@ -57,30 +57,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 14. \345\210\207\345\210\206\346\225\260\347\273\204/README.md" "b/lcp/LCP 14. \345\210\207\345\210\206\346\225\260\347\273\204/README.md" index adf67f63f1f74..b29b41cfc1a8d 100644 --- "a/lcp/LCP 14. \345\210\207\345\210\206\346\225\260\347\273\204/README.md" +++ "b/lcp/LCP 14. \345\210\207\345\210\206\346\225\260\347\273\204/README.md" @@ -35,30 +35,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 15. \346\270\270\344\271\220\345\233\255\347\232\204\350\277\267\345\256\253/README.md" "b/lcp/LCP 15. \346\270\270\344\271\220\345\233\255\347\232\204\350\277\267\345\256\253/README.md" index 99390887a35e1..f2557446a611f 100644 --- "a/lcp/LCP 15. \346\270\270\344\271\220\345\233\255\347\232\204\350\277\267\345\256\253/README.md" +++ "b/lcp/LCP 15. \346\270\270\344\271\220\345\233\255\347\232\204\350\277\267\345\256\253/README.md" @@ -41,30 +41,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 16. \346\270\270\344\271\220\345\233\255\347\232\204\346\270\270\350\247\210\350\256\241\345\210\222/README.md" "b/lcp/LCP 16. \346\270\270\344\271\220\345\233\255\347\232\204\346\270\270\350\247\210\350\256\241\345\210\222/README.md" index b7d4bb852b49f..e7b886957c0d1 100644 --- "a/lcp/LCP 16. \346\270\270\344\271\220\345\233\255\347\232\204\346\270\270\350\247\210\350\256\241\345\210\222/README.md" +++ "b/lcp/LCP 16. \346\270\270\344\271\220\345\233\255\347\232\204\346\270\270\350\247\210\350\256\241\345\210\222/README.md" @@ -49,30 +49,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/README.md" "b/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/README.md" index 9a0a4885272a2..98025a2294d4f 100644 --- "a/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/README.md" +++ "b/lcp/LCP 17. \351\200\237\347\256\227\346\234\272\345\231\250\344\272\272/README.md" @@ -37,14 +37,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def calculate(self, s: str) -> int: @@ -57,10 +53,6 @@ class Solution: return x + y ``` -### **Java** - - - ```java class Solution { public int calculate(String s) { @@ -77,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +85,6 @@ public: }; ``` -### **Go** - ```go func calculate(s string) int { x, y := 1, 0 @@ -111,10 +99,6 @@ func calculate(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 18. \346\227\251\351\244\220\347\273\204\345\220\210/README.md" "b/lcp/LCP 18. \346\227\251\351\244\220\347\273\204\345\220\210/README.md" index 7b68f5b25f36c..e12297c5d4293 100644 --- "a/lcp/LCP 18. \346\227\251\351\244\220\347\273\204\345\220\210/README.md" +++ "b/lcp/LCP 18. \346\227\251\351\244\220\347\273\204\345\220\210/README.md" @@ -72,16 +72,10 @@ ## 解法 - - -二分查找。 +### 方法一 -### **Python3** - - - ```python class Solution: def breakfastNumber(self, staple: List[int], drinks: List[int], x: int) -> int: @@ -101,10 +95,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int breakfastNumber(int[] staple, int[] drinks, int x) { @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func breakfastNumber(staple []int, drinks []int, x int) int { res, n := 0, len(drinks) @@ -182,10 +168,6 @@ func breakfastNumber(staple []int, drinks []int, x int) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/README.md" "b/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/README.md" index 8d65e2d82ffa1..24c8b885ce308 100644 --- "a/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/README.md" +++ "b/lcp/LCP 19. \347\247\213\345\217\266\346\224\266\350\227\217\351\233\206/README.md" @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示对于第 $i$ 片叶子,处于状态 $j$ 时的最小操作次数,其中 $j$ 表示: @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def minimumOperations(self, leaves: str) -> int: @@ -86,10 +80,6 @@ class Solution: return f[n - 1][2] ``` -### **Java** - - - ```java class Solution { public int minimumOperations(String leaves) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func minimumOperations(leaves string) int { n := len(leaves) @@ -172,8 +158,6 @@ func minimumOperations(leaves string) int { } ``` -### **TypeScript** - ```ts function minimumOperations(leaves: string): number { const n = leaves.length; @@ -195,10 +179,6 @@ function minimumOperations(leaves: string): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 20. \345\277\253\351\200\237\345\205\254\344\272\244/README.md" "b/lcp/LCP 20. \345\277\253\351\200\237\345\205\254\344\272\244/README.md" index 3d4f6b7fd27ea..6eafe05dfe573 100644 --- "a/lcp/LCP 20. \345\277\253\351\200\237\345\205\254\344\272\244/README.md" +++ "b/lcp/LCP 20. \345\277\253\351\200\237\345\205\254\344\272\244/README.md" @@ -78,30 +78,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 21. \350\277\275\351\200\220\346\270\270\346\210\217/README.md" "b/lcp/LCP 21. \350\277\275\351\200\220\346\270\270\346\210\217/README.md" index 3f04f3fe8742e..ddd7c19460deb 100644 --- "a/lcp/LCP 21. \350\277\275\351\200\220\346\270\270\346\210\217/README.md" +++ "b/lcp/LCP 21. \350\277\275\351\200\220\346\270\270\346\210\217/README.md" @@ -68,30 +68,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/README.md" "b/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/README.md" index 383f74c464e07..8334e0ae93be5 100644 --- "a/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/README.md" +++ "b/lcp/LCP 22. \351\273\221\347\231\275\346\226\271\346\240\274\347\224\273/README.md" @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:组合计数** +### 方法一:组合计数 我们可以选择涂黑 $n$ 行中的任意 $i$ 行,涂黑 $n$ 列中的任意 $j$ 列。那么涂黑的格子数为 $n \times (i + j) - i \times j$。如果满足 $n \times (i + j) - i \times j = k$,则方案数为 $\binom{n}{i} \times \binom{n}{j}$。累加所有满足条件的方案数即可。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def paintingPlan(self, n: int, k: int) -> int: @@ -74,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int paintingPlan(int n, int k) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func paintingPlan(n int, k int) (ans int) { if k == n*n { @@ -162,8 +148,6 @@ func paintingPlan(n int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function paintingPlan(n: number, k: number): number { if (k === n * n) { @@ -190,10 +174,6 @@ function paintingPlan(n: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 23. \351\255\224\346\234\257\346\216\222\345\210\227/README.md" "b/lcp/LCP 23. \351\255\224\346\234\257\346\216\222\345\210\227/README.md" index dd6355d5d47b9..f54acf6da8439 100644 --- "a/lcp/LCP 23. \351\255\224\346\234\257\346\216\222\345\210\227/README.md" +++ "b/lcp/LCP 23. \351\255\224\346\234\257\346\216\222\345\210\227/README.md" @@ -40,30 +40,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 24. \346\225\260\345\255\227\346\270\270\346\210\217/README.md" "b/lcp/LCP 24. \346\225\260\345\255\227\346\270\270\346\210\217/README.md" index e394af68c6556..a14422277f01e 100644 --- "a/lcp/LCP 24. \346\225\260\345\255\227\346\270\270\346\210\217/README.md" +++ "b/lcp/LCP 24. \346\225\260\345\255\227\346\270\270\346\210\217/README.md" @@ -55,30 +55,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 25. \345\217\244\350\221\243\351\224\256\347\233\230/README.md" "b/lcp/LCP 25. \345\217\244\350\221\243\351\224\256\347\233\230/README.md" index 677eb886e6030..f3d8f0007fd70 100644 --- "a/lcp/LCP 25. \345\217\244\350\221\243\351\224\256\347\233\230/README.md" +++ "b/lcp/LCP 25. \345\217\244\350\221\243\351\224\256\347\233\230/README.md" @@ -31,30 +31,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 26. \345\257\274\350\210\252\350\243\205\347\275\256/README.md" "b/lcp/LCP 26. \345\257\274\350\210\252\350\243\205\347\275\256/README.md" index 5db5fdec2a0df..cdb19defe3e62 100644 --- "a/lcp/LCP 26. \345\257\274\350\210\252\350\243\205\347\275\256/README.md" +++ "b/lcp/LCP 26. \345\257\274\350\210\252\350\243\205\347\275\256/README.md" @@ -48,30 +48,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 27. \351\273\221\347\233\222\345\205\211\347\272\277\345\217\215\345\260\204/README.md" "b/lcp/LCP 27. \351\273\221\347\233\222\345\205\211\347\272\277\345\217\215\345\260\204/README.md" index 577b0db95f7b1..e3da9fdb1cc06 100644 --- "a/lcp/LCP 27. \351\273\221\347\233\222\345\205\211\347\272\277\345\217\215\345\260\204/README.md" +++ "b/lcp/LCP 27. \351\273\221\347\233\222\345\205\211\347\272\277\345\217\215\345\260\204/README.md" @@ -74,30 +74,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 28. \351\207\207\350\264\255\346\226\271\346\241\210/README.md" "b/lcp/LCP 28. \351\207\207\350\264\255\346\226\271\346\241\210/README.md" index 31a338508a3fa..d8325093b8598 100644 --- "a/lcp/LCP 28. \351\207\207\350\264\255\346\226\271\346\241\210/README.md" +++ "b/lcp/LCP 28. \351\207\207\350\264\255\346\226\271\346\241\210/README.md" @@ -35,14 +35,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def purchasePlans(self, nums: List[int], target: int) -> int: @@ -58,10 +54,6 @@ class Solution: return res % 1000000007 ``` -### **Java** - - - ```java class Solution { public int purchasePlans(int[] nums, int target) { @@ -80,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +88,6 @@ public: }; ``` -### **Go** - ```go func purchasePlans(nums []int, target int) int { sort.Ints(nums) @@ -116,10 +104,6 @@ func purchasePlans(nums []int, target int) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 29. \344\271\220\345\233\242\347\253\231\344\275\215/README.md" "b/lcp/LCP 29. \344\271\220\345\233\242\347\253\231\344\275\215/README.md" index 6f79147311a53..f5df926a08e52 100644 --- "a/lcp/LCP 29. \344\271\220\345\233\242\347\253\231\344\275\215/README.md" +++ "b/lcp/LCP 29. \344\271\220\345\233\242\347\253\231\344\275\215/README.md" @@ -37,30 +37,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 30. \351\255\224\345\241\224\346\270\270\346\210\217/README.md" "b/lcp/LCP 30. \351\255\224\345\241\224\346\270\270\346\210\217/README.md" index 93f5e9091ec25..d3bf73f2b984b 100644 --- "a/lcp/LCP 30. \351\255\224\345\241\224\346\270\270\346\210\217/README.md" +++ "b/lcp/LCP 30. \351\255\224\345\241\224\346\270\270\346\210\217/README.md" @@ -31,30 +31,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 31. \345\217\230\346\215\242\347\232\204\350\277\267\345\256\253/README.md" "b/lcp/LCP 31. \345\217\230\346\215\242\347\232\204\350\277\267\345\256\253/README.md" index a90bf65148e17..84f30e63ab17c 100644 --- "a/lcp/LCP 31. \345\217\230\346\215\242\347\232\204\350\277\267\345\256\253/README.md" +++ "b/lcp/LCP 31. \345\217\230\346\215\242\347\232\204\350\277\267\345\256\253/README.md" @@ -50,30 +50,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 32. \346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/README.md" "b/lcp/LCP 32. \346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/README.md" index 68109431246e7..0158e0d957ed1 100644 --- "a/lcp/LCP 32. \346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/README.md" +++ "b/lcp/LCP 32. \346\211\271\351\207\217\345\244\204\347\220\206\344\273\273\345\212\241/README.md" @@ -44,30 +44,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 33. \350\223\204\346\260\264/README.md" "b/lcp/LCP 33. \350\223\204\346\260\264/README.md" index 3d812e57f9afc..043c49a304700 100644 --- "a/lcp/LCP 33. \350\223\204\346\260\264/README.md" +++ "b/lcp/LCP 33. \350\223\204\346\260\264/README.md" @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:贪心 + 枚举** +### 方法一:贪心 + 枚举 题目中涉及两个操作:升级水桶、蓄水。我们应该贪心地把升级水桶的操作放在前面,这样在蓄水时,每次能蓄水的量就会更多,操作次数就会更少。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def storeWater(self, bucket: List[int], vat: List[int]) -> int: @@ -72,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int storeWater(int[] bucket, int[] vat) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func storeWater(bucket []int, vat []int) int { mx := slices.Max(vat) @@ -141,8 +127,6 @@ func storeWater(bucket []int, vat []int) int { } ``` -### **TypeScript** - ```ts function storeWater(bucket: number[], vat: number[]): number { const mx = Math.max(...vat); @@ -162,10 +146,6 @@ function storeWater(bucket: number[], vat: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 34. \344\272\214\345\217\211\346\240\221\346\237\223\350\211\262/README.md" "b/lcp/LCP 34. \344\272\214\345\217\211\346\240\221\346\237\223\350\211\262/README.md" index c0b2d8c9f5a3d..7c879ddf49ff7 100644 --- "a/lcp/LCP 34. \344\272\214\345\217\211\346\240\221\346\237\223\350\211\262/README.md" +++ "b/lcp/LCP 34. \344\272\214\345\217\211\346\240\221\346\237\223\350\211\262/README.md" @@ -31,9 +31,7 @@ ## 解法 - - -**方法一:动态规划(树形 DP)** +### 方法一:动态规划(树形 DP) 我们考虑以 $root$ 为根节点的子树,且 $root$ 节点连着 $t$ 个染色节点的最大价值,其中 $t \in [0, k]$。我们用状态 $f[root][t]$ 来表示。 @@ -47,10 +45,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -76,10 +70,6 @@ class Solution: return max(dfs(root)) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -152,8 +140,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -184,8 +170,6 @@ func maxValue(root *TreeNode, k int) int { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -219,10 +203,6 @@ var maxValue = function (root, k) { }; ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 35. \347\224\265\345\212\250\350\275\246\346\270\270\345\237\216\345\270\202/README.md" "b/lcp/LCP 35. \347\224\265\345\212\250\350\275\246\346\270\270\345\237\216\345\270\202/README.md" index 6e05eaf86cf10..41b0756f0ec48 100644 --- "a/lcp/LCP 35. \347\224\265\345\212\250\350\275\246\346\270\270\345\237\216\345\270\202/README.md" +++ "b/lcp/LCP 35. \347\224\265\345\212\250\350\275\246\346\270\270\345\237\216\345\270\202/README.md" @@ -42,30 +42,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 36. \346\234\200\345\244\232\347\211\214\347\273\204\346\225\260/README.md" "b/lcp/LCP 36. \346\234\200\345\244\232\347\211\214\347\273\204\346\225\260/README.md" index f9bf4c61aebad..50e316286b325 100644 --- "a/lcp/LCP 36. \346\234\200\345\244\232\347\211\214\347\273\204\346\225\260/README.md" +++ "b/lcp/LCP 36. \346\234\200\345\244\232\347\211\214\347\273\204\346\225\260/README.md" @@ -36,30 +36,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 37. \346\234\200\345\260\217\347\237\251\345\275\242\351\235\242\347\247\257/README.md" "b/lcp/LCP 37. \346\234\200\345\260\217\347\237\251\345\275\242\351\235\242\347\247\257/README.md" index 6297df73e8de8..7904af2c0fd7c 100644 --- "a/lcp/LCP 37. \346\234\200\345\260\217\347\237\251\345\275\242\351\235\242\347\247\257/README.md" +++ "b/lcp/LCP 37. \346\234\200\345\260\217\347\237\251\345\275\242\351\235\242\347\247\257/README.md" @@ -33,30 +33,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 38. \345\256\210\345\215\253\345\237\216\345\240\241/README.md" "b/lcp/LCP 38. \345\256\210\345\215\253\345\237\216\345\240\241/README.md" index 5b77b6c222ed3..d7e99018795db 100644 --- "a/lcp/LCP 38. \345\256\210\345\215\253\345\237\216\345\240\241/README.md" +++ "b/lcp/LCP 38. \345\256\210\345\215\253\345\237\216\345\240\241/README.md" @@ -63,30 +63,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/README.md" "b/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/README.md" index 9541c80469507..6296e7806f620 100644 --- "a/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/README.md" +++ "b/lcp/LCP 39. \346\227\240\344\272\272\346\234\272\346\226\271\351\230\265/README.md" @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:哈希表计数** +### 方法一:哈希表计数 我们可以用哈希表 $cnt$ 统计 $source$ 和 $target$ 中每个数字出现的次数之差。对于 $cnt$ 中的每个数字 $x$,如果 $x$ 的出现次数为正数,那么说明 $x$ 在 $target$ 中出现的次数多,我们需要将 $x$ 出现的次数减少到 $0$。因此,我们只需要累加所有出现次数为正数的数字的出现次数之和,即为答案。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def minimumSwitchingTimes( @@ -73,10 +67,6 @@ class Solution: return sum(abs(x) for x in cnt.values()) // 2 ``` -### **Java** - - - ```java class Solution { public int minimumSwitchingTimes(int[][] source, int[][] target) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func minimumSwitchingTimes(source [][]int, target [][]int) (ans int) { cnt := map[int]int{} @@ -150,8 +136,6 @@ func minimumSwitchingTimes(source [][]int, target [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumSwitchingTimes(source: number[][], target: number[][]): number { const cnt: Map = new Map(); @@ -173,10 +157,6 @@ function minimumSwitchingTimes(source: number[][], target: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 40. \345\277\203\347\256\227\346\214\221\346\210\230/README.md" "b/lcp/LCP 40. \345\277\203\347\256\227\346\214\221\346\210\230/README.md" index 1971d03e94d45..c0a7ddd950b70 100644 --- "a/lcp/LCP 40. \345\277\203\347\256\227\346\214\221\346\210\230/README.md" +++ "b/lcp/LCP 40. \345\277\203\347\256\227\346\214\221\346\210\230/README.md" @@ -30,9 +30,7 @@ ## 解法 - - -**方法一:排序 + 贪心** +### 方法一:排序 + 贪心 排序先取最大的 $cnt$ 个数,如果和为偶数则直接返回答案。 @@ -42,10 +40,6 @@ -### **Python3** - - - ```python class Solution: def maxmiumScore(self, cards: List[int], cnt: int) -> int: @@ -61,10 +55,6 @@ class Solution: return max(ans - a + c, ans - b + d, 0) ``` -### **Java** - - - ```java class Solution { public int maxmiumScore(int[] cards, int cnt) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +121,6 @@ public: }; ``` -### **Go** - ```go func maxmiumScore(cards []int, cnt int) int { ans := 0 @@ -165,10 +151,6 @@ func maxmiumScore(cards []int, cnt int) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/README.md" "b/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/README.md" index 2800464489d85..7532f037e1f3d 100644 --- "a/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/README.md" +++ "b/lcp/LCP 41. \351\273\221\347\231\275\347\277\273\350\275\254\346\243\213/README.md" @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们注意到,题目中棋盘的大小最大为 $8 \times 8$,因此,我们可以尝试枚举所有的空余位置作为下一步放置黑棋的位置,然后使用广度优先搜索的方法计算在该位置下可以翻转的白棋的数量,找出最大值即可。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def flipChess(self, chessboard: List[str]) -> int: @@ -99,10 +93,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { private int m; @@ -166,8 +156,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -225,8 +213,6 @@ public: }; ``` -### **Go** - ```go func flipChess(chessboard []string) (ans int) { m, n := len(chessboard), len(chessboard[0]) @@ -286,10 +272,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 42. \347\216\251\345\205\267\345\245\227\345\234\210/README.md" "b/lcp/LCP 42. \347\216\251\345\205\267\345\245\227\345\234\210/README.md" index 87f98cecf4e19..2a9827baaf64e 100644 --- "a/lcp/LCP 42. \347\216\251\345\205\267\345\245\227\345\234\210/README.md" +++ "b/lcp/LCP 42. \347\216\251\345\205\267\345\245\227\345\234\210/README.md" @@ -43,30 +43,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 43. \345\215\201\345\255\227\350\267\257\345\217\243\347\232\204\344\272\244\351\200\232/README.md" "b/lcp/LCP 43. \345\215\201\345\255\227\350\267\257\345\217\243\347\232\204\344\272\244\351\200\232/README.md" index 5fa12c6ba05c0..b8151625b1f8c 100644 --- "a/lcp/LCP 43. \345\215\201\345\255\227\350\267\257\345\217\243\347\232\204\344\272\244\351\200\232/README.md" +++ "b/lcp/LCP 43. \345\215\201\345\255\227\350\267\257\345\217\243\347\232\204\344\272\244\351\200\232/README.md" @@ -57,30 +57,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 44. \345\274\200\345\271\225\345\274\217\347\204\260\347\201\253/README.md" "b/lcp/LCP 44. \345\274\200\345\271\225\345\274\217\347\204\260\347\201\253/README.md" index 2ad1635505373..6b44d449a4871 100644 --- "a/lcp/LCP 44. \345\274\200\345\271\225\345\274\217\347\204\260\347\201\253/README.md" +++ "b/lcp/LCP 44. \345\274\200\345\271\225\345\274\217\347\204\260\347\201\253/README.md" @@ -40,14 +40,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -69,10 +65,6 @@ class Solution: return len(s) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -103,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -133,8 +123,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -161,10 +149,6 @@ func dfs(root *TreeNode) { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 45. \350\207\252\350\241\214\350\275\246\347\202\253\346\212\200\350\265\233\345\234\272/README.md" "b/lcp/LCP 45. \350\207\252\350\241\214\350\275\246\347\202\253\346\212\200\350\265\233\345\234\272/README.md" index cd4cc0941fe24..1f7f9dd0c4c66 100644 --- "a/lcp/LCP 45. \350\207\252\350\241\214\350\275\246\347\202\253\346\212\200\350\265\233\345\234\272/README.md" +++ "b/lcp/LCP 45. \350\207\252\350\241\214\350\275\246\347\202\253\346\212\200\350\265\233\345\234\272/README.md" @@ -43,30 +43,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 46. \345\277\227\346\204\277\350\200\205\350\260\203\351\205\215/README.md" "b/lcp/LCP 46. \345\277\227\346\204\277\350\200\205\350\260\203\351\205\215/README.md" index 54fa1a30967bc..efd53934aa8ad 100644 --- "a/lcp/LCP 46. \345\277\227\346\204\277\350\200\205\350\260\203\351\205\215/README.md" +++ "b/lcp/LCP 46. \345\277\227\346\204\277\350\200\205\350\260\203\351\205\215/README.md" @@ -76,30 +76,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 47. \345\205\245\345\234\272\345\256\211\346\243\200/README.md" "b/lcp/LCP 47. \345\205\245\345\234\272\345\256\211\346\243\200/README.md" index 5f81765b3c821..d476a0a67fd35 100644 --- "a/lcp/LCP 47. \345\205\245\345\234\272\345\256\211\346\243\200/README.md" +++ "b/lcp/LCP 47. \345\205\245\345\234\272\345\256\211\346\243\200/README.md" @@ -80,30 +80,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 48. \346\227\240\351\231\220\346\243\213\345\261\200/README.md" "b/lcp/LCP 48. \346\227\240\351\231\220\346\243\213\345\261\200/README.md" index 64ddc17a03591..d57bd67970efc 100644 --- "a/lcp/LCP 48. \346\227\240\351\231\220\346\243\213\345\261\200/README.md" +++ "b/lcp/LCP 48. \346\227\240\351\231\220\346\243\213\345\261\200/README.md" @@ -64,30 +64,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 49. \347\216\257\345\275\242\351\227\257\345\205\263\346\270\270\346\210\217/README.md" "b/lcp/LCP 49. \347\216\257\345\275\242\351\227\257\345\205\263\346\270\270\346\210\217/README.md" index 57f41cff563e5..a0459a99930de 100644 --- "a/lcp/LCP 49. \347\216\257\345\275\242\351\227\257\345\205\263\346\270\270\346\210\217/README.md" +++ "b/lcp/LCP 49. \347\216\257\345\275\242\351\227\257\345\205\263\346\270\270\346\210\217/README.md" @@ -78,30 +78,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/README.md" "b/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/README.md" index 9bdd54be385f0..1c39559eda2b6 100644 --- "a/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/README.md" +++ "b/lcp/LCP 50. \345\256\235\347\237\263\350\241\245\347\273\231/README.md" @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们直接模拟宝石的赠送过程,最后返回最大值和最小值的差值即可。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def giveGem(self, gem: List[int], operations: List[List[int]]) -> int: @@ -79,10 +73,6 @@ class Solution: return max(gem) - min(gem) ``` -### **Java** - - - ```java class Solution { public int giveGem(int[] gem, int[][] operations) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func giveGem(gem []int, operations [][]int) int { for _, op := range operations { @@ -135,8 +121,6 @@ func giveGem(gem []int, operations [][]int) int { } ``` -### **TypeScript** - ```ts function giveGem(gem: number[], operations: number[][]): number { for (const [x, y] of operations) { @@ -148,10 +132,6 @@ function giveGem(gem: number[], operations: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/README.md" "b/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/README.md" index c9c6c3db157b4..53cf4bb025061 100644 --- "a/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/README.md" +++ "b/lcp/LCP 51. \347\203\271\351\245\252\346\226\231\347\220\206/README.md" @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:二进制枚举** +### 方法一:二进制枚举 我们注意到,料理的数量 $n$ 不超过 $8$,因此,我们可以使用二进制枚举的方法枚举所有的料理方案。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def perfectMenu( @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int perfectMenu(int[] materials, int[][] cookbooks, int[][] attribute, int limit) { @@ -127,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go func perfectMenu(materials []int, cookbooks [][]int, attribute [][]int, limit int) int { n := len(cookbooks) @@ -193,8 +179,6 @@ func perfectMenu(materials []int, cookbooks [][]int, attribute [][]int, limit in } ``` -### **TypeScript** - ```ts function perfectMenu( materials: number[], @@ -229,10 +213,6 @@ function perfectMenu( } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/README.md" "b/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/README.md" index 0bc882a15a3e7..054bee00abb74 100644 --- "a/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/README.md" +++ "b/lcp/LCP 52. \344\272\214\345\217\211\346\220\234\347\264\242\346\240\221\346\237\223\350\211\262/README.md" @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:有序集合 + 倒序遍历** +### 方法一:有序集合 + 倒序遍历 我们先遍历一遍二叉树,将所有节点的值加入到有序集合中。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -104,10 +98,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -148,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -188,8 +176,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -224,8 +210,6 @@ func getNumber(root *TreeNode, ops [][]int) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -756,10 +740,6 @@ class TreeSet { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 53. \345\256\210\346\212\244\345\244\252\347\251\272\345\237\216/README.md" "b/lcp/LCP 53. \345\256\210\346\212\244\345\244\252\347\251\272\345\237\216/README.md" index 23bd4abbbde40..5cf8d68865ab0 100644 --- "a/lcp/LCP 53. \345\256\210\346\212\244\345\244\252\347\251\272\345\237\216/README.md" +++ "b/lcp/LCP 53. \345\256\210\346\212\244\345\244\252\347\251\272\345\237\216/README.md" @@ -52,30 +52,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 54. \345\244\272\345\233\236\346\215\256\347\202\271/README.md" "b/lcp/LCP 54. \345\244\272\345\233\236\346\215\256\347\202\271/README.md" index ad11a48fe136c..415619b6604cf 100644 --- "a/lcp/LCP 54. \345\244\272\345\233\236\346\215\256\347\202\271/README.md" +++ "b/lcp/LCP 54. \345\244\272\345\233\236\346\215\256\347\202\271/README.md" @@ -61,30 +61,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/README.md" "b/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/README.md" index 491ec89a60d1d..a93cd7457aa26 100644 --- "a/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/README.md" +++ "b/lcp/LCP 55. \351\207\207\351\233\206\346\236\234\345\256\236/README.md" @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 对于每个任务,我们贪心地按照 $limit$ 的大小来采集,那么每个任务需要的时间为 $\lceil \frac{num}{limit} \rceil \times time[type]$,其中 $\lceil x \rceil$ 表示对 $x$ 向上取整。我们将所有任务需要的时间求和即为答案。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def getMinimumTime( @@ -74,10 +68,6 @@ class Solution: return sum((num + limit - 1) // limit * time[i] for i, num in fruits) ``` -### **Java** - - - ```java class Solution { public int getMinimumTime(int[] time, int[][] fruits, int limit) { @@ -91,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func getMinimumTime(time []int, fruits [][]int, limit int) (ans int) { for _, f := range fruits { @@ -119,8 +105,6 @@ func getMinimumTime(time []int, fruits [][]int, limit int) (ans int) { } ``` -### **TypeScript** - ```ts function getMinimumTime(time: number[], fruits: number[][], limit: number): number { let ans = 0; @@ -131,10 +115,6 @@ function getMinimumTime(time: number[], fruits: number[][], limit: number): numb } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/README.md" "b/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/README.md" index 9270ff8e8733d..391e37db561c3 100644 --- "a/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/README.md" +++ "b/lcp/LCP 56. \344\277\241\347\211\251\344\274\240\351\200\201/README.md" @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:双端队列 BFS(0-1 BFS)** +### 方法一:双端队列 BFS(0-1 BFS) 每走到一个格子 $(i, j)$,有 $4$ 个方向可以走,如果方向与当前格子的方向相同,那么不需要施法,否则需要施法一次。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def conveyorBelt(self, matrix: List[str], start: List[int], end: List[int]) -> int: @@ -94,10 +88,6 @@ class Solution: q.append((x, y)) ``` -### **Java** - - - ```java class Solution { public int conveyorBelt(String[] matrix, int[] start, int[] end) { @@ -138,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -179,8 +167,6 @@ public: }; ``` -### **Go** - ```go func conveyorBelt(matrix []string, start []int, end []int) int { dirs := [5]int{-1, 0, 1, 0, -1} @@ -226,8 +212,6 @@ func conveyorBelt(matrix []string, start []int, end []int) int { } ``` -### **TypeScript** - ```ts function conveyorBelt(matrix: string[], start: number[], end: number[]): number { const dirs = [-1, 0, 1, 0, -1]; @@ -265,10 +249,6 @@ function conveyorBelt(matrix: string[], start: number[], end: number[]): number } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 57. \346\211\223\345\234\260\351\274\240/README.md" "b/lcp/LCP 57. \346\211\223\345\234\260\351\274\240/README.md" index 37ca7cda3add9..1d02d6a33c717 100644 --- "a/lcp/LCP 57. \346\211\223\345\234\260\351\274\240/README.md" +++ "b/lcp/LCP 57. \346\211\223\345\234\260\351\274\240/README.md" @@ -68,30 +68,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 58. \347\247\257\346\234\250\346\213\274\346\216\245/README.md" "b/lcp/LCP 58. \347\247\257\346\234\250\346\213\274\346\216\245/README.md" index 8c9a7a3f9bf96..b8f1423920ad3 100644 --- "a/lcp/LCP 58. \347\247\257\346\234\250\346\213\274\346\216\245/README.md" +++ "b/lcp/LCP 58. \347\247\257\346\234\250\346\213\274\346\216\245/README.md" @@ -52,30 +52,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 59. \346\220\255\346\241\245\350\277\207\346\262\263/README.md" "b/lcp/LCP 59. \346\220\255\346\241\245\350\277\207\346\262\263/README.md" index 437ce0793a7f2..b48c5f0ce2337 100644 --- "a/lcp/LCP 59. \346\220\255\346\241\245\350\277\207\346\262\263/README.md" +++ "b/lcp/LCP 59. \346\220\255\346\241\245\350\277\207\346\262\263/README.md" @@ -50,30 +50,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 60. \345\212\233\346\211\243\346\263\241\346\263\241\351\276\231/README.md" "b/lcp/LCP 60. \345\212\233\346\211\243\346\263\241\346\263\241\351\276\231/README.md" index 968c690d927cf..267e0a7772153 100644 --- "a/lcp/LCP 60. \345\212\233\346\211\243\346\263\241\346\263\241\351\276\231/README.md" +++ "b/lcp/LCP 60. \345\212\233\346\211\243\346\263\241\346\263\241\351\276\231/README.md" @@ -51,30 +51,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 61. \346\260\224\346\270\251\345\217\230\345\214\226\350\266\213\345\212\277/README.md" "b/lcp/LCP 61. \346\260\224\346\270\251\345\217\230\345\214\226\350\266\213\345\212\277/README.md" index aee38e76fd8ea..c58c7913b3c3b 100644 --- "a/lcp/LCP 61. \346\260\224\346\270\251\345\217\230\345\214\226\350\266\213\345\212\277/README.md" +++ "b/lcp/LCP 61. \346\260\224\346\270\251\345\217\230\345\214\226\350\266\213\345\212\277/README.md" @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们用变量 $f$ 维护当前趋势相同的连续天数,用变量 $ans$ 维护最大的连续天数。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def temperatureTrend(self, temperatureA: List[int], temperatureB: List[int]) -> int: @@ -72,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int temperatureTrend(int[] temperatureA, int[] temperatureB) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func temperatureTrend(temperatureA []int, temperatureB []int) int { ans, f := 0, 0 @@ -134,10 +120,6 @@ func temperatureTrend(temperatureA []int, temperatureB []int) int { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 62. \344\272\244\351\200\232\346\236\242\347\272\275/README.md" "b/lcp/LCP 62. \344\272\244\351\200\232\346\236\242\347\272\275/README.md" index 02df307fe5a38..47b5f62f5699f 100644 --- "a/lcp/LCP 62. \344\272\244\351\200\232\346\236\242\347\272\275/README.md" +++ "b/lcp/LCP 62. \344\272\244\351\200\232\346\236\242\347\272\275/README.md" @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:统计入度和出度** +### 方法一:统计入度和出度 我们创建两个数组 $ind$ 和 $outd$,分别用于记录每个点的入度和出度,用哈希表 $s$ 保存每个节点。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def transportationHub(self, path: List[List[int]]) -> int: @@ -83,10 +77,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int transportationHub(int[][] path) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func transportationHub(path [][]int) int { ind := [1001]int{} @@ -172,8 +158,6 @@ func transportationHub(path [][]int) int { } ``` -### **TypeScript** - ```ts function transportationHub(path: number[][]): number { const ind: number[] = new Array(1001).fill(0); @@ -199,10 +183,6 @@ function transportationHub(path: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 63. \345\274\271\347\217\240\346\270\270\346\210\217/README.md" "b/lcp/LCP 63. \345\274\271\347\217\240\346\270\270\346\210\217/README.md" index 0cae17d1b33a8..20f44961b49fc 100644 --- "a/lcp/LCP 63. \345\274\271\347\217\240\346\270\270\346\210\217/README.md" +++ "b/lcp/LCP 63. \345\274\271\347\217\240\346\270\270\346\210\217/README.md" @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们注意到,从不同的位置打入弹珠,弹珠的前进路线不会重叠。因此,我们可以枚举所有可能的打入位置,然后模拟弹珠的前进过程,判断是否能够入洞,是则将该位置加入答案。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def ballGame(self, num: int, plate: List[str]) -> List[List[int]]: @@ -112,10 +106,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private String[] plate; @@ -172,8 +162,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -222,8 +210,6 @@ public: }; ``` -### **Go** - ```go func ballGame(num int, plate []string) (ans [][]int) { dirs := [5]int{0, 1, 0, -1, 0} @@ -268,10 +254,6 @@ func ballGame(num int, plate []string) (ans [][]int) { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 64. \344\272\214\345\217\211\346\240\221\347\201\257\351\245\260/README.md" "b/lcp/LCP 64. \344\272\214\345\217\211\346\240\221\347\201\257\351\245\260/README.md" index f2ef511488849..cb78433cca280 100644 --- "a/lcp/LCP 64. \344\272\214\345\217\211\346\240\221\347\201\257\351\245\260/README.md" +++ "b/lcp/LCP 64. \344\272\214\345\217\211\346\240\221\347\201\257\351\245\260/README.md" @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们注意到,三个开关只能影响当前节点及其左右子节点,因此我们可以将当前节点的状态分为四种: @@ -80,10 +78,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -114,10 +108,6 @@ class Solution: return dfs(root)[0] ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -166,8 +156,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -209,8 +197,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -248,10 +234,6 @@ func closeLampInTree(root *TreeNode) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 65. \350\210\222\351\200\202\347\232\204\346\271\277\345\272\246/README.md" "b/lcp/LCP 65. \350\210\222\351\200\202\347\232\204\346\271\277\345\272\246/README.md" index 880f451fafe22..dcb95d1c32446 100644 --- "a/lcp/LCP 65. \350\210\222\351\200\202\347\232\204\346\271\277\345\272\246/README.md" +++ "b/lcp/LCP 65. \350\210\222\351\200\202\347\232\204\346\271\277\345\272\246/README.md" @@ -39,30 +39,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/README.md" "b/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/README.md" index 8f501f03449f7..4fca69f810e62 100644 --- "a/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/README.md" +++ "b/lcp/LCP 66. \346\234\200\345\260\217\345\261\225\345\217\260\346\225\260\351\207\217/README.md" @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们用哈希表或数组 $cnt$ 记录当前可用的展台以及数量。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def minNumBooths(self, demand: List[str]) -> int: @@ -71,10 +65,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minNumBooths(String[] demand) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func minNumBooths(demand []string) (ans int) { cnt := [26]int{} @@ -145,10 +131,6 @@ func minNumBooths(demand []string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 67. \350\243\205\351\245\260\346\240\221/README.md" "b/lcp/LCP 67. \350\243\205\351\245\260\346\240\221/README.md" index c1e35f1232d91..2f2f5ff1d3e3e 100644 --- "a/lcp/LCP 67. \350\243\205\351\245\260\346\240\221/README.md" +++ "b/lcp/LCP 67. \350\243\205\351\245\260\346\240\221/README.md" @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们设计一个函数 $dfs(root)$,表示将灯饰插入以 $root$ 为根节点的树中,返回插入灯饰后的树的根节点。那么答案就是 $dfs(root)$。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -83,10 +77,6 @@ class Solution: return dfs(root) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -191,10 +177,6 @@ func expandBinaryTree(root *TreeNode) *TreeNode { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 68. \347\276\216\350\247\202\347\232\204\350\212\261\346\235\237/README.md" "b/lcp/LCP 68. \347\276\216\350\247\202\347\232\204\350\212\261\346\235\237/README.md" index b60b3cc38bdb0..d84b737777da1 100644 --- "a/lcp/LCP 68. \347\276\216\350\247\202\347\232\204\350\212\261\346\235\237/README.md" +++ "b/lcp/LCP 68. \347\276\216\350\247\202\347\232\204\350\212\261\346\235\237/README.md" @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们用双指针 $j$ 和 $i$ 分别指向当前窗口的左右端点,用数组或哈希表 $d$ 记录当前窗口内的元素以及出现的次数。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def beautifulBouquet(self, flowers: List[int], cnt: int) -> int: @@ -75,10 +69,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int beautifulBouquet(int[] flowers, int cnt) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func beautifulBouquet(flowers []int, cnt int) (ans int) { mx := slices.Max(flowers) @@ -144,10 +130,6 @@ func beautifulBouquet(flowers []int, cnt int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/lcp/LCP 69. Hello LeetCode!/README.md b/lcp/LCP 69. Hello LeetCode!/README.md index 954ae1e154b37..0096e691b14f2 100644 --- a/lcp/LCP 69. Hello LeetCode!/README.md +++ b/lcp/LCP 69. Hello LeetCode!/README.md @@ -53,30 +53,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 70. \346\262\231\345\234\260\346\262\273\347\220\206/README.md" "b/lcp/LCP 70. \346\262\231\345\234\260\346\262\273\347\220\206/README.md" index 2319fc79cee95..1ce918836242a 100644 --- "a/lcp/LCP 70. \346\262\231\345\234\260\346\262\273\347\220\206/README.md" +++ "b/lcp/LCP 70. \346\262\231\345\234\260\346\262\273\347\220\206/README.md" @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:找规律** +### 方法一:找规律 我们画图观察,可以发现,第一行只有一个三角形,一定要涂色,而从最后一行开始,到第二行结束,每四行的涂色方案是一样的: @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def sandyLandManagement(self, size: int) -> List[List[int]]: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] sandyLandManagement(int size) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func sandyLandManagement(size int) (ans [][]int) { ans = append(ans, []int{1, 1}) @@ -168,10 +154,6 @@ func sandyLandManagement(size int) (ans [][]int) { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 71. \351\233\206\346\260\264\345\231\250/README.md" "b/lcp/LCP 71. \351\233\206\346\260\264\345\231\250/README.md" index 8903b8b00b1bd..88c1b213487c3 100644 --- "a/lcp/LCP 71. \351\233\206\346\260\264\345\231\250/README.md" +++ "b/lcp/LCP 71. \351\233\206\346\260\264\345\231\250/README.md" @@ -64,30 +64,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 72. \350\241\245\347\273\231\351\251\254\350\275\246/README.md" "b/lcp/LCP 72. \350\241\245\347\273\231\351\251\254\350\275\246/README.md" index b4624ed6ccb87..d98255aa45439 100644 --- "a/lcp/LCP 72. \350\241\245\347\273\231\351\251\254\350\275\246/README.md" +++ "b/lcp/LCP 72. \350\241\245\347\273\231\351\251\254\350\275\246/README.md" @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 根据题目描述,我们每次遍历 `supplies`,找到物资之和最小的两辆相邻马车,将它们车辆的物资整合为一辆,重复上述操作直到车队长度符合要求。 @@ -47,10 +45,6 @@ -### **Python3** - - - ```python class Solution: def supplyWagon(self, supplies: List[int]) -> List[int]: @@ -76,10 +70,6 @@ class Solution: return supplies ``` -### **Java** - - - ```java class Solution { public int[] supplyWagon(int[] supplies) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func supplyWagon(supplies []int) []int { for h := (len(supplies) + 1) >> 1; h > 0; h-- { @@ -173,8 +159,6 @@ func supplyWagon(supplies []int) []int { } ``` -### **TypeScript** - ```ts function supplyWagon(supplies: number[]): number[] { for (let h = (supplies.length + 1) >> 1; h > 0; --h) { @@ -203,10 +187,6 @@ function supplyWagon(supplies: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 73. \346\216\242\351\231\251\350\220\245\345\234\260/README.md" "b/lcp/LCP 73. \346\216\242\351\231\251\350\220\245\345\234\260/README.md" index f7c389bd7bbd0..db4fc710613a6 100644 --- "a/lcp/LCP 73. \346\216\242\351\231\251\350\220\245\345\234\260/README.md" +++ "b/lcp/LCP 73. \346\216\242\351\231\251\350\220\245\345\234\260/README.md" @@ -63,30 +63,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 74. \346\234\200\345\274\272\347\245\235\347\246\217\345\212\233\345\234\272/README.md" "b/lcp/LCP 74. \346\234\200\345\274\272\347\245\235\347\246\217\345\212\233\345\234\272/README.md" index 8a63c60340313..5398501ca29c3 100644 --- "a/lcp/LCP 74. \346\234\200\345\274\272\347\245\235\347\246\217\345\212\233\345\234\272/README.md" +++ "b/lcp/LCP 74. \346\234\200\345\274\272\347\245\235\347\246\217\345\212\233\345\234\272/README.md" @@ -42,30 +42,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 75. \344\274\240\351\200\201\345\215\267\350\275\264/README.md" "b/lcp/LCP 75. \344\274\240\351\200\201\345\215\267\350\275\264/README.md" index efa6ba4f5c599..374cfc5ceac08 100644 --- "a/lcp/LCP 75. \344\274\240\351\200\201\345\215\267\350\275\264/README.md" +++ "b/lcp/LCP 75. \344\274\240\351\200\201\345\215\267\350\275\264/README.md" @@ -72,30 +72,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 76. \351\255\224\346\263\225\346\243\213\347\233\230/README.md" "b/lcp/LCP 76. \351\255\224\346\263\225\346\243\213\347\233\230/README.md" index 2e89c7af84440..d4ca5482a360a 100644 --- "a/lcp/LCP 76. \351\255\224\346\263\225\346\243\213\347\233\230/README.md" +++ "b/lcp/LCP 76. \351\255\224\346\263\225\346\243\213\347\233\230/README.md" @@ -44,30 +44,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/README.md" "b/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/README.md" index 591d8ee912124..20bec07c82864 100644 --- "a/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/README.md" +++ "b/lcp/LCP 77. \347\254\246\346\226\207\345\202\250\345\244\207/README.md" @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们可以将符文按照魔力值从小到大排序,然后使用双指针维护一个滑动窗口,使得滑动窗口中的任意相邻的两块符文之间的魔力值相差不超过,找出满足条件的最大窗口长度即可。 @@ -46,10 +44,6 @@ -### **Python3** - - - ```python class Solution: def runeReserve(self, runes: List[int]) -> int: @@ -63,10 +57,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int runeReserve(int[] runes) { @@ -84,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +92,6 @@ public: }; ``` -### **Go** - ```go func runeReserve(runes []int) (ans int) { sort.Ints(runes) @@ -121,8 +107,6 @@ func runeReserve(runes []int) (ans int) { } ``` -### **TypeScript** - ```ts function runeReserve(runes: number[]): number { runes.sort((a, b) => a - b); @@ -139,10 +123,6 @@ function runeReserve(runes: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/README.md" "b/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/README.md" index 02676f606af5e..71ec8a1138227 100644 --- "a/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/README.md" +++ "b/lcp/LCP 78. \345\237\216\345\242\231\351\230\262\347\272\277/README.md" @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们注意到,如果一个膨胀值 $x$ 满足条件,那么所有小于 $x$ 的值也都满足条件,这存在着单调性。因此我们可以使用二分查找的方法,找到最大的满足条件的膨胀值。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def rampartDefensiveLine(self, rampart: List[List[int]]) -> int: @@ -88,10 +82,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { private int[][] rampart; @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +148,6 @@ public: }; ``` -### **Go** - ```go func rampartDefensiveLine(rampart [][]int) int { check := func(w int) bool { @@ -191,8 +177,6 @@ func rampartDefensiveLine(rampart [][]int) int { } ``` -### **TypeScript** - ```ts function rampartDefensiveLine(rampart: number[][]): number { const check = (w: number): boolean => { @@ -222,10 +206,6 @@ function rampartDefensiveLine(rampart: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/README.md" "b/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/README.md" index f32fa74c5e59d..5e00c9d80b9d2 100644 --- "a/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/README.md" +++ "b/lcp/LCP 79. \346\217\220\345\217\226\345\222\222\346\226\207/README.md" @@ -40,18 +40,12 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 时间复杂度 $O(m \times n \times l)$,空间复杂度 $O(m \times n \times l)$。 -### **Python3** - - - ```python class Solution: def extractMantra(self, matrix: List[str], mantra: str) -> int: @@ -82,10 +76,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int extractMantra(String[] matrix, String mantra) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +151,6 @@ public: }; ``` -### **Go** - ```go func extractMantra(matrix []string, mantra string) (ans int) { m, n, l := len(matrix), len(matrix[0]), len(mantra) @@ -204,8 +190,6 @@ func extractMantra(matrix []string, mantra string) (ans int) { } ``` -### **TypeScript** - ```ts function extractMantra(matrix: string[], mantra: string): number { const [m, n, l] = [matrix.length, matrix[0].length, mantra.length]; @@ -243,10 +227,6 @@ function extractMantra(matrix: string[], mantra: string): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/lcp/LCP 80. \347\224\237\347\211\251\350\277\233\345\214\226\345\275\225/README.md" "b/lcp/LCP 80. \347\224\237\347\211\251\350\277\233\345\214\226\345\275\225/README.md" index ece48428a3641..4e40133c20ecd 100644 --- "a/lcp/LCP 80. \347\224\237\347\211\251\350\277\233\345\214\226\345\275\225/README.md" +++ "b/lcp/LCP 80. \347\224\237\347\211\251\350\277\233\345\214\226\345\275\225/README.md" @@ -42,30 +42,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 81. \344\270\216\351\235\236\347\232\204\350\260\234\351\242\230/README.md" "b/lcp/LCP 81. \344\270\216\351\235\236\347\232\204\350\260\234\351\242\230/README.md" index a2c324b48d66b..e0991dc817a1e 100644 --- "a/lcp/LCP 81. \344\270\216\351\235\236\347\232\204\350\260\234\351\242\230/README.md" +++ "b/lcp/LCP 81. \344\270\216\351\235\236\347\232\204\350\260\234\351\242\230/README.md" @@ -62,30 +62,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcp/LCP 82. \344\270\207\347\201\265\344\271\213\346\240\221/README.md" "b/lcp/LCP 82. \344\270\207\347\201\265\344\271\213\346\240\221/README.md" index 6b62e82ad6c33..8b83448ef3e60 100644 --- "a/lcp/LCP 82. \344\270\207\347\201\265\344\271\213\346\240\221/README.md" +++ "b/lcp/LCP 82. \344\270\207\347\201\265\344\271\213\346\240\221/README.md" @@ -65,30 +65,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git "a/lcs/LCS 01. \344\270\213\350\275\275\346\217\222\344\273\266/README.md" "b/lcs/LCS 01. \344\270\213\350\275\275\346\217\222\344\273\266/README.md" index d6c9d193391d8..2dee051973763 100644 --- "a/lcs/LCS 01. \344\270\213\350\275\275\346\217\222\344\273\266/README.md" +++ "b/lcs/LCS 01. \344\270\213\350\275\275\346\217\222\344\273\266/README.md" @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 如果不能在一分钟内下载完,那么可以先加速,循环直至能在一分钟内下载完。那么“循环次数 + 1”即为最少消耗的分钟数。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def leastMinutes(self, n: int) -> int: @@ -67,10 +61,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int leastMinutes(int n) { @@ -83,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +86,6 @@ public: }; ``` -### **Go** - ```go func leastMinutes(n int) int { ans := 1 @@ -110,7 +96,15 @@ func leastMinutes(n int) int { } ``` -### **JavaScript** +```ts +function leastMinutes(n: number): number { + let ans = 1; + for (let speed = 1; speed < n; speed <<= 1) { + ++ans; + } + return ans; +} +``` ```js /** @@ -126,22 +120,6 @@ var leastMinutes = function (n) { }; ``` -### **TypeScript** - -```ts -function leastMinutes(n: number): number { - let ans = 1; - for (let speed = 1; speed < n; speed <<= 1) { - ++ans; - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git "a/lcs/LCS 02. \345\256\214\346\210\220\344\270\200\345\215\212\351\242\230\347\233\256/README.md" "b/lcs/LCS 02. \345\256\214\346\210\220\344\270\200\345\215\212\351\242\230\347\233\256/README.md" index c5c04180a8321..2abf530c678a8 100644 --- "a/lcs/LCS 02. \345\256\214\346\210\220\344\270\200\345\215\212\351\242\230\347\233\256/README.md" +++ "b/lcs/LCS 02. \345\256\214\346\210\220\344\270\200\345\215\212\351\242\230\347\233\256/README.md" @@ -34,9 +34,7 @@ ## 解法 - - -**方法一:计数 + 排序** +### 方法一:计数 + 排序 我们可以用哈希表或数组 `cnt` 统计每种知识点类型的题目数量,然后对 `cnt` 进行排序,从大到小遍历 `cnt`,直到遍历的题目数量之和大于等于 `n` 即可,此时遍历的次数即为所求。 @@ -44,10 +42,6 @@ -### **Python3** - - - ```python class Solution: def halfQuestions(self, questions: List[int]) -> int: @@ -61,10 +55,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int halfQuestions(int[] questions) { @@ -84,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +93,6 @@ public: }; ``` -### **Go** - ```go func halfQuestions(questions []int) (ans int) { cnt := make([]int, 1010) @@ -123,14 +109,8 @@ func halfQuestions(questions []int) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} questions - * @return {number} - */ -var halfQuestions = function (questions) { +```ts +function halfQuestions(questions: number[]): number { const cnt = new Array(1010).fill(0); for (const x of questions) { ++cnt[x]; @@ -143,13 +123,15 @@ var halfQuestions = function (questions) { n -= cnt[i]; } return ans; -}; +} ``` -### **TypeScript** - -```ts -function halfQuestions(questions: number[]): number { +```js +/** + * @param {number[]} questions + * @return {number} + */ +var halfQuestions = function (questions) { const cnt = new Array(1010).fill(0); for (const x of questions) { ++cnt[x]; @@ -162,13 +144,9 @@ function halfQuestions(questions: number[]): number { n -= cnt[i]; } return ans; -} -``` - -### **...** - -``` - +}; ``` + + diff --git "a/lcs/LCS 03. \344\270\273\351\242\230\347\251\272\351\227\264/README.md" "b/lcs/LCS 03. \344\270\273\351\242\230\347\251\272\351\227\264/README.md" index 0b6c8673abe9e..c0cf9457f807f 100644 --- "a/lcs/LCS 03. \344\270\273\351\242\230\347\251\272\351\227\264/README.md" +++ "b/lcs/LCS 03. \344\270\273\351\242\230\347\251\272\351\227\264/README.md" @@ -34,87 +34,10 @@ ## 解法 - - -并查集。 - -并查集模板: - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` - -对于本题,记 m, n 分别为 grid 的行数和列数。 - -- 将所有走廊及 "0" 对应的格子与超级节点 `m * n` 相连。 -- 对于其它格子,判断其相邻(上、下、左、右)的格子是否为 "0" 或者与当前格子相同,若是,更新 size 并将两个格子相连。 -- 最后,获取不与超级节点相连的格子的最大 size,即为答案。 +### 方法一 -### **Python3** - - - ```python class Solution: def largestArea(self, grid: List[str]) -> int: @@ -150,10 +73,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -206,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -249,8 +166,6 @@ public: }; ``` -### **Go** - ```go func largestArea(grid []string) int { m, n := len(grid), len(grid[0]) @@ -295,8 +210,6 @@ func largestArea(grid []string) int { } ``` -### **JavaScript** - ```js /** * @param {string[]} grid @@ -348,10 +261,6 @@ var largestArea = function (grid) { }; ``` -### **...** - -``` - -``` - + + diff --git a/main.py b/main.py index 7f1628e441682..c24f20d791089 100644 --- a/main.py +++ b/main.py @@ -2,23 +2,41 @@ import os import re -code_block_dict = { - "python": ("Python3", "py"), +sorted_suffixes = [ + "py", + "java", + "cpp", + "go", + "ts", + "rs", + "js", + "cs", + "php", + "c", + "scala", + "swift", + "rb", + "kt", + "nim", + "sql", +] +code_dict = { + "py": ("Python3", "python"), "java": ("Java", "java"), "cpp": ("C++", "cpp"), - "c": ("C", "c"), "go": ("Go", "go"), "ts": ("TypeScript", "ts"), + "rs": ("Rust", "rust"), "js": ("JavaScript", "js"), - "php": ("PHP", "php"), "cs": ("C#", "cs"), - "rust": ("Rust", "rs"), - "sql": ("MySQL", "sql"), - "nim": ("Nim", "nim"), + "php": ("PHP", "php"), + "c": ("C", "c"), "scala": ("Scala", "scala"), "swift": ("Swift", "swift"), "rb": ("Ruby", "rb"), - "kotlin": ("Kotlin", "kt"), + "kt": ("Kotlin", "kotlin"), + "nim": ("Nim", "nim"), + "sql": ("MySQL", "sql"), } @@ -42,7 +60,7 @@ def extract_code(): if i == -1: continue content = content[i + len(mark) :] - for suf, (_, suffix) in code_block_dict.items(): + for suffix, (_, suf) in code_dict.items(): res = re.findall(f"```{suf}\n(.*?)```", content, re.S) if not res: continue @@ -111,13 +129,72 @@ def extract_solution_paragraph(): ["**Solution 1:", "**Solution 2:", "**Solution 3:", "**Solution 4:"], ) + prefix = path[: path.rfind("/")] + tab_start = "" + tab_end = "" + for i in range(1, 5): + codes = [] + for suf in sorted_suffixes: + seq = '' if i == 1 else str(i) + file_name = f"{prefix}/Solution{seq}.{suf}" + try: + with open(file_name, "r", encoding="utf-8") as f: + code = f.read().strip() + code = '```' + code_dict[suf][1] + '\n' + code + '\n```' + codes.append(code) + except: + continue + if codes: + if i > len(blocks): + seq_dict = {1: '一', 2: '二', 3: '三', 4: '四'} + title = f"### 方法{seq_dict[i]}" if is_cn else f"### Solution {i}" + block = ( + title + + '\n\n' + + tab_start + + '\n\n' + + '\n\n'.join(codes) + + '\n\n' + + tab_end + ) + blocks.append(block) + else: + block = ( + blocks[i - 1] + + '\n\n' + + tab_start + + '\n\n' + + '\n\n'.join(codes) + + '\n\n' + + tab_end + ) + blocks[i - 1] = block + is_problem = ( + content.find("## 解法") != -1 + if is_cn + else content.find("## Solutions") != -1 + and content.find("## Description") != -1 + ) + start = '## 解法' if is_cn else '## Solutions' + end = '' if blocks: - prefix = path[: path.rfind("/")] - name = f"{prefix}/Solution.md" if is_cn else f"{prefix}/Solution_EN.md" - with open(name, "w", encoding="utf-8") as f: - f.write("\n\n".join(blocks)) + content = ( + content[: content.find(start)] + + start + + '\n\n' + + '\n\n'.join(blocks) + + '\n\n' + + end + ) + with open(path, "w", encoding="utf-8") as f: + f.write(content) + elif is_problem: + start = '## 解法' if is_cn else '## Solutions' + content = content[: content.find(start)] + start + '\n\n' + end + with open(path, "w", encoding="utf-8") as f: + f.write(content) if __name__ == "__main__": - # extract_code() + extract_code() extract_solution_paragraph() diff --git a/solution/0000-0099/0001.Two Sum/README.md b/solution/0000-0099/0001.Two Sum/README.md index 0ebec1acbca10..1d5329e34f6a7 100644 --- a/solution/0000-0099/0001.Two Sum/README.md +++ b/solution/0000-0099/0001.Two Sum/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以用哈希表 $m$ 存放数组值以及对应的下标。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: @@ -80,10 +74,6 @@ class Solution: m[x] = i ``` -### **Java** - - - ```java class Solution { public int[] twoSum(int[] nums, int target) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func twoSum(nums []int, target int) []int { m := map[int]int{} @@ -135,7 +121,41 @@ func twoSum(nums []int, target int) []int { } ``` -### **JavaScript** +```ts +function twoSum(nums: number[], target: number): number[] { + const m: Map = new Map(); + + for (let i = 0; ; ++i) { + const x = nums[i]; + const y = target - x; + + if (m.has(y)) { + return [m.get(y)!, i]; + } + + m.set(x, i); + } +} +``` + +```rust +use std::collections::HashMap; + +impl Solution { + pub fn two_sum(nums: Vec, target: i32) -> Vec { + let mut map = HashMap::new(); + for (i, item) in nums.iter().enumerate() { + if map.contains_key(item) { + return vec![i as i32, map[item]]; + } else { + let x = target - nums[i]; + map.insert(x, i as i32); + } + } + unreachable!() + } +} +``` ```js /** @@ -156,8 +176,6 @@ var twoSum = function (nums, target) { }; ``` -### **C#** - ```cs public class Solution { public int[] TwoSum(int[] nums, int target) { @@ -176,7 +194,42 @@ public class Solution { } ``` -### **Swift** +```php +class Solution { + /** + * @param Integer[] $nums + * @param Integer $target + * @return Integer[] + */ + function twoSum($nums, $target) { + foreach ($nums as $key => $x) { + $y = $target - $x; + if (isset($hashtable[$y])) { + return [$hashtable[$y], $key]; + } + $hashtable[$x] = $key; + } + } +} +``` + +```scala +import scala.collection.mutable + +object Solution { + def twoSum(nums: Array[Int], target: Int): Array[Int] = { + var map = new mutable.HashMap[Int, Int]() + for (i <- 0 to nums.length) { + if (map.contains(target - nums(i))) { + return Array(map(target - nums(i)), i) + } else { + map += (nums(i) -> i) + } + } + Array(0, 0) + } +} +``` ```swift class Solution { @@ -196,29 +249,20 @@ class Solution { } ``` -### **Rust** - -```rust -use std::collections::HashMap; - -impl Solution { - pub fn two_sum(nums: Vec, target: i32) -> Vec { - let mut map = HashMap::new(); - for (i, item) in nums.iter().enumerate() { - if map.contains_key(item) { - return vec![i as i32, map[item]]; - } else { - let x = target - nums[i]; - map.insert(x, i as i32); - } - } - unreachable!() - } -} +```rb +# @param {Integer[]} nums +# @param {Integer} target +# @return {Integer[]} +def two_sum(nums, target) + nums.each_with_index do |x, idx| + if nums.include? target - x + return [idx, nums.index(target - x)] if nums.index(target - x) != idx + end + next + end +end ``` -### **Nim** - ```nim import std/enumerate @@ -234,50 +278,6 @@ proc twoSum(nums: seq[int], target: int): seq[int] = return @[idx, tdx] ``` -### **PHP** - -```php -class Solution { - /** - * @param Integer[] $nums - * @param Integer $target - * @return Integer[] - */ - function twoSum($nums, $target) { - foreach ($nums as $key => $x) { - $y = $target - $x; - if (isset($hashtable[$y])) { - return [$hashtable[$y], $key]; - } - $hashtable[$x] = $key; - } - } -} -``` - -### **TypeScript** - -```ts -function twoSum(nums: number[], target: number): number[] { - const m: Map = new Map(); - - for (let i = 0; ; ++i) { - const x = nums[i]; - const y = target - x; - - if (m.has(y)) { - return [m.get(y)!, i]; - } - - m.set(x, i); - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0001.Two Sum/README_EN.md b/solution/0000-0099/0001.Two Sum/README_EN.md index e6044cd68c879..74fd192d5dc19 100644 --- a/solution/0000-0099/0001.Two Sum/README_EN.md +++ b/solution/0000-0099/0001.Two Sum/README_EN.md @@ -48,7 +48,7 @@ ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We can use the hash table $m$ to store the array value and the corresponding subscript. @@ -58,8 +58,6 @@ The time complexity is $O(n)$ and the space complexity is $O(n)$. Where $n$ is t -### **Python3** - ```python class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: @@ -71,8 +69,6 @@ class Solution: m[x] = i ``` -### **Java** - ```java class Solution { public int[] twoSum(int[] nums, int target) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +102,6 @@ public: }; ``` -### **Go** - ```go func twoSum(nums []int, target int) []int { m := map[int]int{} @@ -124,69 +116,23 @@ func twoSum(nums []int, target int) []int { } ``` -### **C#** - -```cs -public class Solution { - public int[] TwoSum(int[] nums, int target) { - var m = new Dictionary(); - for (int i = 0, j; ; ++i) { - int x = nums[i]; - int y = target - x; - if (m.TryGetValue(y, out j)) { - return new [] {j, i}; - } - if (!m.ContainsKey(x)) { - m.Add(x, i); - } - } - } -} -``` - -### **JavaScript** +```ts +function twoSum(nums: number[], target: number): number[] { + const m: Map = new Map(); -```js -/** - * @param {number[]} nums - * @param {number} target - * @return {number[]} - */ -var twoSum = function (nums, target) { - const m = new Map(); for (let i = 0; ; ++i) { const x = nums[i]; const y = target - x; + if (m.has(y)) { - return [m.get(y), i]; + return [m.get(y)!, i]; } - m.set(x, i); - } -}; -``` -### **Swift** - -```swift -class Solution { - func twoSum(_ nums: [Int], _ target: Int) -> [Int] { - var m = [Int: Int]() - var i = 0 - while true { - let x = nums[i] - let y = target - nums[i] - if let j = m[target - nums[i]] { - return [j, i] - } - m[nums[i]] = i - i += 1 - } + m.set(x, i); } } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -206,24 +152,42 @@ impl Solution { } ``` -### **Nim** - -```nim -import std/enumerate - -proc twoSum(nums: seq[int], target: int): seq[int] = - var - bal: int - tdx: int - for idx, val in enumerate(nums): - bal = target - val - if bal in nums: - tdx = nums.find(bal) - if idx != tdx: - return @[idx, tdx] +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function (nums, target) { + const m = new Map(); + for (let i = 0; ; ++i) { + const x = nums[i]; + const y = target - x; + if (m.has(y)) { + return [m.get(y), i]; + } + m.set(x, i); + } +}; ``` -### **PHP** +```cs +public class Solution { + public int[] TwoSum(int[] nums, int target) { + var m = new Dictionary(); + for (int i = 0, j; ; ++i) { + int x = nums[i]; + int y = target - x; + if (m.TryGetValue(y, out j)) { + return new [] {j, i}; + } + if (!m.ContainsKey(x)) { + m.Add(x, i); + } + } + } +} +``` ```php class Solution { @@ -244,29 +208,71 @@ class Solution { } ``` -### **TypeScript** - -```ts -function twoSum(nums: number[], target: number): number[] { - const m: Map = new Map(); - - for (let i = 0; ; ++i) { - const x = nums[i]; - const y = target - x; +```scala +import scala.collection.mutable + +object Solution { + def twoSum(nums: Array[Int], target: Int): Array[Int] = { + var map = new mutable.HashMap[Int, Int]() + for (i <- 0 to nums.length) { + if (map.contains(target - nums(i))) { + return Array(map(target - nums(i)), i) + } else { + map += (nums(i) -> i) + } + } + Array(0, 0) + } +} +``` - if (m.has(y)) { - return [m.get(y)!, i]; +```swift +class Solution { + func twoSum(_ nums: [Int], _ target: Int) -> [Int] { + var m = [Int: Int]() + var i = 0 + while true { + let x = nums[i] + let y = target - nums[i] + if let j = m[target - nums[i]] { + return [j, i] + } + m[nums[i]] = i + i += 1 } - - m.set(x, i); } } ``` -### **...** - +```rb +# @param {Integer[]} nums +# @param {Integer} target +# @return {Integer[]} +def two_sum(nums, target) + nums.each_with_index do |x, idx| + if nums.include? target - x + return [idx, nums.index(target - x)] if nums.index(target - x) != idx + end + next + end +end ``` +```nim +import std/enumerate + +proc twoSum(nums: seq[int], target: int): seq[int] = + var + bal: int + tdx: int + for idx, val in enumerate(nums): + bal = target - val + if bal in nums: + tdx = nums.find(bal) + if idx != tdx: + return @[idx, tdx] ``` + + diff --git a/solution/0000-0099/0002.Add Two Numbers/README.md b/solution/0000-0099/0002.Add Two Numbers/README.md index 4c93234ccee35..656406951192e 100644 --- a/solution/0000-0099/0002.Add Two Numbers/README.md +++ b/solution/0000-0099/0002.Add Two Numbers/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们同时遍历两个链表 $l_1$ 和 $l_2$,并使用变量 $carry$ 表示当前是否有进位。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -88,10 +82,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -153,71 +141,6 @@ public: }; ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} l1 - * @param {ListNode} l2 - * @return {ListNode} - */ -var addTwoNumbers = function (l1, l2) { - const dummy = new ListNode(); - let carry = 0; - let cur = dummy; - while (l1 || l2 || carry) { - const s = (l1?.val || 0) + (l2?.val || 0) + carry; - carry = Math.floor(s / 10); - cur.next = new ListNode(s % 10); - cur = cur.next; - l1 = l1?.next; - l2 = l2?.next; - } - return dummy.next; -}; -``` - -### **C#** - -```cs -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { - ListNode dummy = new ListNode(); - int carry = 0; - ListNode cur = dummy; - while (l1 != null || l2 != null || carry != 0) { - int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; - carry = s / 10; - cur.next = new ListNode(s % 10); - cur = cur.next; - l1 = l1 == null ? null : l1.next; - l2 = l2 == null ? null : l2.next; - } - return dummy.next; - } -} -``` - -### **Go** - ```go /** * Definition for singly-linked list. @@ -252,107 +175,6 @@ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { } ``` -### **Ruby** - -```rb -# Definition for singly-linked list. -# class ListNode -# attr_accessor :val, :next -# def initialize(val = 0, _next = nil) -# @val = val -# @next = _next -# end -# end -# @param {ListNode} l1 -# @param {ListNode} l2 -# @return {ListNode} -def add_two_numbers(l1, l2) - dummy = ListNode.new() - carry = 0 - cur = dummy - while !l1.nil? || !l2.nil? || carry > 0 - s = (l1.nil? ? 0 : l1.val) + (l2.nil? ? 0 : l2.val) + carry - carry = s / 10 - cur.next = ListNode.new(s % 10) - cur = cur.next - l1 = l1.nil? ? l1 : l1.next - l2 = l2.nil? ? l2 : l2.next - end - dummy.next -end -``` - -### **Swift** - -```swift -/** - * Definition for singly-linked list. - * public class ListNode { - * public var val: Int - * public var next: ListNode? - * public init() { self.val = 0; self.next = nil; } - * public init(_ val: Int) { self.val = val; self.next = nil; } - * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } - * } - */ -class Solution { - func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { - var dummy = ListNode.init() - var carry = 0 - var l1 = l1 - var l2 = l2 - var cur = dummy - while l1 != nil || l2 != nil || carry != 0 { - let s = (l1?.val ?? 0) + (l2?.val ?? 0) + carry - carry = s / 10 - cur.next = ListNode.init(s % 10) - cur = cur.next! - l1 = l1?.next - l2 = l2?.next - } - return dummy.next - } -} -``` - -### **Nim** - -```nim -#[ - # Driver code in the solution file - # Definition for singly-linked list. - type - Node[int] = ref object - value: int - next: Node[int] - - SinglyLinkedList[T] = object - head, tail: Node[T] -]# - -# More efficient code churning ... -proc addTwoNumbers(l1: var SinglyLinkedList, l2: var SinglyLinkedList): SinglyLinkedList[int] = - var - aggregate: SinglyLinkedList - psum: seq[char] - temp_la, temp_lb: seq[int] - - while not l1.head.isNil: - temp_la.add(l1.head.value) - l1.head = l1.head.next - - while not l2.head.isNil: - temp_lb.add(l2.head.value) - l2.head = l2.head.next - - psum = reversed($(reversed(temp_la).join("").parseInt() + reversed(temp_lb).join("").parseInt())) - for i in psum: aggregate.append(($i).parseInt()) - - result = aggregate -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -387,8 +209,6 @@ function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | nul } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -432,7 +252,64 @@ impl Solution { } ``` -### **PHP** +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function (l1, l2) { + const dummy = new ListNode(); + let carry = 0; + let cur = dummy; + while (l1 || l2 || carry) { + const s = (l1?.val || 0) + (l2?.val || 0) + carry; + carry = Math.floor(s / 10); + cur.next = new ListNode(s % 10); + cur = cur.next; + l1 = l1?.next; + l2 = l2?.next; + } + return dummy.next; +}; +``` + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(); + int carry = 0; + ListNode cur = dummy; + while (l1 != null || l2 != null || carry != 0) { + int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; + carry = s / 10; + cur.next = new ListNode(s % 10); + cur = cur.next; + l1 = l1 == null ? null : l1.next; + l2 = l2 == null ? null : l2.next; + } + return dummy.next; + } +} +``` ```php /** @@ -484,10 +361,99 @@ class Solution { } ``` -### **...** +```swift +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +class Solution { + func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { + var dummy = ListNode.init() + var carry = 0 + var l1 = l1 + var l2 = l2 + var cur = dummy + while l1 != nil || l2 != nil || carry != 0 { + let s = (l1?.val ?? 0) + (l2?.val ?? 0) + carry + carry = s / 10 + cur.next = ListNode.init(s % 10) + cur = cur.next! + l1 = l1?.next + l2 = l2?.next + } + return dummy.next + } +} +``` +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} l1 +# @param {ListNode} l2 +# @return {ListNode} +def add_two_numbers(l1, l2) + dummy = ListNode.new() + carry = 0 + cur = dummy + while !l1.nil? || !l2.nil? || carry > 0 + s = (l1.nil? ? 0 : l1.val) + (l2.nil? ? 0 : l2.val) + carry + carry = s / 10 + cur.next = ListNode.new(s % 10) + cur = cur.next + l1 = l1.nil? ? l1 : l1.next + l2 = l2.nil? ? l2 : l2.next + end + dummy.next +end ``` +```nim +#[ + # Driver code in the solution file + # Definition for singly-linked list. + type + Node[int] = ref object + value: int + next: Node[int] + + SinglyLinkedList[T] = object + head, tail: Node[T] +]# + +# More efficient code churning ... +proc addTwoNumbers(l1: var SinglyLinkedList, l2: var SinglyLinkedList): SinglyLinkedList[int] = + var + aggregate: SinglyLinkedList + psum: seq[char] + temp_la, temp_lb: seq[int] + + while not l1.head.isNil: + temp_la.add(l1.head.value) + l1.head = l1.head.next + + while not l2.head.isNil: + temp_lb.add(l2.head.value) + l2.head = l2.head.next + + psum = reversed($(reversed(temp_la).join("").parseInt() + reversed(temp_lb).join("").parseInt())) + for i in psum: aggregate.append(($i).parseInt()) + + result = aggregate ``` + + diff --git a/solution/0000-0099/0002.Add Two Numbers/README_EN.md b/solution/0000-0099/0002.Add Two Numbers/README_EN.md index 835f7c5b844a5..fb3465868aaf6 100644 --- a/solution/0000-0099/0002.Add Two Numbers/README_EN.md +++ b/solution/0000-0099/0002.Add Two Numbers/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We traverse two linked lists $l_1$ and $l_2$ at the same time, and use the variable $carry$ to indicate whether there is a carry. @@ -54,8 +54,6 @@ The time complexity is $O(\max (m, n))$, where $m$ and $n$ are the lengths of th -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -78,8 +76,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -141,71 +135,6 @@ public: }; ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} l1 - * @param {ListNode} l2 - * @return {ListNode} - */ -var addTwoNumbers = function (l1, l2) { - const dummy = new ListNode(); - let carry = 0; - let cur = dummy; - while (l1 || l2 || carry) { - const s = (l1?.val || 0) + (l2?.val || 0) + carry; - carry = Math.floor(s / 10); - cur.next = new ListNode(s % 10); - cur = cur.next; - l1 = l1?.next; - l2 = l2?.next; - } - return dummy.next; -}; -``` - -### **C#** - -```cs -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { - ListNode dummy = new ListNode(); - int carry = 0; - ListNode cur = dummy; - while (l1 != null || l2 != null || carry != 0) { - int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; - carry = s / 10; - cur.next = new ListNode(s % 10); - cur = cur.next; - l1 = l1 == null ? null : l1.next; - l2 = l2 == null ? null : l2.next; - } - return dummy.next; - } -} -``` - -### **Go** - ```go /** * Definition for singly-linked list. @@ -240,107 +169,6 @@ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { } ``` -### **Ruby** - -```rb -# Definition for singly-linked list. -# class ListNode -# attr_accessor :val, :next -# def initialize(val = 0, _next = nil) -# @val = val -# @next = _next -# end -# end -# @param {ListNode} l1 -# @param {ListNode} l2 -# @return {ListNode} -def add_two_numbers(l1, l2) - dummy = ListNode.new() - carry = 0 - cur = dummy - while !l1.nil? || !l2.nil? || carry > 0 - s = (l1.nil? ? 0 : l1.val) + (l2.nil? ? 0 : l2.val) + carry - carry = s / 10 - cur.next = ListNode.new(s % 10) - cur = cur.next - l1 = l1.nil? ? l1 : l1.next - l2 = l2.nil? ? l2 : l2.next - end - dummy.next -end -``` - -### **Swift** - -```swift -/** - * Definition for singly-linked list. - * public class ListNode { - * public var val: Int - * public var next: ListNode? - * public init() { self.val = 0; self.next = nil; } - * public init(_ val: Int) { self.val = val; self.next = nil; } - * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } - * } - */ -class Solution { - func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { - var dummy = ListNode.init() - var carry = 0 - var l1 = l1 - var l2 = l2 - var cur = dummy - while l1 != nil || l2 != nil || carry != 0 { - let s = (l1?.val ?? 0) + (l2?.val ?? 0) + carry - carry = s / 10 - cur.next = ListNode.init(s % 10) - cur = cur.next! - l1 = l1?.next - l2 = l2?.next - } - return dummy.next - } -} -``` - -### **Nim** - -```nim -#[ - # Driver code in the solution file - # Definition for singly-linked list. - type - Node[int] = ref object - value: int - next: Node[int] - - SinglyLinkedList[T] = object - head, tail: Node[T] -]# - -# More efficient code churning ... -proc addTwoNumbers(l1: var SinglyLinkedList, l2: var SinglyLinkedList): SinglyLinkedList[int] = - var - aggregate: SinglyLinkedList - psum: seq[char] - temp_la, temp_lb: seq[int] - - while not l1.head.isNil: - temp_la.add(l1.head.value) - l1.head = l1.head.next - - while not l2.head.isNil: - temp_lb.add(l2.head.value) - l2.head = l2.head.next - - psum = reversed($(reversed(temp_la).join("").parseInt() + reversed(temp_lb).join("").parseInt())) - for i in psum: aggregate.append(($i).parseInt()) - - result = aggregate -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -375,8 +203,6 @@ function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | nul } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -420,7 +246,64 @@ impl Solution { } ``` -### **PHP** +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function (l1, l2) { + const dummy = new ListNode(); + let carry = 0; + let cur = dummy; + while (l1 || l2 || carry) { + const s = (l1?.val || 0) + (l2?.val || 0) + carry; + carry = Math.floor(s / 10); + cur.next = new ListNode(s % 10); + cur = cur.next; + l1 = l1?.next; + l2 = l2?.next; + } + return dummy.next; +}; +``` + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(); + int carry = 0; + ListNode cur = dummy; + while (l1 != null || l2 != null || carry != 0) { + int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; + carry = s / 10; + cur.next = new ListNode(s % 10); + cur = cur.next; + l1 = l1 == null ? null : l1.next; + l2 = l2 == null ? null : l2.next; + } + return dummy.next; + } +} +``` ```php /** @@ -472,10 +355,99 @@ class Solution { } ``` -### **...** +```swift +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +class Solution { + func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { + var dummy = ListNode.init() + var carry = 0 + var l1 = l1 + var l2 = l2 + var cur = dummy + while l1 != nil || l2 != nil || carry != 0 { + let s = (l1?.val ?? 0) + (l2?.val ?? 0) + carry + carry = s / 10 + cur.next = ListNode.init(s % 10) + cur = cur.next! + l1 = l1?.next + l2 = l2?.next + } + return dummy.next + } +} +``` +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} l1 +# @param {ListNode} l2 +# @return {ListNode} +def add_two_numbers(l1, l2) + dummy = ListNode.new() + carry = 0 + cur = dummy + while !l1.nil? || !l2.nil? || carry > 0 + s = (l1.nil? ? 0 : l1.val) + (l2.nil? ? 0 : l2.val) + carry + carry = s / 10 + cur.next = ListNode.new(s % 10) + cur = cur.next + l1 = l1.nil? ? l1 : l1.next + l2 = l2.nil? ? l2 : l2.next + end + dummy.next +end ``` +```nim +#[ + # Driver code in the solution file + # Definition for singly-linked list. + type + Node[int] = ref object + value: int + next: Node[int] + + SinglyLinkedList[T] = object + head, tail: Node[T] +]# + +# More efficient code churning ... +proc addTwoNumbers(l1: var SinglyLinkedList, l2: var SinglyLinkedList): SinglyLinkedList[int] = + var + aggregate: SinglyLinkedList + psum: seq[char] + temp_la, temp_lb: seq[int] + + while not l1.head.isNil: + temp_la.add(l1.head.value) + l1.head = l1.head.next + + while not l2.head.isNil: + temp_lb.add(l2.head.value) + l2.head = l2.head.next + + psum = reversed($(reversed(temp_la).join("").parseInt() + reversed(temp_lb).join("").parseInt())) + for i in psum: aggregate.append(($i).parseInt()) + + result = aggregate ``` + + diff --git a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/README.md b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/README.md index c1f1114a6ce4c..91ce27aa8aeb3 100644 --- a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/README.md +++ b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:双指针 + 哈希表** +### 方法一:双指针 + 哈希表 定义一个哈希表记录当前窗口内出现的字符,记 $i$ 和 $j$ 分别表示不重复子串的开始位置和结束位置,无重复字符子串的最大长度记为 `ans`。 @@ -71,10 +69,6 @@ for (int i = 0, j = 0; i < n; ++i) { -### **Python3** - - - ```python class Solution: def lengthOfLongestSubstring(self, s: str) -> int: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int lengthOfLongestSubstring(String s) { @@ -111,27 +101,6 @@ class Solution { } ``` -```java -class Solution { - public int lengthOfLongestSubstring(String s) { - boolean[] ss = new boolean[128]; - int ans = 0, j = 0; - int n = s.length(); - for (int i = 0; i < n; ++i) { - char c = s.charAt(i); - while (ss[c]) { - ss[s.charAt(j++)] = false; - } - ans = Math.max(ans, i - j + 1); - ss[c] = true; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -148,27 +117,6 @@ public: }; ``` -```cpp -class Solution { -public: - int lengthOfLongestSubstring(string s) { - bool ss[128] = {false}; - int n = s.size(); - int ans = 0; - for (int i = 0, j = 0; i < n; ++i) { - while (ss[s[i]]) { - ss[s[j++]] = false; - } - ss[s[i]] = true; - ans = max(ans, i - j + 1); - } - return ans; - } -}; -``` - -### **Go** - ```go func lengthOfLongestSubstring(s string) int { ss := map[byte]bool{} @@ -185,23 +133,44 @@ func lengthOfLongestSubstring(s string) int { } ``` -```go -func lengthOfLongestSubstring(s string) (ans int) { - ss := make([]bool, 128) - j := 0 - for i, c := range s { - for ss[c] { - ss[s[j]] = false - j++ - } - ss[c] = true - ans = max(ans, i-j+1) - } - return +```ts +function lengthOfLongestSubstring(s: string): number { + let ans = 0; + const vis = new Set(); + for (let i = 0, j = 0; i < s.length; ++i) { + while (vis.has(s[i])) { + vis.delete(s[j++]); + } + vis.add(s[i]); + ans = Math.max(ans, i - j + 1); + } + return ans; } ``` -### **JavaScript** +```rust +use std::collections::HashSet; + +impl Solution { + pub fn length_of_longest_substring(s: String) -> i32 { + let s = s.as_bytes(); + let mut set = HashSet::new(); + let mut i = 0; + s + .iter() + .map(|c| { + while set.contains(&c) { + set.remove(&s[i]); + i += 1; + } + set.insert(c); + set.len() + }) + .max() + .unwrap_or(0) as i32 + } +} +``` ```js /** @@ -223,8 +192,6 @@ var lengthOfLongestSubstring = function (s) { }; ``` -### **C#** - ```cs public class Solution { public int LengthOfLongestSubstring(string s) { @@ -244,41 +211,33 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function lengthOfLongestSubstring(s: string): number { - let ans = 0; - const vis = new Set(); - for (let i = 0, j = 0; i < s.length; ++i) { - while (vis.has(s[i])) { - vis.delete(s[j++]); - } - vis.add(s[i]); - ans = Math.max(ans, i - j + 1); - } - return ans; -} -``` - -```ts -function lengthOfLongestSubstring(s: string): number { - let ans = 0; - const n = s.length; - const ss: boolean[] = new Array(128).fill(false); - for (let i = 0, j = 0; i < n; ++i) { - while (ss[s[i]]) { - ss[s[j++]] = false; +```php +class Solution { + /** + * @param String $s + * @return Integer + */ + function lengthOfLongestSubstring($s) { + $max = 0; + for ($i = 0; $i < strlen($s); $i++) { + $chars = []; + $sub = ''; + for ($j = $i; $j < strlen($s); $j++) { + if (in_array($s[$j], $chars)) { + break; + } + $sub .= $s[$j]; + $chars[] = $s[$j]; + } + if (strlen($sub) > $max) { + $max = strlen($sub); + } } - ss[s[i]] = true; - ans = Math.max(ans, i - j + 1); + return $max; } - return ans; } ``` -### **Swift** - ```swift class Solution { func lengthOfLongestSubstring(_ s: String) -> Int { @@ -301,8 +260,6 @@ class Solution { } ``` -### **Nim** - ```nim proc lengthOfLongestSubstring(s: string): int = var @@ -323,65 +280,82 @@ proc lengthOfLongestSubstring(s: string): int = result = res # result has the default return value ``` -### **Rust** + -```rust -use std::collections::HashSet; +### 方法二 -impl Solution { - pub fn length_of_longest_substring(s: String) -> i32 { - let s = s.as_bytes(); - let mut set = HashSet::new(); - let mut i = 0; - s - .iter() - .map(|c| { - while set.contains(&c) { - set.remove(&s[i]); - i += 1; - } - set.insert(c); - set.len() - }) - .max() - .unwrap_or(0) as i32 + + +```java +class Solution { + public int lengthOfLongestSubstring(String s) { + boolean[] ss = new boolean[128]; + int ans = 0, j = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + char c = s.charAt(i); + while (ss[c]) { + ss[s.charAt(j++)] = false; + } + ans = Math.max(ans, i - j + 1); + ss[c] = true; + } + return ans; } } ``` -### **PHP** - -```php +```cpp class Solution { - /** - * @param String $s - * @return Integer - */ - function lengthOfLongestSubstring($s) { - $max = 0; - for ($i = 0; $i < strlen($s); $i++) { - $chars = []; - $sub = ''; - for ($j = $i; $j < strlen($s); $j++) { - if (in_array($s[$j], $chars)) { - break; - } - $sub .= $s[$j]; - $chars[] = $s[$j]; - } - if (strlen($sub) > $max) { - $max = strlen($sub); +public: + int lengthOfLongestSubstring(string s) { + bool ss[128] = {false}; + int n = s.size(); + int ans = 0; + for (int i = 0, j = 0; i < n; ++i) { + while (ss[s[i]]) { + ss[s[j++]] = false; } + ss[s[i]] = true; + ans = max(ans, i - j + 1); } - return $max; + return ans; } -} +}; ``` -### **...** - +```go +func lengthOfLongestSubstring(s string) (ans int) { + ss := make([]bool, 128) + j := 0 + for i, c := range s { + for ss[c] { + ss[s[j]] = false + j++ + } + ss[c] = true + ans = max(ans, i-j+1) + } + return +} ``` +```ts +function lengthOfLongestSubstring(s: string): number { + let ans = 0; + const n = s.length; + const ss: boolean[] = new Array(128).fill(false); + for (let i = 0, j = 0; i < n; ++i) { + while (ss[s[i]]) { + ss[s[j++]] = false; + } + ss[s[i]] = true; + ans = Math.max(ans, i - j + 1); + } + return ans; +} ``` + + diff --git a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/README_EN.md b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/README_EN.md index b81860c895c4d..7167c35dc6c40 100644 --- a/solution/0000-0099/0003.Longest Substring Without Repeating Characters/README_EN.md +++ b/solution/0000-0099/0003.Longest Substring Without Repeating Characters/README_EN.md @@ -42,7 +42,7 @@ Notice that the answer must be a substring, "pwke" is a subsequence an ## Solutions -**Solution 1: Two pointers + Hash Table** +### Solution 1: Two pointers + Hash Table Define a hash table to record the characters in the current window. Let $i$ and $j$ represent the start and end positions of the non-repeating substring, respectively. The length of the longest non-repeating substring is recorded by `ans`. @@ -65,8 +65,6 @@ for (int i = 0, j = 0; i < n; ++i) { -### **Python3** - ```python class Solution: def lengthOfLongestSubstring(self, s: str) -> int: @@ -81,8 +79,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int lengthOfLongestSubstring(String s) { @@ -101,27 +97,6 @@ class Solution { } ``` -```java -class Solution { - public int lengthOfLongestSubstring(String s) { - boolean[] ss = new boolean[128]; - int ans = 0, j = 0; - int n = s.length(); - for (int i = 0; i < n; ++i) { - char c = s.charAt(i); - while (ss[c]) { - ss[s.charAt(j++)] = false; - } - ans = Math.max(ans, i - j + 1); - ss[c] = true; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -138,27 +113,6 @@ public: }; ``` -```cpp -class Solution { -public: - int lengthOfLongestSubstring(string s) { - bool ss[128] = {false}; - int n = s.size(); - int ans = 0; - for (int i = 0, j = 0; i < n; ++i) { - while (ss[s[i]]) { - ss[s[j++]] = false; - } - ss[s[i]] = true; - ans = max(ans, i - j + 1); - } - return ans; - } -}; -``` - -### **Go** - ```go func lengthOfLongestSubstring(s string) int { ss := map[byte]bool{} @@ -175,23 +129,44 @@ func lengthOfLongestSubstring(s string) int { } ``` -```go -func lengthOfLongestSubstring(s string) (ans int) { - ss := make([]bool, 128) - j := 0 - for i, c := range s { - for ss[c] { - ss[s[j]] = false - j++ - } - ss[c] = true - ans = max(ans, i-j+1) - } - return +```ts +function lengthOfLongestSubstring(s: string): number { + let ans = 0; + const vis = new Set(); + for (let i = 0, j = 0; i < s.length; ++i) { + while (vis.has(s[i])) { + vis.delete(s[j++]); + } + vis.add(s[i]); + ans = Math.max(ans, i - j + 1); + } + return ans; } ``` -### **JavaScript** +```rust +use std::collections::HashSet; + +impl Solution { + pub fn length_of_longest_substring(s: String) -> i32 { + let s = s.as_bytes(); + let mut set = HashSet::new(); + let mut i = 0; + s + .iter() + .map(|c| { + while set.contains(&c) { + set.remove(&s[i]); + i += 1; + } + set.insert(c); + set.len() + }) + .max() + .unwrap_or(0) as i32 + } +} +``` ```js /** @@ -213,8 +188,6 @@ var lengthOfLongestSubstring = function (s) { }; ``` -### **C#** - ```cs public class Solution { public int LengthOfLongestSubstring(string s) { @@ -234,41 +207,33 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function lengthOfLongestSubstring(s: string): number { - let ans = 0; - const vis = new Set(); - for (let i = 0, j = 0; i < s.length; ++i) { - while (vis.has(s[i])) { - vis.delete(s[j++]); - } - vis.add(s[i]); - ans = Math.max(ans, i - j + 1); - } - return ans; -} -``` - -```ts -function lengthOfLongestSubstring(s: string): number { - let ans = 0; - const n = s.length; - const ss: boolean[] = new Array(128).fill(false); - for (let i = 0, j = 0; i < n; ++i) { - while (ss[s[i]]) { - ss[s[j++]] = false; +```php +class Solution { + /** + * @param String $s + * @return Integer + */ + function lengthOfLongestSubstring($s) { + $max = 0; + for ($i = 0; $i < strlen($s); $i++) { + $chars = []; + $sub = ''; + for ($j = $i; $j < strlen($s); $j++) { + if (in_array($s[$j], $chars)) { + break; + } + $sub .= $s[$j]; + $chars[] = $s[$j]; + } + if (strlen($sub) > $max) { + $max = strlen($sub); + } } - ss[s[i]] = true; - ans = Math.max(ans, i - j + 1); + return $max; } - return ans; } ``` -### **Swift** - ```swift class Solution { func lengthOfLongestSubstring(_ s: String) -> Int { @@ -291,8 +256,6 @@ class Solution { } ``` -### **Nim** - ```nim proc lengthOfLongestSubstring(s: string): int = var @@ -313,65 +276,82 @@ proc lengthOfLongestSubstring(s: string): int = result = res # result has the default return value ``` -### **Rust** + -```rust -use std::collections::HashSet; +### Solution 2 -impl Solution { - pub fn length_of_longest_substring(s: String) -> i32 { - let s = s.as_bytes(); - let mut set = HashSet::new(); - let mut i = 0; - s - .iter() - .map(|c| { - while set.contains(&c) { - set.remove(&s[i]); - i += 1; - } - set.insert(c); - set.len() - }) - .max() - .unwrap_or(0) as i32 + + +```java +class Solution { + public int lengthOfLongestSubstring(String s) { + boolean[] ss = new boolean[128]; + int ans = 0, j = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + char c = s.charAt(i); + while (ss[c]) { + ss[s.charAt(j++)] = false; + } + ans = Math.max(ans, i - j + 1); + ss[c] = true; + } + return ans; } } ``` -### **PHP** - -```php +```cpp class Solution { - /** - * @param String $s - * @return Integer - */ - function lengthOfLongestSubstring($s) { - $max = 0; - for ($i = 0; $i < strlen($s); $i++) { - $chars = []; - $sub = ''; - for ($j = $i; $j < strlen($s); $j++) { - if (in_array($s[$j], $chars)) { - break; - } - $sub .= $s[$j]; - $chars[] = $s[$j]; - } - if (strlen($sub) > $max) { - $max = strlen($sub); +public: + int lengthOfLongestSubstring(string s) { + bool ss[128] = {false}; + int n = s.size(); + int ans = 0; + for (int i = 0, j = 0; i < n; ++i) { + while (ss[s[i]]) { + ss[s[j++]] = false; } + ss[s[i]] = true; + ans = max(ans, i - j + 1); } - return $max; + return ans; } -} +}; ``` -### **...** - +```go +func lengthOfLongestSubstring(s string) (ans int) { + ss := make([]bool, 128) + j := 0 + for i, c := range s { + for ss[c] { + ss[s[j]] = false + j++ + } + ss[c] = true + ans = max(ans, i-j+1) + } + return +} ``` +```ts +function lengthOfLongestSubstring(s: string): number { + let ans = 0; + const n = s.length; + const ss: boolean[] = new Array(128).fill(false); + for (let i = 0, j = 0; i < n; ++i) { + while (ss[s[i]]) { + ss[s[j++]] = false; + } + ss[s[i]] = true; + ans = Math.max(ans, i - j + 1); + } + return ans; +} ``` + + diff --git a/solution/0000-0099/0004.Median of Two Sorted Arrays/README.md b/solution/0000-0099/0004.Median of Two Sorted Arrays/README.md index 38bed5936b324..839cecea32014 100644 --- a/solution/0000-0099/0004.Median of Two Sorted Arrays/README.md +++ b/solution/0000-0099/0004.Median of Two Sorted Arrays/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:分治** +### 方法一:分治 题目要求算法的时间复杂度为 $O(\log (m + n))$,因此不能直接遍历两个数组,而是需要使用二分查找的方法。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: @@ -93,10 +87,6 @@ class Solution: return (a + b) / 2 ``` -### **Java** - - - ```java class Solution { private int m; @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { m, n := len(nums1), len(nums2) @@ -195,8 +181,6 @@ func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { } ``` -### **TypeScript** - ```ts function findMedianSortedArrays(nums1: number[], nums2: number[]): number { const m = nums1.length; @@ -222,8 +206,6 @@ function findMedianSortedArrays(nums1: number[], nums2: number[]): number { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums1 @@ -254,8 +236,6 @@ var findMedianSortedArrays = function (nums1, nums2) { }; ``` -### **C#** - ```cs public class Solution { private int m; @@ -291,10 +271,29 @@ public class Solution { } ``` -### **...** +```nim +import std/[algorithm, sequtils] -``` +proc medianOfTwoSortedArrays(nums1: seq[int], nums2: seq[int]): float = + var + fullList: seq[int] = concat(nums1, nums2) + value: int = fullList.len div 2 + + fullList.sort() + if fullList.len mod 2 == 0: + result = (fullList[value - 1] + fullList[value]) / 2 + else: + result = fullList[value].toFloat() + +# Driver Code + +# var +# arrA: seq[int] = @[1, 2] +# arrB: seq[int] = @[3, 4, 5] +# echo medianOfTwoSortedArrays(arrA, arrB) ``` + + diff --git a/solution/0000-0099/0004.Median of Two Sorted Arrays/README_EN.md b/solution/0000-0099/0004.Median of Two Sorted Arrays/README_EN.md index 18dd287d08aec..044bb180b05d3 100644 --- a/solution/0000-0099/0004.Median of Two Sorted Arrays/README_EN.md +++ b/solution/0000-0099/0004.Median of Two Sorted Arrays/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Divide and Conquer** +### Solution 1: Divide and Conquer The problem requires the time complexity of the algorithm to be $O(\log (m + n))$, so we cannot directly traverse the two arrays, but need to use the binary search method. @@ -60,8 +60,6 @@ The time complexity is $O(\log(m + n))$, and the space complexity is $O(\log(m + -### **Python3** - ```python class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: @@ -83,8 +81,6 @@ class Solution: return (a + b) / 2 ``` -### **Java** - ```java class Solution { private int m; @@ -120,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +143,6 @@ public: }; ``` -### **Go** - ```go func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { m, n := len(nums1), len(nums2) @@ -183,8 +175,6 @@ func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { } ``` -### **TypeScript** - ```ts function findMedianSortedArrays(nums1: number[], nums2: number[]): number { const m = nums1.length; @@ -210,8 +200,6 @@ function findMedianSortedArrays(nums1: number[], nums2: number[]): number { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums1 @@ -242,8 +230,6 @@ var findMedianSortedArrays = function (nums1, nums2) { }; ``` -### **C#** - ```cs public class Solution { private int m; @@ -279,10 +265,29 @@ public class Solution { } ``` -### **...** +```nim +import std/[algorithm, sequtils] -``` +proc medianOfTwoSortedArrays(nums1: seq[int], nums2: seq[int]): float = + var + fullList: seq[int] = concat(nums1, nums2) + value: int = fullList.len div 2 + + fullList.sort() + if fullList.len mod 2 == 0: + result = (fullList[value - 1] + fullList[value]) / 2 + else: + result = fullList[value].toFloat() + +# Driver Code + +# var +# arrA: seq[int] = @[1, 2] +# arrB: seq[int] = @[3, 4, 5] +# echo medianOfTwoSortedArrays(arrA, arrB) ``` + + diff --git a/solution/0000-0099/0005.Longest Palindromic Substring/README.md b/solution/0000-0099/0005.Longest Palindromic Substring/README.md index f3e895b5a171a..1922159a8e432 100644 --- a/solution/0000-0099/0005.Longest Palindromic Substring/README.md +++ b/solution/0000-0099/0005.Longest Palindromic Substring/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示字符串 $s[i..j]$ 是否为回文串,初始时 $f[i][j] = true$。 @@ -52,18 +50,8 @@ 时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是字符串 $s$ 的长度。 -**方法二:枚举回文中间点** - -我们可以枚举回文中间点,向两边扩散,找到最长的回文串。 - -时间复杂度 $O(n^2)$,空间复杂度 $O(1)$。其中 $n$ 是字符串 $s$ 的长度。 - -### **Python3** - - - ```python class Solution: def longestPalindrome(self, s: str) -> str: @@ -80,30 +68,6 @@ class Solution: return s[k : k + mx] ``` -```python -class Solution: - def longestPalindrome(self, s: str) -> str: - def f(l, r): - while l >= 0 and r < n and s[l] == s[r]: - l, r = l - 1, r + 1 - return r - l - 1 - - n = len(s) - start, mx = 0, 1 - for i in range(n): - a = f(i, i) - b = f(i, i + 1) - t = max(a, b) - if mx < t: - mx = t - start = i - ((t - 1) >> 1) - return s[start : start + mx] -``` - -### **Java** - - - ```java class Solution { public String longestPalindrome(String s) { @@ -130,39 +94,6 @@ class Solution { } ``` -```java -class Solution { - private String s; - private int n; - - public String longestPalindrome(String s) { - this.s = s; - n = s.length(); - int start = 0, mx = 1; - for (int i = 0; i < n; ++i) { - int a = f(i, i); - int b = f(i, i + 1); - int t = Math.max(a, b); - if (mx < t) { - mx = t; - start = i - ((t - 1) >> 1); - } - } - return s.substring(start, start + mx); - } - - private int f(int l, int r) { - while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) { - --l; - ++r; - } - return r - l - 1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -187,34 +118,6 @@ public: }; ``` -```cpp -class Solution { -public: - string longestPalindrome(string s) { - int n = s.size(); - int start = 0, mx = 1; - auto f = [&](int l, int r) { - while (l >= 0 && r < n && s[l] == s[r]) { - l--, r++; - } - return r - l - 1; - }; - for (int i = 0; i < n; ++i) { - int a = f(i, i); - int b = f(i, i + 1); - int t = max(a, b); - if (mx < t) { - mx = t; - start = i - (t - 1 >> 1); - } - } - return s.substr(start, mx); - } -}; -``` - -### **Go** - ```go func longestPalindrome(s string) string { n := len(s) @@ -242,90 +145,6 @@ func longestPalindrome(s string) string { } ``` -```go -func longestPalindrome(s string) string { - n := len(s) - start, mx := 0, 1 - f := func(l, r int) int { - for l >= 0 && r < n && s[l] == s[r] { - l, r = l-1, r+1 - } - return r - l - 1 - } - for i := range s { - a, b := f(i, i), f(i, i+1) - t := max(a, b) - if mx < t { - mx = t - start = i - ((t - 1) >> 1) - } - } - return s[start : start+mx] -} -``` - -### **C#** - -```cs -public class Solution { - public string LongestPalindrome(string s) { - int n = s.Length; - bool[,] f = new bool[n, n]; - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; ++j) { - f[i, j] = true; - } - } - int k = 0, mx = 1; - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - f[i, j] = false; - if (s[i] == s[j]) { - f[i, j] = f[i + 1, j - 1]; - if (f[i, j] && mx < j - i + 1) { - mx = j - i + 1; - k = i; - } - } - } - } - return s.Substring(k, mx); - } -} -``` - -### **JavaScript** - -```js -/** - * @param {string} s - * @return {string} - */ -var longestPalindrome = function (s) { - const n = s.length; - const f = Array(n) - .fill(0) - .map(() => Array(n).fill(true)); - let k = 0; - let mx = 1; - for (let i = n - 2; i >= 0; --i) { - for (let j = i + 1; j < n; ++j) { - f[i][j] = false; - if (s[i] === s[j]) { - f[i][j] = f[i + 1][j - 1]; - if (f[i][j] && mx < j - i + 1) { - mx = j - i + 1; - k = i; - } - } - } - } - return s.slice(k, k + mx); -}; -``` - -### **TypeScript** - ```ts function longestPalindrome(s: string): string { const n = s.length; @@ -350,8 +169,6 @@ function longestPalindrome(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn longest_palindrome(s: String) -> String { @@ -374,38 +191,62 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn is_palindrome(s: &str) -> bool { - let mut chars = s.chars(); - while let (Some(c1), Some(c2)) = (chars.next(), chars.next_back()) { - if c1 != c2 { - return false; +```js +/** + * @param {string} s + * @return {string} + */ +var longestPalindrome = function (s) { + const n = s.length; + const f = Array(n) + .fill(0) + .map(() => Array(n).fill(true)); + let k = 0; + let mx = 1; + for (let i = n - 2; i >= 0; --i) { + for (let j = i + 1; j < n; ++j) { + f[i][j] = false; + if (s[i] === s[j]) { + f[i][j] = f[i + 1][j - 1]; + if (f[i][j] && mx < j - i + 1) { + mx = j - i + 1; + k = i; + } } } - true } + return s.slice(k, k + mx); +}; +``` - pub fn longest_palindrome(s: String) -> String { - let size = s.len(); - let mut ans = &s[..1]; - for i in 0..size - 1 { - for j in (i + 1..size).rev() { - if ans.len() > j - i + 1 { - break; - } - if Solution::is_palindrome(&s[i..=j]) { - ans = &s[i..=j]; +```cs +public class Solution { + public string LongestPalindrome(string s) { + int n = s.Length; + bool[,] f = new bool[n, n]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; ++j) { + f[i, j] = true; + } + } + int k = 0, mx = 1; + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + f[i, j] = false; + if (s[i] == s[j]) { + f[i, j] = f[i + 1, j - 1]; + if (f[i, j] && mx < j - i + 1) { + mx = j - i + 1; + k = i; + } } } } - return ans.to_string(); + return s.Substring(k, mx); } } ``` -### **Nim** - ```nim import std/sequtils @@ -430,10 +271,145 @@ proc longestPalindrome(s: string): string = result = s[start ..< start+mx] ``` -### **...** + + +### 方法二:枚举回文中间点 + +我们可以枚举回文中间点,向两边扩散,找到最长的回文串。 + +时间复杂度 $O(n^2)$,空间复杂度 $O(1)$。其中 $n$ 是字符串 $s$ 的长度。 + + +```python +class Solution: + def longestPalindrome(self, s: str) -> str: + def f(l, r): + while l >= 0 and r < n and s[l] == s[r]: + l, r = l - 1, r + 1 + return r - l - 1 + + n = len(s) + start, mx = 0, 1 + for i in range(n): + a = f(i, i) + b = f(i, i + 1) + t = max(a, b) + if mx < t: + mx = t + start = i - ((t - 1) >> 1) + return s[start : start + mx] ``` +```java +class Solution { + private String s; + private int n; + + public String longestPalindrome(String s) { + this.s = s; + n = s.length(); + int start = 0, mx = 1; + for (int i = 0; i < n; ++i) { + int a = f(i, i); + int b = f(i, i + 1); + int t = Math.max(a, b); + if (mx < t) { + mx = t; + start = i - ((t - 1) >> 1); + } + } + return s.substring(start, start + mx); + } + + private int f(int l, int r) { + while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) { + --l; + ++r; + } + return r - l - 1; + } +} +``` + +```cpp +class Solution { +public: + string longestPalindrome(string s) { + int n = s.size(); + int start = 0, mx = 1; + auto f = [&](int l, int r) { + while (l >= 0 && r < n && s[l] == s[r]) { + l--, r++; + } + return r - l - 1; + }; + for (int i = 0; i < n; ++i) { + int a = f(i, i); + int b = f(i, i + 1); + int t = max(a, b); + if (mx < t) { + mx = t; + start = i - (t - 1 >> 1); + } + } + return s.substr(start, mx); + } +}; +``` + +```go +func longestPalindrome(s string) string { + n := len(s) + start, mx := 0, 1 + f := func(l, r int) int { + for l >= 0 && r < n && s[l] == s[r] { + l, r = l-1, r+1 + } + return r - l - 1 + } + for i := range s { + a, b := f(i, i), f(i, i+1) + t := max(a, b) + if mx < t { + mx = t + start = i - ((t - 1) >> 1) + } + } + return s[start : start+mx] +} +``` + +```rust +impl Solution { + pub fn is_palindrome(s: &str) -> bool { + let mut chars = s.chars(); + while let (Some(c1), Some(c2)) = (chars.next(), chars.next_back()) { + if c1 != c2 { + return false; + } + } + true + } + + pub fn longest_palindrome(s: String) -> String { + let size = s.len(); + let mut ans = &s[..1]; + for i in 0..size - 1 { + for j in (i + 1..size).rev() { + if ans.len() > j - i + 1 { + break; + } + if Solution::is_palindrome(&s[i..=j]) { + ans = &s[i..=j]; + } + } + } + return ans.to_string(); + } +} ``` + + diff --git a/solution/0000-0099/0005.Longest Palindromic Substring/README_EN.md b/solution/0000-0099/0005.Longest Palindromic Substring/README_EN.md index 3cc788cd6b2c6..ccf126a3e3591 100644 --- a/solution/0000-0099/0005.Longest Palindromic Substring/README_EN.md +++ b/solution/0000-0099/0005.Longest Palindromic Substring/README_EN.md @@ -32,7 +32,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ to represent whether the string $s[i..j]$ is a palindrome, initially $f[i][j] = true$. @@ -44,16 +44,8 @@ Since $f[i][j]$ depends on $f[i + 1][j - 1]$, we need to ensure that $i + 1$ is The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string $s$. -**Solution 2: Enumerate Palindrome Midpoint** - -We can enumerate the midpoint of the palindrome, spread to both sides, and find the longest palindrome. - -The time complexity is $O(n^2)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string $s$. - -### **Python3** - ```python class Solution: def longestPalindrome(self, s: str) -> str: @@ -70,28 +62,6 @@ class Solution: return s[k : k + mx] ``` -```python -class Solution: - def longestPalindrome(self, s: str) -> str: - def f(l, r): - while l >= 0 and r < n and s[l] == s[r]: - l, r = l - 1, r + 1 - return r - l - 1 - - n = len(s) - start, mx = 0, 1 - for i in range(n): - a = f(i, i) - b = f(i, i + 1) - t = max(a, b) - if mx < t: - mx = t - start = i - ((t - 1) >> 1) - return s[start : start + mx] -``` - -### **Java** - ```java class Solution { public String longestPalindrome(String s) { @@ -118,39 +88,6 @@ class Solution { } ``` -```java -class Solution { - private String s; - private int n; - - public String longestPalindrome(String s) { - this.s = s; - n = s.length(); - int start = 0, mx = 1; - for (int i = 0; i < n; ++i) { - int a = f(i, i); - int b = f(i, i + 1); - int t = Math.max(a, b); - if (mx < t) { - mx = t; - start = i - ((t - 1) >> 1); - } - } - return s.substring(start, start + mx); - } - - private int f(int l, int r) { - while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) { - --l; - ++r; - } - return r - l - 1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -175,34 +112,6 @@ public: }; ``` -```cpp -class Solution { -public: - string longestPalindrome(string s) { - int n = s.size(); - int start = 0, mx = 1; - auto f = [&](int l, int r) { - while (l >= 0 && r < n && s[l] == s[r]) { - l--, r++; - } - return r - l - 1; - }; - for (int i = 0; i < n; ++i) { - int a = f(i, i); - int b = f(i, i + 1); - int t = max(a, b); - if (mx < t) { - mx = t; - start = i - (t - 1 >> 1); - } - } - return s.substr(start, mx); - } -}; -``` - -### **Go** - ```go func longestPalindrome(s string) string { n := len(s) @@ -230,90 +139,6 @@ func longestPalindrome(s string) string { } ``` -```go -func longestPalindrome(s string) string { - n := len(s) - start, mx := 0, 1 - f := func(l, r int) int { - for l >= 0 && r < n && s[l] == s[r] { - l, r = l-1, r+1 - } - return r - l - 1 - } - for i := range s { - a, b := f(i, i), f(i, i+1) - t := max(a, b) - if mx < t { - mx = t - start = i - ((t - 1) >> 1) - } - } - return s[start : start+mx] -} -``` - -### **C#** - -```cs -public class Solution { - public string LongestPalindrome(string s) { - int n = s.Length; - bool[,] f = new bool[n, n]; - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; ++j) { - f[i, j] = true; - } - } - int k = 0, mx = 1; - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - f[i, j] = false; - if (s[i] == s[j]) { - f[i, j] = f[i + 1, j - 1]; - if (f[i, j] && mx < j - i + 1) { - mx = j - i + 1; - k = i; - } - } - } - } - return s.Substring(k, mx); - } -} -``` - -### **JavaScript** - -```js -/** - * @param {string} s - * @return {string} - */ -var longestPalindrome = function (s) { - const n = s.length; - const f = Array(n) - .fill(0) - .map(() => Array(n).fill(true)); - let k = 0; - let mx = 1; - for (let i = n - 2; i >= 0; --i) { - for (let j = i + 1; j < n; ++j) { - f[i][j] = false; - if (s[i] === s[j]) { - f[i][j] = f[i + 1][j - 1]; - if (f[i][j] && mx < j - i + 1) { - mx = j - i + 1; - k = i; - } - } - } - } - return s.slice(k, k + mx); -}; -``` - -### **TypeScript** - ```ts function longestPalindrome(s: string): string { const n = s.length; @@ -338,8 +163,6 @@ function longestPalindrome(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn longest_palindrome(s: String) -> String { @@ -362,38 +185,62 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn is_palindrome(s: &str) -> bool { - let mut chars = s.chars(); - while let (Some(c1), Some(c2)) = (chars.next(), chars.next_back()) { - if c1 != c2 { - return false; +```js +/** + * @param {string} s + * @return {string} + */ +var longestPalindrome = function (s) { + const n = s.length; + const f = Array(n) + .fill(0) + .map(() => Array(n).fill(true)); + let k = 0; + let mx = 1; + for (let i = n - 2; i >= 0; --i) { + for (let j = i + 1; j < n; ++j) { + f[i][j] = false; + if (s[i] === s[j]) { + f[i][j] = f[i + 1][j - 1]; + if (f[i][j] && mx < j - i + 1) { + mx = j - i + 1; + k = i; + } } } - true } + return s.slice(k, k + mx); +}; +``` - pub fn longest_palindrome(s: String) -> String { - let size = s.len(); - let mut ans = &s[..1]; - for i in 0..size - 1 { - for j in (i + 1..size).rev() { - if ans.len() > j - i + 1 { - break; - } - if Solution::is_palindrome(&s[i..=j]) { - ans = &s[i..=j]; +```cs +public class Solution { + public string LongestPalindrome(string s) { + int n = s.Length; + bool[,] f = new bool[n, n]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; ++j) { + f[i, j] = true; + } + } + int k = 0, mx = 1; + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + f[i, j] = false; + if (s[i] == s[j]) { + f[i, j] = f[i + 1, j - 1]; + if (f[i, j] && mx < j - i + 1) { + mx = j - i + 1; + k = i; + } } } } - return ans.to_string(); + return s.Substring(k, mx); } } ``` -### **Nim** - ```nim import std/sequtils @@ -418,10 +265,145 @@ proc longestPalindrome(s: string): string = result = s[start ..< start+mx] ``` -### **...** + + +### Solution 2: Enumerate Palindrome Midpoint + +We can enumerate the midpoint of the palindrome, spread to both sides, and find the longest palindrome. + +The time complexity is $O(n^2)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string $s$. + + +```python +class Solution: + def longestPalindrome(self, s: str) -> str: + def f(l, r): + while l >= 0 and r < n and s[l] == s[r]: + l, r = l - 1, r + 1 + return r - l - 1 + + n = len(s) + start, mx = 0, 1 + for i in range(n): + a = f(i, i) + b = f(i, i + 1) + t = max(a, b) + if mx < t: + mx = t + start = i - ((t - 1) >> 1) + return s[start : start + mx] ``` +```java +class Solution { + private String s; + private int n; + + public String longestPalindrome(String s) { + this.s = s; + n = s.length(); + int start = 0, mx = 1; + for (int i = 0; i < n; ++i) { + int a = f(i, i); + int b = f(i, i + 1); + int t = Math.max(a, b); + if (mx < t) { + mx = t; + start = i - ((t - 1) >> 1); + } + } + return s.substring(start, start + mx); + } + + private int f(int l, int r) { + while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) { + --l; + ++r; + } + return r - l - 1; + } +} +``` + +```cpp +class Solution { +public: + string longestPalindrome(string s) { + int n = s.size(); + int start = 0, mx = 1; + auto f = [&](int l, int r) { + while (l >= 0 && r < n && s[l] == s[r]) { + l--, r++; + } + return r - l - 1; + }; + for (int i = 0; i < n; ++i) { + int a = f(i, i); + int b = f(i, i + 1); + int t = max(a, b); + if (mx < t) { + mx = t; + start = i - (t - 1 >> 1); + } + } + return s.substr(start, mx); + } +}; +``` + +```go +func longestPalindrome(s string) string { + n := len(s) + start, mx := 0, 1 + f := func(l, r int) int { + for l >= 0 && r < n && s[l] == s[r] { + l, r = l-1, r+1 + } + return r - l - 1 + } + for i := range s { + a, b := f(i, i), f(i, i+1) + t := max(a, b) + if mx < t { + mx = t + start = i - ((t - 1) >> 1) + } + } + return s[start : start+mx] +} +``` + +```rust +impl Solution { + pub fn is_palindrome(s: &str) -> bool { + let mut chars = s.chars(); + while let (Some(c1), Some(c2)) = (chars.next(), chars.next_back()) { + if c1 != c2 { + return false; + } + } + true + } + + pub fn longest_palindrome(s: String) -> String { + let size = s.len(); + let mut ans = &s[..1]; + for i in 0..size - 1 { + for j in (i + 1..size).rev() { + if ans.len() > j - i + 1 { + break; + } + if Solution::is_palindrome(&s[i..=j]) { + ans = &s[i..=j]; + } + } + } + return ans.to_string(); + } +} ``` + + diff --git a/solution/0000-0099/0006.Zigzag Conversion/README.md b/solution/0000-0099/0006.Zigzag Conversion/README.md index 637033263a9a1..51157d9ea0ac2 100644 --- a/solution/0000-0099/0006.Zigzag Conversion/README.md +++ b/solution/0000-0099/0006.Zigzag Conversion/README.md @@ -62,9 +62,7 @@ P I ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们用一个二维数组 $g$ 来模拟 $Z$ 字形排列的过程,其中 $g[i][j]$ 表示第 $i$ 行第 $j$ 列的字符。初始时 $i=0$,另外我们定义一个方向变量 $k$,初始时 $k=-1$,表示向上走。 @@ -74,10 +72,6 @@ P I -### **Python3** - - - ```python class Solution: def convert(self, s: str, numRows: int) -> str: @@ -93,29 +87,6 @@ class Solution: return ''.join(chain(*g)) ``` -```python -class Solution: - def convert(self, s: str, numRows: int) -> str: - if numRows == 1: - return s - group = 2 * numRows - 2 - ans = [] - for i in range(1, numRows + 1): - interval = group if i == numRows else 2 * numRows - 2 * i - idx = i - 1 - while idx < len(s): - ans.append(s[idx]) - idx += interval - interval = group - interval - if interval == 0: - interval = group - return ''.join(ans) -``` - -### **Java** - - - ```java class Solution { public String convert(String s, int numRows) { @@ -137,33 +108,6 @@ class Solution { } ``` -```java -class Solution { - public String convert(String s, int numRows) { - if (numRows == 1) { - return s; - } - StringBuilder ans = new StringBuilder(); - int group = 2 * numRows - 2; - for (int i = 1; i <= numRows; i++) { - int interval = i == numRows ? group : 2 * numRows - 2 * i; - int idx = i - 1; - while (idx < s.length()) { - ans.append(s.charAt(idx)); - idx += interval; - interval = group - interval; - if (interval == 0) { - interval = group; - } - } - } - return ans.toString(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -189,30 +133,6 @@ public: }; ``` -```cpp -class Solution { -public: - string convert(string s, int numRows) { - if (numRows == 1) return s; - string ans; - int group = 2 * numRows - 2; - for (int i = 1; i <= numRows; ++i) { - int interval = i == numRows ? group : 2 * numRows - 2 * i; - int idx = i - 1; - while (idx < s.length()) { - ans.push_back(s[idx]); - idx += interval; - interval = group - interval; - if (interval == 0) interval = group; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func convert(s string, numRows int) string { if numRows == 1 { @@ -231,53 +151,53 @@ func convert(s string, numRows int) string { } ``` -```go -func convert(s string, numRows int) string { - if numRows == 1 { - return s - } - n := len(s) - ans := make([]byte, n) - step := 2*numRows - 2 - count := 0 - for i := 0; i < numRows; i++ { - for j := 0; j+i < n; j += step { - ans[count] = s[i+j] - count++ - if i != 0 && i != numRows-1 && j+step-i < n { - ans[count] = s[j+step-i] - count++ - } - } - } - return string(ans) -} -``` - -### **JavaScript** - -```js -/** - * @param {string} s - * @param {number} numRows - * @return {string} - */ -var convert = function (s, numRows) { +```ts +function convert(s: string, numRows: number): string { if (numRows === 1) { return s; } - const g = new Array(numRows).fill(_).map(() => []); + const g: string[][] = new Array(numRows).fill(0).map(() => []); let i = 0; let k = -1; for (const c of s) { g[i].push(c); - if (i === 0 || i === numRows - 1) { + if (i === numRows - 1 || i === 0) { k = -k; } i += k; } return g.flat().join(''); -}; +} +``` + +```rust +impl Solution { + pub fn convert(s: String, num_rows: i32) -> String { + let num_rows = num_rows as usize; + if num_rows == 1 { + return s; + } + let mut ss = vec![String::new(); num_rows]; + let mut i = 0; + let mut to_down = true; + for c in s.chars() { + ss[i].push(c); + if to_down { + i += 1; + } else { + i -= 1; + } + if i == 0 || i == num_rows - 1 { + to_down = !to_down; + } + } + let mut res = String::new(); + for i in 0..num_rows { + res += &ss[i]; + } + res + } +} ``` ```js @@ -287,74 +207,23 @@ var convert = function (s, numRows) { * @return {string} */ var convert = function (s, numRows) { - if (numRows == 1) return s; - const arr = new Array(numRows); - for (let i = 0; i < numRows; i++) arr[i] = []; - let mi = 0, - isDown = true; - for (const c of s) { - arr[mi].push(c); - - if (mi >= numRows - 1) isDown = false; - else if (mi <= 0) isDown = true; - - if (isDown) mi++; - else mi--; - } - let ans = []; - for (const item of arr) { - ans = ans.concat(item); - } - return ans.join(''); -}; -``` - -### **TypeScript** - -```ts -function convert(s: string, numRows: number): string { if (numRows === 1) { return s; } - const g: string[][] = new Array(numRows).fill(0).map(() => []); + const g = new Array(numRows).fill(_).map(() => []); let i = 0; let k = -1; for (const c of s) { g[i].push(c); - if (i === numRows - 1 || i === 0) { + if (i === 0 || i === numRows - 1) { k = -k; } i += k; } return g.flat().join(''); -} -``` - -```ts -function convert(s: string, numRows: number): string { - if (numRows === 1) { - return s; - } - const ss = new Array(numRows).fill(''); - let i = 0; - let toDown = true; - for (const c of s) { - ss[i] += c; - if (toDown) { - i++; - } else { - i--; - } - if (i === 0 || i === numRows - 1) { - toDown = !toDown; - } - } - return ss.reduce((r, s) => r + s); -} +}; ``` -### **C#** - ```cs public class Solution { public string Convert(string s, int numRows) { @@ -383,35 +252,121 @@ public class Solution { } ``` -### **Rust** + -```rust -impl Solution { - pub fn convert(s: String, num_rows: i32) -> String { - let num_rows = num_rows as usize; - if num_rows == 1 { +### 方法二 + + + +```python +class Solution: + def convert(self, s: str, numRows: int) -> str: + if numRows == 1: + return s + group = 2 * numRows - 2 + ans = [] + for i in range(1, numRows + 1): + interval = group if i == numRows else 2 * numRows - 2 * i + idx = i - 1 + while idx < len(s): + ans.append(s[idx]) + idx += interval + interval = group - interval + if interval == 0: + interval = group + return ''.join(ans) +``` + +```java +class Solution { + public String convert(String s, int numRows) { + if (numRows == 1) { return s; } - let mut ss = vec![String::new(); num_rows]; - let mut i = 0; - let mut to_down = true; - for c in s.chars() { - ss[i].push(c); - if to_down { - i += 1; - } else { - i -= 1; + StringBuilder ans = new StringBuilder(); + int group = 2 * numRows - 2; + for (int i = 1; i <= numRows; i++) { + int interval = i == numRows ? group : 2 * numRows - 2 * i; + int idx = i - 1; + while (idx < s.length()) { + ans.append(s.charAt(idx)); + idx += interval; + interval = group - interval; + if (interval == 0) { + interval = group; + } } - if i == 0 || i == num_rows - 1 { - to_down = !to_down; + } + return ans.toString(); + } +} +``` + +```cpp +class Solution { +public: + string convert(string s, int numRows) { + if (numRows == 1) return s; + string ans; + int group = 2 * numRows - 2; + for (int i = 1; i <= numRows; ++i) { + int interval = i == numRows ? group : 2 * numRows - 2 * i; + int idx = i - 1; + while (idx < s.length()) { + ans.push_back(s[idx]); + idx += interval; + interval = group - interval; + if (interval == 0) interval = group; } } - let mut res = String::new(); - for i in 0..num_rows { - res += &ss[i]; + return ans; + } +}; +``` + +```go +func convert(s string, numRows int) string { + if numRows == 1 { + return s + } + n := len(s) + ans := make([]byte, n) + step := 2*numRows - 2 + count := 0 + for i := 0; i < numRows; i++ { + for j := 0; j+i < n; j += step { + ans[count] = s[i+j] + count++ + if i != 0 && i != numRows-1 && j+step-i < n { + ans[count] = s[j+step-i] + count++ + } + } + } + return string(ans) +} +``` + +```ts +function convert(s: string, numRows: number): string { + if (numRows === 1) { + return s; + } + const ss = new Array(numRows).fill(''); + let i = 0; + let toDown = true; + for (const c of s) { + ss[i] += c; + if (toDown) { + i++; + } else { + i--; + } + if (i === 0 || i === numRows - 1) { + toDown = !toDown; } - res } + return ss.reduce((r, s) => r + s); } ``` @@ -427,10 +382,35 @@ impl Solution { } ``` -### **...** +```js +/** + * @param {string} s + * @param {number} numRows + * @return {string} + */ +var convert = function (s, numRows) { + if (numRows == 1) return s; + const arr = new Array(numRows); + for (let i = 0; i < numRows; i++) arr[i] = []; + let mi = 0, + isDown = true; + for (const c of s) { + arr[mi].push(c); -``` + if (mi >= numRows - 1) isDown = false; + else if (mi <= 0) isDown = true; + if (isDown) mi++; + else mi--; + } + let ans = []; + for (const item of arr) { + ans = ans.concat(item); + } + return ans.join(''); +}; ``` + + diff --git a/solution/0000-0099/0006.Zigzag Conversion/README_EN.md b/solution/0000-0099/0006.Zigzag Conversion/README_EN.md index a41757336f86b..21c753e25c056 100644 --- a/solution/0000-0099/0006.Zigzag Conversion/README_EN.md +++ b/solution/0000-0099/0006.Zigzag Conversion/README_EN.md @@ -58,7 +58,7 @@ P I ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We use a two-dimensional array $g$ to simulate the process of the $Z$-shape arrangement, where $g[i][j]$ represents the character at the $i$-th row and the $j$-th column. Initially, $i=0$, and we define a direction variable $k$, initially $k=-1$, indicating moving upwards. @@ -68,10 +68,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - - - ```python class Solution: def convert(self, s: str, numRows: int) -> str: @@ -87,29 +83,6 @@ class Solution: return ''.join(chain(*g)) ``` -```python -class Solution: - def convert(self, s: str, numRows: int) -> str: - if numRows == 1: - return s - group = 2 * numRows - 2 - ans = [] - for i in range(1, numRows + 1): - interval = group if i == numRows else 2 * numRows - 2 * i - idx = i - 1 - while idx < len(s): - ans.append(s[idx]) - idx += interval - interval = group - interval - if interval == 0: - interval = group - return ''.join(ans) -``` - -### **Java** - - - ```java class Solution { public String convert(String s, int numRows) { @@ -131,33 +104,6 @@ class Solution { } ``` -```java -class Solution { - public String convert(String s, int numRows) { - if (numRows == 1) { - return s; - } - StringBuilder ans = new StringBuilder(); - int group = 2 * numRows - 2; - for (int i = 1; i <= numRows; i++) { - int interval = i == numRows ? group : 2 * numRows - 2 * i; - int idx = i - 1; - while (idx < s.length()) { - ans.append(s.charAt(idx)); - idx += interval; - interval = group - interval; - if (interval == 0) { - interval = group; - } - } - } - return ans.toString(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -183,30 +129,6 @@ public: }; ``` -```cpp -class Solution { -public: - string convert(string s, int numRows) { - if (numRows == 1) return s; - string ans; - int group = 2 * numRows - 2; - for (int i = 1; i <= numRows; ++i) { - int interval = i == numRows ? group : 2 * numRows - 2 * i; - int idx = i - 1; - while (idx < s.length()) { - ans.push_back(s[idx]); - idx += interval; - interval = group - interval; - if (interval == 0) interval = group; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func convert(s string, numRows int) string { if numRows == 1 { @@ -225,53 +147,53 @@ func convert(s string, numRows int) string { } ``` -```go -func convert(s string, numRows int) string { - if numRows == 1 { - return s - } - n := len(s) - ans := make([]byte, n) - step := 2*numRows - 2 - count := 0 - for i := 0; i < numRows; i++ { - for j := 0; j+i < n; j += step { - ans[count] = s[i+j] - count++ - if i != 0 && i != numRows-1 && j+step-i < n { - ans[count] = s[j+step-i] - count++ - } - } - } - return string(ans) -} -``` - -### **JavaScript** - -```js -/** - * @param {string} s - * @param {number} numRows - * @return {string} - */ -var convert = function (s, numRows) { +```ts +function convert(s: string, numRows: number): string { if (numRows === 1) { return s; } - const g = new Array(numRows).fill(_).map(() => []); + const g: string[][] = new Array(numRows).fill(0).map(() => []); let i = 0; let k = -1; for (const c of s) { g[i].push(c); - if (i === 0 || i === numRows - 1) { + if (i === numRows - 1 || i === 0) { k = -k; } i += k; } return g.flat().join(''); -}; +} +``` + +```rust +impl Solution { + pub fn convert(s: String, num_rows: i32) -> String { + let num_rows = num_rows as usize; + if num_rows == 1 { + return s; + } + let mut ss = vec![String::new(); num_rows]; + let mut i = 0; + let mut to_down = true; + for c in s.chars() { + ss[i].push(c); + if to_down { + i += 1; + } else { + i -= 1; + } + if i == 0 || i == num_rows - 1 { + to_down = !to_down; + } + } + let mut res = String::new(); + for i in 0..num_rows { + res += &ss[i]; + } + res + } +} ``` ```js @@ -281,74 +203,23 @@ var convert = function (s, numRows) { * @return {string} */ var convert = function (s, numRows) { - if (numRows == 1) return s; - const arr = new Array(numRows); - for (let i = 0; i < numRows; i++) arr[i] = []; - let mi = 0, - isDown = true; - for (const c of s) { - arr[mi].push(c); - - if (mi >= numRows - 1) isDown = false; - else if (mi <= 0) isDown = true; - - if (isDown) mi++; - else mi--; - } - let ans = []; - for (const item of arr) { - ans = ans.concat(item); - } - return ans.join(''); -}; -``` - -### **TypeScript** - -```ts -function convert(s: string, numRows: number): string { if (numRows === 1) { return s; } - const g: string[][] = new Array(numRows).fill(0).map(() => []); + const g = new Array(numRows).fill(_).map(() => []); let i = 0; let k = -1; for (const c of s) { g[i].push(c); - if (i === numRows - 1 || i === 0) { + if (i === 0 || i === numRows - 1) { k = -k; } i += k; } return g.flat().join(''); -} -``` - -```ts -function convert(s: string, numRows: number): string { - if (numRows === 1) { - return s; - } - const ss = new Array(numRows).fill(''); - let i = 0; - let toDown = true; - for (const c of s) { - ss[i] += c; - if (toDown) { - i++; - } else { - i--; - } - if (i === 0 || i === numRows - 1) { - toDown = !toDown; - } - } - return ss.reduce((r, s) => r + s); -} +}; ``` -### **C#** - ```cs public class Solution { public string Convert(string s, int numRows) { @@ -377,35 +248,121 @@ public class Solution { } ``` -### **Rust** + + +### Solution 2 -```rust -impl Solution { - pub fn convert(s: String, num_rows: i32) -> String { - let num_rows = num_rows as usize; - if num_rows == 1 { + + +```python +class Solution: + def convert(self, s: str, numRows: int) -> str: + if numRows == 1: + return s + group = 2 * numRows - 2 + ans = [] + for i in range(1, numRows + 1): + interval = group if i == numRows else 2 * numRows - 2 * i + idx = i - 1 + while idx < len(s): + ans.append(s[idx]) + idx += interval + interval = group - interval + if interval == 0: + interval = group + return ''.join(ans) +``` + +```java +class Solution { + public String convert(String s, int numRows) { + if (numRows == 1) { return s; } - let mut ss = vec![String::new(); num_rows]; - let mut i = 0; - let mut to_down = true; - for c in s.chars() { - ss[i].push(c); - if to_down { - i += 1; - } else { - i -= 1; + StringBuilder ans = new StringBuilder(); + int group = 2 * numRows - 2; + for (int i = 1; i <= numRows; i++) { + int interval = i == numRows ? group : 2 * numRows - 2 * i; + int idx = i - 1; + while (idx < s.length()) { + ans.append(s.charAt(idx)); + idx += interval; + interval = group - interval; + if (interval == 0) { + interval = group; + } } - if i == 0 || i == num_rows - 1 { - to_down = !to_down; + } + return ans.toString(); + } +} +``` + +```cpp +class Solution { +public: + string convert(string s, int numRows) { + if (numRows == 1) return s; + string ans; + int group = 2 * numRows - 2; + for (int i = 1; i <= numRows; ++i) { + int interval = i == numRows ? group : 2 * numRows - 2 * i; + int idx = i - 1; + while (idx < s.length()) { + ans.push_back(s[idx]); + idx += interval; + interval = group - interval; + if (interval == 0) interval = group; } } - let mut res = String::new(); - for i in 0..num_rows { - res += &ss[i]; + return ans; + } +}; +``` + +```go +func convert(s string, numRows int) string { + if numRows == 1 { + return s + } + n := len(s) + ans := make([]byte, n) + step := 2*numRows - 2 + count := 0 + for i := 0; i < numRows; i++ { + for j := 0; j+i < n; j += step { + ans[count] = s[i+j] + count++ + if i != 0 && i != numRows-1 && j+step-i < n { + ans[count] = s[j+step-i] + count++ + } + } + } + return string(ans) +} +``` + +```ts +function convert(s: string, numRows: number): string { + if (numRows === 1) { + return s; + } + const ss = new Array(numRows).fill(''); + let i = 0; + let toDown = true; + for (const c of s) { + ss[i] += c; + if (toDown) { + i++; + } else { + i--; + } + if (i === 0 || i === numRows - 1) { + toDown = !toDown; } - res } + return ss.reduce((r, s) => r + s); } ``` @@ -421,10 +378,35 @@ impl Solution { } ``` -### **...** +```js +/** + * @param {string} s + * @param {number} numRows + * @return {string} + */ +var convert = function (s, numRows) { + if (numRows == 1) return s; + const arr = new Array(numRows); + for (let i = 0; i < numRows; i++) arr[i] = []; + let mi = 0, + isDown = true; + for (const c of s) { + arr[mi].push(c); -``` + if (mi >= numRows - 1) isDown = false; + else if (mi <= 0) isDown = true; + if (isDown) mi++; + else mi--; + } + let ans = []; + for (const item of arr) { + ans = ans.concat(item); + } + return ans.join(''); +}; ``` + + diff --git a/solution/0000-0099/0007.Reverse Integer/README.md b/solution/0000-0099/0007.Reverse Integer/README.md index 2479e7e597128..1c0474905adb1 100644 --- a/solution/0000-0099/0007.Reverse Integer/README.md +++ b/solution/0000-0099/0007.Reverse Integer/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 我们不妨记 $mi$ 和 $mx$ 分别为 $-2^{31}$ 和 $2^{31} - 1$,则 $x$ 的反转结果 $ans$ 需要满足 $mi \le ans \le mx$。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def reverse(self, x: int) -> int: @@ -97,10 +91,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int reverse(int x) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func reverse(x int) (ans int) { for ; x != 0; x /= 10 { @@ -148,7 +134,17 @@ func reverse(x int) (ans int) { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn reverse(mut x: i32) -> i32 { + let is_minus = x < 0; + match x.abs().to_string().chars().rev().collect::().parse::() { + Ok(x) => x * (if is_minus { -1 } else { 1 }), + Err(_) => 0, + } + } +} +``` ```js /** @@ -169,37 +165,6 @@ var reverse = function (x) { }; ``` -### **C** - -```c -int reverse(int x) { - int ans = 0; - for (; x != 0; x /= 10) { - if (ans > INT_MAX / 10 || ans < INT_MIN / 10) { - return 0; - } - ans = ans * 10 + x % 10; - } - return ans; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn reverse(mut x: i32) -> i32 { - let is_minus = x < 0; - match x.abs().to_string().chars().rev().collect::().parse::() { - Ok(x) => x * (if is_minus { -1 } else { 1 }), - Err(_) => 0, - } - } -} -``` - -### **C#** - ```cs public class Solution { public int Reverse(int x) { @@ -215,10 +180,19 @@ public class Solution { } ``` -### **...** - -``` - +```c +int reverse(int x) { + int ans = 0; + for (; x != 0; x /= 10) { + if (ans > INT_MAX / 10 || ans < INT_MIN / 10) { + return 0; + } + ans = ans * 10 + x % 10; + } + return ans; +} ``` + + diff --git a/solution/0000-0099/0007.Reverse Integer/README_EN.md b/solution/0000-0099/0007.Reverse Integer/README_EN.md index b2f0e013b9a0c..7512badd0522a 100644 --- a/solution/0000-0099/0007.Reverse Integer/README_EN.md +++ b/solution/0000-0099/0007.Reverse Integer/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics Let's denote $mi$ and $mx$ as $-2^{31}$ and $2^{31} - 1$ respectively, then the reverse result of $x$, $ans$, needs to satisfy $mi \le ans \le mx$. @@ -63,8 +63,6 @@ The time complexity is $O(\log |x|)$, where $|x|$ is the absolute value of $x$. -### **Python3** - ```python class Solution: def reverse(self, x: int) -> int: @@ -81,8 +79,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int reverse(int x) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +110,6 @@ public: }; ``` -### **Go** - ```go func reverse(x int) (ans int) { for ; x != 0; x /= 10 { @@ -130,7 +122,17 @@ func reverse(x int) (ans int) { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn reverse(mut x: i32) -> i32 { + let is_minus = x < 0; + match x.abs().to_string().chars().rev().collect::().parse::() { + Ok(x) => x * (if is_minus { -1 } else { 1 }), + Err(_) => 0, + } + } +} +``` ```js /** @@ -151,37 +153,6 @@ var reverse = function (x) { }; ``` -### **C** - -```c -int reverse(int x) { - int ans = 0; - for (; x != 0; x /= 10) { - if (ans > INT_MAX / 10 || ans < INT_MIN / 10) { - return 0; - } - ans = ans * 10 + x % 10; - } - return ans; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn reverse(mut x: i32) -> i32 { - let is_minus = x < 0; - match x.abs().to_string().chars().rev().collect::().parse::() { - Ok(x) => x * (if is_minus { -1 } else { 1 }), - Err(_) => 0, - } - } -} -``` - -### **C#** - ```cs public class Solution { public int Reverse(int x) { @@ -197,10 +168,19 @@ public class Solution { } ``` -### **...** - -``` - +```c +int reverse(int x) { + int ans = 0; + for (; x != 0; x /= 10) { + if (ans > INT_MAX / 10 || ans < INT_MIN / 10) { + return 0; + } + ans = ans * 10 + x % 10; + } + return ans; +} ``` + + diff --git a/solution/0000-0099/0008.String to Integer (atoi)/README.md b/solution/0000-0099/0008.String to Integer (atoi)/README.md index 02bc35be907d9..510f85674addd 100644 --- a/solution/0000-0099/0008.String to Integer (atoi)/README.md +++ b/solution/0000-0099/0008.String to Integer (atoi)/README.md @@ -86,9 +86,7 @@ ## 解法 - - -**方法一:遍历字符串** +### 方法一:遍历字符串 我们首先判断字符串是否为空,如果是,直接返回 $0$。 @@ -104,10 +102,6 @@ -### **Python3** - - - ```python class Solution: def myAtoi(self, s: str) -> int: @@ -139,10 +133,6 @@ class Solution: return sign * res ``` -### **Java** - - - ```java class Solution { public int myAtoi(String s) { @@ -171,8 +161,6 @@ class Solution { } ``` -### **Go** - ```go func myAtoi(s string) int { i, n := 0, len(s) @@ -211,10 +199,82 @@ func myAtoi(s string) int { } ``` -### **...** - +```js +const myAtoi = function (str) { + str = str.trim(); + if (!str) return 0; + let isPositive = 1; + let i = 0, + ans = 0; + if (str[i] === '+') { + isPositive = 1; + i++; + } else if (str[i] === '-') { + isPositive = 0; + i++; + } + for (; i < str.length; i++) { + let t = str.charCodeAt(i) - 48; + if (t > 9 || t < 0) break; + if (ans > 2147483647 / 10 || ans > (2147483647 - t) / 10) { + return isPositive ? 2147483647 : -2147483648; + } else { + ans = ans * 10 + t; + } + } + return isPositive ? ans : -ans; +}; ``` +```cs +// https://leetcode.com/problems/string-to-integer-atoi/ + +public partial class Solution +{ + public int MyAtoi(string str) + { + int i = 0; + long result = 0; + bool minus = false; + while (i < str.Length && char.IsWhiteSpace(str[i])) + { + ++i; + } + if (i < str.Length) + { + if (str[i] == '+') + { + ++i; + } + else if (str[i] == '-') + { + minus = true; + ++i; + } + } + while (i < str.Length && char.IsDigit(str[i])) + { + result = result * 10 + str[i] - '0'; + if (result > int.MaxValue) + { + break; + } + ++i; + } + if (minus) result = -result; + if (result > int.MaxValue) + { + result = int.MaxValue; + } + if (result < int.MinValue) + { + result = int.MinValue; + } + return (int)result; + } +} ``` + + diff --git a/solution/0000-0099/0008.String to Integer (atoi)/README_EN.md b/solution/0000-0099/0008.String to Integer (atoi)/README_EN.md index bac37815dfe01..a93f2c2e3866f 100644 --- a/solution/0000-0099/0008.String to Integer (atoi)/README_EN.md +++ b/solution/0000-0099/0008.String to Integer (atoi)/README_EN.md @@ -83,7 +83,7 @@ Since 4193 is in the range [-231, 231 - 1], the final resu ## Solutions -**Solution 1: Traverse the String** +### Solution 1: Traverse the String First, we determine whether the string is empty. If it is, we directly return $0$. @@ -97,8 +97,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string. We only ne -### **Python3** - ```python class Solution: def myAtoi(self, s: str) -> int: @@ -110,7 +108,7 @@ class Solution: i = 0 while s[i] == ' ': i += 1 - # only contains blank space + # 仅包含空格 if i == n: return 0 sign = -1 if s[i] == '-' else 1 @@ -118,11 +116,11 @@ class Solution: i += 1 res, flag = 0, (2**31 - 1) // 10 while i < n: - # not a number, exit the loop + # 非数字,跳出循环体 if not s[i].isdigit(): break c = int(s[i]) - # if overflows + # 溢出判断 if res > flag or (res == flag and c > 7): return 2**31 - 1 if sign > 0 else -(2**31) res = res * 10 + c @@ -130,8 +128,6 @@ class Solution: return sign * res ``` -### **Java** - ```java class Solution { public int myAtoi(String s) { @@ -140,7 +136,7 @@ class Solution { if (n == 0) return 0; int i = 0; while (s.charAt(i) == ' ') { - // only contains blank space + // 仅包含空格 if (++i == n) return 0; } int sign = 1; @@ -148,9 +144,9 @@ class Solution { if (s.charAt(i) == '-' || s.charAt(i) == '+') ++i; int res = 0, flag = Integer.MAX_VALUE / 10; for (; i < n; ++i) { - // not a number, exit the loop + // 非数字,跳出循环体 if (s.charAt(i) < '0' || s.charAt(i) > '9') break; - // if overflows + // 溢出判断 if (res > flag || (res == flag && s.charAt(i) > '7')) return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE; res = res * 10 + (s.charAt(i) - '0'); @@ -160,8 +156,6 @@ class Solution { } ``` -### **Go** - ```go func myAtoi(s string) int { i, n := 0, len(s) @@ -200,10 +194,82 @@ func myAtoi(s string) int { } ``` -### **...** - +```js +const myAtoi = function (str) { + str = str.trim(); + if (!str) return 0; + let isPositive = 1; + let i = 0, + ans = 0; + if (str[i] === '+') { + isPositive = 1; + i++; + } else if (str[i] === '-') { + isPositive = 0; + i++; + } + for (; i < str.length; i++) { + let t = str.charCodeAt(i) - 48; + if (t > 9 || t < 0) break; + if (ans > 2147483647 / 10 || ans > (2147483647 - t) / 10) { + return isPositive ? 2147483647 : -2147483648; + } else { + ans = ans * 10 + t; + } + } + return isPositive ? ans : -ans; +}; ``` +```cs +// https://leetcode.com/problems/string-to-integer-atoi/ + +public partial class Solution +{ + public int MyAtoi(string str) + { + int i = 0; + long result = 0; + bool minus = false; + while (i < str.Length && char.IsWhiteSpace(str[i])) + { + ++i; + } + if (i < str.Length) + { + if (str[i] == '+') + { + ++i; + } + else if (str[i] == '-') + { + minus = true; + ++i; + } + } + while (i < str.Length && char.IsDigit(str[i])) + { + result = result * 10 + str[i] - '0'; + if (result > int.MaxValue) + { + break; + } + ++i; + } + if (minus) result = -result; + if (result > int.MaxValue) + { + result = int.MaxValue; + } + if (result < int.MinValue) + { + result = int.MinValue; + } + return (int)result; + } +} ``` + + diff --git a/solution/0000-0099/0009.Palindrome Number/README.md b/solution/0000-0099/0009.Palindrome Number/README.md index 76972a52010ae..8ac7f651bd3dc 100644 --- a/solution/0000-0099/0009.Palindrome Number/README.md +++ b/solution/0000-0099/0009.Palindrome Number/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:反转一半数字** +### 方法一:反转一半数字 我们先判断特殊情况: @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def isPalindrome(self, x: int) -> bool: @@ -97,10 +91,6 @@ class Solution: return x in (y, y // 10) ``` -### **Java** - - - ```java class Solution { public boolean isPalindrome(int x) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func isPalindrome(x int) bool { if x < 0 || (x > 0 && x%10 == 0) { @@ -149,27 +135,6 @@ func isPalindrome(x int) bool { } ``` -### **JavaScript** - -```js -/** - * @param {number} x - * @return {boolean} - */ -var isPalindrome = function (x) { - if (x < 0 || (x > 0 && x % 10 === 0)) { - return false; - } - let y = 0; - for (; y < x; x = ~~(x / 10)) { - y = y * 10 + (x % 10); - } - return x === y || x === ~~(y / 10); -}; -``` - -### **TypeScript** - ```ts function isPalindrome(x: number): boolean { if (x < 0 || (x > 0 && x % 10 === 0)) { @@ -183,8 +148,6 @@ function isPalindrome(x: number): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_palindrome(x: i32) -> bool { @@ -208,6 +171,29 @@ impl Solution { } ``` +```js +/** + * @param {number} x + * @return {boolean} + */ +var isPalindrome = function (x) { + if (x < 0 || (x > 0 && x % 10 === 0)) { + return false; + } + let y = 0; + for (; y < x; x = ~~(x / 10)) { + y = y * 10 + (x % 10); + } + return x === y || x === ~~(y / 10); +}; +``` + + + +### 方法二 + + + ```rust impl Solution { pub fn is_palindrome(mut x: i32) -> bool { @@ -225,10 +211,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0009.Palindrome Number/README_EN.md b/solution/0000-0099/0009.Palindrome Number/README_EN.md index 9bb58afeb7918..86cb617af9bea 100644 --- a/solution/0000-0099/0009.Palindrome Number/README_EN.md +++ b/solution/0000-0099/0009.Palindrome Number/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Reverse Half of the Number** +### Solution 1: Reverse Half of the Number First, we determine special cases: @@ -69,8 +69,6 @@ The time complexity is $O(\log_{10}(n))$, where $n$ is $x$. For each iteration, -### **Python3** - ```python class Solution: def isPalindrome(self, x: int) -> bool: @@ -83,8 +81,6 @@ class Solution: return x in (y, y // 10) ``` -### **Java** - ```java class Solution { public boolean isPalindrome(int x) { @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func isPalindrome(x int) bool { if x < 0 || (x > 0 && x%10 == 0) { @@ -133,27 +125,6 @@ func isPalindrome(x int) bool { } ``` -### **JavaScript** - -```js -/** - * @param {number} x - * @return {boolean} - */ -var isPalindrome = function (x) { - if (x < 0 || (x > 0 && x % 10 === 0)) { - return false; - } - let y = 0; - for (; y < x; x = ~~(x / 10)) { - y = y * 10 + (x % 10); - } - return x === y || x === ~~(y / 10); -}; -``` - -### **TypeScript** - ```ts function isPalindrome(x: number): boolean { if (x < 0 || (x > 0 && x % 10 === 0)) { @@ -167,8 +138,6 @@ function isPalindrome(x: number): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_palindrome(x: i32) -> bool { @@ -192,6 +161,29 @@ impl Solution { } ``` +```js +/** + * @param {number} x + * @return {boolean} + */ +var isPalindrome = function (x) { + if (x < 0 || (x > 0 && x % 10 === 0)) { + return false; + } + let y = 0; + for (; y < x; x = ~~(x / 10)) { + y = y * 10 + (x % 10); + } + return x === y || x === ~~(y / 10); +}; +``` + + + +### Solution 2 + + + ```rust impl Solution { pub fn is_palindrome(mut x: i32) -> bool { @@ -209,10 +201,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0010.Regular Expression Matching/README.md b/solution/0000-0099/0010.Regular Expression Matching/README.md index 1b129b14682af..d8da6408e5118 100644 --- a/solution/0000-0099/0010.Regular Expression Matching/README.md +++ b/solution/0000-0099/0010.Regular Expression Matching/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j)$,表示从 $s$ 的第 $i$ 个字符开始,和 $p$ 的第 $j$ 个字符开始是否匹配。那么答案就是 $dfs(0, 0)$。 @@ -70,25 +68,8 @@ 时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是 $s$ 和 $p$ 的长度。 -**方法二:动态规划** - -我们可以将方法一中的记忆化搜索转换为动态规划。 - -定义 $f[i][j]$ 表示字符串 $s$ 的前 $i$ 个字符和字符串 $p$ 的前 $j$ 个字符是否匹配。那么答案就是 $f[m][n]$。初始化 $f[0][0] = true$,表示空字符串和空正则表达式是匹配的。 - -与方法一类似,我们可以分情况来讨论。 - -- 如果 $p[j - 1]$ 是 `'*'`,那么我们可以选择匹配 $0$ 个 $s[i - 1]$ 字符,那么就是 $f[i][j] = f[i][j - 2]$。如果此时 $s[i - 1]$ 和 $p[j - 2]$ 匹配,那么我们可以选择匹配 $1$ 个 $s[i - 1]$ 字符,那么就是 $f[i][j] = f[i][j] \lor f[i - 1][j]$。 -- 如果 $p[j - 1]$ 不是 `'*'`,那么如果 $s[i - 1]$ 和 $p[j - 1]$ 匹配,那么就是 $f[i][j] = f[i - 1][j - 1]$。否则匹配失败。 - -时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是 $s$ 和 $p$ 的长度。 - -### **Python3** - - - ```python class Solution: def isMatch(self, s: str, p: str) -> bool: @@ -106,27 +87,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def isMatch(self, s: str, p: str) -> bool: - m, n = len(s), len(p) - f = [[False] * (n + 1) for _ in range(m + 1)] - f[0][0] = True - for i in range(m + 1): - for j in range(1, n + 1): - if p[j - 1] == "*": - f[i][j] = f[i][j - 2] - if i > 0 and (p[j - 2] == "." or s[i - 1] == p[j - 2]): - f[i][j] |= f[i - 1][j] - elif i > 0 and (p[j - 1] == "." or s[i - 1] == p[j - 1]): - f[i][j] = f[i - 1][j - 1] - return f[m][n] -``` - -### **Java** - - - ```java class Solution { private Boolean[][] f; @@ -163,32 +123,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isMatch(String s, String p) { - int m = s.length(), n = p.length(); - boolean[][] f = new boolean[m + 1][n + 1]; - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (p.charAt(j - 1) == '*') { - f[i][j] = f[i][j - 2]; - if (i > 0 && (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1))) { - f[i][j] |= f[i - 1][j]; - } - } else if (i > 0 - && (p.charAt(j - 1) == '.' || p.charAt(j - 1) == s.charAt(i - 1))) { - f[i][j] = f[i - 1][j - 1]; - } - } - } - return f[m][n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -219,33 +153,36 @@ public: }; ``` -```cpp -class Solution { -public: - bool isMatch(string s, string p) { - int m = s.size(), n = p.size(); - bool f[m + 1][n + 1]; - memset(f, false, sizeof f); - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (p[j - 1] == '*') { - f[i][j] = f[i][j - 2]; - if (i && (p[j - 2] == '.' || p[j - 2] == s[i - 1])) { - f[i][j] |= f[i - 1][j]; - } - } else if (i && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { - f[i][j] = f[i - 1][j - 1]; - } - } - } - return f[m][n]; - } -}; +```go +func isMatch(s string, p string) bool { + m, n := len(s), len(p) + f := make([][]int, m+1) + for i := range f { + f[i] = make([]int, n+1) + } + var dfs func(i, j int) bool + dfs = func(i, j int) bool { + if j >= n { + return i == m + } + if f[i][j] != 0 { + return f[i][j] == 1 + } + res := -1 + if j+1 < n && p[j+1] == '*' { + if dfs(i, j+2) || (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i+1, j)) { + res = 1 + } + } else if i < m && (s[i] == p[j] || p[j] == '.') && dfs(i+1, j+1) { + res = 1 + } + f[i][j] = res + return res == 1 + } + return dfs(0, 0) +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -287,64 +224,6 @@ impl Solution { } ``` -### **Go** - -```go -func isMatch(s string, p string) bool { - m, n := len(s), len(p) - f := make([][]int, m+1) - for i := range f { - f[i] = make([]int, n+1) - } - var dfs func(i, j int) bool - dfs = func(i, j int) bool { - if j >= n { - return i == m - } - if f[i][j] != 0 { - return f[i][j] == 1 - } - res := -1 - if j+1 < n && p[j+1] == '*' { - if dfs(i, j+2) || (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i+1, j)) { - res = 1 - } - } else if i < m && (s[i] == p[j] || p[j] == '.') && dfs(i+1, j+1) { - res = 1 - } - f[i][j] = res - return res == 1 - } - return dfs(0, 0) -} -``` - -```go -func isMatch(s string, p string) bool { - m, n := len(s), len(p) - f := make([][]bool, m+1) - for i := range f { - f[i] = make([]bool, n+1) - } - f[0][0] = true - for i := 0; i <= m; i++ { - for j := 1; j <= n; j++ { - if p[j-1] == '*' { - f[i][j] = f[i][j-2] - if i > 0 && (p[j-2] == '.' || p[j-2] == s[i-1]) { - f[i][j] = f[i][j] || f[i-1][j] - } - } else if i > 0 && (p[j-1] == '.' || p[j-1] == s[i-1]) { - f[i][j] = f[i-1][j-1] - } - } - } - return f[m][n] -} -``` - -### **JavaScript** - ```js /** * @param {string} s @@ -377,35 +256,6 @@ var isMatch = function (s, p) { }; ``` -```js -/** - * @param {string} s - * @param {string} p - * @return {boolean} - */ -var isMatch = function (s, p) { - const m = s.length; - const n = p.length; - const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(false)); - f[0][0] = true; - for (let i = 0; i <= m; ++i) { - for (let j = 1; j <= n; ++j) { - if (p[j - 1] === '*') { - f[i][j] = f[i][j - 2]; - if (i && (p[j - 2] === '.' || p[j - 2] === s[i - 1])) { - f[i][j] |= f[i - 1][j]; - } - } else if (i && (p[j - 1] === '.' || p[j - 1] === s[i - 1])) { - f[i][j] = f[i - 1][j - 1]; - } - } - } - return f[m][n]; -}; -``` - -### **C#** - ```cs public class Solution { private string s; @@ -444,6 +294,140 @@ public class Solution { } ``` + + +### 方法二:动态规划 + +我们可以将方法一中的记忆化搜索转换为动态规划。 + +定义 $f[i][j]$ 表示字符串 $s$ 的前 $i$ 个字符和字符串 $p$ 的前 $j$ 个字符是否匹配。那么答案就是 $f[m][n]$。初始化 $f[0][0] = true$,表示空字符串和空正则表达式是匹配的。 + +与方法一类似,我们可以分情况来讨论。 + +- 如果 $p[j - 1]$ 是 `'*'`,那么我们可以选择匹配 $0$ 个 $s[i - 1]$ 字符,那么就是 $f[i][j] = f[i][j - 2]$。如果此时 $s[i - 1]$ 和 $p[j - 2]$ 匹配,那么我们可以选择匹配 $1$ 个 $s[i - 1]$ 字符,那么就是 $f[i][j] = f[i][j] \lor f[i - 1][j]$。 +- 如果 $p[j - 1]$ 不是 `'*'`,那么如果 $s[i - 1]$ 和 $p[j - 1]$ 匹配,那么就是 $f[i][j] = f[i - 1][j - 1]$。否则匹配失败。 + +时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是 $s$ 和 $p$ 的长度。 + + + +```python +class Solution: + def isMatch(self, s: str, p: str) -> bool: + m, n = len(s), len(p) + f = [[False] * (n + 1) for _ in range(m + 1)] + f[0][0] = True + for i in range(m + 1): + for j in range(1, n + 1): + if p[j - 1] == "*": + f[i][j] = f[i][j - 2] + if i > 0 and (p[j - 2] == "." or s[i - 1] == p[j - 2]): + f[i][j] |= f[i - 1][j] + elif i > 0 and (p[j - 1] == "." or s[i - 1] == p[j - 1]): + f[i][j] = f[i - 1][j - 1] + return f[m][n] +``` + +```java +class Solution { + public boolean isMatch(String s, String p) { + int m = s.length(), n = p.length(); + boolean[][] f = new boolean[m + 1][n + 1]; + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (p.charAt(j - 1) == '*') { + f[i][j] = f[i][j - 2]; + if (i > 0 && (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1))) { + f[i][j] |= f[i - 1][j]; + } + } else if (i > 0 + && (p.charAt(j - 1) == '.' || p.charAt(j - 1) == s.charAt(i - 1))) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; + } +} +``` + +```cpp +class Solution { +public: + bool isMatch(string s, string p) { + int m = s.size(), n = p.size(); + bool f[m + 1][n + 1]; + memset(f, false, sizeof f); + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (p[j - 1] == '*') { + f[i][j] = f[i][j - 2]; + if (i && (p[j - 2] == '.' || p[j - 2] == s[i - 1])) { + f[i][j] |= f[i - 1][j]; + } + } else if (i && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; + } +}; +``` + +```go +func isMatch(s string, p string) bool { + m, n := len(s), len(p) + f := make([][]bool, m+1) + for i := range f { + f[i] = make([]bool, n+1) + } + f[0][0] = true + for i := 0; i <= m; i++ { + for j := 1; j <= n; j++ { + if p[j-1] == '*' { + f[i][j] = f[i][j-2] + if i > 0 && (p[j-2] == '.' || p[j-2] == s[i-1]) { + f[i][j] = f[i][j] || f[i-1][j] + } + } else if i > 0 && (p[j-1] == '.' || p[j-1] == s[i-1]) { + f[i][j] = f[i-1][j-1] + } + } + } + return f[m][n] +} +``` + +```js +/** + * @param {string} s + * @param {string} p + * @return {boolean} + */ +var isMatch = function (s, p) { + const m = s.length; + const n = p.length; + const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(false)); + f[0][0] = true; + for (let i = 0; i <= m; ++i) { + for (let j = 1; j <= n; ++j) { + if (p[j - 1] === '*') { + f[i][j] = f[i][j - 2]; + if (i && (p[j - 2] === '.' || p[j - 2] === s[i - 1])) { + f[i][j] |= f[i - 1][j]; + } + } else if (i && (p[j - 1] === '.' || p[j - 1] === s[i - 1])) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; +}; +``` + ```cs public class Solution { public bool IsMatch(string s, string p) { @@ -467,10 +451,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0010.Regular Expression Matching/README_EN.md b/solution/0000-0099/0010.Regular Expression Matching/README_EN.md index ddc4cc808ba14..22e6613f3ec73 100644 --- a/solution/0000-0099/0010.Regular Expression Matching/README_EN.md +++ b/solution/0000-0099/0010.Regular Expression Matching/README_EN.md @@ -51,7 +51,7 @@ ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We design a function $dfs(i, j)$, which indicates whether the $i$-th character of $s$ matches the $j$-th character of $p$. The answer is $dfs(0, 0)$. @@ -65,23 +65,8 @@ During the process, we can use memoization search to avoid repeated calculations The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the lengths of $s$ and $p$ respectively. -**Solution 2: Dynamic Programming** - -We can convert the memoization search in Solution 1 into dynamic programming. - -Define $f[i][j]$ to represent whether the first $i$ characters of string $s$ match the first $j$ characters of string $p$. The answer is $f[m][n]$. Initialize $f[0][0] = true$, indicating that the empty string and the empty regular expression match. - -Similar to Solution 1, we can discuss different cases. - -- If $p[j - 1]$ is `'*'`, we can choose to match $0$ $s[i - 1]$ characters, which is $f[i][j] = f[i][j - 2]$. If $s[i - 1]$ matches $p[j - 2]$, we can choose to match $1$ $s[i - 1]$ character, which is $f[i][j] = f[i][j] \lor f[i - 1][j]$. -- If $p[j - 1]$ is not `'*'`, then if $s[i - 1]$ matches $p[j - 1]$, it is $f[i][j] = f[i - 1][j - 1]$. Otherwise, the match fails. - -The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the lengths of $s$ and $p$ respectively. - -### **Python3** - ```python class Solution: def isMatch(self, s: str, p: str) -> bool: @@ -99,25 +84,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def isMatch(self, s: str, p: str) -> bool: - m, n = len(s), len(p) - f = [[False] * (n + 1) for _ in range(m + 1)] - f[0][0] = True - for i in range(m + 1): - for j in range(1, n + 1): - if p[j - 1] == "*": - f[i][j] = f[i][j - 2] - if i > 0 and (p[j - 2] == "." or s[i - 1] == p[j - 2]): - f[i][j] |= f[i - 1][j] - elif i > 0 and (p[j - 1] == "." or s[i - 1] == p[j - 1]): - f[i][j] = f[i - 1][j - 1] - return f[m][n] -``` - -### **Java** - ```java class Solution { private Boolean[][] f; @@ -154,32 +120,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isMatch(String s, String p) { - int m = s.length(), n = p.length(); - boolean[][] f = new boolean[m + 1][n + 1]; - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (p.charAt(j - 1) == '*') { - f[i][j] = f[i][j - 2]; - if (i > 0 && (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1))) { - f[i][j] |= f[i - 1][j]; - } - } else if (i > 0 - && (p.charAt(j - 1) == '.' || p.charAt(j - 1) == s.charAt(i - 1))) { - f[i][j] = f[i - 1][j - 1]; - } - } - } - return f[m][n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -210,33 +150,36 @@ public: }; ``` -```cpp -class Solution { -public: - bool isMatch(string s, string p) { - int m = s.size(), n = p.size(); - bool f[m + 1][n + 1]; - memset(f, false, sizeof f); - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - if (p[j - 1] == '*') { - f[i][j] = f[i][j - 2]; - if (i && (p[j - 2] == '.' || p[j - 2] == s[i - 1])) { - f[i][j] |= f[i - 1][j]; - } - } else if (i && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { - f[i][j] = f[i - 1][j - 1]; - } - } - } - return f[m][n]; - } -}; +```go +func isMatch(s string, p string) bool { + m, n := len(s), len(p) + f := make([][]int, m+1) + for i := range f { + f[i] = make([]int, n+1) + } + var dfs func(i, j int) bool + dfs = func(i, j int) bool { + if j >= n { + return i == m + } + if f[i][j] != 0 { + return f[i][j] == 1 + } + res := -1 + if j+1 < n && p[j+1] == '*' { + if dfs(i, j+2) || (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i+1, j)) { + res = 1 + } + } else if i < m && (s[i] == p[j] || p[j] == '.') && dfs(i+1, j+1) { + res = 1 + } + f[i][j] = res + return res == 1 + } + return dfs(0, 0) +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -278,64 +221,6 @@ impl Solution { } ``` -### **Go** - -```go -func isMatch(s string, p string) bool { - m, n := len(s), len(p) - f := make([][]int, m+1) - for i := range f { - f[i] = make([]int, n+1) - } - var dfs func(i, j int) bool - dfs = func(i, j int) bool { - if j >= n { - return i == m - } - if f[i][j] != 0 { - return f[i][j] == 1 - } - res := -1 - if j+1 < n && p[j+1] == '*' { - if dfs(i, j+2) || (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i+1, j)) { - res = 1 - } - } else if i < m && (s[i] == p[j] || p[j] == '.') && dfs(i+1, j+1) { - res = 1 - } - f[i][j] = res - return res == 1 - } - return dfs(0, 0) -} -``` - -```go -func isMatch(s string, p string) bool { - m, n := len(s), len(p) - f := make([][]bool, m+1) - for i := range f { - f[i] = make([]bool, n+1) - } - f[0][0] = true - for i := 0; i <= m; i++ { - for j := 1; j <= n; j++ { - if p[j-1] == '*' { - f[i][j] = f[i][j-2] - if i > 0 && (p[j-2] == '.' || p[j-2] == s[i-1]) { - f[i][j] = f[i][j] || f[i-1][j] - } - } else if i > 0 && (p[j-1] == '.' || p[j-1] == s[i-1]) { - f[i][j] = f[i-1][j-1] - } - } - } - return f[m][n] -} -``` - -### **JavaScript** - ```js /** * @param {string} s @@ -368,35 +253,6 @@ var isMatch = function (s, p) { }; ``` -```js -/** - * @param {string} s - * @param {string} p - * @return {boolean} - */ -var isMatch = function (s, p) { - const m = s.length; - const n = p.length; - const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(false)); - f[0][0] = true; - for (let i = 0; i <= m; ++i) { - for (let j = 1; j <= n; ++j) { - if (p[j - 1] === '*') { - f[i][j] = f[i][j - 2]; - if (i && (p[j - 2] === '.' || p[j - 2] === s[i - 1])) { - f[i][j] |= f[i - 1][j]; - } - } else if (i && (p[j - 1] === '.' || p[j - 1] === s[i - 1])) { - f[i][j] = f[i - 1][j - 1]; - } - } - } - return f[m][n]; -}; -``` - -### **C#** - ```cs public class Solution { private string s; @@ -435,6 +291,140 @@ public class Solution { } ``` + + +### Solution 2: Dynamic Programming + +We can convert the memoization search in Solution 1 into dynamic programming. + +Define $f[i][j]$ to represent whether the first $i$ characters of string $s$ match the first $j$ characters of string $p$. The answer is $f[m][n]$. Initialize $f[0][0] = true$, indicating that the empty string and the empty regular expression match. + +Similar to Solution 1, we can discuss different cases. + +- If $p[j - 1]$ is `'*'`, we can choose to match $0$ $s[i - 1]$ characters, which is $f[i][j] = f[i][j - 2]$. If $s[i - 1]$ matches $p[j - 2]$, we can choose to match $1$ $s[i - 1]$ character, which is $f[i][j] = f[i][j] \lor f[i - 1][j]$. +- If $p[j - 1]$ is not `'*'`, then if $s[i - 1]$ matches $p[j - 1]$, it is $f[i][j] = f[i - 1][j - 1]$. Otherwise, the match fails. + +The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the lengths of $s$ and $p$ respectively. + + + +```python +class Solution: + def isMatch(self, s: str, p: str) -> bool: + m, n = len(s), len(p) + f = [[False] * (n + 1) for _ in range(m + 1)] + f[0][0] = True + for i in range(m + 1): + for j in range(1, n + 1): + if p[j - 1] == "*": + f[i][j] = f[i][j - 2] + if i > 0 and (p[j - 2] == "." or s[i - 1] == p[j - 2]): + f[i][j] |= f[i - 1][j] + elif i > 0 and (p[j - 1] == "." or s[i - 1] == p[j - 1]): + f[i][j] = f[i - 1][j - 1] + return f[m][n] +``` + +```java +class Solution { + public boolean isMatch(String s, String p) { + int m = s.length(), n = p.length(); + boolean[][] f = new boolean[m + 1][n + 1]; + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (p.charAt(j - 1) == '*') { + f[i][j] = f[i][j - 2]; + if (i > 0 && (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1))) { + f[i][j] |= f[i - 1][j]; + } + } else if (i > 0 + && (p.charAt(j - 1) == '.' || p.charAt(j - 1) == s.charAt(i - 1))) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; + } +} +``` + +```cpp +class Solution { +public: + bool isMatch(string s, string p) { + int m = s.size(), n = p.size(); + bool f[m + 1][n + 1]; + memset(f, false, sizeof f); + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (p[j - 1] == '*') { + f[i][j] = f[i][j - 2]; + if (i && (p[j - 2] == '.' || p[j - 2] == s[i - 1])) { + f[i][j] |= f[i - 1][j]; + } + } else if (i && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; + } +}; +``` + +```go +func isMatch(s string, p string) bool { + m, n := len(s), len(p) + f := make([][]bool, m+1) + for i := range f { + f[i] = make([]bool, n+1) + } + f[0][0] = true + for i := 0; i <= m; i++ { + for j := 1; j <= n; j++ { + if p[j-1] == '*' { + f[i][j] = f[i][j-2] + if i > 0 && (p[j-2] == '.' || p[j-2] == s[i-1]) { + f[i][j] = f[i][j] || f[i-1][j] + } + } else if i > 0 && (p[j-1] == '.' || p[j-1] == s[i-1]) { + f[i][j] = f[i-1][j-1] + } + } + } + return f[m][n] +} +``` + +```js +/** + * @param {string} s + * @param {string} p + * @return {boolean} + */ +var isMatch = function (s, p) { + const m = s.length; + const n = p.length; + const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(false)); + f[0][0] = true; + for (let i = 0; i <= m; ++i) { + for (let j = 1; j <= n; ++j) { + if (p[j - 1] === '*') { + f[i][j] = f[i][j - 2]; + if (i && (p[j - 2] === '.' || p[j - 2] === s[i - 1])) { + f[i][j] |= f[i - 1][j]; + } + } else if (i && (p[j - 1] === '.' || p[j - 1] === s[i - 1])) { + f[i][j] = f[i - 1][j - 1]; + } + } + } + return f[m][n]; +}; +``` + ```cs public class Solution { public bool IsMatch(string s, string p) { @@ -458,10 +448,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0011.Container With Most Water/README.md b/solution/0000-0099/0011.Container With Most Water/README.md index 0cc9b5a2414c0..e7bc5153626da 100644 --- a/solution/0000-0099/0011.Container With Most Water/README.md +++ b/solution/0000-0099/0011.Container With Most Water/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 一开始,我们考虑相距最远的两个柱子所能容纳水的容量。水的宽度是两根柱子之间的距离,而水的高度取决于两根柱子之间较短的那个。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def maxArea(self, height: List[int]) -> int: @@ -77,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxArea(int[] height) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func maxArea(height []int) (ans int) { i, j := 0, len(height)-1 @@ -140,14 +126,8 @@ func maxArea(height []int) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} height - * @return {number} - */ -var maxArea = function (height) { +```ts +function maxArea(height: number[]): number { let i = 0; let j = height.length - 1; let ans = 0; @@ -161,13 +141,34 @@ var maxArea = function (height) { } } return ans; -}; +} ``` -### **TypeScript** +```rust +impl Solution { + pub fn max_area(height: Vec) -> i32 { + let mut i = 0; + let mut j = height.len() - 1; + let mut res = 0; + while i < j { + res = res.max(height[i].min(height[j]) * ((j - i) as i32)); + if height[i] <= height[j] { + i += 1; + } else { + j -= 1; + } + } + res + } +} +``` -```ts -function maxArea(height: number[]): number { +```js +/** + * @param {number[]} height + * @return {number} + */ +var maxArea = function (height) { let i = 0; let j = height.length - 1; let ans = 0; @@ -181,11 +182,9 @@ function maxArea(height: number[]): number { } } return ans; -} +}; ``` -### **C#** - ```cs public class Solution { public int MaxArea(int[] height) { @@ -205,31 +204,6 @@ public class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn max_area(height: Vec) -> i32 { - let mut i = 0; - let mut j = height.len() - 1; - let mut res = 0; - while i < j { - res = res.max(height[i].min(height[j]) * ((j - i) as i32)); - if height[i] <= height[j] { - i += 1; - } else { - j -= 1; - } - } - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0011.Container With Most Water/README_EN.md b/solution/0000-0099/0011.Container With Most Water/README_EN.md index da79683de3164..5d6524796ea91 100644 --- a/solution/0000-0099/0011.Container With Most Water/README_EN.md +++ b/solution/0000-0099/0011.Container With Most Water/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers Initially, we consider the capacity of the water that the two farthest pillars can hold. The width of the water is the distance between the two pillars, and the height of the water depends on the shorter one between the two pillars. @@ -51,8 +51,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array `height`. Th -### **Python3** - ```python class Solution: def maxArea(self, height: List[int]) -> int: @@ -68,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxArea(int[] height) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +105,6 @@ public: }; ``` -### **Go** - ```go func maxArea(height []int) (ans int) { i, j := 0, len(height)-1 @@ -129,14 +121,8 @@ func maxArea(height []int) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} height - * @return {number} - */ -var maxArea = function (height) { +```ts +function maxArea(height: number[]): number { let i = 0; let j = height.length - 1; let ans = 0; @@ -150,13 +136,34 @@ var maxArea = function (height) { } } return ans; -}; +} ``` -### **TypeScript** +```rust +impl Solution { + pub fn max_area(height: Vec) -> i32 { + let mut i = 0; + let mut j = height.len() - 1; + let mut res = 0; + while i < j { + res = res.max(height[i].min(height[j]) * ((j - i) as i32)); + if height[i] <= height[j] { + i += 1; + } else { + j -= 1; + } + } + res + } +} +``` -```ts -function maxArea(height: number[]): number { +```js +/** + * @param {number[]} height + * @return {number} + */ +var maxArea = function (height) { let i = 0; let j = height.length - 1; let ans = 0; @@ -170,11 +177,9 @@ function maxArea(height: number[]): number { } } return ans; -} +}; ``` -### **C#** - ```cs public class Solution { public int MaxArea(int[] height) { @@ -194,31 +199,6 @@ public class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn max_area(height: Vec) -> i32 { - let mut i = 0; - let mut j = height.len() - 1; - let mut res = 0; - while i < j { - res = res.max(height[i].min(height[j]) * ((j - i) as i32)); - if height[i] <= height[j] { - i += 1; - } else { - j -= 1; - } - } - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0012.Integer to Roman/README.md b/solution/0000-0099/0012.Integer to Roman/README.md index 9812b11fce83b..da2a77d7b686f 100644 --- a/solution/0000-0099/0012.Integer to Roman/README.md +++ b/solution/0000-0099/0012.Integer to Roman/README.md @@ -75,9 +75,7 @@ M 1000 ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们可以先将所有可能的符号 $cs$ 和对应的数值 $vs$ 列出来,然后从大到小枚举每个数值 $vs[i]$,每次尽可能多地使用该数值对应的符号 $cs[i]$,直到数字 $num$ 变为 $0$。 @@ -85,10 +83,6 @@ M 1000 -### **Python3** - - - ```python class Solution: def intToRoman(self, num: int) -> str: @@ -102,10 +96,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String intToRoman(int num) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func intToRoman(num int) string { cs := []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"} @@ -161,8 +147,6 @@ func intToRoman(num int) string { } ``` -### **TypeScript** - ```ts function intToRoman(num: number): string { const cs: string[] = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']; @@ -178,8 +162,6 @@ function intToRoman(num: number): string { } ``` -### **C#** - ```cs public class Solution { public string IntToRoman(int num) { @@ -197,10 +179,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0012.Integer to Roman/README_EN.md b/solution/0000-0099/0012.Integer to Roman/README_EN.md index 596f3c5329149..2926ade50af37 100644 --- a/solution/0000-0099/0012.Integer to Roman/README_EN.md +++ b/solution/0000-0099/0012.Integer to Roman/README_EN.md @@ -62,7 +62,7 @@ M 1000 ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy We can first list all possible symbols $cs$ and their corresponding values $vs$, then enumerate each value $vs[i]$ from large to small. Each time, we use as many symbols $cs[i]$ corresponding to this value as possible, until the number $num$ becomes $0$. @@ -70,8 +70,6 @@ The time complexity is $O(m)$, and the space complexity is $O(m)$. Here, $m$ is -### **Python3** - ```python class Solution: def intToRoman(self, num: int) -> str: @@ -85,8 +83,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String intToRoman(int num) { @@ -105,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +119,6 @@ public: }; ``` -### **Go** - ```go func intToRoman(num int) string { cs := []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"} @@ -142,8 +134,6 @@ func intToRoman(num int) string { } ``` -### **TypeScript** - ```ts function intToRoman(num: number): string { const cs: string[] = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']; @@ -159,8 +149,6 @@ function intToRoman(num: number): string { } ``` -### **C#** - ```cs public class Solution { public string IntToRoman(int num) { @@ -178,10 +166,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0013.Roman to Integer/README.md b/solution/0000-0099/0013.Roman to Integer/README.md index 79cfd38a35043..a05db1b19cf05 100644 --- a/solution/0000-0099/0013.Roman to Integer/README.md +++ b/solution/0000-0099/0013.Roman to Integer/README.md @@ -80,7 +80,7 @@ M 1000 ## 解法 -**方法一:哈希表 + 模拟** +### 方法一:哈希表 + 模拟 我们先用哈希表 $d$ 记录每个字符对应的数值,然后从左到右遍历字符串 $s$,如果当前字符对应的数值小于右边字符对应的数值,则减去当前字符对应的数值,否则加上当前字符对应的数值。 @@ -90,10 +90,6 @@ M 1000 -### **Python3** - - - ```python class Solution: def romanToInt(self, s: str) -> int: @@ -101,10 +97,6 @@ class Solution: return sum((-1 if d[a] < d[b] else 1) * d[a] for a, b in pairwise(s)) + d[s[-1]] ``` -### **Java** - - - ```java class Solution { public int romanToInt(String s) { @@ -125,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +140,6 @@ public: }; ``` -### **Go** - ```go func romanToInt(s string) (ans int) { d := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} @@ -167,8 +155,6 @@ func romanToInt(s string) (ans int) { } ``` -### **TypeScript** - ```ts function romanToInt(s: string): number { const d: Map = new Map([ @@ -189,8 +175,6 @@ function romanToInt(s: string): number { } ``` -### **JavaScript** - ```js const romanToInt = function (s) { const d = { @@ -211,8 +195,6 @@ const romanToInt = function (s) { }; ``` -### **C#** - ```cs public class Solution { public int RomanToInt(string s) { @@ -234,8 +216,6 @@ public class Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -267,10 +247,41 @@ class Solution { } ``` -### **...** - -``` - +```rb +# @param {String} s +# @return {Integer} +def roman_to_int(s) + hash = Hash[ + 'I' => 1, + 'V' => 5, + 'X' => 10, + 'L' => 50, + 'C' => 100, + 'D' => 500, + 'M' => 1000, + 'IV' => 4, + 'IX' => 9, + 'XL' => 40, + 'XC' => 90, + 'CD' => 400, + 'CM' => 900 + ] + res = 0 + i = 0 + while i < s.length + if i < s.length - 1 && !hash[s[i..i+1]].nil? + res += hash[s[i..i+1]] + i += 2 + else + res += hash[s[i]] + i += 1 + end + end + + res +end ``` + + diff --git a/solution/0000-0099/0013.Roman to Integer/README_EN.md b/solution/0000-0099/0013.Roman to Integer/README_EN.md index f5f07c0a3d69a..dfd40b9e7c4c3 100644 --- a/solution/0000-0099/0013.Roman to Integer/README_EN.md +++ b/solution/0000-0099/0013.Roman to Integer/README_EN.md @@ -64,7 +64,7 @@ M 1000 ## Solutions -**Solution 1: Hash Table + Simulation** +### Solution 1: Hash Table + Simulation First, we use a hash table $d$ to record the numerical value corresponding to each character. Then, we traverse the string $s$ from left to right. If the numerical value corresponding to the current character is less than the numerical value corresponding to the character on the right, we subtract the numerical value corresponding to the current character. Otherwise, we add the numerical value corresponding to the current character. @@ -72,8 +72,6 @@ The time complexity is $O(n)$, and the space complexity is $O(m)$. Here, $n$ and -### **Python3** - ```python class Solution: def romanToInt(self, s: str) -> int: @@ -81,8 +79,6 @@ class Solution: return sum((-1 if d[a] < d[b] else 1) * d[a] for a, b in pairwise(s)) + d[s[-1]] ``` -### **Java** - ```java class Solution { public int romanToInt(String s) { @@ -103,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +122,6 @@ public: }; ``` -### **Go** - ```go func romanToInt(s string) (ans int) { d := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} @@ -145,8 +137,6 @@ func romanToInt(s string) (ans int) { } ``` -### **TypeScript** - ```ts function romanToInt(s: string): number { const d: Map = new Map([ @@ -167,8 +157,6 @@ function romanToInt(s: string): number { } ``` -### **JavaScript** - ```js const romanToInt = function (s) { const d = { @@ -189,8 +177,6 @@ const romanToInt = function (s) { }; ``` -### **C#** - ```cs public class Solution { public int RomanToInt(string s) { @@ -212,8 +198,6 @@ public class Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -245,10 +229,41 @@ class Solution { } ``` -### **...** - -``` - +```rb +# @param {String} s +# @return {Integer} +def roman_to_int(s) + hash = Hash[ + 'I' => 1, + 'V' => 5, + 'X' => 10, + 'L' => 50, + 'C' => 100, + 'D' => 500, + 'M' => 1000, + 'IV' => 4, + 'IX' => 9, + 'XL' => 40, + 'XC' => 90, + 'CD' => 400, + 'CM' => 900 + ] + res = 0 + i = 0 + while i < s.length + if i < s.length - 1 && !hash[s[i..i+1]].nil? + res += hash[s[i..i+1]] + i += 2 + else + res += hash[s[i]] + i += 1 + end + end + + res +end ``` + + diff --git a/solution/0000-0099/0014.Longest Common Prefix/README.md b/solution/0000-0099/0014.Longest Common Prefix/README.md index 3eca57184aa0a..1a26c5b8f0ca1 100644 --- a/solution/0000-0099/0014.Longest Common Prefix/README.md +++ b/solution/0000-0099/0014.Longest Common Prefix/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:字符比较** +### 方法一:字符比较 我们以第一个字符串 $strs[0]$ 为基准,依次比较后面的字符串的第 $i$ 个字符是否与 $strs[0]$ 的第 $i$ 个字符相同,如果相同则继续比较下一个字符,否则返回 $strs[0]$ 的前 $i$ 个字符。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: @@ -64,10 +58,6 @@ class Solution: return strs[0] ``` -### **Java** - - - ```java class Solution { public String longestCommonPrefix(String[] strs) { @@ -84,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +91,6 @@ public: }; ``` -### **Go** - ```go func longestCommonPrefix(strs []string) string { n := len(strs) @@ -119,75 +105,6 @@ func longestCommonPrefix(strs []string) string { } ``` -### **C#** - -```cs -public class Solution { - public string LongestCommonPrefix(string[] strs) { - int n = strs.Length; - for (int i = 0; i < strs[0].Length; ++i) { - for (int j = 1; j < n; ++j) { - if (i >= strs[j].Length || strs[j][i] != strs[0][i]) { - return strs[0].Substring(0, i); - } - } - } - return strs[0]; - } -} -``` - -### **Ruby** - -```rb -# @param {String[]} strs -# @return {String} -def longest_common_prefix(strs) - return '' if strs.nil? || strs.length.zero? - - return strs[0] if strs.length == 1 - - idx = 0 - while idx < strs[0].length - cur_char = strs[0][idx] - - str_idx = 1 - while str_idx < strs.length - return idx > 0 ? strs[0][0..idx-1] : '' if strs[str_idx].length <= idx - - return '' if strs[str_idx][idx] != cur_char && idx.zero? - return strs[0][0..idx - 1] if strs[str_idx][idx] != cur_char - str_idx += 1 - end - - idx += 1 - end - - idx > 0 ? strs[0][0..idx] : '' -end -``` - -### **JavaScript** - -```js -/** - * @param {string[]} strs - * @return {string} - */ -var longestCommonPrefix = function (strs) { - for (let j = 0; j < strs[0].length; j++) { - for (let i = 0; i < strs.length; i++) { - if (strs[0][j] !== strs[i][j]) { - return strs[0].substring(0, j); - } - } - } - return strs[0]; -}; -``` - -### **TypeScript** - ```ts function longestCommonPrefix(strs: string[]): string { const len = strs.reduce((r, s) => Math.min(r, s.length), Infinity); @@ -201,8 +118,6 @@ function longestCommonPrefix(strs: string[]): string { } ``` -### **Rust** - ```rust impl Solution { pub fn longest_common_prefix(strs: Vec) -> String { @@ -223,7 +138,38 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {string[]} strs + * @return {string} + */ +var longestCommonPrefix = function (strs) { + for (let j = 0; j < strs[0].length; j++) { + for (let i = 0; i < strs.length; i++) { + if (strs[0][j] !== strs[i][j]) { + return strs[0].substring(0, j); + } + } + } + return strs[0]; +}; +``` + +```cs +public class Solution { + public string LongestCommonPrefix(string[] strs) { + int n = strs.Length; + for (int i = 0; i < strs[0].Length; ++i) { + for (int j = 1; j < n; ++j) { + if (i >= strs[j].Length || strs[j][i] != strs[0][i]) { + return strs[0].Substring(0, i); + } + } + } + return strs[0]; + } +} +``` ```php class Solution { @@ -246,10 +192,34 @@ class Solution { } ``` -### **...** +```rb +# @param {String[]} strs +# @return {String} +def longest_common_prefix(strs) + return '' if strs.nil? || strs.length.zero? + + return strs[0] if strs.length == 1 -``` + idx = 0 + while idx < strs[0].length + cur_char = strs[0][idx] + + str_idx = 1 + while str_idx < strs.length + return idx > 0 ? strs[0][0..idx-1] : '' if strs[str_idx].length <= idx + + return '' if strs[str_idx][idx] != cur_char && idx.zero? + return strs[0][0..idx - 1] if strs[str_idx][idx] != cur_char + str_idx += 1 + end + + idx += 1 + end + idx > 0 ? strs[0][0..idx] : '' +end ``` + + diff --git a/solution/0000-0099/0014.Longest Common Prefix/README_EN.md b/solution/0000-0099/0014.Longest Common Prefix/README_EN.md index 5590f153d672e..4eec74d071635 100644 --- a/solution/0000-0099/0014.Longest Common Prefix/README_EN.md +++ b/solution/0000-0099/0014.Longest Common Prefix/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Character Comparison** +### Solution 1: Character Comparison We use the first string $strs[0]$ as a benchmark, and compare whether the $i$-th character of the subsequent strings is the same as the $i$-th character of $strs[0]$. If they are the same, we continue to compare the next character. Otherwise, we return the first $i$ characters of $strs[0]$. @@ -45,8 +45,6 @@ The time complexity is $O(n \times m)$, where $n$ and $m$ are the length of the -### **Python3** - ```python class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: @@ -57,8 +55,6 @@ class Solution: return strs[0] ``` -### **Java** - ```java class Solution { public String longestCommonPrefix(String[] strs) { @@ -75,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +88,6 @@ public: }; ``` -### **Go** - ```go func longestCommonPrefix(strs []string) string { n := len(strs) @@ -110,75 +102,6 @@ func longestCommonPrefix(strs []string) string { } ``` -### **C#** - -```cs -public class Solution { - public string LongestCommonPrefix(string[] strs) { - int n = strs.Length; - for (int i = 0; i < strs[0].Length; ++i) { - for (int j = 1; j < n; ++j) { - if (i >= strs[j].Length || strs[j][i] != strs[0][i]) { - return strs[0].Substring(0, i); - } - } - } - return strs[0]; - } -} -``` - -### **Ruby** - -```rb -# @param {String[]} strs -# @return {String} -def longest_common_prefix(strs) - return '' if strs.nil? || strs.length.zero? - - return strs[0] if strs.length == 1 - - idx = 0 - while idx < strs[0].length - cur_char = strs[0][idx] - - str_idx = 1 - while str_idx < strs.length - return idx > 0 ? strs[0][0..idx-1] : '' if strs[str_idx].length <= idx - - return '' if strs[str_idx][idx] != cur_char && idx.zero? - return strs[0][0..idx - 1] if strs[str_idx][idx] != cur_char - str_idx += 1 - end - - idx += 1 - end - - idx > 0 ? strs[0][0..idx] : '' -end -``` - -### **JavaScript** - -```js -/** - * @param {string[]} strs - * @return {string} - */ -var longestCommonPrefix = function (strs) { - for (let j = 0; j < strs[0].length; j++) { - for (let i = 0; i < strs.length; i++) { - if (strs[0][j] !== strs[i][j]) { - return strs[0].substring(0, j); - } - } - } - return strs[0]; -}; -``` - -### **TypeScript** - ```ts function longestCommonPrefix(strs: string[]): string { const len = strs.reduce((r, s) => Math.min(r, s.length), Infinity); @@ -192,8 +115,6 @@ function longestCommonPrefix(strs: string[]): string { } ``` -### **Rust** - ```rust impl Solution { pub fn longest_common_prefix(strs: Vec) -> String { @@ -214,7 +135,38 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {string[]} strs + * @return {string} + */ +var longestCommonPrefix = function (strs) { + for (let j = 0; j < strs[0].length; j++) { + for (let i = 0; i < strs.length; i++) { + if (strs[0][j] !== strs[i][j]) { + return strs[0].substring(0, j); + } + } + } + return strs[0]; +}; +``` + +```cs +public class Solution { + public string LongestCommonPrefix(string[] strs) { + int n = strs.Length; + for (int i = 0; i < strs[0].Length; ++i) { + for (int j = 1; j < n; ++j) { + if (i >= strs[j].Length || strs[j][i] != strs[0][i]) { + return strs[0].Substring(0, i); + } + } + } + return strs[0]; + } +} +``` ```php class Solution { @@ -237,10 +189,34 @@ class Solution { } ``` -### **...** +```rb +# @param {String[]} strs +# @return {String} +def longest_common_prefix(strs) + return '' if strs.nil? || strs.length.zero? + + return strs[0] if strs.length == 1 -``` + idx = 0 + while idx < strs[0].length + cur_char = strs[0][idx] + + str_idx = 1 + while str_idx < strs.length + return idx > 0 ? strs[0][0..idx-1] : '' if strs[str_idx].length <= idx + + return '' if strs[str_idx][idx] != cur_char && idx.zero? + return strs[0][0..idx - 1] if strs[str_idx][idx] != cur_char + str_idx += 1 + end + + idx += 1 + end + idx > 0 ? strs[0][0..idx] : '' +end ``` + + diff --git a/solution/0000-0099/0015.3Sum/README.md b/solution/0000-0099/0015.3Sum/README.md index 5ac5cbab03bce..843260c2b1ae3 100644 --- a/solution/0000-0099/0015.3Sum/README.md +++ b/solution/0000-0099/0015.3Sum/README.md @@ -56,9 +56,7 @@ nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。 ## 解法 - - -**方法一:排序 + 双指针** +### 方法一:排序 + 双指针 我们注意到,题目不要求我们按照顺序返回三元组,因此我们不妨先对数组进行排序,这样就可以方便地跳过重复的元素。 @@ -82,10 +80,6 @@ nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。 -### **Python3** - - - ```python class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: @@ -114,10 +108,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> threeSum(int[] nums) { @@ -151,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -187,8 +175,6 @@ public: }; ``` -### **Go** - ```go func threeSum(nums []int) (ans [][]int) { sort.Ints(nums) @@ -220,8 +206,6 @@ func threeSum(nums []int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function threeSum(nums: number[]): number[][] { nums.sort((a, b) => a - b); @@ -254,7 +238,48 @@ function threeSum(nums: number[]): number[][] { } ``` -### **JavaScript** +```rust +use std::cmp::Ordering; + +impl Solution { + pub fn three_sum(mut nums: Vec) -> Vec> { + nums.sort(); + let n = nums.len(); + let mut res = vec![]; + let mut i = 0; + while i < n - 2 && nums[i] <= 0 { + let mut l = i + 1; + let mut r = n - 1; + while l < r { + match (nums[i] + nums[l] + nums[r]).cmp(&0) { + Ordering::Less => { + l += 1; + } + Ordering::Greater => { + r -= 1; + } + Ordering::Equal => { + res.push(vec![nums[i], nums[l], nums[r]]); + l += 1; + r -= 1; + while l < n && nums[l] == nums[l - 1] { + l += 1; + } + while r > 0 && nums[r] == nums[r + 1] { + r -= 1; + } + } + } + } + i += 1; + while i < n - 2 && nums[i] == nums[i - 1] { + i += 1; + } + } + res + } +} +``` ```js /** @@ -292,8 +317,6 @@ var threeSum = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public IList> ThreeSum(int[] nums) { @@ -327,8 +350,6 @@ public class Solution { } ``` -### **Ruby** - ```rb # @param {Integer[]} nums # @return {Integer[][]} @@ -360,55 +381,6 @@ def three_sum(nums) end ``` -### **Rust** - -```rust -use std::cmp::Ordering; - -impl Solution { - pub fn three_sum(mut nums: Vec) -> Vec> { - nums.sort(); - let n = nums.len(); - let mut res = vec![]; - let mut i = 0; - while i < n - 2 && nums[i] <= 0 { - let mut l = i + 1; - let mut r = n - 1; - while l < r { - match (nums[i] + nums[l] + nums[r]).cmp(&0) { - Ordering::Less => { - l += 1; - } - Ordering::Greater => { - r -= 1; - } - Ordering::Equal => { - res.push(vec![nums[i], nums[l], nums[r]]); - l += 1; - r -= 1; - while l < n && nums[l] == nums[l - 1] { - l += 1; - } - while r > 0 && nums[r] == nums[r + 1] { - r -= 1; - } - } - } - } - i += 1; - while i < n - 2 && nums[i] == nums[i - 1] { - i += 1; - } - } - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0015.3Sum/README_EN.md b/solution/0000-0099/0015.3Sum/README_EN.md index b27095b114987..7251bd6512399 100644 --- a/solution/0000-0099/0015.3Sum/README_EN.md +++ b/solution/0000-0099/0015.3Sum/README_EN.md @@ -48,7 +48,7 @@ Notice that the order of the output and the order of the triplets does not matte ## Solutions -**Solution 1: Sort + Two Pointers** +### Solution 1: Sort + Two Pointers We notice that the problem does not require us to return the triplet in order, so we might as well sort the array first, which makes it easy to skip duplicate elements. @@ -72,8 +72,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(\log n)$. The $n -### **Python3** - ```python class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: @@ -102,8 +100,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List> threeSum(int[] nums) { @@ -137,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -173,8 +167,6 @@ public: }; ``` -### **Go** - ```go func threeSum(nums []int) (ans [][]int) { sort.Ints(nums) @@ -206,8 +198,6 @@ func threeSum(nums []int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function threeSum(nums: number[]): number[][] { nums.sort((a, b) => a - b); @@ -240,7 +230,48 @@ function threeSum(nums: number[]): number[][] { } ``` -### **JavaScript** +```rust +use std::cmp::Ordering; + +impl Solution { + pub fn three_sum(mut nums: Vec) -> Vec> { + nums.sort(); + let n = nums.len(); + let mut res = vec![]; + let mut i = 0; + while i < n - 2 && nums[i] <= 0 { + let mut l = i + 1; + let mut r = n - 1; + while l < r { + match (nums[i] + nums[l] + nums[r]).cmp(&0) { + Ordering::Less => { + l += 1; + } + Ordering::Greater => { + r -= 1; + } + Ordering::Equal => { + res.push(vec![nums[i], nums[l], nums[r]]); + l += 1; + r -= 1; + while l < n && nums[l] == nums[l - 1] { + l += 1; + } + while r > 0 && nums[r] == nums[r + 1] { + r -= 1; + } + } + } + } + i += 1; + while i < n - 2 && nums[i] == nums[i - 1] { + i += 1; + } + } + res + } +} +``` ```js /** @@ -278,8 +309,6 @@ var threeSum = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public IList> ThreeSum(int[] nums) { @@ -313,8 +342,6 @@ public class Solution { } ``` -### **Ruby** - ```rb # @param {Integer[]} nums # @return {Integer[][]} @@ -346,55 +373,6 @@ def three_sum(nums) end ``` -### **Rust** - -```rust -use std::cmp::Ordering; - -impl Solution { - pub fn three_sum(mut nums: Vec) -> Vec> { - nums.sort(); - let n = nums.len(); - let mut res = vec![]; - let mut i = 0; - while i < n - 2 && nums[i] <= 0 { - let mut l = i + 1; - let mut r = n - 1; - while l < r { - match (nums[i] + nums[l] + nums[r]).cmp(&0) { - Ordering::Less => { - l += 1; - } - Ordering::Greater => { - r -= 1; - } - Ordering::Equal => { - res.push(vec![nums[i], nums[l], nums[r]]); - l += 1; - r -= 1; - while l < n && nums[l] == nums[l - 1] { - l += 1; - } - while r > 0 && nums[r] == nums[r + 1] { - r -= 1; - } - } - } - } - i += 1; - while i < n - 2 && nums[i] == nums[i - 1] { - i += 1; - } - } - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0016.3Sum Closest/README.md b/solution/0000-0099/0016.3Sum Closest/README.md index 8fd2fae381f91..9c0e59f104442 100644 --- a/solution/0000-0099/0016.3Sum Closest/README.md +++ b/solution/0000-0099/0016.3Sum Closest/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:排序 + 双指针** +### 方法一:排序 + 双指针 我们将数组排序,然后遍历数组,对于每个元素 $nums[i]$,我们使用指针 $j$ 和 $k$ 分别指向 $i+1$ 和 $n-1$,计算三数之和,如果三数之和等于 $target$,则直接返回 $target$,否则根据与 $target$ 的差值更新答案。如果三数之和大于 $target$,则将 $k$ 向左移动一位,否则将 $j$ 向右移动一位。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: @@ -76,10 +70,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int threeSumClosest(int[] nums, int target) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func threeSumClosest(nums []int, target int) int { sort.Ints(nums) @@ -169,23 +155,16 @@ func abs(x int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} target - * @return {number} - */ -var threeSumClosest = function (nums, target) { +```ts +function threeSumClosest(nums: number[], target: number): number { nums.sort((a, b) => a - b); - let ans = 1 << 30; + let ans: number = 1 << 30; const n = nums.length; for (let i = 0; i < n; ++i) { let j = i + 1; let k = n - 1; while (j < k) { - const t = nums[i] + nums[j] + nums[k]; + const t: number = nums[i] + nums[j] + nums[k]; if (t === target) { return t; } @@ -200,21 +179,24 @@ var threeSumClosest = function (nums, target) { } } return ans; -}; +} ``` -### **TypeScript** - -```ts -function threeSumClosest(nums: number[], target: number): number { +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var threeSumClosest = function (nums, target) { nums.sort((a, b) => a - b); - let ans: number = 1 << 30; + let ans = 1 << 30; const n = nums.length; for (let i = 0; i < n; ++i) { let j = i + 1; let k = n - 1; while (j < k) { - const t: number = nums[i] + nums[j] + nums[k]; + const t = nums[i] + nums[j] + nums[k]; if (t === target) { return t; } @@ -229,13 +211,9 @@ function threeSumClosest(nums: number[], target: number): number { } } return ans; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0000-0099/0016.3Sum Closest/README_EN.md b/solution/0000-0099/0016.3Sum Closest/README_EN.md index 55514a8825cbb..deda27b147ac9 100644 --- a/solution/0000-0099/0016.3Sum Closest/README_EN.md +++ b/solution/0000-0099/0016.3Sum Closest/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Sorting + Two Pointers** +### Solution 1: Sorting + Two Pointers We sort the array first, then traverse the array. For each element $nums[i]$, we use pointers $j$ and $k$ to point to $i+1$ and $n-1$ respectively, calculate the sum of the three numbers. If the sum of the three numbers equals $target$, we directly return $target$. Otherwise, we update the answer based on the difference from $target$. If the sum of the three numbers is greater than $target$, we move $k$ one place to the left, otherwise, we move $j$ one place to the right. @@ -46,8 +46,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(\log n)$. Here, -### **Python3** - ```python class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: @@ -69,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int threeSumClosest(int[] nums, int target) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +119,6 @@ public: }; ``` -### **Go** - ```go func threeSumClosest(nums []int, target int) int { sort.Ints(nums) @@ -160,23 +152,16 @@ func abs(x int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} target - * @return {number} - */ -var threeSumClosest = function (nums, target) { +```ts +function threeSumClosest(nums: number[], target: number): number { nums.sort((a, b) => a - b); - let ans = 1 << 30; + let ans: number = 1 << 30; const n = nums.length; for (let i = 0; i < n; ++i) { let j = i + 1; let k = n - 1; while (j < k) { - const t = nums[i] + nums[j] + nums[k]; + const t: number = nums[i] + nums[j] + nums[k]; if (t === target) { return t; } @@ -191,21 +176,24 @@ var threeSumClosest = function (nums, target) { } } return ans; -}; +} ``` -### **TypeScript** - -```ts -function threeSumClosest(nums: number[], target: number): number { +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var threeSumClosest = function (nums, target) { nums.sort((a, b) => a - b); - let ans: number = 1 << 30; + let ans = 1 << 30; const n = nums.length; for (let i = 0; i < n; ++i) { let j = i + 1; let k = n - 1; while (j < k) { - const t: number = nums[i] + nums[j] + nums[k]; + const t = nums[i] + nums[j] + nums[k]; if (t === target) { return t; } @@ -220,13 +208,9 @@ function threeSumClosest(nums: number[], target: number): number { } } return ans; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/README.md b/solution/0000-0099/0017.Letter Combinations of a Phone Number/README.md index 6cfc247979a3f..e25ba6741165b 100644 --- a/solution/0000-0099/0017.Letter Combinations of a Phone Number/README.md +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/README.md @@ -46,26 +46,14 @@ ## 解法 - - -**方法一:遍历** +### 方法一:遍历 我们先用一个数组或者哈希表存储每个数字对应的字母,然后遍历每个数字,将其对应的字母与之前的结果进行组合,得到新的结果。 时间复杂度 $O(4^n)$。空间复杂度 $O(4^n)$。其中 $n$ 是输入数字的长度。 -**方法二:DFS** - -我们可以使用深度优先搜索的方法,枚举所有可能的字母组合。假设当前已经产生了一部分字母组合,但是还有一些数字没有被穷举到,此时我们取出下一个数字所对应的字母,然后依次枚举这个数字所对应的每一个字母,将它们添加到前面已经产生的字母组合后面,形成所有可能的组合。 - -时间复杂度 $O(4^n)$。空间复杂度 $O(n)$。其中 $n$ 是输入数字的长度。 - -### **Python3** - - - ```python class Solution: def letterCombinations(self, digits: str) -> List[str]: @@ -79,31 +67,6 @@ class Solution: return ans ``` -```python -class Solution: - def letterCombinations(self, digits: str) -> List[str]: - def dfs(i: int): - if i >= len(digits): - ans.append("".join(t)) - return - for c in d[int(digits[i]) - 2]: - t.append(c) - dfs(i + 1) - t.pop() - - if not digits: - return [] - d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] - ans = [] - t = [] - dfs(0) - return ans -``` - -### **Java** - - - ```java class Solution { public List letterCombinations(String digits) { @@ -128,39 +91,6 @@ class Solution { } ``` -```java -class Solution { - private final String[] d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; - private String digits; - private List ans = new ArrayList<>(); - private StringBuilder t = new StringBuilder(); - - public List letterCombinations(String digits) { - if (digits.length() == 0) { - return ans; - } - this.digits = digits; - dfs(0); - return ans; - } - - private void dfs(int i) { - if (i >= digits.length()) { - ans.add(t.toString()); - return; - } - String s = d[digits.charAt(i) - '2']; - for (char c : s.toCharArray()) { - t.append(c); - dfs(i + 1); - t.deleteCharAt(t.length() - 1); - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -185,35 +115,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector letterCombinations(string digits) { - if (digits.empty()) { - return {}; - } - vector d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; - vector ans; - string t; - function dfs = [&](int i) { - if (i >= digits.size()) { - ans.push_back(t); - return; - } - for (auto& c : d[digits[i] - '2']) { - t.push_back(c); - dfs(i + 1); - t.pop_back(); - } - }; - dfs(0); - return ans; - } -}; -``` - -### **Go** - ```go func letterCombinations(digits string) []string { ans := []string{} @@ -236,46 +137,16 @@ func letterCombinations(digits string) []string { } ``` -```go -func letterCombinations(digits string) (ans []string) { - d := []string{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"} - t := []rune{} - var dfs func(int) - dfs = func(i int) { - if i >= len(digits) { - ans = append(ans, string(t)) - return - } - for _, c := range d[digits[i]-'2'] { - t = append(t, c) - dfs(i + 1) - t = t[:len(t)-1] - } - } - if len(digits) == 0 { - return - } - dfs(0) - return -} -``` - -### **JavaScript** - -```js -/** - * @param {string} digits - * @return {string[]} - */ -var letterCombinations = function (digits) { +```ts +function letterCombinations(digits: string): string[] { if (digits.length == 0) { return []; } - const ans = ['']; + const ans: string[] = ['']; const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']; for (const i of digits) { const s = d[parseInt(i) - 2]; - const t = []; + const t: string[] = []; for (const a of ans) { for (const b of s) { t.push(a + b); @@ -284,7 +155,31 @@ var letterCombinations = function (digits) { ans.splice(0, ans.length, ...t); } return ans; -}; +} +``` + +```rust +impl Solution { + pub fn letter_combinations(digits: String) -> Vec { + let mut ans: Vec = Vec::new(); + if digits.is_empty() { + return ans; + } + ans.push("".to_string()); + let d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]; + for i in digits.chars() { + let s = &d[((i as u8) - b'2') as usize]; + let mut t: Vec = Vec::new(); + for a in &ans { + for b in s.chars() { + t.push(format!("{}{}", a, b)); + } + } + ans = t; + } + ans + } +} ``` ```js @@ -296,28 +191,22 @@ var letterCombinations = function (digits) { if (digits.length == 0) { return []; } - const ans = []; - const t = []; + const ans = ['']; const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']; - const dfs = i => { - if (i >= digits.length) { - ans.push(t.join('')); - return; - } - const s = d[parseInt(digits[i]) - 2]; - for (const c of s) { - t.push(c); - dfs(i + 1); - t.pop(); + for (const i of digits) { + const s = d[parseInt(i) - 2]; + const t = []; + for (const a of ans) { + for (const b of s) { + t.push(a + b); + } } - }; - dfs(0); + ans.splice(0, ans.length, ...t); + } return ans; }; ``` -### **C#** - ```cs public class Solution { public IList LetterCombinations(string digits) { @@ -342,57 +231,116 @@ public class Solution { } ``` -```cs -public class Solution { - private readonly string[] d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; - private string digits; - private List ans = new List(); - private System.Text.StringBuilder t = new System.Text.StringBuilder(); + - public IList LetterCombinations(string digits) { - if (digits.Length == 0) { +### 方法二:DFS + +我们可以使用深度优先搜索的方法,枚举所有可能的字母组合。假设当前已经产生了一部分字母组合,但是还有一些数字没有被穷举到,此时我们取出下一个数字所对应的字母,然后依次枚举这个数字所对应的每一个字母,将它们添加到前面已经产生的字母组合后面,形成所有可能的组合。 + +时间复杂度 $O(4^n)$。空间复杂度 $O(n)$。其中 $n$ 是输入数字的长度。 + + + +```python +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + def dfs(i: int): + if i >= len(digits): + ans.append("".join(t)) + return + for c in d[int(digits[i]) - 2]: + t.append(c) + dfs(i + 1) + t.pop() + + if not digits: + return [] + d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] + ans = [] + t = [] + dfs(0) + return ans +``` + +```java +class Solution { + private final String[] d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + private String digits; + private List ans = new ArrayList<>(); + private StringBuilder t = new StringBuilder(); + + public List letterCombinations(String digits) { + if (digits.length() == 0) { return ans; } this.digits = digits; - Dfs(0); + dfs(0); return ans; } - private void Dfs(int i) { - if (i >= digits.Length) { - ans.Add(t.ToString()); + private void dfs(int i) { + if (i >= digits.length()) { + ans.add(t.toString()); return; } - string s = d[digits[i] - '2']; - foreach (char c in s) { - t.Append(c); - Dfs(i + 1); - t.Remove(t.Length - 1, 1); + String s = d[digits.charAt(i) - '2']; + for (char c : s.toCharArray()) { + t.append(c); + dfs(i + 1); + t.deleteCharAt(t.length() - 1); } } } ``` -### **TypeScript** - -```ts -function letterCombinations(digits: string): string[] { - if (digits.length == 0) { - return []; - } - const ans: string[] = ['']; - const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']; - for (const i of digits) { - const s = d[parseInt(i) - 2]; - const t: string[] = []; - for (const a of ans) { - for (const b of s) { - t.push(a + b); - } +```cpp +class Solution { +public: + vector letterCombinations(string digits) { + if (digits.empty()) { + return {}; } - ans.splice(0, ans.length, ...t); + vector d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + vector ans; + string t; + function dfs = [&](int i) { + if (i >= digits.size()) { + ans.push_back(t); + return; + } + for (auto& c : d[digits[i] - '2']) { + t.push_back(c); + dfs(i + 1); + t.pop_back(); + } + }; + dfs(0); + return ans; } - return ans; +}; +``` + +```go +func letterCombinations(digits string) (ans []string) { + d := []string{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"} + t := []rune{} + var dfs func(int) + dfs = func(i int) { + if i >= len(digits) { + ans = append(ans, string(t)) + return + } + for _, c := range d[digits[i]-'2'] { + t = append(t, c) + dfs(i + 1) + t = t[:len(t)-1] + } + } + if len(digits) == 0 { + return + } + dfs(0) + return } ``` @@ -421,32 +369,6 @@ function letterCombinations(digits: string): string[] { } ``` -### **Rust** - -```rust -impl Solution { - pub fn letter_combinations(digits: String) -> Vec { - let mut ans: Vec = Vec::new(); - if digits.is_empty() { - return ans; - } - ans.push("".to_string()); - let d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]; - for i in digits.chars() { - let s = &d[((i as u8) - b'2') as usize]; - let mut t: Vec = Vec::new(); - for a in &ans { - for b in s.chars() { - t.push(format!("{}{}", a, b)); - } - } - ans = t; - } - ans - } -} -``` - ```rust impl Solution { pub fn letter_combinations(digits: String) -> Vec { @@ -475,10 +397,66 @@ impl Solution { } ``` -### **...** - +```js +/** + * @param {string} digits + * @return {string[]} + */ +var letterCombinations = function (digits) { + if (digits.length == 0) { + return []; + } + const ans = []; + const t = []; + const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']; + const dfs = i => { + if (i >= digits.length) { + ans.push(t.join('')); + return; + } + const s = d[parseInt(digits[i]) - 2]; + for (const c of s) { + t.push(c); + dfs(i + 1); + t.pop(); + } + }; + dfs(0); + return ans; +}; ``` +```cs +public class Solution { + private readonly string[] d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + private string digits; + private List ans = new List(); + private System.Text.StringBuilder t = new System.Text.StringBuilder(); + + public IList LetterCombinations(string digits) { + if (digits.Length == 0) { + return ans; + } + this.digits = digits; + Dfs(0); + return ans; + } + + private void Dfs(int i) { + if (i >= digits.Length) { + ans.Add(t.ToString()); + return; + } + string s = d[digits[i] - '2']; + foreach (char c in s) { + t.Append(c); + Dfs(i + 1); + t.Remove(t.Length - 1, 1); + } + } +} ``` + + diff --git a/solution/0000-0099/0017.Letter Combinations of a Phone Number/README_EN.md b/solution/0000-0099/0017.Letter Combinations of a Phone Number/README_EN.md index f9e0e6d06f71f..cb8ae61362fa9 100644 --- a/solution/0000-0099/0017.Letter Combinations of a Phone Number/README_EN.md +++ b/solution/0000-0099/0017.Letter Combinations of a Phone Number/README_EN.md @@ -40,22 +40,14 @@ ## Solutions -**Solution 1: Traversal** +### Solution 1: Traversal First, we use an array or hash table to store the letters corresponding to each digit. Then we traverse each digit, combine its corresponding letters with the previous results to get the new results. The time complexity is $O(4^n)$, and the space complexity is $O(4^n)$. Here, $n$ is the length of the input digits. -**Solution 2: DFS** - -We can use the method of depth-first search to enumerate all possible letter combinations. Suppose that a part of the letter combination has been generated, but some digits have not been exhausted. At this time, we take out the letters corresponding to the next digit, and then enumerate each letter corresponding to this digit one by one, add them to the letter combination that has been generated before, to form all possible combinations. - -The time complexity is $O(4^n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the input digits. - -### **Python3** - ```python class Solution: def letterCombinations(self, digits: str) -> List[str]: @@ -69,29 +61,6 @@ class Solution: return ans ``` -```python -class Solution: - def letterCombinations(self, digits: str) -> List[str]: - def dfs(i: int): - if i >= len(digits): - ans.append("".join(t)) - return - for c in d[int(digits[i]) - 2]: - t.append(c) - dfs(i + 1) - t.pop() - - if not digits: - return [] - d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] - ans = [] - t = [] - dfs(0) - return ans -``` - -### **Java** - ```java class Solution { public List letterCombinations(String digits) { @@ -116,39 +85,6 @@ class Solution { } ``` -```java -class Solution { - private final String[] d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; - private String digits; - private List ans = new ArrayList<>(); - private StringBuilder t = new StringBuilder(); - - public List letterCombinations(String digits) { - if (digits.length() == 0) { - return ans; - } - this.digits = digits; - dfs(0); - return ans; - } - - private void dfs(int i) { - if (i >= digits.length()) { - ans.add(t.toString()); - return; - } - String s = d[digits.charAt(i) - '2']; - for (char c : s.toCharArray()) { - t.append(c); - dfs(i + 1); - t.deleteCharAt(t.length() - 1); - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -173,35 +109,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector letterCombinations(string digits) { - if (digits.empty()) { - return {}; - } - vector d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; - vector ans; - string t; - function dfs = [&](int i) { - if (i >= digits.size()) { - ans.push_back(t); - return; - } - for (auto& c : d[digits[i] - '2']) { - t.push_back(c); - dfs(i + 1); - t.pop_back(); - } - }; - dfs(0); - return ans; - } -}; -``` - -### **Go** - ```go func letterCombinations(digits string) []string { ans := []string{} @@ -224,46 +131,16 @@ func letterCombinations(digits string) []string { } ``` -```go -func letterCombinations(digits string) (ans []string) { - d := []string{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"} - t := []rune{} - var dfs func(int) - dfs = func(i int) { - if i >= len(digits) { - ans = append(ans, string(t)) - return - } - for _, c := range d[digits[i]-'2'] { - t = append(t, c) - dfs(i + 1) - t = t[:len(t)-1] - } - } - if len(digits) == 0 { - return - } - dfs(0) - return -} -``` - -### **JavaScript** - -```js -/** - * @param {string} digits - * @return {string[]} - */ -var letterCombinations = function (digits) { +```ts +function letterCombinations(digits: string): string[] { if (digits.length == 0) { return []; } - const ans = ['']; + const ans: string[] = ['']; const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']; for (const i of digits) { const s = d[parseInt(i) - 2]; - const t = []; + const t: string[] = []; for (const a of ans) { for (const b of s) { t.push(a + b); @@ -272,7 +149,31 @@ var letterCombinations = function (digits) { ans.splice(0, ans.length, ...t); } return ans; -}; +} +``` + +```rust +impl Solution { + pub fn letter_combinations(digits: String) -> Vec { + let mut ans: Vec = Vec::new(); + if digits.is_empty() { + return ans; + } + ans.push("".to_string()); + let d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]; + for i in digits.chars() { + let s = &d[((i as u8) - b'2') as usize]; + let mut t: Vec = Vec::new(); + for a in &ans { + for b in s.chars() { + t.push(format!("{}{}", a, b)); + } + } + ans = t; + } + ans + } +} ``` ```js @@ -284,28 +185,22 @@ var letterCombinations = function (digits) { if (digits.length == 0) { return []; } - const ans = []; - const t = []; + const ans = ['']; const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']; - const dfs = i => { - if (i >= digits.length) { - ans.push(t.join('')); - return; - } - const s = d[parseInt(digits[i]) - 2]; - for (const c of s) { - t.push(c); - dfs(i + 1); - t.pop(); + for (const i of digits) { + const s = d[parseInt(i) - 2]; + const t = []; + for (const a of ans) { + for (const b of s) { + t.push(a + b); + } } - }; - dfs(0); + ans.splice(0, ans.length, ...t); + } return ans; }; ``` -### **C#** - ```cs public class Solution { public IList LetterCombinations(string digits) { @@ -330,57 +225,116 @@ public class Solution { } ``` -```cs -public class Solution { - private readonly string[] d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; - private string digits; - private List ans = new List(); - private System.Text.StringBuilder t = new System.Text.StringBuilder(); + - public IList LetterCombinations(string digits) { - if (digits.Length == 0) { +### Solution 2: DFS + +We can use the method of depth-first search to enumerate all possible letter combinations. Suppose that a part of the letter combination has been generated, but some digits have not been exhausted. At this time, we take out the letters corresponding to the next digit, and then enumerate each letter corresponding to this digit one by one, add them to the letter combination that has been generated before, to form all possible combinations. + +The time complexity is $O(4^n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the input digits. + + + +```python +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + def dfs(i: int): + if i >= len(digits): + ans.append("".join(t)) + return + for c in d[int(digits[i]) - 2]: + t.append(c) + dfs(i + 1) + t.pop() + + if not digits: + return [] + d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] + ans = [] + t = [] + dfs(0) + return ans +``` + +```java +class Solution { + private final String[] d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + private String digits; + private List ans = new ArrayList<>(); + private StringBuilder t = new StringBuilder(); + + public List letterCombinations(String digits) { + if (digits.length() == 0) { return ans; } this.digits = digits; - Dfs(0); + dfs(0); return ans; } - private void Dfs(int i) { - if (i >= digits.Length) { - ans.Add(t.ToString()); + private void dfs(int i) { + if (i >= digits.length()) { + ans.add(t.toString()); return; } - string s = d[digits[i] - '2']; - foreach (char c in s) { - t.Append(c); - Dfs(i + 1); - t.Remove(t.Length - 1, 1); + String s = d[digits.charAt(i) - '2']; + for (char c : s.toCharArray()) { + t.append(c); + dfs(i + 1); + t.deleteCharAt(t.length() - 1); } } } ``` -### **TypeScript** - -```ts -function letterCombinations(digits: string): string[] { - if (digits.length == 0) { - return []; - } - const ans: string[] = ['']; - const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']; - for (const i of digits) { - const s = d[parseInt(i) - 2]; - const t: string[] = []; - for (const a of ans) { - for (const b of s) { - t.push(a + b); - } +```cpp +class Solution { +public: + vector letterCombinations(string digits) { + if (digits.empty()) { + return {}; } - ans.splice(0, ans.length, ...t); + vector d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + vector ans; + string t; + function dfs = [&](int i) { + if (i >= digits.size()) { + ans.push_back(t); + return; + } + for (auto& c : d[digits[i] - '2']) { + t.push_back(c); + dfs(i + 1); + t.pop_back(); + } + }; + dfs(0); + return ans; } - return ans; +}; +``` + +```go +func letterCombinations(digits string) (ans []string) { + d := []string{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"} + t := []rune{} + var dfs func(int) + dfs = func(i int) { + if i >= len(digits) { + ans = append(ans, string(t)) + return + } + for _, c := range d[digits[i]-'2'] { + t = append(t, c) + dfs(i + 1) + t = t[:len(t)-1] + } + } + if len(digits) == 0 { + return + } + dfs(0) + return } ``` @@ -409,32 +363,6 @@ function letterCombinations(digits: string): string[] { } ``` -### **Rust** - -```rust -impl Solution { - pub fn letter_combinations(digits: String) -> Vec { - let mut ans: Vec = Vec::new(); - if digits.is_empty() { - return ans; - } - ans.push("".to_string()); - let d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]; - for i in digits.chars() { - let s = &d[((i as u8) - b'2') as usize]; - let mut t: Vec = Vec::new(); - for a in &ans { - for b in s.chars() { - t.push(format!("{}{}", a, b)); - } - } - ans = t; - } - ans - } -} -``` - ```rust impl Solution { pub fn letter_combinations(digits: String) -> Vec { @@ -463,10 +391,66 @@ impl Solution { } ``` -### **...** - +```js +/** + * @param {string} digits + * @return {string[]} + */ +var letterCombinations = function (digits) { + if (digits.length == 0) { + return []; + } + const ans = []; + const t = []; + const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']; + const dfs = i => { + if (i >= digits.length) { + ans.push(t.join('')); + return; + } + const s = d[parseInt(digits[i]) - 2]; + for (const c of s) { + t.push(c); + dfs(i + 1); + t.pop(); + } + }; + dfs(0); + return ans; +}; ``` +```cs +public class Solution { + private readonly string[] d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + private string digits; + private List ans = new List(); + private System.Text.StringBuilder t = new System.Text.StringBuilder(); + + public IList LetterCombinations(string digits) { + if (digits.Length == 0) { + return ans; + } + this.digits = digits; + Dfs(0); + return ans; + } + + private void Dfs(int i) { + if (i >= digits.Length) { + ans.Add(t.ToString()); + return; + } + string s = d[digits[i] - '2']; + foreach (char c in s) { + t.Append(c); + Dfs(i + 1); + t.Remove(t.Length - 1, 1); + } + } +} ``` + + diff --git a/solution/0000-0099/0018.4Sum/README.md b/solution/0000-0099/0018.4Sum/README.md index 146212228698e..963b2b4b6c09f 100644 --- a/solution/0000-0099/0018.4Sum/README.md +++ b/solution/0000-0099/0018.4Sum/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:排序 + 双指针** +### 方法一:排序 + 双指针 我们注意到,题目中要求找到不重复的四元组,那么我们可以先对数组进行排序,这样就可以方便地跳过重复的元素。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> fourSum(int[] nums, int target) { @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -184,8 +172,6 @@ public: }; ``` -### **Go** - ```go func fourSum(nums []int, target int) (ans [][]int) { n := len(nums) @@ -226,17 +212,10 @@ func fourSum(nums []int, target int) (ans [][]int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} target - * @return {number[][]} - */ -var fourSum = function (nums, target) { +```ts +function fourSum(nums: number[], target: number): number[][] { const n = nums.length; - const ans = []; + const ans: number[][] = []; if (n < 4) { return ans; } @@ -269,15 +248,18 @@ var fourSum = function (nums, target) { } } return ans; -}; +} ``` -### **TypeScript** - -```ts -function fourSum(nums: number[], target: number): number[][] { +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number[][]} + */ +var fourSum = function (nums, target) { const n = nums.length; - const ans: number[][] = []; + const ans = []; if (n < 4) { return ans; } @@ -310,11 +292,9 @@ function fourSum(nums: number[], target: number): number[][] { } } return ans; -} +}; ``` -### **C#** - ```cs public class Solution { public IList> FourSum(int[] nums, int target) { @@ -356,10 +336,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0018.4Sum/README_EN.md b/solution/0000-0099/0018.4Sum/README_EN.md index a8d7491cd79d3..36d48d73ec5c3 100644 --- a/solution/0000-0099/0018.4Sum/README_EN.md +++ b/solution/0000-0099/0018.4Sum/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Sorting + Double Pointers** +### Solution 1: Sorting + Double Pointers We notice that the problem requires us to find non-repeating quadruplets. Therefore, we can first sort the array, which makes it easy to skip duplicate elements. @@ -54,8 +54,6 @@ The time complexity is $O(n^3)$, and the space complexity is $O(\log n)$. Here, -### **Python3** - ```python class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: @@ -87,8 +85,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List> fourSum(int[] nums, int target) { @@ -130,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -174,8 +168,6 @@ public: }; ``` -### **Go** - ```go func fourSum(nums []int, target int) (ans [][]int) { n := len(nums) @@ -216,17 +208,10 @@ func fourSum(nums []int, target int) (ans [][]int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} target - * @return {number[][]} - */ -var fourSum = function (nums, target) { +```ts +function fourSum(nums: number[], target: number): number[][] { const n = nums.length; - const ans = []; + const ans: number[][] = []; if (n < 4) { return ans; } @@ -259,15 +244,18 @@ var fourSum = function (nums, target) { } } return ans; -}; +} ``` -### **TypeScript** - -```ts -function fourSum(nums: number[], target: number): number[][] { +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number[][]} + */ +var fourSum = function (nums, target) { const n = nums.length; - const ans: number[][] = []; + const ans = []; if (n < 4) { return ans; } @@ -300,11 +288,9 @@ function fourSum(nums: number[], target: number): number[][] { } } return ans; -} +}; ``` -### **C#** - ```cs public class Solution { public IList> FourSum(int[] nums, int target) { @@ -346,10 +332,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0019.Remove Nth Node From End of List/README.md b/solution/0000-0099/0019.Remove Nth Node From End of List/README.md index 61a5915c1970d..93c65253aa12c 100644 --- a/solution/0000-0099/0019.Remove Nth Node From End of List/README.md +++ b/solution/0000-0099/0019.Remove Nth Node From End of List/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:快慢指针** +### 方法一:快慢指针 我们定义两个指针 `fast` 和 `slow`,初始时都指向链表的虚拟头结点 `dummy`。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -82,10 +76,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -170,25 +156,23 @@ func removeNthFromEnd(head *ListNode, n int) *ListNode { } ``` -### **JavaScript** - -```js +```ts /** * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) + * 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) + * } * } */ -/** - * @param {ListNode} head - * @param {number} n - * @return {ListNode} - */ -var removeNthFromEnd = function (head, n) { + +function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { const dummy = new ListNode(0, head); - let fast = dummy, - slow = dummy; + let fast = dummy; + let slow = dummy; while (n--) { fast = fast.next; } @@ -198,41 +182,9 @@ var removeNthFromEnd = function (head, n) { } slow.next = slow.next.next; return dummy.next; -}; -``` - -### **Ruby** - -```rb -# Definition for singly-linked list. -# class ListNode -# attr_accessor :val, :next -# def initialize(val = 0, _next = nil) -# @val = val -# @next = _next -# end -# end -# @param {ListNode} head -# @param {Integer} n -# @return {ListNode} -def remove_nth_from_end(head, n) - dummy = ListNode.new(0, head) - fast = slow = dummy - while n > 0 - fast = fast.next - n -= 1 - end - while fast.next - slow = slow.next - fast = fast.next - end - slow.next = slow.next.next - return dummy.next -end +} ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -268,25 +220,23 @@ impl Solution { } ``` -### **TypeScript** - -```ts +```js /** * 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 ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) * } */ - -function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { +/** + * @param {ListNode} head + * @param {number} n + * @return {ListNode} + */ +var removeNthFromEnd = function (head, n) { const dummy = new ListNode(0, head); - let fast = dummy; - let slow = dummy; + let fast = dummy, + slow = dummy; while (n--) { fast = fast.next; } @@ -296,13 +246,37 @@ function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { } slow.next = slow.next.next; return dummy.next; -} -``` - -### **...** - +}; ``` +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} head +# @param {Integer} n +# @return {ListNode} +def remove_nth_from_end(head, n) + dummy = ListNode.new(0, head) + fast = slow = dummy + while n > 0 + fast = fast.next + n -= 1 + end + while fast.next + slow = slow.next + fast = fast.next + end + slow.next = slow.next.next + return dummy.next +end ``` + + diff --git a/solution/0000-0099/0019.Remove Nth Node From End of List/README_EN.md b/solution/0000-0099/0019.Remove Nth Node From End of List/README_EN.md index 9438572104a84..1cb51d096b562 100644 --- a/solution/0000-0099/0019.Remove Nth Node From End of List/README_EN.md +++ b/solution/0000-0099/0019.Remove Nth Node From End of List/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Fast and Slow Pointers** +### Solution 1: Fast and Slow Pointers We define two pointers `fast` and `slow`, both initially pointing to the dummy head node of the linked list. @@ -53,8 +53,6 @@ The time complexity is $O(n)$, where $n$ is the length of the linked list. The s -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -73,8 +71,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -103,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -135,8 +129,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -159,25 +151,23 @@ func removeNthFromEnd(head *ListNode, n int) *ListNode { } ``` -### **JavaScript** - -```js +```ts /** * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) + * 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) + * } * } */ -/** - * @param {ListNode} head - * @param {number} n - * @return {ListNode} - */ -var removeNthFromEnd = function (head, n) { + +function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { const dummy = new ListNode(0, head); - let fast = dummy, - slow = dummy; + let fast = dummy; + let slow = dummy; while (n--) { fast = fast.next; } @@ -187,41 +177,9 @@ var removeNthFromEnd = function (head, n) { } slow.next = slow.next.next; return dummy.next; -}; -``` - -### **Ruby** - -```rb -# Definition for singly-linked list. -# class ListNode -# attr_accessor :val, :next -# def initialize(val = 0, _next = nil) -# @val = val -# @next = _next -# end -# end -# @param {ListNode} head -# @param {Integer} n -# @return {ListNode} -def remove_nth_from_end(head, n) - dummy = ListNode.new(0, head) - fast = slow = dummy - while n > 0 - fast = fast.next - n -= 1 - end - while fast.next - slow = slow.next - fast = fast.next - end - slow.next = slow.next.next - return dummy.next -end +} ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -257,25 +215,23 @@ impl Solution { } ``` -### **TypeScript** - -```ts +```js /** * 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 ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) * } */ - -function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { +/** + * @param {ListNode} head + * @param {number} n + * @return {ListNode} + */ +var removeNthFromEnd = function (head, n) { const dummy = new ListNode(0, head); - let fast = dummy; - let slow = dummy; + let fast = dummy, + slow = dummy; while (n--) { fast = fast.next; } @@ -285,13 +241,37 @@ function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { } slow.next = slow.next.next; return dummy.next; -} -``` - -### **...** - +}; ``` +```rb +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} head +# @param {Integer} n +# @return {ListNode} +def remove_nth_from_end(head, n) + dummy = ListNode.new(0, head) + fast = slow = dummy + while n > 0 + fast = fast.next + n -= 1 + end + while fast.next + slow = slow.next + fast = fast.next + end + slow.next = slow.next.next + return dummy.next +end ``` + + diff --git a/solution/0000-0099/0020.Valid Parentheses/README.md b/solution/0000-0099/0020.Valid Parentheses/README.md index 90c196ebc2976..cc90a3ea6ad7d 100644 --- a/solution/0000-0099/0020.Valid Parentheses/README.md +++ b/solution/0000-0099/0020.Valid Parentheses/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 遍历括号字符串 $s$,遇到左括号时,压入当前的左括号;遇到右括号时,弹出栈顶元素(若栈为空,直接返回 `false`),判断是否匹配,若不匹配,直接返回 `false`。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def isValid(self, s: str) -> bool: @@ -83,10 +77,6 @@ class Solution: return not stk ``` -### **Java** - - - ```java class Solution { public boolean isValid(String s) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func isValid(s string) bool { stk := []rune{} @@ -153,61 +139,6 @@ func match(l, r rune) bool { } ``` -### **JavaScript** - -```js -/** - * @param {string} s - * @return {boolean} - */ -var isValid = function (s) { - let stk = []; - for (const c of s) { - if (c == '(' || c == '{' || c == '[') { - stk.push(c); - } else if (stk.length == 0 || !match(stk[stk.length - 1], c)) { - return false; - } else { - stk.pop(); - } - } - return stk.length == 0; -}; - -function match(l, r) { - return (l == '(' && r == ')') || (l == '[' && r == ']') || (l == '{' && r == '}'); -} -``` - -### **Ruby** - -```rb -# @param {String} s -# @return {Boolean} -def is_valid(s) - stack = '' - s.split('').each do |c| - if ['{', '[', '('].include?(c) - stack += c - else - if c == '}' && stack[stack.length - 1] == '{' - - stack = stack.length > 1 ? stack[0..stack.length - 2] : "" - elsif c == ']' && stack[stack.length - 1] == '[' - stack = stack.length > 1 ? stack[0..stack.length - 2] : "" - elsif c == ')' && stack[stack.length - 1] == '(' - stack = stack.length > 1 ? stack[0..stack.length - 2] : "" - else - return false - end - end - end - stack == '' -end -``` - -### **TypeScript** - ```ts const map = new Map([ ['(', ')'], @@ -228,8 +159,6 @@ function isValid(s: string): boolean { } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -252,7 +181,29 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {string} s + * @return {boolean} + */ +var isValid = function (s) { + let stk = []; + for (const c of s) { + if (c == '(' || c == '{' || c == '[') { + stk.push(c); + } else if (stk.length == 0 || !match(stk[stk.length - 1], c)) { + return false; + } else { + stk.pop(); + } + } + return stk.length == 0; +}; + +function match(l, r) { + return (l == '(' && r == ')') || (l == '[' && r == ']') || (l == '{' && r == '}'); +} +``` ```cs public class Solution { @@ -274,10 +225,31 @@ public class Solution { } ``` -### **...** - -``` +```rb +# @param {String} s +# @return {Boolean} +def is_valid(s) + stack = '' + s.split('').each do |c| + if ['{', '[', '('].include?(c) + stack += c + else + if c == '}' && stack[stack.length - 1] == '{' + stack = stack.length > 1 ? stack[0..stack.length - 2] : "" + elsif c == ']' && stack[stack.length - 1] == '[' + stack = stack.length > 1 ? stack[0..stack.length - 2] : "" + elsif c == ')' && stack[stack.length - 1] == '(' + stack = stack.length > 1 ? stack[0..stack.length - 2] : "" + else + return false + end + end + end + stack == '' +end ``` + + diff --git a/solution/0000-0099/0020.Valid Parentheses/README_EN.md b/solution/0000-0099/0020.Valid Parentheses/README_EN.md index 4e9d5af8b5881..7fb54a4161930 100644 --- a/solution/0000-0099/0020.Valid Parentheses/README_EN.md +++ b/solution/0000-0099/0020.Valid Parentheses/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Stack** +### Solution 1: Stack Traverse the bracket string $s$. When encountering a left bracket, push the current left bracket into the stack; when encountering a right bracket, pop the top element of the stack (if the stack is empty, directly return `false`), and judge whether it matches. If it does not match, directly return `false`. @@ -60,8 +60,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def isValid(self, s: str) -> bool: @@ -75,8 +73,6 @@ class Solution: return not stk ``` -### **Java** - ```java class Solution { public boolean isValid(String s) { @@ -97,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +115,6 @@ public: }; ``` -### **Go** - ```go func isValid(s string) bool { stk := []rune{} @@ -143,61 +135,6 @@ func match(l, r rune) bool { } ``` -### **JavaScript** - -```js -/** - * @param {string} s - * @return {boolean} - */ -var isValid = function (s) { - let stk = []; - for (const c of s) { - if (c == '(' || c == '{' || c == '[') { - stk.push(c); - } else if (stk.length == 0 || !match(stk[stk.length - 1], c)) { - return false; - } else { - stk.pop(); - } - } - return stk.length == 0; -}; - -function match(l, r) { - return (l == '(' && r == ')') || (l == '[' && r == ']') || (l == '{' && r == '}'); -} -``` - -### **Ruby** - -```rb -# @param {String} s -# @return {Boolean} -def is_valid(s) - stack = '' - s.split('').each do |c| - if ['{', '[', '('].include?(c) - stack += c - else - if c == '}' && stack[stack.length - 1] == '{' - - stack = stack.length > 1 ? stack[0..stack.length - 2] : "" - elsif c == ']' && stack[stack.length - 1] == '[' - stack = stack.length > 1 ? stack[0..stack.length - 2] : "" - elsif c == ')' && stack[stack.length - 1] == '(' - stack = stack.length > 1 ? stack[0..stack.length - 2] : "" - else - return false - end - end - end - stack == '' -end -``` - -### **TypeScript** - ```ts const map = new Map([ ['(', ')'], @@ -218,8 +155,6 @@ function isValid(s: string): boolean { } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -242,7 +177,29 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {string} s + * @return {boolean} + */ +var isValid = function (s) { + let stk = []; + for (const c of s) { + if (c == '(' || c == '{' || c == '[') { + stk.push(c); + } else if (stk.length == 0 || !match(stk[stk.length - 1], c)) { + return false; + } else { + stk.pop(); + } + } + return stk.length == 0; +}; + +function match(l, r) { + return (l == '(' && r == ')') || (l == '[' && r == ']') || (l == '{' && r == '}'); +} +``` ```cs public class Solution { @@ -264,10 +221,31 @@ public class Solution { } ``` -### **...** - -``` +```rb +# @param {String} s +# @return {Boolean} +def is_valid(s) + stack = '' + s.split('').each do |c| + if ['{', '[', '('].include?(c) + stack += c + else + if c == '}' && stack[stack.length - 1] == '{' + stack = stack.length > 1 ? stack[0..stack.length - 2] : "" + elsif c == ']' && stack[stack.length - 1] == '[' + stack = stack.length > 1 ? stack[0..stack.length - 2] : "" + elsif c == ')' && stack[stack.length - 1] == '(' + stack = stack.length > 1 ? stack[0..stack.length - 2] : "" + else + return false + end + end + end + stack == '' +end ``` + + diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/README.md b/solution/0000-0099/0021.Merge Two Sorted Lists/README.md index b854f145e8067..402f8511977e6 100644 --- a/solution/0000-0099/0021.Merge Two Sorted Lists/README.md +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们先判断链表 $l_1$ 和 $l_2$ 是否为空,若其中一个为空,则返回另一个链表。否则,我们比较 $l_1$ 和 $l_2$ 的头节点: @@ -54,22 +52,8 @@ 时间复杂度 $O(m + n)$,空间复杂度 $O(m + n)$。其中 $m$ 和 $n$ 分别为两个链表的长度。 -**方法二:迭代** - -我们也可以用迭代的方式来实现两个排序链表的合并。 - -我们先定义一个虚拟头节点 $dummy$,然后循环遍历两个链表,比较两个链表的头节点,将较小的节点添加到 $dummy$ 的末尾,直到其中一个链表为空,然后将另一个链表的剩余部分添加到 $dummy$ 的末尾。 - -最后返回 $dummy.next$ 即可。 - -时间复杂度 $O(m + n)$,其中 $m$ 和 $n$ 分别为两个链表的长度。忽略答案链表的空间消耗,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -90,34 +74,6 @@ class Solution: return list2 ``` -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def mergeTwoLists( - self, list1: Optional[ListNode], list2: Optional[ListNode] - ) -> Optional[ListNode]: - dummy = ListNode() - curr = dummy - while list1 and list2: - if list1.val <= list2.val: - curr.next = list1 - list1 = list1.next - else: - curr.next = list2 - list2 = list2.next - curr = curr.next - curr.next = list1 or list2 - return dummy.next -``` - -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -148,39 +104,6 @@ class Solution { } ``` -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode mergeTwoLists(ListNode list1, ListNode list2) { - ListNode dummy = new ListNode(); - ListNode curr = dummy; - while (list1 != null && list2 != null) { - if (list1.val <= list2.val) { - curr.next = list1; - list1 = list1.next; - } else { - curr.next = list2; - list2 = list2.next; - } - curr = curr.next; - } - curr.next = list1 == null ? list2 : list1; - return dummy.next; - } -} -``` - -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -208,65 +131,96 @@ public: }; ``` -```cpp +```go /** * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; + * type ListNode struct { + * Val int + * Next *ListNode + * } */ -class Solution { -public: - ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { - ListNode* dummy = new ListNode(); - ListNode* curr = dummy; - while (list1 && list2) { - if (list1->val <= list2->val) { - curr->next = list1; - list1 = list1->next; - } else { - curr->next = list2; - list2 = list2->next; - } - curr = curr->next; - } - curr->next = list1 ? list1 : list2; - return dummy->next; - } -}; +func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { + if list1 == nil { + return list2 + } + if list2 == nil { + return list1 + } + if list1.Val <= list2.Val { + list1.Next = mergeTwoLists(list1.Next, list2) + return list1 + } else { + list2.Next = mergeTwoLists(list1, list2.Next) + return list2 + } +} ``` -### **JavaScript** - -```js +```ts /** * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) + * 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) + * } * } */ -/** - * @param {ListNode} list1 - * @param {ListNode} list2 - * @return {ListNode} - */ -var mergeTwoLists = function (list1, list2) { - if (!list1 || !list2) { + +function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null { + if (list1 == null || list2 == null) { return list1 || list2; } - if (list1.val <= list2.val) { + if (list1.val < list2.val) { list1.next = mergeTwoLists(list1.next, list2); return list1; } else { list2.next = mergeTwoLists(list1, list2.next); return list2; } -}; +} +``` + +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn merge_two_lists( + list1: Option>, + list2: Option> + ) -> Option> { + match (list1, list2) { + (None, None) => None, + (Some(list), None) => Some(list), + (None, Some(list)) => Some(list), + (Some(mut list1), Some(mut list2)) => { + if list1.val < list2.val { + list1.next = Self::merge_two_lists(list1.next, Some(list2)); + Some(list1) + } else { + list2.next = Self::merge_two_lists(Some(list1), list2.next); + Some(list2) + } + } + } + } +} ``` ```js @@ -283,82 +237,55 @@ var mergeTwoLists = function (list1, list2) { * @return {ListNode} */ var mergeTwoLists = function (list1, list2) { - const dummy = new ListNode(); - let curr = dummy; - while (list1 && list2) { - if (list1.val <= list2.val) { - curr.next = list1; - list1 = list1.next; - } else { - curr.next = list2; - list2 = list2.next; - } - curr = curr.next; + if (!list1 || !list2) { + return list1 || list2; + } + if (list1.val <= list2.val) { + list1.next = mergeTwoLists(list1.next, list2); + return list1; + } else { + list2.next = mergeTwoLists(list1, list2.next); + return list2; } - curr.next = list1 || list2; - return dummy.next; }; ``` -### **Go** - -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { - if list1 == nil { - return list2 - } - if list2 == nil { - return list1 - } - if list1.Val <= list2.Val { - list1.Next = mergeTwoLists(list1.Next, list2) - return list1 - } else { - list2.Next = mergeTwoLists(list1, list2.Next) - return list2 - } -} -``` - -```go +```cs /** * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } * } */ -func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { - dummy := &ListNode{} - curr := dummy - for list1 != nil && list2 != nil { - if list1.Val <= list2.Val { - curr.Next = list1 - list1 = list1.Next - } else { - curr.Next = list2 - list2 = list2.Next - } - curr = curr.Next - } - if list1 != nil { - curr.Next = list1 - } else { - curr.Next = list2 - } - return dummy.Next +public class Solution { + public ListNode MergeTwoLists(ListNode list1, ListNode list2) { + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (list1 != null && list2 != null) + { + if (list1.val <= list2.val) + { + cur.next = list1; + list1 = list1.next; + } + else + { + cur.next = list2; + list2 = list2.next; + } + cur = cur.next; + } + cur.next = list1 == null ? list2 : list1; + return dummy.next; + } } ``` -### **Ruby** - ```rb # Definition for singly-linked list. # class ListNode @@ -389,70 +316,134 @@ def merge_two_lists(list1, list2) end ``` -### **C#** + -```cs +### 方法二:迭代 + +我们也可以用迭代的方式来实现两个排序链表的合并。 + +我们先定义一个虚拟头节点 $dummy$,然后循环遍历两个链表,比较两个链表的头节点,将较小的节点添加到 $dummy$ 的末尾,直到其中一个链表为空,然后将另一个链表的剩余部分添加到 $dummy$ 的末尾。 + +最后返回 $dummy.next$ 即可。 + +时间复杂度 $O(m + n)$,其中 $m$ 和 $n$ 分别为两个链表的长度。忽略答案链表的空间消耗,空间复杂度 $O(1)$。 + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeTwoLists( + self, list1: Optional[ListNode], list2: Optional[ListNode] + ) -> Optional[ListNode]: + dummy = ListNode() + curr = dummy + while list1 and list2: + if list1.val <= list2.val: + curr.next = list1 + list1 = list1.next + else: + curr.next = list2 + list2 = list2.next + curr = curr.next + curr.next = list1 or list2 + return dummy.next +``` + +```java /** * Definition for singly-linked list. * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ -public class Solution { - public ListNode MergeTwoLists(ListNode list1, ListNode list2) { +class Solution { + public ListNode mergeTwoLists(ListNode list1, ListNode list2) { ListNode dummy = new ListNode(); - ListNode cur = dummy; - while (list1 != null && list2 != null) - { - if (list1.val <= list2.val) - { - cur.next = list1; + ListNode curr = dummy; + while (list1 != null && list2 != null) { + if (list1.val <= list2.val) { + curr.next = list1; list1 = list1.next; - } - else - { - cur.next = list2; + } else { + curr.next = list2; list2 = list2.next; } - cur = cur.next; + curr = curr.next; } - cur.next = list1 == null ? list2 : list1; + curr.next = list1 == null ? list2 : list1; return dummy.next; } } ``` -### **TypeScript** +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + ListNode* dummy = new ListNode(); + ListNode* curr = dummy; + while (list1 && list2) { + if (list1->val <= list2->val) { + curr->next = list1; + list1 = list1->next; + } else { + curr->next = list2; + list2 = list2->next; + } + curr = curr->next; + } + curr->next = list1 ? list1 : list2; + return dummy->next; + } +}; +``` -```ts +```go /** * 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) - * } + * type ListNode struct { + * Val int + * Next *ListNode * } */ - -function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null { - if (list1 == null || list2 == null) { - return list1 || list2; - } - if (list1.val < list2.val) { - list1.next = mergeTwoLists(list1.next, list2); - return list1; - } else { - list2.next = mergeTwoLists(list1, list2.next); - return list2; - } +func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { + dummy := &ListNode{} + curr := dummy + for list1 != nil && list2 != nil { + if list1.Val <= list2.Val { + curr.Next = list1 + list1 = list1.Next + } else { + curr.Next = list2 + list2 = list2.Next + } + curr = curr.Next + } + if list1 != nil { + curr.Next = list1 + } else { + curr.Next = list2 + } + return dummy.Next } ``` @@ -487,48 +478,6 @@ function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode } ``` -### **Rust** - -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn merge_two_lists( - list1: Option>, - list2: Option> - ) -> Option> { - match (list1, list2) { - (None, None) => None, - (Some(list), None) => Some(list), - (None, Some(list)) => Some(list), - (Some(mut list1), Some(mut list2)) => { - if list1.val < list2.val { - list1.next = Self::merge_two_lists(list1.next, Some(list2)); - Some(list1) - } else { - list2.next = Self::merge_two_lists(Some(list1), list2.next); - Some(list2) - } - } - } - } -} -``` - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -572,10 +521,37 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} list1 + * @param {ListNode} list2 + * @return {ListNode} + */ +var mergeTwoLists = function (list1, list2) { + const dummy = new ListNode(); + let curr = dummy; + while (list1 && list2) { + if (list1.val <= list2.val) { + curr.next = list1; + list1 = list1.next; + } else { + curr.next = list2; + list2 = list2.next; + } + curr = curr.next; + } + curr.next = list1 || list2; + return dummy.next; +}; ``` + + diff --git a/solution/0000-0099/0021.Merge Two Sorted Lists/README_EN.md b/solution/0000-0099/0021.Merge Two Sorted Lists/README_EN.md index 19ebe5351e645..f8a340a669c41 100644 --- a/solution/0000-0099/0021.Merge Two Sorted Lists/README_EN.md +++ b/solution/0000-0099/0021.Merge Two Sorted Lists/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion First, we judge whether the linked lists $l_1$ and $l_2$ are empty. If one of them is empty, we return the other linked list. Otherwise, we compare the head nodes of $l_1$ and $l_2$: @@ -52,20 +52,8 @@ First, we judge whether the linked lists $l_1$ and $l_2$ are empty. If one of th The time complexity is $O(m + n)$, and the space complexity is $O(m + n)$. Here, $m$ and $n$ are the lengths of the two linked lists respectively. -**Solution 2: Iteration** - -We can also use iteration to implement the merging of two sorted linked lists. - -First, we define a dummy head node $dummy$, then loop through the two linked lists, compare the head nodes of the two linked lists, add the smaller node to the end of $dummy$, until one of the linked lists is empty, then add the remaining part of the other linked list to the end of $dummy$. - -Finally, return $dummy.next$. - -The time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the two linked lists respectively. Ignoring the space consumption of the answer linked list, the space complexity is $O(1)$. - -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -86,32 +74,6 @@ class Solution: return list2 ``` -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def mergeTwoLists( - self, list1: Optional[ListNode], list2: Optional[ListNode] - ) -> Optional[ListNode]: - dummy = ListNode() - curr = dummy - while list1 and list2: - if list1.val <= list2.val: - curr.next = list1 - list1 = list1.next - else: - curr.next = list2 - list2 = list2.next - curr = curr.next - curr.next = list1 or list2 - return dummy.next -``` - -### **Java** - ```java /** * Definition for singly-linked list. @@ -142,39 +104,6 @@ class Solution { } ``` -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode mergeTwoLists(ListNode list1, ListNode list2) { - ListNode dummy = new ListNode(); - ListNode curr = dummy; - while (list1 != null && list2 != null) { - if (list1.val <= list2.val) { - curr.next = list1; - list1 = list1.next; - } else { - curr.next = list2; - list2 = list2.next; - } - curr = curr.next; - } - curr.next = list1 == null ? list2 : list1; - return dummy.next; - } -} -``` - -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -202,65 +131,96 @@ public: }; ``` -```cpp +```go /** * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; + * type ListNode struct { + * Val int + * Next *ListNode + * } */ -class Solution { -public: - ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { - ListNode* dummy = new ListNode(); - ListNode* curr = dummy; - while (list1 && list2) { - if (list1->val <= list2->val) { - curr->next = list1; - list1 = list1->next; - } else { - curr->next = list2; - list2 = list2->next; - } - curr = curr->next; - } - curr->next = list1 ? list1 : list2; - return dummy->next; - } -}; +func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { + if list1 == nil { + return list2 + } + if list2 == nil { + return list1 + } + if list1.Val <= list2.Val { + list1.Next = mergeTwoLists(list1.Next, list2) + return list1 + } else { + list2.Next = mergeTwoLists(list1, list2.Next) + return list2 + } +} ``` -### **JavaScript** - -```js +```ts /** * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) + * 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) + * } * } */ -/** - * @param {ListNode} list1 - * @param {ListNode} list2 - * @return {ListNode} - */ -var mergeTwoLists = function (list1, list2) { - if (!list1 || !list2) { + +function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null { + if (list1 == null || list2 == null) { return list1 || list2; } - if (list1.val <= list2.val) { + if (list1.val < list2.val) { list1.next = mergeTwoLists(list1.next, list2); return list1; } else { list2.next = mergeTwoLists(list1, list2.next); return list2; } -}; +} +``` + +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn merge_two_lists( + list1: Option>, + list2: Option> + ) -> Option> { + match (list1, list2) { + (None, None) => None, + (Some(list), None) => Some(list), + (None, Some(list)) => Some(list), + (Some(mut list1), Some(mut list2)) => { + if list1.val < list2.val { + list1.next = Self::merge_two_lists(list1.next, Some(list2)); + Some(list1) + } else { + list2.next = Self::merge_two_lists(Some(list1), list2.next); + Some(list2) + } + } + } + } +} ``` ```js @@ -277,83 +237,55 @@ var mergeTwoLists = function (list1, list2) { * @return {ListNode} */ var mergeTwoLists = function (list1, list2) { - const dummy = new ListNode(); - let curr = dummy; - while (list1 && list2) { - if (list1.val <= list2.val) { - curr.next = list1; - list1 = list1.next; - } else { - curr.next = list2; - list2 = list2.next; - } - curr = curr.next; + if (!list1 || !list2) { + return list1 || list2; + } + if (list1.val <= list2.val) { + list1.next = mergeTwoLists(list1.next, list2); + return list1; + } else { + list2.next = mergeTwoLists(list1, list2.next); + return list2; } - curr.next = list1 || list2; - return dummy.next; }; ``` -### **Go** - -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { - if list1 == nil { - return list2 - } - if list2 == nil { - return list1 - } - if list1.Val <= list2.Val { - list1.Next = mergeTwoLists(list1.Next, list2) - return list1 - } else { - list2.Next = mergeTwoLists(list1, list2.Next) - return list2 - } - -} -``` - -```go +```cs /** * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } * } */ -func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { - dummy := &ListNode{} - curr := dummy - for list1 != nil && list2 != nil { - if list1.Val <= list2.Val { - curr.Next = list1 - list1 = list1.Next - } else { - curr.Next = list2 - list2 = list2.Next - } - curr = curr.Next - } - if list1 != nil { - curr.Next = list1 - } else { - curr.Next = list2 - } - return dummy.Next +public class Solution { + public ListNode MergeTwoLists(ListNode list1, ListNode list2) { + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (list1 != null && list2 != null) + { + if (list1.val <= list2.val) + { + cur.next = list1; + list1 = list1.next; + } + else + { + cur.next = list2; + list2 = list2.next; + } + cur = cur.next; + } + cur.next = list1 == null ? list2 : list1; + return dummy.next; + } } ``` -### **Ruby** - ```rb # Definition for singly-linked list. # class ListNode @@ -384,70 +316,134 @@ def merge_two_lists(list1, list2) end ``` -### **C#** + -```cs +### Solution 2: Iteration + +We can also use iteration to implement the merging of two sorted linked lists. + +First, we define a dummy head node $dummy$, then loop through the two linked lists, compare the head nodes of the two linked lists, add the smaller node to the end of $dummy$, until one of the linked lists is empty, then add the remaining part of the other linked list to the end of $dummy$. + +Finally, return $dummy.next$. + +The time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the two linked lists respectively. Ignoring the space consumption of the answer linked list, the space complexity is $O(1)$. + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeTwoLists( + self, list1: Optional[ListNode], list2: Optional[ListNode] + ) -> Optional[ListNode]: + dummy = ListNode() + curr = dummy + while list1 and list2: + if list1.val <= list2.val: + curr.next = list1 + list1 = list1.next + else: + curr.next = list2 + list2 = list2.next + curr = curr.next + curr.next = list1 or list2 + return dummy.next +``` + +```java /** * Definition for singly-linked list. * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ -public class Solution { - public ListNode MergeTwoLists(ListNode list1, ListNode list2) { +class Solution { + public ListNode mergeTwoLists(ListNode list1, ListNode list2) { ListNode dummy = new ListNode(); - ListNode cur = dummy; - while (list1 != null && list2 != null) - { - if (list1.val <= list2.val) - { - cur.next = list1; + ListNode curr = dummy; + while (list1 != null && list2 != null) { + if (list1.val <= list2.val) { + curr.next = list1; list1 = list1.next; - } - else - { - cur.next = list2; + } else { + curr.next = list2; list2 = list2.next; } - cur = cur.next; + curr = curr.next; } - cur.next = list1 == null ? list2 : list1; + curr.next = list1 == null ? list2 : list1; return dummy.next; } } ``` -### **TypeScript** +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + ListNode* dummy = new ListNode(); + ListNode* curr = dummy; + while (list1 && list2) { + if (list1->val <= list2->val) { + curr->next = list1; + list1 = list1->next; + } else { + curr->next = list2; + list2 = list2->next; + } + curr = curr->next; + } + curr->next = list1 ? list1 : list2; + return dummy->next; + } +}; +``` -```ts +```go /** * 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) - * } + * type ListNode struct { + * Val int + * Next *ListNode * } */ - -function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null { - if (list1 == null || list2 == null) { - return list1 || list2; - } - if (list1.val < list2.val) { - list1.next = mergeTwoLists(list1.next, list2); - return list1; - } else { - list2.next = mergeTwoLists(list1, list2.next); - return list2; - } +func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { + dummy := &ListNode{} + curr := dummy + for list1 != nil && list2 != nil { + if list1.Val <= list2.Val { + curr.Next = list1 + list1 = list1.Next + } else { + curr.Next = list2 + list2 = list2.Next + } + curr = curr.Next + } + if list1 != nil { + curr.Next = list1 + } else { + curr.Next = list2 + } + return dummy.Next } ``` @@ -482,48 +478,6 @@ function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode } ``` -### **Rust** - -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn merge_two_lists( - list1: Option>, - list2: Option> - ) -> Option> { - match (list1, list2) { - (None, None) => None, - (Some(list), None) => Some(list), - (None, Some(list)) => Some(list), - (Some(mut list1), Some(mut list2)) => { - if list1.val < list2.val { - list1.next = Self::merge_two_lists(list1.next, Some(list2)); - Some(list1) - } else { - list2.next = Self::merge_two_lists(Some(list1), list2.next); - Some(list2) - } - } - } - } -} -``` - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -567,10 +521,37 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} list1 + * @param {ListNode} list2 + * @return {ListNode} + */ +var mergeTwoLists = function (list1, list2) { + const dummy = new ListNode(); + let curr = dummy; + while (list1 && list2) { + if (list1.val <= list2.val) { + curr.next = list1; + list1 = list1.next; + } else { + curr.next = list2; + list2 = list2.next; + } + curr = curr.next; + } + curr.next = list1 || list2; + return dummy.next; +}; ``` + + diff --git a/solution/0000-0099/0022.Generate Parentheses/README.md b/solution/0000-0099/0022.Generate Parentheses/README.md index 3f7daaf24e091..0d98afa468b4f 100644 --- a/solution/0000-0099/0022.Generate Parentheses/README.md +++ b/solution/0000-0099/0022.Generate Parentheses/README.md @@ -34,9 +34,7 @@ ## 解法 - - -**方法一:DFS + 剪枝** +### 方法一:DFS + 剪枝 题目中 $n$ 的范围为 $[1, 8]$,因此我们直接通过“暴力搜索 + 剪枝”的方式通过本题。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def generateParenthesis(self, n: int) -> List[str]: @@ -72,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List ans = new ArrayList<>(); @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func generateParenthesis(n int) (ans []string) { var dfs func(int, int, string) @@ -144,33 +130,6 @@ func generateParenthesis(n int) (ans []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) { @@ -190,8 +149,6 @@ function generateParenthesis(n: number): string[] { } ``` -### **Rust** - ```rust impl Solution { fn dfs(left: i32, right: i32, s: &mut String, res: &mut Vec) { @@ -219,6 +176,35 @@ 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; +}; +``` + + + +### 方法二 + + + ```rust impl Solution { pub fn generate_parenthesis(n: i32) -> Vec { @@ -250,10 +236,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0022.Generate Parentheses/README_EN.md b/solution/0000-0099/0022.Generate Parentheses/README_EN.md index aac0dccd98dca..eebd3b4640867 100644 --- a/solution/0000-0099/0022.Generate Parentheses/README_EN.md +++ b/solution/0000-0099/0022.Generate Parentheses/README_EN.md @@ -23,7 +23,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 through "brute force search + pruning". @@ -38,8 +38,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]: @@ -57,8 +55,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List ans = new ArrayList<>(); @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +100,6 @@ public: }; ``` -### **Go** - ```go func generateParenthesis(n int) (ans []string) { var dfs func(int, int, string) @@ -127,33 +119,6 @@ func generateParenthesis(n int) (ans []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) { @@ -173,8 +138,6 @@ function generateParenthesis(n: number): string[] { } ``` -### **Rust** - ```rust impl Solution { fn dfs(left: i32, right: i32, s: &mut String, res: &mut Vec) { @@ -202,6 +165,35 @@ 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; +}; +``` + + + +### Solution 2 + + + ```rust impl Solution { pub fn generate_parenthesis(n: i32) -> Vec { @@ -233,10 +225,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0023.Merge k Sorted Lists/README.md b/solution/0000-0099/0023.Merge k Sorted Lists/README.md index c4453f45d02e1..70f3a9fea5075 100644 --- a/solution/0000-0099/0023.Merge k Sorted Lists/README.md +++ b/solution/0000-0099/0023.Merge k Sorted Lists/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:优先队列(小根堆)** +### 方法一:优先队列(小根堆) 我们可以创建一个小根堆来 $pq$ 维护所有链表的头节点,每次从小根堆中取出值最小的节点,添加到结果链表的末尾,然后将该节点的下一个节点加入堆中,重复上述步骤直到堆为空。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -88,10 +82,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -165,8 +153,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -204,8 +190,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(*ListNode)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -240,7 +224,54 @@ function mergeKLists(lists: Array): ListNode | null { } ``` -### **JavaScript** +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +impl PartialOrd for ListNode { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} +impl Ord for ListNode { + fn cmp(&self, other: &Self) -> Ordering { + self.val.cmp(&other.val).reverse() + } +} +impl Solution { + pub fn merge_k_lists(lists: Vec>>) -> Option> { + let mut pq = lists + .into_iter() + .filter_map(|head| head) + .collect::>(); + let mut head = None; + let mut cur = &mut head; + while let Some(node) = pq.pop() { + cur = &mut cur.insert(Box::new(ListNode::new(node.val))).next; + if let Some(next) = node.next { + pq.push(next); + } + } + head + } +} +``` ```js /** @@ -275,8 +306,6 @@ var mergeKLists = function (lists) { }; ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -312,61 +341,6 @@ public class Solution { } ``` -### **Rust** - -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -use std::cmp::Ordering; -use std::collections::BinaryHeap; - -impl PartialOrd for ListNode { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} -impl Ord for ListNode { - fn cmp(&self, other: &Self) -> Ordering { - self.val.cmp(&other.val).reverse() - } -} -impl Solution { - pub fn merge_k_lists(lists: Vec>>) -> Option> { - let mut pq = lists - .into_iter() - .filter_map(|head| head) - .collect::>(); - let mut head = None; - let mut cur = &mut head; - while let Some(node) = pq.pop() { - cur = &mut cur.insert(Box::new(ListNode::new(node.val))).next; - if let Some(next) = node.next { - pq.push(next); - } - } - head - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0023.Merge k Sorted Lists/README_EN.md b/solution/0000-0099/0023.Merge k Sorted Lists/README_EN.md index 4b39d965a2841..52194f5c80799 100644 --- a/solution/0000-0099/0023.Merge k Sorted Lists/README_EN.md +++ b/solution/0000-0099/0023.Merge k Sorted Lists/README_EN.md @@ -52,7 +52,7 @@ merging them into one sorted list: ## Solutions -**Solution 1: Priority Queue (Min Heap)** +### Solution 1: Priority Queue (Min Heap) We can create a min heap $pq$ to maintain the head nodes of all linked lists. Each time, we take out the node with the smallest value from the min heap, add it to the end of the result linked list, and then add the next node of this node to the heap. Repeat the above steps until the heap is empty. @@ -60,8 +60,6 @@ The time complexity is $O(n \times \log k)$, and the space complexity is $O(k)$. -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -83,8 +81,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -119,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -158,8 +152,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -197,8 +189,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(*ListNode)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -233,7 +223,54 @@ function mergeKLists(lists: Array): ListNode | null { } ``` -### **JavaScript** +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +impl PartialOrd for ListNode { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} +impl Ord for ListNode { + fn cmp(&self, other: &Self) -> Ordering { + self.val.cmp(&other.val).reverse() + } +} +impl Solution { + pub fn merge_k_lists(lists: Vec>>) -> Option> { + let mut pq = lists + .into_iter() + .filter_map(|head| head) + .collect::>(); + let mut head = None; + let mut cur = &mut head; + while let Some(node) = pq.pop() { + cur = &mut cur.insert(Box::new(ListNode::new(node.val))).next; + if let Some(next) = node.next { + pq.push(next); + } + } + head + } +} +``` ```js /** @@ -268,8 +305,6 @@ var mergeKLists = function (lists) { }; ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -305,61 +340,6 @@ public class Solution { } ``` -### **Rust** - -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -use std::cmp::Ordering; -use std::collections::BinaryHeap; - -impl PartialOrd for ListNode { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} -impl Ord for ListNode { - fn cmp(&self, other: &Self) -> Ordering { - self.val.cmp(&other.val).reverse() - } -} -impl Solution { - pub fn merge_k_lists(lists: Vec>>) -> Option> { - let mut pq = lists - .into_iter() - .filter_map(|head| head) - .collect::>(); - let mut head = None; - let mut cur = &mut head; - while let Some(node) = pq.pop() { - cur = &mut cur.insert(Box::new(ListNode::new(node.val))).next; - if let Some(next) = node.next { - pq.push(next); - } - } - head - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/README.md b/solution/0000-0099/0024.Swap Nodes in Pairs/README.md index c4bab30e44e1e..d412e1eef69d8 100644 --- a/solution/0000-0099/0024.Swap Nodes in Pairs/README.md +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们可以通过递归的方式实现两两交换链表中的节点。 @@ -54,20 +52,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$,其中 $n$ 是链表的长度。 -**方法二:迭代** - -我们设置一个虚拟头节点 $dummy$,初始时指向 $head$,然后设置两个指针 $pre$ 和 $cur$,初始时 $pre$ 指向 $dummy$,而 $cur$ 指向 $head$。 - -接下来,我们遍历链表,每次需要交换 $pre$ 后面的两个节点,因此我们先判断 $cur$ 和 $cur.next$ 是否为空,若不为空,则进行交换,否则终止循环。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$,其中 $n$ 是链表的长度。 - -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -85,29 +71,6 @@ class Solution: return p ``` -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: - dummy = ListNode(next=head) - pre, cur = dummy, head - while cur and cur.next: - t = cur.next - cur.next = t.next - t.next = cur - pre.next = t - pre, cur = cur, cur.next - return dummy.next -``` - -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -133,37 +96,6 @@ class Solution { } ``` -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode swapPairs(ListNode head) { - ListNode dummy = new ListNode(0, head); - ListNode pre = dummy; - ListNode cur = head; - while (cur != null && cur.next != null) { - ListNode t = cur.next; - cur.next = t.next; - t.next = cur; - pre.next = t; - pre = cur; - cur = cur.next; - } - return dummy.next; - } -} -``` - -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -190,38 +122,6 @@ public: }; ``` -```cpp -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* swapPairs(ListNode* head) { - ListNode* dummy = new ListNode(0, head); - ListNode* pre = dummy; - ListNode* cur = head; - while (cur && cur->next) { - ListNode* t = cur->next; - cur->next = t->next; - t->next = cur; - pre->next = t; - pre = cur; - cur = cur->next; - } - return dummy->next; - } -}; -``` - -### **Go** - ```go /** * Definition for singly-linked list. @@ -242,30 +142,6 @@ func swapPairs(head *ListNode) *ListNode { } ``` -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -func swapPairs(head *ListNode) *ListNode { - dummy := &ListNode{Next: head} - pre, cur := dummy, head - for cur != nil && cur.Next != nil { - t := cur.Next - cur.Next = t.Next - t.Next = cur - pre.Next = t - pre, cur = cur, cur.Next - } - return dummy.Next -} -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -291,35 +167,42 @@ function swapPairs(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 swapPairs(head: ListNode | null): ListNode | null { - const dummy = new ListNode(0, head); - let [pre, cur] = [dummy, head]; - while (cur && cur.next) { - const t = cur.next; - cur.next = t.next; - t.next = cur; - pre.next = t; - [pre, cur] = [cur, cur.next]; +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn swap_pairs(head: Option>) -> Option> { + let mut dummy = Some(Box::new(ListNode { val: 0, next: head })); + let mut cur = dummy.as_mut().unwrap(); + while cur.next.is_some() && cur.next.as_ref().unwrap().next.is_some() { + cur.next = { + let mut b = cur.next.as_mut().unwrap().next.take(); + cur.next.as_mut().unwrap().next = b.as_mut().unwrap().next.take(); + let a = cur.next.take(); + b.as_mut().unwrap().next = a; + b + }; + cur = cur.next.as_mut().unwrap().next.as_mut().unwrap(); + } + dummy.unwrap().next } - return dummy.next; } ``` -### **JavaScript** - ```js /** * Definition for singly-linked list. @@ -344,34 +227,6 @@ var swapPairs = function (head) { }; ``` -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @return {ListNode} - */ -var swapPairs = function (head) { - const dummy = new ListNode(0, head); - let [pre, cur] = [dummy, head]; - while (cur && cur.next) { - const t = cur.next; - cur.next = t.next; - t.next = cur; - pre.next = t; - [pre, cur] = [cur, cur.next]; - } - return dummy.next; -}; -``` - -### **Ruby** - ```rb # Definition for singly-linked list. # class ListNode @@ -399,48 +254,171 @@ def swap_pairs(head) end ``` -### **Rust** + -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn swap_pairs(head: Option>) -> Option> { - let mut dummy = Some(Box::new(ListNode { val: 0, next: head })); - let mut cur = dummy.as_mut().unwrap(); - while cur.next.is_some() && cur.next.as_ref().unwrap().next.is_some() { - cur.next = { - let mut b = cur.next.as_mut().unwrap().next.take(); - cur.next.as_mut().unwrap().next = b.as_mut().unwrap().next.take(); - let a = cur.next.take(); - b.as_mut().unwrap().next = a; - b - }; - cur = cur.next.as_mut().unwrap().next.as_mut().unwrap(); +### 方法二:迭代 + +我们设置一个虚拟头节点 $dummy$,初始时指向 $head$,然后设置两个指针 $pre$ 和 $cur$,初始时 $pre$ 指向 $dummy$,而 $cur$ 指向 $head$。 + +接下来,我们遍历链表,每次需要交换 $pre$ 后面的两个节点,因此我们先判断 $cur$ 和 $cur.next$ 是否为空,若不为空,则进行交换,否则终止循环。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$,其中 $n$ 是链表的长度。 + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: + dummy = ListNode(next=head) + pre, cur = dummy, head + while cur and cur.next: + t = cur.next + cur.next = t.next + t.next = cur + pre.next = t + pre, cur = cur, cur.next + return dummy.next +``` + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode swapPairs(ListNode head) { + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy; + ListNode cur = head; + while (cur != null && cur.next != null) { + ListNode t = cur.next; + cur.next = t.next; + t.next = cur; + pre.next = t; + pre = cur; + cur = cur.next; } - dummy.unwrap().next + return dummy.next; } } ``` -### **...** +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + ListNode* dummy = new ListNode(0, head); + ListNode* pre = dummy; + ListNode* cur = head; + while (cur && cur->next) { + ListNode* t = cur->next; + cur->next = t->next; + t->next = cur; + pre->next = t; + pre = cur; + cur = cur->next; + } + return dummy->next; + } +}; +``` +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func swapPairs(head *ListNode) *ListNode { + dummy := &ListNode{Next: head} + pre, cur := dummy, head + for cur != nil && cur.Next != nil { + t := cur.Next + cur.Next = t.Next + t.Next = cur + pre.Next = t + pre, cur = cur, cur.Next + } + return dummy.Next +} ``` +```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 swapPairs(head: ListNode | null): ListNode | null { + const dummy = new ListNode(0, head); + let [pre, cur] = [dummy, head]; + while (cur && cur.next) { + const t = cur.next; + cur.next = t.next; + t.next = cur; + pre.next = t; + [pre, cur] = [cur, cur.next]; + } + return dummy.next; +} +``` + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var swapPairs = function (head) { + const dummy = new ListNode(0, head); + let [pre, cur] = [dummy, head]; + while (cur && cur.next) { + const t = cur.next; + cur.next = t.next; + t.next = cur; + pre.next = t; + [pre, cur] = [cur, cur.next]; + } + return dummy.next; +}; ``` + + diff --git a/solution/0000-0099/0024.Swap Nodes in Pairs/README_EN.md b/solution/0000-0099/0024.Swap Nodes in Pairs/README_EN.md index 764f60e855613..f1606611cdcb0 100644 --- a/solution/0000-0099/0024.Swap Nodes in Pairs/README_EN.md +++ b/solution/0000-0099/0024.Swap Nodes in Pairs/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion We can implement swapping two nodes in the linked list through recursion. @@ -48,18 +48,8 @@ Otherwise, we recursively swap the linked list $head.next.next$, and let the swa The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the linked list. -**Solution 2: Iteration** - -We set a dummy head node $dummy$, initially pointing to $head$, and then set two pointers $pre$ and $cur$, initially $pre$ points to $dummy$, and $cur$ points to $head$. - -Next, we traverse the linked list. Each time we need to swap the two nodes after $pre$, so we first judge whether $cur$ and $cur.next$ are empty. If they are not empty, we perform the swap, otherwise we terminate the loop. - -The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the linked list. - -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -77,27 +67,6 @@ class Solution: return p ``` -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: - dummy = ListNode(next=head) - pre, cur = dummy, head - while cur and cur.next: - t = cur.next - cur.next = t.next - t.next = cur - pre.next = t - pre, cur = cur, cur.next - return dummy.next -``` - -### **Java** - ```java /** * Definition for singly-linked list. @@ -123,37 +92,6 @@ class Solution { } ``` -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode swapPairs(ListNode head) { - ListNode dummy = new ListNode(0, head); - ListNode pre = dummy; - ListNode cur = head; - while (cur != null && cur.next != null) { - ListNode t = cur.next; - cur.next = t.next; - t.next = cur; - pre.next = t; - pre = cur; - cur = cur.next; - } - return dummy.next; - } -} -``` - -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -180,60 +118,6 @@ public: }; ``` -```cpp -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* swapPairs(ListNode* head) { - ListNode* dummy = new ListNode(0, head); - ListNode* pre = dummy; - ListNode* cur = head; - while (cur && cur->next) { - ListNode* t = cur->next; - cur->next = t->next; - t->next = cur; - pre->next = t; - pre = cur; - cur = cur->next; - } - return dummy->next; - } -}; -``` - -### **Go** - -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -func swapPairs(head *ListNode) *ListNode { - dummy := &ListNode{Next: head} - pre, cur := dummy, head - for cur != nil && cur.Next != nil { - t := cur.Next - cur.Next = t.Next - t.Next = cur - pre.Next = t - pre, cur = cur, cur.Next - } - return dummy.Next -} -``` - ```go /** * Definition for singly-linked list. @@ -254,8 +138,6 @@ func swapPairs(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -281,35 +163,42 @@ function swapPairs(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 swapPairs(head: ListNode | null): ListNode | null { - const dummy = new ListNode(0, head); - let [pre, cur] = [dummy, head]; - while (cur && cur.next) { - const t = cur.next; - cur.next = t.next; - t.next = cur; - pre.next = t; - [pre, cur] = [cur, cur.next]; +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn swap_pairs(head: Option>) -> Option> { + let mut dummy = Some(Box::new(ListNode { val: 0, next: head })); + let mut cur = dummy.as_mut().unwrap(); + while cur.next.is_some() && cur.next.as_ref().unwrap().next.is_some() { + cur.next = { + let mut b = cur.next.as_mut().unwrap().next.take(); + cur.next.as_mut().unwrap().next = b.as_mut().unwrap().next.take(); + let a = cur.next.take(); + b.as_mut().unwrap().next = a; + b + }; + cur = cur.next.as_mut().unwrap().next.as_mut().unwrap(); + } + dummy.unwrap().next } - return dummy.next; } ``` -### **JavaScript** - ```js /** * Definition for singly-linked list. @@ -334,34 +223,6 @@ var swapPairs = function (head) { }; ``` -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @return {ListNode} - */ -var swapPairs = function (head) { - const dummy = new ListNode(0, head); - let [pre, cur] = [dummy, head]; - while (cur && cur.next) { - const t = cur.next; - cur.next = t.next; - t.next = cur; - pre.next = t; - [pre, cur] = [cur, cur.next]; - } - return dummy.next; -}; -``` - -### **Ruby** - ```rb # Definition for singly-linked list. # class ListNode @@ -389,48 +250,171 @@ def swap_pairs(head) end ``` -### **Rust** + -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn swap_pairs(head: Option>) -> Option> { - let mut dummy = Some(Box::new(ListNode { val: 0, next: head })); - let mut cur = dummy.as_mut().unwrap(); - while cur.next.is_some() && cur.next.as_ref().unwrap().next.is_some() { - cur.next = { - let mut b = cur.next.as_mut().unwrap().next.take(); - cur.next.as_mut().unwrap().next = b.as_mut().unwrap().next.take(); - let a = cur.next.take(); - b.as_mut().unwrap().next = a; - b - }; - cur = cur.next.as_mut().unwrap().next.as_mut().unwrap(); +### Solution 2: Iteration + +We set a dummy head node $dummy$, initially pointing to $head$, and then set two pointers $pre$ and $cur$, initially $pre$ points to $dummy$, and $cur$ points to $head$. + +Next, we traverse the linked list. Each time we need to swap the two nodes after $pre$, so we first judge whether $cur$ and $cur.next$ are empty. If they are not empty, we perform the swap, otherwise we terminate the loop. + +The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the linked list. + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: + dummy = ListNode(next=head) + pre, cur = dummy, head + while cur and cur.next: + t = cur.next + cur.next = t.next + t.next = cur + pre.next = t + pre, cur = cur, cur.next + return dummy.next +``` + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode swapPairs(ListNode head) { + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy; + ListNode cur = head; + while (cur != null && cur.next != null) { + ListNode t = cur.next; + cur.next = t.next; + t.next = cur; + pre.next = t; + pre = cur; + cur = cur.next; } - dummy.unwrap().next + return dummy.next; + } +} +``` + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + ListNode* dummy = new ListNode(0, head); + ListNode* pre = dummy; + ListNode* cur = head; + while (cur && cur->next) { + ListNode* t = cur->next; + cur->next = t->next; + t->next = cur; + pre->next = t; + pre = cur; + cur = cur->next; + } + return dummy->next; } +}; +``` + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func swapPairs(head *ListNode) *ListNode { + dummy := &ListNode{Next: head} + pre, cur := dummy, head + for cur != nil && cur.Next != nil { + t := cur.Next + cur.Next = t.Next + t.Next = cur + pre.Next = t + pre, cur = cur, cur.Next + } + return dummy.Next } ``` -### **...** +```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 swapPairs(head: ListNode | null): ListNode | null { + const dummy = new ListNode(0, head); + let [pre, cur] = [dummy, head]; + while (cur && cur.next) { + const t = cur.next; + cur.next = t.next; + t.next = cur; + pre.next = t; + [pre, cur] = [cur, cur.next]; + } + return dummy.next; +} ``` +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var swapPairs = function (head) { + const dummy = new ListNode(0, head); + let [pre, cur] = [dummy, head]; + while (cur && cur.next) { + const t = cur.next; + cur.next = t.next; + t.next = cur; + pre.next = t; + [pre, cur] = [cur, cur.next]; + } + return dummy.next; +}; ``` + + diff --git a/solution/0000-0099/0025.Reverse Nodes in k-Group/README.md b/solution/0000-0099/0025.Reverse Nodes in k-Group/README.md index 7355e0a44d289..c1c0f2ea81bc2 100644 --- a/solution/0000-0099/0025.Reverse Nodes in k-Group/README.md +++ b/solution/0000-0099/0025.Reverse Nodes in k-Group/README.md @@ -48,22 +48,12 @@ ## 解法 - - -**方法一:迭代** +### 方法一:迭代 时间复杂度为 $O(n)$,空间复杂度为 $O(1)$,其中 $n$ 是链表的长度。 -**方法二:递归** - -时间复杂度为 $O(n)$,空间复杂度为 $O(\log _k n)$,其中 $n$ 是链表的长度。 - -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -98,10 +88,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -148,7 +134,41 @@ class Solution { } ``` -### **TypeScript** +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseKGroup(head *ListNode, k int) *ListNode { + var dummy *ListNode = &ListNode{} + p, cur := dummy, head + for cur != nil { + start := cur + for i := 0; i < k; i++ { + if cur == nil { + p.Next = start + return dummy.Next + } + cur = cur.Next + } + p.Next, p = reverse(start, cur), start + } + return dummy.Next +} + +func reverse(start, end *ListNode) *ListNode { + var pre *ListNode = nil + for start != end { + tmp := start.Next + start.Next, pre = pre, start + start = tmp + } + return pre +} +``` ```ts /** @@ -201,131 +221,64 @@ function reverse(head: ListNode, tail: ListNode) { } ``` -```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 reverseKGroup(head: ListNode | null, k: number): ListNode | null { - if (k === 1) { - return head; - } - - const dummy = new ListNode(0, head); - let root = dummy; - while (root != null) { - let pre = root; - let cur = root; - - let count = 0; - while (count !== k) { - count++; - cur = cur.next; - if (cur == null) { - return dummy.next; +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn reverse_k_group(head: Option>, k: i32) -> Option> { + fn reverse(head: Option>) -> Option> { + let mut head = head; + let mut pre = None; + while let Some(mut node) = head { + head = node.next.take(); + node.next = pre.take(); + pre = Some(node); } + pre } - const nextRoot = pre.next; - pre.next = cur; + let mut dummy = Some(Box::new(ListNode::new(0))); + let mut pre = &mut dummy; + let mut cur = head; + while cur.is_some() { + let mut q = &mut cur; + for _ in 0..k - 1 { + if q.is_none() { + break; + } + q = &mut q.as_mut().unwrap().next; + } + if q.is_none() { + pre.as_mut().unwrap().next = cur; + return dummy.unwrap().next; + } - let node = nextRoot; - let next = node.next; - node.next = cur.next; - while (node != cur) { - [next.next, node, next] = [node, next, next.next]; + let b = q.as_mut().unwrap().next.take(); + pre.as_mut().unwrap().next = reverse(cur); + while pre.is_some() && pre.as_mut().unwrap().next.is_some() { + pre = &mut pre.as_mut().unwrap().next; + } + cur = b; } - root = nextRoot; + dummy.unwrap().next } - - return dummy.next; } ``` -### **Go** - -迭代: - -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -func reverseKGroup(head *ListNode, k int) *ListNode { - var dummy *ListNode = &ListNode{} - p, cur := dummy, head - for cur != nil { - start := cur - for i := 0; i < k; i++ { - if cur == nil { - p.Next = start - return dummy.Next - } - cur = cur.Next - } - p.Next, p = reverse(start, cur), start - } - return dummy.Next -} - -func reverse(start, end *ListNode) *ListNode { - var pre *ListNode = nil - for start != end { - tmp := start.Next - start.Next, pre = pre, start - start = tmp - } - return pre -} -``` - -递归: - -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -func reverseKGroup(head *ListNode, k int) *ListNode { - start, end := head, head - for i := 0; i < k; i++ { - if end == nil { - return head - } - end = end.Next - } - res := reverse(start, end) - start.Next = reverseKGroup(end, k) - return res -} - -func reverse(start, end *ListNode) *ListNode { - var pre *ListNode = nil - for start != end { - tmp := start.Next - start.Next, pre = pre, start - start = tmp - } - return pre -} -``` - -### **C#** - ```cs /** * Definition for singly-linked list. @@ -377,70 +330,95 @@ public class Solution { } ``` -### **Rust** + -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn reverse_k_group(head: Option>, k: i32) -> Option> { - fn reverse(head: Option>) -> Option> { - let mut head = head; - let mut pre = None; - while let Some(mut node) = head { - head = node.next.take(); - node.next = pre.take(); - pre = Some(node); - } - pre - } +### 方法二:递归 - let mut dummy = Some(Box::new(ListNode::new(0))); - let mut pre = &mut dummy; - let mut cur = head; - while cur.is_some() { - let mut q = &mut cur; - for _ in 0..k - 1 { - if q.is_none() { - break; - } - q = &mut q.as_mut().unwrap().next; - } - if q.is_none() { - pre.as_mut().unwrap().next = cur; - return dummy.unwrap().next; - } +时间复杂度为 $O(n)$,空间复杂度为 $O(\log _k n)$,其中 $n$ 是链表的长度。 - let b = q.as_mut().unwrap().next.take(); - pre.as_mut().unwrap().next = reverse(cur); - while pre.is_some() && pre.as_mut().unwrap().next.is_some() { - pre = &mut pre.as_mut().unwrap().next; - } - cur = b; - } - dummy.unwrap().next - } + + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseKGroup(head *ListNode, k int) *ListNode { + start, end := head, head + for i := 0; i < k; i++ { + if end == nil { + return head + } + end = end.Next + } + res := reverse(start, end) + start.Next = reverseKGroup(end, k) + return res +} + +func reverse(start, end *ListNode) *ListNode { + var pre *ListNode = nil + for start != end { + tmp := start.Next + start.Next, pre = pre, start + start = tmp + } + return pre } ``` -### **...** +```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 reverseKGroup(head: ListNode | null, k: number): ListNode | null { + if (k === 1) { + return head; + } -``` + const dummy = new ListNode(0, head); + let root = dummy; + while (root != null) { + let pre = root; + let cur = root; + + let count = 0; + while (count !== k) { + count++; + cur = cur.next; + if (cur == null) { + return dummy.next; + } + } + const nextRoot = pre.next; + pre.next = cur; + + let node = nextRoot; + let next = node.next; + node.next = cur.next; + while (node != cur) { + [next.next, node, next] = [node, next, next.next]; + } + root = nextRoot; + } + + return dummy.next; +} ``` + + diff --git a/solution/0000-0099/0025.Reverse Nodes in k-Group/README_EN.md b/solution/0000-0099/0025.Reverse Nodes in k-Group/README_EN.md index 87a9f6a6bf708..95906678c1023 100644 --- a/solution/0000-0099/0025.Reverse Nodes in k-Group/README_EN.md +++ b/solution/0000-0099/0025.Reverse Nodes in k-Group/README_EN.md @@ -39,18 +39,12 @@ ## Solutions -**Solution 1: Iteration** +### Solution 1: Iteration The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the linked list. -**Solution 2: Recursion** - -The time complexity is $O(n)$, and the space complexity is $O(\log_k n)$. Here, $n$ is the length of the linked list. - -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -85,8 +79,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -133,7 +125,41 @@ class Solution { } ``` -### **TypeScript** +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseKGroup(head *ListNode, k int) *ListNode { + var dummy *ListNode = &ListNode{} + p, cur := dummy, head + for cur != nil { + start := cur + for i := 0; i < k; i++ { + if cur == nil { + p.Next = start + return dummy.Next + } + cur = cur.Next + } + p.Next, p = reverse(start, cur), start + } + return dummy.Next +} + +func reverse(start, end *ListNode) *ListNode { + var pre *ListNode = nil + for start != end { + tmp := start.Next + start.Next, pre = pre, start + start = tmp + } + return pre +} +``` ```ts /** @@ -186,131 +212,64 @@ function reverse(head: ListNode, tail: ListNode) { } ``` -```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 reverseKGroup(head: ListNode | null, k: number): ListNode | null { - if (k === 1) { - return head; - } - - const dummy = new ListNode(0, head); - let root = dummy; - while (root != null) { - let pre = root; - let cur = root; - - let count = 0; - while (count !== k) { - count++; - cur = cur.next; - if (cur == null) { - return dummy.next; +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn reverse_k_group(head: Option>, k: i32) -> Option> { + fn reverse(head: Option>) -> Option> { + let mut head = head; + let mut pre = None; + while let Some(mut node) = head { + head = node.next.take(); + node.next = pre.take(); + pre = Some(node); } + pre } - const nextRoot = pre.next; - pre.next = cur; + let mut dummy = Some(Box::new(ListNode::new(0))); + let mut pre = &mut dummy; + let mut cur = head; + while cur.is_some() { + let mut q = &mut cur; + for _ in 0..k - 1 { + if q.is_none() { + break; + } + q = &mut q.as_mut().unwrap().next; + } + if q.is_none() { + pre.as_mut().unwrap().next = cur; + return dummy.unwrap().next; + } - let node = nextRoot; - let next = node.next; - node.next = cur.next; - while (node != cur) { - [next.next, node, next] = [node, next, next.next]; + let b = q.as_mut().unwrap().next.take(); + pre.as_mut().unwrap().next = reverse(cur); + while pre.is_some() && pre.as_mut().unwrap().next.is_some() { + pre = &mut pre.as_mut().unwrap().next; + } + cur = b; } - root = nextRoot; + dummy.unwrap().next } - - return dummy.next; -} -``` - -### **Go** - -Iteration: - -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -func reverseKGroup(head *ListNode, k int) *ListNode { - var dummy *ListNode = &ListNode{} - p, cur := dummy, head - for cur != nil { - start := cur - for i := 0; i < k; i++ { - if cur == nil { - p.Next = start - return dummy.Next - } - cur = cur.Next - } - p.Next, p = reverse(start, cur), start - } - return dummy.Next -} - -func reverse(start, end *ListNode) *ListNode { - var pre *ListNode = nil - for start != end { - tmp := start.Next - start.Next, pre = pre, start - start = tmp - } - return pre } ``` -Recursion: - -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -func reverseKGroup(head *ListNode, k int) *ListNode { - start, end := head, head - for i := 0; i < k; i++ { - if end == nil { - return head - } - end = end.Next - } - res := reverse(start, end) - start.Next = reverseKGroup(end, k) - return res -} - -func reverse(start, end *ListNode) *ListNode { - var pre *ListNode = nil - for start != end { - tmp := start.Next - start.Next, pre = pre, start - start = tmp - } - return pre -} -``` - -### **C#** - ```cs /** * Definition for singly-linked list. @@ -362,70 +321,95 @@ public class Solution { } ``` -### **Rust** + -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn reverse_k_group(head: Option>, k: i32) -> Option> { - fn reverse(head: Option>) -> Option> { - let mut head = head; - let mut pre = None; - while let Some(mut node) = head { - head = node.next.take(); - node.next = pre.take(); - pre = Some(node); - } - pre - } +### Solution 2: Recursion - let mut dummy = Some(Box::new(ListNode::new(0))); - let mut pre = &mut dummy; - let mut cur = head; - while cur.is_some() { - let mut q = &mut cur; - for _ in 0..k - 1 { - if q.is_none() { - break; - } - q = &mut q.as_mut().unwrap().next; - } - if q.is_none() { - pre.as_mut().unwrap().next = cur; - return dummy.unwrap().next; - } +The time complexity is $O(n)$, and the space complexity is $O(\log_k n)$. Here, $n$ is the length of the linked list. - let b = q.as_mut().unwrap().next.take(); - pre.as_mut().unwrap().next = reverse(cur); - while pre.is_some() && pre.as_mut().unwrap().next.is_some() { - pre = &mut pre.as_mut().unwrap().next; - } - cur = b; - } - dummy.unwrap().next - } + + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseKGroup(head *ListNode, k int) *ListNode { + start, end := head, head + for i := 0; i < k; i++ { + if end == nil { + return head + } + end = end.Next + } + res := reverse(start, end) + start.Next = reverseKGroup(end, k) + return res +} + +func reverse(start, end *ListNode) *ListNode { + var pre *ListNode = nil + for start != end { + tmp := start.Next + start.Next, pre = pre, start + start = tmp + } + return pre } ``` -### **...** +```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 reverseKGroup(head: ListNode | null, k: number): ListNode | null { + if (k === 1) { + return head; + } + const dummy = new ListNode(0, head); + let root = dummy; + while (root != null) { + let pre = root; + let cur = root; + + let count = 0; + while (count !== k) { + count++; + cur = cur.next; + if (cur == null) { + return dummy.next; + } + } + + const nextRoot = pre.next; + pre.next = cur; + + let node = nextRoot; + let next = node.next; + node.next = cur.next; + while (node != cur) { + [next.next, node, next] = [node, next, next.next]; + } + root = nextRoot; + } + + return dummy.next; +} ``` + + diff --git a/solution/0000-0099/0026.Remove Duplicates from Sorted Array/README.md b/solution/0000-0099/0026.Remove Duplicates from Sorted Array/README.md index ee70ed091a46e..0323ca3d1b1b2 100644 --- a/solution/0000-0099/0026.Remove Duplicates from Sorted Array/README.md +++ b/solution/0000-0099/0026.Remove Duplicates from Sorted Array/README.md @@ -62,9 +62,7 @@ for (int i = 0; i < k; i++) { ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们用一个变量 $k$ 记录当前已经处理好的数组的长度,初始时 $k=0$,表示空数组。 @@ -87,10 +85,6 @@ for (int i = 0; i < k; i++) { -### **Python3** - - - ```python class Solution: def removeDuplicates(self, nums: List[int]) -> int: @@ -102,10 +96,6 @@ class Solution: return k ``` -### **Java** - - - ```java class Solution { public int removeDuplicates(int[] nums) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,18 +125,6 @@ public: }; ``` -```cpp -class Solution { -public: - int removeDuplicates(vector& nums) { - nums.erase(unique(nums.begin(), nums.end()), nums.end()); - return nums.size(); - } -}; -``` - -### **Go** - ```go func removeDuplicates(nums []int) int { k := 0 @@ -162,8 +138,6 @@ func removeDuplicates(nums []int) int { } ``` -### **TypeScript** - ```ts function removeDuplicates(nums: number[]): number { let k: number = 0; @@ -176,7 +150,20 @@ function removeDuplicates(nums: number[]): number { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn remove_duplicates(nums: &mut Vec) -> i32 { + let mut k = 0; + for i in 0..nums.len() { + if k == 0 || nums[i] != nums[k - 1] { + nums[k] = nums[i]; + k += 1; + } + } + k as i32 + } +} +``` ```js /** @@ -194,8 +181,6 @@ var removeDuplicates = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public int RemoveDuplicates(int[] nums) { @@ -210,25 +195,6 @@ public class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn remove_duplicates(nums: &mut Vec) -> i32 { - let mut k = 0; - for i in 0..nums.len() { - if k == 0 || nums[i] != nums[k - 1] { - nums[k] = nums[i]; - k += 1; - } - } - k as i32 - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -247,10 +213,22 @@ class Solution { } ``` -### **...** + -``` +### 方法二 + + +```cpp +class Solution { +public: + int removeDuplicates(vector& nums) { + nums.erase(unique(nums.begin(), nums.end()), nums.end()); + return nums.size(); + } +}; ``` + + diff --git a/solution/0000-0099/0026.Remove Duplicates from Sorted Array/README_EN.md b/solution/0000-0099/0026.Remove Duplicates from Sorted Array/README_EN.md index bc9815b756d58..750403f44f588 100644 --- a/solution/0000-0099/0026.Remove Duplicates from Sorted Array/README_EN.md +++ b/solution/0000-0099/0026.Remove Duplicates from Sorted Array/README_EN.md @@ -61,7 +61,7 @@ It does not matter what you leave beyond the returned k (hence they are undersco ## Solutions -**Solution 1: Single Pass** +### Solution 1: Single Pass We use a variable $k$ to record the current length of the processed array. Initially, $k=0$ represents an empty array. @@ -84,8 +84,6 @@ Similar problems: -### **Python3** - ```python class Solution: def removeDuplicates(self, nums: List[int]) -> int: @@ -97,8 +95,6 @@ class Solution: return k ``` -### **Java** - ```java class Solution { public int removeDuplicates(int[] nums) { @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,18 +124,6 @@ public: }; ``` -```cpp -class Solution { -public: - int removeDuplicates(vector& nums) { - nums.erase(unique(nums.begin(), nums.end()), nums.end()); - return nums.size(); - } -}; -``` - -### **Go** - ```go func removeDuplicates(nums []int) int { k := 0 @@ -155,8 +137,6 @@ func removeDuplicates(nums []int) int { } ``` -### **TypeScript** - ```ts function removeDuplicates(nums: number[]): number { let k: number = 0; @@ -169,7 +149,20 @@ function removeDuplicates(nums: number[]): number { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn remove_duplicates(nums: &mut Vec) -> i32 { + let mut k = 0; + for i in 0..nums.len() { + if k == 0 || nums[i] != nums[k - 1] { + nums[k] = nums[i]; + k += 1; + } + } + k as i32 + } +} +``` ```js /** @@ -187,8 +180,6 @@ var removeDuplicates = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public int RemoveDuplicates(int[] nums) { @@ -203,25 +194,6 @@ public class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn remove_duplicates(nums: &mut Vec) -> i32 { - let mut k = 0; - for i in 0..nums.len() { - if k == 0 || nums[i] != nums[k - 1] { - nums[k] = nums[i]; - k += 1; - } - } - k as i32 - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -240,10 +212,22 @@ class Solution { } ``` -### **...** + -``` +### Solution 2 + + +```cpp +class Solution { +public: + int removeDuplicates(vector& nums) { + nums.erase(unique(nums.begin(), nums.end()), nums.end()); + return nums.size(); + } +}; ``` + + diff --git a/solution/0000-0099/0027.Remove Element/README.md b/solution/0000-0099/0027.Remove Element/README.md index 6a7d8c942e81f..5896feba93efb 100644 --- a/solution/0000-0099/0027.Remove Element/README.md +++ b/solution/0000-0099/0027.Remove Element/README.md @@ -63,9 +63,7 @@ for (int i = 0; i < len; i++) { ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们用变量 $k$ 记录当前不等于 $val$ 的元素个数。 @@ -77,10 +75,6 @@ for (int i = 0; i < len; i++) { -### **Python3** - - - ```python class Solution: def removeElement(self, nums: List[int], val: int) -> int: @@ -92,10 +86,6 @@ class Solution: return k ``` -### **Java** - - - ```java class Solution { public int removeElement(int[] nums, int val) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func removeElement(nums []int, val int) int { k := 0 @@ -142,8 +128,6 @@ func removeElement(nums []int, val int) int { } ``` -### **TypeScript** - ```ts function removeElement(nums: number[], val: number): number { let k: number = 0; @@ -156,7 +140,20 @@ function removeElement(nums: number[], val: number): number { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn remove_element(nums: &mut Vec, val: i32) -> i32 { + let mut k = 0; + for i in 0..nums.len() { + if nums[i] != val { + nums[k] = nums[i]; + k += 1; + } + } + k as i32 + } +} +``` ```js /** @@ -175,25 +172,6 @@ var removeElement = function (nums, val) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn remove_element(nums: &mut Vec, val: i32) -> i32 { - let mut k = 0; - for i in 0..nums.len() { - if nums[i] != val { - nums[k] = nums[i]; - k += 1; - } - } - k as i32 - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -211,10 +189,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0027.Remove Element/README_EN.md b/solution/0000-0099/0027.Remove Element/README_EN.md index 5ccb18dd88187..61caf2805e8a3 100644 --- a/solution/0000-0099/0027.Remove Element/README_EN.md +++ b/solution/0000-0099/0027.Remove Element/README_EN.md @@ -65,7 +65,7 @@ It does not matter what you leave beyond the returned k (hence they are undersco ## Solutions -**Solution 1: One Pass** +### Solution 1: One Pass We use the variable $k$ to record the number of elements that are not equal to $val$. @@ -77,8 +77,6 @@ The time complexity is $O(n)$ and the space complexity is $O(1)$, where $n$ is t -### **Python3** - ```python class Solution: def removeElement(self, nums: List[int], val: int) -> int: @@ -90,8 +88,6 @@ class Solution: return k ``` -### **Java** - ```java class Solution { public int removeElement(int[] nums, int val) { @@ -106,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +117,6 @@ public: }; ``` -### **Go** - ```go func removeElement(nums []int, val int) int { k := 0 @@ -138,8 +130,6 @@ func removeElement(nums []int, val int) int { } ``` -### **TypeScript** - ```ts function removeElement(nums: number[], val: number): number { let k: number = 0; @@ -152,7 +142,20 @@ function removeElement(nums: number[], val: number): number { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn remove_element(nums: &mut Vec, val: i32) -> i32 { + let mut k = 0; + for i in 0..nums.len() { + if nums[i] != val { + nums[k] = nums[i]; + k += 1; + } + } + k as i32 + } +} +``` ```js /** @@ -171,25 +174,6 @@ var removeElement = function (nums, val) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn remove_element(nums: &mut Vec, val: i32) -> i32 { - let mut k = 0; - for i in 0..nums.len() { - if nums[i] != val { - nums[k] = nums[i]; - k += 1; - } - } - k as i32 - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -207,10 +191,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/README.md b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/README.md index ee2ef8cfa843c..68a118698ef9e 100644 --- a/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/README.md +++ b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/README.md @@ -38,30 +38,14 @@ ## 解法 - - -**方法一:遍历** +### 方法一:遍历 以字符串 `haystack` 的每一个字符为起点与字符串 `needle` 进行比较,若发现能够匹配的索引,直接返回即可。 假设字符串 `haystack` 长度为 $n$,字符串 `needle` 长度为 $m$,则时间复杂度为 $O((n-m) \times m)$,空间复杂度 $O(1)$。 -**方法二:Rabin-Karp 字符串匹配算法** - -[Rabin-Karp 算法](https://zh.wikipedia.org/zh-hans/%E6%8B%89%E5%AE%BE-%E5%8D%A1%E6%99%AE%E7%AE%97%E6%B3%95)本质上是利用滑动窗口配合哈希函数对固定长度的字符串哈希之后进行比较,可以将比较两个字符串是否相同的时间复杂度降为 $O(1)$。 - -假设字符串 `haystack` 长度为 $n$,字符串 `needle` 长度为 $m$,则时间复杂度为 $O(n+m)$,空间复杂度 $O(1)$。 - -**方法三:KMP 字符串匹配算法** - -假设字符串 `haystack` 长度为 $n$,字符串 `needle` 长度为 $m$,则时间复杂度为 $O(n+m)$,空间复杂度 $O(m)$。 - -### **Python3** - - - ```python class Solution: def strStr(self, haystack: str, needle: str) -> int: @@ -72,10 +56,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int strStr(String haystack, String needle) { @@ -108,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { private: @@ -161,29 +139,6 @@ public: }; ``` -### **C#** - -```cs -public class Solution { - public int StrStr(string haystack, string needle) { - for (var i = 0; i < haystack.Length - needle.Length + 1; ++i) - { - var j = 0; - for (; j < needle.Length; ++j) - { - if (haystack[i + j] != needle[j]) break; - } - if (j == needle.Length) return i; - } - return -1; - } -} -``` - -### **Go** - -遍历: - ```go func strStr(haystack string, needle string) int { n, m := len(haystack), len(needle) @@ -196,67 +151,6 @@ func strStr(haystack string, needle string) int { } ``` -Rabin-Karp 字符串匹配算法: - -```go -func strStr(haystack string, needle string) int { - n, m := len(haystack), len(needle) - sha, target, left, right, mod := 0, 0, 0, 0, 1<<31-1 - multi := 1 - for i := 0; i < m; i++ { - target = (target*256%mod + int(needle[i])) % mod - } - for i := 1; i < m; i++ { - multi = multi * 256 % mod - } - - for ; right < n; right++ { - sha = (sha*256%mod + int(haystack[right])) % mod - if right-left+1 < m { - continue - } - // 此时 left~right 的长度已经为 needle 的长度 m 了,只需要比对 sha 值与 target 是否一致即可 - // 为避免 hash 冲突,还需要确保 haystack[left:right+1] 与 needle 相同 - if sha == target && haystack[left:right+1] == needle { - return left - } - // 未匹配成功,left 右移一位 - sha = (sha - (int(haystack[left])*multi)%mod + mod) % mod - left++ - } - return -1 -} -``` - -### **JavaScript** - -```js -/** - * @param {string} haystack - * @param {string} needle - * @return {number} - */ -var strStr = function (haystack, needle) { - const slen = haystack.length; - const plen = needle.length; - if (slen == plen) { - return haystack == needle ? 0 : -1; - } - for (let i = 0; i <= slen - plen; i++) { - let j; - for (j = 0; j < plen; j++) { - if (haystack[i + j] != needle[j]) { - break; - } - } - if (j == plen) return i; - } - return -1; -}; -``` - -### **TypeScript** - ```ts function strStr(haystack: string, needle: string): number { const m = haystack.length; @@ -277,39 +171,6 @@ function strStr(haystack: string, needle: string): number { } ``` -```ts -function strStr(haystack: string, needle: string): number { - const m = haystack.length; - const n = needle.length; - const next = new Array(n).fill(0); - let j = 0; - for (let i = 1; i < n; i++) { - while (j > 0 && needle[i] !== needle[j]) { - j = next[j - 1]; - } - if (needle[i] === needle[j]) { - j++; - } - next[i] = j; - } - j = 0; - for (let i = 0; i < m; i++) { - while (j > 0 && haystack[i] !== needle[j]) { - j = next[j - 1]; - } - if (haystack[i] === needle[j]) { - j++; - } - if (j === n) { - return i - n + 1; - } - } - return -1; -} -``` - -### **Rust** - ```rust impl Solution { pub fn str_str(haystack: String, needle: String) -> i32 { @@ -345,7 +206,47 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {string} haystack + * @param {string} needle + * @return {number} + */ +var strStr = function (haystack, needle) { + const slen = haystack.length; + const plen = needle.length; + if (slen == plen) { + return haystack == needle ? 0 : -1; + } + for (let i = 0; i <= slen - plen; i++) { + let j; + for (j = 0; j < plen; j++) { + if (haystack[i + j] != needle[j]) { + break; + } + } + if (j == plen) return i; + } + return -1; +}; +``` + +```cs +public class Solution { + public int StrStr(string haystack, string needle) { + for (var i = 0; i < haystack.Length - needle.Length + 1; ++i) + { + var j = 0; + for (; j < needle.Length; ++j) + { + if (haystack[i + j] != needle[j]) break; + } + if (j == needle.Length) return i; + } + return -1; + } +} +``` ```php class Solution { @@ -370,10 +271,81 @@ class Solution { } ``` -### **...** + + +### 方法二:Rabin-Karp 字符串匹配算法 + +[Rabin-Karp 算法](https://zh.wikipedia.org/zh-hans/%E6%8B%89%E5%AE%BE-%E5%8D%A1%E6%99%AE%E7%AE%97%E6%B3%95)本质上是利用滑动窗口配合哈希函数对固定长度的字符串哈希之后进行比较,可以将比较两个字符串是否相同的时间复杂度降为 $O(1)$。 + +假设字符串 `haystack` 长度为 $n$,字符串 `needle` 长度为 $m$,则时间复杂度为 $O(n+m)$,空间复杂度 $O(1)$。 + + +```go +func strStr(haystack string, needle string) int { + n, m := len(haystack), len(needle) + sha, target, left, right, mod := 0, 0, 0, 0, 1<<31-1 + multi := 1 + for i := 0; i < m; i++ { + target = (target*256%mod + int(needle[i])) % mod + } + for i := 1; i < m; i++ { + multi = multi * 256 % mod + } + + for ; right < n; right++ { + sha = (sha*256%mod + int(haystack[right])) % mod + if right-left+1 < m { + continue + } + // 此时 left~right 的长度已经为 needle 的长度 m 了,只需要比对 sha 值与 target 是否一致即可 + // 为避免 hash 冲突,还需要确保 haystack[left:right+1] 与 needle 相同 + if sha == target && haystack[left:right+1] == needle { + return left + } + // 未匹配成功,left 右移一位 + sha = (sha - (int(haystack[left])*multi)%mod + mod) % mod + left++ + } + return -1 +} ``` +```ts +function strStr(haystack: string, needle: string): number { + const m = haystack.length; + const n = needle.length; + const next = new Array(n).fill(0); + let j = 0; + for (let i = 1; i < n; i++) { + while (j > 0 && needle[i] !== needle[j]) { + j = next[j - 1]; + } + if (needle[i] === needle[j]) { + j++; + } + next[i] = j; + } + j = 0; + for (let i = 0; i < m; i++) { + while (j > 0 && haystack[i] !== needle[j]) { + j = next[j - 1]; + } + if (haystack[i] === needle[j]) { + j++; + } + if (j === n) { + return i - n + 1; + } + } + return -1; +} ``` + +### 方法三:KMP 字符串匹配算法 + +假设字符串 `haystack` 长度为 $n$,字符串 `needle` 长度为 $m$,则时间复杂度为 $O(n+m)$,空间复杂度 $O(m)$。 + + diff --git a/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/README_EN.md b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/README_EN.md index e95cefa2f205d..3abc6a31ba35c 100644 --- a/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/README_EN.md +++ b/solution/0000-0099/0028.Find the Index of the First Occurrence in a String/README_EN.md @@ -34,26 +34,14 @@ The first occurrence is at index 0, so we return 0. ## Solutions -**Solution 1: Traversal** +### Solution 1: Traversal We compare the string `needle` with each character of the string `haystack` as the starting point. If we find a matching index, we return it directly. Assuming the length of the string `haystack` is $n$ and the length of the string `needle` is $m$, the time complexity is $O((n-m) \times m)$, and the space complexity is $O(1)$. -**Solution 2: Rabin-Karp String Matching Algorithm** - -The [Rabin-Karp algorithm](https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm) essentially uses a sliding window combined with a hash function to compare the hashes of fixed-length strings, which can reduce the time complexity of comparing whether two strings are the same to $O(1)$. - -Assuming the length of the string `haystack` is $n$ and the length of the string `needle` is $m$, the time complexity is $O(n+m)$, and the space complexity is $O(1)$. - -**Solution 3: KMP String Matching Algorithm** - -Assuming the length of the string `haystack` is $n$ and the length of the string `needle` is $m$, the time complexity is $O(n+m)$, and the space complexity is $O(m)$. - -### **Python3** - ```python class Solution: def strStr(self, haystack: str, needle: str) -> int: @@ -64,8 +52,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int strStr(String haystack, String needle) { @@ -98,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { private: @@ -151,29 +135,6 @@ public: }; ``` -### **C#** - -```cs -public class Solution { - public int StrStr(string haystack, string needle) { - for (var i = 0; i < haystack.Length - needle.Length + 1; ++i) - { - var j = 0; - for (; j < needle.Length; ++j) - { - if (haystack[i + j] != needle[j]) break; - } - if (j == needle.Length) return i; - } - return -1; - } -} -``` - -### **Go** - -Traverse: - ```go func strStr(haystack string, needle string) int { n, m := len(haystack), len(needle) @@ -186,67 +147,6 @@ func strStr(haystack string, needle string) int { } ``` -Rabin-Karp: - -```go -func strStr(haystack string, needle string) int { - n, m := len(haystack), len(needle) - sha, target, left, right, mod := 0, 0, 0, 0, 1<<31-1 - multi := 1 - for i := 0; i < m; i++ { - target = (target*256%mod + int(needle[i])) % mod - } - for i := 1; i < m; i++ { - multi = multi * 256 % mod - } - - for ; right < n; right++ { - sha = (sha*256%mod + int(haystack[right])) % mod - if right-left+1 < m { - continue - } - // 此时 left~right 的长度已经为 needle 的长度 m 了,只需要比对 sha 值与 target 是否一致即可 - // 为避免 hash 冲突,还需要确保 haystack[left:right+1] 与 needle 相同 - if sha == target && haystack[left:right+1] == needle { - return left - } - // 未匹配成功,left 右移一位 - sha = (sha - (int(haystack[left])*multi)%mod + mod) % mod - left++ - } - return -1 -} -``` - -### **JavaScript** - -```js -/** - * @param {string} haystack - * @param {string} needle - * @return {number} - */ -var strStr = function (haystack, needle) { - const slen = haystack.length; - const plen = needle.length; - if (slen == plen) { - return haystack == needle ? 0 : -1; - } - for (let i = 0; i <= slen - plen; i++) { - let j; - for (j = 0; j < plen; j++) { - if (haystack[i + j] != needle[j]) { - break; - } - } - if (j == plen) return i; - } - return -1; -}; -``` - -### **TypeScript** - ```ts function strStr(haystack: string, needle: string): number { const m = haystack.length; @@ -267,39 +167,6 @@ function strStr(haystack: string, needle: string): number { } ``` -```ts -function strStr(haystack: string, needle: string): number { - const m = haystack.length; - const n = needle.length; - const next = new Array(n).fill(0); - let j = 0; - for (let i = 1; i < n; i++) { - while (j > 0 && needle[i] !== needle[j]) { - j = next[j - 1]; - } - if (needle[i] === needle[j]) { - j++; - } - next[i] = j; - } - j = 0; - for (let i = 0; i < m; i++) { - while (j > 0 && haystack[i] !== needle[j]) { - j = next[j - 1]; - } - if (haystack[i] === needle[j]) { - j++; - } - if (j === n) { - return i - n + 1; - } - } - return -1; -} -``` - -### **Rust** - ```rust impl Solution { pub fn str_str(haystack: String, needle: String) -> i32 { @@ -335,7 +202,47 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {string} haystack + * @param {string} needle + * @return {number} + */ +var strStr = function (haystack, needle) { + const slen = haystack.length; + const plen = needle.length; + if (slen == plen) { + return haystack == needle ? 0 : -1; + } + for (let i = 0; i <= slen - plen; i++) { + let j; + for (j = 0; j < plen; j++) { + if (haystack[i + j] != needle[j]) { + break; + } + } + if (j == plen) return i; + } + return -1; +}; +``` + +```cs +public class Solution { + public int StrStr(string haystack, string needle) { + for (var i = 0; i < haystack.Length - needle.Length + 1; ++i) + { + var j = 0; + for (; j < needle.Length; ++j) + { + if (haystack[i + j] != needle[j]) break; + } + if (j == needle.Length) return i; + } + return -1; + } +} +``` ```php class Solution { @@ -360,10 +267,81 @@ class Solution { } ``` -### **...** + + +### Solution 2: Rabin-Karp String Matching Algorithm + +The [Rabin-Karp algorithm](https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm) essentially uses a sliding window combined with a hash function to compare the hashes of fixed-length strings, which can reduce the time complexity of comparing whether two strings are the same to $O(1)$. + +Assuming the length of the string `haystack` is $n$ and the length of the string `needle` is $m$, the time complexity is $O(n+m)$, and the space complexity is $O(1)$. + + +```go +func strStr(haystack string, needle string) int { + n, m := len(haystack), len(needle) + sha, target, left, right, mod := 0, 0, 0, 0, 1<<31-1 + multi := 1 + for i := 0; i < m; i++ { + target = (target*256%mod + int(needle[i])) % mod + } + for i := 1; i < m; i++ { + multi = multi * 256 % mod + } + + for ; right < n; right++ { + sha = (sha*256%mod + int(haystack[right])) % mod + if right-left+1 < m { + continue + } + // 此时 left~right 的长度已经为 needle 的长度 m 了,只需要比对 sha 值与 target 是否一致即可 + // 为避免 hash 冲突,还需要确保 haystack[left:right+1] 与 needle 相同 + if sha == target && haystack[left:right+1] == needle { + return left + } + // 未匹配成功,left 右移一位 + sha = (sha - (int(haystack[left])*multi)%mod + mod) % mod + left++ + } + return -1 +} ``` +```ts +function strStr(haystack: string, needle: string): number { + const m = haystack.length; + const n = needle.length; + const next = new Array(n).fill(0); + let j = 0; + for (let i = 1; i < n; i++) { + while (j > 0 && needle[i] !== needle[j]) { + j = next[j - 1]; + } + if (needle[i] === needle[j]) { + j++; + } + next[i] = j; + } + j = 0; + for (let i = 0; i < m; i++) { + while (j > 0 && haystack[i] !== needle[j]) { + j = next[j - 1]; + } + if (haystack[i] === needle[j]) { + j++; + } + if (j === n) { + return i - n + 1; + } + } + return -1; +} ``` + +### Solution 3: KMP String Matching Algorithm + +Assuming the length of the string `haystack` is $n$ and the length of the string `needle` is $m$, the time complexity is $O(n+m)$, and the space complexity is $O(m)$. + + diff --git a/solution/0000-0099/0029.Divide Two Integers/README.md b/solution/0000-0099/0029.Divide Two Integers/README.md index 67ec0cb50cf15..d3312c4b0d70e 100644 --- a/solution/0000-0099/0029.Divide Two Integers/README.md +++ b/solution/0000-0099/0029.Divide Two Integers/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:模拟 + 快速幂** +### 方法一:模拟 + 快速幂 除法本质上就是减法,题目要求我们计算出两个数相除之后的取整结果,其实就是计算被除数是多少个除数加上一个小于除数的数构成的。但是一次循环只能做一次减法,效率太低会导致超时,可借助快速幂的思想进行优化。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def divide(self, a: int, b: int) -> int: @@ -79,10 +73,6 @@ class Solution: return ans if sign else -ans ``` -### **Java** - - - ```java class Solution { public int divide(int a, int b) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func divide(a int, b int) int { if b == 1 { @@ -180,8 +166,6 @@ func divide(a int, b int) int { } ``` -### **TypeScript** - ```ts function divide(a: number, b: number): number { if (b === 1) { @@ -213,8 +197,6 @@ function divide(a: number, b: number): number { } ``` -### **C#** - ```cs public class Solution { public int Divide(int a, int b) { @@ -243,10 +225,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0029.Divide Two Integers/README_EN.md b/solution/0000-0099/0029.Divide Two Integers/README_EN.md index 17aba11da6e4f..ae08eaa031184 100644 --- a/solution/0000-0099/0029.Divide Two Integers/README_EN.md +++ b/solution/0000-0099/0029.Divide Two Integers/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Simulation + Fast Power** +### Solution 1: Simulation + Fast Power Division is essentially subtraction. The problem requires us to calculate the integer result after dividing two numbers, which is actually calculating how many divisors and a number less than the divisor constitute the dividend. However, only one subtraction can be done in one loop, which is too inefficient and will lead to timeout. This can be optimized by using the idea of fast power. @@ -49,8 +49,6 @@ Assuming the dividend is $a$ and the divisor is $b$, the time complexity is $O(\ -### **Python3** - ```python class Solution: def divide(self, a: int, b: int) -> int: @@ -73,8 +71,6 @@ class Solution: return ans if sign else -ans ``` -### **Java** - ```java class Solution { public int divide(int a, int b) { @@ -103,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +128,6 @@ public: }; ``` -### **Go** - ```go func divide(a int, b int) int { if b == 1 { @@ -172,8 +164,6 @@ func divide(a int, b int) int { } ``` -### **TypeScript** - ```ts function divide(a: number, b: number): number { if (b === 1) { @@ -205,8 +195,6 @@ function divide(a: number, b: number): number { } ``` -### **C#** - ```cs public class Solution { public int Divide(int a, int b) { @@ -235,10 +223,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0030.Substring with Concatenation of All Words/README.md b/solution/0000-0099/0030.Substring with Concatenation of All Words/README.md index 7a9497043b08a..7585f1051a8d5 100644 --- a/solution/0000-0099/0030.Substring with Concatenation of All Words/README.md +++ b/solution/0000-0099/0030.Substring with Concatenation of All Words/README.md @@ -62,9 +62,7 @@ s 中没有子串长度为 16 并且等于 words 的任何顺序排列的连接 ## 解法 - - -**方法一:哈希表 + 滑动窗口** +### 方法一:哈希表 + 滑动窗口 我们用哈希表 $cnt$ 统计 $words$ 中每个单词出现的次数,用哈希表 $cnt1$ 统计当前滑动窗口中每个单词出现的次数。我们记字符串 $s$ 的长度为 $m$,字符串数组 $words$ 中单词的数量为 $n$,每个单词的长度为 $k$。 @@ -76,10 +74,6 @@ s 中没有子串长度为 16 并且等于 words 的任何顺序排列的连接 -### **Python3** - - - ```python class Solution: def findSubstring(self, s: str, words: List[str]) -> List[int]: @@ -111,10 +105,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List findSubstring(String s, String[] words) { @@ -156,8 +146,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -199,36 +187,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector findSubstring(string s, vector& words) { - unordered_map d; - for (auto& w : words) ++d[w]; - vector ans; - int n = s.size(), m = words.size(), k = words[0].size(); - for (int i = 0; i < k; ++i) { - int cnt = 0; - unordered_map t; - for (int j = i; j <= n; j += k) { - if (j - i >= m * k) { - auto s1 = s.substr(j - m * k, k); - --t[s1]; - cnt -= d[s1] > t[s1]; - } - auto s2 = s.substr(j, k); - ++t[s2]; - cnt += d[s2] >= t[s2]; - if (cnt == m) ans.emplace_back(j - (m - 1) * k); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func findSubstring(s string, words []string) (ans []int) { cnt := map[string]int{} @@ -263,7 +221,46 @@ func findSubstring(s string, words []string) (ans []int) { } ``` -### **C#** +```ts +function findSubstring(s: string, words: string[]): number[] { + const cnt: Map = new Map(); + for (const w of words) { + cnt.set(w, (cnt.get(w) || 0) + 1); + } + const m = s.length; + const n = words.length; + const k = words[0].length; + const ans: number[] = []; + for (let i = 0; i < k; ++i) { + const cnt1: Map = new Map(); + let l = i; + let r = i; + let t = 0; + while (r + k <= m) { + const w = s.slice(r, r + k); + r += k; + if (!cnt.has(w)) { + cnt1.clear(); + l = r; + t = 0; + continue; + } + cnt1.set(w, (cnt1.get(w) || 0) + 1); + ++t; + while (cnt1.get(w)! - cnt.get(w)! > 0) { + const remove = s.slice(l, l + k); + cnt1.set(remove, cnt1.get(remove)! - 1); + l += k; + --t; + } + if (t === n) { + ans.push(l); + } + } + } + return ans; +} +``` ```cs public class Solution { @@ -309,53 +306,40 @@ public class Solution { } ``` -### **TypeScript** + -```ts -function findSubstring(s: string, words: string[]): number[] { - const cnt: Map = new Map(); - for (const w of words) { - cnt.set(w, (cnt.get(w) || 0) + 1); - } - const m = s.length; - const n = words.length; - const k = words[0].length; - const ans: number[] = []; - for (let i = 0; i < k; ++i) { - const cnt1: Map = new Map(); - let l = i; - let r = i; - let t = 0; - while (r + k <= m) { - const w = s.slice(r, r + k); - r += k; - if (!cnt.has(w)) { - cnt1.clear(); - l = r; - t = 0; - continue; - } - cnt1.set(w, (cnt1.get(w) || 0) + 1); - ++t; - while (cnt1.get(w)! - cnt.get(w)! > 0) { - const remove = s.slice(l, l + k); - cnt1.set(remove, cnt1.get(remove)! - 1); - l += k; - --t; - } - if (t === n) { - ans.push(l); +### 方法二 + + + +```cpp +class Solution { +public: + vector findSubstring(string s, vector& words) { + unordered_map d; + for (auto& w : words) ++d[w]; + vector ans; + int n = s.size(), m = words.size(), k = words[0].size(); + for (int i = 0; i < k; ++i) { + int cnt = 0; + unordered_map t; + for (int j = i; j <= n; j += k) { + if (j - i >= m * k) { + auto s1 = s.substr(j - m * k, k); + --t[s1]; + cnt -= d[s1] > t[s1]; + } + auto s2 = s.substr(j, k); + ++t[s2]; + cnt += d[s2] >= t[s2]; + if (cnt == m) ans.emplace_back(j - (m - 1) * k); } } + return ans; } - return ans; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0000-0099/0030.Substring with Concatenation of All Words/README_EN.md b/solution/0000-0099/0030.Substring with Concatenation of All Words/README_EN.md index af533b18b9b5d..5167216754aaa 100644 --- a/solution/0000-0099/0030.Substring with Concatenation of All Words/README_EN.md +++ b/solution/0000-0099/0030.Substring with Concatenation of All Words/README_EN.md @@ -59,7 +59,7 @@ The substring starting at 12 is "thefoobar". It is the concatenation o ## Solutions -**Solution 1: Hash Table + Sliding Window** +### Solution 1: Hash Table + Sliding Window We use a hash table $cnt$ to count the number of times each word appears in $words$, and use a hash table $cnt1$ to count the number of times each word appears in the current sliding window. We denote the length of the string $s$ as $m$, the number of words in the string array $words$ as $n$, and the length of each word as $k$. @@ -71,8 +71,6 @@ The time complexity is $O(m \times k)$, and the space complexity is $O(n \times -### **Python3** - ```python class Solution: def findSubstring(self, s: str, words: List[str]) -> List[int]: @@ -104,8 +102,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List findSubstring(String s, String[] words) { @@ -147,8 +143,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -190,36 +184,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector findSubstring(string s, vector& words) { - unordered_map d; - for (auto& w : words) ++d[w]; - vector ans; - int n = s.size(), m = words.size(), k = words[0].size(); - for (int i = 0; i < k; ++i) { - int cnt = 0; - unordered_map t; - for (int j = i; j <= n; j += k) { - if (j - i >= m * k) { - auto s1 = s.substr(j - m * k, k); - --t[s1]; - cnt -= d[s1] > t[s1]; - } - auto s2 = s.substr(j, k); - ++t[s2]; - cnt += d[s2] >= t[s2]; - if (cnt == m) ans.emplace_back(j - (m - 1) * k); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func findSubstring(s string, words []string) (ans []int) { cnt := map[string]int{} @@ -254,7 +218,46 @@ func findSubstring(s string, words []string) (ans []int) { } ``` -### **C#** +```ts +function findSubstring(s: string, words: string[]): number[] { + const cnt: Map = new Map(); + for (const w of words) { + cnt.set(w, (cnt.get(w) || 0) + 1); + } + const m = s.length; + const n = words.length; + const k = words[0].length; + const ans: number[] = []; + for (let i = 0; i < k; ++i) { + const cnt1: Map = new Map(); + let l = i; + let r = i; + let t = 0; + while (r + k <= m) { + const w = s.slice(r, r + k); + r += k; + if (!cnt.has(w)) { + cnt1.clear(); + l = r; + t = 0; + continue; + } + cnt1.set(w, (cnt1.get(w) || 0) + 1); + ++t; + while (cnt1.get(w)! - cnt.get(w)! > 0) { + const remove = s.slice(l, l + k); + cnt1.set(remove, cnt1.get(remove)! - 1); + l += k; + --t; + } + if (t === n) { + ans.push(l); + } + } + } + return ans; +} +``` ```cs public class Solution { @@ -300,53 +303,40 @@ public class Solution { } ``` -### **TypeScript** + -```ts -function findSubstring(s: string, words: string[]): number[] { - const cnt: Map = new Map(); - for (const w of words) { - cnt.set(w, (cnt.get(w) || 0) + 1); - } - const m = s.length; - const n = words.length; - const k = words[0].length; - const ans: number[] = []; - for (let i = 0; i < k; ++i) { - const cnt1: Map = new Map(); - let l = i; - let r = i; - let t = 0; - while (r + k <= m) { - const w = s.slice(r, r + k); - r += k; - if (!cnt.has(w)) { - cnt1.clear(); - l = r; - t = 0; - continue; - } - cnt1.set(w, (cnt1.get(w) || 0) + 1); - ++t; - while (cnt1.get(w)! - cnt.get(w)! > 0) { - const remove = s.slice(l, l + k); - cnt1.set(remove, cnt1.get(remove)! - 1); - l += k; - --t; - } - if (t === n) { - ans.push(l); +### Solution 2 + + + +```cpp +class Solution { +public: + vector findSubstring(string s, vector& words) { + unordered_map d; + for (auto& w : words) ++d[w]; + vector ans; + int n = s.size(), m = words.size(), k = words[0].size(); + for (int i = 0; i < k; ++i) { + int cnt = 0; + unordered_map t; + for (int j = i; j <= n; j += k) { + if (j - i >= m * k) { + auto s1 = s.substr(j - m * k, k); + --t[s1]; + cnt -= d[s1] > t[s1]; + } + auto s2 = s.substr(j, k); + ++t[s2]; + cnt += d[s2] >= t[s2]; + if (cnt == m) ans.emplace_back(j - (m - 1) * k); } } + return ans; } - return ans; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0000-0099/0031.Next Permutation/README.md b/solution/0000-0099/0031.Next Permutation/README.md index 16e1b320377d1..4192cc426cd4f 100644 --- a/solution/0000-0099/0031.Next Permutation/README.md +++ b/solution/0000-0099/0031.Next Permutation/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:两次遍历** +### 方法一:两次遍历 我们先从后往前遍历数组 $nums$,找到第一个满足 $nums[i] \lt nums[i + 1]$ 的位置 $i$,那么 $nums[i]$ 就是我们需要交换的元素,而 $nums[i + 1]$ 到 $nums[n - 1]$ 的元素是一个降序序列。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def nextPermutation(self, nums: List[int]) -> None: @@ -85,10 +79,6 @@ class Solution: nums[i + 1 :] = nums[i + 1 :][::-1] ``` -### **Java** - - - ```java class Solution { public void nextPermutation(int[] nums) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go func nextPermutation(nums []int) { n := len(nums) @@ -167,8 +153,6 @@ func nextPermutation(nums []int) { } ``` -### **TypeScript** - ```ts function nextPermutation(nums: number[]): void { const n = nums.length; @@ -190,7 +174,29 @@ function nextPermutation(nums: number[]): void { } ``` -### **C#** +```js +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var nextPermutation = function (nums) { + const n = nums.length; + let i = n - 2; + while (i >= 0 && nums[i] >= nums[i + 1]) { + --i; + } + if (i >= 0) { + let j = n - 1; + while (j > i && nums[j] <= nums[i]) { + --j; + } + [nums[i], nums[j]] = [nums[j], nums[i]]; + } + for (i = i + 1, j = n - 1; i < j; ++i, --j) { + [nums[i], nums[j]] = [nums[j], nums[i]]; + } +}; +``` ```cs public class Solution { @@ -221,36 +227,6 @@ public class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {void} Do not return anything, modify nums in-place instead. - */ -var nextPermutation = function (nums) { - const n = nums.length; - let i = n - 2; - while (i >= 0 && nums[i] >= nums[i + 1]) { - --i; - } - if (i >= 0) { - let j = n - 1; - while (j > i && nums[j] <= nums[i]) { - --j; - } - [nums[i], nums[j]] = [nums[j], nums[i]]; - } - for (i = i + 1, j = n - 1; i < j; ++i, --j) { - [nums[i], nums[j]] = [nums[j], nums[i]]; - } -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0031.Next Permutation/README_EN.md b/solution/0000-0099/0031.Next Permutation/README_EN.md index d7fe1d4675ac2..6f218c98e7c38 100644 --- a/solution/0000-0099/0031.Next Permutation/README_EN.md +++ b/solution/0000-0099/0031.Next Permutation/README_EN.md @@ -54,7 +54,7 @@ ## Solutions -**Solution 1: Two traversals** +### Solution 1: Two traversals We first traverse the array from back to front and find the first position $i$ where $nums[i] \lt nums[i + 1]$. @@ -64,8 +64,6 @@ The time complexity is $O(n)$ and the space complexity is $O(1)$. Where $n$ is t -### **Python3** - ```python class Solution: def nextPermutation(self, nums: List[int]) -> None: @@ -77,8 +75,6 @@ class Solution: nums[i + 1 :] = nums[i + 1 :][::-1] ``` -### **Java** - ```java class Solution { public void nextPermutation(int[] nums) { @@ -111,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +129,6 @@ public: }; ``` -### **Go** - ```go func nextPermutation(nums []int) { n := len(nums) @@ -157,8 +149,6 @@ func nextPermutation(nums []int) { } ``` -### **TypeScript** - ```ts function nextPermutation(nums: number[]): void { const n = nums.length; @@ -180,7 +170,29 @@ function nextPermutation(nums: number[]): void { } ``` -### **C#** +```js +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var nextPermutation = function (nums) { + const n = nums.length; + let i = n - 2; + while (i >= 0 && nums[i] >= nums[i + 1]) { + --i; + } + if (i >= 0) { + let j = n - 1; + while (j > i && nums[j] <= nums[i]) { + --j; + } + [nums[i], nums[j]] = [nums[j], nums[i]]; + } + for (i = i + 1, j = n - 1; i < j; ++i, --j) { + [nums[i], nums[j]] = [nums[j], nums[i]]; + } +}; +``` ```cs public class Solution { @@ -211,36 +223,6 @@ public class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {void} Do not return anything, modify nums in-place instead. - */ -var nextPermutation = function (nums) { - const n = nums.length; - let i = n - 2; - while (i >= 0 && nums[i] >= nums[i + 1]) { - --i; - } - if (i >= 0) { - let j = n - 1; - while (j > i && nums[j] <= nums[i]) { - --j; - } - [nums[i], nums[j]] = [nums[j], nums[i]]; - } - for (i = i + 1, j = n - 1; i < j; ++i, --j) { - [nums[i], nums[j]] = [nums[j], nums[i]]; - } -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0032.Longest Valid Parentheses/README.md b/solution/0000-0099/0032.Longest Valid Parentheses/README.md index ccb3aa2c2a2e4..a01bbd90be9c6 100644 --- a/solution/0000-0099/0032.Longest Valid Parentheses/README.md +++ b/solution/0000-0099/0032.Longest Valid Parentheses/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示以 $s[i-1]$ 结尾的最长有效括号的长度,那么答案就是 $\max\limits_{i=1}^n f[i]$。 @@ -73,26 +71,8 @@ $$ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串的长度。 -**方法二:使用栈** - -- 使用栈来存储左括号的索引,栈底元素初始化为 `-1`,用于辅助计算有效括号的长度。 -- 遍历字符串,对于每个字符: - - 如果是左括号,将当前位置压入栈。 - - 如果是右括号,弹出栈顶元素表示匹配了一个左括号。 - - 如果栈为空,说明当前右括号无法匹配,将当前位置压入栈作为新的起点。 - - 如果栈不为空,计算当前有效括号子串的长度,更新最大长度。 -- 最终返回最大长度。 - -总结:这个算法的关键在于维护一个线,栈内存放的是左括号的索引,通过弹出和压入的操作来更新有效括号子串的长度。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串的长度。 - -### **Python3** - - - ```python class Solution: def longestValidParentheses(self, s: str) -> int: @@ -109,27 +89,6 @@ class Solution: return max(f) ``` -```python -class Solution: - def longestValidParentheses(self, s: str) -> int: - stack = [-1] - ans = 0 - for i in range(len(s)): - if s[i] == '(': - stack.append(i) - else: - stack.pop() - if not stack: - stack.append(i) - else: - ans = max(ans, i - stack[-1]) - return ans -``` - -### **Java** - - - ```java class Solution { public int longestValidParentheses(String s) { @@ -154,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -180,8 +137,6 @@ public: }; ``` -### **Go** - ```go func longestValidParentheses(s string) int { n := len(s) @@ -199,56 +154,6 @@ func longestValidParentheses(s string) int { } ``` -```go -func longestValidParentheses(s string) int { - ans := 0 - stack := []int{-1} - for i, v := range s { - if v == '(' { - stack = append(stack, i) - } else { - stack = stack[:len(stack)-1] - if len(stack) == 0 { - stack = append(stack, i) - } else { - if ans < i-stack[len(stack)-1] { - ans = i - stack[len(stack)-1] - } - } - } - } - return ans -} -``` - -### **C#** - -```cs -public class Solution { - public int LongestValidParentheses(string s) { - int n = s.Length; - int[] f = new int[n + 1]; - int ans = 0; - for (int i = 2; i <= n; ++i) { - if (s[i - 1] == ')') { - if (s[i - 2] == '(') { - f[i] = f[i - 2] + 2; - } else { - int j = i - f[i - 1] - 1; - if (j > 0 && s[j - 1] == '(') { - f[i] = f[i - 1] + 2 + f[j - 1]; - } - } - ans = Math.Max(ans, f[i]); - } - } - return ans; - } -} -``` - -### **TypeScript** - ```ts function longestValidParentheses(s: string): number { const n = s.length; @@ -269,30 +174,42 @@ function longestValidParentheses(s: string): number { } ``` -```ts -function longestValidParentheses(s: string): number { - let max_length: number = 0; - const stack: number[] = [-1]; - for (let i = 0; i < s.length; i++) { - if (s.charAt(i) == '(') { - stack.push(i); - } else { - stack.pop(); - - if (stack.length === 0) { - stack.push(i); - } else { - max_length = Math.max(max_length, i - stack[stack.length - 1]); +```rust +impl Solution { + pub fn longest_valid_parentheses(s: String) -> i32 { + let mut ans = 0; + let mut f = vec![0; s.len() + 1]; + for i in 2..=s.len() { + if + s + .chars() + .nth(i - 1) + .unwrap() == ')' + { + if + s + .chars() + .nth(i - 2) + .unwrap() == '(' + { + f[i] = f[i - 2] + 2; + } else if + (i as i32) - f[i - 1] - 1 > 0 && + s + .chars() + .nth(i - (f[i - 1] as usize) - 2) + .unwrap() == '(' + { + f[i] = f[i - 1] + 2 + f[i - (f[i - 1] as usize) - 2]; + } + ans = ans.max(f[i]); } } + ans } - - return max_length; } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -317,65 +234,106 @@ var longestValidParentheses = function (s) { }; ``` -```js -/** - * @param {string} s - * @return {number} - */ -var longestValidParentheses = function (s) { - let ans = 0; - const stack = [-1]; - for (i = 0; i < s.length; i++) { - if (s.charAt(i) === '(') { +```cs +public class Solution { + public int LongestValidParentheses(string s) { + int n = s.Length; + int[] f = new int[n + 1]; + int ans = 0; + for (int i = 2; i <= n; ++i) { + if (s[i - 1] == ')') { + if (s[i - 2] == '(') { + f[i] = f[i - 2] + 2; + } else { + int j = i - f[i - 1] - 1; + if (j > 0 && s[j - 1] == '(') { + f[i] = f[i - 1] + 2 + f[j - 1]; + } + } + ans = Math.Max(ans, f[i]); + } + } + return ans; + } +} +``` + + + +### 方法二:使用栈 + +- 使用栈来存储左括号的索引,栈底元素初始化为 `-1`,用于辅助计算有效括号的长度。 +- 遍历字符串,对于每个字符: + - 如果是左括号,将当前位置压入栈。 + - 如果是右括号,弹出栈顶元素表示匹配了一个左括号。 + - 如果栈为空,说明当前右括号无法匹配,将当前位置压入栈作为新的起点。 + - 如果栈不为空,计算当前有效括号子串的长度,更新最大长度。 +- 最终返回最大长度。 + +总结:这个算法的关键在于维护一个线,栈内存放的是左括号的索引,通过弹出和压入的操作来更新有效括号子串的长度。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串的长度。 + + + +```python +class Solution: + def longestValidParentheses(self, s: str) -> int: + stack = [-1] + ans = 0 + for i in range(len(s)): + if s[i] == '(': + stack.append(i) + else: + stack.pop() + if not stack: + stack.append(i) + else: + ans = max(ans, i - stack[-1]) + return ans +``` + +```go +func longestValidParentheses(s string) int { + ans := 0 + stack := []int{-1} + for i, v := range s { + if v == '(' { + stack = append(stack, i) + } else { + stack = stack[:len(stack)-1] + if len(stack) == 0 { + stack = append(stack, i) + } else { + if ans < i-stack[len(stack)-1] { + ans = i - stack[len(stack)-1] + } + } + } + } + return ans +} +``` + +```ts +function longestValidParentheses(s: string): number { + let max_length: number = 0; + const stack: number[] = [-1]; + for (let i = 0; i < s.length; i++) { + if (s.charAt(i) == '(') { stack.push(i); } else { stack.pop(); + if (stack.length === 0) { stack.push(i); } else { - ans = Math.max(ans, i - stack[stack.length - 1]); + max_length = Math.max(max_length, i - stack[stack.length - 1]); } } } - return ans; -}; -``` - -### **Rust** -```rust -impl Solution { - pub fn longest_valid_parentheses(s: String) -> i32 { - let mut ans = 0; - let mut f = vec![0; s.len() + 1]; - for i in 2..=s.len() { - if - s - .chars() - .nth(i - 1) - .unwrap() == ')' - { - if - s - .chars() - .nth(i - 2) - .unwrap() == '(' - { - f[i] = f[i - 2] + 2; - } else if - (i as i32) - f[i - 1] - 1 > 0 && - s - .chars() - .nth(i - (f[i - 1] as usize) - 2) - .unwrap() == '(' - { - f[i] = f[i - 1] + 2 + f[i - (f[i - 1] as usize) - 2]; - } - ans = ans.max(f[i]); - } - } - ans - } + return max_length; } ``` @@ -401,10 +359,30 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {string} s + * @return {number} + */ +var longestValidParentheses = function (s) { + let ans = 0; + const stack = [-1]; + for (i = 0; i < s.length; i++) { + if (s.charAt(i) === '(') { + stack.push(i); + } else { + stack.pop(); + if (stack.length === 0) { + stack.push(i); + } else { + ans = Math.max(ans, i - stack[stack.length - 1]); + } + } + } + return ans; +}; ``` + + diff --git a/solution/0000-0099/0032.Longest Valid Parentheses/README_EN.md b/solution/0000-0099/0032.Longest Valid Parentheses/README_EN.md index cea5ab48538eb..d99e0e88fe81f 100644 --- a/solution/0000-0099/0032.Longest Valid Parentheses/README_EN.md +++ b/solution/0000-0099/0032.Longest Valid Parentheses/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i]$ to be the length of the longest valid parentheses that ends with $s[i-1]$, and the answer is $max(f[i])$. @@ -67,25 +67,8 @@ Finally, we only need to return $max(f)$. The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string. -**Solution 2: Using Stack** - -- Maintain a stack to store the indices of left parentheses. Initialize the bottom element of the stack with the value -1 to facilitate the calculation of the length of valid parentheses. -- Iterate through each element of the string: - - If the character is a left parenthesis, push the index of the character onto the stack. - - If the character is a right parenthesis, pop an element from the stack to represent that we have found a valid pair of parentheses. - - If the stack is empty, it means we couldn't find a left parenthesis to match the right parenthesis. In this case, push the index of the character as a new starting point. - - If the stack is not empty, calculate the length of the valid parentheses and update it. - -Summary: - -The key to this algorithm is to maintain a stack to store the indices of left parentheses and then update the length of the valid substring of parentheses by pushing and popping elements. - -The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string. - -### **Python3** - ```python class Solution: def longestValidParentheses(self, s: str) -> int: @@ -102,25 +85,6 @@ class Solution: return max(f) ``` -```python -class Solution: - def longestValidParentheses(self, s: str) -> int: - stack = [-1] - ans = 0 - for i in range(len(s)): - if s[i] == '(': - stack.append(i) - else: - stack.pop() - if not stack: - stack.append(i) - else: - ans = max(ans, i - stack[-1]) - return ans -``` - -### **Java** - ```java class Solution { public int longestValidParentheses(String s) { @@ -145,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +133,6 @@ public: }; ``` -### **Go** - ```go func longestValidParentheses(s string) int { n := len(s) @@ -190,56 +150,6 @@ func longestValidParentheses(s string) int { } ``` -```go -func longestValidParentheses(s string) int { - ans := 0 - stack := []int{-1} - for i, v := range s { - if v == '(' { - stack = append(stack, i) - } else { - stack = stack[:len(stack)-1] - if len(stack) == 0 { - stack = append(stack, i) - } else { - if ans < i-stack[len(stack)-1] { - ans = i - stack[len(stack)-1] - } - } - } - } - return ans -} -``` - -### **C#** - -```cs -public class Solution { - public int LongestValidParentheses(string s) { - int n = s.Length; - int[] f = new int[n + 1]; - int ans = 0; - for (int i = 2; i <= n; ++i) { - if (s[i - 1] == ')') { - if (s[i - 2] == '(') { - f[i] = f[i - 2] + 2; - } else { - int j = i - f[i - 1] - 1; - if (j > 0 && s[j - 1] == '(') { - f[i] = f[i - 1] + 2 + f[j - 1]; - } - } - ans = Math.Max(ans, f[i]); - } - } - return ans; - } -} -``` - -### **TypeScript** - ```ts function longestValidParentheses(s: string): number { const n = s.length; @@ -260,30 +170,42 @@ function longestValidParentheses(s: string): number { } ``` -```ts -function longestValidParentheses(s: string): number { - let max_length: number = 0; - const stack: number[] = [-1]; - for (let i = 0; i < s.length; i++) { - if (s.charAt(i) == '(') { - stack.push(i); - } else { - stack.pop(); - - if (stack.length === 0) { - stack.push(i); - } else { - max_length = Math.max(max_length, i - stack[stack.length - 1]); +```rust +impl Solution { + pub fn longest_valid_parentheses(s: String) -> i32 { + let mut ans = 0; + let mut f = vec![0; s.len() + 1]; + for i in 2..=s.len() { + if + s + .chars() + .nth(i - 1) + .unwrap() == ')' + { + if + s + .chars() + .nth(i - 2) + .unwrap() == '(' + { + f[i] = f[i - 2] + 2; + } else if + (i as i32) - f[i - 1] - 1 > 0 && + s + .chars() + .nth(i - (f[i - 1] as usize) - 2) + .unwrap() == '(' + { + f[i] = f[i - 1] + 2 + f[i - (f[i - 1] as usize) - 2]; + } + ans = ans.max(f[i]); } } + ans } - - return max_length; } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -308,65 +230,107 @@ var longestValidParentheses = function (s) { }; ``` -```js -/** - * @param {string} s - * @return {number} - */ -var longestValidParentheses = function (s) { - let ans = 0; - const stack = [-1]; - for (i = 0; i < s.length; i++) { - if (s.charAt(i) === '(') { +```cs +public class Solution { + public int LongestValidParentheses(string s) { + int n = s.Length; + int[] f = new int[n + 1]; + int ans = 0; + for (int i = 2; i <= n; ++i) { + if (s[i - 1] == ')') { + if (s[i - 2] == '(') { + f[i] = f[i - 2] + 2; + } else { + int j = i - f[i - 1] - 1; + if (j > 0 && s[j - 1] == '(') { + f[i] = f[i - 1] + 2 + f[j - 1]; + } + } + ans = Math.Max(ans, f[i]); + } + } + return ans; + } +} +``` + + + +### Solution 2: Using Stack + +- Maintain a stack to store the indices of left parentheses. Initialize the bottom element of the stack with the value -1 to facilitate the calculation of the length of valid parentheses. +- Iterate through each element of the string: + - If the character is a left parenthesis, push the index of the character onto the stack. + - If the character is a right parenthesis, pop an element from the stack to represent that we have found a valid pair of parentheses. + - If the stack is empty, it means we couldn't find a left parenthesis to match the right parenthesis. In this case, push the index of the character as a new starting point. + - If the stack is not empty, calculate the length of the valid parentheses and update it. + +Summary: + +The key to this algorithm is to maintain a stack to store the indices of left parentheses and then update the length of the valid substring of parentheses by pushing and popping elements. + +The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string. + + + +```python +class Solution: + def longestValidParentheses(self, s: str) -> int: + stack = [-1] + ans = 0 + for i in range(len(s)): + if s[i] == '(': + stack.append(i) + else: + stack.pop() + if not stack: + stack.append(i) + else: + ans = max(ans, i - stack[-1]) + return ans +``` + +```go +func longestValidParentheses(s string) int { + ans := 0 + stack := []int{-1} + for i, v := range s { + if v == '(' { + stack = append(stack, i) + } else { + stack = stack[:len(stack)-1] + if len(stack) == 0 { + stack = append(stack, i) + } else { + if ans < i-stack[len(stack)-1] { + ans = i - stack[len(stack)-1] + } + } + } + } + return ans +} +``` + +```ts +function longestValidParentheses(s: string): number { + let max_length: number = 0; + const stack: number[] = [-1]; + for (let i = 0; i < s.length; i++) { + if (s.charAt(i) == '(') { stack.push(i); } else { stack.pop(); + if (stack.length === 0) { stack.push(i); } else { - ans = Math.max(ans, i - stack[stack.length - 1]); + max_length = Math.max(max_length, i - stack[stack.length - 1]); } } } - return ans; -}; -``` - -### **Rust** -```rust -impl Solution { - pub fn longest_valid_parentheses(s: String) -> i32 { - let mut ans = 0; - let mut f = vec![0; s.len() + 1]; - for i in 2..=s.len() { - if - s - .chars() - .nth(i - 1) - .unwrap() == ')' - { - if - s - .chars() - .nth(i - 2) - .unwrap() == '(' - { - f[i] = f[i - 2] + 2; - } else if - (i as i32) - f[i - 1] - 1 > 0 && - s - .chars() - .nth(i - (f[i - 1] as usize) - 2) - .unwrap() == '(' - { - f[i] = f[i - 1] + 2 + f[i - (f[i - 1] as usize) - 2]; - } - ans = ans.max(f[i]); - } - } - ans - } + return max_length; } ``` @@ -392,10 +356,30 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {string} s + * @return {number} + */ +var longestValidParentheses = function (s) { + let ans = 0; + const stack = [-1]; + for (i = 0; i < s.length; i++) { + if (s.charAt(i) === '(') { + stack.push(i); + } else { + stack.pop(); + if (stack.length === 0) { + stack.push(i); + } else { + ans = Math.max(ans, i - stack[stack.length - 1]); + } + } + } + return ans; +}; ``` + + diff --git a/solution/0000-0099/0033.Search in Rotated Sorted Array/README.md b/solution/0000-0099/0033.Search in Rotated Sorted Array/README.md index abbaba1344372..fed9002636b49 100644 --- a/solution/0000-0099/0033.Search in Rotated Sorted Array/README.md +++ b/solution/0000-0099/0033.Search in Rotated Sorted Array/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们使用二分,将数组分割成 $[left,.. mid]$, $[mid + 1,.. right]$ 两部分,这时候可以发现,其中有一部分一定是有序的。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def search(self, nums: List[int], target: int) -> int: @@ -95,10 +89,6 @@ class Solution: return left if nums[left] == target else -1 ``` -### **Java** - - - ```java class Solution { public int search(int[] nums, int target) { @@ -125,10 +115,6 @@ class Solution { } ``` -### **C++** - - - ```cpp class Solution { public: @@ -154,8 +140,6 @@ public: }; ``` -### **Go** - ```go func search(nums []int, target int) int { n := len(nums) @@ -183,15 +167,8 @@ func search(nums []int, target int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} target - * @return {number} - */ -var search = function (nums, target) { +```ts +function search(nums: number[], target: number): number { const n = nums.length; let left = 0, right = n - 1; @@ -212,11 +189,9 @@ var search = function (nums, target) { } } return nums[left] == target ? left : -1; -}; +} ``` -### **Rust** - ```rust impl Solution { pub fn search(nums: Vec, target: i32) -> i32 { @@ -247,10 +222,13 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function search(nums: number[], target: number): number { +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function (nums, target) { const n = nums.length; let left = 0, right = n - 1; @@ -271,13 +249,9 @@ function search(nums: number[], target: number): number { } } return nums[left] == target ? left : -1; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0000-0099/0033.Search in Rotated Sorted Array/README_EN.md b/solution/0000-0099/0033.Search in Rotated Sorted Array/README_EN.md index 9a672fb77866d..63e53167791d3 100644 --- a/solution/0000-0099/0033.Search in Rotated Sorted Array/README_EN.md +++ b/solution/0000-0099/0033.Search in Rotated Sorted Array/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search We use binary search to divide the array into two parts, $[left,.. mid]$ and $[mid + 1,.. right]$. At this point, we can find that one part must be sorted. @@ -55,8 +55,6 @@ The time complexity is $O(\log n)$, where $n$ is the length of the array $nums$. -### **Python3** - ```python class Solution: def search(self, nums: List[int], target: int) -> int: @@ -77,8 +75,6 @@ class Solution: return left if nums[left] == target else -1 ``` -### **Java** - ```java class Solution { public int search(int[] nums, int target) { @@ -105,10 +101,6 @@ class Solution { } ``` -### **C++** - - - ```cpp class Solution { public: @@ -134,8 +126,6 @@ public: }; ``` -### **Go** - ```go func search(nums []int, target int) int { n := len(nums) @@ -163,15 +153,8 @@ func search(nums []int, target int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} target - * @return {number} - */ -var search = function (nums, target) { +```ts +function search(nums: number[], target: number): number { const n = nums.length; let left = 0, right = n - 1; @@ -192,11 +175,9 @@ var search = function (nums, target) { } } return nums[left] == target ? left : -1; -}; +} ``` -### **Rust** - ```rust impl Solution { pub fn search(nums: Vec, target: i32) -> i32 { @@ -227,10 +208,13 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function search(nums: number[], target: number): number { +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function (nums, target) { const n = nums.length; let left = 0, right = n - 1; @@ -251,13 +235,9 @@ function search(nums: number[], target: number): number { } } return nums[left] == target ? left : -1; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/README.md b/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/README.md index 1815b5d0d27de..f6b59b9d8f1be 100644 --- a/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/README.md +++ b/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们可以进行两次二分查找,分别查找出左边界和右边界。 @@ -106,10 +104,6 @@ int search(int left, int right) { -### **Python3** - - - ```python class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: @@ -118,10 +112,6 @@ class Solution: return [-1, -1] if l == r else [l, r - 1] ``` -### **Java** - - - ```java class Solution { public int[] searchRange(int[] nums, int target) { @@ -145,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +147,6 @@ public: }; ``` -### **Go** - ```go func searchRange(nums []int, target int) []int { l := sort.SearchInts(nums, target) @@ -172,7 +158,25 @@ func searchRange(nums []int, target int) []int { } ``` -### **Rust** +```ts +function searchRange(nums: number[], target: number): number[] { + const search = (x: number): number => { + let [left, right] = [0, nums.length]; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + }; + const l = search(target); + const r = search(target + 1); + return l === r ? [-1, -1] : [l, r - 1]; +} +``` ```rust impl Solution { @@ -201,30 +205,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function searchRange(nums: number[], target: number): number[] { - const search = (x: number): number => { - let [left, right] = [0, nums.length]; - while (left < right) { - const mid = (left + right) >> 1; - if (nums[mid] >= x) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - }; - const l = search(target); - const r = search(target + 1); - return l === r ? [-1, -1] : [l, r - 1]; -} -``` - -### **JavaScript** - ```js /** * @param {number[]} nums @@ -251,10 +231,6 @@ var searchRange = function (nums, target) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/README_EN.md b/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/README_EN.md index 0c0b1f8e18cec..7347d6e58fe2f 100644 --- a/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/README_EN.md +++ b/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/README_EN.md @@ -33,7 +33,7 @@ ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search We can perform binary search twice to find the left and right boundaries respectively. @@ -92,8 +92,6 @@ Note that the advantage of these two templates is that they always keep the answ -### **Python3** - ```python class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: @@ -102,8 +100,6 @@ class Solution: return [-1, -1] if l == r else [l, r - 1] ``` -### **Java** - ```java class Solution { public int[] searchRange(int[] nums, int target) { @@ -127,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +135,6 @@ public: }; ``` -### **Go** - ```go func searchRange(nums []int, target int) []int { l := sort.SearchInts(nums, target) @@ -154,7 +146,25 @@ func searchRange(nums []int, target int) []int { } ``` -### **Rust** +```ts +function searchRange(nums: number[], target: number): number[] { + const search = (x: number): number => { + let [left, right] = [0, nums.length]; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + }; + const l = search(target); + const r = search(target + 1); + return l === r ? [-1, -1] : [l, r - 1]; +} +``` ```rust impl Solution { @@ -183,30 +193,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function searchRange(nums: number[], target: number): number[] { - const search = (x: number): number => { - let [left, right] = [0, nums.length]; - while (left < right) { - const mid = (left + right) >> 1; - if (nums[mid] >= x) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - }; - const l = search(target); - const r = search(target + 1); - return l === r ? [-1, -1] : [l, r - 1]; -} -``` - -### **JavaScript** - ```js /** * @param {number[]} nums @@ -233,10 +219,6 @@ var searchRange = function (nums, target) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0035.Search Insert Position/README.md b/solution/0000-0099/0035.Search Insert Position/README.md index 2fb3ef5106c07..d72d9ba9fe76b 100644 --- a/solution/0000-0099/0035.Search Insert Position/README.md +++ b/solution/0000-0099/0035.Search Insert Position/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 由于 $nums$ 数组已经有序,因此我们可以使用二分查找的方法找到目标值 $target$ 的插入位置。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def searchInsert(self, nums: List[int], target: int) -> int: @@ -73,16 +67,6 @@ class Solution: return left ``` -```python -class Solution: - def searchInsert(self, nums: List[int], target: int) -> int: - return bisect_left(nums, target) -``` - -### **Java** - - - ```java class Solution { public int searchInsert(int[] nums, int target) { @@ -100,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,17 +101,6 @@ public: }; ``` -```cpp -class Solution { -public: - int searchInsert(vector& nums, int target) { - return lower_bound(nums.begin(), nums.end(), target) - nums.begin(); - } -}; -``` - -### **Go** - ```go func searchInsert(nums []int, target int) int { left, right := 0, len(nums) @@ -145,14 +116,31 @@ func searchInsert(nums []int, target int) int { } ``` -```go -func searchInsert(nums []int, target int) int { - return sort.SearchInts(nums, target) +```rust +use std::cmp::Ordering; +impl Solution { + pub fn search_insert(nums: Vec, target: i32) -> i32 { + let mut left = 0; + let mut right = nums.len(); + while left < right { + let mid = left + (right - left) / 2; + match nums[mid].cmp(&target) { + Ordering::Less => { + left = mid + 1; + } + Ordering::Greater => { + right = mid; + } + Ordering::Equal => { + return mid as i32; + } + } + } + left as i32 + } } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -174,37 +162,33 @@ var searchInsert = function (nums, target) { }; ``` -### **Rust** + -```rust -use std::cmp::Ordering; -impl Solution { - pub fn search_insert(nums: Vec, target: i32) -> i32 { - let mut left = 0; - let mut right = nums.len(); - while left < right { - let mid = left + (right - left) / 2; - match nums[mid].cmp(&target) { - Ordering::Less => { - left = mid + 1; - } - Ordering::Greater => { - right = mid; - } - Ordering::Equal => { - return mid as i32; - } - } - } - left as i32 - } -} -``` +### 方法二 -### **...** + +```python +class Solution: + def searchInsert(self, nums: List[int], target: int) -> int: + return bisect_left(nums, target) ``` +```cpp +class Solution { +public: + int searchInsert(vector& nums, int target) { + return lower_bound(nums.begin(), nums.end(), target) - nums.begin(); + } +}; +``` + +```go +func searchInsert(nums []int, target int) int { + return sort.SearchInts(nums, target) +} ``` + + diff --git a/solution/0000-0099/0035.Search Insert Position/README_EN.md b/solution/0000-0099/0035.Search Insert Position/README_EN.md index 6452d4e9e86f7..e5d7ddd99639a 100644 --- a/solution/0000-0099/0035.Search Insert Position/README_EN.md +++ b/solution/0000-0099/0035.Search Insert Position/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search Since the array $nums$ is already sorted, we can use the binary search method to find the insertion position of the target value $target$. @@ -50,8 +50,6 @@ The time complexity is $O(\log n)$, and the space complexity is $O(1)$. Here, $n -### **Python3** - ```python class Solution: def searchInsert(self, nums: List[int], target: int) -> int: @@ -65,14 +63,6 @@ class Solution: return left ``` -```python -class Solution: - def searchInsert(self, nums: List[int], target: int) -> int: - return bisect_left(nums, target) -``` - -### **Java** - ```java class Solution { public int searchInsert(int[] nums, int target) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,17 +97,6 @@ public: }; ``` -```cpp -class Solution { -public: - int searchInsert(vector& nums, int target) { - return lower_bound(nums.begin(), nums.end(), target) - nums.begin(); - } -}; -``` - -### **Go** - ```go func searchInsert(nums []int, target int) int { left, right := 0, len(nums) @@ -135,14 +112,31 @@ func searchInsert(nums []int, target int) int { } ``` -```go -func searchInsert(nums []int, target int) int { - return sort.SearchInts(nums, target) +```rust +use std::cmp::Ordering; +impl Solution { + pub fn search_insert(nums: Vec, target: i32) -> i32 { + let mut left = 0; + let mut right = nums.len(); + while left < right { + let mid = left + (right - left) / 2; + match nums[mid].cmp(&target) { + Ordering::Less => { + left = mid + 1; + } + Ordering::Greater => { + right = mid; + } + Ordering::Equal => { + return mid as i32; + } + } + } + left as i32 + } } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -164,37 +158,33 @@ var searchInsert = function (nums, target) { }; ``` -### **Rust** + -```rust -use std::cmp::Ordering; -impl Solution { - pub fn search_insert(nums: Vec, target: i32) -> i32 { - let mut left = 0; - let mut right = nums.len(); - while left < right { - let mid = left + (right - left) / 2; - match nums[mid].cmp(&target) { - Ordering::Less => { - left = mid + 1; - } - Ordering::Greater => { - right = mid; - } - Ordering::Equal => { - return mid as i32; - } - } - } - left as i32 - } -} -``` +### Solution 2 -### **...** + +```python +class Solution: + def searchInsert(self, nums: List[int], target: int) -> int: + return bisect_left(nums, target) +``` + +```cpp +class Solution { +public: + int searchInsert(vector& nums, int target) { + return lower_bound(nums.begin(), nums.end(), target) - nums.begin(); + } +}; ``` +```go +func searchInsert(nums []int, target int) int { + return sort.SearchInts(nums, target) +} ``` + + diff --git a/solution/0000-0099/0036.Valid Sudoku/README.md b/solution/0000-0099/0036.Valid Sudoku/README.md index 007d86e366afb..cff71d3df5f46 100644 --- a/solution/0000-0099/0036.Valid Sudoku/README.md +++ b/solution/0000-0099/0036.Valid Sudoku/README.md @@ -70,9 +70,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 有效的数独满足以下三个条件: @@ -86,10 +84,6 @@ -### **Python3** - - - ```python class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: @@ -111,10 +105,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean isValidSudoku(char[][] board) { @@ -142,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +158,6 @@ public: }; ``` -### **Go** - ```go func isValidSudoku(board [][]byte) bool { row, col, sub := [9][9]bool{}, [9][9]bool{}, [9][9]bool{} @@ -194,20 +180,20 @@ func isValidSudoku(board [][]byte) bool { } ``` -### **JavaScript** - -```js -/** - * @param {character[][]} board - * @return {boolean} - */ -var isValidSudoku = function (board) { - const row = [...Array(9)].map(() => Array(9).fill(false)); - const col = [...Array(9)].map(() => Array(9).fill(false)); - const sub = [...Array(9)].map(() => Array(9).fill(false)); +```ts +function isValidSudoku(board: string[][]): boolean { + const row: boolean[][] = Array.from({ length: 9 }, () => + Array.from({ length: 9 }, () => false), + ); + const col: boolean[][] = Array.from({ length: 9 }, () => + Array.from({ length: 9 }, () => false), + ); + const sub: boolean[][] = Array.from({ length: 9 }, () => + Array.from({ length: 9 }, () => false), + ); for (let i = 0; i < 9; ++i) { for (let j = 0; j < 9; ++j) { - const num = board[i][j].charCodeAt() - '1'.charCodeAt(); + const num = board[i][j].charCodeAt(0) - '1'.charCodeAt(0); if (num < 0 || num > 8) { continue; } @@ -221,25 +207,21 @@ var isValidSudoku = function (board) { } } return true; -}; +} ``` -### **TypeScript** - -```ts -function isValidSudoku(board: string[][]): boolean { - const row: boolean[][] = Array.from({ length: 9 }, () => - Array.from({ length: 9 }, () => false), - ); - const col: boolean[][] = Array.from({ length: 9 }, () => - Array.from({ length: 9 }, () => false), - ); - const sub: boolean[][] = Array.from({ length: 9 }, () => - Array.from({ length: 9 }, () => false), - ); +```js +/** + * @param {character[][]} board + * @return {boolean} + */ +var isValidSudoku = function (board) { + const row = [...Array(9)].map(() => Array(9).fill(false)); + const col = [...Array(9)].map(() => Array(9).fill(false)); + const sub = [...Array(9)].map(() => Array(9).fill(false)); for (let i = 0; i < 9; ++i) { for (let j = 0; j < 9; ++j) { - const num = board[i][j].charCodeAt(0) - '1'.charCodeAt(0); + const num = board[i][j].charCodeAt() - '1'.charCodeAt(); if (num < 0 || num > 8) { continue; } @@ -253,13 +235,9 @@ function isValidSudoku(board: string[][]): boolean { } } return true; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0000-0099/0036.Valid Sudoku/README_EN.md b/solution/0000-0099/0036.Valid Sudoku/README_EN.md index 9e0642a1a740b..fd283a279c97a 100644 --- a/solution/0000-0099/0036.Valid Sudoku/README_EN.md +++ b/solution/0000-0099/0036.Valid Sudoku/README_EN.md @@ -64,7 +64,7 @@ ## Solutions -**Solution 1: Traversal once** +### Solution 1: Traversal once The valid sudoku satisfies the following three conditions: @@ -78,8 +78,6 @@ The time complexity is $O(C)$ and the space complexity is $O(C)$, where $C$ is t -### **Python3** - ```python class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: @@ -101,8 +99,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean isValidSudoku(char[][] board) { @@ -130,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +152,6 @@ public: }; ``` -### **Go** - ```go func isValidSudoku(board [][]byte) bool { row, col, sub := [9][9]bool{}, [9][9]bool{}, [9][9]bool{} @@ -182,20 +174,20 @@ func isValidSudoku(board [][]byte) bool { } ``` -### **JavaScript** - -```js -/** - * @param {character[][]} board - * @return {boolean} - */ -var isValidSudoku = function (board) { - const row = [...Array(9)].map(() => Array(9).fill(false)); - const col = [...Array(9)].map(() => Array(9).fill(false)); - const sub = [...Array(9)].map(() => Array(9).fill(false)); +```ts +function isValidSudoku(board: string[][]): boolean { + const row: boolean[][] = Array.from({ length: 9 }, () => + Array.from({ length: 9 }, () => false), + ); + const col: boolean[][] = Array.from({ length: 9 }, () => + Array.from({ length: 9 }, () => false), + ); + const sub: boolean[][] = Array.from({ length: 9 }, () => + Array.from({ length: 9 }, () => false), + ); for (let i = 0; i < 9; ++i) { for (let j = 0; j < 9; ++j) { - const num = board[i][j].charCodeAt() - '1'.charCodeAt(); + const num = board[i][j].charCodeAt(0) - '1'.charCodeAt(0); if (num < 0 || num > 8) { continue; } @@ -209,25 +201,21 @@ var isValidSudoku = function (board) { } } return true; -}; +} ``` -### **TypeScript** - -```ts -function isValidSudoku(board: string[][]): boolean { - const row: boolean[][] = Array.from({ length: 9 }, () => - Array.from({ length: 9 }, () => false), - ); - const col: boolean[][] = Array.from({ length: 9 }, () => - Array.from({ length: 9 }, () => false), - ); - const sub: boolean[][] = Array.from({ length: 9 }, () => - Array.from({ length: 9 }, () => false), - ); +```js +/** + * @param {character[][]} board + * @return {boolean} + */ +var isValidSudoku = function (board) { + const row = [...Array(9)].map(() => Array(9).fill(false)); + const col = [...Array(9)].map(() => Array(9).fill(false)); + const sub = [...Array(9)].map(() => Array(9).fill(false)); for (let i = 0; i < 9; ++i) { for (let j = 0; j < 9; ++j) { - const num = board[i][j].charCodeAt(0) - '1'.charCodeAt(0); + const num = board[i][j].charCodeAt() - '1'.charCodeAt(); if (num < 0 || num > 8) { continue; } @@ -241,13 +229,9 @@ function isValidSudoku(board: string[][]): boolean { } } return true; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0000-0099/0037.Sudoku Solver/README.md b/solution/0000-0099/0037.Sudoku Solver/README.md index e1fb1e71daef7..65b175b2d803e 100644 --- a/solution/0000-0099/0037.Sudoku Solver/README.md +++ b/solution/0000-0099/0037.Sudoku Solver/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:回溯** +### 方法一:回溯 我们用数组 `row`、`col`、`box` 分别记录每一行、每一列、每个 3x3 宫格中数字是否出现过。如果数字 `i` 在第 `r` 行、第 `c` 列、第 `b` 个 3x3 宫格中出现过,那么 `row[r][i]`、`col[c][i]`、`box[b][i]` 都为 `true`。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def solveSudoku(self, board: List[List[str]]) -> None: @@ -98,10 +92,6 @@ class Solution: dfs(0) ``` -### **Java** - - - ```java class Solution { private boolean ok; @@ -147,8 +137,6 @@ class Solution { } ``` -### **C++** - ```cpp using pii = pair; @@ -193,8 +181,6 @@ public: }; ``` -### **Go** - ```go func solveSudoku(board [][]byte) { var row, col [9][9]bool @@ -234,10 +220,140 @@ func solveSudoku(board [][]byte) { } ``` -### **...** +```cs +public class Solution { + public void SolveSudoku(char[][] board) { + this.board = new ushort?[9,9]; + for (var i = 0; i < 9; ++i) + { + for (var j = 0; j < 9; ++j) + { + if (board[i][j] != '.') + { + this.board[i, j] = (ushort) (1 << (board[i][j] - '0' - 1)); + } + } + } -``` + if (SolveSudoku(0, 0)) + { + for (var i = 0; i < 9; ++i) + { + for (var j = 0; j < 9; ++j) + { + if (board[i][j] == '.') + { + board[i][j] = '0'; + while (this.board[i, j].Value != 0) + { + board[i][j] = (char)(board[i][j] + 1); + this.board[i, j] >>= 1; + } + } + } + } + } + } + + private ushort?[,] board; + + private bool ValidateHorizontalRule(int row) + { + ushort temp = 0; + for (var i = 0; i < 9; ++i) + { + if (board[row, i].HasValue) + { + if ((temp | board[row, i].Value) == temp) + { + return false; + } + temp |= board[row, i].Value; + } + } + return true; + } + + private bool ValidateVerticalRule(int column) + { + ushort temp = 0; + for (var i = 0; i < 9; ++i) + { + if (board[i, column].HasValue) + { + if ((temp | board[i, column].Value) == temp) + { + return false; + } + temp |= board[i, column].Value; + } + } + return true; + } + private bool ValidateBlockRule(int row, int column) + { + var startRow = row / 3 * 3; + var startColumn = column / 3 * 3; + ushort temp = 0; + for (var i = startRow; i < startRow + 3; ++i) + { + for (var j = startColumn; j < startColumn + 3; ++j) + { + if (board[i, j].HasValue) + { + if ((temp | board[i, j].Value) == temp) + { + return false; + } + temp |= board[i, j].Value; + } + } + } + return true; + } + + private bool SolveSudoku(int i, int j) + { + while (true) + { + if (j == 9) + { + ++i; + j = 0; + } + if (i == 9) + { + return true; + } + if (board[i, j].HasValue) + { + ++j; + } + else + { + break; + } + } + + ushort stop = 1 << 9; + for (ushort t = 1; t != stop; t <<= 1) + { + board[i, j] = t; + if (ValidateHorizontalRule(i) && ValidateVerticalRule(j) && ValidateBlockRule(i, j)) + { + if (SolveSudoku(i, j + 1)) + { + return true; + } + } + } + board[i, j] = null; + return false; + } +} ``` + + diff --git a/solution/0000-0099/0037.Sudoku Solver/README_EN.md b/solution/0000-0099/0037.Sudoku Solver/README_EN.md index 8601925ab6878..befb1d9e3390c 100644 --- a/solution/0000-0099/0037.Sudoku Solver/README_EN.md +++ b/solution/0000-0099/0037.Sudoku Solver/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Backtracking** +### Solution 1: Backtracking We use arrays `row`, `col`, and `box` to record whether a number has appeared in each row, each column, and each 3x3 grid respectively. If the number `i` has appeared in the `r`th row, the `c`th column, and the `b`th 3x3 grid, then `row[r][i]`, `col[c][i]`, and `box[b][i]` are all `true`. @@ -49,8 +49,6 @@ The time complexity is $O(9^{81})$, and the space complexity is $O(9^2)$. -### **Python3** - ```python class Solution: def solveSudoku(self, board: List[List[str]]) -> None: @@ -84,8 +82,6 @@ class Solution: dfs(0) ``` -### **Java** - ```java class Solution { private boolean ok; @@ -131,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp using pii = pair; @@ -177,8 +171,6 @@ public: }; ``` -### **Go** - ```go func solveSudoku(board [][]byte) { var row, col [9][9]bool @@ -218,10 +210,140 @@ func solveSudoku(board [][]byte) { } ``` -### **...** +```cs +public class Solution { + public void SolveSudoku(char[][] board) { + this.board = new ushort?[9,9]; + for (var i = 0; i < 9; ++i) + { + for (var j = 0; j < 9; ++j) + { + if (board[i][j] != '.') + { + this.board[i, j] = (ushort) (1 << (board[i][j] - '0' - 1)); + } + } + } -``` + if (SolveSudoku(0, 0)) + { + for (var i = 0; i < 9; ++i) + { + for (var j = 0; j < 9; ++j) + { + if (board[i][j] == '.') + { + board[i][j] = '0'; + while (this.board[i, j].Value != 0) + { + board[i][j] = (char)(board[i][j] + 1); + this.board[i, j] >>= 1; + } + } + } + } + } + } + + private ushort?[,] board; + + private bool ValidateHorizontalRule(int row) + { + ushort temp = 0; + for (var i = 0; i < 9; ++i) + { + if (board[row, i].HasValue) + { + if ((temp | board[row, i].Value) == temp) + { + return false; + } + temp |= board[row, i].Value; + } + } + return true; + } + private bool ValidateVerticalRule(int column) + { + ushort temp = 0; + for (var i = 0; i < 9; ++i) + { + if (board[i, column].HasValue) + { + if ((temp | board[i, column].Value) == temp) + { + return false; + } + temp |= board[i, column].Value; + } + } + return true; + } + + private bool ValidateBlockRule(int row, int column) + { + var startRow = row / 3 * 3; + var startColumn = column / 3 * 3; + ushort temp = 0; + for (var i = startRow; i < startRow + 3; ++i) + { + for (var j = startColumn; j < startColumn + 3; ++j) + { + if (board[i, j].HasValue) + { + if ((temp | board[i, j].Value) == temp) + { + return false; + } + temp |= board[i, j].Value; + } + } + } + return true; + } + + private bool SolveSudoku(int i, int j) + { + while (true) + { + if (j == 9) + { + ++i; + j = 0; + } + if (i == 9) + { + return true; + } + if (board[i, j].HasValue) + { + ++j; + } + else + { + break; + } + } + + ushort stop = 1 << 9; + for (ushort t = 1; t != stop; t <<= 1) + { + board[i, j] = t; + if (ValidateHorizontalRule(i) && ValidateVerticalRule(j) && ValidateBlockRule(i, j)) + { + if (SolveSudoku(i, j + 1)) + { + return true; + } + } + } + board[i, j] = null; + return false; + } +} ``` + + diff --git a/solution/0000-0099/0038.Count and Say/README.md b/solution/0000-0099/0038.Count and Say/README.md index 6da5072d3ee01..6bc02c6e5a510 100644 --- a/solution/0000-0099/0038.Count and Say/README.md +++ b/solution/0000-0099/0038.Count and Say/README.md @@ -71,28 +71,10 @@ countAndSay(4) = 读 "21" = 一 个 2 + 一 个 1 = "12" + "11" = "1211" ## 解法 -**方法一: 模拟** - -题目要求输出第 $n$ 项的外观序列,而第 $n$ 项是序列中第 $n-1$ 项的描述。所以我们遍历 $n-1$ 次,每次迭代用快慢指针 j 和 i,分别记录当前字符的位置以及下一个不等于当前字符的位置,更新上一项的序列为 $j-i$ 个当前字符。 - -时间复杂度: - -1. 外部循环迭代 `for _ in range(n - 1)`,这会执行 `n-1` 次。 -2. 在内部循环中,我们遍历了字符串`s`, 长度最大为上一项的长度。 -3. 内部循环嵌套循环执行了一些基本操作,如比较和字符串拼接,这些基本操作的复杂度可以视为 $O(1)$ 。 - -综合考虑,整体时间复杂度为 $O(n \times m)$, 其中 n 是要生成的序列的项数, m 是前一项的最大长度。 - -空间复杂度: $O(m)$, 其中 m 是前一项的最大长度。 - - +### 方法一 -### **Python3** - - - ```python class Solution: def countAndSay(self, n: int) -> str: @@ -111,10 +93,6 @@ class Solution: return s ``` -### **Java** - - - ```java class Solution { public String countAndSay(int n) { @@ -137,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +136,6 @@ public: }; ``` -### **Go** - ```go func countAndSay(n int) string { s := "1" @@ -183,75 +157,6 @@ func countAndSay(n int) string { } ``` -### **C#** - -```cs -using System.Text; -public class Solution { - public string CountAndSay(int n) { - var s = "1"; - while (n > 1) - { - var sb = new StringBuilder(); - var lastChar = '1'; - var count = 0; - foreach (var ch in s) - { - if (count > 0 && lastChar == ch) - { - ++count; - } - else - { - if (count > 0) - { - sb.Append(count); - sb.Append(lastChar); - } - lastChar = ch; - count = 1; - } - } - if (count > 0) - { - sb.Append(count); - sb.Append(lastChar); - } - s = sb.ToString(); - --n; - } - return s; - } -} -``` - -### **JavaScript** - -```js -const countAndSay = function (n) { - let s = '1'; - - for (let i = 2; i <= n; i++) { - let count = 1, - str = '', - len = s.length; - - for (let j = 0; j < len; j++) { - if (j < len - 1 && s[j] === s[j + 1]) { - count++; - } else { - str += `${count}${s[j]}`; - count = 1; - } - } - s = str; - } - return s; -}; -``` - -### **TypeScript** - ```ts function countAndSay(n: number): string { let s = '1'; @@ -274,8 +179,6 @@ function countAndSay(n: number): string { } ``` -### **Rust** - ```rust use std::iter::once; @@ -300,10 +203,69 @@ impl Solution { } ``` -### **...** +```js +const countAndSay = function (n) { + let s = '1'; + + for (let i = 2; i <= n; i++) { + let count = 1, + str = '', + len = s.length; + for (let j = 0; j < len; j++) { + if (j < len - 1 && s[j] === s[j + 1]) { + count++; + } else { + str += `${count}${s[j]}`; + count = 1; + } + } + s = str; + } + return s; +}; ``` +```cs +using System.Text; +public class Solution { + public string CountAndSay(int n) { + var s = "1"; + while (n > 1) + { + var sb = new StringBuilder(); + var lastChar = '1'; + var count = 0; + foreach (var ch in s) + { + if (count > 0 && lastChar == ch) + { + ++count; + } + else + { + if (count > 0) + { + sb.Append(count); + sb.Append(lastChar); + } + lastChar = ch; + count = 1; + } + } + if (count > 0) + { + sb.Append(count); + sb.Append(lastChar); + } + s = sb.ToString(); + --n; + } + return s; + } +} ``` + + diff --git a/solution/0000-0099/0038.Count and Say/README_EN.md b/solution/0000-0099/0038.Count and Say/README_EN.md index 5157477bb886a..b2de1bbe6e964 100644 --- a/solution/0000-0099/0038.Count and Say/README_EN.md +++ b/solution/0000-0099/0038.Count and Say/README_EN.md @@ -47,7 +47,7 @@ countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11& ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation The task requires outputting the appearance sequence of the $n$-th item, where the $n$-th item is the description of the $n-1$-th item in the sequence. Therefore, we iterate $n-1$ times. In each iteration, we use fast and slow pointers, denoted as j and i respectively, to record the current character's position and the position of the next character that is not equal to the current character. We then update the sequence of the previous item to be $j-i$ occurrences of the current character. @@ -63,8 +63,6 @@ Space Complexity: $O(m)$. -### **Python3** - ```python class Solution: def countAndSay(self, n: int) -> str: @@ -83,8 +81,6 @@ class Solution: return s ``` -### **Java** - ```java class Solution { public String countAndSay(int n) { @@ -107,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +124,6 @@ public: }; ``` -### **Go** - ```go func countAndSay(n int) string { s := "1" @@ -153,75 +145,6 @@ func countAndSay(n int) string { } ``` -### **C#** - -```cs -using System.Text; -public class Solution { - public string CountAndSay(int n) { - var s = "1"; - while (n > 1) - { - var sb = new StringBuilder(); - var lastChar = '1'; - var count = 0; - foreach (var ch in s) - { - if (count > 0 && lastChar == ch) - { - ++count; - } - else - { - if (count > 0) - { - sb.Append(count); - sb.Append(lastChar); - } - lastChar = ch; - count = 1; - } - } - if (count > 0) - { - sb.Append(count); - sb.Append(lastChar); - } - s = sb.ToString(); - --n; - } - return s; - } -} -``` - -### **JavaScript** - -```js -const countAndSay = function (n) { - let s = '1'; - - for (let i = 2; i <= n; i++) { - let count = 1, - str = '', - len = s.length; - - for (let j = 0; j < len; j++) { - if (j < len - 1 && s[j] === s[j + 1]) { - count++; - } else { - str += `${count}${s[j]}`; - count = 1; - } - } - s = str; - } - return s; -}; -``` - -### **TypeScript** - ```ts function countAndSay(n: number): string { let s = '1'; @@ -244,8 +167,6 @@ function countAndSay(n: number): string { } ``` -### **Rust** - ```rust use std::iter::once; @@ -270,10 +191,69 @@ impl Solution { } ``` -### **...** +```js +const countAndSay = function (n) { + let s = '1'; + for (let i = 2; i <= n; i++) { + let count = 1, + str = '', + len = s.length; + + for (let j = 0; j < len; j++) { + if (j < len - 1 && s[j] === s[j + 1]) { + count++; + } else { + str += `${count}${s[j]}`; + count = 1; + } + } + s = str; + } + return s; +}; ``` +```cs +using System.Text; +public class Solution { + public string CountAndSay(int n) { + var s = "1"; + while (n > 1) + { + var sb = new StringBuilder(); + var lastChar = '1'; + var count = 0; + foreach (var ch in s) + { + if (count > 0 && lastChar == ch) + { + ++count; + } + else + { + if (count > 0) + { + sb.Append(count); + sb.Append(lastChar); + } + lastChar = ch; + count = 1; + } + } + if (count > 0) + { + sb.Append(count); + sb.Append(lastChar); + } + s = sb.ToString(); + --n; + } + return s; + } +} ``` + + diff --git a/solution/0000-0099/0039.Combination Sum/README.md b/solution/0000-0099/0039.Combination Sum/README.md index 99dfdcfbdd70c..57bd3080816cc 100644 --- a/solution/0000-0099/0039.Combination Sum/README.md +++ b/solution/0000-0099/0039.Combination Sum/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:排序 + 剪枝 + 回溯(两种写法)** +### 方法一:排序 + 剪枝 + 回溯(两种写法) 我们可以先对数组进行排序,方便剪枝。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: @@ -99,31 +93,6 @@ class Solution: return ans ``` -```python -class Solution: - def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: - def dfs(i: int, s: int): - if s == 0: - ans.append(t[:]) - return - if i >= len(candidates) or s < candidates[i]: - return - dfs(i + 1, s) - t.append(candidates[i]) - dfs(i, s - candidates[i]) - t.pop() - - candidates.sort() - t = [] - ans = [] - dfs(0, target) - return ans -``` - -### **Java** - - - ```java class Solution { private List> ans = new ArrayList<>(); @@ -154,37 +123,6 @@ class Solution { } ``` -```java -class Solution { - private List> ans = new ArrayList<>(); - private List t = new ArrayList<>(); - private int[] candidates; - - public List> combinationSum(int[] candidates, int target) { - Arrays.sort(candidates); - this.candidates = candidates; - dfs(0, target); - return ans; - } - - private void dfs(int i, int s) { - if (s == 0) { - ans.add(new ArrayList(t)); - return; - } - if (i >= candidates.length || s < candidates[i]) { - return; - } - dfs(i + 1, s); - t.add(candidates[i]); - dfs(i, s - candidates[i]); - t.remove(t.size() - 1); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -212,34 +150,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector> combinationSum(vector& candidates, int target) { - sort(candidates.begin(), candidates.end()); - vector> ans; - vector t; - function dfs = [&](int i, int s) { - if (s == 0) { - ans.emplace_back(t); - return; - } - if (i >= candidates.size() || s < candidates[i]) { - return; - } - dfs(i + 1, s); - t.push_back(candidates[i]); - dfs(i, s - candidates[i]); - t.pop_back(); - }; - dfs(0, target); - return ans; - } -}; -``` - -### **Go** - ```go func combinationSum(candidates []int, target int) (ans [][]int) { sort.Ints(candidates) @@ -264,31 +174,6 @@ func combinationSum(candidates []int, target int) (ans [][]int) { } ``` -```go -func combinationSum(candidates []int, target int) (ans [][]int) { - sort.Ints(candidates) - t := []int{} - var dfs func(i, s int) - dfs = func(i, s int) { - if s == 0 { - ans = append(ans, slices.Clone(t)) - return - } - if i >= len(candidates) || s < candidates[i] { - return - } - dfs(i+1, s) - t = append(t, candidates[i]) - dfs(i, s-candidates[i]) - t = t[:len(t)-1] - } - dfs(0, target) - return -} -``` - -### **TypeScript** - ```ts function combinationSum(candidates: number[], target: number): number[][] { candidates.sort((a, b) => a - b); @@ -313,31 +198,6 @@ function combinationSum(candidates: number[], target: number): number[][] { } ``` -```ts -function combinationSum(candidates: number[], target: number): number[][] { - candidates.sort((a, b) => a - b); - const ans: number[][] = []; - const t: number[] = []; - const dfs = (i: number, s: number) => { - if (s === 0) { - ans.push(t.slice()); - return; - } - if (i >= candidates.length || s < candidates[i]) { - return; - } - dfs(i + 1, s); - t.push(candidates[i]); - dfs(i, s - candidates[i]); - t.pop(); - }; - dfs(0, target); - return ans; -} -``` - -### **Rust** - ```rust impl Solution { fn dfs(i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { @@ -364,33 +224,6 @@ impl Solution { } ``` -```rust -impl Solution { - fn dfs(i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { - if s == 0 { - ans.push(t.clone()); - return; - } - if i >= candidates.len() || s < candidates[i] { - return; - } - Self::dfs(i + 1, s, candidates, t, ans); - t.push(candidates[i]); - Self::dfs(i, s - candidates[i], candidates, t, ans); - t.pop(); - } - - pub fn combination_sum(mut candidates: Vec, target: i32) -> Vec> { - candidates.sort(); - let mut ans = Vec::new(); - Self::dfs(0, target, &candidates, &mut vec![], &mut ans); - ans - } -} -``` - -### **C#** - ```cs public class Solution { private List> ans = new List>(); @@ -421,6 +254,159 @@ public class Solution { } ``` + + +### 方法二 + + + +```python +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + def dfs(i: int, s: int): + if s == 0: + ans.append(t[:]) + return + if i >= len(candidates) or s < candidates[i]: + return + dfs(i + 1, s) + t.append(candidates[i]) + dfs(i, s - candidates[i]) + t.pop() + + candidates.sort() + t = [] + ans = [] + dfs(0, target) + return ans +``` + +```java +class Solution { + private List> ans = new ArrayList<>(); + private List t = new ArrayList<>(); + private int[] candidates; + + public List> combinationSum(int[] candidates, int target) { + Arrays.sort(candidates); + this.candidates = candidates; + dfs(0, target); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + ans.add(new ArrayList(t)); + return; + } + if (i >= candidates.length || s < candidates[i]) { + return; + } + dfs(i + 1, s); + t.add(candidates[i]); + dfs(i, s - candidates[i]); + t.remove(t.size() - 1); + } +} +``` + +```cpp +class Solution { +public: + vector> combinationSum(vector& candidates, int target) { + sort(candidates.begin(), candidates.end()); + vector> ans; + vector t; + function dfs = [&](int i, int s) { + if (s == 0) { + ans.emplace_back(t); + return; + } + if (i >= candidates.size() || s < candidates[i]) { + return; + } + dfs(i + 1, s); + t.push_back(candidates[i]); + dfs(i, s - candidates[i]); + t.pop_back(); + }; + dfs(0, target); + return ans; + } +}; +``` + +```go +func combinationSum(candidates []int, target int) (ans [][]int) { + sort.Ints(candidates) + t := []int{} + var dfs func(i, s int) + dfs = func(i, s int) { + if s == 0 { + ans = append(ans, slices.Clone(t)) + return + } + if i >= len(candidates) || s < candidates[i] { + return + } + dfs(i+1, s) + t = append(t, candidates[i]) + dfs(i, s-candidates[i]) + t = t[:len(t)-1] + } + dfs(0, target) + return +} +``` + +```ts +function combinationSum(candidates: number[], target: number): number[][] { + candidates.sort((a, b) => a - b); + const ans: number[][] = []; + const t: number[] = []; + const dfs = (i: number, s: number) => { + if (s === 0) { + ans.push(t.slice()); + return; + } + if (i >= candidates.length || s < candidates[i]) { + return; + } + dfs(i + 1, s); + t.push(candidates[i]); + dfs(i, s - candidates[i]); + t.pop(); + }; + dfs(0, target); + return ans; +} +``` + +```rust +impl Solution { + fn dfs(i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { + if s == 0 { + ans.push(t.clone()); + return; + } + if i >= candidates.len() || s < candidates[i] { + return; + } + Self::dfs(i + 1, s, candidates, t, ans); + t.push(candidates[i]); + Self::dfs(i, s - candidates[i], candidates, t, ans); + t.pop(); + } + + pub fn combination_sum(mut candidates: Vec, target: i32) -> Vec> { + candidates.sort(); + let mut ans = Vec::new(); + Self::dfs(0, target, &candidates, &mut vec![], &mut ans); + ans + } +} +``` + ```cs public class Solution { private List> ans = new List>(); @@ -450,10 +436,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0039.Combination Sum/README_EN.md b/solution/0000-0099/0039.Combination Sum/README_EN.md index 9c95b0aa203b5..85c947a7e9067 100644 --- a/solution/0000-0099/0039.Combination Sum/README_EN.md +++ b/solution/0000-0099/0039.Combination Sum/README_EN.md @@ -48,7 +48,7 @@ These are the only two combinations. ## Solutions -**Solution 1: Sorting + Pruning + Backtracking (Two Implementations)** +### Solution 1: Sorting + Pruning + Backtracking (Two Implementations) We can first sort the array to facilitate pruning. @@ -70,8 +70,6 @@ Similar problems: -### **Python3** - ```python class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: @@ -93,29 +91,6 @@ class Solution: return ans ``` -```python -class Solution: - def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: - def dfs(i: int, s: int): - if s == 0: - ans.append(t[:]) - return - if i >= len(candidates) or s < candidates[i]: - return - dfs(i + 1, s) - t.append(candidates[i]) - dfs(i, s - candidates[i]) - t.pop() - - candidates.sort() - t = [] - ans = [] - dfs(0, target) - return ans -``` - -### **Java** - ```java class Solution { private List> ans = new ArrayList<>(); @@ -146,37 +121,6 @@ class Solution { } ``` -```java -class Solution { - private List> ans = new ArrayList<>(); - private List t = new ArrayList<>(); - private int[] candidates; - - public List> combinationSum(int[] candidates, int target) { - Arrays.sort(candidates); - this.candidates = candidates; - dfs(0, target); - return ans; - } - - private void dfs(int i, int s) { - if (s == 0) { - ans.add(new ArrayList(t)); - return; - } - if (i >= candidates.length || s < candidates[i]) { - return; - } - dfs(i + 1, s); - t.add(candidates[i]); - dfs(i, s - candidates[i]); - t.remove(t.size() - 1); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -204,34 +148,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector> combinationSum(vector& candidates, int target) { - sort(candidates.begin(), candidates.end()); - vector> ans; - vector t; - function dfs = [&](int i, int s) { - if (s == 0) { - ans.emplace_back(t); - return; - } - if (i >= candidates.size() || s < candidates[i]) { - return; - } - dfs(i + 1, s); - t.push_back(candidates[i]); - dfs(i, s - candidates[i]); - t.pop_back(); - }; - dfs(0, target); - return ans; - } -}; -``` - -### **Go** - ```go func combinationSum(candidates []int, target int) (ans [][]int) { sort.Ints(candidates) @@ -256,31 +172,6 @@ func combinationSum(candidates []int, target int) (ans [][]int) { } ``` -```go -func combinationSum(candidates []int, target int) (ans [][]int) { - sort.Ints(candidates) - t := []int{} - var dfs func(i, s int) - dfs = func(i, s int) { - if s == 0 { - ans = append(ans, slices.Clone(t)) - return - } - if i >= len(candidates) || s < candidates[i] { - return - } - dfs(i+1, s) - t = append(t, candidates[i]) - dfs(i, s-candidates[i]) - t = t[:len(t)-1] - } - dfs(0, target) - return -} -``` - -### **TypeScript** - ```ts function combinationSum(candidates: number[], target: number): number[][] { candidates.sort((a, b) => a - b); @@ -305,31 +196,6 @@ function combinationSum(candidates: number[], target: number): number[][] { } ``` -```ts -function combinationSum(candidates: number[], target: number): number[][] { - candidates.sort((a, b) => a - b); - const ans: number[][] = []; - const t: number[] = []; - const dfs = (i: number, s: number) => { - if (s === 0) { - ans.push(t.slice()); - return; - } - if (i >= candidates.length || s < candidates[i]) { - return; - } - dfs(i + 1, s); - t.push(candidates[i]); - dfs(i, s - candidates[i]); - t.pop(); - }; - dfs(0, target); - return ans; -} -``` - -### **Rust** - ```rust impl Solution { fn dfs(i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { @@ -356,33 +222,6 @@ impl Solution { } ``` -```rust -impl Solution { - fn dfs(i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { - if s == 0 { - ans.push(t.clone()); - return; - } - if i >= candidates.len() || s < candidates[i] { - return; - } - Self::dfs(i + 1, s, candidates, t, ans); - t.push(candidates[i]); - Self::dfs(i, s - candidates[i], candidates, t, ans); - t.pop(); - } - - pub fn combination_sum(mut candidates: Vec, target: i32) -> Vec> { - candidates.sort(); - let mut ans = Vec::new(); - Self::dfs(0, target, &candidates, &mut vec![], &mut ans); - ans - } -} -``` - -### **C#** - ```cs public class Solution { private List> ans = new List>(); @@ -413,6 +252,159 @@ public class Solution { } ``` + + +### Solution 2 + + + +```python +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + def dfs(i: int, s: int): + if s == 0: + ans.append(t[:]) + return + if i >= len(candidates) or s < candidates[i]: + return + dfs(i + 1, s) + t.append(candidates[i]) + dfs(i, s - candidates[i]) + t.pop() + + candidates.sort() + t = [] + ans = [] + dfs(0, target) + return ans +``` + +```java +class Solution { + private List> ans = new ArrayList<>(); + private List t = new ArrayList<>(); + private int[] candidates; + + public List> combinationSum(int[] candidates, int target) { + Arrays.sort(candidates); + this.candidates = candidates; + dfs(0, target); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + ans.add(new ArrayList(t)); + return; + } + if (i >= candidates.length || s < candidates[i]) { + return; + } + dfs(i + 1, s); + t.add(candidates[i]); + dfs(i, s - candidates[i]); + t.remove(t.size() - 1); + } +} +``` + +```cpp +class Solution { +public: + vector> combinationSum(vector& candidates, int target) { + sort(candidates.begin(), candidates.end()); + vector> ans; + vector t; + function dfs = [&](int i, int s) { + if (s == 0) { + ans.emplace_back(t); + return; + } + if (i >= candidates.size() || s < candidates[i]) { + return; + } + dfs(i + 1, s); + t.push_back(candidates[i]); + dfs(i, s - candidates[i]); + t.pop_back(); + }; + dfs(0, target); + return ans; + } +}; +``` + +```go +func combinationSum(candidates []int, target int) (ans [][]int) { + sort.Ints(candidates) + t := []int{} + var dfs func(i, s int) + dfs = func(i, s int) { + if s == 0 { + ans = append(ans, slices.Clone(t)) + return + } + if i >= len(candidates) || s < candidates[i] { + return + } + dfs(i+1, s) + t = append(t, candidates[i]) + dfs(i, s-candidates[i]) + t = t[:len(t)-1] + } + dfs(0, target) + return +} +``` + +```ts +function combinationSum(candidates: number[], target: number): number[][] { + candidates.sort((a, b) => a - b); + const ans: number[][] = []; + const t: number[] = []; + const dfs = (i: number, s: number) => { + if (s === 0) { + ans.push(t.slice()); + return; + } + if (i >= candidates.length || s < candidates[i]) { + return; + } + dfs(i + 1, s); + t.push(candidates[i]); + dfs(i, s - candidates[i]); + t.pop(); + }; + dfs(0, target); + return ans; +} +``` + +```rust +impl Solution { + fn dfs(i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { + if s == 0 { + ans.push(t.clone()); + return; + } + if i >= candidates.len() || s < candidates[i] { + return; + } + Self::dfs(i + 1, s, candidates, t, ans); + t.push(candidates[i]); + Self::dfs(i, s - candidates[i], candidates, t, ans); + t.pop(); + } + + pub fn combination_sum(mut candidates: Vec, target: i32) -> Vec> { + candidates.sort(); + let mut ans = Vec::new(); + Self::dfs(0, target, &candidates, &mut vec![], &mut ans); + ans + } +} +``` + ```cs public class Solution { private List> ans = new List>(); @@ -442,10 +434,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0040.Combination Sum II/README.md b/solution/0000-0099/0040.Combination Sum II/README.md index 53d15433dea76..28c0acb016080 100644 --- a/solution/0000-0099/0040.Combination Sum II/README.md +++ b/solution/0000-0099/0040.Combination Sum II/README.md @@ -48,7 +48,7 @@ ## 解法 -**方法一:排序 + 剪枝 + 回溯(两种写法)** +### 方法一:排序 + 剪枝 + 回溯(两种写法) 我们可以先对数组进行排序,方便剪枝以及跳过重复的数字。 @@ -72,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: @@ -99,34 +95,6 @@ class Solution: return ans ``` -```python -class Solution: - def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: - def dfs(i: int, s: int): - if s == 0: - ans.append(t[:]) - return - if i >= len(candidates) or s < candidates[i]: - return - x = candidates[i] - t.append(x) - dfs(i + 1, s - x) - t.pop() - while i < len(candidates) and candidates[i] == x: - i += 1 - dfs(i, s) - - candidates.sort() - ans = [] - t = [] - dfs(0, target) - return ans -``` - -### **Java** - - - ```java class Solution { private List> ans = new ArrayList<>(); @@ -160,41 +128,6 @@ class Solution { } ``` -```java -class Solution { - private List> ans = new ArrayList<>(); - private List t = new ArrayList<>(); - private int[] candidates; - - public List> combinationSum2(int[] candidates, int target) { - Arrays.sort(candidates); - this.candidates = candidates; - dfs(0, target); - return ans; - } - - private void dfs(int i, int s) { - if (s == 0) { - ans.add(new ArrayList<>(t)); - return; - } - if (i >= candidates.length || s < candidates[i]) { - return; - } - int x = candidates[i]; - t.add(x); - dfs(i + 1, s - x); - t.remove(t.size() - 1); - while (i < candidates.length && candidates[i] == x) { - ++i; - } - dfs(i, s); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -225,65 +158,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector> combinationSum2(vector& candidates, int target) { - sort(candidates.begin(), candidates.end()); - vector> ans; - vector t; - function dfs = [&](int i, int s) { - if (s == 0) { - ans.emplace_back(t); - return; - } - if (i >= candidates.size() || s < candidates[i]) { - return; - } - int x = candidates[i]; - t.emplace_back(x); - dfs(i + 1, s - x); - t.pop_back(); - while (i < candidates.size() && candidates[i] == x) { - ++i; - } - dfs(i, s); - }; - dfs(0, target); - return ans; - } -}; -``` - -### **Go** - -```go -func combinationSum2(candidates []int, target int) (ans [][]int) { - sort.Ints(candidates) - t := []int{} - var dfs func(i, s int) - dfs = func(i, s int) { - if s == 0 { - ans = append(ans, slices.Clone(t)) - return - } - if i >= len(candidates) || s < candidates[i] { - return - } - for j := i; j < len(candidates); j++ { - if j > i && candidates[j] == candidates[j-1] { - continue - } - t = append(t, candidates[j]) - dfs(j+1, s-candidates[j]) - t = t[:len(t)-1] - } - } - dfs(0, target) - return -} -``` - ```go func combinationSum2(candidates []int, target int) (ans [][]int) { sort.Ints(candidates) @@ -311,19 +185,12 @@ func combinationSum2(candidates []int, target int) (ans [][]int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} candidates - * @param {number} target - * @return {number[][]} - */ -var combinationSum2 = function (candidates, target) { +```ts +function combinationSum2(candidates: number[], target: number): number[][] { candidates.sort((a, b) => a - b); - const ans = []; - const t = []; - const dfs = (i, s) => { + const ans: number[][] = []; + const t: number[] = []; + const dfs = (i: number, s: number) => { if (s === 0) { ans.push(t.slice()); return; @@ -331,7 +198,7 @@ var combinationSum2 = function (candidates, target) { if (i >= candidates.length || s < candidates[i]) { return; } - for (let j = i; j < candidates.length; ++j) { + for (let j = i; j < candidates.length; j++) { if (j > i && candidates[j] === candidates[j - 1]) { continue; } @@ -342,7 +209,36 @@ var combinationSum2 = function (candidates, target) { }; dfs(0, target); return ans; -}; +} +``` + +```rust +impl Solution { + fn dfs(i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { + if s == 0 { + ans.push(t.clone()); + return; + } + if i >= candidates.len() || s < candidates[i] { + return; + } + for j in i..candidates.len() { + if j > i && candidates[j] == candidates[j - 1] { + continue; + } + t.push(candidates[j]); + Self::dfs(j + 1, s - candidates[j], candidates, t, ans); + t.pop(); + } + } + + pub fn combination_sum2(mut candidates: Vec, target: i32) -> Vec> { + candidates.sort(); + let mut ans = Vec::new(); + Self::dfs(0, target, &candidates, &mut vec![], &mut ans); + ans + } +} ``` ```js @@ -363,46 +259,170 @@ var combinationSum2 = function (candidates, target) { if (i >= candidates.length || s < candidates[i]) { return; } - const x = candidates[i]; - t.push(x); - dfs(i + 1, s - x); - t.pop(); - while (i < candidates.length && candidates[i] === x) { - ++i; + for (let j = i; j < candidates.length; ++j) { + if (j > i && candidates[j] === candidates[j - 1]) { + continue; + } + t.push(candidates[j]); + dfs(j + 1, s - candidates[j]); + t.pop(); } - dfs(i, s); }; dfs(0, target); return ans; }; ``` -### **TypeScript** +```cs +public class Solution { + private List> ans = new List>(); + private List t = new List(); + private int[] candidates; -```ts -function combinationSum2(candidates: number[], target: number): number[][] { - candidates.sort((a, b) => a - b); - const ans: number[][] = []; - const t: number[] = []; - const dfs = (i: number, s: number) => { - if (s === 0) { - ans.push(t.slice()); + public IList> CombinationSum2(int[] candidates, int target) { + Array.Sort(candidates); + this.candidates = candidates; + dfs(0, target); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + ans.Add(new List(t)); return; } - if (i >= candidates.length || s < candidates[i]) { + if (i >= candidates.Length || s < candidates[i]) { return; } - for (let j = i; j < candidates.length; j++) { - if (j > i && candidates[j] === candidates[j - 1]) { + for (int j = i; j < candidates.Length; ++j) { + if (j > i && candidates[j] == candidates[j - 1]) { continue; } - t.push(candidates[j]); + t.Add(candidates[j]); dfs(j + 1, s - candidates[j]); - t.pop(); + t.RemoveAt(t.Count - 1); } - }; - dfs(0, target); - return ans; + } +} +``` + + + +### 方法二 + + + +```python +class Solution: + def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: + def dfs(i: int, s: int): + if s == 0: + ans.append(t[:]) + return + if i >= len(candidates) or s < candidates[i]: + return + x = candidates[i] + t.append(x) + dfs(i + 1, s - x) + t.pop() + while i < len(candidates) and candidates[i] == x: + i += 1 + dfs(i, s) + + candidates.sort() + ans = [] + t = [] + dfs(0, target) + return ans +``` + +```java +class Solution { + private List> ans = new ArrayList<>(); + private List t = new ArrayList<>(); + private int[] candidates; + + public List> combinationSum2(int[] candidates, int target) { + Arrays.sort(candidates); + this.candidates = candidates; + dfs(0, target); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + ans.add(new ArrayList<>(t)); + return; + } + if (i >= candidates.length || s < candidates[i]) { + return; + } + int x = candidates[i]; + t.add(x); + dfs(i + 1, s - x); + t.remove(t.size() - 1); + while (i < candidates.length && candidates[i] == x) { + ++i; + } + dfs(i, s); + } +} +``` + +```cpp +class Solution { +public: + vector> combinationSum2(vector& candidates, int target) { + sort(candidates.begin(), candidates.end()); + vector> ans; + vector t; + function dfs = [&](int i, int s) { + if (s == 0) { + ans.emplace_back(t); + return; + } + if (i >= candidates.size() || s < candidates[i]) { + return; + } + int x = candidates[i]; + t.emplace_back(x); + dfs(i + 1, s - x); + t.pop_back(); + while (i < candidates.size() && candidates[i] == x) { + ++i; + } + dfs(i, s); + }; + dfs(0, target); + return ans; + } +}; +``` + +```go +func combinationSum2(candidates []int, target int) (ans [][]int) { + sort.Ints(candidates) + t := []int{} + var dfs func(i, s int) + dfs = func(i, s int) { + if s == 0 { + ans = append(ans, slices.Clone(t)) + return + } + if i >= len(candidates) || s < candidates[i] { + return + } + for j := i; j < len(candidates); j++ { + if j > i && candidates[j] == candidates[j-1] { + continue + } + t = append(t, candidates[j]) + dfs(j+1, s-candidates[j]) + t = t[:len(t)-1] + } + } + dfs(0, target) + return } ``` @@ -433,37 +453,6 @@ function combinationSum2(candidates: number[], target: number): number[][] { } ``` -### **Rust** - -```rust -impl Solution { - fn dfs(i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { - if s == 0 { - ans.push(t.clone()); - return; - } - if i >= candidates.len() || s < candidates[i] { - return; - } - for j in i..candidates.len() { - if j > i && candidates[j] == candidates[j - 1] { - continue; - } - t.push(candidates[j]); - Self::dfs(j + 1, s - candidates[j], candidates, t, ans); - t.pop(); - } - } - - pub fn combination_sum2(mut candidates: Vec, target: i32) -> Vec> { - candidates.sort(); - let mut ans = Vec::new(); - Self::dfs(0, target, &candidates, &mut vec![], &mut ans); - ans - } -} -``` - ```rust impl Solution { fn dfs(mut i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { @@ -493,39 +482,36 @@ impl Solution { } ``` -### **C#** - -```cs -public class Solution { - private List> ans = new List>(); - private List t = new List(); - private int[] candidates; - - public IList> CombinationSum2(int[] candidates, int target) { - Array.Sort(candidates); - this.candidates = candidates; - dfs(0, target); - return ans; - } - - private void dfs(int i, int s) { - if (s == 0) { - ans.Add(new List(t)); +```js +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum2 = function (candidates, target) { + candidates.sort((a, b) => a - b); + const ans = []; + const t = []; + const dfs = (i, s) => { + if (s === 0) { + ans.push(t.slice()); return; } - if (i >= candidates.Length || s < candidates[i]) { + if (i >= candidates.length || s < candidates[i]) { return; } - for (int j = i; j < candidates.Length; ++j) { - if (j > i && candidates[j] == candidates[j - 1]) { - continue; - } - t.Add(candidates[j]); - dfs(j + 1, s - candidates[j]); - t.RemoveAt(t.Count - 1); + const x = candidates[i]; + t.push(x); + dfs(i + 1, s - x); + t.pop(); + while (i < candidates.length && candidates[i] === x) { + ++i; } - } -} + dfs(i, s); + }; + dfs(0, target); + return ans; +}; ``` ```cs @@ -561,10 +547,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0040.Combination Sum II/README_EN.md b/solution/0000-0099/0040.Combination Sum II/README_EN.md index a7ad541c7da24..3ae4e055d70da 100644 --- a/solution/0000-0099/0040.Combination Sum II/README_EN.md +++ b/solution/0000-0099/0040.Combination Sum II/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Sorting + Pruning + Backtracking (Two Implementations)** +### Solution 1: Sorting + Pruning + Backtracking (Two Implementations) We can first sort the array to facilitate pruning and skipping duplicate numbers. @@ -68,8 +68,6 @@ Similar problems: -### **Python3** - ```python class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: @@ -93,32 +91,6 @@ class Solution: return ans ``` -```python -class Solution: - def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: - def dfs(i: int, s: int): - if s == 0: - ans.append(t[:]) - return - if i >= len(candidates) or s < candidates[i]: - return - x = candidates[i] - t.append(x) - dfs(i + 1, s - x) - t.pop() - while i < len(candidates) and candidates[i] == x: - i += 1 - dfs(i, s) - - candidates.sort() - ans = [] - t = [] - dfs(0, target) - return ans -``` - -### **Java** - ```java class Solution { private List> ans = new ArrayList<>(); @@ -152,41 +124,6 @@ class Solution { } ``` -```java -class Solution { - private List> ans = new ArrayList<>(); - private List t = new ArrayList<>(); - private int[] candidates; - - public List> combinationSum2(int[] candidates, int target) { - Arrays.sort(candidates); - this.candidates = candidates; - dfs(0, target); - return ans; - } - - private void dfs(int i, int s) { - if (s == 0) { - ans.add(new ArrayList<>(t)); - return; - } - if (i >= candidates.length || s < candidates[i]) { - return; - } - int x = candidates[i]; - t.add(x); - dfs(i + 1, s - x); - t.remove(t.size() - 1); - while (i < candidates.length && candidates[i] == x) { - ++i; - } - dfs(i, s); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -217,38 +154,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector> combinationSum2(vector& candidates, int target) { - sort(candidates.begin(), candidates.end()); - vector> ans; - vector t; - function dfs = [&](int i, int s) { - if (s == 0) { - ans.emplace_back(t); - return; - } - if (i >= candidates.size() || s < candidates[i]) { - return; - } - int x = candidates[i]; - t.emplace_back(x); - dfs(i + 1, s - x); - t.pop_back(); - while (i < candidates.size() && candidates[i] == x) { - ++i; - } - dfs(i, s); - }; - dfs(0, target); - return ans; - } -}; -``` - -### **Go** - ```go func combinationSum2(candidates []int, target int) (ans [][]int) { sort.Ints(candidates) @@ -276,46 +181,12 @@ func combinationSum2(candidates []int, target int) (ans [][]int) { } ``` -```go -func combinationSum2(candidates []int, target int) (ans [][]int) { - sort.Ints(candidates) - t := []int{} - var dfs func(i, s int) - dfs = func(i, s int) { - if s == 0 { - ans = append(ans, slices.Clone(t)) - return - } - if i >= len(candidates) || s < candidates[i] { - return - } - for j := i; j < len(candidates); j++ { - if j > i && candidates[j] == candidates[j-1] { - continue - } - t = append(t, candidates[j]) - dfs(j+1, s-candidates[j]) - t = t[:len(t)-1] - } - } - dfs(0, target) - return -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} candidates - * @param {number} target - * @return {number[][]} - */ -var combinationSum2 = function (candidates, target) { +```ts +function combinationSum2(candidates: number[], target: number): number[][] { candidates.sort((a, b) => a - b); - const ans = []; - const t = []; - const dfs = (i, s) => { + const ans: number[][] = []; + const t: number[] = []; + const dfs = (i: number, s: number) => { if (s === 0) { ans.push(t.slice()); return; @@ -323,7 +194,7 @@ var combinationSum2 = function (candidates, target) { if (i >= candidates.length || s < candidates[i]) { return; } - for (let j = i; j < candidates.length; ++j) { + for (let j = i; j < candidates.length; j++) { if (j > i && candidates[j] === candidates[j - 1]) { continue; } @@ -334,7 +205,36 @@ var combinationSum2 = function (candidates, target) { }; dfs(0, target); return ans; -}; +} +``` + +```rust +impl Solution { + fn dfs(i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { + if s == 0 { + ans.push(t.clone()); + return; + } + if i >= candidates.len() || s < candidates[i] { + return; + } + for j in i..candidates.len() { + if j > i && candidates[j] == candidates[j - 1] { + continue; + } + t.push(candidates[j]); + Self::dfs(j + 1, s - candidates[j], candidates, t, ans); + t.pop(); + } + } + + pub fn combination_sum2(mut candidates: Vec, target: i32) -> Vec> { + candidates.sort(); + let mut ans = Vec::new(); + Self::dfs(0, target, &candidates, &mut vec![], &mut ans); + ans + } +} ``` ```js @@ -355,46 +255,170 @@ var combinationSum2 = function (candidates, target) { if (i >= candidates.length || s < candidates[i]) { return; } - const x = candidates[i]; - t.push(x); - dfs(i + 1, s - x); - t.pop(); - while (i < candidates.length && candidates[i] === x) { - ++i; + for (let j = i; j < candidates.length; ++j) { + if (j > i && candidates[j] === candidates[j - 1]) { + continue; + } + t.push(candidates[j]); + dfs(j + 1, s - candidates[j]); + t.pop(); } - dfs(i, s); }; dfs(0, target); return ans; }; ``` -### **TypeScript** +```cs +public class Solution { + private List> ans = new List>(); + private List t = new List(); + private int[] candidates; -```ts -function combinationSum2(candidates: number[], target: number): number[][] { - candidates.sort((a, b) => a - b); - const ans: number[][] = []; - const t: number[] = []; - const dfs = (i: number, s: number) => { - if (s === 0) { - ans.push(t.slice()); + public IList> CombinationSum2(int[] candidates, int target) { + Array.Sort(candidates); + this.candidates = candidates; + dfs(0, target); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + ans.Add(new List(t)); return; } - if (i >= candidates.length || s < candidates[i]) { + if (i >= candidates.Length || s < candidates[i]) { return; } - for (let j = i; j < candidates.length; j++) { - if (j > i && candidates[j] === candidates[j - 1]) { + for (int j = i; j < candidates.Length; ++j) { + if (j > i && candidates[j] == candidates[j - 1]) { continue; } - t.push(candidates[j]); + t.Add(candidates[j]); dfs(j + 1, s - candidates[j]); - t.pop(); + t.RemoveAt(t.Count - 1); } - }; - dfs(0, target); - return ans; + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: + def dfs(i: int, s: int): + if s == 0: + ans.append(t[:]) + return + if i >= len(candidates) or s < candidates[i]: + return + x = candidates[i] + t.append(x) + dfs(i + 1, s - x) + t.pop() + while i < len(candidates) and candidates[i] == x: + i += 1 + dfs(i, s) + + candidates.sort() + ans = [] + t = [] + dfs(0, target) + return ans +``` + +```java +class Solution { + private List> ans = new ArrayList<>(); + private List t = new ArrayList<>(); + private int[] candidates; + + public List> combinationSum2(int[] candidates, int target) { + Arrays.sort(candidates); + this.candidates = candidates; + dfs(0, target); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + ans.add(new ArrayList<>(t)); + return; + } + if (i >= candidates.length || s < candidates[i]) { + return; + } + int x = candidates[i]; + t.add(x); + dfs(i + 1, s - x); + t.remove(t.size() - 1); + while (i < candidates.length && candidates[i] == x) { + ++i; + } + dfs(i, s); + } +} +``` + +```cpp +class Solution { +public: + vector> combinationSum2(vector& candidates, int target) { + sort(candidates.begin(), candidates.end()); + vector> ans; + vector t; + function dfs = [&](int i, int s) { + if (s == 0) { + ans.emplace_back(t); + return; + } + if (i >= candidates.size() || s < candidates[i]) { + return; + } + int x = candidates[i]; + t.emplace_back(x); + dfs(i + 1, s - x); + t.pop_back(); + while (i < candidates.size() && candidates[i] == x) { + ++i; + } + dfs(i, s); + }; + dfs(0, target); + return ans; + } +}; +``` + +```go +func combinationSum2(candidates []int, target int) (ans [][]int) { + sort.Ints(candidates) + t := []int{} + var dfs func(i, s int) + dfs = func(i, s int) { + if s == 0 { + ans = append(ans, slices.Clone(t)) + return + } + if i >= len(candidates) || s < candidates[i] { + return + } + for j := i; j < len(candidates); j++ { + if j > i && candidates[j] == candidates[j-1] { + continue + } + t = append(t, candidates[j]) + dfs(j+1, s-candidates[j]) + t = t[:len(t)-1] + } + } + dfs(0, target) + return } ``` @@ -425,37 +449,6 @@ function combinationSum2(candidates: number[], target: number): number[][] { } ``` -### **Rust** - -```rust -impl Solution { - fn dfs(i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { - if s == 0 { - ans.push(t.clone()); - return; - } - if i >= candidates.len() || s < candidates[i] { - return; - } - for j in i..candidates.len() { - if j > i && candidates[j] == candidates[j - 1] { - continue; - } - t.push(candidates[j]); - Self::dfs(j + 1, s - candidates[j], candidates, t, ans); - t.pop(); - } - } - - pub fn combination_sum2(mut candidates: Vec, target: i32) -> Vec> { - candidates.sort(); - let mut ans = Vec::new(); - Self::dfs(0, target, &candidates, &mut vec![], &mut ans); - ans - } -} -``` - ```rust impl Solution { fn dfs(mut i: usize, s: i32, candidates: &Vec, t: &mut Vec, ans: &mut Vec>) { @@ -485,39 +478,36 @@ impl Solution { } ``` -### **C#** - -```cs -public class Solution { - private List> ans = new List>(); - private List t = new List(); - private int[] candidates; - - public IList> CombinationSum2(int[] candidates, int target) { - Array.Sort(candidates); - this.candidates = candidates; - dfs(0, target); - return ans; - } - - private void dfs(int i, int s) { - if (s == 0) { - ans.Add(new List(t)); +```js +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum2 = function (candidates, target) { + candidates.sort((a, b) => a - b); + const ans = []; + const t = []; + const dfs = (i, s) => { + if (s === 0) { + ans.push(t.slice()); return; } - if (i >= candidates.Length || s < candidates[i]) { + if (i >= candidates.length || s < candidates[i]) { return; } - for (int j = i; j < candidates.Length; ++j) { - if (j > i && candidates[j] == candidates[j - 1]) { - continue; - } - t.Add(candidates[j]); - dfs(j + 1, s - candidates[j]); - t.RemoveAt(t.Count - 1); + const x = candidates[i]; + t.push(x); + dfs(i + 1, s - x); + t.pop(); + while (i < candidates.length && candidates[i] === x) { + ++i; } - } -} + dfs(i, s); + }; + dfs(0, target); + return ans; +}; ``` ```cs @@ -553,10 +543,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0041.First Missing Positive/README.md b/solution/0000-0099/0041.First Missing Positive/README.md index f84e524e46eea..2bfad8be50884 100644 --- a/solution/0000-0099/0041.First Missing Positive/README.md +++ b/solution/0000-0099/0041.First Missing Positive/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:原地交换** +### 方法一:原地交换 我们假设数组 $nums$ 长度为 $n$,那么最小的正整数一定在 $[1, .., n + 1]$ 之间。我们可以遍历数组,将数组中的每个数 $x$ 交换到它应该在的位置上,即 $x$ 应该在的位置为 $x - 1$。如果 $x$ 不在 $[1, n + 1]$ 之间,那么我们就不用管它。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def firstMissingPositive(self, nums: List[int]) -> int: @@ -75,10 +69,6 @@ class Solution: return n + 1 ``` -### **Java** - - - ```java class Solution { public int firstMissingPositive(int[] nums) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func firstMissingPositive(nums []int) int { n := len(nums) @@ -145,34 +131,47 @@ func firstMissingPositive(nums []int) int { } ``` -### **C** - -```c -int firstMissingPositive(int* nums, int numsSize) { - - int Max = nums[0], i, *Count; - - for (i = 1; i < numsSize; i++) { - Max = (Max < nums[i]) ? nums[i] : Max; - } - - Count = (int*) calloc(Max + 1, sizeof(int)); - for (i = 0; i < numsSize; i++) { - if (nums[i] > 0) { - Count[nums[i]]++; +```ts +function firstMissingPositive(nums: number[]): number { + const n = nums.length; + let i = 0; + while (i < n) { + const j = nums[i] - 1; + if (j === i || j < 0 || j >= n || nums[i] === nums[j]) { + i++; + } else { + [nums[i], nums[j]] = [nums[j], nums[i]]; } } - i = 1; - while (Count[i] != 0) { - i++; - } - - return i; + const res = nums.findIndex((v, i) => v !== i + 1); + return (res === -1 ? n : res) + 1; } ``` -### **C#** +```rust +impl Solution { + pub fn first_missing_positive(mut nums: Vec) -> i32 { + let n = nums.len(); + let mut i = 0; + while i < n { + let j = nums[i] - 1; + if (i as i32) == j || j < 0 || j >= (n as i32) || nums[i] == nums[j as usize] { + i += 1; + } else { + nums.swap(i, j as usize); + } + } + ( + nums + .iter() + .enumerate() + .position(|(i, &v)| (v as usize) != i + 1) + .unwrap_or(n) as i32 + ) + 1 + } +} +``` ```cs public class Solution { @@ -212,26 +211,37 @@ public class Solution { } ``` -### **TypeScript** +```c +int firstMissingPositive(int* nums, int numsSize) { + + int Max = nums[0], i, *Count; -```ts -function firstMissingPositive(nums: number[]): number { - const n = nums.length; - let i = 0; - while (i < n) { - const j = nums[i] - 1; - if (j === i || j < 0 || j >= n || nums[i] === nums[j]) { - i++; - } else { - [nums[i], nums[j]] = [nums[j], nums[i]]; + for (i = 1; i < numsSize; i++) { + Max = (Max < nums[i]) ? nums[i] : Max; + } + + Count = (int*) calloc(Max + 1, sizeof(int)); + for (i = 0; i < numsSize; i++) { + if (nums[i] > 0) { + Count[nums[i]]++; } } - const res = nums.findIndex((v, i) => v !== i + 1); - return (res === -1 ? n : res) + 1; + i = 1; + while (Count[i] != 0) { + i++; + } + + return i; } ``` + + +### 方法二 + + + ```ts function firstMissingPositive(nums: number[]): number { const set = new Set(nums); @@ -243,36 +253,6 @@ function firstMissingPositive(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn first_missing_positive(mut nums: Vec) -> i32 { - let n = nums.len(); - let mut i = 0; - while i < n { - let j = nums[i] - 1; - if (i as i32) == j || j < 0 || j >= (n as i32) || nums[i] == nums[j as usize] { - i += 1; - } else { - nums.swap(i, j as usize); - } - } - ( - nums - .iter() - .enumerate() - .position(|(i, &v)| (v as usize) != i + 1) - .unwrap_or(n) as i32 - ) + 1 - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0041.First Missing Positive/README_EN.md b/solution/0000-0099/0041.First Missing Positive/README_EN.md index 040ec35afebb4..98e2e24a4088b 100644 --- a/solution/0000-0099/0041.First Missing Positive/README_EN.md +++ b/solution/0000-0099/0041.First Missing Positive/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: In-place Swap** +### Solution 1: In-place Swap We assume the length of the array $nums$ is $n$, then the smallest positive integer must be in the range $[1, .., n + 1]$. We can traverse the array and swap each number $x$ to its correct position, that is, the position $x - 1$. If $x$ is not in the range $[1, n + 1]$, then we can ignore it. @@ -53,8 +53,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def firstMissingPositive(self, nums: List[int]) -> int: @@ -71,8 +69,6 @@ class Solution: return n + 1 ``` -### **Java** - ```java class Solution { public int firstMissingPositive(int[] nums) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +114,6 @@ public: }; ``` -### **Go** - ```go func firstMissingPositive(nums []int) int { n := len(nums) @@ -139,34 +131,47 @@ func firstMissingPositive(nums []int) int { } ``` -### **C** - -```c -int firstMissingPositive(int* nums, int numsSize) { - - int Max = nums[0], i, *Count; - - for (i = 1; i < numsSize; i++) { - Max = (Max < nums[i]) ? nums[i] : Max; - } - - Count = (int*) calloc(Max + 1, sizeof(int)); - for (i = 0; i < numsSize; i++) { - if (nums[i] > 0) { - Count[nums[i]]++; +```ts +function firstMissingPositive(nums: number[]): number { + const n = nums.length; + let i = 0; + while (i < n) { + const j = nums[i] - 1; + if (j === i || j < 0 || j >= n || nums[i] === nums[j]) { + i++; + } else { + [nums[i], nums[j]] = [nums[j], nums[i]]; } } - i = 1; - while (Count[i] != 0) { - i++; - } - - return i; + const res = nums.findIndex((v, i) => v !== i + 1); + return (res === -1 ? n : res) + 1; } ``` -### **C#** +```rust +impl Solution { + pub fn first_missing_positive(mut nums: Vec) -> i32 { + let n = nums.len(); + let mut i = 0; + while i < n { + let j = nums[i] - 1; + if (i as i32) == j || j < 0 || j >= (n as i32) || nums[i] == nums[j as usize] { + i += 1; + } else { + nums.swap(i, j as usize); + } + } + ( + nums + .iter() + .enumerate() + .position(|(i, &v)| (v as usize) != i + 1) + .unwrap_or(n) as i32 + ) + 1 + } +} +``` ```cs public class Solution { @@ -206,26 +211,37 @@ public class Solution { } ``` -### **TypeScript** +```c +int firstMissingPositive(int* nums, int numsSize) { -```ts -function firstMissingPositive(nums: number[]): number { - const n = nums.length; - let i = 0; - while (i < n) { - const j = nums[i] - 1; - if (j === i || j < 0 || j >= n || nums[i] === nums[j]) { - i++; - } else { - [nums[i], nums[j]] = [nums[j], nums[i]]; + int Max = nums[0], i, *Count; + + for (i = 1; i < numsSize; i++) { + Max = (Max < nums[i]) ? nums[i] : Max; + } + + Count = (int*) calloc(Max + 1, sizeof(int)); + for (i = 0; i < numsSize; i++) { + if (nums[i] > 0) { + Count[nums[i]]++; } } - const res = nums.findIndex((v, i) => v !== i + 1); - return (res === -1 ? n : res) + 1; + i = 1; + while (Count[i] != 0) { + i++; + } + + return i; } ``` + + +### Solution 2 + + + ```ts function firstMissingPositive(nums: number[]): number { const set = new Set(nums); @@ -237,36 +253,6 @@ function firstMissingPositive(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn first_missing_positive(mut nums: Vec) -> i32 { - let n = nums.len(); - let mut i = 0; - while i < n { - let j = nums[i] - 1; - if (i as i32) == j || j < 0 || j >= (n as i32) || nums[i] == nums[j as usize] { - i += 1; - } else { - nums.swap(i, j as usize); - } - } - ( - nums - .iter() - .enumerate() - .position(|(i, &v)| (v as usize) != i + 1) - .unwrap_or(n) as i32 - ) + 1 - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0042.Trapping Rain Water/README.md b/solution/0000-0099/0042.Trapping Rain Water/README.md index fe21136195d62..b2f6a0adf13c7 100644 --- a/solution/0000-0099/0042.Trapping Rain Water/README.md +++ b/solution/0000-0099/0042.Trapping Rain Water/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $left[i]$ 表示下标 $i$ 位置及其左边的最高柱子的高度,定义 $right[i]$ 表示下标 $i$ 位置及其右边的最高柱子的高度。那么下标 $i$ 位置能接的雨水量为 $\min(left[i], right[i]) - height[i]$。我们遍历数组,计算出 $left[i]$ 和 $right[i]$,最后答案为 $\sum_{i=0}^{n-1} min(left[i], right[i]) - height[i]$。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def trap(self, height: List[int]) -> int: @@ -65,10 +59,6 @@ class Solution: return sum(min(l, r) - h for l, r, h in zip(left, right, height)) ``` -### **Java** - - - ```java class Solution { public int trap(int[] height) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,39 +101,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn trap(height: Vec) -> i32 { - let n = height.len(); - let mut left: Vec = vec![0; n]; - let mut right: Vec = vec![0; n]; - - left[0] = height[0]; - right[n - 1] = height[n - 1]; - - // Initialize the left & right vector - for i in 1..n { - left[i] = std::cmp::max(left[i - 1], height[i]); - right[n - i - 1] = std::cmp::max(right[n - i], height[n - i - 1]); - } - - let mut ans = 0; - - // Calculate the ans - for i in 0..n { - ans += std::cmp::min(left[i], right[i]) - height[i]; - } - - ans - } -} -``` - -### **Go** - ```go func trap(height []int) (ans int) { n := len(height) @@ -163,8 +118,6 @@ func trap(height []int) (ans int) { } ``` -### **TypeScript** - ```ts function trap(height: number[]): number { const n = height.length; @@ -182,7 +135,34 @@ function trap(height: number[]): number { } ``` -### **C#** +```rust +impl Solution { + #[allow(dead_code)] + pub fn trap(height: Vec) -> i32 { + let n = height.len(); + let mut left: Vec = vec![0; n]; + let mut right: Vec = vec![0; n]; + + left[0] = height[0]; + right[n - 1] = height[n - 1]; + + // Initialize the left & right vector + for i in 1..n { + left[i] = std::cmp::max(left[i - 1], height[i]); + right[n - i - 1] = std::cmp::max(right[n - i], height[n - i - 1]); + } + + let mut ans = 0; + + // Calculate the ans + for i in 0..n { + ans += std::cmp::min(left[i], right[i]) - height[i]; + } + + ans + } +} +``` ```cs public class Solution { @@ -205,10 +185,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0042.Trapping Rain Water/README_EN.md b/solution/0000-0099/0042.Trapping Rain Water/README_EN.md index 6a5914627efe3..0b7c323ffbc16 100644 --- a/solution/0000-0099/0042.Trapping Rain Water/README_EN.md +++ b/solution/0000-0099/0042.Trapping Rain Water/README_EN.md @@ -33,7 +33,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $left[i]$ as the height of the highest bar to the left of and including the position at index $i$, and $right[i]$ as the height of the highest bar to the right of and including the position at index $i$. Therefore, the amount of rainwater that can be trapped at index $i$ is $min(left[i], right[i]) - height[i]$. We traverse the array to calculate $left[i]$ and $right[i]$, and the final answer is $\sum_{i=0}^{n-1} min(left[i], right[i]) - height[i]$. @@ -41,8 +41,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def trap(self, height: List[int]) -> int: @@ -55,8 +53,6 @@ class Solution: return sum(min(l, r) - h for l, r, h in zip(left, right, height)) ``` -### **Java** - ```java class Solution { public int trap(int[] height) { @@ -78,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,39 +95,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn trap(height: Vec) -> i32 { - let n = height.len(); - let mut left: Vec = vec![0; n]; - let mut right: Vec = vec![0; n]; - - left[0] = height[0]; - right[n - 1] = height[n - 1]; - - // Initialize the left & right vector - for i in 1..n { - left[i] = std::cmp::max(left[i - 1], height[i]); - right[n - i - 1] = std::cmp::max(right[n - i], height[n - i - 1]); - } - - let mut ans = 0; - - // Calculate the ans - for i in 0..n { - ans += std::cmp::min(left[i], right[i]) - height[i]; - } - - ans - } -} -``` - -### **Go** - ```go func trap(height []int) (ans int) { n := len(height) @@ -151,8 +112,6 @@ func trap(height []int) (ans int) { } ``` -### **TypeScript** - ```ts function trap(height: number[]): number { const n = height.length; @@ -170,7 +129,34 @@ function trap(height: number[]): number { } ``` -### **C#** +```rust +impl Solution { + #[allow(dead_code)] + pub fn trap(height: Vec) -> i32 { + let n = height.len(); + let mut left: Vec = vec![0; n]; + let mut right: Vec = vec![0; n]; + + left[0] = height[0]; + right[n - 1] = height[n - 1]; + + // Initialize the left & right vector + for i in 1..n { + left[i] = std::cmp::max(left[i - 1], height[i]); + right[n - i - 1] = std::cmp::max(right[n - i], height[n - i - 1]); + } + + let mut ans = 0; + + // Calculate the ans + for i in 0..n { + ans += std::cmp::min(left[i], right[i]) - height[i]; + } + + ans + } +} +``` ```cs public class Solution { @@ -193,10 +179,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0043.Multiply Strings/README.md b/solution/0000-0099/0043.Multiply Strings/README.md index 07a2d4849d154..ecf31351520ff 100644 --- a/solution/0000-0099/0043.Multiply Strings/README.md +++ b/solution/0000-0099/0043.Multiply Strings/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:数学乘法模拟** +### 方法一:数学乘法模拟 假设 $num1$ 和 $num2$ 的长度分别为 $m$ 和 $n$,则它们的乘积的长度最多为 $m + n$。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def multiply(self, num1: str, num2: str) -> str: @@ -80,10 +74,6 @@ class Solution: return "".join(str(x) for x in arr[i:]) ``` -### **Java** - - - ```java class Solution { public String multiply(String num1, String num2) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go func multiply(num1 string, num2 string) string { if num1 == "0" || num2 == "0" { @@ -177,8 +163,6 @@ func multiply(num1 string, num2 string) string { } ``` -### **TypeScript** - ```ts function multiply(num1: string, num2: string): string { if (num1 === '0' || num2 === '0') { @@ -206,8 +190,6 @@ function multiply(num1: string, num2: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn multiply(num1: String, num2: String) -> String { @@ -240,8 +222,6 @@ impl Solution { } ``` -### **C#** - ```cs public class Solution { public string Multiply(string num1, string num2) { @@ -281,10 +261,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0043.Multiply Strings/README_EN.md b/solution/0000-0099/0043.Multiply Strings/README_EN.md index f89d7c03db083..142a79b3b1dc8 100644 --- a/solution/0000-0099/0043.Multiply Strings/README_EN.md +++ b/solution/0000-0099/0043.Multiply Strings/README_EN.md @@ -27,7 +27,7 @@ ## Solutions -**Solution 1: Simulating Mathematical Multiplication** +### Solution 1: Simulating Mathematical Multiplication Assume the lengths of $num1$ and $num2$ are $m$ and $n$ respectively, then the length of their product can be at most $m + n$. @@ -46,8 +46,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m + n)$. -### **Python3** - ```python class Solution: def multiply(self, num1: str, num2: str) -> str: @@ -67,8 +65,6 @@ class Solution: return "".join(str(x) for x in arr[i:]) ``` -### **Java** - ```java class Solution { public String multiply(String num1, String num2) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +124,6 @@ public: }; ``` -### **Go** - ```go func multiply(num1 string, num2 string) string { if num1 == "0" || num2 == "0" { @@ -162,8 +154,6 @@ func multiply(num1 string, num2 string) string { } ``` -### **TypeScript** - ```ts function multiply(num1: string, num2: string): string { if (num1 === '0' || num2 === '0') { @@ -191,8 +181,6 @@ function multiply(num1: string, num2: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn multiply(num1: String, num2: String) -> String { @@ -225,8 +213,6 @@ impl Solution { } ``` -### **C#** - ```cs public class Solution { public string Multiply(string num1, string num2) { @@ -266,10 +252,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0044.Wildcard Matching/README.md b/solution/0000-0099/0044.Wildcard Matching/README.md index 866540027dc1b..a002761680ad6 100644 --- a/solution/0000-0099/0044.Wildcard Matching/README.md +++ b/solution/0000-0099/0044.Wildcard Matching/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义状态 $dp[i][j]$ 表示 $s$ 的前 $i$ 个字符和 $p$ 的前 $j$ 个字符是否匹配。 @@ -77,10 +75,6 @@ $$ -### **Python3** - - - ```python class Solution: def isMatch(self, s: str, p: str) -> bool: @@ -99,10 +93,6 @@ class Solution: return dp[m][n] ``` -### **Java** - - - ```java class Solution { public boolean isMatch(String s, String p) { @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func isMatch(s string, p string) bool { m, n := len(s), len(p) @@ -184,10 +170,52 @@ func isMatch(s string, p string) bool { } ``` -### **...** +```cs +using System.Linq; -``` +public class Solution { + public bool IsMatch(string s, string p) { + if (p.Count(ch => ch != '*') > s.Length) + { + return false; + } + bool[,] f = new bool[s.Length + 1, p.Length + 1]; + bool[] d = new bool[s.Length + 1]; // d[i] means f[0, j] || f[1, j] || ... || f[i, j] + for (var j = 0; j <= p.Length; ++j) + { + d[0] = j == 0 ? true : d[0] && p[j - 1] == '*'; + for (var i = 0; i <= s.Length; ++i) + { + if (j == 0) + { + f[i, j] = i == 0; + continue; + } + + if (p[j - 1] == '*') + { + if (i > 0) + { + d[i] = f[i, j - 1] || d[i - 1]; + } + f[i, j] = d[i]; + } + else if (p[j - 1] == '?') + { + f[i, j] = i > 0 && f[i - 1, j - 1]; + } + else + { + f[i, j] = i > 0 && f[i - 1, j - 1] && s[i - 1] == p[j - 1]; + } + } + } + return f[s.Length, p.Length]; + } +} ``` + + diff --git a/solution/0000-0099/0044.Wildcard Matching/README_EN.md b/solution/0000-0099/0044.Wildcard Matching/README_EN.md index f9d0d2c245756..2fe444541b4e9 100644 --- a/solution/0000-0099/0044.Wildcard Matching/README_EN.md +++ b/solution/0000-0099/0044.Wildcard Matching/README_EN.md @@ -49,7 +49,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define the state $dp[i][j]$ to represent whether the first $i$ characters of $s$ match the first $j$ characters of $p$. @@ -68,8 +68,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times -### **Python3** - ```python class Solution: def isMatch(self, s: str, p: str) -> bool: @@ -88,8 +86,6 @@ class Solution: return dp[m][n] ``` -### **Java** - ```java class Solution { public boolean isMatch(String s, String p) { @@ -115,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +137,6 @@ public: }; ``` -### **Go** - ```go func isMatch(s string, p string) bool { m, n := len(s), len(p) @@ -171,10 +163,52 @@ func isMatch(s string, p string) bool { } ``` -### **...** +```cs +using System.Linq; -``` +public class Solution { + public bool IsMatch(string s, string p) { + if (p.Count(ch => ch != '*') > s.Length) + { + return false; + } + + bool[,] f = new bool[s.Length + 1, p.Length + 1]; + bool[] d = new bool[s.Length + 1]; // d[i] means f[0, j] || f[1, j] || ... || f[i, j] + for (var j = 0; j <= p.Length; ++j) + { + d[0] = j == 0 ? true : d[0] && p[j - 1] == '*'; + for (var i = 0; i <= s.Length; ++i) + { + if (j == 0) + { + f[i, j] = i == 0; + continue; + } + if (p[j - 1] == '*') + { + if (i > 0) + { + d[i] = f[i, j - 1] || d[i - 1]; + } + f[i, j] = d[i]; + } + else if (p[j - 1] == '?') + { + f[i, j] = i > 0 && f[i - 1, j - 1]; + } + else + { + f[i, j] = i > 0 && f[i - 1, j - 1] && s[i - 1] == p[j - 1]; + } + } + } + return f[s.Length, p.Length]; + } +} ``` + + diff --git a/solution/0000-0099/0045.Jump Game II/README.md b/solution/0000-0099/0045.Jump Game II/README.md index c16f7c9e283e6..099004e339357 100644 --- a/solution/0000-0099/0045.Jump Game II/README.md +++ b/solution/0000-0099/0045.Jump Game II/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们可以用变量 $mx$ 记录当前位置能够到达的最远位置,用变量 $last$ 记录上一次跳跃到的位置,用变量 $ans$ 记录跳跃的次数。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def jump(self, nums: List[int]) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int jump(int[] nums) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func jump(nums []int) (ans int) { mx, last := 0, 0 @@ -138,8 +124,6 @@ func jump(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function jump(nums: number[]): number { let [ans, mx, last] = [0, 0, 0]; @@ -154,7 +138,24 @@ function jump(nums: number[]): number { } ``` -### **C#** +```rust +impl Solution { + pub fn jump(nums: Vec) -> i32 { + let n = nums.len(); + let mut dp = vec![i32::MAX; n]; + dp[0] = 0; + for i in 0..n - 1 { + for j in 1..=nums[i] as usize { + if i + j >= n { + break; + } + dp[i + j] = dp[i + j].min(dp[i] + 1); + } + } + dp[n - 1] + } +} +``` ```cs public class Solution { @@ -172,8 +173,6 @@ public class Solution { } ``` -### **C** - ```c #define min(a, b) a < b ? a : b int jump(int* nums, int numsSize) { @@ -191,31 +190,6 @@ int jump(int* nums, int numsSize) { } ``` -### **Rust** - -```rust -impl Solution { - pub fn jump(nums: Vec) -> i32 { - let n = nums.len(); - let mut dp = vec![i32::MAX; n]; - dp[0] = 0; - for i in 0..n - 1 { - for j in 1..=nums[i] as usize { - if i + j >= n { - break; - } - dp[i + j] = dp[i + j].min(dp[i] + 1); - } - } - dp[n - 1] - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0045.Jump Game II/README_EN.md b/solution/0000-0099/0045.Jump Game II/README_EN.md index 6fed81c002d6c..c83def951a0e1 100644 --- a/solution/0000-0099/0045.Jump Game II/README_EN.md +++ b/solution/0000-0099/0045.Jump Game II/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Greedy Algorithm** +### Solution 1: Greedy Algorithm We can use a variable $mx$ to record the farthest position that can be reached from the current position, a variable $last$ to record the position of the last jump, and a variable $ans$ to record the number of jumps. @@ -60,8 +60,6 @@ Similar problems: -### **Python3** - ```python class Solution: def jump(self, nums: List[int]) -> int: @@ -74,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int jump(int[] nums) { @@ -92,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +105,6 @@ public: }; ``` -### **Go** - ```go func jump(nums []int) (ans int) { mx, last := 0, 0 @@ -127,8 +119,6 @@ func jump(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function jump(nums: number[]): number { let [ans, mx, last] = [0, 0, 0]; @@ -143,7 +133,24 @@ function jump(nums: number[]): number { } ``` -### **C#** +```rust +impl Solution { + pub fn jump(nums: Vec) -> i32 { + let n = nums.len(); + let mut dp = vec![i32::MAX; n]; + dp[0] = 0; + for i in 0..n - 1 { + for j in 1..=nums[i] as usize { + if i + j >= n { + break; + } + dp[i + j] = dp[i + j].min(dp[i] + 1); + } + } + dp[n - 1] + } +} +``` ```cs public class Solution { @@ -161,8 +168,6 @@ public class Solution { } ``` -### **C** - ```c #define min(a, b) a < b ? a : b int jump(int* nums, int numsSize) { @@ -180,31 +185,6 @@ int jump(int* nums, int numsSize) { } ``` -### **Rust** - -```rust -impl Solution { - pub fn jump(nums: Vec) -> i32 { - let n = nums.len(); - let mut dp = vec![i32::MAX; n]; - dp[0] = 0; - for i in 0..n - 1 { - for j in 1..=nums[i] as usize { - if i + j >= n { - break; - } - dp[i + j] = dp[i + j].min(dp[i] + 1); - } - } - dp[n - 1] - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0046.Permutations/README.md b/solution/0000-0099/0046.Permutations/README.md index faba7e6394bd5..0287c3bcb8b44 100644 --- a/solution/0000-0099/0046.Permutations/README.md +++ b/solution/0000-0099/0046.Permutations/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:DFS(回溯)** +### 方法一:DFS(回溯) 我们设计一个函数 $dfs(i)$ 表示已经填完了前 $i$ 个位置,现在需要填第 $i+1$ 个位置。枚举所有可能的数,如果这个数没有被填过,就填入这个数,然后继续填下一个位置,直到填完所有的位置。 @@ -57,65 +55,12 @@ -### **Python3** - - - ```python class Solution: def permute(self, nums: List[int]) -> List[List[int]]: return list(permutations(nums)) ``` -```python -class Solution: - def permute(self, nums: List[int]) -> List[List[int]]: - def dfs(i): - if i == n: - ans.append(t[:]) - return - for j in range(n): - if not vis[j]: - vis[j] = True - t[i] = nums[j] - dfs(i + 1) - vis[j] = False - - n = len(nums) - vis = [False] * n - t = [0] * n - ans = [] - dfs(0) - return ans -``` - -```python -class Solution: - def permute(self, nums: List[int]) -> List[List[int]]: - def dfs(i): - nonlocal mask - if i == n: - ans.append(t[:]) - return - for j in range(n): - if (mask >> j & 1) == 0: - mask |= 1 << j - t[i] = nums[j] - dfs(i + 1) - mask ^= 1 << j - - n = len(nums) - mask = 0 - t = [0] * n - ans = [] - dfs(0) - return ans -``` - -### **Java** - - - ```java class Solution { private List> ans = new ArrayList<>(); @@ -148,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -178,8 +121,6 @@ public: }; ``` -### **Go** - ```go func permute(nums []int) (ans [][]int) { n := len(nums) @@ -205,7 +146,47 @@ func permute(nums []int) (ans [][]int) { } ``` -### **JavaScript** +```ts +function permute(nums: number[]): number[][] { + const n = nums.length; + const res: number[][] = []; + const dfs = (i: number) => { + if (i === n) { + res.push([...nums]); + } + for (let j = i; j < n; j++) { + [nums[i], nums[j]] = [nums[j], nums[i]]; + dfs(i + 1); + [nums[i], nums[j]] = [nums[j], nums[i]]; + } + }; + dfs(0); + return res; +} +``` + +```rust +impl Solution { + fn dfs(i: usize, nums: &mut Vec, res: &mut Vec>) { + let n = nums.len(); + if i == n { + res.push(nums.clone()); + return; + } + for j in i..n { + nums.swap(i, j); + Self::dfs(i + 1, nums, res); + nums.swap(i, j); + } + } + + pub fn permute(mut nums: Vec) -> Vec> { + let mut res = vec![]; + Self::dfs(0, &mut nums, &mut res); + res + } +} +``` ```js /** @@ -237,8 +218,6 @@ var permute = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public IList> Permute(int[] nums) { @@ -267,50 +246,32 @@ public class Solution { } ``` -### **TypeScript** + -```ts -function permute(nums: number[]): number[][] { - const n = nums.length; - const res: number[][] = []; - const dfs = (i: number) => { - if (i === n) { - res.push([...nums]); - } - for (let j = i; j < n; j++) { - [nums[i], nums[j]] = [nums[j], nums[i]]; - dfs(i + 1); - [nums[i], nums[j]] = [nums[j], nums[i]]; - } - }; - dfs(0); - return res; -} -``` +### 方法二 -### **Rust** + -```rust -impl Solution { - fn dfs(i: usize, nums: &mut Vec, res: &mut Vec>) { - let n = nums.len(); - if i == n { - res.push(nums.clone()); - return; - } - for j in i..n { - nums.swap(i, j); - Self::dfs(i + 1, nums, res); - nums.swap(i, j); - } - } +```python +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + def dfs(i): + if i == n: + ans.append(t[:]) + return + for j in range(n): + if not vis[j]: + vis[j] = True + t[i] = nums[j] + dfs(i + 1) + vis[j] = False - pub fn permute(mut nums: Vec) -> Vec> { - let mut res = vec![]; - Self::dfs(0, &mut nums, &mut res); - res - } -} + n = len(nums) + vis = [False] * n + t = [0] * n + ans = [] + dfs(0) + return ans ``` ```rust @@ -353,10 +314,35 @@ impl Solution { } ``` -### **...** + -``` +### 方法三 + + +```python +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + def dfs(i): + nonlocal mask + if i == n: + ans.append(t[:]) + return + for j in range(n): + if (mask >> j & 1) == 0: + mask |= 1 << j + t[i] = nums[j] + dfs(i + 1) + mask ^= 1 << j + + n = len(nums) + mask = 0 + t = [0] * n + ans = [] + dfs(0) + return ans ``` + + diff --git a/solution/0000-0099/0046.Permutations/README_EN.md b/solution/0000-0099/0046.Permutations/README_EN.md index 1a417c4931394..4fe9ddd2d242b 100644 --- a/solution/0000-0099/0046.Permutations/README_EN.md +++ b/solution/0000-0099/0046.Permutations/README_EN.md @@ -28,7 +28,7 @@ ## Solutions -**Solution 1: DFS (Backtracking)** +### Solution 1: DFS (Backtracking) We design a function $dfs(i)$ to represent that the first $i$ positions have been filled, and now we need to fill the $i+1$ position. We enumerate all possible numbers, if this number has not been filled, we fill in this number, and then continue to fill the next position, until all positions are filled. @@ -40,61 +40,12 @@ Similar problems: -### **Python3** - ```python class Solution: def permute(self, nums: List[int]) -> List[List[int]]: return list(permutations(nums)) ``` -```python -class Solution: - def permute(self, nums: List[int]) -> List[List[int]]: - def dfs(i): - if i == n: - ans.append(t[:]) - return - for j in range(n): - if not vis[j]: - vis[j] = True - t[i] = nums[j] - dfs(i + 1) - vis[j] = False - - n = len(nums) - vis = [False] * n - t = [0] * n - ans = [] - dfs(0) - return ans -``` - -```python -class Solution: - def permute(self, nums: List[int]) -> List[List[int]]: - def dfs(i): - nonlocal mask - if i == n: - ans.append(t[:]) - return - for j in range(n): - if (mask >> j & 1) == 0: - mask |= 1 << j - t[i] = nums[j] - dfs(i + 1) - mask ^= 1 << j - - n = len(nums) - mask = 0 - t = [0] * n - ans = [] - dfs(0) - return ans -``` - -### **Java** - ```java class Solution { private List> ans = new ArrayList<>(); @@ -127,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +106,6 @@ public: }; ``` -### **Go** - ```go func permute(nums []int) (ans [][]int) { n := len(nums) @@ -184,7 +131,47 @@ func permute(nums []int) (ans [][]int) { } ``` -### **JavaScript** +```ts +function permute(nums: number[]): number[][] { + const n = nums.length; + const res: number[][] = []; + const dfs = (i: number) => { + if (i === n) { + res.push([...nums]); + } + for (let j = i; j < n; j++) { + [nums[i], nums[j]] = [nums[j], nums[i]]; + dfs(i + 1); + [nums[i], nums[j]] = [nums[j], nums[i]]; + } + }; + dfs(0); + return res; +} +``` + +```rust +impl Solution { + fn dfs(i: usize, nums: &mut Vec, res: &mut Vec>) { + let n = nums.len(); + if i == n { + res.push(nums.clone()); + return; + } + for j in i..n { + nums.swap(i, j); + Self::dfs(i + 1, nums, res); + nums.swap(i, j); + } + } + + pub fn permute(mut nums: Vec) -> Vec> { + let mut res = vec![]; + Self::dfs(0, &mut nums, &mut res); + res + } +} +``` ```js /** @@ -216,8 +203,6 @@ var permute = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public IList> Permute(int[] nums) { @@ -246,50 +231,32 @@ public class Solution { } ``` -### **TypeScript** + -```ts -function permute(nums: number[]): number[][] { - const n = nums.length; - const res: number[][] = []; - const dfs = (i: number) => { - if (i === n) { - res.push([...nums]); - } - for (let j = i; j < n; j++) { - [nums[i], nums[j]] = [nums[j], nums[i]]; - dfs(i + 1); - [nums[i], nums[j]] = [nums[j], nums[i]]; - } - }; - dfs(0); - return res; -} -``` +### Solution 2 -### **Rust** + -```rust -impl Solution { - fn dfs(i: usize, nums: &mut Vec, res: &mut Vec>) { - let n = nums.len(); - if i == n { - res.push(nums.clone()); - return; - } - for j in i..n { - nums.swap(i, j); - Self::dfs(i + 1, nums, res); - nums.swap(i, j); - } - } +```python +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + def dfs(i): + if i == n: + ans.append(t[:]) + return + for j in range(n): + if not vis[j]: + vis[j] = True + t[i] = nums[j] + dfs(i + 1) + vis[j] = False - pub fn permute(mut nums: Vec) -> Vec> { - let mut res = vec![]; - Self::dfs(0, &mut nums, &mut res); - res - } -} + n = len(nums) + vis = [False] * n + t = [0] * n + ans = [] + dfs(0) + return ans ``` ```rust @@ -332,10 +299,35 @@ impl Solution { } ``` -### **...** + -``` +### Solution 3 + + +```python +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + def dfs(i): + nonlocal mask + if i == n: + ans.append(t[:]) + return + for j in range(n): + if (mask >> j & 1) == 0: + mask |= 1 << j + t[i] = nums[j] + dfs(i + 1) + mask ^= 1 << j + + n = len(nums) + mask = 0 + t = [0] * n + ans = [] + dfs(0) + return ans ``` + + diff --git a/solution/0000-0099/0047.Permutations II/README.md b/solution/0000-0099/0047.Permutations II/README.md index 00466d20e2500..a592c39cacdcf 100644 --- a/solution/0000-0099/0047.Permutations II/README.md +++ b/solution/0000-0099/0047.Permutations II/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:排序 + 回溯** +### 方法一:排序 + 回溯 我们可以先对数组进行排序,这样就可以将重复的数字放在一起,方便我们进行去重。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List> ans = new ArrayList<>(); @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func permuteUnique(nums []int) (ans [][]int) { sort.Ints(nums) @@ -186,8 +172,6 @@ func permuteUnique(nums []int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function permuteUnique(nums: number[]): number[][] { nums.sort((a, b) => a - b); @@ -215,7 +199,34 @@ function permuteUnique(nums: number[]): number[][] { } ``` -### **C#** +```rust +use std::collections::HashSet; +impl Solution { + fn dfs(i: usize, nums: &mut Vec, res: &mut Vec>) { + let n = nums.len(); + if i == n { + res.push(nums.clone()); + return; + } + let mut set = HashSet::new(); + for j in i..n { + if set.contains(&nums[j]) { + continue; + } + set.insert(nums[j]); + nums.swap(i, j); + Self::dfs(i + 1, nums, res); + nums.swap(i, j); + } + } + + pub fn permute_unique(mut nums: Vec) -> Vec> { + let mut res = vec![]; + Self::dfs(0, &mut nums, &mut res); + res + } +} +``` ```cs public class Solution { @@ -252,41 +263,6 @@ public class Solution { } ``` -### **Rust** - -```rust -use std::collections::HashSet; -impl Solution { - fn dfs(i: usize, nums: &mut Vec, res: &mut Vec>) { - let n = nums.len(); - if i == n { - res.push(nums.clone()); - return; - } - let mut set = HashSet::new(); - for j in i..n { - if set.contains(&nums[j]) { - continue; - } - set.insert(nums[j]); - nums.swap(i, j); - Self::dfs(i + 1, nums, res); - nums.swap(i, j); - } - } - - pub fn permute_unique(mut nums: Vec) -> Vec> { - let mut res = vec![]; - Self::dfs(0, &mut nums, &mut res); - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0047.Permutations II/README_EN.md b/solution/0000-0099/0047.Permutations II/README_EN.md index b6618ab4b679c..444bb0794057c 100644 --- a/solution/0000-0099/0047.Permutations II/README_EN.md +++ b/solution/0000-0099/0047.Permutations II/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Sorting + Backtracking** +### Solution 1: Sorting + Backtracking We can first sort the array, which allows us to place duplicate numbers together, making it easier for us to remove duplicates. @@ -53,8 +53,6 @@ Similar problems: -### **Python3** - ```python class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: @@ -79,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List> ans = new ArrayList<>(); @@ -115,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +141,6 @@ public: }; ``` -### **Go** - ```go func permuteUnique(nums []int) (ans [][]int) { sort.Ints(nums) @@ -176,8 +168,6 @@ func permuteUnique(nums []int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function permuteUnique(nums: number[]): number[][] { nums.sort((a, b) => a - b); @@ -205,7 +195,34 @@ function permuteUnique(nums: number[]): number[][] { } ``` -### **C#** +```rust +use std::collections::HashSet; +impl Solution { + fn dfs(i: usize, nums: &mut Vec, res: &mut Vec>) { + let n = nums.len(); + if i == n { + res.push(nums.clone()); + return; + } + let mut set = HashSet::new(); + for j in i..n { + if set.contains(&nums[j]) { + continue; + } + set.insert(nums[j]); + nums.swap(i, j); + Self::dfs(i + 1, nums, res); + nums.swap(i, j); + } + } + + pub fn permute_unique(mut nums: Vec) -> Vec> { + let mut res = vec![]; + Self::dfs(0, &mut nums, &mut res); + res + } +} +``` ```cs public class Solution { @@ -242,41 +259,6 @@ public class Solution { } ``` -### **Rust** - -```rust -use std::collections::HashSet; -impl Solution { - fn dfs(i: usize, nums: &mut Vec, res: &mut Vec>) { - let n = nums.len(); - if i == n { - res.push(nums.clone()); - return; - } - let mut set = HashSet::new(); - for j in i..n { - if set.contains(&nums[j]) { - continue; - } - set.insert(nums[j]); - nums.swap(i, j); - Self::dfs(i + 1, nums, res); - nums.swap(i, j); - } - } - - pub fn permute_unique(mut nums: Vec) -> Vec> { - let mut res = vec![]; - Self::dfs(0, &mut nums, &mut res); - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0048.Rotate Image/README.md b/solution/0000-0099/0048.Rotate Image/README.md index 3b7768083826a..10b7f18ea2e1a 100644 --- a/solution/0000-0099/0048.Rotate Image/README.md +++ b/solution/0000-0099/0048.Rotate Image/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:原地翻转** +### 方法一:原地翻转 根据题目要求,我们实际上需要将 $matrix[i][j]$ 旋转至 $matrix[j][n - i - 1]$。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def rotate(self, matrix: List[List[int]]) -> None: @@ -68,10 +62,6 @@ class Solution: matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] ``` -### **Java** - - - ```java class Solution { public void rotate(int[][] matrix) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func rotate(matrix [][]int) { n := len(matrix) @@ -133,25 +119,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. @@ -168,32 +135,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>) { @@ -216,10 +157,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/solution/0000-0099/0048.Rotate Image/README_EN.md b/solution/0000-0099/0048.Rotate Image/README_EN.md index 2bc0408338f94..ad7c68982456b 100644 --- a/solution/0000-0099/0048.Rotate Image/README_EN.md +++ b/solution/0000-0099/0048.Rotate Image/README_EN.md @@ -34,7 +34,7 @@ ## 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]$. @@ -44,8 +44,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: @@ -58,8 +56,6 @@ class Solution: matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] ``` -### **Java** - ```java class Solution { public void rotate(int[][] matrix) { @@ -82,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +97,6 @@ public: }; ``` -### **Go** - ```go func rotate(matrix [][]int) { n := len(matrix) @@ -121,25 +113,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. @@ -156,32 +129,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>) { @@ -204,10 +151,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/solution/0000-0099/0049.Group Anagrams/README.md b/solution/0000-0099/0049.Group Anagrams/README.md index 549e00d5e0315..75e2d043718f3 100644 --- a/solution/0000-0099/0049.Group Anagrams/README.md +++ b/solution/0000-0099/0049.Group Anagrams/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 1. 遍历字符串,对每个字符串按照**字符字典序**排序,得到一个新的字符串。 2. 以新字符串为 `key`,`[str]` 为 `value`,存入哈希表当中(`HashMap>`)。 @@ -63,18 +61,8 @@ 时间复杂度 $O(n\times k\times \log k)$。其中 $n$ 和 $k$ 分别是字符串数组的长度和字符串的最大长度。 -**方法二:计数** - -我们也可以将方法一中的排序部分改为计数,也就是说,将每个字符串 $s$ 中的字符以及出现的次数作为 `key`,将字符串 $s$ 作为 `value` 存入哈希表当中。 - -时间复杂度 $O(n\times (k + C))$。其中 $n$ 和 $k$ 分别是字符串数组的长度和字符串的最大长度,而 $C$ 是字符集的大小,本题中 $C = 26$。 - -### **Python3** - - - ```python class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: @@ -85,22 +73,6 @@ class Solution: return list(d.values()) ``` -```python -class Solution: - def groupAnagrams(self, strs: List[str]) -> List[List[str]]: - d = defaultdict(list) - for s in strs: - cnt = [0] * 26 - for c in s: - cnt[ord(c) - ord('a')] += 1 - d[tuple(cnt)].append(s) - return list(d.values()) -``` - -### **Java** - - - ```java class Solution { public List> groupAnagrams(String[] strs) { @@ -116,6 +88,155 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map> d; + for (auto& s : strs) { + string k = s; + sort(k.begin(), k.end()); + d[k].emplace_back(s); + } + vector> ans; + for (auto& [_, v] : d) ans.emplace_back(v); + return ans; + } +}; +``` + +```go +func groupAnagrams(strs []string) (ans [][]string) { + d := map[string][]string{} + for _, s := range strs { + t := []byte(s) + sort.Slice(t, func(i, j int) bool { return t[i] < t[j] }) + k := string(t) + d[k] = append(d[k], s) + } + for _, v := range d { + ans = append(ans, v) + } + return +} +``` + +```ts +function groupAnagrams(strs: string[]): string[][] { + const d: Map = new Map(); + for (const s of strs) { + const k = s.split('').sort().join(''); + if (!d.has(k)) { + d.set(k, []); + } + d.get(k)!.push(s); + } + return Array.from(d.values()); +} +``` + +```rust +use std::collections::HashMap; + +impl Solution { + pub fn group_anagrams(strs: Vec) -> Vec> { + let mut map = HashMap::new(); + for s in strs { + let key = { + let mut arr = s.chars().collect::>(); + arr.sort(); + arr.iter().collect::() + }; + let val = map.entry(key).or_insert(vec![]); + val.push(s); + } + map.into_iter() + .map(|(_, v)| v) + .collect() + } +} +``` + +```cs +using System.Collections.Generic; + +public class Comparer : IEqualityComparer +{ + public bool Equals(string left, string right) + { + if (left.Length != right.Length) return false; + + var leftCount = new int[26]; + foreach (var ch in left) + { + ++leftCount[ch - 'a']; + } + + var rightCount = new int[26]; + foreach (var ch in right) + { + var index = ch - 'a'; + if (++rightCount[index] > leftCount[index]) return false; + } + + return true; + } + + public int GetHashCode(string obj) + { + var hashCode = 0; + for (int i = 0; i < obj.Length; ++i) + { + hashCode ^= 1 << (obj[i] - 'a'); + } + return hashCode; + } +} + +public class Solution { + public IList> GroupAnagrams(string[] strs) { + var dict = new Dictionary>(new Comparer()); + foreach (var str in strs) + { + List list; + if (!dict.TryGetValue(str, out list)) + { + list = new List(); + dict.Add(str, list); + } + list.Add(str); + } + foreach (var list in dict.Values) + { + list.Sort(); + } + return new List>(dict.Values); + } +} +``` + + + +### 方法二:计数 + +我们也可以将方法一中的排序部分改为计数,也就是说,将每个字符串 $s$ 中的字符以及出现的次数作为 `key`,将字符串 $s$ 作为 `value` 存入哈希表当中。 + +时间复杂度 $O(n\times (k + C))$。其中 $n$ 和 $k$ 分别是字符串数组的长度和字符串的最大长度,而 $C$ 是字符集的大小,本题中 $C = 26$。 + + + +```python +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + d = defaultdict(list) + for s in strs: + cnt = [0] * 26 + for c in s: + cnt[ord(c) - ord('a')] += 1 + d[tuple(cnt)].append(s) + return list(d.values()) +``` + ```java class Solution { public List> groupAnagrams(String[] strs) { @@ -139,25 +260,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector> groupAnagrams(vector& strs) { - unordered_map> d; - for (auto& s : strs) { - string k = s; - sort(k.begin(), k.end()); - d[k].emplace_back(s); - } - vector> ans; - for (auto& [_, v] : d) ans.emplace_back(v); - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -182,24 +284,6 @@ public: }; ``` -### **Go** - -```go -func groupAnagrams(strs []string) (ans [][]string) { - d := map[string][]string{} - for _, s := range strs { - t := []byte(s) - sort.Slice(t, func(i, j int) bool { return t[i] < t[j] }) - k := string(t) - d[k] = append(d[k], s) - } - for _, v := range d { - ans = append(ans, v) - } - return -} -``` - ```go func groupAnagrams(strs []string) (ans [][]string) { d := map[[26]int][]string{} @@ -217,22 +301,6 @@ func groupAnagrams(strs []string) (ans [][]string) { } ``` -### **TypeScript** - -```ts -function groupAnagrams(strs: string[]): string[][] { - const d: Map = new Map(); - for (const s of strs) { - const k = s.split('').sort().join(''); - if (!d.has(k)) { - d.set(k, []); - } - d.get(k)!.push(s); - } - return Array.from(d.values()); -} -``` - ```ts function groupAnagrams(strs: string[]): string[][] { const map = new Map(); @@ -244,34 +312,6 @@ function groupAnagrams(strs: string[]): string[][] { } ``` -### **Rust** - -```rust -use std::collections::HashMap; - -impl Solution { - pub fn group_anagrams(strs: Vec) -> Vec> { - let mut map = HashMap::new(); - for s in strs { - let key = { - let mut arr = s.chars().collect::>(); - arr.sort(); - arr.iter().collect::() - }; - let val = map.entry(key).or_insert(vec![]); - val.push(s); - } - map.into_iter() - .map(|(_, v)| v) - .collect() - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0049.Group Anagrams/README_EN.md b/solution/0000-0099/0049.Group Anagrams/README_EN.md index e6416a724d713..ab32dfa630ed0 100644 --- a/solution/0000-0099/0049.Group Anagrams/README_EN.md +++ b/solution/0000-0099/0049.Group Anagrams/README_EN.md @@ -30,7 +30,7 @@ ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table 1. Traverse the string array, sort each string in **character dictionary order** to get a new string. 2. Use the new string as `key` and `[str]` as `value`, and store them in the hash table (`HashMap>`). @@ -48,16 +48,8 @@ Finally, return the `value` list of the hash table. The time complexity is $O(n\times k\times \log k)$, where $n$ and $k$ are the lengths of the string array and the maximum length of the string, respectively. -**Solution 2: Counting** - -We can also change the sorting part in Solution 1 to counting, that is, use the characters in each string $s$ and their occurrence times as `key`, and use the string $s$ as `value` to store in the hash table. - -The time complexity is $O(n\times (k + C))$, where $n$ and $k$ are the lengths of the string array and the maximum length of the string, respectively, and $C$ is the size of the character set. In this problem, $C = 26$. - -### **Python3** - ```python class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: @@ -68,20 +60,6 @@ class Solution: return list(d.values()) ``` -```python -class Solution: - def groupAnagrams(self, strs: List[str]) -> List[List[str]]: - d = defaultdict(list) - for s in strs: - cnt = [0] * 26 - for c in s: - cnt[ord(c) - ord('a')] += 1 - d[tuple(cnt)].append(s) - return list(d.values()) -``` - -### **Java** - ```java class Solution { public List> groupAnagrams(String[] strs) { @@ -97,6 +75,155 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map> d; + for (auto& s : strs) { + string k = s; + sort(k.begin(), k.end()); + d[k].emplace_back(s); + } + vector> ans; + for (auto& [_, v] : d) ans.emplace_back(v); + return ans; + } +}; +``` + +```go +func groupAnagrams(strs []string) (ans [][]string) { + d := map[string][]string{} + for _, s := range strs { + t := []byte(s) + sort.Slice(t, func(i, j int) bool { return t[i] < t[j] }) + k := string(t) + d[k] = append(d[k], s) + } + for _, v := range d { + ans = append(ans, v) + } + return +} +``` + +```ts +function groupAnagrams(strs: string[]): string[][] { + const d: Map = new Map(); + for (const s of strs) { + const k = s.split('').sort().join(''); + if (!d.has(k)) { + d.set(k, []); + } + d.get(k)!.push(s); + } + return Array.from(d.values()); +} +``` + +```rust +use std::collections::HashMap; + +impl Solution { + pub fn group_anagrams(strs: Vec) -> Vec> { + let mut map = HashMap::new(); + for s in strs { + let key = { + let mut arr = s.chars().collect::>(); + arr.sort(); + arr.iter().collect::() + }; + let val = map.entry(key).or_insert(vec![]); + val.push(s); + } + map.into_iter() + .map(|(_, v)| v) + .collect() + } +} +``` + +```cs +using System.Collections.Generic; + +public class Comparer : IEqualityComparer +{ + public bool Equals(string left, string right) + { + if (left.Length != right.Length) return false; + + var leftCount = new int[26]; + foreach (var ch in left) + { + ++leftCount[ch - 'a']; + } + + var rightCount = new int[26]; + foreach (var ch in right) + { + var index = ch - 'a'; + if (++rightCount[index] > leftCount[index]) return false; + } + + return true; + } + + public int GetHashCode(string obj) + { + var hashCode = 0; + for (int i = 0; i < obj.Length; ++i) + { + hashCode ^= 1 << (obj[i] - 'a'); + } + return hashCode; + } +} + +public class Solution { + public IList> GroupAnagrams(string[] strs) { + var dict = new Dictionary>(new Comparer()); + foreach (var str in strs) + { + List list; + if (!dict.TryGetValue(str, out list)) + { + list = new List(); + dict.Add(str, list); + } + list.Add(str); + } + foreach (var list in dict.Values) + { + list.Sort(); + } + return new List>(dict.Values); + } +} +``` + + + +### Solution 2: Counting + +We can also change the sorting part in Solution 1 to counting, that is, use the characters in each string $s$ and their occurrence times as `key`, and use the string $s$ as `value` to store in the hash table. + +The time complexity is $O(n\times (k + C))$, where $n$ and $k$ are the lengths of the string array and the maximum length of the string, respectively, and $C$ is the size of the character set. In this problem, $C = 26$. + + + +```python +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + d = defaultdict(list) + for s in strs: + cnt = [0] * 26 + for c in s: + cnt[ord(c) - ord('a')] += 1 + d[tuple(cnt)].append(s) + return list(d.values()) +``` + ```java class Solution { public List> groupAnagrams(String[] strs) { @@ -120,25 +247,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector> groupAnagrams(vector& strs) { - unordered_map> d; - for (auto& s : strs) { - string k = s; - sort(k.begin(), k.end()); - d[k].emplace_back(s); - } - vector> ans; - for (auto& [_, v] : d) ans.emplace_back(v); - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -163,24 +271,6 @@ public: }; ``` -### **Go** - -```go -func groupAnagrams(strs []string) (ans [][]string) { - d := map[string][]string{} - for _, s := range strs { - t := []byte(s) - sort.Slice(t, func(i, j int) bool { return t[i] < t[j] }) - k := string(t) - d[k] = append(d[k], s) - } - for _, v := range d { - ans = append(ans, v) - } - return -} -``` - ```go func groupAnagrams(strs []string) (ans [][]string) { d := map[[26]int][]string{} @@ -198,22 +288,6 @@ func groupAnagrams(strs []string) (ans [][]string) { } ``` -### **TypeScript** - -```ts -function groupAnagrams(strs: string[]): string[][] { - const d: Map = new Map(); - for (const s of strs) { - const k = s.split('').sort().join(''); - if (!d.has(k)) { - d.set(k, []); - } - d.get(k)!.push(s); - } - return Array.from(d.values()); -} -``` - ```ts function groupAnagrams(strs: string[]): string[][] { const map = new Map(); @@ -225,34 +299,6 @@ function groupAnagrams(strs: string[]): string[][] { } ``` -### **Rust** - -```rust -use std::collections::HashMap; - -impl Solution { - pub fn group_anagrams(strs: Vec) -> Vec> { - let mut map = HashMap::new(); - for s in strs { - let key = { - let mut arr = s.chars().collect::>(); - arr.sort(); - arr.iter().collect::() - }; - let val = map.entry(key).or_insert(vec![]); - val.push(s); - } - map.into_iter() - .map(|(_, v)| v) - .collect() - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0050.Pow(x, n)/README.md b/solution/0000-0099/0050.Pow(x, n)/README.md index 2d2a6e4f9a457..c4d098884402d 100644 --- a/solution/0000-0099/0050.Pow(x, n)/README.md +++ b/solution/0000-0099/0050.Pow(x, n)/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:数学(快速幂)** +### 方法一:数学(快速幂) 快速幂算法的核心思想是将幂指数 $n$ 拆分为若干个二进制位上的 $1$ 的和,然后将 $x$ 的 $n$ 次幂转化为 $x$ 的若干个幂的乘积。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def myPow(self, x: float, n: int) -> float: @@ -75,10 +69,6 @@ class Solution: return qpow(x, n) if n >= 0 else 1 / qpow(x, -n) ``` -### **Java** - - - ```java class Solution { public double myPow(double x, int n) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,7 +107,40 @@ public: }; ``` -### **Rust** +```go +func myPow(x float64, n int) float64 { + qpow := func(a float64, n int) float64 { + ans := 1.0 + for ; n > 0; n >>= 1 { + if n&1 == 1 { + ans *= a + } + a *= a + } + return ans + } + if n >= 0 { + return qpow(x, n) + } + return 1 / qpow(x, -n) +} +``` + +```ts +function myPow(x: number, n: number): number { + const qpow = (a: number, n: number): number => { + let ans = 1; + for (; n; n >>>= 1) { + if (n & 1) { + ans *= a; + } + a *= a; + } + return ans; + }; + return n >= 0 ? qpow(x, n) : 1 / qpow(x, -n); +} +``` ```rust impl Solution { @@ -150,29 +171,6 @@ impl Solution { } ``` -### **Go** - -```go -func myPow(x float64, n int) float64 { - qpow := func(a float64, n int) float64 { - ans := 1.0 - for ; n > 0; n >>= 1 { - if n&1 == 1 { - ans *= a - } - a *= a - } - return ans - } - if n >= 0 { - return qpow(x, n) - } - return 1 / qpow(x, -n) -} -``` - -### **JavaScript** - ```js /** * @param {number} x @@ -194,26 +192,6 @@ var myPow = function (x, n) { }; ``` -### **TypeScript** - -```ts -function myPow(x: number, n: number): number { - const qpow = (a: number, n: number): number => { - let ans = 1; - for (; n; n >>>= 1) { - if (n & 1) { - ans *= a; - } - a *= a; - } - return ans; - }; - return n >= 0 ? qpow(x, n) : 1 / qpow(x, -n); -} -``` - -### **C#** - ```cs public class Solution { public double MyPow(double x, int n) { @@ -233,10 +211,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0050.Pow(x, n)/README_EN.md b/solution/0000-0099/0050.Pow(x, n)/README_EN.md index c26e17253a59e..f74261b111585 100644 --- a/solution/0000-0099/0050.Pow(x, n)/README_EN.md +++ b/solution/0000-0099/0050.Pow(x, n)/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Mathematics (Fast Powering)** +### Solution 1: Mathematics (Fast Powering) The core idea of the fast powering algorithm is to decompose the exponent $n$ into the sum of $1$s on several binary bits, and then transform the $n$th power of $x$ into the product of several powers of $x$. @@ -50,8 +50,6 @@ The time complexity is $O(\log n)$, and the space complexity is $O(1)$. Here, $n -### **Python3** - ```python class Solution: def myPow(self, x: float, n: int) -> float: @@ -67,8 +65,6 @@ class Solution: return qpow(x, n) if n >= 0 else 1 / qpow(x, -n) ``` -### **Java** - ```java class Solution { public double myPow(double x, int n) { @@ -88,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,7 +103,40 @@ public: }; ``` -### **Rust** +```go +func myPow(x float64, n int) float64 { + qpow := func(a float64, n int) float64 { + ans := 1.0 + for ; n > 0; n >>= 1 { + if n&1 == 1 { + ans *= a + } + a *= a + } + return ans + } + if n >= 0 { + return qpow(x, n) + } + return 1 / qpow(x, -n) +} +``` + +```ts +function myPow(x: number, n: number): number { + const qpow = (a: number, n: number): number => { + let ans = 1; + for (; n; n >>>= 1) { + if (n & 1) { + ans *= a; + } + a *= a; + } + return ans; + }; + return n >= 0 ? qpow(x, n) : 1 / qpow(x, -n); +} +``` ```rust impl Solution { @@ -140,29 +167,6 @@ impl Solution { } ``` -### **Go** - -```go -func myPow(x float64, n int) float64 { - qpow := func(a float64, n int) float64 { - ans := 1.0 - for ; n > 0; n >>= 1 { - if n&1 == 1 { - ans *= a - } - a *= a - } - return ans - } - if n >= 0 { - return qpow(x, n) - } - return 1 / qpow(x, -n) -} -``` - -### **JavaScript** - ```js /** * @param {number} x @@ -184,26 +188,6 @@ var myPow = function (x, n) { }; ``` -### **TypeScript** - -```ts -function myPow(x: number, n: number): number { - const qpow = (a: number, n: number): number => { - let ans = 1; - for (; n; n >>>= 1) { - if (n & 1) { - ans *= a; - } - a *= a; - } - return ans; - }; - return n >= 0 ? qpow(x, n) : 1 / qpow(x, -n); -} -``` - -### **C#** - ```cs public class Solution { public double MyPow(double x, int n) { @@ -223,10 +207,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0051.N-Queens/README.md b/solution/0000-0099/0051.N-Queens/README.md index cfb54f5ee8c28..8c23a7a096e82 100644 --- a/solution/0000-0099/0051.N-Queens/README.md +++ b/solution/0000-0099/0051.N-Queens/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:DFS(回溯)** +### 方法一:DFS(回溯) 我们定义三个数组 $col$, $dg$ 和 $udg$,分别表示列、正对角线和反对角线上的是否有皇后,如果位置 $(i, j)$ 有皇后,那么 $col[j]$, $dg[i + j]$ 和 $udg[n - i + j]$ 都为 $1$。另外,我们用一个数组 $g$ 记录当前棋盘的状态,初始时 $g$ 中的所有元素都是 `'.'`。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def solveNQueens(self, n: int) -> List[List[str]]: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List> ans = new ArrayList<>(); @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +159,6 @@ public: }; ``` -### **Go** - ```go func solveNQueens(n int) (ans [][]string) { col := make([]int, n) @@ -210,8 +196,6 @@ func solveNQueens(n int) (ans [][]string) { } ``` -### **TypeScript** - ```ts function solveNQueens(n: number): string[][] { const col: number[] = new Array(n).fill(0); @@ -241,8 +225,6 @@ function solveNQueens(n: number): string[][] { } ``` -### **C#** - ```cs public class Solution { private int n; @@ -282,10 +264,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0051.N-Queens/README_EN.md b/solution/0000-0099/0051.N-Queens/README_EN.md index f3a24727eeda6..bff3e7a92e67a 100644 --- a/solution/0000-0099/0051.N-Queens/README_EN.md +++ b/solution/0000-0099/0051.N-Queens/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: DFS (Backtracking)** +### Solution 1: DFS (Backtracking) We define three arrays $col$, $dg$, and $udg$ to represent whether there is a queen in the column, the main diagonal, and the anti-diagonal, respectively. If there is a queen at position $(i, j)$, then $col[j]$, $dg[i + j]$, and $udg[n - i + j]$ are all $1$. In addition, we use an array $g$ to record the current state of the chessboard, where all elements in $g$ are initially `'.'`. @@ -51,8 +51,6 @@ The time complexity is $O(n^2 \times n!)$, and the space complexity is $O(n)$. H -### **Python3** - ```python class Solution: def solveNQueens(self, n: int) -> List[List[str]]: @@ -77,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List> ans = new ArrayList<>(); @@ -123,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +149,6 @@ public: }; ``` -### **Go** - ```go func solveNQueens(n int) (ans [][]string) { col := make([]int, n) @@ -194,8 +186,6 @@ func solveNQueens(n int) (ans [][]string) { } ``` -### **TypeScript** - ```ts function solveNQueens(n: number): string[][] { const col: number[] = new Array(n).fill(0); @@ -225,8 +215,6 @@ function solveNQueens(n: number): string[][] { } ``` -### **C#** - ```cs public class Solution { private int n; @@ -266,10 +254,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0052.N-Queens II/README.md b/solution/0000-0099/0052.N-Queens II/README.md index ab98daff541a4..9c81b49000cb3 100644 --- a/solution/0000-0099/0052.N-Queens II/README.md +++ b/solution/0000-0099/0052.N-Queens II/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:回溯** +### 方法一:回溯 我们设计一个函数 $dfs(i)$,表示从第 $i$ 行开始搜索,搜索到的结果累加到答案中。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def totalNQueens(self, n: int) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int n; @@ -127,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func totalNQueens(n int) (ans int) { cols := [10]bool{} @@ -184,8 +170,6 @@ func totalNQueens(n int) (ans int) { } ``` -### **TypeScript** - ```ts function totalNQueens(n: number): number { const cols: boolean[] = Array(10).fill(false); @@ -212,10 +196,6 @@ function totalNQueens(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0052.N-Queens II/README_EN.md b/solution/0000-0099/0052.N-Queens II/README_EN.md index 2e2dcf09f72a1..3d5f0cf9f2351 100644 --- a/solution/0000-0099/0052.N-Queens II/README_EN.md +++ b/solution/0000-0099/0052.N-Queens II/README_EN.md @@ -33,7 +33,7 @@ ## Solutions -**Solution 1: Backtracking** +### Solution 1: Backtracking We design a function $dfs(i)$, which represents starting the search from the $i$th row, and the results of the search are added to the answer. @@ -49,8 +49,6 @@ The time complexity is $O(n!)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def totalNQueens(self, n: int) -> int: @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int n; @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go func totalNQueens(n int) (ans int) { cols := [10]bool{} @@ -170,8 +162,6 @@ func totalNQueens(n int) (ans int) { } ``` -### **TypeScript** - ```ts function totalNQueens(n: number): number { const cols: boolean[] = Array(10).fill(false); @@ -198,10 +188,6 @@ function totalNQueens(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0053.Maximum Subarray/README.md b/solution/0000-0099/0053.Maximum Subarray/README.md index ee62aec238a1e..e083838d5b360 100644 --- a/solution/0000-0099/0053.Maximum Subarray/README.md +++ b/solution/0000-0099/0053.Maximum Subarray/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示以元素 $nums[i]$ 为结尾的连续子数组的最大和,初始时 $f[0] = nums[0]$,那么最终我们要求的答案即为 $\max_{0 \leq i < n} f[i]$。 @@ -73,10 +71,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxSubArray(self, nums: List[int]) -> int: @@ -87,37 +81,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxSubArray(self, nums: List[int]) -> int: - def crossMaxSub(nums, left, mid, right): - lsum = rsum = 0 - lmx = rmx = -inf - for i in range(mid, left - 1, -1): - lsum += nums[i] - lmx = max(lmx, lsum) - for i in range(mid + 1, right + 1): - rsum += nums[i] - rmx = max(rmx, rsum) - return lmx + rmx - - def maxSub(nums, left, right): - if left == right: - return nums[left] - mid = (left + right) >> 1 - lsum = maxSub(nums, left, mid) - rsum = maxSub(nums, mid + 1, right) - csum = crossMaxSub(nums, left, mid, right) - return max(lsum, rsum, csum) - - left, right = 0, len(nums) - 1 - return maxSub(nums, left, right) -``` - -### **Java** - - - ```java class Solution { public int maxSubArray(int[] nums) { @@ -131,40 +94,6 @@ class Solution { } ``` -```java -class Solution { - public int maxSubArray(int[] nums) { - return maxSub(nums, 0, nums.length - 1); - } - - private int maxSub(int[] nums, int left, int right) { - if (left == right) { - return nums[left]; - } - int mid = (left + right) >>> 1; - int lsum = maxSub(nums, left, mid); - int rsum = maxSub(nums, mid + 1, right); - return Math.max(Math.max(lsum, rsum), crossMaxSub(nums, left, mid, right)); - } - - private int crossMaxSub(int[] nums, int left, int mid, int right) { - int lsum = 0, rsum = 0; - int lmx = Integer.MIN_VALUE, rmx = Integer.MIN_VALUE; - for (int i = mid; i >= left; --i) { - lsum += nums[i]; - lmx = Math.max(lmx, lsum); - } - for (int i = mid + 1; i <= right; ++i) { - rsum += nums[i]; - rmx = Math.max(rmx, rsum); - } - return lmx + rmx; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -179,8 +108,6 @@ public: }; ``` -### **Go** - ```go func maxSubArray(nums []int) int { ans, f := nums[0], nums[0] @@ -192,8 +119,6 @@ func maxSubArray(nums []int) int { } ``` -### **TypeScript** - ```ts function maxSubArray(nums: number[]): number { let [ans, f] = [nums[0], nums[0]]; @@ -205,7 +130,20 @@ function maxSubArray(nums: number[]): number { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn max_sub_array(nums: Vec) -> i32 { + let n = nums.len(); + let mut ans = nums[0]; + let mut f = nums[0]; + for i in 1..n { + f = f.max(0) + nums[i]; + ans = ans.max(f); + } + ans + } +} +``` ```js /** @@ -222,8 +160,6 @@ var maxSubArray = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public int MaxSubArray(int[] nums) { @@ -237,27 +173,71 @@ public class Solution { } ``` -### **Rust** + -```rust -impl Solution { - pub fn max_sub_array(nums: Vec) -> i32 { - let n = nums.len(); - let mut ans = nums[0]; - let mut f = nums[0]; - for i in 1..n { - f = f.max(0) + nums[i]; - ans = ans.max(f); - } - ans - } -} -``` +### 方法二 -### **...** + +```python +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + def crossMaxSub(nums, left, mid, right): + lsum = rsum = 0 + lmx = rmx = -inf + for i in range(mid, left - 1, -1): + lsum += nums[i] + lmx = max(lmx, lsum) + for i in range(mid + 1, right + 1): + rsum += nums[i] + rmx = max(rmx, rsum) + return lmx + rmx + + def maxSub(nums, left, right): + if left == right: + return nums[left] + mid = (left + right) >> 1 + lsum = maxSub(nums, left, mid) + rsum = maxSub(nums, mid + 1, right) + csum = crossMaxSub(nums, left, mid, right) + return max(lsum, rsum, csum) + + left, right = 0, len(nums) - 1 + return maxSub(nums, left, right) ``` +```java +class Solution { + public int maxSubArray(int[] nums) { + return maxSub(nums, 0, nums.length - 1); + } + + private int maxSub(int[] nums, int left, int right) { + if (left == right) { + return nums[left]; + } + int mid = (left + right) >>> 1; + int lsum = maxSub(nums, left, mid); + int rsum = maxSub(nums, mid + 1, right); + return Math.max(Math.max(lsum, rsum), crossMaxSub(nums, left, mid, right)); + } + + private int crossMaxSub(int[] nums, int left, int mid, int right) { + int lsum = 0, rsum = 0; + int lmx = Integer.MIN_VALUE, rmx = Integer.MIN_VALUE; + for (int i = mid; i >= left; --i) { + lsum += nums[i]; + lmx = Math.max(lmx, lsum); + } + for (int i = mid + 1; i <= right; ++i) { + rsum += nums[i]; + rmx = Math.max(rmx, rsum); + } + return lmx + rmx; + } +} ``` + + diff --git a/solution/0000-0099/0053.Maximum Subarray/README_EN.md b/solution/0000-0099/0053.Maximum Subarray/README_EN.md index 947cd995ab9d5..912024ba4963c 100644 --- a/solution/0000-0099/0053.Maximum Subarray/README_EN.md +++ b/solution/0000-0099/0053.Maximum Subarray/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i]$ to represent the maximum sum of the continuous subarray ending with the element $nums[i]$. Initially, $f[0] = nums[0]$. The final answer we are looking for is $\max_{0 \leq i < n} f[i]$. @@ -66,8 +66,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. We o -### **Python3** - ```python class Solution: def maxSubArray(self, nums: List[int]) -> int: @@ -78,35 +76,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxSubArray(self, nums: List[int]) -> int: - def crossMaxSub(nums, left, mid, right): - lsum = rsum = 0 - lmx = rmx = -inf - for i in range(mid, left - 1, -1): - lsum += nums[i] - lmx = max(lmx, lsum) - for i in range(mid + 1, right + 1): - rsum += nums[i] - rmx = max(rmx, rsum) - return lmx + rmx - - def maxSub(nums, left, right): - if left == right: - return nums[left] - mid = (left + right) >> 1 - lsum = maxSub(nums, left, mid) - rsum = maxSub(nums, mid + 1, right) - csum = crossMaxSub(nums, left, mid, right) - return max(lsum, rsum, csum) - - left, right = 0, len(nums) - 1 - return maxSub(nums, left, right) -``` - -### **Java** - ```java class Solution { public int maxSubArray(int[] nums) { @@ -120,40 +89,6 @@ class Solution { } ``` -```java -class Solution { - public int maxSubArray(int[] nums) { - return maxSub(nums, 0, nums.length - 1); - } - - private int maxSub(int[] nums, int left, int right) { - if (left == right) { - return nums[left]; - } - int mid = (left + right) >>> 1; - int lsum = maxSub(nums, left, mid); - int rsum = maxSub(nums, mid + 1, right); - return Math.max(Math.max(lsum, rsum), crossMaxSub(nums, left, mid, right)); - } - - private int crossMaxSub(int[] nums, int left, int mid, int right) { - int lsum = 0, rsum = 0; - int lmx = Integer.MIN_VALUE, rmx = Integer.MIN_VALUE; - for (int i = mid; i >= left; --i) { - lsum += nums[i]; - lmx = Math.max(lmx, lsum); - } - for (int i = mid + 1; i <= right; ++i) { - rsum += nums[i]; - rmx = Math.max(rmx, rsum); - } - return lmx + rmx; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -168,8 +103,6 @@ public: }; ``` -### **Go** - ```go func maxSubArray(nums []int) int { ans, f := nums[0], nums[0] @@ -181,8 +114,6 @@ func maxSubArray(nums []int) int { } ``` -### **TypeScript** - ```ts function maxSubArray(nums: number[]): number { let [ans, f] = [nums[0], nums[0]]; @@ -194,7 +125,20 @@ function maxSubArray(nums: number[]): number { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn max_sub_array(nums: Vec) -> i32 { + let n = nums.len(); + let mut ans = nums[0]; + let mut f = nums[0]; + for i in 1..n { + f = f.max(0) + nums[i]; + ans = ans.max(f); + } + ans + } +} +``` ```js /** @@ -211,8 +155,6 @@ var maxSubArray = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public int MaxSubArray(int[] nums) { @@ -226,27 +168,71 @@ public class Solution { } ``` -### **Rust** + -```rust -impl Solution { - pub fn max_sub_array(nums: Vec) -> i32 { - let n = nums.len(); - let mut ans = nums[0]; - let mut f = nums[0]; - for i in 1..n { - f = f.max(0) + nums[i]; - ans = ans.max(f); - } - ans - } -} -``` +### Solution 2 + + -### **...** +```python +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + def crossMaxSub(nums, left, mid, right): + lsum = rsum = 0 + lmx = rmx = -inf + for i in range(mid, left - 1, -1): + lsum += nums[i] + lmx = max(lmx, lsum) + for i in range(mid + 1, right + 1): + rsum += nums[i] + rmx = max(rmx, rsum) + return lmx + rmx + def maxSub(nums, left, right): + if left == right: + return nums[left] + mid = (left + right) >> 1 + lsum = maxSub(nums, left, mid) + rsum = maxSub(nums, mid + 1, right) + csum = crossMaxSub(nums, left, mid, right) + return max(lsum, rsum, csum) + + left, right = 0, len(nums) - 1 + return maxSub(nums, left, right) ``` +```java +class Solution { + public int maxSubArray(int[] nums) { + return maxSub(nums, 0, nums.length - 1); + } + + private int maxSub(int[] nums, int left, int right) { + if (left == right) { + return nums[left]; + } + int mid = (left + right) >>> 1; + int lsum = maxSub(nums, left, mid); + int rsum = maxSub(nums, mid + 1, right); + return Math.max(Math.max(lsum, rsum), crossMaxSub(nums, left, mid, right)); + } + + private int crossMaxSub(int[] nums, int left, int mid, int right) { + int lsum = 0, rsum = 0; + int lmx = Integer.MIN_VALUE, rmx = Integer.MIN_VALUE; + for (int i = mid; i >= left; --i) { + lsum += nums[i]; + lmx = Math.max(lmx, lsum); + } + for (int i = mid + 1; i <= right; ++i) { + rsum += nums[i]; + rmx = Math.max(rmx, rsum); + } + return lmx + rmx; + } +} ``` + + diff --git a/solution/0000-0099/0054.Spiral Matrix/README.md b/solution/0000-0099/0054.Spiral Matrix/README.md index d2023217ad7ca..6c67ca016af82 100644 --- a/solution/0000-0099/0054.Spiral Matrix/README.md +++ b/solution/0000-0099/0054.Spiral Matrix/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们用 $i$ 和 $j$ 分别表示当前访问到的元素的行和列,用 $k$ 表示当前的方向,用数组或哈希表 $vis$ 记录每个元素是否被访问过。每次我们访问到一个元素后,将其标记为已访问,然后按照当前的方向前进一步,如果前进一步后发现越界或者已经访问过,则改变方向继续前进,直到遍历完整个矩阵。 @@ -47,18 +45,8 @@ 对于访问过的元素,我们也可以将其值加上一个常数 $300$,这样就不需要额外的 $vis$ 数组或哈希表来记录是否访问过了,从而将空间复杂度降低到 $O(1)$。 -**方法二:逐层模拟** - -我们也可以从外往里一圈一圈遍历并存储矩阵元素。 - -时间复杂度 $O(m \times n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。 - -### **Python3** - - - ```python class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: @@ -78,52 +66,6 @@ class Solution: return ans ``` -```python -class Solution: - def spiralOrder(self, matrix: List[List[int]]) -> List[int]: - m, n = len(matrix), len(matrix[0]) - dirs = (0, 1, 0, -1, 0) - i = j = k = 0 - ans = [] - for _ in range(m * n): - ans.append(matrix[i][j]) - matrix[i][j] += 300 - x, y = i + dirs[k], j + dirs[k + 1] - if not 0 <= x < m or not 0 <= y < n or matrix[x][y] > 100: - k = (k + 1) % 4 - i = i + dirs[k] - j = j + dirs[k + 1] - # for i in range(m): - # for j in range(n): - # matrix[i][j] -= 300 - return ans -``` - -```python -class Solution: - def spiralOrder(self, matrix: List[List[int]]) -> List[int]: - m, n = len(matrix), len(matrix[0]) - x1, y1, x2, y2 = 0, 0, m - 1, n - 1 - ans = [] - while x1 <= x2 and y1 <= y2: - for j in range(y1, y2 + 1): - ans.append(matrix[x1][j]) - for i in range(x1 + 1, x2 + 1): - ans.append(matrix[i][y2]) - if x1 < x2 and y1 < y2: - for j in range(y2 - 1, y1 - 1, -1): - ans.append(matrix[x2][j]) - for i in range(x2 - 1, x1, -1): - ans.append(matrix[i][y1]) - x1, y1 = x1 + 1, y1 + 1 - x2, y2 = x2 - 1, y2 - 1 - return ans -``` - -### **Java** - - - ```java class Solution { public List spiralOrder(int[][] matrix) { @@ -147,65 +89,6 @@ class Solution { } ``` -```java -class Solution { - public List spiralOrder(int[][] matrix) { - int m = matrix.length, n = matrix[0].length; - int[] dirs = {0, 1, 0, -1, 0}; - List ans = new ArrayList<>(); - for (int h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { - ans.add(matrix[i][j]); - matrix[i][j] += 300; - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { - k = (k + 1) % 4; - } - i += dirs[k]; - j += dirs[k + 1]; - } - // for (int i = 0; i < m; ++i) { - // for (int j = 0; j < n; ++j) { - // matrix[i][j] -= 300; - // } - // } - return ans; - } -} -``` - -```java -class Solution { - public List spiralOrder(int[][] matrix) { - int m = matrix.length, n = matrix[0].length; - int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; - List ans = new ArrayList<>(); - while (x1 <= x2 && y1 <= y2) { - for (int j = y1; j <= y2; ++j) { - ans.add(matrix[x1][j]); - } - for (int i = x1 + 1; i <= x2; ++i) { - ans.add(matrix[i][y2]); - } - if (x1 < x2 && y1 < y2) { - for (int j = y2 - 1; j >= y1; --j) { - ans.add(matrix[x2][j]); - } - for (int i = x2 - 1; i > x1; --i) { - ans.add(matrix[i][y1]); - } - } - ++x1; - ++y1; - --x2; - --y2; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -231,65 +114,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector spiralOrder(vector>& matrix) { - int m = matrix.size(), n = matrix[0].size(); - int dirs[5] = {0, 1, 0, -1, 0}; - vector ans; - for (int h = m * n, i = 0, j = 0, k = 0; h; --h) { - ans.push_back(matrix[i][j]); - matrix[i][j] += 300; - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { - k = (k + 1) % 4; - } - i += dirs[k]; - j += dirs[k + 1]; - } - // for (int i = 0; i < m; ++i) { - // for (int j = 0; j < n; ++j) { - // matrix[i][j] -= 300; - // } - // } - return ans; - } -}; -``` - -```cpp -class Solution { -public: - vector spiralOrder(vector>& matrix) { - int m = matrix.size(), n = matrix[0].size(); - int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; - vector ans; - while (x1 <= x2 && y1 <= y2) { - for (int j = y1; j <= y2; ++j) { - ans.push_back(matrix[x1][j]); - } - for (int i = x1 + 1; i <= x2; ++i) { - ans.push_back(matrix[i][y2]); - } - if (x1 < x2 && y1 < y2) { - for (int j = y2 - 1; j >= y1; --j) { - ans.push_back(matrix[x2][j]); - } - for (int i = x2 - 1; i > x1; --i) { - ans.push_back(matrix[i][y1]); - } - } - ++x1, ++y1; - --x2, --y2; - } - return ans; - } -}; -``` - -### **Go** - ```go func spiralOrder(matrix [][]int) (ans []int) { m, n := len(matrix), len(matrix[0]) @@ -312,56 +136,28 @@ func spiralOrder(matrix [][]int) (ans []int) { } ``` -```go -func spiralOrder(matrix [][]int) (ans []int) { - m, n := len(matrix), len(matrix[0]) - dirs := [5]int{0, 1, 0, -1, 0} - for h, i, j, k := m*n, 0, 0, 0; h > 0; h-- { - ans = append(ans, matrix[i][j]) - matrix[i][j] += 300 - x, y := i+dirs[k], j+dirs[k+1] - if x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100 { - k = (k + 1) % 4 - } - i, j = i+dirs[k], j+dirs[k+1] - } - // for i, row := range matrix { - // for j := range row { - // matrix[i][j] -= 300 - // } - // } - return -} -``` - -```go -func spiralOrder(matrix [][]int) (ans []int) { - m, n := len(matrix), len(matrix[0]) - x1, y1, x2, y2 := 0, 0, m-1, n-1 - for x1 <= x2 && y1 <= y2 { - for j := y1; j <= y2; j++ { - ans = append(ans, matrix[x1][j]) - } - for i := x1 + 1; i <= x2; i++ { - ans = append(ans, matrix[i][y2]) - } - if x1 < x2 && y1 < y2 { - for j := y2 - 1; j >= y1; j-- { - ans = append(ans, matrix[x2][j]) - } - for i := x2 - 1; i > x1; i-- { - ans = append(ans, matrix[i][y1]) - } - } - x1, y1 = x1+1, y1+1 - x2, y2 = x2-1, y2-1 - } - return +```ts +function spiralOrder(matrix: number[][]): number[] { + const m = matrix.length; + const n = matrix[0].length; + const ans: number[] = []; + const vis = new Array(m).fill(0).map(() => new Array(n).fill(false)); + const dirs = [0, 1, 0, -1, 0]; + for (let h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { + ans.push(matrix[i][j]); + vis[i][j] = true; + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n || vis[x][y]) { + k = (k + 1) % 4; + } + i += dirs[k]; + j += dirs[k + 1]; + } + return ans; } ``` -### **Rust** - ```rust impl Solution { pub fn spiral_order(matrix: Vec>) -> Vec { @@ -400,8 +196,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[][]} matrix @@ -428,75 +222,6 @@ var spiralOrder = function (matrix) { }; ``` -```js -/** - * @param {number[][]} matrix - * @return {number[]} - */ -var spiralOrder = function (matrix) { - const m = matrix.length; - const n = matrix[0].length; - const ans = []; - const dirs = [0, 1, 0, -1, 0]; - for (let h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { - ans.push(matrix[i][j]); - matrix[i][j] += 300; - const x = i + dirs[k]; - const y = j + dirs[k + 1]; - if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { - k = (k + 1) % 4; - } - i += dirs[k]; - j += dirs[k + 1]; - } - // for (let i = 0; i < m; ++i) { - // for (let j = 0; j < n; ++j) { - // matrix[i][j] -= 300; - // } - // } - return ans; -}; -``` - -```js -/** - * @param {number[][]} matrix - * @return {number[]} - */ -var spiralOrder = function (matrix) { - const m = matrix.length; - const n = matrix[0].length; - let x1 = 0; - let y1 = 0; - let x2 = m - 1; - let y2 = n - 1; - const ans = []; - while (x1 <= x2 && y1 <= y2) { - for (let j = y1; j <= y2; ++j) { - ans.push(matrix[x1][j]); - } - for (let i = x1 + 1; i <= x2; ++i) { - ans.push(matrix[i][y2]); - } - if (x1 < x2 && y1 < y2) { - for (let j = y2 - 1; j >= y1; --j) { - ans.push(matrix[x2][j]); - } - for (let i = x2 - 1; i > x1; --i) { - ans.push(matrix[i][y1]); - } - } - ++x1; - ++y1; - --x2; - --y2; - } - return ans; -}; -``` - -### **C#** - ```cs public class Solution { public IList SpiralOrder(int[][] matrix) { @@ -519,14 +244,45 @@ public class Solution { } ``` -```cs -public class Solution { - public IList SpiralOrder(int[][] matrix) { - int m = matrix.Length, n = matrix[0].Length; - int[] dirs = new int[] {0, 1, 0, -1, 0}; - IList ans = new List(); + + +### 方法二:逐层模拟 + +我们也可以从外往里一圈一圈遍历并存储矩阵元素。 + +时间复杂度 $O(m \times n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。 + + + +```python +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + m, n = len(matrix), len(matrix[0]) + dirs = (0, 1, 0, -1, 0) + i = j = k = 0 + ans = [] + for _ in range(m * n): + ans.append(matrix[i][j]) + matrix[i][j] += 300 + x, y = i + dirs[k], j + dirs[k + 1] + if not 0 <= x < m or not 0 <= y < n or matrix[x][y] > 100: + k = (k + 1) % 4 + i = i + dirs[k] + j = j + dirs[k + 1] + # for i in range(m): + # for j in range(n): + # matrix[i][j] -= 300 + return ans +``` + +```java +class Solution { + public List spiralOrder(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + int[] dirs = {0, 1, 0, -1, 0}; + List ans = new ArrayList<>(); for (int h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { - ans.Add(matrix[i][j]); + ans.add(matrix[i][j]); matrix[i][j] += 300; int x = i + dirs[k], y = j + dirs[k + 1]; if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { @@ -535,76 +291,100 @@ public class Solution { i += dirs[k]; j += dirs[k + 1]; } - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - matrix[i][j] -= 300; - } - } + // for (int i = 0; i < m; ++i) { + // for (int j = 0; j < n; ++j) { + // matrix[i][j] -= 300; + // } + // } return ans; } } ``` -```cs -public class Solution { - public IList SpiralOrder(int[][] matrix) { - int m = matrix.Length, n = matrix[0].Length; - int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; - IList ans = new List(); - while (x1 <= x2 && y1 <= y2) { - for (int j = y1; j <= y2; ++j) { - ans.Add(matrix[x1][j]); - } - for (int i = x1 + 1; i <= x2; ++i) { - ans.Add(matrix[i][y2]); - } - if (x1 < x2 && y1 < y2) { - for (int j = y2 - 1; j >= y1; --j) { - ans.Add(matrix[x2][j]); - } - for (int i = x2 - 1; i > x1; --i) { - ans.Add(matrix[i][y1]); - } +```cpp +class Solution { +public: + vector spiralOrder(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + int dirs[5] = {0, 1, 0, -1, 0}; + vector ans; + for (int h = m * n, i = 0, j = 0, k = 0; h; --h) { + ans.push_back(matrix[i][j]); + matrix[i][j] += 300; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { + k = (k + 1) % 4; } - ++x1; - ++y1; - --x2; - --y2; + i += dirs[k]; + j += dirs[k + 1]; } + // for (int i = 0; i < m; ++i) { + // for (int j = 0; j < n; ++j) { + // matrix[i][j] -= 300; + // } + // } return ans; } -} +}; ``` -### **TypeScript** +```go +func spiralOrder(matrix [][]int) (ans []int) { + m, n := len(matrix), len(matrix[0]) + dirs := [5]int{0, 1, 0, -1, 0} + for h, i, j, k := m*n, 0, 0, 0; h > 0; h-- { + ans = append(ans, matrix[i][j]) + matrix[i][j] += 300 + x, y := i+dirs[k], j+dirs[k+1] + if x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100 { + k = (k + 1) % 4 + } + i, j = i+dirs[k], j+dirs[k+1] + } + // for i, row := range matrix { + // for j := range row { + // matrix[i][j] -= 300 + // } + // } + return +} +``` ```ts function spiralOrder(matrix: number[][]): number[] { const m = matrix.length; const n = matrix[0].length; const ans: number[] = []; - const vis = new Array(m).fill(0).map(() => new Array(n).fill(false)); const dirs = [0, 1, 0, -1, 0]; for (let h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { ans.push(matrix[i][j]); - vis[i][j] = true; + matrix[i][j] += 300; const x = i + dirs[k]; const y = j + dirs[k + 1]; - if (x < 0 || x >= m || y < 0 || y >= n || vis[x][y]) { + if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { k = (k + 1) % 4; } i += dirs[k]; j += dirs[k + 1]; } + // for (let i = 0; i < m; ++i) { + // for (let j = 0; j < n; ++j) { + // matrix[i][j] -= 300; + // } + // } return ans; } ``` -```ts -function spiralOrder(matrix: number[][]): number[] { +```js +/** + * @param {number[][]} matrix + * @return {number[]} + */ +var spiralOrder = function (matrix) { const m = matrix.length; const n = matrix[0].length; - const ans: number[] = []; + const ans = []; const dirs = [0, 1, 0, -1, 0]; for (let h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { ans.push(matrix[i][j]); @@ -623,6 +403,146 @@ function spiralOrder(matrix: number[][]): number[] { // } // } return ans; +}; +``` + +```cs +public class Solution { + public IList SpiralOrder(int[][] matrix) { + int m = matrix.Length, n = matrix[0].Length; + int[] dirs = new int[] {0, 1, 0, -1, 0}; + IList ans = new List(); + for (int h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { + ans.Add(matrix[i][j]); + matrix[i][j] += 300; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { + k = (k + 1) % 4; + } + i += dirs[k]; + j += dirs[k + 1]; + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + matrix[i][j] -= 300; + } + } + return ans; + } +} +``` + + + +### 方法三 + + + +```python +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + m, n = len(matrix), len(matrix[0]) + x1, y1, x2, y2 = 0, 0, m - 1, n - 1 + ans = [] + while x1 <= x2 and y1 <= y2: + for j in range(y1, y2 + 1): + ans.append(matrix[x1][j]) + for i in range(x1 + 1, x2 + 1): + ans.append(matrix[i][y2]) + if x1 < x2 and y1 < y2: + for j in range(y2 - 1, y1 - 1, -1): + ans.append(matrix[x2][j]) + for i in range(x2 - 1, x1, -1): + ans.append(matrix[i][y1]) + x1, y1 = x1 + 1, y1 + 1 + x2, y2 = x2 - 1, y2 - 1 + return ans +``` + +```java +class Solution { + public List spiralOrder(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; + List ans = new ArrayList<>(); + while (x1 <= x2 && y1 <= y2) { + for (int j = y1; j <= y2; ++j) { + ans.add(matrix[x1][j]); + } + for (int i = x1 + 1; i <= x2; ++i) { + ans.add(matrix[i][y2]); + } + if (x1 < x2 && y1 < y2) { + for (int j = y2 - 1; j >= y1; --j) { + ans.add(matrix[x2][j]); + } + for (int i = x2 - 1; i > x1; --i) { + ans.add(matrix[i][y1]); + } + } + ++x1; + ++y1; + --x2; + --y2; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector spiralOrder(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; + vector ans; + while (x1 <= x2 && y1 <= y2) { + for (int j = y1; j <= y2; ++j) { + ans.push_back(matrix[x1][j]); + } + for (int i = x1 + 1; i <= x2; ++i) { + ans.push_back(matrix[i][y2]); + } + if (x1 < x2 && y1 < y2) { + for (int j = y2 - 1; j >= y1; --j) { + ans.push_back(matrix[x2][j]); + } + for (int i = x2 - 1; i > x1; --i) { + ans.push_back(matrix[i][y1]); + } + } + ++x1, ++y1; + --x2, --y2; + } + return ans; + } +}; +``` + +```go +func spiralOrder(matrix [][]int) (ans []int) { + m, n := len(matrix), len(matrix[0]) + x1, y1, x2, y2 := 0, 0, m-1, n-1 + for x1 <= x2 && y1 <= y2 { + for j := y1; j <= y2; j++ { + ans = append(ans, matrix[x1][j]) + } + for i := x1 + 1; i <= x2; i++ { + ans = append(ans, matrix[i][y2]) + } + if x1 < x2 && y1 < y2 { + for j := y2 - 1; j >= y1; j-- { + ans = append(ans, matrix[x2][j]) + } + for i := x2 - 1; i > x1; i-- { + ans = append(ans, matrix[i][y1]) + } + } + x1, y1 = x1+1, y1+1 + x2, y2 = x2-1, y2-1 + } + return } ``` @@ -659,10 +579,74 @@ function spiralOrder(matrix: number[][]): number[] { } ``` -### **...** - +```js +/** + * @param {number[][]} matrix + * @return {number[]} + */ +var spiralOrder = function (matrix) { + const m = matrix.length; + const n = matrix[0].length; + let x1 = 0; + let y1 = 0; + let x2 = m - 1; + let y2 = n - 1; + const ans = []; + while (x1 <= x2 && y1 <= y2) { + for (let j = y1; j <= y2; ++j) { + ans.push(matrix[x1][j]); + } + for (let i = x1 + 1; i <= x2; ++i) { + ans.push(matrix[i][y2]); + } + if (x1 < x2 && y1 < y2) { + for (let j = y2 - 1; j >= y1; --j) { + ans.push(matrix[x2][j]); + } + for (let i = x2 - 1; i > x1; --i) { + ans.push(matrix[i][y1]); + } + } + ++x1; + ++y1; + --x2; + --y2; + } + return ans; +}; ``` +```cs +public class Solution { + public IList SpiralOrder(int[][] matrix) { + int m = matrix.Length, n = matrix[0].Length; + int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; + IList ans = new List(); + while (x1 <= x2 && y1 <= y2) { + for (int j = y1; j <= y2; ++j) { + ans.Add(matrix[x1][j]); + } + for (int i = x1 + 1; i <= x2; ++i) { + ans.Add(matrix[i][y2]); + } + if (x1 < x2 && y1 < y2) { + for (int j = y2 - 1; j >= y1; --j) { + ans.Add(matrix[x2][j]); + } + for (int i = x2 - 1; i > x1; --i) { + ans.Add(matrix[i][y1]); + } + } + ++x1; + ++y1; + --x2; + --y2; + } + return ans; + } +} ``` + + diff --git a/solution/0000-0099/0054.Spiral Matrix/README_EN.md b/solution/0000-0099/0054.Spiral Matrix/README_EN.md index 768d4a2a0c47f..4531631ecab86 100644 --- a/solution/0000-0099/0054.Spiral Matrix/README_EN.md +++ b/solution/0000-0099/0054.Spiral Matrix/README_EN.md @@ -33,7 +33,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We use $i$ and $j$ to represent the row and column of the current element, use $k$ to represent the current direction, and use an array or hash table $vis$ to record whether each element has been visited. Each time we visit an element, we mark it as visited, then move forward in the current direction. If we find that it is out of bounds or has been visited after moving forward, we change the direction and continue to move forward until the entire matrix is traversed. @@ -41,16 +41,8 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times For visited elements, we can also add a constant $300$ to their values, so we don't need an extra $vis$ array or hash table to record whether they have been visited, thereby reducing the space complexity to $O(1)$. -**Solution 2: Layer-by-layer Simulation** - -We can also traverse and store the matrix elements from the outside to the inside, layer by layer. - -The time complexity is $O(m \times n)$, and the space complexity is $O(1)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, respectively. - -### **Python3** - ```python class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: @@ -70,50 +62,6 @@ class Solution: return ans ``` -```python -class Solution: - def spiralOrder(self, matrix: List[List[int]]) -> List[int]: - m, n = len(matrix), len(matrix[0]) - dirs = (0, 1, 0, -1, 0) - i = j = k = 0 - ans = [] - for _ in range(m * n): - ans.append(matrix[i][j]) - matrix[i][j] += 300 - x, y = i + dirs[k], j + dirs[k + 1] - if not 0 <= x < m or not 0 <= y < n or matrix[x][y] > 100: - k = (k + 1) % 4 - i = i + dirs[k] - j = j + dirs[k + 1] - # for i in range(m): - # for j in range(n): - # matrix[i][j] -= 300 - return ans -``` - -```python -class Solution: - def spiralOrder(self, matrix: List[List[int]]) -> List[int]: - m, n = len(matrix), len(matrix[0]) - x1, y1, x2, y2 = 0, 0, m - 1, n - 1 - ans = [] - while x1 <= x2 and y1 <= y2: - for j in range(y1, y2 + 1): - ans.append(matrix[x1][j]) - for i in range(x1 + 1, x2 + 1): - ans.append(matrix[i][y2]) - if x1 < x2 and y1 < y2: - for j in range(y2 - 1, y1 - 1, -1): - ans.append(matrix[x2][j]) - for i in range(x2 - 1, x1, -1): - ans.append(matrix[i][y1]) - x1, y1 = x1 + 1, y1 + 1 - x2, y2 = x2 - 1, y2 - 1 - return ans -``` - -### **Java** - ```java class Solution { public List spiralOrder(int[][] matrix) { @@ -137,65 +85,6 @@ class Solution { } ``` -```java -class Solution { - public List spiralOrder(int[][] matrix) { - int m = matrix.length, n = matrix[0].length; - int[] dirs = {0, 1, 0, -1, 0}; - List ans = new ArrayList<>(); - for (int h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { - ans.add(matrix[i][j]); - matrix[i][j] += 300; - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { - k = (k + 1) % 4; - } - i += dirs[k]; - j += dirs[k + 1]; - } - // for (int i = 0; i < m; ++i) { - // for (int j = 0; j < n; ++j) { - // matrix[i][j] -= 300; - // } - // } - return ans; - } -} -``` - -```java -class Solution { - public List spiralOrder(int[][] matrix) { - int m = matrix.length, n = matrix[0].length; - int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; - List ans = new ArrayList<>(); - while (x1 <= x2 && y1 <= y2) { - for (int j = y1; j <= y2; ++j) { - ans.add(matrix[x1][j]); - } - for (int i = x1 + 1; i <= x2; ++i) { - ans.add(matrix[i][y2]); - } - if (x1 < x2 && y1 < y2) { - for (int j = y2 - 1; j >= y1; --j) { - ans.add(matrix[x2][j]); - } - for (int i = x2 - 1; i > x1; --i) { - ans.add(matrix[i][y1]); - } - } - ++x1; - ++y1; - --x2; - --y2; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -221,65 +110,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector spiralOrder(vector>& matrix) { - int m = matrix.size(), n = matrix[0].size(); - int dirs[5] = {0, 1, 0, -1, 0}; - vector ans; - for (int h = m * n, i = 0, j = 0, k = 0; h; --h) { - ans.push_back(matrix[i][j]); - matrix[i][j] += 300; - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { - k = (k + 1) % 4; - } - i += dirs[k]; - j += dirs[k + 1]; - } - // for (int i = 0; i < m; ++i) { - // for (int j = 0; j < n; ++j) { - // matrix[i][j] -= 300; - // } - // } - return ans; - } -}; -``` - -```cpp -class Solution { -public: - vector spiralOrder(vector>& matrix) { - int m = matrix.size(), n = matrix[0].size(); - int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; - vector ans; - while (x1 <= x2 && y1 <= y2) { - for (int j = y1; j <= y2; ++j) { - ans.push_back(matrix[x1][j]); - } - for (int i = x1 + 1; i <= x2; ++i) { - ans.push_back(matrix[i][y2]); - } - if (x1 < x2 && y1 < y2) { - for (int j = y2 - 1; j >= y1; --j) { - ans.push_back(matrix[x2][j]); - } - for (int i = x2 - 1; i > x1; --i) { - ans.push_back(matrix[i][y1]); - } - } - ++x1, ++y1; - --x2, --y2; - } - return ans; - } -}; -``` - -### **Go** - ```go func spiralOrder(matrix [][]int) (ans []int) { m, n := len(matrix), len(matrix[0]) @@ -302,56 +132,28 @@ func spiralOrder(matrix [][]int) (ans []int) { } ``` -```go -func spiralOrder(matrix [][]int) (ans []int) { - m, n := len(matrix), len(matrix[0]) - dirs := [5]int{0, 1, 0, -1, 0} - for h, i, j, k := m*n, 0, 0, 0; h > 0; h-- { - ans = append(ans, matrix[i][j]) - matrix[i][j] += 300 - x, y := i+dirs[k], j+dirs[k+1] - if x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100 { - k = (k + 1) % 4 - } - i, j = i+dirs[k], j+dirs[k+1] - } - // for i, row := range matrix { - // for j := range row { - // matrix[i][j] -= 300 - // } - // } - return -} -``` - -```go -func spiralOrder(matrix [][]int) (ans []int) { - m, n := len(matrix), len(matrix[0]) - x1, y1, x2, y2 := 0, 0, m-1, n-1 - for x1 <= x2 && y1 <= y2 { - for j := y1; j <= y2; j++ { - ans = append(ans, matrix[x1][j]) - } - for i := x1 + 1; i <= x2; i++ { - ans = append(ans, matrix[i][y2]) - } - if x1 < x2 && y1 < y2 { - for j := y2 - 1; j >= y1; j-- { - ans = append(ans, matrix[x2][j]) - } - for i := x2 - 1; i > x1; i-- { - ans = append(ans, matrix[i][y1]) - } - } - x1, y1 = x1+1, y1+1 - x2, y2 = x2-1, y2-1 - } - return +```ts +function spiralOrder(matrix: number[][]): number[] { + const m = matrix.length; + const n = matrix[0].length; + const ans: number[] = []; + const vis = new Array(m).fill(0).map(() => new Array(n).fill(false)); + const dirs = [0, 1, 0, -1, 0]; + for (let h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { + ans.push(matrix[i][j]); + vis[i][j] = true; + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n || vis[x][y]) { + k = (k + 1) % 4; + } + i += dirs[k]; + j += dirs[k + 1]; + } + return ans; } ``` -### **Rust** - ```rust impl Solution { pub fn spiral_order(matrix: Vec>) -> Vec { @@ -390,8 +192,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[][]} matrix @@ -418,75 +218,6 @@ var spiralOrder = function (matrix) { }; ``` -```js -/** - * @param {number[][]} matrix - * @return {number[]} - */ -var spiralOrder = function (matrix) { - const m = matrix.length; - const n = matrix[0].length; - const ans = []; - const dirs = [0, 1, 0, -1, 0]; - for (let h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { - ans.push(matrix[i][j]); - matrix[i][j] += 300; - const x = i + dirs[k]; - const y = j + dirs[k + 1]; - if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { - k = (k + 1) % 4; - } - i += dirs[k]; - j += dirs[k + 1]; - } - // for (let i = 0; i < m; ++i) { - // for (let j = 0; j < n; ++j) { - // matrix[i][j] -= 300; - // } - // } - return ans; -}; -``` - -```js -/** - * @param {number[][]} matrix - * @return {number[]} - */ -var spiralOrder = function (matrix) { - const m = matrix.length; - const n = matrix[0].length; - let x1 = 0; - let y1 = 0; - let x2 = m - 1; - let y2 = n - 1; - const ans = []; - while (x1 <= x2 && y1 <= y2) { - for (let j = y1; j <= y2; ++j) { - ans.push(matrix[x1][j]); - } - for (let i = x1 + 1; i <= x2; ++i) { - ans.push(matrix[i][y2]); - } - if (x1 < x2 && y1 < y2) { - for (let j = y2 - 1; j >= y1; --j) { - ans.push(matrix[x2][j]); - } - for (let i = x2 - 1; i > x1; --i) { - ans.push(matrix[i][y1]); - } - } - ++x1; - ++y1; - --x2; - --y2; - } - return ans; -}; -``` - -### **C#** - ```cs public class Solution { public IList SpiralOrder(int[][] matrix) { @@ -509,14 +240,45 @@ public class Solution { } ``` -```cs -public class Solution { - public IList SpiralOrder(int[][] matrix) { - int m = matrix.Length, n = matrix[0].Length; - int[] dirs = new int[] {0, 1, 0, -1, 0}; - IList ans = new List(); + + +### Solution 2: Layer-by-layer Simulation + +We can also traverse and store the matrix elements from the outside to the inside, layer by layer. + +The time complexity is $O(m \times n)$, and the space complexity is $O(1)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, respectively. + + + +```python +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + m, n = len(matrix), len(matrix[0]) + dirs = (0, 1, 0, -1, 0) + i = j = k = 0 + ans = [] + for _ in range(m * n): + ans.append(matrix[i][j]) + matrix[i][j] += 300 + x, y = i + dirs[k], j + dirs[k + 1] + if not 0 <= x < m or not 0 <= y < n or matrix[x][y] > 100: + k = (k + 1) % 4 + i = i + dirs[k] + j = j + dirs[k + 1] + # for i in range(m): + # for j in range(n): + # matrix[i][j] -= 300 + return ans +``` + +```java +class Solution { + public List spiralOrder(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + int[] dirs = {0, 1, 0, -1, 0}; + List ans = new ArrayList<>(); for (int h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { - ans.Add(matrix[i][j]); + ans.add(matrix[i][j]); matrix[i][j] += 300; int x = i + dirs[k], y = j + dirs[k + 1]; if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { @@ -525,76 +287,100 @@ public class Solution { i += dirs[k]; j += dirs[k + 1]; } - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - matrix[i][j] -= 300; - } - } + // for (int i = 0; i < m; ++i) { + // for (int j = 0; j < n; ++j) { + // matrix[i][j] -= 300; + // } + // } return ans; } } ``` -```cs -public class Solution { - public IList SpiralOrder(int[][] matrix) { - int m = matrix.Length, n = matrix[0].Length; - int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; - IList ans = new List(); - while (x1 <= x2 && y1 <= y2) { - for (int j = y1; j <= y2; ++j) { - ans.Add(matrix[x1][j]); - } - for (int i = x1 + 1; i <= x2; ++i) { - ans.Add(matrix[i][y2]); - } - if (x1 < x2 && y1 < y2) { - for (int j = y2 - 1; j >= y1; --j) { - ans.Add(matrix[x2][j]); - } - for (int i = x2 - 1; i > x1; --i) { - ans.Add(matrix[i][y1]); - } +```cpp +class Solution { +public: + vector spiralOrder(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + int dirs[5] = {0, 1, 0, -1, 0}; + vector ans; + for (int h = m * n, i = 0, j = 0, k = 0; h; --h) { + ans.push_back(matrix[i][j]); + matrix[i][j] += 300; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { + k = (k + 1) % 4; } - ++x1; - ++y1; - --x2; - --y2; + i += dirs[k]; + j += dirs[k + 1]; } + // for (int i = 0; i < m; ++i) { + // for (int j = 0; j < n; ++j) { + // matrix[i][j] -= 300; + // } + // } return ans; } -} +}; ``` -### **TypeScript** +```go +func spiralOrder(matrix [][]int) (ans []int) { + m, n := len(matrix), len(matrix[0]) + dirs := [5]int{0, 1, 0, -1, 0} + for h, i, j, k := m*n, 0, 0, 0; h > 0; h-- { + ans = append(ans, matrix[i][j]) + matrix[i][j] += 300 + x, y := i+dirs[k], j+dirs[k+1] + if x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100 { + k = (k + 1) % 4 + } + i, j = i+dirs[k], j+dirs[k+1] + } + // for i, row := range matrix { + // for j := range row { + // matrix[i][j] -= 300 + // } + // } + return +} +``` ```ts function spiralOrder(matrix: number[][]): number[] { const m = matrix.length; const n = matrix[0].length; const ans: number[] = []; - const vis = new Array(m).fill(0).map(() => new Array(n).fill(false)); const dirs = [0, 1, 0, -1, 0]; for (let h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { ans.push(matrix[i][j]); - vis[i][j] = true; + matrix[i][j] += 300; const x = i + dirs[k]; const y = j + dirs[k + 1]; - if (x < 0 || x >= m || y < 0 || y >= n || vis[x][y]) { + if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { k = (k + 1) % 4; } i += dirs[k]; j += dirs[k + 1]; } + // for (let i = 0; i < m; ++i) { + // for (let j = 0; j < n; ++j) { + // matrix[i][j] -= 300; + // } + // } return ans; } ``` -```ts -function spiralOrder(matrix: number[][]): number[] { +```js +/** + * @param {number[][]} matrix + * @return {number[]} + */ +var spiralOrder = function (matrix) { const m = matrix.length; const n = matrix[0].length; - const ans: number[] = []; + const ans = []; const dirs = [0, 1, 0, -1, 0]; for (let h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { ans.push(matrix[i][j]); @@ -613,6 +399,146 @@ function spiralOrder(matrix: number[][]): number[] { // } // } return ans; +}; +``` + +```cs +public class Solution { + public IList SpiralOrder(int[][] matrix) { + int m = matrix.Length, n = matrix[0].Length; + int[] dirs = new int[] {0, 1, 0, -1, 0}; + IList ans = new List(); + for (int h = m * n, i = 0, j = 0, k = 0; h > 0; --h) { + ans.Add(matrix[i][j]); + matrix[i][j] += 300; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] > 100) { + k = (k + 1) % 4; + } + i += dirs[k]; + j += dirs[k + 1]; + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + matrix[i][j] -= 300; + } + } + return ans; + } +} +``` + + + +### Solution 3 + + + +```python +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + m, n = len(matrix), len(matrix[0]) + x1, y1, x2, y2 = 0, 0, m - 1, n - 1 + ans = [] + while x1 <= x2 and y1 <= y2: + for j in range(y1, y2 + 1): + ans.append(matrix[x1][j]) + for i in range(x1 + 1, x2 + 1): + ans.append(matrix[i][y2]) + if x1 < x2 and y1 < y2: + for j in range(y2 - 1, y1 - 1, -1): + ans.append(matrix[x2][j]) + for i in range(x2 - 1, x1, -1): + ans.append(matrix[i][y1]) + x1, y1 = x1 + 1, y1 + 1 + x2, y2 = x2 - 1, y2 - 1 + return ans +``` + +```java +class Solution { + public List spiralOrder(int[][] matrix) { + int m = matrix.length, n = matrix[0].length; + int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; + List ans = new ArrayList<>(); + while (x1 <= x2 && y1 <= y2) { + for (int j = y1; j <= y2; ++j) { + ans.add(matrix[x1][j]); + } + for (int i = x1 + 1; i <= x2; ++i) { + ans.add(matrix[i][y2]); + } + if (x1 < x2 && y1 < y2) { + for (int j = y2 - 1; j >= y1; --j) { + ans.add(matrix[x2][j]); + } + for (int i = x2 - 1; i > x1; --i) { + ans.add(matrix[i][y1]); + } + } + ++x1; + ++y1; + --x2; + --y2; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector spiralOrder(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; + vector ans; + while (x1 <= x2 && y1 <= y2) { + for (int j = y1; j <= y2; ++j) { + ans.push_back(matrix[x1][j]); + } + for (int i = x1 + 1; i <= x2; ++i) { + ans.push_back(matrix[i][y2]); + } + if (x1 < x2 && y1 < y2) { + for (int j = y2 - 1; j >= y1; --j) { + ans.push_back(matrix[x2][j]); + } + for (int i = x2 - 1; i > x1; --i) { + ans.push_back(matrix[i][y1]); + } + } + ++x1, ++y1; + --x2, --y2; + } + return ans; + } +}; +``` + +```go +func spiralOrder(matrix [][]int) (ans []int) { + m, n := len(matrix), len(matrix[0]) + x1, y1, x2, y2 := 0, 0, m-1, n-1 + for x1 <= x2 && y1 <= y2 { + for j := y1; j <= y2; j++ { + ans = append(ans, matrix[x1][j]) + } + for i := x1 + 1; i <= x2; i++ { + ans = append(ans, matrix[i][y2]) + } + if x1 < x2 && y1 < y2 { + for j := y2 - 1; j >= y1; j-- { + ans = append(ans, matrix[x2][j]) + } + for i := x2 - 1; i > x1; i-- { + ans = append(ans, matrix[i][y1]) + } + } + x1, y1 = x1+1, y1+1 + x2, y2 = x2-1, y2-1 + } + return } ``` @@ -649,10 +575,74 @@ function spiralOrder(matrix: number[][]): number[] { } ``` -### **...** - +```js +/** + * @param {number[][]} matrix + * @return {number[]} + */ +var spiralOrder = function (matrix) { + const m = matrix.length; + const n = matrix[0].length; + let x1 = 0; + let y1 = 0; + let x2 = m - 1; + let y2 = n - 1; + const ans = []; + while (x1 <= x2 && y1 <= y2) { + for (let j = y1; j <= y2; ++j) { + ans.push(matrix[x1][j]); + } + for (let i = x1 + 1; i <= x2; ++i) { + ans.push(matrix[i][y2]); + } + if (x1 < x2 && y1 < y2) { + for (let j = y2 - 1; j >= y1; --j) { + ans.push(matrix[x2][j]); + } + for (let i = x2 - 1; i > x1; --i) { + ans.push(matrix[i][y1]); + } + } + ++x1; + ++y1; + --x2; + --y2; + } + return ans; +}; ``` +```cs +public class Solution { + public IList SpiralOrder(int[][] matrix) { + int m = matrix.Length, n = matrix[0].Length; + int x1 = 0, y1 = 0, x2 = m - 1, y2 = n - 1; + IList ans = new List(); + while (x1 <= x2 && y1 <= y2) { + for (int j = y1; j <= y2; ++j) { + ans.Add(matrix[x1][j]); + } + for (int i = x1 + 1; i <= x2; ++i) { + ans.Add(matrix[i][y2]); + } + if (x1 < x2 && y1 < y2) { + for (int j = y2 - 1; j >= y1; --j) { + ans.Add(matrix[x2][j]); + } + for (int i = x2 - 1; i > x1; --i) { + ans.Add(matrix[i][y1]); + } + } + ++x1; + ++y1; + --x2; + --y2; + } + return ans; + } +} ``` + + diff --git a/solution/0000-0099/0055.Jump Game/README.md b/solution/0000-0099/0055.Jump Game/README.md index 696b28942a723..c9d3f477f9ea3 100644 --- a/solution/0000-0099/0055.Jump Game/README.md +++ b/solution/0000-0099/0055.Jump Game/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们用变量 $mx$ 维护当前能够到达的最远下标,初始时 $mx = 0$。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def canJump(self, nums: List[int]) -> bool: @@ -74,10 +68,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean canJump(int[] nums) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,29 +99,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn can_jump(nums: Vec) -> bool { - let n = nums.len(); - let mut mx = 0; - - for i in 0..n { - if mx < i { - return false; - } - mx = std::cmp::max(mx, i + (nums[i] as usize)); - } - - true - } -} -``` - -### **Go** - ```go func canJump(nums []int) bool { mx := 0 @@ -147,8 +112,6 @@ func canJump(nums []int) bool { } ``` -### **TypeScript** - ```ts function canJump(nums: number[]): boolean { let mx: number = 0; @@ -162,7 +125,24 @@ function canJump(nums: number[]): boolean { } ``` -### **JavaScript** +```rust +impl Solution { + #[allow(dead_code)] + pub fn can_jump(nums: Vec) -> bool { + let n = nums.len(); + let mut mx = 0; + + for i in 0..n { + if mx < i { + return false; + } + mx = std::cmp::max(mx, i + (nums[i] as usize)); + } + + true + } +} +``` ```js /** @@ -181,8 +161,6 @@ var canJump = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public bool CanJump(int[] nums) { @@ -198,10 +176,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0055.Jump Game/README_EN.md b/solution/0000-0099/0055.Jump Game/README_EN.md index 1786a52fc8b8a..e574cef19339d 100644 --- a/solution/0000-0099/0055.Jump Game/README_EN.md +++ b/solution/0000-0099/0055.Jump Game/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy We use a variable $mx$ to maintain the farthest index that can currently be reached, initially $mx = 0$. @@ -53,8 +53,6 @@ Similar problems: -### **Python3** - ```python class Solution: def canJump(self, nums: List[int]) -> bool: @@ -66,8 +64,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean canJump(int[] nums) { @@ -83,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,29 +95,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn can_jump(nums: Vec) -> bool { - let n = nums.len(); - let mut mx = 0; - - for i in 0..n { - if mx < i { - return false; - } - mx = std::cmp::max(mx, i + (nums[i] as usize)); - } - - true - } -} -``` - -### **Go** - ```go func canJump(nums []int) bool { mx := 0 @@ -137,8 +108,6 @@ func canJump(nums []int) bool { } ``` -### **TypeScript** - ```ts function canJump(nums: number[]): boolean { let mx: number = 0; @@ -152,7 +121,24 @@ function canJump(nums: number[]): boolean { } ``` -### **JavaScript** +```rust +impl Solution { + #[allow(dead_code)] + pub fn can_jump(nums: Vec) -> bool { + let n = nums.len(); + let mut mx = 0; + + for i in 0..n { + if mx < i { + return false; + } + mx = std::cmp::max(mx, i + (nums[i] as usize)); + } + + true + } +} +``` ```js /** @@ -171,8 +157,6 @@ var canJump = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public bool CanJump(int[] nums) { @@ -188,10 +172,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0056.Merge Intervals/README.md b/solution/0000-0099/0056.Merge Intervals/README.md index f5be28bfe41b2..a615708c70d2a 100644 --- a/solution/0000-0099/0056.Merge Intervals/README.md +++ b/solution/0000-0099/0056.Merge Intervals/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:排序 + 一次遍历** +### 方法一:排序 + 一次遍历 我们可以将区间按照左端点升序排列,然后遍历区间进行合并操作。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: @@ -76,23 +70,6 @@ class Solution: return ans ``` -```python -class Solution: - def merge(self, intervals: List[List[int]]) -> List[List[int]]: - intervals.sort() - ans = [intervals[0]] - for s, e in intervals[1:]: - if ans[-1][1] < s: - ans.append([s, e]) - else: - ans[-1][1] = max(ans[-1][1], e) - return ans -``` - -### **Java** - - - ```java class Solution { public int[][] merge(int[][] intervals) { @@ -115,27 +92,6 @@ class Solution { } ``` -```java -class Solution { - public int[][] merge(int[][] intervals) { - Arrays.sort(intervals, (a, b) -> a[0] - b[0]); - List ans = new ArrayList<>(); - ans.add(intervals[0]); - for (int i = 1; i < intervals.length; ++i) { - int s = intervals[i][0], e = intervals[i][1]; - if (ans.get(ans.size() - 1)[1] < s) { - ans.add(intervals[i]); - } else { - ans.get(ans.size() - 1)[1] = Math.max(ans.get(ans.size() - 1)[1], e); - } - } - return ans.toArray(new int[ans.size()][]); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -158,27 +114,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector> merge(vector>& intervals) { - sort(intervals.begin(), intervals.end()); - vector> ans; - ans.emplace_back(intervals[0]); - for (int i = 1; i < intervals.size(); ++i) { - if (ans.back()[1] < intervals[i][0]) { - ans.emplace_back(intervals[i]); - } else { - ans.back()[1] = max(ans.back()[1], intervals[i][1]); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func merge(intervals [][]int) (ans [][]int) { sort.Slice(intervals, func(i, j int) bool { @@ -198,22 +133,45 @@ func merge(intervals [][]int) (ans [][]int) { } ``` -```go -func merge(intervals [][]int) (ans [][]int) { - sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] }) - ans = append(ans, intervals[0]) - for _, e := range intervals[1:] { - if ans[len(ans)-1][1] < e[0] { - ans = append(ans, e) - } else { - ans[len(ans)-1][1] = max(ans[len(ans)-1][1], e[1]) - } - } - return +```ts +function merge(intervals: number[][]): number[][] { + intervals.sort((a, b) => a[0] - b[0]); + const ans: number[][] = []; + let [st, ed] = intervals[0]; + for (const [s, e] of intervals.slice(1)) { + if (ed < s) { + ans.push([st, ed]); + [st, ed] = [s, e]; + } else { + ed = Math.max(ed, e); + } + } + ans.push([st, ed]); + return ans; } ``` -### **C#** +```rust +impl Solution { + pub fn merge(mut intervals: Vec>) -> Vec> { + intervals.sort_unstable_by(|a, b| a[0].cmp(&b[0])); + let n = intervals.len(); + let mut res = vec![]; + let mut i = 0; + while i < n { + let l = intervals[i][0]; + let mut r = intervals[i][1]; + i += 1; + while i < n && r >= intervals[i][0] { + r = r.max(intervals[i][1]); + i += 1; + } + res.push(vec![l, r]); + } + res + } +} +``` ```cs public class Solution { @@ -236,41 +194,75 @@ public class Solution { } ``` -```cs -public class Solution { - public int[][] Merge(int[][] intervals) { - intervals = intervals.OrderBy(a => a[0]).ToArray(); - var ans = new List(); - ans.Add(intervals[0]); - for (int i = 1; i < intervals.Length; ++i) { - if (ans[ans.Count - 1][1] < intervals[i][0]) { - ans.Add(intervals[i]); + + +### 方法二 + + + +```python +class Solution: + def merge(self, intervals: List[List[int]]) -> List[List[int]]: + intervals.sort() + ans = [intervals[0]] + for s, e in intervals[1:]: + if ans[-1][1] < s: + ans.append([s, e]) + else: + ans[-1][1] = max(ans[-1][1], e) + return ans +``` + +```java +class Solution { + public int[][] merge(int[][] intervals) { + Arrays.sort(intervals, (a, b) -> a[0] - b[0]); + List ans = new ArrayList<>(); + ans.add(intervals[0]); + for (int i = 1; i < intervals.length; ++i) { + int s = intervals[i][0], e = intervals[i][1]; + if (ans.get(ans.size() - 1)[1] < s) { + ans.add(intervals[i]); } else { - ans[ans.Count - 1][1] = Math.Max(ans[ans.Count - 1][1], intervals[i][1]); + ans.get(ans.size() - 1)[1] = Math.max(ans.get(ans.size() - 1)[1], e); } } - return ans.ToArray(); + return ans.toArray(new int[ans.size()][]); } } ``` -### **TypeScript** - -```ts -function merge(intervals: number[][]): number[][] { - intervals.sort((a, b) => a[0] - b[0]); - const ans: number[][] = []; - let [st, ed] = intervals[0]; - for (const [s, e] of intervals.slice(1)) { - if (ed < s) { - ans.push([st, ed]); - [st, ed] = [s, e]; - } else { - ed = Math.max(ed, e); +```cpp +class Solution { +public: + vector> merge(vector>& intervals) { + sort(intervals.begin(), intervals.end()); + vector> ans; + ans.emplace_back(intervals[0]); + for (int i = 1; i < intervals.size(); ++i) { + if (ans.back()[1] < intervals[i][0]) { + ans.emplace_back(intervals[i]); + } else { + ans.back()[1] = max(ans.back()[1], intervals[i][1]); + } } + return ans; } - ans.push([st, ed]); - return ans; +}; +``` + +```go +func merge(intervals [][]int) (ans [][]int) { + sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] }) + ans = append(ans, intervals[0]) + for _, e := range intervals[1:] { + if ans[len(ans)-1][1] < e[0] { + ans = append(ans, e) + } else { + ans[len(ans)-1][1] = max(ans[len(ans)-1][1], e[1]) + } + } + return } ``` @@ -289,6 +281,30 @@ function merge(intervals: number[][]): number[][] { } ``` +```cs +public class Solution { + public int[][] Merge(int[][] intervals) { + intervals = intervals.OrderBy(a => a[0]).ToArray(); + var ans = new List(); + ans.Add(intervals[0]); + for (int i = 1; i < intervals.Length; ++i) { + if (ans[ans.Count - 1][1] < intervals[i][0]) { + ans.Add(intervals[i]); + } else { + ans[ans.Count - 1][1] = Math.Max(ans[ans.Count - 1][1], intervals[i][1]); + } + } + return ans.ToArray(); + } +} +``` + + + +### 方法三 + + + ```ts function merge(intervals: number[][]): number[][] { intervals.sort((a, b) => a[0] - b[0]); @@ -308,34 +324,6 @@ function merge(intervals: number[][]): number[][] { } ``` -### **Rust** - -```rust -impl Solution { - pub fn merge(mut intervals: Vec>) -> Vec> { - intervals.sort_unstable_by(|a, b| a[0].cmp(&b[0])); - let n = intervals.len(); - let mut res = vec![]; - let mut i = 0; - while i < n { - let l = intervals[i][0]; - let mut r = intervals[i][1]; - i += 1; - while i < n && r >= intervals[i][0] { - r = r.max(intervals[i][1]); - i += 1; - } - res.push(vec![l, r]); - } - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0056.Merge Intervals/README_EN.md b/solution/0000-0099/0056.Merge Intervals/README_EN.md index 9cf945edfca9e..8c7d4f921464d 100644 --- a/solution/0000-0099/0056.Merge Intervals/README_EN.md +++ b/solution/0000-0099/0056.Merge Intervals/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Sorting + One-pass Traversal** +### Solution 1: Sorting + One-pass Traversal We can sort the intervals in ascending order by the left endpoint, and then traverse the intervals for merging operations. @@ -51,8 +51,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: @@ -69,21 +67,6 @@ class Solution: return ans ``` -```python -class Solution: - def merge(self, intervals: List[List[int]]) -> List[List[int]]: - intervals.sort() - ans = [intervals[0]] - for s, e in intervals[1:]: - if ans[-1][1] < s: - ans.append([s, e]) - else: - ans[-1][1] = max(ans[-1][1], e) - return ans -``` - -### **Java** - ```java class Solution { public int[][] merge(int[][] intervals) { @@ -106,27 +89,6 @@ class Solution { } ``` -```java -class Solution { - public int[][] merge(int[][] intervals) { - Arrays.sort(intervals, (a, b) -> a[0] - b[0]); - List ans = new ArrayList<>(); - ans.add(intervals[0]); - for (int i = 1; i < intervals.length; ++i) { - int s = intervals[i][0], e = intervals[i][1]; - if (ans.get(ans.size() - 1)[1] < s) { - ans.add(intervals[i]); - } else { - ans.get(ans.size() - 1)[1] = Math.max(ans.get(ans.size() - 1)[1], e); - } - } - return ans.toArray(new int[ans.size()][]); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -149,27 +111,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector> merge(vector>& intervals) { - sort(intervals.begin(), intervals.end()); - vector> ans; - ans.emplace_back(intervals[0]); - for (int i = 1; i < intervals.size(); ++i) { - if (ans.back()[1] < intervals[i][0]) { - ans.emplace_back(intervals[i]); - } else { - ans.back()[1] = max(ans.back()[1], intervals[i][1]); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func merge(intervals [][]int) (ans [][]int) { sort.Slice(intervals, func(i, j int) bool { @@ -189,22 +130,45 @@ func merge(intervals [][]int) (ans [][]int) { } ``` -```go -func merge(intervals [][]int) (ans [][]int) { - sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] }) - ans = append(ans, intervals[0]) - for _, e := range intervals[1:] { - if ans[len(ans)-1][1] < e[0] { - ans = append(ans, e) - } else { - ans[len(ans)-1][1] = max(ans[len(ans)-1][1], e[1]) - } - } - return +```ts +function merge(intervals: number[][]): number[][] { + intervals.sort((a, b) => a[0] - b[0]); + const ans: number[][] = []; + let [st, ed] = intervals[0]; + for (const [s, e] of intervals.slice(1)) { + if (ed < s) { + ans.push([st, ed]); + [st, ed] = [s, e]; + } else { + ed = Math.max(ed, e); + } + } + ans.push([st, ed]); + return ans; } ``` -### **C#** +```rust +impl Solution { + pub fn merge(mut intervals: Vec>) -> Vec> { + intervals.sort_unstable_by(|a, b| a[0].cmp(&b[0])); + let n = intervals.len(); + let mut res = vec![]; + let mut i = 0; + while i < n { + let l = intervals[i][0]; + let mut r = intervals[i][1]; + i += 1; + while i < n && r >= intervals[i][0] { + r = r.max(intervals[i][1]); + i += 1; + } + res.push(vec![l, r]); + } + res + } +} +``` ```cs public class Solution { @@ -227,41 +191,75 @@ public class Solution { } ``` -```cs -public class Solution { - public int[][] Merge(int[][] intervals) { - intervals = intervals.OrderBy(a => a[0]).ToArray(); - var ans = new List(); - ans.Add(intervals[0]); - for (int i = 1; i < intervals.Length; ++i) { - if (ans[ans.Count - 1][1] < intervals[i][0]) { - ans.Add(intervals[i]); + + +### Solution 2 + + + +```python +class Solution: + def merge(self, intervals: List[List[int]]) -> List[List[int]]: + intervals.sort() + ans = [intervals[0]] + for s, e in intervals[1:]: + if ans[-1][1] < s: + ans.append([s, e]) + else: + ans[-1][1] = max(ans[-1][1], e) + return ans +``` + +```java +class Solution { + public int[][] merge(int[][] intervals) { + Arrays.sort(intervals, (a, b) -> a[0] - b[0]); + List ans = new ArrayList<>(); + ans.add(intervals[0]); + for (int i = 1; i < intervals.length; ++i) { + int s = intervals[i][0], e = intervals[i][1]; + if (ans.get(ans.size() - 1)[1] < s) { + ans.add(intervals[i]); } else { - ans[ans.Count - 1][1] = Math.Max(ans[ans.Count - 1][1], intervals[i][1]); + ans.get(ans.size() - 1)[1] = Math.max(ans.get(ans.size() - 1)[1], e); } } - return ans.ToArray(); + return ans.toArray(new int[ans.size()][]); } } ``` -### **TypeScript** - -```ts -function merge(intervals: number[][]): number[][] { - intervals.sort((a, b) => a[0] - b[0]); - const ans: number[][] = []; - let [st, ed] = intervals[0]; - for (const [s, e] of intervals.slice(1)) { - if (ed < s) { - ans.push([st, ed]); - [st, ed] = [s, e]; - } else { - ed = Math.max(ed, e); +```cpp +class Solution { +public: + vector> merge(vector>& intervals) { + sort(intervals.begin(), intervals.end()); + vector> ans; + ans.emplace_back(intervals[0]); + for (int i = 1; i < intervals.size(); ++i) { + if (ans.back()[1] < intervals[i][0]) { + ans.emplace_back(intervals[i]); + } else { + ans.back()[1] = max(ans.back()[1], intervals[i][1]); + } } + return ans; } - ans.push([st, ed]); - return ans; +}; +``` + +```go +func merge(intervals [][]int) (ans [][]int) { + sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] }) + ans = append(ans, intervals[0]) + for _, e := range intervals[1:] { + if ans[len(ans)-1][1] < e[0] { + ans = append(ans, e) + } else { + ans[len(ans)-1][1] = max(ans[len(ans)-1][1], e[1]) + } + } + return } ``` @@ -280,6 +278,30 @@ function merge(intervals: number[][]): number[][] { } ``` +```cs +public class Solution { + public int[][] Merge(int[][] intervals) { + intervals = intervals.OrderBy(a => a[0]).ToArray(); + var ans = new List(); + ans.Add(intervals[0]); + for (int i = 1; i < intervals.Length; ++i) { + if (ans[ans.Count - 1][1] < intervals[i][0]) { + ans.Add(intervals[i]); + } else { + ans[ans.Count - 1][1] = Math.Max(ans[ans.Count - 1][1], intervals[i][1]); + } + } + return ans.ToArray(); + } +} +``` + + + +### Solution 3 + + + ```ts function merge(intervals: number[][]): number[][] { intervals.sort((a, b) => a[0] - b[0]); @@ -299,34 +321,6 @@ function merge(intervals: number[][]): number[][] { } ``` -### **Rust** - -```rust -impl Solution { - pub fn merge(mut intervals: Vec>) -> Vec> { - intervals.sort_unstable_by(|a, b| a[0].cmp(&b[0])); - let n = intervals.len(); - let mut res = vec![]; - let mut i = 0; - while i < n { - let l = intervals[i][0]; - let mut r = intervals[i][1]; - i += 1; - while i < n && r >= intervals[i][0] { - r = r.max(intervals[i][1]); - i += 1; - } - res.push(vec![l, r]); - } - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0057.Insert Interval/README.md b/solution/0000-0099/0057.Insert Interval/README.md index 4079433b14567..162d1ce938b57 100644 --- a/solution/0000-0099/0057.Insert Interval/README.md +++ b/solution/0000-0099/0057.Insert Interval/README.md @@ -62,32 +62,14 @@ ## 解法 - - -**方法一:排序 + 区间合并** +### 方法一:排序 + 区间合并 我们可以先将新区间 `newInterval` 加入到区间列表 `intervals` 中,然后按照区间合并的常规方法进行合并。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是区间的数量。 -**方法二:一次遍历** - -我们可以遍历区间列表 `intervals`,记当前区间为 `interval`,对于每个区间有三种情况: - -- 当前区间在新区间的右侧,即 $newInterval[1] \lt interval[0]$,此时如果新区间还没有被加入,那么将新区间加入到答案中,然后将当前区间加入到答案中。 -- 当前区间在新区间的左侧,即 $interval[1] \lt newInterval[0]$,此时将当前区间加入到答案中。 -- 否则,说明当前区间与新区间有交集,我们取当前区间的左端点和新区间的左端点的最小值,以及当前区间的右端点和新区间的右端点的最大值,作为新区间的左右端点,然后继续遍历区间列表。 - -遍历结束,如果新区间还没有被加入,那么将新区间加入到答案中。 - -时间复杂度 $O(n)$,其中 $n$ 是区间的数量。忽略答案数组的空间消耗,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def insert( @@ -107,34 +89,6 @@ class Solution: return merge(intervals) ``` -```python -class Solution: - def insert( - self, intervals: List[List[int]], newInterval: List[int] - ) -> List[List[int]]: - st, ed = newInterval - ans = [] - insert = False - for s, e in intervals: - if ed < s: - if not insert: - ans.append([st, ed]) - insert = True - ans.append([s, e]) - elif e < st: - ans.append([s, e]) - else: - st = min(st, s) - ed = max(ed, e) - if not insert: - ans.append([st, ed]) - return ans -``` - -### **Java** - - - ```java class Solution { public int[][] insert(int[][] intervals, int[] newInterval) { @@ -163,37 +117,6 @@ class Solution { } ``` -```java -class Solution { - public int[][] insert(int[][] intervals, int[] newInterval) { - List ans = new ArrayList<>(); - int st = newInterval[0], ed = newInterval[1]; - boolean insert = false; - for (int[] interval : intervals) { - int s = interval[0], e = interval[1]; - if (ed < s) { - if (!insert) { - ans.add(new int[] {st, ed}); - insert = true; - } - ans.add(interval); - } else if (e < st) { - ans.add(interval); - } else { - st = Math.min(st, s); - ed = Math.max(ed, e); - } - } - if (!insert) { - ans.add(new int[] {st, ed}); - } - return ans.toArray(new int[ans.size()][]); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -218,38 +141,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector> insert(vector>& intervals, vector& newInterval) { - vector> ans; - int st = newInterval[0], ed = newInterval[1]; - bool insert = false; - for (auto& interval : intervals) { - int s = interval[0], e = interval[1]; - if (ed < s) { - if (!insert) { - ans.push_back({st, ed}); - insert = true; - } - ans.push_back(interval); - } else if (e < st) { - ans.push_back(interval); - } else { - st = min(st, s); - ed = max(ed, e); - } - } - if (!insert) { - ans.push_back({st, ed}); - } - return ans; - } -}; -``` - -### **Go** - ```go func insert(intervals [][]int, newInterval []int) [][]int { merge := func(intervals [][]int) (ans [][]int) { @@ -269,34 +160,6 @@ func insert(intervals [][]int, newInterval []int) [][]int { } ``` -```go -func insert(intervals [][]int, newInterval []int) (ans [][]int) { - st, ed := newInterval[0], newInterval[1] - insert := false - for _, interval := range intervals { - s, e := interval[0], interval[1] - if ed < s { - if !insert { - ans = append(ans, []int{st, ed}) - insert = true - } - ans = append(ans, interval) - } else if e < st { - ans = append(ans, interval) - } else { - st = min(st, s) - ed = max(ed, e) - } - } - if !insert { - ans = append(ans, []int{st, ed}) - } - return -} -``` - -### **TypeScript** - ```ts function insert(intervals: number[][], newInterval: number[]): number[][] { const merge = (intervals: number[][]): number[][] => { @@ -317,34 +180,34 @@ function insert(intervals: number[][], newInterval: number[]): number[][] { } ``` -```ts -function insert(intervals: number[][], newInterval: number[]): number[][] { - let [st, ed] = newInterval; - const ans: number[][] = []; - let insert = false; - for (const [s, e] of intervals) { - if (ed < s) { - if (!insert) { - ans.push([st, ed]); - insert = true; +```rust +impl Solution { + pub fn insert(intervals: Vec>, new_interval: Vec) -> Vec> { + let mut merged_intervals = intervals.clone(); + merged_intervals.push(vec![new_interval[0], new_interval[1]]); + // sort by elem[0] + merged_intervals.sort_by_key(|elem| elem[0]); + // merge interval + let mut result = vec![]; + + for interval in merged_intervals { + if result.is_empty() { + result.push(interval); + continue; + } + + let last_elem = result.last_mut().unwrap(); + if interval[0] > last_elem[1] { + result.push(interval); + } else { + last_elem[1] = last_elem[1].max(interval[1]); } - ans.push([s, e]); - } else if (e < st) { - ans.push([s, e]); - } else { - st = Math.min(st, s); - ed = Math.max(ed, e); } + result } - if (!insert) { - ans.push([st, ed]); - } - return ans; } ``` -### **C#** - ```cs public class Solution { public int[][] Insert(int[][] intervals, int[] newInterval) { @@ -372,62 +235,154 @@ public class Solution { } ``` -```cs -public class Solution { - public int[][] Insert(int[][] intervals, int[] newInterval) { - var ans = new List(); + + +### 方法二:一次遍历 + +我们可以遍历区间列表 `intervals`,记当前区间为 `interval`,对于每个区间有三种情况: + +- 当前区间在新区间的右侧,即 $newInterval[1] \lt interval[0]$,此时如果新区间还没有被加入,那么将新区间加入到答案中,然后将当前区间加入到答案中。 +- 当前区间在新区间的左侧,即 $interval[1] \lt newInterval[0]$,此时将当前区间加入到答案中。 +- 否则,说明当前区间与新区间有交集,我们取当前区间的左端点和新区间的左端点的最小值,以及当前区间的右端点和新区间的右端点的最大值,作为新区间的左右端点,然后继续遍历区间列表。 + +遍历结束,如果新区间还没有被加入,那么将新区间加入到答案中。 + +时间复杂度 $O(n)$,其中 $n$ 是区间的数量。忽略答案数组的空间消耗,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def insert( + self, intervals: List[List[int]], newInterval: List[int] + ) -> List[List[int]]: + st, ed = newInterval + ans = [] + insert = False + for s, e in intervals: + if ed < s: + if not insert: + ans.append([st, ed]) + insert = True + ans.append([s, e]) + elif e < st: + ans.append([s, e]) + else: + st = min(st, s) + ed = max(ed, e) + if not insert: + ans.append([st, ed]) + return ans +``` + +```java +class Solution { + public int[][] insert(int[][] intervals, int[] newInterval) { + List ans = new ArrayList<>(); int st = newInterval[0], ed = newInterval[1]; - bool insert = false; - foreach (var interval in intervals) { + boolean insert = false; + for (int[] interval : intervals) { int s = interval[0], e = interval[1]; if (ed < s) { if (!insert) { - ans.Add(new int[]{st, ed}); + ans.add(new int[] {st, ed}); insert = true; } - ans.Add(interval); - } else if (st > e) { - ans.Add(interval); + ans.add(interval); + } else if (e < st) { + ans.add(interval); } else { - st = Math.Min(st, s); - ed = Math.Max(ed, e); + st = Math.min(st, s); + ed = Math.max(ed, e); } } if (!insert) { - ans.Add(new int[]{st, ed}); + ans.add(new int[] {st, ed}); } - return ans.ToArray(); + return ans.toArray(new int[ans.size()][]); } } ``` -### **Rust** - -```rust -impl Solution { - pub fn insert(intervals: Vec>, new_interval: Vec) -> Vec> { - let mut merged_intervals = intervals.clone(); - merged_intervals.push(vec![new_interval[0], new_interval[1]]); - // sort by elem[0] - merged_intervals.sort_by_key(|elem| elem[0]); - // merge interval - let mut result = vec![]; - - for interval in merged_intervals { - if result.is_empty() { - result.push(interval); - continue; +```cpp +class Solution { +public: + vector> insert(vector>& intervals, vector& newInterval) { + vector> ans; + int st = newInterval[0], ed = newInterval[1]; + bool insert = false; + for (auto& interval : intervals) { + int s = interval[0], e = interval[1]; + if (ed < s) { + if (!insert) { + ans.push_back({st, ed}); + insert = true; + } + ans.push_back(interval); + } else if (e < st) { + ans.push_back(interval); + } else { + st = min(st, s); + ed = max(ed, e); } + } + if (!insert) { + ans.push_back({st, ed}); + } + return ans; + } +}; +``` - let last_elem = result.last_mut().unwrap(); - if interval[0] > last_elem[1] { - result.push(interval); - } else { - last_elem[1] = last_elem[1].max(interval[1]); +```go +func insert(intervals [][]int, newInterval []int) (ans [][]int) { + st, ed := newInterval[0], newInterval[1] + insert := false + for _, interval := range intervals { + s, e := interval[0], interval[1] + if ed < s { + if !insert { + ans = append(ans, []int{st, ed}) + insert = true + } + ans = append(ans, interval) + } else if e < st { + ans = append(ans, interval) + } else { + st = min(st, s) + ed = max(ed, e) + } + } + if !insert { + ans = append(ans, []int{st, ed}) + } + return +} +``` + +```ts +function insert(intervals: number[][], newInterval: number[]): number[][] { + let [st, ed] = newInterval; + const ans: number[][] = []; + let insert = false; + for (const [s, e] of intervals) { + if (ed < s) { + if (!insert) { + ans.push([st, ed]); + insert = true; } + ans.push([s, e]); + } else if (e < st) { + ans.push([s, e]); + } else { + st = Math.min(st, s); + ed = Math.max(ed, e); } - result } + if (!insert) { + ans.push([st, ed]); + } + return ans; } ``` @@ -462,10 +417,35 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public int[][] Insert(int[][] intervals, int[] newInterval) { + var ans = new List(); + int st = newInterval[0], ed = newInterval[1]; + bool insert = false; + foreach (var interval in intervals) { + int s = interval[0], e = interval[1]; + if (ed < s) { + if (!insert) { + ans.Add(new int[]{st, ed}); + insert = true; + } + ans.Add(interval); + } else if (st > e) { + ans.Add(interval); + } else { + st = Math.Min(st, s); + ed = Math.Max(ed, e); + } + } + if (!insert) { + ans.Add(new int[]{st, ed}); + } + return ans.ToArray(); + } +} ``` + + diff --git a/solution/0000-0099/0057.Insert Interval/README_EN.md b/solution/0000-0099/0057.Insert Interval/README_EN.md index bcf71ea5ad766..b7ef4c8758499 100644 --- a/solution/0000-0099/0057.Insert Interval/README_EN.md +++ b/solution/0000-0099/0057.Insert Interval/README_EN.md @@ -40,28 +40,14 @@ ## Solutions -**Solution 1: Sorting + Interval Merging** +### Solution 1: Sorting + Interval Merging We can first add the new interval `newInterval` to the interval list `intervals`, and then merge according to the regular method of interval merging. The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of intervals. -**Solution 2: One-pass Traversal** - -We can traverse the interval list `intervals`, let the current interval be `interval`, and there are three situations for each interval: - -- The current interval is on the right side of the new interval, that is, $newInterval[1] < interval[0]$. At this time, if the new interval has not been added, then add the new interval to the answer, and then add the current interval to the answer. -- The current interval is on the left side of the new interval, that is, $interval[1] < newInterval[0]$. At this time, add the current interval to the answer. -- Otherwise, it means that the current interval and the new interval intersect. We take the minimum of the left endpoint of the current interval and the left endpoint of the new interval, and the maximum of the right endpoint of the current interval and the right endpoint of the new interval, as the left and right endpoints of the new interval, and then continue to traverse the interval list. - -After the traversal, if the new interval has not been added, then add the new interval to the answer. - -The time complexity is $O(n)$, where $n$ is the number of intervals. Ignoring the space consumption of the answer array, the space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def insert( @@ -81,32 +67,6 @@ class Solution: return merge(intervals) ``` -```python -class Solution: - def insert( - self, intervals: List[List[int]], newInterval: List[int] - ) -> List[List[int]]: - st, ed = newInterval - ans = [] - insert = False - for s, e in intervals: - if ed < s: - if not insert: - ans.append([st, ed]) - insert = True - ans.append([s, e]) - elif e < st: - ans.append([s, e]) - else: - st = min(st, s) - ed = max(ed, e) - if not insert: - ans.append([st, ed]) - return ans -``` - -### **Java** - ```java class Solution { public int[][] insert(int[][] intervals, int[] newInterval) { @@ -135,37 +95,6 @@ class Solution { } ``` -```java -class Solution { - public int[][] insert(int[][] intervals, int[] newInterval) { - List ans = new ArrayList<>(); - int st = newInterval[0], ed = newInterval[1]; - boolean insert = false; - for (int[] interval : intervals) { - int s = interval[0], e = interval[1]; - if (ed < s) { - if (!insert) { - ans.add(new int[] {st, ed}); - insert = true; - } - ans.add(interval); - } else if (e < st) { - ans.add(interval); - } else { - st = Math.min(st, s); - ed = Math.max(ed, e); - } - } - if (!insert) { - ans.add(new int[] {st, ed}); - } - return ans.toArray(new int[ans.size()][]); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -190,38 +119,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector> insert(vector>& intervals, vector& newInterval) { - vector> ans; - int st = newInterval[0], ed = newInterval[1]; - bool insert = false; - for (auto& interval : intervals) { - int s = interval[0], e = interval[1]; - if (ed < s) { - if (!insert) { - ans.push_back({st, ed}); - insert = true; - } - ans.push_back(interval); - } else if (e < st) { - ans.push_back(interval); - } else { - st = min(st, s); - ed = max(ed, e); - } - } - if (!insert) { - ans.push_back({st, ed}); - } - return ans; - } -}; -``` - -### **Go** - ```go func insert(intervals [][]int, newInterval []int) [][]int { merge := func(intervals [][]int) (ans [][]int) { @@ -241,34 +138,6 @@ func insert(intervals [][]int, newInterval []int) [][]int { } ``` -```go -func insert(intervals [][]int, newInterval []int) (ans [][]int) { - st, ed := newInterval[0], newInterval[1] - insert := false - for _, interval := range intervals { - s, e := interval[0], interval[1] - if ed < s { - if !insert { - ans = append(ans, []int{st, ed}) - insert = true - } - ans = append(ans, interval) - } else if e < st { - ans = append(ans, interval) - } else { - st = min(st, s) - ed = max(ed, e) - } - } - if !insert { - ans = append(ans, []int{st, ed}) - } - return -} -``` - -### **TypeScript** - ```ts function insert(intervals: number[][], newInterval: number[]): number[][] { const merge = (intervals: number[][]): number[][] => { @@ -289,34 +158,34 @@ function insert(intervals: number[][], newInterval: number[]): number[][] { } ``` -```ts -function insert(intervals: number[][], newInterval: number[]): number[][] { - let [st, ed] = newInterval; - const ans: number[][] = []; - let insert = false; - for (const [s, e] of intervals) { - if (ed < s) { - if (!insert) { - ans.push([st, ed]); - insert = true; +```rust +impl Solution { + pub fn insert(intervals: Vec>, new_interval: Vec) -> Vec> { + let mut merged_intervals = intervals.clone(); + merged_intervals.push(vec![new_interval[0], new_interval[1]]); + // sort by elem[0] + merged_intervals.sort_by_key(|elem| elem[0]); + // merge interval + let mut result = vec![]; + + for interval in merged_intervals { + if result.is_empty() { + result.push(interval); + continue; + } + + let last_elem = result.last_mut().unwrap(); + if interval[0] > last_elem[1] { + result.push(interval); + } else { + last_elem[1] = last_elem[1].max(interval[1]); } - ans.push([s, e]); - } else if (e < st) { - ans.push([s, e]); - } else { - st = Math.min(st, s); - ed = Math.max(ed, e); } + result } - if (!insert) { - ans.push([st, ed]); - } - return ans; } ``` -### **C#** - ```cs public class Solution { public int[][] Insert(int[][] intervals, int[] newInterval) { @@ -344,62 +213,154 @@ public class Solution { } ``` -```cs -public class Solution { - public int[][] Insert(int[][] intervals, int[] newInterval) { - var ans = new List(); + + +### Solution 2: One-pass Traversal + +We can traverse the interval list `intervals`, let the current interval be `interval`, and there are three situations for each interval: + +- The current interval is on the right side of the new interval, that is, $newInterval[1] < interval[0]$. At this time, if the new interval has not been added, then add the new interval to the answer, and then add the current interval to the answer. +- The current interval is on the left side of the new interval, that is, $interval[1] < newInterval[0]$. At this time, add the current interval to the answer. +- Otherwise, it means that the current interval and the new interval intersect. We take the minimum of the left endpoint of the current interval and the left endpoint of the new interval, and the maximum of the right endpoint of the current interval and the right endpoint of the new interval, as the left and right endpoints of the new interval, and then continue to traverse the interval list. + +After the traversal, if the new interval has not been added, then add the new interval to the answer. + +The time complexity is $O(n)$, where $n$ is the number of intervals. Ignoring the space consumption of the answer array, the space complexity is $O(1)$. + + + +```python +class Solution: + def insert( + self, intervals: List[List[int]], newInterval: List[int] + ) -> List[List[int]]: + st, ed = newInterval + ans = [] + insert = False + for s, e in intervals: + if ed < s: + if not insert: + ans.append([st, ed]) + insert = True + ans.append([s, e]) + elif e < st: + ans.append([s, e]) + else: + st = min(st, s) + ed = max(ed, e) + if not insert: + ans.append([st, ed]) + return ans +``` + +```java +class Solution { + public int[][] insert(int[][] intervals, int[] newInterval) { + List ans = new ArrayList<>(); int st = newInterval[0], ed = newInterval[1]; - bool insert = false; - foreach (var interval in intervals) { + boolean insert = false; + for (int[] interval : intervals) { int s = interval[0], e = interval[1]; if (ed < s) { if (!insert) { - ans.Add(new int[]{st, ed}); + ans.add(new int[] {st, ed}); insert = true; } - ans.Add(interval); - } else if (st > e) { - ans.Add(interval); + ans.add(interval); + } else if (e < st) { + ans.add(interval); } else { - st = Math.Min(st, s); - ed = Math.Max(ed, e); + st = Math.min(st, s); + ed = Math.max(ed, e); } } if (!insert) { - ans.Add(new int[]{st, ed}); + ans.add(new int[] {st, ed}); } - return ans.ToArray(); + return ans.toArray(new int[ans.size()][]); } } ``` -### **Rust** - -```rust -impl Solution { - pub fn insert(intervals: Vec>, new_interval: Vec) -> Vec> { - let mut merged_intervals = intervals.clone(); - merged_intervals.push(vec![new_interval[0], new_interval[1]]); - // sort by elem[0] - merged_intervals.sort_by_key(|elem| elem[0]); - // merge interval - let mut result = vec![]; - - for interval in merged_intervals { - if result.is_empty() { - result.push(interval); - continue; +```cpp +class Solution { +public: + vector> insert(vector>& intervals, vector& newInterval) { + vector> ans; + int st = newInterval[0], ed = newInterval[1]; + bool insert = false; + for (auto& interval : intervals) { + int s = interval[0], e = interval[1]; + if (ed < s) { + if (!insert) { + ans.push_back({st, ed}); + insert = true; + } + ans.push_back(interval); + } else if (e < st) { + ans.push_back(interval); + } else { + st = min(st, s); + ed = max(ed, e); } + } + if (!insert) { + ans.push_back({st, ed}); + } + return ans; + } +}; +``` - let last_elem = result.last_mut().unwrap(); - if interval[0] > last_elem[1] { - result.push(interval); - } else { - last_elem[1] = last_elem[1].max(interval[1]); +```go +func insert(intervals [][]int, newInterval []int) (ans [][]int) { + st, ed := newInterval[0], newInterval[1] + insert := false + for _, interval := range intervals { + s, e := interval[0], interval[1] + if ed < s { + if !insert { + ans = append(ans, []int{st, ed}) + insert = true + } + ans = append(ans, interval) + } else if e < st { + ans = append(ans, interval) + } else { + st = min(st, s) + ed = max(ed, e) + } + } + if !insert { + ans = append(ans, []int{st, ed}) + } + return +} +``` + +```ts +function insert(intervals: number[][], newInterval: number[]): number[][] { + let [st, ed] = newInterval; + const ans: number[][] = []; + let insert = false; + for (const [s, e] of intervals) { + if (ed < s) { + if (!insert) { + ans.push([st, ed]); + insert = true; } + ans.push([s, e]); + } else if (e < st) { + ans.push([s, e]); + } else { + st = Math.min(st, s); + ed = Math.max(ed, e); } - result } + if (!insert) { + ans.push([st, ed]); + } + return ans; } ``` @@ -434,10 +395,35 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public int[][] Insert(int[][] intervals, int[] newInterval) { + var ans = new List(); + int st = newInterval[0], ed = newInterval[1]; + bool insert = false; + foreach (var interval in intervals) { + int s = interval[0], e = interval[1]; + if (ed < s) { + if (!insert) { + ans.Add(new int[]{st, ed}); + insert = true; + } + ans.Add(interval); + } else if (st > e) { + ans.Add(interval); + } else { + st = Math.Min(st, s); + ed = Math.Max(ed, e); + } + } + if (!insert) { + ans.Add(new int[]{st, ed}); + } + return ans.ToArray(); + } +} ``` + + diff --git a/solution/0000-0099/0058.Length of Last Word/README.md b/solution/0000-0099/0058.Length of Last Word/README.md index 777034a08a513..530e64173769c 100644 --- a/solution/0000-0099/0058.Length of Last Word/README.md +++ b/solution/0000-0099/0058.Length of Last Word/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:逆向遍历 + 双指针** +### 方法一:逆向遍历 + 双指针 我们从字符串 $s$ 末尾开始遍历,找到第一个不为空格的字符,即为最后一个单词的最后一个字符,下标记为 $i$。然后继续向前遍历,找到第一个为空格的字符,即为最后一个单词的第一个字符的前一个字符,记为 $j$。那么最后一个单词的长度即为 $i - j$。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def lengthOfLastWord(self, s: str) -> int: @@ -74,10 +68,6 @@ class Solution: return i - j ``` -### **Java** - - - ```java class Solution { public int lengthOfLastWord(String s) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func lengthOfLastWord(s string) int { i := len(s) - 1 @@ -129,14 +115,8 @@ func lengthOfLastWord(s string) int { } ``` -### **JavaScript** - -```js -/** - * @param {string} s - * @return {number} - */ -var lengthOfLastWord = function (s) { +```ts +function lengthOfLastWord(s: string): number { let i = s.length - 1; while (i >= 0 && s[i] === ' ') { --i; @@ -146,13 +126,30 @@ var lengthOfLastWord = function (s) { --j; } return i - j; -}; +} ``` -### **TypeScript** +```rust +impl Solution { + pub fn length_of_last_word(s: String) -> i32 { + let s = s.trim_end(); + let n = s.len(); + for (i, c) in s.char_indices().rev() { + if c == ' ' { + return (n - i - 1) as i32; + } + } + n as i32 + } +} +``` -```ts -function lengthOfLastWord(s: string): number { +```js +/** + * @param {string} s + * @return {number} + */ +var lengthOfLastWord = function (s) { let i = s.length - 1; while (i >= 0 && s[i] === ' ') { --i; @@ -162,11 +159,9 @@ function lengthOfLastWord(s: string): number { --j; } return i - j; -} +}; ``` -### **C#** - ```cs public class Solution { public int LengthOfLastWord(string s) { @@ -183,25 +178,6 @@ public class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn length_of_last_word(s: String) -> i32 { - let s = s.trim_end(); - let n = s.len(); - for (i, c) in s.char_indices().rev() { - if c == ' ' { - return (n - i - 1) as i32; - } - } - n as i32 - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -222,10 +198,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0058.Length of Last Word/README_EN.md b/solution/0000-0099/0058.Length of Last Word/README_EN.md index c48548d1862cf..89ef26a7771e8 100644 --- a/solution/0000-0099/0058.Length of Last Word/README_EN.md +++ b/solution/0000-0099/0058.Length of Last Word/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Reverse Traversal + Two Pointers** +### Solution 1: Reverse Traversal + Two Pointers We start traversing from the end of the string $s$, find the first character that is not a space, which is the last character of the last word, and mark the index as $i$. Then continue to traverse forward, find the first character that is a space, which is the character before the first character of the last word, and mark it as $j$. Then the length of the last word is $i - j$. @@ -52,8 +52,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. The sp -### **Python3** - ```python class Solution: def lengthOfLastWord(self, s: str) -> int: @@ -66,8 +64,6 @@ class Solution: return i - j ``` -### **Java** - ```java class Solution { public int lengthOfLastWord(String s) { @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +97,6 @@ public: }; ``` -### **Go** - ```go func lengthOfLastWord(s string) int { i := len(s) - 1 @@ -119,14 +111,8 @@ func lengthOfLastWord(s string) int { } ``` -### **JavaScript** - -```js -/** - * @param {string} s - * @return {number} - */ -var lengthOfLastWord = function (s) { +```ts +function lengthOfLastWord(s: string): number { let i = s.length - 1; while (i >= 0 && s[i] === ' ') { --i; @@ -136,13 +122,30 @@ var lengthOfLastWord = function (s) { --j; } return i - j; -}; +} ``` -### **TypeScript** +```rust +impl Solution { + pub fn length_of_last_word(s: String) -> i32 { + let s = s.trim_end(); + let n = s.len(); + for (i, c) in s.char_indices().rev() { + if c == ' ' { + return (n - i - 1) as i32; + } + } + n as i32 + } +} +``` -```ts -function lengthOfLastWord(s: string): number { +```js +/** + * @param {string} s + * @return {number} + */ +var lengthOfLastWord = function (s) { let i = s.length - 1; while (i >= 0 && s[i] === ' ') { --i; @@ -152,11 +155,9 @@ function lengthOfLastWord(s: string): number { --j; } return i - j; -} +}; ``` -### **C#** - ```cs public class Solution { public int LengthOfLastWord(string s) { @@ -173,25 +174,6 @@ public class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn length_of_last_word(s: String) -> i32 { - let s = s.trim_end(); - let n = s.len(); - for (i, c) in s.char_indices().rev() { - if c == ' ' { - return (n - i - 1) as i32; - } - } - n as i32 - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -212,10 +194,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0059.Spiral Matrix II/README.md b/solution/0000-0099/0059.Spiral Matrix II/README.md index cc06f927d8df9..00edff8b47dac 100644 --- a/solution/0000-0099/0059.Spiral Matrix II/README.md +++ b/solution/0000-0099/0059.Spiral Matrix II/README.md @@ -34,9 +34,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 直接模拟螺旋矩阵的生成过程。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python class Solution: def generateMatrix(self, n: int) -> List[List[int]]: @@ -68,10 +62,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] generateMatrix(int n) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func generateMatrix(n int) [][]int { ans := make([][]int, n) @@ -141,37 +127,6 @@ func generateMatrix(n int) [][]int { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number[][]} - */ -var generateMatrix = function (n) { - const ans = new Array(n).fill(0).map(() => new Array(n).fill(0)); - let [i, j, k] = [0, 0, 0]; - const dirs = [ - [0, 1], - [1, 0], - [0, -1], - [-1, 0], - ]; - for (let v = 1; v <= n * n; ++v) { - ans[i][j] = v; - let [x, y] = [i + dirs[k][0], j + dirs[k][1]]; - if (x < 0 || y < 0 || x >= n || y >= n || ans[x][y] > 0) { - k = (k + 1) % 4; - [x, y] = [i + dirs[k][0], j + dirs[k][1]]; - } - [i, j] = [x, y]; - } - return ans; -}; -``` - -### **TypeScript** - ```ts function generateMatrix(n: number): number[][] { let ans = Array.from({ length: n }, v => new Array(n)); @@ -197,33 +152,6 @@ function generateMatrix(n: number): number[][] { } ``` -```ts -function generateMatrix(n: number): number[][] { - const res = new Array(n).fill(0).map(() => new Array(n).fill(0)); - let num = 1; - for (let i = 0; i < Math.floor(n / 2); i++) { - for (let j = i; j < n - i - 1; j++) { - res[i][j] = num++; - } - for (let j = i; j < n - i - 1; j++) { - res[j][n - i - 1] = num++; - } - for (let j = i; j < n - i - 1; j++) { - res[n - i - 1][n - j - 1] = num++; - } - for (let j = i; j < n - i - 1; j++) { - res[n - j - 1][i] = num++; - } - } - if (n % 2 === 1) { - res[n >> 1][n >> 1] = num; - } - return res; -} -``` - -### **Rust** - ```rust impl Solution { pub fn generate_matrix(n: i32) -> Vec> { @@ -256,10 +184,64 @@ impl Solution { } ``` -### **...** - +```js +/** + * @param {number} n + * @return {number[][]} + */ +var generateMatrix = function (n) { + const ans = new Array(n).fill(0).map(() => new Array(n).fill(0)); + let [i, j, k] = [0, 0, 0]; + const dirs = [ + [0, 1], + [1, 0], + [0, -1], + [-1, 0], + ]; + for (let v = 1; v <= n * n; ++v) { + ans[i][j] = v; + let [x, y] = [i + dirs[k][0], j + dirs[k][1]]; + if (x < 0 || y < 0 || x >= n || y >= n || ans[x][y] > 0) { + k = (k + 1) % 4; + [x, y] = [i + dirs[k][0], j + dirs[k][1]]; + } + [i, j] = [x, y]; + } + return ans; +}; ``` + + +### 方法二 + + + +```ts +function generateMatrix(n: number): number[][] { + const res = new Array(n).fill(0).map(() => new Array(n).fill(0)); + let num = 1; + for (let i = 0; i < Math.floor(n / 2); i++) { + for (let j = i; j < n - i - 1; j++) { + res[i][j] = num++; + } + for (let j = i; j < n - i - 1; j++) { + res[j][n - i - 1] = num++; + } + for (let j = i; j < n - i - 1; j++) { + res[n - i - 1][n - j - 1] = num++; + } + for (let j = i; j < n - i - 1; j++) { + res[n - j - 1][i] = num++; + } + } + if (n % 2 === 1) { + res[n >> 1][n >> 1] = num; + } + return res; +} ``` + + diff --git a/solution/0000-0099/0059.Spiral Matrix II/README_EN.md b/solution/0000-0099/0059.Spiral Matrix II/README_EN.md index 4f5f2b9b66540..da12a8a0293de 100644 --- a/solution/0000-0099/0059.Spiral Matrix II/README_EN.md +++ b/solution/0000-0099/0059.Spiral Matrix II/README_EN.md @@ -30,7 +30,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation Directly simulate the generation process of the spiral matrix. @@ -42,8 +42,6 @@ The time complexity is $O(n^2)$, where $n$ is the side length of the matrix. Ign -### **Python3** - ```python class Solution: def generateMatrix(self, n: int) -> List[List[int]]: @@ -60,8 +58,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] generateMatrix(int n) { @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +102,6 @@ public: }; ``` -### **Go** - ```go func generateMatrix(n int) [][]int { ans := make([][]int, n) @@ -131,37 +123,6 @@ func generateMatrix(n int) [][]int { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number[][]} - */ -var generateMatrix = function (n) { - const ans = new Array(n).fill(0).map(() => new Array(n).fill(0)); - let [i, j, k] = [0, 0, 0]; - const dirs = [ - [0, 1], - [1, 0], - [0, -1], - [-1, 0], - ]; - for (let v = 1; v <= n * n; ++v) { - ans[i][j] = v; - let [x, y] = [i + dirs[k][0], j + dirs[k][1]]; - if (x < 0 || y < 0 || x >= n || y >= n || ans[x][y] > 0) { - k = (k + 1) % 4; - [x, y] = [i + dirs[k][0], j + dirs[k][1]]; - } - [i, j] = [x, y]; - } - return ans; -}; -``` - -### **TypeScript** - ```ts function generateMatrix(n: number): number[][] { let ans = Array.from({ length: n }, v => new Array(n)); @@ -187,33 +148,6 @@ function generateMatrix(n: number): number[][] { } ``` -```ts -function generateMatrix(n: number): number[][] { - const res = new Array(n).fill(0).map(() => new Array(n).fill(0)); - let num = 1; - for (let i = 0; i < Math.floor(n / 2); i++) { - for (let j = i; j < n - i - 1; j++) { - res[i][j] = num++; - } - for (let j = i; j < n - i - 1; j++) { - res[j][n - i - 1] = num++; - } - for (let j = i; j < n - i - 1; j++) { - res[n - i - 1][n - j - 1] = num++; - } - for (let j = i; j < n - i - 1; j++) { - res[n - j - 1][i] = num++; - } - } - if (n % 2 === 1) { - res[n >> 1][n >> 1] = num; - } - return res; -} -``` - -### **Rust** - ```rust impl Solution { pub fn generate_matrix(n: i32) -> Vec> { @@ -246,10 +180,64 @@ impl Solution { } ``` -### **...** - +```js +/** + * @param {number} n + * @return {number[][]} + */ +var generateMatrix = function (n) { + const ans = new Array(n).fill(0).map(() => new Array(n).fill(0)); + let [i, j, k] = [0, 0, 0]; + const dirs = [ + [0, 1], + [1, 0], + [0, -1], + [-1, 0], + ]; + for (let v = 1; v <= n * n; ++v) { + ans[i][j] = v; + let [x, y] = [i + dirs[k][0], j + dirs[k][1]]; + if (x < 0 || y < 0 || x >= n || y >= n || ans[x][y] > 0) { + k = (k + 1) % 4; + [x, y] = [i + dirs[k][0], j + dirs[k][1]]; + } + [i, j] = [x, y]; + } + return ans; +}; ``` + + +### Solution 2 + + + +```ts +function generateMatrix(n: number): number[][] { + const res = new Array(n).fill(0).map(() => new Array(n).fill(0)); + let num = 1; + for (let i = 0; i < Math.floor(n / 2); i++) { + for (let j = i; j < n - i - 1; j++) { + res[i][j] = num++; + } + for (let j = i; j < n - i - 1; j++) { + res[j][n - i - 1] = num++; + } + for (let j = i; j < n - i - 1; j++) { + res[n - i - 1][n - j - 1] = num++; + } + for (let j = i; j < n - i - 1; j++) { + res[n - j - 1][i] = num++; + } + } + if (n % 2 === 1) { + res[n >> 1][n >> 1] = num; + } + return res; +} ``` + + diff --git a/solution/0000-0099/0060.Permutation Sequence/README.md b/solution/0000-0099/0060.Permutation Sequence/README.md index b8f0a8c3358a9..ce50eea1722a2 100644 --- a/solution/0000-0099/0060.Permutation Sequence/README.md +++ b/solution/0000-0099/0060.Permutation Sequence/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们知道,集合 $[1,2,..n]$ 一共有 $n!$ 种排列,如果我们确定首位,那剩余位能组成的排列数量为 $(n-1)!$。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def getPermutation(self, n: int, k: int) -> str: @@ -93,10 +87,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String getPermutation(int n, int k) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go func getPermutation(n int, k int) string { ans := make([]byte, n) @@ -178,37 +164,6 @@ func getPermutation(n int, k int) string { } ``` -### **C#** - -```cs -public class Solution { - public string GetPermutation(int n, int k) { - var ans = new StringBuilder(); - int vis = 0; - for (int i = 0; i < n; ++i) { - int fact = 1; - for (int j = 1; j < n - i; ++j) { - fact *= j; - } - for (int j = 1; j <= n; ++j) { - if (((vis >> j) & 1) == 0) { - if (k > fact) { - k -= fact; - } else { - ans.Append(j); - vis |= 1 << j; - break; - } - } - } - } - return ans.ToString(); - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn get_permutation(n: i32, k: i32) -> String { @@ -241,10 +196,33 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public string GetPermutation(int n, int k) { + var ans = new StringBuilder(); + int vis = 0; + for (int i = 0; i < n; ++i) { + int fact = 1; + for (int j = 1; j < n - i; ++j) { + fact *= j; + } + for (int j = 1; j <= n; ++j) { + if (((vis >> j) & 1) == 0) { + if (k > fact) { + k -= fact; + } else { + ans.Append(j); + vis |= 1 << j; + break; + } + } + } + } + return ans.ToString(); + } +} ``` + + diff --git a/solution/0000-0099/0060.Permutation Sequence/README_EN.md b/solution/0000-0099/0060.Permutation Sequence/README_EN.md index 99d568056ded4..552b595f613f0 100644 --- a/solution/0000-0099/0060.Permutation Sequence/README_EN.md +++ b/solution/0000-0099/0060.Permutation Sequence/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We know that the set $[1,2,..n]$ has a total of $n!$ permutations. If we determine the first digit, the number of permutations that the remaining digits can form is $(n-1)!$. @@ -52,8 +52,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def getPermutation(self, n: int, k: int) -> str: @@ -74,8 +72,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String getPermutation(int n, int k) { @@ -103,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +124,6 @@ public: }; ``` -### **Go** - ```go func getPermutation(n int, k int) string { ans := make([]byte, n) @@ -157,37 +149,6 @@ func getPermutation(n int, k int) string { } ``` -### **C#** - -```cs -public class Solution { - public string GetPermutation(int n, int k) { - var ans = new StringBuilder(); - int vis = 0; - for (int i = 0; i < n; ++i) { - int fact = 1; - for (int j = 1; j < n - i; ++j) { - fact *= j; - } - for (int j = 1; j <= n; ++j) { - if (((vis >> j) & 1) == 0) { - if (k > fact) { - k -= fact; - } else { - ans.Append(j); - vis |= 1 << j; - break; - } - } - } - } - return ans.ToString(); - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn get_permutation(n: i32, k: i32) -> String { @@ -220,10 +181,33 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public string GetPermutation(int n, int k) { + var ans = new StringBuilder(); + int vis = 0; + for (int i = 0; i < n; ++i) { + int fact = 1; + for (int j = 1; j < n - i; ++j) { + fact *= j; + } + for (int j = 1; j <= n; ++j) { + if (((vis >> j) & 1) == 0) { + if (k > fact) { + k -= fact; + } else { + ans.Append(j); + vis |= 1 << j; + break; + } + } + } + } + return ans.ToString(); + } +} ``` + + diff --git a/solution/0000-0099/0061.Rotate List/README.md b/solution/0000-0099/0061.Rotate List/README.md index 27de281ce73a8..878679f647a1c 100644 --- a/solution/0000-0099/0061.Rotate List/README.md +++ b/solution/0000-0099/0061.Rotate List/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:快慢指针 + 链表拼接** +### 方法一:快慢指针 + 链表拼接 我们先判断链表节点数是否小于 $2$,如果是,直接返回 $head$ 即可。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -179,8 +167,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -218,8 +204,6 @@ func rotateRight(head *ListNode, k int) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -263,54 +247,6 @@ function rotateRight(head: ListNode | null, k: number): ListNode | null { } ``` -### **C#** - -```cs -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public ListNode RotateRight(ListNode head, int k) { - if (head == null || head.next == null) { - return head; - } - var cur = head; - int n = 0; - while (cur != null) { - cur = cur.next; - ++n; - } - k %= n; - if (k == 0) { - return head; - } - var fast = head; - var slow = head; - while (k-- > 0) { - fast = fast.next; - } - while (fast.next != null) { - fast = fast.next; - slow = slow.next; - } - var ans = slow.next; - slow.next = null; - fast.next = head; - return ans; - } -} -``` - -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -362,10 +298,50 @@ impl Solution { } ``` -### **...** - -``` - +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode RotateRight(ListNode head, int k) { + if (head == null || head.next == null) { + return head; + } + var cur = head; + int n = 0; + while (cur != null) { + cur = cur.next; + ++n; + } + k %= n; + if (k == 0) { + return head; + } + var fast = head; + var slow = head; + while (k-- > 0) { + fast = fast.next; + } + while (fast.next != null) { + fast = fast.next; + slow = slow.next; + } + var ans = slow.next; + slow.next = null; + fast.next = head; + return ans; + } +} ``` + + diff --git a/solution/0000-0099/0061.Rotate List/README_EN.md b/solution/0000-0099/0061.Rotate List/README_EN.md index d486874542562..bfc6e47f67ba6 100644 --- a/solution/0000-0099/0061.Rotate List/README_EN.md +++ b/solution/0000-0099/0061.Rotate List/README_EN.md @@ -32,7 +32,7 @@ ## Solutions -**Solution 1: Fast and Slow Pointers + Link List Concatenation** +### Solution 1: Fast and Slow Pointers + Link List Concatenation First, we check whether the number of nodes in the linked list is less than $2$. If so, we directly return $head$. @@ -48,8 +48,6 @@ The time complexity is $O(n)$, where $n$ is the number of nodes in the linked li -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -79,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -123,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -169,8 +163,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -208,8 +200,6 @@ func rotateRight(head *ListNode, k int) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -253,54 +243,6 @@ function rotateRight(head: ListNode | null, k: number): ListNode | null { } ``` -### **C#** - -```cs -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public ListNode RotateRight(ListNode head, int k) { - if (head == null || head.next == null) { - return head; - } - var cur = head; - int n = 0; - while (cur != null) { - cur = cur.next; - ++n; - } - k %= n; - if (k == 0) { - return head; - } - var fast = head; - var slow = head; - while (k-- > 0) { - fast = fast.next; - } - while (fast.next != null) { - fast = fast.next; - slow = slow.next; - } - var ans = slow.next; - slow.next = null; - fast.next = head; - return ans; - } -} -``` - -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -352,10 +294,50 @@ impl Solution { } ``` -### **...** - -``` - +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode RotateRight(ListNode head, int k) { + if (head == null || head.next == null) { + return head; + } + var cur = head; + int n = 0; + while (cur != null) { + cur = cur.next; + ++n; + } + k %= n; + if (k == 0) { + return head; + } + var fast = head; + var slow = head; + while (k-- > 0) { + fast = fast.next; + } + while (fast.next != null) { + fast = fast.next; + slow = slow.next; + } + var ans = slow.next; + slow.next = null; + fast.next = head; + return ans; + } +} ``` + + diff --git a/solution/0000-0099/0062.Unique Paths/README.md b/solution/0000-0099/0062.Unique Paths/README.md index 48338a00d0aea..68b9ba1c489a1 100644 --- a/solution/0000-0099/0062.Unique Paths/README.md +++ b/solution/0000-0099/0062.Unique Paths/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示从左上角走到 $(i, j)$ 的路径数量,初始时 $f[0][0] = 1$,答案为 $f[m - 1][n - 1]$。 @@ -84,10 +82,6 @@ $$ -### **Python3** - - - ```python class Solution: def uniquePaths(self, m: int, n: int) -> int: @@ -102,30 +96,6 @@ class Solution: return f[-1][-1] ``` -```python -class Solution: - def uniquePaths(self, m: int, n: int) -> int: - f = [[1] * n for _ in range(m)] - for i in range(1, m): - for j in range(1, n): - f[i][j] = f[i - 1][j] + f[i][j - 1] - return f[-1][-1] -``` - -```python -class Solution: - def uniquePaths(self, m: int, n: int) -> int: - f = [1] * n - for _ in range(1, m): - for j in range(1, n): - f[j] += f[j - 1] - return f[-1] -``` - -### **Java** - - - ```java class Solution { public int uniquePaths(int m, int n) { @@ -146,40 +116,6 @@ class Solution { } ``` -```java -class Solution { - public int uniquePaths(int m, int n) { - var f = new int[m][n]; - for (var g : f) { - Arrays.fill(g, 1); - } - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; j++) { - f[i][j] = f[i - 1][j] + f[i][j - 1]; - } - } - return f[m - 1][n - 1]; - } -} -``` - -```java -class Solution { - public int uniquePaths(int m, int n) { - int[] f = new int[n]; - Arrays.fill(f, 1); - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[j] += f[j - 1]; - } - } - return f[n - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -201,38 +137,6 @@ public: }; ``` -```cpp -class Solution { -public: - int uniquePaths(int m, int n) { - vector> f(m, vector(n, 1)); - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[i][j] = f[i - 1][j] + f[i][j - 1]; - } - } - return f[m - 1][n - 1]; - } -}; -``` - -```cpp -class Solution { -public: - int uniquePaths(int m, int n) { - vector f(n, 1); - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[j] += f[j - 1]; - } - } - return f[n - 1]; - } -}; -``` - -### **Go** - ```go func uniquePaths(m int, n int) int { f := make([][]int, m) @@ -254,41 +158,6 @@ func uniquePaths(m int, n int) int { } ``` -```go -func uniquePaths(m int, n int) int { - f := make([][]int, m) - for i := range f { - f[i] = make([]int, n) - for j := range f[i] { - f[i][j] = 1 - } - } - for i := 1; i < m; i++ { - for j := 1; j < n; j++ { - f[i][j] = f[i-1][j] + f[i][j-1] - } - } - return f[m-1][n-1] -} -``` - -```go -func uniquePaths(m int, n int) int { - f := make([]int, n+1) - for i := range f { - f[i] = 1 - } - for i := 1; i < m; i++ { - for j := 1; j < n; j++ { - f[j] += f[j-1] - } - } - return f[n-1] -} -``` - -### **TypeScript** - ```ts function uniquePaths(m: number, n: number): number { const f: number[][] = Array(m) @@ -309,34 +178,21 @@ function uniquePaths(m: number, n: number): number { } ``` -```ts -function uniquePaths(m: number, n: number): number { - const f: number[][] = Array(m) - .fill(0) - .map(() => Array(n).fill(1)); - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { - f[i][j] = f[i - 1][j] + f[i][j - 1]; - } - } - return f[m - 1][n - 1]; -} -``` - -```ts -function uniquePaths(m: number, n: number): number { - const f: number[] = Array(n).fill(1); - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { - f[j] += f[j - 1]; +```rust +impl Solution { + pub fn unique_paths(m: i32, n: i32) -> i32 { + let (m, n) = (m as usize, n as usize); + let mut f = vec![1; n]; + for i in 1..m { + for j in 1..n { + f[j] += f[j - 1]; + } } + f[n - 1] } - return f[n - 1]; } ``` -### **JavaScript** - ```js /** * @param {number} m @@ -362,14 +218,75 @@ var uniquePaths = function (m, n) { }; ``` -```js -/** - * @param {number} m - * @param {number} n - * @return {number} - */ -var uniquePaths = function (m, n) { - const f = Array(m) + + +### 方法二 + + + +```python +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + f = [[1] * n for _ in range(m)] + for i in range(1, m): + for j in range(1, n): + f[i][j] = f[i - 1][j] + f[i][j - 1] + return f[-1][-1] +``` + +```java +class Solution { + public int uniquePaths(int m, int n) { + var f = new int[m][n]; + for (var g : f) { + Arrays.fill(g, 1); + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; j++) { + f[i][j] = f[i - 1][j] + f[i][j - 1]; + } + } + return f[m - 1][n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int uniquePaths(int m, int n) { + vector> f(m, vector(n, 1)); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[i][j] = f[i - 1][j] + f[i][j - 1]; + } + } + return f[m - 1][n - 1]; + } +}; +``` + +```go +func uniquePaths(m int, n int) int { + f := make([][]int, m) + for i := range f { + f[i] = make([]int, n) + for j := range f[i] { + f[i][j] = 1 + } + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + f[i][j] = f[i-1][j] + f[i][j-1] + } + } + return f[m-1][n-1] +} +``` + +```ts +function uniquePaths(m: number, n: number): number { + const f: number[][] = Array(m) .fill(0) .map(() => Array(n).fill(1)); for (let i = 1; i < m; ++i) { @@ -378,7 +295,7 @@ var uniquePaths = function (m, n) { } } return f[m - 1][n - 1]; -}; +} ``` ```js @@ -388,37 +305,108 @@ var uniquePaths = function (m, n) { * @return {number} */ var uniquePaths = function (m, n) { - const f = Array(n).fill(1); + const f = Array(m) + .fill(0) + .map(() => Array(n).fill(1)); for (let i = 1; i < m; ++i) { for (let j = 1; j < n; ++j) { - f[j] += f[j - 1]; + f[i][j] = f[i - 1][j] + f[i][j - 1]; } } - return f[n - 1]; + return f[m - 1][n - 1]; }; ``` -### **Rust** + -```rust -impl Solution { - pub fn unique_paths(m: i32, n: i32) -> i32 { - let (m, n) = (m as usize, n as usize); - let mut f = vec![1; n]; - for i in 1..m { - for j in 1..n { +### 方法三 + + + +```python +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + f = [1] * n + for _ in range(1, m): + for j in range(1, n): + f[j] += f[j - 1] + return f[-1] +``` + +```java +class Solution { + public int uniquePaths(int m, int n) { + int[] f = new int[n]; + Arrays.fill(f, 1); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { f[j] += f[j - 1]; } } - f[n - 1] + return f[n - 1]; } } ``` -### **...** +```cpp +class Solution { +public: + int uniquePaths(int m, int n) { + vector f(n, 1); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; + } +}; +``` +```go +func uniquePaths(m int, n int) int { + f := make([]int, n+1) + for i := range f { + f[i] = 1 + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + f[j] += f[j-1] + } + } + return f[n-1] +} +``` + +```ts +function uniquePaths(m: number, n: number): number { + const f: number[] = Array(n).fill(1); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; +} ``` +```js +/** + * @param {number} m + * @param {number} n + * @return {number} + */ +var uniquePaths = function (m, n) { + const f = Array(n).fill(1); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; +}; ``` + + diff --git a/solution/0000-0099/0062.Unique Paths/README_EN.md b/solution/0000-0099/0062.Unique Paths/README_EN.md index 7b9e2425a1b14..0225cf10d683f 100644 --- a/solution/0000-0099/0062.Unique Paths/README_EN.md +++ b/solution/0000-0099/0062.Unique Paths/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ to represent the number of paths from the top left corner to $(i, j)$, initially $f[0][0] = 1$, and the answer is $f[m - 1][n - 1]$. @@ -64,8 +64,6 @@ We notice that $f[i][j]$ is only related to $f[i - 1][j]$ and $f[i][j - 1]$, so -### **Python3** - ```python class Solution: def uniquePaths(self, m: int, n: int) -> int: @@ -80,28 +78,6 @@ class Solution: return f[-1][-1] ``` -```python -class Solution: - def uniquePaths(self, m: int, n: int) -> int: - f = [[1] * n for _ in range(m)] - for i in range(1, m): - for j in range(1, n): - f[i][j] = f[i - 1][j] + f[i][j - 1] - return f[-1][-1] -``` - -```python -class Solution: - def uniquePaths(self, m: int, n: int) -> int: - f = [1] * n - for _ in range(1, m): - for j in range(1, n): - f[j] += f[j - 1] - return f[-1] -``` - -### **Java** - ```java class Solution { public int uniquePaths(int m, int n) { @@ -122,40 +98,6 @@ class Solution { } ``` -```java -class Solution { - public int uniquePaths(int m, int n) { - var f = new int[m][n]; - for (var g : f) { - Arrays.fill(g, 1); - } - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; j++) { - f[i][j] = f[i - 1][j] + f[i][j - 1]; - } - } - return f[m - 1][n - 1]; - } -} -``` - -```java -class Solution { - public int uniquePaths(int m, int n) { - int[] f = new int[n]; - Arrays.fill(f, 1); - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[j] += f[j - 1]; - } - } - return f[n - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -177,38 +119,6 @@ public: }; ``` -```cpp -class Solution { -public: - int uniquePaths(int m, int n) { - vector> f(m, vector(n, 1)); - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[i][j] = f[i - 1][j] + f[i][j - 1]; - } - } - return f[m - 1][n - 1]; - } -}; -``` - -```cpp -class Solution { -public: - int uniquePaths(int m, int n) { - vector f(n, 1); - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[j] += f[j - 1]; - } - } - return f[n - 1]; - } -}; -``` - -### **Go** - ```go func uniquePaths(m int, n int) int { f := make([][]int, m) @@ -230,41 +140,6 @@ func uniquePaths(m int, n int) int { } ``` -```go -func uniquePaths(m int, n int) int { - f := make([][]int, m) - for i := range f { - f[i] = make([]int, n) - for j := range f[i] { - f[i][j] = 1 - } - } - for i := 1; i < m; i++ { - for j := 1; j < n; j++ { - f[i][j] = f[i-1][j] + f[i][j-1] - } - } - return f[m-1][n-1] -} -``` - -```go -func uniquePaths(m int, n int) int { - f := make([]int, n+1) - for i := range f { - f[i] = 1 - } - for i := 1; i < m; i++ { - for j := 1; j < n; j++ { - f[j] += f[j-1] - } - } - return f[n-1] -} -``` - -### **TypeScript** - ```ts function uniquePaths(m: number, n: number): number { const f: number[][] = Array(m) @@ -285,34 +160,21 @@ function uniquePaths(m: number, n: number): number { } ``` -```ts -function uniquePaths(m: number, n: number): number { - const f: number[][] = Array(m) - .fill(0) - .map(() => Array(n).fill(1)); - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { - f[i][j] = f[i - 1][j] + f[i][j - 1]; - } - } - return f[m - 1][n - 1]; -} -``` - -```ts -function uniquePaths(m: number, n: number): number { - const f: number[] = Array(n).fill(1); - for (let i = 1; i < m; ++i) { - for (let j = 1; j < n; ++j) { - f[j] += f[j - 1]; +```rust +impl Solution { + pub fn unique_paths(m: i32, n: i32) -> i32 { + let (m, n) = (m as usize, n as usize); + let mut f = vec![1; n]; + for i in 1..m { + for j in 1..n { + f[j] += f[j - 1]; + } } + f[n - 1] } - return f[n - 1]; } ``` -### **JavaScript** - ```js /** * @param {number} m @@ -338,14 +200,75 @@ var uniquePaths = function (m, n) { }; ``` -```js -/** - * @param {number} m - * @param {number} n - * @return {number} - */ -var uniquePaths = function (m, n) { - const f = Array(m) + + +### Solution 2 + + + +```python +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + f = [[1] * n for _ in range(m)] + for i in range(1, m): + for j in range(1, n): + f[i][j] = f[i - 1][j] + f[i][j - 1] + return f[-1][-1] +``` + +```java +class Solution { + public int uniquePaths(int m, int n) { + var f = new int[m][n]; + for (var g : f) { + Arrays.fill(g, 1); + } + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; j++) { + f[i][j] = f[i - 1][j] + f[i][j - 1]; + } + } + return f[m - 1][n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int uniquePaths(int m, int n) { + vector> f(m, vector(n, 1)); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[i][j] = f[i - 1][j] + f[i][j - 1]; + } + } + return f[m - 1][n - 1]; + } +}; +``` + +```go +func uniquePaths(m int, n int) int { + f := make([][]int, m) + for i := range f { + f[i] = make([]int, n) + for j := range f[i] { + f[i][j] = 1 + } + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + f[i][j] = f[i-1][j] + f[i][j-1] + } + } + return f[m-1][n-1] +} +``` + +```ts +function uniquePaths(m: number, n: number): number { + const f: number[][] = Array(m) .fill(0) .map(() => Array(n).fill(1)); for (let i = 1; i < m; ++i) { @@ -354,7 +277,7 @@ var uniquePaths = function (m, n) { } } return f[m - 1][n - 1]; -}; +} ``` ```js @@ -364,37 +287,108 @@ var uniquePaths = function (m, n) { * @return {number} */ var uniquePaths = function (m, n) { - const f = Array(n).fill(1); + const f = Array(m) + .fill(0) + .map(() => Array(n).fill(1)); for (let i = 1; i < m; ++i) { for (let j = 1; j < n; ++j) { - f[j] += f[j - 1]; + f[i][j] = f[i - 1][j] + f[i][j - 1]; } } - return f[n - 1]; + return f[m - 1][n - 1]; }; ``` -### **Rust** + -```rust -impl Solution { - pub fn unique_paths(m: i32, n: i32) -> i32 { - let (m, n) = (m as usize, n as usize); - let mut f = vec![1; n]; - for i in 1..m { - for j in 1..n { +### Solution 3 + + + +```python +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + f = [1] * n + for _ in range(1, m): + for j in range(1, n): + f[j] += f[j - 1] + return f[-1] +``` + +```java +class Solution { + public int uniquePaths(int m, int n) { + int[] f = new int[n]; + Arrays.fill(f, 1); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { f[j] += f[j - 1]; } } - f[n - 1] + return f[n - 1]; } } ``` -### **...** +```cpp +class Solution { +public: + int uniquePaths(int m, int n) { + vector f(n, 1); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; + } +}; +``` + +```go +func uniquePaths(m int, n int) int { + f := make([]int, n+1) + for i := range f { + f[i] = 1 + } + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + f[j] += f[j-1] + } + } + return f[n-1] +} +``` +```ts +function uniquePaths(m: number, n: number): number { + const f: number[] = Array(n).fill(1); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; +} ``` +```js +/** + * @param {number} m + * @param {number} n + * @return {number} + */ +var uniquePaths = function (m, n) { + const f = Array(n).fill(1); + for (let i = 1; i < m; ++i) { + for (let j = 1; j < n; ++j) { + f[j] += f[j - 1]; + } + } + return f[n - 1]; +}; ``` + + diff --git a/solution/0000-0099/0063.Unique Paths II/README.md b/solution/0000-0099/0063.Unique Paths II/README.md index ca09b0d53109c..6317391787aa1 100644 --- a/solution/0000-0099/0063.Unique Paths II/README.md +++ b/solution/0000-0099/0063.Unique Paths II/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $dp[i][j]$ 表示到达网格 $(i,j)$ 的路径数。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: @@ -88,10 +82,6 @@ class Solution: return dp[-1][-1] ``` -### **Java** - - - ```java class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func uniquePathsWithObstacles(obstacleGrid [][]int) int { m, n := len(obstacleGrid), len(obstacleGrid[0]) @@ -167,8 +153,6 @@ func uniquePathsWithObstacles(obstacleGrid [][]int) int { } ``` -### **TypeScript** - ```ts function uniquePathsWithObstacles(obstacleGrid: number[][]): number { const m = obstacleGrid.length; @@ -198,8 +182,6 @@ function uniquePathsWithObstacles(obstacleGrid: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn unique_paths_with_obstacles(obstacle_grid: Vec>) -> i32 { @@ -234,10 +216,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0063.Unique Paths II/README_EN.md b/solution/0000-0099/0063.Unique Paths II/README_EN.md index 12a3dba0d0d47..8da60bc1ecd3e 100644 --- a/solution/0000-0099/0063.Unique Paths II/README_EN.md +++ b/solution/0000-0099/0063.Unique Paths II/README_EN.md @@ -43,7 +43,7 @@ There are two ways to reach the bottom-right corner: ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $dp[i][j]$ to represent the number of paths to reach the grid $(i,j)$. @@ -58,8 +58,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times -### **Python3** - ```python class Solution: def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: @@ -80,8 +78,6 @@ class Solution: return dp[-1][-1] ``` -### **Java** - ```java class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { @@ -105,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +125,6 @@ public: }; ``` -### **Go** - ```go func uniquePathsWithObstacles(obstacleGrid [][]int) int { m, n := len(obstacleGrid), len(obstacleGrid[0]) @@ -157,8 +149,6 @@ func uniquePathsWithObstacles(obstacleGrid [][]int) int { } ``` -### **TypeScript** - ```ts function uniquePathsWithObstacles(obstacleGrid: number[][]): number { const m = obstacleGrid.length; @@ -188,8 +178,6 @@ function uniquePathsWithObstacles(obstacleGrid: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn unique_paths_with_obstacles(obstacle_grid: Vec>) -> i32 { @@ -224,10 +212,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0064.Minimum Path Sum/README.md b/solution/0000-0099/0064.Minimum Path Sum/README.md index 0afc78dd398a4..e48b9da944a96 100644 --- a/solution/0000-0099/0064.Minimum Path Sum/README.md +++ b/solution/0000-0099/0064.Minimum Path Sum/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示从左上角走到 $(i, j)$ 位置的最小路径和。初始时 $f[0][0] = grid[0][0]$,答案为 $f[m - 1][n - 1]$。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def minPathSum(self, grid: List[List[int]]) -> int: @@ -78,10 +72,6 @@ class Solution: return f[-1][-1] ``` -### **Java** - - - ```java class Solution { public int minPathSum(int[][] grid) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func minPathSum(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -154,8 +140,6 @@ func minPathSum(grid [][]int) int { } ``` -### **TypeScript** - ```ts function minPathSum(grid: number[][]): number { const m = grid.length; @@ -179,32 +163,27 @@ function minPathSum(grid: number[][]): number { } ``` -### **C#** - -```cs -public class Solution { - public int MinPathSum(int[][] grid) { - int m = grid.Length, n = grid[0].Length; - int[,] f = new int[m, n]; - f[0, 0] = grid[0][0]; - for (int i = 1; i < m; ++i) { - f[i, 0] = f[i - 1, 0] + grid[i][0]; +```rust +impl Solution { + pub fn min_path_sum(mut grid: Vec>) -> i32 { + let m = grid.len(); + let n = grid[0].len(); + for i in 1..m { + grid[i][0] += grid[i - 1][0]; } - for (int j = 1; j < n; ++j) { - f[0, j] = f[0, j - 1] + grid[0][j]; + for i in 1..n { + grid[0][i] += grid[0][i - 1]; } - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[i, j] = Math.Min(f[i - 1, j], f[i, j - 1]) + grid[i][j]; + for i in 1..m { + for j in 1..n { + grid[i][j] += grid[i][j - 1].min(grid[i - 1][j]); } } - return f[m - 1, n - 1]; + grid[m - 1][n - 1] } } ``` -### **JavaScript** - ```js /** * @param {number[][]} grid @@ -232,33 +211,28 @@ var minPathSum = function (grid) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn min_path_sum(mut grid: Vec>) -> i32 { - let m = grid.len(); - let n = grid[0].len(); - for i in 1..m { - grid[i][0] += grid[i - 1][0]; +```cs +public class Solution { + public int MinPathSum(int[][] grid) { + int m = grid.Length, n = grid[0].Length; + int[,] f = new int[m, n]; + f[0, 0] = grid[0][0]; + for (int i = 1; i < m; ++i) { + f[i, 0] = f[i - 1, 0] + grid[i][0]; } - for i in 1..n { - grid[0][i] += grid[0][i - 1]; + for (int j = 1; j < n; ++j) { + f[0, j] = f[0, j - 1] + grid[0][j]; } - for i in 1..m { - for j in 1..n { - grid[i][j] += grid[i][j - 1].min(grid[i - 1][j]); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[i, j] = Math.Min(f[i - 1, j], f[i, j - 1]) + grid[i][j]; } } - grid[m - 1][n - 1] + return f[m - 1, n - 1]; } } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0064.Minimum Path Sum/README_EN.md b/solution/0000-0099/0064.Minimum Path Sum/README_EN.md index 6b5ce492fd4b7..3cf00148c1341 100644 --- a/solution/0000-0099/0064.Minimum Path Sum/README_EN.md +++ b/solution/0000-0099/0064.Minimum Path Sum/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ to represent the minimum path sum from the top left corner to $(i, j)$. Initially, $f[0][0] = grid[0][0]$, and the answer is $f[m - 1][n - 1]$. @@ -52,8 +52,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times -### **Python3** - ```python class Solution: def minPathSum(self, grid: List[List[int]]) -> int: @@ -70,8 +68,6 @@ class Solution: return f[-1][-1] ``` -### **Java** - ```java class Solution { public int minPathSum(int[][] grid) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +113,6 @@ public: }; ``` -### **Go** - ```go func minPathSum(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -144,8 +136,6 @@ func minPathSum(grid [][]int) int { } ``` -### **TypeScript** - ```ts function minPathSum(grid: number[][]): number { const m = grid.length; @@ -169,32 +159,27 @@ function minPathSum(grid: number[][]): number { } ``` -### **C#** - -```cs -public class Solution { - public int MinPathSum(int[][] grid) { - int m = grid.Length, n = grid[0].Length; - int[,] f = new int[m, n]; - f[0, 0] = grid[0][0]; - for (int i = 1; i < m; ++i) { - f[i, 0] = f[i - 1, 0] + grid[i][0]; +```rust +impl Solution { + pub fn min_path_sum(mut grid: Vec>) -> i32 { + let m = grid.len(); + let n = grid[0].len(); + for i in 1..m { + grid[i][0] += grid[i - 1][0]; } - for (int j = 1; j < n; ++j) { - f[0, j] = f[0, j - 1] + grid[0][j]; + for i in 1..n { + grid[0][i] += grid[0][i - 1]; } - for (int i = 1; i < m; ++i) { - for (int j = 1; j < n; ++j) { - f[i, j] = Math.Min(f[i - 1, j], f[i, j - 1]) + grid[i][j]; + for i in 1..m { + for j in 1..n { + grid[i][j] += grid[i][j - 1].min(grid[i - 1][j]); } } - return f[m - 1, n - 1]; + grid[m - 1][n - 1] } } ``` -### **JavaScript** - ```js /** * @param {number[][]} grid @@ -222,33 +207,28 @@ var minPathSum = function (grid) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn min_path_sum(mut grid: Vec>) -> i32 { - let m = grid.len(); - let n = grid[0].len(); - for i in 1..m { - grid[i][0] += grid[i - 1][0]; +```cs +public class Solution { + public int MinPathSum(int[][] grid) { + int m = grid.Length, n = grid[0].Length; + int[,] f = new int[m, n]; + f[0, 0] = grid[0][0]; + for (int i = 1; i < m; ++i) { + f[i, 0] = f[i - 1, 0] + grid[i][0]; } - for i in 1..n { - grid[0][i] += grid[0][i - 1]; + for (int j = 1; j < n; ++j) { + f[0, j] = f[0, j - 1] + grid[0][j]; } - for i in 1..m { - for j in 1..n { - grid[i][j] += grid[i][j - 1].min(grid[i - 1][j]); + for (int i = 1; i < m; ++i) { + for (int j = 1; j < n; ++j) { + f[i, j] = Math.Min(f[i - 1, j], f[i, j - 1]) + grid[i][j]; } } - grid[m - 1][n - 1] + return f[m - 1, n - 1]; } } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0065.Valid Number/README.md b/solution/0000-0099/0065.Valid Number/README.md index fddc5bbaa130d..b79dc353e1fc3 100644 --- a/solution/0000-0099/0065.Valid Number/README.md +++ b/solution/0000-0099/0065.Valid Number/README.md @@ -73,9 +73,7 @@ ## 解法 - - -**方法一:分情况讨论** +### 方法一:分情况讨论 首先,我们判断字符串是否以正负号开头,如果是,将指针 $i$ 向后移动一位。如果此时指针 $i$ 已经到达字符串末尾,说明字符串只有一个正负号,返回 `false`。 @@ -95,10 +93,6 @@ -### **Python3** - - - ```python class Solution: def isNumber(self, s: str) -> bool: @@ -131,10 +125,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean isNumber(String s) { @@ -176,8 +166,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -206,8 +194,6 @@ public: }; ``` -### **Go** - ```go func isNumber(s string) bool { i, n := 0, len(s) @@ -246,22 +232,6 @@ func isNumber(s string) bool { } ``` -### **C#** - -```cs -using System.Text.RegularExpressions; - -public class Solution { - private readonly Regex _isNumber_Regex = new Regex(@"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([Ee][+-]?\d+)?\s*$"); - - public bool IsNumber(string s) { - return _isNumber_Regex.IsMatch(s); - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn is_number(s: String) -> bool { @@ -322,10 +292,18 @@ impl Solution { } ``` -### **...** +```cs +using System.Text.RegularExpressions; -``` +public class Solution { + private readonly Regex _isNumber_Regex = new Regex(@"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([Ee][+-]?\d+)?\s*$"); + public bool IsNumber(string s) { + return _isNumber_Regex.IsMatch(s); + } +} ``` + + diff --git a/solution/0000-0099/0065.Valid Number/README_EN.md b/solution/0000-0099/0065.Valid Number/README_EN.md index d1ede25f31a44..30d1c07040fee 100644 --- a/solution/0000-0099/0065.Valid Number/README_EN.md +++ b/solution/0000-0099/0065.Valid Number/README_EN.md @@ -67,7 +67,7 @@ ## Solutions -**Solution 1: Case Discussion** +### Solution 1: Case Discussion First, we check if the string starts with a positive or negative sign. If it does, we move the pointer $i$ one step forward. If the pointer $i$ has reached the end of the string at this point, it means the string only contains a positive or negative sign, so we return `false`. @@ -87,8 +87,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is -### **Python3** - ```python class Solution: def isNumber(self, s: str) -> bool: @@ -121,8 +119,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean isNumber(String s) { @@ -164,8 +160,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -194,8 +188,6 @@ public: }; ``` -### **Go** - ```go func isNumber(s string) bool { i, n := 0, len(s) @@ -234,22 +226,6 @@ func isNumber(s string) bool { } ``` -### **C#** - -```cs -using System.Text.RegularExpressions; - -public class Solution { - private readonly Regex _isNumber_Regex = new Regex(@"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([Ee][+-]?\d+)?\s*$"); - - public bool IsNumber(string s) { - return _isNumber_Regex.IsMatch(s); - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn is_number(s: String) -> bool { @@ -310,10 +286,18 @@ impl Solution { } ``` -### **...** +```cs +using System.Text.RegularExpressions; -``` +public class Solution { + private readonly Regex _isNumber_Regex = new Regex(@"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([Ee][+-]?\d+)?\s*$"); + public bool IsNumber(string s) { + return _isNumber_Regex.IsMatch(s); + } +} ``` + + diff --git a/solution/0000-0099/0066.Plus One/README.md b/solution/0000-0099/0066.Plus One/README.md index cebb148fafd2d..3468a2c16dc38 100644 --- a/solution/0000-0099/0066.Plus One/README.md +++ b/solution/0000-0099/0066.Plus One/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们从数组的最后一个元素开始遍历,将当前元素加一,然后对 $10$ 取模,如果取模后的结果不为 $0$,说明当前元素没有进位,直接返回数组即可。否则,当前元素为 $0$,需要进位,继续遍历前一个元素,重复上述操作。如果遍历完数组后,仍然没有返回,说明数组中所有元素都为 $0$,需要在数组的头部插入一个 $1$。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def plusOne(self, digits: List[int]) -> List[int]: @@ -74,10 +68,6 @@ class Solution: return [1] + digits ``` -### **Java** - - - ```java class Solution { public int[] plusOne(int[] digits) { @@ -96,27 +86,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} digits - * @return {number[]} - */ -var plusOne = function (digits) { - for (let i = digits.length - 1; i >= 0; --i) { - ++digits[i]; - digits[i] %= 10; - if (digits[i] != 0) { - return digits; - } - } - return [1, ...digits]; -}; -``` - -### **C++** - ```cpp class Solution { public: @@ -132,8 +101,6 @@ public: }; ``` -### **Go** - ```go func plusOne(digits []int) []int { n := len(digits) @@ -148,8 +115,6 @@ func plusOne(digits []int) []int { } ``` -### **TypeScript** - ```ts function plusOne(digits: number[]): number[] { const n = digits.length; @@ -163,8 +128,6 @@ function plusOne(digits: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn plus_one(mut digits: Vec) -> Vec { @@ -182,10 +145,23 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} digits + * @return {number[]} + */ +var plusOne = function (digits) { + for (let i = digits.length - 1; i >= 0; --i) { + ++digits[i]; + digits[i] %= 10; + if (digits[i] != 0) { + return digits; + } + } + return [1, ...digits]; +}; ``` + + diff --git a/solution/0000-0099/0066.Plus One/README_EN.md b/solution/0000-0099/0066.Plus One/README_EN.md index 4c0a83ae214f7..1c146342359f7 100644 --- a/solution/0000-0099/0066.Plus One/README_EN.md +++ b/solution/0000-0099/0066.Plus One/README_EN.md @@ -50,7 +50,7 @@ Thus, the result should be [1,0]. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We start traversing from the last element of the array, add one to the current element, and then take the modulus by $10$. If the result is not $0$, it means that there is no carry for the current element, and we can directly return the array. Otherwise, the current element is $0$ and needs to be carried over. We continue to traverse the previous element and repeat the above operation. If we still haven't returned after traversing the array, it means that all elements in the array are $0$, and we need to insert a $1$ at the beginning of the array. @@ -58,8 +58,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. Ignoring th -### **Python3** - ```python class Solution: def plusOne(self, digits: List[int]) -> List[int]: @@ -72,8 +70,6 @@ class Solution: return [1] + digits ``` -### **Java** - ```java class Solution { public int[] plusOne(int[] digits) { @@ -92,27 +88,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} digits - * @return {number[]} - */ -var plusOne = function (digits) { - for (let i = digits.length - 1; i >= 0; --i) { - ++digits[i]; - digits[i] %= 10; - if (digits[i] != 0) { - return digits; - } - } - return [1, ...digits]; -}; -``` - -### **C++** - ```cpp class Solution { public: @@ -128,8 +103,6 @@ public: }; ``` -### **Go** - ```go func plusOne(digits []int) []int { n := len(digits) @@ -144,8 +117,6 @@ func plusOne(digits []int) []int { } ``` -### **TypeScript** - ```ts function plusOne(digits: number[]): number[] { const n = digits.length; @@ -159,8 +130,6 @@ function plusOne(digits: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn plus_one(mut digits: Vec) -> Vec { @@ -178,10 +147,23 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} digits + * @return {number[]} + */ +var plusOne = function (digits) { + for (let i = digits.length - 1; i >= 0; --i) { + ++digits[i]; + digits[i] %= 10; + if (digits[i] != 0) { + return digits; + } + } + return [1, ...digits]; +}; ``` + + diff --git a/solution/0000-0099/0067.Add Binary/README.md b/solution/0000-0099/0067.Add Binary/README.md index 2067df00fb9fe..a370bb132cded 100644 --- a/solution/0000-0099/0067.Add Binary/README.md +++ b/solution/0000-0099/0067.Add Binary/README.md @@ -34,9 +34,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们用一个变量 $carry$ 记录当前的进位,用两个指针 $i$ 和 $j$ 分别指向 $a$ 和 $b$ 的末尾,从末尾到开头逐位相加即可。 @@ -44,33 +42,12 @@ -### **Python3** - - - ```python class Solution: def addBinary(self, a: str, b: str) -> str: return bin(int(a, 2) + int(b, 2))[2:] ``` -```python -class Solution: - def addBinary(self, a: str, b: str) -> str: - ans = [] - i, j, carry = len(a) - 1, len(b) - 1, 0 - while i >= 0 or j >= 0 or carry: - carry += (0 if i < 0 else int(a[i])) + (0 if j < 0 else int(b[j])) - carry, v = divmod(carry, 2) - ans.append(str(v)) - i, j = i - 1, j - 1 - return ''.join(ans[::-1]) -``` - -### **Java** - - - ```java class Solution { public String addBinary(String a, String b) { @@ -86,8 +63,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +80,6 @@ public: }; ``` -### **Go** - ```go func addBinary(a string, b string) string { i, j := len(a)-1, len(b)-1 @@ -128,31 +101,12 @@ func addBinary(a string, b string) string { } ``` -### **TypeScript** - ```ts function addBinary(a: string, b: string): string { return (BigInt('0b' + a) + BigInt('0b' + b)).toString(2); } ``` -```ts -function addBinary(a: string, b: string): string { - let i = a.length - 1; - let j = b.length - 1; - let ans: number[] = []; - for (let carry = 0; i >= 0 || j >= 0 || carry; --i, --j) { - carry += (i >= 0 ? a[i] : '0').charCodeAt(0) - '0'.charCodeAt(0); - carry += (j >= 0 ? b[j] : '0').charCodeAt(0) - '0'.charCodeAt(0); - ans.push(carry % 2); - carry >>= 1; - } - return ans.reverse().join(''); -} -``` - -### **Rust** - ```rust impl Solution { pub fn add_binary(a: String, b: String) -> String { @@ -179,10 +133,59 @@ impl Solution { } ``` -### **...** +```cs +public class Solution { + public string AddBinary(string a, string b) { + int i = a.Length - 1; + int j = b.Length - 1; + var sb = new StringBuilder(); + for (int carry = 0; i >= 0 || j >= 0 || carry > 0; --i, --j) { + carry += i >= 0 ? a[i] - '0' : 0; + carry += j >= 0 ? b[j] - '0' : 0; + sb.Append(carry % 2); + carry /= 2; + } + var ans = sb.ToString().ToCharArray(); + Array.Reverse(ans); + return new string(ans); + } +} +``` + + + +### 方法二 + + +```python +class Solution: + def addBinary(self, a: str, b: str) -> str: + ans = [] + i, j, carry = len(a) - 1, len(b) - 1, 0 + while i >= 0 or j >= 0 or carry: + carry += (0 if i < 0 else int(a[i])) + (0 if j < 0 else int(b[j])) + carry, v = divmod(carry, 2) + ans.append(str(v)) + i, j = i - 1, j - 1 + return ''.join(ans[::-1]) ``` +```ts +function addBinary(a: string, b: string): string { + let i = a.length - 1; + let j = b.length - 1; + let ans: number[] = []; + for (let carry = 0; i >= 0 || j >= 0 || carry; --i, --j) { + carry += (i >= 0 ? a[i] : '0').charCodeAt(0) - '0'.charCodeAt(0); + carry += (j >= 0 ? b[j] : '0').charCodeAt(0) - '0'.charCodeAt(0); + ans.push(carry % 2); + carry >>= 1; + } + return ans.reverse().join(''); +} ``` + + diff --git a/solution/0000-0099/0067.Add Binary/README_EN.md b/solution/0000-0099/0067.Add Binary/README_EN.md index 34e0b31835de7..7c78398cc3c00 100644 --- a/solution/0000-0099/0067.Add Binary/README_EN.md +++ b/solution/0000-0099/0067.Add Binary/README_EN.md @@ -25,7 +25,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We use a variable $carry$ to record the current carry, and two pointers $i$ and $j$ to point to the end of $a$ and $b$ respectively, and add them bit by bit from the end to the beginning. @@ -33,29 +33,12 @@ The time complexity is $O(\max(m, n))$, where $m$ and $n$ are the lengths of str -### **Python3** - ```python class Solution: def addBinary(self, a: str, b: str) -> str: return bin(int(a, 2) + int(b, 2))[2:] ``` -```python -class Solution: - def addBinary(self, a: str, b: str) -> str: - ans = [] - i, j, carry = len(a) - 1, len(b) - 1, 0 - while i >= 0 or j >= 0 or carry: - carry += (0 if i < 0 else int(a[i])) + (0 if j < 0 else int(b[j])) - carry, v = divmod(carry, 2) - ans.append(str(v)) - i, j = i - 1, j - 1 - return ''.join(ans[::-1]) -``` - -### **Java** - ```java class Solution { public String addBinary(String a, String b) { @@ -71,8 +54,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,8 +71,6 @@ public: }; ``` -### **Go** - ```go func addBinary(a string, b string) string { i, j := len(a)-1, len(b)-1 @@ -113,31 +92,12 @@ func addBinary(a string, b string) string { } ``` -### **TypeScript** - ```ts function addBinary(a: string, b: string): string { return (BigInt('0b' + a) + BigInt('0b' + b)).toString(2); } ``` -```ts -function addBinary(a: string, b: string): string { - let i = a.length - 1; - let j = b.length - 1; - let ans: number[] = []; - for (let carry = 0; i >= 0 || j >= 0 || carry; --i, --j) { - carry += (i >= 0 ? a[i] : '0').charCodeAt(0) - '0'.charCodeAt(0); - carry += (j >= 0 ? b[j] : '0').charCodeAt(0) - '0'.charCodeAt(0); - ans.push(carry % 2); - carry >>= 1; - } - return ans.reverse().join(''); -} -``` - -### **Rust** - ```rust impl Solution { pub fn add_binary(a: String, b: String) -> String { @@ -164,8 +124,6 @@ impl Solution { } ``` -### **C#** - ```cs public class Solution { public string AddBinary(string a, string b) { @@ -185,10 +143,40 @@ public class Solution { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def addBinary(self, a: str, b: str) -> str: + ans = [] + i, j, carry = len(a) - 1, len(b) - 1, 0 + while i >= 0 or j >= 0 or carry: + carry += (0 if i < 0 else int(a[i])) + (0 if j < 0 else int(b[j])) + carry, v = divmod(carry, 2) + ans.append(str(v)) + i, j = i - 1, j - 1 + return ''.join(ans[::-1]) ``` +```ts +function addBinary(a: string, b: string): string { + let i = a.length - 1; + let j = b.length - 1; + let ans: number[] = []; + for (let carry = 0; i >= 0 || j >= 0 || carry; --i, --j) { + carry += (i >= 0 ? a[i] : '0').charCodeAt(0) - '0'.charCodeAt(0); + carry += (j >= 0 ? b[j] : '0').charCodeAt(0) - '0'.charCodeAt(0); + ans.push(carry % 2); + carry >>= 1; + } + return ans.reverse().join(''); +} ``` + + diff --git a/solution/0000-0099/0068.Text Justification/README.md b/solution/0000-0099/0068.Text Justification/README.md index d1688481f3b24..b8275bcf764eb 100644 --- a/solution/0000-0099/0068.Text Justification/README.md +++ b/solution/0000-0099/0068.Text Justification/README.md @@ -80,9 +80,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 根据题意模拟即可,注意,如果是最后一行,或者这一行只有一个单词,那么要左对齐,否则要均匀分配空格。 @@ -90,10 +88,6 @@ -### **Python3** - - - ```python class Solution: def fullJustify(self, words: List[str], maxWidth: int) -> List[str]: @@ -124,10 +118,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List fullJustify(String[] words, int maxWidth) { @@ -163,8 +153,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -202,8 +190,6 @@ public: }; ``` -### **Go** - ```go func fullJustify(words []string, maxWidth int) (ans []string) { for i, n := 0, len(words); i < n; { @@ -239,8 +225,6 @@ func fullJustify(words []string, maxWidth int) (ans []string) { } ``` -### **TypeScript** - ```ts function fullJustify(words: string[], maxWidth: number): string[] { const ans: string[] = []; @@ -272,8 +256,6 @@ function fullJustify(words: string[], maxWidth: number): string[] { } ``` -### **C#** - ```cs public class Solution { public IList FullJustify(string[] words, int maxWidth) { @@ -310,10 +292,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0068.Text Justification/README_EN.md b/solution/0000-0099/0068.Text Justification/README_EN.md index e25d2f6838229..9f2349b57dac2 100644 --- a/solution/0000-0099/0068.Text Justification/README_EN.md +++ b/solution/0000-0099/0068.Text Justification/README_EN.md @@ -72,7 +72,7 @@ Note that the second line is also left-justified because it contains only one wo ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can simulate the process according to the problem's requirements. Note that if it is the last line, or if there is only one word in the line, then we should align to the left. Otherwise, we should distribute the spaces evenly. @@ -80,8 +80,6 @@ The time complexity is $O(L)$, and the space complexity is $O(L)$. Here, $L$ is -### **Python3** - ```python class Solution: def fullJustify(self, words: List[str], maxWidth: int) -> List[str]: @@ -112,8 +110,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List fullJustify(String[] words, int maxWidth) { @@ -149,8 +145,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -188,8 +182,6 @@ public: }; ``` -### **Go** - ```go func fullJustify(words []string, maxWidth int) (ans []string) { for i, n := 0, len(words); i < n; { @@ -225,8 +217,6 @@ func fullJustify(words []string, maxWidth int) (ans []string) { } ``` -### **TypeScript** - ```ts function fullJustify(words: string[], maxWidth: number): string[] { const ans: string[] = []; @@ -258,8 +248,6 @@ function fullJustify(words: string[], maxWidth: number): string[] { } ``` -### **C#** - ```cs public class Solution { public IList FullJustify(string[] words, int maxWidth) { @@ -296,10 +284,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0069.Sqrt(x)/README.md b/solution/0000-0099/0069.Sqrt(x)/README.md index 2accad08078dd..fdabda07e8ec7 100644 --- a/solution/0000-0099/0069.Sqrt(x)/README.md +++ b/solution/0000-0099/0069.Sqrt(x)/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们定义二分查找的左边界 $l = 0$,右边界 $r = x$,然后在 $[l, r]$ 范围内查找平方根。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def mySqrt(self, x: int) -> int: @@ -70,10 +64,6 @@ class Solution: return l ``` -### **Java** - - - ```java class Solution { public int mySqrt(int x) { @@ -91,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,15 +99,32 @@ public: }; ``` -### **Go** - ```go func mySqrt(x int) int { return sort.Search(x+1, func(i int) bool { return i*i > x }) - 1 } ``` -### **JavaScript** +```rust +impl Solution { + pub fn my_sqrt(x: i32) -> i32 { + let mut l = 0; + let mut r = x; + + while l < r { + let mid = (l + r + 1) / 2; + + if mid > x / mid { + r = mid - 1; + } else { + l = mid; + } + } + + l + } +} +``` ```js /** @@ -140,8 +145,6 @@ var mySqrt = function (x) { }; ``` -### **C#** - ```cs public class Solution { public int MySqrt(int x) { @@ -159,33 +162,6 @@ public class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn my_sqrt(x: i32) -> i32 { - let mut l = 0; - let mut r = x; - - while l < r { - let mid = (l + r + 1) / 2; - - if mid > x / mid { - r = mid - 1; - } else { - l = mid; - } - } - - l - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0069.Sqrt(x)/README_EN.md b/solution/0000-0099/0069.Sqrt(x)/README_EN.md index dd226d87615a5..e22050e8480ba 100644 --- a/solution/0000-0099/0069.Sqrt(x)/README_EN.md +++ b/solution/0000-0099/0069.Sqrt(x)/README_EN.md @@ -38,7 +38,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 = x$, then we search for the square root within the range $[l, r]$. @@ -50,8 +50,6 @@ The time complexity is $O(\log x)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def mySqrt(self, x: int) -> int: @@ -65,8 +63,6 @@ class Solution: return l ``` -### **Java** - ```java class Solution { public int mySqrt(int x) { @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,15 +98,32 @@ public: }; ``` -### **Go** - ```go func mySqrt(x int) int { return sort.Search(x+1, func(i int) bool { return i*i > x }) - 1 } ``` -### **JavaScript** +```rust +impl Solution { + pub fn my_sqrt(x: i32) -> i32 { + let mut l = 0; + let mut r = x; + + while l < r { + let mid = (l + r + 1) / 2; + + if mid > x / mid { + r = mid - 1; + } else { + l = mid; + } + } + + l + } +} +``` ```js /** @@ -133,8 +144,6 @@ var mySqrt = function (x) { }; ``` -### **C#** - ```cs public class Solution { public int MySqrt(int x) { @@ -152,33 +161,6 @@ public class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn my_sqrt(x: i32) -> i32 { - let mut l = 0; - let mut r = x; - - while l < r { - let mid = (l + r + 1) / 2; - - if mid > x / mid { - r = mid - 1; - } else { - l = mid; - } - } - - l - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0070.Climbing Stairs/README.md b/solution/0000-0099/0070.Climbing Stairs/README.md index 93f787291567d..961819868a7b9 100644 --- a/solution/0000-0099/0070.Climbing Stairs/README.md +++ b/solution/0000-0099/0070.Climbing Stairs/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:递推** +### 方法一:递推 我们定义 $f[i]$ 表示爬到第 $i$ 阶楼梯的方法数,那么 $f[i]$ 可以由 $f[i - 1]$ 和 $f[i - 2]$ 转移而来,即: @@ -60,7 +58,120 @@ $$ 时间复杂度 $O(n)$,空间复杂度 $O(1)$。 -**方法二:矩阵快速幂加速递推** + + +```python +class Solution: + def climbStairs(self, n: int) -> int: + a, b = 0, 1 + for _ in range(n): + a, b = b, a + b + return b +``` + +```java +class Solution { + public int climbStairs(int n) { + int a = 0, b = 1; + for (int i = 0; i < n; ++i) { + int c = a + b; + a = b; + b = c; + } + return b; + } +} +``` + +```cpp +class Solution { +public: + int climbStairs(int n) { + int a = 0, b = 1; + for (int i = 0; i < n; ++i) { + int c = a + b; + a = b; + b = c; + } + return b; + } +}; +``` + +```go +func climbStairs(n int) int { + a, b := 0, 1 + for i := 0; i < n; i++ { + a, b = b, a+b + } + return b +} +``` + +```ts +function climbStairs(n: number): number { + let p = 1; + let q = 1; + for (let i = 1; i < n; i++) { + [p, q] = [q, p + q]; + } + return q; +} +``` + +```rust +impl Solution { + pub fn climb_stairs(n: i32) -> i32 { + let (mut p, mut q) = (1, 1); + for i in 1..n { + let t = p + q; + p = q; + q = t; + } + q + } +} +``` + +```js +/** + * @param {number} n + * @return {number} + */ +var climbStairs = function (n) { + let a = 0, + b = 1; + for (let i = 0; i < n; ++i) { + const c = a + b; + a = b; + b = c; + } + return b; +}; +``` + +```php +class Solution { + /** + * @param Integer $n + * @return Integer + */ + function climbStairs($n) { + if ($n <= 2) { + return $n; + } + $dp = [0, 1, 2]; + for ($i = 3; $i <= $n; $i++) { + $dp[$i] = $dp[$i - 2] + $dp[$i - 1]; + } + return $dp[$n]; + } +} +``` + + + +### 方法二:矩阵快速幂加速递推 我们设 $Fib(n)$ 表示一个 $1 \times 2$ 的矩阵 $\begin{bmatrix} F_n & F_{n - 1} \end{bmatrix}$,其中 $F_n$ 和 $F_{n - 1}$ 分别是第 $n$ 个和第 $n - 1$ 个斐波那契数。 @@ -102,19 +213,6 @@ $$ -### **Python3** - - - -```python -class Solution: - def climbStairs(self, n: int) -> int: - a, b = 0, 1 - for _ in range(n): - a, b = b, a + b - return b -``` - ```python class Solution: def climbStairs(self, n: int) -> int: @@ -140,41 +238,6 @@ class Solution: return pow(a, n - 1)[0][0] ``` -```python -import numpy as np - - -class Solution: - def climbStairs(self, n: int) -> int: - res = np.mat([(1, 1)], np.dtype("O")) - factor = np.mat([(1, 1), (1, 0)], np.dtype("O")) - n -= 1 - while n: - if n & 1: - res *= factor - factor *= factor - n >>= 1 - return res[0, 0] -``` - -### **Java** - - - -```java -class Solution { - public int climbStairs(int n) { - int a = 0, b = 1; - for (int i = 0; i < n; ++i) { - int c = a + b; - a = b; - b = c; - } - return b; - } -} -``` - ```java class Solution { private final int[][] a = {{1, 1}, {1, 0}}; @@ -210,23 +273,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int climbStairs(int n) { - int a = 0, b = 1; - for (int i = 0; i < n; ++i) { - int c = a + b; - a = b; - b = c; - } - return b; - } -}; -``` - ```cpp class Solution { public: @@ -263,18 +309,6 @@ private: }; ``` -### **Go** - -```go -func climbStairs(n int) int { - a, b := 0, 1 - for i := 0; i < n; i++ { - a, b = b, a+b - } - return b -} -``` - ```go type matrix [2][2]int @@ -308,39 +342,16 @@ func pow(a matrix, n int) matrix { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number} - */ -var climbStairs = function (n) { - let a = 0, - b = 1; - for (let i = 0; i < n; ++i) { - const c = a + b; - a = b; - b = c; - } - return b; -}; -``` - -```js -/** - * @param {number} n - * @return {number} - */ -var climbStairs = function (n) { +```ts +function climbStairs(n: number): number { const a = [ [1, 1], [1, 0], ]; return pow(a, n - 1)[0][0]; -}; +} -function mul(a, b) { +function mul(a: number[][], b: number[][]): number[][] { const [m, n] = [a.length, b[0].length]; const c = Array(m) .fill(0) @@ -355,7 +366,7 @@ function mul(a, b) { return c; } -function pow(a, n) { +function pow(a: number[][], n: number): number[][] { let res = [ [1, 1], [0, 0], @@ -371,29 +382,20 @@ function pow(a, n) { } ``` -### **TypeScript** - -```ts -function climbStairs(n: number): number { - let p = 1; - let q = 1; - for (let i = 1; i < n; i++) { - [p, q] = [q, p + q]; - } - return q; -} -``` - -```ts -function climbStairs(n: number): number { +```js +/** + * @param {number} n + * @return {number} + */ +var climbStairs = function (n) { const a = [ [1, 1], [1, 0], ]; return pow(a, n - 1)[0][0]; -} +}; -function mul(a: number[][], b: number[][]): number[][] { +function mul(a, b) { const [m, n] = [a.length, b[0].length]; const c = Array(m) .fill(0) @@ -408,7 +410,7 @@ function mul(a: number[][], b: number[][]): number[][] { return c; } -function pow(a: number[][], n: number): number[][] { +function pow(a, n) { let res = [ [1, 1], [0, 0], @@ -424,47 +426,29 @@ function pow(a: number[][], n: number): number[][] { } ``` -### **Rust** - -```rust -impl Solution { - pub fn climb_stairs(n: i32) -> i32 { - let (mut p, mut q) = (1, 1); - for i in 1..n { - let t = p + q; - p = q; - q = t; - } - q - } -} -``` + -### **PHP** +### 方法三 -```php -class Solution { - /** - * @param Integer $n - * @return Integer - */ - function climbStairs($n) { - if ($n <= 2) { - return $n; - } - $dp = [0, 1, 2]; - for ($i = 3; $i <= $n; $i++) { - $dp[$i] = $dp[$i - 2] + $dp[$i - 1]; - } - return $dp[$n]; - } -} -``` + -### **...** +```python +import numpy as np -``` +class Solution: + def climbStairs(self, n: int) -> int: + res = np.mat([(1, 1)], np.dtype("O")) + factor = np.mat([(1, 1), (1, 0)], np.dtype("O")) + n -= 1 + while n: + if n & 1: + res *= factor + factor *= factor + n >>= 1 + return res[0, 0] ``` + + diff --git a/solution/0000-0099/0070.Climbing Stairs/README_EN.md b/solution/0000-0099/0070.Climbing Stairs/README_EN.md index 35e6fd3f7598c..7ce1154ece446 100644 --- a/solution/0000-0099/0070.Climbing Stairs/README_EN.md +++ b/solution/0000-0099/0070.Climbing Stairs/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion We define $f[i]$ to represent the number of ways to climb to the $i$-th step, then $f[i]$ can be transferred from $f[i - 1]$ and $f[i - 2]$, that is: @@ -55,7 +55,120 @@ Since $f[i]$ is only related to $f[i - 1]$ and $f[i - 2]$, we can use two variab The time complexity is $O(n)$, and the space complexity is $O(1)$. -**Solution 2: Matrix Quick Power to Accelerate Recursion** + + +```python +class Solution: + def climbStairs(self, n: int) -> int: + a, b = 0, 1 + for _ in range(n): + a, b = b, a + b + return b +``` + +```java +class Solution { + public int climbStairs(int n) { + int a = 0, b = 1; + for (int i = 0; i < n; ++i) { + int c = a + b; + a = b; + b = c; + } + return b; + } +} +``` + +```cpp +class Solution { +public: + int climbStairs(int n) { + int a = 0, b = 1; + for (int i = 0; i < n; ++i) { + int c = a + b; + a = b; + b = c; + } + return b; + } +}; +``` + +```go +func climbStairs(n int) int { + a, b := 0, 1 + for i := 0; i < n; i++ { + a, b = b, a+b + } + return b +} +``` + +```ts +function climbStairs(n: number): number { + let p = 1; + let q = 1; + for (let i = 1; i < n; i++) { + [p, q] = [q, p + q]; + } + return q; +} +``` + +```rust +impl Solution { + pub fn climb_stairs(n: i32) -> i32 { + let (mut p, mut q) = (1, 1); + for i in 1..n { + let t = p + q; + p = q; + q = t; + } + q + } +} +``` + +```js +/** + * @param {number} n + * @return {number} + */ +var climbStairs = function (n) { + let a = 0, + b = 1; + for (let i = 0; i < n; ++i) { + const c = a + b; + a = b; + b = c; + } + return b; +}; +``` + +```php +class Solution { + /** + * @param Integer $n + * @return Integer + */ + function climbStairs($n) { + if ($n <= 2) { + return $n; + } + $dp = [0, 1, 2]; + for ($i = 3; $i <= $n; $i++) { + $dp[$i] = $dp[$i - 2] + $dp[$i - 1]; + } + return $dp[$n]; + } +} +``` + + + +### Solution 2: Matrix Quick Power to Accelerate Recursion We set $Fib(n)$ to represent a $1 \times 2$ matrix $\begin{bmatrix} F_n & F_{n - 1} \end{bmatrix}$, where $F_n$ and $F_{n - 1}$ are the $n$-th and $(n - 1)$-th Fibonacci numbers respectively. @@ -97,17 +210,6 @@ The time complexity is $O(\log n)$, and the space complexity is $O(1)$. -### **Python3** - -```python -class Solution: - def climbStairs(self, n: int) -> int: - a, b = 0, 1 - for _ in range(n): - a, b = b, a + b - return b -``` - ```python class Solution: def climbStairs(self, n: int) -> int: @@ -133,39 +235,6 @@ class Solution: return pow(a, n - 1)[0][0] ``` -```python -import numpy as np - - -class Solution: - def climbStairs(self, n: int) -> int: - res = np.mat([(1, 1)], np.dtype("O")) - factor = np.mat([(1, 1), (1, 0)], np.dtype("O")) - n -= 1 - while n: - if n & 1: - res *= factor - factor *= factor - n >>= 1 - return res[0, 0] -``` - -### **Java** - -```java -class Solution { - public int climbStairs(int n) { - int a = 0, b = 1; - for (int i = 0; i < n; ++i) { - int c = a + b; - a = b; - b = c; - } - return b; - } -} -``` - ```java class Solution { private final int[][] a = {{1, 1}, {1, 0}}; @@ -201,23 +270,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int climbStairs(int n) { - int a = 0, b = 1; - for (int i = 0; i < n; ++i) { - int c = a + b; - a = b; - b = c; - } - return b; - } -}; -``` - ```cpp class Solution { public: @@ -254,18 +306,6 @@ private: }; ``` -### **Go** - -```go -func climbStairs(n int) int { - a, b := 0, 1 - for i := 0; i < n; i++ { - a, b = b, a+b - } - return b -} -``` - ```go type matrix [2][2]int @@ -299,39 +339,16 @@ func pow(a matrix, n int) matrix { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number} - */ -var climbStairs = function (n) { - let a = 0, - b = 1; - for (let i = 0; i < n; ++i) { - const c = a + b; - a = b; - b = c; - } - return b; -}; -``` - -```js -/** - * @param {number} n - * @return {number} - */ -var climbStairs = function (n) { +```ts +function climbStairs(n: number): number { const a = [ [1, 1], [1, 0], ]; return pow(a, n - 1)[0][0]; -}; +} -function mul(a, b) { +function mul(a: number[][], b: number[][]): number[][] { const [m, n] = [a.length, b[0].length]; const c = Array(m) .fill(0) @@ -346,7 +363,7 @@ function mul(a, b) { return c; } -function pow(a, n) { +function pow(a: number[][], n: number): number[][] { let res = [ [1, 1], [0, 0], @@ -362,29 +379,20 @@ function pow(a, n) { } ``` -### **TypeScript** - -```ts -function climbStairs(n: number): number { - let p = 1; - let q = 1; - for (let i = 1; i < n; i++) { - [p, q] = [q, p + q]; - } - return q; -} -``` - -```ts -function climbStairs(n: number): number { +```js +/** + * @param {number} n + * @return {number} + */ +var climbStairs = function (n) { const a = [ [1, 1], [1, 0], ]; return pow(a, n - 1)[0][0]; -} +}; -function mul(a: number[][], b: number[][]): number[][] { +function mul(a, b) { const [m, n] = [a.length, b[0].length]; const c = Array(m) .fill(0) @@ -399,7 +407,7 @@ function mul(a: number[][], b: number[][]): number[][] { return c; } -function pow(a: number[][], n: number): number[][] { +function pow(a, n) { let res = [ [1, 1], [0, 0], @@ -415,47 +423,29 @@ function pow(a: number[][], n: number): number[][] { } ``` -### **Rust** - -```rust -impl Solution { - pub fn climb_stairs(n: i32) -> i32 { - let (mut p, mut q) = (1, 1); - for i in 1..n { - let t = p + q; - p = q; - q = t; - } - q - } -} -``` + -### **PHP** +### Solution 3 -```php -class Solution { - /** - * @param Integer $n - * @return Integer - */ - function climbStairs($n) { - if ($n <= 2) { - return $n; - } - $dp = [0, 1, 2]; - for ($i = 3; $i <= $n; $i++) { - $dp[$i] = $dp[$i - 2] + $dp[$i - 1]; - } - return $dp[$n]; - } -} -``` + -### **...** +```python +import numpy as np -``` +class Solution: + def climbStairs(self, n: int) -> int: + res = np.mat([(1, 1)], np.dtype("O")) + factor = np.mat([(1, 1), (1, 0)], np.dtype("O")) + n -= 1 + while n: + if n & 1: + res *= factor + factor *= factor + n >>= 1 + return res[0, 0] ``` + + diff --git a/solution/0000-0099/0071.Simplify Path/README.md b/solution/0000-0099/0071.Simplify Path/README.md index b2e0c60431616..1fa7ef783f18a 100644 --- a/solution/0000-0099/0071.Simplify Path/README.md +++ b/solution/0000-0099/0071.Simplify Path/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 我们先将路径按照 `'/'` 分割成若干个子串,然后遍历每个子串,根据子串的内容进行如下操作: @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def simplifyPath(self, path: str) -> str: @@ -100,10 +94,6 @@ class Solution: return '/' + '/'.join(stk) ``` -### **Java** - - - ```java class Solution { public String simplifyPath(String path) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,40 +144,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn simplify_path(path: String) -> String { - let mut s: Vec<&str> = Vec::new(); - - // Split the path - let p_vec = path.split("/").collect::>(); - - // Traverse the path vector - for p in p_vec { - match p { - // Do nothing for "" or "." - "" | "." => { - continue; - } - ".." => { - if !s.is_empty() { - s.pop(); - } - } - _ => s.push(p), - } - } - - "/".to_string() + &s.join("/") - } -} -``` - -### **Go** - ```go func simplifyPath(path string) string { var stk []string @@ -209,14 +163,6 @@ func simplifyPath(path string) string { } ``` -```go -func simplifyPath(path string) string { - return filepath.Clean(path) -} -``` - -### **TypeScript** - ```ts function simplifyPath(path: string): string { const stk: string[] = []; @@ -236,7 +182,35 @@ function simplifyPath(path: string): string { } ``` -### **C#** +```rust +impl Solution { + #[allow(dead_code)] + pub fn simplify_path(path: String) -> String { + let mut s: Vec<&str> = Vec::new(); + + // Split the path + let p_vec = path.split("/").collect::>(); + + // Traverse the path vector + for p in p_vec { + match p { + // Do nothing for "" or "." + "" | "." => { + continue; + } + ".." => { + if !s.is_empty() { + s.pop(); + } + } + _ => s.push(p), + } + } + + "/".to_string() + &s.join("/") + } +} +``` ```cs public class Solution { @@ -263,10 +237,18 @@ public class Solution { } ``` -### **...** + -``` +### 方法二 + + +```go +func simplifyPath(path string) string { + return filepath.Clean(path) +} ``` + + diff --git a/solution/0000-0099/0071.Simplify Path/README_EN.md b/solution/0000-0099/0071.Simplify Path/README_EN.md index 18f4d2aff4fa7..09a460d2ca704 100644 --- a/solution/0000-0099/0071.Simplify Path/README_EN.md +++ b/solution/0000-0099/0071.Simplify Path/README_EN.md @@ -55,7 +55,7 @@ ## Solutions -**Solution 1: Stack** +### Solution 1: Stack We first split the path into a number of substrings split by `'/'`. Then, we traverse each substring and perform the following operations based on the content of the substring: @@ -69,8 +69,6 @@ The time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is t -### **Python3** - ```python class Solution: def simplifyPath(self, path: str) -> str: @@ -86,8 +84,6 @@ class Solution: return '/' + '/'.join(stk) ``` -### **Java** - ```java class Solution { public String simplifyPath(String path) { @@ -107,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,40 +134,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn simplify_path(path: String) -> String { - let mut s: Vec<&str> = Vec::new(); - - // Split the path - let p_vec = path.split("/").collect::>(); - - // Traverse the path vector - for p in p_vec { - match p { - // Do nothing for "" or "." - "" | "." => { - continue; - } - ".." => { - if !s.is_empty() { - s.pop(); - } - } - _ => s.push(p), - } - } - - "/".to_string() + &s.join("/") - } -} -``` - -### **Go** - ```go func simplifyPath(path string) string { var stk []string @@ -193,14 +153,6 @@ func simplifyPath(path string) string { } ``` -```go -func simplifyPath(path string) string { - return filepath.Clean(path) -} -``` - -### **TypeScript** - ```ts function simplifyPath(path: string): string { const stk: string[] = []; @@ -220,7 +172,35 @@ function simplifyPath(path: string): string { } ``` -### **C#** +```rust +impl Solution { + #[allow(dead_code)] + pub fn simplify_path(path: String) -> String { + let mut s: Vec<&str> = Vec::new(); + + // Split the path + let p_vec = path.split("/").collect::>(); + + // Traverse the path vector + for p in p_vec { + match p { + // Do nothing for "" or "." + "" | "." => { + continue; + } + ".." => { + if !s.is_empty() { + s.pop(); + } + } + _ => s.push(p), + } + } + + "/".to_string() + &s.join("/") + } +} +``` ```cs public class Solution { @@ -247,10 +227,18 @@ public class Solution { } ``` -### **...** + -``` +### Solution 2 + + +```go +func simplifyPath(path string) string { + return filepath.Clean(path) +} ``` + + diff --git a/solution/0000-0099/0072.Edit Distance/README.md b/solution/0000-0099/0072.Edit Distance/README.md index 652802b77af32..8441c0600fad0 100644 --- a/solution/0000-0099/0072.Edit Distance/README.md +++ b/solution/0000-0099/0072.Edit Distance/README.md @@ -53,9 +53,7 @@ exection -> execution (插入 'u') ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示将 $word1$ 的前 $i$ 个字符转换成 $word2$ 的前 $j$ 个字符所使用的最少操作数。初始时 $f[i][0] = i$, $f[0][j] = j$。其中 $i \in [1, m], j \in [0, n]$。 @@ -81,10 +79,6 @@ $$ -### **Python3** - - - ```python class Solution: def minDistance(self, word1: str, word2: str) -> int: @@ -102,10 +96,6 @@ class Solution: return f[m][n] ``` -### **Java** - - - ```java class Solution { public int minDistance(String word1, String word2) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func minDistance(word1 string, word2 string) int { m, n := len(word1), len(word2) @@ -181,8 +167,6 @@ func minDistance(word1 string, word2 string) int { } ``` -### **TypeScript** - ```ts function minDistance(word1: string, word2: string): number { const m = word1.length; @@ -207,8 +191,6 @@ function minDistance(word1: string, word2: string): number { } ``` -### **JavaScript** - ```js /** * @param {string} word1 @@ -238,10 +220,6 @@ var minDistance = function (word1, word2) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0072.Edit Distance/README_EN.md b/solution/0000-0099/0072.Edit Distance/README_EN.md index 2946b7a1c8a83..0f20962987347 100644 --- a/solution/0000-0099/0072.Edit Distance/README_EN.md +++ b/solution/0000-0099/0072.Edit Distance/README_EN.md @@ -49,7 +49,7 @@ exection -> execution (insert 'u') ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ as the minimum number of operations to convert $word1$ of length $i$ to $word2$ of length $j$. $f[i][0] = i$, $f[0][j] = j$, $i \in [1, m], j \in [0, n]$. @@ -75,8 +75,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times -### **Python3** - ```python class Solution: def minDistance(self, word1: str, word2: str) -> int: @@ -94,8 +92,6 @@ class Solution: return f[m][n] ``` -### **Java** - ```java class Solution { public int minDistance(String word1, String word2) { @@ -119,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +139,6 @@ public: }; ``` -### **Go** - ```go func minDistance(word1 string, word2 string) int { m, n := len(word1), len(word2) @@ -171,8 +163,6 @@ func minDistance(word1 string, word2 string) int { } ``` -### **TypeScript** - ```ts function minDistance(word1: string, word2: string): number { const m = word1.length; @@ -197,8 +187,6 @@ function minDistance(word1: string, word2: string): number { } ``` -### **JavaScript** - ```js /** * @param {string} word1 @@ -228,10 +216,6 @@ var minDistance = function (word1, word2) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/README.md b/solution/0000-0099/0073.Set Matrix Zeroes/README.md index c6df9b465d8b6..204cefb783546 100644 --- a/solution/0000-0099/0073.Set Matrix Zeroes/README.md +++ b/solution/0000-0099/0073.Set Matrix Zeroes/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:数组标记** +### 方法一:数组标记 我们分别用数组 `rows` 和 `cols` 标记待清零的行和列。 @@ -60,20 +58,8 @@ 时间复杂度 $O(m\times n)$,空间复杂度 $O(m+n)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。 -**方法二:原地标记** - -方法一中使用了额外的数组标记待清零的行和列,实际上我们也可以直接用矩阵的第一行和第一列来标记,不需要开辟额外的数组空间。 - -由于第一行、第一列用来做标记,它们的值可能会因为标记而发生改变,因此,我们需要额外的变量 $i0$, $j0$ 来标记第一行、第一列是否需要被清零。 - -时间复杂度 $O(m\times n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。 - -### **Python3** - - - ```python class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: @@ -90,32 +76,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) { @@ -141,6 +101,168 @@ class Solution { } ``` +```cpp +class Solution { +public: + void setZeroes(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + vector rows(m); + vector cols(n); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (!matrix[i][j]) { + rows[i] = 1; + cols[j] = 1; + } + } + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (rows[i] || cols[j]) { + matrix[i][j] = 0; + } + } + } + } +}; +``` + +```go +func setZeroes(matrix [][]int) { + m, n := len(matrix), len(matrix[0]) + rows := make([]bool, m) + cols := make([]bool, n) + for i, row := range matrix { + for j, v := range row { + if v == 0 { + rows[i] = true + cols[j] = true + } + } + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if rows[i] || cols[j] { + matrix[i][j] = 0 + } + } + } +} +``` + +```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: boolean[] = new Array(m).fill(false); + const cols: boolean[] = 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; + } + } + } + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (rows[i] || cols[j]) { + matrix[i][j] = 0; + } + } + } +} +``` + +```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; + 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; + } + } + } + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (rows[i] || cols[j]) { + matrix[i][j] = 0; + } + } + } +}; +``` + +```cs +public class Solution { + public void SetZeroes(int[][] matrix) { + int m = matrix.Length, n = matrix[0].Length; + bool[] rows = new bool[m], cols = new bool[n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (matrix[i][j] == 0) { + rows[i] = true; + cols[j] = true; + } + } + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (rows[i] || cols[j]) { + matrix[i][j] = 0; + } + } + } + } +} +``` + + + +### 方法二:原地标记 + +方法一中使用了额外的数组标记待清零的行和列,实际上我们也可以直接用矩阵的第一行和第一列来标记,不需要开辟额外的数组空间。 + +由于第一行、第一列用来做标记,它们的值可能会因为标记而发生改变,因此,我们需要额外的变量 $i0$, $j0$ 来标记第一行、第一列是否需要被清零。 + +时间复杂度 $O(m\times n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。 + + + +```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) { @@ -187,34 +309,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - void setZeroes(vector>& matrix) { - int m = matrix.size(), n = matrix[0].size(); - vector rows(m); - vector cols(n); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (!matrix[i][j]) { - rows[i] = 1; - cols[j] = 1; - } - } - } - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (rows[i] || cols[j]) { - matrix[i][j] = 0; - } - } - } - } -}; -``` - ```cpp class Solution { public: @@ -262,31 +356,6 @@ public: }; ``` -### **Go** - -```go -func setZeroes(matrix [][]int) { - m, n := len(matrix), len(matrix[0]) - rows := make([]bool, m) - cols := make([]bool, n) - for i, row := range matrix { - for j, v := range row { - if v == 0 { - rows[i] = true - cols[j] = true - } - } - } - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - if rows[i] || cols[j] { - matrix[i][j] = 0 - } - } - } -} -``` - ```go func setZeroes(matrix [][]int) { m, n := len(matrix), len(matrix[0]) @@ -330,34 +399,39 @@ func setZeroes(matrix [][]int) { } ``` -### **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) { - rows[i] = true; - cols[j] = true; + const i0 = matrix[0].includes(0); + const j0 = matrix.map(row => row[0]).includes(0); + 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 = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (rows[i] || cols[j]) { + 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) { + matrix[0].fill(0); + } + if (j0) { + for (let i = 0; i < m; ++i) { + matrix[i][0] = 0; + } + } +} ``` ```js @@ -404,96 +478,6 @@ var setZeroes = function (matrix) { }; ``` -### **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: boolean[] = new Array(m).fill(false); - const cols: boolean[] = 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; - } - } - } - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (rows[i] || cols[j]) { - matrix[i][j] = 0; - } - } - } -} -``` - -```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 i0 = matrix[0].includes(0); - const j0 = matrix.map(row => row[0]).includes(0); - 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) { - matrix[0].fill(0); - } - if (j0) { - for (let i = 0; i < m; ++i) { - matrix[i][0] = 0; - } - } -} -``` - -### **C#** - -```cs -public class Solution { - public void SetZeroes(int[][] matrix) { - int m = matrix.Length, n = matrix[0].Length; - bool[] rows = new bool[m], cols = new bool[n]; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (matrix[i][j] == 0) { - rows[i] = true; - cols[j] = true; - } - } - } - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (rows[i] || cols[j]) { - matrix[i][j] = 0; - } - } - } - } -} -``` - ```cs public class Solution { public void SetZeroes(int[][] matrix) { @@ -534,10 +518,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0073.Set Matrix Zeroes/README_EN.md b/solution/0000-0099/0073.Set Matrix Zeroes/README_EN.md index 51c671af539a4..cfde306e433d5 100644 --- a/solution/0000-0099/0073.Set Matrix Zeroes/README_EN.md +++ b/solution/0000-0099/0073.Set Matrix Zeroes/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Array Mark** +### Solution 1: Array Mark We use arrays `rows` and `cols` to mark the rows and columns to be cleared. @@ -52,18 +52,8 @@ Then traverse the matrix again, and clear the elements in the rows and columns m The time complexity is $O(m\times n)$, and the space complexity is $O(m+n)$. Where $m$ and $n$ are the number of rows and columns of the matrix respectively. -**Solution 2: Mark in Place** - -In the first method, we use an additional array to mark the rows and columns to be cleared. In fact, we can also use the first row and first column of the matrix to mark them, without creating an additional array. - -Since the first row and the first column are used to mark, their values ​​may change due to the mark, so we need additional variables $i0$, $j0$ to mark whether the first row and the first column need to be cleared. - -The time complexity is $O(m\times n)$, and the space complexity is $O(1)$. Where $m$ and $n$ are the number of rows and columns of the matrix respectively. - -### **Python3** - ```python class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: @@ -80,30 +70,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) { @@ -129,6 +95,168 @@ class Solution { } ``` +```cpp +class Solution { +public: + void setZeroes(vector>& matrix) { + int m = matrix.size(), n = matrix[0].size(); + vector rows(m); + vector cols(n); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (!matrix[i][j]) { + rows[i] = 1; + cols[j] = 1; + } + } + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (rows[i] || cols[j]) { + matrix[i][j] = 0; + } + } + } + } +}; +``` + +```go +func setZeroes(matrix [][]int) { + m, n := len(matrix), len(matrix[0]) + rows := make([]bool, m) + cols := make([]bool, n) + for i, row := range matrix { + for j, v := range row { + if v == 0 { + rows[i] = true + cols[j] = true + } + } + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if rows[i] || cols[j] { + matrix[i][j] = 0 + } + } + } +} +``` + +```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: boolean[] = new Array(m).fill(false); + const cols: boolean[] = 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; + } + } + } + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (rows[i] || cols[j]) { + matrix[i][j] = 0; + } + } + } +} +``` + +```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; + 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; + } + } + } + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (rows[i] || cols[j]) { + matrix[i][j] = 0; + } + } + } +}; +``` + +```cs +public class Solution { + public void SetZeroes(int[][] matrix) { + int m = matrix.Length, n = matrix[0].Length; + bool[] rows = new bool[m], cols = new bool[n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (matrix[i][j] == 0) { + rows[i] = true; + cols[j] = true; + } + } + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (rows[i] || cols[j]) { + matrix[i][j] = 0; + } + } + } + } +} +``` + + + +### Solution 2: Mark in Place + +In the first method, we use an additional array to mark the rows and columns to be cleared. In fact, we can also use the first row and first column of the matrix to mark them, without creating an additional array. + +Since the first row and the first column are used to mark, their values ​​may change due to the mark, so we need additional variables $i0$, $j0$ to mark whether the first row and the first column need to be cleared. + +The time complexity is $O(m\times n)$, and the space complexity is $O(1)$. Where $m$ and $n$ are the number of rows and columns of the matrix respectively. + + + +```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) { @@ -175,34 +303,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - void setZeroes(vector>& matrix) { - int m = matrix.size(), n = matrix[0].size(); - vector rows(m); - vector cols(n); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (!matrix[i][j]) { - rows[i] = 1; - cols[j] = 1; - } - } - } - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (rows[i] || cols[j]) { - matrix[i][j] = 0; - } - } - } - } -}; -``` - ```cpp class Solution { public: @@ -250,31 +350,6 @@ public: }; ``` -### **Go** - -```go -func setZeroes(matrix [][]int) { - m, n := len(matrix), len(matrix[0]) - rows := make([]bool, m) - cols := make([]bool, n) - for i, row := range matrix { - for j, v := range row { - if v == 0 { - rows[i] = true - cols[j] = true - } - } - } - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - if rows[i] || cols[j] { - matrix[i][j] = 0 - } - } - } -} -``` - ```go func setZeroes(matrix [][]int) { m, n := len(matrix), len(matrix[0]) @@ -318,34 +393,39 @@ func setZeroes(matrix [][]int) { } ``` -### **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) { - rows[i] = true; - cols[j] = true; + const i0 = matrix[0].includes(0); + const j0 = matrix.map(row => row[0]).includes(0); + 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 = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (rows[i] || cols[j]) { + 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) { + matrix[0].fill(0); + } + if (j0) { + for (let i = 0; i < m; ++i) { + matrix[i][0] = 0; + } + } +} ``` ```js @@ -392,96 +472,6 @@ var setZeroes = function (matrix) { }; ``` -### **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: boolean[] = new Array(m).fill(false); - const cols: boolean[] = 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; - } - } - } - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (rows[i] || cols[j]) { - matrix[i][j] = 0; - } - } - } -} -``` - -```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 i0 = matrix[0].includes(0); - const j0 = matrix.map(row => row[0]).includes(0); - 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) { - matrix[0].fill(0); - } - if (j0) { - for (let i = 0; i < m; ++i) { - matrix[i][0] = 0; - } - } -} -``` - -### **C#** - -```cs -public class Solution { - public void SetZeroes(int[][] matrix) { - int m = matrix.Length, n = matrix[0].Length; - bool[] rows = new bool[m], cols = new bool[n]; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (matrix[i][j] == 0) { - rows[i] = true; - cols[j] = true; - } - } - } - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (rows[i] || cols[j]) { - matrix[i][j] = 0; - } - } - } - } -} -``` - ```cs public class Solution { public void SetZeroes(int[][] matrix) { @@ -522,10 +512,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0074.Search a 2D Matrix/README.md b/solution/0000-0099/0074.Search a 2D Matrix/README.md index 2d78e7454434c..ed4536c4aed91 100644 --- a/solution/0000-0099/0074.Search a 2D Matrix/README.md +++ b/solution/0000-0099/0074.Search a 2D Matrix/README.md @@ -44,34 +44,14 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们将二维矩阵逻辑展开,然后二分查找即可。 时间复杂度 $O(\log (m \times n))$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。空间复杂度 $O(1)$。 -**方法二:从左下角或右上角搜索** - -这里我们以左下角作为起始搜索点,往右上方向开始搜索,比较当前元素 $matrix[i][j]$ 与 $target$ 的大小关系: - -- 若 $matrix[i][j] = target$,说明找到了目标值,直接返回 `true`。 -- 若 $matrix[i][j] > target$,说明这一行从当前位置开始往右的所有元素均大于 target,应该让 i 指针往上移动,即 $i = i - 1$。 -- 若 $matrix[i][j] < target$,说明这一列从当前位置开始往上的所有元素均小于 target,应该让 j 指针往右移动,即 $j = j + 1$。 - -若搜索结束依然找不到 $target$,返回 `false`。 - -时间复杂度 $O(m + n)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。空间复杂度 $O(1)$。 - -### **Python3** - - - -二分查找: - ```python class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: @@ -87,29 +67,6 @@ class Solution: return matrix[left // n][left % n] == target ``` -从左下角或右上角搜索: - -```python -class Solution: - def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: - m, n = len(matrix), len(matrix[0]) - i, j = m - 1, 0 - while i >= 0 and j < n: - if matrix[i][j] == target: - return True - if matrix[i][j] > target: - i -= 1 - else: - j += 1 - return False -``` - -### **Java** - - - -二分查找: - ```java class Solution { public boolean searchMatrix(int[][] matrix, int target) { @@ -129,31 +86,6 @@ class Solution { } ``` -从左下角或右上角搜索: - -```java -class Solution { - public boolean searchMatrix(int[][] matrix, int target) { - int m = matrix.length, n = matrix[0].length; - for (int i = m - 1, j = 0; i >= 0 && j < n;) { - if (matrix[i][j] == target) { - return true; - } - if (matrix[i][j] > target) { - --i; - } else { - ++j; - } - } - return false; - } -} -``` - -### **C++** - -二分查找: - ```cpp class Solution { public: @@ -174,83 +106,6 @@ public: }; ``` -从左下角或右上角搜索: - -```cpp -class Solution { -public: - bool searchMatrix(vector>& matrix, int target) { - int m = matrix.size(), n = matrix[0].size(); - for (int i = m - 1, j = 0; i >= 0 && j < n;) { - if (matrix[i][j] == target) return true; - if (matrix[i][j] > target) - --i; - else - ++j; - } - return false; - } -}; -``` - -### **JavaScript** - -二分查找: - -```js -/** - * @param {number[][]} matrix - * @param {number} target - * @return {boolean} - */ -var searchMatrix = function (matrix, target) { - const m = matrix.length, - n = matrix[0].length; - let left = 0, - right = m * n - 1; - while (left < right) { - const mid = (left + right + 1) >> 1; - const x = Math.floor(mid / n); - const y = mid % n; - if (matrix[x][y] <= target) { - left = mid; - } else { - right = mid - 1; - } - } - return matrix[Math.floor(left / n)][left % n] == target; -}; -``` - -从左下角或右上角搜索: - -```js -/** - * @param {number[][]} matrix - * @param {number} target - * @return {boolean} - */ -var searchMatrix = function (matrix, target) { - const m = matrix.length, - n = matrix[0].length; - for (let i = m - 1, j = 0; i >= 0 && j < n; ) { - if (matrix[i][j] == target) { - return true; - } - if (matrix[i][j] > target) { - --i; - } else { - ++j; - } - } - return false; -}; -``` - -### **Go** - -二分查找: - ```go func searchMatrix(matrix [][]int, target int) bool { m, n := len(matrix), len(matrix[0]) @@ -268,27 +123,6 @@ func searchMatrix(matrix [][]int, target int) bool { } ``` -从左下角或右上角搜索: - -```go -func searchMatrix(matrix [][]int, target int) bool { - m, n := len(matrix), len(matrix[0]) - for i, j := m-1, 0; i >= 0 && j < n; { - if matrix[i][j] == target { - return true - } - if matrix[i][j] > target { - i-- - } else { - j++ - } - } - return false -} -``` - -### **TypeScript** - ```ts function searchMatrix(matrix: number[][], target: number): boolean { const m = matrix.length; @@ -313,8 +147,6 @@ function searchMatrix(matrix: number[][], target: number): boolean { } ``` -### **Rust** - ```rust use std::cmp::Ordering; impl Solution { @@ -341,6 +173,115 @@ impl Solution { } ``` +```js +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function (matrix, target) { + const m = matrix.length, + n = matrix[0].length; + let left = 0, + right = m * n - 1; + while (left < right) { + const mid = (left + right + 1) >> 1; + const x = Math.floor(mid / n); + const y = mid % n; + if (matrix[x][y] <= target) { + left = mid; + } else { + right = mid - 1; + } + } + return matrix[Math.floor(left / n)][left % n] == target; +}; +``` + + + +### 方法二:从左下角或右上角搜索 + +这里我们以左下角作为起始搜索点,往右上方向开始搜索,比较当前元素 $matrix[i][j]$ 与 $target$ 的大小关系: + +- 若 $matrix[i][j] = target$,说明找到了目标值,直接返回 `true`。 +- 若 $matrix[i][j] > target$,说明这一行从当前位置开始往右的所有元素均大于 target,应该让 i 指针往上移动,即 $i = i - 1$。 +- 若 $matrix[i][j] < target$,说明这一列从当前位置开始往上的所有元素均小于 target,应该让 j 指针往右移动,即 $j = j + 1$。 + +若搜索结束依然找不到 $target$,返回 `false`。 + +时间复杂度 $O(m + n)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + m, n = len(matrix), len(matrix[0]) + i, j = m - 1, 0 + while i >= 0 and j < n: + if matrix[i][j] == target: + return True + if matrix[i][j] > target: + i -= 1 + else: + j += 1 + return False +``` + +```java +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int m = matrix.length, n = matrix[0].length; + for (int i = m - 1, j = 0; i >= 0 && j < n;) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +} +``` + +```cpp +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + int m = matrix.size(), n = matrix[0].size(); + for (int i = m - 1, j = 0; i >= 0 && j < n;) { + if (matrix[i][j] == target) return true; + if (matrix[i][j] > target) + --i; + else + ++j; + } + return false; + } +}; +``` + +```go +func searchMatrix(matrix [][]int, target int) bool { + m, n := len(matrix), len(matrix[0]) + for i, j := m-1, 0; i >= 0 && j < n; { + if matrix[i][j] == target { + return true + } + if matrix[i][j] > target { + i-- + } else { + j++ + } + } + return false +} +``` + ```rust use std::cmp::Ordering; impl Solution { @@ -370,10 +311,29 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function (matrix, target) { + const m = matrix.length, + n = matrix[0].length; + for (let i = m - 1, j = 0; i >= 0 && j < n; ) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; +}; ``` + + diff --git a/solution/0000-0099/0074.Search a 2D Matrix/README_EN.md b/solution/0000-0099/0074.Search a 2D Matrix/README_EN.md index da9175503964a..857912b6d8166 100644 --- a/solution/0000-0099/0074.Search a 2D Matrix/README_EN.md +++ b/solution/0000-0099/0074.Search a 2D Matrix/README_EN.md @@ -42,28 +42,14 @@ ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search We can logically unfold the two-dimensional matrix and then perform binary search. The time complexity is $O(\log(m \times n))$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$. -**Solution 2: Search from the Bottom Left or Top Right** - -Here, we start searching from the bottom left corner and move towards the top right direction. We compare the current element $matrix[i][j]$ with $target$: - -- If $matrix[i][j] = target$, we have found the target value and return `true`. -- If $matrix[i][j] > target$, all elements to the right of the current position in this row are greater than target, so we should move the pointer $i$ upwards, i.e., $i = i - 1$. -- If $matrix[i][j] < target$, all elements above the current position in this column are less than target, so we should move the pointer $j$ to the right, i.e., $j = j + 1$. - -If we still can't find $target$ after the search, return `false`. - -The time complexity is $O(m + 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 searchMatrix(self, matrix: List[List[int]], target: int) -> bool: @@ -79,23 +65,6 @@ class Solution: return matrix[left // n][left % n] == target ``` -```python -class Solution: - def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: - m, n = len(matrix), len(matrix[0]) - i, j = m - 1, 0 - while i >= 0 and j < n: - if matrix[i][j] == target: - return True - if matrix[i][j] > target: - i -= 1 - else: - j += 1 - return False -``` - -### **Java** - ```java class Solution { public boolean searchMatrix(int[][] matrix, int target) { @@ -115,27 +84,6 @@ class Solution { } ``` -```java -class Solution { - public boolean searchMatrix(int[][] matrix, int target) { - int m = matrix.length, n = matrix[0].length; - for (int i = m - 1, j = 0; i >= 0 && j < n;) { - if (matrix[i][j] == target) { - return true; - } - if (matrix[i][j] > target) { - --i; - } else { - ++j; - } - } - return false; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -156,75 +104,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool searchMatrix(vector>& matrix, int target) { - int m = matrix.size(), n = matrix[0].size(); - for (int i = m - 1, j = 0; i >= 0 && j < n;) { - if (matrix[i][j] == target) return true; - if (matrix[i][j] > target) - --i; - else - ++j; - } - return false; - } -}; -``` - -### **JavaScript** - -```js -/** - * @param {number[][]} matrix - * @param {number} target - * @return {boolean} - */ -var searchMatrix = function (matrix, target) { - const m = matrix.length, - n = matrix[0].length; - let left = 0, - right = m * n - 1; - while (left < right) { - const mid = (left + right + 1) >> 1; - const x = Math.floor(mid / n); - const y = mid % n; - if (matrix[x][y] <= target) { - left = mid; - } else { - right = mid - 1; - } - } - return matrix[Math.floor(left / n)][left % n] == target; -}; -``` - -```js -/** - * @param {number[][]} matrix - * @param {number} target - * @return {boolean} - */ -var searchMatrix = function (matrix, target) { - const m = matrix.length, - n = matrix[0].length; - for (let i = m - 1, j = 0; i >= 0 && j < n; ) { - if (matrix[i][j] == target) { - return true; - } - if (matrix[i][j] > target) { - --i; - } else { - ++j; - } - } - return false; -}; -``` - -### **Go** - ```go func searchMatrix(matrix [][]int, target int) bool { m, n := len(matrix), len(matrix[0]) @@ -242,25 +121,6 @@ func searchMatrix(matrix [][]int, target int) bool { } ``` -```go -func searchMatrix(matrix [][]int, target int) bool { - m, n := len(matrix), len(matrix[0]) - for i, j := m-1, 0; i >= 0 && j < n; { - if matrix[i][j] == target { - return true - } - if matrix[i][j] > target { - i-- - } else { - j++ - } - } - return false -} -``` - -### **TypeScript** - ```ts function searchMatrix(matrix: number[][], target: number): boolean { const m = matrix.length; @@ -285,8 +145,6 @@ function searchMatrix(matrix: number[][], target: number): boolean { } ``` -### **Rust** - ```rust use std::cmp::Ordering; impl Solution { @@ -313,6 +171,115 @@ impl Solution { } ``` +```js +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function (matrix, target) { + const m = matrix.length, + n = matrix[0].length; + let left = 0, + right = m * n - 1; + while (left < right) { + const mid = (left + right + 1) >> 1; + const x = Math.floor(mid / n); + const y = mid % n; + if (matrix[x][y] <= target) { + left = mid; + } else { + right = mid - 1; + } + } + return matrix[Math.floor(left / n)][left % n] == target; +}; +``` + + + +### Solution 2: Search from the Bottom Left or Top Right + +Here, we start searching from the bottom left corner and move towards the top right direction. We compare the current element $matrix[i][j]$ with $target$: + +- If $matrix[i][j] = target$, we have found the target value and return `true`. +- If $matrix[i][j] > target$, all elements to the right of the current position in this row are greater than target, so we should move the pointer $i$ upwards, i.e., $i = i - 1$. +- If $matrix[i][j] < target$, all elements above the current position in this column are less than target, so we should move the pointer $j$ to the right, i.e., $j = j + 1$. + +If we still can't find $target$ after the search, return `false`. + +The time complexity is $O(m + 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 searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + m, n = len(matrix), len(matrix[0]) + i, j = m - 1, 0 + while i >= 0 and j < n: + if matrix[i][j] == target: + return True + if matrix[i][j] > target: + i -= 1 + else: + j += 1 + return False +``` + +```java +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int m = matrix.length, n = matrix[0].length; + for (int i = m - 1, j = 0; i >= 0 && j < n;) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +} +``` + +```cpp +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + int m = matrix.size(), n = matrix[0].size(); + for (int i = m - 1, j = 0; i >= 0 && j < n;) { + if (matrix[i][j] == target) return true; + if (matrix[i][j] > target) + --i; + else + ++j; + } + return false; + } +}; +``` + +```go +func searchMatrix(matrix [][]int, target int) bool { + m, n := len(matrix), len(matrix[0]) + for i, j := m-1, 0; i >= 0 && j < n; { + if matrix[i][j] == target { + return true + } + if matrix[i][j] > target { + i-- + } else { + j++ + } + } + return false +} +``` + ```rust use std::cmp::Ordering; impl Solution { @@ -342,10 +309,29 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function (matrix, target) { + const m = matrix.length, + n = matrix[0].length; + for (let i = m - 1, j = 0; i >= 0 && j < n; ) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; +}; ``` + + diff --git a/solution/0000-0099/0075.Sort Colors/README.md b/solution/0000-0099/0075.Sort Colors/README.md index 4d23c873d6e73..47e58e3420177 100644 --- a/solution/0000-0099/0075.Sort Colors/README.md +++ b/solution/0000-0099/0075.Sort Colors/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:三指针** +### 方法一:三指针 我们定义三个指针 $i$, $j$ 和 $k$,其中指针 $i$ 用于指向数组中元素值为 $0$ 的最右边界,指针 $j$ 用于指向数组中元素值为 $2$ 的最左边界,初始时 $i=-1$, $j=n$。指针 $k$ 用于指向当前遍历的元素,初始时 $k=0$。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def sortColors(self, nums: List[int]) -> None: @@ -89,10 +83,6 @@ class Solution: k += 1 ``` -### **Java** - - - ```java class Solution { public void sortColors(int[] nums) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func sortColors(nums []int) { i, j, k := -1, len(nums), 0 @@ -156,8 +142,6 @@ func sortColors(nums []int) { } ``` -### **TypeScript** - ```ts /** Do not return anything, modify nums in-place instead. @@ -181,8 +165,6 @@ function sortColors(nums: number[]): void { } ``` -### **Rust** - ```rust impl Solution { pub fn sort_colors(nums: &mut Vec) { @@ -205,8 +187,6 @@ impl Solution { } ``` -### **C#** - ```cs public class Solution { public void SortColors(int[] nums) { @@ -230,10 +210,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0075.Sort Colors/README_EN.md b/solution/0000-0099/0075.Sort Colors/README_EN.md index 191f2c38b9520..9f2ee876edafb 100644 --- a/solution/0000-0099/0075.Sort Colors/README_EN.md +++ b/solution/0000-0099/0075.Sort Colors/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Three Pointers** +### Solution 1: Three Pointers We define three pointers $i$, $j$, and $k$. Pointer $i$ is used to point to the rightmost boundary of the elements with a value of $0$ in the array, and pointer $j$ is used to point to the leftmost boundary of the elements with a value of $2$ in the array. Initially, $i=-1$, $j=n$. Pointer $k$ is used to point to the current element being traversed, initially $k=0$. @@ -55,8 +55,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. Only one tr -### **Python3** - ```python class Solution: def sortColors(self, nums: List[int]) -> None: @@ -73,8 +71,6 @@ class Solution: k += 1 ``` -### **Java** - ```java class Solution { public void sortColors(int[] nums) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func sortColors(nums []int) { i, j, k := -1, len(nums), 0 @@ -138,8 +130,6 @@ func sortColors(nums []int) { } ``` -### **TypeScript** - ```ts /** Do not return anything, modify nums in-place instead. @@ -163,8 +153,6 @@ function sortColors(nums: number[]): void { } ``` -### **Rust** - ```rust impl Solution { pub fn sort_colors(nums: &mut Vec) { @@ -187,8 +175,6 @@ impl Solution { } ``` -### **C#** - ```cs public class Solution { public void SortColors(int[] nums) { @@ -212,10 +198,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0076.Minimum Window Substring/README.md b/solution/0000-0099/0076.Minimum Window Substring/README.md index 8057dad2774ae..274aa1b3585af 100644 --- a/solution/0000-0099/0076.Minimum Window Substring/README.md +++ b/solution/0000-0099/0076.Minimum Window Substring/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:计数 + 双指针** +### 方法一:计数 + 双指针 我们用一个哈希表或数组 $need$ 统计字符串 $t$ 中每个字符出现的次数,用另一个哈希表或数组 $window$ 统计滑动窗口中每个字符出现的次数。另外,定义两个指针 $j$ 和 $i$ 分别指向窗口的左右边界,变量 $cnt$ 表示窗口中已经包含了 $t$ 中的多少个字符,变量 $k$ 和 $mi$ 分别表示最小覆盖子串的起始位置和长度。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def minWindow(self, s: str, t: str) -> str: @@ -100,10 +94,6 @@ class Solution: return '' if k < 0 else s[k : k + mi] ``` -### **Java** - - - ```java class Solution { public String minWindow(String s, String t) { @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go func minWindow(s string, t string) string { need := [128]int{} @@ -203,8 +189,6 @@ func minWindow(s string, t string) string { } ``` -### **TypeScript** - ```ts function minWindow(s: string, t: string): string { const need: number[] = new Array(128).fill(0); @@ -236,40 +220,6 @@ function minWindow(s: string, t: string): string { } ``` -### **C#** - -```cs -public class Solution { - public string MinWindow(string s, string t) { - int[] need = new int[128]; - int[] window = new int[128]; - foreach (var c in t) { - ++need[c]; - } - int cnt = 0, j = 0, k = -1, mi = 1 << 30; - for (int i = 0; i < s.Length; ++i) { - ++window[s[i]]; - if (need[s[i]] >= window[s[i]]) { - ++cnt; - } - while (cnt == t.Length) { - if (i - j + 1 < mi) { - mi = i - j + 1; - k = j; - } - if (need[s[j]] >= window[s[j]]) { - --cnt; - } - --window[s[j++]]; - } - } - return k < 0 ? "" : s.Substring(k, mi); - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn min_window(s: String, t: String) -> String { @@ -306,10 +256,36 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public string MinWindow(string s, string t) { + int[] need = new int[128]; + int[] window = new int[128]; + foreach (var c in t) { + ++need[c]; + } + int cnt = 0, j = 0, k = -1, mi = 1 << 30; + for (int i = 0; i < s.Length; ++i) { + ++window[s[i]]; + if (need[s[i]] >= window[s[i]]) { + ++cnt; + } + while (cnt == t.Length) { + if (i - j + 1 < mi) { + mi = i - j + 1; + k = j; + } + if (need[s[j]] >= window[s[j]]) { + --cnt; + } + --window[s[j++]]; + } + } + return k < 0 ? "" : s.Substring(k, mi); + } +} ``` + + diff --git a/solution/0000-0099/0076.Minimum Window Substring/README_EN.md b/solution/0000-0099/0076.Minimum Window Substring/README_EN.md index d91c2ac5feef0..2fb08ce69e32b 100644 --- a/solution/0000-0099/0076.Minimum Window Substring/README_EN.md +++ b/solution/0000-0099/0076.Minimum Window Substring/README_EN.md @@ -49,7 +49,7 @@ Since the largest window of s only has one 'a', return empty string. ## Solutions -**Solution 1: Counting + Two Pointers** +### Solution 1: Counting + Two Pointers We use a hash table or array $need$ to count the number of occurrences of each character in string $t$, and another hash table or array $window$ to count the number of occurrences of each character in the sliding window. In addition, we define two pointers $j$ and $i$ to point to the left and right boundaries of the window, respectively. The variable $cnt$ represents how many characters in $t$ are already included in the window. The variables $k$ and $mi$ represent the starting position and length of the minimum covering substring, respectively. @@ -63,8 +63,6 @@ The time complexity is $O(m + n)$, and the space complexity is $O(C)$. Here, $m$ -### **Python3** - ```python class Solution: def minWindow(self, s: str, t: str) -> str: @@ -86,8 +84,6 @@ class Solution: return '' if k < 0 else s[k : k + mi] ``` -### **Java** - ```java class Solution { public String minWindow(String s, String t) { @@ -119,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +147,6 @@ public: }; ``` -### **Go** - ```go func minWindow(s string, t string) string { need := [128]int{} @@ -187,8 +179,6 @@ func minWindow(s string, t string) string { } ``` -### **TypeScript** - ```ts function minWindow(s: string, t: string): string { const need: number[] = new Array(128).fill(0); @@ -220,40 +210,6 @@ function minWindow(s: string, t: string): string { } ``` -### **C#** - -```cs -public class Solution { - public string MinWindow(string s, string t) { - int[] need = new int[128]; - int[] window = new int[128]; - foreach (var c in t) { - ++need[c]; - } - int cnt = 0, j = 0, k = -1, mi = 1 << 30; - for (int i = 0; i < s.Length; ++i) { - ++window[s[i]]; - if (need[s[i]] >= window[s[i]]) { - ++cnt; - } - while (cnt == t.Length) { - if (i - j + 1 < mi) { - mi = i - j + 1; - k = j; - } - if (need[s[j]] >= window[s[j]]) { - --cnt; - } - --window[s[j++]]; - } - } - return k < 0 ? "" : s.Substring(k, mi); - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn min_window(s: String, t: String) -> String { @@ -290,10 +246,36 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public string MinWindow(string s, string t) { + int[] need = new int[128]; + int[] window = new int[128]; + foreach (var c in t) { + ++need[c]; + } + int cnt = 0, j = 0, k = -1, mi = 1 << 30; + for (int i = 0; i < s.Length; ++i) { + ++window[s[i]]; + if (need[s[i]] >= window[s[i]]) { + ++cnt; + } + while (cnt == t.Length) { + if (i - j + 1 < mi) { + mi = i - j + 1; + k = j; + } + if (need[s[j]] >= window[s[j]]) { + --cnt; + } + --window[s[j++]]; + } + } + return k < 0 ? "" : s.Substring(k, mi); + } +} ``` + + diff --git a/solution/0000-0099/0077.Combinations/README.md b/solution/0000-0099/0077.Combinations/README.md index 3053c9255e6fc..942e17967ebff 100644 --- a/solution/0000-0099/0077.Combinations/README.md +++ b/solution/0000-0099/0077.Combinations/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:回溯(两种方式)** +### 方法一:回溯(两种方式) 我们设计一个函数 $dfs(i)$,表示从数字 $i$ 开始搜索,当前搜索路径为 $t$,答案为 $ans$。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def combine(self, n: int, k: int) -> List[List[int]]: @@ -93,30 +87,6 @@ class Solution: return ans ``` -```python -class Solution: - def combine(self, n: int, k: int) -> List[List[int]]: - def dfs(i: int): - if len(t) == k: - ans.append(t[:]) - return - if i > n: - return - for j in range(i, n + 1): - t.append(j) - dfs(j + 1) - t.pop() - - ans = [] - t = [] - dfs(1) - return ans -``` - -### **Java** - - - ```java class Solution { private List> ans = new ArrayList<>(); @@ -147,6 +117,155 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector> combine(int n, int k) { + vector> ans; + vector t; + function dfs = [&](int i) { + if (t.size() == k) { + ans.emplace_back(t); + return; + } + if (i > n) { + return; + } + t.emplace_back(i); + dfs(i + 1); + t.pop_back(); + dfs(i + 1); + }; + dfs(1); + return ans; + } +}; +``` + +```go +func combine(n int, k int) (ans [][]int) { + t := []int{} + var dfs func(int) + dfs = func(i int) { + if len(t) == k { + ans = append(ans, slices.Clone(t)) + return + } + if i > n { + return + } + t = append(t, i) + dfs(i + 1) + t = t[:len(t)-1] + dfs(i + 1) + } + dfs(1) + return +} +``` + +```ts +function combine(n: number, k: number): number[][] { + const ans: number[][] = []; + const t: number[] = []; + const dfs = (i: number) => { + if (t.length === k) { + ans.push(t.slice()); + return; + } + if (i > n) { + return; + } + t.push(i); + dfs(i + 1); + t.pop(); + dfs(i + 1); + }; + dfs(1); + return ans; +} +``` + +```rust +impl Solution { + fn dfs(i: i32, n: i32, k: i32, t: &mut Vec, ans: &mut Vec>) { + if t.len() == (k as usize) { + ans.push(t.clone()); + return; + } + if i > n { + return; + } + t.push(i); + Self::dfs(i + 1, n, k, t, ans); + t.pop(); + Self::dfs(i + 1, n, k, t, ans); + } + + pub fn combine(n: i32, k: i32) -> Vec> { + let mut ans = vec![]; + Self::dfs(1, n, k, &mut vec![], &mut ans); + ans + } +} +``` + +```cs +public class Solution { + private List> ans = new List>(); + private List t = new List(); + private int n; + private int k; + + public IList> Combine(int n, int k) { + this.n = n; + this.k = k; + dfs(1); + return ans; + } + + private void dfs(int i) { + if (t.Count == k) { + ans.Add(new List(t)); + return; + } + if (i > n) { + return; + } + t.Add(i); + dfs(i + 1); + t.RemoveAt(t.Count - 1); + dfs(i + 1); + } +} +``` + + + +### 方法二 + + + +```python +class Solution: + def combine(self, n: int, k: int) -> List[List[int]]: + def dfs(i: int): + if len(t) == k: + ans.append(t[:]) + return + if i > n: + return + for j in range(i, n + 1): + t.append(j) + dfs(j + 1) + t.pop() + + ans = [] + t = [] + dfs(1) + return ans +``` + ```java class Solution { private List> ans = new ArrayList<>(); @@ -178,33 +297,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector> combine(int n, int k) { - vector> ans; - vector t; - function dfs = [&](int i) { - if (t.size() == k) { - ans.emplace_back(t); - return; - } - if (i > n) { - return; - } - t.emplace_back(i); - dfs(i + 1); - t.pop_back(); - dfs(i + 1); - }; - dfs(1); - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -231,30 +323,6 @@ public: }; ``` -### **Go** - -```go -func combine(n int, k int) (ans [][]int) { - t := []int{} - var dfs func(int) - dfs = func(i int) { - if len(t) == k { - ans = append(ans, slices.Clone(t)) - return - } - if i > n { - return - } - t = append(t, i) - dfs(i + 1) - t = t[:len(t)-1] - dfs(i + 1) - } - dfs(1) - return -} -``` - ```go func combine(n int, k int) (ans [][]int) { t := []int{} @@ -278,30 +346,6 @@ func combine(n int, k int) (ans [][]int) { } ``` -### **TypeScript** - -```ts -function combine(n: number, k: number): number[][] { - const ans: number[][] = []; - const t: number[] = []; - const dfs = (i: number) => { - if (t.length === k) { - ans.push(t.slice()); - return; - } - if (i > n) { - return; - } - t.push(i); - dfs(i + 1); - t.pop(); - dfs(i + 1); - }; - dfs(1); - return ans; -} -``` - ```ts function combine(n: number, k: number): number[][] { const ans: number[][] = []; @@ -325,32 +369,6 @@ function combine(n: number, k: number): number[][] { } ``` -### **Rust** - -```rust -impl Solution { - fn dfs(i: i32, n: i32, k: i32, t: &mut Vec, ans: &mut Vec>) { - if t.len() == (k as usize) { - ans.push(t.clone()); - return; - } - if i > n { - return; - } - t.push(i); - Self::dfs(i + 1, n, k, t, ans); - t.pop(); - Self::dfs(i + 1, n, k, t, ans); - } - - pub fn combine(n: i32, k: i32) -> Vec> { - let mut ans = vec![]; - Self::dfs(1, n, k, &mut vec![], &mut ans); - ans - } -} -``` - ```rust impl Solution { fn dfs(i: i32, n: i32, k: i32, t: &mut Vec, ans: &mut Vec>) { @@ -376,38 +394,6 @@ impl Solution { } ``` -### **C#** - -```cs -public class Solution { - private List> ans = new List>(); - private List t = new List(); - private int n; - private int k; - - public IList> Combine(int n, int k) { - this.n = n; - this.k = k; - dfs(1); - return ans; - } - - private void dfs(int i) { - if (t.Count == k) { - ans.Add(new List(t)); - return; - } - if (i > n) { - return; - } - t.Add(i); - dfs(i + 1); - t.RemoveAt(t.Count - 1); - dfs(i + 1); - } -} -``` - ```cs public class Solution { private List> ans = new List>(); @@ -439,10 +425,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0077.Combinations/README_EN.md b/solution/0000-0099/0077.Combinations/README_EN.md index 235fcfe8e3bb3..fbf60245f0371 100644 --- a/solution/0000-0099/0077.Combinations/README_EN.md +++ b/solution/0000-0099/0077.Combinations/README_EN.md @@ -36,7 +36,7 @@ Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be ## Solutions -**Solution 1: Backtracking (Two Ways)** +### Solution 1: Backtracking (Two Ways) We design a function $dfs(i)$, which represents starting the search from number $i$, with the current search path as $t$, and the answer as $ans$. @@ -60,8 +60,6 @@ Similar problems: -### **Python3** - ```python class Solution: def combine(self, n: int, k: int) -> List[List[int]]: @@ -82,28 +80,6 @@ class Solution: return ans ``` -```python -class Solution: - def combine(self, n: int, k: int) -> List[List[int]]: - def dfs(i: int): - if len(t) == k: - ans.append(t[:]) - return - if i > n: - return - for j in range(i, n + 1): - t.append(j) - dfs(j + 1) - t.pop() - - ans = [] - t = [] - dfs(1) - return ans -``` - -### **Java** - ```java class Solution { private List> ans = new ArrayList<>(); @@ -134,6 +110,155 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector> combine(int n, int k) { + vector> ans; + vector t; + function dfs = [&](int i) { + if (t.size() == k) { + ans.emplace_back(t); + return; + } + if (i > n) { + return; + } + t.emplace_back(i); + dfs(i + 1); + t.pop_back(); + dfs(i + 1); + }; + dfs(1); + return ans; + } +}; +``` + +```go +func combine(n int, k int) (ans [][]int) { + t := []int{} + var dfs func(int) + dfs = func(i int) { + if len(t) == k { + ans = append(ans, slices.Clone(t)) + return + } + if i > n { + return + } + t = append(t, i) + dfs(i + 1) + t = t[:len(t)-1] + dfs(i + 1) + } + dfs(1) + return +} +``` + +```ts +function combine(n: number, k: number): number[][] { + const ans: number[][] = []; + const t: number[] = []; + const dfs = (i: number) => { + if (t.length === k) { + ans.push(t.slice()); + return; + } + if (i > n) { + return; + } + t.push(i); + dfs(i + 1); + t.pop(); + dfs(i + 1); + }; + dfs(1); + return ans; +} +``` + +```rust +impl Solution { + fn dfs(i: i32, n: i32, k: i32, t: &mut Vec, ans: &mut Vec>) { + if t.len() == (k as usize) { + ans.push(t.clone()); + return; + } + if i > n { + return; + } + t.push(i); + Self::dfs(i + 1, n, k, t, ans); + t.pop(); + Self::dfs(i + 1, n, k, t, ans); + } + + pub fn combine(n: i32, k: i32) -> Vec> { + let mut ans = vec![]; + Self::dfs(1, n, k, &mut vec![], &mut ans); + ans + } +} +``` + +```cs +public class Solution { + private List> ans = new List>(); + private List t = new List(); + private int n; + private int k; + + public IList> Combine(int n, int k) { + this.n = n; + this.k = k; + dfs(1); + return ans; + } + + private void dfs(int i) { + if (t.Count == k) { + ans.Add(new List(t)); + return; + } + if (i > n) { + return; + } + t.Add(i); + dfs(i + 1); + t.RemoveAt(t.Count - 1); + dfs(i + 1); + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def combine(self, n: int, k: int) -> List[List[int]]: + def dfs(i: int): + if len(t) == k: + ans.append(t[:]) + return + if i > n: + return + for j in range(i, n + 1): + t.append(j) + dfs(j + 1) + t.pop() + + ans = [] + t = [] + dfs(1) + return ans +``` + ```java class Solution { private List> ans = new ArrayList<>(); @@ -165,33 +290,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector> combine(int n, int k) { - vector> ans; - vector t; - function dfs = [&](int i) { - if (t.size() == k) { - ans.emplace_back(t); - return; - } - if (i > n) { - return; - } - t.emplace_back(i); - dfs(i + 1); - t.pop_back(); - dfs(i + 1); - }; - dfs(1); - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -218,30 +316,6 @@ public: }; ``` -### **Go** - -```go -func combine(n int, k int) (ans [][]int) { - t := []int{} - var dfs func(int) - dfs = func(i int) { - if len(t) == k { - ans = append(ans, slices.Clone(t)) - return - } - if i > n { - return - } - t = append(t, i) - dfs(i + 1) - t = t[:len(t)-1] - dfs(i + 1) - } - dfs(1) - return -} -``` - ```go func combine(n int, k int) (ans [][]int) { t := []int{} @@ -265,30 +339,6 @@ func combine(n int, k int) (ans [][]int) { } ``` -### **TypeScript** - -```ts -function combine(n: number, k: number): number[][] { - const ans: number[][] = []; - const t: number[] = []; - const dfs = (i: number) => { - if (t.length === k) { - ans.push(t.slice()); - return; - } - if (i > n) { - return; - } - t.push(i); - dfs(i + 1); - t.pop(); - dfs(i + 1); - }; - dfs(1); - return ans; -} -``` - ```ts function combine(n: number, k: number): number[][] { const ans: number[][] = []; @@ -312,32 +362,6 @@ function combine(n: number, k: number): number[][] { } ``` -### **Rust** - -```rust -impl Solution { - fn dfs(i: i32, n: i32, k: i32, t: &mut Vec, ans: &mut Vec>) { - if t.len() == (k as usize) { - ans.push(t.clone()); - return; - } - if i > n { - return; - } - t.push(i); - Self::dfs(i + 1, n, k, t, ans); - t.pop(); - Self::dfs(i + 1, n, k, t, ans); - } - - pub fn combine(n: i32, k: i32) -> Vec> { - let mut ans = vec![]; - Self::dfs(1, n, k, &mut vec![], &mut ans); - ans - } -} -``` - ```rust impl Solution { fn dfs(i: i32, n: i32, k: i32, t: &mut Vec, ans: &mut Vec>) { @@ -363,38 +387,6 @@ impl Solution { } ``` -### **C#** - -```cs -public class Solution { - private List> ans = new List>(); - private List t = new List(); - private int n; - private int k; - - public IList> Combine(int n, int k) { - this.n = n; - this.k = k; - dfs(1); - return ans; - } - - private void dfs(int i) { - if (t.Count == k) { - ans.Add(new List(t)); - return; - } - if (i > n) { - return; - } - t.Add(i); - dfs(i + 1); - t.RemoveAt(t.Count - 1); - dfs(i + 1); - } -} -``` - ```cs public class Solution { private List> ans = new List>(); @@ -426,10 +418,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0078.Subsets/README.md b/solution/0000-0099/0078.Subsets/README.md index 1d86097f8266a..6dbb20333a2d5 100644 --- a/solution/0000-0099/0078.Subsets/README.md +++ b/solution/0000-0099/0078.Subsets/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:DFS(回溯)** +### 方法一:DFS(回溯) 我们设计一个函数 $dfs(i)$,表示从数组的第 $i$ 个元素开始搜索所有子集。函数 $dfs(i)$ 的执行逻辑如下: @@ -51,20 +49,8 @@ 时间复杂度 $O(n\times 2^n)$,空间复杂度 $O(n)$。其中 $n$ 为数组的长度。一共有 $2^n$ 个子集,每个子集需要 $O(n)$ 的时间来构造。 -**方法二:二进制枚举** - -我们也可以使用二进制枚举的方法得到所有的子集。 - -我们可以使用 $2^n$ 个二进制数来表示 $n$ 个元素的所有子集,对于当前二进制数 $mask$,如果第 $i$ 位为 $1$,表示选择了第 $i$ 个元素,否则表示不选择第 $i$ 个元素。 - -时间复杂度 $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]]: @@ -83,20 +69,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 = [x for i, x in enumerate(nums) if mask >> i & 1] - ans.append(t) - return ans -``` - -### **Java** - - - ```java class Solution { private List> ans = new ArrayList<>(); @@ -122,27 +94,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: @@ -165,28 +116,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector> subsets(vector& nums) { - int n = nums.size(); - vector> ans; - for (int mask = 0; mask < 1 << n; ++mask) { - vector t; - for (int i = 0; i < n; ++i) { - if (mask >> i & 1) { - t.emplace_back(nums[i]); - } - } - ans.emplace_back(t); - } - return ans; - } -}; -``` - -### **Go** - ```go func subsets(nums []int) (ans [][]int) { t := []int{} @@ -206,24 +135,6 @@ func subsets(nums []int) (ans [][]int) { } ``` -```go -func subsets(nums []int) (ans [][]int) { - n := len(nums) - for mask := 0; mask < 1<>i&1 == 1 { - t = append(t, x) - } - } - ans = append(ans, t) - } - return -} -``` - -### **TypeScript** - ```ts function subsets(nums: number[]): number[][] { const ans: number[][] = []; @@ -243,25 +154,6 @@ function subsets(nums: number[]): number[][] { } ``` -```ts -function subsets(nums: number[]): number[][] { - const n = nums.length; - const ans: number[][] = []; - for (let mask = 0; mask < 1 << n; ++mask) { - const t: number[] = []; - for (let i = 0; i < n; ++i) { - if (((mask >> i) & 1) === 1) { - t.push(nums[i]); - } - } - ans.push(t); - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { fn dfs(i: usize, t: &mut Vec, res: &mut Vec>, nums: &Vec) { @@ -283,10 +175,100 @@ impl Solution { } ``` -### **...** + + +### 方法二:二进制枚举 + +我们也可以使用二进制枚举的方法得到所有的子集。 + +我们可以使用 $2^n$ 个二进制数来表示 $n$ 个元素的所有子集,对于当前二进制数 $mask$,如果第 $i$ 位为 $1$,表示选择了第 $i$ 个元素,否则表示不选择第 $i$ 个元素。 + +时间复杂度 $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 = [x for i, x in enumerate(nums) if mask >> i & 1] + 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: + vector> subsets(vector& nums) { + int n = nums.size(); + vector> ans; + for (int mask = 0; mask < 1 << n; ++mask) { + vector t; + for (int i = 0; i < n; ++i) { + if (mask >> i & 1) { + t.emplace_back(nums[i]); + } + } + ans.emplace_back(t); + } + return ans; + } +}; +``` + +```go +func subsets(nums []int) (ans [][]int) { + n := len(nums) + for mask := 0; mask < 1<>i&1 == 1 { + t = append(t, x) + } + } + ans = append(ans, t) + } + return +} +``` + +```ts +function subsets(nums: number[]): number[][] { + const n = nums.length; + const ans: number[][] = []; + for (let mask = 0; mask < 1 << n; ++mask) { + const t: number[] = []; + for (let i = 0; i < n; ++i) { + if (((mask >> i) & 1) === 1) { + t.push(nums[i]); + } + } + ans.push(t); + } + return ans; +} ``` + + diff --git a/solution/0000-0099/0078.Subsets/README_EN.md b/solution/0000-0099/0078.Subsets/README_EN.md index 4084424c47cd1..3361d97d95a71 100644 --- a/solution/0000-0099/0078.Subsets/README_EN.md +++ b/solution/0000-0099/0078.Subsets/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: DFS (Backtracking)** +### Solution 1: DFS (Backtracking) We design a function $dfs(i)$, which represents starting the search from the $i$th element of the array for all subsets. The execution logic of the function $dfs(i)$ is as follows: @@ -45,18 +45,8 @@ In the main function, we call $dfs(0)$, i.e., start searching all subsets from 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. There are a total of $2^n$ subsets, and each subset takes $O(n)$ time to construct. -**Solution 2: Binary Enumeration** - -We can also use the method of binary enumeration to get all subsets. - -We can use $2^n$ binary numbers to represent all subsets of $n$ elements. For the current binary number $mask$, if the $i$th bit is $1$, it means that the $i$th element is selected, otherwise it means that the $i$th element is not selected. - -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 takes $O(n)$ time to construct. - -### **Python3** - ```python class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: @@ -75,18 +65,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 = [x for i, x in enumerate(nums) if mask >> i & 1] - ans.append(t) - return ans -``` - -### **Java** - ```java class Solution { private List> ans = new ArrayList<>(); @@ -112,27 +90,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: @@ -155,28 +112,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector> subsets(vector& nums) { - int n = nums.size(); - vector> ans; - for (int mask = 0; mask < 1 << n; ++mask) { - vector t; - for (int i = 0; i < n; ++i) { - if (mask >> i & 1) { - t.emplace_back(nums[i]); - } - } - ans.emplace_back(t); - } - return ans; - } -}; -``` - -### **Go** - ```go func subsets(nums []int) (ans [][]int) { t := []int{} @@ -196,24 +131,6 @@ func subsets(nums []int) (ans [][]int) { } ``` -```go -func subsets(nums []int) (ans [][]int) { - n := len(nums) - for mask := 0; mask < 1<>i&1 == 1 { - t = append(t, x) - } - } - ans = append(ans, t) - } - return -} -``` - -### **TypeScript** - ```ts function subsets(nums: number[]): number[][] { const ans: number[][] = []; @@ -233,36 +150,17 @@ function subsets(nums: number[]): number[][] { } ``` -```ts -function subsets(nums: number[]): number[][] { - const n = nums.length; - const ans: number[][] = []; - for (let mask = 0; mask < 1 << n; ++mask) { - const t: number[] = []; - for (let i = 0; i < n; ++i) { - if (((mask >> i) & 1) === 1) { - t.push(nums[i]); - } - } - ans.push(t); - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { - fn dfs(i: usize, path: &mut Vec, res: &mut Vec>, nums: &Vec) { + fn dfs(i: usize, t: &mut Vec, res: &mut Vec>, nums: &Vec) { if i == nums.len() { - res.push(path.clone()); + res.push(t.clone()); return; } - Self::dfs(i + 1, path, res, nums); - path.push(nums[i]); - Self::dfs(i + 1, path, res, nums); - path.pop(); + Self::dfs(i + 1, t, res, nums); + t.push(nums[i]); + Self::dfs(i + 1, t, res, nums); + t.pop(); } pub fn subsets(nums: Vec) -> Vec> { @@ -273,10 +171,100 @@ impl Solution { } ``` -### **...** + + +### Solution 2: Binary Enumeration + +We can also use the method of binary enumeration to get all subsets. + +We can use $2^n$ binary numbers to represent all subsets of $n$ elements. For the current binary number $mask$, if the $i$th bit is $1$, it means that the $i$th element is selected, otherwise it means that the $i$th element is not selected. + +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 takes $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 = [x for i, x in enumerate(nums) if mask >> i & 1] + 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: + vector> subsets(vector& nums) { + int n = nums.size(); + vector> ans; + for (int mask = 0; mask < 1 << n; ++mask) { + vector t; + for (int i = 0; i < n; ++i) { + if (mask >> i & 1) { + t.emplace_back(nums[i]); + } + } + ans.emplace_back(t); + } + return ans; + } +}; +``` + +```go +func subsets(nums []int) (ans [][]int) { + n := len(nums) + for mask := 0; mask < 1<>i&1 == 1 { + t = append(t, x) + } + } + ans = append(ans, t) + } + return +} +``` + +```ts +function subsets(nums: number[]): number[][] { + const n = nums.length; + const ans: number[][] = []; + for (let mask = 0; mask < 1 << n; ++mask) { + const t: number[] = []; + for (let i = 0; i < n; ++i) { + if (((mask >> i) & 1) === 1) { + t.push(nums[i]); + } + } + ans.push(t); + } + return ans; +} ``` + + diff --git a/solution/0000-0099/0079.Word Search/README.md b/solution/0000-0099/0079.Word Search/README.md index d33ede5b768b5..82b5d9e642220 100644 --- a/solution/0000-0099/0079.Word Search/README.md +++ b/solution/0000-0099/0079.Word Search/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:DFS(回溯)** +### 方法一:DFS(回溯) 我们可以枚举网格的每一个位置 $(i, j)$ 作为搜索的起点,然后从起点开始进行深度优先搜索,如果可以搜索到单词的末尾,就说明单词存在,否则说明单词不存在。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def exist(self, board: List[List[str]], word: str) -> bool: @@ -95,10 +89,6 @@ class Solution: return any(dfs(i, j, 0) for i in range(m) for j in range(n)) ``` -### **Java** - - - ```java class Solution { private int m; @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -181,8 +169,6 @@ public: }; ``` -### **Go** - ```go func exist(board [][]byte, word string) bool { m, n := len(board), len(board[0]) @@ -217,8 +203,6 @@ func exist(board [][]byte, word string) bool { } ``` -### **TypeScript** - ```ts function exist(board: string[][], word: string): boolean { const [m, n] = [board.length, board[0].length]; @@ -253,55 +237,6 @@ function exist(board: string[][], word: string): boolean { } ``` -### **C#** - -```cs -public class Solution { - private int m; - private int n; - private char[][] board; - private string word; - - public bool Exist(char[][] board, string word) { - m = board.Length; - n = board[0].Length; - this.board = board; - this.word = word; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (dfs(i, j, 0)) { - return true; - } - } - } - return false; - } - - private bool dfs(int i, int j, int k) { - if (k == word.Length - 1) { - return board[i][j] == word[k]; - } - if (board[i][j] != word[k]) { - return false; - } - char c = board[i][j]; - board[i][j] = '0'; - int[] dirs = { -1, 0, 1, 0, -1 }; - for (int u = 0; u < 4; ++u) { - int x = i + dirs[u]; - int y = j + dirs[u + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] != '0' && dfs(x, y, k + 1)) { - return true; - } - } - board[i][j] = c; - return false; - } -} -``` - -### **Rust** - ```rust impl Solution { fn dfs( @@ -357,10 +292,51 @@ impl Solution { } ``` -### **...** +```cs +public class Solution { + private int m; + private int n; + private char[][] board; + private string word; -``` + public bool Exist(char[][] board, string word) { + m = board.Length; + n = board[0].Length; + this.board = board; + this.word = word; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (dfs(i, j, 0)) { + return true; + } + } + } + return false; + } + private bool dfs(int i, int j, int k) { + if (k == word.Length - 1) { + return board[i][j] == word[k]; + } + if (board[i][j] != word[k]) { + return false; + } + char c = board[i][j]; + board[i][j] = '0'; + int[] dirs = { -1, 0, 1, 0, -1 }; + for (int u = 0; u < 4; ++u) { + int x = i + dirs[u]; + int y = j + dirs[u + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] != '0' && dfs(x, y, k + 1)) { + return true; + } + } + board[i][j] = c; + return false; + } +} ``` + + diff --git a/solution/0000-0099/0079.Word Search/README_EN.md b/solution/0000-0099/0079.Word Search/README_EN.md index a4a56763e5915..73269931d88eb 100644 --- a/solution/0000-0099/0079.Word Search/README_EN.md +++ b/solution/0000-0099/0079.Word Search/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: DFS (Backtracking)** +### Solution 1: DFS (Backtracking) We can enumerate each position $(i, j)$ in the grid as the starting point of the search, and then start a depth-first search from the starting point. If we can search to the end of the word, it means the word exists, otherwise, it means the word does not exist. @@ -62,8 +62,6 @@ The time complexity is $O(m \times n \times 3^k)$, and the space complexity is $ -### **Python3** - ```python class Solution: def exist(self, board: List[List[str]], word: str) -> bool: @@ -86,8 +84,6 @@ class Solution: return any(dfs(i, j, 0) for i in range(m) for j in range(n)) ``` -### **Java** - ```java class Solution { private int m; @@ -132,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +164,6 @@ public: }; ``` -### **Go** - ```go func exist(board [][]byte, word string) bool { m, n := len(board), len(board[0]) @@ -206,8 +198,6 @@ func exist(board [][]byte, word string) bool { } ``` -### **TypeScript** - ```ts function exist(board: string[][], word: string): boolean { const [m, n] = [board.length, board[0].length]; @@ -242,55 +232,6 @@ function exist(board: string[][], word: string): boolean { } ``` -### **C#** - -```cs -public class Solution { - private int m; - private int n; - private char[][] board; - private string word; - - public bool Exist(char[][] board, string word) { - m = board.Length; - n = board[0].Length; - this.board = board; - this.word = word; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (dfs(i, j, 0)) { - return true; - } - } - } - return false; - } - - private bool dfs(int i, int j, int k) { - if (k == word.Length - 1) { - return board[i][j] == word[k]; - } - if (board[i][j] != word[k]) { - return false; - } - char c = board[i][j]; - board[i][j] = '0'; - int[] dirs = { -1, 0, 1, 0, -1 }; - for (int u = 0; u < 4; ++u) { - int x = i + dirs[u]; - int y = j + dirs[u + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] != '0' && dfs(x, y, k + 1)) { - return true; - } - } - board[i][j] = c; - return false; - } -} -``` - -### **Rust** - ```rust impl Solution { fn dfs( @@ -346,10 +287,51 @@ impl Solution { } ``` -### **...** +```cs +public class Solution { + private int m; + private int n; + private char[][] board; + private string word; -``` + public bool Exist(char[][] board, string word) { + m = board.Length; + n = board[0].Length; + this.board = board; + this.word = word; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (dfs(i, j, 0)) { + return true; + } + } + } + return false; + } + private bool dfs(int i, int j, int k) { + if (k == word.Length - 1) { + return board[i][j] == word[k]; + } + if (board[i][j] != word[k]) { + return false; + } + char c = board[i][j]; + board[i][j] = '0'; + int[] dirs = { -1, 0, 1, 0, -1 }; + for (int u = 0; u < 4; ++u) { + int x = i + dirs[u]; + int y = j + dirs[u + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] != '0' && dfs(x, y, k + 1)) { + return true; + } + } + board[i][j] = c; + return false; + } +} ``` + + diff --git a/solution/0000-0099/0080.Remove Duplicates from Sorted Array II/README.md b/solution/0000-0099/0080.Remove Duplicates from Sorted Array II/README.md index dca20d9316331..ae842e6011937 100644 --- a/solution/0000-0099/0080.Remove Duplicates from Sorted Array II/README.md +++ b/solution/0000-0099/0080.Remove Duplicates from Sorted Array II/README.md @@ -61,9 +61,7 @@ for (int i = 0; i < len; i++) { ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们用一个变量 $k$ 记录当前已经处理好的数组的长度,初始时 $k=0$,表示空数组。 @@ -86,10 +84,6 @@ for (int i = 0; i < len; i++) { -### **Python3** - - - ```python class Solution: def removeDuplicates(self, nums: List[int]) -> int: @@ -101,10 +95,6 @@ class Solution: return k ``` -### **Java** - - - ```java class Solution { public int removeDuplicates(int[] nums) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func removeDuplicates(nums []int) int { k := 0 @@ -151,8 +137,6 @@ func removeDuplicates(nums []int) int { } ``` -### **TypeScript** - ```ts function removeDuplicates(nums: number[]): number { let k = 0; @@ -165,24 +149,21 @@ function removeDuplicates(nums: number[]): number { } ``` -### **C#** - -```cs -public class Solution { - public int RemoveDuplicates(int[] nums) { - int k = 0; - foreach (int x in nums) { - if (k < 2 || x != nums[k - 2]) { - nums[k++] = x; +```rust +impl Solution { + pub fn remove_duplicates(nums: &mut Vec) -> i32 { + let mut k = 0; + for i in 0..nums.len() { + if k < 2 || nums[i] != nums[k - 2] { + nums[k] = nums[i]; + k += 1; } } - return k; + k as i32 } } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -199,27 +180,20 @@ var removeDuplicates = function (nums) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn remove_duplicates(nums: &mut Vec) -> i32 { - let mut k = 0; - for i in 0..nums.len() { - if k < 2 || nums[i] != nums[k - 2] { - nums[k] = nums[i]; - k += 1; +```cs +public class Solution { + public int RemoveDuplicates(int[] nums) { + int k = 0; + foreach (int x in nums) { + if (k < 2 || x != nums[k - 2]) { + nums[k++] = x; } } - k as i32 + return k; } } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0080.Remove Duplicates from Sorted Array II/README_EN.md b/solution/0000-0099/0080.Remove Duplicates from Sorted Array II/README_EN.md index 139078f9db977..c59153e876250 100644 --- a/solution/0000-0099/0080.Remove Duplicates from Sorted Array II/README_EN.md +++ b/solution/0000-0099/0080.Remove Duplicates from Sorted Array II/README_EN.md @@ -60,7 +60,7 @@ It does not matter what you leave beyond the returned k (hence they are undersco ## Solutions -**Solution 1: Single Pass** +### Solution 1: Single Pass We use a variable $k$ to record the current length of the array that has been processed. Initially, $k=0$, representing an empty array. @@ -83,8 +83,6 @@ Similar problems: -### **Python3** - ```python class Solution: def removeDuplicates(self, nums: List[int]) -> int: @@ -96,8 +94,6 @@ class Solution: return k ``` -### **Java** - ```java class Solution { public int removeDuplicates(int[] nums) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +123,6 @@ public: }; ``` -### **Go** - ```go func removeDuplicates(nums []int) int { k := 0 @@ -144,8 +136,6 @@ func removeDuplicates(nums []int) int { } ``` -### **TypeScript** - ```ts function removeDuplicates(nums: number[]): number { let k = 0; @@ -158,24 +148,21 @@ function removeDuplicates(nums: number[]): number { } ``` -### **C#** - -```cs -public class Solution { - public int RemoveDuplicates(int[] nums) { - int k = 0; - foreach (int x in nums) { - if (k < 2 || x != nums[k - 2]) { - nums[k++] = x; +```rust +impl Solution { + pub fn remove_duplicates(nums: &mut Vec) -> i32 { + let mut k = 0; + for i in 0..nums.len() { + if k < 2 || nums[i] != nums[k - 2] { + nums[k] = nums[i]; + k += 1; } } - return k; + k as i32 } } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -192,27 +179,20 @@ var removeDuplicates = function (nums) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn remove_duplicates(nums: &mut Vec) -> i32 { - let mut k = 0; - for i in 0..nums.len() { - if k < 2 || nums[i] != nums[k - 2] { - nums[k] = nums[i]; - k += 1; +```cs +public class Solution { + public int RemoveDuplicates(int[] nums) { + int k = 0; + foreach (int x in nums) { + if (k < 2 || x != nums[k - 2]) { + nums[k++] = x; } } - k as i32 + return k; } } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0081.Search in Rotated Sorted Array II/README.md b/solution/0000-0099/0081.Search in Rotated Sorted Array II/README.md index aab296a90860f..d0b5d10f6b61b 100644 --- a/solution/0000-0099/0081.Search in Rotated Sorted Array II/README.md +++ b/solution/0000-0099/0081.Search in Rotated Sorted Array II/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们定义二分查找的左边界 $l=0$,右边界 $r=n-1$,其中 $n$ 为数组的长度。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def search(self, nums: List[int], target: int) -> bool: @@ -97,10 +91,6 @@ class Solution: return nums[l] == target ``` -### **Java** - - - ```java class Solution { public boolean search(int[] nums, int target) { @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func search(nums []int, target int) bool { l, r := 0, len(nums)-1 @@ -185,8 +171,6 @@ func search(nums []int, target int) bool { } ``` -### **TypeScript** - ```ts function search(nums: number[], target: number): boolean { let [l, r] = [0, nums.length - 1]; @@ -212,10 +196,6 @@ function search(nums: number[], target: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0081.Search in Rotated Sorted Array II/README_EN.md b/solution/0000-0099/0081.Search in Rotated Sorted Array II/README_EN.md index 5c80edb6d9aab..43d3aa5fb3f13 100644 --- a/solution/0000-0099/0081.Search in Rotated Sorted Array II/README_EN.md +++ b/solution/0000-0099/0081.Search in Rotated Sorted Array II/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search We define the left boundary $l=0$ and the right boundary $r=n-1$ for the binary search, where $n$ is the length of the array. @@ -51,8 +51,6 @@ The time complexity is approximately $O(\log n)$, and the space complexity is $O -### **Python3** - ```python class Solution: def search(self, nums: List[int], target: int) -> bool: @@ -75,8 +73,6 @@ class Solution: return nums[l] == target ``` -### **Java** - ```java class Solution { public boolean search(int[] nums, int target) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +128,6 @@ public: }; ``` -### **Go** - ```go func search(nums []int, target int) bool { l, r := 0, len(nums)-1 @@ -161,8 +153,6 @@ func search(nums []int, target int) bool { } ``` -### **TypeScript** - ```ts function search(nums: number[], target: number): boolean { let [l, r] = [0, nums.length - 1]; @@ -188,10 +178,6 @@ function search(nums: number[], target: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0082.Remove Duplicates from Sorted List II/README.md b/solution/0000-0099/0082.Remove Duplicates from Sorted List II/README.md index 495942d745533..9773cf977bf5b 100644 --- a/solution/0000-0099/0082.Remove Duplicates from Sorted List II/README.md +++ b/solution/0000-0099/0082.Remove Duplicates from Sorted List II/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们先创建一个虚拟头节点 $dummy$,令 $dummy.next = head$,然后创建指针 $pre$ 指向 $dummy$,指针 $cur$ 指向 $head$,开始遍历链表。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -75,10 +69,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -174,76 +160,6 @@ func deleteDuplicates(head *ListNode) *ListNode { } ``` -### **C#** - -```cs -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public ListNode DeleteDuplicates(ListNode head) { - ListNode dummy = new ListNode(0, head); - ListNode pre = dummy; - ListNode cur = head; - while (cur != null) { - while (cur.next != null && cur.next.val == cur.val) { - cur = cur.next; - } - if (pre.next == cur) { - pre = cur; - } else { - pre.next = cur.next; - } - cur = cur.next; - } - return dummy.next; - } -} -``` - -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @return {ListNode} - */ -var deleteDuplicates = function (head) { - const dummy = new ListNode(0, head); - let pre = dummy; - let cur = head; - while (cur) { - while (cur.next && cur.val === cur.next.val) { - cur = cur.next; - } - if (pre.next === cur) { - pre = cur; - } else { - pre.next = cur.next; - } - cur = cur.next; - } - return dummy.next; -}; -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -276,8 +192,6 @@ function deleteDuplicates(head: ListNode | null): ListNode | null { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -316,10 +230,70 @@ impl Solution { } ``` -### **...** - +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var deleteDuplicates = function (head) { + const dummy = new ListNode(0, head); + let pre = dummy; + let cur = head; + while (cur) { + while (cur.next && cur.val === cur.next.val) { + cur = cur.next; + } + if (pre.next === cur) { + pre = cur; + } else { + pre.next = cur.next; + } + cur = cur.next; + } + return dummy.next; +}; ``` +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode DeleteDuplicates(ListNode head) { + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy; + ListNode cur = head; + while (cur != null) { + while (cur.next != null && cur.next.val == cur.val) { + cur = cur.next; + } + if (pre.next == cur) { + pre = cur; + } else { + pre.next = cur.next; + } + cur = cur.next; + } + return dummy.next; + } +} ``` + + diff --git a/solution/0000-0099/0082.Remove Duplicates from Sorted List II/README_EN.md b/solution/0000-0099/0082.Remove Duplicates from Sorted List II/README_EN.md index 4e7eb3bc3cf31..4bd04fb6e8d1c 100644 --- a/solution/0000-0099/0082.Remove Duplicates from Sorted List II/README_EN.md +++ b/solution/0000-0099/0082.Remove Duplicates from Sorted List II/README_EN.md @@ -32,7 +32,7 @@ ## Solutions -**Solution 1: Single Pass** +### Solution 1: Single Pass First, we create a dummy head node $dummy$, and set $dummy.next = head$. Then we create a pointer $pre$ pointing to $dummy$, and a pointer $cur$ pointing to $head$, and start traversing the linked list. @@ -44,8 +44,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -67,8 +65,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -101,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -136,8 +130,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -164,76 +156,6 @@ func deleteDuplicates(head *ListNode) *ListNode { } ``` -### **C#** - -```cs -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public ListNode DeleteDuplicates(ListNode head) { - ListNode dummy = new ListNode(0, head); - ListNode pre = dummy; - ListNode cur = head; - while (cur != null) { - while (cur.next != null && cur.next.val == cur.val) { - cur = cur.next; - } - if (pre.next == cur) { - pre = cur; - } else { - pre.next = cur.next; - } - cur = cur.next; - } - return dummy.next; - } -} -``` - -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @return {ListNode} - */ -var deleteDuplicates = function (head) { - const dummy = new ListNode(0, head); - let pre = dummy; - let cur = head; - while (cur) { - while (cur.next && cur.val === cur.next.val) { - cur = cur.next; - } - if (pre.next === cur) { - pre = cur; - } else { - pre.next = cur.next; - } - cur = cur.next; - } - return dummy.next; -}; -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -266,8 +188,6 @@ function deleteDuplicates(head: ListNode | null): ListNode | null { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -306,10 +226,70 @@ impl Solution { } ``` -### **...** - +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var deleteDuplicates = function (head) { + const dummy = new ListNode(0, head); + let pre = dummy; + let cur = head; + while (cur) { + while (cur.next && cur.val === cur.next.val) { + cur = cur.next; + } + if (pre.next === cur) { + pre = cur; + } else { + pre.next = cur.next; + } + cur = cur.next; + } + return dummy.next; +}; ``` +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode DeleteDuplicates(ListNode head) { + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy; + ListNode cur = head; + while (cur != null) { + while (cur.next != null && cur.next.val == cur.val) { + cur = cur.next; + } + if (pre.next == cur) { + pre = cur; + } else { + pre.next = cur.next; + } + cur = cur.next; + } + return dummy.next; + } +} ``` + + diff --git a/solution/0000-0099/0083.Remove Duplicates from Sorted List/README.md b/solution/0000-0099/0083.Remove Duplicates from Sorted List/README.md index 8f8f371f7ccc3..03c10722ad166 100644 --- a/solution/0000-0099/0083.Remove Duplicates from Sorted List/README.md +++ b/solution/0000-0099/0083.Remove Duplicates from Sorted List/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们用一个指针 $cur$ 来遍历链表。如果当前 $cur$ 与 $cur.next$ 对应的元素相同,我们就将 $cur$ 的 $next$ 指针指向 $cur$ 的下下个节点。否则,说明链表中 $cur$ 对应的元素是不重复的,因此可以将 $cur$ 指针移动到下一个节点。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -69,10 +63,6 @@ class Solution: return head ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -151,35 +137,6 @@ func deleteDuplicates(head *ListNode) *ListNode { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val) { - * this.val = val; - * this.next = null; - * } - */ -/** - * @param {ListNode} head - * @return {ListNode} - */ -var deleteDuplicates = function (head) { - let cur = head; - while (cur && cur.next) { - if (cur.next.val === cur.val) { - cur.next = cur.next.next; - } else { - cur = cur.next; - } - } - return head; -}; -``` - -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -215,7 +172,30 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var deleteDuplicates = function (head) { + let cur = head; + while (cur && cur.next) { + if (cur.next.val === cur.val) { + cur.next = cur.next.next; + } else { + cur = cur.next; + } + } + return head; +}; +``` ```cs /** @@ -244,10 +224,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0083.Remove Duplicates from Sorted List/README_EN.md b/solution/0000-0099/0083.Remove Duplicates from Sorted List/README_EN.md index b0bc0625fea77..a96cb4edadd4c 100644 --- a/solution/0000-0099/0083.Remove Duplicates from Sorted List/README_EN.md +++ b/solution/0000-0099/0083.Remove Duplicates from Sorted List/README_EN.md @@ -32,7 +32,7 @@ ## Solutions -**Solution 1: Single Pass** +### Solution 1: Single Pass We use a pointer $cur$ to traverse the linked list. If the element corresponding to the current $cur$ is the same as the element corresponding to $cur.next$, we set the $next$ pointer of $cur$ to point to the next node of $cur.next$. Otherwise, it means that the element corresponding to $cur$ in the linked list is not duplicated, so we can move the $cur$ pointer to the next node. @@ -42,8 +42,6 @@ The time complexity is $O(n)$, where $n$ is the length of the linked list. The s -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -61,8 +59,6 @@ class Solution: return head ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -141,35 +133,6 @@ func deleteDuplicates(head *ListNode) *ListNode { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val) { - * this.val = val; - * this.next = null; - * } - */ -/** - * @param {ListNode} head - * @return {ListNode} - */ -var deleteDuplicates = function (head) { - let cur = head; - while (cur && cur.next) { - if (cur.next.val === cur.val) { - cur.next = cur.next.next; - } else { - cur = cur.next; - } - } - return head; -}; -``` - -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -205,7 +168,30 @@ impl Solution { } ``` -### **C#** +```js +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var deleteDuplicates = function (head) { + let cur = head; + while (cur && cur.next) { + if (cur.next.val === cur.val) { + cur.next = cur.next.next; + } else { + cur = cur.next; + } + } + return head; +}; +``` ```cs /** @@ -234,10 +220,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0084.Largest Rectangle in Histogram/README.md b/solution/0000-0099/0084.Largest Rectangle in Histogram/README.md index 450765c52267c..492e5e97d4893 100644 --- a/solution/0000-0099/0084.Largest Rectangle in Histogram/README.md +++ b/solution/0000-0099/0084.Largest Rectangle in Histogram/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 我们可以枚举每根柱子的高度 $h$ 作为矩形的高度,利用单调栈,向左右两边找第一个高度小于 $h$ 的下标 $left_i$, $right_i$。那么此时矩形面积为 $h \times (right_i-left_i-1)$,求最大值即可。 @@ -61,10 +59,6 @@ for i in range(n): -### **Python3** - - - ```python class Solution: def largestRectangleArea(self, heights: List[int]) -> int: @@ -82,34 +76,6 @@ class Solution: return max(h * (right[i] - left[i] - 1) for i, h in enumerate(heights)) ``` -```python -class Solution: - def largestRectangleArea(self, heights: List[int]) -> int: - n = len(heights) - stk = [] - left = [-1] * n - right = [n] * n - for i, h in enumerate(heights): - while stk and heights[stk[-1]] >= h: - stk.pop() - if stk: - left[i] = stk[-1] - stk.append(i) - stk = [] - for i in range(n - 1, -1, -1): - h = heights[i] - while stk and heights[stk[-1]] >= h: - stk.pop() - if stk: - right[i] = stk[-1] - stk.append(i) - return max(h * (right[i] - left[i] - 1) for i, h in enumerate(heights)) -``` - -### **Java** - - - ```java class Solution { public int largestRectangleArea(int[] heights) { @@ -133,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,7 +122,32 @@ public: }; ``` -### **Rust** +```go +func largestRectangleArea(heights []int) int { + res, n := 0, len(heights) + var stk []int + left, right := make([]int, n), make([]int, n) + for i := range right { + right[i] = n + } + for i, h := range heights { + for len(stk) > 0 && heights[stk[len(stk)-1]] >= h { + right[stk[len(stk)-1]] = i + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + left[i] = stk[len(stk)-1] + } else { + left[i] = -1 + } + stk = append(stk, i) + } + for i, h := range heights { + res = max(res, h*(right[i]-left[i]-1)) + } + return res +} +``` ```rust impl Solution { @@ -208,39 +197,66 @@ impl Solution { } ``` -### **Go** +```cs +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public int LargestRectangleArea(int[] height) { + var stack = new Stack(); + var result = 0; + var i = 0; + while (i < height.Length || stack.Any()) + { + if (!stack.Any() || (i < height.Length && height[stack.Peek()] < height[i])) + { + stack.Push(i); + ++i; + } + else + { + var previousIndex = stack.Pop(); + var area = height[previousIndex] * (stack.Any() ? (i - stack.Peek() - 1) : i); + result = Math.Max(result, area); + } + } -```go -func largestRectangleArea(heights []int) int { - res, n := 0, len(heights) - var stk []int - left, right := make([]int, n), make([]int, n) - for i := range right { - right[i] = n - } - for i, h := range heights { - for len(stk) > 0 && heights[stk[len(stk)-1]] >= h { - right[stk[len(stk)-1]] = i - stk = stk[:len(stk)-1] - } - if len(stk) > 0 { - left[i] = stk[len(stk)-1] - } else { - left[i] = -1 - } - stk = append(stk, i) - } - for i, h := range heights { - res = max(res, h*(right[i]-left[i]-1)) - } - return res + return result; + } } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def largestRectangleArea(self, heights: List[int]) -> int: + n = len(heights) + stk = [] + left = [-1] * n + right = [n] * n + for i, h in enumerate(heights): + while stk and heights[stk[-1]] >= h: + stk.pop() + if stk: + left[i] = stk[-1] + stk.append(i) + stk = [] + for i in range(n - 1, -1, -1): + h = heights[i] + while stk and heights[stk[-1]] >= h: + stk.pop() + if stk: + right[i] = stk[-1] + stk.append(i) + return max(h * (right[i] - left[i] - 1) for i, h in enumerate(heights)) ``` + + diff --git a/solution/0000-0099/0084.Largest Rectangle in Histogram/README_EN.md b/solution/0000-0099/0084.Largest Rectangle in Histogram/README_EN.md index 9d1997c59592f..f15d876c7703f 100644 --- a/solution/0000-0099/0084.Largest Rectangle in Histogram/README_EN.md +++ b/solution/0000-0099/0084.Largest Rectangle in Histogram/README_EN.md @@ -33,7 +33,7 @@ The largest rectangle is shown in the red area, which has an area = 10 units. ## Solutions -**Solution 1: Monotonic Stack** +### Solution 1: Monotonic Stack We can enumerate the height $h$ of each bar as the height of the rectangle. Using a monotonic stack, we find the index $left_i$, $right_i$ of the first bar with a height less than $h$ to the left and right. The area of the rectangle at this time is $h \times (right_i-left_i-1)$. We can find the maximum value. @@ -51,8 +51,6 @@ for i in range(n): -### **Python3** - ```python class Solution: def largestRectangleArea(self, heights: List[int]) -> int: @@ -70,32 +68,6 @@ class Solution: return max(h * (right[i] - left[i] - 1) for i, h in enumerate(heights)) ``` -```python -class Solution: - def largestRectangleArea(self, heights: List[int]) -> int: - n = len(heights) - stk = [] - left = [-1] * n - right = [n] * n - for i, h in enumerate(heights): - while stk and heights[stk[-1]] >= h: - stk.pop() - if stk: - left[i] = stk[-1] - stk.append(i) - stk = [] - for i in range(n - 1, -1, -1): - h = heights[i] - while stk and heights[stk[-1]] >= h: - stk.pop() - if stk: - right[i] = stk[-1] - stk.append(i) - return max(h * (right[i] - left[i] - 1) for i, h in enumerate(heights)) -``` - -### **Java** - ```java class Solution { public int largestRectangleArea(int[] heights) { @@ -119,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,7 +114,32 @@ public: }; ``` -### **Rust** +```go +func largestRectangleArea(heights []int) int { + res, n := 0, len(heights) + var stk []int + left, right := make([]int, n), make([]int, n) + for i := range right { + right[i] = n + } + for i, h := range heights { + for len(stk) > 0 && heights[stk[len(stk)-1]] >= h { + right[stk[len(stk)-1]] = i + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + left[i] = stk[len(stk)-1] + } else { + left[i] = -1 + } + stk = append(stk, i) + } + for i, h := range heights { + res = max(res, h*(right[i]-left[i]-1)) + } + return res +} +``` ```rust impl Solution { @@ -194,39 +189,66 @@ impl Solution { } ``` -### **Go** +```cs +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public int LargestRectangleArea(int[] height) { + var stack = new Stack(); + var result = 0; + var i = 0; + while (i < height.Length || stack.Any()) + { + if (!stack.Any() || (i < height.Length && height[stack.Peek()] < height[i])) + { + stack.Push(i); + ++i; + } + else + { + var previousIndex = stack.Pop(); + var area = height[previousIndex] * (stack.Any() ? (i - stack.Peek() - 1) : i); + result = Math.Max(result, area); + } + } -```go -func largestRectangleArea(heights []int) int { - res, n := 0, len(heights) - var stk []int - left, right := make([]int, n), make([]int, n) - for i := range right { - right[i] = n - } - for i, h := range heights { - for len(stk) > 0 && heights[stk[len(stk)-1]] >= h { - right[stk[len(stk)-1]] = i - stk = stk[:len(stk)-1] - } - if len(stk) > 0 { - left[i] = stk[len(stk)-1] - } else { - left[i] = -1 - } - stk = append(stk, i) - } - for i, h := range heights { - res = max(res, h*(right[i]-left[i]-1)) - } - return res + return result; + } } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def largestRectangleArea(self, heights: List[int]) -> int: + n = len(heights) + stk = [] + left = [-1] * n + right = [n] * n + for i, h in enumerate(heights): + while stk and heights[stk[-1]] >= h: + stk.pop() + if stk: + left[i] = stk[-1] + stk.append(i) + stk = [] + for i in range(n - 1, -1, -1): + h = heights[i] + while stk and heights[stk[-1]] >= h: + stk.pop() + if stk: + right[i] = stk[-1] + stk.append(i) + return max(h * (right[i] - left[i] - 1) for i, h in enumerate(heights)) ``` + + diff --git a/solution/0000-0099/0085.Maximal Rectangle/README.md b/solution/0000-0099/0085.Maximal Rectangle/README.md index e9a396013b894..a7d33d238b2d3 100644 --- a/solution/0000-0099/0085.Maximal Rectangle/README.md +++ b/solution/0000-0099/0085.Maximal Rectangle/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 我们把每一行视为柱状图的底部,对每一行求柱状图的最大面积即可。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: @@ -95,10 +89,6 @@ class Solution: return max(h * (right[i] - left[i] - 1) for i, h in enumerate(heights)) ``` -### **Java** - - - ```java class Solution { public int maximalRectangle(char[][] matrix) { @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -180,7 +168,49 @@ public: }; ``` -### **Rust** +```go +func maximalRectangle(matrix [][]byte) int { + n := len(matrix[0]) + heights := make([]int, n) + ans := 0 + for _, row := range matrix { + for j, v := range row { + if v == '1' { + heights[j]++ + } else { + heights[j] = 0 + } + } + ans = max(ans, largestRectangleArea(heights)) + } + return ans +} + +func largestRectangleArea(heights []int) int { + res, n := 0, len(heights) + var stk []int + left, right := make([]int, n), make([]int, n) + for i := range right { + right[i] = n + } + for i, h := range heights { + for len(stk) > 0 && heights[stk[len(stk)-1]] >= h { + right[stk[len(stk)-1]] = i + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + left[i] = stk[len(stk)-1] + } else { + left[i] = -1 + } + stk = append(stk, i) + } + for i, h := range heights { + res = max(res, h*(right[i]-left[i]-1)) + } + return res +} +``` ```rust impl Solution { @@ -260,56 +290,59 @@ impl Solution { } ``` -### **Go** +```cs +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution { + private int MaximalRectangleHistagram(int[] height) { + var stack = new Stack(); + var result = 0; + var i = 0; + while (i < height.Length || stack.Any()) + { + if (!stack.Any() || (i < height.Length && height[stack.Peek()] < height[i])) + { + stack.Push(i); + ++i; + } + else + { + var previousIndex = stack.Pop(); + var area = height[previousIndex] * (stack.Any() ? (i - stack.Peek() - 1) : i); + result = Math.Max(result, area); + } + } -```go -func maximalRectangle(matrix [][]byte) int { - n := len(matrix[0]) - heights := make([]int, n) - ans := 0 - for _, row := range matrix { - for j, v := range row { - if v == '1' { - heights[j]++ - } else { - heights[j] = 0 - } - } - ans = max(ans, largestRectangleArea(heights)) - } - return ans -} + return result; + } -func largestRectangleArea(heights []int) int { - res, n := 0, len(heights) - var stk []int - left, right := make([]int, n), make([]int, n) - for i := range right { - right[i] = n - } - for i, h := range heights { - for len(stk) > 0 && heights[stk[len(stk)-1]] >= h { - right[stk[len(stk)-1]] = i - stk = stk[:len(stk)-1] - } - if len(stk) > 0 { - left[i] = stk[len(stk)-1] - } else { - left[i] = -1 - } - stk = append(stk, i) - } - for i, h := range heights { - res = max(res, h*(right[i]-left[i]-1)) - } - return res + public int MaximalRectangle(char[][] matrix) { + var lenI = matrix.Length; + var lenJ = lenI == 0 ? 0 : matrix[0].Length; + var height = new int[lenJ]; + var result = 0; + for (var i = 0; i < lenI; ++i) + { + for (var j = 0; j < lenJ; ++j) + { + if (matrix[i][j] == '1') + { + ++height[j]; + } + else + { + height[j] = 0; + } + } + result = Math.Max(result, MaximalRectangleHistagram(height)); + } + return result; + } } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0085.Maximal Rectangle/README_EN.md b/solution/0000-0099/0085.Maximal Rectangle/README_EN.md index e94431f84c043..08e3355cdea2d 100644 --- a/solution/0000-0099/0085.Maximal Rectangle/README_EN.md +++ b/solution/0000-0099/0085.Maximal Rectangle/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Monotonic Stack** +### Solution 1: Monotonic Stack We treat each row as the base of the histogram, and calculate the maximum area of the histogram for each row. @@ -49,8 +49,6 @@ The time complexity is $O(m \times n)$, where $m$ represents the number of rows -### **Python3** - ```python class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: @@ -87,8 +85,6 @@ class Solution: return max(h * (right[i] - left[i] - 1) for i, h in enumerate(heights)) ``` -### **Java** - ```java class Solution { public int maximalRectangle(char[][] matrix) { @@ -129,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,7 +164,49 @@ public: }; ``` -### **Rust** +```go +func maximalRectangle(matrix [][]byte) int { + n := len(matrix[0]) + heights := make([]int, n) + ans := 0 + for _, row := range matrix { + for j, v := range row { + if v == '1' { + heights[j]++ + } else { + heights[j] = 0 + } + } + ans = max(ans, largestRectangleArea(heights)) + } + return ans +} + +func largestRectangleArea(heights []int) int { + res, n := 0, len(heights) + var stk []int + left, right := make([]int, n), make([]int, n) + for i := range right { + right[i] = n + } + for i, h := range heights { + for len(stk) > 0 && heights[stk[len(stk)-1]] >= h { + right[stk[len(stk)-1]] = i + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + left[i] = stk[len(stk)-1] + } else { + left[i] = -1 + } + stk = append(stk, i) + } + for i, h := range heights { + res = max(res, h*(right[i]-left[i]-1)) + } + return res +} +``` ```rust impl Solution { @@ -250,56 +286,59 @@ impl Solution { } ``` -### **Go** +```cs +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution { + private int MaximalRectangleHistagram(int[] height) { + var stack = new Stack(); + var result = 0; + var i = 0; + while (i < height.Length || stack.Any()) + { + if (!stack.Any() || (i < height.Length && height[stack.Peek()] < height[i])) + { + stack.Push(i); + ++i; + } + else + { + var previousIndex = stack.Pop(); + var area = height[previousIndex] * (stack.Any() ? (i - stack.Peek() - 1) : i); + result = Math.Max(result, area); + } + } -```go -func maximalRectangle(matrix [][]byte) int { - n := len(matrix[0]) - heights := make([]int, n) - ans := 0 - for _, row := range matrix { - for j, v := range row { - if v == '1' { - heights[j]++ - } else { - heights[j] = 0 - } - } - ans = max(ans, largestRectangleArea(heights)) - } - return ans -} + return result; + } -func largestRectangleArea(heights []int) int { - res, n := 0, len(heights) - var stk []int - left, right := make([]int, n), make([]int, n) - for i := range right { - right[i] = n - } - for i, h := range heights { - for len(stk) > 0 && heights[stk[len(stk)-1]] >= h { - right[stk[len(stk)-1]] = i - stk = stk[:len(stk)-1] - } - if len(stk) > 0 { - left[i] = stk[len(stk)-1] - } else { - left[i] = -1 - } - stk = append(stk, i) - } - for i, h := range heights { - res = max(res, h*(right[i]-left[i]-1)) - } - return res + public int MaximalRectangle(char[][] matrix) { + var lenI = matrix.Length; + var lenJ = lenI == 0 ? 0 : matrix[0].Length; + var height = new int[lenJ]; + var result = 0; + for (var i = 0; i < lenI; ++i) + { + for (var j = 0; j < lenJ; ++j) + { + if (matrix[i][j] == '1') + { + ++height[j]; + } + else + { + height[j] = 0; + } + } + result = Math.Max(result, MaximalRectangleHistagram(height)); + } + return result; + } } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0086.Partition List/README.md b/solution/0000-0099/0086.Partition List/README.md index 616af705e35bb..81aa0d55ce69c 100644 --- a/solution/0000-0099/0086.Partition List/README.md +++ b/solution/0000-0099/0086.Partition List/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们创建两个链表,一个存放小于 $x$ 的节点,另一个存放大于等于 $x$ 的节点,之后进行拼接即可。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -75,10 +69,6 @@ class Solution: return d1.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -178,44 +164,6 @@ func partition(head *ListNode, x int) *ListNode { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @param {number} x - * @return {ListNode} - */ -var partition = function (head, x) { - const d1 = new ListNode(); - const d2 = new ListNode(); - let t1 = d1, - t2 = d2; - while (head) { - if (head.val < x) { - t1.next = head; - t1 = t1.next; - } else { - t2.next = head; - t2 = t2.next; - } - head = head.next; - } - t1.next = d2.next; - t2.next = null; - return d1.next; -}; -``` - -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -255,10 +203,40 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} x + * @return {ListNode} + */ +var partition = function (head, x) { + const d1 = new ListNode(); + const d2 = new ListNode(); + let t1 = d1, + t2 = d2; + while (head) { + if (head.val < x) { + t1.next = head; + t1 = t1.next; + } else { + t2.next = head; + t2 = t2.next; + } + head = head.next; + } + t1.next = d2.next; + t2.next = null; + return d1.next; +}; ``` + + diff --git a/solution/0000-0099/0086.Partition List/README_EN.md b/solution/0000-0099/0086.Partition List/README_EN.md index c95f4f179d03a..33560ceb24876 100644 --- a/solution/0000-0099/0086.Partition List/README_EN.md +++ b/solution/0000-0099/0086.Partition List/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We create two linked lists, one to store nodes less than $x$, and the other to store nodes greater than or equal to $x$. Then we concatenate them. @@ -42,8 +42,6 @@ The time complexity is $O(n)$, where $n$ is the length of the original linked li -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -67,8 +65,6 @@ class Solution: return d1.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -102,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -139,8 +133,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -168,44 +160,6 @@ func partition(head *ListNode, x int) *ListNode { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @param {number} x - * @return {ListNode} - */ -var partition = function (head, x) { - const d1 = new ListNode(); - const d2 = new ListNode(); - let t1 = d1, - t2 = d2; - while (head) { - if (head.val < x) { - t1.next = head; - t1 = t1.next; - } else { - t2.next = head; - t2 = t2.next; - } - head = head.next; - } - t1.next = d2.next; - t2.next = null; - return d1.next; -}; -``` - -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -245,10 +199,40 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} x + * @return {ListNode} + */ +var partition = function (head, x) { + const d1 = new ListNode(); + const d2 = new ListNode(); + let t1 = d1, + t2 = d2; + while (head) { + if (head.val < x) { + t1.next = head; + t1 = t1.next; + } else { + t2.next = head; + t2 = t2.next; + } + head = head.next; + } + t1.next = d2.next; + t2.next = null; + return d1.next; +}; ``` + + diff --git a/solution/0000-0099/0087.Scramble String/README.md b/solution/0000-0099/0087.Scramble String/README.md index 9732c91407a57..3cf514af87ea1 100644 --- a/solution/0000-0099/0087.Scramble String/README.md +++ b/solution/0000-0099/0087.Scramble String/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j, k)$,表示字符串 $s_1$ 从 $i$ 开始长度为 $k$ 的子串是否能变换为字符串 $s_2$ 从 $j$ 开始长度为 $k$ 的子串。如果能变换,返回 `true`,否则返回 `false`。那么答案就是 $dfs(0, 0, n)$,其中 $n$ 是字符串的长度。 @@ -82,24 +80,8 @@ 时间复杂度 $O(n^4)$,空间复杂度 $O(n^3)$。其中 $n$ 是字符串的长度。 -**方法二:动态规划(区间 DP)** - -我们定义 $f[i][j][k]$ 表示字符串 $s_1$ 从 $i$ 开始长度为 $k$ 的子串是否能变换为字符串 $s_2$ 从 $j$ 开始长度为 $k$ 的子串。那么答案就是 $f[0][0][n]$,其中 $n$ 是字符串的长度。 - -对于长度为 $1$ 的子串,如果 $s_1[i] = s_2[j]$,那么 $f[i][j][1] = true$,否则 $f[i][j][1] = false$。 - -接下来,我们从小到大枚举子串的长度 $k$,从 $0$ 开始枚举 $i$,从 $0$ 开始枚举 $j$,如果 $f[i][j][h] \land f[i + h][j + h][k - h]$ 或者 $f[i][j + k - h][h] \land f[i + h][j][k - h]$ 成立,那么 $f[i][j][k]$ 也成立。 - -最后,我们返回 $f[0][0][n]$。 - -时间复杂度 $O(n^4)$,空间复杂度 $O(n^3)$。其中 $n$ 是字符串的长度。 - -### **Python3** - - - ```python class Solution: def isScramble(self, s1: str, s2: str) -> bool: @@ -117,31 +99,6 @@ class Solution: return dfs(0, 0, len(s1)) ``` -```python -class Solution: - def isScramble(self, s1: str, s2: str) -> bool: - n = len(s1) - f = [[[False] * (n + 1) for _ in range(n)] for _ in range(n)] - for i in range(n): - for j in range(n): - f[i][j][1] = s1[i] == s2[j] - for k in range(2, n + 1): - for i in range(n - k + 1): - for j in range(n - k + 1): - for h in range(1, k): - if f[i][j][h] and f[i + h][j + h][k - h]: - f[i][j][k] = True - break - if f[i + h][j][k - h] and f[i][j + k - h][h]: - f[i][j][k] = True - break - return f[0][0][n] -``` - -### **Java** - - - ```java class Solution { private Boolean[][][] f; @@ -176,39 +133,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isScramble(String s1, String s2) { - int n = s1.length(); - boolean[][][] f = new boolean[n][n][n + 1]; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - f[i][j][1] = s1.charAt(i) == s2.charAt(j); - } - } - for (int k = 2; k <= n; ++k) { - for (int i = 0; i <= n - k; ++i) { - for (int j = 0; j <= n - k; ++j) { - for (int h = 1; h < k; ++h) { - if (f[i][j][h] && f[i + h][j + h][k - h]) { - f[i][j][k] = true; - break; - } - if (f[i + h][j][k - h] && f[i][j + k - h][h]) { - f[i][j][k] = true; - break; - } - } - } - } - } - return f[0][0][n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -238,41 +162,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool isScramble(string s1, string s2) { - int n = s1.length(); - bool f[n][n][n + 1]; - memset(f, false, sizeof(f)); - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - f[i][j][1] = s1[i] == s2[j]; - } - } - for (int k = 2; k <= n; ++k) { - for (int i = 0; i <= n - k; ++i) { - for (int j = 0; j <= n - k; ++j) { - for (int h = 1; h < k; ++h) { - if () { - f[i][j][k] = true; - break; - } - if (f[i + h][j][k - h] && f[i][j + k - h][h]) { - f[i][j][k] = true; - break; - } - } - } - } - } - return f[0][0][n]; - } -}; -``` - -### **Go** - ```go func isScramble(s1 string, s2 string) bool { n := len(s1) @@ -304,35 +193,6 @@ func isScramble(s1 string, s2 string) bool { } ``` -```go -func isScramble(s1 string, s2 string) bool { - n := len(s1) - f := make([][][]bool, n) - for i := range f { - f[i] = make([][]bool, n) - for j := 0; j < n; j++ { - f[i][j] = make([]bool, n+1) - f[i][j][1] = s1[i] == s2[j] - } - } - for k := 2; k <= n; k++ { - for i := 0; i <= n-k; i++ { - for j := 0; j <= n-k; j++ { - for h := 1; h < k; h++ { - if (f[i][j][h] && f[i+h][j+h][k-h]) || (f[i+h][j][k-h] && f[i][j+k-h][h]) { - f[i][j][k] = true - break - } - } - } - } - } - return f[0][0][n] -} -``` - -### **TypeScript** - ```ts function isScramble(s1: string, s2: string): boolean { const n = s1.length; @@ -360,39 +220,6 @@ function isScramble(s1: string, s2: string): boolean { } ``` -```ts -function isScramble(s1: string, s2: string): boolean { - const n = s1.length; - const f = new Array(n) - .fill(0) - .map(() => new Array(n).fill(0).map(() => new Array(n + 1).fill(false))); - for (let i = 0; i < n; ++i) { - for (let j = 0; j < n; ++j) { - f[i][j][1] = s1[i] === s2[j]; - } - } - for (let k = 2; k <= n; ++k) { - for (let i = 0; i <= n - k; ++i) { - for (let j = 0; j <= n - k; ++j) { - for (let h = 1; h < k; ++h) { - if (f[i][j][h] && f[i + h][j + h][k - h]) { - f[i][j][k] = true; - break; - } - if (f[i + h][j][k - h] && f[i][j + k - h][h]) { - f[i][j][k] = true; - break; - } - } - } - } - } - return f[0][0][n]; -} -``` - -### **C#** - ```cs public class Solution { private string s1; @@ -430,6 +257,165 @@ public class Solution { } ``` + + +### 方法二:动态规划(区间 DP) + +我们定义 $f[i][j][k]$ 表示字符串 $s_1$ 从 $i$ 开始长度为 $k$ 的子串是否能变换为字符串 $s_2$ 从 $j$ 开始长度为 $k$ 的子串。那么答案就是 $f[0][0][n]$,其中 $n$ 是字符串的长度。 + +对于长度为 $1$ 的子串,如果 $s_1[i] = s_2[j]$,那么 $f[i][j][1] = true$,否则 $f[i][j][1] = false$。 + +接下来,我们从小到大枚举子串的长度 $k$,从 $0$ 开始枚举 $i$,从 $0$ 开始枚举 $j$,如果 $f[i][j][h] \land f[i + h][j + h][k - h]$ 或者 $f[i][j + k - h][h] \land f[i + h][j][k - h]$ 成立,那么 $f[i][j][k]$ 也成立。 + +最后,我们返回 $f[0][0][n]$。 + +时间复杂度 $O(n^4)$,空间复杂度 $O(n^3)$。其中 $n$ 是字符串的长度。 + + + +```python +class Solution: + def isScramble(self, s1: str, s2: str) -> bool: + n = len(s1) + f = [[[False] * (n + 1) for _ in range(n)] for _ in range(n)] + for i in range(n): + for j in range(n): + f[i][j][1] = s1[i] == s2[j] + for k in range(2, n + 1): + for i in range(n - k + 1): + for j in range(n - k + 1): + for h in range(1, k): + if f[i][j][h] and f[i + h][j + h][k - h]: + f[i][j][k] = True + break + if f[i + h][j][k - h] and f[i][j + k - h][h]: + f[i][j][k] = True + break + return f[0][0][n] +``` + +```java +class Solution { + public boolean isScramble(String s1, String s2) { + int n = s1.length(); + boolean[][][] f = new boolean[n][n][n + 1]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + f[i][j][1] = s1.charAt(i) == s2.charAt(j); + } + } + for (int k = 2; k <= n; ++k) { + for (int i = 0; i <= n - k; ++i) { + for (int j = 0; j <= n - k; ++j) { + for (int h = 1; h < k; ++h) { + if (f[i][j][h] && f[i + h][j + h][k - h]) { + f[i][j][k] = true; + break; + } + if (f[i + h][j][k - h] && f[i][j + k - h][h]) { + f[i][j][k] = true; + break; + } + } + } + } + } + return f[0][0][n]; + } +} +``` + +```cpp +class Solution { +public: + bool isScramble(string s1, string s2) { + int n = s1.length(); + bool f[n][n][n + 1]; + memset(f, false, sizeof(f)); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + f[i][j][1] = s1[i] == s2[j]; + } + } + for (int k = 2; k <= n; ++k) { + for (int i = 0; i <= n - k; ++i) { + for (int j = 0; j <= n - k; ++j) { + for (int h = 1; h < k; ++h) { + if () { + f[i][j][k] = true; + break; + } + if (f[i + h][j][k - h] && f[i][j + k - h][h]) { + f[i][j][k] = true; + break; + } + } + } + } + } + return f[0][0][n]; + } +}; +``` + +```go +func isScramble(s1 string, s2 string) bool { + n := len(s1) + f := make([][][]bool, n) + for i := range f { + f[i] = make([][]bool, n) + for j := 0; j < n; j++ { + f[i][j] = make([]bool, n+1) + f[i][j][1] = s1[i] == s2[j] + } + } + for k := 2; k <= n; k++ { + for i := 0; i <= n-k; i++ { + for j := 0; j <= n-k; j++ { + for h := 1; h < k; h++ { + if (f[i][j][h] && f[i+h][j+h][k-h]) || (f[i+h][j][k-h] && f[i][j+k-h][h]) { + f[i][j][k] = true + break + } + } + } + } + } + return f[0][0][n] +} +``` + +```ts +function isScramble(s1: string, s2: string): boolean { + const n = s1.length; + const f = new Array(n) + .fill(0) + .map(() => new Array(n).fill(0).map(() => new Array(n + 1).fill(false))); + for (let i = 0; i < n; ++i) { + for (let j = 0; j < n; ++j) { + f[i][j][1] = s1[i] === s2[j]; + } + } + for (let k = 2; k <= n; ++k) { + for (let i = 0; i <= n - k; ++i) { + for (let j = 0; j <= n - k; ++j) { + for (let h = 1; h < k; ++h) { + if (f[i][j][h] && f[i + h][j + h][k - h]) { + f[i][j][k] = true; + break; + } + if (f[i + h][j][k - h] && f[i][j + k - h][h]) { + f[i][j][k] = true; + break; + } + } + } + } + } + return f[0][0][n]; +} +``` + ```cs public class Solution { public bool IsScramble(string s1, string s2) { @@ -461,10 +447,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0087.Scramble String/README_EN.md b/solution/0000-0099/0087.Scramble String/README_EN.md index 03deeadd10941..8bd45d23a53ed 100644 --- a/solution/0000-0099/0087.Scramble String/README_EN.md +++ b/solution/0000-0099/0087.Scramble String/README_EN.md @@ -61,7 +61,7 @@ As one possible scenario led s1 to be scrambled to s2, we return true. ## Solutions -**Solution 1: Memorized Search** +### Solution 1: Memorized Search We design a function $dfs(i, j, k)$, which means whether the substring starting from $i$ with length $k$ in $s_1$ can be converted into the substring starting from $j$ with length $k$ in $s_2$. If it can be converted, return `true`, otherwise return `false`. The answer is $dfs(0, 0, n)$, where $n$ is the length of the string. @@ -76,22 +76,8 @@ In order to avoid repeated calculation, we can use memory search. The time complexity is $O(n^4)$, and the space complexity is $O(n^3)$. Where $n$ is the length of the string. -**Solution 2: Dynamic Programming (Interval DP)** - -We define $f[i][j][k]$ as whether the substring of length $k$ starting from $i$ of string $s_1$ can be transformed into the substring of length $k$ starting from $j$ of string $s_2$. Then the answer is $f[0][0][n]$, where $n$ is the length of the string. - -For substring of length $1$, if $s_1[i] = s_2[j]$, then $f[i][j][1] = true$, otherwise $f[i][j][1] = false$. - -Next, we enumerate the length $k$ of the substring from small to large, and enumerate $i$ from $0$, and enumerate $j$ from $0$. If $f[i][j][h] \land f[i + h][j + h][k - h]$ or $f[i][j + k - h][h] \land f[i + h][j][k - h]$ is true, then $f[i][j][k]$ is also true. - -Finally, we return $f[0][0][n]$. - -The time complexity is $O(n^4)$, and the space complexity is $O(n^3)$. Where $n$ is the length of the string. - -### **Python3** - ```python class Solution: def isScramble(self, s1: str, s2: str) -> bool: @@ -109,29 +95,6 @@ class Solution: return dfs(0, 0, len(s1)) ``` -```python -class Solution: - def isScramble(self, s1: str, s2: str) -> bool: - n = len(s1) - f = [[[False] * (n + 1) for _ in range(n)] for _ in range(n)] - for i in range(n): - for j in range(n): - f[i][j][1] = s1[i] == s2[j] - for k in range(2, n + 1): - for i in range(n - k + 1): - for j in range(n - k + 1): - for h in range(1, k): - if f[i][j][h] and f[i + h][j + h][k - h]: - f[i][j][k] = True - break - if f[i + h][j][k - h] and f[i][j + k - h][h]: - f[i][j][k] = True - break - return f[0][0][n] -``` - -### **Java** - ```java class Solution { private Boolean[][][] f; @@ -166,39 +129,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isScramble(String s1, String s2) { - int n = s1.length(); - boolean[][][] f = new boolean[n][n][n + 1]; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - f[i][j][1] = s1.charAt(i) == s2.charAt(j); - } - } - for (int k = 2; k <= n; ++k) { - for (int i = 0; i <= n - k; ++i) { - for (int j = 0; j <= n - k; ++j) { - for (int h = 1; h < k; ++h) { - if (f[i][j][h] && f[i + h][j + h][k - h]) { - f[i][j][k] = true; - break; - } - if (f[i + h][j][k - h] && f[i][j + k - h][h]) { - f[i][j][k] = true; - break; - } - } - } - } - } - return f[0][0][n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -228,41 +158,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool isScramble(string s1, string s2) { - int n = s1.length(); - bool f[n][n][n + 1]; - memset(f, false, sizeof(f)); - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - f[i][j][1] = s1[i] == s2[j]; - } - } - for (int k = 2; k <= n; ++k) { - for (int i = 0; i <= n - k; ++i) { - for (int j = 0; j <= n - k; ++j) { - for (int h = 1; h < k; ++h) { - if (f[i][j][h] && f[i + h][j + h][k - h]) { - f[i][j][k] = true; - break; - } - if (f[i + h][j][k - h] && f[i][j + k - h][h]) { - f[i][j][k] = true; - break; - } - } - } - } - } - return f[0][0][n]; - } -}; -``` - -### **Go** - ```go func isScramble(s1 string, s2 string) bool { n := len(s1) @@ -294,35 +189,6 @@ func isScramble(s1 string, s2 string) bool { } ``` -```go -func isScramble(s1 string, s2 string) bool { - n := len(s1) - f := make([][][]bool, n) - for i := range f { - f[i] = make([][]bool, n) - for j := 0; j < n; j++ { - f[i][j] = make([]bool, n+1) - f[i][j][1] = s1[i] == s2[j] - } - } - for k := 2; k <= n; k++ { - for i := 0; i <= n-k; i++ { - for j := 0; j <= n-k; j++ { - for h := 1; h < k; h++ { - if (f[i][j][h] && f[i+h][j+h][k-h]) || (f[i+h][j][k-h] && f[i][j+k-h][h]) { - f[i][j][k] = true - break - } - } - } - } - } - return f[0][0][n] -} -``` - -### **TypeScript** - ```ts function isScramble(s1: string, s2: string): boolean { const n = s1.length; @@ -350,39 +216,6 @@ function isScramble(s1: string, s2: string): boolean { } ``` -```ts -function isScramble(s1: string, s2: string): boolean { - const n = s1.length; - const f = new Array(n) - .fill(0) - .map(() => new Array(n).fill(0).map(() => new Array(n + 1).fill(false))); - for (let i = 0; i < n; ++i) { - for (let j = 0; j < n; ++j) { - f[i][j][1] = s1[i] === s2[j]; - } - } - for (let k = 2; k <= n; ++k) { - for (let i = 0; i <= n - k; ++i) { - for (let j = 0; j <= n - k; ++j) { - for (let h = 1; h < k; ++h) { - if (f[i][j][h] && f[i + h][j + h][k - h]) { - f[i][j][k] = true; - break; - } - if (f[i + h][j][k - h] && f[i][j + k - h][h]) { - f[i][j][k] = true; - break; - } - } - } - } - } - return f[0][0][n]; -} -``` - -### **C#** - ```cs public class Solution { private string s1; @@ -420,6 +253,165 @@ public class Solution { } ``` + + +### Solution 2: Dynamic Programming (Interval DP) + +We define $f[i][j][k]$ as whether the substring of length $k$ starting from $i$ of string $s_1$ can be transformed into the substring of length $k$ starting from $j$ of string $s_2$. Then the answer is $f[0][0][n]$, where $n$ is the length of the string. + +For substring of length $1$, if $s_1[i] = s_2[j]$, then $f[i][j][1] = true$, otherwise $f[i][j][1] = false$. + +Next, we enumerate the length $k$ of the substring from small to large, and enumerate $i$ from $0$, and enumerate $j$ from $0$. If $f[i][j][h] \land f[i + h][j + h][k - h]$ or $f[i][j + k - h][h] \land f[i + h][j][k - h]$ is true, then $f[i][j][k]$ is also true. + +Finally, we return $f[0][0][n]$. + +The time complexity is $O(n^4)$, and the space complexity is $O(n^3)$. Where $n$ is the length of the string. + + + +```python +class Solution: + def isScramble(self, s1: str, s2: str) -> bool: + n = len(s1) + f = [[[False] * (n + 1) for _ in range(n)] for _ in range(n)] + for i in range(n): + for j in range(n): + f[i][j][1] = s1[i] == s2[j] + for k in range(2, n + 1): + for i in range(n - k + 1): + for j in range(n - k + 1): + for h in range(1, k): + if f[i][j][h] and f[i + h][j + h][k - h]: + f[i][j][k] = True + break + if f[i + h][j][k - h] and f[i][j + k - h][h]: + f[i][j][k] = True + break + return f[0][0][n] +``` + +```java +class Solution { + public boolean isScramble(String s1, String s2) { + int n = s1.length(); + boolean[][][] f = new boolean[n][n][n + 1]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + f[i][j][1] = s1.charAt(i) == s2.charAt(j); + } + } + for (int k = 2; k <= n; ++k) { + for (int i = 0; i <= n - k; ++i) { + for (int j = 0; j <= n - k; ++j) { + for (int h = 1; h < k; ++h) { + if (f[i][j][h] && f[i + h][j + h][k - h]) { + f[i][j][k] = true; + break; + } + if (f[i + h][j][k - h] && f[i][j + k - h][h]) { + f[i][j][k] = true; + break; + } + } + } + } + } + return f[0][0][n]; + } +} +``` + +```cpp +class Solution { +public: + bool isScramble(string s1, string s2) { + int n = s1.length(); + bool f[n][n][n + 1]; + memset(f, false, sizeof(f)); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + f[i][j][1] = s1[i] == s2[j]; + } + } + for (int k = 2; k <= n; ++k) { + for (int i = 0; i <= n - k; ++i) { + for (int j = 0; j <= n - k; ++j) { + for (int h = 1; h < k; ++h) { + if () { + f[i][j][k] = true; + break; + } + if (f[i + h][j][k - h] && f[i][j + k - h][h]) { + f[i][j][k] = true; + break; + } + } + } + } + } + return f[0][0][n]; + } +}; +``` + +```go +func isScramble(s1 string, s2 string) bool { + n := len(s1) + f := make([][][]bool, n) + for i := range f { + f[i] = make([][]bool, n) + for j := 0; j < n; j++ { + f[i][j] = make([]bool, n+1) + f[i][j][1] = s1[i] == s2[j] + } + } + for k := 2; k <= n; k++ { + for i := 0; i <= n-k; i++ { + for j := 0; j <= n-k; j++ { + for h := 1; h < k; h++ { + if (f[i][j][h] && f[i+h][j+h][k-h]) || (f[i+h][j][k-h] && f[i][j+k-h][h]) { + f[i][j][k] = true + break + } + } + } + } + } + return f[0][0][n] +} +``` + +```ts +function isScramble(s1: string, s2: string): boolean { + const n = s1.length; + const f = new Array(n) + .fill(0) + .map(() => new Array(n).fill(0).map(() => new Array(n + 1).fill(false))); + for (let i = 0; i < n; ++i) { + for (let j = 0; j < n; ++j) { + f[i][j][1] = s1[i] === s2[j]; + } + } + for (let k = 2; k <= n; ++k) { + for (let i = 0; i <= n - k; ++i) { + for (let j = 0; j <= n - k; ++j) { + for (let h = 1; h < k; ++h) { + if (f[i][j][h] && f[i + h][j + h][k - h]) { + f[i][j][k] = true; + break; + } + if (f[i + h][j][k - h] && f[i][j + k - h][h]) { + f[i][j][k] = true; + break; + } + } + } + } + } + return f[0][0][n]; +} +``` + ```cs public class Solution { public bool IsScramble(string s1, string s2) { @@ -451,10 +443,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0088.Merge Sorted Array/README.md b/solution/0000-0099/0088.Merge Sorted Array/README.md index 6b98ab68353f8..c3c09dc90630f 100644 --- a/solution/0000-0099/0088.Merge Sorted Array/README.md +++ b/solution/0000-0099/0088.Merge Sorted Array/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们注意到数组的有序性,可以使用双指针的方法,从后向前遍历两个数组,每次取两个数组中较大的一个放进合并后的数组的最后面。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: @@ -91,10 +85,6 @@ class Solution: k -= 1 ``` -### **Java** - - - ```java class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func merge(nums1 []int, m int, nums2 []int, n int) { for i, j, k := m-1, n-1, m+n-1; j >= 0; k-- { @@ -134,8 +120,6 @@ func merge(nums1 []int, m int, nums2 []int, n int) { } ``` -### **TypeScript** - ```ts /** Do not return anything, modify nums1 in-place instead. @@ -147,37 +131,6 @@ function merge(nums1: number[], m: number, nums2: number[], n: number): void { } ``` -```ts -/** - Do not return anything, modify nums1 in-place instead. - */ -function merge(nums1: number[], m: number, nums2: number[], n: number): void { - nums1.length = m; - nums2.length = n; - nums1.push(...nums2); - nums1.sort((a, b) => a - b); -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} nums1 - * @param {number} m - * @param {number[]} nums2 - * @param {number} n - * @return {void} Do not return anything, modify nums1 in-place instead. - */ -var merge = function (nums1, m, nums2, n) { - for (let i = m - 1, j = n - 1, k = m + n - 1; j >= 0; --k) { - nums1[k] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]; - } -}; -``` - -### **Rust** - ```rust impl Solution { pub fn merge(nums1: &mut Vec, m: i32, nums2: &mut Vec, n: i32) { @@ -207,7 +160,20 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {number[]} nums1 + * @param {number} m + * @param {number[]} nums2 + * @param {number} n + * @return {void} Do not return anything, modify nums1 in-place instead. + */ +var merge = function (nums1, m, nums2, n) { + for (let i = m - 1, j = n - 1, k = m + n - 1; j >= 0; --k) { + nums1[k] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]; + } +}; +``` ```php class Solution { @@ -230,10 +196,24 @@ class Solution { } ``` -### **...** + + +### 方法二 -``` + +```ts +/** + Do not return anything, modify nums1 in-place instead. + */ +function merge(nums1: number[], m: number, nums2: number[], n: number): void { + nums1.length = m; + nums2.length = n; + nums1.push(...nums2); + nums1.sort((a, b) => a - b); +} ``` + + diff --git a/solution/0000-0099/0088.Merge Sorted Array/README_EN.md b/solution/0000-0099/0088.Merge Sorted Array/README_EN.md index 5cf3d5cdb73d5..e15af0f9dc54f 100644 --- a/solution/0000-0099/0088.Merge Sorted Array/README_EN.md +++ b/solution/0000-0099/0088.Merge Sorted Array/README_EN.md @@ -55,7 +55,7 @@ Note that because m = 0, there are no elements in nums1. The 0 is only there to ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We use two pointers $i$ and $j$ pointing to the end of two arrays, and a pointer $k$ pointing to the end of the merged array. @@ -65,8 +65,6 @@ The time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of two arra -### **Python3** - ```python class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: @@ -82,8 +80,6 @@ class Solution: k -= 1 ``` -### **Java** - ```java class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +101,6 @@ public: }; ``` -### **Go** - ```go func merge(nums1 []int, m int, nums2 []int, n int) { for i, j, k := m-1, n-1, m+n-1; j >= 0; k-- { @@ -123,8 +115,6 @@ func merge(nums1 []int, m int, nums2 []int, n int) { } ``` -### **TypeScript** - ```ts /** Do not return anything, modify nums1 in-place instead. @@ -136,37 +126,6 @@ function merge(nums1: number[], m: number, nums2: number[], n: number): void { } ``` -```ts -/** - Do not return anything, modify nums1 in-place instead. - */ -function merge(nums1: number[], m: number, nums2: number[], n: number): void { - nums1.length = m; - nums2.length = n; - nums1.push(...nums2); - nums1.sort((a, b) => a - b); -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} nums1 - * @param {number} m - * @param {number[]} nums2 - * @param {number} n - * @return {void} Do not return anything, modify nums1 in-place instead. - */ -var merge = function (nums1, m, nums2, n) { - for (let i = m - 1, j = n - 1, k = m + n - 1; j >= 0; --k) { - nums1[k] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]; - } -}; -``` - -### **Rust** - ```rust impl Solution { pub fn merge(nums1: &mut Vec, m: i32, nums2: &mut Vec, n: i32) { @@ -196,7 +155,20 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {number[]} nums1 + * @param {number} m + * @param {number[]} nums2 + * @param {number} n + * @return {void} Do not return anything, modify nums1 in-place instead. + */ +var merge = function (nums1, m, nums2, n) { + for (let i = m - 1, j = n - 1, k = m + n - 1; j >= 0; --k) { + nums1[k] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]; + } +}; +``` ```php class Solution { @@ -219,10 +191,24 @@ class Solution { } ``` -### **...** + -``` +### Solution 2 + + +```ts +/** + Do not return anything, modify nums1 in-place instead. + */ +function merge(nums1: number[], m: number, nums2: number[], n: number): void { + nums1.length = m; + nums2.length = n; + nums1.push(...nums2); + nums1.sort((a, b) => a - b); +} ``` + + diff --git a/solution/0000-0099/0089.Gray Code/README.md b/solution/0000-0099/0089.Gray Code/README.md index afe5482da3474..27524e99cf06b 100644 --- a/solution/0000-0099/0089.Gray Code/README.md +++ b/solution/0000-0099/0089.Gray Code/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:二进制码转格雷码** +### 方法一:二进制码转格雷码 格雷码是我们在工程中常会遇到的一种编码方式,它的基本的特点就是任意两个相邻的代码只有一位二进制数不同。 @@ -79,20 +77,12 @@ int gray(x) { -### **Python3** - - - ```python class Solution: def grayCode(self, n: int) -> List[int]: return [i ^ (i >> 1) for i in range(1 << n)] ``` -### **Java** - - - ```java class Solution { public List grayCode(int n) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func grayCode(n int) (ans []int) { for i := 0; i < 1< + + diff --git a/solution/0000-0099/0089.Gray Code/README_EN.md b/solution/0000-0099/0089.Gray Code/README_EN.md index abe208e58b443..3e85e9a814ff4 100644 --- a/solution/0000-0099/0089.Gray Code/README_EN.md +++ b/solution/0000-0099/0089.Gray Code/README_EN.md @@ -51,7 +51,7 @@ The binary representation of [0,1,3,2] is [00,01,11,10]. ## Solutions -**Solution 1: Binary to Gray Code Conversion** +### Solution 1: Binary to Gray Code Conversion Gray code is a type of encoding method that we often encounter in engineering. Its basic feature is that only one bit of binary number is different between any two adjacent codes. @@ -73,16 +73,12 @@ The time complexity is $O(2^n)$, where $n$ is the integer given in the problem. -### **Python3** - ```python class Solution: def grayCode(self, n: int) -> List[int]: return [i ^ (i >> 1) for i in range(1 << n)] ``` -### **Java** - ```java class Solution { public List grayCode(int n) { @@ -95,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func grayCode(n int) (ans []int) { for i := 0; i < 1< + + diff --git a/solution/0000-0099/0090.Subsets II/README.md b/solution/0000-0099/0090.Subsets II/README.md index abc5ddc3de256..a852b90784728 100644 --- a/solution/0000-0099/0090.Subsets II/README.md +++ b/solution/0000-0099/0090.Subsets II/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:排序 + DFS** +### 方法一:排序 + DFS 我们可以先对数组 $nums$ 进行排序,方便去重。 @@ -57,22 +55,8 @@ 时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(n)$。其中 $n$ 是数组的长度。 -**方法二:排序 + 二进制枚举** - -与方法一类似,我们先对数组 $nums$ 进行排序,方便去重。 - -接下来,我们在 $[0, 2^n)$ 的范围内枚举一个二进制数 $mask$,其中 $mask$ 的二进制表示是一个 $n$ 位的位串,如果 $mask$ 的第 $i$ 位为 $1$,表示选择 $nums[i]$,为 $0$ 表示不选择 $nums[i]$。注意,如果 $mask$ 的 $i - 1$ 位为 $0$,且 $nums[i] = nums[i - 1]$,则说明在当前枚举到的方案中,第 $i$ 个元素和第 $i - 1$ 个元素相同,为了避免重复,我们跳过这种情况。否则,我们将 $mask$ 对应的子集加入答案数组中。 - -枚举结束后,我们返回答案数组即可。 - -时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(n)$。其中 $n$ 是数组的长度。 - -### **Python3** - - - ```python class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: @@ -94,30 +78,6 @@ class Solution: return ans ``` -```python -class Solution: - def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: - nums.sort() - n = len(nums) - ans = [] - for mask in range(1 << n): - ok = True - t = [] - for i in range(n): - if mask >> i & 1: - if i and (mask >> (i - 1) & 1) == 0 and nums[i] == nums[i - 1]: - ok = False - break - t.append(nums[i]) - if ok: - ans.append(t) - return ans -``` - -### **Java** - - - ```java class Solution { private List> ans = new ArrayList<>(); @@ -147,35 +107,6 @@ class Solution { } ``` -```java -class Solution { - public List> subsetsWithDup(int[] nums) { - Arrays.sort(nums); - int n = nums.length; - List> ans = new ArrayList<>(); - for (int mask = 0; mask < 1 << n; ++mask) { - List t = new ArrayList<>(); - boolean ok = true; - for (int i = 0; i < n; ++i) { - if ((mask >> i & 1) == 1) { - if (i > 0 && (mask >> (i - 1) & 1) == 0 && nums[i] == nums[i - 1]) { - ok = false; - break; - } - t.add(nums[i]); - } - } - if (ok) { - ans.add(t); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -203,36 +134,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector> subsetsWithDup(vector& nums) { - sort(nums.begin(), nums.end()); - int n = nums.size(); - vector> ans; - for (int mask = 0; mask < 1 << n; ++mask) { - vector t; - bool ok = true; - for (int i = 0; i < n; ++i) { - if ((mask >> i & 1) == 1) { - if (i > 0 && (mask >> (i - 1) & 1) == 0 && nums[i] == nums[i - 1]) { - ok = false; - break; - } - t.push_back(nums[i]); - } - } - if (ok) { - ans.push_back(t); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func subsetsWithDup(nums []int) (ans [][]int) { sort.Ints(nums) @@ -257,32 +158,6 @@ func subsetsWithDup(nums []int) (ans [][]int) { } ``` -```go -func subsetsWithDup(nums []int) (ans [][]int) { - sort.Ints(nums) - n := len(nums) - for mask := 0; mask < 1<>i&1 == 1 { - if i > 0 && mask>>(i-1)&1 == 0 && nums[i] == nums[i-1] { - ok = false - break - } - t = append(t, nums[i]) - } - } - if ok { - ans = append(ans, t) - } - } - return -} -``` - -### **TypeScript** - ```ts function subsetsWithDup(nums: number[]): number[][] { nums.sort((a, b) => a - b); @@ -307,33 +182,6 @@ function subsetsWithDup(nums: number[]): number[][] { } ``` -```ts -function subsetsWithDup(nums: number[]): number[][] { - nums.sort((a, b) => a - b); - const n = nums.length; - const ans: number[][] = []; - for (let mask = 0; mask < 1 << n; ++mask) { - const t: number[] = []; - let ok: boolean = true; - for (let i = 0; i < n; ++i) { - if (((mask >> i) & 1) === 1) { - if (i && ((mask >> (i - 1)) & 1) === 0 && nums[i] === nums[i - 1]) { - ok = false; - break; - } - t.push(nums[i]); - } - } - if (ok) { - ans.push(t); - } - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn subsets_with_dup(nums: Vec) -> Vec> { @@ -363,6 +211,144 @@ impl Solution { } ``` + + +### 方法二:排序 + 二进制枚举 + +与方法一类似,我们先对数组 $nums$ 进行排序,方便去重。 + +接下来,我们在 $[0, 2^n)$ 的范围内枚举一个二进制数 $mask$,其中 $mask$ 的二进制表示是一个 $n$ 位的位串,如果 $mask$ 的第 $i$ 位为 $1$,表示选择 $nums[i]$,为 $0$ 表示不选择 $nums[i]$。注意,如果 $mask$ 的 $i - 1$ 位为 $0$,且 $nums[i] = nums[i - 1]$,则说明在当前枚举到的方案中,第 $i$ 个元素和第 $i - 1$ 个元素相同,为了避免重复,我们跳过这种情况。否则,我们将 $mask$ 对应的子集加入答案数组中。 + +枚举结束后,我们返回答案数组即可。 + +时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(n)$。其中 $n$ 是数组的长度。 + + + +```python +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: + nums.sort() + n = len(nums) + ans = [] + for mask in range(1 << n): + ok = True + t = [] + for i in range(n): + if mask >> i & 1: + if i and (mask >> (i - 1) & 1) == 0 and nums[i] == nums[i - 1]: + ok = False + break + t.append(nums[i]) + if ok: + ans.append(t) + return ans +``` + +```java +class Solution { + public List> subsetsWithDup(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + List> ans = new ArrayList<>(); + for (int mask = 0; mask < 1 << n; ++mask) { + List t = new ArrayList<>(); + boolean ok = true; + for (int i = 0; i < n; ++i) { + if ((mask >> i & 1) == 1) { + if (i > 0 && (mask >> (i - 1) & 1) == 0 && nums[i] == nums[i - 1]) { + ok = false; + break; + } + t.add(nums[i]); + } + } + if (ok) { + ans.add(t); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector> subsetsWithDup(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + vector> ans; + for (int mask = 0; mask < 1 << n; ++mask) { + vector t; + bool ok = true; + for (int i = 0; i < n; ++i) { + if ((mask >> i & 1) == 1) { + if (i > 0 && (mask >> (i - 1) & 1) == 0 && nums[i] == nums[i - 1]) { + ok = false; + break; + } + t.push_back(nums[i]); + } + } + if (ok) { + ans.push_back(t); + } + } + return ans; + } +}; +``` + +```go +func subsetsWithDup(nums []int) (ans [][]int) { + sort.Ints(nums) + n := len(nums) + for mask := 0; mask < 1<>i&1 == 1 { + if i > 0 && mask>>(i-1)&1 == 0 && nums[i] == nums[i-1] { + ok = false + break + } + t = append(t, nums[i]) + } + } + if ok { + ans = append(ans, t) + } + } + return +} +``` + +```ts +function subsetsWithDup(nums: number[]): number[][] { + nums.sort((a, b) => a - b); + const n = nums.length; + const ans: number[][] = []; + for (let mask = 0; mask < 1 << n; ++mask) { + const t: number[] = []; + let ok: boolean = true; + for (let i = 0; i < n; ++i) { + if (((mask >> i) & 1) === 1) { + if (i && ((mask >> (i - 1)) & 1) === 0 && nums[i] === nums[i - 1]) { + ok = false; + break; + } + t.push(nums[i]); + } + } + if (ok) { + ans.push(t); + } + } + return ans; +} +``` + ```rust impl Solution { pub fn subsets_with_dup(nums: Vec) -> Vec> { @@ -391,10 +377,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0090.Subsets II/README_EN.md b/solution/0000-0099/0090.Subsets II/README_EN.md index fcf2dbcd52cc9..c345f93e8bbed 100644 --- a/solution/0000-0099/0090.Subsets II/README_EN.md +++ b/solution/0000-0099/0090.Subsets II/README_EN.md @@ -26,7 +26,7 @@ ## Solutions -**Solution 1: Sorting + DFS** +### Solution 1: Sorting + DFS We can first sort the array $nums$ to facilitate deduplication. @@ -40,20 +40,8 @@ Finally, we only need to call $dfs(0)$ and return the answer 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. -**Solution 2: Sorting + Binary Enumeration** - -Similar to Solution 1, we first sort the array $nums$ to facilitate deduplication. - -Next, we enumerate a binary number $mask$ in the range of $[0, 2^n)$, where the binary representation of $mask$ is an $n$-bit bit string. If the $i$-th bit of $mask$ is $1$, it means to select $nums[i]$, and $0$ means not to select $nums[i]$. Note that if the $i - 1$ bit of $mask$ is $0$, and $nums[i] = nums[i - 1]$, it means that in the current enumerated scheme, the $i$-th element and the $i - 1$-th element are the same. To avoid repetition, we skip this situation. Otherwise, we add the subset corresponding to $mask$ to the answer array. - -After the enumeration ends, we return the answer 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. - -### **Python3** - ```python class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: @@ -75,28 +63,6 @@ class Solution: return ans ``` -```python -class Solution: - def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: - nums.sort() - n = len(nums) - ans = [] - for mask in range(1 << n): - ok = True - t = [] - for i in range(n): - if mask >> i & 1: - if i and (mask >> (i - 1) & 1) == 0 and nums[i] == nums[i - 1]: - ok = False - break - t.append(nums[i]) - if ok: - ans.append(t) - return ans -``` - -### **Java** - ```java class Solution { private List> ans = new ArrayList<>(); @@ -126,35 +92,6 @@ class Solution { } ``` -```java -class Solution { - public List> subsetsWithDup(int[] nums) { - Arrays.sort(nums); - int n = nums.length; - List> ans = new ArrayList<>(); - for (int mask = 0; mask < 1 << n; ++mask) { - List t = new ArrayList<>(); - boolean ok = true; - for (int i = 0; i < n; ++i) { - if ((mask >> i & 1) == 1) { - if (i > 0 && (mask >> (i - 1) & 1) == 0 && nums[i] == nums[i - 1]) { - ok = false; - break; - } - t.add(nums[i]); - } - } - if (ok) { - ans.add(t); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -182,36 +119,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector> subsetsWithDup(vector& nums) { - sort(nums.begin(), nums.end()); - int n = nums.size(); - vector> ans; - for (int mask = 0; mask < 1 << n; ++mask) { - vector t; - bool ok = true; - for (int i = 0; i < n; ++i) { - if ((mask >> i & 1) == 1) { - if (i > 0 && (mask >> (i - 1) & 1) == 0 && nums[i] == nums[i - 1]) { - ok = false; - break; - } - t.push_back(nums[i]); - } - } - if (ok) { - ans.push_back(t); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func subsetsWithDup(nums []int) (ans [][]int) { sort.Ints(nums) @@ -236,32 +143,6 @@ func subsetsWithDup(nums []int) (ans [][]int) { } ``` -```go -func subsetsWithDup(nums []int) (ans [][]int) { - sort.Ints(nums) - n := len(nums) - for mask := 0; mask < 1<>i&1 == 1 { - if i > 0 && mask>>(i-1)&1 == 0 && nums[i] == nums[i-1] { - ok = false - break - } - t = append(t, nums[i]) - } - } - if ok { - ans = append(ans, t) - } - } - return -} -``` - -### **TypeScript** - ```ts function subsetsWithDup(nums: number[]): number[][] { nums.sort((a, b) => a - b); @@ -286,33 +167,6 @@ function subsetsWithDup(nums: number[]): number[][] { } ``` -```ts -function subsetsWithDup(nums: number[]): number[][] { - nums.sort((a, b) => a - b); - const n = nums.length; - const ans: number[][] = []; - for (let mask = 0; mask < 1 << n; ++mask) { - const t: number[] = []; - let ok: boolean = true; - for (let i = 0; i < n; ++i) { - if (((mask >> i) & 1) === 1) { - if (i && ((mask >> (i - 1)) & 1) === 0 && nums[i] === nums[i - 1]) { - ok = false; - break; - } - t.push(nums[i]); - } - } - if (ok) { - ans.push(t); - } - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn subsets_with_dup(nums: Vec) -> Vec> { @@ -342,6 +196,144 @@ impl Solution { } ``` + + +### Solution 2: Sorting + Binary Enumeration + +Similar to Solution 1, we first sort the array $nums$ to facilitate deduplication. + +Next, we enumerate a binary number $mask$ in the range of $[0, 2^n)$, where the binary representation of $mask$ is an $n$-bit bit string. If the $i$-th bit of $mask$ is $1$, it means to select $nums[i]$, and $0$ means not to select $nums[i]$. Note that if the $i - 1$ bit of $mask$ is $0$, and $nums[i] = nums[i - 1]$, it means that in the current enumerated scheme, the $i$-th element and the $i - 1$-th element are the same. To avoid repetition, we skip this situation. Otherwise, we add the subset corresponding to $mask$ to the answer array. + +After the enumeration ends, we return the answer 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. + + + +```python +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: + nums.sort() + n = len(nums) + ans = [] + for mask in range(1 << n): + ok = True + t = [] + for i in range(n): + if mask >> i & 1: + if i and (mask >> (i - 1) & 1) == 0 and nums[i] == nums[i - 1]: + ok = False + break + t.append(nums[i]) + if ok: + ans.append(t) + return ans +``` + +```java +class Solution { + public List> subsetsWithDup(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + List> ans = new ArrayList<>(); + for (int mask = 0; mask < 1 << n; ++mask) { + List t = new ArrayList<>(); + boolean ok = true; + for (int i = 0; i < n; ++i) { + if ((mask >> i & 1) == 1) { + if (i > 0 && (mask >> (i - 1) & 1) == 0 && nums[i] == nums[i - 1]) { + ok = false; + break; + } + t.add(nums[i]); + } + } + if (ok) { + ans.add(t); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector> subsetsWithDup(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + vector> ans; + for (int mask = 0; mask < 1 << n; ++mask) { + vector t; + bool ok = true; + for (int i = 0; i < n; ++i) { + if ((mask >> i & 1) == 1) { + if (i > 0 && (mask >> (i - 1) & 1) == 0 && nums[i] == nums[i - 1]) { + ok = false; + break; + } + t.push_back(nums[i]); + } + } + if (ok) { + ans.push_back(t); + } + } + return ans; + } +}; +``` + +```go +func subsetsWithDup(nums []int) (ans [][]int) { + sort.Ints(nums) + n := len(nums) + for mask := 0; mask < 1<>i&1 == 1 { + if i > 0 && mask>>(i-1)&1 == 0 && nums[i] == nums[i-1] { + ok = false + break + } + t = append(t, nums[i]) + } + } + if ok { + ans = append(ans, t) + } + } + return +} +``` + +```ts +function subsetsWithDup(nums: number[]): number[][] { + nums.sort((a, b) => a - b); + const n = nums.length; + const ans: number[][] = []; + for (let mask = 0; mask < 1 << n; ++mask) { + const t: number[] = []; + let ok: boolean = true; + for (let i = 0; i < n; ++i) { + if (((mask >> i) & 1) === 1) { + if (i && ((mask >> (i - 1)) & 1) === 0 && nums[i] === nums[i - 1]) { + ok = false; + break; + } + t.push(nums[i]); + } + } + if (ok) { + ans.push(t); + } + } + return ans; +} +``` + ```rust impl Solution { pub fn subsets_with_dup(nums: Vec) -> Vec> { @@ -370,10 +362,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0091.Decode Ways/README.md b/solution/0000-0099/0091.Decode Ways/README.md index 8ae8bdb321efe..d0844d54928f3 100644 --- a/solution/0000-0099/0091.Decode Ways/README.md +++ b/solution/0000-0099/0091.Decode Ways/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示字符串的前 $i$ 个字符的解码方法数,初始时 $f[0]=1$,其余 $f[i]=0$。 @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def numDecodings(self, s: str) -> int: @@ -98,22 +92,6 @@ class Solution: return f[n] ``` -```python -class Solution: - def numDecodings(self, s: str) -> int: - f, g = 0, 1 - for i, c in enumerate(s, 1): - h = g if c != "0" else 0 - if i > 1 and s[i - 2] != "0" and int(s[i - 2 : i]) <= 26: - h += f - f, g = g, h - return g -``` - -### **Java** - - - ```java class Solution { public int numDecodings(String s) { @@ -133,26 +111,6 @@ class Solution { } ``` -```java -class Solution { - public int numDecodings(String s) { - int n = s.length(); - int f = 0, g = 1; - for (int i = 1; i <= n; ++i) { - int h = s.charAt(i - 1) != '0' ? g : 0; - if (i > 1 && s.charAt(i - 2) != '0' && Integer.valueOf(s.substring(i - 2, i)) <= 26) { - h += f; - } - f = g; - g = h; - } - return g; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -174,27 +132,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numDecodings(string s) { - int n = s.size(); - int f = 0, g = 1; - for (int i = 1; i <= n; ++i) { - int h = s[i - 1] != '0' ? g : 0; - if (i > 1 && (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) { - h += f; - } - f = g; - g = h; - } - return g; - } -}; -``` - -### **Go** - ```go func numDecodings(s string) int { n := len(s) @@ -212,26 +149,6 @@ func numDecodings(s string) int { } ``` -```go -func numDecodings(s string) int { - n := len(s) - f, g := 0, 1 - for i := 1; i <= n; i++ { - h := 0 - if s[i-1] != '0' { - h = g - } - if i > 1 && (s[i-2] == '1' || (s[i-2] == '2' && s[i-1] <= '6')) { - h += f - } - f, g = g, h - } - return g -} -``` - -### **TypeScript** - ```ts function numDecodings(s: string): number { const n = s.length; @@ -249,23 +166,6 @@ function numDecodings(s: string): number { } ``` -```ts -function numDecodings(s: string): number { - const n = s.length; - let [f, g] = [0, 1]; - for (let i = 1; i <= n; ++i) { - let h = s[i - 1] !== '0' ? g : 0; - if (i > 1 && (s[i - 2] === '1' || (s[i - 2] === '2' && s[i - 1] <= '6'))) { - h += f; - } - [f, g] = [g, h]; - } - return g; -} -``` - -### **C#** - ```cs public class Solution { public int NumDecodings(string s) { @@ -285,10 +185,47 @@ public class Solution { } ``` -```cs -public class Solution { - public int NumDecodings(string s) { - int n = s.Length; + + +### 方法二 + + + +```python +class Solution: + def numDecodings(self, s: str) -> int: + f, g = 0, 1 + for i, c in enumerate(s, 1): + h = g if c != "0" else 0 + if i > 1 and s[i - 2] != "0" and int(s[i - 2 : i]) <= 26: + h += f + f, g = g, h + return g +``` + +```java +class Solution { + public int numDecodings(String s) { + int n = s.length(); + int f = 0, g = 1; + for (int i = 1; i <= n; ++i) { + int h = s.charAt(i - 1) != '0' ? g : 0; + if (i > 1 && s.charAt(i - 2) != '0' && Integer.valueOf(s.substring(i - 2, i)) <= 26) { + h += f; + } + f = g; + g = h; + } + return g; + } +} +``` + +```cpp +class Solution { +public: + int numDecodings(string s) { + int n = s.size(); int f = 0, g = 1; for (int i = 1; i <= n; ++i) { int h = s[i - 1] != '0' ? g : 0; @@ -300,13 +237,60 @@ public class Solution { } return g; } -} +}; ``` -### **...** +```go +func numDecodings(s string) int { + n := len(s) + f, g := 0, 1 + for i := 1; i <= n; i++ { + h := 0 + if s[i-1] != '0' { + h = g + } + if i > 1 && (s[i-2] == '1' || (s[i-2] == '2' && s[i-1] <= '6')) { + h += f + } + f, g = g, h + } + return g +} +``` +```ts +function numDecodings(s: string): number { + const n = s.length; + let [f, g] = [0, 1]; + for (let i = 1; i <= n; ++i) { + let h = s[i - 1] !== '0' ? g : 0; + if (i > 1 && (s[i - 2] === '1' || (s[i - 2] === '2' && s[i - 1] <= '6'))) { + h += f; + } + [f, g] = [g, h]; + } + return g; +} ``` +```cs +public class Solution { + public int NumDecodings(string s) { + int n = s.Length; + int f = 0, g = 1; + for (int i = 1; i <= n; ++i) { + int h = s[i - 1] != '0' ? g : 0; + if (i > 1 && (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) { + h += f; + } + f = g; + g = h; + } + return g; + } +} ``` + + diff --git a/solution/0000-0099/0091.Decode Ways/README_EN.md b/solution/0000-0099/0091.Decode Ways/README_EN.md index 433cf19e29e96..0d8ab6ac5f993 100644 --- a/solution/0000-0099/0091.Decode Ways/README_EN.md +++ b/solution/0000-0099/0091.Decode Ways/README_EN.md @@ -61,7 +61,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i]$ to represent the number of decoding methods for the first $i$ characters of the string. Initially, $f[0]=1$, and the rest $f[i]=0$. @@ -74,8 +74,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def numDecodings(self, s: str) -> int: @@ -89,20 +87,6 @@ class Solution: return f[n] ``` -```python -class Solution: - def numDecodings(self, s: str) -> int: - f, g = 0, 1 - for i, c in enumerate(s, 1): - h = g if c != "0" else 0 - if i > 1 and s[i - 2] != "0" and int(s[i - 2 : i]) <= 26: - h += f - f, g = g, h - return g -``` - -### **Java** - ```java class Solution { public int numDecodings(String s) { @@ -122,26 +106,6 @@ class Solution { } ``` -```java -class Solution { - public int numDecodings(String s) { - int n = s.length(); - int f = 0, g = 1; - for (int i = 1; i <= n; ++i) { - int h = s.charAt(i - 1) != '0' ? g : 0; - if (i > 1 && s.charAt(i - 2) != '0' && Integer.valueOf(s.substring(i - 2, i)) <= 26) { - h += f; - } - f = g; - g = h; - } - return g; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -163,27 +127,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numDecodings(string s) { - int n = s.size(); - int f = 0, g = 1; - for (int i = 1; i <= n; ++i) { - int h = s[i - 1] != '0' ? g : 0; - if (i > 1 && (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) { - h += f; - } - f = g; - g = h; - } - return g; - } -}; -``` - -### **Go** - ```go func numDecodings(s string) int { n := len(s) @@ -201,26 +144,6 @@ func numDecodings(s string) int { } ``` -```go -func numDecodings(s string) int { - n := len(s) - f, g := 0, 1 - for i := 1; i <= n; i++ { - h := 0 - if s[i-1] != '0' { - h = g - } - if i > 1 && (s[i-2] == '1' || (s[i-2] == '2' && s[i-1] <= '6')) { - h += f - } - f, g = g, h - } - return g -} -``` - -### **TypeScript** - ```ts function numDecodings(s: string): number { const n = s.length; @@ -238,23 +161,6 @@ function numDecodings(s: string): number { } ``` -```ts -function numDecodings(s: string): number { - const n = s.length; - let [f, g] = [0, 1]; - for (let i = 1; i <= n; ++i) { - let h = s[i - 1] !== '0' ? g : 0; - if (i > 1 && (s[i - 2] === '1' || (s[i - 2] === '2' && s[i - 1] <= '6'))) { - h += f; - } - [f, g] = [g, h]; - } - return g; -} -``` - -### **C#** - ```cs public class Solution { public int NumDecodings(string s) { @@ -274,10 +180,47 @@ public class Solution { } ``` -```cs -public class Solution { - public int NumDecodings(string s) { - int n = s.Length; + + +### Solution 2 + + + +```python +class Solution: + def numDecodings(self, s: str) -> int: + f, g = 0, 1 + for i, c in enumerate(s, 1): + h = g if c != "0" else 0 + if i > 1 and s[i - 2] != "0" and int(s[i - 2 : i]) <= 26: + h += f + f, g = g, h + return g +``` + +```java +class Solution { + public int numDecodings(String s) { + int n = s.length(); + int f = 0, g = 1; + for (int i = 1; i <= n; ++i) { + int h = s.charAt(i - 1) != '0' ? g : 0; + if (i > 1 && s.charAt(i - 2) != '0' && Integer.valueOf(s.substring(i - 2, i)) <= 26) { + h += f; + } + f = g; + g = h; + } + return g; + } +} +``` + +```cpp +class Solution { +public: + int numDecodings(string s) { + int n = s.size(); int f = 0, g = 1; for (int i = 1; i <= n; ++i) { int h = s[i - 1] != '0' ? g : 0; @@ -289,13 +232,60 @@ public class Solution { } return g; } -} +}; ``` -### **...** +```go +func numDecodings(s string) int { + n := len(s) + f, g := 0, 1 + for i := 1; i <= n; i++ { + h := 0 + if s[i-1] != '0' { + h = g + } + if i > 1 && (s[i-2] == '1' || (s[i-2] == '2' && s[i-1] <= '6')) { + h += f + } + f, g = g, h + } + return g +} +``` +```ts +function numDecodings(s: string): number { + const n = s.length; + let [f, g] = [0, 1]; + for (let i = 1; i <= n; ++i) { + let h = s[i - 1] !== '0' ? g : 0; + if (i > 1 && (s[i - 2] === '1' || (s[i - 2] === '2' && s[i - 1] <= '6'))) { + h += f; + } + [f, g] = [g, h]; + } + return g; +} ``` +```cs +public class Solution { + public int NumDecodings(string s) { + int n = s.Length; + int f = 0, g = 1; + for (int i = 1; i <= n; ++i) { + int h = s[i - 1] != '0' ? g : 0; + if (i > 1 && (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) { + h += f; + } + f = g; + g = h; + } + return g; + } +} ``` + + diff --git a/solution/0000-0099/0092.Reverse Linked List II/README.md b/solution/0000-0099/0092.Reverse Linked List II/README.md index 6401210567726..26ce5c8f79331 100644 --- a/solution/0000-0099/0092.Reverse Linked List II/README.md +++ b/solution/0000-0099/0092.Reverse Linked List II/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 定义一个虚拟头结点 `dummy`,指向链表的头结点 `head`,然后定义一个指针 `pre` 指向 `dummy`,从虚拟头结点开始遍历链表,遍历到第 `left` 个结点时,将 `pre` 指向该结点,然后从该结点开始遍历 `right - left + 1` 次,将遍历到的结点依次插入到 `pre` 的后面,最后返回 `dummy.next` 即可。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -82,10 +76,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -195,88 +181,6 @@ func reverseBetween(head *ListNode, left int, right int) *ListNode { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @param {number} left - * @param {number} right - * @return {ListNode} - */ -var reverseBetween = function (head, left, right) { - if (!head.next || left == right) { - return head; - } - const dummy = new ListNode(0, head); - let pre = dummy; - for (let i = 0; i < left - 1; ++i) { - pre = pre.next; - } - const p = pre; - const q = pre.next; - let cur = q; - for (let i = 0; i < right - left + 1; ++i) { - const t = cur.next; - cur.next = pre; - pre = cur; - cur = t; - } - p.next = pre; - q.next = cur; - return dummy.next; -}; -``` - -### **C#** - -```cs -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public ListNode ReverseBetween(ListNode head, int left, int right) { - if (head.next == null || left == right) { - return head; - } - ListNode dummy = new ListNode(0, head); - ListNode pre = dummy; - for (int i = 0; i < left - 1; ++i) { - pre = pre.next; - } - ListNode p = pre; - ListNode q = pre.next; - ListNode cur = q; - for (int i = 0; i < right - left + 1; ++i) { - ListNode t = cur.next; - cur.next = pre; - pre = cur; - cur = t; - } - p.next = pre; - q.next = cur; - return dummy.next; - } -} -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -317,8 +221,6 @@ function reverseBetween(head: ListNode | null, left: number, right: number): Lis } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -363,10 +265,82 @@ impl Solution { } ``` -### **...** - +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} left + * @param {number} right + * @return {ListNode} + */ +var reverseBetween = function (head, left, right) { + if (!head.next || left == right) { + return head; + } + const dummy = new ListNode(0, head); + let pre = dummy; + for (let i = 0; i < left - 1; ++i) { + pre = pre.next; + } + const p = pre; + const q = pre.next; + let cur = q; + for (let i = 0; i < right - left + 1; ++i) { + const t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + p.next = pre; + q.next = cur; + return dummy.next; +}; ``` +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode ReverseBetween(ListNode head, int left, int right) { + if (head.next == null || left == right) { + return head; + } + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy; + for (int i = 0; i < left - 1; ++i) { + pre = pre.next; + } + ListNode p = pre; + ListNode q = pre.next; + ListNode cur = q; + for (int i = 0; i < right - left + 1; ++i) { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + p.next = pre; + q.next = cur; + return dummy.next; + } +} ``` + + diff --git a/solution/0000-0099/0092.Reverse Linked List II/README_EN.md b/solution/0000-0099/0092.Reverse Linked List II/README_EN.md index 3ec559c047625..dc118323d8af9 100644 --- a/solution/0000-0099/0092.Reverse Linked List II/README_EN.md +++ b/solution/0000-0099/0092.Reverse Linked List II/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation Define a dummy head node `dummy`, pointing to the head node `head` of the linked list. Then define a pointer `pre` pointing to `dummy`. Start traversing the linked list from the dummy head node. When you traverse to the `left` node, point `pre` to this node. Then start traversing `right - left + 1` times from this node, and insert the nodes you traverse into the back of `pre`. Finally, return `dummy.next`. @@ -44,8 +44,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -73,8 +71,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -151,8 +145,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -184,88 +176,6 @@ func reverseBetween(head *ListNode, left int, right int) *ListNode { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @param {number} left - * @param {number} right - * @return {ListNode} - */ -var reverseBetween = function (head, left, right) { - if (!head.next || left == right) { - return head; - } - const dummy = new ListNode(0, head); - let pre = dummy; - for (let i = 0; i < left - 1; ++i) { - pre = pre.next; - } - const p = pre; - const q = pre.next; - let cur = q; - for (let i = 0; i < right - left + 1; ++i) { - const t = cur.next; - cur.next = pre; - pre = cur; - cur = t; - } - p.next = pre; - q.next = cur; - return dummy.next; -}; -``` - -### **C#** - -```cs -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public ListNode ReverseBetween(ListNode head, int left, int right) { - if (head.next == null || left == right) { - return head; - } - ListNode dummy = new ListNode(0, head); - ListNode pre = dummy; - for (int i = 0; i < left - 1; ++i) { - pre = pre.next; - } - ListNode p = pre; - ListNode q = pre.next; - ListNode cur = q; - for (int i = 0; i < right - left + 1; ++i) { - ListNode t = cur.next; - cur.next = pre; - pre = cur; - cur = t; - } - p.next = pre; - q.next = cur; - return dummy.next; - } -} -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -306,8 +216,6 @@ function reverseBetween(head: ListNode | null, left: number, right: number): Lis } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -352,10 +260,82 @@ impl Solution { } ``` -### **...** - +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} left + * @param {number} right + * @return {ListNode} + */ +var reverseBetween = function (head, left, right) { + if (!head.next || left == right) { + return head; + } + const dummy = new ListNode(0, head); + let pre = dummy; + for (let i = 0; i < left - 1; ++i) { + pre = pre.next; + } + const p = pre; + const q = pre.next; + let cur = q; + for (let i = 0; i < right - left + 1; ++i) { + const t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + p.next = pre; + q.next = cur; + return dummy.next; +}; ``` +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode ReverseBetween(ListNode head, int left, int right) { + if (head.next == null || left == right) { + return head; + } + ListNode dummy = new ListNode(0, head); + ListNode pre = dummy; + for (int i = 0; i < left - 1; ++i) { + pre = pre.next; + } + ListNode p = pre; + ListNode q = pre.next; + ListNode cur = q; + for (int i = 0; i < right - left + 1; ++i) { + ListNode t = cur.next; + cur.next = pre; + pre = cur; + cur = t; + } + p.next = pre; + q.next = cur; + return dummy.next; + } +} ``` + + diff --git a/solution/0000-0099/0093.Restore IP Addresses/README.md b/solution/0000-0099/0093.Restore IP Addresses/README.md index 11d93bb022a92..359ba3da32032 100644 --- a/solution/0000-0099/0093.Restore IP Addresses/README.md +++ b/solution/0000-0099/0093.Restore IP Addresses/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们定义一个函数 $dfs(i)$,表示从字符串 $s$ 的第 $i$ 位开始,搜索能够组成的 IP 地址列表。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def restoreIpAddresses(self, s: str) -> List[str]: @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int n; @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go func restoreIpAddresses(s string) (ans []string) { n := len(s) @@ -200,8 +186,6 @@ func restoreIpAddresses(s string) (ans []string) { } ``` -### **TypeScript** - ```ts function restoreIpAddresses(s: string): string[] { const n = s.length; @@ -231,8 +215,6 @@ function restoreIpAddresses(s: string): string[] { } ``` -### **C#** - ```cs public class Solution { private IList ans = new List(); @@ -269,10 +251,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0093.Restore IP Addresses/README_EN.md b/solution/0000-0099/0093.Restore IP Addresses/README_EN.md index c5d9d946913d1..e5a710cc136a0 100644 --- a/solution/0000-0099/0093.Restore IP Addresses/README_EN.md +++ b/solution/0000-0099/0093.Restore IP Addresses/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We define a function $dfs(i)$, which represents the list of IP addresses that can be formed starting from the $i$th position of string $s$. @@ -58,8 +58,6 @@ The time complexity is $O(n \times 3^4)$, and the space complexity is $O(n)$. He -### **Python3** - ```python class Solution: def restoreIpAddresses(self, s: str) -> List[str]: @@ -87,8 +85,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int n; @@ -125,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +153,6 @@ public: }; ``` -### **Go** - ```go func restoreIpAddresses(s string) (ans []string) { n := len(s) @@ -190,8 +182,6 @@ func restoreIpAddresses(s string) (ans []string) { } ``` -### **TypeScript** - ```ts function restoreIpAddresses(s: string): string[] { const n = s.length; @@ -221,8 +211,6 @@ function restoreIpAddresses(s: string): string[] { } ``` -### **C#** - ```cs public class Solution { private IList ans = new List(); @@ -259,10 +247,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0094.Binary Tree Inorder Traversal/README.md b/solution/0000-0099/0094.Binary Tree Inorder Traversal/README.md index ac3f01820c745..a9afff4b46c45 100644 --- a/solution/0000-0099/0094.Binary Tree Inorder Traversal/README.md +++ b/solution/0000-0099/0094.Binary Tree Inorder Traversal/README.md @@ -46,47 +46,14 @@ ## 解法 - - -**方法一:递归遍历** +### 方法一:递归遍历 我们先递归左子树,再访问根节点,接着递归右子树。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数,空间复杂度主要取决于递归调用的栈空间。 -**方法二:栈实现非递归遍历** - -非递归的思路如下: - -1. 定义一个栈 stk -2. 将树的左节点依次入栈 -3. 左节点为空时,弹出栈顶元素并处理 -4. 重复 2-3 的操作 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数,空间复杂度主要取决于栈空间。 - -**方法三:Morris 实现中序遍历** - -Morris 遍历无需使用栈,空间复杂度为 $O(1)$。核心思想是: - -遍历二叉树节点, - -1. 若当前节点 root 的左子树为空,**将当前节点值添加至结果列表 ans** 中,并将当前节点更新为 `root.right` -2. 若当前节点 root 的左子树不为空,找到左子树的最右节点 prev(也即是 root 节点在中序遍历下的前驱节点): - - 若前驱节点 prev 的右子树为空,将前驱节点的右子树指向当前节点 root,并将当前节点更新为 `root.left`。 - - 若前驱节点 prev 的右子树不为空,**将当前节点值添加至结果列表 ans** 中,然后将前驱节点右子树指向空(即解除 prev 与 root 的指向关系),并将当前节点更新为 `root.right`。 -3. 循环以上步骤,直至二叉树节点为空,遍历结束。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是二叉树的节点数。 - -### **Python3** - - - -递归: - ```python # Definition for a binary tree node. # class TreeNode: @@ -109,65 +76,6 @@ class Solution: return ans ``` -栈实现非递归: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: - ans, stk = [], [] - while root or stk: - if root: - stk.append(root) - root = root.left - else: - root = stk.pop() - ans.append(root.val) - root = root.right - return ans -``` - -Morris 遍历: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: - ans = [] - while root: - if root.left is None: - ans.append(root.val) - root = root.right - else: - prev = root.left - while prev.right and prev.right != root: - prev = prev.right - if prev.right is None: - prev.right = root - root = root.left - else: - ans.append(root.val) - prev.right = None - root = root.right - return ans -``` - -### **Java** - - - -递归: - ```java /** * Definition for a binary tree node. @@ -204,91 +112,142 @@ class Solution { } ``` -栈实现非递归: - -```java +```cpp /** * Definition for a binary tree node. - * public class TreeNode { + * struct TreeNode { * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; */ class Solution { - public List inorderTraversal(TreeNode root) { - List ans = new ArrayList<>(); - Deque stk = new ArrayDeque<>(); - while (root != null || !stk.isEmpty()) { - if (root != null) { - stk.push(root); - root = root.left; +public: + vector inorderTraversal(TreeNode* root) { + vector ans; + while (root) { + if (!root->left) { + ans.push_back(root->val); + root = root->right; } else { - root = stk.pop(); - ans.add(root.val); - root = root.right; + TreeNode* prev = root->left; + while (prev->right && prev->right != root) { + prev = prev->right; + } + if (!prev->right) { + prev->right = root; + root = root->left; + } else { + ans.push_back(root->val); + prev->right = nullptr; + root = root->right; + } } } return ans; } -} +}; ``` -Morris 遍历: +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func inorderTraversal(root *TreeNode) []int { + var ans []int + for root != nil { + if root.Left == nil { + ans = append(ans, root.Val) + root = root.Right + } else { + prev := root.Left + for prev.Right != nil && prev.Right != root { + prev = prev.Right + } + if prev.Right == nil { + prev.Right = root + root = root.Left + } else { + ans = append(ans, root.Val) + prev.Right = nil + root = root.Right + } + } + } + return ans +} +``` -```java +```ts /** * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; + * 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) * } * } */ -class Solution { - public List inorderTraversal(TreeNode root) { - List ans = new ArrayList<>(); - while (root != null) { - if (root.left == null) { - ans.add(root.val); - root = root.right; - } else { - TreeNode prev = root.left; - while (prev.right != null && prev.right != root) { - prev = prev.right; - } - if (prev.right == null) { - prev.right = root; - root = root.left; - } else { - ans.add(root.val); - prev.right = null; - root = root.right; - } - } - } - return ans; + +function inorderTraversal(root: TreeNode | null): number[] { + if (root == null) { + return []; } + return [...inorderTraversal(root.left), root.val, ...inorderTraversal(root.right)]; } ``` -### **JavaScript** +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(root: &Option>>, res: &mut Vec) { + if root.is_none() { + return; + } + let node = root.as_ref().unwrap().borrow(); + Self::dfs(&node.left, res); + res.push(node.val); + Self::dfs(&node.right, res); + } -递归: + pub fn inorder_traversal(root: Option>>) -> Vec { + let mut res = vec![]; + Self::dfs(&root, &mut res); + res + } +} +``` ```js /** @@ -316,39 +275,150 @@ var inorderTraversal = function (root) { }; ``` -栈实现非递归: + -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) +### 方法二:栈实现非递归遍历 + +非递归的思路如下: + +1. 定义一个栈 stk +2. 将树的左节点依次入栈 +3. 左节点为空时,弹出栈顶元素并处理 +4. 重复 2-3 的操作 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数,空间复杂度主要取决于栈空间。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans, stk = [], [] + while root or stk: + if root: + stk.append(root) + root = root.left + else: + root = stk.pop() + ans.append(root.val) + root = root.right + return ans +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } * } */ +class Solution { + public List inorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + Deque stk = new ArrayDeque<>(); + while (root != null || !stk.isEmpty()) { + if (root != null) { + stk.push(root); + root = root.left; + } else { + root = stk.pop(); + ans.add(root.val); + root = root.right; + } + } + return ans; + } +} +``` + +```ts /** - * @param {TreeNode} root - * @return {number[]} + * 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) + * } + * } */ -var inorderTraversal = function (root) { - let ans = [], - stk = []; - while (root || stk.length > 0) { - if (root) { - stk.push(root); + +function inorderTraversal(root: TreeNode | null): number[] { + const res = []; + const stack = []; + while (root != null || stack.length != 0) { + if (root != null) { + stack.push(root); root = root.left; } else { - root = stk.pop(); - ans.push(root.val); - root = root.right; + const { val, right } = stack.pop(); + res.push(val); + root = right; } } - return ans; -}; + return res; +} ``` -Morris 遍历: +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn inorder_traversal(mut root: Option>>) -> Vec { + let mut res = vec![]; + let mut stack = vec![]; + while root.is_some() || !stack.is_empty() { + if root.is_some() { + let next = root.as_mut().unwrap().borrow_mut().left.take(); + stack.push(root); + root = next; + } else { + let mut node = stack.pop().unwrap(); + let mut node = node.as_mut().unwrap().borrow_mut(); + res.push(node.val); + root = node.right.take(); + } + } + res + } +} +``` ```js /** @@ -364,171 +434,111 @@ Morris 遍历: * @return {number[]} */ var inorderTraversal = function (root) { - let ans = []; - while (root) { - if (!root.left) { + let ans = [], + stk = []; + while (root || stk.length > 0) { + if (root) { + stk.push(root); + root = root.left; + } else { + root = stk.pop(); ans.push(root.val); root = root.right; - } else { - let prev = root.left; - while (prev.right && prev.right != root) { - prev = prev.right; - } - if (!prev.right) { - prev.right = root; - root = root.left; - } else { - ans.push(root.val); - prev.right = null; - root = root.right; - } } } return ans; }; ``` -### **C++** + -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector inorderTraversal(TreeNode* root) { - vector ans; - while (root) { - if (!root->left) { - ans.push_back(root->val); - root = root->right; - } else { - TreeNode* prev = root->left; - while (prev->right && prev->right != root) { - prev = prev->right; - } - if (!prev->right) { - prev->right = root; - root = root->left; - } else { - ans.push_back(root->val); - prev->right = nullptr; - root = root->right; - } - } - } - return ans; - } -}; -``` +### 方法三:Morris 实现中序遍历 -### **Go** +Morris 遍历无需使用栈,空间复杂度为 $O(1)$。核心思想是: -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func inorderTraversal(root *TreeNode) []int { - var ans []int - for root != nil { - if root.Left == nil { - ans = append(ans, root.Val) - root = root.Right - } else { - prev := root.Left - for prev.Right != nil && prev.Right != root { - prev = prev.Right - } - if prev.Right == nil { - prev.Right = root - root = root.Left - } else { - ans = append(ans, root.Val) - prev.Right = nil - root = root.Right - } - } - } - return ans -} -``` +遍历二叉树节点, -### **TypeScript** +1. 若当前节点 root 的左子树为空,**将当前节点值添加至结果列表 ans** 中,并将当前节点更新为 `root.right` +2. 若当前节点 root 的左子树不为空,找到左子树的最右节点 prev(也即是 root 节点在中序遍历下的前驱节点): + - 若前驱节点 prev 的右子树为空,将前驱节点的右子树指向当前节点 root,并将当前节点更新为 `root.left`。 + - 若前驱节点 prev 的右子树不为空,**将当前节点值添加至结果列表 ans** 中,然后将前驱节点右子树指向空(即解除 prev 与 root 的指向关系),并将当前节点更新为 `root.right`。 +3. 循环以上步骤,直至二叉树节点为空,遍历结束。 -递归: +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是二叉树的节点数。 -```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 inorderTraversal(root: TreeNode | null): number[] { - if (root == null) { - return []; - } - return [...inorderTraversal(root.left), root.val, ...inorderTraversal(root.right)]; -} +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + while root: + if root.left is None: + ans.append(root.val) + root = root.right + else: + prev = root.left + while prev.right and prev.right != root: + prev = prev.right + if prev.right is None: + prev.right = root + root = root.left + else: + ans.append(root.val) + prev.right = None + root = root.right + return ans ``` -迭代: - -```ts +```java /** * 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) + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; * } * } */ - -function inorderTraversal(root: TreeNode | null): number[] { - const res = []; - const stack = []; - while (root != null || stack.length != 0) { - if (root != null) { - stack.push(root); - root = root.left; - } else { - const { val, right } = stack.pop(); - res.push(val); - root = right; +class Solution { + public List inorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + while (root != null) { + if (root.left == null) { + ans.add(root.val); + root = root.right; + } else { + TreeNode prev = root.left; + while (prev.right != null && prev.right != root) { + prev = prev.right; + } + if (prev.right == null) { + prev.right = root; + root = root.left; + } else { + ans.add(root.val); + prev.right = null; + root = root.right; + } + } } + return ans; } - return res; } ``` -Morris 遍历: - ```ts /** * Definition for a binary tree node. @@ -570,98 +580,44 @@ function inorderTraversal(root: TreeNode | null): number[] { } ``` -### **Rust** - -递归: - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(root: &Option>>, res: &mut Vec) { - if root.is_none() { - return; - } - let node = root.as_ref().unwrap().borrow(); - Self::dfs(&node.left, res); - res.push(node.val); - Self::dfs(&node.right, res); - } - - pub fn inorder_traversal(root: Option>>) -> Vec { - let mut res = vec![]; - Self::dfs(&root, &mut res); - res - } -} -``` - -迭代: - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - pub fn inorder_traversal(mut root: Option>>) -> Vec { - let mut res = vec![]; - let mut stack = vec![]; - while root.is_some() || !stack.is_empty() { - if root.is_some() { - let next = root.as_mut().unwrap().borrow_mut().left.take(); - stack.push(root); - root = next; +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var inorderTraversal = function (root) { + let ans = []; + while (root) { + if (!root.left) { + ans.push(root.val); + root = root.right; + } else { + let prev = root.left; + while (prev.right && prev.right != root) { + prev = prev.right; + } + if (!prev.right) { + prev.right = root; + root = root.left; } else { - let mut node = stack.pop().unwrap(); - let mut node = node.as_mut().unwrap().borrow_mut(); - res.push(node.val); - root = node.right.take(); + ans.push(root.val); + prev.right = null; + root = root.right; } } - res } -} -``` - -### **...** - -``` - + return ans; +}; ``` + + diff --git a/solution/0000-0099/0094.Binary Tree Inorder Traversal/README_EN.md b/solution/0000-0099/0094.Binary Tree Inorder Traversal/README_EN.md index ff7d900babfdd..49ebcbafe7f74 100644 --- a/solution/0000-0099/0094.Binary Tree Inorder Traversal/README_EN.md +++ b/solution/0000-0099/0094.Binary Tree Inorder Traversal/README_EN.md @@ -41,43 +41,14 @@ ## Solutions -**Solution 1: Recursive Traversal** +### Solution 1: Recursive Traversal We first recursively traverse the left subtree, then visit the root node, and finally recursively traverse the right subtree. The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree, and the space complexity mainly depends on the stack space of the recursive call. -**Solution 2: Stack Implementation for Non-recursive Traversal** - -The non-recursive approach is as follows: - -1. Define a stack `stk`. -2. Push the left nodes of the tree into the stack in sequence. -3. When the left node is null, pop and process the top element of the stack. -4. Repeat steps 2-3. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree, and the space complexity mainly depends on the stack space. - -**Solution 3: Morris Implementation for In-order Traversal** - -Morris traversal does not require a stack, so the space complexity is $O(1)$. The core idea is: - -Traverse the binary tree nodes, - -1. If the left subtree of the current node `root` is null, **add the current node value to the result list `ans`**, and update the current node to `root.right`. -2. If the left subtree of the current node `root` is not null, find the rightmost node `prev` of the left subtree (which is the predecessor node of the `root` node in in-order traversal): - - If the right subtree of the predecessor node `prev` is null, point the right subtree of the predecessor node to the current node `root`, and update the current node to `root.left`. - - If the right subtree of the predecessor node `prev` is not null, **add the current node value to the result list `ans`**, then point the right subtree of the predecessor node to null (i.e., disconnect `prev` and `root`), and update the current node to `root.right`. -3. Repeat the above steps until the binary tree node is null, and the traversal ends. - -The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the number of nodes in the binary tree. - -### **Python3** - -Recusive: - ```python # Definition for a binary tree node. # class TreeNode: @@ -100,63 +71,6 @@ class Solution: return ans ``` -Non-recursive: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: - ans, stk = [], [] - while root or stk: - if root: - stk.append(root) - root = root.left - else: - root = stk.pop() - ans.append(root.val) - root = root.right - return ans -``` - -Morris Traversal: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: - ans = [] - while root: - if root.left is None: - ans.append(root.val) - root = root.right - else: - prev = root.left - while prev.right and prev.right != root: - prev = prev.right - if prev.right is None: - prev.right = root - root = root.left - else: - ans.append(root.val) - prev.right = None - root = root.right - return ans -``` - -### **Java** - -Recursive: - ```java /** * Definition for a binary tree node. @@ -193,91 +107,142 @@ class Solution { } ``` -Non-recursive: - -```java +```cpp /** * Definition for a binary tree node. - * public class TreeNode { + * struct TreeNode { * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; */ class Solution { - public List inorderTraversal(TreeNode root) { - List ans = new ArrayList<>(); - Deque stk = new ArrayDeque<>(); - while (root != null || !stk.isEmpty()) { - if (root != null) { - stk.push(root); - root = root.left; +public: + vector inorderTraversal(TreeNode* root) { + vector ans; + while (root) { + if (!root->left) { + ans.push_back(root->val); + root = root->right; } else { - root = stk.pop(); - ans.add(root.val); - root = root.right; + TreeNode* prev = root->left; + while (prev->right && prev->right != root) { + prev = prev->right; + } + if (!prev->right) { + prev->right = root; + root = root->left; + } else { + ans.push_back(root->val); + prev->right = nullptr; + root = root->right; + } } } return ans; } -} +}; ``` -Morris Traversal: +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func inorderTraversal(root *TreeNode) []int { + var ans []int + for root != nil { + if root.Left == nil { + ans = append(ans, root.Val) + root = root.Right + } else { + prev := root.Left + for prev.Right != nil && prev.Right != root { + prev = prev.Right + } + if prev.Right == nil { + prev.Right = root + root = root.Left + } else { + ans = append(ans, root.Val) + prev.Right = nil + root = root.Right + } + } + } + return ans +} +``` -```java +```ts /** * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; + * 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) * } * } */ -class Solution { - public List inorderTraversal(TreeNode root) { - List ans = new ArrayList<>(); - while (root != null) { - if (root.left == null) { - ans.add(root.val); - root = root.right; - } else { - TreeNode prev = root.left; - while (prev.right != null && prev.right != root) { - prev = prev.right; - } - if (prev.right == null) { - prev.right = root; - root = root.left; - } else { - ans.add(root.val); - prev.right = null; - root = root.right; - } - } - } - return ans; + +function inorderTraversal(root: TreeNode | null): number[] { + if (root == null) { + return []; } + return [...inorderTraversal(root.left), root.val, ...inorderTraversal(root.right)]; } ``` -### **JavaScript** +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(root: &Option>>, res: &mut Vec) { + if root.is_none() { + return; + } + let node = root.as_ref().unwrap().borrow(); + Self::dfs(&node.left, res); + res.push(node.val); + Self::dfs(&node.right, res); + } -Recursive: + pub fn inorder_traversal(root: Option>>) -> Vec { + let mut res = vec![]; + Self::dfs(&root, &mut res); + res + } +} +``` ```js /** @@ -305,39 +270,150 @@ var inorderTraversal = function (root) { }; ``` -Non-recursive: + -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) +### Solution 2: Stack Implementation for Non-recursive Traversal + +The non-recursive approach is as follows: + +1. Define a stack `stk`. +2. Push the left nodes of the tree into the stack in sequence. +3. When the left node is null, pop and process the top element of the stack. +4. Repeat steps 2-3. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree, and the space complexity mainly depends on the stack space. + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans, stk = [], [] + while root or stk: + if root: + stk.append(root) + root = root.left + else: + root = stk.pop() + ans.append(root.val) + root = root.right + return ans +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } * } */ +class Solution { + public List inorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + Deque stk = new ArrayDeque<>(); + while (root != null || !stk.isEmpty()) { + if (root != null) { + stk.push(root); + root = root.left; + } else { + root = stk.pop(); + ans.add(root.val); + root = root.right; + } + } + return ans; + } +} +``` + +```ts /** - * @param {TreeNode} root - * @return {number[]} + * 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) + * } + * } */ -var inorderTraversal = function (root) { - let ans = [], - stk = []; - while (root || stk.length > 0) { - if (root) { - stk.push(root); + +function inorderTraversal(root: TreeNode | null): number[] { + const res = []; + const stack = []; + while (root != null || stack.length != 0) { + if (root != null) { + stack.push(root); root = root.left; } else { - root = stk.pop(); - ans.push(root.val); - root = root.right; + const { val, right } = stack.pop(); + res.push(val); + root = right; } } - return ans; -}; + return res; +} ``` -Morris Traversal: +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn inorder_traversal(mut root: Option>>) -> Vec { + let mut res = vec![]; + let mut stack = vec![]; + while root.is_some() || !stack.is_empty() { + if root.is_some() { + let next = root.as_mut().unwrap().borrow_mut().left.take(); + stack.push(root); + root = next; + } else { + let mut node = stack.pop().unwrap(); + let mut node = node.as_mut().unwrap().borrow_mut(); + res.push(node.val); + root = node.right.take(); + } + } + res + } +} +``` ```js /** @@ -353,171 +429,111 @@ Morris Traversal: * @return {number[]} */ var inorderTraversal = function (root) { - let ans = []; - while (root) { - if (!root.left) { + let ans = [], + stk = []; + while (root || stk.length > 0) { + if (root) { + stk.push(root); + root = root.left; + } else { + root = stk.pop(); ans.push(root.val); root = root.right; - } else { - let prev = root.left; - while (prev.right && prev.right != root) { - prev = prev.right; - } - if (!prev.right) { - prev.right = root; - root = root.left; - } else { - ans.push(root.val); - prev.right = null; - root = root.right; - } } } return ans; }; ``` -### **C++** + -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector inorderTraversal(TreeNode* root) { - vector ans; - while (root) { - if (!root->left) { - ans.push_back(root->val); - root = root->right; - } else { - TreeNode* prev = root->left; - while (prev->right && prev->right != root) { - prev = prev->right; - } - if (!prev->right) { - prev->right = root; - root = root->left; - } else { - ans.push_back(root->val); - prev->right = nullptr; - root = root->right; - } - } - } - return ans; - } -}; -``` +### Solution 3: Morris Implementation for In-order Traversal -### **Go** +Morris traversal does not require a stack, so the space complexity is $O(1)$. The core idea is: -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func inorderTraversal(root *TreeNode) []int { - var ans []int - for root != nil { - if root.Left == nil { - ans = append(ans, root.Val) - root = root.Right - } else { - prev := root.Left - for prev.Right != nil && prev.Right != root { - prev = prev.Right - } - if prev.Right == nil { - prev.Right = root - root = root.Left - } else { - ans = append(ans, root.Val) - prev.Right = nil - root = root.Right - } - } - } - return ans -} -``` +Traverse the binary tree nodes, -### **TypeScript** +1. If the left subtree of the current node `root` is null, **add the current node value to the result list `ans`**, and update the current node to `root.right`. +2. If the left subtree of the current node `root` is not null, find the rightmost node `prev` of the left subtree (which is the predecessor node of the `root` node in in-order traversal): + - If the right subtree of the predecessor node `prev` is null, point the right subtree of the predecessor node to the current node `root`, and update the current node to `root.left`. + - If the right subtree of the predecessor node `prev` is not null, **add the current node value to the result list `ans`**, then point the right subtree of the predecessor node to null (i.e., disconnect `prev` and `root`), and update the current node to `root.right`. +3. Repeat the above steps until the binary tree node is null, and the traversal ends. -Recursion: +The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the number of nodes in the binary tree. -```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 inorderTraversal(root: TreeNode | null): number[] { - if (root == null) { - return []; - } - return [...inorderTraversal(root.left), root.val, ...inorderTraversal(root.right)]; -} +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + while root: + if root.left is None: + ans.append(root.val) + root = root.right + else: + prev = root.left + while prev.right and prev.right != root: + prev = prev.right + if prev.right is None: + prev.right = root + root = root.left + else: + ans.append(root.val) + prev.right = None + root = root.right + return ans ``` -Iteration: - -```ts +```java /** * 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) + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; * } * } */ - -function inorderTraversal(root: TreeNode | null): number[] { - const res = []; - const stack = []; - while (root != null || stack.length != 0) { - if (root != null) { - stack.push(root); - root = root.left; - } else { - const { val, right } = stack.pop(); - res.push(val); - root = right; +class Solution { + public List inorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + while (root != null) { + if (root.left == null) { + ans.add(root.val); + root = root.right; + } else { + TreeNode prev = root.left; + while (prev.right != null && prev.right != root) { + prev = prev.right; + } + if (prev.right == null) { + prev.right = root; + root = root.left; + } else { + ans.add(root.val); + prev.right = null; + root = root.right; + } + } } + return ans; } - return res; } ``` -Morris Traversal: - ```ts /** * Definition for a binary tree node. @@ -559,98 +575,44 @@ function inorderTraversal(root: TreeNode | null): number[] { } ``` -### **Rust** - -Recursion: - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(root: &Option>>, res: &mut Vec) { - if root.is_none() { - return; - } - let node = root.as_ref().unwrap().borrow(); - Self::dfs(&node.left, res); - res.push(node.val); - Self::dfs(&node.right, res); - } - - pub fn inorder_traversal(root: Option>>) -> Vec { - let mut res = vec![]; - Self::dfs(&root, &mut res); - res - } -} -``` - -Iteration: - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - pub fn inorder_traversal(mut root: Option>>) -> Vec { - let mut res = vec![]; - let mut stack = vec![]; - while root.is_some() || !stack.is_empty() { - if root.is_some() { - let next = root.as_mut().unwrap().borrow_mut().left.take(); - stack.push(root); - root = next; +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var inorderTraversal = function (root) { + let ans = []; + while (root) { + if (!root.left) { + ans.push(root.val); + root = root.right; + } else { + let prev = root.left; + while (prev.right && prev.right != root) { + prev = prev.right; + } + if (!prev.right) { + prev.right = root; + root = root.left; } else { - let mut node = stack.pop().unwrap(); - let mut node = node.as_mut().unwrap().borrow_mut(); - res.push(node.val); - root = node.right.take(); + ans.push(root.val); + prev.right = null; + root = root.right; } } - res } -} -``` - -### **...** - -``` - + return ans; +}; ``` + + diff --git a/solution/0000-0099/0095.Unique Binary Search Trees II/README.md b/solution/0000-0099/0095.Unique Binary Search Trees II/README.md index 9e98d72d78544..d32118a60f01b 100644 --- a/solution/0000-0099/0095.Unique Binary Search Trees II/README.md +++ b/solution/0000-0099/0095.Unique Binary Search Trees II/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们设计一个函数 $dfs(i, j)$,返回由 $[i, j]$ 组成的所有可行的二叉搜索树,那么答案就是 $dfs(1, n)$。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -81,10 +75,6 @@ class Solution: return dfs(1, n) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -164,8 +152,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -197,8 +183,6 @@ func generateTrees(n int) []*TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -235,8 +219,6 @@ function generateTrees(n: number): Array { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -293,10 +275,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0095.Unique Binary Search Trees II/README_EN.md b/solution/0000-0099/0095.Unique Binary Search Trees II/README_EN.md index aa14f32268808..e4babfaae3d0f 100644 --- a/solution/0000-0099/0095.Unique Binary Search Trees II/README_EN.md +++ b/solution/0000-0099/0095.Unique Binary Search Trees II/README_EN.md @@ -30,7 +30,7 @@ ## Solutions -**Solution 1: DFS (Depth-First Search)** +### Solution 1: DFS (Depth-First Search) We design a function $dfs(i, j)$ that returns all feasible binary search trees composed of $[i, j]$, so the answer is $dfs(1, n)$. @@ -43,8 +43,6 @@ The time complexity is $O(n \times G(n))$, and the space complexity is $O(n \tim -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -69,8 +67,6 @@ class Solution: return dfs(1, n) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -150,8 +144,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -183,8 +175,6 @@ func generateTrees(n int) []*TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -221,8 +211,6 @@ function generateTrees(n: number): Array { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -279,10 +267,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0096.Unique Binary Search Trees/README.md b/solution/0000-0099/0096.Unique Binary Search Trees/README.md index bbe1805ff980f..6a15ba0a1756e 100644 --- a/solution/0000-0099/0096.Unique Binary Search Trees/README.md +++ b/solution/0000-0099/0096.Unique Binary Search Trees/README.md @@ -34,9 +34,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示 $[1, i]$ 能产生的二叉搜索树的个数,初始时 $f[0] = 1$,答案为 $f[n]$。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python class Solution: def numTrees(self, n: int) -> int: @@ -62,10 +56,6 @@ class Solution: return f[n] ``` -### **Java** - - - ```java class Solution { public int numTrees(int n) { @@ -81,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +87,6 @@ public: }; ``` -### **Go** - ```go func numTrees(n int) int { f := make([]int, n+1) @@ -114,7 +100,18 @@ func numTrees(n int) int { } ``` -### **Rust** +```ts +function numTrees(n: number): number { + const f: number[] = Array(n + 1).fill(0); + f[0] = 1; + for (let i = 1; i <= n; ++i) { + for (let j = 0; j < i; ++j) { + f[i] += f[j] * f[i - j - 1]; + } + } + return f[n]; +} +``` ```rust impl Solution { @@ -132,23 +129,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function numTrees(n: number): number { - const f: number[] = Array(n + 1).fill(0); - f[0] = 1; - for (let i = 1; i <= n; ++i) { - for (let j = 0; j < i; ++j) { - f[i] += f[j] * f[i - j - 1]; - } - } - return f[n]; -} -``` - -### **C#** - ```cs public class Solution { public int NumTrees(int n) { @@ -164,10 +144,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0096.Unique Binary Search Trees/README_EN.md b/solution/0000-0099/0096.Unique Binary Search Trees/README_EN.md index 1b866b88d4940..ae877a115ccfd 100644 --- a/solution/0000-0099/0096.Unique Binary Search Trees/README_EN.md +++ b/solution/0000-0099/0096.Unique Binary Search Trees/README_EN.md @@ -30,7 +30,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i]$ to represent the number of binary search trees that can be generated from $[1, i]$. Initially, $f[0] = 1$, and the answer is $f[n]$. @@ -42,8 +42,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def numTrees(self, n: int) -> int: @@ -54,8 +52,6 @@ class Solution: return f[n] ``` -### **Java** - ```java class Solution { public int numTrees(int n) { @@ -71,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,8 +83,6 @@ public: }; ``` -### **Go** - ```go func numTrees(n int) int { f := make([]int, n+1) @@ -104,7 +96,18 @@ func numTrees(n int) int { } ``` -### **Rust** +```ts +function numTrees(n: number): number { + const f: number[] = Array(n + 1).fill(0); + f[0] = 1; + for (let i = 1; i <= n; ++i) { + for (let j = 0; j < i; ++j) { + f[i] += f[j] * f[i - j - 1]; + } + } + return f[n]; +} +``` ```rust impl Solution { @@ -122,23 +125,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function numTrees(n: number): number { - const f: number[] = Array(n + 1).fill(0); - f[0] = 1; - for (let i = 1; i <= n; ++i) { - for (let j = 0; j < i; ++j) { - f[i] += f[j] * f[i - j - 1]; - } - } - return f[n]; -} -``` - -### **C#** - ```cs public class Solution { public int NumTrees(int n) { @@ -154,10 +140,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0097.Interleaving String/README.md b/solution/0000-0099/0097.Interleaving String/README.md index 5352a0549a721..b2402f3d6afa3 100644 --- a/solution/0000-0099/0097.Interleaving String/README.md +++ b/solution/0000-0099/0097.Interleaving String/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们记字符串 $s_1$ 的长度为 $m$,字符串 $s_2$ 的长度为 $n$,如果 $m + n \neq |s_3|$,那么 $s_3$ 一定不是 $s_1$ 和 $s_2$ 的交错字符串,返回 `false`。 @@ -80,34 +78,8 @@ 时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是字符串 $s_1$ 和 $s_2$ 的长度。 -**方法二:动态规划** - -我们可以将方法一中的记忆化搜索转化为动态规划。 - -定义 $f[i][j]$ 表示字符串 $s_1$ 的前 $i$ 个字符和字符串 $s_2$ 的前 $j$ 个字符是否能交错组成字符串 $s_3$ 的前 $i + j$ 个字符。在进行状态转移时,我们可以考虑当前字符是由 $s_1$ 的最后一个字符还是 $s_2$ 的最后一个字符得到的,因此有状态转移方程: - -$$ -f[i][j] = \begin{cases} -f[i - 1][j] & \text{if } s_1[i - 1] = s_3[i + j - 1] \\ -\text{or } f[i][j - 1] & \text{if } s_2[j - 1] = s_3[i + j - 1] \\ -\text{false} & \text{otherwise} -\end{cases} -$$ - -其中 $f[0][0] = \text{true}$ 表示空串是两个空串的交错字符串。 - -答案即为 $f[m][n]$。 - -时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是字符串 $s_1$ 和 $s_2$ 的长度。 - -我们注意到,状态 $f[i][j]$ 只和状态 $f[i - 1][j]$、$f[i][j - 1]$、$f[i - 1][j - 1]$ 有关,因此我们可以使用滚动数组优化空间复杂度,将空间复杂度优化到 $O(n)$。 - -### **Python3** - - - ```python class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: @@ -128,45 +100,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def isInterleave(self, s1: str, s2: str, s3: str) -> bool: - m, n = len(s1), len(s2) - if m + n != len(s3): - return False - f = [[False] * (n + 1) for _ in range(m + 1)] - f[0][0] = True - for i in range(m + 1): - for j in range(n + 1): - k = i + j - 1 - if i and s1[i - 1] == s3[k]: - f[i][j] = f[i - 1][j] - if j and s2[j - 1] == s3[k]: - f[i][j] |= f[i][j - 1] - return f[m][n] -``` - -```python -class Solution: - def isInterleave(self, s1: str, s2: str, s3: str) -> bool: - m, n = len(s1), len(s2) - if m + n != len(s3): - return False - f = [True] + [False] * n - for i in range(m + 1): - for j in range(n + 1): - k = i + j - 1 - if i: - f[j] &= s1[i - 1] == s3[k] - if j: - f[j] |= f[j - 1] and s2[j - 1] == s3[k] - return f[n] -``` - -### **Java** - - - ```java class Solution { private Map, Boolean> f = new HashMap<>(); @@ -210,58 +143,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isInterleave(String s1, String s2, String s3) { - int m = s1.length(), n = s2.length(); - if (m + n != s3.length()) { - return false; - } - boolean[][] f = new boolean[m + 1][n + 1]; - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i > 0 && s1.charAt(i - 1) == s3.charAt(k)) { - f[i][j] = f[i - 1][j]; - } - if (j > 0 && s2.charAt(j - 1) == s3.charAt(k)) { - f[i][j] |= f[i][j - 1]; - } - } - } - return f[m][n]; - } -} -``` - -```java -class Solution { - public boolean isInterleave(String s1, String s2, String s3) { - int m = s1.length(), n = s2.length(); - if (m + n != s3.length()) { - return false; - } - boolean[] f = new boolean[n + 1]; - f[0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i > 0) { - f[j] &= s1.charAt(i - 1) == s3.charAt(k); - } - if (j > 0) { - f[j] |= (f[j - 1] & s2.charAt(j - 1) == s3.charAt(k)); - } - } - } - return f[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -293,62 +174,58 @@ public: }; ``` -```cpp -class Solution { -public: - bool isInterleave(string s1, string s2, string s3) { - int m = s1.size(), n = s2.size(); - if (m + n != s3.size()) { - return false; - } - bool f[m + 1][n + 1]; - memset(f, false, sizeof(f)); - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i > 0 && s1[i - 1] == s3[k]) { - f[i][j] = f[i - 1][j]; - } - if (j > 0 && s2[j - 1] == s3[k]) { - f[i][j] |= f[i][j - 1]; - } - } - } - return f[m][n]; - } -}; +```go +func isInterleave(s1 string, s2 string, s3 string) bool { + m, n := len(s1), len(s2) + if m+n != len(s3) { + return false + } + + f := map[int]bool{} + var dfs func(int, int) bool + dfs = func(i, j int) bool { + if i >= m && j >= n { + return true + } + if v, ok := f[i*200+j]; ok { + return v + } + k := i + j + f[i*200+j] = (i < m && s1[i] == s3[k] && dfs(i+1, j)) || (j < n && s2[j] == s3[k] && dfs(i, j+1)) + return f[i*200+j] + } + return dfs(0, 0) +} ``` -```cpp -class Solution { -public: - bool isInterleave(string s1, string s2, string s3) { - int m = s1.size(), n = s2.size(); - if (m + n != s3.size()) { - return false; +```ts +function isInterleave(s1: string, s2: string, s3: string): boolean { + const m = s1.length; + const n = s2.length; + if (m + n !== s3.length) { + return false; + } + const f: number[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); + const dfs = (i: number, j: number): boolean => { + if (i >= m && j >= n) { + return true; } - bool f[n + 1]; - memset(f, false, sizeof(f)); - f[0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i) { - f[j] &= s1[i - 1] == s3[k]; - } - if (j) { - f[j] |= (s2[j - 1] == s3[k] && f[j - 1]); - } - } + if (f[i][j]) { + return f[i][j] === 1; } - return f[n]; - } -}; + f[i][j] = -1; + if (i < m && s1[i] === s3[i + j] && dfs(i + 1, j)) { + f[i][j] = 1; + } + if (f[i][j] === -1 && j < n && s2[j] === s3[i + j] && dfs(i, j + 1)) { + f[i][j] = 1; + } + return f[i][j] === 1; + }; + return dfs(0, 0); +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -417,38 +294,149 @@ impl Solution { } ``` -### **Go** - -```go -func isInterleave(s1 string, s2 string, s3 string) bool { - m, n := len(s1), len(s2) - if m+n != len(s3) { - return false - } +```cs +public class Solution { + private int m; + private int n; + private string s1; + private string s2; + private string s3; + private int[,] f; - f := map[int]bool{} - var dfs func(int, int) bool - dfs = func(i, j int) bool { - if i >= m && j >= n { - return true - } - if v, ok := f[i*200+j]; ok { - return v - } - k := i + j - f[i*200+j] = (i < m && s1[i] == s3[k] && dfs(i+1, j)) || (j < n && s2[j] == s3[k] && dfs(i, j+1)) - return f[i*200+j] - } - return dfs(0, 0) -} -``` + public bool IsInterleave(string s1, string s2, string s3) { + m = s1.Length; + n = s2.Length; + if (m + n != s3.Length) { + return false; + } + this.s1 = s1; + this.s2 = s2; + this.s3 = s3; + f = new int[m + 1, n + 1]; + return dfs(0, 0); + } -```go -func isInterleave(s1 string, s2 string, s3 string) bool { - m, n := len(s1), len(s2) - if m+n != len(s3) { - return false - } + private bool dfs(int i, int j) { + if (i >= m && j >= n) { + return true; + } + if (f[i, j] != 0) { + return f[i, j] == 1; + } + f[i, j] = -1; + if (i < m && s1[i] == s3[i + j] && dfs(i + 1, j)) { + f[i, j] = 1; + } + if (f[i, j] == -1 && j < n && s2[j] == s3[i + j] && dfs(i, j + 1)) { + f[i, j] = 1; + } + return f[i, j] == 1; + } +} +``` + + + +### 方法二:动态规划 + +我们可以将方法一中的记忆化搜索转化为动态规划。 + +定义 $f[i][j]$ 表示字符串 $s_1$ 的前 $i$ 个字符和字符串 $s_2$ 的前 $j$ 个字符是否能交错组成字符串 $s_3$ 的前 $i + j$ 个字符。在进行状态转移时,我们可以考虑当前字符是由 $s_1$ 的最后一个字符还是 $s_2$ 的最后一个字符得到的,因此有状态转移方程: + +$$ +f[i][j] = \begin{cases} +f[i - 1][j] & \text{if } s_1[i - 1] = s_3[i + j - 1] \\ +\text{or } f[i][j - 1] & \text{if } s_2[j - 1] = s_3[i + j - 1] \\ +\text{false} & \text{otherwise} +\end{cases} +$$ + +其中 $f[0][0] = \text{true}$ 表示空串是两个空串的交错字符串。 + +答案即为 $f[m][n]$。 + +时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是字符串 $s_1$ 和 $s_2$ 的长度。 + +我们注意到,状态 $f[i][j]$ 只和状态 $f[i - 1][j]$、$f[i][j - 1]$、$f[i - 1][j - 1]$ 有关,因此我们可以使用滚动数组优化空间复杂度,将空间复杂度优化到 $O(n)$。 + + + +```python +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + m, n = len(s1), len(s2) + if m + n != len(s3): + return False + f = [[False] * (n + 1) for _ in range(m + 1)] + f[0][0] = True + for i in range(m + 1): + for j in range(n + 1): + k = i + j - 1 + if i and s1[i - 1] == s3[k]: + f[i][j] = f[i - 1][j] + if j and s2[j - 1] == s3[k]: + f[i][j] |= f[i][j - 1] + return f[m][n] +``` + +```java +class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + int m = s1.length(), n = s2.length(); + if (m + n != s3.length()) { + return false; + } + boolean[][] f = new boolean[m + 1][n + 1]; + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1.charAt(i - 1) == s3.charAt(k)) { + f[i][j] = f[i - 1][j]; + } + if (j > 0 && s2.charAt(j - 1) == s3.charAt(k)) { + f[i][j] |= f[i][j - 1]; + } + } + } + return f[m][n]; + } +} +``` + +```cpp +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + int m = s1.size(), n = s2.size(); + if (m + n != s3.size()) { + return false; + } + bool f[m + 1][n + 1]; + memset(f, false, sizeof(f)); + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1[i - 1] == s3[k]) { + f[i][j] = f[i - 1][j]; + } + if (j > 0 && s2[j - 1] == s3[k]) { + f[i][j] |= f[i][j - 1]; + } + } + } + return f[m][n]; + } +}; +``` + +```go +func isInterleave(s1 string, s2 string, s3 string) bool { + m, n := len(s1), len(s2) + if m+n != len(s3) { + return false + } f := make([][]bool, m+1) for i := range f { f[i] = make([]bool, n+1) @@ -469,59 +457,6 @@ func isInterleave(s1 string, s2 string, s3 string) bool { } ``` -```go -func isInterleave(s1 string, s2 string, s3 string) bool { - m, n := len(s1), len(s2) - if m+n != len(s3) { - return false - } - f := make([]bool, n+1) - f[0] = true - for i := 0; i <= m; i++ { - for j := 0; j <= n; j++ { - k := i + j - 1 - if i > 0 { - f[j] = (f[j] && s1[i-1] == s3[k]) - } - if j > 0 { - f[j] = (f[j] || (s2[j-1] == s3[k] && f[j-1])) - } - } - } - return f[n] -} -``` - -### **TypeScript** - -```ts -function isInterleave(s1: string, s2: string, s3: string): boolean { - const m = s1.length; - const n = s2.length; - if (m + n !== s3.length) { - return false; - } - const f: number[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); - const dfs = (i: number, j: number): boolean => { - if (i >= m && j >= n) { - return true; - } - if (f[i][j]) { - return f[i][j] === 1; - } - f[i][j] = -1; - if (i < m && s1[i] === s3[i + j] && dfs(i + 1, j)) { - f[i][j] = 1; - } - if (f[i][j] === -1 && j < n && s2[j] === s3[i + j] && dfs(i, j + 1)) { - f[i][j] = 1; - } - return f[i][j] === 1; - }; - return dfs(0, 0); -} -``` - ```ts function isInterleave(s1: string, s2: string, s3: string): boolean { const m = s1.length; @@ -546,95 +481,150 @@ function isInterleave(s1: string, s2: string, s3: string): boolean { } ``` -```ts -function isInterleave(s1: string, s2: string, s3: string): boolean { - const m = s1.length; - const n = s2.length; - if (m + n !== s3.length) { - return false; - } - const f: boolean[] = new Array(n + 1).fill(false); - f[0] = true; - for (let i = 0; i <= m; ++i) { - for (let j = 0; j <= n; ++j) { - const k = i + j - 1; - if (i) { - f[j] = f[j] && s1[i - 1] === s3[k]; - } - if (j) { - f[j] = f[j] || (f[j - 1] && s2[j - 1] === s3[k]); +```cs +public class Solution { + public bool IsInterleave(string s1, string s2, string s3) { + int m = s1.Length, n = s2.Length; + if (m + n != s3.Length) { + return false; + } + bool[,] f = new bool[m + 1, n + 1]; + f[0, 0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1[i - 1] == s3[k]) { + f[i, j] = f[i - 1, j]; + } + if (j > 0 && s2[j - 1] == s3[k]) { + f[i, j] |= f[i, j - 1]; + } } } + return f[m, n]; } - return f[n]; } ``` -### **C#** + -```cs -public class Solution { - private int m; - private int n; - private string s1; - private string s2; - private string s3; - private int[,] f; +### 方法三 - public bool IsInterleave(string s1, string s2, string s3) { - m = s1.Length; - n = s2.Length; - if (m + n != s3.Length) { - return false; - } - this.s1 = s1; - this.s2 = s2; - this.s3 = s3; - f = new int[m + 1, n + 1]; - return dfs(0, 0); - } + - private bool dfs(int i, int j) { - if (i >= m && j >= n) { - return true; - } - if (f[i, j] != 0) { - return f[i, j] == 1; - } - f[i, j] = -1; - if (i < m && s1[i] == s3[i + j] && dfs(i + 1, j)) { - f[i, j] = 1; +```python +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + m, n = len(s1), len(s2) + if m + n != len(s3): + return False + f = [True] + [False] * n + for i in range(m + 1): + for j in range(n + 1): + k = i + j - 1 + if i: + f[j] &= s1[i - 1] == s3[k] + if j: + f[j] |= f[j - 1] and s2[j - 1] == s3[k] + return f[n] +``` + +```java +class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + int m = s1.length(), n = s2.length(); + if (m + n != s3.length()) { + return false; } - if (f[i, j] == -1 && j < n && s2[j] == s3[i + j] && dfs(i, j + 1)) { - f[i, j] = 1; + boolean[] f = new boolean[n + 1]; + f[0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0) { + f[j] &= s1.charAt(i - 1) == s3.charAt(k); + } + if (j > 0) { + f[j] |= (f[j - 1] & s2.charAt(j - 1) == s3.charAt(k)); + } + } } - return f[i, j] == 1; + return f[n]; } } ``` -```cs -public class Solution { - public bool IsInterleave(string s1, string s2, string s3) { - int m = s1.Length, n = s2.Length; - if (m + n != s3.Length) { +```cpp +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + int m = s1.size(), n = s2.size(); + if (m + n != s3.size()) { return false; } - bool[,] f = new bool[m + 1, n + 1]; - f[0, 0] = true; + bool f[n + 1]; + memset(f, false, sizeof(f)); + f[0] = true; for (int i = 0; i <= m; ++i) { for (int j = 0; j <= n; ++j) { int k = i + j - 1; - if (i > 0 && s1[i - 1] == s3[k]) { - f[i, j] = f[i - 1, j]; + if (i) { + f[j] &= s1[i - 1] == s3[k]; } - if (j > 0 && s2[j - 1] == s3[k]) { - f[i, j] |= f[i, j - 1]; + if (j) { + f[j] |= (s2[j - 1] == s3[k] && f[j - 1]); } } } - return f[m, n]; + return f[n]; } +}; +``` + +```go +func isInterleave(s1 string, s2 string, s3 string) bool { + m, n := len(s1), len(s2) + if m+n != len(s3) { + return false + } + f := make([]bool, n+1) + f[0] = true + for i := 0; i <= m; i++ { + for j := 0; j <= n; j++ { + k := i + j - 1 + if i > 0 { + f[j] = (f[j] && s1[i-1] == s3[k]) + } + if j > 0 { + f[j] = (f[j] || (s2[j-1] == s3[k] && f[j-1])) + } + } + } + return f[n] +} +``` + +```ts +function isInterleave(s1: string, s2: string, s3: string): boolean { + const m = s1.length; + const n = s2.length; + if (m + n !== s3.length) { + return false; + } + const f: boolean[] = new Array(n + 1).fill(false); + f[0] = true; + for (let i = 0; i <= m; ++i) { + for (let j = 0; j <= n; ++j) { + const k = i + j - 1; + if (i) { + f[j] = f[j] && s1[i - 1] === s3[k]; + } + if (j) { + f[j] = f[j] || (f[j - 1] && s2[j - 1] === s3[k]); + } + } + } + return f[n]; } ``` @@ -663,10 +653,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0097.Interleaving String/README_EN.md b/solution/0000-0099/0097.Interleaving String/README_EN.md index b38333693c8d7..62ba9ed5da645 100644 --- a/solution/0000-0099/0097.Interleaving String/README_EN.md +++ b/solution/0000-0099/0097.Interleaving String/README_EN.md @@ -58,7 +58,7 @@ Since s3 can be obtained by interleaving s1 and s2, we return true. ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search Let's denote the length of string $s_1$ as $m$ and the length of string $s_2$ as $n$. If $m + n \neq |s_3|$, then $s_3$ is definitely not an interleaving string of $s_1$ and $s_2$, so we return `false`. @@ -78,32 +78,8 @@ To avoid repeated calculations, we can use memoization search. The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the lengths of strings $s_1$ and $s_2$ respectively. -**Solution 2: Dynamic Programming** - -We can convert the memoization search in Solution 1 into dynamic programming. - -We define $f[i][j]$ to represent whether the first $i$ characters of string $s_1$ and the first $j$ characters of string $s_2$ can interleave to form the first $i + j$ characters of string $s_3$. When transitioning states, we can consider whether the current character is obtained from the last character of $s_1$ or the last character of $s_2$. Therefore, we have the state transition equation: - -$$ -f[i][j] = \begin{cases} -f[i - 1][j] & \text{if } s_1[i - 1] = s_3[i + j - 1] \\ -\text{or } f[i][j - 1] & \text{if } s_2[j - 1] = s_3[i + j - 1] \\ -\text{false} & \text{otherwise} -\end{cases} -$$ - -where $f[0][0] = \text{true}$ indicates that an empty string is an interleaving string of two empty strings. - -The answer is $f[m][n]$. - -The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the lengths of strings $s_1$ and $s_2$ respectively. - -We notice that the state $f[i][j]$ is only related to the states $f[i - 1][j]$, $f[i][j - 1]$, and $f[i - 1][j - 1]$. Therefore, we can use a rolling array to optimize the space complexity, reducing the original space complexity from $O(m \times n)$ to $O(n)$. - -### **Python3** - ```python class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: @@ -124,43 +100,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def isInterleave(self, s1: str, s2: str, s3: str) -> bool: - m, n = len(s1), len(s2) - if m + n != len(s3): - return False - f = [[False] * (n + 1) for _ in range(m + 1)] - f[0][0] = True - for i in range(m + 1): - for j in range(n + 1): - k = i + j - 1 - if i and s1[i - 1] == s3[k]: - f[i][j] = f[i - 1][j] - if j and s2[j - 1] == s3[k]: - f[i][j] |= f[i][j - 1] - return f[m][n] -``` - -```python -class Solution: - def isInterleave(self, s1: str, s2: str, s3: str) -> bool: - m, n = len(s1), len(s2) - if m + n != len(s3): - return False - f = [True] + [False] * n - for i in range(m + 1): - for j in range(n + 1): - k = i + j - 1 - if i: - f[j] &= s1[i - 1] == s3[k] - if j: - f[j] |= f[j - 1] and s2[j - 1] == s3[k] - return f[n] -``` - -### **Java** - ```java class Solution { private Map, Boolean> f = new HashMap<>(); @@ -204,58 +143,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isInterleave(String s1, String s2, String s3) { - int m = s1.length(), n = s2.length(); - if (m + n != s3.length()) { - return false; - } - boolean[][] f = new boolean[m + 1][n + 1]; - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i > 0 && s1.charAt(i - 1) == s3.charAt(k)) { - f[i][j] = f[i - 1][j]; - } - if (j > 0 && s2.charAt(j - 1) == s3.charAt(k)) { - f[i][j] |= f[i][j - 1]; - } - } - } - return f[m][n]; - } -} -``` - -```java -class Solution { - public boolean isInterleave(String s1, String s2, String s3) { - int m = s1.length(), n = s2.length(); - if (m + n != s3.length()) { - return false; - } - boolean[] f = new boolean[n + 1]; - f[0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i > 0) { - f[j] &= s1.charAt(i - 1) == s3.charAt(k); - } - if (j > 0) { - f[j] |= (f[j - 1] & s2.charAt(j - 1) == s3.charAt(k)); - } - } - } - return f[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -287,62 +174,58 @@ public: }; ``` -```cpp -class Solution { -public: - bool isInterleave(string s1, string s2, string s3) { - int m = s1.size(), n = s2.size(); - if (m + n != s3.size()) { - return false; - } - bool f[m + 1][n + 1]; - memset(f, false, sizeof(f)); - f[0][0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i > 0 && s1[i - 1] == s3[k]) { - f[i][j] = f[i - 1][j]; - } - if (j > 0 && s2[j - 1] == s3[k]) { - f[i][j] |= f[i][j - 1]; - } - } - } - return f[m][n]; - } -}; +```go +func isInterleave(s1 string, s2 string, s3 string) bool { + m, n := len(s1), len(s2) + if m+n != len(s3) { + return false + } + + f := map[int]bool{} + var dfs func(int, int) bool + dfs = func(i, j int) bool { + if i >= m && j >= n { + return true + } + if v, ok := f[i*200+j]; ok { + return v + } + k := i + j + f[i*200+j] = (i < m && s1[i] == s3[k] && dfs(i+1, j)) || (j < n && s2[j] == s3[k] && dfs(i, j+1)) + return f[i*200+j] + } + return dfs(0, 0) +} ``` -```cpp -class Solution { -public: - bool isInterleave(string s1, string s2, string s3) { - int m = s1.size(), n = s2.size(); - if (m + n != s3.size()) { - return false; +```ts +function isInterleave(s1: string, s2: string, s3: string): boolean { + const m = s1.length; + const n = s2.length; + if (m + n !== s3.length) { + return false; + } + const f: number[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); + const dfs = (i: number, j: number): boolean => { + if (i >= m && j >= n) { + return true; } - bool f[n + 1]; - memset(f, false, sizeof(f)); - f[0] = true; - for (int i = 0; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - int k = i + j - 1; - if (i) { - f[j] &= s1[i - 1] == s3[k]; - } - if (j) { - f[j] |= (s2[j - 1] == s3[k] && f[j - 1]); - } - } + if (f[i][j]) { + return f[i][j] === 1; } - return f[n]; - } -}; + f[i][j] = -1; + if (i < m && s1[i] === s3[i + j] && dfs(i + 1, j)) { + f[i][j] = 1; + } + if (f[i][j] === -1 && j < n && s2[j] === s3[i + j] && dfs(i, j + 1)) { + f[i][j] = 1; + } + return f[i][j] === 1; + }; + return dfs(0, 0); +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -411,108 +294,166 @@ impl Solution { } ``` -### **Go** - -```go -func isInterleave(s1 string, s2 string, s3 string) bool { - m, n := len(s1), len(s2) - if m+n != len(s3) { - return false - } +```cs +public class Solution { + private int m; + private int n; + private string s1; + private string s2; + private string s3; + private int[,] f; - f := map[int]bool{} - var dfs func(int, int) bool - dfs = func(i, j int) bool { - if i >= m && j >= n { - return true - } - if v, ok := f[i*200+j]; ok { - return v - } - k := i + j - f[i*200+j] = (i < m && s1[i] == s3[k] && dfs(i+1, j)) || (j < n && s2[j] == s3[k] && dfs(i, j+1)) - return f[i*200+j] - } - return dfs(0, 0) -} -``` + public bool IsInterleave(string s1, string s2, string s3) { + m = s1.Length; + n = s2.Length; + if (m + n != s3.Length) { + return false; + } + this.s1 = s1; + this.s2 = s2; + this.s3 = s3; + f = new int[m + 1, n + 1]; + return dfs(0, 0); + } -```go -func isInterleave(s1 string, s2 string, s3 string) bool { - m, n := len(s1), len(s2) - if m+n != len(s3) { - return false - } - f := make([][]bool, m+1) - for i := range f { - f[i] = make([]bool, n+1) - } - f[0][0] = true - for i := 0; i <= m; i++ { - for j := 0; j <= n; j++ { - k := i + j - 1 - if i > 0 && s1[i-1] == s3[k] { - f[i][j] = f[i-1][j] - } - if j > 0 && s2[j-1] == s3[k] { - f[i][j] = (f[i][j] || f[i][j-1]) - } - } - } - return f[m][n] + private bool dfs(int i, int j) { + if (i >= m && j >= n) { + return true; + } + if (f[i, j] != 0) { + return f[i, j] == 1; + } + f[i, j] = -1; + if (i < m && s1[i] == s3[i + j] && dfs(i + 1, j)) { + f[i, j] = 1; + } + if (f[i, j] == -1 && j < n && s2[j] == s3[i + j] && dfs(i, j + 1)) { + f[i, j] = 1; + } + return f[i, j] == 1; + } } ``` + + +### Solution 2: Dynamic Programming + +We can convert the memoization search in Solution 1 into dynamic programming. + +We define $f[i][j]$ to represent whether the first $i$ characters of string $s_1$ and the first $j$ characters of string $s_2$ can interleave to form the first $i + j$ characters of string $s_3$. When transitioning states, we can consider whether the current character is obtained from the last character of $s_1$ or the last character of $s_2$. Therefore, we have the state transition equation: + +$$ +f[i][j] = \begin{cases} +f[i - 1][j] & \text{if } s_1[i - 1] = s_3[i + j - 1] \\ +\text{or } f[i][j - 1] & \text{if } s_2[j - 1] = s_3[i + j - 1] \\ +\text{false} & \text{otherwise} +\end{cases} +$$ + +where $f[0][0] = \text{true}$ indicates that an empty string is an interleaving string of two empty strings. + +The answer is $f[m][n]$. + +The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the lengths of strings $s_1$ and $s_2$ respectively. + +We notice that the state $f[i][j]$ is only related to the states $f[i - 1][j]$, $f[i][j - 1]$, and $f[i - 1][j - 1]$. Therefore, we can use a rolling array to optimize the space complexity, reducing the original space complexity from $O(m \times n)$ to $O(n)$. + + + +```python +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + m, n = len(s1), len(s2) + if m + n != len(s3): + return False + f = [[False] * (n + 1) for _ in range(m + 1)] + f[0][0] = True + for i in range(m + 1): + for j in range(n + 1): + k = i + j - 1 + if i and s1[i - 1] == s3[k]: + f[i][j] = f[i - 1][j] + if j and s2[j - 1] == s3[k]: + f[i][j] |= f[i][j - 1] + return f[m][n] +``` + +```java +class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + int m = s1.length(), n = s2.length(); + if (m + n != s3.length()) { + return false; + } + boolean[][] f = new boolean[m + 1][n + 1]; + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1.charAt(i - 1) == s3.charAt(k)) { + f[i][j] = f[i - 1][j]; + } + if (j > 0 && s2.charAt(j - 1) == s3.charAt(k)) { + f[i][j] |= f[i][j - 1]; + } + } + } + return f[m][n]; + } +} +``` + +```cpp +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + int m = s1.size(), n = s2.size(); + if (m + n != s3.size()) { + return false; + } + bool f[m + 1][n + 1]; + memset(f, false, sizeof(f)); + f[0][0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1[i - 1] == s3[k]) { + f[i][j] = f[i - 1][j]; + } + if (j > 0 && s2[j - 1] == s3[k]) { + f[i][j] |= f[i][j - 1]; + } + } + } + return f[m][n]; + } +}; +``` + ```go func isInterleave(s1 string, s2 string, s3 string) bool { m, n := len(s1), len(s2) if m+n != len(s3) { return false } - f := make([]bool, n+1) - f[0] = true + f := make([][]bool, m+1) + for i := range f { + f[i] = make([]bool, n+1) + } + f[0][0] = true for i := 0; i <= m; i++ { for j := 0; j <= n; j++ { k := i + j - 1 - if i > 0 { - f[j] = (f[j] && s1[i-1] == s3[k]) + if i > 0 && s1[i-1] == s3[k] { + f[i][j] = f[i-1][j] } - if j > 0 { - f[j] = (f[j] || (s2[j-1] == s3[k] && f[j-1])) + if j > 0 && s2[j-1] == s3[k] { + f[i][j] = (f[i][j] || f[i][j-1]) } } } - return f[n] -} -``` - -### **TypeScript** - -```ts -function isInterleave(s1: string, s2: string, s3: string): boolean { - const m = s1.length; - const n = s2.length; - if (m + n !== s3.length) { - return false; - } - const f: number[][] = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); - const dfs = (i: number, j: number): boolean => { - if (i >= m && j >= n) { - return true; - } - if (f[i][j]) { - return f[i][j] === 1; - } - f[i][j] = -1; - if (i < m && s1[i] === s3[i + j] && dfs(i + 1, j)) { - f[i][j] = 1; - } - if (f[i][j] === -1 && j < n && s2[j] === s3[i + j] && dfs(i, j + 1)) { - f[i][j] = 1; - } - return f[i][j] === 1; - }; - return dfs(0, 0); + return f[m][n] } ``` @@ -540,95 +481,150 @@ function isInterleave(s1: string, s2: string, s3: string): boolean { } ``` -```ts -function isInterleave(s1: string, s2: string, s3: string): boolean { - const m = s1.length; - const n = s2.length; - if (m + n !== s3.length) { - return false; - } - const f: boolean[] = new Array(n + 1).fill(false); - f[0] = true; - for (let i = 0; i <= m; ++i) { - for (let j = 0; j <= n; ++j) { - const k = i + j - 1; - if (i) { - f[j] = f[j] && s1[i - 1] === s3[k]; - } - if (j) { - f[j] = f[j] || (f[j - 1] && s2[j - 1] === s3[k]); +```cs +public class Solution { + public bool IsInterleave(string s1, string s2, string s3) { + int m = s1.Length, n = s2.Length; + if (m + n != s3.Length) { + return false; + } + bool[,] f = new bool[m + 1, n + 1]; + f[0, 0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0 && s1[i - 1] == s3[k]) { + f[i, j] = f[i - 1, j]; + } + if (j > 0 && s2[j - 1] == s3[k]) { + f[i, j] |= f[i, j - 1]; + } } } + return f[m, n]; } - return f[n]; } ``` -### **C#** + -```cs -public class Solution { - private int m; - private int n; - private string s1; - private string s2; - private string s3; - private int[,] f; +### Solution 3 - public bool IsInterleave(string s1, string s2, string s3) { - m = s1.Length; - n = s2.Length; - if (m + n != s3.Length) { - return false; - } - this.s1 = s1; - this.s2 = s2; - this.s3 = s3; - f = new int[m + 1, n + 1]; - return dfs(0, 0); - } + - private bool dfs(int i, int j) { - if (i >= m && j >= n) { - return true; - } - if (f[i, j] != 0) { - return f[i, j] == 1; - } - f[i, j] = -1; - if (i < m && s1[i] == s3[i + j] && dfs(i + 1, j)) { - f[i, j] = 1; +```python +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + m, n = len(s1), len(s2) + if m + n != len(s3): + return False + f = [True] + [False] * n + for i in range(m + 1): + for j in range(n + 1): + k = i + j - 1 + if i: + f[j] &= s1[i - 1] == s3[k] + if j: + f[j] |= f[j - 1] and s2[j - 1] == s3[k] + return f[n] +``` + +```java +class Solution { + public boolean isInterleave(String s1, String s2, String s3) { + int m = s1.length(), n = s2.length(); + if (m + n != s3.length()) { + return false; } - if (f[i, j] == -1 && j < n && s2[j] == s3[i + j] && dfs(i, j + 1)) { - f[i, j] = 1; + boolean[] f = new boolean[n + 1]; + f[0] = true; + for (int i = 0; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + int k = i + j - 1; + if (i > 0) { + f[j] &= s1.charAt(i - 1) == s3.charAt(k); + } + if (j > 0) { + f[j] |= (f[j - 1] & s2.charAt(j - 1) == s3.charAt(k)); + } + } } - return f[i, j] == 1; + return f[n]; } } ``` -```cs -public class Solution { - public bool IsInterleave(string s1, string s2, string s3) { - int m = s1.Length, n = s2.Length; - if (m + n != s3.Length) { +```cpp +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + int m = s1.size(), n = s2.size(); + if (m + n != s3.size()) { return false; } - bool[,] f = new bool[m + 1, n + 1]; - f[0, 0] = true; + bool f[n + 1]; + memset(f, false, sizeof(f)); + f[0] = true; for (int i = 0; i <= m; ++i) { for (int j = 0; j <= n; ++j) { int k = i + j - 1; - if (i > 0 && s1[i - 1] == s3[k]) { - f[i, j] = f[i - 1, j]; + if (i) { + f[j] &= s1[i - 1] == s3[k]; } - if (j > 0 && s2[j - 1] == s3[k]) { - f[i, j] |= f[i, j - 1]; + if (j) { + f[j] |= (s2[j - 1] == s3[k] && f[j - 1]); } } } - return f[m, n]; + return f[n]; } +}; +``` + +```go +func isInterleave(s1 string, s2 string, s3 string) bool { + m, n := len(s1), len(s2) + if m+n != len(s3) { + return false + } + f := make([]bool, n+1) + f[0] = true + for i := 0; i <= m; i++ { + for j := 0; j <= n; j++ { + k := i + j - 1 + if i > 0 { + f[j] = (f[j] && s1[i-1] == s3[k]) + } + if j > 0 { + f[j] = (f[j] || (s2[j-1] == s3[k] && f[j-1])) + } + } + } + return f[n] +} +``` + +```ts +function isInterleave(s1: string, s2: string, s3: string): boolean { + const m = s1.length; + const n = s2.length; + if (m + n !== s3.length) { + return false; + } + const f: boolean[] = new Array(n + 1).fill(false); + f[0] = true; + for (let i = 0; i <= m; ++i) { + for (let j = 0; j <= n; ++j) { + const k = i + j - 1; + if (i) { + f[j] = f[j] && s1[i - 1] === s3[k]; + } + if (j) { + f[j] = f[j] || (f[j - 1] && s2[j - 1] === s3[k]); + } + } + } + return f[n]; } ``` @@ -657,10 +653,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0098.Validate Binary Search Tree/README.md b/solution/0000-0099/0098.Validate Binary Search Tree/README.md index 9b4954d7df768..465b4db67b1d9 100644 --- a/solution/0000-0099/0098.Validate Binary Search Tree/README.md +++ b/solution/0000-0099/0098.Validate Binary Search Tree/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 中序遍历,若是一个有效的二叉搜索树,那么遍历到的序列应该是单调递增的。所以只要比较判断遍历到的当前数是否大于上一个数即可。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -86,29 +80,6 @@ class Solution: return dfs(root) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def isValidBST(self, root: Optional[TreeNode]) -> bool: - def dfs(root, l, r): - if root is None: - return True - if root.val <= l or root.val >= r: - return False - return dfs(root.left, l, root.val) and dfs(root.right, root.val, r) - - return dfs(root, -inf, inf) -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -152,41 +123,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public boolean isValidBST(TreeNode root) { - return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE); - } - - private boolean dfs(TreeNode root, long l, long r) { - if (root == null) { - return true; - } - if (root.val <= l || root.val >= r) { - return false; - } - return dfs(root.left, l, root.val) && dfs(root.right, root.val, r); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -219,34 +155,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool isValidBST(TreeNode* root) { - return dfs(root, LONG_MIN, LONG_MAX); - } - - bool dfs(TreeNode* root, long long l, long long r) { - if (!root) return true; - if (root->val <= l || root->val >= r) return false; - return dfs(root->left, l, root->val) && dfs(root->right, root->val, r); - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -281,33 +189,6 @@ func isValidBST(root *TreeNode) bool { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func isValidBST(root *TreeNode) bool { - return dfs(root, math.MinInt64, math.MaxInt64) -} - -func dfs(root *TreeNode, l, r int64) bool { - if root == nil { - return true - } - v := int64(root.Val) - if v <= l || v >= r { - return false - } - return dfs(root.Left, l, v) && dfs(root.Right, v, r) -} -``` - -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -345,35 +226,6 @@ var isValidBST = function (root) { }; ``` -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {boolean} - */ -var isValidBST = function (root) { - function dfs(root, l, r) { - if (!root) { - return true; - } - if (root.val <= l || root.val >= r) { - return false; - } - return dfs(root.left, l, root.val) && dfs(root.right, root.val, r); - } - return dfs(root, -Infinity, Infinity); -}; -``` - -### **C#** - ```cs /** * Definition for a binary tree node. @@ -419,6 +271,142 @@ public class Solution { } ``` + + +### 方法二 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isValidBST(self, root: Optional[TreeNode]) -> bool: + def dfs(root, l, r): + if root is None: + return True + if root.val <= l or root.val >= r: + return False + return dfs(root.left, l, root.val) and dfs(root.right, root.val, r) + + return dfs(root, -inf, inf) +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean isValidBST(TreeNode root) { + return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE); + } + + private boolean dfs(TreeNode root, long l, long r) { + if (root == null) { + return true; + } + if (root.val <= l || root.val >= r) { + return false; + } + return dfs(root.left, l, root.val) && dfs(root.right, root.val, r); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isValidBST(TreeNode* root) { + return dfs(root, LONG_MIN, LONG_MAX); + } + + bool dfs(TreeNode* root, long long l, long long r) { + if (!root) return true; + if (root->val <= l || root->val >= r) return false; + return dfs(root->left, l, root->val) && dfs(root->right, root->val, r); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isValidBST(root *TreeNode) bool { + return dfs(root, math.MinInt64, math.MaxInt64) +} + +func dfs(root *TreeNode, l, r int64) bool { + if root == nil { + return true + } + v := int64(root.Val) + if v <= l || v >= r { + return false + } + return dfs(root.Left, l, v) && dfs(root.Right, v, r) +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isValidBST = function (root) { + function dfs(root, l, r) { + if (!root) { + return true; + } + if (root.val <= l || root.val >= r) { + return false; + } + return dfs(root.left, l, root.val) && dfs(root.right, root.val, r); + } + return dfs(root, -Infinity, Infinity); +}; +``` + ```cs /** * Definition for a binary tree node. @@ -450,10 +438,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0098.Validate Binary Search Tree/README_EN.md b/solution/0000-0099/0098.Validate Binary Search Tree/README_EN.md index 04f0858e94a9e..841e13600f086 100644 --- a/solution/0000-0099/0098.Validate Binary Search Tree/README_EN.md +++ b/solution/0000-0099/0098.Validate Binary Search Tree/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion In-order traversal. If it is a valid binary search tree, then the sequence traversed should be monotonically increasing. So, we only need to compare and judge whether the current number traversed is greater than the previous number. @@ -50,8 +50,6 @@ 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: @@ -78,27 +76,6 @@ class Solution: return dfs(root) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def isValidBST(self, root: Optional[TreeNode]) -> bool: - def dfs(root, l, r): - if root is None: - return True - if root.val <= l or root.val >= r: - return False - return dfs(root.left, l, root.val) and dfs(root.right, root.val, r) - - return dfs(root, -inf, inf) -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -142,41 +119,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public boolean isValidBST(TreeNode root) { - return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE); - } - - private boolean dfs(TreeNode root, long l, long r) { - if (root == null) { - return true; - } - if (root.val <= l || root.val >= r) { - return false; - } - return dfs(root.left, l, root.val) && dfs(root.right, root.val, r); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -209,34 +151,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool isValidBST(TreeNode* root) { - return dfs(root, LONG_MIN, LONG_MAX); - } - - bool dfs(TreeNode* root, long long l, long long r) { - if (!root) return true; - if (root->val <= l || root->val >= r) return false; - return dfs(root->left, l, root->val) && dfs(root->right, root->val, r); - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -271,33 +185,6 @@ func isValidBST(root *TreeNode) bool { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func isValidBST(root *TreeNode) bool { - return dfs(root, math.MinInt64, math.MaxInt64) -} - -func dfs(root *TreeNode, l, r int64) bool { - if root == nil { - return true - } - v := int64(root.Val) - if v <= l || v >= r { - return false - } - return dfs(root.Left, l, v) && dfs(root.Right, v, r) -} -``` - -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -335,35 +222,6 @@ var isValidBST = function (root) { }; ``` -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {boolean} - */ -var isValidBST = function (root) { - function dfs(root, l, r) { - if (!root) { - return true; - } - if (root.val <= l || root.val >= r) { - return false; - } - return dfs(root.left, l, root.val) && dfs(root.right, root.val, r); - } - return dfs(root, -Infinity, Infinity); -}; -``` - -### **C#** - ```cs /** * Definition for a binary tree node. @@ -409,6 +267,142 @@ public class Solution { } ``` + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isValidBST(self, root: Optional[TreeNode]) -> bool: + def dfs(root, l, r): + if root is None: + return True + if root.val <= l or root.val >= r: + return False + return dfs(root.left, l, root.val) and dfs(root.right, root.val, r) + + return dfs(root, -inf, inf) +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean isValidBST(TreeNode root) { + return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE); + } + + private boolean dfs(TreeNode root, long l, long r) { + if (root == null) { + return true; + } + if (root.val <= l || root.val >= r) { + return false; + } + return dfs(root.left, l, root.val) && dfs(root.right, root.val, r); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isValidBST(TreeNode* root) { + return dfs(root, LONG_MIN, LONG_MAX); + } + + bool dfs(TreeNode* root, long long l, long long r) { + if (!root) return true; + if (root->val <= l || root->val >= r) return false; + return dfs(root->left, l, root->val) && dfs(root->right, root->val, r); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isValidBST(root *TreeNode) bool { + return dfs(root, math.MinInt64, math.MaxInt64) +} + +func dfs(root *TreeNode, l, r int64) bool { + if root == nil { + return true + } + v := int64(root.Val) + if v <= l || v >= r { + return false + } + return dfs(root.Left, l, v) && dfs(root.Right, v, r) +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isValidBST = function (root) { + function dfs(root, l, r) { + if (!root) { + return true; + } + if (root.val <= l || root.val >= r) { + return false; + } + return dfs(root.left, l, root.val) && dfs(root.right, root.val, r); + } + return dfs(root, -Infinity, Infinity); +}; +``` + ```cs /** * Definition for a binary tree node. @@ -440,10 +434,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0000-0099/0099.Recover Binary Search Tree/README.md b/solution/0000-0099/0099.Recover Binary Search Tree/README.md index 06ac9c57c67a1..85f7120230d01 100644 --- a/solution/0000-0099/0099.Recover Binary Search Tree/README.md +++ b/solution/0000-0099/0099.Recover Binary Search Tree/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:中序遍历** +### 方法一:中序遍历 中序遍历二叉搜索树,得到的序列是递增的。如果有两个节点的值被错误地交换,那么中序遍历得到的序列中,一定会出现两个逆序对。我们用 `first` 和 `second` 分别记录这两个逆序对中较小值和较大值的节点,最后交换这两个节点的值即可。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -84,10 +78,6 @@ class Solution: first.val, second.val = second.val, first.val ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -202,51 +188,6 @@ func recoverTree(root *TreeNode) { } ``` -### **C#** - -```cs -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -public class Solution { - private TreeNode prev, first, second; - - public void RecoverTree(TreeNode root) { - dfs(root); - int t = first.val; - first.val = second.val; - second.val = t; - } - - private void dfs(TreeNode root) { - if (root == null) { - return; - } - dfs(root.left); - if (prev != null && prev.val > root.val) { - if (first == null) { - first = prev; - } - second = root; - } - prev = root; - dfs(root.right); - } -} -``` - -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -285,10 +226,47 @@ var recoverTree = function (root) { }; ``` -### **...** +```cs +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + private TreeNode prev, first, second; -``` + public void RecoverTree(TreeNode root) { + dfs(root); + int t = first.val; + first.val = second.val; + second.val = t; + } + private void dfs(TreeNode root) { + if (root == null) { + return; + } + dfs(root.left); + if (prev != null && prev.val > root.val) { + if (first == null) { + first = prev; + } + second = root; + } + prev = root; + dfs(root.right); + } +} ``` + + diff --git a/solution/0000-0099/0099.Recover Binary Search Tree/README_EN.md b/solution/0000-0099/0099.Recover Binary Search Tree/README_EN.md index a3ef9ad62942b..4355d0e4abe8d 100644 --- a/solution/0000-0099/0099.Recover Binary Search Tree/README_EN.md +++ b/solution/0000-0099/0099.Recover Binary Search Tree/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: In-order Traversal** +### Solution 1: In-order Traversal In-order traversal of a binary search tree results in an increasing sequence. If two nodes' values are mistakenly swapped, there will definitely be two reverse pairs in the sequence obtained from the in-order traversal. We use `first` and `second` to record the smaller and larger values of these two reverse pairs, respectively. Finally, swapping the values of these two nodes will correct the mistake. @@ -44,8 +44,6 @@ 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: @@ -76,8 +74,6 @@ class Solution: first.val, second.val = second.val, first.val ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -123,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -159,8 +153,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -192,51 +184,6 @@ func recoverTree(root *TreeNode) { } ``` -### **C#** - -```cs -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -public class Solution { - private TreeNode prev, first, second; - - public void RecoverTree(TreeNode root) { - dfs(root); - int t = first.val; - first.val = second.val; - second.val = t; - } - - private void dfs(TreeNode root) { - if (root == null) { - return; - } - dfs(root.left); - if (prev != null && prev.val > root.val) { - if (first == null) { - first = prev; - } - second = root; - } - prev = root; - dfs(root.right); - } -} -``` - -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -275,10 +222,47 @@ var recoverTree = function (root) { }; ``` -### **...** +```cs +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + private TreeNode prev, first, second; -``` + public void RecoverTree(TreeNode root) { + dfs(root); + int t = first.val; + first.val = second.val; + second.val = t; + } + private void dfs(TreeNode root) { + if (root == null) { + return; + } + dfs(root.left); + if (prev != null && prev.val > root.val) { + if (first == null) { + first = prev; + } + second = root; + } + prev = root; + dfs(root.right); + } +} ``` + + diff --git a/solution/0100-0199/0100.Same Tree/README.md b/solution/0100-0199/0100.Same Tree/README.md index 11ff1245648ae..61308d525a479 100644 --- a/solution/0100-0199/0100.Same Tree/README.md +++ b/solution/0100-0199/0100.Same Tree/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们可以使用 DFS 递归的方法来解决这个问题。 @@ -54,22 +52,8 @@ 时间复杂度 $O(\min(m, n))$,空间复杂度 $O(\min(m, n))$。其中 $m$ 和 $n$ 分别是两个二叉树的节点个数。空间复杂度主要取决于递归调用的层数,递归调用的层数不会超过较小的二叉树的节点个数。 -**方法二:BFS** - -我们也可以使用 BFS 迭代的方法来解决这个问题。 - -首先将两个二叉树的根节点分别加入两个队列。每次从两个队列各取出一个节点,进行如下比较操作。如果两个节点的值不相同,则两个二叉树的结构一定不同,如果两个节点的值相同,则判断两个节点的子节点是否为空,如果只有一个节点的左子节点为空,则两个二叉树的结构一定不同,如果只有一个节点的右子节点为空,则两个二叉树的结构一定不同,如果左右子节点的结构相同,则将两个节点的左子节点和右子节点分别加入两个队列,对于下一次迭代,将从两个队列各取出一个节点进行比较。当两个队列同时为空时,说明我们已经比较完了所有节点,两个二叉树的结构完全相同。 - -时间复杂度 $O(\min(m, n))$,空间复杂度 $O(\min(m, n))$。其中 $m$ 和 $n$ 分别是两个二叉树的节点个数。空间复杂度主要取决于队列中的元素个数,队列中的元素个数不会超过较小的二叉树的节点个数。 - -### **Python3** - - - -DFS: - ```python # Definition for a binary tree node. # class TreeNode: @@ -86,7 +70,211 @@ class Solution: return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) ``` -BFS: +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + if (p == q) return true; + if (p == null || q == null || p.val != q.val) return false; + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q) { + if (p == q) return true; + if (!p || !q || p->val != q->val) return false; + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isSameTree(p *TreeNode, q *TreeNode) bool { + if p == q { + return true + } + if p == nil || q == nil || p.Val != q.Val { + return false + } + return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) +} +``` + +```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 isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { + if (p == null && q == null) { + return true; + } + if (p == null || q == null || p.val !== q.val) { + return false; + } + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(p: &Option>>, q: &Option>>) -> bool { + if p.is_none() && q.is_none() { + return true; + } + if p.is_none() || q.is_none() { + return false; + } + let r1 = p.as_ref().unwrap().borrow(); + let r2 = q.as_ref().unwrap().borrow(); + r1.val == r2.val && Self::dfs(&r1.left, &r2.left) && Self::dfs(&r1.right, &r2.right) + } + + pub fn is_same_tree( + p: Option>>, + q: Option>> + ) -> bool { + Self::dfs(&p, &q) + } +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} p + * @param {TreeNode} q + * @return {boolean} + */ +var isSameTree = function (p, q) { + if (!p && !q) return true; + if (p && q) { + return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } + return false; +}; +``` + +```php +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($val = 0, $left = null, $right = null) { + * $this->val = $val; + * $this->left = $left; + * $this->right = $right; + * } + * } + */ +class Solution { + /** + * @param TreeNode $p + * @param TreeNode $q + * @return Boolean + */ + function isSameTree($p, $q) { + if ($p == null && $q == null) { + return true; + } + if ($p == null || $q == null) { + return false; + } + if ($p->val != $q->val) { + return false; + } + return $this->isSameTree($p->left, $q->left) && $this->isSameTree($p->right, $q->right); + } +} +``` + + + +### 方法二:BFS + +我们也可以使用 BFS 迭代的方法来解决这个问题。 + +首先将两个二叉树的根节点分别加入两个队列。每次从两个队列各取出一个节点,进行如下比较操作。如果两个节点的值不相同,则两个二叉树的结构一定不同,如果两个节点的值相同,则判断两个节点的子节点是否为空,如果只有一个节点的左子节点为空,则两个二叉树的结构一定不同,如果只有一个节点的右子节点为空,则两个二叉树的结构一定不同,如果左右子节点的结构相同,则将两个节点的左子节点和右子节点分别加入两个队列,对于下一次迭代,将从两个队列各取出一个节点进行比较。当两个队列同时为空时,说明我们已经比较完了所有节点,两个二叉树的结构完全相同。 + +时间复杂度 $O(\min(m, n))$,空间复杂度 $O(\min(m, n))$。其中 $m$ 和 $n$ 分别是两个二叉树的节点个数。空间复杂度主要取决于队列中的元素个数,队列中的元素个数不会超过较小的二叉树的节点个数。 + + ```python # Definition for a binary tree node. @@ -121,35 +309,6 @@ class Solution: return True ``` -### **Java** - - - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public boolean isSameTree(TreeNode p, TreeNode q) { - if (p == q) return true; - if (p == null || q == null || p.val != q.val) return false; - return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); - } -} -``` - ```java /** * Definition for a binary tree node. @@ -206,30 +365,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool isSameTree(TreeNode* p, TreeNode* q) { - if (p == q) return true; - if (!p || !q || p->val != q->val) return false; - return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -273,28 +408,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func isSameTree(p *TreeNode, q *TreeNode) bool { - if p == q { - return true - } - if p == nil || q == nil || p.Val != q.Val { - return false - } - return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) -} -``` - ```go /** * Definition for a binary tree node. @@ -340,59 +453,6 @@ func isSameTree(p *TreeNode, q *TreeNode) bool { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} p - * @param {TreeNode} q - * @return {boolean} - */ -var isSameTree = function (p, q) { - if (!p && !q) return true; - if (p && q) { - return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); - } - return false; -}; -``` - -### **TypeScript** - -```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 isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { - if (p == null && q == null) { - return true; - } - if (p == null || q == null || p.val !== q.val) { - return false; - } - return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); -} -``` - ```ts /** * Definition for a binary tree node. @@ -447,51 +507,6 @@ function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { } ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(p: &Option>>, q: &Option>>) -> bool { - if p.is_none() && q.is_none() { - return true; - } - if p.is_none() || q.is_none() { - return false; - } - let r1 = p.as_ref().unwrap().borrow(); - let r2 = q.as_ref().unwrap().borrow(); - r1.val == r2.val && Self::dfs(&r1.left, &r2.left) && Self::dfs(&r1.right, &r2.right) - } - - pub fn is_same_tree( - p: Option>>, - q: Option>> - ) -> bool { - Self::dfs(&p, &q) - } -} -``` - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -563,47 +578,6 @@ impl Solution { } ``` -### **PHP** - -```php -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($val = 0, $left = null, $right = null) { - * $this->val = $val; - * $this->left = $left; - * $this->right = $right; - * } - * } - */ -class Solution { - /** - * @param TreeNode $p - * @param TreeNode $q - * @return Boolean - */ - function isSameTree($p, $q) { - if ($p == null && $q == null) { - return true; - } - if ($p == null || $q == null) { - return false; - } - if ($p->val != $q->val) { - return false; - } - return $this->isSameTree($p->left, $q->left) && $this->isSameTree($p->right, $q->right); - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0100.Same Tree/README_EN.md b/solution/0100-0199/0100.Same Tree/README_EN.md index 810adfe685677..5cb157c8097ef 100644 --- a/solution/0100-0199/0100.Same Tree/README_EN.md +++ b/solution/0100-0199/0100.Same Tree/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We can use the DFS recursive method to solve this problem. @@ -48,18 +48,8 @@ First, determine whether the root nodes of the two binary trees are the same. If The time complexity is $O(\min(m, n))$, and the space complexity is $O(\min(m, n))$. Here, $m$ and $n$ are the number of nodes in the two binary trees, respectively. The space complexity mainly depends on the number of layers of recursive calls, which will not exceed the number of nodes in the smaller binary tree. -**Solution 2: BFS** - -We can also use the BFS iterative method to solve this problem. - -First, add the root nodes of the two binary trees to two queues. Each time, take out one node from each of the two queues and perform the following comparison operations. If the values of the two nodes are not the same, then the structures of the two binary trees are definitely different. If the values of the two nodes are the same, then determine whether the child nodes of the two nodes are null. If only the left child node of one node is null, then the structures of the two binary trees are definitely different. If only the right child node of one node is null, then the structures of the two binary trees are definitely different. If the structures of the left and right child nodes are the same, then add the left and right child nodes of the two nodes to the two queues respectively. For the next iteration, take out one node from each of the two queues for comparison. When both queues are empty at the same time, it means that we have compared all the nodes, and the structures of the two binary trees are completely the same. - -The time complexity is $O(\min(m, n))$, and the space complexity is $O(\min(m, n))$. Here, $m$ and $n$ are the number of nodes in the two binary trees, respectively. The space complexity mainly depends on the number of elements in the queue, which will not exceed the number of nodes in the smaller binary tree. - -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -76,6 +66,212 @@ class Solution: return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) ``` +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + if (p == q) return true; + if (p == null || q == null || p.val != q.val) return false; + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q) { + if (p == q) return true; + if (!p || !q || p->val != q->val) return false; + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isSameTree(p *TreeNode, q *TreeNode) bool { + if p == q { + return true + } + if p == nil || q == nil || p.Val != q.Val { + return false + } + return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) +} +``` + +```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 isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { + if (p == null && q == null) { + return true; + } + if (p == null || q == null || p.val !== q.val) { + return false; + } + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(p: &Option>>, q: &Option>>) -> bool { + if p.is_none() && q.is_none() { + return true; + } + if p.is_none() || q.is_none() { + return false; + } + let r1 = p.as_ref().unwrap().borrow(); + let r2 = q.as_ref().unwrap().borrow(); + r1.val == r2.val && Self::dfs(&r1.left, &r2.left) && Self::dfs(&r1.right, &r2.right) + } + + pub fn is_same_tree( + p: Option>>, + q: Option>> + ) -> bool { + Self::dfs(&p, &q) + } +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} p + * @param {TreeNode} q + * @return {boolean} + */ +var isSameTree = function (p, q) { + if (!p && !q) return true; + if (p && q) { + return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } + return false; +}; +``` + +```php +/** + * Definition for a binary tree node. + * class TreeNode { + * public $val = null; + * public $left = null; + * public $right = null; + * function __construct($val = 0, $left = null, $right = null) { + * $this->val = $val; + * $this->left = $left; + * $this->right = $right; + * } + * } + */ +class Solution { + /** + * @param TreeNode $p + * @param TreeNode $q + * @return Boolean + */ + function isSameTree($p, $q) { + if ($p == null && $q == null) { + return true; + } + if ($p == null || $q == null) { + return false; + } + if ($p->val != $q->val) { + return false; + } + return $this->isSameTree($p->left, $q->left) && $this->isSameTree($p->right, $q->right); + } +} +``` + + + +### Solution 2: BFS + +We can also use the BFS iterative method to solve this problem. + +First, add the root nodes of the two binary trees to two queues. Each time, take out one node from each of the two queues and perform the following comparison operations. If the values of the two nodes are not the same, then the structures of the two binary trees are definitely different. If the values of the two nodes are the same, then determine whether the child nodes of the two nodes are null. If only the left child node of one node is null, then the structures of the two binary trees are definitely different. If only the right child node of one node is null, then the structures of the two binary trees are definitely different. If the structures of the left and right child nodes are the same, then add the left and right child nodes of the two nodes to the two queues respectively. For the next iteration, take out one node from each of the two queues for comparison. When both queues are empty at the same time, it means that we have compared all the nodes, and the structures of the two binary trees are completely the same. + +The time complexity is $O(\min(m, n))$, and the space complexity is $O(\min(m, n))$. Here, $m$ and $n$ are the number of nodes in the two binary trees, respectively. The space complexity mainly depends on the number of elements in the queue, which will not exceed the number of nodes in the smaller binary tree. + + + ```python # Definition for a binary tree node. # class TreeNode: @@ -109,33 +305,6 @@ class Solution: return True ``` -### **Java** - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public boolean isSameTree(TreeNode p, TreeNode q) { - if (p == q) return true; - if (p == null || q == null || p.val != q.val) return false; - return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); - } -} -``` - ```java /** * Definition for a binary tree node. @@ -192,30 +361,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool isSameTree(TreeNode* p, TreeNode* q) { - if (p == q) return true; - if (!p || !q || p->val != q->val) return false; - return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -259,28 +404,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func isSameTree(p *TreeNode, q *TreeNode) bool { - if p == q { - return true - } - if p == nil || q == nil || p.Val != q.Val { - return false - } - return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) -} -``` - ```go /** * Definition for a binary tree node. @@ -326,59 +449,6 @@ func isSameTree(p *TreeNode, q *TreeNode) bool { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} p - * @param {TreeNode} q - * @return {boolean} - */ -var isSameTree = function (p, q) { - if (!p && !q) return true; - if (p && q) { - return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); - } - return false; -}; -``` - -### **TypeScript** - -```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 isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { - if (p == null && q == null) { - return true; - } - if (p == null || q == null || p.val !== q.val) { - return false; - } - return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); -} -``` - ```ts /** * Definition for a binary tree node. @@ -433,51 +503,6 @@ function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { } ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(p: &Option>>, q: &Option>>) -> bool { - if p.is_none() && q.is_none() { - return true; - } - if p.is_none() || q.is_none() { - return false; - } - let r1 = p.as_ref().unwrap().borrow(); - let r2 = q.as_ref().unwrap().borrow(); - r1.val == r2.val && Self::dfs(&r1.left, &r2.left) && Self::dfs(&r1.right, &r2.right) - } - - pub fn is_same_tree( - p: Option>>, - q: Option>> - ) -> bool { - Self::dfs(&p, &q) - } -} -``` - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -549,47 +574,6 @@ impl Solution { } ``` -### **PHP** - -```php -/** - * Definition for a binary tree node. - * class TreeNode { - * public $val = null; - * public $left = null; - * public $right = null; - * function __construct($val = 0, $left = null, $right = null) { - * $this->val = $val; - * $this->left = $left; - * $this->right = $right; - * } - * } - */ -class Solution { - /** - * @param TreeNode $p - * @param TreeNode $q - * @return Boolean - */ - function isSameTree($p, $q) { - if ($p == null && $q == null) { - return true; - } - if ($p == null || $q == null) { - return false; - } - if ($p->val != $q->val) { - return false; - } - return $this->isSameTree($p->left, $q->left) && $this->isSameTree($p->right, $q->right); - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0101.Symmetric Tree/README.md b/solution/0100-0199/0101.Symmetric Tree/README.md index 62652309f309a..224a73dc855cf 100644 --- a/solution/0100-0199/0101.Symmetric Tree/README.md +++ b/solution/0100-0199/0101.Symmetric Tree/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们设计一个函数 $dfs(root1, root2)$,用于判断两个二叉树是否对称。答案即为 $dfs(root, root)$。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -78,10 +72,6 @@ class Solution: return dfs(root, root) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -168,8 +154,6 @@ func isSymmetric(root *TreeNode) bool { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -200,8 +184,6 @@ function isSymmetric(root: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -245,6 +227,35 @@ impl Solution { } ``` +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isSymmetric = function (root) { + function dfs(root1, root2) { + if (!root1 && !root2) return true; + if (!root1 || !root2 || root1.val != root2.val) return false; + return dfs(root1.left, root2.right) && dfs(root1.right, root2.left); + } + return dfs(root, root); +}; +``` + + + +### 方法二 + + + ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -295,14 +306,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - -``` - -``` + diff --git a/solution/0100-0199/0101.Symmetric Tree/README_EN.md b/solution/0100-0199/0101.Symmetric Tree/README_EN.md index 3ab077e2c968e..c0b59c902e8ad 100644 --- a/solution/0100-0199/0101.Symmetric Tree/README_EN.md +++ b/solution/0100-0199/0101.Symmetric Tree/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion We design a function $dfs(root1, root2)$ to determine whether two binary trees are symmetric. The answer is $dfs(root, root)$. @@ -48,8 +48,6 @@ 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: @@ -69,8 +67,6 @@ class Solution: return dfs(root, root) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -131,8 +125,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -157,8 +149,6 @@ func isSymmetric(root *TreeNode) bool { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -189,8 +179,6 @@ function isSymmetric(root: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -234,6 +222,35 @@ impl Solution { } ``` +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isSymmetric = function (root) { + function dfs(root1, root2) { + if (!root1 && !root2) return true; + if (!root1 || !root2 || root1.val != root2.val) return false; + return dfs(root1.left, root2.right) && dfs(root1.right, root2.left); + } + return dfs(root, root); +}; +``` + + + +### Solution 2 + + + ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -284,10 +301,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0102.Binary Tree Level Order Traversal/README.md b/solution/0100-0199/0102.Binary Tree Level Order Traversal/README.md index 1e3974e3bcac6..196b6192d3462 100644 --- a/solution/0100-0199/0102.Binary Tree Level Order Traversal/README.md +++ b/solution/0100-0199/0102.Binary Tree Level Order Traversal/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们可以使用 BFS 的方法来解决这道题。首先将根节点入队,然后不断地进行以下操作,直到队列为空: @@ -57,10 +55,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -134,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -170,8 +158,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -205,43 +191,6 @@ func levelOrder(root *TreeNode) (ans [][]int) { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number[][]} - */ -var levelOrder = function (root) { - let ans = []; - if (!root) { - return ans; - } - let q = [root]; - while (q.length) { - let t = []; - for (let n = q.length; n; --n) { - const { val, left, right } = q.shift(); - t.push(val); - left && q.push(left); - right && q.push(right); - } - ans.push(t); - } - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -278,8 +227,6 @@ function levelOrder(root: TreeNode | null): number[][] { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -333,10 +280,39 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var levelOrder = function (root) { + let ans = []; + if (!root) { + return ans; + } + let q = [root]; + while (q.length) { + let t = []; + for (let n = q.length; n; --n) { + const { val, left, right } = q.shift(); + t.push(val); + left && q.push(left); + right && q.push(right); + } + ans.push(t); + } + return ans; +}; ``` + + diff --git a/solution/0100-0199/0102.Binary Tree Level Order Traversal/README_EN.md b/solution/0100-0199/0102.Binary Tree Level Order Traversal/README_EN.md index 87bc9f9e3c3fa..fc171d88c3c26 100644 --- a/solution/0100-0199/0102.Binary Tree Level Order Traversal/README_EN.md +++ b/solution/0100-0199/0102.Binary Tree Level Order Traversal/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: BFS** +### Solution 1: BFS We can use the BFS method to solve this problem. First, enqueue the root node, then continuously perform the following operations until the queue is empty: @@ -51,8 +51,6 @@ 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: @@ -79,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -124,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -160,8 +154,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -195,43 +187,6 @@ func levelOrder(root *TreeNode) (ans [][]int) { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number[][]} - */ -var levelOrder = function (root) { - let ans = []; - if (!root) { - return ans; - } - let q = [root]; - while (q.length) { - let t = []; - for (let n = q.length; n; --n) { - const { val, left, right } = q.shift(); - t.push(val); - left && q.push(left); - right && q.push(right); - } - ans.push(t); - } - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -268,8 +223,6 @@ function levelOrder(root: TreeNode | null): number[][] { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -323,10 +276,39 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var levelOrder = function (root) { + let ans = []; + if (!root) { + return ans; + } + let q = [root]; + while (q.length) { + let t = []; + for (let n = q.length; n; --n) { + const { val, left, right } = q.shift(); + t.push(val); + left && q.push(left); + right && q.push(right); + } + ans.push(t); + } + return ans; +}; ``` + + diff --git a/solution/0100-0199/0103.Binary Tree Zigzag Level Order Traversal/README.md b/solution/0100-0199/0103.Binary Tree Zigzag Level Order Traversal/README.md index 4393f75ea848b..e1bab36774c21 100644 --- a/solution/0100-0199/0103.Binary Tree Zigzag Level Order Traversal/README.md +++ b/solution/0100-0199/0103.Binary Tree Zigzag Level Order Traversal/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 为了实现锯齿形层序遍历,需要在层序遍历的基础上增加一个标志位 `left`,用于标记当前层的节点值的顺序。如果 `left` 为 `true`,则当前层的节点值按照从左到右的顺序存入结果数组 `ans` 中;如果 `left` 为 `false`,则当前层的节点值按照从右到左的顺序存入结果数组 `ans` 中。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -85,10 +79,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -176,8 +164,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -218,52 +204,6 @@ func zigzagLevelOrder(root *TreeNode) (ans [][]int) { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number[][]} - */ -var zigzagLevelOrder = function (root) { - const ans = []; - if (!root) { - return ans; - } - const q = [root]; - let left = 1; - while (q.length) { - const t = []; - for (let n = q.length; n; --n) { - const node = q.shift(); - t.push(node.val); - if (node.left) { - q.push(node.left); - } - if (node.right) { - q.push(node.right); - } - } - if (!left) { - t.reverse(); - } - ans.push(t); - left ^= 1; - } - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -300,8 +240,6 @@ function zigzagLevelOrder(root: TreeNode | null): number[][] { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -358,10 +296,48 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var zigzagLevelOrder = function (root) { + const ans = []; + if (!root) { + return ans; + } + const q = [root]; + let left = 1; + while (q.length) { + const t = []; + for (let n = q.length; n; --n) { + const node = q.shift(); + t.push(node.val); + if (node.left) { + q.push(node.left); + } + if (node.right) { + q.push(node.right); + } + } + if (!left) { + t.reverse(); + } + ans.push(t); + left ^= 1; + } + return ans; +}; ``` + + diff --git a/solution/0100-0199/0103.Binary Tree Zigzag Level Order Traversal/README_EN.md b/solution/0100-0199/0103.Binary Tree Zigzag Level Order Traversal/README_EN.md index a0f87f1b6f2a2..8e5fcfe46dc1a 100644 --- a/solution/0100-0199/0103.Binary Tree Zigzag Level Order Traversal/README_EN.md +++ b/solution/0100-0199/0103.Binary Tree Zigzag Level Order Traversal/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: BFS** +### Solution 1: BFS To implement zigzag level order traversal, we need to add a flag `left` on the basis of level order traversal. This flag is used to mark the order of the node values in the current level. If `left` is `true`, the node values of the current level are stored in the result array `ans` from left to right. If `left` is `false`, the node values of the current level are stored in the result array `ans` from right to left. @@ -46,8 +46,6 @@ 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: @@ -77,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -127,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -166,8 +160,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -208,52 +200,6 @@ func zigzagLevelOrder(root *TreeNode) (ans [][]int) { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number[][]} - */ -var zigzagLevelOrder = function (root) { - const ans = []; - if (!root) { - return ans; - } - const q = [root]; - let left = 1; - while (q.length) { - const t = []; - for (let n = q.length; n; --n) { - const node = q.shift(); - t.push(node.val); - if (node.left) { - q.push(node.left); - } - if (node.right) { - q.push(node.right); - } - } - if (!left) { - t.reverse(); - } - ans.push(t); - left ^= 1; - } - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -290,8 +236,6 @@ function zigzagLevelOrder(root: TreeNode | null): number[][] { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -348,10 +292,48 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var zigzagLevelOrder = function (root) { + const ans = []; + if (!root) { + return ans; + } + const q = [root]; + let left = 1; + while (q.length) { + const t = []; + for (let n = q.length; n; --n) { + const node = q.shift(); + t.push(node.val); + if (node.left) { + q.push(node.left); + } + if (node.right) { + q.push(node.right); + } + } + if (!left) { + t.reverse(); + } + ans.push(t); + left ^= 1; + } + return ans; +}; ``` + + diff --git a/solution/0100-0199/0104.Maximum Depth of Binary Tree/README.md b/solution/0100-0199/0104.Maximum Depth of Binary Tree/README.md index 1ae6dfab1a7a2..a6a97090fe2c3 100644 --- a/solution/0100-0199/0104.Maximum Depth of Binary Tree/README.md +++ b/solution/0100-0199/0104.Maximum Depth of Binary Tree/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 递归遍历左右子树,求左右子树的最大深度,然后取最大值加 $1$ 即可。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -70,10 +64,6 @@ class Solution: return 1 + max(l, r) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -146,31 +132,6 @@ func maxDepth(root *TreeNode) int { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number} - */ -var maxDepth = function (root) { - if (!root) return 0; - const l = maxDepth(root.left); - const r = maxDepth(root.right); - return 1 + Math.max(l, r); -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -194,8 +155,6 @@ function maxDepth(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -232,7 +191,26 @@ impl Solution { } ``` -### **C** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var maxDepth = function (root) { + if (!root) return 0; + const l = maxDepth(root.left); + const r = maxDepth(root.right); + return 1 + Math.max(l, r); +}; +``` ```c /** @@ -256,10 +234,6 @@ int maxDepth(struct TreeNode* root) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0104.Maximum Depth of Binary Tree/README_EN.md b/solution/0100-0199/0104.Maximum Depth of Binary Tree/README_EN.md index 0cdee43ac4845..c04856e24180a 100644 --- a/solution/0100-0199/0104.Maximum Depth of Binary Tree/README_EN.md +++ b/solution/0100-0199/0104.Maximum Depth of Binary Tree/README_EN.md @@ -33,7 +33,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion Recursively traverse the left and right subtrees, calculate the maximum depth of the left and right subtrees, and then take the maximum value plus $1$. @@ -41,8 +41,6 @@ The time complexity is $O(n)$, where $n$ is the number of nodes in the binary tr -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -58,8 +56,6 @@ class Solution: return 1 + max(l, r) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -88,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -112,8 +106,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -132,31 +124,6 @@ func maxDepth(root *TreeNode) int { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number} - */ -var maxDepth = function (root) { - if (!root) return 0; - const l = maxDepth(root.left); - const r = maxDepth(root.right); - return 1 + Math.max(l, r); -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -180,8 +147,6 @@ function maxDepth(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -218,7 +183,26 @@ impl Solution { } ``` -### **C** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var maxDepth = function (root) { + if (!root) return 0; + const l = maxDepth(root.left); + const r = maxDepth(root.right); + return 1 + Math.max(l, r); +}; +``` ```c /** @@ -242,10 +226,6 @@ int maxDepth(struct TreeNode* root) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/README.md b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/README.md index d232c6100b270..5aade841fba9d 100644 --- a/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/README.md +++ b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 前序序列的第一个结点 $preorder[0]$ 为根节点,我们在中序序列中找到根节点的位置 $i$,可以将中序序列划分为左子树 $inorder[0..i]$ 、右子树 $inorder[i+1..]$。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -84,31 +78,6 @@ class Solution: return dfs(0, 0, len(preorder)) ``` -```python -class Solution: - def getBinaryTrees(self, preOrder: List[int], inOrder: List[int]) -> List[TreeNode]: - def dfs(i: int, j: int, n: int) -> List[TreeNode]: - if n <= 0: - return [None] - v = preOrder[i] - ans = [] - for k in d[v]: - if j <= k < j + n: - for l in dfs(i + 1, j, k - j): - for r in dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)): - ans.append(TreeNode(v, l, r)) - return ans - - d = defaultdict(list) - for i, x in enumerate(inOrder): - d[x].append(i) - return dfs(0, 0, len(preOrder)) -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -153,50 +122,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private int[] preorder; - private Map d = new HashMap<>(); - - public TreeNode buildTree(int[] preorder, int[] inorder) { - int n = preorder.length; - this.preorder = preorder; - for (int i = 0; i < n; ++i) { - d.put(inorder[i], i); - } - return dfs(0, 0, n); - } - - private TreeNode dfs(int i, int j, int n) { - if (n <= 0) { - return null; - } - int v = preorder[i]; - int k = d.get(v); - TreeNode l = dfs(i + 1, j, k - j); - TreeNode r = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); - return new TreeNode(v, l, r); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -232,53 +157,6 @@ public: }; ``` -```cpp -/** - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * }; - */ -class Solution { -public: - vector getBinaryTrees(vector& preOrder, vector& inOrder) { - int n = inOrder.size(); - unordered_map> d; - for (int i = 0; i < n; ++i) { - d[inOrder[i]].push_back(i); - } - function(int, int, int)> dfs = [&](int i, int j, int n) -> vector { - vector ans; - if (n <= 0) { - ans.push_back(nullptr); - return ans; - } - int v = preOrder[i]; - for (int k : d[v]) { - if (k >= j && k < j + n) { - auto lefts = dfs(i + 1, j, k - j); - auto rights = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); - for (TreeNode* l : lefts) { - for (TreeNode* r : rights) { - TreeNode* node = new TreeNode(v); - node->left = l; - node->right = r; - ans.push_back(node); - } - } - } - } - return ans; - }; - return dfs(0, 0, n); - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -308,40 +186,6 @@ func buildTree(preorder []int, inorder []int) *TreeNode { } ``` -```go -func getBinaryTrees(preOrder []int, inOrder []int) []*TreeNode { - n := len(preOrder) - d := map[int][]int{} - for i, x := range inOrder { - d[x] = append(d[x], i) - } - var dfs func(i, j, n int) []*TreeNode - dfs = func(i, j, n int) []*TreeNode { - ans := []*TreeNode{} - if n <= 0 { - ans = append(ans, nil) - return ans - } - v := preOrder[i] - for _, k := range d[v] { - if k >= j && k < j+n { - lefts := dfs(i+1, j, k-j) - rights := dfs(i+1+k-j, k+1, n-1-(k-j)) - for _, left := range lefts { - for _, right := range rights { - ans = append(ans, &TreeNode{v, left, right}) - } - } - } - } - return ans - } - return dfs(0, 0, n) -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -377,8 +221,6 @@ function buildTree(preorder: number[], inorder: number[]): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -430,8 +272,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -466,10 +306,152 @@ var buildTree = function (preorder, inorder) { }; ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def getBinaryTrees(self, preOrder: List[int], inOrder: List[int]) -> List[TreeNode]: + def dfs(i: int, j: int, n: int) -> List[TreeNode]: + if n <= 0: + return [None] + v = preOrder[i] + ans = [] + for k in d[v]: + if j <= k < j + n: + for l in dfs(i + 1, j, k - j): + for r in dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)): + ans.append(TreeNode(v, l, r)) + return ans + + d = defaultdict(list) + for i, x in enumerate(inOrder): + d[x].append(i) + return dfs(0, 0, len(preOrder)) ``` +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int[] preorder; + private Map d = new HashMap<>(); + + public TreeNode buildTree(int[] preorder, int[] inorder) { + int n = preorder.length; + this.preorder = preorder; + for (int i = 0; i < n; ++i) { + d.put(inorder[i], i); + } + return dfs(0, 0, n); + } + + private TreeNode dfs(int i, int j, int n) { + if (n <= 0) { + return null; + } + int v = preorder[i]; + int k = d.get(v); + TreeNode l = dfs(i + 1, j, k - j); + TreeNode r = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); + return new TreeNode(v, l, r); + } +} +``` + +```cpp +/** + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * }; + */ +class Solution { +public: + vector getBinaryTrees(vector& preOrder, vector& inOrder) { + int n = inOrder.size(); + unordered_map> d; + for (int i = 0; i < n; ++i) { + d[inOrder[i]].push_back(i); + } + function(int, int, int)> dfs = [&](int i, int j, int n) -> vector { + vector ans; + if (n <= 0) { + ans.push_back(nullptr); + return ans; + } + int v = preOrder[i]; + for (int k : d[v]) { + if (k >= j && k < j + n) { + auto lefts = dfs(i + 1, j, k - j); + auto rights = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); + for (TreeNode* l : lefts) { + for (TreeNode* r : rights) { + TreeNode* node = new TreeNode(v); + node->left = l; + node->right = r; + ans.push_back(node); + } + } + } + } + return ans; + }; + return dfs(0, 0, n); + } +}; +``` + +```go +func getBinaryTrees(preOrder []int, inOrder []int) []*TreeNode { + n := len(preOrder) + d := map[int][]int{} + for i, x := range inOrder { + d[x] = append(d[x], i) + } + var dfs func(i, j, n int) []*TreeNode + dfs = func(i, j, n int) []*TreeNode { + ans := []*TreeNode{} + if n <= 0 { + ans = append(ans, nil) + return ans + } + v := preOrder[i] + for _, k := range d[v] { + if k >= j && k < j+n { + lefts := dfs(i+1, j, k-j) + rights := dfs(i+1+k-j, k+1, n-1-(k-j)) + for _, left := range lefts { + for _, right := range rights { + ans = append(ans, &TreeNode{v, left, right}) + } + } + } + } + return ans + } + return dfs(0, 0, n) +} ``` + + diff --git a/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/README_EN.md b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/README_EN.md index adc1480ac4fd3..0e410b2878022 100644 --- a/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/README_EN.md +++ b/solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion The first node $preorder[0]$ in the preorder sequence is the root node. We find the position $i$ of the root node in the inorder sequence, which divides the inorder sequence into the left subtree $inorder[0..i]$ and the right subtree $inorder[i+1..]$. @@ -52,8 +52,6 @@ If the node values given in the problem have duplicates, then we only need to re -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -76,29 +74,6 @@ class Solution: return dfs(0, 0, len(preorder)) ``` -```python -class Solution: - def getBinaryTrees(self, preOrder: List[int], inOrder: List[int]) -> List[TreeNode]: - def dfs(i: int, j: int, n: int) -> List[TreeNode]: - if n <= 0: - return [None] - v = preOrder[i] - ans = [] - for k in d[v]: - if j <= k < j + n: - for l in dfs(i + 1, j, k - j): - for r in dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)): - ans.append(TreeNode(v, l, r)) - return ans - - d = defaultdict(list) - for i, x in enumerate(inOrder): - d[x].append(i) - return dfs(0, 0, len(preOrder)) -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -143,50 +118,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private int[] preorder; - private Map d = new HashMap<>(); - - public TreeNode buildTree(int[] preorder, int[] inorder) { - int n = preorder.length; - this.preorder = preorder; - for (int i = 0; i < n; ++i) { - d.put(inorder[i], i); - } - return dfs(0, 0, n); - } - - private TreeNode dfs(int i, int j, int n) { - if (n <= 0) { - return null; - } - int v = preorder[i]; - int k = d.get(v); - TreeNode l = dfs(i + 1, j, k - j); - TreeNode r = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); - return new TreeNode(v, l, r); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -222,53 +153,6 @@ public: }; ``` -```cpp -/** - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * }; - */ -class Solution { -public: - vector getBinaryTrees(vector& preOrder, vector& inOrder) { - int n = inOrder.size(); - unordered_map> d; - for (int i = 0; i < n; ++i) { - d[inOrder[i]].push_back(i); - } - function(int, int, int)> dfs = [&](int i, int j, int n) -> vector { - vector ans; - if (n <= 0) { - ans.push_back(nullptr); - return ans; - } - int v = preOrder[i]; - for (int k : d[v]) { - if (k >= j && k < j + n) { - auto lefts = dfs(i + 1, j, k - j); - auto rights = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); - for (TreeNode* l : lefts) { - for (TreeNode* r : rights) { - TreeNode* node = new TreeNode(v); - node->left = l; - node->right = r; - ans.push_back(node); - } - } - } - } - return ans; - }; - return dfs(0, 0, n); - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -298,40 +182,6 @@ func buildTree(preorder []int, inorder []int) *TreeNode { } ``` -```go -func getBinaryTrees(preOrder []int, inOrder []int) []*TreeNode { - n := len(preOrder) - d := map[int][]int{} - for i, x := range inOrder { - d[x] = append(d[x], i) - } - var dfs func(i, j, n int) []*TreeNode - dfs = func(i, j, n int) []*TreeNode { - ans := []*TreeNode{} - if n <= 0 { - ans = append(ans, nil) - return ans - } - v := preOrder[i] - for _, k := range d[v] { - if k >= j && k < j+n { - lefts := dfs(i+1, j, k-j) - rights := dfs(i+1+k-j, k+1, n-1-(k-j)) - for _, left := range lefts { - for _, right := range rights { - ans = append(ans, &TreeNode{v, left, right}) - } - } - } - } - return ans - } - return dfs(0, 0, n) -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -367,8 +217,6 @@ function buildTree(preorder: number[], inorder: number[]): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -420,8 +268,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -456,10 +302,152 @@ var buildTree = function (preorder, inorder) { }; ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def getBinaryTrees(self, preOrder: List[int], inOrder: List[int]) -> List[TreeNode]: + def dfs(i: int, j: int, n: int) -> List[TreeNode]: + if n <= 0: + return [None] + v = preOrder[i] + ans = [] + for k in d[v]: + if j <= k < j + n: + for l in dfs(i + 1, j, k - j): + for r in dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)): + ans.append(TreeNode(v, l, r)) + return ans + + d = defaultdict(list) + for i, x in enumerate(inOrder): + d[x].append(i) + return dfs(0, 0, len(preOrder)) +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int[] preorder; + private Map d = new HashMap<>(); + + public TreeNode buildTree(int[] preorder, int[] inorder) { + int n = preorder.length; + this.preorder = preorder; + for (int i = 0; i < n; ++i) { + d.put(inorder[i], i); + } + return dfs(0, 0, n); + } + + private TreeNode dfs(int i, int j, int n) { + if (n <= 0) { + return null; + } + int v = preorder[i]; + int k = d.get(v); + TreeNode l = dfs(i + 1, j, k - j); + TreeNode r = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); + return new TreeNode(v, l, r); + } +} +``` +```cpp +/** + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * }; + */ +class Solution { +public: + vector getBinaryTrees(vector& preOrder, vector& inOrder) { + int n = inOrder.size(); + unordered_map> d; + for (int i = 0; i < n; ++i) { + d[inOrder[i]].push_back(i); + } + function(int, int, int)> dfs = [&](int i, int j, int n) -> vector { + vector ans; + if (n <= 0) { + ans.push_back(nullptr); + return ans; + } + int v = preOrder[i]; + for (int k : d[v]) { + if (k >= j && k < j + n) { + auto lefts = dfs(i + 1, j, k - j); + auto rights = dfs(i + 1 + k - j, k + 1, n - 1 - (k - j)); + for (TreeNode* l : lefts) { + for (TreeNode* r : rights) { + TreeNode* node = new TreeNode(v); + node->left = l; + node->right = r; + ans.push_back(node); + } + } + } + } + return ans; + }; + return dfs(0, 0, n); + } +}; ``` +```go +func getBinaryTrees(preOrder []int, inOrder []int) []*TreeNode { + n := len(preOrder) + d := map[int][]int{} + for i, x := range inOrder { + d[x] = append(d[x], i) + } + var dfs func(i, j, n int) []*TreeNode + dfs = func(i, j, n int) []*TreeNode { + ans := []*TreeNode{} + if n <= 0 { + ans = append(ans, nil) + return ans + } + v := preOrder[i] + for _, k := range d[v] { + if k >= j && k < j+n { + lefts := dfs(i+1, j, k-j) + rights := dfs(i+1+k-j, k+1, n-1-(k-j)) + for _, left := range lefts { + for _, right := range rights { + ans = append(ans, &TreeNode{v, left, right}) + } + } + } + } + return ans + } + return dfs(0, 0, n) +} ``` + + diff --git a/solution/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/README.md b/solution/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/README.md index fd0fe626984ec..c365c2c02e30f 100644 --- a/solution/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/README.md +++ b/solution/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 思路同 [105. 从前序与中序遍历序列构造二叉树](/solution/0100-0199/0105.Construct%20Binary%20Tree%20from%20Preorder%20and%20Inorder%20Traversal/README.md)。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -73,10 +67,6 @@ class Solution: return root ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -152,8 +140,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -184,8 +170,6 @@ func buildTree(inorder []int, postorder []int) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -216,8 +200,6 @@ function buildTree(inorder: number[], postorder: number[]): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -288,10 +270,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/README_EN.md b/solution/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/README_EN.md index 7db8d2e67360a..5790f766631b1 100644 --- a/solution/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/README_EN.md +++ b/solution/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion The approach is the same as in [105. Construct Binary Tree from Preorder and Inorder Traversal](/solution/0100-0199/0105.Construct%20Binary%20Tree%20from%20Preorder%20and%20Inorder%20Traversal/README_EN.md). @@ -44,8 +44,6 @@ 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: @@ -65,8 +63,6 @@ class Solution: return root ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -107,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -174,8 +166,6 @@ func buildTree(inorder []int, postorder []int) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -206,8 +196,6 @@ function buildTree(inorder: number[], postorder: number[]): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -278,10 +266,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0107.Binary Tree Level Order Traversal II/README.md b/solution/0100-0199/0107.Binary Tree Level Order Traversal II/README.md index a433a7561637b..1e9af9ca69401 100644 --- a/solution/0100-0199/0107.Binary Tree Level Order Traversal II/README.md +++ b/solution/0100-0199/0107.Binary Tree Level Order Traversal II/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 思路同 [102](/solution/0100-0199/0102.Binary%20Tree%20Level%20Order%20Traversal/README.md),最后反转一下结果即可。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -82,10 +76,6 @@ class Solution: return ans[::-1] ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -166,7 +154,39 @@ public: }; ``` -### **Rust** +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func levelOrderBottom(root *TreeNode) [][]int { + ans := [][]int{} + if root == nil { + return ans + } + q := []*TreeNode{root} + for len(q) > 0 { + var t []int + for i := len(q); i > 0; i-- { + node := q[0] + q = q[1:] + t = append(t, node.Val) + if node.Left != nil { + q = append(q, node.Left) + } + if node.Right != nil { + q = append(q, node.Right) + } + } + ans = append([][]int{t}, ans...) + } + return ans +} +``` ```rust // Definition for a binary tree node. @@ -225,44 +245,6 @@ impl Solution { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func levelOrderBottom(root *TreeNode) [][]int { - ans := [][]int{} - if root == nil { - return ans - } - q := []*TreeNode{root} - for len(q) > 0 { - var t []int - for i := len(q); i > 0; i-- { - node := q[0] - q = q[1:] - t = append(t, node.Val) - if node.Left != nil { - q = append(q, node.Left) - } - if node.Right != nil { - q = append(q, node.Right) - } - } - ans = append([][]int{t}, ans...) - } - return ans -} -``` - -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -294,10 +276,6 @@ var levelOrderBottom = function (root) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0107.Binary Tree Level Order Traversal II/README_EN.md b/solution/0100-0199/0107.Binary Tree Level Order Traversal II/README_EN.md index 7546cce28d74a..98512947a9945 100644 --- a/solution/0100-0199/0107.Binary Tree Level Order Traversal II/README_EN.md +++ b/solution/0100-0199/0107.Binary Tree Level Order Traversal II/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: BFS** +### Solution 1: BFS The approach is the same as in [102. Binary Tree Level Order Traversal](/solution/0100-0199/0102.Binary%20Tree%20Level%20Order%20Traversal/README_EN.md), just reverse the result in the end. @@ -46,8 +46,6 @@ 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: @@ -74,8 +72,6 @@ class Solution: return ans[::-1] ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -119,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -156,7 +150,39 @@ public: }; ``` -### **Rust** +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func levelOrderBottom(root *TreeNode) [][]int { + ans := [][]int{} + if root == nil { + return ans + } + q := []*TreeNode{root} + for len(q) > 0 { + var t []int + for i := len(q); i > 0; i-- { + node := q[0] + q = q[1:] + t = append(t, node.Val) + if node.Left != nil { + q = append(q, node.Left) + } + if node.Right != nil { + q = append(q, node.Right) + } + } + ans = append([][]int{t}, ans...) + } + return ans +} +``` ```rust // Definition for a binary tree node. @@ -215,44 +241,6 @@ impl Solution { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func levelOrderBottom(root *TreeNode) [][]int { - ans := [][]int{} - if root == nil { - return ans - } - q := []*TreeNode{root} - for len(q) > 0 { - var t []int - for i := len(q); i > 0; i-- { - node := q[0] - q = q[1:] - t = append(t, node.Val) - if node.Left != nil { - q = append(q, node.Left) - } - if node.Right != nil { - q = append(q, node.Right) - } - } - ans = append([][]int{t}, ans...) - } - return ans -} -``` - -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -284,10 +272,6 @@ var levelOrderBottom = function (root) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0108.Convert Sorted Array to Binary Search Tree/README.md b/solution/0100-0199/0108.Convert Sorted Array to Binary Search Tree/README.md index 5ca3933b216d7..8f5b36a6af0f7 100644 --- a/solution/0100-0199/0108.Convert Sorted Array to Binary Search Tree/README.md +++ b/solution/0100-0199/0108.Convert Sorted Array to Binary Search Tree/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:二分 + 递归** +### 方法一:二分 + 递归 我们设计一个递归函数 $dfs(l, r)$,表示当前待构造的二叉搜索树的节点值都在数组 `nums` 的下标范围 $[l, r]$ 内。该函数返回构造出的二叉搜索树的根节点。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -85,10 +79,6 @@ class Solution: return dfs(0, len(nums) - 1) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -156,37 +144,29 @@ public: }; ``` -### **JavaScript** - -```js +```go /** * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode * } */ -/** - * @param {number[]} nums - * @return {TreeNode} - */ -var sortedArrayToBST = function (nums) { - const dfs = (l, r) => { - if (l > r) { - return null; - } - const mid = (l + r) >> 1; - const left = dfs(l, mid - 1); - const right = dfs(mid + 1, r); - return new TreeNode(nums[mid], left, right); - }; - return dfs(0, nums.length - 1); -}; +func sortedArrayToBST(nums []int) *TreeNode { + var dfs func(int, int) *TreeNode + dfs = func(l, r int) *TreeNode { + if l > r { + return nil + } + mid := (l + r) >> 1 + left, right := dfs(l, mid-1), dfs(mid+1, r) + return &TreeNode{nums[mid], left, right} + } + return dfs(0, len(nums)-1) +} ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -216,33 +196,6 @@ function sortedArrayToBST(nums: number[]): TreeNode | null { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func sortedArrayToBST(nums []int) *TreeNode { - var dfs func(int, int) *TreeNode - dfs = func(l, r int) *TreeNode { - if l > r { - return nil - } - mid := (l + r) >> 1 - left, right := dfs(l, mid-1), dfs(mid+1, r) - return &TreeNode{nums[mid], left, right} - } - return dfs(0, len(nums)-1) -} -``` - -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -287,10 +240,33 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {number[]} nums + * @return {TreeNode} + */ +var sortedArrayToBST = function (nums) { + const dfs = (l, r) => { + if (l > r) { + return null; + } + const mid = (l + r) >> 1; + const left = dfs(l, mid - 1); + const right = dfs(mid + 1, r); + return new TreeNode(nums[mid], left, right); + }; + return dfs(0, nums.length - 1); +}; ``` + + diff --git a/solution/0100-0199/0108.Convert Sorted Array to Binary Search Tree/README_EN.md b/solution/0100-0199/0108.Convert Sorted Array to Binary Search Tree/README_EN.md index 185b0e2fa817f..c55aa827d97a5 100644 --- a/solution/0100-0199/0108.Convert Sorted Array to Binary Search Tree/README_EN.md +++ b/solution/0100-0199/0108.Convert Sorted Array to Binary Search Tree/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Binary Search + Recursion** +### Solution 1: Binary Search + Recursion We design a recursive function $dfs(l, r)$, which indicates that the node values of the current binary search tree to be constructed are all within the index range $[l, r]$ of the array `nums`. This function returns the root node of the constructed binary search tree. @@ -53,8 +53,6 @@ The time complexity is $O(n)$, and the space complexity is $O(\log n)$. Here, $n -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -75,8 +73,6 @@ class Solution: return dfs(0, len(nums) - 1) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -144,37 +138,29 @@ public: }; ``` -### **JavaScript** - -```js +```go /** * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode * } */ -/** - * @param {number[]} nums - * @return {TreeNode} - */ -var sortedArrayToBST = function (nums) { - const dfs = (l, r) => { - if (l > r) { - return null; - } - const mid = (l + r) >> 1; - const left = dfs(l, mid - 1); - const right = dfs(mid + 1, r); - return new TreeNode(nums[mid], left, right); - }; - return dfs(0, nums.length - 1); -}; +func sortedArrayToBST(nums []int) *TreeNode { + var dfs func(int, int) *TreeNode + dfs = func(l, r int) *TreeNode { + if l > r { + return nil + } + mid := (l + r) >> 1 + left, right := dfs(l, mid-1), dfs(mid+1, r) + return &TreeNode{nums[mid], left, right} + } + return dfs(0, len(nums)-1) +} ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -204,33 +190,6 @@ function sortedArrayToBST(nums: number[]): TreeNode | null { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func sortedArrayToBST(nums []int) *TreeNode { - var dfs func(int, int) *TreeNode - dfs = func(l, r int) *TreeNode { - if l > r { - return nil - } - mid := (l + r) >> 1 - left, right := dfs(l, mid-1), dfs(mid+1, r) - return &TreeNode{nums[mid], left, right} - } - return dfs(0, len(nums)-1) -} -``` - -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -275,10 +234,33 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {number[]} nums + * @return {TreeNode} + */ +var sortedArrayToBST = function (nums) { + const dfs = (l, r) => { + if (l > r) { + return null; + } + const mid = (l + r) >> 1; + const left = dfs(l, mid - 1); + const right = dfs(mid + 1, r); + return new TreeNode(nums[mid], left, right); + }; + return dfs(0, nums.length - 1); +}; ``` + + diff --git a/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/README.md b/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/README.md index b1470c6e469b1..2add7c9d3f57a 100644 --- a/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/README.md +++ b/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/README.md @@ -40,14 +40,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -77,10 +73,6 @@ class Solution: return buildBST(nums, 0, len(nums) - 1) ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -129,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -177,50 +167,44 @@ private: }; ``` -### **JavaScript** - -```js +```go /** * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) + * type ListNode struct { + * Val int + * Next *ListNode * } */ /** * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode * } */ -/** - * @param {ListNode} head - * @return {TreeNode} - */ -var sortedListToBST = function (head) { - const buildBST = (nums, start, end) => { - if (start > end) { - return null; - } - const mid = (start + end) >> 1; - const root = new TreeNode(nums[mid]); - root.left = buildBST(nums, start, mid - 1); - root.right = buildBST(nums, mid + 1, end); - return root; - }; +func sortedListToBST(head *ListNode) *TreeNode { + nums := []int{} + for head != nil { + nums = append(nums, head.Val) + head = head.Next + } + return buildBST(nums, 0, len(nums)-1) +} - const nums = new Array(); - for (; head != null; head = head.next) { - nums.push(head.val); - } - return buildBST(nums, 0, nums.length - 1); -}; +func buildBST(nums []int, start, end int) *TreeNode { + if start > end { + return nil + } + mid := (start + end) >> 1 + return &TreeNode{ + Val: nums[mid], + Left: buildBST(nums, start, mid-1), + Right: buildBST(nums, mid+1, end), + } +} ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -271,8 +255,6 @@ function sortedListToBST(head: ListNode | null): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -339,7 +321,45 @@ impl Solution { } ``` -### **C** +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {ListNode} head + * @return {TreeNode} + */ +var sortedListToBST = function (head) { + const buildBST = (nums, start, end) => { + if (start > end) { + return null; + } + const mid = (start + end) >> 1; + const root = new TreeNode(nums[mid]); + root.left = buildBST(nums, start, mid - 1); + root.right = buildBST(nums, mid + 1, end); + return root; + }; + + const nums = new Array(); + for (; head != null; head = head.next) { + nums.push(head.val); + } + return buildBST(nums, 0, nums.length - 1); +}; +``` ```c /** @@ -384,50 +404,6 @@ struct TreeNode* sortedListToBST(struct ListNode* head) { } ``` -### **Go** - -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func sortedListToBST(head *ListNode) *TreeNode { - nums := []int{} - for head != nil { - nums = append(nums, head.Val) - head = head.Next - } - return buildBST(nums, 0, len(nums)-1) -} - -func buildBST(nums []int, start, end int) *TreeNode { - if start > end { - return nil - } - mid := (start + end) >> 1 - return &TreeNode{ - Val: nums[mid], - Left: buildBST(nums, start, mid-1), - Right: buildBST(nums, mid+1, end), - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/README_EN.md b/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/README_EN.md index 7ae1ce0a51866..ad667418e60c0 100644 --- a/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/README_EN.md +++ b/solution/0100-0199/0109.Convert Sorted List to Binary Search Tree/README_EN.md @@ -32,9 +32,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -65,8 +65,6 @@ class Solution: return buildBST(nums, 0, len(nums) - 1) ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -115,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -163,50 +159,44 @@ private: }; ``` -### **JavaScript** - -```js +```go /** * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) + * type ListNode struct { + * Val int + * Next *ListNode * } */ /** * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode * } */ -/** - * @param {ListNode} head - * @return {TreeNode} - */ -var sortedListToBST = function (head) { - const buildBST = (nums, start, end) => { - if (start > end) { - return null; - } - const mid = (start + end) >> 1; - const root = new TreeNode(nums[mid]); - root.left = buildBST(nums, start, mid - 1); - root.right = buildBST(nums, mid + 1, end); - return root; - }; +func sortedListToBST(head *ListNode) *TreeNode { + nums := []int{} + for head != nil { + nums = append(nums, head.Val) + head = head.Next + } + return buildBST(nums, 0, len(nums)-1) +} - const nums = new Array(); - for (; head != null; head = head.next) { - nums.push(head.val); - } - return buildBST(nums, 0, nums.length - 1); -}; +func buildBST(nums []int, start, end int) *TreeNode { + if start > end { + return nil + } + mid := (start + end) >> 1 + return &TreeNode{ + Val: nums[mid], + Left: buildBST(nums, start, mid-1), + Right: buildBST(nums, mid+1, end), + } +} ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -257,8 +247,6 @@ function sortedListToBST(head: ListNode | null): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -325,7 +313,45 @@ impl Solution { } ``` -### **C** +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {ListNode} head + * @return {TreeNode} + */ +var sortedListToBST = function (head) { + const buildBST = (nums, start, end) => { + if (start > end) { + return null; + } + const mid = (start + end) >> 1; + const root = new TreeNode(nums[mid]); + root.left = buildBST(nums, start, mid - 1); + root.right = buildBST(nums, mid + 1, end); + return root; + }; + + const nums = new Array(); + for (; head != null; head = head.next) { + nums.push(head.val); + } + return buildBST(nums, 0, nums.length - 1); +}; +``` ```c /** @@ -370,50 +396,6 @@ struct TreeNode* sortedListToBST(struct ListNode* head) { } ``` -### **Go** - -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func sortedListToBST(head *ListNode) *TreeNode { - nums := []int{} - for head != nil { - nums = append(nums, head.Val) - head = head.Next - } - return buildBST(nums, 0, len(nums)-1) -} - -func buildBST(nums []int, start, end int) *TreeNode { - if start > end { - return nil - } - mid := (start + end) >> 1 - return &TreeNode{ - Val: nums[mid], - Left: buildBST(nums, start, mid-1), - Right: buildBST(nums, mid+1, end), - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0110.Balanced Binary Tree/README.md b/solution/0100-0199/0110.Balanced Binary Tree/README.md index 9ed68e2a0ec9c..d6e4e32c76b35 100644 --- a/solution/0100-0199/0110.Balanced Binary Tree/README.md +++ b/solution/0100-0199/0110.Balanced Binary Tree/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:自底向上的递归** +### 方法一:自底向上的递归 定义函数 $height(root)$ 计算二叉树的高度,处理逻辑如下: @@ -63,10 +61,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -87,10 +81,6 @@ class Solution: return height(root) >= 0 ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -126,39 +116,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {boolean} - */ -var isBalanced = function (root) { - const height = root => { - if (!root) { - return 0; - } - const l = height(root.left); - const r = height(root.right); - if (l == -1 || r == -1 || Math.abs(l - r) > 1) { - return -1; - } - return 1 + Math.max(l, r); - }; - return height(root) >= 0; -}; -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -190,8 +147,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -227,8 +182,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -260,8 +213,6 @@ function isBalanced(root: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -303,10 +254,35 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isBalanced = function (root) { + const height = root => { + if (!root) { + return 0; + } + const l = height(root.left); + const r = height(root.right); + if (l == -1 || r == -1 || Math.abs(l - r) > 1) { + return -1; + } + return 1 + Math.max(l, r); + }; + return height(root) >= 0; +}; ``` + + diff --git a/solution/0100-0199/0110.Balanced Binary Tree/README_EN.md b/solution/0100-0199/0110.Balanced Binary Tree/README_EN.md index 6f090fd7f16e2..2bc4430f860f5 100644 --- a/solution/0100-0199/0110.Balanced Binary Tree/README_EN.md +++ b/solution/0100-0199/0110.Balanced Binary Tree/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Bottom-Up Recursion** +### Solution 1: Bottom-Up Recursion We define a function $height(root)$ to calculate the height of a binary tree, with the following logic: @@ -51,8 +51,6 @@ 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: @@ -73,8 +71,6 @@ class Solution: return height(root) >= 0 ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -110,39 +106,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {boolean} - */ -var isBalanced = function (root) { - const height = root => { - if (!root) { - return 0; - } - const l = height(root.left); - const r = height(root.right); - if (l == -1 || r == -1 || Math.abs(l - r) > 1) { - return -1; - } - return 1 + Math.max(l, r); - }; - return height(root) >= 0; -}; -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -174,8 +137,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -211,8 +172,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -244,8 +203,6 @@ function isBalanced(root: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -287,10 +244,35 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isBalanced = function (root) { + const height = root => { + if (!root) { + return 0; + } + const l = height(root.left); + const r = height(root.right); + if (l == -1 || r == -1 || Math.abs(l - r) > 1) { + return -1; + } + return 1 + Math.max(l, r); + }; + return height(root) >= 0; +}; ``` + + diff --git a/solution/0100-0199/0111.Minimum Depth of Binary Tree/README.md b/solution/0100-0199/0111.Minimum Depth of Binary Tree/README.md index 22bcb668ef282..f9ef9bbdc39d5 100644 --- a/solution/0100-0199/0111.Minimum Depth of Binary Tree/README.md +++ b/solution/0100-0199/0111.Minimum Depth of Binary Tree/README.md @@ -39,26 +39,14 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 递归的终止条件是当前节点为空,此时返回 $0$;如果当前节点左右子树有一个为空,返回不为空的子树的最小深度加 $1$;如果当前节点左右子树都不为空,返回左右子树最小深度的较小值加 $1$。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。 -**方法二:BFS** - -使用队列实现广度优先搜索,初始时将根节点加入队列。每次从队列中取出一个节点,如果该节点是叶子节点,则直接返回当前深度;如果该节点不是叶子节点,则将该节点的所有非空子节点加入队列。继续搜索下一层节点,直到找到叶子节点。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -77,35 +65,6 @@ class Solution: return 1 + min(self.minDepth(root.left), self.minDepth(root.right)) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def minDepth(self, root: Optional[TreeNode]) -> int: - if root is None: - return 0 - q = deque([root]) - ans = 0 - while 1: - ans += 1 - for _ in range(len(q)): - node = q.popleft() - if node.left is None and node.right is None: - return ans - if node.left: - q.append(node.left) - if node.right: - q.append(node.right) -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -138,6 +97,220 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int minDepth(TreeNode* root) { + if (!root) { + return 0; + } + if (!root->left) { + return 1 + minDepth(root->right); + } + if (!root->right) { + return 1 + minDepth(root->left); + } + return 1 + min(minDepth(root->left), minDepth(root->right)); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func minDepth(root *TreeNode) int { + if root == nil { + return 0 + } + if root.Left == nil { + return 1 + minDepth(root.Right) + } + if root.Right == nil { + return 1 + minDepth(root.Left) + } + return 1 + min(minDepth(root.Left), minDepth(root.Right)) +} +``` + +```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 minDepth(root: TreeNode | null): number { + if (root == null) { + return 0; + } + const { left, right } = root; + if (left == null) { + return 1 + minDepth(right); + } + if (right == null) { + return 1 + minDepth(left); + } + return 1 + Math.min(minDepth(left), minDepth(right)); +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(root: &Option>>) -> i32 { + if root.is_none() { + return 0; + } + let node = root.as_ref().unwrap().borrow(); + if node.left.is_none() { + return 1 + Self::dfs(&node.right); + } + if node.right.is_none() { + return 1 + Self::dfs(&node.left); + } + 1 + Self::dfs(&node.left).min(Self::dfs(&node.right)) + } + + pub fn min_depth(root: Option>>) -> i32 { + Self::dfs(&root) + } +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var minDepth = function (root) { + if (!root) { + return 0; + } + if (!root.left) { + return 1 + minDepth(root.right); + } + if (!root.right) { + return 1 + minDepth(root.left); + } + return 1 + Math.min(minDepth(root.left), minDepth(root.right)); +}; +``` + +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +#define min(a, b) (((a) < (b)) ? (a) : (b)) + +int minDepth(struct TreeNode* root) { + if (!root) { + return 0; + } + if (!root->left) { + return 1 + minDepth(root->right); + } + if (!root->right) { + return 1 + minDepth(root->left); + } + int left = minDepth(root->left); + int right = minDepth(root->right); + return 1 + min(left, right); +} +``` + + + +### 方法二:BFS + +使用队列实现广度优先搜索,初始时将根节点加入队列。每次从队列中取出一个节点,如果该节点是叶子节点,则直接返回当前深度;如果该节点不是叶子节点,则将该节点的所有非空子节点加入队列。继续搜索下一层节点,直到找到叶子节点。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def minDepth(self, root: Optional[TreeNode]) -> int: + if root is None: + return 0 + q = deque([root]) + ans = 0 + while 1: + ans += 1 + for _ in range(len(q)): + node = q.popleft() + if node.left is None and node.right is None: + return ans + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) +``` + ```java /** * Definition for a binary tree node. @@ -181,37 +354,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int minDepth(TreeNode* root) { - if (!root) { - return 0; - } - if (!root->left) { - return 1 + minDepth(root->right); - } - if (!root->right) { - return 1 + minDepth(root->left); - } - return 1 + min(minDepth(root->left), minDepth(root->right)); - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -252,31 +394,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func minDepth(root *TreeNode) int { - if root == nil { - return 0 - } - if root.Left == nil { - return 1 + minDepth(root.Right) - } - if root.Right == nil { - return 1 + minDepth(root.Left) - } - return 1 + min(minDepth(root.Left), minDepth(root.Right)) -} -``` - ```go /** * Definition for a binary tree node. @@ -310,49 +427,22 @@ func minDepth(root *TreeNode) (ans int) { } ``` -### **JavaScript** - -```js +```ts /** * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) + * 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) + * } * } */ -/** - * @param {TreeNode} root - * @return {number} - */ -var minDepth = function (root) { - if (!root) { - return 0; - } - if (!root.left) { - return 1 + minDepth(root.right); - } - if (!root.right) { - return 1 + minDepth(root.left); - } - return 1 + Math.min(minDepth(root.left), minDepth(root.right)); -}; -``` -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number} - */ -var minDepth = function (root) { +function minDepth(root: TreeNode | null): number { if (!root) { return 0; } @@ -373,57 +463,23 @@ var minDepth = function (root) { } } } -}; +} ``` -### **TypeScript** - -```ts +```js /** * 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 TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) * } */ - -function minDepth(root: TreeNode | null): number { - if (root == null) { - return 0; - } - const { left, right } = root; - if (left == null) { - return 1 + minDepth(right); - } - if (right == null) { - return 1 + minDepth(left); - } - return 1 + Math.min(minDepth(left), minDepth(right)); -} -``` - -```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) - * } - * } + * @param {TreeNode} root + * @return {number} */ - -function minDepth(root: TreeNode | null): number { +var minDepth = function (root) { if (!root) { return 0; } @@ -444,87 +500,9 @@ function minDepth(root: TreeNode | null): number { } } } -} -``` - -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(root: &Option>>) -> i32 { - if root.is_none() { - return 0; - } - let node = root.as_ref().unwrap().borrow(); - if node.left.is_none() { - return 1 + Self::dfs(&node.right); - } - if node.right.is_none() { - return 1 + Self::dfs(&node.left); - } - 1 + Self::dfs(&node.left).min(Self::dfs(&node.right)) - } - - pub fn min_depth(root: Option>>) -> i32 { - Self::dfs(&root) - } -} -``` - -### **C** - -```c -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -#define min(a, b) (((a) < (b)) ? (a) : (b)) - -int minDepth(struct TreeNode* root) { - if (!root) { - return 0; - } - if (!root->left) { - return 1 + minDepth(root->right); - } - if (!root->right) { - return 1 + minDepth(root->left); - } - int left = minDepth(root->left); - int right = minDepth(root->right); - return 1 + min(left, right); -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0100-0199/0111.Minimum Depth of Binary Tree/README_EN.md b/solution/0100-0199/0111.Minimum Depth of Binary Tree/README_EN.md index 84e898728c3b8..c4a6236aba3b6 100644 --- a/solution/0100-0199/0111.Minimum Depth of Binary Tree/README_EN.md +++ b/solution/0100-0199/0111.Minimum Depth of Binary Tree/README_EN.md @@ -35,22 +35,14 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion The termination condition for recursion is when the current node is null, at which point return $0$. If one of the left or right subtrees of the current node is null, return the minimum depth of the non-null subtree plus $1$. If neither the left nor right subtree of the current node is null, return the smaller value of the minimum depths of the left and right subtrees plus $1$. The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. -**Solution 2: BFS** - -Use a queue to implement breadth-first search, initially adding the root node to the queue. Each time, take a node from the queue. If this node is a leaf node, directly return the current depth. If this node is not a leaf node, add all non-null child nodes of this node to the queue. Continue to search the next layer of nodes until a leaf node is found. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. - -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -69,33 +61,6 @@ class Solution: return 1 + min(self.minDepth(root.left), self.minDepth(root.right)) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def minDepth(self, root: Optional[TreeNode]) -> int: - if root is None: - return 0 - q = deque([root]) - ans = 0 - while 1: - ans += 1 - for _ in range(len(q)): - node = q.popleft() - if node.left is None and node.right is None: - return ans - if node.left: - q.append(node.left) - if node.right: - q.append(node.right) -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -128,6 +93,220 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int minDepth(TreeNode* root) { + if (!root) { + return 0; + } + if (!root->left) { + return 1 + minDepth(root->right); + } + if (!root->right) { + return 1 + minDepth(root->left); + } + return 1 + min(minDepth(root->left), minDepth(root->right)); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func minDepth(root *TreeNode) int { + if root == nil { + return 0 + } + if root.Left == nil { + return 1 + minDepth(root.Right) + } + if root.Right == nil { + return 1 + minDepth(root.Left) + } + return 1 + min(minDepth(root.Left), minDepth(root.Right)) +} +``` + +```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 minDepth(root: TreeNode | null): number { + if (root == null) { + return 0; + } + const { left, right } = root; + if (left == null) { + return 1 + minDepth(right); + } + if (right == null) { + return 1 + minDepth(left); + } + return 1 + Math.min(minDepth(left), minDepth(right)); +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(root: &Option>>) -> i32 { + if root.is_none() { + return 0; + } + let node = root.as_ref().unwrap().borrow(); + if node.left.is_none() { + return 1 + Self::dfs(&node.right); + } + if node.right.is_none() { + return 1 + Self::dfs(&node.left); + } + 1 + Self::dfs(&node.left).min(Self::dfs(&node.right)) + } + + pub fn min_depth(root: Option>>) -> i32 { + Self::dfs(&root) + } +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var minDepth = function (root) { + if (!root) { + return 0; + } + if (!root.left) { + return 1 + minDepth(root.right); + } + if (!root.right) { + return 1 + minDepth(root.left); + } + return 1 + Math.min(minDepth(root.left), minDepth(root.right)); +}; +``` + +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +#define min(a, b) (((a) < (b)) ? (a) : (b)) + +int minDepth(struct TreeNode* root) { + if (!root) { + return 0; + } + if (!root->left) { + return 1 + minDepth(root->right); + } + if (!root->right) { + return 1 + minDepth(root->left); + } + int left = minDepth(root->left); + int right = minDepth(root->right); + return 1 + min(left, right); +} +``` + + + +### Solution 2: BFS + +Use a queue to implement breadth-first search, initially adding the root node to the queue. Each time, take a node from the queue. If this node is a leaf node, directly return the current depth. If this node is not a leaf node, add all non-null child nodes of this node to the queue. Continue to search the next layer of nodes until a leaf node is found. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def minDepth(self, root: Optional[TreeNode]) -> int: + if root is None: + return 0 + q = deque([root]) + ans = 0 + while 1: + ans += 1 + for _ in range(len(q)): + node = q.popleft() + if node.left is None and node.right is None: + return ans + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) +``` + ```java /** * Definition for a binary tree node. @@ -171,37 +350,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int minDepth(TreeNode* root) { - if (!root) { - return 0; - } - if (!root->left) { - return 1 + minDepth(root->right); - } - if (!root->right) { - return 1 + minDepth(root->left); - } - return 1 + min(minDepth(root->left), minDepth(root->right)); - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -242,31 +390,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func minDepth(root *TreeNode) int { - if root == nil { - return 0 - } - if root.Left == nil { - return 1 + minDepth(root.Right) - } - if root.Right == nil { - return 1 + minDepth(root.Left) - } - return 1 + min(minDepth(root.Left), minDepth(root.Right)) -} -``` - ```go /** * Definition for a binary tree node. @@ -300,49 +423,22 @@ func minDepth(root *TreeNode) (ans int) { } ``` -### **JavaScript** - -```js +```ts /** * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) + * 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) + * } * } */ -/** - * @param {TreeNode} root - * @return {number} - */ -var minDepth = function (root) { - if (!root) { - return 0; - } - if (!root.left) { - return 1 + minDepth(root.right); - } - if (!root.right) { - return 1 + minDepth(root.left); - } - return 1 + Math.min(minDepth(root.left), minDepth(root.right)); -}; -``` -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number} - */ -var minDepth = function (root) { +function minDepth(root: TreeNode | null): number { if (!root) { return 0; } @@ -363,57 +459,23 @@ var minDepth = function (root) { } } } -}; +} ``` -### **TypeScript** - -```ts +```js /** * 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 TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) * } */ - -function minDepth(root: TreeNode | null): number { - if (root == null) { - return 0; - } - const { left, right } = root; - if (left == null) { - return 1 + minDepth(right); - } - if (right == null) { - return 1 + minDepth(left); - } - return 1 + Math.min(minDepth(left), minDepth(right)); -} -``` - -```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) - * } - * } + * @param {TreeNode} root + * @return {number} */ - -function minDepth(root: TreeNode | null): number { +var minDepth = function (root) { if (!root) { return 0; } @@ -434,87 +496,9 @@ function minDepth(root: TreeNode | null): number { } } } -} -``` - -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(root: &Option>>) -> i32 { - if root.is_none() { - return 0; - } - let node = root.as_ref().unwrap().borrow(); - if node.left.is_none() { - return 1 + Self::dfs(&node.right); - } - if node.right.is_none() { - return 1 + Self::dfs(&node.left); - } - 1 + Self::dfs(&node.left).min(Self::dfs(&node.right)) - } - - pub fn min_depth(root: Option>>) -> i32 { - Self::dfs(&root) - } -} -``` - -### **C** - -```c -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -#define min(a, b) (((a) < (b)) ? (a) : (b)) - -int minDepth(struct TreeNode* root) { - if (!root) { - return 0; - } - if (!root->left) { - return 1 + minDepth(root->right); - } - if (!root->right) { - return 1 + minDepth(root->left); - } - int left = minDepth(root->left); - int right = minDepth(root->right); - return 1 + min(left, right); -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0100-0199/0112.Path Sum/README.md b/solution/0100-0199/0112.Path Sum/README.md index 80cbf144f5952..b9335de1ae466 100644 --- a/solution/0100-0199/0112.Path Sum/README.md +++ b/solution/0100-0199/0112.Path Sum/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 从根节点开始,递归地对树进行遍历,并在遍历过程中更新节点的值为从根节点到该节点的路径和。当遍历到叶子节点时,判断该路径和是否等于目标值,如果相等则返回 `true`,否则返回 `false`。 @@ -60,10 +58,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. @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -177,8 +163,6 @@ func hasPathSum(root *TreeNode, targetSum int) bool { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -206,8 +190,6 @@ function hasPathSum(root: TreeNode | null, targetSum: number): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -248,8 +230,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -275,10 +255,6 @@ var hasPathSum = function (root, targetSum) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0112.Path Sum/README_EN.md b/solution/0100-0199/0112.Path Sum/README_EN.md index e797496f5b2ab..0f679dce70ff9 100644 --- a/solution/0100-0199/0112.Path Sum/README_EN.md +++ b/solution/0100-0199/0112.Path Sum/README_EN.md @@ -47,7 +47,7 @@ There is no root-to-leaf path with sum = 5. ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion Starting from the root node, recursively traverse the tree and update the value of the node to the path sum from the root node to that node. When you traverse to a leaf node, determine whether this path sum is equal to the target value. If it is equal, return `true`, otherwise return `false`. @@ -55,8 +55,6 @@ The time complexity is $O(n)$, where $n$ is the number of nodes in the binary tr -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -77,8 +75,6 @@ class Solution: return dfs(root, 0) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -141,8 +135,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -168,8 +160,6 @@ func hasPathSum(root *TreeNode, targetSum int) bool { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -197,8 +187,6 @@ function hasPathSum(root: TreeNode | null, targetSum: number): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -239,8 +227,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -266,10 +252,6 @@ var hasPathSum = function (root, targetSum) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0113.Path Sum II/README.md b/solution/0100-0199/0113.Path Sum II/README.md index c4246c1029fe6..b69e7773d129c 100644 --- a/solution/0100-0199/0113.Path Sum II/README.md +++ b/solution/0100-0199/0113.Path Sum II/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们从根节点开始,递归遍历所有从根节点到叶子节点的路径,并记录路径和。当遍历到叶子节点时,如果此时路径和等于 `targetSum`,则将此路径加入答案。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -134,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -200,8 +186,6 @@ func pathSum(root *TreeNode, targetSum int) (ans [][]int) { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -259,8 +243,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -292,10 +274,6 @@ var pathSum = function (root, targetSum) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0113.Path Sum II/README_EN.md b/solution/0100-0199/0113.Path Sum II/README_EN.md index 887efcdeb6ee9..fb94306b6f1fe 100644 --- a/solution/0100-0199/0113.Path Sum II/README_EN.md +++ b/solution/0100-0199/0113.Path Sum II/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We start from the root node, recursively traverse all paths from the root node to the leaf nodes, and record the path sum. When we traverse to a leaf node, if the current path sum equals `targetSum`, then we add this path to the answer. @@ -52,8 +52,6 @@ The time complexity is $O(n^2)$, where $n$ is the number of nodes in the binary -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -80,8 +78,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. @@ -157,8 +151,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -189,8 +181,6 @@ func pathSum(root *TreeNode, targetSum int) (ans [][]int) { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -248,8 +238,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -281,10 +269,6 @@ var pathSum = function (root, targetSum) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0114.Flatten Binary Tree to Linked List/README.md b/solution/0100-0199/0114.Flatten Binary Tree to Linked List/README.md index 2ad1a5440e67b..bf779d05be032 100644 --- a/solution/0100-0199/0114.Flatten Binary Tree to Linked List/README.md +++ b/solution/0100-0199/0114.Flatten Binary Tree to Linked List/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:寻找前驱节点** +### 方法一:寻找前驱节点 先序遍历的访问顺序是“根、左子树、右子树”,左子树最后一个节点访问完后,接着会访问根节点的右子树节点。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -90,10 +84,6 @@ class Solution: root = root.right ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -166,65 +154,6 @@ public: }; ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - #[allow(dead_code)] - pub fn flatten(root: &mut Option>>) { - if root.is_none() { - return; - } - let mut v: Vec>>> = Vec::new(); - // Initialize the vector - Self::pre_order_traverse(&mut v, root); - // Traverse the vector - let n = v.len(); - for i in 0..n - 1 { - v[i].as_ref().unwrap().borrow_mut().left = None; - v[i].as_ref().unwrap().borrow_mut().right = v[i + 1].clone(); - } - } - - #[allow(dead_code)] - fn pre_order_traverse( - v: &mut Vec>>>, - root: &Option>> - ) { - if root.is_none() { - return; - } - v.push(root.clone()); - let left = root.as_ref().unwrap().borrow().left.clone(); - let right = root.as_ref().unwrap().borrow().right.clone(); - Self::pre_order_traverse(v, &left); - Self::pre_order_traverse(v, &right); - } -} -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -250,33 +179,6 @@ func flatten(root *TreeNode) { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func flatten(root *TreeNode) { - for root != nil { - left, right := root.Left, root.Right - root.Left = nil - if left != nil { - root.Right = left - for left.Right != nil { - left = left.Right - } - left.Right = right - } - root = root.Right - } -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -311,7 +213,60 @@ function flatten(root: TreeNode | null): void { } ``` -### **JavaScript** +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + #[allow(dead_code)] + pub fn flatten(root: &mut Option>>) { + if root.is_none() { + return; + } + let mut v: Vec>>> = Vec::new(); + // Initialize the vector + Self::pre_order_traverse(&mut v, root); + // Traverse the vector + let n = v.len(); + for i in 0..n - 1 { + v[i].as_ref().unwrap().borrow_mut().left = None; + v[i].as_ref().unwrap().borrow_mut().right = v[i + 1].clone(); + } + } + + #[allow(dead_code)] + fn pre_order_traverse( + v: &mut Vec>>>, + root: &Option>> + ) { + if root.is_none() { + return; + } + v.push(root.clone()); + let left = root.as_ref().unwrap().borrow().left.clone(); + let right = root.as_ref().unwrap().borrow().right.clone(); + Self::pre_order_traverse(v, &left); + Self::pre_order_traverse(v, &right); + } +} +``` ```js /** @@ -342,10 +297,37 @@ var flatten = function (root) { }; ``` -### **...** + -``` +### 方法二 + + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func flatten(root *TreeNode) { + for root != nil { + left, right := root.Left, root.Right + root.Left = nil + if left != nil { + root.Right = left + for left.Right != nil { + left = left.Right + } + left.Right = right + } + root = root.Right + } +} ``` + + diff --git a/solution/0100-0199/0114.Flatten Binary Tree to Linked List/README_EN.md b/solution/0100-0199/0114.Flatten Binary Tree to Linked List/README_EN.md index 5e3dda1af937d..4aa5f012039c7 100644 --- a/solution/0100-0199/0114.Flatten Binary Tree to Linked List/README_EN.md +++ b/solution/0100-0199/0114.Flatten Binary Tree to Linked List/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Find Predecessor Node** +### Solution 1: Find Predecessor Node The visit order of preorder traversal is "root, left subtree, right subtree". After the last node of the left subtree is visited, the right subtree node of the root node will be visited next. @@ -56,8 +56,6 @@ The time complexity is $O(n)$, where $n$ is the number of nodes in the tree. The -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -81,8 +79,6 @@ class Solution: root = root.right ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -103,11 +99,16 @@ class Solution { public void flatten(TreeNode root) { while (root != null) { if (root.left != null) { + // 找到当前节点左子树的最右节点 TreeNode pre = root.left; while (pre.right != null) { pre = pre.right; } + + // 将左子树的最右节点指向原来的右子树 pre.right = root.right; + + // 将当前节点指向左子树 root.right = root.left; root.left = null; } @@ -117,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -150,65 +149,6 @@ public: }; ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - #[allow(dead_code)] - pub fn flatten(root: &mut Option>>) { - if root.is_none() { - return; - } - let mut v: Vec>>> = Vec::new(); - // Initialize the vector - Self::pre_order_traverse(&mut v, root); - // Traverse the vector - let n = v.len(); - for i in 0..n - 1 { - v[i].as_ref().unwrap().borrow_mut().left = None; - v[i].as_ref().unwrap().borrow_mut().right = v[i + 1].clone(); - } - } - - #[allow(dead_code)] - fn pre_order_traverse( - v: &mut Vec>>>, - root: &Option>> - ) { - if root.is_none() { - return; - } - v.push(root.clone()); - let left = root.as_ref().unwrap().borrow().left.clone(); - let right = root.as_ref().unwrap().borrow().right.clone(); - Self::pre_order_traverse(v, &left); - Self::pre_order_traverse(v, &right); - } -} -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -234,33 +174,6 @@ func flatten(root *TreeNode) { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func flatten(root *TreeNode) { - for root != nil { - left, right := root.Left, root.Right - root.Left = nil - if left != nil { - root.Right = left - for left.Right != nil { - left = left.Right - } - left.Right = right - } - root = root.Right - } -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -295,7 +208,60 @@ function flatten(root: TreeNode | null): void { } ``` -### **JavaScript** +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + #[allow(dead_code)] + pub fn flatten(root: &mut Option>>) { + if root.is_none() { + return; + } + let mut v: Vec>>> = Vec::new(); + // Initialize the vector + Self::pre_order_traverse(&mut v, root); + // Traverse the vector + let n = v.len(); + for i in 0..n - 1 { + v[i].as_ref().unwrap().borrow_mut().left = None; + v[i].as_ref().unwrap().borrow_mut().right = v[i + 1].clone(); + } + } + + #[allow(dead_code)] + fn pre_order_traverse( + v: &mut Vec>>>, + root: &Option>> + ) { + if root.is_none() { + return; + } + v.push(root.clone()); + let left = root.as_ref().unwrap().borrow().left.clone(); + let right = root.as_ref().unwrap().borrow().right.clone(); + Self::pre_order_traverse(v, &left); + Self::pre_order_traverse(v, &right); + } +} +``` ```js /** @@ -326,10 +292,37 @@ var flatten = function (root) { }; ``` -### **...** + -``` +### Solution 2 + + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func flatten(root *TreeNode) { + for root != nil { + left, right := root.Left, root.Right + root.Left = nil + if left != nil { + root.Right = left + for left.Right != nil { + left = left.Right + } + left.Right = right + } + root = root.Right + } +} ``` + + diff --git a/solution/0100-0199/0115.Distinct Subsequences/README.md b/solution/0100-0199/0115.Distinct Subsequences/README.md index 01bb3a86772d8..1d97d02b80093 100644 --- a/solution/0100-0199/0115.Distinct Subsequences/README.md +++ b/solution/0100-0199/0115.Distinct Subsequences/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示字符串 $s$ 的前 $i$ 个字符中,子序列构成字符串 $t$ 的前 $j$ 个字符的方案数。初始时 $f[i][0]=1$,其中 $i \in [0,m]$。 @@ -76,10 +74,6 @@ $$ -### **Python3** - - - ```python class Solution: def numDistinct(self, s: str, t: str) -> int: @@ -95,22 +89,6 @@ class Solution: return f[m][n] ``` -```python -class Solution: - def numDistinct(self, s: str, t: str) -> int: - n = len(t) - f = [1] + [0] * n - for a in s: - for j in range(n, 0, -1): - if a == t[j - 1]: - f[j] += f[j - 1] - return f[n] -``` - -### **Java** - - - ```java class Solution { public int numDistinct(String s, String t) { @@ -132,27 +110,6 @@ class Solution { } ``` -```java -class Solution { - public int numDistinct(String s, String t) { - int n = t.length(); - int[] f = new int[n + 1]; - f[0] = 1; - for (char a : s.toCharArray()) { - for (int j = n; j > 0; --j) { - char b = t.charAt(j - 1); - if (a == b) { - f[j] += f[j - 1]; - } - } - } - return f[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -176,29 +133,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numDistinct(string s, string t) { - int n = t.size(); - unsigned long long f[n + 1]; - memset(f, 0, sizeof(f)); - f[0] = 1; - for (char& a : s) { - for (int j = n; j; --j) { - char b = t[j - 1]; - if (a == b) { - f[j] += f[j - 1]; - } - } - } - return f[n]; - } -}; -``` - -### **Go** - ```go func numDistinct(s string, t string) int { m, n := len(s), len(t) @@ -221,24 +155,6 @@ func numDistinct(s string, t string) int { } ``` -```go -func numDistinct(s string, t string) int { - n := len(t) - f := make([]int, n+1) - f[0] = 1 - for _, a := range s { - for j := n; j > 0; j-- { - if b := t[j-1]; byte(a) == b { - f[j] += f[j-1] - } - } - } - return f[n] -} -``` - -### **TypeScript** - ```ts function numDistinct(s: string, t: string): number { const m = s.length; @@ -259,25 +175,6 @@ function numDistinct(s: string, t: string): number { } ``` -```ts -function numDistinct(s: string, t: string): number { - const n = t.length; - const f: number[] = new Array(n + 1).fill(0); - f[0] = 1; - for (const a of s) { - for (let j = n; j; --j) { - const b = t[j - 1]; - if (a === b) { - f[j] += f[j - 1]; - } - } - } - return f[n]; -} -``` - -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -307,10 +204,97 @@ impl Solution { } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def numDistinct(self, s: str, t: str) -> int: + n = len(t) + f = [1] + [0] * n + for a in s: + for j in range(n, 0, -1): + if a == t[j - 1]: + f[j] += f[j - 1] + return f[n] +``` + +```java +class Solution { + public int numDistinct(String s, String t) { + int n = t.length(); + int[] f = new int[n + 1]; + f[0] = 1; + for (char a : s.toCharArray()) { + for (int j = n; j > 0; --j) { + char b = t.charAt(j - 1); + if (a == b) { + f[j] += f[j - 1]; + } + } + } + return f[n]; + } +} +``` + +```cpp +class Solution { +public: + int numDistinct(string s, string t) { + int n = t.size(); + unsigned long long f[n + 1]; + memset(f, 0, sizeof(f)); + f[0] = 1; + for (char& a : s) { + for (int j = n; j; --j) { + char b = t[j - 1]; + if (a == b) { + f[j] += f[j - 1]; + } + } + } + return f[n]; + } +}; +``` +```go +func numDistinct(s string, t string) int { + n := len(t) + f := make([]int, n+1) + f[0] = 1 + for _, a := range s { + for j := n; j > 0; j-- { + if b := t[j-1]; byte(a) == b { + f[j] += f[j-1] + } + } + } + return f[n] +} ``` +```ts +function numDistinct(s: string, t: string): number { + const n = t.length; + const f: number[] = new Array(n + 1).fill(0); + f[0] = 1; + for (const a of s) { + for (let j = n; j; --j) { + const b = t[j - 1]; + if (a === b) { + f[j] += f[j - 1]; + } + } + } + return f[n]; +} ``` + + diff --git a/solution/0100-0199/0115.Distinct Subsequences/README_EN.md b/solution/0100-0199/0115.Distinct Subsequences/README_EN.md index 01e2b9f6a1b7a..1dc4aa6ea7e49 100644 --- a/solution/0100-0199/0115.Distinct Subsequences/README_EN.md +++ b/solution/0100-0199/0115.Distinct Subsequences/README_EN.md @@ -44,7 +44,7 @@ As shown below, there are 5 ways you can generate "bag" from s. ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ as the number of schemes where the first $i$ characters of string $s$ form the first $j$ characters of string $t$. Initially, $f[i][0]=1$ for all $i \in [0,m]$. @@ -72,8 +72,6 @@ We notice that the calculation of $f[i][j]$ is only related to $f[i-1][..]$. The -### **Python3** - ```python class Solution: def numDistinct(self, s: str, t: str) -> int: @@ -89,20 +87,6 @@ class Solution: return f[m][n] ``` -```python -class Solution: - def numDistinct(self, s: str, t: str) -> int: - n = len(t) - f = [1] + [0] * n - for a in s: - for j in range(n, 0, -1): - if a == t[j - 1]: - f[j] += f[j - 1] - return f[n] -``` - -### **Java** - ```java class Solution { public int numDistinct(String s, String t) { @@ -124,49 +108,6 @@ class Solution { } ``` -```java -class Solution { - public int numDistinct(String s, String t) { - int n = t.length(); - int[] f = new int[n + 1]; - f[0] = 1; - for (char a : s.toCharArray()) { - for (int j = n; j > 0; --j) { - char b = t.charAt(j - 1); - if (a == b) { - f[j] += f[j - 1]; - } - } - } - return f[n]; - } -} -``` - -### **Go** - -```go -func numDistinct(s string, t string) int { - m, n := len(s), len(t) - dp := make([][]int, m+1) - for i := 0; i <= m; i++ { - dp[i] = make([]int, n+1) - dp[i][0] = 1 - } - for i := 1; i <= m; i++ { - for j := 1; j <= n; j++ { - dp[i][j] = dp[i-1][j] - if s[i-1] == t[j-1] { - dp[i][j] += dp[i-1][j-1] - } - } - } - return dp[m][n] -} -``` - -### **C++** - ```cpp class Solution { public: @@ -190,29 +131,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numDistinct(string s, string t) { - int n = t.size(); - unsigned long long f[n + 1]; - memset(f, 0, sizeof(f)); - f[0] = 1; - for (char& a : s) { - for (int j = n; j; --j) { - char b = t[j - 1]; - if (a == b) { - f[j] += f[j - 1]; - } - } - } - return f[n]; - } -}; -``` - -### **Go** - ```go func numDistinct(s string, t string) int { m, n := len(s), len(t) @@ -235,24 +153,6 @@ func numDistinct(s string, t string) int { } ``` -```go -func numDistinct(s string, t string) int { - n := len(t) - f := make([]int, n+1) - f[0] = 1 - for _, a := range s { - for j := n; j > 0; j-- { - if b := t[j-1]; byte(a) == b { - f[j] += f[j-1] - } - } - } - return f[n] -} -``` - -### **TypeScript** - ```ts function numDistinct(s: string, t: string): number { const m = s.length; @@ -273,25 +173,6 @@ function numDistinct(s: string, t: string): number { } ``` -```ts -function numDistinct(s: string, t: string): number { - const n = t.length; - const f: number[] = new Array(n + 1).fill(0); - f[0] = 1; - for (const a of s) { - for (let j = n; j; --j) { - const b = t[j - 1]; - if (a === b) { - f[j] += f[j - 1]; - } - } - } - return f[n]; -} -``` - -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -321,10 +202,97 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def numDistinct(self, s: str, t: str) -> int: + n = len(t) + f = [1] + [0] * n + for a in s: + for j in range(n, 0, -1): + if a == t[j - 1]: + f[j] += f[j - 1] + return f[n] +``` + +```java +class Solution { + public int numDistinct(String s, String t) { + int n = t.length(); + int[] f = new int[n + 1]; + f[0] = 1; + for (char a : s.toCharArray()) { + for (int j = n; j > 0; --j) { + char b = t.charAt(j - 1); + if (a == b) { + f[j] += f[j - 1]; + } + } + } + return f[n]; + } +} +``` + +```cpp +class Solution { +public: + int numDistinct(string s, string t) { + int n = t.size(); + unsigned long long f[n + 1]; + memset(f, 0, sizeof(f)); + f[0] = 1; + for (char& a : s) { + for (int j = n; j; --j) { + char b = t[j - 1]; + if (a == b) { + f[j] += f[j - 1]; + } + } + } + return f[n]; + } +}; +``` +```go +func numDistinct(s string, t string) int { + n := len(t) + f := make([]int, n+1) + f[0] = 1 + for _, a := range s { + for j := n; j > 0; j-- { + if b := t[j-1]; byte(a) == b { + f[j] += f[j-1] + } + } + } + return f[n] +} ``` +```ts +function numDistinct(s: string, t: string): number { + const n = t.length; + const f: number[] = new Array(n + 1).fill(0); + f[0] = 1; + for (const a of s) { + for (let j = n; j; --j) { + const b = t[j - 1]; + if (a === b) { + f[j] += f[j - 1]; + } + } + } + return f[n]; +} ``` + + diff --git a/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/README.md b/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/README.md index 0429385dfeea7..bb1509fb02e56 100644 --- a/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/README.md +++ b/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/README.md @@ -61,28 +61,14 @@ struct Node { ## 解法 - - -**方法一:BFS** +### 方法一:BFS 使用队列进行层序遍历,每次遍历一层时,将当前层的节点按顺序连接起来。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。 -**方法二:DFS** - -使用递归进行前序遍历,每次遍历到一个节点时,将其左右子节点按顺序连接起来。 - -具体地,我们设计一个函数 $dfs(left, right)$,表示将 $left$ 节点的 $next$ 指针指向 $right$ 节点。在函数中,我们首先判断 $left$ 和 $right$ 是否为空,若都不为空,则将 $left.next$ 指向 $right$,然后递归地调用 $dfs(left.left, left.right)$, $dfs(left.right, right.left)$, $dfs(right.left, right.right)$。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。 - -### **Python3** - - - ```python """ # Definition for a Node. @@ -114,37 +100,6 @@ class Solution: return root ``` -```python -""" -# Definition for a Node. -class Node: - def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): - self.val = val - self.left = left - self.right = right - self.next = next -""" - - -class Solution: - def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': - def dfs(left, right): - if left is None or right is None: - return - left.next = right - dfs(left.left, left.right) - dfs(left.right, right.left) - dfs(right.left, right.right) - - if root: - dfs(root.left, root.right) - return root -``` - -### **Java** - - - ```java /* // Definition for a Node. @@ -197,52 +152,6 @@ class Solution { } ``` -```java -/* -// Definition for a Node. -class Node { - public int val; - public Node left; - public Node right; - public Node next; - - public Node() {} - - public Node(int _val) { - val = _val; - } - - public Node(int _val, Node _left, Node _right, Node _next) { - val = _val; - left = _left; - right = _right; - next = _next; - } -}; -*/ - -class Solution { - public Node connect(Node root) { - if (root != null) { - dfs(root.left, root.right); - } - return root; - } - - private void dfs(Node left, Node right) { - if (left == null || right == null) { - return; - } - left.next = right; - dfs(left.left, left.right); - dfs(left.right, right.left); - dfs(right.left, right.right); - } -} -``` - -### **C++** - ```cpp /* // Definition for a Node. @@ -291,47 +200,6 @@ public: }; ``` -```cpp -/* -// Definition for a Node. -class Node { -public: - int val; - Node* left; - Node* right; - Node* next; - - Node() : val(0), left(NULL), right(NULL), next(NULL) {} - - Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} - - Node(int _val, Node* _left, Node* _right, Node* _next) - : val(_val), left(_left), right(_right), next(_next) {} -}; -*/ - -class Solution { -public: - Node* connect(Node* root) { - function dfs = [&](Node* left, Node* right) { - if (!left || !right) { - return; - } - left->next = right; - dfs(left->left, left->right); - dfs(left->right, right->left); - dfs(right->left, right->right); - }; - if (root) { - dfs(root->left, root->right); - } - return root; - } -}; -``` - -### **Go** - ```go /** * Definition for a Node. @@ -369,37 +237,6 @@ func connect(root *Node) *Node { } ``` -```go -/** - * Definition for a Node. - * type Node struct { - * Val int - * Left *Node - * Right *Node - * Next *Node - * } - */ - -func connect(root *Node) *Node { - var dfs func(*Node, *Node) - dfs = func(left, right *Node) { - if left == nil || right == nil { - return - } - left.Next = right - dfs(left.Left, left.Right) - dfs(left.Right, right.Left) - dfs(right.Left, right.Right) - } - if root != nil { - dfs(root.Left, root.Right) - } - return root -} -``` - -### **TypeScript** - ```ts /** * Definition for Node. @@ -432,6 +269,157 @@ function connect(root: Node | null): Node | null { } ``` + + +### 方法二:DFS + +使用递归进行前序遍历,每次遍历到一个节点时,将其左右子节点按顺序连接起来。 + +具体地,我们设计一个函数 $dfs(left, right)$,表示将 $left$ 节点的 $next$ 指针指向 $right$ 节点。在函数中,我们首先判断 $left$ 和 $right$ 是否为空,若都不为空,则将 $left.next$ 指向 $right$,然后递归地调用 $dfs(left.left, left.right)$, $dfs(left.right, right.left)$, $dfs(right.left, right.right)$。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。 + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): + self.val = val + self.left = left + self.right = right + self.next = next +""" + + +class Solution: + def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': + def dfs(left, right): + if left is None or right is None: + return + left.next = right + dfs(left.left, left.right) + dfs(left.right, right.left) + dfs(right.left, right.right) + + if root: + dfs(root.left, root.right) + return root +``` + +```java +/* +// Definition for a Node. +class Node { + public int val; + public Node left; + public Node right; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _left, Node _right, Node _next) { + val = _val; + left = _left; + right = _right; + next = _next; + } +}; +*/ + +class Solution { + public Node connect(Node root) { + if (root != null) { + dfs(root.left, root.right); + } + return root; + } + + private void dfs(Node left, Node right) { + if (left == null || right == null) { + return; + } + left.next = right; + dfs(left.left, left.right); + dfs(left.right, right.left); + dfs(right.left, right.right); + } +} +``` + +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; +*/ + +class Solution { +public: + Node* connect(Node* root) { + function dfs = [&](Node* left, Node* right) { + if (!left || !right) { + return; + } + left->next = right; + dfs(left->left, left->right); + dfs(left->right, right->left); + dfs(right->left, right->right); + }; + if (root) { + dfs(root->left, root->right); + } + return root; + } +}; +``` + +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Left *Node + * Right *Node + * Next *Node + * } + */ + +func connect(root *Node) *Node { + var dfs func(*Node, *Node) + dfs = func(left, right *Node) { + if left == nil || right == nil { + return + } + left.Next = right + dfs(left.Left, left.Right) + dfs(left.Right, right.Left) + dfs(right.Left, right.Right) + } + if root != nil { + dfs(root.Left, root.Right) + } + return root +} +``` + ```ts /** * Definition for Node. @@ -469,10 +457,6 @@ function connect(root: Node | null): Node | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/README_EN.md b/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/README_EN.md index 1e92a00009663..3f2da057fc9c7 100644 --- a/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/README_EN.md +++ b/solution/0100-0199/0116.Populating Next Right Pointers in Each Node/README_EN.md @@ -53,24 +53,14 @@ struct Node { ## Solutions -**Solution 1: BFS** +### Solution 1: BFS Use a queue for level order traversal, and each time you traverse a level, connect the nodes of the current level in order. The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. -**Solution 2: DFS** - -Use recursion for preorder traversal, and each time you traverse to a node, connect its left and right child nodes in order. - -Specifically, we design a function $dfs(left, right)$, which points the $next$ pointer of the $left$ node to the $right$ node. In the function, we first check whether $left$ and $right$ are null. If both are not null, point $left.next$ to $right$, and then recursively call $dfs(left.left, left.right)$, $dfs(left.right, right.left)$, $dfs(right.left, right.right)$. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. - -### **Python3** - ```python """ # Definition for a Node. @@ -102,35 +92,6 @@ class Solution: return root ``` -```python -""" -# Definition for a Node. -class Node: - def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): - self.val = val - self.left = left - self.right = right - self.next = next -""" - - -class Solution: - def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': - def dfs(left, right): - if left is None or right is None: - return - left.next = right - dfs(left.left, left.right) - dfs(left.right, right.left) - dfs(right.left, right.right) - - if root: - dfs(root.left, root.right) - return root -``` - -### **Java** - ```java /* // Definition for a Node. @@ -183,52 +144,6 @@ class Solution { } ``` -```java -/* -// Definition for a Node. -class Node { - public int val; - public Node left; - public Node right; - public Node next; - - public Node() {} - - public Node(int _val) { - val = _val; - } - - public Node(int _val, Node _left, Node _right, Node _next) { - val = _val; - left = _left; - right = _right; - next = _next; - } -}; -*/ - -class Solution { - public Node connect(Node root) { - if (root != null) { - dfs(root.left, root.right); - } - return root; - } - - private void dfs(Node left, Node right) { - if (left == null || right == null) { - return; - } - left.next = right; - dfs(left.left, left.right); - dfs(left.right, right.left); - dfs(right.left, right.right); - } -} -``` - -### **C++** - ```cpp /* // Definition for a Node. @@ -277,47 +192,6 @@ public: }; ``` -```cpp -/* -// Definition for a Node. -class Node { -public: - int val; - Node* left; - Node* right; - Node* next; - - Node() : val(0), left(NULL), right(NULL), next(NULL) {} - - Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} - - Node(int _val, Node* _left, Node* _right, Node* _next) - : val(_val), left(_left), right(_right), next(_next) {} -}; -*/ - -class Solution { -public: - Node* connect(Node* root) { - function dfs = [&](Node* left, Node* right) { - if (!left || !right) { - return; - } - left->next = right; - dfs(left->left, left->right); - dfs(left->right, right->left); - dfs(right->left, right->right); - }; - if (root) { - dfs(root->left, root->right); - } - return root; - } -}; -``` - -### **Go** - ```go /** * Definition for a Node. @@ -355,37 +229,6 @@ func connect(root *Node) *Node { } ``` -```go -/** - * Definition for a Node. - * type Node struct { - * Val int - * Left *Node - * Right *Node - * Next *Node - * } - */ - -func connect(root *Node) *Node { - var dfs func(*Node, *Node) - dfs = func(left, right *Node) { - if left == nil || right == nil { - return - } - left.Next = right - dfs(left.Left, left.Right) - dfs(left.Right, right.Left) - dfs(right.Left, right.Right) - } - if root != nil { - dfs(root.Left, root.Right) - } - return root -} -``` - -### **TypeScript** - ```ts /** * Definition for Node. @@ -418,6 +261,157 @@ function connect(root: Node | null): Node | null { } ``` + + +### Solution 2: DFS + +Use recursion for preorder traversal, and each time you traverse to a node, connect its left and right child nodes in order. + +Specifically, we design a function $dfs(left, right)$, which points the $next$ pointer of the $left$ node to the $right$ node. In the function, we first check whether $left$ and $right$ are null. If both are not null, point $left.next$ to $right$, and then recursively call $dfs(left.left, left.right)$, $dfs(left.right, right.left)$, $dfs(right.left, right.right)$. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): + self.val = val + self.left = left + self.right = right + self.next = next +""" + + +class Solution: + def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': + def dfs(left, right): + if left is None or right is None: + return + left.next = right + dfs(left.left, left.right) + dfs(left.right, right.left) + dfs(right.left, right.right) + + if root: + dfs(root.left, root.right) + return root +``` + +```java +/* +// Definition for a Node. +class Node { + public int val; + public Node left; + public Node right; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _left, Node _right, Node _next) { + val = _val; + left = _left; + right = _right; + next = _next; + } +}; +*/ + +class Solution { + public Node connect(Node root) { + if (root != null) { + dfs(root.left, root.right); + } + return root; + } + + private void dfs(Node left, Node right) { + if (left == null || right == null) { + return; + } + left.next = right; + dfs(left.left, left.right); + dfs(left.right, right.left); + dfs(right.left, right.right); + } +} +``` + +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; +*/ + +class Solution { +public: + Node* connect(Node* root) { + function dfs = [&](Node* left, Node* right) { + if (!left || !right) { + return; + } + left->next = right; + dfs(left->left, left->right); + dfs(left->right, right->left); + dfs(right->left, right->right); + }; + if (root) { + dfs(root->left, root->right); + } + return root; + } +}; +``` + +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Left *Node + * Right *Node + * Next *Node + * } + */ + +func connect(root *Node) *Node { + var dfs func(*Node, *Node) + dfs = func(left, right *Node) { + if left == nil || right == nil { + return + } + left.Next = right + dfs(left.Left, left.Right) + dfs(left.Right, right.Left) + dfs(right.Left, right.Right) + } + if root != nil { + dfs(root.Left, root.Right) + } + return root +} +``` + ```ts /** * Definition for Node. @@ -455,10 +449,6 @@ function connect(root: Node | null): Node | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/README.md b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/README.md index 2d490115bfac8..363586b2bbc86 100644 --- a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/README.md +++ b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/README.md @@ -57,28 +57,14 @@ struct Node { ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们使用队列 $q$ 进行层序遍历,每次遍历一层时,将当前层的节点按顺序连接起来。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。 -**方法二:空间优化** - -方法一的空间复杂度较高,因为需要使用队列存储每一层的节点。我们可以使用常数空间来实现。 - -定义两个指针 $prev$ 和 $next$,分别指向下一层的前一个节点和第一个节点。遍历当前层的节点时,把下一层的节点串起来,同时找到下一层的第一个节点。当前层遍历完后,把下一层的第一个节点 $next$ 赋值给 $node$,继续遍历。 - -时间复杂度 $O(n)$,其中 $n$ 为二叉树的节点个数。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python """ # Definition for a Node. @@ -110,44 +96,6 @@ class Solution: return root ``` -```python -""" -# Definition for a Node. -class Node: - def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): - self.val = val - self.left = left - self.right = right - self.next = next -""" - - -class Solution: - def connect(self, root: 'Node') -> 'Node': - def modify(curr): - nonlocal prev, next - if curr is None: - return - next = next or curr - if prev: - prev.next = curr - prev = curr - - node = root - while node: - prev = next = None - while node: - modify(node.left) - modify(node.right) - node = node.next - node = next - return root -``` - -### **Java** - - - ```java /* // Definition for a Node. @@ -200,6 +148,229 @@ class Solution { } ``` +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; +*/ + +class Solution { +public: + Node* connect(Node* root) { + if (!root) { + return root; + } + queue q{{root}}; + while (!q.empty()) { + Node* p = nullptr; + for (int n = q.size(); n; --n) { + Node* node = q.front(); + q.pop(); + if (p) { + p->next = node; + } + p = node; + if (node->left) { + q.push(node->left); + } + if (node->right) { + q.push(node->right); + } + } + } + return root; + } +}; +``` + +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Left *Node + * Right *Node + * Next *Node + * } + */ + +func connect(root *Node) *Node { + if root == nil { + return root + } + q := []*Node{root} + for len(q) > 0 { + var p *Node + for n := len(q); n > 0; n-- { + node := q[0] + q = q[1:] + if p != nil { + p.Next = node + } + p = node + if node.Left != nil { + q = append(q, node.Left) + } + if node.Right != nil { + q = append(q, node.Right) + } + } + } + return root +} +``` + +```ts +/** + * Definition for Node. + * class Node { + * val: number + * left: Node | null + * right: Node | null + * next: Node | null + * constructor(val?: number, left?: Node, right?: Node, next?: Node) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function connect(root: Node | null): Node | null { + if (!root) { + return null; + } + const q: Node[] = [root]; + while (q.length) { + const nq: Node[] = []; + let p: Node | null = null; + for (const node of q) { + if (p) { + p.next = node; + } + p = node; + const { left, right } = node; + left && nq.push(left); + right && nq.push(right); + } + q.splice(0, q.length, ...nq); + } + return root; +} +``` + +```cs +/* +// Definition for a Node. +public class Node { + public int val; + public Node left; + public Node right; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _left, Node _right, Node _next) { + val = _val; + left = _left; + right = _right; + next = _next; + } +} +*/ + +public class Solution { + public Node Connect(Node root) { + if (root == null) { + return null; + } + var q = new Queue(); + q.Enqueue(root); + while (q.Count > 0) { + Node p = null; + for (int i = q.Count; i > 0; --i) { + var node = q.Dequeue(); + if (p != null) { + p.next = node; + } + p = node; + if (node.left != null) { + q.Enqueue(node.left); + } + if (node.right != null) { + q.Enqueue(node.right); + } + } + } + return root; + } +} +``` + + + +### 方法二:空间优化 + +方法一的空间复杂度较高,因为需要使用队列存储每一层的节点。我们可以使用常数空间来实现。 + +定义两个指针 $prev$ 和 $next$,分别指向下一层的前一个节点和第一个节点。遍历当前层的节点时,把下一层的节点串起来,同时找到下一层的第一个节点。当前层遍历完后,把下一层的第一个节点 $next$ 赋值给 $node$,继续遍历。 + +时间复杂度 $O(n)$,其中 $n$ 为二叉树的节点个数。空间复杂度 $O(1)$。 + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): + self.val = val + self.left = left + self.right = right + self.next = next +""" + + +class Solution: + def connect(self, root: 'Node') -> 'Node': + def modify(curr): + nonlocal prev, next + if curr is None: + return + next = next or curr + if prev: + prev.next = curr + prev = curr + + node = root + while node: + prev = next = None + while node: + modify(node.left) + modify(node.right) + node = node.next + node = next + return root +``` + ```java /* // Definition for a Node. @@ -257,56 +428,6 @@ class Solution { } ``` -### **C++** - -```cpp -/* -// Definition for a Node. -class Node { -public: - int val; - Node* left; - Node* right; - Node* next; - - Node() : val(0), left(NULL), right(NULL), next(NULL) {} - - Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} - - Node(int _val, Node* _left, Node* _right, Node* _next) - : val(_val), left(_left), right(_right), next(_next) {} -}; -*/ - -class Solution { -public: - Node* connect(Node* root) { - if (!root) { - return root; - } - queue q{{root}}; - while (!q.empty()) { - Node* p = nullptr; - for (int n = q.size(); n; --n) { - Node* node = q.front(); - q.pop(); - if (p) { - p->next = node; - } - p = node; - if (node->left) { - q.push(node->left); - } - if (node->right) { - q.push(node->right); - } - } - } - return root; - } -}; -``` - ```cpp /* // Definition for a Node. @@ -358,45 +479,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a Node. - * type Node struct { - * Val int - * Left *Node - * Right *Node - * Next *Node - * } - */ - -func connect(root *Node) *Node { - if root == nil { - return root - } - q := []*Node{root} - for len(q) > 0 { - var p *Node - for n := len(q); n > 0; n-- { - node := q[0] - q = q[1:] - if p != nil { - p.Next = node - } - p = node - if node.Left != nil { - q = append(q, node.Left) - } - if node.Right != nil { - q = append(q, node.Right) - } - } - } - return root -} -``` - ```go /** * Definition for a Node. @@ -436,48 +518,6 @@ func connect(root *Node) *Node { } ``` -### **TypeScript** - -```ts -/** - * Definition for Node. - * class Node { - * val: number - * left: Node | null - * right: Node | null - * next: Node | null - * constructor(val?: number, left?: Node, right?: Node, next?: Node) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * this.next = (next===undefined ? null : next) - * } - * } - */ - -function connect(root: Node | null): Node | null { - if (!root) { - return null; - } - const q: Node[] = [root]; - while (q.length) { - const nq: Node[] = []; - let p: Node | null = null; - for (const node of q) { - if (p) { - p.next = node; - } - p = node; - const { left, right } = node; - left && nq.push(left); - right && nq.push(right); - } - q.splice(0, q.length, ...nq); - } - return root; -} -``` - ```ts /** * Definition for Node. @@ -521,60 +561,6 @@ function connect(root: Node | null): Node | null { } ``` -### **C#** - -```cs -/* -// Definition for a Node. -public class Node { - public int val; - public Node left; - public Node right; - public Node next; - - public Node() {} - - public Node(int _val) { - val = _val; - } - - public Node(int _val, Node _left, Node _right, Node _next) { - val = _val; - left = _left; - right = _right; - next = _next; - } -} -*/ - -public class Solution { - public Node Connect(Node root) { - if (root == null) { - return null; - } - var q = new Queue(); - q.Enqueue(root); - while (q.Count > 0) { - Node p = null; - for (int i = q.Count; i > 0; --i) { - var node = q.Dequeue(); - if (p != null) { - p.next = node; - } - p = node; - if (node.left != null) { - q.Enqueue(node.left); - } - if (node.right != null) { - q.Enqueue(node.right); - } - } - } - return root; - } -} -``` - ```cs /* // Definition for a Node. @@ -632,10 +618,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/README_EN.md b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/README_EN.md index 2e8d2042f165b..98414594ccf42 100644 --- a/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/README_EN.md +++ b/solution/0100-0199/0117.Populating Next Right Pointers in Each Node II/README_EN.md @@ -53,24 +53,14 @@ struct Node { ## Solutions -**Solution 1: BFS** +### Solution 1: BFS We use a queue $q$ for level order traversal. Each time we traverse a level, we connect the nodes of the current level in order. The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. -**Solution 2: Space Optimization** - -The space complexity of Solution 1 is relatively high because it requires a queue to store the nodes of each level. We can implement it with constant space. - -We define two pointers $prev$ and $next$, which point to the previous node and the first node of the next level, respectively. When traversing the nodes of the current level, we string the nodes of the next level together and find the first node of the next level. After the current level is traversed, we assign the first node $next$ of the next level to $node$ and continue to traverse. - -The time complexity is $O(n)$, where $n$ is the number of nodes in the binary tree. The space complexity is $O(1)$. - -### **Python3** - ```python """ # Definition for a Node. @@ -102,42 +92,6 @@ class Solution: return root ``` -```python -""" -# Definition for a Node. -class Node: - def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): - self.val = val - self.left = left - self.right = right - self.next = next -""" - - -class Solution: - def connect(self, root: 'Node') -> 'Node': - def modify(curr): - nonlocal prev, next - if curr is None: - return - next = next or curr - if prev: - prev.next = curr - prev = curr - - node = root - while node: - prev = next = None - while node: - modify(node.left) - modify(node.right) - node = node.next - node = next - return root -``` - -### **Java** - ```java /* // Definition for a Node. @@ -190,6 +144,229 @@ class Solution { } ``` +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + Node* next; + + Node() : val(0), left(NULL), right(NULL), next(NULL) {} + + Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} + + Node(int _val, Node* _left, Node* _right, Node* _next) + : val(_val), left(_left), right(_right), next(_next) {} +}; +*/ + +class Solution { +public: + Node* connect(Node* root) { + if (!root) { + return root; + } + queue q{{root}}; + while (!q.empty()) { + Node* p = nullptr; + for (int n = q.size(); n; --n) { + Node* node = q.front(); + q.pop(); + if (p) { + p->next = node; + } + p = node; + if (node->left) { + q.push(node->left); + } + if (node->right) { + q.push(node->right); + } + } + } + return root; + } +}; +``` + +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Left *Node + * Right *Node + * Next *Node + * } + */ + +func connect(root *Node) *Node { + if root == nil { + return root + } + q := []*Node{root} + for len(q) > 0 { + var p *Node + for n := len(q); n > 0; n-- { + node := q[0] + q = q[1:] + if p != nil { + p.Next = node + } + p = node + if node.Left != nil { + q = append(q, node.Left) + } + if node.Right != nil { + q = append(q, node.Right) + } + } + } + return root +} +``` + +```ts +/** + * Definition for Node. + * class Node { + * val: number + * left: Node | null + * right: Node | null + * next: Node | null + * constructor(val?: number, left?: Node, right?: Node, next?: Node) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function connect(root: Node | null): Node | null { + if (!root) { + return null; + } + const q: Node[] = [root]; + while (q.length) { + const nq: Node[] = []; + let p: Node | null = null; + for (const node of q) { + if (p) { + p.next = node; + } + p = node; + const { left, right } = node; + left && nq.push(left); + right && nq.push(right); + } + q.splice(0, q.length, ...nq); + } + return root; +} +``` + +```cs +/* +// Definition for a Node. +public class Node { + public int val; + public Node left; + public Node right; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _left, Node _right, Node _next) { + val = _val; + left = _left; + right = _right; + next = _next; + } +} +*/ + +public class Solution { + public Node Connect(Node root) { + if (root == null) { + return null; + } + var q = new Queue(); + q.Enqueue(root); + while (q.Count > 0) { + Node p = null; + for (int i = q.Count; i > 0; --i) { + var node = q.Dequeue(); + if (p != null) { + p.next = node; + } + p = node; + if (node.left != null) { + q.Enqueue(node.left); + } + if (node.right != null) { + q.Enqueue(node.right); + } + } + } + return root; + } +} +``` + + + +### Solution 2: Space Optimization + +The space complexity of Solution 1 is relatively high because it requires a queue to store the nodes of each level. We can implement it with constant space. + +We define two pointers $prev$ and $next$, which point to the previous node and the first node of the next level, respectively. When traversing the nodes of the current level, we string the nodes of the next level together and find the first node of the next level. After the current level is traversed, we assign the first node $next$ of the next level to $node$ and continue to traverse. + +The time complexity is $O(n)$, where $n$ is the number of nodes in the binary tree. The space complexity is $O(1)$. + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): + self.val = val + self.left = left + self.right = right + self.next = next +""" + + +class Solution: + def connect(self, root: 'Node') -> 'Node': + def modify(curr): + nonlocal prev, next + if curr is None: + return + next = next or curr + if prev: + prev.next = curr + prev = curr + + node = root + while node: + prev = next = None + while node: + modify(node.left) + modify(node.right) + node = node.next + node = next + return root +``` + ```java /* // Definition for a Node. @@ -247,56 +424,6 @@ class Solution { } ``` -### **C++** - -```cpp -/* -// Definition for a Node. -class Node { -public: - int val; - Node* left; - Node* right; - Node* next; - - Node() : val(0), left(NULL), right(NULL), next(NULL) {} - - Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} - - Node(int _val, Node* _left, Node* _right, Node* _next) - : val(_val), left(_left), right(_right), next(_next) {} -}; -*/ - -class Solution { -public: - Node* connect(Node* root) { - if (!root) { - return root; - } - queue q{{root}}; - while (!q.empty()) { - Node* p = nullptr; - for (int n = q.size(); n; --n) { - Node* node = q.front(); - q.pop(); - if (p) { - p->next = node; - } - p = node; - if (node->left) { - q.push(node->left); - } - if (node->right) { - q.push(node->right); - } - } - } - return root; - } -}; -``` - ```cpp /* // Definition for a Node. @@ -348,45 +475,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a Node. - * type Node struct { - * Val int - * Left *Node - * Right *Node - * Next *Node - * } - */ - -func connect(root *Node) *Node { - if root == nil { - return root - } - q := []*Node{root} - for len(q) > 0 { - var p *Node - for n := len(q); n > 0; n-- { - node := q[0] - q = q[1:] - if p != nil { - p.Next = node - } - p = node - if node.Left != nil { - q = append(q, node.Left) - } - if node.Right != nil { - q = append(q, node.Right) - } - } - } - return root -} -``` - ```go /** * Definition for a Node. @@ -426,48 +514,6 @@ func connect(root *Node) *Node { } ``` -### **TypeScript** - -```ts -/** - * Definition for Node. - * class Node { - * val: number - * left: Node | null - * right: Node | null - * next: Node | null - * constructor(val?: number, left?: Node, right?: Node, next?: Node) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * this.next = (next===undefined ? null : next) - * } - * } - */ - -function connect(root: Node | null): Node | null { - if (!root) { - return null; - } - const q: Node[] = [root]; - while (q.length) { - const nq: Node[] = []; - let p: Node | null = null; - for (const node of q) { - if (p) { - p.next = node; - } - p = node; - const { left, right } = node; - left && nq.push(left); - right && nq.push(right); - } - q.splice(0, q.length, ...nq); - } - return root; -} -``` - ```ts /** * Definition for Node. @@ -511,60 +557,6 @@ function connect(root: Node | null): Node | null { } ``` -### **C#** - -```cs -/* -// Definition for a Node. -public class Node { - public int val; - public Node left; - public Node right; - public Node next; - - public Node() {} - - public Node(int _val) { - val = _val; - } - - public Node(int _val, Node _left, Node _right, Node _next) { - val = _val; - left = _left; - right = _right; - next = _next; - } -} -*/ - -public class Solution { - public Node Connect(Node root) { - if (root == null) { - return null; - } - var q = new Queue(); - q.Enqueue(root); - while (q.Count > 0) { - Node p = null; - for (int i = q.Count; i > 0; --i) { - var node = q.Dequeue(); - if (p != null) { - p.next = node; - } - p = node; - if (node.left != null) { - q.Enqueue(node.left); - } - if (node.right != null) { - q.Enqueue(node.right); - } - } - } - return root; - } -} -``` - ```cs /* // Definition for a Node. @@ -622,10 +614,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0118.Pascal's Triangle/README.md b/solution/0100-0199/0118.Pascal's Triangle/README.md index 879c9528b9799..23497a3ad8240 100644 --- a/solution/0100-0199/0118.Pascal's Triangle/README.md +++ b/solution/0100-0199/0118.Pascal's Triangle/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们先创建一个答案数组 $f$,然后将 $f$ 的第一行元素设为 $[1]$。接下来,我们从第二行开始,每一行的开头和结尾元素都是 $1$,其它 $f[i][j] = f[i - 1][j - 1] + f[i - 1][j]$。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python class Solution: def generate(self, numRows: int) -> List[List[int]]: @@ -62,10 +56,6 @@ class Solution: return f ``` -### **Java** - - - ```java class Solution { public List> generate(int numRows) { @@ -85,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,31 +95,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn generate(num_rows: i32) -> Vec> { - let mut ret_vec: Vec> = Vec::new(); - let mut cur_vec: Vec = Vec::new(); - - for i in 0..num_rows as usize { - let mut new_vec: Vec = vec![1; i + 1]; - for j in 1..i { - new_vec[j] = cur_vec[j - 1] + cur_vec[j]; - } - cur_vec = new_vec.clone(); - ret_vec.push(new_vec); - } - - ret_vec - } -} -``` - -### **Go** - ```go func generate(numRows int) [][]int { f := [][]int{[]int{1}} @@ -147,8 +110,6 @@ func generate(numRows int) [][]int { } ``` -### **TypeScript** - ```ts function generate(numRows: number): number[][] { const f: number[][] = [[1]]; @@ -164,7 +125,26 @@ function generate(numRows: number): number[][] { } ``` -### **JavaScript** +```rust +impl Solution { + #[allow(dead_code)] + pub fn generate(num_rows: i32) -> Vec> { + let mut ret_vec: Vec> = Vec::new(); + let mut cur_vec: Vec = Vec::new(); + + for i in 0..num_rows as usize { + let mut new_vec: Vec = vec![1; i + 1]; + for j in 1..i { + new_vec[j] = cur_vec[j - 1] + cur_vec[j]; + } + cur_vec = new_vec.clone(); + ret_vec.push(new_vec); + } + + ret_vec + } +} +``` ```js /** @@ -185,10 +165,6 @@ var generate = function (numRows) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0118.Pascal's Triangle/README_EN.md b/solution/0100-0199/0118.Pascal's Triangle/README_EN.md index 9237c2fdefc48..d3d0aa74e9853 100644 --- a/solution/0100-0199/0118.Pascal's Triangle/README_EN.md +++ b/solution/0100-0199/0118.Pascal's Triangle/README_EN.md @@ -25,7 +25,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation First, we create an answer array $f$, and then set the first row of $f$ to $[1]$. Next, starting from the second row, the first and last elements of each row are $1$, and the other elements are calculated by $f[i][j] = f[i - 1][j - 1] + f[i - 1][j]$. @@ -33,8 +33,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ -### **Python3** - ```python class Solution: def generate(self, numRows: int) -> List[List[int]]: @@ -45,8 +43,6 @@ class Solution: return f ``` -### **Java** - ```java class Solution { public List> generate(int numRows) { @@ -66,8 +62,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -88,31 +82,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn generate(num_rows: i32) -> Vec> { - let mut ret_vec: Vec> = Vec::new(); - let mut cur_vec: Vec = Vec::new(); - - for i in 0..num_rows as usize { - let mut new_vec: Vec = vec![1; i + 1]; - for j in 1..i { - new_vec[j] = cur_vec[j - 1] + cur_vec[j]; - } - cur_vec = new_vec.clone(); - ret_vec.push(new_vec); - } - - ret_vec - } -} -``` - -### **Go** - ```go func generate(numRows int) [][]int { f := [][]int{[]int{1}} @@ -128,8 +97,6 @@ func generate(numRows int) [][]int { } ``` -### **TypeScript** - ```ts function generate(numRows: number): number[][] { const f: number[][] = [[1]]; @@ -145,7 +112,26 @@ function generate(numRows: number): number[][] { } ``` -### **JavaScript** +```rust +impl Solution { + #[allow(dead_code)] + pub fn generate(num_rows: i32) -> Vec> { + let mut ret_vec: Vec> = Vec::new(); + let mut cur_vec: Vec = Vec::new(); + + for i in 0..num_rows as usize { + let mut new_vec: Vec = vec![1; i + 1]; + for j in 1..i { + new_vec[j] = cur_vec[j - 1] + cur_vec[j]; + } + cur_vec = new_vec.clone(); + ret_vec.push(new_vec); + } + + ret_vec + } +} +``` ```js /** @@ -166,10 +152,6 @@ var generate = function (numRows) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0119.Pascal's Triangle II/README.md b/solution/0100-0199/0119.Pascal's Triangle II/README.md index 448c81b857ef8..2f911350df896 100644 --- a/solution/0100-0199/0119.Pascal's Triangle II/README.md +++ b/solution/0100-0199/0119.Pascal's Triangle II/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:递推** +### 方法一:递推 我们创建一个长度为 $rowIndex + 1$ 的数组 $f$,初始时所有元素均为 $1$。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def getRow(self, rowIndex: int) -> List[int]: @@ -79,10 +73,6 @@ class Solution: return f ``` -### **Java** - - - ```java class Solution { public List getRow(int rowIndex) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func getRow(rowIndex int) []int { f := make([]int, rowIndex+1) @@ -134,8 +120,6 @@ func getRow(rowIndex int) []int { } ``` -### **TypeScript** - ```ts function getRow(rowIndex: number): number[] { const f: number[] = Array(rowIndex + 1).fill(1); @@ -148,8 +132,6 @@ function getRow(rowIndex: number): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn get_row(row_index: i32) -> Vec { @@ -165,10 +147,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0119.Pascal's Triangle II/README_EN.md b/solution/0100-0199/0119.Pascal's Triangle II/README_EN.md index 0e73637c3021b..dde569a9e1a3b 100644 --- a/solution/0100-0199/0119.Pascal's Triangle II/README_EN.md +++ b/solution/0100-0199/0119.Pascal's Triangle II/README_EN.md @@ -31,7 +31,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion We create an array $f$ of length $rowIndex + 1$, initially all elements are $1$. @@ -43,8 +43,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ i -### **Python3** - ```python class Solution: def getRow(self, rowIndex: int) -> List[int]: @@ -55,8 +53,6 @@ class Solution: return f ``` -### **Java** - ```java class Solution { public List getRow(int rowIndex) { @@ -74,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +85,6 @@ public: }; ``` -### **Go** - ```go func getRow(rowIndex int) []int { f := make([]int, rowIndex+1) @@ -108,8 +100,6 @@ func getRow(rowIndex int) []int { } ``` -### **TypeScript** - ```ts function getRow(rowIndex: number): number[] { const f: number[] = Array(rowIndex + 1).fill(1); @@ -122,8 +112,6 @@ function getRow(rowIndex: number): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn get_row(row_index: i32) -> Vec { @@ -139,10 +127,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0120.Triangle/README.md b/solution/0100-0199/0120.Triangle/README.md index 0acf09dac2880..ba731d1e0f2bd 100644 --- a/solution/0100-0199/0120.Triangle/README.md +++ b/solution/0100-0199/0120.Triangle/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示从三角形底部走到位置 $(i, j)$ 的最小路径和。这里的位置 $(i, j)$ 指的是三角形中第 $i$ 行第 $j$ 列(均从 $0$ 开始编号)的位置。那么我们有如下的状态转移方程: @@ -73,10 +71,6 @@ $$ -### **Python3** - - - ```python class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: @@ -88,33 +82,6 @@ class Solution: return f[0][0] ``` -```python -class Solution: - def minimumTotal(self, triangle: List[List[int]]) -> int: - n = len(triangle) - f = [0] * (n + 1) - for i in range(n - 1, -1, -1): - for j in range(i + 1): - f[j] = min(f[j], f[j + 1]) + triangle[i][j] - return f[0] -``` - -```python -class Solution: - def minimumTotal(self, triangle: List[List[int]]) -> int: - n = len(triangle) - for i in range(n - 2, -1, -1): - for j in range(i + 1): - triangle[i][j] = ( - min(triangle[i + 1][j], triangle[i + 1][j + 1]) + triangle[i][j] - ) - return triangle[0][0] -``` - -### **Java** - - - ```java class Solution { public int minimumTotal(List> triangle) { @@ -130,23 +97,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumTotal(List> triangle) { - for (int i = triangle.size() - 2; i >= 0; --i) { - for (int j = 0; j <= i; ++j) { - int x = triangle.get(i).get(j); - int y = Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)); - triangle.get(i).set(j, x + y); - } - } - return triangle.get(0).get(0); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -164,22 +114,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minimumTotal(vector>& triangle) { - for (int i = triangle.size() - 2; ~i; --i) { - for (int j = 0; j <= i; ++j) { - triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]); - } - } - return triangle[0][0]; - } -}; -``` - -### **Go** - ```go func minimumTotal(triangle [][]int) int { n := len(triangle) @@ -193,19 +127,6 @@ func minimumTotal(triangle [][]int) int { } ``` -```go -func minimumTotal(triangle [][]int) int { - for i := len(triangle) - 2; i >= 0; i-- { - for j := 0; j <= i; j++ { - triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]) - } - } - return triangle[0][0] -} -``` - -### **TypeScript** - ```ts function minimumTotal(triangle: number[][]): number { const n = triangle.length; @@ -219,19 +140,6 @@ function minimumTotal(triangle: number[][]): number { } ``` -```ts -function minimumTotal(triangle: number[][]): number { - for (let i = triangle.length - 2; ~i; --i) { - for (let j = 0; j <= i; ++j) { - triangle[i][j] += Math.min(triangle[i + 1][j], triangle[i + 1][j + 1]); - } - } - return triangle[0][0]; -} -``` - -### **Rust** - ```rust impl Solution { pub fn minimum_total(triangle: Vec>) -> i32 { @@ -247,6 +155,74 @@ impl Solution { } ``` + + +### 方法二 + + + +```python +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + n = len(triangle) + f = [0] * (n + 1) + for i in range(n - 1, -1, -1): + for j in range(i + 1): + f[j] = min(f[j], f[j + 1]) + triangle[i][j] + return f[0] +``` + +```java +class Solution { + public int minimumTotal(List> triangle) { + for (int i = triangle.size() - 2; i >= 0; --i) { + for (int j = 0; j <= i; ++j) { + int x = triangle.get(i).get(j); + int y = Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)); + triangle.get(i).set(j, x + y); + } + } + return triangle.get(0).get(0); + } +} +``` + +```cpp +class Solution { +public: + int minimumTotal(vector>& triangle) { + for (int i = triangle.size() - 2; ~i; --i) { + for (int j = 0; j <= i; ++j) { + triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]); + } + } + return triangle[0][0]; + } +}; +``` + +```go +func minimumTotal(triangle [][]int) int { + for i := len(triangle) - 2; i >= 0; i-- { + for j := 0; j <= i; j++ { + triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]) + } + } + return triangle[0][0] +} +``` + +```ts +function minimumTotal(triangle: number[][]): number { + for (let i = triangle.length - 2; ~i; --i) { + for (let j = 0; j <= i; ++j) { + triangle[i][j] += Math.min(triangle[i + 1][j], triangle[i + 1][j + 1]); + } + } + return triangle[0][0]; +} +``` + ```rust impl Solution { pub fn minimum_total(triangle: Vec>) -> i32 { @@ -261,10 +237,24 @@ impl Solution { } ``` -### **...** + -``` +### 方法三 + + +```python +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + n = len(triangle) + for i in range(n - 2, -1, -1): + for j in range(i + 1): + triangle[i][j] = ( + min(triangle[i + 1][j], triangle[i + 1][j + 1]) + triangle[i][j] + ) + return triangle[0][0] ``` + + diff --git a/solution/0100-0199/0120.Triangle/README_EN.md b/solution/0100-0199/0120.Triangle/README_EN.md index 60dff94029504..c11de0a1a0eff 100644 --- a/solution/0100-0199/0120.Triangle/README_EN.md +++ b/solution/0100-0199/0120.Triangle/README_EN.md @@ -44,7 +44,7 @@ The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above) ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ as the minimum path sum from the bottom of the triangle to the position $(i, j)$. Here, the position $(i, j)$ refers to the position in the $i$th row and $j$th column of the triangle (both starting from $0$). Then we have the following state transition equation: @@ -62,8 +62,6 @@ Furthermore, we can directly reuse the `triangle` as the `f` array, so there is -### **Python3** - ```python class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: @@ -75,31 +73,6 @@ class Solution: return f[0][0] ``` -```python -class Solution: - def minimumTotal(self, triangle: List[List[int]]) -> int: - n = len(triangle) - f = [0] * (n + 1) - for i in range(n - 1, -1, -1): - for j in range(i + 1): - f[j] = min(f[j], f[j + 1]) + triangle[i][j] - return f[0] -``` - -```python -class Solution: - def minimumTotal(self, triangle: List[List[int]]) -> int: - n = len(triangle) - for i in range(n - 2, -1, -1): - for j in range(i + 1): - triangle[i][j] = ( - min(triangle[i + 1][j], triangle[i + 1][j + 1]) + triangle[i][j] - ) - return triangle[0][0] -``` - -### **Java** - ```java class Solution { public int minimumTotal(List> triangle) { @@ -115,23 +88,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumTotal(List> triangle) { - for (int i = triangle.size() - 2; i >= 0; --i) { - for (int j = 0; j <= i; ++j) { - int x = triangle.get(i).get(j); - int y = Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)); - triangle.get(i).set(j, x + y); - } - } - return triangle.get(0).get(0); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -149,22 +105,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minimumTotal(vector>& triangle) { - for (int i = triangle.size() - 2; ~i; --i) { - for (int j = 0; j <= i; ++j) { - triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]); - } - } - return triangle[0][0]; - } -}; -``` - -### **Go** - ```go func minimumTotal(triangle [][]int) int { n := len(triangle) @@ -178,19 +118,6 @@ func minimumTotal(triangle [][]int) int { } ``` -```go -func minimumTotal(triangle [][]int) int { - for i := len(triangle) - 2; i >= 0; i-- { - for j := 0; j <= i; j++ { - triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]) - } - } - return triangle[0][0] -} -``` - -### **TypeScript** - ```ts function minimumTotal(triangle: number[][]): number { const n = triangle.length; @@ -204,19 +131,6 @@ function minimumTotal(triangle: number[][]): number { } ``` -```ts -function minimumTotal(triangle: number[][]): number { - for (let i = triangle.length - 2; ~i; --i) { - for (let j = 0; j <= i; ++j) { - triangle[i][j] += Math.min(triangle[i + 1][j], triangle[i + 1][j + 1]); - } - } - return triangle[0][0]; -} -``` - -### **Rust** - ```rust impl Solution { pub fn minimum_total(triangle: Vec>) -> i32 { @@ -232,6 +146,74 @@ impl Solution { } ``` + + +### Solution 2 + + + +```python +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + n = len(triangle) + f = [0] * (n + 1) + for i in range(n - 1, -1, -1): + for j in range(i + 1): + f[j] = min(f[j], f[j + 1]) + triangle[i][j] + return f[0] +``` + +```java +class Solution { + public int minimumTotal(List> triangle) { + for (int i = triangle.size() - 2; i >= 0; --i) { + for (int j = 0; j <= i; ++j) { + int x = triangle.get(i).get(j); + int y = Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)); + triangle.get(i).set(j, x + y); + } + } + return triangle.get(0).get(0); + } +} +``` + +```cpp +class Solution { +public: + int minimumTotal(vector>& triangle) { + for (int i = triangle.size() - 2; ~i; --i) { + for (int j = 0; j <= i; ++j) { + triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]); + } + } + return triangle[0][0]; + } +}; +``` + +```go +func minimumTotal(triangle [][]int) int { + for i := len(triangle) - 2; i >= 0; i-- { + for j := 0; j <= i; j++ { + triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]) + } + } + return triangle[0][0] +} +``` + +```ts +function minimumTotal(triangle: number[][]): number { + for (let i = triangle.length - 2; ~i; --i) { + for (let j = 0; j <= i; ++j) { + triangle[i][j] += Math.min(triangle[i + 1][j], triangle[i + 1][j + 1]); + } + } + return triangle[0][0]; +} +``` + ```rust impl Solution { pub fn minimum_total(triangle: Vec>) -> i32 { @@ -246,10 +228,24 @@ impl Solution { } ``` -### **...** + -``` +### Solution 3 + + +```python +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + n = len(triangle) + for i in range(n - 2, -1, -1): + for j in range(i + 1): + triangle[i][j] = ( + min(triangle[i + 1][j], triangle[i + 1][j + 1]) + triangle[i][j] + ) + return triangle[0][0] ``` + + diff --git a/solution/0100-0199/0121.Best Time to Buy and Sell Stock/README.md b/solution/0100-0199/0121.Best Time to Buy and Sell Stock/README.md index 2168086a899f1..9013c6d5d9c10 100644 --- a/solution/0100-0199/0121.Best Time to Buy and Sell Stock/README.md +++ b/solution/0100-0199/0121.Best Time to Buy and Sell Stock/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:枚举 + 维护前缀最小值** +### 方法一:枚举 + 维护前缀最小值 我们可以枚举数组 $nums$ 每个元素作为卖出价格,那么我们需要在前面找到一个最小值作为买入价格,这样才能使得利润最大化。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def maxProfit(self, prices: List[int]) -> int: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxProfit(int[] prices) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +91,6 @@ public: }; ``` -### **Go** - ```go func maxProfit(prices []int) (ans int) { mi := prices[0] @@ -116,7 +102,31 @@ func maxProfit(prices []int) (ans int) { } ``` -### **JavaScript** +```ts +function maxProfit(prices: number[]): number { + let ans = 0; + let mi = prices[0]; + for (const v of prices) { + ans = Math.max(ans, v - mi); + mi = Math.min(mi, v); + } + return ans; +} +``` + +```rust +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + let mut res = 0; + let mut min = i32::MAX; + for price in prices { + res = res.max(price - min); + min = min.min(price); + } + res + } +} +``` ```js /** @@ -134,8 +144,6 @@ var maxProfit = function (prices) { }; ``` -### **C#** - ```cs public class Solution { public int MaxProfit(int[] prices) { @@ -149,38 +157,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function maxProfit(prices: number[]): number { - let ans = 0; - let mi = prices[0]; - for (const v of prices) { - ans = Math.max(ans, v - mi); - mi = Math.min(mi, v); - } - return ans; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn max_profit(prices: Vec) -> i32 { - let mut res = 0; - let mut min = i32::MAX; - for price in prices { - res = res.max(price - min); - min = min.min(price); - } - res - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -200,10 +176,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0121.Best Time to Buy and Sell Stock/README_EN.md b/solution/0100-0199/0121.Best Time to Buy and Sell Stock/README_EN.md index 290d82dc6260d..ea59c16f9734f 100644 --- a/solution/0100-0199/0121.Best Time to Buy and Sell Stock/README_EN.md +++ b/solution/0100-0199/0121.Best Time to Buy and Sell Stock/README_EN.md @@ -38,7 +38,7 @@ Note that buying on day 2 and selling on day 1 is not allowed because you must b ## Solutions -**Solution 1: Enumerate + Maintain the Minimum Value of the Prefix** +### Solution 1: Enumerate + Maintain the Minimum Value of the Prefix We can enumerate each element of the array $nums$ as the selling price. Then we need to find a minimum value in front of it as the purchase price to maximize the profit. @@ -50,8 +50,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def maxProfit(self, prices: List[int]) -> int: @@ -62,8 +60,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxProfit(int[] prices) { @@ -77,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +87,6 @@ public: }; ``` -### **Go** - ```go func maxProfit(prices []int) (ans int) { mi := prices[0] @@ -106,7 +98,31 @@ func maxProfit(prices []int) (ans int) { } ``` -### **JavaScript** +```ts +function maxProfit(prices: number[]): number { + let ans = 0; + let mi = prices[0]; + for (const v of prices) { + ans = Math.max(ans, v - mi); + mi = Math.min(mi, v); + } + return ans; +} +``` + +```rust +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + let mut res = 0; + let mut min = i32::MAX; + for price in prices { + res = res.max(price - min); + min = min.min(price); + } + res + } +} +``` ```js /** @@ -124,8 +140,6 @@ var maxProfit = function (prices) { }; ``` -### **C#** - ```cs public class Solution { public int MaxProfit(int[] prices) { @@ -139,38 +153,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function maxProfit(prices: number[]): number { - let ans = 0; - let mi = prices[0]; - for (const v of prices) { - ans = Math.max(ans, v - mi); - mi = Math.min(mi, v); - } - return ans; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn max_profit(prices: Vec) -> i32 { - let mut res = 0; - let mut min = i32::MAX; - for price in prices { - res = res.max(price - min); - min = min.min(price); - } - res - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -190,10 +172,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/README.md b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/README.md index a2a5d0b4a7fef..24de95480f8fc 100644 --- a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/README.md +++ b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/README.md @@ -49,15 +49,106 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 从第二天开始,如果当天股价大于前一天股价,则在前一天买入,当天卖出,即可获得利润。如果当天股价小于前一天股价,则不买入,不卖出。也即是说,所有上涨交易日都做买卖,所有下跌交易日都不做买卖,最终获得的利润是最大的。 时间复杂度 $O(n)$,其中 $n$ 为数组 `prices` 的长度。空间复杂度 $O(1)$。 -**方法二:动态规划** + + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + return sum(max(0, b - a) for a, b in pairwise(prices)) +``` + +```java +class Solution { + public int maxProfit(int[] prices) { + int ans = 0; + for (int i = 1; i < prices.length; ++i) { + ans += Math.max(0, prices[i] - prices[i - 1]); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int ans = 0; + for (int i = 1; i < prices.size(); ++i) ans += max(0, prices[i] - prices[i - 1]); + return ans; + } +}; +``` + +```go +func maxProfit(prices []int) (ans int) { + for i, v := range prices[1:] { + t := v - prices[i] + if t > 0 { + ans += t + } + } + return +} +``` + +```ts +function maxProfit(prices: number[]): number { + let ans = 0; + for (let i = 1; i < prices.length; i++) { + ans += Math.max(0, prices[i] - prices[i - 1]); + } + return ans; +} +``` + +```rust +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + let mut res = 0; + for i in 1..prices.len() { + res += (0).max(prices[i] - prices[i - 1]); + } + res + } +} +``` + +```js +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function (prices) { + let ans = 0; + for (let i = 1; i < prices.length; i++) { + ans += Math.max(0, prices[i] - prices[i - 1]); + } + return ans; +}; +``` + +```cs +public class Solution { + public int MaxProfit(int[] prices) { + int ans = 0; + for (int i = 1; i < prices.Length; ++i) { + ans += Math.Max(0, prices[i] - prices[i - 1]); + } + return ans; + } +} +``` + + + +### 方法二:动态规划 我们设 $f[i][j]$ 表示第 $i$ 天交易完后的最大利润,其中 $j$ 表示当前是否持有股票,持有股票时 $j=0$,不持有股票时 $j=1$。初始状态为 $f[0][0]=-prices[0]$,其余状态均为 $0$。 @@ -78,24 +169,8 @@ $$ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `prices` 的长度。 -**方法三:动态规划(空间优化)** - -我们可以发现,在方法二中,第 $i$ 天的状态,只与第 $i-1$ 天的状态有关,因此我们可以只用两个变量来维护第 $i-1$ 天的状态,从而将空间复杂度优化到 $O(1)$。 - -时间复杂度 $O(n)$,其中 $n$ 为数组 `prices` 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - -```python -class Solution: - def maxProfit(self, prices: List[int]) -> int: - return sum(max(0, b - a) for a, b in pairwise(prices)) -``` - ```python class Solution: def maxProfit(self, prices: List[int]) -> int: @@ -108,35 +183,6 @@ class Solution: return f[n - 1][1] ``` -```python -class Solution: - def maxProfit(self, prices: List[int]) -> int: - n = len(prices) - f = [-prices[0], 0] - for i in range(1, n): - g = [0] * 2 - g[0] = max(f[0], f[1] - prices[i]) - g[1] = max(f[1], f[0] + prices[i]) - f = g - return f[1] -``` - -### **Java** - - - -```java -class Solution { - public int maxProfit(int[] prices) { - int ans = 0; - for (int i = 1; i < prices.length; ++i) { - ans += Math.max(0, prices[i] - prices[i - 1]); - } - return ans; - } -} -``` - ```java class Solution { public int maxProfit(int[] prices) { @@ -152,35 +198,6 @@ class Solution { } ``` -```java -class Solution { - public int maxProfit(int[] prices) { - int n = prices.length; - int[] f = new int[] {-prices[0], 0}; - for (int i = 1; i < n; ++i) { - int[] g = new int[2]; - g[0] = Math.max(f[0], f[1] - prices[i]); - g[1] = Math.max(f[1], f[0] + prices[i]); - f = g; - } - return f[1]; - } -} -``` - -### **C++** - -```cpp -class Solution { -public: - int maxProfit(vector& prices) { - int ans = 0; - for (int i = 1; i < prices.size(); ++i) ans += max(0, prices[i] - prices[i - 1]); - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -198,37 +215,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxProfit(vector& prices) { - int n = prices.size(); - int f[2] = {-prices[0], 0}; - for (int i = 1; i < n; ++i) { - int g[2]; - g[0] = max(f[0], f[1] - prices[i]); - g[1] = max(f[1], f[0] + prices[i]); - f[0] = g[0], f[1] = g[1]; - } - return f[1]; - } -}; -``` - -### **Go** - -```go -func maxProfit(prices []int) (ans int) { - for i, v := range prices[1:] { - t := v - prices[i] - if t > 0 { - ans += t - } - } - return -} -``` - ```go func maxProfit(prices []int) int { n := len(prices) @@ -242,46 +228,6 @@ func maxProfit(prices []int) int { } ``` -```go -func maxProfit(prices []int) int { - n := len(prices) - f := [2]int{-prices[0], 0} - for i := 1; i < n; i++ { - g := [2]int{} - g[0] = max(f[0], f[1]-prices[i]) - g[1] = max(f[1], f[0]+prices[i]) - f = g - } - return f[1] -} -``` - -### **TypeScript** - -```ts -function maxProfit(prices: number[]): number { - let ans = 0; - for (let i = 1; i < prices.length; i++) { - ans += Math.max(0, prices[i] - prices[i - 1]); - } - return ans; -} -``` - -### **C#** - -```cs -public class Solution { - public int MaxProfit(int[] prices) { - int ans = 0; - for (int i = 1; i < prices.Length; ++i) { - ans += Math.Max(0, prices[i] - prices[i - 1]); - } - return ans; - } -} -``` - ```cs public class Solution { public int MaxProfit(int[] prices) { @@ -296,40 +242,76 @@ public class Solution { } ``` -### **JavaScript** + -```js -/** - * @param {number[]} prices - * @return {number} - */ -var maxProfit = function (prices) { - let ans = 0; - for (let i = 1; i < prices.length; i++) { - ans += Math.max(0, prices[i] - prices[i - 1]); - } - return ans; -}; -``` +### 方法三:动态规划(空间优化) -### **Rust** +我们可以发现,在方法二中,第 $i$ 天的状态,只与第 $i-1$ 天的状态有关,因此我们可以只用两个变量来维护第 $i-1$ 天的状态,从而将空间复杂度优化到 $O(1)$。 -```rust -impl Solution { - pub fn max_profit(prices: Vec) -> i32 { - let mut res = 0; - for i in 1..prices.len() { - res += (0).max(prices[i] - prices[i - 1]); +时间复杂度 $O(n)$,其中 $n$ 为数组 `prices` 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + n = len(prices) + f = [-prices[0], 0] + for i in range(1, n): + g = [0] * 2 + g[0] = max(f[0], f[1] - prices[i]) + g[1] = max(f[1], f[0] + prices[i]) + f = g + return f[1] +``` + +```java +class Solution { + public int maxProfit(int[] prices) { + int n = prices.length; + int[] f = new int[] {-prices[0], 0}; + for (int i = 1; i < n; ++i) { + int[] g = new int[2]; + g[0] = Math.max(f[0], f[1] - prices[i]); + g[1] = Math.max(f[1], f[0] + prices[i]); + f = g; } - res + return f[1]; } } ``` -### **...** - +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int n = prices.size(); + int f[2] = {-prices[0], 0}; + for (int i = 1; i < n; ++i) { + int g[2]; + g[0] = max(f[0], f[1] - prices[i]); + g[1] = max(f[1], f[0] + prices[i]); + f[0] = g[0], f[1] = g[1]; + } + return f[1]; + } +}; ``` +```go +func maxProfit(prices []int) int { + n := len(prices) + f := [2]int{-prices[0], 0} + for i := 1; i < n; i++ { + g := [2]int{} + g[0] = max(f[0], f[1]-prices[i]) + g[1] = max(f[1], f[0]+prices[i]) + f = g + } + return f[1] +} ``` + + diff --git a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/README_EN.md b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/README_EN.md index c7a351ecb213e..47504597f490c 100644 --- a/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/README_EN.md +++ b/solution/0100-0199/0122.Best Time to Buy and Sell Stock II/README_EN.md @@ -48,13 +48,106 @@ Total profit is 4. ## Solutions -**Solution 1: Greedy Algorithm** +### Solution 1: Greedy Algorithm Starting from the second day, if the stock price is higher than the previous day, buy on the previous day and sell on the current day to make a profit. If the stock price is lower than the previous day, do not buy or sell. In other words, buy and sell on all rising trading days, and do not trade on all falling trading days. The final profit will be the maximum. The time complexity is $O(n)$, where $n$ is the length of the `prices` array. The space complexity is $O(1)$. -**Solution 2: Dynamic Programming** + + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + return sum(max(0, b - a) for a, b in pairwise(prices)) +``` + +```java +class Solution { + public int maxProfit(int[] prices) { + int ans = 0; + for (int i = 1; i < prices.length; ++i) { + ans += Math.max(0, prices[i] - prices[i - 1]); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int ans = 0; + for (int i = 1; i < prices.size(); ++i) ans += max(0, prices[i] - prices[i - 1]); + return ans; + } +}; +``` + +```go +func maxProfit(prices []int) (ans int) { + for i, v := range prices[1:] { + t := v - prices[i] + if t > 0 { + ans += t + } + } + return +} +``` + +```ts +function maxProfit(prices: number[]): number { + let ans = 0; + for (let i = 1; i < prices.length; i++) { + ans += Math.max(0, prices[i] - prices[i - 1]); + } + return ans; +} +``` + +```rust +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + let mut res = 0; + for i in 1..prices.len() { + res += (0).max(prices[i] - prices[i - 1]); + } + res + } +} +``` + +```js +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function (prices) { + let ans = 0; + for (let i = 1; i < prices.length; i++) { + ans += Math.max(0, prices[i] - prices[i - 1]); + } + return ans; +}; +``` + +```cs +public class Solution { + public int MaxProfit(int[] prices) { + int ans = 0; + for (int i = 1; i < prices.Length; ++i) { + ans += Math.Max(0, prices[i] - prices[i - 1]); + } + return ans; + } +} +``` + + + +### Solution 2: Dynamic Programming We define $f[i][j]$ as the maximum profit after trading on the $i$th day, where $j$ indicates whether we currently hold the stock. When holding the stock, $j=0$, and when not holding the stock, $j=1$. The initial state is $f[0][0]=-prices[0]$, and all other states are $0$. @@ -75,22 +168,8 @@ The final answer is $f[n-1][1]$, where $n$ is the length of the `prices` array. The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the `prices` array. -**Solution 3: Dynamic Programming (Space Optimization)** - -We can find that in Solution 2, the state of the $i$th day is only related to the state of the $i-1$th day. Therefore, we can use only two variables to maintain the state of the $i-1$th day, thereby optimizing the space complexity to $O(1)$. - -The time complexity is $O(n)$, where $n$ is the length of the `prices` array. The space complexity is $O(1)$. - -### **Python3** - -```python -class Solution: - def maxProfit(self, prices: List[int]) -> int: - return sum(max(0, b - a) for a, b in pairwise(prices)) -``` - ```python class Solution: def maxProfit(self, prices: List[int]) -> int: @@ -103,33 +182,6 @@ class Solution: return f[n - 1][1] ``` -```python -class Solution: - def maxProfit(self, prices: List[int]) -> int: - n = len(prices) - f = [-prices[0], 0] - for i in range(1, n): - g = [0] * 2 - g[0] = max(f[0], f[1] - prices[i]) - g[1] = max(f[1], f[0] + prices[i]) - f = g - return f[1] -``` - -### **Java** - -```java -class Solution { - public int maxProfit(int[] prices) { - int ans = 0; - for (int i = 1; i < prices.length; ++i) { - ans += Math.max(0, prices[i] - prices[i - 1]); - } - return ans; - } -} -``` - ```java class Solution { public int maxProfit(int[] prices) { @@ -145,35 +197,6 @@ class Solution { } ``` -```java -class Solution { - public int maxProfit(int[] prices) { - int n = prices.length; - int[] f = new int[] {-prices[0], 0}; - for (int i = 1; i < n; ++i) { - int[] g = new int[2]; - g[0] = Math.max(f[0], f[1] - prices[i]); - g[1] = Math.max(f[1], f[0] + prices[i]); - f = g; - } - return f[1]; - } -} -``` - -### **C++** - -```cpp -class Solution { -public: - int maxProfit(vector& prices) { - int ans = 0; - for (int i = 1; i < prices.size(); ++i) ans += max(0, prices[i] - prices[i - 1]); - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -191,37 +214,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxProfit(vector& prices) { - int n = prices.size(); - int f[2] = {-prices[0], 0}; - for (int i = 1; i < n; ++i) { - int g[2]; - g[0] = max(f[0], f[1] - prices[i]); - g[1] = max(f[1], f[0] + prices[i]); - f[0] = g[0], f[1] = g[1]; - } - return f[1]; - } -}; -``` - -### **Go** - -```go -func maxProfit(prices []int) (ans int) { - for i, v := range prices[1:] { - t := v - prices[i] - if t > 0 { - ans += t - } - } - return -} -``` - ```go func maxProfit(prices []int) int { n := len(prices) @@ -235,46 +227,6 @@ func maxProfit(prices []int) int { } ``` -```go -func maxProfit(prices []int) int { - n := len(prices) - f := [2]int{-prices[0], 0} - for i := 1; i < n; i++ { - g := [2]int{} - g[0] = max(f[0], f[1]-prices[i]) - g[1] = max(f[1], f[0]+prices[i]) - f = g - } - return f[1] -} -``` - -### **TypeScript** - -```ts -function maxProfit(prices: number[]): number { - let ans = 0; - for (let i = 1; i < prices.length; i++) { - ans += Math.max(0, prices[i] - prices[i - 1]); - } - return ans; -} -``` - -### **C#** - -```cs -public class Solution { - public int MaxProfit(int[] prices) { - int ans = 0; - for (int i = 1; i < prices.Length; ++i) { - ans += Math.Max(0, prices[i] - prices[i - 1]); - } - return ans; - } -} -``` - ```cs public class Solution { public int MaxProfit(int[] prices) { @@ -289,40 +241,76 @@ public class Solution { } ``` -### **JavaScript** + -```js -/** - * @param {number[]} prices - * @return {number} - */ -var maxProfit = function (prices) { - let ans = 0; - for (let i = 1; i < prices.length; i++) { - ans += Math.max(0, prices[i] - prices[i - 1]); - } - return ans; -}; -``` +### Solution 3: Dynamic Programming (Space Optimization) -### **Rust** +We can find that in Solution 2, the state of the $i$th day is only related to the state of the $i-1$th day. Therefore, we can use only two variables to maintain the state of the $i-1$th day, thereby optimizing the space complexity to $O(1)$. -```rust -impl Solution { - pub fn max_profit(prices: Vec) -> i32 { - let mut res = 0; - for i in 1..prices.len() { - res += (0).max(prices[i] - prices[i - 1]); +The time complexity is $O(n)$, where $n$ is the length of the `prices` array. The space complexity is $O(1)$. + + + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + n = len(prices) + f = [-prices[0], 0] + for i in range(1, n): + g = [0] * 2 + g[0] = max(f[0], f[1] - prices[i]) + g[1] = max(f[1], f[0] + prices[i]) + f = g + return f[1] +``` + +```java +class Solution { + public int maxProfit(int[] prices) { + int n = prices.length; + int[] f = new int[] {-prices[0], 0}; + for (int i = 1; i < n; ++i) { + int[] g = new int[2]; + g[0] = Math.max(f[0], f[1] - prices[i]); + g[1] = Math.max(f[1], f[0] + prices[i]); + f = g; } - res + return f[1]; } } ``` -### **...** - +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int n = prices.size(); + int f[2] = {-prices[0], 0}; + for (int i = 1; i < n; ++i) { + int g[2]; + g[0] = max(f[0], f[1] - prices[i]); + g[1] = max(f[1], f[0] + prices[i]); + f[0] = g[0], f[1] = g[1]; + } + return f[1]; + } +}; ``` +```go +func maxProfit(prices []int) int { + n := len(prices) + f := [2]int{-prices[0], 0} + for i := 1; i < n; i++ { + g := [2]int{} + g[0] = max(f[0], f[1]-prices[i]) + g[1] = max(f[1], f[0]+prices[i]) + f = g + } + return f[1] +} ``` + + diff --git a/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/README.md b/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/README.md index e67997b3b8e7f..d747b971efc1b 100644 --- a/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/README.md +++ b/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义以下几个变量,其中: @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def maxProfit(self, prices: List[int]) -> int: @@ -93,10 +87,6 @@ class Solution: return f4 ``` -### **Java** - - - ```java class Solution { public int maxProfit(int[] prices) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,7 +119,31 @@ public: }; ``` -### **Rust** +```go +func maxProfit(prices []int) int { + f1, f2, f3, f4 := -prices[0], 0, -prices[0], 0 + for i := 1; i < len(prices); i++ { + f1 = max(f1, -prices[i]) + f2 = max(f2, f1+prices[i]) + f3 = max(f3, f2-prices[i]) + f4 = max(f4, f3+prices[i]) + } + return f4 +} +``` + +```ts +function maxProfit(prices: number[]): number { + let [f1, f2, f3, f4] = [-prices[0], 0, -prices[0], 0]; + for (let i = 1; i < prices.length; ++i) { + f1 = Math.max(f1, -prices[i]); + f2 = Math.max(f2, f1 + prices[i]); + f3 = Math.max(f3, f2 - prices[i]); + f4 = Math.max(f4, f3 + prices[i]); + } + return f4; +} +``` ```rust impl Solution { @@ -155,23 +167,6 @@ impl Solution { } ``` -### **Go** - -```go -func maxProfit(prices []int) int { - f1, f2, f3, f4 := -prices[0], 0, -prices[0], 0 - for i := 1; i < len(prices); i++ { - f1 = max(f1, -prices[i]) - f2 = max(f2, f1+prices[i]) - f3 = max(f3, f2-prices[i]) - f4 = max(f4, f3+prices[i]) - } - return f4 -} -``` - -### **C#** - ```cs public class Solution { public int MaxProfit(int[] prices) { @@ -187,25 +182,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function maxProfit(prices: number[]): number { - let [f1, f2, f3, f4] = [-prices[0], 0, -prices[0], 0]; - for (let i = 1; i < prices.length; ++i) { - f1 = Math.max(f1, -prices[i]); - f2 = Math.max(f2, f1 + prices[i]); - f3 = Math.max(f3, f2 - prices[i]); - f4 = Math.max(f4, f3 + prices[i]); - } - return f4; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/README_EN.md b/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/README_EN.md index fa00c5242d893..678fc146bc812 100644 --- a/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/README_EN.md +++ b/solution/0100-0199/0123.Best Time to Buy and Sell Stock III/README_EN.md @@ -46,7 +46,7 @@ Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define the following variables: @@ -63,11 +63,10 @@ The time complexity is $O(n)$, where $n$ is the length of the `prices` array. Th -### **Python3** - ```python class Solution: def maxProfit(self, prices: List[int]) -> int: + # 第一次买入,第一次卖出,第二次买入,第二次卖出 f1, f2, f3, f4 = -prices[0], 0, -prices[0], 0 for price in prices[1:]: f1 = max(f1, -price) @@ -77,11 +76,10 @@ class Solution: return f4 ``` -### **Java** - ```java class Solution { public int maxProfit(int[] prices) { + // 第一次买入,第一次卖出,第二次买入,第二次卖出 int f1 = -prices[0], f2 = 0, f3 = -prices[0], f4 = 0; for (int i = 1; i < prices.length; ++i) { f1 = Math.max(f1, -prices[i]); @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,7 +108,31 @@ public: }; ``` -### **Rust** +```go +func maxProfit(prices []int) int { + f1, f2, f3, f4 := -prices[0], 0, -prices[0], 0 + for i := 1; i < len(prices); i++ { + f1 = max(f1, -prices[i]) + f2 = max(f2, f1+prices[i]) + f3 = max(f3, f2-prices[i]) + f4 = max(f4, f3+prices[i]) + } + return f4 +} +``` + +```ts +function maxProfit(prices: number[]): number { + let [f1, f2, f3, f4] = [-prices[0], 0, -prices[0], 0]; + for (let i = 1; i < prices.length; ++i) { + f1 = Math.max(f1, -prices[i]); + f2 = Math.max(f2, f1 + prices[i]); + f3 = Math.max(f3, f2 - prices[i]); + f4 = Math.max(f4, f3 + prices[i]); + } + return f4; +} +``` ```rust impl Solution { @@ -136,23 +156,6 @@ impl Solution { } ``` -### **Go** - -```go -func maxProfit(prices []int) int { - f1, f2, f3, f4 := -prices[0], 0, -prices[0], 0 - for i := 1; i < len(prices); i++ { - f1 = max(f1, -prices[i]) - f2 = max(f2, f1+prices[i]) - f3 = max(f3, f2-prices[i]) - f4 = max(f4, f3+prices[i]) - } - return f4 -} -``` - -### **C#** - ```cs public class Solution { public int MaxProfit(int[] prices) { @@ -168,25 +171,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function maxProfit(prices: number[]): number { - let [f1, f2, f3, f4] = [-prices[0], 0, -prices[0], 0]; - for (let i = 1; i < prices.length; ++i) { - f1 = Math.max(f1, -prices[i]); - f2 = Math.max(f2, f1 + prices[i]); - f3 = Math.max(f3, f2 - prices[i]); - f4 = Math.max(f4, f3 + prices[i]); - } - return f4; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0124.Binary Tree Maximum Path Sum/README.md b/solution/0100-0199/0124.Binary Tree Maximum Path Sum/README.md index 6db9f3df22e1a..cb69ac0707025 100644 --- a/solution/0100-0199/0124.Binary Tree Maximum Path Sum/README.md +++ b/solution/0100-0199/0124.Binary Tree Maximum Path Sum/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们思考二叉树递归问题的经典套路: @@ -66,10 +64,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -166,8 +154,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -194,8 +180,6 @@ func maxPathSum(root *TreeNode) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -227,7 +211,46 @@ function maxPathSum(root: TreeNode | null): number { } ``` -### **JavaScript** +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(root: &Option>>, res: &mut i32) -> i32 { + if root.is_none() { + return 0; + } + let node = root.as_ref().unwrap().borrow(); + let left = (0).max(Self::dfs(&node.left, res)); + let right = (0).max(Self::dfs(&node.right, res)); + *res = (node.val + left + right).max(*res); + node.val + left.max(right) + } + + pub fn max_path_sum(root: Option>>) -> i32 { + let mut res = -1000; + Self::dfs(&root, &mut res); + res + } +} +``` ```js /** @@ -258,8 +281,6 @@ var maxPathSum = function (root) { }; ``` -### **C#** - ```cs /** * Definition for a binary tree node. @@ -294,53 +315,6 @@ public class Solution { } ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(root: &Option>>, res: &mut i32) -> i32 { - if root.is_none() { - return 0; - } - let node = root.as_ref().unwrap().borrow(); - let left = (0).max(Self::dfs(&node.left, res)); - let right = (0).max(Self::dfs(&node.right, res)); - *res = (node.val + left + right).max(*res); - node.val + left.max(right) - } - - pub fn max_path_sum(root: Option>>) -> i32 { - let mut res = -1000; - Self::dfs(&root, &mut res); - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0124.Binary Tree Maximum Path Sum/README_EN.md b/solution/0100-0199/0124.Binary Tree Maximum Path Sum/README_EN.md index 87786e90e5997..86a9567a92866 100644 --- a/solution/0100-0199/0124.Binary Tree Maximum Path Sum/README_EN.md +++ b/solution/0100-0199/0124.Binary Tree Maximum Path Sum/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion When thinking about the classic routine of recursion problems in binary trees, we consider: @@ -61,8 +61,6 @@ 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: @@ -86,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -124,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -157,8 +151,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -185,8 +177,6 @@ func maxPathSum(root *TreeNode) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -218,7 +208,46 @@ function maxPathSum(root: TreeNode | null): number { } ``` -### **JavaScript** +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(root: &Option>>, res: &mut i32) -> i32 { + if root.is_none() { + return 0; + } + let node = root.as_ref().unwrap().borrow(); + let left = (0).max(Self::dfs(&node.left, res)); + let right = (0).max(Self::dfs(&node.right, res)); + *res = (node.val + left + right).max(*res); + node.val + left.max(right) + } + + pub fn max_path_sum(root: Option>>) -> i32 { + let mut res = -1000; + Self::dfs(&root, &mut res); + res + } +} +``` ```js /** @@ -249,8 +278,6 @@ var maxPathSum = function (root) { }; ``` -### **C#** - ```cs /** * Definition for a binary tree node. @@ -285,53 +312,6 @@ public class Solution { } ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(root: &Option>>, res: &mut i32) -> i32 { - if root.is_none() { - return 0; - } - let node = root.as_ref().unwrap().borrow(); - let left = (0).max(Self::dfs(&node.left, res)); - let right = (0).max(Self::dfs(&node.right, res)); - *res = (node.val + left + right).max(*res); - node.val + left.max(right) - } - - pub fn max_path_sum(root: Option>>) -> i32 { - let mut res = -1000; - Self::dfs(&root, &mut res); - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0125.Valid Palindrome/README.md b/solution/0100-0199/0125.Valid Palindrome/README.md index dbba3199b4df8..2eea316e4e843 100644 --- a/solution/0100-0199/0125.Valid Palindrome/README.md +++ b/solution/0100-0199/0125.Valid Palindrome/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们用双指针 $i$ 和 $j$ 分别指向字符串 $s$ 的两端,接下来循环以下过程,直至 $i \geq j$: @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def isPalindrome(self, s: str) -> bool: @@ -87,10 +81,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean isPalindrome(String s) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func isPalindrome(s string) bool { i, j := 0, len(s)-1 @@ -167,54 +153,6 @@ func tolower(ch byte) byte { } ``` -### **C#** - -```cs -public class Solution { - public bool IsPalindrome(string s) { - int i = 0, j = s.Length - 1; - while (i < j) { - if (!char.IsLetterOrDigit(s[i])) { - ++i; - } else if (!char.IsLetterOrDigit(s[j])) { - --j; - } else if (char.ToLower(s[i++]) != char.ToLower(s[j--])) { - return false; - } - } - return true; - } -} -``` - -### **JavaScript** - -```js -/** - * @param {string} s - * @return {boolean} - */ -var isPalindrome = function (s) { - let i = 0; - let j = s.length - 1; - while (i < j) { - if (!/[a-zA-Z0-9]/.test(s[i])) { - ++i; - } else if (!/[a-zA-Z0-9]/.test(s[j])) { - --j; - } else if (s[i].toLowerCase() !== s[j].toLowerCase()) { - return false; - } else { - ++i; - --j; - } - } - return true; -}; -``` - -### **TypeScript** - ```ts function isPalindrome(s: string): boolean { let i = 0; @@ -235,8 +173,6 @@ function isPalindrome(s: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_palindrome(s: String) -> bool { @@ -264,7 +200,47 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function (s) { + let i = 0; + let j = s.length - 1; + while (i < j) { + if (!/[a-zA-Z0-9]/.test(s[i])) { + ++i; + } else if (!/[a-zA-Z0-9]/.test(s[j])) { + --j; + } else if (s[i].toLowerCase() !== s[j].toLowerCase()) { + return false; + } else { + ++i; + --j; + } + } + return true; +}; +``` + +```cs +public class Solution { + public bool IsPalindrome(string s) { + int i = 0, j = s.Length - 1; + while (i < j) { + if (!char.IsLetterOrDigit(s[i])) { + ++i; + } else if (!char.IsLetterOrDigit(s[j])) { + --j; + } else if (char.ToLower(s[i++]) != char.ToLower(s[j--])) { + return false; + } + } + return true; + } +} +``` ```php class Solution { @@ -290,10 +266,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0125.Valid Palindrome/README_EN.md b/solution/0100-0199/0125.Valid Palindrome/README_EN.md index e08c0aa8a2bf8..76975a8226637 100644 --- a/solution/0100-0199/0125.Valid Palindrome/README_EN.md +++ b/solution/0100-0199/0125.Valid Palindrome/README_EN.md @@ -44,7 +44,7 @@ Since an empty string reads the same forward and backward, it is a palindrome. ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We use two pointers $i$ and $j$ to point to the two ends of the string $s$, and then loop through the following process until $i \geq j$: @@ -59,8 +59,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. The sp -### **Python3** - ```python class Solution: def isPalindrome(self, s: str) -> bool: @@ -77,8 +75,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean isPalindrome(String s) { @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +118,6 @@ public: }; ``` -### **Go** - ```go func isPalindrome(s string) bool { i, j := 0, len(s)-1 @@ -155,54 +147,6 @@ func tolower(ch byte) byte { } ``` -### **C#** - -```cs -public class Solution { - public bool IsPalindrome(string s) { - int i = 0, j = s.Length - 1; - while (i < j) { - if (!char.IsLetterOrDigit(s[i])) { - ++i; - } else if (!char.IsLetterOrDigit(s[j])) { - --j; - } else if (char.ToLower(s[i++]) != char.ToLower(s[j--])) { - return false; - } - } - return true; - } -} -``` - -### **JavaScript** - -```js -/** - * @param {string} s - * @return {boolean} - */ -var isPalindrome = function (s) { - let i = 0; - let j = s.length - 1; - while (i < j) { - if (!/[a-zA-Z0-9]/.test(s[i])) { - ++i; - } else if (!/[a-zA-Z0-9]/.test(s[j])) { - --j; - } else if (s[i].toLowerCase() !== s[j].toLowerCase()) { - return false; - } else { - ++i; - --j; - } - } - return true; -}; -``` - -### **TypeScript** - ```ts function isPalindrome(s: string): boolean { let i = 0; @@ -223,8 +167,6 @@ function isPalindrome(s: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_palindrome(s: String) -> bool { @@ -252,7 +194,47 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function (s) { + let i = 0; + let j = s.length - 1; + while (i < j) { + if (!/[a-zA-Z0-9]/.test(s[i])) { + ++i; + } else if (!/[a-zA-Z0-9]/.test(s[j])) { + --j; + } else if (s[i].toLowerCase() !== s[j].toLowerCase()) { + return false; + } else { + ++i; + --j; + } + } + return true; +}; +``` + +```cs +public class Solution { + public bool IsPalindrome(string s) { + int i = 0, j = s.Length - 1; + while (i < j) { + if (!char.IsLetterOrDigit(s[i])) { + ++i; + } else if (!char.IsLetterOrDigit(s[j])) { + --j; + } else if (char.ToLower(s[i++]) != char.ToLower(s[j--])) { + return false; + } + } + return true; + } +} +``` ```php class Solution { @@ -278,10 +260,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0126.Word Ladder II/README.md b/solution/0100-0199/0126.Word Ladder II/README.md index 9449d531f8a05..0f1b9b374a16b 100644 --- a/solution/0100-0199/0126.Word Ladder II/README.md +++ b/solution/0100-0199/0126.Word Ladder II/README.md @@ -56,16 +56,10 @@ ## 解法 - - -DFS。 +### 方法一 -### **Python3** - - - ```python class Solution: def findLadders( @@ -117,10 +111,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List> ans; @@ -190,8 +180,6 @@ class Solution { } ``` -### **Go** - ```go func findLadders(beginWord string, endWord string, wordList []string) [][]string { var ans [][]string @@ -264,10 +252,6 @@ func findLadders(beginWord string, endWord string, wordList []string) [][]string } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0126.Word Ladder II/README_EN.md b/solution/0100-0199/0126.Word Ladder II/README_EN.md index 59d1f71ec6f0b..d99ddb375a9f1 100644 --- a/solution/0100-0199/0126.Word Ladder II/README_EN.md +++ b/solution/0100-0199/0126.Word Ladder II/README_EN.md @@ -49,12 +49,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python class Solution: def findLadders( @@ -106,8 +104,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List> ans; @@ -177,8 +173,6 @@ class Solution { } ``` -### **Go** - ```go func findLadders(beginWord string, endWord string, wordList []string) [][]string { var ans [][]string @@ -251,10 +245,6 @@ func findLadders(beginWord string, endWord string, wordList []string) [][]string } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0127.Word Ladder/README.md b/solution/0100-0199/0127.Word Ladder/README.md index 431210dc1ff33..91072d1c476c7 100644 --- a/solution/0100-0199/0127.Word Ladder/README.md +++ b/solution/0100-0199/0127.Word Ladder/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS BFS 最小步数模型。本题可以用朴素 BFS,也可以用双向 BFS 优化搜索空间,从而提升效率。 @@ -88,12 +86,6 @@ def extend(m1, m2, q): -### **Python3** - - - -朴素 BFS: - ```python class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: @@ -120,48 +112,6 @@ class Solution: return 0 ``` -双向 BFS: - -```python -class Solution: - def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: - def extend(m1, m2, q): - for _ in range(len(q)): - s = q.popleft() - step = m1[s] - s = list(s) - for i in range(len(s)): - ch = s[i] - for j in range(26): - s[i] = chr(ord('a') + j) - t = ''.join(s) - if t in m1 or t not in words: - continue - if t in m2: - return step + 1 + m2[t] - m1[t] = step + 1 - q.append(t) - s[i] = ch - return -1 - - words = set(wordList) - if endWord not in words: - return 0 - q1, q2 = deque([beginWord]), deque([endWord]) - m1, m2 = {beginWord: 0}, {endWord: 0} - while q1 and q2: - t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) - if t != -1: - return t + 1 - return 0 -``` - -### **Java** - - - -朴素 BFS: - ```java class Solution { public int ladderLength(String beginWord, String endWord, List wordList) { @@ -197,7 +147,182 @@ class Solution { } ``` -双向 BFS: +```cpp +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector& wordList) { + unordered_set words(wordList.begin(), wordList.end()); + queue q{{beginWord}}; + int ans = 1; + while (!q.empty()) { + ++ans; + for (int i = q.size(); i > 0; --i) { + string s = q.front(); + q.pop(); + for (int j = 0; j < s.size(); ++j) { + char ch = s[j]; + for (char k = 'a'; k <= 'z'; ++k) { + s[j] = k; + if (!words.count(s)) continue; + if (s == endWord) return ans; + q.push(s); + words.erase(s); + } + s[j] = ch; + } + } + } + return 0; + } +}; +``` + +```go +func ladderLength(beginWord string, endWord string, wordList []string) int { + words := make(map[string]bool) + for _, word := range wordList { + words[word] = true + } + q := []string{beginWord} + ans := 1 + for len(q) > 0 { + ans++ + for i := len(q); i > 0; i-- { + s := q[0] + q = q[1:] + chars := []byte(s) + for j := 0; j < len(chars); j++ { + ch := chars[j] + for k := 'a'; k <= 'z'; k++ { + chars[j] = byte(k) + t := string(chars) + if !words[t] { + continue + } + if t == endWord { + return ans + } + q = append(q, t) + words[t] = false + } + chars[j] = ch + } + } + } + return 0 +} +``` + +```cs +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public int LadderLength(string beginWord, string endWord, IList wordList) { + var words = Enumerable.Repeat(beginWord, 1).Concat(wordList).Select((word, i) => new { Word = word, Index = i }).ToList(); + var endWordIndex = words.Find(w => w.Word == endWord)?.Index; + if (endWordIndex == null) { + return 0; + } + + var paths = new List[words.Count]; + for (var i = 0; i < paths.Length; ++i) + { + paths[i] = new List(); + } + for (var i = 0; i < beginWord.Length; ++i) + { + var hashMap = new Hashtable(); + foreach (var item in words) + { + var newWord = string.Format("{0}_{1}", item.Word.Substring(0, i), item.Word.Substring(i + 1)); + List similars; + if (!hashMap.ContainsKey(newWord)) + { + similars = new List(); + hashMap.Add(newWord, similars); + } + else + { + similars = (List)hashMap[newWord]; + } + foreach (var similar in similars) + { + paths[similar].Add(item.Index); + paths[item.Index].Add(similar); + } + similars.Add(item.Index); + } + } + + var left = words.Count - 1; + var lastRound = new List { 0 }; + var visited = new bool[words.Count]; + visited[0] = true; + for (var result = 2; left > 0; ++result) + { + var thisRound = new List(); + foreach (var index in lastRound) + { + foreach (var next in paths[index]) + { + if (!visited[next]) + { + visited[next] = true; + if (next == endWordIndex) return result; + thisRound.Add(next); + } + } + } + if (thisRound.Count == 0) break; + lastRound = thisRound; + } + + return 0; + } +} +``` + + + +### 方法二 + + + +```python +class Solution: + def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: + def extend(m1, m2, q): + for _ in range(len(q)): + s = q.popleft() + step = m1[s] + s = list(s) + for i in range(len(s)): + ch = s[i] + for j in range(26): + s[i] = chr(ord('a') + j) + t = ''.join(s) + if t in m1 or t not in words: + continue + if t in m2: + return step + 1 + m2[t] + m1[t] = step + 1 + q.append(t) + s[i] = ch + return -1 + + words = set(wordList) + if endWord not in words: + return 0 + q1, q2 = deque([beginWord]), deque([endWord]) + m1, m2 = {beginWord: 0}, {endWord: 0} + while q1 and q2: + t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) + if t != -1: + return t + 1 + return 0 +``` ```java class Solution { @@ -252,42 +377,6 @@ class Solution { } ``` -### **C++** - -朴素 BFS: - -```cpp -class Solution { -public: - int ladderLength(string beginWord, string endWord, vector& wordList) { - unordered_set words(wordList.begin(), wordList.end()); - queue q{{beginWord}}; - int ans = 1; - while (!q.empty()) { - ++ans; - for (int i = q.size(); i > 0; --i) { - string s = q.front(); - q.pop(); - for (int j = 0; j < s.size(); ++j) { - char ch = s[j]; - for (char k = 'a'; k <= 'z'; ++k) { - s[j] = k; - if (!words.count(s)) continue; - if (s == endWord) return ans; - q.push(s); - words.erase(s); - } - s[j] = ch; - } - } - } - return 0; - } -}; -``` - -双向 BFS: - ```cpp class Solution { public: @@ -329,48 +418,6 @@ public: }; ``` -### **Go** - -朴素 BFS: - -```go -func ladderLength(beginWord string, endWord string, wordList []string) int { - words := make(map[string]bool) - for _, word := range wordList { - words[word] = true - } - q := []string{beginWord} - ans := 1 - for len(q) > 0 { - ans++ - for i := len(q); i > 0; i-- { - s := q[0] - q = q[1:] - chars := []byte(s) - for j := 0; j < len(chars); j++ { - ch := chars[j] - for k := 'a'; k <= 'z'; k++ { - chars[j] = byte(k) - t := string(chars) - if !words[t] { - continue - } - if t == endWord { - return ans - } - q = append(q, t) - words[t] = false - } - chars[j] = ch - } - } - } - return 0 -} -``` - -双向 BFS: - ```go func ladderLength(beginWord string, endWord string, wordList []string) int { words := make(map[string]bool) @@ -425,10 +472,6 @@ func ladderLength(beginWord string, endWord string, wordList []string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0127.Word Ladder/README_EN.md b/solution/0100-0199/0127.Word Ladder/README_EN.md index 972772e6aef5c..241f113be1397 100644 --- a/solution/0100-0199/0127.Word Ladder/README_EN.md +++ b/solution/0100-0199/0127.Word Ladder/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: BFS** +### Solution 1: BFS BFS minimum step model. This problem can be solved with naive BFS, or it can be optimized with bidirectional BFS to reduce the search space and improve efficiency. @@ -84,8 +84,6 @@ def extend(m1, m2, q): -### **Python3** - ```python class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: @@ -112,42 +110,6 @@ class Solution: return 0 ``` -```python -class Solution: - def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: - def extend(m1, m2, q): - for _ in range(len(q)): - s = q.popleft() - step = m1[s] - s = list(s) - for i in range(len(s)): - ch = s[i] - for j in range(26): - s[i] = chr(ord('a') + j) - t = ''.join(s) - if t in m1 or t not in words: - continue - if t in m2: - return step + 1 + m2[t] - m1[t] = step + 1 - q.append(t) - s[i] = ch - return -1 - - words = set(wordList) - if endWord not in words: - return 0 - q1, q2 = deque([beginWord]), deque([endWord]) - m1, m2 = {beginWord: 0}, {endWord: 0} - while q1 and q2: - t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) - if t != -1: - return t + 1 - return 0 -``` - -### **Java** - ```java class Solution { public int ladderLength(String beginWord, String endWord, List wordList) { @@ -183,6 +145,183 @@ class Solution { } ``` +```cpp +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector& wordList) { + unordered_set words(wordList.begin(), wordList.end()); + queue q{{beginWord}}; + int ans = 1; + while (!q.empty()) { + ++ans; + for (int i = q.size(); i > 0; --i) { + string s = q.front(); + q.pop(); + for (int j = 0; j < s.size(); ++j) { + char ch = s[j]; + for (char k = 'a'; k <= 'z'; ++k) { + s[j] = k; + if (!words.count(s)) continue; + if (s == endWord) return ans; + q.push(s); + words.erase(s); + } + s[j] = ch; + } + } + } + return 0; + } +}; +``` + +```go +func ladderLength(beginWord string, endWord string, wordList []string) int { + words := make(map[string]bool) + for _, word := range wordList { + words[word] = true + } + q := []string{beginWord} + ans := 1 + for len(q) > 0 { + ans++ + for i := len(q); i > 0; i-- { + s := q[0] + q = q[1:] + chars := []byte(s) + for j := 0; j < len(chars); j++ { + ch := chars[j] + for k := 'a'; k <= 'z'; k++ { + chars[j] = byte(k) + t := string(chars) + if !words[t] { + continue + } + if t == endWord { + return ans + } + q = append(q, t) + words[t] = false + } + chars[j] = ch + } + } + } + return 0 +} +``` + +```cs +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public int LadderLength(string beginWord, string endWord, IList wordList) { + var words = Enumerable.Repeat(beginWord, 1).Concat(wordList).Select((word, i) => new { Word = word, Index = i }).ToList(); + var endWordIndex = words.Find(w => w.Word == endWord)?.Index; + if (endWordIndex == null) { + return 0; + } + + var paths = new List[words.Count]; + for (var i = 0; i < paths.Length; ++i) + { + paths[i] = new List(); + } + for (var i = 0; i < beginWord.Length; ++i) + { + var hashMap = new Hashtable(); + foreach (var item in words) + { + var newWord = string.Format("{0}_{1}", item.Word.Substring(0, i), item.Word.Substring(i + 1)); + List similars; + if (!hashMap.ContainsKey(newWord)) + { + similars = new List(); + hashMap.Add(newWord, similars); + } + else + { + similars = (List)hashMap[newWord]; + } + foreach (var similar in similars) + { + paths[similar].Add(item.Index); + paths[item.Index].Add(similar); + } + similars.Add(item.Index); + } + } + + var left = words.Count - 1; + var lastRound = new List { 0 }; + var visited = new bool[words.Count]; + visited[0] = true; + for (var result = 2; left > 0; ++result) + { + var thisRound = new List(); + foreach (var index in lastRound) + { + foreach (var next in paths[index]) + { + if (!visited[next]) + { + visited[next] = true; + if (next == endWordIndex) return result; + thisRound.Add(next); + } + } + } + if (thisRound.Count == 0) break; + lastRound = thisRound; + } + + return 0; + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: + def extend(m1, m2, q): + for _ in range(len(q)): + s = q.popleft() + step = m1[s] + s = list(s) + for i in range(len(s)): + ch = s[i] + for j in range(26): + s[i] = chr(ord('a') + j) + t = ''.join(s) + if t in m1 or t not in words: + continue + if t in m2: + return step + 1 + m2[t] + m1[t] = step + 1 + q.append(t) + s[i] = ch + return -1 + + words = set(wordList) + if endWord not in words: + return 0 + q1, q2 = deque([beginWord]), deque([endWord]) + m1, m2 = {beginWord: 0}, {endWord: 0} + while q1 and q2: + t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) + if t != -1: + return t + 1 + return 0 +``` + ```java class Solution { private Set words; @@ -236,38 +375,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int ladderLength(string beginWord, string endWord, vector& wordList) { - unordered_set words(wordList.begin(), wordList.end()); - queue q{{beginWord}}; - int ans = 1; - while (!q.empty()) { - ++ans; - for (int i = q.size(); i > 0; --i) { - string s = q.front(); - q.pop(); - for (int j = 0; j < s.size(); ++j) { - char ch = s[j]; - for (char k = 'a'; k <= 'z'; ++k) { - s[j] = k; - if (!words.count(s)) continue; - if (s == endWord) return ans; - q.push(s); - words.erase(s); - } - s[j] = ch; - } - } - } - return 0; - } -}; -``` - ```cpp class Solution { public: @@ -309,44 +416,6 @@ public: }; ``` -### **Go** - -```go -func ladderLength(beginWord string, endWord string, wordList []string) int { - words := make(map[string]bool) - for _, word := range wordList { - words[word] = true - } - q := []string{beginWord} - ans := 1 - for len(q) > 0 { - ans++ - for i := len(q); i > 0; i-- { - s := q[0] - q = q[1:] - chars := []byte(s) - for j := 0; j < len(chars); j++ { - ch := chars[j] - for k := 'a'; k <= 'z'; k++ { - chars[j] = byte(k) - t := string(chars) - if !words[t] { - continue - } - if t == endWord { - return ans - } - q = append(q, t) - words[t] = false - } - chars[j] = ch - } - } - } - return 0 -} -``` - ```go func ladderLength(beginWord string, endWord string, wordList []string) int { words := make(map[string]bool) @@ -401,10 +470,6 @@ func ladderLength(beginWord string, endWord string, wordList []string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/README.md b/solution/0100-0199/0128.Longest Consecutive Sequence/README.md index d57edb2367a6a..5b6f9cd80fa59 100644 --- a/solution/0100-0199/0128.Longest Consecutive Sequence/README.md +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们先将数组排序,然后用一个变量 $t$ 记录当前连续序列的长度,用一个变量 $ans$ 记录最长连续序列的长度。 @@ -53,18 +51,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组的长度。 -**方法二:哈希表** - -我们用哈希表存储数组中的所有元素,然后遍历数组中的每个元素 $x$,如果当前元素的前驱 $x-1$ 不在哈希表中,那么我们以当前元素为起点,不断尝试匹配 $x+1, x+2, x+3, \dots$,直到匹配不到为止,此时的匹配长度即为以 $x$ 为起点的最长连续序列长度,我们更新答案即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组的长度。 - -### **Python3** - - - ```python class Solution: def longestConsecutive(self, nums: List[int]) -> int: @@ -84,24 +72,6 @@ class Solution: return ans ``` -```python -class Solution: - def longestConsecutive(self, nums: List[int]) -> int: - s = set(nums) - ans = 0 - for x in nums: - if x - 1 not in s: - y = x + 1 - while y in s: - y += 1 - ans = max(ans, y - x) - return ans -``` - -### **Java** - - - ```java class Solution { public int longestConsecutive(int[] nums) { @@ -126,30 +96,6 @@ class Solution { } ``` -```java -class Solution { - public int longestConsecutive(int[] nums) { - Set s = new HashSet<>(); - for (int x : nums) { - s.add(x); - } - int ans = 0; - for (int x : nums) { - if (!s.contains(x - 1)) { - int y = x + 1; - while (s.contains(y)) { - ++y; - } - ans = Math.max(ans, y - x); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -175,28 +121,52 @@ public: }; ``` -```cpp -class Solution { -public: - int longestConsecutive(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - int ans = 0; - for (int x : nums) { - if (!s.count(x - 1)) { - int y = x + 1; - while (s.count(y)) { - y++; - } - ans = max(ans, y - x); - } +```go +func longestConsecutive(nums []int) int { + n := len(nums) + if n < 2 { + return n + } + sort.Ints(nums) + ans, t := 1, 1 + for i, x := range nums[1:] { + if x == nums[i] { + continue + } + if x == nums[i]+1 { + t++ + ans = max(ans, t) + } else { + t = 1 + } + } + return ans +} +``` + +```ts +function longestConsecutive(nums: number[]): number { + const n = nums.length; + if (n < 2) { + return n; + } + let ans = 1; + let t = 1; + nums.sort((a, b) => a - b); + for (let i = 1; i < n; ++i) { + if (nums[i] === nums[i - 1]) { + continue; + } + if (nums[i] === nums[i - 1] + 1) { + ans = Math.max(ans, ++t); + } else { + t = 1; } - return ans; } -}; + return ans; +} ``` -### **Rust** - ```rust use std::collections::HashSet; @@ -228,52 +198,6 @@ impl Solution { } ``` -### **Go** - -```go -func longestConsecutive(nums []int) int { - n := len(nums) - if n < 2 { - return n - } - sort.Ints(nums) - ans, t := 1, 1 - for i, x := range nums[1:] { - if x == nums[i] { - continue - } - if x == nums[i]+1 { - t++ - ans = max(ans, t) - } else { - t = 1 - } - } - return ans -} -``` - -```go -func longestConsecutive(nums []int) (ans int) { - s := map[int]bool{} - for _, x := range nums { - s[x] = true - } - for _, x := range nums { - if !s[x-1] { - y := x + 1 - for s[y] { - y++ - } - ans = max(ans, y-x) - } - } - return -} -``` - -### **JavaScript** - ```js /** * @param {number[]} nums @@ -301,49 +225,88 @@ var longestConsecutive = function (nums) { }; ``` -```js -/** - * @param {number[]} nums - * @return {number} - */ -var longestConsecutive = function (nums) { - const s = new Set(nums); - let ans = 0; - for (const x of nums) { - if (!s.has(x - 1)) { - let y = x + 1; - while (s.has(y)) { - y++; + + +### 方法二:哈希表 + +我们用哈希表存储数组中的所有元素,然后遍历数组中的每个元素 $x$,如果当前元素的前驱 $x-1$ 不在哈希表中,那么我们以当前元素为起点,不断尝试匹配 $x+1, x+2, x+3, \dots$,直到匹配不到为止,此时的匹配长度即为以 $x$ 为起点的最长连续序列长度,我们更新答案即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组的长度。 + + + +```python +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + s = set(nums) + ans = 0 + for x in nums: + if x - 1 not in s: + y = x + 1 + while y in s: + y += 1 + ans = max(ans, y - x) + return ans +``` + +```java +class Solution { + public int longestConsecutive(int[] nums) { + Set s = new HashSet<>(); + for (int x : nums) { + s.add(x); + } + int ans = 0; + for (int x : nums) { + if (!s.contains(x - 1)) { + int y = x + 1; + while (s.contains(y)) { + ++y; + } + ans = Math.max(ans, y - x); } - ans = Math.max(ans, y - x); } + return ans; } - return ans; -}; +} ``` -### **TypeScript** - -```ts -function longestConsecutive(nums: number[]): number { - const n = nums.length; - if (n < 2) { - return n; - } - let ans = 1; - let t = 1; - nums.sort((a, b) => a - b); - for (let i = 1; i < n; ++i) { - if (nums[i] === nums[i - 1]) { - continue; - } - if (nums[i] === nums[i - 1] + 1) { - ans = Math.max(ans, ++t); - } else { - t = 1; +```cpp +class Solution { +public: + int longestConsecutive(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + int ans = 0; + for (int x : nums) { + if (!s.count(x - 1)) { + int y = x + 1; + while (s.count(y)) { + y++; + } + ans = max(ans, y - x); + } } + return ans; } - return ans; +}; +``` + +```go +func longestConsecutive(nums []int) (ans int) { + s := map[int]bool{} + for _, x := range nums { + s[x] = true + } + for _, x := range nums { + if !s[x-1] { + y := x + 1 + for s[y] { + y++ + } + ans = max(ans, y-x) + } + } + return } ``` @@ -364,10 +327,27 @@ function longestConsecutive(nums: number[]): number { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function (nums) { + const s = new Set(nums); + let ans = 0; + for (const x of nums) { + if (!s.has(x - 1)) { + let y = x + 1; + while (s.has(y)) { + y++; + } + ans = Math.max(ans, y - x); + } + } + return ans; +}; ``` + + diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/README_EN.md b/solution/0100-0199/0128.Longest Consecutive Sequence/README_EN.md index 1f25a47f7fef1..29717f9814029 100644 --- a/solution/0100-0199/0128.Longest Consecutive Sequence/README_EN.md +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting First, we sort the array, then use a variable $t$ to record the current length of the consecutive sequence, and a variable $ans$ to record the length of the longest consecutive sequence. @@ -48,16 +48,8 @@ Finally, we return the answer $ans$. The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array. -**Solution 2: Hash Table** - -We use a hash table to store all elements in the array, and then traverse each element $x$ in the array. If the predecessor $x-1$ of the current element is not in the hash table, then we start with the current element and continuously try to match $x+1, x+2, x+3, \dots$, until no match is found. The length of the match at this time is the longest consecutive sequence length starting with $x$, and we update the answer accordingly. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array. - -### **Python3** - ```python class Solution: def longestConsecutive(self, nums: List[int]) -> int: @@ -77,22 +69,6 @@ class Solution: return ans ``` -```python -class Solution: - def longestConsecutive(self, nums: List[int]) -> int: - s = set(nums) - ans = 0 - for x in nums: - if x - 1 not in s: - y = x + 1 - while y in s: - y += 1 - ans = max(ans, y - x) - return ans -``` - -### **Java** - ```java class Solution { public int longestConsecutive(int[] nums) { @@ -117,30 +93,6 @@ class Solution { } ``` -```java -class Solution { - public int longestConsecutive(int[] nums) { - Set s = new HashSet<>(); - for (int x : nums) { - s.add(x); - } - int ans = 0; - for (int x : nums) { - if (!s.contains(x - 1)) { - int y = x + 1; - while (s.contains(y)) { - ++y; - } - ans = Math.max(ans, y - x); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -166,28 +118,52 @@ public: }; ``` -```cpp -class Solution { -public: - int longestConsecutive(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - int ans = 0; - for (int x : nums) { - if (!s.count(x - 1)) { - int y = x + 1; - while (s.count(y)) { - y++; - } - ans = max(ans, y - x); - } +```go +func longestConsecutive(nums []int) int { + n := len(nums) + if n < 2 { + return n + } + sort.Ints(nums) + ans, t := 1, 1 + for i, x := range nums[1:] { + if x == nums[i] { + continue + } + if x == nums[i]+1 { + t++ + ans = max(ans, t) + } else { + t = 1 + } + } + return ans +} +``` + +```ts +function longestConsecutive(nums: number[]): number { + const n = nums.length; + if (n < 2) { + return n; + } + let ans = 1; + let t = 1; + nums.sort((a, b) => a - b); + for (let i = 1; i < n; ++i) { + if (nums[i] === nums[i - 1]) { + continue; + } + if (nums[i] === nums[i - 1] + 1) { + ans = Math.max(ans, ++t); + } else { + t = 1; } - return ans; } -}; + return ans; +} ``` -### **Rust** - ```rust use std::collections::HashSet; @@ -219,52 +195,6 @@ impl Solution { } ``` -### **Go** - -```go -func longestConsecutive(nums []int) int { - n := len(nums) - if n < 2 { - return n - } - sort.Ints(nums) - ans, t := 1, 1 - for i, x := range nums[1:] { - if x == nums[i] { - continue - } - if x == nums[i]+1 { - t++ - ans = max(ans, t) - } else { - t = 1 - } - } - return ans -} -``` - -```go -func longestConsecutive(nums []int) (ans int) { - s := map[int]bool{} - for _, x := range nums { - s[x] = true - } - for _, x := range nums { - if !s[x-1] { - y := x + 1 - for s[y] { - y++ - } - ans = max(ans, y-x) - } - } - return -} -``` - -### **JavaScript** - ```js /** * @param {number[]} nums @@ -292,49 +222,88 @@ var longestConsecutive = function (nums) { }; ``` -```js -/** - * @param {number[]} nums - * @return {number} - */ -var longestConsecutive = function (nums) { - const s = new Set(nums); - let ans = 0; - for (const x of nums) { - if (!s.has(x - 1)) { - let y = x + 1; - while (s.has(y)) { - y++; + + +### Solution 2: Hash Table + +We use a hash table to store all elements in the array, and then traverse each element $x$ in the array. If the predecessor $x-1$ of the current element is not in the hash table, then we start with the current element and continuously try to match $x+1, x+2, x+3, \dots$, until no match is found. The length of the match at this time is the longest consecutive sequence length starting with $x$, and we update the answer accordingly. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array. + + + +```python +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + s = set(nums) + ans = 0 + for x in nums: + if x - 1 not in s: + y = x + 1 + while y in s: + y += 1 + ans = max(ans, y - x) + return ans +``` + +```java +class Solution { + public int longestConsecutive(int[] nums) { + Set s = new HashSet<>(); + for (int x : nums) { + s.add(x); + } + int ans = 0; + for (int x : nums) { + if (!s.contains(x - 1)) { + int y = x + 1; + while (s.contains(y)) { + ++y; + } + ans = Math.max(ans, y - x); } - ans = Math.max(ans, y - x); } + return ans; } - return ans; -}; +} ``` -### **TypeScript** - -```ts -function longestConsecutive(nums: number[]): number { - const n = nums.length; - if (n < 2) { - return n; - } - let ans = 1; - let t = 1; - nums.sort((a, b) => a - b); - for (let i = 1; i < n; ++i) { - if (nums[i] === nums[i - 1]) { - continue; - } - if (nums[i] === nums[i - 1] + 1) { - ans = Math.max(ans, ++t); - } else { - t = 1; +```cpp +class Solution { +public: + int longestConsecutive(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + int ans = 0; + for (int x : nums) { + if (!s.count(x - 1)) { + int y = x + 1; + while (s.count(y)) { + y++; + } + ans = max(ans, y - x); + } } + return ans; } - return ans; +}; +``` + +```go +func longestConsecutive(nums []int) (ans int) { + s := map[int]bool{} + for _, x := range nums { + s[x] = true + } + for _, x := range nums { + if !s[x-1] { + y := x + 1 + for s[y] { + y++ + } + ans = max(ans, y-x) + } + } + return } ``` @@ -355,10 +324,27 @@ function longestConsecutive(nums: number[]): number { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function (nums) { + const s = new Set(nums); + let ans = 0; + for (const x of nums) { + if (!s.has(x - 1)) { + let y = x + 1; + while (s.has(y)) { + y++; + } + ans = Math.max(ans, y - x); + } + } + return ans; +}; ``` + + diff --git a/solution/0100-0199/0129.Sum Root to Leaf Numbers/README.md b/solution/0100-0199/0129.Sum Root to Leaf Numbers/README.md index 28fa46c145945..fac4544e161d0 100644 --- a/solution/0100-0199/0129.Sum Root to Leaf Numbers/README.md +++ b/solution/0100-0199/0129.Sum Root to Leaf Numbers/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们可以设计一个函数 $dfs(root, s)$,表示从当前节点 $root$ 出发,且当前路径数字为 $s$,返回从当前节点到叶子节点的所有路径数字之和。那么答案就是 $dfs(root, 0)$。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -99,10 +93,6 @@ class Solution: return dfs(root, 0) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -165,8 +153,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -192,36 +178,6 @@ func sumNumbers(root *TreeNode) int { } ``` -### **C** - -```c -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -int dfs(struct TreeNode* root, int num) { - if (!root) { - return 0; - } - num = num * 10 + root->val; - if (!root->left && !root->right) { - return num; - } - return dfs(root->left, num) + dfs(root->right, num); -} - -int sumNumbers(struct TreeNode* root) { - return dfs(root, 0); -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -248,8 +204,6 @@ function sumNumbers(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -290,8 +244,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -316,10 +268,32 @@ var sumNumbers = function (root) { }; ``` -### **...** +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ -``` +int dfs(struct TreeNode* root, int num) { + if (!root) { + return 0; + } + num = num * 10 + root->val; + if (!root->left && !root->right) { + return num; + } + return dfs(root->left, num) + dfs(root->right, num); +} +int sumNumbers(struct TreeNode* root) { + return dfs(root, 0); +} ``` + + diff --git a/solution/0100-0199/0129.Sum Root to Leaf Numbers/README_EN.md b/solution/0100-0199/0129.Sum Root to Leaf Numbers/README_EN.md index a2bb1f3a57557..cfc1217f4e38e 100644 --- a/solution/0100-0199/0129.Sum Root to Leaf Numbers/README_EN.md +++ b/solution/0100-0199/0129.Sum Root to Leaf Numbers/README_EN.md @@ -51,7 +51,7 @@ Therefore, sum = 495 + 491 + 40 = 1026. ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We can design a function $dfs(root, s)$, which represents the sum of all path numbers from the current node $root$ to the leaf nodes, given that the current path number is $s$. The answer is $dfs(root, 0)$. @@ -66,8 +66,6 @@ The time complexity is $O(n)$, and the space complexity is $O(\log n)$. Here, $n -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -88,8 +86,6 @@ class Solution: return dfs(root, 0) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -124,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -152,8 +146,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -179,36 +171,6 @@ func sumNumbers(root *TreeNode) int { } ``` -### **C** - -```c -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -int dfs(struct TreeNode* root, int num) { - if (!root) { - return 0; - } - num = num * 10 + root->val; - if (!root->left && !root->right) { - return num; - } - return dfs(root->left, num) + dfs(root->right, num); -} - -int sumNumbers(struct TreeNode* root) { - return dfs(root, 0); -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -235,8 +197,6 @@ function sumNumbers(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -277,8 +237,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -303,10 +261,32 @@ var sumNumbers = function (root) { }; ``` -### **...** +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ -``` +int dfs(struct TreeNode* root, int num) { + if (!root) { + return 0; + } + num = num * 10 + root->val; + if (!root->left && !root->right) { + return num; + } + return dfs(root->left, num) + dfs(root->right, num); +} +int sumNumbers(struct TreeNode* root) { + return dfs(root, 0); +} ``` + + diff --git a/solution/0100-0199/0130.Surrounded Regions/README.md b/solution/0100-0199/0130.Surrounded Regions/README.md index 19ecad61aeb0a..74ed25ff327d4 100644 --- a/solution/0100-0199/0130.Surrounded Regions/README.md +++ b/solution/0100-0199/0130.Surrounded Regions/README.md @@ -42,18 +42,10 @@ ## 解法 -DFS、BFS、并查集均可。 - - +### 方法一 -### **Python3** - - - -DFS: - ```python class Solution: def solve(self, board: List[List[str]]) -> None: @@ -83,44 +75,6 @@ class Solution: board[i][j] = 'O' ``` -并查集: - -```python -class Solution: - def solve(self, board: List[List[str]]) -> None: - """ - Do not return anything, modify board in-place instead. - """ - - def find(x): - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - m, n = len(board), len(board[0]) - p = list(range(m * n + 1)) - for i in range(m): - for j in range(n): - if board[i][j] == 'O': - if i == 0 or i == m - 1 or j == 0 or j == n - 1: - p[find(i * n + j)] = find(m * n) - else: - for a, b in [(-1, 0), (1, 0), (0, -1), (0, 1)]: - x, y = i + a, j + b - if board[x][y] == 'O': - p[find(x * n + y)] = find(i * n + j) - for i in range(m): - for j in range(n): - if board[i][j] == 'O' and find(i * n + j) != find(m * n): - board[i][j] = 'X' -``` - -### **Java** - - - -DFS: - ```java class Solution { private char[][] board; @@ -163,58 +117,69 @@ class Solution { } ``` -并查集: - -```java +```cpp class Solution { - private int[] p; - - public void solve(char[][] board) { - int m = board.length; - int n = board[0].length; - p = new int[m * n + 1]; - for (int i = 0; i < p.length; ++i) { - p[i] = i; - } - int[] dirs = {-1, 0, 1, 0, -1}; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (board[i][j] == 'O') { - if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { - p[find(i * n + j)] = find(m * n); - } else { - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k]; - int y = j + dirs[k + 1]; - if (board[x][y] == 'O') { - p[find(x * n + y)] = find(i * n + j); - } - } - } - } - } - } +public: + void solve(vector>& board) { + int m = board.size(), n = board[0].size(); + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if ((i == 0 || i == m - 1 || j == 0 || j == n - 1) && board[i][j] == 'O') + dfs(board, i, j); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { - if (board[i][j] == 'O' && find(i * n + j) != find(m * n)) { + if (board[i][j] == '.') + board[i][j] = 'O'; + else if (board[i][j] == 'O') board[i][j] = 'X'; - } } } } - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); + void dfs(vector>& board, int i, int j) { + board[i][j] = '.'; + vector dirs = {-1, 0, 1, 0, -1}; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < board.size() && y >= 0 && y < board[0].size() && board[x][y] == 'O') + dfs(board, x, y); } - return p[x]; } -} +}; ``` -### **TypeScript** - -DFS: +```go +func solve(board [][]byte) { + m, n := len(board), len(board[0]) + var dfs func(i, j int) + dfs = func(i, j int) { + board[i][j] = '.' + dirs := []int{-1, 0, 1, 0, -1} + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'O' { + dfs(x, y) + } + } + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if (i == 0 || i == m-1 || j == 0 || j == n-1) && board[i][j] == 'O' { + dfs(i, j) + } + } + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if board[i][j] == '.' { + board[i][j] = 'O' + } else if board[i][j] == 'O' { + board[i][j] = 'X' + } + } + } +} +``` ```ts /** @@ -253,90 +218,197 @@ function solve(board: string[][]): void { } ``` -并查集: - -```ts -/** - Do not return anything, modify board in-place instead. - */ -function solve(board: string[][]): void { - const m = board.length; - const n = board[0].length; - let p = new Array(m * n + 1); - for (let i = 0; i < p.length; ++i) { - p[i] = i; +```rust +impl Solution { + fn dfs(i: usize, j: usize, mark: char, vis: &mut Vec>, board: &mut Vec>) { + if vis[i][j] || board[i][j] != mark { + return; + } + vis[i][j] = true; + if i > 0 { + Self::dfs(i - 1, j, mark, vis, board); + } + if i < vis.len() - 1 { + Self::dfs(i + 1, j, mark, vis, board); + } + if j > 0 { + Self::dfs(i, j - 1, mark, vis, board); + } + if j < vis[0].len() - 1 { + Self::dfs(i, j + 1, mark, vis, board); + } } - function find(x) { - if (p[x] != x) { - p[x] = find(p[x]); + + pub fn solve(board: &mut Vec>) { + let m = board.len(); + let n = board[0].len(); + let mut vis = vec![vec![false; n]; m]; + for i in 0..m { + Self::dfs(i, 0, board[i][0], &mut vis, board); + Self::dfs(i, n - 1, board[i][n - 1], &mut vis, board); + } + for i in 0..n { + Self::dfs(0, i, board[0][i], &mut vis, board); + Self::dfs(m - 1, i, board[m - 1][i], &mut vis, board); + } + for i in 0..m { + for j in 0..n { + if vis[i][j] { + continue; + } + board[i][j] = 'X'; + } } - return p[x]; } - const dirs = [-1, 0, 1, 0, -1]; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (board[i][j] == 'O') { - if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { - p[find(i * n + j)] = find(m * n); - } else { - for (let k = 0; k < 4; ++k) { - const x = i + dirs[k]; - const y = j + dirs[k + 1]; - if (board[x][y] == 'O') { - p[find(x * n + y)] = find(i * n + j); +} +``` + +```cs +using System; +using System.Collections.Generic; + +public class Solution { + private static readonly int[,] directions = new int[4, 2] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 }}; + public void Solve(char[][] board) { + var lenI = board.Length; + var lenJ = lenI == 0 ? 0 : board[0].Length; + + for (var i = 0; i < lenI; ++i) + { + for (var j = 0; j < lenJ; ++j) + { + if (board[i][j] == 'O') + { + var marked = new List>(); + marked.Add(Tuple.Create(i, j)); + board[i][j] = 'M'; + bool escaped = false; + for (var m = 0; m < marked.Count; ++m) + { + for (var k = 0; k < 4; ++k) + { + var newI = marked[m].Item1 + directions[k, 0]; + var newJ = marked[m].Item2 + directions[k, 1]; + if (newI < 0 || newI >= lenI || newJ < 0 || newJ >= lenJ) + { + escaped = true; + } + else if (board[newI][newJ] == 'O') + { + board[newI][newJ] = 'M'; + marked.Add(Tuple.Create(newI, newJ)); + } + } + } + + if (!escaped) + { + foreach (var item in marked) + { + board[item.Item1][item.Item2] = 'X'; } } } } } - } - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (board[i][j] == 'O' && find(i * n + j) != find(m * n)) { - board[i][j] = 'X'; + + for (var i = 0; i < lenI; ++i) + { + for (var j = 0; j < lenJ; ++j) + { + if (board[i][j] == 'M') + { + board[i][j] = 'O'; + } } } } } ``` -### **C++** + -DFS: +### 方法二 -```cpp + + +```python +class Solution: + def solve(self, board: List[List[str]]) -> None: + """ + Do not return anything, modify board in-place instead. + """ + + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + m, n = len(board), len(board[0]) + p = list(range(m * n + 1)) + for i in range(m): + for j in range(n): + if board[i][j] == 'O': + if i == 0 or i == m - 1 or j == 0 or j == n - 1: + p[find(i * n + j)] = find(m * n) + else: + for a, b in [(-1, 0), (1, 0), (0, -1), (0, 1)]: + x, y = i + a, j + b + if board[x][y] == 'O': + p[find(x * n + y)] = find(i * n + j) + for i in range(m): + for j in range(n): + if board[i][j] == 'O' and find(i * n + j) != find(m * n): + board[i][j] = 'X' +``` + +```java class Solution { -public: - void solve(vector>& board) { - int m = board.size(), n = board[0].size(); - for (int i = 0; i < m; ++i) - for (int j = 0; j < n; ++j) - if ((i == 0 || i == m - 1 || j == 0 || j == n - 1) && board[i][j] == 'O') - dfs(board, i, j); + private int[] p; + + public void solve(char[][] board) { + int m = board.length; + int n = board[0].length; + p = new int[m * n + 1]; + for (int i = 0; i < p.length; ++i) { + p[i] = i; + } + int[] dirs = {-1, 0, 1, 0, -1}; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { - if (board[i][j] == '.') - board[i][j] = 'O'; - else if (board[i][j] == 'O') + if (board[i][j] == 'O') { + if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { + p[find(i * n + j)] = find(m * n); + } else { + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k]; + int y = j + dirs[k + 1]; + if (board[x][y] == 'O') { + p[find(x * n + y)] = find(i * n + j); + } + } + } + } + } + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (board[i][j] == 'O' && find(i * n + j) != find(m * n)) { board[i][j] = 'X'; + } } } } - void dfs(vector>& board, int i, int j) { - board[i][j] = '.'; - vector dirs = {-1, 0, 1, 0, -1}; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < board.size() && y >= 0 && y < board[0].size() && board[x][y] == 'O') - dfs(board, x, y); + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); } + return p[x]; } -}; +} ``` -并查集: - ```cpp class Solution { public: @@ -374,45 +446,6 @@ public: }; ``` -### **Go** - -DFS: - -```go -func solve(board [][]byte) { - m, n := len(board), len(board[0]) - var dfs func(i, j int) - dfs = func(i, j int) { - board[i][j] = '.' - dirs := []int{-1, 0, 1, 0, -1} - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'O' { - dfs(x, y) - } - } - } - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - if (i == 0 || i == m-1 || j == 0 || j == n-1) && board[i][j] == 'O' { - dfs(i, j) - } - } - } - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - if board[i][j] == '.' { - board[i][j] = 'O' - } else if board[i][j] == 'O' { - board[i][j] = 'X' - } - } - } -} -``` - -并查集: - ```go func solve(board [][]byte) { m, n := len(board), len(board[0]) @@ -454,46 +487,44 @@ func solve(board [][]byte) { } ``` -### **Rust** - -```rust -impl Solution { - fn dfs(i: usize, j: usize, mark: char, vis: &mut Vec>, board: &mut Vec>) { - if vis[i][j] || board[i][j] != mark { - return; - } - vis[i][j] = true; - if i > 0 { - Self::dfs(i - 1, j, mark, vis, board); - } - if i < vis.len() - 1 { - Self::dfs(i + 1, j, mark, vis, board); - } - if j > 0 { - Self::dfs(i, j - 1, mark, vis, board); - } - if j < vis[0].len() - 1 { - Self::dfs(i, j + 1, mark, vis, board); - } +```ts +/** + Do not return anything, modify board in-place instead. + */ +function solve(board: string[][]): void { + const m = board.length; + const n = board[0].length; + let p = new Array(m * n + 1); + for (let i = 0; i < p.length; ++i) { + p[i] = i; } - - pub fn solve(board: &mut Vec>) { - let m = board.len(); - let n = board[0].len(); - let mut vis = vec![vec![false; n]; m]; - for i in 0..m { - Self::dfs(i, 0, board[i][0], &mut vis, board); - Self::dfs(i, n - 1, board[i][n - 1], &mut vis, board); - } - for i in 0..n { - Self::dfs(0, i, board[0][i], &mut vis, board); - Self::dfs(m - 1, i, board[m - 1][i], &mut vis, board); + function find(x) { + if (p[x] != x) { + p[x] = find(p[x]); } - for i in 0..m { - for j in 0..n { - if vis[i][j] { - continue; + return p[x]; + } + const dirs = [-1, 0, 1, 0, -1]; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (board[i][j] == 'O') { + if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { + p[find(i * n + j)] = find(m * n); + } else { + for (let k = 0; k < 4; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (board[x][y] == 'O') { + p[find(x * n + y)] = find(i * n + j); + } + } } + } + } + } + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (board[i][j] == 'O' && find(i * n + j) != find(m * n)) { board[i][j] = 'X'; } } @@ -501,10 +532,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0130.Surrounded Regions/README_EN.md b/solution/0100-0199/0130.Surrounded Regions/README_EN.md index 7ef2beb9653ca..1896ad29bc47e 100644 --- a/solution/0100-0199/0130.Surrounded Regions/README_EN.md +++ b/solution/0100-0199/0130.Surrounded Regions/README_EN.md @@ -40,11 +40,9 @@ The other three 'O' form a surrounded region, so they are flipped. ## Solutions - - -### **Python3** +### Solution 1 -DFS: + ```python class Solution: @@ -75,42 +73,6 @@ class Solution: board[i][j] = 'O' ``` -Union find: - -```python -class Solution: - def solve(self, board: List[List[str]]) -> None: - """ - Do not return anything, modify board in-place instead. - """ - - def find(x): - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - m, n = len(board), len(board[0]) - p = list(range(m * n + 1)) - for i in range(m): - for j in range(n): - if board[i][j] == 'O': - if i == 0 or i == m - 1 or j == 0 or j == n - 1: - p[find(i * n + j)] = find(m * n) - else: - for a, b in [(-1, 0), (1, 0), (0, -1), (0, 1)]: - x, y = i + a, j + b - if board[x][y] == 'O': - p[find(x * n + y)] = find(i * n + j) - for i in range(m): - for j in range(n): - if board[i][j] == 'O' and find(i * n + j) != find(m * n): - board[i][j] = 'X' -``` - -### **Java** - -DFS: - ```java class Solution { private char[][] board; @@ -153,58 +115,69 @@ class Solution { } ``` -Union find: - -```java +```cpp class Solution { - private int[] p; - - public void solve(char[][] board) { - int m = board.length; - int n = board[0].length; - p = new int[m * n + 1]; - for (int i = 0; i < p.length; ++i) { - p[i] = i; - } - int[] dirs = {-1, 0, 1, 0, -1}; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (board[i][j] == 'O') { - if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { - p[find(i * n + j)] = find(m * n); - } else { - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k]; - int y = j + dirs[k + 1]; - if (board[x][y] == 'O') { - p[find(x * n + y)] = find(i * n + j); - } - } - } - } - } - } +public: + void solve(vector>& board) { + int m = board.size(), n = board[0].size(); + for (int i = 0; i < m; ++i) + for (int j = 0; j < n; ++j) + if ((i == 0 || i == m - 1 || j == 0 || j == n - 1) && board[i][j] == 'O') + dfs(board, i, j); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { - if (board[i][j] == 'O' && find(i * n + j) != find(m * n)) { + if (board[i][j] == '.') + board[i][j] = 'O'; + else if (board[i][j] == 'O') board[i][j] = 'X'; - } } } } - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); + void dfs(vector>& board, int i, int j) { + board[i][j] = '.'; + vector dirs = {-1, 0, 1, 0, -1}; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < board.size() && y >= 0 && y < board[0].size() && board[x][y] == 'O') + dfs(board, x, y); } - return p[x]; } -} +}; ``` -### **TypeScript** - -DFS: +```go +func solve(board [][]byte) { + m, n := len(board), len(board[0]) + var dfs func(i, j int) + dfs = func(i, j int) { + board[i][j] = '.' + dirs := []int{-1, 0, 1, 0, -1} + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'O' { + dfs(x, y) + } + } + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if (i == 0 || i == m-1 || j == 0 || j == n-1) && board[i][j] == 'O' { + dfs(i, j) + } + } + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if board[i][j] == '.' { + board[i][j] = 'O' + } else if board[i][j] == 'O' { + board[i][j] = 'X' + } + } + } +} +``` ```ts /** @@ -243,90 +216,197 @@ function solve(board: string[][]): void { } ``` -Union find: - -```ts -/** - Do not return anything, modify board in-place instead. - */ -function solve(board: string[][]): void { - const m = board.length; - const n = board[0].length; - let p = new Array(m * n + 1); - for (let i = 0; i < p.length; ++i) { - p[i] = i; +```rust +impl Solution { + fn dfs(i: usize, j: usize, mark: char, vis: &mut Vec>, board: &mut Vec>) { + if vis[i][j] || board[i][j] != mark { + return; + } + vis[i][j] = true; + if i > 0 { + Self::dfs(i - 1, j, mark, vis, board); + } + if i < vis.len() - 1 { + Self::dfs(i + 1, j, mark, vis, board); + } + if j > 0 { + Self::dfs(i, j - 1, mark, vis, board); + } + if j < vis[0].len() - 1 { + Self::dfs(i, j + 1, mark, vis, board); + } } - function find(x) { - if (p[x] != x) { - p[x] = find(p[x]); + + pub fn solve(board: &mut Vec>) { + let m = board.len(); + let n = board[0].len(); + let mut vis = vec![vec![false; n]; m]; + for i in 0..m { + Self::dfs(i, 0, board[i][0], &mut vis, board); + Self::dfs(i, n - 1, board[i][n - 1], &mut vis, board); + } + for i in 0..n { + Self::dfs(0, i, board[0][i], &mut vis, board); + Self::dfs(m - 1, i, board[m - 1][i], &mut vis, board); + } + for i in 0..m { + for j in 0..n { + if vis[i][j] { + continue; + } + board[i][j] = 'X'; + } } - return p[x]; } - const dirs = [-1, 0, 1, 0, -1]; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (board[i][j] == 'O') { - if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { - p[find(i * n + j)] = find(m * n); - } else { - for (let k = 0; k < 4; ++k) { - const x = i + dirs[k]; - const y = j + dirs[k + 1]; - if (board[x][y] == 'O') { - p[find(x * n + y)] = find(i * n + j); +} +``` + +```cs +using System; +using System.Collections.Generic; + +public class Solution { + private static readonly int[,] directions = new int[4, 2] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 }}; + public void Solve(char[][] board) { + var lenI = board.Length; + var lenJ = lenI == 0 ? 0 : board[0].Length; + + for (var i = 0; i < lenI; ++i) + { + for (var j = 0; j < lenJ; ++j) + { + if (board[i][j] == 'O') + { + var marked = new List>(); + marked.Add(Tuple.Create(i, j)); + board[i][j] = 'M'; + bool escaped = false; + for (var m = 0; m < marked.Count; ++m) + { + for (var k = 0; k < 4; ++k) + { + var newI = marked[m].Item1 + directions[k, 0]; + var newJ = marked[m].Item2 + directions[k, 1]; + if (newI < 0 || newI >= lenI || newJ < 0 || newJ >= lenJ) + { + escaped = true; + } + else if (board[newI][newJ] == 'O') + { + board[newI][newJ] = 'M'; + marked.Add(Tuple.Create(newI, newJ)); + } + } + } + + if (!escaped) + { + foreach (var item in marked) + { + board[item.Item1][item.Item2] = 'X'; } } } } } - } - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (board[i][j] == 'O' && find(i * n + j) != find(m * n)) { - board[i][j] = 'X'; + + for (var i = 0; i < lenI; ++i) + { + for (var j = 0; j < lenJ; ++j) + { + if (board[i][j] == 'M') + { + board[i][j] = 'O'; + } } } } } ``` -### **C++** + -DFS: +### Solution 2 -```cpp + + +```python +class Solution: + def solve(self, board: List[List[str]]) -> None: + """ + Do not return anything, modify board in-place instead. + """ + + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + m, n = len(board), len(board[0]) + p = list(range(m * n + 1)) + for i in range(m): + for j in range(n): + if board[i][j] == 'O': + if i == 0 or i == m - 1 or j == 0 or j == n - 1: + p[find(i * n + j)] = find(m * n) + else: + for a, b in [(-1, 0), (1, 0), (0, -1), (0, 1)]: + x, y = i + a, j + b + if board[x][y] == 'O': + p[find(x * n + y)] = find(i * n + j) + for i in range(m): + for j in range(n): + if board[i][j] == 'O' and find(i * n + j) != find(m * n): + board[i][j] = 'X' +``` + +```java class Solution { -public: - void solve(vector>& board) { - int m = board.size(), n = board[0].size(); - for (int i = 0; i < m; ++i) - for (int j = 0; j < n; ++j) - if ((i == 0 || i == m - 1 || j == 0 || j == n - 1) && board[i][j] == 'O') - dfs(board, i, j); + private int[] p; + + public void solve(char[][] board) { + int m = board.length; + int n = board[0].length; + p = new int[m * n + 1]; + for (int i = 0; i < p.length; ++i) { + p[i] = i; + } + int[] dirs = {-1, 0, 1, 0, -1}; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { - if (board[i][j] == '.') - board[i][j] = 'O'; - else if (board[i][j] == 'O') + if (board[i][j] == 'O') { + if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { + p[find(i * n + j)] = find(m * n); + } else { + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k]; + int y = j + dirs[k + 1]; + if (board[x][y] == 'O') { + p[find(x * n + y)] = find(i * n + j); + } + } + } + } + } + } + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (board[i][j] == 'O' && find(i * n + j) != find(m * n)) { board[i][j] = 'X'; + } } } } - void dfs(vector>& board, int i, int j) { - board[i][j] = '.'; - vector dirs = {-1, 0, 1, 0, -1}; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < board.size() && y >= 0 && y < board[0].size() && board[x][y] == 'O') - dfs(board, x, y); + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); } + return p[x]; } -}; +} ``` -Union find: - ```cpp class Solution { public: @@ -364,45 +444,6 @@ public: }; ``` -### **Go** - -DFS: - -```go -func solve(board [][]byte) { - m, n := len(board), len(board[0]) - var dfs func(i, j int) - dfs = func(i, j int) { - board[i][j] = '.' - dirs := []int{-1, 0, 1, 0, -1} - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'O' { - dfs(x, y) - } - } - } - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - if (i == 0 || i == m-1 || j == 0 || j == n-1) && board[i][j] == 'O' { - dfs(i, j) - } - } - } - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - if board[i][j] == '.' { - board[i][j] = 'O' - } else if board[i][j] == 'O' { - board[i][j] = 'X' - } - } - } -} -``` - -Union find: - ```go func solve(board [][]byte) { m, n := len(board), len(board[0]) @@ -444,46 +485,44 @@ func solve(board [][]byte) { } ``` -### **Rust** - -```rust -impl Solution { - fn dfs(i: usize, j: usize, mark: char, vis: &mut Vec>, board: &mut Vec>) { - if vis[i][j] || board[i][j] != mark { - return; - } - vis[i][j] = true; - if i > 0 { - Self::dfs(i - 1, j, mark, vis, board); - } - if i < vis.len() - 1 { - Self::dfs(i + 1, j, mark, vis, board); - } - if j > 0 { - Self::dfs(i, j - 1, mark, vis, board); - } - if j < vis[0].len() - 1 { - Self::dfs(i, j + 1, mark, vis, board); - } +```ts +/** + Do not return anything, modify board in-place instead. + */ +function solve(board: string[][]): void { + const m = board.length; + const n = board[0].length; + let p = new Array(m * n + 1); + for (let i = 0; i < p.length; ++i) { + p[i] = i; } - - pub fn solve(board: &mut Vec>) { - let m = board.len(); - let n = board[0].len(); - let mut vis = vec![vec![false; n]; m]; - for i in 0..m { - Self::dfs(i, 0, board[i][0], &mut vis, board); - Self::dfs(i, n - 1, board[i][n - 1], &mut vis, board); - } - for i in 0..n { - Self::dfs(0, i, board[0][i], &mut vis, board); - Self::dfs(m - 1, i, board[m - 1][i], &mut vis, board); + function find(x) { + if (p[x] != x) { + p[x] = find(p[x]); } - for i in 0..m { - for j in 0..n { - if vis[i][j] { - continue; + return p[x]; + } + const dirs = [-1, 0, 1, 0, -1]; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (board[i][j] == 'O') { + if (i == 0 || i == m - 1 || j == 0 || j == n - 1) { + p[find(i * n + j)] = find(m * n); + } else { + for (let k = 0; k < 4; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (board[x][y] == 'O') { + p[find(x * n + y)] = find(i * n + j); + } + } } + } + } + } + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (board[i][j] == 'O' && find(i * n + j) != find(m * n)) { board[i][j] = 'X'; } } @@ -491,10 +530,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0131.Palindrome Partitioning/README.md b/solution/0100-0199/0131.Palindrome Partitioning/README.md index 6135226d46efa..9f169795d2413 100644 --- a/solution/0100-0199/0131.Palindrome Partitioning/README.md +++ b/solution/0100-0199/0131.Palindrome Partitioning/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:预处理 + DFS(回溯)** +### 方法一:预处理 + DFS(回溯) 我们可以使用动态规划,预处理出字符串中的任意子串是否为回文串,即 $f[i][j]$ 表示子串 $s[i..j]$ 是否为回文串。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def partition(self, s: str) -> List[List[str]]: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int n; @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +148,6 @@ public: }; ``` -### **Go** - ```go func partition(s string) (ans [][]string) { n := len(s) @@ -197,8 +183,6 @@ func partition(s string) (ans [][]string) { } ``` -### **TypeScript** - ```ts function partition(s: string): string[][] { const n = s.length; @@ -228,8 +212,6 @@ function partition(s: string): string[][] { } ``` -### **C#** - ```cs public class Solution { private int n; @@ -272,10 +254,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0131.Palindrome Partitioning/README_EN.md b/solution/0100-0199/0131.Palindrome Partitioning/README_EN.md index 565eb66cf2065..c206d0101a229 100644 --- a/solution/0100-0199/0131.Palindrome Partitioning/README_EN.md +++ b/solution/0100-0199/0131.Palindrome Partitioning/README_EN.md @@ -24,9 +24,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int n; @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +125,6 @@ public: }; ``` -### **Go** - ```go func partition(s string) (ans [][]string) { n := len(s) @@ -166,8 +160,6 @@ func partition(s string) (ans [][]string) { } ``` -### **TypeScript** - ```ts function partition(s: string): string[][] { const n = s.length; @@ -197,8 +189,6 @@ function partition(s: string): string[][] { } ``` -### **C#** - ```cs public class Solution { private int n; @@ -241,10 +231,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0132.Palindrome Partitioning II/README.md b/solution/0100-0199/0132.Palindrome Partitioning II/README.md index 534ffd8b4359e..65817101308c5 100644 --- a/solution/0100-0199/0132.Palindrome Partitioning II/README.md +++ b/solution/0100-0199/0132.Palindrome Partitioning II/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们先预处理得到字符串 $s$ 的每一个子串 $s[i..j]$ 是否为回文串,记录在二维数组 $g[i][j]$ 中,其中 $g[i][j]$ 表示子串 $s[i..j]$ 是否为回文串。 @@ -69,10 +67,6 @@ $$ -### **Python3** - - - ```python class Solution: def minCut(self, s: str) -> int: @@ -89,10 +83,6 @@ class Solution: return f[-1] ``` -### **Java** - - - ```java class Solution { public int minCut(String s) { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func minCut(s string) int { n := len(s) @@ -184,8 +170,6 @@ func minCut(s string) int { } ``` -### **TypeScript** - ```ts function minCut(s: string): number { const n = s.length; @@ -211,8 +195,6 @@ function minCut(s: string): number { } ``` -### **C#** - ```cs public class Solution { public int MinCut(string s) { @@ -242,10 +224,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0132.Palindrome Partitioning II/README_EN.md b/solution/0100-0199/0132.Palindrome Partitioning II/README_EN.md index 3f81379188678..854a17515ae41 100644 --- a/solution/0100-0199/0132.Palindrome Partitioning II/README_EN.md +++ b/solution/0100-0199/0132.Palindrome Partitioning II/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return f[-1] ``` -### **Java** - ```java class Solution { public int minCut(String s) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +116,6 @@ public: }; ``` -### **Go** - ```go func minCut(s string) int { n := len(s) @@ -154,8 +148,6 @@ func minCut(s string) int { } ``` -### **TypeScript** - ```ts function minCut(s: string): number { const n = s.length; @@ -181,8 +173,6 @@ function minCut(s: string): number { } ``` -### **C#** - ```cs public class Solution { public int MinCut(string s) { @@ -212,10 +202,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0133.Clone Graph/README.md b/solution/0100-0199/0133.Clone Graph/README.md index 3ec49e83e8379..288d8d167ec26 100644 --- a/solution/0100-0199/0133.Clone Graph/README.md +++ b/solution/0100-0199/0133.Clone Graph/README.md @@ -78,14 +78,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python """ # Definition for a Node. @@ -114,10 +110,6 @@ class Solution: return clone(node) ``` -### **Java** - - - ```java /* // Definition for a Node. @@ -159,45 +151,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -/** - * Definition for Node. - * class Node { - * val: number - * neighbors: Node[] - * constructor(val?: number, neighbors?: Node[]) { - * this.val = (val===undefined ? 0 : val) - * this.neighbors = (neighbors===undefined ? [] : neighbors) - * } - * } - */ - -function cloneGraph(node: Node | null): Node | null { - if (node == null) return null; - - const visited = new Map(); - visited.set(node, new Node(node.val)); - const queue = [node]; - while (queue.length) { - const cur = queue.shift(); - for (let neighbor of cur.neighbors || []) { - if (!visited.has(neighbor)) { - queue.push(neighbor); - const newNeighbor = new Node(neighbor.val, []); - visited.set(neighbor, newNeighbor); - } - const newNode = visited.get(cur); - newNode.neighbors.push(visited.get(neighbor)); - } - } - return visited.get(node); -} -``` - -### **C++** - ```cpp /* // Definition for a Node. @@ -236,8 +189,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -269,10 +220,78 @@ func cloneGraph(node *Node) *Node { } ``` -### **...** +```ts +/** + * Definition for Node. + * class Node { + * val: number + * neighbors: Node[] + * constructor(val?: number, neighbors?: Node[]) { + * this.val = (val===undefined ? 0 : val) + * this.neighbors = (neighbors===undefined ? [] : neighbors) + * } + * } + */ + +function cloneGraph(node: Node | null): Node | null { + if (node == null) return null; + const visited = new Map(); + visited.set(node, new Node(node.val)); + const queue = [node]; + while (queue.length) { + const cur = queue.shift(); + for (let neighbor of cur.neighbors || []) { + if (!visited.has(neighbor)) { + queue.push(neighbor); + const newNeighbor = new Node(neighbor.val, []); + visited.set(neighbor, newNeighbor); + } + const newNode = visited.get(cur); + newNode.neighbors.push(visited.get(neighbor)); + } + } + return visited.get(node); +} ``` +```cs +using System.Collections.Generic; + +public class Solution { + public Node CloneGraph(Node node) { + if (node == null) return null; + var dict = new Dictionary(); + var queue = new Queue(); + queue.Enqueue(CloneVal(node)); + dict.Add(node.val, queue.Peek()); + while (queue.Count > 0) + { + var current = queue.Dequeue(); + var newNeighbors = new List(current.neighbors.Count); + foreach (var oldNeighbor in current.neighbors) + { + Node newNeighbor; + if (!dict.TryGetValue(oldNeighbor.val, out newNeighbor)) + { + newNeighbor = CloneVal(oldNeighbor); + queue.Enqueue(newNeighbor); + dict.Add(newNeighbor.val, newNeighbor); + } + newNeighbors.Add(newNeighbor); + } + current.neighbors = newNeighbors; + } + return dict[node.val]; + } + + private Node CloneVal(Node node) + { + return new Node(node.val, new List(node.neighbors)); + } +} ``` + + diff --git a/solution/0100-0199/0133.Clone Graph/README_EN.md b/solution/0100-0199/0133.Clone Graph/README_EN.md index 2612548bec070..f1def1eec3f6d 100644 --- a/solution/0100-0199/0133.Clone Graph/README_EN.md +++ b/solution/0100-0199/0133.Clone Graph/README_EN.md @@ -69,9 +69,9 @@ class Node { ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -101,8 +101,6 @@ class Solution: return clone(node) ``` -### **Java** - ```java /* // Definition for a Node. @@ -144,45 +142,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -/** - * Definition for Node. - * class Node { - * val: number - * neighbors: Node[] - * constructor(val?: number, neighbors?: Node[]) { - * this.val = (val===undefined ? 0 : val) - * this.neighbors = (neighbors===undefined ? [] : neighbors) - * } - * } - */ - -function cloneGraph(node: Node | null): Node | null { - if (node == null) return null; - - const visited = new Map(); - visited.set(node, new Node(node.val)); - const queue = [node]; - while (queue.length) { - const cur = queue.shift(); - for (let neighbor of cur.neighbors || []) { - if (!visited.has(neighbor)) { - queue.push(neighbor); - const newNeighbor = new Node(neighbor.val, []); - visited.set(neighbor, newNeighbor); - } - const newNode = visited.get(cur); - newNode.neighbors.push(visited.get(neighbor)); - } - } - return visited.get(node); -} -``` - -### **C++** - ```cpp /* // Definition for a Node. @@ -221,8 +180,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -254,10 +211,78 @@ func cloneGraph(node *Node) *Node { } ``` -### **...** +```ts +/** + * Definition for Node. + * class Node { + * val: number + * neighbors: Node[] + * constructor(val?: number, neighbors?: Node[]) { + * this.val = (val===undefined ? 0 : val) + * this.neighbors = (neighbors===undefined ? [] : neighbors) + * } + * } + */ + +function cloneGraph(node: Node | null): Node | null { + if (node == null) return null; + const visited = new Map(); + visited.set(node, new Node(node.val)); + const queue = [node]; + while (queue.length) { + const cur = queue.shift(); + for (let neighbor of cur.neighbors || []) { + if (!visited.has(neighbor)) { + queue.push(neighbor); + const newNeighbor = new Node(neighbor.val, []); + visited.set(neighbor, newNeighbor); + } + const newNode = visited.get(cur); + newNode.neighbors.push(visited.get(neighbor)); + } + } + return visited.get(node); +} ``` +```cs +using System.Collections.Generic; + +public class Solution { + public Node CloneGraph(Node node) { + if (node == null) return null; + var dict = new Dictionary(); + var queue = new Queue(); + queue.Enqueue(CloneVal(node)); + dict.Add(node.val, queue.Peek()); + while (queue.Count > 0) + { + var current = queue.Dequeue(); + var newNeighbors = new List(current.neighbors.Count); + foreach (var oldNeighbor in current.neighbors) + { + Node newNeighbor; + if (!dict.TryGetValue(oldNeighbor.val, out newNeighbor)) + { + newNeighbor = CloneVal(oldNeighbor); + queue.Enqueue(newNeighbor); + dict.Add(newNeighbor.val, newNeighbor); + } + newNeighbors.Add(newNeighbor); + } + current.neighbors = newNeighbors; + } + return dict[node.val]; + } + + private Node CloneVal(Node node) + { + return new Node(node.val, new List(node.neighbors)); + } +} ``` + + diff --git a/solution/0100-0199/0134.Gas Station/README.md b/solution/0100-0199/0134.Gas Station/README.md index ea10b5090069d..8c129efa8303a 100644 --- a/solution/0100-0199/0134.Gas Station/README.md +++ b/solution/0100-0199/0134.Gas Station/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:从任意起点开始遍历** +### 方法一:从任意起点开始遍历 我们用 $i$, $j$ 分别标记起点和终点,用 $s$ 表示当前剩余汽油,而 $cnt$ 表示当前行驶过的加油站数量。初始时,我们将起点设在最后一个位置,即 $i=n-1$。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: @@ -89,10 +83,6 @@ class Solution: return -1 if s < 0 else i ``` -### **Java** - - - ```java class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func canCompleteCircuit(gas []int, cost []int) int { n := len(gas) @@ -162,8 +148,6 @@ func canCompleteCircuit(gas []int, cost []int) int { } ``` -### **TypeScript** - ```ts function canCompleteCircuit(gas: number[], cost: number[]): number { const n = gas.length; @@ -185,8 +169,6 @@ function canCompleteCircuit(gas: number[], cost: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int CanCompleteCircuit(int[] gas, int[] cost) { @@ -208,10 +190,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0134.Gas Station/README_EN.md b/solution/0100-0199/0134.Gas Station/README_EN.md index ce623ab281839..ba21c8905a67c 100644 --- a/solution/0100-0199/0134.Gas Station/README_EN.md +++ b/solution/0100-0199/0134.Gas Station/README_EN.md @@ -51,9 +51,9 @@ Therefore, you can't travel around the circuit once no matter where you star ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return -1 if s < 0 else i ``` -### **Java** - ```java class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +115,6 @@ public: }; ``` -### **Go** - ```go func canCompleteCircuit(gas []int, cost []int) int { n := len(gas) @@ -143,8 +137,6 @@ func canCompleteCircuit(gas []int, cost []int) int { } ``` -### **TypeScript** - ```ts function canCompleteCircuit(gas: number[], cost: number[]): number { const n = gas.length; @@ -166,8 +158,6 @@ function canCompleteCircuit(gas: number[], cost: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int CanCompleteCircuit(int[] gas, int[] cost) { @@ -189,10 +179,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0135.Candy/README.md b/solution/0100-0199/0135.Candy/README.md index 6f6b520d3809b..b50ee678f52e9 100644 --- a/solution/0100-0199/0135.Candy/README.md +++ b/solution/0100-0199/0135.Candy/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:两次遍历** +### 方法一:两次遍历 我们初始化两个数组 $left$ 和 $right$,其中 $left[i]$ 表示当前孩子比左边孩子评分高时,当前孩子至少应该获得的糖果数,而 $right[i]$ 表示当前孩子比右边孩子评分高时,当前孩子至少应该获得的糖果数。初始时 $left[i]=1$, $right[i]=1$。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def candy(self, ratings: List[int]) -> int: @@ -80,10 +74,6 @@ class Solution: return sum(max(a, b) for a, b in zip(left, right)) ``` -### **Java** - - - ```java class Solution { public int candy(int[] ratings) { @@ -111,38 +101,6 @@ class Solution { } ``` -```java -class Solution { - public int candy(int[] ratings) { - int n = ratings.length; - int up = 0; - int down = 0; - int peak = 0; - int candies = 1; - for (int i = 1; i < n; i++) { - if (ratings[i - 1] < ratings[i]) { - up++; - peak = up + 1; - down = 0; - candies += peak; - } else if (ratings[i] == ratings[i - 1]) { - peak = 0; - up = 0; - down = 0; - candies++; - } else { - down++; - up = 0; - candies += down + (peak > down ? 0 : 1); - } - } - return candies; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -169,8 +127,6 @@ public: }; ``` -### **Go** - ```go func candy(ratings []int) int { n := len(ratings) @@ -199,8 +155,6 @@ func candy(ratings []int) int { } ``` -### **TypeScript** - ```ts function candy(ratings: number[]): number { const n = ratings.length; @@ -224,8 +178,6 @@ function candy(ratings: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int Candy(int[] ratings) { @@ -253,10 +205,42 @@ public class Solution { } ``` -### **...** + -``` +### 方法二 + + +```java +class Solution { + public int candy(int[] ratings) { + int n = ratings.length; + int up = 0; + int down = 0; + int peak = 0; + int candies = 1; + for (int i = 1; i < n; i++) { + if (ratings[i - 1] < ratings[i]) { + up++; + peak = up + 1; + down = 0; + candies += peak; + } else if (ratings[i] == ratings[i - 1]) { + peak = 0; + up = 0; + down = 0; + candies++; + } else { + down++; + up = 0; + candies += down + (peak > down ? 0 : 1); + } + } + return candies; + } +} ``` + + diff --git a/solution/0100-0199/0135.Candy/README_EN.md b/solution/0100-0199/0135.Candy/README_EN.md index bf5362bbdb441..06d8feb6bc257 100644 --- a/solution/0100-0199/0135.Candy/README_EN.md +++ b/solution/0100-0199/0135.Candy/README_EN.md @@ -44,7 +44,7 @@ The third child gets 1 candy because it satisfies the above two conditions. ## Solutions -**Solution 1: Two traversals** +### Solution 1: Two traversals We initialize two arrays $left$ and $right$, where $left[i]$ represents the minimum number of candies the current child should get when the current child's score is higher than the left child's score, and $right[i]$ represents the minimum number of candies the current child should get when the current child's score is higher than the right child's score. Initially, $left[i]=1$, $right[i]=1$. @@ -56,8 +56,6 @@ Time complexity $O(n)$, space complexity $O(n)$. Where $n$ is the length of the -### **Python3** - ```python class Solution: def candy(self, ratings: List[int]) -> int: @@ -73,8 +71,6 @@ class Solution: return sum(max(a, b) for a, b in zip(left, right)) ``` -### **Java** - ```java class Solution { public int candy(int[] ratings) { @@ -102,38 +98,6 @@ class Solution { } ``` -```java -class Solution { - public int candy(int[] ratings) { - int n = ratings.length; - int up = 0; - int down = 0; - int peak = 0; - int candies = 1; - for (int i = 1; i < n; i++) { - if (ratings[i - 1] < ratings[i]) { - up++; - peak = up + 1; - down = 0; - candies += peak; - } else if (ratings[i] == ratings[i - 1]) { - peak = 0; - up = 0; - down = 0; - candies++; - } else { - down++; - up = 0; - candies += down + (peak > down ? 0 : 1); - } - } - return candies; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -160,8 +124,6 @@ public: }; ``` -### **Go** - ```go func candy(ratings []int) int { n := len(ratings) @@ -190,8 +152,6 @@ func candy(ratings []int) int { } ``` -### **TypeScript** - ```ts function candy(ratings: number[]): number { const n = ratings.length; @@ -215,8 +175,6 @@ function candy(ratings: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int Candy(int[] ratings) { @@ -244,10 +202,42 @@ public class Solution { } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + public int candy(int[] ratings) { + int n = ratings.length; + int up = 0; + int down = 0; + int peak = 0; + int candies = 1; + for (int i = 1; i < n; i++) { + if (ratings[i - 1] < ratings[i]) { + up++; + peak = up + 1; + down = 0; + candies += peak; + } else if (ratings[i] == ratings[i - 1]) { + peak = 0; + up = 0; + down = 0; + candies++; + } else { + down++; + up = 0; + candies += down + (peak > down ? 0 : 1); + } + } + return candies; + } +} ``` + + diff --git a/solution/0100-0199/0136.Single Number/README.md b/solution/0100-0199/0136.Single Number/README.md index 4bd6ca358d480..5955baa5521f0 100644 --- a/solution/0100-0199/0136.Single Number/README.md +++ b/solution/0100-0199/0136.Single Number/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 异或运算的性质: @@ -64,20 +62,12 @@ -### **Python3** - - - ```python class Solution: def singleNumber(self, nums: List[int]) -> int: return reduce(xor, nums) ``` -### **Java** - - - ```java class Solution { public int singleNumber(int[] nums) { @@ -90,16 +80,6 @@ class Solution { } ``` -```java -class Solution { - public int singleNumber(int[] nums) { - return Arrays.stream(nums).reduce(0, (a, b) -> a ^ b); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -113,8 +93,6 @@ public: }; ``` -### **Go** - ```go func singleNumber(nums []int) (ans int) { for _, v := range nums { @@ -124,28 +102,12 @@ func singleNumber(nums []int) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var singleNumber = function (nums) { - return nums.reduce((a, b) => a ^ b); -}; -``` - -### **TypeScript** - ```ts function singleNumber(nums: number[]): number { return nums.reduce((r, v) => r ^ v); } ``` -### **Rust** - ```rust impl Solution { pub fn single_number(nums: Vec) -> i32 { @@ -156,7 +118,23 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {number[]} nums + * @return {number} + */ +var singleNumber = function (nums) { + return nums.reduce((a, b) => a ^ b); +}; +``` + +```cs +public class Solution { + public int SingleNumber(int[] nums) { + return nums.Aggregate(0, (a, b) => a ^ b); + } +} +``` ```c int singleNumber(int* nums, int numsSize) { @@ -168,8 +146,6 @@ int singleNumber(int* nums, int numsSize) { } ``` -### **Swift** - ```swift class Solution { func singleNumber(_ nums: [Int]) -> Int { @@ -178,20 +154,20 @@ class Solution { } ``` -### **C#** - -```cs -public class Solution { - public int SingleNumber(int[] nums) { - return nums.Aggregate(0, (a, b) => a ^ b); - } -} -``` + -### **...** +### 方法二 -``` + +```java +class Solution { + public int singleNumber(int[] nums) { + return Arrays.stream(nums).reduce(0, (a, b) -> a ^ b); + } +} ``` + + diff --git a/solution/0100-0199/0136.Single Number/README_EN.md b/solution/0100-0199/0136.Single Number/README_EN.md index cf670ec826988..186a33edd9358 100644 --- a/solution/0100-0199/0136.Single Number/README_EN.md +++ b/solution/0100-0199/0136.Single Number/README_EN.md @@ -30,7 +30,7 @@ ## Solutions -**Solution 1: Bitwise Operation** +### Solution 1: Bitwise Operation The XOR operation has the following properties: @@ -43,16 +43,12 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def singleNumber(self, nums: List[int]) -> int: return reduce(xor, nums) ``` -### **Java** - ```java class Solution { public int singleNumber(int[] nums) { @@ -65,16 +61,6 @@ class Solution { } ``` -```java -class Solution { - public int singleNumber(int[] nums) { - return Arrays.stream(nums).reduce(0, (a, b) -> a ^ b); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -88,8 +74,6 @@ public: }; ``` -### **Go** - ```go func singleNumber(nums []int) (ans int) { for _, v := range nums { @@ -99,28 +83,12 @@ func singleNumber(nums []int) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var singleNumber = function (nums) { - return nums.reduce((a, b) => a ^ b); -}; -``` - -### **TypeScript** - ```ts function singleNumber(nums: number[]): number { return nums.reduce((r, v) => r ^ v); } ``` -### **Rust** - ```rust impl Solution { pub fn single_number(nums: Vec) -> i32 { @@ -131,7 +99,23 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {number[]} nums + * @return {number} + */ +var singleNumber = function (nums) { + return nums.reduce((a, b) => a ^ b); +}; +``` + +```cs +public class Solution { + public int SingleNumber(int[] nums) { + return nums.Aggregate(0, (a, b) => a ^ b); + } +} +``` ```c int singleNumber(int* nums, int numsSize) { @@ -143,8 +127,6 @@ int singleNumber(int* nums, int numsSize) { } ``` -### **Swift** - ```swift class Solution { func singleNumber(_ nums: [Int]) -> Int { @@ -153,20 +135,20 @@ class Solution { } ``` -### **C#** - -```cs -public class Solution { - public int SingleNumber(int[] nums) { - return nums.Aggregate(0, (a, b) => a ^ b); - } -} -``` + -### **...** +### Solution 2 -``` + +```java +class Solution { + public int singleNumber(int[] nums) { + return Arrays.stream(nums).reduce(0, (a, b) -> a ^ b); + } +} ``` + + diff --git a/solution/0100-0199/0137.Single Number II/README.md b/solution/0100-0199/0137.Single Number II/README.md index f7442b4cc2a1f..31aaddbe62e53 100644 --- a/solution/0100-0199/0137.Single Number II/README.md +++ b/solution/0100-0199/0137.Single Number II/README.md @@ -38,57 +38,14 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 我们可以枚举每个二进制位 $i$,对于每个二进制位,我们统计所有数字在该二进制位上的和,如果该二进制位上的和能被 $3$ 整除,那么只出现一次的数字在该二进制位上为 $0$,否则为 $1$。 时间复杂度 $O(n \times \log M)$,空间复杂度 $O(1)$。其中 $n$ 和 $M$ 分别是数组的长度和数组中元素的范围。 -**方法二:数字电路** - -我们考虑一种更高效的方法,该方法使用数字电路来模拟上述的位运算。 - -一个整数的每个二进制位是 $0$ 或 $1$,只能表示 $2$ 种状态。但我们需要表示当前遍历过的所有整数的第 $i$ 位之和模 $3$ 的结果,因此,我们可以使用 $a$ 和 $b$ 两个整数来表示。那么会有以下三种情况: - -1. 整数 $a$ 的第 $i$ 位为 $0$ 且整数 $b$ 的第 $i$ 位为 $0$,表示模 $3$ 结果是 $0$; -1. 整数 $a$ 的第 $i$ 位为 $0$ 且整数 $b$ 的第 $i$ 位为 $1$,表示模 $3$ 结果是 $1$; -1. 整数 $a$ 的第 $i$ 位为 $1$ 且整数 $b$ 的第 $i$ 位为 $0$,表示模 $3$ 结果是 $2$。 - -我们用整数 $c$ 表示当前要读入的数,那么有以下真值表: - -| $a_i$ | $b_i$ | $c_i$ | 新的 $a_i$ | 新的 $b_i$ | -| ----- | ----- | ----- | ---------- | ---------- | -| 0 | 0 | 0 | 0 | 0 | -| 0 | 0 | 1 | 0 | 1 | -| 0 | 1 | 0 | 0 | 1 | -| 0 | 1 | 1 | 1 | 0 | -| 1 | 0 | 0 | 1 | 0 | -| 1 | 0 | 1 | 0 | 0 | - -基于以上真值表,我们可以写出逻辑表达式: - -$$ -a_i = a_i' b_i c_i + a_i b_i' c_i' -$$ - -以及: - -$$ -b_i = a_i' b_i' c_i + a_i' b_i c_i' = a_i' (b_i \oplus c_i) -$$ - -最后结果是 $b$,因为 $b$ 的二进制位上为 $1$ 时表示这个数字出现了 $1$ 次。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是数组的长度。 - -### **Python3** - - - ```python class Solution: def singleNumber(self, nums: List[int]) -> int: @@ -103,21 +60,6 @@ class Solution: return ans ``` -```python -class Solution: - def singleNumber(self, nums: List[int]) -> int: - a = b = 0 - for c in nums: - aa = (~a & b & c) | (a & ~b & ~c) - bb = ~a & (b ^ c) - a, b = aa, bb - return b -``` - -### **Java** - - - ```java class Solution { public int singleNumber(int[] nums) { @@ -135,54 +77,6 @@ class Solution { } ``` -```java -class Solution { - public int singleNumber(int[] nums) { - int a = 0, b = 0; - for (int c : nums) { - int aa = (~a & b & c) | (a & ~b & ~c); - int bb = ~a & (b ^ c); - a = aa; - b = bb; - } - return b; - } -} -``` - -### **Go** - -需要注意 Golang 中的 `int` 在 64 位平台上相当于 `int64` - -```go -func singleNumber(nums []int) int { - ans := int32(0) - for i := 0; i < 32; i++ { - cnt := int32(0) - for _, num := range nums { - cnt += int32(num) >> i & 1 - } - cnt %= 3 - ans |= cnt << i - } - return int(ans) -} -``` - -```go -func singleNumber(nums []int) int { - a, b := 0, 0 - for _, c := range nums { - aa := (^a & b & c) | (a & ^b & ^c) - bb := ^a & (b ^ c) - a, b = aa, bb - } - return b -} -``` - -### **C++** - ```cpp class Solution { public: @@ -201,24 +95,21 @@ public: }; ``` -```cpp -class Solution { -public: - int singleNumber(vector& nums) { - int a = 0, b = 0; - for (int c : nums) { - int aa = (~a & b & c) | (a & ~b & ~c); - int bb = ~a & (b ^ c); - a = aa; - b = bb; - } - return b; - } -}; +```go +func singleNumber(nums []int) int { + ans := int32(0) + for i := 0; i < 32; i++ { + cnt := int32(0) + for _, num := range nums { + cnt += int32(num) >> i & 1 + } + cnt %= 3 + ans |= cnt << i + } + return int(ans) +} ``` -### **TypeScript** - ```ts function singleNumber(nums: number[]): number { let ans = 0; @@ -230,22 +121,6 @@ function singleNumber(nums: number[]): number { } ``` -```ts -function singleNumber(nums: number[]): number { - let a = 0; - let b = 0; - for (const c of nums) { - const aa = (~a & b & c) | (a & ~b & ~c); - const bb = ~a & (b ^ c); - a = aa; - b = bb; - } - return b; -} -``` - -### **Rust** - ```rust impl Solution { pub fn single_number(nums: Vec) -> i32 { @@ -262,26 +137,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn single_number(nums: Vec) -> i32 { - let mut a = 0; - let mut b = 0; - - for c in nums { - let aa = (!a & b & c) | (a & !b & !c); - let bb = !a & (b ^ c); - a = aa; - b = bb; - } - - return b; - } -} -``` - -### **C** - ```c int singleNumber(int* nums, int numsSize) { int ans = 0; @@ -298,8 +153,6 @@ int singleNumber(int* nums, int numsSize) { } ``` -### **Swift** - ```swift class Solution { func singleNumber(_ nums: [Int]) -> Int { @@ -315,10 +168,133 @@ class Solution { } ``` -### **...** + + +### 方法二:数字电路 + +我们考虑一种更高效的方法,该方法使用数字电路来模拟上述的位运算。 + +一个整数的每个二进制位是 $0$ 或 $1$,只能表示 $2$ 种状态。但我们需要表示当前遍历过的所有整数的第 $i$ 位之和模 $3$ 的结果,因此,我们可以使用 $a$ 和 $b$ 两个整数来表示。那么会有以下三种情况: + +1. 整数 $a$ 的第 $i$ 位为 $0$ 且整数 $b$ 的第 $i$ 位为 $0$,表示模 $3$ 结果是 $0$; +1. 整数 $a$ 的第 $i$ 位为 $0$ 且整数 $b$ 的第 $i$ 位为 $1$,表示模 $3$ 结果是 $1$; +1. 整数 $a$ 的第 $i$ 位为 $1$ 且整数 $b$ 的第 $i$ 位为 $0$,表示模 $3$ 结果是 $2$。 + +我们用整数 $c$ 表示当前要读入的数,那么有以下真值表: +| $a_i$ | $b_i$ | $c_i$ | 新的 $a_i$ | 新的 $b_i$ | +| ----- | ----- | ----- | ---------- | ---------- | +| 0 | 0 | 0 | 0 | 0 | +| 0 | 0 | 1 | 0 | 1 | +| 0 | 1 | 0 | 0 | 1 | +| 0 | 1 | 1 | 1 | 0 | +| 1 | 0 | 0 | 1 | 0 | +| 1 | 0 | 1 | 0 | 0 | + +基于以上真值表,我们可以写出逻辑表达式: + +$$ +a_i = a_i' b_i c_i + a_i b_i' c_i' +$$ + +以及: + +$$ +b_i = a_i' b_i' c_i + a_i' b_i c_i' = a_i' (b_i \oplus c_i) +$$ + +最后结果是 $b$,因为 $b$ 的二进制位上为 $1$ 时表示这个数字出现了 $1$ 次。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是数组的长度。 + + + +```python +class Solution: + def singleNumber(self, nums: List[int]) -> int: + a = b = 0 + for c in nums: + aa = (~a & b & c) | (a & ~b & ~c) + bb = ~a & (b ^ c) + a, b = aa, bb + return b ``` +```java +class Solution { + public int singleNumber(int[] nums) { + int a = 0, b = 0; + for (int c : nums) { + int aa = (~a & b & c) | (a & ~b & ~c); + int bb = ~a & (b ^ c); + a = aa; + b = bb; + } + return b; + } +} +``` + +```cpp +class Solution { +public: + int singleNumber(vector& nums) { + int a = 0, b = 0; + for (int c : nums) { + int aa = (~a & b & c) | (a & ~b & ~c); + int bb = ~a & (b ^ c); + a = aa; + b = bb; + } + return b; + } +}; +``` + +```go +func singleNumber(nums []int) int { + a, b := 0, 0 + for _, c := range nums { + aa := (^a & b & c) | (a & ^b & ^c) + bb := ^a & (b ^ c) + a, b = aa, bb + } + return b +} +``` + +```ts +function singleNumber(nums: number[]): number { + let a = 0; + let b = 0; + for (const c of nums) { + const aa = (~a & b & c) | (a & ~b & ~c); + const bb = ~a & (b ^ c); + a = aa; + b = bb; + } + return b; +} +``` + +```rust +impl Solution { + pub fn single_number(nums: Vec) -> i32 { + let mut a = 0; + let mut b = 0; + + for c in nums { + let aa = (!a & b & c) | (a & !b & !c); + let bb = !a & (b ^ c); + a = aa; + b = bb; + } + + return b; + } +} ``` + + diff --git a/solution/0100-0199/0137.Single Number II/README_EN.md b/solution/0100-0199/0137.Single Number II/README_EN.md index 2d94ec1673113..d4cf18a43ff35 100644 --- a/solution/0100-0199/0137.Single Number II/README_EN.md +++ b/solution/0100-0199/0137.Single Number II/README_EN.md @@ -27,53 +27,14 @@ ## Solutions -**Solution 1: Bitwise Operation** +### Solution 1: Bitwise Operation We can enumerate each binary bit $i$, and for each binary bit, we calculate the sum of all numbers on that bit. If the sum of the numbers on that bit can be divided by 3, then the number that only appears once on that bit is 0, otherwise it is 1. The time complexity is $O(n \times \log M)$, where $n$ and $M$ are the length of the array and the range of elements in the array, respectively. The space complexity is $O(1)$. -**Solution 2: Digital Circuit** - -We can use a more efficient method that uses digital circuits to simulate the above bitwise operation. - -Each binary bit of an integer can only represent 2 states, 0 or 1. However, we need to represent the sum of the $i$-th bit of all integers traversed so far modulo 3. Therefore, we can use two integers $a$ and $b$ to represent it. There are three possible cases: - -1. The $i$-th bit of integer $a$ is 0 and the $i$-th bit of integer $b$ is 0, which means the modulo 3 result is 0; -2. The $i$-th bit of integer $a$ is 0 and the $i$-th bit of integer $b$ is 1, which means the modulo 3 result is 1; -3. The $i$-th bit of integer $a$ is 1 and the $i$-th bit of integer $b$ is 0, which means the modulo 3 result is 2. - -We use integer $c$ to represent the number to be read in, and the truth table is as follows: - -| $a_i$ | $b_i$ | $c_i$ | New $a_i$ | New $b_i$ | -| ----- | ----- | ----- | --------- | --------- | -| 0 | 0 | 0 | 0 | 0 | -| 0 | 0 | 1 | 0 | 1 | -| 0 | 1 | 0 | 0 | 1 | -| 0 | 1 | 1 | 1 | 0 | -| 1 | 0 | 0 | 1 | 0 | -| 1 | 0 | 1 | 0 | 0 | - -Based on the truth table, we can write the logical expression: - -$$ -a_i = a_i' b_i c_i + a_i b_i' c_i' -$$ - -and: - -$$ -b_i = a_i' b_i' c_i + a_i' b_i c_i' = a_i' (b_i \oplus c_i) -$$ - -The final result is $b$, because when the binary bit of $b$ is 1, it means that the number appears only once. - -The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def singleNumber(self, nums: List[int]) -> int: @@ -88,19 +49,6 @@ class Solution: return ans ``` -```python -class Solution: - def singleNumber(self, nums: List[int]) -> int: - a = b = 0 - for c in nums: - aa = (~a & b & c) | (a & ~b & ~c) - bb = ~a & (b ^ c) - a, b = aa, bb - return b -``` - -### **Java** - ```java class Solution { public int singleNumber(int[] nums) { @@ -118,52 +66,6 @@ class Solution { } ``` -```java -class Solution { - public int singleNumber(int[] nums) { - int a = 0, b = 0; - for (int c : nums) { - int aa = (~a & b & c) | (a & ~b & ~c); - int bb = ~a & (b ^ c); - a = aa; - b = bb; - } - return b; - } -} -``` - -### **Go** - -```go -func singleNumber(nums []int) int { - ans := int32(0) - for i := 0; i < 32; i++ { - cnt := int32(0) - for _, num := range nums { - cnt += int32(num) >> i & 1 - } - cnt %= 3 - ans |= cnt << i - } - return int(ans) -} -``` - -```go -func singleNumber(nums []int) int { - a, b := 0, 0 - for _, c := range nums { - aa := (^a & b & c) | (a & ^b & ^c) - bb := ^a & (b ^ c) - a, b = aa, bb - } - return b -} -``` - -### **C++** - ```cpp class Solution { public: @@ -182,24 +84,21 @@ public: }; ``` -```cpp -class Solution { -public: - int singleNumber(vector& nums) { - int a = 0, b = 0; - for (int c : nums) { - int aa = (~a & b & c) | (a & ~b & ~c); - int bb = ~a & (b ^ c); - a = aa; - b = bb; - } - return b; - } -}; +```go +func singleNumber(nums []int) int { + ans := int32(0) + for i := 0; i < 32; i++ { + cnt := int32(0) + for _, num := range nums { + cnt += int32(num) >> i & 1 + } + cnt %= 3 + ans |= cnt << i + } + return int(ans) +} ``` -### **TypeScript** - ```ts function singleNumber(nums: number[]): number { let ans = 0; @@ -211,22 +110,6 @@ function singleNumber(nums: number[]): number { } ``` -```ts -function singleNumber(nums: number[]): number { - let a = 0; - let b = 0; - for (const c of nums) { - const aa = (~a & b & c) | (a & ~b & ~c); - const bb = ~a & (b ^ c); - a = aa; - b = bb; - } - return b; -} -``` - -### **Rust** - ```rust impl Solution { pub fn single_number(nums: Vec) -> i32 { @@ -243,26 +126,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn single_number(nums: Vec) -> i32 { - let mut a = 0; - let mut b = 0; - - for c in nums { - let aa = (!a & b & c) | (a & !b & !c); - let bb = !a & (b ^ c); - a = aa; - b = bb; - } - - return b; - } -} -``` - -### **C** - ```c int singleNumber(int* nums, int numsSize) { int ans = 0; @@ -279,8 +142,6 @@ int singleNumber(int* nums, int numsSize) { } ``` -### **Swift** - ```swift class Solution { func singleNumber(_ nums: [Int]) -> Int { @@ -296,10 +157,133 @@ class Solution { } ``` -### **...** + + +### Solution 2: Digital Circuit + +We can use a more efficient method that uses digital circuits to simulate the above bitwise operation. + +Each binary bit of an integer can only represent 2 states, 0 or 1. However, we need to represent the sum of the $i$-th bit of all integers traversed so far modulo 3. Therefore, we can use two integers $a$ and $b$ to represent it. There are three possible cases: + +1. The $i$-th bit of integer $a$ is 0 and the $i$-th bit of integer $b$ is 0, which means the modulo 3 result is 0; +2. The $i$-th bit of integer $a$ is 0 and the $i$-th bit of integer $b$ is 1, which means the modulo 3 result is 1; +3. The $i$-th bit of integer $a$ is 1 and the $i$-th bit of integer $b$ is 0, which means the modulo 3 result is 2. + +We use integer $c$ to represent the number to be read in, and the truth table is as follows: + +| $a_i$ | $b_i$ | $c_i$ | New $a_i$ | New $b_i$ | +| ----- | ----- | ----- | --------- | --------- | +| 0 | 0 | 0 | 0 | 0 | +| 0 | 0 | 1 | 0 | 1 | +| 0 | 1 | 0 | 0 | 1 | +| 0 | 1 | 1 | 1 | 0 | +| 1 | 0 | 0 | 1 | 0 | +| 1 | 0 | 1 | 0 | 0 | + +Based on the truth table, we can write the logical expression: + +$$ +a_i = a_i' b_i c_i + a_i b_i' c_i' +$$ + +and: +$$ +b_i = a_i' b_i' c_i + a_i' b_i c_i' = a_i' (b_i \oplus c_i) +$$ + +The final result is $b$, because when the binary bit of $b$ is 1, it means that the number appears only once. + +The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$. + + + +```python +class Solution: + def singleNumber(self, nums: List[int]) -> int: + a = b = 0 + for c in nums: + aa = (~a & b & c) | (a & ~b & ~c) + bb = ~a & (b ^ c) + a, b = aa, bb + return b ``` +```java +class Solution { + public int singleNumber(int[] nums) { + int a = 0, b = 0; + for (int c : nums) { + int aa = (~a & b & c) | (a & ~b & ~c); + int bb = ~a & (b ^ c); + a = aa; + b = bb; + } + return b; + } +} +``` + +```cpp +class Solution { +public: + int singleNumber(vector& nums) { + int a = 0, b = 0; + for (int c : nums) { + int aa = (~a & b & c) | (a & ~b & ~c); + int bb = ~a & (b ^ c); + a = aa; + b = bb; + } + return b; + } +}; +``` + +```go +func singleNumber(nums []int) int { + a, b := 0, 0 + for _, c := range nums { + aa := (^a & b & c) | (a & ^b & ^c) + bb := ^a & (b ^ c) + a, b = aa, bb + } + return b +} +``` + +```ts +function singleNumber(nums: number[]): number { + let a = 0; + let b = 0; + for (const c of nums) { + const aa = (~a & b & c) | (a & ~b & ~c); + const bb = ~a & (b ^ c); + a = aa; + b = bb; + } + return b; +} +``` + +```rust +impl Solution { + pub fn single_number(nums: Vec) -> i32 { + let mut a = 0; + let mut b = 0; + + for c in nums { + let aa = (!a & b & c) | (a & !b & !c); + let bb = !a & (b ^ c); + a = aa; + b = bb; + } + + return b; + } +} ``` + + diff --git a/solution/0100-0199/0138.Copy List with Random Pointer/README.md b/solution/0100-0199/0138.Copy List with Random Pointer/README.md index 1831d8035fb65..e38161f75631a 100644 --- a/solution/0100-0199/0138.Copy List with Random Pointer/README.md +++ b/solution/0100-0199/0138.Copy List with Random Pointer/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 遍历链表,将链表中的每个节点都复制一份,然后将原节点和复制节点的对应关系存储在哈希表中,同时连接好复制节点的 $next$ 指针。 @@ -76,22 +74,8 @@ 时间复杂度为 $O(n)$,空间复杂度为 $O(n)$。其中 $n$ 为链表的长度。 -**方法二:拼接 + 拆分** - -遍历链表,将链表中的每个节点都复制一份,然后将复制节点插入到原节点的后面。 - -接下来再遍历链表,根据原节点的 $random$ 指针,将复制节点的 $random$ 指针连接好。 - -最后再遍历链表,将链表拆分成原链表和复制链表。 - -时间复杂度为 $O(n)$,空间复杂度为 $O(1)$。其中 $n$ 为链表的长度。 - -### **Python3** - - - ```python """ # Definition for a Node. @@ -122,47 +106,6 @@ class Solution: return dummy.next ``` -```python -""" -# Definition for a Node. -class Node: - def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): - self.val = int(x) - self.next = next - self.random = random -""" - - -class Solution: - def copyRandomList(self, head: "Node") -> "Node": - if head is None: - return None - cur = head - while cur: - node = Node(cur.val, cur.next) - cur.next = node - cur = node.next - - cur = head - while cur: - if cur.random: - cur.next.random = cur.random.next - cur = cur.next.next - - ans = head.next - cur = head - while cur: - nxt = cur.next - if nxt: - cur.next = nxt.next - cur = nxt - return ans -``` - -### **Java** - - - ```java /* // Definition for a Node. @@ -198,51 +141,6 @@ class Solution { } ``` -```java -/* -// Definition for a Node. -class Node { - int val; - Node next; - Node random; - - public Node(int val) { - this.val = val; - this.next = null; - this.random = null; - } -} -*/ -class Solution { - public Node copyRandomList(Node head) { - if (head == null) { - return null; - } - for (Node cur = head; cur != null;) { - Node node = new Node(cur.val, cur.next); - cur.next = node; - cur = node.next; - } - for (Node cur = head; cur != null; cur = cur.next.next) { - if (cur.random != null) { - cur.next.random = cur.random.next; - } - } - Node ans = head.next; - for (Node cur = head; cur != null;) { - Node nxt = cur.next; - if (nxt != null) { - cur.next = nxt.next; - } - cur = nxt; - } - return ans; - } -} -``` - -### **C++** - ```cpp /* // Definition for a Node. @@ -280,54 +178,6 @@ public: }; ``` -```cpp -/* -// Definition for a Node. -class Node { -public: - int val; - Node* next; - Node* random; - - Node(int _val) { - val = _val; - next = NULL; - random = NULL; - } -}; -*/ -class Solution { -public: - Node* copyRandomList(Node* head) { - if (!head) { - return nullptr; - } - for (Node* cur = head; cur;) { - Node* node = new Node(cur->val); - node->next = cur->next; - cur->next = node; - cur = node->next; - } - for (Node* cur = head; cur; cur = cur->next->next) { - if (cur->random) { - cur->next->random = cur->random->next; - } - } - Node* ans = head->next; - for (Node* cur = head; cur;) { - Node* nxt = cur->next; - if (nxt) { - cur->next = nxt->next; - } - cur = nxt; - } - return ans; - } -}; -``` - -### **Go** - ```go /** * Definition for a Node. @@ -356,43 +206,69 @@ func copyRandomList(head *Node) *Node { } ``` -```go +```ts /** - * Definition for a Node. - * type Node struct { - * Val int - * Next *Node - * Random *Node + * Definition for Node. + * class Node { + * val: number + * next: Node | null + * random: Node | null + * constructor(val?: number, next?: Node, random?: Node) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * this.random = (random===undefined ? null : random) + * } * } */ -func copyRandomList(head *Node) *Node { - if head == nil { - return nil - } - for cur := head; cur != nil; { - node := &Node{cur.Val, cur.Next, nil} - cur.Next = node - cur = node.Next - } - for cur := head; cur != nil; cur = cur.Next.Next { - if cur.Random != nil { - cur.Next.Random = cur.Random.Next - } - } - ans := head.Next - for cur := head; cur != nil; { - nxt := cur.Next - if nxt != nil { - cur.Next = nxt.Next - } - cur = nxt - } - return ans +function copyRandomList(head: Node | null): Node | null { + const map = new Map(); + let cur = head; + while (cur != null) { + map.set(cur, new Node(cur.val)); + cur = cur.next; + } + cur = head; + while (cur != null) { + map.get(cur).next = map.get(cur.next) ?? null; + map.get(cur).random = map.get(cur.random) ?? null; + cur = cur.next; + } + return map.get(head); } ``` -### **C#** +```js +/** + * // Definition for a Node. + * function Node(val, next, random) { + * this.val = val; + * this.next = next; + * this.random = random; + * }; + */ + +/** + * @param {Node} head + * @return {Node} + */ +var copyRandomList = function (head) { + const d = new Map(); + const dummy = new Node(0); + let tail = dummy; + for (let cur = head; cur; cur = cur.next) { + tail.next = new Node(cur.val); + tail = tail.next; + d.set(cur, tail); + } + tail = dummy.next; + for (let cur = head; cur; cur = cur.next) { + tail.random = d.get(cur.random); + tail = tail.next; + } + return dummy.next; +}; +``` ```cs /* @@ -430,28 +306,78 @@ public class Solution { } ``` -```cs + + +### 方法二:拼接 + 拆分 + +遍历链表,将链表中的每个节点都复制一份,然后将复制节点插入到原节点的后面。 + +接下来再遍历链表,根据原节点的 $random$ 指针,将复制节点的 $random$ 指针连接好。 + +最后再遍历链表,将链表拆分成原链表和复制链表。 + +时间复杂度为 $O(n)$,空间复杂度为 $O(1)$。其中 $n$ 为链表的长度。 + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): + self.val = int(x) + self.next = next + self.random = random +""" + + +class Solution: + def copyRandomList(self, head: "Node") -> "Node": + if head is None: + return None + cur = head + while cur: + node = Node(cur.val, cur.next) + cur.next = node + cur = node.next + + cur = head + while cur: + if cur.random: + cur.next.random = cur.random.next + cur = cur.next.next + + ans = head.next + cur = head + while cur: + nxt = cur.next + if nxt: + cur.next = nxt.next + cur = nxt + return ans +``` + +```java /* // Definition for a Node. -public class Node { - public int val; - public Node next; - public Node random; +class Node { + int val; + Node next; + Node random; - public Node(int _val) { - val = _val; - next = null; - random = null; + public Node(int val) { + this.val = val; + this.next = null; + this.random = null; } } */ - -public class Solution { - public Node CopyRandomList(Node head) { +class Solution { + public Node copyRandomList(Node head) { if (head == null) { return null; } - for (Node cur = head; cur != null; ) { + for (Node cur = head; cur != null;) { Node node = new Node(cur.val, cur.next); cur.next = node; cur = node.next; @@ -462,7 +388,7 @@ public class Solution { } } Node ans = head.next; - for (Node cur = head; cur != null; ) { + for (Node cur = head; cur != null;) { Node nxt = cur.next; if (nxt != null) { cur.next = nxt.next; @@ -474,40 +400,88 @@ public class Solution { } ``` -### **JavaScript** - -```js -/** - * // Definition for a Node. - * function Node(val, next, random) { - * this.val = val; - * this.next = next; - * this.random = random; - * }; - */ +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + Node* random; -/** - * @param {Node} head - * @return {Node} - */ -var copyRandomList = function (head) { - const d = new Map(); - const dummy = new Node(0); - let tail = dummy; - for (let cur = head; cur; cur = cur.next) { - tail.next = new Node(cur.val); - tail = tail.next; - d.set(cur, tail); + Node(int _val) { + val = _val; + next = NULL; + random = NULL; } - tail = dummy.next; - for (let cur = head; cur; cur = cur.next) { - tail.random = d.get(cur.random); - tail = tail.next; +}; +*/ +class Solution { +public: + Node* copyRandomList(Node* head) { + if (!head) { + return nullptr; + } + for (Node* cur = head; cur;) { + Node* node = new Node(cur->val); + node->next = cur->next; + cur->next = node; + cur = node->next; + } + for (Node* cur = head; cur; cur = cur->next->next) { + if (cur->random) { + cur->next->random = cur->random->next; + } + } + Node* ans = head->next; + for (Node* cur = head; cur;) { + Node* nxt = cur->next; + if (nxt) { + cur->next = nxt->next; + } + cur = nxt; + } + return ans; } - return dummy.next; }; ``` +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Next *Node + * Random *Node + * } + */ + +func copyRandomList(head *Node) *Node { + if head == nil { + return nil + } + for cur := head; cur != nil; { + node := &Node{cur.Val, cur.Next, nil} + cur.Next = node + cur = node.Next + } + for cur := head; cur != nil; cur = cur.Next.Next { + if cur.Random != nil { + cur.Next.Random = cur.Random.Next + } + } + ans := head.Next + for cur := head; cur != nil; { + nxt := cur.Next + if nxt != nil { + cur.Next = nxt.Next + } + cur = nxt + } + return ans +} +``` + ```js /** * // Definition for a Node. @@ -548,44 +522,50 @@ var copyRandomList = function (head) { }; ``` -### **TypeScript** - -```ts -/** - * Definition for Node. - * class Node { - * val: number - * next: Node | null - * random: Node | null - * constructor(val?: number, next?: Node, random?: Node) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * this.random = (random===undefined ? null : random) - * } - * } - */ +```cs +/* +// Definition for a Node. +public class Node { + public int val; + public Node next; + public Node random; -function copyRandomList(head: Node | null): Node | null { - const map = new Map(); - let cur = head; - while (cur != null) { - map.set(cur, new Node(cur.val)); - cur = cur.next; - } - cur = head; - while (cur != null) { - map.get(cur).next = map.get(cur.next) ?? null; - map.get(cur).random = map.get(cur.random) ?? null; - cur = cur.next; + public Node(int _val) { + val = _val; + next = null; + random = null; } - return map.get(head); } -``` - -### **...** - -``` +*/ +public class Solution { + public Node CopyRandomList(Node head) { + if (head == null) { + return null; + } + for (Node cur = head; cur != null; ) { + Node node = new Node(cur.val, cur.next); + cur.next = node; + cur = node.next; + } + for (Node cur = head; cur != null; cur = cur.next.next) { + if (cur.random != null) { + cur.next.random = cur.random.next; + } + } + Node ans = head.next; + for (Node cur = head; cur != null; ) { + Node nxt = cur.next; + if (nxt != null) { + cur.next = nxt.next; + } + cur = nxt; + } + return ans; + } +} ``` + + diff --git a/solution/0100-0199/0138.Copy List with Random Pointer/README_EN.md b/solution/0100-0199/0138.Copy List with Random Pointer/README_EN.md index b4386efaf920c..d489d6e906537 100644 --- a/solution/0100-0199/0138.Copy List with Random Pointer/README_EN.md +++ b/solution/0100-0199/0138.Copy List with Random Pointer/README_EN.md @@ -56,9 +56,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -90,45 +90,6 @@ class Solution: return dummy.next ``` -```python -""" -# Definition for a Node. -class Node: - def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): - self.val = int(x) - self.next = next - self.random = random -""" - - -class Solution: - def copyRandomList(self, head: "Node") -> "Node": - if head is None: - return None - cur = head - while cur: - node = Node(cur.val, cur.next) - cur.next = node - cur = node.next - - cur = head - while cur: - if cur.random: - cur.next.random = cur.random.next - cur = cur.next.next - - ans = head.next - cur = head - while cur: - nxt = cur.next - if nxt: - cur.next = nxt.next - cur = nxt - return ans -``` - -### **Java** - ```java /* // Definition for a Node. @@ -164,51 +125,6 @@ class Solution { } ``` -```java -/* -// Definition for a Node. -class Node { - int val; - Node next; - Node random; - - public Node(int val) { - this.val = val; - this.next = null; - this.random = null; - } -} -*/ -class Solution { - public Node copyRandomList(Node head) { - if (head == null) { - return null; - } - for (Node cur = head; cur != null;) { - Node node = new Node(cur.val, cur.next); - cur.next = node; - cur = node.next; - } - for (Node cur = head; cur != null; cur = cur.next.next) { - if (cur.random != null) { - cur.next.random = cur.random.next; - } - } - Node ans = head.next; - for (Node cur = head; cur != null;) { - Node nxt = cur.next; - if (nxt != null) { - cur.next = nxt.next; - } - cur = nxt; - } - return ans; - } -} -``` - -### **C++** - ```cpp /* // Definition for a Node. @@ -246,54 +162,6 @@ public: }; ``` -```cpp -/* -// Definition for a Node. -class Node { -public: - int val; - Node* next; - Node* random; - - Node(int _val) { - val = _val; - next = NULL; - random = NULL; - } -}; -*/ -class Solution { -public: - Node* copyRandomList(Node* head) { - if (!head) { - return nullptr; - } - for (Node* cur = head; cur;) { - Node* node = new Node(cur->val); - node->next = cur->next; - cur->next = node; - cur = node->next; - } - for (Node* cur = head; cur; cur = cur->next->next) { - if (cur->random) { - cur->next->random = cur->random->next; - } - } - Node* ans = head->next; - for (Node* cur = head; cur;) { - Node* nxt = cur->next; - if (nxt) { - cur->next = nxt->next; - } - cur = nxt; - } - return ans; - } -}; -``` - -### **Go** - ```go /** * Definition for a Node. @@ -322,43 +190,69 @@ func copyRandomList(head *Node) *Node { } ``` -```go +```ts /** - * Definition for a Node. - * type Node struct { - * Val int - * Next *Node - * Random *Node + * Definition for Node. + * class Node { + * val: number + * next: Node | null + * random: Node | null + * constructor(val?: number, next?: Node, random?: Node) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * this.random = (random===undefined ? null : random) + * } * } */ -func copyRandomList(head *Node) *Node { - if head == nil { - return nil - } - for cur := head; cur != nil; { - node := &Node{cur.Val, cur.Next, nil} - cur.Next = node - cur = node.Next - } - for cur := head; cur != nil; cur = cur.Next.Next { - if cur.Random != nil { - cur.Next.Random = cur.Random.Next - } - } - ans := head.Next - for cur := head; cur != nil; { - nxt := cur.Next - if nxt != nil { - cur.Next = nxt.Next - } - cur = nxt - } - return ans +function copyRandomList(head: Node | null): Node | null { + const map = new Map(); + let cur = head; + while (cur != null) { + map.set(cur, new Node(cur.val)); + cur = cur.next; + } + cur = head; + while (cur != null) { + map.get(cur).next = map.get(cur.next) ?? null; + map.get(cur).random = map.get(cur.random) ?? null; + cur = cur.next; + } + return map.get(head); } ``` -### **C#** +```js +/** + * // Definition for a Node. + * function Node(val, next, random) { + * this.val = val; + * this.next = next; + * this.random = random; + * }; + */ + +/** + * @param {Node} head + * @return {Node} + */ +var copyRandomList = function (head) { + const d = new Map(); + const dummy = new Node(0); + let tail = dummy; + for (let cur = head; cur; cur = cur.next) { + tail.next = new Node(cur.val); + tail = tail.next; + d.set(cur, tail); + } + tail = dummy.next; + for (let cur = head; cur; cur = cur.next) { + tail.random = d.get(cur.random); + tail = tail.next; + } + return dummy.next; +}; +``` ```cs /* @@ -396,28 +290,70 @@ public class Solution { } ``` -```cs + + +### Solution 2 + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): + self.val = int(x) + self.next = next + self.random = random +""" + + +class Solution: + def copyRandomList(self, head: "Node") -> "Node": + if head is None: + return None + cur = head + while cur: + node = Node(cur.val, cur.next) + cur.next = node + cur = node.next + + cur = head + while cur: + if cur.random: + cur.next.random = cur.random.next + cur = cur.next.next + + ans = head.next + cur = head + while cur: + nxt = cur.next + if nxt: + cur.next = nxt.next + cur = nxt + return ans +``` + +```java /* // Definition for a Node. -public class Node { - public int val; - public Node next; - public Node random; +class Node { + int val; + Node next; + Node random; - public Node(int _val) { - val = _val; - next = null; - random = null; + public Node(int val) { + this.val = val; + this.next = null; + this.random = null; } } */ - -public class Solution { - public Node CopyRandomList(Node head) { +class Solution { + public Node copyRandomList(Node head) { if (head == null) { return null; } - for (Node cur = head; cur != null; ) { + for (Node cur = head; cur != null;) { Node node = new Node(cur.val, cur.next); cur.next = node; cur = node.next; @@ -428,7 +364,7 @@ public class Solution { } } Node ans = head.next; - for (Node cur = head; cur != null; ) { + for (Node cur = head; cur != null;) { Node nxt = cur.next; if (nxt != null) { cur.next = nxt.next; @@ -440,40 +376,88 @@ public class Solution { } ``` -### **JavaScript** - -```js -/** - * // Definition for a Node. - * function Node(val, next, random) { - * this.val = val; - * this.next = next; - * this.random = random; - * }; - */ +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + Node* random; -/** - * @param {Node} head - * @return {Node} - */ -var copyRandomList = function (head) { - const d = new Map(); - const dummy = new Node(0); - let tail = dummy; - for (let cur = head; cur; cur = cur.next) { - tail.next = new Node(cur.val); - tail = tail.next; - d.set(cur, tail); + Node(int _val) { + val = _val; + next = NULL; + random = NULL; } - tail = dummy.next; - for (let cur = head; cur; cur = cur.next) { - tail.random = d.get(cur.random); - tail = tail.next; +}; +*/ +class Solution { +public: + Node* copyRandomList(Node* head) { + if (!head) { + return nullptr; + } + for (Node* cur = head; cur;) { + Node* node = new Node(cur->val); + node->next = cur->next; + cur->next = node; + cur = node->next; + } + for (Node* cur = head; cur; cur = cur->next->next) { + if (cur->random) { + cur->next->random = cur->random->next; + } + } + Node* ans = head->next; + for (Node* cur = head; cur;) { + Node* nxt = cur->next; + if (nxt) { + cur->next = nxt->next; + } + cur = nxt; + } + return ans; } - return dummy.next; }; ``` +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Next *Node + * Random *Node + * } + */ + +func copyRandomList(head *Node) *Node { + if head == nil { + return nil + } + for cur := head; cur != nil; { + node := &Node{cur.Val, cur.Next, nil} + cur.Next = node + cur = node.Next + } + for cur := head; cur != nil; cur = cur.Next.Next { + if cur.Random != nil { + cur.Next.Random = cur.Random.Next + } + } + ans := head.Next + for cur := head; cur != nil; { + nxt := cur.Next + if nxt != nil { + cur.Next = nxt.Next + } + cur = nxt + } + return ans +} +``` + ```js /** * // Definition for a Node. @@ -514,44 +498,50 @@ var copyRandomList = function (head) { }; ``` -### **TypeScript** - -```ts -/** - * Definition for Node. - * class Node { - * val: number - * next: Node | null - * random: Node | null - * constructor(val?: number, next?: Node, random?: Node) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * this.random = (random===undefined ? null : random) - * } - * } - */ +```cs +/* +// Definition for a Node. +public class Node { + public int val; + public Node next; + public Node random; -function copyRandomList(head: Node | null): Node | null { - const map = new Map(); - let cur = head; - while (cur != null) { - map.set(cur, new Node(cur.val)); - cur = cur.next; - } - cur = head; - while (cur != null) { - map.get(cur).next = map.get(cur.next) ?? null; - map.get(cur).random = map.get(cur.random) ?? null; - cur = cur.next; + public Node(int _val) { + val = _val; + next = null; + random = null; } - return map.get(head); } -``` - -### **...** - -``` +*/ +public class Solution { + public Node CopyRandomList(Node head) { + if (head == null) { + return null; + } + for (Node cur = head; cur != null; ) { + Node node = new Node(cur.val, cur.next); + cur.next = node; + cur = node.next; + } + for (Node cur = head; cur != null; cur = cur.next.next) { + if (cur.random != null) { + cur.next.random = cur.random.next; + } + } + Node ans = head.next; + for (Node cur = head; cur != null; ) { + Node nxt = cur.next; + if (nxt != null) { + cur.next = nxt.next; + } + cur = nxt; + } + return ans; + } +} ``` + + diff --git a/solution/0100-0199/0139.Word Break/README.md b/solution/0100-0199/0139.Word Break/README.md index 7266809652184..a31e9b0407a0a 100644 --- a/solution/0100-0199/0139.Word Break/README.md +++ b/solution/0100-0199/0139.Word Break/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:哈希表 + 动态规划** +### 方法一:哈希表 + 动态规划 我们定义 $f[i]$ 表示字符串 $s$ 的前 $i$ 个字符能否拆分成 $wordDict$ 中的单词,初始时 $f[0]=true$,其余为 $false$。答案为 $f[n]$。 @@ -60,22 +58,8 @@ 时间复杂度 $O(n^3)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度。 -**方法二:前缀树 + 动态规划** - -我们先将 $wordDict$ 中的单词存入前缀树中,然后使用动态规划求解。 - -我们定义 $f[i]$ 表示从字符串 $s$ 的第 $i$ 个字符开始往后拆分,能否拆分成 $wordDict$ 中的单词,初始时 $f[n]=true$,其余为 $false$。答案为 $f[0]$。 - -接下来,我们从大到小枚举 $i$,对于每个 $i$,我们从 $i$ 开始往后拆分,如果 $s[i:j]$ 在前缀树中,且 $f[j+1]=true$,则 $f[i]=true$。 - -时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度。 - -### **Python3** - - - ```python class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: @@ -87,6 +71,137 @@ class Solution: return f[n] ``` +```java +class Solution { + public boolean wordBreak(String s, List wordDict) { + Set words = new HashSet<>(wordDict); + int n = s.length(); + boolean[] f = new boolean[n + 1]; + f[0] = true; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + if (f[j] && words.contains(s.substring(j, i))) { + f[i] = true; + break; + } + } + } + return f[n]; + } +} +``` + +```cpp +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + unordered_set words(wordDict.begin(), wordDict.end()); + int n = s.size(); + bool f[n + 1]; + memset(f, false, sizeof(f)); + f[0] = true; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + if (f[j] && words.count(s.substr(j, i - j))) { + f[i] = true; + break; + } + } + } + return f[n]; + } +}; +``` + +```go +func wordBreak(s string, wordDict []string) bool { + words := map[string]bool{} + for _, w := range wordDict { + words[w] = true + } + n := len(s) + f := make([]bool, n+1) + f[0] = true + for i := 1; i <= n; i++ { + for j := 0; j < i; j++ { + if f[j] && words[s[j:i]] { + f[i] = true + break + } + } + } + return f[n] +} +``` + +```ts +function wordBreak(s: string, wordDict: string[]): boolean { + const words = new Set(wordDict); + const n = s.length; + const f: boolean[] = new Array(n + 1).fill(false); + f[0] = true; + for (let i = 1; i <= n; ++i) { + for (let j = 0; j < i; ++j) { + if (f[j] && words.has(s.substring(j, i))) { + f[i] = true; + break; + } + } + } + return f[n]; +} +``` + +```rust +impl Solution { + pub fn word_break(s: String, word_dict: Vec) -> bool { + let words: std::collections::HashSet = word_dict.into_iter().collect(); + let mut f = vec![false; s.len() + 1]; + f[0] = true; + for i in 1..=s.len() { + for j in 0..i { + f[i] |= f[j] && words.contains(&s[j..i]); + } + } + f[s.len()] + } +} +``` + +```cs +public class Solution { + public bool WordBreak(string s, IList wordDict) { + var words = new HashSet(wordDict); + int n = s.Length; + var f = new bool[n + 1]; + f[0] = true; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + if (f[j] && words.Contains(s.Substring(j, i - j))) { + f[i] = true; + break; + } + } + } + return f[n]; + } +} +``` + + + +### 方法二:前缀树 + 动态规划 + +我们先将 $wordDict$ 中的单词存入前缀树中,然后使用动态规划求解。 + +我们定义 $f[i]$ 表示从字符串 $s$ 的第 $i$ 个字符开始往后拆分,能否拆分成 $wordDict$ 中的单词,初始时 $f[n]=true$,其余为 $false$。答案为 $f[0]$。 + +接下来,我们从大到小枚举 $i$,对于每个 $i$,我们从 $i$ 开始往后拆分,如果 $s[i:j]$ 在前缀树中,且 $f[j+1]=true$,则 $f[i]=true$。 + +时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度。 + + + ```python class Trie: def __init__(self): @@ -124,30 +239,6 @@ class Solution: return f[0] ``` -### **Java** - - - -```java -class Solution { - public boolean wordBreak(String s, List wordDict) { - Set words = new HashSet<>(wordDict); - int n = s.length(); - boolean[] f = new boolean[n + 1]; - f[0] = true; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j < i; ++j) { - if (f[j] && words.contains(s.substring(j, i))) { - f[i] = true; - break; - } - } - } - return f[n]; - } -} -``` - ```java class Solution { public boolean wordBreak(String s, List wordDict) { @@ -194,30 +285,6 @@ class Trie { } ``` -### **C++** - -```cpp -class Solution { -public: - bool wordBreak(string s, vector& wordDict) { - unordered_set words(wordDict.begin(), wordDict.end()); - int n = s.size(); - bool f[n + 1]; - memset(f, false, sizeof(f)); - f[0] = true; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j < i; ++j) { - if (f[j] && words.count(s.substr(j, i - j))) { - f[i] = true; - break; - } - } - } - return f[n]; - } -}; -``` - ```cpp class Trie { public: @@ -267,29 +334,6 @@ public: }; ``` -### **Go** - -```go -func wordBreak(s string, wordDict []string) bool { - words := map[string]bool{} - for _, w := range wordDict { - words[w] = true - } - n := len(s) - f := make([]bool, n+1) - f[0] = true - for i := 1; i <= n; i++ { - for j := 0; j < i; j++ { - if f[j] && words[s[j:i]] { - f[i] = true - break - } - } - } - return f[n] -} -``` - ```go type trie struct { children [26]*trie @@ -338,99 +382,6 @@ func wordBreak(s string, wordDict []string) bool { } ``` -### **C#** - -```cs -public class Solution { - public bool WordBreak(string s, IList wordDict) { - var words = new HashSet(wordDict); - int n = s.Length; - var f = new bool[n + 1]; - f[0] = true; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j < i; ++j) { - if (f[j] && words.Contains(s.Substring(j, i - j))) { - f[i] = true; - break; - } - } - } - return f[n]; - } -} -``` - -```cs -public class Solution { - public bool WordBreak(string s, IList wordDict) { - Trie trie = new Trie(); - foreach (string w in wordDict) { - trie.Insert(w); - } - int n = s.Length; - bool[] f = new bool[n + 1]; - f[n] = true; - for (int i = n - 1; i >= 0; --i) { - Trie node = trie; - for (int j = i; j < n; ++j) { - int k = s[j] - 'a'; - if (node.Children[k] == null) { - break; - } - node = node.Children[k]; - if (node.IsEnd && f[j + 1]) { - f[i] = true; - break; - } - } - } - return f[0]; - } -} - -class Trie { - public Trie[] Children { get; set; } - public bool IsEnd { get; set; } - - public Trie() { - Children = new Trie[26]; - IsEnd = false; - } - - public void Insert(string word) { - Trie node = this; - foreach (char c in word) { - int i = c - 'a'; - if (node.Children[i] == null) { - node.Children[i] = new Trie(); - } - node = node.Children[i]; - } - node.IsEnd = true; - } -} -``` - -### **TypeScript** - -```ts -function wordBreak(s: string, wordDict: string[]): boolean { - const words = new Set(wordDict); - const n = s.length; - const f: boolean[] = new Array(n + 1).fill(false); - f[0] = true; - for (let i = 1; i <= n; ++i) { - for (let j = 0; j < i; ++j) { - if (f[j] && words.has(s.substring(j, i))) { - f[i] = true; - break; - } - } - } - return f[n]; -} -``` - ```ts function wordBreak(s: string, wordDict: string[]): boolean { const trie = new Trie(); @@ -480,28 +431,57 @@ class Trie { } ``` -### **Rust** - -```rust -impl Solution { - pub fn word_break(s: String, word_dict: Vec) -> bool { - let words: std::collections::HashSet = word_dict.into_iter().collect(); - let mut f = vec![false; s.len() + 1]; - f[0] = true; - for i in 1..=s.len() { - for j in 0..i { - f[i] |= f[j] && words.contains(&s[j..i]); +```cs +public class Solution { + public bool WordBreak(string s, IList wordDict) { + Trie trie = new Trie(); + foreach (string w in wordDict) { + trie.Insert(w); + } + int n = s.Length; + bool[] f = new bool[n + 1]; + f[n] = true; + for (int i = n - 1; i >= 0; --i) { + Trie node = trie; + for (int j = i; j < n; ++j) { + int k = s[j] - 'a'; + if (node.Children[k] == null) { + break; + } + node = node.Children[k]; + if (node.IsEnd && f[j + 1]) { + f[i] = true; + break; + } } } - f[s.len()] + return f[0]; } } -``` -### **...** +class Trie { + public Trie[] Children { get; set; } + public bool IsEnd { get; set; } -``` + public Trie() { + Children = new Trie[26]; + IsEnd = false; + } + public void Insert(string word) { + Trie node = this; + foreach (char c in word) { + int i = c - 'a'; + if (node.Children[i] == null) { + node.Children[i] = new Trie(); + } + node = node.Children[i]; + } + node.IsEnd = true; + } +} ``` + + diff --git a/solution/0100-0199/0139.Word Break/README_EN.md b/solution/0100-0199/0139.Word Break/README_EN.md index b17348dcf36ab..881af1523ef15 100644 --- a/solution/0100-0199/0139.Word Break/README_EN.md +++ b/solution/0100-0199/0139.Word Break/README_EN.md @@ -46,12 +46,10 @@ Note that you are allowed to reuse a dictionary word. ## Solutions -Dynamic Programming. +### Solution 1 -### **Python3** - ```python class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: @@ -63,6 +61,129 @@ class Solution: return f[n] ``` +```java +class Solution { + public boolean wordBreak(String s, List wordDict) { + Set words = new HashSet<>(wordDict); + int n = s.length(); + boolean[] f = new boolean[n + 1]; + f[0] = true; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + if (f[j] && words.contains(s.substring(j, i))) { + f[i] = true; + break; + } + } + } + return f[n]; + } +} +``` + +```cpp +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + unordered_set words(wordDict.begin(), wordDict.end()); + int n = s.size(); + bool f[n + 1]; + memset(f, false, sizeof(f)); + f[0] = true; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + if (f[j] && words.count(s.substr(j, i - j))) { + f[i] = true; + break; + } + } + } + return f[n]; + } +}; +``` + +```go +func wordBreak(s string, wordDict []string) bool { + words := map[string]bool{} + for _, w := range wordDict { + words[w] = true + } + n := len(s) + f := make([]bool, n+1) + f[0] = true + for i := 1; i <= n; i++ { + for j := 0; j < i; j++ { + if f[j] && words[s[j:i]] { + f[i] = true + break + } + } + } + return f[n] +} +``` + +```ts +function wordBreak(s: string, wordDict: string[]): boolean { + const words = new Set(wordDict); + const n = s.length; + const f: boolean[] = new Array(n + 1).fill(false); + f[0] = true; + for (let i = 1; i <= n; ++i) { + for (let j = 0; j < i; ++j) { + if (f[j] && words.has(s.substring(j, i))) { + f[i] = true; + break; + } + } + } + return f[n]; +} +``` + +```rust +impl Solution { + pub fn word_break(s: String, word_dict: Vec) -> bool { + let words: std::collections::HashSet = word_dict.into_iter().collect(); + let mut f = vec![false; s.len() + 1]; + f[0] = true; + for i in 1..=s.len() { + for j in 0..i { + f[i] |= f[j] && words.contains(&s[j..i]); + } + } + f[s.len()] + } +} +``` + +```cs +public class Solution { + public bool WordBreak(string s, IList wordDict) { + var words = new HashSet(wordDict); + int n = s.Length; + var f = new bool[n + 1]; + f[0] = true; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < i; ++j) { + if (f[j] && words.Contains(s.Substring(j, i - j))) { + f[i] = true; + break; + } + } + } + return f[n]; + } +} +``` + + + +### Solution 2 + + + ```python class Trie: def __init__(self): @@ -100,28 +221,6 @@ class Solution: return f[0] ``` -### **Java** - -```java -class Solution { - public boolean wordBreak(String s, List wordDict) { - Set words = new HashSet<>(wordDict); - int n = s.length(); - boolean[] f = new boolean[n + 1]; - f[0] = true; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j < i; ++j) { - if (f[j] && words.contains(s.substring(j, i))) { - f[i] = true; - break; - } - } - } - return f[n]; - } -} -``` - ```java class Solution { public boolean wordBreak(String s, List wordDict) { @@ -168,30 +267,6 @@ class Trie { } ``` -### **C++** - -```cpp -class Solution { -public: - bool wordBreak(string s, vector& wordDict) { - unordered_set words(wordDict.begin(), wordDict.end()); - int n = s.size(); - bool f[n + 1]; - memset(f, false, sizeof(f)); - f[0] = true; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j < i; ++j) { - if (f[j] && words.count(s.substr(j, i - j))) { - f[i] = true; - break; - } - } - } - return f[n]; - } -}; -``` - ```cpp class Trie { public: @@ -241,29 +316,6 @@ public: }; ``` -### **Go** - -```go -func wordBreak(s string, wordDict []string) bool { - words := map[string]bool{} - for _, w := range wordDict { - words[w] = true - } - n := len(s) - f := make([]bool, n+1) - f[0] = true - for i := 1; i <= n; i++ { - for j := 0; j < i; j++ { - if f[j] && words[s[j:i]] { - f[i] = true - break - } - } - } - return f[n] -} -``` - ```go type trie struct { children [26]*trie @@ -312,99 +364,6 @@ func wordBreak(s string, wordDict []string) bool { } ``` -### **C#** - -```cs -public class Solution { - public bool WordBreak(string s, IList wordDict) { - var words = new HashSet(wordDict); - int n = s.Length; - var f = new bool[n + 1]; - f[0] = true; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j < i; ++j) { - if (f[j] && words.Contains(s.Substring(j, i - j))) { - f[i] = true; - break; - } - } - } - return f[n]; - } -} -``` - -```cs -public class Solution { - public bool WordBreak(string s, IList wordDict) { - Trie trie = new Trie(); - foreach (string w in wordDict) { - trie.Insert(w); - } - int n = s.Length; - bool[] f = new bool[n + 1]; - f[n] = true; - for (int i = n - 1; i >= 0; --i) { - Trie node = trie; - for (int j = i; j < n; ++j) { - int k = s[j] - 'a'; - if (node.Children[k] == null) { - break; - } - node = node.Children[k]; - if (node.IsEnd && f[j + 1]) { - f[i] = true; - break; - } - } - } - return f[0]; - } -} - -class Trie { - public Trie[] Children { get; set; } - public bool IsEnd { get; set; } - - public Trie() { - Children = new Trie[26]; - IsEnd = false; - } - - public void Insert(string word) { - Trie node = this; - foreach (char c in word) { - int i = c - 'a'; - if (node.Children[i] == null) { - node.Children[i] = new Trie(); - } - node = node.Children[i]; - } - node.IsEnd = true; - } -} -``` - -### **TypeScript** - -```ts -function wordBreak(s: string, wordDict: string[]): boolean { - const words = new Set(wordDict); - const n = s.length; - const f: boolean[] = new Array(n + 1).fill(false); - f[0] = true; - for (let i = 1; i <= n; ++i) { - for (let j = 0; j < i; ++j) { - if (f[j] && words.has(s.substring(j, i))) { - f[i] = true; - break; - } - } - } - return f[n]; -} -``` - ```ts function wordBreak(s: string, wordDict: string[]): boolean { const trie = new Trie(); @@ -454,28 +413,57 @@ class Trie { } ``` -### **Rust** - -```rust -impl Solution { - pub fn word_break(s: String, word_dict: Vec) -> bool { - let words: std::collections::HashSet = word_dict.into_iter().collect(); - let mut f = vec![false; s.len() + 1]; - f[0] = true; - for i in 1..=s.len() { - for j in 0..i { - f[i] |= f[j] && words.contains(&s[j..i]); +```cs +public class Solution { + public bool WordBreak(string s, IList wordDict) { + Trie trie = new Trie(); + foreach (string w in wordDict) { + trie.Insert(w); + } + int n = s.Length; + bool[] f = new bool[n + 1]; + f[n] = true; + for (int i = n - 1; i >= 0; --i) { + Trie node = trie; + for (int j = i; j < n; ++j) { + int k = s[j] - 'a'; + if (node.Children[k] == null) { + break; + } + node = node.Children[k]; + if (node.IsEnd && f[j + 1]) { + f[i] = true; + break; + } } } - f[s.len()] + return f[0]; } } -``` -### **...** +class Trie { + public Trie[] Children { get; set; } + public bool IsEnd { get; set; } -``` + public Trie() { + Children = new Trie[26]; + IsEnd = false; + } + public void Insert(string word) { + Trie node = this; + foreach (char c in word) { + int i = c - 'a'; + if (node.Children[i] == null) { + node.Children[i] = new Trie(); + } + node = node.Children[i]; + } + node.IsEnd = true; + } +} ``` + + diff --git a/solution/0100-0199/0140.Word Break II/README.md b/solution/0100-0199/0140.Word Break II/README.md index 949d458adfc7d..29f65cb038916 100644 --- a/solution/0100-0199/0140.Word Break II/README.md +++ b/solution/0100-0199/0140.Word Break II/README.md @@ -50,16 +50,10 @@ ## 解法 - - -**方法一:前缀树 + DFS** +### 方法一:前缀树 + DFS -### **Python3** - - - ```python class Trie: def __init__(self): @@ -104,10 +98,6 @@ class Solution: return [' '.join(v) for v in ans] ``` -### **Java** - - - ```java class Trie { Trie[] children = new Trie[26]; @@ -168,8 +158,6 @@ class Solution { } ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -233,10 +221,86 @@ func wordBreak(s string, wordDict []string) []string { } ``` -### **...** +```cs +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; -``` +class Node +{ + public int Index1 { get; set; } + public int Index2 { get; set; } +} + +public class Solution { + public IList WordBreak(string s, IList wordDict) { + var paths = new List>[s.Length + 1]; + paths[s.Length] = new List> { Tuple.Create(-1, (string)null) }; + var wordDictGroup = wordDict.GroupBy(word => word.Length); + for (var i = s.Length - 1; i >= 0; --i) + { + paths[i] = new List>(); + foreach (var wordGroup in wordDictGroup) + { + var wordLength = wordGroup.Key; + if (i + wordLength <= s.Length && paths[i + wordLength].Count > 0) + { + foreach (var word in wordGroup) + { + if (s.Substring(i, wordLength) == word) + { + paths[i].Add(Tuple.Create(i + wordLength, word)); + } + } + } + } + } + return GenerateResults(paths); + } + + private IList GenerateResults(List>[] paths) + { + var results = new List(); + var sb = new StringBuilder(); + var stack = new Stack(); + stack.Push(new Node()); + while (stack.Count > 0) + { + var node = stack.Peek(); + if (node.Index1 == paths.Length - 1 || node.Index2 == paths[node.Index1].Count) + { + if (node.Index1 == paths.Length - 1) + { + results.Add(sb.ToString()); + } + stack.Pop(); + if (stack.Count > 0) + { + var parent = stack.Peek(); + var length = paths[parent.Index1][parent.Index2 - 1].Item2.Length; + if (length < sb.Length) ++length; + sb.Remove(sb.Length - length, length); + } + } + else + { + var newNode = new Node { Index1 = paths[node.Index1][node.Index2].Item1, Index2 = 0 }; + if (sb.Length != 0) + { + sb.Append(' '); + } + sb.Append(paths[node.Index1][node.Index2].Item2); + stack.Push(newNode); + ++node.Index2; + } + } + return results; + } +} ``` + + diff --git a/solution/0100-0199/0140.Word Break II/README_EN.md b/solution/0100-0199/0140.Word Break II/README_EN.md index 5f6ba26327fac..577d070be5fe5 100644 --- a/solution/0100-0199/0140.Word Break II/README_EN.md +++ b/solution/0100-0199/0140.Word Break II/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -93,8 +93,6 @@ class Solution: return [' '.join(v) for v in ans] ``` -### **Java** - ```java class Trie { Trie[] children = new Trie[26]; @@ -155,8 +153,6 @@ class Solution { } ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -220,10 +216,86 @@ func wordBreak(s string, wordDict []string) []string { } ``` -### **...** +```cs +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; -``` +class Node +{ + public int Index1 { get; set; } + public int Index2 { get; set; } +} +public class Solution { + public IList WordBreak(string s, IList wordDict) { + var paths = new List>[s.Length + 1]; + paths[s.Length] = new List> { Tuple.Create(-1, (string)null) }; + var wordDictGroup = wordDict.GroupBy(word => word.Length); + for (var i = s.Length - 1; i >= 0; --i) + { + paths[i] = new List>(); + foreach (var wordGroup in wordDictGroup) + { + var wordLength = wordGroup.Key; + if (i + wordLength <= s.Length && paths[i + wordLength].Count > 0) + { + foreach (var word in wordGroup) + { + if (s.Substring(i, wordLength) == word) + { + paths[i].Add(Tuple.Create(i + wordLength, word)); + } + } + } + } + } + + return GenerateResults(paths); + } + + private IList GenerateResults(List>[] paths) + { + var results = new List(); + var sb = new StringBuilder(); + var stack = new Stack(); + stack.Push(new Node()); + while (stack.Count > 0) + { + var node = stack.Peek(); + if (node.Index1 == paths.Length - 1 || node.Index2 == paths[node.Index1].Count) + { + if (node.Index1 == paths.Length - 1) + { + results.Add(sb.ToString()); + } + stack.Pop(); + if (stack.Count > 0) + { + var parent = stack.Peek(); + var length = paths[parent.Index1][parent.Index2 - 1].Item2.Length; + if (length < sb.Length) ++length; + sb.Remove(sb.Length - length, length); + } + } + else + { + var newNode = new Node { Index1 = paths[node.Index1][node.Index2].Item1, Index2 = 0 }; + if (sb.Length != 0) + { + sb.Append(' '); + } + sb.Append(paths[node.Index1][node.Index2].Item2); + stack.Push(newNode); + ++node.Index2; + } + } + return results; + } +} ``` + + diff --git a/solution/0100-0199/0141.Linked List Cycle/README.md b/solution/0100-0199/0141.Linked List Cycle/README.md index 52e27ad0e570b..29034124a8589 100644 --- a/solution/0100-0199/0141.Linked List Cycle/README.md +++ b/solution/0100-0199/0141.Linked List Cycle/README.md @@ -60,28 +60,14 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 遍历链表,并使用哈希表记录每个节点。当某个节点二次出现时,则表示存在环,直接返回 `true`。否则链表遍历结束,返回 `false`。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是链表中的节点数。 -**方法二:快慢指针** - -我们定义快慢指针 $fast$ 和 $slow$,初始时均指向 $head$。 - -快指针每次走两步,慢指针每次走一步,不断循环。当快慢指针相遇时,说明链表存在环。如果循环结束依然没有相遇,说明链表不存在环。 - -时间复杂度 $O(n)$,其中 $n$ 是链表中的节点数。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -100,10 +86,6 @@ class Solution: return False ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -132,8 +114,6 @@ public class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -160,8 +140,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -182,8 +160,6 @@ func hasCycle(head *ListNode) bool { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -211,35 +187,6 @@ function hasCycle(head: ListNode | null): boolean { } ``` -```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 hasCycle(head: ListNode | null): boolean { - let slow = head; - let fast = head; - while (fast !== null && fast.next !== null) { - slow = slow.next; - fast = fast.next.next; - if (slow === fast) { - return true; - } - } - return false; -} -``` - -### **JavaScript** - ```js /** * Definition for singly-linked list. @@ -267,8 +214,6 @@ var hasCycle = function (head) { }; ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -297,10 +242,45 @@ public class Solution { } ``` -### **...** + + +### 方法二:快慢指针 -``` +我们定义快慢指针 $fast$ 和 $slow$,初始时均指向 $head$。 + +快指针每次走两步,慢指针每次走一步,不断循环。当快慢指针相遇时,说明链表存在环。如果循环结束依然没有相遇,说明链表不存在环。 + +时间复杂度 $O(n)$,其中 $n$ 是链表中的节点数。空间复杂度 $O(1)$。 + + + +```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 hasCycle(head: ListNode | null): boolean { + let slow = head; + let fast = head; + while (fast !== null && fast.next !== null) { + slow = slow.next; + fast = fast.next.next; + if (slow === fast) { + return true; + } + } + return false; +} ``` + + diff --git a/solution/0100-0199/0141.Linked List Cycle/README_EN.md b/solution/0100-0199/0141.Linked List Cycle/README_EN.md index b07b131435f3c..de18baa4eb131 100644 --- a/solution/0100-0199/0141.Linked List Cycle/README_EN.md +++ b/solution/0100-0199/0141.Linked List Cycle/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -71,8 +71,6 @@ class Solution: return False ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -101,8 +99,6 @@ public class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -129,8 +125,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -151,8 +145,6 @@ func hasCycle(head *ListNode) bool { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -180,35 +172,6 @@ function hasCycle(head: ListNode | null): boolean { } ``` -```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 hasCycle(head: ListNode | null): boolean { - let slow = head; - let fast = head; - while (fast !== null && fast.next !== null) { - slow = slow.next; - fast = fast.next.next; - if (slow === fast) { - return true; - } - } - return false; -} -``` - -### **JavaScript** - ```js /** * Definition for singly-linked list. @@ -236,8 +199,6 @@ var hasCycle = function (head) { }; ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -266,10 +227,39 @@ public class Solution { } ``` -### **...** + -``` +### 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 hasCycle(head: ListNode | null): boolean { + let slow = head; + let fast = head; + while (fast !== null && fast.next !== null) { + slow = slow.next; + fast = fast.next.next; + if (slow === fast) { + return true; + } + } + return false; +} ``` + + diff --git a/solution/0100-0199/0142.Linked List Cycle II/README.md b/solution/0100-0199/0142.Linked List Cycle II/README.md index 4fae3739a59d6..8a3f5a227e383 100644 --- a/solution/0100-0199/0142.Linked List Cycle II/README.md +++ b/solution/0100-0199/0142.Linked List Cycle II/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:快慢指针** +### 方法一:快慢指针 我们先利用快慢指针判断链表是否有环,如果有环的话,快慢指针一定会相遇,且相遇的节点一定在环中。 @@ -87,10 +85,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -113,10 +107,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -149,8 +139,6 @@ public class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -182,8 +170,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -210,8 +196,6 @@ func detectCycle(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -243,8 +227,6 @@ function detectCycle(head: ListNode | null): ListNode | null { } ``` -### **JavaScript** - ```js /** * Definition for singly-linked list. @@ -276,10 +258,6 @@ var detectCycle = function (head) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0142.Linked List Cycle II/README_EN.md b/solution/0100-0199/0142.Linked List Cycle II/README_EN.md index b750ca23bb0d2..d7f1ca1fc8f98 100644 --- a/solution/0100-0199/0142.Linked List Cycle II/README_EN.md +++ b/solution/0100-0199/0142.Linked List Cycle II/README_EN.md @@ -49,7 +49,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We first use the fast and slow pointers to judge whether the linked list has a ring. If there is a ring, the fast and slow pointers will definitely meet, and the meeting node must be in the ring. @@ -71,8 +71,6 @@ The time complexity is $O(n)$, where $n$ is the number of nodes in the linked li -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -95,8 +93,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -129,8 +125,6 @@ public class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -162,8 +156,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -190,8 +182,6 @@ func detectCycle(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -223,8 +213,6 @@ function detectCycle(head: ListNode | null): ListNode | null { } ``` -### **JavaScript** - ```js /** * Definition for singly-linked list. @@ -256,10 +244,6 @@ var detectCycle = function (head) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0143.Reorder List/README.md b/solution/0100-0199/0143.Reorder List/README.md index 7dc4b951a86b4..55480e12e46fd 100644 --- a/solution/0100-0199/0143.Reorder List/README.md +++ b/solution/0100-0199/0143.Reorder List/README.md @@ -48,9 +48,7 @@ L0 → Ln → L1 → Ln - 1 → L - -**方法一:快慢指针 + 反转链表 + 合并链表** +### 方法一:快慢指针 + 反转链表 + 合并链表 我们先用快慢指针找到链表的中点,然后将链表的后半部分反转,最后将左右两个链表合并。 @@ -58,10 +56,6 @@ L0 → Ln → L1 → Ln - 1 → L -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -97,10 +91,6 @@ class Solution: cur, pre = pre.next, t ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -148,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -199,8 +187,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -240,7 +226,78 @@ func reorderList(head *ListNode) { } ``` -### **JavaScript** +```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) + * } + * } + */ + +/** + Do not return anything, modify head in-place instead. + */ +function reorderList(head: ListNode | null): void { + const arr = []; + let node = head; + while (node.next != null) { + arr.push(node); + node = node.next; + } + let l = 0; + let r = arr.length - 1; + while (l < r) { + const start = arr[l]; + const end = arr[r]; + [end.next.next, start.next, end.next] = [start.next, end.next, null]; + l++; + r--; + } +} +``` + +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +use std::collections::VecDeque; +impl Solution { + pub fn reorder_list(head: &mut Option>) { + let mut tail = &mut head.as_mut().unwrap().next; + let mut head = tail.take(); + let mut deque = VecDeque::new(); + while head.is_some() { + let next = head.as_mut().unwrap().next.take(); + deque.push_back(head); + head = next; + } + let mut flag = false; + while !deque.is_empty() { + *tail = if flag { deque.pop_front().unwrap() } else { deque.pop_back().unwrap() }; + tail = &mut tail.as_mut().unwrap().next; + flag = !flag; + } + } +} +``` ```js /** @@ -289,8 +346,6 @@ var reorderList = function (head) { }; ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -340,42 +395,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) - * } - * } - */ +### 方法二 -/** - Do not return anything, modify head in-place instead. - */ -function reorderList(head: ListNode | null): void { - const arr = []; - let node = head; - while (node.next != null) { - arr.push(node); - node = node.next; - } - let l = 0; - let r = arr.length - 1; - while (l < r) { - const start = arr[l]; - const end = arr[r]; - [end.next.next, start.next, end.next] = [start.next, end.next, null]; - l++; - r--; - } -} -``` + ```ts /** @@ -420,50 +444,6 @@ function reorderList(head: ListNode | null): void { } ``` -### **Rust** - -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -use std::collections::VecDeque; -impl Solution { - pub fn reorder_list(head: &mut Option>) { - let mut tail = &mut head.as_mut().unwrap().next; - let mut head = tail.take(); - let mut deque = VecDeque::new(); - while head.is_some() { - let next = head.as_mut().unwrap().next.take(); - deque.push_back(head); - head = next; - } - let mut flag = false; - while !deque.is_empty() { - *tail = if flag { deque.pop_front().unwrap() } else { deque.pop_back().unwrap() }; - tail = &mut tail.as_mut().unwrap().next; - flag = !flag; - } - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0143.Reorder List/README_EN.md b/solution/0100-0199/0143.Reorder List/README_EN.md index cfdc205d1d625..e1e1f9d987871 100644 --- a/solution/0100-0199/0143.Reorder List/README_EN.md +++ b/solution/0100-0199/0143.Reorder List/README_EN.md @@ -43,9 +43,9 @@ L0 → Ln → L1 → Ln - 1 ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -55,14 +55,17 @@ L0 → Ln → L1 → Ln - 1 # self.next = next class Solution: def reorderList(self, head: Optional[ListNode]) -> None: + # 快慢指针找到链表中点 fast = slow = head while fast.next and fast.next.next: slow = slow.next fast = fast.next.next + # cur 指向右半部分链表 cur = slow.next slow.next = None + # 反转右半部分链表 pre = None while cur: t = cur.next @@ -70,6 +73,8 @@ class Solution: pre, cur = cur, t cur = head + # 此时 cur, pre 分别指向链表左右两半的第一个节点 + # 合并 while pre: t = pre.next pre.next = cur.next @@ -77,8 +82,6 @@ class Solution: cur, pre = pre.next, t ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -92,15 +95,18 @@ class Solution: */ class Solution { public void reorderList(ListNode head) { + // 快慢指针找到链表中点 ListNode fast = head, slow = head; while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; } + // cur 指向右半部分链表 ListNode cur = slow.next; slow.next = null; + // 反转右半部分链表 ListNode pre = null; while (cur != null) { ListNode t = cur.next; @@ -110,6 +116,8 @@ class Solution { } cur = head; + // 此时 cur, pre 分别指向链表左右两半的第一个节点 + // 合并 while (pre != null) { ListNode t = pre.next; pre.next = cur.next; @@ -121,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -137,6 +143,7 @@ class Solution { class Solution { public: void reorderList(ListNode* head) { + // 快慢指针找到链表中点 ListNode* fast = head; ListNode* slow = head; while (fast->next && fast->next->next) { @@ -144,9 +151,11 @@ public: fast = fast->next->next; } + // cur 指向右半部分链表 ListNode* cur = slow->next; slow->next = nullptr; + // 反转右半部分链表 ListNode* pre = nullptr; while (cur) { ListNode* t = cur->next; @@ -156,6 +165,8 @@ public: } cur = head; + // 此时 cur, pre 分别指向链表左右两半的第一个节点 + // 合并 while (pre) { ListNode* t = pre->next; pre->next = cur->next; @@ -167,8 +178,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -178,14 +187,17 @@ public: * } */ func reorderList(head *ListNode) { + // 快慢指针找到链表中点 fast, slow := head, head for fast.Next != nil && fast.Next.Next != nil { slow, fast = slow.Next, fast.Next.Next } + // cur 指向右半部分链表 cur := slow.Next slow.Next = nil + // 反转右半部分链表 var pre *ListNode for cur != nil { t := cur.Next @@ -194,6 +206,8 @@ func reorderList(head *ListNode) { } cur = head + // 此时 cur, pre 分别指向链表左右两半的第一个节点 + // 合并 for pre != nil { t := pre.Next pre.Next = cur.Next @@ -203,7 +217,78 @@ func reorderList(head *ListNode) { } ``` -### **JavaScript** +```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) + * } + * } + */ + +/** + Do not return anything, modify head in-place instead. + */ +function reorderList(head: ListNode | null): void { + const arr = []; + let node = head; + while (node.next != null) { + arr.push(node); + node = node.next; + } + let l = 0; + let r = arr.length - 1; + while (l < r) { + const start = arr[l]; + const end = arr[r]; + [end.next.next, start.next, end.next] = [start.next, end.next, null]; + l++; + r--; + } +} +``` + +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +use std::collections::VecDeque; +impl Solution { + pub fn reorder_list(head: &mut Option>) { + let mut tail = &mut head.as_mut().unwrap().next; + let mut head = tail.take(); + let mut deque = VecDeque::new(); + while head.is_some() { + let next = head.as_mut().unwrap().next.take(); + deque.push_back(head); + head = next; + } + let mut flag = false; + while !deque.is_empty() { + *tail = if flag { deque.pop_front().unwrap() } else { deque.pop_back().unwrap() }; + tail = &mut tail.as_mut().unwrap().next; + flag = !flag; + } + } +} +``` ```js /** @@ -218,6 +303,7 @@ func reorderList(head *ListNode) { * @return {void} Do not return anything, modify head in-place instead. */ var reorderList = function (head) { + // 快慢指针找到链表中点 let slow = head; let fast = head; while (fast.next && fast.next.next) { @@ -225,9 +311,11 @@ var reorderList = function (head) { fast = fast.next.next; } + // cur 指向右半部分链表 let cur = slow.next; slow.next = null; + // 反转右半部分链表 let pre = null; while (cur) { const t = cur.next; @@ -237,6 +325,8 @@ var reorderList = function (head) { } cur = head; + // 此时 cur, pre 分别指向链表左右两半的第一个节点 + // 合并 while (pre) { const t = pre.next; pre.next = cur.next; @@ -247,8 +337,6 @@ var reorderList = function (head) { }; ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -263,6 +351,7 @@ var reorderList = function (head) { */ public class Solution { public void ReorderList(ListNode head) { + // 快慢指针找到链表中点 ListNode slow = head; ListNode fast = head; while (fast.next != null && fast.next.next != null) { @@ -270,9 +359,11 @@ public class Solution { fast = fast.next.next; } + // cur 指向右半部分链表 ListNode cur = slow.next; slow.next = null; + // 反转右半部分链表 ListNode pre = null; while (cur != null) { ListNode t = cur.next; @@ -282,6 +373,8 @@ public class Solution { } cur = head; + // 此时 cur, pre 分别指向链表左右两半的第一个节点 + // 合并 while (pre != null) { ListNode t = pre.next; pre.next = cur.next; @@ -293,42 +386,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 -/** - Do not return anything, modify head in-place instead. - */ -function reorderList(head: ListNode | null): void { - const arr = []; - let node = head; - while (node.next != null) { - arr.push(node); - node = node.next; - } - let l = 0; - let r = arr.length - 1; - while (l < r) { - const start = arr[l]; - const end = arr[r]; - [end.next.next, start.next, end.next] = [start.next, end.next, null]; - l++; - r--; - } -} -``` + ```ts /** @@ -349,18 +411,18 @@ function reorderList(head: ListNode | null): void { function reorderList(head: ListNode | null): void { let slow = head; let fast = head; - + // 找到中心节点 while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } - + // 反转节点 let next = slow.next; slow.next = null; while (next != null) { [next.next, slow, next] = [slow, next, next.next]; } - + // 合并 let left = head; let right = slow; while (right.next != null) { @@ -373,50 +435,6 @@ function reorderList(head: ListNode | null): void { } ``` -### **Rust** - -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -use std::collections::VecDeque; -impl Solution { - pub fn reorder_list(head: &mut Option>) { - let mut tail = &mut head.as_mut().unwrap().next; - let mut head = tail.take(); - let mut deque = VecDeque::new(); - while head.is_some() { - let next = head.as_mut().unwrap().next.take(); - deque.push_back(head); - head = next; - } - let mut flag = false; - while !deque.is_empty() { - *tail = if flag { deque.pop_front().unwrap() } else { deque.pop_back().unwrap() }; - tail = &mut tail.as_mut().unwrap().next; - flag = !flag; - } - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0144.Binary Tree Preorder Traversal/README.md b/solution/0100-0199/0144.Binary Tree Preorder Traversal/README.md index 2880351772e9f..35ad34d266cc0 100644 --- a/solution/0100-0199/0144.Binary Tree Preorder Traversal/README.md +++ b/solution/0100-0199/0144.Binary Tree Preorder Traversal/README.md @@ -60,43 +60,10 @@ ## 解法 - - -**1. 递归遍历** - -先访问根节点,接着递归左子树、右子树。 - -**2. 栈实现非递归遍历** - -非递归的思路如下: - -1. 定义一个栈 stk,先将根节点压入栈 -2. 若栈不为空,每次从栈中弹出一个节点 -3. 处理该节点 -4. 先把节点右孩子压入栈,接着把节点左孩子压入栈(如果有孩子节点) -5. 重复 2-4 -6. 返回结果 - -**3. Morris 实现前序遍历** - -Morris 遍历无需使用栈,空间复杂度为 O(1)。核心思想是: - -遍历二叉树节点, - -1. 若当前节点 root 的左子树为空,**将当前节点值添加至结果列表 ans** 中,并将当前节点更新为 `root.right` -2. 若当前节点 root 的左子树不为空,找到左子树的最右节点 prev(也即是 root 节点在中序遍历下的前驱节点): - - 若前驱节点 prev 的右子树为空,**将当前节点值添加至结果列表 ans** 中,然后将前驱节点的右子树指向当前节点 root,并将当前节点更新为 `root.left`。 - - 若前驱节点 prev 的右子树不为空,将前驱节点右子树指向空(即解除 prev 与 root 的指向关系),并将当前节点更新为 `root.right`。 -3. 循环以上步骤,直至二叉树节点为空,遍历结束。 +### 方法一 -### **Python3** - - - -递归: - ```python # Definition for a binary tree node. # class TreeNode: @@ -119,67 +86,6 @@ class Solution: return ans ``` -栈实现非递归: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: - ans = [] - if root is None: - return ans - stk = [root] - while stk: - node = stk.pop() - ans.append(node.val) - if node.right: - stk.append(node.right) - if node.left: - stk.append(node.left) - return ans -``` - -Morris 遍历: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: - ans = [] - while root: - if root.left is None: - ans.append(root.val) - root = root.right - else: - prev = root.left - while prev.right and prev.right != root: - prev = prev.right - if prev.right is None: - ans.append(root.val) - prev.right = root - root = root.left - else: - prev.right = None - root = root.right - return ans -``` - -### **Java** - - - -递归: - ```java /** * Definition for a binary tree node. @@ -216,165 +122,6 @@ class Solution { } ``` -非递归: - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public List preorderTraversal(TreeNode root) { - List ans = new ArrayList<>(); - if (root == null) { - return ans; - } - Deque stk = new ArrayDeque<>(); - stk.push(root); - while (!stk.isEmpty()) { - TreeNode node = stk.pop(); - ans.add(node.val); - if (node.right != null) { - stk.push(node.right); - } - if (node.left != null) { - stk.push(node.left); - } - } - return ans; - } -} -``` - -Morris 遍历: - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public List preorderTraversal(TreeNode root) { - List ans = new ArrayList<>(); - while (root != null) { - if (root.left == null) { - ans.add(root.val); - root = root.right; - } else { - TreeNode prev = root.left; - while (prev.right != null && prev.right != root) { - prev = prev.right; - } - if (prev.right == null) { - ans.add(root.val); - prev.right = root; - root = root.left; - } else { - prev.right = null; - root = root.right; - } - } - } - return ans; - } -} -``` - -### **TypeScript** - -```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 preorderTraversal(root: TreeNode | null): number[] { - let ans = []; - if (!root) return ans; - let stk = [root]; - while (stk.length) { - let node = stk.pop(); - ans.push(node.val); - if (node.right) stk.push(node.right); - if (node.left) stk.push(node.left); - } - return ans; -} -``` - -```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 preorderTraversal(root: TreeNode | null): number[] { - let ans = []; - while (root) { - if (!root.left) { - ans.push(root.val); - root = root.right; - } else { - let prev = root.left; - while (prev.right && prev.right != root) { - prev = prev.right; - } - if (!prev.right) { - ans.push(root.val); - prev.right = root; - root = root.left; - } else { - prev.right = null; - root = root.right; - } - } - } - return ans; -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -415,8 +162,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -451,7 +196,34 @@ func preorderTraversal(root *TreeNode) []int { } ``` -### **Rust** +```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 preorderTraversal(root: TreeNode | null): number[] { + let ans = []; + if (!root) return ans; + let stk = [root]; + while (stk.length) { + let node = stk.pop(); + ans.push(node.val); + if (node.right) stk.push(node.right); + if (node.left) stk.push(node.left); + } + return ans; +} +``` ```rust // Definition for a binary tree node. @@ -493,6 +265,114 @@ impl Solution { } ``` + + +### 方法二 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + if root is None: + return ans + stk = [root] + while stk: + node = stk.pop() + ans.append(node.val) + if node.right: + stk.append(node.right) + if node.left: + stk.append(node.left) + return ans +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List preorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + if (root == null) { + return ans; + } + Deque stk = new ArrayDeque<>(); + stk.push(root); + while (!stk.isEmpty()) { + TreeNode node = stk.pop(); + ans.add(node.val); + if (node.right != null) { + stk.push(node.right); + } + if (node.left != null) { + stk.push(node.left); + } + } + return ans; + } +} +``` + +```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 preorderTraversal(root: TreeNode | null): number[] { + let ans = []; + while (root) { + if (!root.left) { + ans.push(root.val); + root = root.right; + } else { + let prev = root.left; + while (prev.right && prev.right != root) { + prev = prev.right; + } + if (!prev.right) { + ans.push(root.val); + prev.right = root; + root = root.left; + } else { + prev.right = null; + root = root.right; + } + } + } + return ans; +} +``` + ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -537,10 +417,83 @@ impl Solution { } ``` -### **...** + + +### 方法三 + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + while root: + if root.left is None: + ans.append(root.val) + root = root.right + else: + prev = root.left + while prev.right and prev.right != root: + prev = prev.right + if prev.right is None: + ans.append(root.val) + prev.right = root + root = root.left + else: + prev.right = None + root = root.right + return ans ``` +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List preorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + while (root != null) { + if (root.left == null) { + ans.add(root.val); + root = root.right; + } else { + TreeNode prev = root.left; + while (prev.right != null && prev.right != root) { + prev = prev.right; + } + if (prev.right == null) { + ans.add(root.val); + prev.right = root; + root = root.left; + } else { + prev.right = null; + root = root.right; + } + } + } + return ans; + } +} ``` + + diff --git a/solution/0100-0199/0144.Binary Tree Preorder Traversal/README_EN.md b/solution/0100-0199/0144.Binary Tree Preorder Traversal/README_EN.md index 3e1de20d9c0f5..92403e6a88f7c 100644 --- a/solution/0100-0199/0144.Binary Tree Preorder Traversal/README_EN.md +++ b/solution/0100-0199/0144.Binary Tree Preorder Traversal/README_EN.md @@ -41,18 +41,10 @@ ## Solutions -**1. Recusive Traversal** - -**2. Non-recursive using Stack** - -**3. Morris Traversal** +### Solution 1 -### **Python3** - -Recursive: - ```python # Definition for a binary tree node. # class TreeNode: @@ -75,65 +67,6 @@ class Solution: return ans ``` -Non-recursive: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: - ans = [] - if root is None: - return ans - stk = [root] - while stk: - node = stk.pop() - ans.append(node.val) - if node.right: - stk.append(node.right) - if node.left: - stk.append(node.left) - return ans -``` - -Morris Traversal: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: - ans = [] - while root: - if root.left is None: - ans.append(root.val) - root = root.right - else: - prev = root.left - while prev.right and prev.right != root: - prev = prev.right - if prev.right is None: - ans.append(root.val) - prev.right = root - root = root.left - else: - prev.right = None - root = root.right - return ans -``` - -### **Java** - -Recursive: - ```java /** * Definition for a binary tree node. @@ -170,165 +103,6 @@ class Solution { } ``` -Non-recursive: - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public List preorderTraversal(TreeNode root) { - List ans = new ArrayList<>(); - if (root == null) { - return ans; - } - Deque stk = new ArrayDeque<>(); - stk.push(root); - while (!stk.isEmpty()) { - TreeNode node = stk.pop(); - ans.add(node.val); - if (node.right != null) { - stk.push(node.right); - } - if (node.left != null) { - stk.push(node.left); - } - } - return ans; - } -} -``` - -Morris Traversal: - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public List preorderTraversal(TreeNode root) { - List ans = new ArrayList<>(); - while (root != null) { - if (root.left == null) { - ans.add(root.val); - root = root.right; - } else { - TreeNode prev = root.left; - while (prev.right != null && prev.right != root) { - prev = prev.right; - } - if (prev.right == null) { - ans.add(root.val); - prev.right = root; - root = root.left; - } else { - prev.right = null; - root = root.right; - } - } - } - return ans; - } -} -``` - -### **TypeScript** - -```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 preorderTraversal(root: TreeNode | null): number[] { - let ans = []; - if (!root) return ans; - let stk = [root]; - while (stk.length) { - let node = stk.pop(); - ans.push(node.val); - if (node.right) stk.push(node.right); - if (node.left) stk.push(node.left); - } - return ans; -} -``` - -```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 preorderTraversal(root: TreeNode | null): number[] { - let ans = []; - while (root) { - if (!root.left) { - ans.push(root.val); - root = root.right; - } else { - let prev = root.left; - while (prev.right && prev.right != root) { - prev = prev.right; - } - if (!prev.right) { - ans.push(root.val); - prev.right = root; - root = root.left; - } else { - prev.right = null; - root = root.right; - } - } - } - return ans; -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -369,8 +143,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -405,7 +177,34 @@ func preorderTraversal(root *TreeNode) []int { } ``` -### **Rust** +```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 preorderTraversal(root: TreeNode | null): number[] { + let ans = []; + if (!root) return ans; + let stk = [root]; + while (stk.length) { + let node = stk.pop(); + ans.push(node.val); + if (node.right) stk.push(node.right); + if (node.left) stk.push(node.left); + } + return ans; +} +``` ```rust // Definition for a binary tree node. @@ -447,6 +246,114 @@ impl Solution { } ``` + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + if root is None: + return ans + stk = [root] + while stk: + node = stk.pop() + ans.append(node.val) + if node.right: + stk.append(node.right) + if node.left: + stk.append(node.left) + return ans +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List preorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + if (root == null) { + return ans; + } + Deque stk = new ArrayDeque<>(); + stk.push(root); + while (!stk.isEmpty()) { + TreeNode node = stk.pop(); + ans.add(node.val); + if (node.right != null) { + stk.push(node.right); + } + if (node.left != null) { + stk.push(node.left); + } + } + return ans; + } +} +``` + +```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 preorderTraversal(root: TreeNode | null): number[] { + let ans = []; + while (root) { + if (!root.left) { + ans.push(root.val); + root = root.right; + } else { + let prev = root.left; + while (prev.right && prev.right != root) { + prev = prev.right; + } + if (!prev.right) { + ans.push(root.val); + prev.right = root; + root = root.left; + } else { + prev.right = null; + root = root.right; + } + } + } + return ans; +} +``` + ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -491,10 +398,83 @@ impl Solution { } ``` -### **...** + +### Solution 3 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + while root: + if root.left is None: + ans.append(root.val) + root = root.right + else: + prev = root.left + while prev.right and prev.right != root: + prev = prev.right + if prev.right is None: + ans.append(root.val) + prev.right = root + root = root.left + else: + prev.right = None + root = root.right + return ans ``` +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List preorderTraversal(TreeNode root) { + List ans = new ArrayList<>(); + while (root != null) { + if (root.left == null) { + ans.add(root.val); + root = root.right; + } else { + TreeNode prev = root.left; + while (prev.right != null && prev.right != root) { + prev = prev.right; + } + if (prev.right == null) { + ans.add(root.val); + prev.right = root; + root = root.left; + } else { + prev.right = null; + root = root.right; + } + } + } + return ans; + } +} ``` + + diff --git a/solution/0100-0199/0145.Binary Tree Postorder Traversal/README.md b/solution/0100-0199/0145.Binary Tree Postorder Traversal/README.md index 1902d056ccd06..348a8e1ec01d4 100644 --- a/solution/0100-0199/0145.Binary Tree Postorder Traversal/README.md +++ b/solution/0100-0199/0145.Binary Tree Postorder Traversal/README.md @@ -46,43 +46,10 @@ ## 解法 - - -**1. 递归遍历** - -先递归左右子树,再访问根节点。 - -**2. 栈实现非递归遍历** - -非递归的思路如下: - -先序遍历的顺序是:头、左、右,如果我们改变左右孩子的顺序,就能将顺序变成:头、右、左。 - -我们先不打印头节点,而是存放到另一个收集栈 ans 中,最后遍历结束,输出收集栈元素,即是后序遍历:左、右、头。收集栈是为了实现结果列表的逆序。我们也可以直接使用链表,每次插入元素时,放在头部,最后直接返回链表即可,无需进行逆序。 - -**3. Morris 实现后序遍历** - -Morris 遍历无需使用栈,空间复杂度为 O(1)。核心思想是: - -遍历二叉树节点, - -1. 若当前节点 root 的右子树为空,**将当前节点值添加至结果列表 ans** 中,并将当前节点更新为 `root.left` -2. 若当前节点 root 的右子树不为空,找到右子树的最左节点 next(也即是 root 节点在中序遍历下的后继节点): - - 若后继节点 next 的左子树为空,**将当前节点值添加至结果列表 ans** 中,然后将后继节点的左子树指向当前节点 root,并将当前节点更新为 `root.right`。 - - 若后继节点 next 的左子树不为空,将后继节点左子树指向空(即解除 next 与 root 的指向关系),并将当前节点更新为 `root.left`。 -3. 循环以上步骤,直至二叉树节点为空,遍历结束。 -4. 最后返回结果列表的逆序即可。 - -> Morris 后序遍历跟 Morris 前序遍历思路一致,只是将前序的“根左右”变为“根右左”,最后逆序结果即可变成“左右根”。 +### 方法一 -### **Python3** - - - -递归: - ```python # Definition for a binary tree node. # class TreeNode: @@ -105,67 +72,6 @@ class Solution: return ans ``` -栈实现非递归: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: - ans = [] - if root is None: - return ans - stk = [root] - while stk: - node = stk.pop() - ans.append(node.val) - if node.left: - stk.append(node.left) - if node.right: - stk.append(node.right) - return ans[::-1] -``` - -Morris 遍历: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: - ans = [] - while root: - if root.right is None: - ans.append(root.val) - root = root.left - else: - next = root.right - while next.left and next.left != root: - next = next.left - if next.left != root: - ans.append(root.val) - next.left = root - root = root.right - else: - next.left = None - root = root.left - return ans[::-1] -``` - -### **Java** - - - -递归: - ```java /** * Definition for a binary tree node. @@ -202,200 +108,6 @@ class Solution { } ``` -栈实现非递归: - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public List postorderTraversal(TreeNode root) { - LinkedList ans = new LinkedList<>(); - if (root == null) { - return ans; - } - Deque stk = new ArrayDeque<>(); - stk.push(root); - while (!stk.isEmpty()) { - TreeNode node = stk.pop(); - ans.addFirst(node.val); - if (node.left != null) { - stk.push(node.left); - } - if (node.right != null) { - stk.push(node.right); - } - } - return ans; - } -} -``` - -Morris 遍历: - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public List postorderTraversal(TreeNode root) { - LinkedList ans = new LinkedList<>(); - while (root != null) { - if (root.right == null) { - ans.addFirst(root.val); - root = root.left; - } else { - TreeNode next = root.right; - while (next.left != null && next.left != root) { - next = next.left; - } - if (next.left == null) { - ans.addFirst(root.val); - next.left = root; - root = root.right; - } else { - next.left = null; - root = root.left; - } - } - } - return ans; - } -} -``` - -### **TypeScript** - -```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 postorderTraversal(root: TreeNode | null): number[] { - if (root == null) return []; - let stack = []; - let ans = []; - let prev = null; - while (root || stack.length) { - while (root) { - stack.push(root); - root = root.left; - } - root = stack.pop(); - if (!root.right || root.right == prev) { - ans.push(root.val); - prev = root; - root = null; - } else { - stack.push(root); - root = root.right; - } - } - return ans; -} -``` - -```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 postorderTraversal(root: TreeNode | null): number[] { - if (root == null) { - return []; - } - const { val, left, right } = root; - return [...postorderTraversal(left), ...postorderTraversal(right), val]; -} -``` - -```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 postorderTraversal(root: TreeNode | null): number[] { - const res = []; - while (root != null) { - const { val, left, right } = root; - if (right == null) { - res.push(val); - root = left; - } else { - let next = right; - while (next.left != null && next.left != root) { - next = next.left; - } - if (next.left == null) { - res.push(val); - next.left = root; - root = right; - } else { - next.left = null; - root = left; - } - } - } - return res.reverse(); -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -437,8 +149,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -473,7 +183,44 @@ func postorderTraversal(root *TreeNode) []int { } ``` -### **Rust** +```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 postorderTraversal(root: TreeNode | null): number[] { + if (root == null) return []; + let stack = []; + let ans = []; + let prev = null; + while (root || stack.length) { + while (root) { + stack.push(root); + root = root.left; + } + root = stack.pop(); + if (!root.right || root.right == prev) { + ans.push(root.val); + prev = root; + root = null; + } else { + stack.push(root); + root = root.right; + } + } + return ans; +} +``` ```rust // Definition for a binary tree node. @@ -515,6 +262,98 @@ impl Solution { } ``` + + +### 方法二 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + if root is None: + return ans + stk = [root] + while stk: + node = stk.pop() + ans.append(node.val) + if node.left: + stk.append(node.left) + if node.right: + stk.append(node.right) + return ans[::-1] +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List postorderTraversal(TreeNode root) { + LinkedList ans = new LinkedList<>(); + if (root == null) { + return ans; + } + Deque stk = new ArrayDeque<>(); + stk.push(root); + while (!stk.isEmpty()) { + TreeNode node = stk.pop(); + ans.addFirst(node.val); + if (node.left != null) { + stk.push(node.left); + } + if (node.right != null) { + stk.push(node.right); + } + } + return ans; + } +} +``` + +```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 postorderTraversal(root: TreeNode | null): number[] { + if (root == null) { + return []; + } + const { val, left, right } = root; + return [...postorderTraversal(left), ...postorderTraversal(right), val]; +} +``` + ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -561,10 +400,124 @@ impl Solution { } ``` -### **...** + + +### 方法三 + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + while root: + if root.right is None: + ans.append(root.val) + root = root.left + else: + next = root.right + while next.left and next.left != root: + next = next.left + if next.left != root: + ans.append(root.val) + next.left = root + root = root.right + else: + next.left = None + root = root.left + return ans[::-1] ``` +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List postorderTraversal(TreeNode root) { + LinkedList ans = new LinkedList<>(); + while (root != null) { + if (root.right == null) { + ans.addFirst(root.val); + root = root.left; + } else { + TreeNode next = root.right; + while (next.left != null && next.left != root) { + next = next.left; + } + if (next.left == null) { + ans.addFirst(root.val); + next.left = root; + root = root.right; + } else { + next.left = null; + root = root.left; + } + } + } + return ans; + } +} +``` + +```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 postorderTraversal(root: TreeNode | null): number[] { + const res = []; + while (root != null) { + const { val, left, right } = root; + if (right == null) { + res.push(val); + root = left; + } else { + let next = right; + while (next.left != null && next.left != root) { + next = next.left; + } + if (next.left == null) { + res.push(val); + next.left = root; + root = right; + } else { + next.left = null; + root = left; + } + } + } + return res.reverse(); +} ``` + + diff --git a/solution/0100-0199/0145.Binary Tree Postorder Traversal/README_EN.md b/solution/0100-0199/0145.Binary Tree Postorder Traversal/README_EN.md index 9bb1c9038dc46..55f196c227478 100644 --- a/solution/0100-0199/0145.Binary Tree Postorder Traversal/README_EN.md +++ b/solution/0100-0199/0145.Binary Tree Postorder Traversal/README_EN.md @@ -41,18 +41,10 @@ ## Solutions -**1. Recusive Traversal** - -**2. Non-recursive using Stack** - -**3. Morris Traversal** +### Solution 1 -### **Python3** - -Recursive: - ```python # Definition for a binary tree node. # class TreeNode: @@ -75,65 +67,6 @@ class Solution: return ans ``` -Non-recursive: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: - ans = [] - if root is None: - return ans - stk = [root] - while stk: - node = stk.pop() - ans.append(node.val) - if node.left: - stk.append(node.left) - if node.right: - stk.append(node.right) - return ans[::-1] -``` - -Morris Traversal: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: - ans = [] - while root: - if root.right is None: - ans.append(root.val) - root = root.left - else: - next = root.right - while next.left and next.left != root: - next = next.left - if next.left != root: - ans.append(root.val) - next.left = root - root = root.right - else: - next.left = None - root = root.left - return ans[::-1] -``` - -### **Java** - -Recursive: - ```java /** * Definition for a binary tree node. @@ -170,200 +103,6 @@ class Solution { } ``` -Non-recursive: - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public List postorderTraversal(TreeNode root) { - LinkedList ans = new LinkedList<>(); - if (root == null) { - return ans; - } - Deque stk = new ArrayDeque<>(); - stk.push(root); - while (!stk.isEmpty()) { - TreeNode node = stk.pop(); - ans.addFirst(node.val); - if (node.left != null) { - stk.push(node.left); - } - if (node.right != null) { - stk.push(node.right); - } - } - return ans; - } -} -``` - -Morris Traversal: - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public List postorderTraversal(TreeNode root) { - LinkedList ans = new LinkedList<>(); - while (root != null) { - if (root.right == null) { - ans.addFirst(root.val); - root = root.left; - } else { - TreeNode next = root.right; - while (next.left != null && next.left != root) { - next = next.left; - } - if (next.left == null) { - ans.addFirst(root.val); - next.left = root; - root = root.right; - } else { - next.left = null; - root = root.left; - } - } - } - return ans; - } -} -``` - -### **TypeScript** - -```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 postorderTraversal(root: TreeNode | null): number[] { - if (root == null) return []; - let stack = []; - let ans = []; - let prev = null; - while (root || stack.length) { - while (root) { - stack.push(root); - root = root.left; - } - root = stack.pop(); - if (!root.right || root.right == prev) { - ans.push(root.val); - prev = root; - root = null; - } else { - stack.push(root); - root = root.right; - } - } - return ans; -} -``` - -```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 postorderTraversal(root: TreeNode | null): number[] { - if (root == null) { - return []; - } - const { val, left, right } = root; - return [...postorderTraversal(left), ...postorderTraversal(right), val]; -} -``` - -```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 postorderTraversal(root: TreeNode | null): number[] { - const res = []; - while (root != null) { - const { val, left, right } = root; - if (right == null) { - res.push(val); - root = left; - } else { - let next = right; - while (next.left != null && next.left != root) { - next = next.left; - } - if (next.left == null) { - res.push(val); - next.left = root; - root = right; - } else { - next.left = null; - root = left; - } - } - } - return res.reverse(); -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -405,8 +144,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -441,7 +178,44 @@ func postorderTraversal(root *TreeNode) []int { } ``` -### **Rust** +```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 postorderTraversal(root: TreeNode | null): number[] { + if (root == null) return []; + let stack = []; + let ans = []; + let prev = null; + while (root || stack.length) { + while (root) { + stack.push(root); + root = root.left; + } + root = stack.pop(); + if (!root.right || root.right == prev) { + ans.push(root.val); + prev = root; + root = null; + } else { + stack.push(root); + root = root.right; + } + } + return ans; +} +``` ```rust // Definition for a binary tree node. @@ -483,6 +257,98 @@ impl Solution { } ``` + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + if root is None: + return ans + stk = [root] + while stk: + node = stk.pop() + ans.append(node.val) + if node.left: + stk.append(node.left) + if node.right: + stk.append(node.right) + return ans[::-1] +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List postorderTraversal(TreeNode root) { + LinkedList ans = new LinkedList<>(); + if (root == null) { + return ans; + } + Deque stk = new ArrayDeque<>(); + stk.push(root); + while (!stk.isEmpty()) { + TreeNode node = stk.pop(); + ans.addFirst(node.val); + if (node.left != null) { + stk.push(node.left); + } + if (node.right != null) { + stk.push(node.right); + } + } + return ans; + } +} +``` + +```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 postorderTraversal(root: TreeNode | null): number[] { + if (root == null) { + return []; + } + const { val, left, right } = root; + return [...postorderTraversal(left), ...postorderTraversal(right), val]; +} +``` + ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -529,10 +395,124 @@ impl Solution { } ``` -### **...** + + +### Solution 3 + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + while root: + if root.right is None: + ans.append(root.val) + root = root.left + else: + next = root.right + while next.left and next.left != root: + next = next.left + if next.left != root: + ans.append(root.val) + next.left = root + root = root.right + else: + next.left = None + root = root.left + return ans[::-1] ``` +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List postorderTraversal(TreeNode root) { + LinkedList ans = new LinkedList<>(); + while (root != null) { + if (root.right == null) { + ans.addFirst(root.val); + root = root.left; + } else { + TreeNode next = root.right; + while (next.left != null && next.left != root) { + next = next.left; + } + if (next.left == null) { + ans.addFirst(root.val); + next.left = root; + root = root.right; + } else { + next.left = null; + root = root.left; + } + } + } + return ans; + } +} +``` + +```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 postorderTraversal(root: TreeNode | null): number[] { + const res = []; + while (root != null) { + const { val, left, right } = root; + if (right == null) { + res.push(val); + root = left; + } else { + let next = right; + while (next.left != null && next.left != root) { + next = next.left; + } + if (next.left == null) { + res.push(val); + next.left = root; + root = right; + } else { + next.left = null; + root = left; + } + } + } + return res.reverse(); +} ``` + + diff --git a/solution/0100-0199/0146.LRU Cache/README.md b/solution/0100-0199/0146.LRU Cache/README.md index 9e59aa2756e73..31485232c75ec 100644 --- a/solution/0100-0199/0146.LRU Cache/README.md +++ b/solution/0100-0199/0146.LRU Cache/README.md @@ -59,9 +59,7 @@ lRUCache.get(4); // 返回 4 ## 解法 - - -**方法一:哈希表 + 双向链表** +### 方法一:哈希表 + 双向链表 我们可以用“哈希表”和“双向链表”实现一个 LRU 缓存。 @@ -76,10 +74,6 @@ lRUCache.get(4); // 返回 4 -### **Python3** - - - ```python class Node: def __init__(self, key=0, val=0): @@ -147,10 +141,6 @@ class LRUCache: # obj.put(key,value) ``` -### **Java** - - - ```java class Node { int key; @@ -239,214 +229,6 @@ class LRUCache { */ ``` -### **Rust** - -```rust -use std::cell::RefCell; -use std::collections::HashMap; -use std::rc::Rc; - -struct Node { - key: i32, - value: i32, - prev: Option>>, - next: Option>>, -} - -impl Node { - #[inline] - fn new(key: i32, value: i32) -> Self { - Self { - key, - value, - prev: None, - next: None, - } - } -} - -struct LRUCache { - capacity: usize, - cache: HashMap>>, - head: Option>>, - tail: Option>>, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl LRUCache { - fn new(capacity: i32) -> Self { - Self { - capacity: capacity as usize, - cache: HashMap::new(), - head: None, - tail: None, - } - } - - fn get(&mut self, key: i32) -> i32 { - match self.cache.get(&key) { - Some(node) => { - let node = Rc::clone(node); - self.remove(&node); - self.push_front(&node); - let value = node.borrow().value; - value - } - None => -1, - } - } - - fn put(&mut self, key: i32, value: i32) { - match self.cache.get(&key) { - Some(node) => { - let node = Rc::clone(node); - node.borrow_mut().value = value; - self.remove(&node); - self.push_front(&node); - } - None => { - let node = Rc::new(RefCell::new(Node::new(key, value))); - self.cache.insert(key, Rc::clone(&node)); - self.push_front(&node); - if self.cache.len() > self.capacity { - let back_key = self.pop_back().unwrap().borrow().key; - self.cache.remove(&back_key); - } - } - }; - } - - fn push_front(&mut self, node: &Rc>) { - match self.head.take() { - Some(head) => { - head.borrow_mut().prev = Some(Rc::clone(node)); - node.borrow_mut().prev = None; - node.borrow_mut().next = Some(head); - self.head = Some(Rc::clone(node)); - } - None => { - self.head = Some(Rc::clone(node)); - self.tail = Some(Rc::clone(node)); - } - }; - } - - fn remove(&mut self, node: &Rc>) { - match (node.borrow().prev.as_ref(), node.borrow().next.as_ref()) { - (None, None) => { - self.head = None; - self.tail = None; - } - (None, Some(next)) => { - self.head = Some(Rc::clone(next)); - next.borrow_mut().prev = None; - } - (Some(prev), None) => { - self.tail = Some(Rc::clone(prev)); - prev.borrow_mut().next = None; - } - (Some(prev), Some(next)) => { - next.borrow_mut().prev = Some(Rc::clone(prev)); - prev.borrow_mut().next = Some(Rc::clone(next)); - } - }; - } - - fn pop_back(&mut self) -> Option>> { - match self.tail.take() { - Some(tail) => { - self.remove(&tail); - Some(tail) - } - None => None, - } - } -}/** - * Your LRUCache object will be instantiated and called as such: - * let obj = LRUCache::new(capacity); - * let ret_1: i32 = obj.get(key); - * obj.put(key, value); - */ -``` - -### **Go** - -```go -type node struct { - key, val int - prev, next *node -} - -type LRUCache struct { - capacity int - cache map[int]*node - head, tail *node -} - -func Constructor(capacity int) LRUCache { - head := new(node) - tail := new(node) - head.next = tail - tail.prev = head - return LRUCache{ - capacity: capacity, - cache: make(map[int]*node, capacity), - head: head, - tail: tail, - } -} - -func (this *LRUCache) Get(key int) int { - n, ok := this.cache[key] - if !ok { - return -1 - } - this.moveToFront(n) - return n.val -} - -func (this *LRUCache) Put(key int, value int) { - n, ok := this.cache[key] - if ok { - n.val = value - this.moveToFront(n) - return - } - if len(this.cache) == this.capacity { - back := this.tail.prev - this.remove(back) - delete(this.cache, back.key) - } - n = &node{key: key, val: value} - this.pushFront(n) - this.cache[key] = n -} - -func (this *LRUCache) moveToFront(n *node) { - this.remove(n) - this.pushFront(n) -} - -func (this *LRUCache) remove(n *node) { - n.prev.next = n.next - n.next.prev = n.prev - n.prev = nil - n.next = nil -} - -func (this *LRUCache) pushFront(n *node) { - n.prev = this.head - n.next = this.head.next - this.head.next.prev = n - this.head.next = n -} -``` - -### **C++** - ```cpp struct Node { int k; @@ -541,7 +323,76 @@ private: */ ``` -### **TypeScript** +```go +type node struct { + key, val int + prev, next *node +} + +type LRUCache struct { + capacity int + cache map[int]*node + head, tail *node +} + +func Constructor(capacity int) LRUCache { + head := new(node) + tail := new(node) + head.next = tail + tail.prev = head + return LRUCache{ + capacity: capacity, + cache: make(map[int]*node, capacity), + head: head, + tail: tail, + } +} + +func (this *LRUCache) Get(key int) int { + n, ok := this.cache[key] + if !ok { + return -1 + } + this.moveToFront(n) + return n.val +} + +func (this *LRUCache) Put(key int, value int) { + n, ok := this.cache[key] + if ok { + n.val = value + this.moveToFront(n) + return + } + if len(this.cache) == this.capacity { + back := this.tail.prev + this.remove(back) + delete(this.cache, back.key) + } + n = &node{key: key, val: value} + this.pushFront(n) + this.cache[key] = n +} + +func (this *LRUCache) moveToFront(n *node) { + this.remove(n) + this.pushFront(n) +} + +func (this *LRUCache) remove(n *node) { + n.prev.next = n.next + n.next.prev = n.prev + n.prev = nil + n.next = nil +} + +func (this *LRUCache) pushFront(n *node) { + n.prev = this.head + n.next = this.head.next + this.head.next.prev = n + this.head.next = n +} +``` ```ts class LRUCache { @@ -579,7 +430,136 @@ class LRUCache { */ ``` -### **C#** +```rust +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +struct Node { + key: i32, + value: i32, + prev: Option>>, + next: Option>>, +} + +impl Node { + #[inline] + fn new(key: i32, value: i32) -> Self { + Self { + key, + value, + prev: None, + next: None, + } + } +} + +struct LRUCache { + capacity: usize, + cache: HashMap>>, + head: Option>>, + tail: Option>>, +} + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl LRUCache { + fn new(capacity: i32) -> Self { + Self { + capacity: capacity as usize, + cache: HashMap::new(), + head: None, + tail: None, + } + } + + fn get(&mut self, key: i32) -> i32 { + match self.cache.get(&key) { + Some(node) => { + let node = Rc::clone(node); + self.remove(&node); + self.push_front(&node); + let value = node.borrow().value; + value + } + None => -1, + } + } + + fn put(&mut self, key: i32, value: i32) { + match self.cache.get(&key) { + Some(node) => { + let node = Rc::clone(node); + node.borrow_mut().value = value; + self.remove(&node); + self.push_front(&node); + } + None => { + let node = Rc::new(RefCell::new(Node::new(key, value))); + self.cache.insert(key, Rc::clone(&node)); + self.push_front(&node); + if self.cache.len() > self.capacity { + let back_key = self.pop_back().unwrap().borrow().key; + self.cache.remove(&back_key); + } + } + }; + } + + fn push_front(&mut self, node: &Rc>) { + match self.head.take() { + Some(head) => { + head.borrow_mut().prev = Some(Rc::clone(node)); + node.borrow_mut().prev = None; + node.borrow_mut().next = Some(head); + self.head = Some(Rc::clone(node)); + } + None => { + self.head = Some(Rc::clone(node)); + self.tail = Some(Rc::clone(node)); + } + }; + } + + fn remove(&mut self, node: &Rc>) { + match (node.borrow().prev.as_ref(), node.borrow().next.as_ref()) { + (None, None) => { + self.head = None; + self.tail = None; + } + (None, Some(next)) => { + self.head = Some(Rc::clone(next)); + next.borrow_mut().prev = None; + } + (Some(prev), None) => { + self.tail = Some(Rc::clone(prev)); + prev.borrow_mut().next = None; + } + (Some(prev), Some(next)) => { + next.borrow_mut().prev = Some(Rc::clone(prev)); + prev.borrow_mut().next = Some(Rc::clone(next)); + } + }; + } + + fn pop_back(&mut self) -> Option>> { + match self.tail.take() { + Some(tail) => { + self.remove(&tail); + Some(tail) + } + None => None, + } + } +}/** + * Your LRUCache object will be instantiated and called as such: + * let obj = LRUCache::new(capacity); + * let ret_1: i32 = obj.get(key); + * obj.put(key, value); + */ +``` ```cs public class LRUCache { @@ -660,10 +640,6 @@ public class LRUCache { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0146.LRU Cache/README_EN.md b/solution/0100-0199/0146.LRU Cache/README_EN.md index b08cde0ccc38b..4fce6dd033b14 100644 --- a/solution/0100-0199/0146.LRU Cache/README_EN.md +++ b/solution/0100-0199/0146.LRU Cache/README_EN.md @@ -51,9 +51,9 @@ lRUCache.get(4); // return 4 ## Solutions - +### Solution 1 -### **Python3** + ```python class Node: @@ -122,8 +122,6 @@ class LRUCache: # obj.put(key,value) ``` -### **Java** - ```java class Node { int key; @@ -212,214 +210,6 @@ class LRUCache { */ ``` -### **Rust** - -```rust -use std::cell::RefCell; -use std::collections::HashMap; -use std::rc::Rc; - -struct Node { - key: i32, - value: i32, - prev: Option>>, - next: Option>>, -} - -impl Node { - #[inline] - fn new(key: i32, value: i32) -> Self { - Self { - key, - value, - prev: None, - next: None, - } - } -} - -struct LRUCache { - capacity: usize, - cache: HashMap>>, - head: Option>>, - tail: Option>>, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl LRUCache { - fn new(capacity: i32) -> Self { - Self { - capacity: capacity as usize, - cache: HashMap::new(), - head: None, - tail: None, - } - } - - fn get(&mut self, key: i32) -> i32 { - match self.cache.get(&key) { - Some(node) => { - let node = Rc::clone(node); - self.remove(&node); - self.push_front(&node); - let value = node.borrow().value; - value - } - None => -1, - } - } - - fn put(&mut self, key: i32, value: i32) { - match self.cache.get(&key) { - Some(node) => { - let node = Rc::clone(node); - node.borrow_mut().value = value; - self.remove(&node); - self.push_front(&node); - } - None => { - let node = Rc::new(RefCell::new(Node::new(key, value))); - self.cache.insert(key, Rc::clone(&node)); - self.push_front(&node); - if self.cache.len() > self.capacity { - let back_key = self.pop_back().unwrap().borrow().key; - self.cache.remove(&back_key); - } - } - }; - } - - fn push_front(&mut self, node: &Rc>) { - match self.head.take() { - Some(head) => { - head.borrow_mut().prev = Some(Rc::clone(node)); - node.borrow_mut().prev = None; - node.borrow_mut().next = Some(head); - self.head = Some(Rc::clone(node)); - } - None => { - self.head = Some(Rc::clone(node)); - self.tail = Some(Rc::clone(node)); - } - }; - } - - fn remove(&mut self, node: &Rc>) { - match (node.borrow().prev.as_ref(), node.borrow().next.as_ref()) { - (None, None) => { - self.head = None; - self.tail = None; - } - (None, Some(next)) => { - self.head = Some(Rc::clone(next)); - next.borrow_mut().prev = None; - } - (Some(prev), None) => { - self.tail = Some(Rc::clone(prev)); - prev.borrow_mut().next = None; - } - (Some(prev), Some(next)) => { - next.borrow_mut().prev = Some(Rc::clone(prev)); - prev.borrow_mut().next = Some(Rc::clone(next)); - } - }; - } - - fn pop_back(&mut self) -> Option>> { - match self.tail.take() { - Some(tail) => { - self.remove(&tail); - Some(tail) - } - None => None, - } - } -}/** - * Your LRUCache object will be instantiated and called as such: - * let obj = LRUCache::new(capacity); - * let ret_1: i32 = obj.get(key); - * obj.put(key, value); - */ -``` - -### **Go** - -```go -type node struct { - key, val int - prev, next *node -} - -type LRUCache struct { - capacity int - cache map[int]*node - head, tail *node -} - -func Constructor(capacity int) LRUCache { - head := new(node) - tail := new(node) - head.next = tail - tail.prev = head - return LRUCache{ - capacity: capacity, - cache: make(map[int]*node, capacity), - head: head, - tail: tail, - } -} - -func (this *LRUCache) Get(key int) int { - n, ok := this.cache[key] - if !ok { - return -1 - } - this.moveToFront(n) - return n.val -} - -func (this *LRUCache) Put(key int, value int) { - n, ok := this.cache[key] - if ok { - n.val = value - this.moveToFront(n) - return - } - if len(this.cache) == this.capacity { - back := this.tail.prev - this.remove(back) - delete(this.cache, back.key) - } - n = &node{key: key, val: value} - this.pushFront(n) - this.cache[key] = n -} - -func (this *LRUCache) moveToFront(n *node) { - this.remove(n) - this.pushFront(n) -} - -func (this *LRUCache) remove(n *node) { - n.prev.next = n.next - n.next.prev = n.prev - n.prev = nil - n.next = nil -} - -func (this *LRUCache) pushFront(n *node) { - n.prev = this.head - n.next = this.head.next - this.head.next.prev = n - this.head.next = n -} -``` - -### **C++** - ```cpp struct Node { int k; @@ -514,7 +304,76 @@ private: */ ``` -### **TypeScript** +```go +type node struct { + key, val int + prev, next *node +} + +type LRUCache struct { + capacity int + cache map[int]*node + head, tail *node +} + +func Constructor(capacity int) LRUCache { + head := new(node) + tail := new(node) + head.next = tail + tail.prev = head + return LRUCache{ + capacity: capacity, + cache: make(map[int]*node, capacity), + head: head, + tail: tail, + } +} + +func (this *LRUCache) Get(key int) int { + n, ok := this.cache[key] + if !ok { + return -1 + } + this.moveToFront(n) + return n.val +} + +func (this *LRUCache) Put(key int, value int) { + n, ok := this.cache[key] + if ok { + n.val = value + this.moveToFront(n) + return + } + if len(this.cache) == this.capacity { + back := this.tail.prev + this.remove(back) + delete(this.cache, back.key) + } + n = &node{key: key, val: value} + this.pushFront(n) + this.cache[key] = n +} + +func (this *LRUCache) moveToFront(n *node) { + this.remove(n) + this.pushFront(n) +} + +func (this *LRUCache) remove(n *node) { + n.prev.next = n.next + n.next.prev = n.prev + n.prev = nil + n.next = nil +} + +func (this *LRUCache) pushFront(n *node) { + n.prev = this.head + n.next = this.head.next + this.head.next.prev = n + this.head.next = n +} +``` ```ts class LRUCache { @@ -552,7 +411,136 @@ class LRUCache { */ ``` -### **C#** +```rust +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +struct Node { + key: i32, + value: i32, + prev: Option>>, + next: Option>>, +} + +impl Node { + #[inline] + fn new(key: i32, value: i32) -> Self { + Self { + key, + value, + prev: None, + next: None, + } + } +} + +struct LRUCache { + capacity: usize, + cache: HashMap>>, + head: Option>>, + tail: Option>>, +} + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl LRUCache { + fn new(capacity: i32) -> Self { + Self { + capacity: capacity as usize, + cache: HashMap::new(), + head: None, + tail: None, + } + } + + fn get(&mut self, key: i32) -> i32 { + match self.cache.get(&key) { + Some(node) => { + let node = Rc::clone(node); + self.remove(&node); + self.push_front(&node); + let value = node.borrow().value; + value + } + None => -1, + } + } + + fn put(&mut self, key: i32, value: i32) { + match self.cache.get(&key) { + Some(node) => { + let node = Rc::clone(node); + node.borrow_mut().value = value; + self.remove(&node); + self.push_front(&node); + } + None => { + let node = Rc::new(RefCell::new(Node::new(key, value))); + self.cache.insert(key, Rc::clone(&node)); + self.push_front(&node); + if self.cache.len() > self.capacity { + let back_key = self.pop_back().unwrap().borrow().key; + self.cache.remove(&back_key); + } + } + }; + } + + fn push_front(&mut self, node: &Rc>) { + match self.head.take() { + Some(head) => { + head.borrow_mut().prev = Some(Rc::clone(node)); + node.borrow_mut().prev = None; + node.borrow_mut().next = Some(head); + self.head = Some(Rc::clone(node)); + } + None => { + self.head = Some(Rc::clone(node)); + self.tail = Some(Rc::clone(node)); + } + }; + } + + fn remove(&mut self, node: &Rc>) { + match (node.borrow().prev.as_ref(), node.borrow().next.as_ref()) { + (None, None) => { + self.head = None; + self.tail = None; + } + (None, Some(next)) => { + self.head = Some(Rc::clone(next)); + next.borrow_mut().prev = None; + } + (Some(prev), None) => { + self.tail = Some(Rc::clone(prev)); + prev.borrow_mut().next = None; + } + (Some(prev), Some(next)) => { + next.borrow_mut().prev = Some(Rc::clone(prev)); + prev.borrow_mut().next = Some(Rc::clone(next)); + } + }; + } + + fn pop_back(&mut self) -> Option>> { + match self.tail.take() { + Some(tail) => { + self.remove(&tail); + Some(tail) + } + None => None, + } + } +}/** + * Your LRUCache object will be instantiated and called as such: + * let obj = LRUCache::new(capacity); + * let ret_1: i32 = obj.get(key); + * obj.put(key, value); + */ +``` ```cs public class LRUCache { @@ -633,10 +621,6 @@ public class LRUCache { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0147.Insertion Sort List/README.md b/solution/0100-0199/0147.Insertion Sort List/README.md index d0d4f024ae956..13a3b972c5c20 100644 --- a/solution/0100-0199/0147.Insertion Sort List/README.md +++ b/solution/0100-0199/0147.Insertion Sort List/README.md @@ -53,21 +53,10 @@ ## 解法 - - -遍历链表,每次将遍历到的结点 cur 与前一个结点 pre 进行值比较: - -- 若结点 cur 的值比 pre 的大,说明当前 cur 已在正确的位置,直接往下遍历。 -- 否则,从链表第一个结点开始遍历,将结点 cur 插入到正确的位置。 - -依次遍历,直至 cur 指向空,遍历结束。 +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -95,10 +84,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -138,8 +123,6 @@ class Solution { } ``` -### **JavaScript** - ```js /** * Definition for singly-linked list. @@ -177,10 +160,6 @@ var insertionSortList = function (head) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0147.Insertion Sort List/README_EN.md b/solution/0100-0199/0147.Insertion Sort List/README_EN.md index 8719609df7eb2..2d97ba7845e03 100644 --- a/solution/0100-0199/0147.Insertion Sort List/README_EN.md +++ b/solution/0100-0199/0147.Insertion Sort List/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -72,8 +72,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -113,8 +111,6 @@ class Solution { } ``` -### **JavaScript** - ```js /** * Definition for singly-linked list. @@ -152,10 +148,6 @@ var insertionSortList = function (head) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0148.Sort List/README.md b/solution/0100-0199/0148.Sort List/README.md index 8e048e0010640..194c4bc38092b 100644 --- a/solution/0100-0199/0148.Sort List/README.md +++ b/solution/0100-0199/0148.Sort List/README.md @@ -49,16 +49,10 @@ ## 解法 - - -先用快慢指针找到链表中点,然后分成左右两个链表,递归排序左右链表。最后合并两个排序的链表即可。 +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -89,10 +83,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -181,8 +169,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -223,105 +209,6 @@ func sortList(head *ListNode) *ListNode { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @return {ListNode} - */ -var sortList = function (head) { - if (!head || !head.next) { - return head; - } - let slow = head; - let fast = head.next; - while (fast && fast.next) { - slow = slow.next; - fast = fast.next.next; - } - let t = slow.next; - slow.next = null; - let l1 = sortList(head); - let l2 = sortList(t); - const dummy = new ListNode(); - let cur = dummy; - while (l1 && l2) { - if (l1.val <= l2.val) { - cur.next = l1; - l1 = l1.next; - } else { - cur.next = l2; - l2 = l2.next; - } - cur = cur.next; - } - cur.next = l1 || l2; - return dummy.next; -}; -``` - -### **C#** - -```cs -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public ListNode SortList(ListNode head) { - if (head == null || head.next == null) - { - return head; - } - ListNode slow = head, fast = head.next; - while (fast != null && fast.next != null) - { - slow = slow.next; - fast = fast.next.next; - } - ListNode t = slow.next; - slow.next = null; - ListNode l1 = SortList(head); - ListNode l2 = SortList(t); - ListNode dummy = new ListNode(); - ListNode cur = dummy; - while (l1 != null && l2 != null) - { - if (l1.val <= l2.val) - { - cur.next = l1; - l1 = l1.next; - } - else - { - cur.next = l2; - l2 = l2.next; - } - cur = cur.next; - } - cur.next = l1 == null ? l2 : l1; - return dummy.next; - } -} -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -366,8 +253,6 @@ function sortList(head: ListNode | null): ListNode | null { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -427,10 +312,99 @@ impl Solution { } ``` -### **...** - +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var sortList = function (head) { + if (!head || !head.next) { + return head; + } + let slow = head; + let fast = head.next; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + let t = slow.next; + slow.next = null; + let l1 = sortList(head); + let l2 = sortList(t); + const dummy = new ListNode(); + let cur = dummy; + while (l1 && l2) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 || l2; + return dummy.next; +}; ``` +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode SortList(ListNode head) { + if (head == null || head.next == null) + { + return head; + } + ListNode slow = head, fast = head.next; + while (fast != null && fast.next != null) + { + slow = slow.next; + fast = fast.next.next; + } + ListNode t = slow.next; + slow.next = null; + ListNode l1 = SortList(head); + ListNode l2 = SortList(t); + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (l1 != null && l2 != null) + { + if (l1.val <= l2.val) + { + cur.next = l1; + l1 = l1.next; + } + else + { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} ``` + + diff --git a/solution/0100-0199/0148.Sort List/README_EN.md b/solution/0100-0199/0148.Sort List/README_EN.md index 4fa11027d1647..dbbb29ebd6cb1 100644 --- a/solution/0100-0199/0148.Sort List/README_EN.md +++ b/solution/0100-0199/0148.Sort List/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -75,8 +75,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -120,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -165,8 +161,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -207,105 +201,6 @@ func sortList(head *ListNode) *ListNode { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @return {ListNode} - */ -var sortList = function (head) { - if (!head || !head.next) { - return head; - } - let slow = head; - let fast = head.next; - while (fast && fast.next) { - slow = slow.next; - fast = fast.next.next; - } - let t = slow.next; - slow.next = null; - let l1 = sortList(head); - let l2 = sortList(t); - const dummy = new ListNode(); - let cur = dummy; - while (l1 && l2) { - if (l1.val <= l2.val) { - cur.next = l1; - l1 = l1.next; - } else { - cur.next = l2; - l2 = l2.next; - } - cur = cur.next; - } - cur.next = l1 || l2; - return dummy.next; -}; -``` - -### **C#** - -```cs -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -public class Solution { - public ListNode SortList(ListNode head) { - if (head == null || head.next == null) - { - return head; - } - ListNode slow = head, fast = head.next; - while (fast != null && fast.next != null) - { - slow = slow.next; - fast = fast.next.next; - } - ListNode t = slow.next; - slow.next = null; - ListNode l1 = SortList(head); - ListNode l2 = SortList(t); - ListNode dummy = new ListNode(); - ListNode cur = dummy; - while (l1 != null && l2 != null) - { - if (l1.val <= l2.val) - { - cur.next = l1; - l1 = l1.next; - } - else - { - cur.next = l2; - l2 = l2.next; - } - cur = cur.next; - } - cur.next = l1 == null ? l2 : l1; - return dummy.next; - } -} -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -321,14 +216,14 @@ public class Solution { function sortList(head: ListNode | null): ListNode | null { if (head == null || head.next == null) return head; - // slow and fast pointer to locate the middle node + // 快慢指针定位中点 let slow: ListNode = head, fast: ListNode = head.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } - // merge sort + // 归并排序 let mid: ListNode = slow.next; slow.next = null; let l1: ListNode = sortList(head); @@ -350,8 +245,6 @@ function sortList(head: ListNode | null): ListNode | null { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -411,10 +304,99 @@ impl Solution { } ``` -### **...** - +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var sortList = function (head) { + if (!head || !head.next) { + return head; + } + let slow = head; + let fast = head.next; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + let t = slow.next; + slow.next = null; + let l1 = sortList(head); + let l2 = sortList(t); + const dummy = new ListNode(); + let cur = dummy; + while (l1 && l2) { + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 || l2; + return dummy.next; +}; ``` +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode SortList(ListNode head) { + if (head == null || head.next == null) + { + return head; + } + ListNode slow = head, fast = head.next; + while (fast != null && fast.next != null) + { + slow = slow.next; + fast = fast.next.next; + } + ListNode t = slow.next; + slow.next = null; + ListNode l1 = SortList(head); + ListNode l2 = SortList(t); + ListNode dummy = new ListNode(); + ListNode cur = dummy; + while (l1 != null && l2 != null) + { + if (l1.val <= l2.val) + { + cur.next = l1; + l1 = l1.next; + } + else + { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + cur.next = l1 == null ? l2 : l1; + return dummy.next; + } +} ``` + + diff --git a/solution/0100-0199/0149.Max Points on a Line/README.md b/solution/0100-0199/0149.Max Points on a Line/README.md index c5af53fffaa46..a368bc2f8e9e6 100644 --- a/solution/0100-0199/0149.Max Points on a Line/README.md +++ b/solution/0100-0199/0149.Max Points on a Line/README.md @@ -37,30 +37,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` 所有横纵坐标差的最大值。 - -相似题目: - -- [面试题 16.14. 最佳直线](/lcci/16.14.Best%20Line/README.md) - -### **Python3** - - - ```python class Solution: def maxPoints(self, points: List[List[int]]) -> int: @@ -80,31 +64,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxPoints(self, points: List[List[int]]) -> int: - def gcd(a, b): - return a if b == 0 else gcd(b, a % b) - - n = len(points) - ans = 1 - for i in range(n): - x1, y1 = points[i] - cnt = Counter() - 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] += 1 - ans = max(ans, cnt[k] + 1) - return ans -``` - -### **Java** - - - ```java class Solution { public int maxPoints(int[][] points) { @@ -131,39 +90,61 @@ class Solution { } ``` -```java +```cpp class Solution { - public int maxPoints(int[][] points) { - int n = points.length; +public: + int maxPoints(vector>& points) { + int n = points.size(); int ans = 1; for (int i = 0; i < n; ++i) { int x1 = points[i][0], y1 = points[i][1]; - Map cnt = new HashMap<>(); for (int j = i + 1; j < n; ++j) { int x2 = points[j][0], y2 = points[j][1]; - int dx = x2 - x1, dy = y2 - y1; - int g = gcd(dx, dy); - String k = (dx / g) + "." + (dy / g); - cnt.put(k, cnt.getOrDefault(k, 0) + 1); - ans = Math.max(ans, cnt.get(k) + 1); + int cnt = 2; + for (int k = j + 1; k < n; ++k) { + int x3 = points[k][0], y3 = points[k][1]; + int a = (y2 - y1) * (x3 - x1); + int b = (y3 - y1) * (x2 - x1); + cnt += a == b; + } + ans = max(ans, cnt); } } return ans; } +}; +``` - private int gcd(int a, int b) { - return b == 0 ? a : gcd(b, a % b); - } +```go +func maxPoints(points [][]int) int { + n := len(points) + ans := 1 + 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 ans < cnt { + ans = cnt + } + } + } + return ans } ``` -### **C++** - -```cpp -class Solution { -public: - int maxPoints(vector>& points) { - int n = points.size(); +```cs +public class Solution { + public int MaxPoints(int[][] points) { + int n = points.Length; int ans = 1; for (int i = 0; i < n; ++i) { int x1 = points[i][0], y1 = points[i][1]; @@ -174,14 +155,79 @@ public: int x3 = points[k][0], y3 = points[k][1]; int a = (y2 - y1) * (x3 - x1); int b = (y3 - y1) * (x2 - x1); - cnt += a == b; + if (a == b) { + ++cnt; + } + } + if (ans < cnt) { + ans = cnt; } - ans = max(ans, cnt); } } 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` 所有横纵坐标差的最大值。 + +相似题目: + +- [面试题 16.14. 最佳直线](/lcci/16.14.Best%20Line/README.md) + + + +```python +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + def gcd(a, b): + return a if b == 0 else gcd(b, a % b) + + n = len(points) + ans = 1 + for i in range(n): + x1, y1 = points[i] + cnt = Counter() + 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] += 1 + ans = max(ans, cnt[k] + 1) + return ans +``` + +```java +class Solution { + public int maxPoints(int[][] points) { + int n = points.length; + int ans = 1; + for (int i = 0; i < n; ++i) { + int x1 = points[i][0], y1 = points[i][1]; + Map cnt = new HashMap<>(); + for (int j = i + 1; j < n; ++j) { + int x2 = points[j][0], y2 = points[j][1]; + int dx = x2 - x1, dy = y2 - y1; + int g = gcd(dx, dy); + String k = (dx / g) + "." + (dy / g); + cnt.put(k, cnt.getOrDefault(k, 0) + 1); + ans = Math.max(ans, cnt.get(k) + 1); + } + } + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} ``` ```cpp @@ -210,34 +256,6 @@ public: }; ``` -### **Go** - -```go -func maxPoints(points [][]int) int { - n := len(points) - ans := 1 - 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 ans < cnt { - ans = cnt - } - } - } - return ans -} -``` - ```go func maxPoints(points [][]int) int { n := len(points) @@ -268,40 +286,6 @@ func gcd(a, b int) int { } ``` -### **C#** - -```cs -public class Solution { - public int MaxPoints(int[][] points) { - int n = points.Length; - int ans = 1; - 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]; - int a = (y2 - y1) * (x3 - x1); - int b = (y3 - y1) * (x2 - x1); - if (a == b) { - ++cnt; - } - } - if (ans < cnt) { - ans = cnt; - } - } - } - return ans; - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0149.Max Points on a Line/README_EN.md b/solution/0100-0199/0149.Max Points on a Line/README_EN.md index c6457bf5dec98..932098fe9c9de 100644 --- a/solution/0100-0199/0149.Max Points on a Line/README_EN.md +++ b/solution/0100-0199/0149.Max Points on a Line/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,29 +56,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxPoints(self, points: List[List[int]]) -> int: - def gcd(a, b): - return a if b == 0 else gcd(b, a % b) - - n = len(points) - ans = 1 - for i in range(n): - x1, y1 = points[i] - cnt = Counter() - 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] += 1 - ans = max(ans, cnt[k] + 1) - return ans -``` - -### **Java** - ```java class Solution { public int maxPoints(int[][] points) { @@ -105,39 +82,61 @@ class Solution { } ``` -```java +```cpp class Solution { - public int maxPoints(int[][] points) { - int n = points.length; +public: + int maxPoints(vector>& points) { + int n = points.size(); int ans = 1; for (int i = 0; i < n; ++i) { int x1 = points[i][0], y1 = points[i][1]; - Map cnt = new HashMap<>(); for (int j = i + 1; j < n; ++j) { int x2 = points[j][0], y2 = points[j][1]; - int dx = x2 - x1, dy = y2 - y1; - int g = gcd(dx, dy); - String k = (dx / g) + "." + (dy / g); - cnt.put(k, cnt.getOrDefault(k, 0) + 1); - ans = Math.max(ans, cnt.get(k) + 1); + int cnt = 2; + for (int k = j + 1; k < n; ++k) { + int x3 = points[k][0], y3 = points[k][1]; + int a = (y2 - y1) * (x3 - x1); + int b = (y3 - y1) * (x2 - x1); + cnt += a == b; + } + ans = max(ans, cnt); } } return ans; } +}; +``` - private int gcd(int a, int b) { - return b == 0 ? a : gcd(b, a % b); - } +```go +func maxPoints(points [][]int) int { + n := len(points) + ans := 1 + 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 ans < cnt { + ans = cnt + } + } + } + return ans } ``` -### **C++** - -```cpp -class Solution { -public: - int maxPoints(vector>& points) { - int n = points.size(); +```cs +public class Solution { + public int MaxPoints(int[][] points) { + int n = points.Length; int ans = 1; for (int i = 0; i < n; ++i) { int x1 = points[i][0], y1 = points[i][1]; @@ -148,14 +147,71 @@ public: int x3 = points[k][0], y3 = points[k][1]; int a = (y2 - y1) * (x3 - x1); int b = (y3 - y1) * (x2 - x1); - cnt += a == b; + if (a == b) { + ++cnt; + } + } + if (ans < cnt) { + ans = cnt; } - ans = max(ans, cnt); } } return ans; } -}; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + def gcd(a, b): + return a if b == 0 else gcd(b, a % b) + + n = len(points) + ans = 1 + for i in range(n): + x1, y1 = points[i] + cnt = Counter() + 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] += 1 + ans = max(ans, cnt[k] + 1) + return ans +``` + +```java +class Solution { + public int maxPoints(int[][] points) { + int n = points.length; + int ans = 1; + for (int i = 0; i < n; ++i) { + int x1 = points[i][0], y1 = points[i][1]; + Map cnt = new HashMap<>(); + for (int j = i + 1; j < n; ++j) { + int x2 = points[j][0], y2 = points[j][1]; + int dx = x2 - x1, dy = y2 - y1; + int g = gcd(dx, dy); + String k = (dx / g) + "." + (dy / g); + cnt.put(k, cnt.getOrDefault(k, 0) + 1); + ans = Math.max(ans, cnt.get(k) + 1); + } + } + return ans; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} ``` ```cpp @@ -184,34 +240,6 @@ public: }; ``` -### **Go** - -```go -func maxPoints(points [][]int) int { - n := len(points) - ans := 1 - 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 ans < cnt { - ans = cnt - } - } - } - return ans -} -``` - ```go func maxPoints(points [][]int) int { n := len(points) @@ -242,40 +270,6 @@ func gcd(a, b int) int { } ``` -### **C#** - -```cs -public class Solution { - public int MaxPoints(int[][] points) { - int n = points.Length; - int ans = 1; - 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]; - int a = (y2 - y1) * (x3 - x1); - int b = (y3 - y1) * (x2 - x1); - if (a == b) { - ++cnt; - } - } - if (ans < cnt) { - ans = cnt; - } - } - } - return ans; - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0150.Evaluate Reverse Polish Notation/README.md b/solution/0100-0199/0150.Evaluate Reverse Polish Notation/README.md index b27fe526c5c91..3ad4f39bb4221 100644 --- a/solution/0100-0199/0150.Evaluate Reverse Polish Notation/README.md +++ b/solution/0100-0199/0150.Evaluate Reverse Polish Notation/README.md @@ -82,16 +82,10 @@ ## 解法 - - -利用栈存储运算数,每次遇到符号,对栈顶两个元素进行运算。 +### 方法一 -### **Python3** - - - ```python import operator @@ -113,32 +107,6 @@ class Solution: return s[0] ``` -需要注意 Python 的整除对负数也是向下取整(例如:`6 // -132 = -1`),和答案对应不上,所以需要特殊处理。 - -```python -class Solution: - def evalRPN(self, tokens: List[str]) -> int: - nums = [] - for t in tokens: - if len(t) > 1 or t.isdigit(): - nums.append(int(t)) - else: - if t == "+": - nums[-2] += nums[-1] - elif t == "-": - nums[-2] -= nums[-1] - elif t == "*": - nums[-2] *= nums[-1] - else: - nums[-2] = int(nums[-2] / nums[-1]) - nums.pop() - return nums[0] -``` - -### **Java** - - - ```java class Solution { public int evalRPN(String[] tokens) { @@ -170,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -200,8 +166,6 @@ public: }; ``` -### **Go** - ```go func evalRPN(tokens []string) int { // https://github.com/emirpasic/gods#arraystack @@ -234,43 +198,6 @@ func popInt(stack *arraystack.Stack) int { } ``` -### **C#** - -```cs -using System.Collections.Generic; - -public class Solution { - public int EvalRPN(string[] tokens) { - var stack = new Stack(); - foreach (var token in tokens) - { - switch (token) - { - case "+": - stack.Push(stack.Pop() + stack.Pop()); - break; - case "-": - stack.Push(-stack.Pop() + stack.Pop()); - break; - case "*": - stack.Push(stack.Pop() * stack.Pop()); - break; - case "/": - var right = stack.Pop(); - stack.Push(stack.Pop() / right); - break; - default: - stack.Push(int.Parse(token)); - break; - } - } - return stack.Pop(); - } -} -``` - -### **TypeScript** - ```ts function evalRPN(tokens: string[]): number { const stack = []; @@ -300,8 +227,6 @@ function evalRPN(tokens: string[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn eval_rpn(tokens: Vec) -> i32 { @@ -327,10 +252,65 @@ impl Solution { } ``` -### **...** +```cs +using System.Collections.Generic; +public class Solution { + public int EvalRPN(string[] tokens) { + var stack = new Stack(); + foreach (var token in tokens) + { + switch (token) + { + case "+": + stack.Push(stack.Pop() + stack.Pop()); + break; + case "-": + stack.Push(-stack.Pop() + stack.Pop()); + break; + case "*": + stack.Push(stack.Pop() * stack.Pop()); + break; + case "/": + var right = stack.Pop(); + stack.Push(stack.Pop() / right); + break; + default: + stack.Push(int.Parse(token)); + break; + } + } + return stack.Pop(); + } +} ``` + + +### 方法二 + + + +```python +class Solution: + def evalRPN(self, tokens: List[str]) -> int: + nums = [] + for t in tokens: + if len(t) > 1 or t.isdigit(): + nums.append(int(t)) + else: + if t == "+": + nums[-2] += nums[-1] + elif t == "-": + nums[-2] -= nums[-1] + elif t == "*": + nums[-2] *= nums[-1] + else: + nums[-2] = int(nums[-2] / nums[-1]) + nums.pop() + return nums[0] ``` + + diff --git a/solution/0100-0199/0150.Evaluate Reverse Polish Notation/README_EN.md b/solution/0100-0199/0150.Evaluate Reverse Polish Notation/README_EN.md index 4cc50b8f199da..c2636cd5b43ce 100644 --- a/solution/0100-0199/0150.Evaluate Reverse Polish Notation/README_EN.md +++ b/solution/0100-0199/0150.Evaluate Reverse Polish Notation/README_EN.md @@ -60,9 +60,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python import operator @@ -85,28 +85,6 @@ class Solution: return s[0] ``` -```python -class Solution: - def evalRPN(self, tokens: List[str]) -> int: - nums = [] - for t in tokens: - if len(t) > 1 or t.isdigit(): - nums.append(int(t)) - else: - if t == "+": - nums[-2] += nums[-1] - elif t == "-": - nums[-2] -= nums[-1] - elif t == "*": - nums[-2] *= nums[-1] - else: - nums[-2] = int(nums[-2] / nums[-1]) - nums.pop() - return nums[0] -``` - -### **Java** - ```java class Solution { public int evalRPN(String[] tokens) { @@ -138,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +144,6 @@ public: }; ``` -### **Go** - ```go func evalRPN(tokens []string) int { // https://github.com/emirpasic/gods#arraystack @@ -202,43 +176,6 @@ func popInt(stack *arraystack.Stack) int { } ``` -### **C#** - -```cs -using System.Collections.Generic; - -public class Solution { - public int EvalRPN(string[] tokens) { - var stack = new Stack(); - foreach (var token in tokens) - { - switch (token) - { - case "+": - stack.Push(stack.Pop() + stack.Pop()); - break; - case "-": - stack.Push(-stack.Pop() + stack.Pop()); - break; - case "*": - stack.Push(stack.Pop() * stack.Pop()); - break; - case "/": - var right = stack.Pop(); - stack.Push(stack.Pop() / right); - break; - default: - stack.Push(int.Parse(token)); - break; - } - } - return stack.Pop(); - } -} -``` - -### **TypeScript** - ```ts function evalRPN(tokens: string[]): number { const stack = []; @@ -268,8 +205,6 @@ function evalRPN(tokens: string[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn eval_rpn(tokens: Vec) -> i32 { @@ -295,10 +230,65 @@ impl Solution { } ``` -### **...** +```cs +using System.Collections.Generic; +public class Solution { + public int EvalRPN(string[] tokens) { + var stack = new Stack(); + foreach (var token in tokens) + { + switch (token) + { + case "+": + stack.Push(stack.Pop() + stack.Pop()); + break; + case "-": + stack.Push(-stack.Pop() + stack.Pop()); + break; + case "*": + stack.Push(stack.Pop() * stack.Pop()); + break; + case "/": + var right = stack.Pop(); + stack.Push(stack.Pop() / right); + break; + default: + stack.Push(int.Parse(token)); + break; + } + } + return stack.Pop(); + } +} ``` + + +### Solution 2 + + + +```python +class Solution: + def evalRPN(self, tokens: List[str]) -> int: + nums = [] + for t in tokens: + if len(t) > 1 or t.isdigit(): + nums.append(int(t)) + else: + if t == "+": + nums[-2] += nums[-1] + elif t == "-": + nums[-2] -= nums[-1] + elif t == "*": + nums[-2] *= nums[-1] + else: + nums[-2] = int(nums[-2] / nums[-1]) + nums.pop() + return nums[0] ``` + + diff --git a/solution/0100-0199/0151.Reverse Words in a String/README.md b/solution/0100-0199/0151.Reverse Words in a String/README.md index 3511aac0ea97f..4ac7ec05cd8a8 100644 --- a/solution/0100-0199/0151.Reverse Words in a String/README.md +++ b/solution/0100-0199/0151.Reverse Words in a String/README.md @@ -58,53 +58,20 @@ ## 解法 - - -**方法一:使用语言自带的函数** +### 方法一:使用语言自带的函数 我们将字符串按照空格分割成字符串列表,然后将列表反转,最后将列表拼接成以空格分割的字符串即可。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串的长度。 -**方法二:双指针** - -我们可以使用双指针 $i$ 和 $j$,每次找到一个单词,将其添加到结果列表中,最后将结果列表反转,再拼接成字符串即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串的长度。 - -### **Python3** - - - ```python class Solution: def reverseWords(self, s: str) -> str: return ' '.join(reversed(s.split())) ``` -```python -class Solution: - def reverseWords(self, s: str) -> str: - ans = [] - i, n = 0, len(s) - while i < n: - while i < n and s[i] == ' ': - i += 1 - if i < n: - j = i - while j < n and s[j] != ' ': - j += 1 - ans.append(s[i:j]) - i = j - return ' '.join(ans[::-1]) -``` - -### **Java** - - - ```java class Solution { public String reverseWords(String s) { @@ -115,33 +82,6 @@ class Solution { } ``` -```java -class Solution { - public String reverseWords(String s) { - List words = new ArrayList<>(); - int n = s.length(); - for (int i = 0; i < n;) { - while (i < n && s.charAt(i) == ' ') { - ++i; - } - if (i < n) { - StringBuilder t = new StringBuilder(); - int j = i; - while (j < n && s.charAt(j) != ' ') { - t.append(s.charAt(j++)); - } - words.add(t.toString()); - i = j; - } - } - Collections.reverse(words); - return String.join(" ", words); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -172,8 +112,6 @@ public: }; ``` -### **Go** - ```go func reverseWords(s string) string { words := strings.Split(s, " ") @@ -187,26 +125,12 @@ func reverseWords(s string) string { } ``` -### **C#** - -```cs -public class Solution { - public string ReverseWords(string s) { - return string.Join(" ", s.Trim().Split(" ").Where(word => !string.IsNullOrEmpty(word) && !string.IsNullOrEmpty(word.Trim())).Reverse()); - } -} -``` - -### **TypeScript** - ```ts function reverseWords(s: string): string { return s.trim().split(/\s+/).reverse().join(' '); } ``` -### **Rust** - ```rust impl Solution { pub fn reverse_words(s: String) -> String { @@ -215,10 +139,66 @@ impl Solution { } ``` -### **...** +```cs +public class Solution { + public string ReverseWords(string s) { + return string.Join(" ", s.Trim().Split(" ").Where(word => !string.IsNullOrEmpty(word) && !string.IsNullOrEmpty(word.Trim())).Reverse()); + } +} +``` + + + +### 方法二:双指针 +我们可以使用双指针 $i$ 和 $j$,每次找到一个单词,将其添加到结果列表中,最后将结果列表反转,再拼接成字符串即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串的长度。 + + + +```python +class Solution: + def reverseWords(self, s: str) -> str: + ans = [] + i, n = 0, len(s) + while i < n: + while i < n and s[i] == ' ': + i += 1 + if i < n: + j = i + while j < n and s[j] != ' ': + j += 1 + ans.append(s[i:j]) + i = j + return ' '.join(ans[::-1]) ``` +```java +class Solution { + public String reverseWords(String s) { + List words = new ArrayList<>(); + int n = s.length(); + for (int i = 0; i < n;) { + while (i < n && s.charAt(i) == ' ') { + ++i; + } + if (i < n) { + StringBuilder t = new StringBuilder(); + int j = i; + while (j < n && s.charAt(j) != ' ') { + t.append(s.charAt(j++)); + } + words.add(t.toString()); + i = j; + } + } + Collections.reverse(words); + return String.join(" ", words); + } +} ``` + + diff --git a/solution/0100-0199/0151.Reverse Words in a String/README_EN.md b/solution/0100-0199/0151.Reverse Words in a String/README_EN.md index 0909264ae35dd..067c75f3c7b5a 100644 --- a/solution/0100-0199/0151.Reverse Words in a String/README_EN.md +++ b/solution/0100-0199/0151.Reverse Words in a String/README_EN.md @@ -50,47 +50,20 @@ ## Solutions -**Solution 1: Use Language Built-in Functions** +### Solution 1: Use Language Built-in Functions We split the string into a list of strings by spaces, then reverse the list, and finally join the list into a string separated by spaces. Time complexity $O(n)$, space complexity $O(n)$, where $n$ is the length of the string. -**Solution 2: Two Pointers** - -We can use two pointers $i$ and $j$, each time we find a word, add it to the result list, then reverse the result list, and finally join the list into a string. - -Time complexity $O(n)$, space complexity $O(n)$, where $n$ is the length of the string. - -### **Python3** - ```python class Solution: def reverseWords(self, s: str) -> str: return ' '.join(reversed(s.split())) ``` -```python -class Solution: - def reverseWords(self, s: str) -> str: - ans = [] - i, n = 0, len(s) - while i < n: - while i < n and s[i] == ' ': - i += 1 - if i < n: - j = i - while j < n and s[j] != ' ': - j += 1 - ans.append(s[i:j]) - i = j - return ' '.join(ans[::-1]) -``` - -### **Java** - ```java class Solution { public String reverseWords(String s) { @@ -101,33 +74,6 @@ class Solution { } ``` -```java -class Solution { - public String reverseWords(String s) { - List words = new ArrayList<>(); - int n = s.length(); - for (int i = 0; i < n;) { - while (i < n && s.charAt(i) == ' ') { - ++i; - } - if (i < n) { - StringBuilder t = new StringBuilder(); - int j = i; - while (j < n && s.charAt(j) != ' ') { - t.append(s.charAt(j++)); - } - words.add(t.toString()); - i = j; - } - } - Collections.reverse(words); - return String.join(" ", words); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -158,8 +104,6 @@ public: }; ``` -### **Go** - ```go func reverseWords(s string) string { words := strings.Split(s, " ") @@ -173,26 +117,12 @@ func reverseWords(s string) string { } ``` -### **C#** - -```cs -public class Solution { - public string ReverseWords(string s) { - return string.Join(" ", s.Trim().Split(" ").Where(word => !string.IsNullOrEmpty(word) && !string.IsNullOrEmpty(word.Trim())).Reverse()); - } -} -``` - -### **TypeScript** - ```ts function reverseWords(s: string): string { return s.trim().split(/\s+/).reverse().join(' '); } ``` -### **Rust** - ```rust impl Solution { pub fn reverse_words(s: String) -> String { @@ -201,10 +131,66 @@ impl Solution { } ``` -### **...** +```cs +public class Solution { + public string ReverseWords(string s) { + return string.Join(" ", s.Trim().Split(" ").Where(word => !string.IsNullOrEmpty(word) && !string.IsNullOrEmpty(word.Trim())).Reverse()); + } +} +``` + + + +### Solution 2: Two Pointers + +We can use two pointers $i$ and $j$, each time we find a word, add it to the result list, then reverse the result list, and finally join the list into a string. +Time complexity $O(n)$, space complexity $O(n)$, where $n$ is the length of the string. + + + +```python +class Solution: + def reverseWords(self, s: str) -> str: + ans = [] + i, n = 0, len(s) + while i < n: + while i < n and s[i] == ' ': + i += 1 + if i < n: + j = i + while j < n and s[j] != ' ': + j += 1 + ans.append(s[i:j]) + i = j + return ' '.join(ans[::-1]) ``` +```java +class Solution { + public String reverseWords(String s) { + List words = new ArrayList<>(); + int n = s.length(); + for (int i = 0; i < n;) { + while (i < n && s.charAt(i) == ' ') { + ++i; + } + if (i < n) { + StringBuilder t = new StringBuilder(); + int j = i; + while (j < n && s.charAt(j) != ' ') { + t.append(s.charAt(j++)); + } + words.add(t.toString()); + i = j; + } + } + Collections.reverse(words); + return String.join(" ", words); + } +} ``` + + diff --git a/solution/0100-0199/0152.Maximum Product Subarray/README.md b/solution/0100-0199/0152.Maximum Product Subarray/README.md index 646a42998d3ff..980913f32d6bc 100644 --- a/solution/0100-0199/0152.Maximum Product Subarray/README.md +++ b/solution/0100-0199/0152.Maximum Product Subarray/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义两个变量 $f$ 和 $g$,其中 $f$ 表示以 $nums[i]$ 结尾的乘积最大子数组的乘积,而 $g$ 表示以 $nums[i]$ 结尾的乘积最小子数组的乘积。初始时 $f$ 和 $g$ 都等于 $nums[0]$。答案为所有 $f$ 中的最大值。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def maxProduct(self, nums: List[int]) -> int: @@ -71,10 +65,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxProduct(int[] nums) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +96,6 @@ public: }; ``` -### **Go** - ```go func maxProduct(nums []int) int { f, g, ans := nums[0], nums[0], nums[0] @@ -123,8 +109,6 @@ func maxProduct(nums []int) int { } ``` -### **TypeScript** - ```ts function maxProduct(nums: number[]): number { let [f, g, ans] = [nums[0], nums[0], nums[0]]; @@ -138,25 +122,6 @@ function maxProduct(nums: number[]): number { } ``` -### **C#** - -```cs -public class Solution { - public int MaxProduct(int[] nums) { - int f = nums[0], g = nums[0], ans = nums[0]; - for (int i = 1; i < nums.Length; ++i) { - int ff = f, gg = g; - f = Math.Max(nums[i], Math.Max(ff * nums[i], gg * nums[i])); - g = Math.Min(nums[i], Math.Min(ff * nums[i], gg * nums[i])); - ans = Math.Max(ans, f); - } - return ans; - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn max_product(nums: Vec) -> i32 { @@ -174,8 +139,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -193,10 +156,21 @@ var maxProduct = function (nums) { }; ``` -### **...** - -``` - +```cs +public class Solution { + public int MaxProduct(int[] nums) { + int f = nums[0], g = nums[0], ans = nums[0]; + for (int i = 1; i < nums.Length; ++i) { + int ff = f, gg = g; + f = Math.Max(nums[i], Math.Max(ff * nums[i], gg * nums[i])); + g = Math.Min(nums[i], Math.Min(ff * nums[i], gg * nums[i])); + ans = Math.Max(ans, f); + } + return ans; + } +} ``` + + diff --git a/solution/0100-0199/0152.Maximum Product Subarray/README_EN.md b/solution/0100-0199/0152.Maximum Product Subarray/README_EN.md index 2682039b27afb..d926421d37a76 100644 --- a/solution/0100-0199/0152.Maximum Product Subarray/README_EN.md +++ b/solution/0100-0199/0152.Maximum Product Subarray/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxProduct(int[] nums) { @@ -69,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +83,6 @@ public: }; ``` -### **Go** - ```go func maxProduct(nums []int) int { f, g, ans := nums[0], nums[0], nums[0] @@ -102,8 +96,6 @@ func maxProduct(nums []int) int { } ``` -### **TypeScript** - ```ts function maxProduct(nums: number[]): number { let [f, g, ans] = [nums[0], nums[0], nums[0]]; @@ -117,25 +109,6 @@ function maxProduct(nums: number[]): number { } ``` -### **C#** - -```cs -public class Solution { - public int MaxProduct(int[] nums) { - int f = nums[0], g = nums[0], ans = nums[0]; - for (int i = 1; i < nums.Length; ++i) { - int ff = f, gg = g; - f = Math.Max(nums[i], Math.Max(ff * nums[i], gg * nums[i])); - g = Math.Min(nums[i], Math.Min(ff * nums[i], gg * nums[i])); - ans = Math.Max(ans, f); - } - return ans; - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn max_product(nums: Vec) -> i32 { @@ -153,8 +126,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -172,10 +143,21 @@ var maxProduct = function (nums) { }; ``` -### **...** - -``` - +```cs +public class Solution { + public int MaxProduct(int[] nums) { + int f = nums[0], g = nums[0], ans = nums[0]; + for (int i = 1; i < nums.Length; ++i) { + int ff = f, gg = g; + f = Math.Max(nums[i], Math.Max(ff * nums[i], gg * nums[i])); + g = Math.Min(nums[i], Math.Min(ff * nums[i], gg * nums[i])); + ans = Math.Max(ans, f); + } + return ans; + } +} ``` + + diff --git a/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/README.md b/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/README.md index 0b32d409c990f..95be27a3a377a 100644 --- a/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/README.md +++ b/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 初始,判断数组首尾元素的大小关系,若 `nums[0] <= nums[n - 1]` 条件成立,则说明当前数组已经是递增数组,最小值一定是数组第一个元素,提前返回 `nums[0]`。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def findMin(self, nums: List[int]) -> int: @@ -94,10 +88,6 @@ class Solution: return nums[left] ``` -### **Java** - - - ```java class Solution { public int findMin(int[] nums) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func findMin(nums []int) int { n := len(nums) @@ -161,28 +147,22 @@ func findMin(nums []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var findMin = function (nums) { - let l = 0, - r = nums.length - 1; - if (nums[l] < nums[r]) return nums[0]; - while (l < r) { - const m = (l + r) >> 1; - if (nums[m] > nums[r]) l = m + 1; - else r = m; +```ts +function findMin(nums: number[]): number { + let left = 0; + let right = nums.length - 1; + while (left < right) { + const mid = (left + right) >>> 1; + if (nums[mid] > nums[right]) { + left = mid + 1; + } else { + right = mid; + } } - return nums[l]; -}; + return nums[left]; +} ``` -### **Rust** - ```rust impl Solution { pub fn find_min(nums: Vec) -> i32 { @@ -201,28 +181,24 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function findMin(nums: number[]): number { - let left = 0; - let right = nums.length - 1; - while (left < right) { - const mid = (left + right) >>> 1; - if (nums[mid] > nums[right]) { - left = mid + 1; - } else { - right = mid; - } +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findMin = function (nums) { + let l = 0, + r = nums.length - 1; + if (nums[l] < nums[r]) return nums[0]; + while (l < r) { + const m = (l + r) >> 1; + if (nums[m] > nums[r]) l = m + 1; + else r = m; } - return nums[left]; -} -``` - -### **...** - -``` - + return nums[l]; +}; ``` + + diff --git a/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/README_EN.md b/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/README_EN.md index 0740cf72b9f17..ebe33a7aff3ec 100644 --- a/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/README_EN.md +++ b/solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/README_EN.md @@ -55,9 +55,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return nums[left] ``` -### **Java** - ```java class Solution { public int findMin(int[] nums) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func findMin(nums []int) int { n := len(nums) @@ -139,28 +133,22 @@ func findMin(nums []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var findMin = function (nums) { - let l = 0, - r = nums.length - 1; - if (nums[l] < nums[r]) return nums[0]; - while (l < r) { - const m = (l + r) >> 1; - if (nums[m] > nums[r]) l = m + 1; - else r = m; +```ts +function findMin(nums: number[]): number { + let left = 0; + let right = nums.length - 1; + while (left < right) { + const mid = (left + right) >>> 1; + if (nums[mid] > nums[right]) { + left = mid + 1; + } else { + right = mid; + } } - return nums[l]; -}; + return nums[left]; +} ``` -### **Rust** - ```rust impl Solution { pub fn find_min(nums: Vec) -> i32 { @@ -179,28 +167,24 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function findMin(nums: number[]): number { - let left = 0; - let right = nums.length - 1; - while (left < right) { - const mid = (left + right) >>> 1; - if (nums[mid] > nums[right]) { - left = mid + 1; - } else { - right = mid; - } +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findMin = function (nums) { + let l = 0, + r = nums.length - 1; + if (nums[l] < nums[r]) return nums[0]; + while (l < r) { + const m = (l + r) >> 1; + if (nums[m] > nums[r]) l = m + 1; + else r = m; } - return nums[left]; -} -``` - -### **...** - -``` - + return nums[l]; +}; ``` + + diff --git a/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/README.md b/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/README.md index 723abe843e145..9ce39225fd1c6 100644 --- a/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/README.md +++ b/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 若 `nums[mid] > nums[right]`,说明最小值在 mid 的右边;若 `nums[mid] < nums[right]`,说明最小值在 mid 的左边(包括 mid);若相等,无法判断,直接将 right 减 1。循环比较。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def findMin(self, nums: List[int]) -> int: @@ -83,10 +77,6 @@ class Solution: return nums[left] ``` -### **Java** - - - ```java class Solution { public int findMin(int[] nums) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,32 +115,6 @@ public: }; ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var findMin = function (nums) { - let left = 0, - right = nums.length - 1; - while (left < right) { - const mid = (left + right) >> 1; - if (nums[mid] > nums[right]) { - left = mid + 1; - } else if (nums[mid] < nums[right]) { - right = mid; - } else { - --right; - } - } - return nums[left]; -}; -``` - -### **Go** - ```go func findMin(nums []int) int { left, right := 0, len(nums)-1 @@ -170,8 +132,6 @@ func findMin(nums []int) int { } ``` -### **TypeScript** - ```ts function findMin(nums: number[]): number { let left = 0, @@ -190,10 +150,28 @@ function findMin(nums: number[]): number { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findMin = function (nums) { + let left = 0, + right = nums.length - 1; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] > nums[right]) { + left = mid + 1; + } else if (nums[mid] < nums[right]) { + right = mid; + } else { + --right; + } + } + return nums[left]; +}; ``` + + diff --git a/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/README_EN.md b/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/README_EN.md index 72dde1d4d9b32..3232026a878ef 100644 --- a/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/README_EN.md +++ b/solution/0100-0199/0154.Find Minimum in Rotated Sorted Array II/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return nums[left] ``` -### **Java** - ```java class Solution { public int findMin(int[] nums) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,32 +99,6 @@ public: }; ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var findMin = function (nums) { - let left = 0, - right = nums.length - 1; - while (left < right) { - const mid = (left + right) >> 1; - if (nums[mid] > nums[right]) { - left = mid + 1; - } else if (nums[mid] < nums[right]) { - right = mid; - } else { - --right; - } - } - return nums[left]; -}; -``` - -### **Go** - ```go func findMin(nums []int) int { left, right := 0, len(nums)-1 @@ -146,8 +116,6 @@ func findMin(nums []int) int { } ``` -### **TypeScript** - ```ts function findMin(nums: number[]): number { let left = 0, @@ -166,10 +134,28 @@ function findMin(nums: number[]): number { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findMin = function (nums) { + let left = 0, + right = nums.length - 1; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] > nums[right]) { + left = mid + 1; + } else if (nums[mid] < nums[right]) { + right = mid; + } else { + --right; + } + } + return nums[left]; +}; ``` + + diff --git a/solution/0100-0199/0155.Min Stack/README.md b/solution/0100-0199/0155.Min Stack/README.md index 7d57f1a226bb8..df253da44054b 100644 --- a/solution/0100-0199/0155.Min Stack/README.md +++ b/solution/0100-0199/0155.Min Stack/README.md @@ -53,9 +53,7 @@ minStack.getMin(); --> 返回 -2. ## 解法 - - -**方法一:双栈** +### 方法一:双栈 我们用两个栈来实现,其中 `stk1` 用来存储数据,`stk2` 用来存储当前栈中的最小值。初始时,`stk2` 中存储一个极大值。 @@ -68,10 +66,6 @@ minStack.getMin(); --> 返回 -2. -### **Python3** - - - ```python class MinStack: def __init__(self): @@ -101,10 +95,6 @@ class MinStack: # param_4 = obj.getMin() ``` -### **Java** - - - ```java class MinStack { private Deque stk1 = new ArrayDeque<>(); @@ -143,8 +133,6 @@ class MinStack { */ ``` -### **C++** - ```cpp class MinStack { public: @@ -185,8 +173,6 @@ private: */ ``` -### **Go** - ```go type MinStack struct { stk1 []int @@ -225,8 +211,6 @@ func (this *MinStack) GetMin() int { */ ``` -### **TypeScript** - ```ts class MinStack { stk1: number[]; @@ -266,57 +250,6 @@ class MinStack { */ ``` -### **JavaScript** - -```js -var MinStack = function () { - this.stk1 = []; - this.stk2 = [Infinity]; -}; - -/** - * @param {number} val - * @return {void} - */ -MinStack.prototype.push = function (val) { - this.stk1.push(val); - this.stk2.push(Math.min(this.stk2[this.stk2.length - 1], val)); -}; - -/** - * @return {void} - */ -MinStack.prototype.pop = function () { - this.stk1.pop(); - this.stk2.pop(); -}; - -/** - * @return {number} - */ -MinStack.prototype.top = function () { - return this.stk1[this.stk1.length - 1]; -}; - -/** - * @return {number} - */ -MinStack.prototype.getMin = function () { - return this.stk2[this.stk2.length - 1]; -}; - -/** - * Your MinStack object will be instantiated and called as such: - * var obj = new MinStack() - * obj.push(val) - * obj.pop() - * var param_3 = obj.top() - * var param_4 = obj.getMin() - */ -``` - -### **Rust** - ```rust use std::collections::VecDeque; struct MinStack { @@ -364,7 +297,52 @@ impl MinStack { */ ``` -### **C#** +```js +var MinStack = function () { + this.stk1 = []; + this.stk2 = [Infinity]; +}; + +/** + * @param {number} val + * @return {void} + */ +MinStack.prototype.push = function (val) { + this.stk1.push(val); + this.stk2.push(Math.min(this.stk2[this.stk2.length - 1], val)); +}; + +/** + * @return {void} + */ +MinStack.prototype.pop = function () { + this.stk1.pop(); + this.stk2.pop(); +}; + +/** + * @return {number} + */ +MinStack.prototype.top = function () { + return this.stk1[this.stk1.length - 1]; +}; + +/** + * @return {number} + */ +MinStack.prototype.getMin = function () { + return this.stk2[this.stk2.length - 1]; +}; + +/** + * Your MinStack object will be instantiated and called as such: + * var obj = new MinStack() + * obj.push(val) + * obj.pop() + * var param_3 = obj.top() + * var param_4 = obj.getMin() + */ +``` ```cs public class MinStack { @@ -404,10 +382,6 @@ public class MinStack { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0155.Min Stack/README_EN.md b/solution/0100-0199/0155.Min Stack/README_EN.md index f1697dd7c33bf..6af6605fe91f9 100644 --- a/solution/0100-0199/0155.Min Stack/README_EN.md +++ b/solution/0100-0199/0155.Min Stack/README_EN.md @@ -51,9 +51,9 @@ minStack.getMin(); // return -2 ## Solutions - +### Solution 1 -### **Python3** + ```python class MinStack: @@ -84,8 +84,6 @@ class MinStack: # param_4 = obj.getMin() ``` -### **Java** - ```java class MinStack { private Deque stk1 = new ArrayDeque<>(); @@ -124,8 +122,6 @@ class MinStack { */ ``` -### **C++** - ```cpp class MinStack { public: @@ -166,8 +162,6 @@ private: */ ``` -### **Go** - ```go type MinStack struct { stk1 []int @@ -206,8 +200,6 @@ func (this *MinStack) GetMin() int { */ ``` -### **TypeScript** - ```ts class MinStack { stk1: number[]; @@ -247,57 +239,6 @@ class MinStack { */ ``` -### **JavaScript** - -```js -var MinStack = function () { - this.stk1 = []; - this.stk2 = [Infinity]; -}; - -/** - * @param {number} val - * @return {void} - */ -MinStack.prototype.push = function (val) { - this.stk1.push(val); - this.stk2.push(Math.min(this.stk2[this.stk2.length - 1], val)); -}; - -/** - * @return {void} - */ -MinStack.prototype.pop = function () { - this.stk1.pop(); - this.stk2.pop(); -}; - -/** - * @return {number} - */ -MinStack.prototype.top = function () { - return this.stk1[this.stk1.length - 1]; -}; - -/** - * @return {number} - */ -MinStack.prototype.getMin = function () { - return this.stk2[this.stk2.length - 1]; -}; - -/** - * Your MinStack object will be instantiated and called as such: - * var obj = new MinStack() - * obj.push(val) - * obj.pop() - * var param_3 = obj.top() - * var param_4 = obj.getMin() - */ -``` - -### **Rust** - ```rust use std::collections::VecDeque; struct MinStack { @@ -345,7 +286,52 @@ impl MinStack { */ ``` -### **C#** +```js +var MinStack = function () { + this.stk1 = []; + this.stk2 = [Infinity]; +}; + +/** + * @param {number} val + * @return {void} + */ +MinStack.prototype.push = function (val) { + this.stk1.push(val); + this.stk2.push(Math.min(this.stk2[this.stk2.length - 1], val)); +}; + +/** + * @return {void} + */ +MinStack.prototype.pop = function () { + this.stk1.pop(); + this.stk2.pop(); +}; + +/** + * @return {number} + */ +MinStack.prototype.top = function () { + return this.stk1[this.stk1.length - 1]; +}; + +/** + * @return {number} + */ +MinStack.prototype.getMin = function () { + return this.stk2[this.stk2.length - 1]; +}; + +/** + * Your MinStack object will be instantiated and called as such: + * var obj = new MinStack() + * obj.push(val) + * obj.pop() + * var param_3 = obj.top() + * var param_4 = obj.getMin() + */ +``` ```cs public class MinStack { @@ -385,10 +371,6 @@ public class MinStack { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0156.Binary Tree Upside Down/README.md b/solution/0100-0199/0156.Binary Tree Upside Down/README.md index b6cec6ca0dd47..816ad092bb77e 100644 --- a/solution/0100-0199/0156.Binary Tree Upside Down/README.md +++ b/solution/0100-0199/0156.Binary Tree Upside Down/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 若根节点为空,或者根节点左子树为空,直接返回根节点。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -93,10 +87,6 @@ class Solution: return new_root ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -180,10 +166,6 @@ func upsideDownBinaryTree(root *TreeNode) *TreeNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0156.Binary Tree Upside Down/README_EN.md b/solution/0100-0199/0156.Binary Tree Upside Down/README_EN.md index 13498faef1e67..8a7e8870898bc 100644 --- a/solution/0100-0199/0156.Binary Tree Upside Down/README_EN.md +++ b/solution/0100-0199/0156.Binary Tree Upside Down/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -73,8 +73,6 @@ class Solution: return new_root ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -134,8 +130,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -158,10 +152,6 @@ func upsideDownBinaryTree(root *TreeNode) *TreeNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0157.Read N Characters Given Read4/README.md b/solution/0100-0199/0157.Read N Characters Given Read4/README.md index 9fc9f0b965f65..84bd228b2f1f5 100644 --- a/solution/0100-0199/0157.Read N Characters Given Read4/README.md +++ b/solution/0100-0199/0157.Read N Characters Given Read4/README.md @@ -89,9 +89,7 @@ read4(buf4); // read4 返回 0。现在 buf = "",fp 指向文件末 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 直接模拟读取文件的过程,每次读取 4 个字符,然后将读取的字符存入缓存数组中,直到读取的字符数目达到 n 或者文件读取完毕。 @@ -99,10 +97,6 @@ read4(buf4); // read4 返回 0。现在 buf = "",fp 指向文件末 -### **Python3** - - - ```python """ The read4 API is already defined for you. @@ -140,10 +134,6 @@ class Solution: return i ``` -### **Java** - - - ```java /** * The read4 API is defined in the parent class Reader4. @@ -173,8 +163,6 @@ public class Solution extends Reader4 { } ``` -### **C++** - ```cpp /** * The read4 API is defined in the parent class Reader4. @@ -205,8 +193,6 @@ public: }; ``` -### **Go** - ```go /** * The read4 API is already defined for you. @@ -241,10 +227,6 @@ var solution = func(read4 func([]byte) int) func([]byte, int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0157.Read N Characters Given Read4/README_EN.md b/solution/0100-0199/0157.Read N Characters Given Read4/README_EN.md index 7e6b3546b58f9..7bdfe4d90a478 100644 --- a/solution/0100-0199/0157.Read N Characters Given Read4/README_EN.md +++ b/solution/0100-0199/0157.Read N Characters Given Read4/README_EN.md @@ -95,9 +95,9 @@ Note that "abc" is the file's content, not buf. buf is the destina ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -136,8 +136,6 @@ class Solution: return i ``` -### **Java** - ```java /** * The read4 API is defined in the parent class Reader4. @@ -167,8 +165,6 @@ public class Solution extends Reader4 { } ``` -### **C++** - ```cpp /** * The read4 API is defined in the parent class Reader4. @@ -199,8 +195,6 @@ public: }; ``` -### **Go** - ```go /** * The read4 API is already defined for you. @@ -235,10 +229,6 @@ var solution = func(read4 func([]byte) int) func([]byte, int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0158.Read N Characters Given read4 II - Call Multiple Times/README.md b/solution/0100-0199/0158.Read N Characters Given read4 II - Call Multiple Times/README.md index 59626975f18a9..c43f041f34054 100644 --- a/solution/0100-0199/0158.Read N Characters Given read4 II - Call Multiple Times/README.md +++ b/solution/0100-0199/0158.Read N Characters Given read4 II - Call Multiple Times/README.md @@ -104,16 +104,10 @@ sol.read (buf, 1); // 我们已经到达文件的末尾,不能读取更多的 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 -### **Python3** - - - ```python # The read4 API is already defined for you. # def read4(buf4: List[str]) -> int: @@ -139,10 +133,6 @@ class Solution: return j ``` -### **Java** - - - ```java /** * The read4 API is defined in the parent class Reader4. @@ -178,8 +168,6 @@ public class Solution extends Reader4 { } ``` -### **C++** - ```cpp /** * The read4 API is defined in the parent class Reader4. @@ -213,8 +201,6 @@ private: }; ``` -### **Go** - ```go /** * The read4 API is already defined for you. @@ -253,16 +239,6 @@ var solution = func(read4 func([]byte) int) func([]byte, int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0158.Read N Characters Given read4 II - Call Multiple Times/README_EN.md b/solution/0100-0199/0158.Read N Characters Given read4 II - Call Multiple Times/README_EN.md index 548b3b6daa037..f622f4aeeda2e 100644 --- a/solution/0100-0199/0158.Read N Characters Given read4 II - Call Multiple Times/README_EN.md +++ b/solution/0100-0199/0158.Read N Characters Given read4 II - Call Multiple Times/README_EN.md @@ -99,9 +99,9 @@ sol.read(buf, 1); // We have reached the end of file, no more characters can be ## Solutions - +### Solution 1 -### **Python3** + ```python # The read4 API is already defined for you. @@ -128,8 +128,6 @@ class Solution: return j ``` -### **Java** - ```java /** * The read4 API is defined in the parent class Reader4. @@ -165,8 +163,6 @@ public class Solution extends Reader4 { } ``` -### **C++** - ```cpp /** * The read4 API is defined in the parent class Reader4. @@ -200,8 +196,6 @@ private: }; ``` -### **Go** - ```go /** * The read4 API is already defined for you. @@ -240,16 +234,6 @@ var solution = func(read4 func([]byte) int) func([]byte, int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0159.Longest Substring with At Most Two Distinct Characters/README.md b/solution/0100-0199/0159.Longest Substring with At Most Two Distinct Characters/README.md index 90040a7b19e76..b9d3f800ece1a 100644 --- a/solution/0100-0199/0159.Longest Substring with At Most Two Distinct Characters/README.md +++ b/solution/0100-0199/0159.Longest Substring with At Most Two Distinct Characters/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:哈希表 + 滑动窗口** +### 方法一:哈希表 + 滑动窗口 我们维护一个哈希表 `cnt` 记录当前滑动窗口中各个字符出现的次数,如果哈希表中的键值对个数超过 $2$,则说明当前滑动窗口中包含了超过 $2$ 个不同的字符,此时需要移动左指针 `j`,直到哈希表中的键值对个数不超过 $2$ 为止,然后更新窗口的最大长度。 @@ -47,10 +45,6 @@ -### **Python3** - - - ```python class Solution: def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int: @@ -67,10 +61,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int lengthOfLongestSubstringTwoDistinct(String s) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func lengthOfLongestSubstringTwoDistinct(s string) (ans int) { cnt := map[byte]int{} @@ -140,10 +126,6 @@ func lengthOfLongestSubstringTwoDistinct(s string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0159.Longest Substring with At Most Two Distinct Characters/README_EN.md b/solution/0100-0199/0159.Longest Substring with At Most Two Distinct Characters/README_EN.md index 590520890f058..7d510d9f93acb 100644 --- a/solution/0100-0199/0159.Longest Substring with At Most Two Distinct Characters/README_EN.md +++ b/solution/0100-0199/0159.Longest Substring with At Most Two Distinct Characters/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int lengthOfLongestSubstringTwoDistinct(String s) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +99,6 @@ public: }; ``` -### **Go** - ```go func lengthOfLongestSubstringTwoDistinct(s string) (ans int) { cnt := map[byte]int{} @@ -124,10 +118,6 @@ func lengthOfLongestSubstringTwoDistinct(s string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0160.Intersection of Two Linked Lists/README.md b/solution/0100-0199/0160.Intersection of Two Linked Lists/README.md index dab190a88db4b..61e6531376831 100644 --- a/solution/0100-0199/0160.Intersection of Two Linked Lists/README.md +++ b/solution/0100-0199/0160.Intersection of Two Linked Lists/README.md @@ -92,9 +92,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 使用两个指针 $a$, $b$ 分别指向两个链表 $headA$, $headB$。 @@ -106,10 +104,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -127,10 +121,6 @@ class Solution: return a ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -155,8 +145,6 @@ public class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -179,35 +167,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 a = headA; - let b = headB; - while (a != b) { - a = a ? a.next : headB; - b = b ? b.next : headA; - } - return a; -}; -``` - -### **Go** - ```go /** * Definition for singly-linked list. @@ -234,8 +193,6 @@ func getIntersectionNode(headA, headB *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -260,7 +217,30 @@ function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): Li } ``` -### **Swift** +```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 a = headA; + let b = headB; + while (a != b) { + a = a ? a.next : headB; + b = b ? b.next : headA; + } + return a; +}; +``` ```swift /** @@ -288,10 +268,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0160.Intersection of Two Linked Lists/README_EN.md b/solution/0100-0199/0160.Intersection of Two Linked Lists/README_EN.md index 88876d3555269..b892ad458a3e1 100644 --- a/solution/0100-0199/0160.Intersection of Two Linked Lists/README_EN.md +++ b/solution/0100-0199/0160.Intersection of Two Linked Lists/README_EN.md @@ -74,9 +74,9 @@ Explanation: The two lists do not intersect, so return null. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -95,8 +95,6 @@ class Solution: return a ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -121,8 +119,6 @@ public class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -145,35 +141,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 a = headA; - let b = headB; - while (a != b) { - a = a ? a.next : headB; - b = b ? b.next : headA; - } - return a; -}; -``` - -### **Go** - ```go /** * Definition for singly-linked list. @@ -200,8 +167,6 @@ func getIntersectionNode(headA, headB *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -226,7 +191,30 @@ function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): Li } ``` -### **Swift** +```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 a = headA; + let b = headB; + while (a != b) { + a = a ? a.next : headB; + b = b ? b.next : headA; + } + return a; +}; +``` ```swift /** @@ -254,10 +242,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0161.One Edit Distance/README.md b/solution/0100-0199/0161.One Edit Distance/README.md index f460eea5d1791..f9cb53a5e522a 100644 --- a/solution/0100-0199/0161.One Edit Distance/README.md +++ b/solution/0100-0199/0161.One Edit Distance/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:分情况讨论** +### 方法一:分情况讨论 记 $m$ 表示字符串 $s$ 的长度,$n$ 表示字符串 $t$ 的长度。我们可以假定 $m$ 恒大于等于 $n$。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def isOneEditDistance(self, s: str, t: str) -> bool: @@ -81,10 +75,6 @@ class Solution: return m == n + 1 ``` -### **Java** - - - ```java class Solution { public boolean isOneEditDistance(String s, String t) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func isOneEditDistance(s string, t string) bool { m, n := len(s), len(t) @@ -151,10 +137,6 @@ func isOneEditDistance(s string, t string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0161.One Edit Distance/README_EN.md b/solution/0100-0199/0161.One Edit Distance/README_EN.md index afbfa215d3b2b..1042f1348af88 100644 --- a/solution/0100-0199/0161.One Edit Distance/README_EN.md +++ b/solution/0100-0199/0161.One Edit Distance/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return m == n + 1 ``` -### **Java** - ```java class Solution { public boolean isOneEditDistance(String s, String t) { @@ -84,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +100,6 @@ public: }; ``` -### **Go** - ```go func isOneEditDistance(s string, t string) bool { m, n := len(s), len(t) @@ -127,10 +121,6 @@ func isOneEditDistance(s string, t string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0162.Find Peak Element/README.md b/solution/0100-0199/0162.Find Peak Element/README.md index 5fecca8cf6bbc..9e44f8a11cc2e 100644 --- a/solution/0100-0199/0162.Find Peak Element/README.md +++ b/solution/0100-0199/0162.Find Peak Element/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们定义二分查找的左边界 $left=0$,右边界 $right=n-1$,其中 $n$ 是数组的长度。在每一步二分查找中,我们找到当前区间的中间元素 $mid$,然后比较 $mid$ 与其右边元素 $mid+1$ 的值: @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def findPeakElement(self, nums: List[int]) -> int: @@ -75,10 +69,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int findPeakElement(int[] nums) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func findPeakElement(nums []int) int { left, right := 0, len(nums)-1 @@ -133,8 +119,6 @@ func findPeakElement(nums []int) int { } ``` -### **TypeScript** - ```ts function findPeakElement(nums: number[]): number { let [left, right] = [0, nums.length - 1]; @@ -150,10 +134,6 @@ function findPeakElement(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0162.Find Peak Element/README_EN.md b/solution/0100-0199/0162.Find Peak Element/README_EN.md index fec9e4a7c01e7..5e6c5c341f551 100644 --- a/solution/0100-0199/0162.Find Peak Element/README_EN.md +++ b/solution/0100-0199/0162.Find Peak Element/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search We define the left boundary of binary search as $left=0$ and the right boundary as $right=n-1$, where $n$ is the length of the array. In each step of binary search, we find the middle element $mid$ of the current interval, and compare the values of $mid$ and its right neighbor $mid+1$: @@ -50,8 +50,6 @@ The time complexity is $O(\log n)$, where $n$ is the length of the array $nums$. -### **Python3** - ```python class Solution: def findPeakElement(self, nums: List[int]) -> int: @@ -65,8 +63,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { public int findPeakElement(int[] nums) { @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +98,6 @@ public: }; ``` -### **Go** - ```go func findPeakElement(nums []int) int { left, right := 0, len(nums)-1 @@ -121,8 +113,6 @@ func findPeakElement(nums []int) int { } ``` -### **TypeScript** - ```ts function findPeakElement(nums: number[]): number { let [left, right] = [0, nums.length - 1]; @@ -138,10 +128,6 @@ function findPeakElement(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0163.Missing Ranges/README.md b/solution/0100-0199/0163.Missing Ranges/README.md index 5c60511443e12..b06e662ca93a3 100644 --- a/solution/0100-0199/0163.Missing Ranges/README.md +++ b/solution/0100-0199/0163.Missing Ranges/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们直接按照题意模拟即可。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def findMissingRanges( @@ -77,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> findMissingRanges(int[] nums, int lower, int upper) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go func findMissingRanges(nums []int, lower int, upper int) (ans [][]int) { n := len(nums) @@ -155,8 +141,6 @@ func findMissingRanges(nums []int, lower int, upper int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function findMissingRanges(nums: number[], lower: number, upper: number): number[][] { const n = nums.length; @@ -179,10 +163,6 @@ function findMissingRanges(nums: number[], lower: number, upper: number): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0163.Missing Ranges/README_EN.md b/solution/0100-0199/0163.Missing Ranges/README_EN.md index aab082c6f4cba..6f831e08daeb5 100644 --- a/solution/0100-0199/0163.Missing Ranges/README_EN.md +++ b/solution/0100-0199/0163.Missing Ranges/README_EN.md @@ -45,7 +45,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can simulate the problem directly according to the requirements. @@ -53,8 +53,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. Igno -### **Python3** - ```python class Solution: def findMissingRanges( @@ -74,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List> findMissingRanges(int[] nums, int lower, int upper) { @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +121,6 @@ public: }; ``` -### **Go** - ```go func findMissingRanges(nums []int, lower int, upper int) (ans [][]int) { n := len(nums) @@ -150,8 +142,6 @@ func findMissingRanges(nums []int, lower int, upper int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function findMissingRanges(nums: number[], lower: number, upper: number): number[][] { const n = nums.length; @@ -174,10 +164,6 @@ function findMissingRanges(nums: number[], lower: number, upper: number): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0164.Maximum Gap/README.md b/solution/0100-0199/0164.Maximum Gap/README.md index 9aa98f24c5113..dce7733b5bb52 100644 --- a/solution/0100-0199/0164.Maximum Gap/README.md +++ b/solution/0100-0199/0164.Maximum Gap/README.md @@ -37,15 +37,7 @@ ## 解法 - - -**前言** - -一种容易想到的解法是将数组排序后得到相邻元素之间最大的差值,时间复杂度 $O(n \log n)$,不符合题目要求。 - -只有使用不基于比较的的排序算法才能在线性时间复杂度解决。 - -**方法一:桶排序** +### 方法一:桶排序 假设数组 $nums$ 有 $n$ 个元素,所有元素从小到大依次是 $nums_0$ 到 $nums_{n - 1}$,最大间距是 $maxGap$。考虑数组中的最大元素和最小元素之差。 @@ -65,10 +57,6 @@ $$ -### **Python3** - - - ```python class Solution: def maximumGap(self, nums: List[int]) -> int: @@ -93,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumGap(int[] nums) { @@ -136,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp using pii = pair; @@ -172,8 +154,6 @@ public: }; ``` -### **Go** - ```go func maximumGap(nums []int) int { n := len(nums) @@ -210,8 +190,6 @@ func maximumGap(nums []int) int { } ``` -### **C#** - ```cs using System; using System.Linq; @@ -254,10 +232,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0164.Maximum Gap/README_EN.md b/solution/0100-0199/0164.Maximum Gap/README_EN.md index 5ca13daec95ef..23d1a3a70e5f0 100644 --- a/solution/0100-0199/0164.Maximum Gap/README_EN.md +++ b/solution/0100-0199/0164.Maximum Gap/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumGap(int[] nums) { @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp using pii = pair; @@ -140,8 +136,6 @@ public: }; ``` -### **Go** - ```go func maximumGap(nums []int) int { n := len(nums) @@ -178,8 +172,6 @@ func maximumGap(nums []int) int { } ``` -### **C#** - ```cs using System; using System.Linq; @@ -222,10 +214,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0165.Compare Version Numbers/README.md b/solution/0100-0199/0165.Compare Version Numbers/README.md index 23b01bccae073..911e2dcd428ae 100644 --- a/solution/0100-0199/0165.Compare Version Numbers/README.md +++ b/solution/0100-0199/0165.Compare Version Numbers/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 同时遍历两个字符串,用两个指针 $i$ 和 $j$ 分别指向两个字符串的当前位置,初始时 $i = j = 0$。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def compareVersion(self, version1: str, version2: str) -> int: @@ -94,10 +88,6 @@ class Solution: return 0 ``` -### **Java** - - - ```java class Solution { public int compareVersion(String version1, String version2) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func compareVersion(version1 string, version2 string) int { m, n := len(version1), len(version2) @@ -169,7 +155,19 @@ func compareVersion(version1 string, version2 string) int { } ``` -### **C#** +```ts +function compareVersion(version1: string, version2: string): number { + let v1 = version1.split('.'), + v2 = version2.split('.'); + for (let i = 0; i < Math.max(v1.length, v2.length); i++) { + let c1 = Number(v1[i] || 0), + c2 = Number(v2[i] || 0); + if (c1 > c2) return 1; + if (c1 < c2) return -1; + } + return 0; +} +``` ```cs public class Solution { @@ -192,26 +190,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function compareVersion(version1: string, version2: string): number { - let v1 = version1.split('.'), - v2 = version2.split('.'); - for (let i = 0; i < Math.max(v1.length, v2.length); i++) { - let c1 = Number(v1[i] || 0), - c2 = Number(v2[i] || 0); - if (c1 > c2) return 1; - if (c1 < c2) return -1; - } - return 0; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0165.Compare Version Numbers/README_EN.md b/solution/0100-0199/0165.Compare Version Numbers/README_EN.md index 75dcd91d06611..084d2f154d8b5 100644 --- a/solution/0100-0199/0165.Compare Version Numbers/README_EN.md +++ b/solution/0100-0199/0165.Compare Version Numbers/README_EN.md @@ -58,9 +58,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -81,8 +81,6 @@ class Solution: return 0 ``` -### **Java** - ```java class Solution { public int compareVersion(String version1, String version2) { @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +124,6 @@ public: }; ``` -### **Go** - ```go func compareVersion(version1 string, version2 string) int { m, n := len(version1), len(version2) @@ -154,7 +148,19 @@ func compareVersion(version1 string, version2 string) int { } ``` -### **C#** +```ts +function compareVersion(version1: string, version2: string): number { + let v1 = version1.split('.'), + v2 = version2.split('.'); + for (let i = 0; i < Math.max(v1.length, v2.length); i++) { + let c1 = Number(v1[i] || 0), + c2 = Number(v2[i] || 0); + if (c1 > c2) return 1; + if (c1 < c2) return -1; + } + return 0; +} +``` ```cs public class Solution { @@ -177,26 +183,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function compareVersion(version1: string, version2: string): number { - let v1 = version1.split('.'), - v2 = version2.split('.'); - for (let i = 0; i < Math.max(v1.length, v2.length); i++) { - let c1 = Number(v1[i] || 0), - c2 = Number(v2[i] || 0); - if (c1 > c2) return 1; - if (c1 < c2) return -1; - } - return 0; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0166.Fraction to Recurring Decimal/README.md b/solution/0100-0199/0166.Fraction to Recurring Decimal/README.md index 11e393ee45103..2686f15ccb65c 100644 --- a/solution/0100-0199/0166.Fraction to Recurring Decimal/README.md +++ b/solution/0100-0199/0166.Fraction to Recurring Decimal/README.md @@ -48,16 +48,10 @@ ## 解法 - - -在进行除法时使用 HashMap 存储余数及其关联的索引,这样每当出现相同的余数时,我们就知道有一个重复的小数部分。 +### 方法一 -### **Python3** - - - ```python class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: @@ -87,10 +81,6 @@ class Solution: return ''.join(res) ``` -### **Java** - - - ```java class Solution { public String fractionToDecimal(int numerator, int denominator) { @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp using LL = long long; @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go func fractionToDecimal(numerator int, denominator int) string { if numerator == 0 { @@ -207,10 +193,66 @@ func abs(x int) int { } ``` -### **...** - -``` +```cs +// https://leetcode.com/problems/fraction-to-recurring-decimal/ + +using System.Collections.Generic; +using System.Text; + +public partial class Solution +{ + public string FractionToDecimal(int numerator, int denominator) + { + var n = (long)numerator; + var d = (long)denominator; + var sb = new StringBuilder(); + if (n < 0) + { + n = -n; + if (d < 0) + { + d = -d; + } + else + { + sb.Append('-'); + } + } + else if (n > 0 && d < 0) + { + d = -d; + sb.Append('-'); + } + sb.Append(n / d); + n = n % d; + if (n != 0) + { + sb.Append('.'); + var dict = new Dictionary(); + while (n != 0) + { + int index; + if (dict.TryGetValue(n, out index)) + { + sb.Insert(index, '('); + sb.Append(')'); + break; + } + else + { + dict.Add(n, sb.Length); + n *= 10; + sb.Append(n / d); + n %= d; + } + } + } + return sb.ToString(); + } +} ``` + + diff --git a/solution/0100-0199/0166.Fraction to Recurring Decimal/README_EN.md b/solution/0100-0199/0166.Fraction to Recurring Decimal/README_EN.md index ee7e018d02686..442022d0da394 100644 --- a/solution/0100-0199/0166.Fraction to Recurring Decimal/README_EN.md +++ b/solution/0100-0199/0166.Fraction to Recurring Decimal/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return ''.join(res) ``` -### **Java** - ```java class Solution { public String fractionToDecimal(int numerator, int denominator) { @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp using LL = long long; @@ -150,8 +146,6 @@ public: }; ``` -### **Go** - ```go func fractionToDecimal(numerator int, denominator int) string { if numerator == 0 { @@ -195,10 +189,66 @@ func abs(x int) int { } ``` -### **...** - -``` +```cs +// https://leetcode.com/problems/fraction-to-recurring-decimal/ + +using System.Collections.Generic; +using System.Text; + +public partial class Solution +{ + public string FractionToDecimal(int numerator, int denominator) + { + var n = (long)numerator; + var d = (long)denominator; + var sb = new StringBuilder(); + if (n < 0) + { + n = -n; + if (d < 0) + { + d = -d; + } + else + { + sb.Append('-'); + } + } + else if (n > 0 && d < 0) + { + d = -d; + sb.Append('-'); + } + sb.Append(n / d); + n = n % d; + if (n != 0) + { + sb.Append('.'); + var dict = new Dictionary(); + while (n != 0) + { + int index; + if (dict.TryGetValue(n, out index)) + { + sb.Insert(index, '('); + sb.Append(')'); + break; + } + else + { + dict.Add(n, sb.Length); + n *= 10; + sb.Append(n / d); + n %= d; + } + } + } + return sb.ToString(); + } +} ``` + + diff --git a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/README.md b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/README.md index b8aece0189f8d..8aced4c7b6aab 100644 --- a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/README.md +++ b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/README.md @@ -51,26 +51,14 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们注意到数组按照非递减顺序排列,因此对于每个 $numbers[i]$,可以通过二分查找的方式找到 $target - numbers[i]$ 的位置,如果存在,那么返回 $[i + 1, j + 1]$ 即可。 时间复杂度 $O(n \times \log n)$,其中 $n$ 为数组 $numbers$ 的长度。空间复杂度 $O(1)$。 -**方法二:双指针** - -我们定义两个指针 $i$ 和 $j$,分别指向数组的第一个元素和最后一个元素。每次计算 $numbers[i] + numbers[j]$,如果和等于目标值,那么返回 $[i + 1, j + 1]$ 即可。如果和小于目标值,那么将 $i$ 右移一位,如果和大于目标值,那么将 $j$ 左移一位。 - -时间复杂度 $O(n)$,其中 $n$ 为数组 $numbers$ 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: @@ -82,24 +70,6 @@ class Solution: return [i + 1, j + 1] ``` -```python -class Solution: - def twoSum(self, numbers: List[int], target: int) -> List[int]: - i, j = 0, len(numbers) - 1 - while i < j: - x = numbers[i] + numbers[j] - if x == target: - return [i + 1, j + 1] - if x < target: - i += 1 - else: - j -= 1 -``` - -### **Java** - - - ```java class Solution { public int[] twoSum(int[] numbers, int target) { @@ -122,26 +92,6 @@ class Solution { } ``` -```java -class Solution { - public int[] twoSum(int[] numbers, int target) { - for (int i = 0, j = numbers.length - 1;;) { - int x = numbers[i] + numbers[j]; - if (x == target) { - return new int[] {i + 1, j + 1}; - } - if (x < target) { - ++i; - } else { - --j; - } - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -157,27 +107,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector twoSum(vector& numbers, int target) { - for (int i = 0, j = numbers.size() - 1;;) { - int x = numbers[i] + numbers[j]; - if (x == target) { - return {i + 1, j + 1}; - } - if (x < target) { - ++i; - } else { - --j; - } - } - } -}; -``` - -### **Go** - ```go func twoSum(numbers []int, target int) []int { for i, n := 0, len(numbers); ; i++ { @@ -190,24 +119,6 @@ func twoSum(numbers []int, target int) []int { } ``` -```go -func twoSum(numbers []int, target int) []int { - for i, j := 0, len(numbers)-1; ; { - x := numbers[i] + numbers[j] - if x == target { - return []int{i + 1, j + 1} - } - if x < target { - i++ - } else { - j-- - } - } -} -``` - -### **TypeScript** - ```ts function twoSum(numbers: number[], target: number): number[] { const n = numbers.length; @@ -230,24 +141,32 @@ function twoSum(numbers: number[], target: number): number[] { } ``` -```ts -function twoSum(numbers: number[], target: number): number[] { - for (let i = 0, j = numbers.length - 1; ; ) { - const x = numbers[i] + numbers[j]; - if (x === target) { - return [i + 1, j + 1]; - } - if (x < target) { - ++i; - } else { - --j; +```rust +use std::cmp::Ordering; + +impl Solution { + pub fn two_sum(numbers: Vec, target: i32) -> Vec { + let n = numbers.len(); + let mut l = 0; + let mut r = n - 1; + loop { + match (numbers[l] + numbers[r]).cmp(&target) { + Ordering::Less => { + l += 1; + } + Ordering::Greater => { + r -= 1; + } + Ordering::Equal => { + break; + } + } } + vec![(l as i32) + 1, (r as i32) + 1] } } ``` -### **JavaScript** - ```js /** * @param {number[]} numbers @@ -275,6 +194,99 @@ var twoSum = function (numbers, target) { }; ``` + + +### 方法二:双指针 + +我们定义两个指针 $i$ 和 $j$,分别指向数组的第一个元素和最后一个元素。每次计算 $numbers[i] + numbers[j]$,如果和等于目标值,那么返回 $[i + 1, j + 1]$ 即可。如果和小于目标值,那么将 $i$ 右移一位,如果和大于目标值,那么将 $j$ 左移一位。 + +时间复杂度 $O(n)$,其中 $n$ 为数组 $numbers$ 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def twoSum(self, numbers: List[int], target: int) -> List[int]: + i, j = 0, len(numbers) - 1 + while i < j: + x = numbers[i] + numbers[j] + if x == target: + return [i + 1, j + 1] + if x < target: + i += 1 + else: + j -= 1 +``` + +```java +class Solution { + public int[] twoSum(int[] numbers, int target) { + for (int i = 0, j = numbers.length - 1;;) { + int x = numbers[i] + numbers[j]; + if (x == target) { + return new int[] {i + 1, j + 1}; + } + if (x < target) { + ++i; + } else { + --j; + } + } + } +} +``` + +```cpp +class Solution { +public: + vector twoSum(vector& numbers, int target) { + for (int i = 0, j = numbers.size() - 1;;) { + int x = numbers[i] + numbers[j]; + if (x == target) { + return {i + 1, j + 1}; + } + if (x < target) { + ++i; + } else { + --j; + } + } + } +}; +``` + +```go +func twoSum(numbers []int, target int) []int { + for i, j := 0, len(numbers)-1; ; { + x := numbers[i] + numbers[j] + if x == target { + return []int{i + 1, j + 1} + } + if x < target { + i++ + } else { + j-- + } + } +} +``` + +```ts +function twoSum(numbers: number[], target: number): number[] { + for (let i = 0, j = numbers.length - 1; ; ) { + const x = numbers[i] + numbers[j]; + if (x === target) { + return [i + 1, j + 1]; + } + if (x < target) { + ++i; + } else { + --j; + } + } +} +``` + ```js /** * @param {number[]} numbers @@ -296,38 +308,6 @@ var twoSum = function (numbers, target) { }; ``` -### **Rust** - -```rust -use std::cmp::Ordering; - -impl Solution { - pub fn two_sum(numbers: Vec, target: i32) -> Vec { - let n = numbers.len(); - let mut l = 0; - let mut r = n - 1; - loop { - match (numbers[l] + numbers[r]).cmp(&target) { - Ordering::Less => { - l += 1; - } - Ordering::Greater => { - r -= 1; - } - Ordering::Equal => { - break; - } - } - } - vec![(l as i32) + 1, (r as i32) + 1] - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/README_EN.md b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/README_EN.md index f4085cc6b610b..bd83f75ae421d 100644 --- a/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/README_EN.md +++ b/solution/0100-0199/0167.Two Sum II - Input Array Is Sorted/README_EN.md @@ -50,22 +50,14 @@ ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search Note that the array is sorted in non-decreasing order, so for each `numbers[i]`, we can find the position of `target - numbers[i]` by binary search, and return $[i + 1, j + 1]$ if it exists. The time complexity is $O(n \times \log n)$, where $n$ is the length of the array `numbers`. The space complexity is $O(1)$. -**Solution 2: Two Pointers** - -We define two pointers $i$ and $j$, which point to the first element and the last element of the array respectively. Each time we calculate $numbers[i] + numbers[j]$. If the sum is equal to the target value, return $[i + 1, j + 1]$ directly. If the sum is less than the target value, move $i$ to the right by one position, and if the sum is greater than the target value, move $j$ to the left by one position. - -The time complexity is $O(n)$, where $n$ is the length of the array `numbers`. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: @@ -77,22 +69,6 @@ class Solution: return [i + 1, j + 1] ``` -```python -class Solution: - def twoSum(self, numbers: List[int], target: int) -> List[int]: - i, j = 0, len(numbers) - 1 - while i < j: - x = numbers[i] + numbers[j] - if x == target: - return [i + 1, j + 1] - if x < target: - i += 1 - else: - j -= 1 -``` - -### **Java** - ```java class Solution { public int[] twoSum(int[] numbers, int target) { @@ -115,26 +91,6 @@ class Solution { } ``` -```java -class Solution { - public int[] twoSum(int[] numbers, int target) { - for (int i = 0, j = numbers.length - 1;;) { - int x = numbers[i] + numbers[j]; - if (x == target) { - return new int[] {i + 1, j + 1}; - } - if (x < target) { - ++i; - } else { - --j; - } - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -150,27 +106,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector twoSum(vector& numbers, int target) { - for (int i = 0, j = numbers.size() - 1;;) { - int x = numbers[i] + numbers[j]; - if (x == target) { - return {i + 1, j + 1}; - } - if (x < target) { - ++i; - } else { - --j; - } - } - } -}; -``` - -### **Go** - ```go func twoSum(numbers []int, target int) []int { for i, n := 0, len(numbers); ; i++ { @@ -183,24 +118,6 @@ func twoSum(numbers []int, target int) []int { } ``` -```go -func twoSum(numbers []int, target int) []int { - for i, j := 0, len(numbers)-1; ; { - x := numbers[i] + numbers[j] - if x == target { - return []int{i + 1, j + 1} - } - if x < target { - i++ - } else { - j-- - } - } -} -``` - -### **TypeScript** - ```ts function twoSum(numbers: number[], target: number): number[] { const n = numbers.length; @@ -223,24 +140,32 @@ function twoSum(numbers: number[], target: number): number[] { } ``` -```ts -function twoSum(numbers: number[], target: number): number[] { - for (let i = 0, j = numbers.length - 1; ; ) { - const x = numbers[i] + numbers[j]; - if (x === target) { - return [i + 1, j + 1]; - } - if (x < target) { - ++i; - } else { - --j; +```rust +use std::cmp::Ordering; + +impl Solution { + pub fn two_sum(numbers: Vec, target: i32) -> Vec { + let n = numbers.len(); + let mut l = 0; + let mut r = n - 1; + loop { + match (numbers[l] + numbers[r]).cmp(&target) { + Ordering::Less => { + l += 1; + } + Ordering::Greater => { + r -= 1; + } + Ordering::Equal => { + break; + } + } } + vec![(l as i32) + 1, (r as i32) + 1] } } ``` -### **JavaScript** - ```js /** * @param {number[]} numbers @@ -268,6 +193,99 @@ var twoSum = function (numbers, target) { }; ``` + + +### Solution 2: Two Pointers + +We define two pointers $i$ and $j$, which point to the first element and the last element of the array respectively. Each time we calculate $numbers[i] + numbers[j]$. If the sum is equal to the target value, return $[i + 1, j + 1]$ directly. If the sum is less than the target value, move $i$ to the right by one position, and if the sum is greater than the target value, move $j$ to the left by one position. + +The time complexity is $O(n)$, where $n$ is the length of the array `numbers`. The space complexity is $O(1)$. + + + +```python +class Solution: + def twoSum(self, numbers: List[int], target: int) -> List[int]: + i, j = 0, len(numbers) - 1 + while i < j: + x = numbers[i] + numbers[j] + if x == target: + return [i + 1, j + 1] + if x < target: + i += 1 + else: + j -= 1 +``` + +```java +class Solution { + public int[] twoSum(int[] numbers, int target) { + for (int i = 0, j = numbers.length - 1;;) { + int x = numbers[i] + numbers[j]; + if (x == target) { + return new int[] {i + 1, j + 1}; + } + if (x < target) { + ++i; + } else { + --j; + } + } + } +} +``` + +```cpp +class Solution { +public: + vector twoSum(vector& numbers, int target) { + for (int i = 0, j = numbers.size() - 1;;) { + int x = numbers[i] + numbers[j]; + if (x == target) { + return {i + 1, j + 1}; + } + if (x < target) { + ++i; + } else { + --j; + } + } + } +}; +``` + +```go +func twoSum(numbers []int, target int) []int { + for i, j := 0, len(numbers)-1; ; { + x := numbers[i] + numbers[j] + if x == target { + return []int{i + 1, j + 1} + } + if x < target { + i++ + } else { + j-- + } + } +} +``` + +```ts +function twoSum(numbers: number[], target: number): number[] { + for (let i = 0, j = numbers.length - 1; ; ) { + const x = numbers[i] + numbers[j]; + if (x === target) { + return [i + 1, j + 1]; + } + if (x < target) { + ++i; + } else { + --j; + } + } +} +``` + ```js /** * @param {number[]} numbers @@ -289,38 +307,6 @@ var twoSum = function (numbers, target) { }; ``` -### **Rust** - -```rust -use std::cmp::Ordering; - -impl Solution { - pub fn two_sum(numbers: Vec, target: i32) -> Vec { - let n = numbers.len(); - let mut l = 0; - let mut r = n - 1; - loop { - match (numbers[l] + numbers[r]).cmp(&target) { - Ordering::Less => { - l += 1; - } - Ordering::Greater => { - r -= 1; - } - Ordering::Equal => { - break; - } - } - } - vec![(l as i32) + 1, (r as i32) + 1] - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0168.Excel Sheet Column Title/README.md b/solution/0100-0199/0168.Excel Sheet Column Title/README.md index a6cda436428d7..85c8c2efc3483 100644 --- a/solution/0100-0199/0168.Excel Sheet Column Title/README.md +++ b/solution/0100-0199/0168.Excel Sheet Column Title/README.md @@ -61,14 +61,10 @@ AB -> 28 ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def convertToTitle(self, columnNumber: int) -> str: @@ -80,10 +76,6 @@ class Solution: return ''.join(res[::-1]) ``` -### **Java** - - - ```java class Solution { public String convertToTitle(int columnNumber) { @@ -98,7 +90,30 @@ class Solution { } ``` -### **Rust** +```go +func convertToTitle(columnNumber int) string { + res := []rune{} + for columnNumber != 0 { + columnNumber -= 1 + res = append([]rune{rune(columnNumber%26 + int('A'))}, res...) + columnNumber /= 26 + } + return string(res) +} +``` + +```ts +function convertToTitle(columnNumber: number): string { + let res: string[] = []; + while (columnNumber > 0) { + --columnNumber; + let num: number = columnNumber % 26; + res.unshift(String.fromCharCode(num + 65)); + columnNumber = Math.floor(columnNumber / 26); + } + return res.join(''); +} +``` ```rust impl Solution { @@ -124,23 +139,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function convertToTitle(columnNumber: number): string { - let res: string[] = []; - while (columnNumber > 0) { - --columnNumber; - let num: number = columnNumber % 26; - res.unshift(String.fromCharCode(num + 65)); - columnNumber = Math.floor(columnNumber / 26); - } - return res.join(''); -} -``` - -### **C#** - ```cs public class Solution { public string ConvertToTitle(int columnNumber) { @@ -155,24 +153,6 @@ public class Solution { } ``` -### **Go** - -```go -func convertToTitle(columnNumber int) string { - res := []rune{} - for columnNumber != 0 { - columnNumber -= 1 - res = append([]rune{rune(columnNumber%26 + int('A'))}, res...) - columnNumber /= 26 - } - return string(res) -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0168.Excel Sheet Column Title/README_EN.md b/solution/0100-0199/0168.Excel Sheet Column Title/README_EN.md index f73f4fb5f7903..148ec00aba422 100644 --- a/solution/0100-0199/0168.Excel Sheet Column Title/README_EN.md +++ b/solution/0100-0199/0168.Excel Sheet Column Title/README_EN.md @@ -50,9 +50,9 @@ AB -> 28 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ''.join(res[::-1]) ``` -### **Java** - ```java class Solution { public String convertToTitle(int columnNumber) { @@ -81,7 +79,30 @@ class Solution { } ``` -### **Rust** +```go +func convertToTitle(columnNumber int) string { + res := []rune{} + for columnNumber != 0 { + columnNumber -= 1 + res = append([]rune{rune(columnNumber%26 + int('A'))}, res...) + columnNumber /= 26 + } + return string(res) +} +``` + +```ts +function convertToTitle(columnNumber: number): string { + let res: string[] = []; + while (columnNumber > 0) { + --columnNumber; + let num: number = columnNumber % 26; + res.unshift(String.fromCharCode(num + 65)); + columnNumber = Math.floor(columnNumber / 26); + } + return res.join(''); +} +``` ```rust impl Solution { @@ -107,23 +128,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function convertToTitle(columnNumber: number): string { - let res: string[] = []; - while (columnNumber > 0) { - --columnNumber; - let num: number = columnNumber % 26; - res.unshift(String.fromCharCode(num + 65)); - columnNumber = Math.floor(columnNumber / 26); - } - return res.join(''); -} -``` - -### **C#** - ```cs public class Solution { public string ConvertToTitle(int columnNumber) { @@ -138,24 +142,6 @@ public class Solution { } ``` -### **Go** - -```go -func convertToTitle(columnNumber int) string { - res := []rune{} - for columnNumber != 0 { - columnNumber -= 1 - res = append([]rune{rune(columnNumber%26 + int('A'))}, res...) - columnNumber /= 26 - } - return string(res) -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0169.Majority Element/README.md b/solution/0100-0199/0169.Majority Element/README.md index 37e1c984f83cc..68a0889ff56b1 100644 --- a/solution/0100-0199/0169.Majority Element/README.md +++ b/solution/0100-0199/0169.Majority Element/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:摩尔投票法** +### 方法一:摩尔投票法 摩尔投票法的基本步骤如下: @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def majorityElement(self, nums: List[int]) -> int: @@ -73,10 +67,6 @@ class Solution: return m ``` -### **Java** - - - ```java class Solution { public int majorityElement(int[] nums) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func majorityElement(nums []int) int { var cnt, m int @@ -134,8 +120,6 @@ func majorityElement(nums []int) int { } ``` -### **TypeScript** - ```ts function majorityElement(nums: number[]): number { let cnt: number = 0; @@ -152,7 +136,23 @@ function majorityElement(nums: number[]): number { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn majority_element(nums: Vec) -> i32 { + let mut m = 0; + let mut cnt = 0; + for &x in nums.iter() { + if cnt == 0 { + m = x; + cnt = 1; + } else { + cnt += if m == x { 1 } else { -1 }; + } + } + m + } +} +``` ```js /** @@ -174,8 +174,6 @@ var majorityElement = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public int MajorityElement(int[] nums) { @@ -193,28 +191,6 @@ public class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn majority_element(nums: Vec) -> i32 { - let mut m = 0; - let mut cnt = 0; - for &x in nums.iter() { - if cnt == 0 { - m = x; - cnt = 1; - } else { - cnt += if m == x { 1 } else { -1 }; - } - } - m - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -239,10 +215,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0169.Majority Element/README_EN.md b/solution/0100-0199/0169.Majority Element/README_EN.md index 342710156b922..c4c2f7e7f02e8 100644 --- a/solution/0100-0199/0169.Majority Element/README_EN.md +++ b/solution/0100-0199/0169.Majority Element/README_EN.md @@ -30,7 +30,7 @@ ## Solutions -**Solution 1: Moore Voting Algorithm** +### Solution 1: Moore Voting Algorithm The basic steps of the Moore voting algorithm are as follows: @@ -45,8 +45,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def majorityElement(self, nums: List[int]) -> int: @@ -59,8 +57,6 @@ class Solution: return m ``` -### **Java** - ```java class Solution { public int majorityElement(int[] nums) { @@ -78,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +92,6 @@ public: }; ``` -### **Go** - ```go func majorityElement(nums []int) int { var cnt, m int @@ -118,8 +110,6 @@ func majorityElement(nums []int) int { } ``` -### **TypeScript** - ```ts function majorityElement(nums: number[]): number { let cnt: number = 0; @@ -136,7 +126,23 @@ function majorityElement(nums: number[]): number { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn majority_element(nums: Vec) -> i32 { + let mut m = 0; + let mut cnt = 0; + for &x in nums.iter() { + if cnt == 0 { + m = x; + cnt = 1; + } else { + cnt += if m == x { 1 } else { -1 }; + } + } + m + } +} +``` ```js /** @@ -158,8 +164,6 @@ var majorityElement = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public int MajorityElement(int[] nums) { @@ -177,28 +181,6 @@ public class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn majority_element(nums: Vec) -> i32 { - let mut m = 0; - let mut cnt = 0; - for &x in nums.iter() { - if cnt == 0 { - m = x; - cnt = 1; - } else { - cnt += if m == x { 1 } else { -1 }; - } - } - m - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -223,10 +205,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0170.Two Sum III - Data structure design/README.md b/solution/0100-0199/0170.Two Sum III - Data structure design/README.md index 12388102a5446..4eadedf3a4a0e 100644 --- a/solution/0100-0199/0170.Two Sum III - Data structure design/README.md +++ b/solution/0100-0199/0170.Two Sum III - Data structure design/README.md @@ -47,9 +47,7 @@ twoSum.find(7); // 没有两个整数加起来等于 7 ,返回 false ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们用哈希表 `cnt` 存储数字出现的次数。 @@ -66,10 +64,6 @@ twoSum.find(7); // 没有两个整数加起来等于 7 ,返回 false -### **Python3** - - - ```python class TwoSum: def __init__(self): @@ -93,10 +87,6 @@ class TwoSum: # param_2 = obj.find(value) ``` -### **Java** - - - ```java class TwoSum { private Map cnt = new HashMap<>(); @@ -130,8 +120,6 @@ class TwoSum { */ ``` -### **C++** - ```cpp class TwoSum { public: @@ -166,8 +154,6 @@ private: */ ``` -### **Go** - ```go type TwoSum struct { cnt map[int]int @@ -199,10 +185,6 @@ func (this *TwoSum) Find(value int) bool { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0170.Two Sum III - Data structure design/README_EN.md b/solution/0100-0199/0170.Two Sum III - Data structure design/README_EN.md index 8d6e6a35a2ca9..9069f1f7b2eb8 100644 --- a/solution/0100-0199/0170.Two Sum III - Data structure design/README_EN.md +++ b/solution/0100-0199/0170.Two Sum III - Data structure design/README_EN.md @@ -44,9 +44,9 @@ twoSum.find(7); // No two integers sum up to 7, return false ## Solutions - +### Solution 1 -### **Python3** + ```python class TwoSum: @@ -71,8 +71,6 @@ class TwoSum: # param_2 = obj.find(value) ``` -### **Java** - ```java class TwoSum { private Map cnt = new HashMap<>(); @@ -106,8 +104,6 @@ class TwoSum { */ ``` -### **C++** - ```cpp class TwoSum { public: @@ -142,8 +138,6 @@ private: */ ``` -### **Go** - ```go type TwoSum struct { cnt map[int]int @@ -175,10 +169,6 @@ func (this *TwoSum) Find(value int) bool { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0171.Excel Sheet Column Number/README.md b/solution/0100-0199/0171.Excel Sheet Column Number/README.md index 88e2a0c876e80..eedd78e6db7f0 100644 --- a/solution/0100-0199/0171.Excel Sheet Column Number/README.md +++ b/solution/0100-0199/0171.Excel Sheet Column Number/README.md @@ -54,14 +54,10 @@ AB -> 28 ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def titleToNumber(self, columnTitle: str) -> int: @@ -71,10 +67,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int titleToNumber(String columnTitle) { @@ -87,20 +79,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function titleToNumber(columnTitle: string): number { - let res: number = 0; - for (let char of columnTitle) { - res = res * 26 + char.charCodeAt(0) - 64; - } - return res; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -114,8 +92,6 @@ public: }; ``` -### **Go** - ```go func titleToNumber(columnTitle string) int { res := 0 @@ -126,10 +102,16 @@ func titleToNumber(columnTitle string) int { } ``` -### **...** - -``` - +```ts +function titleToNumber(columnTitle: string): number { + let res: number = 0; + for (let char of columnTitle) { + res = res * 26 + char.charCodeAt(0) - 64; + } + return res; +} ``` + + diff --git a/solution/0100-0199/0171.Excel Sheet Column Number/README_EN.md b/solution/0100-0199/0171.Excel Sheet Column Number/README_EN.md index 2e367a4d77b81..a66f342f98689 100644 --- a/solution/0100-0199/0171.Excel Sheet Column Number/README_EN.md +++ b/solution/0100-0199/0171.Excel Sheet Column Number/README_EN.md @@ -52,9 +52,9 @@ AB -> 28 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public int titleToNumber(String columnTitle) { @@ -79,20 +77,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function titleToNumber(columnTitle: string): number { - let res: number = 0; - for (let char of columnTitle) { - res = res * 26 + char.charCodeAt(0) - 64; - } - return res; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -106,8 +90,6 @@ public: }; ``` -### **Go** - ```go func titleToNumber(columnTitle string) int { res := 0 @@ -118,10 +100,16 @@ func titleToNumber(columnTitle string) int { } ``` -### **...** - -``` - +```ts +function titleToNumber(columnTitle: string): number { + let res: number = 0; + for (let char of columnTitle) { + res = res * 26 + char.charCodeAt(0) - 64; + } + return res; +} ``` + + diff --git a/solution/0100-0199/0172.Factorial Trailing Zeroes/README.md b/solution/0100-0199/0172.Factorial Trailing Zeroes/README.md index 7fde2b12479b8..d0270019048e2 100644 --- a/solution/0100-0199/0172.Factorial Trailing Zeroes/README.md +++ b/solution/0100-0199/0172.Factorial Trailing Zeroes/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 题目实际上是求 $[1,n]$ 中有多少个 $5$ 的因数。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def trailingZeroes(self, n: int) -> int: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int trailingZeroes(int n) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func trailingZeroes(n int) int { ans := 0 @@ -126,8 +112,6 @@ func trailingZeroes(n int) int { } ``` -### **TypeScript** - ```ts function trailingZeroes(n: number): number { let ans = 0; @@ -139,10 +123,6 @@ function trailingZeroes(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0172.Factorial Trailing Zeroes/README_EN.md b/solution/0100-0199/0172.Factorial Trailing Zeroes/README_EN.md index 5111bd6124c08..63d89304e76e9 100644 --- a/solution/0100-0199/0172.Factorial Trailing Zeroes/README_EN.md +++ b/solution/0100-0199/0172.Factorial Trailing Zeroes/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int trailingZeroes(int n) { @@ -73,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,8 +85,6 @@ public: }; ``` -### **Go** - ```go func trailingZeroes(n int) int { ans := 0 @@ -102,8 +96,6 @@ func trailingZeroes(n int) int { } ``` -### **TypeScript** - ```ts function trailingZeroes(n: number): number { let ans = 0; @@ -115,10 +107,6 @@ function trailingZeroes(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0173.Binary Search Tree Iterator/README.md b/solution/0100-0199/0173.Binary Search Tree Iterator/README.md index 80a8a21006423..aa7b9cb18bee5 100644 --- a/solution/0100-0199/0173.Binary Search Tree Iterator/README.md +++ b/solution/0100-0199/0173.Binary Search Tree Iterator/README.md @@ -67,26 +67,14 @@ bSTIterator.hasNext(); // 返回 False ## 解法 - - -**方法一:递归** +### 方法一:递归 初始化数据时,递归中序遍历,将二叉搜索树每个结点的值保存在列表 `vals` 中。用 `cur` 指针记录外部即将遍历的位置,初始化为 0。 调用 `next()` 时,返回 `vals[cur]`,同时 `cur` 指针自增。调用 `hasNext()` 时,判断 `cur` 指针是否已经达到 `len(vals)` 个数,若是,说明已经遍历结束,返回 false,否则返回 true。 -**方法二:栈迭代** - -初始化时,从根节点一路遍历所有左子节点,压入栈 `stack` 中。 - -调用 `next()`时,弹出栈顶元素 `cur`,获取 `cur` 的右子节点 `node`,若 `node` 不为空,一直循环压入左节点。最后返回 `cur.val` 即可。调用 `hasNext()` 时,判断 `stack` 是否为空,空则表示迭代结束。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -121,42 +109,6 @@ class BSTIterator: # param_2 = obj.hasNext() ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class BSTIterator: - def __init__(self, root: TreeNode): - self.stack = [] - while root: - self.stack.append(root) - root = root.left - - def next(self) -> int: - cur = self.stack.pop() - node = cur.right - while node: - self.stack.append(node) - node = node.left - return cur.val - - def hasNext(self) -> bool: - return len(self.stack) > 0 - - -# Your BSTIterator object will be instantiated and called as such: -# obj = BSTIterator(root) -# param_1 = obj.next() -# param_2 = obj.hasNext() -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -206,54 +158,6 @@ class BSTIterator { */ ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class BSTIterator { - private Deque stack = new LinkedList<>(); - - public BSTIterator(TreeNode root) { - for (; root != null; root = root.left) { - stack.offerLast(root); - } - } - - public int next() { - TreeNode cur = stack.pollLast(); - for (TreeNode node = cur.right; node != null; node = node.left) { - stack.offerLast(node); - } - return cur.val; - } - - public boolean hasNext() { - return !stack.isEmpty(); - } -} - -/** - * Your BSTIterator object will be instantiated and called as such: - * BSTIterator obj = new BSTIterator(root); - * int param_1 = obj.next(); - * boolean param_2 = obj.hasNext(); - */ -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -300,52 +204,6 @@ public: */ ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class BSTIterator { -public: - stack stack; - BSTIterator(TreeNode* root) { - for (; root != nullptr; root = root->left) { - stack.push(root); - } - } - - int next() { - TreeNode* cur = stack.top(); - stack.pop(); - TreeNode* node = cur->right; - for (; node != nullptr; node = node->left) { - stack.push(node); - } - return cur->val; - } - - bool hasNext() { - return !stack.empty(); - } -}; - -/** - * Your BSTIterator object will be instantiated and called as such: - * BSTIterator* obj = new BSTIterator(root); - * int param_1 = obj->next(); - * bool param_2 = obj->hasNext(); - */ -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -390,7 +248,121 @@ func (this *BSTIterator) HasNext() bool { */ ``` -## **JavaScript** +```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) + * } + * } + */ + +class BSTIterator { + private data: number[]; + private index: number; + + constructor(root: TreeNode | null) { + this.index = 0; + this.data = []; + const dfs = (root: TreeNode | null) => { + if (root == null) { + return; + } + const { val, left, right } = root; + dfs(left); + this.data.push(val); + dfs(right); + }; + dfs(root); + } + + next(): number { + return this.data[this.index++]; + } + + hasNext(): boolean { + return this.index < this.data.length; + } +} + +/** + * Your BSTIterator object will be instantiated and called as such: + * var obj = new BSTIterator(root) + * var param_1 = obj.next() + * var param_2 = obj.hasNext() + */ +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +struct BSTIterator { + vals: Vec, + index: usize, +} + +use std::rc::Rc; +use std::cell::RefCell; +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl BSTIterator { + fn inorder(root: &Option>>, res: &mut Vec) { + if let Some(node) = root { + let node = node.as_ref().borrow(); + Self::inorder(&node.left, res); + res.push(node.val); + Self::inorder(&node.right, res); + } + } + + fn new(root: Option>>) -> Self { + let mut vals = vec![]; + Self::inorder(&root, &mut vals); + BSTIterator { + vals, + index: 0, + } + } + + fn next(&mut self) -> i32 { + self.index += 1; + self.vals[self.index - 1] + } + + fn has_next(&self) -> bool { + self.index != self.vals.len() + } +}/** + * Your BSTIterator object will be instantiated and called as such: + * let obj = BSTIterator::new(root); + * let ret_1: i32 = obj.next(); + * let ret_2: bool = obj.has_next(); + */ +``` ```js /** @@ -438,56 +410,135 @@ BSTIterator.prototype.hasNext = function () { */ ``` -### **TypeScript** + -```ts +### 方法二:栈迭代 + +初始化时,从根节点一路遍历所有左子节点,压入栈 `stack` 中。 + +调用 `next()`时,弹出栈顶元素 `cur`,获取 `cur` 的右子节点 `node`,若 `node` 不为空,一直循环压入左节点。最后返回 `cur.val` 即可。调用 `hasNext()` 时,判断 `stack` 是否为空,空则表示迭代结束。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class BSTIterator: + def __init__(self, root: TreeNode): + self.stack = [] + while root: + self.stack.append(root) + root = root.left + + def next(self) -> int: + cur = self.stack.pop() + node = cur.right + while node: + self.stack.append(node) + node = node.left + return cur.val + + def hasNext(self) -> bool: + return len(self.stack) > 0 + + +# Your BSTIterator object will be instantiated and called as such: +# obj = BSTIterator(root) +# param_1 = obj.next() +# param_2 = obj.hasNext() +``` + +```java /** * 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) + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; * } * } */ - class BSTIterator { - private data: number[]; - private index: number; + private Deque stack = new LinkedList<>(); - constructor(root: TreeNode | null) { - this.index = 0; - this.data = []; - const dfs = (root: TreeNode | null) => { - if (root == null) { - return; - } - const { val, left, right } = root; - dfs(left); - this.data.push(val); - dfs(right); - }; - dfs(root); + public BSTIterator(TreeNode root) { + for (; root != null; root = root.left) { + stack.offerLast(root); + } } - next(): number { - return this.data[this.index++]; + public int next() { + TreeNode cur = stack.pollLast(); + for (TreeNode node = cur.right; node != null; node = node.left) { + stack.offerLast(node); + } + return cur.val; } - hasNext(): boolean { - return this.index < this.data.length; + public boolean hasNext() { + return !stack.isEmpty(); } } /** * Your BSTIterator object will be instantiated and called as such: - * var obj = new BSTIterator(root) - * var param_1 = obj.next() - * var param_2 = obj.hasNext() + * BSTIterator obj = new BSTIterator(root); + * int param_1 = obj.next(); + * boolean param_2 = obj.hasNext(); + */ +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class BSTIterator { +public: + stack stack; + BSTIterator(TreeNode* root) { + for (; root != nullptr; root = root->left) { + stack.push(root); + } + } + + int next() { + TreeNode* cur = stack.top(); + stack.pop(); + TreeNode* node = cur->right; + for (; node != nullptr; node = node->left) { + stack.push(node); + } + return cur->val; + } + + bool hasNext() { + return !stack.empty(); + } +}; + +/** + * Your BSTIterator object will be instantiated and called as such: + * BSTIterator* obj = new BSTIterator(root); + * int param_1 = obj->next(); + * bool param_2 = obj->hasNext(); */ ``` @@ -546,73 +597,6 @@ class BSTIterator { */ ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -struct BSTIterator { - vals: Vec, - index: usize, -} - -use std::rc::Rc; -use std::cell::RefCell; -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl BSTIterator { - fn inorder(root: &Option>>, res: &mut Vec) { - if let Some(node) = root { - let node = node.as_ref().borrow(); - Self::inorder(&node.left, res); - res.push(node.val); - Self::inorder(&node.right, res); - } - } - - fn new(root: Option>>) -> Self { - let mut vals = vec![]; - Self::inorder(&root, &mut vals); - BSTIterator { - vals, - index: 0, - } - } - - fn next(&mut self) -> i32 { - self.index += 1; - self.vals[self.index - 1] - } - - fn has_next(&self) -> bool { - self.index != self.vals.len() - } -}/** - * Your BSTIterator object will be instantiated and called as such: - * let obj = BSTIterator::new(root); - * let ret_1: i32 = obj.next(); - * let ret_2: bool = obj.has_next(); - */ -``` - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -680,10 +664,6 @@ impl BSTIterator { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0173.Binary Search Tree Iterator/README_EN.md b/solution/0100-0199/0173.Binary Search Tree Iterator/README_EN.md index 3612731ccf011..bbf0889193739 100644 --- a/solution/0100-0199/0173.Binary Search Tree Iterator/README_EN.md +++ b/solution/0100-0199/0173.Binary Search Tree Iterator/README_EN.md @@ -58,9 +58,9 @@ bSTIterator.hasNext(); // return False ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -96,40 +96,6 @@ class BSTIterator: # param_2 = obj.hasNext() ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class BSTIterator: - def __init__(self, root: TreeNode): - self.stack = [] - while root: - self.stack.append(root) - root = root.left - - def next(self) -> int: - cur = self.stack.pop() - node = cur.right - while node: - self.stack.append(node) - node = node.left - return cur.val - - def hasNext(self) -> bool: - return len(self.stack) > 0 - - -# Your BSTIterator object will be instantiated and called as such: -# obj = BSTIterator(root) -# param_1 = obj.next() -# param_2 = obj.hasNext() -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -179,54 +145,6 @@ class BSTIterator { */ ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class BSTIterator { - private Deque stack = new LinkedList<>(); - - public BSTIterator(TreeNode root) { - for (; root != null; root = root.left) { - stack.offerLast(root); - } - } - - public int next() { - TreeNode cur = stack.pollLast(); - for (TreeNode node = cur.right; node != null; node = node.left) { - stack.offerLast(node); - } - return cur.val; - } - - public boolean hasNext() { - return !stack.isEmpty(); - } -} - -/** - * Your BSTIterator object will be instantiated and called as such: - * BSTIterator obj = new BSTIterator(root); - * int param_1 = obj.next(); - * boolean param_2 = obj.hasNext(); - */ -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -273,52 +191,6 @@ public: */ ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class BSTIterator { -public: - stack stack; - BSTIterator(TreeNode* root) { - for (; root != nullptr; root = root->left) { - stack.push(root); - } - } - - int next() { - TreeNode* cur = stack.top(); - stack.pop(); - TreeNode* node = cur->right; - for (; node != nullptr; node = node->left) { - stack.push(node); - } - return cur->val; - } - - bool hasNext() { - return !stack.empty(); - } -}; - -/** - * Your BSTIterator object will be instantiated and called as such: - * BSTIterator* obj = new BSTIterator(root); - * int param_1 = obj->next(); - * bool param_2 = obj->hasNext(); - */ -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -363,7 +235,121 @@ func (this *BSTIterator) HasNext() bool { */ ``` -## **JavaScript** +```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) + * } + * } + */ + +class BSTIterator { + private data: number[]; + private index: number; + + constructor(root: TreeNode | null) { + this.index = 0; + this.data = []; + const dfs = (root: TreeNode | null) => { + if (root == null) { + return; + } + const { val, left, right } = root; + dfs(left); + this.data.push(val); + dfs(right); + }; + dfs(root); + } + + next(): number { + return this.data[this.index++]; + } + + hasNext(): boolean { + return this.index < this.data.length; + } +} + +/** + * Your BSTIterator object will be instantiated and called as such: + * var obj = new BSTIterator(root) + * var param_1 = obj.next() + * var param_2 = obj.hasNext() + */ +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +struct BSTIterator { + vals: Vec, + index: usize, +} + +use std::rc::Rc; +use std::cell::RefCell; +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl BSTIterator { + fn inorder(root: &Option>>, res: &mut Vec) { + if let Some(node) = root { + let node = node.as_ref().borrow(); + Self::inorder(&node.left, res); + res.push(node.val); + Self::inorder(&node.right, res); + } + } + + fn new(root: Option>>) -> Self { + let mut vals = vec![]; + Self::inorder(&root, &mut vals); + BSTIterator { + vals, + index: 0, + } + } + + fn next(&mut self) -> i32 { + self.index += 1; + self.vals[self.index - 1] + } + + fn has_next(&self) -> bool { + self.index != self.vals.len() + } +}/** + * Your BSTIterator object will be instantiated and called as such: + * let obj = BSTIterator::new(root); + * let ret_1: i32 = obj.next(); + * let ret_2: bool = obj.has_next(); + */ +``` ```js /** @@ -411,56 +397,131 @@ BSTIterator.prototype.hasNext = function () { */ ``` -### **TypeScript** + -```ts +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class BSTIterator: + def __init__(self, root: TreeNode): + self.stack = [] + while root: + self.stack.append(root) + root = root.left + + def next(self) -> int: + cur = self.stack.pop() + node = cur.right + while node: + self.stack.append(node) + node = node.left + return cur.val + + def hasNext(self) -> bool: + return len(self.stack) > 0 + + +# Your BSTIterator object will be instantiated and called as such: +# obj = BSTIterator(root) +# param_1 = obj.next() +# param_2 = obj.hasNext() +``` + +```java /** * 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) + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; * } * } */ - class BSTIterator { - private data: number[]; - private index: number; + private Deque stack = new LinkedList<>(); - constructor(root: TreeNode | null) { - this.index = 0; - this.data = []; - const dfs = (root: TreeNode | null) => { - if (root == null) { - return; - } - const { val, left, right } = root; - dfs(left); - this.data.push(val); - dfs(right); - }; - dfs(root); + public BSTIterator(TreeNode root) { + for (; root != null; root = root.left) { + stack.offerLast(root); + } } - next(): number { - return this.data[this.index++]; + public int next() { + TreeNode cur = stack.pollLast(); + for (TreeNode node = cur.right; node != null; node = node.left) { + stack.offerLast(node); + } + return cur.val; } - hasNext(): boolean { - return this.index < this.data.length; + public boolean hasNext() { + return !stack.isEmpty(); } } /** * Your BSTIterator object will be instantiated and called as such: - * var obj = new BSTIterator(root) - * var param_1 = obj.next() - * var param_2 = obj.hasNext() + * BSTIterator obj = new BSTIterator(root); + * int param_1 = obj.next(); + * boolean param_2 = obj.hasNext(); + */ +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class BSTIterator { +public: + stack stack; + BSTIterator(TreeNode* root) { + for (; root != nullptr; root = root->left) { + stack.push(root); + } + } + + int next() { + TreeNode* cur = stack.top(); + stack.pop(); + TreeNode* node = cur->right; + for (; node != nullptr; node = node->left) { + stack.push(node); + } + return cur->val; + } + + bool hasNext() { + return !stack.empty(); + } +}; + +/** + * Your BSTIterator object will be instantiated and called as such: + * BSTIterator* obj = new BSTIterator(root); + * int param_1 = obj->next(); + * bool param_2 = obj->hasNext(); */ ``` @@ -519,73 +580,6 @@ class BSTIterator { */ ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -struct BSTIterator { - vals: Vec, - index: usize, -} - -use std::rc::Rc; -use std::cell::RefCell; -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl BSTIterator { - fn inorder(root: &Option>>, res: &mut Vec) { - if let Some(node) = root { - let node = node.as_ref().borrow(); - Self::inorder(&node.left, res); - res.push(node.val); - Self::inorder(&node.right, res); - } - } - - fn new(root: Option>>) -> Self { - let mut vals = vec![]; - Self::inorder(&root, &mut vals); - BSTIterator { - vals, - index: 0, - } - } - - fn next(&mut self) -> i32 { - self.index += 1; - self.vals[self.index - 1] - } - - fn has_next(&self) -> bool { - self.index != self.vals.len() - } -}/** - * Your BSTIterator object will be instantiated and called as such: - * let obj = BSTIterator::new(root); - * let ret_1: i32 = obj.next(); - * let ret_2: bool = obj.has_next(); - */ -``` - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -653,10 +647,6 @@ impl BSTIterator { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0174.Dungeon Game/README.md b/solution/0100-0199/0174.Dungeon Game/README.md index c8e124cf18486..3c752e929eb49 100644 --- a/solution/0100-0199/0174.Dungeon Game/README.md +++ b/solution/0100-0199/0174.Dungeon Game/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 定义 $dp[i][j]$ 表示从 $(i, j)$ 到终点所需的最小初始值,那么 $dp[i][j]$ 的值可以由 $dp[i+1][j]$ 和 $dp[i][j+1]$ 得到,即: @@ -73,10 +71,6 @@ $$ -### **Python3** - - - ```python class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: @@ -89,10 +83,6 @@ class Solution: return dp[0][0] ``` -### **Java** - - - ```java class Solution { public int calculateMinimumHP(int[][] dungeon) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go func calculateMinimumHP(dungeon [][]int) int { m, n := len(dungeon), len(dungeon[0]) @@ -154,8 +140,6 @@ func calculateMinimumHP(dungeon [][]int) int { } ``` -### **C#** - ```cs public class Solution { public int CalculateMinimumHP(int[][] dungeon) { @@ -176,10 +160,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0174.Dungeon Game/README_EN.md b/solution/0100-0199/0174.Dungeon Game/README_EN.md index 787b8e52a4a7f..f2cb1f4aba705 100644 --- a/solution/0100-0199/0174.Dungeon Game/README_EN.md +++ b/solution/0100-0199/0174.Dungeon Game/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return dp[0][0] ``` -### **Java** - ```java class Solution { public int calculateMinimumHP(int[][] dungeon) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +97,6 @@ public: }; ``` -### **Go** - ```go func calculateMinimumHP(dungeon [][]int) int { m, n := len(dungeon), len(dungeon[0]) @@ -123,8 +117,6 @@ func calculateMinimumHP(dungeon [][]int) int { } ``` -### **C#** - ```cs public class Solution { public int CalculateMinimumHP(int[][] dungeon) { @@ -145,10 +137,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0175.Combine Two Tables/README.md b/solution/0100-0199/0175.Combine Two Tables/README.md index e6c97f4f66d3a..bddf1bb2e2150 100644 --- a/solution/0100-0199/0175.Combine Two Tables/README.md +++ b/solution/0100-0199/0175.Combine Two Tables/README.md @@ -78,26 +78,12 @@ addressId = 1 包含了 personId = 2 的地址信息。 ## 解法 - - -**方法一:左连接** +### 方法一:左连接 我们可以使用左连接,将 `Person` 表左连接 `Address` 表,连接条件为 `Person.personId = Address.personId`,这样就可以得到每个人的姓、名、城市和州。如果 `personId` 的地址不在 `Address` 表中,则报告为空 `null`。 -### **SQL** - -```sql -# Write your MySQL query statement below -SELECT firstName, lastName, city, state -FROM - Person - LEFT JOIN Address USING (personId); -``` - -### **Pandas** - ```python import pandas as pd @@ -108,4 +94,14 @@ def combine_two_tables(person: pd.DataFrame, address: pd.DataFrame) -> pd.DataFr ] ``` +```sql +# Write your MySQL query statement below +SELECT firstName, lastName, city, state +FROM + Person + LEFT JOIN Address USING (personId); +``` + + + diff --git a/solution/0100-0199/0175.Combine Two Tables/README_EN.md b/solution/0100-0199/0175.Combine Two Tables/README_EN.md index 9dea3d587ccac..92375ff062329 100644 --- a/solution/0100-0199/0175.Combine Two Tables/README_EN.md +++ b/solution/0100-0199/0175.Combine Two Tables/README_EN.md @@ -76,24 +76,12 @@ addressId = 1 contains information about the address of personId = 2. ## Solutions -**Solution 1: LEFT JOIN** +### Solution 1: LEFT JOIN We can use a left join to join the `Person` table with the `Address` table on the condition `Person.personId = Address.personId`, which will give us the first name, last name, city, and state of each person. If the address of a `personId` is not in the `Address` table, it will be reported as `null`. -### **SQL** - -```sql -# Write your MySQL query statement below -SELECT firstName, lastName, city, state -FROM - Person - LEFT JOIN Address USING (personId); -``` - -### **Pandas** - ```python import pandas as pd @@ -104,4 +92,14 @@ def combine_two_tables(person: pd.DataFrame, address: pd.DataFrame) -> pd.DataFr ] ``` +```sql +# Write your MySQL query statement below +SELECT firstName, lastName, city, state +FROM + Person + LEFT JOIN Address USING (personId); +``` + + + diff --git a/solution/0100-0199/0176.Second Highest Salary/README.md b/solution/0100-0199/0176.Second Highest Salary/README.md index ca8b5820d9978..020ce9476875a 100644 --- a/solution/0100-0199/0176.Second Highest Salary/README.md +++ b/solution/0100-0199/0176.Second Highest Salary/README.md @@ -71,23 +71,34 @@ Employee 表: ## 解法 - - -**方法一:使用 LIMIT 语句和子查询** +### 方法一:使用 LIMIT 语句和子查询 我们可以按照薪水降序排列,然后使用 `LIMIT` 语句来获取第二高的薪水,如果不存在第二高的薪水,那么就返回 `null`。 -**方法二:使用 MAX() 函数和子查询** + -我们也可以使用 `MAX()` 函数,从小于 `MAX()` 的薪水中挑选一个最大的薪水即可。 +```python +import pandas as pd -**方法三:使用 DISTINCT 和窗口函数** -我们还可以先通过 `DENSE_RANK()` 函数计算出每个员工的薪水排名,然后再筛选出排名为 $2$ 的员工薪水即可。 +def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame: + # Drop any duplicate salary values to avoid counting duplicates as separate salary ranks + unique_salaries = employee["salary"].drop_duplicates() - + # Sort the unique salaries in descending order and get the second highest salary + second_highest = ( + unique_salaries.nlargest(2).iloc[-1] if len(unique_salaries) >= 2 else None + ) -### **SQL** + # If the second highest salary doesn't exist (e.g., there are fewer than two unique salaries), return None + if second_highest is None: + return pd.DataFrame({"SecondHighestSalary": [None]}) + + # Create a DataFrame with the second highest salary + result_df = pd.DataFrame({"SecondHighestSalary": [second_highest]}) + + return result_df +``` ```sql # Write your MySQL query statement below @@ -100,6 +111,14 @@ SELECT ) AS SecondHighestSalary; ``` + + +### 方法二:使用 MAX() 函数和子查询 + +我们也可以使用 `MAX()` 函数,从小于 `MAX()` 的薪水中挑选一个最大的薪水即可。 + + + ```sql # Write your MySQL query statement below SELECT MAX(salary) AS SecondHighestSalary @@ -107,35 +126,20 @@ FROM Employee WHERE salary < (SELECT MAX(salary) FROM Employee); ``` -```sql -# Write your MySQL query statement below -WITH T AS (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rk FROM Employee) -SELECT (SELECT DISTINCT salary FROM T WHERE rk = 2) AS SecondHighestSalary; -``` - -### **Pandas** - -```python -import pandas as pd - + -def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame: - # Drop any duplicate salary values to avoid counting duplicates as separate salary ranks - unique_salaries = employee["salary"].drop_duplicates() +### 方法三:使用 DISTINCT 和窗口函数 - # Sort the unique salaries in descending order and get the second highest salary - second_highest = ( - unique_salaries.nlargest(2).iloc[-1] if len(unique_salaries) >= 2 else None - ) - - # If the second highest salary doesn't exist (e.g., there are fewer than two unique salaries), return None - if second_highest is None: - return pd.DataFrame({"SecondHighestSalary": [None]}) +我们还可以先通过 `DENSE_RANK()` 函数计算出每个员工的薪水排名,然后再筛选出排名为 $2$ 的员工薪水即可。 - # Create a DataFrame with the second highest salary - result_df = pd.DataFrame({"SecondHighestSalary": [second_highest]}) + - return result_df +```sql +# Write your MySQL query statement below +WITH T AS (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rk FROM Employee) +SELECT (SELECT DISTINCT salary FROM T WHERE rk = 2) AS SecondHighestSalary; ``` + + diff --git a/solution/0100-0199/0176.Second Highest Salary/README_EN.md b/solution/0100-0199/0176.Second Highest Salary/README_EN.md index 10f92131487bb..cc55eed831ddc 100644 --- a/solution/0100-0199/0176.Second Highest Salary/README_EN.md +++ b/solution/0100-0199/0176.Second Highest Salary/README_EN.md @@ -64,15 +64,32 @@ Employee table: ## Solutions -**Solution 1: Use Sub Query and LIMIT** +### Solution 1: Use Sub Query and LIMIT -**Solution 2: Use `MAX()` function** + -**Solution 3: Use `IFNULL()` and window function** +```python +import pandas as pd - -### **SQL** +def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame: + # Drop any duplicate salary values to avoid counting duplicates as separate salary ranks + unique_salaries = employee["salary"].drop_duplicates() + + # Sort the unique salaries in descending order and get the second highest salary + second_highest = ( + unique_salaries.nlargest(2).iloc[-1] if len(unique_salaries) >= 2 else None + ) + + # If the second highest salary doesn't exist (e.g., there are fewer than two unique salaries), return None + if second_highest is None: + return pd.DataFrame({"SecondHighestSalary": [None]}) + + # Create a DataFrame with the second highest salary + result_df = pd.DataFrame({"SecondHighestSalary": [second_highest]}) + + return result_df +``` ```sql # Write your MySQL query statement below @@ -85,6 +102,12 @@ SELECT ) AS SecondHighestSalary; ``` + + +### Solution 2: Use `MAX()` function + + + ```sql # Write your MySQL query statement below SELECT MAX(salary) AS SecondHighestSalary @@ -92,35 +115,18 @@ FROM Employee WHERE salary < (SELECT MAX(salary) FROM Employee); ``` + + +### Solution 3: Use `IFNULL()` and window function + + + ```sql # Write your MySQL query statement below WITH T AS (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rk FROM Employee) SELECT (SELECT DISTINCT salary FROM T WHERE rk = 2) AS SecondHighestSalary; ``` -### **Pandas** - -```python -import pandas as pd - - -def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame: - # Drop any duplicate salary values to avoid counting duplicates as separate salary ranks - unique_salaries = employee["salary"].drop_duplicates() - - # Sort the unique salaries in descending order and get the second highest salary - second_highest = ( - unique_salaries.nlargest(2).iloc[-1] if len(unique_salaries) >= 2 else None - ) - - # If the second highest salary doesn't exist (e.g., there are fewer than two unique salaries), return None - if second_highest is None: - return pd.DataFrame({"SecondHighestSalary": [None]}) - - # Create a DataFrame with the second highest salary - result_df = pd.DataFrame({"SecondHighestSalary": [second_highest]}) - - return result_df -``` - + + diff --git a/solution/0100-0199/0177.Nth Highest Salary/README.md b/solution/0100-0199/0177.Nth Highest Salary/README.md index 759fa5735f347..86b04b588c4c0 100644 --- a/solution/0100-0199/0177.Nth Highest Salary/README.md +++ b/solution/0100-0199/0177.Nth Highest Salary/README.md @@ -68,15 +68,24 @@ n = 2 ## 解法 - - -**方法一:排序 + LIMIT** +### 方法一:排序 + LIMIT 我们可以先对 `salary` 进行降序排序,然后使用 `LIMIT` 语句获取第 $n$ 高的工资。 -### **SQL** +```python +import pandas as pd + + +def nth_highest_salary(employee: pd.DataFrame, N: int) -> pd.DataFrame: + unique_salaries = employee.salary.unique() + if len(unique_salaries) < N: + return pd.DataFrame([np.NaN], columns=[f"getNthHighestSalary({N})"]) + else: + salary = sorted(unique_salaries, reverse=True)[N - 1] + return pd.DataFrame([salary], columns=[f"getNthHighestSalary({N})"]) +``` ```sql CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT @@ -94,19 +103,6 @@ BEGIN END ``` -### **Pandas** - -```python -import pandas as pd - - -def nth_highest_salary(employee: pd.DataFrame, N: int) -> pd.DataFrame: - unique_salaries = employee.salary.unique() - if len(unique_salaries) < N: - return pd.DataFrame([np.NaN], columns=[f"getNthHighestSalary({N})"]) - else: - salary = sorted(unique_salaries, reverse=True)[N - 1] - return pd.DataFrame([salary], columns=[f"getNthHighestSalary({N})"]) -``` - + + diff --git a/solution/0100-0199/0177.Nth Highest Salary/README_EN.md b/solution/0100-0199/0177.Nth Highest Salary/README_EN.md index 79d7e5df11925..27629406bf750 100644 --- a/solution/0100-0199/0177.Nth Highest Salary/README_EN.md +++ b/solution/0100-0199/0177.Nth Highest Salary/README_EN.md @@ -66,9 +66,22 @@ n = 2 ## Solutions +### Solution 1 + -### **SQL** +```python +import pandas as pd + + +def nth_highest_salary(employee: pd.DataFrame, N: int) -> pd.DataFrame: + unique_salaries = employee.salary.unique() + if len(unique_salaries) < N: + return pd.DataFrame([np.NaN], columns=[f"getNthHighestSalary({N})"]) + else: + salary = sorted(unique_salaries, reverse=True)[N - 1] + return pd.DataFrame([salary], columns=[f"getNthHighestSalary({N})"]) +``` ```sql CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT @@ -86,19 +99,6 @@ BEGIN END ``` -### **Pandas** - -```python -import pandas as pd - - -def nth_highest_salary(employee: pd.DataFrame, N: int) -> pd.DataFrame: - unique_salaries = employee.salary.unique() - if len(unique_salaries) < N: - return pd.DataFrame([np.NaN], columns=[f"getNthHighestSalary({N})"]) - else: - salary = sorted(unique_salaries, reverse=True)[N - 1] - return pd.DataFrame([salary], columns=[f"getNthHighestSalary({N})"]) -``` - + + diff --git a/solution/0100-0199/0178.Rank Scores/README.md b/solution/0100-0199/0178.Rank Scores/README.md index a6dbb3bff20b9..1dd71d9b571ba 100644 --- a/solution/0100-0199/0178.Rank Scores/README.md +++ b/solution/0100-0199/0178.Rank Scores/README.md @@ -64,9 +64,7 @@ Scores 表: ## 解法 - - -**方法一:使用窗口函数 `DENSE_RANK()`** +### 方法一:使用窗口函数 `DENSE_RANK()` 使用 `DENSE_RANK()` 函数,语法如下: @@ -84,13 +82,21 @@ DENSE_RANK() OVER ( 与 `RANK()` 函数不同,`DENSE_RANK()` 函数始终返回连续的排名值。 -**方法二:变量** + -MySQL 8 开始才提供了 `ROW_NUMBER()`,`RANK()`,`DENSE_RANK()` 等[窗口函数](https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html),在之前的版本,可以使用变量实现类似的功能。 +```python +import pandas as pd - -### **SQL** +def order_scores(scores: pd.DataFrame) -> pd.DataFrame: + # Use the rank method to assign ranks to the scores in descending order with no gaps + scores["rank"] = scores["score"].rank(method="dense", ascending=False) + + # Drop id column & Sort the DataFrame by score in descending order + result_df = scores.drop("id", axis=1).sort_values(by="score", ascending=False) + + return result_df +``` ```sql # Write your MySQL query statement below @@ -100,6 +106,14 @@ SELECT FROM Scores; ``` + + +### 方法二:变量 + +MySQL 8 开始才提供了 `ROW_NUMBER()`,`RANK()`,`DENSE_RANK()` 等[窗口函数](https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html),在之前的版本,可以使用变量实现类似的功能。 + + + ```sql SELECT Score, @@ -122,20 +136,6 @@ FROM ) s; ``` -### **Pandas** - -```python -import pandas as pd - - -def order_scores(scores: pd.DataFrame) -> pd.DataFrame: - # Use the rank method to assign ranks to the scores in descending order with no gaps - scores["rank"] = scores["score"].rank(method="dense", ascending=False) - - # Drop id column & Sort the DataFrame by score in descending order - result_df = scores.drop("id", axis=1).sort_values(by="score", ascending=False) - - return result_df -``` - + + diff --git a/solution/0100-0199/0178.Rank Scores/README_EN.md b/solution/0100-0199/0178.Rank Scores/README_EN.md index 506bac7fa42ec..10fae504964fc 100644 --- a/solution/0100-0199/0178.Rank Scores/README_EN.md +++ b/solution/0100-0199/0178.Rank Scores/README_EN.md @@ -62,26 +62,23 @@ Scores table: ## Solutions - - -**Solution 1: Use `DENSE_RANK()`** +### Solution 1 -Use `DENSE_RANK()` to solve this problem. + -```sql -DENSE_RANK() OVER ( - PARTITION BY [{,...}] - ORDER BY [ASC|DESC], [{,...}] -) -``` +```python +import pandas as pd -**Solution 2: Use variables** -MySQL only provides [window function](https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html) after version 8. In previous versions, variables can be used to achieve similar functions. +def order_scores(scores: pd.DataFrame) -> pd.DataFrame: + # Use the rank method to assign ranks to the scores in descending order with no gaps + scores["rank"] = scores["score"].rank(method="dense", ascending=False) - + # Drop id column & Sort the DataFrame by score in descending order + result_df = scores.drop("id", axis=1).sort_values(by="score", ascending=False) -### **SQL** + return result_df +``` ```sql # Write your MySQL query statement below @@ -91,6 +88,12 @@ SELECT FROM Scores; ``` + + +### Solution 2 + + + ```sql SELECT Score, @@ -113,20 +116,6 @@ FROM ) s; ``` -### **Pandas** - -```python -import pandas as pd - - -def order_scores(scores: pd.DataFrame) -> pd.DataFrame: - # Use the rank method to assign ranks to the scores in descending order with no gaps - scores["rank"] = scores["score"].rank(method="dense", ascending=False) - - # Drop id column & Sort the DataFrame by score in descending order - result_df = scores.drop("id", axis=1).sort_values(by="score", ascending=False) - - return result_df -``` - + + diff --git a/solution/0100-0199/0179.Largest Number/README.md b/solution/0100-0199/0179.Largest Number/README.md index 56a4b38ed352e..670c25fd51ddf 100644 --- a/solution/0100-0199/0179.Largest Number/README.md +++ b/solution/0100-0199/0179.Largest Number/README.md @@ -36,18 +36,12 @@ ## 解法 - - -**方法一:自定义排序** +### 方法一:自定义排序 先转成字符串列表,再对字符串列表进行字典序降序排列。最后将列表所有字符串拼接即可。 -### **Python3** - - - ```python class Solution: def largestNumber(self, nums: List[int]) -> str: @@ -56,10 +50,6 @@ class Solution: return "0" if nums[0] == "0" else "".join(nums) ``` -### **Java** - - - ```java class Solution { public String largestNumber(int[] nums) { @@ -76,8 +66,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +83,6 @@ public: }; ``` -### **Go** - ```go func largestNumber(nums []int) string { vs := make([]string, len(nums)) @@ -113,8 +99,6 @@ func largestNumber(nums []int) string { } ``` -### **C#** - ```cs using System; using System.Globalization; @@ -172,10 +156,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0179.Largest Number/README_EN.md b/solution/0100-0199/0179.Largest Number/README_EN.md index 2e7ccc0b43813..45aad3af51728 100644 --- a/solution/0100-0199/0179.Largest Number/README_EN.md +++ b/solution/0100-0199/0179.Largest Number/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -45,8 +45,6 @@ class Solution: return "0" if nums[0] == "0" else "".join(nums) ``` -### **Java** - ```java class Solution { public String largestNumber(int[] nums) { @@ -63,8 +61,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -82,8 +78,6 @@ public: }; ``` -### **Go** - ```go func largestNumber(nums []int) string { vs := make([]string, len(nums)) @@ -100,8 +94,6 @@ func largestNumber(nums []int) string { } ``` -### **C#** - ```cs using System; using System.Globalization; @@ -159,10 +151,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0180.Consecutive Numbers/README.md b/solution/0100-0199/0180.Consecutive Numbers/README.md index 911fbce488071..7c7e06dfd6b43 100644 --- a/solution/0100-0199/0180.Consecutive Numbers/README.md +++ b/solution/0100-0199/0180.Consecutive Numbers/README.md @@ -55,23 +55,29 @@ Result 表: ## 解法 - - -**方法一:两次连接** +### 方法一:两次连接 我们可以使用两次连接来解决这个问题。 我们首先进行一次自连接,连接条件是 `l1.num = l2.num` 并且 `l1.id = l2.id - 1`,这样我们就可以找出所有至少连续出现两次的数字。然后,我们再进行一次自连接,连接条件是 `l2.num = l3.num` 并且 `l2.id = l3.id - 1`,这样我们就可以找出所有至少连续出现三次的数字。最后,我们只需要筛选出去重的 `l2.num` 即可。 -**方法二:窗口函数** + -我们可以使用窗口函数 `LAG` 和 `LEAD` 来获取上一行的 `num` 和下一行的 `num`,记录在字段 $a$ 和 $b$ 中。最后,我们只需要筛选出 $a =num$ 并且 $b = num$ 的行,这些行就是至少连续出现三次的数字。注意,我们需要使用 `DISTINCT` 关键字来对结果去重。 +```python +import pandas as pd -我们也可以对数字进行分组,具体做法是使用 `IF` 函数来判断当前行与前一行的 `num` 是否相等,如果相等则记为 $0$,否则记为 $1$,然后使用窗口函数 `SUM` 来计算前缀和,这样计算出的前缀和就是分组的标识。最后,我们只需要按照分组标识进行分组,然后筛选出每组中的行数大于等于 $3$ 的数字即可。同样,我们需要使用 `DISTINCT` 关键字来对结果去重。 - - -### **SQL** +def consecutive_numbers(logs: pd.DataFrame) -> pd.DataFrame: + all_the_same = lambda lst: lst.nunique() == 1 + logs["is_consecutive"] = ( + logs["num"].rolling(window=3, center=True, min_periods=3).apply(all_the_same) + ) + return ( + logs.query("is_consecutive == 1.0")[["num"]] + .drop_duplicates() + .rename(columns={"num": "ConsecutiveNums"}) + ) +``` ```sql # Write your MySQL query statement below @@ -82,6 +88,16 @@ FROM JOIN Logs AS l3 ON l2.id = l3.id - 1 AND l2.num = l3.num; ``` + + +### 方法二:窗口函数 + +我们可以使用窗口函数 `LAG` 和 `LEAD` 来获取上一行的 `num` 和下一行的 `num`,记录在字段 $a$ 和 $b$ 中。最后,我们只需要筛选出 $a =num$ 并且 $b = num$ 的行,这些行就是至少连续出现三次的数字。注意,我们需要使用 `DISTINCT` 关键字来对结果去重。 + +我们也可以对数字进行分组,具体做法是使用 `IF` 函数来判断当前行与前一行的 `num` 是否相等,如果相等则记为 $0$,否则记为 $1$,然后使用窗口函数 `SUM` 来计算前缀和,这样计算出的前缀和就是分组的标识。最后,我们只需要按照分组标识进行分组,然后筛选出每组中的行数大于等于 $3$ 的数字即可。同样,我们需要使用 `DISTINCT` 关键字来对结果去重。 + + + ```sql # Write your MySQL query statement below WITH @@ -97,6 +113,12 @@ FROM T WHERE a = num AND b = num; ``` + + +### 方法三 + + + ```sql # Write your MySQL query statement below WITH @@ -116,22 +138,6 @@ GROUP BY p HAVING COUNT(1) >= 3; ``` -### **Pandas** - -```python -import pandas as pd - - -def consecutive_numbers(logs: pd.DataFrame) -> pd.DataFrame: - all_the_same = lambda lst: lst.nunique() == 1 - logs["is_consecutive"] = ( - logs["num"].rolling(window=3, center=True, min_periods=3).apply(all_the_same) - ) - return ( - logs.query("is_consecutive == 1.0")[["num"]] - .drop_duplicates() - .rename(columns={"num": "ConsecutiveNums"}) - ) -``` - + + diff --git a/solution/0100-0199/0180.Consecutive Numbers/README_EN.md b/solution/0100-0199/0180.Consecutive Numbers/README_EN.md index 402e19ca9cb56..92431de0390b1 100644 --- a/solution/0100-0199/0180.Consecutive Numbers/README_EN.md +++ b/solution/0100-0199/0180.Consecutive Numbers/README_EN.md @@ -53,21 +53,29 @@ Logs table: ## Solutions -**Solution 1: Two Joins** +### Solution 1: Two Joins We can use two joins to solve this problem. First, we perform a self-join with the condition `l1.num = l2.num` and `l1.id = l2.id - 1`, so that we can find all numbers that appear at least twice in a row. Then, we perform another self-join with the condition `l2.num = l3.num` and `l2.id = l3.id - 1`, so that we can find all numbers that appear at least three times in a row. Finally, we only need to select the distinct `l2.num`. -**Solution 2: Window Function** - -We can use the window functions `LAG` and `LEAD` to obtain the `num` of the previous row and the next row of the current row, and record them in the fields $a$ and $b$, respectively. Finally, we only need to filter out the rows where $a = num$ and $b = num$, which are the numbers that appear at least three times in a row. Note that we need to use the `DISTINCT` keyword to remove duplicates from the results. + -We can also group the numbers by using the `IF` function to determine whether the `num` of the current row is equal to the `num` of the previous row. If they are equal, we set it to $0$, otherwise we set it to $1$. Then, we use the window function `SUM` to calculate the prefix sum, which is the grouping identifier. Finally, we only need to group by the grouping identifier and filter out the numbers with a row count greater than or equal to $3$ in each group. Similarly, we need to use the `DISTINCT` keyword to remove duplicates from the results. +```python +import pandas as pd - -### **SQL** +def consecutive_numbers(logs: pd.DataFrame) -> pd.DataFrame: + all_the_same = lambda lst: lst.nunique() == 1 + logs["is_consecutive"] = ( + logs["num"].rolling(window=3, center=True, min_periods=3).apply(all_the_same) + ) + return ( + logs.query("is_consecutive == 1.0")[["num"]] + .drop_duplicates() + .rename(columns={"num": "ConsecutiveNums"}) + ) +``` ```sql # Write your MySQL query statement below @@ -78,6 +86,16 @@ FROM JOIN Logs AS l3 ON l2.id = l3.id - 1 AND l2.num = l3.num; ``` + + +### Solution 2: Window Function + +We can use the window functions `LAG` and `LEAD` to obtain the `num` of the previous row and the next row of the current row, and record them in the fields $a$ and $b$, respectively. Finally, we only need to filter out the rows where $a = num$ and $b = num$, which are the numbers that appear at least three times in a row. Note that we need to use the `DISTINCT` keyword to remove duplicates from the results. + +We can also group the numbers by using the `IF` function to determine whether the `num` of the current row is equal to the `num` of the previous row. If they are equal, we set it to $0$, otherwise we set it to $1$. Then, we use the window function `SUM` to calculate the prefix sum, which is the grouping identifier. Finally, we only need to group by the grouping identifier and filter out the numbers with a row count greater than or equal to $3$ in each group. Similarly, we need to use the `DISTINCT` keyword to remove duplicates from the results. + + + ```sql # Write your MySQL query statement below WITH @@ -93,6 +111,12 @@ FROM T WHERE a = num AND b = num; ``` + + +### Solution 3 + + + ```sql # Write your MySQL query statement below WITH @@ -112,22 +136,6 @@ GROUP BY p HAVING COUNT(1) >= 3; ``` -### **Pandas** - -```python -import pandas as pd - - -def consecutive_numbers(logs: pd.DataFrame) -> pd.DataFrame: - all_the_same = lambda lst: lst.nunique() == 1 - logs["is_consecutive"] = ( - logs["num"].rolling(window=3, center=True, min_periods=3).apply(all_the_same) - ) - return ( - logs.query("is_consecutive == 1.0")[["num"]] - .drop_duplicates() - .rename(columns={"num": "ConsecutiveNums"}) - ) -``` - + + diff --git a/solution/0100-0199/0181.Employees Earning More Than Their Managers/README.md b/solution/0100-0199/0181.Employees Earning More Than Their Managers/README.md index 98d39c81a10f4..bb5bb1b47da49 100644 --- a/solution/0100-0199/0181.Employees Earning More Than Their Managers/README.md +++ b/solution/0100-0199/0181.Employees Earning More Than Their Managers/README.md @@ -54,11 +54,20 @@ Employee 表: ## 解法 - +### 方法一 -### **SQL** +```python +import pandas as pd + + +def find_employees(employee: pd.DataFrame) -> pd.DataFrame: + df = employee.merge(right=employee, how="left", left_on="managerId", right_on="id") + emp = df[df["salary_x"] > df["salary_y"]]["name_x"] + + return pd.DataFrame({"Employee": emp}) +``` ```sql SELECT Name AS Employee @@ -71,6 +80,12 @@ WHERE ); ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below SELECT @@ -81,17 +96,6 @@ FROM WHERE e1.salary > e2.salary; ``` -### **Pandas** - -```python -import pandas as pd - - -def find_employees(employee: pd.DataFrame) -> pd.DataFrame: - df = employee.merge(right=employee, how="left", left_on="managerId", right_on="id") - emp = df[df["salary_x"] > df["salary_y"]]["name_x"] - - return pd.DataFrame({"Employee": emp}) -``` - + + diff --git a/solution/0100-0199/0181.Employees Earning More Than Their Managers/README_EN.md b/solution/0100-0199/0181.Employees Earning More Than Their Managers/README_EN.md index d22ed817ff531..d25f1350e0791 100644 --- a/solution/0100-0199/0181.Employees Earning More Than Their Managers/README_EN.md +++ b/solution/0100-0199/0181.Employees Earning More Than Their Managers/README_EN.md @@ -52,9 +52,20 @@ Employee table: ## Solutions +### Solution 1 + -### **SQL** +```python +import pandas as pd + + +def find_employees(employee: pd.DataFrame) -> pd.DataFrame: + df = employee.merge(right=employee, how="left", left_on="managerId", right_on="id") + emp = df[df["salary_x"] > df["salary_y"]]["name_x"] + + return pd.DataFrame({"Employee": emp}) +``` ```sql SELECT Name AS Employee @@ -67,6 +78,12 @@ WHERE ); ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below SELECT @@ -77,17 +94,6 @@ FROM WHERE e1.salary > e2.salary; ``` -### **Pandas** - -```python -import pandas as pd - - -def find_employees(employee: pd.DataFrame) -> pd.DataFrame: - df = employee.merge(right=employee, how="left", left_on="managerId", right_on="id") - emp = df[df["salary_x"] > df["salary_y"]]["name_x"] - - return pd.DataFrame({"Employee": emp}) -``` - + + diff --git a/solution/0100-0199/0182.Duplicate Emails/README.md b/solution/0100-0199/0182.Duplicate Emails/README.md index de856d137ffee..c024701e74ab6 100644 --- a/solution/0100-0199/0182.Duplicate Emails/README.md +++ b/solution/0100-0199/0182.Duplicate Emails/README.md @@ -53,19 +53,23 @@ Person 表: ## 解法 - - -**方法一:分组统计** +### 方法一:分组统计 我们可以使用 `GROUP BY` 语句,按照 `email` 字段进行分组,然后使用 `HAVING` 语句,筛选出现次数大于 $1$ 的 `email`。 -**方法二:自连接** + -我们可以使用自连接的方法,将 `Person` 表自身连接一次,然后筛选出 `id` 不同,但 `email` 相同的记录。 +```python +import pandas as pd - -### **SQL** +def duplicate_emails(person: pd.DataFrame) -> pd.DataFrame: + results = pd.DataFrame() + + results = person.loc[person.duplicated(subset=["email"]), ["email"]] + + return results.drop_duplicates() +``` ```sql # Write your MySQL query statement below @@ -75,6 +79,14 @@ GROUP BY 1 HAVING COUNT(1) > 1; ``` + + +### 方法二:自连接 + +我们可以使用自连接的方法,将 `Person` 表自身连接一次,然后筛选出 `id` 不同,但 `email` 相同的记录。 + + + ```sql SELECT DISTINCT p1.email FROM @@ -83,18 +95,6 @@ FROM WHERE p1.id != p2.id AND p1.email = p2.email; ``` -### **Pandas** - -```python -import pandas as pd - - -def duplicate_emails(person: pd.DataFrame) -> pd.DataFrame: - results = pd.DataFrame() - - results = person.loc[person.duplicated(subset=["email"]), ["email"]] - - return results.drop_duplicates() -``` - + + diff --git a/solution/0100-0199/0182.Duplicate Emails/README_EN.md b/solution/0100-0199/0182.Duplicate Emails/README_EN.md index 4a3b34af72cde..fcd89b3433ed0 100644 --- a/solution/0100-0199/0182.Duplicate Emails/README_EN.md +++ b/solution/0100-0199/0182.Duplicate Emails/README_EN.md @@ -49,17 +49,23 @@ Person table: ## Solutions -**Solution 1: Group By + Having** +### Solution 1: Group By + Having We can use the `GROUP BY` statement to group the data by the `email` field, and then use the `HAVING` statement to filter out the `email` addresses that appear more than once. -**Solution 2: Self-Join** + -We can use a self-join to join the `Person` table with itself, and then filter out the records where the `id` is different but the `email` is the same. +```python +import pandas as pd - -### **SQL** +def duplicate_emails(person: pd.DataFrame) -> pd.DataFrame: + results = pd.DataFrame() + + results = person.loc[person.duplicated(subset=["email"]), ["email"]] + + return results.drop_duplicates() +``` ```sql # Write your MySQL query statement below @@ -69,6 +75,14 @@ GROUP BY 1 HAVING COUNT(1) > 1; ``` + + +### Solution 2: Self-Join + +We can use a self-join to join the `Person` table with itself, and then filter out the records where the `id` is different but the `email` is the same. + + + ```sql SELECT DISTINCT p1.email FROM @@ -77,18 +91,6 @@ FROM WHERE p1.id != p2.id AND p1.email = p2.email; ``` -### **Pandas** - -```python -import pandas as pd - - -def duplicate_emails(person: pd.DataFrame) -> pd.DataFrame: - results = pd.DataFrame() - - results = person.loc[person.duplicated(subset=["email"]), ["email"]] - - return results.drop_duplicates() -``` - + + diff --git a/solution/0100-0199/0183.Customers Who Never Order/README.md b/solution/0100-0199/0183.Customers Who Never Order/README.md index 606d73069cada..67d27c328838b 100644 --- a/solution/0100-0199/0183.Customers Who Never Order/README.md +++ b/solution/0100-0199/0183.Customers Who Never Order/README.md @@ -71,19 +71,25 @@ Orders table: ## 解法 - - -**方法一:NOT IN** +### 方法一:NOT IN 列举所有已存在订单的客户 ID,使用 `NOT IN` 找到不存在其中的客户。 -**方法二:LEFT JOIN** + -使用 `LEFT JOIN` 连接表格,返回 `CustomerId` 为 `NULL` 的数据。 +```python +import pandas as pd - -### **SQL** +def find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame: + # Select the customers whose 'id' is not present in the orders DataFrame's 'customerId' column. + df = customers[~customers["id"].isin(orders["customerId"])] + + # Build a DataFrame that only contains the 'name' column and rename it as 'Customers'. + df = df[["name"]].rename(columns={"name": "Customers"}) + + return df +``` ```sql # Write your MySQL query statement below @@ -96,6 +102,14 @@ WHERE ); ``` + + +### 方法二:LEFT JOIN + +使用 `LEFT JOIN` 连接表格,返回 `CustomerId` 为 `NULL` 的数据。 + + + ```sql # Write your MySQL query statement below SELECT name AS Customers @@ -105,20 +119,6 @@ FROM WHERE o.id IS NULL; ``` -### **Pandas** - -```python -import pandas as pd - - -def find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame: - # Select the customers whose 'id' is not present in the orders DataFrame's 'customerId' column. - df = customers[~customers["id"].isin(orders["customerId"])] - - # Build a DataFrame that only contains the 'name' column and rename it as 'Customers'. - df = df[["name"]].rename(columns={"name": "Customers"}) - - return df -``` - + + diff --git a/solution/0100-0199/0183.Customers Who Never Order/README_EN.md b/solution/0100-0199/0183.Customers Who Never Order/README_EN.md index 1992c74855e8c..e16760458a7ee 100644 --- a/solution/0100-0199/0183.Customers Who Never Order/README_EN.md +++ b/solution/0100-0199/0183.Customers Who Never Order/README_EN.md @@ -73,17 +73,25 @@ Orders table: ## Solutions -**Solution 1: NOT IN** +### Solution 1: NOT IN List all customer IDs of existing orders, and use `NOT IN` to find customers who are not in the list. -**Solution 2: LEFT JOIN** + -Use `LEFT JOIN` to join the tables and return the data where `CustomerId` is `NULL`. +```python +import pandas as pd - -### **SQL** +def find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame: + # Select the customers whose 'id' is not present in the orders DataFrame's 'customerId' column. + df = customers[~customers["id"].isin(orders["customerId"])] + + # Build a DataFrame that only contains the 'name' column and rename it as 'Customers'. + df = df[["name"]].rename(columns={"name": "Customers"}) + + return df +``` ```sql # Write your MySQL query statement below @@ -96,6 +104,14 @@ WHERE ); ``` + + +### Solution 2: LEFT JOIN + +Use `LEFT JOIN` to join the tables and return the data where `CustomerId` is `NULL`. + + + ```sql # Write your MySQL query statement below SELECT name AS Customers @@ -105,20 +121,6 @@ FROM WHERE o.id IS NULL; ``` -### **Pandas** - -```python -import pandas as pd - - -def find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame: - # Select the customers whose 'id' is not present in the orders DataFrame's 'customerId' column. - df = customers[~customers["id"].isin(orders["customerId"])] - - # Build a DataFrame that only contains the 'name' column and rename it as 'Customers'. - df = df[["name"]].rename(columns={"name": "Customers"}) - - return df -``` - + + diff --git a/solution/0100-0199/0184.Department Highest Salary/README.md b/solution/0100-0199/0184.Department Highest Salary/README.md index a1703922343df..f5b8edec1d690 100644 --- a/solution/0100-0199/0184.Department Highest Salary/README.md +++ b/solution/0100-0199/0184.Department Highest Salary/README.md @@ -78,20 +78,12 @@ Department 表: ## 解法 - - -**方法一:等值连接 + 子查询** +### 方法一:等值连接 + 子查询 我们可以使用等值连接,将 `Employee` 表和 `Department` 表连接起来,连接条件为 `Employee.departmentId = Department.id`,然后使用子查询来找到每个部门的最高工资,最后使用 `WHERE` 子句来筛选出每个部门中薪资最高的员工。 -**方法二:等值连接 + 窗口函数** - -我们可以使用等值连接,将 `Employee` 表和 `Department` 表连接起来,连接条件为 `Employee.departmentId = Department.id`,然后使用窗口函数 `rank()`,它可以为每个部门的每个员工分配一个排名,然后我们可以选择排名为 $1$ 的行即可。 - -### **SQL** - ```sql # Write your MySQL query statement below SELECT d.name AS department, e.name AS employee, salary @@ -106,6 +98,14 @@ WHERE ); ``` + + +### 方法二:等值连接 + 窗口函数 + +我们可以使用等值连接,将 `Employee` 表和 `Department` 表连接起来,连接条件为 `Employee.departmentId = Department.id`,然后使用窗口函数 `rank()`,它可以为每个部门的每个员工分配一个排名,然后我们可以选择排名为 $1$ 的行即可。 + + + ```sql # Write your MySQL query statement below WITH @@ -128,3 +128,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/0100-0199/0184.Department Highest Salary/README_EN.md b/solution/0100-0199/0184.Department Highest Salary/README_EN.md index 3a941a1d99dd0..5061bdba470b6 100644 --- a/solution/0100-0199/0184.Department Highest Salary/README_EN.md +++ b/solution/0100-0199/0184.Department Highest Salary/README_EN.md @@ -78,18 +78,12 @@ Department table: ## Solutions -**Solution 1: Equi-Join + Subquery** +### Solution 1: Equi-Join + Subquery We can use an equi-join to join the `Employee` table and the `Department` table based on `Employee.departmentId = Department.id`, and then use a subquery to find the highest salary for each department. Finally, we can use a `WHERE` clause to filter out the employees with the highest salary in each department. -**Solution 2: Equi-Join + Window Function** - -We can use an equi-join to join the `Employee` table and the `Department` table based on `Employee.departmentId = Department.id`, and then use the window function `rank()`, which assigns a rank to each employee in each department based on their salary. Finally, we can select the rows with a rank of $1$ for each department. - -### **SQL** - ```sql # Write your MySQL query statement below SELECT d.name AS department, e.name AS employee, salary @@ -104,6 +98,14 @@ WHERE ); ``` + + +### Solution 2: Equi-Join + Window Function + +We can use an equi-join to join the `Employee` table and the `Department` table based on `Employee.departmentId = Department.id`, and then use the window function `rank()`, which assigns a rank to each employee in each department based on their salary. Finally, we can select the rows with a rank of $1$ for each department. + + + ```sql # Write your MySQL query statement below WITH @@ -126,3 +128,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/0100-0199/0185.Department Top Three Salaries/README.md b/solution/0100-0199/0185.Department Top Three Salaries/README.md index 95ff8e9eba82d..9185b5fb17934 100644 --- a/solution/0100-0199/0185.Department Top Three Salaries/README.md +++ b/solution/0100-0199/0185.Department Top Three Salaries/README.md @@ -96,11 +96,32 @@ Department 表: ## 解法 - +### 方法一 -### **SQL** +```python +import pandas as pd + + +def top_three_salaries( + employee: pd.DataFrame, department: pd.DataFrame +) -> pd.DataFrame: + salary_cutoff = ( + employee.drop_duplicates(["salary", "departmentId"]) + .groupby("departmentId")["salary"] + .nlargest(3) + .groupby("departmentId") + .min() + ) + employee["Department"] = department.set_index("id")["name"][ + employee["departmentId"] + ].values + employee["cutoff"] = salary_cutoff[employee["departmentId"]].values + return employee[employee["salary"] >= employee["cutoff"]].rename( + columns={"name": "Employee", "salary": "Salary"} + )[["Department", "Employee", "Salary"]] +``` ```sql SELECT @@ -120,6 +141,12 @@ WHERE ) < 3; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below WITH @@ -139,29 +166,6 @@ FROM WHERE rk <= 3; ``` -### **Pandas** - -```python -import pandas as pd - - -def top_three_salaries( - employee: pd.DataFrame, department: pd.DataFrame -) -> pd.DataFrame: - salary_cutoff = ( - employee.drop_duplicates(["salary", "departmentId"]) - .groupby("departmentId")["salary"] - .nlargest(3) - .groupby("departmentId") - .min() - ) - employee["Department"] = department.set_index("id")["name"][ - employee["departmentId"] - ].values - employee["cutoff"] = salary_cutoff[employee["departmentId"]].values - return employee[employee["salary"] >= employee["cutoff"]].rename( - columns={"name": "Employee", "salary": "Salary"} - )[["Department", "Employee", "Salary"]] -``` - + + diff --git a/solution/0100-0199/0185.Department Top Three Salaries/README_EN.md b/solution/0100-0199/0185.Department Top Three Salaries/README_EN.md index 823a0a43c156b..14565e34c8c50 100644 --- a/solution/0100-0199/0185.Department Top Three Salaries/README_EN.md +++ b/solution/0100-0199/0185.Department Top Three Salaries/README_EN.md @@ -94,9 +94,32 @@ In the Sales department: ## Solutions +### Solution 1 + -### **SQL** +```python +import pandas as pd + + +def top_three_salaries( + employee: pd.DataFrame, department: pd.DataFrame +) -> pd.DataFrame: + salary_cutoff = ( + employee.drop_duplicates(["salary", "departmentId"]) + .groupby("departmentId")["salary"] + .nlargest(3) + .groupby("departmentId") + .min() + ) + employee["Department"] = department.set_index("id")["name"][ + employee["departmentId"] + ].values + employee["cutoff"] = salary_cutoff[employee["departmentId"]].values + return employee[employee["salary"] >= employee["cutoff"]].rename( + columns={"name": "Employee", "salary": "Salary"} + )[["Department", "Employee", "Salary"]] +``` ```sql SELECT @@ -116,6 +139,12 @@ WHERE ) < 3; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below WITH @@ -135,29 +164,6 @@ FROM WHERE rk <= 3; ``` -### **Pandas** - -```python -import pandas as pd - - -def top_three_salaries( - employee: pd.DataFrame, department: pd.DataFrame -) -> pd.DataFrame: - salary_cutoff = ( - employee.drop_duplicates(["salary", "departmentId"]) - .groupby("departmentId")["salary"] - .nlargest(3) - .groupby("departmentId") - .min() - ) - employee["Department"] = department.set_index("id")["name"][ - employee["departmentId"] - ].values - employee["cutoff"] = salary_cutoff[employee["departmentId"]].values - return employee[employee["salary"] >= employee["cutoff"]].rename( - columns={"name": "Employee", "salary": "Salary"} - )[["Department", "Employee", "Salary"]] -``` - + + diff --git a/solution/0100-0199/0186.Reverse Words in a String II/README.md b/solution/0100-0199/0186.Reverse Words in a String II/README.md index 83ed8d027ed59..e2eeaa6f4a2ab 100644 --- a/solution/0100-0199/0186.Reverse Words in a String II/README.md +++ b/solution/0100-0199/0186.Reverse Words in a String II/README.md @@ -46,16 +46,10 @@ ## 解法 - - -先翻转里面每个单词,最后再将字符串整体翻转。 +### 方法一 -### **Python3** - - - ```python class Solution: def reverseWords(self, s: List[str]) -> None: @@ -80,10 +74,6 @@ class Solution: reverse(s, 0, n - 1) ``` -### **Java** - - - ```java class Solution { public void reverseWords(char[] s) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func reverseWords(s []byte) { n := len(s) @@ -160,10 +146,6 @@ func reverse(s []byte, i, j int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0186.Reverse Words in a String II/README_EN.md b/solution/0100-0199/0186.Reverse Words in a String II/README_EN.md index a17a0dc29099d..d3d24f6207038 100644 --- a/solution/0100-0199/0186.Reverse Words in a String II/README_EN.md +++ b/solution/0100-0199/0186.Reverse Words in a String II/README_EN.md @@ -31,9 +31,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: reverse(s, 0, n - 1) ``` -### **Java** - ```java class Solution { public void reverseWords(char[] s) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func reverseWords(s []byte) { n := len(s) @@ -137,10 +131,6 @@ func reverse(s []byte, i, j int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0187.Repeated DNA Sequences/README.md b/solution/0100-0199/0187.Repeated DNA Sequences/README.md index b4d8a2227d50f..b8eea3d9e267d 100644 --- a/solution/0100-0199/0187.Repeated DNA Sequences/README.md +++ b/solution/0100-0199/0187.Repeated DNA Sequences/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们定义一个哈希表 $cnt$,用于存储所有长度为 $10$ 的子字符串出现的次数。 @@ -55,18 +53,8 @@ 时间复杂度 $O(n \times 10)$,空间复杂度 $O(n \times 10)$。其中 $n$ 是字符串 $s$ 的长度。 -**方法二:Rabin-Karp 字符串匹配算法** - -本质上是滑动窗口和哈希的结合方法,和 [0028.找出字符串中第一个匹配项的下标](https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/) 类似,本题可以借助哈希函数将子序列计数的时间复杂度降低到 $O(1)$。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $s$ 的长度。 - -### **Python3** - - - ```python class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: @@ -80,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List findRepeatedDnaSequences(String s) { @@ -100,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +101,6 @@ public: }; ``` -### **Go** - ```go func findRepeatedDnaSequences(s string) (ans []string) { cnt := map[string]int{} @@ -135,28 +115,44 @@ func findRepeatedDnaSequences(s string) (ans []string) { } ``` -```go -func findRepeatedDnaSequences(s string) []string { - hashCode := map[byte]int{'A': 0, 'C': 1, 'G': 2, 'T': 3} - ans, cnt, left, right := []string{}, map[int]int{}, 0, 0 - - sha, multi := 0, int(math.Pow(4, 9)) - for ; right < len(s); right++ { - sha = sha*4 + hashCode[s[right]] - if right-left+1 < 10 { - continue - } - cnt[sha]++ - if cnt[sha] == 2 { - ans = append(ans, s[left:right+1]) - } - sha, left = sha-multi*hashCode[s[left]], left+1 - } - return ans +```ts +function findRepeatedDnaSequences(s: string): string[] { + const n = s.length; + const cnt: Map = new Map(); + const ans: string[] = []; + for (let i = 0; i <= n - 10; ++i) { + const t = s.slice(i, i + 10); + cnt.set(t, (cnt.get(t) ?? 0) + 1); + if (cnt.get(t) === 2) { + ans.push(t); + } + } + return ans; } ``` -### **JavaScript** +```rust +use std::collections::HashMap; + +impl Solution { + pub fn find_repeated_dna_sequences(s: String) -> Vec { + if s.len() < 10 { + return vec![]; + } + let mut cnt = HashMap::new(); + let mut ans = Vec::new(); + for i in 0..s.len() - 9 { + let t = &s[i..i + 10]; + let count = cnt.entry(t).or_insert(0); + *count += 1; + if *count == 2 { + ans.push(t.to_string()); + } + } + ans + } +} +``` ```js /** @@ -177,8 +173,6 @@ var findRepeatedDnaSequences = function (s) { }; ``` -### **C#** - ```cs public class Solution { public IList FindRepeatedDnaSequences(string s) { @@ -198,53 +192,37 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function findRepeatedDnaSequences(s: string): string[] { - const n = s.length; - const cnt: Map = new Map(); - const ans: string[] = []; - for (let i = 0; i <= n - 10; ++i) { - const t = s.slice(i, i + 10); - cnt.set(t, (cnt.get(t) ?? 0) + 1); - if (cnt.get(t) === 2) { - ans.push(t); - } - } - return ans; -} -``` + -### **Rust** +### 方法二:Rabin-Karp 字符串匹配算法 -```rust -use std::collections::HashMap; +本质上是滑动窗口和哈希的结合方法,和 [0028.找出字符串中第一个匹配项的下标](https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/) 类似,本题可以借助哈希函数将子序列计数的时间复杂度降低到 $O(1)$。 -impl Solution { - pub fn find_repeated_dna_sequences(s: String) -> Vec { - if s.len() < 10 { - return vec![]; - } - let mut cnt = HashMap::new(); - let mut ans = Vec::new(); - for i in 0..s.len() - 9 { - let t = &s[i..i + 10]; - let count = cnt.entry(t).or_insert(0); - *count += 1; - if *count == 2 { - ans.push(t.to_string()); - } - } - ans - } -} -``` +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $s$ 的长度。 -### **...** + -``` +```go +func findRepeatedDnaSequences(s string) []string { + hashCode := map[byte]int{'A': 0, 'C': 1, 'G': 2, 'T': 3} + ans, cnt, left, right := []string{}, map[int]int{}, 0, 0 + sha, multi := 0, int(math.Pow(4, 9)) + for ; right < len(s); right++ { + sha = sha*4 + hashCode[s[right]] + if right-left+1 < 10 { + continue + } + cnt[sha]++ + if cnt[sha] == 2 { + ans = append(ans, s[left:right+1]) + } + sha, left = sha-multi*hashCode[s[left]], left+1 + } + return ans +} ``` + + diff --git a/solution/0100-0199/0187.Repeated DNA Sequences/README_EN.md b/solution/0100-0199/0187.Repeated DNA Sequences/README_EN.md index ad6428947fd9e..ac12bd325ce9a 100644 --- a/solution/0100-0199/0187.Repeated DNA Sequences/README_EN.md +++ b/solution/0100-0199/0187.Repeated DNA Sequences/README_EN.md @@ -32,7 +32,7 @@ ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We define a hash table $cnt$ to store the occurrence count of all substrings of length $10$. @@ -42,16 +42,8 @@ After the iteration, we return the answer array. The time complexity is $O(n \times 10)$, and the space complexity is $O(n \times 10)$. Here, $n$ is the length of the string $s$. -**Solution 2: Rabin-Karp String Matching Algorithm** - -This method essentially combines sliding window and hash. Similar to 0028. Find the Index of the First Occurrence in a String, this problem can use a hash function to reduce the time complexity of counting subsequences to $O(1)$. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$. - -### **Python3** - ```python class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: @@ -65,8 +57,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List findRepeatedDnaSequences(String s) { @@ -83,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,44 +90,58 @@ public: }; ``` -### **Go** - ```go -func findRepeatedDnaSequences(s string) []string { - ans, cnt := []string{}, map[string]int{} - for i := 0; i <= len(s)-10; i++ { - sub := s[i : i+10] - cnt[sub]++ - if cnt[sub] == 2 { - ans = append(ans, sub) +func findRepeatedDnaSequences(s string) (ans []string) { + cnt := map[string]int{} + for i := 0; i < len(s)-10+1; i++ { + t := s[i : i+10] + cnt[t]++ + if cnt[t] == 2 { + ans = append(ans, t) } } - return ans + return } ``` -```go -func findRepeatedDnaSequences(s string) []string { - hashCode := map[byte]int{'A': 0, 'C': 1, 'G': 2, 'T': 3} - ans, cnt, left, right := []string{}, map[int]int{}, 0, 0 - - sha, multi := 0, int(math.Pow(4, 9)) - for ; right < len(s); right++ { - sha = sha*4 + hashCode[s[right]] - if right-left+1 < 10 { - continue - } - cnt[sha]++ - if cnt[sha] == 2 { - ans = append(ans, s[left:right+1]) - } - sha, left = sha-multi*hashCode[s[left]], left+1 - } - return ans +```ts +function findRepeatedDnaSequences(s: string): string[] { + const n = s.length; + const cnt: Map = new Map(); + const ans: string[] = []; + for (let i = 0; i <= n - 10; ++i) { + const t = s.slice(i, i + 10); + cnt.set(t, (cnt.get(t) ?? 0) + 1); + if (cnt.get(t) === 2) { + ans.push(t); + } + } + return ans; } ``` -### **JavaScript** +```rust +use std::collections::HashMap; + +impl Solution { + pub fn find_repeated_dna_sequences(s: String) -> Vec { + if s.len() < 10 { + return vec![]; + } + let mut cnt = HashMap::new(); + let mut ans = Vec::new(); + for i in 0..s.len() - 9 { + let t = &s[i..i + 10]; + let count = cnt.entry(t).or_insert(0); + *count += 1; + if *count == 2 { + ans.push(t.to_string()); + } + } + ans + } +} +``` ```js /** @@ -160,8 +162,6 @@ var findRepeatedDnaSequences = function (s) { }; ``` -### **C#** - ```cs public class Solution { public IList FindRepeatedDnaSequences(string s) { @@ -181,53 +181,37 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function findRepeatedDnaSequences(s: string): string[] { - const n = s.length; - const cnt: Map = new Map(); - const ans: string[] = []; - for (let i = 0; i <= n - 10; ++i) { - const t = s.slice(i, i + 10); - cnt.set(t, (cnt.get(t) ?? 0) + 1); - if (cnt.get(t) === 2) { - ans.push(t); - } - } - return ans; -} -``` + -### **Rust** +### Solution 2: Rabin-Karp String Matching Algorithm -```rust -use std::collections::HashMap; +This method essentially combines sliding window and hash. Similar to 0028. Find the Index of the First Occurrence in a String, this problem can use a hash function to reduce the time complexity of counting subsequences to $O(1)$. -impl Solution { - pub fn find_repeated_dna_sequences(s: String) -> Vec { - if s.len() < 10 { - return vec![]; - } - let mut cnt = HashMap::new(); - let mut ans = Vec::new(); - for i in 0..s.len() - 9 { - let t = &s[i..i + 10]; - let count = cnt.entry(t).or_insert(0); - *count += 1; - if *count == 2 { - ans.push(t.to_string()); - } - } - ans - } -} -``` +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$. -### **...** + -``` +```go +func findRepeatedDnaSequences(s string) []string { + hashCode := map[byte]int{'A': 0, 'C': 1, 'G': 2, 'T': 3} + ans, cnt, left, right := []string{}, map[int]int{}, 0, 0 + sha, multi := 0, int(math.Pow(4, 9)) + for ; right < len(s); right++ { + sha = sha*4 + hashCode[s[right]] + if right-left+1 < 10 { + continue + } + cnt[sha]++ + if cnt[sha] == 2 { + ans = append(ans, s[left:right+1]) + } + sha, left = sha-multi*hashCode[s[left]], left+1 + } + return ans +} ``` + + diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/README.md b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/README.md index df761f7c9a77a..dd068462d037c 100644 --- a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/README.md +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j, k)$,表示从第 $i$ 天开始,最多完成 $j$ 笔交易,以及当前持有股票的状态为 $k$(不持有股票用 $0$ 表示,持有股票用 $1$ 表示)时,所能获得的最大利润。答案即为 $dfs(0, k, 0)$。 @@ -60,38 +58,8 @@ 时间复杂度 $O(n \times k)$,空间复杂度 $O(n \times k)$。其中 $n$ 和 $k$ 分别为数组 $prices$ 的长度和 $k$ 的值。 -**方法二:动态规划** - -我们也可以使用动态规划的方法,定义 $f[i][j][k]$ 表示到第 $i$ 天时,最多交易 $j$ 次(这里我们规定交易次数等于买入次数),且当前持有股票的状态为 $k$ 时,所能获得的最大利润。初始时 $f[i][j][k]=0$。答案即为 $f[n - 1][k][0]$。 - -当 $i = 0$ 时,股票价格为 $prices[0]$,那么对任意 $j \in [1, k]$,我们有 $f[0][j][1] = -prices[0]$,表示第 $0$ 天买入股票,此时利润为 $-prices[0]$。 - -当 $i \gt 0$ 时: - -- 如果第 $i$ 天不持有股票,可能是第 $i-1$ 天持有股票并且在第 $i$ 天卖出;或者第 $i-1$ 天没持有股票并且第 $i$ 天不进行任何操作。因此 $f[i][j][0] = \max(f[i - 1][j][1] + prices[i], f[i - 1][j][0])$; -- 如果第 $i$ 天持有股票,可能是第 $i-1$ 天没持有股票并且在第 $i$ 天买入;或者第 $i-1$ 天持有股票并且第 $i$ 天不进行任何操作。因此 $f[i][j][1] = \max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1])$。 - -综上,当 $i \gt 0$ 时,我们可以得到状态转移方程: - -$$ -\begin{aligned} -f[i][j][0] &= \max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]) \\ -f[i][j][1] &= \max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]) -\end{aligned} -$$ - -最后答案即为 $f[n - 1][k][0]$。 - -时间复杂度 $O(n \times k)$,空间复杂度 $O(n \times k)$。其中 $n$ 和 $k$ 分别为数组 $prices$ 的长度和 $k$ 的值。 - -我们注意到,状态 $f[i][]$ 只与状态 $f[i - 1][]$ 有关,因此我们可以优化掉第一维的空间,将空间复杂度降至 $O(k)$。 - -### **Python3** - - - ```python class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: @@ -109,37 +77,6 @@ class Solution: return dfs(0, k, 0) ``` -```python -class Solution: - def maxProfit(self, k: int, prices: List[int]) -> int: - n = len(prices) - f = [[[0] * 2 for _ in range(k + 1)] for _ in range(n)] - for j in range(1, k + 1): - f[0][j][1] = -prices[0] - for i, x in enumerate(prices[1:], 1): - for j in range(1, k + 1): - f[i][j][0] = max(f[i - 1][j][1] + x, f[i - 1][j][0]) - f[i][j][1] = max(f[i - 1][j - 1][0] - x, f[i - 1][j][1]) - return f[n - 1][k][0] -``` - -```python -class Solution: - def maxProfit(self, k: int, prices: List[int]) -> int: - f = [[0] * 2 for _ in range(k + 1)] - for j in range(1, k + 1): - f[j][1] = -prices[0] - for x in prices[1:]: - for j in range(k, 0, -1): - f[j][0] = max(f[j][1] + x, f[j][0]) - f[j][1] = max(f[j - 1][0] - x, f[j][1]) - return f[k][0] -``` - -### **Java** - - - ```java class Solution { private Integer[][][] f; @@ -171,46 +108,6 @@ class Solution { } ``` -```java -class Solution { - public int maxProfit(int k, int[] prices) { - int n = prices.length; - int[][][] f = new int[n][k + 1][2]; - for (int j = 1; j <= k; ++j) { - f[0][j][1] = -prices[0]; - } - for (int i = 1; i < n; ++i) { - for (int j = 1; j <= k; ++j) { - f[i][j][0] = Math.max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); - f[i][j][1] = Math.max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); - } - } - return f[n - 1][k][0]; - } -} -``` - -```java -class Solution { - public int maxProfit(int k, int[] prices) { - int n = prices.length; - int[][] f = new int[k + 1][2]; - for (int j = 1; j <= k; ++j) { - f[j][1] = -prices[0]; - } - for (int i = 1; i < n; ++i) { - for (int j = k; j > 0; --j) { - f[j][0] = Math.max(f[j][1] + prices[i], f[j][0]); - f[j][1] = Math.max(f[j - 1][0] - prices[i], f[j][1]); - } - } - return f[k][0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -238,50 +135,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxProfit(int k, vector& prices) { - int n = prices.size(); - int f[n][k + 1][2]; - memset(f, 0, sizeof(f)); - for (int j = 1; j <= k; ++j) { - f[0][j][1] = -prices[0]; - } - for (int i = 1; i < n; ++i) { - for (int j = 1; j <= k; ++j) { - f[i][j][0] = max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); - f[i][j][1] = max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); - } - } - return f[n - 1][k][0]; - } -}; -``` - -```cpp -class Solution { -public: - int maxProfit(int k, vector& prices) { - int n = prices.size(); - int f[k + 1][2]; - memset(f, 0, sizeof(f)); - for (int j = 1; j <= k; ++j) { - f[j][1] = -prices[0]; - } - for (int i = 1; i < n; ++i) { - for (int j = k; j; --j) { - f[j][0] = max(f[j][1] + prices[i], f[j][0]); - f[j][1] = max(f[j - 1][0] - prices[i], f[j][1]); - } - } - return f[k][0]; - } -}; -``` - -### **Go** - ```go func maxProfit(k int, prices []int) int { n := len(prices) @@ -313,44 +166,6 @@ func maxProfit(k int, prices []int) int { } ``` -```go -func maxProfit(k int, prices []int) int { - n := len(prices) - f := make([][][2]int, n) - for i := range f { - f[i] = make([][2]int, k+1) - } - for j := 1; j <= k; j++ { - f[0][j][1] = -prices[0] - } - for i := 1; i < n; i++ { - for j := 1; j <= k; j++ { - f[i][j][0] = max(f[i-1][j][1]+prices[i], f[i-1][j][0]) - f[i][j][1] = max(f[i-1][j-1][0]-prices[i], f[i-1][j][1]) - } - } - return f[n-1][k][0] -} -``` - -```go -func maxProfit(k int, prices []int) int { - f := make([][2]int, k+1) - for j := 1; j <= k; j++ { - f[j][1] = -prices[0] - } - for _, x := range prices[1:] { - for j := k; j > 0; j-- { - f[j][0] = max(f[j][1]+x, f[j][0]) - f[j][1] = max(f[j-1][0]-x, f[j][1]) - } - } - return f[k][0] -} -``` - -### **TypeScript** - ```ts function maxProfit(k: number, prices: number[]): number { const n = prices.length; @@ -376,43 +191,6 @@ function maxProfit(k: number, prices: number[]): number { } ``` -```ts -function maxProfit(k: number, prices: number[]): number { - const n = prices.length; - const f = Array.from({ length: n }, () => - Array.from({ length: k + 1 }, () => Array.from({ length: 2 }, () => 0)), - ); - for (let j = 1; j <= k; ++j) { - f[0][j][1] = -prices[0]; - } - for (let i = 1; i < n; ++i) { - for (let j = 1; j <= k; ++j) { - f[i][j][0] = Math.max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); - f[i][j][1] = Math.max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); - } - } - return f[n - 1][k][0]; -} -``` - -```ts -function maxProfit(k: number, prices: number[]): number { - const f = Array.from({ length: k + 1 }, () => Array.from({ length: 2 }, () => 0)); - for (let j = 1; j <= k; ++j) { - f[j][1] = -prices[0]; - } - for (const x of prices.slice(1)) { - for (let j = k; j; --j) { - f[j][0] = Math.max(f[j][1] + x, f[j][0]); - f[j][1] = Math.max(f[j - 1][0] - x, f[j][1]); - } - } - return f[k][0]; -} -``` - -### **C#** - ```cs public class Solution { private int[,,] f; @@ -451,6 +229,129 @@ public class Solution { } ``` + + +### 方法二:动态规划 + +我们也可以使用动态规划的方法,定义 $f[i][j][k]$ 表示到第 $i$ 天时,最多交易 $j$ 次(这里我们规定交易次数等于买入次数),且当前持有股票的状态为 $k$ 时,所能获得的最大利润。初始时 $f[i][j][k]=0$。答案即为 $f[n - 1][k][0]$。 + +当 $i = 0$ 时,股票价格为 $prices[0]$,那么对任意 $j \in [1, k]$,我们有 $f[0][j][1] = -prices[0]$,表示第 $0$ 天买入股票,此时利润为 $-prices[0]$。 + +当 $i \gt 0$ 时: + +- 如果第 $i$ 天不持有股票,可能是第 $i-1$ 天持有股票并且在第 $i$ 天卖出;或者第 $i-1$ 天没持有股票并且第 $i$ 天不进行任何操作。因此 $f[i][j][0] = \max(f[i - 1][j][1] + prices[i], f[i - 1][j][0])$; +- 如果第 $i$ 天持有股票,可能是第 $i-1$ 天没持有股票并且在第 $i$ 天买入;或者第 $i-1$ 天持有股票并且第 $i$ 天不进行任何操作。因此 $f[i][j][1] = \max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1])$。 + +综上,当 $i \gt 0$ 时,我们可以得到状态转移方程: + +$$ +\begin{aligned} +f[i][j][0] &= \max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]) \\ +f[i][j][1] &= \max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]) +\end{aligned} +$$ + +最后答案即为 $f[n - 1][k][0]$。 + +时间复杂度 $O(n \times k)$,空间复杂度 $O(n \times k)$。其中 $n$ 和 $k$ 分别为数组 $prices$ 的长度和 $k$ 的值。 + +我们注意到,状态 $f[i][]$ 只与状态 $f[i - 1][]$ 有关,因此我们可以优化掉第一维的空间,将空间复杂度降至 $O(k)$。 + + + +```python +class Solution: + def maxProfit(self, k: int, prices: List[int]) -> int: + n = len(prices) + f = [[[0] * 2 for _ in range(k + 1)] for _ in range(n)] + for j in range(1, k + 1): + f[0][j][1] = -prices[0] + for i, x in enumerate(prices[1:], 1): + for j in range(1, k + 1): + f[i][j][0] = max(f[i - 1][j][1] + x, f[i - 1][j][0]) + f[i][j][1] = max(f[i - 1][j - 1][0] - x, f[i - 1][j][1]) + return f[n - 1][k][0] +``` + +```java +class Solution { + public int maxProfit(int k, int[] prices) { + int n = prices.length; + int[][][] f = new int[n][k + 1][2]; + for (int j = 1; j <= k; ++j) { + f[0][j][1] = -prices[0]; + } + for (int i = 1; i < n; ++i) { + for (int j = 1; j <= k; ++j) { + f[i][j][0] = Math.max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); + f[i][j][1] = Math.max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); + } + } + return f[n - 1][k][0]; + } +} +``` + +```cpp +class Solution { +public: + int maxProfit(int k, vector& prices) { + int n = prices.size(); + int f[n][k + 1][2]; + memset(f, 0, sizeof(f)); + for (int j = 1; j <= k; ++j) { + f[0][j][1] = -prices[0]; + } + for (int i = 1; i < n; ++i) { + for (int j = 1; j <= k; ++j) { + f[i][j][0] = max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); + f[i][j][1] = max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); + } + } + return f[n - 1][k][0]; + } +}; +``` + +```go +func maxProfit(k int, prices []int) int { + n := len(prices) + f := make([][][2]int, n) + for i := range f { + f[i] = make([][2]int, k+1) + } + for j := 1; j <= k; j++ { + f[0][j][1] = -prices[0] + } + for i := 1; i < n; i++ { + for j := 1; j <= k; j++ { + f[i][j][0] = max(f[i-1][j][1]+prices[i], f[i-1][j][0]) + f[i][j][1] = max(f[i-1][j-1][0]-prices[i], f[i-1][j][1]) + } + } + return f[n-1][k][0] +} +``` + +```ts +function maxProfit(k: number, prices: number[]): number { + const n = prices.length; + const f = Array.from({ length: n }, () => + Array.from({ length: k + 1 }, () => Array.from({ length: 2 }, () => 0)), + ); + for (let j = 1; j <= k; ++j) { + f[0][j][1] = -prices[0]; + } + for (let i = 1; i < n; ++i) { + for (let j = 1; j <= k; ++j) { + f[i][j][0] = Math.max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); + f[i][j][1] = Math.max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); + } + } + return f[n - 1][k][0]; +} +``` + ```cs public class Solution { public int MaxProfit(int k, int[] prices) { @@ -470,6 +371,97 @@ public class Solution { } ``` + + +### 方法三 + + + +```python +class Solution: + def maxProfit(self, k: int, prices: List[int]) -> int: + f = [[0] * 2 for _ in range(k + 1)] + for j in range(1, k + 1): + f[j][1] = -prices[0] + for x in prices[1:]: + for j in range(k, 0, -1): + f[j][0] = max(f[j][1] + x, f[j][0]) + f[j][1] = max(f[j - 1][0] - x, f[j][1]) + return f[k][0] +``` + +```java +class Solution { + public int maxProfit(int k, int[] prices) { + int n = prices.length; + int[][] f = new int[k + 1][2]; + for (int j = 1; j <= k; ++j) { + f[j][1] = -prices[0]; + } + for (int i = 1; i < n; ++i) { + for (int j = k; j > 0; --j) { + f[j][0] = Math.max(f[j][1] + prices[i], f[j][0]); + f[j][1] = Math.max(f[j - 1][0] - prices[i], f[j][1]); + } + } + return f[k][0]; + } +} +``` + +```cpp +class Solution { +public: + int maxProfit(int k, vector& prices) { + int n = prices.size(); + int f[k + 1][2]; + memset(f, 0, sizeof(f)); + for (int j = 1; j <= k; ++j) { + f[j][1] = -prices[0]; + } + for (int i = 1; i < n; ++i) { + for (int j = k; j; --j) { + f[j][0] = max(f[j][1] + prices[i], f[j][0]); + f[j][1] = max(f[j - 1][0] - prices[i], f[j][1]); + } + } + return f[k][0]; + } +}; +``` + +```go +func maxProfit(k int, prices []int) int { + f := make([][2]int, k+1) + for j := 1; j <= k; j++ { + f[j][1] = -prices[0] + } + for _, x := range prices[1:] { + for j := k; j > 0; j-- { + f[j][0] = max(f[j][1]+x, f[j][0]) + f[j][1] = max(f[j-1][0]-x, f[j][1]) + } + } + return f[k][0] +} +``` + +```ts +function maxProfit(k: number, prices: number[]): number { + const f = Array.from({ length: k + 1 }, () => Array.from({ length: 2 }, () => 0)); + for (let j = 1; j <= k; ++j) { + f[j][1] = -prices[0]; + } + for (const x of prices.slice(1)) { + for (let j = k; j; --j) { + f[j][0] = Math.max(f[j][1] + x, f[j][0]); + f[j][1] = Math.max(f[j - 1][0] - x, f[j][1]); + } + } + return f[k][0]; +} +``` + ```cs public class Solution { public int MaxProfit(int k, int[] prices) { @@ -489,10 +481,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/README_EN.md b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/README_EN.md index a7a64d943194c..e41280be6765a 100644 --- a/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/README_EN.md +++ b/solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We design a function $dfs(i, j, k)$ to represent the maximum profit that can be obtained when starting from day $i$, completing at most $j$ transactions, and holding the stock with the current state $k$ (not holding the stock is represented by $0$, and holding the stock is represented by $1$). The answer is $dfs(0, k, 0)$. @@ -55,36 +55,8 @@ During the process, we can use memoization search to save the results of each ca The time complexity is $O(n \times k)$, and the space complexity is $O(n \times k)$, where $n$ and $k$ are the length of the prices array and the value of $k$, respectively. -**Solution 2: Dynamic Programming** - -We can also use dynamic programming to define $f[i][j][k]$ as the maximum profit that can be obtained when completing at most j transactions (here we define the number of transactions as the number of purchases), and holding the stock with the current state k on the i-th day. The initial value of $f[i][j][k]$ is 0. The answer is $f[n - 1][k][0]$. - -When $i = 0$, the stock price is $prices[0]$. For any $j$ \in [1, k]$, we have $f[0][j][1] = -prices[0]$, which means buying the stock on the 0-th day with a profit of $-prices[0]$. - -When $i > 0$: - -- If the i-th day does not hold the stock, it may be that the stock was held on the i-1-th day and sold on the i-th day, or the stock was not held on the i-1-th day and no operation was performed on the i-th day. Therefore, $f[i][j][0] = \max(f[i - 1][j][1] + prices[i], f[i - 1][j][0])$. -- If the i-th day holds the stock, it may be that the stock was not held on the i-1-th day and bought on the i-th day, or the stock was held on the i-1-th day and no operation was performed on the i-th day. Therefore, $f[i][j][1] = max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1])$. - -Therefore, when $i > 0$, we can get the state transition equation: - -$$ -\begin{aligned} -f[i][j][0] &= \max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]) \\ -f[i][j][1] &= \max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]) -\end{aligned} -$$ - -The final answer is $f[n - 1][k][0]$. - -The time complexity is $O(n \times k)$, and the space complexity is $O(n \times k)$, where $n$ and $k$ are the length of the prices array and the value of $k$, respectively. - -We notice that the state $f[i][]$ only depends on the state $f[i - 1][]$, so we can optimize the first dimension of the space and reduce the space complexity to $O(k)$. - -### **Python3** - ```python class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: @@ -102,35 +74,6 @@ class Solution: return dfs(0, k, 0) ``` -```python -class Solution: - def maxProfit(self, k: int, prices: List[int]) -> int: - n = len(prices) - f = [[[0] * 2 for _ in range(k + 1)] for _ in range(n)] - for j in range(1, k + 1): - f[0][j][1] = -prices[0] - for i, x in enumerate(prices[1:], 1): - for j in range(1, k + 1): - f[i][j][0] = max(f[i - 1][j][1] + x, f[i - 1][j][0]) - f[i][j][1] = max(f[i - 1][j - 1][0] - x, f[i - 1][j][1]) - return f[n - 1][k][0] -``` - -```python -class Solution: - def maxProfit(self, k: int, prices: List[int]) -> int: - f = [[0] * 2 for _ in range(k + 1)] - for j in range(1, k + 1): - f[j][1] = -prices[0] - for x in prices[1:]: - for j in range(k, 0, -1): - f[j][0] = max(f[j][1] + x, f[j][0]) - f[j][1] = max(f[j - 1][0] - x, f[j][1]) - return f[k][0] -``` - -### **Java** - ```java class Solution { private Integer[][][] f; @@ -162,46 +105,6 @@ class Solution { } ``` -```java -class Solution { - public int maxProfit(int k, int[] prices) { - int n = prices.length; - int[][][] f = new int[n][k + 1][2]; - for (int j = 1; j <= k; ++j) { - f[0][j][1] = -prices[0]; - } - for (int i = 1; i < n; ++i) { - for (int j = 1; j <= k; ++j) { - f[i][j][0] = Math.max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); - f[i][j][1] = Math.max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); - } - } - return f[n - 1][k][0]; - } -} -``` - -```java -class Solution { - public int maxProfit(int k, int[] prices) { - int n = prices.length; - int[][] f = new int[k + 1][2]; - for (int j = 1; j <= k; ++j) { - f[j][1] = -prices[0]; - } - for (int i = 1; i < n; ++i) { - for (int j = k; j > 0; --j) { - f[j][0] = Math.max(f[j][1] + prices[i], f[j][0]); - f[j][1] = Math.max(f[j - 1][0] - prices[i], f[j][1]); - } - } - return f[k][0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -229,50 +132,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxProfit(int k, vector& prices) { - int n = prices.size(); - int f[n][k + 1][2]; - memset(f, 0, sizeof(f)); - for (int j = 1; j <= k; ++j) { - f[0][j][1] = -prices[0]; - } - for (int i = 1; i < n; ++i) { - for (int j = 1; j <= k; ++j) { - f[i][j][0] = max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); - f[i][j][1] = max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); - } - } - return f[n - 1][k][0]; - } -}; -``` - -```cpp -class Solution { -public: - int maxProfit(int k, vector& prices) { - int n = prices.size(); - int f[k + 1][2]; - memset(f, 0, sizeof(f)); - for (int j = 1; j <= k; ++j) { - f[j][1] = -prices[0]; - } - for (int i = 1; i < n; ++i) { - for (int j = k; j; --j) { - f[j][0] = max(f[j][1] + prices[i], f[j][0]); - f[j][1] = max(f[j - 1][0] - prices[i], f[j][1]); - } - } - return f[k][0]; - } -}; -``` - -### **Go** - ```go func maxProfit(k int, prices []int) int { n := len(prices) @@ -304,44 +163,6 @@ func maxProfit(k int, prices []int) int { } ``` -```go -func maxProfit(k int, prices []int) int { - n := len(prices) - f := make([][][2]int, n) - for i := range f { - f[i] = make([][2]int, k+1) - } - for j := 1; j <= k; j++ { - f[0][j][1] = -prices[0] - } - for i := 1; i < n; i++ { - for j := 1; j <= k; j++ { - f[i][j][0] = max(f[i-1][j][1]+prices[i], f[i-1][j][0]) - f[i][j][1] = max(f[i-1][j-1][0]-prices[i], f[i-1][j][1]) - } - } - return f[n-1][k][0] -} -``` - -```go -func maxProfit(k int, prices []int) int { - f := make([][2]int, k+1) - for j := 1; j <= k; j++ { - f[j][1] = -prices[0] - } - for _, x := range prices[1:] { - for j := k; j > 0; j-- { - f[j][0] = max(f[j][1]+x, f[j][0]) - f[j][1] = max(f[j-1][0]-x, f[j][1]) - } - } - return f[k][0] -} -``` - -### **TypeScript** - ```ts function maxProfit(k: number, prices: number[]): number { const n = prices.length; @@ -367,43 +188,6 @@ function maxProfit(k: number, prices: number[]): number { } ``` -```ts -function maxProfit(k: number, prices: number[]): number { - const n = prices.length; - const f = Array.from({ length: n }, () => - Array.from({ length: k + 1 }, () => Array.from({ length: 2 }, () => 0)), - ); - for (let j = 1; j <= k; ++j) { - f[0][j][1] = -prices[0]; - } - for (let i = 1; i < n; ++i) { - for (let j = 1; j <= k; ++j) { - f[i][j][0] = Math.max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); - f[i][j][1] = Math.max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); - } - } - return f[n - 1][k][0]; -} -``` - -```ts -function maxProfit(k: number, prices: number[]): number { - const f = Array.from({ length: k + 1 }, () => Array.from({ length: 2 }, () => 0)); - for (let j = 1; j <= k; ++j) { - f[j][1] = -prices[0]; - } - for (const x of prices.slice(1)) { - for (let j = k; j; --j) { - f[j][0] = Math.max(f[j][1] + x, f[j][0]); - f[j][1] = Math.max(f[j - 1][0] - x, f[j][1]); - } - } - return f[k][0]; -} -``` - -### **C#** - ```cs public class Solution { private int[,,] f; @@ -442,6 +226,129 @@ public class Solution { } ``` + + +### Solution 2: Dynamic Programming + +We can also use dynamic programming to define $f[i][j][k]$ as the maximum profit that can be obtained when completing at most j transactions (here we define the number of transactions as the number of purchases), and holding the stock with the current state k on the i-th day. The initial value of $f[i][j][k]$ is 0. The answer is $f[n - 1][k][0]$. + +When $i = 0$, the stock price is $prices[0]$. For any $j$ \in [1, k]$, we have $f[0][j][1] = -prices[0]$, which means buying the stock on the 0-th day with a profit of $-prices[0]$. + +When $i > 0$: + +- If the i-th day does not hold the stock, it may be that the stock was held on the i-1-th day and sold on the i-th day, or the stock was not held on the i-1-th day and no operation was performed on the i-th day. Therefore, $f[i][j][0] = \max(f[i - 1][j][1] + prices[i], f[i - 1][j][0])$. +- If the i-th day holds the stock, it may be that the stock was not held on the i-1-th day and bought on the i-th day, or the stock was held on the i-1-th day and no operation was performed on the i-th day. Therefore, $f[i][j][1] = max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1])$. + +Therefore, when $i > 0$, we can get the state transition equation: + +$$ +\begin{aligned} +f[i][j][0] &= \max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]) \\ +f[i][j][1] &= \max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]) +\end{aligned} +$$ + +The final answer is $f[n - 1][k][0]$. + +The time complexity is $O(n \times k)$, and the space complexity is $O(n \times k)$, where $n$ and $k$ are the length of the prices array and the value of $k$, respectively. + +We notice that the state $f[i][]$ only depends on the state $f[i - 1][]$, so we can optimize the first dimension of the space and reduce the space complexity to $O(k)$. + + + +```python +class Solution: + def maxProfit(self, k: int, prices: List[int]) -> int: + n = len(prices) + f = [[[0] * 2 for _ in range(k + 1)] for _ in range(n)] + for j in range(1, k + 1): + f[0][j][1] = -prices[0] + for i, x in enumerate(prices[1:], 1): + for j in range(1, k + 1): + f[i][j][0] = max(f[i - 1][j][1] + x, f[i - 1][j][0]) + f[i][j][1] = max(f[i - 1][j - 1][0] - x, f[i - 1][j][1]) + return f[n - 1][k][0] +``` + +```java +class Solution { + public int maxProfit(int k, int[] prices) { + int n = prices.length; + int[][][] f = new int[n][k + 1][2]; + for (int j = 1; j <= k; ++j) { + f[0][j][1] = -prices[0]; + } + for (int i = 1; i < n; ++i) { + for (int j = 1; j <= k; ++j) { + f[i][j][0] = Math.max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); + f[i][j][1] = Math.max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); + } + } + return f[n - 1][k][0]; + } +} +``` + +```cpp +class Solution { +public: + int maxProfit(int k, vector& prices) { + int n = prices.size(); + int f[n][k + 1][2]; + memset(f, 0, sizeof(f)); + for (int j = 1; j <= k; ++j) { + f[0][j][1] = -prices[0]; + } + for (int i = 1; i < n; ++i) { + for (int j = 1; j <= k; ++j) { + f[i][j][0] = max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); + f[i][j][1] = max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); + } + } + return f[n - 1][k][0]; + } +}; +``` + +```go +func maxProfit(k int, prices []int) int { + n := len(prices) + f := make([][][2]int, n) + for i := range f { + f[i] = make([][2]int, k+1) + } + for j := 1; j <= k; j++ { + f[0][j][1] = -prices[0] + } + for i := 1; i < n; i++ { + for j := 1; j <= k; j++ { + f[i][j][0] = max(f[i-1][j][1]+prices[i], f[i-1][j][0]) + f[i][j][1] = max(f[i-1][j-1][0]-prices[i], f[i-1][j][1]) + } + } + return f[n-1][k][0] +} +``` + +```ts +function maxProfit(k: number, prices: number[]): number { + const n = prices.length; + const f = Array.from({ length: n }, () => + Array.from({ length: k + 1 }, () => Array.from({ length: 2 }, () => 0)), + ); + for (let j = 1; j <= k; ++j) { + f[0][j][1] = -prices[0]; + } + for (let i = 1; i < n; ++i) { + for (let j = 1; j <= k; ++j) { + f[i][j][0] = Math.max(f[i - 1][j][1] + prices[i], f[i - 1][j][0]); + f[i][j][1] = Math.max(f[i - 1][j - 1][0] - prices[i], f[i - 1][j][1]); + } + } + return f[n - 1][k][0]; +} +``` + ```cs public class Solution { public int MaxProfit(int k, int[] prices) { @@ -461,6 +368,97 @@ public class Solution { } ``` + + +### Solution 3 + + + +```python +class Solution: + def maxProfit(self, k: int, prices: List[int]) -> int: + f = [[0] * 2 for _ in range(k + 1)] + for j in range(1, k + 1): + f[j][1] = -prices[0] + for x in prices[1:]: + for j in range(k, 0, -1): + f[j][0] = max(f[j][1] + x, f[j][0]) + f[j][1] = max(f[j - 1][0] - x, f[j][1]) + return f[k][0] +``` + +```java +class Solution { + public int maxProfit(int k, int[] prices) { + int n = prices.length; + int[][] f = new int[k + 1][2]; + for (int j = 1; j <= k; ++j) { + f[j][1] = -prices[0]; + } + for (int i = 1; i < n; ++i) { + for (int j = k; j > 0; --j) { + f[j][0] = Math.max(f[j][1] + prices[i], f[j][0]); + f[j][1] = Math.max(f[j - 1][0] - prices[i], f[j][1]); + } + } + return f[k][0]; + } +} +``` + +```cpp +class Solution { +public: + int maxProfit(int k, vector& prices) { + int n = prices.size(); + int f[k + 1][2]; + memset(f, 0, sizeof(f)); + for (int j = 1; j <= k; ++j) { + f[j][1] = -prices[0]; + } + for (int i = 1; i < n; ++i) { + for (int j = k; j; --j) { + f[j][0] = max(f[j][1] + prices[i], f[j][0]); + f[j][1] = max(f[j - 1][0] - prices[i], f[j][1]); + } + } + return f[k][0]; + } +}; +``` + +```go +func maxProfit(k int, prices []int) int { + f := make([][2]int, k+1) + for j := 1; j <= k; j++ { + f[j][1] = -prices[0] + } + for _, x := range prices[1:] { + for j := k; j > 0; j-- { + f[j][0] = max(f[j][1]+x, f[j][0]) + f[j][1] = max(f[j-1][0]-x, f[j][1]) + } + } + return f[k][0] +} +``` + +```ts +function maxProfit(k: number, prices: number[]): number { + const f = Array.from({ length: k + 1 }, () => Array.from({ length: 2 }, () => 0)); + for (let j = 1; j <= k; ++j) { + f[j][1] = -prices[0]; + } + for (const x of prices.slice(1)) { + for (let j = k; j; --j) { + f[j][0] = Math.max(f[j][1] + x, f[j][0]); + f[j][1] = Math.max(f[j - 1][0] - x, f[j][1]); + } + } + return f[k][0]; +} +``` + ```cs public class Solution { public int MaxProfit(int k, int[] prices) { @@ -480,10 +478,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0100-0199/0189.Rotate Array/README.md b/solution/0100-0199/0189.Rotate Array/README.md index 1d995132f1d79..102eb8d777cf2 100644 --- a/solution/0100-0199/0189.Rotate Array/README.md +++ b/solution/0100-0199/0189.Rotate Array/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:三次翻转** +### 方法一:三次翻转 我们不妨记数组长度为 $n$,然后将 $k$ 对 $n$ 取模,得到实际需要旋转的步数 $k$。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def rotate(self, nums: List[int], k: int) -> None: @@ -92,17 +86,6 @@ class Solution: reverse(k, n - 1) ``` -```python -class Solution: - def rotate(self, nums: List[int], k: int) -> None: - k %= len(nums) - nums[:] = nums[-k:] + nums[:-k] -``` - -### **Java** - - - ```java class Solution { private int[] nums; @@ -126,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +122,6 @@ public: }; ``` -### **Go** - ```go func rotate(nums []int, k int) { n := len(nums) @@ -158,8 +137,6 @@ func rotate(nums []int, k int) { } ``` -### **TypeScript** - ```ts /** Do not return anything, modify nums in-place instead. @@ -180,33 +157,18 @@ function rotate(nums: number[], k: number): void { } ``` -### **C#** - -```cs -public class Solution { - private int[] nums; - - public void Rotate(int[] nums, int k) { - this.nums = nums; - int n = nums.Length; - k %= n; - reverse(0, n - 1); - reverse(0, k - 1); - reverse(k, n - 1); - } - - private void reverse(int i, int j) { - for (; i < j; ++i, --j) { - int t = nums[i]; - nums[i] = nums[j]; - nums[j] = t; - } +```rust +impl Solution { + pub fn rotate(nums: &mut Vec, k: i32) { + let n = nums.len(); + let k = (k as usize) % n; + nums.reverse(); + nums[..k].reverse(); + nums[k..].reverse(); } } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -227,24 +189,42 @@ var rotate = function (nums, k) { }; ``` -### **Rust** +```cs +public class Solution { + private int[] nums; -```rust -impl Solution { - pub fn rotate(nums: &mut Vec, k: i32) { - let n = nums.len(); - let k = (k as usize) % n; - nums.reverse(); - nums[..k].reverse(); - nums[k..].reverse(); + public void Rotate(int[] nums, int k) { + this.nums = nums; + int n = nums.Length; + k %= n; + reverse(0, n - 1); + reverse(0, k - 1); + reverse(k, n - 1); + } + + private void reverse(int i, int j) { + for (; i < j; ++i, --j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } } } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def rotate(self, nums: List[int], k: int) -> None: + k %= len(nums) + nums[:] = nums[-k:] + nums[:-k] ``` + + diff --git a/solution/0100-0199/0189.Rotate Array/README_EN.md b/solution/0100-0199/0189.Rotate Array/README_EN.md index 228ddad1e55bd..1848f08bde46d 100644 --- a/solution/0100-0199/0189.Rotate Array/README_EN.md +++ b/solution/0100-0199/0189.Rotate Array/README_EN.md @@ -47,7 +47,7 @@ rotate 2 steps to the right: [3,99,-1,-100] ## Solutions -**Solution 1: Reverse three times** +### Solution 1: Reverse three times We can assume the length of the array is $n$ and calculate the actual number of steps needed by taking the module of $k$ and $n$, which is $k \bmod n$. @@ -67,8 +67,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def rotate(self, nums: List[int], k: int) -> None: @@ -84,15 +82,6 @@ class Solution: reverse(k, n - 1) ``` -```python -class Solution: - def rotate(self, nums: List[int], k: int) -> None: - k %= len(nums) - nums[:] = nums[-k:] + nums[:-k] -``` - -### **Java** - ```java class Solution { private int[] nums; @@ -116,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +118,6 @@ public: }; ``` -### **Go** - ```go func rotate(nums []int, k int) { n := len(nums) @@ -148,8 +133,6 @@ func rotate(nums []int, k int) { } ``` -### **TypeScript** - ```ts /** Do not return anything, modify nums in-place instead. @@ -170,33 +153,18 @@ function rotate(nums: number[], k: number): void { } ``` -### **C#** - -```cs -public class Solution { - private int[] nums; - - public void Rotate(int[] nums, int k) { - this.nums = nums; - int n = nums.Length; - k %= n; - reverse(0, n - 1); - reverse(0, k - 1); - reverse(k, n - 1); - } - - private void reverse(int i, int j) { - for (; i < j; ++i, --j) { - int t = nums[i]; - nums[i] = nums[j]; - nums[j] = t; - } +```rust +impl Solution { + pub fn rotate(nums: &mut Vec, k: i32) { + let n = nums.len(); + let k = (k as usize) % n; + nums.reverse(); + nums[..k].reverse(); + nums[k..].reverse(); } } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -217,24 +185,42 @@ var rotate = function (nums, k) { }; ``` -### **Rust** +```cs +public class Solution { + private int[] nums; -```rust -impl Solution { - pub fn rotate(nums: &mut Vec, k: i32) { - let n = nums.len(); - let k = (k as usize) % n; - nums.reverse(); - nums[..k].reverse(); - nums[k..].reverse(); + public void Rotate(int[] nums, int k) { + this.nums = nums; + int n = nums.Length; + k %= n; + reverse(0, n - 1); + reverse(0, k - 1); + reverse(k, n - 1); + } + + private void reverse(int i, int j) { + for (; i < j; ++i, --j) { + int t = nums[i]; + nums[i] = nums[j]; + nums[j] = t; + } } } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def rotate(self, nums: List[int], k: int) -> None: + k %= len(nums) + nums[:] = nums[-k:] + nums[:-k] ``` + + diff --git a/solution/0100-0199/0190.Reverse Bits/README.md b/solution/0100-0199/0190.Reverse Bits/README.md index 99547016ea360..6bf24a9678c37 100644 --- a/solution/0100-0199/0190.Reverse Bits/README.md +++ b/solution/0100-0199/0190.Reverse Bits/README.md @@ -47,14 +47,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def reverseBits(self, n: int) -> int: @@ -65,10 +61,6 @@ class Solution: return res ``` -### **Java** - - - ```java public class Solution { // you need treat n as an unsigned value @@ -83,8 +75,6 @@ public class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,26 +89,17 @@ public: }; ``` -### **JavaScript** - -```js -/** - * @param {number} n - a positive integer - * @return {number} - a positive integer - */ -var reverseBits = function (n) { - let res = 0; - for (let i = 0; i < 32 && n > 0; ++i) { - res |= (n & 1) << (31 - i); - n >>>= 1; - } - // 无符号右移 - return res >>> 0; -}; +```go +func reverseBits(num uint32) uint32 { + var ans uint32 = 0 + for i := 0; i < 32; i++ { + ans |= (num & 1) << (31 - i) + num >>= 1 + } + return ans +} ``` -### **Rust** - ```rust impl Solution { pub fn reverse_bits(mut x: u32) -> u32 { @@ -132,23 +113,22 @@ impl Solution { } ``` -### **Go** - -```go -func reverseBits(num uint32) uint32 { - var ans uint32 = 0 - for i := 0; i < 32; i++ { - ans |= (num & 1) << (31 - i) - num >>= 1 - } - return ans -} -``` - -### **...** - -``` - +```js +/** + * @param {number} n - a positive integer + * @return {number} - a positive integer + */ +var reverseBits = function (n) { + let res = 0; + for (let i = 0; i < 32 && n > 0; ++i) { + res |= (n & 1) << (31 - i); + n >>>= 1; + } + // 无符号右移 + return res >>> 0; +}; ``` + + diff --git a/solution/0100-0199/0190.Reverse Bits/README_EN.md b/solution/0100-0199/0190.Reverse Bits/README_EN.md index 434636976ea25..d5f34795fadfb 100644 --- a/solution/0100-0199/0190.Reverse Bits/README_EN.md +++ b/solution/0100-0199/0190.Reverse Bits/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return res ``` -### **Java** - ```java public class Solution { // you need treat n as an unsigned value @@ -72,8 +70,6 @@ public class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -88,25 +84,17 @@ public: }; ``` -### **JavaScript** - -```js -/** - * @param {number} n - a positive integer - * @return {number} - a positive integer - */ -var reverseBits = function (n) { - let res = 0; - for (let i = 0; i < 32 && n > 0; ++i) { - res |= (n & 1) << (31 - i); - n >>>= 1; - } - return res >>> 0; -}; +```go +func reverseBits(num uint32) uint32 { + var ans uint32 = 0 + for i := 0; i < 32; i++ { + ans |= (num & 1) << (31 - i) + num >>= 1 + } + return ans +} ``` -### **Rust** - ```rust impl Solution { pub fn reverse_bits(mut x: u32) -> u32 { @@ -120,23 +108,22 @@ impl Solution { } ``` -### **Go** - -```go -func reverseBits(num uint32) uint32 { - var ans uint32 = 0 - for i := 0; i < 32; i++ { - ans |= (num & 1) << (31 - i) - num >>= 1 - } - return ans -} -``` - -### **...** - -``` - +```js +/** + * @param {number} n - a positive integer + * @return {number} - a positive integer + */ +var reverseBits = function (n) { + let res = 0; + for (let i = 0; i < 32 && n > 0; ++i) { + res |= (n & 1) << (31 - i); + n >>>= 1; + } + // 无符号右移 + return res >>> 0; +}; ``` + + diff --git a/solution/0100-0199/0191.Number of 1 Bits/README.md b/solution/0100-0199/0191.Number of 1 Bits/README.md index 4f96a76011115..fdd47fafcb91b 100644 --- a/solution/0100-0199/0191.Number of 1 Bits/README.md +++ b/solution/0100-0199/0191.Number of 1 Bits/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 利用 `n & (n - 1)` 消除 `n` 中最后一位 1 这一特点,优化过程: @@ -90,18 +88,8 @@ HAMMING-WEIGHT(n) [0, 0, 0, 0] // 4 & 3 = 0 ``` -**方法二:lowbit** - -`x -= (x & -x)` 可以消除二进制形式的最后一位 1。 - -同 [剑指 Offer 15. 二进制中 1 的个数](/lcof/面试题15.%20二进制中1的个数/README.md) - -### **Python3** - - - ```python class Solution: def hammingWeight(self, n: int) -> int: @@ -112,20 +100,6 @@ class Solution: return ans ``` -```python -class Solution: - def hammingWeight(self, n: int) -> int: - ans = 0 - while n: - n -= n & -n - ans += 1 - return ans -``` - -### **Java** - - - ```java public class Solution { // you need to treat n as an unsigned value @@ -140,22 +114,6 @@ public class Solution { } ``` -```java -public class Solution { - // you need to treat n as an unsigned value - public int hammingWeight(int n) { - int ans = 0; - while (n != 0) { - n -= (n & -n); - ++ans; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -170,22 +128,6 @@ public: }; ``` -```cpp -class Solution { -public: - int hammingWeight(uint32_t n) { - int ans = 0; - while (n) { - n -= (n & -n); - ++ans; - } - return ans; - } -}; -``` - -### **Go** - ```go func hammingWeight(num uint32) int { ans := 0 @@ -197,18 +139,24 @@ func hammingWeight(num uint32) int { } ``` -```go -func hammingWeight(num uint32) int { - ans := 0 - for num != 0 { - num -= (num & -num) - ans++ - } - return ans +```ts +function hammingWeight(n: number): number { + let ans: number = 0; + while (n !== 0) { + ans++; + n &= n - 1; + } + return ans; } ``` -### **JavaScript** +```rust +impl Solution { + pub fn hammingWeight(n: u32) -> i32 { + n.count_ones() as i32 + } +} +``` ```js /** @@ -225,31 +173,6 @@ var hammingWeight = function (n) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn hammingWeight(n: u32) -> i32 { - n.count_ones() as i32 - } -} -``` - -```rust -impl Solution { - pub fn hammingWeight(mut n: u32) -> i32 { - let mut res = 0; - while n != 0 { - n &= n - 1; - res += 1; - } - res - } -} -``` - -### **C** - ```c int hammingWeight(uint32_t n) { int ans = 0; @@ -261,23 +184,78 @@ int hammingWeight(uint32_t n) { } ``` -### **Typescript** + -```ts -function hammingWeight(n: number): number { - let ans: number = 0; - while (n !== 0) { - ans++; - n &= n - 1; +### 方法二:lowbit + +`x -= (x & -x)` 可以消除二进制形式的最后一位 1。 + +同 [剑指 Offer 15. 二进制中 1 的个数](/lcof/面试题15.%20二进制中1的个数/README.md) + + + +```python +class Solution: + def hammingWeight(self, n: int) -> int: + ans = 0 + while n: + n -= n & -n + ans += 1 + return ans +``` + +```java +public class Solution { + // you need to treat n as an unsigned value + public int hammingWeight(int n) { + int ans = 0; + while (n != 0) { + n -= (n & -n); + ++ans; + } + return ans; } - return ans; } ``` -### **...** +```cpp +class Solution { +public: + int hammingWeight(uint32_t n) { + int ans = 0; + while (n) { + n -= (n & -n); + ++ans; + } + return ans; + } +}; +``` +```go +func hammingWeight(num uint32) int { + ans := 0 + for num != 0 { + num -= (num & -num) + ans++ + } + return ans +} ``` +```rust +impl Solution { + pub fn hammingWeight(mut n: u32) -> i32 { + let mut res = 0; + while n != 0 { + n &= n - 1; + res += 1; + } + res + } +} ``` + + diff --git a/solution/0100-0199/0191.Number of 1 Bits/README_EN.md b/solution/0100-0199/0191.Number of 1 Bits/README_EN.md index 1c48e21ff4cc9..4773fba413636 100644 --- a/solution/0100-0199/0191.Number of 1 Bits/README_EN.md +++ b/solution/0100-0199/0191.Number of 1 Bits/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,18 +64,6 @@ class Solution: return ans ``` -```python -class Solution: - def hammingWeight(self, n: int) -> int: - ans = 0 - while n: - n -= n & -n - ans += 1 - return ans -``` - -### **Java** - ```java public class Solution { // you need to treat n as an unsigned value @@ -90,22 +78,6 @@ public class Solution { } ``` -```java -public class Solution { - // you need to treat n as an unsigned value - public int hammingWeight(int n) { - int ans = 0; - while (n != 0) { - n -= (n & -n); - ++ans; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -120,22 +92,6 @@ public: }; ``` -```cpp -class Solution { -public: - int hammingWeight(uint32_t n) { - int ans = 0; - while (n) { - n -= (n & -n); - ++ans; - } - return ans; - } -}; -``` - -### **Go** - ```go func hammingWeight(num uint32) int { ans := 0 @@ -147,18 +103,24 @@ func hammingWeight(num uint32) int { } ``` -```go -func hammingWeight(num uint32) int { - ans := 0 - for num != 0 { - num -= (num & -num) - ans++ - } - return ans +```ts +function hammingWeight(n: number): number { + let ans: number = 0; + while (n !== 0) { + ans++; + n &= n - 1; + } + return ans; } ``` -### **JavaScript** +```rust +impl Solution { + pub fn hammingWeight(n: u32) -> i32 { + n.count_ones() as i32 + } +} +``` ```js /** @@ -175,31 +137,6 @@ var hammingWeight = function (n) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn hammingWeight(n: u32) -> i32 { - n.count_ones() as i32 - } -} -``` - -```rust -impl Solution { - pub fn hammingWeight(mut n: u32) -> i32 { - let mut res = 0; - while n != 0 { - n &= n - 1; - res += 1; - } - res - } -} -``` - -### **C** - ```c int hammingWeight(uint32_t n) { int ans = 0; @@ -211,23 +148,74 @@ int hammingWeight(uint32_t n) { } ``` -### **Typescript** + -```ts -function hammingWeight(n: number): number { - let ans: number = 0; - while (n !== 0) { - ans++; - n &= n - 1; +### Solution 2 + + + +```python +class Solution: + def hammingWeight(self, n: int) -> int: + ans = 0 + while n: + n -= n & -n + ans += 1 + return ans +``` + +```java +public class Solution { + // you need to treat n as an unsigned value + public int hammingWeight(int n) { + int ans = 0; + while (n != 0) { + n -= (n & -n); + ++ans; + } + return ans; } - return ans; } ``` -### **...** +```cpp +class Solution { +public: + int hammingWeight(uint32_t n) { + int ans = 0; + while (n) { + n -= (n & -n); + ++ans; + } + return ans; + } +}; +``` +```go +func hammingWeight(num uint32) int { + ans := 0 + for num != 0 { + num -= (num & -num) + ans++ + } + return ans +} ``` +```rust +impl Solution { + pub fn hammingWeight(mut n: u32) -> i32 { + let mut res = 0; + while n != 0 { + n &= n - 1; + res += 1; + } + res + } +} ``` + + diff --git a/solution/0100-0199/0192.Word Frequency/README.md b/solution/0100-0199/0192.Word Frequency/README.md index c6f71035bbaab..a26ac0c574aa5 100644 --- a/solution/0100-0199/0192.Word Frequency/README.md +++ b/solution/0100-0199/0192.Word Frequency/README.md @@ -41,17 +41,4 @@ day 1 ## 解法 - - - - -### **Bash** - - - -```sh -# Read from the file words.txt and output the word frequency list to stdout. -cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -nr | awk '{print $2, $1}' -``` - - + diff --git a/solution/0100-0199/0192.Word Frequency/README_EN.md b/solution/0100-0199/0192.Word Frequency/README_EN.md index 2dbcd6e7b0d30..0fefee4067795 100644 --- a/solution/0100-0199/0192.Word Frequency/README_EN.md +++ b/solution/0100-0199/0192.Word Frequency/README_EN.md @@ -41,13 +41,4 @@ day 1 ## Solutions - - -### **Bash** - -```sh -# Read from the file words.txt and output the word frequency list to stdout. -cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -nr | awk '{print $2, $1}' -``` - - + diff --git a/solution/0100-0199/0193.Valid Phone Numbers/README.md b/solution/0100-0199/0193.Valid Phone Numbers/README.md index 7671b3f0e53c0..c868d28fcf5c9 100644 --- a/solution/0100-0199/0193.Valid Phone Numbers/README.md +++ b/solution/0100-0199/0193.Valid Phone Numbers/README.md @@ -33,27 +33,4 @@ ## 解法 - - - - -### **Bash** - - - -```sh -# Read from the file file.txt and output all valid phone numbers to stdout. -grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt -``` - -```sh -# Read from the file file.txt and output all valid phone numbers to stdout. -sed -n -E '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/p' file.txt -``` - -```sh -# Read from the file file.txt and output all valid phone numbers to stdout. -awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt -``` - - + diff --git a/solution/0100-0199/0193.Valid Phone Numbers/README_EN.md b/solution/0100-0199/0193.Valid Phone Numbers/README_EN.md index ec9fdfa464156..9f4e478cafce5 100644 --- a/solution/0100-0199/0193.Valid Phone Numbers/README_EN.md +++ b/solution/0100-0199/0193.Valid Phone Numbers/README_EN.md @@ -29,23 +29,4 @@ ## Solutions - - -### **Bash** - -```sh -# Read from the file file.txt and output all valid phone numbers to stdout. -grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt -``` - -```sh -# Read from the file file.txt and output all valid phone numbers to stdout. -sed -n -E '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/p' file.txt -``` - -```sh -# Read from the file file.txt and output all valid phone numbers to stdout. -awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt -``` - - + diff --git a/solution/0100-0199/0194.Transpose File/README.md b/solution/0100-0199/0194.Transpose File/README.md index 23e450f02fe5a..020cf40b043fa 100644 --- a/solution/0100-0199/0194.Transpose File/README.md +++ b/solution/0100-0199/0194.Transpose File/README.md @@ -31,31 +31,4 @@ age 21 30 ## 解法 - - - - -### **Bash** - - - -```sh -# Read from the file file.txt and print its transposed content to stdout. -awk ' -{ - for (i=1; i<=NF; i++) { - if(NR == 1) { - res[i] = re$i - } else { - res[i] = res[i]" "$i - } - } -}END { - for (i=1;i<=NF;i++) { - print res[i] - } -} -' file.txt -``` - - + diff --git a/solution/0100-0199/0194.Transpose File/README_EN.md b/solution/0100-0199/0194.Transpose File/README_EN.md index c907e2e942438..862f914ec36d5 100644 --- a/solution/0100-0199/0194.Transpose File/README_EN.md +++ b/solution/0100-0199/0194.Transpose File/README_EN.md @@ -27,27 +27,4 @@ age 21 30 ## Solutions - - -### **Bash** - -```sh -# Read from the file file.txt and print its transposed content to stdout. -awk ' -{ - for (i=1; i<=NF; i++) { - if(NR == 1) { - res[i] = re$i - } else { - res[i] = res[i]" "$i - } - } -}END { - for (i=1;i<=NF;i++) { - print res[i] - } -} -' file.txt -``` - - + diff --git a/solution/0100-0199/0195.Tenth Line/README.md b/solution/0100-0199/0195.Tenth Line/README.md index 12b957042e61a..4c3d6c1384737 100644 --- a/solution/0100-0199/0195.Tenth Line/README.md +++ b/solution/0100-0199/0195.Tenth Line/README.md @@ -35,27 +35,4 @@ Line 10 ## 解法 - - - - -### **Bash** - - - -```sh -# Read from the file file.txt and output the tenth line to stdout. -tail -n +10 file.txt | head -1 -``` - -```sh -# Read from the file file.txt and output the tenth line to stdout. -awk 'NR == 10' file.txt -``` - -```sh -# Read from the file file.txt and output the tenth line to stdout. -sed -n 10p file.txt -``` - - + diff --git a/solution/0100-0199/0195.Tenth Line/README_EN.md b/solution/0100-0199/0195.Tenth Line/README_EN.md index 67c2637df5b2f..9e0935b0b0505 100644 --- a/solution/0100-0199/0195.Tenth Line/README_EN.md +++ b/solution/0100-0199/0195.Tenth Line/README_EN.md @@ -35,23 +35,4 @@ Line 10 ## Solutions - - -### **Bash** - -```sh -# Read from the file file.txt and output the tenth line to stdout. -tail -n +10 file.txt | head -1 -``` - -```sh -# Read from the file file.txt and output the tenth line to stdout. -awk 'NR == 10' file.txt -``` - -```sh -# Read from the file file.txt and output the tenth line to stdout. -sed -n 10p file.txt -``` - - + diff --git a/solution/0100-0199/0196.Delete Duplicate Emails/README.md b/solution/0100-0199/0196.Delete Duplicate Emails/README.md index 120175eb21ad7..0b6e67db96237 100644 --- a/solution/0100-0199/0196.Delete Duplicate Emails/README.md +++ b/solution/0100-0199/0196.Delete Duplicate Emails/README.md @@ -56,11 +56,21 @@ Person 表: ## 解法 - +### 方法一 -### **SQL** +```python +import pandas as pd + + +# Modify Person in place +def delete_duplicate_emails(person: pd.DataFrame) -> None: + # Sort the rows based on id (Ascending order) + person.sort_values(by="id", ascending=True, inplace=True) + # Drop the duplicates based on email. + person.drop_duplicates(subset="email", keep="first", inplace=True) +``` ```sql # Write your MySQL query statement below @@ -68,6 +78,12 @@ DELETE FROM Person WHERE id NOT IN (SELECT MIN(id) FROM (SELECT * FROM Person) AS p GROUP BY email); ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below DELETE FROM Person @@ -88,6 +104,12 @@ WHERE ); ``` + + +### 方法三 + + + ```sql DELETE p2 FROM @@ -97,18 +119,6 @@ WHERE p1.id < p2.id; ``` -### **Pandas** - -```python -import pandas as pd - - -# Modify Person in place -def delete_duplicate_emails(person: pd.DataFrame) -> None: - # Sort the rows based on id (Ascending order) - person.sort_values(by="id", ascending=True, inplace=True) - # Drop the duplicates based on email. - person.drop_duplicates(subset="email", keep="first", inplace=True) -``` - + + diff --git a/solution/0100-0199/0196.Delete Duplicate Emails/README_EN.md b/solution/0100-0199/0196.Delete Duplicate Emails/README_EN.md index d9e74cf4b59e6..0083bf6287f42 100644 --- a/solution/0100-0199/0196.Delete Duplicate Emails/README_EN.md +++ b/solution/0100-0199/0196.Delete Duplicate Emails/README_EN.md @@ -54,9 +54,21 @@ Person table: ## Solutions +### Solution 1 + -### **SQL** +```python +import pandas as pd + + +# Modify Person in place +def delete_duplicate_emails(person: pd.DataFrame) -> None: + # Sort the rows based on id (Ascending order) + person.sort_values(by="id", ascending=True, inplace=True) + # Drop the duplicates based on email. + person.drop_duplicates(subset="email", keep="first", inplace=True) +``` ```sql # Write your MySQL query statement below @@ -64,6 +76,12 @@ DELETE FROM Person WHERE id NOT IN (SELECT MIN(id) FROM (SELECT * FROM Person) AS p GROUP BY email); ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below DELETE FROM Person @@ -84,6 +102,12 @@ WHERE ); ``` + + +### Solution 3 + + + ```sql DELETE p2 FROM @@ -93,18 +117,6 @@ WHERE p1.id < p2.id; ``` -### **Pandas** - -```python -import pandas as pd - - -# Modify Person in place -def delete_duplicate_emails(person: pd.DataFrame) -> None: - # Sort the rows based on id (Ascending order) - person.sort_values(by="id", ascending=True, inplace=True) - # Drop the duplicates based on email. - person.drop_duplicates(subset="email", keep="first", inplace=True) -``` - + + diff --git a/solution/0100-0199/0197.Rising Temperature/README.md b/solution/0100-0199/0197.Rising Temperature/README.md index 05718f04ece75..7315f44bb7e9b 100644 --- a/solution/0100-0199/0197.Rising Temperature/README.md +++ b/solution/0100-0199/0197.Rising Temperature/README.md @@ -59,15 +59,22 @@ Weather 表: ## 解法 - - -**方法一:自连接 + DATEDIFF/SUBDATE 函数** +### 方法一:自连接 + DATEDIFF/SUBDATE 函数 我们可以通过自连接的方式,将 `Weather` 表中的每一行与它的前一行进行比较,如果温度更高,并且日期相差一天,那么就是我们要找的结果。 -### **SQL** +```python +import pandas as pd + + +def rising_temperature(weather: pd.DataFrame) -> pd.DataFrame: + weather.sort_values(by="recordDate", inplace=True) + return weather[ + (weather.temperature.diff() > 0) & (weather.recordDate.diff().dt.days == 1) + ][["id"]] +``` ```sql # Write your MySQL query statement below @@ -78,6 +85,12 @@ FROM ON DATEDIFF(w1.recordDate, w2.recordDate) = 1 AND w1.temperature > w2.temperature; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below SELECT w1.id @@ -87,17 +100,6 @@ FROM ON SUBDATE(w1.recordDate, 1) = w2.recordDate AND w1.temperature > w2.temperature; ``` -### **Pandas** - -```python -import pandas as pd - - -def rising_temperature(weather: pd.DataFrame) -> pd.DataFrame: - weather.sort_values(by="recordDate", inplace=True) - return weather[ - (weather.temperature.diff() > 0) & (weather.recordDate.diff().dt.days == 1) - ][["id"]] -``` - + + diff --git a/solution/0100-0199/0197.Rising Temperature/README_EN.md b/solution/0100-0199/0197.Rising Temperature/README_EN.md index 1c77ae9dabd14..24eb78c0aa349 100644 --- a/solution/0100-0199/0197.Rising Temperature/README_EN.md +++ b/solution/0100-0199/0197.Rising Temperature/README_EN.md @@ -54,13 +54,22 @@ In 2015-01-04, the temperature was higher than the previous day (20 -> 30). ## Solutions -**Solution 1: Self-Join + DATEDIFF/SUBDATE Function** +### Solution 1: Self-Join + DATEDIFF/SUBDATE Function We can use self-join to compare each row in the `Weather` table with its previous row. If the temperature is higher and the date difference is one day, then it is the result we are looking for. -### **SQL** +```python +import pandas as pd + + +def rising_temperature(weather: pd.DataFrame) -> pd.DataFrame: + weather.sort_values(by="recordDate", inplace=True) + return weather[ + (weather.temperature.diff() > 0) & (weather.recordDate.diff().dt.days == 1) + ][["id"]] +``` ```sql # Write your MySQL query statement below @@ -71,6 +80,12 @@ FROM ON DATEDIFF(w1.recordDate, w2.recordDate) = 1 AND w1.temperature > w2.temperature; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below SELECT w1.id @@ -80,17 +95,6 @@ FROM ON SUBDATE(w1.recordDate, 1) = w2.recordDate AND w1.temperature > w2.temperature; ``` -### **Pandas** - -```python -import pandas as pd - - -def rising_temperature(weather: pd.DataFrame) -> pd.DataFrame: - weather.sort_values(by="recordDate", inplace=True) - return weather[ - (weather.temperature.diff() > 0) & (weather.recordDate.diff().dt.days == 1) - ][["id"]] -``` - + + diff --git a/solution/0100-0199/0198.House Robber/README.md b/solution/0100-0199/0198.House Robber/README.md index 41021760645fe..2203e306b0ed6 100644 --- a/solution/0100-0199/0198.House Robber/README.md +++ b/solution/0100-0199/0198.House Robber/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示前 $i$ 间房屋能偷窃到的最高总金额,初始时 $f[0]=0$, $f[1]=nums[0]$。 @@ -70,10 +68,6 @@ $$ -### **Python3** - - - ```python class Solution: def rob(self, nums: List[int]) -> int: @@ -85,19 +79,6 @@ class Solution: return f[n] ``` -```python -class Solution: - def rob(self, nums: List[int]) -> int: - f = g = 0 - for x in nums: - f, g = max(f, g), f + x - return max(f, g) -``` - -### **Java** - - - ```java class Solution { public int rob(int[] nums) { @@ -112,22 +93,6 @@ class Solution { } ``` -```java -class Solution { - public int rob(int[] nums) { - int f = 0, g = 0; - for (int x : nums) { - int ff = Math.max(f, g); - g = f + x; - f = ff; - } - return Math.max(f, g); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -144,23 +109,6 @@ public: }; ``` -```cpp -class Solution { -public: - int rob(vector& nums) { - int f = 0, g = 0; - for (int& x : nums) { - int ff = max(f, g); - g = f + x; - f = ff; - } - return max(f, g); - } -}; -``` - -### **Go** - ```go func rob(nums []int) int { n := len(nums) @@ -173,18 +121,6 @@ func rob(nums []int) int { } ``` -```go -func rob(nums []int) int { - f, g := 0, 0 - for _, x := range nums { - f, g = max(f, g), f+x - } - return max(f, g) -} -``` - -### **TypeScript** - ```ts function rob(nums: number[]): number { const n = nums.length; @@ -197,18 +133,6 @@ function rob(nums: number[]): number { } ``` -```ts -function rob(nums: number[]): number { - let [f, g] = [0, 0]; - for (const x of nums) { - [f, g] = [Math.max(f, g), f + x]; - } - return Math.max(f, g); -} -``` - -### **Rust** - ```rust impl Solution { pub fn rob(nums: Vec) -> i32 { @@ -221,10 +145,70 @@ impl Solution { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def rob(self, nums: List[int]) -> int: + f = g = 0 + for x in nums: + f, g = max(f, g), f + x + return max(f, g) ``` +```java +class Solution { + public int rob(int[] nums) { + int f = 0, g = 0; + for (int x : nums) { + int ff = Math.max(f, g); + g = f + x; + f = ff; + } + return Math.max(f, g); + } +} +``` + +```cpp +class Solution { +public: + int rob(vector& nums) { + int f = 0, g = 0; + for (int& x : nums) { + int ff = max(f, g); + g = f + x; + f = ff; + } + return max(f, g); + } +}; +``` + +```go +func rob(nums []int) int { + f, g := 0, 0 + for _, x := range nums { + f, g = max(f, g), f+x + } + return max(f, g) +} +``` + +```ts +function rob(nums: number[]): number { + let [f, g] = [0, 0]; + for (const x of nums) { + [f, g] = [Math.max(f, g), f + x]; + } + return Math.max(f, g); +} ``` + + diff --git a/solution/0100-0199/0198.House Robber/README_EN.md b/solution/0100-0199/0198.House Robber/README_EN.md index bcb4b857ab958..beb113c5cc17c 100644 --- a/solution/0100-0199/0198.House Robber/README_EN.md +++ b/solution/0100-0199/0198.House Robber/README_EN.md @@ -37,9 +37,9 @@ Total amount you can rob = 2 + 9 + 1 = 12. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,17 +52,6 @@ class Solution: return f[n] ``` -```python -class Solution: - def rob(self, nums: List[int]) -> int: - f = g = 0 - for x in nums: - f, g = max(f, g), f + x - return max(f, g) -``` - -### **Java** - ```java class Solution { public int rob(int[] nums) { @@ -77,22 +66,6 @@ class Solution { } ``` -```java -class Solution { - public int rob(int[] nums) { - int f = 0, g = 0; - for (int x : nums) { - int ff = Math.max(f, g); - g = f + x; - f = ff; - } - return Math.max(f, g); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -109,23 +82,6 @@ public: }; ``` -```cpp -class Solution { -public: - int rob(vector& nums) { - int f = 0, g = 0; - for (int& x : nums) { - int ff = max(f, g); - g = f + x; - f = ff; - } - return max(f, g); - } -}; -``` - -### **Go** - ```go func rob(nums []int) int { n := len(nums) @@ -138,18 +94,6 @@ func rob(nums []int) int { } ``` -```go -func rob(nums []int) int { - f, g := 0, 0 - for _, x := range nums { - f, g = max(f, g), f+x - } - return max(f, g) -} -``` - -### **TypeScript** - ```ts function rob(nums: number[]): number { const n = nums.length; @@ -162,18 +106,6 @@ function rob(nums: number[]): number { } ``` -```ts -function rob(nums: number[]): number { - let [f, g] = [0, 0]; - for (const x of nums) { - [f, g] = [Math.max(f, g), f + x]; - } - return Math.max(f, g); -} -``` - -### **Rust** - ```rust impl Solution { pub fn rob(nums: Vec) -> i32 { @@ -186,10 +118,70 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def rob(self, nums: List[int]) -> int: + f = g = 0 + for x in nums: + f, g = max(f, g), f + x + return max(f, g) +``` + +```java +class Solution { + public int rob(int[] nums) { + int f = 0, g = 0; + for (int x : nums) { + int ff = Math.max(f, g); + g = f + x; + f = ff; + } + return Math.max(f, g); + } +} +``` + +```cpp +class Solution { +public: + int rob(vector& nums) { + int f = 0, g = 0; + for (int& x : nums) { + int ff = max(f, g); + g = f + x; + f = ff; + } + return max(f, g); + } +}; +``` +```go +func rob(nums []int) int { + f, g := 0, 0 + for _, x := range nums { + f, g = max(f, g), f+x + } + return max(f, g) +} ``` +```ts +function rob(nums: number[]): number { + let [f, g] = [0, 0]; + for (const x of nums) { + [f, g] = [Math.max(f, g), f + x]; + } + return Math.max(f, g); +} ``` + + diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/README.md b/solution/0100-0199/0199.Binary Tree Right Side View/README.md index 3f9caa599f3a3..a3da6fbd5d79e 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/README.md +++ b/solution/0100-0199/0199.Binary Tree Right Side View/README.md @@ -44,26 +44,14 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 使用 BFS 层序遍历二叉树,每层最后一个节点即为该层的右视图节点。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树节点个数。 -**方法二:DFS** - -使用 DFS 深度优先遍历二叉树,每次先遍历右子树,再遍历左子树,这样每层第一个遍历到的节点即为该层的右视图节点。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树节点个数。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -88,32 +76,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def rightSideView(self, root: Optional[TreeNode]) -> List[int]: - def dfs(node, depth): - if node is None: - return - if depth == len(ans): - ans.append(node.val) - dfs(node.right, depth + 1) - dfs(node.left, depth + 1) - - ans = [] - dfs(root, 0) - return ans -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -155,45 +117,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private List ans = new ArrayList<>(); - - public List rightSideView(TreeNode root) { - dfs(root, 0); - return ans; - } - - private void dfs(TreeNode node, int depth) { - if (node == null) { - return; - } - if (depth == ans.size()) { - ans.add(node.val); - } - dfs(node.right, depth + 1); - dfs(node.left, depth + 1); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -232,40 +155,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector rightSideView(TreeNode* root) { - vector ans; - function dfs = [&](TreeNode* node, int depth) { - if (!node) { - return; - } - if (depth == ans.size()) { - ans.emplace_back(node->val); - } - dfs(node->right, depth + 1); - dfs(node->left, depth + 1); - }; - dfs(root, 0); - return ans; - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -297,34 +186,6 @@ func rightSideView(root *TreeNode) (ans []int) { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func rightSideView(root *TreeNode) (ans []int) { - var dfs func(*TreeNode, int) - dfs = func(node *TreeNode, depth int) { - if node == nil { - return - } - if depth == len(ans) { - ans = append(ans, node.Val) - } - dfs(node.Right, depth+1) - dfs(node.Left, depth+1) - } - dfs(root, 0) - return -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -359,40 +220,6 @@ function rightSideView(root: TreeNode | null): number[] { } ``` -```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 rightSideView(root: TreeNode | null): number[] { - const ans = []; - const dfs = (node: TreeNode | null, depth: number) => { - if (!node) { - return; - } - if (depth == ans.length) { - ans.push(node.val); - } - dfs(node.right, depth + 1); - dfs(node.left, depth + 1); - }; - dfs(root, 0); - return ans; -} -``` - -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -443,10 +270,165 @@ impl Solution { } ``` -### **...** + + +### 方法二:DFS + +使用 DFS 深度优先遍历二叉树,每次先遍历右子树,再遍历左子树,这样每层第一个遍历到的节点即为该层的右视图节点。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树节点个数。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def rightSideView(self, root: Optional[TreeNode]) -> List[int]: + def dfs(node, depth): + if node is None: + return + if depth == len(ans): + ans.append(node.val) + dfs(node.right, depth + 1) + dfs(node.left, depth + 1) + + ans = [] + dfs(root, 0) + return ans +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List ans = new ArrayList<>(); + + public List rightSideView(TreeNode root) { + dfs(root, 0); + return ans; + } + + private void dfs(TreeNode node, int depth) { + if (node == null) { + return; + } + if (depth == ans.size()) { + ans.add(node.val); + } + dfs(node.right, depth + 1); + dfs(node.left, depth + 1); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector rightSideView(TreeNode* root) { + vector ans; + function dfs = [&](TreeNode* node, int depth) { + if (!node) { + return; + } + if (depth == ans.size()) { + ans.emplace_back(node->val); + } + dfs(node->right, depth + 1); + dfs(node->left, depth + 1); + }; + dfs(root, 0); + return ans; + } +}; +``` +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func rightSideView(root *TreeNode) (ans []int) { + var dfs func(*TreeNode, int) + dfs = func(node *TreeNode, depth int) { + if node == nil { + return + } + if depth == len(ans) { + ans = append(ans, node.Val) + } + dfs(node.Right, depth+1) + dfs(node.Left, depth+1) + } + dfs(root, 0) + return +} ``` +```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 rightSideView(root: TreeNode | null): number[] { + const ans = []; + const dfs = (node: TreeNode | null, depth: number) => { + if (!node) { + return; + } + if (depth == ans.length) { + ans.push(node.val); + } + dfs(node.right, depth + 1); + dfs(node.left, depth + 1); + }; + dfs(root, 0); + return ans; +} ``` + + diff --git a/solution/0100-0199/0199.Binary Tree Right Side View/README_EN.md b/solution/0100-0199/0199.Binary Tree Right Side View/README_EN.md index 87102348b31d1..d8e3f14ec48cc 100644 --- a/solution/0100-0199/0199.Binary Tree Right Side View/README_EN.md +++ b/solution/0100-0199/0199.Binary Tree Right Side View/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -66,30 +66,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def rightSideView(self, root: Optional[TreeNode]) -> List[int]: - def dfs(node, depth): - if node is None: - return - if depth == len(ans): - ans.append(node.val) - dfs(node.right, depth + 1) - dfs(node.left, depth + 1) - - ans = [] - dfs(root, 0) - return ans -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -131,45 +107,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private List ans = new ArrayList<>(); - - public List rightSideView(TreeNode root) { - dfs(root, 0); - return ans; - } - - private void dfs(TreeNode node, int depth) { - if (node == null) { - return; - } - if (depth == ans.size()) { - ans.add(node.val); - } - dfs(node.right, depth + 1); - dfs(node.left, depth + 1); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -208,40 +145,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector rightSideView(TreeNode* root) { - vector ans; - function dfs = [&](TreeNode* node, int depth) { - if (!node) { - return; - } - if (depth == ans.size()) { - ans.emplace_back(node->val); - } - dfs(node->right, depth + 1); - dfs(node->left, depth + 1); - }; - dfs(root, 0); - return ans; - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -273,34 +176,6 @@ func rightSideView(root *TreeNode) (ans []int) { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func rightSideView(root *TreeNode) (ans []int) { - var dfs func(*TreeNode, int) - dfs = func(node *TreeNode, depth int) { - if node == nil { - return - } - if depth == len(ans) { - ans = append(ans, node.Val) - } - dfs(node.Right, depth+1) - dfs(node.Left, depth+1) - } - dfs(root, 0) - return -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -335,40 +210,6 @@ function rightSideView(root: TreeNode | null): number[] { } ``` -```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 rightSideView(root: TreeNode | null): number[] { - const ans = []; - const dfs = (node: TreeNode | null, depth: number) => { - if (!node) { - return; - } - if (depth == ans.length) { - ans.push(node.val); - } - dfs(node.right, depth + 1); - dfs(node.left, depth + 1); - }; - dfs(root, 0); - return ans; -} -``` - -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -419,10 +260,161 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def rightSideView(self, root: Optional[TreeNode]) -> List[int]: + def dfs(node, depth): + if node is None: + return + if depth == len(ans): + ans.append(node.val) + dfs(node.right, depth + 1) + dfs(node.left, depth + 1) + + ans = [] + dfs(root, 0) + return ans ``` +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List ans = new ArrayList<>(); + + public List rightSideView(TreeNode root) { + dfs(root, 0); + return ans; + } + + private void dfs(TreeNode node, int depth) { + if (node == null) { + return; + } + if (depth == ans.size()) { + ans.add(node.val); + } + dfs(node.right, depth + 1); + dfs(node.left, depth + 1); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector rightSideView(TreeNode* root) { + vector ans; + function dfs = [&](TreeNode* node, int depth) { + if (!node) { + return; + } + if (depth == ans.size()) { + ans.emplace_back(node->val); + } + dfs(node->right, depth + 1); + dfs(node->left, depth + 1); + }; + dfs(root, 0); + return ans; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func rightSideView(root *TreeNode) (ans []int) { + var dfs func(*TreeNode, int) + dfs = func(node *TreeNode, depth int) { + if node == nil { + return + } + if depth == len(ans) { + ans = append(ans, node.Val) + } + dfs(node.Right, depth+1) + dfs(node.Left, depth+1) + } + dfs(root, 0) + return +} +``` + +```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 rightSideView(root: TreeNode | null): number[] { + const ans = []; + const dfs = (node: TreeNode | null, depth: number) => { + if (!node) { + return; + } + if (depth == ans.length) { + ans.push(node.val); + } + dfs(node.right, depth + 1); + dfs(node.left, depth + 1); + }; + dfs(root, 0); + return ans; +} ``` + + diff --git a/solution/0200-0299/0200.Number of Islands/README.md b/solution/0200-0299/0200.Number of Islands/README.md index a9466f8d163a1..47534db2fb56b 100644 --- a/solution/0200-0299/0200.Number of Islands/README.md +++ b/solution/0200-0299/0200.Number of Islands/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:Flood fill 算法** +### 方法一:Flood fill 算法 Flood fill 算法是从一个区域中提取若干个连通的点与其他相邻区域区分开(或分别染成不同颜色)的经典算法。因为其思路类似洪水从一个区域扩散到所有能到达的区域而得名。 @@ -61,7 +59,233 @@ Flood fill 算法是从一个区域中提取若干个连通的点与其他相邻 时间复杂度 $O(m\times n)$,空间复杂度 $O(m\times n)$。其中 $m$ 和 $n$ 分别为网格的行数和列数。 -**方法二:并查集** + + +```python +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + def dfs(i, j): + grid[i][j] = '0' + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and grid[x][y] == '1': + dfs(x, y) + + ans = 0 + dirs = (-1, 0, 1, 0, -1) + m, n = len(grid), len(grid[0]) + for i in range(m): + for j in range(n): + if grid[i][j] == '1': + dfs(i, j) + ans += 1 + return ans +``` + +```java +class Solution { + private char[][] grid; + private int m; + private int n; + + public int numIslands(char[][] grid) { + m = grid.length; + n = grid[0].length; + this.grid = grid; + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + dfs(i, j); + ++ans; + } + } + } + return ans; + } + + private void dfs(int i, int j) { + grid[i][j] = '0'; + int[] dirs = {-1, 0, 1, 0, -1}; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k]; + int y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { + dfs(x, y); + } + } + } +} +``` + +```cpp +class Solution { +public: + int numIslands(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + int ans = 0; + int dirs[5] = {-1, 0, 1, 0, -1}; + function dfs = [&](int i, int j) { + grid[i][j] = '0'; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == '1') { + dfs(x, y); + } + } + }; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + dfs(i, j); + ++ans; + } + } + } + return ans; + } +}; +``` + +```go +func numIslands(grid [][]byte) int { + m, n := len(grid), len(grid[0]) + var dfs func(i, j int) + dfs = func(i, j int) { + grid[i][j] = '0' + dirs := []int{-1, 0, 1, 0, -1} + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' { + dfs(x, y) + } + } + } + ans := 0 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] == '1' { + dfs(i, j) + ans++ + } + } + } + return ans +} +``` + +```ts +function numIslands(grid: string[][]): number { + const m = grid.length; + const n = grid[0].length; + let ans = 0; + function dfs(i, j) { + grid[i][j] = '0'; + const dirs = [-1, 0, 1, 0, -1]; + for (let k = 0; k < 4; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { + dfs(x, y); + } + } + } + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + dfs(i, j); + ++ans; + } + } + } + return ans; +} +``` + +```rust +const DIRS: [i32; 5] = [-1, 0, 1, 0, -1]; + +impl Solution { + pub fn num_islands(grid: Vec>) -> i32 { + fn dfs(grid: &mut Vec>, i: usize, j: usize) { + grid[i][j] = '0'; + for k in 0..4 { + let x = (i as i32) + DIRS[k]; + let y = (j as i32) + DIRS[k + 1]; + if + x >= 0 && + (x as usize) < grid.len() && + y >= 0 && + (y as usize) < grid[0].len() && + grid[x as usize][y as usize] == '1' + { + dfs(grid, x as usize, y as usize); + } + } + } + + let mut grid = grid; + let mut ans = 0; + for i in 0..grid.len() { + for j in 0..grid[0].len() { + if grid[i][j] == '1' { + dfs(&mut grid, i, j); + ans += 1; + } + } + } + ans + } +} +``` + +```cs +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public int NumIslands(char[][] grid) + { + var queue = new Queue>(); + var lenI = grid.Length; + var lenJ = lenI == 0 ? 0 : grid[0].Length; + var paths = new int[,] { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; + var result = 0; + for (var i = 0; i < lenI; ++i) + { + for (var j = 0; j < lenJ; ++j) + { + if (grid[i][j] == '1') + { + ++result; + grid[i][j] = '0'; + queue.Enqueue(Tuple.Create(i, j)); + while (queue.Any()) + { + var position = queue.Dequeue(); + for (var k = 0; k < 4; ++k) + { + var next = Tuple.Create(position.Item1 + paths[k, 0], position.Item2 + paths[k, 1]); + if (next.Item1 >= 0 && next.Item1 < lenI && next.Item2 >= 0 && next.Item2 < lenJ && grid[next.Item1][next.Item2] == '1') + { + grid[next.Item1][next.Item2] = '0'; + queue.Enqueue(next); + } + } + } + } + } + } + return result; + } +} +``` + + + +### 方法二:并查集 并查集是一种树形的数据结构,顾名思义,它用于处理一些不交集的**合并**及**查询**问题。 它支持两种操作: @@ -102,35 +326,6 @@ def union(a, b): -### **Python3** - - - -DFS - Flood Fill 算法: - -```python -class Solution: - def numIslands(self, grid: List[List[str]]) -> int: - def dfs(i, j): - grid[i][j] = '0' - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n and grid[x][y] == '1': - dfs(x, y) - - ans = 0 - dirs = (-1, 0, 1, 0, -1) - m, n = len(grid), len(grid[0]) - for i in range(m): - for j in range(n): - if grid[i][j] == '1': - dfs(i, j) - ans += 1 - return ans -``` - -BFS - Flood Fill 算法: - ```python class Solution: def numIslands(self, grid: List[List[str]]) -> int: @@ -156,77 +351,6 @@ class Solution: return ans ``` -并查集: - -```python -class Solution: - def numIslands(self, grid: List[List[str]]) -> int: - def find(x): - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - dirs = (0, 1, 0) - m, n = len(grid), len(grid[0]) - p = list(range(m * n)) - for i in range(m): - for j in range(n): - if grid[i][j] == '1': - for a, b in pairwise(dirs): - x, y = i + a, j + b - if x < m and y < n and grid[x][y] == '1': - p[find(i * n + j)] = find(x * n + y) - return sum( - grid[i][j] == '1' and i * n + j == find(i * n + j) - for i in range(m) - for j in range(n) - ) -``` - -### **Java** - - - -DFS - Flood Fill 算法: - -```java -class Solution { - private char[][] grid; - private int m; - private int n; - - public int numIslands(char[][] grid) { - m = grid.length; - n = grid[0].length; - this.grid = grid; - int ans = 0; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == '1') { - dfs(i, j); - ++ans; - } - } - } - return ans; - } - - private void dfs(int i, int j) { - grid[i][j] = '0'; - int[] dirs = {-1, 0, 1, 0, -1}; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k]; - int y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { - dfs(x, y); - } - } - } -} -``` - -BFS - Flood Fill 算法: - ```java class Solution { private char[][] grid; @@ -269,129 +393,229 @@ class Solution { } ``` -并查集: - -```java +```cpp class Solution { - private int[] p; - - public int numIslands(char[][] grid) { - int m = grid.length; - int n = grid[0].length; - p = new int[m * n]; - for (int i = 0; i < p.length; ++i) { - p[i] = i; - } - int[] dirs = {1, 0, 1}; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == '1') { - for (int k = 0; k < 2; ++k) { - int x = i + dirs[k]; - int y = j + dirs[k + 1]; - if (x < m && y < n && grid[x][y] == '1') { - p[find(x * n + y)] = find(i * n + j); - } +public: + int numIslands(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + int ans = 0; + int dirs[5] = {-1, 0, 1, 0, -1}; + function bfs = [&](int i, int j) { + grid[i][j] = '0'; + queue> q; + q.push({i, j}); + vector dirs = {-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 < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == '1') { + q.push({x, y}); + grid[x][y] = '0'; } } } - } - int ans = 0; + }; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { - if (grid[i][j] == '1' && i * n + j == find(i * n + j)) { + if (grid[i][j] == '1') { + bfs(i, j); ++ans; } } } return ans; } +}; +``` - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); +```go +func numIslands(grid [][]byte) int { + m, n := len(grid), len(grid[0]) + bfs := func(i, j int) { + grid[i][j] = '0' + q := [][]int{[]int{i, j}} + 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 < m && y >= 0 && y < n && grid[x][y] == '1' { + q = append(q, []int{x, y}) + grid[x][y] = '0' + } + } + } + } + ans := 0 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] == '1' { + bfs(i, j) + ans++ + } + } + } + return ans +} +``` + +```ts +function numIslands(grid: string[][]): number { + const m = grid.length; + const n = grid[0].length; + let ans = 0; + function bfs(i, j) { + grid[i][j] = '0'; + let q = [[i, j]]; + const dirs = [-1, 0, 1, 0, -1]; + while (q.length) { + [i, j] = q.shift(); + for (let k = 0; k < 4; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { + q.push([x, y]); + grid[x][y] = '0'; + } + } + } + } + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + bfs(i, j); + ++ans; + } } - return p[x]; } + return ans; } ``` -### **C++** +```rust +use std::collections::VecDeque; -DFS - Flood Fill 算法: +const DIRS: [i32; 5] = [-1, 0, 1, 0, -1]; -```cpp -class Solution { -public: - int numIslands(vector>& grid) { - int m = grid.size(); - int n = grid[0].size(); - int ans = 0; - int dirs[5] = {-1, 0, 1, 0, -1}; - function dfs = [&](int i, int j) { +impl Solution { + pub fn num_islands(grid: Vec>) -> i32 { + fn bfs(grid: &mut Vec>, i: usize, j: usize) { grid[i][j] = '0'; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == '1') { - dfs(x, y); + let mut queue = VecDeque::from([(i, j)]); + while !queue.is_empty() { + let (i, j) = queue.pop_front().unwrap(); + for k in 0..4 { + let x = (i as i32) + DIRS[k]; + let y = (j as i32) + DIRS[k + 1]; + if + x >= 0 && + (x as usize) < grid.len() && + y >= 0 && + (y as usize) < grid[0].len() && + grid[x as usize][y as usize] == '1' + { + grid[x as usize][y as usize] = '0'; + queue.push_back((x as usize, y as usize)); + } } } - }; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == '1') { - dfs(i, j); - ++ans; + } + + let mut grid = grid; + let mut ans = 0; + for i in 0..grid.len() { + for j in 0..grid[0].len() { + if grid[i][j] == '1' { + bfs(&mut grid, i, j); + ans += 1; } } } - return ans; + ans } -}; +} ``` -BFS - Flood Fill 算法: + -```cpp -class Solution { -public: - int numIslands(vector>& grid) { - int m = grid.size(); - int n = grid[0].size(); - int ans = 0; - int dirs[5] = {-1, 0, 1, 0, -1}; - function bfs = [&](int i, int j) { - grid[i][j] = '0'; - queue> q; - q.push({i, j}); - vector dirs = {-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 < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == '1') { - q.push({x, y}); - grid[x][y] = '0'; +### 方法三 + + + +```python +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + dirs = (0, 1, 0) + m, n = len(grid), len(grid[0]) + p = list(range(m * n)) + for i in range(m): + for j in range(n): + if grid[i][j] == '1': + for a, b in pairwise(dirs): + x, y = i + a, j + b + if x < m and y < n and grid[x][y] == '1': + p[find(i * n + j)] = find(x * n + y) + return sum( + grid[i][j] == '1' and i * n + j == find(i * n + j) + for i in range(m) + for j in range(n) + ) +``` + +```java +class Solution { + private int[] p; + + public int numIslands(char[][] grid) { + int m = grid.length; + int n = grid[0].length; + p = new int[m * n]; + for (int i = 0; i < p.length; ++i) { + p[i] = i; + } + int[] dirs = {1, 0, 1}; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + for (int k = 0; k < 2; ++k) { + int x = i + dirs[k]; + int y = j + dirs[k + 1]; + if (x < m && y < n && grid[x][y] == '1') { + p[find(x * n + y)] = find(i * n + j); + } } } } - }; + } + int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { - if (grid[i][j] == '1') { - bfs(i, j); + if (grid[i][j] == '1' && i * n + j == find(i * n + j)) { ++ans; } } } return ans; } -}; -``` -并查集: + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} +``` ```cpp class Solution { @@ -432,73 +656,6 @@ public: }; ``` -### **Go** - -DFS - Flood Fill 算法: - -```go -func numIslands(grid [][]byte) int { - m, n := len(grid), len(grid[0]) - var dfs func(i, j int) - dfs = func(i, j int) { - grid[i][j] = '0' - dirs := []int{-1, 0, 1, 0, -1} - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' { - dfs(x, y) - } - } - } - ans := 0 - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - if grid[i][j] == '1' { - dfs(i, j) - ans++ - } - } - } - return ans -} -``` - -BFS - Flood Fill 算法: - -```go -func numIslands(grid [][]byte) int { - m, n := len(grid), len(grid[0]) - bfs := func(i, j int) { - grid[i][j] = '0' - q := [][]int{[]int{i, j}} - 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 < m && y >= 0 && y < n && grid[x][y] == '1' { - q = append(q, []int{x, y}) - grid[x][y] = '0' - } - } - } - } - ans := 0 - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - if grid[i][j] == '1' { - bfs(i, j) - ans++ - } - } - } - return ans -} -``` - -并查集: - ```go func numIslands(grid [][]byte) int { m, n := len(grid), len(grid[0]) @@ -538,75 +695,6 @@ func numIslands(grid [][]byte) int { } ``` -### **TypeScript** - -DFS - Flood Fill 算法: - -```ts -function numIslands(grid: string[][]): number { - const m = grid.length; - const n = grid[0].length; - let ans = 0; - function dfs(i, j) { - grid[i][j] = '0'; - const dirs = [-1, 0, 1, 0, -1]; - for (let k = 0; k < 4; ++k) { - const x = i + dirs[k]; - const y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { - dfs(x, y); - } - } - } - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (grid[i][j] == '1') { - dfs(i, j); - ++ans; - } - } - } - return ans; -} -``` - -BFS - Flood Fill 算法: - -```ts -function numIslands(grid: string[][]): number { - const m = grid.length; - const n = grid[0].length; - let ans = 0; - function bfs(i, j) { - grid[i][j] = '0'; - let q = [[i, j]]; - const dirs = [-1, 0, 1, 0, -1]; - while (q.length) { - [i, j] = q.shift(); - for (let k = 0; k < 4; ++k) { - const x = i + dirs[k]; - const y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { - q.push([x, y]); - grid[x][y] = '0'; - } - } - } - } - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (grid[i][j] == '1') { - bfs(i, j); - ++ans; - } - } - } - return ans; -} -``` - -并查集: - ```ts function numIslands(grid: string[][]): number { const m = grid.length; @@ -647,95 +735,6 @@ function numIslands(grid: string[][]): number { } ``` -### **Rust** - -DFS - Flood Fill 算法: - -```rust -const DIRS: [i32; 5] = [-1, 0, 1, 0, -1]; - -impl Solution { - pub fn num_islands(grid: Vec>) -> i32 { - fn dfs(grid: &mut Vec>, i: usize, j: usize) { - grid[i][j] = '0'; - for k in 0..4 { - let x = (i as i32) + DIRS[k]; - let y = (j as i32) + DIRS[k + 1]; - if - x >= 0 && - (x as usize) < grid.len() && - y >= 0 && - (y as usize) < grid[0].len() && - grid[x as usize][y as usize] == '1' - { - dfs(grid, x as usize, y as usize); - } - } - } - - let mut grid = grid; - let mut ans = 0; - for i in 0..grid.len() { - for j in 0..grid[0].len() { - if grid[i][j] == '1' { - dfs(&mut grid, i, j); - ans += 1; - } - } - } - ans - } -} -``` - -BFS - Flood Fill 算法: - -```rust -use std::collections::VecDeque; - -const DIRS: [i32; 5] = [-1, 0, 1, 0, -1]; - -impl Solution { - pub fn num_islands(grid: Vec>) -> i32 { - fn bfs(grid: &mut Vec>, i: usize, j: usize) { - grid[i][j] = '0'; - let mut queue = VecDeque::from([(i, j)]); - while !queue.is_empty() { - let (i, j) = queue.pop_front().unwrap(); - for k in 0..4 { - let x = (i as i32) + DIRS[k]; - let y = (j as i32) + DIRS[k + 1]; - if - x >= 0 && - (x as usize) < grid.len() && - y >= 0 && - (y as usize) < grid[0].len() && - grid[x as usize][y as usize] == '1' - { - grid[x as usize][y as usize] = '0'; - queue.push_back((x as usize, y as usize)); - } - } - } - } - - let mut grid = grid; - let mut ans = 0; - for i in 0..grid.len() { - for j in 0..grid[0].len() { - if grid[i][j] == '1' { - bfs(&mut grid, i, j); - ans += 1; - } - } - } - ans - } -} -``` - -并查集: - ```rust const DIRS: [usize; 3] = [1, 0, 1]; @@ -781,10 +780,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0200.Number of Islands/README_EN.md b/solution/0200-0299/0200.Number of Islands/README_EN.md index 003d43872b844..47da0c8660c74 100644 --- a/solution/0200-0299/0200.Number of Islands/README_EN.md +++ b/solution/0200-0299/0200.Number of Islands/README_EN.md @@ -45,16 +45,10 @@ ## Solutions -DFS, BFS or Union find. - -> Flood fill, also called seed fill, is a flooding algorithm that determines and alters the area connected to a given node in a multi-dimensional array with some matching attribute. It is used in the "bucket" fill tool of paint programs to fill connected, similarly-colored areas with a different color. +### Solution 1 -### **Python3** - -DFS: - ```python class Solution: def numIslands(self, grid: List[List[str]]) -> int: @@ -76,64 +70,6 @@ class Solution: return ans ``` -BFS: - -```python -class Solution: - def numIslands(self, grid: List[List[str]]) -> int: - def bfs(i, j): - grid[i][j] = '0' - q = deque([(i, j)]) - while q: - i, j = q.popleft() - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n and grid[x][y] == '1': - q.append((x, y)) - grid[x][y] = 0 - - ans = 0 - dirs = (-1, 0, 1, 0, -1) - m, n = len(grid), len(grid[0]) - for i in range(m): - for j in range(n): - if grid[i][j] == '1': - bfs(i, j) - ans += 1 - return ans -``` - -Union Find: - -```python -class Solution: - def numIslands(self, grid: List[List[str]]) -> int: - def find(x): - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - dirs = (0, 1, 0) - m, n = len(grid), len(grid[0]) - p = list(range(m * n)) - for i in range(m): - for j in range(n): - if grid[i][j] == '1': - for a, b in pairwise(dirs): - x, y = i + a, j + b - if x < m and y < n and grid[x][y] == '1': - p[find(i * n + j)] = find(x * n + y) - return sum( - grid[i][j] == '1' and i * n + j == find(i * n + j) - for i in range(m) - for j in range(n) - ) -``` - -### **Java** - -DFS: - ```java class Solution { private char[][] grid; @@ -170,7 +106,201 @@ class Solution { } ``` -BFS: +```cpp +class Solution { +public: + int numIslands(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + int ans = 0; + int dirs[5] = {-1, 0, 1, 0, -1}; + function dfs = [&](int i, int j) { + grid[i][j] = '0'; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == '1') { + dfs(x, y); + } + } + }; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + dfs(i, j); + ++ans; + } + } + } + return ans; + } +}; +``` + +```go +func numIslands(grid [][]byte) int { + m, n := len(grid), len(grid[0]) + var dfs func(i, j int) + dfs = func(i, j int) { + grid[i][j] = '0' + dirs := []int{-1, 0, 1, 0, -1} + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' { + dfs(x, y) + } + } + } + ans := 0 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] == '1' { + dfs(i, j) + ans++ + } + } + } + return ans +} +``` + +```ts +function numIslands(grid: string[][]): number { + const m = grid.length; + const n = grid[0].length; + let ans = 0; + function dfs(i, j) { + grid[i][j] = '0'; + const dirs = [-1, 0, 1, 0, -1]; + for (let k = 0; k < 4; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { + dfs(x, y); + } + } + } + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + dfs(i, j); + ++ans; + } + } + } + return ans; +} +``` + +```rust +const DIRS: [i32; 5] = [-1, 0, 1, 0, -1]; + +impl Solution { + pub fn num_islands(grid: Vec>) -> i32 { + fn dfs(grid: &mut Vec>, i: usize, j: usize) { + grid[i][j] = '0'; + for k in 0..4 { + let x = (i as i32) + DIRS[k]; + let y = (j as i32) + DIRS[k + 1]; + if + x >= 0 && + (x as usize) < grid.len() && + y >= 0 && + (y as usize) < grid[0].len() && + grid[x as usize][y as usize] == '1' + { + dfs(grid, x as usize, y as usize); + } + } + } + + let mut grid = grid; + let mut ans = 0; + for i in 0..grid.len() { + for j in 0..grid[0].len() { + if grid[i][j] == '1' { + dfs(&mut grid, i, j); + ans += 1; + } + } + } + ans + } +} +``` + +```cs +using System; +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public int NumIslands(char[][] grid) + { + var queue = new Queue>(); + var lenI = grid.Length; + var lenJ = lenI == 0 ? 0 : grid[0].Length; + var paths = new int[,] { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; + var result = 0; + for (var i = 0; i < lenI; ++i) + { + for (var j = 0; j < lenJ; ++j) + { + if (grid[i][j] == '1') + { + ++result; + grid[i][j] = '0'; + queue.Enqueue(Tuple.Create(i, j)); + while (queue.Any()) + { + var position = queue.Dequeue(); + for (var k = 0; k < 4; ++k) + { + var next = Tuple.Create(position.Item1 + paths[k, 0], position.Item2 + paths[k, 1]); + if (next.Item1 >= 0 && next.Item1 < lenI && next.Item2 >= 0 && next.Item2 < lenJ && grid[next.Item1][next.Item2] == '1') + { + grid[next.Item1][next.Item2] = '0'; + queue.Enqueue(next); + } + } + } + } + } + } + return result; + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + def bfs(i, j): + grid[i][j] = '0' + q = deque([(i, j)]) + while q: + i, j = q.popleft() + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and grid[x][y] == '1': + q.append((x, y)) + grid[x][y] = 0 + + ans = 0 + dirs = (-1, 0, 1, 0, -1) + m, n = len(grid), len(grid[0]) + for i in range(m): + for j in range(n): + if grid[i][j] == '1': + bfs(i, j) + ans += 1 + return ans +``` ```java class Solution { @@ -214,129 +344,229 @@ class Solution { } ``` -Union Find: - -```java +```cpp class Solution { - private int[] p; - - public int numIslands(char[][] grid) { - int m = grid.length; - int n = grid[0].length; - p = new int[m * n]; - for (int i = 0; i < p.length; ++i) { - p[i] = i; - } - int[] dirs = {1, 0, 1}; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == '1') { - for (int k = 0; k < 2; ++k) { - int x = i + dirs[k]; - int y = j + dirs[k + 1]; - if (x < m && y < n && grid[x][y] == '1') { - p[find(x * n + y)] = find(i * n + j); - } +public: + int numIslands(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + int ans = 0; + int dirs[5] = {-1, 0, 1, 0, -1}; + function bfs = [&](int i, int j) { + grid[i][j] = '0'; + queue> q; + q.push({i, j}); + vector dirs = {-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 < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == '1') { + q.push({x, y}); + grid[x][y] = '0'; } } } - } - int ans = 0; + }; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { - if (grid[i][j] == '1' && i * n + j == find(i * n + j)) { + if (grid[i][j] == '1') { + bfs(i, j); ++ans; } } } return ans; } +}; +``` - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); +```go +func numIslands(grid [][]byte) int { + m, n := len(grid), len(grid[0]) + bfs := func(i, j int) { + grid[i][j] = '0' + q := [][]int{[]int{i, j}} + 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 < m && y >= 0 && y < n && grid[x][y] == '1' { + q = append(q, []int{x, y}) + grid[x][y] = '0' + } + } + } + } + ans := 0 + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] == '1' { + bfs(i, j) + ans++ + } + } + } + return ans +} +``` + +```ts +function numIslands(grid: string[][]): number { + const m = grid.length; + const n = grid[0].length; + let ans = 0; + function bfs(i, j) { + grid[i][j] = '0'; + let q = [[i, j]]; + const dirs = [-1, 0, 1, 0, -1]; + while (q.length) { + [i, j] = q.shift(); + for (let k = 0; k < 4; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { + q.push([x, y]); + grid[x][y] = '0'; + } + } } - return p[x]; } + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + bfs(i, j); + ++ans; + } + } + } + return ans; } ``` -### **C++** +```rust +use std::collections::VecDeque; -DFS: +const DIRS: [i32; 5] = [-1, 0, 1, 0, -1]; -```cpp -class Solution { -public: - int numIslands(vector>& grid) { - int m = grid.size(); - int n = grid[0].size(); - int ans = 0; - int dirs[5] = {-1, 0, 1, 0, -1}; - function dfs = [&](int i, int j) { +impl Solution { + pub fn num_islands(grid: Vec>) -> i32 { + fn bfs(grid: &mut Vec>, i: usize, j: usize) { grid[i][j] = '0'; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == '1') { - dfs(x, y); + let mut queue = VecDeque::from([(i, j)]); + while !queue.is_empty() { + let (i, j) = queue.pop_front().unwrap(); + for k in 0..4 { + let x = (i as i32) + DIRS[k]; + let y = (j as i32) + DIRS[k + 1]; + if + x >= 0 && + (x as usize) < grid.len() && + y >= 0 && + (y as usize) < grid[0].len() && + grid[x as usize][y as usize] == '1' + { + grid[x as usize][y as usize] = '0'; + queue.push_back((x as usize, y as usize)); + } } } - }; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == '1') { - dfs(i, j); - ++ans; + } + + let mut grid = grid; + let mut ans = 0; + for i in 0..grid.len() { + for j in 0..grid[0].len() { + if grid[i][j] == '1' { + bfs(&mut grid, i, j); + ans += 1; } } } - return ans; + ans } -}; +} ``` -BFS: + -```cpp -class Solution { -public: - int numIslands(vector>& grid) { - int m = grid.size(); - int n = grid[0].size(); - int ans = 0; - int dirs[5] = {-1, 0, 1, 0, -1}; - function bfs = [&](int i, int j) { - grid[i][j] = '0'; - queue> q; - q.push({i, j}); - vector dirs = {-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 < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == '1') { - q.push({x, y}); - grid[x][y] = '0'; +### Solution 3 + + + +```python +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + dirs = (0, 1, 0) + m, n = len(grid), len(grid[0]) + p = list(range(m * n)) + for i in range(m): + for j in range(n): + if grid[i][j] == '1': + for a, b in pairwise(dirs): + x, y = i + a, j + b + if x < m and y < n and grid[x][y] == '1': + p[find(i * n + j)] = find(x * n + y) + return sum( + grid[i][j] == '1' and i * n + j == find(i * n + j) + for i in range(m) + for j in range(n) + ) +``` + +```java +class Solution { + private int[] p; + + public int numIslands(char[][] grid) { + int m = grid.length; + int n = grid[0].length; + p = new int[m * n]; + for (int i = 0; i < p.length; ++i) { + p[i] = i; + } + int[] dirs = {1, 0, 1}; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + for (int k = 0; k < 2; ++k) { + int x = i + dirs[k]; + int y = j + dirs[k + 1]; + if (x < m && y < n && grid[x][y] == '1') { + p[find(x * n + y)] = find(i * n + j); + } } } } - }; + } + int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { - if (grid[i][j] == '1') { - bfs(i, j); + if (grid[i][j] == '1' && i * n + j == find(i * n + j)) { ++ans; } } } return ans; } -}; -``` -Union find: + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} +``` ```cpp class Solution { @@ -377,73 +607,6 @@ public: }; ``` -### **Go** - -DFS: - -```go -func numIslands(grid [][]byte) int { - m, n := len(grid), len(grid[0]) - var dfs func(i, j int) - dfs = func(i, j int) { - grid[i][j] = '0' - dirs := []int{-1, 0, 1, 0, -1} - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' { - dfs(x, y) - } - } - } - ans := 0 - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - if grid[i][j] == '1' { - dfs(i, j) - ans++ - } - } - } - return ans -} -``` - -BFS: - -```go -func numIslands(grid [][]byte) int { - m, n := len(grid), len(grid[0]) - bfs := func(i, j int) { - grid[i][j] = '0' - q := [][]int{[]int{i, j}} - 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 < m && y >= 0 && y < n && grid[x][y] == '1' { - q = append(q, []int{x, y}) - grid[x][y] = '0' - } - } - } - } - ans := 0 - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - if grid[i][j] == '1' { - bfs(i, j) - ans++ - } - } - } - return ans -} -``` - -Union find: - ```go func numIslands(grid [][]byte) int { m, n := len(grid), len(grid[0]) @@ -483,75 +646,6 @@ func numIslands(grid [][]byte) int { } ``` -### **TypeScript** - -DFS: - -```ts -function numIslands(grid: string[][]): number { - const m = grid.length; - const n = grid[0].length; - let ans = 0; - function dfs(i, j) { - grid[i][j] = '0'; - const dirs = [-1, 0, 1, 0, -1]; - for (let k = 0; k < 4; ++k) { - const x = i + dirs[k]; - const y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { - dfs(x, y); - } - } - } - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (grid[i][j] == '1') { - dfs(i, j); - ++ans; - } - } - } - return ans; -} -``` - -BFS: - -```ts -function numIslands(grid: string[][]): number { - const m = grid.length; - const n = grid[0].length; - let ans = 0; - function bfs(i, j) { - grid[i][j] = '0'; - let q = [[i, j]]; - const dirs = [-1, 0, 1, 0, -1]; - while (q.length) { - [i, j] = q.shift(); - for (let k = 0; k < 4; ++k) { - const x = i + dirs[k]; - const y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { - q.push([x, y]); - grid[x][y] = '0'; - } - } - } - } - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (grid[i][j] == '1') { - bfs(i, j); - ++ans; - } - } - } - return ans; -} -``` - -Union find: - ```ts function numIslands(grid: string[][]): number { const m = grid.length; @@ -592,95 +686,6 @@ function numIslands(grid: string[][]): number { } ``` -### **Rust** - -DFS: - -```rust -const DIRS: [i32; 5] = [-1, 0, 1, 0, -1]; - -impl Solution { - pub fn num_islands(grid: Vec>) -> i32 { - fn dfs(grid: &mut Vec>, i: usize, j: usize) { - grid[i][j] = '0'; - for k in 0..4 { - let x = (i as i32) + DIRS[k]; - let y = (j as i32) + DIRS[k + 1]; - if - x >= 0 && - (x as usize) < grid.len() && - y >= 0 && - (y as usize) < grid[0].len() && - grid[x as usize][y as usize] == '1' - { - dfs(grid, x as usize, y as usize); - } - } - } - - let mut grid = grid; - let mut ans = 0; - for i in 0..grid.len() { - for j in 0..grid[0].len() { - if grid[i][j] == '1' { - dfs(&mut grid, i, j); - ans += 1; - } - } - } - ans - } -} -``` - -BFS: - -```rust -use std::collections::VecDeque; - -const DIRS: [i32; 5] = [-1, 0, 1, 0, -1]; - -impl Solution { - pub fn num_islands(grid: Vec>) -> i32 { - fn bfs(grid: &mut Vec>, i: usize, j: usize) { - grid[i][j] = '0'; - let mut queue = VecDeque::from([(i, j)]); - while !queue.is_empty() { - let (i, j) = queue.pop_front().unwrap(); - for k in 0..4 { - let x = (i as i32) + DIRS[k]; - let y = (j as i32) + DIRS[k + 1]; - if - x >= 0 && - (x as usize) < grid.len() && - y >= 0 && - (y as usize) < grid[0].len() && - grid[x as usize][y as usize] == '1' - { - grid[x as usize][y as usize] = '0'; - queue.push_back((x as usize, y as usize)); - } - } - } - } - - let mut grid = grid; - let mut ans = 0; - for i in 0..grid.len() { - for j in 0..grid[0].len() { - if grid[i][j] == '1' { - bfs(&mut grid, i, j); - ans += 1; - } - } - } - ans - } -} -``` - -Union find: - ```rust const DIRS: [usize; 3] = [1, 0, 1]; @@ -726,10 +731,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0201.Bitwise AND of Numbers Range/README.md b/solution/0200-0299/0201.Bitwise AND of Numbers Range/README.md index 9580882b57c45..558767e70c6ab 100644 --- a/solution/0200-0299/0201.Bitwise AND of Numbers Range/README.md +++ b/solution/0200-0299/0201.Bitwise AND of Numbers Range/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 题目可以转换为求数字的公共二进制前缀。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def rangeBitwiseAnd(self, left: int, right: int) -> int: @@ -65,10 +59,6 @@ class Solution: return right ``` -### **Java** - - - ```java class Solution { public int rangeBitwiseAnd(int left, int right) { @@ -80,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +82,6 @@ public: }; ``` -### **Go** - ```go func rangeBitwiseAnd(left int, right int) int { for left < right { @@ -105,21 +91,6 @@ func rangeBitwiseAnd(left int, right int) int { } ``` -### **C#** - -```cs -public class Solution { - public int RangeBitwiseAnd(int left, int right) { - while (left < right) { - right &= (right - 1); - } - return right; - } -} -``` - -### **JavaScript** - ```js /** * @param {number} left @@ -134,10 +105,17 @@ var rangeBitwiseAnd = function (left, right) { }; ``` -### **...** - -``` - +```cs +public class Solution { + public int RangeBitwiseAnd(int left, int right) { + while (left < right) { + right &= (right - 1); + } + return right; + } +} ``` + + diff --git a/solution/0200-0299/0201.Bitwise AND of Numbers Range/README_EN.md b/solution/0200-0299/0201.Bitwise AND of Numbers Range/README_EN.md index 28d2dad195032..31b40bace88cd 100644 --- a/solution/0200-0299/0201.Bitwise AND of Numbers Range/README_EN.md +++ b/solution/0200-0299/0201.Bitwise AND of Numbers Range/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -49,8 +49,6 @@ class Solution: return right ``` -### **Java** - ```java class Solution { public int rangeBitwiseAnd(int left, int right) { @@ -62,8 +60,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -76,8 +72,6 @@ public: }; ``` -### **Go** - ```go func rangeBitwiseAnd(left int, right int) int { for left < right { @@ -87,21 +81,6 @@ func rangeBitwiseAnd(left int, right int) int { } ``` -### **C#** - -```cs -public class Solution { - public int RangeBitwiseAnd(int left, int right) { - while (left < right) { - right &= (right - 1); - } - return right; - } -} -``` - -### **JavaScript** - ```js /** * @param {number} left @@ -116,10 +95,17 @@ var rangeBitwiseAnd = function (left, right) { }; ``` -### **...** - -``` - +```cs +public class Solution { + public int RangeBitwiseAnd(int left, int right) { + while (left < right) { + right &= (right - 1); + } + return right; + } +} ``` + + diff --git a/solution/0200-0299/0202.Happy Number/README.md b/solution/0200-0299/0202.Happy Number/README.md index f8ab414ae7b6f..2fab4bd49fee0 100644 --- a/solution/0200-0299/0202.Happy Number/README.md +++ b/solution/0200-0299/0202.Happy Number/README.md @@ -49,28 +49,14 @@ ## 解法 - - -**方法一:哈希表 + 模拟** +### 方法一:哈希表 + 模拟 将每次转换后的数字存入哈希表,如果出现重复数字,说明进入了循环,不是快乐数。否则,如果转换后的数字为 $1$,说明是快乐数。 时间复杂度 $O(\log n)$,空间复杂度 $O(\log n)$。 -**方法二:快慢指针** - -与判断链表是否存在环原理一致。如果 $n$ 是快乐数,那么快指针最终会与慢指针相遇,且相遇时的数字为 $1$;否则,快指针最终会与慢指针相遇,且相遇时的数字不为 $1$。 - -因此,最后判断快慢指针相遇时的数字是否为 $1$ 即可。 - -时间复杂度 $O(\log n)$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def isHappy(self, n: int) -> bool: @@ -85,26 +71,6 @@ class Solution: return n == 1 ``` -```python -class Solution: - def isHappy(self, n: int) -> bool: - def next(x): - y = 0 - while x: - x, v = divmod(x, 10) - y += v * v - return y - - slow, fast = n, next(n) - while slow != fast: - slow, fast = next(slow), next(next(fast)) - return slow == 1 -``` - -### **Java** - - - ```java class Solution { public boolean isHappy(int n) { @@ -123,29 +89,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isHappy(int n) { - int slow = n, fast = next(n); - while (slow != fast) { - slow = next(slow); - fast = next(next(fast)); - } - return slow == 1; - } - - private int next(int x) { - int y = 0; - for (; x > 0; x /= 10) { - y += (x % 10) * (x % 10); - } - return y; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -164,29 +107,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool isHappy(int n) { - auto next = [](int x) { - int y = 0; - for (; x; x /= 10) { - y += pow(x % 10, 2); - } - return y; - }; - int slow = n, fast = next(n); - while (slow != fast) { - slow = next(slow); - fast = next(next(fast)); - } - return slow == 1; - } -}; -``` - -### **Go** - ```go func isHappy(n int) bool { vis := map[int]bool{} @@ -202,25 +122,6 @@ func isHappy(n int) bool { } ``` -```go -func isHappy(n int) bool { - next := func(x int) (y int) { - for ; x > 0; x /= 10 { - y += (x % 10) * (x % 10) - } - return - } - slow, fast := n, next(n) - for slow != fast { - slow = next(slow) - fast = next(next(fast)) - } - return slow == 1 -} -``` - -### **TypeScript** - ```ts function isHappy(n: number): boolean { const getNext = (n: number) => { @@ -244,29 +145,6 @@ function isHappy(n: number): boolean { } ``` -```ts -function isHappy(n: number): boolean { - const getNext = (n: number) => { - let res = 0; - while (n !== 0) { - res += (n % 10) ** 2; - n = Math.floor(n / 10); - } - return res; - }; - - let slow = n; - let fast = getNext(n); - while (slow !== fast) { - slow = getNext(slow); - fast = getNext(getNext(fast)); - } - return fast === 1; -} -``` - -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -294,30 +172,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn is_happy(n: i32) -> bool { - let get_next = |mut n: i32| { - let mut res = 0; - while n != 0 { - res += (n % 10).pow(2); - n /= 10; - } - res - }; - let mut slow = n; - let mut fast = get_next(n); - while slow != fast { - slow = get_next(slow); - fast = get_next(get_next(fast)); - } - slow == 1 - } -} -``` - -### **C** - ```c int getNext(int n) { int res = 0; @@ -339,10 +193,136 @@ bool isHappy(int n) { } ``` -### **...** + + +### 方法二:快慢指针 + +与判断链表是否存在环原理一致。如果 $n$ 是快乐数,那么快指针最终会与慢指针相遇,且相遇时的数字为 $1$;否则,快指针最终会与慢指针相遇,且相遇时的数字不为 $1$。 + +因此,最后判断快慢指针相遇时的数字是否为 $1$ 即可。 + +时间复杂度 $O(\log n)$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def isHappy(self, n: int) -> bool: + def next(x): + y = 0 + while x: + x, v = divmod(x, 10) + y += v * v + return y + + slow, fast = n, next(n) + while slow != fast: + slow, fast = next(slow), next(next(fast)) + return slow == 1 +``` + +```java +class Solution { + public boolean isHappy(int n) { + int slow = n, fast = next(n); + while (slow != fast) { + slow = next(slow); + fast = next(next(fast)); + } + return slow == 1; + } + + private int next(int x) { + int y = 0; + for (; x > 0; x /= 10) { + y += (x % 10) * (x % 10); + } + return y; + } +} +``` + +```cpp +class Solution { +public: + bool isHappy(int n) { + auto next = [](int x) { + int y = 0; + for (; x; x /= 10) { + y += pow(x % 10, 2); + } + return y; + }; + int slow = n, fast = next(n); + while (slow != fast) { + slow = next(slow); + fast = next(next(fast)); + } + return slow == 1; + } +}; +``` + +```go +func isHappy(n int) bool { + next := func(x int) (y int) { + for ; x > 0; x /= 10 { + y += (x % 10) * (x % 10) + } + return + } + slow, fast := n, next(n) + for slow != fast { + slow = next(slow) + fast = next(next(fast)) + } + return slow == 1 +} +``` + +```ts +function isHappy(n: number): boolean { + const getNext = (n: number) => { + let res = 0; + while (n !== 0) { + res += (n % 10) ** 2; + n = Math.floor(n / 10); + } + return res; + }; + let slow = n; + let fast = getNext(n); + while (slow !== fast) { + slow = getNext(slow); + fast = getNext(getNext(fast)); + } + return fast === 1; +} ``` +```rust +impl Solution { + pub fn is_happy(n: i32) -> bool { + let get_next = |mut n: i32| { + let mut res = 0; + while n != 0 { + res += (n % 10).pow(2); + n /= 10; + } + res + }; + let mut slow = n; + let mut fast = get_next(n); + while slow != fast { + slow = get_next(slow); + fast = get_next(get_next(fast)); + } + slow == 1 + } +} ``` + + diff --git a/solution/0200-0299/0202.Happy Number/README_EN.md b/solution/0200-0299/0202.Happy Number/README_EN.md index 7d09853defa6a..31f7eef0885dd 100644 --- a/solution/0200-0299/0202.Happy Number/README_EN.md +++ b/solution/0200-0299/0202.Happy Number/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,24 +63,6 @@ class Solution: return n == 1 ``` -```python -class Solution: - def isHappy(self, n: int) -> bool: - def next(x): - y = 0 - while x: - x, v = divmod(x, 10) - y += v * v - return y - - slow, fast = n, next(n) - while slow != fast: - slow, fast = next(slow), next(next(fast)) - return slow == 1 -``` - -### **Java** - ```java class Solution { public boolean isHappy(int n) { @@ -99,29 +81,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isHappy(int n) { - int slow = n, fast = next(n); - while (slow != fast) { - slow = next(slow); - fast = next(next(fast)); - } - return slow == 1; - } - - private int next(int x) { - int y = 0; - for (; x > 0; x /= 10) { - y += (x % 10) * (x % 10); - } - return y; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -140,29 +99,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool isHappy(int n) { - auto next = [](int x) { - int y = 0; - for (; x; x /= 10) { - y += pow(x % 10, 2); - } - return y; - }; - int slow = n, fast = next(n); - while (slow != fast) { - slow = next(slow); - fast = next(next(fast)); - } - return slow == 1; - } -}; -``` - -### **Go** - ```go func isHappy(n int) bool { vis := map[int]bool{} @@ -178,25 +114,6 @@ func isHappy(n int) bool { } ``` -```go -func isHappy(n int) bool { - next := func(x int) (y int) { - for ; x > 0; x /= 10 { - y += (x % 10) * (x % 10) - } - return - } - slow, fast := n, next(n) - for slow != fast { - slow = next(slow) - fast = next(next(fast)) - } - return slow == 1 -} -``` - -### **TypeScript** - ```ts function isHappy(n: number): boolean { const getNext = (n: number) => { @@ -220,29 +137,6 @@ function isHappy(n: number): boolean { } ``` -```ts -function isHappy(n: number): boolean { - const getNext = (n: number) => { - let res = 0; - while (n !== 0) { - res += (n % 10) ** 2; - n = Math.floor(n / 10); - } - return res; - }; - - let slow = n; - let fast = getNext(n); - while (slow !== fast) { - slow = getNext(slow); - fast = getNext(getNext(fast)); - } - return fast === 1; -} -``` - -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -270,30 +164,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn is_happy(n: i32) -> bool { - let get_next = |mut n: i32| { - let mut res = 0; - while n != 0 { - res += (n % 10).pow(2); - n /= 10; - } - res - }; - let mut slow = n; - let mut fast = get_next(n); - while slow != fast { - slow = get_next(slow); - fast = get_next(get_next(fast)); - } - slow == 1 - } -} -``` - -### **C** - ```c int getNext(int n) { int res = 0; @@ -315,10 +185,130 @@ bool isHappy(int n) { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def isHappy(self, n: int) -> bool: + def next(x): + y = 0 + while x: + x, v = divmod(x, 10) + y += v * v + return y + + slow, fast = n, next(n) + while slow != fast: + slow, fast = next(slow), next(next(fast)) + return slow == 1 +``` + +```java +class Solution { + public boolean isHappy(int n) { + int slow = n, fast = next(n); + while (slow != fast) { + slow = next(slow); + fast = next(next(fast)); + } + return slow == 1; + } + + private int next(int x) { + int y = 0; + for (; x > 0; x /= 10) { + y += (x % 10) * (x % 10); + } + return y; + } +} +``` + +```cpp +class Solution { +public: + bool isHappy(int n) { + auto next = [](int x) { + int y = 0; + for (; x; x /= 10) { + y += pow(x % 10, 2); + } + return y; + }; + int slow = n, fast = next(n); + while (slow != fast) { + slow = next(slow); + fast = next(next(fast)); + } + return slow == 1; + } +}; +``` + +```go +func isHappy(n int) bool { + next := func(x int) (y int) { + for ; x > 0; x /= 10 { + y += (x % 10) * (x % 10) + } + return + } + slow, fast := n, next(n) + for slow != fast { + slow = next(slow) + fast = next(next(fast)) + } + return slow == 1 +} +``` + +```ts +function isHappy(n: number): boolean { + const getNext = (n: number) => { + let res = 0; + while (n !== 0) { + res += (n % 10) ** 2; + n = Math.floor(n / 10); + } + return res; + }; + let slow = n; + let fast = getNext(n); + while (slow !== fast) { + slow = getNext(slow); + fast = getNext(getNext(fast)); + } + return fast === 1; +} ``` +```rust +impl Solution { + pub fn is_happy(n: i32) -> bool { + let get_next = |mut n: i32| { + let mut res = 0; + while n != 0 { + res += (n % 10).pow(2); + n /= 10; + } + res + }; + let mut slow = n; + let mut fast = get_next(n); + while slow != fast { + slow = get_next(slow); + fast = get_next(get_next(fast)); + } + slow == 1 + } +} ``` + + diff --git a/solution/0200-0299/0203.Remove Linked List Elements/README.md b/solution/0200-0299/0203.Remove Linked List Elements/README.md index 34d95c7870f18..ce439426bdd14 100644 --- a/solution/0200-0299/0203.Remove Linked List Elements/README.md +++ b/solution/0200-0299/0203.Remove Linked List Elements/README.md @@ -43,14 +43,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -69,10 +65,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -99,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,38 +110,6 @@ public: }; ``` -### **C#** - -```cs -public class Solution { - public ListNode RemoveElements(ListNode head, int val) { - ListNode newHead = null; - ListNode newTail = null; - var current = head; - while (current != null) - { - if (current.val != val) - { - if (newHead == null) - { - newHead = newTail = current; - } - else - { - newTail.next = current; - newTail = current; - } - } - current = current.next; - } - if (newTail != null) newTail.next = null; - return newHead; - } -} -``` - -### **Go** - ```go func removeElements(head *ListNode, val int) *ListNode { dummy := new(ListNode) @@ -168,8 +126,6 @@ func removeElements(head *ListNode, val int) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -197,8 +153,6 @@ function removeElements(head: ListNode | null, val: number): ListNode | null { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -233,10 +187,34 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public ListNode RemoveElements(ListNode head, int val) { + ListNode newHead = null; + ListNode newTail = null; + var current = head; + while (current != null) + { + if (current.val != val) + { + if (newHead == null) + { + newHead = newTail = current; + } + else + { + newTail.next = current; + newTail = current; + } + } + current = current.next; + } + if (newTail != null) newTail.next = null; + return newHead; + } +} ``` + + diff --git a/solution/0200-0299/0203.Remove Linked List Elements/README_EN.md b/solution/0200-0299/0203.Remove Linked List Elements/README_EN.md index f9fc2ca01b018..180ffa065aad0 100644 --- a/solution/0200-0299/0203.Remove Linked List Elements/README_EN.md +++ b/solution/0200-0299/0203.Remove Linked List Elements/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -61,8 +61,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,38 +106,6 @@ public: }; ``` -### **C#** - -```cs -public class Solution { - public ListNode RemoveElements(ListNode head, int val) { - ListNode newHead = null; - ListNode newTail = null; - var current = head; - while (current != null) - { - if (current.val != val) - { - if (newHead == null) - { - newHead = newTail = current; - } - else - { - newTail.next = current; - newTail = current; - } - } - current = current.next; - } - if (newTail != null) newTail.next = null; - return newHead; - } -} -``` - -### **Go** - ```go func removeElements(head *ListNode, val int) *ListNode { dummy := new(ListNode) @@ -158,8 +122,6 @@ func removeElements(head *ListNode, val int) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -187,8 +149,6 @@ function removeElements(head: ListNode | null, val: number): ListNode | null { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -223,10 +183,34 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public ListNode RemoveElements(ListNode head, int val) { + ListNode newHead = null; + ListNode newTail = null; + var current = head; + while (current != null) + { + if (current.val != val) + { + if (newHead == null) + { + newHead = newTail = current; + } + else + { + newTail.next = current; + newTail = current; + } + } + current = current.next; + } + if (newTail != null) newTail.next = null; + return newHead; + } +} ``` + + diff --git a/solution/0200-0299/0204.Count Primes/README.md b/solution/0200-0299/0204.Count Primes/README.md index b9dceb5902f89..ecba228589727 100644 --- a/solution/0200-0299/0204.Count Primes/README.md +++ b/solution/0200-0299/0204.Count Primes/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:埃氏筛** +### 方法一:埃氏筛 如果 $x$ 是质数,那么大于 $x$ 的 $x$ 的倍数 $2x$,$3x$,… 一定不是质数,因此我们可以从这里入手。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def countPrimes(self, n: int) -> int: @@ -73,10 +67,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countPrimes(int n) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func countPrimes(n int) int { primes := make([]bool, n) @@ -136,8 +122,6 @@ func countPrimes(n int) int { } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -158,8 +142,6 @@ var countPrimes = function (n) { }; ``` -### **C#** - ```cs public class Solution { public int CountPrimes(int n) { @@ -181,10 +163,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0204.Count Primes/README_EN.md b/solution/0200-0299/0204.Count Primes/README_EN.md index 3c8f454d79fd7..93c53339de12c 100644 --- a/solution/0200-0299/0204.Count Primes/README_EN.md +++ b/solution/0200-0299/0204.Count Primes/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countPrimes(int n) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +91,6 @@ public: }; ``` -### **Go** - ```go func countPrimes(n int) int { primes := make([]bool, n) @@ -116,8 +110,6 @@ func countPrimes(n int) int { } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -138,8 +130,6 @@ var countPrimes = function (n) { }; ``` -### **C#** - ```cs public class Solution { public int CountPrimes(int n) { @@ -161,10 +151,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0205.Isomorphic Strings/README.md b/solution/0200-0299/0205.Isomorphic Strings/README.md index 6d66cc48b97bd..9226e6538d74b 100644 --- a/solution/0200-0299/0205.Isomorphic Strings/README.md +++ b/solution/0200-0299/0205.Isomorphic Strings/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:哈希表或数组** +### 方法一:哈希表或数组 我们可以用两个哈希表或数组 $d_1$ 和 $d_2$ 记录 $s$ 和 $t$ 中字符的映射关系。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def isIsomorphic(self, s: str, t: str) -> bool: @@ -76,22 +70,6 @@ class Solution: return True ``` -```python -class Solution: - def isIsomorphic(self, s: str, t: str) -> bool: - d1, d2 = [0] * 256, [0] * 256 - for i, (a, b) in enumerate(zip(s, t), 1): - a, b = ord(a), ord(b) - if d1[a] != d2[b]: - return False - d1[a] = d2[b] = i - return True -``` - -### **Java** - - - ```java class Solution { public boolean isIsomorphic(String s, String t) { @@ -114,27 +92,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isIsomorphic(String s, String t) { - int[] d1 = new int[256]; - int[] d2 = new int[256]; - int n = s.length(); - for (int i = 0; i < n; ++i) { - char a = s.charAt(i), b = t.charAt(i); - if (d1[a] != d2[b]) { - return false; - } - d1[a] = i + 1; - d2[b] = i + 1; - } - return true; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -154,8 +111,6 @@ public: }; ``` -### **Go** - ```go func isIsomorphic(s string, t string) bool { d1 := [256]int{} @@ -171,29 +126,6 @@ func isIsomorphic(s string, t string) bool { } ``` -### **C#** - -```cs -public class Solution { - public bool IsIsomorphic(string s, string t) { - int[] d1 = new int[256]; - int[] d2 = new int[256]; - for (int i = 0; i < s.Length; ++i) { - var a = s[i]; - var b = t[i]; - if (d1[a] != d2[b]) { - return false; - } - d1[a] = i + 1; - d2[b] = i + 1; - } - return true; - } -} -``` - -### **TypeScript** - ```ts function isIsomorphic(s: string, t: string): boolean { const d1: number[] = new Array(256).fill(0); @@ -211,8 +143,6 @@ function isIsomorphic(s: string, t: string): boolean { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -237,10 +167,62 @@ impl Solution { } ``` -### **...** +```cs +public class Solution { + public bool IsIsomorphic(string s, string t) { + int[] d1 = new int[256]; + int[] d2 = new int[256]; + for (int i = 0; i < s.Length; ++i) { + var a = s[i]; + var b = t[i]; + if (d1[a] != d2[b]) { + return false; + } + d1[a] = i + 1; + d2[b] = i + 1; + } + return true; + } +} +``` + + + +### 方法二 + + +```python +class Solution: + def isIsomorphic(self, s: str, t: str) -> bool: + d1, d2 = [0] * 256, [0] * 256 + for i, (a, b) in enumerate(zip(s, t), 1): + a, b = ord(a), ord(b) + if d1[a] != d2[b]: + return False + d1[a] = d2[b] = i + return True ``` +```java +class Solution { + public boolean isIsomorphic(String s, String t) { + int[] d1 = new int[256]; + int[] d2 = new int[256]; + int n = s.length(); + for (int i = 0; i < n; ++i) { + char a = s.charAt(i), b = t.charAt(i); + if (d1[a] != d2[b]) { + return false; + } + d1[a] = i + 1; + d2[b] = i + 1; + } + return true; + } +} ``` + + diff --git a/solution/0200-0299/0205.Isomorphic Strings/README_EN.md b/solution/0200-0299/0205.Isomorphic Strings/README_EN.md index 4b9d2d99dfedf..dbde0abbc2944 100644 --- a/solution/0200-0299/0205.Isomorphic Strings/README_EN.md +++ b/solution/0200-0299/0205.Isomorphic Strings/README_EN.md @@ -32,7 +32,7 @@ ## Solutions -**Solution 1: Hash Table or Array** +### Solution 1: Hash Table or Array We can use two hash tables or arrays $d_1$ and $d_2$ to record the character mapping relationship between $s$ and $t$. @@ -42,8 +42,6 @@ The time complexity is $O(n)$ and the space complexity is $O(C)$. Where $n$ is t -### **Python3** - ```python class Solution: def isIsomorphic(self, s: str, t: str) -> bool: @@ -57,20 +55,6 @@ class Solution: return True ``` -```python -class Solution: - def isIsomorphic(self, s: str, t: str) -> bool: - d1, d2 = [0] * 256, [0] * 256 - for i, (a, b) in enumerate(zip(s, t), 1): - a, b = ord(a), ord(b) - if d1[a] != d2[b]: - return False - d1[a] = d2[b] = i - return True -``` - -### **Java** - ```java class Solution { public boolean isIsomorphic(String s, String t) { @@ -93,27 +77,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isIsomorphic(String s, String t) { - int[] d1 = new int[256]; - int[] d2 = new int[256]; - int n = s.length(); - for (int i = 0; i < n; ++i) { - char a = s.charAt(i), b = t.charAt(i); - if (d1[a] != d2[b]) { - return false; - } - d1[a] = i + 1; - d2[b] = i + 1; - } - return true; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -133,8 +96,6 @@ public: }; ``` -### **Go** - ```go func isIsomorphic(s string, t string) bool { d1 := [256]int{} @@ -150,29 +111,6 @@ func isIsomorphic(s string, t string) bool { } ``` -### **C#** - -```cs -public class Solution { - public bool IsIsomorphic(string s, string t) { - int[] d1 = new int[256]; - int[] d2 = new int[256]; - for (int i = 0; i < s.Length; ++i) { - var a = s[i]; - var b = t[i]; - if (d1[a] != d2[b]) { - return false; - } - d1[a] = i + 1; - d2[b] = i + 1; - } - return true; - } -} -``` - -### **TypeScript** - ```ts function isIsomorphic(s: string, t: string): boolean { const d1: number[] = new Array(256).fill(0); @@ -190,8 +128,6 @@ function isIsomorphic(s: string, t: string): boolean { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -216,10 +152,62 @@ impl Solution { } ``` -### **...** +```cs +public class Solution { + public bool IsIsomorphic(string s, string t) { + int[] d1 = new int[256]; + int[] d2 = new int[256]; + for (int i = 0; i < s.Length; ++i) { + var a = s[i]; + var b = t[i]; + if (d1[a] != d2[b]) { + return false; + } + d1[a] = i + 1; + d2[b] = i + 1; + } + return true; + } +} +``` + + +### Solution 2 + + + +```python +class Solution: + def isIsomorphic(self, s: str, t: str) -> bool: + d1, d2 = [0] * 256, [0] * 256 + for i, (a, b) in enumerate(zip(s, t), 1): + a, b = ord(a), ord(b) + if d1[a] != d2[b]: + return False + d1[a] = d2[b] = i + return True ``` +```java +class Solution { + public boolean isIsomorphic(String s, String t) { + int[] d1 = new int[256]; + int[] d2 = new int[256]; + int n = s.length(); + for (int i = 0; i < n; ++i) { + char a = s.charAt(i), b = t.charAt(i); + if (d1[a] != d2[b]) { + return false; + } + d1[a] = i + 1; + d2[b] = i + 1; + } + return true; + } +} ``` + + diff --git a/solution/0200-0299/0206.Reverse Linked List/README.md b/solution/0200-0299/0206.Reverse Linked List/README.md index 2ccd5d6103901..bd447279d6079 100644 --- a/solution/0200-0299/0206.Reverse Linked List/README.md +++ b/solution/0200-0299/0206.Reverse Linked List/README.md @@ -50,22 +50,14 @@ ## 解法 -**方法一:头插法** +### 方法一:头插法 创建虚拟头节点 $dummy$,遍历链表,将每个节点依次插入 $dummy$ 的下一个节点。遍历结束,返回 $dummy.next$。 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为链表的长度。 -**方法二:递归** - -递归反转链表的第二个节点到尾部的所有节点,然后 $head$ 插在反转后的链表的尾部。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为链表的长度。 - -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -84,26 +76,6 @@ class Solution: return dummy.next ``` -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def reverseList(self, head: ListNode) -> ListNode: - if head is None or head.next is None: - return head - ans = self.reverseList(head.next) - head.next.next = head - head.next = None - return ans -``` - -### **Java** - -迭代版本: - ```java /** * Definition for singly-linked list. @@ -130,61 +102,33 @@ class Solution { } ``` -递归版本: - -```java +```cpp /** * Definition for singly-linked list. - * public class ListNode { + * struct ListNode { * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; */ class Solution { - public ListNode reverseList(ListNode head) { - if (head == null || head.next == null) { - return head; +public: + ListNode* reverseList(ListNode* head) { + ListNode* dummy = new ListNode(); + ListNode* curr = head; + while (curr) { + ListNode* next = curr->next; + curr->next = dummy->next; + dummy->next = curr; + curr = next; } - ListNode ans = reverseList(head.next); - head.next.next = head; - head.next = null; - return ans; - } -} -``` - -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @return {ListNode} - */ -var reverseList = function (head) { - let dummy = new ListNode(); - let curr = head; - while (curr) { - let next = curr.next; - curr.next = dummy.next; - dummy.next = curr; - curr = next; + return dummy->next; } - return dummy.next; }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -206,79 +150,90 @@ func reverseList(head *ListNode) *ListNode { } ``` -```go +```ts /** * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode + * 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) + * } * } */ -func reverseList(head *ListNode) *ListNode { - if head == nil || head.Next == nil { - return head - } - ans := reverseList(head.Next) - head.Next.Next = head - head.Next = nil - return ans + +function reverseList(head: ListNode | null): ListNode | null { + if (head == null) { + return head; + } + let pre = null; + let cur = head; + while (cur != null) { + const next = cur.next; + cur.next = pre; + [pre, cur] = [cur, next]; + } + return pre; } ``` -### **C++** - -```cpp -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* reverseList(ListNode* head) { - ListNode* dummy = new ListNode(); - ListNode* curr = head; - while (curr) { - ListNode* next = curr->next; - curr->next = dummy->next; - dummy->next = curr; - curr = next; +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn reverse_list(head: Option>) -> Option> { + let mut head = head; + let mut pre = None; + while let Some(mut node) = head { + head = node.next.take(); + node.next = pre.take(); + pre = Some(node); } - return dummy->next; + pre } -}; +} ``` -```cpp +```js /** * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } */ -class Solution { -public: - ListNode* reverseList(ListNode* head) { - if (!head || !head->next) return head; - ListNode* ans = reverseList(head->next); - head->next->next = head; - head->next = nullptr; - return ans; +/** + * @param {ListNode} head + * @return {ListNode} + */ +var reverseList = function (head) { + let dummy = new ListNode(); + let curr = head; + while (curr) { + let next = curr.next; + curr.next = dummy.next; + dummy.next = curr; + curr = next; } + return dummy.next; }; ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -306,39 +261,97 @@ public class Solution { } ``` -### **TypeScript** + -循环: +### 方法二:递归 -```ts +递归反转链表的第二个节点到尾部的所有节点,然后 $head$ 插在反转后的链表的尾部。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为链表的长度。 + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + if head is None or head.next is None: + return head + ans = self.reverseList(head.next) + head.next.next = head + head.next = None + return ans +``` + +```java /** * 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) - * } + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ - -function reverseList(head: ListNode | null): ListNode | null { - if (head == null) { - return head; - } - let pre = null; - let cur = head; - while (cur != null) { - const next = cur.next; - cur.next = pre; - [pre, cur] = [cur, next]; +class Solution { + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode ans = reverseList(head.next); + head.next.next = head; + head.next = null; + return ans; } - return pre; } ``` -递归: +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + if (!head || !head->next) return head; + ListNode* ans = reverseList(head->next); + head->next->next = head; + head->next = nullptr; + return ans; + } +}; +``` + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseList(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + ans := reverseList(head.Next) + head.Next.Next = head + head.Next = nil + return ans +} +``` ```ts /** @@ -371,43 +384,6 @@ function reverseList(head: ListNode | null): ListNode | null { } ``` -### **Rust** - -循环: - -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn reverse_list(head: Option>) -> Option> { - let mut head = head; - let mut pre = None; - while let Some(mut node) = head { - head = node.next.take(); - node.next = pre.take(); - pre = Some(node); - } - pre - } -} -``` - -递归: - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -443,10 +419,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0206.Reverse Linked List/README_EN.md b/solution/0200-0299/0206.Reverse Linked List/README_EN.md index 8a920cf47b153..b22be76a5fc97 100644 --- a/solution/0200-0299/0206.Reverse Linked List/README_EN.md +++ b/solution/0200-0299/0206.Reverse Linked List/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -63,26 +63,6 @@ class Solution: return dummy.next ``` -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def reverseList(self, head: ListNode) -> ListNode: - if head is None or head.next is None: - return head - ans = self.reverseList(head.next) - head.next.next = head - head.next = None - return ans -``` - -### **Java** - -Iterative version: - ```java /** * Definition for singly-linked list. @@ -109,61 +89,33 @@ class Solution { } ``` -Recursive version: - -```java +```cpp /** * Definition for singly-linked list. - * public class ListNode { + * struct ListNode { * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; */ class Solution { - public ListNode reverseList(ListNode head) { - if (head == null || head.next == null) { - return head; +public: + ListNode* reverseList(ListNode* head) { + ListNode* dummy = new ListNode(); + ListNode* curr = head; + while (curr) { + ListNode* next = curr->next; + curr->next = dummy->next; + dummy->next = curr; + curr = next; } - ListNode ans = reverseList(head.next); - head.next.next = head; - head.next = null; - return ans; - } -} -``` - -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @return {ListNode} - */ -var reverseList = function (head) { - let dummy = new ListNode(); - let curr = head; - while (curr) { - let next = curr.next; - curr.next = dummy.next; - dummy.next = curr; - curr = next; + return dummy->next; } - return dummy.next; }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -185,79 +137,90 @@ func reverseList(head *ListNode) *ListNode { } ``` -```go +```ts /** * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode + * 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) + * } * } */ -func reverseList(head *ListNode) *ListNode { - if head == nil || head.Next == nil { - return head - } - ans := reverseList(head.Next) - head.Next.Next = head - head.Next = nil - return ans + +function reverseList(head: ListNode | null): ListNode | null { + if (head == null) { + return head; + } + let pre = null; + let cur = head; + while (cur != null) { + const next = cur.next; + cur.next = pre; + [pre, cur] = [cur, next]; + } + return pre; } ``` -### **C++** - -```cpp -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* reverseList(ListNode* head) { - ListNode* dummy = new ListNode(); - ListNode* curr = head; - while (curr) { - ListNode* next = curr->next; - curr->next = dummy->next; - dummy->next = curr; - curr = next; +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn reverse_list(head: Option>) -> Option> { + let mut head = head; + let mut pre = None; + while let Some(mut node) = head { + head = node.next.take(); + node.next = pre.take(); + pre = Some(node); } - return dummy->next; + pre } -}; +} ``` -```cpp +```js /** * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } */ -class Solution { -public: - ListNode* reverseList(ListNode* head) { - if (!head || !head->next) return head; - ListNode* ans = reverseList(head->next); - head->next->next = head; - head->next = nullptr; - return ans; +/** + * @param {ListNode} head + * @return {ListNode} + */ +var reverseList = function (head) { + let dummy = new ListNode(); + let curr = head; + while (curr) { + let next = curr.next; + curr.next = dummy.next; + dummy.next = curr; + curr = next; } + return dummy.next; }; ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -285,39 +248,93 @@ public class Solution { } ``` -### **TypeScript** + -Loop: +### Solution 2 -```ts + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + if head is None or head.next is None: + return head + ans = self.reverseList(head.next) + head.next.next = head + head.next = None + return ans +``` + +```java /** * 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) - * } + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ - -function reverseList(head: ListNode | null): ListNode | null { - if (head == null) { - return head; - } - let pre = null; - let cur = head; - while (cur != null) { - const next = cur.next; - cur.next = pre; - [pre, cur] = [cur, next]; +class Solution { + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode ans = reverseList(head.next); + head.next.next = head; + head.next = null; + return ans; } - return pre; } ``` -Recursion: +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + if (!head || !head->next) return head; + ListNode* ans = reverseList(head->next); + head->next->next = head; + head->next = nullptr; + return ans; + } +}; +``` + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseList(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + ans := reverseList(head.Next) + head.Next.Next = head + head.Next = nil + return ans +} +``` ```ts /** @@ -350,43 +367,6 @@ function reverseList(head: ListNode | null): ListNode | null { } ``` -### **Rust** - -Loop: - -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn reverse_list(head: Option>) -> Option> { - let mut head = head; - let mut pre = None; - while let Some(mut node) = head { - head = node.next.take(); - node.next = pre.take(); - pre = Some(node); - } - pre - } -} -``` - -Recursion: - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -422,10 +402,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0207.Course Schedule/README.md b/solution/0200-0299/0207.Course Schedule/README.md index 090864c87811f..8ae73f3e5d994 100644 --- a/solution/0200-0299/0207.Course Schedule/README.md +++ b/solution/0200-0299/0207.Course Schedule/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:拓扑排序** +### 方法一:拓扑排序 对于本题,我们可以将课程看作图中的节点,先修课程看作图中的边,那么我们可以将本题转化为判断有向图中是否存在环。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: @@ -84,10 +78,6 @@ class Solution: return cnt == numCourses ``` -### **Java** - - - ```java class Solution { public boolean canFinish(int numCourses, int[][] prerequisites) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,60 +143,6 @@ public: }; ``` -### **Rust** - -```rust -use std::collections::VecDeque; - -impl Solution { - #[allow(dead_code)] - pub fn can_finish(num_course: i32, prerequisites: Vec>) -> bool { - let num_course = num_course as usize; - // The graph representation - let mut graph: Vec> = vec![vec![]; num_course]; - // Record the in degree for each node - let mut in_degree_vec: Vec = vec![0; num_course]; - let mut q: VecDeque = VecDeque::new(); - let mut count = 0; - - // Initialize the graph & in degree vector - for p in &prerequisites { - let (from, to) = (p[0], p[1]); - graph[from as usize].push(to); - in_degree_vec[to as usize] += 1; - } - - // Enqueue the first batch of nodes with in degree 0 - for i in 0..num_course { - if in_degree_vec[i] == 0 { - q.push_back(i); - } - } - - // Begin the traverse & update through the graph - while !q.is_empty() { - // Get the current node index - let index = q.front().unwrap().clone(); - // This course can be finished - count += 1; - q.pop_front(); - for i in &graph[index] { - // Update the in degree for the current node - in_degree_vec[*i as usize] -= 1; - // See if can be enqueued - if in_degree_vec[*i as usize] == 0 { - q.push_back(*i as usize); - } - } - } - - count == num_course - } -} -``` - -### **Go** - ```go func canFinish(numCourses int, prerequisites [][]int) bool { g := make([][]int, numCourses) @@ -240,8 +174,6 @@ func canFinish(numCourses int, prerequisites [][]int) bool { } ``` -### **TypeScript** - ```ts function canFinish(numCourses: number, prerequisites: number[][]): boolean { const g: number[][] = new Array(numCourses).fill(0).map(() => []); @@ -270,7 +202,55 @@ function canFinish(numCourses: number, prerequisites: number[][]): boolean { } ``` -### **C#** +```rust +use std::collections::VecDeque; + +impl Solution { + #[allow(dead_code)] + pub fn can_finish(num_course: i32, prerequisites: Vec>) -> bool { + let num_course = num_course as usize; + // The graph representation + let mut graph: Vec> = vec![vec![]; num_course]; + // Record the in degree for each node + let mut in_degree_vec: Vec = vec![0; num_course]; + let mut q: VecDeque = VecDeque::new(); + let mut count = 0; + + // Initialize the graph & in degree vector + for p in &prerequisites { + let (from, to) = (p[0], p[1]); + graph[from as usize].push(to); + in_degree_vec[to as usize] += 1; + } + + // Enqueue the first batch of nodes with in degree 0 + for i in 0..num_course { + if in_degree_vec[i] == 0 { + q.push_back(i); + } + } + + // Begin the traverse & update through the graph + while !q.is_empty() { + // Get the current node index + let index = q.front().unwrap().clone(); + // This course can be finished + count += 1; + q.pop_front(); + for i in &graph[index] { + // Update the in degree for the current node + in_degree_vec[*i as usize] -= 1; + // See if can be enqueued + if in_degree_vec[*i as usize] == 0 { + q.push_back(*i as usize); + } + } + } + + count == num_course + } +} +``` ```cs public class Solution { @@ -306,10 +286,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0207.Course Schedule/README_EN.md b/solution/0200-0299/0207.Course Schedule/README_EN.md index b01b1c0ded1e6..4918686d75be7 100644 --- a/solution/0200-0299/0207.Course Schedule/README_EN.md +++ b/solution/0200-0299/0207.Course Schedule/README_EN.md @@ -44,7 +44,7 @@ To take course 1 you should have finished course 0, and to take course 0 you sho ## Solutions -**Solution 1: Topological Sorting** +### Solution 1: Topological Sorting For this problem, we can consider the courses as nodes in a graph, and prerequisites as edges in the graph. Thus, we can transform this problem into determining whether there is a cycle in the directed graph. @@ -56,8 +56,6 @@ The time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, -### **Python3** - ```python class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: @@ -78,8 +76,6 @@ class Solution: return cnt == numCourses ``` -### **Java** - ```java class Solution { public boolean canFinish(int numCourses, int[][] prerequisites) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,60 +141,6 @@ public: }; ``` -### **Rust** - -```rust -use std::collections::VecDeque; - -impl Solution { - #[allow(dead_code)] - pub fn can_finish(num_course: i32, prerequisites: Vec>) -> bool { - let num_course = num_course as usize; - // The graph representation - let mut graph: Vec> = vec![vec![]; num_course]; - // Record the in degree for each node - let mut in_degree_vec: Vec = vec![0; num_course]; - let mut q: VecDeque = VecDeque::new(); - let mut count = 0; - - // Initialize the graph & in degree vector - for p in &prerequisites { - let (from, to) = (p[0], p[1]); - graph[from as usize].push(to); - in_degree_vec[to as usize] += 1; - } - - // Enqueue the first batch of nodes with in degree 0 - for i in 0..num_course { - if in_degree_vec[i] == 0 { - q.push_back(i); - } - } - - // Begin the traverse & update through the graph - while !q.is_empty() { - // Get the current node index - let index = q.front().unwrap().clone(); - // This course can be finished - count += 1; - q.pop_front(); - for i in &graph[index] { - // Update the in degree for the current node - in_degree_vec[*i as usize] -= 1; - // See if can be enqueued - if in_degree_vec[*i as usize] == 0 { - q.push_back(*i as usize); - } - } - } - - count == num_course - } -} -``` - -### **Go** - ```go func canFinish(numCourses int, prerequisites [][]int) bool { g := make([][]int, numCourses) @@ -232,8 +172,6 @@ func canFinish(numCourses int, prerequisites [][]int) bool { } ``` -### **TypeScript** - ```ts function canFinish(numCourses: number, prerequisites: number[][]): boolean { const g: number[][] = new Array(numCourses).fill(0).map(() => []); @@ -262,7 +200,55 @@ function canFinish(numCourses: number, prerequisites: number[][]): boolean { } ``` -### **C#** +```rust +use std::collections::VecDeque; + +impl Solution { + #[allow(dead_code)] + pub fn can_finish(num_course: i32, prerequisites: Vec>) -> bool { + let num_course = num_course as usize; + // The graph representation + let mut graph: Vec> = vec![vec![]; num_course]; + // Record the in degree for each node + let mut in_degree_vec: Vec = vec![0; num_course]; + let mut q: VecDeque = VecDeque::new(); + let mut count = 0; + + // Initialize the graph & in degree vector + for p in &prerequisites { + let (from, to) = (p[0], p[1]); + graph[from as usize].push(to); + in_degree_vec[to as usize] += 1; + } + + // Enqueue the first batch of nodes with in degree 0 + for i in 0..num_course { + if in_degree_vec[i] == 0 { + q.push_back(i); + } + } + + // Begin the traverse & update through the graph + while !q.is_empty() { + // Get the current node index + let index = q.front().unwrap().clone(); + // This course can be finished + count += 1; + q.pop_front(); + for i in &graph[index] { + // Update the in degree for the current node + in_degree_vec[*i as usize] -= 1; + // See if can be enqueued + if in_degree_vec[*i as usize] == 0 { + q.push_back(*i as usize); + } + } + } + + count == num_course + } +} +``` ```cs public class Solution { @@ -298,10 +284,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0208.Implement Trie (Prefix Tree)/README.md b/solution/0200-0299/0208.Implement Trie (Prefix Tree)/README.md index 7b58728078fb8..004f91071348e 100644 --- a/solution/0200-0299/0208.Implement Trie (Prefix Tree)/README.md +++ b/solution/0200-0299/0208.Implement Trie (Prefix Tree)/README.md @@ -50,9 +50,7 @@ trie.search("app"); // 返回 True ## 解法 - - -**方法一:前缀树** +### 方法一:前缀树 前缀树每个节点包括两部分: @@ -81,10 +79,6 @@ trie.search("app"); // 返回 True -### **Python3** - - - ```python class Trie: def __init__(self): @@ -125,10 +119,6 @@ class Trie: # param_3 = obj.startsWith(prefix) ``` -### **Java** - - - ```java class Trie { private Trie[] children; @@ -182,71 +172,6 @@ class Trie { */ ``` -### **JavaScript** - -```js -/** - * Initialize your data structure here. - */ -var Trie = function () { - this.children = {}; -}; - -/** - * Inserts a word into the trie. - * @param {string} word - * @return {void} - */ -Trie.prototype.insert = function (word) { - let node = this.children; - for (let char of word) { - if (!node[char]) { - node[char] = {}; - } - node = node[char]; - } - node.isEnd = true; -}; - -/** - * Returns if the word is in the trie. - * @param {string} word - * @return {boolean} - */ -Trie.prototype.search = function (word) { - let node = this.searchPrefix(word); - return node != undefined && node.isEnd != undefined; -}; - -Trie.prototype.searchPrefix = function (prefix) { - let node = this.children; - for (let char of prefix) { - if (!node[char]) return false; - node = node[char]; - } - return node; -}; - -/** - * Returns if there is any word in the trie that starts with the given prefix. - * @param {string} prefix - * @return {boolean} - */ -Trie.prototype.startsWith = function (prefix) { - return this.searchPrefix(prefix); -}; - -/** - * Your Trie object will be instantiated and called as such: - * var obj = new Trie() - * obj.insert(word) - * var param_2 = obj.search(word) - * var param_3 = obj.startsWith(prefix) - */ -``` - -### **C++** - ```cpp class Trie { private: @@ -298,7 +223,107 @@ public: */ ``` -### **Rust** +```go +type Trie struct { + children [26]*Trie + isEnd bool +} + +func Constructor() Trie { + return Trie{} +} + +func (this *Trie) Insert(word string) { + node := this + for _, c := range word { + idx := c - 'a' + if node.children[idx] == nil { + node.children[idx] = &Trie{} + } + node = node.children[idx] + } + node.isEnd = true +} + +func (this *Trie) Search(word string) bool { + node := this.SearchPrefix(word) + return node != nil && node.isEnd +} + +func (this *Trie) StartsWith(prefix string) bool { + node := this.SearchPrefix(prefix) + return node != nil +} + +func (this *Trie) SearchPrefix(s string) *Trie { + node := this + for _, c := range s { + idx := c - 'a' + if node.children[idx] == nil { + return nil + } + node = node.children[idx] + } + return node +} + +/** + * Your Trie object will be instantiated and called as such: + * obj := Constructor(); + * obj.Insert(word); + * param_2 := obj.Search(word); + * param_3 := obj.StartsWith(prefix); + */ +``` + +```ts +class TrieNode { + children; + isEnd; + constructor() { + this.children = new Array(26); + this.isEnd = false; + } +} + +class Trie { + root; + constructor() { + this.root = new TrieNode(); + } + + insert(word: string): void { + let head = this.root; + for (let char of word) { + let index = char.charCodeAt(0) - 97; + if (!head.children[index]) { + head.children[index] = new TrieNode(); + } + head = head.children[index]; + } + head.isEnd = true; + } + + search(word: string): boolean { + let head = this.searchPrefix(word); + return head != null && head.isEnd; + } + + startsWith(prefix: string): boolean { + return this.searchPrefix(prefix) != null; + } + + private searchPrefix(prefix: string) { + let head = this.root; + for (let char of prefix) { + let index = char.charCodeAt(0) - 97; + if (!head.children[index]) return null; + head = head.children[index]; + } + return head; + } +} +``` ```rust use std::{ rc::Rc, cell::RefCell, collections::HashMap }; @@ -394,63 +419,67 @@ impl Trie { } ``` -### **Go** - -```go -type Trie struct { - children [26]*Trie - isEnd bool -} - -func Constructor() Trie { - return Trie{} -} +```js +/** + * Initialize your data structure here. + */ +var Trie = function () { + this.children = {}; +}; -func (this *Trie) Insert(word string) { - node := this - for _, c := range word { - idx := c - 'a' - if node.children[idx] == nil { - node.children[idx] = &Trie{} - } - node = node.children[idx] - } - node.isEnd = true -} +/** + * Inserts a word into the trie. + * @param {string} word + * @return {void} + */ +Trie.prototype.insert = function (word) { + let node = this.children; + for (let char of word) { + if (!node[char]) { + node[char] = {}; + } + node = node[char]; + } + node.isEnd = true; +}; -func (this *Trie) Search(word string) bool { - node := this.SearchPrefix(word) - return node != nil && node.isEnd -} +/** + * Returns if the word is in the trie. + * @param {string} word + * @return {boolean} + */ +Trie.prototype.search = function (word) { + let node = this.searchPrefix(word); + return node != undefined && node.isEnd != undefined; +}; -func (this *Trie) StartsWith(prefix string) bool { - node := this.SearchPrefix(prefix) - return node != nil -} +Trie.prototype.searchPrefix = function (prefix) { + let node = this.children; + for (let char of prefix) { + if (!node[char]) return false; + node = node[char]; + } + return node; +}; -func (this *Trie) SearchPrefix(s string) *Trie { - node := this - for _, c := range s { - idx := c - 'a' - if node.children[idx] == nil { - return nil - } - node = node.children[idx] - } - return node -} +/** + * Returns if there is any word in the trie that starts with the given prefix. + * @param {string} prefix + * @return {boolean} + */ +Trie.prototype.startsWith = function (prefix) { + return this.searchPrefix(prefix); +}; /** * Your Trie object will be instantiated and called as such: - * obj := Constructor(); - * obj.Insert(word); - * param_2 := obj.Search(word); - * param_3 := obj.StartsWith(prefix); + * var obj = new Trie() + * obj.insert(word) + * var param_2 = obj.search(word) + * var param_3 = obj.startsWith(prefix) */ ``` -### **C#** - ```cs public class Trie { bool isEnd; @@ -505,10 +534,6 @@ public class Trie { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0208.Implement Trie (Prefix Tree)/README_EN.md b/solution/0200-0299/0208.Implement Trie (Prefix Tree)/README_EN.md index f26f37d158fb0..e14d4f6ad4b29 100644 --- a/solution/0200-0299/0208.Implement Trie (Prefix Tree)/README_EN.md +++ b/solution/0200-0299/0208.Implement Trie (Prefix Tree)/README_EN.md @@ -46,9 +46,9 @@ trie.search("app"); // return True ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -90,8 +90,6 @@ class Trie: # param_3 = obj.startsWith(prefix) ``` -### **Java** - ```java class Trie { private Trie[] children; @@ -145,71 +143,6 @@ class Trie { */ ``` -### **JavaScript** - -```js -/** - * Initialize your data structure here. - */ -var Trie = function () { - this.children = {}; -}; - -/** - * Inserts a word into the trie. - * @param {string} word - * @return {void} - */ -Trie.prototype.insert = function (word) { - let node = this.children; - for (let char of word) { - if (!node[char]) { - node[char] = {}; - } - node = node[char]; - } - node.isEnd = true; -}; - -/** - * Returns if the word is in the trie. - * @param {string} word - * @return {boolean} - */ -Trie.prototype.search = function (word) { - let node = this.searchPrefix(word); - return node != undefined && node.isEnd != undefined; -}; - -Trie.prototype.searchPrefix = function (prefix) { - let node = this.children; - for (let char of prefix) { - if (!node[char]) return false; - node = node[char]; - } - return node; -}; - -/** - * Returns if there is any word in the trie that starts with the given prefix. - * @param {string} prefix - * @return {boolean} - */ -Trie.prototype.startsWith = function (prefix) { - return this.searchPrefix(prefix); -}; - -/** - * Your Trie object will be instantiated and called as such: - * var obj = new Trie() - * obj.insert(word) - * var param_2 = obj.search(word) - * var param_3 = obj.startsWith(prefix) - */ -``` - -### **C++** - ```cpp class Trie { private: @@ -261,7 +194,107 @@ public: */ ``` -### **Rust** +```go +type Trie struct { + children [26]*Trie + isEnd bool +} + +func Constructor() Trie { + return Trie{} +} + +func (this *Trie) Insert(word string) { + node := this + for _, c := range word { + idx := c - 'a' + if node.children[idx] == nil { + node.children[idx] = &Trie{} + } + node = node.children[idx] + } + node.isEnd = true +} + +func (this *Trie) Search(word string) bool { + node := this.SearchPrefix(word) + return node != nil && node.isEnd +} + +func (this *Trie) StartsWith(prefix string) bool { + node := this.SearchPrefix(prefix) + return node != nil +} + +func (this *Trie) SearchPrefix(s string) *Trie { + node := this + for _, c := range s { + idx := c - 'a' + if node.children[idx] == nil { + return nil + } + node = node.children[idx] + } + return node +} + +/** + * Your Trie object will be instantiated and called as such: + * obj := Constructor(); + * obj.Insert(word); + * param_2 := obj.Search(word); + * param_3 := obj.StartsWith(prefix); + */ +``` + +```ts +class TrieNode { + children; + isEnd; + constructor() { + this.children = new Array(26); + this.isEnd = false; + } +} + +class Trie { + root; + constructor() { + this.root = new TrieNode(); + } + + insert(word: string): void { + let head = this.root; + for (let char of word) { + let index = char.charCodeAt(0) - 97; + if (!head.children[index]) { + head.children[index] = new TrieNode(); + } + head = head.children[index]; + } + head.isEnd = true; + } + + search(word: string): boolean { + let head = this.searchPrefix(word); + return head != null && head.isEnd; + } + + startsWith(prefix: string): boolean { + return this.searchPrefix(prefix) != null; + } + + private searchPrefix(prefix: string) { + let head = this.root; + for (let char of prefix) { + let index = char.charCodeAt(0) - 97; + if (!head.children[index]) return null; + head = head.children[index]; + } + return head; + } +} +``` ```rust use std::{ rc::Rc, cell::RefCell, collections::HashMap }; @@ -357,63 +390,67 @@ impl Trie { } ``` -### **Go** - -```go -type Trie struct { - children [26]*Trie - isEnd bool -} - -func Constructor() Trie { - return Trie{} -} +```js +/** + * Initialize your data structure here. + */ +var Trie = function () { + this.children = {}; +}; -func (this *Trie) Insert(word string) { - node := this - for _, c := range word { - idx := c - 'a' - if node.children[idx] == nil { - node.children[idx] = &Trie{} - } - node = node.children[idx] - } - node.isEnd = true -} +/** + * Inserts a word into the trie. + * @param {string} word + * @return {void} + */ +Trie.prototype.insert = function (word) { + let node = this.children; + for (let char of word) { + if (!node[char]) { + node[char] = {}; + } + node = node[char]; + } + node.isEnd = true; +}; -func (this *Trie) Search(word string) bool { - node := this.SearchPrefix(word) - return node != nil && node.isEnd -} +/** + * Returns if the word is in the trie. + * @param {string} word + * @return {boolean} + */ +Trie.prototype.search = function (word) { + let node = this.searchPrefix(word); + return node != undefined && node.isEnd != undefined; +}; -func (this *Trie) StartsWith(prefix string) bool { - node := this.SearchPrefix(prefix) - return node != nil -} +Trie.prototype.searchPrefix = function (prefix) { + let node = this.children; + for (let char of prefix) { + if (!node[char]) return false; + node = node[char]; + } + return node; +}; -func (this *Trie) SearchPrefix(s string) *Trie { - node := this - for _, c := range s { - idx := c - 'a' - if node.children[idx] == nil { - return nil - } - node = node.children[idx] - } - return node -} +/** + * Returns if there is any word in the trie that starts with the given prefix. + * @param {string} prefix + * @return {boolean} + */ +Trie.prototype.startsWith = function (prefix) { + return this.searchPrefix(prefix); +}; /** * Your Trie object will be instantiated and called as such: - * obj := Constructor(); - * obj.Insert(word); - * param_2 := obj.Search(word); - * param_3 := obj.StartsWith(prefix); + * var obj = new Trie() + * obj.insert(word) + * var param_2 = obj.search(word) + * var param_3 = obj.startsWith(prefix) */ ``` -### **C#** - ```cs public class Trie { bool isEnd; @@ -468,10 +505,6 @@ public class Trie { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0209.Minimum Size Subarray Sum/README.md b/solution/0200-0299/0209.Minimum Size Subarray Sum/README.md index 4bb2532a45944..75dfb4cc07576 100644 --- a/solution/0200-0299/0209.Minimum Size Subarray Sum/README.md +++ b/solution/0200-0299/0209.Minimum Size Subarray Sum/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:前缀和 + 二分查找** +### 方法一:前缀和 + 二分查找 我们先预处理出数组 $nums$ 的前缀和数组 $s$,其中 $s[i]$ 表示数组 $nums$ 前 $i$ 项元素之和。由于数组 $nums$ 中的元素都是正整数,因此数组 $s$ 也是单调递增的。另外,我们初始化答案 $ans = n + 1$,其中 $n$ 为数组 $nums$ 的长度。 @@ -66,22 +64,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 -**方法二:双指针** - -我们可以使用双指针 $j$ 和 $i$ 维护一个窗口,其中窗口中的所有元素之和小于 $target$。初始时 $j = 0$,答案 $ans = n + 1$,其中 $n$ 为数组 $nums$ 的长度。 - -接下来,指针 $i$ 从 $0$ 开始向右移动,每次移动一步,我们将指针 $i$ 对应的元素加入窗口,同时更新窗口中元素之和。如果窗口中元素之和大于等于 $target$,说明当前子数组满足条件,我们可以更新答案,即 $ans = \min(ans, i - j + 1)$。然后我们不断地从窗口中移除元素 $nums[j]$,直到窗口中元素之和小于 $target$,然后重复上述过程。 - -最后,如果 $ans \leq n$,则说明存在满足条件的子数组,返回 $ans$,否则返回 $0$。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。 - -### **Python3** - - - ```python class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: @@ -95,25 +79,6 @@ class Solution: return ans if ans <= n else 0 ``` -```python -class Solution: - def minSubArrayLen(self, target: int, nums: List[int]) -> int: - n = len(nums) - ans = n + 1 - s = j = 0 - for i, x in enumerate(nums): - s += x - while j < n and s >= target: - ans = min(ans, i - j + 1) - s -= nums[j] - j += 1 - return ans if ans <= n else 0 -``` - -### **Java** - - - ```java class Solution { public int minSubArrayLen(int target, int[] nums) { @@ -147,26 +112,6 @@ class Solution { } ``` -```java -class Solution { - public int minSubArrayLen(int target, int[] nums) { - int n = nums.length; - long s = 0; - int ans = n + 1; - for (int i = 0, j = 0; i < n; ++i) { - s += nums[i]; - while (j < n && s >= target) { - ans = Math.min(ans, i - j + 1); - s -= nums[j++]; - } - } - return ans <= n ? ans : 0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -188,27 +133,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minSubArrayLen(int target, vector& nums) { - int n = nums.size(); - long long s = 0; - int ans = n + 1; - for (int i = 0, j = 0; i < n; ++i) { - s += nums[i]; - while (j < n && s >= target) { - ans = min(ans, i - j + 1); - s -= nums[j++]; - } - } - return ans == n + 1 ? 0 : ans; - } -}; -``` - -### **Go** - ```go func minSubArrayLen(target int, nums []int) int { n := len(nums) @@ -230,48 +154,6 @@ func minSubArrayLen(target int, nums []int) int { } ``` -```go -func minSubArrayLen(target int, nums []int) int { - n := len(nums) - s := 0 - ans := n + 1 - for i, j := 0, 0; i < n; i++ { - s += nums[i] - for s >= target { - ans = min(ans, i-j+1) - s -= nums[j] - j++ - } - } - if ans == n+1 { - return 0 - } - return ans -} -``` - -### **C#** - -```cs -public class Solution { - public int MinSubArrayLen(int target, int[] nums) { - int n = nums.Length; - long s = 0; - int ans = n + 1; - for (int i = 0, j = 0; i < n; ++i) { - s += nums[i]; - while (s >= target) { - ans = Math.Min(ans, i - j + 1); - s -= nums[j++]; - } - } - return ans == n + 1 ? 0 : ans; - } -} -``` - -### **TypeScript** - ```ts function minSubArrayLen(target: number, nums: number[]): number { const n = nums.length; @@ -303,24 +185,6 @@ function minSubArrayLen(target: number, nums: number[]): number { } ``` -```ts -function minSubArrayLen(target: number, nums: number[]): number { - const n = nums.length; - let s = 0; - let ans = n + 1; - for (let i = 0, j = 0; i < n; ++i) { - s += nums[i]; - while (s >= target) { - ans = Math.min(ans, i - j + 1); - s -= nums[j++]; - } - } - return ans === n + 1 ? 0 : ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn min_sub_array_len(target: i32, nums: Vec) -> i32 { @@ -345,10 +209,126 @@ impl Solution { } ``` -### **...** +```cs +public class Solution { + public int MinSubArrayLen(int target, int[] nums) { + int n = nums.Length; + long s = 0; + int ans = n + 1; + for (int i = 0, j = 0; i < n; ++i) { + s += nums[i]; + while (s >= target) { + ans = Math.Min(ans, i - j + 1); + s -= nums[j++]; + } + } + return ans == n + 1 ? 0 : ans; + } +} +``` + + + +### 方法二:双指针 + +我们可以使用双指针 $j$ 和 $i$ 维护一个窗口,其中窗口中的所有元素之和小于 $target$。初始时 $j = 0$,答案 $ans = n + 1$,其中 $n$ 为数组 $nums$ 的长度。 + +接下来,指针 $i$ 从 $0$ 开始向右移动,每次移动一步,我们将指针 $i$ 对应的元素加入窗口,同时更新窗口中元素之和。如果窗口中元素之和大于等于 $target$,说明当前子数组满足条件,我们可以更新答案,即 $ans = \min(ans, i - j + 1)$。然后我们不断地从窗口中移除元素 $nums[j]$,直到窗口中元素之和小于 $target$,然后重复上述过程。 + +最后,如果 $ans \leq n$,则说明存在满足条件的子数组,返回 $ans$,否则返回 $0$。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。 + + + +```python +class Solution: + def minSubArrayLen(self, target: int, nums: List[int]) -> int: + n = len(nums) + ans = n + 1 + s = j = 0 + for i, x in enumerate(nums): + s += x + while j < n and s >= target: + ans = min(ans, i - j + 1) + s -= nums[j] + j += 1 + return ans if ans <= n else 0 +``` + +```java +class Solution { + public int minSubArrayLen(int target, int[] nums) { + int n = nums.length; + long s = 0; + int ans = n + 1; + for (int i = 0, j = 0; i < n; ++i) { + s += nums[i]; + while (j < n && s >= target) { + ans = Math.min(ans, i - j + 1); + s -= nums[j++]; + } + } + return ans <= n ? ans : 0; + } +} +``` + +```cpp +class Solution { +public: + int minSubArrayLen(int target, vector& nums) { + int n = nums.size(); + long long s = 0; + int ans = n + 1; + for (int i = 0, j = 0; i < n; ++i) { + s += nums[i]; + while (j < n && s >= target) { + ans = min(ans, i - j + 1); + s -= nums[j++]; + } + } + return ans == n + 1 ? 0 : ans; + } +}; +``` +```go +func minSubArrayLen(target int, nums []int) int { + n := len(nums) + s := 0 + ans := n + 1 + for i, j := 0, 0; i < n; i++ { + s += nums[i] + for s >= target { + ans = min(ans, i-j+1) + s -= nums[j] + j++ + } + } + if ans == n+1 { + return 0 + } + return ans +} ``` +```ts +function minSubArrayLen(target: number, nums: number[]): number { + const n = nums.length; + let s = 0; + let ans = n + 1; + for (let i = 0, j = 0; i < n; ++i) { + s += nums[i]; + while (s >= target) { + ans = Math.min(ans, i - j + 1); + s -= nums[j++]; + } + } + return ans === n + 1 ? 0 : ans; +} ``` + + diff --git a/solution/0200-0299/0209.Minimum Size Subarray Sum/README_EN.md b/solution/0200-0299/0209.Minimum Size Subarray Sum/README_EN.md index c324220d472c4..e33d535e2e2f7 100644 --- a/solution/0200-0299/0209.Minimum Size Subarray Sum/README_EN.md +++ b/solution/0200-0299/0209.Minimum Size Subarray Sum/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Prefix Sum + Binary Search** +### Solution 1: Prefix Sum + Binary Search First, we preprocess the prefix sum array $s$ of the array $nums$, where $s[i]$ represents the sum of the first $i$ elements of the array $nums$. Since all elements in the array $nums$ are positive integers, the array $s$ is also monotonically increasing. Also, we initialize the answer $ans = n + 1$, where $n$ is the length of the array $nums$. @@ -53,20 +53,8 @@ Finally, if $ans \leq n$, it means that there exists a subarray that satisfies t The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. -**Solution 2: Two Pointers** - -We can use two pointers $j$ and $i$ to maintain a window, where the sum of all elements in the window is less than $target$. Initially, $j = 0$, and the answer $ans = n + 1$, where $n$ is the length of the array $nums$. - -Next, the pointer $i$ starts to move to the right from $0$, moving one step each time. We add the element corresponding to the pointer $i$ to the window and update the sum of the elements in the window. If the sum of the elements in the window is greater than or equal to $target$, it means that the current subarray satisfies the condition, and we can update the answer, i.e., $ans = \min(ans, i - j + 1)$. Then we continuously remove the element $nums[j]$ from the window until the sum of the elements in the window is less than $target$, and then repeat the above process. - -Finally, if $ans \leq n$, it means that there exists a subarray that satisfies the condition, return $ans$, otherwise return $0$. - -The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$. - -### **Python3** - ```python class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: @@ -80,23 +68,6 @@ class Solution: return ans if ans <= n else 0 ``` -```python -class Solution: - def minSubArrayLen(self, target: int, nums: List[int]) -> int: - n = len(nums) - ans = n + 1 - s = j = 0 - for i, x in enumerate(nums): - s += x - while j < n and s >= target: - ans = min(ans, i - j + 1) - s -= nums[j] - j += 1 - return ans if ans <= n else 0 -``` - -### **Java** - ```java class Solution { public int minSubArrayLen(int target, int[] nums) { @@ -130,26 +101,6 @@ class Solution { } ``` -```java -class Solution { - public int minSubArrayLen(int target, int[] nums) { - int n = nums.length; - long s = 0; - int ans = n + 1; - for (int i = 0, j = 0; i < n; ++i) { - s += nums[i]; - while (j < n && s >= target) { - ans = Math.min(ans, i - j + 1); - s -= nums[j++]; - } - } - return ans <= n ? ans : 0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -171,27 +122,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minSubArrayLen(int target, vector& nums) { - int n = nums.size(); - long long s = 0; - int ans = n + 1; - for (int i = 0, j = 0; i < n; ++i) { - s += nums[i]; - while (j < n && s >= target) { - ans = min(ans, i - j + 1); - s -= nums[j++]; - } - } - return ans == n + 1 ? 0 : ans; - } -}; -``` - -### **Go** - ```go func minSubArrayLen(target int, nums []int) int { n := len(nums) @@ -213,48 +143,6 @@ func minSubArrayLen(target int, nums []int) int { } ``` -```go -func minSubArrayLen(target int, nums []int) int { - n := len(nums) - s := 0 - ans := n + 1 - for i, j := 0, 0; i < n; i++ { - s += nums[i] - for s >= target { - ans = min(ans, i-j+1) - s -= nums[j] - j++ - } - } - if ans == n+1 { - return 0 - } - return ans -} -``` - -### **C#** - -```cs -public class Solution { - public int MinSubArrayLen(int target, int[] nums) { - int n = nums.Length; - long s = 0; - int ans = n + 1; - for (int i = 0, j = 0; i < n; ++i) { - s += nums[i]; - while (s >= target) { - ans = Math.Min(ans, i - j + 1); - s -= nums[j++]; - } - } - return ans == n + 1 ? 0 : ans; - } -} -``` - -### **TypeScript** - ```ts function minSubArrayLen(target: number, nums: number[]): number { const n = nums.length; @@ -286,24 +174,6 @@ function minSubArrayLen(target: number, nums: number[]): number { } ``` -```ts -function minSubArrayLen(target: number, nums: number[]): number { - const n = nums.length; - let s = 0; - let ans = n + 1; - for (let i = 0, j = 0; i < n; ++i) { - s += nums[i]; - while (s >= target) { - ans = Math.min(ans, i - j + 1); - s -= nums[j++]; - } - } - return ans === n + 1 ? 0 : ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn min_sub_array_len(target: i32, nums: Vec) -> i32 { @@ -328,10 +198,126 @@ impl Solution { } ``` -### **...** +```cs +public class Solution { + public int MinSubArrayLen(int target, int[] nums) { + int n = nums.Length; + long s = 0; + int ans = n + 1; + for (int i = 0, j = 0; i < n; ++i) { + s += nums[i]; + while (s >= target) { + ans = Math.Min(ans, i - j + 1); + s -= nums[j++]; + } + } + return ans == n + 1 ? 0 : ans; + } +} +``` + + + +### Solution 2: Two Pointers + +We can use two pointers $j$ and $i$ to maintain a window, where the sum of all elements in the window is less than $target$. Initially, $j = 0$, and the answer $ans = n + 1$, where $n$ is the length of the array $nums$. + +Next, the pointer $i$ starts to move to the right from $0$, moving one step each time. We add the element corresponding to the pointer $i$ to the window and update the sum of the elements in the window. If the sum of the elements in the window is greater than or equal to $target$, it means that the current subarray satisfies the condition, and we can update the answer, i.e., $ans = \min(ans, i - j + 1)$. Then we continuously remove the element $nums[j]$ from the window until the sum of the elements in the window is less than $target$, and then repeat the above process. + +Finally, if $ans \leq n$, it means that there exists a subarray that satisfies the condition, return $ans$, otherwise return $0$. + +The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$. + + + +```python +class Solution: + def minSubArrayLen(self, target: int, nums: List[int]) -> int: + n = len(nums) + ans = n + 1 + s = j = 0 + for i, x in enumerate(nums): + s += x + while j < n and s >= target: + ans = min(ans, i - j + 1) + s -= nums[j] + j += 1 + return ans if ans <= n else 0 +``` + +```java +class Solution { + public int minSubArrayLen(int target, int[] nums) { + int n = nums.length; + long s = 0; + int ans = n + 1; + for (int i = 0, j = 0; i < n; ++i) { + s += nums[i]; + while (j < n && s >= target) { + ans = Math.min(ans, i - j + 1); + s -= nums[j++]; + } + } + return ans <= n ? ans : 0; + } +} +``` + +```cpp +class Solution { +public: + int minSubArrayLen(int target, vector& nums) { + int n = nums.size(); + long long s = 0; + int ans = n + 1; + for (int i = 0, j = 0; i < n; ++i) { + s += nums[i]; + while (j < n && s >= target) { + ans = min(ans, i - j + 1); + s -= nums[j++]; + } + } + return ans == n + 1 ? 0 : ans; + } +}; +``` +```go +func minSubArrayLen(target int, nums []int) int { + n := len(nums) + s := 0 + ans := n + 1 + for i, j := 0, 0; i < n; i++ { + s += nums[i] + for s >= target { + ans = min(ans, i-j+1) + s -= nums[j] + j++ + } + } + if ans == n+1 { + return 0 + } + return ans +} ``` +```ts +function minSubArrayLen(target: number, nums: number[]): number { + const n = nums.length; + let s = 0; + let ans = n + 1; + for (let i = 0, j = 0; i < n; ++i) { + s += nums[i]; + while (s >= target) { + ans = Math.min(ans, i - j + 1); + s -= nums[j++]; + } + } + return ans === n + 1 ? 0 : ans; +} ``` + + diff --git a/solution/0200-0299/0210.Course Schedule II/README.md b/solution/0200-0299/0210.Course Schedule II/README.md index 0eef495ec11aa..0ef20de83fbf5 100644 --- a/solution/0200-0299/0210.Course Schedule II/README.md +++ b/solution/0200-0299/0210.Course Schedule II/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:拓扑排序** +### 方法一:拓扑排序 我们创建一个邻接表 $g$,用于存储每个节点的后继节点,同时还需要一个数组 $indeg$ 存储每个节点的入度。在构建邻接表的同时,我们也统计每个节点的入度。当入度为 $0$ 的节点代表没有任何前置课程,可以直接学习,我们将其加入队列 $q$ 中。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: @@ -94,10 +88,6 @@ class Solution: return ans if len(ans) == numCourses else [] ``` -### **Java** - - - ```java class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { @@ -131,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -166,8 +154,6 @@ public: }; ``` -### **Go** - ```go func findOrder(numCourses int, prerequisites [][]int) []int { g := make([][]int, numCourses) @@ -202,8 +188,6 @@ func findOrder(numCourses int, prerequisites [][]int) []int { } ``` -### **TypeScript** - ```ts function findOrder(numCourses: number, prerequisites: number[][]): number[] { const g: number[][] = Array.from({ length: numCourses }, () => []); @@ -232,45 +216,6 @@ function findOrder(numCourses: number, prerequisites: number[][]): number[] { } ``` -### **C#** - -```cs -public class Solution { - public int[] FindOrder(int numCourses, int[][] prerequisites) { - var g = new List[numCourses]; - for (int i = 0; i < numCourses; ++i) { - g[i] = new List(); - } - var indeg = new int[numCourses]; - foreach (var p in prerequisites) { - int a = p[0], b = p[1]; - g[b].Add(a); - ++indeg[a]; - } - var q = new Queue(); - for (int i = 0; i < numCourses; ++i) { - if (indeg[i] == 0) { - q.Enqueue(i); - } - } - var ans = new int[numCourses]; - var cnt = 0; - while (q.Count > 0) { - int i = q.Dequeue(); - ans[cnt++] = i; - foreach (int j in g[i]) { - if (--indeg[j] == 0) { - q.Enqueue(j); - } - } - } - return cnt == numCourses ? ans : new int[0]; - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn find_order(num_courses: i32, prerequisites: Vec>) -> Vec { @@ -312,10 +257,41 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public int[] FindOrder(int numCourses, int[][] prerequisites) { + var g = new List[numCourses]; + for (int i = 0; i < numCourses; ++i) { + g[i] = new List(); + } + var indeg = new int[numCourses]; + foreach (var p in prerequisites) { + int a = p[0], b = p[1]; + g[b].Add(a); + ++indeg[a]; + } + var q = new Queue(); + for (int i = 0; i < numCourses; ++i) { + if (indeg[i] == 0) { + q.Enqueue(i); + } + } + var ans = new int[numCourses]; + var cnt = 0; + while (q.Count > 0) { + int i = q.Dequeue(); + ans[cnt++] = i; + foreach (int j in g[i]) { + if (--indeg[j] == 0) { + q.Enqueue(j); + } + } + } + return cnt == numCourses ? ans : new int[0]; + } +} ``` + + diff --git a/solution/0200-0299/0210.Course Schedule II/README_EN.md b/solution/0200-0299/0210.Course Schedule II/README_EN.md index 5f4d9de210cd3..9a72b59ded91c 100644 --- a/solution/0200-0299/0210.Course Schedule II/README_EN.md +++ b/solution/0200-0299/0210.Course Schedule II/README_EN.md @@ -51,9 +51,9 @@ So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return ans if len(ans) == numCourses else [] ``` -### **Java** - ```java class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { @@ -110,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +141,6 @@ public: }; ``` -### **Go** - ```go func findOrder(numCourses int, prerequisites [][]int) []int { g := make([][]int, numCourses) @@ -181,8 +175,6 @@ func findOrder(numCourses int, prerequisites [][]int) []int { } ``` -### **TypeScript** - ```ts function findOrder(numCourses: number, prerequisites: number[][]): number[] { const g: number[][] = Array.from({ length: numCourses }, () => []); @@ -211,45 +203,6 @@ function findOrder(numCourses: number, prerequisites: number[][]): number[] { } ``` -### **C#** - -```cs -public class Solution { - public int[] FindOrder(int numCourses, int[][] prerequisites) { - var g = new List[numCourses]; - for (int i = 0; i < numCourses; ++i) { - g[i] = new List(); - } - var indeg = new int[numCourses]; - foreach (var p in prerequisites) { - int a = p[0], b = p[1]; - g[b].Add(a); - ++indeg[a]; - } - var q = new Queue(); - for (int i = 0; i < numCourses; ++i) { - if (indeg[i] == 0) { - q.Enqueue(i); - } - } - var ans = new int[numCourses]; - var cnt = 0; - while (q.Count > 0) { - int i = q.Dequeue(); - ans[cnt++] = i; - foreach (int j in g[i]) { - if (--indeg[j] == 0) { - q.Enqueue(j); - } - } - } - return cnt == numCourses ? ans : new int[0]; - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn find_order(num_courses: i32, prerequisites: Vec>) -> Vec { @@ -291,10 +244,41 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public int[] FindOrder(int numCourses, int[][] prerequisites) { + var g = new List[numCourses]; + for (int i = 0; i < numCourses; ++i) { + g[i] = new List(); + } + var indeg = new int[numCourses]; + foreach (var p in prerequisites) { + int a = p[0], b = p[1]; + g[b].Add(a); + ++indeg[a]; + } + var q = new Queue(); + for (int i = 0; i < numCourses; ++i) { + if (indeg[i] == 0) { + q.Enqueue(i); + } + } + var ans = new int[numCourses]; + var cnt = 0; + while (q.Count > 0) { + int i = q.Dequeue(); + ans[cnt++] = i; + foreach (int j in g[i]) { + if (--indeg[j] == 0) { + q.Enqueue(j); + } + } + } + return cnt == numCourses ? ans : new int[0]; + } +} ``` + + diff --git a/solution/0200-0299/0211.Design Add and Search Words Data Structure/README.md b/solution/0200-0299/0211.Design Add and Search Words Data Structure/README.md index 22d92ca5fcf8c..61f7f6608ab0a 100644 --- a/solution/0200-0299/0211.Design Add and Search Words Data Structure/README.md +++ b/solution/0200-0299/0211.Design Add and Search Words Data Structure/README.md @@ -51,16 +51,10 @@ wordDictionary.search("b.."); // 返回 True ## 解法 - - -“前缀树”实现。 +### 方法一 -### **Python3** - - - ```python class Trie: def __init__(self): @@ -105,10 +99,6 @@ class WordDictionary: # param_2 = obj.search(word) ``` -### **Java** - - - ```java class Trie { Trie[] children = new Trie[26]; @@ -168,7 +158,75 @@ class WordDictionary { */ ``` -### **Go** +```cpp +class trie { +public: + vector children; + bool is_end; + + trie() { + children = vector(26, nullptr); + is_end = false; + } + + void insert(const string& word) { + trie* cur = this; + for (char c : word) { + c -= 'a'; + if (cur->children[c] == nullptr) { + cur->children[c] = new trie; + } + cur = cur->children[c]; + } + cur->is_end = true; + } +}; + +class WordDictionary { +private: + trie* root; + +public: + WordDictionary() + : root(new trie) {} + + void addWord(string word) { + root->insert(word); + } + + bool search(string word) { + return dfs(word, 0, root); + } + +private: + bool dfs(const string& word, int i, trie* cur) { + if (i == word.size()) { + return cur->is_end; + } + char c = word[i]; + if (c != '.') { + trie* child = cur->children[c - 'a']; + if (child != nullptr && dfs(word, i + 1, child)) { + return true; + } + } else { + for (trie* child : cur->children) { + if (child != nullptr && dfs(word, i + 1, child)) { + return true; + } + } + } + return false; + } +}; + +/** + * Your WordDictionary object will be instantiated and called as such: + * WordDictionary* obj = new WordDictionary(); + * obj->addWord(word); + * bool param_2 = obj->search(word); + */ +``` ```go type WordDictionary struct { @@ -235,82 +293,76 @@ func (t *trie) insert(word string) { */ ``` -### **C++** - -```cpp -class trie { -public: - vector children; - bool is_end; - - trie() { - children = vector(26, nullptr); - is_end = false; - } +```cs +using System.Collections.Generic; +using System.Linq; - void insert(const string& word) { - trie* cur = this; - for (char c : word) { - c -= 'a'; - if (cur->children[c] == nullptr) { - cur->children[c] = new trie; - } - cur = cur->children[c]; - } - cur->is_end = true; +class TrieNode { + public bool IsEnd { get; set; } + public TrieNode[] Children { get; set; } + public TrieNode() { + Children = new TrieNode[26]; } -}; - -class WordDictionary { -private: - trie* root; +} -public: - WordDictionary() - : root(new trie) {} +public class WordDictionary { + private TrieNode root; - void addWord(string word) { - root->insert(word); + public WordDictionary() { + root = new TrieNode(); } - bool search(string word) { - return dfs(word, 0, root); + public void AddWord(string word) { + var node = root; + for (var i = 0; i < word.Length; ++i) + { + TrieNode nextNode; + var index = word[i] - 'a'; + nextNode = node.Children[index]; + if (nextNode == null) + { + nextNode = new TrieNode(); + node.Children[index] = nextNode; + } + node = nextNode; + } + node.IsEnd = true; } -private: - bool dfs(const string& word, int i, trie* cur) { - if (i == word.size()) { - return cur->is_end; - } - char c = word[i]; - if (c != '.') { - trie* child = cur->children[c - 'a']; - if (child != nullptr && dfs(word, i + 1, child)) { - return true; - } - } else { - for (trie* child : cur->children) { - if (child != nullptr && dfs(word, i + 1, child)) { - return true; + public bool Search(string word) { + var queue = new Queue(); + queue.Enqueue(root); + for (var i = 0; i < word.Length; ++i) + { + var count = queue.Count; + while (count-- > 0) + { + var node = queue.Dequeue(); + if (word[i] == '.') + { + foreach (var nextNode in node.Children) + { + if (nextNode != null) + { + queue.Enqueue(nextNode); + } + } + } + else + { + var nextNode = node.Children[word[i] - 'a']; + if (nextNode != null) + { + queue.Enqueue(nextNode); + } } } } - return false; + return queue.Any(n => n.IsEnd); } -}; - -/** - * Your WordDictionary object will be instantiated and called as such: - * WordDictionary* obj = new WordDictionary(); - * obj->addWord(word); - * bool param_2 = obj->search(word); - */ -``` - -### **...** - -``` - +} ``` + + diff --git a/solution/0200-0299/0211.Design Add and Search Words Data Structure/README_EN.md b/solution/0200-0299/0211.Design Add and Search Words Data Structure/README_EN.md index 7ee6f3be1fca1..459e63fdfd881 100644 --- a/solution/0200-0299/0211.Design Add and Search Words Data Structure/README_EN.md +++ b/solution/0200-0299/0211.Design Add and Search Words Data Structure/README_EN.md @@ -48,9 +48,9 @@ wordDictionary.search("b.."); // return True ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -96,8 +96,6 @@ class WordDictionary: # param_2 = obj.search(word) ``` -### **Java** - ```java class Trie { Trie[] children = new Trie[26]; @@ -157,7 +155,75 @@ class WordDictionary { */ ``` -### **Go** +```cpp +class trie { +public: + vector children; + bool is_end; + + trie() { + children = vector(26, nullptr); + is_end = false; + } + + void insert(const string& word) { + trie* cur = this; + for (char c : word) { + c -= 'a'; + if (cur->children[c] == nullptr) { + cur->children[c] = new trie; + } + cur = cur->children[c]; + } + cur->is_end = true; + } +}; + +class WordDictionary { +private: + trie* root; + +public: + WordDictionary() + : root(new trie) {} + + void addWord(string word) { + root->insert(word); + } + + bool search(string word) { + return dfs(word, 0, root); + } + +private: + bool dfs(const string& word, int i, trie* cur) { + if (i == word.size()) { + return cur->is_end; + } + char c = word[i]; + if (c != '.') { + trie* child = cur->children[c - 'a']; + if (child != nullptr && dfs(word, i + 1, child)) { + return true; + } + } else { + for (trie* child : cur->children) { + if (child != nullptr && dfs(word, i + 1, child)) { + return true; + } + } + } + return false; + } +}; + +/** + * Your WordDictionary object will be instantiated and called as such: + * WordDictionary* obj = new WordDictionary(); + * obj->addWord(word); + * bool param_2 = obj->search(word); + */ +``` ```go type WordDictionary struct { @@ -224,82 +290,76 @@ func (t *trie) insert(word string) { */ ``` -### **C++** +```cs +using System.Collections.Generic; +using System.Linq; -```cpp -class trie { -public: - vector children; - bool is_end; - - trie() { - children = vector(26, nullptr); - is_end = false; - } - - void insert(const string& word) { - trie* cur = this; - for (char c : word) { - c -= 'a'; - if (cur->children[c] == nullptr) { - cur->children[c] = new trie; - } - cur = cur->children[c]; - } - cur->is_end = true; +class TrieNode { + public bool IsEnd { get; set; } + public TrieNode[] Children { get; set; } + public TrieNode() { + Children = new TrieNode[26]; } -}; - -class WordDictionary { -private: - trie* root; +} -public: - WordDictionary() - : root(new trie) {} +public class WordDictionary { + private TrieNode root; - void addWord(string word) { - root->insert(word); + public WordDictionary() { + root = new TrieNode(); } - bool search(string word) { - return dfs(word, 0, root); + public void AddWord(string word) { + var node = root; + for (var i = 0; i < word.Length; ++i) + { + TrieNode nextNode; + var index = word[i] - 'a'; + nextNode = node.Children[index]; + if (nextNode == null) + { + nextNode = new TrieNode(); + node.Children[index] = nextNode; + } + node = nextNode; + } + node.IsEnd = true; } -private: - bool dfs(const string& word, int i, trie* cur) { - if (i == word.size()) { - return cur->is_end; - } - char c = word[i]; - if (c != '.') { - trie* child = cur->children[c - 'a']; - if (child != nullptr && dfs(word, i + 1, child)) { - return true; - } - } else { - for (trie* child : cur->children) { - if (child != nullptr && dfs(word, i + 1, child)) { - return true; + public bool Search(string word) { + var queue = new Queue(); + queue.Enqueue(root); + for (var i = 0; i < word.Length; ++i) + { + var count = queue.Count; + while (count-- > 0) + { + var node = queue.Dequeue(); + if (word[i] == '.') + { + foreach (var nextNode in node.Children) + { + if (nextNode != null) + { + queue.Enqueue(nextNode); + } + } + } + else + { + var nextNode = node.Children[word[i] - 'a']; + if (nextNode != null) + { + queue.Enqueue(nextNode); + } } } } - return false; + return queue.Any(n => n.IsEnd); } -}; - -/** - * Your WordDictionary object will be instantiated and called as such: - * WordDictionary* obj = new WordDictionary(); - * obj->addWord(word); - * bool param_2 = obj->search(word); - */ -``` - -### **...** - -``` - +} ``` + + diff --git a/solution/0200-0299/0212.Word Search II/README.md b/solution/0200-0299/0212.Word Search II/README.md index 9fbe399177e34..686172d6e6739 100644 --- a/solution/0200-0299/0212.Word Search II/README.md +++ b/solution/0200-0299/0212.Word Search II/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:前缀树 + DFS** +### 方法一:前缀树 + DFS 我们首先将 `words` 中的单词构建成前缀树,前缀树的每个节点包含一个长度为 $26$ 的数组 `children`,表示该节点的子节点,数组的下标表示子节点对应的字符,数组的值表示子节点的引用。同时,每个节点还包含一个整数 `ref`,表示该节点对应的单词在 `words` 中的引用,如果该节点不是单词的结尾,则 `ref` 的值为 $-1$。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Trie: def __init__(self): @@ -106,10 +100,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Trie { Trie[] children = new Trie[26]; @@ -173,8 +163,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -240,8 +228,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -300,8 +286,6 @@ func findWords(board [][]byte, words []string) (ans []string) { } ``` -### **TypeScript** - ```ts class Trie { children: Trie[]; @@ -364,10 +348,6 @@ function findWords(board: string[][], words: string[]): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0212.Word Search II/README_EN.md b/solution/0200-0299/0212.Word Search II/README_EN.md index df0558d62a09d..88bcb045dcb1d 100644 --- a/solution/0200-0299/0212.Word Search II/README_EN.md +++ b/solution/0200-0299/0212.Word Search II/README_EN.md @@ -39,12 +39,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python class Trie: def __init__(self): @@ -90,8 +88,6 @@ class Solution: return ans ``` -### **Java** - ```java class Trie { Trie[] children = new Trie[26]; @@ -155,8 +151,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -222,8 +216,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -282,8 +274,6 @@ func findWords(board [][]byte, words []string) (ans []string) { } ``` -### **TypeScript** - ```ts class Trie { children: Trie[]; @@ -346,10 +336,6 @@ function findWords(board: string[][], words: string[]): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0213.House Robber II/README.md b/solution/0200-0299/0213.House Robber II/README.md index de5a872920b4f..24c718e2c3c1e 100644 --- a/solution/0200-0299/0213.House Robber II/README.md +++ b/solution/0200-0299/0213.House Robber II/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 环状排列意味着第一个房屋和最后一个房屋中最多只能选择一个偷窃,因此可以把此环状排列房间问题约化为两个单排排列房屋子问题。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def rob(self, nums: List[int]) -> int: @@ -74,10 +68,6 @@ class Solution: return max(_rob(nums[1:]), _rob(nums[:-1])) ``` -### **Java** - - - ```java class Solution { public int rob(int[] nums) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func rob(nums []int) int { n := len(nums) @@ -145,8 +131,6 @@ func robRange(nums []int, l, r int) int { } ``` -### **TypeScript** - ```ts function rob(nums: number[]): number { const n = nums.length; @@ -164,8 +148,6 @@ function rob(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn rob(nums: Vec) -> i32 { @@ -185,10 +167,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0213.House Robber II/README_EN.md b/solution/0200-0299/0213.House Robber II/README_EN.md index 67b8c2293a634..0fa2b7dc1b914 100644 --- a/solution/0200-0299/0213.House Robber II/README_EN.md +++ b/solution/0200-0299/0213.House Robber II/README_EN.md @@ -43,7 +43,7 @@ Total amount you can rob = 1 + 3 = 4. ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming The circular arrangement means that at most one of the first and last houses can be chosen for theft, so this circular arrangement problem can be reduced to two single-row house problems. @@ -51,8 +51,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def rob(self, nums: List[int]) -> int: @@ -67,8 +65,6 @@ class Solution: return max(_rob(nums[1:]), _rob(nums[:-1])) ``` -### **Java** - ```java class Solution { public int rob(int[] nums) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +110,6 @@ public: }; ``` -### **Go** - ```go func rob(nums []int) int { n := len(nums) @@ -136,8 +128,6 @@ func robRange(nums []int, l, r int) int { } ``` -### **TypeScript** - ```ts function rob(nums: number[]): number { const n = nums.length; @@ -155,8 +145,6 @@ function rob(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn rob(nums: Vec) -> i32 { @@ -176,10 +164,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0214.Shortest Palindrome/README.md b/solution/0200-0299/0214.Shortest Palindrome/README.md index 389a3a7ffd8e3..6842c2edea6c3 100644 --- a/solution/0200-0299/0214.Shortest Palindrome/README.md +++ b/solution/0200-0299/0214.Shortest Palindrome/README.md @@ -35,9 +35,7 @@ ## 解法 - - -**方法一:字符串哈希** +### 方法一:字符串哈希 **字符串哈希**是把一个任意长度的字符串映射成一个非负整数,并且其冲突的概率几乎为 0。字符串哈希用于计算字符串哈希值,快速判断两个字符串是否相等。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def shortestPalindrome(self, s: str) -> str: @@ -75,10 +69,6 @@ class Solution: return s if idx == n else s[idx:][::-1] + s ``` -### **Java** - - - ```java class Solution { public String shortestPalindrome(String s) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef unsigned long long ull; @@ -133,8 +121,6 @@ public: }; ``` -### **Go** - ```go func shortestPalindrome(s string) string { n := len(s) @@ -161,8 +147,6 @@ func shortestPalindrome(s string) string { } ``` -### **Rust** - ```rust impl Solution { pub fn shortest_palindrome(s: String) -> String { @@ -187,10 +171,48 @@ impl Solution { } ``` -### **...** - -``` +```cs +// https://leetcode.com/problems/shortest-palindrome/ + +using System.Text; + +public partial class Solution +{ + public string ShortestPalindrome(string s) + { + for (var i = s.Length - 1; i >= 0; --i) + { + var k = i; + var j = 0; + while (j < k) + { + if (s[j] == s[k]) + { + ++j; + --k; + } + else + { + break; + } + } + if (j >= k) + { + var sb = new StringBuilder(s.Length * 2 - i - 1); + for (var l = s.Length - 1; l >= i + 1; --l) + { + sb.Append(s[l]); + } + sb.Append(s); + return sb.ToString(); + } + } + return string.Empty; + } +} ``` + + diff --git a/solution/0200-0299/0214.Shortest Palindrome/README_EN.md b/solution/0200-0299/0214.Shortest Palindrome/README_EN.md index f43416eb460ff..d8bb3c658b2dc 100644 --- a/solution/0200-0299/0214.Shortest Palindrome/README_EN.md +++ b/solution/0200-0299/0214.Shortest Palindrome/README_EN.md @@ -26,9 +26,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -48,8 +48,6 @@ class Solution: return s if idx == n else s[idx:][::-1] + s ``` -### **Java** - ```java class Solution { public String shortestPalindrome(String s) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef unsigned long long ull; @@ -104,8 +100,6 @@ public: }; ``` -### **Go** - ```go func shortestPalindrome(s string) string { n := len(s) @@ -132,8 +126,6 @@ func shortestPalindrome(s string) string { } ``` -### **Rust** - ```rust impl Solution { pub fn shortest_palindrome(s: String) -> String { @@ -158,10 +150,48 @@ impl Solution { } ``` -### **...** - -``` +```cs +// https://leetcode.com/problems/shortest-palindrome/ + +using System.Text; + +public partial class Solution +{ + public string ShortestPalindrome(string s) + { + for (var i = s.Length - 1; i >= 0; --i) + { + var k = i; + var j = 0; + while (j < k) + { + if (s[j] == s[k]) + { + ++j; + --k; + } + else + { + break; + } + } + if (j >= k) + { + var sb = new StringBuilder(s.Length * 2 - i - 1); + for (var l = s.Length - 1; l >= i + 1; --l) + { + sb.Append(s[l]); + } + sb.Append(s); + return sb.ToString(); + } + } + return string.Empty; + } +} ``` + + diff --git a/solution/0200-0299/0215.Kth Largest Element in an Array/README.md b/solution/0200-0299/0215.Kth Largest Element in an Array/README.md index 8844384653068..b72f81b5ed4e1 100644 --- a/solution/0200-0299/0215.Kth Largest Element in an Array/README.md +++ b/solution/0200-0299/0215.Kth Largest Element in an Array/README.md @@ -38,28 +38,14 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们可以将数组 $nums$ 升序排列,然后获取 $nums[n-k]$。 时间复杂度 $O(n \times \log n)$,其中 $n$ 表示数组 $nums$ 的长度。 -**方法二:Partition** - -我们注意到,并不是所有时候,都需要整个数组进入有序状态,只需要**局部有序**,或者说,从大到小排序,只要 $[0..k)$ 位置的元素有序,那么就能确定结果,此处使用**快速排序**。 - -快速排序有一特点,每一次循环结束时,能够确定的是 $partition$ 一定处于它该处于的索引位置。从而根据它得知,结果值是在左数组还是在右数组当中,然后对那一数组进行排序即可。 - -时间复杂度 $O(n)$,其中 $n$ 表示数组 $nums$ 的长度。 - -### **Python3** - - - ```python class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: @@ -87,10 +73,6 @@ class Solution: return quick_sort(0, n - 1, n - k) ``` -### **Java** - - - ```java class Solution { public int findKthLargest(int[] nums, int k) { @@ -123,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +129,6 @@ public: }; ``` -### **Go** - ```go func findKthLargest(nums []int, k int) int { n := len(nums) @@ -187,8 +165,6 @@ func quickSort(nums []int, left, right, k int) int { } ``` -### **TypeScript** - ```ts function findKthLargest(nums: number[], k: number): number { const n = nums.length; @@ -218,8 +194,6 @@ function findKthLargest(nums: number[], k: number): number { } ``` -### **Rust** - ```rust use rand::Rng; @@ -252,6 +226,18 @@ impl Solution { } ``` + + +### 方法二:Partition + +我们注意到,并不是所有时候,都需要整个数组进入有序状态,只需要**局部有序**,或者说,从大到小排序,只要 $[0..k)$ 位置的元素有序,那么就能确定结果,此处使用**快速排序**。 + +快速排序有一特点,每一次循环结束时,能够确定的是 $partition$ 一定处于它该处于的索引位置。从而根据它得知,结果值是在左数组还是在右数组当中,然后对那一数组进行排序即可。 + +时间复杂度 $O(n)$,其中 $n$ 表示数组 $nums$ 的长度。 + + + ```rust use rand::Rng; @@ -283,10 +269,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0215.Kth Largest Element in an Array/README_EN.md b/solution/0200-0299/0215.Kth Largest Element in an Array/README_EN.md index 6affc376986cd..03fa6ba322c19 100644 --- a/solution/0200-0299/0215.Kth Largest Element in an Array/README_EN.md +++ b/solution/0200-0299/0215.Kth Largest Element in an Array/README_EN.md @@ -28,24 +28,14 @@ ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting We can sort the array $nums$ in ascending order, and then get $nums[n-k]$. The time complexity is $O(n \times \log n)$, where $n$ is the length of the array $nums$. -**Solution 2: Partition** - -We notice that it is not always necessary for the entire array to be in an ordered state. We only need **local order**. That is to say, if the elements in the position $[0..k)$ are sorted in descending order, then we can determine the result. Here we use **quick sort**. - -Quick sort has a characteristic that at the end of each loop, it can be determined that the $partition$ is definitely at the index position it should be. Therefore, based on it, we know whether the result value is in the left array or in the right array, and then sort that array. - -The time complexity is $O(n)$, where $n$ is the length of the array $nums$. - -### **Python3** - ```python class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: @@ -73,8 +63,6 @@ class Solution: return quick_sort(0, n - 1, n - k) ``` -### **Java** - ```java class Solution { public int findKthLargest(int[] nums, int k) { @@ -107,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +119,6 @@ public: }; ``` -### **Go** - ```go func findKthLargest(nums []int, k int) int { n := len(nums) @@ -171,8 +155,6 @@ func quickSort(nums []int, left, right, k int) int { } ``` -### **TypeScript** - ```ts function findKthLargest(nums: number[], k: number): number { const n = nums.length; @@ -202,8 +184,6 @@ function findKthLargest(nums: number[], k: number): number { } ``` -### **Rust** - ```rust use rand::Rng; @@ -236,6 +216,18 @@ impl Solution { } ``` + + +### Solution 2: Partition + +We notice that it is not always necessary for the entire array to be in an ordered state. We only need **local order**. That is to say, if the elements in the position $[0..k)$ are sorted in descending order, then we can determine the result. Here we use **quick sort**. + +Quick sort has a characteristic that at the end of each loop, it can be determined that the $partition$ is definitely at the index position it should be. Therefore, based on it, we know whether the result value is in the left array or in the right array, and then sort that array. + +The time complexity is $O(n)$, where $n$ is the length of the array $nums$. + + + ```rust use rand::Rng; @@ -267,10 +259,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0216.Combination Sum III/README.md b/solution/0200-0299/0216.Combination Sum III/README.md index bff5cee6a4e65..9c1f8bc797a47 100644 --- a/solution/0200-0299/0216.Combination Sum III/README.md +++ b/solution/0200-0299/0216.Combination Sum III/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:剪枝 + 回溯(两种方式)** +### 方法一:剪枝 + 回溯(两种方式) 我们设计一个函数 $dfs(i, s)$,表示当前枚举到数字 $i$,还剩下和为 $s$ 的数字需要枚举,当前搜索路径为 $t$,答案为 $ans$。 @@ -81,26 +79,8 @@ 时间复杂度 $(C_{9}^k \times k)$,空间复杂度 $O(k)$。 -**方法二:二进制枚举** - -我们可以用一个长度为 $9$ 的二进制整数表示数字 $1$ 到 $9$ 的选取情况,其中二进制整数的第 $i$ 位表示数字 $i + 1$ 是否被选取,如果第 $i$ 位为 $1$,则表示数字 $i + 1$ 被选取,否则表示数字 $i + 1$ 没有被选取。 - -我们在 $[0, 2^9)$ 范围内枚举二进制整数,对于当前枚举到的二进制整数 $mask$,如果 $mask$ 的二进制表示中 $1$ 的个数为 $k$,且 $mask$ 的二进制表示中 $1$ 所对应的数字之和为 $n$,则说明 $mask$ 对应的数字选取方案是一组答案。我们将 $mask$ 对应的数字选取方案加入答案即可。 - -时间复杂度 $O(2^9 \times 9)$,空间复杂度 $O(k)$。 - -相似题目: - -- [39. 组合总和](/solution/0000-0099/0039.Combination%20Sum/README.md) -- [40. 组合总和 II](/solution/0000-0099/0040.Combination%20Sum%20II/README.md) -- [77. 组合](/solution/0000-0099/0077.Combinations/README.md) - -### **Python3** - - - ```python class Solution: def combinationSum3(self, k: int, n: int) -> List[List[int]]: @@ -122,43 +102,6 @@ class Solution: return ans ``` -```python -class Solution: - def combinationSum3(self, k: int, n: int) -> List[List[int]]: - def dfs(i: int, s: int): - if s == 0: - if len(t) == k: - ans.append(t[:]) - return - if i > 9 or i > s or len(t) >= k: - return - for j in range(i, 10): - t.append(j) - dfs(j + 1, s - j) - t.pop() - - ans = [] - t = [] - dfs(1, n) - return ans -``` - -```python -class Solution: - def combinationSum3(self, k: int, n: int) -> List[List[int]]: - ans = [] - for mask in range(1 << 9): - if mask.bit_count() == k: - t = [i + 1 for i in range(9) if mask >> i & 1] - if sum(t) == n: - ans.append(t) - return ans -``` - -### **Java** - - - ```java class Solution { private List> ans = new ArrayList<>(); @@ -189,63 +132,6 @@ class Solution { } ``` -```java -class Solution { - private List> ans = new ArrayList<>(); - private List t = new ArrayList<>(); - private int k; - - public List> combinationSum3(int k, int n) { - this.k = k; - dfs(1, n); - return ans; - } - - private void dfs(int i, int s) { - if (s == 0) { - if (t.size() == k) { - ans.add(new ArrayList<>(t)); - } - return; - } - if (i > 9 || i > s || t.size() >= k) { - return; - } - for (int j = i; j <= 9; ++j) { - t.add(j); - dfs(j + 1, s - j); - t.remove(t.size() - 1); - } - } -} -``` - -```java -class Solution { - public List> combinationSum3(int k, int n) { - List> ans = new ArrayList<>(); - for (int mask = 0; mask < 1 << 9; ++mask) { - if (Integer.bitCount(mask) == k) { - List t = new ArrayList<>(); - int s = 0; - for (int i = 0; i < 9; ++i) { - if ((mask >> i & 1) == 1) { - s += (i + 1); - t.add(i + 1); - } - } - if (s == n) { - ans.add(t); - } - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -273,61 +159,54 @@ public: }; ``` -```cpp -class Solution { -public: - vector> combinationSum3(int k, int n) { - vector> ans; - vector t; - function dfs = [&](int i, int s) { - if (s == 0) { - if (t.size() == k) { - ans.emplace_back(t); - } - return; - } - if (i > 9 || i > s || t.size() >= k) { - return; - } - for (int j = i; j <= 9; ++j) { - t.emplace_back(j); - dfs(j + 1, s - j); - t.pop_back(); - } - }; - dfs(1, n); - return ans; - } -}; +```go +func combinationSum3(k int, n int) (ans [][]int) { + t := []int{} + var dfs func(i, s int) + dfs = func(i, s int) { + if s == 0 { + if len(t) == k { + ans = append(ans, slices.Clone(t)) + } + return + } + if i > 9 || i > s || len(t) >= k { + return + } + t = append(t, i) + dfs(i+1, s-i) + t = t[:len(t)-1] + dfs(i+1, s) + } + dfs(1, n) + return +} ``` -```cpp -class Solution { -public: - vector> combinationSum3(int k, int n) { - vector> ans; - for (int mask = 0; mask < 1 << 9; ++mask) { - if (__builtin_popcount(mask) == k) { - int s = 0; - vector t; - for (int i = 0; i < 9; ++i) { - if (mask >> i & 1) { - t.push_back(i + 1); - s += i + 1; - } - } - if (s == n) { - ans.emplace_back(t); - } +```ts +function combinationSum3(k: number, n: number): number[][] { + const ans: number[][] = []; + const t: number[] = []; + const dfs = (i: number, s: number) => { + if (s === 0) { + if (t.length === k) { + ans.push(t.slice()); } + return; } - return ans; - } -}; + if (i > 9 || i > s || t.length >= k) { + return; + } + t.push(i); + dfs(i + 1, s - i); + t.pop(); + dfs(i + 1, s); + }; + dfs(1, n); + return ans; +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -367,44 +246,146 @@ impl Solution { } ``` -### **Go** +```cs +public class Solution { + private List> ans = new List>(); + private List t = new List(); + private int k; -```go -func combinationSum3(k int, n int) (ans [][]int) { - t := []int{} - var dfs func(i, s int) - dfs = func(i, s int) { - if s == 0 { - if len(t) == k { - ans = append(ans, slices.Clone(t)) - } - return - } - if i > 9 || i > s || len(t) >= k { - return - } - t = append(t, i) - dfs(i+1, s-i) - t = t[:len(t)-1] - dfs(i+1, s) - } - dfs(1, n) - return + public IList> CombinationSum3(int k, int n) { + this.k = k; + dfs(1, n); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + if (t.Count == k) { + ans.Add(new List(t)); + } + return; + } + if (i > 9 || i > s || t.Count >= k) { + return; + } + t.Add(i); + dfs(i + 1, s - i); + t.RemoveAt(t.Count - 1); + dfs(i + 1, s); + } } ``` -```go -func combinationSum3(k int, n int) (ans [][]int) { - t := []int{} - var dfs func(i, s int) - dfs = func(i, s int) { - if s == 0 { - if len(t) == k { - ans = append(ans, slices.Clone(t)) - } - return - } - if i > 9 || i > s || len(t) >= k { + + +### 方法二:二进制枚举 + +我们可以用一个长度为 $9$ 的二进制整数表示数字 $1$ 到 $9$ 的选取情况,其中二进制整数的第 $i$ 位表示数字 $i + 1$ 是否被选取,如果第 $i$ 位为 $1$,则表示数字 $i + 1$ 被选取,否则表示数字 $i + 1$ 没有被选取。 + +我们在 $[0, 2^9)$ 范围内枚举二进制整数,对于当前枚举到的二进制整数 $mask$,如果 $mask$ 的二进制表示中 $1$ 的个数为 $k$,且 $mask$ 的二进制表示中 $1$ 所对应的数字之和为 $n$,则说明 $mask$ 对应的数字选取方案是一组答案。我们将 $mask$ 对应的数字选取方案加入答案即可。 + +时间复杂度 $O(2^9 \times 9)$,空间复杂度 $O(k)$。 + +相似题目: + +- [39. 组合总和](/solution/0000-0099/0039.Combination%20Sum/README.md) +- [40. 组合总和 II](/solution/0000-0099/0040.Combination%20Sum%20II/README.md) +- [77. 组合](/solution/0000-0099/0077.Combinations/README.md) + + + +```python +class Solution: + def combinationSum3(self, k: int, n: int) -> List[List[int]]: + def dfs(i: int, s: int): + if s == 0: + if len(t) == k: + ans.append(t[:]) + return + if i > 9 or i > s or len(t) >= k: + return + for j in range(i, 10): + t.append(j) + dfs(j + 1, s - j) + t.pop() + + ans = [] + t = [] + dfs(1, n) + return ans +``` + +```java +class Solution { + private List> ans = new ArrayList<>(); + private List t = new ArrayList<>(); + private int k; + + public List> combinationSum3(int k, int n) { + this.k = k; + dfs(1, n); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + if (t.size() == k) { + ans.add(new ArrayList<>(t)); + } + return; + } + if (i > 9 || i > s || t.size() >= k) { + return; + } + for (int j = i; j <= 9; ++j) { + t.add(j); + dfs(j + 1, s - j); + t.remove(t.size() - 1); + } + } +} +``` + +```cpp +class Solution { +public: + vector> combinationSum3(int k, int n) { + vector> ans; + vector t; + function dfs = [&](int i, int s) { + if (s == 0) { + if (t.size() == k) { + ans.emplace_back(t); + } + return; + } + if (i > 9 || i > s || t.size() >= k) { + return; + } + for (int j = i; j <= 9; ++j) { + t.emplace_back(j); + dfs(j + 1, s - j); + t.pop_back(); + } + }; + dfs(1, n); + return ans; + } +}; +``` + +```go +func combinationSum3(k int, n int) (ans [][]int) { + t := []int{} + var dfs func(i, s int) + dfs = func(i, s int) { + if s == 0 { + if len(t) == k { + ans = append(ans, slices.Clone(t)) + } + return + } + if i > 9 || i > s || len(t) >= k { return } for j := i; j <= 9; j++ { @@ -418,53 +399,6 @@ func combinationSum3(k int, n int) (ans [][]int) { } ``` -```go -func combinationSum3(k int, n int) (ans [][]int) { - for mask := 0; mask < 1<<9; mask++ { - if bits.OnesCount(uint(mask)) == k { - t := []int{} - s := 0 - for i := 0; i < 9; i++ { - if mask>>i&1 == 1 { - s += i + 1 - t = append(t, i+1) - } - } - if s == n { - ans = append(ans, t) - } - } - } - return -} -``` - -### **TypeScript** - -```ts -function combinationSum3(k: number, n: number): number[][] { - const ans: number[][] = []; - const t: number[] = []; - const dfs = (i: number, s: number) => { - if (s === 0) { - if (t.length === k) { - ans.push(t.slice()); - } - return; - } - if (i > 9 || i > s || t.length >= k) { - return; - } - t.push(i); - dfs(i + 1, s - i); - t.pop(); - dfs(i + 1, s); - }; - dfs(1, n); - return ans; -} -``` - ```ts function combinationSum3(k: number, n: number): number[][] { const ans: number[][] = []; @@ -490,39 +424,6 @@ function combinationSum3(k: number, n: number): number[][] { } ``` -```ts -function combinationSum3(k: number, n: number): number[][] { - const ans: number[][] = []; - for (let mask = 0; mask < 1 << 9; ++mask) { - if (bitCount(mask) === k) { - const t: number[] = []; - let s = 0; - for (let i = 0; i < 9; ++i) { - if (mask & (1 << i)) { - t.push(i + 1); - s += i + 1; - } - } - if (s === n) { - ans.push(t); - } - } - } - return ans; -} - -function bitCount(i: number): number { - i = i - ((i >>> 1) & 0x55555555); - i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); - i = (i + (i >>> 4)) & 0x0f0f0f0f; - i = i + (i >>> 8); - i = i + (i >>> 16); - return i & 0x3f; -} -``` - -### **C#** - ```cs public class Solution { private List> ans = new List>(); @@ -545,42 +446,131 @@ public class Solution { if (i > 9 || i > s || t.Count >= k) { return; } - t.Add(i); - dfs(i + 1, s - i); - t.RemoveAt(t.Count - 1); - dfs(i + 1, s); + for (int j = i; j <= 9; ++j) { + t.Add(j); + dfs(j + 1, s - j); + t.RemoveAt(t.Count - 1); + } } } ``` -```cs -public class Solution { - private List> ans = new List>(); - private List t = new List(); - private int k; + - public IList> CombinationSum3(int k, int n) { - this.k = k; - dfs(1, n); +### 方法三 + + + +```python +class Solution: + def combinationSum3(self, k: int, n: int) -> List[List[int]]: + ans = [] + for mask in range(1 << 9): + if mask.bit_count() == k: + t = [i + 1 for i in range(9) if mask >> i & 1] + if sum(t) == n: + ans.append(t) + return ans +``` + +```java +class Solution { + public List> combinationSum3(int k, int n) { + List> ans = new ArrayList<>(); + for (int mask = 0; mask < 1 << 9; ++mask) { + if (Integer.bitCount(mask) == k) { + List t = new ArrayList<>(); + int s = 0; + for (int i = 0; i < 9; ++i) { + if ((mask >> i & 1) == 1) { + s += (i + 1); + t.add(i + 1); + } + } + if (s == n) { + ans.add(t); + } + } + } return ans; } +} +``` - private void dfs(int i, int s) { - if (s == 0) { - if (t.Count == k) { - ans.Add(new List(t)); +```cpp +class Solution { +public: + vector> combinationSum3(int k, int n) { + vector> ans; + for (int mask = 0; mask < 1 << 9; ++mask) { + if (__builtin_popcount(mask) == k) { + int s = 0; + vector t; + for (int i = 0; i < 9; ++i) { + if (mask >> i & 1) { + t.push_back(i + 1); + s += i + 1; + } + } + if (s == n) { + ans.emplace_back(t); + } } - return; } - if (i > 9 || i > s || t.Count >= k) { - return; - } - for (int j = i; j <= 9; ++j) { - t.Add(j); - dfs(j + 1, s - j); - t.RemoveAt(t.Count - 1); + return ans; + } +}; +``` + +```go +func combinationSum3(k int, n int) (ans [][]int) { + for mask := 0; mask < 1<<9; mask++ { + if bits.OnesCount(uint(mask)) == k { + t := []int{} + s := 0 + for i := 0; i < 9; i++ { + if mask>>i&1 == 1 { + s += i + 1 + t = append(t, i+1) + } + } + if s == n { + ans = append(ans, t) + } + } + } + return +} +``` + +```ts +function combinationSum3(k: number, n: number): number[][] { + const ans: number[][] = []; + for (let mask = 0; mask < 1 << 9; ++mask) { + if (bitCount(mask) === k) { + const t: number[] = []; + let s = 0; + for (let i = 0; i < 9; ++i) { + if (mask & (1 << i)) { + t.push(i + 1); + s += i + 1; + } + } + if (s === n) { + ans.push(t); + } } } + return ans; +} + +function bitCount(i: number): number { + i = i - ((i >>> 1) & 0x55555555); + i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); + i = (i + (i >>> 4)) & 0x0f0f0f0f; + i = i + (i >>> 8); + i = i + (i >>> 16); + return i & 0x3f; } ``` @@ -617,10 +607,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0216.Combination Sum III/README_EN.md b/solution/0200-0299/0216.Combination Sum III/README_EN.md index dd1c840610a55..05dc6964fdd7a 100644 --- a/solution/0200-0299/0216.Combination Sum III/README_EN.md +++ b/solution/0200-0299/0216.Combination Sum III/README_EN.md @@ -54,12 +54,10 @@ Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2 ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python class Solution: def combinationSum3(self, k: int, n: int) -> List[List[int]]: @@ -81,41 +79,6 @@ class Solution: return ans ``` -```python -class Solution: - def combinationSum3(self, k: int, n: int) -> List[List[int]]: - def dfs(i: int, s: int): - if s == 0: - if len(t) == k: - ans.append(t[:]) - return - if i > 9 or i > s or len(t) >= k: - return - for j in range(i, 10): - t.append(j) - dfs(j + 1, s - j) - t.pop() - - ans = [] - t = [] - dfs(1, n) - return ans -``` - -```python -class Solution: - def combinationSum3(self, k: int, n: int) -> List[List[int]]: - ans = [] - for mask in range(1 << 9): - if mask.bit_count() == k: - t = [i + 1 for i in range(9) if mask >> i & 1] - if sum(t) == n: - ans.append(t) - return ans -``` - -### **Java** - ```java class Solution { private List> ans = new ArrayList<>(); @@ -146,63 +109,6 @@ class Solution { } ``` -```java -class Solution { - private List> ans = new ArrayList<>(); - private List t = new ArrayList<>(); - private int k; - - public List> combinationSum3(int k, int n) { - this.k = k; - dfs(1, n); - return ans; - } - - private void dfs(int i, int s) { - if (s == 0) { - if (t.size() == k) { - ans.add(new ArrayList<>(t)); - } - return; - } - if (i > 9 || i > s || t.size() >= k) { - return; - } - for (int j = i; j <= 9; ++j) { - t.add(j); - dfs(j + 1, s - j); - t.remove(t.size() - 1); - } - } -} -``` - -```java -class Solution { - public List> combinationSum3(int k, int n) { - List> ans = new ArrayList<>(); - for (int mask = 0; mask < 1 << 9; ++mask) { - if (Integer.bitCount(mask) == k) { - List t = new ArrayList<>(); - int s = 0; - for (int i = 0; i < 9; ++i) { - if ((mask >> i & 1) == 1) { - s += (i + 1); - t.add(i + 1); - } - } - if (s == n) { - ans.add(t); - } - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -230,61 +136,54 @@ public: }; ``` -```cpp -class Solution { -public: - vector> combinationSum3(int k, int n) { - vector> ans; - vector t; - function dfs = [&](int i, int s) { - if (s == 0) { - if (t.size() == k) { - ans.emplace_back(t); - } - return; - } - if (i > 9 || i > s || t.size() >= k) { - return; - } - for (int j = i; j <= 9; ++j) { - t.emplace_back(j); - dfs(j + 1, s - j); - t.pop_back(); - } - }; - dfs(1, n); - return ans; - } -}; +```go +func combinationSum3(k int, n int) (ans [][]int) { + t := []int{} + var dfs func(i, s int) + dfs = func(i, s int) { + if s == 0 { + if len(t) == k { + ans = append(ans, slices.Clone(t)) + } + return + } + if i > 9 || i > s || len(t) >= k { + return + } + t = append(t, i) + dfs(i+1, s-i) + t = t[:len(t)-1] + dfs(i+1, s) + } + dfs(1, n) + return +} ``` -```cpp -class Solution { -public: - vector> combinationSum3(int k, int n) { - vector> ans; - for (int mask = 0; mask < 1 << 9; ++mask) { - if (__builtin_popcount(mask) == k) { - int s = 0; - vector t; - for (int i = 0; i < 9; ++i) { - if (mask >> i & 1) { - t.push_back(i + 1); - s += i + 1; - } - } - if (s == n) { - ans.emplace_back(t); - } +```ts +function combinationSum3(k: number, n: number): number[][] { + const ans: number[][] = []; + const t: number[] = []; + const dfs = (i: number, s: number) => { + if (s === 0) { + if (t.length === k) { + ans.push(t.slice()); } + return; } - return ans; - } -}; + if (i > 9 || i > s || t.length >= k) { + return; + } + t.push(i); + dfs(i + 1, s - i); + t.pop(); + dfs(i + 1, s); + }; + dfs(1, n); + return ans; +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -324,101 +223,144 @@ impl Solution { } ``` -### **Go** +```cs +public class Solution { + private List> ans = new List>(); + private List t = new List(); + private int k; -```go -func combinationSum3(k int, n int) (ans [][]int) { - t := []int{} - var dfs func(i, s int) - dfs = func(i, s int) { - if s == 0 { - if len(t) == k { - ans = append(ans, slices.Clone(t)) - } - return - } - if i > 9 || i > s || len(t) >= k { - return - } - t = append(t, i) - dfs(i+1, s-i) - t = t[:len(t)-1] - dfs(i+1, s) - } - dfs(1, n) - return -} -``` + public IList> CombinationSum3(int k, int n) { + this.k = k; + dfs(1, n); + return ans; + } -```go -func combinationSum3(k int, n int) (ans [][]int) { - t := []int{} - var dfs func(i, s int) - dfs = func(i, s int) { - if s == 0 { - if len(t) == k { - ans = append(ans, slices.Clone(t)) - } - return - } - if i > 9 || i > s || len(t) >= k { - return - } - for j := i; j <= 9; j++ { - t = append(t, j) - dfs(j+1, s-j) - t = t[:len(t)-1] - } - } - dfs(1, n) - return + private void dfs(int i, int s) { + if (s == 0) { + if (t.Count == k) { + ans.Add(new List(t)); + } + return; + } + if (i > 9 || i > s || t.Count >= k) { + return; + } + t.Add(i); + dfs(i + 1, s - i); + t.RemoveAt(t.Count - 1); + dfs(i + 1, s); + } } ``` -```go -func combinationSum3(k int, n int) (ans [][]int) { - for mask := 0; mask < 1<<9; mask++ { - if bits.OnesCount(uint(mask)) == k { - t := []int{} - s := 0 - for i := 0; i < 9; i++ { - if mask>>i&1 == 1 { - s += i + 1 - t = append(t, i+1) - } - } - if s == n { - ans = append(ans, t) - } - } - } - return -} + + +### Solution 2 + + + +```python +class Solution: + def combinationSum3(self, k: int, n: int) -> List[List[int]]: + def dfs(i: int, s: int): + if s == 0: + if len(t) == k: + ans.append(t[:]) + return + if i > 9 or i > s or len(t) >= k: + return + for j in range(i, 10): + t.append(j) + dfs(j + 1, s - j) + t.pop() + + ans = [] + t = [] + dfs(1, n) + return ans ``` -### **TypeScript** +```java +class Solution { + private List> ans = new ArrayList<>(); + private List t = new ArrayList<>(); + private int k; -```ts -function combinationSum3(k: number, n: number): number[][] { - const ans: number[][] = []; - const t: number[] = []; - const dfs = (i: number, s: number) => { - if (s === 0) { - if (t.length === k) { - ans.push(t.slice()); + public List> combinationSum3(int k, int n) { + this.k = k; + dfs(1, n); + return ans; + } + + private void dfs(int i, int s) { + if (s == 0) { + if (t.size() == k) { + ans.add(new ArrayList<>(t)); } return; } - if (i > 9 || i > s || t.length >= k) { + if (i > 9 || i > s || t.size() >= k) { return; } - t.push(i); - dfs(i + 1, s - i); - t.pop(); - dfs(i + 1, s); - }; - dfs(1, n); - return ans; + for (int j = i; j <= 9; ++j) { + t.add(j); + dfs(j + 1, s - j); + t.remove(t.size() - 1); + } + } +} +``` + +```cpp +class Solution { +public: + vector> combinationSum3(int k, int n) { + vector> ans; + vector t; + function dfs = [&](int i, int s) { + if (s == 0) { + if (t.size() == k) { + ans.emplace_back(t); + } + return; + } + if (i > 9 || i > s || t.size() >= k) { + return; + } + for (int j = i; j <= 9; ++j) { + t.emplace_back(j); + dfs(j + 1, s - j); + t.pop_back(); + } + }; + dfs(1, n); + return ans; + } +}; +``` + +```go +func combinationSum3(k int, n int) (ans [][]int) { + t := []int{} + var dfs func(i, s int) + dfs = func(i, s int) { + if s == 0 { + if len(t) == k { + ans = append(ans, slices.Clone(t)) + } + return + } + if i > 9 || i > s || len(t) >= k { + return + } + for j := i; j <= 9; j++ { + t = append(t, j) + dfs(j+1, s-j) + t = t[:len(t)-1] + } + } + dfs(1, n) + return } ``` @@ -447,39 +389,6 @@ function combinationSum3(k: number, n: number): number[][] { } ``` -```ts -function combinationSum3(k: number, n: number): number[][] { - const ans: number[][] = []; - for (let mask = 0; mask < 1 << 9; ++mask) { - if (bitCount(mask) === k) { - const t: number[] = []; - let s = 0; - for (let i = 0; i < 9; ++i) { - if (mask & (1 << i)) { - t.push(i + 1); - s += i + 1; - } - } - if (s === n) { - ans.push(t); - } - } - } - return ans; -} - -function bitCount(i: number): number { - i = i - ((i >>> 1) & 0x55555555); - i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); - i = (i + (i >>> 4)) & 0x0f0f0f0f; - i = i + (i >>> 8); - i = i + (i >>> 16); - return i & 0x3f; -} -``` - -### **C#** - ```cs public class Solution { private List> ans = new List>(); @@ -502,42 +411,131 @@ public class Solution { if (i > 9 || i > s || t.Count >= k) { return; } - t.Add(i); - dfs(i + 1, s - i); - t.RemoveAt(t.Count - 1); - dfs(i + 1, s); + for (int j = i; j <= 9; ++j) { + t.Add(j); + dfs(j + 1, s - j); + t.RemoveAt(t.Count - 1); + } } } ``` -```cs -public class Solution { - private List> ans = new List>(); - private List t = new List(); - private int k; + - public IList> CombinationSum3(int k, int n) { - this.k = k; - dfs(1, n); +### Solution 3 + + + +```python +class Solution: + def combinationSum3(self, k: int, n: int) -> List[List[int]]: + ans = [] + for mask in range(1 << 9): + if mask.bit_count() == k: + t = [i + 1 for i in range(9) if mask >> i & 1] + if sum(t) == n: + ans.append(t) + return ans +``` + +```java +class Solution { + public List> combinationSum3(int k, int n) { + List> ans = new ArrayList<>(); + for (int mask = 0; mask < 1 << 9; ++mask) { + if (Integer.bitCount(mask) == k) { + List t = new ArrayList<>(); + int s = 0; + for (int i = 0; i < 9; ++i) { + if ((mask >> i & 1) == 1) { + s += (i + 1); + t.add(i + 1); + } + } + if (s == n) { + ans.add(t); + } + } + } return ans; } +} +``` - private void dfs(int i, int s) { - if (s == 0) { - if (t.Count == k) { - ans.Add(new List(t)); +```cpp +class Solution { +public: + vector> combinationSum3(int k, int n) { + vector> ans; + for (int mask = 0; mask < 1 << 9; ++mask) { + if (__builtin_popcount(mask) == k) { + int s = 0; + vector t; + for (int i = 0; i < 9; ++i) { + if (mask >> i & 1) { + t.push_back(i + 1); + s += i + 1; + } + } + if (s == n) { + ans.emplace_back(t); + } } - return; } - if (i > 9 || i > s || t.Count >= k) { - return; - } - for (int j = i; j <= 9; ++j) { - t.Add(j); - dfs(j + 1, s - j); - t.RemoveAt(t.Count - 1); + return ans; + } +}; +``` + +```go +func combinationSum3(k int, n int) (ans [][]int) { + for mask := 0; mask < 1<<9; mask++ { + if bits.OnesCount(uint(mask)) == k { + t := []int{} + s := 0 + for i := 0; i < 9; i++ { + if mask>>i&1 == 1 { + s += i + 1 + t = append(t, i+1) + } + } + if s == n { + ans = append(ans, t) + } + } + } + return +} +``` + +```ts +function combinationSum3(k: number, n: number): number[][] { + const ans: number[][] = []; + for (let mask = 0; mask < 1 << 9; ++mask) { + if (bitCount(mask) === k) { + const t: number[] = []; + let s = 0; + for (let i = 0; i < 9; ++i) { + if (mask & (1 << i)) { + t.push(i + 1); + s += i + 1; + } + } + if (s === n) { + ans.push(t); + } } } + return ans; +} + +function bitCount(i: number): number { + i = i - ((i >>> 1) & 0x55555555); + i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); + i = (i + (i >>> 4)) & 0x0f0f0f0f; + i = i + (i >>> 8); + i = i + (i >>> 16); + return i & 0x3f; } ``` @@ -574,10 +572,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0217.Contains Duplicate/README.md b/solution/0200-0299/0217.Contains Duplicate/README.md index c24e10a64997b..e89fbcada9366 100644 --- a/solution/0200-0299/0217.Contains Duplicate/README.md +++ b/solution/0200-0299/0217.Contains Duplicate/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们先对数组 `nums` 进行排序。 @@ -51,34 +49,14 @@ 时间复杂度 $O(n \times \log n)$。其中 $n$ 是数组 `nums` 的长度。 -**方法二:哈希表** - -遍历数组,将出现过的元素记录在哈希表 $s$ 中。若元素第二次出现时,说明数组中存在重复元素,直接返回 `true`。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `nums` 的长度。 - -### **Python3** - - - ```python class Solution: def containsDuplicate(self, nums: List[int]) -> bool: return any(a == b for a, b in pairwise(sorted(nums))) ``` -```python -class Solution: - def containsDuplicate(self, nums: List[int]) -> bool: - return len(set(nums)) < len(nums) -``` - -### **Java** - - - ```java class Solution { public boolean containsDuplicate(int[] nums) { @@ -93,22 +71,6 @@ class Solution { } ``` -```java -class Solution { - public boolean containsDuplicate(int[] nums) { - Set s = new HashSet<>(); - for (int num : nums) { - if (!s.add(num)) { - return true; - } - } - return false; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -124,18 +86,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool containsDuplicate(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - return s.size() < nums.size(); - } -}; -``` - -### **Go** - ```go func containsDuplicate(nums []int) bool { sort.Ints(nums) @@ -148,33 +98,6 @@ func containsDuplicate(nums []int) bool { } ``` -```go -func containsDuplicate(nums []int) bool { - s := map[int]bool{} - for _, v := range nums { - if s[v] { - return true - } - s[v] = true - } - return false -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {boolean} - */ -var containsDuplicate = function (nums) { - return new Set(nums).size !== nums.length; -}; -``` - -### **TypeScript** - ```ts function containsDuplicate(nums: number[]): boolean { nums.sort((a, b) => a - b); @@ -188,14 +111,6 @@ function containsDuplicate(nums: number[]): boolean { } ``` -```ts -function containsDuplicate(nums: number[]): boolean { - return new Set(nums).size !== nums.length; -} -``` - -### **Rust** - ```rust impl Solution { pub fn contains_duplicate(mut nums: Vec) -> bool { @@ -211,16 +126,36 @@ impl Solution { } ``` -```rust -use std::collections::HashSet; -impl Solution { - pub fn contains_duplicate(nums: Vec) -> bool { - nums.iter().collect::>().len() != nums.len() +```js +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function (nums) { + return new Set(nums).size !== nums.length; +}; +``` + +```cs +public class Solution { + public bool ContainsDuplicate(int[] nums) { + return nums.Distinct().Count() < nums.Length; } } ``` -### **C** +```php +class Solution { + /** + * @param Integer[] $nums + * @return Boolean + */ + function containsDuplicate($nums) { + $numsUnique = array_unique($nums); + return count($nums) != count($numsUnique); + } +} +``` ```c int cmp(const void* a, const void* b) { @@ -238,35 +173,74 @@ bool containsDuplicate(int* nums, int numsSize) { } ``` -### **C#** + -```cs -public class Solution { - public bool ContainsDuplicate(int[] nums) { - return nums.Distinct().Count() < nums.Length; +### 方法二:哈希表 + +遍历数组,将出现过的元素记录在哈希表 $s$ 中。若元素第二次出现时,说明数组中存在重复元素,直接返回 `true`。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `nums` 的长度。 + + + +```python +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + return len(set(nums)) < len(nums) +``` + +```java +class Solution { + public boolean containsDuplicate(int[] nums) { + Set s = new HashSet<>(); + for (int num : nums) { + if (!s.add(num)) { + return true; + } + } + return false; } } ``` -### **PHP** - -```php +```cpp class Solution { - /** - * @param Integer[] $nums - * @return Boolean - */ - function containsDuplicate($nums) { - $numsUnique = array_unique($nums); - return count($nums) != count($numsUnique); +public: + bool containsDuplicate(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + return s.size() < nums.size(); } -} +}; ``` -### **...** +```go +func containsDuplicate(nums []int) bool { + s := map[int]bool{} + for _, v := range nums { + if s[v] { + return true + } + s[v] = true + } + return false +} +``` +```ts +function containsDuplicate(nums: number[]): boolean { + return new Set(nums).size !== nums.length; +} ``` +```rust +use std::collections::HashSet; +impl Solution { + pub fn contains_duplicate(nums: Vec) -> bool { + nums.iter().collect::>().len() != nums.len() + } +} ``` + + diff --git a/solution/0200-0299/0217.Contains Duplicate/README_EN.md b/solution/0200-0299/0217.Contains Duplicate/README_EN.md index cde49fa4fdfe8..02778b06c2017 100644 --- a/solution/0200-0299/0217.Contains Duplicate/README_EN.md +++ b/solution/0200-0299/0217.Contains Duplicate/README_EN.md @@ -27,7 +27,7 @@ ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting First, we sort the array `nums`. @@ -37,30 +37,14 @@ Otherwise, when the traversal ends, we return `false`. The time complexity is $O(n \times \log n)$, where $n$ is the length of the array `nums`. -**Solution 2: Hash Table** - -We traverse the array and record the elements that have appeared in the hash table $s$. If an element appears for the second time, it means that there are duplicate elements in the array, and we directly return `true`. - -The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array `nums`. - -### **Python3** - ```python class Solution: def containsDuplicate(self, nums: List[int]) -> bool: return any(a == b for a, b in pairwise(sorted(nums))) ``` -```python -class Solution: - def containsDuplicate(self, nums: List[int]) -> bool: - return len(set(nums)) < len(nums) -``` - -### **Java** - ```java class Solution { public boolean containsDuplicate(int[] nums) { @@ -75,22 +59,6 @@ class Solution { } ``` -```java -class Solution { - public boolean containsDuplicate(int[] nums) { - Set s = new HashSet<>(); - for (int num : nums) { - if (!s.add(num)) { - return true; - } - } - return false; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -106,18 +74,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool containsDuplicate(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - return s.size() < nums.size(); - } -}; -``` - -### **Go** - ```go func containsDuplicate(nums []int) bool { sort.Ints(nums) @@ -130,33 +86,6 @@ func containsDuplicate(nums []int) bool { } ``` -```go -func containsDuplicate(nums []int) bool { - s := map[int]bool{} - for _, v := range nums { - if s[v] { - return true - } - s[v] = true - } - return false -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {boolean} - */ -var containsDuplicate = function (nums) { - return new Set(nums).size !== nums.length; -}; -``` - -### **TypeScript** - ```ts function containsDuplicate(nums: number[]): boolean { nums.sort((a, b) => a - b); @@ -170,14 +99,6 @@ function containsDuplicate(nums: number[]): boolean { } ``` -```ts -function containsDuplicate(nums: number[]): boolean { - return new Set(nums).size !== nums.length; -} -``` - -### **Rust** - ```rust impl Solution { pub fn contains_duplicate(mut nums: Vec) -> bool { @@ -193,16 +114,36 @@ impl Solution { } ``` -```rust -use std::collections::HashSet; -impl Solution { - pub fn contains_duplicate(nums: Vec) -> bool { - nums.iter().collect::>().len() != nums.len() +```js +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function (nums) { + return new Set(nums).size !== nums.length; +}; +``` + +```cs +public class Solution { + public bool ContainsDuplicate(int[] nums) { + return nums.Distinct().Count() < nums.Length; } } ``` -### **C** +```php +class Solution { + /** + * @param Integer[] $nums + * @return Boolean + */ + function containsDuplicate($nums) { + $numsUnique = array_unique($nums); + return count($nums) != count($numsUnique); + } +} +``` ```c int cmp(const void* a, const void* b) { @@ -220,35 +161,74 @@ bool containsDuplicate(int* nums, int numsSize) { } ``` -### **C#** + -```cs -public class Solution { - public bool ContainsDuplicate(int[] nums) { - return nums.Distinct().Count() < nums.Length; +### Solution 2: Hash Table + +We traverse the array and record the elements that have appeared in the hash table $s$. If an element appears for the second time, it means that there are duplicate elements in the array, and we directly return `true`. + +The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array `nums`. + + + +```python +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + return len(set(nums)) < len(nums) +``` + +```java +class Solution { + public boolean containsDuplicate(int[] nums) { + Set s = new HashSet<>(); + for (int num : nums) { + if (!s.add(num)) { + return true; + } + } + return false; } } ``` -### **PHP** - -```php +```cpp class Solution { - /** - * @param Integer[] $nums - * @return Boolean - */ - function containsDuplicate($nums) { - $numsUnique = array_unique($nums); - return count($nums) != count($numsUnique); +public: + bool containsDuplicate(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + return s.size() < nums.size(); } -} +}; ``` -### **...** +```go +func containsDuplicate(nums []int) bool { + s := map[int]bool{} + for _, v := range nums { + if s[v] { + return true + } + s[v] = true + } + return false +} +``` +```ts +function containsDuplicate(nums: number[]): boolean { + return new Set(nums).size !== nums.length; +} ``` +```rust +use std::collections::HashSet; +impl Solution { + pub fn contains_duplicate(nums: Vec) -> bool { + nums.iter().collect::>().len() != nums.len() + } +} ``` + + diff --git a/solution/0200-0299/0218.The Skyline Problem/README.md b/solution/0200-0299/0218.The Skyline Problem/README.md index 632d1e7d668fb..74b7d124d2254 100644 --- a/solution/0200-0299/0218.The Skyline Problem/README.md +++ b/solution/0200-0299/0218.The Skyline Problem/README.md @@ -53,18 +53,12 @@ ## 解法 - - -**方法一:扫描线+优先队列** +### 方法一:扫描线+优先队列 记录下所有建筑物的左右边界线,升序排序之后得到序列 lines。对于每一个边界线 lines[i],找出所有包含 lines[i] 的建筑物,并确保建筑物的左边界小于等于 lines[i],右边界大于 lines[i],则这些建筑物中高度最高的建筑物的高度就是该线轮廓点的高度。可以使用建筑物的高度构建优先队列(大根堆),同时需要注意高度相同的轮廓点需要合并为一个。 -### **Python3** - - - ```python from queue import PriorityQueue @@ -91,9 +85,44 @@ class Solution: return skys ``` -### **Go** +```cpp +class Solution { +public: + vector> getSkyline(vector>& buildings) { + set poss; + map m; + for (auto v : buildings) { + poss.insert(v[0]); + poss.insert(v[1]); + } + + int i = 0; + for (int pos : poss) + m.insert(pair(pos, i++)); + + vector highs(m.size(), 0); + for (auto v : buildings) { + const int b = m[v[0]], e = m[v[1]]; + for (int i = b; i < e; ++i) + highs[i] = max(highs[i], v[2]); + } - + vector> res; + vector mm(poss.begin(), poss.end()); + for (int i = 0; i < highs.size(); ++i) { + if (highs[i] != highs[i + 1]) + res.push_back(pair(mm[i], highs[i])); + else { + const int start = i; + res.push_back(pair(mm[start], highs[i])); + while (highs[i] == highs[i + 1]) + ++i; + } + } + return res; + } +}; +``` ```go type Matrix struct{ left, right, height int } @@ -143,49 +172,6 @@ func getSkyline(buildings [][]int) [][]int { } ``` -### **C++** - -```cpp -class Solution { -public: - vector> getSkyline(vector>& buildings) { - set poss; - map m; - for (auto v : buildings) { - poss.insert(v[0]); - poss.insert(v[1]); - } - - int i = 0; - for (int pos : poss) - m.insert(pair(pos, i++)); - - vector highs(m.size(), 0); - for (auto v : buildings) { - const int b = m[v[0]], e = m[v[1]]; - for (int i = b; i < e; ++i) - highs[i] = max(highs[i], v[2]); - } - - vector> res; - vector mm(poss.begin(), poss.end()); - for (int i = 0; i < highs.size(); ++i) { - if (highs[i] != highs[i + 1]) - res.push_back(pair(mm[i], highs[i])); - else { - const int start = i; - res.push_back(pair(mm[start], highs[i])); - while (highs[i] == highs[i + 1]) - ++i; - } - } - return res; - } -}; -``` - -### **Rust** - ```rust impl Solution { pub fn get_skyline(buildings: Vec>) -> Vec> { @@ -221,10 +207,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0218.The Skyline Problem/README_EN.md b/solution/0200-0299/0218.The Skyline Problem/README_EN.md index 2c03646dbbaec..04b296c89705c 100644 --- a/solution/0200-0299/0218.The Skyline Problem/README_EN.md +++ b/solution/0200-0299/0218.The Skyline Problem/README_EN.md @@ -50,9 +50,9 @@ Figure B shows the skyline formed by those buildings. The red points in figure B ## Solutions - +### Solution 1 -### **Python3** + ```python from queue import PriorityQueue @@ -80,7 +80,44 @@ class Solution: return skys ``` -### **Go** +```cpp +class Solution { +public: + vector> getSkyline(vector>& buildings) { + set poss; + map m; + for (auto v : buildings) { + poss.insert(v[0]); + poss.insert(v[1]); + } + + int i = 0; + for (int pos : poss) + m.insert(pair(pos, i++)); + + vector highs(m.size(), 0); + for (auto v : buildings) { + const int b = m[v[0]], e = m[v[1]]; + for (int i = b; i < e; ++i) + highs[i] = max(highs[i], v[2]); + } + + vector> res; + vector mm(poss.begin(), poss.end()); + for (int i = 0; i < highs.size(); ++i) { + if (highs[i] != highs[i + 1]) + res.push_back(pair(mm[i], highs[i])); + else { + const int start = i; + res.push_back(pair(mm[start], highs[i])); + while (highs[i] == highs[i + 1]) + ++i; + } + } + return res; + } +}; +``` ```go type Matrix struct{ left, right, height int } @@ -130,49 +167,6 @@ func getSkyline(buildings [][]int) [][]int { } ``` -### **C++** - -```cpp -class Solution { -public: - vector> getSkyline(vector>& buildings) { - set poss; - map m; - for (auto v : buildings) { - poss.insert(v[0]); - poss.insert(v[1]); - } - - int i = 0; - for (int pos : poss) - m.insert(pair(pos, i++)); - - vector highs(m.size(), 0); - for (auto v : buildings) { - const int b = m[v[0]], e = m[v[1]]; - for (int i = b; i < e; ++i) - highs[i] = max(highs[i], v[2]); - } - - vector> res; - vector mm(poss.begin(), poss.end()); - for (int i = 0; i < highs.size(); ++i) { - if (highs[i] != highs[i + 1]) - res.push_back(pair(mm[i], highs[i])); - else { - const int start = i; - res.push_back(pair(mm[start], highs[i])); - while (highs[i] == highs[i + 1]) - ++i; - } - } - return res; - } -}; -``` - -### **Rust** - ```rust impl Solution { pub fn get_skyline(buildings: Vec>) -> Vec> { @@ -208,10 +202,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0219.Contains Duplicate II/README.md b/solution/0200-0299/0219.Contains Duplicate II/README.md index 5f32138389a06..81ceb3a827eb0 100644 --- a/solution/0200-0299/0219.Contains Duplicate II/README.md +++ b/solution/0200-0299/0219.Contains Duplicate II/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们用哈希表 $d$ 存放最近遍历到的数以及对应的下标。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: @@ -71,10 +65,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +96,6 @@ public: }; ``` -### **Go** - ```go func containsNearbyDuplicate(nums []int, k int) bool { d := map[int]int{} @@ -123,7 +109,18 @@ func containsNearbyDuplicate(nums []int, k int) bool { } ``` -### **C#** +```ts +function containsNearbyDuplicate(nums: number[], k: number): boolean { + const d: Map = new Map(); + for (let i = 0; i < nums.length; ++i) { + if (d.has(nums[i]) && i - d.get(nums[i])! <= k) { + return true; + } + d.set(nums[i], i); + } + return false; +} +``` ```cs public class Solution { @@ -140,23 +137,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function containsNearbyDuplicate(nums: number[], k: number): boolean { - const d: Map = new Map(); - for (let i = 0; i < nums.length; ++i) { - if (d.has(nums[i]) && i - d.get(nums[i])! <= k) { - return true; - } - d.set(nums[i], i); - } - return false; -} -``` - -### **PHP** - ```php class Solution { /** @@ -178,10 +158,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0219.Contains Duplicate II/README_EN.md b/solution/0200-0299/0219.Contains Duplicate II/README_EN.md index 4ab09d9dcce45..4962fb90fe41a 100644 --- a/solution/0200-0299/0219.Contains Duplicate II/README_EN.md +++ b/solution/0200-0299/0219.Contains Duplicate II/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We use a hash table $d$ to store the nearest index of the number it has visited. @@ -51,8 +51,6 @@ The time complexity is $O(n)$ and the space complexity is $O(n)$. Here $n$ is th -### **Python3** - ```python class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: @@ -64,8 +62,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { @@ -81,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +93,6 @@ public: }; ``` -### **Go** - ```go func containsNearbyDuplicate(nums []int, k int) bool { d := map[int]int{} @@ -114,7 +106,18 @@ func containsNearbyDuplicate(nums []int, k int) bool { } ``` -### **C#** +```ts +function containsNearbyDuplicate(nums: number[], k: number): boolean { + const d: Map = new Map(); + for (let i = 0; i < nums.length; ++i) { + if (d.has(nums[i]) && i - d.get(nums[i])! <= k) { + return true; + } + d.set(nums[i], i); + } + return false; +} +``` ```cs public class Solution { @@ -131,23 +134,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function containsNearbyDuplicate(nums: number[], k: number): boolean { - const d: Map = new Map(); - for (let i = 0; i < nums.length; ++i) { - if (d.has(nums[i]) && i - d.get(nums[i])! <= k) { - return true; - } - d.set(nums[i], i); - } - return false; -} -``` - -### **PHP** - ```php class Solution { /** @@ -169,10 +155,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0220.Contains Duplicate III/README.md b/solution/0200-0299/0220.Contains Duplicate III/README.md index 54dfb7617f710..35c2a50251bf9 100644 --- a/solution/0200-0299/0220.Contains Duplicate III/README.md +++ b/solution/0200-0299/0220.Contains Duplicate III/README.md @@ -53,9 +53,7 @@ abs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0 ## 解法 - - -**方法一:滑动窗口 + 有序集合** +### 方法一:滑动窗口 + 有序集合 我们维护一个大小为 $k$ 的滑动窗口,窗口中的元素保持有序。 @@ -65,10 +63,6 @@ abs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0 -### **Python3** - - - ```python from sortedcontainers import SortedSet @@ -88,10 +82,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int indexDiff, int valueDiff) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { n := len(nums) @@ -155,36 +141,6 @@ func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { } ``` -### **C#** - -```cs -public class Solution { - public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t) { - if (k <= 0 || t < 0) return false; - var index = new SortedList(); - for (int i = 0; i < nums.Length; ++i) { - if (index.ContainsKey(nums[i])) { - return true; - } - index.Add(nums[i], null); - var j = index.IndexOfKey(nums[i]); - if (j > 0 && (long)nums[i] - index.Keys[j - 1] <= t) { - return true; - } - if (j < index.Count - 1 && (long)index.Keys[j + 1] - nums[i] <= t) { - return true; - } - if (index.Count > k) { - index.Remove(nums[i - k]); - } - } - return false; - } -} -``` - -### **TypeScript** - ```ts function containsNearbyAlmostDuplicate( nums: number[], @@ -846,10 +802,32 @@ class TreeMultiSet { } ``` -### **...** - -``` - +```cs +public class Solution { + public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t) { + if (k <= 0 || t < 0) return false; + var index = new SortedList(); + for (int i = 0; i < nums.Length; ++i) { + if (index.ContainsKey(nums[i])) { + return true; + } + index.Add(nums[i], null); + var j = index.IndexOfKey(nums[i]); + if (j > 0 && (long)nums[i] - index.Keys[j - 1] <= t) { + return true; + } + if (j < index.Count - 1 && (long)index.Keys[j + 1] - nums[i] <= t) { + return true; + } + if (index.Count > k) { + index.Remove(nums[i - k]); + } + } + return false; + } +} ``` + + diff --git a/solution/0200-0299/0220.Contains Duplicate III/README_EN.md b/solution/0200-0299/0220.Contains Duplicate III/README_EN.md index 8bebf53420607..bde265c9df35c 100644 --- a/solution/0200-0299/0220.Contains Duplicate III/README_EN.md +++ b/solution/0200-0299/0220.Contains Duplicate III/README_EN.md @@ -49,7 +49,7 @@ abs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0 ## Solutions -**Solution 1: Sliding Window + Ordered Set** +### Solution 1: Sliding Window + Ordered Set We maintain a sliding window of size $k$, and the elements in the window are kept in order. @@ -59,8 +59,6 @@ The time complexity is $O(n \times \log k)$, where $n$ is the length of the arra -### **Python3** - ```python from sortedcontainers import SortedSet @@ -80,8 +78,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int indexDiff, int valueDiff) { @@ -101,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +113,6 @@ public: }; ``` -### **Go** - ```go func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { n := len(nums) @@ -145,36 +137,6 @@ func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { } ``` -### **C#** - -```cs -public class Solution { - public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t) { - if (k <= 0 || t < 0) return false; - var index = new SortedList(); - for (int i = 0; i < nums.Length; ++i) { - if (index.ContainsKey(nums[i])) { - return true; - } - index.Add(nums[i], null); - var j = index.IndexOfKey(nums[i]); - if (j > 0 && (long)nums[i] - index.Keys[j - 1] <= t) { - return true; - } - if (j < index.Count - 1 && (long)index.Keys[j + 1] - nums[i] <= t) { - return true; - } - if (index.Count > k) { - index.Remove(nums[i - k]); - } - } - return false; - } -} -``` - -### **TypeScript** - ```ts function containsNearbyAlmostDuplicate( nums: number[], @@ -836,10 +798,32 @@ class TreeMultiSet { } ``` -### **...** - -``` - +```cs +public class Solution { + public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t) { + if (k <= 0 || t < 0) return false; + var index = new SortedList(); + for (int i = 0; i < nums.Length; ++i) { + if (index.ContainsKey(nums[i])) { + return true; + } + index.Add(nums[i], null); + var j = index.IndexOfKey(nums[i]); + if (j > 0 && (long)nums[i] - index.Keys[j - 1] <= t) { + return true; + } + if (j < index.Count - 1 && (long)index.Keys[j + 1] - nums[i] <= t) { + return true; + } + if (index.Count > k) { + index.Remove(nums[i - k]); + } + } + return false; + } +} ``` + + diff --git a/solution/0200-0299/0221.Maximal Square/README.md b/solution/0200-0299/0221.Maximal Square/README.md index 44da08349d55b..d7a6c49842883 100644 --- a/solution/0200-0299/0221.Maximal Square/README.md +++ b/solution/0200-0299/0221.Maximal Square/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $dp[i + 1][j + 1]$ 表示以下标 $(i, j)$ 作为正方形右下角的最大正方形边长。答案为所有 $dp[i + 1][j + 1]$ 中的最大值。 @@ -64,10 +62,6 @@ $$ -### **Python3** - - - ```python class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: @@ -82,10 +76,6 @@ class Solution: return mx * mx ``` -### **Java** - - - ```java class Solution { public int maximalSquare(char[][] matrix) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func maximalSquare(matrix [][]byte) int { m, n := len(matrix), len(matrix[0]) @@ -149,8 +135,6 @@ func maximalSquare(matrix [][]byte) int { } ``` -### **C#** - ```cs public class Solution { public int MaximalSquare(char[][] matrix) { @@ -173,10 +157,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0221.Maximal Square/README_EN.md b/solution/0200-0299/0221.Maximal Square/README_EN.md index 0456a72b08b8e..e1b98998b13d4 100644 --- a/solution/0200-0299/0221.Maximal Square/README_EN.md +++ b/solution/0200-0299/0221.Maximal Square/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $dp[i + 1][j + 1]$ as the maximum square side length with the lower right corner at index $(i, j)$. The answer is the maximum value among all $dp[i + 1][j + 1]$. @@ -58,8 +58,6 @@ The time complexity is $O(m\times n)$, and the space complexity is $O(m\times n) -### **Python3** - ```python class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: @@ -74,8 +72,6 @@ class Solution: return mx * mx ``` -### **Java** - ```java class Solution { public int maximalSquare(char[][] matrix) { @@ -95,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func maximalSquare(matrix [][]byte) int { m, n := len(matrix), len(matrix[0]) @@ -139,8 +131,6 @@ func maximalSquare(matrix [][]byte) int { } ``` -### **C#** - ```cs public class Solution { public int MaximalSquare(char[][] matrix) { @@ -163,10 +153,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0222.Count Complete Tree Nodes/README.md b/solution/0200-0299/0222.Count Complete Tree Nodes/README.md index ebc6c9921e1e4..e349a861a1889 100644 --- a/solution/0200-0299/0222.Count Complete Tree Nodes/README.md +++ b/solution/0200-0299/0222.Count Complete Tree Nodes/README.md @@ -49,35 +49,14 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 递归遍历整棵树,统计结点个数。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为树的结点个数。 -**方法二:二分查找** - -对于此题,我们还可以利用完全二叉树的特点,设计一个更快的算法。 - -完全二叉树的特点:叶子结点只能出现在最下层和次下层,且最下层的叶子结点集中在树的左部。需要注意的是,满二叉树肯定是完全二叉树,而完全二叉树不一定是满二叉树。 - -若满二叉树的层数为 $h$,则总结点数为 $2^h - 1$。 - -我们可以先对 $root$ 的左右子树进行高度统计,分别记为 $left$ 和 $right$。 - -1. 若 $left = right$,说明左子树是一颗满二叉树,那么左子树的结点总数为 $2^{left} - 1$,加上 $root$ 结点,就是 $2^{left}$,然后递归统计右子树即可。 -1. 若 $left \gt right$,说明右子树是一个满二叉树,那么右子树的结点总数为 $2^{right} - 1$,加上 $root$ 结点,就是 $2^{right}$,然后递归统计左子树即可。 - -时间复杂度 $O(\log^2 n)$。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -92,34 +71,6 @@ class Solution: return 1 + self.countNodes(root.left) + self.countNodes(root.right) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def countNodes(self, root: Optional[TreeNode]) -> int: - def depth(root): - d = 0 - while root: - d += 1 - root = root.left - return d - - if root is None: - return 0 - left, right = depth(root.left), depth(root.right) - if left == right: - return (1 << left) + self.countNodes(root.right) - return (1 << right) + self.countNodes(root.left) -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -146,6 +97,160 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int countNodes(TreeNode* root) { + if (!root) { + return 0; + } + return 1 + countNodes(root->left) + countNodes(root->right); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func countNodes(root *TreeNode) int { + if root == nil { + return 0 + } + return 1 + countNodes(root.Left) + countNodes(root.Right) +} +``` + +```rust +use std::cell::RefCell; +use std::rc::Rc; + +impl Solution { + pub fn count_nodes(root: Option>>) -> i32 { + if let Some(node) = root { + let node = node.borrow(); + let left = Self::depth(&node.left); + let right = Self::depth(&node.right); + if left == right { + Self::count_nodes(node.right.clone()) + (1 << left) + } else { + Self::count_nodes(node.left.clone()) + (1 << right) + } + } else { + 0 + } + } + + fn depth(root: &Option>>) -> i32 { + if let Some(node) = root { Self::depth(&node.borrow().left) + 1 } else { 0 } + } +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var countNodes = function (root) { + if (!root) { + return 0; + } + return 1 + countNodes(root.left) + countNodes(root.right); +}; +``` + +```cs +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public int CountNodes(TreeNode root) { + if (root == null) { + return 0; + } + return 1 + CountNodes(root.left) + CountNodes(root.right); + } +} +``` + + + +### 方法二:二分查找 + +对于此题,我们还可以利用完全二叉树的特点,设计一个更快的算法。 + +完全二叉树的特点:叶子结点只能出现在最下层和次下层,且最下层的叶子结点集中在树的左部。需要注意的是,满二叉树肯定是完全二叉树,而完全二叉树不一定是满二叉树。 + +若满二叉树的层数为 $h$,则总结点数为 $2^h - 1$。 + +我们可以先对 $root$ 的左右子树进行高度统计,分别记为 $left$ 和 $right$。 + +1. 若 $left = right$,说明左子树是一颗满二叉树,那么左子树的结点总数为 $2^{left} - 1$,加上 $root$ 结点,就是 $2^{left}$,然后递归统计右子树即可。 +1. 若 $left \gt right$,说明右子树是一个满二叉树,那么右子树的结点总数为 $2^{right} - 1$,加上 $root$ 结点,就是 $2^{right}$,然后递归统计左子树即可。 + +时间复杂度 $O(\log^2 n)$。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def countNodes(self, root: Optional[TreeNode]) -> int: + def depth(root): + d = 0 + while root: + d += 1 + root = root.left + return d + + if root is None: + return 0 + left, right = depth(root.left), depth(root.right) + if left == right: + return (1 << left) + self.countNodes(root.right) + return (1 << right) + self.countNodes(root.left) +``` + ```java /** * Definition for a binary tree node. @@ -185,31 +290,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int countNodes(TreeNode* root) { - if (!root) { - return 0; - } - return 1 + countNodes(root->left) + countNodes(root->right); - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -246,25 +326,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func countNodes(root *TreeNode) int { - if root == nil { - return 0 - } - return 1 + countNodes(root.Left) + countNodes(root.Right) -} -``` - ```go /** * Definition for a binary tree node. @@ -293,29 +354,6 @@ func depth(root *TreeNode) (d int) { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number} - */ -var countNodes = function (root) { - if (!root) { - return 0; - } - return 1 + countNodes(root.left) + countNodes(root.right); -}; -``` - ```js /** * Definition for a binary tree node. @@ -349,32 +387,6 @@ var countNodes = function (root) { }; ``` -### **C#** - -```cs -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -public class Solution { - public int CountNodes(TreeNode root) { - if (root == null) { - return 0; - } - return 1 + CountNodes(root.left) + CountNodes(root.right); - } -} -``` - ```cs /** * Definition for a binary tree node. @@ -412,38 +424,6 @@ public class Solution { } ``` -### **Rust** - -```rust -use std::cell::RefCell; -use std::rc::Rc; - -impl Solution { - pub fn count_nodes(root: Option>>) -> i32 { - if let Some(node) = root { - let node = node.borrow(); - let left = Self::depth(&node.left); - let right = Self::depth(&node.right); - if left == right { - Self::count_nodes(node.right.clone()) + (1 << left) - } else { - Self::count_nodes(node.left.clone()) + (1 << right) - } - } else { - 0 - } - } - - fn depth(root: &Option>>) -> i32 { - if let Some(node) = root { Self::depth(&node.borrow().left) + 1 } else { 0 } - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0222.Count Complete Tree Nodes/README_EN.md b/solution/0200-0299/0222.Count Complete Tree Nodes/README_EN.md index e6104a8cf22c5..20e27e258373a 100644 --- a/solution/0200-0299/0222.Count Complete Tree Nodes/README_EN.md +++ b/solution/0200-0299/0222.Count Complete Tree Nodes/README_EN.md @@ -43,31 +43,14 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion We recursively traverse the entire tree and count the number of nodes. The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the tree. -**Solution 2: Binary Search** - -For this problem, we can also take advantage of the characteristics of a complete binary tree to design a faster algorithm. - -Characteristics of a complete binary tree: leaf nodes can only appear on the bottom and second-to-bottom layers, and the leaf nodes on the bottom layer are concentrated on the left side of the tree. It should be noted that a full binary tree is definitely a complete binary tree, but a complete binary tree is not necessarily a full binary tree. - -If the number of layers in a full binary tree is $h$, then the total number of nodes is $2^h - 1$. - -We first count the heights of the left and right subtrees of $root$, denoted as $left$ and $right$. - -1. If $left = right$, it means that the left subtree is a full binary tree, so the total number of nodes in the left subtree is $2^{left} - 1$. Plus the $root$ node, it is $2^{left}$. Then we recursively count the right subtree. -1. If $left > right$, it means that the right subtree is a full binary tree, so the total number of nodes in the right subtree is $2^{right} - 1$. Plus the $root$ node, it is $2^{right}$. Then we recursively count the left subtree. - -The time complexity is $O(\log^2 n)$. - -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -82,32 +65,6 @@ class Solution: return 1 + self.countNodes(root.left) + self.countNodes(root.right) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def countNodes(self, root: Optional[TreeNode]) -> int: - def depth(root): - d = 0 - while root: - d += 1 - root = root.left - return d - - if root is None: - return 0 - left, right = depth(root.left), depth(root.right) - if left == right: - return (1 << left) + self.countNodes(root.right) - return (1 << right) + self.countNodes(root.left) -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -134,6 +91,160 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int countNodes(TreeNode* root) { + if (!root) { + return 0; + } + return 1 + countNodes(root->left) + countNodes(root->right); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func countNodes(root *TreeNode) int { + if root == nil { + return 0 + } + return 1 + countNodes(root.Left) + countNodes(root.Right) +} +``` + +```rust +use std::cell::RefCell; +use std::rc::Rc; + +impl Solution { + pub fn count_nodes(root: Option>>) -> i32 { + if let Some(node) = root { + let node = node.borrow(); + let left = Self::depth(&node.left); + let right = Self::depth(&node.right); + if left == right { + Self::count_nodes(node.right.clone()) + (1 << left) + } else { + Self::count_nodes(node.left.clone()) + (1 << right) + } + } else { + 0 + } + } + + fn depth(root: &Option>>) -> i32 { + if let Some(node) = root { Self::depth(&node.borrow().left) + 1 } else { 0 } + } +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var countNodes = function (root) { + if (!root) { + return 0; + } + return 1 + countNodes(root.left) + countNodes(root.right); +}; +``` + +```cs +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public int CountNodes(TreeNode root) { + if (root == null) { + return 0; + } + return 1 + CountNodes(root.left) + CountNodes(root.right); + } +} +``` + + + +### Solution 2: Binary Search + +For this problem, we can also take advantage of the characteristics of a complete binary tree to design a faster algorithm. + +Characteristics of a complete binary tree: leaf nodes can only appear on the bottom and second-to-bottom layers, and the leaf nodes on the bottom layer are concentrated on the left side of the tree. It should be noted that a full binary tree is definitely a complete binary tree, but a complete binary tree is not necessarily a full binary tree. + +If the number of layers in a full binary tree is $h$, then the total number of nodes is $2^h - 1$. + +We first count the heights of the left and right subtrees of $root$, denoted as $left$ and $right$. + +1. If $left = right$, it means that the left subtree is a full binary tree, so the total number of nodes in the left subtree is $2^{left} - 1$. Plus the $root$ node, it is $2^{left}$. Then we recursively count the right subtree. +1. If $left > right$, it means that the right subtree is a full binary tree, so the total number of nodes in the right subtree is $2^{right} - 1$. Plus the $root$ node, it is $2^{right}$. Then we recursively count the left subtree. + +The time complexity is $O(\log^2 n)$. + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def countNodes(self, root: Optional[TreeNode]) -> int: + def depth(root): + d = 0 + while root: + d += 1 + root = root.left + return d + + if root is None: + return 0 + left, right = depth(root.left), depth(root.right) + if left == right: + return (1 << left) + self.countNodes(root.right) + return (1 << right) + self.countNodes(root.left) +``` + ```java /** * Definition for a binary tree node. @@ -173,31 +284,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int countNodes(TreeNode* root) { - if (!root) { - return 0; - } - return 1 + countNodes(root->left) + countNodes(root->right); - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -234,25 +320,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func countNodes(root *TreeNode) int { - if root == nil { - return 0 - } - return 1 + countNodes(root.Left) + countNodes(root.Right) -} -``` - ```go /** * Definition for a binary tree node. @@ -281,29 +348,6 @@ func depth(root *TreeNode) (d int) { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number} - */ -var countNodes = function (root) { - if (!root) { - return 0; - } - return 1 + countNodes(root.left) + countNodes(root.right); -}; -``` - ```js /** * Definition for a binary tree node. @@ -337,32 +381,6 @@ var countNodes = function (root) { }; ``` -### **C#** - -```cs -/** - * Definition for a binary tree node. - * public class TreeNode { - * public int val; - * public TreeNode left; - * public TreeNode right; - * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -public class Solution { - public int CountNodes(TreeNode root) { - if (root == null) { - return 0; - } - return 1 + CountNodes(root.left) + CountNodes(root.right); - } -} -``` - ```cs /** * Definition for a binary tree node. @@ -400,38 +418,6 @@ public class Solution { } ``` -### **Rust** - -```rust -use std::cell::RefCell; -use std::rc::Rc; - -impl Solution { - pub fn count_nodes(root: Option>>) -> i32 { - if let Some(node) = root { - let node = node.borrow(); - let left = Self::depth(&node.left); - let right = Self::depth(&node.right); - if left == right { - Self::count_nodes(node.right.clone()) + (1 << left) - } else { - Self::count_nodes(node.left.clone()) + (1 << right) - } - } else { - 0 - } - } - - fn depth(root: &Option>>) -> i32 { - if let Some(node) = root { Self::depth(&node.borrow().left) + 1 } else { 0 } - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0223.Rectangle Area/README.md b/solution/0200-0299/0223.Rectangle Area/README.md index eba85577741d8..5051ab40a91c0 100644 --- a/solution/0200-0299/0223.Rectangle Area/README.md +++ b/solution/0200-0299/0223.Rectangle Area/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:计算重叠面积** +### 方法一:计算重叠面积 我们先计算出两个矩形各自的面积,记为 $a$ 和 $b$,然后计算重叠的宽度 $width$ 和高度 $height$,那么重叠的面积为 $max(width, 0) \times max(height, 0)$,最后将 $a$, $b$ 和重叠面积相减即可。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def computeArea( @@ -77,10 +71,6 @@ class Solution: return a + b - max(height, 0) * max(width, 0) ``` -### **Java** - - - ```java class Solution { public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +96,6 @@ public: }; ``` -### **Go** - ```go func computeArea(ax1 int, ay1 int, ax2 int, ay2 int, bx1 int, by1 int, bx2 int, by2 int) int { a := (ax2 - ax1) * (ay2 - ay1) @@ -120,8 +106,6 @@ func computeArea(ax1 int, ay1 int, ax2 int, ay2 int, bx1 int, by1 int, bx2 int, } ``` -### **TypeScript** - ```ts function computeArea( ax1: number, @@ -141,8 +125,6 @@ function computeArea( } ``` -### **C#** - ```cs public class Solution { public int ComputeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { @@ -155,10 +137,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0223.Rectangle Area/README_EN.md b/solution/0200-0299/0223.Rectangle Area/README_EN.md index 05808907edecc..eb3630fa35361 100644 --- a/solution/0200-0299/0223.Rectangle Area/README_EN.md +++ b/solution/0200-0299/0223.Rectangle Area/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: Calculate Overlapping Area** +### Solution 1: Calculate Overlapping Area First, we calculate the area of the two rectangles separately, denoted as $a$ and $b$. Then we calculate the overlapping width $width$ and height $height$. The overlapping area is $max(width, 0) \times max(height, 0)$. Finally, we subtract the overlapping area from $a$ and $b$. @@ -45,8 +45,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def computeArea( @@ -67,8 +65,6 @@ class Solution: return a + b - max(height, 0) * max(width, 0) ``` -### **Java** - ```java class Solution { public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { @@ -81,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +90,6 @@ public: }; ``` -### **Go** - ```go func computeArea(ax1 int, ay1 int, ax2 int, ay2 int, bx1 int, by1 int, bx2 int, by2 int) int { a := (ax2 - ax1) * (ay2 - ay1) @@ -108,8 +100,6 @@ func computeArea(ax1 int, ay1 int, ax2 int, ay2 int, bx1 int, by1 int, bx2 int, } ``` -### **TypeScript** - ```ts function computeArea( ax1: number, @@ -129,8 +119,6 @@ function computeArea( } ``` -### **C#** - ```cs public class Solution { public int ComputeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { @@ -143,10 +131,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0224.Basic Calculator/README.md b/solution/0200-0299/0224.Basic Calculator/README.md index a0a54faa748bf..9d89fbd7c018f 100644 --- a/solution/0200-0299/0224.Basic Calculator/README.md +++ b/solution/0200-0299/0224.Basic Calculator/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 我们用一个栈 $stk$ 来保存当前的计算结果和操作符,用一个变量 $sign$ 保存当前的符号,变量 $ans$ 保存最终的计算结果。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def calculate(self, s: str) -> int: @@ -102,10 +96,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int calculate(String s) { @@ -142,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +170,6 @@ public: }; ``` -### **Go** - ```go func calculate(s string) (ans int) { stk := []int{} @@ -219,8 +205,6 @@ func calculate(s string) (ans int) { } ``` -### **TypeScript** - ```ts function calculate(s: string): number { const stk: number[] = []; @@ -257,8 +241,6 @@ function calculate(s: string): number { } ``` -### **C#** - ```cs public class Solution { public int Calculate(string s) { @@ -297,10 +279,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0224.Basic Calculator/README_EN.md b/solution/0200-0299/0224.Basic Calculator/README_EN.md index a8ef63b124ac6..0f0241fd94f6d 100644 --- a/solution/0200-0299/0224.Basic Calculator/README_EN.md +++ b/solution/0200-0299/0224.Basic Calculator/README_EN.md @@ -45,7 +45,7 @@ ## Solutions -**Solution 1: Stack** +### Solution 1: Stack We use a stack $stk$ to save the current calculation result and operator, a variable $sign$ to save the current sign, and a variable $ans$ to save the final calculation result. @@ -63,8 +63,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is -### **Python3** - ```python class Solution: def calculate(self, s: str) -> int: @@ -94,8 +92,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int calculate(String s) { @@ -132,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -172,8 +166,6 @@ public: }; ``` -### **Go** - ```go func calculate(s string) (ans int) { stk := []int{} @@ -209,8 +201,6 @@ func calculate(s string) (ans int) { } ``` -### **TypeScript** - ```ts function calculate(s: string): number { const stk: number[] = []; @@ -247,8 +237,6 @@ function calculate(s: string): number { } ``` -### **C#** - ```cs public class Solution { public int Calculate(string s) { @@ -287,10 +275,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0225.Implement Stack using Queues/README.md b/solution/0200-0299/0225.Implement Stack using Queues/README.md index e68016ceb4fb2..c6223b2ee1866 100644 --- a/solution/0200-0299/0225.Implement Stack using Queues/README.md +++ b/solution/0200-0299/0225.Implement Stack using Queues/README.md @@ -62,9 +62,7 @@ myStack.empty(); // 返回 False ## 解法 - - -**方法一:两个队列** +### 方法一:两个队列 我们使用两个队列 $q_1$ 和 $q_2$,其中 $q_1$ 用于存储栈中的元素,而 $q_2$ 用于辅助实现栈的操作。 @@ -77,10 +75,6 @@ myStack.empty(); // 返回 False -### **Python3** - - - ```python class MyStack: def __init__(self): @@ -111,10 +105,6 @@ class MyStack: # param_4 = obj.empty() ``` -### **Java** - - - ```java import java.util.Deque; @@ -158,8 +148,6 @@ class MyStack { */ ``` -### **C++** - ```cpp class MyStack { public: @@ -204,62 +192,6 @@ private: */ ``` -### **Rust** - -```rust -use std::collections::VecDeque; - -struct MyStack { - /// There could only be two status at all time - /// 1. One contains N elements, the other is empty - /// 2. One contains N - 1 elements, the other contains exactly 1 element - q_1: VecDeque, - q_2: VecDeque, - // Either 1 or 2, originally begins from 1 - index: i32, -} - -impl MyStack { - fn new() -> Self { - Self { - q_1: VecDeque::new(), - q_2: VecDeque::new(), - index: 1, - } - } - - fn move_data(&mut self) { - // Always move from q1 to q2 - assert!(self.q_2.len() == 1); - while !self.q_1.is_empty() { - self.q_2.push_back(self.q_1.pop_front().unwrap()); - } - let tmp = self.q_1.clone(); - self.q_1 = self.q_2.clone(); - self.q_2 = tmp; - } - - fn push(&mut self, x: i32) { - self.q_2.push_back(x); - self.move_data(); - } - - fn pop(&mut self) -> i32 { - self.q_1.pop_front().unwrap() - } - - fn top(&mut self) -> i32 { - *self.q_1.front().unwrap() - } - - fn empty(&self) -> bool { - self.q_1.is_empty() - } -} -``` - -### **Go** - ```go type MyStack struct { q1 []int @@ -303,8 +235,6 @@ func (this *MyStack) Empty() bool { */ ``` -### **TypeScript** - ```ts class MyStack { q1: number[] = []; @@ -343,10 +273,58 @@ class MyStack { */ ``` -### **...** +```rust +use std::collections::VecDeque; -``` +struct MyStack { + /// There could only be two status at all time + /// 1. One contains N elements, the other is empty + /// 2. One contains N - 1 elements, the other contains exactly 1 element + q_1: VecDeque, + q_2: VecDeque, + // Either 1 or 2, originally begins from 1 + index: i32, +} + +impl MyStack { + fn new() -> Self { + Self { + q_1: VecDeque::new(), + q_2: VecDeque::new(), + index: 1, + } + } + fn move_data(&mut self) { + // Always move from q1 to q2 + assert!(self.q_2.len() == 1); + while !self.q_1.is_empty() { + self.q_2.push_back(self.q_1.pop_front().unwrap()); + } + let tmp = self.q_1.clone(); + self.q_1 = self.q_2.clone(); + self.q_2 = tmp; + } + + fn push(&mut self, x: i32) { + self.q_2.push_back(x); + self.move_data(); + } + + fn pop(&mut self) -> i32 { + self.q_1.pop_front().unwrap() + } + + fn top(&mut self) -> i32 { + *self.q_1.front().unwrap() + } + + fn empty(&self) -> bool { + self.q_1.is_empty() + } +} ``` + + diff --git a/solution/0200-0299/0225.Implement Stack using Queues/README_EN.md b/solution/0200-0299/0225.Implement Stack using Queues/README_EN.md index 23c1d86d92681..e2e1f978ded81 100644 --- a/solution/0200-0299/0225.Implement Stack using Queues/README_EN.md +++ b/solution/0200-0299/0225.Implement Stack using Queues/README_EN.md @@ -55,7 +55,7 @@ myStack.empty(); // return False ## Solutions -**Solution 1: Two Queues** +### Solution 1: Two Queues We use two queues $q_1$ and $q_2$, where $q_1$ is used to store the elements in the stack, and $q_2$ is used to assist in implementing the stack operations. @@ -68,8 +68,6 @@ The space complexity is $O(n)$, where $n$ is the number of elements in the stack -### **Python3** - ```python class MyStack: def __init__(self): @@ -100,8 +98,6 @@ class MyStack: # param_4 = obj.empty() ``` -### **Java** - ```java import java.util.Deque; @@ -145,8 +141,6 @@ class MyStack { */ ``` -### **C++** - ```cpp class MyStack { public: @@ -191,62 +185,6 @@ private: */ ``` -### **Rust** - -```rust -use std::collections::VecDeque; - -struct MyStack { - /// There could only be two status at all time - /// 1. One contains N elements, the other is empty - /// 2. One contains N - 1 elements, the other contains exactly 1 element - q_1: VecDeque, - q_2: VecDeque, - // Either 1 or 2, originally begins from 1 - index: i32, -} - -impl MyStack { - fn new() -> Self { - Self { - q_1: VecDeque::new(), - q_2: VecDeque::new(), - index: 1, - } - } - - fn move_data(&mut self) { - // Always move from q1 to q2 - assert!(self.q_2.len() == 1); - while !self.q_1.is_empty() { - self.q_2.push_back(self.q_1.pop_front().unwrap()); - } - let tmp = self.q_1.clone(); - self.q_1 = self.q_2.clone(); - self.q_2 = tmp; - } - - fn push(&mut self, x: i32) { - self.q_2.push_back(x); - self.move_data(); - } - - fn pop(&mut self) -> i32 { - self.q_1.pop_front().unwrap() - } - - fn top(&mut self) -> i32 { - *self.q_1.front().unwrap() - } - - fn empty(&self) -> bool { - self.q_1.is_empty() - } -} -``` - -### **Go** - ```go type MyStack struct { q1 []int @@ -290,8 +228,6 @@ func (this *MyStack) Empty() bool { */ ``` -### **TypeScript** - ```ts class MyStack { q1: number[] = []; @@ -330,10 +266,58 @@ class MyStack { */ ``` -### **...** +```rust +use std::collections::VecDeque; -``` +struct MyStack { + /// There could only be two status at all time + /// 1. One contains N elements, the other is empty + /// 2. One contains N - 1 elements, the other contains exactly 1 element + q_1: VecDeque, + q_2: VecDeque, + // Either 1 or 2, originally begins from 1 + index: i32, +} + +impl MyStack { + fn new() -> Self { + Self { + q_1: VecDeque::new(), + q_2: VecDeque::new(), + index: 1, + } + } + + fn move_data(&mut self) { + // Always move from q1 to q2 + assert!(self.q_2.len() == 1); + while !self.q_1.is_empty() { + self.q_2.push_back(self.q_1.pop_front().unwrap()); + } + let tmp = self.q_1.clone(); + self.q_1 = self.q_2.clone(); + self.q_2 = tmp; + } + + fn push(&mut self, x: i32) { + self.q_2.push_back(x); + self.move_data(); + } + fn pop(&mut self) -> i32 { + self.q_1.pop_front().unwrap() + } + + fn top(&mut self) -> i32 { + *self.q_1.front().unwrap() + } + + fn empty(&self) -> bool { + self.q_1.is_empty() + } +} ``` + + diff --git a/solution/0200-0299/0226.Invert Binary Tree/README.md b/solution/0200-0299/0226.Invert Binary Tree/README.md index 954f3e7c44772..cd1c17bef5d92 100644 --- a/solution/0200-0299/0226.Invert Binary Tree/README.md +++ b/solution/0200-0299/0226.Invert Binary Tree/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 递归的思路很简单,就是交换当前节点的左右子树,然后递归地交换当前节点的左右子树。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -80,26 +74,6 @@ class Solution: return root ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: - if root is None: - return None - l, r = self.invertTree(root.left), self.invertTree(root.right) - root.left, root.right = r, l - return root -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -135,38 +109,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public TreeNode invertTree(TreeNode root) { - if (root == null) { - return null; - } - TreeNode l = invertTree(root.left); - TreeNode r = invertTree(root.right); - root.left = r; - root.right = l; - return root; - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -196,34 +138,58 @@ public: }; ``` -```cpp +```go /** * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } */ -class Solution { -public: - TreeNode* invertTree(TreeNode* root) { - if (!root) { - return root; - } - TreeNode* l = invertTree(root->left); - TreeNode* r = invertTree(root->right); - root->left = r; - root->right = l; - return root; - } -}; +func invertTree(root *TreeNode) *TreeNode { + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return + } + root.Left, root.Right = root.Right, root.Left + dfs(root.Left) + dfs(root.Right) + } + dfs(root) + return root +} ``` -### **Rust** +```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 invertTree(root: TreeNode | null): TreeNode | null { + const dfs = (root: TreeNode | null) => { + if (root === null) { + return; + } + [root.left, root.right] = [root.right, root.left]; + dfs(root.left); + dfs(root.right); + }; + dfs(root); + return root; +} +``` ```rust // Definition for a binary tree node. @@ -266,53 +232,6 @@ impl Solution { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func invertTree(root *TreeNode) *TreeNode { - var dfs func(*TreeNode) - dfs = func(root *TreeNode) { - if root == nil { - return - } - root.Left, root.Right = root.Right, root.Left - dfs(root.Left) - dfs(root.Right) - } - dfs(root) - return root -} -``` - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func invertTree(root *TreeNode) *TreeNode { - if root == nil { - return root - } - l, r := invertTree(root.Left), invertTree(root.Right) - root.Left, root.Right = r, l - return root -} -``` - -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -340,59 +259,101 @@ var invertTree = function (root) { }; ``` -```js + + +### 方法二 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if root is None: + return None + l, r = self.invertTree(root.left), self.invertTree(root.right) + root.left, root.right = r, l + return root +``` + +```java /** * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } * } */ +class Solution { + public TreeNode invertTree(TreeNode root) { + if (root == null) { + return null; + } + TreeNode l = invertTree(root.left); + TreeNode r = invertTree(root.right); + root.left = r; + root.right = l; + return root; + } +} +``` + +```cpp /** - * @param {TreeNode} root - * @return {TreeNode} + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; */ -var invertTree = function (root) { - if (!root) { +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + if (!root) { + return root; + } + TreeNode* l = invertTree(root->left); + TreeNode* r = invertTree(root->right); + root->left = r; + root->right = l; return root; } - const l = invertTree(root.left); - const r = invertTree(root.right); - root.left = r; - root.right = l; - return root; }; ``` -### **TypeScript** - -```ts +```go /** * 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) - * } + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode * } */ - -function invertTree(root: TreeNode | null): TreeNode | null { - const dfs = (root: TreeNode | null) => { - if (root === null) { - return; - } - [root.left, root.right] = [root.right, root.left]; - dfs(root.left); - dfs(root.right); - }; - dfs(root); - return root; +func invertTree(root *TreeNode) *TreeNode { + if root == nil { + return root + } + l, r := invertTree(root.Left), invertTree(root.Right) + root.Left, root.Right = r, l + return root } ``` @@ -423,10 +384,31 @@ function invertTree(root: TreeNode | null): TreeNode | null { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {TreeNode} + */ +var invertTree = function (root) { + if (!root) { + return root; + } + const l = invertTree(root.left); + const r = invertTree(root.right); + root.left = r; + root.right = l; + return root; +}; ``` + + diff --git a/solution/0200-0299/0226.Invert Binary Tree/README_EN.md b/solution/0200-0299/0226.Invert Binary Tree/README_EN.md index 428d6ce77f8c4..b0787b487af3e 100644 --- a/solution/0200-0299/0226.Invert Binary Tree/README_EN.md +++ b/solution/0200-0299/0226.Invert Binary Tree/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion The idea of recursion is very simple, which is to swap the left and right subtrees of the current node, and then recursively swap the left and right subtrees of the current node. @@ -46,8 +46,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -68,24 +66,6 @@ class Solution: return root ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: - if root is None: - return None - l, r = self.invertTree(root.left), self.invertTree(root.right) - root.left, root.right = r, l - return root -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -121,38 +101,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public TreeNode invertTree(TreeNode root) { - if (root == null) { - return null; - } - TreeNode l = invertTree(root.left); - TreeNode r = invertTree(root.right); - root.left = r; - root.right = l; - return root; - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -182,34 +130,58 @@ public: }; ``` -```cpp +```go /** * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } */ -class Solution { -public: - TreeNode* invertTree(TreeNode* root) { - if (!root) { - return root; - } - TreeNode* l = invertTree(root->left); - TreeNode* r = invertTree(root->right); - root->left = r; - root->right = l; - return root; - } -}; +func invertTree(root *TreeNode) *TreeNode { + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return + } + root.Left, root.Right = root.Right, root.Left + dfs(root.Left) + dfs(root.Right) + } + dfs(root) + return root +} ``` -### **Rust** +```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 invertTree(root: TreeNode | null): TreeNode | null { + const dfs = (root: TreeNode | null) => { + if (root === null) { + return; + } + [root.left, root.right] = [root.right, root.left]; + dfs(root.left); + dfs(root.right); + }; + dfs(root); + return root; +} +``` ```rust // Definition for a binary tree node. @@ -252,53 +224,6 @@ impl Solution { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func invertTree(root *TreeNode) *TreeNode { - var dfs func(*TreeNode) - dfs = func(root *TreeNode) { - if root == nil { - return - } - root.Left, root.Right = root.Right, root.Left - dfs(root.Left) - dfs(root.Right) - } - dfs(root) - return root -} -``` - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func invertTree(root *TreeNode) *TreeNode { - if root == nil { - return root - } - l, r := invertTree(root.Left), invertTree(root.Right) - root.Left, root.Right = r, l - return root -} -``` - -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -326,59 +251,101 @@ var invertTree = function (root) { }; ``` -```js + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if root is None: + return None + l, r = self.invertTree(root.left), self.invertTree(root.right) + root.left, root.right = r, l + return root +``` + +```java /** * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } * } */ +class Solution { + public TreeNode invertTree(TreeNode root) { + if (root == null) { + return null; + } + TreeNode l = invertTree(root.left); + TreeNode r = invertTree(root.right); + root.left = r; + root.right = l; + return root; + } +} +``` + +```cpp /** - * @param {TreeNode} root - * @return {TreeNode} + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; */ -var invertTree = function (root) { - if (!root) { +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + if (!root) { + return root; + } + TreeNode* l = invertTree(root->left); + TreeNode* r = invertTree(root->right); + root->left = r; + root->right = l; return root; } - const l = invertTree(root.left); - const r = invertTree(root.right); - root.left = r; - root.right = l; - return root; }; ``` -### **TypeScript** - -```ts +```go /** * 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) - * } + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode * } */ - -function invertTree(root: TreeNode | null): TreeNode | null { - const dfs = (root: TreeNode | null) => { - if (root === null) { - return; - } - [root.left, root.right] = [root.right, root.left]; - dfs(root.left); - dfs(root.right); - }; - dfs(root); - return root; +func invertTree(root *TreeNode) *TreeNode { + if root == nil { + return root + } + l, r := invertTree(root.Left), invertTree(root.Right) + root.Left, root.Right = r, l + return root } ``` @@ -409,10 +376,31 @@ function invertTree(root: TreeNode | null): TreeNode | null { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {TreeNode} + */ +var invertTree = function (root) { + if (!root) { + return root; + } + const l = invertTree(root.left); + const r = invertTree(root.right); + root.left = r; + root.right = l; + return root; +}; ``` + + diff --git a/solution/0200-0299/0227.Basic Calculator II/README.md b/solution/0200-0299/0227.Basic Calculator II/README.md index 0b62976986e70..b2450f75b35ec 100644 --- a/solution/0200-0299/0227.Basic Calculator II/README.md +++ b/solution/0200-0299/0227.Basic Calculator II/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 遍历字符串 $s$,并用变量 `sign` 记录每个数字之前的运算符,对于第一个数字,其之前的运算符视为加号。每次遍历到数字末尾时,根据 `sign` 来决定计算方式: @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def calculate(self, s: str) -> int: @@ -95,10 +89,6 @@ class Solution: return sum(stk) ``` -### **Java** - - - ```java class Solution { public int calculate(String s) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -173,8 +161,6 @@ public: }; ``` -### **Go** - ```go func calculate(s string) int { sign := '+' @@ -208,10 +194,93 @@ func calculate(s string) int { } ``` -### **...** +```cs +using System.Collections.Generic; +using System.Linq; + +struct Element +{ + public char Op; + public int Number; + public Element(char op, int number) + { + Op = op; + Number = number; + } +} -``` +public class Solution { + public int Calculate(string s) { + var stack = new Stack(); + var readingNumber = false; + var number = 0; + var op = '+'; + foreach (var ch in ((IEnumerable)s).Concat(Enumerable.Repeat('+', 1))) + { + if (ch >= '0' && ch <= '9') + { + if (!readingNumber) + { + readingNumber = true; + number = 0; + } + number = (number * 10) + (ch - '0'); + } + else if (ch != ' ') + { + readingNumber = false; + if (op == '+' || op == '-') + { + if (stack.Count == 2) + { + var prev = stack.Pop(); + var first = stack.Pop(); + if (prev.Op == '+') + { + stack.Push(new Element(first.Op, first.Number + prev.Number)); + } + else // '-' + { + stack.Push(new Element(first.Op, first.Number - prev.Number)); + } + } + stack.Push(new Element(op, number)); + } + else + { + var prev = stack.Pop(); + if (op == '*') + { + stack.Push(new Element(prev.Op, prev.Number * number)); + } + else // '/' + { + stack.Push(new Element(prev.Op, prev.Number / number)); + } + } + op = ch; + } + } + if (stack.Count == 2) + { + var second = stack.Pop(); + var first = stack.Pop(); + if (second.Op == '+') + { + stack.Push(new Element(first.Op, first.Number + second.Number)); + } + else // '-' + { + stack.Push(new Element(first.Op, first.Number - second.Number)); + } + } + + return stack.Peek().Number; + } +} ``` + + diff --git a/solution/0200-0299/0227.Basic Calculator II/README_EN.md b/solution/0200-0299/0227.Basic Calculator II/README_EN.md index 0ec8175c09705..9d8115521eabc 100644 --- a/solution/0200-0299/0227.Basic Calculator II/README_EN.md +++ b/solution/0200-0299/0227.Basic Calculator II/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Stack** +### Solution 1: Stack We traverse the string $s$, and use a variable `sign` to record the operator before each number. For the first number, its previous operator is considered as a plus sign. Each time we traverse to the end of a number, we decide the calculation method based on `sign`: @@ -50,8 +50,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is -### **Python3** - ```python class Solution: def calculate(self, s: str) -> int: @@ -76,8 +74,6 @@ class Solution: return sum(stk) ``` -### **Java** - ```java class Solution { public int calculate(String s) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +146,6 @@ public: }; ``` -### **Go** - ```go func calculate(s string) int { sign := '+' @@ -187,10 +179,93 @@ func calculate(s string) int { } ``` -### **...** +```cs +using System.Collections.Generic; +using System.Linq; -``` +struct Element +{ + public char Op; + public int Number; + public Element(char op, int number) + { + Op = op; + Number = number; + } +} +public class Solution { + public int Calculate(string s) { + var stack = new Stack(); + var readingNumber = false; + var number = 0; + var op = '+'; + foreach (var ch in ((IEnumerable)s).Concat(Enumerable.Repeat('+', 1))) + { + if (ch >= '0' && ch <= '9') + { + if (!readingNumber) + { + readingNumber = true; + number = 0; + } + number = (number * 10) + (ch - '0'); + } + else if (ch != ' ') + { + readingNumber = false; + if (op == '+' || op == '-') + { + if (stack.Count == 2) + { + var prev = stack.Pop(); + var first = stack.Pop(); + if (prev.Op == '+') + { + stack.Push(new Element(first.Op, first.Number + prev.Number)); + } + else // '-' + { + stack.Push(new Element(first.Op, first.Number - prev.Number)); + } + } + stack.Push(new Element(op, number)); + } + else + { + var prev = stack.Pop(); + if (op == '*') + { + stack.Push(new Element(prev.Op, prev.Number * number)); + } + else // '/' + { + stack.Push(new Element(prev.Op, prev.Number / number)); + } + } + op = ch; + } + } + + if (stack.Count == 2) + { + var second = stack.Pop(); + var first = stack.Pop(); + if (second.Op == '+') + { + stack.Push(new Element(first.Op, first.Number + second.Number)); + } + else // '-' + { + stack.Push(new Element(first.Op, first.Number - second.Number)); + } + } + + return stack.Peek().Number; + } +} ``` + + diff --git a/solution/0200-0299/0228.Summary Ranges/README.md b/solution/0200-0299/0228.Summary Ranges/README.md index 3964ab36e4bdd..77d59573d3aef 100644 --- a/solution/0200-0299/0228.Summary Ranges/README.md +++ b/solution/0200-0299/0228.Summary Ranges/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们可以用双指针 $i$ 和 $j$ 找出每个区间的左右端点。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List summaryRanges(int[] nums) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,7 +123,42 @@ public: }; ``` -### **Rust** +```go +func summaryRanges(nums []int) (ans []string) { + f := func(i, j int) string { + if i == j { + return strconv.Itoa(nums[i]) + } + return strconv.Itoa(nums[i]) + "->" + strconv.Itoa(nums[j]) + } + for i, j, n := 0, 0, len(nums); i < n; i = j + 1 { + j = i + for j+1 < n && nums[j+1] == nums[j]+1 { + j++ + } + ans = append(ans, f(i, j)) + } + return +} +``` + +```ts +function summaryRanges(nums: number[]): string[] { + const f = (i: number, j: number): string => { + return i === j ? `${nums[i]}` : `${nums[i]}->${nums[j]}`; + }; + const n = nums.length; + const ans: string[] = []; + for (let i = 0, j = 0; i < n; i = j + 1) { + j = i; + while (j + 1 < n && nums[j + 1] === nums[j] + 1) { + ++j; + } + ans.push(f(i, j)); + } + return ans; +} +``` ```rust impl Solution { @@ -177,49 +200,6 @@ impl Solution { } ``` -### **Go** - -```go -func summaryRanges(nums []int) (ans []string) { - f := func(i, j int) string { - if i == j { - return strconv.Itoa(nums[i]) - } - return strconv.Itoa(nums[i]) + "->" + strconv.Itoa(nums[j]) - } - for i, j, n := 0, 0, len(nums); i < n; i = j + 1 { - j = i - for j+1 < n && nums[j+1] == nums[j]+1 { - j++ - } - ans = append(ans, f(i, j)) - } - return -} -``` - -### **TypeScript** - -```ts -function summaryRanges(nums: number[]): string[] { - const f = (i: number, j: number): string => { - return i === j ? `${nums[i]}` : `${nums[i]}->${nums[j]}`; - }; - const n = nums.length; - const ans: string[] = []; - for (let i = 0, j = 0; i < n; i = j + 1) { - j = i; - while (j + 1 < n && nums[j + 1] === nums[j] + 1) { - ++j; - } - ans.push(f(i, j)); - } - return ans; -} -``` - -### **C#** - ```cs public class Solution { public IList SummaryRanges(int[] nums) { @@ -240,10 +220,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0228.Summary Ranges/README_EN.md b/solution/0200-0299/0228.Summary Ranges/README_EN.md index 1387d096738bf..e0ad5e85f37e2 100644 --- a/solution/0200-0299/0228.Summary Ranges/README_EN.md +++ b/solution/0200-0299/0228.Summary Ranges/README_EN.md @@ -53,7 +53,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We can use two pointers $i$ and $j$ to find the left and right endpoints of each interval. @@ -63,8 +63,6 @@ Time complexity $O(n)$, where $n$ is the length of the array. Space complexity $ -### **Python3** - ```python class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: @@ -83,8 +81,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List summaryRanges(int[] nums) { @@ -105,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,7 +121,42 @@ public: }; ``` -### **Rust** +```go +func summaryRanges(nums []int) (ans []string) { + f := func(i, j int) string { + if i == j { + return strconv.Itoa(nums[i]) + } + return strconv.Itoa(nums[i]) + "->" + strconv.Itoa(nums[j]) + } + for i, j, n := 0, 0, len(nums); i < n; i = j + 1 { + j = i + for j+1 < n && nums[j+1] == nums[j]+1 { + j++ + } + ans = append(ans, f(i, j)) + } + return +} +``` + +```ts +function summaryRanges(nums: number[]): string[] { + const f = (i: number, j: number): string => { + return i === j ? `${nums[i]}` : `${nums[i]}->${nums[j]}`; + }; + const n = nums.length; + const ans: string[] = []; + for (let i = 0, j = 0; i < n; i = j + 1) { + j = i; + while (j + 1 < n && nums[j + 1] === nums[j] + 1) { + ++j; + } + ans.push(f(i, j)); + } + return ans; +} +``` ```rust impl Solution { @@ -169,49 +198,6 @@ impl Solution { } ``` -### **Go** - -```go -func summaryRanges(nums []int) (ans []string) { - f := func(i, j int) string { - if i == j { - return strconv.Itoa(nums[i]) - } - return strconv.Itoa(nums[i]) + "->" + strconv.Itoa(nums[j]) - } - for i, j, n := 0, 0, len(nums); i < n; i = j + 1 { - j = i - for j+1 < n && nums[j+1] == nums[j]+1 { - j++ - } - ans = append(ans, f(i, j)) - } - return -} -``` - -### **TypeScript** - -```ts -function summaryRanges(nums: number[]): string[] { - const f = (i: number, j: number): string => { - return i === j ? `${nums[i]}` : `${nums[i]}->${nums[j]}`; - }; - const n = nums.length; - const ans: string[] = []; - for (let i = 0, j = 0; i < n; i = j + 1) { - j = i; - while (j + 1 < n && nums[j + 1] === nums[j] + 1) { - ++j; - } - ans.push(f(i, j)); - } - return ans; -} -``` - -### **C#** - ```cs public class Solution { public IList SummaryRanges(int[] nums) { @@ -232,10 +218,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0229.Majority Element II/README.md b/solution/0200-0299/0229.Majority Element II/README.md index 60bc997f40e97..b71d7f70fe853 100644 --- a/solution/0200-0299/0229.Majority Element II/README.md +++ b/solution/0200-0299/0229.Majority Element II/README.md @@ -44,16 +44,10 @@ ## 解法 - - -摩尔投票法。 +### 方法一 -### **Python3** - - - ```python class Solution: def majorityElement(self, nums: List[int]) -> List[int]: @@ -73,10 +67,6 @@ class Solution: return [m for m in [m1, m2] if nums.count(m) > len(nums) // 3] ``` -### **Java** - - - ```java class Solution { public List majorityElement(int[] nums) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go func majorityElement(nums []int) []int { var n1, n2 int @@ -189,8 +175,6 @@ func majorityElement(nums []int) []int { } ``` -### **C#** - ```cs public class Solution { public IList MajorityElement(int[] nums) { @@ -230,8 +214,6 @@ public class Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -252,10 +234,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0229.Majority Element II/README_EN.md b/solution/0200-0299/0229.Majority Element II/README_EN.md index 7b5d10d2db821..0d7da14c11004 100644 --- a/solution/0200-0299/0229.Majority Element II/README_EN.md +++ b/solution/0200-0299/0229.Majority Element II/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return [m for m in [m1, m2] if nums.count(m) > len(nums) // 3] ``` -### **Java** - ```java class Solution { public List majorityElement(int[] nums) { @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +136,6 @@ public: }; ``` -### **Go** - ```go func majorityElement(nums []int) []int { var n1, n2 int @@ -178,8 +172,6 @@ func majorityElement(nums []int) []int { } ``` -### **C#** - ```cs public class Solution { public IList MajorityElement(int[] nums) { @@ -219,8 +211,6 @@ public class Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -241,10 +231,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0230.Kth Smallest Element in a BST/README.md b/solution/0200-0299/0230.Kth Smallest Element in a BST/README.md index 6ee7b9ceb61cb..e7422ffa04302 100644 --- a/solution/0200-0299/0230.Kth Smallest Element in a BST/README.md +++ b/solution/0200-0299/0230.Kth Smallest Element in a BST/README.md @@ -42,24 +42,12 @@ ## 解法 - - -**方法一:中序遍历** +### 方法一:中序遍历 由于二叉搜索树的性质,中序遍历一定能得到升序序列,因此可以采用中序遍历找出第 k 小的元素。 -**方法二:预处理结点数** - -预处理每个结点作为根节点的子树的节点数。 - -这种算法可以用来优化频繁查找第 k 个树、而二叉搜索树本身不被修改的情况。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -82,6 +70,190 @@ class Solution: root = root.right ``` +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int kthSmallest(TreeNode root, int k) { + Deque stk = new ArrayDeque<>(); + while (root != null || !stk.isEmpty()) { + if (root != null) { + stk.push(root); + root = root.left; + } else { + root = stk.pop(); + if (--k == 0) { + return root.val; + } + root = root.right; + } + } + return 0; + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int kthSmallest(TreeNode* root, int k) { + stack stk; + while (root || !stk.empty()) { + if (root) { + stk.push(root); + root = root->left; + } else { + root = stk.top(); + stk.pop(); + if (--k == 0) return root->val; + root = root->right; + } + } + return 0; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func kthSmallest(root *TreeNode, k int) int { + stk := []*TreeNode{} + for root != nil || len(stk) > 0 { + if root != nil { + stk = append(stk, root) + root = root.Left + } else { + root = stk[len(stk)-1] + stk = stk[:len(stk)-1] + k-- + if k == 0 { + return root.Val + } + root = root.Right + } + } + return 0 +} +``` + +```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 kthSmallest(root: TreeNode | null, k: number): number { + const dfs = (root: TreeNode | null) => { + if (root == null) { + return -1; + } + const { val, left, right } = root; + const l = dfs(left); + if (l !== -1) { + return l; + } + k--; + if (k === 0) { + return val; + } + return dfs(right); + }; + return dfs(root); +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(root: Option>>, res: &mut Vec, k: usize) { + if let Some(node) = root { + let mut node = node.borrow_mut(); + Self::dfs(node.left.take(), res, k); + res.push(node.val); + if res.len() >= k { + return; + } + Self::dfs(node.right.take(), res, k); + } + } + pub fn kth_smallest(root: Option>>, k: i32) -> i32 { + let k = k as usize; + let mut res: Vec = Vec::with_capacity(k); + Self::dfs(root, &mut res, k); + res[k - 1] + } +} +``` + + + +### 方法二:预处理结点数 + +预处理每个结点作为根节点的子树的节点数。 + +这种算法可以用来优化频繁查找第 k 个树、而二叉搜索树本身不被修改的情况。 + + + ```python # Definition for a binary tree node. # class TreeNode: @@ -123,46 +295,6 @@ class Solution: return bst.kthSmallest(k) ``` -### **Java** - - - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public int kthSmallest(TreeNode root, int k) { - Deque stk = new ArrayDeque<>(); - while (root != null || !stk.isEmpty()) { - if (root != null) { - stk.push(root); - root = root.left; - } else { - root = stk.pop(); - if (--k == 0) { - return root.val; - } - root = root.right; - } - } - return 0; - } -} -``` - ```java /** * Definition for a binary tree node. @@ -223,40 +355,6 @@ class BST { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int kthSmallest(TreeNode* root, int k) { - stack stk; - while (root || !stk.empty()) { - if (root) { - stk.push(root); - root = root->left; - } else { - root = stk.top(); - stk.pop(); - if (--k == 0) return root->val; - root = root->right; - } - } - return 0; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -311,37 +409,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func kthSmallest(root *TreeNode, k int) int { - stk := []*TreeNode{} - for root != nil || len(stk) > 0 { - if root != nil { - stk = append(stk, root) - root = root.Left - } else { - root = stk[len(stk)-1] - stk = stk[:len(stk)-1] - k-- - if k == 0 { - return root.Val - } - root = root.Right - } - } - return 0 -} -``` - ```go /** * Definition for a binary tree node. @@ -397,91 +464,6 @@ func kthSmallest(root *TreeNode, k int) int { } ``` -### **TypeScript** - -```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 kthSmallest(root: TreeNode | null, k: number): number { - const dfs = (root: TreeNode | null) => { - if (root == null) { - return -1; - } - const { val, left, right } = root; - const l = dfs(left); - if (l !== -1) { - return l; - } - k--; - if (k === 0) { - return val; - } - return dfs(right); - }; - return dfs(root); -} -``` - -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(root: Option>>, res: &mut Vec, k: usize) { - if let Some(node) = root { - let mut node = node.borrow_mut(); - Self::dfs(node.left.take(), res, k); - res.push(node.val); - if res.len() >= k { - return; - } - Self::dfs(node.right.take(), res, k); - } - } - pub fn kth_smallest(root: Option>>, k: i32) -> i32 { - let k = k as usize; - let mut res: Vec = Vec::with_capacity(k); - Self::dfs(root, &mut res, k); - res[k - 1] - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0230.Kth Smallest Element in a BST/README_EN.md b/solution/0200-0299/0230.Kth Smallest Element in a BST/README_EN.md index 8ee2339932f40..184224f684194 100644 --- a/solution/0200-0299/0230.Kth Smallest Element in a BST/README_EN.md +++ b/solution/0200-0299/0230.Kth Smallest Element in a BST/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -61,6 +61,186 @@ class Solution: root = root.right ``` +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int kthSmallest(TreeNode root, int k) { + Deque stk = new ArrayDeque<>(); + while (root != null || !stk.isEmpty()) { + if (root != null) { + stk.push(root); + root = root.left; + } else { + root = stk.pop(); + if (--k == 0) { + return root.val; + } + root = root.right; + } + } + return 0; + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int kthSmallest(TreeNode* root, int k) { + stack stk; + while (root || !stk.empty()) { + if (root) { + stk.push(root); + root = root->left; + } else { + root = stk.top(); + stk.pop(); + if (--k == 0) return root->val; + root = root->right; + } + } + return 0; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func kthSmallest(root *TreeNode, k int) int { + stk := []*TreeNode{} + for root != nil || len(stk) > 0 { + if root != nil { + stk = append(stk, root) + root = root.Left + } else { + root = stk[len(stk)-1] + stk = stk[:len(stk)-1] + k-- + if k == 0 { + return root.Val + } + root = root.Right + } + } + return 0 +} +``` + +```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 kthSmallest(root: TreeNode | null, k: number): number { + const dfs = (root: TreeNode | null) => { + if (root == null) { + return -1; + } + const { val, left, right } = root; + const l = dfs(left); + if (l !== -1) { + return l; + } + k--; + if (k === 0) { + return val; + } + return dfs(right); + }; + return dfs(root); +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(root: Option>>, res: &mut Vec, k: usize) { + if let Some(node) = root { + let mut node = node.borrow_mut(); + Self::dfs(node.left.take(), res, k); + res.push(node.val); + if res.len() >= k { + return; + } + Self::dfs(node.right.take(), res, k); + } + } + pub fn kth_smallest(root: Option>>, k: i32) -> i32 { + let k = k as usize; + let mut res: Vec = Vec::with_capacity(k); + Self::dfs(root, &mut res, k); + res[k - 1] + } +} +``` + + + +### Solution 2 + + + ```python # Definition for a binary tree node. # class TreeNode: @@ -102,44 +282,6 @@ class Solution: return bst.kthSmallest(k) ``` -### **Java** - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public int kthSmallest(TreeNode root, int k) { - Deque stk = new ArrayDeque<>(); - while (root != null || !stk.isEmpty()) { - if (root != null) { - stk.push(root); - root = root.left; - } else { - root = stk.pop(); - if (--k == 0) { - return root.val; - } - root = root.right; - } - } - return 0; - } -} -``` - ```java /** * Definition for a binary tree node. @@ -200,40 +342,6 @@ class BST { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int kthSmallest(TreeNode* root, int k) { - stack stk; - while (root || !stk.empty()) { - if (root) { - stk.push(root); - root = root->left; - } else { - root = stk.top(); - stk.pop(); - if (--k == 0) return root->val; - root = root->right; - } - } - return 0; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -288,37 +396,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func kthSmallest(root *TreeNode, k int) int { - stk := []*TreeNode{} - for root != nil || len(stk) > 0 { - if root != nil { - stk = append(stk, root) - root = root.Left - } else { - root = stk[len(stk)-1] - stk = stk[:len(stk)-1] - k-- - if k == 0 { - return root.Val - } - root = root.Right - } - } - return 0 -} -``` - ```go /** * Definition for a binary tree node. @@ -374,91 +451,6 @@ func kthSmallest(root *TreeNode, k int) int { } ``` -### **TypeScript** - -```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 kthSmallest(root: TreeNode | null, k: number): number { - const dfs = (root: TreeNode | null) => { - if (root == null) { - return -1; - } - const { val, left, right } = root; - const l = dfs(left); - if (l !== -1) { - return l; - } - k--; - if (k === 0) { - return val; - } - return dfs(right); - }; - return dfs(root); -} -``` - -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(root: Option>>, res: &mut Vec, k: usize) { - if let Some(node) = root { - let mut node = node.borrow_mut(); - Self::dfs(node.left.take(), res, k); - res.push(node.val); - if res.len() >= k { - return; - } - Self::dfs(node.right.take(), res, k); - } - } - pub fn kth_smallest(root: Option>>, k: i32) -> i32 { - let k = k as usize; - let mut res: Vec = Vec::with_capacity(k); - Self::dfs(root, &mut res, k); - res[k - 1] - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0231.Power of Two/README.md b/solution/0200-0299/0231.Power of Two/README.md index e3126fa0e15a5..7afd5e9adc9c1 100644 --- a/solution/0200-0299/0231.Power of Two/README.md +++ b/solution/0200-0299/0231.Power of Two/README.md @@ -63,42 +63,18 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 $\texttt{n\&(n-1)}$ 可将最后一个二进制形式的 $n$ 的最后一位 $1$ 移除,若移除后为 $0$,说明 $n$ 是 $2$ 的幂。 -**方法二:lowbit** - -$\texttt{n\&(-n)}$ 可以得到 $n$ 的最后一位 $1$ 表示的十进制数,若与 $n$ 相等,说明 $n$ 是 $2$ 的幂。 - -注意:要满足 $n$ 是 $2$ 的幂次方,需要保证 $n$ 大于 $0$。 - -### **Python3** - - - ```python class Solution: def isPowerOfTwo(self, n: int) -> bool: return n > 0 and (n & (n - 1)) == 0 ``` -lowbit: - -```python -class Solution: - def isPowerOfTwo(self, n: int) -> bool: - return n > 0 and n == n & (-n) -``` - -### **Java** - - - ```java class Solution { public boolean isPowerOfTwo(int n) { @@ -107,18 +83,6 @@ class Solution { } ``` -lowbit: - -```java -class Solution { - public boolean isPowerOfTwo(int n) { - return n > 0 && n == (n & (-n)); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -128,18 +92,17 @@ public: }; ``` -lowbit: - -```cpp -class Solution { -public: - bool isPowerOfTwo(int n) { - return n > 0 && n == (n & (-n)); - } -}; +```go +func isPowerOfTwo(n int) bool { + return n > 0 && (n&(n-1)) == 0 +} ``` -### **JavaScript** +```ts +function isPowerOfTwo(n: number): boolean { + return n > 0 && (n & (n - 1)) === 0; +} +``` ```js /** @@ -151,27 +114,38 @@ var isPowerOfTwo = function (n) { }; ``` -lowbit: + -```js -/** - * @param {number} n - * @return {boolean} - */ -var isPowerOfTwo = function (n) { - return n > 0 && n == (n & -n); -}; -``` +### 方法二:lowbit -### **Go** +$\texttt{n\&(-n)}$ 可以得到 $n$ 的最后一位 $1$ 表示的十进制数,若与 $n$ 相等,说明 $n$ 是 $2$ 的幂。 -```go -func isPowerOfTwo(n int) bool { - return n > 0 && (n&(n-1)) == 0 +注意:要满足 $n$ 是 $2$ 的幂次方,需要保证 $n$ 大于 $0$。 + + + +```python +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + return n > 0 and n == n & (-n) +``` + +```java +class Solution { + public boolean isPowerOfTwo(int n) { + return n > 0 && n == (n & (-n)); + } } ``` -lowbit: +```cpp +class Solution { +public: + bool isPowerOfTwo(int n) { + return n > 0 && n == (n & (-n)); + } +}; +``` ```go func isPowerOfTwo(n int) bool { @@ -179,26 +153,22 @@ func isPowerOfTwo(n int) bool { } ``` -### **TypeScript** - -```ts -function isPowerOfTwo(n: number): boolean { - return n > 0 && (n & (n - 1)) === 0; -} -``` - -lowbit: - ```ts function isPowerOfTwo(n: number): boolean { return n > 0 && (n & (n - 1)) === 0; } ``` -### **...** - -``` - +```js +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfTwo = function (n) { + return n > 0 && n == (n & -n); +}; ``` + + diff --git a/solution/0200-0299/0231.Power of Two/README_EN.md b/solution/0200-0299/0231.Power of Two/README_EN.md index 8a2f4b5be62c1..c076aa054d088 100644 --- a/solution/0200-0299/0231.Power of Two/README_EN.md +++ b/solution/0200-0299/0231.Power of Two/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,16 +54,6 @@ class Solution: return n > 0 and (n & (n - 1)) == 0 ``` -lowbit: - -```python -class Solution: - def isPowerOfTwo(self, n: int) -> bool: - return n > 0 and n == n & (-n) -``` - -### **Java** - ```java class Solution { public boolean isPowerOfTwo(int n) { @@ -72,18 +62,6 @@ class Solution { } ``` -lowbit: - -```java -class Solution { - public boolean isPowerOfTwo(int n) { - return n > 0 && n == (n & (-n)); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -93,16 +71,17 @@ public: }; ``` -```cpp -class Solution { -public: - bool isPowerOfTwo(int n) { - return n > 0 && n == (n & (-n)); - } -}; +```go +func isPowerOfTwo(n int) bool { + return n > 0 && (n&(n-1)) == 0 +} ``` -### **JavaScript** +```ts +function isPowerOfTwo(n: number): boolean { + return n > 0 && (n & (n - 1)) === 0; +} +``` ```js /** @@ -114,27 +93,34 @@ var isPowerOfTwo = function (n) { }; ``` -lowbit: + -```js -/** - * @param {number} n - * @return {boolean} - */ -var isPowerOfTwo = function (n) { - return n > 0 && n == (n & -n); -}; -``` +### Solution 2 -### **Go** + -```go -func isPowerOfTwo(n int) bool { - return n > 0 && (n&(n-1)) == 0 +```python +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + return n > 0 and n == n & (-n) +``` + +```java +class Solution { + public boolean isPowerOfTwo(int n) { + return n > 0 && n == (n & (-n)); + } } ``` -lowbit: +```cpp +class Solution { +public: + bool isPowerOfTwo(int n) { + return n > 0 && n == (n & (-n)); + } +}; +``` ```go func isPowerOfTwo(n int) bool { @@ -142,26 +128,22 @@ func isPowerOfTwo(n int) bool { } ``` -### **TypeScript** - ```ts function isPowerOfTwo(n: number): boolean { return n > 0 && (n & (n - 1)) === 0; } ``` -lowbit: - -```ts -function isPowerOfTwo(n: number): boolean { - return n > 0 && n === (n & -n); -} -``` - -### **...** - -``` - +```js +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfTwo = function (n) { + return n > 0 && n == (n & -n); +}; ``` + + diff --git a/solution/0200-0299/0232.Implement Queue using Stacks/README.md b/solution/0200-0299/0232.Implement Queue using Stacks/README.md index 3d093ebfa8124..5ef9cfc8b94ec 100644 --- a/solution/0200-0299/0232.Implement Queue using Stacks/README.md +++ b/solution/0200-0299/0232.Implement Queue using Stacks/README.md @@ -67,9 +67,7 @@ myQueue.empty(); // return false ## 解法 - - -**方法一:双栈** +### 方法一:双栈 使用两个栈,其中栈 `stk1`用于入队,另一个栈 `stk2` 用于出队。 @@ -83,10 +81,6 @@ myQueue.empty(); // return false -### **Python3** - - - ```python class MyQueue: def __init__(self): @@ -121,10 +115,6 @@ class MyQueue: # param_4 = obj.empty() ``` -### **Java** - - - ```java class MyQueue { private Deque stk1 = new ArrayDeque<>(); @@ -170,8 +160,6 @@ class MyQueue { */ ``` -### **C++** - ```cpp class MyQueue { public: @@ -222,8 +210,6 @@ private: */ ``` -### **Go** - ```go type MyQueue struct { stk1 []int @@ -273,8 +259,6 @@ func (this *MyQueue) move() { */ ``` -### **TypeScript** - ```ts class MyQueue { stk1: number[]; @@ -322,8 +306,6 @@ class MyQueue { */ ``` -### **Rust** - ```rust struct MyQueue { in_stack: Vec, @@ -382,10 +364,6 @@ impl MyQueue { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0232.Implement Queue using Stacks/README_EN.md b/solution/0200-0299/0232.Implement Queue using Stacks/README_EN.md index 32dc6e51866dc..456370887f2d6 100644 --- a/solution/0200-0299/0232.Implement Queue using Stacks/README_EN.md +++ b/solution/0200-0299/0232.Implement Queue using Stacks/README_EN.md @@ -55,9 +55,9 @@ myQueue.empty(); // return false ## Solutions - +### Solution 1 -### **Python3** + ```python class MyQueue: @@ -93,8 +93,6 @@ class MyQueue: # param_4 = obj.empty() ``` -### **Java** - ```java class MyQueue { private Deque stk1 = new ArrayDeque<>(); @@ -140,8 +138,6 @@ class MyQueue { */ ``` -### **C++** - ```cpp class MyQueue { public: @@ -192,8 +188,6 @@ private: */ ``` -### **Go** - ```go type MyQueue struct { stk1 []int @@ -243,8 +237,6 @@ func (this *MyQueue) move() { */ ``` -### **TypeScript** - ```ts class MyQueue { stk1: number[]; @@ -292,8 +284,6 @@ class MyQueue { */ ``` -### **Rust** - ```rust struct MyQueue { in_stack: Vec, @@ -352,10 +342,6 @@ impl MyQueue { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0233.Number of Digit One/README.md b/solution/0200-0299/0233.Number of Digit One/README.md index 40ad15dd1f283..9ea12359b6e87 100644 --- a/solution/0200-0299/0233.Number of Digit One/README.md +++ b/solution/0200-0299/0233.Number of Digit One/README.md @@ -34,9 +34,7 @@ ## 解法 - - -**方法一:数位 DP** +### 方法一:数位 DP 这道题实际上是求在给定区间 $[l,..r]$ 中,数字中出现 $1$ 个数。个数与数的位数以及每一位上的数字有关。我们可以用数位 DP 的思路来解决这道题。数位 DP 中,数的大小对复杂度的影响很小。 @@ -76,10 +74,6 @@ $$ -### **Python3** - - - ```python class Solution: def countDigitOne(self, n: int) -> int: @@ -102,10 +96,6 @@ class Solution: return dfs(l, 0, True) ``` -### **Java** - - - ```java class Solution { private int[] a = new int[12]; @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -181,8 +169,6 @@ public: }; ``` -### **Go** - ```go func countDigitOne(n int) int { a := make([]int, 12) @@ -228,8 +214,6 @@ func countDigitOne(n int) int { } ``` -### **C#** - ```cs public class Solution { public int CountDigitOne(int n) { @@ -250,10 +234,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0233.Number of Digit One/README_EN.md b/solution/0200-0299/0233.Number of Digit One/README_EN.md index 2a193906f35f6..443b55cb90a5e 100644 --- a/solution/0200-0299/0233.Number of Digit One/README_EN.md +++ b/solution/0200-0299/0233.Number of Digit One/README_EN.md @@ -30,12 +30,10 @@ ## Solutions -simple digital dp problem (or it can be solved by finding a rule) +### Solution 1 -### **Python3** - ```python class Solution: def countDigitOne(self, n: int) -> int: @@ -58,8 +56,6 @@ class Solution: return dfs(l, 0, True) ``` -### **Java** - ```java class Solution { private int[] a = new int[12]; @@ -97,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +129,6 @@ public: }; ``` -### **Go** - ```go func countDigitOne(n int) int { a := make([]int, 12) @@ -182,8 +174,6 @@ func countDigitOne(n int) int { } ``` -### **C#** - ```cs public class Solution { public int CountDigitOne(int n) { @@ -204,10 +194,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0234.Palindrome Linked List/README.md b/solution/0200-0299/0234.Palindrome Linked List/README.md index 5fce54f691684..78c5bad1c65eb 100644 --- a/solution/0200-0299/0234.Palindrome Linked List/README.md +++ b/solution/0200-0299/0234.Palindrome Linked List/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:快慢指针** +### 方法一:快慢指针 我们可以先用快慢指针找到链表的中点,接着反转右半部分的链表。然后同时遍历前后两段链表,若前后两段链表节点对应的值不等,说明不是回文链表,否则说明是回文链表。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -76,10 +70,6 @@ class Solution: return True ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -160,8 +148,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -193,7 +179,43 @@ func isPalindrome(head *ListNode) bool { } ``` -### **JavaScript** +```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 { + 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 /** @@ -234,8 +256,6 @@ var isPalindrome = function (head) { }; ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -277,50 +297,6 @@ 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 { - 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; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0234.Palindrome Linked List/README_EN.md b/solution/0200-0299/0234.Palindrome Linked List/README_EN.md index 11c9fda3c1150..80c39bec7276d 100644 --- a/solution/0200-0299/0234.Palindrome Linked List/README_EN.md +++ b/solution/0200-0299/0234.Palindrome Linked List/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -61,8 +61,6 @@ class Solution: return True ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -103,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -143,8 +139,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -176,7 +170,43 @@ func isPalindrome(head *ListNode) bool { } ``` -### **JavaScript** +```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 { + 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 /** @@ -217,8 +247,6 @@ var isPalindrome = function (head) { }; ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -260,50 +288,6 @@ 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 { - 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; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/README.md b/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/README.md index 485dd5979181c..d12bc7e4948da 100644 --- a/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/README.md +++ b/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:迭代或递归** +### 方法一:迭代或递归 从上到下搜索,找到第一个值位于 $[p.val, q.val]$ 之间的结点即可。 @@ -54,12 +52,6 @@ -### **Python3** - - - -迭代: - ```python # Definition for a binary tree node. # class TreeNode: @@ -82,34 +74,6 @@ class Solution: return root ``` -递归: - -```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 lowestCommonAncestor( - self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode' - ) -> 'TreeNode': - if root.val < min(p.val, q.val): - return self.lowestCommonAncestor(root.right, p, q) - if root.val > max(p.val, q.val): - return self.lowestCommonAncestor(root.left, p, q) - return root -``` - -### **Java** - - - -迭代: - ```java /** * Definition for a binary tree node. @@ -136,36 +100,6 @@ class Solution { } ``` -递归: - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ - -class Solution { - public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { - if (root.val < Math.min(p.val, q.val)) { - return lowestCommonAncestor(root.right, p, q); - } - if (root.val > Math.max(p.val, q.val)) { - return lowestCommonAncestor(root.left, p, q); - } - return root; - } -} -``` - -### **C++** - -迭代: - ```cpp /** * Definition for a binary tree node. @@ -193,37 +127,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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { - if (root->val < min(p->val, q->val)) { - return lowestCommonAncestor(root->right, p, q); - } - if (root->val > max(p->val, q->val)) { - return lowestCommonAncestor(root->left, p, q); - } - return root; - } -}; -``` - -### **Go** - -迭代: - ```go /** * Definition for a binary tree node. @@ -247,33 +150,6 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { } ``` -递归: - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ - -func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { - if root.Val < p.Val && root.Val < q.Val { - return lowestCommonAncestor(root.Right, p, q) - } - if root.Val > p.Val && root.Val > q.Val { - return lowestCommonAncestor(root.Left, p, q) - } - return root -} -``` - -### **TypeScript** - -迭代: - ```ts /** * Definition for a binary tree node. @@ -306,7 +182,101 @@ function lowestCommonAncestor( } ``` -递归: + + +### 方法二 + + + +```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 lowestCommonAncestor( + self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode' + ) -> 'TreeNode': + if root.val < min(p.val, q.val): + return self.lowestCommonAncestor(root.right, p, q) + if root.val > max(p.val, q.val): + return self.lowestCommonAncestor(root.left, p, q) + return root +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root.val < Math.min(p.val, q.val)) { + return lowestCommonAncestor(root.right, p, q); + } + if (root.val > Math.max(p.val, q.val)) { + return lowestCommonAncestor(root.left, p, q); + } + return root; + } +} +``` + +```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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (root->val < min(p->val, q->val)) { + return lowestCommonAncestor(root->right, p, q); + } + if (root->val > max(p->val, q->val)) { + return lowestCommonAncestor(root->left, p, q); + } + return root; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + if root.Val < p.Val && root.Val < q.Val { + return lowestCommonAncestor(root.Right, p, q) + } + if root.Val > p.Val && root.Val > q.Val { + return lowestCommonAncestor(root.Left, p, q) + } + return root +} +``` ```ts /** @@ -334,10 +304,6 @@ function lowestCommonAncestor( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/README_EN.md b/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/README_EN.md index ff4963a02eb08..4f06e16f43671 100644 --- a/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/README_EN.md +++ b/solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/README_EN.md @@ -45,11 +45,9 @@ ## Solutions - - -### **Python3** +### Solution 1 -Iterative: + ```python # Definition for a binary tree node. @@ -73,32 +71,6 @@ class Solution: return root ``` -Recursive: - -```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 lowestCommonAncestor( - self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode' - ) -> 'TreeNode': - if root.val < min(p.val, q.val): - return self.lowestCommonAncestor(root.right, p, q) - if root.val > max(p.val, q.val): - return self.lowestCommonAncestor(root.left, p, q) - return root -``` - -### **Java** - -Iterative: - ```java /** * Definition for a binary tree node. @@ -125,36 +97,6 @@ class Solution { } ``` -Recursive: - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ - -class Solution { - public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { - if (root.val < Math.min(p.val, q.val)) { - return lowestCommonAncestor(root.right, p, q); - } - if (root.val > Math.max(p.val, q.val)) { - return lowestCommonAncestor(root.left, p, q); - } - return root; - } -} -``` - -### **C++** - -Iterative: - ```cpp /** * Definition for a binary tree node. @@ -182,37 +124,6 @@ public: }; ``` -Recursive: - -```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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { - if (root->val < min(p->val, q->val)) { - return lowestCommonAncestor(root->right, p, q); - } - if (root->val > max(p->val, q->val)) { - return lowestCommonAncestor(root->left, p, q); - } - return root; - } -}; -``` - -### **Go** - -Iterative: - ```go /** * Definition for a binary tree node. @@ -236,33 +147,6 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { } ``` -Recursive: - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ - -func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { - if root.Val < p.Val && root.Val < q.Val { - return lowestCommonAncestor(root.Right, p, q) - } - if root.Val > p.Val && root.Val > q.Val { - return lowestCommonAncestor(root.Left, p, q) - } - return root -} -``` - -### **TypeScript** - -Iterative: - ```ts /** * Definition for a binary tree node. @@ -295,7 +179,101 @@ function lowestCommonAncestor( } ``` -Recursive: + + +### 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 lowestCommonAncestor( + self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode' + ) -> 'TreeNode': + if root.val < min(p.val, q.val): + return self.lowestCommonAncestor(root.right, p, q) + if root.val > max(p.val, q.val): + return self.lowestCommonAncestor(root.left, p, q) + return root +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root.val < Math.min(p.val, q.val)) { + return lowestCommonAncestor(root.right, p, q); + } + if (root.val > Math.max(p.val, q.val)) { + return lowestCommonAncestor(root.left, p, q); + } + return root; + } +} +``` + +```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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (root->val < min(p->val, q->val)) { + return lowestCommonAncestor(root->right, p, q); + } + if (root->val > max(p->val, q->val)) { + return lowestCommonAncestor(root->left, p, q); + } + return root; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + if root.Val < p.Val && root.Val < q.Val { + return lowestCommonAncestor(root.Right, p, q) + } + if root.Val > p.Val && root.Val > q.Val { + return lowestCommonAncestor(root.Left, p, q) + } + return root +} +``` ```ts /** @@ -323,10 +301,6 @@ function lowestCommonAncestor( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0236.Lowest Common Ancestor of a Binary Tree/README.md b/solution/0200-0299/0236.Lowest Common Ancestor of a Binary Tree/README.md index d266807450881..c96633e9b2e0b 100644 --- a/solution/0200-0299/0236.Lowest Common Ancestor of a Binary Tree/README.md +++ b/solution/0200-0299/0236.Lowest Common Ancestor of a Binary Tree/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 根据“**最近公共祖先**”的定义,若 root 是 p, q 的最近公共祖先 ,则只可能为以下情况之一: @@ -68,10 +66,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -92,10 +86,6 @@ class Solution: return root if left and right else (left or right) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -169,34 +155,6 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} root - * @param {TreeNode} p - * @param {TreeNode} q - * @return {TreeNode} - */ -var lowestCommonAncestor = function (root, p, q) { - if (!root || root == p || root == q) return root; - const left = lowestCommonAncestor(root.left, p, q); - const right = lowestCommonAncestor(root.right, p, q); - if (!left) return right; - if (!right) return left; - return root; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -235,8 +193,6 @@ function lowestCommonAncestor( } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -288,10 +244,30 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} p + * @param {TreeNode} q + * @return {TreeNode} + */ +var lowestCommonAncestor = function (root, p, q) { + if (!root || root == p || root == q) return root; + const left = lowestCommonAncestor(root.left, p, q); + const right = lowestCommonAncestor(root.right, p, q); + if (!left) return right; + if (!right) return left; + return root; +}; ``` + + diff --git a/solution/0200-0299/0236.Lowest Common Ancestor of a Binary Tree/README_EN.md b/solution/0200-0299/0236.Lowest Common Ancestor of a Binary Tree/README_EN.md index 4155c2a1f8756..7e57175574bb5 100644 --- a/solution/0200-0299/0236.Lowest Common Ancestor of a Binary Tree/README_EN.md +++ b/solution/0200-0299/0236.Lowest Common Ancestor of a Binary Tree/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -69,8 +69,6 @@ class Solution: return root if left and right else (left or right) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -117,8 +113,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -144,34 +138,6 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val) { - * this.val = val; - * this.left = this.right = null; - * } - */ -/** - * @param {TreeNode} root - * @param {TreeNode} p - * @param {TreeNode} q - * @return {TreeNode} - */ -var lowestCommonAncestor = function (root, p, q) { - if (!root || root == p || root == q) return root; - const left = lowestCommonAncestor(root.left, p, q); - const right = lowestCommonAncestor(root.right, p, q); - if (!left) return right; - if (!right) return left; - return root; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -210,8 +176,6 @@ function lowestCommonAncestor( } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -263,10 +227,30 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} p + * @param {TreeNode} q + * @return {TreeNode} + */ +var lowestCommonAncestor = function (root, p, q) { + if (!root || root == p || root == q) return root; + const left = lowestCommonAncestor(root.left, p, q); + const right = lowestCommonAncestor(root.right, p, q); + if (!left) return right; + if (!right) return left; + return root; +}; ``` + + diff --git a/solution/0200-0299/0237.Delete Node in a Linked List/README.md b/solution/0200-0299/0237.Delete Node in a Linked List/README.md index f4631aac49e81..3200276756021 100644 --- a/solution/0200-0299/0237.Delete Node in a Linked List/README.md +++ b/solution/0200-0299/0237.Delete Node in a Linked List/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:节点赋值** +### 方法一:节点赋值 我们可以将当前节点的值替换为下一个节点的值,然后删除下一个节点。这样就可以达到删除当前节点的目的。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -91,10 +85,6 @@ class Solution: node.next = node.next.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -148,8 +134,6 @@ func deleteNode(node *ListNode) { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -172,7 +156,23 @@ function deleteNode(node: ListNode | null): void { } ``` -### **C#** +```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; +}; +``` ```cs /** @@ -191,30 +191,20 @@ public class Solution { } ``` -### **JavaScript** - -```js +```c /** * 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. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; */ -var deleteNode = function (node) { - node.val = node.next.val; - node.next = node.next.next; -}; -``` - -### **...** - -``` - +void deleteNode(struct ListNode* node) { + node->val = node->next->val; + node->next = node->next->next; +} ``` + + diff --git a/solution/0200-0299/0237.Delete Node in a Linked List/README_EN.md b/solution/0200-0299/0237.Delete Node in a Linked List/README_EN.md index fa1a0e6912793..5055c416e96e0 100644 --- a/solution/0200-0299/0237.Delete Node in a Linked List/README_EN.md +++ b/solution/0200-0299/0237.Delete Node in a Linked List/README_EN.md @@ -56,7 +56,7 @@ ## Solutions -**Solution 1: Node assignment** +### Solution 1: Node assignment We can replace the value of the current node with the value of the next node, and then delete the next node. This can achieve the purpose of deleting the current node. @@ -64,8 +64,6 @@ Time complexity $O(1)$, space complexity $O(1)$. -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -84,8 +82,6 @@ class Solution: node.next = node.next.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -103,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -123,8 +117,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -139,8 +131,6 @@ func deleteNode(node *ListNode) { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -163,7 +153,23 @@ function deleteNode(node: ListNode | null): void { } ``` -### **C#** +```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; +}; +``` ```cs /** @@ -182,30 +188,20 @@ public class Solution { } ``` -### **JavaScript** - -```js +```c /** * 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. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; */ -var deleteNode = function (node) { - node.val = node.next.val; - node.next = node.next.next; -}; -``` - -### **...** - -``` - +void deleteNode(struct ListNode* node) { + node->val = node->next->val; + node->next = node->next->next; +} ``` + + diff --git a/solution/0200-0299/0238.Product of Array Except Self/README.md b/solution/0200-0299/0238.Product of Array Except Self/README.md index 063b249024247..51d4e403dcef5 100644 --- a/solution/0200-0299/0238.Product of Array Except Self/README.md +++ b/solution/0200-0299/0238.Product of Array Except Self/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:两次遍历** +### 方法一:两次遍历 我们定义两个变量 $left$ 和 $right$,分别表示当前元素左边所有元素的乘积和右边所有元素的乘积。初始时 $left=1$, $right=1$。定义一个长度为 $n$ 的答案数组 $ans$。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] productExceptSelf(int[] nums) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func productExceptSelf(nums []int) []int { n := len(nums) @@ -141,30 +127,6 @@ func productExceptSelf(nums []int) []int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var productExceptSelf = function (nums) { - const n = nums.length; - const ans = new Array(n); - for (let i = 0, left = 1; i < n; ++i) { - ans[i] = left; - left *= nums[i]; - } - for (let i = n - 1, right = 1; i >= 0; --i) { - ans[i] *= right; - right *= nums[i]; - } - return ans; -}; -``` - -### **TypeScript** - ```ts function productExceptSelf(nums: number[]): number[] { const n = nums.length; @@ -181,14 +143,6 @@ function productExceptSelf(nums: number[]): number[] { } ``` -```ts -function productExceptSelf(nums: number[]): number[] { - return nums.map((_, i) => nums.reduce((pre, val, j) => pre * (i === j ? 1 : val), 1)); -} -``` - -### **Rust** - ```rust impl Solution { pub fn product_except_self(nums: Vec) -> Vec { @@ -207,7 +161,25 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var productExceptSelf = function (nums) { + const n = nums.length; + const ans = new Array(n); + for (let i = 0, left = 1; i < n; ++i) { + ans[i] = left; + left *= nums[i]; + } + for (let i = n - 1, right = 1; i >= 0; --i) { + ans[i] *= right; + right *= nums[i]; + } + return ans; +}; +``` ```cs public class Solution { @@ -227,8 +199,6 @@ public class Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -251,10 +221,18 @@ class Solution { } ``` -### **...** + + +### 方法二 -``` + +```ts +function productExceptSelf(nums: number[]): number[] { + return nums.map((_, i) => nums.reduce((pre, val, j) => pre * (i === j ? 1 : val), 1)); +} ``` + + diff --git a/solution/0200-0299/0238.Product of Array Except Self/README_EN.md b/solution/0200-0299/0238.Product of Array Except Self/README_EN.md index 1336f81da0e1d..a2543d293ada4 100644 --- a/solution/0200-0299/0238.Product of Array Except Self/README_EN.md +++ b/solution/0200-0299/0238.Product of Array Except Self/README_EN.md @@ -32,7 +32,7 @@ ## Solutions -**Solution 1: Two Passes** +### Solution 1: Two Passes We define two variables $left$ and $right$, which represent the product of all elements to the left and right of the current element respectively. Initially, $left=1$, $right=1$. Define an answer array $ans$ of length $n$. @@ -46,8 +46,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array `nums`. Igno -### **Python3** - ```python class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: @@ -63,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] productExceptSelf(int[] nums) { @@ -83,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +98,6 @@ public: }; ``` -### **Go** - ```go func productExceptSelf(nums []int) []int { n := len(nums) @@ -123,30 +115,6 @@ func productExceptSelf(nums []int) []int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var productExceptSelf = function (nums) { - const n = nums.length; - const ans = new Array(n); - for (let i = 0, left = 1; i < n; ++i) { - ans[i] = left; - left *= nums[i]; - } - for (let i = n - 1, right = 1; i >= 0; --i) { - ans[i] *= right; - right *= nums[i]; - } - return ans; -}; -``` - -### **TypeScript** - ```ts function productExceptSelf(nums: number[]): number[] { const n = nums.length; @@ -163,14 +131,6 @@ function productExceptSelf(nums: number[]): number[] { } ``` -```ts -function productExceptSelf(nums: number[]): number[] { - return nums.map((_, i) => nums.reduce((pre, val, j) => pre * (i === j ? 1 : val), 1)); -} -``` - -### **Rust** - ```rust impl Solution { pub fn product_except_self(nums: Vec) -> Vec { @@ -189,7 +149,25 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var productExceptSelf = function (nums) { + const n = nums.length; + const ans = new Array(n); + for (let i = 0, left = 1; i < n; ++i) { + ans[i] = left; + left *= nums[i]; + } + for (let i = n - 1, right = 1; i >= 0; --i) { + ans[i] *= right; + right *= nums[i]; + } + return ans; +}; +``` ```cs public class Solution { @@ -209,8 +187,6 @@ public class Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -233,10 +209,18 @@ class Solution { } ``` -### **...** + -``` +### Solution 2 + + +```ts +function productExceptSelf(nums: number[]): number[] { + return nums.map((_, i) => nums.reduce((pre, val, j) => pre * (i === j ? 1 : val), 1)); +} ``` + + diff --git a/solution/0200-0299/0239.Sliding Window Maximum/README.md b/solution/0200-0299/0239.Sliding Window Maximum/README.md index 7044302d1b78c..ef8006e218119 100644 --- a/solution/0200-0299/0239.Sliding Window Maximum/README.md +++ b/solution/0200-0299/0239.Sliding Window Maximum/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:优先队列(大根堆)** +### 方法一:优先队列(大根堆) 我们可以使用优先队列(大根堆)来维护滑动窗口中的最大值。 @@ -57,29 +55,8 @@ 时间复杂度 $O(n \times \log k)$,空间复杂度 $O(k)$。其中 $n$ 为数组长度。 -**方法二:单调队列** - -这道题也可以使用单调队列来解决。时间复杂度 $O(n)$,空间复杂度 $O(k)$。 - -单调队列常见模型:找出滑动窗口中的最大值/最小值。模板: - -```python -q = deque() -for i in range(n): - # 判断队头是否滑出窗口 - while q and checkout_out(q[0]): - q.popleft() - while q and check(q[-1]): - q.pop() - q.append(i) -``` - -### **Python3** - - - ```python class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: @@ -94,26 +71,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: - q = deque() - ans = [] - for i, v in enumerate(nums): - if q and i - k + 1 > q[0]: - q.popleft() - while q and nums[q[-1]] <= v: - q.pop() - q.append(i) - if i >= k - 1: - ans.append(nums[q[0]]) - return ans -``` - -### **Java** - - - ```java class Solution { public int[] maxSlidingWindow(int[] nums, int k) { @@ -136,31 +93,6 @@ class Solution { } ``` -```java -class Solution { - public int[] maxSlidingWindow(int[] nums, int k) { - int n = nums.length; - int[] ans = new int[n - k + 1]; - Deque q = new ArrayDeque<>(); - for (int i = 0, j = 0; i < n; ++i) { - if (!q.isEmpty() && i - k + 1 > q.peekFirst()) { - q.pollFirst(); - } - while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) { - q.pollLast(); - } - q.offer(i); - if (i >= k - 1) { - ans[j++] = nums[q.peekFirst()]; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -183,30 +115,35 @@ public: }; ``` -```cpp -class Solution { -public: - vector maxSlidingWindow(vector& nums, int k) { - deque q; - vector ans; - for (int i = 0; i < nums.size(); ++i) { - if (!q.empty() && i - k + 1 > q.front()) { - q.pop_front(); - } - while (!q.empty() && nums[q.back()] <= nums[i]) { - q.pop_back(); - } - q.push_back(i); - if (i >= k - 1) { - ans.emplace_back(nums[q.front()]); - } - } - return ans; - } -}; -``` +```go +func maxSlidingWindow(nums []int, k int) (ans []int) { + q := hp{} + for i, v := range nums[:k-1] { + heap.Push(&q, pair{v, i}) + } + for i := k - 1; i < len(nums); i++ { + heap.Push(&q, pair{nums[i], i}) + for q[0].i <= i-k { + heap.Pop(&q) + } + ans = append(ans, q[0].v) + } + return +} + +type pair struct{ v, i int } -### **Rust** +type hp []pair + +func (h hp) Len() int { return len(h) } +func (h hp) Less(i, j int) bool { + a, b := h[i], h[j] + return a.v > b.v || (a.v == b.v && i < j) +} +func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } +func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } +``` ```rust use std::collections::VecDeque; @@ -242,59 +179,6 @@ impl Solution { } ``` -### **Go** - -```go -func maxSlidingWindow(nums []int, k int) (ans []int) { - q := hp{} - for i, v := range nums[:k-1] { - heap.Push(&q, pair{v, i}) - } - for i := k - 1; i < len(nums); i++ { - heap.Push(&q, pair{nums[i], i}) - for q[0].i <= i-k { - heap.Pop(&q) - } - ans = append(ans, q[0].v) - } - return -} - -type pair struct{ v, i int } - -type hp []pair - -func (h hp) Len() int { return len(h) } -func (h hp) Less(i, j int) bool { - a, b := h[i], h[j] - return a.v > b.v || (a.v == b.v && i < j) -} -func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } -func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } -``` - -```go -func maxSlidingWindow(nums []int, k int) (ans []int) { - q := []int{} - for i, v := range nums { - if len(q) > 0 && i-k+1 > q[0] { - q = q[1:] - } - for len(q) > 0 && nums[q[len(q)-1]] <= v { - q = q[:len(q)-1] - } - q = append(q, i) - if i >= k-1 { - ans = append(ans, nums[q[0]]) - } - } - return ans -} -``` - -### **JavaScript** - ```js /** * @param {number[]} nums @@ -320,10 +204,137 @@ var maxSlidingWindow = function (nums, k) { }; ``` -### **...** +```cs +using System.Collections.Generic; + +public class Solution { + public int[] MaxSlidingWindow(int[] nums, int k) { + if (nums.Length == 0) return new int[0]; + var result = new int[nums.Length - k + 1]; + var descOrderNums = new LinkedList(); + for (var i = 0; i < nums.Length; ++i) + { + if (i >= k && nums[i - k] == descOrderNums.First.Value) + { + descOrderNums.RemoveFirst(); + } + while (descOrderNums.Count > 0 && nums[i] > descOrderNums.Last.Value) + { + descOrderNums.RemoveLast(); + } + descOrderNums.AddLast(nums[i]); + if (i >= k - 1) + { + result[i - k + 1] = descOrderNums.First.Value; + } + } + return result; + } +} +``` + + +### 方法二:单调队列 + +这道题也可以使用单调队列来解决。时间复杂度 $O(n)$,空间复杂度 $O(k)$。 + +单调队列常见模型:找出滑动窗口中的最大值/最小值。模板: + +```python +q = deque() +for i in range(n): + # 判断队头是否滑出窗口 + while q and checkout_out(q[0]): + q.popleft() + while q and check(q[-1]): + q.pop() + q.append(i) ``` + + +```python +class Solution: + def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: + q = deque() + ans = [] + for i, v in enumerate(nums): + if q and i - k + 1 > q[0]: + q.popleft() + while q and nums[q[-1]] <= v: + q.pop() + q.append(i) + if i >= k - 1: + ans.append(nums[q[0]]) + return ans +``` + +```java +class Solution { + public int[] maxSlidingWindow(int[] nums, int k) { + int n = nums.length; + int[] ans = new int[n - k + 1]; + Deque q = new ArrayDeque<>(); + for (int i = 0, j = 0; i < n; ++i) { + if (!q.isEmpty() && i - k + 1 > q.peekFirst()) { + q.pollFirst(); + } + while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) { + q.pollLast(); + } + q.offer(i); + if (i >= k - 1) { + ans[j++] = nums[q.peekFirst()]; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + deque q; + vector ans; + for (int i = 0; i < nums.size(); ++i) { + if (!q.empty() && i - k + 1 > q.front()) { + q.pop_front(); + } + while (!q.empty() && nums[q.back()] <= nums[i]) { + q.pop_back(); + } + q.push_back(i); + if (i >= k - 1) { + ans.emplace_back(nums[q.front()]); + } + } + return ans; + } +}; +``` + +```go +func maxSlidingWindow(nums []int, k int) (ans []int) { + q := []int{} + for i, v := range nums { + if len(q) > 0 && i-k+1 > q[0] { + q = q[1:] + } + for len(q) > 0 && nums[q[len(q)-1]] <= v { + q = q[:len(q)-1] + } + q = append(q, i) + if i >= k-1 { + ans = append(ans, nums[q[0]]) + } + } + return ans +} ``` + + diff --git a/solution/0200-0299/0239.Sliding Window Maximum/README_EN.md b/solution/0200-0299/0239.Sliding Window Maximum/README_EN.md index 279315714e278..1f25e4c5e6e54 100644 --- a/solution/0200-0299/0239.Sliding Window Maximum/README_EN.md +++ b/solution/0200-0299/0239.Sliding Window Maximum/README_EN.md @@ -43,9 +43,9 @@ Window position Max ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,24 +61,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: - q = deque() - ans = [] - for i, v in enumerate(nums): - if q and i - k + 1 > q[0]: - q.popleft() - while q and nums[q[-1]] <= v: - q.pop() - q.append(i) - if i >= k - 1: - ans.append(nums[q[0]]) - return ans -``` - -### **Java** - ```java class Solution { public int[] maxSlidingWindow(int[] nums, int k) { @@ -101,31 +83,6 @@ class Solution { } ``` -```java -class Solution { - public int[] maxSlidingWindow(int[] nums, int k) { - int n = nums.length; - int[] ans = new int[n - k + 1]; - Deque q = new ArrayDeque<>(); - for (int i = 0, j = 0; i < n; ++i) { - if (!q.isEmpty() && i - k + 1 > q.peekFirst()) { - q.pollFirst(); - } - while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) { - q.pollLast(); - } - q.offer(i); - if (i >= k - 1) { - ans[j++] = nums[q.peekFirst()]; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -148,30 +105,35 @@ public: }; ``` -```cpp -class Solution { -public: - vector maxSlidingWindow(vector& nums, int k) { - deque q; - vector ans; - for (int i = 0; i < nums.size(); ++i) { - if (!q.empty() && i - k + 1 > q.front()) { - q.pop_front(); - } - while (!q.empty() && nums[q.back()] <= nums[i]) { - q.pop_back(); - } - q.push_back(i); - if (i >= k - 1) { - ans.emplace_back(nums[q.front()]); - } - } - return ans; - } -}; -``` +```go +func maxSlidingWindow(nums []int, k int) (ans []int) { + q := hp{} + for i, v := range nums[:k-1] { + heap.Push(&q, pair{v, i}) + } + for i := k - 1; i < len(nums); i++ { + heap.Push(&q, pair{nums[i], i}) + for q[0].i <= i-k { + heap.Pop(&q) + } + ans = append(ans, q[0].v) + } + return +} + +type pair struct{ v, i int } + +type hp []pair -### **Rust** +func (h hp) Len() int { return len(h) } +func (h hp) Less(i, j int) bool { + a, b := h[i], h[j] + return a.v > b.v || (a.v == b.v && i < j) +} +func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } +func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } +``` ```rust use std::collections::VecDeque; @@ -207,59 +169,6 @@ impl Solution { } ``` -### **Go** - -```go -func maxSlidingWindow(nums []int, k int) (ans []int) { - q := hp{} - for i, v := range nums[:k-1] { - heap.Push(&q, pair{v, i}) - } - for i := k - 1; i < len(nums); i++ { - heap.Push(&q, pair{nums[i], i}) - for q[0].i <= i-k { - heap.Pop(&q) - } - ans = append(ans, q[0].v) - } - return -} - -type pair struct{ v, i int } - -type hp []pair - -func (h hp) Len() int { return len(h) } -func (h hp) Less(i, j int) bool { - a, b := h[i], h[j] - return a.v > b.v || (a.v == b.v && i < j) -} -func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } -func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } -``` - -```go -func maxSlidingWindow(nums []int, k int) (ans []int) { - q := []int{} - for i, v := range nums { - if len(q) > 0 && i-k+1 > q[0] { - q = q[1:] - } - for len(q) > 0 && nums[q[len(q)-1]] <= v { - q = q[:len(q)-1] - } - q = append(q, i) - if i >= k-1 { - ans = append(ans, nums[q[0]]) - } - } - return ans -} -``` - -### **JavaScript** - ```js /** * @param {number[]} nums @@ -285,10 +194,122 @@ var maxSlidingWindow = function (nums, k) { }; ``` -### **...** +```cs +using System.Collections.Generic; + +public class Solution { + public int[] MaxSlidingWindow(int[] nums, int k) { + if (nums.Length == 0) return new int[0]; + var result = new int[nums.Length - k + 1]; + var descOrderNums = new LinkedList(); + for (var i = 0; i < nums.Length; ++i) + { + if (i >= k && nums[i - k] == descOrderNums.First.Value) + { + descOrderNums.RemoveFirst(); + } + while (descOrderNums.Count > 0 && nums[i] > descOrderNums.Last.Value) + { + descOrderNums.RemoveLast(); + } + descOrderNums.AddLast(nums[i]); + if (i >= k - 1) + { + result[i - k + 1] = descOrderNums.First.Value; + } + } + return result; + } +} +``` + + +### Solution 2 + + + +```python +class Solution: + def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: + q = deque() + ans = [] + for i, v in enumerate(nums): + if q and i - k + 1 > q[0]: + q.popleft() + while q and nums[q[-1]] <= v: + q.pop() + q.append(i) + if i >= k - 1: + ans.append(nums[q[0]]) + return ans ``` +```java +class Solution { + public int[] maxSlidingWindow(int[] nums, int k) { + int n = nums.length; + int[] ans = new int[n - k + 1]; + Deque q = new ArrayDeque<>(); + for (int i = 0, j = 0; i < n; ++i) { + if (!q.isEmpty() && i - k + 1 > q.peekFirst()) { + q.pollFirst(); + } + while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) { + q.pollLast(); + } + q.offer(i); + if (i >= k - 1) { + ans[j++] = nums[q.peekFirst()]; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + deque q; + vector ans; + for (int i = 0; i < nums.size(); ++i) { + if (!q.empty() && i - k + 1 > q.front()) { + q.pop_front(); + } + while (!q.empty() && nums[q.back()] <= nums[i]) { + q.pop_back(); + } + q.push_back(i); + if (i >= k - 1) { + ans.emplace_back(nums[q.front()]); + } + } + return ans; + } +}; +``` + +```go +func maxSlidingWindow(nums []int, k int) (ans []int) { + q := []int{} + for i, v := range nums { + if len(q) > 0 && i-k+1 > q[0] { + q = q[1:] + } + for len(q) > 0 && nums[q[len(q)-1]] <= v { + q = q[:len(q)-1] + } + q = append(q, i) + if i >= k-1 { + ans = append(ans, nums[q[0]]) + } + } + return ans +} ``` + + diff --git a/solution/0200-0299/0240.Search a 2D Matrix II/README.md b/solution/0200-0299/0240.Search a 2D Matrix II/README.md index 34e47f18fb678..eba4e74ed4325 100644 --- a/solution/0200-0299/0240.Search a 2D Matrix II/README.md +++ b/solution/0200-0299/0240.Search a 2D Matrix II/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 由于每一行的所有元素升序排列,因此,对于每一行,我们可以使用二分查找找到第一个大于等于 `target` 的元素,然后判断该元素是否等于 `target`。如果等于 `target`,说明找到了目标值,直接返回 `true`。如果不等于 `target`,说明这一行的所有元素都小于 `target`,应该继续搜索下一行。 @@ -55,24 +53,8 @@ 时间复杂度 $O(m \times \log n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。 -**方法二:从左下角或右上角搜索** - -这里我们以左下角作为起始搜索点,往右上方向开始搜索,比较当前元素 `matrix[i][j]`与 `target` 的大小关系: - -- 若 `matrix[i][j] == target`,说明找到了目标值,直接返回 `true`。 -- 若 `matrix[i][j] > target`,说明这一行从当前位置开始往右的所有元素均大于 `target`,应该让 $i$ 指针往上移动,即 $i \leftarrow i - 1$。 -- 若 `matrix[i][j] < target`,说明这一列从当前位置开始往上的所有元素均小于 `target`,应该让 $j$ 指针往右移动,即 $j \leftarrow j + 1$。 - -若搜索结束依然找不到 `target`,返回 `false`。 - -时间复杂度 $O(m + n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。 - -### **Python3** - - - ```python class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: @@ -83,25 +65,6 @@ class Solution: return False ``` -```python -class Solution: - def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: - m, n = len(matrix), len(matrix[0]) - i, j = m - 1, 0 - while i >= 0 and j < n: - if matrix[i][j] == target: - return True - if matrix[i][j] > target: - i -= 1 - else: - j += 1 - return False -``` - -### **Java** - - - ```java class Solution { public boolean searchMatrix(int[][] matrix, int target) { @@ -116,28 +79,6 @@ class Solution { } ``` -```java -class Solution { - public boolean searchMatrix(int[][] matrix, int target) { - int m = matrix.length, n = matrix[0].length; - int i = m - 1, j = 0; - while (i >= 0 && j < n) { - if (matrix[i][j] == target) { - return true; - } - if (matrix[i][j] > target) { - --i; - } else { - ++j; - } - } - return false; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -153,29 +94,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool searchMatrix(vector>& matrix, int target) { - int m = matrix.size(), n = matrix[0].size(); - int i = m - 1, j = 0; - while (i >= 0 && j < n) { - if (matrix[i][j] == target) { - return true; - } - if (matrix[i][j] > target) { - --i; - } else { - ++j; - } - } - return false; - } -}; -``` - -### **Go** - ```go func searchMatrix(matrix [][]int, target int) bool { for _, row := range matrix { @@ -188,26 +106,6 @@ func searchMatrix(matrix [][]int, target int) bool { } ``` -```go -func searchMatrix(matrix [][]int, target int) bool { - m, n := len(matrix), len(matrix[0]) - i, j := m-1, 0 - for i >= 0 && j < n { - if matrix[i][j] == target { - return true - } - if matrix[i][j] > target { - i-- - } else { - j++ - } - } - return false -} -``` - -### **TypeScript** - ```ts function searchMatrix(matrix: number[][], target: number): boolean { const n = matrix[0].length; @@ -230,63 +128,6 @@ function searchMatrix(matrix: number[][], target: number): boolean { } ``` -```ts -function searchMatrix(matrix: number[][], target: number): boolean { - let m = matrix.length, - n = matrix[0].length; - let i = m - 1, - j = 0; - while (i >= 0 && j < n) { - let cur = matrix[i][j]; - if (cur == target) return true; - if (cur > target) { - --i; - } else { - ++j; - } - } - return false; -} -``` - -### **C#** - -```cs -public class Solution { - public bool SearchMatrix(int[][] matrix, int target) { - foreach (int[] row in matrix) { - int j = Array.BinarySearch(row, target); - if (j >= 0) { - return true; - } - } - return false; - } -} -``` - -```cs -public class Solution { - public bool SearchMatrix(int[][] matrix, int target) { - int m = matrix.Length, n = matrix[0].Length; - int i = m - 1, j = 0; - while (i >= 0 && j < n) { - if (matrix[i][j] == target) { - return true; - } - if (matrix[i][j] > target) { - --i; - } else { - ++j; - } - } - return false; - } -} -``` - -### **Rust** - ```rust use std::cmp::Ordering; @@ -314,8 +155,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[][]} matrix @@ -343,10 +182,149 @@ var searchMatrix = function (matrix, target) { }; ``` -### **...** +```cs +public class Solution { + public bool SearchMatrix(int[][] matrix, int target) { + foreach (int[] row in matrix) { + int j = Array.BinarySearch(row, target); + if (j >= 0) { + return true; + } + } + return false; + } +} +``` + + + +### 方法二:从左下角或右上角搜索 + +这里我们以左下角作为起始搜索点,往右上方向开始搜索,比较当前元素 `matrix[i][j]`与 `target` 的大小关系: + +- 若 `matrix[i][j] == target`,说明找到了目标值,直接返回 `true`。 +- 若 `matrix[i][j] > target`,说明这一行从当前位置开始往右的所有元素均大于 `target`,应该让 $i$ 指针往上移动,即 $i \leftarrow i - 1$。 +- 若 `matrix[i][j] < target`,说明这一列从当前位置开始往上的所有元素均小于 `target`,应该让 $j$ 指针往右移动,即 $j \leftarrow j + 1$。 + +若搜索结束依然找不到 `target`,返回 `false`。 +时间复杂度 $O(m + n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。 + + + +```python +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + m, n = len(matrix), len(matrix[0]) + i, j = m - 1, 0 + while i >= 0 and j < n: + if matrix[i][j] == target: + return True + if matrix[i][j] > target: + i -= 1 + else: + j += 1 + return False ``` +```java +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int m = matrix.length, n = matrix[0].length; + int i = m - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +} +``` + +```cpp +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + int m = matrix.size(), n = matrix[0].size(); + int i = m - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +}; +``` + +```go +func searchMatrix(matrix [][]int, target int) bool { + m, n := len(matrix), len(matrix[0]) + i, j := m-1, 0 + for i >= 0 && j < n { + if matrix[i][j] == target { + return true + } + if matrix[i][j] > target { + i-- + } else { + j++ + } + } + return false +} +``` + +```ts +function searchMatrix(matrix: number[][], target: number): boolean { + let m = matrix.length, + n = matrix[0].length; + let i = m - 1, + j = 0; + while (i >= 0 && j < n) { + let cur = matrix[i][j]; + if (cur == target) return true; + if (cur > target) { + --i; + } else { + ++j; + } + } + return false; +} +``` + +```cs +public class Solution { + public bool SearchMatrix(int[][] matrix, int target) { + int m = matrix.Length, n = matrix[0].Length; + int i = m - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +} ``` + + diff --git a/solution/0200-0299/0240.Search a 2D Matrix II/README_EN.md b/solution/0200-0299/0240.Search a 2D Matrix II/README_EN.md index 261c99e538125..103bdc184c9ab 100644 --- a/solution/0200-0299/0240.Search a 2D Matrix II/README_EN.md +++ b/solution/0200-0299/0240.Search a 2D Matrix II/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,23 +55,6 @@ class Solution: return False ``` -```python -class Solution: - def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: - m, n = len(matrix), len(matrix[0]) - i, j = m - 1, 0 - while i >= 0 and j < n: - if matrix[i][j] == target: - return True - if matrix[i][j] > target: - i -= 1 - else: - j += 1 - return False -``` - -### **Java** - ```java class Solution { public boolean searchMatrix(int[][] matrix, int target) { @@ -86,28 +69,6 @@ class Solution { } ``` -```java -class Solution { - public boolean searchMatrix(int[][] matrix, int target) { - int m = matrix.length, n = matrix[0].length; - int i = m - 1, j = 0; - while (i >= 0 && j < n) { - if (matrix[i][j] == target) { - return true; - } - if (matrix[i][j] > target) { - --i; - } else { - ++j; - } - } - return false; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -123,29 +84,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool searchMatrix(vector>& matrix, int target) { - int m = matrix.size(), n = matrix[0].size(); - int i = m - 1, j = 0; - while (i >= 0 && j < n) { - if (matrix[i][j] == target) { - return true; - } - if (matrix[i][j] > target) { - --i; - } else { - ++j; - } - } - return false; - } -}; -``` - -### **Go** - ```go func searchMatrix(matrix [][]int, target int) bool { for _, row := range matrix { @@ -158,26 +96,6 @@ func searchMatrix(matrix [][]int, target int) bool { } ``` -```go -func searchMatrix(matrix [][]int, target int) bool { - m, n := len(matrix), len(matrix[0]) - i, j := m-1, 0 - for i >= 0 && j < n { - if matrix[i][j] == target { - return true - } - if matrix[i][j] > target { - i-- - } else { - j++ - } - } - return false -} -``` - -### **TypeScript** - ```ts function searchMatrix(matrix: number[][], target: number): boolean { const n = matrix[0].length; @@ -200,63 +118,6 @@ function searchMatrix(matrix: number[][], target: number): boolean { } ``` -```ts -function searchMatrix(matrix: number[][], target: number): boolean { - let m = matrix.length, - n = matrix[0].length; - let i = m - 1, - j = 0; - while (i >= 0 && j < n) { - let cur = matrix[i][j]; - if (cur == target) return true; - if (cur > target) { - --i; - } else { - ++j; - } - } - return false; -} -``` - -### **C#** - -```cs -public class Solution { - public bool SearchMatrix(int[][] matrix, int target) { - foreach (int[] row in matrix) { - int j = Array.BinarySearch(row, target); - if (j >= 0) { - return true; - } - } - return false; - } -} -``` - -```cs -public class Solution { - public bool SearchMatrix(int[][] matrix, int target) { - int m = matrix.Length, n = matrix[0].Length; - int i = m - 1, j = 0; - while (i >= 0 && j < n) { - if (matrix[i][j] == target) { - return true; - } - if (matrix[i][j] > target) { - --i; - } else { - ++j; - } - } - return false; - } -} -``` - -### **Rust** - ```rust use std::cmp::Ordering; @@ -284,8 +145,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[][]} matrix @@ -313,10 +172,139 @@ var searchMatrix = function (matrix, target) { }; ``` -### **...** +```cs +public class Solution { + public bool SearchMatrix(int[][] matrix, int target) { + foreach (int[] row in matrix) { + int j = Array.BinarySearch(row, target); + if (j >= 0) { + return true; + } + } + return false; + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + m, n = len(matrix), len(matrix[0]) + i, j = m - 1, 0 + while i >= 0 and j < n: + if matrix[i][j] == target: + return True + if matrix[i][j] > target: + i -= 1 + else: + j += 1 + return False +``` + +```java +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int m = matrix.length, n = matrix[0].length; + int i = m - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +} +``` + +```cpp +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + int m = matrix.size(), n = matrix[0].size(); + int i = m - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +}; +``` + +```go +func searchMatrix(matrix [][]int, target int) bool { + m, n := len(matrix), len(matrix[0]) + i, j := m-1, 0 + for i >= 0 && j < n { + if matrix[i][j] == target { + return true + } + if matrix[i][j] > target { + i-- + } else { + j++ + } + } + return false +} +``` +```ts +function searchMatrix(matrix: number[][], target: number): boolean { + let m = matrix.length, + n = matrix[0].length; + let i = m - 1, + j = 0; + while (i >= 0 && j < n) { + let cur = matrix[i][j]; + if (cur == target) return true; + if (cur > target) { + --i; + } else { + ++j; + } + } + return false; +} ``` +```cs +public class Solution { + public bool SearchMatrix(int[][] matrix, int target) { + int m = matrix.Length, n = matrix[0].Length; + int i = m - 1, j = 0; + while (i >= 0 && j < n) { + if (matrix[i][j] == target) { + return true; + } + if (matrix[i][j] > target) { + --i; + } else { + ++j; + } + } + return false; + } +} ``` + + diff --git a/solution/0200-0299/0241.Different Ways to Add Parentheses/README.md b/solution/0200-0299/0241.Different Ways to Add Parentheses/README.md index f7303a8b3a1d7..e3a9c71e8bd8b 100644 --- a/solution/0200-0299/0241.Different Ways to Add Parentheses/README.md +++ b/solution/0200-0299/0241.Different Ways to Add Parentheses/README.md @@ -47,16 +47,10 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 -### **Python3** - - - ```python class Solution: def diffWaysToCompute(self, expression: str) -> List[int]: @@ -81,10 +75,6 @@ class Solution: return dfs(expression) ``` -### **Java** - - - ```java class Solution { private static Map> memo = new HashMap<>(); @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -166,8 +154,6 @@ private: }; ``` -### **Go** - ```go var memo = map[string][]int{} @@ -205,10 +191,70 @@ func dfs(exp string) []int { } ``` -### **...** +```cs +using System.Collections.Generic; + +public class Solution { + public IList DiffWaysToCompute(string input) { + var values = new List(); + var operators = new List(); + var sum = 0; + foreach (var ch in input) + { + if (ch == '+' || ch == '-' || ch == '*') + { + values.Add(sum); + operators.Add(ch); + sum = 0; + } + else + { + sum = sum * 10 + ch - '0'; + } + } + values.Add(sum); -``` + var f = new List[values.Count, values.Count]; + for (var i = 0; i < values.Count; ++i) + { + f[i, i] = new List { values[i] }; + } + + for (var diff = 1; diff < values.Count; ++diff) + { + for (var left = 0; left + diff < values.Count; ++left) + { + var right = left + diff; + f[left, right] = new List(); + for (var i = left; i < right; ++i) + { + foreach (var leftValue in f[left, i]) + { + foreach (var rightValue in f[i + 1, right]) + { + switch (operators[i]) + { + case '+': + f[left, right].Add(leftValue + rightValue); + break; + case '-': + f[left, right].Add(leftValue - rightValue); + break; + case '*': + f[left, right].Add(leftValue * rightValue); + break; + } + } + } + } + } + } + return f[0, values.Count - 1]; + } +} ``` + + diff --git a/solution/0200-0299/0241.Different Ways to Add Parentheses/README_EN.md b/solution/0200-0299/0241.Different Ways to Add Parentheses/README_EN.md index 50e4f23e41532..fd8fb8bef1d88 100644 --- a/solution/0200-0299/0241.Different Ways to Add Parentheses/README_EN.md +++ b/solution/0200-0299/0241.Different Ways to Add Parentheses/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return dfs(expression) ``` -### **Java** - ```java class Solution { private static Map> memo = new HashMap<>(); @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +150,6 @@ private: }; ``` -### **Go** - ```go var memo = map[string][]int{} @@ -193,10 +187,70 @@ func dfs(exp string) []int { } ``` -### **...** +```cs +using System.Collections.Generic; -``` +public class Solution { + public IList DiffWaysToCompute(string input) { + var values = new List(); + var operators = new List(); + var sum = 0; + foreach (var ch in input) + { + if (ch == '+' || ch == '-' || ch == '*') + { + values.Add(sum); + operators.Add(ch); + sum = 0; + } + else + { + sum = sum * 10 + ch - '0'; + } + } + values.Add(sum); + + var f = new List[values.Count, values.Count]; + for (var i = 0; i < values.Count; ++i) + { + f[i, i] = new List { values[i] }; + } + + for (var diff = 1; diff < values.Count; ++diff) + { + for (var left = 0; left + diff < values.Count; ++left) + { + var right = left + diff; + f[left, right] = new List(); + for (var i = left; i < right; ++i) + { + foreach (var leftValue in f[left, i]) + { + foreach (var rightValue in f[i + 1, right]) + { + switch (operators[i]) + { + case '+': + f[left, right].Add(leftValue + rightValue); + break; + case '-': + f[left, right].Add(leftValue - rightValue); + break; + case '*': + f[left, right].Add(leftValue * rightValue); + break; + } + } + } + } + } + } + return f[0, values.Count - 1]; + } +} ``` + + diff --git a/solution/0200-0299/0242.Valid Anagram/README.md b/solution/0200-0299/0242.Valid Anagram/README.md index 6f15152936927..aee582c1a44c4 100644 --- a/solution/0200-0299/0242.Valid Anagram/README.md +++ b/solution/0200-0299/0242.Valid Anagram/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们先判断两个字符串的长度是否相等,如果不相等,说明两个字符串中的字符肯定不同,返回 `false`。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def isAnagram(self, s: str, t: str) -> bool: @@ -69,16 +63,6 @@ class Solution: return True ``` -```python -class Solution: - def isAnagram(self, s: str, t: str) -> bool: - return Counter(s) == Counter(t) -``` - -### **Java** - - - ```java class Solution { public boolean isAnagram(String s, String t) { @@ -100,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +101,6 @@ public: }; ``` -### **Go** - ```go func isAnagram(s string, t string) bool { if len(s) != len(t) { @@ -140,15 +120,8 @@ func isAnagram(s string, t string) bool { } ``` -### **JavaScript** - -```js -/** - * @param {string} s - * @param {string} t - * @return {boolean} - */ -var isAnagram = function (s, t) { +```ts +function isAnagram(s: string, t: string): boolean { if (s.length !== t.length) { return false; } @@ -158,13 +131,38 @@ var isAnagram = function (s, t) { --cnt[t.charCodeAt(i) - 'a'.charCodeAt(0)]; } return cnt.every(x => x === 0); -}; +} ``` -### **TypeScript** +```rust +impl Solution { + pub fn is_anagram(s: String, t: String) -> bool { + let n = s.len(); + let m = t.len(); + if n != m { + return false; + } + let mut s = s.chars().collect::>(); + let mut t = t.chars().collect::>(); + s.sort(); + t.sort(); + for i in 0..n { + if s[i] != t[i] { + return false; + } + } + true + } +} +``` -```ts -function isAnagram(s: string, t: string): boolean { +```js +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isAnagram = function (s, t) { if (s.length !== t.length) { return false; } @@ -174,11 +172,9 @@ function isAnagram(s: string, t: string): boolean { --cnt[t.charCodeAt(i) - 'a'.charCodeAt(0)]; } return cnt.every(x => x === 0); -} +}; ``` -### **C#** - ```cs public class Solution { public bool IsAnagram(string s, string t) { @@ -195,30 +191,35 @@ public class Solution { } ``` -### **Rust** +```c +int cmp(const void* a, const void* b) { + return *(char*) a - *(char*) b; +} -```rust -impl Solution { - pub fn is_anagram(s: String, t: String) -> bool { - let n = s.len(); - let m = t.len(); - if n != m { - return false; - } - let mut s = s.chars().collect::>(); - let mut t = t.chars().collect::>(); - s.sort(); - t.sort(); - for i in 0..n { - if s[i] != t[i] { - return false; - } - } - true +bool isAnagram(char* s, char* t) { + int n = strlen(s); + int m = strlen(t); + if (n != m) { + return 0; } + qsort(s, n, sizeof(char), cmp); + qsort(t, n, sizeof(char), cmp); + return !strcmp(s, t); } ``` + + +### 方法二 + + + +```python +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + return Counter(s) == Counter(t) +``` + ```rust impl Solution { pub fn is_anagram(s: String, t: String) -> bool { @@ -238,25 +239,6 @@ impl Solution { } ``` -### **C** - -```c -int cmp(const void* a, const void* b) { - return *(char*) a - *(char*) b; -} - -bool isAnagram(char* s, char* t) { - int n = strlen(s); - int m = strlen(t); - if (n != m) { - return 0; - } - qsort(s, n, sizeof(char), cmp); - qsort(t, n, sizeof(char), cmp); - return !strcmp(s, t); -} -``` - ```c bool isAnagram(char* s, char* t) { int n = strlen(s); @@ -278,10 +260,6 @@ bool isAnagram(char* s, char* t) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0242.Valid Anagram/README_EN.md b/solution/0200-0299/0242.Valid Anagram/README_EN.md index 051fd68878b1b..b69b11c4cf65e 100644 --- a/solution/0200-0299/0242.Valid Anagram/README_EN.md +++ b/solution/0200-0299/0242.Valid Anagram/README_EN.md @@ -29,7 +29,7 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We first determine whether the length of the two strings is equal. If they are not equal, the characters in the two strings must be different, so return `false`. @@ -39,8 +39,6 @@ The time complexity is $O(n)$, the space complexity is $O(C)$, where $n$ is the -### **Python3** - ```python class Solution: def isAnagram(self, s: str, t: str) -> bool: @@ -54,14 +52,6 @@ class Solution: return True ``` -```python -class Solution: - def isAnagram(self, s: str, t: str) -> bool: - return Counter(s) == Counter(t) -``` - -### **Java** - ```java class Solution { public boolean isAnagram(String s, String t) { @@ -83,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +90,6 @@ public: }; ``` -### **Go** - ```go func isAnagram(s string, t string) bool { if len(s) != len(t) { @@ -123,15 +109,8 @@ func isAnagram(s string, t string) bool { } ``` -### **JavaScript** - -```js -/** - * @param {string} s - * @param {string} t - * @return {boolean} - */ -var isAnagram = function (s, t) { +```ts +function isAnagram(s: string, t: string): boolean { if (s.length !== t.length) { return false; } @@ -141,13 +120,38 @@ var isAnagram = function (s, t) { --cnt[t.charCodeAt(i) - 'a'.charCodeAt(0)]; } return cnt.every(x => x === 0); -}; +} ``` -### **TypeScript** +```rust +impl Solution { + pub fn is_anagram(s: String, t: String) -> bool { + let n = s.len(); + let m = t.len(); + if n != m { + return false; + } + let mut s = s.chars().collect::>(); + let mut t = t.chars().collect::>(); + s.sort(); + t.sort(); + for i in 0..n { + if s[i] != t[i] { + return false; + } + } + true + } +} +``` -```ts -function isAnagram(s: string, t: string): boolean { +```js +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isAnagram = function (s, t) { if (s.length !== t.length) { return false; } @@ -157,11 +161,9 @@ function isAnagram(s: string, t: string): boolean { --cnt[t.charCodeAt(i) - 'a'.charCodeAt(0)]; } return cnt.every(x => x === 0); -} +}; ``` -### **C#** - ```cs public class Solution { public bool IsAnagram(string s, string t) { @@ -178,30 +180,35 @@ public class Solution { } ``` -### **Rust** +```c +int cmp(const void* a, const void* b) { + return *(char*) a - *(char*) b; +} -```rust -impl Solution { - pub fn is_anagram(s: String, t: String) -> bool { - let n = s.len(); - let m = t.len(); - if n != m { - return false; - } - let mut s = s.chars().collect::>(); - let mut t = t.chars().collect::>(); - s.sort(); - t.sort(); - for i in 0..n { - if s[i] != t[i] { - return false; - } - } - true +bool isAnagram(char* s, char* t) { + int n = strlen(s); + int m = strlen(t); + if (n != m) { + return 0; } + qsort(s, n, sizeof(char), cmp); + qsort(t, n, sizeof(char), cmp); + return !strcmp(s, t); } ``` + + +### Solution 2 + + + +```python +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + return Counter(s) == Counter(t) +``` + ```rust impl Solution { pub fn is_anagram(s: String, t: String) -> bool { @@ -221,25 +228,6 @@ impl Solution { } ``` -### **C** - -```c -int cmp(const void* a, const void* b) { - return *(char*) a - *(char*) b; -} - -bool isAnagram(char* s, char* t) { - int n = strlen(s); - int m = strlen(t); - if (n != m) { - return 0; - } - qsort(s, n, sizeof(char), cmp); - qsort(t, n, sizeof(char), cmp); - return !strcmp(s, t); -} -``` - ```c bool isAnagram(char* s, char* t) { int n = strlen(s); @@ -261,10 +249,6 @@ bool isAnagram(char* s, char* t) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0243.Shortest Word Distance/README.md b/solution/0200-0299/0243.Shortest Word Distance/README.md index 0e47aace72c0c..869b58513793b 100644 --- a/solution/0200-0299/0243.Shortest Word Distance/README.md +++ b/solution/0200-0299/0243.Shortest Word Distance/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 遍历数组 `wordsDict`,找到 `word1` 和 `word2` 的下标 $i$ 和 $j$,求 $i-j$ 的最小值。 @@ -47,10 +45,6 @@ -### **Python3** - - - ```python class Solution: def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: @@ -66,10 +60,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int shortestDistance(String[] wordsDict, String word1, String word2) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func shortestDistance(wordsDict []string, word1 string, word2 string) int { ans := 0x3f3f3f3f @@ -141,10 +127,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0243.Shortest Word Distance/README_EN.md b/solution/0200-0299/0243.Shortest Word Distance/README_EN.md index 2b1c9d695fa5e..5fe74c747d119 100644 --- a/solution/0200-0299/0243.Shortest Word Distance/README_EN.md +++ b/solution/0200-0299/0243.Shortest Word Distance/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int shortestDistance(String[] wordsDict, String word1, String word2) { @@ -75,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +94,6 @@ public: }; ``` -### **Go** - ```go func shortestDistance(wordsDict []string, word1 string, word2 string) int { ans := 0x3f3f3f3f @@ -126,10 +120,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0244.Shortest Word Distance II/README.md b/solution/0200-0299/0244.Shortest Word Distance II/README.md index 64318ef322e5c..abfccc9fa3485 100644 --- a/solution/0200-0299/0244.Shortest Word Distance II/README.md +++ b/solution/0200-0299/0244.Shortest Word Distance II/README.md @@ -46,9 +46,7 @@ wordDistance.shortest("makes", "coding"); // 返回 1 ## 解法 - - -**方法一:哈希表 + 双指针** +### 方法一:哈希表 + 双指针 我们用哈希表 $d$ 存储每个单词在数组中出现的所有下标,然后用双指针 $i$ 和 $j$ 分别指向两个单词在数组中出现的下标列表 $a$ 和 $b$,每次更新下标差值的最小值,然后移动下标较小的指针,直到其中一个指针遍历完下标列表。 @@ -56,10 +54,6 @@ wordDistance.shortest("makes", "coding"); // 返回 1 -### **Python3** - - - ```python class WordDistance: def __init__(self, wordsDict: List[str]): @@ -85,10 +79,6 @@ class WordDistance: # param_1 = obj.shortest(word1,word2) ``` -### **Java** - - - ```java class WordDistance { private Map> d = new HashMap<>(); @@ -122,8 +112,6 @@ class WordDistance { */ ``` -### **C++** - ```cpp class WordDistance { public: @@ -159,8 +147,6 @@ private: */ ``` -### **Go** - ```go type WordDistance struct { d map[string][]int @@ -203,10 +189,6 @@ func abs(x int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0244.Shortest Word Distance II/README_EN.md b/solution/0200-0299/0244.Shortest Word Distance II/README_EN.md index 1c1240ae978b4..f25dcde7a09bd 100644 --- a/solution/0200-0299/0244.Shortest Word Distance II/README_EN.md +++ b/solution/0200-0299/0244.Shortest Word Distance II/README_EN.md @@ -43,9 +43,9 @@ wordDistance.shortest("makes", "coding"); // return 1 ## Solutions - +### Solution 1 -### **Python3** + ```python class WordDistance: @@ -72,8 +72,6 @@ class WordDistance: # param_1 = obj.shortest(word1,word2) ``` -### **Java** - ```java class WordDistance { private Map> d = new HashMap<>(); @@ -107,8 +105,6 @@ class WordDistance { */ ``` -### **C++** - ```cpp class WordDistance { public: @@ -144,8 +140,6 @@ private: */ ``` -### **Go** - ```go type WordDistance struct { d map[string][]int @@ -188,10 +182,6 @@ func abs(x int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0245.Shortest Word Distance III/README.md b/solution/0200-0299/0245.Shortest Word Distance III/README.md index be492d81b198e..c1c5f969ce344 100644 --- a/solution/0200-0299/0245.Shortest Word Distance III/README.md +++ b/solution/0200-0299/0245.Shortest Word Distance III/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:分情况讨论** +### 方法一:分情况讨论 先判断 `word1` 和 `word2` 是否相等: @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def shortestWordDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int shortestWordDistance(String[] wordsDict, String word1, String word2) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func shortestWordDistance(wordsDict []string, word1 string, word2 string) int { ans := len(wordsDict) @@ -190,10 +176,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0245.Shortest Word Distance III/README_EN.md b/solution/0200-0299/0245.Shortest Word Distance III/README_EN.md index 8b70e6d5fb0b9..653fa2beff371 100644 --- a/solution/0200-0299/0245.Shortest Word Distance III/README_EN.md +++ b/solution/0200-0299/0245.Shortest Word Distance III/README_EN.md @@ -28,9 +28,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int shortestWordDistance(String[] wordsDict, String word1, String word2) { @@ -88,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func shortestWordDistance(wordsDict []string, word1 string, word2 string) int { ans := len(wordsDict) @@ -163,10 +157,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0246.Strobogrammatic Number/README.md b/solution/0200-0299/0246.Strobogrammatic Number/README.md index 50c2779869705..33787cfb43824 100644 --- a/solution/0200-0299/0246.Strobogrammatic Number/README.md +++ b/solution/0200-0299/0246.Strobogrammatic Number/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:双指针模拟** +### 方法一:双指针模拟 我们定义一个数组 $d$,其中 $d[i]$ 表示数字 $i$ 旋转 180° 之后的数字。如果 $d[i]$ 为 $-1$,表示数字 $i$ 不能旋转 180° 得到一个数字。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python class Solution: def isStrobogrammatic(self, num: str) -> bool: @@ -65,10 +59,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean isStrobogrammatic(String num) { @@ -84,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +90,6 @@ public: }; ``` -### **Go** - ```go func isStrobogrammatic(num string) bool { d := []int{0, 1, -1, -1, -1, -1, 9, -1, 8, 6} @@ -117,10 +103,6 @@ func isStrobogrammatic(num string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0246.Strobogrammatic Number/README_EN.md b/solution/0200-0299/0246.Strobogrammatic Number/README_EN.md index 8deca649ea67b..d83002384ded2 100644 --- a/solution/0200-0299/0246.Strobogrammatic Number/README_EN.md +++ b/solution/0200-0299/0246.Strobogrammatic Number/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean isStrobogrammatic(String num) { @@ -75,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +89,6 @@ public: }; ``` -### **Go** - ```go func isStrobogrammatic(num string) bool { d := []int{0, 1, -1, -1, -1, -1, 9, -1, 8, 6} @@ -108,10 +102,6 @@ func isStrobogrammatic(num string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0247.Strobogrammatic Number II/README.md b/solution/0200-0299/0247.Strobogrammatic Number II/README.md index 3dc2bfb99b183..811cbf2fa5e74 100644 --- a/solution/0200-0299/0247.Strobogrammatic Number II/README.md +++ b/solution/0200-0299/0247.Strobogrammatic Number II/README.md @@ -35,9 +35,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 若长度为 $1$,则中心对称数只有 $0, 1, 8$;若长度为 $2$,则中心对称数只有 $11, 69, 88, 96$。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def findStrobogrammatic(self, n: int) -> List[str]: @@ -80,10 +74,6 @@ class Solution: return dfs(n) ``` -### **Java** - - - ```java class Solution { private static final int[][] PAIRS = {{1, 1}, {8, 8}, {6, 9}, {9, 6}}; @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func findStrobogrammatic(n int) []string { var dfs func(int) []string @@ -166,10 +152,6 @@ func findStrobogrammatic(n int) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0247.Strobogrammatic Number II/README_EN.md b/solution/0200-0299/0247.Strobogrammatic Number II/README_EN.md index 17a59c43e230b..e69e7786ae716 100644 --- a/solution/0200-0299/0247.Strobogrammatic Number II/README_EN.md +++ b/solution/0200-0299/0247.Strobogrammatic Number II/README_EN.md @@ -25,9 +25,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -48,8 +48,6 @@ class Solution: return dfs(n) ``` -### **Java** - ```java class Solution { private static final int[][] PAIRS = {{1, 1}, {8, 8}, {6, 9}, {9, 6}}; @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +100,6 @@ public: }; ``` -### **Go** - ```go func findStrobogrammatic(n int) []string { var dfs func(int) []string @@ -132,10 +126,6 @@ func findStrobogrammatic(n int) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0248.Strobogrammatic Number III/README.md b/solution/0200-0299/0248.Strobogrammatic Number III/README.md index e3ec2fb7bd593..c53d45ab875a2 100644 --- a/solution/0200-0299/0248.Strobogrammatic Number III/README.md +++ b/solution/0200-0299/0248.Strobogrammatic Number III/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 若长度为 $1$,则中心对称数只有 $0, 1, 8$;若长度为 $2$,则中心对称数只有 $11, 69, 88, 96$。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def strobogrammaticInRange(self, low: str, high: str) -> int: @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int[][] PAIRS = {{1, 1}, {8, 8}, {6, 9}, {9, 6}}; @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -178,8 +166,6 @@ public: }; ``` -### **Go** - ```go func strobogrammaticInRange(low string, high string) int { n := 0 @@ -219,10 +205,6 @@ func strobogrammaticInRange(low string, high string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0248.Strobogrammatic Number III/README_EN.md b/solution/0200-0299/0248.Strobogrammatic Number III/README_EN.md index 3ce5922d2a58c..156c5360b0b04 100644 --- a/solution/0200-0299/0248.Strobogrammatic Number III/README_EN.md +++ b/solution/0200-0299/0248.Strobogrammatic Number III/README_EN.md @@ -28,9 +28,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int[][] PAIRS = {{1, 1}, {8, 8}, {6, 9}, {9, 6}}; @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -139,8 +135,6 @@ public: }; ``` -### **Go** - ```go func strobogrammaticInRange(low string, high string) int { n := 0 @@ -180,10 +174,6 @@ func strobogrammaticInRange(low string, high string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0249.Group Shifted Strings/README.md b/solution/0200-0299/0249.Group Shifted Strings/README.md index eb6c61fa8ed49..8b464ea788bf5 100644 --- a/solution/0200-0299/0249.Group Shifted Strings/README.md +++ b/solution/0200-0299/0249.Group Shifted Strings/README.md @@ -28,16 +28,10 @@ ## 解法 - - -将每个字符串第一个字母变成 'a'。 +### 方法一 -### **Python3** - - - ```python class Solution: def groupStrings(self, strings: List[str]) -> List[List[str]]: @@ -55,10 +49,6 @@ class Solution: return list(mp.values()) ``` -### **Java** - - - ```java class Solution { public List> groupStrings(String[] strings) { @@ -81,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func groupStrings(strings []string) [][]string { mp := make(map[string][]string) @@ -127,10 +113,6 @@ func groupStrings(strings []string) [][]string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0249.Group Shifted Strings/README_EN.md b/solution/0200-0299/0249.Group Shifted Strings/README_EN.md index 598f60936e584..2d01cfdb70df9 100644 --- a/solution/0200-0299/0249.Group Shifted Strings/README_EN.md +++ b/solution/0200-0299/0249.Group Shifted Strings/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return list(mp.values()) ``` -### **Java** - ```java class Solution { public List> groupStrings(String[] strings) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +104,6 @@ public: }; ``` -### **Go** - ```go func groupStrings(strings []string) [][]string { mp := make(map[string][]string) @@ -128,10 +122,6 @@ func groupStrings(strings []string) [][]string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0250.Count Univalue Subtrees/README.md b/solution/0200-0299/0250.Count Univalue Subtrees/README.md index a5f28b1bd9ffa..b1e1eea6d6681 100644 --- a/solution/0200-0299/0250.Count Univalue Subtrees/README.md +++ b/solution/0200-0299/0250.Count Univalue Subtrees/README.md @@ -25,9 +25,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们设计一个递归函数 $dfs(root)$,该函数返回以 $root$ 为根的子树中所有节点的值是否相同。 @@ -42,10 +40,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -74,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -163,8 +151,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -198,48 +184,6 @@ func countUnivalSubtrees(root *TreeNode) (ans int) { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number} - */ -var countUnivalSubtrees = function (root) { - let ans = 0; - const dfs = root => { - if (!root) { - return true; - } - const l = dfs(root.left); - const r = dfs(root.right); - if (!l || !r) { - return false; - } - if (root.left && root.left.val !== root.val) { - return false; - } - if (root.right && root.right.val !== root.val) { - return false; - } - ++ans; - return true; - }; - dfs(root); - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -280,10 +224,44 @@ function countUnivalSubtrees(root: TreeNode | null): number { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var countUnivalSubtrees = function (root) { + let ans = 0; + const dfs = root => { + if (!root) { + return true; + } + const l = dfs(root.left); + const r = dfs(root.right); + if (!l || !r) { + return false; + } + if (root.left && root.left.val !== root.val) { + return false; + } + if (root.right && root.right.val !== root.val) { + return false; + } + ++ans; + return true; + }; + dfs(root); + return ans; +}; ``` + + diff --git a/solution/0200-0299/0250.Count Univalue Subtrees/README_EN.md b/solution/0200-0299/0250.Count Univalue Subtrees/README_EN.md index 33262ce052a7d..adae92e4895f4 100644 --- a/solution/0200-0299/0250.Count Univalue Subtrees/README_EN.md +++ b/solution/0200-0299/0250.Count Univalue Subtrees/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -72,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -118,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -159,8 +155,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -194,48 +188,6 @@ func countUnivalSubtrees(root *TreeNode) (ans int) { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number} - */ -var countUnivalSubtrees = function (root) { - let ans = 0; - const dfs = root => { - if (!root) { - return true; - } - const l = dfs(root.left); - const r = dfs(root.right); - if (!l || !r) { - return false; - } - if (root.left && root.left.val !== root.val) { - return false; - } - if (root.right && root.right.val !== root.val) { - return false; - } - ++ans; - return true; - }; - dfs(root); - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -276,10 +228,44 @@ function countUnivalSubtrees(root: TreeNode | null): number { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var countUnivalSubtrees = function (root) { + let ans = 0; + const dfs = root => { + if (!root) { + return true; + } + const l = dfs(root.left); + const r = dfs(root.right); + if (!l || !r) { + return false; + } + if (root.left && root.left.val !== root.val) { + return false; + } + if (root.right && root.right.val !== root.val) { + return false; + } + ++ans; + return true; + }; + dfs(root); + return ans; +}; ``` + + diff --git a/solution/0200-0299/0251.Flatten 2D Vector/README.md b/solution/0200-0299/0251.Flatten 2D Vector/README.md index 82ed1a60ee6b5..9d19c99b5c44d 100644 --- a/solution/0200-0299/0251.Flatten 2D Vector/README.md +++ b/solution/0200-0299/0251.Flatten 2D Vector/README.md @@ -39,9 +39,7 @@ iterator.hasNext(); // 返回 false ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们定义两个指针 $i$ 和 $j$,分别指向当前二维向量的行和列,初始时 $i = 0$,$j = 0$。 @@ -55,10 +53,6 @@ iterator.hasNext(); // 返回 false -### **Python3** - - - ```python class Vector2D: def __init__(self, vec: List[List[int]]): @@ -88,10 +82,6 @@ class Vector2D: # param_2 = obj.hasNext() ``` -### **Java** - - - ```java class Vector2D { private int i; @@ -128,8 +118,6 @@ class Vector2D { */ ``` -### **C++** - ```cpp class Vector2D { public: @@ -168,8 +156,6 @@ private: */ ``` -### **Go** - ```go type Vector2D struct { i, j int @@ -207,8 +193,6 @@ func (this *Vector2D) forward() { */ ``` -### **TypeScript** - ```ts class Vector2D { i: number; @@ -247,10 +231,6 @@ class Vector2D { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0251.Flatten 2D Vector/README_EN.md b/solution/0200-0299/0251.Flatten 2D Vector/README_EN.md index 6952ed93477be..5237bfa5b8b91 100644 --- a/solution/0200-0299/0251.Flatten 2D Vector/README_EN.md +++ b/solution/0200-0299/0251.Flatten 2D Vector/README_EN.md @@ -50,9 +50,9 @@ vector2D.hasNext(); // return False ## Solutions - +### Solution 1 -### **Python3** + ```python class Vector2D: @@ -83,8 +83,6 @@ class Vector2D: # param_2 = obj.hasNext() ``` -### **Java** - ```java class Vector2D { private int i; @@ -121,8 +119,6 @@ class Vector2D { */ ``` -### **C++** - ```cpp class Vector2D { public: @@ -161,8 +157,6 @@ private: */ ``` -### **Go** - ```go type Vector2D struct { i, j int @@ -200,8 +194,6 @@ func (this *Vector2D) forward() { */ ``` -### **TypeScript** - ```ts class Vector2D { i: number; @@ -240,10 +232,6 @@ class Vector2D { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0252.Meeting Rooms/README.md b/solution/0200-0299/0252.Meeting Rooms/README.md index 475fbc2af3298..d065a5a931d7e 100644 --- a/solution/0200-0299/0252.Meeting Rooms/README.md +++ b/solution/0200-0299/0252.Meeting Rooms/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们将会议按照开始时间进行排序,然后遍历排序后的会议,如果当前会议的开始时间小于前一个会议的结束时间,则说明两个会议有重叠,返回 `false` 即可。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python class Solution: def canAttendMeetings(self, intervals: List[List[int]]) -> bool: @@ -59,10 +53,6 @@ class Solution: return all(a[1] <= b[0] for a, b in pairwise(intervals)) ``` -### **Java** - - - ```java class Solution { public boolean canAttendMeetings(int[][] intervals) { @@ -79,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,7 +86,31 @@ public: }; ``` -### **Rust** +```go +func canAttendMeetings(intervals [][]int) bool { + sort.Slice(intervals, func(i, j int) bool { + return intervals[i][0] < intervals[j][0] + }) + for i := 1; i < len(intervals); i++ { + if intervals[i][0] < intervals[i-1][1] { + return false + } + } + return true +} +``` + +```ts +function canAttendMeetings(intervals: number[][]): boolean { + intervals.sort((a, b) => a[0] - b[0]); + for (let i = 1; i < intervals.length; ++i) { + if (intervals[i][0] < intervals[i - 1][1]) { + return false; + } + } + return true; +} +``` ```rust impl Solution { @@ -133,40 +145,6 @@ impl Solution { } ``` -### **Go** - -```go -func canAttendMeetings(intervals [][]int) bool { - sort.Slice(intervals, func(i, j int) bool { - return intervals[i][0] < intervals[j][0] - }) - for i := 1; i < len(intervals); i++ { - if intervals[i][0] < intervals[i-1][1] { - return false - } - } - return true -} -``` - -### **TypeScript** - -```ts -function canAttendMeetings(intervals: number[][]): boolean { - intervals.sort((a, b) => a[0] - b[0]); - for (let i = 1; i < intervals.length; ++i) { - if (intervals[i][0] < intervals[i - 1][1]) { - return false; - } - } - return true; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0252.Meeting Rooms/README_EN.md b/solution/0200-0299/0252.Meeting Rooms/README_EN.md index e633f568307ea..03642e2538335 100644 --- a/solution/0200-0299/0252.Meeting Rooms/README_EN.md +++ b/solution/0200-0299/0252.Meeting Rooms/README_EN.md @@ -25,9 +25,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -36,8 +36,6 @@ class Solution: return all(a[1] <= b[0] for a, b in pairwise(intervals)) ``` -### **Java** - ```java class Solution { public boolean canAttendMeetings(int[][] intervals) { @@ -54,8 +52,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -73,7 +69,31 @@ public: }; ``` -### **Rust** +```go +func canAttendMeetings(intervals [][]int) bool { + sort.Slice(intervals, func(i, j int) bool { + return intervals[i][0] < intervals[j][0] + }) + for i := 1; i < len(intervals); i++ { + if intervals[i][0] < intervals[i-1][1] { + return false + } + } + return true +} +``` + +```ts +function canAttendMeetings(intervals: number[][]): boolean { + intervals.sort((a, b) => a[0] - b[0]); + for (let i = 1; i < intervals.length; ++i) { + if (intervals[i][0] < intervals[i - 1][1]) { + return false; + } + } + return true; +} +``` ```rust impl Solution { @@ -108,40 +128,6 @@ impl Solution { } ``` -### **Go** - -```go -func canAttendMeetings(intervals [][]int) bool { - sort.Slice(intervals, func(i, j int) bool { - return intervals[i][0] < intervals[j][0] - }) - for i := 1; i < len(intervals); i++ { - if intervals[i][0] < intervals[i-1][1] { - return false - } - } - return true -} -``` - -### **TypeScript** - -```ts -function canAttendMeetings(intervals: number[][]): boolean { - intervals.sort((a, b) => a[0] - b[0]); - for (let i = 1; i < intervals.length; ++i) { - if (intervals[i][0] < intervals[i - 1][1]) { - return false; - } - } - return true; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0253.Meeting Rooms II/README.md b/solution/0200-0299/0253.Meeting Rooms II/README.md index e1edb7ffd8dbe..29bb7526c1187 100644 --- a/solution/0200-0299/0253.Meeting Rooms II/README.md +++ b/solution/0200-0299/0253.Meeting Rooms II/README.md @@ -35,16 +35,10 @@ ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 -### **Python3** - - - ```python class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: @@ -55,10 +49,6 @@ class Solution: return max(accumulate(delta)) ``` -### **Java** - - - ```java class Solution { public int minMeetingRooms(int[][] intervals) { @@ -78,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,7 +86,20 @@ public: }; ``` -### **Rust** +```go +func minMeetingRooms(intervals [][]int) int { + n := 1000010 + delta := make([]int, n) + for _, e := range intervals { + delta[e[0]]++ + delta[e[1]]-- + } + for i := 1; i < n; i++ { + delta[i] += delta[i-1] + } + return slices.Max(delta) +} +``` ```rust use std::{ collections::BinaryHeap, cmp::Reverse }; @@ -138,27 +139,6 @@ impl Solution { } ``` -### **Go** - -```go -func minMeetingRooms(intervals [][]int) int { - n := 1000010 - delta := make([]int, n) - for _, e := range intervals { - delta[e[0]]++ - delta[e[1]]-- - } - for i := 1; i < n; i++ { - delta[i] += delta[i-1] - } - return slices.Max(delta) -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0253.Meeting Rooms II/README_EN.md b/solution/0200-0299/0253.Meeting Rooms II/README_EN.md index de0522f1345b4..3d1e225ede577 100644 --- a/solution/0200-0299/0253.Meeting Rooms II/README_EN.md +++ b/solution/0200-0299/0253.Meeting Rooms II/README_EN.md @@ -24,9 +24,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -38,8 +38,6 @@ class Solution: return max(accumulate(delta)) ``` -### **Java** - ```java class Solution { public int minMeetingRooms(int[][] intervals) { @@ -59,8 +57,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -79,7 +75,20 @@ public: }; ``` -### **Rust** +```go +func minMeetingRooms(intervals [][]int) int { + n := 1000010 + delta := make([]int, n) + for _, e := range intervals { + delta[e[0]]++ + delta[e[1]]-- + } + for i := 1; i < n; i++ { + delta[i] += delta[i-1] + } + return slices.Max(delta) +} +``` ```rust use std::{ collections::BinaryHeap, cmp::Reverse }; @@ -119,27 +128,6 @@ impl Solution { } ``` -### **Go** - -```go -func minMeetingRooms(intervals [][]int) int { - n := 1000010 - delta := make([]int, n) - for _, e := range intervals { - delta[e[0]]++ - delta[e[1]]-- - } - for i := 1; i < n; i++ { - delta[i] += delta[i-1] - } - return slices.Max(delta) -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0254.Factor Combinations/README.md b/solution/0200-0299/0254.Factor Combinations/README.md index b1659db68be44..4464f4c1be7cc 100644 --- a/solution/0200-0299/0254.Factor Combinations/README.md +++ b/solution/0200-0299/0254.Factor Combinations/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:回溯** +### 方法一:回溯 我们设计函数 $dfs(n, i)$,其中 $n$ 表示当前待分解的数,$i$ 表示当前分解的数的最大因子,函数的作用是将 $n$ 分解为若干个因子,其中每个因子都不小于 $i$,并将所有分解结果保存到 $ans$ 中。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def getFactors(self, n: int) -> List[List[int]]: @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List t = new ArrayList<>(); @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func getFactors(n int) [][]int { t := []int{} @@ -178,10 +164,6 @@ func getFactors(n int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0254.Factor Combinations/README_EN.md b/solution/0200-0299/0254.Factor Combinations/README_EN.md index e35d01122f39c..56c55cacfc080 100644 --- a/solution/0200-0299/0254.Factor Combinations/README_EN.md +++ b/solution/0200-0299/0254.Factor Combinations/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List t = new ArrayList<>(); @@ -98,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +122,6 @@ public: }; ``` -### **Go** - ```go func getFactors(n int) [][]int { t := []int{} @@ -150,10 +144,6 @@ func getFactors(n int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0255.Verify Preorder Sequence in Binary Search Tree/README.md b/solution/0200-0299/0255.Verify Preorder Sequence in Binary Search Tree/README.md index 574f40d424b6b..41a0559f87d49 100644 --- a/solution/0200-0299/0255.Verify Preorder Sequence in Binary Search Tree/README.md +++ b/solution/0200-0299/0255.Verify Preorder Sequence in Binary Search Tree/README.md @@ -40,20 +40,10 @@ ## 解法 - - -二叉搜索树先序遍历时,每次移向左子树时,值递减,移向右子树时,值递增。 - -因此,可以维护一个单调递减栈。遍历序列,若当前值大于栈顶元素,说明开始要进入右子树的遍历。只要栈顶元素比当前值小,就表示还是左子树,要移除,也就是从栈中弹出,直至栈顶元素大于当前值,或者栈为空。此过程要记录弹出栈的最后一个元素 last。 - -接下来继续往后遍历,之后右子树的每个节点,都要比 last 大,才能满足二叉搜索树,否则直接返回 false。 +### 方法一 -### **Python3** - - - ```python class Solution: def verifyPreorder(self, preorder: List[int]) -> bool: @@ -68,10 +58,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean verifyPreorder(int[] preorder) { @@ -91,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +96,6 @@ public: }; ``` -### **Go** - ```go func verifyPreorder(preorder []int) bool { var stk []int @@ -132,10 +114,6 @@ func verifyPreorder(preorder []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0255.Verify Preorder Sequence in Binary Search Tree/README_EN.md b/solution/0200-0299/0255.Verify Preorder Sequence in Binary Search Tree/README_EN.md index 23b00834bf117..3bcae995ce5be 100644 --- a/solution/0200-0299/0255.Verify Preorder Sequence in Binary Search Tree/README_EN.md +++ b/solution/0200-0299/0255.Verify Preorder Sequence in Binary Search Tree/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean verifyPreorder(int[] preorder) { @@ -74,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +91,6 @@ public: }; ``` -### **Go** - ```go func verifyPreorder(preorder []int) bool { var stk []int @@ -115,10 +109,6 @@ func verifyPreorder(preorder []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0256.Paint House/README.md b/solution/0200-0299/0256.Paint House/README.md index 31143da7a1f98..cc98e26af5b5b 100644 --- a/solution/0200-0299/0256.Paint House/README.md +++ b/solution/0200-0299/0256.Paint House/README.md @@ -45,18 +45,12 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 表示房子的数量。 -### **Python3** - - - ```python class Solution: def minCost(self, costs: List[List[int]]) -> int: @@ -66,10 +60,6 @@ class Solution: return min(a, b, c) ``` -### **Java** - - - ```java class Solution { public int minCost(int[][] costs) { @@ -85,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +91,6 @@ public: }; ``` -### **Go** - ```go func minCost(costs [][]int) int { r, g, b := 0, 0, 0 @@ -118,8 +104,6 @@ func minCost(costs [][]int) int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} costs @@ -134,10 +118,6 @@ var minCost = function (costs) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0256.Paint House/README_EN.md b/solution/0200-0299/0256.Paint House/README_EN.md index bf9bc7b48c78b..2862758f638dc 100644 --- a/solution/0200-0299/0256.Paint House/README_EN.md +++ b/solution/0200-0299/0256.Paint House/README_EN.md @@ -43,9 +43,9 @@ Minimum cost: 2 + 5 + 3 = 10. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return min(a, b, c) ``` -### **Java** - ```java class Solution { public int minCost(int[][] costs) { @@ -73,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +87,6 @@ public: }; ``` -### **Go** - ```go func minCost(costs [][]int) int { r, g, b := 0, 0, 0 @@ -106,8 +100,6 @@ func minCost(costs [][]int) int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} costs @@ -122,10 +114,6 @@ var minCost = function (costs) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0257.Binary Tree Paths/README.md b/solution/0200-0299/0257.Binary Tree Paths/README.md index 6193d9641d437..082c7869589ee 100644 --- a/solution/0200-0299/0257.Binary Tree Paths/README.md +++ b/solution/0200-0299/0257.Binary Tree Paths/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们可以使用深度优先搜索的方法遍历整棵二叉树,每一次我们将当前的节点添加到路径中。如果当前的节点是叶子节点,则我们将整个路径加入到答案中。否则我们继续递归遍历节点的孩子节点。最后当我们递归结束返回到当前节点时,我们需要将当前节点从路径中删除。 @@ -46,10 +44,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -76,10 +70,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. @@ -170,8 +158,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -202,8 +188,6 @@ func binaryTreePaths(root *TreeNode) (ans []string) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -240,10 +224,6 @@ function binaryTreePaths(root: TreeNode | null): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0257.Binary Tree Paths/README_EN.md b/solution/0200-0299/0257.Binary Tree Paths/README_EN.md index 649a8e1d0f68b..648b2ee5de2ec 100644 --- a/solution/0200-0299/0257.Binary Tree Paths/README_EN.md +++ b/solution/0200-0299/0257.Binary Tree Paths/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -155,8 +151,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -187,8 +181,6 @@ func binaryTreePaths(root *TreeNode) (ans []string) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -225,10 +217,6 @@ function binaryTreePaths(root: TreeNode | null): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0258.Add Digits/README.md b/solution/0200-0299/0258.Add Digits/README.md index b02e0e9dda330..d560d6774a2d7 100644 --- a/solution/0200-0299/0258.Add Digits/README.md +++ b/solution/0200-0299/0258.Add Digits/README.md @@ -41,39 +41,16 @@ ## 解法 - - -题目要求的数叫做“数根”,我们把 1~30 的数根列出来: - -``` -原数: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 -数根: 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 -``` - -可以看到,数根 9 个为一组,循环出现。我们可以得出下面的规律: - -- n = 0:数根是 0 -- n 是 9 的倍数:数根是 9 -- n 不是 9 的倍数:数根是 n % 9 - -将上面的规律用式子:`(n - 1) % 9 + 1` 统一表达。 +### 方法一 -### **Python3** - - - ```python class Solution: def addDigits(self, num: int) -> int: return 0 if num == 0 else (num - 1) % 9 + 1 ``` -### **Java** - - - ```java class Solution { public int addDigits(int num) { @@ -82,8 +59,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +68,6 @@ public: }; ``` -### **Go** - ```go func addDigits(num int) int { if num == 0 { @@ -104,8 +77,6 @@ func addDigits(num int) int { } ``` -### **Rust** - ```rust impl Solution { pub fn add_digits(num: i32) -> i32 { @@ -123,6 +94,12 @@ impl Solution { } ``` + + +### 方法二 + + + ```rust impl Solution { pub fn add_digits(mut num: i32) -> i32 { @@ -131,10 +108,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0258.Add Digits/README_EN.md b/solution/0200-0299/0258.Add Digits/README_EN.md index 6b27d9f42911f..496980c0bac37 100644 --- a/solution/0200-0299/0258.Add Digits/README_EN.md +++ b/solution/0200-0299/0258.Add Digits/README_EN.md @@ -37,9 +37,9 @@ Since 2 has only one digit, return it. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -47,8 +47,6 @@ class Solution: return 0 if num == 0 else (num - 1) % 9 + 1 ``` -### **Java** - ```java class Solution { public int addDigits(int num) { @@ -57,8 +55,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -68,8 +64,6 @@ public: }; ``` -### **Go** - ```go func addDigits(num int) int { if num == 0 { @@ -79,8 +73,6 @@ func addDigits(num int) int { } ``` -### **Rust** - ```rust impl Solution { pub fn add_digits(num: i32) -> i32 { @@ -98,6 +90,12 @@ impl Solution { } ``` + + +### Solution 2 + + + ```rust impl Solution { pub fn add_digits(mut num: i32) -> i32 { @@ -106,10 +104,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0259.3Sum Smaller/README.md b/solution/0200-0299/0259.3Sum Smaller/README.md index 9aae8fcdfc9e2..77adc8f7bb408 100644 --- a/solution/0200-0299/0259.3Sum Smaller/README.md +++ b/solution/0200-0299/0259.3Sum Smaller/README.md @@ -45,16 +45,10 @@ ## 解法 - - -双指针解决。 +### 方法一 -### **Python3** - - - ```python class Solution: def threeSumSmaller(self, nums: List[int], target: int) -> int: @@ -72,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int threeSumSmaller(int[] nums, int target) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func threeSumSmaller(nums []int, target int) int { sort.Ints(nums) @@ -146,8 +132,6 @@ func threeSumSmaller(nums []int, target int) int { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -174,10 +158,6 @@ var threeSumSmaller = function (nums, target) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0259.3Sum Smaller/README_EN.md b/solution/0200-0299/0259.3Sum Smaller/README_EN.md index 95e6f854a811f..f07ee934f3982 100644 --- a/solution/0200-0299/0259.3Sum Smaller/README_EN.md +++ b/solution/0200-0299/0259.3Sum Smaller/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int threeSumSmaller(int[] nums, int target) { @@ -88,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func threeSumSmaller(nums []int, target int) int { sort.Ints(nums) @@ -135,8 +129,6 @@ func threeSumSmaller(nums []int, target int) int { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -163,10 +155,6 @@ var threeSumSmaller = function (nums, target) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0260.Single Number III/README.md b/solution/0200-0299/0260.Single Number III/README.md index 618feae729908..f5cfec26473bb 100644 --- a/solution/0200-0299/0260.Single Number III/README.md +++ b/solution/0200-0299/0260.Single Number III/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 异或运算有以下性质: @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def singleNumber(self, nums: List[int]) -> List[int]: @@ -82,10 +76,6 @@ class Solution: return [a, b] ``` -### **Java** - - - ```java class Solution { public int[] singleNumber(int[] nums) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func singleNumber(nums []int) []int { xs := 0 @@ -149,7 +135,20 @@ func singleNumber(nums []int) []int { } ``` -### **Rust** +```ts +function singleNumber(nums: number[]): number[] { + const xs = nums.reduce((a, b) => a ^ b); + const lb = xs & -xs; + let a = 0; + for (const x of nums) { + if (x & lb) { + a ^= x; + } + } + const b = xs ^ a; + return [a, b]; +} +``` ```rust impl Solution { @@ -168,10 +167,12 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function singleNumber(nums: number[]): number[] { +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var singleNumber = function (nums) { const xs = nums.reduce((a, b) => a ^ b); const lb = xs & -xs; let a = 0; @@ -182,11 +183,9 @@ function singleNumber(nums: number[]): number[] { } const b = xs ^ a; return [a, b]; -} +}; ``` -### **C#** - ```cs public class Solution { public int[] SingleNumber(int[] nums) { @@ -204,31 +203,6 @@ public class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var singleNumber = function (nums) { - const xs = nums.reduce((a, b) => a ^ b); - const lb = xs & -xs; - let a = 0; - for (const x of nums) { - if (x & lb) { - a ^= x; - } - } - const b = xs ^ a; - return [a, b]; -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0260.Single Number III/README_EN.md b/solution/0200-0299/0260.Single Number III/README_EN.md index 796da9ed6073c..640178f29a9bc 100644 --- a/solution/0200-0299/0260.Single Number III/README_EN.md +++ b/solution/0200-0299/0260.Single Number III/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Bitwise Operation** +### Solution 1: Bitwise Operation The XOR operation has the following properties: @@ -59,8 +59,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def singleNumber(self, nums: List[int]) -> List[int]: @@ -74,8 +72,6 @@ class Solution: return [a, b] ``` -### **Java** - ```java class Solution { public int[] singleNumber(int[] nums) { @@ -96,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +113,6 @@ public: }; ``` -### **Go** - ```go func singleNumber(nums []int) []int { xs := 0 @@ -139,7 +131,20 @@ func singleNumber(nums []int) []int { } ``` -### **Rust** +```ts +function singleNumber(nums: number[]): number[] { + const xs = nums.reduce((a, b) => a ^ b); + const lb = xs & -xs; + let a = 0; + for (const x of nums) { + if (x & lb) { + a ^= x; + } + } + const b = xs ^ a; + return [a, b]; +} +``` ```rust impl Solution { @@ -158,10 +163,12 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function singleNumber(nums: number[]): number[] { +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var singleNumber = function (nums) { const xs = nums.reduce((a, b) => a ^ b); const lb = xs & -xs; let a = 0; @@ -172,11 +179,9 @@ function singleNumber(nums: number[]): number[] { } const b = xs ^ a; return [a, b]; -} +}; ``` -### **C#** - ```cs public class Solution { public int[] SingleNumber(int[] nums) { @@ -194,31 +199,6 @@ public class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var singleNumber = function (nums) { - const xs = nums.reduce((a, b) => a ^ b); - const lb = xs & -xs; - let a = 0; - for (const x of nums) { - if (x & lb) { - a ^= x; - } - } - const b = xs ^ a; - return [a, b]; -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0261.Graph Valid Tree/README.md b/solution/0200-0299/0261.Graph Valid Tree/README.md index f8422b5ad548f..3842d33a5bbc6 100644 --- a/solution/0200-0299/0261.Graph Valid Tree/README.md +++ b/solution/0200-0299/0261.Graph Valid Tree/README.md @@ -43,79 +43,10 @@ ## 解法 - - -并查集模板题。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` +### 方法一 -### **Python3** - - - ```python class Solution: def validTree(self, n: int, edges: List[List[int]]) -> bool: @@ -133,10 +64,6 @@ class Solution: return n == 1 ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -166,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -192,8 +117,6 @@ public: }; ``` -### **Go** - ```go func validTree(n int, edges [][]int) bool { p := make([]int, n) @@ -219,8 +142,6 @@ func validTree(n int, edges [][]int) bool { } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -249,10 +170,6 @@ var validTree = function (n, edges) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0261.Graph Valid Tree/README_EN.md b/solution/0200-0299/0261.Graph Valid Tree/README_EN.md index f3323dfce891f..b989138710931 100644 --- a/solution/0200-0299/0261.Graph Valid Tree/README_EN.md +++ b/solution/0200-0299/0261.Graph Valid Tree/README_EN.md @@ -37,12 +37,10 @@ ## Solutions -Union find. +### Solution 1 -### **Python3** - ```python class Solution: def validTree(self, n: int, edges: List[List[int]]) -> bool: @@ -60,8 +58,6 @@ class Solution: return n == 1 ``` -### **Java** - ```java class Solution { private int[] p; @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func validTree(n int, edges [][]int) bool { p := make([]int, n) @@ -144,8 +136,6 @@ func validTree(n int, edges [][]int) bool { } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -174,10 +164,6 @@ var validTree = function (n, edges) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0262.Trips and Users/README.md b/solution/0200-0299/0262.Trips and Users/README.md index 1c345dfe16742..837a9c19a153a 100644 --- a/solution/0200-0299/0262.Trips and Users/README.md +++ b/solution/0200-0299/0262.Trips and Users/README.md @@ -121,27 +121,10 @@ Users 表: ## 解法 - +### 方法一 -### **SQL** - -```sql -# Write your MySQL query statement below -SELECT - request_at AS Day, - ROUND(AVG(status != 'completed'), 2) AS 'Cancellation Rate' -FROM - Trips AS t - JOIN Users AS u1 ON (t.client_id = u1.users_id AND u1.banned = 'No') - JOIN Users AS u2 ON (t.driver_id = u2.users_id AND u2.banned = 'No') -WHERE request_at BETWEEN '2013-10-01' AND '2013-10-03' -GROUP BY request_at; -``` - -### **Pandas** - ```python import pandas as pd @@ -188,4 +171,19 @@ def trips_and_users(trips: pd.DataFrame, users: pd.DataFrame) -> pd.DataFrame: return df[["Day", "Cancellation Rate"]] ``` +```sql +# Write your MySQL query statement below +SELECT + request_at AS Day, + ROUND(AVG(status != 'completed'), 2) AS 'Cancellation Rate' +FROM + Trips AS t + JOIN Users AS u1 ON (t.client_id = u1.users_id AND u1.banned = 'No') + JOIN Users AS u2 ON (t.driver_id = u2.users_id AND u2.banned = 'No') +WHERE request_at BETWEEN '2013-10-01' AND '2013-10-03' +GROUP BY request_at; +``` + + + diff --git a/solution/0200-0299/0262.Trips and Users/README_EN.md b/solution/0200-0299/0262.Trips and Users/README_EN.md index 9a03b62d6876a..0e0ff8b569891 100644 --- a/solution/0200-0299/0262.Trips and Users/README_EN.md +++ b/solution/0200-0299/0262.Trips and Users/README_EN.md @@ -110,24 +110,9 @@ On 2013-10-03: ## Solutions - - -### **SQL** - -```sql -# Write your MySQL query statement below -SELECT - request_at AS Day, - ROUND(AVG(status != 'completed'), 2) AS 'Cancellation Rate' -FROM - Trips AS t - JOIN Users AS u1 ON (t.client_id = u1.users_id AND u1.banned = 'No') - JOIN Users AS u2 ON (t.driver_id = u2.users_id AND u2.banned = 'No') -WHERE request_at BETWEEN '2013-10-01' AND '2013-10-03' -GROUP BY request_at; -``` +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -175,4 +160,19 @@ def trips_and_users(trips: pd.DataFrame, users: pd.DataFrame) -> pd.DataFrame: return df[["Day", "Cancellation Rate"]] ``` +```sql +# Write your MySQL query statement below +SELECT + request_at AS Day, + ROUND(AVG(status != 'completed'), 2) AS 'Cancellation Rate' +FROM + Trips AS t + JOIN Users AS u1 ON (t.client_id = u1.users_id AND u1.banned = 'No') + JOIN Users AS u2 ON (t.driver_id = u2.users_id AND u2.banned = 'No') +WHERE request_at BETWEEN '2013-10-01' AND '2013-10-03' +GROUP BY request_at; +``` + + + diff --git a/solution/0200-0299/0263.Ugly Number/README.md b/solution/0200-0299/0263.Ugly Number/README.md index 3a909e557750c..73b19dfb1e6dd 100644 --- a/solution/0200-0299/0263.Ugly Number/README.md +++ b/solution/0200-0299/0263.Ugly Number/README.md @@ -44,20 +44,10 @@ ## 解法 - - -- 若 `n < 1`,说明 n 一定不是丑数,返回 false。 -- 若 `n % 2 == 0`,说明 2 是 n 的因子,此时应 `n /= 2`,然后继续判断 n 除以 2 后的值的因子。 -- 若 `n % 3 == 0`,说明 3 是 n 的因子,此时应 `n /= 3`,然后继续判断 n 除以 3 后的值的因子。 -- 若 `n % 5 == 0`,说明 5 是 n 的因子,此时应 `n /= 5`,然后继续判断 n 除以 5 后的值的因子。 -- 最后,判断 n 是否等于 1,若是,说明 n 的因子只可能包含 2、3、5,返回 true;否则返回 false。 +### 方法一 -### **Python3** - - - ```python class Solution: def isUgly(self, n: int) -> bool: @@ -69,10 +59,6 @@ class Solution: return n == 1 ``` -### **Java** - - - ```java class Solution { public boolean isUgly(int n) { @@ -91,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,7 +96,19 @@ public: }; ``` -### **JavaScript** +```go +func isUgly(n int) bool { + if n < 1 { + return false + } + for _, x := range []int{2, 3, 5} { + for n%x == 0 { + n /= x + } + } + return n == 1 +} +``` ```js /** @@ -134,24 +130,6 @@ var isUgly = function (n) { }; ``` -### **Go** - -```go -func isUgly(n int) bool { - if n < 1 { - return false - } - for _, x := range []int{2, 3, 5} { - for n%x == 0 { - n /= x - } - } - return n == 1 -} -``` - -### **PHP** - ```php class Solution { /** @@ -175,10 +153,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0263.Ugly Number/README_EN.md b/solution/0200-0299/0263.Ugly Number/README_EN.md index 36b19efe597f5..f0c5f05153a97 100644 --- a/solution/0200-0299/0263.Ugly Number/README_EN.md +++ b/solution/0200-0299/0263.Ugly Number/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return n == 1 ``` -### **Java** - ```java class Solution { public boolean isUgly(int n) { @@ -77,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,7 +94,19 @@ public: }; ``` -### **JavaScript** +```go +func isUgly(n int) bool { + if n < 1 { + return false + } + for _, x := range []int{2, 3, 5} { + for n%x == 0 { + n /= x + } + } + return n == 1 +} +``` ```js /** @@ -120,24 +128,6 @@ var isUgly = function (n) { }; ``` -### **Go** - -```go -func isUgly(n int) bool { - if n < 1 { - return false - } - for _, x := range []int{2, 3, 5} { - for n%x == 0 { - n /= x - } - } - return n == 1 -} -``` - -### **PHP** - ```php class Solution { /** @@ -161,10 +151,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0264.Ugly Number II/README.md b/solution/0200-0299/0264.Ugly Number II/README.md index 28e16f7161d76..7f04569688a7b 100644 --- a/solution/0200-0299/0264.Ugly Number II/README.md +++ b/solution/0200-0299/0264.Ugly Number II/README.md @@ -38,32 +38,14 @@ ## 解法 - - -**方法一:优先队列(最小堆)** +### 方法一:优先队列(最小堆) 初始时,将第一个丑数 $1$ 加入堆。每次取出堆顶元素 $x$,由于 $2x$, $3x$, $5x$ 也是丑数,因此将它们加入堆中。为了避免重复元素,可以用哈希表 $vis$ 去重。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。 -**方法二:动态规划** - -定义数组 $dp$,其中 $dp[i-1]$ 表示第 $i$ 个丑数,那么第 $n$ 个丑数就是 $dp[n - 1]$。最小的丑数是 $1$,所以 $dp[0]=1$。 - -定义 $3$ 个指针 $p_2$, $p_3$ 和 $p_5$,表示下一个丑数是当前指针指向的丑数乘以对应的质因数。初始时,三个指针的值都指向 $0$。 - -当 $i$ 在 $[1,2..n-1]$ 范围内,我们更新 $dp[i]=\min(dp[p_2] \times 2, dp[p_3] \times 3, dp[p_5] \times 5)$,然后分别比较 $dp[i]$ 与 $dp[p_2] \times 2$, $dp[p_3] \times 3$, $dp[p_5] \times 5$ 是否相等,若是,则对应的指针加 $1$。 - -最后返回 $dp[n - 1]$ 即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。 - -### **Python3** - - - ```python class Solution: def nthUglyNumber(self, n: int) -> int: @@ -80,27 +62,6 @@ class Solution: return ans ``` -```python -class Solution: - def nthUglyNumber(self, n: int) -> int: - dp = [1] * n - p2 = p3 = p5 = 0 - for i in range(1, n): - next2, next3, next5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 - dp[i] = min(next2, next3, next5) - if dp[i] == next2: - p2 += 1 - if dp[i] == next3: - p3 += 1 - if dp[i] == next5: - p5 += 1 - return dp[-1] -``` - -### **Java** - - - ```java class Solution { public int nthUglyNumber(int n) { @@ -124,26 +85,6 @@ class Solution { } ``` -```java -class Solution { - public int nthUglyNumber(int n) { - int[] dp = new int[n]; - dp[0] = 1; - int p2 = 0, p3 = 0, p5 = 0; - for (int i = 1; i < n; ++i) { - int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; - dp[i] = Math.min(next2, Math.min(next3, next5)); - if (dp[i] == next2) ++p2; - if (dp[i] == next3) ++p3; - if (dp[i] == next5) ++p5; - } - return dp[n - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -169,27 +110,6 @@ public: }; ``` -```cpp -class Solution { -public: - int nthUglyNumber(int n) { - vector dp(n); - dp[0] = 1; - int p2 = 0, p3 = 0, p5 = 0; - for (int i = 1; i < n; ++i) { - int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; - dp[i] = min(next2, min(next3, next5)); - if (dp[i] == next2) ++p2; - if (dp[i] == next3) ++p3; - if (dp[i] == next5) ++p5; - } - return dp[n - 1]; - } -}; -``` - -### **Go** - ```go func nthUglyNumber(n int) int { h := IntHeap([]int{1}) @@ -227,30 +147,6 @@ func (h *IntHeap) Pop() any { } ``` -```go -func nthUglyNumber(n int) int { - dp := make([]int, n) - dp[0] = 1 - p2, p3, p5 := 0, 0, 0 - for i := 1; i < n; i++ { - next2, next3, next5 := dp[p2]*2, dp[p3]*3, dp[p5]*5 - dp[i] = min(next2, min(next3, next5)) - if dp[i] == next2 { - p2++ - } - if dp[i] == next3 { - p3++ - } - if dp[i] == next5 { - p5++ - } - } - return dp[n-1] -} -``` - -### **JavaScript** - ```js /** * @param {number} n @@ -275,8 +171,6 @@ var nthUglyNumber = function (n) { }; ``` -### **C#** - ```cs public class Solution { public int NthUglyNumber(int n) { @@ -301,10 +195,98 @@ public class Solution { } ``` -### **...** + + +### 方法二:动态规划 + +定义数组 $dp$,其中 $dp[i-1]$ 表示第 $i$ 个丑数,那么第 $n$ 个丑数就是 $dp[n - 1]$。最小的丑数是 $1$,所以 $dp[0]=1$。 + +定义 $3$ 个指针 $p_2$, $p_3$ 和 $p_5$,表示下一个丑数是当前指针指向的丑数乘以对应的质因数。初始时,三个指针的值都指向 $0$。 + +当 $i$ 在 $[1,2..n-1]$ 范围内,我们更新 $dp[i]=\min(dp[p_2] \times 2, dp[p_3] \times 3, dp[p_5] \times 5)$,然后分别比较 $dp[i]$ 与 $dp[p_2] \times 2$, $dp[p_3] \times 3$, $dp[p_5] \times 5$ 是否相等,若是,则对应的指针加 $1$。 +最后返回 $dp[n - 1]$ 即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。 + + + +```python +class Solution: + def nthUglyNumber(self, n: int) -> int: + dp = [1] * n + p2 = p3 = p5 = 0 + for i in range(1, n): + next2, next3, next5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 + dp[i] = min(next2, next3, next5) + if dp[i] == next2: + p2 += 1 + if dp[i] == next3: + p3 += 1 + if dp[i] == next5: + p5 += 1 + return dp[-1] ``` +```java +class Solution { + public int nthUglyNumber(int n) { + int[] dp = new int[n]; + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = Math.min(next2, Math.min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + } + return dp[n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int nthUglyNumber(int n) { + vector dp(n); + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = min(next2, min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + } + return dp[n - 1]; + } +}; +``` + +```go +func nthUglyNumber(n int) int { + dp := make([]int, n) + dp[0] = 1 + p2, p3, p5 := 0, 0, 0 + for i := 1; i < n; i++ { + next2, next3, next5 := dp[p2]*2, dp[p3]*3, dp[p5]*5 + dp[i] = min(next2, min(next3, next5)) + if dp[i] == next2 { + p2++ + } + if dp[i] == next3 { + p3++ + } + if dp[i] == next5 { + p5++ + } + } + return dp[n-1] +} ``` + + diff --git a/solution/0200-0299/0264.Ugly Number II/README_EN.md b/solution/0200-0299/0264.Ugly Number II/README_EN.md index e2164af760077..875d68722bcfb 100644 --- a/solution/0200-0299/0264.Ugly Number II/README_EN.md +++ b/solution/0200-0299/0264.Ugly Number II/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,43 +54,6 @@ class Solution: return ans ``` -```python -class Solution: - def nthUglyNumber(self, n: int) -> int: - dp = [1] * n - p2 = p3 = p5 = 0 - for i in range(1, n): - next2, next3, next5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 - dp[i] = min(next2, next3, next5) - if dp[i] == next2: - p2 += 1 - if dp[i] == next3: - p3 += 1 - if dp[i] == next5: - p5 += 1 - return dp[-1] -``` - -### **Java** - -```java -class Solution { - public int nthUglyNumber(int n) { - int[] dp = new int[n]; - dp[0] = 1; - int p2 = 0, p3 = 0, p5 = 0; - for (int i = 1; i < n; ++i) { - int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; - dp[i] = Math.min(next2, Math.min(next3, next5)); - if (dp[i] == next2) ++p2; - if (dp[i] == next3) ++p3; - if (dp[i] == next5) ++p5; - } - return dp[n - 1]; - } -} -``` - ```java class Solution { public int nthUglyNumber(int n) { @@ -114,27 +77,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int nthUglyNumber(int n) { - vector dp(n); - dp[0] = 1; - int p2 = 0, p3 = 0, p5 = 0; - for (int i = 1; i < n; ++i) { - int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; - dp[i] = min(next2, min(next3, next5)); - if (dp[i] == next2) ++p2; - if (dp[i] == next3) ++p3; - if (dp[i] == next5) ++p5; - } - return dp[n - 1]; - } -}; -``` - ```cpp class Solution { public: @@ -160,8 +102,6 @@ public: }; ``` -### **Go** - ```go func nthUglyNumber(n int) int { h := IntHeap([]int{1}) @@ -199,30 +139,6 @@ func (h *IntHeap) Pop() any { } ``` -```go -func nthUglyNumber(n int) int { - dp := make([]int, n) - dp[0] = 1 - p2, p3, p5 := 0, 0, 0 - for i := 1; i < n; i++ { - next2, next3, next5 := dp[p2]*2, dp[p3]*3, dp[p5]*5 - dp[i] = min(next2, min(next3, next5)) - if dp[i] == next2 { - p2++ - } - if dp[i] == next3 { - p3++ - } - if dp[i] == next5 { - p5++ - } - } - return dp[n-1] -} -``` - -### **JavaScript** - ```js /** * @param {number} n @@ -247,8 +163,6 @@ var nthUglyNumber = function (n) { }; ``` -### **C#** - ```cs public class Solution { public int NthUglyNumber(int n) { @@ -273,10 +187,88 @@ public class Solution { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def nthUglyNumber(self, n: int) -> int: + dp = [1] * n + p2 = p3 = p5 = 0 + for i in range(1, n): + next2, next3, next5 = dp[p2] * 2, dp[p3] * 3, dp[p5] * 5 + dp[i] = min(next2, next3, next5) + if dp[i] == next2: + p2 += 1 + if dp[i] == next3: + p3 += 1 + if dp[i] == next5: + p5 += 1 + return dp[-1] +``` + +```java +class Solution { + public int nthUglyNumber(int n) { + int[] dp = new int[n]; + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = Math.min(next2, Math.min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + } + return dp[n - 1]; + } +} +``` +```cpp +class Solution { +public: + int nthUglyNumber(int n) { + vector dp(n); + dp[0] = 1; + int p2 = 0, p3 = 0, p5 = 0; + for (int i = 1; i < n; ++i) { + int next2 = dp[p2] * 2, next3 = dp[p3] * 3, next5 = dp[p5] * 5; + dp[i] = min(next2, min(next3, next5)); + if (dp[i] == next2) ++p2; + if (dp[i] == next3) ++p3; + if (dp[i] == next5) ++p5; + } + return dp[n - 1]; + } +}; ``` +```go +func nthUglyNumber(n int) int { + dp := make([]int, n) + dp[0] = 1 + p2, p3, p5 := 0, 0, 0 + for i := 1; i < n; i++ { + next2, next3, next5 := dp[p2]*2, dp[p3]*3, dp[p5]*5 + dp[i] = min(next2, min(next3, next5)) + if dp[i] == next2 { + p2++ + } + if dp[i] == next3 { + p3++ + } + if dp[i] == next5 { + p5++ + } + } + return dp[n-1] +} ``` + + diff --git a/solution/0200-0299/0265.Paint House II/README.md b/solution/0200-0299/0265.Paint House II/README.md index de79223ad8f3e..0d333bdc81b52 100644 --- a/solution/0200-0299/0265.Paint House II/README.md +++ b/solution/0200-0299/0265.Paint House II/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 定义 $f[i][j]$ 表示粉刷前 $i$ 个房子,且最后一个房子被粉刷成第 $j$ 种颜色的最小花费。答案为 $\min_{0 \leq j < k} f[n][j]$。 @@ -70,10 +68,6 @@ $$ -### **Python3** - - - ```python class Solution: def minCostII(self, costs: List[List[int]]) -> int: @@ -88,10 +82,6 @@ class Solution: return min(f) ``` -### **Java** - - - ```java class Solution { public int minCostII(int[][] costs) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func minCostII(costs [][]int) int { n, k := len(costs), len(costs[0]) @@ -170,10 +156,6 @@ func cp(arr []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0265.Paint House II/README_EN.md b/solution/0200-0299/0265.Paint House II/README_EN.md index f31c49a7f1c46..37e4d5294f310 100644 --- a/solution/0200-0299/0265.Paint House II/README_EN.md +++ b/solution/0200-0299/0265.Paint House II/README_EN.md @@ -48,9 +48,9 @@ Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return min(f) ``` -### **Java** - ```java class Solution { public int minCostII(int[][] costs) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +113,6 @@ public: }; ``` -### **Go** - ```go func minCostII(costs [][]int) int { n, k := len(costs), len(costs[0]) @@ -146,10 +140,6 @@ func cp(arr []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0266.Palindrome Permutation/README.md b/solution/0200-0299/0266.Palindrome Permutation/README.md index 2cd1047e8c82b..1ae5283f35102 100644 --- a/solution/0200-0299/0266.Palindrome Permutation/README.md +++ b/solution/0200-0299/0266.Palindrome Permutation/README.md @@ -42,38 +42,20 @@ ## 解法 - - -**方法一:数组** +### 方法一:数组 创建一个长度为 $26$ 的数组,统计每个字母出现的频率,至多有一个字符出现奇数次数即可。 时间复杂度 $O(n)$,空间复杂度 $O(|\Sigma|)$。其中 $n$ 是字符串的长度,而 $|\Sigma|$ 是字符集的大小,本题中字符集为小写字母,因此 $|\Sigma|=26$。 -**方法二:哈希表** - -利用哈希表来维护元素。遍历字符串每个字母 $s[i]$,若 $s[i]$ 在哈希表中,则将 $s[i]$ 从哈希表中删除,否则将 $s[i]$ 加入哈希表。 - -遍历结束,若哈希表中元素个数不超过 $1$,则返回 $true$,否则返回 $false$。 - -时间复杂度 $O(n)$,空间复杂度 $O(|\Sigma|)$。其中 $n$ 是字符串的长度,而 $|\Sigma|$ 是字符集的大小,本题中字符集为小写字母,因此 $|\Sigma|=26$。 - -### **Python3** - - - ```python class Solution: def canPermutePalindrome(self, s: str) -> bool: return sum(v & 1 for v in Counter(s).values()) < 2 ``` -### **Java** - - - ```java class Solution { public boolean canPermutePalindrome(String s) { @@ -90,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +89,6 @@ public: }; ``` -### **Go** - ```go func canPermutePalindrome(s string) bool { cnt := [26]int{} @@ -125,8 +103,6 @@ func canPermutePalindrome(s string) bool { } ``` -### **TypeScript** - ```ts function canPermutePalindrome(s: string): boolean { const cnt: number[] = new Array(26).fill(0); @@ -137,8 +113,6 @@ function canPermutePalindrome(s: string): boolean { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -153,10 +127,14 @@ var canPermutePalindrome = function (s) { }; ``` -### **...** + -``` +### 方法二:哈希表 -``` +利用哈希表来维护元素。遍历字符串每个字母 $s[i]$,若 $s[i]$ 在哈希表中,则将 $s[i]$ 从哈希表中删除,否则将 $s[i]$ 加入哈希表。 - +遍历结束,若哈希表中元素个数不超过 $1$,则返回 $true$,否则返回 $false$。 + +时间复杂度 $O(n)$,空间复杂度 $O(|\Sigma|)$。其中 $n$ 是字符串的长度,而 $|\Sigma|$ 是字符集的大小,本题中字符集为小写字母,因此 $|\Sigma|=26$。 + + diff --git a/solution/0200-0299/0266.Palindrome Permutation/README_EN.md b/solution/0200-0299/0266.Palindrome Permutation/README_EN.md index 3468bf07d97f7..86515ddeef7c4 100644 --- a/solution/0200-0299/0266.Palindrome Permutation/README_EN.md +++ b/solution/0200-0299/0266.Palindrome Permutation/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -48,8 +48,6 @@ class Solution: return sum(v & 1 for v in Counter(s).values()) < 2 ``` -### **Java** - ```java class Solution { public boolean canPermutePalindrome(String s) { @@ -66,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -85,8 +81,6 @@ public: }; ``` -### **Go** - ```go func canPermutePalindrome(s string) bool { cnt := [26]int{} @@ -101,8 +95,6 @@ func canPermutePalindrome(s string) bool { } ``` -### **TypeScript** - ```ts function canPermutePalindrome(s: string): boolean { const cnt: number[] = new Array(26).fill(0); @@ -113,8 +105,6 @@ function canPermutePalindrome(s: string): boolean { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -129,10 +119,6 @@ var canPermutePalindrome = function (s) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0267.Palindrome Permutation II/README.md b/solution/0200-0299/0267.Palindrome Permutation II/README.md index 7e887b7617ed1..3ce16e64a0980 100644 --- a/solution/0200-0299/0267.Palindrome Permutation II/README.md +++ b/solution/0200-0299/0267.Palindrome Permutation II/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:回溯** +### 方法一:回溯 回文排列需要满足至多有一个字符出现奇数次数。若不满足条件,答案提前返回。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python class Solution: def generatePalindromes(self, s: str) -> List[str]: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List ans = new ArrayList<>(); @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -166,8 +154,6 @@ public: }; ``` -### **Go** - ```go func generatePalindromes(s string) []string { cnt := map[byte]int{} @@ -204,10 +190,6 @@ func generatePalindromes(s string) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0267.Palindrome Permutation II/README_EN.md b/solution/0200-0299/0267.Palindrome Permutation II/README_EN.md index 43a8a617b7058..cc479989d2314 100644 --- a/solution/0200-0299/0267.Palindrome Permutation II/README_EN.md +++ b/solution/0200-0299/0267.Palindrome Permutation II/README_EN.md @@ -26,9 +26,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List ans = new ArrayList<>(); @@ -99,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +136,6 @@ public: }; ``` -### **Go** - ```go func generatePalindromes(s string) []string { cnt := map[byte]int{} @@ -178,10 +172,6 @@ func generatePalindromes(s string) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0268.Missing Number/README.md b/solution/0200-0299/0268.Missing Number/README.md index 727d71ee35915..99bfaf70af47c 100644 --- a/solution/0200-0299/0268.Missing Number/README.md +++ b/solution/0200-0299/0268.Missing Number/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 异或运算的性质: @@ -71,35 +69,14 @@ 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组长度。 -**方法二:数学** - -我们也可以用数学求解。求出 $[0,..n]$ 的和,减去数组中所有数的和,就得到了缺失的数字。 - -时间复杂度 $O(n)$,其中 $n$ 为数组长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def missingNumber(self, nums: List[int]) -> int: return reduce(xor, (i ^ v for i, v in enumerate(nums, 1))) ``` -```python -class Solution: - def missingNumber(self, nums: List[int]) -> int: - n = len(nums) - return (1 + n) * n // 2 - sum(nums) -``` - -### **Java** - - - ```java class Solution { public int missingNumber(int[] nums) { @@ -113,21 +90,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; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -142,18 +104,6 @@ public: }; ``` -```cpp -class Solution { -public: - int missingNumber(vector& nums) { - int n = nums.size(); - return (1 + n) * n / 2 - accumulate(nums.begin(), nums.end(), 0); - } -}; -``` - -### **Go** - ```go func missingNumber(nums []int) (ans int) { n := len(nums) @@ -165,19 +115,17 @@ func missingNumber(nums []int) (ans int) { } ``` -```go -func missingNumber(nums []int) (ans int) { - n := len(nums) - ans = n - for i, v := range nums { - ans += i - v - } - return +```ts +function missingNumber(nums: number[]): number { + const n = nums.length; + let ans = n; + for (let i = 0; i < n; ++i) { + ans ^= i ^ nums[i]; + } + return ans; } ``` -### **Rust** - ```rust impl Solution { pub fn missing_number(nums: Vec) -> i32 { @@ -191,29 +139,86 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn missing_number(nums: Vec) -> i32 { - let n = nums.len() as i32; - let mut ans = n; - for (i, &v) in nums.iter().enumerate() { - ans += (i as i32) - v; +```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; +}; +``` + +```php +class Solution { + /** + * @param Integer[] $nums + * @return Integer + */ + function missingNumber($nums) { + $n = count($nums); + $sumN = (($n + 1) * $n) / 2; + for ($i = 0; $i < $n; $i++) { + $sumN -= $nums[$i]; } - ans + return $sumN; } } ``` -### **TypeScript** + -```ts -function missingNumber(nums: number[]): number { - const n = nums.length; - let ans = n; - for (let i = 0; i < n; ++i) { - ans ^= i ^ nums[i]; +### 方法二:数学 + +我们也可以用数学求解。求出 $[0,..n]$ 的和,减去数组中所有数的和,就得到了缺失的数字。 + +时间复杂度 $O(n)$,其中 $n$ 为数组长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def missingNumber(self, nums: List[int]) -> int: + n = len(nums) + return (1 + n) * n // 2 - sum(nums) +``` + +```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; +} +``` + +```cpp +class Solution { +public: + int missingNumber(vector& nums) { + int n = nums.size(); + return (1 + n) * n / 2 - accumulate(nums.begin(), nums.end(), 0); + } +}; +``` + +```go +func missingNumber(nums []int) (ans int) { + n := len(nums) + ans = n + for i, v := range nums { + ans += i - v + } + return } ``` @@ -228,21 +233,17 @@ function missingNumber(nums: number[]): number { } ``` -### **JavaScript** - -```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]; +```rust +impl Solution { + pub fn missing_number(nums: Vec) -> i32 { + let n = nums.len() as i32; + let mut ans = n; + for (i, &v) in nums.iter().enumerate() { + ans += (i as i32) - v; + } + ans } - return ans; -}; +} ``` ```js @@ -260,29 +261,6 @@ var missingNumber = function (nums) { }; ``` -### **PHP** - -```php -class Solution { - /** - * @param Integer[] $nums - * @return Integer - */ - function missingNumber($nums) { - $n = count($nums); - $sumN = (($n + 1) * $n) / 2; - for ($i = 0; $i < $n; $i++) { - $sumN -= $nums[$i]; - } - return $sumN; - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0268.Missing Number/README_EN.md b/solution/0200-0299/0268.Missing Number/README_EN.md index 50c6461cafb7c..29cf09a82e7c8 100644 --- a/solution/0200-0299/0268.Missing Number/README_EN.md +++ b/solution/0200-0299/0268.Missing Number/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Bitwise Operation** +### Solution 1: Bitwise Operation The XOR operation has the following properties: @@ -57,31 +57,14 @@ Therefore, we can traverse the array, perform XOR operation between each element The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$. -**Solution 2: Mathematics** - -We can also solve this problem using mathematics. By calculating the sum of $[0,..n]$, subtracting the sum of all numbers in the array, we can obtain the missing number. - -The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def missingNumber(self, nums: List[int]) -> int: return reduce(xor, (i ^ v for i, v in enumerate(nums, 1))) ``` -```python -class Solution: - def missingNumber(self, nums: List[int]) -> int: - n = len(nums) - return (1 + n) * n // 2 - sum(nums) -``` - -### **Java** - ```java class Solution { public int missingNumber(int[] nums) { @@ -95,21 +78,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; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -124,18 +92,6 @@ public: }; ``` -```cpp -class Solution { -public: - int missingNumber(vector& nums) { - int n = nums.size(); - return (1 + n) * n / 2 - accumulate(nums.begin(), nums.end(), 0); - } -}; -``` - -### **Go** - ```go func missingNumber(nums []int) (ans int) { n := len(nums) @@ -147,19 +103,17 @@ func missingNumber(nums []int) (ans int) { } ``` -```go -func missingNumber(nums []int) (ans int) { - n := len(nums) - ans = n - for i, v := range nums { - ans += i - v - } - return +```ts +function missingNumber(nums: number[]): number { + const n = nums.length; + let ans = n; + for (let i = 0; i < n; ++i) { + ans ^= i ^ nums[i]; + } + return ans; } ``` -### **Rust** - ```rust impl Solution { pub fn missing_number(nums: Vec) -> i32 { @@ -173,29 +127,86 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn missing_number(nums: Vec) -> i32 { - let n = nums.len() as i32; - let mut ans = n; - for (i, &v) in nums.iter().enumerate() { - ans += (i as i32) - v; +```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; +}; +``` + +```php +class Solution { + /** + * @param Integer[] $nums + * @return Integer + */ + function missingNumber($nums) { + $n = count($nums); + $sumN = (($n + 1) * $n) / 2; + for ($i = 0; $i < $n; $i++) { + $sumN -= $nums[$i]; } - ans + return $sumN; } } ``` -### **TypeScript** + -```ts -function missingNumber(nums: number[]): number { - const n = nums.length; - let ans = n; - for (let i = 0; i < n; ++i) { - ans ^= i ^ nums[i]; +### Solution 2: Mathematics + +We can also solve this problem using mathematics. By calculating the sum of $[0,..n]$, subtracting the sum of all numbers in the array, we can obtain the missing number. + +The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$. + + + +```python +class Solution: + def missingNumber(self, nums: List[int]) -> int: + n = len(nums) + return (1 + n) * n // 2 - sum(nums) +``` + +```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; +} +``` + +```cpp +class Solution { +public: + int missingNumber(vector& nums) { + int n = nums.size(); + return (1 + n) * n / 2 - accumulate(nums.begin(), nums.end(), 0); + } +}; +``` + +```go +func missingNumber(nums []int) (ans int) { + n := len(nums) + ans = n + for i, v := range nums { + ans += i - v + } + return } ``` @@ -210,21 +221,17 @@ function missingNumber(nums: number[]): number { } ``` -### **JavaScript** - -```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]; +```rust +impl Solution { + pub fn missing_number(nums: Vec) -> i32 { + let n = nums.len() as i32; + let mut ans = n; + for (i, &v) in nums.iter().enumerate() { + ans += (i as i32) - v; + } + ans } - return ans; -}; +} ``` ```js @@ -242,29 +249,6 @@ var missingNumber = function (nums) { }; ``` -### **PHP** - -```php -class Solution { - /** - * @param Integer[] $nums - * @return Integer - */ - function missingNumber($nums) { - $n = count($nums); - $sumN = (($n + 1) * $n) / 2; - for ($i = 0; $i < $n; $i++) { - $sumN -= $nums[$i]; - } - return $sumN; - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0269.Alien Dictionary/README.md b/solution/0200-0299/0269.Alien Dictionary/README.md index f7dc0ea0ce5a8..e3fa1d0852926 100644 --- a/solution/0200-0299/0269.Alien Dictionary/README.md +++ b/solution/0200-0299/0269.Alien Dictionary/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:拓扑排序 + BFS** +### 方法一:拓扑排序 + BFS 用数组 $g$ 记录在火星字典中的字母先后关系,$g[i][j] = true$ 表示字母 $i + 'a'$ 在字母 $j + 'a'$ 的前面;用数组 $s$ 记录当前字典出现过的字母,$cnt$ 表示出现过的字母数。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def alienOrder(self, words: List[str]) -> str: @@ -133,10 +127,6 @@ class Solution: return '' if len(ans) < cnt else ''.join(ans) ``` -### **Java** - - - ```java class Solution { @@ -214,8 +204,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -275,10 +263,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0269.Alien Dictionary/README_EN.md b/solution/0200-0299/0269.Alien Dictionary/README_EN.md index 55ad46e6fb3ef..dd922bee2f7cb 100644 --- a/solution/0200-0299/0269.Alien Dictionary/README_EN.md +++ b/solution/0200-0299/0269.Alien Dictionary/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -106,8 +106,6 @@ class Solution: return '' if len(ans) < cnt else ''.join(ans) ``` -### **Java** - ```java class Solution { @@ -185,8 +183,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -246,10 +242,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0270.Closest Binary Search Tree Value/README.md b/solution/0200-0299/0270.Closest Binary Search Tree Value/README.md index bb28af9bfdc1e..37964985485a1 100644 --- a/solution/0200-0299/0270.Closest Binary Search Tree Value/README.md +++ b/solution/0200-0299/0270.Closest Binary Search Tree Value/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:中序遍历** +### 方法一:中序遍历 我们用一个变量 $mi$ 维护最小的差值,用一个变量 $ans$ 维护答案。初始时 $mi=\infty$, $ans=root.val$。 @@ -46,20 +44,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉搜索树的节点数。 -**方法二:二分查找** - -与方法一类似,我们用一个变量 $mi$ 维护最小的差值,用一个变量 $ans$ 维护答案。初始时 $mi=\infty$, $ans=root.val$。 - -接下来,进行二分查找,每次计算当前节点与目标值 $target$ 的差的绝对值 $t$。如果 $t \lt mi$,或者 $t = mi$ 且当前节点的值小于 $ans$,则更新 $mi$ 和 $ans$。如果当前节点的值大于 $target$,则查找左子树,否则查找右子树。当我们遍历到叶子节点时,就可以结束二分查找了。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是二叉搜索树的节点数。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -85,32 +71,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def closestValue(self, root: Optional[TreeNode], target: float) -> int: - ans, mi = root.val, inf - while root: - t = abs(root.val - target) - if t < mi or (t == mi and root.val < ans): - mi = t - ans = root.val - if root.val > target: - root = root.left - else: - root = root.right - return ans -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -153,45 +113,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public int closestValue(TreeNode root, double target) { - int ans = root.val; - double mi = Double.MAX_VALUE; - while (root != null) { - double t = Math.abs(root.val - target); - if (t < mi || (t == mi && root.val < ans)) { - mi = t; - ans = root.val; - } - if (root.val > target) { - root = root.left; - } else { - root = root.right; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -227,42 +148,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int closestValue(TreeNode* root, double target) { - int ans = root->val; - double mi = INT_MAX; - while (root) { - double t = abs(root->val - target); - if (t < mi || (t == mi && root->val < ans)) { - mi = t; - ans = root->val; - } - if (root->val > target) { - root = root->left; - } else { - root = root->right; - } - } - return ans; - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -293,36 +178,6 @@ func closestValue(root *TreeNode, target float64) int { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func closestValue(root *TreeNode, target float64) int { - ans := root.Val - mi := math.MaxFloat64 - for root != nil { - t := math.Abs(float64(root.Val) - target) - if t < mi || (t == mi && root.Val < ans) { - mi = t - ans = root.Val - } - if float64(root.Val) > target { - root = root.Left - } else { - root = root.Right - } - } - return ans -} -``` - -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -357,6 +212,139 @@ var closestValue = function (root, target) { }; ``` + + +### 方法二:二分查找 + +与方法一类似,我们用一个变量 $mi$ 维护最小的差值,用一个变量 $ans$ 维护答案。初始时 $mi=\infty$, $ans=root.val$。 + +接下来,进行二分查找,每次计算当前节点与目标值 $target$ 的差的绝对值 $t$。如果 $t \lt mi$,或者 $t = mi$ 且当前节点的值小于 $ans$,则更新 $mi$ 和 $ans$。如果当前节点的值大于 $target$,则查找左子树,否则查找右子树。当我们遍历到叶子节点时,就可以结束二分查找了。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是二叉搜索树的节点数。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def closestValue(self, root: Optional[TreeNode], target: float) -> int: + ans, mi = root.val, inf + while root: + t = abs(root.val - target) + if t < mi or (t == mi and root.val < ans): + mi = t + ans = root.val + if root.val > target: + root = root.left + else: + root = root.right + return ans +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int closestValue(TreeNode root, double target) { + int ans = root.val; + double mi = Double.MAX_VALUE; + while (root != null) { + double t = Math.abs(root.val - target); + if (t < mi || (t == mi && root.val < ans)) { + mi = t; + ans = root.val; + } + if (root.val > target) { + root = root.left; + } else { + root = root.right; + } + } + return ans; + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int closestValue(TreeNode* root, double target) { + int ans = root->val; + double mi = INT_MAX; + while (root) { + double t = abs(root->val - target); + if (t < mi || (t == mi && root->val < ans)) { + mi = t; + ans = root->val; + } + if (root->val > target) { + root = root->left; + } else { + root = root->right; + } + } + return ans; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func closestValue(root *TreeNode, target float64) int { + ans := root.Val + mi := math.MaxFloat64 + for root != nil { + t := math.Abs(float64(root.Val) - target) + if t < mi || (t == mi && root.Val < ans) { + mi = t + ans = root.Val + } + if float64(root.Val) > target { + root = root.Left + } else { + root = root.Right + } + } + return ans +} +``` + ```js /** * Definition for a binary tree node. @@ -390,10 +378,6 @@ var closestValue = function (root, target) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0270.Closest Binary Search Tree Value/README_EN.md b/solution/0200-0299/0270.Closest Binary Search Tree Value/README_EN.md index 90f22e254d7c0..f83cf536af005 100644 --- a/solution/0200-0299/0270.Closest Binary Search Tree Value/README_EN.md +++ b/solution/0200-0299/0270.Closest Binary Search Tree Value/README_EN.md @@ -32,12 +32,10 @@ ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -63,30 +61,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def closestValue(self, root: Optional[TreeNode], target: float) -> int: - ans, mi = root.val, inf - while root: - t = abs(root.val - target) - if t < mi or (t == mi and root.val < ans): - mi = t - ans = root.val - if root.val > target: - root = root.left - else: - root = root.right - return ans -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -129,45 +103,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public int closestValue(TreeNode root, double target) { - int ans = root.val; - double mi = Double.MAX_VALUE; - while (root != null) { - double t = Math.abs(root.val - target); - if (t < mi || (t == mi && root.val < ans)) { - mi = t; - ans = root.val; - } - if (root.val > target) { - root = root.left; - } else { - root = root.right; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -203,42 +138,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int closestValue(TreeNode* root, double target) { - int ans = root->val; - double mi = INT_MAX; - while (root) { - double t = abs(root->val - target); - if (t < mi || (t == mi && root->val < ans)) { - mi = t; - ans = root->val; - } - if (root->val > target) { - root = root->left; - } else { - root = root->right; - } - } - return ans; - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -269,36 +168,6 @@ func closestValue(root *TreeNode, target float64) int { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func closestValue(root *TreeNode, target float64) int { - ans := root.Val - mi := math.MaxFloat64 - for root != nil { - t := math.Abs(float64(root.Val) - target) - if t < mi || (t == mi && root.Val < ans) { - mi = t - ans = root.Val - } - if float64(root.Val) > target { - root = root.Left - } else { - root = root.Right - } - } - return ans -} -``` - -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -333,6 +202,133 @@ var closestValue = function (root, target) { }; ``` + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def closestValue(self, root: Optional[TreeNode], target: float) -> int: + ans, mi = root.val, inf + while root: + t = abs(root.val - target) + if t < mi or (t == mi and root.val < ans): + mi = t + ans = root.val + if root.val > target: + root = root.left + else: + root = root.right + return ans +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int closestValue(TreeNode root, double target) { + int ans = root.val; + double mi = Double.MAX_VALUE; + while (root != null) { + double t = Math.abs(root.val - target); + if (t < mi || (t == mi && root.val < ans)) { + mi = t; + ans = root.val; + } + if (root.val > target) { + root = root.left; + } else { + root = root.right; + } + } + return ans; + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int closestValue(TreeNode* root, double target) { + int ans = root->val; + double mi = INT_MAX; + while (root) { + double t = abs(root->val - target); + if (t < mi || (t == mi && root->val < ans)) { + mi = t; + ans = root->val; + } + if (root->val > target) { + root = root->left; + } else { + root = root->right; + } + } + return ans; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func closestValue(root *TreeNode, target float64) int { + ans := root.Val + mi := math.MaxFloat64 + for root != nil { + t := math.Abs(float64(root.Val) - target) + if t < mi || (t == mi && root.Val < ans) { + mi = t + ans = root.Val + } + if float64(root.Val) > target { + root = root.Left + } else { + root = root.Right + } + } + return ans +} +``` + ```js /** * Definition for a binary tree node. @@ -366,10 +362,6 @@ var closestValue = function (root, target) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0271.Encode and Decode Strings/README.md b/solution/0200-0299/0271.Encode and Decode Strings/README.md index 53b03fcc16487..e1a5e3c0232c7 100644 --- a/solution/0200-0299/0271.Encode and Decode Strings/README.md +++ b/solution/0200-0299/0271.Encode and Decode Strings/README.md @@ -47,28 +47,14 @@ ## 解法 - - -**方法一:使用非 ASCII 码的分隔符** +### 方法一:使用非 ASCII 码的分隔符 Python 中可以直接 `chr(257)` 作为字符串的分隔符,这样就可以实现字符串的编码和解码。 时间复杂度 $O(n)$。 -**方法二:编码字符串长度** - -编码时,将字符串的长度转成固定 $4$ 位的字符串,加上字符串本身,依次拼接到结果字符串。 - -解码时,先取前四位字符串,得到长度,再通过长度截取后面的字符串。依次截取,最终得到字符串列表。 - -时间复杂度 $O(n)$。 - -### **Python3** - - - ```python class Codec: def encode(self, strs: List[str]) -> str: @@ -85,36 +71,6 @@ class Codec: # codec.decode(codec.encode(strs)) ``` -```python -class Codec: - def encode(self, strs: List[str]) -> str: - """Encodes a list of strings to a single string.""" - ans = [] - for s in strs: - ans.append('{:4}'.format(len(s)) + s) - return ''.join(ans) - - def decode(self, s: str) -> List[str]: - """Decodes a single string to a list of strings.""" - ans = [] - i, n = 0, len(s) - while i < n: - size = int(s[i : i + 4]) - i += 4 - ans.append(s[i : i + size]) - i += size - return ans - - -# Your Codec object will be instantiated and called as such: -# codec = Codec() -# codec.decode(codec.encode(strs)) -``` - -### **Java** - - - ```java public class Codec { @@ -145,8 +101,6 @@ public class Codec { // codec.decode(codec.encode(strs)); ``` -### **C++** - ```cpp class Codec { public: @@ -181,8 +135,6 @@ public: // codec.decode(codec.encode(strs)); ``` -### **Go** - ```go type Codec struct { } @@ -217,10 +169,44 @@ func (codec *Codec) Decode(strs string) []string { // codec.Decode(codec.Encode(strs)); ``` -### **...** + -``` +### 方法二:编码字符串长度 + +编码时,将字符串的长度转成固定 $4$ 位的字符串,加上字符串本身,依次拼接到结果字符串。 + +解码时,先取前四位字符串,得到长度,再通过长度截取后面的字符串。依次截取,最终得到字符串列表。 + +时间复杂度 $O(n)$。 + + +```python +class Codec: + def encode(self, strs: List[str]) -> str: + """Encodes a list of strings to a single string.""" + ans = [] + for s in strs: + ans.append('{:4}'.format(len(s)) + s) + return ''.join(ans) + + def decode(self, s: str) -> List[str]: + """Decodes a single string to a list of strings.""" + ans = [] + i, n = 0, len(s) + while i < n: + size = int(s[i : i + 4]) + i += 4 + ans.append(s[i : i + size]) + i += size + return ans + + +# Your Codec object will be instantiated and called as such: +# codec = Codec() +# codec.decode(codec.encode(strs)) ``` + + diff --git a/solution/0200-0299/0271.Encode and Decode Strings/README_EN.md b/solution/0200-0299/0271.Encode and Decode Strings/README_EN.md index cf8d0f30e99c6..c4a3ca923a5af 100644 --- a/solution/0200-0299/0271.Encode and Decode Strings/README_EN.md +++ b/solution/0200-0299/0271.Encode and Decode Strings/README_EN.md @@ -79,9 +79,9 @@ String[] strs = decoder.decode(msg); ## Solutions - +### Solution 1 -### **Python3** + ```python class Codec: @@ -99,34 +99,6 @@ class Codec: # codec.decode(codec.encode(strs)) ``` -```python -class Codec: - def encode(self, strs: List[str]) -> str: - """Encodes a list of strings to a single string.""" - ans = [] - for s in strs: - ans.append('{:4}'.format(len(s)) + s) - return ''.join(ans) - - def decode(self, s: str) -> List[str]: - """Decodes a single string to a list of strings.""" - ans = [] - i, n = 0, len(s) - while i < n: - size = int(s[i : i + 4]) - i += 4 - ans.append(s[i : i + size]) - i += size - return ans - - -# Your Codec object will be instantiated and called as such: -# codec = Codec() -# codec.decode(codec.encode(strs)) -``` - -### **Java** - ```java public class Codec { @@ -157,8 +129,6 @@ public class Codec { // codec.decode(codec.encode(strs)); ``` -### **C++** - ```cpp class Codec { public: @@ -193,8 +163,6 @@ public: // codec.decode(codec.encode(strs)); ``` -### **Go** - ```go type Codec struct { } @@ -229,10 +197,38 @@ func (codec *Codec) Decode(strs string) []string { // codec.Decode(codec.Encode(strs)); ``` -### **...** + + +### Solution 2 -``` + + +```python +class Codec: + def encode(self, strs: List[str]) -> str: + """Encodes a list of strings to a single string.""" + ans = [] + for s in strs: + ans.append('{:4}'.format(len(s)) + s) + return ''.join(ans) + + def decode(self, s: str) -> List[str]: + """Decodes a single string to a list of strings.""" + ans = [] + i, n = 0, len(s) + while i < n: + size = int(s[i : i + 4]) + i += 4 + ans.append(s[i : i + size]) + i += size + return ans + +# Your Codec object will be instantiated and called as such: +# codec = Codec() +# codec.decode(codec.encode(strs)) ``` + + diff --git a/solution/0200-0299/0272.Closest Binary Search Tree Value II/README.md b/solution/0200-0299/0272.Closest Binary Search Tree Value II/README.md index 5c140b235ec1c..921fd270a454c 100644 --- a/solution/0200-0299/0272.Closest Binary Search Tree Value II/README.md +++ b/solution/0200-0299/0272.Closest Binary Search Tree Value II/README.md @@ -44,21 +44,10 @@ ## 解法 - - -中序遍历,当结果元素个数小于 k 时,直接添加。否则,拿第一个元素与当前节点 root 各自与 target 的差值的绝对值进行比较。 - -- 若当前节点 root 与目标值的差值的绝对值大于等于第一个节点与目标值差值的绝对值,移除第一个元素,然后添加当前节点 root.val。 -- 否则,无需再遍历后面的节点。 - -时间复杂度 $O(n)$,空间复杂度 $O(k)$。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -86,10 +75,6 @@ class Solution: return list(q) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -139,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -186,8 +169,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -221,10 +202,6 @@ func closestKValues(root *TreeNode, target float64, k int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0272.Closest Binary Search Tree Value II/README_EN.md b/solution/0200-0299/0272.Closest Binary Search Tree Value II/README_EN.md index 303617adf086a..02122446685cb 100644 --- a/solution/0200-0299/0272.Closest Binary Search Tree Value II/README_EN.md +++ b/solution/0200-0299/0272.Closest Binary Search Tree Value II/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -69,8 +69,6 @@ class Solution: return list(q) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -120,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -167,8 +163,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -202,10 +196,6 @@ func closestKValues(root *TreeNode, target float64, k int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0273.Integer to English Words/README.md b/solution/0200-0299/0273.Integer to English Words/README.md index c378ab1da46c6..80d04d117b71e 100644 --- a/solution/0200-0299/0273.Integer to English Words/README.md +++ b/solution/0200-0299/0273.Integer to English Words/README.md @@ -41,14 +41,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def numberToWords(self, num: int) -> str: @@ -113,10 +109,6 @@ class Solution: return ''.join(res).strip() ``` -### **Java** - - - ```java class Solution { private static Map map; @@ -191,47 +183,6 @@ class Solution { } ``` -```java -class Solution { - private String[] lt20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", - "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", - "Seventeen", "Eighteen", "Nineteen"}; - private String[] tens - = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; - private String[] thousands = {"Billion", "Million", "Thousand", ""}; - - public String numberToWords(int num) { - if (num == 0) { - return "Zero"; - } - StringBuilder sb = new StringBuilder(); - for (int i = 1000000000, j = 0; i > 0; i /= 1000, ++j) { - if (num / i == 0) { - continue; - } - sb.append(transfer(num / i)).append(thousands[j]).append(' '); - num %= i; - } - return sb.toString().trim(); - } - - private String transfer(int num) { - if (num == 0) { - return ""; - } - if (num < 20) { - return lt20[num] + " "; - } - if (num < 100) { - return tens[num / 10] + " " + transfer(num % 10); - } - return lt20[num / 100] + " Hundred " + transfer(num % 100); - } -} -``` - -### **C#** - ```cs using System.Collections.Generic; using System.Linq; @@ -323,10 +274,51 @@ public class Solution { } ``` -### **...** + -``` +### 方法二 + + + +```java +class Solution { + private String[] lt20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", + "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", + "Seventeen", "Eighteen", "Nineteen"}; + private String[] tens + = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; + private String[] thousands = {"Billion", "Million", "Thousand", ""}; + public String numberToWords(int num) { + if (num == 0) { + return "Zero"; + } + StringBuilder sb = new StringBuilder(); + for (int i = 1000000000, j = 0; i > 0; i /= 1000, ++j) { + if (num / i == 0) { + continue; + } + sb.append(transfer(num / i)).append(thousands[j]).append(' '); + num %= i; + } + return sb.toString().trim(); + } + + private String transfer(int num) { + if (num == 0) { + return ""; + } + if (num < 20) { + return lt20[num] + " "; + } + if (num < 100) { + return tens[num / 10] + " " + transfer(num % 10); + } + return lt20[num / 100] + " Hundred " + transfer(num % 100); + } +} ``` + + diff --git a/solution/0200-0299/0273.Integer to English Words/README_EN.md b/solution/0200-0299/0273.Integer to English Words/README_EN.md index ddc795672c39c..dda52c8fc8ea0 100644 --- a/solution/0200-0299/0273.Integer to English Words/README_EN.md +++ b/solution/0200-0299/0273.Integer to English Words/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -105,8 +105,6 @@ class Solution: return ''.join(res).strip() ``` -### **Java** - ```java class Solution { private static Map map; @@ -181,47 +179,6 @@ class Solution { } ``` -```java -class Solution { - private String[] lt20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", - "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", - "Seventeen", "Eighteen", "Nineteen"}; - private String[] tens - = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; - private String[] thousands = {"Billion", "Million", "Thousand", ""}; - - public String numberToWords(int num) { - if (num == 0) { - return "Zero"; - } - StringBuilder sb = new StringBuilder(); - for (int i = 1000000000, j = 0; i > 0; i /= 1000, ++j) { - if (num / i == 0) { - continue; - } - sb.append(transfer(num / i)).append(thousands[j]).append(' '); - num %= i; - } - return sb.toString().trim(); - } - - private String transfer(int num) { - if (num == 0) { - return ""; - } - if (num < 20) { - return lt20[num] + " "; - } - if (num < 100) { - return tens[num / 10] + " " + transfer(num % 10); - } - return lt20[num / 100] + " Hundred " + transfer(num % 100); - } -} -``` - -### **C#** - ```cs using System.Collections.Generic; using System.Linq; @@ -313,10 +270,51 @@ public class Solution { } ``` -### **...** + -``` +### Solution 2 + + + +```java +class Solution { + private String[] lt20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", + "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", + "Seventeen", "Eighteen", "Nineteen"}; + private String[] tens + = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; + private String[] thousands = {"Billion", "Million", "Thousand", ""}; + + public String numberToWords(int num) { + if (num == 0) { + return "Zero"; + } + StringBuilder sb = new StringBuilder(); + for (int i = 1000000000, j = 0; i > 0; i /= 1000, ++j) { + if (num / i == 0) { + continue; + } + sb.append(transfer(num / i)).append(thousands[j]).append(' '); + num %= i; + } + return sb.toString().trim(); + } + private String transfer(int num) { + if (num == 0) { + return ""; + } + if (num < 20) { + return lt20[num] + " "; + } + if (num < 100) { + return tens[num / 10] + " " + transfer(num % 10); + } + return lt20[num / 100] + " Hundred " + transfer(num % 100); + } +} ``` + + diff --git a/solution/0200-0299/0274.H-Index/README.md b/solution/0200-0299/0274.H-Index/README.md index 1bb9fdb6b3250..d9d128f6101f6 100644 --- a/solution/0200-0299/0274.H-Index/README.md +++ b/solution/0200-0299/0274.H-Index/README.md @@ -39,36 +39,14 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们可以先对数组 `citations` 按照元素值从大到小进行排序。然后我们从大到小枚举 $h$ 值,如果某个 $h$ 值满足 $citations[h-1] \geq h$,则说明有至少 $h$ 篇论文分别被引用了至少 $h$ 次,直接返回 $h$ 即可。如果没有找到这样的 $h$ 值,说明所有的论文都没有被引用,返回 $0$。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组 `citations` 的长度。 -**方法二:计数 + 求和** - -我们可以使用一个长度为 $n+1$ 的数组 $cnt$,其中 $cnt[i]$ 表示引用次数为 $i$ 的论文的篇数。我们遍历数组 `citations`,将引用次数大于 $n$ 的论文都当作引用次数为 $n$ 的论文,然后将每篇论文的引用次数作为下标,将 $cnt$ 中对应的元素值加 $1$。这样我们就统计出了每个引用次数对应的论文篇数。 - -接下来,我们从大到小枚举 $h$ 值,将 $cnt$ 中下标为 $h$ 的元素值加到变量 $s$ 中,其中 $s$ 表示引用次数大于等于 $h$ 的论文篇数。如果 $s \geq h$,说明至少有 $h$ 篇论文分别被引用了至少 $h$ 次,直接返回 $h$ 即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `citations` 的长度。 - -**方法三:二分查找** - -我们注意到,如果存在一个 $h$ 值满足至少有 $h$ 篇论文至少被引用 $h$ 次,那么对于任意一个 $h' \lt h$,都有至少 $h'$ 篇论文至少被引用 $h'$ 次。因此我们可以使用二分查找的方法,找到最大的 $h$ 值,使得至少有 $h$ 篇论文至少被引用 $h$ 次。 - -我们定义二分查找的左边界 $l=0$,右边界 $r=n$。每次我们取 $mid = \lfloor \frac{l + r + 1}{2} \rfloor$,其中 $\lfloor x \rfloor$ 表示对 $x$ 向下取整。然后我们统计数组 `citations` 中大于等于 $mid$ 的元素的个数,记为 $s$。如果 $s \geq mid$,说明至少有 $mid$ 篇论文至少被引用 $mid$ 次,此时我们将左边界 $l$ 变为 $mid$,否则我们将右边界 $r$ 变为 $mid-1$。当左边界 $l$ 等于右边界 $r$ 时,我们找到了最大的 $h$ 值,即为 $l$ 或 $r$。 - -时间复杂度 $O(n \times \log n)$,其中 $n$ 是数组 `citations` 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def hIndex(self, citations: List[int]) -> int: @@ -79,6 +57,93 @@ class Solution: return 0 ``` +```java +class Solution { + public int hIndex(int[] citations) { + Arrays.sort(citations); + int n = citations.length; + for (int h = n; h > 0; --h) { + if (citations[n - h] >= h) { + return h; + } + } + return 0; + } +} +``` + +```cpp +class Solution { +public: + int hIndex(vector& citations) { + sort(citations.rbegin(), citations.rend()); + for (int h = citations.size(); h; --h) { + if (citations[h - 1] >= h) { + return h; + } + } + return 0; + } +}; +``` + +```go +func hIndex(citations []int) int { + sort.Ints(citations) + n := len(citations) + for h := n; h > 0; h-- { + if citations[n-h] >= h { + return h + } + } + return 0 +} +``` + +```ts +function hIndex(citations: number[]): number { + citations.sort((a, b) => b - a); + for (let h = citations.length; h; --h) { + if (citations[h - 1] >= h) { + return h; + } + } + return 0; +} +``` + +```rust +impl Solution { + #[allow(dead_code)] + pub fn h_index(citations: Vec) -> i32 { + let mut citations = citations; + citations.sort_by(|&lhs, &rhs| { rhs.cmp(&lhs) }); + + let n = citations.len(); + + for i in (1..=n).rev() { + if citations[i - 1] >= (i as i32) { + return i as i32; + } + } + + 0 + } +} +``` + + + +### 方法二:计数 + 求和 + +我们可以使用一个长度为 $n+1$ 的数组 $cnt$,其中 $cnt[i]$ 表示引用次数为 $i$ 的论文的篇数。我们遍历数组 `citations`,将引用次数大于 $n$ 的论文都当作引用次数为 $n$ 的论文,然后将每篇论文的引用次数作为下标,将 $cnt$ 中对应的元素值加 $1$。这样我们就统计出了每个引用次数对应的论文篇数。 + +接下来,我们从大到小枚举 $h$ 值,将 $cnt$ 中下标为 $h$ 的元素值加到变量 $s$ 中,其中 $s$ 表示引用次数大于等于 $h$ 的论文篇数。如果 $s \geq h$,说明至少有 $h$ 篇论文分别被引用了至少 $h$ 次,直接返回 $h$ 即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `citations` 的长度。 + + + ```python class Solution: def hIndex(self, citations: List[int]) -> int: @@ -93,45 +158,33 @@ class Solution: return h ``` -```python -class Solution: - def hIndex(self, citations: List[int]) -> int: - l, r = 0, len(citations) - while l < r: - mid = (l + r + 1) >> 1 - if sum(x >= mid for x in citations) >= mid: - l = mid - else: - r = mid - 1 - return l -``` - -### **Java** - - - ```java class Solution { public int hIndex(int[] citations) { - Arrays.sort(citations); int n = citations.length; - for (int h = n; h > 0; --h) { - if (citations[n - h] >= h) { + int[] cnt = new int[n + 1]; + for (int x : citations) { + ++cnt[Math.min(x, n)]; + } + for (int h = n, s = 0;; --h) { + s += cnt[h]; + if (s >= h) { return h; } } - return 0; } } ``` -```java +```cpp class Solution { - public int hIndex(int[] citations) { - int n = citations.length; - int[] cnt = new int[n + 1]; +public: + int hIndex(vector& citations) { + int n = citations.size(); + int cnt[n + 1]; + memset(cnt, 0, sizeof(cnt)); for (int x : citations) { - ++cnt[Math.min(x, n)]; + ++cnt[min(x, n)]; } for (int h = n, s = 0;; --h) { s += cnt[h]; @@ -140,9 +193,66 @@ class Solution { } } } +}; +``` + +```go +func hIndex(citations []int) int { + n := len(citations) + cnt := make([]int, n+1) + for _, x := range citations { + cnt[min(x, n)]++ + } + for h, s := n, 0; ; h-- { + s += cnt[h] + if s >= h { + return h + } + } } ``` +```ts +function hIndex(citations: number[]): number { + const n: number = citations.length; + const cnt: number[] = new Array(n + 1).fill(0); + for (const x of citations) { + ++cnt[Math.min(x, n)]; + } + for (let h = n, s = 0; ; --h) { + s += cnt[h]; + if (s >= h) { + return h; + } + } +} +``` + + + +### 方法三:二分查找 + +我们注意到,如果存在一个 $h$ 值满足至少有 $h$ 篇论文至少被引用 $h$ 次,那么对于任意一个 $h' \lt h$,都有至少 $h'$ 篇论文至少被引用 $h'$ 次。因此我们可以使用二分查找的方法,找到最大的 $h$ 值,使得至少有 $h$ 篇论文至少被引用 $h$ 次。 + +我们定义二分查找的左边界 $l=0$,右边界 $r=n$。每次我们取 $mid = \lfloor \frac{l + r + 1}{2} \rfloor$,其中 $\lfloor x \rfloor$ 表示对 $x$ 向下取整。然后我们统计数组 `citations` 中大于等于 $mid$ 的元素的个数,记为 $s$。如果 $s \geq mid$,说明至少有 $mid$ 篇论文至少被引用 $mid$ 次,此时我们将左边界 $l$ 变为 $mid$,否则我们将右边界 $r$ 变为 $mid-1$。当左边界 $l$ 等于右边界 $r$ 时,我们找到了最大的 $h$ 值,即为 $l$ 或 $r$。 + +时间复杂度 $O(n \times \log n)$,其中 $n$ 是数组 `citations` 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def hIndex(self, citations: List[int]) -> int: + l, r = 0, len(citations) + while l < r: + mid = (l + r + 1) >> 1 + if sum(x >= mid for x in citations) >= mid: + l = mid + else: + r = mid - 1 + return l +``` + ```java class Solution { public int hIndex(int[] citations) { @@ -166,43 +276,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int hIndex(vector& citations) { - sort(citations.rbegin(), citations.rend()); - for (int h = citations.size(); h; --h) { - if (citations[h - 1] >= h) { - return h; - } - } - return 0; - } -}; -``` - -```cpp -class Solution { -public: - int hIndex(vector& citations) { - int n = citations.size(); - int cnt[n + 1]; - memset(cnt, 0, sizeof(cnt)); - for (int x : citations) { - ++cnt[min(x, n)]; - } - for (int h = n, s = 0;; --h) { - s += cnt[h]; - if (s >= h) { - return h; - } - } - } -}; -``` - ```cpp class Solution { public: @@ -227,59 +300,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn h_index(citations: Vec) -> i32 { - let mut citations = citations; - citations.sort_by(|&lhs, &rhs| { rhs.cmp(&lhs) }); - - let n = citations.len(); - - for i in (1..=n).rev() { - if citations[i - 1] >= (i as i32) { - return i as i32; - } - } - - 0 - } -} -``` - -### **Go** - -```go -func hIndex(citations []int) int { - sort.Ints(citations) - n := len(citations) - for h := n; h > 0; h-- { - if citations[n-h] >= h { - return h - } - } - return 0 -} -``` - -```go -func hIndex(citations []int) int { - n := len(citations) - cnt := make([]int, n+1) - for _, x := range citations { - cnt[min(x, n)]++ - } - for h, s := n, 0; ; h-- { - s += cnt[h] - if s >= h { - return h - } - } -} -``` - ```go func hIndex(citations []int) int { l, r := 0, len(citations) @@ -301,36 +321,6 @@ func hIndex(citations []int) int { } ``` -### **TypeScript** - -```ts -function hIndex(citations: number[]): number { - citations.sort((a, b) => b - a); - for (let h = citations.length; h; --h) { - if (citations[h - 1] >= h) { - return h; - } - } - return 0; -} -``` - -```ts -function hIndex(citations: number[]): number { - const n: number = citations.length; - const cnt: number[] = new Array(n + 1).fill(0); - for (const x of citations) { - ++cnt[Math.min(x, n)]; - } - for (let h = n, s = 0; ; --h) { - s += cnt[h]; - if (s >= h) { - return h; - } - } -} -``` - ```ts function hIndex(citations: number[]): number { let l = 0; @@ -353,10 +343,6 @@ function hIndex(citations: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0274.H-Index/README_EN.md b/solution/0200-0299/0274.H-Index/README_EN.md index 89844fc110084..ee06292ca42ae 100644 --- a/solution/0200-0299/0274.H-Index/README_EN.md +++ b/solution/0200-0299/0274.H-Index/README_EN.md @@ -36,32 +36,14 @@ Since the researcher has 3 papers with at least 3 citations each and the remaini ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting We can sort the array `citations` in descending order. Then we enumerate the value $h$ from large to small, if there is an $h$ value satisfying $citations[h-1] \geq h$, it means that there are at least $h$ papers that have been cited at least $h$ times, just return $h$ directly. If we cannot find such an $h$ value, it means that all the papers have not been cited, return $0$. Time complexity $O(n \times \log n)$, space complexity $O(\log n)$. Here $n$ is the length of the array `citations`. -**Solution 2: Counting + Sum** - -We can use an array $cnt$ of length $n+1$, where $cnt[i]$ represents the number of papers with the reference count of $i$. We traverse the array `citations` and treat the papers with the reference count greater than $n$ as papers with a reference count of $n$. Then we use the reference count as the index and add $1$ to the corresponding element of $cnt$ for each paper. In this way, we have counted the number of papers for each reference count. - -Then we enumerate the value $h$ from large to small, and add the element value of $cnt$ with the index of $h$ to the variable $s$, where $s$ represents the number of papers with a reference count greater than or equal to $h$. If $s \geq h$, it means that at least $h$ papers have been cited at least $h$ times, just return $h$ directly. - -Time complexity $O(n)$, space complexity $O(n)$. Here $n$ is the length of the array `citations`. - -**Solution 3: Binary Search** - -We notice that if there is a $h$ value that satisfies at least $h$ papers are cited at least $h$ times, then for any $h' -### **Python3** - ```python class Solution: def hIndex(self, citations: List[int]) -> int: @@ -72,6 +54,93 @@ class Solution: return 0 ``` +```java +class Solution { + public int hIndex(int[] citations) { + Arrays.sort(citations); + int n = citations.length; + for (int h = n; h > 0; --h) { + if (citations[n - h] >= h) { + return h; + } + } + return 0; + } +} +``` + +```cpp +class Solution { +public: + int hIndex(vector& citations) { + sort(citations.rbegin(), citations.rend()); + for (int h = citations.size(); h; --h) { + if (citations[h - 1] >= h) { + return h; + } + } + return 0; + } +}; +``` + +```go +func hIndex(citations []int) int { + sort.Ints(citations) + n := len(citations) + for h := n; h > 0; h-- { + if citations[n-h] >= h { + return h + } + } + return 0 +} +``` + +```ts +function hIndex(citations: number[]): number { + citations.sort((a, b) => b - a); + for (let h = citations.length; h; --h) { + if (citations[h - 1] >= h) { + return h; + } + } + return 0; +} +``` + +```rust +impl Solution { + #[allow(dead_code)] + pub fn h_index(citations: Vec) -> i32 { + let mut citations = citations; + citations.sort_by(|&lhs, &rhs| { rhs.cmp(&lhs) }); + + let n = citations.len(); + + for i in (1..=n).rev() { + if citations[i - 1] >= (i as i32) { + return i as i32; + } + } + + 0 + } +} +``` + + + +### Solution 2: Counting + Sum + +We can use an array $cnt$ of length $n+1$, where $cnt[i]$ represents the number of papers with the reference count of $i$. We traverse the array `citations` and treat the papers with the reference count greater than $n$ as papers with a reference count of $n$. Then we use the reference count as the index and add $1$ to the corresponding element of $cnt$ for each paper. In this way, we have counted the number of papers for each reference count. + +Then we enumerate the value $h$ from large to small, and add the element value of $cnt$ with the index of $h$ to the variable $s$, where $s$ represents the number of papers with a reference count greater than or equal to $h$. If $s \geq h$, it means that at least $h$ papers have been cited at least $h$ times, just return $h$ directly. + +Time complexity $O(n)$, space complexity $O(n)$. Here $n$ is the length of the array `citations`. + + + ```python class Solution: def hIndex(self, citations: List[int]) -> int: @@ -86,43 +155,33 @@ class Solution: return h ``` -```python -class Solution: - def hIndex(self, citations: List[int]) -> int: - l, r = 0, len(citations) - while l < r: - mid = (l + r + 1) >> 1 - if sum(x >= mid for x in citations) >= mid: - l = mid - else: - r = mid - 1 - return l -``` - -### **Java** - ```java class Solution { public int hIndex(int[] citations) { - Arrays.sort(citations); int n = citations.length; - for (int h = n; h > 0; --h) { - if (citations[n - h] >= h) { + int[] cnt = new int[n + 1]; + for (int x : citations) { + ++cnt[Math.min(x, n)]; + } + for (int h = n, s = 0;; --h) { + s += cnt[h]; + if (s >= h) { return h; } } - return 0; } } ``` -```java +```cpp class Solution { - public int hIndex(int[] citations) { - int n = citations.length; - int[] cnt = new int[n + 1]; +public: + int hIndex(vector& citations) { + int n = citations.size(); + int cnt[n + 1]; + memset(cnt, 0, sizeof(cnt)); for (int x : citations) { - ++cnt[Math.min(x, n)]; + ++cnt[min(x, n)]; } for (int h = n, s = 0;; --h) { s += cnt[h]; @@ -131,9 +190,66 @@ class Solution { } } } +}; +``` + +```go +func hIndex(citations []int) int { + n := len(citations) + cnt := make([]int, n+1) + for _, x := range citations { + cnt[min(x, n)]++ + } + for h, s := n, 0; ; h-- { + s += cnt[h] + if s >= h { + return h + } + } +} +``` + +```ts +function hIndex(citations: number[]): number { + const n: number = citations.length; + const cnt: number[] = new Array(n + 1).fill(0); + for (const x of citations) { + ++cnt[Math.min(x, n)]; + } + for (let h = n, s = 0; ; --h) { + s += cnt[h]; + if (s >= h) { + return h; + } + } } ``` + + +### Solution 3: Binary Search + +We notice that if there is a $h$ value that satisfies at least $h$ papers are cited at least $h$ times, then for any $h' + +```python +class Solution: + def hIndex(self, citations: List[int]) -> int: + l, r = 0, len(citations) + while l < r: + mid = (l + r + 1) >> 1 + if sum(x >= mid for x in citations) >= mid: + l = mid + else: + r = mid - 1 + return l +``` + ```java class Solution { public int hIndex(int[] citations) { @@ -157,43 +273,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int hIndex(vector& citations) { - sort(citations.rbegin(), citations.rend()); - for (int h = citations.size(); h; --h) { - if (citations[h - 1] >= h) { - return h; - } - } - return 0; - } -}; -``` - -```cpp -class Solution { -public: - int hIndex(vector& citations) { - int n = citations.size(); - int cnt[n + 1]; - memset(cnt, 0, sizeof(cnt)); - for (int x : citations) { - ++cnt[min(x, n)]; - } - for (int h = n, s = 0;; --h) { - s += cnt[h]; - if (s >= h) { - return h; - } - } - } -}; -``` - ```cpp class Solution { public: @@ -218,59 +297,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn h_index(citations: Vec) -> i32 { - let mut citations = citations; - citations.sort_by(|&lhs, &rhs| { rhs.cmp(&lhs) }); - - let n = citations.len(); - - for i in (1..=n).rev() { - if citations[i - 1] >= (i as i32) { - return i as i32; - } - } - - 0 - } -} -``` - -### **Go** - -```go -func hIndex(citations []int) int { - sort.Ints(citations) - n := len(citations) - for h := n; h > 0; h-- { - if citations[n-h] >= h { - return h - } - } - return 0 -} -``` - -```go -func hIndex(citations []int) int { - n := len(citations) - cnt := make([]int, n+1) - for _, x := range citations { - cnt[min(x, n)]++ - } - for h, s := n, 0; ; h-- { - s += cnt[h] - if s >= h { - return h - } - } -} -``` - ```go func hIndex(citations []int) int { l, r := 0, len(citations) @@ -292,36 +318,6 @@ func hIndex(citations []int) int { } ``` -### **TypeScript** - -```ts -function hIndex(citations: number[]): number { - citations.sort((a, b) => b - a); - for (let h = citations.length; h; --h) { - if (citations[h - 1] >= h) { - return h; - } - } - return 0; -} -``` - -```ts -function hIndex(citations: number[]): number { - const n: number = citations.length; - const cnt: number[] = new Array(n + 1).fill(0); - for (const x of citations) { - ++cnt[Math.min(x, n)]; - } - for (let h = n, s = 0; ; --h) { - s += cnt[h]; - if (s >= h) { - return h; - } - } -} -``` - ```ts function hIndex(citations: number[]): number { let l = 0; @@ -344,10 +340,6 @@ function hIndex(citations: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0275.H-Index II/README.md b/solution/0200-0299/0275.H-Index II/README.md index 6dcc09335081f..e3d4b23242da9 100644 --- a/solution/0200-0299/0275.H-Index II/README.md +++ b/solution/0200-0299/0275.H-Index II/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们注意到,如果有至少 $x$ 篇论文的引用次数大于等于 $x$,那么对于任意 $y \lt x$,其引用次数也一定大于等于 $y$。这存在着单调性。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def hIndex(self, citations: List[int]) -> int: @@ -72,10 +66,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int hIndex(int[] citations) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func hIndex(citations []int) int { n := len(citations) @@ -132,7 +118,22 @@ func hIndex(citations []int) int { } ``` -### **Rust** +```ts +function hIndex(citations: number[]): number { + const n = citations.length; + let left = 0, + right = n; + while (left < right) { + const mid = (left + right + 1) >> 1; + if (citations[n - mid] >= mid) { + left = mid; + } else { + right = mid - 1; + } + } + return left; +} +``` ```rust impl Solution { @@ -152,27 +153,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function hIndex(citations: number[]): number { - const n = citations.length; - let left = 0, - right = n; - while (left < right) { - const mid = (left + right + 1) >> 1; - if (citations[n - mid] >= mid) { - left = mid; - } else { - right = mid - 1; - } - } - return left; -} -``` - -### **C#** - ```cs public class Solution { public int HIndex(int[] citations) { @@ -191,10 +171,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0275.H-Index II/README_EN.md b/solution/0200-0299/0275.H-Index II/README_EN.md index fee1adb4f8ccd..75717b8e75fa8 100644 --- a/solution/0200-0299/0275.H-Index II/README_EN.md +++ b/solution/0200-0299/0275.H-Index II/README_EN.md @@ -39,7 +39,7 @@ Since the researcher has 3 papers with at least 3 citations each and the remaini ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search We notice that if there are at least $x$ papers with citation counts greater than or equal to $x$, then for any $y \lt x$, its citation count must also be greater than or equal to $y$. This exhibits monotonicity. @@ -49,8 +49,6 @@ The time complexity is $O(\log n)$, where $n$ is the length of the array $citati -### **Python3** - ```python class Solution: def hIndex(self, citations: List[int]) -> int: @@ -65,28 +63,24 @@ class Solution: return left ``` -### **Java** - ```java class Solution { public int hIndex(int[] citations) { int n = citations.length; int left = 0, right = n; while (left < right) { - int mid = (left + right + 1) >> 1; - if (citations[n - mid] >= mid) { - left = mid; + int mid = (left + right) >>> 1; + if (citations[mid] >= n - mid) { + right = mid; } else { - right = mid - 1; + left = mid + 1; } } - return left; + return n - left; } } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +99,6 @@ public: }; ``` -### **Go** - ```go func hIndex(citations []int) int { n := len(citations) @@ -123,7 +115,22 @@ func hIndex(citations []int) int { } ``` -### **Rust** +```ts +function hIndex(citations: number[]): number { + const n = citations.length; + let left = 0, + right = n; + while (left < right) { + const mid = (left + right + 1) >> 1; + if (citations[n - mid] >= mid) { + left = mid; + } else { + right = mid - 1; + } + } + return left; +} +``` ```rust impl Solution { @@ -143,27 +150,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function hIndex(citations: number[]): number { - const n = citations.length; - let left = 0, - right = n; - while (left < right) { - const mid = (left + right + 1) >> 1; - if (citations[n - mid] >= mid) { - left = mid; - } else { - right = mid - 1; - } - } - return left; -} -``` - -### **C#** - ```cs public class Solution { public int HIndex(int[] citations) { @@ -182,10 +168,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0276.Paint Fence/README.md b/solution/0200-0299/0276.Paint Fence/README.md index e02ac2f8d1d4c..273ab04f8aa97 100644 --- a/solution/0200-0299/0276.Paint Fence/README.md +++ b/solution/0200-0299/0276.Paint Fence/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 定义 $dp[i][0]$ 表示栅栏 $[0,..i]$ 且最后两个栅栏颜色不同的方案数,$dp[i][1]$ 表示栅栏 $[0,..i]$ 且最后两个栅栏颜色相同的方案数。 @@ -72,10 +70,6 @@ $$ -### **Python3** - - - ```python class Solution: def numWays(self, n: int, k: int) -> int: @@ -87,10 +81,6 @@ class Solution: return sum(dp[-1]) ``` -### **Java** - - - ```java class Solution { public int numWays(int n, int k) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func numWays(n int, k int) int { dp := make([][]int, n) @@ -139,10 +125,6 @@ func numWays(n int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0276.Paint Fence/README_EN.md b/solution/0200-0299/0276.Paint Fence/README_EN.md index ce83cfe55a84b..891ec83630a55 100644 --- a/solution/0200-0299/0276.Paint Fence/README_EN.md +++ b/solution/0200-0299/0276.Paint Fence/README_EN.md @@ -48,9 +48,9 @@ Note that painting all the posts red or all the posts green is invalid because t ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return sum(dp[-1]) ``` -### **Java** - ```java class Solution { public int numWays(int n, int k) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func numWays(n int, k int) int { dp := make([][]int, n) @@ -113,10 +107,6 @@ func numWays(n int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0277.Find the Celebrity/README.md b/solution/0200-0299/0277.Find the Celebrity/README.md index 2215f4605f7ad..d6320d6c03ef3 100644 --- a/solution/0200-0299/0277.Find the Celebrity/README.md +++ b/solution/0200-0299/0277.Find the Celebrity/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:O(n) 遍历** +### 方法一:O(n) 遍历 经过验证,若暴力遍历,调用 $O(n^2)$ 次 $knows$ 方法,会报 TLE 错误。因此,我们需要寻找更优的解法。 @@ -106,10 +104,6 @@ ans = 6 -### **Python3** - - - ```python # The knows API is already defined for you. # return a bool, whether a knows b @@ -129,10 +123,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ @@ -157,8 +147,6 @@ public class Solution extends Relation { } ``` -### **C++** - ```cpp /* The knows API is defined for you. bool knows(int a, int b); */ @@ -184,8 +172,6 @@ public: }; ``` -### **Go** - ```go /** * The knows API is already defined for you. @@ -211,10 +197,6 @@ func solution(knows func(a int, b int) bool) func(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0277.Find the Celebrity/README_EN.md b/solution/0200-0299/0277.Find the Celebrity/README_EN.md index 8c71a4f1d1f0d..a9c922d4fe181 100644 --- a/solution/0200-0299/0277.Find the Celebrity/README_EN.md +++ b/solution/0200-0299/0277.Find the Celebrity/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # The knows API is already defined for you. @@ -67,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java /* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ @@ -93,8 +91,6 @@ public class Solution extends Relation { } ``` -### **C++** - ```cpp /* The knows API is defined for you. bool knows(int a, int b); */ @@ -120,8 +116,6 @@ public: }; ``` -### **Go** - ```go /** * The knows API is already defined for you. @@ -147,10 +141,6 @@ func solution(knows func(a int, b int) bool) func(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0278.First Bad Version/README.md b/solution/0200-0299/0278.First Bad Version/README.md index cde8ed288128b..6c7873db6b342 100644 --- a/solution/0200-0299/0278.First Bad Version/README.md +++ b/solution/0200-0299/0278.First Bad Version/README.md @@ -42,16 +42,10 @@ ## 解法 - - -二分查找。 +### 方法一 -### **Python3** - - - ```python # The isBadVersion API is already defined for you. # @param version, an integer @@ -75,10 +69,6 @@ class Solution: return left ``` -### **Java** - - - ```java /* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */ @@ -99,8 +89,6 @@ public class Solution extends VersionControl { } ``` -### **C++** - ```cpp // The API isBadVersion is defined for you. // bool isBadVersion(int version); @@ -122,46 +110,6 @@ public: }; ``` -### **JavaScript** - -```js -/** - * Definition for isBadVersion() - * - * @param {integer} version number - * @return {boolean} whether the version is bad - * isBadVersion = function(version) { - * ... - * }; - */ - -/** - * @param {function} isBadVersion() - * @return {function} - */ -var solution = function (isBadVersion) { - /** - * @param {integer} n Total versions - * @return {integer} The first bad version - */ - return function (n) { - let left = 1; - let right = n; - while (left < right) { - const mid = (left + right) >>> 1; - if (isBadVersion(mid)) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - }; -}; -``` - -### **Go** - ```go /** * Forward declaration of isBadVersion API. @@ -185,8 +133,6 @@ func firstBadVersion(n int) int { } ``` -### **Rust** - ```rust // The API isBadVersion is defined for you. // isBadVersion(version:i32)-> bool; @@ -209,10 +155,42 @@ impl Solution { } ``` -### **...** - -``` +```js +/** + * Definition for isBadVersion() + * + * @param {integer} version number + * @return {boolean} whether the version is bad + * isBadVersion = function(version) { + * ... + * }; + */ +/** + * @param {function} isBadVersion() + * @return {function} + */ +var solution = function (isBadVersion) { + /** + * @param {integer} n Total versions + * @return {integer} The first bad version + */ + return function (n) { + let left = 1; + let right = n; + while (left < right) { + const mid = (left + right) >>> 1; + if (isBadVersion(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + }; +}; ``` + + diff --git a/solution/0200-0299/0278.First Bad Version/README_EN.md b/solution/0200-0299/0278.First Bad Version/README_EN.md index 72428326c5e6e..f04c8e6562d28 100644 --- a/solution/0200-0299/0278.First Bad Version/README_EN.md +++ b/solution/0200-0299/0278.First Bad Version/README_EN.md @@ -39,9 +39,9 @@ Then 4 is the first bad version. ## Solutions - +### Solution 1 -### **Python3** + ```python # The isBadVersion API is already defined for you. @@ -66,8 +66,6 @@ class Solution: return left ``` -### **Java** - ```java /* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */ @@ -88,8 +86,6 @@ public class Solution extends VersionControl { } ``` -### **C++** - ```cpp // The API isBadVersion is defined for you. // bool isBadVersion(int version); @@ -111,46 +107,6 @@ public: }; ``` -### **JavaScript** - -```js -/** - * Definition for isBadVersion() - * - * @param {integer} version number - * @return {boolean} whether the version is bad - * isBadVersion = function(version) { - * ... - * }; - */ - -/** - * @param {function} isBadVersion() - * @return {function} - */ -var solution = function (isBadVersion) { - /** - * @param {integer} n Total versions - * @return {integer} The first bad version - */ - return function (n) { - let left = 1; - let right = n; - while (left < right) { - const mid = (left + right) >>> 1; - if (isBadVersion(mid)) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - }; -}; -``` - -### **Go** - ```go /** * Forward declaration of isBadVersion API. @@ -174,8 +130,6 @@ func firstBadVersion(n int) int { } ``` -### **Rust** - ```rust // The API isBadVersion is defined for you. // isBadVersion(version:i32)-> bool; @@ -198,10 +152,42 @@ impl Solution { } ``` -### **...** - -``` +```js +/** + * Definition for isBadVersion() + * + * @param {integer} version number + * @return {boolean} whether the version is bad + * isBadVersion = function(version) { + * ... + * }; + */ +/** + * @param {function} isBadVersion() + * @return {function} + */ +var solution = function (isBadVersion) { + /** + * @param {integer} n Total versions + * @return {integer} The first bad version + */ + return function (n) { + let left = 1; + let right = n; + while (left < right) { + const mid = (left + right) >>> 1; + if (isBadVersion(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + }; +}; ``` + + diff --git a/solution/0200-0299/0279.Perfect Squares/README.md b/solution/0200-0299/0279.Perfect Squares/README.md index a13f6d7664456..7f47ce141622d 100644 --- a/solution/0200-0299/0279.Perfect Squares/README.md +++ b/solution/0200-0299/0279.Perfect Squares/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:动态规划(完全背包)** +### 方法一:动态规划(完全背包) 我们定义 $f[i][j]$ 表示使用数字 $1, 2, \cdots, i$ 的完全平方数组成和为 $j$ 的最少数量。初始时 $f[0][0] = 0$,其余位置的值均为正无穷。 @@ -74,10 +72,6 @@ $$ -### **Python3** - - - ```python class Solution: def numSquares(self, n: int) -> int: @@ -92,21 +86,6 @@ class Solution: return f[m][n] ``` -```python -class Solution: - def numSquares(self, n: int) -> int: - m = int(sqrt(n)) - f = [0] + [inf] * n - for i in range(1, m + 1): - for j in range(i * i, n + 1): - f[j] = min(f[j], f[j - i * i] + 1) - return f[n] -``` - -### **Java** - - - ```java class Solution { public int numSquares(int n) { @@ -129,25 +108,6 @@ class Solution { } ``` -```java -class Solution { - public int numSquares(int n) { - int m = (int) Math.sqrt(n); - int[] f = new int[n + 1]; - Arrays.fill(f, 1 << 30); - f[0] = 0; - for (int i = 1; i <= m; ++i) { - for (int j = i * i; j <= n; ++j) { - f[j] = Math.min(f[j], f[j - i * i] + 1); - } - } - return f[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -169,26 +129,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numSquares(int n) { - int m = sqrt(n); - int f[n + 1]; - memset(f, 0x3f, sizeof(f)); - f[0] = 0; - for (int i = 1; i <= m; ++i) { - for (int j = i * i; j <= n; ++j) { - f[j] = min(f[j], f[j - i * i] + 1); - } - } - return f[n]; - } -}; -``` - -### **Go** - ```go func numSquares(n int) int { m := int(math.Sqrt(float64(n))) @@ -213,25 +153,6 @@ func numSquares(n int) int { } ``` -```go -func numSquares(n int) int { - m := int(math.Sqrt(float64(n))) - f := make([]int, n+1) - for i := range f { - f[i] = 1 << 30 - } - f[0] = 0 - for i := 1; i <= m; i++ { - for j := i * i; j <= n; j++ { - f[j] = min(f[j], f[j-i*i]+1) - } - } - return f[n] -} -``` - -### **TypeScript** - ```ts function numSquares(n: number): number { const m = Math.floor(Math.sqrt(n)); @@ -251,22 +172,6 @@ function numSquares(n: number): number { } ``` -```ts -function numSquares(n: number): number { - const m = Math.floor(Math.sqrt(n)); - const f: number[] = Array(n + 1).fill(1 << 30); - f[0] = 0; - for (let i = 1; i <= m; ++i) { - for (let j = i * i; j <= n; ++j) { - f[j] = Math.min(f[j], f[j - i * i] + 1); - } - } - return f[n]; -} -``` - -### **Rust** - ```rust impl Solution { pub fn num_squares(n: i32) -> i32 { @@ -286,6 +191,89 @@ impl Solution { } ``` + + +### 方法二 + + + +```python +class Solution: + def numSquares(self, n: int) -> int: + m = int(sqrt(n)) + f = [0] + [inf] * n + for i in range(1, m + 1): + for j in range(i * i, n + 1): + f[j] = min(f[j], f[j - i * i] + 1) + return f[n] +``` + +```java +class Solution { + public int numSquares(int n) { + int m = (int) Math.sqrt(n); + int[] f = new int[n + 1]; + Arrays.fill(f, 1 << 30); + f[0] = 0; + for (int i = 1; i <= m; ++i) { + for (int j = i * i; j <= n; ++j) { + f[j] = Math.min(f[j], f[j - i * i] + 1); + } + } + return f[n]; + } +} +``` + +```cpp +class Solution { +public: + int numSquares(int n) { + int m = sqrt(n); + int f[n + 1]; + memset(f, 0x3f, sizeof(f)); + f[0] = 0; + for (int i = 1; i <= m; ++i) { + for (int j = i * i; j <= n; ++j) { + f[j] = min(f[j], f[j - i * i] + 1); + } + } + return f[n]; + } +}; +``` + +```go +func numSquares(n int) int { + m := int(math.Sqrt(float64(n))) + f := make([]int, n+1) + for i := range f { + f[i] = 1 << 30 + } + f[0] = 0 + for i := 1; i <= m; i++ { + for j := i * i; j <= n; j++ { + f[j] = min(f[j], f[j-i*i]+1) + } + } + return f[n] +} +``` + +```ts +function numSquares(n: number): number { + const m = Math.floor(Math.sqrt(n)); + const f: number[] = Array(n + 1).fill(1 << 30); + f[0] = 0; + for (let i = 1; i <= m; ++i) { + for (let j = i * i; j <= n; ++j) { + f[j] = Math.min(f[j], f[j - i * i] + 1); + } + } + return f[n]; +} +``` + ```rust impl Solution { pub fn num_squares(n: i32) -> i32 { @@ -302,10 +290,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0279.Perfect Squares/README_EN.md b/solution/0200-0299/0279.Perfect Squares/README_EN.md index ca0420f3dc141..6b7d7b6411188 100644 --- a/solution/0200-0299/0279.Perfect Squares/README_EN.md +++ b/solution/0200-0299/0279.Perfect Squares/README_EN.md @@ -34,12 +34,10 @@ ## Solutions -For dynamic programming, define `dp[i]` to represent the least number of perfect square numbers that sum to `i`. +### Solution 1 -### **Python3** - ```python class Solution: def numSquares(self, n: int) -> int: @@ -54,19 +52,6 @@ class Solution: return f[m][n] ``` -```python -class Solution: - def numSquares(self, n: int) -> int: - m = int(sqrt(n)) - f = [0] + [inf] * n - for i in range(1, m + 1): - for j in range(i * i, n + 1): - f[j] = min(f[j], f[j - i * i] + 1) - return f[n] -``` - -### **Java** - ```java class Solution { public int numSquares(int n) { @@ -89,25 +74,6 @@ class Solution { } ``` -```java -class Solution { - public int numSquares(int n) { - int m = (int) Math.sqrt(n); - int[] f = new int[n + 1]; - Arrays.fill(f, 1 << 30); - f[0] = 0; - for (int i = 1; i <= m; ++i) { - for (int j = i * i; j <= n; ++j) { - f[j] = Math.min(f[j], f[j - i * i] + 1); - } - } - return f[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -129,26 +95,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numSquares(int n) { - int m = sqrt(n); - int f[n + 1]; - memset(f, 0x3f, sizeof(f)); - f[0] = 0; - for (int i = 1; i <= m; ++i) { - for (int j = i * i; j <= n; ++j) { - f[j] = min(f[j], f[j - i * i] + 1); - } - } - return f[n]; - } -}; -``` - -### **Go** - ```go func numSquares(n int) int { m := int(math.Sqrt(float64(n))) @@ -173,25 +119,6 @@ func numSquares(n int) int { } ``` -```go -func numSquares(n int) int { - m := int(math.Sqrt(float64(n))) - f := make([]int, n+1) - for i := range f { - f[i] = 1 << 30 - } - f[0] = 0 - for i := 1; i <= m; i++ { - for j := i * i; j <= n; j++ { - f[j] = min(f[j], f[j-i*i]+1) - } - } - return f[n] -} -``` - -### **TypeScript** - ```ts function numSquares(n: number): number { const m = Math.floor(Math.sqrt(n)); @@ -211,22 +138,6 @@ function numSquares(n: number): number { } ``` -```ts -function numSquares(n: number): number { - const m = Math.floor(Math.sqrt(n)); - const f: number[] = Array(n + 1).fill(1 << 30); - f[0] = 0; - for (let i = 1; i <= m; ++i) { - for (let j = i * i; j <= n; ++j) { - f[j] = Math.min(f[j], f[j - i * i] + 1); - } - } - return f[n]; -} -``` - -### **Rust** - ```rust impl Solution { pub fn num_squares(n: i32) -> i32 { @@ -246,6 +157,89 @@ impl Solution { } ``` + + +### Solution 2 + + + +```python +class Solution: + def numSquares(self, n: int) -> int: + m = int(sqrt(n)) + f = [0] + [inf] * n + for i in range(1, m + 1): + for j in range(i * i, n + 1): + f[j] = min(f[j], f[j - i * i] + 1) + return f[n] +``` + +```java +class Solution { + public int numSquares(int n) { + int m = (int) Math.sqrt(n); + int[] f = new int[n + 1]; + Arrays.fill(f, 1 << 30); + f[0] = 0; + for (int i = 1; i <= m; ++i) { + for (int j = i * i; j <= n; ++j) { + f[j] = Math.min(f[j], f[j - i * i] + 1); + } + } + return f[n]; + } +} +``` + +```cpp +class Solution { +public: + int numSquares(int n) { + int m = sqrt(n); + int f[n + 1]; + memset(f, 0x3f, sizeof(f)); + f[0] = 0; + for (int i = 1; i <= m; ++i) { + for (int j = i * i; j <= n; ++j) { + f[j] = min(f[j], f[j - i * i] + 1); + } + } + return f[n]; + } +}; +``` + +```go +func numSquares(n int) int { + m := int(math.Sqrt(float64(n))) + f := make([]int, n+1) + for i := range f { + f[i] = 1 << 30 + } + f[0] = 0 + for i := 1; i <= m; i++ { + for j := i * i; j <= n; j++ { + f[j] = min(f[j], f[j-i*i]+1) + } + } + return f[n] +} +``` + +```ts +function numSquares(n: number): number { + const m = Math.floor(Math.sqrt(n)); + const f: number[] = Array(n + 1).fill(1 << 30); + f[0] = 0; + for (let i = 1; i <= m; ++i) { + for (let j = i * i; j <= n; ++j) { + f[j] = Math.min(f[j], f[j - i * i] + 1); + } + } + return f[n]; +} +``` + ```rust impl Solution { pub fn num_squares(n: i32) -> i32 { @@ -262,10 +256,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0280.Wiggle Sort/README.md b/solution/0200-0299/0280.Wiggle Sort/README.md index 6fd102cb91753..b2ecd52b48630 100644 --- a/solution/0200-0299/0280.Wiggle Sort/README.md +++ b/solution/0200-0299/0280.Wiggle Sort/README.md @@ -46,14 +46,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def wiggleSort(self, nums: List[int]) -> None: @@ -67,10 +63,6 @@ class Solution: nums[i], nums[i - 1] = nums[i - 1], nums[i] ``` -### **Java** - - - ```java class Solution { public void wiggleSort(int[] nums) { @@ -89,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +94,6 @@ public: }; ``` -### **Go** - ```go func wiggleSort(nums []int) { for i := 1; i < len(nums); i++ { @@ -116,10 +104,6 @@ func wiggleSort(nums []int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0280.Wiggle Sort/README_EN.md b/solution/0200-0299/0280.Wiggle Sort/README_EN.md index 5fcd18ff8ccbd..bca5ef01524db 100644 --- a/solution/0200-0299/0280.Wiggle Sort/README_EN.md +++ b/solution/0200-0299/0280.Wiggle Sort/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: nums[i], nums[i - 1] = nums[i - 1], nums[i] ``` -### **Java** - ```java class Solution { public void wiggleSort(int[] nums) { @@ -75,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,8 +86,6 @@ public: }; ``` -### **Go** - ```go func wiggleSort(nums []int) { for i := 1; i < len(nums); i++ { @@ -102,10 +96,6 @@ func wiggleSort(nums []int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0281.Zigzag Iterator/README.md b/solution/0200-0299/0281.Zigzag Iterator/README.md index 5bd1539c77372..a1611f73c022d 100644 --- a/solution/0200-0299/0281.Zigzag Iterator/README.md +++ b/solution/0200-0299/0281.Zigzag Iterator/README.md @@ -34,16 +34,10 @@ v2 = [3,4,5,6] ## 解法 - - -定义 vectors 列表保存输入的所有一维向量,indexes 表示 vectors 列表每一项当前所遍历到的下标位置,cur 表示当前遍历到的 vector 列表,而 size 表示 vectors 列表元素个数。具体实现参考以下代码实现。 +### 方法一 -### **Python3** - - - ```python class ZigzagIterator: def __init__(self, v1: List[int], v2: List[int]): @@ -74,7 +68,49 @@ class ZigzagIterator: # while i.hasNext(): v.append(i.next()) ``` -### **Rust** +```java +public class ZigzagIterator { + private int cur; + private int size; + private List indexes = new ArrayList<>(); + private List> vectors = new ArrayList<>(); + + public ZigzagIterator(List v1, List v2) { + cur = 0; + size = 2; + indexes.add(0); + indexes.add(0); + vectors.add(v1); + vectors.add(v2); + } + + public int next() { + List vector = vectors.get(cur); + int index = indexes.get(cur); + int res = vector.get(index); + indexes.set(cur, index + 1); + cur = (cur + 1) % size; + return res; + } + + public boolean hasNext() { + int start = cur; + while (indexes.get(cur) == vectors.get(cur).size()) { + cur = (cur + 1) % size; + if (start == cur) { + return false; + } + } + return true; + } +} + +/** + * Your ZigzagIterator object will be instantiated and called as such: + * ZigzagIterator i = new ZigzagIterator(v1, v2); + * while (i.hasNext()) v[f()] = i.next(); + */ +``` ```rust struct ZigzagIterator { @@ -132,58 +168,6 @@ impl ZigzagIterator { } ``` -### **Java** - - - -```java -public class ZigzagIterator { - private int cur; - private int size; - private List indexes = new ArrayList<>(); - private List> vectors = new ArrayList<>(); - - public ZigzagIterator(List v1, List v2) { - cur = 0; - size = 2; - indexes.add(0); - indexes.add(0); - vectors.add(v1); - vectors.add(v2); - } - - public int next() { - List vector = vectors.get(cur); - int index = indexes.get(cur); - int res = vector.get(index); - indexes.set(cur, index + 1); - cur = (cur + 1) % size; - return res; - } - - public boolean hasNext() { - int start = cur; - while (indexes.get(cur) == vectors.get(cur).size()) { - cur = (cur + 1) % size; - if (start == cur) { - return false; - } - } - return true; - } -} - -/** - * Your ZigzagIterator object will be instantiated and called as such: - * ZigzagIterator i = new ZigzagIterator(v1, v2); - * while (i.hasNext()) v[f()] = i.next(); - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0281.Zigzag Iterator/README_EN.md b/solution/0200-0299/0281.Zigzag Iterator/README_EN.md index c05ee2562041f..8627eb3587e68 100644 --- a/solution/0200-0299/0281.Zigzag Iterator/README_EN.md +++ b/solution/0200-0299/0281.Zigzag Iterator/README_EN.md @@ -62,9 +62,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class ZigzagIterator: @@ -96,7 +96,49 @@ class ZigzagIterator: # while i.hasNext(): v.append(i.next()) ``` -### **Rust** +```java +public class ZigzagIterator { + private int cur; + private int size; + private List indexes = new ArrayList<>(); + private List> vectors = new ArrayList<>(); + + public ZigzagIterator(List v1, List v2) { + cur = 0; + size = 2; + indexes.add(0); + indexes.add(0); + vectors.add(v1); + vectors.add(v2); + } + + public int next() { + List vector = vectors.get(cur); + int index = indexes.get(cur); + int res = vector.get(index); + indexes.set(cur, index + 1); + cur = (cur + 1) % size; + return res; + } + + public boolean hasNext() { + int start = cur; + while (indexes.get(cur) == vectors.get(cur).size()) { + cur = (cur + 1) % size; + if (start == cur) { + return false; + } + } + return true; + } +} + +/** + * Your ZigzagIterator object will be instantiated and called as such: + * ZigzagIterator i = new ZigzagIterator(v1, v2); + * while (i.hasNext()) v[f()] = i.next(); + */ +``` ```rust struct ZigzagIterator { @@ -154,56 +196,6 @@ impl ZigzagIterator { } ``` -### **Java** - -```java -public class ZigzagIterator { - private int cur; - private int size; - private List indexes = new ArrayList<>(); - private List> vectors = new ArrayList<>(); - - public ZigzagIterator(List v1, List v2) { - cur = 0; - size = 2; - indexes.add(0); - indexes.add(0); - vectors.add(v1); - vectors.add(v2); - } - - public int next() { - List vector = vectors.get(cur); - int index = indexes.get(cur); - int res = vector.get(index); - indexes.set(cur, index + 1); - cur = (cur + 1) % size; - return res; - } - - public boolean hasNext() { - int start = cur; - while (indexes.get(cur) == vectors.get(cur).size()) { - cur = (cur + 1) % size; - if (start == cur) { - return false; - } - } - return true; - } -} - -/** - * Your ZigzagIterator object will be instantiated and called as such: - * ZigzagIterator i = new ZigzagIterator(v1, v2); - * while (i.hasNext()) v[f()] = i.next(); - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0282.Expression Add Operators/README.md b/solution/0200-0299/0282.Expression Add Operators/README.md index 9a895f3e1d7d9..9d1945221dee5 100644 --- a/solution/0200-0299/0282.Expression Add Operators/README.md +++ b/solution/0200-0299/0282.Expression Add Operators/README.md @@ -48,14 +48,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def addOperators(self, num: str, target: int) -> List[str]: @@ -86,12 +82,7 @@ class Solution: return ans ``` -### **Java** - - - ```java - class Solution { private List ans; private String num; @@ -127,10 +118,118 @@ class Solution { } ``` -### **...** +```cs +using System; +using System.Collections.Generic; -``` +public class Expression +{ + public long Value; + public override string ToString() + { + return Value.ToString(); + } +} + +public class BinaryExpression : Expression +{ + public char Operator; + + public Expression LeftChild; + public Expression RightChild; + + public override string ToString() + { + return string.Format("{0}{1}{2}", LeftChild, Operator, RightChild); + } +} + +public class Solution { + public IList AddOperators(string num, int target) { + var results = new List(); + if (string.IsNullOrEmpty(num)) return results; + this.num = num; + this.results = new List[num.Length, num.Length, 3]; + foreach (var ex in Search(0, num.Length - 1, 0)) + { + if (ex.Value == target) + { + results.Add(ex.ToString()); + } + } + return results; + } + + private string num; + private List[,,] results; + + private List Search(int left, int right, int level) + { + if (results[left, right, level] != null) + { + return results[left, right, level]; + } + var result = new List(); + if (level < 2) + { + for (var i = left + 1; i <= right; ++i) + { + List leftResult, rightResult; + leftResult = Search(left, i - 1, level); + rightResult = Search(i, right, level + 1); + foreach (var l in leftResult) + { + foreach (var r in rightResult) + { + var newObjects = new List>(); + if (level == 0) + { + newObjects.Add(Tuple.Create('+', l.Value + r.Value)); + newObjects.Add(Tuple.Create('-', l.Value - r.Value)); + } + else + { + newObjects.Add(Tuple.Create('*', l.Value * r.Value)); + } + foreach (var newObject in newObjects) + { + result.Add(new BinaryExpression + { + Value = newObject.Item2, + Operator = newObject.Item1, + LeftChild = l, + RightChild = r + }); + } + } + } + } + } + else + { + if (left == right || num[left] != '0') + { + long x = 0; + for (var i = left; i <= right; ++i) + { + x = x * 10 + num[i] - '0'; + } + result.Add(new Expression + { + Value = x + }); + } + } + if (level < 2) + { + result.AddRange(Search(left, right, level + 1)); + } + return results[left, right, level] = result; + } +} ``` + + diff --git a/solution/0200-0299/0282.Expression Add Operators/README_EN.md b/solution/0200-0299/0282.Expression Add Operators/README_EN.md index 66a68ced6955b..016248a53e818 100644 --- a/solution/0200-0299/0282.Expression Add Operators/README_EN.md +++ b/solution/0200-0299/0282.Expression Add Operators/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,10 +78,7 @@ class Solution: return ans ``` -### **Java** - ```java - class Solution { private List ans; private String num; @@ -117,10 +114,118 @@ class Solution { } ``` -### **...** +```cs +using System; +using System.Collections.Generic; -``` +public class Expression +{ + public long Value; + + public override string ToString() + { + return Value.ToString(); + } +} + +public class BinaryExpression : Expression +{ + public char Operator; + + public Expression LeftChild; + public Expression RightChild; + + public override string ToString() + { + return string.Format("{0}{1}{2}", LeftChild, Operator, RightChild); + } +} + +public class Solution { + public IList AddOperators(string num, int target) { + var results = new List(); + if (string.IsNullOrEmpty(num)) return results; + this.num = num; + this.results = new List[num.Length, num.Length, 3]; + foreach (var ex in Search(0, num.Length - 1, 0)) + { + if (ex.Value == target) + { + results.Add(ex.ToString()); + } + } + return results; + } + private string num; + private List[,,] results; + + private List Search(int left, int right, int level) + { + if (results[left, right, level] != null) + { + return results[left, right, level]; + } + var result = new List(); + if (level < 2) + { + for (var i = left + 1; i <= right; ++i) + { + List leftResult, rightResult; + leftResult = Search(left, i - 1, level); + rightResult = Search(i, right, level + 1); + foreach (var l in leftResult) + { + foreach (var r in rightResult) + { + var newObjects = new List>(); + if (level == 0) + { + newObjects.Add(Tuple.Create('+', l.Value + r.Value)); + newObjects.Add(Tuple.Create('-', l.Value - r.Value)); + } + else + { + newObjects.Add(Tuple.Create('*', l.Value * r.Value)); + } + foreach (var newObject in newObjects) + { + result.Add(new BinaryExpression + { + Value = newObject.Item2, + Operator = newObject.Item1, + LeftChild = l, + RightChild = r + }); + } + } + } + } + } + else + { + if (left == right || num[left] != '0') + { + long x = 0; + for (var i = left; i <= right; ++i) + { + x = x * 10 + num[i] - '0'; + } + result.Add(new Expression + { + Value = x + }); + } + } + if (level < 2) + { + result.AddRange(Search(left, right, level + 1)); + } + return results[left, right, level] = result; + } +} ``` + + diff --git a/solution/0200-0299/0283.Move Zeroes/README.md b/solution/0200-0299/0283.Move Zeroes/README.md index 8f1e1ce423e48..1be9402176753 100644 --- a/solution/0200-0299/0283.Move Zeroes/README.md +++ b/solution/0200-0299/0283.Move Zeroes/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们使用两个指针 $i$ 和 $j$,其中指针 $i$ 指向当前已经处理好的序列的尾部,而指针 $j$ 指向待处理序列的头部。初始时 $i=-1$。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def moveZeroes(self, nums: List[int]) -> None: @@ -67,10 +61,6 @@ class Solution: nums[i], nums[j] = nums[j], nums[i] ``` -### **Java** - - - ```java class Solution { public void moveZeroes(int[] nums) { @@ -86,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +90,6 @@ public: }; ``` -### **Go** - ```go func moveZeroes(nums []int) { i := -1 @@ -116,27 +102,6 @@ func moveZeroes(nums []int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {void} Do not return anything, modify nums in-place instead. - */ -var moveZeroes = function (nums) { - let i = -1; - for (let j = 0; j < nums.length; ++j) { - if (nums[j]) { - const t = nums[++i]; - nums[i] = nums[j]; - nums[j] = t; - } - } -}; -``` - -### **TypeScript** - ```ts /** Do not return anything, modify nums in-place instead. @@ -155,8 +120,6 @@ function moveZeroes(nums: number[]): void { } ``` -### **Rust** - ```rust impl Solution { pub fn move_zeroes(nums: &mut Vec) { @@ -174,7 +137,22 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var moveZeroes = function (nums) { + let i = -1; + for (let j = 0; j < nums.length; ++j) { + if (nums[j]) { + const t = nums[++i]; + nums[i] = nums[j]; + nums[j] = t; + } + } +}; +``` ```c void moveZeroes(int* nums, int numsSize) { @@ -191,10 +169,6 @@ void moveZeroes(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0283.Move Zeroes/README_EN.md b/solution/0200-0299/0283.Move Zeroes/README_EN.md index f0af9ebd0a69b..b3da94fb9077d 100644 --- a/solution/0200-0299/0283.Move Zeroes/README_EN.md +++ b/solution/0200-0299/0283.Move Zeroes/README_EN.md @@ -29,7 +29,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We use two pointers $i$ and $j$, where pointer $i$ points to the end of the sequence that has been processed, and pointer $j$ points to the head of the sequence to be processed. Initially, $i=-1$. @@ -39,8 +39,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def moveZeroes(self, nums: List[int]) -> None: @@ -51,8 +49,6 @@ class Solution: nums[i], nums[j] = nums[j], nums[i] ``` -### **Java** - ```java class Solution { public void moveZeroes(int[] nums) { @@ -68,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -84,8 +78,6 @@ public: }; ``` -### **Go** - ```go func moveZeroes(nums []int) { i := -1 @@ -98,27 +90,6 @@ func moveZeroes(nums []int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {void} Do not return anything, modify nums in-place instead. - */ -var moveZeroes = function (nums) { - let i = -1; - for (let j = 0; j < nums.length; ++j) { - if (nums[j]) { - const t = nums[++i]; - nums[i] = nums[j]; - nums[j] = t; - } - } -}; -``` - -### **TypeScript** - ```ts /** Do not return anything, modify nums in-place instead. @@ -137,8 +108,6 @@ function moveZeroes(nums: number[]): void { } ``` -### **Rust** - ```rust impl Solution { pub fn move_zeroes(nums: &mut Vec) { @@ -156,7 +125,22 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var moveZeroes = function (nums) { + let i = -1; + for (let j = 0; j < nums.length; ++j) { + if (nums[j]) { + const t = nums[++i]; + nums[i] = nums[j]; + nums[j] = t; + } + } +}; +``` ```c void moveZeroes(int* nums, int numsSize) { @@ -173,10 +157,6 @@ void moveZeroes(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0284.Peeking Iterator/README.md b/solution/0200-0299/0284.Peeking Iterator/README.md index 8534bdd175922..ff66b85b29927 100644 --- a/solution/0200-0299/0284.Peeking Iterator/README.md +++ b/solution/0200-0299/0284.Peeking Iterator/README.md @@ -56,16 +56,10 @@ peekingIterator.hasNext(); // 返回 False ## 解法 - - -定义一个变量 peekElement 专门用来保存下一个值,布尔变量 hasPeeked 标记是否保存了下一个元素。 +### 方法一 -### **Python3** - - - ```python # Below is the interface for Iterator, which is already defined for you. # @@ -134,10 +128,6 @@ class PeekingIterator: # iter.next() # Should return the same value as [val]. ``` -### **Java** - - - ```java // Java Iterator interface reference: // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html @@ -181,8 +171,6 @@ class PeekingIterator implements Iterator { } ``` -### **C++** - ```cpp /* * Below is the interface for Iterator, which is already defined for you. @@ -240,8 +228,6 @@ private: }; ``` -### **Go** - ```go /* Below is the interface for Iterator, which is already defined for you. * @@ -289,10 +275,6 @@ func (this *PeekingIterator) peek() int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0284.Peeking Iterator/README_EN.md b/solution/0200-0299/0284.Peeking Iterator/README_EN.md index 84c122bddf96c..8b710d660a2f6 100644 --- a/solution/0200-0299/0284.Peeking Iterator/README_EN.md +++ b/solution/0200-0299/0284.Peeking Iterator/README_EN.md @@ -51,9 +51,9 @@ peekingIterator.hasNext(); // return False ## Solutions - +### Solution 1 -### **Python3** + ```python # Below is the interface for Iterator, which is already defined for you. @@ -123,8 +123,6 @@ class PeekingIterator: # iter.next() # Should return the same value as [val]. ``` -### **Java** - ```java // Java Iterator interface reference: // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html @@ -168,8 +166,6 @@ class PeekingIterator implements Iterator { } ``` -### **C++** - ```cpp /* * Below is the interface for Iterator, which is already defined for you. @@ -227,8 +223,6 @@ private: }; ``` -### **Go** - ```go /* Below is the interface for Iterator, which is already defined for you. * @@ -276,10 +270,6 @@ func (this *PeekingIterator) peek() int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0285.Inorder Successor in BST/README.md b/solution/0200-0299/0285.Inorder Successor in BST/README.md index 78082948e0fe3..b5bb2c4b8e137 100644 --- a/solution/0200-0299/0285.Inorder Successor in BST/README.md +++ b/solution/0200-0299/0285.Inorder Successor in BST/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:二分搜索** +### 方法一:二分搜索 二叉搜索树的中序遍历是一个升序序列,因此可以使用二分搜索的方法。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -169,8 +155,6 @@ func inorderSuccessor(root *TreeNode, p *TreeNode) (ans *TreeNode) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -200,8 +184,6 @@ function inorderSuccessor(root: TreeNode | null, p: TreeNode | null): TreeNode | } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -229,10 +211,6 @@ var inorderSuccessor = function (root, p) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0285.Inorder Successor in BST/README_EN.md b/solution/0200-0299/0285.Inorder Successor in BST/README_EN.md index a9286a14880f7..dd25a95dfa73c 100644 --- a/solution/0200-0299/0285.Inorder Successor in BST/README_EN.md +++ b/solution/0200-0299/0285.Inorder Successor in BST/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -142,8 +136,6 @@ func inorderSuccessor(root *TreeNode, p *TreeNode) (ans *TreeNode) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -173,8 +165,6 @@ function inorderSuccessor(root: TreeNode | null, p: TreeNode | null): TreeNode | } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -202,10 +192,6 @@ var inorderSuccessor = function (root, p) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0286.Walls and Gates/README.md b/solution/0200-0299/0286.Walls and Gates/README.md index 4f9fbbb4af06c..bfaef78441861 100644 --- a/solution/0200-0299/0286.Walls and Gates/README.md +++ b/solution/0200-0299/0286.Walls and Gates/README.md @@ -59,18 +59,10 @@ ## 解法 - - -BFS。 - -将所有门放入队列,依次向外扩进行宽搜。由于宽度优先搜索保证我们在搜索 d + 1 距离的位置时, 距离为 d 的位置都已经被搜索过了,所以到达每一个房间的时候一定是最短距离。 +### 方法一 -### **Python3** - - - ```python class Solution: def wallsAndGates(self, rooms: List[List[int]]) -> None: @@ -92,10 +84,6 @@ class Solution: q.append((x, y)) ``` -### **Java** - - - ```java class Solution { public void wallsAndGates(int[][] rooms) { @@ -129,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +149,6 @@ public: }; ``` -### **Go** - ```go func wallsAndGates(rooms [][]int) { m, n := len(rooms), len(rooms[0]) @@ -195,10 +179,6 @@ func wallsAndGates(rooms [][]int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0286.Walls and Gates/README_EN.md b/solution/0200-0299/0286.Walls and Gates/README_EN.md index d56c4db64bb3d..66004110e2ce5 100644 --- a/solution/0200-0299/0286.Walls and Gates/README_EN.md +++ b/solution/0200-0299/0286.Walls and Gates/README_EN.md @@ -41,12 +41,10 @@ ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def wallsAndGates(self, rooms: List[List[int]]) -> None: @@ -68,8 +66,6 @@ class Solution: q.append((x, y)) ``` -### **Java** - ```java class Solution { public void wallsAndGates(int[][] rooms) { @@ -103,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +131,6 @@ public: }; ``` -### **Go** - ```go func wallsAndGates(rooms [][]int) { m, n := len(rooms), len(rooms[0]) @@ -169,10 +161,6 @@ func wallsAndGates(rooms [][]int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0287.Find the Duplicate Number/README.md b/solution/0200-0299/0287.Find the Duplicate Number/README.md index de4c579533da3..806c7ddcf5ab9 100644 --- a/solution/0200-0299/0287.Find the Duplicate Number/README.md +++ b/solution/0200-0299/0287.Find the Duplicate Number/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们可以发现,如果 $[1,..x]$ 中的数字个数大于 $x$,那么重复的数字一定在 $[1,..x]$ 中,否则重复的数字一定在 $[x+1,..n]$ 中。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def findDuplicate(self, nums: List[int]) -> int: @@ -75,10 +69,6 @@ class Solution: return bisect_left(range(len(nums)), True, key=f) ``` -### **Java** - - - ```java class Solution { public int findDuplicate(int[] nums) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,35 +114,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn find_duplicate(nums: Vec) -> i32 { - let mut left = 0; - let mut right = nums.len() - 1; - - while left < right { - let mid = (left + right) >> 1; - let cnt = nums - .iter() - .filter(|x| **x <= (mid as i32)) - .count(); - if cnt > mid { - right = mid; - } else { - left = mid + 1; - } - } - - left as i32 - } -} -``` - -### **Go** - ```go func findDuplicate(nums []int) int { return sort.Search(len(nums), func(x int) bool { @@ -169,14 +128,8 @@ func findDuplicate(nums []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var findDuplicate = function (nums) { +```ts +function findDuplicate(nums: number[]): number { let l = 0; let r = nums.length - 1; while (l < r) { @@ -194,13 +147,40 @@ var findDuplicate = function (nums) { } } return l; -}; +} ``` -### **TypeScript** +```rust +impl Solution { + #[allow(dead_code)] + pub fn find_duplicate(nums: Vec) -> i32 { + let mut left = 0; + let mut right = nums.len() - 1; -```ts -function findDuplicate(nums: number[]): number { + while left < right { + let mid = (left + right) >> 1; + let cnt = nums + .iter() + .filter(|x| **x <= (mid as i32)) + .count(); + if cnt > mid { + right = mid; + } else { + left = mid + 1; + } + } + + left as i32 + } +} +``` + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function (nums) { let l = 0; let r = nums.length - 1; while (l < r) { @@ -218,13 +198,9 @@ function findDuplicate(nums: number[]): number { } } return l; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0200-0299/0287.Find the Duplicate Number/README_EN.md b/solution/0200-0299/0287.Find the Duplicate Number/README_EN.md index 0e4b06c1e9628..92ac888485ec4 100644 --- a/solution/0200-0299/0287.Find the Duplicate Number/README_EN.md +++ b/solution/0200-0299/0287.Find the Duplicate Number/README_EN.md @@ -45,7 +45,7 @@ ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search We can observe that if the number of elements in $[1,..x]$ is greater than $x$, then the duplicate number must be in $[1,..x]$, otherwise the duplicate number must be in $[x+1,..n]$. @@ -55,8 +55,6 @@ The time complexity is $O(n \times \log n)$, where $n$ is the length of the arra -### **Python3** - ```python class Solution: def findDuplicate(self, nums: List[int]) -> int: @@ -66,8 +64,6 @@ class Solution: return bisect_left(range(len(nums)), True, key=f) ``` -### **Java** - ```java class Solution { public int findDuplicate(int[] nums) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,35 +109,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn find_duplicate(nums: Vec) -> i32 { - let mut left = 0; - let mut right = nums.len() - 1; - - while left < right { - let mid = (left + right) >> 1; - let cnt = nums - .iter() - .filter(|x| **x <= (mid as i32)) - .count(); - if cnt > mid { - right = mid; - } else { - left = mid + 1; - } - } - - left as i32 - } -} -``` - -### **Go** - ```go func findDuplicate(nums []int) int { return sort.Search(len(nums), func(x int) bool { @@ -158,14 +123,8 @@ func findDuplicate(nums []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var findDuplicate = function (nums) { +```ts +function findDuplicate(nums: number[]): number { let l = 0; let r = nums.length - 1; while (l < r) { @@ -183,13 +142,40 @@ var findDuplicate = function (nums) { } } return l; -}; +} ``` -### **TypeScript** +```rust +impl Solution { + #[allow(dead_code)] + pub fn find_duplicate(nums: Vec) -> i32 { + let mut left = 0; + let mut right = nums.len() - 1; -```ts -function findDuplicate(nums: number[]): number { + while left < right { + let mid = (left + right) >> 1; + let cnt = nums + .iter() + .filter(|x| **x <= (mid as i32)) + .count(); + if cnt > mid { + right = mid; + } else { + left = mid + 1; + } + } + + left as i32 + } +} +``` + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function (nums) { let l = 0; let r = nums.length - 1; while (l < r) { @@ -207,13 +193,9 @@ function findDuplicate(nums: number[]): number { } } return l; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0200-0299/0288.Unique Word Abbreviation/README.md b/solution/0200-0299/0288.Unique Word Abbreviation/README.md index 02b5f688444a4..ba9c7d2799b19 100644 --- a/solution/0200-0299/0288.Unique Word Abbreviation/README.md +++ b/solution/0200-0299/0288.Unique Word Abbreviation/README.md @@ -65,9 +65,7 @@ validWordAbbr.isUnique("cake"); // 返回 true,因为 "cake" 已经存在于 ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 根据题目描述,我们定义一个函数 $abbr(s)$,它的功能是计算单词 $s$ 的缩写。如果单词 $s$ 的长度小于 $3$,那么它的缩写就是它本身;否则,它的缩写是它的首字母 + (它的长度 - 2) + 它的尾字母。 @@ -79,10 +77,6 @@ validWordAbbr.isUnique("cake"); // 返回 true,因为 "cake" 已经存在于 -### **Python3** - - - ```python class ValidWordAbbr: def __init__(self, dictionary: List[str]): @@ -103,10 +97,6 @@ class ValidWordAbbr: # param_1 = obj.isUnique(word) ``` -### **Java** - - - ```java class ValidWordAbbr { private Map> d = new HashMap<>(); @@ -135,8 +125,6 @@ class ValidWordAbbr { */ ``` -### **C++** - ```cpp class ValidWordAbbr { public: @@ -167,8 +155,6 @@ private: */ ``` -### **Go** - ```go type ValidWordAbbr struct { d map[string]map[string]bool @@ -206,8 +192,6 @@ func abbr(s string) string { */ ``` -### **TypeScript** - ```ts class ValidWordAbbr { private d: Map> = new Map(); @@ -240,10 +224,6 @@ class ValidWordAbbr { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0288.Unique Word Abbreviation/README_EN.md b/solution/0200-0299/0288.Unique Word Abbreviation/README_EN.md index 2ebeb06cf1a71..2a2ec1d007179 100644 --- a/solution/0200-0299/0288.Unique Word Abbreviation/README_EN.md +++ b/solution/0200-0299/0288.Unique Word Abbreviation/README_EN.md @@ -59,7 +59,7 @@ validWordAbbr.isUnique("cake"); // return true, because "cake&quo ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table According to the problem description, we define a function $abbr(s)$, which calculates the abbreviation of the word $s$. If the length of the word $s$ is less than $3$, then its abbreviation is itself; otherwise, its abbreviation is its first letter + (its length - 2) + its last letter. @@ -71,8 +71,6 @@ In terms of time complexity, the time complexity of initializing the hash table -### **Python3** - ```python class ValidWordAbbr: def __init__(self, dictionary: List[str]): @@ -93,8 +91,6 @@ class ValidWordAbbr: # param_1 = obj.isUnique(word) ``` -### **Java** - ```java class ValidWordAbbr { private Map> d = new HashMap<>(); @@ -123,8 +119,6 @@ class ValidWordAbbr { */ ``` -### **C++** - ```cpp class ValidWordAbbr { public: @@ -155,8 +149,6 @@ private: */ ``` -### **Go** - ```go type ValidWordAbbr struct { d map[string]map[string]bool @@ -194,8 +186,6 @@ func abbr(s string) string { */ ``` -### **TypeScript** - ```ts class ValidWordAbbr { private d: Map> = new Map(); @@ -228,10 +218,6 @@ class ValidWordAbbr { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0289.Game of Life/README.md b/solution/0200-0299/0289.Game of Life/README.md index fb122a80c264f..ff18c0f9a1391 100644 --- a/solution/0200-0299/0289.Game of Life/README.md +++ b/solution/0200-0299/0289.Game of Life/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:原地标记** +### 方法一:原地标记 我们不妨定义两个新的状态,其中状态 $2$ 表示活细胞在下一个状态转为死细胞,状态 $-1$ 表示死细胞在下一个状态转为活细胞。那么,对于当前遍历到的格子,如果格子大于 $0$,就表示当前格子是活细胞,否则就是死细胞。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def gameOfLife(self, board: List[List[int]]) -> None: @@ -98,10 +92,6 @@ class Solution: board[i][j] = 1 ``` -### **Java** - - - ```java class Solution { public void gameOfLife(int[][] board) { @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,68 +163,6 @@ public: }; ``` -### **Rust** - -```rust -const DIR: [(i32, i32); 8] = [ - (-1, 0), - (1, 0), - (0, -1), - (0, 1), - (-1, -1), - (-1, 1), - (1, -1), - (1, 1), -]; - -impl Solution { - #[allow(dead_code)] - pub fn game_of_life(board: &mut Vec>) { - let n = board.len(); - let m = board[0].len(); - let mut weight_vec: Vec> = vec![vec![0; m]; n]; - - // Initialize the weight vector - for i in 0..n { - for j in 0..m { - if board[i][j] == 0 { - continue; - } - for (dx, dy) in DIR { - let x = (i as i32) + dx; - let y = (j as i32) + dy; - if Self::check_bounds(x, y, n as i32, m as i32) { - weight_vec[x as usize][y as usize] += 1; - } - } - } - } - - // Update the board - for i in 0..n { - for j in 0..m { - if weight_vec[i][j] < 2 { - board[i][j] = 0; - } else if weight_vec[i][j] <= 3 { - if board[i][j] == 0 && weight_vec[i][j] == 3 { - board[i][j] = 1; - } - } else { - board[i][j] = 0; - } - } - } - } - - #[allow(dead_code)] - fn check_bounds(i: i32, j: i32, n: i32, m: i32) -> bool { - i >= 0 && i < n && j >= 0 && j < m - } -} -``` - -### **Go** - ```go func gameOfLife(board [][]int) { m, n := len(board), len(board[0]) @@ -271,8 +197,6 @@ func gameOfLife(board [][]int) { } ``` -### **TypeScript** - ```ts /** Do not return anything, modify board in-place instead. @@ -311,7 +235,63 @@ function gameOfLife(board: number[][]): void { } ``` -### **C#** +```rust +const DIR: [(i32, i32); 8] = [ + (-1, 0), + (1, 0), + (0, -1), + (0, 1), + (-1, -1), + (-1, 1), + (1, -1), + (1, 1), +]; + +impl Solution { + #[allow(dead_code)] + pub fn game_of_life(board: &mut Vec>) { + let n = board.len(); + let m = board[0].len(); + let mut weight_vec: Vec> = vec![vec![0; m]; n]; + + // Initialize the weight vector + for i in 0..n { + for j in 0..m { + if board[i][j] == 0 { + continue; + } + for (dx, dy) in DIR { + let x = (i as i32) + dx; + let y = (j as i32) + dy; + if Self::check_bounds(x, y, n as i32, m as i32) { + weight_vec[x as usize][y as usize] += 1; + } + } + } + } + + // Update the board + for i in 0..n { + for j in 0..m { + if weight_vec[i][j] < 2 { + board[i][j] = 0; + } else if weight_vec[i][j] <= 3 { + if board[i][j] == 0 && weight_vec[i][j] == 3 { + board[i][j] = 1; + } + } else { + board[i][j] = 0; + } + } + } + } + + #[allow(dead_code)] + fn check_bounds(i: i32, j: i32, n: i32, m: i32) -> bool { + i >= 0 && i < n && j >= 0 && j < m + } +} +``` ```cs public class Solution { @@ -350,10 +330,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0289.Game of Life/README_EN.md b/solution/0200-0299/0289.Game of Life/README_EN.md index c3d319b50d4bb..a175adc125a32 100644 --- a/solution/0200-0299/0289.Game of Life/README_EN.md +++ b/solution/0200-0299/0289.Game of Life/README_EN.md @@ -52,7 +52,7 @@ ## Solutions -**Solution 1: In-place marking** +### Solution 1: In-place marking Let's define two new states. State $2$ indicates that the living cell becomes dead in the next state, and state $-1$ indicates that the dead cell becomes alive in the next state. Therefore, for the current grid we are traversing, if the grid is greater than $0$, it means that the current grid is a living cell, otherwise it is a dead cell. @@ -64,8 +64,6 @@ The time complexity is $O(m \times n)$, where $m$ and $n$ are the number of rows -### **Python3** - ```python class Solution: def gameOfLife(self, board: List[List[int]]) -> None: @@ -89,8 +87,6 @@ class Solution: board[i][j] = 1 ``` -### **Java** - ```java class Solution { public void gameOfLife(int[][] board) { @@ -126,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,68 +158,6 @@ public: }; ``` -### **Rust** - -```rust -const DIR: [(i32, i32); 8] = [ - (-1, 0), - (1, 0), - (0, -1), - (0, 1), - (-1, -1), - (-1, 1), - (1, -1), - (1, 1), -]; - -impl Solution { - #[allow(dead_code)] - pub fn game_of_life(board: &mut Vec>) { - let n = board.len(); - let m = board[0].len(); - let mut weight_vec: Vec> = vec![vec![0; m]; n]; - - // Initialize the weight vector - for i in 0..n { - for j in 0..m { - if board[i][j] == 0 { - continue; - } - for (dx, dy) in DIR { - let x = (i as i32) + dx; - let y = (j as i32) + dy; - if Self::check_bounds(x, y, n as i32, m as i32) { - weight_vec[x as usize][y as usize] += 1; - } - } - } - } - - // Update the board - for i in 0..n { - for j in 0..m { - if weight_vec[i][j] < 2 { - board[i][j] = 0; - } else if weight_vec[i][j] <= 3 { - if board[i][j] == 0 && weight_vec[i][j] == 3 { - board[i][j] = 1; - } - } else { - board[i][j] = 0; - } - } - } - } - - #[allow(dead_code)] - fn check_bounds(i: i32, j: i32, n: i32, m: i32) -> bool { - i >= 0 && i < n && j >= 0 && j < m - } -} -``` - -### **Go** - ```go func gameOfLife(board [][]int) { m, n := len(board), len(board[0]) @@ -260,8 +192,6 @@ func gameOfLife(board [][]int) { } ``` -### **TypeScript** - ```ts /** Do not return anything, modify board in-place instead. @@ -300,7 +230,63 @@ function gameOfLife(board: number[][]): void { } ``` -### **C#** +```rust +const DIR: [(i32, i32); 8] = [ + (-1, 0), + (1, 0), + (0, -1), + (0, 1), + (-1, -1), + (-1, 1), + (1, -1), + (1, 1), +]; + +impl Solution { + #[allow(dead_code)] + pub fn game_of_life(board: &mut Vec>) { + let n = board.len(); + let m = board[0].len(); + let mut weight_vec: Vec> = vec![vec![0; m]; n]; + + // Initialize the weight vector + for i in 0..n { + for j in 0..m { + if board[i][j] == 0 { + continue; + } + for (dx, dy) in DIR { + let x = (i as i32) + dx; + let y = (j as i32) + dy; + if Self::check_bounds(x, y, n as i32, m as i32) { + weight_vec[x as usize][y as usize] += 1; + } + } + } + } + + // Update the board + for i in 0..n { + for j in 0..m { + if weight_vec[i][j] < 2 { + board[i][j] = 0; + } else if weight_vec[i][j] <= 3 { + if board[i][j] == 0 && weight_vec[i][j] == 3 { + board[i][j] = 1; + } + } else { + board[i][j] = 0; + } + } + } + } + + #[allow(dead_code)] + fn check_bounds(i: i32, j: i32, n: i32, m: i32) -> bool { + i >= 0 && i < n && j >= 0 && j < m + } +} +``` ```cs public class Solution { @@ -339,10 +325,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0290.Word Pattern/README.md b/solution/0200-0299/0290.Word Pattern/README.md index 534257f25cd51..27991a02bc8a4 100644 --- a/solution/0200-0299/0290.Word Pattern/README.md +++ b/solution/0200-0299/0290.Word Pattern/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们先将字符串 $s$ 按照空格分割成单词数组 $ws$,如果 $pattern$ 和 $ws$ 的长度不相等,直接返回 `false`。否则,我们使用两个哈希表 $d_1$ 和 $d_2$,分别记录 $pattern$ 和 $ws$ 中每个字符和单词的对应关系。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def wordPattern(self, pattern: str, s: str) -> bool: @@ -79,10 +73,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean wordPattern(String pattern, String s) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func wordPattern(pattern string, s string) bool { ws := strings.Split(s, " ") @@ -161,8 +147,6 @@ func wordPattern(pattern string, s string) bool { } ``` -### **TypeScript** - ```ts function wordPattern(pattern: string, s: string): boolean { const ws = s.split(' '); @@ -187,36 +171,6 @@ function wordPattern(pattern: string, s: string): boolean { } ``` -### **C#** - -```cs -public class Solution { - public bool WordPattern(string pattern, string s) { - var ws = s.Split(' '); - if (pattern.Length != ws.Length) { - return false; - } - var d1 = new Dictionary(); - var d2 = new Dictionary(); - for (int i = 0; i < ws.Length; ++i) { - var a = pattern[i]; - var b = ws[i]; - if (d1.ContainsKey(a) && d1[a] != b) { - return false; - } - if (d2.ContainsKey(b) && d2[b] != a) { - return false; - } - d1[a] = b; - d2[b] = a; - } - return true; - } -} -``` - -### **Rust** - ```rust use std::collections::HashMap; @@ -248,10 +202,32 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public bool WordPattern(string pattern, string s) { + var ws = s.Split(' '); + if (pattern.Length != ws.Length) { + return false; + } + var d1 = new Dictionary(); + var d2 = new Dictionary(); + for (int i = 0; i < ws.Length; ++i) { + var a = pattern[i]; + var b = ws[i]; + if (d1.ContainsKey(a) && d1[a] != b) { + return false; + } + if (d2.ContainsKey(b) && d2[b] != a) { + return false; + } + d1[a] = b; + d2[b] = a; + } + return true; + } +} ``` + + diff --git a/solution/0200-0299/0290.Word Pattern/README_EN.md b/solution/0200-0299/0290.Word Pattern/README_EN.md index 982334612add2..915069af35318 100644 --- a/solution/0200-0299/0290.Word Pattern/README_EN.md +++ b/solution/0200-0299/0290.Word Pattern/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table First, we split the string $s$ into a word array $ws$ with spaces. If the length of $pattern$ and $ws$ is not equal, return `false` directly. Otherwise, we use two hash tables $d_1$ and $d_2$ to record the correspondence between each character and word in $pattern$ and $ws$. @@ -56,8 +56,6 @@ The time complexity is $O(m + n)$ and the space complexity is $O(m + n)$. Here $ -### **Python3** - ```python class Solution: def wordPattern(self, pattern: str, s: str) -> bool: @@ -74,8 +72,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean wordPattern(String pattern, String s) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +123,6 @@ public: }; ``` -### **Go** - ```go func wordPattern(pattern string, s string) bool { ws := strings.Split(s, " ") @@ -154,8 +146,6 @@ func wordPattern(pattern string, s string) bool { } ``` -### **TypeScript** - ```ts function wordPattern(pattern: string, s: string): boolean { const ws = s.split(' '); @@ -180,36 +170,6 @@ function wordPattern(pattern: string, s: string): boolean { } ``` -### **C#** - -```cs -public class Solution { - public bool WordPattern(string pattern, string s) { - var ws = s.Split(' '); - if (pattern.Length != ws.Length) { - return false; - } - var d1 = new Dictionary(); - var d2 = new Dictionary(); - for (int i = 0; i < ws.Length; ++i) { - var a = pattern[i]; - var b = ws[i]; - if (d1.ContainsKey(a) && d1[a] != b) { - return false; - } - if (d2.ContainsKey(b) && d2[b] != a) { - return false; - } - d1[a] = b; - d2[b] = a; - } - return true; - } -} -``` - -### **Rust** - ```rust use std::collections::HashMap; @@ -241,10 +201,32 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public bool WordPattern(string pattern, string s) { + var ws = s.Split(' '); + if (pattern.Length != ws.Length) { + return false; + } + var d1 = new Dictionary(); + var d2 = new Dictionary(); + for (int i = 0; i < ws.Length; ++i) { + var a = pattern[i]; + var b = ws[i]; + if (d1.ContainsKey(a) && d1[a] != b) { + return false; + } + if (d2.ContainsKey(b) && d2[b] != a) { + return false; + } + d1[a] = b; + d2[b] = a; + } + return true; + } +} ``` + + diff --git a/solution/0200-0299/0291.Word Pattern II/README.md b/solution/0200-0299/0291.Word Pattern II/README.md index 151eab73254de..8fbd89dad9e17 100644 --- a/solution/0200-0299/0291.Word Pattern II/README.md +++ b/solution/0200-0299/0291.Word Pattern II/README.md @@ -48,14 +48,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def wordPatternMatch(self, pattern: str, s: str) -> bool: @@ -84,10 +80,6 @@ class Solution: return dfs(0, 0) ``` -### **Java** - - - ```java class Solution { private Set vis; @@ -137,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +161,6 @@ public: }; ``` -### **Go** - ```go func wordPatternMatch(pattern string, s string) bool { m, n := len(pattern), len(s) @@ -210,10 +198,6 @@ func wordPatternMatch(pattern string, s string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0291.Word Pattern II/README_EN.md b/solution/0200-0299/0291.Word Pattern II/README_EN.md index e6beb6cc10df8..beae028b9c838 100644 --- a/solution/0200-0299/0291.Word Pattern II/README_EN.md +++ b/solution/0200-0299/0291.Word Pattern II/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return dfs(0, 0) ``` -### **Java** - ```java class Solution { private Set vis; @@ -127,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +157,6 @@ public: }; ``` -### **Go** - ```go func wordPatternMatch(pattern string, s string) bool { m, n := len(pattern), len(s) @@ -200,10 +194,6 @@ func wordPatternMatch(pattern string, s string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0292.Nim Game/README.md b/solution/0200-0299/0292.Nim Game/README.md index d6e73e5118a18..58472ad2ca03b 100644 --- a/solution/0200-0299/0292.Nim Game/README.md +++ b/solution/0200-0299/0292.Nim Game/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:数学推理** +### 方法一:数学推理 第一个得到 $4$ 的倍数(即 $n$ 能被 $4$ 整除)的将会输掉比赛。 @@ -73,20 +71,12 @@ -### **Python3** - - - ```python class Solution: def canWinNim(self, n: int) -> bool: return n % 4 != 0 ``` -### **Java** - - - ```java class Solution { public boolean canWinNim(int n) { @@ -95,16 +85,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function canWinNim(n: number): boolean { - return n % 4 != 0; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -114,15 +94,17 @@ public: }; ``` -### **Go** - ```go func canWinNim(n int) bool { return n%4 != 0 } ``` -### **Rust** +```ts +function canWinNim(n: number): boolean { + return n % 4 != 0; +} +``` ```rust impl Solution { @@ -132,10 +114,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0292.Nim Game/README_EN.md b/solution/0200-0299/0292.Nim Game/README_EN.md index 412b9b42a41fc..0ad5a6be63b81 100644 --- a/solution/0200-0299/0292.Nim Game/README_EN.md +++ b/solution/0200-0299/0292.Nim Game/README_EN.md @@ -51,9 +51,9 @@ In all outcomes, your friend wins. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return n % 4 != 0 ``` -### **Java** - ```java class Solution { public boolean canWinNim(int n) { @@ -71,16 +69,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function canWinNim(n: number): boolean { - return n % 4 != 0; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -90,15 +78,17 @@ public: }; ``` -### **Go** - ```go func canWinNim(n int) bool { return n%4 != 0 } ``` -### **Rust** +```ts +function canWinNim(n: number): boolean { + return n % 4 != 0; +} +``` ```rust impl Solution { @@ -108,10 +98,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0293.Flip Game/README.md b/solution/0200-0299/0293.Flip Game/README.md index 2b4c4d612e3d9..ee05f848eb4e1 100644 --- a/solution/0200-0299/0293.Flip Game/README.md +++ b/solution/0200-0299/0293.Flip Game/README.md @@ -39,14 +39,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def generatePossibleNextMoves(self, currentState: str) -> List[str]: @@ -60,10 +56,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List generatePossibleNextMoves(String currentState) { @@ -83,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +94,6 @@ public: }; ``` -### **Go** - ```go func generatePossibleNextMoves(currentState string) []string { ans := []string{} @@ -121,10 +109,6 @@ func generatePossibleNextMoves(currentState string) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0293.Flip Game/README_EN.md b/solution/0200-0299/0293.Flip Game/README_EN.md index e3673d40a1417..c87394b843239 100644 --- a/solution/0200-0299/0293.Flip Game/README_EN.md +++ b/solution/0200-0299/0293.Flip Game/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List generatePossibleNextMoves(String currentState) { @@ -73,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +90,6 @@ public: }; ``` -### **Go** - ```go func generatePossibleNextMoves(currentState string) []string { ans := []string{} @@ -111,10 +105,6 @@ func generatePossibleNextMoves(currentState string) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0294.Flip Game II/README.md b/solution/0200-0299/0294.Flip Game II/README.md index 20ad71f9f0e2f..d5978d8b1957e 100644 --- a/solution/0200-0299/0294.Flip Game II/README.md +++ b/solution/0200-0299/0294.Flip Game II/README.md @@ -42,43 +42,10 @@ ## 解法 - - -**方法一:状态压缩 + 记忆化搜索** - -**方法二:Sprague-Grundy 定理** - -Sprague-Grundy 定理为游戏的每一个状态定义了一个 Sprague-Grundy 数(简称 SG 数),游戏状态的组合相当于 SG 数的异或运算。 - -Sprague-Grundy 定理的完整表述如下: - -若一个游戏满足以下条件: - -1. 双人、回合制 -1. 信息完全公开 -1. 无随机因素 -1. 必然在有限步内结束,且每步的走法数有限 -1. 没有平局 -1. 双方可采取的行动及胜利目标都相同 -1. 这个胜利目标是自己亲手达成终局状态,或者说走最后一步者为胜(normal play) - -则游戏中的每个状态可以按如下规则赋予一个非负整数,称为 Sprague-Grundy 数,即 $SG(A)=mex\{SG(B)|A->B\}$。(式中 $A$, $B$ 代表状态,代表 $A$ 状态经一步行动可以到达 $B$ 状态,而 $mex$ 表示一个集合所不包含的最小非负整数) - -SG 数有如下性质: - -1. SG 数为 0 的状态,后手必胜;SG 数为正的状态,先手必胜; -1. 若一个母状态可以拆分成多个相互独立的子状态,则母状态的 SG 数等于各个子状态的 SG 数的异或。 - -参考资料:[Sprague-Grundy 定理是怎么想出来的](https://zhuanlan.zhihu.com/p/20611132) - -时间复杂度 $O(n^2)$。 +### 方法一:状态压缩 + 记忆化搜索 -### **Python3** - - - ```python class Solution: def canWin(self, currentState: str) -> bool: @@ -99,38 +66,6 @@ class Solution: return dfs(mask) ``` -```python -class Solution: - def canWin(self, currentState: str) -> bool: - def win(i): - if sg[i] != -1: - return sg[i] - vis = [False] * n - for j in range(i - 1): - vis[win(j) ^ win(i - j - 2)] = True - for j in range(n): - if not vis[j]: - sg[i] = j - return j - return 0 - - n = len(currentState) - sg = [-1] * (n + 1) - sg[0] = sg[1] = 0 - ans = i = 0 - while i < n: - j = i - while j < n and currentState[j] == '+': - j += 1 - ans ^= win(j - i) - i = j + 1 - return ans > 0 -``` - -### **Java** - - - ```java class Solution { private int n; @@ -167,6 +102,127 @@ class Solution { } ``` +```cpp +using ll = long long; + +class Solution { +public: + int n; + unordered_map memo; + + bool canWin(string currentState) { + n = currentState.size(); + ll mask = 0; + for (int i = 0; i < n; ++i) + if (currentState[i] == '+') mask |= 1ll << i; + return dfs(mask); + } + + bool dfs(ll mask) { + if (memo.count(mask)) return memo[mask]; + for (int i = 0; i < n - 1; ++i) { + if ((mask & (1ll << i)) == 0 || (mask & (1ll << (i + 1))) == 0) continue; + if (dfs(mask ^ (1ll << i) ^ (1ll << (i + 1)))) continue; + memo[mask] = true; + return true; + } + memo[mask] = false; + return false; + } +}; +``` + +```go +func canWin(currentState string) bool { + n := len(currentState) + memo := map[int]bool{} + mask := 0 + for i, c := range currentState { + if c == '+' { + mask |= 1 << i + } + } + var dfs func(int) bool + dfs = func(mask int) bool { + if v, ok := memo[mask]; ok { + return v + } + for i := 0; i < n-1; i++ { + if (mask&(1< + +### 方法二:Sprague-Grundy 定理 + +Sprague-Grundy 定理为游戏的每一个状态定义了一个 Sprague-Grundy 数(简称 SG 数),游戏状态的组合相当于 SG 数的异或运算。 + +Sprague-Grundy 定理的完整表述如下: + +若一个游戏满足以下条件: + +1. 双人、回合制 +1. 信息完全公开 +1. 无随机因素 +1. 必然在有限步内结束,且每步的走法数有限 +1. 没有平局 +1. 双方可采取的行动及胜利目标都相同 +1. 这个胜利目标是自己亲手达成终局状态,或者说走最后一步者为胜(normal play) + +则游戏中的每个状态可以按如下规则赋予一个非负整数,称为 Sprague-Grundy 数,即 $SG(A)=mex\{SG(B)|A->B\}$。(式中 $A$, $B$ 代表状态,代表 $A$ 状态经一步行动可以到达 $B$ 状态,而 $mex$ 表示一个集合所不包含的最小非负整数) + +SG 数有如下性质: + +1. SG 数为 0 的状态,后手必胜;SG 数为正的状态,先手必胜; +1. 若一个母状态可以拆分成多个相互独立的子状态,则母状态的 SG 数等于各个子状态的 SG 数的异或。 + +参考资料:[Sprague-Grundy 定理是怎么想出来的](https://zhuanlan.zhihu.com/p/20611132) + +时间复杂度 $O(n^2)$。 + + + +```python +class Solution: + def canWin(self, currentState: str) -> bool: + def win(i): + if sg[i] != -1: + return sg[i] + vis = [False] * n + for j in range(i - 1): + vis[win(j) ^ win(i - j - 2)] = True + for j in range(n): + if not vis[j]: + sg[i] = j + return j + return 0 + + n = len(currentState) + sg = [-1] * (n + 1) + sg[0] = sg[1] = 0 + ans = i = 0 + while i < n: + j = i + while j < n and currentState[j] == '+': + j += 1 + ans ^= win(j - i) + i = j + 1 + return ans > 0 +``` + ```java class Solution { private int n; @@ -208,38 +264,6 @@ class Solution { } ``` -### **C++** - -```cpp -using ll = long long; - -class Solution { -public: - int n; - unordered_map memo; - - bool canWin(string currentState) { - n = currentState.size(); - ll mask = 0; - for (int i = 0; i < n; ++i) - if (currentState[i] == '+') mask |= 1ll << i; - return dfs(mask); - } - - bool dfs(ll mask) { - if (memo.count(mask)) return memo[mask]; - for (int i = 0; i < n - 1; ++i) { - if ((mask & (1ll << i)) == 0 || (mask & (1ll << (i + 1))) == 0) continue; - if (dfs(mask ^ (1ll << i) ^ (1ll << (i + 1)))) continue; - memo[mask] = true; - return true; - } - memo[mask] = false; - return false; - } -}; -``` - ```cpp class Solution { public: @@ -269,40 +293,6 @@ public: }; ``` -### **Go** - -```go -func canWin(currentState string) bool { - n := len(currentState) - memo := map[int]bool{} - mask := 0 - for i, c := range currentState { - if c == '+' { - mask |= 1 << i - } - } - var dfs func(int) bool - dfs = func(mask int) bool { - if v, ok := memo[mask]; ok { - return v - } - for i := 0; i < n-1; i++ { - if (mask&(1< + + diff --git a/solution/0200-0299/0294.Flip Game II/README_EN.md b/solution/0200-0299/0294.Flip Game II/README_EN.md index 648072bce5373..6a54a833ab9ed 100644 --- a/solution/0200-0299/0294.Flip Game II/README_EN.md +++ b/solution/0200-0299/0294.Flip Game II/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,36 +63,6 @@ class Solution: return dfs(mask) ``` -```python -class Solution: - def canWin(self, currentState: str) -> bool: - def win(i): - if sg[i] != -1: - return sg[i] - vis = [False] * n - for j in range(i - 1): - vis[win(j) ^ win(i - j - 2)] = True - for j in range(n): - if not vis[j]: - sg[i] = j - return j - return 0 - - n = len(currentState) - sg = [-1] * (n + 1) - sg[0] = sg[1] = 0 - ans = i = 0 - while i < n: - j = i - while j < n and currentState[j] == '+': - j += 1 - ans ^= win(j - i) - i = j + 1 - return ans > 0 -``` - -### **Java** - ```java class Solution { private int n; @@ -129,6 +99,102 @@ class Solution { } ``` +```cpp +using ll = long long; + +class Solution { +public: + int n; + unordered_map memo; + + bool canWin(string currentState) { + n = currentState.size(); + ll mask = 0; + for (int i = 0; i < n; ++i) + if (currentState[i] == '+') mask |= 1ll << i; + return dfs(mask); + } + + bool dfs(ll mask) { + if (memo.count(mask)) return memo[mask]; + for (int i = 0; i < n - 1; ++i) { + if ((mask & (1ll << i)) == 0 || (mask & (1ll << (i + 1))) == 0) continue; + if (dfs(mask ^ (1ll << i) ^ (1ll << (i + 1)))) continue; + memo[mask] = true; + return true; + } + memo[mask] = false; + return false; + } +}; +``` + +```go +func canWin(currentState string) bool { + n := len(currentState) + memo := map[int]bool{} + mask := 0 + for i, c := range currentState { + if c == '+' { + mask |= 1 << i + } + } + var dfs func(int) bool + dfs = func(mask int) bool { + if v, ok := memo[mask]; ok { + return v + } + for i := 0; i < n-1; i++ { + if (mask&(1< + +### Solution 2 + + + +```python +class Solution: + def canWin(self, currentState: str) -> bool: + def win(i): + if sg[i] != -1: + return sg[i] + vis = [False] * n + for j in range(i - 1): + vis[win(j) ^ win(i - j - 2)] = True + for j in range(n): + if not vis[j]: + sg[i] = j + return j + return 0 + + n = len(currentState) + sg = [-1] * (n + 1) + sg[0] = sg[1] = 0 + ans = i = 0 + while i < n: + j = i + while j < n and currentState[j] == '+': + j += 1 + ans ^= win(j - i) + i = j + 1 + return ans > 0 +``` + ```java class Solution { private int n; @@ -170,38 +236,6 @@ class Solution { } ``` -### **C++** - -```cpp -using ll = long long; - -class Solution { -public: - int n; - unordered_map memo; - - bool canWin(string currentState) { - n = currentState.size(); - ll mask = 0; - for (int i = 0; i < n; ++i) - if (currentState[i] == '+') mask |= 1ll << i; - return dfs(mask); - } - - bool dfs(ll mask) { - if (memo.count(mask)) return memo[mask]; - for (int i = 0; i < n - 1; ++i) { - if ((mask & (1ll << i)) == 0 || (mask & (1ll << (i + 1))) == 0) continue; - if (dfs(mask ^ (1ll << i) ^ (1ll << (i + 1)))) continue; - memo[mask] = true; - return true; - } - memo[mask] = false; - return false; - } -}; -``` - ```cpp class Solution { public: @@ -231,40 +265,6 @@ public: }; ``` -### **Go** - -```go -func canWin(currentState string) bool { - n := len(currentState) - memo := map[int]bool{} - mask := 0 - for i, c := range currentState { - if c == '+' { - mask |= 1 << i - } - } - var dfs func(int) bool - dfs = func(mask int) bool { - if v, ok := memo[mask]; ok { - return v - } - for i := 0; i < n-1; i++ { - if (mask&(1< + + diff --git a/solution/0200-0299/0295.Find Median from Data Stream/README.md b/solution/0200-0299/0295.Find Median from Data Stream/README.md index dae41eeeb8ea6..21d79c78a28c5 100644 --- a/solution/0200-0299/0295.Find Median from Data Stream/README.md +++ b/solution/0200-0299/0295.Find Median from Data Stream/README.md @@ -54,9 +54,7 @@ medianFinder.findMedian(); // return 2.0 ## 解法 - - -**方法一:优先队列(双堆)** +### 方法一:优先队列(双堆) 创建大根堆、小根堆,其中:大根堆存放较小的一半元素,小根堆存放较大的一半元素。 @@ -70,10 +68,6 @@ medianFinder.findMedian(); // return 2.0 -### **Python3** - - - ```python class MedianFinder: def __init__(self): @@ -101,10 +95,6 @@ class MedianFinder: # param_2 = obj.findMedian() ``` -### **Java** - - - ```java class MedianFinder { private PriorityQueue q1 = new PriorityQueue<>(); @@ -138,8 +128,6 @@ class MedianFinder { */ ``` -### **C++** - ```cpp class MedianFinder { public: @@ -177,8 +165,6 @@ private: */ ``` -### **Go** - ```go type MedianFinder struct { q1 hp @@ -224,45 +210,6 @@ func (h *hp) Pop() any { } ``` -### **JavaScript** - -```js -/** - * initialize your data structure here. - */ -var MedianFinder = function () { - this.val = []; -}; - -/** - * @param {number} num - * @return {void} - */ -MedianFinder.prototype.addNum = function (num) { - let left = 0; - let right = this.val.length; - while (left < right) { - let mid = left + ~~((right - left) / 2); - if (num > this.val[mid]) { - left = mid + 1; - } else { - right = mid; - } - } - this.val.splice(left, 0, num); -}; - -/** - * @return {number} - */ -MedianFinder.prototype.findMedian = function () { - let mid = ~~(this.val.length / 2); - return this.val.length % 2 ? this.val[mid] : (this.val[mid - 1] + this.val[mid]) / 2; -}; -``` - -### **TypeScript** - ```ts class MedianFinder { private nums: number[]; @@ -304,8 +251,6 @@ class MedianFinder { */ ``` -### **Rust** - ```rust struct MedianFinder { nums: Vec, @@ -350,7 +295,40 @@ impl MedianFinder { */ ``` -### **C#** +```js +/** + * initialize your data structure here. + */ +var MedianFinder = function () { + this.val = []; +}; + +/** + * @param {number} num + * @return {void} + */ +MedianFinder.prototype.addNum = function (num) { + let left = 0; + let right = this.val.length; + while (left < right) { + let mid = left + ~~((right - left) / 2); + if (num > this.val[mid]) { + left = mid + 1; + } else { + right = mid; + } + } + this.val.splice(left, 0, num); +}; + +/** + * @return {number} + */ +MedianFinder.prototype.findMedian = function () { + let mid = ~~(this.val.length / 2); + return this.val.length % 2 ? this.val[mid] : (this.val[mid - 1] + this.val[mid]) / 2; +}; +``` ```cs public class MedianFinder { @@ -411,10 +389,6 @@ public class MedianFinder { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0295.Find Median from Data Stream/README_EN.md b/solution/0200-0299/0295.Find Median from Data Stream/README_EN.md index 7ed2552de8009..61df34c86e3fa 100644 --- a/solution/0200-0299/0295.Find Median from Data Stream/README_EN.md +++ b/solution/0200-0299/0295.Find Median from Data Stream/README_EN.md @@ -57,9 +57,9 @@ medianFinder.findMedian(); // return 2.0 ## Solutions - +### Solution 1 -### **Python3** + ```python class MedianFinder: @@ -88,8 +88,6 @@ class MedianFinder: # param_2 = obj.findMedian() ``` -### **Java** - ```java class MedianFinder { private PriorityQueue q1 = new PriorityQueue<>(); @@ -123,8 +121,6 @@ class MedianFinder { */ ``` -### **C++** - ```cpp class MedianFinder { public: @@ -162,8 +158,6 @@ private: */ ``` -### **Go** - ```go type MedianFinder struct { q1 hp @@ -209,45 +203,6 @@ func (h *hp) Pop() any { } ``` -### **JavaScript** - -```js -/** - * initialize your data structure here. - */ -var MedianFinder = function () { - this.val = []; -}; - -/** - * @param {number} num - * @return {void} - */ -MedianFinder.prototype.addNum = function (num) { - let left = 0; - let right = this.val.length; - while (left < right) { - let mid = left + ~~((right - left) / 2); - if (num > this.val[mid]) { - left = mid + 1; - } else { - right = mid; - } - } - this.val.splice(left, 0, num); -}; - -/** - * @return {number} - */ -MedianFinder.prototype.findMedian = function () { - let mid = ~~(this.val.length / 2); - return this.val.length % 2 ? this.val[mid] : (this.val[mid - 1] + this.val[mid]) / 2; -}; -``` - -### **TypeScript** - ```ts class MedianFinder { private nums: number[]; @@ -289,8 +244,6 @@ class MedianFinder { */ ``` -### **Rust** - ```rust struct MedianFinder { nums: Vec, @@ -335,7 +288,40 @@ impl MedianFinder { */ ``` -### **C#** +```js +/** + * initialize your data structure here. + */ +var MedianFinder = function () { + this.val = []; +}; + +/** + * @param {number} num + * @return {void} + */ +MedianFinder.prototype.addNum = function (num) { + let left = 0; + let right = this.val.length; + while (left < right) { + let mid = left + ~~((right - left) / 2); + if (num > this.val[mid]) { + left = mid + 1; + } else { + right = mid; + } + } + this.val.splice(left, 0, num); +}; + +/** + * @return {number} + */ +MedianFinder.prototype.findMedian = function () { + let mid = ~~(this.val.length / 2); + return this.val.length % 2 ? this.val[mid] : (this.val[mid - 1] + this.val[mid]) / 2; +}; +``` ```cs public class MedianFinder { @@ -396,10 +382,6 @@ public class MedianFinder { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0296.Best Meeting Point/README.md b/solution/0200-0299/0296.Best Meeting Point/README.md index 9964e3af3e31d..309b07e49254d 100644 --- a/solution/0200-0299/0296.Best Meeting Point/README.md +++ b/solution/0200-0299/0296.Best Meeting Point/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:排序 + 中位数** +### 方法一:排序 + 中位数 对于每一行,我们可以将所有的 $1$ 的下标排序,然后取中位数 $i$ 作为碰头地点的横坐标。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def minTotalDistance(self, grid: List[List[int]]) -> int: @@ -85,10 +79,6 @@ class Solution: return f(rows, i) + f(cols, j) ``` -### **Java** - - - ```java class Solution { public int minTotalDistance(int[][] grid) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,7 +139,37 @@ public: }; ``` -### **Rust** +```go +func minTotalDistance(grid [][]int) int { + rows, cols := []int{}, []int{} + for i, row := range grid { + for j, v := range row { + if v == 1 { + rows = append(rows, i) + cols = append(cols, j) + } + } + } + sort.Ints(cols) + i := rows[len(rows)>>1] + j := cols[len(cols)>>1] + f := func(arr []int, x int) int { + s := 0 + for _, v := range arr { + s += abs(v - x) + } + return s + } + return f(rows, i) + f(cols, j) +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} +``` ```rust impl Solution { @@ -193,44 +211,6 @@ impl Solution { } ``` -### **Go** - -```go -func minTotalDistance(grid [][]int) int { - rows, cols := []int{}, []int{} - for i, row := range grid { - for j, v := range row { - if v == 1 { - rows = append(rows, i) - cols = append(cols, j) - } - } - } - sort.Ints(cols) - i := rows[len(rows)>>1] - j := cols[len(cols)>>1] - f := func(arr []int, x int) int { - s := 0 - for _, v := range arr { - s += abs(v - x) - } - return s - } - return f(rows, i) + f(cols, j) -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0296.Best Meeting Point/README_EN.md b/solution/0200-0299/0296.Best Meeting Point/README_EN.md index e9c7946f99783..c05acd320826d 100644 --- a/solution/0200-0299/0296.Best Meeting Point/README_EN.md +++ b/solution/0200-0299/0296.Best Meeting Point/README_EN.md @@ -41,9 +41,9 @@ So return 6. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return f(rows, i) + f(cols, j) ``` -### **Java** - ```java class Solution { public int minTotalDistance(int[][] grid) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,7 +123,37 @@ public: }; ``` -### **Rust** +```go +func minTotalDistance(grid [][]int) int { + rows, cols := []int{}, []int{} + for i, row := range grid { + for j, v := range row { + if v == 1 { + rows = append(rows, i) + cols = append(cols, j) + } + } + } + sort.Ints(cols) + i := rows[len(rows)>>1] + j := cols[len(cols)>>1] + f := func(arr []int, x int) int { + s := 0 + for _, v := range arr { + s += abs(v - x) + } + return s + } + return f(rows, i) + f(cols, j) +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} +``` ```rust impl Solution { @@ -169,44 +195,6 @@ impl Solution { } ``` -### **Go** - -```go -func minTotalDistance(grid [][]int) int { - rows, cols := []int{}, []int{} - for i, row := range grid { - for j, v := range row { - if v == 1 { - rows = append(rows, i) - cols = append(cols, j) - } - } - } - sort.Ints(cols) - i := rows[len(rows)>>1] - j := cols[len(cols)>>1] - f := func(arr []int, x int) int { - s := 0 - for _, v := range arr { - s += abs(v - x) - } - return s - } - return f(rows, i) + f(cols, j) -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/README.md b/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/README.md index 1d7c6e6edff8a..ad10dce90130c 100644 --- a/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/README.md +++ b/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/README.md @@ -53,14 +53,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode(object): @@ -118,10 +114,6 @@ class Codec: # ans = deser.deserialize(ser.serialize(root)) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -186,8 +178,6 @@ public class Codec { // TreeNode ans = deser.deserialize(ser.serialize(root)); ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -241,7 +231,112 @@ public: // TreeNode* ans = deser.deserialize(ser.serialize(root)); ``` -### **JavaScript** +```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) + * } + * } + */ + +/* + * Encodes a tree to a single string. + */ +function serialize(root: TreeNode | null): string { + return JSON.stringify(root); +} + +/* + * Decodes your encoded data to tree. + */ +function deserialize(data: string): TreeNode | null { + return JSON.parse(data); +} + +/** + * Your functions will be called as such: + * deserialize(serialize(root)); + */ +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +struct Codec {} + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl Codec { + fn new() -> Self { + Codec {} + } + + fn serialize(&self, root: Option>>) -> String { + if root.is_none() { + return String::from("#"); + } + let mut node = root.as_ref().unwrap().borrow_mut(); + let left = node.left.take(); + let right = node.right.take(); + format!("{},{},{}", self.serialize(right), self.serialize(left), node.val) + } + + fn deserialize(&self, data: String) -> Option>> { + if data.len() == 1 { + return None; + } + Self::renew(&mut data.split(",").collect()) + } + + fn renew(vals: &mut Vec<&str>) -> Option>> { + let val = vals.pop().unwrap_or("#"); + if val == "#" { + return None; + } + Some( + Rc::new( + RefCell::new(TreeNode { + val: val.parse().unwrap(), + left: Self::renew(vals), + right: Self::renew(vals), + }) + ) + ) + } +}/** + * Your Codec object will be instantiated and called as such: + * let obj = Codec::new(); + * let data: String = obj.serialize(strs); + * let ans: Option>> = obj.deserialize(data); + */ +``` ```js /** @@ -304,42 +399,11 @@ const rdeserialize = dataList => { */ ``` -### **TypeScript** - -```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) - * } - * } - */ - -/* - * Encodes a tree to a single string. - */ -function serialize(root: TreeNode | null): string { - return JSON.stringify(root); -} + -/* - * Decodes your encoded data to tree. - */ -function deserialize(data: string): TreeNode | null { - return JSON.parse(data); -} +### 方法二 -/** - * Your functions will be called as such: - * deserialize(serialize(root)); - */ -``` + ```ts /** @@ -392,84 +456,6 @@ function deserialize(data: string): TreeNode | null { */ ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -struct Codec {} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl Codec { - fn new() -> Self { - Codec {} - } - - fn serialize(&self, root: Option>>) -> String { - if root.is_none() { - return String::from("#"); - } - let mut node = root.as_ref().unwrap().borrow_mut(); - let left = node.left.take(); - let right = node.right.take(); - format!("{},{},{}", self.serialize(right), self.serialize(left), node.val) - } - - fn deserialize(&self, data: String) -> Option>> { - if data.len() == 1 { - return None; - } - Self::renew(&mut data.split(",").collect()) - } - - fn renew(vals: &mut Vec<&str>) -> Option>> { - let val = vals.pop().unwrap_or("#"); - if val == "#" { - return None; - } - Some( - Rc::new( - RefCell::new(TreeNode { - val: val.parse().unwrap(), - left: Self::renew(vals), - right: Self::renew(vals), - }) - ) - ) - } -}/** - * Your Codec object will be instantiated and called as such: - * let obj = Codec::new(); - * let data: String = obj.serialize(strs); - * let ans: Option>> = obj.deserialize(data); - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/README_EN.md b/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/README_EN.md index 943a4ec3772b4..1d9d572452a53 100644 --- a/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/README_EN.md +++ b/solution/0200-0299/0297.Serialize and Deserialize Binary Tree/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -96,8 +96,6 @@ class Codec: # ans = deser.deserialize(ser.serialize(root)) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -162,8 +160,6 @@ public class Codec { // TreeNode ans = deser.deserialize(ser.serialize(root)); ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -217,7 +213,112 @@ public: // TreeNode* ans = deser.deserialize(ser.serialize(root)); ``` -### **JavaScript** +```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) + * } + * } + */ + +/* + * Encodes a tree to a single string. + */ +function serialize(root: TreeNode | null): string { + return JSON.stringify(root); +} + +/* + * Decodes your encoded data to tree. + */ +function deserialize(data: string): TreeNode | null { + return JSON.parse(data); +} + +/** + * Your functions will be called as such: + * deserialize(serialize(root)); + */ +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +struct Codec {} + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl Codec { + fn new() -> Self { + Codec {} + } + + fn serialize(&self, root: Option>>) -> String { + if root.is_none() { + return String::from("#"); + } + let mut node = root.as_ref().unwrap().borrow_mut(); + let left = node.left.take(); + let right = node.right.take(); + format!("{},{},{}", self.serialize(right), self.serialize(left), node.val) + } + + fn deserialize(&self, data: String) -> Option>> { + if data.len() == 1 { + return None; + } + Self::renew(&mut data.split(",").collect()) + } + + fn renew(vals: &mut Vec<&str>) -> Option>> { + let val = vals.pop().unwrap_or("#"); + if val == "#" { + return None; + } + Some( + Rc::new( + RefCell::new(TreeNode { + val: val.parse().unwrap(), + left: Self::renew(vals), + right: Self::renew(vals), + }) + ) + ) + } +}/** + * Your Codec object will be instantiated and called as such: + * let obj = Codec::new(); + * let data: String = obj.serialize(strs); + * let ans: Option>> = obj.deserialize(data); + */ +``` ```js /** @@ -280,42 +381,11 @@ const rdeserialize = dataList => { */ ``` -### **TypeScript** - -```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) - * } - * } - */ - -/* - * Encodes a tree to a single string. - */ -function serialize(root: TreeNode | null): string { - return JSON.stringify(root); -} + -/* - * Decodes your encoded data to tree. - */ -function deserialize(data: string): TreeNode | null { - return JSON.parse(data); -} +### Solution 2 -/** - * Your functions will be called as such: - * deserialize(serialize(root)); - */ -``` + ```ts /** @@ -368,84 +438,6 @@ function deserialize(data: string): TreeNode | null { */ ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -struct Codec {} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl Codec { - fn new() -> Self { - Codec {} - } - - fn serialize(&self, root: Option>>) -> String { - if root.is_none() { - return String::from("#"); - } - let mut node = root.as_ref().unwrap().borrow_mut(); - let left = node.left.take(); - let right = node.right.take(); - format!("{},{},{}", self.serialize(right), self.serialize(left), node.val) - } - - fn deserialize(&self, data: String) -> Option>> { - if data.len() == 1 { - return None; - } - Self::renew(&mut data.split(",").collect()) - } - - fn renew(vals: &mut Vec<&str>) -> Option>> { - let val = vals.pop().unwrap_or("#"); - if val == "#" { - return None; - } - Some( - Rc::new( - RefCell::new(TreeNode { - val: val.parse().unwrap(), - left: Self::renew(vals), - right: Self::renew(vals), - }) - ) - ) - } -}/** - * Your Codec object will be instantiated and called as such: - * let obj = Codec::new(); - * let data: String = obj.serialize(strs); - * let ans: Option>> = obj.deserialize(data); - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/README.md b/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/README.md index e3e763dd3190e..7efae40d4d692 100644 --- a/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/README.md +++ b/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们设计一个函数 $dfs(root)$,表示以 $root$ 为连续序列的第一个节点的最长连续序列路径长度。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -90,10 +84,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -177,8 +165,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -211,8 +197,6 @@ func longestConsecutive(root *TreeNode) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -251,10 +235,6 @@ function longestConsecutive(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/README_EN.md b/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/README_EN.md index 98694ebd144c9..99eabc42b6b7b 100644 --- a/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/README_EN.md +++ b/solution/0200-0299/0298.Binary Tree Longest Consecutive Sequence/README_EN.md @@ -37,12 +37,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -71,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -116,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -156,8 +150,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -190,8 +182,6 @@ func longestConsecutive(root *TreeNode) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -230,10 +220,6 @@ function longestConsecutive(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0299.Bulls and Cows/README.md b/solution/0200-0299/0299.Bulls and Cows/README.md index bce16522b9433..3e495f8fa2e13 100644 --- a/solution/0200-0299/0299.Bulls and Cows/README.md +++ b/solution/0200-0299/0299.Bulls and Cows/README.md @@ -56,14 +56,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def getHint(self, secret: str, guess: str) -> str: @@ -82,10 +78,6 @@ class Solution: return f'{x}A{y}B' ``` -### **Java** - - - ```java class Solution { public String getHint(String secret, String guess) { @@ -109,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +123,6 @@ public: }; ``` -### **Go** - ```go func getHint(secret string, guess string) string { x, y := 0, 0 @@ -156,8 +144,6 @@ func getHint(secret string, guess string) string { } ``` -### **PHP** - ```php class Solution { /** @@ -187,10 +173,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0200-0299/0299.Bulls and Cows/README_EN.md b/solution/0200-0299/0299.Bulls and Cows/README_EN.md index 31ff8b1bbb3e2..72a67216d1465 100644 --- a/solution/0200-0299/0299.Bulls and Cows/README_EN.md +++ b/solution/0200-0299/0299.Bulls and Cows/README_EN.md @@ -51,9 +51,9 @@ Note that only one of the two unmatched 1s is counted as a cow since the non-bul ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return f'{x}A{y}B' ``` -### **Java** - ```java class Solution { public String getHint(String secret, String guess) { @@ -98,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +118,6 @@ public: }; ``` -### **Go** - ```go func getHint(secret string, guess string) string { x, y := 0, 0 @@ -145,8 +139,6 @@ func getHint(secret string, guess string) string { } ``` -### **PHP** - ```php class Solution { /** @@ -176,10 +168,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0300.Longest Increasing Subsequence/README.md b/solution/0300-0399/0300.Longest Increasing Subsequence/README.md index aa216888c9339..e7675e16ab017 100644 --- a/solution/0300-0399/0300.Longest Increasing Subsequence/README.md +++ b/solution/0300-0399/0300.Longest Increasing Subsequence/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示以 $nums[i]$ 结尾的最长递增子序列的长度,初始时 $f[i] = 1$,答案为 $f[i]$ 的最大值。 @@ -64,22 +62,8 @@ 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。 -**方法二:离散化 + 树状数组** - -我们将数组中的元素离散化,然后使用树状数组维护不大于某个元素的最长递增子序列的长度。 - -遍历数组中的每个元素 $x$,将其离散化,然后在树状数组中查找不大于 $x-1$ 的最长递增子序列的长度 $t$,则 $x$ 的最长递增子序列的长度为 $t+1$,更新答案,并且更新树状数组中 $x$ 的最长递增子序列的长度。 - -遍历完数组中的所有元素,即可得到答案。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。 - -### **Python3** - - - ```python class Solution: def lengthOfLIS(self, nums: List[int]) -> int: @@ -92,6 +76,110 @@ class Solution: return max(f) ``` +```java +class Solution { + public int lengthOfLIS(int[] nums) { + int n = nums.length; + int[] f = new int[n]; + Arrays.fill(f, 1); + int ans = 1; + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + f[i] = Math.max(f[i], f[j] + 1); + } + } + ans = Math.max(ans, f[i]); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int lengthOfLIS(vector& nums) { + int n = nums.size(); + vector f(n, 1); + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + f[i] = max(f[i], f[j] + 1); + } + } + } + return *max_element(f.begin(), f.end()); + } +}; +``` + +```go +func lengthOfLIS(nums []int) int { + n := len(nums) + f := make([]int, n) + for i := range f { + f[i] = 1 + } + ans := 1 + for i := 1; i < n; i++ { + for j := 0; j < i; j++ { + if nums[j] < nums[i] { + f[i] = max(f[i], f[j]+1) + ans = max(ans, f[i]) + } + } + } + return ans +} +``` + +```ts +function lengthOfLIS(nums: number[]): number { + const n = nums.length; + const f: number[] = new Array(n).fill(1); + for (let i = 1; i < n; ++i) { + for (let j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + f[i] = Math.max(f[i], f[j] + 1); + } + } + } + return Math.max(...f); +} +``` + +```rust +impl Solution { + pub fn length_of_lis(nums: Vec) -> i32 { + let n = nums.len(); + let mut f = vec![1; n]; + for i in 1..n { + for j in 0..i { + if nums[j] < nums[i] { + f[i] = f[i].max(f[j] + 1); + } + } + } + *f.iter().max().unwrap() + } +} +``` + + + +### 方法二:离散化 + 树状数组 + +我们将数组中的元素离散化,然后使用树状数组维护不大于某个元素的最长递增子序列的长度。 + +遍历数组中的每个元素 $x$,将其离散化,然后在树状数组中查找不大于 $x-1$ 的最长递增子序列的长度 $t$,则 $x$ 的最长递增子序列的长度为 $t+1$,更新答案,并且更新树状数组中 $x$ 的最长递增子序列的长度。 + +遍历完数组中的所有元素,即可得到答案。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。 + + + ```python class BinaryIndexedTree: def __init__(self, n: int): @@ -123,30 +211,6 @@ class Solution: return tree.query(m) ``` -### **Java** - - - -```java -class Solution { - public int lengthOfLIS(int[] nums) { - int n = nums.length; - int[] f = new int[n]; - Arrays.fill(f, 1); - int ans = 1; - for (int i = 1; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (nums[j] < nums[i]) { - f[i] = Math.max(f[i], f[j] + 1); - } - } - ans = Math.max(ans, f[i]); - } - return ans; - } -} -``` - ```java class Solution { public int lengthOfLIS(int[] nums) { @@ -209,26 +273,6 @@ class BinaryIndexedTree { } ``` -### **C++** - -```cpp -class Solution { -public: - int lengthOfLIS(vector& nums) { - int n = nums.size(); - vector f(n, 1); - for (int i = 1; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (nums[j] < nums[i]) { - f[i] = max(f[i], f[j] + 1); - } - } - } - return *max_element(f.begin(), f.end()); - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -274,28 +318,6 @@ public: }; ``` -### **Go** - -```go -func lengthOfLIS(nums []int) int { - n := len(nums) - f := make([]int, n) - for i := range f { - f[i] = 1 - } - ans := 1 - for i := 1; i < n; i++ { - for j := 0; j < i; j++ { - if nums[j] < nums[i] { - f[i] = max(f[i], f[j]+1) - ans = max(ans, f[i]) - } - } - } - return ans -} -``` - ```go type BinaryIndexedTree struct { n int @@ -344,23 +366,6 @@ func lengthOfLIS(nums []int) int { } ``` -### **TypeScript** - -```ts -function lengthOfLIS(nums: number[]): number { - const n = nums.length; - const f: number[] = new Array(n).fill(1); - for (let i = 1; i < n; ++i) { - for (let j = 0; j < i; ++j) { - if (nums[j] < nums[i]) { - f[i] = Math.max(f[i], f[j] + 1); - } - } - } - return Math.max(...f); -} -``` - ```ts class BinaryIndexedTree { private n: number; @@ -415,29 +420,6 @@ function search(nums: number[], x: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn length_of_lis(nums: Vec) -> i32 { - let n = nums.len(); - let mut f = vec![1; n]; - for i in 1..n { - for j in 0..i { - if nums[j] < nums[i] { - f[i] = f[i].max(f[j] + 1); - } - } - } - *f.iter().max().unwrap() - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0300.Longest Increasing Subsequence/README_EN.md b/solution/0300-0399/0300.Longest Increasing Subsequence/README_EN.md index 37e1ac18ac10a..9c24ba06e58e6 100644 --- a/solution/0300-0399/0300.Longest Increasing Subsequence/README_EN.md +++ b/solution/0300-0399/0300.Longest Increasing Subsequence/README_EN.md @@ -42,12 +42,10 @@ ## Solutions -Dynamic programming or Binary Indexed Tree. +### Solution 1 -### **Python3** - ```python class Solution: def lengthOfLIS(self, nums: List[int]) -> int: @@ -60,6 +58,102 @@ class Solution: return max(f) ``` +```java +class Solution { + public int lengthOfLIS(int[] nums) { + int n = nums.length; + int[] f = new int[n]; + Arrays.fill(f, 1); + int ans = 1; + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + f[i] = Math.max(f[i], f[j] + 1); + } + } + ans = Math.max(ans, f[i]); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int lengthOfLIS(vector& nums) { + int n = nums.size(); + vector f(n, 1); + for (int i = 1; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + f[i] = max(f[i], f[j] + 1); + } + } + } + return *max_element(f.begin(), f.end()); + } +}; +``` + +```go +func lengthOfLIS(nums []int) int { + n := len(nums) + f := make([]int, n) + for i := range f { + f[i] = 1 + } + ans := 1 + for i := 1; i < n; i++ { + for j := 0; j < i; j++ { + if nums[j] < nums[i] { + f[i] = max(f[i], f[j]+1) + ans = max(ans, f[i]) + } + } + } + return ans +} +``` + +```ts +function lengthOfLIS(nums: number[]): number { + const n = nums.length; + const f: number[] = new Array(n).fill(1); + for (let i = 1; i < n; ++i) { + for (let j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + f[i] = Math.max(f[i], f[j] + 1); + } + } + } + return Math.max(...f); +} +``` + +```rust +impl Solution { + pub fn length_of_lis(nums: Vec) -> i32 { + let n = nums.len(); + let mut f = vec![1; n]; + for i in 1..n { + for j in 0..i { + if nums[j] < nums[i] { + f[i] = f[i].max(f[j] + 1); + } + } + } + *f.iter().max().unwrap() + } +} +``` + + + +### Solution 2 + + + ```python class BinaryIndexedTree: def __init__(self, n: int): @@ -91,28 +185,6 @@ class Solution: return tree.query(m) ``` -### **Java** - -```java -class Solution { - public int lengthOfLIS(int[] nums) { - int n = nums.length; - int[] f = new int[n]; - Arrays.fill(f, 1); - int ans = 1; - for (int i = 1; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (nums[j] < nums[i]) { - f[i] = Math.max(f[i], f[j] + 1); - } - } - ans = Math.max(ans, f[i]); - } - return ans; - } -} -``` - ```java class Solution { public int lengthOfLIS(int[] nums) { @@ -175,26 +247,6 @@ class BinaryIndexedTree { } ``` -### **C++** - -```cpp -class Solution { -public: - int lengthOfLIS(vector& nums) { - int n = nums.size(); - vector f(n, 1); - for (int i = 1; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (nums[j] < nums[i]) { - f[i] = max(f[i], f[j] + 1); - } - } - } - return *max_element(f.begin(), f.end()); - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -240,28 +292,6 @@ public: }; ``` -### **Go** - -```go -func lengthOfLIS(nums []int) int { - n := len(nums) - f := make([]int, n) - for i := range f { - f[i] = 1 - } - ans := 1 - for i := 1; i < n; i++ { - for j := 0; j < i; j++ { - if nums[j] < nums[i] { - f[i] = max(f[i], f[j]+1) - ans = max(ans, f[i]) - } - } - } - return ans -} -``` - ```go type BinaryIndexedTree struct { n int @@ -310,23 +340,6 @@ func lengthOfLIS(nums []int) int { } ``` -### **TypeScript** - -```ts -function lengthOfLIS(nums: number[]): number { - const n = nums.length; - const f: number[] = new Array(n).fill(1); - for (let i = 1; i < n; ++i) { - for (let j = 0; j < i; ++j) { - if (nums[j] < nums[i]) { - f[i] = Math.max(f[i], f[j] + 1); - } - } - } - return Math.max(...f); -} -``` - ```ts class BinaryIndexedTree { private n: number; @@ -381,29 +394,6 @@ function search(nums: number[], x: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn length_of_lis(nums: Vec) -> i32 { - let n = nums.len(); - let mut f = vec![1; n]; - for i in 1..n { - for j in 0..i { - if nums[j] < nums[i] { - f[i] = f[i].max(f[j] + 1); - } - } - } - *f.iter().max().unwrap() - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0301.Remove Invalid Parentheses/README.md b/solution/0300-0399/0301.Remove Invalid Parentheses/README.md index a19cd768a2ffa..caec92673384d 100644 --- a/solution/0300-0399/0301.Remove Invalid Parentheses/README.md +++ b/solution/0300-0399/0301.Remove Invalid Parentheses/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:DFS + 剪枝** +### 方法一:DFS + 剪枝 我们首先处理得到字符串 $s$ 待删除的左、右括号的最小数量,分别记为 $l$ 和 $r$。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def removeInvalidParentheses(self, s: str) -> List[str]: @@ -109,10 +103,6 @@ class Solution: return list(ans) ``` -### **Java** - - - ```java class Solution { private String s; @@ -162,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -209,8 +197,6 @@ public: }; ``` -### **Go** - ```go func removeInvalidParentheses(s string) []string { vis := map[string]bool{} @@ -260,10 +246,6 @@ func removeInvalidParentheses(s string) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0301.Remove Invalid Parentheses/README_EN.md b/solution/0300-0399/0301.Remove Invalid Parentheses/README_EN.md index 76c9dc1dff1d3..fadcc9fc0c1fe 100644 --- a/solution/0300-0399/0301.Remove Invalid Parentheses/README_EN.md +++ b/solution/0300-0399/0301.Remove Invalid Parentheses/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return list(ans) ``` -### **Java** - ```java class Solution { private String s; @@ -127,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -174,8 +170,6 @@ public: }; ``` -### **Go** - ```go func removeInvalidParentheses(s string) []string { vis := map[string]bool{} @@ -225,10 +219,6 @@ func removeInvalidParentheses(s string) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/README.md b/solution/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/README.md index 5d2900be0c9f9..16f794cd69765 100644 --- a/solution/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/README.md +++ b/solution/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/README.md @@ -49,16 +49,10 @@ ## 解法 - - -二分查找,时间复杂度 `O(mlogn + nlogm)`。 +### 方法一 -### **Python3** - - - ```python class Solution: def minArea(self, image: List[List[str]], x: int, y: int) -> int: @@ -110,10 +104,6 @@ class Solution: return (d - u + 1) * (r - l + 1) ``` -### **Java** - - - ```java class Solution { @@ -183,8 +173,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -242,8 +230,6 @@ public: }; ``` -### **Go** - ```go func minArea(image [][]byte, x int, y int) int { m, n := len(image), len(image[0]) @@ -307,10 +293,6 @@ func minArea(image [][]byte, x int, y int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/README_EN.md b/solution/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/README_EN.md index 4ab43ae9b7220..84589b3079b2c 100644 --- a/solution/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/README_EN.md +++ b/solution/0300-0399/0302.Smallest Rectangle Enclosing Black Pixels/README_EN.md @@ -43,12 +43,10 @@ ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python class Solution: def minArea(self, image: List[List[str]], x: int, y: int) -> int: @@ -100,8 +98,6 @@ class Solution: return (d - u + 1) * (r - l + 1) ``` -### **Java** - ```java class Solution { @@ -171,8 +167,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -230,8 +224,6 @@ public: }; ``` -### **Go** - ```go func minArea(image [][]byte, x int, y int) int { m, n := len(image), len(image[0]) @@ -295,10 +287,6 @@ func minArea(image [][]byte, x int, y int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0303.Range Sum Query - Immutable/README.md b/solution/0300-0399/0303.Range Sum Query - Immutable/README.md index 68f3da4569c3a..cb28a26d09ebf 100644 --- a/solution/0300-0399/0303.Range Sum Query - Immutable/README.md +++ b/solution/0300-0399/0303.Range Sum Query - Immutable/README.md @@ -50,9 +50,7 @@ numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1)) ## 解法 - - -**方法一:前缀和** +### 方法一:前缀和 我们创建一个长度为 $n + 1$ 的前缀和数组 $s$,其中 $s[i]$ 表示前 $i$ 个元素的前缀和,即 $s[i] = \sum_{j=0}^{i-1} nums[j]$,那么索引 $[left, right]$ 之间的元素的和就可以表示为 $s[right + 1] - s[left]$。 @@ -60,10 +58,6 @@ numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1)) -### **Python3** - - - ```python class NumArray: def __init__(self, nums: List[int]): @@ -78,10 +72,6 @@ class NumArray: # param_1 = obj.sumRange(left,right) ``` -### **Java** - - - ```java class NumArray { private int[] s; @@ -106,8 +96,6 @@ class NumArray { */ ``` -### **C++** - ```cpp class NumArray { public: @@ -134,8 +122,6 @@ private: */ ``` -### **Go** - ```go type NumArray struct { s []int @@ -161,38 +147,6 @@ func (this *NumArray) SumRange(left int, right int) int { */ ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - */ -var NumArray = function (nums) { - const n = nums.length; - this.s = Array(n + 1).fill(0); - for (let i = 0; i < n; ++i) { - this.s[i + 1] = this.s[i] + nums[i]; - } -}; - -/** - * @param {number} left - * @param {number} right - * @return {number} - */ -NumArray.prototype.sumRange = function (left, right) { - return this.s[right + 1] - this.s[left]; -}; - -/** - * Your NumArray object will be instantiated and called as such: - * var obj = new NumArray(nums) - * var param_1 = obj.sumRange(left,right) - */ -``` - -### **TypeScript** - ```ts class NumArray { private s: number[]; @@ -217,8 +171,6 @@ class NumArray { */ ``` -### **Rust** - ```rust struct NumArray { s: Vec, @@ -248,44 +200,34 @@ impl NumArray { */ ``` -### **C** - -```c -typedef struct { - int* s; -} NumArray; - -NumArray* numArrayCreate(int* nums, int n) { - int* s = malloc(sizeof(int) * (n + 1)); - s[0] = 0; - for (int i = 0; i < n; i++) { - s[i + 1] = s[i] + nums[i]; +```js +/** + * @param {number[]} nums + */ +var NumArray = function (nums) { + const n = nums.length; + this.s = Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + this.s[i + 1] = this.s[i] + nums[i]; } - NumArray* obj = malloc(sizeof(NumArray)); - obj->s = s; - return obj; -} - -int numArraySumRange(NumArray* obj, int left, int right) { - return obj->s[right + 1] - obj->s[left]; -} - -void numArrayFree(NumArray* obj) { - free(obj->s); - free(obj); -} +}; /** - * Your NumArray struct will be instantiated and called as such: - * NumArray* obj = numArrayCreate(nums, numsSize); - * int param_1 = numArraySumRange(obj, left, right); + * @param {number} left + * @param {number} right + * @return {number} + */ +NumArray.prototype.sumRange = function (left, right) { + return this.s[right + 1] - this.s[left]; +}; - * numArrayFree(obj); -*/ +/** + * Your NumArray object will be instantiated and called as such: + * var obj = new NumArray(nums) + * var param_1 = obj.sumRange(left,right) + */ ``` -### **PHP** - ```php class NumArray { /** @@ -315,10 +257,40 @@ class NumArray { */ ``` -### **...** +```c +typedef struct { + int* s; +} NumArray; -``` +NumArray* numArrayCreate(int* nums, int n) { + int* s = malloc(sizeof(int) * (n + 1)); + s[0] = 0; + for (int i = 0; i < n; i++) { + s[i + 1] = s[i] + nums[i]; + } + NumArray* obj = malloc(sizeof(NumArray)); + obj->s = s; + return obj; +} + +int numArraySumRange(NumArray* obj, int left, int right) { + return obj->s[right + 1] - obj->s[left]; +} + +void numArrayFree(NumArray* obj) { + free(obj->s); + free(obj); +} +/** + * Your NumArray struct will be instantiated and called as such: + * NumArray* obj = numArrayCreate(nums, numsSize); + * int param_1 = numArraySumRange(obj, left, right); + + * numArrayFree(obj); +*/ ``` + + diff --git a/solution/0300-0399/0303.Range Sum Query - Immutable/README_EN.md b/solution/0300-0399/0303.Range Sum Query - Immutable/README_EN.md index 8f772fa24ec29..f02d729ce72a2 100644 --- a/solution/0300-0399/0303.Range Sum Query - Immutable/README_EN.md +++ b/solution/0300-0399/0303.Range Sum Query - Immutable/README_EN.md @@ -46,7 +46,7 @@ numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 ## Solutions -**Solution 1: Prefix Sum** +### Solution 1: Prefix Sum We create a prefix sum array $s$ of length $n + 1$, where $s[i]$ represents the prefix sum of the first $i$ elements, that is, $s[i] = \sum_{j=0}^{i-1} nums[j]$. Therefore, the sum of the elements between the indices $[left, right]$ can be expressed as $s[right + 1] - s[left]$. @@ -54,8 +54,6 @@ The time complexity for initializing the prefix sum array $s$ is $O(n)$, and the -### **Python3** - ```python class NumArray: def __init__(self, nums: List[int]): @@ -70,8 +68,6 @@ class NumArray: # param_1 = obj.sumRange(left,right) ``` -### **Java** - ```java class NumArray { private int[] s; @@ -96,8 +92,6 @@ class NumArray { */ ``` -### **C++** - ```cpp class NumArray { public: @@ -124,8 +118,6 @@ private: */ ``` -### **Go** - ```go type NumArray struct { s []int @@ -151,38 +143,6 @@ func (this *NumArray) SumRange(left int, right int) int { */ ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - */ -var NumArray = function (nums) { - const n = nums.length; - this.s = Array(n + 1).fill(0); - for (let i = 0; i < n; ++i) { - this.s[i + 1] = this.s[i] + nums[i]; - } -}; - -/** - * @param {number} left - * @param {number} right - * @return {number} - */ -NumArray.prototype.sumRange = function (left, right) { - return this.s[right + 1] - this.s[left]; -}; - -/** - * Your NumArray object will be instantiated and called as such: - * var obj = new NumArray(nums) - * var param_1 = obj.sumRange(left,right) - */ -``` - -### **TypeScript** - ```ts class NumArray { private s: number[]; @@ -207,8 +167,6 @@ class NumArray { */ ``` -### **Rust** - ```rust struct NumArray { s: Vec, @@ -238,44 +196,34 @@ impl NumArray { */ ``` -### **C** - -```c -typedef struct { - int* s; -} NumArray; - -NumArray* numArrayCreate(int* nums, int n) { - int* s = malloc(sizeof(int) * (n + 1)); - s[0] = 0; - for (int i = 0; i < n; i++) { - s[i + 1] = s[i] + nums[i]; +```js +/** + * @param {number[]} nums + */ +var NumArray = function (nums) { + const n = nums.length; + this.s = Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + this.s[i + 1] = this.s[i] + nums[i]; } - NumArray* obj = malloc(sizeof(NumArray)); - obj->s = s; - return obj; -} - -int numArraySumRange(NumArray* obj, int left, int right) { - return obj->s[right + 1] - obj->s[left]; -} - -void numArrayFree(NumArray* obj) { - free(obj->s); - free(obj); -} +}; /** - * Your NumArray struct will be instantiated and called as such: - * NumArray* obj = numArrayCreate(nums, numsSize); - * int param_1 = numArraySumRange(obj, left, right); + * @param {number} left + * @param {number} right + * @return {number} + */ +NumArray.prototype.sumRange = function (left, right) { + return this.s[right + 1] - this.s[left]; +}; - * numArrayFree(obj); -*/ +/** + * Your NumArray object will be instantiated and called as such: + * var obj = new NumArray(nums) + * var param_1 = obj.sumRange(left,right) + */ ``` -### **PHP** - ```php class NumArray { /** @@ -305,10 +253,40 @@ class NumArray { */ ``` -### **...** +```c +typedef struct { + int* s; +} NumArray; -``` +NumArray* numArrayCreate(int* nums, int n) { + int* s = malloc(sizeof(int) * (n + 1)); + s[0] = 0; + for (int i = 0; i < n; i++) { + s[i + 1] = s[i] + nums[i]; + } + NumArray* obj = malloc(sizeof(NumArray)); + obj->s = s; + return obj; +} +int numArraySumRange(NumArray* obj, int left, int right) { + return obj->s[right + 1] - obj->s[left]; +} + +void numArrayFree(NumArray* obj) { + free(obj->s); + free(obj); +} + +/** + * Your NumArray struct will be instantiated and called as such: + * NumArray* obj = numArrayCreate(nums, numsSize); + * int param_1 = numArraySumRange(obj, left, right); + + * numArrayFree(obj); +*/ ``` + + diff --git a/solution/0300-0399/0304.Range Sum Query 2D - Immutable/README.md b/solution/0300-0399/0304.Range Sum Query 2D - Immutable/README.md index 25fc40cb89adf..af8b18c366cd5 100644 --- a/solution/0300-0399/0304.Range Sum Query 2D - Immutable/README.md +++ b/solution/0300-0399/0304.Range Sum Query 2D - Immutable/README.md @@ -55,9 +55,7 @@ numMatrix.sumRegion(1, 2, 2, 4); // return 12 (蓝色矩形框的元素总和) ## 解法 - - -**方法一:二维前缀和** +### 方法一:二维前缀和 我们用 $s[i + 1][j + 1]$ 表示第 $i$ 行第 $j$ 列左上部分所有元素之和,下标 $i$ 和 $j$ 均从 $0$ 开始。可以得到以下前缀和公式: @@ -77,10 +75,6 @@ $$ -### **Python3** - - - ```python class NumMatrix: def __init__(self, matrix: List[List[int]]): @@ -106,10 +100,6 @@ class NumMatrix: # param_1 = obj.sumRegion(row1,col1,row2,col2) ``` -### **Java** - - - ```java class NumMatrix { private int[][] s; @@ -136,8 +126,6 @@ class NumMatrix { */ ``` -### **C++** - ```cpp class NumMatrix { public: @@ -165,9 +153,71 @@ public: */ ``` -### **Rust** +```go +type NumMatrix struct { + s [][]int +} + +func Constructor(matrix [][]int) NumMatrix { + m, n := len(matrix), len(matrix[0]) + s := make([][]int, m+1) + for i := range s { + s[i] = make([]int, n+1) + } + for i, row := range matrix { + for j, v := range row { + s[i+1][j+1] = s[i+1][j] + s[i][j+1] - s[i][j] + v + } + } + return NumMatrix{s} +} + +func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { + return this.s[row2+1][col2+1] - this.s[row2+1][col1] - this.s[row1][col2+1] + this.s[row1][col1] +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * obj := Constructor(matrix); + * param_1 := obj.SumRegion(row1,col1,row2,col2); + */ +``` + +```ts +class NumMatrix { + private s: number[][]; + + constructor(matrix: number[][]) { + const m = matrix.length; + const n = matrix[0].length; + this.s = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + this.s[i + 1][j + 1] = + this.s[i + 1][j] + this.s[i][j + 1] - this.s[i][j] + matrix[i][j]; + } + } + } + + sumRegion(row1: number, col1: number, row2: number, col2: number): number { + return ( + this.s[row2 + 1][col2 + 1] - + this.s[row2 + 1][col1] - + this.s[row1][col2 + 1] + + this.s[row1][col1] + ); + } +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * var obj = new NumMatrix(matrix) + * var param_1 = obj.sumRegion(row1,col1,row2,col2) + */ +``` ```rust + /** * Your NumMatrix object will be instantiated and called as such: * let obj = NumMatrix::new(matrix); @@ -230,40 +280,6 @@ impl NumMatrix { } ``` -### **Go** - -```go -type NumMatrix struct { - s [][]int -} - -func Constructor(matrix [][]int) NumMatrix { - m, n := len(matrix), len(matrix[0]) - s := make([][]int, m+1) - for i := range s { - s[i] = make([]int, n+1) - } - for i, row := range matrix { - for j, v := range row { - s[i+1][j+1] = s[i+1][j] + s[i][j+1] - s[i][j] + v - } - } - return NumMatrix{s} -} - -func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { - return this.s[row2+1][col2+1] - this.s[row2+1][col1] - this.s[row1][col2+1] + this.s[row1][col1] -} - -/** - * Your NumMatrix object will be instantiated and called as such: - * obj := Constructor(matrix); - * param_1 := obj.SumRegion(row1,col1,row2,col2); - */ -``` - -### **JavaScript** - ```js /** * @param {number[][]} matrix @@ -303,45 +319,6 @@ NumMatrix.prototype.sumRegion = function (row1, col1, row2, col2) { */ ``` -### **TypeScript** - -```ts -class NumMatrix { - private s: number[][]; - - constructor(matrix: number[][]) { - const m = matrix.length; - const n = matrix[0].length; - this.s = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - this.s[i + 1][j + 1] = - this.s[i + 1][j] + this.s[i][j + 1] - this.s[i][j] + matrix[i][j]; - } - } - } - - sumRegion(row1: number, col1: number, row2: number, col2: number): number { - return ( - this.s[row2 + 1][col2 + 1] - - this.s[row2 + 1][col1] - - this.s[row1][col2 + 1] + - this.s[row1][col1] - ); - } -} - -/** - * Your NumMatrix object will be instantiated and called as such: - * var obj = new NumMatrix(matrix) - * var param_1 = obj.sumRegion(row1,col1,row2,col2) - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0304.Range Sum Query 2D - Immutable/README_EN.md b/solution/0300-0399/0304.Range Sum Query 2D - Immutable/README_EN.md index e02447a18ab1b..d32fe101d7055 100644 --- a/solution/0300-0399/0304.Range Sum Query 2D - Immutable/README_EN.md +++ b/solution/0300-0399/0304.Range Sum Query 2D - Immutable/README_EN.md @@ -52,7 +52,7 @@ numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) ## Solutions -**Solution 1: Two-dimensional Prefix Sum** +### Solution 1: Two-dimensional Prefix Sum We use $s[i + 1][j + 1]$ to represent the sum of all elements in the upper left part of the $i$th row and $j$th column, where indices $i$ and $j$ both start from $0$. We can get the following prefix sum formula: @@ -72,8 +72,6 @@ The time complexity for initializing is $O(m \times n)$, and the time complexity -### **Python3** - ```python class NumMatrix: def __init__(self, matrix: List[List[int]]): @@ -99,8 +97,6 @@ class NumMatrix: # param_1 = obj.sumRegion(row1,col1,row2,col2) ``` -### **Java** - ```java class NumMatrix { private int[][] s; @@ -127,8 +123,6 @@ class NumMatrix { */ ``` -### **C++** - ```cpp class NumMatrix { public: @@ -156,7 +150,68 @@ public: */ ``` -### **Rust** +```go +type NumMatrix struct { + s [][]int +} + +func Constructor(matrix [][]int) NumMatrix { + m, n := len(matrix), len(matrix[0]) + s := make([][]int, m+1) + for i := range s { + s[i] = make([]int, n+1) + } + for i, row := range matrix { + for j, v := range row { + s[i+1][j+1] = s[i+1][j] + s[i][j+1] - s[i][j] + v + } + } + return NumMatrix{s} +} + +func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { + return this.s[row2+1][col2+1] - this.s[row2+1][col1] - this.s[row1][col2+1] + this.s[row1][col1] +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * obj := Constructor(matrix); + * param_1 := obj.SumRegion(row1,col1,row2,col2); + */ +``` + +```ts +class NumMatrix { + private s: number[][]; + + constructor(matrix: number[][]) { + const m = matrix.length; + const n = matrix[0].length; + this.s = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + this.s[i + 1][j + 1] = + this.s[i + 1][j] + this.s[i][j + 1] - this.s[i][j] + matrix[i][j]; + } + } + } + + sumRegion(row1: number, col1: number, row2: number, col2: number): number { + return ( + this.s[row2 + 1][col2 + 1] - + this.s[row2 + 1][col1] - + this.s[row1][col2 + 1] + + this.s[row1][col1] + ); + } +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * var obj = new NumMatrix(matrix) + * var param_1 = obj.sumRegion(row1,col1,row2,col2) + */ +``` ```rust @@ -222,40 +277,6 @@ impl NumMatrix { } ``` -### **Go** - -```go -type NumMatrix struct { - s [][]int -} - -func Constructor(matrix [][]int) NumMatrix { - m, n := len(matrix), len(matrix[0]) - s := make([][]int, m+1) - for i := range s { - s[i] = make([]int, n+1) - } - for i, row := range matrix { - for j, v := range row { - s[i+1][j+1] = s[i+1][j] + s[i][j+1] - s[i][j] + v - } - } - return NumMatrix{s} -} - -func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { - return this.s[row2+1][col2+1] - this.s[row2+1][col1] - this.s[row1][col2+1] + this.s[row1][col1] -} - -/** - * Your NumMatrix object will be instantiated and called as such: - * obj := Constructor(matrix); - * param_1 := obj.SumRegion(row1,col1,row2,col2); - */ -``` - -### **JavaScript** - ```js /** * @param {number[][]} matrix @@ -295,45 +316,6 @@ NumMatrix.prototype.sumRegion = function (row1, col1, row2, col2) { */ ``` -### **TypeScript** - -```ts -class NumMatrix { - private s: number[][]; - - constructor(matrix: number[][]) { - const m = matrix.length; - const n = matrix[0].length; - this.s = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0)); - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - this.s[i + 1][j + 1] = - this.s[i + 1][j] + this.s[i][j + 1] - this.s[i][j] + matrix[i][j]; - } - } - } - - sumRegion(row1: number, col1: number, row2: number, col2: number): number { - return ( - this.s[row2 + 1][col2 + 1] - - this.s[row2 + 1][col1] - - this.s[row1][col2 + 1] + - this.s[row1][col1] - ); - } -} - -/** - * Your NumMatrix object will be instantiated and called as such: - * var obj = new NumMatrix(matrix) - * var param_1 = obj.sumRegion(row1,col1,row2,col2) - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0305.Number of Islands II/README.md b/solution/0300-0399/0305.Number of Islands II/README.md index 594451a8d1ef5..db6c5c723d8c3 100644 --- a/solution/0300-0399/0305.Number of Islands II/README.md +++ b/solution/0300-0399/0305.Number of Islands II/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:并查集** +### 方法一:并查集 我们用一个二维数组 $grid$ 来表示一个地图,其中 $0$ 和 $1$ 分别表示水和陆地。初始时 $grid$ 中的所有单元格都是水单元格(即所有单元格都是 $0$),用一个变量 $cnt$ 来记录岛屿的数量。而岛屿之间的连通关系可以用一个并查集 $uf$ 来维护。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class UnionFind: def __init__(self, n: int): @@ -119,10 +113,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class UnionFind { private final int[] p; @@ -189,8 +179,6 @@ class Solution { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -256,8 +244,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p, size []int @@ -323,8 +309,6 @@ func numIslands2(m int, n int, positions [][]int) (ans []int) { } ``` -## **TypeScript** - ```ts class UnionFind { p: number[]; @@ -387,10 +371,6 @@ function numIslands2(m: number, n: number, positions: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0305.Number of Islands II/README_EN.md b/solution/0300-0399/0305.Number of Islands II/README_EN.md index bf2258fd6956b..f47a7c481cd59 100644 --- a/solution/0300-0399/0305.Number of Islands II/README_EN.md +++ b/solution/0300-0399/0305.Number of Islands II/README_EN.md @@ -49,7 +49,7 @@ Initially, the 2d grid is filled with water. ## Solutions -**Solution 1: Union-Find** +### Solution 1: Union-Find We use a two-dimensional array $grid$ to represent a map, where $0$ and $1$ represent water and land respectively. Initially, all cells in $grid$ are water cells (i.e., all cells are $0$), and we use a variable $cnt$ to record the number of islands. The connectivity between islands can be maintained by a union-find set $uf$. @@ -59,8 +59,6 @@ The time complexity is $O(k \times \alpha(m \times n))$ or $O(k \times \log(m \t -### **Python3** - ```python class UnionFind: def __init__(self, n: int): @@ -111,8 +109,6 @@ class Solution: return ans ``` -### **Java** - ```java class UnionFind { private final int[] p; @@ -179,8 +175,6 @@ class Solution { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -246,8 +240,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p, size []int @@ -313,8 +305,6 @@ func numIslands2(m int, n int, positions [][]int) (ans []int) { } ``` -## **TypeScript** - ```ts class UnionFind { p: number[]; @@ -377,10 +367,6 @@ function numIslands2(m: number, n: number, positions: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0306.Additive Number/README.md b/solution/0300-0399/0306.Additive Number/README.md index 2d0f2e98fcb1a..70bd415b517ba 100644 --- a/solution/0300-0399/0306.Additive Number/README.md +++ b/solution/0300-0399/0306.Additive Number/README.md @@ -46,18 +46,10 @@ ## 解法 - - -DFS + 剪枝。 - -Python 大整数相加不会有溢出问题。由于 num 字符串长度最大为 35,因此对于其他语言,可以通过控制整数长度防止溢出。 +### 方法一 -### **Python3** - - - ```python class Solution: def isAdditiveNumber(self, num: str) -> bool: @@ -84,10 +76,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean isAdditiveNumber(String num) { @@ -129,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +146,6 @@ public: }; ``` -### **Go** - ```go func isAdditiveNumber(num string) bool { n := len(num) @@ -202,10 +186,6 @@ func isAdditiveNumber(num string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0306.Additive Number/README_EN.md b/solution/0300-0399/0306.Additive Number/README_EN.md index bc98d4203038c..2786873d37a03 100644 --- a/solution/0300-0399/0306.Additive Number/README_EN.md +++ b/solution/0300-0399/0306.Additive Number/README_EN.md @@ -46,9 +46,9 @@ The additive sequence is: 1, 99, 100, 199.  ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean isAdditiveNumber(String num) { @@ -119,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +146,6 @@ public: }; ``` -### **Go** - ```go func isAdditiveNumber(num string) bool { n := len(num) @@ -192,10 +186,6 @@ func isAdditiveNumber(num string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0307.Range Sum Query - Mutable/README.md b/solution/0300-0399/0307.Range Sum Query - Mutable/README.md index 8413741c05ec6..f250381559b35 100644 --- a/solution/0300-0399/0307.Range Sum Query - Mutable/README.md +++ b/solution/0300-0399/0307.Range Sum Query - Mutable/README.md @@ -54,9 +54,7 @@ numArray.sumRange(0, 2); // 返回 1 + 2 + 5 = 8 ## 解法 - - -**方法一:树状数组** +### 方法一:树状数组 树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作: @@ -75,23 +73,8 @@ numArray.sumRange(0, 2); // 返回 1 + 2 + 5 = 8 空间复杂度为 $O(n)$。 -**方法二:线段树** - -线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 $\log(width)$。更新某个元素的值,只需要更新 $\log(width)$ 个区间,并且这些区间都包含在一个包含该元素的大区间内。 - -- 线段树的每个节点代表一个区间; -- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 $[1, N]$; -- 线段树的每个叶子节点代表一个长度为 $1$ 的元区间 $[x, x]$; -- 对于每个内部节点 $[l, r]$,它的左儿子是 $[l, mid]$,右儿子是 $[mid + 1, r]$, 其中 $mid = \lfloor \frac{l + r}{2} \rfloor$(即向下取整)。 - -对于本题,构造函数的时间复杂度为 $O(n \log n)$,其他操作的时间复杂度为 $O(\log n)$。空间复杂度为 $O(n)$。 - -### **Python3** - - - ```python class BinaryIndexedTree: __slots__ = ["n", "c"] @@ -135,6 +118,297 @@ class NumArray: # param_2 = obj.sumRange(left,right) ``` +```java +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +} + +class NumArray { + private BinaryIndexedTree tree; + + public NumArray(int[] nums) { + int n = nums.length; + tree = new BinaryIndexedTree(n); + for (int i = 0; i < n; ++i) { + tree.update(i + 1, nums[i]); + } + } + + public void update(int index, int val) { + int prev = sumRange(index, index); + tree.update(index + 1, val - prev); + } + + public int sumRange(int left, int right) { + return tree.query(right + 1) - tree.query(left); + } +} + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray obj = new NumArray(nums); + * obj.update(index,val); + * int param_2 = obj.sumRange(left,right); + */ +``` + +```cpp +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +}; + +class NumArray { +public: + BinaryIndexedTree* tree; + + NumArray(vector& nums) { + int n = nums.size(); + tree = new BinaryIndexedTree(n); + for (int i = 0; i < n; ++i) tree->update(i + 1, nums[i]); + } + + void update(int index, int val) { + int prev = sumRange(index, index); + tree->update(index + 1, val - prev); + } + + int sumRange(int left, int right) { + return tree->query(right + 1) - tree->query(left); + } +}; + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray* obj = new NumArray(nums); + * obj->update(index,val); + * int param_2 = obj->sumRange(left,right); + */ +``` + +```go +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (t *BinaryIndexedTree) update(x, delta int) { + for ; x <= t.n; x += x & -x { + t.c[x] += delta + } +} + +func (t *BinaryIndexedTree) query(x int) (s int) { + for ; x > 0; x -= x & -x { + s += t.c[x] + } + return s +} + +type NumArray struct { + tree *BinaryIndexedTree +} + +func Constructor(nums []int) NumArray { + tree := newBinaryIndexedTree(len(nums)) + for i, v := range nums { + tree.update(i+1, v) + } + return NumArray{tree} +} + +func (t *NumArray) Update(index int, val int) { + prev := t.SumRange(index, index) + t.tree.update(index+1, val-prev) +} + +func (t *NumArray) SumRange(left int, right int) int { + return t.tree.query(right+1) - t.tree.query(left) +} + +/** + * Your NumArray object will be instantiated and called as such: + * obj := Constructor(nums); + * obj.Update(index,val); + * param_2 := obj.SumRange(left,right); + */ +``` + +```ts +class BinaryIndexedTree { + private n: number; + private c: number[]; + + constructor(n: number) { + this.n = n; + this.c = Array(n + 1).fill(0); + } + + update(x: number, delta: number): void { + while (x <= this.n) { + this.c[x] += delta; + x += x & -x; + } + } + + query(x: number): number { + let s = 0; + while (x > 0) { + s += this.c[x]; + x -= x & -x; + } + return s; + } +} + +class NumArray { + private tree: BinaryIndexedTree; + + constructor(nums: number[]) { + const n = nums.length; + this.tree = new BinaryIndexedTree(n); + for (let i = 0; i < n; ++i) { + this.tree.update(i + 1, nums[i]); + } + } + + update(index: number, val: number): void { + const prev = this.sumRange(index, index); + this.tree.update(index + 1, val - prev); + } + + sumRange(left: number, right: number): number { + return this.tree.query(right + 1) - this.tree.query(left); + } +} + +/** + * Your NumArray object will be instantiated and called as such: + * var obj = new NumArray(nums) + * obj.update(index,val) + * var param_2 = obj.sumRange(left,right) + */ +``` + +```cs +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void Update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + public int Query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +} + +public class NumArray { + private BinaryIndexedTree tree; + + public NumArray(int[] nums) { + int n = nums.Length; + tree = new BinaryIndexedTree(n); + for (int i = 0; i < n; ++i) { + tree.Update(i + 1, nums[i]); + } + } + + public void Update(int index, int val) { + int prev = SumRange(index, index); + tree.Update(index + 1, val - prev); + } + + public int SumRange(int left, int right) { + return tree.Query(right + 1) - tree.Query(left); + } +} + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray obj = new NumArray(nums); + * obj.Update(index,val); + * int param_2 = obj.SumRange(left,right); + */ +``` + + + +### 方法二:线段树 + +线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 $\log(width)$。更新某个元素的值,只需要更新 $\log(width)$ 个区间,并且这些区间都包含在一个包含该元素的大区间内。 + +- 线段树的每个节点代表一个区间; +- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 $[1, N]$; +- 线段树的每个叶子节点代表一个长度为 $1$ 的元区间 $[x, x]$; +- 对于每个内部节点 $[l, r]$,它的左儿子是 $[l, mid]$,右儿子是 $[mid + 1, r]$, 其中 $mid = \lfloor \frac{l + r}{2} \rfloor$(即向下取整)。 + +对于本题,构造函数的时间复杂度为 $O(n \log n)$,其他操作的时间复杂度为 $O(\log n)$。空间复杂度为 $O(n)$。 + + + ```python class Node: __slots__ = ["l", "r", "v"] @@ -191,80 +465,20 @@ class SegmentTree: class NumArray: __slots__ = ["tree"] - def __init__(self, nums: List[int]): - self.tree = SegmentTree(nums) - - def update(self, index: int, val: int) -> None: - self.tree.modify(1, index + 1, val) - - def sumRange(self, left: int, right: int) -> int: - return self.tree.query(1, left + 1, right + 1) - - -# Your NumArray object will be instantiated and called as such: -# obj = NumArray(nums) -# obj.update(index,val) -# param_2 = obj.sumRange(left,right) -``` - -### **Java** - - - -```java -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += x & -x; - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= x & -x; - } - return s; - } -} - -class NumArray { - private BinaryIndexedTree tree; - - public NumArray(int[] nums) { - int n = nums.length; - tree = new BinaryIndexedTree(n); - for (int i = 0; i < n; ++i) { - tree.update(i + 1, nums[i]); - } - } - - public void update(int index, int val) { - int prev = sumRange(index, index); - tree.update(index + 1, val - prev); - } + def __init__(self, nums: List[int]): + self.tree = SegmentTree(nums) - public int sumRange(int left, int right) { - return tree.query(right + 1) - tree.query(left); - } -} + def update(self, index: int, val: int) -> None: + self.tree.modify(1, index + 1, val) -/** - * Your NumArray object will be instantiated and called as such: - * NumArray obj = new NumArray(nums); - * obj.update(index,val); - * int param_2 = obj.sumRange(left,right); - */ + def sumRange(self, left: int, right: int) -> int: + return self.tree.query(1, left + 1, right + 1) + + +# Your NumArray object will be instantiated and called as such: +# obj = NumArray(nums) +# obj.update(index,val) +# param_2 = obj.sumRange(left,right) ``` ```java @@ -359,63 +573,6 @@ class NumArray { */ ``` -### **C++** - -```cpp -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += x & -x; - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= x & -x; - } - return s; - } -}; - -class NumArray { -public: - BinaryIndexedTree* tree; - - NumArray(vector& nums) { - int n = nums.size(); - tree = new BinaryIndexedTree(n); - for (int i = 0; i < n; ++i) tree->update(i + 1, nums[i]); - } - - void update(int index, int val) { - int prev = sumRange(index, index); - tree->update(index + 1, val - prev); - } - - int sumRange(int left, int right) { - return tree->query(right + 1) - tree->query(left); - } -}; - -/** - * Your NumArray object will be instantiated and called as such: - * NumArray* obj = new NumArray(nums); - * obj->update(index,val); - * int param_2 = obj->sumRange(left,right); - */ -``` - ```cpp class Node { public: @@ -502,61 +659,6 @@ public: */ ``` -### **Go** - -```go -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (t *BinaryIndexedTree) update(x, delta int) { - for ; x <= t.n; x += x & -x { - t.c[x] += delta - } -} - -func (t *BinaryIndexedTree) query(x int) (s int) { - for ; x > 0; x -= x & -x { - s += t.c[x] - } - return s -} - -type NumArray struct { - tree *BinaryIndexedTree -} - -func Constructor(nums []int) NumArray { - tree := newBinaryIndexedTree(len(nums)) - for i, v := range nums { - tree.update(i+1, v) - } - return NumArray{tree} -} - -func (t *NumArray) Update(index int, val int) { - prev := t.SumRange(index, index) - t.tree.update(index+1, val-prev) -} - -func (t *NumArray) SumRange(left int, right int) int { - return t.tree.query(right+1) - t.tree.query(left) -} - -/** - * Your NumArray object will be instantiated and called as such: - * obj := Constructor(nums); - * obj.Update(index,val); - * param_2 := obj.SumRange(left,right); - */ -``` - ```go type Node struct { l, r, v int @@ -651,64 +753,6 @@ func (this *NumArray) SumRange(left int, right int) int { */ ``` -### **TypeScript** - -```ts -class BinaryIndexedTree { - private n: number; - private c: number[]; - - constructor(n: number) { - this.n = n; - this.c = Array(n + 1).fill(0); - } - - update(x: number, delta: number): void { - while (x <= this.n) { - this.c[x] += delta; - x += x & -x; - } - } - - query(x: number): number { - let s = 0; - while (x > 0) { - s += this.c[x]; - x -= x & -x; - } - return s; - } -} - -class NumArray { - private tree: BinaryIndexedTree; - - constructor(nums: number[]) { - const n = nums.length; - this.tree = new BinaryIndexedTree(n); - for (let i = 0; i < n; ++i) { - this.tree.update(i + 1, nums[i]); - } - } - - update(index: number, val: number): void { - const prev = this.sumRange(index, index); - this.tree.update(index + 1, val - prev); - } - - sumRange(left: number, right: number): number { - return this.tree.query(right + 1) - this.tree.query(left); - } -} - -/** - * Your NumArray object will be instantiated and called as such: - * var obj = new NumArray(nums) - * obj.update(index,val) - * var param_2 = obj.sumRange(left,right) - */ -``` - ```ts class Node { l: number; @@ -801,64 +845,6 @@ class NumArray { */ ``` -### **C#** - -```cs -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void Update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += x & -x; - } - } - - public int Query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= x & -x; - } - return s; - } -} - -public class NumArray { - private BinaryIndexedTree tree; - - public NumArray(int[] nums) { - int n = nums.Length; - tree = new BinaryIndexedTree(n); - for (int i = 0; i < n; ++i) { - tree.Update(i + 1, nums[i]); - } - } - - public void Update(int index, int val) { - int prev = SumRange(index, index); - tree.Update(index + 1, val - prev); - } - - public int SumRange(int left, int right) { - return tree.Query(right + 1) - tree.Query(left); - } -} - -/** - * Your NumArray object will be instantiated and called as such: - * NumArray obj = new NumArray(nums); - * obj.Update(index,val); - * int param_2 = obj.SumRange(left,right); - */ -``` - ```cs public class Node { public int l; @@ -951,10 +937,6 @@ public class NumArray { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0307.Range Sum Query - Mutable/README_EN.md b/solution/0300-0399/0307.Range Sum Query - Mutable/README_EN.md index 864210d224a13..febd5fafe2915 100644 --- a/solution/0300-0399/0307.Range Sum Query - Mutable/README_EN.md +++ b/solution/0300-0399/0307.Range Sum Query - Mutable/README_EN.md @@ -50,12 +50,10 @@ numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8 ## Solutions -Binary Indexed Tree or Segment Tree. +### Solution 1 -### **Python3** - ```python class BinaryIndexedTree: __slots__ = ["n", "c"] @@ -99,6 +97,288 @@ class NumArray: # param_2 = obj.sumRange(left,right) ``` +```java +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +} + +class NumArray { + private BinaryIndexedTree tree; + + public NumArray(int[] nums) { + int n = nums.length; + tree = new BinaryIndexedTree(n); + for (int i = 0; i < n; ++i) { + tree.update(i + 1, nums[i]); + } + } + + public void update(int index, int val) { + int prev = sumRange(index, index); + tree.update(index + 1, val - prev); + } + + public int sumRange(int left, int right) { + return tree.query(right + 1) - tree.query(left); + } +} + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray obj = new NumArray(nums); + * obj.update(index,val); + * int param_2 = obj.sumRange(left,right); + */ +``` + +```cpp +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +}; + +class NumArray { +public: + BinaryIndexedTree* tree; + + NumArray(vector& nums) { + int n = nums.size(); + tree = new BinaryIndexedTree(n); + for (int i = 0; i < n; ++i) tree->update(i + 1, nums[i]); + } + + void update(int index, int val) { + int prev = sumRange(index, index); + tree->update(index + 1, val - prev); + } + + int sumRange(int left, int right) { + return tree->query(right + 1) - tree->query(left); + } +}; + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray* obj = new NumArray(nums); + * obj->update(index,val); + * int param_2 = obj->sumRange(left,right); + */ +``` + +```go +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (t *BinaryIndexedTree) update(x, delta int) { + for ; x <= t.n; x += x & -x { + t.c[x] += delta + } +} + +func (t *BinaryIndexedTree) query(x int) (s int) { + for ; x > 0; x -= x & -x { + s += t.c[x] + } + return s +} + +type NumArray struct { + tree *BinaryIndexedTree +} + +func Constructor(nums []int) NumArray { + tree := newBinaryIndexedTree(len(nums)) + for i, v := range nums { + tree.update(i+1, v) + } + return NumArray{tree} +} + +func (t *NumArray) Update(index int, val int) { + prev := t.SumRange(index, index) + t.tree.update(index+1, val-prev) +} + +func (t *NumArray) SumRange(left int, right int) int { + return t.tree.query(right+1) - t.tree.query(left) +} + +/** + * Your NumArray object will be instantiated and called as such: + * obj := Constructor(nums); + * obj.Update(index,val); + * param_2 := obj.SumRange(left,right); + */ +``` + +```ts +class BinaryIndexedTree { + private n: number; + private c: number[]; + + constructor(n: number) { + this.n = n; + this.c = Array(n + 1).fill(0); + } + + update(x: number, delta: number): void { + while (x <= this.n) { + this.c[x] += delta; + x += x & -x; + } + } + + query(x: number): number { + let s = 0; + while (x > 0) { + s += this.c[x]; + x -= x & -x; + } + return s; + } +} + +class NumArray { + private tree: BinaryIndexedTree; + + constructor(nums: number[]) { + const n = nums.length; + this.tree = new BinaryIndexedTree(n); + for (let i = 0; i < n; ++i) { + this.tree.update(i + 1, nums[i]); + } + } + + update(index: number, val: number): void { + const prev = this.sumRange(index, index); + this.tree.update(index + 1, val - prev); + } + + sumRange(left: number, right: number): number { + return this.tree.query(right + 1) - this.tree.query(left); + } +} + +/** + * Your NumArray object will be instantiated and called as such: + * var obj = new NumArray(nums) + * obj.update(index,val) + * var param_2 = obj.sumRange(left,right) + */ +``` + +```cs +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void Update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + public int Query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +} + +public class NumArray { + private BinaryIndexedTree tree; + + public NumArray(int[] nums) { + int n = nums.Length; + tree = new BinaryIndexedTree(n); + for (int i = 0; i < n; ++i) { + tree.Update(i + 1, nums[i]); + } + } + + public void Update(int index, int val) { + int prev = SumRange(index, index); + tree.Update(index + 1, val - prev); + } + + public int SumRange(int left, int right) { + return tree.Query(right + 1) - tree.Query(left); + } +} + +/** + * Your NumArray object will be instantiated and called as such: + * NumArray obj = new NumArray(nums); + * obj.Update(index,val); + * int param_2 = obj.SumRange(left,right); + */ +``` + + + +### Solution 2 + + + ```python class Node: __slots__ = ["l", "r", "v"] @@ -155,78 +435,20 @@ class SegmentTree: class NumArray: __slots__ = ["tree"] - def __init__(self, nums: List[int]): - self.tree = SegmentTree(nums) - - def update(self, index: int, val: int) -> None: - self.tree.modify(1, index + 1, val) - - def sumRange(self, left: int, right: int) -> int: - return self.tree.query(1, left + 1, right + 1) - - -# Your NumArray object will be instantiated and called as such: -# obj = NumArray(nums) -# obj.update(index,val) -# param_2 = obj.sumRange(left,right) -``` - -### **Java** - -```java -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += x & -x; - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= x & -x; - } - return s; - } -} - -class NumArray { - private BinaryIndexedTree tree; - - public NumArray(int[] nums) { - int n = nums.length; - tree = new BinaryIndexedTree(n); - for (int i = 0; i < n; ++i) { - tree.update(i + 1, nums[i]); - } - } - - public void update(int index, int val) { - int prev = sumRange(index, index); - tree.update(index + 1, val - prev); - } + def __init__(self, nums: List[int]): + self.tree = SegmentTree(nums) - public int sumRange(int left, int right) { - return tree.query(right + 1) - tree.query(left); - } -} + def update(self, index: int, val: int) -> None: + self.tree.modify(1, index + 1, val) -/** - * Your NumArray object will be instantiated and called as such: - * NumArray obj = new NumArray(nums); - * obj.update(index,val); - * int param_2 = obj.sumRange(left,right); - */ + def sumRange(self, left: int, right: int) -> int: + return self.tree.query(1, left + 1, right + 1) + + +# Your NumArray object will be instantiated and called as such: +# obj = NumArray(nums) +# obj.update(index,val) +# param_2 = obj.sumRange(left,right) ``` ```java @@ -321,63 +543,6 @@ class NumArray { */ ``` -### **C++** - -```cpp -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += x & -x; - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= x & -x; - } - return s; - } -}; - -class NumArray { -public: - BinaryIndexedTree* tree; - - NumArray(vector& nums) { - int n = nums.size(); - tree = new BinaryIndexedTree(n); - for (int i = 0; i < n; ++i) tree->update(i + 1, nums[i]); - } - - void update(int index, int val) { - int prev = sumRange(index, index); - tree->update(index + 1, val - prev); - } - - int sumRange(int left, int right) { - return tree->query(right + 1) - tree->query(left); - } -}; - -/** - * Your NumArray object will be instantiated and called as such: - * NumArray* obj = new NumArray(nums); - * obj->update(index,val); - * int param_2 = obj->sumRange(left,right); - */ -``` - ```cpp class Node { public: @@ -464,61 +629,6 @@ public: */ ``` -### **Go** - -```go -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (t *BinaryIndexedTree) update(x, delta int) { - for ; x <= t.n; x += x & -x { - t.c[x] += delta - } -} - -func (t *BinaryIndexedTree) query(x int) (s int) { - for ; x > 0; x -= x & -x { - s += t.c[x] - } - return s -} - -type NumArray struct { - tree *BinaryIndexedTree -} - -func Constructor(nums []int) NumArray { - tree := newBinaryIndexedTree(len(nums)) - for i, v := range nums { - tree.update(i+1, v) - } - return NumArray{tree} -} - -func (t *NumArray) Update(index int, val int) { - prev := t.SumRange(index, index) - t.tree.update(index+1, val-prev) -} - -func (t *NumArray) SumRange(left int, right int) int { - return t.tree.query(right+1) - t.tree.query(left) -} - -/** - * Your NumArray object will be instantiated and called as such: - * obj := Constructor(nums); - * obj.Update(index,val); - * param_2 := obj.SumRange(left,right); - */ -``` - ```go type Node struct { l, r, v int @@ -613,64 +723,6 @@ func (this *NumArray) SumRange(left int, right int) int { */ ``` -### **TypeScript** - -```ts -class BinaryIndexedTree { - private n: number; - private c: number[]; - - constructor(n: number) { - this.n = n; - this.c = Array(n + 1).fill(0); - } - - update(x: number, delta: number): void { - while (x <= this.n) { - this.c[x] += delta; - x += x & -x; - } - } - - query(x: number): number { - let s = 0; - while (x > 0) { - s += this.c[x]; - x -= x & -x; - } - return s; - } -} - -class NumArray { - private tree: BinaryIndexedTree; - - constructor(nums: number[]) { - const n = nums.length; - this.tree = new BinaryIndexedTree(n); - for (let i = 0; i < n; ++i) { - this.tree.update(i + 1, nums[i]); - } - } - - update(index: number, val: number): void { - const prev = this.sumRange(index, index); - this.tree.update(index + 1, val - prev); - } - - sumRange(left: number, right: number): number { - return this.tree.query(right + 1) - this.tree.query(left); - } -} - -/** - * Your NumArray object will be instantiated and called as such: - * var obj = new NumArray(nums) - * obj.update(index,val) - * var param_2 = obj.sumRange(left,right) - */ -``` - ```ts class Node { l: number; @@ -763,64 +815,6 @@ class NumArray { */ ``` -### **C#** - -```cs -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void Update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += x & -x; - } - } - - public int Query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= x & -x; - } - return s; - } -} - -public class NumArray { - private BinaryIndexedTree tree; - - public NumArray(int[] nums) { - int n = nums.Length; - tree = new BinaryIndexedTree(n); - for (int i = 0; i < n; ++i) { - tree.Update(i + 1, nums[i]); - } - } - - public void Update(int index, int val) { - int prev = SumRange(index, index); - tree.Update(index + 1, val - prev); - } - - public int SumRange(int left, int right) { - return tree.Query(right + 1) - tree.Query(left); - } -} - -/** - * Your NumArray object will be instantiated and called as such: - * NumArray obj = new NumArray(nums); - * obj.Update(index,val); - * int param_2 = obj.SumRange(left,right); - */ -``` - ```cs public class Node { public int l; @@ -913,10 +907,6 @@ public class NumArray { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0308.Range Sum Query 2D - Mutable/README.md b/solution/0300-0399/0308.Range Sum Query 2D - Mutable/README.md index e597cf2c81c99..8f4da9b791825 100644 --- a/solution/0300-0399/0308.Range Sum Query 2D - Mutable/README.md +++ b/solution/0300-0399/0308.Range Sum Query 2D - Mutable/README.md @@ -59,9 +59,7 @@ numMatrix.sumRegion(2, 1, 4, 3); // 返回 10 (即,右侧红色矩形的和) ## 解法 - - -**方法一:树状数组** +### 方法一:树状数组 树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作: @@ -72,23 +70,8 @@ numMatrix.sumRegion(2, 1, 4, 3); // 返回 10 (即,右侧红色矩形的和) 对于本题,可以构建二维树状数组。 -**方法二:线段树** - -线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。 - -- 线段树的每个节点代表一个区间; -- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 `[1, N]`; -- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`; -- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。 - -### **Python3** - - - -树状数组: - ```python class BinaryIndexedTree: def __init__(self, n): @@ -140,7 +123,230 @@ class NumMatrix: # param_2 = obj.sumRegion(row1,col1,row2,col2) ``` -线段树: +```java +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + public static int lowbit(int x) { + return x & -x; + } +} + +class NumMatrix { + private BinaryIndexedTree[] trees; + + public NumMatrix(int[][] matrix) { + int m = matrix.length; + int n = matrix[0].length; + trees = new BinaryIndexedTree[m]; + for (int i = 0; i < m; ++i) { + BinaryIndexedTree tree = new BinaryIndexedTree(n); + for (int j = 0; j < n; ++j) { + tree.update(j + 1, matrix[i][j]); + } + trees[i] = tree; + } + } + + public void update(int row, int col, int val) { + BinaryIndexedTree tree = trees[row]; + int prev = tree.query(col + 1) - tree.query(col); + tree.update(col + 1, val - prev); + } + + public int sumRegion(int row1, int col1, int row2, int col2) { + int s = 0; + for (int i = row1; i <= row2; ++i) { + BinaryIndexedTree tree = trees[i]; + s += tree.query(col2 + 1) - tree.query(col1); + } + return s; + } +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * NumMatrix obj = new NumMatrix(matrix); + * obj.update(row,col,val); + * int param_2 = obj.sumRegion(row1,col1,row2,col2); + */ +``` + +```cpp +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + int lowbit(int x) { + return x & -x; + } +}; + +class NumMatrix { +public: + vector trees; + + NumMatrix(vector>& matrix) { + int m = matrix.size(); + int n = matrix[0].size(); + trees.resize(m); + for (int i = 0; i < m; ++i) { + BinaryIndexedTree* tree = new BinaryIndexedTree(n); + for (int j = 0; j < n; ++j) tree->update(j + 1, matrix[i][j]); + trees[i] = tree; + } + } + + void update(int row, int col, int val) { + BinaryIndexedTree* tree = trees[row]; + int prev = tree->query(col + 1) - tree->query(col); + tree->update(col + 1, val - prev); + } + + int sumRegion(int row1, int col1, int row2, int col2) { + int s = 0; + for (int i = row1; i <= row2; ++i) { + BinaryIndexedTree* tree = trees[i]; + s += tree->query(col2 + 1) - tree->query(col1); + } + return s; + } +}; + +/** + * Your NumMatrix object will be instantiated and called as such: + * NumMatrix* obj = new NumMatrix(matrix); + * obj->update(row,col,val); + * int param_2 = obj->sumRegion(row1,col1,row2,col2); + */ +``` + +```go +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) lowbit(x int) int { + return x & -x +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += this.lowbit(x) + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= this.lowbit(x) + } + return s +} + +type NumMatrix struct { + trees []*BinaryIndexedTree +} + +func Constructor(matrix [][]int) NumMatrix { + n := len(matrix[0]) + var trees []*BinaryIndexedTree + for _, row := range matrix { + tree := newBinaryIndexedTree(n) + for j, v := range row { + tree.update(j+1, v) + } + trees = append(trees, tree) + } + return NumMatrix{trees} +} + +func (this *NumMatrix) Update(row int, col int, val int) { + tree := this.trees[row] + prev := tree.query(col+1) - tree.query(col) + tree.update(col+1, val-prev) +} + +func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { + s := 0 + for i := row1; i <= row2; i++ { + tree := this.trees[i] + s += tree.query(col2+1) - tree.query(col1) + } + return s +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * obj := Constructor(matrix); + * obj.Update(row,col,val); + * param_2 := obj.SumRegion(row1,col1,row2,col2); + */ +``` + + + +### 方法二:线段树 + +线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。 + +- 线段树的每个节点代表一个区间; +- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 `[1, N]`; +- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`; +- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。 + + ```python class Node: @@ -215,85 +421,6 @@ class NumMatrix: # param_2 = obj.sumRegion(row1,col1,row2,col2) ``` -### **Java** - - - -树状数组: - -```java -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - public static int lowbit(int x) { - return x & -x; - } -} - -class NumMatrix { - private BinaryIndexedTree[] trees; - - public NumMatrix(int[][] matrix) { - int m = matrix.length; - int n = matrix[0].length; - trees = new BinaryIndexedTree[m]; - for (int i = 0; i < m; ++i) { - BinaryIndexedTree tree = new BinaryIndexedTree(n); - for (int j = 0; j < n; ++j) { - tree.update(j + 1, matrix[i][j]); - } - trees[i] = tree; - } - } - - public void update(int row, int col, int val) { - BinaryIndexedTree tree = trees[row]; - int prev = tree.query(col + 1) - tree.query(col); - tree.update(col + 1, val - prev); - } - - public int sumRegion(int row1, int col1, int row2, int col2) { - int s = 0; - for (int i = row1; i <= row2; ++i) { - BinaryIndexedTree tree = trees[i]; - s += tree.query(col2 + 1) - tree.query(col1); - } - return s; - } -} - -/** - * Your NumMatrix object will be instantiated and called as such: - * NumMatrix obj = new NumMatrix(matrix); - * obj.update(row,col,val); - * int param_2 = obj.sumRegion(row1,col1,row2,col2); - */ -``` - -线段树: - ```java class Node { int l; @@ -396,82 +523,6 @@ class NumMatrix { */ ``` -### **C++** - -树状数组: - -```cpp -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - int lowbit(int x) { - return x & -x; - } -}; - -class NumMatrix { -public: - vector trees; - - NumMatrix(vector>& matrix) { - int m = matrix.size(); - int n = matrix[0].size(); - trees.resize(m); - for (int i = 0; i < m; ++i) { - BinaryIndexedTree* tree = new BinaryIndexedTree(n); - for (int j = 0; j < n; ++j) tree->update(j + 1, matrix[i][j]); - trees[i] = tree; - } - } - - void update(int row, int col, int val) { - BinaryIndexedTree* tree = trees[row]; - int prev = tree->query(col + 1) - tree->query(col); - tree->update(col + 1, val - prev); - } - - int sumRegion(int row1, int col1, int row2, int col2) { - int s = 0; - for (int i = row1; i <= row2; ++i) { - BinaryIndexedTree* tree = trees[i]; - s += tree->query(col2 + 1) - tree->query(col1); - } - return s; - } -}; - -/** - * Your NumMatrix object will be instantiated and called as such: - * NumMatrix* obj = new NumMatrix(matrix); - * obj->update(row,col,val); - * int param_2 = obj->sumRegion(row1,col1,row2,col2); - */ -``` - -线段树: - ```cpp class Node { public: @@ -563,85 +614,6 @@ public: */ ``` -### **Go** - -树状数组: - -```go -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (this *BinaryIndexedTree) lowbit(x int) int { - return x & -x -} - -func (this *BinaryIndexedTree) update(x, delta int) { - for x <= this.n { - this.c[x] += delta - x += this.lowbit(x) - } -} - -func (this *BinaryIndexedTree) query(x int) int { - s := 0 - for x > 0 { - s += this.c[x] - x -= this.lowbit(x) - } - return s -} - -type NumMatrix struct { - trees []*BinaryIndexedTree -} - -func Constructor(matrix [][]int) NumMatrix { - n := len(matrix[0]) - var trees []*BinaryIndexedTree - for _, row := range matrix { - tree := newBinaryIndexedTree(n) - for j, v := range row { - tree.update(j+1, v) - } - trees = append(trees, tree) - } - return NumMatrix{trees} -} - -func (this *NumMatrix) Update(row int, col int, val int) { - tree := this.trees[row] - prev := tree.query(col+1) - tree.query(col) - tree.update(col+1, val-prev) -} - -func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { - s := 0 - for i := row1; i <= row2; i++ { - tree := this.trees[i] - s += tree.query(col2+1) - tree.query(col1) - } - return s -} - -/** - * Your NumMatrix object will be instantiated and called as such: - * obj := Constructor(matrix); - * obj.Update(row,col,val); - * param_2 := obj.SumRegion(row1,col1,row2,col2); - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0308.Range Sum Query 2D - Mutable/README_EN.md b/solution/0300-0399/0308.Range Sum Query 2D - Mutable/README_EN.md index a42fd8e095a94..635dda8691e0f 100644 --- a/solution/0300-0399/0308.Range Sum Query 2D - Mutable/README_EN.md +++ b/solution/0300-0399/0308.Range Sum Query 2D - Mutable/README_EN.md @@ -55,14 +55,10 @@ numMatrix.sumRegion(2, 1, 4, 3); // return 10 (i.e. sum of the right red rectang ## Solutions -Binary Indexed Tree or Segment Tree. +### Solution 1 -### **Python3** - -Binary Indexed Tree: - ```python class BinaryIndexedTree: def __init__(self, n): @@ -114,6 +110,224 @@ class NumMatrix: # param_2 = obj.sumRegion(row1,col1,row2,col2) ``` +```java +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + public static int lowbit(int x) { + return x & -x; + } +} + +class NumMatrix { + private BinaryIndexedTree[] trees; + + public NumMatrix(int[][] matrix) { + int m = matrix.length; + int n = matrix[0].length; + trees = new BinaryIndexedTree[m]; + for (int i = 0; i < m; ++i) { + BinaryIndexedTree tree = new BinaryIndexedTree(n); + for (int j = 0; j < n; ++j) { + tree.update(j + 1, matrix[i][j]); + } + trees[i] = tree; + } + } + + public void update(int row, int col, int val) { + BinaryIndexedTree tree = trees[row]; + int prev = tree.query(col + 1) - tree.query(col); + tree.update(col + 1, val - prev); + } + + public int sumRegion(int row1, int col1, int row2, int col2) { + int s = 0; + for (int i = row1; i <= row2; ++i) { + BinaryIndexedTree tree = trees[i]; + s += tree.query(col2 + 1) - tree.query(col1); + } + return s; + } +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * NumMatrix obj = new NumMatrix(matrix); + * obj.update(row,col,val); + * int param_2 = obj.sumRegion(row1,col1,row2,col2); + */ +``` + +```cpp +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + int lowbit(int x) { + return x & -x; + } +}; + +class NumMatrix { +public: + vector trees; + + NumMatrix(vector>& matrix) { + int m = matrix.size(); + int n = matrix[0].size(); + trees.resize(m); + for (int i = 0; i < m; ++i) { + BinaryIndexedTree* tree = new BinaryIndexedTree(n); + for (int j = 0; j < n; ++j) tree->update(j + 1, matrix[i][j]); + trees[i] = tree; + } + } + + void update(int row, int col, int val) { + BinaryIndexedTree* tree = trees[row]; + int prev = tree->query(col + 1) - tree->query(col); + tree->update(col + 1, val - prev); + } + + int sumRegion(int row1, int col1, int row2, int col2) { + int s = 0; + for (int i = row1; i <= row2; ++i) { + BinaryIndexedTree* tree = trees[i]; + s += tree->query(col2 + 1) - tree->query(col1); + } + return s; + } +}; + +/** + * Your NumMatrix object will be instantiated and called as such: + * NumMatrix* obj = new NumMatrix(matrix); + * obj->update(row,col,val); + * int param_2 = obj->sumRegion(row1,col1,row2,col2); + */ +``` + +```go +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) lowbit(x int) int { + return x & -x +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += this.lowbit(x) + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= this.lowbit(x) + } + return s +} + +type NumMatrix struct { + trees []*BinaryIndexedTree +} + +func Constructor(matrix [][]int) NumMatrix { + n := len(matrix[0]) + var trees []*BinaryIndexedTree + for _, row := range matrix { + tree := newBinaryIndexedTree(n) + for j, v := range row { + tree.update(j+1, v) + } + trees = append(trees, tree) + } + return NumMatrix{trees} +} + +func (this *NumMatrix) Update(row int, col int, val int) { + tree := this.trees[row] + prev := tree.query(col+1) - tree.query(col) + tree.update(col+1, val-prev) +} + +func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { + s := 0 + for i := row1; i <= row2; i++ { + tree := this.trees[i] + s += tree.query(col2+1) - tree.query(col1) + } + return s +} + +/** + * Your NumMatrix object will be instantiated and called as such: + * obj := Constructor(matrix); + * obj.Update(row,col,val); + * param_2 := obj.SumRegion(row1,col1,row2,col2); + */ +``` + + + +### Solution 2 + + + ```python class Node: def __init__(self): @@ -187,81 +401,6 @@ class NumMatrix: # param_2 = obj.sumRegion(row1,col1,row2,col2) ``` -### **Java** - -Binary Indexed Tree: - -```java -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - public static int lowbit(int x) { - return x & -x; - } -} - -class NumMatrix { - private BinaryIndexedTree[] trees; - - public NumMatrix(int[][] matrix) { - int m = matrix.length; - int n = matrix[0].length; - trees = new BinaryIndexedTree[m]; - for (int i = 0; i < m; ++i) { - BinaryIndexedTree tree = new BinaryIndexedTree(n); - for (int j = 0; j < n; ++j) { - tree.update(j + 1, matrix[i][j]); - } - trees[i] = tree; - } - } - - public void update(int row, int col, int val) { - BinaryIndexedTree tree = trees[row]; - int prev = tree.query(col + 1) - tree.query(col); - tree.update(col + 1, val - prev); - } - - public int sumRegion(int row1, int col1, int row2, int col2) { - int s = 0; - for (int i = row1; i <= row2; ++i) { - BinaryIndexedTree tree = trees[i]; - s += tree.query(col2 + 1) - tree.query(col1); - } - return s; - } -} - -/** - * Your NumMatrix object will be instantiated and called as such: - * NumMatrix obj = new NumMatrix(matrix); - * obj.update(row,col,val); - * int param_2 = obj.sumRegion(row1,col1,row2,col2); - */ -``` - ```java class Node { int l; @@ -364,82 +503,6 @@ class NumMatrix { */ ``` -### **C++** - -Binary Indexed Tree: - -```cpp -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - int lowbit(int x) { - return x & -x; - } -}; - -class NumMatrix { -public: - vector trees; - - NumMatrix(vector>& matrix) { - int m = matrix.size(); - int n = matrix[0].size(); - trees.resize(m); - for (int i = 0; i < m; ++i) { - BinaryIndexedTree* tree = new BinaryIndexedTree(n); - for (int j = 0; j < n; ++j) tree->update(j + 1, matrix[i][j]); - trees[i] = tree; - } - } - - void update(int row, int col, int val) { - BinaryIndexedTree* tree = trees[row]; - int prev = tree->query(col + 1) - tree->query(col); - tree->update(col + 1, val - prev); - } - - int sumRegion(int row1, int col1, int row2, int col2) { - int s = 0; - for (int i = row1; i <= row2; ++i) { - BinaryIndexedTree* tree = trees[i]; - s += tree->query(col2 + 1) - tree->query(col1); - } - return s; - } -}; - -/** - * Your NumMatrix object will be instantiated and called as such: - * NumMatrix* obj = new NumMatrix(matrix); - * obj->update(row,col,val); - * int param_2 = obj->sumRegion(row1,col1,row2,col2); - */ -``` - -Segment Tree: - ```cpp class Node { public: @@ -531,85 +594,6 @@ public: */ ``` -### **Go** - -Binary Indexed Tree: - -```go -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (this *BinaryIndexedTree) lowbit(x int) int { - return x & -x -} - -func (this *BinaryIndexedTree) update(x, delta int) { - for x <= this.n { - this.c[x] += delta - x += this.lowbit(x) - } -} - -func (this *BinaryIndexedTree) query(x int) int { - s := 0 - for x > 0 { - s += this.c[x] - x -= this.lowbit(x) - } - return s -} - -type NumMatrix struct { - trees []*BinaryIndexedTree -} - -func Constructor(matrix [][]int) NumMatrix { - n := len(matrix[0]) - var trees []*BinaryIndexedTree - for _, row := range matrix { - tree := newBinaryIndexedTree(n) - for j, v := range row { - tree.update(j+1, v) - } - trees = append(trees, tree) - } - return NumMatrix{trees} -} - -func (this *NumMatrix) Update(row int, col int, val int) { - tree := this.trees[row] - prev := tree.query(col+1) - tree.query(col) - tree.update(col+1, val-prev) -} - -func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { - s := 0 - for i := row1; i <= row2; i++ { - tree := this.trees[i] - s += tree.query(col2+1) - tree.query(col1) - } - return s -} - -/** - * Your NumMatrix object will be instantiated and called as such: - * obj := Constructor(matrix); - * obj.Update(row,col,val); - * param_2 := obj.SumRegion(row1,col1,row2,col2); - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/README.md b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/README.md index f425d8093facf..eb67b3c19320a 100644 --- a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/README.md +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j)$,表示从第 $i$ 天开始,状态为 $j$ 时,能够获得的最大利润。其中 $j$ 的取值为 $0, 1$,分别表示当前不持有股票和持有股票。答案即为 $dfs(0, 0)$。 @@ -61,24 +59,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $prices$ 的长度。 -**方法二:动态规划** - -我们也可以用动态规划的方法求解。 - -我们定义 $f[i][j]$ 表示到第 $i$ 天,且状态为 $j$ 时,能够获得的最大利润。其中 $j$ 的取值为 $0, 1$,分别表示当前不持有股票和持有股票。初始时 $f[0][0] = 0$, $f[0][1] = -prices[0]$。 - -当 $i \geq 1$ 时,如果当前不持有股票,那么 $f[i][0]$ 可以由 $f[i - 1][0]$ 和 $f[i - 1][1] + prices[i]$ 转移得到,即 $f[i][0] = \max(f[i - 1][0], f[i - 1][1] + prices[i])$;如果当前持有股票,那么 $f[i][1]$ 可以由 $f[i - 1][1]$ 和 $f[i - 2][0] - prices[i]$ 转移得到,即 $f[i][1] = \max(f[i - 1][1], f[i - 2][0] - prices[i])$。最终答案为 $f[n - 1][0]$。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $prices$ 的长度。 - -我们注意到,状态 $f[i][]$ 的转移只与 $f[i - 1][]$ 和 $f[i - 2][0]$ 有关,因此我们可以用三个变量 $f$, $f_0$, $f_1$ 代替数组 $f$,将空间复杂度优化到 $O(1)$。 - -### **Python3** - - - ```python class Solution: def maxProfit(self, prices: List[int]) -> int: @@ -96,31 +78,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def maxProfit(self, prices: List[int]) -> int: - n = len(prices) - f = [[0] * 2 for _ in range(n)] - f[0][1] = -prices[0] - for i in range(1, n): - f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i]) - f[i][1] = max(f[i - 1][1], f[i - 2][0] - prices[i]) - return f[n - 1][0] -``` - -```python -class Solution: - def maxProfit(self, prices: List[int]) -> int: - f, f0, f1 = 0, 0, -prices[0] - for x in prices[1:]: - f, f0, f1 = f0, max(f0, f1 + x), max(f1, f - x) - return f0 -``` - -### **Java** - - - ```java class Solution { private int[] prices; @@ -150,38 +107,6 @@ class Solution { } ``` -```java -class Solution { - public int maxProfit(int[] prices) { - int n = prices.length; - int[][] f = new int[n][2]; - f[0][1] = -prices[0]; - for (int i = 1; i < n; i++) { - f[i][0] = Math.max(f[i - 1][0], f[i - 1][1] + prices[i]); - f[i][1] = Math.max(f[i - 1][1], (i > 1 ? f[i - 2][0] : 0) - prices[i]); - } - return f[n - 1][0]; - } -} -``` - -```java -class Solution { - public int maxProfit(int[] prices) { - int f = 0, f0 = 0, f1 = -prices[0]; - for (int i = 1; i < prices.length; ++i) { - int g0 = Math.max(f0, f1 + prices[i]); - f1 = Math.max(f1, f - prices[i]); - f = f0; - f0 = g0; - } - return f0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -209,41 +134,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxProfit(vector& prices) { - int n = prices.size(); - int f[n][2]; - memset(f, 0, sizeof(f)); - f[0][1] = -prices[0]; - for (int i = 1; i < n; ++i) { - f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i]); - f[i][1] = max(f[i - 1][1], (i > 1 ? f[i - 2][0] : 0) - prices[i]); - } - return f[n - 1][0]; - } -}; -``` - -```cpp -class Solution { -public: - int maxProfit(vector& prices) { - int f = 0, f0 = 0, f1 = -prices[0]; - for (int i = 1; i < prices.size(); ++i) { - int g0 = max(f0, f1 + prices[i]); - f1 = max(f1, f - prices[i]); - f = f0; - f0 = g0; - } - return f0; - } -}; -``` - -### **Go** - ```go func maxProfit(prices []int) int { n := len(prices) @@ -272,35 +162,6 @@ func maxProfit(prices []int) int { } ``` -```go -func maxProfit(prices []int) int { - n := len(prices) - f := make([][2]int, n) - f[0][1] = -prices[0] - for i := 1; i < n; i++ { - f[i][0] = max(f[i-1][0], f[i-1][1]+prices[i]) - if i > 1 { - f[i][1] = max(f[i-1][1], f[i-2][0]-prices[i]) - } else { - f[i][1] = max(f[i-1][1], -prices[i]) - } - } - return f[n-1][0] -} -``` - -```go -func maxProfit(prices []int) int { - f, f0, f1 := 0, 0, -prices[0] - for _, x := range prices[1:] { - f, f0, f1 = f0, max(f0, f1+x), max(f1, f-x) - } - return f0 -} -``` - -### **TypeScript** - ```ts function maxProfit(prices: number[]): number { const n = prices.length; @@ -324,6 +185,83 @@ function maxProfit(prices: number[]): number { } ``` + + +### 方法二:动态规划 + +我们也可以用动态规划的方法求解。 + +我们定义 $f[i][j]$ 表示到第 $i$ 天,且状态为 $j$ 时,能够获得的最大利润。其中 $j$ 的取值为 $0, 1$,分别表示当前不持有股票和持有股票。初始时 $f[0][0] = 0$, $f[0][1] = -prices[0]$。 + +当 $i \geq 1$ 时,如果当前不持有股票,那么 $f[i][0]$ 可以由 $f[i - 1][0]$ 和 $f[i - 1][1] + prices[i]$ 转移得到,即 $f[i][0] = \max(f[i - 1][0], f[i - 1][1] + prices[i])$;如果当前持有股票,那么 $f[i][1]$ 可以由 $f[i - 1][1]$ 和 $f[i - 2][0] - prices[i]$ 转移得到,即 $f[i][1] = \max(f[i - 1][1], f[i - 2][0] - prices[i])$。最终答案为 $f[n - 1][0]$。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $prices$ 的长度。 + +我们注意到,状态 $f[i][]$ 的转移只与 $f[i - 1][]$ 和 $f[i - 2][0]$ 有关,因此我们可以用三个变量 $f$, $f_0$, $f_1$ 代替数组 $f$,将空间复杂度优化到 $O(1)$。 + + + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + n = len(prices) + f = [[0] * 2 for _ in range(n)] + f[0][1] = -prices[0] + for i in range(1, n): + f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i]) + f[i][1] = max(f[i - 1][1], f[i - 2][0] - prices[i]) + return f[n - 1][0] +``` + +```java +class Solution { + public int maxProfit(int[] prices) { + int n = prices.length; + int[][] f = new int[n][2]; + f[0][1] = -prices[0]; + for (int i = 1; i < n; i++) { + f[i][0] = Math.max(f[i - 1][0], f[i - 1][1] + prices[i]); + f[i][1] = Math.max(f[i - 1][1], (i > 1 ? f[i - 2][0] : 0) - prices[i]); + } + return f[n - 1][0]; + } +} +``` + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int n = prices.size(); + int f[n][2]; + memset(f, 0, sizeof(f)); + f[0][1] = -prices[0]; + for (int i = 1; i < n; ++i) { + f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i]); + f[i][1] = max(f[i - 1][1], (i > 1 ? f[i - 2][0] : 0) - prices[i]); + } + return f[n - 1][0]; + } +}; +``` + +```go +func maxProfit(prices []int) int { + n := len(prices) + f := make([][2]int, n) + f[0][1] = -prices[0] + for i := 1; i < n; i++ { + f[i][0] = max(f[i-1][0], f[i-1][1]+prices[i]) + if i > 1 { + f[i][1] = max(f[i-1][1], f[i-2][0]-prices[i]) + } else { + f[i][1] = max(f[i-1][1], -prices[i]) + } + } + return f[n-1][0] +} +``` + ```ts function maxProfit(prices: number[]): number { const n = prices.length; @@ -337,6 +275,62 @@ function maxProfit(prices: number[]): number { } ``` + + +### 方法三 + + + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + f, f0, f1 = 0, 0, -prices[0] + for x in prices[1:]: + f, f0, f1 = f0, max(f0, f1 + x), max(f1, f - x) + return f0 +``` + +```java +class Solution { + public int maxProfit(int[] prices) { + int f = 0, f0 = 0, f1 = -prices[0]; + for (int i = 1; i < prices.length; ++i) { + int g0 = Math.max(f0, f1 + prices[i]); + f1 = Math.max(f1, f - prices[i]); + f = f0; + f0 = g0; + } + return f0; + } +} +``` + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int f = 0, f0 = 0, f1 = -prices[0]; + for (int i = 1; i < prices.size(); ++i) { + int g0 = max(f0, f1 + prices[i]); + f1 = max(f1, f - prices[i]); + f = f0; + f0 = g0; + } + return f0; + } +}; +``` + +```go +func maxProfit(prices []int) int { + f, f0, f1 := 0, 0, -prices[0] + for _, x := range prices[1:] { + f, f0, f1 = f0, max(f0, f1+x), max(f1, f-x) + } + return f0 +} +``` + ```ts function maxProfit(prices: number[]): number { let [f, f0, f1] = [0, 0, -prices[0]]; @@ -347,10 +341,6 @@ function maxProfit(prices: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/README_EN.md b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/README_EN.md index 9adafbe037917..d4f3874495230 100644 --- a/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/README_EN.md +++ b/solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We design a function $dfs(i, j)$, which represents the maximum profit that can be obtained starting from the $i$th day with state $j$. The values of $j$ are $0$ and $1$, respectively representing currently not holding a stock and holding a stock. The answer is $dfs(0, 0)$. @@ -56,22 +56,8 @@ To avoid repeated calculations, we use the method of memoization search, and use The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $prices$. -**Solution 2: Dynamic Programming** - -We can also use dynamic programming to solve this problem. - -We define $f[i][j]$ to represent the maximum profit that can be obtained on the $i$th day with state $j$. The values of $j$ are $0$ and $1$, respectively representing currently not holding a stock and holding a stock. Initially, $f[0][0] = 0$, $f[0][1] = -prices[0]$. - -When $i \geq 1$, if we currently do not hold a stock, then $f[i][0]$ can be obtained by transitioning from $f[i - 1][0]$ and $f[i - 1][1] + prices[i]$, i.e., $f[i][0] = \max(f[i - 1][0], f[i - 1][1] + prices[i])$. If we currently hold a stock, then $f[i][1]$ can be obtained by transitioning from $f[i - 1][1]$ and $f[i - 2][0] - prices[i]$, i.e., $f[i][1] = \max(f[i - 1][1], f[i - 2][0] - prices[i])$. The final answer is $f[n - 1][0]$. - -The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $prices$. - -We notice that the transition of state $f[i][]$ is only related to $f[i - 1][]$ and $f[i - 2][0]$, so we can use three variables $f$, $f_0$, $f_1$ to replace the array $f$, optimizing the space complexity to $O(1)$. - -### **Python3** - ```python class Solution: def maxProfit(self, prices: List[int]) -> int: @@ -89,29 +75,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def maxProfit(self, prices: List[int]) -> int: - n = len(prices) - f = [[0] * 2 for _ in range(n)] - f[0][1] = -prices[0] - for i in range(1, n): - f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i]) - f[i][1] = max(f[i - 1][1], f[i - 2][0] - prices[i]) - return f[n - 1][0] -``` - -```python -class Solution: - def maxProfit(self, prices: List[int]) -> int: - f, f0, f1 = 0, 0, -prices[0] - for x in prices[1:]: - f, f0, f1 = f0, max(f0, f1 + x), max(f1, f - x) - return f0 -``` - -### **Java** - ```java class Solution { private int[] prices; @@ -141,38 +104,6 @@ class Solution { } ``` -```java -class Solution { - public int maxProfit(int[] prices) { - int n = prices.length; - int[][] f = new int[n][2]; - f[0][1] = -prices[0]; - for (int i = 1; i < n; i++) { - f[i][0] = Math.max(f[i - 1][0], f[i - 1][1] + prices[i]); - f[i][1] = Math.max(f[i - 1][1], (i > 1 ? f[i - 2][0] : 0) - prices[i]); - } - return f[n - 1][0]; - } -} -``` - -```java -class Solution { - public int maxProfit(int[] prices) { - int f = 0, f0 = 0, f1 = -prices[0]; - for (int i = 1; i < prices.length; ++i) { - int g0 = Math.max(f0, f1 + prices[i]); - f1 = Math.max(f1, f - prices[i]); - f = f0; - f0 = g0; - } - return f0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -200,41 +131,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxProfit(vector& prices) { - int n = prices.size(); - int f[n][2]; - memset(f, 0, sizeof(f)); - f[0][1] = -prices[0]; - for (int i = 1; i < n; ++i) { - f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i]); - f[i][1] = max(f[i - 1][1], (i > 1 ? f[i - 2][0] : 0) - prices[i]); - } - return f[n - 1][0]; - } -}; -``` - -```cpp -class Solution { -public: - int maxProfit(vector& prices) { - int f = 0, f0 = 0, f1 = -prices[0]; - for (int i = 1; i < prices.size(); ++i) { - int g0 = max(f0, f1 + prices[i]); - f1 = max(f1, f - prices[i]); - f = f0; - f0 = g0; - } - return f0; - } -}; -``` - -### **Go** - ```go func maxProfit(prices []int) int { n := len(prices) @@ -263,35 +159,6 @@ func maxProfit(prices []int) int { } ``` -```go -func maxProfit(prices []int) int { - n := len(prices) - f := make([][2]int, n) - f[0][1] = -prices[0] - for i := 1; i < n; i++ { - f[i][0] = max(f[i-1][0], f[i-1][1]+prices[i]) - if i > 1 { - f[i][1] = max(f[i-1][1], f[i-2][0]-prices[i]) - } else { - f[i][1] = max(f[i-1][1], -prices[i]) - } - } - return f[n-1][0] -} -``` - -```go -func maxProfit(prices []int) int { - f, f0, f1 := 0, 0, -prices[0] - for _, x := range prices[1:] { - f, f0, f1 = f0, max(f0, f1+x), max(f1, f-x) - } - return f0 -} -``` - -### **TypeScript** - ```ts function maxProfit(prices: number[]): number { const n = prices.length; @@ -315,6 +182,83 @@ function maxProfit(prices: number[]): number { } ``` + + +### Solution 2: Dynamic Programming + +We can also use dynamic programming to solve this problem. + +We define $f[i][j]$ to represent the maximum profit that can be obtained on the $i$th day with state $j$. The values of $j$ are $0$ and $1$, respectively representing currently not holding a stock and holding a stock. Initially, $f[0][0] = 0$, $f[0][1] = -prices[0]$. + +When $i \geq 1$, if we currently do not hold a stock, then $f[i][0]$ can be obtained by transitioning from $f[i - 1][0]$ and $f[i - 1][1] + prices[i]$, i.e., $f[i][0] = \max(f[i - 1][0], f[i - 1][1] + prices[i])$. If we currently hold a stock, then $f[i][1]$ can be obtained by transitioning from $f[i - 1][1]$ and $f[i - 2][0] - prices[i]$, i.e., $f[i][1] = \max(f[i - 1][1], f[i - 2][0] - prices[i])$. The final answer is $f[n - 1][0]$. + +The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $prices$. + +We notice that the transition of state $f[i][]$ is only related to $f[i - 1][]$ and $f[i - 2][0]$, so we can use three variables $f$, $f_0$, $f_1$ to replace the array $f$, optimizing the space complexity to $O(1)$. + + + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + n = len(prices) + f = [[0] * 2 for _ in range(n)] + f[0][1] = -prices[0] + for i in range(1, n): + f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i]) + f[i][1] = max(f[i - 1][1], f[i - 2][0] - prices[i]) + return f[n - 1][0] +``` + +```java +class Solution { + public int maxProfit(int[] prices) { + int n = prices.length; + int[][] f = new int[n][2]; + f[0][1] = -prices[0]; + for (int i = 1; i < n; i++) { + f[i][0] = Math.max(f[i - 1][0], f[i - 1][1] + prices[i]); + f[i][1] = Math.max(f[i - 1][1], (i > 1 ? f[i - 2][0] : 0) - prices[i]); + } + return f[n - 1][0]; + } +} +``` + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int n = prices.size(); + int f[n][2]; + memset(f, 0, sizeof(f)); + f[0][1] = -prices[0]; + for (int i = 1; i < n; ++i) { + f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i]); + f[i][1] = max(f[i - 1][1], (i > 1 ? f[i - 2][0] : 0) - prices[i]); + } + return f[n - 1][0]; + } +}; +``` + +```go +func maxProfit(prices []int) int { + n := len(prices) + f := make([][2]int, n) + f[0][1] = -prices[0] + for i := 1; i < n; i++ { + f[i][0] = max(f[i-1][0], f[i-1][1]+prices[i]) + if i > 1 { + f[i][1] = max(f[i-1][1], f[i-2][0]-prices[i]) + } else { + f[i][1] = max(f[i-1][1], -prices[i]) + } + } + return f[n-1][0] +} +``` + ```ts function maxProfit(prices: number[]): number { const n = prices.length; @@ -328,6 +272,62 @@ function maxProfit(prices: number[]): number { } ``` + + +### Solution 3 + + + +```python +class Solution: + def maxProfit(self, prices: List[int]) -> int: + f, f0, f1 = 0, 0, -prices[0] + for x in prices[1:]: + f, f0, f1 = f0, max(f0, f1 + x), max(f1, f - x) + return f0 +``` + +```java +class Solution { + public int maxProfit(int[] prices) { + int f = 0, f0 = 0, f1 = -prices[0]; + for (int i = 1; i < prices.length; ++i) { + int g0 = Math.max(f0, f1 + prices[i]); + f1 = Math.max(f1, f - prices[i]); + f = f0; + f0 = g0; + } + return f0; + } +} +``` + +```cpp +class Solution { +public: + int maxProfit(vector& prices) { + int f = 0, f0 = 0, f1 = -prices[0]; + for (int i = 1; i < prices.size(); ++i) { + int g0 = max(f0, f1 + prices[i]); + f1 = max(f1, f - prices[i]); + f = f0; + f0 = g0; + } + return f0; + } +}; +``` + +```go +func maxProfit(prices []int) int { + f, f0, f1 := 0, 0, -prices[0] + for _, x := range prices[1:] { + f, f0, f1 = f0, max(f0, f1+x), max(f1, f-x) + } + return f0 +} +``` + ```ts function maxProfit(prices: number[]): number { let [f, f0, f1] = [0, 0, -prices[0]]; @@ -338,10 +338,6 @@ function maxProfit(prices: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0310.Minimum Height Trees/README.md b/solution/0300-0399/0310.Minimum Height Trees/README.md index 0b23c570ad446..c3e8be433802b 100644 --- a/solution/0300-0399/0310.Minimum Height Trees/README.md +++ b/solution/0300-0399/0310.Minimum Height Trees/README.md @@ -49,18 +49,10 @@ ## 解法 - - -拓扑排序,BFS 实现。 - -每一轮删除入度为 1 的节点,同时减小与之连接的节点的入度。循环此操作,最后一轮删除的节点,即为要找的最小高度树的根节点。 +### 方法一 -### **Python3** - - - ```python class Solution: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: @@ -87,10 +79,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List findMinHeightTrees(int n, int[][] edges) { @@ -131,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +154,6 @@ public: }; ``` -### **Go** - ```go func findMinHeightTrees(n int, edges [][]int) []int { if n == 1 { @@ -209,10 +193,6 @@ func findMinHeightTrees(n int, edges [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0310.Minimum Height Trees/README_EN.md b/solution/0300-0399/0310.Minimum Height Trees/README_EN.md index 4abd3a98f045c..f55d23fb82be7 100644 --- a/solution/0300-0399/0310.Minimum Height Trees/README_EN.md +++ b/solution/0300-0399/0310.Minimum Height Trees/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List findMinHeightTrees(int n, int[][] edges) { @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +147,6 @@ public: }; ``` -### **Go** - ```go func findMinHeightTrees(n int, edges [][]int) []int { if n == 1 { @@ -192,10 +186,6 @@ func findMinHeightTrees(n int, edges [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0311.Sparse Matrix Multiplication/README.md b/solution/0300-0399/0311.Sparse Matrix Multiplication/README.md index 47905fcdb2bca..af8218f1ab24f 100644 --- a/solution/0300-0399/0311.Sparse Matrix Multiplication/README.md +++ b/solution/0300-0399/0311.Sparse Matrix Multiplication/README.md @@ -40,28 +40,14 @@ ## 解法 - - -**方法一:直接相乘** +### 方法一:直接相乘 我们可以直接按照矩阵乘法的定义,计算出结果矩阵中的每一个元素。 时间复杂度 $O(m \times n \times k)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是矩阵 $mat1$ 的行数和矩阵 $mat2$ 的列数,而 $k$ 是矩阵 $mat1$ 的列数或矩阵 $mat2$ 的行数。 -**方法二:预处理** - -我们可以预处理出两个矩阵的稀疏表示,即 $g1[i]$ 表示矩阵 $mat1$ 第 $i$ 行中所有非零元素的列下标和值,而 $g2[i]$ 表示矩阵 $mat2$ 第 $i$ 行中所有非零元素的列下标和值。 - -接下来,我们遍历每一行 $i$,遍历 $g1[i]$ 中的每一个元素 $(k, x)$,遍历 $g2[k]$ 中的每一个元素 $(j, y)$,那么最终 $mat1[i][k] \times mat2[k][j]$ 就会对应到结果矩阵中的 $ans[i][j]$,我们将所有的结果累加即可。 - -时间复杂度 $O(m \times n \times k)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是矩阵 $mat1$ 的行数和矩阵 $mat2$ 的列数,而 $k$ 是矩阵 $mat1$ 的列数或矩阵 $mat2$ 的行数。 - -### **Python3** - - - ```python class Solution: def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: @@ -74,6 +60,86 @@ class Solution: return ans ``` +```java +class Solution { + public int[][] multiply(int[][] mat1, int[][] mat2) { + int m = mat1.length, n = mat2[0].length; + int[][] ans = new int[m][n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < mat2.length; ++k) { + ans[i][j] += mat1[i][k] * mat2[k][j]; + } + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector> multiply(vector>& mat1, vector>& mat2) { + int m = mat1.size(), n = mat2[0].size(); + vector> ans(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < mat2.size(); ++k) { + ans[i][j] += mat1[i][k] * mat2[k][j]; + } + } + } + return ans; + } +}; +``` + +```go +func multiply(mat1 [][]int, mat2 [][]int) [][]int { + m, n := len(mat1), len(mat2[0]) + ans := make([][]int, m) + for i := range ans { + ans[i] = make([]int, n) + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + for k := 0; k < len(mat2); k++ { + ans[i][j] += mat1[i][k] * mat2[k][j] + } + } + } + return ans +} +``` + +```ts +function multiply(mat1: number[][], mat2: number[][]): number[][] { + const [m, n] = [mat1.length, mat2[0].length]; + const ans: number[][] = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + for (let k = 0; k < mat2.length; ++k) { + ans[i][j] += mat1[i][k] * mat2[k][j]; + } + } + } + return ans; +} +``` + + + +### 方法二:预处理 + +我们可以预处理出两个矩阵的稀疏表示,即 $g1[i]$ 表示矩阵 $mat1$ 第 $i$ 行中所有非零元素的列下标和值,而 $g2[i]$ 表示矩阵 $mat2$ 第 $i$ 行中所有非零元素的列下标和值。 + +接下来,我们遍历每一行 $i$,遍历 $g1[i]$ 中的每一个元素 $(k, x)$,遍历 $g2[k]$ 中的每一个元素 $(j, y)$,那么最终 $mat1[i][k] \times mat2[k][j]$ 就会对应到结果矩阵中的 $ans[i][j]$,我们将所有的结果累加即可。 + +时间复杂度 $O(m \times n \times k)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是矩阵 $mat1$ 的行数和矩阵 $mat2$ 的列数,而 $k$ 是矩阵 $mat1$ 的列数或矩阵 $mat2$ 的行数。 + + + ```python class Solution: def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: @@ -96,27 +162,6 @@ class Solution: return ans ``` -### **Java** - - - -```java -class Solution { - public int[][] multiply(int[][] mat1, int[][] mat2) { - int m = mat1.length, n = mat2[0].length; - int[][] ans = new int[m][n]; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int k = 0; k < mat2.length; ++k) { - ans[i][j] += mat1[i][k] * mat2[k][j]; - } - } - } - return ans; - } -} -``` - ```java class Solution { public int[][] multiply(int[][] mat1, int[][] mat2) { @@ -152,26 +197,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector> multiply(vector>& mat1, vector>& mat2) { - int m = mat1.size(), n = mat2[0].size(); - vector> ans(m, vector(n)); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int k = 0; k < mat2.size(); ++k) { - ans[i][j] += mat1[i][k] * mat2[k][j]; - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -204,26 +229,6 @@ public: }; ``` -### **Go** - -```go -func multiply(mat1 [][]int, mat2 [][]int) [][]int { - m, n := len(mat1), len(mat2[0]) - ans := make([][]int, m) - for i := range ans { - ans[i] = make([]int, n) - } - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - for k := 0; k < len(mat2); k++ { - ans[i][j] += mat1[i][k] * mat2[k][j] - } - } - } - return ans -} -``` - ```go func multiply(mat1 [][]int, mat2 [][]int) [][]int { m, n := len(mat1), len(mat2[0]) @@ -258,23 +263,6 @@ func multiply(mat1 [][]int, mat2 [][]int) [][]int { } ``` -### **TypeScript** - -```ts -function multiply(mat1: number[][], mat2: number[][]): number[][] { - const [m, n] = [mat1.length, mat2[0].length]; - const ans: number[][] = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - for (let k = 0; k < mat2.length; ++k) { - ans[i][j] += mat1[i][k] * mat2[k][j]; - } - } - } - return ans; -} -``` - ```ts function multiply(mat1: number[][], mat2: number[][]): number[][] { const [m, n] = [mat1.length, mat2[0].length]; @@ -304,10 +292,6 @@ function multiply(mat1: number[][], mat2: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0311.Sparse Matrix Multiplication/README_EN.md b/solution/0300-0399/0311.Sparse Matrix Multiplication/README_EN.md index 7f40dd6e12c1f..33415c257c7a6 100644 --- a/solution/0300-0399/0311.Sparse Matrix Multiplication/README_EN.md +++ b/solution/0300-0399/0311.Sparse Matrix Multiplication/README_EN.md @@ -34,24 +34,14 @@ ## Solutions -**Solution 1: Direct Multiplication** +### Solution 1: Direct Multiplication We can directly calculate each element in the result matrix according to the definition of matrix multiplication. The time complexity is $O(m \times n \times k)$, and the space complexity is $O(m \times n)$. Where $m$ and $n$ are the number of rows of matrix $mat1$ and the number of columns of matrix $mat2$ respectively, and $k$ is the number of columns of matrix $mat1$ or the number of rows of matrix $mat2$. -**Solution 2: Preprocessing** - -We can preprocess the sparse representation of the two matrices, i.e., $g1[i]$ represents the column index and value of all non-zero elements in the $i$th row of matrix $mat1$, and $g2[i]$ represents the column index and value of all non-zero elements in the $i$th row of matrix $mat2$. - -Next, we traverse each row $i$, traverse each element $(k, x)$ in $g1[i]$, traverse each element $(j, y)$ in $g2[k]$, then $mat1[i][k] \times mat2[k][j]$ will correspond to $ans[i][j]$ in the result matrix, and we can accumulate all the results. - -The time complexity is $O(m \times n \times k)$, and the space complexity is $O(m \times n)$. Where $m$ and $n$ are the number of rows of matrix $mat1$ and the number of columns of matrix $mat2$ respectively, and $k$ is the number of columns of matrix $mat1$ or the number of rows of matrix $mat2$. - -### **Python3** - ```python class Solution: def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: @@ -64,6 +54,86 @@ class Solution: return ans ``` +```java +class Solution { + public int[][] multiply(int[][] mat1, int[][] mat2) { + int m = mat1.length, n = mat2[0].length; + int[][] ans = new int[m][n]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < mat2.length; ++k) { + ans[i][j] += mat1[i][k] * mat2[k][j]; + } + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector> multiply(vector>& mat1, vector>& mat2) { + int m = mat1.size(), n = mat2[0].size(); + vector> ans(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < mat2.size(); ++k) { + ans[i][j] += mat1[i][k] * mat2[k][j]; + } + } + } + return ans; + } +}; +``` + +```go +func multiply(mat1 [][]int, mat2 [][]int) [][]int { + m, n := len(mat1), len(mat2[0]) + ans := make([][]int, m) + for i := range ans { + ans[i] = make([]int, n) + } + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + for k := 0; k < len(mat2); k++ { + ans[i][j] += mat1[i][k] * mat2[k][j] + } + } + } + return ans +} +``` + +```ts +function multiply(mat1: number[][], mat2: number[][]): number[][] { + const [m, n] = [mat1.length, mat2[0].length]; + const ans: number[][] = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + for (let k = 0; k < mat2.length; ++k) { + ans[i][j] += mat1[i][k] * mat2[k][j]; + } + } + } + return ans; +} +``` + + + +### Solution 2: Preprocessing + +We can preprocess the sparse representation of the two matrices, i.e., $g1[i]$ represents the column index and value of all non-zero elements in the $i$th row of matrix $mat1$, and $g2[i]$ represents the column index and value of all non-zero elements in the $i$th row of matrix $mat2$. + +Next, we traverse each row $i$, traverse each element $(k, x)$ in $g1[i]$, traverse each element $(j, y)$ in $g2[k]$, then $mat1[i][k] \times mat2[k][j]$ will correspond to $ans[i][j]$ in the result matrix, and we can accumulate all the results. + +The time complexity is $O(m \times n \times k)$, and the space complexity is $O(m \times n)$. Where $m$ and $n$ are the number of rows of matrix $mat1$ and the number of columns of matrix $mat2$ respectively, and $k$ is the number of columns of matrix $mat1$ or the number of rows of matrix $mat2$. + + + ```python class Solution: def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: @@ -86,25 +156,6 @@ class Solution: return ans ``` -### **Java** - -```java -class Solution { - public int[][] multiply(int[][] mat1, int[][] mat2) { - int m = mat1.length, n = mat2[0].length; - int[][] ans = new int[m][n]; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int k = 0; k < mat2.length; ++k) { - ans[i][j] += mat1[i][k] * mat2[k][j]; - } - } - } - return ans; - } -} -``` - ```java class Solution { public int[][] multiply(int[][] mat1, int[][] mat2) { @@ -140,26 +191,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector> multiply(vector>& mat1, vector>& mat2) { - int m = mat1.size(), n = mat2[0].size(); - vector> ans(m, vector(n)); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int k = 0; k < mat2.size(); ++k) { - ans[i][j] += mat1[i][k] * mat2[k][j]; - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -192,26 +223,6 @@ public: }; ``` -### **Go** - -```go -func multiply(mat1 [][]int, mat2 [][]int) [][]int { - m, n := len(mat1), len(mat2[0]) - ans := make([][]int, m) - for i := range ans { - ans[i] = make([]int, n) - } - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - for k := 0; k < len(mat2); k++ { - ans[i][j] += mat1[i][k] * mat2[k][j] - } - } - } - return ans -} -``` - ```go func multiply(mat1 [][]int, mat2 [][]int) [][]int { m, n := len(mat1), len(mat2[0]) @@ -246,23 +257,6 @@ func multiply(mat1 [][]int, mat2 [][]int) [][]int { } ``` -### **TypeScript** - -```ts -function multiply(mat1: number[][], mat2: number[][]): number[][] { - const [m, n] = [mat1.length, mat2[0].length]; - const ans: number[][] = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - for (let k = 0; k < mat2.length; ++k) { - ans[i][j] += mat1[i][k] * mat2[k][j]; - } - } - } - return ans; -} -``` - ```ts function multiply(mat1: number[][], mat2: number[][]): number[][] { const [m, n] = [mat1.length, mat2[0].length]; @@ -292,10 +286,6 @@ function multiply(mat1: number[][], mat2: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0312.Burst Balloons/README.md b/solution/0300-0399/0312.Burst Balloons/README.md index efd21153b2d60..016a11d90c46d 100644 --- a/solution/0300-0399/0312.Burst Balloons/README.md +++ b/solution/0300-0399/0312.Burst Balloons/README.md @@ -41,21 +41,10 @@ coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 ## 解法 - - -区间 DP。 - -- 状态表示:`dp[i][j]` 表示戳破区间 `(i, j)` 内所有气球获得的最大硬币数。 -- 状态计算:枚举开区间 `(i, j)` 中以气球 k 作为最后戳破的气球。那么 `dp[i][j] = max(dp[i][k] + dp[k][j] + nums[i] * nums[k] * nums[j]), k ∈ [i + 1, j)`。 - -以区间长度 l 从小到大开始处理每个状态值。 +### 方法一 -### **Python3** - - - ```python class Solution: def maxCoins(self, nums: List[int]) -> int: @@ -72,10 +61,6 @@ class Solution: return dp[0][-1] ``` -### **Java** - - - ```java class Solution { public int maxCoins(int[] nums) { @@ -99,27 +84,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function maxCoins(nums: number[]): number { - let n = nums.length; - let dp = Array.from({ length: n + 1 }, v => new Array(n + 2).fill(0)); - nums.unshift(1); - nums.push(1); - for (let i = n - 1; i >= 0; --i) { - for (let j = i + 2; j < n + 2; ++j) { - for (let k = i + 1; k < j; ++k) { - dp[i][j] = Math.max(nums[i] * nums[k] * nums[j] + dp[i][k] + dp[k][j], dp[i][j]); - } - } - } - return dp[0][n + 1]; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -141,8 +105,6 @@ public: }; ``` -### **Go** - ```go func maxCoins(nums []int) int { vals := make([]int, len(nums)+2) @@ -167,10 +129,23 @@ func maxCoins(nums []int) int { } ``` -### **...** - -``` - +```ts +function maxCoins(nums: number[]): number { + let n = nums.length; + let dp = Array.from({ length: n + 1 }, v => new Array(n + 2).fill(0)); + nums.unshift(1); + nums.push(1); + for (let i = n - 1; i >= 0; --i) { + for (let j = i + 2; j < n + 2; ++j) { + for (let k = i + 1; k < j; ++k) { + dp[i][j] = Math.max(nums[i] * nums[k] * nums[j] + dp[i][k] + dp[k][j], dp[i][j]); + } + } + } + return dp[0][n + 1]; +} ``` + + diff --git a/solution/0300-0399/0312.Burst Balloons/README_EN.md b/solution/0300-0399/0312.Burst Balloons/README_EN.md index e6f2cb58b669f..f68b80a5337e9 100644 --- a/solution/0300-0399/0312.Burst Balloons/README_EN.md +++ b/solution/0300-0399/0312.Burst Balloons/README_EN.md @@ -38,9 +38,9 @@ coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return dp[0][-1] ``` -### **Java** - ```java class Solution { public int maxCoins(int[] nums) { @@ -83,27 +81,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function maxCoins(nums: number[]): number { - let n = nums.length; - let dp = Array.from({ length: n + 1 }, v => new Array(n + 2).fill(0)); - nums.unshift(1); - nums.push(1); - for (let i = n - 1; i >= 0; --i) { - for (let j = i + 2; j < n + 2; ++j) { - for (let k = i + 1; k < j; ++k) { - dp[i][j] = Math.max(nums[i] * nums[k] * nums[j] + dp[i][k] + dp[k][j], dp[i][j]); - } - } - } - return dp[0][n + 1]; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -125,8 +102,6 @@ public: }; ``` -### **Go** - ```go func maxCoins(nums []int) int { vals := make([]int, len(nums)+2) @@ -151,10 +126,23 @@ func maxCoins(nums []int) int { } ``` -### **...** - -``` - +```ts +function maxCoins(nums: number[]): number { + let n = nums.length; + let dp = Array.from({ length: n + 1 }, v => new Array(n + 2).fill(0)); + nums.unshift(1); + nums.push(1); + for (let i = n - 1; i >= 0; --i) { + for (let j = i + 2; j < n + 2; ++j) { + for (let k = i + 1; k < j; ++k) { + dp[i][j] = Math.max(nums[i] * nums[k] * nums[j] + dp[i][k] + dp[k][j], dp[i][j]); + } + } + } + return dp[0][n + 1]; +} ``` + + diff --git a/solution/0300-0399/0313.Super Ugly Number/README.md b/solution/0300-0399/0313.Super Ugly Number/README.md index 7c8310b6c2d06..e37012d8a5732 100644 --- a/solution/0300-0399/0313.Super Ugly Number/README.md +++ b/solution/0300-0399/0313.Super Ugly Number/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:优先队列(小根堆)** +### 方法一:优先队列(小根堆) 我们用一个优先队列(小根堆)维护所有可能的超级丑数,初始时将 $1$ 放入队列中。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int: @@ -83,10 +77,6 @@ class Solution: return x ``` -### **Java** - - - ```java class Solution { public int nthSuperUglyNumber(int n, int[] primes) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func nthSuperUglyNumber(n int, primes []int) (x int) { q := hp{[]int{1}} @@ -169,6 +155,12 @@ func (h *hp) Pop() any { } ``` + + +### 方法二 + + + ```go type Ugly struct{ value, prime, index int } type Queue []Ugly @@ -202,10 +194,6 @@ func nthSuperUglyNumber(n int, primes []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0313.Super Ugly Number/README_EN.md b/solution/0300-0399/0313.Super Ugly Number/README_EN.md index 07bcee900aa53..bd4ad634b9f58 100644 --- a/solution/0300-0399/0313.Super Ugly Number/README_EN.md +++ b/solution/0300-0399/0313.Super Ugly Number/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Priority Queue (Min Heap)** +### Solution 1: Priority Queue (Min Heap) We use a priority queue (min heap) to maintain all possible super ugly numbers, initially putting $1$ into the queue. @@ -52,8 +52,6 @@ The time complexity is $O(n \times m \times \log (n \times m))$, and the space c -### **Python3** - ```python class Solution: def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int: @@ -70,8 +68,6 @@ class Solution: return x ``` -### **Java** - ```java class Solution { public int nthSuperUglyNumber(int n, int[] primes) { @@ -97,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +117,6 @@ public: }; ``` -### **Go** - ```go func nthSuperUglyNumber(n int, primes []int) (x int) { q := hp{[]int{1}} @@ -154,6 +146,12 @@ func (h *hp) Pop() any { } ``` + + +### Solution 2 + + + ```go type Ugly struct{ value, prime, index int } type Queue []Ugly @@ -187,10 +185,6 @@ func nthSuperUglyNumber(n int, primes []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/README.md b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/README.md index cfeaaedf1a4f4..3f3feacaa0069 100644 --- a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/README.md +++ b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/README.md @@ -44,26 +44,14 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS DFS 遍历二叉树,记录每个节点的值、深度,以及横向的偏移量。然后对所有节点按照横向偏移量从小到大排序,再按照深度从小到大排序,最后按照横向偏移量分组。 时间复杂度 $O(n\log \log n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。 -**方法二:BFS** - -本题较好的做法应该是 BFS,从上往下逐层进行遍历。 - -时间复杂度 $O(n\log n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的结点数。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -89,34 +77,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]: - if root is None: - return [] - q = deque([(root, 0)]) - d = defaultdict(list) - while q: - for _ in range(len(q)): - root, offset = q.popleft() - d[offset].append(root.val) - if root.left: - q.append((root.left, offset - 1)) - if root.right: - q.append((root.right, offset + 1)) - return [v for _, v in sorted(d.items())] -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -161,52 +121,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public List> verticalOrder(TreeNode root) { - List> ans = new ArrayList<>(); - if (root == null) { - return ans; - } - Deque> q = new ArrayDeque<>(); - q.offer(new Pair<>(root, 0)); - TreeMap> d = new TreeMap<>(); - while (!q.isEmpty()) { - for (int n = q.size(); n > 0; --n) { - var p = q.pollFirst(); - root = p.getKey(); - int offset = p.getValue(); - d.computeIfAbsent(offset, k -> new ArrayList()).add(root.val); - if (root.left != null) { - q.offer(new Pair<>(root.left, offset - 1)); - } - if (root.right != null) { - q.offer(new Pair<>(root.right, offset + 1)); - } - } - } - return new ArrayList<>(d.values()); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -250,46 +164,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector> verticalOrder(TreeNode* root) { - vector> ans; - if (!root) return ans; - map> d; - queue> q{{{root, 0}}}; - while (!q.empty()) { - for (int n = q.size(); n; --n) { - auto p = q.front(); - q.pop(); - root = p.first; - int offset = p.second; - d[offset].push_back(root->val); - if (root->left) q.push({root->left, offset - 1}); - if (root->right) q.push({root->right, offset + 1}); - } - } - for (auto& [_, v] : d) { - ans.push_back(v); - } - return ans; - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -330,6 +204,122 @@ func verticalOrder(root *TreeNode) [][]int { } ``` + + +### 方法二:BFS + +本题较好的做法应该是 BFS,从上往下逐层进行遍历。 + +时间复杂度 $O(n\log n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的结点数。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + if root is None: + return [] + q = deque([(root, 0)]) + d = defaultdict(list) + while q: + for _ in range(len(q)): + root, offset = q.popleft() + d[offset].append(root.val) + if root.left: + q.append((root.left, offset - 1)) + if root.right: + q.append((root.right, offset + 1)) + return [v for _, v in sorted(d.items())] +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List> verticalOrder(TreeNode root) { + List> ans = new ArrayList<>(); + if (root == null) { + return ans; + } + Deque> q = new ArrayDeque<>(); + q.offer(new Pair<>(root, 0)); + TreeMap> d = new TreeMap<>(); + while (!q.isEmpty()) { + for (int n = q.size(); n > 0; --n) { + var p = q.pollFirst(); + root = p.getKey(); + int offset = p.getValue(); + d.computeIfAbsent(offset, k -> new ArrayList()).add(root.val); + if (root.left != null) { + q.offer(new Pair<>(root.left, offset - 1)); + } + if (root.right != null) { + q.offer(new Pair<>(root.right, offset + 1)); + } + } + } + return new ArrayList<>(d.values()); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> verticalOrder(TreeNode* root) { + vector> ans; + if (!root) return ans; + map> d; + queue> q{{{root, 0}}}; + while (!q.empty()) { + for (int n = q.size(); n; --n) { + auto p = q.front(); + q.pop(); + root = p.first; + int offset = p.second; + d[offset].push_back(root->val); + if (root->left) q.push({root->left, offset - 1}); + if (root->right) q.push({root->right, offset + 1}); + } + } + for (auto& [_, v] : d) { + ans.push_back(v); + } + return ans; + } +}; +``` + ```go /** * Definition for a binary tree node. @@ -378,10 +368,6 @@ type pair struct { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/README_EN.md b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/README_EN.md index f9031bd0eaa82..2bfcb352ebe5a 100644 --- a/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/README_EN.md +++ b/solution/0300-0399/0314.Binary Tree Vertical Order Traversal/README_EN.md @@ -40,22 +40,14 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS DFS traverses the binary tree, recording the value, depth, and horizontal offset of each node. Then sort all nodes by horizontal offset from small to large, then by depth from small to large, and finally group by horizontal offset. The time complexity is $O(n\log \log n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree. -**Solution 2: BFS** - -A better approach to this problem should be BFS, traversing from top to bottom level by level. - -The time complexity is $O(n\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree. - -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -81,32 +73,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]: - if root is None: - return [] - q = deque([(root, 0)]) - d = defaultdict(list) - while q: - for _ in range(len(q)): - root, offset = q.popleft() - d[offset].append(root.val) - if root.left: - q.append((root.left, offset - 1)) - if root.right: - q.append((root.right, offset + 1)) - return [v for _, v in sorted(d.items())] -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -151,52 +117,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public List> verticalOrder(TreeNode root) { - List> ans = new ArrayList<>(); - if (root == null) { - return ans; - } - Deque> q = new ArrayDeque<>(); - q.offer(new Pair<>(root, 0)); - TreeMap> d = new TreeMap<>(); - while (!q.isEmpty()) { - for (int n = q.size(); n > 0; --n) { - var p = q.pollFirst(); - root = p.getKey(); - int offset = p.getValue(); - d.computeIfAbsent(offset, k -> new ArrayList()).add(root.val); - if (root.left != null) { - q.offer(new Pair<>(root.left, offset - 1)); - } - if (root.right != null) { - q.offer(new Pair<>(root.right, offset + 1)); - } - } - } - return new ArrayList<>(d.values()); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -240,49 +160,122 @@ public: }; ``` -### **C++** +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func verticalOrder(root *TreeNode) [][]int { + d := map[int][][]int{} + var dfs func(*TreeNode, int, int) + dfs = func(root *TreeNode, depth, offset int) { + if root == nil { + return + } + d[offset] = append(d[offset], []int{depth, root.Val}) + dfs(root.Left, depth+1, offset-1) + dfs(root.Right, depth+1, offset+1) + } + dfs(root, 0, 0) + idx := []int{} + for i := range d { + idx = append(idx, i) + } + sort.Ints(idx) + ans := [][]int{} + for _, i := range idx { + v := d[i] + sort.SliceStable(v, func(i, j int) bool { return v[i][0] < v[j][0] }) + t := []int{} + for _, x := range v { + t = append(t, x[1]) + } + ans = append(ans, t) + } + return ans +} +``` -```cpp + + +### Solution 2: BFS + +A better approach to this problem should be BFS, traversing from top to bottom level by level. + +The time complexity is $O(n\log n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree. + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + if root is None: + return [] + q = deque([(root, 0)]) + d = defaultdict(list) + while q: + for _ in range(len(q)): + root, offset = q.popleft() + d[offset].append(root.val) + if root.left: + q.append((root.left, offset - 1)) + if root.right: + q.append((root.right, offset + 1)) + return [v for _, v in sorted(d.items())] +``` + +```java /** * Definition for a binary tree node. - * struct TreeNode { + * public class TreeNode { * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } */ -using pii = pair; - class Solution { -public: - map> d; - - vector> verticalOrder(TreeNode* root) { - dfs(root, 0, 0); - vector> ans; - for (auto& [_, v] : d) { - sort(v.begin(), v.end(), [&](pii& a, pii& b) { - return a.first < b.first; - }); - vector t; - for (auto& x : v) { - t.push_back(x.second); + public List> verticalOrder(TreeNode root) { + List> ans = new ArrayList<>(); + if (root == null) { + return ans; + } + Deque> q = new ArrayDeque<>(); + q.offer(new Pair<>(root, 0)); + TreeMap> d = new TreeMap<>(); + while (!q.isEmpty()) { + for (int n = q.size(); n > 0; --n) { + var p = q.pollFirst(); + root = p.getKey(); + int offset = p.getValue(); + d.computeIfAbsent(offset, k -> new ArrayList()).add(root.val); + if (root.left != null) { + q.offer(new Pair<>(root.left, offset - 1)); + } + if (root.right != null) { + q.offer(new Pair<>(root.right, offset + 1)); + } } - ans.push_back(t); } - return ans; - } - - void dfs(TreeNode* root, int depth, int offset) { - if (!root) return; - d[offset].push_back({depth, root->val}); - dfs(root->left, depth + 1, offset - 1); - dfs(root->right, depth + 1, offset + 1); + return new ArrayList<>(d.values()); } -}; +} ``` ```cpp @@ -323,48 +316,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func verticalOrder(root *TreeNode) [][]int { - d := map[int][][]int{} - var dfs func(*TreeNode, int, int) - dfs = func(root *TreeNode, depth, offset int) { - if root == nil { - return - } - d[offset] = append(d[offset], []int{depth, root.Val}) - dfs(root.Left, depth+1, offset-1) - dfs(root.Right, depth+1, offset+1) - } - dfs(root, 0, 0) - idx := []int{} - for i := range d { - idx = append(idx, i) - } - sort.Ints(idx) - ans := [][]int{} - for _, i := range idx { - v := d[i] - sort.SliceStable(v, func(i, j int) bool { return v[i][0] < v[j][0] }) - t := []int{} - for _, x := range v { - t = append(t, x[1]) - } - ans = append(ans, t) - } - return ans -} -``` - ```go /** * Definition for a binary tree node. @@ -413,10 +364,6 @@ type pair struct { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0315.Count of Smaller Numbers After Self/README.md b/solution/0300-0399/0315.Count of Smaller Numbers After Self/README.md index 7cac65354a711..763ac0c378611 100644 --- a/solution/0300-0399/0315.Count of Smaller Numbers After Self/README.md +++ b/solution/0300-0399/0315.Count of Smaller Numbers After Self/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:树状数组** +### 方法一:树状数组 树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作: @@ -64,25 +62,8 @@ 解决方案是直接遍历数组,每个位置先求出 `query(a[i])`,然后再修改树状数组 `update(a[i], 1)` 即可。当数的范围比较大时,需要进行离散化,即先进行去重并排序,然后对每个数字进行编号。 -**方法二:线段树** - -线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。 - -- 线段树的每个节点代表一个区间; -- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 `[1, N]`; -- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`; -- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。 - -**方法三:归并排序** - -### **Python3** - - - -树状数组: - ```python class BinaryIndexedTree: def __init__(self, n): @@ -119,7 +100,182 @@ class Solution: return ans[::-1] ``` -线段树: +```java +class Solution { + public List countSmaller(int[] nums) { + Set s = new HashSet<>(); + for (int v : nums) { + s.add(v); + } + List alls = new ArrayList<>(s); + alls.sort(Comparator.comparingInt(a -> a)); + int n = alls.size(); + Map m = new HashMap<>(n); + for (int i = 0; i < n; ++i) { + m.put(alls.get(i), i + 1); + } + BinaryIndexedTree tree = new BinaryIndexedTree(n); + LinkedList ans = new LinkedList<>(); + for (int i = nums.length - 1; i >= 0; --i) { + int x = m.get(nums[i]); + tree.update(x, 1); + ans.addFirst(tree.query(x - 1)); + } + return ans; + } +} + +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + public static int lowbit(int x) { + return x & -x; + } +} +``` + +```cpp +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + int lowbit(int x) { + return x & -x; + } +}; + +class Solution { +public: + vector countSmaller(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + vector alls(s.begin(), s.end()); + sort(alls.begin(), alls.end()); + unordered_map m; + int n = alls.size(); + for (int i = 0; i < n; ++i) m[alls[i]] = i + 1; + BinaryIndexedTree* tree = new BinaryIndexedTree(n); + vector ans(nums.size()); + for (int i = nums.size() - 1; i >= 0; --i) { + int x = m[nums[i]]; + tree->update(x, 1); + ans[i] = tree->query(x - 1); + } + return ans; + } +}; +``` + +```go +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) lowbit(x int) int { + return x & -x +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += this.lowbit(x) + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= this.lowbit(x) + } + return s +} + +func countSmaller(nums []int) []int { + s := make(map[int]bool) + for _, v := range nums { + s[v] = true + } + var alls []int + for v := range s { + alls = append(alls, v) + } + sort.Ints(alls) + m := make(map[int]int) + for i, v := range alls { + m[v] = i + 1 + } + ans := make([]int, len(nums)) + tree := newBinaryIndexedTree(len(alls)) + for i := len(nums) - 1; i >= 0; i-- { + x := m[nums[i]] + tree.update(x, 1) + ans[i] = tree.query(x - 1) + } + return ans +} +``` + + + +### 方法二:线段树 + +线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。 + +- 线段树的每个节点代表一个区间; +- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 `[1, N]`; +- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`; +- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。 + + ```python class Node: @@ -182,70 +338,6 @@ class Solution: return ans[::-1] ``` -### **Java** - - - -树状数组: - -```java -class Solution { - public List countSmaller(int[] nums) { - Set s = new HashSet<>(); - for (int v : nums) { - s.add(v); - } - List alls = new ArrayList<>(s); - alls.sort(Comparator.comparingInt(a -> a)); - int n = alls.size(); - Map m = new HashMap<>(n); - for (int i = 0; i < n; ++i) { - m.put(alls.get(i), i + 1); - } - BinaryIndexedTree tree = new BinaryIndexedTree(n); - LinkedList ans = new LinkedList<>(); - for (int i = nums.length - 1; i >= 0; --i) { - int x = m.get(nums[i]); - tree.update(x, 1); - ans.addFirst(tree.query(x - 1)); - } - return ans; - } -} - -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - public static int lowbit(int x) { - return x & -x; - } -} -``` - -线段树: - ```java class Solution { public List countSmaller(int[] nums) { @@ -334,64 +426,6 @@ class SegmentTree { } ``` -### **C++** - -树状数组: - -```cpp -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - int lowbit(int x) { - return x & -x; - } -}; - -class Solution { -public: - vector countSmaller(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - vector alls(s.begin(), s.end()); - sort(alls.begin(), alls.end()); - unordered_map m; - int n = alls.size(); - for (int i = 0; i < n; ++i) m[alls[i]] = i + 1; - BinaryIndexedTree* tree = new BinaryIndexedTree(n); - vector ans(nums.size()); - for (int i = nums.size() - 1; i >= 0; --i) { - int x = m[nums[i]]; - tree->update(x, 1); - ans[i] = tree->query(x - 1); - } - return ans; - } -}; -``` - -线段树: - ```cpp class Node { public: @@ -467,68 +501,6 @@ public: }; ``` -### **Go** - -树状数组: - -```go -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (this *BinaryIndexedTree) lowbit(x int) int { - return x & -x -} - -func (this *BinaryIndexedTree) update(x, delta int) { - for x <= this.n { - this.c[x] += delta - x += this.lowbit(x) - } -} - -func (this *BinaryIndexedTree) query(x int) int { - s := 0 - for x > 0 { - s += this.c[x] - x -= this.lowbit(x) - } - return s -} - -func countSmaller(nums []int) []int { - s := make(map[int]bool) - for _, v := range nums { - s[v] = true - } - var alls []int - for v := range s { - alls = append(alls, v) - } - sort.Ints(alls) - m := make(map[int]int) - for i, v := range alls { - m[v] = i + 1 - } - ans := make([]int, len(nums)) - tree := newBinaryIndexedTree(len(alls)) - for i := len(nums) - 1; i >= 0; i-- { - x := m[nums[i]] - tree.update(x, 1) - ans[i] = tree.query(x - 1) - } - return ans -} -``` - -归并排序: - ```go type Pair struct { val int @@ -588,10 +560,8 @@ func merge(arr []Pair, low, mid, high int) { } ``` -### **...** + -``` +### 方法三:归并排序 -``` - - + diff --git a/solution/0300-0399/0315.Count of Smaller Numbers After Self/README_EN.md b/solution/0300-0399/0315.Count of Smaller Numbers After Self/README_EN.md index 38f5c5c2307ac..3b4119fff1d6a 100644 --- a/solution/0300-0399/0315.Count of Smaller Numbers After Self/README_EN.md +++ b/solution/0300-0399/0315.Count of Smaller Numbers After Self/README_EN.md @@ -43,14 +43,10 @@ To the right of 1 there is 0 smaller element. ## Solutions -Binary Indexed Tree or Segment Tree. +### Solution 1 -### **Python3** - -Binary Indexed Tree: - ```python class BinaryIndexedTree: def __init__(self, n): @@ -87,6 +83,176 @@ class Solution: return ans[::-1] ``` +```java +class Solution { + public List countSmaller(int[] nums) { + Set s = new HashSet<>(); + for (int v : nums) { + s.add(v); + } + List alls = new ArrayList<>(s); + alls.sort(Comparator.comparingInt(a -> a)); + int n = alls.size(); + Map m = new HashMap<>(n); + for (int i = 0; i < n; ++i) { + m.put(alls.get(i), i + 1); + } + BinaryIndexedTree tree = new BinaryIndexedTree(n); + LinkedList ans = new LinkedList<>(); + for (int i = nums.length - 1; i >= 0; --i) { + int x = m.get(nums[i]); + tree.update(x, 1); + ans.addFirst(tree.query(x - 1)); + } + return ans; + } +} + +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + public static int lowbit(int x) { + return x & -x; + } +} +``` + +```cpp +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + int lowbit(int x) { + return x & -x; + } +}; + +class Solution { +public: + vector countSmaller(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + vector alls(s.begin(), s.end()); + sort(alls.begin(), alls.end()); + unordered_map m; + int n = alls.size(); + for (int i = 0; i < n; ++i) m[alls[i]] = i + 1; + BinaryIndexedTree* tree = new BinaryIndexedTree(n); + vector ans(nums.size()); + for (int i = nums.size() - 1; i >= 0; --i) { + int x = m[nums[i]]; + tree->update(x, 1); + ans[i] = tree->query(x - 1); + } + return ans; + } +}; +``` + +```go +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) lowbit(x int) int { + return x & -x +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += this.lowbit(x) + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= this.lowbit(x) + } + return s +} + +func countSmaller(nums []int) []int { + s := make(map[int]bool) + for _, v := range nums { + s[v] = true + } + var alls []int + for v := range s { + alls = append(alls, v) + } + sort.Ints(alls) + m := make(map[int]int) + for i, v := range alls { + m[v] = i + 1 + } + ans := make([]int, len(nums)) + tree := newBinaryIndexedTree(len(alls)) + for i := len(nums) - 1; i >= 0; i-- { + x := m[nums[i]] + tree.update(x, 1) + ans[i] = tree.query(x - 1) + } + return ans +} +``` + + + +### Solution 2 + + + ```python class Node: def __init__(self): @@ -148,68 +314,6 @@ class Solution: return ans[::-1] ``` -### **Java** - -Binary Indexed Tree: - -```java -class Solution { - public List countSmaller(int[] nums) { - Set s = new HashSet<>(); - for (int v : nums) { - s.add(v); - } - List alls = new ArrayList<>(s); - alls.sort(Comparator.comparingInt(a -> a)); - int n = alls.size(); - Map m = new HashMap<>(n); - for (int i = 0; i < n; ++i) { - m.put(alls.get(i), i + 1); - } - BinaryIndexedTree tree = new BinaryIndexedTree(n); - LinkedList ans = new LinkedList<>(); - for (int i = nums.length - 1; i >= 0; --i) { - int x = m.get(nums[i]); - tree.update(x, 1); - ans.addFirst(tree.query(x - 1)); - } - return ans; - } -} - -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - public static int lowbit(int x) { - return x & -x; - } -} -``` - -Segment Tree: - ```java class Solution { public List countSmaller(int[] nums) { @@ -298,64 +402,6 @@ class SegmentTree { } ``` -### **C++** - -Binary Indexed Tree: - -```cpp -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - int lowbit(int x) { - return x & -x; - } -}; - -class Solution { -public: - vector countSmaller(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - vector alls(s.begin(), s.end()); - sort(alls.begin(), alls.end()); - unordered_map m; - int n = alls.size(); - for (int i = 0; i < n; ++i) m[alls[i]] = i + 1; - BinaryIndexedTree* tree = new BinaryIndexedTree(n); - vector ans(nums.size()); - for (int i = nums.size() - 1; i >= 0; --i) { - int x = m[nums[i]]; - tree->update(x, 1); - ans[i] = tree->query(x - 1); - } - return ans; - } -}; -``` - -Segment Tree: - ```cpp class Node { public: @@ -431,70 +477,65 @@ public: }; ``` -### **Go** - -Binary Indexed Tree: - ```go -type BinaryIndexedTree struct { - n int - c []int +type Pair struct { + val int + index int } -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (this *BinaryIndexedTree) lowbit(x int) int { - return x & -x -} +var ( + tmp []Pair + count []int +) -func (this *BinaryIndexedTree) update(x, delta int) { - for x <= this.n { - this.c[x] += delta - x += this.lowbit(x) +func countSmaller(nums []int) []int { + tmp, count = make([]Pair, len(nums)), make([]int, len(nums)) + array := make([]Pair, len(nums)) + for i, v := range nums { + array[i] = Pair{val: v, index: i} } + sorted(array, 0, len(array)-1) + return count } -func (this *BinaryIndexedTree) query(x int) int { - s := 0 - for x > 0 { - s += this.c[x] - x -= this.lowbit(x) +func sorted(arr []Pair, low, high int) { + if low >= high { + return } - return s + mid := low + (high-low)/2 + sorted(arr, low, mid) + sorted(arr, mid+1, high) + merge(arr, low, mid, high) } -func countSmaller(nums []int) []int { - s := make(map[int]bool) - for _, v := range nums { - s[v] = true +func merge(arr []Pair, low, mid, high int) { + left, right := low, mid+1 + idx := low + for left <= mid && right <= high { + if arr[left].val <= arr[right].val { + count[arr[left].index] += right - mid - 1 + tmp[idx], left = arr[left], left+1 + } else { + tmp[idx], right = arr[right], right+1 + } + idx++ } - var alls []int - for v := range s { - alls = append(alls, v) + for left <= mid { + count[arr[left].index] += right - mid - 1 + tmp[idx] = arr[left] + idx, left = idx+1, left+1 } - sort.Ints(alls) - m := make(map[int]int) - for i, v := range alls { - m[v] = i + 1 + for right <= high { + tmp[idx] = arr[right] + idx, right = idx+1, right+1 } - ans := make([]int, len(nums)) - tree := newBinaryIndexedTree(len(alls)) - for i := len(nums) - 1; i >= 0; i-- { - x := m[nums[i]] - tree.update(x, 1) - ans[i] = tree.query(x - 1) + // 排序 + for i := low; i <= high; i++ { + arr[i] = tmp[i] } - return ans } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0316.Remove Duplicate Letters/README.md b/solution/0300-0399/0316.Remove Duplicate Letters/README.md index ec21fa3e43375..ddfdeb894936d 100644 --- a/solution/0300-0399/0316.Remove Duplicate Letters/README.md +++ b/solution/0300-0399/0316.Remove Duplicate Letters/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 我们用一个数组 `last` 记录每个字符最后一次出现的位置,用栈来保存结果字符串,用一个数组 `vis` 或者一个整型变量 `mask` 记录当前字符是否在栈中。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def removeDuplicateLetters(self, s: str) -> str: @@ -72,32 +66,6 @@ class Solution: return ''.join(stk) ``` -```python -class Solution: - def removeDuplicateLetters(self, s: str) -> str: - count, in_stack = [0] * 128, [False] * 128 - stack = [] - for c in s: - count[ord(c)] += 1 - for c in s: - count[ord(c)] -= 1 - if in_stack[ord(c)]: - continue - while len(stack) and stack[-1] > c: - peek = stack[-1] - if count[ord(peek)] < 1: - break - in_stack[ord(peek)] = False - stack.pop() - stack.append(c) - in_stack[ord(c)] = True - return ''.join(stack) -``` - -### **Java** - - - ```java class Solution { public String removeDuplicateLetters(String s) { @@ -128,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +124,6 @@ public: }; ``` -### **Go** - ```go func removeDuplicateLetters(s string) string { last := make([]int, 26) @@ -183,6 +147,34 @@ func removeDuplicateLetters(s string) string { } ``` + + +### 方法二 + + + +```python +class Solution: + def removeDuplicateLetters(self, s: str) -> str: + count, in_stack = [0] * 128, [False] * 128 + stack = [] + for c in s: + count[ord(c)] += 1 + for c in s: + count[ord(c)] -= 1 + if in_stack[ord(c)]: + continue + while len(stack) and stack[-1] > c: + peek = stack[-1] + if count[ord(peek)] < 1: + break + in_stack[ord(peek)] = False + stack.pop() + stack.append(c) + in_stack[ord(c)] = True + return ''.join(stack) +``` + ```go func removeDuplicateLetters(s string) string { count, in_stack, stack := make([]int, 128), make([]bool, 128), make([]rune, 0) @@ -207,10 +199,6 @@ func removeDuplicateLetters(s string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0316.Remove Duplicate Letters/README_EN.md b/solution/0300-0399/0316.Remove Duplicate Letters/README_EN.md index 6e8ad2739be1c..bfa407dbae416 100644 --- a/solution/0300-0399/0316.Remove Duplicate Letters/README_EN.md +++ b/solution/0300-0399/0316.Remove Duplicate Letters/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Stack** +### Solution 1: Stack We use an array `last` to record the last occurrence of each character, a stack to save the result string, and an array `vis` or an integer variable `mask` to record whether the current character is in the stack. @@ -46,8 +46,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def removeDuplicateLetters(self, s: str) -> str: @@ -64,30 +62,6 @@ class Solution: return ''.join(stk) ``` -```python -class Solution: - def removeDuplicateLetters(self, s: str) -> str: - count, in_stack = [0] * 128, [False] * 128 - stack = [] - for c in s: - count[ord(c)] += 1 - for c in s: - count[ord(c)] -= 1 - if in_stack[ord(c)]: - continue - while len(stack) and stack[-1] > c: - peek = stack[-1] - if count[ord(peek)] < 1: - break - in_stack[ord(peek)] = False - stack.pop() - stack.append(c) - in_stack[ord(c)] = True - return ''.join(stack) -``` - -### **Java** - ```java class Solution { public String removeDuplicateLetters(String s) { @@ -118,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +120,6 @@ public: }; ``` -### **Go** - ```go func removeDuplicateLetters(s string) string { last := make([]int, 26) @@ -173,6 +143,34 @@ func removeDuplicateLetters(s string) string { } ``` + + +### Solution 2 + + + +```python +class Solution: + def removeDuplicateLetters(self, s: str) -> str: + count, in_stack = [0] * 128, [False] * 128 + stack = [] + for c in s: + count[ord(c)] += 1 + for c in s: + count[ord(c)] -= 1 + if in_stack[ord(c)]: + continue + while len(stack) and stack[-1] > c: + peek = stack[-1] + if count[ord(peek)] < 1: + break + in_stack[ord(peek)] = False + stack.pop() + stack.append(c) + in_stack[ord(c)] = True + return ''.join(stack) +``` + ```go func removeDuplicateLetters(s string) string { count, in_stack, stack := make([]int, 128), make([]bool, 128), make([]rune, 0) @@ -197,10 +195,6 @@ func removeDuplicateLetters(s string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0317.Shortest Distance from All Buildings/README.md b/solution/0300-0399/0317.Shortest Distance from All Buildings/README.md index 90d6852be8e67..ae3e86ec57838 100644 --- a/solution/0300-0399/0317.Shortest Distance from All Buildings/README.md +++ b/solution/0300-0399/0317.Shortest Distance from All Buildings/README.md @@ -64,18 +64,10 @@ ## 解法 - - -BFS。 - -记 total 变量表示建筑物(`grid[i][j] = 1`)的个数,`cnt[i][j]` 表示空地 `(i, j)` 上能到达的建筑物数量;`dist[i][j]` 表示空地 `(i, j)` 到每个建筑物的距离之和。求解的是满足 `cnt[i][j] == total` 的空地距离和的最小值。 +### 方法一 -### **Python3** - - - ```python class Solution: def shortestDistance(self, grid: List[List[int]]) -> int: @@ -115,10 +107,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - - - ```java class Solution { public int shortestDistance(int[][] grid) { @@ -169,8 +157,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -220,8 +206,6 @@ public: }; ``` -### **Go** - ```go func shortestDistance(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -278,10 +262,6 @@ func shortestDistance(grid [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md b/solution/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md index afc05718190cc..cc5fa2390f26c 100644 --- a/solution/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md +++ b/solution/0300-0399/0317.Shortest Distance from All Buildings/README_EN.md @@ -58,12 +58,10 @@ So return 7. ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def shortestDistance(self, grid: List[List[int]]) -> int: @@ -103,8 +101,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - ```java class Solution { public int shortestDistance(int[][] grid) { @@ -155,8 +151,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -206,8 +200,6 @@ public: }; ``` -### **Go** - ```go func shortestDistance(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -264,10 +256,6 @@ func shortestDistance(grid [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0318.Maximum Product of Word Lengths/README.md b/solution/0300-0399/0318.Maximum Product of Word Lengths/README.md index 304ead3f06e26..6c0286804199d 100644 --- a/solution/0300-0399/0318.Maximum Product of Word Lengths/README.md +++ b/solution/0300-0399/0318.Maximum Product of Word Lengths/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 题目需要我们找到两个没有公共字母的字符串,使得它们的长度乘积最大。我们可以将每个字符串用一个二进制数 $mask[i]$ 表示,这个二进制数的每一位表示字符串中是否含有某个字母。如果两个字符串没有公共字母,那么这两个字符串对应的二进制数的按位与的结果为 $0$,即 $mask[i] \& mask[j] = 0$。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def maxProduct(self, words: List[str]) -> int: @@ -76,27 +70,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxProduct(self, words: List[str]) -> int: - mask = defaultdict(int) - ans = 0 - for s in words: - a = len(s) - x = 0 - for c in s: - x |= 1 << (ord(c) - ord("a")) - for y, b in mask.items(): - if (x & y) == 0: - ans = max(ans, a * b) - mask[x] = max(mask[x], a) - return ans -``` - -### **Java** - - - ```java class Solution { public int maxProduct(String[] words) { @@ -118,6 +91,89 @@ class Solution { } ``` +```cpp +class Solution { +public: + int maxProduct(vector& words) { + int n = words.size(); + int mask[n]; + memset(mask, 0, sizeof(mask)); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (char& c : words[i]) { + mask[i] |= 1 << (c - 'a'); + } + for (int j = 0; j < i; ++j) { + if ((mask[i] & mask[j]) == 0) { + ans = max(ans, (int) (words[i].size() * words[j].size())); + } + } + } + return ans; + } +}; +``` + +```go +func maxProduct(words []string) (ans int) { + n := len(words) + mask := make([]int, n) + for i, s := range words { + for _, c := range s { + mask[i] |= 1 << (c - 'a') + } + for j, t := range words[:i] { + if mask[i]&mask[j] == 0 { + ans = max(ans, len(s)*len(t)) + } + } + } + return +} +``` + +```ts +function maxProduct(words: string[]): number { + const n = words.length; + const mask: number[] = Array(n).fill(0); + let ans = 0; + for (let i = 0; i < n; ++i) { + for (const c of words[i]) { + mask[i] |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); + } + for (let j = 0; j < i; ++j) { + if ((mask[i] & mask[j]) === 0) { + ans = Math.max(ans, words[i].length * words[j].length); + } + } + } + return ans; +} +``` + + + +### 方法二 + + + +```python +class Solution: + def maxProduct(self, words: List[str]) -> int: + mask = defaultdict(int) + ans = 0 + for s in words: + a = len(s) + x = 0 + for c in s: + x |= 1 << (ord(c) - ord("a")) + for y, b in mask.items(): + if (x & y) == 0: + ans = max(ans, a * b) + mask[x] = max(mask[x], a) + return ans +``` + ```java class Solution { public int maxProduct(String[] words) { @@ -142,31 +198,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maxProduct(vector& words) { - int n = words.size(); - int mask[n]; - memset(mask, 0, sizeof(mask)); - int ans = 0; - for (int i = 0; i < n; ++i) { - for (char& c : words[i]) { - mask[i] |= 1 << (c - 'a'); - } - for (int j = 0; j < i; ++j) { - if ((mask[i] & mask[j]) == 0) { - ans = max(ans, (int) (words[i].size() * words[j].size())); - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -191,26 +222,6 @@ public: }; ``` -### **Go** - -```go -func maxProduct(words []string) (ans int) { - n := len(words) - mask := make([]int, n) - for i, s := range words { - for _, c := range s { - mask[i] |= 1 << (c - 'a') - } - for j, t := range words[:i] { - if mask[i]&mask[j] == 0 { - ans = max(ans, len(s)*len(t)) - } - } - } - return -} -``` - ```go func maxProduct(words []string) (ans int) { mask := map[int]int{} @@ -231,27 +242,6 @@ func maxProduct(words []string) (ans int) { } ``` -### **TypeScript** - -```ts -function maxProduct(words: string[]): number { - const n = words.length; - const mask: number[] = Array(n).fill(0); - let ans = 0; - for (let i = 0; i < n; ++i) { - for (const c of words[i]) { - mask[i] |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); - } - for (let j = 0; j < i; ++j) { - if ((mask[i] & mask[j]) === 0) { - ans = Math.max(ans, words[i].length * words[j].length); - } - } - } - return ans; -} -``` - ```ts function maxProduct(words: string[]): number { const mask: Map = new Map(); @@ -273,10 +263,6 @@ function maxProduct(words: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0318.Maximum Product of Word Lengths/README_EN.md b/solution/0300-0399/0318.Maximum Product of Word Lengths/README_EN.md index 104778a58d348..9bac1b703fa51 100644 --- a/solution/0300-0399/0318.Maximum Product of Word Lengths/README_EN.md +++ b/solution/0300-0399/0318.Maximum Product of Word Lengths/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Bit Manipulation** +### Solution 1: Bit Manipulation The problem requires us to find two strings without common letters, so that their length product is maximized. We can represent each string with a binary number $mask[i]$, where each bit of this binary number indicates whether the string contains a certain letter. If two strings do not have common letters, then the bitwise AND result of the two binary numbers corresponding to these strings is $0$, that is, $mask[i] \& mask[j] = 0$. @@ -54,8 +54,6 @@ The time complexity is $O(n^2 + L)$, and the space complexity is $O(n)$. Here, $ -### **Python3** - ```python class Solution: def maxProduct(self, words: List[str]) -> int: @@ -70,25 +68,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxProduct(self, words: List[str]) -> int: - mask = defaultdict(int) - ans = 0 - for s in words: - a = len(s) - x = 0 - for c in s: - x |= 1 << (ord(c) - ord("a")) - for y, b in mask.items(): - if (x & y) == 0: - ans = max(ans, a * b) - mask[x] = max(mask[x], a) - return ans -``` - -### **Java** - ```java class Solution { public int maxProduct(String[] words) { @@ -110,6 +89,89 @@ class Solution { } ``` +```cpp +class Solution { +public: + int maxProduct(vector& words) { + int n = words.size(); + int mask[n]; + memset(mask, 0, sizeof(mask)); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (char& c : words[i]) { + mask[i] |= 1 << (c - 'a'); + } + for (int j = 0; j < i; ++j) { + if ((mask[i] & mask[j]) == 0) { + ans = max(ans, (int) (words[i].size() * words[j].size())); + } + } + } + return ans; + } +}; +``` + +```go +func maxProduct(words []string) (ans int) { + n := len(words) + mask := make([]int, n) + for i, s := range words { + for _, c := range s { + mask[i] |= 1 << (c - 'a') + } + for j, t := range words[:i] { + if mask[i]&mask[j] == 0 { + ans = max(ans, len(s)*len(t)) + } + } + } + return +} +``` + +```ts +function maxProduct(words: string[]): number { + const n = words.length; + const mask: number[] = Array(n).fill(0); + let ans = 0; + for (let i = 0; i < n; ++i) { + for (const c of words[i]) { + mask[i] |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); + } + for (let j = 0; j < i; ++j) { + if ((mask[i] & mask[j]) === 0) { + ans = Math.max(ans, words[i].length * words[j].length); + } + } + } + return ans; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def maxProduct(self, words: List[str]) -> int: + mask = defaultdict(int) + ans = 0 + for s in words: + a = len(s) + x = 0 + for c in s: + x |= 1 << (ord(c) - ord("a")) + for y, b in mask.items(): + if (x & y) == 0: + ans = max(ans, a * b) + mask[x] = max(mask[x], a) + return ans +``` + ```java class Solution { public int maxProduct(String[] words) { @@ -134,31 +196,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maxProduct(vector& words) { - int n = words.size(); - int mask[n]; - memset(mask, 0, sizeof(mask)); - int ans = 0; - for (int i = 0; i < n; ++i) { - for (char& c : words[i]) { - mask[i] |= 1 << (c - 'a'); - } - for (int j = 0; j < i; ++j) { - if ((mask[i] & mask[j]) == 0) { - ans = max(ans, (int) (words[i].size() * words[j].size())); - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -183,26 +220,6 @@ public: }; ``` -### **Go** - -```go -func maxProduct(words []string) (ans int) { - n := len(words) - mask := make([]int, n) - for i, s := range words { - for _, c := range s { - mask[i] |= 1 << (c - 'a') - } - for j, t := range words[:i] { - if mask[i]&mask[j] == 0 { - ans = max(ans, len(s)*len(t)) - } - } - } - return -} -``` - ```go func maxProduct(words []string) (ans int) { mask := map[int]int{} @@ -223,27 +240,6 @@ func maxProduct(words []string) (ans int) { } ``` -### **TypeScript** - -```ts -function maxProduct(words: string[]): number { - const n = words.length; - const mask: number[] = Array(n).fill(0); - let ans = 0; - for (let i = 0; i < n; ++i) { - for (const c of words[i]) { - mask[i] |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); - } - for (let j = 0; j < i; ++j) { - if ((mask[i] & mask[j]) === 0) { - ans = Math.max(ans, words[i].length * words[j].length); - } - } - } - return ans; -} -``` - ```ts function maxProduct(words: string[]): number { const mask: Map = new Map(); @@ -265,10 +261,6 @@ function maxProduct(words: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0319.Bulb Switcher/README.md b/solution/0300-0399/0319.Bulb Switcher/README.md index 7e306837fdad0..78c54fbfc6f15 100644 --- a/solution/0300-0399/0319.Bulb Switcher/README.md +++ b/solution/0300-0399/0319.Bulb Switcher/README.md @@ -54,32 +54,24 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def bulbSwitch(self, n: int) -> int: return int(n ** (1 / 2)) ``` -### **Java** - - - ```java - -``` - -### **...** - -``` - +class Solution { + public int bulbSwitch(int n) { + return (int) Math.sqrt(n); + } +} ``` + + diff --git a/solution/0300-0399/0319.Bulb Switcher/README_EN.md b/solution/0300-0399/0319.Bulb Switcher/README_EN.md index 4722dcd00e3d2..769553a91c68a 100644 --- a/solution/0300-0399/0319.Bulb Switcher/README_EN.md +++ b/solution/0300-0399/0319.Bulb Switcher/README_EN.md @@ -45,9 +45,9 @@ So you should return 1 because there is only one bulb is on. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,16 +55,14 @@ class Solution: return int(n ** (1 / 2)) ``` -### **Java** - ```java - -``` - -### **...** - -``` - +class Solution { + public int bulbSwitch(int n) { + return (int) Math.sqrt(n); + } +} ``` + + diff --git a/solution/0300-0399/0320.Generalized Abbreviation/README.md b/solution/0300-0399/0320.Generalized Abbreviation/README.md index 9f621500aa650..914b3673a3a68 100644 --- a/solution/0300-0399/0320.Generalized Abbreviation/README.md +++ b/solution/0300-0399/0320.Generalized Abbreviation/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们设计一个函数 $dfs(i)$,表示对于字符串 $word[i:]$,返回其所有可能的缩写。 @@ -72,18 +70,8 @@ 时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $word$ 的长度。 -**方法二:二进制枚举** - -由于字符串 $word$ 的长度不超过 $15$,因此我们可以使用二进制枚举的方法枚举所有的缩写。我们用一个长度为 $n$ 的二进制数 $i$ 表示一种缩写方式,其中 $0$ 表示保留对应的字符,而 $1$ 表示删除对应的字符。我们在 $[0, 2^n)$ 的范围内枚举所有 $i$,并将其转换成对应的缩写,添加到答案列表中即可。 - -时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $word$ 的长度。 - -### **Python3** - - - ```python class Solution: def generateAbbreviations(self, word: str) -> List[str]: @@ -100,32 +88,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def generateAbbreviations(self, word: str) -> List[str]: - n = len(word) - ans = [] - for i in range(1 << n): - cnt = 0 - s = [] - for j in range(n): - if i >> j & 1: - cnt += 1 - else: - if cnt: - s.append(str(cnt)) - cnt = 0 - s.append(word[j]) - if cnt: - s.append(str(cnt)) - ans.append("".join(s)) - return ans -``` - -### **Java** - - - ```java class Solution { private String word; @@ -155,6 +117,114 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector generateAbbreviations(string word) { + int n = word.size(); + function(int)> dfs = [&](int i) -> vector { + if (i >= n) { + return {""}; + } + vector ans; + for (auto& s : dfs(i + 1)) { + string p(1, word[i]); + ans.emplace_back(p + s); + } + for (int j = i + 1; j <= n; ++j) { + for (auto& s : dfs(j + 1)) { + string p = j < n ? string(1, word[j]) : ""; + ans.emplace_back(to_string(j - i) + p + s); + } + } + return ans; + }; + return dfs(0); + } +}; +``` + +```go +func generateAbbreviations(word string) []string { + n := len(word) + var dfs func(int) []string + dfs = func(i int) []string { + if i >= n { + return []string{""} + } + ans := []string{} + for _, s := range dfs(i + 1) { + ans = append(ans, word[i:i+1]+s) + } + for j := i + 1; j <= n; j++ { + for _, s := range dfs(j + 1) { + p := "" + if j < n { + p = word[j : j+1] + } + ans = append(ans, strconv.Itoa(j-i)+p+s) + } + } + return ans + } + return dfs(0) +} +``` + +```ts +function generateAbbreviations(word: string): string[] { + const n = word.length; + const dfs = (i: number): string[] => { + if (i >= n) { + return ['']; + } + const ans: string[] = []; + for (const s of dfs(i + 1)) { + ans.push(word[i] + s); + } + for (let j = i + 1; j <= n; ++j) { + for (const s of dfs(j + 1)) { + ans.push((j - i).toString() + (j < n ? word[j] : '') + s); + } + } + return ans; + }; + return dfs(0); +} +``` + + + +### 方法二:二进制枚举 + +由于字符串 $word$ 的长度不超过 $15$,因此我们可以使用二进制枚举的方法枚举所有的缩写。我们用一个长度为 $n$ 的二进制数 $i$ 表示一种缩写方式,其中 $0$ 表示保留对应的字符,而 $1$ 表示删除对应的字符。我们在 $[0, 2^n)$ 的范围内枚举所有 $i$,并将其转换成对应的缩写,添加到答案列表中即可。 + +时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $word$ 的长度。 + + + +```python +class Solution: + def generateAbbreviations(self, word: str) -> List[str]: + n = len(word) + ans = [] + for i in range(1 << n): + cnt = 0 + s = [] + for j in range(n): + if i >> j & 1: + cnt += 1 + else: + if cnt: + s.append(str(cnt)) + cnt = 0 + s.append(word[j]) + if cnt: + s.append(str(cnt)) + ans.append("".join(s)) + return ans +``` + ```java class Solution { public List generateAbbreviations(String word) { @@ -184,35 +254,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector generateAbbreviations(string word) { - int n = word.size(); - function(int)> dfs = [&](int i) -> vector { - if (i >= n) { - return {""}; - } - vector ans; - for (auto& s : dfs(i + 1)) { - string p(1, word[i]); - ans.emplace_back(p + s); - } - for (int j = i + 1; j <= n; ++j) { - for (auto& s : dfs(j + 1)) { - string p = j < n ? string(1, word[j]) : ""; - ans.emplace_back(to_string(j - i) + p + s); - } - } - return ans; - }; - return dfs(0); - } -}; -``` - ```cpp class Solution { public: @@ -243,35 +284,6 @@ public: }; ``` -### **Go** - -```go -func generateAbbreviations(word string) []string { - n := len(word) - var dfs func(int) []string - dfs = func(i int) []string { - if i >= n { - return []string{""} - } - ans := []string{} - for _, s := range dfs(i + 1) { - ans = append(ans, word[i:i+1]+s) - } - for j := i + 1; j <= n; j++ { - for _, s := range dfs(j + 1) { - p := "" - if j < n { - p = word[j : j+1] - } - ans = append(ans, strconv.Itoa(j-i)+p+s) - } - } - return ans - } - return dfs(0) -} -``` - ```go func generateAbbreviations(word string) (ans []string) { n := len(word) @@ -298,34 +310,6 @@ func generateAbbreviations(word string) (ans []string) { } ``` -### **TypeScript** - -```ts -function generateAbbreviations(word: string): string[] { - const n = word.length; - const dfs = (i: number): string[] => { - if (i >= n) { - return ['']; - } - const ans: string[] = []; - for (const s of dfs(i + 1)) { - ans.push(word[i] + s); - } - for (let j = i + 1; j <= n; ++j) { - for (const s of dfs(j + 1)) { - ans.push((j - i).toString() + (j < n ? word[j] : '') + s); - } - } - return ans; - }; - return dfs(0); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0320.Generalized Abbreviation/README_EN.md b/solution/0300-0399/0320.Generalized Abbreviation/README_EN.md index 6e27c86f49940..6ee8f45c4810a 100644 --- a/solution/0300-0399/0320.Generalized Abbreviation/README_EN.md +++ b/solution/0300-0399/0320.Generalized Abbreviation/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We design a function $dfs(i)$, which returns all possible abbreviations for the string $word[i:]$. @@ -59,16 +59,8 @@ Finally, we call $dfs(0)$ in the main function. The time complexity is $O(n \times 2^n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $word$. -**Solution 2: Binary Enumeration** - -Since the length of the string $word$ does not exceed $15$, we can use the method of binary enumeration to enumerate all abbreviations. We use a binary number $i$ of length $n$ to represent an abbreviation, where $0$ represents keeping the corresponding character, and $1$ represents deleting the corresponding character. We enumerate all $i$ in the range of $[0, 2^n)$, convert it into the corresponding abbreviation, and add it to the answer list. - -The time complexity is $O(n \times 2^n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $word$. - -### **Python3** - ```python class Solution: def generateAbbreviations(self, word: str) -> List[str]: @@ -85,30 +77,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def generateAbbreviations(self, word: str) -> List[str]: - n = len(word) - ans = [] - for i in range(1 << n): - cnt = 0 - s = [] - for j in range(n): - if i >> j & 1: - cnt += 1 - else: - if cnt: - s.append(str(cnt)) - cnt = 0 - s.append(word[j]) - if cnt: - s.append(str(cnt)) - ans.append("".join(s)) - return ans -``` - -### **Java** - ```java class Solution { private String word; @@ -138,6 +106,114 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector generateAbbreviations(string word) { + int n = word.size(); + function(int)> dfs = [&](int i) -> vector { + if (i >= n) { + return {""}; + } + vector ans; + for (auto& s : dfs(i + 1)) { + string p(1, word[i]); + ans.emplace_back(p + s); + } + for (int j = i + 1; j <= n; ++j) { + for (auto& s : dfs(j + 1)) { + string p = j < n ? string(1, word[j]) : ""; + ans.emplace_back(to_string(j - i) + p + s); + } + } + return ans; + }; + return dfs(0); + } +}; +``` + +```go +func generateAbbreviations(word string) []string { + n := len(word) + var dfs func(int) []string + dfs = func(i int) []string { + if i >= n { + return []string{""} + } + ans := []string{} + for _, s := range dfs(i + 1) { + ans = append(ans, word[i:i+1]+s) + } + for j := i + 1; j <= n; j++ { + for _, s := range dfs(j + 1) { + p := "" + if j < n { + p = word[j : j+1] + } + ans = append(ans, strconv.Itoa(j-i)+p+s) + } + } + return ans + } + return dfs(0) +} +``` + +```ts +function generateAbbreviations(word: string): string[] { + const n = word.length; + const dfs = (i: number): string[] => { + if (i >= n) { + return ['']; + } + const ans: string[] = []; + for (const s of dfs(i + 1)) { + ans.push(word[i] + s); + } + for (let j = i + 1; j <= n; ++j) { + for (const s of dfs(j + 1)) { + ans.push((j - i).toString() + (j < n ? word[j] : '') + s); + } + } + return ans; + }; + return dfs(0); +} +``` + + + +### Solution 2: Binary Enumeration + +Since the length of the string $word$ does not exceed $15$, we can use the method of binary enumeration to enumerate all abbreviations. We use a binary number $i$ of length $n$ to represent an abbreviation, where $0$ represents keeping the corresponding character, and $1$ represents deleting the corresponding character. We enumerate all $i$ in the range of $[0, 2^n)$, convert it into the corresponding abbreviation, and add it to the answer list. + +The time complexity is $O(n \times 2^n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $word$. + + + +```python +class Solution: + def generateAbbreviations(self, word: str) -> List[str]: + n = len(word) + ans = [] + for i in range(1 << n): + cnt = 0 + s = [] + for j in range(n): + if i >> j & 1: + cnt += 1 + else: + if cnt: + s.append(str(cnt)) + cnt = 0 + s.append(word[j]) + if cnt: + s.append(str(cnt)) + ans.append("".join(s)) + return ans +``` + ```java class Solution { public List generateAbbreviations(String word) { @@ -167,35 +243,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector generateAbbreviations(string word) { - int n = word.size(); - function(int)> dfs = [&](int i) -> vector { - if (i >= n) { - return {""}; - } - vector ans; - for (auto& s : dfs(i + 1)) { - string p(1, word[i]); - ans.emplace_back(p + s); - } - for (int j = i + 1; j <= n; ++j) { - for (auto& s : dfs(j + 1)) { - string p = j < n ? string(1, word[j]) : ""; - ans.emplace_back(to_string(j - i) + p + s); - } - } - return ans; - }; - return dfs(0); - } -}; -``` - ```cpp class Solution { public: @@ -226,35 +273,6 @@ public: }; ``` -### **Go** - -```go -func generateAbbreviations(word string) []string { - n := len(word) - var dfs func(int) []string - dfs = func(i int) []string { - if i >= n { - return []string{""} - } - ans := []string{} - for _, s := range dfs(i + 1) { - ans = append(ans, word[i:i+1]+s) - } - for j := i + 1; j <= n; j++ { - for _, s := range dfs(j + 1) { - p := "" - if j < n { - p = word[j : j+1] - } - ans = append(ans, strconv.Itoa(j-i)+p+s) - } - } - return ans - } - return dfs(0) -} -``` - ```go func generateAbbreviations(word string) (ans []string) { n := len(word) @@ -281,34 +299,6 @@ func generateAbbreviations(word string) (ans []string) { } ``` -### **TypeScript** - -```ts -function generateAbbreviations(word: string): string[] { - const n = word.length; - const dfs = (i: number): string[] => { - if (i >= n) { - return ['']; - } - const ans: string[] = []; - for (const s of dfs(i + 1)) { - ans.push(word[i] + s); - } - for (let j = i + 1; j <= n; ++j) { - for (const s of dfs(j + 1)) { - ans.push((j - i).toString() + (j < n ? word[j] : '') + s); - } - } - return ans; - }; - return dfs(0); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0321.Create Maximum Number/README.md b/solution/0300-0399/0321.Create Maximum Number/README.md index 6688266da1a6e..979b0f4c6ae98 100644 --- a/solution/0300-0399/0321.Create Maximum Number/README.md +++ b/solution/0300-0399/0321.Create Maximum Number/README.md @@ -41,9 +41,7 @@ k = 3 ## 解法 - - -**方法一:枚举 + 单调栈** +### 方法一:枚举 + 单调栈 我们可以枚举从数组 $nums1$ 中取出 $x$ 个数,那么从数组 $nums2$ 中就需要取出 $k-x$ 个数。其中 $x \in [max(0, k-n), min(k, m)]$。 @@ -55,10 +53,6 @@ k = 3 -### **Python3** - - - ```python class Solution: def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]: @@ -114,10 +108,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] maxNumber(int[] nums1, int[] nums2, int k) { @@ -186,8 +176,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -256,8 +244,6 @@ public: }; ``` -### **Go** - ```go func maxNumber(nums1 []int, nums2 []int, k int) []int { m, n := len(nums1), len(nums2) @@ -328,8 +314,6 @@ func maxNumber(nums1 []int, nums2 []int, k int) []int { } ``` -### **TypeScript** - ```ts function maxNumber(nums1: number[], nums2: number[], k: number): number[] { const m = nums1.length; @@ -400,10 +384,6 @@ function merge(nums1: number[], nums2: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0321.Create Maximum Number/README_EN.md b/solution/0300-0399/0321.Create Maximum Number/README_EN.md index 496cb71abb546..d6e04e78a3953 100644 --- a/solution/0300-0399/0321.Create Maximum Number/README_EN.md +++ b/solution/0300-0399/0321.Create Maximum Number/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -104,8 +104,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] maxNumber(int[] nums1, int[] nums2, int k) { @@ -174,8 +172,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -244,8 +240,6 @@ public: }; ``` -### **Go** - ```go func maxNumber(nums1 []int, nums2 []int, k int) []int { m, n := len(nums1), len(nums2) @@ -316,8 +310,6 @@ func maxNumber(nums1 []int, nums2 []int, k int) []int { } ``` -### **TypeScript** - ```ts function maxNumber(nums1: number[], nums2: number[], k: number): number[] { const m = nums1.length; @@ -388,10 +380,6 @@ function merge(nums1: number[], nums2: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0322.Coin Change/README.md b/solution/0300-0399/0322.Coin Change/README.md index f87895b8f13c0..2852a942eeced 100644 --- a/solution/0300-0399/0322.Coin Change/README.md +++ b/solution/0300-0399/0322.Coin Change/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:动态规划(完全背包)** +### 方法一:动态规划(完全背包) 我们定义 $f[i][j]$ 表示使用前 $i$ 种硬币,凑出金额 $j$ 的最少硬币数。初始时 $f[0][0] = 0$,其余位置的值均为正无穷。 @@ -84,10 +82,6 @@ $$ -### **Python3** - - - ```python class Solution: def coinChange(self, coins: List[int], amount: int) -> int: @@ -102,21 +96,6 @@ class Solution: return -1 if f[m][n] >= inf else f[m][n] ``` -```python -class Solution: - def coinChange(self, coins: List[int], amount: int) -> int: - n = amount - f = [0] + [inf] * n - for x in coins: - for j in range(x, n + 1): - f[j] = min(f[j], f[j - x] + 1) - return -1 if f[n] >= inf else f[n] -``` - -### **Java** - - - ```java class Solution { public int coinChange(int[] coins, int amount) { @@ -141,26 +120,6 @@ class Solution { } ``` -```java -class Solution { - public int coinChange(int[] coins, int amount) { - final int inf = 1 << 30; - int n = amount; - int[] f = new int[n + 1]; - Arrays.fill(f, inf); - f[0] = 0; - for (int x : coins) { - for (int j = x; j <= n; ++j) { - f[j] = Math.min(f[j], f[j - x] + 1); - } - } - return f[n] >= inf ? -1 : f[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -182,26 +141,6 @@ public: }; ``` -```cpp -class Solution { -public: - int coinChange(vector& coins, int amount) { - int n = amount; - int f[n + 1]; - memset(f, 0x3f, sizeof(f)); - f[0] = 0; - for (int x : coins) { - for (int j = x; j <= n; ++j) { - f[j] = min(f[j], f[j - x] + 1); - } - } - return f[n] > n ? -1 : f[n]; - } -}; -``` - -### **Go** - ```go func coinChange(coins []int, amount int) int { m, n := len(coins), amount @@ -229,38 +168,11 @@ func coinChange(coins []int, amount int) int { } ``` -```go -func coinChange(coins []int, amount int) int { - n := amount - f := make([]int, n+1) - for i := range f { - f[i] = 1 << 30 - } - f[0] = 0 - for _, x := range coins { - for j := x; j <= n; j++ { - f[j] = min(f[j], f[j-x]+1) - } - } - if f[n] > n { - return -1 - } - return f[n] -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} coins - * @param {number} amount - * @return {number} - */ -var coinChange = function (coins, amount) { +```ts +function coinChange(coins: number[], amount: number): number { const m = coins.length; const n = amount; - const f = Array(m + 1) + const f: number[][] = Array(m + 1) .fill(0) .map(() => Array(n + 1).fill(1 << 30)); f[0][0] = 0; @@ -273,7 +185,27 @@ var coinChange = function (coins, amount) { } } return f[m][n] > n ? -1 : f[m][n]; -}; +} +``` + +```rust +impl Solution { + pub fn coin_change(coins: Vec, amount: i32) -> i32 { + let n = amount as usize; + let mut f = vec![n + 1; n + 1]; + f[0] = 0; + for &x in &coins { + for j in x as usize..=n { + f[j] = f[j].min(f[j - (x as usize)] + 1); + } + } + if f[n] > n { + -1 + } else { + f[n] as i32 + } + } +} ``` ```js @@ -283,25 +215,9 @@ var coinChange = function (coins, amount) { * @return {number} */ var coinChange = function (coins, amount) { - const n = amount; - const f = Array(n + 1).fill(1 << 30); - f[0] = 0; - for (const x of coins) { - for (let j = x; j <= n; ++j) { - f[j] = Math.min(f[j], f[j - x] + 1); - } - } - return f[n] > n ? -1 : f[n]; -}; -``` - -### **TypeScript** - -```ts -function coinChange(coins: number[], amount: number): number { const m = coins.length; const n = amount; - const f: number[][] = Array(m + 1) + const f = Array(m + 1) .fill(0) .map(() => Array(n + 1).fill(1 << 30)); f[0][0] = 0; @@ -314,6 +230,79 @@ function coinChange(coins: number[], amount: number): number { } } return f[m][n] > n ? -1 : f[m][n]; +}; +``` + + + +### 方法二 + + + +```python +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + n = amount + f = [0] + [inf] * n + for x in coins: + for j in range(x, n + 1): + f[j] = min(f[j], f[j - x] + 1) + return -1 if f[n] >= inf else f[n] +``` + +```java +class Solution { + public int coinChange(int[] coins, int amount) { + final int inf = 1 << 30; + int n = amount; + int[] f = new int[n + 1]; + Arrays.fill(f, inf); + f[0] = 0; + for (int x : coins) { + for (int j = x; j <= n; ++j) { + f[j] = Math.min(f[j], f[j - x] + 1); + } + } + return f[n] >= inf ? -1 : f[n]; + } +} +``` + +```cpp +class Solution { +public: + int coinChange(vector& coins, int amount) { + int n = amount; + int f[n + 1]; + memset(f, 0x3f, sizeof(f)); + f[0] = 0; + for (int x : coins) { + for (int j = x; j <= n; ++j) { + f[j] = min(f[j], f[j - x] + 1); + } + } + return f[n] > n ? -1 : f[n]; + } +}; +``` + +```go +func coinChange(coins []int, amount int) int { + n := amount + f := make([]int, n+1) + for i := range f { + f[i] = 1 << 30 + } + f[0] = 0 + for _, x := range coins { + for j := x; j <= n; j++ { + f[j] = min(f[j], f[j-x]+1) + } + } + if f[n] > n { + return -1 + } + return f[n] } ``` @@ -331,32 +320,25 @@ function coinChange(coins: number[], amount: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn coin_change(coins: Vec, amount: i32) -> i32 { - let n = amount as usize; - let mut f = vec![n + 1; n + 1]; - f[0] = 0; - for &x in &coins { - for j in x as usize..=n { - f[j] = f[j].min(f[j - (x as usize)] + 1); - } - } - if f[n] > n { - -1 - } else { - f[n] as i32 +```js +/** + * @param {number[]} coins + * @param {number} amount + * @return {number} + */ +var coinChange = function (coins, amount) { + const n = amount; + const f = Array(n + 1).fill(1 << 30); + f[0] = 0; + for (const x of coins) { + for (let j = x; j <= n; ++j) { + f[j] = Math.min(f[j], f[j - x] + 1); } } -} -``` - -### **...** - -``` - + return f[n] > n ? -1 : f[n]; +}; ``` + + diff --git a/solution/0300-0399/0322.Coin Change/README_EN.md b/solution/0300-0399/0322.Coin Change/README_EN.md index 115fe694aae5d..3912bead0b41d 100644 --- a/solution/0300-0399/0322.Coin Change/README_EN.md +++ b/solution/0300-0399/0322.Coin Change/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,19 +62,6 @@ class Solution: return -1 if f[m][n] >= inf else f[m][n] ``` -```python -class Solution: - def coinChange(self, coins: List[int], amount: int) -> int: - n = amount - f = [0] + [inf] * n - for x in coins: - for j in range(x, n + 1): - f[j] = min(f[j], f[j - x] + 1) - return -1 if f[n] >= inf else f[n] -``` - -### **Java** - ```java class Solution { public int coinChange(int[] coins, int amount) { @@ -99,26 +86,6 @@ class Solution { } ``` -```java -class Solution { - public int coinChange(int[] coins, int amount) { - final int inf = 1 << 30; - int n = amount; - int[] f = new int[n + 1]; - Arrays.fill(f, inf); - f[0] = 0; - for (int x : coins) { - for (int j = x; j <= n; ++j) { - f[j] = Math.min(f[j], f[j - x] + 1); - } - } - return f[n] >= inf ? -1 : f[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -140,26 +107,6 @@ public: }; ``` -```cpp -class Solution { -public: - int coinChange(vector& coins, int amount) { - int n = amount; - int f[n + 1]; - memset(f, 0x3f, sizeof(f)); - f[0] = 0; - for (int x : coins) { - for (int j = x; j <= n; ++j) { - f[j] = min(f[j], f[j - x] + 1); - } - } - return f[n] > n ? -1 : f[n]; - } -}; -``` - -### **Go** - ```go func coinChange(coins []int, amount int) int { m, n := len(coins), amount @@ -187,38 +134,11 @@ func coinChange(coins []int, amount int) int { } ``` -```go -func coinChange(coins []int, amount int) int { - n := amount - f := make([]int, n+1) - for i := range f { - f[i] = 1 << 30 - } - f[0] = 0 - for _, x := range coins { - for j := x; j <= n; j++ { - f[j] = min(f[j], f[j-x]+1) - } - } - if f[n] > n { - return -1 - } - return f[n] -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} coins - * @param {number} amount - * @return {number} - */ -var coinChange = function (coins, amount) { +```ts +function coinChange(coins: number[], amount: number): number { const m = coins.length; const n = amount; - const f = Array(m + 1) + const f: number[][] = Array(m + 1) .fill(0) .map(() => Array(n + 1).fill(1 << 30)); f[0][0] = 0; @@ -231,7 +151,27 @@ var coinChange = function (coins, amount) { } } return f[m][n] > n ? -1 : f[m][n]; -}; +} +``` + +```rust +impl Solution { + pub fn coin_change(coins: Vec, amount: i32) -> i32 { + let n = amount as usize; + let mut f = vec![n + 1; n + 1]; + f[0] = 0; + for &x in &coins { + for j in x as usize..=n { + f[j] = f[j].min(f[j - (x as usize)] + 1); + } + } + if f[n] > n { + -1 + } else { + f[n] as i32 + } + } +} ``` ```js @@ -241,25 +181,9 @@ var coinChange = function (coins, amount) { * @return {number} */ var coinChange = function (coins, amount) { - const n = amount; - const f = Array(n + 1).fill(1 << 30); - f[0] = 0; - for (const x of coins) { - for (let j = x; j <= n; ++j) { - f[j] = Math.min(f[j], f[j - x] + 1); - } - } - return f[n] > n ? -1 : f[n]; -}; -``` - -### **TypeScript** - -```ts -function coinChange(coins: number[], amount: number): number { const m = coins.length; const n = amount; - const f: number[][] = Array(m + 1) + const f = Array(m + 1) .fill(0) .map(() => Array(n + 1).fill(1 << 30)); f[0][0] = 0; @@ -272,6 +196,79 @@ function coinChange(coins: number[], amount: number): number { } } return f[m][n] > n ? -1 : f[m][n]; +}; +``` + + + +### Solution 2 + + + +```python +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + n = amount + f = [0] + [inf] * n + for x in coins: + for j in range(x, n + 1): + f[j] = min(f[j], f[j - x] + 1) + return -1 if f[n] >= inf else f[n] +``` + +```java +class Solution { + public int coinChange(int[] coins, int amount) { + final int inf = 1 << 30; + int n = amount; + int[] f = new int[n + 1]; + Arrays.fill(f, inf); + f[0] = 0; + for (int x : coins) { + for (int j = x; j <= n; ++j) { + f[j] = Math.min(f[j], f[j - x] + 1); + } + } + return f[n] >= inf ? -1 : f[n]; + } +} +``` + +```cpp +class Solution { +public: + int coinChange(vector& coins, int amount) { + int n = amount; + int f[n + 1]; + memset(f, 0x3f, sizeof(f)); + f[0] = 0; + for (int x : coins) { + for (int j = x; j <= n; ++j) { + f[j] = min(f[j], f[j - x] + 1); + } + } + return f[n] > n ? -1 : f[n]; + } +}; +``` + +```go +func coinChange(coins []int, amount int) int { + n := amount + f := make([]int, n+1) + for i := range f { + f[i] = 1 << 30 + } + f[0] = 0 + for _, x := range coins { + for j := x; j <= n; j++ { + f[j] = min(f[j], f[j-x]+1) + } + } + if f[n] > n { + return -1 + } + return f[n] } ``` @@ -289,32 +286,25 @@ function coinChange(coins: number[], amount: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn coin_change(coins: Vec, amount: i32) -> i32 { - let n = amount as usize; - let mut f = vec![n + 1; n + 1]; - f[0] = 0; - for &x in &coins { - for j in x as usize..=n { - f[j] = f[j].min(f[j - (x as usize)] + 1); - } - } - if f[n] > n { - -1 - } else { - f[n] as i32 +```js +/** + * @param {number[]} coins + * @param {number} amount + * @return {number} + */ +var coinChange = function (coins, amount) { + const n = amount; + const f = Array(n + 1).fill(1 << 30); + f[0] = 0; + for (const x of coins) { + for (let j = x; j <= n; ++j) { + f[j] = Math.min(f[j], f[j - x] + 1); } } -} -``` - -### **....** - -``` - + return f[n] > n ? -1 : f[n]; +}; ``` + + diff --git a/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README.md b/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README.md index 46a4c943aea00..508abd5f574f8 100644 --- a/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README.md +++ b/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README.md @@ -44,79 +44,10 @@ ## 解法 - - -并查集。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` +### 方法一 -### **Python3** - - - ```python class Solution: def countComponents(self, n: int, edges: List[List[int]]) -> int: @@ -131,10 +62,6 @@ class Solution: return sum(i == find(i) for i in range(n)) ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -166,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -190,8 +115,6 @@ public: }; ``` -### **Go** - ```go func countComponents(n int, edges [][]int) (ans int) { p := make([]int, n) @@ -218,8 +141,6 @@ func countComponents(n int, edges [][]int) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -250,10 +171,6 @@ var countComponents = function (n, edges) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README_EN.md b/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README_EN.md index d1fb120dafd78..25891bfd8588d 100644 --- a/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README_EN.md +++ b/solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return sum(i == find(i) for i in range(n)) ``` -### **Java** - ```java class Solution { private int[] p; @@ -88,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func countComponents(n int, edges [][]int) (ans int) { p := make([]int, n) @@ -140,8 +134,6 @@ func countComponents(n int, edges [][]int) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -172,10 +164,6 @@ var countComponents = function (n, edges) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0324.Wiggle Sort II/README.md b/solution/0300-0399/0324.Wiggle Sort II/README.md index c2c2ea3b181b6..f73c5d844aaab 100644 --- a/solution/0300-0399/0324.Wiggle Sort II/README.md +++ b/solution/0300-0399/0324.Wiggle Sort II/README.md @@ -43,18 +43,10 @@ ## 解法 - - -**方法一:排序** - -**方法二:桶排序** +### 方法一:排序 -### **Python3** - - - ```python class Solution: def wiggleSort(self, nums: List[int]) -> None: @@ -73,6 +65,96 @@ class Solution: j -= 1 ``` +```java +class Solution { + public void wiggleSort(int[] nums) { + int[] arr = nums.clone(); + Arrays.sort(arr); + int n = nums.length; + int i = (n - 1) >> 1, j = n - 1; + for (int k = 0; k < n; ++k) { + if (k % 2 == 0) { + nums[k] = arr[i--]; + } else { + nums[k] = arr[j--]; + } + } + } +} +``` + +```cpp +class Solution { +public: + void wiggleSort(vector& nums) { + vector arr = nums; + sort(arr.begin(), arr.end()); + int n = nums.size(); + int i = (n - 1) >> 1, j = n - 1; + for (int k = 0; k < n; ++k) { + if (k % 2 == 0) + nums[k] = arr[i--]; + else + nums[k] = arr[j--]; + } + } +}; +``` + +```go +func wiggleSort(nums []int) { + n := len(nums) + arr := make([]int, n) + copy(arr, nums) + sort.Ints(arr) + i, j := (n-1)>>1, n-1 + for k := 0; k < n; k++ { + if k%2 == 0 { + nums[k] = arr[i] + i-- + } else { + nums[k] = arr[j] + j-- + } + } +} +``` + +```js +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var wiggleSort = function (nums) { + let bucket = new Array(5001).fill(0); + for (const v of nums) { + bucket[v]++; + } + const n = nums.length; + let j = 5000; + for (let i = 1; i < n; i += 2) { + while (bucket[j] == 0) { + --j; + } + nums[i] = j; + --bucket[j]; + } + for (let i = 0; i < n; i += 2) { + while (bucket[j] == 0) { + --j; + } + nums[i] = j; + --bucket[j]; + } +}; +``` + + + +### 方法二:桶排序 + + + ```python class Solution: def wiggleSort(self, nums: List[int]) -> None: @@ -96,28 +178,6 @@ class Solution: bucket[j] -= 1 ``` -### **Java** - - - -```java -class Solution { - public void wiggleSort(int[] nums) { - int[] arr = nums.clone(); - Arrays.sort(arr); - int n = nums.length; - int i = (n - 1) >> 1, j = n - 1; - for (int k = 0; k < n; ++k) { - if (k % 2 == 0) { - nums[k] = arr[i--]; - } else { - nums[k] = arr[j--]; - } - } - } -} -``` - ```java class Solution { public void wiggleSort(int[] nums) { @@ -145,26 +205,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - void wiggleSort(vector& nums) { - vector arr = nums; - sort(arr.begin(), arr.end()); - int n = nums.size(); - int i = (n - 1) >> 1, j = n - 1; - for (int k = 0; k < n; ++k) { - if (k % 2 == 0) - nums[k] = arr[i--]; - else - nums[k] = arr[j--]; - } - } -}; -``` - ```cpp class Solution { public: @@ -187,27 +227,6 @@ public: }; ``` -### **Go** - -```go -func wiggleSort(nums []int) { - n := len(nums) - arr := make([]int, n) - copy(arr, nums) - sort.Ints(arr) - i, j := (n-1)>>1, n-1 - for k := 0; k < n; k++ { - if k%2 == 0 { - nums[k] = arr[i] - i-- - } else { - nums[k] = arr[j] - j-- - } - } -} -``` - ```go func wiggleSort(nums []int) { bucket := make([]int, 5001) @@ -232,41 +251,6 @@ func wiggleSort(nums []int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {void} Do not return anything, modify nums in-place instead. - */ -var wiggleSort = function (nums) { - let bucket = new Array(5001).fill(0); - for (const v of nums) { - bucket[v]++; - } - const n = nums.length; - let j = 5000; - for (let i = 1; i < n; i += 2) { - while (bucket[j] == 0) { - --j; - } - nums[i] = j; - --bucket[j]; - } - for (let i = 0; i < n; i += 2) { - while (bucket[j] == 0) { - --j; - } - nums[i] = j; - --bucket[j]; - } -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0324.Wiggle Sort II/README_EN.md b/solution/0300-0399/0324.Wiggle Sort II/README_EN.md index 477c2161e0d35..fe4ebde9df553 100644 --- a/solution/0300-0399/0324.Wiggle Sort II/README_EN.md +++ b/solution/0300-0399/0324.Wiggle Sort II/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,6 +60,96 @@ class Solution: j -= 1 ``` +```java +class Solution { + public void wiggleSort(int[] nums) { + int[] arr = nums.clone(); + Arrays.sort(arr); + int n = nums.length; + int i = (n - 1) >> 1, j = n - 1; + for (int k = 0; k < n; ++k) { + if (k % 2 == 0) { + nums[k] = arr[i--]; + } else { + nums[k] = arr[j--]; + } + } + } +} +``` + +```cpp +class Solution { +public: + void wiggleSort(vector& nums) { + vector arr = nums; + sort(arr.begin(), arr.end()); + int n = nums.size(); + int i = (n - 1) >> 1, j = n - 1; + for (int k = 0; k < n; ++k) { + if (k % 2 == 0) + nums[k] = arr[i--]; + else + nums[k] = arr[j--]; + } + } +}; +``` + +```go +func wiggleSort(nums []int) { + n := len(nums) + arr := make([]int, n) + copy(arr, nums) + sort.Ints(arr) + i, j := (n-1)>>1, n-1 + for k := 0; k < n; k++ { + if k%2 == 0 { + nums[k] = arr[i] + i-- + } else { + nums[k] = arr[j] + j-- + } + } +} +``` + +```js +/** + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var wiggleSort = function (nums) { + let bucket = new Array(5001).fill(0); + for (const v of nums) { + bucket[v]++; + } + const n = nums.length; + let j = 5000; + for (let i = 1; i < n; i += 2) { + while (bucket[j] == 0) { + --j; + } + nums[i] = j; + --bucket[j]; + } + for (let i = 0; i < n; i += 2) { + while (bucket[j] == 0) { + --j; + } + nums[i] = j; + --bucket[j]; + } +}; +``` + + + +### Solution 2 + + + ```python class Solution: def wiggleSort(self, nums: List[int]) -> None: @@ -83,26 +173,6 @@ class Solution: bucket[j] -= 1 ``` -### **Java** - -```java -class Solution { - public void wiggleSort(int[] nums) { - int[] arr = nums.clone(); - Arrays.sort(arr); - int n = nums.length; - int i = (n - 1) >> 1, j = n - 1; - for (int k = 0; k < n; ++k) { - if (k % 2 == 0) { - nums[k] = arr[i--]; - } else { - nums[k] = arr[j--]; - } - } - } -} -``` - ```java class Solution { public void wiggleSort(int[] nums) { @@ -130,26 +200,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - void wiggleSort(vector& nums) { - vector arr = nums; - sort(arr.begin(), arr.end()); - int n = nums.size(); - int i = (n - 1) >> 1, j = n - 1; - for (int k = 0; k < n; ++k) { - if (k % 2 == 0) - nums[k] = arr[i--]; - else - nums[k] = arr[j--]; - } - } -}; -``` - ```cpp class Solution { public: @@ -172,27 +222,6 @@ public: }; ``` -### **Go** - -```go -func wiggleSort(nums []int) { - n := len(nums) - arr := make([]int, n) - copy(arr, nums) - sort.Ints(arr) - i, j := (n-1)>>1, n-1 - for k := 0; k < n; k++ { - if k%2 == 0 { - nums[k] = arr[i] - i-- - } else { - nums[k] = arr[j] - j-- - } - } -} -``` - ```go func wiggleSort(nums []int) { bucket := make([]int, 5001) @@ -217,41 +246,6 @@ func wiggleSort(nums []int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {void} Do not return anything, modify nums in-place instead. - */ -var wiggleSort = function (nums) { - let bucket = new Array(5001).fill(0); - for (const v of nums) { - bucket[v]++; - } - const n = nums.length; - let j = 5000; - for (let i = 1; i < n; i += 2) { - while (bucket[j] == 0) { - --j; - } - nums[i] = j; - --bucket[j]; - } - for (let i = 0; i < n; i += 2) { - while (bucket[j] == 0) { - --j; - } - nums[i] = j; - --bucket[j]; - } -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0325.Maximum Size Subarray Sum Equals k/README.md b/solution/0300-0399/0325.Maximum Size Subarray Sum Equals k/README.md index 2c52e2b287590..81baccd29552e 100644 --- a/solution/0300-0399/0325.Maximum Size Subarray Sum Equals k/README.md +++ b/solution/0300-0399/0325.Maximum Size Subarray Sum Equals k/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:哈希表 + 前缀和** +### 方法一:哈希表 + 前缀和 我们可以用一个哈希表 $d$ 记录数组 $nums$ 中每个前缀和第一次出现的下标,初始时 $d[0] = -1$。另外定义一个变量 $s$ 记录前缀和。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def maxSubArrayLen(self, nums: List[int], k: int) -> int: @@ -69,10 +63,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxSubArrayLen(int[] nums, int k) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func maxSubArrayLen(nums []int, k int) (ans int) { d := map[int]int{0: -1} @@ -132,8 +118,6 @@ func maxSubArrayLen(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function maxSubArrayLen(nums: number[], k: number): number { const d: Map = new Map(); @@ -153,10 +137,6 @@ function maxSubArrayLen(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0325.Maximum Size Subarray Sum Equals k/README_EN.md b/solution/0300-0399/0325.Maximum Size Subarray Sum Equals k/README_EN.md index a45f072b43cdb..2333996dff325 100644 --- a/solution/0300-0399/0325.Maximum Size Subarray Sum Equals k/README_EN.md +++ b/solution/0300-0399/0325.Maximum Size Subarray Sum Equals k/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxSubArrayLen(int[] nums, int k) { @@ -71,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +90,6 @@ public: }; ``` -### **Go** - ```go func maxSubArrayLen(nums []int, k int) (ans int) { d := map[int]int{0: -1} @@ -113,8 +107,6 @@ func maxSubArrayLen(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function maxSubArrayLen(nums: number[], k: number): number { const d: Map = new Map(); @@ -134,10 +126,6 @@ function maxSubArrayLen(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0326.Power of Three/README.md b/solution/0300-0399/0326.Power of Three/README.md index d9cf87ebe21a4..04cf8e87d426c 100644 --- a/solution/0300-0399/0326.Power of Three/README.md +++ b/solution/0300-0399/0326.Power of Three/README.md @@ -54,26 +54,14 @@ ## 解法 - - -**方法一:试除法** +### 方法一:试除法 如果 $n \gt 2$,我们可以不断地将 $n$ 除以 $3$,如果不能整除,说明 $n$ 不是 $3$ 的幂,否则继续除以 $3$,直到 $n$ 小于等于 $2$。如果 $n$ 等于 $1$,说明 $n$ 是 $3$ 的幂,否则不是 $3$ 的幂。 时间复杂度 $O(\log_3n)$,空间复杂度 $O(1)$。 -**方法二:数学** - -如果 $n$ 是 $3$ 的幂,那么 $n$ 最大是 $3^{19} = 1162261467$,因此我们只需要判断 $n$ 是否是 $3^{19}$ 的约数即可。 - -时间复杂度 $O(1)$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def isPowerOfThree(self, n: int) -> bool: @@ -84,16 +72,6 @@ class Solution: return n == 1 ``` -```python -class Solution: - def isPowerOfThree(self, n: int) -> bool: - return n > 0 and 1162261467 % n == 0 -``` - -### **Java** - - - ```java class Solution { public boolean isPowerOfThree(int n) { @@ -108,16 +86,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isPowerOfThree(int n) { - return n > 0 && 1162261467 % n == 0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -133,17 +101,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool isPowerOfThree(int n) { - return n > 0 && 1162261467 % n == 0; - } -}; -``` - -### **Go** - ```go func isPowerOfThree(n int) bool { for n > 2 { @@ -156,22 +113,12 @@ func isPowerOfThree(n int) bool { } ``` -```go -func isPowerOfThree(n int) bool { - return n > 0 && 1162261467%n == 0 -} -``` - -### **TypeScript** - ```ts function isPowerOfThree(n: number): boolean { return n > 0 && 1162261467 % n == 0; } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -182,10 +129,45 @@ var isPowerOfThree = function (n) { }; ``` -### **...** + + +### 方法二:数学 + +如果 $n$ 是 $3$ 的幂,那么 $n$ 最大是 $3^{19} = 1162261467$,因此我们只需要判断 $n$ 是否是 $3^{19}$ 的约数即可。 + +时间复杂度 $O(1)$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def isPowerOfThree(self, n: int) -> bool: + return n > 0 and 1162261467 % n == 0 +``` + +```java +class Solution { + public boolean isPowerOfThree(int n) { + return n > 0 && 1162261467 % n == 0; + } +} +``` +```cpp +class Solution { +public: + bool isPowerOfThree(int n) { + return n > 0 && 1162261467 % n == 0; + } +}; ``` +```go +func isPowerOfThree(n int) bool { + return n > 0 && 1162261467%n == 0 +} ``` + + diff --git a/solution/0300-0399/0326.Power of Three/README_EN.md b/solution/0300-0399/0326.Power of Three/README_EN.md index f8cec1cd0498b..a249214e8ed3c 100644 --- a/solution/0300-0399/0326.Power of Three/README_EN.md +++ b/solution/0300-0399/0326.Power of Three/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,14 +59,6 @@ class Solution: return n == 1 ``` -```python -class Solution: - def isPowerOfThree(self, n: int) -> bool: - return n > 0 and 1162261467 % n == 0 -``` - -### **Java** - ```java class Solution { public boolean isPowerOfThree(int n) { @@ -81,16 +73,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isPowerOfThree(int n) { - return n > 0 && 1162261467 % n == 0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -106,17 +88,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool isPowerOfThree(int n) { - return n > 0 && 1162261467 % n == 0; - } -}; -``` - -### **Go** - ```go func isPowerOfThree(n int) bool { for n > 2 { @@ -129,22 +100,12 @@ func isPowerOfThree(n int) bool { } ``` -```go -func isPowerOfThree(n int) bool { - return n > 0 && 1162261467%n == 0 -} -``` - -### **TypeScript** - ```ts function isPowerOfThree(n: number): boolean { return n > 0 && 1162261467 % n == 0; } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -155,10 +116,41 @@ var isPowerOfThree = function (n) { }; ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def isPowerOfThree(self, n: int) -> bool: + return n > 0 and 1162261467 % n == 0 ``` +```java +class Solution { + public boolean isPowerOfThree(int n) { + return n > 0 && 1162261467 % n == 0; + } +} +``` + +```cpp +class Solution { +public: + bool isPowerOfThree(int n) { + return n > 0 && 1162261467 % n == 0; + } +}; +``` + +```go +func isPowerOfThree(n int) bool { + return n > 0 && 1162261467%n == 0 +} ``` + + diff --git a/solution/0300-0399/0327.Count of Range Sum/README.md b/solution/0300-0399/0327.Count of Range Sum/README.md index 2f88da0bd08c4..c51e2576408c6 100644 --- a/solution/0300-0399/0327.Count of Range Sum/README.md +++ b/solution/0300-0399/0327.Count of Range Sum/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:前缀和 + 树状数组** +### 方法一:前缀和 + 树状数组 题目要求区间和,因此我们可以先求出前缀和数组 $s$,其中 $s[i]$ 表示 $nums$ 中前 $i$ 个元素的和。那么对于任意的 $i \lt j$,$s[j+1] - s[i]$ 就是 $nums$ 中下标在 $[i, j]$ 的元素之和。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class BinaryIndexedTree: def __init__(self, n): @@ -90,10 +84,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class BinaryIndexedTree { private int n; @@ -167,8 +157,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -228,8 +216,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -289,8 +275,6 @@ func countRangeSum(nums []int, lower int, upper int) (ans int) { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -363,10 +347,6 @@ function search(nums: number[], r: number, x: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0327.Count of Range Sum/README_EN.md b/solution/0300-0399/0327.Count of Range Sum/README_EN.md index e8baa8866393b..94deeb62daec5 100644 --- a/solution/0300-0399/0327.Count of Range Sum/README_EN.md +++ b/solution/0300-0399/0327.Count of Range Sum/README_EN.md @@ -36,12 +36,10 @@ ## Solutions -Binary Indexed Tree or Segment Tree. +### Solution 1 -### **Python3** - ```python class BinaryIndexedTree: def __init__(self, n): @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class BinaryIndexedTree { private int n; @@ -150,8 +146,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -211,8 +205,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -272,8 +264,6 @@ func countRangeSum(nums []int, lower int, upper int) (ans int) { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -346,10 +336,6 @@ function search(nums: number[], r: number, x: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0328.Odd Even Linked List/README.md b/solution/0300-0399/0328.Odd Even Linked List/README.md index 8d6b7e04d7ca3..5a50efcf23be1 100644 --- a/solution/0300-0399/0328.Odd Even Linked List/README.md +++ b/solution/0300-0399/0328.Odd Even Linked List/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们可以用两个指针 $a$ 和 $b$ 分别表示奇数节点和偶数节点的尾节点。初始时,指针 $a$ 指向链表的头节点 $head$,指针 $b$ 指向链表的第二个节点 $head.next$。另外,我们用一个指针 $c$ 指向偶数节点的头节点 $head.next$,即指针 $b$ 的初始位置。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -83,10 +77,6 @@ class Solution: return head ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -177,8 +163,6 @@ func oddEvenList(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -208,10 +192,6 @@ function oddEvenList(head: ListNode | null): ListNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0328.Odd Even Linked List/README_EN.md b/solution/0300-0399/0328.Odd Even Linked List/README_EN.md index 27d95f844862b..e60ccc0afa1fc 100644 --- a/solution/0300-0399/0328.Odd Even Linked List/README_EN.md +++ b/solution/0300-0399/0328.Odd Even Linked List/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -62,8 +62,6 @@ class Solution: return head ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -127,8 +123,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -154,8 +148,6 @@ func oddEvenList(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -185,10 +177,6 @@ function oddEvenList(head: ListNode | null): ListNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0329.Longest Increasing Path in a Matrix/README.md b/solution/0300-0399/0329.Longest Increasing Path in a Matrix/README.md index 8ddb953309e3a..7ff7fa2c4ac1d 100644 --- a/solution/0300-0399/0329.Longest Increasing Path in a Matrix/README.md +++ b/solution/0300-0399/0329.Longest Increasing Path in a Matrix/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j)$,它表示从矩阵中的坐标 $(i, j)$ 出发,可以得到的最长递增路径的长度。那么答案就是 $\max_{i, j} \textit{dfs}(i, j)$。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def longestIncreasingPath(self, matrix: List[List[int]]) -> int: @@ -84,10 +78,6 @@ class Solution: return max(dfs(i, j) for i in range(m) for j in range(n)) ``` -### **Java** - - - ```java class Solution { private int m; @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go func longestIncreasingPath(matrix [][]int) (ans int) { m, n := len(matrix), len(matrix[0]) @@ -194,8 +180,6 @@ func longestIncreasingPath(matrix [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function longestIncreasingPath(matrix: number[][]): number { const m = matrix.length; @@ -227,10 +211,6 @@ function longestIncreasingPath(matrix: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0329.Longest Increasing Path in a Matrix/README_EN.md b/solution/0300-0399/0329.Longest Increasing Path in a Matrix/README_EN.md index cc844ff10aed8..7fc1a47565938 100644 --- a/solution/0300-0399/0329.Longest Increasing Path in a Matrix/README_EN.md +++ b/solution/0300-0399/0329.Longest Increasing Path in a Matrix/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return max(dfs(i, j) for i in range(m) for j in range(n)) ``` -### **Java** - ```java class Solution { private int m; @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +135,6 @@ public: }; ``` -### **Go** - ```go func longestIncreasingPath(matrix [][]int) (ans int) { m, n := len(matrix), len(matrix[0]) @@ -172,8 +166,6 @@ func longestIncreasingPath(matrix [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function longestIncreasingPath(matrix: number[][]): number { const m = matrix.length; @@ -205,10 +197,6 @@ function longestIncreasingPath(matrix: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0330.Patching Array/README.md b/solution/0300-0399/0330.Patching Array/README.md index cb5031af0c7e7..f066a36e313d0 100644 --- a/solution/0300-0399/0330.Patching Array/README.md +++ b/solution/0300-0399/0330.Patching Array/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们假设数字 $x$ 是最小的不能表示的正整数,那么 $[1,..x-1]$ 的这些数都是可以表示的。为了能表示数字 $x$,我们需要添加一个小于等于 $x$ 的数: @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def minPatches(self, nums: List[int], n: int) -> int: @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minPatches(int[] nums, int n) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func minPatches(nums []int, n int) (ans int) { x := 1 @@ -156,8 +142,6 @@ func minPatches(nums []int, n int) (ans int) { } ``` -### **TypeScript** - ```ts function minPatches(nums: number[], n: number): number { let x = 1; @@ -174,10 +158,6 @@ function minPatches(nums: number[], n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0330.Patching Array/README_EN.md b/solution/0300-0399/0330.Patching Array/README_EN.md index f7c48c23148ff..b7df64b975d82 100644 --- a/solution/0300-0399/0330.Patching Array/README_EN.md +++ b/solution/0300-0399/0330.Patching Array/README_EN.md @@ -48,9 +48,9 @@ Explanation: The two patches can be [2, 4]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minPatches(int[] nums, int n) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +104,6 @@ public: }; ``` -### **Go** - ```go func minPatches(nums []int, n int) (ans int) { x := 1 @@ -126,8 +120,6 @@ func minPatches(nums []int, n int) (ans int) { } ``` -### **TypeScript** - ```ts function minPatches(nums: number[], n: number): number { let x = 1; @@ -144,10 +136,6 @@ function minPatches(nums: number[], n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/README.md b/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/README.md index e75ed4221ae88..9c28d813c3eb4 100644 --- a/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/README.md +++ b/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 我们将字符串 `preorder` 按逗号分割成数组,然后遍历数组,如果遇到了连续两个 `'#'`,并且第三个元素不是 `'#'`,那么就将这三个元素替换成一个 `'#'`,这个过程一直持续到数组遍历结束。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def isValidSerialization(self, preorder: str) -> bool: @@ -85,10 +79,6 @@ class Solution: return len(stk) == 1 and stk[0] == "#" ``` -### **Java** - - - ```java class Solution { public boolean isValidSerialization(String preorder) { @@ -107,27 +97,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isValidSerialization(String preorder) { - List stk = new ArrayList<>(); - for (String s : preorder.split(",")) { - stk.add(s); - while (stk.size() >= 3 && stk.get(stk.size() - 1).equals("#") - && stk.get(stk.size() - 2).equals("#") && !stk.get(stk.size() - 3).equals("#")) { - stk.remove(stk.size() - 1); - stk.remove(stk.size() - 1); - stk.remove(stk.size() - 1); - stk.add("#"); - } - } - return stk.size() == 1 && stk.get(0).equals("#"); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -149,8 +118,6 @@ public: }; ``` -### **Go** - ```go func isValidSerialization(preorder string) bool { stk := []string{} @@ -165,10 +132,31 @@ func isValidSerialization(preorder string) bool { } ``` -### **...** + + +### 方法二 -``` + +```java +class Solution { + public boolean isValidSerialization(String preorder) { + List stk = new ArrayList<>(); + for (String s : preorder.split(",")) { + stk.add(s); + while (stk.size() >= 3 && stk.get(stk.size() - 1).equals("#") + && stk.get(stk.size() - 2).equals("#") && !stk.get(stk.size() - 3).equals("#")) { + stk.remove(stk.size() - 1); + stk.remove(stk.size() - 1); + stk.remove(stk.size() - 1); + stk.add("#"); + } + } + return stk.size() == 1 && stk.get(0).equals("#"); + } +} ``` + + diff --git a/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/README_EN.md b/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/README_EN.md index 376f44c699063..c816462fd8012 100644 --- a/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/README_EN.md +++ b/solution/0300-0399/0331.Verify Preorder Serialization of a Binary Tree/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return len(stk) == 1 and stk[0] == "#" ``` -### **Java** - ```java class Solution { public boolean isValidSerialization(String preorder) { @@ -77,27 +75,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isValidSerialization(String preorder) { - List stk = new ArrayList<>(); - for (String s : preorder.split(",")) { - stk.add(s); - while (stk.size() >= 3 && stk.get(stk.size() - 1).equals("#") - && stk.get(stk.size() - 2).equals("#") && !stk.get(stk.size() - 3).equals("#")) { - stk.remove(stk.size() - 1); - stk.remove(stk.size() - 1); - stk.remove(stk.size() - 1); - stk.add("#"); - } - } - return stk.size() == 1 && stk.get(0).equals("#"); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -119,8 +96,6 @@ public: }; ``` -### **Go** - ```go func isValidSerialization(preorder string) bool { stk := []string{} @@ -135,10 +110,31 @@ func isValidSerialization(preorder string) bool { } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + public boolean isValidSerialization(String preorder) { + List stk = new ArrayList<>(); + for (String s : preorder.split(",")) { + stk.add(s); + while (stk.size() >= 3 && stk.get(stk.size() - 1).equals("#") + && stk.get(stk.size() - 2).equals("#") && !stk.get(stk.size() - 3).equals("#")) { + stk.remove(stk.size() - 1); + stk.remove(stk.size() - 1); + stk.remove(stk.size() - 1); + stk.add("#"); + } + } + return stk.size() == 1 && stk.get(0).equals("#"); + } +} ``` + + diff --git a/solution/0300-0399/0332.Reconstruct Itinerary/README.md b/solution/0300-0399/0332.Reconstruct Itinerary/README.md index 527df6d785480..491f2c56653d8 100644 --- a/solution/0300-0399/0332.Reconstruct Itinerary/README.md +++ b/solution/0300-0399/0332.Reconstruct Itinerary/README.md @@ -48,14 +48,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findItinerary(self, tickets: List[List[str]]) -> List[str]: @@ -76,10 +72,6 @@ class Solution: return itinerary[::-1] ``` -### **Java** - - - ```java class Solution { void dfs(Map> adjLists, List ans, String curr) { @@ -114,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,10 +142,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0332.Reconstruct Itinerary/README_EN.md b/solution/0300-0399/0332.Reconstruct Itinerary/README_EN.md index 6a0a99388ddbf..e05d20452fcbc 100644 --- a/solution/0300-0399/0332.Reconstruct Itinerary/README_EN.md +++ b/solution/0300-0399/0332.Reconstruct Itinerary/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return itinerary[::-1] ``` -### **Java** - ```java class Solution { void dfs(Map> adjLists, List ans, String curr) { @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,10 +138,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0333.Largest BST Subtree/README.md b/solution/0300-0399/0333.Largest BST Subtree/README.md index af81dab211f77..effce4934db8e 100644 --- a/solution/0300-0399/0333.Largest BST Subtree/README.md +++ b/solution/0300-0399/0333.Largest BST Subtree/README.md @@ -54,16 +54,10 @@ ## 解法 - - -后序遍历,定义 `dfs(root)` 获取以当前结点为根结点的二叉搜索树的结点最小值、最大值、结点数。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -134,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -171,8 +159,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -202,10 +188,6 @@ func largestBSTSubtree(root *TreeNode) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0333.Largest BST Subtree/README_EN.md b/solution/0300-0399/0333.Largest BST Subtree/README_EN.md index 493607fce4d2a..8f711e28de3d8 100644 --- a/solution/0300-0399/0333.Largest BST Subtree/README_EN.md +++ b/solution/0300-0399/0333.Largest BST Subtree/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -74,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -117,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -154,8 +150,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -185,10 +179,6 @@ func largestBSTSubtree(root *TreeNode) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0334.Increasing Triplet Subsequence/README.md b/solution/0300-0399/0334.Increasing Triplet Subsequence/README.md index d823ebf921c1b..d99fb0f6c5cb3 100644 --- a/solution/0300-0399/0334.Increasing Triplet Subsequence/README.md +++ b/solution/0300-0399/0334.Increasing Triplet Subsequence/README.md @@ -50,16 +50,10 @@ ## 解法 - - -用 min, mid 记录遍历过程中遇到的最小值以及中间值,若出现 num > mid,说明找到了满足题目的三元组,返回 true;否则遍历结束返回 false。 +### 方法一 -### **Python3** - - - ```python class Solution: def increasingTriplet(self, nums: List[int]) -> bool: @@ -74,10 +68,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean increasingTriplet(int[] nums) { @@ -102,50 +92,6 @@ class Solution { } ``` -空间优化: - -```java -class Solution { - public boolean increasingTriplet(int[] nums) { - int min = Integer.MAX_VALUE, mid = Integer.MAX_VALUE; - for (int num : nums) { - if (num > mid) { - return true; - } - if (num <= min) { - min = num; - } else { - mid = num; - } - } - return false; - } -} -``` - -### **TypeScript** - -```ts -function increasingTriplet(nums: number[]): boolean { - let n = nums.length; - if (n < 3) return false; - let min = nums[0], - mid = Number.MAX_SAFE_INTEGER; - for (let num of nums) { - if (num <= min) { - min = num; - } else if (num <= mid) { - mid = num; - } else if (num > mid) { - return true; - } - } - return false; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -163,8 +109,6 @@ public: }; ``` -### **Go** - ```go func increasingTriplet(nums []int) bool { min, mid := math.MaxInt32, math.MaxInt32 @@ -182,7 +126,24 @@ func increasingTriplet(nums []int) bool { } ``` -### **Rust** +```ts +function increasingTriplet(nums: number[]): boolean { + let n = nums.length; + if (n < 3) return false; + let min = nums[0], + mid = Number.MAX_SAFE_INTEGER; + for (let num of nums) { + if (num <= min) { + min = num; + } else if (num <= mid) { + mid = num; + } else if (num > mid) { + return true; + } + } + return false; +} +``` ```rust impl Solution { @@ -207,10 +168,31 @@ impl Solution { } ``` -### **...** + -``` +### 方法二 + + +```java +class Solution { + public boolean increasingTriplet(int[] nums) { + int min = Integer.MAX_VALUE, mid = Integer.MAX_VALUE; + for (int num : nums) { + if (num > mid) { + return true; + } + if (num <= min) { + min = num; + } else { + mid = num; + } + } + return false; + } +} ``` + + diff --git a/solution/0300-0399/0334.Increasing Triplet Subsequence/README_EN.md b/solution/0300-0399/0334.Increasing Triplet Subsequence/README_EN.md index 5696d7f2cabff..bc88029be185d 100644 --- a/solution/0300-0399/0334.Increasing Triplet Subsequence/README_EN.md +++ b/solution/0300-0399/0334.Increasing Triplet Subsequence/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean increasingTriplet(int[] nums) { @@ -88,48 +86,6 @@ class Solution { } ``` -```java -class Solution { - public boolean increasingTriplet(int[] nums) { - int min = Integer.MAX_VALUE, mid = Integer.MAX_VALUE; - for (int num : nums) { - if (num > mid) { - return true; - } - if (num <= min) { - min = num; - } else { - mid = num; - } - } - return false; - } -} -``` - -### **TypeScript** - -```ts -function increasingTriplet(nums: number[]): boolean { - let n = nums.length; - if (n < 3) return false; - let min = nums[0], - mid = Number.MAX_SAFE_INTEGER; - for (let num of nums) { - if (num <= min) { - min = num; - } else if (num <= mid) { - mid = num; - } else if (num > mid) { - return true; - } - } - return false; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -147,8 +103,6 @@ public: }; ``` -### **Go** - ```go func increasingTriplet(nums []int) bool { min, mid := math.MaxInt32, math.MaxInt32 @@ -166,7 +120,24 @@ func increasingTriplet(nums []int) bool { } ``` -### **Rust** +```ts +function increasingTriplet(nums: number[]): boolean { + let n = nums.length; + if (n < 3) return false; + let min = nums[0], + mid = Number.MAX_SAFE_INTEGER; + for (let num of nums) { + if (num <= min) { + min = num; + } else if (num <= mid) { + mid = num; + } else if (num > mid) { + return true; + } + } + return false; +} +``` ```rust impl Solution { @@ -191,10 +162,31 @@ impl Solution { } ``` -### **...** + + +### Solution 2 -``` + +```java +class Solution { + public boolean increasingTriplet(int[] nums) { + int min = Integer.MAX_VALUE, mid = Integer.MAX_VALUE; + for (int num : nums) { + if (num > mid) { + return true; + } + if (num <= min) { + min = num; + } else { + mid = num; + } + } + return false; + } +} ``` + + diff --git a/solution/0300-0399/0335.Self Crossing/README.md b/solution/0300-0399/0335.Self Crossing/README.md index 72b816ee4573c..de65449ac910f 100644 --- a/solution/0300-0399/0335.Self Crossing/README.md +++ b/solution/0300-0399/0335.Self Crossing/README.md @@ -45,33 +45,10 @@ ## 解法 - - -```bash - i-2 - case 1 : i-1┌─┐ - └─┼─>i - i-3 - - i-2 - case 2 : i-1 ┌────┐ - └─══>┘i-3 - i i-4 - - case 3 : i-4 - ┌──┐ - │i<┼─┐ - i-3│ i-5│i-1 - └────┘ - i-2 -``` +### 方法一 -### **Python3** - - - ```python class Solution: def isSelfCrossing(self, distance: List[int]) -> bool: @@ -92,10 +69,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean isSelfCrossing(int[] distance) { @@ -117,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +105,6 @@ public: }; ``` -### **Go** - ```go func isSelfCrossing(distance []int) bool { d := distance @@ -154,10 +123,23 @@ func isSelfCrossing(distance []int) bool { } ``` -### **...** - -``` - +```cs +public class Solution { + public bool IsSelfCrossing(int[] x) { + for (var i = 3; i < x.Length; ++i) + { + if (x[i] >= x[i - 2] && x[i - 1] <= x[i - 3]) return true; + if (i > 3 && x[i] + x[i - 4] >= x[i - 2]) + { + if (x[i - 1] == x[i - 3]) return true; + if (i > 4 && x[i - 2] >= x[i - 4] && x[i - 1] <= x[i - 3] && x[i - 1] + x[i - 5] >= x[i - 3]) return true; + } + } + return false; + } +} ``` + + diff --git a/solution/0300-0399/0335.Self Crossing/README_EN.md b/solution/0300-0399/0335.Self Crossing/README_EN.md index f65ba9e8fa173..4264ab737f588 100644 --- a/solution/0300-0399/0335.Self Crossing/README_EN.md +++ b/solution/0300-0399/0335.Self Crossing/README_EN.md @@ -45,29 +45,10 @@ ## Solutions -```bash - i-2 - case 1 : i-1┌─┐ - └─┼─>i - i-3 - - i-2 - case 2 : i-1 ┌────┐ - └─══>┘i-3 - i i-4 - - case 3 : i-4 - ┌──┐ - │i<┼─┐ - i-3│ i-5│i-1 - └────┘ - i-2 -``` +### Solution 1 -### **Python3** - ```python class Solution: def isSelfCrossing(self, distance: List[int]) -> bool: @@ -88,8 +69,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean isSelfCrossing(int[] distance) { @@ -111,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +105,6 @@ public: }; ``` -### **Go** - ```go func isSelfCrossing(distance []int) bool { d := distance @@ -148,10 +123,23 @@ func isSelfCrossing(distance []int) bool { } ``` -### **...** - -``` - +```cs +public class Solution { + public bool IsSelfCrossing(int[] x) { + for (var i = 3; i < x.Length; ++i) + { + if (x[i] >= x[i - 2] && x[i - 1] <= x[i - 3]) return true; + if (i > 3 && x[i] + x[i - 4] >= x[i - 2]) + { + if (x[i - 1] == x[i - 3]) return true; + if (i > 4 && x[i - 2] >= x[i - 4] && x[i - 1] <= x[i - 3] && x[i - 1] + x[i - 5] >= x[i - 3]) return true; + } + } + return false; + } +} ``` + + diff --git a/solution/0300-0399/0336.Palindrome Pairs/README.md b/solution/0300-0399/0336.Palindrome Pairs/README.md index 8ddfe421a3a8b..c8ae2a58290df 100644 --- a/solution/0300-0399/0336.Palindrome Pairs/README.md +++ b/solution/0300-0399/0336.Palindrome Pairs/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:字符串哈希** +### 方法一:字符串哈希 **字符串哈希**是把一个任意长度的字符串映射成一个非负整数,并且其冲突的概率几乎为 $0$。字符串哈希用于计算字符串哈希值,快速判断两个字符串是否相等。 @@ -68,14 +66,8 @@ 除了在极特殊构造的数据上,上述 $hash$ 算法很难产生冲突,一般情况下上述 $hash$ 算法完全可以出现在题目的标准答案中。我们还可以多取一些恰当的 $BASE$ 和 $MOD$ 的值(例如大质数),多进行几组 $hash$ 运算,当结果都相同时才认为原字符串相等,就更加难以构造出使这个 $hash$ 产生错误的数据。 -**方法二:前缀树** - -### **Python3** - - - ```python class Solution: def palindromePairs(self, words: List[str]) -> List[List[int]]: @@ -92,10 +84,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int BASE = 131; @@ -143,6 +131,106 @@ class Solution { } ``` +```go +func palindromePairs(words []string) [][]int { + base := 131 + mod := int(1e9) + 7 + mul := make([]int, 310) + mul[0] = 1 + for i := 1; i < len(mul); i++ { + mul[i] = (mul[i-1] * base) % mod + } + n := len(words) + prefix := make([]int, n) + suffix := make([]int, n) + for i, word := range words { + m := len(word) + for j, c := range word { + t := int(c-'a') + 1 + s := int(word[m-j-1]-'a') + 1 + prefix[i] = (prefix[i]*base)%mod + t + suffix[i] = (suffix[i]*base)%mod + s + } + } + check := func(i, j, n, m int) bool { + t := ((prefix[i]*mul[n])%mod + prefix[j]) % mod + s := ((suffix[j]*mul[m])%mod + suffix[i]) % mod + return t == s + } + var ans [][]int + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + if check(i, j, len(words[j]), len(words[i])) { + ans = append(ans, []int{i, j}) + } + if check(j, i, len(words[i]), len(words[j])) { + ans = append(ans, []int{j, i}) + } + } + } + return ans +} +``` + +```cs +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public IList> PalindromePairs(string[] words) { + var results = new List>(); + var reverseDict = words.Select((w, i) => new {Word = w, Index = i}).ToDictionary(w => new string(w.Word.Reverse().ToArray()), w => w.Index); + + for (var i = 0; i < words.Length; ++i) + { + var word = words[i]; + for (var j = 0; j <= word.Length; ++j) + { + if (j > 0 && IsPalindrome(word, 0, j - 1)) + { + var suffix = word.Substring(j); + int pairIndex; + if (reverseDict.TryGetValue(suffix, out pairIndex) && i != pairIndex) + { + results.Add(new [] { pairIndex, i}); + } + } + if (IsPalindrome(word, j, word.Length - 1)) + { + var prefix = word.Substring(0, j); + int pairIndex; + if (reverseDict.TryGetValue(prefix, out pairIndex) && i != pairIndex) + { + results.Add(new [] { i, pairIndex}); + } + } + } + } + + return results; + } + + private bool IsPalindrome(string word, int startIndex, int endIndex) + { + var i = startIndex; + var j = endIndex; + while (i < j) + { + if (word[i] != word[j]) return false; + ++i; + --j; + } + return true; + } +} +``` + + + +### 方法二:前缀树 + + + ```java class Trie { Trie[] children = new Trie[26]; @@ -224,53 +312,6 @@ class Solution { } ``` -### **Go** - -```go -func palindromePairs(words []string) [][]int { - base := 131 - mod := int(1e9) + 7 - mul := make([]int, 310) - mul[0] = 1 - for i := 1; i < len(mul); i++ { - mul[i] = (mul[i-1] * base) % mod - } - n := len(words) - prefix := make([]int, n) - suffix := make([]int, n) - for i, word := range words { - m := len(word) - for j, c := range word { - t := int(c-'a') + 1 - s := int(word[m-j-1]-'a') + 1 - prefix[i] = (prefix[i]*base)%mod + t - suffix[i] = (suffix[i]*base)%mod + s - } - } - check := func(i, j, n, m int) bool { - t := ((prefix[i]*mul[n])%mod + prefix[j]) % mod - s := ((suffix[j]*mul[m])%mod + suffix[i]) % mod - return t == s - } - var ans [][]int - for i := 0; i < n; i++ { - for j := i + 1; j < n; j++ { - if check(i, j, len(words[j]), len(words[i])) { - ans = append(ans, []int{i, j}) - } - if check(j, i, len(words[i]), len(words[j])) { - ans = append(ans, []int{j, i}) - } - } - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0336.Palindrome Pairs/README_EN.md b/solution/0300-0399/0336.Palindrome Pairs/README_EN.md index 387a4946e1ed5..9178bd4065998 100644 --- a/solution/0300-0399/0336.Palindrome Pairs/README_EN.md +++ b/solution/0300-0399/0336.Palindrome Pairs/README_EN.md @@ -54,9 +54,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int BASE = 131; @@ -123,6 +121,106 @@ class Solution { } ``` +```go +func palindromePairs(words []string) [][]int { + base := 131 + mod := int(1e9) + 7 + mul := make([]int, 310) + mul[0] = 1 + for i := 1; i < len(mul); i++ { + mul[i] = (mul[i-1] * base) % mod + } + n := len(words) + prefix := make([]int, n) + suffix := make([]int, n) + for i, word := range words { + m := len(word) + for j, c := range word { + t := int(c-'a') + 1 + s := int(word[m-j-1]-'a') + 1 + prefix[i] = (prefix[i]*base)%mod + t + suffix[i] = (suffix[i]*base)%mod + s + } + } + check := func(i, j, n, m int) bool { + t := ((prefix[i]*mul[n])%mod + prefix[j]) % mod + s := ((suffix[j]*mul[m])%mod + suffix[i]) % mod + return t == s + } + var ans [][]int + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + if check(i, j, len(words[j]), len(words[i])) { + ans = append(ans, []int{i, j}) + } + if check(j, i, len(words[i]), len(words[j])) { + ans = append(ans, []int{j, i}) + } + } + } + return ans +} +``` + +```cs +using System.Collections.Generic; +using System.Linq; + +public class Solution { + public IList> PalindromePairs(string[] words) { + var results = new List>(); + var reverseDict = words.Select((w, i) => new {Word = w, Index = i}).ToDictionary(w => new string(w.Word.Reverse().ToArray()), w => w.Index); + + for (var i = 0; i < words.Length; ++i) + { + var word = words[i]; + for (var j = 0; j <= word.Length; ++j) + { + if (j > 0 && IsPalindrome(word, 0, j - 1)) + { + var suffix = word.Substring(j); + int pairIndex; + if (reverseDict.TryGetValue(suffix, out pairIndex) && i != pairIndex) + { + results.Add(new [] { pairIndex, i}); + } + } + if (IsPalindrome(word, j, word.Length - 1)) + { + var prefix = word.Substring(0, j); + int pairIndex; + if (reverseDict.TryGetValue(prefix, out pairIndex) && i != pairIndex) + { + results.Add(new [] { i, pairIndex}); + } + } + } + } + + return results; + } + + private bool IsPalindrome(string word, int startIndex, int endIndex) + { + var i = startIndex; + var j = endIndex; + while (i < j) + { + if (word[i] != word[j]) return false; + ++i; + --j; + } + return true; + } +} +``` + + + +### Solution 2 + + + ```java class Trie { Trie[] children = new Trie[26]; @@ -204,53 +302,6 @@ class Solution { } ``` -### **Go** - -```go -func palindromePairs(words []string) [][]int { - base := 131 - mod := int(1e9) + 7 - mul := make([]int, 310) - mul[0] = 1 - for i := 1; i < len(mul); i++ { - mul[i] = (mul[i-1] * base) % mod - } - n := len(words) - prefix := make([]int, n) - suffix := make([]int, n) - for i, word := range words { - m := len(word) - for j, c := range word { - t := int(c-'a') + 1 - s := int(word[m-j-1]-'a') + 1 - prefix[i] = (prefix[i]*base)%mod + t - suffix[i] = (suffix[i]*base)%mod + s - } - } - check := func(i, j, n, m int) bool { - t := ((prefix[i]*mul[n])%mod + prefix[j]) % mod - s := ((suffix[j]*mul[m])%mod + suffix[i]) % mod - return t == s - } - var ans [][]int - for i := 0; i < n; i++ { - for j := i + 1; j < n; j++ { - if check(i, j, len(words[j]), len(words[i])) { - ans = append(ans, []int{i, j}) - } - if check(j, i, len(words[i]), len(words[j])) { - ans = append(ans, []int{j, i}) - } - } - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0337.House Robber III/README.md b/solution/0300-0399/0337.House Robber III/README.md index a0a8959665925..e9c631e62c81f 100644 --- a/solution/0300-0399/0337.House Robber III/README.md +++ b/solution/0300-0399/0337.House Robber III/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:树形 DP** +### 方法一:树形 DP 我们定义一个函数 $dfs(root)$,表示偷取以 $root$ 为根的二叉树的最大金额。该函数返回一个二元组 $(a, b)$,其中 $a$ 表示偷取 $root$ 节点时能得到的最大金额,而 $b$ 表示不偷取 $root$ 节点时能得到的最大金额。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -90,10 +84,6 @@ class Solution: return max(dfs(root)) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -127,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -184,8 +170,6 @@ func rob(root *TreeNode) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -214,10 +198,6 @@ function rob(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0337.House Robber III/README_EN.md b/solution/0300-0399/0337.House Robber III/README_EN.md index accb0724d3f1a..631892e5b0a11 100644 --- a/solution/0300-0399/0337.House Robber III/README_EN.md +++ b/solution/0300-0399/0337.House Robber III/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -60,8 +60,6 @@ class Solution: return max(dfs(root)) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -126,8 +122,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -152,8 +146,6 @@ func rob(root *TreeNode) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -182,10 +174,6 @@ function rob(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0338.Counting Bits/README.md b/solution/0300-0399/0338.Counting Bits/README.md index ace18ada7f140..d75d1e1c72d04 100644 --- a/solution/0300-0399/0338.Counting Bits/README.md +++ b/solution/0300-0399/0338.Counting Bits/README.md @@ -58,47 +58,20 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 我们直接枚举 $0 \leq i \leq n$ 中的每个数,对于每个数 $i$,我们用库函数或者 $lowbit$ 运算得到 $i$ 中二进制位 $1$ 的个数。 时间复杂度 $O(n \times \log n)$,忽略答案的空间消耗,空间复杂度 $O(1)$。 -**方法二:动态规划** - -我们定义一个长度为 $n+1$ 的答案数组 $ans$,初始时 $ans[0]=0$。 - -对于 $1 \leq i \leq n$,我们有 $ans[i] = ans[i \text{ and } (i-1)] + 1$。其中 $i \text{ and } (i-1)$ 表示将 $i$ 的二进制表示中的最低位 $1$ 变成 $0$ 之后的数,显然 $i \text{ and } (i-1) < i$,且 $ans[i \text{ and } (i-1)]$ 已经被计算出来了,我们就能以 $O(1)$ 的时间得到 $ans[i]$。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def countBits(self, n: int) -> List[int]: return [i.bit_count() for i in range(n + 1)] ``` -```python -class Solution: - def countBits(self, n: int) -> List[int]: - ans = [0] * (n + 1) - for i in range(1, n + 1): - ans[i] = ans[i & (i - 1)] + 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int[] countBits(int n) { @@ -111,20 +84,6 @@ class Solution { } ``` -```java -class Solution { - public int[] countBits(int n) { - int[] ans = new int[n + 1]; - for (int i = 1; i <= n; ++i) { - ans[i] = ans[i & (i - 1)] + 1; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -138,21 +97,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector countBits(int n) { - vector ans(n + 1); - for (int i = 1; i <= n; ++i) { - ans[i] = ans[i & (i - 1)] + 1; - } - return ans; - } -}; -``` - -### **Go** - ```go func countBits(n int) []int { ans := make([]int, n+1) @@ -163,18 +107,6 @@ func countBits(n int) []int { } ``` -```go -func countBits(n int) []int { - ans := make([]int, n+1) - for i := 1; i <= n; i++ { - ans[i] = ans[i&(i-1)] + 1 - } - return ans -} -``` - -### **TypeScript** - ```ts function countBits(n: number): number[] { const ans: number[] = Array(n + 1).fill(0); @@ -194,6 +126,62 @@ function bitCount(n: number): number { } ``` + + +### 方法二:动态规划 + +我们定义一个长度为 $n+1$ 的答案数组 $ans$,初始时 $ans[0]=0$。 + +对于 $1 \leq i \leq n$,我们有 $ans[i] = ans[i \text{ and } (i-1)] + 1$。其中 $i \text{ and } (i-1)$ 表示将 $i$ 的二进制表示中的最低位 $1$ 变成 $0$ 之后的数,显然 $i \text{ and } (i-1) < i$,且 $ans[i \text{ and } (i-1)]$ 已经被计算出来了,我们就能以 $O(1)$ 的时间得到 $ans[i]$。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def countBits(self, n: int) -> List[int]: + ans = [0] * (n + 1) + for i in range(1, n + 1): + ans[i] = ans[i & (i - 1)] + 1 + return ans +``` + +```java +class Solution { + public int[] countBits(int n) { + int[] ans = new int[n + 1]; + for (int i = 1; i <= n; ++i) { + ans[i] = ans[i & (i - 1)] + 1; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector countBits(int n) { + vector ans(n + 1); + for (int i = 1; i <= n; ++i) { + ans[i] = ans[i & (i - 1)] + 1; + } + return ans; + } +}; +``` + +```go +func countBits(n int) []int { + ans := make([]int, n+1) + for i := 1; i <= n; i++ { + ans[i] = ans[i&(i-1)] + 1 + } + return ans +} +``` + ```ts function countBits(n: number): number[] { const ans: number[] = Array(n + 1).fill(0); @@ -204,10 +192,6 @@ function countBits(n: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0338.Counting Bits/README_EN.md b/solution/0300-0399/0338.Counting Bits/README_EN.md index 315b58fa0e7ec..ba5e4f423610e 100644 --- a/solution/0300-0399/0338.Counting Bits/README_EN.md +++ b/solution/0300-0399/0338.Counting Bits/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,17 +59,6 @@ class Solution: return [i.bit_count() for i in range(n + 1)] ``` -```python -class Solution: - def countBits(self, n: int) -> List[int]: - ans = [0] * (n + 1) - for i in range(1, n + 1): - ans[i] = ans[i & (i - 1)] + 1 - return ans -``` - -### **Java** - ```java class Solution { public int[] countBits(int n) { @@ -82,20 +71,6 @@ class Solution { } ``` -```java -class Solution { - public int[] countBits(int n) { - int[] ans = new int[n + 1]; - for (int i = 1; i <= n; ++i) { - ans[i] = ans[i & (i - 1)] + 1; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -109,21 +84,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector countBits(int n) { - vector ans(n + 1); - for (int i = 1; i <= n; ++i) { - ans[i] = ans[i & (i - 1)] + 1; - } - return ans; - } -}; -``` - -### **Go** - ```go func countBits(n int) []int { ans := make([]int, n+1) @@ -134,18 +94,6 @@ func countBits(n int) []int { } ``` -```go -func countBits(n int) []int { - ans := make([]int, n+1) - for i := 1; i <= n; i++ { - ans[i] = ans[i&(i-1)] + 1 - } - return ans -} -``` - -### **TypeScript** - ```ts function countBits(n: number): number[] { const ans: number[] = Array(n + 1).fill(0); @@ -165,6 +113,56 @@ function bitCount(n: number): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def countBits(self, n: int) -> List[int]: + ans = [0] * (n + 1) + for i in range(1, n + 1): + ans[i] = ans[i & (i - 1)] + 1 + return ans +``` + +```java +class Solution { + public int[] countBits(int n) { + int[] ans = new int[n + 1]; + for (int i = 1; i <= n; ++i) { + ans[i] = ans[i & (i - 1)] + 1; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector countBits(int n) { + vector ans(n + 1); + for (int i = 1; i <= n; ++i) { + ans[i] = ans[i & (i - 1)] + 1; + } + return ans; + } +}; +``` + +```go +func countBits(n int) []int { + ans := make([]int, n+1) + for i := 1; i <= n; i++ { + ans[i] = ans[i&(i-1)] + 1 + } + return ans +} +``` + ```ts function countBits(n: number): number[] { const ans: number[] = Array(n + 1).fill(0); @@ -175,10 +173,6 @@ function countBits(n: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0339.Nested List Weight Sum/README.md b/solution/0300-0399/0339.Nested List Weight Sum/README.md index 890f0c3933e56..39d6cad37a456 100644 --- a/solution/0300-0399/0339.Nested List Weight Sum/README.md +++ b/solution/0300-0399/0339.Nested List Weight Sum/README.md @@ -49,16 +49,10 @@ ## 解法 - - -DFS 实现。 +### 方法一 -### **Python3** - - - ```python # """ # This is the interface that allows for creating nested lists. @@ -116,10 +110,6 @@ class Solution: return dfs(nestedList, 1) ``` -### **Java** - - - ```java /** * // This is the interface that allows for creating nested lists. @@ -168,8 +158,6 @@ class Solution { } ``` -### **JavaScript** - ```js /** * // This is the interface that allows for creating nested lists. @@ -229,10 +217,6 @@ var depthSum = function (nestedList) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0339.Nested List Weight Sum/README_EN.md b/solution/0300-0399/0339.Nested List Weight Sum/README_EN.md index 907e356182bbe..dd4659f8a255e 100644 --- a/solution/0300-0399/0339.Nested List Weight Sum/README_EN.md +++ b/solution/0300-0399/0339.Nested List Weight Sum/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # """ @@ -105,8 +105,6 @@ class Solution: return dfs(nestedList, 1) ``` -### **Java** - ```java /** * // This is the interface that allows for creating nested lists. @@ -155,8 +153,6 @@ class Solution { } ``` -### **JavaScript** - ```js /** * // This is the interface that allows for creating nested lists. @@ -216,10 +212,6 @@ var depthSum = function (nestedList) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0340.Longest Substring with At Most K Distinct Characters/README.md b/solution/0300-0399/0340.Longest Substring with At Most K Distinct Characters/README.md index 955c8f136c091..a56f4f0b2a112 100644 --- a/solution/0300-0399/0340.Longest Substring with At Most K Distinct Characters/README.md +++ b/solution/0300-0399/0340.Longest Substring with At Most K Distinct Characters/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:滑动窗口 + 哈希表** +### 方法一:滑动窗口 + 哈希表 我们可以使用滑动窗口的思想,维护一个滑动窗口,使得窗口内的字符串中不同字符的个数不超过 $k$ 个。窗口内不同字符个数的统计可以用哈希表 `cnt` 来维护。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python class Solution: def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int: @@ -69,10 +63,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int lengthOfLongestSubstringKDistinct(String s, int k) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func lengthOfLongestSubstringKDistinct(s string, k int) (ans int) { cnt := map[byte]int{} @@ -142,10 +128,6 @@ func lengthOfLongestSubstringKDistinct(s string, k int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0340.Longest Substring with At Most K Distinct Characters/README_EN.md b/solution/0300-0399/0340.Longest Substring with At Most K Distinct Characters/README_EN.md index 52aaa9164a1ba..14fe929983b1d 100644 --- a/solution/0300-0399/0340.Longest Substring with At Most K Distinct Characters/README_EN.md +++ b/solution/0300-0399/0340.Longest Substring with At Most K Distinct Characters/README_EN.md @@ -32,9 +32,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int lengthOfLongestSubstringKDistinct(String s, int k) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +99,6 @@ public: }; ``` -### **Go** - ```go func lengthOfLongestSubstringKDistinct(s string, k int) (ans int) { cnt := map[byte]int{} @@ -124,10 +118,6 @@ func lengthOfLongestSubstringKDistinct(s string, k int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0341.Flatten Nested List Iterator/README.md b/solution/0300-0399/0341.Flatten Nested List Iterator/README.md index ed91c41d5b492..9bfad9571318a 100644 --- a/solution/0300-0399/0341.Flatten Nested List Iterator/README.md +++ b/solution/0300-0399/0341.Flatten Nested List Iterator/README.md @@ -55,22 +55,12 @@ return res ## 解法 - - -**方法一:递归** +### 方法一:递归 根据题意要求可以将 NestedInteger 数据结构视作一个 N 叉树,当元素为一个整数时,该节点是 N 叉树的叶子节点,当元素为一个整数数组时,该节点是 N 叉树的非叶子节点,数组中的每一个元素包含子树的所有节点。故直接递归遍历 N 叉树并记录所有的叶子节点即可。 -**方法二:直接展开** - -调用 hasNext 时,如果 nestedList 的第一个元素是列表类型,则不断展开这个元素,直到第一个元素是整数类型。 调用 Next 方法时,由于 `hasNext()` 方法已确保 nestedList 第一个元素为整数类型,直接返回即可。 - -### **Python3** - - - ```python # """ # This is the interface that allows for creating nested lists. @@ -122,10 +112,6 @@ class NestedIterator: # while i.hasNext(): v.append(i.next()) ``` -### **Java** - - - ```java /** * // This is the interface that allows for creating nested lists. @@ -184,8 +170,6 @@ public class NestedIterator implements Iterator { */ ``` -### **C++** - ```cpp /** * // This is the interface that allows for creating nested lists. @@ -241,7 +225,64 @@ private: */ ``` -### **TypeScript** +```go +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * type NestedInteger struct { + * } + * + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * func (this NestedInteger) IsInteger() bool {} + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * // So before calling this method, you should have a check + * func (this NestedInteger) GetInteger() int {} + * + * // Set this NestedInteger to hold a single integer. + * func (n *NestedInteger) SetInteger(value int) {} + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * func (this *NestedInteger) Add(elem NestedInteger) {} + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The list length is zero if this NestedInteger holds a single integer + * // You can access NestedInteger's List element directly if you want to modify it + * func (this NestedInteger) GetList() []*NestedInteger {} + */ + +type NestedIterator struct { + iterator []int + index, length int +} + +func Constructor(nestedList []*NestedInteger) *NestedIterator { + result := make([]int, 0) + var traversal func(nodes []*NestedInteger) + traversal = func(nodes []*NestedInteger) { + for _, child := range nodes { + if child.IsInteger() { + result = append(result, child.GetInteger()) + } else { + traversal(child.GetList()) + } + } + } + traversal(nestedList) + return &NestedIterator{iterator: result, index: 0, length: len(result)} +} + +func (this *NestedIterator) Next() int { + res := this.iterator[this.index] + this.index++ + return res +} + +func (this *NestedIterator) HasNext() bool { + return this.index < this.length +} +``` ```ts /** @@ -320,8 +361,6 @@ class NestedIterator { */ ``` -### **Rust** - ```rust // #[derive(Debug, PartialEq, Eq)] // pub enum NestedInteger { @@ -373,70 +412,13 @@ impl NestedIterator { */ ``` -### **Go** - -递归: - -```go -/** - * // This is the interface that allows for creating nested lists. - * // You should not implement it, or speculate about its implementation - * type NestedInteger struct { - * } - * - * // Return true if this NestedInteger holds a single integer, rather than a nested list. - * func (this NestedInteger) IsInteger() bool {} - * - * // Return the single integer that this NestedInteger holds, if it holds a single integer - * // The result is undefined if this NestedInteger holds a nested list - * // So before calling this method, you should have a check - * func (this NestedInteger) GetInteger() int {} - * - * // Set this NestedInteger to hold a single integer. - * func (n *NestedInteger) SetInteger(value int) {} - * - * // Set this NestedInteger to hold a nested list and adds a nested integer to it. - * func (this *NestedInteger) Add(elem NestedInteger) {} - * - * // Return the nested list that this NestedInteger holds, if it holds a nested list - * // The list length is zero if this NestedInteger holds a single integer - * // You can access NestedInteger's List element directly if you want to modify it - * func (this NestedInteger) GetList() []*NestedInteger {} - */ - -type NestedIterator struct { - iterator []int - index, length int -} - -func Constructor(nestedList []*NestedInteger) *NestedIterator { - result := make([]int, 0) - var traversal func(nodes []*NestedInteger) - traversal = func(nodes []*NestedInteger) { - for _, child := range nodes { - if child.IsInteger() { - result = append(result, child.GetInteger()) - } else { - traversal(child.GetList()) - } - } - } - traversal(nestedList) - return &NestedIterator{iterator: result, index: 0, length: len(result)} -} + -func (this *NestedIterator) Next() int { - res := this.iterator[this.index] - this.index++ - return res -} +### 方法二:直接展开 -func (this *NestedIterator) HasNext() bool { - return this.index < this.length -} -``` +调用 hasNext 时,如果 nestedList 的第一个元素是列表类型,则不断展开这个元素,直到第一个元素是整数类型。 调用 Next 方法时,由于 `hasNext()` 方法已确保 nestedList 第一个元素为整数类型,直接返回即可。 -直接展开: + ```go /** @@ -496,10 +478,6 @@ func (this *NestedIterator) HasNext() bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0341.Flatten Nested List Iterator/README_EN.md b/solution/0300-0399/0341.Flatten Nested List Iterator/README_EN.md index 69893080ba465..f7428170b0498 100644 --- a/solution/0300-0399/0341.Flatten Nested List Iterator/README_EN.md +++ b/solution/0300-0399/0341.Flatten Nested List Iterator/README_EN.md @@ -53,9 +53,9 @@ return res ## Solutions - +### Solution 1 -### **Python3** + ```python # """ @@ -108,8 +108,6 @@ class NestedIterator: # while i.hasNext(): v.append(i.next()) ``` -### **Java** - ```java /** * // This is the interface that allows for creating nested lists. @@ -168,8 +166,6 @@ public class NestedIterator implements Iterator { */ ``` -### **C++** - ```cpp /** * // This is the interface that allows for creating nested lists. @@ -225,7 +221,64 @@ private: */ ``` -### **TypeScript** +```go +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * type NestedInteger struct { + * } + * + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * func (this NestedInteger) IsInteger() bool {} + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * // So before calling this method, you should have a check + * func (this NestedInteger) GetInteger() int {} + * + * // Set this NestedInteger to hold a single integer. + * func (n *NestedInteger) SetInteger(value int) {} + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * func (this *NestedInteger) Add(elem NestedInteger) {} + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The list length is zero if this NestedInteger holds a single integer + * // You can access NestedInteger's List element directly if you want to modify it + * func (this NestedInteger) GetList() []*NestedInteger {} + */ + +type NestedIterator struct { + iterator []int + index, length int +} + +func Constructor(nestedList []*NestedInteger) *NestedIterator { + result := make([]int, 0) + var traversal func(nodes []*NestedInteger) + traversal = func(nodes []*NestedInteger) { + for _, child := range nodes { + if child.IsInteger() { + result = append(result, child.GetInteger()) + } else { + traversal(child.GetList()) + } + } + } + traversal(nestedList) + return &NestedIterator{iterator: result, index: 0, length: len(result)} +} + +func (this *NestedIterator) Next() int { + res := this.iterator[this.index] + this.index++ + return res +} + +func (this *NestedIterator) HasNext() bool { + return this.index < this.length +} +``` ```ts /** @@ -304,8 +357,6 @@ class NestedIterator { */ ``` -### **Rust** - ```rust // #[derive(Debug, PartialEq, Eq)] // pub enum NestedInteger { @@ -357,70 +408,11 @@ impl NestedIterator { */ ``` -### **Go** - -recursion: - -```go -/** - * // This is the interface that allows for creating nested lists. - * // You should not implement it, or speculate about its implementation - * type NestedInteger struct { - * } - * - * // Return true if this NestedInteger holds a single integer, rather than a nested list. - * func (this NestedInteger) IsInteger() bool {} - * - * // Return the single integer that this NestedInteger holds, if it holds a single integer - * // The result is undefined if this NestedInteger holds a nested list - * // So before calling this method, you should have a check - * func (this NestedInteger) GetInteger() int {} - * - * // Set this NestedInteger to hold a single integer. - * func (n *NestedInteger) SetInteger(value int) {} - * - * // Set this NestedInteger to hold a nested list and adds a nested integer to it. - * func (this *NestedInteger) Add(elem NestedInteger) {} - * - * // Return the nested list that this NestedInteger holds, if it holds a nested list - * // The list length is zero if this NestedInteger holds a single integer - * // You can access NestedInteger's List element directly if you want to modify it - * func (this NestedInteger) GetList() []*NestedInteger {} - */ - -type NestedIterator struct { - iterator []int - index, length int -} - -func Constructor(nestedList []*NestedInteger) *NestedIterator { - result := make([]int, 0) - var traversal func(nodes []*NestedInteger) - traversal = func(nodes []*NestedInteger) { - for _, child := range nodes { - if child.IsInteger() { - result = append(result, child.GetInteger()) - } else { - traversal(child.GetList()) - } - } - } - traversal(nestedList) - return &NestedIterator{iterator: result, index: 0, length: len(result)} -} - -func (this *NestedIterator) Next() int { - res := this.iterator[this.index] - this.index++ - return res -} + -func (this *NestedIterator) HasNext() bool { - return this.index < this.length -} -``` +### Solution 2 -Expand directly: + ```go /** @@ -480,10 +472,6 @@ func (this *NestedIterator) HasNext() bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0342.Power of Four/README.md b/solution/0300-0399/0342.Power of Four/README.md index 4dfdd887f329c..93f85f1319841 100644 --- a/solution/0300-0399/0342.Power of Four/README.md +++ b/solution/0300-0399/0342.Power of Four/README.md @@ -47,24 +47,16 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def isPowerOfFour(self, n: int) -> bool: return n > 0 and (n & (n - 1)) == 0 and (n & 0xAAAAAAAA) == 0 ``` -### **Java** - - - ```java class Solution { public boolean isPowerOfFour(int n) { @@ -73,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -84,38 +74,28 @@ public: }; ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {boolean} - */ -var isPowerOfFour = function (n) { - return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; -}; -``` - -### **Go** - ```go func isPowerOfFour(n int) bool { return n > 0 && (n&(n-1)) == 0 && (n&0xaaaaaaaa) == 0 } ``` -### **TypeScript** - ```ts function isPowerOfFour(n: number): boolean { return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; } ``` -### **...** - -``` - +```js +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfFour = function (n) { + return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; +}; ``` + + diff --git a/solution/0300-0399/0342.Power of Four/README_EN.md b/solution/0300-0399/0342.Power of Four/README_EN.md index 0f5eaa06941ee..190cd522befb6 100644 --- a/solution/0300-0399/0342.Power of Four/README_EN.md +++ b/solution/0300-0399/0342.Power of Four/README_EN.md @@ -31,9 +31,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -41,8 +41,6 @@ class Solution: return n > 0 and (n & (n - 1)) == 0 and (n & 0xAAAAAAAA) == 0 ``` -### **Java** - ```java class Solution { public boolean isPowerOfFour(int n) { @@ -51,8 +49,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -62,38 +58,28 @@ public: }; ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {boolean} - */ -var isPowerOfFour = function (n) { - return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; -}; -``` - -### **Go** - ```go func isPowerOfFour(n int) bool { return n > 0 && (n&(n-1)) == 0 && (n&0xaaaaaaaa) == 0 } ``` -### **TypeScript** - ```ts function isPowerOfFour(n: number): boolean { return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; } ``` -### **...** - -``` - +```js +/** + * @param {number} n + * @return {boolean} + */ +var isPowerOfFour = function (n) { + return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; +}; ``` + + diff --git a/solution/0300-0399/0343.Integer Break/README.md b/solution/0300-0399/0343.Integer Break/README.md index 71ed2fe538ce0..686663c69997f 100644 --- a/solution/0300-0399/0343.Integer Break/README.md +++ b/solution/0300-0399/0343.Integer Break/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $dp[i]$ 表示正整数 $n$ 能获得的最大乘积,初始化 $dp[1] = 1$。答案即为 $dp[n]$。 @@ -50,18 +48,8 @@ $$ 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为正整数 $n$。 -**方法二:数学** - -当 $n \lt 4$ 时,$n$ 不能拆分成至少两个正整数的和,因此 $n - 1$ 是最大乘积。当 $n \ge 4$ 时,我们尽可能多地拆分 $3$,当剩下的最后一段为 $4$ 时,我们将其拆分为 $2 + 2$,这样乘积最大。 - -时间复杂度 $O(1)$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def integerBreak(self, n: int) -> int: @@ -72,22 +60,6 @@ class Solution: return dp[n] ``` -```python -class Solution: - def integerBreak(self, n: int) -> int: - if n < 4: - return n - 1 - if n % 3 == 0: - return pow(3, n // 3) - if n % 3 == 1: - return pow(3, n // 3 - 1) * 4 - return pow(3, n // 3) * 2 -``` - -### **Java** - - - ```java class Solution { public int integerBreak(int n) { @@ -103,25 +75,6 @@ class Solution { } ``` -```java -class Solution { - public int integerBreak(int n) { - if (n < 4) { - return n - 1; - } - if (n % 3 == 0) { - return (int) Math.pow(3, n / 3); - } - if (n % 3 == 1) { - return (int) Math.pow(3, n / 3 - 1) * 4; - } - return (int) Math.pow(3, n / 3) * 2; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -138,26 +91,6 @@ public: }; ``` -```cpp -class Solution { -public: - int integerBreak(int n) { - if (n < 4) { - return n - 1; - } - if (n % 3 == 0) { - return pow(3, n / 3); - } - if (n % 3 == 1) { - return pow(3, n / 3 - 1) * 4; - } - return pow(3, n / 3) * 2; - } -}; -``` - -### **Go** - ```go func integerBreak(n int) int { dp := make([]int, n+1) @@ -171,22 +104,29 @@ func integerBreak(n int) int { } ``` -```go -func integerBreak(n int) int { - if n < 4 { - return n - 1 - } - if n%3 == 0 { - return int(math.Pow(3, float64(n/3))) - } - if n%3 == 1 { - return int(math.Pow(3, float64(n/3-1))) * 4 - } - return int(math.Pow(3, float64(n/3))) * 2 +```ts +function integerBreak(n: number): number { + let dp = new Array(n + 1).fill(1); + for (let i = 3; i <= n; i++) { + for (let j = 1; j < i; j++) { + dp[i] = Math.max(dp[i], j * (i - j), j * dp[i - j]); + } + } + return dp.pop(); } ``` -### **C** +```rust +impl Solution { + pub fn integer_break(n: i32) -> i32 { + if n < 4 { + return n - 1; + } + let count = (n - 2) / 3; + (3i32).pow(count as u32) * (n - count * 3) + } +} +``` ```c int integerBreak(int n) { @@ -198,31 +138,75 @@ int integerBreak(int n) { } ``` -### **Rust** + -```rust -impl Solution { - pub fn integer_break(n: i32) -> i32 { - if n < 4 { +### 方法二:数学 + +当 $n \lt 4$ 时,$n$ 不能拆分成至少两个正整数的和,因此 $n - 1$ 是最大乘积。当 $n \ge 4$ 时,我们尽可能多地拆分 $3$,当剩下的最后一段为 $4$ 时,我们将其拆分为 $2 + 2$,这样乘积最大。 + +时间复杂度 $O(1)$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def integerBreak(self, n: int) -> int: + if n < 4: + return n - 1 + if n % 3 == 0: + return pow(3, n // 3) + if n % 3 == 1: + return pow(3, n // 3 - 1) * 4 + return pow(3, n // 3) * 2 +``` + +```java +class Solution { + public int integerBreak(int n) { + if (n < 4) { return n - 1; } - let count = (n - 2) / 3; - (3i32).pow(count as u32) * (n - count * 3) + if (n % 3 == 0) { + return (int) Math.pow(3, n / 3); + } + if (n % 3 == 1) { + return (int) Math.pow(3, n / 3 - 1) * 4; + } + return (int) Math.pow(3, n / 3) * 2; } } ``` -### **TypeScript** - -```ts -function integerBreak(n: number): number { - let dp = new Array(n + 1).fill(1); - for (let i = 3; i <= n; i++) { - for (let j = 1; j < i; j++) { - dp[i] = Math.max(dp[i], j * (i - j), j * dp[i - j]); +```cpp +class Solution { +public: + int integerBreak(int n) { + if (n < 4) { + return n - 1; + } + if (n % 3 == 0) { + return pow(3, n / 3); } + if (n % 3 == 1) { + return pow(3, n / 3 - 1) * 4; + } + return pow(3, n / 3) * 2; } - return dp.pop(); +}; +``` + +```go +func integerBreak(n int) int { + if n < 4 { + return n - 1 + } + if n%3 == 0 { + return int(math.Pow(3, float64(n/3))) + } + if n%3 == 1 { + return int(math.Pow(3, float64(n/3-1))) * 4 + } + return int(math.Pow(3, float64(n/3))) * 2 } ``` @@ -242,10 +226,6 @@ function integerBreak(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0343.Integer Break/README_EN.md b/solution/0300-0399/0343.Integer Break/README_EN.md index 71fc4632b5b9d..31ddd604160aa 100644 --- a/solution/0300-0399/0343.Integer Break/README_EN.md +++ b/solution/0300-0399/0343.Integer Break/README_EN.md @@ -34,12 +34,10 @@ ## Solutions -Dynamic programming. +### Solution 1 -### **Python3** - ```python class Solution: def integerBreak(self, n: int) -> int: @@ -50,20 +48,6 @@ class Solution: return dp[n] ``` -```python -class Solution: - def integerBreak(self, n: int) -> int: - if n < 4: - return n - 1 - if n % 3 == 0: - return pow(3, n // 3) - if n % 3 == 1: - return pow(3, n // 3 - 1) * 4 - return pow(3, n // 3) * 2 -``` - -### **Java** - ```java class Solution { public int integerBreak(int n) { @@ -79,25 +63,6 @@ class Solution { } ``` -```java -class Solution { - public int integerBreak(int n) { - if (n < 4) { - return n - 1; - } - if (n % 3 == 0) { - return (int) Math.pow(3, n / 3); - } - if (n % 3 == 1) { - return (int) Math.pow(3, n / 3 - 1) * 4; - } - return (int) Math.pow(3, n / 3) * 2; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -114,26 +79,6 @@ public: }; ``` -```cpp -class Solution { -public: - int integerBreak(int n) { - if (n < 4) { - return n - 1; - } - if (n % 3 == 0) { - return pow(3, n / 3); - } - if (n % 3 == 1) { - return pow(3, n / 3 - 1) * 4; - } - return pow(3, n / 3) * 2; - } -}; -``` - -### **Go** - ```go func integerBreak(n int) int { dp := make([]int, n+1) @@ -147,22 +92,29 @@ func integerBreak(n int) int { } ``` -```go -func integerBreak(n int) int { - if n < 4 { - return n - 1 - } - if n%3 == 0 { - return int(math.Pow(3, float64(n/3))) - } - if n%3 == 1 { - return int(math.Pow(3, float64(n/3-1))) * 4 - } - return int(math.Pow(3, float64(n/3))) * 2 +```ts +function integerBreak(n: number): number { + let dp = new Array(n + 1).fill(1); + for (let i = 3; i <= n; i++) { + for (let j = 1; j < i; j++) { + dp[i] = Math.max(dp[i], j * (i - j), j * dp[i - j]); + } + } + return dp.pop(); } ``` -### **C** +```rust +impl Solution { + pub fn integer_break(n: i32) -> i32 { + if n < 4 { + return n - 1; + } + let count = (n - 2) / 3; + (3i32).pow(count as u32) * (n - count * 3) + } +} +``` ```c int integerBreak(int n) { @@ -174,31 +126,71 @@ int integerBreak(int n) { } ``` -### **Rust** + + +### Solution 2 -```rust -impl Solution { - pub fn integer_break(n: i32) -> i32 { - if n < 4 { + + +```python +class Solution: + def integerBreak(self, n: int) -> int: + if n < 4: + return n - 1 + if n % 3 == 0: + return pow(3, n // 3) + if n % 3 == 1: + return pow(3, n // 3 - 1) * 4 + return pow(3, n // 3) * 2 +``` + +```java +class Solution { + public int integerBreak(int n) { + if (n < 4) { return n - 1; } - let count = (n - 2) / 3; - (3i32).pow(count as u32) * (n - count * 3) + if (n % 3 == 0) { + return (int) Math.pow(3, n / 3); + } + if (n % 3 == 1) { + return (int) Math.pow(3, n / 3 - 1) * 4; + } + return (int) Math.pow(3, n / 3) * 2; } } ``` -### **TypeScript** - -```ts -function integerBreak(n: number): number { - let dp = new Array(n + 1).fill(1); - for (let i = 3; i <= n; i++) { - for (let j = 1; j < i; j++) { - dp[i] = Math.max(dp[i], j * (i - j), j * dp[i - j]); +```cpp +class Solution { +public: + int integerBreak(int n) { + if (n < 4) { + return n - 1; } + if (n % 3 == 0) { + return pow(3, n / 3); + } + if (n % 3 == 1) { + return pow(3, n / 3 - 1) * 4; + } + return pow(3, n / 3) * 2; } - return dp.pop(); +}; +``` + +```go +func integerBreak(n int) int { + if n < 4 { + return n - 1 + } + if n%3 == 0 { + return int(math.Pow(3, float64(n/3))) + } + if n%3 == 1 { + return int(math.Pow(3, float64(n/3-1))) * 4 + } + return int(math.Pow(3, float64(n/3))) * 2 } ``` @@ -218,10 +210,6 @@ function integerBreak(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0344.Reverse String/README.md b/solution/0300-0399/0344.Reverse String/README.md index 50f9d968aac8d..0cb8fe517453d 100644 --- a/solution/0300-0399/0344.Reverse String/README.md +++ b/solution/0300-0399/0344.Reverse String/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们用两个指针 $i$ 和 $j$,初始时分别指向数组的首尾,每次将 $i$ 和 $j$ 对应的元素交换,然后 $i$ 向后移动,$j$ 向前移动,直到 $i$ 和 $j$ 相遇。 @@ -46,10 +44,6 @@ -### **Python3** - - - ```python class Solution: def reverseString(self, s: List[str]) -> None: @@ -59,16 +53,6 @@ class Solution: i, j = i + 1, j - 1 ``` -```python -class Solution: - def reverseString(self, s: List[str]) -> None: - s[:] = s[::-1] -``` - -### **Java** - - - ```java class Solution { public void reverseString(char[] s) { @@ -81,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +76,6 @@ public: }; ``` -### **Go** - ```go func reverseString(s []byte) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { @@ -104,8 +84,6 @@ func reverseString(s []byte) { } ``` -### **TypeScript** - ```ts /** Do not return anything, modify s in-place instead. @@ -117,17 +95,20 @@ function reverseString(s: string[]): void { } ``` -```ts -/** - Do not return anything, modify s in-place instead. - */ -function reverseString(s: string[]): void { - s.reverse(); +```rust +impl Solution { + pub fn reverse_string(s: &mut Vec) { + let mut i = 0; + let mut j = s.len() - 1; + while i < j { + s.swap(i, j); + i += 1; + j -= 1; + } + } } ``` -### **JavaScript** - ```js /** * @param {character[]} s @@ -140,26 +121,27 @@ var reverseString = function (s) { }; ``` -### **Rust** + -```rust -impl Solution { - pub fn reverse_string(s: &mut Vec) { - let mut i = 0; - let mut j = s.len() - 1; - while i < j { - s.swap(i, j); - i += 1; - j -= 1; - } - } -} -``` +### 方法二 -### **...** + +```python +class Solution: + def reverseString(self, s: List[str]) -> None: + s[:] = s[::-1] ``` +```ts +/** + Do not return anything, modify s in-place instead. + */ +function reverseString(s: string[]): void { + s.reverse(); +} ``` + + diff --git a/solution/0300-0399/0344.Reverse String/README_EN.md b/solution/0300-0399/0344.Reverse String/README_EN.md index 251db21850ae2..349fd2ebd485a 100644 --- a/solution/0300-0399/0344.Reverse String/README_EN.md +++ b/solution/0300-0399/0344.Reverse String/README_EN.md @@ -26,9 +26,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -39,14 +39,6 @@ class Solution: i, j = i + 1, j - 1 ``` -```python -class Solution: - def reverseString(self, s: List[str]) -> None: - s[:] = s[::-1] -``` - -### **Java** - ```java class Solution { public void reverseString(char[] s) { @@ -59,8 +51,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -72,8 +62,6 @@ public: }; ``` -### **Go** - ```go func reverseString(s []byte) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { @@ -82,8 +70,6 @@ func reverseString(s []byte) { } ``` -### **TypeScript** - ```ts /** Do not return anything, modify s in-place instead. @@ -95,17 +81,20 @@ function reverseString(s: string[]): void { } ``` -```ts -/** - Do not return anything, modify s in-place instead. - */ -function reverseString(s: string[]): void { - s.reverse(); +```rust +impl Solution { + pub fn reverse_string(s: &mut Vec) { + let mut i = 0; + let mut j = s.len() - 1; + while i < j { + s.swap(i, j); + i += 1; + j -= 1; + } + } } ``` -### **JavaScript** - ```js /** * @param {character[]} s @@ -118,26 +107,27 @@ var reverseString = function (s) { }; ``` -### **Rust** + -```rust -impl Solution { - pub fn reverse_string(s: &mut Vec) { - let mut i = 0; - let mut j = s.len() - 1; - while i < j { - s.swap(i, j); - i += 1; - j -= 1; - } - } -} -``` +### Solution 2 -### **...** + +```python +class Solution: + def reverseString(self, s: List[str]) -> None: + s[:] = s[::-1] ``` +```ts +/** + Do not return anything, modify s in-place instead. + */ +function reverseString(s: string[]): void { + s.reverse(); +} ``` + + diff --git a/solution/0300-0399/0345.Reverse Vowels of a String/README.md b/solution/0300-0399/0345.Reverse Vowels of a String/README.md index ca05644f78fdc..2fed237c26e11 100644 --- a/solution/0300-0399/0345.Reverse Vowels of a String/README.md +++ b/solution/0300-0399/0345.Reverse Vowels of a String/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们可以用两个指针 $i$ 和 $j$,初始时分别指向字符串的首尾。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python class Solution: def reverseVowels(self, s: str) -> str: @@ -69,10 +63,6 @@ class Solution: return "".join(cs) ``` -### **Java** - - - ```java class Solution { public String reverseVowels(String s) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func reverseVowels(s string) string { vowels := [128]bool{} @@ -156,8 +142,6 @@ func reverseVowels(s string) string { } ``` -### **TypeScript** - ```ts function reverseVowels(s: string): string { const vowels = new Set(['a', 'e', 'i', 'o', 'u']); @@ -175,8 +159,6 @@ function reverseVowels(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn reverse_vowels(s: String) -> String { @@ -201,10 +183,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0345.Reverse Vowels of a String/README_EN.md b/solution/0300-0399/0345.Reverse Vowels of a String/README_EN.md index be70e63466df8..2a6f2db66b1b6 100644 --- a/solution/0300-0399/0345.Reverse Vowels of a String/README_EN.md +++ b/solution/0300-0399/0345.Reverse Vowels of a String/README_EN.md @@ -26,9 +26,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -47,8 +47,6 @@ class Solution: return "".join(cs) ``` -### **Java** - ```java class Solution { public String reverseVowels(String s) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +102,6 @@ public: }; ``` -### **Go** - ```go func reverseVowels(s string) string { vowels := [128]bool{} @@ -132,8 +126,6 @@ func reverseVowels(s string) string { } ``` -### **TypeScript** - ```ts function reverseVowels(s: string): string { const vowels = new Set(['a', 'e', 'i', 'o', 'u']); @@ -151,8 +143,6 @@ function reverseVowels(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn reverse_vowels(s: String) -> String { @@ -177,10 +167,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0346.Moving Average from Data Stream/README.md b/solution/0300-0399/0346.Moving Average from Data Stream/README.md index 7c6426df77abe..b1dd37b53dd91 100644 --- a/solution/0300-0399/0346.Moving Average from Data Stream/README.md +++ b/solution/0300-0399/0346.Moving Average from Data Stream/README.md @@ -46,18 +46,10 @@ movingAverage.next(5); // 返回 6.0 = (10 + 3 + 5) / 3 ## 解法 - - -**方法一:循环数组** - -**方法二:队列** +### 方法一:循环数组 -### **Python3** - - - ```python class MovingAverage: def __init__(self, size: int): @@ -78,30 +70,6 @@ class MovingAverage: # param_1 = obj.next(val) ``` -```python -class MovingAverage: - def __init__(self, size: int): - self.n = size - self.s = 0 - self.q = deque() - - def next(self, val: int) -> float: - if len(self.q) == self.n: - self.s -= self.q.popleft() - self.q.append(val) - self.s += val - return self.s / len(self.q) - - -# Your MovingAverage object will be instantiated and called as such: -# obj = MovingAverage(size) -# param_1 = obj.next(val) -``` - -### **Java** - - - ```java class MovingAverage { private int[] arr; @@ -128,35 +96,6 @@ class MovingAverage { */ ``` -```java -class MovingAverage { - private Deque q = new ArrayDeque<>(); - private int n; - private int s; - - public MovingAverage(int size) { - n = size; - } - - public double next(int val) { - if (q.size() == n) { - s -= q.pollFirst(); - } - q.offer(val); - s += val; - return s * 1.0 / q.size(); - } -} - -/** - * Your MovingAverage object will be instantiated and called as such: - * MovingAverage obj = new MovingAverage(size); - * double param_1 = obj.next(val); - */ -``` - -### **C++** - ```cpp class MovingAverage { public: @@ -185,6 +124,86 @@ private: */ ``` +```go +type MovingAverage struct { + arr []int + cnt int + s int +} + +func Constructor(size int) MovingAverage { + arr := make([]int, size) + return MovingAverage{arr, 0, 0} +} + +func (this *MovingAverage) Next(val int) float64 { + idx := this.cnt % len(this.arr) + this.s += val - this.arr[idx] + this.arr[idx] = val + this.cnt++ + return float64(this.s) / float64(min(this.cnt, len(this.arr))) +} + +/** + * Your MovingAverage object will be instantiated and called as such: + * obj := Constructor(size); + * param_1 := obj.Next(val); + */ +``` + + + +### 方法二:队列 + + + +```python +class MovingAverage: + def __init__(self, size: int): + self.n = size + self.s = 0 + self.q = deque() + + def next(self, val: int) -> float: + if len(self.q) == self.n: + self.s -= self.q.popleft() + self.q.append(val) + self.s += val + return self.s / len(self.q) + + +# Your MovingAverage object will be instantiated and called as such: +# obj = MovingAverage(size) +# param_1 = obj.next(val) +``` + +```java +class MovingAverage { + private Deque q = new ArrayDeque<>(); + private int n; + private int s; + + public MovingAverage(int size) { + n = size; + } + + public double next(int val) { + if (q.size() == n) { + s -= q.pollFirst(); + } + q.offer(val); + s += val; + return s * 1.0 / q.size(); + } +} + +/** + * Your MovingAverage object will be instantiated and called as such: + * MovingAverage obj = new MovingAverage(size); + * double param_1 = obj.next(val); + */ +``` + ```cpp class MovingAverage { public: @@ -215,35 +234,6 @@ private: */ ``` -### **Go** - -```go -type MovingAverage struct { - arr []int - cnt int - s int -} - -func Constructor(size int) MovingAverage { - arr := make([]int, size) - return MovingAverage{arr, 0, 0} -} - -func (this *MovingAverage) Next(val int) float64 { - idx := this.cnt % len(this.arr) - this.s += val - this.arr[idx] - this.arr[idx] = val - this.cnt++ - return float64(this.s) / float64(min(this.cnt, len(this.arr))) -} - -/** - * Your MovingAverage object will be instantiated and called as such: - * obj := Constructor(size); - * param_1 := obj.Next(val); - */ -``` - ```go type MovingAverage struct { q []int @@ -272,10 +262,6 @@ func (this *MovingAverage) Next(val int) float64 { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0346.Moving Average from Data Stream/README_EN.md b/solution/0300-0399/0346.Moving Average from Data Stream/README_EN.md index a03339d7f6972..1cc5c378812b7 100644 --- a/solution/0300-0399/0346.Moving Average from Data Stream/README_EN.md +++ b/solution/0300-0399/0346.Moving Average from Data Stream/README_EN.md @@ -42,9 +42,9 @@ movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3 ## Solutions - +### Solution 1 -### **Python3** + ```python class MovingAverage: @@ -66,28 +66,6 @@ class MovingAverage: # param_1 = obj.next(val) ``` -```python -class MovingAverage: - def __init__(self, size: int): - self.n = size - self.s = 0 - self.q = deque() - - def next(self, val: int) -> float: - if len(self.q) == self.n: - self.s -= self.q.popleft() - self.q.append(val) - self.s += val - return self.s / len(self.q) - - -# Your MovingAverage object will be instantiated and called as such: -# obj = MovingAverage(size) -# param_1 = obj.next(val) -``` - -### **Java** - ```java class MovingAverage { private int[] arr; @@ -114,35 +92,6 @@ class MovingAverage { */ ``` -```java -class MovingAverage { - private Deque q = new ArrayDeque<>(); - private int n; - private int s; - - public MovingAverage(int size) { - n = size; - } - - public double next(int val) { - if (q.size() == n) { - s -= q.pollFirst(); - } - q.offer(val); - s += val; - return s * 1.0 / q.size(); - } -} - -/** - * Your MovingAverage object will be instantiated and called as such: - * MovingAverage obj = new MovingAverage(size); - * double param_1 = obj.next(val); - */ -``` - -### **C++** - ```cpp class MovingAverage { public: @@ -171,6 +120,86 @@ private: */ ``` +```go +type MovingAverage struct { + arr []int + cnt int + s int +} + +func Constructor(size int) MovingAverage { + arr := make([]int, size) + return MovingAverage{arr, 0, 0} +} + +func (this *MovingAverage) Next(val int) float64 { + idx := this.cnt % len(this.arr) + this.s += val - this.arr[idx] + this.arr[idx] = val + this.cnt++ + return float64(this.s) / float64(min(this.cnt, len(this.arr))) +} + +/** + * Your MovingAverage object will be instantiated and called as such: + * obj := Constructor(size); + * param_1 := obj.Next(val); + */ +``` + + + +### Solution 2 + + + +```python +class MovingAverage: + def __init__(self, size: int): + self.n = size + self.s = 0 + self.q = deque() + + def next(self, val: int) -> float: + if len(self.q) == self.n: + self.s -= self.q.popleft() + self.q.append(val) + self.s += val + return self.s / len(self.q) + + +# Your MovingAverage object will be instantiated and called as such: +# obj = MovingAverage(size) +# param_1 = obj.next(val) +``` + +```java +class MovingAverage { + private Deque q = new ArrayDeque<>(); + private int n; + private int s; + + public MovingAverage(int size) { + n = size; + } + + public double next(int val) { + if (q.size() == n) { + s -= q.pollFirst(); + } + q.offer(val); + s += val; + return s * 1.0 / q.size(); + } +} + +/** + * Your MovingAverage object will be instantiated and called as such: + * MovingAverage obj = new MovingAverage(size); + * double param_1 = obj.next(val); + */ +``` + ```cpp class MovingAverage { public: @@ -201,35 +230,6 @@ private: */ ``` -### **Go** - -```go -type MovingAverage struct { - arr []int - cnt int - s int -} - -func Constructor(size int) MovingAverage { - arr := make([]int, size) - return MovingAverage{arr, 0, 0} -} - -func (this *MovingAverage) Next(val int) float64 { - idx := this.cnt % len(this.arr) - this.s += val - this.arr[idx] - this.arr[idx] = val - this.cnt++ - return float64(this.s) / float64(min(this.cnt, len(this.arr))) -} - -/** - * Your MovingAverage object will be instantiated and called as such: - * obj := Constructor(size); - * param_1 := obj.Next(val); - */ -``` - ```go type MovingAverage struct { q []int @@ -258,10 +258,6 @@ func (this *MovingAverage) Next(val int) float64 { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0347.Top K Frequent Elements/README.md b/solution/0300-0399/0347.Top K Frequent Elements/README.md index 0bfff9d247b54..d17b4c1ae09d8 100644 --- a/solution/0300-0399/0347.Top K Frequent Elements/README.md +++ b/solution/0300-0399/0347.Top K Frequent Elements/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:哈希表 + 优先队列(小根堆)** +### 方法一:哈希表 + 优先队列(小根堆) 使用哈希表统计每个元素出现的次数,然后使用优先队列(小根堆)维护前 $k$ 个出现次数最多的元素。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: @@ -60,22 +54,6 @@ class Solution: return [v[0] for v in cnt.most_common(k)] ``` -```python -class Solution: - def topKFrequent(self, nums: List[int], k: int) -> List[int]: - cnt = Counter(nums) - hp = [] - for num, freq in cnt.items(): - heappush(hp, (freq, num)) - if len(hp) > k: - heappop(hp) - return [v[1] for v in hp] -``` - -### **Java** - - - ```java class Solution { public int[] topKFrequent(int[] nums, int k) { @@ -93,72 +71,6 @@ class Solution { } ``` -```java -class Solution { - public int[] topKFrequent(int[] nums, int k) { - Map cnt = new HashMap<>(); - for (int v : nums) { - cnt.put(v, cnt.getOrDefault(v, 0) + 1); - } - PriorityQueue pq = new PriorityQueue<>((a, b) -> a[1] - b[1]); - for (var e : cnt.entrySet()) { - pq.offer(new int[] {e.getKey(), e.getValue()}); - if (pq.size() > k) { - pq.poll(); - } - } - int[] ans = new int[k]; - for (int i = 0; i < k; ++i) { - ans[i] = pq.poll()[0]; - } - return ans; - } -} -``` - -### **TypeScript** - -```ts -function topKFrequent(nums: number[], k: number): number[] { - let hashMap = new Map(); - for (let num of nums) { - hashMap.set(num, (hashMap.get(num) || 0) + 1); - } - let list = [...hashMap]; - list.sort((a, b) => b[1] - a[1]); - let ans = []; - for (let i = 0; i < k; i++) { - ans.push(list[i][0]); - } - return ans; -} -``` - -```ts -function topKFrequent(nums: number[], k: number): number[] { - const map = new Map(); - let maxCount = 0; - for (const num of nums) { - map.set(num, (map.get(num) ?? 0) + 1); - maxCount = Math.max(maxCount, map.get(num)); - } - - const res = []; - while (k > 0) { - for (const key of map.keys()) { - if (map.get(key) === maxCount) { - res.push(key); - k--; - } - } - maxCount--; - } - return res; -} -``` - -### **C++** - ```cpp using pii = pair; @@ -184,8 +96,6 @@ public: }; ``` -### **Go** - ```go func topKFrequent(nums []int, k int) []int { cnt := map[int]int{} @@ -216,7 +126,21 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **Rust** +```ts +function topKFrequent(nums: number[], k: number): number[] { + let hashMap = new Map(); + for (let num of nums) { + hashMap.set(num, (hashMap.get(num) || 0) + 1); + } + let list = [...hashMap]; + list.sort((a, b) => b[1] - a[1]); + let ans = []; + for (let i = 0; i < k; i++) { + ans.push(list[i][0]); + } + return ans; +} +``` ```rust use std::collections::HashMap; @@ -249,10 +173,70 @@ impl Solution { } ``` -### **...** + +### 方法二 + + + +```python +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + cnt = Counter(nums) + hp = [] + for num, freq in cnt.items(): + heappush(hp, (freq, num)) + if len(hp) > k: + heappop(hp) + return [v[1] for v in hp] +``` + +```java +class Solution { + public int[] topKFrequent(int[] nums, int k) { + Map cnt = new HashMap<>(); + for (int v : nums) { + cnt.put(v, cnt.getOrDefault(v, 0) + 1); + } + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[1] - b[1]); + for (var e : cnt.entrySet()) { + pq.offer(new int[] {e.getKey(), e.getValue()}); + if (pq.size() > k) { + pq.poll(); + } + } + int[] ans = new int[k]; + for (int i = 0; i < k; ++i) { + ans[i] = pq.poll()[0]; + } + return ans; + } +} ``` +```ts +function topKFrequent(nums: number[], k: number): number[] { + const map = new Map(); + let maxCount = 0; + for (const num of nums) { + map.set(num, (map.get(num) ?? 0) + 1); + maxCount = Math.max(maxCount, map.get(num)); + } + + const res = []; + while (k > 0) { + for (const key of map.keys()) { + if (map.get(key) === maxCount) { + res.push(key); + k--; + } + } + maxCount--; + } + return res; +} ``` + + diff --git a/solution/0300-0399/0347.Top K Frequent Elements/README_EN.md b/solution/0300-0399/0347.Top K Frequent Elements/README_EN.md index bf053e8e77c35..814e4bfd49a87 100644 --- a/solution/0300-0399/0347.Top K Frequent Elements/README_EN.md +++ b/solution/0300-0399/0347.Top K Frequent Elements/README_EN.md @@ -29,9 +29,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -40,20 +40,6 @@ class Solution: return [v[0] for v in cnt.most_common(k)] ``` -```python -class Solution: - def topKFrequent(self, nums: List[int], k: int) -> List[int]: - cnt = Counter(nums) - hp = [] - for num, freq in cnt.items(): - heappush(hp, (freq, num)) - if len(hp) > k: - heappop(hp) - return [v[1] for v in hp] -``` - -### **Java** - ```java class Solution { public int[] topKFrequent(int[] nums, int k) { @@ -71,72 +57,6 @@ class Solution { } ``` -```java -class Solution { - public int[] topKFrequent(int[] nums, int k) { - Map cnt = new HashMap<>(); - for (int v : nums) { - cnt.put(v, cnt.getOrDefault(v, 0) + 1); - } - PriorityQueue pq = new PriorityQueue<>((a, b) -> a[1] - b[1]); - for (var e : cnt.entrySet()) { - pq.offer(new int[] {e.getKey(), e.getValue()}); - if (pq.size() > k) { - pq.poll(); - } - } - int[] ans = new int[k]; - for (int i = 0; i < k; ++i) { - ans[i] = pq.poll()[0]; - } - return ans; - } -} -``` - -### **TypeScript** - -```ts -function topKFrequent(nums: number[], k: number): number[] { - let hashMap = new Map(); - for (let num of nums) { - hashMap.set(num, (hashMap.get(num) || 0) + 1); - } - let list = [...hashMap]; - list.sort((a, b) => b[1] - a[1]); - let ans = []; - for (let i = 0; i < k; i++) { - ans.push(list[i][0]); - } - return ans; -} -``` - -```ts -function topKFrequent(nums: number[], k: number): number[] { - const map = new Map(); - let maxCount = 0; - for (const num of nums) { - map.set(num, (map.get(num) ?? 0) + 1); - maxCount = Math.max(maxCount, map.get(num)); - } - - const res = []; - while (k > 0) { - for (const key of map.keys()) { - if (map.get(key) === maxCount) { - res.push(key); - k--; - } - } - maxCount--; - } - return res; -} -``` - -### **C++** - ```cpp using pii = pair; @@ -162,8 +82,6 @@ public: }; ``` -### **Go** - ```go func topKFrequent(nums []int, k int) []int { cnt := map[int]int{} @@ -194,7 +112,21 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **Rust** +```ts +function topKFrequent(nums: number[], k: number): number[] { + let hashMap = new Map(); + for (let num of nums) { + hashMap.set(num, (hashMap.get(num) || 0) + 1); + } + let list = [...hashMap]; + list.sort((a, b) => b[1] - a[1]); + let ans = []; + for (let i = 0; i < k; i++) { + ans.push(list[i][0]); + } + return ans; +} +``` ```rust use std::collections::HashMap; @@ -227,10 +159,70 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + cnt = Counter(nums) + hp = [] + for num, freq in cnt.items(): + heappush(hp, (freq, num)) + if len(hp) > k: + heappop(hp) + return [v[1] for v in hp] ``` +```java +class Solution { + public int[] topKFrequent(int[] nums, int k) { + Map cnt = new HashMap<>(); + for (int v : nums) { + cnt.put(v, cnt.getOrDefault(v, 0) + 1); + } + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[1] - b[1]); + for (var e : cnt.entrySet()) { + pq.offer(new int[] {e.getKey(), e.getValue()}); + if (pq.size() > k) { + pq.poll(); + } + } + int[] ans = new int[k]; + for (int i = 0; i < k; ++i) { + ans[i] = pq.poll()[0]; + } + return ans; + } +} +``` + +```ts +function topKFrequent(nums: number[], k: number): number[] { + const map = new Map(); + let maxCount = 0; + for (const num of nums) { + map.set(num, (map.get(num) ?? 0) + 1); + maxCount = Math.max(maxCount, map.get(num)); + } + + const res = []; + while (k > 0) { + for (const key of map.keys()) { + if (map.get(key) === maxCount) { + res.push(key); + k--; + } + } + maxCount--; + } + return res; +} ``` + + diff --git a/solution/0300-0399/0348.Design Tic-Tac-Toe/README.md b/solution/0300-0399/0348.Design Tic-Tac-Toe/README.md index 61ef4413dd938..ef8bf931fbfc6 100644 --- a/solution/0300-0399/0348.Design Tic-Tac-Toe/README.md +++ b/solution/0300-0399/0348.Design Tic-Tac-Toe/README.md @@ -67,16 +67,10 @@ toe.move(2, 1, 1); -> 函数返回 1 (此时,玩家 1 赢得了该场比赛 ## 解法 - - -思路同[1275. 找出井字棋的获胜者](solution/1200-1299/1275.Find%20Winner%20on%20a%20Tic%20Tac%20Toe%20Game/README)。 +### 方法一 -### **Python3** - - - ```python class TicTacToe: def __init__(self, n: int): @@ -119,10 +113,6 @@ class TicTacToe: # param_1 = obj.move(row,col,player) ``` -### **Java** - - - ```java class TicTacToe { private int n; @@ -168,10 +158,6 @@ class TicTacToe { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0348.Design Tic-Tac-Toe/README_EN.md b/solution/0300-0399/0348.Design Tic-Tac-Toe/README_EN.md index e15a7139de009..a35a011a2d414 100644 --- a/solution/0300-0399/0348.Design Tic-Tac-Toe/README_EN.md +++ b/solution/0300-0399/0348.Design Tic-Tac-Toe/README_EN.md @@ -90,9 +90,9 @@ ticTacToe.move(2, 1, 1); // return 1 (player 1 wins) ## Solutions - +### Solution 1 -### **Python3** + ```python class TicTacToe: @@ -136,8 +136,6 @@ class TicTacToe: # param_1 = obj.move(row,col,player) ``` -### **Java** - ```java class TicTacToe { private int n; @@ -183,10 +181,6 @@ class TicTacToe { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0349.Intersection of Two Arrays/README.md b/solution/0300-0399/0349.Intersection of Two Arrays/README.md index ac734062c25d9..26e2afbb2dcdc 100644 --- a/solution/0300-0399/0349.Intersection of Two Arrays/README.md +++ b/solution/0300-0399/0349.Intersection of Two Arrays/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:哈希表或数组** +### 方法一:哈希表或数组 我们先用哈希表或者一个长度为 $1001$ 的数组 $s$ 记录数组 $nums1$ 中出现的元素,然后遍历数组 $nums2$ 中每个元素,如果元素 $x$ 在 $s$ 中,那么将 $x$ 加入答案,并且从 $s$ 中移除 $x$。 @@ -48,20 +46,12 @@ -### **Python3** - - - ```python class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: return list(set(nums1) & set(nums2)) ``` -### **Java** - - - ```java class Solution { public int[] intersection(int[] nums1, int[] nums2) { @@ -81,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +92,6 @@ public: }; ``` -### **Go** - ```go func intersection(nums1 []int, nums2 []int) (ans []int) { s := [1001]bool{} @@ -122,8 +108,6 @@ func intersection(nums1 []int, nums2 []int) (ans []int) { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums1 @@ -146,19 +130,22 @@ var intersection = function (nums1, nums2) { }; ``` -```js -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number[]} - */ -var intersection = function (nums1, nums2) { - return Array.from(new Set(nums1)).filter(num => new Set(nums2).has(num)); -}; +```cs +public class Solution { + public int[] Intersection(int[] nums1, int[] nums2) { + List result = new List(); + HashSet arr1 = new(nums1); + HashSet arr2 = new(nums2); + foreach (int x in arr1) { + if (arr2.Contains(x)) { + result.Add(x); + } + } + return result.ToArray(); + } +} ``` -### **PHP** - ```php class Solution { /** @@ -183,28 +170,23 @@ class Solution { } ``` -### **C#** - -```cs -public class Solution { - public int[] Intersection(int[] nums1, int[] nums2) { - List result = new List(); - HashSet arr1 = new(nums1); - HashSet arr2 = new(nums2); - foreach (int x in arr1) { - if (arr2.Contains(x)) { - result.Add(x); - } - } - return result.ToArray(); - } -} -``` + -### **...** +### 方法二 -``` + +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersection = function (nums1, nums2) { + return Array.from(new Set(nums1)).filter(num => new Set(nums2).has(num)); +}; ``` + + diff --git a/solution/0300-0399/0349.Intersection of Two Arrays/README_EN.md b/solution/0300-0399/0349.Intersection of Two Arrays/README_EN.md index 3e5316a7200ae..6363e9711315f 100644 --- a/solution/0300-0399/0349.Intersection of Two Arrays/README_EN.md +++ b/solution/0300-0399/0349.Intersection of Two Arrays/README_EN.md @@ -32,9 +32,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -42,8 +42,6 @@ class Solution: return list(set(nums1) & set(nums2)) ``` -### **Java** - ```java class Solution { public int[] intersection(int[] nums1, int[] nums2) { @@ -63,8 +61,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -86,8 +82,6 @@ public: }; ``` -### **Go** - ```go func intersection(nums1 []int, nums2 []int) (ans []int) { s := [1001]bool{} @@ -104,8 +98,6 @@ func intersection(nums1 []int, nums2 []int) (ans []int) { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums1 @@ -128,19 +120,22 @@ var intersection = function (nums1, nums2) { }; ``` -```js -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number[]} - */ -var intersection = function (nums1, nums2) { - return Array.from(new Set(nums1)).filter(num => new Set(nums2).has(num)); -}; +```cs +public class Solution { + public int[] Intersection(int[] nums1, int[] nums2) { + List result = new List(); + HashSet arr1 = new(nums1); + HashSet arr2 = new(nums2); + foreach (int x in arr1) { + if (arr2.Contains(x)) { + result.Add(x); + } + } + return result.ToArray(); + } +} ``` -### **PHP** - ```php class Solution { /** @@ -165,28 +160,23 @@ class Solution { } ``` -### **C#** - -```cs -public class Solution { - public int[] Intersection(int[] nums1, int[] nums2) { - List result = new List(); - HashSet arr1 = new(nums1); - HashSet arr2 = new(nums2); - foreach (int x in arr1) { - if (arr2.Contains(x)) { - result.Add(x); - } - } - return result.ToArray(); - } -} -``` + -### **...** +### Solution 2 -``` + +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersection = function (nums1, nums2) { + return Array.from(new Set(nums1)).filter(num => new Set(nums2).has(num)); +}; ``` + + diff --git a/solution/0300-0399/0350.Intersection of Two Arrays II/README.md b/solution/0300-0399/0350.Intersection of Two Arrays II/README.md index afd0c46700632..a9915732b722c 100644 --- a/solution/0300-0399/0350.Intersection of Two Arrays II/README.md +++ b/solution/0300-0399/0350.Intersection of Two Arrays II/README.md @@ -44,16 +44,10 @@ ## 解法 - - -“哈希表”实现。 +### 方法一 -### **Python3** - - - ```python class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: @@ -66,10 +60,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int[] intersect(int[] nums1, int[] nums2) { @@ -93,32 +83,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number[]} - */ -var intersect = function (nums1, nums2) { - const counter = {}; - for (const num of nums1) { - counter[num] = (counter[num] || 0) + 1; - } - let res = []; - for (const num of nums2) { - if (counter[num] > 0) { - res.push(num); - counter[num] -= 1; - } - } - return res; -}; -``` - -### **C++** - ```cpp class Solution { public: @@ -137,8 +101,6 @@ public: }; ``` -### **Go** - ```go func intersect(nums1 []int, nums2 []int) []int { counter := make(map[int]int) @@ -156,8 +118,6 @@ func intersect(nums1 []int, nums2 []int) []int { } ``` -### **TypeScript** - ```ts function intersect(nums1: number[], nums2: number[]): number[] { const map = new Map(); @@ -176,8 +136,6 @@ function intersect(nums1: number[], nums2: number[]): number[] { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -199,33 +157,28 @@ impl Solution { } ``` -### **PHP** - -```php -class Solution { - /** - * @param Integer[] $nums1 - * @param Integer[] $nums2 - * @return Integer[] - */ - function intersect($nums1, $nums2) { - $rs = []; - for ($i = 0; $i < count($nums1); $i++) { - $hashtable[$nums1[$i]] += 1; - } - for ($j = 0; $j < count($nums2); $j++) { - if (isset($hashtable[$nums2[$j]]) && $hashtable[$nums2[$j]] > 0) { - array_push($rs, $nums2[$j]); - $hashtable[$nums2[$j]] -= 1; - } +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersect = function (nums1, nums2) { + const counter = {}; + for (const num of nums1) { + counter[num] = (counter[num] || 0) + 1; + } + let res = []; + for (const num of nums2) { + if (counter[num] > 0) { + res.push(num); + counter[num] -= 1; } - return $rs; } -} + return res; +}; ``` -### **C#** - ```cs public class Solution { public int[] Intersect(int[] nums1, int[] nums2) { @@ -257,10 +210,29 @@ public class Solution { } ``` -### **...** - -``` - +```php +class Solution { + /** + * @param Integer[] $nums1 + * @param Integer[] $nums2 + * @return Integer[] + */ + function intersect($nums1, $nums2) { + $rs = []; + for ($i = 0; $i < count($nums1); $i++) { + $hashtable[$nums1[$i]] += 1; + } + for ($j = 0; $j < count($nums2); $j++) { + if (isset($hashtable[$nums2[$j]]) && $hashtable[$nums2[$j]] > 0) { + array_push($rs, $nums2[$j]); + $hashtable[$nums2[$j]] -= 1; + } + } + return $rs; + } +} ``` + + diff --git a/solution/0300-0399/0350.Intersection of Two Arrays II/README_EN.md b/solution/0300-0399/0350.Intersection of Two Arrays II/README_EN.md index 5db82879f3a8a..604bf79260197 100644 --- a/solution/0300-0399/0350.Intersection of Two Arrays II/README_EN.md +++ b/solution/0300-0399/0350.Intersection of Two Arrays II/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public int[] intersect(int[] nums1, int[] nums2) { @@ -82,32 +80,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number[]} - */ -var intersect = function (nums1, nums2) { - const counter = {}; - for (const num of nums1) { - counter[num] = (counter[num] || 0) + 1; - } - let res = []; - for (const num of nums2) { - if (counter[num] > 0) { - res.push(num); - counter[num] -= 1; - } - } - return res; -}; -``` - -### **C++** - ```cpp class Solution { public: @@ -126,8 +98,6 @@ public: }; ``` -### **Go** - ```go func intersect(nums1 []int, nums2 []int) []int { counter := make(map[int]int) @@ -145,8 +115,6 @@ func intersect(nums1 []int, nums2 []int) []int { } ``` -### **TypeScript** - ```ts function intersect(nums1: number[], nums2: number[]): number[] { const map = new Map(); @@ -165,8 +133,6 @@ function intersect(nums1: number[], nums2: number[]): number[] { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -188,33 +154,28 @@ impl Solution { } ``` -### **PHP** - -```php -class Solution { - /** - * @param Integer[] $nums1 - * @param Integer[] $nums2 - * @return Integer[] - */ - function intersect($nums1, $nums2) { - $rs = []; - for ($i = 0; $i < count($nums1); $i++) { - $hashtable[$nums1[$i]] += 1; - } - for ($j = 0; $j < count($nums2); $j++) { - if (isset($hashtable[$nums2[$j]]) && $hashtable[$nums2[$j]] > 0) { - array_push($rs, $nums2[$j]); - $hashtable[$nums2[$j]] -= 1; - } +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var intersect = function (nums1, nums2) { + const counter = {}; + for (const num of nums1) { + counter[num] = (counter[num] || 0) + 1; + } + let res = []; + for (const num of nums2) { + if (counter[num] > 0) { + res.push(num); + counter[num] -= 1; } - return $rs; } -} + return res; +}; ``` -### **C#** - ```cs public class Solution { public int[] Intersect(int[] nums1, int[] nums2) { @@ -246,10 +207,29 @@ public class Solution { } ``` -### **...** - -``` - +```php +class Solution { + /** + * @param Integer[] $nums1 + * @param Integer[] $nums2 + * @return Integer[] + */ + function intersect($nums1, $nums2) { + $rs = []; + for ($i = 0; $i < count($nums1); $i++) { + $hashtable[$nums1[$i]] += 1; + } + for ($j = 0; $j < count($nums2); $j++) { + if (isset($hashtable[$nums2[$j]]) && $hashtable[$nums2[$j]] > 0) { + array_push($rs, $nums2[$j]); + $hashtable[$nums2[$j]] -= 1; + } + } + return $rs; + } +} ``` + + diff --git a/solution/0300-0399/0351.Android Unlock Patterns/README.md b/solution/0300-0399/0351.Android Unlock Patterns/README.md index 78507c2d4b362..5e6c4b6634e74 100644 --- a/solution/0300-0399/0351.Android Unlock Patterns/README.md +++ b/solution/0300-0399/0351.Android Unlock Patterns/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们定义一个二维数组 $cross$,其中 $cross[i][j]$ 表示数字 $i$ 和数字 $j$ 之间是否有中间数字,如果有则 $cross[i][j]$ 的值为中间数字,否则为 $0$。 @@ -91,10 +89,6 @@ -### **Python3** - - - ```python class Solution: def numberOfPatterns(self, m: int, n: int) -> int: @@ -123,10 +117,6 @@ class Solution: return dfs(1) * 4 + dfs(2) * 4 + dfs(5) ``` -### **Java** - - - ```java class Solution { private int m; @@ -166,8 +156,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -206,8 +194,6 @@ public: }; ``` -### **Go** - ```go func numberOfPatterns(m int, n int) int { cross := [10][10]int{} @@ -251,8 +237,6 @@ func numberOfPatterns(m int, n int) int { } ``` -### **TypeScript** - ```ts function numberOfPatterns(m: number, n: number): number { const cross: number[][] = Array(10) @@ -289,10 +273,6 @@ function numberOfPatterns(m: number, n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0351.Android Unlock Patterns/README_EN.md b/solution/0300-0399/0351.Android Unlock Patterns/README_EN.md index 1f6c5d9b14998..9bb8b32cfccf5 100644 --- a/solution/0300-0399/0351.Android Unlock Patterns/README_EN.md +++ b/solution/0300-0399/0351.Android Unlock Patterns/README_EN.md @@ -55,9 +55,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -87,8 +87,6 @@ class Solution: return dfs(1) * 4 + dfs(2) * 4 + dfs(5) ``` -### **Java** - ```java class Solution { private int m; @@ -128,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +164,6 @@ public: }; ``` -### **Go** - ```go func numberOfPatterns(m int, n int) int { cross := [10][10]int{} @@ -213,8 +207,6 @@ func numberOfPatterns(m int, n int) int { } ``` -### **TypeScript** - ```ts function numberOfPatterns(m: number, n: number): number { const cross: number[][] = Array(10) @@ -251,10 +243,6 @@ function numberOfPatterns(m: number, n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0352.Data Stream as Disjoint Intervals/README.md b/solution/0300-0399/0352.Data Stream as Disjoint Intervals/README.md index 22c0e64bfe3de..6f4af8b0548f4 100644 --- a/solution/0300-0399/0352.Data Stream as Disjoint Intervals/README.md +++ b/solution/0300-0399/0352.Data Stream as Disjoint Intervals/README.md @@ -60,14 +60,10 @@ summaryRanges.getIntervals(); // 返回 [[1, 3], [6, 7]] ## 解法 - +### 方法一 -### **Python3** - - - ```python from sortedcontainers import SortedDict @@ -107,10 +103,6 @@ class SummaryRanges: # # param_2 = obj.getIntervals() ``` -### **Java** - - - ```java class SummaryRanges { private TreeMap mp; @@ -152,8 +144,6 @@ class SummaryRanges { */ ``` -### **C++** - ```cpp class SummaryRanges { private: @@ -192,10 +182,6 @@ public: */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0352.Data Stream as Disjoint Intervals/README_EN.md b/solution/0300-0399/0352.Data Stream as Disjoint Intervals/README_EN.md index 73327581d8e5d..78ca19d18f9c5 100644 --- a/solution/0300-0399/0352.Data Stream as Disjoint Intervals/README_EN.md +++ b/solution/0300-0399/0352.Data Stream as Disjoint Intervals/README_EN.md @@ -52,9 +52,9 @@ summaryRanges.getIntervals(); // return [[1, 3], [6, 7]] ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedDict @@ -95,8 +95,6 @@ class SummaryRanges: # # param_2 = obj.getIntervals() ``` -### **Java** - ```java class SummaryRanges { private TreeMap mp; @@ -138,8 +136,6 @@ class SummaryRanges { */ ``` -### **C++** - ```cpp class SummaryRanges { private: @@ -178,10 +174,6 @@ public: */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0353.Design Snake Game/README.md b/solution/0300-0399/0353.Design Snake Game/README.md index 6141fbce8ea5d..d278ab54d2b56 100644 --- a/solution/0300-0399/0353.Design Snake Game/README.md +++ b/solution/0300-0399/0353.Design Snake Game/README.md @@ -63,9 +63,7 @@ snakeGame.move("U"); // 返回 -1 ,蛇与边界相撞,游戏结束 ## 解法 - - -**方法一:双端队列模拟** +### 方法一:双端队列模拟 我们可以使用双端队列来模拟蛇的移动。 @@ -83,10 +81,6 @@ snakeGame.move("U"); // 返回 -1 ,蛇与边界相撞,游戏结束 -### **Python3** - - - ```python class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): @@ -133,10 +127,6 @@ class SnakeGame: # param_1 = obj.move(direction) ``` -### **Java** - - - ```java class SnakeGame { private int m; @@ -199,8 +189,6 @@ class SnakeGame { */ ``` -### **C++** - ```cpp class SnakeGame { public: @@ -268,8 +256,6 @@ private: */ ``` -### **Go** - ```go type SnakeGame struct { m int @@ -328,8 +314,6 @@ func (this *SnakeGame) Move(direction string) int { */ ``` -### **TypeScript** - ```ts class SnakeGame { private m: number; @@ -396,10 +380,6 @@ class SnakeGame { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0353.Design Snake Game/README_EN.md b/solution/0300-0399/0353.Design Snake Game/README_EN.md index 7c275030870b5..f3175517acf60 100644 --- a/solution/0300-0399/0353.Design Snake Game/README_EN.md +++ b/solution/0300-0399/0353.Design Snake Game/README_EN.md @@ -60,9 +60,9 @@ snakeGame.move("U"); // return -1, game over because snake collides wi ## Solutions - +### Solution 1 -### **Python3** + ```python class SnakeGame: @@ -110,8 +110,6 @@ class SnakeGame: # param_1 = obj.move(direction) ``` -### **Java** - ```java class SnakeGame { private int m; @@ -174,8 +172,6 @@ class SnakeGame { */ ``` -### **C++** - ```cpp class SnakeGame { public: @@ -243,8 +239,6 @@ private: */ ``` -### **Go** - ```go type SnakeGame struct { m int @@ -303,8 +297,6 @@ func (this *SnakeGame) Move(direction string) int { */ ``` -### **TypeScript** - ```ts class SnakeGame { private m: number; @@ -371,10 +363,6 @@ class SnakeGame { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0354.Russian Doll Envelopes/README.md b/solution/0300-0399/0354.Russian Doll Envelopes/README.md index 923ff77aac74a..6717f3a65e952 100644 --- a/solution/0300-0399/0354.Russian Doll Envelopes/README.md +++ b/solution/0300-0399/0354.Russian Doll Envelopes/README.md @@ -41,20 +41,12 @@ ## 解法 - - -按 w 进行升序排序,若 w 相同则按 h 降序排序。然后问题转换为求 h 数组的最长递增子序列长度。参考 [300. 最长递增子序列](/solution/0300-0399/0300.Longest%20Increasing%20Subsequence/README.md)。 - -**方法一:贪心 + 二分查找** +### 方法一:贪心 + 二分查找 时间复杂度 O(nlogn)。 -### **Python3** - - - ```python class Solution: def maxEnvelopes(self, envelopes: List[List[int]]) -> int: @@ -71,10 +63,6 @@ class Solution: return len(d) ``` -### **Java** - - - ```java class Solution { public int maxEnvelopes(int[][] envelopes) { @@ -106,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +118,6 @@ public: }; ``` -### **Go** - ```go func maxEnvelopes(envelopes [][]int) int { sort.Slice(envelopes, func(i, j int) bool { @@ -171,10 +155,6 @@ func maxEnvelopes(envelopes [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0354.Russian Doll Envelopes/README_EN.md b/solution/0300-0399/0354.Russian Doll Envelopes/README_EN.md index ef9020e67b787..abfd79711d305 100644 --- a/solution/0300-0399/0354.Russian Doll Envelopes/README_EN.md +++ b/solution/0300-0399/0354.Russian Doll Envelopes/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return len(d) ``` -### **Java** - ```java class Solution { public int maxEnvelopes(int[][] envelopes) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func maxEnvelopes(envelopes [][]int) int { sort.Slice(envelopes, func(i, j int) bool { @@ -157,10 +151,6 @@ func maxEnvelopes(envelopes [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0355.Design Twitter/README.md b/solution/0300-0399/0355.Design Twitter/README.md index 08ab6e9fe1000..e4620a94856cb 100644 --- a/solution/0300-0399/0355.Design Twitter/README.md +++ b/solution/0300-0399/0355.Design Twitter/README.md @@ -52,16 +52,10 @@ twitter.getNewsFeed(1); // 用户 1 获取推文应当返回一个列表,其 ## 解法 - - -“哈希表 + 堆”实现。 +### 方法一 -### **Python3** - - - ```python class Twitter: def __init__(self): @@ -115,10 +109,6 @@ class Twitter: # obj.unfollow(followerId,followeeId) ``` -### **Java** - - - ```java class Twitter { private Map> userTweets; @@ -187,10 +177,6 @@ class Twitter { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0355.Design Twitter/README_EN.md b/solution/0300-0399/0355.Design Twitter/README_EN.md index 3773244211048..a65aa833c1bd1 100644 --- a/solution/0300-0399/0355.Design Twitter/README_EN.md +++ b/solution/0300-0399/0355.Design Twitter/README_EN.md @@ -49,9 +49,9 @@ twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 t ## Solutions - +### Solution 1 -### **Python3** + ```python class Twitter: @@ -106,8 +106,6 @@ class Twitter: # obj.unfollow(followerId,followeeId) ``` -### **Java** - ```java class Twitter { private Map> userTweets; @@ -176,10 +174,6 @@ class Twitter { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0356.Line Reflection/README.md b/solution/0300-0399/0356.Line Reflection/README.md index 66a1b1f6edf0e..9c8f552537a5b 100644 --- a/solution/0300-0399/0356.Line Reflection/README.md +++ b/solution/0300-0399/0356.Line Reflection/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们先找出所有点中的最小、最大的 $x$ 坐标 $minX$ 和 $maxX$。若存在满足条件的直线,则直线 $x = (minX + maxX) / 2$,或者说 $s = minX + maxX$。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def isReflected(self, points: List[List[int]]) -> bool: @@ -72,10 +66,6 @@ class Solution: return all((s - x, y) in point_set for x, y in points) ``` -### **Java** - - - ```java class Solution { public boolean isReflected(int[][] points) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func isReflected(points [][]int) bool { const inf = 1 << 30 @@ -145,10 +131,6 @@ func isReflected(points [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0356.Line Reflection/README_EN.md b/solution/0300-0399/0356.Line Reflection/README_EN.md index 041a8474ee8e7..0251a8995c7de 100644 --- a/solution/0300-0399/0356.Line Reflection/README_EN.md +++ b/solution/0300-0399/0356.Line Reflection/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return all((s - x, y) in point_set for x, y in points) ``` -### **Java** - ```java class Solution { public boolean isReflected(int[][] points) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +103,6 @@ public: }; ``` -### **Go** - ```go func isReflected(points [][]int) bool { const inf = 1 << 30 @@ -129,10 +123,6 @@ func isReflected(points [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0357.Count Numbers with Unique Digits/README.md b/solution/0300-0399/0357.Count Numbers with Unique Digits/README.md index 4dbc0409de014..a93ae4a46c6d6 100644 --- a/solution/0300-0399/0357.Count Numbers with Unique Digits/README.md +++ b/solution/0300-0399/0357.Count Numbers with Unique Digits/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:排列组合** +### 方法一:排列组合 当 $n=0$ 时,有 $0\le x \lt 1$,只有 $1$ 个数字,即 $0$。 @@ -53,7 +51,77 @@ 时间复杂度 $O(n)$。 -**方法二:状态压缩 + 数位 DP** + + +```python +class Solution: + def countNumbersWithUniqueDigits(self, n: int) -> int: + if n == 0: + return 1 + if n == 1: + return 10 + ans, cur = 10, 9 + for i in range(n - 1): + cur *= 9 - i + ans += cur + return ans +``` + +```java +class Solution { + public int countNumbersWithUniqueDigits(int n) { + if (n == 0) { + return 1; + } + if (n == 1) { + return 10; + } + int ans = 10; + for (int i = 0, cur = 9; i < n - 1; ++i) { + cur *= (9 - i); + ans += cur; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int countNumbersWithUniqueDigits(int n) { + if (n == 0) return 1; + if (n == 1) return 10; + int ans = 10; + for (int i = 0, cur = 9; i < n - 1; ++i) { + cur *= (9 - i); + ans += cur; + } + return ans; + } +}; +``` + +```go +func countNumbersWithUniqueDigits(n int) int { + if n == 0 { + return 1 + } + if n == 1 { + return 10 + } + ans := 10 + for i, cur := 0, 9; i < n-1; i++ { + cur *= (9 - i) + ans += cur + } + return ans +} +``` + + + +### 方法二:状态压缩 + 数位 DP 这道题实际上是求在给定区间 $[l,..r]$ 中,满足条件的数的个数。条件与数的大小无关,而只与数的组成有关,因此可以使用数位 DP 的思想求解。数位 DP 中,数的大小对复杂度的影响很小。 @@ -90,24 +158,6 @@ $$ -### **Python3** - - - -```python -class Solution: - def countNumbersWithUniqueDigits(self, n: int) -> int: - if n == 0: - return 1 - if n == 1: - return 10 - ans, cur = 10, 9 - for i in range(n - 1): - cur *= 9 - i - ans += cur - return ans -``` - ```python class Solution: def countNumbersWithUniqueDigits(self, n: int) -> int: @@ -128,29 +178,6 @@ class Solution: return dfs(n, 0, True) ``` -### **Java** - - - -```java -class Solution { - public int countNumbersWithUniqueDigits(int n) { - if (n == 0) { - return 1; - } - if (n == 1) { - return 10; - } - int ans = 10; - for (int i = 0, cur = 9; i < n - 1; ++i) { - cur *= (9 - i); - ans += cur; - } - return ans; - } -} -``` - ```java class Solution { private int[][] dp = new int[10][1 << 11]; @@ -188,24 +215,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int countNumbersWithUniqueDigits(int n) { - if (n == 0) return 1; - if (n == 1) return 10; - int ans = 10; - for (int i = 0, cur = 9; i < n - 1; ++i) { - cur *= (9 - i); - ans += cur; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -240,25 +249,6 @@ public: }; ``` -### **Go** - -```go -func countNumbersWithUniqueDigits(n int) int { - if n == 0 { - return 1 - } - if n == 1 { - return 10 - } - ans := 10 - for i, cur := 0, 9; i < n-1; i++ { - cur *= (9 - i) - ans += cur - } - return ans -} -``` - ```go func countNumbersWithUniqueDigits(n int) int { dp := make([][]int, 10) @@ -297,10 +287,6 @@ func countNumbersWithUniqueDigits(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0357.Count Numbers with Unique Digits/README_EN.md b/solution/0300-0399/0357.Count Numbers with Unique Digits/README_EN.md index 1e5e322e37c6f..a07519940989b 100644 --- a/solution/0300-0399/0357.Count Numbers with Unique Digits/README_EN.md +++ b/solution/0300-0399/0357.Count Numbers with Unique Digits/README_EN.md @@ -31,9 +31,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -49,6 +49,64 @@ class Solution: return ans ``` +```java +class Solution { + public int countNumbersWithUniqueDigits(int n) { + if (n == 0) { + return 1; + } + if (n == 1) { + return 10; + } + int ans = 10; + for (int i = 0, cur = 9; i < n - 1; ++i) { + cur *= (9 - i); + ans += cur; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int countNumbersWithUniqueDigits(int n) { + if (n == 0) return 1; + if (n == 1) return 10; + int ans = 10; + for (int i = 0, cur = 9; i < n - 1; ++i) { + cur *= (9 - i); + ans += cur; + } + return ans; + } +}; +``` + +```go +func countNumbersWithUniqueDigits(n int) int { + if n == 0 { + return 1 + } + if n == 1 { + return 10 + } + ans := 10 + for i, cur := 0, 9; i < n-1; i++ { + cur *= (9 - i) + ans += cur + } + return ans +} +``` + + + +### Solution 2 + + + ```python class Solution: def countNumbersWithUniqueDigits(self, n: int) -> int: @@ -69,27 +127,6 @@ class Solution: return dfs(n, 0, True) ``` -### **Java** - -```java -class Solution { - public int countNumbersWithUniqueDigits(int n) { - if (n == 0) { - return 1; - } - if (n == 1) { - return 10; - } - int ans = 10; - for (int i = 0, cur = 9; i < n - 1; ++i) { - cur *= (9 - i); - ans += cur; - } - return ans; - } -} -``` - ```java class Solution { private int[][] dp = new int[10][1 << 11]; @@ -127,24 +164,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int countNumbersWithUniqueDigits(int n) { - if (n == 0) return 1; - if (n == 1) return 10; - int ans = 10; - for (int i = 0, cur = 9; i < n - 1; ++i) { - cur *= (9 - i); - ans += cur; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -179,25 +198,6 @@ public: }; ``` -### **Go** - -```go -func countNumbersWithUniqueDigits(n int) int { - if n == 0 { - return 1 - } - if n == 1 { - return 10 - } - ans := 10 - for i, cur := 0, 9; i < n-1; i++ { - cur *= (9 - i) - ans += cur - } - return ans -} -``` - ```go func countNumbersWithUniqueDigits(n int) int { dp := make([][]int, 10) @@ -236,10 +236,6 @@ func countNumbersWithUniqueDigits(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0358.Rearrange String k Distance Apart/README.md b/solution/0300-0399/0358.Rearrange String k Distance Apart/README.md index 59a9d6905fe4f..63c73981183f7 100644 --- a/solution/0300-0399/0358.Rearrange String k Distance Apart/README.md +++ b/solution/0300-0399/0358.Rearrange String k Distance Apart/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:贪心 + 哈希表 + 优先队列(大根堆)** +### 方法一:贪心 + 哈希表 + 优先队列(大根堆) 先用哈希表 `cnt` 统计每个字母出现的次数,然后构建一个大根堆 `pq`,其中每个元素是一个 `(v, c)` 的元组,其中 `c` 是字母,`v` 是字母出现的次数。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def rearrangeString(self, s: str, k: int) -> str: @@ -85,10 +79,6 @@ class Solution: return "" if len(ans) != len(s) else "".join(ans) ``` -### **Java** - - - ```java class Solution { public String rearrangeString(String s, int k) { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +140,6 @@ public: }; ``` -### **Go** - ```go func rearrangeString(s string, k int) string { cnt := map[byte]int{} @@ -202,10 +188,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0358.Rearrange String k Distance Apart/README_EN.md b/solution/0300-0399/0358.Rearrange String k Distance Apart/README_EN.md index 10e01701d7dc4..4f1d5b73bb877 100644 --- a/solution/0300-0399/0358.Rearrange String k Distance Apart/README_EN.md +++ b/solution/0300-0399/0358.Rearrange String k Distance Apart/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return "" if len(ans) != len(s) else "".join(ans) ``` -### **Java** - ```java class Solution { public String rearrangeString(String s, int k) { @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +126,6 @@ public: }; ``` -### **Go** - ```go func rearrangeString(s string, k int) string { cnt := map[byte]int{} @@ -180,10 +174,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0359.Logger Rate Limiter/README.md b/solution/0300-0399/0359.Logger Rate Limiter/README.md index 1f7ebd73c8d6e..14711dc051112 100644 --- a/solution/0300-0399/0359.Logger Rate Limiter/README.md +++ b/solution/0300-0399/0359.Logger Rate Limiter/README.md @@ -51,16 +51,10 @@ logger.shouldPrintMessage(11, "foo"); // 11 >= 11 ,返回 true ,下一次 "f ## 解法 - - -哈希表实现。 +### 方法一 -### **Python3** - - - ```python class Logger: def __init__(self): @@ -87,10 +81,6 @@ class Logger: # param_1 = obj.shouldPrintMessage(timestamp,message) ``` -### **Java** - - - ```java class Logger { @@ -123,8 +113,6 @@ class Logger { */ ``` -### **JavaScript** - ```js /** * Initialize your data structure here. @@ -157,10 +145,6 @@ Logger.prototype.shouldPrintMessage = function (timestamp, message) { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0359.Logger Rate Limiter/README_EN.md b/solution/0300-0399/0359.Logger Rate Limiter/README_EN.md index 2be0d5071065d..faea6cf5487d7 100644 --- a/solution/0300-0399/0359.Logger Rate Limiter/README_EN.md +++ b/solution/0300-0399/0359.Logger Rate Limiter/README_EN.md @@ -47,9 +47,9 @@ logger.shouldPrintMessage(11, "foo"); // 11 >= 11, return true, nex ## Solutions - +### Solution 1 -### **Python3** + ```python class Logger: @@ -77,8 +77,6 @@ class Logger: # param_1 = obj.shouldPrintMessage(timestamp,message) ``` -### **Java** - ```java class Logger { @@ -111,8 +109,6 @@ class Logger { */ ``` -### **JavaScript** - ```js /** * Initialize your data structure here. @@ -145,10 +141,6 @@ Logger.prototype.shouldPrintMessage = function (timestamp, message) { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0360.Sort Transformed Array/README.md b/solution/0300-0399/0360.Sort Transformed Array/README.md index 46b9662621e99..d52f3956e74ad 100644 --- a/solution/0300-0399/0360.Sort Transformed Array/README.md +++ b/solution/0300-0399/0360.Sort Transformed Array/README.md @@ -40,22 +40,10 @@ ## 解法 - - -双指针。 - -利用抛物线的性质,i,j 分别指向排序数组首尾,从两端向中间夹逼。 - -- 若 `a > 0`,抛物线向上,两端具有最大值,比较两端点的较大值,添加到结果数组。 -- 若 `a < 0`,抛物线向下,两端具有最小值,比较两端点的较小值,添加到结果数组。 -- 若 `a == 0`,合并到以上的任意一种情况均可。 +### 方法一 -### **Python3** - - - ```python class Solution: def sortTransformedArray( @@ -88,10 +76,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int[] sortTransformedArray(int[] nums, int a, int b, int c) { @@ -129,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +151,6 @@ public: }; ``` -### **Go** - ```go func sortTransformedArray(nums []int, a int, b int, c int) []int { n := len(nums) @@ -209,10 +189,6 @@ func f(a, b, c, x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0360.Sort Transformed Array/README_EN.md b/solution/0300-0399/0360.Sort Transformed Array/README_EN.md index 09f82c7e84fb9..ec24d56f1fe34 100644 --- a/solution/0300-0399/0360.Sort Transformed Array/README_EN.md +++ b/solution/0300-0399/0360.Sort Transformed Array/README_EN.md @@ -28,9 +28,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public int[] sortTransformedArray(int[] nums, int a, int b, int c) { @@ -103,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +139,6 @@ public: }; ``` -### **Go** - ```go func sortTransformedArray(nums []int, a int, b int, c int) []int { n := len(nums) @@ -183,10 +177,6 @@ func f(a, b, c, x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0361.Bomb Enemy/README.md b/solution/0300-0399/0361.Bomb Enemy/README.md index b0e9071ebcef5..7d38d94f921ce 100644 --- a/solution/0300-0399/0361.Bomb Enemy/README.md +++ b/solution/0300-0399/0361.Bomb Enemy/README.md @@ -47,14 +47,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxKilledEnemies(self, grid: List[List[str]]) -> int: @@ -96,10 +92,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public int maxKilledEnemies(char[][] grid) { @@ -159,8 +151,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -214,8 +204,6 @@ public: }; ``` -### **Go** - ```go func maxKilledEnemies(grid [][]byte) int { m, n := len(grid), len(grid[0]) @@ -275,10 +263,6 @@ func maxKilledEnemies(grid [][]byte) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0361.Bomb Enemy/README_EN.md b/solution/0300-0399/0361.Bomb Enemy/README_EN.md index 7ce046ac156eb..530147c0ebcf0 100644 --- a/solution/0300-0399/0361.Bomb Enemy/README_EN.md +++ b/solution/0300-0399/0361.Bomb Enemy/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public int maxKilledEnemies(char[][] grid) { @@ -141,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -196,8 +192,6 @@ public: }; ``` -### **Go** - ```go func maxKilledEnemies(grid [][]byte) int { m, n := len(grid), len(grid[0]) @@ -257,10 +251,6 @@ func maxKilledEnemies(grid [][]byte) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0362.Design Hit Counter/README.md b/solution/0300-0399/0362.Design Hit Counter/README.md index 0f04086aa8a7d..85d351833774b 100644 --- a/solution/0300-0399/0362.Design Hit Counter/README.md +++ b/solution/0300-0399/0362.Design Hit Counter/README.md @@ -56,16 +56,10 @@ counter.getHits(301); // 在时刻 301 统计过去 5 分钟内的敲击次数 ## 解法 - - -用哈希表作为计数器实现。 +### 方法一 -### **Python3** - - - ```python class HitCounter: def __init__(self): @@ -95,45 +89,6 @@ class HitCounter: # param_2 = obj.getHits(timestamp) ``` -### **Rust** - -```rust -use std::{ collections::BinaryHeap, cmp::Reverse }; - -struct HitCounter { - /// A min heap - pq: BinaryHeap>, -} - -impl HitCounter { - fn new() -> Self { - Self { - pq: BinaryHeap::new(), - } - } - - fn hit(&mut self, timestamp: i32) { - self.pq.push(Reverse(timestamp)); - } - - fn get_hits(&mut self, timestamp: i32) -> i32 { - while let Some(Reverse(min_elem)) = self.pq.peek() { - if *min_elem <= timestamp - 300 { - self.pq.pop(); - } else { - break; - } - } - - self.pq.len() as i32 - } -} -``` - -### **Java** - - - ```java class HitCounter { @@ -175,10 +130,39 @@ class HitCounter { */ ``` -### **...** +```rust +use std::{ collections::BinaryHeap, cmp::Reverse }; -``` +struct HitCounter { + /// A min heap + pq: BinaryHeap>, +} + +impl HitCounter { + fn new() -> Self { + Self { + pq: BinaryHeap::new(), + } + } + fn hit(&mut self, timestamp: i32) { + self.pq.push(Reverse(timestamp)); + } + + fn get_hits(&mut self, timestamp: i32) -> i32 { + while let Some(Reverse(min_elem)) = self.pq.peek() { + if *min_elem <= timestamp - 300 { + self.pq.pop(); + } else { + break; + } + } + + self.pq.len() as i32 + } +} ``` + + diff --git a/solution/0300-0399/0362.Design Hit Counter/README_EN.md b/solution/0300-0399/0362.Design Hit Counter/README_EN.md index 79ffc82e12160..0b8a26364b14a 100644 --- a/solution/0300-0399/0362.Design Hit Counter/README_EN.md +++ b/solution/0300-0399/0362.Design Hit Counter/README_EN.md @@ -51,9 +51,9 @@ hitCounter.getHits(301); // get hits at timestamp 301, return 3. ## Solutions - +### Solution 1 -### **Python3** + ```python class HitCounter: @@ -84,43 +84,6 @@ class HitCounter: # param_2 = obj.getHits(timestamp) ``` -### **Rust** - -```rust -use std::{ collections::BinaryHeap, cmp::Reverse }; - -struct HitCounter { - /// A min heap - pq: BinaryHeap>, -} - -impl HitCounter { - fn new() -> Self { - Self { - pq: BinaryHeap::new(), - } - } - - fn hit(&mut self, timestamp: i32) { - self.pq.push(Reverse(timestamp)); - } - - fn get_hits(&mut self, timestamp: i32) -> i32 { - while let Some(Reverse(min_elem)) = self.pq.peek() { - if *min_elem <= timestamp - 300 { - self.pq.pop(); - } else { - break; - } - } - - self.pq.len() as i32 - } -} -``` - -### **Java** - ```java class HitCounter { @@ -162,10 +125,39 @@ class HitCounter { */ ``` -### **...** +```rust +use std::{ collections::BinaryHeap, cmp::Reverse }; -``` +struct HitCounter { + /// A min heap + pq: BinaryHeap>, +} + +impl HitCounter { + fn new() -> Self { + Self { + pq: BinaryHeap::new(), + } + } + fn hit(&mut self, timestamp: i32) { + self.pq.push(Reverse(timestamp)); + } + + fn get_hits(&mut self, timestamp: i32) -> i32 { + while let Some(Reverse(min_elem)) = self.pq.peek() { + if *min_elem <= timestamp - 300 { + self.pq.pop(); + } else { + break; + } + } + + self.pq.len() as i32 + } +} ``` + + diff --git a/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/README.md b/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/README.md index 012b323ffe87c..b05d172f72550 100644 --- a/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/README.md +++ b/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:枚举边界 + 有序集合** +### 方法一:枚举边界 + 有序集合 我们可以枚举矩形的上下边界 $i$ 和 $j$,然后计算出该边界内每列的元素和,记录在数组 $nums$ 中,问题转化为如何在数组 $nums$ 中寻找不超过 $k$ 的最大子数组和。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python from sortedcontainers import SortedSet @@ -85,10 +79,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxSumSubmatrix(int[][] matrix, int k) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func maxSumSubmatrix(matrix [][]int, k int) int { m, n := len(matrix), len(matrix[0]) @@ -183,8 +169,6 @@ func maxSumSubmatrix(matrix [][]int, k int) int { } ``` -### **TypeScript** - ```ts function maxSumSubmatrix(matrix: number[][], k: number): number { const m = matrix.length; @@ -853,10 +837,6 @@ class TreeMultiSet { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/README_EN.md b/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/README_EN.md index d547e9e8f9ef4..8751a7129468a 100644 --- a/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/README_EN.md +++ b/solution/0300-0399/0363.Max Sum of Rectangle No Larger Than K/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedSet @@ -68,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxSumSubmatrix(int[][] matrix, int k) { @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +130,6 @@ public: }; ``` -### **Go** - ```go func maxSumSubmatrix(matrix [][]int, k int) int { m, n := len(matrix), len(matrix[0]) @@ -164,8 +158,6 @@ func maxSumSubmatrix(matrix [][]int, k int) int { } ``` -### **TypeScript** - ```ts function maxSumSubmatrix(matrix: number[][], k: number): number { const m = matrix.length; @@ -834,10 +826,6 @@ class TreeMultiSet { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0364.Nested List Weight Sum II/README.md b/solution/0300-0399/0364.Nested List Weight Sum II/README.md index d8254cd44f570..8c3cefe6cc6f5 100644 --- a/solution/0300-0399/0364.Nested List Weight Sum II/README.md +++ b/solution/0300-0399/0364.Nested List Weight Sum II/README.md @@ -46,16 +46,10 @@ ## 解法 - - -先求序列的最大深度 `depth`,然后利用 DFS 累加求和。 +### 方法一 -### **Python3** - - - ```python # """ # This is the interface that allows for creating nested lists. @@ -122,10 +116,6 @@ class Solution: return dfs(nestedList, depth) ``` -### **Java** - - - ```java /** * // This is the interface that allows for creating nested lists. @@ -186,8 +176,6 @@ class Solution { } ``` -### **JavaScript** - ```js /** * // This is the interface that allows for creating nested lists. @@ -258,10 +246,6 @@ var depthSumInverse = function (nestedList) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0364.Nested List Weight Sum II/README_EN.md b/solution/0300-0399/0364.Nested List Weight Sum II/README_EN.md index 8bd90e552dfdd..a035ea433bd58 100644 --- a/solution/0300-0399/0364.Nested List Weight Sum II/README_EN.md +++ b/solution/0300-0399/0364.Nested List Weight Sum II/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # """ @@ -112,8 +112,6 @@ class Solution: return dfs(nestedList, depth) ``` -### **Java** - ```java /** * // This is the interface that allows for creating nested lists. @@ -174,8 +172,6 @@ class Solution { } ``` -### **JavaScript** - ```js /** * // This is the interface that allows for creating nested lists. @@ -246,10 +242,6 @@ var depthSumInverse = function (nestedList) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0365.Water and Jug Problem/README.md b/solution/0300-0399/0365.Water and Jug Problem/README.md index 650260781e616..9430e4bcde0fd 100644 --- a/solution/0300-0399/0365.Water and Jug Problem/README.md +++ b/solution/0300-0399/0365.Water and Jug Problem/README.md @@ -51,18 +51,10 @@ ## 解法 - - -可以认为,每次操作只会让壶里的水带来 x 或者 y 的变化量。因此只要满足 `ax + by = z` 即可。 - -根据裴蜀定理,`ax + by = z` 有解,当且仅当 z 是 x,y 的最大公约数的倍数。所以我们只要找到 x,y 的最大公约数,然后判断 z 是否是这个最大公约数的倍数即可求得答案。 +### 方法一 -### **Python3** - - - ```python class Solution: def canMeasureWater( @@ -102,22 +94,6 @@ class Solution: return False ``` -```python -class Solution: - def canMeasureWater( - self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int - ) -> bool: - if jug1Capacity + jug2Capacity < targetCapacity: - return False - if jug1Capacity == 0 or jug2Capacity == 0: - return targetCapacity == 0 or jug1Capacity + jug2Capacity == targetCapacity - return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0 -``` - -### **Java** - - - ```java class Solution { public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) { @@ -159,26 +135,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) { - if (jug1Capacity + jug2Capacity < targetCapacity) { - return false; - } - if (jug1Capacity == 0 || jug2Capacity == 0) { - return targetCapacity == 0 || jug1Capacity + jug2Capacity == targetCapacity; - } - return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0; - } - - private int gcd(int a, int b) { - return b == 0 ? a : gcd(b, a % b); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -195,8 +151,6 @@ public: }; ``` -### **Go** - ```go func canMeasureWater(jug1Capacity int, jug2Capacity int, targetCapacity int) bool { if jug1Capacity+jug2Capacity < targetCapacity { @@ -217,10 +171,70 @@ func canMeasureWater(jug1Capacity int, jug2Capacity int, targetCapacity int) boo } ``` -### **...** +```cs +using System; + +public class Solution { + public bool CanMeasureWater(int x, int y, int z) { + if (x == 0 || y == 0) return z == x || z == y; + var gcd = GetGcd(x, y); + return z >= 0 && z <= x + y && z % gcd == 0; + } + + private int GetGcd(int x, int y) + { + while (x > 0) + { + var quotient = x / y; + var reminder = x % y; + if (reminder == 0) + { + return y; + } + x = y; + y = reminder; + } + throw new Exception("Invalid x or y"); + } +} +``` + + + +### 方法二 + + +```python +class Solution: + def canMeasureWater( + self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int + ) -> bool: + if jug1Capacity + jug2Capacity < targetCapacity: + return False + if jug1Capacity == 0 or jug2Capacity == 0: + return targetCapacity == 0 or jug1Capacity + jug2Capacity == targetCapacity + return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0 ``` +```java +class Solution { + public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) { + if (jug1Capacity + jug2Capacity < targetCapacity) { + return false; + } + if (jug1Capacity == 0 || jug2Capacity == 0) { + return targetCapacity == 0 || jug1Capacity + jug2Capacity == targetCapacity; + } + return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} ``` + + diff --git a/solution/0300-0399/0365.Water and Jug Problem/README_EN.md b/solution/0300-0399/0365.Water and Jug Problem/README_EN.md index 976b272e3e023..b51a3db6e47b1 100644 --- a/solution/0300-0399/0365.Water and Jug Problem/README_EN.md +++ b/solution/0300-0399/0365.Water and Jug Problem/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -91,20 +91,6 @@ class Solution: return False ``` -```python -class Solution: - def canMeasureWater( - self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int - ) -> bool: - if jug1Capacity + jug2Capacity < targetCapacity: - return False - if jug1Capacity == 0 or jug2Capacity == 0: - return targetCapacity == 0 or jug1Capacity + jug2Capacity == targetCapacity - return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0 -``` - -### **Java** - ```java class Solution { public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) { @@ -146,26 +132,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) { - if (jug1Capacity + jug2Capacity < targetCapacity) { - return false; - } - if (jug1Capacity == 0 || jug2Capacity == 0) { - return targetCapacity == 0 || jug1Capacity + jug2Capacity == targetCapacity; - } - return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0; - } - - private int gcd(int a, int b) { - return b == 0 ? a : gcd(b, a % b); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -182,8 +148,6 @@ public: }; ``` -### **Go** - ```go func canMeasureWater(jug1Capacity int, jug2Capacity int, targetCapacity int) bool { if jug1Capacity+jug2Capacity < targetCapacity { @@ -204,10 +168,70 @@ func canMeasureWater(jug1Capacity int, jug2Capacity int, targetCapacity int) boo } ``` -### **...** +```cs +using System; + +public class Solution { + public bool CanMeasureWater(int x, int y, int z) { + if (x == 0 || y == 0) return z == x || z == y; + var gcd = GetGcd(x, y); + return z >= 0 && z <= x + y && z % gcd == 0; + } + private int GetGcd(int x, int y) + { + while (x > 0) + { + var quotient = x / y; + var reminder = x % y; + if (reminder == 0) + { + return y; + } + x = y; + y = reminder; + } + throw new Exception("Invalid x or y"); + } +} ``` + + +### Solution 2 + + + +```python +class Solution: + def canMeasureWater( + self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int + ) -> bool: + if jug1Capacity + jug2Capacity < targetCapacity: + return False + if jug1Capacity == 0 or jug2Capacity == 0: + return targetCapacity == 0 or jug1Capacity + jug2Capacity == targetCapacity + return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0 +``` + +```java +class Solution { + public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) { + if (jug1Capacity + jug2Capacity < targetCapacity) { + return false; + } + if (jug1Capacity == 0 || jug2Capacity == 0) { + return targetCapacity == 0 || jug1Capacity + jug2Capacity == targetCapacity; + } + return targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} ``` + + diff --git a/solution/0300-0399/0366.Find Leaves of Binary Tree/README.md b/solution/0300-0399/0366.Find Leaves of Binary Tree/README.md index 94e8a4d1c2aa6..eda64911fa5ba 100644 --- a/solution/0300-0399/0366.Find Leaves of Binary Tree/README.md +++ b/solution/0300-0399/0366.Find Leaves of Binary Tree/README.md @@ -55,16 +55,10 @@ ## 解法 - - -添加前置节点 prev,初始时 `prev.left = root`。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -95,10 +89,6 @@ class Solution: return res ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -145,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -187,8 +175,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -230,10 +216,6 @@ func dfs(root, prev *TreeNode, t *[]int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0366.Find Leaves of Binary Tree/README_EN.md b/solution/0300-0399/0366.Find Leaves of Binary Tree/README_EN.md index 9e8b28ded4636..e8c4c64b9f803 100644 --- a/solution/0300-0399/0366.Find Leaves of Binary Tree/README_EN.md +++ b/solution/0300-0399/0366.Find Leaves of Binary Tree/README_EN.md @@ -39,9 +39,9 @@ Explanation: ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -73,8 +73,6 @@ class Solution: return res ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -121,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -163,8 +159,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -206,10 +200,6 @@ func dfs(root, prev *TreeNode, t *[]int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0367.Valid Perfect Square/README.md b/solution/0300-0399/0367.Valid Perfect Square/README.md index 68097692b6194..2ee1659e8670f 100644 --- a/solution/0300-0399/0367.Valid Perfect Square/README.md +++ b/solution/0300-0399/0367.Valid Perfect Square/README.md @@ -40,26 +40,14 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 不断循环二分枚举数字,判断该数的平方与 `num` 的大小关系,进而缩短空间,继续循环直至 $left \lt right$ 不成立。循环结束判断 $left^2$ 与 `num` 是否相等。 时间复杂度:$O(logN)$。 -**方法二:转换为数学问题** - -由于 `n² = 1 + 3 + 5 + ... + (2n-1)`,对数字 `num` 不断减去 $i$ (`i = 1, 3, 5, ...`) 直至 `num` 不大于 0,如果最终 `num` 等于 0,说明是一个有效的完全平方数。 - -时间复杂度:$O(sqrt(N))$。 - -### **Python3** - - - ```python class Solution: def isPerfectSquare(self, num: int) -> bool: @@ -73,20 +61,6 @@ class Solution: return left * left == num ``` -```python -class Solution: - def isPerfectSquare(self, num: int) -> bool: - i = 1 - while num > 0: - num -= i - i += 2 - return num == 0 -``` - -### **Java** - - - ```java class Solution { public boolean isPerfectSquare(int num) { @@ -104,19 +78,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isPerfectSquare(int num) { - for (int i = 1; num > 0; i += 2) { - num -= i; - } - return num == 0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -134,18 +95,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool isPerfectSquare(int num) { - for (int i = 1; num > 0; i += 2) num -= i; - return num == 0; - } -}; -``` - -### **Go** - ```go func isPerfectSquare(num int) bool { left, right := 1, num @@ -161,17 +110,6 @@ func isPerfectSquare(num int) bool { } ``` -```go -func isPerfectSquare(num int) bool { - for i := 1; num > 0; i += 2 { - num -= i - } - return num == 0 -} -``` - -### **TypeScript** - ```ts function isPerfectSquare(num: number): boolean { let left = 1; @@ -188,19 +126,6 @@ function isPerfectSquare(num: number): boolean { } ``` -```ts -function isPerfectSquare(num: number): boolean { - let i = 1; - while (num > 0) { - num -= i; - i += 2; - } - return num === 0; -} -``` - -### **Rust** - ```rust use std::cmp::Ordering; impl Solution { @@ -227,6 +152,67 @@ impl Solution { } ``` + + +### 方法二:转换为数学问题 + +由于 `n² = 1 + 3 + 5 + ... + (2n-1)`,对数字 `num` 不断减去 $i$ (`i = 1, 3, 5, ...`) 直至 `num` 不大于 0,如果最终 `num` 等于 0,说明是一个有效的完全平方数。 + +时间复杂度:$O(sqrt(N))$。 + + + +```python +class Solution: + def isPerfectSquare(self, num: int) -> bool: + i = 1 + while num > 0: + num -= i + i += 2 + return num == 0 +``` + +```java +class Solution { + public boolean isPerfectSquare(int num) { + for (int i = 1; num > 0; i += 2) { + num -= i; + } + return num == 0; + } +} +``` + +```cpp +class Solution { +public: + bool isPerfectSquare(int num) { + for (int i = 1; num > 0; i += 2) num -= i; + return num == 0; + } +}; +``` + +```go +func isPerfectSquare(num int) bool { + for i := 1; num > 0; i += 2 { + num -= i + } + return num == 0 +} +``` + +```ts +function isPerfectSquare(num: number): boolean { + let i = 1; + while (num > 0) { + num -= i; + i += 2; + } + return num === 0; +} +``` + ```rust impl Solution { pub fn is_perfect_square(mut num: i32) -> bool { @@ -240,10 +226,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0367.Valid Perfect Square/README_EN.md b/solution/0300-0399/0367.Valid Perfect Square/README_EN.md index 5ea1d2955d42f..34351f97dfc2a 100644 --- a/solution/0300-0399/0367.Valid Perfect Square/README_EN.md +++ b/solution/0300-0399/0367.Valid Perfect Square/README_EN.md @@ -36,27 +36,10 @@ ## Solutions -**Solution 1: Binary search** - -**Solution 2: Math trick** - -This is a math problem: - -```bash -1 = 1 -4 = 1 + 3 -9 = 1 + 3 + 5 -16 = 1 + 3 + 5 + 7 -25 = 1 + 3 + 5 + 7 + 9 -36 = 1 + 3 + 5 + 7 + 9 + 11 -.... -so 1+3+...+(2n-1) = (2n-1 + 1)n/2 = n² -``` +### Solution 1: Binary search -### **Python3** - ```python class Solution: def isPerfectSquare(self, num: int) -> bool: @@ -70,18 +53,6 @@ class Solution: return left * left == num ``` -```python -class Solution: - def isPerfectSquare(self, num: int) -> bool: - i = 1 - while num > 0: - num -= i - i += 2 - return num == 0 -``` - -### **Java** - ```java class Solution { public boolean isPerfectSquare(int num) { @@ -99,19 +70,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isPerfectSquare(int num) { - for (int i = 1; num > 0; i += 2) { - num -= i; - } - return num == 0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -129,18 +87,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool isPerfectSquare(int num) { - for (int i = 1; num > 0; i += 2) num -= i; - return num == 0; - } -}; -``` - -### **Go** - ```go func isPerfectSquare(num int) bool { left, right := 1, num @@ -156,17 +102,6 @@ func isPerfectSquare(num int) bool { } ``` -```go -func isPerfectSquare(num int) bool { - for i := 1; num > 0; i += 2 { - num -= i - } - return num == 0 -} -``` - -### **TypeScript** - ```ts function isPerfectSquare(num: number): boolean { let left = 1; @@ -183,19 +118,6 @@ function isPerfectSquare(num: number): boolean { } ``` -```ts -function isPerfectSquare(num: number): boolean { - let i = 1; - while (num > 0) { - num -= i; - i += 2; - } - return num === 0; -} -``` - -### **Rust** - ```rust use std::cmp::Ordering; impl Solution { @@ -222,6 +144,76 @@ impl Solution { } ``` + + +### Solution 2: Math trick + +This is a math problem: + +```bash +1 = 1 +4 = 1 + 3 +9 = 1 + 3 + 5 +16 = 1 + 3 + 5 + 7 +25 = 1 + 3 + 5 + 7 + 9 +36 = 1 + 3 + 5 + 7 + 9 + 11 +.... +so 1+3+...+(2n-1) = (2n-1 + 1)n/2 = n² +``` + + + +```python +class Solution: + def isPerfectSquare(self, num: int) -> bool: + i = 1 + while num > 0: + num -= i + i += 2 + return num == 0 +``` + +```java +class Solution { + public boolean isPerfectSquare(int num) { + for (int i = 1; num > 0; i += 2) { + num -= i; + } + return num == 0; + } +} +``` + +```cpp +class Solution { +public: + bool isPerfectSquare(int num) { + for (int i = 1; num > 0; i += 2) num -= i; + return num == 0; + } +}; +``` + +```go +func isPerfectSquare(num int) bool { + for i := 1; num > 0; i += 2 { + num -= i + } + return num == 0 +} +``` + +```ts +function isPerfectSquare(num: number): boolean { + let i = 1; + while (num > 0) { + num -= i; + i += 2; + } + return num === 0; +} +``` + ```rust impl Solution { pub fn is_perfect_square(mut num: i32) -> bool { @@ -235,10 +227,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0368.Largest Divisible Subset/README.md b/solution/0300-0399/0368.Largest Divisible Subset/README.md index 319e1167fcee6..88500897c718a 100644 --- a/solution/0300-0399/0368.Largest Divisible Subset/README.md +++ b/solution/0300-0399/0368.Largest Divisible Subset/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:排序 + 动态规划** +### 方法一:排序 + 动态规划 我们先对数组进行排序,这样可以保证对于任意的 $i \lt j$,如果 $nums[i]$ 可以整除 $nums[j]$,那么 $nums[i]$ 一定在 $nums[j]$ 的左边。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def largestDivisibleSubset(self, nums: List[int]) -> List[int]: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List largestDivisibleSubset(int[] nums) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +147,6 @@ public: }; ``` -### **Go** - ```go func largestDivisibleSubset(nums []int) (ans []int) { sort.Ints(nums) @@ -190,10 +176,6 @@ func largestDivisibleSubset(nums []int) (ans []int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0368.Largest Divisible Subset/README_EN.md b/solution/0300-0399/0368.Largest Divisible Subset/README_EN.md index 01c0fe3bccbf9..f20496a25d17f 100644 --- a/solution/0300-0399/0368.Largest Divisible Subset/README_EN.md +++ b/solution/0300-0399/0368.Largest Divisible Subset/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List largestDivisibleSubset(int[] nums) { @@ -102,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +133,6 @@ public: }; ``` -### **Go** - ```go func largestDivisibleSubset(nums []int) (ans []int) { sort.Ints(nums) @@ -168,10 +162,6 @@ func largestDivisibleSubset(nums []int) (ans []int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0369.Plus One Linked List/README.md b/solution/0300-0399/0369.Plus One Linked List/README.md index df3d7973a8cb9..b506a6cca5cba 100644 --- a/solution/0300-0399/0369.Plus One Linked List/README.md +++ b/solution/0300-0399/0369.Plus One Linked List/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:链表遍历** +### 方法一:链表遍历 我们先设置一个虚拟头节点 `dummy`,初始值为 $0$,指向链表头节点 `head`。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -80,10 +74,6 @@ class Solution: return dummy if dummy.val else dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -181,10 +167,6 @@ func plusOne(head *ListNode) *ListNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0369.Plus One Linked List/README_EN.md b/solution/0300-0399/0369.Plus One Linked List/README_EN.md index 4b3913fbf3f4b..2748342958c00 100644 --- a/solution/0300-0399/0369.Plus One Linked List/README_EN.md +++ b/solution/0300-0399/0369.Plus One Linked List/README_EN.md @@ -27,9 +27,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -53,8 +53,6 @@ class Solution: return dummy if dummy.val else dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -120,8 +116,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -152,10 +146,6 @@ func plusOne(head *ListNode) *ListNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0370.Range Addition/README.md b/solution/0300-0399/0370.Range Addition/README.md index ac012b11b6487..97242577acbd2 100644 --- a/solution/0300-0399/0370.Range Addition/README.md +++ b/solution/0300-0399/0370.Range Addition/README.md @@ -35,9 +35,7 @@ ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 差分数组模板题。 @@ -45,25 +43,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。 -**方法二:树状数组 + 差分思想** - -时间复杂度 $O(n\times \log n)$。 - -树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作: - -1. **单点更新** `update(x, delta)`: 把序列 $x$ 位置的数加上一个值 $delta$; -1. **前缀和查询** `query(x)`:查询序列 $[1,...x]$ 区间的区间和,即位置 $x$ 的前缀和。 - -这两个操作的时间复杂度均为 $O(\log n)$。 - -### **Python3** - - - -差分数组: - ```python class Solution: def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]: @@ -75,7 +56,93 @@ class Solution: return list(accumulate(d)) ``` -树状数组: +```java +class Solution { + public int[] getModifiedArray(int length, int[][] updates) { + int[] d = new int[length]; + for (var e : updates) { + int l = e[0], r = e[1], c = e[2]; + d[l] += c; + if (r + 1 < length) { + d[r + 1] -= c; + } + } + for (int i = 1; i < length; ++i) { + d[i] += d[i - 1]; + } + return d; + } +} +``` + +```cpp +class Solution { +public: + vector getModifiedArray(int length, vector>& updates) { + vector d(length); + for (auto& e : updates) { + int l = e[0], r = e[1], c = e[2]; + d[l] += c; + if (r + 1 < length) d[r + 1] -= c; + } + for (int i = 1; i < length; ++i) d[i] += d[i - 1]; + return d; + } +}; +``` + +```go +func getModifiedArray(length int, updates [][]int) []int { + d := make([]int, length) + for _, e := range updates { + l, r, c := e[0], e[1], e[2] + d[l] += c + if r+1 < length { + d[r+1] -= c + } + } + for i := 1; i < length; i++ { + d[i] += d[i-1] + } + return d +} +``` + +```js +/** + * @param {number} length + * @param {number[][]} updates + * @return {number[]} + */ +var getModifiedArray = function (length, updates) { + const d = new Array(length).fill(0); + for (const [l, r, c] of updates) { + d[l] += c; + if (r + 1 < length) { + d[r + 1] -= c; + } + } + for (let i = 1; i < length; ++i) { + d[i] += d[i - 1]; + } + return d; +}; +``` + + + +### 方法二:树状数组 + 差分思想 + +时间复杂度 $O(n\times \log n)$。 + +树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作: + +1. **单点更新** `update(x, delta)`: 把序列 $x$ 位置的数加上一个值 $delta$; +1. **前缀和查询** `query(x)`:查询序列 $[1,...x]$ 区间的区间和,即位置 $x$ 的前缀和。 + +这两个操作的时间复杂度均为 $O(\log n)$。 + + ```python class BinaryIndexedTree: @@ -109,33 +176,6 @@ class Solution: return [tree.query(i + 1) for i in range(length)] ``` -### **Java** - - - -差分数组: - -```java -class Solution { - public int[] getModifiedArray(int length, int[][] updates) { - int[] d = new int[length]; - for (var e : updates) { - int l = e[0], r = e[1], c = e[2]; - d[l] += c; - if (r + 1 < length) { - d[r + 1] -= c; - } - } - for (int i = 1; i < length; ++i) { - d[i] += d[i - 1]; - } - return d; - } -} -``` - -树状数组: - ```java class Solution { public int[] getModifiedArray(int length, int[][] updates) { @@ -184,28 +224,6 @@ class BinaryIndexedTree { } ``` -### **C++** - -差分数组: - -```cpp -class Solution { -public: - vector getModifiedArray(int length, vector>& updates) { - vector d(length); - for (auto& e : updates) { - int l = e[0], r = e[1], c = e[2]; - d[l] += c; - if (r + 1 < length) d[r + 1] -= c; - } - for (int i = 1; i < length; ++i) d[i] += d[i - 1]; - return d; - } -}; -``` - -树状数组: - ```cpp class BinaryIndexedTree { public: @@ -253,29 +271,6 @@ public: }; ``` -### **Go** - -差分数组: - -```go -func getModifiedArray(length int, updates [][]int) []int { - d := make([]int, length) - for _, e := range updates { - l, r, c := e[0], e[1], e[2] - d[l] += c - if r+1 < length { - d[r+1] -= c - } - } - for i := 1; i < length; i++ { - d[i] += d[i-1] - } - return d -} -``` - -树状数组: - ```go type BinaryIndexedTree struct { n int @@ -322,33 +317,6 @@ func getModifiedArray(length int, updates [][]int) []int { } ``` -### **JavaScript** - -```js -/** - * @param {number} length - * @param {number[][]} updates - * @return {number[]} - */ -var getModifiedArray = function (length, updates) { - const d = new Array(length).fill(0); - for (const [l, r, c] of updates) { - d[l] += c; - if (r + 1 < length) { - d[r + 1] -= c; - } - } - for (let i = 1; i < length; ++i) { - d[i] += d[i - 1]; - } - return d; -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0370.Range Addition/README_EN.md b/solution/0300-0399/0370.Range Addition/README_EN.md index 00114d7ba1714..1010e6c8f899a 100644 --- a/solution/0300-0399/0370.Range Addition/README_EN.md +++ b/solution/0300-0399/0370.Range Addition/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,6 +52,85 @@ class Solution: return list(accumulate(d)) ``` +```java +class Solution { + public int[] getModifiedArray(int length, int[][] updates) { + int[] d = new int[length]; + for (var e : updates) { + int l = e[0], r = e[1], c = e[2]; + d[l] += c; + if (r + 1 < length) { + d[r + 1] -= c; + } + } + for (int i = 1; i < length; ++i) { + d[i] += d[i - 1]; + } + return d; + } +} +``` + +```cpp +class Solution { +public: + vector getModifiedArray(int length, vector>& updates) { + vector d(length); + for (auto& e : updates) { + int l = e[0], r = e[1], c = e[2]; + d[l] += c; + if (r + 1 < length) d[r + 1] -= c; + } + for (int i = 1; i < length; ++i) d[i] += d[i - 1]; + return d; + } +}; +``` + +```go +func getModifiedArray(length int, updates [][]int) []int { + d := make([]int, length) + for _, e := range updates { + l, r, c := e[0], e[1], e[2] + d[l] += c + if r+1 < length { + d[r+1] -= c + } + } + for i := 1; i < length; i++ { + d[i] += d[i-1] + } + return d +} +``` + +```js +/** + * @param {number} length + * @param {number[][]} updates + * @return {number[]} + */ +var getModifiedArray = function (length, updates) { + const d = new Array(length).fill(0); + for (const [l, r, c] of updates) { + d[l] += c; + if (r + 1 < length) { + d[r + 1] -= c; + } + } + for (let i = 1; i < length; ++i) { + d[i] += d[i - 1]; + } + return d; +}; +``` + + + +### Solution 2 + + + ```python class BinaryIndexedTree: def __init__(self, n): @@ -84,27 +163,6 @@ class Solution: return [tree.query(i + 1) for i in range(length)] ``` -### **Java** - -```java -class Solution { - public int[] getModifiedArray(int length, int[][] updates) { - int[] d = new int[length]; - for (var e : updates) { - int l = e[0], r = e[1], c = e[2]; - d[l] += c; - if (r + 1 < length) { - d[r + 1] -= c; - } - } - for (int i = 1; i < length; ++i) { - d[i] += d[i - 1]; - } - return d; - } -} -``` - ```java class Solution { public int[] getModifiedArray(int length, int[][] updates) { @@ -153,24 +211,6 @@ class BinaryIndexedTree { } ``` -### **C++** - -```cpp -class Solution { -public: - vector getModifiedArray(int length, vector>& updates) { - vector d(length); - for (auto& e : updates) { - int l = e[0], r = e[1], c = e[2]; - d[l] += c; - if (r + 1 < length) d[r + 1] -= c; - } - for (int i = 1; i < length; ++i) d[i] += d[i - 1]; - return d; - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -218,25 +258,6 @@ public: }; ``` -### **Go** - -```go -func getModifiedArray(length int, updates [][]int) []int { - d := make([]int, length) - for _, e := range updates { - l, r, c := e[0], e[1], e[2] - d[l] += c - if r+1 < length { - d[r+1] -= c - } - } - for i := 1; i < length; i++ { - d[i] += d[i-1] - } - return d -} -``` - ```go type BinaryIndexedTree struct { n int @@ -283,33 +304,6 @@ func getModifiedArray(length int, updates [][]int) []int { } ``` -### **JavaScript** - -```js -/** - * @param {number} length - * @param {number[][]} updates - * @return {number[]} - */ -var getModifiedArray = function (length, updates) { - const d = new Array(length).fill(0); - for (const [l, r, c] of updates) { - d[l] += c; - if (r + 1 < length) { - d[r + 1] -= c; - } - } - for (let i = 1; i < length; ++i) { - d[i] += d[i - 1]; - } - return d; -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0371.Sum of Two Integers/README.md b/solution/0300-0399/0371.Sum of Two Integers/README.md index 3708fa23fe388..cfdff7e2b1450 100644 --- a/solution/0300-0399/0371.Sum of Two Integers/README.md +++ b/solution/0300-0399/0371.Sum of Two Integers/README.md @@ -34,9 +34,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 两数字的二进制形式 a,b ,求和 s = a + b ,a(i)、b(i) 分别表示 a、b 的第 i 个二进制位。一共有 4 种情况: @@ -58,12 +56,6 @@ -### **Python3** - - - -由于 python `int` 是无限长整型,左移不会自动溢出,因此需要特殊处理。 - ```python class Solution: def getSum(self, a: int, b: int) -> int: @@ -74,10 +66,6 @@ class Solution: return a if a < 0x80000000 else ~(a ^ 0xFFFFFFFF) ``` -### **Java** - - - ```java class Solution { public int getSum(int a, int b) { @@ -86,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +88,6 @@ public: }; ``` -### **Go** - ```go func getSum(a int, b int) int { for b != 0 { @@ -115,10 +99,6 @@ func getSum(a int, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0371.Sum of Two Integers/README_EN.md b/solution/0300-0399/0371.Sum of Two Integers/README_EN.md index a3d97285c9a50..f37281a2ecce6 100644 --- a/solution/0300-0399/0371.Sum of Two Integers/README_EN.md +++ b/solution/0300-0399/0371.Sum of Two Integers/README_EN.md @@ -23,9 +23,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -37,8 +37,6 @@ class Solution: return a if a < 0x80000000 else ~(a ^ 0xFFFFFFFF) ``` -### **Java** - ```java class Solution { public int getSum(int a, int b) { @@ -47,8 +45,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -63,8 +59,6 @@ public: }; ``` -### **Go** - ```go func getSum(a int, b int) int { for b != 0 { @@ -76,10 +70,6 @@ func getSum(a int, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0372.Super Pow/README.md b/solution/0300-0399/0372.Super Pow/README.md index efd2f220d6ae1..5411693316462 100644 --- a/solution/0300-0399/0372.Super Pow/README.md +++ b/solution/0300-0399/0372.Super Pow/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:快速幂** +### 方法一:快速幂 我们初始化答案变量 $ans = 1$。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def superPow(self, a: int, b: List[int]) -> int: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private final int mod = 1337; @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func superPow(a int, b []int) int { const mod int = 1337 @@ -162,8 +148,6 @@ func superPow(a int, b []int) int { } ``` -### **TypeScript** - ```ts function superPow(a: number, b: number[]): number { let ans = 1; @@ -186,10 +170,6 @@ function superPow(a: number, b: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0372.Super Pow/README_EN.md b/solution/0300-0399/0372.Super Pow/README_EN.md index 13f1bb87844e0..83707700d05f2 100644 --- a/solution/0300-0399/0372.Super Pow/README_EN.md +++ b/solution/0300-0399/0372.Super Pow/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private final int mod = 1337; @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +107,6 @@ public: }; ``` -### **Go** - ```go func superPow(a int, b []int) int { const mod int = 1337 @@ -135,8 +129,6 @@ func superPow(a int, b []int) int { } ``` -### **TypeScript** - ```ts function superPow(a: number, b: number[]): number { let ans = 1; @@ -159,10 +151,6 @@ function superPow(a: number, b: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0373.Find K Pairs with Smallest Sums/README.md b/solution/0300-0399/0373.Find K Pairs with Smallest Sums/README.md index 47eb14f333a29..1bce0ce4bd611 100644 --- a/solution/0300-0399/0373.Find K Pairs with Smallest Sums/README.md +++ b/solution/0300-0399/0373.Find K Pairs with Smallest Sums/README.md @@ -54,16 +54,10 @@ ## 解法 - - - +### 方法一 -### **Python3** - - - ```python class Solution: def kSmallestPairs( @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> kSmallestPairs(int[] nums1, int[] nums2, int k) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func kSmallestPairs(nums1, nums2 []int, k int) (ans [][]int) { m, n := len(nums1), len(nums2) @@ -171,10 +157,6 @@ func (h *hp) Push(v any) { h.data = append(h.data, v.(pair)) } func (h *hp) Pop() any { a := h.data; v := a[len(a)-1]; h.data = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0373.Find K Pairs with Smallest Sums/README_EN.md b/solution/0300-0399/0373.Find K Pairs with Smallest Sums/README_EN.md index 2224c5726b178..308977a785b91 100644 --- a/solution/0300-0399/0373.Find K Pairs with Smallest Sums/README_EN.md +++ b/solution/0300-0399/0373.Find K Pairs with Smallest Sums/README_EN.md @@ -48,12 +48,10 @@ ## Solutions - +### Solution 1 -### **Python3** - ```python class Solution: def kSmallestPairs( @@ -71,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List> kSmallestPairs(int[] nums1, int[] nums2, int k) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +117,6 @@ public: }; ``` -### **Go** - ```go func kSmallestPairs(nums1, nums2 []int, k int) (ans [][]int) { m, n := len(nums1), len(nums2) @@ -159,10 +151,6 @@ func (h *hp) Push(v any) { h.data = append(h.data, v.(pair)) } func (h *hp) Pop() any { a := h.data; v := a[len(a)-1]; h.data = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0374.Guess Number Higher or Lower/README.md b/solution/0300-0399/0374.Guess Number Higher or Lower/README.md index 8a2c19c94540e..90b434f13b01c 100644 --- a/solution/0300-0399/0374.Guess Number Higher or Lower/README.md +++ b/solution/0300-0399/0374.Guess Number Higher or Lower/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们在区间 $[1,..n]$ 进行二分查找,找到第一个满足 `guess(x) <= 0` 的数,即为答案。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python # The guess API is already defined for you. # @param num, your guess @@ -97,24 +91,6 @@ class Solution: return left ``` -```python -# The guess API is already defined for you. -# @param num, your guess -# @return -1 if num is higher than the picked number -# 1 if num is lower than the picked number -# otherwise return 0 -# def guess(num: int) -> int: - - -class Solution: - def guessNumber(self, n: int) -> int: - return bisect.bisect(range(1, n + 1), 0, key=lambda x: -guess(x)) -``` - -### **Java** - - - ```java /** * Forward declaration of guess API. @@ -141,8 +117,6 @@ public class Solution extends GuessGame { } ``` -### **C++** - ```cpp /** * Forward declaration of guess API. @@ -170,8 +144,6 @@ public: }; ``` -### **Go** - ```go /** * Forward declaration of guess API. @@ -196,54 +168,6 @@ func guessNumber(n int) int { } ``` -```go -/** - * Forward declaration of guess API. - * @param num your guess - * @return -1 if num is higher than the picked number - * 1 if num is lower than the picked number - * otherwise return 0 - * func guess(num int) int; - */ - -func guessNumber(n int) int { - return sort.Search(n, func(i int) bool { - i++ - return guess(i) <= 0 - }) + 1 -} -``` - -### **C#** - -```cs -/** - * Forward declaration of guess API. - * @param num your guess - * @return -1 if num is higher than the picked number - * 1 if num is lower than the picked number - * otherwise return 0 - * int guess(int num); - */ - -public class Solution : GuessGame { - public int GuessNumber(int n) { - int left = 1, right = n; - while (left < right) { - int mid = left + ((right - left) >> 1); - if (guess(mid) <= 0) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - } -} -``` - -### **TypeScript** - ```ts /** * Forward declaration of guess API. @@ -269,9 +193,8 @@ function guessNumber(n: number): number { } ``` -### **Rust** - ```rust + /** * Forward declaration of guess API. * @param num your guess @@ -303,10 +226,70 @@ impl Solution { } ``` -### **...** +```cs +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is higher than the picked number + * 1 if num is lower than the picked number + * otherwise return 0 + * int guess(int num); + */ + +public class Solution : GuessGame { + public int GuessNumber(int n) { + int left = 1, right = n; + while (left < right) { + int mid = left + ((right - left) >> 1); + if (guess(mid) <= 0) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + + + +### 方法二 + + + +```python +# The guess API is already defined for you. +# @param num, your guess +# @return -1 if num is higher than the picked number +# 1 if num is lower than the picked number +# otherwise return 0 +# def guess(num: int) -> int: + +class Solution: + def guessNumber(self, n: int) -> int: + return bisect.bisect(range(1, n + 1), 0, key=lambda x: -guess(x)) ``` +```go +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is higher than the picked number + * 1 if num is lower than the picked number + * otherwise return 0 + * func guess(num int) int; + */ + +func guessNumber(n int) int { + return sort.Search(n, func(i int) bool { + i++ + return guess(i) <= 0 + }) + 1 +} ``` + + diff --git a/solution/0300-0399/0374.Guess Number Higher or Lower/README_EN.md b/solution/0300-0399/0374.Guess Number Higher or Lower/README_EN.md index dfbb2f45d4e9b..ccd6ac007d897 100644 --- a/solution/0300-0399/0374.Guess Number Higher or Lower/README_EN.md +++ b/solution/0300-0399/0374.Guess Number Higher or Lower/README_EN.md @@ -52,9 +52,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # The guess API is already defined for you. @@ -75,22 +75,6 @@ class Solution: return left ``` -```python -# The guess API is already defined for you. -# @param num, your guess -# @return -1 if num is higher than the picked number -# 1 if num is lower than the picked number -# otherwise return 0 -# def guess(num: int) -> int: - - -class Solution: - def guessNumber(self, n: int) -> int: - return bisect.bisect(range(1, n + 1), 0, key=lambda x: -guess(x)) -``` - -### **Java** - ```java /** * Forward declaration of guess API. @@ -117,8 +101,6 @@ public class Solution extends GuessGame { } ``` -### **C++** - ```cpp /** * Forward declaration of guess API. @@ -146,8 +128,6 @@ public: }; ``` -### **Go** - ```go /** * Forward declaration of guess API. @@ -172,54 +152,6 @@ func guessNumber(n int) int { } ``` -```go -/** - * Forward declaration of guess API. - * @param num your guess - * @return -1 if num is higher than the picked number - * 1 if num is lower than the picked number - * otherwise return 0 - * func guess(num int) int; - */ - -func guessNumber(n int) int { - return sort.Search(n, func(i int) bool { - i++ - return guess(i) <= 0 - }) + 1 -} -``` - -### **C#** - -```cs -/** - * Forward declaration of guess API. - * @param num your guess - * @return -1 if num is higher than the picked number - * 1 if num is lower than the picked number - * otherwise return 0 - * int guess(int num); - */ - -public class Solution : GuessGame { - public int GuessNumber(int n) { - int left = 1, right = n; - while (left < right) { - int mid = left + ((right - left) >> 1); - if (guess(mid) <= 0) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - } -} -``` - -### **TypeScript** - ```ts /** * Forward declaration of guess API. @@ -245,9 +177,8 @@ function guessNumber(n: number): number { } ``` -### **Rust** - ```rust + /** * Forward declaration of guess API. * @param num your guess @@ -279,10 +210,70 @@ impl Solution { } ``` -### **...** +```cs +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is higher than the picked number + * 1 if num is lower than the picked number + * otherwise return 0 + * int guess(int num); + */ +public class Solution : GuessGame { + public int GuessNumber(int n) { + int left = 1, right = n; + while (left < right) { + int mid = left + ((right - left) >> 1); + if (guess(mid) <= 0) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} ``` + + +### Solution 2 + + + +```python +# The guess API is already defined for you. +# @param num, your guess +# @return -1 if num is higher than the picked number +# 1 if num is lower than the picked number +# otherwise return 0 +# def guess(num: int) -> int: + + +class Solution: + def guessNumber(self, n: int) -> int: + return bisect.bisect(range(1, n + 1), 0, key=lambda x: -guess(x)) +``` + +```go +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is higher than the picked number + * 1 if num is lower than the picked number + * otherwise return 0 + * func guess(num int) int; + */ + +func guessNumber(n int) int { + return sort.Search(n, func(i int) bool { + i++ + return guess(i) <= 0 + }) + 1 +} ``` + + diff --git a/solution/0300-0399/0375.Guess Number Higher or Lower II/README.md b/solution/0300-0399/0375.Guess Number Higher or Lower II/README.md index 9cdceace02431..8f309809e1d84 100644 --- a/solution/0300-0399/0375.Guess Number Higher or Lower II/README.md +++ b/solution/0300-0399/0375.Guess Number Higher or Lower II/README.md @@ -74,21 +74,10 @@ ## 解法 - - -区间 DP。 - -- 状态表示:`dp[i][j]` 表示数字区间 `[i, j]` 确保赢得游戏的最少现金。 -- 状态计算:枚举闭区间 `[i, j]` 中以数字 k 作为选择的数字。那么 `dp[i][j] = min(dp[i][j], max(dp[i][k - 1], dp[k + 1][j]) + k), k ∈ [i, j]`。 - -以区间长度 l 从小到大开始处理每个状态值。 +### 方法一 -### **Python3** - - - ```python class Solution: def getMoneyAmount(self, n: int) -> int: @@ -103,10 +92,6 @@ class Solution: return dp[1][n] ``` -### **Java** - - - ```java class Solution { public int getMoneyAmount(int n) { @@ -126,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +131,6 @@ public: }; ``` -### **Go** - ```go func getMoneyAmount(n int) int { dp := make([][]int, n+10) @@ -170,10 +151,6 @@ func getMoneyAmount(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0375.Guess Number Higher or Lower II/README_EN.md b/solution/0300-0399/0375.Guess Number Higher or Lower II/README_EN.md index 3f8976bcd9418..44f2c81c66fc0 100644 --- a/solution/0300-0399/0375.Guess Number Higher or Lower II/README_EN.md +++ b/solution/0300-0399/0375.Guess Number Higher or Lower II/README_EN.md @@ -70,9 +70,9 @@ The worst case is that you pay 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -88,8 +88,6 @@ class Solution: return dp[1][n] ``` -### **Java** - ```java class Solution { public int getMoneyAmount(int n) { @@ -109,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +127,6 @@ public: }; ``` -### **Go** - ```go func getMoneyAmount(n int) int { dp := make([][]int, n+10) @@ -153,10 +147,6 @@ func getMoneyAmount(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0376.Wiggle Subsequence/README.md b/solution/0300-0399/0376.Wiggle Subsequence/README.md index 7a059e4cae100..d0785ecff716f 100644 --- a/solution/0300-0399/0376.Wiggle Subsequence/README.md +++ b/solution/0300-0399/0376.Wiggle Subsequence/README.md @@ -60,25 +60,10 @@ ## 解法 - - -动态规划。 - -设 up 表示以前 i 个元素中的某一个元素结尾的最长上升摆动序列的长度,down 表示以前 i 个元素中的某一个元素结尾的最长下降摆动序列的长度。初始 `up = 1`, `down = 1`。 - -从数组下标 1 开始遍历: - -- 若 `nums[i] > nums[i - 1]`,则需要更新最长上升摆动序列的长度:`up = max(up, down + 1)` -- 若 `nums[i] < nums[i - 1]`,则需要更新最长下降摆动序列的长度:`down = max(down, up + 1)` - -最后返回 `max(up, down)` 即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: @@ -91,10 +76,6 @@ class Solution: return max(up, down) ``` -### **Java** - - - ```java class Solution { public int wiggleMaxLength(int[] nums) { @@ -111,27 +92,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function wiggleMaxLength(nums: number[]): number { - let up = 1, - down = 1; - for (let i = 1; i < nums.length; ++i) { - let prev = nums[i - 1], - cur = nums[i]; - if (cur > prev) { - up = Math.max(up, down + 1); - } else if (cur < prev) { - down = Math.max(down, up + 1); - } - } - return Math.max(up, down); -} -``` - -### **C++** - ```cpp class Solution { public: @@ -149,8 +109,6 @@ public: }; ``` -### **Go** - ```go func wiggleMaxLength(nums []int) int { up, down := 1, 1 @@ -165,10 +123,23 @@ func wiggleMaxLength(nums []int) int { } ``` -### **...** - -``` - +```ts +function wiggleMaxLength(nums: number[]): number { + let up = 1, + down = 1; + for (let i = 1; i < nums.length; ++i) { + let prev = nums[i - 1], + cur = nums[i]; + if (cur > prev) { + up = Math.max(up, down + 1); + } else if (cur < prev) { + down = Math.max(down, up + 1); + } + } + return Math.max(up, down); +} ``` + + diff --git a/solution/0300-0399/0376.Wiggle Subsequence/README_EN.md b/solution/0300-0399/0376.Wiggle Subsequence/README_EN.md index aebaca0f2bc23..9b2028225106e 100644 --- a/solution/0300-0399/0376.Wiggle Subsequence/README_EN.md +++ b/solution/0300-0399/0376.Wiggle Subsequence/README_EN.md @@ -53,12 +53,10 @@ One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8). ## Solutions -Dynamic programming. +### Solution 1 -### **Python3** - ```python class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: @@ -71,8 +69,6 @@ class Solution: return max(up, down) ``` -### **Java** - ```java class Solution { public int wiggleMaxLength(int[] nums) { @@ -89,27 +85,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function wiggleMaxLength(nums: number[]): number { - let up = 1, - down = 1; - for (let i = 1; i < nums.length; ++i) { - let prev = nums[i - 1], - cur = nums[i]; - if (cur > prev) { - up = Math.max(up, down + 1); - } else if (cur < prev) { - down = Math.max(down, up + 1); - } - } - return Math.max(up, down); -} -``` - -### **C++** - ```cpp class Solution { public: @@ -127,8 +102,6 @@ public: }; ``` -### **Go** - ```go func wiggleMaxLength(nums []int) int { up, down := 1, 1 @@ -143,10 +116,23 @@ func wiggleMaxLength(nums []int) int { } ``` -### **...** - -``` - +```ts +function wiggleMaxLength(nums: number[]): number { + let up = 1, + down = 1; + for (let i = 1; i < nums.length; ++i) { + let prev = nums[i - 1], + cur = nums[i]; + if (cur > prev) { + up = Math.max(up, down + 1); + } else if (cur < prev) { + down = Math.max(down, up + 1); + } + } + return Math.max(up, down); +} ``` + + diff --git a/solution/0300-0399/0377.Combination Sum IV/README.md b/solution/0300-0399/0377.Combination Sum IV/README.md index 67f401740bc51..bbfaccd42d321 100644 --- a/solution/0300-0399/0377.Combination Sum IV/README.md +++ b/solution/0300-0399/0377.Combination Sum IV/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示总和为 $i$ 的元素组合的个数,初始时 $f[0] = 1$,其余 $f[i] = 0$。最终答案即为 $f[target]$。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: @@ -82,10 +76,6 @@ class Solution: return f[target] ``` -### **Java** - - - ```java class Solution { public int combinationSum4(int[] nums, int target) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func combinationSum4(nums []int, target int) int { f := make([]int, target+1) @@ -141,16 +127,9 @@ func combinationSum4(nums []int, target int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} target - * @return {number} - */ -var combinationSum4 = function (nums, target) { - const f = new Array(target + 1).fill(0); +```ts +function combinationSum4(nums: number[], target: number): number { + const f: number[] = new Array(target + 1).fill(0); f[0] = 1; for (let i = 1; i <= target; ++i) { for (const x of nums) { @@ -160,14 +139,17 @@ var combinationSum4 = function (nums, target) { } } return f[target]; -}; +} ``` -### **TypeScript** - -```ts -function combinationSum4(nums: number[], target: number): number { - const f: number[] = new Array(target + 1).fill(0); +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var combinationSum4 = function (nums, target) { + const f = new Array(target + 1).fill(0); f[0] = 1; for (let i = 1; i <= target; ++i) { for (const x of nums) { @@ -177,11 +159,9 @@ function combinationSum4(nums: number[], target: number): number { } } return f[target]; -} +}; ``` -### **C#** - ```cs public class Solution { public int CombinationSum4(int[] nums, int target) { @@ -199,10 +179,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0377.Combination Sum IV/README_EN.md b/solution/0300-0399/0377.Combination Sum IV/README_EN.md index a5e0d6e7a329f..b4212a821e201 100644 --- a/solution/0300-0399/0377.Combination Sum IV/README_EN.md +++ b/solution/0300-0399/0377.Combination Sum IV/README_EN.md @@ -48,14 +48,10 @@ Note that different sequences are counted as different combinations. ## Solutions -Dynamic programming. - -`dp[i]` represents the number of element combinations whose sum is `i`. +### Solution 1 -### **Python3** - ```python class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: @@ -67,8 +63,6 @@ class Solution: return f[target] ``` -### **Java** - ```java class Solution { public int combinationSum4(int[] nums, int target) { @@ -86,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +99,6 @@ public: }; ``` -### **Go** - ```go func combinationSum4(nums []int, target int) int { f := make([]int, target+1) @@ -124,16 +114,9 @@ func combinationSum4(nums []int, target int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} target - * @return {number} - */ -var combinationSum4 = function (nums, target) { - const f = new Array(target + 1).fill(0); +```ts +function combinationSum4(nums: number[], target: number): number { + const f: number[] = new Array(target + 1).fill(0); f[0] = 1; for (let i = 1; i <= target; ++i) { for (const x of nums) { @@ -143,14 +126,17 @@ var combinationSum4 = function (nums, target) { } } return f[target]; -}; +} ``` -### **TypeScript** - -```ts -function combinationSum4(nums: number[], target: number): number { - const f: number[] = new Array(target + 1).fill(0); +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var combinationSum4 = function (nums, target) { + const f = new Array(target + 1).fill(0); f[0] = 1; for (let i = 1; i <= target; ++i) { for (const x of nums) { @@ -160,11 +146,9 @@ function combinationSum4(nums: number[], target: number): number { } } return f[target]; -} +}; ``` -### **C#** - ```cs public class Solution { public int CombinationSum4(int[] nums, int target) { @@ -182,10 +166,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0378.Kth Smallest Element in a Sorted Matrix/README.md b/solution/0300-0399/0378.Kth Smallest Element in a Sorted Matrix/README.md index cc4d5174bfe78..36bdfb2e9c602 100644 --- a/solution/0300-0399/0378.Kth Smallest Element in a Sorted Matrix/README.md +++ b/solution/0300-0399/0378.Kth Smallest Element in a Sorted Matrix/README.md @@ -52,16 +52,10 @@ ## 解法 - - -二分法。 +### 方法一 -### **Python3** - - - ```python class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: @@ -87,10 +81,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int kthSmallest(int[][] matrix, int k) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +147,6 @@ private: }; ``` -### **Go** - ```go func kthSmallest(matrix [][]int, k int) int { n := len(matrix) @@ -191,10 +177,6 @@ func check(matrix [][]int, mid, k, n int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0378.Kth Smallest Element in a Sorted Matrix/README_EN.md b/solution/0300-0399/0378.Kth Smallest Element in a Sorted Matrix/README_EN.md index 601269a245434..b337ca2b932e3 100644 --- a/solution/0300-0399/0378.Kth Smallest Element in a Sorted Matrix/README_EN.md +++ b/solution/0300-0399/0378.Kth Smallest Element in a Sorted Matrix/README_EN.md @@ -47,12 +47,10 @@ ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: @@ -78,8 +76,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { public int kthSmallest(int[][] matrix, int k) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +142,6 @@ private: }; ``` -### **Go** - ```go func kthSmallest(matrix [][]int, k int) int { n := len(matrix) @@ -180,10 +172,6 @@ func check(matrix [][]int, mid, k, n int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0379.Design Phone Directory/README.md b/solution/0300-0399/0379.Design Phone Directory/README.md index 32767e19c48d8..6b21efb886873 100644 --- a/solution/0300-0399/0379.Design Phone Directory/README.md +++ b/solution/0300-0399/0379.Design Phone Directory/README.md @@ -55,14 +55,10 @@ directory.check(2); ## 解法 - +### 方法一 -### **Python3** - - - ```python class PhoneDirectory: def __init__(self, maxNumbers: int): @@ -103,10 +99,6 @@ class PhoneDirectory: # obj.release(number) ``` -### **Java** - - - ```java class PhoneDirectory { @@ -154,10 +146,6 @@ class PhoneDirectory { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0379.Design Phone Directory/README_EN.md b/solution/0300-0399/0379.Design Phone Directory/README_EN.md index 482738c826021..06952e65ac529 100644 --- a/solution/0300-0399/0379.Design Phone Directory/README_EN.md +++ b/solution/0300-0399/0379.Design Phone Directory/README_EN.md @@ -47,9 +47,9 @@ phoneDirectory.check(2); // Number 2 is available again, return true. ## Solutions - +### Solution 1 -### **Python3** + ```python class PhoneDirectory: @@ -91,8 +91,6 @@ class PhoneDirectory: # obj.release(number) ``` -### **Java** - ```java class PhoneDirectory { @@ -140,10 +138,6 @@ class PhoneDirectory { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0380.Insert Delete GetRandom O(1)/README.md b/solution/0300-0399/0380.Insert Delete GetRandom O(1)/README.md index b2eb77d4399c3..dc2e9b04bb3f0 100644 --- a/solution/0300-0399/0380.Insert Delete GetRandom O(1)/README.md +++ b/solution/0300-0399/0380.Insert Delete GetRandom O(1)/README.md @@ -55,9 +55,7 @@ randomizedSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom ## 解法 - - -**方法一:哈希表 + 动态列表** +### 方法一:哈希表 + 动态列表 我们定义一个动态列表 $q$,用于存储集合中的元素,定义一个哈希表 $d$,用于存储每个元素在 $q$ 中的下标。 @@ -71,10 +69,6 @@ randomizedSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom -### **Python3** - - - ```python class RandomizedSet: def __init__(self): @@ -109,10 +103,6 @@ class RandomizedSet: # param_3 = obj.getRandom() ``` -### **Java** - - - ```java class RandomizedSet { private Map d = new HashMap<>(); @@ -157,8 +147,6 @@ class RandomizedSet { */ ``` -### **C++** - ```cpp class RandomizedSet { public: @@ -204,8 +192,6 @@ private: */ ``` -### **Go** - ```go type RandomizedSet struct { d map[int]int @@ -250,8 +236,6 @@ func (this *RandomizedSet) GetRandom() int { */ ``` -### **TypeScript** - ```ts class RandomizedSet { private d: Map = new Map(); @@ -294,8 +278,6 @@ class RandomizedSet { */ ``` -### **Rust** - ```rust use std::collections::HashSet; use rand::Rng; @@ -336,8 +318,6 @@ impl RandomizedSet { */ ``` -### **C#** - ```cs public class RandomizedSet { private Dictionary d = new Dictionary(); @@ -382,10 +362,6 @@ public class RandomizedSet { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0380.Insert Delete GetRandom O(1)/README_EN.md b/solution/0300-0399/0380.Insert Delete GetRandom O(1)/README_EN.md index d73d7a877e9ea..d6415a9516c95 100644 --- a/solution/0300-0399/0380.Insert Delete GetRandom O(1)/README_EN.md +++ b/solution/0300-0399/0380.Insert Delete GetRandom O(1)/README_EN.md @@ -47,7 +47,7 @@ randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() ## Solutions -**Solution 1: Hash Table + Dynamic List** +### Solution 1: Hash Table + Dynamic List We define a dynamic list $q$ to store the elements in the set, and a hash table $d$ to store the index of each element in $q$. @@ -61,8 +61,6 @@ Time complexity $O(1)$, space complexity $O(n)$, where $n$ is the number of elem -### **Python3** - ```python class RandomizedSet: def __init__(self): @@ -97,8 +95,6 @@ class RandomizedSet: # param_3 = obj.getRandom() ``` -### **Java** - ```java class RandomizedSet { private Map d = new HashMap<>(); @@ -143,8 +139,6 @@ class RandomizedSet { */ ``` -### **C++** - ```cpp class RandomizedSet { public: @@ -190,8 +184,6 @@ private: */ ``` -### **Go** - ```go type RandomizedSet struct { d map[int]int @@ -236,8 +228,6 @@ func (this *RandomizedSet) GetRandom() int { */ ``` -### **TypeScript** - ```ts class RandomizedSet { private d: Map = new Map(); @@ -280,8 +270,6 @@ class RandomizedSet { */ ``` -### **Rust** - ```rust use std::collections::HashSet; use rand::Rng; @@ -322,8 +310,6 @@ impl RandomizedSet { */ ``` -### **C#** - ```cs public class RandomizedSet { private Dictionary d = new Dictionary(); @@ -368,10 +354,6 @@ public class RandomizedSet { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0381.Insert Delete GetRandom O(1) - Duplicates allowed/README.md b/solution/0300-0399/0381.Insert Delete GetRandom O(1) - Duplicates allowed/README.md index 536ed2312ed20..8fdc521bd9ce8 100644 --- a/solution/0300-0399/0381.Insert Delete GetRandom O(1) - Duplicates allowed/README.md +++ b/solution/0300-0399/0381.Insert Delete GetRandom O(1) - Duplicates allowed/README.md @@ -59,20 +59,10 @@ collection.getRandom(); // getRandom 应该返回 1 或 2,两者的可能性 ## 解法 - - -“哈希表 + 动态列表”实现。 - -哈希表存放每个元素的值和对应的下标集合,而动态列表在每个下标位置存放每个元素。由动态列表实现元素的随机返回。 - -注意,在 `remove()` 实现上,将列表的最后一个元素设置到待删元素的位置上,然后删除最后一个元素,这样在删除元素的时候,不需要挪动一大批元素,从而实现 `O(1)` 时间内操作。 +### 方法一 -### **Python3** - - - ```python class RandomizedCollection: def __init__(self): @@ -128,10 +118,6 @@ class RandomizedCollection: # param_3 = obj.getRandom() ``` -### **Java** - - - ```java class RandomizedCollection { private Map> m; @@ -197,10 +183,6 @@ class RandomizedCollection { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0381.Insert Delete GetRandom O(1) - Duplicates allowed/README_EN.md b/solution/0300-0399/0381.Insert Delete GetRandom O(1) - Duplicates allowed/README_EN.md index b139083100a03..612f9b4df8e73 100644 --- a/solution/0300-0399/0381.Insert Delete GetRandom O(1) - Duplicates allowed/README_EN.md +++ b/solution/0300-0399/0381.Insert Delete GetRandom O(1) - Duplicates allowed/README_EN.md @@ -56,9 +56,9 @@ randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equall ## Solutions - +### Solution 1 -### **Python3** + ```python class RandomizedCollection: @@ -115,8 +115,6 @@ class RandomizedCollection: # param_3 = obj.getRandom() ``` -### **Java** - ```java class RandomizedCollection { private Map> m; @@ -182,10 +180,6 @@ class RandomizedCollection { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0382.Linked List Random Node/README.md b/solution/0300-0399/0382.Linked List Random Node/README.md index d0920e799bb88..52d81a59c6166 100644 --- a/solution/0300-0399/0382.Linked List Random Node/README.md +++ b/solution/0300-0399/0382.Linked List Random Node/README.md @@ -56,24 +56,10 @@ solution.getRandom(); // 返回 3 ## 解法 - - -蓄水池抽样问题。即从一个包含 n 个对象的列表 S 中随机选取 k 个对象,n 为一个非常大或者不知道的值。通常情况下,n 是一个非常大的值,大到无法一次性把所有列表 S 中的对象都放到内存中。我们这个问题是蓄水池抽样问题的一个特例,即 k=1。 - -**解法**:我们总是选择第一个对象,以 1/2 的概率选择第二个,以 1/3 的概率选择第三个,以此类推,以 1/m 的概率选择第 m 个对象。当该过程结束时,每一个对象具有相同的选中概率,即 1/n。 - -**证明**:第 m 个对象最终被选中的概率 P = `选择 m 的概率 × 其后面所有对象不被选择的概率`,即: - - - -思路同:[398. 随机数索引](/solution/0300-0399/0398.Random%20Pick%20Index/README.md) +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -101,10 +87,6 @@ class Solution: # param_1 = obj.getRandom() ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -144,8 +126,6 @@ class Solution { */ ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -183,8 +163,6 @@ public: */ ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -220,10 +198,6 @@ func (this *Solution) GetRandom() int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0382.Linked List Random Node/README_EN.md b/solution/0300-0399/0382.Linked List Random Node/README_EN.md index 28bb57eb81a71..a39bd824c6005 100644 --- a/solution/0300-0399/0382.Linked List Random Node/README_EN.md +++ b/solution/0300-0399/0382.Linked List Random Node/README_EN.md @@ -53,9 +53,9 @@ solution.getRandom(); // return 3 ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -84,8 +84,6 @@ class Solution: # param_1 = obj.getRandom() ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -125,8 +123,6 @@ class Solution { */ ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -164,8 +160,6 @@ public: */ ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -201,10 +195,6 @@ func (this *Solution) GetRandom() int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0383.Ransom Note/README.md b/solution/0300-0399/0383.Ransom Note/README.md index 44cabea0cfd21..e36002ad59ae5 100644 --- a/solution/0300-0399/0383.Ransom Note/README.md +++ b/solution/0300-0399/0383.Ransom Note/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:哈希表或数组** +### 方法一:哈希表或数组 我们可以用一个哈希表或长度为 $26$ 的数组 $cnt$ 记录字符串 `magazine` 中所有字符出现的次数。然后遍历字符串 `ransomNote`,对于其中的每个字符 $c$,我们将其从 $cnt$ 的次数减 $1$,如果减 $1$ 之后的次数小于 $0$,说明 $c$ 在 `magazine` 中出现的次数不够,因此无法构成 `ransomNote`,返回 $false$ 即可。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: @@ -73,10 +67,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean canConstruct(String ransomNote, String magazine) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func canConstruct(ransomNote string, magazine string) bool { cnt := [26]int{} @@ -132,8 +118,6 @@ func canConstruct(ransomNote string, magazine string) bool { } ``` -### **TypeScript** - ```ts function canConstruct(ransomNote: string, magazine: string): boolean { const cnt: number[] = Array(26).fill(0); @@ -149,8 +133,6 @@ function canConstruct(ransomNote: string, magazine: string): boolean { } ``` -### **C#** - ```cs public class Solution { public bool CanConstruct(string ransomNote, string magazine) { @@ -168,8 +150,6 @@ public class Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -194,10 +174,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0383.Ransom Note/README_EN.md b/solution/0300-0399/0383.Ransom Note/README_EN.md index e3a3698e4ef77..7ebeecec35405 100644 --- a/solution/0300-0399/0383.Ransom Note/README_EN.md +++ b/solution/0300-0399/0383.Ransom Note/README_EN.md @@ -29,7 +29,7 @@ ## Solutions -**Solution 1: Hash Table or Array** +### Solution 1: Hash Table or Array We can use a hash table or an array $cnt$ of length $26$ to record the number of times each character appears in the string `magazine`. Then traverse the string `ransomNote`, for each character $c$ in it, we decrease the number of $c$ by $1$ in $cnt$. If the number of $c$ is less than $0$ after the decrease, it means that the number of $c$ in `magazine` is not enough, so it cannot be composed of `ransomNote`, just return $false$. @@ -39,8 +39,6 @@ The time complexity is $O(m + n)$, and the space complexity is $O(C)$. Where $m$ -### **Python3** - ```python class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: @@ -52,8 +50,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean canConstruct(String ransomNote, String magazine) { @@ -71,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +85,6 @@ public: }; ``` -### **Go** - ```go func canConstruct(ransomNote string, magazine string) bool { cnt := [26]int{} @@ -109,8 +101,6 @@ func canConstruct(ransomNote string, magazine string) bool { } ``` -### **TypeScript** - ```ts function canConstruct(ransomNote: string, magazine: string): boolean { const cnt: number[] = Array(26).fill(0); @@ -126,8 +116,6 @@ function canConstruct(ransomNote: string, magazine: string): boolean { } ``` -### **C#** - ```cs public class Solution { public bool CanConstruct(string ransomNote, string magazine) { @@ -145,8 +133,6 @@ public class Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -171,10 +157,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0384.Shuffle an Array/README.md b/solution/0300-0399/0384.Shuffle an Array/README.md index 5f649b7cf28fb..77147f24f99f2 100644 --- a/solution/0300-0399/0384.Shuffle an Array/README.md +++ b/solution/0300-0399/0384.Shuffle an Array/README.md @@ -47,14 +47,10 @@ solution.shuffle(); // 随机返回数组 [1, 2, 3] 打乱后的结果。例 ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def __init__(self, nums: List[int]): @@ -78,10 +74,6 @@ class Solution: # param_2 = obj.shuffle() ``` -### **Java** - - - ```java class Solution { private int[] nums; @@ -121,8 +113,6 @@ class Solution { */ ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +147,6 @@ public: */ ``` -### **Go** - ```go type Solution struct { nums, original []int @@ -190,49 +178,6 @@ func (this *Solution) Shuffle() []int { */ ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - */ -const Solution = function (nums) { - this.nums = nums || []; -}; - -/** - * Resets the array to its original configuration and return it. - * @return {number[]} - */ -Solution.prototype.reset = function () { - return this.nums; -}; - -/** - * Returns a random shuffling of the array. - * @return {number[]} - */ -Solution.prototype.shuffle = function () { - let a = this.nums.slice(); - for (let i = 0; i < a.length; i++) { - let rand = Math.floor(Math.random() * (a.length - i)) + i; - let tmp = a[i]; - a[i] = a[rand]; - a[rand] = tmp; - } - return a; -}; - -/** - * Your Solution object will be instantiated and called as such: - * var obj = Object.create(Solution).createNew(nums) - * var param_1 = obj.reset() - * var param_2 = obj.shuffle() - */ -``` - -### **TypeScript** - ```ts class Solution { private nums: number[]; @@ -264,8 +209,6 @@ class Solution { */ ``` -### **Rust** - ```rust use rand::Rng; struct Solution { @@ -302,10 +245,45 @@ impl Solution { */ ``` -### **...** +```js +/** + * @param {number[]} nums + */ +const Solution = function (nums) { + this.nums = nums || []; +}; -``` +/** + * Resets the array to its original configuration and return it. + * @return {number[]} + */ +Solution.prototype.reset = function () { + return this.nums; +}; + +/** + * Returns a random shuffling of the array. + * @return {number[]} + */ +Solution.prototype.shuffle = function () { + let a = this.nums.slice(); + for (let i = 0; i < a.length; i++) { + let rand = Math.floor(Math.random() * (a.length - i)) + i; + let tmp = a[i]; + a[i] = a[rand]; + a[rand] = tmp; + } + return a; +}; +/** + * Your Solution object will be instantiated and called as such: + * var obj = Object.create(Solution).createNew(nums) + * var param_1 = obj.reset() + * var param_2 = obj.shuffle() + */ ``` + + diff --git a/solution/0300-0399/0384.Shuffle an Array/README_EN.md b/solution/0300-0399/0384.Shuffle an Array/README_EN.md index a1e4c7b5b0127..ce6578a9ee3c0 100644 --- a/solution/0300-0399/0384.Shuffle an Array/README_EN.md +++ b/solution/0300-0399/0384.Shuffle an Array/README_EN.md @@ -46,9 +46,9 @@ solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: # param_2 = obj.shuffle() ``` -### **Java** - ```java class Solution { private int[] nums; @@ -114,8 +112,6 @@ class Solution { */ ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +146,6 @@ public: */ ``` -### **Go** - ```go type Solution struct { nums, original []int @@ -183,49 +177,6 @@ func (this *Solution) Shuffle() []int { */ ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - */ -const Solution = function (nums) { - this.nums = nums || []; -}; - -/** - * Resets the array to its original configuration and return it. - * @return {number[]} - */ -Solution.prototype.reset = function () { - return this.nums; -}; - -/** - * Returns a random shuffling of the array. - * @return {number[]} - */ -Solution.prototype.shuffle = function () { - let a = this.nums.slice(); - for (let i = 0; i < a.length; i++) { - let rand = Math.floor(Math.random() * (a.length - i)) + i; - let tmp = a[i]; - a[i] = a[rand]; - a[rand] = tmp; - } - return a; -}; - -/** - * Your Solution object will be instantiated and called as such: - * var obj = Object.create(Solution).createNew(nums) - * var param_1 = obj.reset() - * var param_2 = obj.shuffle() - */ -``` - -### **TypeScript** - ```ts class Solution { private nums: number[]; @@ -257,8 +208,6 @@ class Solution { */ ``` -### **Rust** - ```rust use rand::Rng; struct Solution { @@ -295,10 +244,45 @@ impl Solution { */ ``` -### **...** +```js +/** + * @param {number[]} nums + */ +const Solution = function (nums) { + this.nums = nums || []; +}; -``` +/** + * Resets the array to its original configuration and return it. + * @return {number[]} + */ +Solution.prototype.reset = function () { + return this.nums; +}; + +/** + * Returns a random shuffling of the array. + * @return {number[]} + */ +Solution.prototype.shuffle = function () { + let a = this.nums.slice(); + for (let i = 0; i < a.length; i++) { + let rand = Math.floor(Math.random() * (a.length - i)) + i; + let tmp = a[i]; + a[i] = a[rand]; + a[rand] = tmp; + } + return a; +}; +/** + * Your Solution object will be instantiated and called as such: + * var obj = Object.create(Solution).createNew(nums) + * var param_1 = obj.reset() + * var param_2 = obj.shuffle() + */ ``` + + diff --git a/solution/0300-0399/0385.Mini Parser/README.md b/solution/0300-0399/0385.Mini Parser/README.md index a9d613da2ff84..d56c5c7a5e9b8 100644 --- a/solution/0300-0399/0385.Mini Parser/README.md +++ b/solution/0300-0399/0385.Mini Parser/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们首先判断字符串 $s$ 是否为空或是一个空列表,如果是的话,直接返回一个空的 `NestedInteger` 即可。如果 $s$ 是一个整数,我们直接返回一个包含这个整数的 `NestedInteger`。否则,我们从左到右遍历字符串 $s$,如果当前深度为 $0$,并且遇到了逗号或者字符串 $s$ 的末尾,则我们截取出一个子串并递归调用函数解析该子串,将返回值加入到列表中。否则,如果当前遇到了左括号,我们将深度加 $1$,并继续遍历。如果遇到了右括号,我们将深度减 $1$,继续遍历。 @@ -56,27 +54,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $s$ 的长度。 -**方法二:栈** - -我们可以使用栈来模拟递归的过程。 - -我们首先判断字符串 $s$ 是否是一个整数,如果是,直接返回一个包含这个整数的 `NestedInteger`。否则,我们从左到右遍历字符串 $s$,对于当前遍历到的字符 $c$: - -- 如果 $c$ 是负号,我们将负号标识置为 `true`; -- 如果 $c$ 是数字,我们将数字加入到当前数字 $x$ 中,其中 $x$ 的初始值为 $0$; -- 如果 $c$ 是左括号,我们将一个新的 `NestedInteger` 压入栈中; -- 如果 $c$ 是右括号或者逗号,我们判断当前字符的前一个字符是否是数字,如果是,我们根据负号标识将当前数字 $x$ 加入到栈顶的 `NestedInteger` 中,然后将负号标识置为 `false`,当前数字 $x$ 重置为 $0$。如果 $c$ 是右括号,并且当前栈的大小大于 $1$,我们将栈顶的 `NestedInteger` 出栈,将其加入到栈顶的 `NestedInteger` 中。 - -遍历结束后,返回栈顶的 `NestedInteger` 即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $s$ 的长度。 - -### **Python3** - - - ```python # """ # This is the interface that allows for creating nested lists. @@ -139,6 +118,249 @@ class Solution: return ans ``` +```java +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * public interface NestedInteger { + * // Constructor initializes an empty nested list. + * public NestedInteger(); + * + * // Constructor initializes a single integer. + * public NestedInteger(int value); + * + * // @return true if this NestedInteger holds a single integer, rather than a nested list. + * public boolean isInteger(); + * + * // @return the single integer that this NestedInteger holds, if it holds a single integer + * // Return null if this NestedInteger holds a nested list + * public Integer getInteger(); + * + * // Set this NestedInteger to hold a single integer. + * public void setInteger(int value); + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * public void add(NestedInteger ni); + * + * // @return the nested list that this NestedInteger holds, if it holds a nested list + * // Return empty list if this NestedInteger holds a single integer + * public List getList(); + * } + */ +class Solution { + public NestedInteger deserialize(String s) { + if ("".equals(s) || "[]".equals(s)) { + return new NestedInteger(); + } + if (s.charAt(0) != '[') { + return new NestedInteger(Integer.parseInt(s)); + } + NestedInteger ans = new NestedInteger(); + int depth = 0; + for (int i = 1, j = 1; i < s.length(); ++i) { + if (depth == 0 && (s.charAt(i) == ',' || i == s.length() - 1)) { + ans.add(deserialize(s.substring(j, i))); + j = i + 1; + } else if (s.charAt(i) == '[') { + ++depth; + } else if (s.charAt(i) == ']') { + --depth; + } + } + return ans; + } +} +``` + +```cpp +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * public: + * // Constructor initializes an empty nested list. + * NestedInteger(); + * + * // Constructor initializes a single integer. + * NestedInteger(int value); + * + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * bool isInteger() const; + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * int getInteger() const; + * + * // Set this NestedInteger to hold a single integer. + * void setInteger(int value); + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * void add(const NestedInteger &ni); + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The result is undefined if this NestedInteger holds a single integer + * const vector &getList() const; + * }; + */ +class Solution { +public: + NestedInteger deserialize(string s) { + if (s == "" || s == "[]") { + return NestedInteger(); + } + if (s[0] != '[') { + return NestedInteger(stoi(s)); + } + NestedInteger ans; + int depth = 0; + for (int i = 1, j = 1; i < s.size(); ++i) { + if (depth == 0 && (s[i] == ',' || i == s.size() - 1)) { + ans.add(deserialize(s.substr(j, i - j))); + j = i + 1; + } else if (s[i] == '[') { + ++depth; + } else if (s[i] == ']') { + --depth; + } + } + return ans; + } +}; +``` + +```go +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * type NestedInteger struct { + * } + * + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * func (n NestedInteger) IsInteger() bool {} + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * // So before calling this method, you should have a check + * func (n NestedInteger) GetInteger() int {} + * + * // Set this NestedInteger to hold a single integer. + * func (n *NestedInteger) SetInteger(value int) {} + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * func (n *NestedInteger) Add(elem NestedInteger) {} + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The list length is zero if this NestedInteger holds a single integer + * // You can access NestedInteger's List element directly if you want to modify it + * func (n NestedInteger) GetList() []*NestedInteger {} + */ +func deserialize(s string) *NestedInteger { + ans := &NestedInteger{} + if s == "" || s == "[]" { + return ans + } + if s[0] != '[' { + v, _ := strconv.Atoi(s) + ans.SetInteger(v) + return ans + } + depth := 0 + for i, j := 1, 1; i < len(s); i++ { + if depth == 0 && (s[i] == ',' || i == len(s)-1) { + (*ans).Add(*deserialize(s[j:i])) + j = i + 1 + } else if s[i] == '[' { + depth++ + } else if s[i] == ']' { + depth-- + } + } + return ans +} +``` + +```ts +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * If value is provided, then it holds a single integer + * Otherwise it holds an empty nested list + * constructor(value?: number) { + * ... + * }; + * + * Return true if this NestedInteger holds a single integer, rather than a nested list. + * isInteger(): boolean { + * ... + * }; + * + * Return the single integer that this NestedInteger holds, if it holds a single integer + * Return null if this NestedInteger holds a nested list + * getInteger(): number | null { + * ... + * }; + * + * Set this NestedInteger to hold a single integer equal to value. + * setInteger(value: number) { + * ... + * }; + * + * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. + * add(elem: NestedInteger) { + * ... + * }; + * + * Return the nested list that this NestedInteger holds, + * or an empty list if this NestedInteger holds a single integer + * getList(): NestedInteger[] { + * ... + * }; + * }; + */ + +function deserialize(s: string): NestedInteger { + if (s === '' || s === '[]') { + return new NestedInteger(); + } + if (s[0] !== '[') { + return new NestedInteger(+s); + } + const ans: NestedInteger = new NestedInteger(); + let depth = 0; + for (let i = 1, j = 1; i < s.length; ++i) { + if (depth === 0 && (s[i] === ',' || i === s.length - 1)) { + ans.add(deserialize(s.slice(j, i))); + j = i + 1; + } else if (s[i] === '[') { + ++depth; + } else if (s[i] === ']') { + --depth; + } + } + return ans; +} +``` + + + +### 方法二:栈 + +我们可以使用栈来模拟递归的过程。 + +我们首先判断字符串 $s$ 是否是一个整数,如果是,直接返回一个包含这个整数的 `NestedInteger`。否则,我们从左到右遍历字符串 $s$,对于当前遍历到的字符 $c$: + +- 如果 $c$ 是负号,我们将负号标识置为 `true`; +- 如果 $c$ 是数字,我们将数字加入到当前数字 $x$ 中,其中 $x$ 的初始值为 $0$; +- 如果 $c$ 是左括号,我们将一个新的 `NestedInteger` 压入栈中; +- 如果 $c$ 是右括号或者逗号,我们判断当前字符的前一个字符是否是数字,如果是,我们根据负号标识将当前数字 $x$ 加入到栈顶的 `NestedInteger` 中,然后将负号标识置为 `false`,当前数字 $x$ 重置为 $0$。如果 $c$ 是右括号,并且当前栈的大小大于 $1$,我们将栈顶的 `NestedInteger` 出栈,将其加入到栈顶的 `NestedInteger` 中。 + +遍历结束后,返回栈顶的 `NestedInteger` 即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $s$ 的长度。 + + + ```python # """ # This is the interface that allows for creating nested lists. @@ -206,64 +428,6 @@ class Solution: return stk.pop() ``` -### **Java** - - - -```java -/** - * // This is the interface that allows for creating nested lists. - * // You should not implement it, or speculate about its implementation - * public interface NestedInteger { - * // Constructor initializes an empty nested list. - * public NestedInteger(); - * - * // Constructor initializes a single integer. - * public NestedInteger(int value); - * - * // @return true if this NestedInteger holds a single integer, rather than a nested list. - * public boolean isInteger(); - * - * // @return the single integer that this NestedInteger holds, if it holds a single integer - * // Return null if this NestedInteger holds a nested list - * public Integer getInteger(); - * - * // Set this NestedInteger to hold a single integer. - * public void setInteger(int value); - * - * // Set this NestedInteger to hold a nested list and adds a nested integer to it. - * public void add(NestedInteger ni); - * - * // @return the nested list that this NestedInteger holds, if it holds a nested list - * // Return empty list if this NestedInteger holds a single integer - * public List getList(); - * } - */ -class Solution { - public NestedInteger deserialize(String s) { - if ("".equals(s) || "[]".equals(s)) { - return new NestedInteger(); - } - if (s.charAt(0) != '[') { - return new NestedInteger(Integer.parseInt(s)); - } - NestedInteger ans = new NestedInteger(); - int depth = 0; - for (int i = 1, j = 1; i < s.length(); ++i) { - if (depth == 0 && (s.charAt(i) == ',' || i == s.length() - 1)) { - ans.add(deserialize(s.substring(j, i))); - j = i + 1; - } else if (s.charAt(i) == '[') { - ++depth; - } else if (s.charAt(i) == ']') { - --depth; - } - } - return ans; - } -} -``` - ```java /** * // This is the interface that allows for creating nested lists. @@ -329,64 +493,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * // This is the interface that allows for creating nested lists. - * // You should not implement it, or speculate about its implementation - * class NestedInteger { - * public: - * // Constructor initializes an empty nested list. - * NestedInteger(); - * - * // Constructor initializes a single integer. - * NestedInteger(int value); - * - * // Return true if this NestedInteger holds a single integer, rather than a nested list. - * bool isInteger() const; - * - * // Return the single integer that this NestedInteger holds, if it holds a single integer - * // The result is undefined if this NestedInteger holds a nested list - * int getInteger() const; - * - * // Set this NestedInteger to hold a single integer. - * void setInteger(int value); - * - * // Set this NestedInteger to hold a nested list and adds a nested integer to it. - * void add(const NestedInteger &ni); - * - * // Return the nested list that this NestedInteger holds, if it holds a nested list - * // The result is undefined if this NestedInteger holds a single integer - * const vector &getList() const; - * }; - */ -class Solution { -public: - NestedInteger deserialize(string s) { - if (s == "" || s == "[]") { - return NestedInteger(); - } - if (s[0] != '[') { - return NestedInteger(stoi(s)); - } - NestedInteger ans; - int depth = 0; - for (int i = 1, j = 1; i < s.size(); ++i) { - if (depth == 0 && (s[i] == ',' || i == s.size() - 1)) { - ans.add(deserialize(s.substr(j, i - j))); - j = i + 1; - } else if (s[i] == '[') { - ++depth; - } else if (s[i] == ']') { - --depth; - } - } - return ans; - } -}; -``` - ```cpp /** * // This is the interface that allows for creating nested lists. @@ -454,59 +560,6 @@ public: }; ``` -### **Go** - -```go -/** - * // This is the interface that allows for creating nested lists. - * // You should not implement it, or speculate about its implementation - * type NestedInteger struct { - * } - * - * // Return true if this NestedInteger holds a single integer, rather than a nested list. - * func (n NestedInteger) IsInteger() bool {} - * - * // Return the single integer that this NestedInteger holds, if it holds a single integer - * // The result is undefined if this NestedInteger holds a nested list - * // So before calling this method, you should have a check - * func (n NestedInteger) GetInteger() int {} - * - * // Set this NestedInteger to hold a single integer. - * func (n *NestedInteger) SetInteger(value int) {} - * - * // Set this NestedInteger to hold a nested list and adds a nested integer to it. - * func (n *NestedInteger) Add(elem NestedInteger) {} - * - * // Return the nested list that this NestedInteger holds, if it holds a nested list - * // The list length is zero if this NestedInteger holds a single integer - * // You can access NestedInteger's List element directly if you want to modify it - * func (n NestedInteger) GetList() []*NestedInteger {} - */ -func deserialize(s string) *NestedInteger { - ans := &NestedInteger{} - if s == "" || s == "[]" { - return ans - } - if s[0] != '[' { - v, _ := strconv.Atoi(s) - ans.SetInteger(v) - return ans - } - depth := 0 - for i, j := 1, 1; i < len(s); i++ { - if depth == 0 && (s[i] == ',' || i == len(s)-1) { - (*ans).Add(*deserialize(s[j:i])) - j = i + 1 - } else if s[i] == '[' { - depth++ - } else if s[i] == ']' { - depth-- - } - } - return ans -} -``` - ```go /** * // This is the interface that allows for creating nested lists. @@ -572,71 +625,6 @@ func deserialize(s string) *NestedInteger { } ``` -### **TypeScript** - -```ts -/** - * // This is the interface that allows for creating nested lists. - * // You should not implement it, or speculate about its implementation - * class NestedInteger { - * If value is provided, then it holds a single integer - * Otherwise it holds an empty nested list - * constructor(value?: number) { - * ... - * }; - * - * Return true if this NestedInteger holds a single integer, rather than a nested list. - * isInteger(): boolean { - * ... - * }; - * - * Return the single integer that this NestedInteger holds, if it holds a single integer - * Return null if this NestedInteger holds a nested list - * getInteger(): number | null { - * ... - * }; - * - * Set this NestedInteger to hold a single integer equal to value. - * setInteger(value: number) { - * ... - * }; - * - * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. - * add(elem: NestedInteger) { - * ... - * }; - * - * Return the nested list that this NestedInteger holds, - * or an empty list if this NestedInteger holds a single integer - * getList(): NestedInteger[] { - * ... - * }; - * }; - */ - -function deserialize(s: string): NestedInteger { - if (s === '' || s === '[]') { - return new NestedInteger(); - } - if (s[0] !== '[') { - return new NestedInteger(+s); - } - const ans: NestedInteger = new NestedInteger(); - let depth = 0; - for (let i = 1, j = 1; i < s.length; ++i) { - if (depth === 0 && (s[i] === ',' || i === s.length - 1)) { - ans.add(deserialize(s.slice(j, i))); - j = i + 1; - } else if (s[i] === '[') { - ++depth; - } else if (s[i] === ']') { - --depth; - } - } - return ans; -} -``` - ```ts /** * // This is the interface that allows for creating nested lists. @@ -707,10 +695,6 @@ function deserialize(s: string): NestedInteger { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0385.Mini Parser/README_EN.md b/solution/0300-0399/0385.Mini Parser/README_EN.md index 26797965204c3..30ee6563c4811 100644 --- a/solution/0300-0399/0385.Mini Parser/README_EN.md +++ b/solution/0300-0399/0385.Mini Parser/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion We first judge whether the string $s$ is empty or an empty list. If so, simply return an empty `NestedInteger`. If $s$ is an integer, we simply return a `NestedInteger` containing this integer. Otherwise, we traverse the string $s$ from left to right. If the current depth is $0$ and we encounter a comma or the end of the string $s$, we take a substring and recursively call the function to parse the substring and add the return value to the list. Otherwise, if the current encounter is a left parenthesis, we increase the depth by $1$ and continue to traverse. If we encounter a right parenthesis, we decrease the depth by $1$ and continue to traverse. @@ -50,25 +50,8 @@ After the traversal is over, return the answer. The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$. -**Solution 2: Stack** - -We can use a stack to simulate the recursive process. - -We first judge whether the string $s$ is an integer. If so, we simply return a `NestedInteger` containing this integer. Otherwise, we traverse the string $s$ from left to right. For the character $c$ currently traversed: - -- If $c$ is a negative sign, we set the negative sign to `true`; -- If $c$ is a number, we add the number to the current number $x$, where the initial value of $x$ is $0$; -- If $c$ is a left parenthesis, we push a new `NestedInteger` onto the stack; -- If $c$ is a right parenthesis or comma, we judge whether the previous character of the current character is a number. If so, we add the current number $x$ to the top `NestedInteger` of the stack according to the negative sign, and then reset the negative sign to `false` and the current number $x$ to $0$. If $c$ is a right parenthesis and the size of the current stack is greater than $1$, we pop the top `NestedInteger` of the stack and add it to the top `NestedInteger` of the stack. - -After the traversal is over, return the top `NestedInteger` of the stack. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$. - -### **Python3** - ```python # """ # This is the interface that allows for creating nested lists. @@ -131,6 +114,249 @@ class Solution: return ans ``` +```java +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * public interface NestedInteger { + * // Constructor initializes an empty nested list. + * public NestedInteger(); + * + * // Constructor initializes a single integer. + * public NestedInteger(int value); + * + * // @return true if this NestedInteger holds a single integer, rather than a nested list. + * public boolean isInteger(); + * + * // @return the single integer that this NestedInteger holds, if it holds a single integer + * // Return null if this NestedInteger holds a nested list + * public Integer getInteger(); + * + * // Set this NestedInteger to hold a single integer. + * public void setInteger(int value); + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * public void add(NestedInteger ni); + * + * // @return the nested list that this NestedInteger holds, if it holds a nested list + * // Return empty list if this NestedInteger holds a single integer + * public List getList(); + * } + */ +class Solution { + public NestedInteger deserialize(String s) { + if ("".equals(s) || "[]".equals(s)) { + return new NestedInteger(); + } + if (s.charAt(0) != '[') { + return new NestedInteger(Integer.parseInt(s)); + } + NestedInteger ans = new NestedInteger(); + int depth = 0; + for (int i = 1, j = 1; i < s.length(); ++i) { + if (depth == 0 && (s.charAt(i) == ',' || i == s.length() - 1)) { + ans.add(deserialize(s.substring(j, i))); + j = i + 1; + } else if (s.charAt(i) == '[') { + ++depth; + } else if (s.charAt(i) == ']') { + --depth; + } + } + return ans; + } +} +``` + +```cpp +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * public: + * // Constructor initializes an empty nested list. + * NestedInteger(); + * + * // Constructor initializes a single integer. + * NestedInteger(int value); + * + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * bool isInteger() const; + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * int getInteger() const; + * + * // Set this NestedInteger to hold a single integer. + * void setInteger(int value); + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * void add(const NestedInteger &ni); + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The result is undefined if this NestedInteger holds a single integer + * const vector &getList() const; + * }; + */ +class Solution { +public: + NestedInteger deserialize(string s) { + if (s == "" || s == "[]") { + return NestedInteger(); + } + if (s[0] != '[') { + return NestedInteger(stoi(s)); + } + NestedInteger ans; + int depth = 0; + for (int i = 1, j = 1; i < s.size(); ++i) { + if (depth == 0 && (s[i] == ',' || i == s.size() - 1)) { + ans.add(deserialize(s.substr(j, i - j))); + j = i + 1; + } else if (s[i] == '[') { + ++depth; + } else if (s[i] == ']') { + --depth; + } + } + return ans; + } +}; +``` + +```go +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * type NestedInteger struct { + * } + * + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * func (n NestedInteger) IsInteger() bool {} + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * // So before calling this method, you should have a check + * func (n NestedInteger) GetInteger() int {} + * + * // Set this NestedInteger to hold a single integer. + * func (n *NestedInteger) SetInteger(value int) {} + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * func (n *NestedInteger) Add(elem NestedInteger) {} + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The list length is zero if this NestedInteger holds a single integer + * // You can access NestedInteger's List element directly if you want to modify it + * func (n NestedInteger) GetList() []*NestedInteger {} + */ +func deserialize(s string) *NestedInteger { + ans := &NestedInteger{} + if s == "" || s == "[]" { + return ans + } + if s[0] != '[' { + v, _ := strconv.Atoi(s) + ans.SetInteger(v) + return ans + } + depth := 0 + for i, j := 1, 1; i < len(s); i++ { + if depth == 0 && (s[i] == ',' || i == len(s)-1) { + (*ans).Add(*deserialize(s[j:i])) + j = i + 1 + } else if s[i] == '[' { + depth++ + } else if s[i] == ']' { + depth-- + } + } + return ans +} +``` + +```ts +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * If value is provided, then it holds a single integer + * Otherwise it holds an empty nested list + * constructor(value?: number) { + * ... + * }; + * + * Return true if this NestedInteger holds a single integer, rather than a nested list. + * isInteger(): boolean { + * ... + * }; + * + * Return the single integer that this NestedInteger holds, if it holds a single integer + * Return null if this NestedInteger holds a nested list + * getInteger(): number | null { + * ... + * }; + * + * Set this NestedInteger to hold a single integer equal to value. + * setInteger(value: number) { + * ... + * }; + * + * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. + * add(elem: NestedInteger) { + * ... + * }; + * + * Return the nested list that this NestedInteger holds, + * or an empty list if this NestedInteger holds a single integer + * getList(): NestedInteger[] { + * ... + * }; + * }; + */ + +function deserialize(s: string): NestedInteger { + if (s === '' || s === '[]') { + return new NestedInteger(); + } + if (s[0] !== '[') { + return new NestedInteger(+s); + } + const ans: NestedInteger = new NestedInteger(); + let depth = 0; + for (let i = 1, j = 1; i < s.length; ++i) { + if (depth === 0 && (s[i] === ',' || i === s.length - 1)) { + ans.add(deserialize(s.slice(j, i))); + j = i + 1; + } else if (s[i] === '[') { + ++depth; + } else if (s[i] === ']') { + --depth; + } + } + return ans; +} +``` + + + +### Solution 2: Stack + +We can use a stack to simulate the recursive process. + +We first judge whether the string $s$ is an integer. If so, we simply return a `NestedInteger` containing this integer. Otherwise, we traverse the string $s$ from left to right. For the character $c$ currently traversed: + +- If $c$ is a negative sign, we set the negative sign to `true`; +- If $c$ is a number, we add the number to the current number $x$, where the initial value of $x$ is $0$; +- If $c$ is a left parenthesis, we push a new `NestedInteger` onto the stack; +- If $c$ is a right parenthesis or comma, we judge whether the previous character of the current character is a number. If so, we add the current number $x$ to the top `NestedInteger` of the stack according to the negative sign, and then reset the negative sign to `false` and the current number $x$ to $0$. If $c$ is a right parenthesis and the size of the current stack is greater than $1$, we pop the top `NestedInteger` of the stack and add it to the top `NestedInteger` of the stack. + +After the traversal is over, return the top `NestedInteger` of the stack. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the string $s$. + + + ```python # """ # This is the interface that allows for creating nested lists. @@ -198,62 +424,6 @@ class Solution: return stk.pop() ``` -### **Java** - -```java -/** - * // This is the interface that allows for creating nested lists. - * // You should not implement it, or speculate about its implementation - * public interface NestedInteger { - * // Constructor initializes an empty nested list. - * public NestedInteger(); - * - * // Constructor initializes a single integer. - * public NestedInteger(int value); - * - * // @return true if this NestedInteger holds a single integer, rather than a nested list. - * public boolean isInteger(); - * - * // @return the single integer that this NestedInteger holds, if it holds a single integer - * // Return null if this NestedInteger holds a nested list - * public Integer getInteger(); - * - * // Set this NestedInteger to hold a single integer. - * public void setInteger(int value); - * - * // Set this NestedInteger to hold a nested list and adds a nested integer to it. - * public void add(NestedInteger ni); - * - * // @return the nested list that this NestedInteger holds, if it holds a nested list - * // Return empty list if this NestedInteger holds a single integer - * public List getList(); - * } - */ -class Solution { - public NestedInteger deserialize(String s) { - if ("".equals(s) || "[]".equals(s)) { - return new NestedInteger(); - } - if (s.charAt(0) != '[') { - return new NestedInteger(Integer.parseInt(s)); - } - NestedInteger ans = new NestedInteger(); - int depth = 0; - for (int i = 1, j = 1; i < s.length(); ++i) { - if (depth == 0 && (s.charAt(i) == ',' || i == s.length() - 1)) { - ans.add(deserialize(s.substring(j, i))); - j = i + 1; - } else if (s.charAt(i) == '[') { - ++depth; - } else if (s.charAt(i) == ']') { - --depth; - } - } - return ans; - } -} -``` - ```java /** * // This is the interface that allows for creating nested lists. @@ -319,64 +489,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * // This is the interface that allows for creating nested lists. - * // You should not implement it, or speculate about its implementation - * class NestedInteger { - * public: - * // Constructor initializes an empty nested list. - * NestedInteger(); - * - * // Constructor initializes a single integer. - * NestedInteger(int value); - * - * // Return true if this NestedInteger holds a single integer, rather than a nested list. - * bool isInteger() const; - * - * // Return the single integer that this NestedInteger holds, if it holds a single integer - * // The result is undefined if this NestedInteger holds a nested list - * int getInteger() const; - * - * // Set this NestedInteger to hold a single integer. - * void setInteger(int value); - * - * // Set this NestedInteger to hold a nested list and adds a nested integer to it. - * void add(const NestedInteger &ni); - * - * // Return the nested list that this NestedInteger holds, if it holds a nested list - * // The result is undefined if this NestedInteger holds a single integer - * const vector &getList() const; - * }; - */ -class Solution { -public: - NestedInteger deserialize(string s) { - if (s == "" || s == "[]") { - return NestedInteger(); - } - if (s[0] != '[') { - return NestedInteger(stoi(s)); - } - NestedInteger ans; - int depth = 0; - for (int i = 1, j = 1; i < s.size(); ++i) { - if (depth == 0 && (s[i] == ',' || i == s.size() - 1)) { - ans.add(deserialize(s.substr(j, i - j))); - j = i + 1; - } else if (s[i] == '[') { - ++depth; - } else if (s[i] == ']') { - --depth; - } - } - return ans; - } -}; -``` - ```cpp /** * // This is the interface that allows for creating nested lists. @@ -444,59 +556,6 @@ public: }; ``` -### **Go** - -```go -/** - * // This is the interface that allows for creating nested lists. - * // You should not implement it, or speculate about its implementation - * type NestedInteger struct { - * } - * - * // Return true if this NestedInteger holds a single integer, rather than a nested list. - * func (n NestedInteger) IsInteger() bool {} - * - * // Return the single integer that this NestedInteger holds, if it holds a single integer - * // The result is undefined if this NestedInteger holds a nested list - * // So before calling this method, you should have a check - * func (n NestedInteger) GetInteger() int {} - * - * // Set this NestedInteger to hold a single integer. - * func (n *NestedInteger) SetInteger(value int) {} - * - * // Set this NestedInteger to hold a nested list and adds a nested integer to it. - * func (n *NestedInteger) Add(elem NestedInteger) {} - * - * // Return the nested list that this NestedInteger holds, if it holds a nested list - * // The list length is zero if this NestedInteger holds a single integer - * // You can access NestedInteger's List element directly if you want to modify it - * func (n NestedInteger) GetList() []*NestedInteger {} - */ -func deserialize(s string) *NestedInteger { - ans := &NestedInteger{} - if s == "" || s == "[]" { - return ans - } - if s[0] != '[' { - v, _ := strconv.Atoi(s) - ans.SetInteger(v) - return ans - } - depth := 0 - for i, j := 1, 1; i < len(s); i++ { - if depth == 0 && (s[i] == ',' || i == len(s)-1) { - (*ans).Add(*deserialize(s[j:i])) - j = i + 1 - } else if s[i] == '[' { - depth++ - } else if s[i] == ']' { - depth-- - } - } - return ans -} -``` - ```go /** * // This is the interface that allows for creating nested lists. @@ -562,71 +621,6 @@ func deserialize(s string) *NestedInteger { } ``` -### **TypeScript** - -```ts -/** - * // This is the interface that allows for creating nested lists. - * // You should not implement it, or speculate about its implementation - * class NestedInteger { - * If value is provided, then it holds a single integer - * Otherwise it holds an empty nested list - * constructor(value?: number) { - * ... - * }; - * - * Return true if this NestedInteger holds a single integer, rather than a nested list. - * isInteger(): boolean { - * ... - * }; - * - * Return the single integer that this NestedInteger holds, if it holds a single integer - * Return null if this NestedInteger holds a nested list - * getInteger(): number | null { - * ... - * }; - * - * Set this NestedInteger to hold a single integer equal to value. - * setInteger(value: number) { - * ... - * }; - * - * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. - * add(elem: NestedInteger) { - * ... - * }; - * - * Return the nested list that this NestedInteger holds, - * or an empty list if this NestedInteger holds a single integer - * getList(): NestedInteger[] { - * ... - * }; - * }; - */ - -function deserialize(s: string): NestedInteger { - if (s === '' || s === '[]') { - return new NestedInteger(); - } - if (s[0] !== '[') { - return new NestedInteger(+s); - } - const ans: NestedInteger = new NestedInteger(); - let depth = 0; - for (let i = 1, j = 1; i < s.length; ++i) { - if (depth === 0 && (s[i] === ',' || i === s.length - 1)) { - ans.add(deserialize(s.slice(j, i))); - j = i + 1; - } else if (s[i] === '[') { - ++depth; - } else if (s[i] === ']') { - --depth; - } - } - return ans; -} -``` - ```ts /** * // This is the interface that allows for creating nested lists. @@ -697,10 +691,6 @@ function deserialize(s: string): NestedInteger { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0386.Lexicographical Numbers/README.md b/solution/0300-0399/0386.Lexicographical Numbers/README.md index 0fae761c7dcc8..45ec88a34a821 100644 --- a/solution/0300-0399/0386.Lexicographical Numbers/README.md +++ b/solution/0300-0399/0386.Lexicographical Numbers/README.md @@ -36,16 +36,10 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS -### **Python3** - - - ```python class Solution: def lexicalOrder(self, n: int) -> List[int]: @@ -62,10 +56,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List lexicalOrder(int n) { @@ -88,29 +78,6 @@ class Solution { } ``` -```java -class Solution { - public List lexicalOrder(int n) { - List ans = new ArrayList<>(); - int v = 1; - for (int i = 0; i < n; ++i) { - ans.add(v); - if (v * 10 <= n) { - v *= 10; - } else { - while (v % 10 == 9 || v + 1 > n) { - v /= 10; - } - ++v; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -128,28 +95,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector lexicalOrder(int n) { - vector ans; - int v = 1; - for (int i = 0; i < n; ++i) { - ans.push_back(v); - if (v * 10 <= n) - v *= 10; - else { - while (v % 10 == 9 || v + 1 > n) v /= 10; - ++v; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func lexicalOrder(n int) []int { var ans []int @@ -170,27 +115,6 @@ func lexicalOrder(n int) []int { } ``` -```go -func lexicalOrder(n int) []int { - var ans []int - v := 1 - for i := 0; i < n; i++ { - ans = append(ans, v) - if v*10 <= n { - v *= 10 - } else { - for v%10 == 9 || v+1 > n { - v /= 10 - } - v++ - } - } - return ans -} -``` - -### **Rust** - ```rust impl Solution { fn dfs(mut num: i32, n: i32, res: &mut Vec) { @@ -213,8 +137,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -238,10 +160,72 @@ var lexicalOrder = function (n) { }; ``` -### **...** + +### 方法二 + + + +```java +class Solution { + public List lexicalOrder(int n) { + List ans = new ArrayList<>(); + int v = 1; + for (int i = 0; i < n; ++i) { + ans.add(v); + if (v * 10 <= n) { + v *= 10; + } else { + while (v % 10 == 9 || v + 1 > n) { + v /= 10; + } + ++v; + } + } + return ans; + } +} ``` +```cpp +class Solution { +public: + vector lexicalOrder(int n) { + vector ans; + int v = 1; + for (int i = 0; i < n; ++i) { + ans.push_back(v); + if (v * 10 <= n) + v *= 10; + else { + while (v % 10 == 9 || v + 1 > n) v /= 10; + ++v; + } + } + return ans; + } +}; +``` + +```go +func lexicalOrder(n int) []int { + var ans []int + v := 1 + for i := 0; i < n; i++ { + ans = append(ans, v) + if v*10 <= n { + v *= 10 + } else { + for v%10 == 9 || v+1 > n { + v /= 10 + } + v++ + } + } + return ans +} ``` + + diff --git a/solution/0300-0399/0386.Lexicographical Numbers/README_EN.md b/solution/0300-0399/0386.Lexicographical Numbers/README_EN.md index 295e4d86c83fe..3e3a59a55044e 100644 --- a/solution/0300-0399/0386.Lexicographical Numbers/README_EN.md +++ b/solution/0300-0399/0386.Lexicographical Numbers/README_EN.md @@ -25,12 +25,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python class Solution: def lexicalOrder(self, n: int) -> List[int]: @@ -47,24 +45,6 @@ class Solution: return ans ``` -```python -class Solution: - def lexicalOrder(self, n: int) -> List[int]: - v = 1 - ans = [] - for i in range(n): - ans.append(v) - if v * 10 <= n: - v *= 10 - else: - while v % 10 == 9 or v + 1 > n: - v //= 10 - v += 1 - return ans -``` - -### **Java** - ```java class Solution { public List lexicalOrder(int n) { @@ -87,29 +67,6 @@ class Solution { } ``` -```java -class Solution { - public List lexicalOrder(int n) { - List ans = new ArrayList<>(); - int v = 1; - for (int i = 0; i < n; ++i) { - ans.add(v); - if (v * 10 <= n) { - v *= 10; - } else { - while (v % 10 == 9 || v + 1 > n) { - v /= 10; - } - ++v; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -127,28 +84,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector lexicalOrder(int n) { - vector ans; - int v = 1; - for (int i = 0; i < n; ++i) { - ans.push_back(v); - if (v * 10 <= n) - v *= 10; - else { - while (v % 10 == 9 || v + 1 > n) v /= 10; - ++v; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func lexicalOrder(n int) []int { var ans []int @@ -169,27 +104,6 @@ func lexicalOrder(n int) []int { } ``` -```go -func lexicalOrder(n int) []int { - var ans []int - v := 1 - for i := 0; i < n; i++ { - ans = append(ans, v) - if v*10 <= n { - v *= 10 - } else { - for v%10 == 9 || v+1 > n { - v /= 10 - } - v++ - } - } - return ans -} -``` - -### **Rust** - ```rust impl Solution { fn dfs(mut num: i32, n: i32, res: &mut Vec) { @@ -212,8 +126,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -237,10 +149,72 @@ var lexicalOrder = function (n) { }; ``` -### **...** + + +### Solution 2 + + +```java +class Solution { + public List lexicalOrder(int n) { + List ans = new ArrayList<>(); + int v = 1; + for (int i = 0; i < n; ++i) { + ans.add(v); + if (v * 10 <= n) { + v *= 10; + } else { + while (v % 10 == 9 || v + 1 > n) { + v /= 10; + } + ++v; + } + } + return ans; + } +} ``` +```cpp +class Solution { +public: + vector lexicalOrder(int n) { + vector ans; + int v = 1; + for (int i = 0; i < n; ++i) { + ans.push_back(v); + if (v * 10 <= n) + v *= 10; + else { + while (v % 10 == 9 || v + 1 > n) v /= 10; + ++v; + } + } + return ans; + } +}; +``` + +```go +func lexicalOrder(n int) []int { + var ans []int + v := 1 + for i := 0; i < n; i++ { + ans = append(ans, v) + if v*10 <= n { + v *= 10 + } else { + for v%10 == 9 || v+1 > n { + v /= 10 + } + v++ + } + } + return ans +} ``` + + diff --git a/solution/0300-0399/0387.First Unique Character in a String/README.md b/solution/0300-0399/0387.First Unique Character in a String/README.md index 70818329b69fd..0862d74dec0da 100644 --- a/solution/0300-0399/0387.First Unique Character in a String/README.md +++ b/solution/0300-0399/0387.First Unique Character in a String/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:数组或哈希表** +### 方法一:数组或哈希表 我们可以用数组或哈希表 $cnt$ 记录字符串 $s$ 中每个字符出现的次数。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def firstUniqChar(self, s: str) -> int: @@ -70,10 +64,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int firstUniqChar(String s) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func firstUniqChar(s string) int { cnt := [26]int{} @@ -130,7 +116,20 @@ func firstUniqChar(s string) int { } ``` -### **JavaScript** +```ts +function firstUniqChar(s: string): number { + const cnt = new Array(26).fill(0); + for (const c of s) { + cnt[c.charCodeAt(0) - 97]++; + } + for (let i = 0; i < s.length; i++) { + if (cnt[s.charCodeAt(i) - 97] === 1) { + return i; + } + } + return -1; +} +``` ```js /** @@ -151,25 +150,6 @@ var firstUniqChar = function (s) { }; ``` -### **TypeScript** - -```ts -function firstUniqChar(s: string): number { - const cnt = new Array(26).fill(0); - for (const c of s) { - cnt[c.charCodeAt(0) - 97]++; - } - for (let i = 0; i < s.length; i++) { - if (cnt[s.charCodeAt(i) - 97] === 1) { - return i; - } - } - return -1; -} -``` - -### **PHP** - ```php class Solution { /** @@ -190,10 +170,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0387.First Unique Character in a String/README_EN.md b/solution/0300-0399/0387.First Unique Character in a String/README_EN.md index 7f4b6c8ce1837..15147e53414e3 100644 --- a/solution/0300-0399/0387.First Unique Character in a String/README_EN.md +++ b/solution/0300-0399/0387.First Unique Character in a String/README_EN.md @@ -27,9 +27,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -41,8 +41,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int firstUniqChar(String s) { @@ -61,8 +59,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -82,8 +78,6 @@ public: }; ``` -### **Go** - ```go func firstUniqChar(s string) int { cnt := [26]int{} @@ -99,7 +93,20 @@ func firstUniqChar(s string) int { } ``` -### **JavaScript** +```ts +function firstUniqChar(s: string): number { + const cnt = new Array(26).fill(0); + for (const c of s) { + cnt[c.charCodeAt(0) - 97]++; + } + for (let i = 0; i < s.length; i++) { + if (cnt[s.charCodeAt(i) - 97] === 1) { + return i; + } + } + return -1; +} +``` ```js /** @@ -120,25 +127,6 @@ var firstUniqChar = function (s) { }; ``` -### **TypeScript** - -```ts -function firstUniqChar(s: string): number { - const cnt = new Array(26).fill(0); - for (const c of s) { - cnt[c.charCodeAt(0) - 97]++; - } - for (let i = 0; i < s.length; i++) { - if (cnt[s.charCodeAt(i) - 97] === 1) { - return i; - } - } - return -1; -} -``` - -### **PHP** - ```php class Solution { /** @@ -159,10 +147,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0388.Longest Absolute File Path/README.md b/solution/0300-0399/0388.Longest Absolute File Path/README.md index b5d798b6f0f4f..b6d11c057cb0e 100644 --- a/solution/0300-0399/0388.Longest Absolute File Path/README.md +++ b/solution/0300-0399/0388.Longest Absolute File Path/README.md @@ -77,16 +77,10 @@ dir ## 解法 - - -遍历文件系统的时候需要在各个目录间切换,在实际的 Linux 中,有 `pushd` 和 `popd` 命令,本题可以使用栈模拟这一过程 +### 方法一 -### **Python3** - - - ```python class Solution: def lengthLongestPath(self, input: str) -> int: @@ -124,10 +118,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int lengthLongestPath(String input) { @@ -173,51 +163,6 @@ class Solution { } ``` -### **Go** - -```go -func lengthLongestPath(input string) int { - i, n := 0, len(input) - ans := 0 - var stk []int - for i < n { - ident := 0 - for ; input[i] == '\t'; i++ { - ident++ - } - - cur, isFile := 0, false - for ; i < n && input[i] != '\n'; i++ { - cur++ - if input[i] == '.' { - isFile = true - } - } - i++ - - // popd - for len(stk) > 0 && len(stk) > ident { - stk = stk[:len(stk)-1] - } - - if len(stk) > 0 { - cur += stk[len(stk)-1] + 1 - } - - // pushd - if !isFile { - stk = append(stk, cur) - continue - } - - ans = max(ans, cur) - } - return ans -} -``` - -### **C++** - ```cpp class Solution { public: @@ -263,10 +208,47 @@ public: }; ``` -### **...** +```go +func lengthLongestPath(input string) int { + i, n := 0, len(input) + ans := 0 + var stk []int + for i < n { + ident := 0 + for ; input[i] == '\t'; i++ { + ident++ + } -``` + cur, isFile := 0, false + for ; i < n && input[i] != '\n'; i++ { + cur++ + if input[i] == '.' { + isFile = true + } + } + i++ + + // popd + for len(stk) > 0 && len(stk) > ident { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + cur += stk[len(stk)-1] + 1 + } + + // pushd + if !isFile { + stk = append(stk, cur) + continue + } + + ans = max(ans, cur) + } + return ans +} ``` + + diff --git a/solution/0300-0399/0388.Longest Absolute File Path/README_EN.md b/solution/0300-0399/0388.Longest Absolute File Path/README_EN.md index a197ebdf3a5d0..6a85adf956ccb 100644 --- a/solution/0300-0399/0388.Longest Absolute File Path/README_EN.md +++ b/solution/0300-0399/0388.Longest Absolute File Path/README_EN.md @@ -69,9 +69,9 @@ We return 32 since it is the longest absolute path to a file. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -110,8 +110,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int lengthLongestPath(String input) { @@ -157,51 +155,6 @@ class Solution { } ``` -### **Go** - -```go -func lengthLongestPath(input string) int { - i, n := 0, len(input) - ans := 0 - var stk []int - for i < n { - ident := 0 - for ; input[i] == '\t'; i++ { - ident++ - } - - cur, isFile := 0, false - for ; i < n && input[i] != '\n'; i++ { - cur++ - if input[i] == '.' { - isFile = true - } - } - i++ - - // popd - for len(stk) > 0 && len(stk) > ident { - stk = stk[:len(stk)-1] - } - - if len(stk) > 0 { - cur += stk[len(stk)-1] + 1 - } - - // pushd - if !isFile { - stk = append(stk, cur) - continue - } - - ans = max(ans, cur) - } - return ans -} -``` - -### **C++** - ```cpp class Solution { public: @@ -247,10 +200,47 @@ public: }; ``` -### **...** +```go +func lengthLongestPath(input string) int { + i, n := 0, len(input) + ans := 0 + var stk []int + for i < n { + ident := 0 + for ; input[i] == '\t'; i++ { + ident++ + } -``` + cur, isFile := 0, false + for ; i < n && input[i] != '\n'; i++ { + cur++ + if input[i] == '.' { + isFile = true + } + } + i++ + + // popd + for len(stk) > 0 && len(stk) > ident { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + cur += stk[len(stk)-1] + 1 + } + + // pushd + if !isFile { + stk = append(stk, cur) + continue + } + + ans = max(ans, cur) + } + return ans +} ``` + + diff --git a/solution/0300-0399/0389.Find the Difference/README.md b/solution/0300-0399/0389.Find the Difference/README.md index 9da3653d797bf..59f42ba593520 100644 --- a/solution/0300-0399/0389.Find the Difference/README.md +++ b/solution/0300-0399/0389.Find the Difference/README.md @@ -41,26 +41,14 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们可以用一个哈希表或数组 $cnt$ 统计字符串 $s$ 中每个字符出现的次数,再遍历字符串 $t$,对于每个字符,我们在 $cnt$ 中减去一次出现的次数,如果对应次数为负数,则说明该字符在 $t$ 中出现的次数大于在 $s$ 中出现的次数,因此该字符为被添加的字符。 时间复杂度 $O(n)$,空间复杂度 $O(|\Sigma|)$,其中 $n$ 为字符串的长度,而 $\Sigma$ 表示字符集,这里字符集为所有小写字母,所以 $|\Sigma|=26$。 -**方法二:求和** - -我们可以将字符串 $t$ 中每个字符的 ASCII 码的值求和,再减去字符串 $s$ 中每个字符的 ASCII 码的值求和,最后的结果即为被添加的字符的 ASCII 码对应的值。 - -时间复杂度 $O(n)$,其中 $n$ 为字符串的长度,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def findTheDifference(self, s: str, t: str) -> str: @@ -71,18 +59,6 @@ class Solution: return c ``` -```python -class Solution: - def findTheDifference(self, s: str, t: str) -> str: - a = sum(ord(c) for c in s) - b = sum(ord(c) for c in t) - return chr(b - a) -``` - -### **Java** - - - ```java class Solution { public char findTheDifference(String s, String t) { @@ -99,23 +75,6 @@ class Solution { } ``` -```java -class Solution { - public char findTheDifference(String s, String t) { - int ss = 0; - for (int i = 0; i < t.length(); ++i) { - ss += t.charAt(i); - } - for (int i = 0; i < s.length(); ++i) { - ss -= s.charAt(i); - } - return (char) ss; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -134,24 +93,6 @@ public: }; ``` -```cpp -class Solution { -public: - char findTheDifference(string s, string t) { - int a = 0, b = 0; - for (char& c : s) { - a += c; - } - for (char& c : t) { - b += c; - } - return b - a; - } -}; -``` - -### **Go** - ```go func findTheDifference(s, t string) byte { cnt := [26]int{} @@ -168,21 +109,6 @@ func findTheDifference(s, t string) byte { } ``` -```go -func findTheDifference(s string, t string) byte { - ss := 0 - for _, c := range s { - ss -= int(c) - } - for _, c := range t { - ss += int(c) - } - return byte(ss) -} -``` - -### **TypeScript** - ```ts function findTheDifference(s: string, t: string): string { const cnt: number[] = Array(26).fill(0); @@ -200,17 +126,6 @@ function findTheDifference(s: string, t: string): string { } ``` -```ts -function findTheDifference(s: string, t: string): string { - return String.fromCharCode( - [...t].reduce((r, v) => r + v.charCodeAt(0), 0) - - [...s].reduce((r, v) => r + v.charCodeAt(0), 0), - ); -} -``` - -### **Rust** - ```rust impl Solution { pub fn find_the_difference(s: String, t: String) -> char { @@ -236,23 +151,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn find_the_difference(s: String, t: String) -> char { - let mut ans = 0; - for c in s.as_bytes() { - ans ^= c; - } - for c in t.as_bytes() { - ans ^= c; - } - char::from(ans) - } -} -``` - -### **C** - ```c char findTheDifference(char* s, char* t) { int n = strlen(s); @@ -270,6 +168,92 @@ char findTheDifference(char* s, char* t) { } ``` + + +### 方法二:求和 + +我们可以将字符串 $t$ 中每个字符的 ASCII 码的值求和,再减去字符串 $s$ 中每个字符的 ASCII 码的值求和,最后的结果即为被添加的字符的 ASCII 码对应的值。 + +时间复杂度 $O(n)$,其中 $n$ 为字符串的长度,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def findTheDifference(self, s: str, t: str) -> str: + a = sum(ord(c) for c in s) + b = sum(ord(c) for c in t) + return chr(b - a) +``` + +```java +class Solution { + public char findTheDifference(String s, String t) { + int ss = 0; + for (int i = 0; i < t.length(); ++i) { + ss += t.charAt(i); + } + for (int i = 0; i < s.length(); ++i) { + ss -= s.charAt(i); + } + return (char) ss; + } +} +``` + +```cpp +class Solution { +public: + char findTheDifference(string s, string t) { + int a = 0, b = 0; + for (char& c : s) { + a += c; + } + for (char& c : t) { + b += c; + } + return b - a; + } +}; +``` + +```go +func findTheDifference(s string, t string) byte { + ss := 0 + for _, c := range s { + ss -= int(c) + } + for _, c := range t { + ss += int(c) + } + return byte(ss) +} +``` + +```ts +function findTheDifference(s: string, t: string): string { + return String.fromCharCode( + [...t].reduce((r, v) => r + v.charCodeAt(0), 0) - + [...s].reduce((r, v) => r + v.charCodeAt(0), 0), + ); +} +``` + +```rust +impl Solution { + pub fn find_the_difference(s: String, t: String) -> char { + let mut ans = 0; + for c in s.as_bytes() { + ans ^= c; + } + for c in t.as_bytes() { + ans ^= c; + } + char::from(ans) + } +} +``` + ```c char findTheDifference(char* s, char* t) { int n = strlen(s); @@ -283,10 +267,6 @@ char findTheDifference(char* s, char* t) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0389.Find the Difference/README_EN.md b/solution/0300-0399/0389.Find the Difference/README_EN.md index f2b1bbd0751f2..e926f58bc322e 100644 --- a/solution/0300-0399/0389.Find the Difference/README_EN.md +++ b/solution/0300-0399/0389.Find the Difference/README_EN.md @@ -37,22 +37,14 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We can use a hash table or array $cnt$ to count the occurrence of each character in string $s$, then traverse string $t$. For each character, we subtract its occurrence in $cnt$. If the corresponding count is negative, it means that the occurrence of this character in $t$ is greater than in $s$, so this character is the added character. The time complexity is $O(n)$, and the space complexity is $O(|\Sigma|)$, where $n$ is the length of the string, and $\Sigma$ represents the character set. Here the character set is all lowercase letters, so $|\Sigma|=26$. -**Solution 2: Summation** - -We can sum the ASCII values of each character in string $t$, then subtract the sum of the ASCII values of each character in string $s$. The final result is the ASCII value of the added character. - -The time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def findTheDifference(self, s: str, t: str) -> str: @@ -63,16 +55,6 @@ class Solution: return c ``` -```python -class Solution: - def findTheDifference(self, s: str, t: str) -> str: - a = sum(ord(c) for c in s) - b = sum(ord(c) for c in t) - return chr(b - a) -``` - -### **Java** - ```java class Solution { public char findTheDifference(String s, String t) { @@ -89,23 +71,6 @@ class Solution { } ``` -```java -class Solution { - public char findTheDifference(String s, String t) { - int ss = 0; - for (int i = 0; i < t.length(); ++i) { - ss += t.charAt(i); - } - for (int i = 0; i < s.length(); ++i) { - ss -= s.charAt(i); - } - return (char) ss; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -124,24 +89,6 @@ public: }; ``` -```cpp -class Solution { -public: - char findTheDifference(string s, string t) { - int a = 0, b = 0; - for (char& c : s) { - a += c; - } - for (char& c : t) { - b += c; - } - return b - a; - } -}; -``` - -### **Go** - ```go func findTheDifference(s, t string) byte { cnt := [26]int{} @@ -158,21 +105,6 @@ func findTheDifference(s, t string) byte { } ``` -```go -func findTheDifference(s string, t string) byte { - ss := 0 - for _, c := range s { - ss -= int(c) - } - for _, c := range t { - ss += int(c) - } - return byte(ss) -} -``` - -### **TypeScript** - ```ts function findTheDifference(s: string, t: string): string { const cnt: number[] = Array(26).fill(0); @@ -190,17 +122,6 @@ function findTheDifference(s: string, t: string): string { } ``` -```ts -function findTheDifference(s: string, t: string): string { - return String.fromCharCode( - [...t].reduce((r, v) => r + v.charCodeAt(0), 0) - - [...s].reduce((r, v) => r + v.charCodeAt(0), 0), - ); -} -``` - -### **Rust** - ```rust impl Solution { pub fn find_the_difference(s: String, t: String) -> char { @@ -226,23 +147,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn find_the_difference(s: String, t: String) -> char { - let mut ans = 0; - for c in s.as_bytes() { - ans ^= c; - } - for c in t.as_bytes() { - ans ^= c; - } - char::from(ans) - } -} -``` - -### **C** - ```c char findTheDifference(char* s, char* t) { int n = strlen(s); @@ -260,6 +164,92 @@ char findTheDifference(char* s, char* t) { } ``` + + +### Solution 2: Summation + +We can sum the ASCII values of each character in string $t$, then subtract the sum of the ASCII values of each character in string $s$. The final result is the ASCII value of the added character. + +The time complexity is $O(n)$, where $n$ is the length of the string. The space complexity is $O(1)$. + + + +```python +class Solution: + def findTheDifference(self, s: str, t: str) -> str: + a = sum(ord(c) for c in s) + b = sum(ord(c) for c in t) + return chr(b - a) +``` + +```java +class Solution { + public char findTheDifference(String s, String t) { + int ss = 0; + for (int i = 0; i < t.length(); ++i) { + ss += t.charAt(i); + } + for (int i = 0; i < s.length(); ++i) { + ss -= s.charAt(i); + } + return (char) ss; + } +} +``` + +```cpp +class Solution { +public: + char findTheDifference(string s, string t) { + int a = 0, b = 0; + for (char& c : s) { + a += c; + } + for (char& c : t) { + b += c; + } + return b - a; + } +}; +``` + +```go +func findTheDifference(s string, t string) byte { + ss := 0 + for _, c := range s { + ss -= int(c) + } + for _, c := range t { + ss += int(c) + } + return byte(ss) +} +``` + +```ts +function findTheDifference(s: string, t: string): string { + return String.fromCharCode( + [...t].reduce((r, v) => r + v.charCodeAt(0), 0) - + [...s].reduce((r, v) => r + v.charCodeAt(0), 0), + ); +} +``` + +```rust +impl Solution { + pub fn find_the_difference(s: String, t: String) -> char { + let mut ans = 0; + for c in s.as_bytes() { + ans ^= c; + } + for c in t.as_bytes() { + ans ^= c; + } + char::from(ans) + } +} +``` + ```c char findTheDifference(char* s, char* t) { int n = strlen(s); @@ -273,10 +263,6 @@ char findTheDifference(char* s, char* t) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0390.Elimination Game/README.md b/solution/0300-0399/0390.Elimination Game/README.md index 2ae868a5173cd..04227cc5f4314 100644 --- a/solution/0300-0399/0390.Elimination Game/README.md +++ b/solution/0300-0399/0390.Elimination Game/README.md @@ -51,27 +51,10 @@ arr = [6] ## 解法 - - -用 `i` 记录该从左边还是右边进行删除。由于经过每轮删除过后都是一个等差数列,因此我们用 `a1`, `an` 记录首尾元素,`cnt` 记录数列元素个数,`step` 记录元素间的间隔,`step` 初始为 1。 - -- 若从左边删除: - - `a1` 变为 `a1 + step` - - 若 `cnt` 为奇数个,`an` 变为 `an - step`,否则 `an` 不变 -- 若从右边删除: - - `an` 变为 `an - step` - - 若 `cnt` 为奇数个,`a1` 变为 `a1 + step`,否则 `a1` 不变 - -每次经过一轮删除,数列元素个数 `cnt` 变为 `cnt >> 1`,元素间隔 `step` 变为 `step << 1`,`i` 自增 1。 - -当元素个数剩下 1 个时,退出循环,返回 `a1` 即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def lastRemaining(self, n: int) -> int: @@ -92,10 +75,6 @@ class Solution: return a1 ``` -### **Java** - - - ```java class Solution { public int lastRemaining(int n) { @@ -118,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +116,6 @@ public: }; ``` -### **Go** - ```go func lastRemaining(n int) int { a1, an, step := 1, n, 1 @@ -161,10 +136,6 @@ func lastRemaining(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0390.Elimination Game/README_EN.md b/solution/0300-0399/0390.Elimination Game/README_EN.md index fcc6b4f85b3e4..3462e89f68e1c 100644 --- a/solution/0300-0399/0390.Elimination Game/README_EN.md +++ b/solution/0300-0399/0390.Elimination Game/README_EN.md @@ -43,9 +43,9 @@ arr = [6] ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return a1 ``` -### **Java** - ```java class Solution { public int lastRemaining(int n) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func lastRemaining(n int) int { a1, an, step := 1, n, 1 @@ -134,10 +128,6 @@ func lastRemaining(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0391.Perfect Rectangle/README.md b/solution/0300-0399/0391.Perfect Rectangle/README.md index f7e445e2f14fc..fa59e23f33a9c 100644 --- a/solution/0300-0399/0391.Perfect Rectangle/README.md +++ b/solution/0300-0399/0391.Perfect Rectangle/README.md @@ -45,16 +45,10 @@ ## 解法 - - -利用哈希表统计小矩形顶点出现的次数,除了最终大矩形的四个顶点只出现 1 次外,其他顶点的出现次数只有可能是 2 或 4。另外,为了满足条件,小矩形的面积和必须等于大矩形(无重叠) +### 方法一 -### **Python3** - - - ```python class Solution: def isRectangleCover(self, rectangles: List[List[int]]) -> bool: @@ -90,10 +84,6 @@ class Solution: return all(c == 2 or c == 4 for c in cnt.values()) ``` -### **Java** - - - ```java class Solution { public boolean isRectangleCover(int[][] rectangles) { @@ -161,8 +151,6 @@ class Solution { } ``` -### **C++** - ```cpp #include using namespace std; @@ -207,8 +195,6 @@ public: }; ``` -### **Go** - ```go type pair struct { first int @@ -257,10 +243,6 @@ func isRectangleCover(rectangles [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0391.Perfect Rectangle/README_EN.md b/solution/0300-0399/0391.Perfect Rectangle/README_EN.md index 5755426331241..e97adfd7df964 100644 --- a/solution/0300-0399/0391.Perfect Rectangle/README_EN.md +++ b/solution/0300-0399/0391.Perfect Rectangle/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,8 +83,6 @@ class Solution: return all(c == 2 or c == 4 for c in cnt.values()) ``` -### **Java** - ```java class Solution { public boolean isRectangleCover(int[][] rectangles) { @@ -152,8 +150,6 @@ class Solution { } ``` -### **C++** - ```cpp #include using namespace std; @@ -198,8 +194,6 @@ public: }; ``` -### **Go** - ```go type pair struct { first int @@ -248,10 +242,6 @@ func isRectangleCover(rectangles [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0392.Is Subsequence/README.md b/solution/0300-0399/0392.Is Subsequence/README.md index 667180ec012b7..491e9882271ec 100644 --- a/solution/0300-0399/0392.Is Subsequence/README.md +++ b/solution/0300-0399/0392.Is Subsequence/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们定义两个指针 $i$ 和 $j$,分别指向字符串 $s$ 和 $t$ 的初始位置。每次我们比较两个指针指向的字符,如果相同,则两个指针同时右移;如果不同,则只有 $j$ 右移。当指针 $i$ 移动到字符串 $s$ 的末尾时,说明 $s$ 是 $t$ 的子序列。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def isSubsequence(self, s: str, t: str) -> bool: @@ -71,10 +65,6 @@ class Solution: return i == len(s) ``` -### **Java** - - - ```java class Solution { public boolean isSubsequence(String s, String t) { @@ -91,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +97,6 @@ public: }; ``` -### **Go** - ```go func isSubsequence(s string, t string) bool { i, j, m, n := 0, 0, len(s), len(t) @@ -124,8 +110,6 @@ func isSubsequence(s string, t string) bool { } ``` -### **TypeScript** - ```ts function isSubsequence(s: string, t: string): boolean { const m = s.length; @@ -140,8 +124,6 @@ function isSubsequence(s: string, t: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_subsequence(s: String, t: String) -> bool { @@ -162,24 +144,6 @@ impl Solution { } ``` -### **C** - -```c -bool isSubsequence(char* s, char* t) { - int m = strlen(s); - int n = strlen(t); - int i = 0; - for (int j = 0; i < m && j < n; ++j) { - if (s[i] == t[j]) { - ++i; - } - } - return i == m; -} -``` - -### **C#** - ```cs public class Solution { public bool IsSubsequence(string s, string t) { @@ -195,10 +159,20 @@ public class Solution { } ``` -### **...** - -``` - +```c +bool isSubsequence(char* s, char* t) { + int m = strlen(s); + int n = strlen(t); + int i = 0; + for (int j = 0; i < m && j < n; ++j) { + if (s[i] == t[j]) { + ++i; + } + } + return i == m; +} ``` + + diff --git a/solution/0300-0399/0392.Is Subsequence/README_EN.md b/solution/0300-0399/0392.Is Subsequence/README_EN.md index b638dda6cc580..4bfaa31832ea1 100644 --- a/solution/0300-0399/0392.Is Subsequence/README_EN.md +++ b/solution/0300-0399/0392.Is Subsequence/README_EN.md @@ -30,7 +30,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We define two pointers $i$ and $j$ to point to the initial position of the string $s$ and $t$ respectively. Each time we compare the two characters pointed to by the two pointers, if they are the same, both pointers move right at the same time; if they are not the same, only $j$ moves right. When the pointer $i$ moves to the end of the string $s$, it means that $s$ is the subsequence of $t$. @@ -38,8 +38,6 @@ The time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the stri -### **Python3** - ```python class Solution: def isSubsequence(self, s: str, t: str) -> bool: @@ -51,8 +49,6 @@ class Solution: return i == len(s) ``` -### **Java** - ```java class Solution { public boolean isSubsequence(String s, String t) { @@ -69,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +81,6 @@ public: }; ``` -### **Go** - ```go func isSubsequence(s string, t string) bool { i, j, m, n := 0, 0, len(s), len(t) @@ -102,8 +94,6 @@ func isSubsequence(s string, t string) bool { } ``` -### **TypeScript** - ```ts function isSubsequence(s: string, t: string): boolean { const m = s.length; @@ -118,8 +108,6 @@ function isSubsequence(s: string, t: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_subsequence(s: String, t: String) -> bool { @@ -140,24 +128,6 @@ impl Solution { } ``` -### **C** - -```c -bool isSubsequence(char* s, char* t) { - int m = strlen(s); - int n = strlen(t); - int i = 0; - for (int j = 0; i < m && j < n; ++j) { - if (s[i] == t[j]) { - ++i; - } - } - return i == m; -} -``` - -### **C#** - ```cs public class Solution { public bool IsSubsequence(string s, string t) { @@ -173,10 +143,20 @@ public class Solution { } ``` -### **...** - -``` - +```c +bool isSubsequence(char* s, char* t) { + int m = strlen(s); + int n = strlen(t); + int i = 0; + for (int j = 0; i < m && j < n; ++j) { + if (s[i] == t[j]) { + ++i; + } + } + return i == m; +} ``` + + diff --git a/solution/0300-0399/0393.UTF-8 Validation/README.md b/solution/0300-0399/0393.UTF-8 Validation/README.md index 07f5358ef1b3e..68cd295fb5528 100644 --- a/solution/0300-0399/0393.UTF-8 Validation/README.md +++ b/solution/0300-0399/0393.UTF-8 Validation/README.md @@ -64,14 +64,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def validUtf8(self, data: List[int]) -> bool: @@ -94,10 +90,6 @@ class Solution: return n == 0 ``` -### **Java** - - - ```java class Solution { public boolean validUtf8(int[] data) { @@ -125,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +142,6 @@ public: }; ``` -### **Go** - ```go func validUtf8(data []int) bool { n := 0 @@ -179,10 +167,6 @@ func validUtf8(data []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0393.UTF-8 Validation/README_EN.md b/solution/0300-0399/0393.UTF-8 Validation/README_EN.md index 1a50c9b6b46e3..ccc3715470455 100644 --- a/solution/0300-0399/0393.UTF-8 Validation/README_EN.md +++ b/solution/0300-0399/0393.UTF-8 Validation/README_EN.md @@ -60,9 +60,9 @@ But the second continuation byte does not start with 10, so it is invalid. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -86,8 +86,6 @@ class Solution: return n == 0 ``` -### **Java** - ```java class Solution { public boolean validUtf8(int[] data) { @@ -115,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +138,6 @@ public: }; ``` -### **Go** - ```go func validUtf8(data []int) bool { n := 0 @@ -169,10 +163,6 @@ func validUtf8(data []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0394.Decode String/README.md b/solution/0300-0399/0394.Decode String/README.md index 349ea567390f6..7e9e15982b036 100644 --- a/solution/0300-0399/0394.Decode String/README.md +++ b/solution/0300-0399/0394.Decode String/README.md @@ -57,25 +57,10 @@ ## 解法 - - -用栈 s1 存储左括号前的数字 num,栈 s2 存储左括号前的字符串 res。 - -遍历字符串 s 中每个字符 c: - -- 若 c 是数字,则累乘数字 num -- 若 `c == '['`,则将左括号前的数字 num 存入 s1,左括号前的字符串 res 存入 s2,并将 num 重新置为 0,res 置为空串 -- 若 `c == ']'`,则 `res = s2.pop() + res * s1.pop()` -- 若 c 是字符,则累加字符串 res - -最后返回 res 即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def decodeString(self, s: str) -> str: @@ -95,10 +80,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public String decodeString(String s) { @@ -129,8 +110,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function decodeString(s: string): string { let ans = ''; @@ -156,10 +135,6 @@ function decodeString(s: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0394.Decode String/README_EN.md b/solution/0300-0399/0394.Decode String/README_EN.md index 9d36e2d6e9109..1a98ebac40a2e 100644 --- a/solution/0300-0399/0394.Decode String/README_EN.md +++ b/solution/0300-0399/0394.Decode String/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public String decodeString(String s) { @@ -101,8 +99,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function decodeString(s: string): string { let ans = ''; @@ -128,10 +124,6 @@ function decodeString(s: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0395.Longest Substring with At Least K Repeating Characters/README.md b/solution/0300-0399/0395.Longest Substring with At Least K Repeating Characters/README.md index 2c91fbf7623ad..9402d47cd1da5 100644 --- a/solution/0300-0399/0395.Longest Substring with At Least K Repeating Characters/README.md +++ b/solution/0300-0399/0395.Longest Substring with At Least K Repeating Characters/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:分治** +### 方法一:分治 对于字符串 $s$,如果存在某个字符 $c$,其出现次数小于 $k$,则任何包含 $c$ 的子串都不可能满足题目要求。因此我们可以将 $s$ 按照每个不满足条件的字符 $c$ 进行分割,分割得到的每个子串都是原字符串的一个「子问题」,我们可以递归地求解每个子问题,最终的答案即为所有子问题的最大值。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def longestSubstring(self, s: str, k: int) -> int: @@ -79,10 +73,6 @@ class Solution: return dfs(0, len(s) - 1) ``` -### **Java** - - - ```java class Solution { private String s; @@ -131,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +164,6 @@ public: }; ``` -### **Go** - ```go func longestSubstring(s string, k int) int { var dfs func(l, r int) int @@ -219,10 +205,6 @@ func longestSubstring(s string, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0395.Longest Substring with At Least K Repeating Characters/README_EN.md b/solution/0300-0399/0395.Longest Substring with At Least K Repeating Characters/README_EN.md index 28a0b13bc4d75..3e0ff93d8abd4 100644 --- a/solution/0300-0399/0395.Longest Substring with At Least K Repeating Characters/README_EN.md +++ b/solution/0300-0399/0395.Longest Substring with At Least K Repeating Characters/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return dfs(0, len(s) - 1) ``` -### **Java** - ```java class Solution { private String s; @@ -116,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +157,6 @@ public: }; ``` -### **Go** - ```go func longestSubstring(s string, k int) int { var dfs func(l, r int) int @@ -204,10 +198,6 @@ func longestSubstring(s string, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0396.Rotate Function/README.md b/solution/0300-0399/0396.Rotate Function/README.md index 2db47ba893ea9..282a5a029bd42 100644 --- a/solution/0300-0399/0396.Rotate Function/README.md +++ b/solution/0300-0399/0396.Rotate Function/README.md @@ -52,21 +52,10 @@ F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 ## 解法 - - -``` -f(0) = 0 * nums[0] + 1 * nums[1] + ... + (n - 1) * nums[n - 1] -f(1) = 1 * nums[0] + 2 * nums[1] + ... + 0 * nums[n - 1] -... -f(k) = f(k - 1) + s - n * nums[n - k] -``` +### 方法一 -### **Python3** - - - ```python class Solution: def maxRotateFunction(self, nums: List[int]) -> int: @@ -79,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxRotateFunction(int[] nums) { @@ -103,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +107,6 @@ public: }; ``` -### **Go** - ```go func maxRotateFunction(nums []int) int { f, s, n := 0, 0, len(nums) @@ -144,8 +125,6 @@ func maxRotateFunction(nums []int) int { } ``` -### **TypeScript** - ```ts function maxRotateFunction(nums: number[]): number { const n = nums.length; @@ -160,8 +139,6 @@ function maxRotateFunction(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_rotate_function(nums: Vec) -> i32 { @@ -184,10 +161,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0396.Rotate Function/README_EN.md b/solution/0300-0399/0396.Rotate Function/README_EN.md index f1e2fc43139be..0287cac98549b 100644 --- a/solution/0300-0399/0396.Rotate Function/README_EN.md +++ b/solution/0300-0399/0396.Rotate Function/README_EN.md @@ -48,9 +48,9 @@ So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxRotateFunction(int[] nums) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +103,6 @@ public: }; ``` -### **Go** - ```go func maxRotateFunction(nums []int) int { f, s, n := 0, 0, len(nums) @@ -127,8 +121,6 @@ func maxRotateFunction(nums []int) int { } ``` -### **TypeScript** - ```ts function maxRotateFunction(nums: number[]): number { const n = nums.length; @@ -143,8 +135,6 @@ function maxRotateFunction(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_rotate_function(nums: Vec) -> i32 { @@ -167,10 +157,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0397.Integer Replacement/README.md b/solution/0300-0399/0397.Integer Replacement/README.md index 62fd8aafd4be7..b8bb92c267784 100644 --- a/solution/0300-0399/0397.Integer Replacement/README.md +++ b/solution/0300-0399/0397.Integer Replacement/README.md @@ -51,16 +51,10 @@ ## 解法 - - -偶数直接除以 2,对于奇数,若二进制形式如 `0bxxx11`,并且不为 3,则进行加 1,否则进行减 1。 +### 方法一 -### **Python3** - - - ```python class Solution: def integerReplacement(self, n: int) -> int: @@ -76,10 +70,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int integerReplacement(int n) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func integerReplacement(n int) int { ans := 0 @@ -140,10 +126,6 @@ func integerReplacement(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0397.Integer Replacement/README_EN.md b/solution/0300-0399/0397.Integer Replacement/README_EN.md index 340e40df56b7a..db0bd123386ca 100644 --- a/solution/0300-0399/0397.Integer Replacement/README_EN.md +++ b/solution/0300-0399/0397.Integer Replacement/README_EN.md @@ -47,9 +47,9 @@ or 7 -> 6 -> 3 -> 2 -> 1 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int integerReplacement(int n) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +105,6 @@ public: }; ``` -### **Go** - ```go func integerReplacement(n int) int { ans := 0 @@ -128,10 +122,6 @@ func integerReplacement(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0398.Random Pick Index/README.md b/solution/0300-0399/0398.Random Pick Index/README.md index fb551fde3d49e..f6113d3316b1d 100644 --- a/solution/0300-0399/0398.Random Pick Index/README.md +++ b/solution/0300-0399/0398.Random Pick Index/README.md @@ -54,24 +54,10 @@ solution.pick(3); // 随机返回索引 2, 3 或者 4 之一。每个索引的 ## 解法 - - -蓄水池抽样问题。即从一个包含 n 个对象的列表 S 中随机选取 k 个对象,n 为一个非常大或者不知道的值。通常情况下,n 是一个非常大的值,大到无法一次性把所有列表 S 中的对象都放到内存中。我们这个问题是蓄水池抽样问题的一个特例,即 k=1。 - -**解法**:我们总是选择第一个对象,以 1/2 的概率选择第二个,以 1/3 的概率选择第三个,以此类推,以 1/m 的概率选择第 m 个对象。当该过程结束时,每一个对象具有相同的选中概率,即 1/n。 - -**证明**:第 m 个对象最终被选中的概率 P = `选择 m 的概率 × 其后面所有对象不被选择的概率`,即: - - - -思路同:[382. 链表随机节点](/solution/0300-0399/0382.Linked%20List%20Random%20Node/README.md) +### 方法一 -### **Python3** - - - ```python class Solution: def __init__(self, nums: List[int]): @@ -93,10 +79,6 @@ class Solution: # param_1 = obj.pick(target) ``` -### **Java** - - - ```java class Solution { private int[] nums; @@ -128,8 +110,6 @@ class Solution { */ ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +139,6 @@ public: */ ``` -### **Go** - ```go type Solution struct { nums []int @@ -191,10 +169,6 @@ func (this *Solution) Pick(target int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0398.Random Pick Index/README_EN.md b/solution/0300-0399/0398.Random Pick Index/README_EN.md index 07ee58c05c130..92e7d1e2a5b60 100644 --- a/solution/0300-0399/0398.Random Pick Index/README_EN.md +++ b/solution/0300-0399/0398.Random Pick Index/README_EN.md @@ -42,9 +42,9 @@ solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each ind ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: # param_1 = obj.pick(target) ``` -### **Java** - ```java class Solution { private int[] nums; @@ -100,8 +98,6 @@ class Solution { */ ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +127,6 @@ public: */ ``` -### **Go** - ```go type Solution struct { nums []int @@ -163,10 +157,6 @@ func (this *Solution) Pick(target int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0399.Evaluate Division/README.md b/solution/0300-0399/0399.Evaluate Division/README.md index 7c2406bd73c42..69b3ca69a1af7 100644 --- a/solution/0300-0399/0399.Evaluate Division/README.md +++ b/solution/0300-0399/0399.Evaluate Division/README.md @@ -61,81 +61,10 @@ ## 解法 - - -并查集。对于本题,具备等式关系的所有变量构成同一个集合,同时,需要维护一个权重数组 w,初始时 `w[i] = 1`。对于等式关系如 `a / b = 2`,令 `w[a] = 2`。在 `find()` 查找祖宗节点的时候,同时进行路径压缩,并更新节点权重。而在合并节点时,`p[pa] = pb`,同时更新 pa 的权重为 `w[pa] = w[b] * (a / b) / w[a]`。 - -以下是并查集的几个常用模板。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` +### 方法一 -### **Python3** - - - ```python class Solution: def calcEquation( @@ -165,10 +94,6 @@ class Solution: ] ``` -### **Java** - - - ```java class Solution { private Map p; @@ -217,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -261,8 +184,6 @@ public: }; ``` -### **Go** - ```go func calcEquation(equations [][]string, values []float64, queries [][]string) []float64 { p := make(map[string]string) @@ -305,8 +226,6 @@ func calcEquation(equations [][]string, values []float64, queries [][]string) [] } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -394,10 +313,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0300-0399/0399.Evaluate Division/README_EN.md b/solution/0300-0399/0399.Evaluate Division/README_EN.md index 69a035fac1e49..af1e99d20cc72 100644 --- a/solution/0300-0399/0399.Evaluate Division/README_EN.md +++ b/solution/0300-0399/0399.Evaluate Division/README_EN.md @@ -57,12 +57,10 @@ note: x is undefined => -1.0 ## Solutions -Union find. +### Solution 1 -### **Python3** - ```python class Solution: def calcEquation( @@ -92,8 +90,6 @@ class Solution: ] ``` -### **Java** - ```java class Solution { private Map p; @@ -142,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -186,8 +180,6 @@ public: }; ``` -### **Go** - ```go func calcEquation(equations [][]string, values []float64, queries [][]string) []float64 { p := make(map[string]string) @@ -230,8 +222,6 @@ func calcEquation(equations [][]string, values []float64, queries [][]string) [] } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -319,10 +309,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0400.Nth Digit/README.md b/solution/0400-0499/0400.Nth Digit/README.md index 89df80c689d23..89a6985e8bd14 100644 --- a/solution/0400-0499/0400.Nth Digit/README.md +++ b/solution/0400-0499/0400.Nth Digit/README.md @@ -35,9 +35,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 位数为 $k$ 的最小整数和最大整数分别为 $10^{k-1}$ 和 $10^k-1$,因此 $k$ 位数的总位数为 $k \times 9 \times 10^{k-1}$。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def findNthDigit(self, n: int) -> int: @@ -68,10 +62,6 @@ class Solution: return int(str(num)[idx]) ``` -### **Java** - - - ```java class Solution { public int findNthDigit(int n) { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func findNthDigit(n int) int { k, cnt := 1, 9 @@ -123,8 +109,6 @@ func findNthDigit(n int) int { } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -144,8 +128,6 @@ var findNthDigit = function (n) { }; ``` -### **C#** - ```cs public class Solution { public int FindNthDigit(int n) { @@ -162,10 +144,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0400.Nth Digit/README_EN.md b/solution/0400-0499/0400.Nth Digit/README_EN.md index ca395510b3d81..7b2c5dbf986c8 100644 --- a/solution/0400-0499/0400.Nth Digit/README_EN.md +++ b/solution/0400-0499/0400.Nth Digit/README_EN.md @@ -31,27 +31,23 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: def findNthDigit(self, n: int) -> int: - bits, t = 1, 9 - while n > bits * t: - n -= bits * t - bits += 1 - t *= 10 - - start = 10 ** (bits - 1) + (n // bits) - 1 - if n % bits == 0: - return start % 10 - return int(str((start + 1))[(n % bits) - 1]) + k, cnt = 1, 9 + while k * cnt < n: + n -= k * cnt + k += 1 + cnt *= 10 + num = 10 ** (k - 1) + (n - 1) // k + idx = (n - 1) % k + return int(str(num)[idx]) ``` -### **Java** - ```java class Solution { public int findNthDigit(int n) { @@ -68,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +81,6 @@ public: }; ``` -### **Go** - ```go func findNthDigit(n int) int { k, cnt := 1, 9 @@ -103,8 +95,6 @@ func findNthDigit(n int) int { } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -124,8 +114,6 @@ var findNthDigit = function (n) { }; ``` -### **C#** - ```cs public class Solution { public int FindNthDigit(int n) { @@ -142,10 +130,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0401.Binary Watch/README.md b/solution/0400-0499/0401.Binary Watch/README.md index ce0f33b85913e..9a35397769e97 100644 --- a/solution/0400-0499/0401.Binary Watch/README.md +++ b/solution/0400-0499/0401.Binary Watch/README.md @@ -54,24 +54,14 @@ ## 解法 - - -**方法一:枚举组合** +### 方法一:枚举组合 题目可转换为求 i(`i∈[0,12)`) 和 j(`j∈[0,60)`) 所有可能的组合。 合法组合需要满足的条件是:i 的二进制形式中 1 的个数加上 j 的二进制形式中 1 的个数,结果等于 turnedOn。 -**方法二:二进制枚举** - -利用 10 个二进制位表示手表,其中前 4 位代表小时,后 6 位代表分钟。枚举 `[0, 1 << 10)` 的所有数,找出合法的数。 - -### **Python3** - - - ```python class Solution: def readBinaryWatch(self, turnedOn: int) -> List[str]: @@ -83,21 +73,6 @@ class Solution: ] ``` -```python -class Solution: - def readBinaryWatch(self, turnedOn: int) -> List[str]: - ans = [] - for i in range(1 << 10): - h, m = i >> 6, i & 0b111111 - if h < 12 and m < 60 and i.bit_count() == turnedOn: - ans.append('{:d}:{:02d}'.format(h, m)) - return ans -``` - -### **Java** - - - ```java class Solution { public List readBinaryWatch(int turnedOn) { @@ -114,23 +89,6 @@ class Solution { } ``` -```java -class Solution { - public List readBinaryWatch(int turnedOn) { - List ans = new ArrayList<>(); - for (int i = 0; i < 1 << 10; ++i) { - int h = i >> 6, m = i & 0b111111; - if (h < 12 && m < 60 && Integer.bitCount(i) == turnedOn) { - ans.add(String.format("%d:%02d", h, m)); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -148,24 +106,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector readBinaryWatch(int turnedOn) { - vector ans; - for (int i = 0; i < 1 << 10; ++i) { - int h = i >> 6, m = i & 0b111111; - if (h < 12 && m < 60 && __builtin_popcount(i) == turnedOn) { - ans.push_back(to_string(h) + ":" + (m < 10 ? "0" : "") + to_string(m)); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func readBinaryWatch(turnedOn int) []string { var ans []string @@ -180,21 +120,6 @@ func readBinaryWatch(turnedOn int) []string { } ``` -```go -func readBinaryWatch(turnedOn int) []string { - var ans []string - for i := 0; i < 1<<10; i++ { - h, m := i>>6, i&0b111111 - if h < 12 && m < 60 && bits.OnesCount(uint(i)) == turnedOn { - ans = append(ans, fmt.Sprintf("%d:%02d", h, m)) - } - } - return ans -} -``` - -### **TypeScript** - ```ts function readBinaryWatch(turnedOn: number): string[] { if (turnedOn === 0) { @@ -229,8 +154,6 @@ function readBinaryWatch(turnedOn: number): string[] { } ``` -### **Rust** - ```rust impl Solution { fn create_time(bit_arr: &[bool; 10]) -> (i32, i32) { @@ -280,10 +203,69 @@ impl Solution { } ``` -### **...** + + +### 方法二:二进制枚举 + +利用 10 个二进制位表示手表,其中前 4 位代表小时,后 6 位代表分钟。枚举 `[0, 1 << 10)` 的所有数,找出合法的数。 + + + +```python +class Solution: + def readBinaryWatch(self, turnedOn: int) -> List[str]: + ans = [] + for i in range(1 << 10): + h, m = i >> 6, i & 0b111111 + if h < 12 and m < 60 and i.bit_count() == turnedOn: + ans.append('{:d}:{:02d}'.format(h, m)) + return ans +``` + +```java +class Solution { + public List readBinaryWatch(int turnedOn) { + List ans = new ArrayList<>(); + for (int i = 0; i < 1 << 10; ++i) { + int h = i >> 6, m = i & 0b111111; + if (h < 12 && m < 60 && Integer.bitCount(i) == turnedOn) { + ans.add(String.format("%d:%02d", h, m)); + } + } + return ans; + } +} +``` +```cpp +class Solution { +public: + vector readBinaryWatch(int turnedOn) { + vector ans; + for (int i = 0; i < 1 << 10; ++i) { + int h = i >> 6, m = i & 0b111111; + if (h < 12 && m < 60 && __builtin_popcount(i) == turnedOn) { + ans.push_back(to_string(h) + ":" + (m < 10 ? "0" : "") + to_string(m)); + } + } + return ans; + } +}; ``` +```go +func readBinaryWatch(turnedOn int) []string { + var ans []string + for i := 0; i < 1<<10; i++ { + h, m := i>>6, i&0b111111 + if h < 12 && m < 60 && bits.OnesCount(uint(i)) == turnedOn { + ans = append(ans, fmt.Sprintf("%d:%02d", h, m)) + } + } + return ans +} ``` + + diff --git a/solution/0400-0499/0401.Binary Watch/README_EN.md b/solution/0400-0499/0401.Binary Watch/README_EN.md index 61e9f928170ad..1d626b779ae5b 100644 --- a/solution/0400-0499/0401.Binary Watch/README_EN.md +++ b/solution/0400-0499/0401.Binary Watch/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,19 +58,6 @@ class Solution: ] ``` -```python -class Solution: - def readBinaryWatch(self, turnedOn: int) -> List[str]: - ans = [] - for i in range(1 << 10): - h, m = i >> 6, i & 0b111111 - if h < 12 and m < 60 and i.bit_count() == turnedOn: - ans.append('{:d}:{:02d}'.format(h, m)) - return ans -``` - -### **Java** - ```java class Solution { public List readBinaryWatch(int turnedOn) { @@ -87,23 +74,6 @@ class Solution { } ``` -```java -class Solution { - public List readBinaryWatch(int turnedOn) { - List ans = new ArrayList<>(); - for (int i = 0; i < 1 << 10; ++i) { - int h = i >> 6, m = i & 0b111111; - if (h < 12 && m < 60 && Integer.bitCount(i) == turnedOn) { - ans.add(String.format("%d:%02d", h, m)); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -121,24 +91,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector readBinaryWatch(int turnedOn) { - vector ans; - for (int i = 0; i < 1 << 10; ++i) { - int h = i >> 6, m = i & 0b111111; - if (h < 12 && m < 60 && __builtin_popcount(i) == turnedOn) { - ans.push_back(to_string(h) + ":" + (m < 10 ? "0" : "") + to_string(m)); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func readBinaryWatch(turnedOn int) []string { var ans []string @@ -153,21 +105,6 @@ func readBinaryWatch(turnedOn int) []string { } ``` -```go -func readBinaryWatch(turnedOn int) []string { - var ans []string - for i := 0; i < 1<<10; i++ { - h, m := i>>6, i&0b111111 - if h < 12 && m < 60 && bits.OnesCount(uint(i)) == turnedOn { - ans = append(ans, fmt.Sprintf("%d:%02d", h, m)) - } - } - return ans -} -``` - -### **TypeScript** - ```ts function readBinaryWatch(turnedOn: number): string[] { if (turnedOn === 0) { @@ -202,8 +139,6 @@ function readBinaryWatch(turnedOn: number): string[] { } ``` -### **Rust** - ```rust impl Solution { fn create_time(bit_arr: &[bool; 10]) -> (i32, i32) { @@ -253,10 +188,67 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def readBinaryWatch(self, turnedOn: int) -> List[str]: + ans = [] + for i in range(1 << 10): + h, m = i >> 6, i & 0b111111 + if h < 12 and m < 60 and i.bit_count() == turnedOn: + ans.append('{:d}:{:02d}'.format(h, m)) + return ans ``` +```java +class Solution { + public List readBinaryWatch(int turnedOn) { + List ans = new ArrayList<>(); + for (int i = 0; i < 1 << 10; ++i) { + int h = i >> 6, m = i & 0b111111; + if (h < 12 && m < 60 && Integer.bitCount(i) == turnedOn) { + ans.add(String.format("%d:%02d", h, m)); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector readBinaryWatch(int turnedOn) { + vector ans; + for (int i = 0; i < 1 << 10; ++i) { + int h = i >> 6, m = i & 0b111111; + if (h < 12 && m < 60 && __builtin_popcount(i) == turnedOn) { + ans.push_back(to_string(h) + ":" + (m < 10 ? "0" : "") + to_string(m)); + } + } + return ans; + } +}; +``` + +```go +func readBinaryWatch(turnedOn int) []string { + var ans []string + for i := 0; i < 1<<10; i++ { + h, m := i>>6, i&0b111111 + if h < 12 && m < 60 && bits.OnesCount(uint(i)) == turnedOn { + ans = append(ans, fmt.Sprintf("%d:%02d", h, m)) + } + } + return ans +} ``` + + diff --git a/solution/0400-0499/0402.Remove K Digits/README.md b/solution/0400-0499/0402.Remove K Digits/README.md index f70e6ce28cf3e..bc6ccc6ec9401 100644 --- a/solution/0400-0499/0402.Remove K Digits/README.md +++ b/solution/0400-0499/0402.Remove K Digits/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:贪心算法** +### 方法一:贪心算法 前置知识:两个相同位数的数字大小关系取决于第一个不同位的数的大小。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def removeKdigits(self, num: str, k: int) -> str: @@ -79,8 +73,6 @@ class Solution: return ''.join(stk[:remain]).lstrip('0') or '0' ``` -### **Java** - ```java class Solution { public String removeKdigits(String num, int k) { @@ -104,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +120,6 @@ public: }; ``` -### **Go** - ```go func removeKdigits(num string, k int) string { stk, remain := make([]byte, 0), len(num)-k @@ -153,8 +141,6 @@ func removeKdigits(num string, k int) string { } ``` -### **TypeScript** - ```ts function removeKdigits(num: string, k: number): string { let nums = [...num]; @@ -170,10 +156,6 @@ function removeKdigits(num: string, k: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0402.Remove K Digits/README_EN.md b/solution/0400-0499/0402.Remove K Digits/README_EN.md index 24e730e7b3cc0..bc9893bf88f9d 100644 --- a/solution/0400-0499/0402.Remove K Digits/README_EN.md +++ b/solution/0400-0499/0402.Remove K Digits/README_EN.md @@ -42,12 +42,10 @@ ## Solutions -**Solution 1: Greedy Algorithm** +### Solution 1: Greedy Algorithm -### **Python3** - ```python class Solution: def removeKdigits(self, num: str, k: int) -> str: @@ -61,8 +59,6 @@ class Solution: return ''.join(stk[:remain]).lstrip('0') or '0' ``` -### **Java** - ```java class Solution { public String removeKdigits(String num, int k) { @@ -86,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +106,6 @@ public: }; ``` -### **Go** - ```go func removeKdigits(num string, k int) string { stk, remain := make([]byte, 0), len(num)-k @@ -135,8 +127,6 @@ func removeKdigits(num string, k int) string { } ``` -### **TypeScript** - ```ts function removeKdigits(num: string, k: number): string { let nums = [...num]; @@ -152,10 +142,6 @@ function removeKdigits(num: string, k: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0403.Frog Jump/README.md b/solution/0400-0499/0403.Frog Jump/README.md index 0ffba118de841..e705d852a797e 100644 --- a/solution/0400-0499/0403.Frog Jump/README.md +++ b/solution/0400-0499/0403.Frog Jump/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:哈希表 + 记忆化搜索** +### 方法一:哈希表 + 记忆化搜索 我们用哈希表 $pos$ 记录每个石子的下标,接下来设计一个函数 $dfs(i, k)$,表示青蛙从第 $i$ 个石子跳跃且上一次跳跃距离为 $k$,如果青蛙能够到达终点,那么函数返回 `true`,否则返回 `false`。 @@ -59,22 +57,8 @@ 时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是石子的数量。 -**方法二:动态规划** - -我们定义 $f[i][k]$ 表示青蛙能否达到「现在所处的石子编号」为 $i$,「上一次跳跃距离」为 $k$ 的状态。初始时 $f[0][0] = true$,其余均为 `false`。 - -考虑 $f[i]$,我们可以枚举上一块石子的编号 $j$,那么上一次跳跃的距离 $k=stones[i]-stones[j]$。如果 $k-1 \gt j$,那么青蛙无法从第 $j$ 块石子跳跃到第 $i$ 块石子,我们可以直接跳过这种情况。否则,青蛙可以从第 $j$ 块石子跳跃到第 $i$ 块石子,那么 $f[i][k] = f[j][k-1] \lor f[j][k] \lor f[j][k+1]$。如果 $i=n-1$,且 $f[i][k]=true$,那么青蛙可以成功过河,我们就可以返回 `true`。 - -否则,我们最后返回 `false`。 - -时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是石子的数量。 - -### **Python3** - - - ```python class Solution: def canCross(self, stones: List[int]) -> bool: @@ -92,27 +76,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def canCross(self, stones: List[int]) -> bool: - n = len(stones) - f = [[False] * n for _ in range(n)] - f[0][0] = True - for i in range(1, n): - for j in range(i - 1, -1, -1): - k = stones[i] - stones[j] - if k - 1 > j: - break - f[i][k] = f[j][k - 1] or f[j][k] or f[j][k + 1] - if i == n - 1 and f[i][k]: - return True - return False -``` - -### **Java** - - - ```java class Solution { private Boolean[][] f; @@ -150,31 +113,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canCross(int[] stones) { - int n = stones.length; - boolean[][] f = new boolean[n][n]; - f[0][0] = true; - for (int i = 1; i < n; ++i) { - for (int j = i - 1; j >= 0; --j) { - int k = stones[i] - stones[j]; - if (k - 1 > j) { - break; - } - f[i][k] = f[j][k - 1] || f[j][k] || f[j][k + 1]; - if (i == n - 1 && f[i][k]) { - return true; - } - } - } - return false; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -205,33 +143,73 @@ public: }; ``` -```cpp -class Solution { -public: - bool canCross(vector& stones) { - int n = stones.size(); - bool f[n][n]; - memset(f, false, sizeof(f)); - f[0][0] = true; - for (int i = 1; i < n; ++i) { - for (int j = i - 1; j >= 0; --j) { - int k = stones[i] - stones[j]; - if (k - 1 > j) { - break; - } - f[i][k] = f[j][k - 1] || f[j][k] || f[j][k + 1]; - if (i == n - 1 && f[i][k]) { +```go +func canCross(stones []int) bool { + n := len(stones) + f := make([][]int, n) + pos := map[int]int{} + for i := range f { + pos[stones[i]] = i + f[i] = make([]int, n) + for j := range f[i] { + f[i][j] = -1 + } + } + var dfs func(int, int) bool + dfs = func(i, k int) bool { + if i == n-1 { + return true + } + if f[i][k] != -1 { + return f[i][k] == 1 + } + for j := k - 1; j <= k+1; j++ { + if j > 0 { + if p, ok := pos[stones[i]+j]; ok { + if dfs(p, j) { + f[i][k] = 1 + return true + } + } + } + } + f[i][k] = 0 + return false + } + return dfs(0, 0) +} +``` + +```ts +function canCross(stones: number[]): boolean { + const n = stones.length; + const pos: Map = new Map(); + for (let i = 0; i < n; ++i) { + pos.set(stones[i], i); + } + const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(-1)); + const dfs = (i: number, k: number): boolean => { + if (i === n - 1) { + return true; + } + if (f[i][k] !== -1) { + return f[i][k] === 1; + } + for (let j = k - 1; j <= k + 1; ++j) { + if (j > 0 && pos.has(stones[i] + j)) { + if (dfs(pos.get(stones[i] + j)!, j)) { + f[i][k] = 1; return true; } } } + f[i][k] = 0; return false; - } -}; + }; + return dfs(0, 0); +} ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -283,72 +261,83 @@ impl Solution { } ``` -```rust -impl Solution { - #[allow(dead_code)] - pub fn can_cross(stones: Vec) -> bool { - let n = stones.len(); - let mut dp = vec![vec![false; n]; n]; + - // Initialize the dp vector - dp[0][0] = true; +### 方法二:动态规划 - // Begin the actual dp process - for i in 1..n { - for j in (0..=i - 1).rev() { - let k = (stones[i] - stones[j]) as usize; - if k - 1 > j { +我们定义 $f[i][k]$ 表示青蛙能否达到「现在所处的石子编号」为 $i$,「上一次跳跃距离」为 $k$ 的状态。初始时 $f[0][0] = true$,其余均为 `false`。 + +考虑 $f[i]$,我们可以枚举上一块石子的编号 $j$,那么上一次跳跃的距离 $k=stones[i]-stones[j]$。如果 $k-1 \gt j$,那么青蛙无法从第 $j$ 块石子跳跃到第 $i$ 块石子,我们可以直接跳过这种情况。否则,青蛙可以从第 $j$ 块石子跳跃到第 $i$ 块石子,那么 $f[i][k] = f[j][k-1] \lor f[j][k] \lor f[j][k+1]$。如果 $i=n-1$,且 $f[i][k]=true$,那么青蛙可以成功过河,我们就可以返回 `true`。 + +否则,我们最后返回 `false`。 + +时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是石子的数量。 + + + +```python +class Solution: + def canCross(self, stones: List[int]) -> bool: + n = len(stones) + f = [[False] * n for _ in range(n)] + f[0][0] = True + for i in range(1, n): + for j in range(i - 1, -1, -1): + k = stones[i] - stones[j] + if k - 1 > j: + break + f[i][k] = f[j][k - 1] or f[j][k] or f[j][k + 1] + if i == n - 1 and f[i][k]: + return True + return False +``` + +```java +class Solution { + public boolean canCross(int[] stones) { + int n = stones.length; + boolean[][] f = new boolean[n][n]; + f[0][0] = true; + for (int i = 1; i < n; ++i) { + for (int j = i - 1; j >= 0; --j) { + int k = stones[i] - stones[j]; + if (k - 1 > j) { break; } - dp[i][k] = dp[j][k - 1] || dp[j][k] || dp[j][k + 1]; - if i == n - 1 && dp[i][k] { + f[i][k] = f[j][k - 1] || f[j][k] || f[j][k + 1]; + if (i == n - 1 && f[i][k]) { return true; } } } - - false + return false; } } ``` -### **Go** - -```go -func canCross(stones []int) bool { - n := len(stones) - f := make([][]int, n) - pos := map[int]int{} - for i := range f { - pos[stones[i]] = i - f[i] = make([]int, n) - for j := range f[i] { - f[i][j] = -1 - } - } - var dfs func(int, int) bool - dfs = func(i, k int) bool { - if i == n-1 { - return true - } - if f[i][k] != -1 { - return f[i][k] == 1 - } - for j := k - 1; j <= k+1; j++ { - if j > 0 { - if p, ok := pos[stones[i]+j]; ok { - if dfs(p, j) { - f[i][k] = 1 - return true - } - } - } - } - f[i][k] = 0 - return false - } - return dfs(0, 0) -} +```cpp +class Solution { +public: + bool canCross(vector& stones) { + int n = stones.size(); + bool f[n][n]; + memset(f, false, sizeof(f)); + f[0][0] = true; + for (int i = 1; i < n; ++i) { + for (int j = i - 1; j >= 0; --j) { + int k = stones[i] - stones[j]; + if (k - 1 > j) { + break; + } + f[i][k] = f[j][k - 1] || f[j][k] || f[j][k + 1]; + if (i == n - 1 && f[i][k]) { + return true; + } + } + } + return false; + } +}; ``` ```go @@ -375,38 +364,6 @@ func canCross(stones []int) bool { } ``` -### **TypeScript** - -```ts -function canCross(stones: number[]): boolean { - const n = stones.length; - const pos: Map = new Map(); - for (let i = 0; i < n; ++i) { - pos.set(stones[i], i); - } - const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(-1)); - const dfs = (i: number, k: number): boolean => { - if (i === n - 1) { - return true; - } - if (f[i][k] !== -1) { - return f[i][k] === 1; - } - for (let j = k - 1; j <= k + 1; ++j) { - if (j > 0 && pos.has(stones[i] + j)) { - if (dfs(pos.get(stones[i] + j)!, j)) { - f[i][k] = 1; - return true; - } - } - } - f[i][k] = 0; - return false; - }; - return dfs(0, 0); -} -``` - ```ts function canCross(stones: number[]): boolean { const n = stones.length; @@ -428,10 +385,35 @@ function canCross(stones: number[]): boolean { } ``` -### **...** +```rust +impl Solution { + #[allow(dead_code)] + pub fn can_cross(stones: Vec) -> bool { + let n = stones.len(); + let mut dp = vec![vec![false; n]; n]; -``` + // Initialize the dp vector + dp[0][0] = true; + // Begin the actual dp process + for i in 1..n { + for j in (0..=i - 1).rev() { + let k = (stones[i] - stones[j]) as usize; + if k - 1 > j { + break; + } + dp[i][k] = dp[j][k - 1] || dp[j][k] || dp[j][k + 1]; + if i == n - 1 && dp[i][k] { + return true; + } + } + } + + false + } +} ``` + + diff --git a/solution/0400-0499/0403.Frog Jump/README_EN.md b/solution/0400-0499/0403.Frog Jump/README_EN.md index c33cf691112d2..e177ac3bf7123 100644 --- a/solution/0400-0499/0403.Frog Jump/README_EN.md +++ b/solution/0400-0499/0403.Frog Jump/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Hash Table + Memoization** +### Solution 1: Hash Table + Memoization We use a hash table $pos$ to record the index of each stone. Next, we design a function $dfs(i, k)$, which means that the frog jumps from the $i$-th stone and the last jump distance is $k$. If the frog can reach the end, the function returns `true`, otherwise it returns `false`. @@ -55,20 +55,8 @@ In order to prevent repeated calculations in the function $dfs(i, k)$, we can us The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the number of stones. -**Solution 2: Dynamic Programming** - -We define $f[i][k]$ to be true if and only if it is possible to reach stone $i$ with last jump of size $k$. Initially $f[0][0] = true$, and all other elements of $f$ are false. - -We can determine the value of $f[i][k]$ for all $i$ and $k$ using a double loop. For each possible jump size $k$, we look at the stones we could have jumped from: $i-k$, $i-k+1$, $i-k+2$. If any of these stones exist and if we can reach them with a last jump of size $k-1$, $k$, or $k+1$, then we can reach stone $i$ with a last jump of size $k$. - -If we can reach the last stone, the answer is true. Otherwise, the answer is false. - -The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the number of stones. - -### **Python3** - ```python class Solution: def canCross(self, stones: List[int]) -> bool: @@ -86,25 +74,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def canCross(self, stones: List[int]) -> bool: - n = len(stones) - f = [[False] * n for _ in range(n)] - f[0][0] = True - for i in range(1, n): - for j in range(i - 1, -1, -1): - k = stones[i] - stones[j] - if k - 1 > j: - break - f[i][k] = f[j][k - 1] or f[j][k] or f[j][k + 1] - if i == n - 1 and f[i][k]: - return True - return False -``` - -### **Java** - ```java class Solution { private Boolean[][] f; @@ -142,31 +111,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canCross(int[] stones) { - int n = stones.length; - boolean[][] f = new boolean[n][n]; - f[0][0] = true; - for (int i = 1; i < n; ++i) { - for (int j = i - 1; j >= 0; --j) { - int k = stones[i] - stones[j]; - if (k - 1 > j) { - break; - } - f[i][k] = f[j][k - 1] || f[j][k] || f[j][k + 1]; - if (i == n - 1 && f[i][k]) { - return true; - } - } - } - return false; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -197,33 +141,73 @@ public: }; ``` -```cpp -class Solution { -public: - bool canCross(vector& stones) { - int n = stones.size(); - bool f[n][n]; - memset(f, false, sizeof(f)); - f[0][0] = true; - for (int i = 1; i < n; ++i) { - for (int j = i - 1; j >= 0; --j) { - int k = stones[i] - stones[j]; - if (k - 1 > j) { - break; - } - f[i][k] = f[j][k - 1] || f[j][k] || f[j][k + 1]; - if (i == n - 1 && f[i][k]) { +```go +func canCross(stones []int) bool { + n := len(stones) + f := make([][]int, n) + pos := map[int]int{} + for i := range f { + pos[stones[i]] = i + f[i] = make([]int, n) + for j := range f[i] { + f[i][j] = -1 + } + } + var dfs func(int, int) bool + dfs = func(i, k int) bool { + if i == n-1 { + return true + } + if f[i][k] != -1 { + return f[i][k] == 1 + } + for j := k - 1; j <= k+1; j++ { + if j > 0 { + if p, ok := pos[stones[i]+j]; ok { + if dfs(p, j) { + f[i][k] = 1 + return true + } + } + } + } + f[i][k] = 0 + return false + } + return dfs(0, 0) +} +``` + +```ts +function canCross(stones: number[]): boolean { + const n = stones.length; + const pos: Map = new Map(); + for (let i = 0; i < n; ++i) { + pos.set(stones[i], i); + } + const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(-1)); + const dfs = (i: number, k: number): boolean => { + if (i === n - 1) { + return true; + } + if (f[i][k] !== -1) { + return f[i][k] === 1; + } + for (let j = k - 1; j <= k + 1; ++j) { + if (j > 0 && pos.has(stones[i] + j)) { + if (dfs(pos.get(stones[i] + j)!, j)) { + f[i][k] = 1; return true; } } } + f[i][k] = 0; return false; - } -}; + }; + return dfs(0, 0); +} ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -275,72 +259,83 @@ impl Solution { } ``` -```rust -impl Solution { - #[allow(dead_code)] - pub fn can_cross(stones: Vec) -> bool { - let n = stones.len(); - let mut dp = vec![vec![false; n]; n]; + - // Initialize the dp vector - dp[0][0] = true; +### Solution 2: Dynamic Programming - // Begin the actual dp process - for i in 1..n { - for j in (0..=i - 1).rev() { - let k = (stones[i] - stones[j]) as usize; - if k - 1 > j { +We define $f[i][k]$ to be true if and only if it is possible to reach stone $i$ with last jump of size $k$. Initially $f[0][0] = true$, and all other elements of $f$ are false. + +We can determine the value of $f[i][k]$ for all $i$ and $k$ using a double loop. For each possible jump size $k$, we look at the stones we could have jumped from: $i-k$, $i-k+1$, $i-k+2$. If any of these stones exist and if we can reach them with a last jump of size $k-1$, $k$, or $k+1$, then we can reach stone $i$ with a last jump of size $k$. + +If we can reach the last stone, the answer is true. Otherwise, the answer is false. + +The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ is the number of stones. + + + +```python +class Solution: + def canCross(self, stones: List[int]) -> bool: + n = len(stones) + f = [[False] * n for _ in range(n)] + f[0][0] = True + for i in range(1, n): + for j in range(i - 1, -1, -1): + k = stones[i] - stones[j] + if k - 1 > j: + break + f[i][k] = f[j][k - 1] or f[j][k] or f[j][k + 1] + if i == n - 1 and f[i][k]: + return True + return False +``` + +```java +class Solution { + public boolean canCross(int[] stones) { + int n = stones.length; + boolean[][] f = new boolean[n][n]; + f[0][0] = true; + for (int i = 1; i < n; ++i) { + for (int j = i - 1; j >= 0; --j) { + int k = stones[i] - stones[j]; + if (k - 1 > j) { break; } - dp[i][k] = dp[j][k - 1] || dp[j][k] || dp[j][k + 1]; - if i == n - 1 && dp[i][k] { + f[i][k] = f[j][k - 1] || f[j][k] || f[j][k + 1]; + if (i == n - 1 && f[i][k]) { return true; } } } - - false + return false; } } ``` -### **Go** - -```go -func canCross(stones []int) bool { - n := len(stones) - f := make([][]int, n) - pos := map[int]int{} - for i := range f { - pos[stones[i]] = i - f[i] = make([]int, n) - for j := range f[i] { - f[i][j] = -1 - } - } - var dfs func(int, int) bool - dfs = func(i, k int) bool { - if i == n-1 { - return true - } - if f[i][k] != -1 { - return f[i][k] == 1 - } - for j := k - 1; j <= k+1; j++ { - if j > 0 { - if p, ok := pos[stones[i]+j]; ok { - if dfs(p, j) { - f[i][k] = 1 - return true - } - } - } - } - f[i][k] = 0 - return false - } - return dfs(0, 0) -} +```cpp +class Solution { +public: + bool canCross(vector& stones) { + int n = stones.size(); + bool f[n][n]; + memset(f, false, sizeof(f)); + f[0][0] = true; + for (int i = 1; i < n; ++i) { + for (int j = i - 1; j >= 0; --j) { + int k = stones[i] - stones[j]; + if (k - 1 > j) { + break; + } + f[i][k] = f[j][k - 1] || f[j][k] || f[j][k + 1]; + if (i == n - 1 && f[i][k]) { + return true; + } + } + } + return false; + } +}; ``` ```go @@ -367,38 +362,6 @@ func canCross(stones []int) bool { } ``` -### **TypeScript** - -```ts -function canCross(stones: number[]): boolean { - const n = stones.length; - const pos: Map = new Map(); - for (let i = 0; i < n; ++i) { - pos.set(stones[i], i); - } - const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(-1)); - const dfs = (i: number, k: number): boolean => { - if (i === n - 1) { - return true; - } - if (f[i][k] !== -1) { - return f[i][k] === 1; - } - for (let j = k - 1; j <= k + 1; ++j) { - if (j > 0 && pos.has(stones[i] + j)) { - if (dfs(pos.get(stones[i] + j)!, j)) { - f[i][k] = 1; - return true; - } - } - } - f[i][k] = 0; - return false; - }; - return dfs(0, 0); -} -``` - ```ts function canCross(stones: number[]): boolean { const n = stones.length; @@ -420,10 +383,35 @@ function canCross(stones: number[]): boolean { } ``` -### **...** +```rust +impl Solution { + #[allow(dead_code)] + pub fn can_cross(stones: Vec) -> bool { + let n = stones.len(); + let mut dp = vec![vec![false; n]; n]; -``` + // Initialize the dp vector + dp[0][0] = true; + // Begin the actual dp process + for i in 1..n { + for j in (0..=i - 1).rev() { + let k = (stones[i] - stones[j]) as usize; + if k - 1 > j { + break; + } + dp[i][k] = dp[j][k - 1] || dp[j][k] || dp[j][k + 1]; + if i == n - 1 && dp[i][k] { + return true; + } + } + } + + false + } +} ``` + + diff --git a/solution/0400-0499/0404.Sum of Left Leaves/README.md b/solution/0400-0499/0404.Sum of Left Leaves/README.md index eb95b27ed3d9a..91e23fee19fea 100644 --- a/solution/0400-0499/0404.Sum of Left Leaves/README.md +++ b/solution/0400-0499/0404.Sum of Left Leaves/README.md @@ -40,14 +40,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -69,10 +65,6 @@ class Solution: return res ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -99,8 +91,6 @@ class Solution { } ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -124,8 +114,6 @@ func sumOfLeftLeaves(root *TreeNode) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -160,8 +148,6 @@ function sumOfLeftLeaves(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -206,8 +192,6 @@ impl Solution { } ``` -### **C** - ```c /** * Definition for a binary tree node. @@ -233,10 +217,6 @@ int sumOfLeftLeaves(struct TreeNode* root) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0404.Sum of Left Leaves/README_EN.md b/solution/0400-0499/0404.Sum of Left Leaves/README_EN.md index e1b884b12b02e..4d40dbe3eb1bd 100644 --- a/solution/0400-0499/0404.Sum of Left Leaves/README_EN.md +++ b/solution/0400-0499/0404.Sum of Left Leaves/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -59,8 +59,6 @@ class Solution: return res ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -87,8 +85,6 @@ class Solution { } ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -112,8 +108,6 @@ func sumOfLeftLeaves(root *TreeNode) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -148,8 +142,6 @@ function sumOfLeftLeaves(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -194,8 +186,6 @@ impl Solution { } ``` -### **C** - ```c /** * Definition for a binary tree node. @@ -221,10 +211,6 @@ int sumOfLeftLeaves(struct TreeNode* root) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0405.Convert a Number to Hexadecimal/README.md b/solution/0400-0499/0405.Convert a Number to Hexadecimal/README.md index 7e90f2c1522f5..520b49843536c 100644 --- a/solution/0400-0499/0405.Convert a Number to Hexadecimal/README.md +++ b/solution/0400-0499/0405.Convert a Number to Hexadecimal/README.md @@ -39,16 +39,10 @@ ## 解法 - - -将数字的二进制位每 4 个一组转换为 16 进制即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def toHex(self, num: int) -> str: @@ -63,10 +57,6 @@ class Solution: return ''.join(s) ``` -### **Java** - - - ```java class Solution { public String toHex(int num) { @@ -88,27 +78,6 @@ class Solution { } ``` -```java -class Solution { - public String toHex(int num) { - if (num == 0) { - return "0"; - } - StringBuilder sb = new StringBuilder(); - for (int i = 7; i >= 0; --i) { - int x = (num >> (4 * i)) & 0xf; - if (sb.length() > 0 || x != 0) { - char c = x < 10 ? (char) (x + '0') : (char) (x - 10 + 'a'); - sb.append(c); - } - } - return sb.toString(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -127,8 +96,6 @@ public: }; ``` -### **Go** - ```go func toHex(num int) string { if num == 0 { @@ -151,10 +118,31 @@ func toHex(num int) string { } ``` -### **...** + + +### 方法二 -``` + +```java +class Solution { + public String toHex(int num) { + if (num == 0) { + return "0"; + } + StringBuilder sb = new StringBuilder(); + for (int i = 7; i >= 0; --i) { + int x = (num >> (4 * i)) & 0xf; + if (sb.length() > 0 || x != 0) { + char c = x < 10 ? (char) (x + '0') : (char) (x - 10 + 'a'); + sb.append(c); + } + } + return sb.toString(); + } +} ``` + + diff --git a/solution/0400-0499/0405.Convert a Number to Hexadecimal/README_EN.md b/solution/0400-0499/0405.Convert a Number to Hexadecimal/README_EN.md index bbdc7cb9f99ce..68fea6984a9db 100644 --- a/solution/0400-0499/0405.Convert a Number to Hexadecimal/README_EN.md +++ b/solution/0400-0499/0405.Convert a Number to Hexadecimal/README_EN.md @@ -27,9 +27,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -45,8 +45,6 @@ class Solution: return ''.join(s) ``` -### **Java** - ```java class Solution { public String toHex(int num) { @@ -68,27 +66,6 @@ class Solution { } ``` -```java -class Solution { - public String toHex(int num) { - if (num == 0) { - return "0"; - } - StringBuilder sb = new StringBuilder(); - for (int i = 7; i >= 0; --i) { - int x = (num >> (4 * i)) & 0xf; - if (sb.length() > 0 || x != 0) { - char c = x < 10 ? (char) (x + '0') : (char) (x - 10 + 'a'); - sb.append(c); - } - } - return sb.toString(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -107,8 +84,6 @@ public: }; ``` -### **Go** - ```go func toHex(num int) string { if num == 0 { @@ -131,10 +106,31 @@ func toHex(num int) string { } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + public String toHex(int num) { + if (num == 0) { + return "0"; + } + StringBuilder sb = new StringBuilder(); + for (int i = 7; i >= 0; --i) { + int x = (num >> (4 * i)) & 0xf; + if (sb.length() > 0 || x != 0) { + char c = x < 10 ? (char) (x + '0') : (char) (x - 10 + 'a'); + sb.append(c); + } + } + return sb.toString(); + } +} ``` + + diff --git a/solution/0400-0499/0406.Queue Reconstruction by Height/README.md b/solution/0400-0499/0406.Queue Reconstruction by Height/README.md index 5053a47cd7bfa..8116fd1cc69b7 100644 --- a/solution/0400-0499/0406.Queue Reconstruction by Height/README.md +++ b/solution/0400-0499/0406.Queue Reconstruction by Height/README.md @@ -50,16 +50,10 @@ ## 解法 - - -对 people 按照身高降序排列,若身高相同,则按照人数 k 升序排列。然后按照索引位置依次将 people 插入到结果列表中即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] reconstructQueue(int[][] people) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +92,6 @@ public: }; ``` -### **Go** - ```go func reconstructQueue(people [][]int) [][]int { sort.Slice(people, func(i, j int) bool { @@ -121,10 +107,6 @@ func reconstructQueue(people [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0406.Queue Reconstruction by Height/README_EN.md b/solution/0400-0499/0406.Queue Reconstruction by Height/README_EN.md index d875fdc8f1775..46adf7692dbc2 100644 --- a/solution/0400-0499/0406.Queue Reconstruction by Height/README_EN.md +++ b/solution/0400-0499/0406.Queue Reconstruction by Height/README_EN.md @@ -43,9 +43,9 @@ Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] reconstructQueue(int[][] people) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,8 +85,6 @@ public: }; ``` -### **Go** - ```go func reconstructQueue(people [][]int) [][]int { sort.Slice(people, func(i, j int) bool { @@ -106,10 +100,6 @@ func reconstructQueue(people [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0407.Trapping Rain Water II/README.md b/solution/0400-0499/0407.Trapping Rain Water II/README.md index bbf1b73e657a0..ef0a47758c99f 100644 --- a/solution/0400-0499/0407.Trapping Rain Water II/README.md +++ b/solution/0400-0499/0407.Trapping Rain Water II/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:优先队列(小根堆)** +### 方法一:优先队列(小根堆) 接雨水问题的变种,由于矩阵的边界上的高度是确定的,因此可以将矩阵的边界上的高度加入优先队列,然后从优先队列中取出最小的高度,然后将其四周的高度与其比较,如果四周的高度小于当前高度,则可以接雨水,接雨水的体积为当前高度减去四周的高度,然后将较大的高度加入优先队列,重复上述过程,直到优先队列为空。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def trapRainWater(self, heightMap: List[List[int]]) -> int: @@ -82,10 +76,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int trapRainWater(int[][] heightMap) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func trapRainWater(heightMap [][]int) (ans int) { m, n := len(heightMap), len(heightMap[0]) @@ -197,10 +183,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0407.Trapping Rain Water II/README_EN.md b/solution/0400-0499/0407.Trapping Rain Water II/README_EN.md index 7b5786633f72f..a954671a76c84 100644 --- a/solution/0400-0499/0407.Trapping Rain Water II/README_EN.md +++ b/solution/0400-0499/0407.Trapping Rain Water II/README_EN.md @@ -36,9 +36,9 @@ The total volume of water trapped is 4. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int trapRainWater(int[][] heightMap) { @@ -98,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +132,6 @@ public: }; ``` -### **Go** - ```go func trapRainWater(heightMap [][]int) (ans int) { m, n := len(heightMap), len(heightMap[0]) @@ -177,10 +171,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0408.Valid Word Abbreviation/README.md b/solution/0400-0499/0408.Valid Word Abbreviation/README.md index 028ff440a3016..5d6b458bd1141 100644 --- a/solution/0400-0499/0408.Valid Word Abbreviation/README.md +++ b/solution/0400-0499/0408.Valid Word Abbreviation/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以直接模拟字符匹配替换。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def validWordAbbreviation(self, word: str, abbr: str) -> bool: @@ -106,10 +100,6 @@ class Solution: return i + x == m and j == n ``` -### **Java** - - - ```java class Solution { public boolean validWordAbbreviation(String word, String abbr) { @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +152,6 @@ public: }; ``` -### **Go** - ```go func validWordAbbreviation(word string, abbr string) bool { m, n := len(word), len(abbr) @@ -189,8 +175,6 @@ func validWordAbbreviation(word string, abbr string) bool { } ``` -### **TypeScript** - ```ts function validWordAbbreviation(word: string, abbr: string): boolean { const [m, n] = [word.length, abbr.length]; @@ -213,10 +197,6 @@ function validWordAbbreviation(word: string, abbr: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0408.Valid Word Abbreviation/README_EN.md b/solution/0400-0499/0408.Valid Word Abbreviation/README_EN.md index 98cb844e6a709..bdc451ca73ee4 100644 --- a/solution/0400-0499/0408.Valid Word Abbreviation/README_EN.md +++ b/solution/0400-0499/0408.Valid Word Abbreviation/README_EN.md @@ -58,7 +58,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can directly simulate character matching and replacement. @@ -78,8 +78,6 @@ The time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the stri -### **Python3** - ```python class Solution: def validWordAbbreviation(self, word: str, abbr: str) -> bool: @@ -100,8 +98,6 @@ class Solution: return i + x == m and j == n ``` -### **Java** - ```java class Solution { public boolean validWordAbbreviation(String word, String abbr) { @@ -128,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +150,6 @@ public: }; ``` -### **Go** - ```go func validWordAbbreviation(word string, abbr string) bool { m, n := len(word), len(abbr) @@ -181,8 +173,6 @@ func validWordAbbreviation(word string, abbr string) bool { } ``` -### **TypeScript** - ```ts function validWordAbbreviation(word: string, abbr: string): boolean { const [m, n] = [word.length, abbr.length]; @@ -205,10 +195,6 @@ function validWordAbbreviation(word: string, abbr: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0409.Longest Palindrome/README.md b/solution/0400-0499/0409.Longest Palindrome/README.md index 1c8560193ba52..1c0ba9a9a869b 100644 --- a/solution/0400-0499/0409.Longest Palindrome/README.md +++ b/solution/0400-0499/0409.Longest Palindrome/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 一个合法的回文字符串,最多存在一个出现奇数次数的字符,其余字符出现次数均为偶数。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def longestPalindrome(self, s: str) -> int: @@ -76,10 +70,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestPalindrome(String s) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func longestPalindrome(s string) (ans int) { cnt := [128]int{} @@ -139,8 +125,6 @@ func longestPalindrome(s string) (ans int) { } ``` -### **TypeScript** - ```ts function longestPalindrome(s: string): number { let n = s.length; @@ -157,27 +141,6 @@ function longestPalindrome(s: string): number { } ``` -```ts -function longestPalindrome(s: string): number { - const map = new Map(); - for (const c of s) { - map.set(c, (map.get(c) ?? 0) + 1); - } - let hasOdd = false; - let res = 0; - for (const v of map.values()) { - res += v; - if (v & 1) { - hasOdd = true; - res--; - } - } - return res + (hasOdd ? 1 : 0); -} -``` - -### **Rust** - ```rust use std::collections::HashMap; @@ -201,10 +164,31 @@ impl Solution { } ``` -### **...** + -``` +### 方法二 + + +```ts +function longestPalindrome(s: string): number { + const map = new Map(); + for (const c of s) { + map.set(c, (map.get(c) ?? 0) + 1); + } + let hasOdd = false; + let res = 0; + for (const v of map.values()) { + res += v; + if (v & 1) { + hasOdd = true; + res--; + } + } + return res + (hasOdd ? 1 : 0); +} ``` + + diff --git a/solution/0400-0499/0409.Longest Palindrome/README_EN.md b/solution/0400-0499/0409.Longest Palindrome/README_EN.md index d0a3d19723200..9c6f24ca7649f 100644 --- a/solution/0400-0499/0409.Longest Palindrome/README_EN.md +++ b/solution/0400-0499/0409.Longest Palindrome/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting A valid palindrome string can have at most one character that appears an odd number of times, and the rest of the characters appear an even number of times. @@ -49,8 +49,6 @@ The time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is -### **Python3** - ```python class Solution: def longestPalindrome(self, s: str) -> int: @@ -62,8 +60,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestPalindrome(String s) { @@ -83,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +99,6 @@ public: }; ``` -### **Go** - ```go func longestPalindrome(s string) (ans int) { cnt := [128]int{} @@ -123,8 +115,6 @@ func longestPalindrome(s string) (ans int) { } ``` -### **TypeScript** - ```ts function longestPalindrome(s: string): number { let n = s.length; @@ -141,27 +131,6 @@ function longestPalindrome(s: string): number { } ``` -```ts -function longestPalindrome(s: string): number { - const map = new Map(); - for (const c of s) { - map.set(c, (map.get(c) ?? 0) + 1); - } - let hasOdd = false; - let res = 0; - for (const v of map.values()) { - res += v; - if (v & 1) { - hasOdd = true; - res--; - } - } - return res + (hasOdd ? 1 : 0); -} -``` - -### **Rust** - ```rust use std::collections::HashMap; @@ -185,10 +154,31 @@ impl Solution { } ``` -### **...** + -``` +### Solution 2 + + +```ts +function longestPalindrome(s: string): number { + const map = new Map(); + for (const c of s) { + map.set(c, (map.get(c) ?? 0) + 1); + } + let hasOdd = false; + let res = 0; + for (const v of map.values()) { + res += v; + if (v & 1) { + hasOdd = true; + res--; + } + } + return res + (hasOdd ? 1 : 0); +} ``` + + diff --git a/solution/0400-0499/0410.Split Array Largest Sum/README.md b/solution/0400-0499/0410.Split Array Largest Sum/README.md index c36e1704b1b4e..a30a284a6b7d0 100644 --- a/solution/0400-0499/0410.Split Array Largest Sum/README.md +++ b/solution/0400-0499/0410.Split Array Largest Sum/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们注意到,当子数组的和的最大值越大,子数组的个数越少,当存在一个满足条件的子数组和的最大值时,那么比这个最大值更大的子数组和的最大值一定也满足条件。也就是说,我们可以对子数组和的最大值进行二分查找,找到满足条件的最小值。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def splitArray(self, nums: List[int], k: int) -> int: @@ -82,10 +76,6 @@ class Solution: return left + bisect_left(range(left, right + 1), True, key=check) ``` -### **Java** - - - ```java class Solution { public int splitArray(int[] nums, int k) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func splitArray(nums []int, k int) int { left, right := 0, 0 @@ -178,8 +164,6 @@ func splitArray(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function splitArray(nums: number[], k: number): number { let left = 0; @@ -212,10 +196,6 @@ function splitArray(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0410.Split Array Largest Sum/README_EN.md b/solution/0400-0499/0410.Split Array Largest Sum/README_EN.md index 61020a00675ad..1bef90a1a7b22 100644 --- a/solution/0400-0499/0410.Split Array Largest Sum/README_EN.md +++ b/solution/0400-0499/0410.Split Array Largest Sum/README_EN.md @@ -40,7 +40,7 @@ The best way is to split it into [1,2,3] and [4,5], where the largest sum among ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search We notice that the larger the maximum sum of the subarrays, the fewer the number of subarrays. When there is a maximum sum of the subarrays that meets the condition, then a larger maximum sum of the subarrays will definitely meet the condition. This means that we can perform a binary search for the maximum sum of the subarrays to find the smallest value that meets the condition. @@ -52,8 +52,6 @@ The time complexity is $O(n \times \log m)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def splitArray(self, nums: List[int], k: int) -> int: @@ -70,8 +68,6 @@ class Solution: return left + bisect_left(range(left, right + 1), True, key=check) ``` -### **Java** - ```java class Solution { public int splitArray(int[] nums, int k) { @@ -105,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +134,6 @@ public: }; ``` -### **Go** - ```go func splitArray(nums []int, k int) int { left, right := 0, 0 @@ -164,8 +156,6 @@ func splitArray(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function splitArray(nums: number[], k: number): number { let left = 0; @@ -198,10 +188,6 @@ function splitArray(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0411.Minimum Unique Word Abbreviation/README.md b/solution/0400-0499/0411.Minimum Unique Word Abbreviation/README.md index 955fc498afd1c..4294f4b827e09 100644 --- a/solution/0400-0499/0411.Minimum Unique Word Abbreviation/README.md +++ b/solution/0400-0499/0411.Minimum Unique Word Abbreviation/README.md @@ -64,30 +64,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0400-0499/0411.Minimum Unique Word Abbreviation/README_EN.md b/solution/0400-0499/0411.Minimum Unique Word Abbreviation/README_EN.md index 600d01f93503e..b56e010081f8e 100644 --- a/solution/0400-0499/0411.Minimum Unique Word Abbreviation/README_EN.md +++ b/solution/0400-0499/0411.Minimum Unique Word Abbreviation/README_EN.md @@ -59,24 +59,4 @@ Since none of them are abbreviations of words in the dictionary, returning any o ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0400-0499/0412.Fizz Buzz/README.md b/solution/0400-0499/0412.Fizz Buzz/README.md index e99fc656786e8..0764cf3c190e9 100644 --- a/solution/0400-0499/0412.Fizz Buzz/README.md +++ b/solution/0400-0499/0412.Fizz Buzz/README.md @@ -47,14 +47,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def fizzBuzz(self, n: int) -> List[str]: @@ -71,10 +67,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List fizzBuzz(int n) { @@ -97,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +106,6 @@ public: }; ``` -### **Go** - ```go func fizzBuzz(n int) []string { var ans []string @@ -138,7 +126,18 @@ func fizzBuzz(n int) []string { } ``` -### **PHP** +```js +const fizzBuzz = function (n) { + let arr = []; + for (let i = 1; i <= n; i++) { + if (i % 15 === 0) arr.push('FizzBuzz'); + else if (i % 3 === 0) arr.push('Fizz'); + else if (i % 5 === 0) arr.push('Buzz'); + else arr.push(`${i}`); + } + return arr; +}; +``` ```php class Solution { @@ -164,10 +163,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0412.Fizz Buzz/README_EN.md b/solution/0400-0499/0412.Fizz Buzz/README_EN.md index 0ff429229ebcd..d06717b73026b 100644 --- a/solution/0400-0499/0412.Fizz Buzz/README_EN.md +++ b/solution/0400-0499/0412.Fizz Buzz/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List fizzBuzz(int n) { @@ -77,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func fizzBuzz(n int) []string { var ans []string @@ -118,7 +112,18 @@ func fizzBuzz(n int) []string { } ``` -### **PHP** +```js +const fizzBuzz = function (n) { + let arr = []; + for (let i = 1; i <= n; i++) { + if (i % 15 === 0) arr.push('FizzBuzz'); + else if (i % 3 === 0) arr.push('Fizz'); + else if (i % 5 === 0) arr.push('Buzz'); + else arr.push(`${i}`); + } + return arr; +}; +``` ```php class Solution { @@ -144,10 +149,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0413.Arithmetic Slices/README.md b/solution/0400-0499/0413.Arithmetic Slices/README.md index af45d2cd905f3..6463d6fe51594 100644 --- a/solution/0400-0499/0413.Arithmetic Slices/README.md +++ b/solution/0400-0499/0413.Arithmetic Slices/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:遍历计数** +### 方法一:遍历计数 我们用 $d$ 表示当前相邻两个元素的差值,用 $cnt$ 表示当前等差数列的长度,初始时 $d = 3000$, $cnt = 2$。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: @@ -88,25 +82,6 @@ class Solution: return ans ``` -```python -class Solution: - def numberOfArithmeticSlices(self, nums: List[int]) -> int: - ans = cnt = 0 - d = 3000 - for a, b in pairwise(nums): - if b - a == d: - cnt += 1 - else: - d = b - a - cnt = 0 - ans += cnt - return ans -``` - -### **Java** - - - ```java class Solution { public int numberOfArithmeticSlices(int[] nums) { @@ -126,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +121,6 @@ public: }; ``` -### **Go** - ```go func numberOfArithmeticSlices(nums []int) (ans int) { cnt, d := 0, 3000 @@ -167,8 +138,6 @@ func numberOfArithmeticSlices(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfArithmeticSlices(nums: number[]): number { let ans = 0; @@ -189,10 +158,27 @@ function numberOfArithmeticSlices(nums: number[]): number { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def numberOfArithmeticSlices(self, nums: List[int]) -> int: + ans = cnt = 0 + d = 3000 + for a, b in pairwise(nums): + if b - a == d: + cnt += 1 + else: + d = b - a + cnt = 0 + ans += cnt + return ans ``` + + diff --git a/solution/0400-0499/0413.Arithmetic Slices/README_EN.md b/solution/0400-0499/0413.Arithmetic Slices/README_EN.md index 11c0d600f3944..68dafa2eece1b 100644 --- a/solution/0400-0499/0413.Arithmetic Slices/README_EN.md +++ b/solution/0400-0499/0413.Arithmetic Slices/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,23 +59,6 @@ class Solution: return ans ``` -```python -class Solution: - def numberOfArithmeticSlices(self, nums: List[int]) -> int: - ans = cnt = 0 - d = 3000 - for a, b in pairwise(nums): - if b - a == d: - cnt += 1 - else: - d = b - a - cnt = 0 - ans += cnt - return ans -``` - -### **Java** - ```java class Solution { public int numberOfArithmeticSlices(int[] nums) { @@ -95,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +98,6 @@ public: }; ``` -### **Go** - ```go func numberOfArithmeticSlices(nums []int) (ans int) { cnt, d := 0, 3000 @@ -136,8 +115,6 @@ func numberOfArithmeticSlices(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfArithmeticSlices(nums: number[]): number { let ans = 0; @@ -158,10 +135,27 @@ function numberOfArithmeticSlices(nums: number[]): number { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def numberOfArithmeticSlices(self, nums: List[int]) -> int: + ans = cnt = 0 + d = 3000 + for a, b in pairwise(nums): + if b - a == d: + cnt += 1 + else: + d = b - a + cnt = 0 + ans += cnt + return ans ``` + + diff --git a/solution/0400-0499/0414.Third Maximum Number/README.md b/solution/0400-0499/0414.Third Maximum Number/README.md index 21995a835d183..2b10111cd1d52 100644 --- a/solution/0400-0499/0414.Third Maximum Number/README.md +++ b/solution/0400-0499/0414.Third Maximum Number/README.md @@ -48,26 +48,10 @@ ## 解法 - - -定义 $m_1$, $m_2$, $m_3$ 分别表示数组的第 `1` 大、第 `2` 大、第 `3` 大的数,初始化为一个足够小的数。 - -遍历数组每个元素 `num`: - -- 若 `num` 与前三大数中的某一个相等,直接跳过,因为我们要找的是在所有不同数字中的第三大。 -- 若 `num` 比 $m_1$ 大,说明找到了一个最大的数,此时我们要把 `num` 赋值给 $m_1$,即 $m_1 = num$,但在做赋值操作之前,我们要先把旧值赋给 $m_2$,依次类推。 -- 对于 `num` 比 $m_2$、$m_3$ 大的情况,也按照上面的赋值方法进行处理。 - -遍历结束,判断 $m_3$ 这个值是否在初始化之后改变过,若是,说明找到了第 `3` 大数,返回 $m_3$,否则返回 $m_1$。 - -本方法时间复杂度 $O(n)$,空间复杂度 $O(1)$。 +### 方法一 -### **Python3** - - - ```python class Solution: def thirdMax(self, nums: List[int]) -> int: @@ -84,10 +68,6 @@ class Solution: return m3 if m3 != -inf else m1 ``` -### **Java** - - - ```java class Solution { public int thirdMax(int[] nums) { @@ -114,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +117,6 @@ public: }; ``` -### **Go** - ```go func thirdMax(nums []int) int { m1, m2, m3 := math.MinInt64, math.MinInt64, math.MinInt64 @@ -163,10 +139,6 @@ func thirdMax(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0414.Third Maximum Number/README_EN.md b/solution/0400-0499/0414.Third Maximum Number/README_EN.md index ef0e349f82e04..c8696cc1f4b3f 100644 --- a/solution/0400-0499/0414.Third Maximum Number/README_EN.md +++ b/solution/0400-0499/0414.Third Maximum Number/README_EN.md @@ -53,9 +53,9 @@ The third distinct maximum is 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return m3 if m3 != -inf else m1 ``` -### **Java** - ```java class Solution { public int thirdMax(int[] nums) { @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +122,6 @@ public: }; ``` -### **Go** - ```go func thirdMax(nums []int) int { m1, m2, m3 := math.MinInt64, math.MinInt64, math.MinInt64 @@ -150,10 +144,6 @@ func thirdMax(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0415.Add Strings/README.md b/solution/0400-0499/0415.Add Strings/README.md index 6fb125ed76e43..c99ac897d9f80 100644 --- a/solution/0400-0499/0415.Add Strings/README.md +++ b/solution/0400-0499/0415.Add Strings/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们用两个指针 $i$ 和 $j$ 分别指向两个字符串的末尾,从末尾开始逐位相加。每次取出对应位的数字 $a$ 和 $b$,计算它们的和 $a + b + c$,其中 $c$ 表示上一次相加的进位,最后将 $a + b + c$ 的个位数添加到追加到答案字符串的末尾,然后将 $a + b + c$ 的十位数作为进位 $c$ 的值,循环此过程直至两个字符串的指针都已经指向了字符串的开头并且进位 $c$ 的值为 $0$。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def addStrings(self, num1: str, num2: str) -> str: @@ -99,10 +93,6 @@ class Solution: return ''.join(ans[::-1]) ``` -### **Java** - - - ```java class Solution { public String addStrings(String num1, String num2) { @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -188,8 +176,6 @@ public: }; ``` -### **Go** - ```go func addStrings(num1 string, num2 string) string { i, j := len(num1)-1, len(num2)-1 @@ -243,61 +229,6 @@ func subStrings(num1 string, num2 string) string { } ``` -### **JavaScript** - -```js -/** - * @param {string} num1 - * @param {string} num2 - * @return {string} - */ -var addStrings = function (num1, num2) { - let i = num1.length - 1; - let j = num2.length - 1; - const ans = []; - for (let c = 0; i >= 0 || j >= 0 || c; --i, --j) { - c += i < 0 ? 0 : +num1[i]; - c += j < 0 ? 0 : +num2[j]; - ans.push(c % 10); - c = Math.floor(c / 10); - } - return ans.reverse().join(''); -}; - -/** - * @param {string} num1 - * @param {string} num2 - * @return {string} - */ -var subStrings = function (num1, num2) { - const m = num1.length; - const n = num2.length; - const neg = m < n || (m == n && num1 < num2); - if (neg) { - const t = num1; - num1 = num2; - num2 = t; - } - let i = num1.length - 1; - let j = num2.length - 1; - const ans = []; - for (let c = 0; i >= 0; --i, --j) { - c = +num1[i] - c; - if (j >= 0) { - c -= +num2[j]; - } - ans.push((c + 10) % 10); - c = c < 0 ? 1 : 0; - } - while (ans.length > 1 && ans.at(-1) === 0) { - ans.pop(); - } - return (neg ? '-' : '') + ans.reverse().join(''); -}; -``` - -### **TypeScript** - ```ts function addStrings(num1: string, num2: string): string { let i = num1.length - 1; @@ -339,8 +270,6 @@ function subStrings(num1: string, num2: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn add_strings(num1: String, num2: String) -> String { @@ -367,10 +296,57 @@ impl Solution { } ``` -### **...** - -``` +```js +/** + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var addStrings = function (num1, num2) { + let i = num1.length - 1; + let j = num2.length - 1; + const ans = []; + for (let c = 0; i >= 0 || j >= 0 || c; --i, --j) { + c += i < 0 ? 0 : +num1[i]; + c += j < 0 ? 0 : +num2[j]; + ans.push(c % 10); + c = Math.floor(c / 10); + } + return ans.reverse().join(''); +}; +/** + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var subStrings = function (num1, num2) { + const m = num1.length; + const n = num2.length; + const neg = m < n || (m == n && num1 < num2); + if (neg) { + const t = num1; + num1 = num2; + num2 = t; + } + let i = num1.length - 1; + let j = num2.length - 1; + const ans = []; + for (let c = 0; i >= 0; --i, --j) { + c = +num1[i] - c; + if (j >= 0) { + c -= +num2[j]; + } + ans.push((c + 10) % 10); + c = c < 0 ? 1 : 0; + } + while (ans.length > 1 && ans.at(-1) === 0) { + ans.pop(); + } + return (neg ? '-' : '') + ans.reverse().join(''); +}; ``` + + diff --git a/solution/0400-0499/0415.Add Strings/README_EN.md b/solution/0400-0499/0415.Add Strings/README_EN.md index 3c04568b9e91b..df53e392bde59 100644 --- a/solution/0400-0499/0415.Add Strings/README_EN.md +++ b/solution/0400-0499/0415.Add Strings/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We use two pointers $i$ and $j$ to point to the end of the two strings respectively, and start adding bit by bit from the end. Each time we take out the corresponding digits $a$ and $b$, calculate their sum $a + b + c$, where $c$ represents the carry from the last addition. Finally, we append the units digit of $a + b + c$ to the end of the answer string, and then take the tens digit of $a + b + c$ as the value of the carry $c$, and loop this process until the pointers of both strings have pointed to the beginning of the string and the value of the carry $c$ is $0$. @@ -53,8 +53,6 @@ The following code also implements string subtraction, refer to the `subStrings( -### **Python3** - ```python class Solution: def addStrings(self, num1: str, num2: str) -> str: @@ -89,8 +87,6 @@ class Solution: return ''.join(ans[::-1]) ``` -### **Java** - ```java class Solution { public String addStrings(String num1, String num2) { @@ -132,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +170,6 @@ public: }; ``` -### **Go** - ```go func addStrings(num1 string, num2 string) string { i, j := len(num1)-1, len(num2)-1 @@ -231,61 +223,6 @@ func subStrings(num1 string, num2 string) string { } ``` -### **JavaScript** - -```js -/** - * @param {string} num1 - * @param {string} num2 - * @return {string} - */ -var addStrings = function (num1, num2) { - let i = num1.length - 1; - let j = num2.length - 1; - const ans = []; - for (let c = 0; i >= 0 || j >= 0 || c; --i, --j) { - c += i < 0 ? 0 : +num1[i]; - c += j < 0 ? 0 : +num2[j]; - ans.push(c % 10); - c = Math.floor(c / 10); - } - return ans.reverse().join(''); -}; - -/** - * @param {string} num1 - * @param {string} num2 - * @return {string} - */ -var subStrings = function (num1, num2) { - const m = num1.length; - const n = num2.length; - const neg = m < n || (m == n && num1 < num2); - if (neg) { - const t = num1; - num1 = num2; - num2 = t; - } - let i = num1.length - 1; - let j = num2.length - 1; - const ans = []; - for (let c = 0; i >= 0; --i, --j) { - c = +num1[i] - c; - if (j >= 0) { - c -= +num2[j]; - } - ans.push((c + 10) % 10); - c = c < 0 ? 1 : 0; - } - while (ans.length > 1 && ans.at(-1) === 0) { - ans.pop(); - } - return (neg ? '-' : '') + ans.reverse().join(''); -}; -``` - -### **TypeScript** - ```ts function addStrings(num1: string, num2: string): string { let i = num1.length - 1; @@ -327,8 +264,6 @@ function subStrings(num1: string, num2: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn add_strings(num1: String, num2: String) -> String { @@ -355,10 +290,57 @@ impl Solution { } ``` -### **...** - -``` +```js +/** + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var addStrings = function (num1, num2) { + let i = num1.length - 1; + let j = num2.length - 1; + const ans = []; + for (let c = 0; i >= 0 || j >= 0 || c; --i, --j) { + c += i < 0 ? 0 : +num1[i]; + c += j < 0 ? 0 : +num2[j]; + ans.push(c % 10); + c = Math.floor(c / 10); + } + return ans.reverse().join(''); +}; +/** + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var subStrings = function (num1, num2) { + const m = num1.length; + const n = num2.length; + const neg = m < n || (m == n && num1 < num2); + if (neg) { + const t = num1; + num1 = num2; + num2 = t; + } + let i = num1.length - 1; + let j = num2.length - 1; + const ans = []; + for (let c = 0; i >= 0; --i, --j) { + c = +num1[i] - c; + if (j >= 0) { + c -= +num2[j]; + } + ans.push((c + 10) % 10); + c = c < 0 ? 1 : 0; + } + while (ans.length > 1 && ans.at(-1) === 0) { + ans.pop(); + } + return (neg ? '-' : '') + ans.reverse().join(''); +}; ``` + + diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/README.md b/solution/0400-0499/0416.Partition Equal Subset Sum/README.md index b1c53a7127388..4e03a22f71445 100644 --- a/solution/0400-0499/0416.Partition Equal Subset Sum/README.md +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们先计算出数组的总和 $s$,如果总和是奇数,那么一定不能分割成两个和相等的子集,直接返回 $false$。如果总和是偶数,我们记目标子集的和为 $m = \frac{s}{2}$,那么问题就转化成了:是否存在一个子集,使得其元素的和为 $m$。 @@ -58,10 +56,6 @@ $$ -### **Python3** - - - ```python class Solution: def canPartition(self, nums: List[int]) -> bool: @@ -77,23 +71,6 @@ class Solution: return f[n][m] ``` -```python -class Solution: - def canPartition(self, nums: List[int]) -> bool: - m, mod = divmod(sum(nums), 2) - if mod: - return False - f = [True] + [False] * m - for x in nums: - for j in range(m, x - 1, -1): - f[j] = f[j] or f[j - x] - return f[m] -``` - -### **Java** - - - ```java class Solution { public boolean canPartition(int[] nums) { @@ -120,32 +97,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canPartition(int[] nums) { - // int s = Arrays.stream(nums).sum(); - int s = 0; - for (int x : nums) { - s += x; - } - if (s % 2 == 1) { - return false; - } - int m = s >> 1; - boolean[] f = new boolean[m + 1]; - f[0] = true; - for (int x : nums) { - for (int j = m; j >= x; --j) { - f[j] |= f[j - x]; - } - } - return f[m]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -170,30 +121,53 @@ public: }; ``` -```cpp -class Solution { -public: - bool canPartition(vector& nums) { - int s = accumulate(nums.begin(), nums.end(), 0); - if (s % 2 == 1) { - return false; - } - int m = s >> 1; - bool f[m + 1]; - memset(f, false, sizeof(f)); - f[0] = true; - for (int& x : nums) { - for (int j = m; j >= x; --j) { - f[j] |= f[j - x]; - } +```go +func canPartition(nums []int) bool { + s := 0 + for _, x := range nums { + s += x + } + if s%2 == 1 { + return false + } + n, m := len(nums), s>>1 + f := make([][]bool, n+1) + for i := range f { + f[i] = make([]bool, m+1) + } + f[0][0] = true + for i := 1; i <= n; i++ { + x := nums[i-1] + for j := 0; j <= m; j++ { + f[i][j] = f[i-1][j] || (j >= x && f[i-1][j-x]) + } + } + return f[n][m] +} +``` + +```ts +function canPartition(nums: number[]): boolean { + const s = nums.reduce((a, b) => a + b, 0); + if (s % 2 === 1) { + return false; + } + const n = nums.length; + const m = s >> 1; + const f: boolean[][] = Array(n + 1) + .fill(0) + .map(() => Array(m + 1).fill(false)); + f[0][0] = true; + for (let i = 1; i <= n; ++i) { + const x = nums[i - 1]; + for (let j = 0; j <= m; ++j) { + f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); } - return f[m]; } -}; + return f[n][m]; +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -230,67 +204,95 @@ impl Solution { } ``` -```rust -impl Solution { - #[allow(dead_code)] - pub fn can_partition(nums: Vec) -> bool { - let mut sum = 0; - for e in &nums { - sum += *e; +```js +/** + * @param {number[]} nums + * @return {boolean} + */ +var canPartition = function (nums) { + const s = nums.reduce((a, b) => a + b, 0); + if (s % 2 === 1) { + return false; + } + const n = nums.length; + const m = s >> 1; + const f = Array(n + 1) + .fill(0) + .map(() => Array(m + 1).fill(false)); + f[0][0] = true; + for (let i = 1; i <= n; ++i) { + const x = nums[i - 1]; + for (let j = 0; j <= m; ++j) { + f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); } + } + return f[n][m]; +}; +``` - if sum % 2 != 0 { - return false; - } + - let m = (sum >> 1) as usize; +### 方法二 - // Here dp[i] means if it can be sum up to `i` for all the number we've traversed through so far - // Which is actually compressing the 2-D dp vector to 1-D - let mut dp: Vec = vec![false; m + 1]; + - // Initialize the dp vector - dp[0] = true; +```python +class Solution: + def canPartition(self, nums: List[int]) -> bool: + m, mod = divmod(sum(nums), 2) + if mod: + return False + f = [True] + [False] * m + for x in nums: + for j in range(m, x - 1, -1): + f[j] = f[j] or f[j - x] + return f[m] +``` - // Begin the actual dp process - for e in &nums { - // For every num in nums vector - for i in (*e as usize..=m).rev() { - // Update the current status - dp[i] |= dp[i - (*e as usize)]; +```java +class Solution { + public boolean canPartition(int[] nums) { + // int s = Arrays.stream(nums).sum(); + int s = 0; + for (int x : nums) { + s += x; + } + if (s % 2 == 1) { + return false; + } + int m = s >> 1; + boolean[] f = new boolean[m + 1]; + f[0] = true; + for (int x : nums) { + for (int j = m; j >= x; --j) { + f[j] |= f[j - x]; } } - - dp[m] + return f[m]; } } ``` -### **Go** - -```go -func canPartition(nums []int) bool { - s := 0 - for _, x := range nums { - s += x - } - if s%2 == 1 { - return false - } - n, m := len(nums), s>>1 - f := make([][]bool, n+1) - for i := range f { - f[i] = make([]bool, m+1) - } - f[0][0] = true - for i := 1; i <= n; i++ { - x := nums[i-1] - for j := 0; j <= m; j++ { - f[i][j] = f[i-1][j] || (j >= x && f[i-1][j-x]) - } - } - return f[n][m] -} +```cpp +class Solution { +public: + bool canPartition(vector& nums) { + int s = accumulate(nums.begin(), nums.end(), 0); + if (s % 2 == 1) { + return false; + } + int m = s >> 1; + bool f[m + 1]; + memset(f, false, sizeof(f)); + f[0] = true; + for (int& x : nums) { + for (int j = m; j >= x; --j) { + f[j] |= f[j - x]; + } + } + return f[m]; + } +}; ``` ```go @@ -314,30 +316,6 @@ func canPartition(nums []int) bool { } ``` -### **TypeScript** - -```ts -function canPartition(nums: number[]): boolean { - const s = nums.reduce((a, b) => a + b, 0); - if (s % 2 === 1) { - return false; - } - const n = nums.length; - const m = s >> 1; - const f: boolean[][] = Array(n + 1) - .fill(0) - .map(() => Array(m + 1).fill(false)); - f[0][0] = true; - for (let i = 1; i <= n; ++i) { - const x = nums[i - 1]; - for (let j = 0; j <= m; ++j) { - f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); - } - } - return f[n][m]; -} -``` - ```ts function canPartition(nums: number[]): boolean { const s = nums.reduce((a, b) => a + b, 0); @@ -356,32 +334,40 @@ function canPartition(nums: number[]): boolean { } ``` -### **JavaScript** +```rust +impl Solution { + #[allow(dead_code)] + pub fn can_partition(nums: Vec) -> bool { + let mut sum = 0; + for e in &nums { + sum += *e; + } -```js -/** - * @param {number[]} nums - * @return {boolean} - */ -var canPartition = function (nums) { - const s = nums.reduce((a, b) => a + b, 0); - if (s % 2 === 1) { - return false; - } - const n = nums.length; - const m = s >> 1; - const f = Array(n + 1) - .fill(0) - .map(() => Array(m + 1).fill(false)); - f[0][0] = true; - for (let i = 1; i <= n; ++i) { - const x = nums[i - 1]; - for (let j = 0; j <= m; ++j) { - f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); + if sum % 2 != 0 { + return false; + } + + let m = (sum >> 1) as usize; + + // Here dp[i] means if it can be sum up to `i` for all the number we've traversed through so far + // Which is actually compressing the 2-D dp vector to 1-D + let mut dp: Vec = vec![false; m + 1]; + + // Initialize the dp vector + dp[0] = true; + + // Begin the actual dp process + for e in &nums { + // For every num in nums vector + for i in (*e as usize..=m).rev() { + // Update the current status + dp[i] |= dp[i - (*e as usize)]; + } } + + dp[m] } - return f[n][m]; -}; +} ``` ```js @@ -406,10 +392,6 @@ var canPartition = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0416.Partition Equal Subset Sum/README_EN.md b/solution/0400-0499/0416.Partition Equal Subset Sum/README_EN.md index 2ddafdf4a6e83..b3a9ceb5c6f8f 100644 --- a/solution/0400-0499/0416.Partition Equal Subset Sum/README_EN.md +++ b/solution/0400-0499/0416.Partition Equal Subset Sum/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,21 +52,6 @@ class Solution: return f[n][m] ``` -```python -class Solution: - def canPartition(self, nums: List[int]) -> bool: - m, mod = divmod(sum(nums), 2) - if mod: - return False - f = [True] + [False] * m - for x in nums: - for j in range(m, x - 1, -1): - f[j] = f[j] or f[j - x] - return f[m] -``` - -### **Java** - ```java class Solution { public boolean canPartition(int[] nums) { @@ -93,32 +78,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canPartition(int[] nums) { - // int s = Arrays.stream(nums).sum(); - int s = 0; - for (int x : nums) { - s += x; - } - if (s % 2 == 1) { - return false; - } - int m = s >> 1; - boolean[] f = new boolean[m + 1]; - f[0] = true; - for (int x : nums) { - for (int j = m; j >= x; --j) { - f[j] |= f[j - x]; - } - } - return f[m]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -143,30 +102,53 @@ public: }; ``` -```cpp -class Solution { -public: - bool canPartition(vector& nums) { - int s = accumulate(nums.begin(), nums.end(), 0); - if (s % 2 == 1) { - return false; - } - int m = s >> 1; - bool f[m + 1]; - memset(f, false, sizeof(f)); - f[0] = true; - for (int& x : nums) { - for (int j = m; j >= x; --j) { - f[j] |= f[j - x]; - } +```go +func canPartition(nums []int) bool { + s := 0 + for _, x := range nums { + s += x + } + if s%2 == 1 { + return false + } + n, m := len(nums), s>>1 + f := make([][]bool, n+1) + for i := range f { + f[i] = make([]bool, m+1) + } + f[0][0] = true + for i := 1; i <= n; i++ { + x := nums[i-1] + for j := 0; j <= m; j++ { + f[i][j] = f[i-1][j] || (j >= x && f[i-1][j-x]) + } + } + return f[n][m] +} +``` + +```ts +function canPartition(nums: number[]): boolean { + const s = nums.reduce((a, b) => a + b, 0); + if (s % 2 === 1) { + return false; + } + const n = nums.length; + const m = s >> 1; + const f: boolean[][] = Array(n + 1) + .fill(0) + .map(() => Array(m + 1).fill(false)); + f[0][0] = true; + for (let i = 1; i <= n; ++i) { + const x = nums[i - 1]; + for (let j = 0; j <= m; ++j) { + f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); } - return f[m]; } -}; + return f[n][m]; +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -203,67 +185,95 @@ impl Solution { } ``` -```rust -impl Solution { - #[allow(dead_code)] - pub fn can_partition(nums: Vec) -> bool { - let mut sum = 0; - for e in &nums { - sum += *e; +```js +/** + * @param {number[]} nums + * @return {boolean} + */ +var canPartition = function (nums) { + const s = nums.reduce((a, b) => a + b, 0); + if (s % 2 === 1) { + return false; + } + const n = nums.length; + const m = s >> 1; + const f = Array(n + 1) + .fill(0) + .map(() => Array(m + 1).fill(false)); + f[0][0] = true; + for (let i = 1; i <= n; ++i) { + const x = nums[i - 1]; + for (let j = 0; j <= m; ++j) { + f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); } + } + return f[n][m]; +}; +``` - if sum % 2 != 0 { - return false; - } + - let m = (sum >> 1) as usize; +### Solution 2 - // Here dp[i] means if it can be sum up to `i` for all the number we've traversed through so far - // Which is actually compressing the 2-D dp vector to 1-D - let mut dp: Vec = vec![false; m + 1]; + - // Initialize the dp vector - dp[0] = true; +```python +class Solution: + def canPartition(self, nums: List[int]) -> bool: + m, mod = divmod(sum(nums), 2) + if mod: + return False + f = [True] + [False] * m + for x in nums: + for j in range(m, x - 1, -1): + f[j] = f[j] or f[j - x] + return f[m] +``` - // Begin the actual dp process - for e in &nums { - // For every num in nums vector - for i in (*e as usize..=m).rev() { - // Update the current status - dp[i] |= dp[i - (*e as usize)]; +```java +class Solution { + public boolean canPartition(int[] nums) { + // int s = Arrays.stream(nums).sum(); + int s = 0; + for (int x : nums) { + s += x; + } + if (s % 2 == 1) { + return false; + } + int m = s >> 1; + boolean[] f = new boolean[m + 1]; + f[0] = true; + for (int x : nums) { + for (int j = m; j >= x; --j) { + f[j] |= f[j - x]; } } - - dp[m] + return f[m]; } } ``` -### **Go** - -```go -func canPartition(nums []int) bool { - s := 0 - for _, x := range nums { - s += x - } - if s%2 == 1 { - return false - } - n, m := len(nums), s>>1 - f := make([][]bool, n+1) - for i := range f { - f[i] = make([]bool, m+1) - } - f[0][0] = true - for i := 1; i <= n; i++ { - x := nums[i-1] - for j := 0; j <= m; j++ { - f[i][j] = f[i-1][j] || (j >= x && f[i-1][j-x]) - } - } - return f[n][m] -} +```cpp +class Solution { +public: + bool canPartition(vector& nums) { + int s = accumulate(nums.begin(), nums.end(), 0); + if (s % 2 == 1) { + return false; + } + int m = s >> 1; + bool f[m + 1]; + memset(f, false, sizeof(f)); + f[0] = true; + for (int& x : nums) { + for (int j = m; j >= x; --j) { + f[j] |= f[j - x]; + } + } + return f[m]; + } +}; ``` ```go @@ -287,30 +297,6 @@ func canPartition(nums []int) bool { } ``` -### **TypeScript** - -```ts -function canPartition(nums: number[]): boolean { - const s = nums.reduce((a, b) => a + b, 0); - if (s % 2 === 1) { - return false; - } - const n = nums.length; - const m = s >> 1; - const f: boolean[][] = Array(n + 1) - .fill(0) - .map(() => Array(m + 1).fill(false)); - f[0][0] = true; - for (let i = 1; i <= n; ++i) { - const x = nums[i - 1]; - for (let j = 0; j <= m; ++j) { - f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); - } - } - return f[n][m]; -} -``` - ```ts function canPartition(nums: number[]): boolean { const s = nums.reduce((a, b) => a + b, 0); @@ -329,32 +315,40 @@ function canPartition(nums: number[]): boolean { } ``` -### **JavaScript** +```rust +impl Solution { + #[allow(dead_code)] + pub fn can_partition(nums: Vec) -> bool { + let mut sum = 0; + for e in &nums { + sum += *e; + } -```js -/** - * @param {number[]} nums - * @return {boolean} - */ -var canPartition = function (nums) { - const s = nums.reduce((a, b) => a + b, 0); - if (s % 2 === 1) { - return false; - } - const n = nums.length; - const m = s >> 1; - const f = Array(n + 1) - .fill(0) - .map(() => Array(m + 1).fill(false)); - f[0][0] = true; - for (let i = 1; i <= n; ++i) { - const x = nums[i - 1]; - for (let j = 0; j <= m; ++j) { - f[i][j] = f[i - 1][j] || (j >= x && f[i - 1][j - x]); + if sum % 2 != 0 { + return false; + } + + let m = (sum >> 1) as usize; + + // Here dp[i] means if it can be sum up to `i` for all the number we've traversed through so far + // Which is actually compressing the 2-D dp vector to 1-D + let mut dp: Vec = vec![false; m + 1]; + + // Initialize the dp vector + dp[0] = true; + + // Begin the actual dp process + for e in &nums { + // For every num in nums vector + for i in (*e as usize..=m).rev() { + // Update the current status + dp[i] |= dp[i - (*e as usize)]; + } } + + dp[m] } - return f[n][m]; -}; +} ``` ```js @@ -379,10 +373,6 @@ var canPartition = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0417.Pacific Atlantic Water Flow/README.md b/solution/0400-0499/0417.Pacific Atlantic Water Flow/README.md index ea1e356f18dc3..d871a7f1743ef 100644 --- a/solution/0400-0499/0417.Pacific Atlantic Water Flow/README.md +++ b/solution/0400-0499/0417.Pacific Atlantic Water Flow/README.md @@ -45,16 +45,10 @@ ## 解法 - - -反向寻找,从海洋开始逆流,只要比该陆地高的地方就能逆流。最后是寻找两个海洋的水流都能经过的陆地即为结果。 +### 方法一 -### **Python3** - - - ```python class Solution: def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: @@ -95,10 +89,6 @@ class Solution: ] ``` -### **Java** - - - ```java class Solution { private int[][] heights; @@ -159,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef pair pii; @@ -224,8 +212,6 @@ public: }; ``` -### **Go** - ```go func pacificAtlantic(heights [][]int) [][]int { m, n := len(heights), len(heights[0]) @@ -276,8 +262,6 @@ func pacificAtlantic(heights [][]int) [][]int { } ``` -### **TypeScript** - ```ts function pacificAtlantic(heights: number[][]): number[][] { const m = heights.length; @@ -331,10 +315,6 @@ function pacificAtlantic(heights: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0417.Pacific Atlantic Water Flow/README_EN.md b/solution/0400-0499/0417.Pacific Atlantic Water Flow/README_EN.md index cd1c50d682b41..807830891b226 100644 --- a/solution/0400-0499/0417.Pacific Atlantic Water Flow/README_EN.md +++ b/solution/0400-0499/0417.Pacific Atlantic Water Flow/README_EN.md @@ -56,9 +56,9 @@ Note that there are other possible paths for these cells to flow to the Pacific ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -100,8 +100,6 @@ class Solution: ] ``` -### **Java** - ```java class Solution { private int[][] heights; @@ -162,8 +160,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef pair pii; @@ -227,8 +223,6 @@ public: }; ``` -### **Go** - ```go func pacificAtlantic(heights [][]int) [][]int { m, n := len(heights), len(heights[0]) @@ -279,8 +273,6 @@ func pacificAtlantic(heights [][]int) [][]int { } ``` -### **TypeScript** - ```ts function pacificAtlantic(heights: number[][]): number[][] { const m = heights.length; @@ -334,10 +326,6 @@ function pacificAtlantic(heights: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0418.Sentence Screen Fitting/README.md b/solution/0400-0499/0418.Sentence Screen Fitting/README.md index f54e633a0259a..4f61c9753f9f6 100644 --- a/solution/0400-0499/0418.Sentence Screen Fitting/README.md +++ b/solution/0400-0499/0418.Sentence Screen Fitting/README.md @@ -77,9 +77,7 @@ had-- ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们将句子的每个单词拼接上一个空格,然后把句子拼接起来,得到字符串 $s$。例如,对于句子 `["hello", "world"]`,得到的字符串为 `"hello world "`。记 $s$ 的长度为 $m$。 @@ -93,10 +91,6 @@ had-- -### **Python3** - - - ```python class Solution: def wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int: @@ -112,10 +106,6 @@ class Solution: return cur // m ``` -### **Java** - - - ```java class Solution { public int wordsTyping(String[] sentence, int rows, int cols) { @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -165,8 +153,6 @@ public: }; ``` -### **Go** - ```go func wordsTyping(sentence []string, rows int, cols int) int { s := strings.Join(sentence, " ") + " " @@ -186,8 +172,6 @@ func wordsTyping(sentence []string, rows int, cols int) int { } ``` -### **TypeScript** - ```ts function wordsTyping(sentence: string[], rows: number, cols: number): number { const s = sentence.join(' ') + ' '; @@ -207,10 +191,6 @@ function wordsTyping(sentence: string[], rows: number, cols: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0418.Sentence Screen Fitting/README_EN.md b/solution/0400-0499/0418.Sentence Screen Fitting/README_EN.md index 6825dad0f49ba..24b57f71e8d13 100644 --- a/solution/0400-0499/0418.Sentence Screen Fitting/README_EN.md +++ b/solution/0400-0499/0418.Sentence Screen Fitting/README_EN.md @@ -57,9 +57,9 @@ The character '-' signifies an empty space on the screen. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return cur // m ``` -### **Java** - ```java class Solution { public int wordsTyping(String[] sentence, int rows, int cols) { @@ -99,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +123,6 @@ public: }; ``` -### **Go** - ```go func wordsTyping(sentence []string, rows int, cols int) int { s := strings.Join(sentence, " ") + " " @@ -148,8 +142,6 @@ func wordsTyping(sentence []string, rows int, cols int) int { } ``` -### **TypeScript** - ```ts function wordsTyping(sentence: string[], rows: number, cols: number): number { const s = sentence.join(' ') + ' '; @@ -169,10 +161,6 @@ function wordsTyping(sentence: string[], rows: number, cols: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0419.Battleships in a Board/README.md b/solution/0400-0499/0419.Battleships in a Board/README.md index 37e641e6d40e0..7006f93f949c9 100644 --- a/solution/0400-0499/0419.Battleships in a Board/README.md +++ b/solution/0400-0499/0419.Battleships in a Board/README.md @@ -43,18 +43,10 @@ ## 解法 - - -初始化结果数 ans = 0。 - -遍历二维甲板,若 X 的左方、上方不为 X,则结果 ans 加 1。 +### 方法一 -### **Python3** - - - ```python class Solution: def countBattleships(self, board: List[List[str]]) -> int: @@ -72,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countBattleships(char[][] board) { @@ -100,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +107,6 @@ public: }; ``` -### **Go** - ```go func countBattleships(board [][]byte) int { m, n := len(board), len(board[0]) @@ -145,10 +129,6 @@ func countBattleships(board [][]byte) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0419.Battleships in a Board/README_EN.md b/solution/0400-0499/0419.Battleships in a Board/README_EN.md index 1c5371d653d7a..4e723b6f2aacf 100644 --- a/solution/0400-0499/0419.Battleships in a Board/README_EN.md +++ b/solution/0400-0499/0419.Battleships in a Board/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countBattleships(char[][] board) { @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +102,6 @@ public: }; ``` -### **Go** - ```go func countBattleships(board [][]byte) int { m, n := len(board), len(board[0]) @@ -130,10 +124,6 @@ func countBattleships(board [][]byte) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0420.Strong Password Checker/README.md b/solution/0400-0499/0420.Strong Password Checker/README.md index 20c7c5e78656d..3e9a8c7b30cd1 100644 --- a/solution/0400-0499/0420.Strong Password Checker/README.md +++ b/solution/0400-0499/0420.Strong Password Checker/README.md @@ -58,14 +58,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def strongPasswordChecker(self, password: str) -> int: @@ -129,10 +125,6 @@ class Solution: return n - 20 + max(replace, 3 - types) ``` -### **Java** - - - ```java class Solution { public int strongPasswordChecker(String password) { @@ -215,8 +207,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -293,10 +283,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0420.Strong Password Checker/README_EN.md b/solution/0400-0499/0420.Strong Password Checker/README_EN.md index 4bbc53398d00c..7b0bab40a3ba7 100644 --- a/solution/0400-0499/0420.Strong Password Checker/README_EN.md +++ b/solution/0400-0499/0420.Strong Password Checker/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -110,8 +110,6 @@ class Solution: return n - 20 + max(replace, 3 - types) ``` -### **Java** - ```java class Solution { public int strongPasswordChecker(String password) { @@ -194,8 +192,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -272,10 +268,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/README.md b/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/README.md index f5530e3293296..46cb331c184e0 100644 --- a/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/README.md +++ b/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:前缀树** +### 方法一:前缀树 题目是求两个元素的异或最大值,可以从最高位开始考虑。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Trie: __slots__ = ("children",) @@ -93,10 +87,6 @@ class Solution: return max(trie.search(x) for x in nums) ``` -### **Java** - - - ```java class Trie { private Trie[] children = new Trie[2]; @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -195,8 +183,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [2]*Trie @@ -242,8 +228,6 @@ func findMaximumXOR(nums []int) (ans int) { } ``` -### **Rust** - ```rust struct Trie { children: [Option>; 2], @@ -296,10 +280,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/README_EN.md b/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/README_EN.md index c7af2fa61f0e0..36655e56b82f4 100644 --- a/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/README_EN.md +++ b/solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/README_EN.md @@ -32,9 +32,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -72,8 +72,6 @@ class Solution: return max(trie.search(x) for x in nums) ``` -### **Java** - ```java class Trie { private Trie[] children = new Trie[2]; @@ -121,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -172,8 +168,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [2]*Trie @@ -219,8 +213,6 @@ func findMaximumXOR(nums []int) (ans int) { } ``` -### **Rust** - ```rust struct Trie { children: [Option>; 2], @@ -273,10 +265,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0422.Valid Word Square/README.md b/solution/0400-0499/0422.Valid Word Square/README.md index 8bc4590d1adf1..601dd2b5a68ac 100644 --- a/solution/0400-0499/0422.Valid Word Square/README.md +++ b/solution/0400-0499/0422.Valid Word Square/README.md @@ -91,9 +91,7 @@ false ## 解法 - - -**方法一:遍历检查** +### 方法一:遍历检查 我们观察发现,只要不满足 $words[i][j] = words[j][i]$,就可以直接返回 `false`。 @@ -103,10 +101,6 @@ false -### **Python3** - - - ```python class Solution: def validWordSquare(self, words: List[str]) -> bool: @@ -120,21 +114,6 @@ class Solution: return True ``` -```python -class Solution: - def validWordSquare(self, words: List[str]) -> bool: - m = len(words) - for i, w in enumerate(words): - for j, c in enumerate(w): - if j >= m or i >= len(words[j]) or c != words[j][i]: - return False - return True -``` - -### **Java** - - - ```java class Solution { public boolean validWordSquare(List words) { @@ -155,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +152,6 @@ public: }; ``` -### **Go** - ```go func validWordSquare(words []string) bool { m := len(words) @@ -191,8 +166,6 @@ func validWordSquare(words []string) bool { } ``` -### **TypeScript** - ```ts function validWordSquare(words: string[]): boolean { const m = words.length; @@ -208,10 +181,23 @@ function validWordSquare(words: string[]): boolean { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def validWordSquare(self, words: List[str]) -> bool: + m = len(words) + for i, w in enumerate(words): + for j, c in enumerate(w): + if j >= m or i >= len(words[j]) or c != words[j][i]: + return False + return True ``` + + diff --git a/solution/0400-0499/0422.Valid Word Square/README_EN.md b/solution/0400-0499/0422.Valid Word Square/README_EN.md index 3db2876eb80d2..cf7b0b8f861d6 100644 --- a/solution/0400-0499/0422.Valid Word Square/README_EN.md +++ b/solution/0400-0499/0422.Valid Word Square/README_EN.md @@ -56,9 +56,9 @@ Therefore, it is NOT a valid word square. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,19 +73,6 @@ class Solution: return True ``` -```python -class Solution: - def validWordSquare(self, words: List[str]) -> bool: - m = len(words) - for i, w in enumerate(words): - for j, c in enumerate(w): - if j >= m or i >= len(words[j]) or c != words[j][i]: - return False - return True -``` - -### **Java** - ```java class Solution { public boolean validWordSquare(List words) { @@ -106,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +111,6 @@ public: }; ``` -### **Go** - ```go func validWordSquare(words []string) bool { m := len(words) @@ -142,8 +125,6 @@ func validWordSquare(words []string) bool { } ``` -### **TypeScript** - ```ts function validWordSquare(words: string[]): boolean { const m = words.length; @@ -159,10 +140,23 @@ function validWordSquare(words: string[]): boolean { } ``` -### **...** + + +### Solution 2 -``` + +```python +class Solution: + def validWordSquare(self, words: List[str]) -> bool: + m = len(words) + for i, w in enumerate(words): + for j, c in enumerate(w): + if j >= m or i >= len(words[j]) or c != words[j][i]: + return False + return True ``` + + diff --git a/solution/0400-0499/0423.Reconstruct Original Digits from English/README.md b/solution/0400-0499/0423.Reconstruct Original Digits from English/README.md index ecaecef424753..3213674cba84f 100644 --- a/solution/0400-0499/0423.Reconstruct Original Digits from English/README.md +++ b/solution/0400-0499/0423.Reconstruct Original Digits from English/README.md @@ -36,36 +36,10 @@ ## 解法 - - -统计 `["e","g","f","i","h","o","n","s","r","u","t","w","v","x","z"]` 每个字母在哪些数字出现过。 - -| 字母 | 数字 | -| ---- | ------------- | -| e | 0 1 3 5 7 8 9 | -| g | 8 | -| f | 4 5 | -| i | 5 6 8 9 | -| h | 3 8 | -| o | 0 1 2 4 | -| n | 1 7 9 | -| s | 6 7 | -| r | 0 3 4 | -| u | 4 | -| t | 2 3 8 | -| w | 2 | -| v | 5 7 | -| x | 6 | -| z | 0 | - -由于部分字母只在某个数字出现过,比如字母 `z` 只在 `0` 出现过,因此我们统计英文中 `z` 的数量,就可以推断数字 0 的个数,依次类推。 +### 方法一 -### **Python3** - - - ```python class Solution: def originalDigits(self, s: str) -> str: @@ -88,10 +62,6 @@ class Solution: return ''.join(cnt[i] * str(i) for i in range(10)) ``` -### **Java** - - - ```java class Solution { public String originalDigits(String s) { @@ -124,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +123,6 @@ public: }; ``` -### **Go** - ```go func originalDigits(s string) string { counter := make([]int, 26) @@ -185,10 +151,6 @@ func originalDigits(s string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0423.Reconstruct Original Digits from English/README_EN.md b/solution/0400-0499/0423.Reconstruct Original Digits from English/README_EN.md index 20e35ef9fa397..d5d8b15a636b0 100644 --- a/solution/0400-0499/0423.Reconstruct Original Digits from English/README_EN.md +++ b/solution/0400-0499/0423.Reconstruct Original Digits from English/README_EN.md @@ -25,9 +25,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return ''.join(cnt[i] * str(i) for i in range(10)) ``` -### **Java** - ```java class Solution { public String originalDigits(String s) { @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +112,6 @@ public: }; ``` -### **Go** - ```go func originalDigits(s string) string { counter := make([]int, 26) @@ -146,10 +140,6 @@ func originalDigits(s string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0424.Longest Repeating Character Replacement/README.md b/solution/0400-0499/0424.Longest Repeating Character Replacement/README.md index 8585986899f5d..abb5197e33b45 100644 --- a/solution/0400-0499/0424.Longest Repeating Character Replacement/README.md +++ b/solution/0400-0499/0424.Longest Repeating Character Replacement/README.md @@ -43,21 +43,10 @@ ## 解法 - - -我们维护一个数组 `int[26]` 来存储当前窗口中各个字母的出现次数,j 表示窗口的左边界,i 表示窗口右边界。 - -- 窗口扩张:j 不变,i++ -- 窗口滑动:j++,i++ - -`maxCnt` 保存滑动窗口内相同字母出现次数的**历史最大值**,通过判断窗口宽度 `i - j + 1` 是否大于 `maxCnt + k` 来决定窗口是否做滑动,否则窗口就扩张。 +### 方法一 -### **Python3** - - - ```python class Solution: def characterReplacement(self, s: str, k: int) -> int: @@ -73,10 +62,6 @@ class Solution: return i - j ``` -### **Java** - - - ```java class Solution { public int characterReplacement(String s, int k) { @@ -97,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +102,6 @@ public: }; ``` -### **Go** - ```go func characterReplacement(s string, k int) int { counter := make([]int, 26) @@ -140,10 +121,6 @@ func characterReplacement(s string, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0424.Longest Repeating Character Replacement/README_EN.md b/solution/0400-0499/0424.Longest Repeating Character Replacement/README_EN.md index 0ac68e949ab2b..844b8319919e1 100644 --- a/solution/0400-0499/0424.Longest Repeating Character Replacement/README_EN.md +++ b/solution/0400-0499/0424.Longest Repeating Character Replacement/README_EN.md @@ -37,9 +37,9 @@ There may exists other ways to achieve this answer too. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return i - j ``` -### **Java** - ```java class Solution { public int characterReplacement(String s, int k) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +96,6 @@ public: }; ``` -### **Go** - ```go func characterReplacement(s string, k int) int { counter := make([]int, 26) @@ -121,10 +115,6 @@ func characterReplacement(s string, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0425.Word Squares/README.md b/solution/0400-0499/0425.Word Squares/README.md index a26d1ef5d4b46..66d4f87f68880 100644 --- a/solution/0400-0499/0425.Word Squares/README.md +++ b/solution/0400-0499/0425.Word Squares/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:前缀树 + DFS** +### 方法一:前缀树 + DFS 根据已添加单词确定下一个单词的前缀,继续进行搜索。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Trie: def __init__(self): @@ -112,10 +106,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Trie { Trie[] children = new Trie[26]; @@ -186,8 +176,6 @@ class Solution { } ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -253,10 +241,6 @@ func wordSquares(words []string) [][]string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0425.Word Squares/README_EN.md b/solution/0400-0499/0425.Word Squares/README_EN.md index f2b7d9cd0cc0a..e4b1587ed8614 100644 --- a/solution/0400-0499/0425.Word Squares/README_EN.md +++ b/solution/0400-0499/0425.Word Squares/README_EN.md @@ -44,9 +44,9 @@ The output consists of two word squares. The order of output does not matter (ju ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -96,8 +96,6 @@ class Solution: return ans ``` -### **Java** - ```java class Trie { Trie[] children = new Trie[26]; @@ -168,8 +166,6 @@ class Solution { } ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -235,10 +231,6 @@ func wordSquares(words []string) [][]string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/README.md b/solution/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/README.md index cf4024f2c97bc..999e2e29d77ef 100644 --- a/solution/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/README.md +++ b/solution/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/README.md @@ -61,18 +61,10 @@ ## 解法 - - -- 排序链表:二叉搜索树中序遍历得到有序序列 -- 循环链表:头节点指向链表尾节点,尾节点指向链表头节点 -- 双向链表:`prev.right = cur`、`cur.left = prev`、`prev = cur` +### 方法一 -### **Python3** - - - ```python """ # Definition for a Node. @@ -108,10 +100,6 @@ class Solution: return head ``` -### **Java** - - - ```java /* // Definition for a Node. @@ -167,8 +155,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -223,8 +209,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -263,8 +247,6 @@ func treeToDoublyList(root *Node) *Node { } ``` -### **JavaScript** - ```js /** * // Definition for a Node. @@ -303,10 +285,6 @@ var treeToDoublyList = function (root) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/README_EN.md b/solution/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/README_EN.md index df2dd8703fe46..df19f27e0471a 100644 --- a/solution/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/README_EN.md +++ b/solution/0400-0499/0426.Convert Binary Search Tree to Sorted Doubly Linked List/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -82,8 +82,6 @@ class Solution: return head ``` -### **Java** - ```java /* // Definition for a Node. @@ -139,8 +137,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -195,8 +191,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -235,8 +229,6 @@ func treeToDoublyList(root *Node) *Node { } ``` -### **JavaScript** - ```js /** * // Definition for a Node. @@ -275,10 +267,6 @@ var treeToDoublyList = function (root) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0427.Construct Quad Tree/README.md b/solution/0400-0499/0427.Construct Quad Tree/README.md index 2e72ceab710b8..e72e2f2750974 100644 --- a/solution/0400-0499/0427.Construct Quad Tree/README.md +++ b/solution/0400-0499/0427.Construct Quad Tree/README.md @@ -86,18 +86,12 @@ topRight 具有不同的值,因此我们将其再分为 4 个子网格,这 ## 解法 - - -**方法一:DFS** +### 方法一:DFS DFS 递归遍历 grid,先判断 grid 是否为叶子节点,是则返回叶子节点相关信息;否则递归 grid 4 个子节点。 -### **Python3** - - - ```python """ # Definition for a QuadTree node. @@ -135,10 +129,6 @@ class Solution: return dfs(0, 0, len(grid) - 1, len(grid[0]) - 1) ``` -### **Java** - - - ```java /* // Definition for a QuadTree node. @@ -207,8 +197,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a QuadTree node. @@ -279,8 +267,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a QuadTree node. @@ -323,10 +309,6 @@ func construct(grid [][]int) *Node { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0427.Construct Quad Tree/README_EN.md b/solution/0400-0499/0427.Construct Quad Tree/README_EN.md index c7eced5d340e5..e3a9d0350ae8c 100644 --- a/solution/0400-0499/0427.Construct Quad Tree/README_EN.md +++ b/solution/0400-0499/0427.Construct Quad Tree/README_EN.md @@ -78,9 +78,9 @@ Explanation is shown in the photo below: ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -119,8 +119,6 @@ class Solution: return dfs(0, 0, len(grid) - 1, len(grid[0]) - 1) ``` -### **Java** - ```java /* // Definition for a QuadTree node. @@ -189,8 +187,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a QuadTree node. @@ -261,8 +257,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a QuadTree node. @@ -305,10 +299,6 @@ func construct(grid [][]int) *Node { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0428.Serialize and Deserialize N-ary Tree/README.md b/solution/0400-0499/0428.Serialize and Deserialize N-ary Tree/README.md index f61dcb43d53d7..f0532f7382ef0 100644 --- a/solution/0400-0499/0428.Serialize and Deserialize N-ary Tree/README.md +++ b/solution/0400-0499/0428.Serialize and Deserialize N-ary Tree/README.md @@ -64,30 +64,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0400-0499/0428.Serialize and Deserialize N-ary Tree/README_EN.md b/solution/0400-0499/0428.Serialize and Deserialize N-ary Tree/README_EN.md index 55e51c260717c..20018fadebed7 100644 --- a/solution/0400-0499/0428.Serialize and Deserialize N-ary Tree/README_EN.md +++ b/solution/0400-0499/0428.Serialize and Deserialize N-ary Tree/README_EN.md @@ -56,24 +56,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0400-0499/0429.N-ary Tree Level Order Traversal/README.md b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/README.md index 50b0db2c70a47..d8fcb87b6e9ee 100644 --- a/solution/0400-0499/0429.N-ary Tree Level Order Traversal/README.md +++ b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/README.md @@ -41,30 +41,14 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 借助队列,逐层遍历。 时间复杂度 $O(n)$。 -**方法二:DFS** - -按深度遍历。 - -假设当前深度为 i,遍历到的节点为 root。若结果列表 `ans[i]` 不存在,则创建一个空列表放入 ans 中,然后将 `root.val` 放入 `ans[i]`。接着往下一层遍历(root 的子节点)。 - -时间复杂度 $O(n)$。 - -### **Python3** - - - -BFS: - ```python """ # Definition for a Node. @@ -91,40 +75,6 @@ class Solution: return ans ``` -DFS: - -```python -""" -# Definition for a Node. -class Node: - def __init__(self, val=None, children=None): - self.val = val - self.children = children -""" - - -class Solution: - def levelOrder(self, root: 'Node') -> List[List[int]]: - def dfs(root, i): - if root is None: - return - if len(ans) <= i: - ans.append([]) - ans[i].append(root.val) - for child in root.children: - dfs(child, i + 1) - - ans = [] - dfs(root, 0) - return ans -``` - -### **Java** - - - -BFS: - ```java /* // Definition for a Node. @@ -167,22 +117,21 @@ class Solution { } ``` -DFS: - -```java +```cpp /* // Definition for a Node. class Node { - public int val; - public List children; +public: + int val; + vector children; - public Node() {} + Node() {} - public Node(int _val) { + Node(int _val) { val = _val; } - public Node(int _val, List _children) { + Node(int _val, vector _children) { val = _val; children = _children; } @@ -190,46 +139,142 @@ class Node { */ class Solution { - public List> levelOrder(Node root) { - List> ans = new ArrayList<>(); - dfs(root, 0, ans); +public: + vector> levelOrder(Node* root) { + vector> ans; + if (!root) return ans; + queue q{{root}}; + while (!q.empty()) { + vector t; + for (int n = q.size(); n > 0; --n) { + root = q.front(); + q.pop(); + t.push_back(root->val); + for (auto& child : root->children) q.push(child); + } + ans.push_back(t); + } return ans; } +}; +``` - private void dfs(Node root, int i, List> ans) { - if (root == null) { - return; - } - if (ans.size() <= i) { - ans.add(new ArrayList<>()); - } - ans.get(i++).add(root.val); - for (Node child : root.children) { - dfs(child, i, ans); +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Children []*Node + * } + */ + +func levelOrder(root *Node) [][]int { + var ans [][]int + if root == nil { + return ans + } + q := []*Node{root} + for len(q) > 0 { + var t []int + for n := len(q); n > 0; n-- { + root = q[0] + q = q[1:] + t = append(t, root.Val) + for _, child := range root.Children { + q = append(q, child) + } + } + ans = append(ans, t) + } + return ans +} +``` + +```ts +/** + * Definition for node. + * class Node { + * val: number + * children: Node[] + * constructor(val?: number) { + * this.val = (val===undefined ? 0 : val) + * this.children = [] + * } + * } + */ + +function levelOrder(root: Node | null): number[][] { + const res = []; + if (root == null) { + return res; + } + const queue = [root]; + while (queue.length !== 0) { + const n = queue.length; + const vals = []; + for (let i = 0; i < n; i++) { + const { val, children } = queue.shift(); + vals.push(val); + queue.push(...children); } + res.push(vals); } + return res; } ``` -### **C++** + -BFS: +### 方法二:DFS -```cpp +按深度遍历。 + +假设当前深度为 i,遍历到的节点为 root。若结果列表 `ans[i]` 不存在,则创建一个空列表放入 ans 中,然后将 `root.val` 放入 `ans[i]`。接着往下一层遍历(root 的子节点)。 + +时间复杂度 $O(n)$。 + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + + +class Solution: + def levelOrder(self, root: 'Node') -> List[List[int]]: + def dfs(root, i): + if root is None: + return + if len(ans) <= i: + ans.append([]) + ans[i].append(root.val) + for child in root.children: + dfs(child, i + 1) + + ans = [] + dfs(root, 0) + return ans +``` + +```java /* // Definition for a Node. class Node { -public: - int val; - vector children; + public int val; + public List children; - Node() {} + public Node() {} - Node(int _val) { + public Node(int _val) { val = _val; } - Node(int _val, vector _children) { + public Node(int _val, List _children) { val = _val; children = _children; } @@ -237,27 +282,26 @@ public: */ class Solution { -public: - vector> levelOrder(Node* root) { - vector> ans; - if (!root) return ans; - queue q{{root}}; - while (!q.empty()) { - vector t; - for (int n = q.size(); n > 0; --n) { - root = q.front(); - q.pop(); - t.push_back(root->val); - for (auto& child : root->children) q.push(child); - } - ans.push_back(t); - } + public List> levelOrder(Node root) { + List> ans = new ArrayList<>(); + dfs(root, 0, ans); return ans; } -}; -``` -DFS: + private void dfs(Node root, int i, List> ans) { + if (root == null) { + return; + } + if (ans.size() <= i) { + ans.add(new ArrayList<>()); + } + ans.get(i++).add(root.val); + for (Node child : root.children) { + dfs(child, i, ans); + } + } +} +``` ```cpp /* @@ -297,43 +341,6 @@ public: }; ``` -### **Go** - -BFS: - -```go -/** - * Definition for a Node. - * type Node struct { - * Val int - * Children []*Node - * } - */ - -func levelOrder(root *Node) [][]int { - var ans [][]int - if root == nil { - return ans - } - q := []*Node{root} - for len(q) > 0 { - var t []int - for n := len(q); n > 0; n-- { - root = q[0] - q = q[1:] - t = append(t, root.Val) - for _, child := range root.Children { - q = append(q, child) - } - } - ans = append(ans, t) - } - return ans -} -``` - -DFS: - ```go /** * Definition for a Node. @@ -363,45 +370,6 @@ func levelOrder(root *Node) [][]int { } ``` -### **TypeScript** - -BFS: - -```ts -/** - * Definition for node. - * class Node { - * val: number - * children: Node[] - * constructor(val?: number) { - * this.val = (val===undefined ? 0 : val) - * this.children = [] - * } - * } - */ - -function levelOrder(root: Node | null): number[][] { - const res = []; - if (root == null) { - return res; - } - const queue = [root]; - while (queue.length !== 0) { - const n = queue.length; - const vals = []; - for (let i = 0; i < n; i++) { - const { val, children } = queue.shift(); - vals.push(val); - queue.push(...children); - } - res.push(vals); - } - return res; -} -``` - -DFS: - ```ts /** * Definition for node. @@ -433,10 +401,6 @@ function levelOrder(root: Node | null): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0429.N-ary Tree Level Order Traversal/README_EN.md b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/README_EN.md index a48e788414ed9..52ed6c053de35 100644 --- a/solution/0400-0499/0429.N-ary Tree Level Order Traversal/README_EN.md +++ b/solution/0400-0499/0429.N-ary Tree Level Order Traversal/README_EN.md @@ -37,14 +37,10 @@ ## Solutions -BFS or DFS. +### Solution 1 -### **Python3** - -BFS: - ```python """ # Definition for a Node. @@ -71,38 +67,6 @@ class Solution: return ans ``` -DFS: - -```python -""" -# Definition for a Node. -class Node: - def __init__(self, val=None, children=None): - self.val = val - self.children = children -""" - - -class Solution: - def levelOrder(self, root: 'Node') -> List[List[int]]: - def dfs(root, i): - if root is None: - return - if len(ans) <= i: - ans.append([]) - ans[i].append(root.val) - for child in root.children: - dfs(child, i + 1) - - ans = [] - dfs(root, 0) - return ans -``` - -### **Java** - -BFS: - ```java /* // Definition for a Node. @@ -145,22 +109,21 @@ class Solution { } ``` -DFS: - -```java +```cpp /* // Definition for a Node. class Node { - public int val; - public List children; +public: + int val; + vector children; - public Node() {} + Node() {} - public Node(int _val) { + Node(int _val) { val = _val; } - public Node(int _val, List _children) { + Node(int _val, vector _children) { val = _val; children = _children; } @@ -168,46 +131,136 @@ class Node { */ class Solution { - public List> levelOrder(Node root) { - List> ans = new ArrayList<>(); - dfs(root, 0, ans); +public: + vector> levelOrder(Node* root) { + vector> ans; + if (!root) return ans; + queue q{{root}}; + while (!q.empty()) { + vector t; + for (int n = q.size(); n > 0; --n) { + root = q.front(); + q.pop(); + t.push_back(root->val); + for (auto& child : root->children) q.push(child); + } + ans.push_back(t); + } return ans; } +}; +``` - private void dfs(Node root, int i, List> ans) { - if (root == null) { - return; - } - if (ans.size() <= i) { - ans.add(new ArrayList<>()); - } - ans.get(i++).add(root.val); - for (Node child : root.children) { - dfs(child, i, ans); +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Children []*Node + * } + */ + +func levelOrder(root *Node) [][]int { + var ans [][]int + if root == nil { + return ans + } + q := []*Node{root} + for len(q) > 0 { + var t []int + for n := len(q); n > 0; n-- { + root = q[0] + q = q[1:] + t = append(t, root.Val) + for _, child := range root.Children { + q = append(q, child) + } + } + ans = append(ans, t) + } + return ans +} +``` + +```ts +/** + * Definition for node. + * class Node { + * val: number + * children: Node[] + * constructor(val?: number) { + * this.val = (val===undefined ? 0 : val) + * this.children = [] + * } + * } + */ + +function levelOrder(root: Node | null): number[][] { + const res = []; + if (root == null) { + return res; + } + const queue = [root]; + while (queue.length !== 0) { + const n = queue.length; + const vals = []; + for (let i = 0; i < n; i++) { + const { val, children } = queue.shift(); + vals.push(val); + queue.push(...children); } + res.push(vals); } + return res; } ``` -### **C++** + -BFS: +### Solution 2 -```cpp + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + + +class Solution: + def levelOrder(self, root: 'Node') -> List[List[int]]: + def dfs(root, i): + if root is None: + return + if len(ans) <= i: + ans.append([]) + ans[i].append(root.val) + for child in root.children: + dfs(child, i + 1) + + ans = [] + dfs(root, 0) + return ans +``` + +```java /* // Definition for a Node. class Node { -public: - int val; - vector children; + public int val; + public List children; - Node() {} + public Node() {} - Node(int _val) { + public Node(int _val) { val = _val; } - Node(int _val, vector _children) { + public Node(int _val, List _children) { val = _val; children = _children; } @@ -215,27 +268,26 @@ public: */ class Solution { -public: - vector> levelOrder(Node* root) { - vector> ans; - if (!root) return ans; - queue q{{root}}; - while (!q.empty()) { - vector t; - for (int n = q.size(); n > 0; --n) { - root = q.front(); - q.pop(); - t.push_back(root->val); - for (auto& child : root->children) q.push(child); - } - ans.push_back(t); - } + public List> levelOrder(Node root) { + List> ans = new ArrayList<>(); + dfs(root, 0, ans); return ans; } -}; -``` -DFS: + private void dfs(Node root, int i, List> ans) { + if (root == null) { + return; + } + if (ans.size() <= i) { + ans.add(new ArrayList<>()); + } + ans.get(i++).add(root.val); + for (Node child : root.children) { + dfs(child, i, ans); + } + } +} +``` ```cpp /* @@ -275,43 +327,6 @@ public: }; ``` -### **Go** - -BFS: - -```go -/** - * Definition for a Node. - * type Node struct { - * Val int - * Children []*Node - * } - */ - -func levelOrder(root *Node) [][]int { - var ans [][]int - if root == nil { - return ans - } - q := []*Node{root} - for len(q) > 0 { - var t []int - for n := len(q); n > 0; n-- { - root = q[0] - q = q[1:] - t = append(t, root.Val) - for _, child := range root.Children { - q = append(q, child) - } - } - ans = append(ans, t) - } - return ans -} -``` - -DFS: - ```go /** * Definition for a Node. @@ -341,45 +356,6 @@ func levelOrder(root *Node) [][]int { } ``` -### **TypeScript** - -BFS: - -```ts -/** - * Definition for node. - * class Node { - * val: number - * children: Node[] - * constructor(val?: number) { - * this.val = (val===undefined ? 0 : val) - * this.children = [] - * } - * } - */ - -function levelOrder(root: Node | null): number[][] { - const res = []; - if (root == null) { - return res; - } - const queue = [root]; - while (queue.length !== 0) { - const n = queue.length; - const vals = []; - for (let i = 0; i < n; i++) { - const { val, children } = queue.shift(); - vals.push(val); - queue.push(...children); - } - res.push(vals); - } - return res; -} -``` - -DFS: - ```ts /** * Definition for node. @@ -411,10 +387,6 @@ function levelOrder(root: Node | null): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0430.Flatten a Multilevel Doubly Linked List/README.md b/solution/0400-0499/0430.Flatten a Multilevel Doubly Linked List/README.md index 2b9f395f9310c..bdb01fdb2618b 100644 --- a/solution/0400-0499/0430.Flatten a Multilevel Doubly Linked List/README.md +++ b/solution/0400-0499/0430.Flatten a Multilevel Doubly Linked List/README.md @@ -95,14 +95,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python """ # Definition for a Node. @@ -136,10 +132,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /* // Definition for a Node. @@ -178,8 +170,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -230,10 +220,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0430.Flatten a Multilevel Doubly Linked List/README_EN.md b/solution/0400-0499/0430.Flatten a Multilevel Doubly Linked List/README_EN.md index 4230e24120e3a..ea81998cd98f3 100644 --- a/solution/0400-0499/0430.Flatten a Multilevel Doubly Linked List/README_EN.md +++ b/solution/0400-0499/0430.Flatten a Multilevel Doubly Linked List/README_EN.md @@ -85,9 +85,9 @@ After flattening the multilevel linked list it becomes: ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -122,8 +122,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /* // Definition for a Node. @@ -162,8 +160,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -214,10 +210,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0431.Encode N-ary Tree to Binary Tree/README.md b/solution/0400-0499/0431.Encode N-ary Tree to Binary Tree/README.md index 1e1ee9918a5b4..f028ed751afd6 100644 --- a/solution/0400-0499/0431.Encode N-ary Tree to Binary Tree/README.md +++ b/solution/0400-0499/0431.Encode N-ary Tree to Binary Tree/README.md @@ -27,30 +27,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0400-0499/0431.Encode N-ary Tree to Binary Tree/README_EN.md b/solution/0400-0499/0431.Encode N-ary Tree to Binary Tree/README_EN.md index 3b4d7bca250d1..26784517b53f2 100644 --- a/solution/0400-0499/0431.Encode N-ary Tree to Binary Tree/README_EN.md +++ b/solution/0400-0499/0431.Encode N-ary Tree to Binary Tree/README_EN.md @@ -41,24 +41,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0400-0499/0432.All O`one Data Structure/README.md b/solution/0400-0499/0432.All O`one Data Structure/README.md index 936f0e295a055..5d05ac51f9c65 100644 --- a/solution/0400-0499/0432.All O`one Data Structure/README.md +++ b/solution/0400-0499/0432.All O`one Data Structure/README.md @@ -55,14 +55,10 @@ allOne.getMinKey(); // 返回 "leet" ## 解法 - +### 方法一 -### **Python3** - - - ```python class Node: def __init__(self, key='', cnt=0): @@ -141,10 +137,6 @@ class AllOne: # param_4 = obj.getMinKey() ``` -### **Java** - - - ```java class AllOne { Node root = new Node(); @@ -247,10 +239,6 @@ class Node { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0432.All O`one Data Structure/README_EN.md b/solution/0400-0499/0432.All O`one Data Structure/README_EN.md index 1463baa32414a..7e3e826fee7db 100644 --- a/solution/0400-0499/0432.All O`one Data Structure/README_EN.md +++ b/solution/0400-0499/0432.All O`one Data Structure/README_EN.md @@ -51,9 +51,9 @@ allOne.getMinKey(); // return "leet" ## Solutions - +### Solution 1 -### **Python3** + ```python class Node: @@ -133,8 +133,6 @@ class AllOne: # param_4 = obj.getMinKey() ``` -### **Java** - ```java class AllOne { Node root = new Node(); @@ -237,10 +235,6 @@ class Node { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0433.Minimum Genetic Mutation/README.md b/solution/0400-0499/0433.Minimum Genetic Mutation/README.md index 1731953b72e8d..a9fe8c95ddc24 100644 --- a/solution/0400-0499/0433.Minimum Genetic Mutation/README.md +++ b/solution/0400-0499/0433.Minimum Genetic Mutation/README.md @@ -57,18 +57,10 @@ ## 解法 - - -**方法一:BFS** - -**方法二:DFS** +### 方法一:BFS -### **Python3** - - - ```python class Solution: def minMutation(self, start: str, end: str, bank: List[str]) -> int: @@ -88,32 +80,6 @@ class Solution: return -1 ``` -```python -class Solution: - def minMutation(self, start: str, end: str, bank: List[str]) -> int: - def dfs(start, t): - if start == end: - nonlocal ans - ans = min(ans, t) - return - for i, x in enumerate(start): - for y in 'ACGT': - if x != y: - nxt = start[:i] + y + start[i + 1 :] - if nxt in s: - s.remove(nxt) - dfs(nxt, t + 1) - - s = set(bank) - ans = inf - dfs(start, 0) - return -1 if ans == inf else ans -``` - -### **Java** - - - ```java class Solution { public int minMutation(String start, String end, String[] bank) { @@ -150,46 +116,6 @@ class Solution { } ``` -```java -class Solution { - private int ans; - private Set s; - private static final char[] seq = {'A', 'C', 'G', 'T'}; - - public int minMutation(String start, String end, String[] bank) { - s = new HashSet<>(); - for (String b : bank) { - s.add(b); - } - ans = Integer.MAX_VALUE; - dfs(start, end, 0); - s.remove(start); - return ans == Integer.MAX_VALUE ? -1 : ans; - } - - private void dfs(String start, String end, int t) { - if (start.equals(end)) { - ans = Math.min(ans, t); - return; - } - for (int i = 0; i < start.length(); ++i) { - for (char c : seq) { - if (start.charAt(i) == c) { - continue; - } - String nxt = start.substring(0, i) + c + start.substring(i + 1); - if (s.contains(nxt)) { - s.remove(nxt); - dfs(nxt, end, t + 1); - } - } - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -224,42 +150,6 @@ public: }; ``` -```cpp -class Solution { -public: - int ans; - string seq = "ACGT"; - - int minMutation(string start, string end, vector& bank) { - unordered_set s; - for (auto& b : bank) s.insert(b); - ans = INT_MAX; - s.erase(start); - dfs(start, end, s, 0); - return ans == INT_MAX ? -1 : ans; - } - - void dfs(string& start, string& end, unordered_set& s, int t) { - if (start == end) { - ans = min(ans, t); - return; - } - for (int i = 0; i < start.size(); ++i) { - for (char& c : seq) { - if (start[i] == c) continue; - string nxt = start.substr(0, i) + c + start.substr(i + 1, start.size() - i - 1); - if (s.count(nxt)) { - s.erase(nxt); - dfs(nxt, end, s, t + 1); - } - } - } - } -}; -``` - -### **Go** - ```go func minMutation(start string, end string, bank []string) int { s := make(map[string]bool) @@ -297,46 +187,6 @@ func minMutation(start string, end string, bank []string) int { } ``` -```go -func minMutation(start string, end string, bank []string) int { - s := make(map[string]bool) - for _, b := range bank { - s[b] = true - } - ans := math.MaxInt32 - s[start] = false - seq := []rune{'A', 'C', 'G', 'T'} - var dfs func(start string, t int) - dfs = func(start string, t int) { - if start == end { - if ans > t { - ans = t - } - return - } - for i, x := range start { - for _, y := range seq { - if x == y { - continue - } - nxt := start[:i] + string(y) + start[i+1:] - if s[nxt] { - s[nxt] = false - dfs(nxt, t+1) - } - } - } - } - dfs(start, 0) - if ans == math.MaxInt32 { - return -1 - } - return ans -} -``` - -### **TypeScript** - ```ts function minMutation(start: string, end: string, bank: string[]): number { const queue = [start]; @@ -368,8 +218,6 @@ function minMutation(start: string, end: string, bank: string[]): number { } ``` -### **Rust** - ```rust use std::collections::VecDeque; impl Solution { @@ -405,10 +253,144 @@ impl Solution { } ``` -### **...** + +### 方法二:DFS + + + +```python +class Solution: + def minMutation(self, start: str, end: str, bank: List[str]) -> int: + def dfs(start, t): + if start == end: + nonlocal ans + ans = min(ans, t) + return + for i, x in enumerate(start): + for y in 'ACGT': + if x != y: + nxt = start[:i] + y + start[i + 1 :] + if nxt in s: + s.remove(nxt) + dfs(nxt, t + 1) + + s = set(bank) + ans = inf + dfs(start, 0) + return -1 if ans == inf else ans ``` +```java +class Solution { + private int ans; + private Set s; + private static final char[] seq = {'A', 'C', 'G', 'T'}; + + public int minMutation(String start, String end, String[] bank) { + s = new HashSet<>(); + for (String b : bank) { + s.add(b); + } + ans = Integer.MAX_VALUE; + dfs(start, end, 0); + s.remove(start); + return ans == Integer.MAX_VALUE ? -1 : ans; + } + + private void dfs(String start, String end, int t) { + if (start.equals(end)) { + ans = Math.min(ans, t); + return; + } + for (int i = 0; i < start.length(); ++i) { + for (char c : seq) { + if (start.charAt(i) == c) { + continue; + } + String nxt = start.substring(0, i) + c + start.substring(i + 1); + if (s.contains(nxt)) { + s.remove(nxt); + dfs(nxt, end, t + 1); + } + } + } + } +} +``` + +```cpp +class Solution { +public: + int ans; + string seq = "ACGT"; + + int minMutation(string start, string end, vector& bank) { + unordered_set s; + for (auto& b : bank) s.insert(b); + ans = INT_MAX; + s.erase(start); + dfs(start, end, s, 0); + return ans == INT_MAX ? -1 : ans; + } + + void dfs(string& start, string& end, unordered_set& s, int t) { + if (start == end) { + ans = min(ans, t); + return; + } + for (int i = 0; i < start.size(); ++i) { + for (char& c : seq) { + if (start[i] == c) continue; + string nxt = start.substr(0, i) + c + start.substr(i + 1, start.size() - i - 1); + if (s.count(nxt)) { + s.erase(nxt); + dfs(nxt, end, s, t + 1); + } + } + } + } +}; +``` + +```go +func minMutation(start string, end string, bank []string) int { + s := make(map[string]bool) + for _, b := range bank { + s[b] = true + } + ans := math.MaxInt32 + s[start] = false + seq := []rune{'A', 'C', 'G', 'T'} + var dfs func(start string, t int) + dfs = func(start string, t int) { + if start == end { + if ans > t { + ans = t + } + return + } + for i, x := range start { + for _, y := range seq { + if x == y { + continue + } + nxt := start[:i] + string(y) + start[i+1:] + if s[nxt] { + s[nxt] = false + dfs(nxt, t+1) + } + } + } + } + dfs(start, 0) + if ans == math.MaxInt32 { + return -1 + } + return ans +} ``` + + diff --git a/solution/0400-0499/0433.Minimum Genetic Mutation/README_EN.md b/solution/0400-0499/0433.Minimum Genetic Mutation/README_EN.md index e0c106f219cb8..e46e17721b593 100644 --- a/solution/0400-0499/0433.Minimum Genetic Mutation/README_EN.md +++ b/solution/0400-0499/0433.Minimum Genetic Mutation/README_EN.md @@ -44,12 +44,10 @@ ## Solutions -BFS or DFS. +### Solution 1 -### **Python3** - ```python class Solution: def minMutation(self, start: str, end: str, bank: List[str]) -> int: @@ -69,30 +67,6 @@ class Solution: return -1 ``` -```python -class Solution: - def minMutation(self, start: str, end: str, bank: List[str]) -> int: - def dfs(start, t): - if start == end: - nonlocal ans - ans = min(ans, t) - return - for i, x in enumerate(start): - for y in 'ACGT': - if x != y: - nxt = start[:i] + y + start[i + 1 :] - if nxt in s: - s.remove(nxt) - dfs(nxt, t + 1) - - s = set(bank) - ans = inf - dfs(start, 0) - return -1 if ans == inf else ans -``` - -### **Java** - ```java class Solution { public int minMutation(String start, String end, String[] bank) { @@ -129,46 +103,6 @@ class Solution { } ``` -```java -class Solution { - private int ans; - private Set s; - private static final char[] seq = {'A', 'C', 'G', 'T'}; - - public int minMutation(String start, String end, String[] bank) { - s = new HashSet<>(); - for (String b : bank) { - s.add(b); - } - ans = Integer.MAX_VALUE; - dfs(start, end, 0); - s.remove(start); - return ans == Integer.MAX_VALUE ? -1 : ans; - } - - private void dfs(String start, String end, int t) { - if (start.equals(end)) { - ans = Math.min(ans, t); - return; - } - for (int i = 0; i < start.length(); ++i) { - for (char c : seq) { - if (start.charAt(i) == c) { - continue; - } - String nxt = start.substring(0, i) + c + start.substring(i + 1); - if (s.contains(nxt)) { - s.remove(nxt); - dfs(nxt, end, t + 1); - } - } - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -203,42 +137,6 @@ public: }; ``` -```cpp -class Solution { -public: - int ans; - string seq = "ACGT"; - - int minMutation(string start, string end, vector& bank) { - unordered_set s; - for (auto& b : bank) s.insert(b); - ans = INT_MAX; - s.erase(start); - dfs(start, end, s, 0); - return ans == INT_MAX ? -1 : ans; - } - - void dfs(string& start, string& end, unordered_set& s, int t) { - if (start == end) { - ans = min(ans, t); - return; - } - for (int i = 0; i < start.size(); ++i) { - for (char& c : seq) { - if (start[i] == c) continue; - string nxt = start.substr(0, i) + c + start.substr(i + 1, start.size() - i - 1); - if (s.count(nxt)) { - s.erase(nxt); - dfs(nxt, end, s, t + 1); - } - } - } - } -}; -``` - -### **Go** - ```go func minMutation(start string, end string, bank []string) int { s := make(map[string]bool) @@ -276,46 +174,6 @@ func minMutation(start string, end string, bank []string) int { } ``` -```go -func minMutation(start string, end string, bank []string) int { - s := make(map[string]bool) - for _, b := range bank { - s[b] = true - } - ans := math.MaxInt32 - s[start] = false - seq := []rune{'A', 'C', 'G', 'T'} - var dfs func(start string, t int) - dfs = func(start string, t int) { - if start == end { - if ans > t { - ans = t - } - return - } - for i, x := range start { - for _, y := range seq { - if x == y { - continue - } - nxt := start[:i] + string(y) + start[i+1:] - if s[nxt] { - s[nxt] = false - dfs(nxt, t+1) - } - } - } - } - dfs(start, 0) - if ans == math.MaxInt32 { - return -1 - } - return ans -} -``` - -### **TypeScript** - ```ts function minMutation(start: string, end: string, bank: string[]): number { const queue = [start]; @@ -347,8 +205,6 @@ function minMutation(start: string, end: string, bank: string[]): number { } ``` -### **Rust** - ```rust use std::collections::VecDeque; impl Solution { @@ -384,10 +240,144 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def minMutation(self, start: str, end: str, bank: List[str]) -> int: + def dfs(start, t): + if start == end: + nonlocal ans + ans = min(ans, t) + return + for i, x in enumerate(start): + for y in 'ACGT': + if x != y: + nxt = start[:i] + y + start[i + 1 :] + if nxt in s: + s.remove(nxt) + dfs(nxt, t + 1) + s = set(bank) + ans = inf + dfs(start, 0) + return -1 if ans == inf else ans ``` +```java +class Solution { + private int ans; + private Set s; + private static final char[] seq = {'A', 'C', 'G', 'T'}; + + public int minMutation(String start, String end, String[] bank) { + s = new HashSet<>(); + for (String b : bank) { + s.add(b); + } + ans = Integer.MAX_VALUE; + dfs(start, end, 0); + s.remove(start); + return ans == Integer.MAX_VALUE ? -1 : ans; + } + + private void dfs(String start, String end, int t) { + if (start.equals(end)) { + ans = Math.min(ans, t); + return; + } + for (int i = 0; i < start.length(); ++i) { + for (char c : seq) { + if (start.charAt(i) == c) { + continue; + } + String nxt = start.substring(0, i) + c + start.substring(i + 1); + if (s.contains(nxt)) { + s.remove(nxt); + dfs(nxt, end, t + 1); + } + } + } + } +} +``` + +```cpp +class Solution { +public: + int ans; + string seq = "ACGT"; + + int minMutation(string start, string end, vector& bank) { + unordered_set s; + for (auto& b : bank) s.insert(b); + ans = INT_MAX; + s.erase(start); + dfs(start, end, s, 0); + return ans == INT_MAX ? -1 : ans; + } + + void dfs(string& start, string& end, unordered_set& s, int t) { + if (start == end) { + ans = min(ans, t); + return; + } + for (int i = 0; i < start.size(); ++i) { + for (char& c : seq) { + if (start[i] == c) continue; + string nxt = start.substr(0, i) + c + start.substr(i + 1, start.size() - i - 1); + if (s.count(nxt)) { + s.erase(nxt); + dfs(nxt, end, s, t + 1); + } + } + } + } +}; +``` + +```go +func minMutation(start string, end string, bank []string) int { + s := make(map[string]bool) + for _, b := range bank { + s[b] = true + } + ans := math.MaxInt32 + s[start] = false + seq := []rune{'A', 'C', 'G', 'T'} + var dfs func(start string, t int) + dfs = func(start string, t int) { + if start == end { + if ans > t { + ans = t + } + return + } + for i, x := range start { + for _, y := range seq { + if x == y { + continue + } + nxt := start[:i] + string(y) + start[i+1:] + if s[nxt] { + s[nxt] = false + dfs(nxt, t+1) + } + } + } + } + dfs(start, 0) + if ans == math.MaxInt32 { + return -1 + } + return ans +} ``` + + diff --git a/solution/0400-0499/0434.Number of Segments in a String/README.md b/solution/0400-0499/0434.Number of Segments in a String/README.md index a82953c482f3a..896f6c2986c17 100644 --- a/solution/0400-0499/0434.Number of Segments in a String/README.md +++ b/solution/0400-0499/0434.Number of Segments in a String/README.md @@ -19,46 +19,20 @@ ## 解法 - - -**方法一:字符串分割** +### 方法一:字符串分割 将字符串 `s` 按照空格进行分割,然后统计不为空的单词个数。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。 -**方法二:模拟** - -直接模拟,遍历字符串,检测每个字符,统计个数。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def countSegments(self, s: str) -> int: return len(s.split()) ``` -```python -class Solution: - def countSegments(self, s: str) -> int: - ans = 0 - for i, c in enumerate(s): - if c != ' ' and (i == 0 or s[i - 1] == ' '): - ans += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int countSegments(String s) { @@ -73,22 +47,6 @@ class Solution { } ``` -```java -class Solution { - public int countSegments(String s) { - int ans = 0; - for (int i = 0; i < s.length(); ++i) { - if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) { - ++ans; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -101,23 +59,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countSegments(string s) { - int ans = 0; - for (int i = 0; i < s.size(); ++i) { - if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) { - ++ans; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func countSegments(s string) int { ans := 0 @@ -130,20 +71,6 @@ func countSegments(s string) int { } ``` -```go -func countSegments(s string) int { - ans := 0 - for i, c := range s { - if c != ' ' && (i == 0 || s[i-1] == ' ') { - ans++ - } - } - return ans -} -``` - -### **PHP** - ```php class Solution { /** @@ -163,10 +90,67 @@ class Solution { } ``` -### **...** + + +### 方法二:模拟 + +直接模拟,遍历字符串,检测每个字符,统计个数。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def countSegments(self, s: str) -> int: + ans = 0 + for i, c in enumerate(s): + if c != ' ' and (i == 0 or s[i - 1] == ' '): + ans += 1 + return ans +``` + +```java +class Solution { + public int countSegments(String s) { + int ans = 0; + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) { + ++ans; + } + } + return ans; + } +} +``` +```cpp +class Solution { +public: + int countSegments(string s) { + int ans = 0; + for (int i = 0; i < s.size(); ++i) { + if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) { + ++ans; + } + } + return ans; + } +}; ``` +```go +func countSegments(s string) int { + ans := 0 + for i, c := range s { + if c != ' ' && (i == 0 || s[i-1] == ' ') { + ans++ + } + } + return ans +} ``` + + diff --git a/solution/0400-0499/0434.Number of Segments in a String/README_EN.md b/solution/0400-0499/0434.Number of Segments in a String/README_EN.md index 092d07065fed7..68b889f5db55b 100644 --- a/solution/0400-0499/0434.Number of Segments in a String/README_EN.md +++ b/solution/0400-0499/0434.Number of Segments in a String/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -45,32 +45,6 @@ class Solution: return len(s.split()) ``` -```python -class Solution: - def countSegments(self, s: str) -> int: - ans = 0 - for i, c in enumerate(s): - if c != ' ' and (i == 0 or s[i - 1] == ' '): - ans += 1 - return ans -``` - -### **Java** - -```java -class Solution { - public int countSegments(String s) { - int res = 0; - for (String t : s.split(" ")) { - if (!"".equals(t)) { - ++res; - } - } - return res; - } -} -``` - ```java class Solution { public int countSegments(String s) { @@ -85,8 +59,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,23 +71,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countSegments(string s) { - int ans = 0; - for (int i = 0; i < s.size(); ++i) { - if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) { - ++ans; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func countSegments(s string) int { ans := 0 @@ -128,20 +83,6 @@ func countSegments(s string) int { } ``` -```go -func countSegments(s string) int { - ans := 0 - for i, c := range s { - if c != ' ' && (i == 0 || s[i-1] == ' ') { - ans++ - } - } - return ans -} -``` - -### **PHP** - ```php class Solution { /** @@ -161,10 +102,63 @@ class Solution { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def countSegments(self, s: str) -> int: + ans = 0 + for i, c in enumerate(s): + if c != ' ' and (i == 0 or s[i - 1] == ' '): + ans += 1 + return ans +``` + +```java +class Solution { + public int countSegments(String s) { + int ans = 0; + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) { + ++ans; + } + } + return ans; + } +} +``` +```cpp +class Solution { +public: + int countSegments(string s) { + int ans = 0; + for (int i = 0; i < s.size(); ++i) { + if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) { + ++ans; + } + } + return ans; + } +}; ``` +```go +func countSegments(s string) int { + ans := 0 + for i, c := range s { + if c != ' ' && (i == 0 || s[i-1] == ' ') { + ans++ + } + } + return ans +} ``` + + diff --git a/solution/0400-0499/0435.Non-overlapping Intervals/README.md b/solution/0400-0499/0435.Non-overlapping Intervals/README.md index 66704eef555b3..beddaab712c75 100644 --- a/solution/0400-0499/0435.Non-overlapping Intervals/README.md +++ b/solution/0400-0499/0435.Non-overlapping Intervals/README.md @@ -46,29 +46,12 @@ ## 解法 - - -**方法一:转换为最长上升子序列问题** +### 方法一:转换为最长上升子序列问题 最长上升子序列问题,动态规划的做法,时间复杂度是 $O(n^2)$,这里可以采用贪心优化,将复杂度降至 $O(n\log n)$。 -**方法二:排序 + 贪心** - -先按照区间右边界排序。优先选择最小的区间的右边界作为起始边界。遍历区间: - -- 若当前区间左边界大于等于起始右边界,说明该区间无需移除,直接更新起始右边界; -- 否则说明该区间需要移除,更新移除区间的数量 ans。 - -最后返回 ans 即可。 - -时间复杂度 $O(n\log n)$。 - -### **Python3** - - - ```python class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: @@ -82,24 +65,6 @@ class Solution: return ans ``` -```python -class Solution: - def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: - intervals.sort() - d = [intervals[0][1]] - for s, e in intervals[1:]: - if s >= d[-1]: - d.append(e) - else: - idx = bisect_left(d, s) - d[idx] = min(d[idx], e) - return len(intervals) - len(d) -``` - -### **Java** - - - ```java class Solution { public int eraseOverlapIntervals(int[][] intervals) { @@ -117,62 +82,6 @@ class Solution { } ``` -```java -class Solution { - public int eraseOverlapIntervals(int[][] intervals) { - Arrays.sort(intervals, (a, b) -> { - if (a[0] != b[0]) { - return a[0] - b[0]; - } - return a[1] - b[1]; - }); - int n = intervals.length; - int[] d = new int[n + 1]; - d[1] = intervals[0][1]; - int size = 1; - for (int i = 1; i < n; ++i) { - int s = intervals[i][0], e = intervals[i][1]; - if (s >= d[size]) { - d[++size] = e; - } else { - int left = 1, right = size; - while (left < right) { - int mid = (left + right) >> 1; - if (d[mid] >= s) { - right = mid; - } else { - left = mid + 1; - } - } - d[left] = Math.min(d[left], e); - } - } - return n - size; - } -} -``` - -### **TypeScript** - -```ts -function eraseOverlapIntervals(intervals: number[][]): number { - intervals.sort((a, b) => a[1] - b[1]); - let end = intervals[0][1], - ans = 0; - for (let i = 1; i < intervals.length; ++i) { - let cur = intervals[i]; - if (end > cur[0]) { - ans++; - } else { - end = cur[1]; - } - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -190,8 +99,6 @@ public: }; ``` -### **Go** - ```go func eraseOverlapIntervals(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { @@ -209,10 +116,87 @@ func eraseOverlapIntervals(intervals [][]int) int { } ``` -### **...** +```ts +function eraseOverlapIntervals(intervals: number[][]): number { + intervals.sort((a, b) => a[1] - b[1]); + let end = intervals[0][1], + ans = 0; + for (let i = 1; i < intervals.length; ++i) { + let cur = intervals[i]; + if (end > cur[0]) { + ans++; + } else { + end = cur[1]; + } + } + return ans; +} +``` + + + +### 方法二:排序 + 贪心 + +先按照区间右边界排序。优先选择最小的区间的右边界作为起始边界。遍历区间: + +- 若当前区间左边界大于等于起始右边界,说明该区间无需移除,直接更新起始右边界; +- 否则说明该区间需要移除,更新移除区间的数量 ans。 + +最后返回 ans 即可。 + +时间复杂度 $O(n\log n)$。 + + +```python +class Solution: + def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: + intervals.sort() + d = [intervals[0][1]] + for s, e in intervals[1:]: + if s >= d[-1]: + d.append(e) + else: + idx = bisect_left(d, s) + d[idx] = min(d[idx], e) + return len(intervals) - len(d) ``` +```java +class Solution { + public int eraseOverlapIntervals(int[][] intervals) { + Arrays.sort(intervals, (a, b) -> { + if (a[0] != b[0]) { + return a[0] - b[0]; + } + return a[1] - b[1]; + }); + int n = intervals.length; + int[] d = new int[n + 1]; + d[1] = intervals[0][1]; + int size = 1; + for (int i = 1; i < n; ++i) { + int s = intervals[i][0], e = intervals[i][1]; + if (s >= d[size]) { + d[++size] = e; + } else { + int left = 1, right = size; + while (left < right) { + int mid = (left + right) >> 1; + if (d[mid] >= s) { + right = mid; + } else { + left = mid + 1; + } + } + d[left] = Math.min(d[left], e); + } + } + return n - size; + } +} ``` + + diff --git a/solution/0400-0499/0435.Non-overlapping Intervals/README_EN.md b/solution/0400-0499/0435.Non-overlapping Intervals/README_EN.md index f4b0448a89f64..dd1f3c7822f95 100644 --- a/solution/0400-0499/0435.Non-overlapping Intervals/README_EN.md +++ b/solution/0400-0499/0435.Non-overlapping Intervals/README_EN.md @@ -42,12 +42,10 @@ ## Solutions -Greedy. +### Solution 1 -### **Python3** - ```python class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: @@ -61,22 +59,6 @@ class Solution: return ans ``` -```python -class Solution: - def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: - intervals.sort() - d = [intervals[0][1]] - for s, e in intervals[1:]: - if s >= d[-1]: - d.append(e) - else: - idx = bisect_left(d, s) - d[idx] = min(d[idx], e) - return len(intervals) - len(d) -``` - -### **Java** - ```java class Solution { public int eraseOverlapIntervals(int[][] intervals) { @@ -94,62 +76,6 @@ class Solution { } ``` -```java -class Solution { - public int eraseOverlapIntervals(int[][] intervals) { - Arrays.sort(intervals, (a, b) -> { - if (a[0] != b[0]) { - return a[0] - b[0]; - } - return a[1] - b[1]; - }); - int n = intervals.length; - int[] d = new int[n + 1]; - d[1] = intervals[0][1]; - int size = 1; - for (int i = 1; i < n; ++i) { - int s = intervals[i][0], e = intervals[i][1]; - if (s >= d[size]) { - d[++size] = e; - } else { - int left = 1, right = size; - while (left < right) { - int mid = (left + right) >> 1; - if (d[mid] >= s) { - right = mid; - } else { - left = mid + 1; - } - } - d[left] = Math.min(d[left], e); - } - } - return n - size; - } -} -``` - -### **TypeScript** - -```ts -function eraseOverlapIntervals(intervals: number[][]): number { - intervals.sort((a, b) => a[1] - b[1]); - let end = intervals[0][1], - ans = 0; - for (let i = 1; i < intervals.length; ++i) { - let cur = intervals[i]; - if (end > cur[0]) { - ans++; - } else { - end = cur[1]; - } - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -167,8 +93,6 @@ public: }; ``` -### **Go** - ```go func eraseOverlapIntervals(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { @@ -186,10 +110,78 @@ func eraseOverlapIntervals(intervals [][]int) int { } ``` -### **...** +```ts +function eraseOverlapIntervals(intervals: number[][]): number { + intervals.sort((a, b) => a[1] - b[1]); + let end = intervals[0][1], + ans = 0; + for (let i = 1; i < intervals.length; ++i) { + let cur = intervals[i]; + if (end > cur[0]) { + ans++; + } else { + end = cur[1]; + } + } + return ans; +} +``` + + +### Solution 2 + + + +```python +class Solution: + def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: + intervals.sort() + d = [intervals[0][1]] + for s, e in intervals[1:]: + if s >= d[-1]: + d.append(e) + else: + idx = bisect_left(d, s) + d[idx] = min(d[idx], e) + return len(intervals) - len(d) ``` +```java +class Solution { + public int eraseOverlapIntervals(int[][] intervals) { + Arrays.sort(intervals, (a, b) -> { + if (a[0] != b[0]) { + return a[0] - b[0]; + } + return a[1] - b[1]; + }); + int n = intervals.length; + int[] d = new int[n + 1]; + d[1] = intervals[0][1]; + int size = 1; + for (int i = 1; i < n; ++i) { + int s = intervals[i][0], e = intervals[i][1]; + if (s >= d[size]) { + d[++size] = e; + } else { + int left = 1, right = size; + while (left < right) { + int mid = (left + right) >> 1; + if (d[mid] >= s) { + right = mid; + } else { + left = mid + 1; + } + } + d[left] = Math.min(d[left], e); + } + } + return n - size; + } +} ``` + + diff --git a/solution/0400-0499/0436.Find Right Interval/README.md b/solution/0400-0499/0436.Find Right Interval/README.md index 5e5a4fed76568..4b3e40b6c891f 100644 --- a/solution/0400-0499/0436.Find Right Interval/README.md +++ b/solution/0400-0499/0436.Find Right Interval/README.md @@ -53,16 +53,10 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 -### **Python3** - - - ```python class Solution: def findRightInterval(self, intervals: List[List[int]]) -> List[int]: @@ -78,10 +72,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] findRightInterval(int[][] intervals) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func findRightInterval(intervals [][]int) []int { n := len(intervals) @@ -176,8 +162,6 @@ func findRightInterval(intervals [][]int) []int { } ``` -### **TypeScript** - ```ts function findRightInterval(intervals: number[][]): number[] { const n = intervals.length; @@ -207,10 +191,6 @@ function findRightInterval(intervals: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0436.Find Right Interval/README_EN.md b/solution/0400-0499/0436.Find Right Interval/README_EN.md index e21909756efc2..31e28065b1b5e 100644 --- a/solution/0400-0499/0436.Find Right Interval/README_EN.md +++ b/solution/0400-0499/0436.Find Right Interval/README_EN.md @@ -50,12 +50,10 @@ The right interval for [2,3] is [3,4] since start2 = 3 is the smalles ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python class Solution: def findRightInterval(self, intervals: List[List[int]]) -> List[int]: @@ -71,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] findRightInterval(int[][] intervals) { @@ -102,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +126,6 @@ public: }; ``` -### **Go** - ```go func findRightInterval(intervals [][]int) []int { n := len(intervals) @@ -167,8 +159,6 @@ func findRightInterval(intervals [][]int) []int { } ``` -### **TypeScript** - ```ts function findRightInterval(intervals: number[][]): number[] { const n = intervals.length; @@ -198,10 +188,6 @@ function findRightInterval(intervals: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0437.Path Sum III/README.md b/solution/0400-0499/0437.Path Sum III/README.md index 52f4825cbce40..16d1ac5a9a648 100644 --- a/solution/0400-0499/0437.Path Sum III/README.md +++ b/solution/0400-0499/0437.Path Sum III/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:哈希表 + 前缀和 + 递归** +### 方法一:哈希表 + 前缀和 + 递归 我们可以运用前缀和的思想,对二叉树进行递归遍历,同时用哈希表 $cnt$ 统计从根节点到当前节点的路径上各个前缀和出现的次数。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -91,10 +85,6 @@ class Solution: return dfs(root, 0) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -198,8 +184,6 @@ func pathSum(root *TreeNode, targetSum int) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -234,10 +218,6 @@ function pathSum(root: TreeNode | null, targetSum: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0437.Path Sum III/README_EN.md b/solution/0400-0499/0437.Path Sum III/README_EN.md index f0a261c3f4ff1..ff5a8de8fdec8 100644 --- a/solution/0400-0499/0437.Path Sum III/README_EN.md +++ b/solution/0400-0499/0437.Path Sum III/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -63,8 +63,6 @@ class Solution: return dfs(root, 0) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -139,8 +135,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -168,8 +162,6 @@ func pathSum(root *TreeNode, targetSum int) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -204,10 +196,6 @@ function pathSum(root: TreeNode | null, targetSum: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0438.Find All Anagrams in a String/README.md b/solution/0400-0499/0438.Find All Anagrams in a String/README.md index 11954ea37382a..fe6a6a63b08fc 100644 --- a/solution/0400-0499/0438.Find All Anagrams in a String/README.md +++ b/solution/0400-0499/0438.Find All Anagrams in a String/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 我们不妨设字符串 $s$ 的长度为 $m$,字符串 $p$ 的长度为 $n$。 @@ -56,18 +54,8 @@ 时间复杂度 $O(m \times C)$,空间复杂度 $O(C)$。其中 $m$ 是字符串 $s$ 的长度;而 $C$ 是字符集大小,在本题中字符集为所有小写字母,所以 $C = 26$。 -**方法二:双指针(滑动窗口优化)** - -我们可以对方法一进行优化,与方法一类似,我们用一个固定长度为 $26$ 的数组 $cnt1$ 记录 $p$ 中每个字母的出现次数,用另一个数组 $cnt2$ 记录当前滑动窗口中每个字母的出现次数,用指针 $i$ 和 $j$ 分别指向滑动窗口的左右边界。每一次移动指针 $j$,将 $cnt2[s[j]]$ 的值加 $1$,如果当前 $cnt2[s[j]]$ 的值大于 $cnt1[s[j]]$,则将指针 $i$ 不断右移,直到 $cnt2[s[j]]$ 的值不大于 $cnt1[s[j]]$。此时,如果滑动窗口的长度等于 $p$ 的长度,我们就找到了一个异位词,将起始位置加入答案。继续移动指针 $j$,重复上述操作,直到指针 $j$ 移动到 $s$ 的末尾。 - -时间复杂度 $(m + n)$,空间复杂度 $O(C)$。其中 $m$ 和 $n$ 分别是字符串 $s$ 和 $p$ 的长度;而 $C$ 是字符集大小,在本题中字符集为所有小写字母,所以 $C = 26$。 - -### **Python3** - - - ```python class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: @@ -85,30 +73,6 @@ class Solution: return ans ``` -```python -class Solution: - def findAnagrams(self, s: str, p: str) -> List[int]: - m, n = len(s), len(p) - ans = [] - if m < n: - return ans - cnt1 = Counter(p) - cnt2 = Counter() - j = 0 - for i, c in enumerate(s): - cnt2[c] += 1 - while cnt2[c] > cnt1[c]: - cnt2[s[j]] -= 1 - j += 1 - if i - j + 1 == n: - ans.append(j) - return ans -``` - -### **Java** - - - ```java class Solution { public List findAnagrams(String s, String p) { @@ -137,36 +101,6 @@ class Solution { } ``` -```java -class Solution { - public List findAnagrams(String s, String p) { - int m = s.length(), n = p.length(); - List ans = new ArrayList<>(); - if (m < n) { - return ans; - } - int[] cnt1 = new int[26]; - for (int i = 0; i < n; ++i) { - ++cnt1[p.charAt(i) - 'a']; - } - int[] cnt2 = new int[26]; - for (int i = 0, j = 0; i < m; ++i) { - int k = s.charAt(i) - 'a'; - ++cnt2[k]; - while (cnt2[k] > cnt1[k]) { - --cnt2[s.charAt(j++) - 'a']; - } - if (i - j + 1 == n) { - ans.add(j); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -196,37 +130,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector findAnagrams(string s, string p) { - int m = s.size(), n = p.size(); - vector ans; - if (m < n) { - return ans; - } - vector cnt1(26); - for (char& c : p) { - ++cnt1[c - 'a']; - } - vector cnt2(26); - for (int i = 0, j = 0; i < m; ++i) { - int k = s[i] - 'a'; - ++cnt2[k]; - while (cnt2[k] > cnt1[k]) { - --cnt2[s[j++] - 'a']; - } - if (i - j + 1 == n) { - ans.push_back(j); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func findAnagrams(s string, p string) (ans []int) { m, n := len(s), len(p) @@ -252,34 +155,6 @@ func findAnagrams(s string, p string) (ans []int) { } ``` -```go -func findAnagrams(s string, p string) (ans []int) { - m, n := len(s), len(p) - if m < n { - return - } - cnt1 := [26]int{} - cnt2 := [26]int{} - for _, c := range p { - cnt1[c-'a']++ - } - j := 0 - for i, c := range s { - cnt2[c-'a']++ - for cnt2[c-'a'] > cnt1[c-'a'] { - cnt2[s[j]-'a']-- - j++ - } - if i-j+1 == n { - ans = append(ans, j) - } - } - return -} -``` - -### **TypeScript** - ```ts function findAnagrams(s: string, p: string): number[] { const m = s.length; @@ -308,36 +183,6 @@ function findAnagrams(s: string, p: string): number[] { } ``` -```ts -function findAnagrams(s: string, p: string): number[] { - const m = s.length; - const n = p.length; - const ans: number[] = []; - if (m < n) { - return ans; - } - const cnt1: number[] = new Array(26).fill(0); - const cnt2: number[] = new Array(26).fill(0); - const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); - for (const c of p) { - ++cnt1[idx(c)]; - } - for (let i = 0, j = 0; i < m; ++i) { - const k = idx(s[i]); - ++cnt2[k]; - while (cnt2[k] > cnt1[k]) { - --cnt2[idx(s[j++])]; - } - if (i - j + 1 === n) { - ans.push(j); - } - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn find_anagrams(s: String, p: String) -> Vec { @@ -368,8 +213,6 @@ impl Solution { } ``` -### **C#** - ```cs public class Solution { public IList FindAnagrams(string s, string p) { @@ -398,10 +241,147 @@ public class Solution { } ``` -### **...** + + +### 方法二:双指针(滑动窗口优化) + +我们可以对方法一进行优化,与方法一类似,我们用一个固定长度为 $26$ 的数组 $cnt1$ 记录 $p$ 中每个字母的出现次数,用另一个数组 $cnt2$ 记录当前滑动窗口中每个字母的出现次数,用指针 $i$ 和 $j$ 分别指向滑动窗口的左右边界。每一次移动指针 $j$,将 $cnt2[s[j]]$ 的值加 $1$,如果当前 $cnt2[s[j]]$ 的值大于 $cnt1[s[j]]$,则将指针 $i$ 不断右移,直到 $cnt2[s[j]]$ 的值不大于 $cnt1[s[j]]$。此时,如果滑动窗口的长度等于 $p$ 的长度,我们就找到了一个异位词,将起始位置加入答案。继续移动指针 $j$,重复上述操作,直到指针 $j$ 移动到 $s$ 的末尾。 + +时间复杂度 $(m + n)$,空间复杂度 $O(C)$。其中 $m$ 和 $n$ 分别是字符串 $s$ 和 $p$ 的长度;而 $C$ 是字符集大小,在本题中字符集为所有小写字母,所以 $C = 26$。 + + +```python +class Solution: + def findAnagrams(self, s: str, p: str) -> List[int]: + m, n = len(s), len(p) + ans = [] + if m < n: + return ans + cnt1 = Counter(p) + cnt2 = Counter() + j = 0 + for i, c in enumerate(s): + cnt2[c] += 1 + while cnt2[c] > cnt1[c]: + cnt2[s[j]] -= 1 + j += 1 + if i - j + 1 == n: + ans.append(j) + return ans ``` +```java +class Solution { + public List findAnagrams(String s, String p) { + int m = s.length(), n = p.length(); + List ans = new ArrayList<>(); + if (m < n) { + return ans; + } + int[] cnt1 = new int[26]; + for (int i = 0; i < n; ++i) { + ++cnt1[p.charAt(i) - 'a']; + } + int[] cnt2 = new int[26]; + for (int i = 0, j = 0; i < m; ++i) { + int k = s.charAt(i) - 'a'; + ++cnt2[k]; + while (cnt2[k] > cnt1[k]) { + --cnt2[s.charAt(j++) - 'a']; + } + if (i - j + 1 == n) { + ans.add(j); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector findAnagrams(string s, string p) { + int m = s.size(), n = p.size(); + vector ans; + if (m < n) { + return ans; + } + vector cnt1(26); + for (char& c : p) { + ++cnt1[c - 'a']; + } + vector cnt2(26); + for (int i = 0, j = 0; i < m; ++i) { + int k = s[i] - 'a'; + ++cnt2[k]; + while (cnt2[k] > cnt1[k]) { + --cnt2[s[j++] - 'a']; + } + if (i - j + 1 == n) { + ans.push_back(j); + } + } + return ans; + } +}; +``` + +```go +func findAnagrams(s string, p string) (ans []int) { + m, n := len(s), len(p) + if m < n { + return + } + cnt1 := [26]int{} + cnt2 := [26]int{} + for _, c := range p { + cnt1[c-'a']++ + } + j := 0 + for i, c := range s { + cnt2[c-'a']++ + for cnt2[c-'a'] > cnt1[c-'a'] { + cnt2[s[j]-'a']-- + j++ + } + if i-j+1 == n { + ans = append(ans, j) + } + } + return +} +``` + +```ts +function findAnagrams(s: string, p: string): number[] { + const m = s.length; + const n = p.length; + const ans: number[] = []; + if (m < n) { + return ans; + } + const cnt1: number[] = new Array(26).fill(0); + const cnt2: number[] = new Array(26).fill(0); + const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); + for (const c of p) { + ++cnt1[idx(c)]; + } + for (let i = 0, j = 0; i < m; ++i) { + const k = idx(s[i]); + ++cnt2[k]; + while (cnt2[k] > cnt1[k]) { + --cnt2[idx(s[j++])]; + } + if (i - j + 1 === n) { + ans.push(j); + } + } + return ans; +} ``` + + diff --git a/solution/0400-0499/0438.Find All Anagrams in a String/README_EN.md b/solution/0400-0499/0438.Find All Anagrams in a String/README_EN.md index 36912cad0d82c..0cc0f59bf7ba7 100644 --- a/solution/0400-0499/0438.Find All Anagrams in a String/README_EN.md +++ b/solution/0400-0499/0438.Find All Anagrams in a String/README_EN.md @@ -40,9 +40,9 @@ The substring with start index = 2 is "ab", which is an anagram of &qu ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,28 +61,6 @@ class Solution: return ans ``` -```python -class Solution: - def findAnagrams(self, s: str, p: str) -> List[int]: - m, n = len(s), len(p) - ans = [] - if m < n: - return ans - cnt1 = Counter(p) - cnt2 = Counter() - j = 0 - for i, c in enumerate(s): - cnt2[c] += 1 - while cnt2[c] > cnt1[c]: - cnt2[s[j]] -= 1 - j += 1 - if i - j + 1 == n: - ans.append(j) - return ans -``` - -### **Java** - ```java class Solution { public List findAnagrams(String s, String p) { @@ -111,36 +89,6 @@ class Solution { } ``` -```java -class Solution { - public List findAnagrams(String s, String p) { - int m = s.length(), n = p.length(); - List ans = new ArrayList<>(); - if (m < n) { - return ans; - } - int[] cnt1 = new int[26]; - for (int i = 0; i < n; ++i) { - ++cnt1[p.charAt(i) - 'a']; - } - int[] cnt2 = new int[26]; - for (int i = 0, j = 0; i < m; ++i) { - int k = s.charAt(i) - 'a'; - ++cnt2[k]; - while (cnt2[k] > cnt1[k]) { - --cnt2[s.charAt(j++) - 'a']; - } - if (i - j + 1 == n) { - ans.add(j); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -170,37 +118,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector findAnagrams(string s, string p) { - int m = s.size(), n = p.size(); - vector ans; - if (m < n) { - return ans; - } - vector cnt1(26); - for (char& c : p) { - ++cnt1[c - 'a']; - } - vector cnt2(26); - for (int i = 0, j = 0; i < m; ++i) { - int k = s[i] - 'a'; - ++cnt2[k]; - while (cnt2[k] > cnt1[k]) { - --cnt2[s[j++] - 'a']; - } - if (i - j + 1 == n) { - ans.push_back(j); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func findAnagrams(s string, p string) (ans []int) { m, n := len(s), len(p) @@ -226,34 +143,6 @@ func findAnagrams(s string, p string) (ans []int) { } ``` -```go -func findAnagrams(s string, p string) (ans []int) { - m, n := len(s), len(p) - if m < n { - return - } - cnt1 := [26]int{} - cnt2 := [26]int{} - for _, c := range p { - cnt1[c-'a']++ - } - j := 0 - for i, c := range s { - cnt2[c-'a']++ - for cnt2[c-'a'] > cnt1[c-'a'] { - cnt2[s[j]-'a']-- - j++ - } - if i-j+1 == n { - ans = append(ans, j) - } - } - return -} -``` - -### **TypeScript** - ```ts function findAnagrams(s: string, p: string): number[] { const m = s.length; @@ -282,36 +171,6 @@ function findAnagrams(s: string, p: string): number[] { } ``` -```ts -function findAnagrams(s: string, p: string): number[] { - const m = s.length; - const n = p.length; - const ans: number[] = []; - if (m < n) { - return ans; - } - const cnt1: number[] = new Array(26).fill(0); - const cnt2: number[] = new Array(26).fill(0); - const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); - for (const c of p) { - ++cnt1[idx(c)]; - } - for (let i = 0, j = 0; i < m; ++i) { - const k = idx(s[i]); - ++cnt2[k]; - while (cnt2[k] > cnt1[k]) { - --cnt2[idx(s[j++])]; - } - if (i - j + 1 === n) { - ans.push(j); - } - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn find_anagrams(s: String, p: String) -> Vec { @@ -342,8 +201,6 @@ impl Solution { } ``` -### **C#** - ```cs public class Solution { public IList FindAnagrams(string s, string p) { @@ -372,10 +229,143 @@ public class Solution { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def findAnagrams(self, s: str, p: str) -> List[int]: + m, n = len(s), len(p) + ans = [] + if m < n: + return ans + cnt1 = Counter(p) + cnt2 = Counter() + j = 0 + for i, c in enumerate(s): + cnt2[c] += 1 + while cnt2[c] > cnt1[c]: + cnt2[s[j]] -= 1 + j += 1 + if i - j + 1 == n: + ans.append(j) + return ans ``` +```java +class Solution { + public List findAnagrams(String s, String p) { + int m = s.length(), n = p.length(); + List ans = new ArrayList<>(); + if (m < n) { + return ans; + } + int[] cnt1 = new int[26]; + for (int i = 0; i < n; ++i) { + ++cnt1[p.charAt(i) - 'a']; + } + int[] cnt2 = new int[26]; + for (int i = 0, j = 0; i < m; ++i) { + int k = s.charAt(i) - 'a'; + ++cnt2[k]; + while (cnt2[k] > cnt1[k]) { + --cnt2[s.charAt(j++) - 'a']; + } + if (i - j + 1 == n) { + ans.add(j); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector findAnagrams(string s, string p) { + int m = s.size(), n = p.size(); + vector ans; + if (m < n) { + return ans; + } + vector cnt1(26); + for (char& c : p) { + ++cnt1[c - 'a']; + } + vector cnt2(26); + for (int i = 0, j = 0; i < m; ++i) { + int k = s[i] - 'a'; + ++cnt2[k]; + while (cnt2[k] > cnt1[k]) { + --cnt2[s[j++] - 'a']; + } + if (i - j + 1 == n) { + ans.push_back(j); + } + } + return ans; + } +}; +``` + +```go +func findAnagrams(s string, p string) (ans []int) { + m, n := len(s), len(p) + if m < n { + return + } + cnt1 := [26]int{} + cnt2 := [26]int{} + for _, c := range p { + cnt1[c-'a']++ + } + j := 0 + for i, c := range s { + cnt2[c-'a']++ + for cnt2[c-'a'] > cnt1[c-'a'] { + cnt2[s[j]-'a']-- + j++ + } + if i-j+1 == n { + ans = append(ans, j) + } + } + return +} +``` + +```ts +function findAnagrams(s: string, p: string): number[] { + const m = s.length; + const n = p.length; + const ans: number[] = []; + if (m < n) { + return ans; + } + const cnt1: number[] = new Array(26).fill(0); + const cnt2: number[] = new Array(26).fill(0); + const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); + for (const c of p) { + ++cnt1[idx(c)]; + } + for (let i = 0, j = 0; i < m; ++i) { + const k = idx(s[i]); + ++cnt2[k]; + while (cnt2[k] > cnt1[k]) { + --cnt2[idx(s[j++])]; + } + if (i - j + 1 === n) { + ans.push(j); + } + } + return ans; +} ``` + + diff --git a/solution/0400-0499/0439.Ternary Expression Parser/README.md b/solution/0400-0499/0439.Ternary Expression Parser/README.md index 560580475a1e0..f5dda48e9ca06 100644 --- a/solution/0400-0499/0439.Ternary Expression Parser/README.md +++ b/solution/0400-0499/0439.Ternary Expression Parser/README.md @@ -53,9 +53,7 @@ or "(F ? 1 : (T ? 4 : 5))" --> "(T ? 4 : 5)" --> "4" ## 解法 - - -**方法一:栈** +### 方法一:栈 我们从右到左遍历字符串 `expression`,对于当前遍历到的字符 $c$: @@ -70,10 +68,6 @@ or "(F ? 1 : (T ? 4 : 5))" --> "(T ? 4 : 5)" --> "4" -### **Python3** - - - ```python class Solution: def parseTernary(self, expression: str) -> str: @@ -98,10 +92,6 @@ class Solution: return stk[0] ``` -### **Java** - - - ```java class Solution { public String parseTernary(String expression) { @@ -134,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +158,6 @@ public: }; ``` -### **Go** - ```go func parseTernary(expression string) string { stk := []byte{} @@ -202,10 +188,6 @@ func parseTernary(expression string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0439.Ternary Expression Parser/README_EN.md b/solution/0400-0499/0439.Ternary Expression Parser/README_EN.md index 7ed2e5ab9eb68..9fa9cdb6d81f3 100644 --- a/solution/0400-0499/0439.Ternary Expression Parser/README_EN.md +++ b/solution/0400-0499/0439.Ternary Expression Parser/README_EN.md @@ -50,9 +50,9 @@ or "(F ? 1 : (T ? 4 : 5))" --> "(T ? 4 : 5)" --> " ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,8 +78,6 @@ class Solution: return stk[0] ``` -### **Java** - ```java class Solution { public String parseTernary(String expression) { @@ -112,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +144,6 @@ public: }; ``` -### **Go** - ```go func parseTernary(expression string) string { stk := []byte{} @@ -180,10 +174,6 @@ func parseTernary(expression string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README.md b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README.md index 829dedf08b130..5c7683e54e679 100644 --- a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README.md +++ b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README.md @@ -35,14 +35,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findKthNumber(self, n: int, k: int) -> int: @@ -66,10 +62,6 @@ class Solution: return curr ``` -### **Java** - - - ```java class Solution { private int n; @@ -104,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +131,6 @@ public: }; ``` -### **Go** - ```go func findKthNumber(n int, k int) int { count := func(curr int) int { @@ -171,10 +159,6 @@ func findKthNumber(n int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README_EN.md b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README_EN.md index 06d29653726b7..63dc1e0541d38 100644 --- a/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README_EN.md +++ b/solution/0400-0499/0440.K-th Smallest in Lexicographical Order/README_EN.md @@ -31,9 +31,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return curr ``` -### **Java** - ```java class Solution { private int n; @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +127,6 @@ public: }; ``` -### **Go** - ```go func findKthNumber(n int, k int) int { count := func(curr int) int { @@ -161,10 +155,6 @@ func findKthNumber(n int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0441.Arranging Coins/README.md b/solution/0400-0499/0441.Arranging Coins/README.md index 72703e9912433..2b9a934952066 100644 --- a/solution/0400-0499/0441.Arranging Coins/README.md +++ b/solution/0400-0499/0441.Arranging Coins/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:数学推导** +### 方法一:数学推导 `(1 + x) * x / 2 <= n`,求解 x。 @@ -48,37 +46,14 @@ 由于 2n 可能溢出,故转换为 `x <= sqrt(2) * sqrt(n + 1/8) - 1/2`。 -**方法二:二分查找** - -### **Python3** - - - ```python class Solution: def arrangeCoins(self, n: int) -> int: return int(math.sqrt(2) * math.sqrt(n + 0.125) - 0.5) ``` -```python -class Solution: - def arrangeCoins(self, n: int) -> int: - left, right = 1, n - while left < right: - mid = (left + right + 1) >> 1 - if (1 + mid) * mid // 2 <= n: - left = mid - else: - right = mid - 1 - return left -``` - -### **Java** - - - ```java class Solution { public int arrangeCoins(int n) { @@ -87,25 +62,6 @@ class Solution { } ``` -```java -class Solution { - public int arrangeCoins(int n) { - long left = 1, right = n; - while (left < right) { - long mid = (left + right + 1) >>> 1; - if ((1 + mid) * mid / 2 <= n) { - left = mid; - } else { - right = mid - 1; - } - } - return (int) left; - } -} -``` - -### **C++** - ```cpp using LL = long; @@ -126,8 +82,6 @@ public: }; ``` -### **Go** - ```go func arrangeCoins(n int) int { left, right := 1, n @@ -143,10 +97,42 @@ func arrangeCoins(n int) int { } ``` -### **...** + + +### 方法二:二分查找 + + +```python +class Solution: + def arrangeCoins(self, n: int) -> int: + left, right = 1, n + while left < right: + mid = (left + right + 1) >> 1 + if (1 + mid) * mid // 2 <= n: + left = mid + else: + right = mid - 1 + return left ``` +```java +class Solution { + public int arrangeCoins(int n) { + long left = 1, right = n; + while (left < right) { + long mid = (left + right + 1) >>> 1; + if ((1 + mid) * mid / 2 <= n) { + left = mid; + } else { + right = mid - 1; + } + } + return (int) left; + } +} ``` + + diff --git a/solution/0400-0499/0441.Arranging Coins/README_EN.md b/solution/0400-0499/0441.Arranging Coins/README_EN.md index 157b3f682a473..1c0677c0ff98e 100644 --- a/solution/0400-0499/0441.Arranging Coins/README_EN.md +++ b/solution/0400-0499/0441.Arranging Coins/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -44,21 +44,6 @@ class Solution: return int(math.sqrt(2) * math.sqrt(n + 0.125) - 0.5) ``` -```python -class Solution: - def arrangeCoins(self, n: int) -> int: - left, right = 1, n - while left < right: - mid = (left + right + 1) >> 1 - if (1 + mid) * mid // 2 <= n: - left = mid - else: - right = mid - 1 - return left -``` - -### **Java** - ```java class Solution { public int arrangeCoins(int n) { @@ -67,25 +52,6 @@ class Solution { } ``` -```java -class Solution { - public int arrangeCoins(int n) { - long left = 1, right = n; - while (left < right) { - long mid = (left + right + 1) >>> 1; - if ((1 + mid) * mid / 2 <= n) { - left = mid; - } else { - right = mid - 1; - } - } - return (int) left; - } -} -``` - -### **C++** - ```cpp using LL = long; @@ -106,8 +72,6 @@ public: }; ``` -### **Go** - ```go func arrangeCoins(n int) int { left, right := 1, n @@ -123,10 +87,42 @@ func arrangeCoins(n int) int { } ``` -### **...** + +### Solution 2 + + + +```python +class Solution: + def arrangeCoins(self, n: int) -> int: + left, right = 1, n + while left < right: + mid = (left + right + 1) >> 1 + if (1 + mid) * mid // 2 <= n: + left = mid + else: + right = mid - 1 + return left ``` +```java +class Solution { + public int arrangeCoins(int n) { + long left = 1, right = n; + while (left < right) { + long mid = (left + right + 1) >>> 1; + if ((1 + mid) * mid / 2 <= n) { + left = mid; + } else { + right = mid - 1; + } + } + return (int) left; + } +} ``` + + diff --git a/solution/0400-0499/0442.Find All Duplicates in an Array/README.md b/solution/0400-0499/0442.Find All Duplicates in an Array/README.md index 3efde188aa71b..874baf6caf8fe 100644 --- a/solution/0400-0499/0442.Find All Duplicates in an Array/README.md +++ b/solution/0400-0499/0442.Find All Duplicates in an Array/README.md @@ -46,14 +46,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: @@ -63,10 +59,6 @@ class Solution: return [v for i, v in enumerate(nums) if v != i + 1] ``` -### **Java** - - - ```java class Solution { public List findDuplicates(int[] nums) { @@ -93,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +106,6 @@ public: }; ``` -### **Go** - ```go func findDuplicates(nums []int) []int { for i := range nums { @@ -135,10 +123,6 @@ func findDuplicates(nums []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0442.Find All Duplicates in an Array/README_EN.md b/solution/0400-0499/0442.Find All Duplicates in an Array/README_EN.md index 177b6099a8135..7b376b9676a29 100644 --- a/solution/0400-0499/0442.Find All Duplicates in an Array/README_EN.md +++ b/solution/0400-0499/0442.Find All Duplicates in an Array/README_EN.md @@ -31,9 +31,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -44,8 +44,6 @@ class Solution: return [v for i, v in enumerate(nums) if v != i + 1] ``` -### **Java** - ```java class Solution { public List findDuplicates(int[] nums) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +91,6 @@ public: }; ``` -### **Go** - ```go func findDuplicates(nums []int) []int { for i := range nums { @@ -114,10 +108,6 @@ func findDuplicates(nums []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0443.String Compression/README.md b/solution/0400-0499/0443.String Compression/README.md index 71578cfb60615..ac9c15df31545 100644 --- a/solution/0400-0499/0443.String Compression/README.md +++ b/solution/0400-0499/0443.String Compression/README.md @@ -58,16 +58,10 @@ ## 解法 - - -双指针。 +### 方法一 -### **Python3** - - - ```python class Solution: def compress(self, chars: List[str]) -> int: @@ -87,10 +81,6 @@ class Solution: return k ``` -### **Java** - - - ```java class Solution { public int compress(char[] chars) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func compress(chars []byte) int { i, k, n := 0, 0, len(chars) @@ -161,8 +147,6 @@ func compress(chars []byte) int { } ``` -### **Rust** - ```rust impl Solution { pub fn compress(chars: &mut Vec) -> i32 { @@ -189,10 +173,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0443.String Compression/README_EN.md b/solution/0400-0499/0443.String Compression/README_EN.md index f63ec7004f8d8..3969fea1d84d4 100644 --- a/solution/0400-0499/0443.String Compression/README_EN.md +++ b/solution/0400-0499/0443.String Compression/README_EN.md @@ -53,9 +53,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return k ``` -### **Java** - ```java class Solution { public int compress(char[] chars) { @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func compress(chars []byte) int { i, k, n := 0, 0, len(chars) @@ -148,8 +142,6 @@ func compress(chars []byte) int { } ``` -### **Rust** - ```rust impl Solution { pub fn compress(chars: &mut Vec) -> i32 { @@ -176,10 +168,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0444.Sequence Reconstruction/README.md b/solution/0400-0499/0444.Sequence Reconstruction/README.md index e3c155e797765..0754d0f6357d4 100644 --- a/solution/0400-0499/0444.Sequence Reconstruction/README.md +++ b/solution/0400-0499/0444.Sequence Reconstruction/README.md @@ -69,18 +69,12 @@ ## 解法 - - -**方法一:拓扑排序** +### 方法一:拓扑排序 BFS 实现。 -### **Python3** - - - ```python class Solution: def sequenceReconstruction( @@ -104,10 +98,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean sequenceReconstruction(int[] nums, List> sequences) { @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +163,6 @@ public: }; ``` -### **Go** - ```go func sequenceReconstruction(nums []int, sequences [][]int) bool { n := len(nums) @@ -212,10 +198,6 @@ func sequenceReconstruction(nums []int, sequences [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0444.Sequence Reconstruction/README_EN.md b/solution/0400-0499/0444.Sequence Reconstruction/README_EN.md index 8003b71bb87df..7f6358aacb703 100644 --- a/solution/0400-0499/0444.Sequence Reconstruction/README_EN.md +++ b/solution/0400-0499/0444.Sequence Reconstruction/README_EN.md @@ -68,9 +68,9 @@ Since nums is the only shortest supersequence, we return true. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -95,8 +95,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean sequenceReconstruction(int[] nums, List> sequences) { @@ -133,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +160,6 @@ public: }; ``` -### **Go** - ```go func sequenceReconstruction(nums []int, sequences [][]int) bool { n := len(nums) @@ -201,10 +195,6 @@ func sequenceReconstruction(nums []int, sequences [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0445.Add Two Numbers II/README.md b/solution/0400-0499/0445.Add Two Numbers II/README.md index 3bc5301b9427b..02a055e42fb5e 100644 --- a/solution/0400-0499/0445.Add Two Numbers II/README.md +++ b/solution/0400-0499/0445.Add Two Numbers II/README.md @@ -51,28 +51,12 @@ ## 解法 - - -**方法一:翻转** +### 方法一:翻转 手动翻转链表 `l1` 与 `l2`,将此题转换为 [2. 两数相加](https://leetcode.cn/problems/add-two-numbers/),相加过程一致。对于最后返回的结果链表也需要进行翻转,共计三次。 -**方法二:栈** - -我们可以使用两个栈 $s1$ 和 $s2$ 分别存储两个链表元素,然后同时遍历两个栈,并使用变量 $carry$ 表示当前是否有进位。 - -遍历时,我们弹出对应栈的栈顶元素,计算它们与进位 $carry$ 的和,然后更新进位的值,并创建一个链表节点,插入答案链表的头部。如果两个栈都遍历结束,并且进位为 $0$ 时,遍历结束。 - -最后我们返回答案链表的头节点即可。 - -时间复杂度 $O(\max(m, n))$,空间复杂度 $O(m + n)$。其中 $m$ 和 $n$ 分别为两个链表的长度。 - -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -101,10 +85,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -140,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -182,8 +160,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -222,8 +198,6 @@ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -259,8 +233,6 @@ function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | nul } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -317,6 +289,20 @@ impl Solution { } ``` + + +### 方法二:栈 + +我们可以使用两个栈 $s1$ 和 $s2$ 分别存储两个链表元素,然后同时遍历两个栈,并使用变量 $carry$ 表示当前是否有进位。 + +遍历时,我们弹出对应栈的栈顶元素,计算它们与进位 $carry$ 的和,然后更新进位的值,并创建一个链表节点,插入答案链表的头部。如果两个栈都遍历结束,并且进位为 $0$ 时,遍历结束。 + +最后我们返回答案链表的头节点即可。 + +时间复杂度 $O(\max(m, n))$,空间复杂度 $O(m + n)$。其中 $m$ 和 $n$ 分别为两个链表的长度。 + + + ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -373,10 +359,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0445.Add Two Numbers II/README_EN.md b/solution/0400-0499/0445.Add Two Numbers II/README_EN.md index dbb30eb033ef1..a4c3220f4765d 100644 --- a/solution/0400-0499/0445.Add Two Numbers II/README_EN.md +++ b/solution/0400-0499/0445.Add Two Numbers II/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -76,8 +76,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -113,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -155,8 +151,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -195,8 +189,6 @@ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -232,8 +224,6 @@ function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | nul } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -290,6 +280,12 @@ impl Solution { } ``` + + +### Solution 2 + + + ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -346,10 +342,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/README.md b/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/README.md index a508452a3de6b..1539931ee89d2 100644 --- a/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/README.md +++ b/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:动态规划 + 哈希表** +### 方法一:动态规划 + 哈希表 我们定义 $f[i][d]$ 表示以 $nums[i]$ 为结尾,公差为 $d$ 的弱等差子序列(最少有两个元素)的个数。由于 $d$ 的范围很大,所以我们使用哈希表来统计。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def numberOfArithmeticSlices(self, nums: List[int]) -> int: @@ -90,10 +84,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numberOfArithmeticSlices(int[] nums) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func numberOfArithmeticSlices(nums []int) (ans int) { f := make([]map[int]int, len(nums)) @@ -156,8 +142,6 @@ func numberOfArithmeticSlices(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfArithmeticSlices(nums: number[]): number { const n = nums.length; @@ -175,10 +159,6 @@ function numberOfArithmeticSlices(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/README_EN.md b/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/README_EN.md index c9db97aae8307..1cabecbf01cd2 100644 --- a/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/README_EN.md +++ b/solution/0400-0499/0446.Arithmetic Slices II - Subsequence/README_EN.md @@ -55,9 +55,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numberOfArithmeticSlices(int[] nums) { @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +112,6 @@ public: }; ``` -### **Go** - ```go func numberOfArithmeticSlices(nums []int) (ans int) { f := make([]map[int]int, len(nums)) @@ -136,8 +130,6 @@ func numberOfArithmeticSlices(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfArithmeticSlices(nums: number[]): number { const n = nums.length; @@ -155,10 +147,6 @@ function numberOfArithmeticSlices(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0447.Number of Boomerangs/README.md b/solution/0400-0499/0447.Number of Boomerangs/README.md index 41fda5e321e0e..40a5f7ebfad88 100644 --- a/solution/0400-0499/0447.Number of Boomerangs/README.md +++ b/solution/0400-0499/0447.Number of Boomerangs/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:枚举 + 计数** +### 方法一:枚举 + 计数 我们可以枚举 `points` 中的每个点作为回旋镖的点 $i$,然后用一个哈希表 $cnt$ 记录其他点到 $i$ 的距离出现的次数。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def numberOfBoomerangs(self, points: List[List[int]]) -> int: @@ -76,23 +70,6 @@ class Solution: return ans << 1 ``` -```python -class Solution: - def numberOfBoomerangs(self, points: List[List[int]]) -> int: - ans = 0 - for p1 in points: - cnt = Counter() - for p2 in points: - d = dist(p1, p2) - cnt[d] += 1 - ans += sum(x * (x - 1) for x in cnt.values()) - return ans -``` - -### **Java** - - - ```java class Solution { public int numberOfBoomerangs(int[][] points) { @@ -110,6 +87,73 @@ class Solution { } ``` +```cpp +class Solution { +public: + int numberOfBoomerangs(vector>& points) { + int ans = 0; + for (auto& p1 : points) { + unordered_map cnt; + for (auto& p2 : points) { + int d = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); + ans += cnt[d]; + cnt[d]++; + } + } + return ans << 1; + } +}; +``` + +```go +func numberOfBoomerangs(points [][]int) (ans int) { + for _, p1 := range points { + cnt := map[int]int{} + for _, p2 := range points { + d := (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]) + ans += cnt[d] + cnt[d]++ + } + } + ans <<= 1 + return +} +``` + +```ts +function numberOfBoomerangs(points: number[][]): number { + let ans = 0; + for (const [x1, y1] of points) { + const cnt: Map = new Map(); + for (const [x2, y2] of points) { + const d = (x1 - x2) ** 2 + (y1 - y2) ** 2; + ans += cnt.get(d) || 0; + cnt.set(d, (cnt.get(d) || 0) + 1); + } + } + return ans << 1; +} +``` + + + +### 方法二 + + + +```python +class Solution: + def numberOfBoomerangs(self, points: List[List[int]]) -> int: + ans = 0 + for p1 in points: + cnt = Counter() + for p2 in points: + d = dist(p1, p2) + cnt[d] += 1 + ans += sum(x * (x - 1) for x in cnt.values()) + return ans +``` + ```java class Solution { public int numberOfBoomerangs(int[][] points) { @@ -129,26 +173,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numberOfBoomerangs(vector>& points) { - int ans = 0; - for (auto& p1 : points) { - unordered_map cnt; - for (auto& p2 : points) { - int d = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); - ans += cnt[d]; - cnt[d]++; - } - } - return ans << 1; - } -}; -``` - ```cpp class Solution { public: @@ -169,23 +193,6 @@ public: }; ``` -### **Go** - -```go -func numberOfBoomerangs(points [][]int) (ans int) { - for _, p1 := range points { - cnt := map[int]int{} - for _, p2 := range points { - d := (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]) - ans += cnt[d] - cnt[d]++ - } - } - ans <<= 1 - return -} -``` - ```go func numberOfBoomerangs(points [][]int) (ans int) { for _, p1 := range points { @@ -202,23 +209,6 @@ func numberOfBoomerangs(points [][]int) (ans int) { } ``` -### **TypeScript** - -```ts -function numberOfBoomerangs(points: number[][]): number { - let ans = 0; - for (const [x1, y1] of points) { - const cnt: Map = new Map(); - for (const [x2, y2] of points) { - const d = (x1 - x2) ** 2 + (y1 - y2) ** 2; - ans += cnt.get(d) || 0; - cnt.set(d, (cnt.get(d) || 0) + 1); - } - } - return ans << 1; -} -``` - ```ts function numberOfBoomerangs(points: number[][]): number { let ans = 0; @@ -236,10 +226,6 @@ function numberOfBoomerangs(points: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0447.Number of Boomerangs/README_EN.md b/solution/0400-0499/0447.Number of Boomerangs/README_EN.md index 10f1d0d2bbee2..484a9dd82147d 100644 --- a/solution/0400-0499/0447.Number of Boomerangs/README_EN.md +++ b/solution/0400-0499/0447.Number of Boomerangs/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Enumeration + Counting** +### Solution 1: Enumeration + Counting We can enumerate each point in `points` as the boomerang's point $i$, and then use a hash table $cnt$ to record the number of times the distance from other points to $i$ appears. @@ -54,8 +54,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ i -### **Python3** - ```python class Solution: def numberOfBoomerangs(self, points: List[List[int]]) -> int: @@ -69,21 +67,6 @@ class Solution: return ans << 1 ``` -```python -class Solution: - def numberOfBoomerangs(self, points: List[List[int]]) -> int: - ans = 0 - for p1 in points: - cnt = Counter() - for p2 in points: - d = dist(p1, p2) - cnt[d] += 1 - ans += sum(x * (x - 1) for x in cnt.values()) - return ans -``` - -### **Java** - ```java class Solution { public int numberOfBoomerangs(int[][] points) { @@ -101,6 +84,73 @@ class Solution { } ``` +```cpp +class Solution { +public: + int numberOfBoomerangs(vector>& points) { + int ans = 0; + for (auto& p1 : points) { + unordered_map cnt; + for (auto& p2 : points) { + int d = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); + ans += cnt[d]; + cnt[d]++; + } + } + return ans << 1; + } +}; +``` + +```go +func numberOfBoomerangs(points [][]int) (ans int) { + for _, p1 := range points { + cnt := map[int]int{} + for _, p2 := range points { + d := (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]) + ans += cnt[d] + cnt[d]++ + } + } + ans <<= 1 + return +} +``` + +```ts +function numberOfBoomerangs(points: number[][]): number { + let ans = 0; + for (const [x1, y1] of points) { + const cnt: Map = new Map(); + for (const [x2, y2] of points) { + const d = (x1 - x2) ** 2 + (y1 - y2) ** 2; + ans += cnt.get(d) || 0; + cnt.set(d, (cnt.get(d) || 0) + 1); + } + } + return ans << 1; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def numberOfBoomerangs(self, points: List[List[int]]) -> int: + ans = 0 + for p1 in points: + cnt = Counter() + for p2 in points: + d = dist(p1, p2) + cnt[d] += 1 + ans += sum(x * (x - 1) for x in cnt.values()) + return ans +``` + ```java class Solution { public int numberOfBoomerangs(int[][] points) { @@ -120,26 +170,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numberOfBoomerangs(vector>& points) { - int ans = 0; - for (auto& p1 : points) { - unordered_map cnt; - for (auto& p2 : points) { - int d = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); - ans += cnt[d]; - cnt[d]++; - } - } - return ans << 1; - } -}; -``` - ```cpp class Solution { public: @@ -160,23 +190,6 @@ public: }; ``` -### **Go** - -```go -func numberOfBoomerangs(points [][]int) (ans int) { - for _, p1 := range points { - cnt := map[int]int{} - for _, p2 := range points { - d := (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]) - ans += cnt[d] - cnt[d]++ - } - } - ans <<= 1 - return -} -``` - ```go func numberOfBoomerangs(points [][]int) (ans int) { for _, p1 := range points { @@ -193,23 +206,6 @@ func numberOfBoomerangs(points [][]int) (ans int) { } ``` -### **TypeScript** - -```ts -function numberOfBoomerangs(points: number[][]): number { - let ans = 0; - for (const [x1, y1] of points) { - const cnt: Map = new Map(); - for (const [x2, y2] of points) { - const d = (x1 - x2) ** 2 + (y1 - y2) ** 2; - ans += cnt.get(d) || 0; - cnt.set(d, (cnt.get(d) || 0) + 1); - } - } - return ans << 1; -} -``` - ```ts function numberOfBoomerangs(points: number[][]): number { let ans = 0; @@ -227,10 +223,6 @@ function numberOfBoomerangs(points: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/README.md b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/README.md index 2715f9d9ded8b..57aa1f01fcca4 100644 --- a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/README.md +++ b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/README.md @@ -38,28 +38,14 @@ ## 解法 - - -**方法一:数组或哈希表** +### 方法一:数组或哈希表 我们可以使用数组或哈希表记录数组中的数字,然后遍历 `[1, n]` 区间内的数字,若数字不存在于数组或哈希表中,则说明数组中缺失该数字,将其添加到结果列表中。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。 -**方法二:原地修改** - -我们可以遍历数组 $nums$,将 $|nums[i]|-1$ 位置的数字标记为负数,表示数组 $nums[i]$ 出现过。最后遍历数组 $nums$,若 $nums[i]$ 为正数,则说明数组中缺失 $i+1$,将其添加到结果列表中。 - -遍历结束后,返回结果列表即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组长度。 - -### **Python3** - - - ```python class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: @@ -67,20 +53,6 @@ class Solution: return [x for x in range(1, len(nums) + 1) if x not in s] ``` -```python -class Solution: - def findDisappearedNumbers(self, nums: List[int]) -> List[int]: - for x in nums: - i = abs(x) - 1 - if nums[i] > 0: - nums[i] *= -1 - return [i + 1 for i in range(len(nums)) if nums[i] > 0] -``` - -### **Java** - - - ```java class Solution { public List findDisappearedNumbers(int[] nums) { @@ -100,29 +72,6 @@ class Solution { } ``` -```java -class Solution { - public List findDisappearedNumbers(int[] nums) { - int n = nums.length; - for (int x : nums) { - int i = Math.abs(x) - 1; - if (nums[i] > 0) { - nums[i] *= -1; - } - } - List ans = new ArrayList<>(); - for (int i = 0; i < n; i++) { - if (nums[i] > 0) { - ans.add(i + 1); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -144,6 +93,82 @@ public: }; ``` +```go +func findDisappearedNumbers(nums []int) (ans []int) { + n := len(nums) + s := make([]bool, n+1) + for _, x := range nums { + s[x] = true + } + for i := 1; i <= n; i++ { + if !s[i] { + ans = append(ans, i) + } + } + return +} +``` + +```ts +function findDisappearedNumbers(nums: number[]): number[] { + const n = nums.length; + const s: boolean[] = new Array(n + 1).fill(false); + for (const x of nums) { + s[x] = true; + } + const ans: number[] = []; + for (let i = 1; i <= n; ++i) { + if (!s[i]) { + ans.push(i); + } + } + return ans; +} +``` + + + +### 方法二:原地修改 + +我们可以遍历数组 $nums$,将 $|nums[i]|-1$ 位置的数字标记为负数,表示数组 $nums[i]$ 出现过。最后遍历数组 $nums$,若 $nums[i]$ 为正数,则说明数组中缺失 $i+1$,将其添加到结果列表中。 + +遍历结束后,返回结果列表即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组长度。 + + + +```python +class Solution: + def findDisappearedNumbers(self, nums: List[int]) -> List[int]: + for x in nums: + i = abs(x) - 1 + if nums[i] > 0: + nums[i] *= -1 + return [i + 1 for i in range(len(nums)) if nums[i] > 0] +``` + +```java +class Solution { + public List findDisappearedNumbers(int[] nums) { + int n = nums.length; + for (int x : nums) { + int i = Math.abs(x) - 1; + if (nums[i] > 0) { + nums[i] *= -1; + } + } + List ans = new ArrayList<>(); + for (int i = 0; i < n; i++) { + if (nums[i] > 0) { + ans.add(i + 1); + } + } + return ans; + } +} +``` + ```cpp class Solution { public: @@ -166,24 +191,6 @@ public: }; ``` -### **Go** - -```go -func findDisappearedNumbers(nums []int) (ans []int) { - n := len(nums) - s := make([]bool, n+1) - for _, x := range nums { - s[x] = true - } - for i := 1; i <= n; i++ { - if !s[i] { - ans = append(ans, i) - } - } - return -} -``` - ```go func findDisappearedNumbers(nums []int) (ans []int) { n := len(nums) @@ -209,25 +216,6 @@ func abs(x int) int { } ``` -### **TypeScript** - -```ts -function findDisappearedNumbers(nums: number[]): number[] { - const n = nums.length; - const s: boolean[] = new Array(n + 1).fill(false); - for (const x of nums) { - s[x] = true; - } - const ans: number[] = []; - for (let i = 1; i <= n; ++i) { - if (!s[i]) { - ans.push(i); - } - } - return ans; -} -``` - ```ts function findDisappearedNumbers(nums: number[]): number[] { const n = nums.length; @@ -247,10 +235,6 @@ function findDisappearedNumbers(nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/README_EN.md b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/README_EN.md index 918d0496e20b1..91f3ab45287ee 100644 --- a/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/README_EN.md +++ b/solution/0400-0499/0448.Find All Numbers Disappeared in an Array/README_EN.md @@ -28,9 +28,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -39,18 +39,6 @@ class Solution: return [x for x in range(1, len(nums) + 1) if x not in s] ``` -```python -class Solution: - def findDisappearedNumbers(self, nums: List[int]) -> List[int]: - for x in nums: - i = abs(x) - 1 - if nums[i] > 0: - nums[i] *= -1 - return [i + 1 for i in range(len(nums)) if nums[i] > 0] -``` - -### **Java** - ```java class Solution { public List findDisappearedNumbers(int[] nums) { @@ -70,29 +58,6 @@ class Solution { } ``` -```java -class Solution { - public List findDisappearedNumbers(int[] nums) { - int n = nums.length; - for (int x : nums) { - int i = Math.abs(x) - 1; - if (nums[i] > 0) { - nums[i] *= -1; - } - } - List ans = new ArrayList<>(); - for (int i = 0; i < n; i++) { - if (nums[i] > 0) { - ans.add(i + 1); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -114,6 +79,76 @@ public: }; ``` +```go +func findDisappearedNumbers(nums []int) (ans []int) { + n := len(nums) + s := make([]bool, n+1) + for _, x := range nums { + s[x] = true + } + for i := 1; i <= n; i++ { + if !s[i] { + ans = append(ans, i) + } + } + return +} +``` + +```ts +function findDisappearedNumbers(nums: number[]): number[] { + const n = nums.length; + const s: boolean[] = new Array(n + 1).fill(false); + for (const x of nums) { + s[x] = true; + } + const ans: number[] = []; + for (let i = 1; i <= n; ++i) { + if (!s[i]) { + ans.push(i); + } + } + return ans; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def findDisappearedNumbers(self, nums: List[int]) -> List[int]: + for x in nums: + i = abs(x) - 1 + if nums[i] > 0: + nums[i] *= -1 + return [i + 1 for i in range(len(nums)) if nums[i] > 0] +``` + +```java +class Solution { + public List findDisappearedNumbers(int[] nums) { + int n = nums.length; + for (int x : nums) { + int i = Math.abs(x) - 1; + if (nums[i] > 0) { + nums[i] *= -1; + } + } + List ans = new ArrayList<>(); + for (int i = 0; i < n; i++) { + if (nums[i] > 0) { + ans.add(i + 1); + } + } + return ans; + } +} +``` + ```cpp class Solution { public: @@ -136,24 +171,6 @@ public: }; ``` -### **Go** - -```go -func findDisappearedNumbers(nums []int) (ans []int) { - n := len(nums) - s := make([]bool, n+1) - for _, x := range nums { - s[x] = true - } - for i := 1; i <= n; i++ { - if !s[i] { - ans = append(ans, i) - } - } - return -} -``` - ```go func findDisappearedNumbers(nums []int) (ans []int) { n := len(nums) @@ -179,25 +196,6 @@ func abs(x int) int { } ``` -### **TypeScript** - -```ts -function findDisappearedNumbers(nums: number[]): number[] { - const n = nums.length; - const s: boolean[] = new Array(n + 1).fill(false); - for (const x of nums) { - s[x] = true; - } - const ans: number[] = []; - for (let i = 1; i <= n; ++i) { - if (!s[i]) { - ans.push(i); - } - } - return ans; -} -``` - ```ts function findDisappearedNumbers(nums: number[]): number[] { const n = nums.length; @@ -217,10 +215,6 @@ function findDisappearedNumbers(nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0449.Serialize and Deserialize BST/README.md b/solution/0400-0499/0449.Serialize and Deserialize BST/README.md index 4689bc07f056f..12cd6f2dd61a9 100644 --- a/solution/0400-0499/0449.Serialize and Deserialize BST/README.md +++ b/solution/0400-0499/0449.Serialize and Deserialize BST/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:先序遍历** +### 方法一:先序遍历 题目给定的是二叉搜索树,我们知道二叉搜索树的中序遍历是有序的,而通过“先序遍历”和“中序遍历”可以唯一确定一棵二叉树,所以我们可以通过先序遍历的结果和中序遍历的结果来唯一确定一棵二叉搜索树。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -108,10 +102,6 @@ class Codec: # return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -177,8 +167,6 @@ public class Codec { // return ans; ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -249,8 +237,6 @@ public: // return ans; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -323,10 +309,6 @@ func (this *Codec) deserialize(data string) *TreeNode { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0449.Serialize and Deserialize BST/README_EN.md b/solution/0400-0499/0449.Serialize and Deserialize BST/README_EN.md index 6aa7670be348a..2f0d9136db314 100644 --- a/solution/0400-0499/0449.Serialize and Deserialize BST/README_EN.md +++ b/solution/0400-0499/0449.Serialize and Deserialize BST/README_EN.md @@ -29,9 +29,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -85,8 +85,6 @@ class Codec: # return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -152,8 +150,6 @@ public class Codec { // return ans; ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -224,8 +220,6 @@ public: // return ans; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -298,10 +292,6 @@ func (this *Codec) deserialize(data string) *TreeNode { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0450.Delete Node in a BST/README.md b/solution/0400-0499/0450.Delete Node in a BST/README.md index 86ff1000debbc..0235c0a1c81c4 100644 --- a/solution/0400-0499/0450.Delete Node in a BST/README.md +++ b/solution/0400-0499/0450.Delete Node in a BST/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 二叉搜索树有以下性质: @@ -86,10 +84,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -119,10 +113,6 @@ class Solution: return root ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -169,8 +159,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -206,8 +194,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -245,8 +231,6 @@ func deleteNode(root *TreeNode, key int) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -295,8 +279,6 @@ function deleteNode(root: TreeNode | null, key: number): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -371,10 +353,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0450.Delete Node in a BST/README_EN.md b/solution/0400-0499/0450.Delete Node in a BST/README_EN.md index 73e9b1b47958b..1250f71ceb29e 100644 --- a/solution/0400-0499/0450.Delete Node in a BST/README_EN.md +++ b/solution/0400-0499/0450.Delete Node in a BST/README_EN.md @@ -56,9 +56,9 @@ Please notice that another valid answer is [5,2,6,null,4,null,7] and it's al ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -89,8 +89,6 @@ class Solution: return root ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -137,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -174,8 +170,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -213,8 +207,6 @@ func deleteNode(root *TreeNode, key int) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -263,8 +255,6 @@ function deleteNode(root: TreeNode | null, key: number): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -339,10 +329,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0451.Sort Characters By Frequency/README.md b/solution/0400-0499/0451.Sort Characters By Frequency/README.md index ad75aa1e2f943..012ec62bf942a 100644 --- a/solution/0400-0499/0451.Sort Characters By Frequency/README.md +++ b/solution/0400-0499/0451.Sort Characters By Frequency/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:哈希表 + 排序** +### 方法一:哈希表 + 排序 我们用哈希表 $cnt$ 统计字符串 $s$ 中每个字符出现的次数,然后将 $cnt$ 中的键值对按照出现次数降序排序,最后按照排序后的顺序拼接字符串即可。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def frequencySort(self, s: str) -> str: @@ -71,10 +65,6 @@ class Solution: return ''.join(c * v for c, v in sorted(cnt.items(), key=lambda x: -x[1])) ``` -### **Java** - - - ```java class Solution { public String frequencySort(String s) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func frequencySort(s string) string { cnt := map[byte]int{} @@ -142,8 +128,6 @@ func frequencySort(s string) string { } ``` -### **TypeScript** - ```ts function frequencySort(s: string): string { const cnt: Map = new Map(); @@ -159,8 +143,6 @@ function frequencySort(s: string): string { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -178,8 +160,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -200,10 +180,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0451.Sort Characters By Frequency/README_EN.md b/solution/0400-0499/0451.Sort Characters By Frequency/README_EN.md index cd931e713a697..16a91ed56e474 100644 --- a/solution/0400-0499/0451.Sort Characters By Frequency/README_EN.md +++ b/solution/0400-0499/0451.Sort Characters By Frequency/README_EN.md @@ -46,9 +46,9 @@ Note that 'A' and 'a' are treated as two different characters. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return ''.join(c * v for c, v in sorted(cnt.items(), key=lambda x: -x[1])) ``` -### **Java** - ```java class Solution { public String frequencySort(String s) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +101,6 @@ public: }; ``` -### **Go** - ```go func frequencySort(s string) string { cnt := map[byte]int{} @@ -126,8 +120,6 @@ func frequencySort(s string) string { } ``` -### **TypeScript** - ```ts function frequencySort(s: string): string { const cnt: Map = new Map(); @@ -143,8 +135,6 @@ function frequencySort(s: string): string { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -162,8 +152,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -184,10 +172,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/README.md b/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/README.md index 1110bd47224a6..e1f0bcbf32c9d 100644 --- a/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/README.md +++ b/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:排序 + 贪心** +### 方法一:排序 + 贪心 我们可以将所有气球按照右端点升序排序,然后从左到右遍历气球,维护当前的箭所能覆盖的最右端点 $last$,如果当前气球的左端点 $a$ 大于 $last$,说明当前箭无法覆盖当前气球,需要额外射出一支箭,那么答案加一,同时更新 $last$ 为当前气球的右端点 $b$。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def findMinArrowShots(self, points: List[List[int]]) -> int: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int findMinArrowShots(int[][] points) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func findMinArrowShots(points [][]int) (ans int) { sort.Slice(points, func(i, j int) bool { return points[i][1] < points[j][1] }) @@ -144,8 +130,6 @@ func findMinArrowShots(points [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function findMinArrowShots(points: number[][]): number { points.sort((a, b) => a[1] - b[1]); @@ -161,8 +145,6 @@ function findMinArrowShots(points: number[][]): number { } ``` -### **C#** - ```cs public class Solution { public int FindMinArrowShots(int[][] points) { @@ -180,10 +162,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/README_EN.md b/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/README_EN.md index 679adc65d1e81..0515f74be68ba 100644 --- a/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/README_EN.md +++ b/solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,11 +65,10 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int findMinArrowShots(int[][] points) { + // 直接 a[1] - b[1] 可能会溢出 Arrays.sort(points, Comparator.comparingInt(a -> a[1])); int ans = 0; long last = -(1L << 60); @@ -85,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +105,6 @@ public: }; ``` -### **Go** - ```go func findMinArrowShots(points [][]int) (ans int) { sort.Slice(points, func(i, j int) bool { return points[i][1] < points[j][1] }) @@ -125,8 +120,6 @@ func findMinArrowShots(points [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function findMinArrowShots(points: number[][]): number { points.sort((a, b) => a[1] - b[1]); @@ -142,8 +135,6 @@ function findMinArrowShots(points: number[][]): number { } ``` -### **C#** - ```cs public class Solution { public int FindMinArrowShots(int[][] points) { @@ -161,10 +152,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/README.md b/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/README.md index dcd6cb90d8ca4..fbdc3060e8ddd 100644 --- a/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/README.md +++ b/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 我们不妨记数组 $nums$ 的最小值为 $mi$,数组的和为 $s$,数组的长度为 $n$。 @@ -71,20 +69,12 @@ $$ -### **Python3** - - - ```python class Solution: def minMoves(self, nums: List[int]) -> int: return sum(nums) - min(nums) * len(nums) ``` -### **Java** - - - ```java class Solution { public int minMoves(int[] nums) { @@ -93,22 +83,6 @@ class Solution { } ``` -```java -class Solution { - public int minMoves(int[] nums) { - int s = 0; - int mi = 1 << 30; - for (int x : nums) { - s += x; - mi = Math.min(mi, x); - } - return s - mi * nums.length; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -124,8 +98,6 @@ public: }; ``` -### **Go** - ```go func minMoves(nums []int) int { mi := 1 << 30 @@ -140,8 +112,6 @@ func minMoves(nums []int) int { } ``` -### **TypeScript** - ```ts function minMoves(nums: number[]): number { let mi = 1 << 30; @@ -154,10 +124,26 @@ function minMoves(nums: number[]): number { } ``` -### **...** + -``` +### 方法二 + + +```java +class Solution { + public int minMoves(int[] nums) { + int s = 0; + int mi = 1 << 30; + for (int x : nums) { + s += x; + mi = Math.min(mi, x); + } + return s - mi * nums.length; + } +} ``` + + diff --git a/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/README_EN.md b/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/README_EN.md index 6c4dc2b1b6110..2c3720c39ff9b 100644 --- a/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/README_EN.md +++ b/solution/0400-0499/0453.Minimum Moves to Equal Array Elements/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -47,8 +47,6 @@ class Solution: return sum(nums) - min(nums) * len(nums) ``` -### **Java** - ```java class Solution { public int minMoves(int[] nums) { @@ -57,22 +55,6 @@ class Solution { } ``` -```java -class Solution { - public int minMoves(int[] nums) { - int s = 0; - int mi = 1 << 30; - for (int x : nums) { - s += x; - mi = Math.min(mi, x); - } - return s - mi * nums.length; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -88,8 +70,6 @@ public: }; ``` -### **Go** - ```go func minMoves(nums []int) int { mi := 1 << 30 @@ -104,8 +84,6 @@ func minMoves(nums []int) int { } ``` -### **TypeScript** - ```ts function minMoves(nums: number[]): number { let mi = 1 << 30; @@ -118,10 +96,26 @@ function minMoves(nums: number[]): number { } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + public int minMoves(int[] nums) { + int s = 0; + int mi = 1 << 30; + for (int x : nums) { + s += x; + mi = Math.min(mi, x); + } + return s - mi * nums.length; + } +} ``` + + diff --git a/solution/0400-0499/0454.4Sum II/README.md b/solution/0400-0499/0454.4Sum II/README.md index 6c628bce98b19..81bc3d9e6dddf 100644 --- a/solution/0400-0499/0454.4Sum II/README.md +++ b/solution/0400-0499/0454.4Sum II/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以将数组 $nums1$ 和 $nums2$ 中的元素 $a$ 和 $b$ 相加,将所有可能的和存储在哈希表 $cnt$ 中,其中键为两数之和,值为两数之和出现的次数。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def fourSumCount( @@ -73,10 +67,6 @@ class Solution: return sum(cnt[-(c + d)] for c in nums3 for d in nums4) ``` -### **Java** - - - ```java class Solution { public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) (ans int) { cnt := map[int]int{} @@ -139,8 +125,6 @@ func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) (ans int) } ``` -### **TypeScript** - ```ts function fourSumCount(nums1: number[], nums2: number[], nums3: number[], nums4: number[]): number { const cnt: Map = new Map(); @@ -161,10 +145,6 @@ function fourSumCount(nums1: number[], nums2: number[], nums3: number[], nums4: } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0454.4Sum II/README_EN.md b/solution/0400-0499/0454.4Sum II/README_EN.md index 4f2c4fb60e3f2..d2984aa1fbf7f 100644 --- a/solution/0400-0499/0454.4Sum II/README_EN.md +++ b/solution/0400-0499/0454.4Sum II/README_EN.md @@ -44,14 +44,12 @@ The two tuples are: ## Solutions -**Solution 1: HashMap** +### Solution 1: HashMap Time complexity $O(n^2)$, Space complexity $O(n^2)$. -### **Python3** - ```python class Solution: def fourSumCount( @@ -61,8 +59,6 @@ class Solution: return sum(cnt[-(c + d)] for c in nums3 for d in nums4) ``` -### **Java** - ```java class Solution { public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { @@ -83,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +100,6 @@ public: }; ``` -### **Go** - ```go func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) (ans int) { cnt := map[int]int{} @@ -125,8 +117,6 @@ func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) (ans int) } ``` -### **TypeScript** - ```ts function fourSumCount(nums1: number[], nums2: number[], nums3: number[], nums4: number[]): number { const cnt: Map = new Map(); @@ -147,10 +137,6 @@ function fourSumCount(nums1: number[], nums2: number[], nums3: number[], nums4: } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0455.Assign Cookies/README.md b/solution/0400-0499/0455.Assign Cookies/README.md index 2fa2f1112a6b4..3b58e13a74b03 100644 --- a/solution/0400-0499/0455.Assign Cookies/README.md +++ b/solution/0400-0499/0455.Assign Cookies/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:排序 + 双指针** +### 方法一:排序 + 双指针 根据题目描述,我们应该优先将饼干分配给胃口值小的孩子,这样可以尽可能满足更多的孩子。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: @@ -81,10 +75,6 @@ class Solution: return len(g) ``` -### **Java** - - - ```java class Solution { public int findContentChildren(int[] g, int[] s) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func findContentChildren(g []int, s []int) int { sort.Ints(g) @@ -147,15 +133,8 @@ func findContentChildren(g []int, s []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} g - * @param {number[]} s - * @return {number} - */ -var findContentChildren = function (g, s) { +```ts +function findContentChildren(g: number[], s: number[]): number { g.sort((a, b) => a - b); s.sort((a, b) => a - b); const m = g.length; @@ -169,13 +148,16 @@ var findContentChildren = function (g, s) { } } return m; -}; +} ``` -### **TypeScript** - -```ts -function findContentChildren(g: number[], s: number[]): number { +```js +/** + * @param {number[]} g + * @param {number[]} s + * @return {number} + */ +var findContentChildren = function (g, s) { g.sort((a, b) => a - b); s.sort((a, b) => a - b); const m = g.length; @@ -189,13 +171,9 @@ function findContentChildren(g: number[], s: number[]): number { } } return m; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0400-0499/0455.Assign Cookies/README_EN.md b/solution/0400-0499/0455.Assign Cookies/README_EN.md index d6a50ce09f06f..d619571dd16b5 100644 --- a/solution/0400-0499/0455.Assign Cookies/README_EN.md +++ b/solution/0400-0499/0455.Assign Cookies/README_EN.md @@ -40,9 +40,9 @@ You need to output 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return len(g) ``` -### **Java** - ```java class Solution { public int findContentChildren(int[] g, int[] s) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +99,6 @@ public: }; ``` -### **Go** - ```go func findContentChildren(g []int, s []int) int { sort.Ints(g) @@ -123,15 +117,8 @@ func findContentChildren(g []int, s []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} g - * @param {number[]} s - * @return {number} - */ -var findContentChildren = function (g, s) { +```ts +function findContentChildren(g: number[], s: number[]): number { g.sort((a, b) => a - b); s.sort((a, b) => a - b); const m = g.length; @@ -145,13 +132,16 @@ var findContentChildren = function (g, s) { } } return m; -}; +} ``` -### **TypeScript** - -```ts -function findContentChildren(g: number[], s: number[]): number { +```js +/** + * @param {number[]} g + * @param {number[]} s + * @return {number} + */ +var findContentChildren = function (g, s) { g.sort((a, b) => a - b); s.sort((a, b) => a - b); const m = g.length; @@ -165,13 +155,9 @@ function findContentChildren(g: number[], s: number[]): number { } } return m; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0400-0499/0456.132 Pattern/README.md b/solution/0400-0499/0456.132 Pattern/README.md index 18537a4c85e25..ac932750828d6 100644 --- a/solution/0400-0499/0456.132 Pattern/README.md +++ b/solution/0400-0499/0456.132 Pattern/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 我们可以枚举从右往左枚举整数 $nums[i]$,并维护一个单调栈,栈中的元素从栈底到栈顶单调递减。维护一个变量 $vk$,表示 $nums[i]$ 右侧且小于 $nums[i]$ 的最大值。初始时,$vk$ 的值为 $-\infty$。 @@ -60,22 +58,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组的长度。 -**方法二:离散化 + 树状数组** - -我们可以用树状数组维护比某个数小的元素的个数,用一个数组 $left$ 记录 $nums[i]$ 左侧的最小值。 - -我们从右往左遍历数组,对于遍历到的每个元素 $nums[i]$,我们将 $nums[i]$ 离散化为一个整数 $x$,将 $left[i]$ 离散化为一个整数 $y$,如果此时 $x \gt y$,并且树状数组中存在比 $y$ 大但比 $x$ 小的元素,则说明存在满足 $nums[i] \lt nums[k] \lt nums[j]$ 的三元组,返回 `true`。否则,我们将 $nums[i]$ 的离散化结果 $x$ 更新到树状数组中。 - -如果遍历结束后仍未找到满足条件的三元组,说明不存在这样的三元组,返回 `false`。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组的长度。 - -### **Python3** - - - ```python class Solution: def find132pattern(self, nums: List[int]) -> bool: @@ -90,6 +74,115 @@ class Solution: return False ``` +```java +class Solution { + public boolean find132pattern(int[] nums) { + int vk = -(1 << 30); + Deque stk = new ArrayDeque<>(); + for (int i = nums.length - 1; i >= 0; --i) { + if (nums[i] < vk) { + return true; + } + while (!stk.isEmpty() && stk.peek() < nums[i]) { + vk = stk.pop(); + } + stk.push(nums[i]); + } + return false; + } +} +``` + +```cpp +class Solution { +public: + bool find132pattern(vector& nums) { + int vk = INT_MIN; + stack stk; + for (int i = nums.size() - 1; ~i; --i) { + if (nums[i] < vk) { + return true; + } + while (!stk.empty() && stk.top() < nums[i]) { + vk = stk.top(); + stk.pop(); + } + stk.push(nums[i]); + } + return false; + } +}; +``` + +```go +func find132pattern(nums []int) bool { + vk := -(1 << 30) + stk := []int{} + for i := len(nums) - 1; i >= 0; i-- { + if nums[i] < vk { + return true + } + for len(stk) > 0 && stk[len(stk)-1] < nums[i] { + vk = stk[len(stk)-1] + stk = stk[:len(stk)-1] + } + stk = append(stk, nums[i]) + } + return false +} +``` + +```ts +function find132pattern(nums: number[]): boolean { + let vk = -Infinity; + const stk: number[] = []; + for (let i = nums.length - 1; i >= 0; --i) { + if (nums[i] < vk) { + return true; + } + while (stk.length && stk[stk.length - 1] < nums[i]) { + vk = stk.pop()!; + } + stk.push(nums[i]); + } + return false; +} +``` + +```rust +impl Solution { + pub fn find132pattern(nums: Vec) -> bool { + let n = nums.len(); + let mut vk = i32::MIN; + let mut stk = vec![]; + for i in (0..n).rev() { + if nums[i] < vk { + return true; + } + while !stk.is_empty() && stk.last().unwrap() < &nums[i] { + vk = stk.pop().unwrap(); + } + stk.push(nums[i]); + } + false + } +} +``` + + + +### 方法二:离散化 + 树状数组 + +我们可以用树状数组维护比某个数小的元素的个数,用一个数组 $left$ 记录 $nums[i]$ 左侧的最小值。 + +我们从右往左遍历数组,对于遍历到的每个元素 $nums[i]$,我们将 $nums[i]$ 离散化为一个整数 $x$,将 $left[i]$ 离散化为一个整数 $y$,如果此时 $x \gt y$,并且树状数组中存在比 $y$ 大但比 $x$ 小的元素,则说明存在满足 $nums[i] \lt nums[k] \lt nums[j]$ 的三元组,返回 `true`。否则,我们将 $nums[i]$ 的离散化结果 $x$ 更新到树状数组中。 + +如果遍历结束后仍未找到满足条件的三元组,说明不存在这样的三元组,返回 `false`。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组的长度。 + + + ```python class BinaryIndexedTree: def __init__(self, n): @@ -126,29 +219,6 @@ class Solution: return False ``` -### **Java** - - - -```java -class Solution { - public boolean find132pattern(int[] nums) { - int vk = -(1 << 30); - Deque stk = new ArrayDeque<>(); - for (int i = nums.length - 1; i >= 0; --i) { - if (nums[i] < vk) { - return true; - } - while (!stk.isEmpty() && stk.peek() < nums[i]) { - vk = stk.pop(); - } - stk.push(nums[i]); - } - return false; - } -} -``` - ```java class BinaryIndexedTree { private int n; @@ -217,29 +287,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool find132pattern(vector& nums) { - int vk = INT_MIN; - stack stk; - for (int i = nums.size() - 1; ~i; --i) { - if (nums[i] < vk) { - return true; - } - while (!stk.empty() && stk.top() < nums[i]) { - vk = stk.top(); - stk.pop(); - } - stk.push(nums[i]); - } - return false; - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -295,26 +342,6 @@ public: }; ``` -### **Go** - -```go -func find132pattern(nums []int) bool { - vk := -(1 << 30) - stk := []int{} - for i := len(nums) - 1; i >= 0; i-- { - if nums[i] < vk { - return true - } - for len(stk) > 0 && stk[len(stk)-1] < nums[i] { - vk = stk[len(stk)-1] - stk = stk[:len(stk)-1] - } - stk = append(stk, nums[i]) - } - return false -} -``` - ```go type BinaryIndexedTree struct { n int @@ -371,25 +398,6 @@ func find132pattern(nums []int) bool { } ``` -### **TypeScript** - -```ts -function find132pattern(nums: number[]): boolean { - let vk = -Infinity; - const stk: number[] = []; - for (let i = nums.length - 1; i >= 0; --i) { - if (nums[i] < vk) { - return true; - } - while (stk.length && stk[stk.length - 1] < nums[i]) { - vk = stk.pop()!; - } - stk.push(nums[i]); - } - return false; -} -``` - ```ts class BinaryIndextedTree { n: number; @@ -457,32 +465,6 @@ function search(nums: number[], x: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn find132pattern(nums: Vec) -> bool { - let n = nums.len(); - let mut vk = i32::MIN; - let mut stk = vec![]; - for i in (0..n).rev() { - if nums[i] < vk { - return true; - } - while !stk.is_empty() && stk.last().unwrap() < &nums[i] { - vk = stk.pop().unwrap(); - } - stk.push(nums[i]); - } - false - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0456.132 Pattern/README_EN.md b/solution/0400-0499/0456.132 Pattern/README_EN.md index 7bc025a837410..5cd5584827a83 100644 --- a/solution/0400-0499/0456.132 Pattern/README_EN.md +++ b/solution/0400-0499/0456.132 Pattern/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,6 +62,107 @@ class Solution: return False ``` +```java +class Solution { + public boolean find132pattern(int[] nums) { + int vk = -(1 << 30); + Deque stk = new ArrayDeque<>(); + for (int i = nums.length - 1; i >= 0; --i) { + if (nums[i] < vk) { + return true; + } + while (!stk.isEmpty() && stk.peek() < nums[i]) { + vk = stk.pop(); + } + stk.push(nums[i]); + } + return false; + } +} +``` + +```cpp +class Solution { +public: + bool find132pattern(vector& nums) { + int vk = INT_MIN; + stack stk; + for (int i = nums.size() - 1; ~i; --i) { + if (nums[i] < vk) { + return true; + } + while (!stk.empty() && stk.top() < nums[i]) { + vk = stk.top(); + stk.pop(); + } + stk.push(nums[i]); + } + return false; + } +}; +``` + +```go +func find132pattern(nums []int) bool { + vk := -(1 << 30) + stk := []int{} + for i := len(nums) - 1; i >= 0; i-- { + if nums[i] < vk { + return true + } + for len(stk) > 0 && stk[len(stk)-1] < nums[i] { + vk = stk[len(stk)-1] + stk = stk[:len(stk)-1] + } + stk = append(stk, nums[i]) + } + return false +} +``` + +```ts +function find132pattern(nums: number[]): boolean { + let vk = -Infinity; + const stk: number[] = []; + for (let i = nums.length - 1; i >= 0; --i) { + if (nums[i] < vk) { + return true; + } + while (stk.length && stk[stk.length - 1] < nums[i]) { + vk = stk.pop()!; + } + stk.push(nums[i]); + } + return false; +} +``` + +```rust +impl Solution { + pub fn find132pattern(nums: Vec) -> bool { + let n = nums.len(); + let mut vk = i32::MIN; + let mut stk = vec![]; + for i in (0..n).rev() { + if nums[i] < vk { + return true; + } + while !stk.is_empty() && stk.last().unwrap() < &nums[i] { + vk = stk.pop().unwrap(); + } + stk.push(nums[i]); + } + false + } +} +``` + + + +### Solution 2 + + + ```python class BinaryIndexedTree: def __init__(self, n): @@ -98,27 +199,6 @@ class Solution: return False ``` -### **Java** - -```java -class Solution { - public boolean find132pattern(int[] nums) { - int vk = -(1 << 30); - Deque stk = new ArrayDeque<>(); - for (int i = nums.length - 1; i >= 0; --i) { - if (nums[i] < vk) { - return true; - } - while (!stk.isEmpty() && stk.peek() < nums[i]) { - vk = stk.pop(); - } - stk.push(nums[i]); - } - return false; - } -} -``` - ```java class BinaryIndexedTree { private int n; @@ -187,29 +267,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool find132pattern(vector& nums) { - int vk = INT_MIN; - stack stk; - for (int i = nums.size() - 1; ~i; --i) { - if (nums[i] < vk) { - return true; - } - while (!stk.empty() && stk.top() < nums[i]) { - vk = stk.top(); - stk.pop(); - } - stk.push(nums[i]); - } - return false; - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -265,26 +322,6 @@ public: }; ``` -### **Go** - -```go -func find132pattern(nums []int) bool { - vk := -(1 << 30) - stk := []int{} - for i := len(nums) - 1; i >= 0; i-- { - if nums[i] < vk { - return true - } - for len(stk) > 0 && stk[len(stk)-1] < nums[i] { - vk = stk[len(stk)-1] - stk = stk[:len(stk)-1] - } - stk = append(stk, nums[i]) - } - return false -} -``` - ```go type BinaryIndexedTree struct { n int @@ -341,25 +378,6 @@ func find132pattern(nums []int) bool { } ``` -### **TypeScript** - -```ts -function find132pattern(nums: number[]): boolean { - let vk = -Infinity; - const stk: number[] = []; - for (let i = nums.length - 1; i >= 0; --i) { - if (nums[i] < vk) { - return true; - } - while (stk.length && stk[stk.length - 1] < nums[i]) { - vk = stk.pop()!; - } - stk.push(nums[i]); - } - return false; -} -``` - ```ts class BinaryIndextedTree { n: number; @@ -427,32 +445,6 @@ function search(nums: number[], x: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn find132pattern(nums: Vec) -> bool { - let n = nums.len(); - let mut vk = i32::MIN; - let mut stk = vec![]; - for i in (0..n).rev() { - if nums[i] < vk { - return true; - } - while !stk.is_empty() && stk.last().unwrap() < &nums[i] { - vk = stk.pop().unwrap(); - } - stk.push(nums[i]); - } - false - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0457.Circular Array Loop/README.md b/solution/0400-0499/0457.Circular Array Loop/README.md index 49e0f57a58205..afeb817afb4c7 100644 --- a/solution/0400-0499/0457.Circular Array Loop/README.md +++ b/solution/0400-0499/0457.Circular Array Loop/README.md @@ -67,16 +67,10 @@ ## 解法 - - -快慢指针。 +### 方法一 -### **Python3** - - - ```python class Solution: def circularArrayLoop(self, nums: List[int]) -> bool: @@ -102,10 +96,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { private int n; @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -178,8 +166,6 @@ public: }; ``` -### **Go** - ```go func circularArrayLoop(nums []int) bool { for i, num := range nums { @@ -211,10 +197,6 @@ func next(nums []int, i int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0457.Circular Array Loop/README_EN.md b/solution/0400-0499/0457.Circular Array Loop/README_EN.md index e4f1f7c553cd4..44813ebdba3d1 100644 --- a/solution/0400-0499/0457.Circular Array Loop/README_EN.md +++ b/solution/0400-0499/0457.Circular Array Loop/README_EN.md @@ -66,9 +66,9 @@ We can see the cycle 3 --> 4 --> 3 --> ..., and all of its nodes are wh ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -95,8 +95,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { private int n; @@ -135,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +165,6 @@ public: }; ``` -### **Go** - ```go func circularArrayLoop(nums []int) bool { for i, num := range nums { @@ -202,10 +196,6 @@ func next(nums []int, i int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0458.Poor Pigs/README.md b/solution/0400-0499/0458.Poor Pigs/README.md index 4406a95ea3d77..903088360c493 100644 --- a/solution/0400-0499/0458.Poor Pigs/README.md +++ b/solution/0400-0499/0458.Poor Pigs/README.md @@ -54,18 +54,10 @@ ## 解法 - - -每只 🐖 可以喝液体的次数是 `minutesToTest / minutesToDie`,那么 🐖 会有 `(minutesToTest / minutesToDie) + 1` 种状态,即喝完第 1 次死亡,喝完第 2 次死亡,...,喝完第 `minutesToTest / minutesToDie` 死亡,喝完第 `minutesToTest / minutesToDie` 次依然存活。 - -我们设定 `base = (minutesToTest / minutesToDie) + 1`,n 只 🐖 能验证的范围是 `pow(base, n)`,因此求 `pow(base, n) >= buckets` 的最小 n 即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int: @@ -77,10 +69,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { @@ -94,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +94,6 @@ public: }; ``` -### **Go** - ```go func poorPigs(buckets int, minutesToDie int, minutesToTest int) int { base := minutesToTest/minutesToDie + 1 @@ -121,10 +105,6 @@ func poorPigs(buckets int, minutesToDie int, minutesToTest int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0458.Poor Pigs/README_EN.md b/solution/0400-0499/0458.Poor Pigs/README_EN.md index e45a3ccaeea88..d5eb4f302822b 100644 --- a/solution/0400-0499/0458.Poor Pigs/README_EN.md +++ b/solution/0400-0499/0458.Poor Pigs/README_EN.md @@ -56,9 +56,9 @@ At time 30, one of the two pigs must die, and the poisonous bucket is the one it ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +96,6 @@ public: }; ``` -### **Go** - ```go func poorPigs(buckets int, minutesToDie int, minutesToTest int) int { base := minutesToTest/minutesToDie + 1 @@ -113,10 +107,6 @@ func poorPigs(buckets int, minutesToDie int, minutesToTest int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0459.Repeated Substring Pattern/README.md b/solution/0400-0499/0459.Repeated Substring Pattern/README.md index 6f222486939fa..6d8d496e16739 100644 --- a/solution/0400-0499/0459.Repeated Substring Pattern/README.md +++ b/solution/0400-0499/0459.Repeated Substring Pattern/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:双倍字符串** +### 方法一:双倍字符串 若长度为 $n$ 的字符串 $s$ 由 $m$ 个重复子串组成,将 $s$ 拼接在自身上,得到字符串 $ss$,长度为 $2n$,此时若从下标 $1$ 开始查找 $s$,那么查找到的下标一定小于 $s$ 的长度。 @@ -58,20 +56,12 @@ -### **Python3** - - - ```python class Solution: def repeatedSubstringPattern(self, s: str) -> bool: return (s + s).index(s, 1) < len(s) ``` -### **Java** - - - ```java class Solution { public boolean repeatedSubstringPattern(String s) { @@ -81,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -92,22 +80,32 @@ public: }; ``` -### **Go** - ```go func repeatedSubstringPattern(s string) bool { return strings.Index(s[1:]+s, s) < len(s)-1 } ``` -### **TypeScript** - ```ts function repeatedSubstringPattern(s: string): boolean { return (s + s).slice(1, (s.length << 1) - 1).includes(s); } ``` +```rust +impl Solution { + pub fn repeated_substring_pattern(s: String) -> bool { + (s.clone() + &s)[1..s.len() * 2 - 1].contains(&s) + } +} +``` + + + +### 方法二 + + + ```ts function repeatedSubstringPattern(s: string): boolean { const n = s.length; @@ -131,20 +129,6 @@ function repeatedSubstringPattern(s: string): boolean { } ``` -### **Rust** - -```rust -impl Solution { - pub fn repeated_substring_pattern(s: String) -> bool { - (s.clone() + &s)[1..s.len() * 2 - 1].contains(&s) - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0459.Repeated Substring Pattern/README_EN.md b/solution/0400-0499/0459.Repeated Substring Pattern/README_EN.md index 5a189ba97066c..c01462be26185 100644 --- a/solution/0400-0499/0459.Repeated Substring Pattern/README_EN.md +++ b/solution/0400-0499/0459.Repeated Substring Pattern/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -50,8 +50,6 @@ class Solution: return (s + s).index(s, 1) < len(s) ``` -### **Java** - ```java class Solution { public boolean repeatedSubstringPattern(String s) { @@ -61,8 +59,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -72,22 +68,32 @@ public: }; ``` -### **Go** - ```go func repeatedSubstringPattern(s string) bool { return strings.Index(s[1:]+s, s) < len(s)-1 } ``` -### **TypeScript** - ```ts function repeatedSubstringPattern(s: string): boolean { return (s + s).slice(1, (s.length << 1) - 1).includes(s); } ``` +```rust +impl Solution { + pub fn repeated_substring_pattern(s: String) -> bool { + (s.clone() + &s)[1..s.len() * 2 - 1].contains(&s) + } +} +``` + + + +### Solution 2 + + + ```ts function repeatedSubstringPattern(s: string): boolean { const n = s.length; @@ -111,20 +117,6 @@ function repeatedSubstringPattern(s: string): boolean { } ``` -### **Rust** - -```rust -impl Solution { - pub fn repeated_substring_pattern(s: String) -> bool { - (s.clone() + &s)[1..s.len() * 2 - 1].contains(&s) - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0460.LFU Cache/README.md b/solution/0400-0499/0460.LFU Cache/README.md index 43d620a35d479..bfc59e06a4edc 100644 --- a/solution/0400-0499/0460.LFU Cache/README.md +++ b/solution/0400-0499/0460.LFU Cache/README.md @@ -67,9 +67,7 @@ lfu.get(4); // 返回 4 ## 解法 - - -**方法一:双哈希表 + 双向链表** +### 方法一:双哈希表 + 双向链表 我们定义两个哈希表,其中: @@ -94,10 +92,6 @@ lfu.get(4); // 返回 4 -### **Python3** - - - ```python class Node: def __init__(self, key: int, value: int) -> None: @@ -189,10 +183,6 @@ class LFUCache: # obj.put(key,value) ``` -### **Java** - - - ```java class LFUCache { @@ -312,8 +302,6 @@ class LFUCache { } ``` -### **C++** - ```cpp class Node { public: @@ -438,8 +426,6 @@ private: */ ``` -### **Go** - ```go type LFUCache struct { cache map[int]*node @@ -563,8 +549,6 @@ func (l *list) empty() bool { } ``` -### **Rust** - ```rust use std::cell::RefCell; use std::collections::HashMap; @@ -752,10 +736,6 @@ impl LFUCache { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0460.LFU Cache/README_EN.md b/solution/0400-0499/0460.LFU Cache/README_EN.md index 5fef344b8ba54..e71abb4e76e3b 100644 --- a/solution/0400-0499/0460.LFU Cache/README_EN.md +++ b/solution/0400-0499/0460.LFU Cache/README_EN.md @@ -67,9 +67,9 @@ lfu.get(4); // return 4 ## Solutions - +### Solution 1 -### **Python3** + ```python class Node: @@ -162,8 +162,6 @@ class LFUCache: # obj.put(key,value) ``` -### **Java** - ```java class LFUCache { @@ -283,8 +281,6 @@ class LFUCache { } ``` -### **C++** - ```cpp class Node { public: @@ -409,8 +405,6 @@ private: */ ``` -### **Go** - ```go type LFUCache struct { cache map[int]*node @@ -534,8 +528,6 @@ func (l *list) empty() bool { } ``` -### **Rust** - ```rust use std::cell::RefCell; use std::collections::HashMap; @@ -723,10 +715,6 @@ impl LFUCache { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0461.Hamming Distance/README.md b/solution/0400-0499/0461.Hamming Distance/README.md index 263a88c4b5eb1..26c0292de7bde 100644 --- a/solution/0400-0499/0461.Hamming Distance/README.md +++ b/solution/0400-0499/0461.Hamming Distance/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 我们将 $x$ 和 $y$ 按位异或,得到的结果中的 $1$ 的个数就是汉明距离。 @@ -51,20 +49,12 @@ -### **Python3** - - - ```python class Solution: def hammingDistance(self, x: int, y: int) -> int: return (x ^ y).bit_count() ``` -### **Java** - - - ```java class Solution { public int hammingDistance(int x, int y) { @@ -73,8 +63,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -84,23 +72,14 @@ public: }; ``` -### **Go** - ```go func hammingDistance(x int, y int) int { return bits.OnesCount(uint(x ^ y)) } ``` -### **JavaScript** - -```js -/** - * @param {number} x - * @param {number} y - * @return {number} - */ -var hammingDistance = function (x, y) { +```ts +function hammingDistance(x: number, y: number): number { x ^= y; let ans = 0; while (x) { @@ -108,13 +87,16 @@ var hammingDistance = function (x, y) { ++ans; } return ans; -}; +} ``` -### **TypeScript** - -```ts -function hammingDistance(x: number, y: number): number { +```js +/** + * @param {number} x + * @param {number} y + * @return {number} + */ +var hammingDistance = function (x, y) { x ^= y; let ans = 0; while (x) { @@ -122,13 +104,9 @@ function hammingDistance(x: number, y: number): number { ++ans; } return ans; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0400-0499/0461.Hamming Distance/README_EN.md b/solution/0400-0499/0461.Hamming Distance/README_EN.md index 937045f7f1c4e..1a7a4693f345b 100644 --- a/solution/0400-0499/0461.Hamming Distance/README_EN.md +++ b/solution/0400-0499/0461.Hamming Distance/README_EN.md @@ -37,25 +37,16 @@ The above arrows point to positions where the corresponding bits are different. ## Solutions -Use xor operation to find different bits. - -- 0 ^ 0 = 0 -- 1 ^ 1 = 0 -- 0 ^ 1 = 1 -- 1 ^ 0 = 1 +### Solution 1 -### **Python3** - ```python class Solution: def hammingDistance(self, x: int, y: int) -> int: return (x ^ y).bit_count() ``` -### **Java** - ```java class Solution { public int hammingDistance(int x, int y) { @@ -64,8 +55,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -75,23 +64,14 @@ public: }; ``` -### **Go** - ```go func hammingDistance(x int, y int) int { return bits.OnesCount(uint(x ^ y)) } ``` -### **JavaScript** - -```js -/** - * @param {number} x - * @param {number} y - * @return {number} - */ -var hammingDistance = function (x, y) { +```ts +function hammingDistance(x: number, y: number): number { x ^= y; let ans = 0; while (x) { @@ -99,13 +79,16 @@ var hammingDistance = function (x, y) { ++ans; } return ans; -}; +} ``` -### **TypeScript** - -```ts -function hammingDistance(x: number, y: number): number { +```js +/** + * @param {number} x + * @param {number} y + * @return {number} + */ +var hammingDistance = function (x, y) { x ^= y; let ans = 0; while (x) { @@ -113,13 +96,9 @@ function hammingDistance(x: number, y: number): number { ++ans; } return ans; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0400-0499/0462.Minimum Moves to Equal Array Elements II/README.md b/solution/0400-0499/0462.Minimum Moves to Equal Array Elements II/README.md index bcb4b02860530..e6d06d5d85fd7 100644 --- a/solution/0400-0499/0462.Minimum Moves to Equal Array Elements II/README.md +++ b/solution/0400-0499/0462.Minimum Moves to Equal Array Elements II/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:排序 + 中位数** +### 方法一:排序 + 中位数 这个问题可以抽象为,在数轴上有 $n$ 个点,找到一个点使得所有点到该点的距离之和最小。答案为 $n$ 个点的中位数。 @@ -62,18 +60,8 @@ - [296. 最佳的碰头地点](/solution/0200-0299/0296.Best%20Meeting%20Point/README.md) - [2448. 使数组相等的最小开销](/solution/2400-2499/2448.Minimum%20Cost%20to%20Make%20Array%20Equal/README.md) -**方法二:排序 + 前缀和** - -如果我们不知道中位数的性质,也可以使用前缀和的方法来求解。 - -时间复杂度 $O(n\log n)$,空间复杂度 $O(n)$。 - -### **Python3** - - - ```python class Solution: def minMoves2(self, nums: List[int]) -> int: @@ -82,25 +70,6 @@ class Solution: return sum(abs(v - k) for v in nums) ``` -```python -class Solution: - def minMoves2(self, nums: List[int]) -> int: - def move(i): - v = nums[i] - a = v * i - s[i] - b = s[-1] - s[i + 1] - v * (n - i - 1) - return a + b - - nums.sort() - s = [0] + list(accumulate(nums)) - n = len(nums) - return min(move(i) for i in range(n)) -``` - -### **Java** - - - ```java class Solution { public int minMoves2(int[] nums) { @@ -115,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +97,6 @@ public: }; ``` -### **Go** - ```go func minMoves2(nums []int) int { sort.Ints(nums) @@ -151,8 +116,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minMoves2(nums: number[]): number { nums.sort((a, b) => a - b); @@ -161,8 +124,6 @@ function minMoves2(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_moves2(mut nums: Vec) -> i32 { @@ -177,10 +138,31 @@ impl Solution { } ``` -### **...** + -``` +### 方法二:排序 + 前缀和 + +如果我们不知道中位数的性质,也可以使用前缀和的方法来求解。 +时间复杂度 $O(n\log n)$,空间复杂度 $O(n)$。 + + + +```python +class Solution: + def minMoves2(self, nums: List[int]) -> int: + def move(i): + v = nums[i] + a = v * i - s[i] + b = s[-1] - s[i + 1] - v * (n - i - 1) + return a + b + + nums.sort() + s = [0] + list(accumulate(nums)) + n = len(nums) + return min(move(i) for i in range(n)) ``` + + diff --git a/solution/0400-0499/0462.Minimum Moves to Equal Array Elements II/README_EN.md b/solution/0400-0499/0462.Minimum Moves to Equal Array Elements II/README_EN.md index 0bf1475741137..f1cbefea7210f 100644 --- a/solution/0400-0499/0462.Minimum Moves to Equal Array Elements II/README_EN.md +++ b/solution/0400-0499/0462.Minimum Moves to Equal Array Elements II/README_EN.md @@ -39,9 +39,9 @@ Only two moves are needed (remember each move increments or decrements one eleme ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,23 +51,6 @@ class Solution: return sum(abs(v - k) for v in nums) ``` -```python -class Solution: - def minMoves2(self, nums: List[int]) -> int: - def move(i): - v = nums[i] - a = v * i - s[i] - b = s[-1] - s[i + 1] - v * (n - i - 1) - return a + b - - nums.sort() - s = [0] + list(accumulate(nums)) - n = len(nums) - return min(move(i) for i in range(n)) -``` - -### **Java** - ```java class Solution { public int minMoves2(int[] nums) { @@ -82,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +78,6 @@ public: }; ``` -### **Go** - ```go func minMoves2(nums []int) int { sort.Ints(nums) @@ -118,8 +97,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minMoves2(nums: number[]): number { nums.sort((a, b) => a - b); @@ -128,8 +105,6 @@ function minMoves2(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_moves2(mut nums: Vec) -> i32 { @@ -144,10 +119,27 @@ impl Solution { } ``` -### **...** + -``` +### Solution 2 + + + +```python +class Solution: + def minMoves2(self, nums: List[int]) -> int: + def move(i): + v = nums[i] + a = v * i - s[i] + b = s[-1] - s[i + 1] - v * (n - i - 1) + return a + b + nums.sort() + s = [0] + list(accumulate(nums)) + n = len(nums) + return min(move(i) for i in range(n)) ``` + + diff --git a/solution/0400-0499/0463.Island Perimeter/README.md b/solution/0400-0499/0463.Island Perimeter/README.md index 93f1f3cd25510..98d758b309334 100644 --- a/solution/0400-0499/0463.Island Perimeter/README.md +++ b/solution/0400-0499/0463.Island Perimeter/README.md @@ -50,16 +50,10 @@ ## 解法 - - -遍历二维数组 +### 方法一 -### **Python3** - - - ```python class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: @@ -76,10 +70,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int islandPerimeter(int[][] grid) { @@ -104,41 +94,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function islandPerimeter(grid: number[][]): number { - let m = grid.length, - n = grid[0].length; - let ans = 0; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - let top = 0, - left = 0; - if (i > 0) { - top = grid[i - 1][j]; - } - if (j > 0) { - left = grid[i][j - 1]; - } - let cur = grid[i][j]; - if (cur != top) ++ans; - if (cur != left) ++ans; - } - } - // 最后一行, 最后一列 - for (let i = 0; i < m; ++i) { - if (grid[i][n - 1] == 1) ++ans; - } - for (let j = 0; j < n; ++j) { - if (grid[m - 1][j] == 1) ++ans; - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -159,8 +114,6 @@ public: }; ``` -### **Go** - ```go func islandPerimeter(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -182,10 +135,37 @@ func islandPerimeter(grid [][]int) int { } ``` -### **...** - -``` - +```ts +function islandPerimeter(grid: number[][]): number { + let m = grid.length, + n = grid[0].length; + let ans = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + let top = 0, + left = 0; + if (i > 0) { + top = grid[i - 1][j]; + } + if (j > 0) { + left = grid[i][j - 1]; + } + let cur = grid[i][j]; + if (cur != top) ++ans; + if (cur != left) ++ans; + } + } + // 最后一行, 最后一列 + for (let i = 0; i < m; ++i) { + if (grid[i][n - 1] == 1) ++ans; + } + for (let j = 0; j < n; ++j) { + if (grid[m - 1][j] == 1) ++ans; + } + return ans; +} ``` + + diff --git a/solution/0400-0499/0463.Island Perimeter/README_EN.md b/solution/0400-0499/0463.Island Perimeter/README_EN.md index 1c01a99f63d79..3df48c0771873 100644 --- a/solution/0400-0499/0463.Island Perimeter/README_EN.md +++ b/solution/0400-0499/0463.Island Perimeter/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int islandPerimeter(int[][] grid) { @@ -92,41 +90,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function islandPerimeter(grid: number[][]): number { - let m = grid.length, - n = grid[0].length; - let ans = 0; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - let top = 0, - left = 0; - if (i > 0) { - top = grid[i - 1][j]; - } - if (j > 0) { - left = grid[i][j - 1]; - } - let cur = grid[i][j]; - if (cur != top) ++ans; - if (cur != left) ++ans; - } - } - // 最后一行, 最后一列 - for (let i = 0; i < m; ++i) { - if (grid[i][n - 1] == 1) ++ans; - } - for (let j = 0; j < n; ++j) { - if (grid[m - 1][j] == 1) ++ans; - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -147,8 +110,6 @@ public: }; ``` -### **Go** - ```go func islandPerimeter(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -170,10 +131,37 @@ func islandPerimeter(grid [][]int) int { } ``` -### **...** - -``` - +```ts +function islandPerimeter(grid: number[][]): number { + let m = grid.length, + n = grid[0].length; + let ans = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + let top = 0, + left = 0; + if (i > 0) { + top = grid[i - 1][j]; + } + if (j > 0) { + left = grid[i][j - 1]; + } + let cur = grid[i][j]; + if (cur != top) ++ans; + if (cur != left) ++ans; + } + } + // 最后一行, 最后一列 + for (let i = 0; i < m; ++i) { + if (grid[i][n - 1] == 1) ++ans; + } + for (let j = 0; j < n; ++j) { + if (grid[m - 1][j] == 1) ++ans; + } + return ans; +} ``` + + diff --git a/solution/0400-0499/0464.Can I Win/README.md b/solution/0400-0499/0464.Can I Win/README.md index c4f7bcd91f4f0..2cf39378d358f 100644 --- a/solution/0400-0499/0464.Can I Win/README.md +++ b/solution/0400-0499/0464.Can I Win/README.md @@ -54,16 +54,10 @@ ## 解法 - - -**方法一:状态压缩 + 记忆化搜索** +### 方法一:状态压缩 + 记忆化搜索 -### **Python3** - - - ```python class Solution: def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool: @@ -82,10 +76,6 @@ class Solution: return dfs(0, 0) ``` -### **Java** - - - ```java class Solution { private Map memo = new HashMap<>(); @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func canIWin(maxChoosableInteger int, desiredTotal int) bool { s := (1 + maxChoosableInteger) * maxChoosableInteger / 2 @@ -177,10 +163,6 @@ func canIWin(maxChoosableInteger int, desiredTotal int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0464.Can I Win/README_EN.md b/solution/0400-0499/0464.Can I Win/README_EN.md index 76699778c71c6..55e6388697943 100644 --- a/solution/0400-0499/0464.Can I Win/README_EN.md +++ b/solution/0400-0499/0464.Can I Win/README_EN.md @@ -50,9 +50,9 @@ Same with other integers chosen by the first player, the second player will alwa ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return dfs(0, 0) ``` -### **Java** - ```java class Solution { private Map memo = new HashMap<>(); @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +130,6 @@ public: }; ``` -### **Go** - ```go func canIWin(maxChoosableInteger int, desiredTotal int) bool { s := (1 + maxChoosableInteger) * maxChoosableInteger / 2 @@ -165,10 +159,6 @@ func canIWin(maxChoosableInteger int, desiredTotal int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0465.Optimal Account Balancing/README.md b/solution/0400-0499/0465.Optimal Account Balancing/README.md index e8dd9ea8f23dd..c978d3cb80789 100644 --- a/solution/0400-0499/0465.Optimal Account Balancing/README.md +++ b/solution/0400-0499/0465.Optimal Account Balancing/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:状态压缩动态规划 + 子集枚举** +### 方法一:状态压缩动态规划 + 子集枚举 我们先遍历数组 `transactions`,统计每个人的收支情况,然后将所有收支不为零的人的收支情况存入数组 $nums$ 中。如果我们可以找到一个子集,子集中共有 $k$ 个人,且这 $k$ 个人的收支情况之和为零,那么我们最多通过 $k-1$ 次交易,就能够使得这 $k$ 个人的收支情况全部清零。这样,我们就能将原问题转化成一个子集枚举的问题。 @@ -76,10 +74,6 @@ $$ -### **Python3** - - - ```python class Solution: def minTransfers(self, transactions: List[List[int]]) -> int: @@ -105,10 +99,6 @@ class Solution: return f[-1] ``` -### **Java** - - - ```java class Solution { public int minTransfers(int[][] transactions) { @@ -146,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -186,8 +174,6 @@ public: }; ``` -### **Go** - ```go func minTransfers(transactions [][]int) int { g := [12]int{} @@ -222,8 +208,6 @@ func minTransfers(transactions [][]int) int { } ``` -### **TypeScript** - ```ts function minTransfers(transactions: number[][]): number { const g: number[] = new Array(12).fill(0); @@ -262,10 +246,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0465.Optimal Account Balancing/README_EN.md b/solution/0400-0499/0465.Optimal Account Balancing/README_EN.md index ed85a980679e5..a7f757fc4189c 100644 --- a/solution/0400-0499/0465.Optimal Account Balancing/README_EN.md +++ b/solution/0400-0499/0465.Optimal Account Balancing/README_EN.md @@ -46,9 +46,9 @@ Therefore, person #1 only need to give person #0 4, and all debt is settled. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return f[-1] ``` -### **Java** - ```java class Solution { public int minTransfers(int[][] transactions) { @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +150,6 @@ public: }; ``` -### **Go** - ```go func minTransfers(transactions [][]int) int { g := [12]int{} @@ -190,8 +184,6 @@ func minTransfers(transactions [][]int) int { } ``` -### **TypeScript** - ```ts function minTransfers(transactions: number[][]): number { const g: number[] = new Array(12).fill(0); @@ -230,10 +222,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0466.Count The Repetitions/README.md b/solution/0400-0499/0466.Count The Repetitions/README.md index fd567c66dcf9f..5c64231f250f4 100644 --- a/solution/0400-0499/0466.Count The Repetitions/README.md +++ b/solution/0400-0499/0466.Count The Repetitions/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:预处理 + 递推** +### 方法一:预处理 + 递推 我们预处理出以字符串 $s2$ 的每个位置 $i$ 开始匹配一个完整的 $s1$ 后,下一个位置 $j$ 以及经过了多少个 $s2$,即 $d[i] = (cnt, j)$,其中 $cnt$ 表示匹配了多少个 $s2$,而 $j$ 表示字符串 $s2$ 的下一个位置。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int: @@ -92,10 +86,6 @@ class Solution: return ans // n2 ``` -### **Java** - - - ```java class Solution { public int getMaxRepetitions(String s1, int n1, String s2, int n2) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func getMaxRepetitions(s1 string, n1 int, s2 string, n2 int) (ans int) { n := len(s2) @@ -184,8 +170,6 @@ func getMaxRepetitions(s1 string, n1 int, s2 string, n2 int) (ans int) { } ``` -### **TypeScript** - ```ts function getMaxRepetitions(s1: string, n1: number, s2: string, n2: number): number { const n = s2.length; @@ -212,10 +196,6 @@ function getMaxRepetitions(s1: string, n1: number, s2: string, n2: number): numb } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0466.Count The Repetitions/README_EN.md b/solution/0400-0499/0466.Count The Repetitions/README_EN.md index 06645ff48a567..625734101ebf4 100644 --- a/solution/0400-0499/0466.Count The Repetitions/README_EN.md +++ b/solution/0400-0499/0466.Count The Repetitions/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return ans // n2 ``` -### **Java** - ```java class Solution { public int getMaxRepetitions(String s1, int n1, String s2, int n2) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +124,6 @@ public: }; ``` -### **Go** - ```go func getMaxRepetitions(s1 string, n1 int, s2 string, n2 int) (ans int) { n := len(s2) @@ -157,8 +151,6 @@ func getMaxRepetitions(s1 string, n1 int, s2 string, n2 int) (ans int) { } ``` -### **TypeScript** - ```ts function getMaxRepetitions(s1: string, n1: number, s2: string, n2: number): number { const n = s2.length; @@ -185,10 +177,6 @@ function getMaxRepetitions(s1: string, n1: number, s2: string, n2: number): numb } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0467.Unique Substrings in Wraparound String/README.md b/solution/0400-0499/0467.Unique Substrings in Wraparound String/README.md index e7ede123075ad..59c3a21de569c 100644 --- a/solution/0400-0499/0467.Unique Substrings in Wraparound String/README.md +++ b/solution/0400-0499/0467.Unique Substrings in Wraparound String/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 不妨设 `dp[α]` 表示 p 中以字符 α 结尾且在 s 中的子串的最大长度,将 dp 求和可以得到最终结果。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def findSubstringInWraproundString(self, p: str) -> int: @@ -82,10 +76,6 @@ class Solution: return sum(dp) ``` -### **Java** - - - ```java class Solution { public int findSubstringInWraproundString(String p) { @@ -109,53 +99,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function findSubstringInWraproundString(p: string): number { - const n = p.length; - const dp = new Array(26).fill(0); - let cur = 1; - dp[p.charCodeAt(0) - 'a'.charCodeAt(0)] = 1; - for (let i = 1; i < n; i++) { - if ((p.charCodeAt(i) - p.charCodeAt(i - 1) + 25) % 26 == 0) { - cur++; - } else { - cur = 1; - } - const index = p.charCodeAt(i) - 'a'.charCodeAt(0); - dp[index] = Math.max(dp[index], cur); - } - return dp.reduce((r, v) => r + v); -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn find_substring_in_wrapround_string(p: String) -> i32 { - let n = p.len(); - let p = p.as_bytes(); - let mut dp = [0; 26]; - let mut cur = 1; - dp[(p[0] - b'a') as usize] = 1; - for i in 1..n { - if (p[i] - p[i - 1] + 25) % 26 == 0 { - cur += 1; - } else { - cur = 1; - } - let index = (p[i] - b'a') as usize; - dp[index] = dp[index].max(cur); - } - dp.into_iter().sum() - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -177,8 +120,6 @@ public: }; ``` -### **Go** - ```go func findSubstringInWraproundString(p string) int { dp := make([]int, 26) @@ -200,10 +141,47 @@ func findSubstringInWraproundString(p string) int { } ``` -### **...** - +```ts +function findSubstringInWraproundString(p: string): number { + const n = p.length; + const dp = new Array(26).fill(0); + let cur = 1; + dp[p.charCodeAt(0) - 'a'.charCodeAt(0)] = 1; + for (let i = 1; i < n; i++) { + if ((p.charCodeAt(i) - p.charCodeAt(i - 1) + 25) % 26 == 0) { + cur++; + } else { + cur = 1; + } + const index = p.charCodeAt(i) - 'a'.charCodeAt(0); + dp[index] = Math.max(dp[index], cur); + } + return dp.reduce((r, v) => r + v); +} ``` +```rust +impl Solution { + pub fn find_substring_in_wrapround_string(p: String) -> i32 { + let n = p.len(); + let p = p.as_bytes(); + let mut dp = [0; 26]; + let mut cur = 1; + dp[(p[0] - b'a') as usize] = 1; + for i in 1..n { + if (p[i] - p[i - 1] + 25) % 26 == 0 { + cur += 1; + } else { + cur = 1; + } + let index = (p[i] - b'a') as usize; + dp[index] = dp[index].max(cur); + } + dp.into_iter().sum() + } +} ``` + + diff --git a/solution/0400-0499/0467.Unique Substrings in Wraparound String/README_EN.md b/solution/0400-0499/0467.Unique Substrings in Wraparound String/README_EN.md index 3de8b118f3ace..16e855a14bde9 100644 --- a/solution/0400-0499/0467.Unique Substrings in Wraparound String/README_EN.md +++ b/solution/0400-0499/0467.Unique Substrings in Wraparound String/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return sum(dp) ``` -### **Java** - ```java class Solution { public int findSubstringInWraproundString(String p) { @@ -91,53 +89,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function findSubstringInWraproundString(p: string): number { - const n = p.length; - const dp = new Array(26).fill(0); - let cur = 1; - dp[p.charCodeAt(0) - 'a'.charCodeAt(0)] = 1; - for (let i = 1; i < n; i++) { - if ((p.charCodeAt(i) - p.charCodeAt(i - 1) + 25) % 26 == 0) { - cur++; - } else { - cur = 1; - } - const index = p.charCodeAt(i) - 'a'.charCodeAt(0); - dp[index] = Math.max(dp[index], cur); - } - return dp.reduce((r, v) => r + v); -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn find_substring_in_wrapround_string(p: String) -> i32 { - let n = p.len(); - let p = p.as_bytes(); - let mut dp = [0; 26]; - let mut cur = 1; - dp[(p[0] - b'a') as usize] = 1; - for i in 1..n { - if (p[i] - p[i - 1] + 25) % 26 == 0 { - cur += 1; - } else { - cur = 1; - } - let index = (p[i] - b'a') as usize; - dp[index] = dp[index].max(cur); - } - dp.into_iter().sum() - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -159,8 +110,6 @@ public: }; ``` -### **Go** - ```go func findSubstringInWraproundString(p string) int { dp := make([]int, 26) @@ -182,10 +131,47 @@ func findSubstringInWraproundString(p string) int { } ``` -### **...** - +```ts +function findSubstringInWraproundString(p: string): number { + const n = p.length; + const dp = new Array(26).fill(0); + let cur = 1; + dp[p.charCodeAt(0) - 'a'.charCodeAt(0)] = 1; + for (let i = 1; i < n; i++) { + if ((p.charCodeAt(i) - p.charCodeAt(i - 1) + 25) % 26 == 0) { + cur++; + } else { + cur = 1; + } + const index = p.charCodeAt(i) - 'a'.charCodeAt(0); + dp[index] = Math.max(dp[index], cur); + } + return dp.reduce((r, v) => r + v); +} ``` +```rust +impl Solution { + pub fn find_substring_in_wrapround_string(p: String) -> i32 { + let n = p.len(); + let p = p.as_bytes(); + let mut dp = [0; 26]; + let mut cur = 1; + dp[(p[0] - b'a') as usize] = 1; + for i in 1..n { + if (p[i] - p[i - 1] + 25) % 26 == 0 { + cur += 1; + } else { + cur = 1; + } + let index = (p[i] - b'a') as usize; + dp[index] = dp[index].max(cur); + } + dp.into_iter().sum() + } +} ``` + + diff --git a/solution/0400-0499/0468.Validate IP Address/README.md b/solution/0400-0499/0468.Validate IP Address/README.md index 4efa8aa1f849c..11196f8f8c2c7 100644 --- a/solution/0400-0499/0468.Validate IP Address/README.md +++ b/solution/0400-0499/0468.Validate IP Address/README.md @@ -56,14 +56,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def validIPAddress(self, IP: str) -> str: @@ -94,16 +90,6 @@ class Solution: return "Neither" ``` -### **Java** - - - -```java - -``` - -### **TypeScript** - ```ts function validIPAddress(queryIP: string): string { const isIPv4 = () => { @@ -147,8 +133,6 @@ function validIPAddress(queryIP: string): string { } ``` -### **Rust** - ```rust impl Solution { fn is_IPv4(s: &String) -> bool { @@ -206,10 +190,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0468.Validate IP Address/README_EN.md b/solution/0400-0499/0468.Validate IP Address/README_EN.md index 8eca659ddbc89..754076e3b2c0f 100644 --- a/solution/0400-0499/0468.Validate IP Address/README_EN.md +++ b/solution/0400-0499/0468.Validate IP Address/README_EN.md @@ -52,9 +52,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -86,14 +86,6 @@ class Solution: return "Neither" ``` -### **Java** - -```java - -``` - -### **TypeScript** - ```ts function validIPAddress(queryIP: string): string { const isIPv4 = () => { @@ -137,8 +129,6 @@ function validIPAddress(queryIP: string): string { } ``` -### **Rust** - ```rust impl Solution { fn is_IPv4(s: &String) -> bool { @@ -196,10 +186,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0469.Convex Polygon/README.md b/solution/0400-0499/0469.Convex Polygon/README.md index 37a9f1f3648c9..2e1d443106e80 100644 --- a/solution/0400-0499/0469.Convex Polygon/README.md +++ b/solution/0400-0499/0469.Convex Polygon/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:数学(向量叉积)** +### 方法一:数学(向量叉积) 假设当前连续的三个顶点分别为 $p_1, p_2, p_3$,我们可以计算向量 $\overrightarrow{p_1p_2}$ 和 $\overrightarrow{p_1p_3}$ 的叉积,记为 $cur$。如果 $cur$ 的方向与之前的 $pre$ 方向不一致,说明多边形不是凸多边形。否则,我们更新 $pre = cur$,继续遍历下一个顶点。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def isConvex(self, points: List[List[int]]) -> bool: @@ -79,10 +73,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean isConvex(List> points) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func isConvex(points [][]int) bool { n := len(points) @@ -158,10 +144,6 @@ func isConvex(points [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0469.Convex Polygon/README_EN.md b/solution/0400-0499/0469.Convex Polygon/README_EN.md index ce00e6395ae19..7c55f203079e8 100644 --- a/solution/0400-0499/0469.Convex Polygon/README_EN.md +++ b/solution/0400-0499/0469.Convex Polygon/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean isConvex(List> points) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func isConvex(points [][]int) bool { n := len(points) @@ -136,10 +130,6 @@ func isConvex(points [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0470.Implement Rand10() Using Rand7()/README.md b/solution/0400-0499/0470.Implement Rand10() Using Rand7()/README.md index c05917977fe2a..02825cf63e839 100644 --- a/solution/0400-0499/0470.Implement Rand10() Using Rand7()/README.md +++ b/solution/0400-0499/0470.Implement Rand10() Using Rand7()/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:拒绝采样** +### 方法一:拒绝采样 我们可以使用拒绝采样的方法实现等概率生成任意区间的随机数。拒绝采样的思路是如果生成的随机数落在我们希望的区间内,那么就返回该随机数,否则会不断生成直到生成一个落在区间内的随机数为止。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python # The rand7() API is already defined for you. # def rand7(): @@ -94,10 +88,6 @@ class Solution: return x % 10 + 1 ``` -### **Java** - - - ```java /** * The rand7() API is already defined in the parent class SolBase. @@ -118,8 +108,6 @@ class Solution extends SolBase { } ``` -### **C++** - ```cpp // The rand7() API is already defined for you. // int rand7(); @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func rand10() int { for { @@ -155,8 +141,6 @@ func rand10() int { } ``` -### **TypeScript** - ```ts /** * The rand7() API is already defined for you. @@ -176,9 +160,8 @@ function rand10(): number { } ``` -### **Rust** - ```rust + /** * The rand7() API is already defined for you. * @return a random integer in the range 1 to 7 @@ -199,10 +182,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0470.Implement Rand10() Using Rand7()/README_EN.md b/solution/0400-0499/0470.Implement Rand10() Using Rand7()/README_EN.md index 5a6d7cacae7ea..db27b5506c127 100644 --- a/solution/0400-0499/0470.Implement Rand10() Using Rand7()/README_EN.md +++ b/solution/0400-0499/0470.Implement Rand10() Using Rand7()/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # The rand7() API is already defined for you. @@ -59,8 +59,6 @@ class Solution: return x % 10 + 1 ``` -### **Java** - ```java /** * The rand7() API is already defined in the parent class SolBase. @@ -81,8 +79,6 @@ class Solution extends SolBase { } ``` -### **C++** - ```cpp // The rand7() API is already defined for you. // int rand7(); @@ -103,8 +99,6 @@ public: }; ``` -### **Go** - ```go func rand10() int { for { @@ -118,8 +112,6 @@ func rand10() int { } ``` -### **TypeScript** - ```ts /** * The rand7() API is already defined for you. @@ -139,9 +131,8 @@ function rand10(): number { } ``` -### **Rust** - ```rust + /** * The rand7() API is already defined for you. * @return a random integer in the range 1 to 7 @@ -162,10 +153,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0471.Encode String with Shortest Length/README.md b/solution/0400-0499/0471.Encode String with Shortest Length/README.md index f2b1159564851..8f8a3b7b6df1a 100644 --- a/solution/0400-0499/0471.Encode String with Shortest Length/README.md +++ b/solution/0400-0499/0471.Encode String with Shortest Length/README.md @@ -70,9 +70,7 @@ ## 解法 - - -**方法一:动态规划(区间 DP)** +### 方法一:动态规划(区间 DP) 在这道题中,我们需要判断一个字符串是否能够进行压缩,也即是说,一个字符串是否能通过其子串重复多次构成。我们可以利用第 $459$ 题的方法来判断,定义一个方法 $g(i, j)$,表示将字符串 $s[i...j]$ 进行压缩后得到的字符串。 @@ -86,10 +84,6 @@ -### **Python3** - - - ```python class Solution: def encode(self, s: str) -> str: @@ -116,10 +110,6 @@ class Solution: return f[0][-1] ``` -### **Java** - - - ```java class Solution { private String s; @@ -160,8 +150,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -200,8 +188,6 @@ public: }; ``` -### **Go** - ```go func encode(s string) string { n := len(s) @@ -238,8 +224,6 @@ func encode(s string) string { } ``` -### **TypeScript** - ```ts function encode(s: string): string { const n = s.length; @@ -273,10 +257,6 @@ function encode(s: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0471.Encode String with Shortest Length/README_EN.md b/solution/0400-0499/0471.Encode String with Shortest Length/README_EN.md index e0cdec2d56444..1a404a5d2495f 100644 --- a/solution/0400-0499/0471.Encode String with Shortest Length/README_EN.md +++ b/solution/0400-0499/0471.Encode String with Shortest Length/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return f[0][-1] ``` -### **Java** - ```java class Solution { private String s; @@ -117,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +153,6 @@ public: }; ``` -### **Go** - ```go func encode(s string) string { n := len(s) @@ -195,8 +189,6 @@ func encode(s string) string { } ``` -### **TypeScript** - ```ts function encode(s: string): string { const n = s.length; @@ -230,10 +222,6 @@ function encode(s: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0472.Concatenated Words/README.md b/solution/0400-0499/0472.Concatenated Words/README.md index 0f539a98f9da7..aa4b4b8762e3a 100644 --- a/solution/0400-0499/0472.Concatenated Words/README.md +++ b/solution/0400-0499/0472.Concatenated Words/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:前缀树 + DFS** +### 方法一:前缀树 + DFS 判断一个单词是不是连接词,需要判断这个单词是否完全由至少两个给定数组中的更短的非空单词(可以重复)组成。判断更短的单词是否在给定数组中,可以使用字典树实现。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Trie: def __init__(self): @@ -109,10 +103,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Trie { Trie[] children = new Trie[26]; @@ -167,8 +157,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -221,8 +209,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -276,10 +262,6 @@ func findAllConcatenatedWordsInADict(words []string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0472.Concatenated Words/README_EN.md b/solution/0400-0499/0472.Concatenated Words/README_EN.md index b4ec78348baab..e9360e16fcc68 100644 --- a/solution/0400-0499/0472.Concatenated Words/README_EN.md +++ b/solution/0400-0499/0472.Concatenated Words/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -84,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java class Trie { Trie[] children = new Trie[26]; @@ -140,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -194,8 +190,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -249,10 +243,6 @@ func findAllConcatenatedWordsInADict(words []string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0473.Matchsticks to Square/README.md b/solution/0400-0499/0473.Matchsticks to Square/README.md index 25e51100ef0ce..e6f1906649a76 100644 --- a/solution/0400-0499/0473.Matchsticks to Square/README.md +++ b/solution/0400-0499/0473.Matchsticks to Square/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:排序 + 回溯** +### 方法一:排序 + 回溯 用 $edges[i]$ 记录正方形每条边当前的长度,对于第 $u$ 根火柴,尝试把它加到 $edges[i]$ 每条边,若加入后 $edges[i]$ 不超过正方形期望长度 $x$,则继续往下递归 $u+1$ 根火柴。若所有火柴都能被加入,说明满足拼成正方形的要求。 @@ -51,23 +49,8 @@ 时间复杂度 $O(4^n)$,其中 $n$ 表示 $matchsticks$ 的长度。每根火柴可以被放入正方形的 $4$ 条边,共有 $n$ 根火柴。 -**方法二:状态压缩 + 记忆化搜索** - -记当前火柴被划分的情况为 $state$。对于第 $i$ 个数,若 $state \ \& \ (1<s$,说明第 $i$ 个火柴棒不能被添加到当前子集中,由于我们对 $matchsticks$ 数组进行升序排列,因此从 $matchsticks$ 从第 $i$ 个火柴棒开始的所有数字都不能被添加到当前子集,直接返回 $false$。 -- 否则,将第 $i$ 个火柴棒添加到当前子集中,状态变为 $state \ |\ (1< -### **Python3** - - - ```python class Solution: def makesquare(self, matchsticks: List[int]) -> bool: @@ -91,33 +74,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def makesquare(self, matchsticks: List[int]) -> bool: - @cache - def dfs(state, t): - if state == (1 << len(matchsticks)) - 1: - return True - for i, v in enumerate(matchsticks): - if state & (1 << i): - continue - if t + v > s: - break - if dfs(state | (1 << i), (t + v) % s): - return True - return False - - s, mod = divmod(sum(matchsticks), 4) - matchsticks.sort() - if mod: - return False - return dfs(0, 0) -``` - -### **Java** - - - ```java class Solution { public boolean makesquare(int[] matchsticks) { @@ -154,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -185,8 +139,6 @@ public: }; ``` -### **Go** - ```go func makesquare(matchsticks []int) bool { s := 0 @@ -219,8 +171,6 @@ func makesquare(matchsticks []int) bool { } ``` -### **Rust** - ```rust impl Solution { pub fn makesquare(matchsticks: Vec) -> bool { @@ -255,10 +205,44 @@ impl Solution { } ``` -### **...** + -``` +### 方法二:状态压缩 + 记忆化搜索 + +记当前火柴被划分的情况为 $state$。对于第 $i$ 个数,若 $state \ \& \ (1<s$,说明第 $i$ 个火柴棒不能被添加到当前子集中,由于我们对 $matchsticks$ 数组进行升序排列,因此从 $matchsticks$ 从第 $i$ 个火柴棒开始的所有数字都不能被添加到当前子集,直接返回 $false$。 +- 否则,将第 $i$ 个火柴棒添加到当前子集中,状态变为 $state \ |\ (1< + +```python +class Solution: + def makesquare(self, matchsticks: List[int]) -> bool: + @cache + def dfs(state, t): + if state == (1 << len(matchsticks)) - 1: + return True + for i, v in enumerate(matchsticks): + if state & (1 << i): + continue + if t + v > s: + break + if dfs(state | (1 << i), (t + v) % s): + return True + return False + s, mod = divmod(sum(matchsticks), 4) + matchsticks.sort() + if mod: + return False + return dfs(0, 0) ``` + + diff --git a/solution/0400-0499/0473.Matchsticks to Square/README_EN.md b/solution/0400-0499/0473.Matchsticks to Square/README_EN.md index d7463488ffa37..e4b8e1fbafde4 100644 --- a/solution/0400-0499/0473.Matchsticks to Square/README_EN.md +++ b/solution/0400-0499/0473.Matchsticks to Square/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,31 +62,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def makesquare(self, matchsticks: List[int]) -> bool: - @cache - def dfs(state, t): - if state == (1 << len(matchsticks)) - 1: - return True - for i, v in enumerate(matchsticks): - if state & (1 << i): - continue - if t + v > s: - break - if dfs(state | (1 << i), (t + v) % s): - return True - return False - - s, mod = divmod(sum(matchsticks), 4) - matchsticks.sort() - if mod: - return False - return dfs(0, 0) -``` - -### **Java** - ```java class Solution { public boolean makesquare(int[] matchsticks) { @@ -123,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +127,6 @@ public: }; ``` -### **Go** - ```go func makesquare(matchsticks []int) bool { s := 0 @@ -188,8 +159,6 @@ func makesquare(matchsticks []int) bool { } ``` -### **Rust** - ```rust impl Solution { pub fn makesquare(matchsticks: Vec) -> bool { @@ -224,10 +193,35 @@ impl Solution { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def makesquare(self, matchsticks: List[int]) -> bool: + @cache + def dfs(state, t): + if state == (1 << len(matchsticks)) - 1: + return True + for i, v in enumerate(matchsticks): + if state & (1 << i): + continue + if t + v > s: + break + if dfs(state | (1 << i), (t + v) % s): + return True + return False + + s, mod = divmod(sum(matchsticks), 4) + matchsticks.sort() + if mod: + return False + return dfs(0, 0) ``` + + diff --git a/solution/0400-0499/0474.Ones and Zeroes/README.md b/solution/0400-0499/0474.Ones and Zeroes/README.md index c5db41fc0d3aa..b83db127f555e 100644 --- a/solution/0400-0499/0474.Ones and Zeroes/README.md +++ b/solution/0400-0499/0474.Ones and Zeroes/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j][k]$ 表示在前 $i$ 个字符串中,使用 $j$ 个 0 和 $k$ 个 1 的情况下最多可以得到的字符串数量。初始时 $f[i][j][k]=0$,答案为 $f[sz][m][n]$,其中 $sz$ 是数组 $strs$ 的长度。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def findMaxForm(self, strs: List[str], m: int, n: int) -> int: @@ -86,22 +80,6 @@ class Solution: return f[sz][m][n] ``` -```python -class Solution: - def findMaxForm(self, strs: List[str], m: int, n: int) -> int: - f = [[0] * (n + 1) for _ in range(m + 1)] - for s in strs: - a, b = s.count("0"), s.count("1") - for i in range(m, a - 1, -1): - for j in range(n, b - 1, -1): - f[i][j] = max(f[i][j], f[i - a][j - b] + 1) - return f[m][n] -``` - -### **Java** - - - ```java class Solution { public int findMaxForm(String[] strs, int m, int n) { @@ -131,33 +109,6 @@ class Solution { } ``` -```java -class Solution { - public int findMaxForm(String[] strs, int m, int n) { - int[][] f = new int[m + 1][n + 1]; - for (String s : strs) { - int[] cnt = count(s); - for (int i = m; i >= cnt[0]; --i) { - for (int j = n; j >= cnt[1]; --j) { - f[i][j] = Math.max(f[i][j], f[i - cnt[0]][j - cnt[1]] + 1); - } - } - } - return f[m][n]; - } - - private int[] count(String s) { - int[] cnt = new int[2]; - for (int i = 0; i < s.length(); ++i) { - ++cnt[s.charAt(i) - '0']; - } - return cnt; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -186,32 +137,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findMaxForm(vector& strs, int m, int n) { - int f[m + 1][n + 1]; - memset(f, 0, sizeof(f)); - for (auto& s : strs) { - auto [a, b] = count(s); - for (int i = m; i >= a; --i) { - for (int j = n; j >= b; --j) { - f[i][j] = max(f[i][j], f[i - a][j - b] + 1); - } - } - } - return f[m][n]; - } - - pair count(string& s) { - int a = count_if(s.begin(), s.end(), [](char c) { return c == '0'; }); - return {a, s.size() - a}; - } -}; -``` - -### **Go** - ```go func findMaxForm(strs []string, m int, n int) int { sz := len(strs) @@ -242,31 +167,6 @@ func count(s string) (int, int) { } ``` -```go -func findMaxForm(strs []string, m int, n int) int { - f := make([][]int, m+1) - for i := range f { - f[i] = make([]int, n+1) - } - for _, s := range strs { - a, b := count(s) - for j := m; j >= a; j-- { - for k := n; k >= b; k-- { - f[j][k] = max(f[j][k], f[j-a][k-b]+1) - } - } - } - return f[m][n] -} - -func count(s string) (int, int) { - a := strings.Count(s, "0") - return a, len(s) - a -} -``` - -### **TypeScript** - ```ts function findMaxForm(strs: string[], m: number, n: number): number { const sz = strs.length; @@ -295,6 +195,96 @@ function findMaxForm(strs: string[], m: number, n: number): number { } ``` + + +### 方法二 + + + +```python +class Solution: + def findMaxForm(self, strs: List[str], m: int, n: int) -> int: + f = [[0] * (n + 1) for _ in range(m + 1)] + for s in strs: + a, b = s.count("0"), s.count("1") + for i in range(m, a - 1, -1): + for j in range(n, b - 1, -1): + f[i][j] = max(f[i][j], f[i - a][j - b] + 1) + return f[m][n] +``` + +```java +class Solution { + public int findMaxForm(String[] strs, int m, int n) { + int[][] f = new int[m + 1][n + 1]; + for (String s : strs) { + int[] cnt = count(s); + for (int i = m; i >= cnt[0]; --i) { + for (int j = n; j >= cnt[1]; --j) { + f[i][j] = Math.max(f[i][j], f[i - cnt[0]][j - cnt[1]] + 1); + } + } + } + return f[m][n]; + } + + private int[] count(String s) { + int[] cnt = new int[2]; + for (int i = 0; i < s.length(); ++i) { + ++cnt[s.charAt(i) - '0']; + } + return cnt; + } +} +``` + +```cpp +class Solution { +public: + int findMaxForm(vector& strs, int m, int n) { + int f[m + 1][n + 1]; + memset(f, 0, sizeof(f)); + for (auto& s : strs) { + auto [a, b] = count(s); + for (int i = m; i >= a; --i) { + for (int j = n; j >= b; --j) { + f[i][j] = max(f[i][j], f[i - a][j - b] + 1); + } + } + } + return f[m][n]; + } + + pair count(string& s) { + int a = count_if(s.begin(), s.end(), [](char c) { return c == '0'; }); + return {a, s.size() - a}; + } +}; +``` + +```go +func findMaxForm(strs []string, m int, n int) int { + f := make([][]int, m+1) + for i := range f { + f[i] = make([]int, n+1) + } + for _, s := range strs { + a, b := count(s) + for j := m; j >= a; j-- { + for k := n; k >= b; k-- { + f[j][k] = max(f[j][k], f[j-a][k-b]+1) + } + } + } + return f[m][n] +} + +func count(s string) (int, int) { + a := strings.Count(s, "0") + return a, len(s) - a +} +``` + ```ts function findMaxForm(strs: string[], m: number, n: number): number { const f = Array.from({ length: m + 1 }, () => Array.from({ length: n + 1 }, () => 0)); @@ -317,10 +307,6 @@ function findMaxForm(strs: string[], m: number, n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0474.Ones and Zeroes/README_EN.md b/solution/0400-0499/0474.Ones and Zeroes/README_EN.md index 32f41ea930a21..fc36c1d77d880 100644 --- a/solution/0400-0499/0474.Ones and Zeroes/README_EN.md +++ b/solution/0400-0499/0474.Ones and Zeroes/README_EN.md @@ -41,9 +41,9 @@ Other valid but smaller subsets include {"0001", "1"} and {& ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,20 +60,6 @@ class Solution: return f[sz][m][n] ``` -```python -class Solution: - def findMaxForm(self, strs: List[str], m: int, n: int) -> int: - f = [[0] * (n + 1) for _ in range(m + 1)] - for s in strs: - a, b = s.count("0"), s.count("1") - for i in range(m, a - 1, -1): - for j in range(n, b - 1, -1): - f[i][j] = max(f[i][j], f[i - a][j - b] + 1) - return f[m][n] -``` - -### **Java** - ```java class Solution { public int findMaxForm(String[] strs, int m, int n) { @@ -103,33 +89,6 @@ class Solution { } ``` -```java -class Solution { - public int findMaxForm(String[] strs, int m, int n) { - int[][] f = new int[m + 1][n + 1]; - for (String s : strs) { - int[] cnt = count(s); - for (int i = m; i >= cnt[0]; --i) { - for (int j = n; j >= cnt[1]; --j) { - f[i][j] = Math.max(f[i][j], f[i - cnt[0]][j - cnt[1]] + 1); - } - } - } - return f[m][n]; - } - - private int[] count(String s) { - int[] cnt = new int[2]; - for (int i = 0; i < s.length(); ++i) { - ++cnt[s.charAt(i) - '0']; - } - return cnt; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -158,32 +117,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findMaxForm(vector& strs, int m, int n) { - int f[m + 1][n + 1]; - memset(f, 0, sizeof(f)); - for (auto& s : strs) { - auto [a, b] = count(s); - for (int i = m; i >= a; --i) { - for (int j = n; j >= b; --j) { - f[i][j] = max(f[i][j], f[i - a][j - b] + 1); - } - } - } - return f[m][n]; - } - - pair count(string& s) { - int a = count_if(s.begin(), s.end(), [](char c) { return c == '0'; }); - return {a, s.size() - a}; - } -}; -``` - -### **Go** - ```go func findMaxForm(strs []string, m int, n int) int { sz := len(strs) @@ -214,31 +147,6 @@ func count(s string) (int, int) { } ``` -```go -func findMaxForm(strs []string, m int, n int) int { - f := make([][]int, m+1) - for i := range f { - f[i] = make([]int, n+1) - } - for _, s := range strs { - a, b := count(s) - for j := m; j >= a; j-- { - for k := n; k >= b; k-- { - f[j][k] = max(f[j][k], f[j-a][k-b]+1) - } - } - } - return f[m][n] -} - -func count(s string) (int, int) { - a := strings.Count(s, "0") - return a, len(s) - a -} -``` - -### **TypeScript** - ```ts function findMaxForm(strs: string[], m: number, n: number): number { const sz = strs.length; @@ -267,6 +175,96 @@ function findMaxForm(strs: string[], m: number, n: number): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def findMaxForm(self, strs: List[str], m: int, n: int) -> int: + f = [[0] * (n + 1) for _ in range(m + 1)] + for s in strs: + a, b = s.count("0"), s.count("1") + for i in range(m, a - 1, -1): + for j in range(n, b - 1, -1): + f[i][j] = max(f[i][j], f[i - a][j - b] + 1) + return f[m][n] +``` + +```java +class Solution { + public int findMaxForm(String[] strs, int m, int n) { + int[][] f = new int[m + 1][n + 1]; + for (String s : strs) { + int[] cnt = count(s); + for (int i = m; i >= cnt[0]; --i) { + for (int j = n; j >= cnt[1]; --j) { + f[i][j] = Math.max(f[i][j], f[i - cnt[0]][j - cnt[1]] + 1); + } + } + } + return f[m][n]; + } + + private int[] count(String s) { + int[] cnt = new int[2]; + for (int i = 0; i < s.length(); ++i) { + ++cnt[s.charAt(i) - '0']; + } + return cnt; + } +} +``` + +```cpp +class Solution { +public: + int findMaxForm(vector& strs, int m, int n) { + int f[m + 1][n + 1]; + memset(f, 0, sizeof(f)); + for (auto& s : strs) { + auto [a, b] = count(s); + for (int i = m; i >= a; --i) { + for (int j = n; j >= b; --j) { + f[i][j] = max(f[i][j], f[i - a][j - b] + 1); + } + } + } + return f[m][n]; + } + + pair count(string& s) { + int a = count_if(s.begin(), s.end(), [](char c) { return c == '0'; }); + return {a, s.size() - a}; + } +}; +``` + +```go +func findMaxForm(strs []string, m int, n int) int { + f := make([][]int, m+1) + for i := range f { + f[i] = make([]int, n+1) + } + for _, s := range strs { + a, b := count(s) + for j := m; j >= a; j-- { + for k := n; k >= b; k-- { + f[j][k] = max(f[j][k], f[j-a][k-b]+1) + } + } + } + return f[m][n] +} + +func count(s string) (int, int) { + a := strings.Count(s, "0") + return a, len(s) - a +} +``` + ```ts function findMaxForm(strs: string[], m: number, n: number): number { const f = Array.from({ length: m + 1 }, () => Array.from({ length: n + 1 }, () => 0)); @@ -289,10 +287,6 @@ function findMaxForm(strs: string[], m: number, n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0475.Heaters/README.md b/solution/0400-0499/0475.Heaters/README.md index 16b4d117e61a4..8dbdbf4e76512 100644 --- a/solution/0400-0499/0475.Heaters/README.md +++ b/solution/0400-0499/0475.Heaters/README.md @@ -50,16 +50,10 @@ ## 解法 - - -排序 + 二分查找 + 双指针。 +### 方法一 -### **Python3** - - - ```python class Solution: def findRadius(self, houses: List[int], heaters: List[int]) -> int: @@ -92,10 +86,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int findRadius(int[] houses, int[] heaters) { @@ -115,31 +105,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function findRadius(houses: number[], heaters: number[]): number { - houses.sort((a, b) => a - b); - heaters.sort((a, b) => a - b); - const m = houses.length, - n = heaters.length; - let ans = 0; - for (let i = 0, j = 0; i < m; i++) { - let cur = Math.abs(houses[i] - heaters[j]); - while ( - j + 1 < n && - Math.abs(houses[i] - heaters[j]) >= Math.abs(houses[i] - heaters[j + 1]) - ) { - cur = Math.min(Math.abs(houses[i] - heaters[++j]), cur); - } - ans = Math.max(cur, ans); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -175,8 +140,6 @@ public: }; ``` -### **Go** - ```go func findRadius(houses []int, heaters []int) int { sort.Ints(houses) @@ -214,10 +177,27 @@ func findRadius(houses []int, heaters []int) int { } ``` -### **...** - -``` - +```ts +function findRadius(houses: number[], heaters: number[]): number { + houses.sort((a, b) => a - b); + heaters.sort((a, b) => a - b); + const m = houses.length, + n = heaters.length; + let ans = 0; + for (let i = 0, j = 0; i < m; i++) { + let cur = Math.abs(houses[i] - heaters[j]); + while ( + j + 1 < n && + Math.abs(houses[i] - heaters[j]) >= Math.abs(houses[i] - heaters[j + 1]) + ) { + cur = Math.min(Math.abs(houses[i] - heaters[++j]), cur); + } + ans = Math.max(cur, ans); + } + return ans; +} ``` + + diff --git a/solution/0400-0499/0475.Heaters/README_EN.md b/solution/0400-0499/0475.Heaters/README_EN.md index 7729d79ac8e4b..eba1ec59791a1 100644 --- a/solution/0400-0499/0475.Heaters/README_EN.md +++ b/solution/0400-0499/0475.Heaters/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,8 +82,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { public int findRadius(int[] houses, int[] heaters) { @@ -103,31 +101,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function findRadius(houses: number[], heaters: number[]): number { - houses.sort((a, b) => a - b); - heaters.sort((a, b) => a - b); - const m = houses.length, - n = heaters.length; - let ans = 0; - for (let i = 0, j = 0; i < m; i++) { - let cur = Math.abs(houses[i] - heaters[j]); - while ( - j + 1 < n && - Math.abs(houses[i] - heaters[j]) >= Math.abs(houses[i] - heaters[j + 1]) - ) { - cur = Math.min(Math.abs(houses[i] - heaters[++j]), cur); - } - ans = Math.max(cur, ans); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -163,8 +136,6 @@ public: }; ``` -### **Go** - ```go func findRadius(houses []int, heaters []int) int { sort.Ints(houses) @@ -202,10 +173,27 @@ func findRadius(houses []int, heaters []int) int { } ``` -### **...** - -``` - +```ts +function findRadius(houses: number[], heaters: number[]): number { + houses.sort((a, b) => a - b); + heaters.sort((a, b) => a - b); + const m = houses.length, + n = heaters.length; + let ans = 0; + for (let i = 0, j = 0; i < m; i++) { + let cur = Math.abs(houses[i] - heaters[j]); + while ( + j + 1 < n && + Math.abs(houses[i] - heaters[j]) >= Math.abs(houses[i] - heaters[j + 1]) + ) { + cur = Math.min(Math.abs(houses[i] - heaters[++j]), cur); + } + ans = Math.max(cur, ans); + } + return ans; +} ``` + + diff --git a/solution/0400-0499/0476.Number Complement/README.md b/solution/0400-0499/0476.Number Complement/README.md index 171900d247367..baa3129ef01c4 100644 --- a/solution/0400-0499/0476.Number Complement/README.md +++ b/solution/0400-0499/0476.Number Complement/README.md @@ -49,14 +49,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findComplement(self, num: int) -> int: @@ -72,16 +68,6 @@ class Solution: return ans ``` -```python -class Solution: - def findComplement(self, num: int) -> int: - return num ^ (2 ** (len(bin(num)[2:])) - 1) -``` - -### **Java** - - - ```java class Solution { public int findComplement(int num) { @@ -102,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,25 +98,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findComplement(int num) { - int ans = 0; - bool find = false; - for (int i = 30; i >= 0; --i) { - int b = num & (1 << i); - if (!find && b == 0) continue; - find = true; - if (b == 0) ans |= (1 << i); - } - return ans; - } -}; -``` - -### **Go** - ```go func findComplement(num int) int { ans := 0 @@ -151,10 +116,35 @@ func findComplement(num int) int { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def findComplement(self, num: int) -> int: + return num ^ (2 ** (len(bin(num)[2:])) - 1) ``` +```cpp +class Solution { +public: + int findComplement(int num) { + int ans = 0; + bool find = false; + for (int i = 30; i >= 0; --i) { + int b = num & (1 << i); + if (!find && b == 0) continue; + find = true; + if (b == 0) ans |= (1 << i); + } + return ans; + } +}; ``` + + diff --git a/solution/0400-0499/0476.Number Complement/README_EN.md b/solution/0400-0499/0476.Number Complement/README_EN.md index 58d49e2e1d152..fe654a3f5f7bd 100644 --- a/solution/0400-0499/0476.Number Complement/README_EN.md +++ b/solution/0400-0499/0476.Number Complement/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,14 +60,6 @@ class Solution: return ans ``` -```python -class Solution: - def findComplement(self, num: int) -> int: - return num ^ (2 ** (len(bin(num)[2:])) - 1) -``` - -### **Java** - ```java class Solution { public int findComplement(int num) { @@ -88,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,25 +90,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findComplement(int num) { - int ans = 0; - bool find = false; - for (int i = 30; i >= 0; --i) { - int b = num & (1 << i); - if (!find && b == 0) continue; - find = true; - if (b == 0) ans |= (1 << i); - } - return ans; - } -}; -``` - -### **Go** - ```go func findComplement(num int) int { ans := 0 @@ -137,10 +108,35 @@ func findComplement(num int) int { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def findComplement(self, num: int) -> int: + return num ^ (2 ** (len(bin(num)[2:])) - 1) ``` +```cpp +class Solution { +public: + int findComplement(int num) { + int ans = 0; + bool find = false; + for (int i = 30; i >= 0; --i) { + int b = num & (1 << i); + if (!find && b == 0) continue; + find = true; + if (b == 0) ans |= (1 << i); + } + return ans; + } +}; ``` + + diff --git a/solution/0400-0499/0477.Total Hamming Distance/README.md b/solution/0400-0499/0477.Total Hamming Distance/README.md index fc1b2bf1b2ffb..de93e9c243664 100644 --- a/solution/0400-0499/0477.Total Hamming Distance/README.md +++ b/solution/0400-0499/0477.Total Hamming Distance/README.md @@ -41,16 +41,10 @@ HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 ## 解法 - - -**方法一:位运算** +### 方法一:位运算 -### **Python3** - - - ```python class Solution: def totalHammingDistance(self, nums: List[int]) -> int: @@ -67,10 +61,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int totalHammingDistance(int[] nums) { @@ -89,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +98,6 @@ public: }; ``` -### **Go** - ```go func totalHammingDistance(nums []int) int { ans := 0 @@ -128,10 +114,6 @@ func totalHammingDistance(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0477.Total Hamming Distance/README_EN.md b/solution/0400-0499/0477.Total Hamming Distance/README_EN.md index 83b593be33caf..76438a8d1e95d 100644 --- a/solution/0400-0499/0477.Total Hamming Distance/README_EN.md +++ b/solution/0400-0499/0477.Total Hamming Distance/README_EN.md @@ -38,9 +38,9 @@ HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int totalHammingDistance(int[] nums) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +95,6 @@ public: }; ``` -### **Go** - ```go func totalHammingDistance(nums []int) int { ans := 0 @@ -117,10 +111,6 @@ func totalHammingDistance(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0478.Generate Random Point in a Circle/README.md b/solution/0400-0499/0478.Generate Random Point in a Circle/README.md index b4832cd455ca4..03814dcde16fa 100644 --- a/solution/0400-0499/0478.Generate Random Point in a Circle/README.md +++ b/solution/0400-0499/0478.Generate Random Point in a Circle/README.md @@ -42,14 +42,10 @@ solution.randPoint ();//返回[0.36572,0.17248] ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def __init__(self, radius: float, x_center: float, y_center: float): @@ -65,18 +61,6 @@ class Solution: return [x, y] ``` -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0478.Generate Random Point in a Circle/README_EN.md b/solution/0400-0499/0478.Generate Random Point in a Circle/README_EN.md index 47fdfa139f417..f5a5af95e99c0 100644 --- a/solution/0400-0499/0478.Generate Random Point in a Circle/README_EN.md +++ b/solution/0400-0499/0478.Generate Random Point in a Circle/README_EN.md @@ -41,9 +41,9 @@ solution.randPoint(); // return [0.36572, 0.17248] ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,16 +60,6 @@ class Solution: return [x, y] ``` -### **Java** - -```java - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0479.Largest Palindrome Product/README.md b/solution/0400-0499/0479.Largest Palindrome Product/README.md index 677289b461289..fb235218b441c 100644 --- a/solution/0400-0499/0479.Largest Palindrome Product/README.md +++ b/solution/0400-0499/0479.Largest Palindrome Product/README.md @@ -35,14 +35,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def largestPalindrome(self, n: int) -> int: @@ -60,10 +56,6 @@ class Solution: return 9 ``` -### **Java** - - - ```java class Solution { public int largestPalindrome(int n) { @@ -86,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +99,6 @@ public: }; ``` -### **Go** - ```go func largestPalindrome(n int) int { mx := int(math.Pow10(n)) - 1 @@ -129,10 +117,6 @@ func largestPalindrome(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0479.Largest Palindrome Product/README_EN.md b/solution/0400-0499/0479.Largest Palindrome Product/README_EN.md index 1ba9b2d7333b5..44a6a1b9c7093 100644 --- a/solution/0400-0499/0479.Largest Palindrome Product/README_EN.md +++ b/solution/0400-0499/0479.Largest Palindrome Product/README_EN.md @@ -31,9 +31,9 @@ Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return 9 ``` -### **Java** - ```java class Solution { public int largestPalindrome(int n) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +95,6 @@ public: }; ``` -### **Go** - ```go func largestPalindrome(n int) int { mx := int(math.Pow10(n)) - 1 @@ -119,10 +113,6 @@ func largestPalindrome(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0480.Sliding Window Median/README.md b/solution/0400-0499/0480.Sliding Window Median/README.md index 51a41a9728d0d..869350ae5843a 100644 --- a/solution/0400-0499/0480.Sliding Window Median/README.md +++ b/solution/0400-0499/0480.Sliding Window Median/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:双优先队列(大小根堆) + 延迟删除** +### 方法一:双优先队列(大小根堆) + 延迟删除 我们可以使用两个优先队列(大小根堆)维护当前窗口中的元素,其中一个优先队列存储当前窗口中较小的一半元素,另一个优先队列存储当前窗口中较大的一半元素。这样,当前窗口的中位数就是两个优先队列的堆顶元素的平均值或其中的一个。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class MedianFinder: def __init__(self, k: int): @@ -147,10 +141,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class MedianFinder { private PriorityQueue small = new PriorityQueue<>(Comparator.reverseOrder()); @@ -238,8 +228,6 @@ class Solution { } ``` -### **C++** - ```cpp class MedianFinder { public: @@ -331,8 +319,6 @@ public: }; ``` -### **Go** - ```go type MedianFinder struct { small hp @@ -434,10 +420,6 @@ func (h *hp) Pop() any { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0480.Sliding Window Median/README_EN.md b/solution/0400-0499/0480.Sliding Window Median/README_EN.md index 2c64219ea1d18..7ce12c1690b4c 100644 --- a/solution/0400-0499/0480.Sliding Window Median/README_EN.md +++ b/solution/0400-0499/0480.Sliding Window Median/README_EN.md @@ -49,9 +49,9 @@ Window position Median ## Solutions - +### Solution 1 -### **Python3** + ```python class MedianFinder: @@ -121,8 +121,6 @@ class Solution: return ans ``` -### **Java** - ```java class MedianFinder { private PriorityQueue small = new PriorityQueue<>(Comparator.reverseOrder()); @@ -210,8 +208,6 @@ class Solution { } ``` -### **C++** - ```cpp class MedianFinder { public: @@ -303,8 +299,6 @@ public: }; ``` -### **Go** - ```go type MedianFinder struct { small hp @@ -406,10 +400,6 @@ func (h *hp) Pop() any { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0481.Magical String/README.md b/solution/0400-0499/0481.Magical String/README.md index 6a17dd58f483d..a7c602065b053 100644 --- a/solution/0400-0499/0481.Magical String/README.md +++ b/solution/0400-0499/0481.Magical String/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:模拟构造过程** +### 方法一:模拟构造过程 根据题目,我们得知,字符串 $s$ 的每一组数字都可以由字符串 $s$ 自身的数字得到。 @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def magicalString(self, n: int) -> int: @@ -99,10 +93,6 @@ class Solution: return s[:n].count(1) ``` -### **Java** - - - ```java class Solution { public int magicalString(int n) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func magicalString(n int) (ans int) { s := []int{1, 2, 2} @@ -165,8 +151,6 @@ func magicalString(n int) (ans int) { } ``` -### **TypeScript** - ```ts function magicalString(n: number): number { const cs = [...'1221121']; @@ -183,8 +167,6 @@ function magicalString(n: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn magical_string(n: i32) -> i32 { @@ -208,10 +190,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0481.Magical String/README_EN.md b/solution/0400-0499/0481.Magical String/README_EN.md index b51d82da1c9a9..25762c9854d72 100644 --- a/solution/0400-0499/0481.Magical String/README_EN.md +++ b/solution/0400-0499/0481.Magical String/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,13 +51,12 @@ class Solution: while len(s) < n: pre = s[-1] cur = 3 - pre + # cur 表示这一组的数字,s[i] 表示这一组数字出现的次数 s += [cur] * s[i] i += 1 return s[:n].count(1) ``` -### **Java** - ```java class Solution { public int magicalString(int n) { @@ -80,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +96,6 @@ public: }; ``` -### **Go** - ```go func magicalString(n int) (ans int) { s := []int{1, 2, 2} @@ -120,8 +115,6 @@ func magicalString(n int) (ans int) { } ``` -### **TypeScript** - ```ts function magicalString(n: number): number { const cs = [...'1221121']; @@ -138,8 +131,6 @@ function magicalString(n: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn magical_string(n: i32) -> i32 { @@ -163,10 +154,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0482.License Key Formatting/README.md b/solution/0400-0499/0482.License Key Formatting/README.md index a70600293b984..143b28ca31fe4 100644 --- a/solution/0400-0499/0482.License Key Formatting/README.md +++ b/solution/0400-0499/0482.License Key Formatting/README.md @@ -43,16 +43,10 @@ ## 解法 - - -简单模拟。 +### 方法一 -### **Python3** - - - ```python class Solution: def licenseKeyFormatting(self, s: str, k: int) -> str: @@ -71,10 +65,6 @@ class Solution: return ''.join(res) ``` -### **Java** - - - ```java class Solution { public String licenseKeyFormatting(String s, int k) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func licenseKeyFormatting(s string, k int) string { s = strings.ReplaceAll(s, "-", "") @@ -157,10 +143,6 @@ func licenseKeyFormatting(s string, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0482.License Key Formatting/README_EN.md b/solution/0400-0499/0482.License Key Formatting/README_EN.md index 4f62635a464aa..211c9aa14ceca 100644 --- a/solution/0400-0499/0482.License Key Formatting/README_EN.md +++ b/solution/0400-0499/0482.License Key Formatting/README_EN.md @@ -39,9 +39,9 @@ Note that the two extra dashes are not needed and can be removed. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ''.join(res) ``` -### **Java** - ```java class Solution { public String licenseKeyFormatting(String s, int k) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +115,6 @@ public: }; ``` -### **Go** - ```go func licenseKeyFormatting(s string, k int) string { s = strings.ReplaceAll(s, "-", "") @@ -145,10 +139,6 @@ func licenseKeyFormatting(s string, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0483.Smallest Good Base/README.md b/solution/0400-0499/0483.Smallest Good Base/README.md index e6d9503f1e23d..3feff19567efa 100644 --- a/solution/0400-0499/0483.Smallest Good Base/README.md +++ b/solution/0400-0499/0483.Smallest Good Base/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 假设 $n$ 在 $k$ 进制下的所有位数均为 $1$,且位数为 $m+1$,那么有式子 ①: @@ -162,10 +160,6 @@ $$ -### **Python3** - - - ```python class Solution: def smallestGoodBase(self, n: str) -> str: @@ -190,10 +184,6 @@ class Solution: return str(num - 1) ``` -### **Java** - - - ```java class Solution { public String smallestGoodBase(String n) { @@ -238,8 +228,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -262,10 +250,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0483.Smallest Good Base/README_EN.md b/solution/0400-0499/0483.Smallest Good Base/README_EN.md index 6e00723d45750..10fd1fab3ed1c 100644 --- a/solution/0400-0499/0483.Smallest Good Base/README_EN.md +++ b/solution/0400-0499/0483.Smallest Good Base/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return str(num - 1) ``` -### **Java** - ```java class Solution { public String smallestGoodBase(String n) { @@ -117,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,10 +137,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0484.Find Permutation/README.md b/solution/0400-0499/0484.Find Permutation/README.md index b943da33a7f0f..0944fd47f38d6 100644 --- a/solution/0400-0499/0484.Find Permutation/README.md +++ b/solution/0400-0499/0484.Find Permutation/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 先初始化结果数组 `ans` 为 `[1, 2, 3, ..., n+1]`。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def findPermutation(self, s: str) -> List[int]: @@ -77,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] findPermutation(String s) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func findPermutation(s string) []int { n := len(s) @@ -161,10 +147,6 @@ func reverse(arr []int, i, j int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0484.Find Permutation/README_EN.md b/solution/0400-0499/0484.Find Permutation/README_EN.md index 5512495258cad..6b9576abbebe7 100644 --- a/solution/0400-0499/0484.Find Permutation/README_EN.md +++ b/solution/0400-0499/0484.Find Permutation/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] findPermutation(String s) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +110,6 @@ public: }; ``` -### **Go** - ```go func findPermutation(s string) []int { n := len(s) @@ -141,10 +135,6 @@ func reverse(arr []int, i, j int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0485.Max Consecutive Ones/README.md b/solution/0400-0499/0485.Max Consecutive Ones/README.md index ca8f6dd52723e..a1e9a5519a9ff 100644 --- a/solution/0400-0499/0485.Max Consecutive Ones/README.md +++ b/solution/0400-0499/0485.Max Consecutive Ones/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 遍历数组,记录当前连续 $1$ 的个数 `cnt`,以及最大连续 $1$ 的个数 `ans`。如果当前元素为 $1$,则 `cnt++`,否则更新 `ans`,并且 `cnt=0`。最后返回 `max(ans, cnt)` 即可。 @@ -46,10 +44,6 @@ -### **Python3** - - - ```python class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: @@ -63,10 +57,6 @@ class Solution: return max(ans, cnt) ``` -### **Java** - - - ```java class Solution { public int findMaxConsecutiveOnes(int[] nums) { @@ -84,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +92,6 @@ public: }; ``` -### **Go** - ```go func findMaxConsecutiveOnes(nums []int) int { ans, cnt := 0, 0 @@ -121,30 +107,6 @@ func findMaxConsecutiveOnes(nums []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var findMaxConsecutiveOnes = function (nums) { - let res = 0, - t = 0; - for (let num of nums) { - if (num == 1) { - ++t; - } else { - res = Math.max(res, t); - t = 0; - } - } - return Math.max(res, t); -}; -``` - -### **TypeScript** - ```ts function findMaxConsecutiveOnes(nums: number[]): number { let res = 0; @@ -161,8 +123,6 @@ function findMaxConsecutiveOnes(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn find_max_consecutive_ones(nums: Vec) -> i32 { @@ -181,7 +141,25 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findMaxConsecutiveOnes = function (nums) { + let res = 0, + t = 0; + for (let num of nums) { + if (num == 1) { + ++t; + } else { + res = Math.max(res, t); + t = 0; + } + } + return Math.max(res, t); +}; +``` ```php class Solution { @@ -204,10 +182,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0485.Max Consecutive Ones/README_EN.md b/solution/0400-0499/0485.Max Consecutive Ones/README_EN.md index b22cb8f862ca2..1e9e8051d5501 100644 --- a/solution/0400-0499/0485.Max Consecutive Ones/README_EN.md +++ b/solution/0400-0499/0485.Max Consecutive Ones/README_EN.md @@ -32,9 +32,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -49,8 +49,6 @@ class Solution: return max(ans, cnt) ``` -### **Java** - ```java class Solution { public int findMaxConsecutiveOnes(int[] nums) { @@ -68,8 +66,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -88,8 +84,6 @@ public: }; ``` -### **Go** - ```go func findMaxConsecutiveOnes(nums []int) int { ans, cnt := 0, 0 @@ -105,30 +99,6 @@ func findMaxConsecutiveOnes(nums []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var findMaxConsecutiveOnes = function (nums) { - let res = 0, - t = 0; - for (let num of nums) { - if (num == 1) { - ++t; - } else { - res = Math.max(res, t); - t = 0; - } - } - return Math.max(res, t); -}; -``` - -### **TypeScript** - ```ts function findMaxConsecutiveOnes(nums: number[]): number { let res = 0; @@ -145,8 +115,6 @@ function findMaxConsecutiveOnes(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn find_max_consecutive_ones(nums: Vec) -> i32 { @@ -165,7 +133,25 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findMaxConsecutiveOnes = function (nums) { + let res = 0, + t = 0; + for (let num of nums) { + if (num == 1) { + ++t; + } else { + res = Math.max(res, t); + t = 0; + } + } + return Math.max(res, t); +}; +``` ```php class Solution { @@ -188,10 +174,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0486.Predict the Winner/README.md b/solution/0400-0499/0486.Predict the Winner/README.md index 2824a7c56c90b..39eb4a4f510fc 100644 --- a/solution/0400-0499/0486.Predict the Winner/README.md +++ b/solution/0400-0499/0486.Predict the Winner/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j)$,表示从第 $i$ 个数到第 $j$ 个数,当前玩家与另一个玩家的得分之差的最大值。那么答案就是 $dfs(0, n - 1) \gt 0$。 @@ -60,33 +58,8 @@ 时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是数组的长度。 -**方法二:动态规划** - -我们也可以使用动态规划的方法,定义 $f[i][j]$ 表示当前玩家在 $nums[i..j]$ 这些数字中能够获得的最大得分的差值。那么最后答案就是 $f[0][n - 1] \gt 0$。 - -初始时 $f[i][i]=nums[i]$,因为只有一个数,所以当前玩家只能拿取这个数,得分差值为 $nums[i]$。 - -考虑 $f[i][j]$,其中 $i \lt j$,有两种情况: - -- 如果当前玩家拿走了 $nums[i]$,那么剩下的数字为 $nums[i + 1..j]$,此时轮到另一个玩家进行游戏,所以 $f[i][j] = nums[i] - f[i + 1][j]$。 -- 如果当前玩家拿走了 $nums[j]$,那么剩下的数字为 $nums[i..j - 1]$,此时轮到另一个玩家进行游戏,所以 $f[i][j] = nums[j] - f[i][j - 1]$。 - -因此,最终的状态转移方程为 $f[i][j] = \max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1])$。 - -最后,我们只需要判断 $f[0][n - 1] \gt 0$ 即可。 - -时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是数组的长度。 - -相似题目: - -- [877. 石子游戏](/solution/0800-0899/0877.Stone%20Game/README.md) - -### **Python3** - - - ```python class Solution: def PredictTheWinner(self, nums: List[int]) -> bool: @@ -99,23 +72,6 @@ class Solution: return dfs(0, len(nums) - 1) >= 0 ``` -```python -class Solution: - def PredictTheWinner(self, nums: List[int]) -> bool: - n = len(nums) - f = [[0] * n for _ in range(n)] - for i, x in enumerate(nums): - f[i][i] = x - for i in range(n - 2, -1, -1): - for j in range(i + 1, n): - f[i][j] = max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]) - return f[0][n - 1] >= 0 -``` - -### **Java** - - - ```java class Solution { private int[] nums; @@ -140,26 +96,6 @@ class Solution { } ``` -```java -class Solution { - public boolean PredictTheWinner(int[] nums) { - int n = nums.length; - int[][] f = new int[n][n]; - for (int i = 0; i < n; ++i) { - f[i][i] = nums[i]; - } - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = Math.max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]); - } - } - return f[0][n - 1] >= 0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -181,28 +117,44 @@ public: }; ``` -```cpp -class Solution { -public: - bool PredictTheWinner(vector& nums) { - int n = nums.size(); - int f[n][n]; - memset(f, 0, sizeof(f)); - for (int i = 0; i < n; ++i) { - f[i][i] = nums[i]; +```go +func PredictTheWinner(nums []int) bool { + n := len(nums) + f := make([][]int, n) + for i := range f { + f[i] = make([]int, n) + } + var dfs func(i, j int) int + dfs = func(i, j int) int { + if i > j { + return 0 + } + if f[i][j] == 0 { + f[i][j] = max(nums[i]-dfs(i+1, j), nums[j]-dfs(i, j-1)) + } + return f[i][j] + } + return dfs(0, n-1) >= 0 +} +``` + +```ts +function PredictTheWinner(nums: number[]): boolean { + const n = nums.length; + const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(0)); + const dfs = (i: number, j: number): number => { + if (i > j) { + return 0; } - for (int i = n - 2; ~i; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]); - } + if (f[i][j] === 0) { + f[i][j] = Math.max(nums[i] - dfs(i + 1, j), nums[j] - dfs(i, j - 1)); } - return f[0][n - 1] >= 0; - } -}; + return f[i][j]; + }; + return dfs(0, n - 1) >= 0; +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -232,29 +184,82 @@ impl Solution { } ``` -### **Go** + -```go -func PredictTheWinner(nums []int) bool { - n := len(nums) - f := make([][]int, n) - for i := range f { - f[i] = make([]int, n) - } - var dfs func(i, j int) int - dfs = func(i, j int) int { - if i > j { - return 0 - } - if f[i][j] == 0 { - f[i][j] = max(nums[i]-dfs(i+1, j), nums[j]-dfs(i, j-1)) - } - return f[i][j] - } - return dfs(0, n-1) >= 0 +### 方法二:动态规划 + +我们也可以使用动态规划的方法,定义 $f[i][j]$ 表示当前玩家在 $nums[i..j]$ 这些数字中能够获得的最大得分的差值。那么最后答案就是 $f[0][n - 1] \gt 0$。 + +初始时 $f[i][i]=nums[i]$,因为只有一个数,所以当前玩家只能拿取这个数,得分差值为 $nums[i]$。 + +考虑 $f[i][j]$,其中 $i \lt j$,有两种情况: + +- 如果当前玩家拿走了 $nums[i]$,那么剩下的数字为 $nums[i + 1..j]$,此时轮到另一个玩家进行游戏,所以 $f[i][j] = nums[i] - f[i + 1][j]$。 +- 如果当前玩家拿走了 $nums[j]$,那么剩下的数字为 $nums[i..j - 1]$,此时轮到另一个玩家进行游戏,所以 $f[i][j] = nums[j] - f[i][j - 1]$。 + +因此,最终的状态转移方程为 $f[i][j] = \max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1])$。 + +最后,我们只需要判断 $f[0][n - 1] \gt 0$ 即可。 + +时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是数组的长度。 + +相似题目: + +- [877. 石子游戏](/solution/0800-0899/0877.Stone%20Game/README.md) + + + +```python +class Solution: + def PredictTheWinner(self, nums: List[int]) -> bool: + n = len(nums) + f = [[0] * n for _ in range(n)] + for i, x in enumerate(nums): + f[i][i] = x + for i in range(n - 2, -1, -1): + for j in range(i + 1, n): + f[i][j] = max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]) + return f[0][n - 1] >= 0 +``` + +```java +class Solution { + public boolean PredictTheWinner(int[] nums) { + int n = nums.length; + int[][] f = new int[n][n]; + for (int i = 0; i < n; ++i) { + f[i][i] = nums[i]; + } + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = Math.max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]); + } + } + return f[0][n - 1] >= 0; + } } ``` +```cpp +class Solution { +public: + bool PredictTheWinner(vector& nums) { + int n = nums.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int i = 0; i < n; ++i) { + f[i][i] = nums[i]; + } + for (int i = n - 2; ~i; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]); + } + } + return f[0][n - 1] >= 0; + } +}; +``` + ```go func PredictTheWinner(nums []int) bool { n := len(nums) @@ -272,25 +277,6 @@ func PredictTheWinner(nums []int) bool { } ``` -### **TypeScript** - -```ts -function PredictTheWinner(nums: number[]): boolean { - const n = nums.length; - const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(0)); - const dfs = (i: number, j: number): number => { - if (i > j) { - return 0; - } - if (f[i][j] === 0) { - f[i][j] = Math.max(nums[i] - dfs(i + 1, j), nums[j] - dfs(i, j - 1)); - } - return f[i][j]; - }; - return dfs(0, n - 1) >= 0; -} -``` - ```ts function PredictTheWinner(nums: number[]): boolean { const n = nums.length; @@ -307,10 +293,6 @@ function PredictTheWinner(nums: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0486.Predict the Winner/README_EN.md b/solution/0400-0499/0486.Predict the Winner/README_EN.md index 2b466ec6766d2..084a48f305ae1 100644 --- a/solution/0400-0499/0486.Predict the Winner/README_EN.md +++ b/solution/0400-0499/0486.Predict the Winner/README_EN.md @@ -41,9 +41,9 @@ Finally, player 1 has more score (234) than player 2 (12), so you need to return ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,21 +57,6 @@ class Solution: return dfs(0, len(nums) - 1) >= 0 ``` -```python -class Solution: - def PredictTheWinner(self, nums: List[int]) -> bool: - n = len(nums) - f = [[0] * n for _ in range(n)] - for i, x in enumerate(nums): - f[i][i] = x - for i in range(n - 2, -1, -1): - for j in range(i + 1, n): - f[i][j] = max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]) - return f[0][n - 1] >= 0 -``` - -### **Java** - ```java class Solution { private int[] nums; @@ -96,26 +81,6 @@ class Solution { } ``` -```java -class Solution { - public boolean PredictTheWinner(int[] nums) { - int n = nums.length; - int[][] f = new int[n][n]; - for (int i = 0; i < n; ++i) { - f[i][i] = nums[i]; - } - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = Math.max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]); - } - } - return f[0][n - 1] >= 0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -137,28 +102,44 @@ public: }; ``` -```cpp -class Solution { -public: - bool PredictTheWinner(vector& nums) { - int n = nums.size(); - int f[n][n]; - memset(f, 0, sizeof(f)); - for (int i = 0; i < n; ++i) { - f[i][i] = nums[i]; +```go +func PredictTheWinner(nums []int) bool { + n := len(nums) + f := make([][]int, n) + for i := range f { + f[i] = make([]int, n) + } + var dfs func(i, j int) int + dfs = func(i, j int) int { + if i > j { + return 0 + } + if f[i][j] == 0 { + f[i][j] = max(nums[i]-dfs(i+1, j), nums[j]-dfs(i, j-1)) + } + return f[i][j] + } + return dfs(0, n-1) >= 0 +} +``` + +```ts +function PredictTheWinner(nums: number[]): boolean { + const n = nums.length; + const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(0)); + const dfs = (i: number, j: number): number => { + if (i > j) { + return 0; } - for (int i = n - 2; ~i; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]); - } + if (f[i][j] === 0) { + f[i][j] = Math.max(nums[i] - dfs(i + 1, j), nums[j] - dfs(i, j - 1)); } - return f[0][n - 1] >= 0; - } -}; + return f[i][j]; + }; + return dfs(0, n - 1) >= 0; +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -188,29 +169,63 @@ impl Solution { } ``` -### **Go** + -```go -func PredictTheWinner(nums []int) bool { - n := len(nums) - f := make([][]int, n) - for i := range f { - f[i] = make([]int, n) - } - var dfs func(i, j int) int - dfs = func(i, j int) int { - if i > j { - return 0 - } - if f[i][j] == 0 { - f[i][j] = max(nums[i]-dfs(i+1, j), nums[j]-dfs(i, j-1)) - } - return f[i][j] - } - return dfs(0, n-1) >= 0 +### Solution 2 + + + +```python +class Solution: + def PredictTheWinner(self, nums: List[int]) -> bool: + n = len(nums) + f = [[0] * n for _ in range(n)] + for i, x in enumerate(nums): + f[i][i] = x + for i in range(n - 2, -1, -1): + for j in range(i + 1, n): + f[i][j] = max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]) + return f[0][n - 1] >= 0 +``` + +```java +class Solution { + public boolean PredictTheWinner(int[] nums) { + int n = nums.length; + int[][] f = new int[n][n]; + for (int i = 0; i < n; ++i) { + f[i][i] = nums[i]; + } + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = Math.max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]); + } + } + return f[0][n - 1] >= 0; + } } ``` +```cpp +class Solution { +public: + bool PredictTheWinner(vector& nums) { + int n = nums.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int i = 0; i < n; ++i) { + f[i][i] = nums[i]; + } + for (int i = n - 2; ~i; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = max(nums[i] - f[i + 1][j], nums[j] - f[i][j - 1]); + } + } + return f[0][n - 1] >= 0; + } +}; +``` + ```go func PredictTheWinner(nums []int) bool { n := len(nums) @@ -228,25 +243,6 @@ func PredictTheWinner(nums []int) bool { } ``` -### **TypeScript** - -```ts -function PredictTheWinner(nums: number[]): boolean { - const n = nums.length; - const f: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(0)); - const dfs = (i: number, j: number): number => { - if (i > j) { - return 0; - } - if (f[i][j] === 0) { - f[i][j] = Math.max(nums[i] - dfs(i + 1, j), nums[j] - dfs(i, j - 1)); - } - return f[i][j]; - }; - return dfs(0, n - 1) >= 0; -} -``` - ```ts function PredictTheWinner(nums: number[]): boolean { const n = nums.length; @@ -263,10 +259,6 @@ function PredictTheWinner(nums: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0487.Max Consecutive Ones II/README.md b/solution/0400-0499/0487.Max Consecutive Ones II/README.md index ccfa3554af057..d57b7bd927ed1 100644 --- a/solution/0400-0499/0487.Max Consecutive Ones II/README.md +++ b/solution/0400-0499/0487.Max Consecutive Ones II/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:预处理 + 枚举** +### 方法一:预处理 + 枚举 定义 `left`, `right` 数组表示以第 $i$ 个元素结尾(开头),往前(往后)累计的最大连续 $1$ 的个数。 @@ -53,30 +51,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 `nums` 的长度。 -**方法二:滑动窗口** - -找出最大的窗口,使得窗口内的 $0$ 的个数不超过 $1$ 个。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为 `nums` 的长度。 - -相似题目:[1004. 最大连续 1 的个数 III](/solution/1000-1099/1004.Max%20Consecutive%20Ones%20III/README.md) - -以下是滑动窗口的优化版本。 - -维护一个单调变长的窗口。这种窗口经常出现在寻求“最大窗口”的问题中:因为求的是“最大”,所以我们没有必要缩短窗口,于是代码就少了缩短窗口的部分;从另一个角度讲,本题里的 K 是资源数,一旦透支,窗口就不能再增长了。 - -- l 是窗口左端点,负责移动起始位置 -- r 是窗口右端点,负责扩展窗口 -- k 是资源数,每次要替换 0,k 减 1,同时 r 向右移动 -- `r++` 每次都会执行,`l++` 只有资源 `k < 0` 时才触发,因此 `r - l` 的值只会单调递增(或保持不变) -- 移动左端点时,如果当前元素是 0,说明可以释放一个资源,k 加 1 - -### **Python3** - - - ```python class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: @@ -102,42 +78,6 @@ class Solution: return ans ``` -```python -class Solution: - def findMaxConsecutiveOnes(self, nums: List[int]) -> int: - ans = 1 - cnt = j = 0 - for i, v in enumerate(nums): - if v == 0: - cnt += 1 - while cnt > 1: - if nums[j] == 0: - cnt -= 1 - j += 1 - ans = max(ans, i - j + 1) - return ans -``` - -```python -class Solution: - def findMaxConsecutiveOnes(self, nums: List[int]) -> int: - l = r = 0 - k = 1 - while r < len(nums): - if nums[r] == 0: - k -= 1 - if k < 0: - if nums[l] == 0: - k += 1 - l += 1 - r += 1 - return r - l -``` - -### **Java** - - - ```java class Solution { public int findMaxConsecutiveOnes(int[] nums) { @@ -170,47 +110,6 @@ class Solution { } ``` -```java -class Solution { - public int findMaxConsecutiveOnes(int[] nums) { - int j = 0, cnt = 0; - int ans = 1; - for (int i = 0; i < nums.length; ++i) { - if (nums[i] == 0) { - ++cnt; - } - while (cnt > 1) { - if (nums[j++] == 0) { - --cnt; - } - } - ans = Math.max(ans, i - j + 1); - } - return ans; - } -} -``` - -```java -class Solution { - public int findMaxConsecutiveOnes(int[] nums) { - int l = 0, r = 0; - int k = 1; - while (r < nums.length) { - if (nums[r++] == 0) { - --k; - } - if (k < 0 && nums[l++] == 0) { - ++k; - } - } - return r - l; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -243,49 +142,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findMaxConsecutiveOnes(vector& nums) { - int ans = 1; - int cnt = 0, j = 0; - for (int i = 0; i < nums.size(); ++i) { - if (nums[i] == 0) { - ++cnt; - } - while (cnt > 1) { - if (nums[j++] == 0) { - --cnt; - } - } - ans = max(ans, i - j + 1); - } - return ans; - } -}; -``` - -```cpp -class Solution { -public: - int findMaxConsecutiveOnes(vector& nums) { - int l = 0, r = 0; - int k = 1; - while (r < nums.size()) { - if (nums[r++] == 0) { - --k; - } - if (k < 0 && nums[l++] == 0) { - ++k; - } - } - return r - l; - } -}; -``` - -### **Go** - ```go func findMaxConsecutiveOnes(nums []int) int { n := len(nums) @@ -324,6 +180,87 @@ func findMaxConsecutiveOnes(nums []int) int { } ``` + + +### 方法二:滑动窗口 + +找出最大的窗口,使得窗口内的 $0$ 的个数不超过 $1$ 个。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为 `nums` 的长度。 + +相似题目:[1004. 最大连续 1 的个数 III](/solution/1000-1099/1004.Max%20Consecutive%20Ones%20III/README.md) + +以下是滑动窗口的优化版本。 + +维护一个单调变长的窗口。这种窗口经常出现在寻求“最大窗口”的问题中:因为求的是“最大”,所以我们没有必要缩短窗口,于是代码就少了缩短窗口的部分;从另一个角度讲,本题里的 K 是资源数,一旦透支,窗口就不能再增长了。 + +- l 是窗口左端点,负责移动起始位置 +- r 是窗口右端点,负责扩展窗口 +- k 是资源数,每次要替换 0,k 减 1,同时 r 向右移动 +- `r++` 每次都会执行,`l++` 只有资源 `k < 0` 时才触发,因此 `r - l` 的值只会单调递增(或保持不变) +- 移动左端点时,如果当前元素是 0,说明可以释放一个资源,k 加 1 + + + +```python +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + ans = 1 + cnt = j = 0 + for i, v in enumerate(nums): + if v == 0: + cnt += 1 + while cnt > 1: + if nums[j] == 0: + cnt -= 1 + j += 1 + ans = max(ans, i - j + 1) + return ans +``` + +```java +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int j = 0, cnt = 0; + int ans = 1; + for (int i = 0; i < nums.length; ++i) { + if (nums[i] == 0) { + ++cnt; + } + while (cnt > 1) { + if (nums[j++] == 0) { + --cnt; + } + } + ans = Math.max(ans, i - j + 1); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + int ans = 1; + int cnt = 0, j = 0; + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] == 0) { + ++cnt; + } + while (cnt > 1) { + if (nums[j++] == 0) { + --cnt; + } + } + ans = max(ans, i - j + 1); + } + return ans; + } +}; +``` + ```go func findMaxConsecutiveOnes(nums []int) int { ans := 1 @@ -344,6 +281,65 @@ func findMaxConsecutiveOnes(nums []int) int { } ``` + + +### 方法三 + + + +```python +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + l = r = 0 + k = 1 + while r < len(nums): + if nums[r] == 0: + k -= 1 + if k < 0: + if nums[l] == 0: + k += 1 + l += 1 + r += 1 + return r - l +``` + +```java +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int l = 0, r = 0; + int k = 1; + while (r < nums.length) { + if (nums[r++] == 0) { + --k; + } + if (k < 0 && nums[l++] == 0) { + ++k; + } + } + return r - l; + } +} +``` + +```cpp +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + int l = 0, r = 0; + int k = 1; + while (r < nums.size()) { + if (nums[r++] == 0) { + --k; + } + if (k < 0 && nums[l++] == 0) { + ++k; + } + } + return r - l; + } +}; +``` + ```go func findMaxConsecutiveOnes(nums []int) int { l, r := 0, 0 @@ -363,10 +359,6 @@ func findMaxConsecutiveOnes(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0487.Max Consecutive Ones II/README_EN.md b/solution/0400-0499/0487.Max Consecutive Ones II/README_EN.md index f5f945dec8ad1..5ffd326bc4a9c 100644 --- a/solution/0400-0499/0487.Max Consecutive Ones II/README_EN.md +++ b/solution/0400-0499/0487.Max Consecutive Ones II/README_EN.md @@ -42,9 +42,9 @@ The max number of consecutive ones is 4. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,40 +71,6 @@ class Solution: return ans ``` -```python -class Solution: - def findMaxConsecutiveOnes(self, nums: List[int]) -> int: - ans = 1 - cnt = j = 0 - for i, v in enumerate(nums): - if v == 0: - cnt += 1 - while cnt > 1: - if nums[j] == 0: - cnt -= 1 - j += 1 - ans = max(ans, i - j + 1) - return ans -``` - -```python -class Solution: - def findMaxConsecutiveOnes(self, nums: List[int]) -> int: - l = r = 0 - k = 1 - while r < len(nums): - if nums[r] == 0: - k -= 1 - if k < 0: - if nums[l] == 0: - k += 1 - l += 1 - r += 1 - return r - l -``` - -### **Java** - ```java class Solution { public int findMaxConsecutiveOnes(int[] nums) { @@ -137,47 +103,6 @@ class Solution { } ``` -```java -class Solution { - public int findMaxConsecutiveOnes(int[] nums) { - int j = 0, cnt = 0; - int ans = 1; - for (int i = 0; i < nums.length; ++i) { - if (nums[i] == 0) { - ++cnt; - } - while (cnt > 1) { - if (nums[j++] == 0) { - --cnt; - } - } - ans = Math.max(ans, i - j + 1); - } - return ans; - } -} -``` - -```java -class Solution { - public int findMaxConsecutiveOnes(int[] nums) { - int l = 0, r = 0; - int k = 1; - while (r < nums.length) { - if (nums[r++] == 0) { - --k; - } - if (k < 0 && nums[l++] == 0) { - ++k; - } - } - return r - l; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -210,49 +135,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findMaxConsecutiveOnes(vector& nums) { - int ans = 1; - int cnt = 0, j = 0; - for (int i = 0; i < nums.size(); ++i) { - if (nums[i] == 0) { - ++cnt; - } - while (cnt > 1) { - if (nums[j++] == 0) { - --cnt; - } - } - ans = max(ans, i - j + 1); - } - return ans; - } -}; -``` - -```cpp -class Solution { -public: - int findMaxConsecutiveOnes(vector& nums) { - int l = 0, r = 0; - int k = 1; - while (r < nums.size()) { - if (nums[r++] == 0) { - --k; - } - if (k < 0 && nums[l++] == 0) { - ++k; - } - } - return r - l; - } -}; -``` - -### **Go** - ```go func findMaxConsecutiveOnes(nums []int) int { n := len(nums) @@ -291,6 +173,71 @@ func findMaxConsecutiveOnes(nums []int) int { } ``` + + +### Solution 2 + + + +```python +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + ans = 1 + cnt = j = 0 + for i, v in enumerate(nums): + if v == 0: + cnt += 1 + while cnt > 1: + if nums[j] == 0: + cnt -= 1 + j += 1 + ans = max(ans, i - j + 1) + return ans +``` + +```java +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int j = 0, cnt = 0; + int ans = 1; + for (int i = 0; i < nums.length; ++i) { + if (nums[i] == 0) { + ++cnt; + } + while (cnt > 1) { + if (nums[j++] == 0) { + --cnt; + } + } + ans = Math.max(ans, i - j + 1); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + int ans = 1; + int cnt = 0, j = 0; + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] == 0) { + ++cnt; + } + while (cnt > 1) { + if (nums[j++] == 0) { + --cnt; + } + } + ans = max(ans, i - j + 1); + } + return ans; + } +}; +``` + ```go func findMaxConsecutiveOnes(nums []int) int { ans := 1 @@ -311,6 +258,65 @@ func findMaxConsecutiveOnes(nums []int) int { } ``` + + +### Solution 3 + + + +```python +class Solution: + def findMaxConsecutiveOnes(self, nums: List[int]) -> int: + l = r = 0 + k = 1 + while r < len(nums): + if nums[r] == 0: + k -= 1 + if k < 0: + if nums[l] == 0: + k += 1 + l += 1 + r += 1 + return r - l +``` + +```java +class Solution { + public int findMaxConsecutiveOnes(int[] nums) { + int l = 0, r = 0; + int k = 1; + while (r < nums.length) { + if (nums[r++] == 0) { + --k; + } + if (k < 0 && nums[l++] == 0) { + ++k; + } + } + return r - l; + } +} +``` + +```cpp +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + int l = 0, r = 0; + int k = 1; + while (r < nums.size()) { + if (nums[r++] == 0) { + --k; + } + if (k < 0 && nums[l++] == 0) { + ++k; + } + } + return r - l; + } +}; +``` + ```go func findMaxConsecutiveOnes(nums []int) int { l, r := 0, 0 @@ -330,10 +336,6 @@ func findMaxConsecutiveOnes(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0488.Zuma Game/README.md b/solution/0400-0499/0488.Zuma Game/README.md index fbed174534b96..b838a81175ed5 100644 --- a/solution/0400-0499/0488.Zuma Game/README.md +++ b/solution/0400-0499/0488.Zuma Game/README.md @@ -84,14 +84,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findMinStep(self, board: str, hand: str) -> int: @@ -120,18 +116,6 @@ class Solution: return -1 ``` -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0488.Zuma Game/README_EN.md b/solution/0400-0499/0488.Zuma Game/README_EN.md index 3b67b40387fc1..09cd1ec20ada0 100644 --- a/solution/0400-0499/0488.Zuma Game/README_EN.md +++ b/solution/0400-0499/0488.Zuma Game/README_EN.md @@ -68,9 +68,9 @@ There are still balls remaining on the board, and you are out of balls to insert ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -100,16 +100,6 @@ class Solution: return -1 ``` -### **Java** - -```java - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0489.Robot Room Cleaner/README.md b/solution/0400-0499/0489.Robot Room Cleaner/README.md index 222c670a91805..d96e77374918c 100644 --- a/solution/0400-0499/0489.Robot Room Cleaner/README.md +++ b/solution/0400-0499/0489.Robot Room Cleaner/README.md @@ -82,9 +82,7 @@ interface Robot { ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们不妨假设机器人的初始位置为 $(0, 0)$,方向为 $d=0$。我们将初始位置进行打扫,并标记为已访问。然后,我们依次选择上、右、下、左四个方向进行探索,每次探索前都先判断是否已经访问过,如果没有访问过,我们就朝着该方向前进一步,然后递归探索。如果已经访问过,我们就顺时针旋转 $90^\circ$,然后继续探索下一个方向。当我们探索完所有的方向后,我们需要回到上一个位置,这时我们只需要顺时针旋转 $180^\circ$,然后前进一步,再顺时针旋转 $180^\circ$ 即可。 @@ -92,10 +90,6 @@ interface Robot { -### **Python3** - - - ```python # """ # This is the robot's control interface. @@ -157,10 +151,6 @@ class Solution: dfs(0, 0, 0) ``` -### **Java** - - - ```java /** * // This is the robot's control interface. @@ -210,8 +200,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the robot's control interface. @@ -259,8 +247,6 @@ public: }; ``` -### **Go** - ```go /** * // This is the robot's control interface. @@ -306,8 +292,6 @@ func cleanRoom(robot *Robot) { } ``` -### **TypeScript** - ```ts /** * class Robot { @@ -352,10 +336,6 @@ function cleanRoom(robot: Robot) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0489.Robot Room Cleaner/README_EN.md b/solution/0400-0499/0489.Robot Room Cleaner/README_EN.md index d2db87963929d..9f836b7e71e16 100644 --- a/solution/0400-0499/0489.Robot Room Cleaner/README_EN.md +++ b/solution/0400-0499/0489.Robot Room Cleaner/README_EN.md @@ -74,9 +74,9 @@ From the top left corner, its position is one row below and three columns right. ## Solutions - +### Solution 1 -### **Python3** + ```python # """ @@ -139,8 +139,6 @@ class Solution: dfs(0, 0, 0) ``` -### **Java** - ```java /** * // This is the robot's control interface. @@ -190,8 +188,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the robot's control interface. @@ -239,8 +235,6 @@ public: }; ``` -### **Go** - ```go /** * // This is the robot's control interface. @@ -286,8 +280,6 @@ func cleanRoom(robot *Robot) { } ``` -### **TypeScript** - ```ts /** * class Robot { @@ -332,10 +324,6 @@ function cleanRoom(robot: Robot) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0490.The Maze/README.md b/solution/0400-0499/0490.The Maze/README.md index 9822627da5e36..9a60590b1b326 100644 --- a/solution/0400-0499/0490.The Maze/README.md +++ b/solution/0400-0499/0490.The Maze/README.md @@ -62,18 +62,10 @@ ## 解法 - - -DFS 或 BFS。 +### 方法一 -### **Python3** - - - -DFS: - ```python class Solution: def hasPath( @@ -97,37 +89,6 @@ class Solution: return vis[destination[0]][destination[1]] ``` -BFS: - -```python -class Solution: - def hasPath( - self, maze: List[List[int]], start: List[int], destination: List[int] - ) -> bool: - m, n = len(maze), len(maze[0]) - q = deque([start]) - rs, cs = start - vis = {(rs, cs)} - while q: - i, j = q.popleft() - for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: - x, y = i, j - while 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0: - x, y = x + a, y + b - if [x, y] == destination: - return True - if (x, y) not in vis: - vis.add((x, y)) - q.append((x, y)) - return False -``` - -### **Java** - - - -DFS: - ```java class Solution { private boolean[][] vis; @@ -168,45 +129,6 @@ class Solution { } ``` -BFS: - -```java -class Solution { - public boolean hasPath(int[][] maze, int[] start, int[] destination) { - int m = maze.length; - int n = maze[0].length; - boolean[][] vis = new boolean[m][n]; - vis[start[0]][start[1]] = true; - Deque q = new LinkedList<>(); - q.offer(start); - 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, y = j; - int a = dirs[k], b = dirs[k + 1]; - while ( - x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { - x += a; - y += b; - } - if (x == destination[0] && y == destination[1]) { - return true; - } - if (!vis[x][y]) { - vis[x][y] = true; - q.offer(new int[] {x, y}); - } - } - } - return false; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -244,6 +166,102 @@ public: }; ``` +```go +func hasPath(maze [][]int, start []int, destination []int) bool { + m, n := len(maze), len(maze[0]) + vis := make([][]bool, m) + for i := range vis { + vis[i] = make([]bool, n) + } + var dfs func(i, j int) + dfs = func(i, j int) { + if vis[i][j] { + return + } + vis[i][j] = true + if i == destination[0] && j == destination[1] { + return + } + dirs := []int{-1, 0, 1, 0, -1} + for k := 0; k < 4; k++ { + x, y := i, j + a, b := dirs[k], dirs[k+1] + for x+a >= 0 && x+a < m && y+b >= 0 && y+b < n && maze[x+a][y+b] == 0 { + x += a + y += b + } + dfs(x, y) + } + } + dfs(start[0], start[1]) + return vis[destination[0]][destination[1]] +} +``` + + + +### 方法二 + + + +```python +class Solution: + def hasPath( + self, maze: List[List[int]], start: List[int], destination: List[int] + ) -> bool: + m, n = len(maze), len(maze[0]) + q = deque([start]) + rs, cs = start + vis = {(rs, cs)} + while q: + i, j = q.popleft() + for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: + x, y = i, j + while 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0: + x, y = x + a, y + b + if [x, y] == destination: + return True + if (x, y) not in vis: + vis.add((x, y)) + q.append((x, y)) + return False +``` + +```java +class Solution { + public boolean hasPath(int[][] maze, int[] start, int[] destination) { + int m = maze.length; + int n = maze[0].length; + boolean[][] vis = new boolean[m][n]; + vis[start[0]][start[1]] = true; + Deque q = new LinkedList<>(); + q.offer(start); + 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, y = j; + int a = dirs[k], b = dirs[k + 1]; + while ( + x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { + x += a; + y += b; + } + if (x == destination[0] && y == destination[1]) { + return true; + } + if (!vis[x][y]) { + vis[x][y] = true; + q.offer(new int[] {x, y}); + } + } + } + return false; + } +} +``` + ```cpp class Solution { public: @@ -277,40 +295,6 @@ public: }; ``` -### **Go** - -```go -func hasPath(maze [][]int, start []int, destination []int) bool { - m, n := len(maze), len(maze[0]) - vis := make([][]bool, m) - for i := range vis { - vis[i] = make([]bool, n) - } - var dfs func(i, j int) - dfs = func(i, j int) { - if vis[i][j] { - return - } - vis[i][j] = true - if i == destination[0] && j == destination[1] { - return - } - dirs := []int{-1, 0, 1, 0, -1} - for k := 0; k < 4; k++ { - x, y := i, j - a, b := dirs[k], dirs[k+1] - for x+a >= 0 && x+a < m && y+b >= 0 && y+b < n && maze[x+a][y+b] == 0 { - x += a - y += b - } - dfs(x, y) - } - } - dfs(start[0], start[1]) - return vis[destination[0]][destination[1]] -} -``` - ```go func hasPath(maze [][]int, start []int, destination []int) bool { m, n := len(maze), len(maze[0]) @@ -344,10 +328,6 @@ func hasPath(maze [][]int, start []int, destination []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0490.The Maze/README_EN.md b/solution/0400-0499/0490.The Maze/README_EN.md index c23b69cae08ce..93ad09bc1f8c9 100644 --- a/solution/0400-0499/0490.The Maze/README_EN.md +++ b/solution/0400-0499/0490.The Maze/README_EN.md @@ -52,11 +52,9 @@ ## Solutions - - -### **Python3** +### Solution 1 -DFS. + ```python class Solution: @@ -81,35 +79,6 @@ class Solution: return vis[destination[0]][destination[1]] ``` -BFS. - -```python -class Solution: - def hasPath( - self, maze: List[List[int]], start: List[int], destination: List[int] - ) -> bool: - m, n = len(maze), len(maze[0]) - q = deque([start]) - rs, cs = start - vis = {(rs, cs)} - while q: - i, j = q.popleft() - for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: - x, y = i, j - while 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0: - x, y = x + a, y + b - if [x, y] == destination: - return True - if (x, y) not in vis: - vis.add((x, y)) - q.append((x, y)) - return False -``` - -### **Java** - -DFS. - ```java class Solution { private boolean[][] vis; @@ -150,45 +119,6 @@ class Solution { } ``` -BFS. - -```java -class Solution { - public boolean hasPath(int[][] maze, int[] start, int[] destination) { - int m = maze.length; - int n = maze[0].length; - boolean[][] vis = new boolean[m][n]; - vis[start[0]][start[1]] = true; - Deque q = new LinkedList<>(); - q.offer(start); - 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, y = j; - int a = dirs[k], b = dirs[k + 1]; - while ( - x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { - x += a; - y += b; - } - if (x == destination[0] && y == destination[1]) { - return true; - } - if (!vis[x][y]) { - vis[x][y] = true; - q.offer(new int[] {x, y}); - } - } - } - return false; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -226,6 +156,102 @@ public: }; ``` +```go +func hasPath(maze [][]int, start []int, destination []int) bool { + m, n := len(maze), len(maze[0]) + vis := make([][]bool, m) + for i := range vis { + vis[i] = make([]bool, n) + } + var dfs func(i, j int) + dfs = func(i, j int) { + if vis[i][j] { + return + } + vis[i][j] = true + if i == destination[0] && j == destination[1] { + return + } + dirs := []int{-1, 0, 1, 0, -1} + for k := 0; k < 4; k++ { + x, y := i, j + a, b := dirs[k], dirs[k+1] + for x+a >= 0 && x+a < m && y+b >= 0 && y+b < n && maze[x+a][y+b] == 0 { + x += a + y += b + } + dfs(x, y) + } + } + dfs(start[0], start[1]) + return vis[destination[0]][destination[1]] +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def hasPath( + self, maze: List[List[int]], start: List[int], destination: List[int] + ) -> bool: + m, n = len(maze), len(maze[0]) + q = deque([start]) + rs, cs = start + vis = {(rs, cs)} + while q: + i, j = q.popleft() + for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: + x, y = i, j + while 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0: + x, y = x + a, y + b + if [x, y] == destination: + return True + if (x, y) not in vis: + vis.add((x, y)) + q.append((x, y)) + return False +``` + +```java +class Solution { + public boolean hasPath(int[][] maze, int[] start, int[] destination) { + int m = maze.length; + int n = maze[0].length; + boolean[][] vis = new boolean[m][n]; + vis[start[0]][start[1]] = true; + Deque q = new LinkedList<>(); + q.offer(start); + 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, y = j; + int a = dirs[k], b = dirs[k + 1]; + while ( + x + a >= 0 && x + a < m && y + b >= 0 && y + b < n && maze[x + a][y + b] == 0) { + x += a; + y += b; + } + if (x == destination[0] && y == destination[1]) { + return true; + } + if (!vis[x][y]) { + vis[x][y] = true; + q.offer(new int[] {x, y}); + } + } + } + return false; + } +} +``` + ```cpp class Solution { public: @@ -259,40 +285,6 @@ public: }; ``` -### **Go** - -```go -func hasPath(maze [][]int, start []int, destination []int) bool { - m, n := len(maze), len(maze[0]) - vis := make([][]bool, m) - for i := range vis { - vis[i] = make([]bool, n) - } - var dfs func(i, j int) - dfs = func(i, j int) { - if vis[i][j] { - return - } - vis[i][j] = true - if i == destination[0] && j == destination[1] { - return - } - dirs := []int{-1, 0, 1, 0, -1} - for k := 0; k < 4; k++ { - x, y := i, j - a, b := dirs[k], dirs[k+1] - for x+a >= 0 && x+a < m && y+b >= 0 && y+b < n && maze[x+a][y+b] == 0 { - x += a - y += b - } - dfs(x, y) - } - } - dfs(start[0], start[1]) - return vis[destination[0]][destination[1]] -} -``` - ```go func hasPath(maze [][]int, start []int, destination []int) bool { m, n := len(maze), len(maze[0]) @@ -326,10 +318,6 @@ func hasPath(maze [][]int, start []int, destination []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0491.Non-decreasing Subsequences/README.md b/solution/0400-0499/0491.Non-decreasing Subsequences/README.md index b339eaeac2122..d6be04edbed77 100644 --- a/solution/0400-0499/0491.Non-decreasing Subsequences/README.md +++ b/solution/0400-0499/0491.Non-decreasing Subsequences/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS DFS 递归枚举每个数字选中或不选中,这里需要满足两个条件: @@ -48,10 +46,6 @@ DFS 递归枚举每个数字选中或不选中,这里需要满足两个条件 -### **Python3** - - - ```python class Solution: def findSubsequences(self, nums: List[int]) -> List[List[int]]: @@ -72,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] nums; @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func findSubsequences(nums []int) [][]int { var ans [][]int @@ -162,10 +148,6 @@ func findSubsequences(nums []int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0491.Non-decreasing Subsequences/README_EN.md b/solution/0400-0499/0491.Non-decreasing Subsequences/README_EN.md index 56c78ec0af163..e04a794fc0cc9 100644 --- a/solution/0400-0499/0491.Non-decreasing Subsequences/README_EN.md +++ b/solution/0400-0499/0491.Non-decreasing Subsequences/README_EN.md @@ -31,9 +31,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] nums; @@ -88,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +111,6 @@ public: }; ``` -### **Go** - ```go func findSubsequences(nums []int) [][]int { var ans [][]int @@ -143,10 +137,6 @@ func findSubsequences(nums []int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0492.Construct the Rectangle/README.md b/solution/0400-0499/0492.Construct the Rectangle/README.md index 8d0dc7df93c26..587beb2e18eee 100644 --- a/solution/0400-0499/0492.Construct the Rectangle/README.md +++ b/solution/0400-0499/0492.Construct the Rectangle/README.md @@ -50,14 +50,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def constructRectangle(self, area: int) -> List[int]: @@ -67,10 +63,6 @@ class Solution: return [area // w, w] ``` -### **Java** - - - ```java class Solution { public int[] constructRectangle(int area) { @@ -83,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +86,6 @@ public: }; ``` -### **Go** - ```go func constructRectangle(area int) []int { w := int(math.Sqrt(float64(area))) @@ -108,10 +96,6 @@ func constructRectangle(area int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0492.Construct the Rectangle/README_EN.md b/solution/0400-0499/0492.Construct the Rectangle/README_EN.md index feb9e229be47c..cef09d018c11b 100644 --- a/solution/0400-0499/0492.Construct the Rectangle/README_EN.md +++ b/solution/0400-0499/0492.Construct the Rectangle/README_EN.md @@ -47,9 +47,9 @@ But according to requirement 2, [1,4] is illegal; according to requirement 3, [ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return [area // w, w] ``` -### **Java** - ```java class Solution { public int[] constructRectangle(int area) { @@ -74,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +83,6 @@ public: }; ``` -### **Go** - ```go func constructRectangle(area int) []int { w := int(math.Sqrt(float64(area))) @@ -99,10 +93,6 @@ func constructRectangle(area int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0493.Reverse Pairs/README.md b/solution/0400-0499/0493.Reverse Pairs/README.md index 0c0f32fc07ebe..78c48b84cce65 100644 --- a/solution/0400-0499/0493.Reverse Pairs/README.md +++ b/solution/0400-0499/0493.Reverse Pairs/README.md @@ -33,46 +33,14 @@ ## 解法 - - -**方法一:归并排序** +### 方法一:归并排序 归并排序的过程中,如果左边的数大于右边的数,则右边的数与左边的数之后的数都构成逆序对。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组长度。 -**方法二:树状数组** - -树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作: - -1. **单点更新** `update(x, delta)`: 把序列 x 位置的数加上一个值 delta; -1. **前缀和查询** `query(x)`:查询序列 `[1,...x]` 区间的区间和,即位置 x 的前缀和。 - -这两个操作的时间复杂度均为 $O(\log n)$。 - -树状数组最基本的功能就是求比某点 x 小的点的个数(这里的比较是抽象的概念,可以是数的大小、坐标的大小、质量的大小等等)。 - -比如给定数组 `a[5] = {2, 5, 3, 4, 1}`,求 `b[i] = 位置 i 左边小于等于 a[i] 的数的个数`。对于此例,`b[5] = {0, 1, 1, 2, 0}`。 - -解决方案是直接遍历数组,每个位置先求出 `query(a[i])`,然后再修改树状数组 `update(a[i], 1)` 即可。当数的范围比较大时,需要进行离散化,即先进行去重并排序,然后对每个数字进行编号。 - -**方法三:线段树** - -线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。 - -- 线段树的每个节点代表一个区间; -- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 `[1, N]`; -- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`; -- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。 - -### **Python3** - - - -归并排序: - ```python class Solution: def reversePairs(self, nums: List[int]) -> int: @@ -105,120 +73,6 @@ class Solution: return merge_sort(0, len(nums) - 1) ``` -树状数组: - -```python -class BinaryIndexedTree: - def __init__(self, n): - self.n = n - self.c = [0] * (n + 1) - - @staticmethod - def lowbit(x): - return x & -x - - def update(self, x, delta): - while x <= self.n: - self.c[x] += delta - x += BinaryIndexedTree.lowbit(x) - - def query(self, x): - s = 0 - while x > 0: - s += self.c[x] - x -= BinaryIndexedTree.lowbit(x) - return s - - -class Solution: - def reversePairs(self, nums: List[int]) -> int: - s = set() - for num in nums: - s.add(num) - s.add(num * 2) - alls = sorted(s) - m = {v: i for i, v in enumerate(alls, 1)} - ans = 0 - tree = BinaryIndexedTree(len(m)) - for num in nums[::-1]: - ans += tree.query(m[num] - 1) - tree.update(m[num * 2], 1) - return ans -``` - -线段树: - -```python -class Node: - def __init__(self): - self.l = 0 - self.r = 0 - self.v = 0 - - -class SegmentTree: - def __init__(self, n): - self.tr = [Node() for _ in range(4 * n)] - self.build(1, 1, n) - - def build(self, u, l, r): - self.tr[u].l = l - self.tr[u].r = r - if l == r: - return - mid = (l + r) >> 1 - self.build(u << 1, l, mid) - self.build(u << 1 | 1, mid + 1, r) - - def modify(self, u, x, v): - if self.tr[u].l == x and self.tr[u].r == x: - self.tr[u].v += 1 - return - mid = (self.tr[u].l + self.tr[u].r) >> 1 - if x <= mid: - self.modify(u << 1, x, v) - else: - self.modify(u << 1 | 1, x, v) - self.pushup(u) - - def pushup(self, u): - self.tr[u].v = self.tr[u << 1].v + self.tr[u << 1 | 1].v - - def query(self, u, l, r): - if self.tr[u].l >= l and self.tr[u].r <= r: - return self.tr[u].v - mid = (self.tr[u].l + self.tr[u].r) >> 1 - v = 0 - if l <= mid: - v += self.query(u << 1, l, r) - if r > mid: - v += self.query(u << 1 | 1, l, r) - return v - - -class Solution: - def reversePairs(self, nums: List[int]) -> int: - s = set() - for num in nums: - s.add(num) - s.add(num * 2) - alls = sorted(s) - m = {v: i for i, v in enumerate(alls, 1)} - tree = SegmentTree(len(m)) - ans = 0 - for v in nums[::-1]: - x = m[v] - ans += tree.query(1, 1, x - 1) - tree.modify(1, m[v * 2], 1) - return ans -``` - -### **Java** - - - -归并排序: - ```java class Solution { private int[] nums; @@ -269,7 +123,154 @@ class Solution { } ``` -树状数组: +```cpp +class Solution { +public: + int reversePairs(vector& nums) { + int n = nums.size(); + int t[n]; + function mergeSort = [&](int l, int r) -> int { + if (l >= r) { + return 0; + } + int mid = (l + r) >> 1; + int ans = mergeSort(l, mid) + mergeSort(mid + 1, r); + int i = l, j = mid + 1, k = 0; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j] * 2LL) { + ++i; + } else { + ans += mid - i + 1; + ++j; + } + } + i = l; + j = mid + 1; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j]) { + t[k++] = nums[i++]; + } else { + t[k++] = nums[j++]; + } + } + while (i <= mid) { + t[k++] = nums[i++]; + } + while (j <= r) { + t[k++] = nums[j++]; + } + for (i = l; i <= r; ++i) { + nums[i] = t[i - l]; + } + return ans; + }; + return mergeSort(0, n - 1); + } +}; +``` + +```go +func reversePairs(nums []int) int { + n := len(nums) + t := make([]int, n) + var mergeSort func(l, r int) int + mergeSort = func(l, r int) int { + if l >= r { + return 0 + } + mid := (l + r) >> 1 + ans := mergeSort(l, mid) + mergeSort(mid+1, r) + i, j, k := l, mid+1, 0 + for i <= mid && j <= r { + if nums[i] <= nums[j]*2 { + i++ + } else { + ans += mid - i + 1 + j++ + } + } + i, j = l, mid+1 + for i <= mid && j <= r { + if nums[i] <= nums[j] { + t[k] = nums[i] + k, i = k+1, i+1 + } else { + t[k] = nums[j] + k, j = k+1, j+1 + } + } + for ; i <= mid; i, k = i+1, k+1 { + t[k] = nums[i] + } + for ; j <= r; j, k = j+1, k+1 { + t[k] = nums[j] + } + for i = l; i <= r; i++ { + nums[i] = t[i-l] + } + return ans + } + return mergeSort(0, n-1) +} +``` + + + +### 方法二:树状数组 + +树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作: + +1. **单点更新** `update(x, delta)`: 把序列 x 位置的数加上一个值 delta; +1. **前缀和查询** `query(x)`:查询序列 `[1,...x]` 区间的区间和,即位置 x 的前缀和。 + +这两个操作的时间复杂度均为 $O(\log n)$。 + +树状数组最基本的功能就是求比某点 x 小的点的个数(这里的比较是抽象的概念,可以是数的大小、坐标的大小、质量的大小等等)。 + +比如给定数组 `a[5] = {2, 5, 3, 4, 1}`,求 `b[i] = 位置 i 左边小于等于 a[i] 的数的个数`。对于此例,`b[5] = {0, 1, 1, 2, 0}`。 + +解决方案是直接遍历数组,每个位置先求出 `query(a[i])`,然后再修改树状数组 `update(a[i], 1)` 即可。当数的范围比较大时,需要进行离散化,即先进行去重并排序,然后对每个数字进行编号。 + + + +```python +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + @staticmethod + def lowbit(x): + return x & -x + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += BinaryIndexedTree.lowbit(x) + + def query(self, x): + s = 0 + while x > 0: + s += self.c[x] + x -= BinaryIndexedTree.lowbit(x) + return s + + +class Solution: + def reversePairs(self, nums: List[int]) -> int: + s = set() + for num in nums: + s.add(num) + s.add(num * 2) + alls = sorted(s) + m = {v: i for i, v in enumerate(alls, 1)} + ans = 0 + tree = BinaryIndexedTree(len(m)) + for num in nums[::-1]: + ans += tree.query(m[num] - 1) + tree.update(m[num * 2], 1) + return ans +``` ```java class Solution { @@ -311,22 +312,207 @@ class BinaryIndexedTree { } } - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + public static int lowbit(int x) { + return x & -x; + } +} +``` + +```cpp +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + int lowbit(int x) { + return x & -x; + } +}; + +class Solution { +public: + int reversePairs(vector& nums) { + set s; + for (int num : nums) { + s.insert(num); + s.insert(num * 2ll); + } + unordered_map m; + int idx = 0; + for (long long num : s) m[num] = ++idx; + BinaryIndexedTree* tree = new BinaryIndexedTree(m.size()); + int ans = 0; + for (int i = nums.size() - 1; i >= 0; --i) { + ans += tree->query(m[nums[i]] - 1); + tree->update(m[nums[i] * 2ll], 1); + } + return ans; + } +}; +``` + +```go +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) lowbit(x int) int { + return x & -x +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += this.lowbit(x) + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= this.lowbit(x) + } + return s +} + +func reversePairs(nums []int) int { + s := make(map[int]bool) + for _, num := range nums { + s[num] = true + s[num*2] = true + } + var alls []int + for num := range s { + alls = append(alls, num) + } + sort.Ints(alls) + m := make(map[int]int) + for i, num := range alls { + m[num] = i + 1 + } + tree := newBinaryIndexedTree(len(m)) + ans := 0 + for i := len(nums) - 1; i >= 0; i-- { + ans += tree.query(m[nums[i]] - 1) + tree.update(m[nums[i]*2], 1) + } + return ans +} +``` + + + +### 方法三:线段树 + +线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。 + +- 线段树的每个节点代表一个区间; +- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 `[1, N]`; +- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`; +- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。 + + + +```python +class Node: + def __init__(self): + self.l = 0 + self.r = 0 + self.v = 0 + + +class SegmentTree: + def __init__(self, n): + self.tr = [Node() for _ in range(4 * n)] + self.build(1, 1, n) + + def build(self, u, l, r): + self.tr[u].l = l + self.tr[u].r = r + if l == r: + return + mid = (l + r) >> 1 + self.build(u << 1, l, mid) + self.build(u << 1 | 1, mid + 1, r) + + def modify(self, u, x, v): + if self.tr[u].l == x and self.tr[u].r == x: + self.tr[u].v += 1 + return + mid = (self.tr[u].l + self.tr[u].r) >> 1 + if x <= mid: + self.modify(u << 1, x, v) + else: + self.modify(u << 1 | 1, x, v) + self.pushup(u) + + def pushup(self, u): + self.tr[u].v = self.tr[u << 1].v + self.tr[u << 1 | 1].v - public static int lowbit(int x) { - return x & -x; - } -} -``` + def query(self, u, l, r): + if self.tr[u].l >= l and self.tr[u].r <= r: + return self.tr[u].v + mid = (self.tr[u].l + self.tr[u].r) >> 1 + v = 0 + if l <= mid: + v += self.query(u << 1, l, r) + if r > mid: + v += self.query(u << 1 | 1, l, r) + return v -线段树: + +class Solution: + def reversePairs(self, nums: List[int]) -> int: + s = set() + for num in nums: + s.add(num) + s.add(num * 2) + alls = sorted(s) + m = {v: i for i, v in enumerate(alls, 1)} + tree = SegmentTree(len(m)) + ans = 0 + for v in nums[::-1]: + x = m[v] + ans += tree.query(1, 1, x - 1) + tree.modify(1, m[v * 2], 1) + return ans +``` ```java class Solution { @@ -415,113 +601,6 @@ class SegmentTree { } ``` -### **C++** - -归并排序: - -```cpp -class Solution { -public: - int reversePairs(vector& nums) { - int n = nums.size(); - int t[n]; - function mergeSort = [&](int l, int r) -> int { - if (l >= r) { - return 0; - } - int mid = (l + r) >> 1; - int ans = mergeSort(l, mid) + mergeSort(mid + 1, r); - int i = l, j = mid + 1, k = 0; - while (i <= mid && j <= r) { - if (nums[i] <= nums[j] * 2LL) { - ++i; - } else { - ans += mid - i + 1; - ++j; - } - } - i = l; - j = mid + 1; - while (i <= mid && j <= r) { - if (nums[i] <= nums[j]) { - t[k++] = nums[i++]; - } else { - t[k++] = nums[j++]; - } - } - while (i <= mid) { - t[k++] = nums[i++]; - } - while (j <= r) { - t[k++] = nums[j++]; - } - for (i = l; i <= r; ++i) { - nums[i] = t[i - l]; - } - return ans; - }; - return mergeSort(0, n - 1); - } -}; -``` - -树状数组: - -```cpp -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - int lowbit(int x) { - return x & -x; - } -}; - -class Solution { -public: - int reversePairs(vector& nums) { - set s; - for (int num : nums) { - s.insert(num); - s.insert(num * 2ll); - } - unordered_map m; - int idx = 0; - for (long long num : s) m[num] = ++idx; - BinaryIndexedTree* tree = new BinaryIndexedTree(m.size()); - int ans = 0; - for (int i = nums.size() - 1; i >= 0; --i) { - ans += tree->query(m[nums[i]] - 1); - tree->update(m[nums[i] * 2ll], 1); - } - return ans; - } -}; -``` - -线段树: - ```cpp class Node { public: @@ -598,117 +677,6 @@ public: }; ``` -### **Go** - -归并排序: - -```go -func reversePairs(nums []int) int { - n := len(nums) - t := make([]int, n) - var mergeSort func(l, r int) int - mergeSort = func(l, r int) int { - if l >= r { - return 0 - } - mid := (l + r) >> 1 - ans := mergeSort(l, mid) + mergeSort(mid+1, r) - i, j, k := l, mid+1, 0 - for i <= mid && j <= r { - if nums[i] <= nums[j]*2 { - i++ - } else { - ans += mid - i + 1 - j++ - } - } - i, j = l, mid+1 - for i <= mid && j <= r { - if nums[i] <= nums[j] { - t[k] = nums[i] - k, i = k+1, i+1 - } else { - t[k] = nums[j] - k, j = k+1, j+1 - } - } - for ; i <= mid; i, k = i+1, k+1 { - t[k] = nums[i] - } - for ; j <= r; j, k = j+1, k+1 { - t[k] = nums[j] - } - for i = l; i <= r; i++ { - nums[i] = t[i-l] - } - return ans - } - return mergeSort(0, n-1) -} -``` - -树状数组: - -```go -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (this *BinaryIndexedTree) lowbit(x int) int { - return x & -x -} - -func (this *BinaryIndexedTree) update(x, delta int) { - for x <= this.n { - this.c[x] += delta - x += this.lowbit(x) - } -} - -func (this *BinaryIndexedTree) query(x int) int { - s := 0 - for x > 0 { - s += this.c[x] - x -= this.lowbit(x) - } - return s -} - -func reversePairs(nums []int) int { - s := make(map[int]bool) - for _, num := range nums { - s[num] = true - s[num*2] = true - } - var alls []int - for num := range s { - alls = append(alls, num) - } - sort.Ints(alls) - m := make(map[int]int) - for i, num := range alls { - m[num] = i + 1 - } - tree := newBinaryIndexedTree(len(m)) - ans := 0 - for i := len(nums) - 1; i >= 0; i-- { - ans += tree.query(m[nums[i]] - 1) - tree.update(m[nums[i]*2], 1) - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0493.Reverse Pairs/README_EN.md b/solution/0400-0499/0493.Reverse Pairs/README_EN.md index c87bf3fefec13..2612c7fa32651 100644 --- a/solution/0400-0499/0493.Reverse Pairs/README_EN.md +++ b/solution/0400-0499/0493.Reverse Pairs/README_EN.md @@ -45,14 +45,10 @@ ## Solutions -Merge Sort or Binary Indexed Tree or Segment Tree. +### Solution 1 -### **Python3** - -Merge Sort: - ```python class Solution: def reversePairs(self, nums: List[int]) -> int: @@ -85,118 +81,6 @@ class Solution: return merge_sort(0, len(nums) - 1) ``` -Binary Indexed Tree: - -```python -class BinaryIndexedTree: - def __init__(self, n): - self.n = n - self.c = [0] * (n + 1) - - @staticmethod - def lowbit(x): - return x & -x - - def update(self, x, delta): - while x <= self.n: - self.c[x] += delta - x += BinaryIndexedTree.lowbit(x) - - def query(self, x): - s = 0 - while x > 0: - s += self.c[x] - x -= BinaryIndexedTree.lowbit(x) - return s - - -class Solution: - def reversePairs(self, nums: List[int]) -> int: - s = set() - for num in nums: - s.add(num) - s.add(num * 2) - alls = sorted(s) - m = {v: i for i, v in enumerate(alls, 1)} - ans = 0 - tree = BinaryIndexedTree(len(m)) - for num in nums[::-1]: - ans += tree.query(m[num] - 1) - tree.update(m[num * 2], 1) - return ans -``` - -Segment Tree: - -```python -class Node: - def __init__(self): - self.l = 0 - self.r = 0 - self.v = 0 - - -class SegmentTree: - def __init__(self, n): - self.tr = [Node() for _ in range(4 * n)] - self.build(1, 1, n) - - def build(self, u, l, r): - self.tr[u].l = l - self.tr[u].r = r - if l == r: - return - mid = (l + r) >> 1 - self.build(u << 1, l, mid) - self.build(u << 1 | 1, mid + 1, r) - - def modify(self, u, x, v): - if self.tr[u].l == x and self.tr[u].r == x: - self.tr[u].v += 1 - return - mid = (self.tr[u].l + self.tr[u].r) >> 1 - if x <= mid: - self.modify(u << 1, x, v) - else: - self.modify(u << 1 | 1, x, v) - self.pushup(u) - - def pushup(self, u): - self.tr[u].v = self.tr[u << 1].v + self.tr[u << 1 | 1].v - - def query(self, u, l, r): - if self.tr[u].l >= l and self.tr[u].r <= r: - return self.tr[u].v - mid = (self.tr[u].l + self.tr[u].r) >> 1 - v = 0 - if l <= mid: - v += self.query(u << 1, l, r) - if r > mid: - v += self.query(u << 1 | 1, l, r) - return v - - -class Solution: - def reversePairs(self, nums: List[int]) -> int: - s = set() - for num in nums: - s.add(num) - s.add(num * 2) - alls = sorted(s) - m = {v: i for i, v in enumerate(alls, 1)} - tree = SegmentTree(len(m)) - ans = 0 - for v in nums[::-1]: - x = m[v] - ans += tree.query(1, 1, x - 1) - tree.modify(1, m[v * 2], 1) - return ans -``` - -### **Java** - -Merge Sort: - ```java class Solution { private int[] nums; @@ -247,7 +131,141 @@ class Solution { } ``` -Binary Indexed Tree: +```cpp +class Solution { +public: + int reversePairs(vector& nums) { + int n = nums.size(); + int t[n]; + function mergeSort = [&](int l, int r) -> int { + if (l >= r) { + return 0; + } + int mid = (l + r) >> 1; + int ans = mergeSort(l, mid) + mergeSort(mid + 1, r); + int i = l, j = mid + 1, k = 0; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j] * 2LL) { + ++i; + } else { + ans += mid - i + 1; + ++j; + } + } + i = l; + j = mid + 1; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j]) { + t[k++] = nums[i++]; + } else { + t[k++] = nums[j++]; + } + } + while (i <= mid) { + t[k++] = nums[i++]; + } + while (j <= r) { + t[k++] = nums[j++]; + } + for (i = l; i <= r; ++i) { + nums[i] = t[i - l]; + } + return ans; + }; + return mergeSort(0, n - 1); + } +}; +``` + +```go +func reversePairs(nums []int) int { + n := len(nums) + t := make([]int, n) + var mergeSort func(l, r int) int + mergeSort = func(l, r int) int { + if l >= r { + return 0 + } + mid := (l + r) >> 1 + ans := mergeSort(l, mid) + mergeSort(mid+1, r) + i, j, k := l, mid+1, 0 + for i <= mid && j <= r { + if nums[i] <= nums[j]*2 { + i++ + } else { + ans += mid - i + 1 + j++ + } + } + i, j = l, mid+1 + for i <= mid && j <= r { + if nums[i] <= nums[j] { + t[k] = nums[i] + k, i = k+1, i+1 + } else { + t[k] = nums[j] + k, j = k+1, j+1 + } + } + for ; i <= mid; i, k = i+1, k+1 { + t[k] = nums[i] + } + for ; j <= r; j, k = j+1, k+1 { + t[k] = nums[j] + } + for i = l; i <= r; i++ { + nums[i] = t[i-l] + } + return ans + } + return mergeSort(0, n-1) +} +``` + + + +### Solution 2 + + + +```python +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + @staticmethod + def lowbit(x): + return x & -x + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += BinaryIndexedTree.lowbit(x) + + def query(self, x): + s = 0 + while x > 0: + s += self.c[x] + x -= BinaryIndexedTree.lowbit(x) + return s + + +class Solution: + def reversePairs(self, nums: List[int]) -> int: + s = set() + for num in nums: + s.add(num) + s.add(num * 2) + alls = sorted(s) + m = {v: i for i, v in enumerate(alls, 1)} + ans = 0 + tree = BinaryIndexedTree(len(m)) + for num in nums[::-1]: + ans += tree.query(m[num] - 1) + tree.update(m[num * 2], 1) + return ans +``` ```java class Solution { @@ -282,30 +300,208 @@ class BinaryIndexedTree { c = new int[n + 1]; } - public void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + public static int lowbit(int x) { + return x & -x; + } +} +``` + +```cpp +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + int lowbit(int x) { + return x & -x; + } +}; + +class Solution { +public: + int reversePairs(vector& nums) { + set s; + for (int num : nums) { + s.insert(num); + s.insert(num * 2ll); + } + unordered_map m; + int idx = 0; + for (long long num : s) m[num] = ++idx; + BinaryIndexedTree* tree = new BinaryIndexedTree(m.size()); + int ans = 0; + for (int i = nums.size() - 1; i >= 0; --i) { + ans += tree->query(m[nums[i]] - 1); + tree->update(m[nums[i] * 2ll], 1); + } + return ans; + } +}; +``` + +```go +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) lowbit(x int) int { + return x & -x +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += this.lowbit(x) + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= this.lowbit(x) + } + return s +} + +func reversePairs(nums []int) int { + s := make(map[int]bool) + for _, num := range nums { + s[num] = true + s[num*2] = true + } + var alls []int + for num := range s { + alls = append(alls, num) + } + sort.Ints(alls) + m := make(map[int]int) + for i, num := range alls { + m[num] = i + 1 + } + tree := newBinaryIndexedTree(len(m)) + ans := 0 + for i := len(nums) - 1; i >= 0; i-- { + ans += tree.query(m[nums[i]] - 1) + tree.update(m[nums[i]*2], 1) + } + return ans +} +``` + + + +### Solution 3 + + + +```python +class Node: + def __init__(self): + self.l = 0 + self.r = 0 + self.v = 0 + + +class SegmentTree: + def __init__(self, n): + self.tr = [Node() for _ in range(4 * n)] + self.build(1, 1, n) + + def build(self, u, l, r): + self.tr[u].l = l + self.tr[u].r = r + if l == r: + return + mid = (l + r) >> 1 + self.build(u << 1, l, mid) + self.build(u << 1 | 1, mid + 1, r) + + def modify(self, u, x, v): + if self.tr[u].l == x and self.tr[u].r == x: + self.tr[u].v += 1 + return + mid = (self.tr[u].l + self.tr[u].r) >> 1 + if x <= mid: + self.modify(u << 1, x, v) + else: + self.modify(u << 1 | 1, x, v) + self.pushup(u) + + def pushup(self, u): + self.tr[u].v = self.tr[u << 1].v + self.tr[u << 1 | 1].v + + def query(self, u, l, r): + if self.tr[u].l >= l and self.tr[u].r <= r: + return self.tr[u].v + mid = (self.tr[u].l + self.tr[u].r) >> 1 + v = 0 + if l <= mid: + v += self.query(u << 1, l, r) + if r > mid: + v += self.query(u << 1 | 1, l, r) + return v - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - public static int lowbit(int x) { - return x & -x; - } -} +class Solution: + def reversePairs(self, nums: List[int]) -> int: + s = set() + for num in nums: + s.add(num) + s.add(num * 2) + alls = sorted(s) + m = {v: i for i, v in enumerate(alls, 1)} + tree = SegmentTree(len(m)) + ans = 0 + for v in nums[::-1]: + x = m[v] + ans += tree.query(1, 1, x - 1) + tree.modify(1, m[v * 2], 1) + return ans ``` -Segment Tree: - ```java class Solution { public int reversePairs(int[] nums) { @@ -393,113 +589,6 @@ class SegmentTree { } ``` -### **C++** - -Merge Sort: - -```cpp -class Solution { -public: - int reversePairs(vector& nums) { - int n = nums.size(); - int t[n]; - function mergeSort = [&](int l, int r) -> int { - if (l >= r) { - return 0; - } - int mid = (l + r) >> 1; - int ans = mergeSort(l, mid) + mergeSort(mid + 1, r); - int i = l, j = mid + 1, k = 0; - while (i <= mid && j <= r) { - if (nums[i] <= nums[j] * 2LL) { - ++i; - } else { - ans += mid - i + 1; - ++j; - } - } - i = l; - j = mid + 1; - while (i <= mid && j <= r) { - if (nums[i] <= nums[j]) { - t[k++] = nums[i++]; - } else { - t[k++] = nums[j++]; - } - } - while (i <= mid) { - t[k++] = nums[i++]; - } - while (j <= r) { - t[k++] = nums[j++]; - } - for (i = l; i <= r; ++i) { - nums[i] = t[i - l]; - } - return ans; - }; - return mergeSort(0, n - 1); - } -}; -``` - -Binary Indexed Tree: - -```cpp -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - int lowbit(int x) { - return x & -x; - } -}; - -class Solution { -public: - int reversePairs(vector& nums) { - set s; - for (int num : nums) { - s.insert(num); - s.insert(num * 2ll); - } - unordered_map m; - int idx = 0; - for (long long num : s) m[num] = ++idx; - BinaryIndexedTree* tree = new BinaryIndexedTree(m.size()); - int ans = 0; - for (int i = nums.size() - 1; i >= 0; --i) { - ans += tree->query(m[nums[i]] - 1); - tree->update(m[nums[i] * 2ll], 1); - } - return ans; - } -}; -``` - -Segment Tree: - ```cpp class Node { public: @@ -576,113 +665,6 @@ public: }; ``` -### **Go** - -```go -func reversePairs(nums []int) int { - n := len(nums) - t := make([]int, n) - var mergeSort func(l, r int) int - mergeSort = func(l, r int) int { - if l >= r { - return 0 - } - mid := (l + r) >> 1 - ans := mergeSort(l, mid) + mergeSort(mid+1, r) - i, j, k := l, mid+1, 0 - for i <= mid && j <= r { - if nums[i] <= nums[j]*2 { - i++ - } else { - ans += mid - i + 1 - j++ - } - } - i, j = l, mid+1 - for i <= mid && j <= r { - if nums[i] <= nums[j] { - t[k] = nums[i] - k, i = k+1, i+1 - } else { - t[k] = nums[j] - k, j = k+1, j+1 - } - } - for ; i <= mid; i, k = i+1, k+1 { - t[k] = nums[i] - } - for ; j <= r; j, k = j+1, k+1 { - t[k] = nums[j] - } - for i = l; i <= r; i++ { - nums[i] = t[i-l] - } - return ans - } - return mergeSort(0, n-1) -} -``` - -```go -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (this *BinaryIndexedTree) lowbit(x int) int { - return x & -x -} - -func (this *BinaryIndexedTree) update(x, delta int) { - for x <= this.n { - this.c[x] += delta - x += this.lowbit(x) - } -} - -func (this *BinaryIndexedTree) query(x int) int { - s := 0 - for x > 0 { - s += this.c[x] - x -= this.lowbit(x) - } - return s -} - -func reversePairs(nums []int) int { - s := make(map[int]bool) - for _, num := range nums { - s[num] = true - s[num*2] = true - } - var alls []int - for num := range s { - alls = append(alls, num) - } - sort.Ints(alls) - m := make(map[int]int) - for i, num := range alls { - m[num] = i + 1 - } - tree := newBinaryIndexedTree(len(m)) - ans := 0 - for i := len(nums) - 1; i >= 0; i-- { - ans += tree.query(m[nums[i]] - 1) - tree.update(m[nums[i]*2], 1) - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0494.Target Sum/README.md b/solution/0400-0499/0494.Target Sum/README.md index b996c3cb4ac33..222e5ee807dfb 100644 --- a/solution/0400-0499/0494.Target Sum/README.md +++ b/solution/0400-0499/0494.Target Sum/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 题目可以转换为 `0-1` 背包问题。 @@ -63,10 +61,6 @@ -### **Python3** - -动态规划——`0-1` 背包朴素做法: - ```python class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: @@ -84,44 +78,6 @@ class Solution: return dp[-1][-1] ``` -动态规划——`0-1` 背包空间优化: - -```python -class Solution: - def findTargetSumWays(self, nums: List[int], target: int) -> int: - s = sum(nums) - if s < target or (s - target) % 2 != 0: - return 0 - n = (s - target) // 2 - dp = [0] * (n + 1) - dp[0] = 1 - for v in nums: - for j in range(n, v - 1, -1): - dp[j] += dp[j - v] - return dp[-1] -``` - -DFS: - -```python -class Solution: - def findTargetSumWays(self, nums: List[int], target: int) -> int: - @cache - def dfs(i, t): - if i == n: - if t == target: - return 1 - return 0 - return dfs(i + 1, t + nums[i]) + dfs(i + 1, t - nums[i]) - - ans, n = 0, len(nums) - return dfs(0, 0) -``` - -### **Java** - - - ```java class Solution { public int findTargetSumWays(int[] nums, int target) { @@ -149,31 +105,6 @@ class Solution { } ``` -```java -class Solution { - public int findTargetSumWays(int[] nums, int target) { - int s = 0; - for (int v : nums) { - s += v; - } - if (s < target || (s - target) % 2 != 0) { - return 0; - } - int n = (s - target) / 2; - int[] dp = new int[n + 1]; - dp[0] = 1; - for (int v : nums) { - for (int j = n; j >= v; --j) { - dp[j] += dp[j - v]; - } - } - return dp[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -194,25 +125,33 @@ public: }; ``` -```cpp -class Solution { -public: - int findTargetSumWays(vector& nums, int target) { - int s = accumulate(nums.begin(), nums.end(), 0); - if (s < target || (s - target) % 2 != 0) return 0; - int n = (s - target) / 2; - vector dp(n + 1); - dp[0] = 1; - for (int& v : nums) - for (int j = n; j >= v; --j) - dp[j] += dp[j - v]; - return dp[n]; - } -}; +```go +func findTargetSumWays(nums []int, target int) int { + s := 0 + for _, v := range nums { + s += v + } + if s < target || (s-target)%2 != 0 { + return 0 + } + m, n := len(nums), (s-target)/2 + dp := make([][]int, m+1) + for i := range dp { + dp[i] = make([]int, n+1) + } + dp[0][0] = 1 + for i := 1; i <= m; i++ { + for j := 0; j <= n; j++ { + dp[i][j] = dp[i-1][j] + if nums[i-1] <= j { + dp[i][j] += dp[i-1][j-nums[i-1]] + } + } + } + return dp[m][n] +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -252,65 +191,92 @@ impl Solution { } ``` -```rust -impl Solution { - #[allow(dead_code)] - pub fn find_target_sum_ways(nums: Vec, target: i32) -> i32 { - let mut sum = 0; - for e in &nums { - sum += *e; +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var findTargetSumWays = function (nums, target) { + let s = 0; + for (let v of nums) { + s += v; + } + if (s < target || (s - target) % 2 != 0) { + return 0; + } + const m = nums.length; + const n = (s - target) / 2; + let dp = new Array(n + 1).fill(0); + dp[0] = 1; + for (let i = 1; i <= m; ++i) { + for (let j = n; j >= nums[i - 1]; --j) { + dp[j] += dp[j - nums[i - 1]]; } + } + return dp[n]; +}; +``` - if sum < target || (sum - target) % 2 != 0 { - // Just directly return - return 0; - } + - let n = ((sum - target) / 2) as usize; - let mut dp: Vec = vec![0; n + 1]; +### 方法二 - // Initialize the dp vector - dp[0] = 1; + - // Begin the actual dp phase - for e in &nums { - for i in (*e as usize..=n).rev() { - dp[i] += dp[i - (*e as usize)]; +```python +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + s = sum(nums) + if s < target or (s - target) % 2 != 0: + return 0 + n = (s - target) // 2 + dp = [0] * (n + 1) + dp[0] = 1 + for v in nums: + for j in range(n, v - 1, -1): + dp[j] += dp[j - v] + return dp[-1] +``` + +```java +class Solution { + public int findTargetSumWays(int[] nums, int target) { + int s = 0; + for (int v : nums) { + s += v; + } + if (s < target || (s - target) % 2 != 0) { + return 0; + } + int n = (s - target) / 2; + int[] dp = new int[n + 1]; + dp[0] = 1; + for (int v : nums) { + for (int j = n; j >= v; --j) { + dp[j] += dp[j - v]; } } - - dp[n] + return dp[n]; } } ``` -### **Go** - -```go -func findTargetSumWays(nums []int, target int) int { - s := 0 - for _, v := range nums { - s += v - } - if s < target || (s-target)%2 != 0 { - return 0 - } - m, n := len(nums), (s-target)/2 - dp := make([][]int, m+1) - for i := range dp { - dp[i] = make([]int, n+1) - } - dp[0][0] = 1 - for i := 1; i <= m; i++ { - for j := 0; j <= n; j++ { - dp[i][j] = dp[i-1][j] - if nums[i-1] <= j { - dp[i][j] += dp[i-1][j-nums[i-1]] - } - } - } - return dp[m][n] -} +```cpp +class Solution { +public: + int findTargetSumWays(vector& nums, int target) { + int s = accumulate(nums.begin(), nums.end(), 0); + if (s < target || (s - target) % 2 != 0) return 0; + int n = (s - target) / 2; + vector dp(n + 1); + dp[0] = 1; + for (int& v : nums) + for (int j = n; j >= v; --j) + dp[j] += dp[j - v]; + return dp[n]; + } +}; ``` ```go @@ -334,39 +300,59 @@ func findTargetSumWays(nums []int, target int) int { } ``` -### **JavaScript** +```rust +impl Solution { + #[allow(dead_code)] + pub fn find_target_sum_ways(nums: Vec, target: i32) -> i32 { + let mut sum = 0; + for e in &nums { + sum += *e; + } -```js -/** - * @param {number[]} nums - * @param {number} target - * @return {number} - */ -var findTargetSumWays = function (nums, target) { - let s = 0; - for (let v of nums) { - s += v; - } - if (s < target || (s - target) % 2 != 0) { - return 0; - } - const m = nums.length; - const n = (s - target) / 2; - let dp = new Array(n + 1).fill(0); - dp[0] = 1; - for (let i = 1; i <= m; ++i) { - for (let j = n; j >= nums[i - 1]; --j) { - dp[j] += dp[j - nums[i - 1]]; + if sum < target || (sum - target) % 2 != 0 { + // Just directly return + return 0; } + + let n = ((sum - target) / 2) as usize; + let mut dp: Vec = vec![0; n + 1]; + + // Initialize the dp vector + dp[0] = 1; + + // Begin the actual dp phase + for e in &nums { + for i in (*e as usize..=n).rev() { + dp[i] += dp[i - (*e as usize)]; + } + } + + dp[n] } - return dp[n]; -}; +} ``` -### **...** + -``` +### 方法三 + + + +```python +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + @cache + def dfs(i, t): + if i == n: + if t == target: + return 1 + return 0 + return dfs(i + 1, t + nums[i]) + dfs(i + 1, t - nums[i]) + ans, n = 0, len(nums) + return dfs(0, 0) ``` + + diff --git a/solution/0400-0499/0494.Target Sum/README_EN.md b/solution/0400-0499/0494.Target Sum/README_EN.md index 2456d64c8ce61..14a07171b747c 100644 --- a/solution/0400-0499/0494.Target Sum/README_EN.md +++ b/solution/0400-0499/0494.Target Sum/README_EN.md @@ -47,14 +47,10 @@ ## Solutions -Dynamic programming. - -It is similar to the 0-1 Knapsack problem, except that the index may appear negative, which requires special handling. +### Solution 1 -### **Python3** - ```python class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: @@ -72,40 +68,6 @@ class Solution: return dp[-1][-1] ``` -```python -class Solution: - def findTargetSumWays(self, nums: List[int], target: int) -> int: - s = sum(nums) - if s < target or (s - target) % 2 != 0: - return 0 - n = (s - target) // 2 - dp = [0] * (n + 1) - dp[0] = 1 - for v in nums: - for j in range(n, v - 1, -1): - dp[j] += dp[j - v] - return dp[-1] -``` - -DFS: - -```python -class Solution: - def findTargetSumWays(self, nums: List[int], target: int) -> int: - @cache - def dfs(i, t): - if i == n: - if t == target: - return 1 - return 0 - return dfs(i + 1, t + nums[i]) + dfs(i + 1, t - nums[i]) - - ans, n = 0, len(nums) - return dfs(0, 0) -``` - -### **Java** - ```java class Solution { public int findTargetSumWays(int[] nums, int target) { @@ -133,31 +95,6 @@ class Solution { } ``` -```java -class Solution { - public int findTargetSumWays(int[] nums, int target) { - int s = 0; - for (int v : nums) { - s += v; - } - if (s < target || (s - target) % 2 != 0) { - return 0; - } - int n = (s - target) / 2; - int[] dp = new int[n + 1]; - dp[0] = 1; - for (int v : nums) { - for (int j = n; j >= v; --j) { - dp[j] += dp[j - v]; - } - } - return dp[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -178,25 +115,33 @@ public: }; ``` -```cpp -class Solution { -public: - int findTargetSumWays(vector& nums, int target) { - int s = accumulate(nums.begin(), nums.end(), 0); - if (s < target || (s - target) % 2 != 0) return 0; - int n = (s - target) / 2; - vector dp(n + 1); - dp[0] = 1; - for (int& v : nums) - for (int j = n; j >= v; --j) - dp[j] += dp[j - v]; - return dp[n]; - } -}; +```go +func findTargetSumWays(nums []int, target int) int { + s := 0 + for _, v := range nums { + s += v + } + if s < target || (s-target)%2 != 0 { + return 0 + } + m, n := len(nums), (s-target)/2 + dp := make([][]int, m+1) + for i := range dp { + dp[i] = make([]int, n+1) + } + dp[0][0] = 1 + for i := 1; i <= m; i++ { + for j := 0; j <= n; j++ { + dp[i][j] = dp[i-1][j] + if nums[i-1] <= j { + dp[i][j] += dp[i-1][j-nums[i-1]] + } + } + } + return dp[m][n] +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -236,65 +181,92 @@ impl Solution { } ``` -```rust -impl Solution { - #[allow(dead_code)] - pub fn find_target_sum_ways(nums: Vec, target: i32) -> i32 { - let mut sum = 0; - for e in &nums { - sum += *e; +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var findTargetSumWays = function (nums, target) { + let s = 0; + for (let v of nums) { + s += v; + } + if (s < target || (s - target) % 2 != 0) { + return 0; + } + const m = nums.length; + const n = (s - target) / 2; + let dp = new Array(n + 1).fill(0); + dp[0] = 1; + for (let i = 1; i <= m; ++i) { + for (let j = n; j >= nums[i - 1]; --j) { + dp[j] += dp[j - nums[i - 1]]; } + } + return dp[n]; +}; +``` - if sum < target || (sum - target) % 2 != 0 { - // Just directly return - return 0; - } + - let n = ((sum - target) / 2) as usize; - let mut dp: Vec = vec![0; n + 1]; +### Solution 2 - // Initialize the dp vector - dp[0] = 1; + - // Begin the actual dp phase - for e in &nums { - for i in (*e as usize..=n).rev() { - dp[i] += dp[i - (*e as usize)]; +```python +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + s = sum(nums) + if s < target or (s - target) % 2 != 0: + return 0 + n = (s - target) // 2 + dp = [0] * (n + 1) + dp[0] = 1 + for v in nums: + for j in range(n, v - 1, -1): + dp[j] += dp[j - v] + return dp[-1] +``` + +```java +class Solution { + public int findTargetSumWays(int[] nums, int target) { + int s = 0; + for (int v : nums) { + s += v; + } + if (s < target || (s - target) % 2 != 0) { + return 0; + } + int n = (s - target) / 2; + int[] dp = new int[n + 1]; + dp[0] = 1; + for (int v : nums) { + for (int j = n; j >= v; --j) { + dp[j] += dp[j - v]; } } - - dp[n] + return dp[n]; } } ``` -### **Go** - -```go -func findTargetSumWays(nums []int, target int) int { - s := 0 - for _, v := range nums { - s += v - } - if s < target || (s-target)%2 != 0 { - return 0 - } - m, n := len(nums), (s-target)/2 - dp := make([][]int, m+1) - for i := range dp { - dp[i] = make([]int, n+1) - } - dp[0][0] = 1 - for i := 1; i <= m; i++ { - for j := 0; j <= n; j++ { - dp[i][j] = dp[i-1][j] - if nums[i-1] <= j { - dp[i][j] += dp[i-1][j-nums[i-1]] - } - } - } - return dp[m][n] -} +```cpp +class Solution { +public: + int findTargetSumWays(vector& nums, int target) { + int s = accumulate(nums.begin(), nums.end(), 0); + if (s < target || (s - target) % 2 != 0) return 0; + int n = (s - target) / 2; + vector dp(n + 1); + dp[0] = 1; + for (int& v : nums) + for (int j = n; j >= v; --j) + dp[j] += dp[j - v]; + return dp[n]; + } +}; ``` ```go @@ -318,39 +290,59 @@ func findTargetSumWays(nums []int, target int) int { } ``` -### **JavaScript** +```rust +impl Solution { + #[allow(dead_code)] + pub fn find_target_sum_ways(nums: Vec, target: i32) -> i32 { + let mut sum = 0; + for e in &nums { + sum += *e; + } -```js -/** - * @param {number[]} nums - * @param {number} target - * @return {number} - */ -var findTargetSumWays = function (nums, target) { - let s = 0; - for (let v of nums) { - s += v; - } - if (s < target || (s - target) % 2 != 0) { - return 0; - } - const m = nums.length; - const n = (s - target) / 2; - let dp = new Array(n + 1).fill(0); - dp[0] = 1; - for (let i = 1; i <= m; ++i) { - for (let j = n; j >= nums[i - 1]; --j) { - dp[j] += dp[j - nums[i - 1]]; + if sum < target || (sum - target) % 2 != 0 { + // Just directly return + return 0; } + + let n = ((sum - target) / 2) as usize; + let mut dp: Vec = vec![0; n + 1]; + + // Initialize the dp vector + dp[0] = 1; + + // Begin the actual dp phase + for e in &nums { + for i in (*e as usize..=n).rev() { + dp[i] += dp[i - (*e as usize)]; + } + } + + dp[n] } - return dp[n]; -}; +} ``` -### **...** + -``` +### Solution 3 + + + +```python +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + @cache + def dfs(i, t): + if i == n: + if t == target: + return 1 + return 0 + return dfs(i + 1, t + nums[i]) + dfs(i + 1, t - nums[i]) + ans, n = 0, len(nums) + return dfs(0, 0) ``` + + diff --git a/solution/0400-0499/0495.Teemo Attacking/README.md b/solution/0400-0499/0495.Teemo Attacking/README.md index f192ef9ca9ced..6ecc2194e9f22 100644 --- a/solution/0400-0499/0495.Teemo Attacking/README.md +++ b/solution/0400-0499/0495.Teemo Attacking/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们先考虑最后一次攻击,此次攻击一定可以使得艾希处于中毒状态,所以总中毒时间至少为 `duration`。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int: @@ -75,10 +69,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int findPoisonedDuration(int[] timeSeries, int duration) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +96,6 @@ public: }; ``` -### **Go** - ```go func findPoisonedDuration(timeSeries []int, duration int) (ans int) { ans = duration @@ -120,7 +106,16 @@ func findPoisonedDuration(timeSeries []int, duration int) (ans int) { } ``` -### **C#** +```ts +function findPoisonedDuration(timeSeries: number[], duration: number): number { + const n = timeSeries.length; + let ans = duration; + for (let i = 1; i < n; ++i) { + ans += Math.min(duration, timeSeries[i] - timeSeries[i - 1]); + } + return ans; +} +``` ```cs public class Solution { @@ -135,23 +130,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function findPoisonedDuration(timeSeries: number[], duration: number): number { - const n = timeSeries.length; - let ans = duration; - for (let i = 1; i < n; ++i) { - ans += Math.min(duration, timeSeries[i] - timeSeries[i - 1]); - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0495.Teemo Attacking/README_EN.md b/solution/0400-0499/0495.Teemo Attacking/README_EN.md index 56478f0b74953..78be413ed75ab 100644 --- a/solution/0400-0499/0495.Teemo Attacking/README_EN.md +++ b/solution/0400-0499/0495.Teemo Attacking/README_EN.md @@ -43,9 +43,9 @@ Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int findPoisonedDuration(int[] timeSeries, int duration) { @@ -71,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +83,6 @@ public: }; ``` -### **Go** - ```go func findPoisonedDuration(timeSeries []int, duration int) (ans int) { ans = duration @@ -99,7 +93,16 @@ func findPoisonedDuration(timeSeries []int, duration int) (ans int) { } ``` -### **C#** +```ts +function findPoisonedDuration(timeSeries: number[], duration: number): number { + const n = timeSeries.length; + let ans = duration; + for (let i = 1; i < n; ++i) { + ans += Math.min(duration, timeSeries[i] - timeSeries[i - 1]); + } + return ans; +} +``` ```cs public class Solution { @@ -114,23 +117,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function findPoisonedDuration(timeSeries: number[], duration: number): number { - const n = timeSeries.length; - let ans = duration; - for (let i = 1; i < n; ++i) { - ans += Math.min(duration, timeSeries[i] - timeSeries[i - 1]); - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0496.Next Greater Element I/README.md b/solution/0400-0499/0496.Next Greater Element I/README.md index c29eb0d0a6009..911ccc8bef8d9 100644 --- a/solution/0400-0499/0496.Next Greater Element I/README.md +++ b/solution/0400-0499/0496.Next Greater Element I/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 单调栈常见模型:找出每个数左/右边**离它最近的**且**比它大/小的数**。模板: @@ -73,10 +71,6 @@ for i in range(n): -### **Python3** - - - ```python class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: @@ -89,24 +83,6 @@ class Solution: return [m.get(v, -1) for v in nums1] ``` -```python -class Solution: - def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: - m = {} - stk = [] - for v in nums2[::-1]: - while stk and stk[-1] <= v: - stk.pop() - if stk: - m[v] = stk[-1] - stk.append(v) - return [m.get(x, -1) for x in nums1] -``` - -### **Java** - - - ```java class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { @@ -128,49 +104,82 @@ class Solution { } ``` -```java +```cpp class Solution { - public int[] nextGreaterElement(int[] nums1, int[] nums2) { - Deque stk = new ArrayDeque<>(); - Map m = new HashMap<>(); - for (int i = nums2.length - 1; i >= 0; --i) { - while (!stk.isEmpty() && stk.peek() <= nums2[i]) { +public: + vector nextGreaterElement(vector& nums1, vector& nums2) { + stack stk; + unordered_map m; + for (int& v : nums2) { + while (!stk.empty() && stk.top() < v) { + m[stk.top()] = v; stk.pop(); } - if (!stk.isEmpty()) { - m.put(nums2[i], stk.peek()); - } - stk.push(nums2[i]); - } - int n = nums1.length; - int[] ans = new int[n]; - for (int i = 0; i < n; ++i) { - ans[i] = m.getOrDefault(nums1[i], -1); + stk.push(v); } + vector ans; + for (int& v : nums1) ans.push_back(m.count(v) ? m[v] : -1); return ans; } +}; +``` + +```go +func nextGreaterElement(nums1 []int, nums2 []int) []int { + stk := []int{} + m := map[int]int{} + for _, v := range nums2 { + for len(stk) > 0 && stk[len(stk)-1] < v { + m[stk[len(stk)-1]] = v + stk = stk[:len(stk)-1] + } + stk = append(stk, v) + } + var ans []int + for _, v := range nums1 { + val, ok := m[v] + if !ok { + val = -1 + } + ans = append(ans, val) + } + return ans +} +``` + +```ts +function nextGreaterElement(nums1: number[], nums2: number[]): number[] { + const map = new Map(); + const stack: number[] = [Infinity]; + for (const num of nums2) { + while (num > stack[stack.length - 1]) { + map.set(stack.pop(), num); + } + stack.push(num); + } + return nums1.map(num => map.get(num) || -1); } ``` -### **JavaScript** +```rust +use std::collections::HashMap; -```js -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number[]} - */ -var nextGreaterElement = function (nums1, nums2) { - let stk = []; - let m = {}; - for (let v of nums2) { - while (stk && stk[stk.length - 1] < v) { - m[stk.pop()] = v; +impl Solution { + pub fn next_greater_element(nums1: Vec, nums2: Vec) -> Vec { + let mut map = HashMap::new(); + let mut stack = Vec::new(); + for num in nums2 { + while num > *stack.last().unwrap_or(&i32::MAX) { + map.insert(stack.pop().unwrap(), num); + } + stack.push(num); } - stk.push(v); + nums1 + .iter() + .map(|n| *map.get(n).unwrap_or(&-1)) + .collect::>() } - return nums1.map(e => m[e] || -1); -}; +} ``` ```js @@ -182,12 +191,9 @@ var nextGreaterElement = function (nums1, nums2) { var nextGreaterElement = function (nums1, nums2) { let stk = []; let m = {}; - for (let v of nums2.reverse()) { - while (stk && stk[stk.length - 1] <= v) { - stk.pop(); - } - if (stk) { - m[v] = stk[stk.length - 1]; + for (let v of nums2) { + while (stk && stk[stk.length - 1] < v) { + m[stk.pop()] = v; } stk.push(v); } @@ -195,26 +201,48 @@ var nextGreaterElement = function (nums1, nums2) { }; ``` -### **C++** + -```cpp +### 方法二 + + + +```python +class Solution: + def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: + m = {} + stk = [] + for v in nums2[::-1]: + while stk and stk[-1] <= v: + stk.pop() + if stk: + m[v] = stk[-1] + stk.append(v) + return [m.get(x, -1) for x in nums1] +``` + +```java class Solution { -public: - vector nextGreaterElement(vector& nums1, vector& nums2) { - stack stk; - unordered_map m; - for (int& v : nums2) { - while (!stk.empty() && stk.top() < v) { - m[stk.top()] = v; + public int[] nextGreaterElement(int[] nums1, int[] nums2) { + Deque stk = new ArrayDeque<>(); + Map m = new HashMap<>(); + for (int i = nums2.length - 1; i >= 0; --i) { + while (!stk.isEmpty() && stk.peek() <= nums2[i]) { stk.pop(); } - stk.push(v); + if (!stk.isEmpty()) { + m.put(nums2[i], stk.peek()); + } + stk.push(nums2[i]); + } + int n = nums1.length; + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + ans[i] = m.getOrDefault(nums1[i], -1); } - vector ans; - for (int& v : nums1) ans.push_back(m.count(v) ? m[v] : -1); return ans; } -}; +} ``` ```cpp @@ -235,31 +263,6 @@ public: }; ``` -### **Go** - -```go -func nextGreaterElement(nums1 []int, nums2 []int) []int { - stk := []int{} - m := map[int]int{} - for _, v := range nums2 { - for len(stk) > 0 && stk[len(stk)-1] < v { - m[stk[len(stk)-1]] = v - stk = stk[:len(stk)-1] - } - stk = append(stk, v) - } - var ans []int - for _, v := range nums1 { - val, ok := m[v] - if !ok { - val = -1 - } - ans = append(ans, val) - } - return ans -} -``` - ```go func nextGreaterElement(nums1 []int, nums2 []int) []int { stk := []int{} @@ -285,45 +288,6 @@ func nextGreaterElement(nums1 []int, nums2 []int) []int { } ``` -### **TypeScript** - -```ts -function nextGreaterElement(nums1: number[], nums2: number[]): number[] { - const map = new Map(); - const stack: number[] = [Infinity]; - for (const num of nums2) { - while (num > stack[stack.length - 1]) { - map.set(stack.pop(), num); - } - stack.push(num); - } - return nums1.map(num => map.get(num) || -1); -} -``` - -### **Rust** - -```rust -use std::collections::HashMap; - -impl Solution { - pub fn next_greater_element(nums1: Vec, nums2: Vec) -> Vec { - let mut map = HashMap::new(); - let mut stack = Vec::new(); - for num in nums2 { - while num > *stack.last().unwrap_or(&i32::MAX) { - map.insert(stack.pop().unwrap(), num); - } - stack.push(num); - } - nums1 - .iter() - .map(|n| *map.get(n).unwrap_or(&-1)) - .collect::>() - } -} -``` - ```rust impl Solution { pub fn next_greater_element(nums1: Vec, nums2: Vec) -> Vec { @@ -346,10 +310,28 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var nextGreaterElement = function (nums1, nums2) { + let stk = []; + let m = {}; + for (let v of nums2.reverse()) { + while (stk && stk[stk.length - 1] <= v) { + stk.pop(); + } + if (stk) { + m[v] = stk[stk.length - 1]; + } + stk.push(v); + } + return nums1.map(e => m[e] || -1); +}; ``` + + diff --git a/solution/0400-0499/0496.Next Greater Element I/README_EN.md b/solution/0400-0499/0496.Next Greater Element I/README_EN.md index 5185bb5a92017..5cd2134babe12 100644 --- a/solution/0400-0499/0496.Next Greater Element I/README_EN.md +++ b/solution/0400-0499/0496.Next Greater Element I/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,22 +65,6 @@ class Solution: return [m.get(v, -1) for v in nums1] ``` -```python -class Solution: - def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: - m = {} - stk = [] - for v in nums2[::-1]: - while stk and stk[-1] <= v: - stk.pop() - if stk: - m[v] = stk[-1] - stk.append(v) - return [m.get(x, -1) for x in nums1] -``` - -### **Java** - ```java class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { @@ -102,49 +86,82 @@ class Solution { } ``` -```java +```cpp class Solution { - public int[] nextGreaterElement(int[] nums1, int[] nums2) { - Deque stk = new ArrayDeque<>(); - Map m = new HashMap<>(); - for (int i = nums2.length - 1; i >= 0; --i) { - while (!stk.isEmpty() && stk.peek() <= nums2[i]) { +public: + vector nextGreaterElement(vector& nums1, vector& nums2) { + stack stk; + unordered_map m; + for (int& v : nums2) { + while (!stk.empty() && stk.top() < v) { + m[stk.top()] = v; stk.pop(); } - if (!stk.isEmpty()) { - m.put(nums2[i], stk.peek()); - } - stk.push(nums2[i]); - } - int n = nums1.length; - int[] ans = new int[n]; - for (int i = 0; i < n; ++i) { - ans[i] = m.getOrDefault(nums1[i], -1); + stk.push(v); } + vector ans; + for (int& v : nums1) ans.push_back(m.count(v) ? m[v] : -1); return ans; } +}; +``` + +```go +func nextGreaterElement(nums1 []int, nums2 []int) []int { + stk := []int{} + m := map[int]int{} + for _, v := range nums2 { + for len(stk) > 0 && stk[len(stk)-1] < v { + m[stk[len(stk)-1]] = v + stk = stk[:len(stk)-1] + } + stk = append(stk, v) + } + var ans []int + for _, v := range nums1 { + val, ok := m[v] + if !ok { + val = -1 + } + ans = append(ans, val) + } + return ans +} +``` + +```ts +function nextGreaterElement(nums1: number[], nums2: number[]): number[] { + const map = new Map(); + const stack: number[] = [Infinity]; + for (const num of nums2) { + while (num > stack[stack.length - 1]) { + map.set(stack.pop(), num); + } + stack.push(num); + } + return nums1.map(num => map.get(num) || -1); } ``` -### **JavaScript** +```rust +use std::collections::HashMap; -```js -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number[]} - */ -var nextGreaterElement = function (nums1, nums2) { - let stk = []; - let m = {}; - for (let v of nums2) { - while (stk && stk[stk.length - 1] < v) { - m[stk.pop()] = v; +impl Solution { + pub fn next_greater_element(nums1: Vec, nums2: Vec) -> Vec { + let mut map = HashMap::new(); + let mut stack = Vec::new(); + for num in nums2 { + while num > *stack.last().unwrap_or(&i32::MAX) { + map.insert(stack.pop().unwrap(), num); + } + stack.push(num); } - stk.push(v); + nums1 + .iter() + .map(|n| *map.get(n).unwrap_or(&-1)) + .collect::>() } - return nums1.map(e => m[e] || -1); -}; +} ``` ```js @@ -156,12 +173,9 @@ var nextGreaterElement = function (nums1, nums2) { var nextGreaterElement = function (nums1, nums2) { let stk = []; let m = {}; - for (let v of nums2.reverse()) { - while (stk && stk[stk.length - 1] <= v) { - stk.pop(); - } - if (stk) { - m[v] = stk[stk.length - 1]; + for (let v of nums2) { + while (stk && stk[stk.length - 1] < v) { + m[stk.pop()] = v; } stk.push(v); } @@ -169,26 +183,48 @@ var nextGreaterElement = function (nums1, nums2) { }; ``` -### **C++** + + +### Solution 2 -```cpp + + +```python +class Solution: + def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: + m = {} + stk = [] + for v in nums2[::-1]: + while stk and stk[-1] <= v: + stk.pop() + if stk: + m[v] = stk[-1] + stk.append(v) + return [m.get(x, -1) for x in nums1] +``` + +```java class Solution { -public: - vector nextGreaterElement(vector& nums1, vector& nums2) { - stack stk; - unordered_map m; - for (int& v : nums2) { - while (!stk.empty() && stk.top() < v) { - m[stk.top()] = v; + public int[] nextGreaterElement(int[] nums1, int[] nums2) { + Deque stk = new ArrayDeque<>(); + Map m = new HashMap<>(); + for (int i = nums2.length - 1; i >= 0; --i) { + while (!stk.isEmpty() && stk.peek() <= nums2[i]) { stk.pop(); } - stk.push(v); + if (!stk.isEmpty()) { + m.put(nums2[i], stk.peek()); + } + stk.push(nums2[i]); + } + int n = nums1.length; + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + ans[i] = m.getOrDefault(nums1[i], -1); } - vector ans; - for (int& v : nums1) ans.push_back(m.count(v) ? m[v] : -1); return ans; } -}; +} ``` ```cpp @@ -209,31 +245,6 @@ public: }; ``` -### **Go** - -```go -func nextGreaterElement(nums1 []int, nums2 []int) []int { - stk := []int{} - m := map[int]int{} - for _, v := range nums2 { - for len(stk) > 0 && stk[len(stk)-1] < v { - m[stk[len(stk)-1]] = v - stk = stk[:len(stk)-1] - } - stk = append(stk, v) - } - var ans []int - for _, v := range nums1 { - val, ok := m[v] - if !ok { - val = -1 - } - ans = append(ans, val) - } - return ans -} -``` - ```go func nextGreaterElement(nums1 []int, nums2 []int) []int { stk := []int{} @@ -259,45 +270,6 @@ func nextGreaterElement(nums1 []int, nums2 []int) []int { } ``` -### **TypeScript** - -```ts -function nextGreaterElement(nums1: number[], nums2: number[]): number[] { - const map = new Map(); - const stack: number[] = [Infinity]; - for (const num of nums2) { - while (num > stack[stack.length - 1]) { - map.set(stack.pop(), num); - } - stack.push(num); - } - return nums1.map(num => map.get(num) || -1); -} -``` - -### **Rust** - -```rust -use std::collections::HashMap; - -impl Solution { - pub fn next_greater_element(nums1: Vec, nums2: Vec) -> Vec { - let mut map = HashMap::new(); - let mut stack = Vec::new(); - for num in nums2 { - while num > *stack.last().unwrap_or(&i32::MAX) { - map.insert(stack.pop().unwrap(), num); - } - stack.push(num); - } - nums1 - .iter() - .map(|n| *map.get(n).unwrap_or(&-1)) - .collect::>() - } -} -``` - ```rust impl Solution { pub fn next_greater_element(nums1: Vec, nums2: Vec) -> Vec { @@ -320,10 +292,28 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[]} + */ +var nextGreaterElement = function (nums1, nums2) { + let stk = []; + let m = {}; + for (let v of nums2.reverse()) { + while (stk && stk[stk.length - 1] <= v) { + stk.pop(); + } + if (stk) { + m[v] = stk[stk.length - 1]; + } + stk.push(v); + } + return nums1.map(e => m[e] || -1); +}; ``` + + diff --git a/solution/0400-0499/0497.Random Point in Non-overlapping Rectangles/README.md b/solution/0400-0499/0497.Random Point in Non-overlapping Rectangles/README.md index ffc259e43d488..7f0e42a424a3e 100644 --- a/solution/0400-0499/0497.Random Point in Non-overlapping Rectangles/README.md +++ b/solution/0400-0499/0497.Random Point in Non-overlapping Rectangles/README.md @@ -60,18 +60,12 @@ solution.pick(); // 返回 [0, 0] ## 解法 - - -**方法一:前缀和 + 二分查找** +### 方法一:前缀和 + 二分查找 将矩形面积求前缀和 $s$,然后随机获取到一个面积 $v$,利用二分查找定位到是哪个矩形,然后继续随机获取该矩形的其中一个整数点坐标即可。 -### **Python3** - - - ```python class Solution: def __init__(self, rects: List[List[int]]): @@ -92,10 +86,6 @@ class Solution: # param_1 = obj.pick() ``` -### **Java** - - - ```java class Solution { private int[] s; @@ -136,8 +126,6 @@ class Solution { */ ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +158,6 @@ public: */ ``` -### **Go** - ```go type Solution struct { s []int @@ -205,10 +191,6 @@ func (this *Solution) Pick() []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0497.Random Point in Non-overlapping Rectangles/README_EN.md b/solution/0400-0499/0497.Random Point in Non-overlapping Rectangles/README_EN.md index 3028db5cb3890..fa71c19e9f2a5 100644 --- a/solution/0400-0499/0497.Random Point in Non-overlapping Rectangles/README_EN.md +++ b/solution/0400-0499/0497.Random Point in Non-overlapping Rectangles/README_EN.md @@ -53,9 +53,9 @@ solution.pick(); // return [0, 0] ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: # param_1 = obj.pick() ``` -### **Java** - ```java class Solution { private int[] s; @@ -119,8 +117,6 @@ class Solution { */ ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +149,6 @@ public: */ ``` -### **Go** - ```go type Solution struct { s []int @@ -188,10 +182,6 @@ func (this *Solution) Pick() []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0498.Diagonal Traverse/README.md b/solution/0400-0499/0498.Diagonal Traverse/README.md index 1255d6f6eb27f..2d396800f0c91 100644 --- a/solution/0400-0499/0498.Diagonal Traverse/README.md +++ b/solution/0400-0499/0498.Diagonal Traverse/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:定点遍历** +### 方法一:定点遍历 对于每一轮 $k$,我们固定从右上方开始往左下方遍历,得到 $t$。如果 $k$ 为偶数,再将 $t$ 逆序。然后将 $t$ 添加到结果数组 `ans` 中。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python class Solution: def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]: @@ -73,10 +67,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] findDiagonalOrder(int[][] mat) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func findDiagonalOrder(mat [][]int) []int { m, n := len(mat), len(mat[0]) @@ -160,8 +146,6 @@ func findDiagonalOrder(mat [][]int) []int { } ``` -### **TypeScript** - ```ts function findDiagonalOrder(mat: number[][]): number[] { const res = []; @@ -200,8 +184,6 @@ function findDiagonalOrder(mat: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn find_diagonal_order(mat: Vec>) -> Vec { @@ -236,10 +218,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0498.Diagonal Traverse/README_EN.md b/solution/0400-0499/0498.Diagonal Traverse/README_EN.md index 8c0f02a981fe6..4647dac73d523 100644 --- a/solution/0400-0499/0498.Diagonal Traverse/README_EN.md +++ b/solution/0400-0499/0498.Diagonal Traverse/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] findDiagonalOrder(int[][] mat) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +105,6 @@ public: }; ``` -### **Go** - ```go func findDiagonalOrder(mat [][]int) []int { m, n := len(mat), len(mat[0]) @@ -142,8 +136,6 @@ func findDiagonalOrder(mat [][]int) []int { } ``` -### **TypeScript** - ```ts function findDiagonalOrder(mat: number[][]): number[] { const res = []; @@ -182,8 +174,6 @@ function findDiagonalOrder(mat: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn find_diagonal_order(mat: Vec>) -> Vec { @@ -218,10 +208,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0499.The Maze III/README.md b/solution/0400-0499/0499.The Maze III/README.md index f5991fbefd755..b40f0c44449df 100644 --- a/solution/0400-0499/0499.The Maze III/README.md +++ b/solution/0400-0499/0499.The Maze III/README.md @@ -68,16 +68,10 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS -### **Python3** - - - ```python class Solution: def findShortestWay( @@ -113,10 +107,6 @@ class Solution: return path[rh][ch] or 'impossible' ``` -### **Java** - - - ```java class Solution { public String findShortestWay(int[][] maze, int[] ball, int[] hole) { @@ -163,8 +153,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -205,8 +193,6 @@ public: }; ``` -### **Go** - ```go import "math" @@ -256,10 +242,6 @@ func findShortestWay(maze [][]int, ball []int, hole []int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0400-0499/0499.The Maze III/README_EN.md b/solution/0400-0499/0499.The Maze III/README_EN.md index b41e5107b0cb5..15d6b37e52da9 100644 --- a/solution/0400-0499/0499.The Maze III/README_EN.md +++ b/solution/0400-0499/0499.The Maze III/README_EN.md @@ -59,12 +59,10 @@ Both ways have shortest distance 6, but the first way is lexicographically small ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def findShortestWay( @@ -100,8 +98,6 @@ class Solution: return path[rh][ch] or 'impossible' ``` -### **Java** - ```java class Solution { public String findShortestWay(int[][] maze, int[] ball, int[] hole) { @@ -148,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -190,8 +184,6 @@ public: }; ``` -### **Go** - ```go import "math" @@ -241,10 +233,6 @@ func findShortestWay(maze [][]int, ball []int, hole []int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0500.Keyboard Row/README.md b/solution/0500-0599/0500.Keyboard Row/README.md index 5e387bbe3a906..863336b86614d 100644 --- a/solution/0500-0599/0500.Keyboard Row/README.md +++ b/solution/0500-0599/0500.Keyboard Row/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:字符映射** +### 方法一:字符映射 我们将每个键盘行的字符映射到对应的行数,然后遍历字符串数组,判断每个字符串是否都在同一行即可。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def findWords(self, words: List[str]) -> List[str]: @@ -81,22 +75,6 @@ class Solution: return ans ``` -```python -class Solution: - def findWords(self, words: List[str]) -> List[str]: - ans = [] - s = "12210111011122000010020202" - for w in words: - x = s[ord(w[0].lower()) - ord('a')] - if all(s[ord(c.lower()) - ord('a')] == x for c in w): - ans.append(w) - return ans -``` - -### **Java** - - - ```java class Solution { public String[] findWords(String[] words) { @@ -121,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +123,6 @@ public: }; ``` -### **Go** - ```go func findWords(words []string) (ans []string) { s := "12210111011122000010020202" @@ -169,7 +143,27 @@ func findWords(words []string) (ans []string) { } ``` -### **C#** +```ts +function findWords(words: string[]): string[] { + const s = '12210111011122000010020202'; + const ans: string[] = []; + for (const w of words) { + const t = w.toLowerCase(); + const x = s[t.charCodeAt(0) - 'a'.charCodeAt(0)]; + let ok = true; + for (const c of t) { + if (s[c.charCodeAt(0) - 'a'.charCodeAt(0)] !== x) { + ok = false; + break; + } + } + if (ok) { + ans.push(w); + } + } + return ans; +} +``` ```cs public class Solution { @@ -194,34 +188,24 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function findWords(words: string[]): string[] { - const s = '12210111011122000010020202'; - const ans: string[] = []; - for (const w of words) { - const t = w.toLowerCase(); - const x = s[t.charCodeAt(0) - 'a'.charCodeAt(0)]; - let ok = true; - for (const c of t) { - if (s[c.charCodeAt(0) - 'a'.charCodeAt(0)] !== x) { - ok = false; - break; - } - } - if (ok) { - ans.push(w); - } - } - return ans; -} -``` + -### **...** +### 方法二 -``` + +```python +class Solution: + def findWords(self, words: List[str]) -> List[str]: + ans = [] + s = "12210111011122000010020202" + for w in words: + x = s[ord(w[0].lower()) - ord('a')] + if all(s[ord(c.lower()) - ord('a')] == x for c in w): + ans.append(w) + return ans ``` + + diff --git a/solution/0500-0599/0500.Keyboard Row/README_EN.md b/solution/0500-0599/0500.Keyboard Row/README_EN.md index 0bf2ab2bcee0a..7dc70bb87d4cd 100644 --- a/solution/0500-0599/0500.Keyboard Row/README_EN.md +++ b/solution/0500-0599/0500.Keyboard Row/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,20 +65,6 @@ class Solution: return ans ``` -```python -class Solution: - def findWords(self, words: List[str]) -> List[str]: - ans = [] - s = "12210111011122000010020202" - for w in words: - x = s[ord(w[0].lower()) - ord('a')] - if all(s[ord(c.lower()) - ord('a')] == x for c in w): - ans.append(w) - return ans -``` - -### **Java** - ```java class Solution { public String[] findWords(String[] words) { @@ -103,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +113,6 @@ public: }; ``` -### **Go** - ```go func findWords(words []string) (ans []string) { s := "12210111011122000010020202" @@ -151,7 +133,27 @@ func findWords(words []string) (ans []string) { } ``` -### **C#** +```ts +function findWords(words: string[]): string[] { + const s = '12210111011122000010020202'; + const ans: string[] = []; + for (const w of words) { + const t = w.toLowerCase(); + const x = s[t.charCodeAt(0) - 'a'.charCodeAt(0)]; + let ok = true; + for (const c of t) { + if (s[c.charCodeAt(0) - 'a'.charCodeAt(0)] !== x) { + ok = false; + break; + } + } + if (ok) { + ans.push(w); + } + } + return ans; +} +``` ```cs public class Solution { @@ -176,34 +178,24 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function findWords(words: string[]): string[] { - const s = '12210111011122000010020202'; - const ans: string[] = []; - for (const w of words) { - const t = w.toLowerCase(); - const x = s[t.charCodeAt(0) - 'a'.charCodeAt(0)]; - let ok = true; - for (const c of t) { - if (s[c.charCodeAt(0) - 'a'.charCodeAt(0)] !== x) { - ok = false; - break; - } - } - if (ok) { - ans.push(w); - } - } - return ans; -} -``` + -### **...** +### Solution 2 -``` + +```python +class Solution: + def findWords(self, words: List[str]) -> List[str]: + ans = [] + s = "12210111011122000010020202" + for w in words: + x = s[ord(w[0].lower()) - ord('a')] + if all(s[ord(c.lower()) - ord('a')] == x for c in w): + ans.append(w) + return ans ``` + + diff --git a/solution/0500-0599/0501.Find Mode in Binary Search Tree/README.md b/solution/0500-0599/0501.Find Mode in Binary Search Tree/README.md index 0e5442f76ae3f..c76b267022a9b 100644 --- a/solution/0500-0599/0501.Find Mode in Binary Search Tree/README.md +++ b/solution/0500-0599/0501.Find Mode in Binary Search Tree/README.md @@ -49,16 +49,10 @@ ## 解法 - - -中序遍历。其中,mx 表示最大频数,cnt 表示上一个元素出现的次数,prev 表示上一个元素,ans 表示结果列表。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -184,8 +172,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -224,8 +210,6 @@ func findMode(root *TreeNode) []int { } ``` -### **C#** - ```cs public class Solution { private int mx; @@ -261,10 +245,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0501.Find Mode in Binary Search Tree/README_EN.md b/solution/0500-0599/0501.Find Mode in Binary Search Tree/README_EN.md index 64f6baf11e13d..05122b135dece 100644 --- a/solution/0500-0599/0501.Find Mode in Binary Search Tree/README_EN.md +++ b/solution/0500-0599/0501.Find Mode in Binary Search Tree/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -78,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -130,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -171,8 +167,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -211,8 +205,6 @@ func findMode(root *TreeNode) []int { } ``` -### **C#** - ```cs public class Solution { private int mx; @@ -248,10 +240,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0502.IPO/README.md b/solution/0500-0599/0502.IPO/README.md index 5dfc06bcd4841..a539fff200e00 100644 --- a/solution/0500-0599/0502.IPO/README.md +++ b/solution/0500-0599/0502.IPO/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列(双堆)** +### 方法一:贪心 + 优先队列(双堆) 将每个项目放入优先队列 $q_1$ 中,按照启动资本从小到大排序。如果堆顶元素启动资本不超过当前已有的资金,则循环弹出,放入另一个优先队列 $q_2$ 中,按照纯利润从大到小排序。取出当前利润最大的项目,将其纯利润加入到当前资金中,重复上述操作 $k$ 次。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def findMaximizedCapital( @@ -86,10 +80,6 @@ class Solution: return w ``` -### **Java** - - - ```java class Solution { public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp using pii = pair; @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func findMaximizedCapital(k int, w int, profits []int, capital []int) int { q1 := hp2{} @@ -186,10 +172,6 @@ func (h *hp2) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp2) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0502.IPO/README_EN.md b/solution/0500-0599/0502.IPO/README_EN.md index e117f4084e6d1..021b6d65745e9 100644 --- a/solution/0500-0599/0502.IPO/README_EN.md +++ b/solution/0500-0599/0502.IPO/README_EN.md @@ -49,9 +49,9 @@ Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return w ``` -### **Java** - ```java class Solution { public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) { @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp using pii = pair; @@ -126,8 +122,6 @@ public: }; ``` -### **Go** - ```go func findMaximizedCapital(k int, w int, profits []int, capital []int) int { q1 := hp2{} @@ -169,10 +163,6 @@ func (h *hp2) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp2) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0503.Next Greater Element II/README.md b/solution/0500-0599/0503.Next Greater Element II/README.md index 4098d75952b93..a8f9388bf23bb 100644 --- a/solution/0500-0599/0503.Next Greater Element II/README.md +++ b/solution/0500-0599/0503.Next Greater Element II/README.md @@ -40,16 +40,10 @@ ## 解法 - - -**方法一:单调栈 + 循环数组** +### 方法一:单调栈 + 循环数组 -### **Python3** - - - ```python class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: @@ -63,26 +57,6 @@ class Solution: return ans ``` -```python -class Solution: - def nextGreaterElements(self, nums: List[int]) -> List[int]: - n = len(nums) - ans = [-1] * n - stk = [] - for i in range(n * 2 - 1, -1, -1): - i %= n - while stk and stk[-1] <= nums[i]: - stk.pop() - if stk: - ans[i] = stk[-1] - stk.append(nums[i]) - return ans -``` - -### **Java** - - - ```java class Solution { public int[] nextGreaterElements(int[] nums) { @@ -101,29 +75,60 @@ class Solution { } ``` -```java +```cpp class Solution { - public int[] nextGreaterElements(int[] nums) { - int n = nums.length; - int[] ans = new int[n]; - Arrays.fill(ans, -1); - Deque stk = new ArrayDeque<>(); - for (int i = n * 2 - 1; i >= 0; --i) { - int j = i % n; - while (!stk.isEmpty() && stk.peek() <= nums[j]) { +public: + vector nextGreaterElements(vector& nums) { + int n = nums.size(); + vector ans(n, -1); + stack stk; + for (int i = 0; i < (n << 1); ++i) { + while (!stk.empty() && nums[stk.top()] < nums[i % n]) { + ans[stk.top()] = nums[i % n]; stk.pop(); } - if (!stk.isEmpty()) { - ans[j] = stk.peek(); - } - stk.push(nums[j]); + stk.push(i % n); } return ans; } +}; +``` + +```go +func nextGreaterElements(nums []int) []int { + n := len(nums) + ans := make([]int, n) + for i := range ans { + ans[i] = -1 + } + var stk []int + for i := 0; i < (n << 1); i++ { + for len(stk) > 0 && nums[stk[len(stk)-1]] < nums[i%n] { + ans[stk[len(stk)-1]] = nums[i%n] + stk = stk[:len(stk)-1] + } + stk = append(stk, i%n) + } + return ans } ``` -### **JavaScript** +```ts +function nextGreaterElements(nums: number[]): number[] { + const stack: number[] = [], + len = nums.length; + const res: number[] = new Array(len).fill(-1); + for (let i = 0; i < 2 * len - 1; i++) { + const j = i % len; + while (stack.length !== 0 && nums[stack[stack.length - 1]] < nums[j]) { + res[stack[stack.length - 1]] = nums[j]; + stack.pop(); + } + stack.push(j); + } + return res; +} +``` ```js /** @@ -145,48 +150,48 @@ var nextGreaterElements = function (nums) { }; ``` -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var nextGreaterElements = function (nums) { - const n = nums.length; - let stk = []; - let ans = new Array(n).fill(-1); - for (let i = n * 2 - 1; ~i; --i) { - const j = i % n; - while (stk.length && stk[stk.length - 1] <= nums[j]) { - stk.pop(); - } - if (stk.length) { - ans[j] = stk[stk.length - 1]; - } - stk.push(nums[j]); - } - return ans; -}; -``` + -### **C++** +### 方法二 -```cpp + + +```python +class Solution: + def nextGreaterElements(self, nums: List[int]) -> List[int]: + n = len(nums) + ans = [-1] * n + stk = [] + for i in range(n * 2 - 1, -1, -1): + i %= n + while stk and stk[-1] <= nums[i]: + stk.pop() + if stk: + ans[i] = stk[-1] + stk.append(nums[i]) + return ans +``` + +```java class Solution { -public: - vector nextGreaterElements(vector& nums) { - int n = nums.size(); - vector ans(n, -1); - stack stk; - for (int i = 0; i < (n << 1); ++i) { - while (!stk.empty() && nums[stk.top()] < nums[i % n]) { - ans[stk.top()] = nums[i % n]; + public int[] nextGreaterElements(int[] nums) { + int n = nums.length; + int[] ans = new int[n]; + Arrays.fill(ans, -1); + Deque stk = new ArrayDeque<>(); + for (int i = n * 2 - 1; i >= 0; --i) { + int j = i % n; + while (!stk.isEmpty() && stk.peek() <= nums[j]) { stk.pop(); } - stk.push(i % n); + if (!stk.isEmpty()) { + ans[j] = stk.peek(); + } + stk.push(nums[j]); } return ans; } -}; +} ``` ```cpp @@ -207,27 +212,6 @@ public: }; ``` -### **Go** - -```go -func nextGreaterElements(nums []int) []int { - n := len(nums) - ans := make([]int, n) - for i := range ans { - ans[i] = -1 - } - var stk []int - for i := 0; i < (n << 1); i++ { - for len(stk) > 0 && nums[stk[len(stk)-1]] < nums[i%n] { - ans[stk[len(stk)-1]] = nums[i%n] - stk = stk[:len(stk)-1] - } - stk = append(stk, i%n) - } - return ans -} -``` - ```go func nextGreaterElements(nums []int) []int { n := len(nums) @@ -250,29 +234,29 @@ func nextGreaterElements(nums []int) []int { } ``` -### **TypeScript** - -```ts -function nextGreaterElements(nums: number[]): number[] { - const stack: number[] = [], - len = nums.length; - const res: number[] = new Array(len).fill(-1); - for (let i = 0; i < 2 * len - 1; i++) { - const j = i % len; - while (stack.length !== 0 && nums[stack[stack.length - 1]] < nums[j]) { - res[stack[stack.length - 1]] = nums[j]; - stack.pop(); +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var nextGreaterElements = function (nums) { + const n = nums.length; + let stk = []; + let ans = new Array(n).fill(-1); + for (let i = n * 2 - 1; ~i; --i) { + const j = i % n; + while (stk.length && stk[stk.length - 1] <= nums[j]) { + stk.pop(); } - stack.push(j); + if (stk.length) { + ans[j] = stk[stk.length - 1]; + } + stk.push(nums[j]); } - return res; -} -``` - -### **...** - -``` - + return ans; +}; ``` + + diff --git a/solution/0500-0599/0503.Next Greater Element II/README_EN.md b/solution/0500-0599/0503.Next Greater Element II/README_EN.md index eb7efd9f76617..e2f12372f467f 100644 --- a/solution/0500-0599/0503.Next Greater Element II/README_EN.md +++ b/solution/0500-0599/0503.Next Greater Element II/README_EN.md @@ -36,9 +36,9 @@ The second 1's next greater number needs to search circularly, which is also ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,24 +53,6 @@ class Solution: return ans ``` -```python -class Solution: - def nextGreaterElements(self, nums: List[int]) -> List[int]: - n = len(nums) - ans = [-1] * n - stk = [] - for i in range(n * 2 - 1, -1, -1): - i %= n - while stk and stk[-1] <= nums[i]: - stk.pop() - if stk: - ans[i] = stk[-1] - stk.append(nums[i]) - return ans -``` - -### **Java** - ```java class Solution { public int[] nextGreaterElements(int[] nums) { @@ -89,29 +71,60 @@ class Solution { } ``` -```java +```cpp class Solution { - public int[] nextGreaterElements(int[] nums) { - int n = nums.length; - int[] ans = new int[n]; - Arrays.fill(ans, -1); - Deque stk = new ArrayDeque<>(); - for (int i = n * 2 - 1; i >= 0; --i) { - int j = i % n; - while (!stk.isEmpty() && stk.peek() <= nums[j]) { +public: + vector nextGreaterElements(vector& nums) { + int n = nums.size(); + vector ans(n, -1); + stack stk; + for (int i = 0; i < (n << 1); ++i) { + while (!stk.empty() && nums[stk.top()] < nums[i % n]) { + ans[stk.top()] = nums[i % n]; stk.pop(); } - if (!stk.isEmpty()) { - ans[j] = stk.peek(); - } - stk.push(nums[j]); + stk.push(i % n); } return ans; } +}; +``` + +```go +func nextGreaterElements(nums []int) []int { + n := len(nums) + ans := make([]int, n) + for i := range ans { + ans[i] = -1 + } + var stk []int + for i := 0; i < (n << 1); i++ { + for len(stk) > 0 && nums[stk[len(stk)-1]] < nums[i%n] { + ans[stk[len(stk)-1]] = nums[i%n] + stk = stk[:len(stk)-1] + } + stk = append(stk, i%n) + } + return ans } ``` -### **JavaScript** +```ts +function nextGreaterElements(nums: number[]): number[] { + const stack: number[] = [], + len = nums.length; + const res: number[] = new Array(len).fill(-1); + for (let i = 0; i < 2 * len - 1; i++) { + const j = i % len; + while (stack.length !== 0 && nums[stack[stack.length - 1]] < nums[j]) { + res[stack[stack.length - 1]] = nums[j]; + stack.pop(); + } + stack.push(j); + } + return res; +} +``` ```js /** @@ -133,48 +146,48 @@ var nextGreaterElements = function (nums) { }; ``` -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var nextGreaterElements = function (nums) { - const n = nums.length; - let stk = []; - let ans = new Array(n).fill(-1); - for (let i = n * 2 - 1; ~i; --i) { - const j = i % n; - while (stk.length && stk[stk.length - 1] <= nums[j]) { - stk.pop(); - } - if (stk.length) { - ans[j] = stk[stk.length - 1]; - } - stk.push(nums[j]); - } - return ans; -}; -``` + -### **C++** +### Solution 2 -```cpp + + +```python +class Solution: + def nextGreaterElements(self, nums: List[int]) -> List[int]: + n = len(nums) + ans = [-1] * n + stk = [] + for i in range(n * 2 - 1, -1, -1): + i %= n + while stk and stk[-1] <= nums[i]: + stk.pop() + if stk: + ans[i] = stk[-1] + stk.append(nums[i]) + return ans +``` + +```java class Solution { -public: - vector nextGreaterElements(vector& nums) { - int n = nums.size(); - vector ans(n, -1); - stack stk; - for (int i = 0; i < (n << 1); ++i) { - while (!stk.empty() && nums[stk.top()] < nums[i % n]) { - ans[stk.top()] = nums[i % n]; + public int[] nextGreaterElements(int[] nums) { + int n = nums.length; + int[] ans = new int[n]; + Arrays.fill(ans, -1); + Deque stk = new ArrayDeque<>(); + for (int i = n * 2 - 1; i >= 0; --i) { + int j = i % n; + while (!stk.isEmpty() && stk.peek() <= nums[j]) { stk.pop(); } - stk.push(i % n); + if (!stk.isEmpty()) { + ans[j] = stk.peek(); + } + stk.push(nums[j]); } return ans; } -}; +} ``` ```cpp @@ -195,27 +208,6 @@ public: }; ``` -### **Go** - -```go -func nextGreaterElements(nums []int) []int { - n := len(nums) - ans := make([]int, n) - for i := range ans { - ans[i] = -1 - } - var stk []int - for i := 0; i < (n << 1); i++ { - for len(stk) > 0 && nums[stk[len(stk)-1]] < nums[i%n] { - ans[stk[len(stk)-1]] = nums[i%n] - stk = stk[:len(stk)-1] - } - stk = append(stk, i%n) - } - return ans -} -``` - ```go func nextGreaterElements(nums []int) []int { n := len(nums) @@ -238,29 +230,29 @@ func nextGreaterElements(nums []int) []int { } ``` -### **TypeScript** - -```ts -function nextGreaterElements(nums: number[]): number[] { - const stack: number[] = [], - len = nums.length; - const res: number[] = new Array(len).fill(-1); - for (let i = 0; i < 2 * len - 1; i++) { - const j = i % len; - while (stack.length !== 0 && nums[stack[stack.length - 1]] < nums[j]) { - res[stack[stack.length - 1]] = nums[j]; - stack.pop(); +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var nextGreaterElements = function (nums) { + const n = nums.length; + let stk = []; + let ans = new Array(n).fill(-1); + for (let i = n * 2 - 1; ~i; --i) { + const j = i % n; + while (stk.length && stk[stk.length - 1] <= nums[j]) { + stk.pop(); } - stack.push(j); + if (stk.length) { + ans[j] = stk[stk.length - 1]; + } + stk.push(nums[j]); } - return res; -} -``` - -### **...** - -``` - + return ans; +}; ``` + + diff --git a/solution/0500-0599/0504.Base 7/README.md b/solution/0500-0599/0504.Base 7/README.md index 588f8e43334c6..7189942043093 100644 --- a/solution/0500-0599/0504.Base 7/README.md +++ b/solution/0500-0599/0504.Base 7/README.md @@ -34,9 +34,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们不妨假设 `num` 大于等于 $0$,那么,如果 `num` 等于 $0$,只需要返回 $0$ 即可。否则,我们将 $num$ 模 $7$ 的结果保存起来,最后逆序拼接成字符串即可。 @@ -44,10 +42,6 @@ -### **Python3** - - - ```python class Solution: def convertToBase7(self, num: int) -> str: @@ -62,10 +56,6 @@ class Solution: return ''.join(ans[::-1]) ``` -### **Java** - - - ```java class Solution { public String convertToBase7(int num) { @@ -85,7 +75,38 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + string convertToBase7(int num) { + if (num == 0) return "0"; + if (num < 0) return "-" + convertToBase7(-num); + string ans = ""; + while (num) { + ans = to_string(num % 7) + ans; + num /= 7; + } + return ans; + } +}; +``` + +```go +func convertToBase7(num int) string { + if num == 0 { + return "0" + } + if num < 0 { + return "-" + convertToBase7(-num) + } + ans := []byte{} + for num != 0 { + ans = append([]byte{'0' + byte(num%7)}, ans...) + num /= 7 + } + return string(ans) +} +``` ```ts function convertToBase7(num: number): string { @@ -106,8 +127,6 @@ function convertToBase7(num: number): string { } ``` -### **Rust** - ```rust impl Solution { pub fn convert_to_base7(mut num: i32) -> String { @@ -131,47 +150,6 @@ impl Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string convertToBase7(int num) { - if (num == 0) return "0"; - if (num < 0) return "-" + convertToBase7(-num); - string ans = ""; - while (num) { - ans = to_string(num % 7) + ans; - num /= 7; - } - return ans; - } -}; -``` - -### **Go** - -```go -func convertToBase7(num int) string { - if num == 0 { - return "0" - } - if num < 0 { - return "-" + convertToBase7(-num) - } - ans := []byte{} - for num != 0 { - ans = append([]byte{'0' + byte(num%7)}, ans...) - num /= 7 - } - return string(ans) -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0504.Base 7/README_EN.md b/solution/0500-0599/0504.Base 7/README_EN.md index 318f11545c1f6..103a82e886a04 100644 --- a/solution/0500-0599/0504.Base 7/README_EN.md +++ b/solution/0500-0599/0504.Base 7/README_EN.md @@ -23,9 +23,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -41,8 +41,6 @@ class Solution: return ''.join(ans[::-1]) ``` -### **Java** - ```java class Solution { public String convertToBase7(int num) { @@ -62,7 +60,38 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + string convertToBase7(int num) { + if (num == 0) return "0"; + if (num < 0) return "-" + convertToBase7(-num); + string ans = ""; + while (num) { + ans = to_string(num % 7) + ans; + num /= 7; + } + return ans; + } +}; +``` + +```go +func convertToBase7(num int) string { + if num == 0 { + return "0" + } + if num < 0 { + return "-" + convertToBase7(-num) + } + ans := []byte{} + for num != 0 { + ans = append([]byte{'0' + byte(num%7)}, ans...) + num /= 7 + } + return string(ans) +} +``` ```ts function convertToBase7(num: number): string { @@ -83,8 +112,6 @@ function convertToBase7(num: number): string { } ``` -### **Rust** - ```rust impl Solution { pub fn convert_to_base7(mut num: i32) -> String { @@ -108,47 +135,6 @@ impl Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string convertToBase7(int num) { - if (num == 0) return "0"; - if (num < 0) return "-" + convertToBase7(-num); - string ans = ""; - while (num) { - ans = to_string(num % 7) + ans; - num /= 7; - } - return ans; - } -}; -``` - -### **Go** - -```go -func convertToBase7(num int) string { - if num == 0 { - return "0" - } - if num < 0 { - return "-" + convertToBase7(-num) - } - ans := []byte{} - for num != 0 { - ans = append([]byte{'0' + byte(num%7)}, ans...) - num /= 7 - } - return string(ans) -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0505.The Maze II/README.md b/solution/0500-0599/0505.The Maze II/README.md index df846c6f9f3e2..f374181c9003f 100644 --- a/solution/0500-0599/0505.The Maze II/README.md +++ b/solution/0500-0599/0505.The Maze II/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们定义一个二维数组 $dist$,其中 $dist[i][j]$ 表示从起始位置到达 $(i,j)$ 的最短路径长度。初始时,$dist$ 中的所有元素都被初始化为一个很大的数,除了起始位置,因为起始位置到自身的距离是 $0$。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def shortestDistance( @@ -108,10 +102,6 @@ class Solution: return -1 if dist[di][dj] == inf else dist[di][dj] ``` -### **Java** - - - ```java class Solution { public int shortestDistance(int[][] maze, int[] start, int[] destination) { @@ -150,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -187,8 +175,6 @@ public: }; ``` -### **Go** - ```go func shortestDistance(maze [][]int, start []int, destination []int) int { m, n := len(maze), len(maze[0]) @@ -227,8 +213,6 @@ func shortestDistance(maze [][]int, start []int, destination []int) int { } ``` -### **TypeScript** - ```ts function shortestDistance(maze: number[][], start: number[], destination: number[]): number { const m = maze.length; @@ -261,10 +245,6 @@ function shortestDistance(maze: number[][], start: number[], destination: number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0505.The Maze II/README_EN.md b/solution/0500-0599/0505.The Maze II/README_EN.md index 44029a84ff950..7953a6beea707 100644 --- a/solution/0500-0599/0505.The Maze II/README_EN.md +++ b/solution/0500-0599/0505.The Maze II/README_EN.md @@ -55,12 +55,10 @@ The length of the path is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12. ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def shortestDistance( @@ -85,8 +83,6 @@ class Solution: return -1 if dist[di][dj] == inf else dist[di][dj] ``` -### **Java** - ```java class Solution { public int shortestDistance(int[][] maze, int[] start, int[] destination) { @@ -125,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +156,6 @@ public: }; ``` -### **Go** - ```go func shortestDistance(maze [][]int, start []int, destination []int) int { m, n := len(maze), len(maze[0]) @@ -202,8 +194,6 @@ func shortestDistance(maze [][]int, start []int, destination []int) int { } ``` -### **TypeScript** - ```ts function shortestDistance(maze: number[][], start: number[], destination: number[]): number { const m = maze.length; @@ -236,10 +226,6 @@ function shortestDistance(maze: number[][], start: number[], destination: number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0506.Relative Ranks/README.md b/solution/0500-0599/0506.Relative Ranks/README.md index 6ab63de5bd38d..62675399b16dd 100644 --- a/solution/0500-0599/0506.Relative Ranks/README.md +++ b/solution/0500-0599/0506.Relative Ranks/README.md @@ -49,14 +49,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findRelativeRanks(self, score: List[int]) -> List[str]: @@ -70,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public String[] findRelativeRanks(int[] score) { @@ -93,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +104,6 @@ public: }; ``` -### **Go** - ```go func findRelativeRanks(score []int) []string { n := len(score) @@ -139,10 +127,6 @@ func findRelativeRanks(score []int) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0506.Relative Ranks/README_EN.md b/solution/0500-0599/0506.Relative Ranks/README_EN.md index 56c19f3cc469a..103f7e608ba29 100644 --- a/solution/0500-0599/0506.Relative Ranks/README_EN.md +++ b/solution/0500-0599/0506.Relative Ranks/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public String[] findRelativeRanks(int[] score) { @@ -84,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +101,6 @@ public: }; ``` -### **Go** - ```go func findRelativeRanks(score []int) []string { n := len(score) @@ -130,10 +124,6 @@ func findRelativeRanks(score []int) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0507.Perfect Number/README.md b/solution/0500-0599/0507.Perfect Number/README.md index b917116e6a76c..a7e32acb8ce58 100644 --- a/solution/0500-0599/0507.Perfect Number/README.md +++ b/solution/0500-0599/0507.Perfect Number/README.md @@ -37,14 +37,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def checkPerfectNumber(self, num: int) -> bool: @@ -60,10 +56,6 @@ class Solution: return s == num ``` -### **Java** - - - ```java class Solution { @@ -85,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +94,6 @@ public: }; ``` -### **Go** - ```go func checkPerfectNumber(num int) bool { if num == 1 { @@ -124,10 +112,6 @@ func checkPerfectNumber(num int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0507.Perfect Number/README_EN.md b/solution/0500-0599/0507.Perfect Number/README_EN.md index a956aeb8c95bd..749c6ddcabade 100644 --- a/solution/0500-0599/0507.Perfect Number/README_EN.md +++ b/solution/0500-0599/0507.Perfect Number/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return s == num ``` -### **Java** - ```java class Solution { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +91,6 @@ public: }; ``` -### **Go** - ```go func checkPerfectNumber(num int) bool { if num == 1 { @@ -115,10 +109,6 @@ func checkPerfectNumber(num int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0508.Most Frequent Subtree Sum/README.md b/solution/0500-0599/0508.Most Frequent Subtree Sum/README.md index cd37e6d73098b..3f54ae34e17f5 100644 --- a/solution/0500-0599/0508.Most Frequent Subtree Sum/README.md +++ b/solution/0500-0599/0508.Most Frequent Subtree Sum/README.md @@ -41,16 +41,10 @@ ## 解法 - - -后序遍历获取每个子树元素和,同时用哈希表记录每个子树元素和出现的次数,以及最大的次数 mx。最后判断哈希表中出现次数为 mx 的,获取对应的子树元素,组成结果列表 ans。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -74,10 +68,6 @@ class Solution: return [k for k, v in counter.items() if v == mx] ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -127,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -166,8 +154,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -203,8 +189,6 @@ func findFrequentTreeSum(root *TreeNode) []int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -244,8 +228,6 @@ function findFrequentTreeSum(root: TreeNode | null): number[] { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -299,10 +281,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0508.Most Frequent Subtree Sum/README_EN.md b/solution/0500-0599/0508.Most Frequent Subtree Sum/README_EN.md index 171a92c0047e3..8ad61861bae11 100644 --- a/solution/0500-0599/0508.Most Frequent Subtree Sum/README_EN.md +++ b/solution/0500-0599/0508.Most Frequent Subtree Sum/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -60,8 +60,6 @@ class Solution: return [k for k, v in counter.items() if v == mx] ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -150,8 +146,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -187,8 +181,6 @@ func findFrequentTreeSum(root *TreeNode) []int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -228,8 +220,6 @@ function findFrequentTreeSum(root: TreeNode | null): number[] { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -283,10 +273,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0509.Fibonacci Number/README.md b/solution/0500-0599/0509.Fibonacci Number/README.md index 7c9e545bc55cf..18558393948b3 100644 --- a/solution/0500-0599/0509.Fibonacci Number/README.md +++ b/solution/0500-0599/0509.Fibonacci Number/README.md @@ -51,14 +51,10 @@ F(n) = F(n - 1) + F(n - 2),其中 n > 1 ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def fib(self, n: int) -> int: @@ -68,10 +64,6 @@ class Solution: return a ``` -### **Java** - - - ```java class Solution { public int fib(int n) { @@ -86,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +93,6 @@ public: }; ``` -### **Go** - ```go func fib(n int) int { a, b := 0, 1 @@ -115,27 +103,6 @@ func fib(n int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number} - */ -var fib = function (n) { - let a = 0; - let b = 1; - while (n--) { - const c = a + b; - a = b; - b = c; - } - return a; -}; -``` - -### **TypeScript** - ```ts function fib(n: number): number { let a = 0; @@ -147,17 +114,6 @@ function fib(n: number): number { } ``` -```ts -function fib(n: number): number { - if (n < 2) { - return n; - } - return fib(n - 1) + fib(n - 2); -} -``` - -### **Rust** - ```rust impl Solution { pub fn fib(n: i32) -> i32 { @@ -173,19 +129,23 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn fib(n: i32) -> i32 { - if n < 2 { - return n; - } - Self::fib(n - 1) + Self::fib(n - 2) +```js +/** + * @param {number} n + * @return {number} + */ +var fib = function (n) { + let a = 0; + let b = 1; + while (n--) { + const c = a + b; + a = b; + b = c; } -} + return a; +}; ``` -### **PHP** - ```php class Solution { /** @@ -205,10 +165,32 @@ class Solution { } ``` -### **...** + + +### 方法二 + + +```ts +function fib(n: number): number { + if (n < 2) { + return n; + } + return fib(n - 1) + fib(n - 2); +} ``` +```rust +impl Solution { + pub fn fib(n: i32) -> i32 { + if n < 2 { + return n; + } + Self::fib(n - 1) + Self::fib(n - 2) + } +} ``` + + diff --git a/solution/0500-0599/0509.Fibonacci Number/README_EN.md b/solution/0500-0599/0509.Fibonacci Number/README_EN.md index add12450d3c03..8da7e3e16a335 100644 --- a/solution/0500-0599/0509.Fibonacci Number/README_EN.md +++ b/solution/0500-0599/0509.Fibonacci Number/README_EN.md @@ -47,9 +47,9 @@ F(n) = F(n - 1) + F(n - 2), for n > 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return a ``` -### **Java** - ```java class Solution { public int fib(int n) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +89,6 @@ public: }; ``` -### **Go** - ```go func fib(n int) int { a, b := 0, 1 @@ -105,27 +99,6 @@ func fib(n int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number} - */ -var fib = function (n) { - let a = 0; - let b = 1; - while (n--) { - const c = a + b; - a = b; - b = c; - } - return a; -}; -``` - -### **TypeScript** - ```ts function fib(n: number): number { let a = 0; @@ -137,17 +110,6 @@ function fib(n: number): number { } ``` -```ts -function fib(n: number): number { - if (n < 2) { - return n; - } - return fib(n - 1) + fib(n - 2); -} -``` - -### **Rust** - ```rust impl Solution { pub fn fib(n: i32) -> i32 { @@ -163,19 +125,23 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn fib(n: i32) -> i32 { - if n < 2 { - return n; - } - Self::fib(n - 1) + Self::fib(n - 2) +```js +/** + * @param {number} n + * @return {number} + */ +var fib = function (n) { + let a = 0; + let b = 1; + while (n--) { + const c = a + b; + a = b; + b = c; } -} + return a; +}; ``` -### **PHP** - ```php class Solution { /** @@ -195,10 +161,32 @@ class Solution { } ``` -### **...** + + +### Solution 2 + + +```ts +function fib(n: number): number { + if (n < 2) { + return n; + } + return fib(n - 1) + fib(n - 2); +} ``` +```rust +impl Solution { + pub fn fib(n: i32) -> i32 { + if n < 2 { + return n; + } + Self::fib(n - 1) + Self::fib(n - 2) + } +} ``` + + diff --git a/solution/0500-0599/0510.Inorder Successor in BST II/README.md b/solution/0500-0599/0510.Inorder Successor in BST II/README.md index 8fc02113aee40..8503f21314b0b 100644 --- a/solution/0500-0599/0510.Inorder Successor in BST II/README.md +++ b/solution/0500-0599/0510.Inorder Successor in BST II/README.md @@ -83,19 +83,10 @@ class Node { ## 解法 - - -判断 node 是否有右子树, - -- 若有,找到右子树的最左节点返回 -- 若没有,则向上寻找父节点,直到节点等于父节点的左孩子,返回父节点 +### 方法一 -### **Python3** - - - ```python """ # Definition for a Node. @@ -120,10 +111,6 @@ class Solution: return node.parent ``` -### **Java** - - - ```java /* // Definition for a Node. @@ -153,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -181,8 +166,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for Node. @@ -209,8 +192,6 @@ func inorderSuccessor(node *Node) *Node { } ``` -### **JavaScript** - ```js /** * // Definition for a Node. @@ -237,10 +218,6 @@ var inorderSuccessor = function (node) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0510.Inorder Successor in BST II/README_EN.md b/solution/0500-0599/0510.Inorder Successor in BST II/README_EN.md index bedb6d7bd5bec..639c357ff10f8 100644 --- a/solution/0500-0599/0510.Inorder Successor in BST II/README_EN.md +++ b/solution/0500-0599/0510.Inorder Successor in BST II/README_EN.md @@ -50,9 +50,9 @@ class Node { ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -78,8 +78,6 @@ class Solution: return node.parent ``` -### **Java** - ```java /* // Definition for a Node. @@ -109,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -137,8 +133,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for Node. @@ -165,8 +159,6 @@ func inorderSuccessor(node *Node) *Node { } ``` -### **JavaScript** - ```js /** * // Definition for a Node. @@ -193,10 +185,6 @@ var inorderSuccessor = function (node) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0511.Game Play Analysis I/README.md b/solution/0500-0599/0511.Game Play Analysis I/README.md index 40d61c0867d12..84da9bc038a63 100644 --- a/solution/0500-0599/0511.Game Play Analysis I/README.md +++ b/solution/0500-0599/0511.Game Play Analysis I/README.md @@ -52,25 +52,12 @@ Result 表: ## 解法 - - -**方法一:分组求最小值** +### 方法一:分组求最小值 我们可以用 `GROUP BY` 对 `player_id` 进行分组,然后取每一组中最小的 `event_date` 作为玩家第一次登录平台的日期。 -### **SQL** - -```sql -# Write your MySQL query statement below -SELECT player_id, MIN(event_date) AS first_login -FROM Activity -GROUP BY 1; -``` - -### **Pandas** - ```python import pandas as pd @@ -83,4 +70,13 @@ def game_analysis(activity: pd.DataFrame) -> pd.DataFrame: ) ``` +```sql +# Write your MySQL query statement below +SELECT player_id, MIN(event_date) AS first_login +FROM Activity +GROUP BY 1; +``` + + + diff --git a/solution/0500-0599/0511.Game Play Analysis I/README_EN.md b/solution/0500-0599/0511.Game Play Analysis I/README_EN.md index 76aff9bc421c6..79d6fd660c35d 100644 --- a/solution/0500-0599/0511.Game Play Analysis I/README_EN.md +++ b/solution/0500-0599/0511.Game Play Analysis I/README_EN.md @@ -55,23 +55,12 @@ Activity table: ## Solutions -**Solution 1: Group By + Min Function** +### Solution 1: Group By + Min Function We can use `GROUP BY` to group the `player_id` and then take the minimum `event_date` in each group as the date when the player first logged into the platform. -### **SQL** - -```sql -# Write your MySQL query statement below -SELECT player_id, MIN(event_date) AS first_login -FROM Activity -GROUP BY 1; -``` - -### **Pandas** - ```python import pandas as pd @@ -84,4 +73,13 @@ def game_analysis(activity: pd.DataFrame) -> pd.DataFrame: ) ``` +```sql +# Write your MySQL query statement below +SELECT player_id, MIN(event_date) AS first_login +FROM Activity +GROUP BY 1; +``` + + + diff --git a/solution/0500-0599/0512.Game Play Analysis II/README.md b/solution/0500-0599/0512.Game Play Analysis II/README.md index c25d80bc7d23c..40263ca9e6b4e 100644 --- a/solution/0500-0599/0512.Game Play Analysis II/README.md +++ b/solution/0500-0599/0512.Game Play Analysis II/README.md @@ -53,20 +53,12 @@ Activity table: ## 解法 - - -**方法一:子查询** +### 方法一:子查询 我们可以使用 `GROUP BY` 和 `MIN` 函数来找到每个玩家的第一次登录日期,然后使用联合键子查询来找到每个玩家的第一次登录设备。 -**方法二:窗口函数** - -我们可以使用窗口函数 `rank()`,它可以为每个玩家的每个登录日期分配一个排名,然后我们可以选择排名为 $1$ 的行。 - -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -83,6 +75,14 @@ WHERE ); ``` + + +### 方法二:窗口函数 + +我们可以使用窗口函数 `rank()`,它可以为每个玩家的每个登录日期分配一个排名,然后我们可以选择排名为 $1$ 的行。 + + + ```sql # Write your MySQL query statement below WITH @@ -101,3 +101,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/0500-0599/0512.Game Play Analysis II/README_EN.md b/solution/0500-0599/0512.Game Play Analysis II/README_EN.md index 9ad78ecbb3aea..b1badfcf647c7 100644 --- a/solution/0500-0599/0512.Game Play Analysis II/README_EN.md +++ b/solution/0500-0599/0512.Game Play Analysis II/README_EN.md @@ -55,18 +55,12 @@ Activity table: ## Solutions -**Solution 1: Subquery** +### Solution 1: Subquery We can use `GROUP BY` and `MIN` functions to find the first login date for each player, and then use a subquery with a composite key to find the first login device for each player. -**Solution 2: Window Function** - -We can use the window function `rank()`, which assigns a rank to each login date for each player, and then select the rows with a rank of $1$. - -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -83,6 +77,14 @@ WHERE ); ``` + + +### Solution 2: Window Function + +We can use the window function `rank()`, which assigns a rank to each login date for each player, and then select the rows with a rank of $1$. + + + ```sql # Write your MySQL query statement below WITH @@ -101,3 +103,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/0500-0599/0513.Find Bottom Left Tree Value/README.md b/solution/0500-0599/0513.Find Bottom Left Tree Value/README.md index 4c1b782aba420..878773765e79d 100644 --- a/solution/0500-0599/0513.Find Bottom Left Tree Value/README.md +++ b/solution/0500-0599/0513.Find Bottom Left Tree Value/README.md @@ -41,22 +41,12 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS BFS 找最后一层第一个节点。 -**方法二:DFS** - -DFS 先序遍历,找深度最大的,且第一次被遍历到的节点。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -79,34 +69,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: - def dfs(root, curr): - if root is None: - return - dfs(root.left, curr + 1) - dfs(root.right, curr + 1) - nonlocal ans, mx - if mx < curr: - mx = curr - ans = root.val - - ans = mx = 0 - dfs(root, 1) - return ans -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -145,47 +107,66 @@ class Solution { } ``` -```java +```cpp /** * Definition for a binary tree node. - * public class TreeNode { + * struct TreeNode { * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; */ class Solution { - private int ans = 0; - private int mx = 0; - - public int findBottomLeftValue(TreeNode root) { - dfs(root, 1); +public: + int findBottomLeftValue(TreeNode* root) { + queue q{{root}}; + int ans = 0; + while (!q.empty()) { + ans = q.front()->val; + for (int i = q.size(); i; --i) { + TreeNode* node = q.front(); + q.pop(); + if (node->left) q.push(node->left); + if (node->right) q.push(node->right); + } + } return ans; } +}; +``` - private void dfs(TreeNode root, int curr) { - if (root == null) { - return; - } - dfs(root.left, curr + 1); - dfs(root.right, curr + 1); - if (mx < curr) { - mx = curr; - ans = root.val; - } - } +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func findBottomLeftValue(root *TreeNode) int { + q := []*TreeNode{root} + ans := 0 + for len(q) > 0 { + ans = q[0].Val + for i := len(q); i > 0; i-- { + node := q[0] + q = q[1:] + if node.Left != nil { + q = append(q, node.Left) + } + if node.Right != nil { + q = append(q, node.Right) + } + } + } + return ans } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -220,27 +201,110 @@ function findBottomLeftValue(root: TreeNode | null): number { } ``` -```ts +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +use std::collections::VecDeque; +impl Solution { + pub fn find_bottom_left_value(root: Option>>) -> i32 { + let mut queue = VecDeque::new(); + queue.push_back(root); + let mut res = 0; + while !queue.is_empty() { + res = queue.front().unwrap().as_ref().unwrap().borrow_mut().val; + for _ in 0..queue.len() { + let node = queue.pop_front().unwrap(); + let mut node = node.as_ref().unwrap().borrow_mut(); + if node.left.is_some() { + queue.push_back(node.left.take()); + } + if node.right.is_some() { + queue.push_back(node.right.take()); + } + } + } + res + } +} +``` + + + +### 方法二:DFS + +DFS 先序遍历,找深度最大的,且第一次被遍历到的节点。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: + def dfs(root, curr): + if root is None: + return + dfs(root.left, curr + 1) + dfs(root.right, curr + 1) + nonlocal ans, mx + if mx < curr: + mx = curr + ans = root.val + + ans = mx = 0 + dfs(root, 1) + return ans +``` + +```java /** * 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) + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; * } * } */ +class Solution { + private int ans = 0; + private int mx = 0; -function findBottomLeftValue(root: TreeNode | null): number { - let mx = 0; - let ans = 0; + public int findBottomLeftValue(TreeNode root) { + dfs(root, 1); + return ans; + } - function dfs(root, curr) { - if (!root) { + private void dfs(TreeNode root, int curr) { + if (root == null) { return; } dfs(root.left, curr + 1); @@ -250,44 +314,9 @@ function findBottomLeftValue(root: TreeNode | null): number { ans = root.val; } } - dfs(root, 1); - return ans; } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int findBottomLeftValue(TreeNode* root) { - queue q{{root}}; - int ans = 0; - while (!q.empty()) { - ans = q.front()->val; - for (int i = q.size(); i; --i) { - TreeNode* node = q.front(); - q.pop(); - if (node->left) q.push(node->left); - if (node->right) q.push(node->right); - } - } - return ans; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -321,37 +350,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func findBottomLeftValue(root *TreeNode) int { - q := []*TreeNode{root} - ans := 0 - for len(q) > 0 { - ans = q[0].Val - for i := len(q); i > 0; i-- { - node := q[0] - q = q[1:] - if node.Left != nil { - q = append(q, node.Left) - } - if node.Right != nil { - q = append(q, node.Right) - } - } - } - return ans -} -``` - ```go /** * Definition for a binary tree node. @@ -380,50 +378,38 @@ func findBottomLeftValue(root *TreeNode) int { } ``` -### **Rust** +```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) + * } + * } + */ -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -use std::collections::VecDeque; -impl Solution { - pub fn find_bottom_left_value(root: Option>>) -> i32 { - let mut queue = VecDeque::new(); - queue.push_back(root); - let mut res = 0; - while !queue.is_empty() { - res = queue.front().unwrap().as_ref().unwrap().borrow_mut().val; - for _ in 0..queue.len() { - let node = queue.pop_front().unwrap(); - let mut node = node.as_ref().unwrap().borrow_mut(); - if node.left.is_some() { - queue.push_back(node.left.take()); - } - if node.right.is_some() { - queue.push_back(node.right.take()); - } - } +function findBottomLeftValue(root: TreeNode | null): number { + let mx = 0; + let ans = 0; + + function dfs(root, curr) { + if (!root) { + return; + } + dfs(root.left, curr + 1); + dfs(root.right, curr + 1); + if (mx < curr) { + mx = curr; + ans = root.val; } - res } + dfs(root, 1); + return ans; } ``` @@ -472,10 +458,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0513.Find Bottom Left Tree Value/README_EN.md b/solution/0500-0599/0513.Find Bottom Left Tree Value/README_EN.md index 8f59443bf30dc..069872cf490e9 100644 --- a/solution/0500-0599/0513.Find Bottom Left Tree Value/README_EN.md +++ b/solution/0500-0599/0513.Find Bottom Left Tree Value/README_EN.md @@ -31,9 +31,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -57,32 +57,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: - def dfs(root, curr): - if root is None: - return - dfs(root.left, curr + 1) - dfs(root.right, curr + 1) - nonlocal ans, mx - if mx < curr: - mx = curr - ans = root.val - - ans = mx = 0 - dfs(root, 1) - return ans -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -121,47 +95,66 @@ class Solution { } ``` -```java +```cpp /** * Definition for a binary tree node. - * public class TreeNode { + * struct TreeNode { * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; */ class Solution { - private int ans = 0; - private int mx = 0; - - public int findBottomLeftValue(TreeNode root) { - dfs(root, 1); +public: + int findBottomLeftValue(TreeNode* root) { + queue q{{root}}; + int ans = 0; + while (!q.empty()) { + ans = q.front()->val; + for (int i = q.size(); i; --i) { + TreeNode* node = q.front(); + q.pop(); + if (node->left) q.push(node->left); + if (node->right) q.push(node->right); + } + } return ans; } +}; +``` - private void dfs(TreeNode root, int curr) { - if (root == null) { - return; - } - dfs(root.left, curr + 1); - dfs(root.right, curr + 1); - if (mx < curr) { - mx = curr; - ans = root.val; - } - } +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func findBottomLeftValue(root *TreeNode) int { + q := []*TreeNode{root} + ans := 0 + for len(q) > 0 { + ans = q[0].Val + for i := len(q); i > 0; i-- { + node := q[0] + q = q[1:] + if node.Left != nil { + q = append(q, node.Left) + } + if node.Right != nil { + q = append(q, node.Right) + } + } + } + return ans } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -196,27 +189,108 @@ function findBottomLeftValue(root: TreeNode | null): number { } ``` -```ts +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +use std::collections::VecDeque; +impl Solution { + pub fn find_bottom_left_value(root: Option>>) -> i32 { + let mut queue = VecDeque::new(); + queue.push_back(root); + let mut res = 0; + while !queue.is_empty() { + res = queue.front().unwrap().as_ref().unwrap().borrow_mut().val; + for _ in 0..queue.len() { + let node = queue.pop_front().unwrap(); + let mut node = node.as_ref().unwrap().borrow_mut(); + if node.left.is_some() { + queue.push_back(node.left.take()); + } + if node.right.is_some() { + queue.push_back(node.right.take()); + } + } + } + res + } +} +``` + + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: + def dfs(root, curr): + if root is None: + return + dfs(root.left, curr + 1) + dfs(root.right, curr + 1) + nonlocal ans, mx + if mx < curr: + mx = curr + ans = root.val + + ans = mx = 0 + dfs(root, 1) + return ans +``` + +```java /** * 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) + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; * } * } */ +class Solution { + private int ans = 0; + private int mx = 0; -function findBottomLeftValue(root: TreeNode | null): number { - let mx = 0; - let ans = 0; + public int findBottomLeftValue(TreeNode root) { + dfs(root, 1); + return ans; + } - function dfs(root, curr) { - if (!root) { + private void dfs(TreeNode root, int curr) { + if (root == null) { return; } dfs(root.left, curr + 1); @@ -226,44 +300,9 @@ function findBottomLeftValue(root: TreeNode | null): number { ans = root.val; } } - dfs(root, 1); - return ans; } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int findBottomLeftValue(TreeNode* root) { - queue q{{root}}; - int ans = 0; - while (!q.empty()) { - ans = q.front()->val; - for (int i = q.size(); i; --i) { - TreeNode* node = q.front(); - q.pop(); - if (node->left) q.push(node->left); - if (node->right) q.push(node->right); - } - } - return ans; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -297,37 +336,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func findBottomLeftValue(root *TreeNode) int { - q := []*TreeNode{root} - ans := 0 - for len(q) > 0 { - ans = q[0].Val - for i := len(q); i > 0; i-- { - node := q[0] - q = q[1:] - if node.Left != nil { - q = append(q, node.Left) - } - if node.Right != nil { - q = append(q, node.Right) - } - } - } - return ans -} -``` - ```go /** * Definition for a binary tree node. @@ -356,50 +364,38 @@ func findBottomLeftValue(root *TreeNode) int { } ``` -### **Rust** +```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) + * } + * } + */ -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -use std::collections::VecDeque; -impl Solution { - pub fn find_bottom_left_value(root: Option>>) -> i32 { - let mut queue = VecDeque::new(); - queue.push_back(root); - let mut res = 0; - while !queue.is_empty() { - res = queue.front().unwrap().as_ref().unwrap().borrow_mut().val; - for _ in 0..queue.len() { - let node = queue.pop_front().unwrap(); - let mut node = node.as_ref().unwrap().borrow_mut(); - if node.left.is_some() { - queue.push_back(node.left.take()); - } - if node.right.is_some() { - queue.push_back(node.right.take()); - } - } +function findBottomLeftValue(root: TreeNode | null): number { + let mx = 0; + let ans = 0; + + function dfs(root, curr) { + if (!root) { + return; + } + dfs(root.left, curr + 1); + dfs(root.right, curr + 1); + if (mx < curr) { + mx = curr; + ans = root.val; } - res } + dfs(root, 1); + return ans; } ``` @@ -448,10 +444,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0514.Freedom Trail/README.md b/solution/0500-0599/0514.Freedom Trail/README.md index b74ca482821d2..cc54a49071f7b 100644 --- a/solution/0500-0599/0514.Freedom Trail/README.md +++ b/solution/0500-0599/0514.Freedom Trail/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们首先预处理出字符串 $ring$ 中每个字符 $c$ 出现的位置列表,记录在数组 $pos[c]$ 中。不妨假设字符串 $key$ 和 $ring$ 的长度分别为 $m$ 和 $n$。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def findRotateSteps(self, ring: str, key: str) -> int: @@ -97,10 +91,6 @@ class Solution: return min(f[-1][j] for j in pos[key[-1]]) ``` -### **Java** - - - ```java class Solution { public int findRotateSteps(String ring, String key) { @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +155,6 @@ public: }; ``` -### **Go** - ```go func findRotateSteps(ring string, key string) int { m, n := len(key), len(ring) @@ -208,10 +194,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0514.Freedom Trail/README_EN.md b/solution/0500-0599/0514.Freedom Trail/README_EN.md index c9f22df429c6b..6ebe1713659ee 100644 --- a/solution/0500-0599/0514.Freedom Trail/README_EN.md +++ b/solution/0500-0599/0514.Freedom Trail/README_EN.md @@ -48,9 +48,9 @@ So the final output is 4. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return min(f[-1][j] for j in pos[key[-1]]) ``` -### **Java** - ```java class Solution { public int findRotateSteps(String ring, String key) { @@ -107,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +135,6 @@ public: }; ``` -### **Go** - ```go func findRotateSteps(ring string, key string) int { m, n := len(key), len(ring) @@ -180,10 +174,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0515.Find Largest Value in Each Tree Row/README.md b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/README.md index 504d85343356c..607fc30a19eeb 100644 --- a/solution/0500-0599/0515.Find Largest Value in Each Tree Row/README.md +++ b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/README.md @@ -39,22 +39,12 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS BFS 找每一层最大的节点值。 -**方法二:DFS** - -DFS 先序遍历,找每个深度最大的节点值。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -81,34 +71,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def largestValues(self, root: Optional[TreeNode]) -> List[int]: - def dfs(root, curr): - if root is None: - return - if curr == len(ans): - ans.append(root.val) - else: - ans[curr] = max(ans[curr], root.val) - dfs(root.left, curr + 1) - dfs(root.right, curr + 1) - - ans = [] - dfs(root, 0) - return ans -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -152,47 +114,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private List ans = new ArrayList<>(); - - public List largestValues(TreeNode root) { - dfs(root, 0); - return ans; - } - - private void dfs(TreeNode root, int curr) { - if (root == null) { - return; - } - if (curr == ans.size()) { - ans.add(root.val); - } else { - ans.set(curr, Math.max(ans.get(curr), root.val)); - } - dfs(root.left, curr + 1); - dfs(root.right, curr + 1); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -227,41 +148,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector ans; - - vector largestValues(TreeNode* root) { - dfs(root, 0); - return ans; - } - - void dfs(TreeNode* root, int curr) { - if (!root) return; - if (curr == ans.size()) - ans.push_back(root->val); - else - ans[curr] = max(ans[curr], root->val); - dfs(root->left, curr + 1); - dfs(root->right, curr + 1); - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -296,37 +182,6 @@ func largestValues(root *TreeNode) []int { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func largestValues(root *TreeNode) []int { - var ans []int - var dfs func(*TreeNode, int) - dfs = func(root *TreeNode, curr int) { - if root == nil { - return - } - if curr == len(ans) { - ans = append(ans, root.Val) - } else { - ans[curr] = max(ans[curr], root.Val) - } - dfs(root.Left, curr+1) - dfs(root.Right, curr+1) - } - dfs(root, 0) - return ans -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -363,43 +218,6 @@ function largestValues(root: TreeNode | null): number[] { } ``` -```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 largestValues(root: TreeNode | null): number[] { - const res = []; - const dfs = (root: TreeNode | null, depth: number) => { - if (root == null) { - return; - } - const { val, left, right } = root; - if (res.length == depth) { - res.push(val); - } else { - res[depth] = Math.max(res[depth], val); - } - dfs(left, depth + 1); - dfs(right, depth + 1); - }; - dfs(root, 0); - return res; -} -``` - -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -449,6 +267,174 @@ impl Solution { } ``` + + +### 方法二:DFS + +DFS 先序遍历,找每个深度最大的节点值。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def largestValues(self, root: Optional[TreeNode]) -> List[int]: + def dfs(root, curr): + if root is None: + return + if curr == len(ans): + ans.append(root.val) + else: + ans[curr] = max(ans[curr], root.val) + dfs(root.left, curr + 1) + dfs(root.right, curr + 1) + + ans = [] + dfs(root, 0) + return ans +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List ans = new ArrayList<>(); + + public List largestValues(TreeNode root) { + dfs(root, 0); + return ans; + } + + private void dfs(TreeNode root, int curr) { + if (root == null) { + return; + } + if (curr == ans.size()) { + ans.add(root.val); + } else { + ans.set(curr, Math.max(ans.get(curr), root.val)); + } + dfs(root.left, curr + 1); + dfs(root.right, curr + 1); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector ans; + + vector largestValues(TreeNode* root) { + dfs(root, 0); + return ans; + } + + void dfs(TreeNode* root, int curr) { + if (!root) return; + if (curr == ans.size()) + ans.push_back(root->val); + else + ans[curr] = max(ans[curr], root->val); + dfs(root->left, curr + 1); + dfs(root->right, curr + 1); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func largestValues(root *TreeNode) []int { + var ans []int + var dfs func(*TreeNode, int) + dfs = func(root *TreeNode, curr int) { + if root == nil { + return + } + if curr == len(ans) { + ans = append(ans, root.Val) + } else { + ans[curr] = max(ans[curr], root.Val) + } + dfs(root.Left, curr+1) + dfs(root.Right, curr+1) + } + dfs(root, 0) + return ans +} +``` + +```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 largestValues(root: TreeNode | null): number[] { + const res = []; + const dfs = (root: TreeNode | null, depth: number) => { + if (root == null) { + return; + } + const { val, left, right } = root; + if (res.length == depth) { + res.push(val); + } else { + res[depth] = Math.max(res[depth], val); + } + dfs(left, depth + 1); + dfs(right, depth + 1); + }; + dfs(root, 0); + return res; +} +``` + ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -493,10 +479,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0515.Find Largest Value in Each Tree Row/README_EN.md b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/README_EN.md index 2e3445b7ace70..a546f6480ef27 100644 --- a/solution/0500-0599/0515.Find Largest Value in Each Tree Row/README_EN.md +++ b/solution/0500-0599/0515.Find Largest Value in Each Tree Row/README_EN.md @@ -31,9 +31,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -61,32 +61,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def largestValues(self, root: Optional[TreeNode]) -> List[int]: - def dfs(root, curr): - if root is None: - return - if curr == len(ans): - ans.append(root.val) - else: - ans[curr] = max(ans[curr], root.val) - dfs(root.left, curr + 1) - dfs(root.right, curr + 1) - - ans = [] - dfs(root, 0) - return ans -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -130,47 +104,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private List ans = new ArrayList<>(); - - public List largestValues(TreeNode root) { - dfs(root, 0); - return ans; - } - - private void dfs(TreeNode root, int curr) { - if (root == null) { - return; - } - if (curr == ans.size()) { - ans.add(root.val); - } else { - ans.set(curr, Math.max(ans.get(curr), root.val)); - } - dfs(root.left, curr + 1); - dfs(root.right, curr + 1); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -205,41 +138,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector ans; - - vector largestValues(TreeNode* root) { - dfs(root, 0); - return ans; - } - - void dfs(TreeNode* root, int curr) { - if (!root) return; - if (curr == ans.size()) - ans.push_back(root->val); - else - ans[curr] = max(ans[curr], root->val); - dfs(root->left, curr + 1); - dfs(root->right, curr + 1); - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -274,37 +172,6 @@ func largestValues(root *TreeNode) []int { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func largestValues(root *TreeNode) []int { - var ans []int - var dfs func(*TreeNode, int) - dfs = func(root *TreeNode, curr int) { - if root == nil { - return - } - if curr == len(ans) { - ans = append(ans, root.Val) - } else { - ans[curr] = max(ans[curr], root.Val) - } - dfs(root.Left, curr+1) - dfs(root.Right, curr+1) - } - dfs(root, 0) - return ans -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -341,43 +208,6 @@ function largestValues(root: TreeNode | null): number[] { } ``` -```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 largestValues(root: TreeNode | null): number[] { - const res = []; - const dfs = (root: TreeNode | null, depth: number) => { - if (root == null) { - return; - } - const { val, left, right } = root; - if (res.length == depth) { - res.push(val); - } else { - res[depth] = Math.max(res[depth], val); - } - dfs(left, depth + 1); - dfs(right, depth + 1); - }; - dfs(root, 0); - return res; -} -``` - -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -427,6 +257,172 @@ impl Solution { } ``` + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def largestValues(self, root: Optional[TreeNode]) -> List[int]: + def dfs(root, curr): + if root is None: + return + if curr == len(ans): + ans.append(root.val) + else: + ans[curr] = max(ans[curr], root.val) + dfs(root.left, curr + 1) + dfs(root.right, curr + 1) + + ans = [] + dfs(root, 0) + return ans +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List ans = new ArrayList<>(); + + public List largestValues(TreeNode root) { + dfs(root, 0); + return ans; + } + + private void dfs(TreeNode root, int curr) { + if (root == null) { + return; + } + if (curr == ans.size()) { + ans.add(root.val); + } else { + ans.set(curr, Math.max(ans.get(curr), root.val)); + } + dfs(root.left, curr + 1); + dfs(root.right, curr + 1); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector ans; + + vector largestValues(TreeNode* root) { + dfs(root, 0); + return ans; + } + + void dfs(TreeNode* root, int curr) { + if (!root) return; + if (curr == ans.size()) + ans.push_back(root->val); + else + ans[curr] = max(ans[curr], root->val); + dfs(root->left, curr + 1); + dfs(root->right, curr + 1); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func largestValues(root *TreeNode) []int { + var ans []int + var dfs func(*TreeNode, int) + dfs = func(root *TreeNode, curr int) { + if root == nil { + return + } + if curr == len(ans) { + ans = append(ans, root.Val) + } else { + ans[curr] = max(ans[curr], root.Val) + } + dfs(root.Left, curr+1) + dfs(root.Right, curr+1) + } + dfs(root, 0) + return ans +} +``` + +```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 largestValues(root: TreeNode | null): number[] { + const res = []; + const dfs = (root: TreeNode | null, depth: number) => { + if (root == null) { + return; + } + const { val, left, right } = root; + if (res.length == depth) { + res.push(val); + } else { + res[depth] = Math.max(res[depth], val); + } + dfs(left, depth + 1); + dfs(right, depth + 1); + }; + dfs(root, 0); + return res; +} +``` + ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -471,10 +467,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0516.Longest Palindromic Subsequence/README.md b/solution/0500-0599/0516.Longest Palindromic Subsequence/README.md index 610d7de178942..564274ecad3cd 100644 --- a/solution/0500-0599/0516.Longest Palindromic Subsequence/README.md +++ b/solution/0500-0599/0516.Longest Palindromic Subsequence/README.md @@ -39,21 +39,10 @@ ## 解法 - - -动态规划。 - -设 `dp[i][j]` 表示字符串 `s[i..j]` 中的最长回文子序列的长度。初始化 `dp[i][i] = 1`(`i∈[0, n-1]`)。 - -- 对于 `s[i] == s[j]`,`dp[i][j] = dp[i + 1][j - 1] + 2`; -- 对于 `s[i] != s[j]`,`dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])`。 +### 方法一 -### **Python3** - - - ```python class Solution: def longestPalindromeSubseq(self, s: str) -> int: @@ -70,10 +59,6 @@ class Solution: return dp[0][-1] ``` -### **Java** - - - ```java class Solution { public int longestPalindromeSubseq(String s) { @@ -96,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +104,6 @@ public: }; ``` -### **Go** - ```go func longestPalindromeSubseq(s string) int { n := len(s) @@ -144,10 +125,6 @@ func longestPalindromeSubseq(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0516.Longest Palindromic Subsequence/README_EN.md b/solution/0500-0599/0516.Longest Palindromic Subsequence/README_EN.md index 9dd46121223de..d72d255203171 100644 --- a/solution/0500-0599/0516.Longest Palindromic Subsequence/README_EN.md +++ b/solution/0500-0599/0516.Longest Palindromic Subsequence/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return dp[0][-1] ``` -### **Java** - ```java class Solution { public int longestPalindromeSubseq(String s) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +100,6 @@ public: }; ``` -### **Go** - ```go func longestPalindromeSubseq(s string) int { n := len(s) @@ -127,10 +121,6 @@ func longestPalindromeSubseq(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0517.Super Washing Machines/README.md b/solution/0500-0599/0517.Super Washing Machines/README.md index 9366c0f0f2c70..4989684142a4d 100644 --- a/solution/0500-0599/0517.Super Washing Machines/README.md +++ b/solution/0500-0599/0517.Super Washing Machines/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 如果洗衣机内的衣服总数不能被洗衣机的数量整除,那么不可能使得每台洗衣机内的衣服数量相等,直接返回 $-1$。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def findMinMoves(self, machines: List[int]) -> int: @@ -98,10 +92,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int findMinMoves(int[] machines) { @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func findMinMoves(machines []int) (ans int) { n := len(machines) @@ -180,8 +166,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function findMinMoves(machines: number[]): number { const n = machines.length; @@ -201,10 +185,6 @@ function findMinMoves(machines: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0517.Super Washing Machines/README_EN.md b/solution/0500-0599/0517.Super Washing Machines/README_EN.md index 7c762be3ffffc..e81ea2e74c6dd 100644 --- a/solution/0500-0599/0517.Super Washing Machines/README_EN.md +++ b/solution/0500-0599/0517.Super Washing Machines/README_EN.md @@ -52,9 +52,9 @@ It's impossible to make all three washing machines have the same number of d ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int findMinMoves(int[] machines) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +117,6 @@ public: }; ``` -### **Go** - ```go func findMinMoves(machines []int) (ans int) { n := len(machines) @@ -151,8 +145,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function findMinMoves(machines: number[]): number { const n = machines.length; @@ -172,10 +164,6 @@ function findMinMoves(machines: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0518.Coin Change II/README.md b/solution/0500-0599/0518.Coin Change II/README.md index ca6073700090c..3447d53cf104a 100644 --- a/solution/0500-0599/0518.Coin Change II/README.md +++ b/solution/0500-0599/0518.Coin Change II/README.md @@ -59,18 +59,10 @@ ## 解法 - - -动态规划。 - -完全背包问题。 +### 方法一 -### **Python3** - - - ```python class Solution: def change(self, amount: int, coins: List[int]) -> int: @@ -82,10 +74,6 @@ class Solution: return dp[-1] ``` -### **Java** - - - ```java class Solution { public int change(int amount, int[] coins) { @@ -104,14 +92,53 @@ class Solution { } ``` -下面对 k 这层循环进行优化: +```cpp +class Solution { +public: + int change(int amount, vector& coins) { + vector dp(amount + 1); + dp[0] = 1; + for (auto coin : coins) { + for (int j = coin; j <= amount; ++j) { + dp[j] += dp[j - coin]; + } + } + return dp[amount]; + } +}; +``` + +```go +func change(amount int, coins []int) int { + dp := make([]int, amount+1) + dp[0] = 1 + for _, coin := range coins { + for j := coin; j <= amount; j++ { + dp[j] += dp[j-coin] + } + } + return dp[amount] +} +``` + +```ts +function change(amount: number, coins: number[]): number { + let dp = new Array(amount + 1).fill(0); + dp[0] = 1; + for (let coin of coins) { + for (let i = coin; i <= amount; ++i) { + dp[i] += dp[i - coin]; + } + } + return dp.pop(); +} +``` -由于: + -- `dp[i][j] = dp[i - 1][j] + dp[i - 1][j - v] + dp[i - 1][j - 2v] + ... + dp[i - 1][j - kv]` -- `dp[i][j - v] = dp[i - 1][j - v] + dp[i - 1][j - 2v] + ... + dp[i - 1][j - kv]` +### 方法二 -因此 `dp[i][j] = dp[i - 1][j] + dp[i][j - v]`。 + ```java class Solution { @@ -133,7 +160,11 @@ class Solution { } ``` -空间优化: + + +### 方法三 + + ```java class Solution { @@ -151,58 +182,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function change(amount: number, coins: number[]): number { - let dp = new Array(amount + 1).fill(0); - dp[0] = 1; - for (let coin of coins) { - for (let i = coin; i <= amount; ++i) { - dp[i] += dp[i - coin]; - } - } - return dp.pop(); -} -``` - -### **Go** - -```go -func change(amount int, coins []int) int { - dp := make([]int, amount+1) - dp[0] = 1 - for _, coin := range coins { - for j := coin; j <= amount; j++ { - dp[j] += dp[j-coin] - } - } - return dp[amount] -} -``` - -### **C++** - -```cpp -class Solution { -public: - int change(int amount, vector& coins) { - vector dp(amount + 1); - dp[0] = 1; - for (auto coin : coins) { - for (int j = coin; j <= amount; ++j) { - dp[j] += dp[j - coin]; - } - } - return dp[amount]; - } -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0518.Coin Change II/README_EN.md b/solution/0500-0599/0518.Coin Change II/README_EN.md index d1191311eab61..75e57a06882fd 100644 --- a/solution/0500-0599/0518.Coin Change II/README_EN.md +++ b/solution/0500-0599/0518.Coin Change II/README_EN.md @@ -52,14 +52,10 @@ ## Solutions -Dynamic programming. - -Complete knapsack problem. +### Solution 1 -### **Python3** - ```python class Solution: def change(self, amount: int, coins: List[int]) -> int: @@ -71,8 +67,6 @@ class Solution: return dp[-1] ``` -### **Java** - ```java class Solution { public int change(int amount, int[] coins) { @@ -91,42 +85,34 @@ class Solution { } ``` -```java -class Solution { - public int change(int amount, int[] coins) { - int m = coins.length; - int[][] dp = new int[m + 1][amount + 1]; - dp[0][0] = 1; - for (int i = 1; i <= m; ++i) { - int v = coins[i - 1]; - for (int j = 0; j <= amount; ++j) { - dp[i][j] = dp[i - 1][j]; - if (j >= v) { - dp[i][j] += dp[i][j - v]; - } - } - } - return dp[m][amount]; - } -} -``` - -```java +```cpp class Solution { - public int change(int amount, int[] coins) { - int[] dp = new int[amount + 1]; +public: + int change(int amount, vector& coins) { + vector dp(amount + 1); dp[0] = 1; - for (int coin : coins) { - for (int j = coin; j <= amount; j++) { + for (auto coin : coins) { + for (int j = coin; j <= amount; ++j) { dp[j] += dp[j - coin]; } } return dp[amount]; } -} +}; ``` -### **TypeScript** +```go +func change(amount int, coins []int) int { + dp := make([]int, amount+1) + dp[0] = 1 + for _, coin := range coins { + for j := coin; j <= amount; j++ { + dp[j] += dp[j-coin] + } + } + return dp[amount] +} +``` ```ts function change(amount: number, coins: number[]): number { @@ -141,43 +127,54 @@ function change(amount: number, coins: number[]): number { } ``` -### **Go** + -```go -func change(amount int, coins []int) int { - dp := make([]int, amount+1) - dp[0] = 1 - for _, coin := range coins { - for j := coin; j <= amount; j++ { - dp[j] += dp[j-coin] - } - } - return dp[amount] +### Solution 2 + + + +```java +class Solution { + public int change(int amount, int[] coins) { + int m = coins.length; + int[][] dp = new int[m + 1][amount + 1]; + dp[0][0] = 1; + for (int i = 1; i <= m; ++i) { + int v = coins[i - 1]; + for (int j = 0; j <= amount; ++j) { + dp[i][j] = dp[i - 1][j]; + if (j >= v) { + dp[i][j] += dp[i][j - v]; + } + } + } + return dp[m][amount]; + } } ``` -### **C++** + -```cpp +### Solution 3 + + + +```java class Solution { -public: - int change(int amount, vector& coins) { - vector dp(amount + 1); + public int change(int amount, int[] coins) { + int[] dp = new int[amount + 1]; dp[0] = 1; - for (auto coin : coins) { - for (int j = coin; j <= amount; ++j) { + for (int coin : coins) { + // 顺序遍历,0-1背包问题是倒序遍历 + for (int j = coin; j <= amount; j++) { dp[j] += dp[j - coin]; } } return dp[amount]; } -}; -``` - -### **...** - -``` - +} ``` + + diff --git a/solution/0500-0599/0519.Random Flip Matrix/README.md b/solution/0500-0599/0519.Random Flip Matrix/README.md index fc68a4b045ec2..f81e6c4f0498a 100644 --- a/solution/0500-0599/0519.Random Flip Matrix/README.md +++ b/solution/0500-0599/0519.Random Flip Matrix/README.md @@ -49,14 +49,10 @@ solution.flip(); // 返回 [2, 0],此时返回 [0,0]、[1,0] 和 [2,0] 的概 ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def __init__(self, m: int, n: int): @@ -83,10 +79,6 @@ class Solution: # obj.reset() ``` -### **Java** - - - ```java class Solution { private int m; @@ -122,10 +114,6 @@ class Solution { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0519.Random Flip Matrix/README_EN.md b/solution/0500-0599/0519.Random Flip Matrix/README_EN.md index af110a3363799..ec9ef2d97ad9a 100644 --- a/solution/0500-0599/0519.Random Flip Matrix/README_EN.md +++ b/solution/0500-0599/0519.Random Flip Matrix/README_EN.md @@ -46,9 +46,9 @@ solution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally li ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: # obj.reset() ``` -### **Java** - ```java class Solution { private int m; @@ -113,10 +111,6 @@ class Solution { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0520.Detect Capital/README.md b/solution/0500-0599/0520.Detect Capital/README.md index 262f7b598d884..8a4ed1b6455d0 100644 --- a/solution/0500-0599/0520.Detect Capital/README.md +++ b/solution/0500-0599/0520.Detect Capital/README.md @@ -43,14 +43,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def detectCapitalUse(self, word: str) -> bool: @@ -61,10 +57,6 @@ class Solution: return cnt == 0 or cnt == len(word) or (cnt == 1 and word[0].isupper()) ``` -### **Java** - - - ```java class Solution { public boolean detectCapitalUse(String word) { @@ -80,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +84,6 @@ public: }; ``` -### **Go** - ```go func detectCapitalUse(word string) bool { cnt := 0 @@ -108,10 +96,6 @@ func detectCapitalUse(word string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0520.Detect Capital/README_EN.md b/solution/0500-0599/0520.Detect Capital/README_EN.md index fd390818b25de..369cb9cf22b8c 100644 --- a/solution/0500-0599/0520.Detect Capital/README_EN.md +++ b/solution/0500-0599/0520.Detect Capital/README_EN.md @@ -32,9 +32,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -46,8 +46,6 @@ class Solution: return cnt == 0 or cnt == len(word) or (cnt == 1 and word[0].isupper()) ``` -### **Java** - ```java class Solution { public boolean detectCapitalUse(String word) { @@ -63,8 +61,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -77,8 +73,6 @@ public: }; ``` -### **Go** - ```go func detectCapitalUse(word string) bool { cnt := 0 @@ -91,10 +85,6 @@ func detectCapitalUse(word string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0521.Longest Uncommon Subsequence I/README.md b/solution/0500-0599/0521.Longest Uncommon Subsequence I/README.md index 3aa8886edb0c2..e9109107cb130 100644 --- a/solution/0500-0599/0521.Longest Uncommon Subsequence I/README.md +++ b/solution/0500-0599/0521.Longest Uncommon Subsequence I/README.md @@ -52,34 +52,16 @@ ## 解法 - - -**此题最难之处是理解题目想描述的是什么玩意**。 - -假定: `a = "abc", b = "abb"` - -要是说其中最长的相同子序列,便是 `ab`。 - -而特殊序列则是求**非子序列**,此时列举 `a` 的子序列 `"abc"`,`b` 拿不出来,那这就是一个成功的非子序列。 - -如此,在 `a != b` 时,谁最长谁就是 _最长的特殊序列_ +### 方法一 -### **Python3** - - - ```python class Solution: def findLUSlength(self, a: str, b: str) -> int: return -1 if a == b else max(len(a), len(b)) ``` -### **Java** - - - ```java class Solution { public int findLUSlength(String a, String b) { @@ -88,29 +70,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function findLUSlength(a: string, b: string): number { - return a != b ? Math.max(a.length, b.length) : -1; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn find_lu_slength(a: String, b: String) -> i32 { - if a == b { - return -1; - } - a.len().max(b.len()) as i32 - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -120,8 +79,6 @@ public: }; ``` -### **Go** - ```go func findLUSlength(a string, b string) int { if a == b { @@ -134,10 +91,23 @@ func findLUSlength(a string, b string) int { } ``` -### **...** - +```ts +function findLUSlength(a: string, b: string): number { + return a != b ? Math.max(a.length, b.length) : -1; +} ``` +```rust +impl Solution { + pub fn find_lu_slength(a: String, b: String) -> i32 { + if a == b { + return -1; + } + a.len().max(b.len()) as i32 + } +} ``` + + diff --git a/solution/0500-0599/0521.Longest Uncommon Subsequence I/README_EN.md b/solution/0500-0599/0521.Longest Uncommon Subsequence I/README_EN.md index 950ef27f50df0..5afc6330f2779 100644 --- a/solution/0500-0599/0521.Longest Uncommon Subsequence I/README_EN.md +++ b/solution/0500-0599/0521.Longest Uncommon Subsequence I/README_EN.md @@ -50,9 +50,9 @@ Note that "cdc" is also a longest uncommon subsequence. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return -1 if a == b else max(len(a), len(b)) ``` -### **Java** - ```java class Solution { public int findLUSlength(String a, String b) { @@ -70,29 +68,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function findLUSlength(a: string, b: string): number { - return a != b ? Math.max(a.length, b.length) : -1; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn find_lu_slength(a: String, b: String) -> i32 { - if a == b { - return -1; - } - a.len().max(b.len()) as i32 - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -102,8 +77,6 @@ public: }; ``` -### **Go** - ```go func findLUSlength(a string, b string) int { if a == b { @@ -116,10 +89,23 @@ func findLUSlength(a string, b string) int { } ``` -### **...** - +```ts +function findLUSlength(a: string, b: string): number { + return a != b ? Math.max(a.length, b.length) : -1; +} ``` +```rust +impl Solution { + pub fn find_lu_slength(a: String, b: String) -> i32 { + if a == b { + return -1; + } + a.len().max(b.len()) as i32 + } +} ``` + + diff --git a/solution/0500-0599/0522.Longest Uncommon Subsequence II/README.md b/solution/0500-0599/0522.Longest Uncommon Subsequence II/README.md index 83c92bac7fc24..cce97b9ee8b5e 100644 --- a/solution/0500-0599/0522.Longest Uncommon Subsequence II/README.md +++ b/solution/0500-0599/0522.Longest Uncommon Subsequence II/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:判断子序列** +### 方法一:判断子序列 判断是否独有,只需要取字符串 $s$ 本身,与其他字符串比较即可。题目可以转化为:获取**非其他字符串子序列**的字符串的最大长度。若不存在,返回 -1。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def findLUSlength(self, strs: List[str]) -> int: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int findLUSlength(String[] strs) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func findLUSlength(strs []string) int { check := func(a, b string) bool { @@ -178,10 +164,6 @@ func findLUSlength(strs []string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0522.Longest Uncommon Subsequence II/README_EN.md b/solution/0500-0599/0522.Longest Uncommon Subsequence II/README_EN.md index c191be4660b4a..512d1168e49d8 100644 --- a/solution/0500-0599/0522.Longest Uncommon Subsequence II/README_EN.md +++ b/solution/0500-0599/0522.Longest Uncommon Subsequence II/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int findLUSlength(String[] strs) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func findLUSlength(strs []string) int { check := func(a, b string) bool { @@ -155,10 +149,6 @@ func findLUSlength(strs []string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0523.Continuous Subarray Sum/README.md b/solution/0500-0599/0523.Continuous Subarray Sum/README.md index 780b88fec1508..f39a04521353f 100644 --- a/solution/0500-0599/0523.Continuous Subarray Sum/README.md +++ b/solution/0500-0599/0523.Continuous Subarray Sum/README.md @@ -55,18 +55,10 @@ ## 解法 - - -前缀和 + 哈希表。 - -要满足区间和是 k 的倍数,也即 `s[i] - s[j] = n * k` (其中 `i - j >= 2`),变形,得 `s[i] / k - s[j] / k = n`,所以只要满足 `s[i] % k == s[j] % k` 即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def checkSubarraySum(self, nums: List[int], k: int) -> bool: @@ -82,10 +74,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean checkSubarraySum(int[] nums, int k) { @@ -107,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +113,6 @@ public: }; ``` -### **Go** - ```go func checkSubarraySum(nums []int, k int) bool { mp := map[int]int{0: -1} @@ -147,10 +131,6 @@ func checkSubarraySum(nums []int, k int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0523.Continuous Subarray Sum/README_EN.md b/solution/0500-0599/0523.Continuous Subarray Sum/README_EN.md index 51bc9fd4d43aa..4287d80db2145 100644 --- a/solution/0500-0599/0523.Continuous Subarray Sum/README_EN.md +++ b/solution/0500-0599/0523.Continuous Subarray Sum/README_EN.md @@ -57,9 +57,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean checkSubarraySum(int[] nums, int k) { @@ -99,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +115,6 @@ public: }; ``` -### **Go** - ```go func checkSubarraySum(nums []int, k int) bool { mp := map[int]int{0: -1} @@ -139,10 +133,6 @@ func checkSubarraySum(nums []int, k int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0524.Longest Word in Dictionary through Deleting/README.md b/solution/0500-0599/0524.Longest Word in Dictionary through Deleting/README.md index e18bfb96437b8..ed0f3556e0e69 100644 --- a/solution/0500-0599/0524.Longest Word in Dictionary through Deleting/README.md +++ b/solution/0500-0599/0524.Longest Word in Dictionary through Deleting/README.md @@ -39,14 +39,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findLongestWord(self, s: str, dictionary: List[str]) -> str: @@ -66,10 +62,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public String findLongestWord(String s, List dictionary) { @@ -98,7 +90,51 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + string findLongestWord(string s, vector& dictionary) { + string ans = ""; + for (string& a : dictionary) + if (check(s, a) && (ans.size() < a.size() || (ans.size() == a.size() && a < ans))) + ans = a; + return ans; + } + + bool check(string& a, string& b) { + int m = a.size(), n = b.size(); + int i = 0, j = 0; + while (i < m && j < n) { + if (a[i] == b[j]) ++j; + ++i; + } + return j == n; + } +}; +``` + +```go +func findLongestWord(s string, dictionary []string) string { + ans := "" + check := func(a, b string) bool { + m, n := len(a), len(b) + i, j := 0, 0 + for i < m && j < n { + if a[i] == b[j] { + j++ + } + i++ + } + return j == n + } + for _, a := range dictionary { + if check(s, a) && (len(ans) < len(a) || (len(ans) == len(a) && a < ans)) { + ans = a + } + } + return ans +} +``` ```ts function findLongestWord(s: string, dictionary: string[]): string { @@ -130,8 +166,6 @@ function findLongestWord(s: string, dictionary: string[]): string { } ``` -### **Rust** - ```rust impl Solution { pub fn find_longest_word(s: String, mut dictionary: Vec) -> String { @@ -157,60 +191,6 @@ impl Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string findLongestWord(string s, vector& dictionary) { - string ans = ""; - for (string& a : dictionary) - if (check(s, a) && (ans.size() < a.size() || (ans.size() == a.size() && a < ans))) - ans = a; - return ans; - } - - bool check(string& a, string& b) { - int m = a.size(), n = b.size(); - int i = 0, j = 0; - while (i < m && j < n) { - if (a[i] == b[j]) ++j; - ++i; - } - return j == n; - } -}; -``` - -### **Go** - -```go -func findLongestWord(s string, dictionary []string) string { - ans := "" - check := func(a, b string) bool { - m, n := len(a), len(b) - i, j := 0, 0 - for i < m && j < n { - if a[i] == b[j] { - j++ - } - i++ - } - return j == n - } - for _, a := range dictionary { - if check(s, a) && (len(ans) < len(a) || (len(ans) == len(a) && a < ans)) { - ans = a - } - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0524.Longest Word in Dictionary through Deleting/README_EN.md b/solution/0500-0599/0524.Longest Word in Dictionary through Deleting/README_EN.md index 18db07494c770..315db7aa51339 100644 --- a/solution/0500-0599/0524.Longest Word in Dictionary through Deleting/README_EN.md +++ b/solution/0500-0599/0524.Longest Word in Dictionary through Deleting/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public String findLongestWord(String s, List dictionary) { @@ -86,7 +84,51 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + string findLongestWord(string s, vector& dictionary) { + string ans = ""; + for (string& a : dictionary) + if (check(s, a) && (ans.size() < a.size() || (ans.size() == a.size() && a < ans))) + ans = a; + return ans; + } + + bool check(string& a, string& b) { + int m = a.size(), n = b.size(); + int i = 0, j = 0; + while (i < m && j < n) { + if (a[i] == b[j]) ++j; + ++i; + } + return j == n; + } +}; +``` + +```go +func findLongestWord(s string, dictionary []string) string { + ans := "" + check := func(a, b string) bool { + m, n := len(a), len(b) + i, j := 0, 0 + for i < m && j < n { + if a[i] == b[j] { + j++ + } + i++ + } + return j == n + } + for _, a := range dictionary { + if check(s, a) && (len(ans) < len(a) || (len(ans) == len(a) && a < ans)) { + ans = a + } + } + return ans +} +``` ```ts function findLongestWord(s: string, dictionary: string[]): string { @@ -118,8 +160,6 @@ function findLongestWord(s: string, dictionary: string[]): string { } ``` -### **Rust** - ```rust impl Solution { pub fn find_longest_word(s: String, mut dictionary: Vec) -> String { @@ -145,60 +185,6 @@ impl Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string findLongestWord(string s, vector& dictionary) { - string ans = ""; - for (string& a : dictionary) - if (check(s, a) && (ans.size() < a.size() || (ans.size() == a.size() && a < ans))) - ans = a; - return ans; - } - - bool check(string& a, string& b) { - int m = a.size(), n = b.size(); - int i = 0, j = 0; - while (i < m && j < n) { - if (a[i] == b[j]) ++j; - ++i; - } - return j == n; - } -}; -``` - -### **Go** - -```go -func findLongestWord(s string, dictionary []string) string { - ans := "" - check := func(a, b string) bool { - m, n := len(a), len(b) - i, j := 0, 0 - for i < m && j < n { - if a[i] == b[j] { - j++ - } - i++ - } - return j == n - } - for _, a := range dictionary { - if check(s, a) && (len(ans) < len(a) || (len(ans) == len(a) && a < ans)) { - ans = a - } - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0525.Contiguous Array/README.md b/solution/0500-0599/0525.Contiguous Array/README.md index 08257abd03ab4..fbc182a5836b2 100644 --- a/solution/0500-0599/0525.Contiguous Array/README.md +++ b/solution/0500-0599/0525.Contiguous Array/README.md @@ -35,24 +35,10 @@ ## 解法 - - -前缀和 + 哈希表,把 0 当作 -1 处理,题目变成求和为 0 的子数组。 - -遍历数组,用哈希表 mp 记录某个前缀和第一次出现的位置。初始值 `mp[0] = -1`。 - -当前缀和 s 在此前出现过,说明这两个前缀和区间差构成的所有元素和为 0,满足条件,更新 ans 值。否则将 s 记录到 mp 中。 - -最后返回 ans。 - -> 这里初始化 `mp[0] = -1`,是为了统一操作。当数组从第一个元素开始的前 n 个元素的和为 0 时,也可以用 `ans = max(ans, i - mp[s])`。 +### 方法一 -### **Python3** - - - ```python class Solution: def findMaxLength(self, nums: List[int]) -> int: @@ -67,10 +53,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int findMaxLength(int[] nums) { @@ -90,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +91,6 @@ public: }; ``` -### **Go** - ```go func findMaxLength(nums []int) int { mp := map[int]int{0: -1} @@ -132,8 +110,6 @@ func findMaxLength(nums []int) int { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -153,10 +129,6 @@ var findMaxLength = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0525.Contiguous Array/README_EN.md b/solution/0500-0599/0525.Contiguous Array/README_EN.md index 7901f02ea8653..505df329b3ef3 100644 --- a/solution/0500-0599/0525.Contiguous Array/README_EN.md +++ b/solution/0500-0599/0525.Contiguous Array/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int findMaxLength(int[] nums) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +89,6 @@ public: }; ``` -### **Go** - ```go func findMaxLength(nums []int) int { mp := map[int]int{0: -1} @@ -114,8 +108,6 @@ func findMaxLength(nums []int) int { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -135,10 +127,6 @@ var findMaxLength = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0526.Beautiful Arrangement/README.md b/solution/0500-0599/0526.Beautiful Arrangement/README.md index 429ebbdc873c4..515c2453640f6 100644 --- a/solution/0500-0599/0526.Beautiful Arrangement/README.md +++ b/solution/0500-0599/0526.Beautiful Arrangement/README.md @@ -48,16 +48,10 @@ ## 解法 - - -DFS 回溯,或者状态压缩。 +### 方法一 -### **Python3** - - - ```python class Solution: def countArrangement(self, n: int) -> int: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int n; @@ -130,30 +120,6 @@ class Solution { } ``` -```java -class Solution { - public int countArrangement(int N) { - int maxn = 1 << N; - int[] f = new int[maxn]; - f[0] = 1; - for (int i = 0; i < maxn; ++i) { - int s = 1; - for (int j = 0; j < N; ++j) { - s += (i >> j) & 1; - } - for (int j = 1; j <= N; ++j) { - if (((i >> (j - 1) & 1) == 0) && (s % j == 0 || j % s == 0)) { - f[i | (1 << (j - 1))] += f[i]; - } - } - } - return f[maxn - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -190,8 +156,6 @@ public: }; ``` -### **Go** - ```go func countArrangement(n int) int { ans := 0 @@ -225,8 +189,6 @@ func countArrangement(n int) int { } ``` -### **TypeScript** - ```ts function countArrangement(n: number): number { const vis = new Array(n + 1).fill(0); @@ -258,8 +220,6 @@ function countArrangement(n: number): number { } ``` -### **Rust** - ```rust impl Solution { fn dfs(i: usize, n: usize, mat: &Vec>, vis: &mut Vec, res: &mut i32) { @@ -295,10 +255,34 @@ impl Solution { } ``` -### **...** + -``` +### 方法二 + + +```java +class Solution { + public int countArrangement(int N) { + int maxn = 1 << N; + int[] f = new int[maxn]; + f[0] = 1; + for (int i = 0; i < maxn; ++i) { + int s = 1; + for (int j = 0; j < N; ++j) { + s += (i >> j) & 1; + } + for (int j = 1; j <= N; ++j) { + if (((i >> (j - 1) & 1) == 0) && (s % j == 0 || j % s == 0)) { + f[i | (1 << (j - 1))] += f[i]; + } + } + } + return f[maxn - 1]; + } +} ``` + + diff --git a/solution/0500-0599/0526.Beautiful Arrangement/README_EN.md b/solution/0500-0599/0526.Beautiful Arrangement/README_EN.md index 35198bd43e8be..7ec778e8afc56 100644 --- a/solution/0500-0599/0526.Beautiful Arrangement/README_EN.md +++ b/solution/0500-0599/0526.Beautiful Arrangement/README_EN.md @@ -44,9 +44,9 @@ The second beautiful arrangement is [2,1]: ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int n; @@ -118,30 +116,6 @@ class Solution { } ``` -```java -class Solution { - public int countArrangement(int N) { - int maxn = 1 << N; - int[] f = new int[maxn]; - f[0] = 1; - for (int i = 0; i < maxn; ++i) { - int s = 1; - for (int j = 0; j < N; ++j) { - s += (i >> j) & 1; - } - for (int j = 1; j <= N; ++j) { - if (((i >> (j - 1) & 1) == 0) && (s % j == 0 || j % s == 0)) { - f[i | (1 << (j - 1))] += f[i]; - } - } - } - return f[maxn - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -178,8 +152,6 @@ public: }; ``` -### **Go** - ```go func countArrangement(n int) int { ans := 0 @@ -213,8 +185,6 @@ func countArrangement(n int) int { } ``` -### **TypeScript** - ```ts function countArrangement(n: number): number { const vis = new Array(n + 1).fill(0); @@ -246,8 +216,6 @@ function countArrangement(n: number): number { } ``` -### **Rust** - ```rust impl Solution { fn dfs(i: usize, n: usize, mat: &Vec>, vis: &mut Vec, res: &mut i32) { @@ -283,10 +251,34 @@ impl Solution { } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + public int countArrangement(int N) { + int maxn = 1 << N; + int[] f = new int[maxn]; + f[0] = 1; + for (int i = 0; i < maxn; ++i) { + int s = 1; + for (int j = 0; j < N; ++j) { + s += (i >> j) & 1; + } + for (int j = 1; j <= N; ++j) { + if (((i >> (j - 1) & 1) == 0) && (s % j == 0 || j % s == 0)) { + f[i | (1 << (j - 1))] += f[i]; + } + } + } + return f[maxn - 1]; + } +} ``` + + diff --git a/solution/0500-0599/0527.Word Abbreviation/README.md b/solution/0500-0599/0527.Word Abbreviation/README.md index 11a1873de0929..e1f81afdb374d 100644 --- a/solution/0500-0599/0527.Word Abbreviation/README.md +++ b/solution/0500-0599/0527.Word Abbreviation/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:分组字典树** +### 方法一:分组字典树 我们注意到,如果两个单词的缩写相同,那么它们的首尾字母一定相同,并且它们的长度一定相同。因此,我们可以将所有的单词按照长度以及末尾字母进行分组,对于每组单词,我们使用字典树存储这组单词的信息。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Trie: __slots__ = ["children", "cnt"] @@ -114,10 +108,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Trie { private final Trie[] children = new Trie[26]; @@ -170,8 +160,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -236,8 +224,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -296,8 +282,6 @@ func wordsAbbreviation(words []string) (ans []string) { } ``` -### **TypeScript** - ```ts class Trie { private children: Trie[] = Array(26); @@ -352,10 +336,6 @@ function wordsAbbreviation(words: string[]): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0527.Word Abbreviation/README_EN.md b/solution/0500-0599/0527.Word Abbreviation/README_EN.md index d5632c1e4e8d9..c4d7244ba0406 100644 --- a/solution/0500-0599/0527.Word Abbreviation/README_EN.md +++ b/solution/0500-0599/0527.Word Abbreviation/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Grouped Trie** +### Solution 1: Grouped Trie We notice that if two words have the same abbreviation, their first and last letters must be the same, and their lengths must be the same. Therefore, we can group all words by length and last letter, and use a trie to store the information of each group of words. @@ -60,8 +60,6 @@ The time complexity is $O(L)$, and the space complexity is $O(L)$. Here, $L$ is -### **Python3** - ```python class Trie: __slots__ = ["children", "cnt"] @@ -108,8 +106,6 @@ class Solution: return ans ``` -### **Java** - ```java class Trie { private final Trie[] children = new Trie[26]; @@ -162,8 +158,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -228,8 +222,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -288,8 +280,6 @@ func wordsAbbreviation(words []string) (ans []string) { } ``` -### **TypeScript** - ```ts class Trie { private children: Trie[] = Array(26); @@ -344,10 +334,6 @@ function wordsAbbreviation(words: string[]): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0528.Random Pick with Weight/README.md b/solution/0500-0599/0528.Random Pick with Weight/README.md index d2ff0042993f9..bd33f181c7551 100644 --- a/solution/0500-0599/0528.Random Pick with Weight/README.md +++ b/solution/0500-0599/0528.Random Pick with Weight/README.md @@ -69,16 +69,10 @@ solution.pickIndex(); // 返回 0,返回下标 0,返回该下标概率为 1/ ## 解法 - - -“前缀和 + 二分查找”。 +### 方法一 -### **Python3** - - - ```python class Solution: def __init__(self, w: List[int]): @@ -103,10 +97,6 @@ class Solution: # param_1 = obj.pickIndex() ``` -### **Java** - - - ```java class Solution { private int[] s; @@ -142,8 +132,6 @@ class Solution { */ ``` -### **C++** - ```cpp class Solution { public: @@ -177,8 +165,6 @@ public: */ ``` -### **Go** - ```go type Solution struct { s []int @@ -215,48 +201,6 @@ func (this *Solution) PickIndex() int { */ ``` -### **JavaScript** - -```js -/** - * @param {number[]} w - */ -var Solution = function (w) { - const n = w.length; - this.s = new Array(n + 1).fill(0); - for (let i = 0; i < n; ++i) { - this.s[i + 1] = this.s[i] + w[i]; - } -}; - -/** - * @return {number} - */ -Solution.prototype.pickIndex = function () { - const n = this.s.length; - const x = 1 + Math.floor(Math.random() * this.s[n - 1]); - let left = 1, - right = n - 1; - while (left < right) { - const mid = (left + right) >> 1; - if (this.s[mid] >= x) { - right = mid; - } else { - left = mid + 1; - } - } - return left - 1; -}; - -/** - * Your Solution object will be instantiated and called as such: - * var obj = new Solution(w) - * var param_1 = obj.pickIndex() - */ -``` - -### **Rust** - ```rust use rand::{ thread_rng, Rng }; @@ -298,10 +242,44 @@ impl Solution { */ ``` -### **...** +```js +/** + * @param {number[]} w + */ +var Solution = function (w) { + const n = w.length; + this.s = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + this.s[i + 1] = this.s[i] + w[i]; + } +}; -``` +/** + * @return {number} + */ +Solution.prototype.pickIndex = function () { + const n = this.s.length; + const x = 1 + Math.floor(Math.random() * this.s[n - 1]); + let left = 1, + right = n - 1; + while (left < right) { + const mid = (left + right) >> 1; + if (this.s[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left - 1; +}; +/** + * Your Solution object will be instantiated and called as such: + * var obj = new Solution(w) + * var param_1 = obj.pickIndex() + */ ``` + + diff --git a/solution/0500-0599/0528.Random Pick with Weight/README_EN.md b/solution/0500-0599/0528.Random Pick with Weight/README_EN.md index 22ebd5a16f90b..f201d822240fd 100644 --- a/solution/0500-0599/0528.Random Pick with Weight/README_EN.md +++ b/solution/0500-0599/0528.Random Pick with Weight/README_EN.md @@ -66,9 +66,9 @@ and so on. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -94,8 +94,6 @@ class Solution: # param_1 = obj.pickIndex() ``` -### **Java** - ```java class Solution { private int[] s; @@ -131,8 +129,6 @@ class Solution { */ ``` -### **C++** - ```cpp class Solution { public: @@ -166,8 +162,6 @@ public: */ ``` -### **Go** - ```go type Solution struct { s []int @@ -204,48 +198,6 @@ func (this *Solution) PickIndex() int { */ ``` -### **JavaScript** - -```js -/** - * @param {number[]} w - */ -var Solution = function (w) { - const n = w.length; - this.s = new Array(n + 1).fill(0); - for (let i = 0; i < n; ++i) { - this.s[i + 1] = this.s[i] + w[i]; - } -}; - -/** - * @return {number} - */ -Solution.prototype.pickIndex = function () { - const n = this.s.length; - const x = 1 + Math.floor(Math.random() * this.s[n - 1]); - let left = 1, - right = n - 1; - while (left < right) { - const mid = (left + right) >> 1; - if (this.s[mid] >= x) { - right = mid; - } else { - left = mid + 1; - } - } - return left - 1; -}; - -/** - * Your Solution object will be instantiated and called as such: - * var obj = new Solution(w) - * var param_1 = obj.pickIndex() - */ -``` - -### **Rust** - ```rust use rand::{ thread_rng, Rng }; @@ -287,10 +239,44 @@ impl Solution { */ ``` -### **...** +```js +/** + * @param {number[]} w + */ +var Solution = function (w) { + const n = w.length; + this.s = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + this.s[i + 1] = this.s[i] + w[i]; + } +}; -``` +/** + * @return {number} + */ +Solution.prototype.pickIndex = function () { + const n = this.s.length; + const x = 1 + Math.floor(Math.random() * this.s[n - 1]); + let left = 1, + right = n - 1; + while (left < right) { + const mid = (left + right) >> 1; + if (this.s[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left - 1; +}; +/** + * Your Solution object will be instantiated and called as such: + * var obj = new Solution(w) + * var param_1 = obj.pickIndex() + */ ``` + + diff --git a/solution/0500-0599/0529.Minesweeper/README.md b/solution/0500-0599/0529.Minesweeper/README.md index 16d01d4cc0a63..bd206fc6fb51e 100644 --- a/solution/0500-0599/0529.Minesweeper/README.md +++ b/solution/0500-0599/0529.Minesweeper/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们记 $click = (i, j)$,如果 $board[i][j]$ 等于 `'M'`,那么直接将 $board[i][j]$ 的值改为 `'X'` 即可。否则,我们需要统计 $board[i][j]$ 周围的地雷数量 $cnt$,如果 $cnt$ 不为 $0$,那么将 $board[i][j]$ 的值改为 $cnt$ 的字符串形式。否则,将 $board[i][j]$ 的值改为 `'B'`,并且递归地搜索处理 $board[i][j]$ 周围的未挖出的方块。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: @@ -103,10 +97,6 @@ class Solution: return board ``` -### **Java** - - - ```java class Solution { private char[][] board; @@ -151,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -193,8 +181,6 @@ public: }; ``` -### **Go** - ```go func updateBoard(board [][]byte, click []int) [][]byte { m, n := len(board), len(board[0]) @@ -233,8 +219,6 @@ func updateBoard(board [][]byte, click []int) [][]byte { } ``` -### **TypeScript** - ```ts function updateBoard(board: string[][], click: number[]): string[][] { const m = board.length; @@ -273,10 +257,6 @@ function updateBoard(board: string[][], click: number[]): string[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0529.Minesweeper/README_EN.md b/solution/0500-0599/0529.Minesweeper/README_EN.md index a71614af47fb9..3c5a3b7d19317 100644 --- a/solution/0500-0599/0529.Minesweeper/README_EN.md +++ b/solution/0500-0599/0529.Minesweeper/README_EN.md @@ -58,9 +58,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -89,8 +89,6 @@ class Solution: return board ``` -### **Java** - ```java class Solution { private char[][] board; @@ -135,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -177,8 +173,6 @@ public: }; ``` -### **Go** - ```go func updateBoard(board [][]byte, click []int) [][]byte { m, n := len(board), len(board[0]) @@ -217,8 +211,6 @@ func updateBoard(board [][]byte, click []int) [][]byte { } ``` -### **TypeScript** - ```ts function updateBoard(board: string[][], click: number[]): string[][] { const m = board.length; @@ -257,10 +249,6 @@ function updateBoard(board: string[][], click: number[]): string[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0530.Minimum Absolute Difference in BST/README.md b/solution/0500-0599/0530.Minimum Absolute Difference in BST/README.md index e0bc87ad091df..4a0be22689ff5 100644 --- a/solution/0500-0599/0530.Minimum Absolute Difference in BST/README.md +++ b/solution/0500-0599/0530.Minimum Absolute Difference in BST/README.md @@ -41,18 +41,12 @@ ## 解法 - - -**方法一:中序遍历** +### 方法一:中序遍历 中序遍历二叉搜索树,获取当前节点与上个节点差值的最小值即可。 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -76,10 +70,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -156,7 +144,39 @@ public: }; ``` -### **Rust** +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func getMinimumDifference(root *TreeNode) int { + inf := 0x3f3f3f3f + ans, prev := inf, inf + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return + } + dfs(root.Left) + ans = min(ans, abs(prev-root.Val)) + prev = root.Val + dfs(root.Right) + } + dfs(root) + return ans +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} +``` ```rust // Definition for a binary tree node. @@ -205,40 +225,6 @@ impl Solution { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func getMinimumDifference(root *TreeNode) int { - inf := 0x3f3f3f3f - ans, prev := inf, inf - var dfs func(*TreeNode) - dfs = func(root *TreeNode) { - if root == nil { - return - } - dfs(root.Left) - ans = min(ans, abs(prev-root.Val)) - prev = root.Val - dfs(root.Right) - } - dfs(root) - return ans -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x -} -``` - + + diff --git a/solution/0500-0599/0530.Minimum Absolute Difference in BST/README_EN.md b/solution/0500-0599/0530.Minimum Absolute Difference in BST/README_EN.md index 2974648e5f605..58c31235584c9 100644 --- a/solution/0500-0599/0530.Minimum Absolute Difference in BST/README_EN.md +++ b/solution/0500-0599/0530.Minimum Absolute Difference in BST/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -103,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -139,7 +135,39 @@ public: }; ``` -### **Rust** +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func getMinimumDifference(root *TreeNode) int { + inf := 0x3f3f3f3f + ans, prev := inf, inf + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return + } + dfs(root.Left) + ans = min(ans, abs(prev-root.Val)) + prev = root.Val + dfs(root.Right) + } + dfs(root) + return ans +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} +``` ```rust // Definition for a binary tree node. @@ -188,46 +216,6 @@ impl Solution { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func getMinimumDifference(root *TreeNode) int { - inf := 0x3f3f3f3f - ans, prev := inf, inf - var dfs func(*TreeNode) - dfs = func(root *TreeNode) { - if root == nil { - return - } - dfs(root.Left) - ans = min(ans, abs(prev-root.Val)) - prev = root.Val - dfs(root.Right) - } - dfs(root) - return ans -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0531.Lonely Pixel I/README.md b/solution/0500-0599/0531.Lonely Pixel I/README.md index 85ac4c0ee34de..f3022ad59d57a 100644 --- a/solution/0500-0599/0531.Lonely Pixel I/README.md +++ b/solution/0500-0599/0531.Lonely Pixel I/README.md @@ -40,16 +40,10 @@ ## 解法 - - -数组或哈希表统计每一行、每一列中 'B' 出现的次数。 +### 方法一 -### **Python3** - - - ```python class Solution: def findLonelyPixel(self, picture: List[List[str]]) -> int: @@ -70,10 +64,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int findLonelyPixel(char[][] picture) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func findLonelyPixel(picture [][]byte) int { m, n := len(picture), len(picture[0]) @@ -167,10 +153,6 @@ func findLonelyPixel(picture [][]byte) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0531.Lonely Pixel I/README_EN.md b/solution/0500-0599/0531.Lonely Pixel I/README_EN.md index aa038f1a39fec..e9ad13f339d9a 100644 --- a/solution/0500-0599/0531.Lonely Pixel I/README_EN.md +++ b/solution/0500-0599/0531.Lonely Pixel I/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public int findLonelyPixel(char[][] picture) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +121,6 @@ public: }; ``` -### **Go** - ```go func findLonelyPixel(picture [][]byte) int { m, n := len(picture), len(picture[0]) @@ -155,10 +149,6 @@ func findLonelyPixel(picture [][]byte) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0532.K-diff Pairs in an Array/README.md b/solution/0500-0599/0532.K-diff Pairs in an Array/README.md index 77c1a950baf34..97606a481bab5 100644 --- a/solution/0500-0599/0532.K-diff Pairs in an Array/README.md +++ b/solution/0500-0599/0532.K-diff Pairs in an Array/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 由于 $k$ 是一个定值,因此用哈希表 $ans$ 记录数对的较小值,就能够确定较大的值。最后返回 ans 的大小作为答案。 @@ -67,20 +65,8 @@ 时间复杂度 $O(n)$,其中 $n$ 表示数组 $nums$ 的长度。 -**方法二:排序 + 双指针** - -只需要统计组合的数量,因此可以改动原数组,对其排序,使用双指针来统计。 - -声明 `left` 与 `right` 指针,初始化为 0 和 1。根据 `abs(nums[left] - nums[right])` 与 `k` 值对比结果移动指针。 - -需要注意的是,**不能出现重复的组合**,所以移动指针时,不能仅仅是 `+1`,需要到一个不等于当前值的位置。 - -### **Python3** - - - ```python class Solution: def findPairs(self, nums: List[int], k: int) -> int: @@ -94,10 +80,6 @@ class Solution: return len(ans) ``` -### **Java** - - - ```java class Solution { public int findPairs(int[] nums, int k) { @@ -117,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +115,6 @@ public: }; ``` -### **Go** - ```go func findPairs(nums []int, k int) int { vis := map[int]bool{} @@ -154,8 +132,6 @@ func findPairs(nums []int, k int) int { } ``` -### **Rust** - ```rust impl Solution { pub fn find_pairs(mut nums: Vec, k: i32) -> i32 { @@ -189,10 +165,14 @@ impl Solution { } ``` -### **...** + -``` +### 方法二:排序 + 双指针 -``` +只需要统计组合的数量,因此可以改动原数组,对其排序,使用双指针来统计。 - +声明 `left` 与 `right` 指针,初始化为 0 和 1。根据 `abs(nums[left] - nums[right])` 与 `k` 值对比结果移动指针。 + +需要注意的是,**不能出现重复的组合**,所以移动指针时,不能仅仅是 `+1`,需要到一个不等于当前值的位置。 + + diff --git a/solution/0500-0599/0532.K-diff Pairs in an Array/README_EN.md b/solution/0500-0599/0532.K-diff Pairs in an Array/README_EN.md index bdd6b0af37719..20ba1e3dd7561 100644 --- a/solution/0500-0599/0532.K-diff Pairs in an Array/README_EN.md +++ b/solution/0500-0599/0532.K-diff Pairs in an Array/README_EN.md @@ -53,9 +53,9 @@ Although we have two 1s in the input, we should only return the number of +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return len(ans) ``` -### **Java** - ```java class Solution { public int findPairs(int[] nums, int k) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +105,6 @@ public: }; ``` -### **Go** - ```go func findPairs(nums []int, k int) int { vis := map[int]bool{} @@ -128,8 +122,6 @@ func findPairs(nums []int, k int) int { } ``` -### **Rust** - ```rust impl Solution { pub fn find_pairs(mut nums: Vec, k: i32) -> i32 { @@ -163,10 +155,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0533.Lonely Pixel II/README.md b/solution/0500-0599/0533.Lonely Pixel II/README.md index 11533250779a9..42000f316067b 100644 --- a/solution/0500-0599/0533.Lonely Pixel II/README.md +++ b/solution/0500-0599/0533.Lonely Pixel II/README.md @@ -49,16 +49,10 @@ ## 解法 - - -“哈希表”实现。 +### 方法一 -### **Python3** - - - ```python class Solution: def findBlackPixel(self, picture: List[List[str]], target: int) -> int: @@ -87,10 +81,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int findBlackPixel(char[][] picture, int target) { @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -192,8 +180,6 @@ public: }; ``` -### **Go** - ```go func findBlackPixel(picture [][]byte, target int) int { m, n := len(picture), len(picture[0]) @@ -252,10 +238,6 @@ func all(row1, row2 []byte) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0533.Lonely Pixel II/README_EN.md b/solution/0500-0599/0533.Lonely Pixel II/README_EN.md index 38e951298573d..99004ca026bdf 100644 --- a/solution/0500-0599/0533.Lonely Pixel II/README_EN.md +++ b/solution/0500-0599/0533.Lonely Pixel II/README_EN.md @@ -45,9 +45,9 @@ Take 'B' at row r = 0 and column c = 1 as an example: ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public int findBlackPixel(char[][] picture, int target) { @@ -132,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -180,8 +176,6 @@ public: }; ``` -### **Go** - ```go func findBlackPixel(picture [][]byte, target int) int { m, n := len(picture), len(picture[0]) @@ -240,10 +234,6 @@ func all(row1, row2 []byte) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0534.Game Play Analysis III/README.md b/solution/0500-0599/0534.Game Play Analysis III/README.md index 6b793484d7efe..497b23def4f78 100644 --- a/solution/0500-0599/0534.Game Play Analysis III/README.md +++ b/solution/0500-0599/0534.Game Play Analysis III/README.md @@ -64,20 +64,12 @@ Activity table: ## 解法 - - -**方法一:使用窗口函数** +### 方法一:使用窗口函数 我们可以使用窗口函数 `SUM() OVER()`,按照 `player_id` 分组,按照 `event_date` 排序,计算每个用户截止到当前日期的游戏总数。 -**方法二:使用自连接 + 分组** - -我们也可以使用自连接,将 `Activity` 表自连接,连接条件为 `t1.player_id = t2.player_id AND t1.event_date >= t2.event_date`,然后按照 `t1.player_id` 和 `t1.event_date` 分组,累计 `t2.games_played`,得到每个用户截止到当前日期的游戏总数。 - -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -90,6 +82,14 @@ SELECT FROM Activity; ``` + + +### 方法二:使用自连接 + 分组 + +我们也可以使用自连接,将 `Activity` 表自连接,连接条件为 `t1.player_id = t2.player_id AND t1.event_date >= t2.event_date`,然后按照 `t1.player_id` 和 `t1.event_date` 分组,累计 `t2.games_played`,得到每个用户截止到当前日期的游戏总数。 + + + ```sql # Write your MySQL query statement below SELECT @@ -103,6 +103,12 @@ WHERE t1.player_id = t2.player_id AND t1.event_date >= t2.event_date GROUP BY 1, 2; ``` + + +### 方法三 + + + ```sql # Write your MySQL query statement below SELECT @@ -116,3 +122,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/0500-0599/0534.Game Play Analysis III/README_EN.md b/solution/0500-0599/0534.Game Play Analysis III/README_EN.md index 2fbca0d36af0e..bd8fbf3d1fc9d 100644 --- a/solution/0500-0599/0534.Game Play Analysis III/README_EN.md +++ b/solution/0500-0599/0534.Game Play Analysis III/README_EN.md @@ -61,18 +61,12 @@ Note that for each player we only care about the days when the player logged in. ## Solutions -**Solution 1: Window Function** +### Solution 1: Window Function We can use the window function `SUM() OVER()` to group by `player_id`, sort by `event_date`, and calculate the total number of games played by each user up to the current date. -**Solution 2: Self-Join + Group By** - -We can also use a self-join to join the `Activity` table with itself on the condition of `t1.player_id = t2.player_id AND t1.event_date >= t2.event_date`, and then group by `t1.player_id` and `t1.event_date`, and calculate the cumulative sum of `t2.games_played`. This will give us the total number of games played by each user up to the current date. - -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -85,6 +79,14 @@ SELECT FROM Activity; ``` + + +### Solution 2: Self-Join + Group By + +We can also use a self-join to join the `Activity` table with itself on the condition of `t1.player_id = t2.player_id AND t1.event_date >= t2.event_date`, and then group by `t1.player_id` and `t1.event_date`, and calculate the cumulative sum of `t2.games_played`. This will give us the total number of games played by each user up to the current date. + + + ```sql # Write your MySQL query statement below SELECT @@ -98,6 +100,12 @@ WHERE t1.player_id = t2.player_id AND t1.event_date >= t2.event_date GROUP BY 1, 2; ``` + + +### Solution 3 + + + ```sql # Write your MySQL query statement below SELECT @@ -111,3 +119,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/0500-0599/0535.Encode and Decode TinyURL/README.md b/solution/0500-0599/0535.Encode and Decode TinyURL/README.md index 0b4a30c240405..cd6bca705a1e3 100644 --- a/solution/0500-0599/0535.Encode and Decode TinyURL/README.md +++ b/solution/0500-0599/0535.Encode and Decode TinyURL/README.md @@ -47,16 +47,10 @@ string ans = obj.decode(tiny); // 返回解密后得到的原本的 URL 。 ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 -### **Python3** - - - ```python class Codec: def __init__(self): @@ -81,10 +75,6 @@ class Codec: # codec.decode(codec.encode(url)) ``` -### **Java** - - - ```java public class Codec { private Map m = new HashMap<>(); @@ -110,8 +100,6 @@ public class Codec { // codec.decode(codec.encode(url)); ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +127,6 @@ private: // solution.decode(solution.encode(url)); ``` -### **Go** - ```go type Codec struct { m map[int]string @@ -174,10 +160,6 @@ func (this *Codec) decode(shortUrl string) string { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0535.Encode and Decode TinyURL/README_EN.md b/solution/0500-0599/0535.Encode and Decode TinyURL/README_EN.md index 044a06e819f5e..a60df8e80d639 100644 --- a/solution/0500-0599/0535.Encode and Decode TinyURL/README_EN.md +++ b/solution/0500-0599/0535.Encode and Decode TinyURL/README_EN.md @@ -41,9 +41,9 @@ string ans = obj.decode(tiny); // returns the original url after decoding it. ## Solutions - +### Solution 1 -### **Python3** + ```python class Codec: @@ -69,8 +69,6 @@ class Codec: # codec.decode(codec.encode(url)) ``` -### **Java** - ```java public class Codec { private Map m = new HashMap<>(); @@ -96,8 +94,6 @@ public class Codec { // codec.decode(codec.encode(url)); ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +121,6 @@ private: // solution.decode(solution.encode(url)); ``` -### **Go** - ```go type Codec struct { m map[int]string @@ -160,10 +154,6 @@ func (this *Codec) decode(shortUrl string) string { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0536.Construct Binary Tree from String/README.md b/solution/0500-0599/0536.Construct Binary Tree from String/README.md index 92e178fdb387e..ee7289556dd7b 100644 --- a/solution/0500-0599/0536.Construct Binary Tree from String/README.md +++ b/solution/0500-0599/0536.Construct Binary Tree from String/README.md @@ -47,18 +47,10 @@ ## 解法 - - -DFS。 - -利用 cnt 变量,检测子树的位置,若 cnt == 0,说明已经定位到其中一棵子树,start 表示子树开始的位置(注意要去掉括号)。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -93,10 +85,6 @@ class Solution: return dfs(s) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -149,8 +137,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -194,8 +180,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -241,10 +225,6 @@ func str2tree(s string) *TreeNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0536.Construct Binary Tree from String/README_EN.md b/solution/0500-0599/0536.Construct Binary Tree from String/README_EN.md index e493fc8210036..8377806ae5e33 100644 --- a/solution/0500-0599/0536.Construct Binary Tree from String/README_EN.md +++ b/solution/0500-0599/0536.Construct Binary Tree from String/README_EN.md @@ -42,12 +42,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -82,8 +80,6 @@ class Solution: return dfs(s) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -136,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -181,8 +175,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -228,10 +220,6 @@ func str2tree(s string) *TreeNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0537.Complex Number Multiplication/README.md b/solution/0500-0599/0537.Complex Number Multiplication/README.md index 6642ee7a63a7b..73d2f2d6c379b 100644 --- a/solution/0500-0599/0537.Complex Number Multiplication/README.md +++ b/solution/0500-0599/0537.Complex Number Multiplication/README.md @@ -44,16 +44,10 @@ ## 解法 - - -`(a+bi)(c+di) = ac-bd+(ad+cb)i`。 +### 方法一 -### **Python3** - - - ```python class Solution: def complexNumberMultiply(self, num1: str, num2: str) -> str: @@ -62,10 +56,6 @@ class Solution: return f'{a * c - b * d}+{a * d + c * b}i' ``` -### **Java** - - - ```java class Solution { public String complexNumberMultiply(String num1, String num2) { @@ -80,24 +70,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function complexNumberMultiply(num1: string, num2: string): string { - let arr1 = num1.split('+'), - arr2 = num2.split('+'); - let r1 = Number(arr1[0]), - r2 = Number(arr2[0]); - let v1 = Number(arr1[1].substring(0, arr1[1].length - 1)), - v2 = Number(arr2[1].substring(0, arr2[1].length - 1)); - let ansR = r1 * r2 - v1 * v2; - let ansV = r1 * v2 + r2 * v1; - return `${ansR}+${ansV}i`; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -110,8 +82,6 @@ public: }; ``` -### **Go** - ```go func complexNumberMultiply(num1, num2 string) string { parse := func(num string) (a, b int) { @@ -126,10 +96,20 @@ func complexNumberMultiply(num1, num2 string) string { } ``` -### **...** - -``` - +```ts +function complexNumberMultiply(num1: string, num2: string): string { + let arr1 = num1.split('+'), + arr2 = num2.split('+'); + let r1 = Number(arr1[0]), + r2 = Number(arr2[0]); + let v1 = Number(arr1[1].substring(0, arr1[1].length - 1)), + v2 = Number(arr2[1].substring(0, arr2[1].length - 1)); + let ansR = r1 * r2 - v1 * v2; + let ansV = r1 * v2 + r2 * v1; + return `${ansR}+${ansV}i`; +} ``` + + diff --git a/solution/0500-0599/0537.Complex Number Multiplication/README_EN.md b/solution/0500-0599/0537.Complex Number Multiplication/README_EN.md index 4f2699927e527..df82279c5dd9f 100644 --- a/solution/0500-0599/0537.Complex Number Multiplication/README_EN.md +++ b/solution/0500-0599/0537.Complex Number Multiplication/README_EN.md @@ -40,12 +40,10 @@ ## Solutions -`(a+bi)(c+di) = ac-bd+(ad+cb)i` +### Solution 1 -### **Python3** - ```python class Solution: def complexNumberMultiply(self, num1: str, num2: str) -> str: @@ -54,8 +52,6 @@ class Solution: return f'{a * c - b * d}+{a * d + c * b}i' ``` -### **Java** - ```java class Solution { public String complexNumberMultiply(String num1, String num2) { @@ -70,24 +66,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function complexNumberMultiply(num1: string, num2: string): string { - let arr1 = num1.split('+'), - arr2 = num2.split('+'); - let r1 = Number(arr1[0]), - r2 = Number(arr2[0]); - let v1 = Number(arr1[1].substring(0, arr1[1].length - 1)), - v2 = Number(arr2[1].substring(0, arr2[1].length - 1)); - let ansR = r1 * r2 - v1 * v2; - let ansV = r1 * v2 + r2 * v1; - return `${ansR}+${ansV}i`; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -100,8 +78,6 @@ public: }; ``` -### **Go** - ```go func complexNumberMultiply(num1, num2 string) string { parse := func(num string) (a, b int) { @@ -116,10 +92,20 @@ func complexNumberMultiply(num1, num2 string) string { } ``` -### **...** - -``` - +```ts +function complexNumberMultiply(num1: string, num2: string): string { + let arr1 = num1.split('+'), + arr2 = num2.split('+'); + let r1 = Number(arr1[0]), + r2 = Number(arr2[0]); + let v1 = Number(arr1[1].substring(0, arr1[1].length - 1)), + v2 = Number(arr2[1].substring(0, arr2[1].length - 1)); + let ansR = r1 * r2 - v1 * v2; + let ansV = r1 * v2 + r2 * v1; + return `${ansR}+${ansV}i`; +} ``` + + diff --git a/solution/0500-0599/0538.Convert BST to Greater Tree/README.md b/solution/0500-0599/0538.Convert BST to Greater Tree/README.md index 110637b8a0d11..13f64ab07558a 100644 --- a/solution/0500-0599/0538.Convert BST to Greater Tree/README.md +++ b/solution/0500-0599/0538.Convert BST to Greater Tree/README.md @@ -59,43 +59,14 @@ ## 解法 - - -**前言** - -二叉搜索树的中序遍历(左根右)结果是一个单调递增的有序序列,我们反序进行中序遍历(右根左),即可以得到一个单调递减的有序序列。通过累加单调递减的有序序列,我们可以得到大于等于 `node.val` 的新值,并重新赋值给 `node`。 - -关于反序中序遍历,有三种方法,一是递归遍历,二是栈实现非递归遍历,三是 Morris 遍历。 - -**方法一:递归** +### 方法一:递归 按照“右根左”的顺序,递归遍历二叉搜索树,累加遍历到的所有节点值到 $s$ 中,然后每次赋值给对应的 `node` 节点。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉搜索树的节点数。 -**方法二:Morris 遍历** - -Morris 遍历无需使用栈,时间复杂度 $O(n)$,空间复杂度为 $O(1)$。核心思想是: - -定义 s 表示二叉搜索树节点值累加和。遍历二叉树节点: - -1. 若当前节点 root 的右子树为空,**将当前节点值添加至 s** 中,更新当前节点值为 s,并将当前节点更新为 `root.left`。 -2. 若当前节点 root 的右子树不为空,找到右子树的最左节点 next(也即是 root 节点在中序遍历下的后继节点): - - 若后继节点 next 的左子树为空,将后继节点的左子树指向当前节点 root,并将当前节点更新为 `root.right`。 - - 若后继节点 next 的左子树不为空,**将当前节点值添加 s** 中,更新当前节点值为 s,然后将后继节点左子树指向空(即解除 next 与 root 的指向关系),并将当前节点更新为 `root.left`。 -3. 循环以上步骤,直至二叉树节点为空,遍历结束。 -4. 最后返回二叉搜索树根节点即可。 - -> Morris 反序中序遍历跟 Morris 中序遍历思路一致,只是将中序遍历的“左根右”变为“右根左”。 - -### **Python3** - - - -递归遍历: - ```python # Definition for a binary tree node. # class TreeNode: @@ -119,45 +90,6 @@ class Solution: return root ``` -Morris 遍历: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def convertBST(self, root: TreeNode) -> TreeNode: - s = 0 - node = root - while root: - if root.right is None: - s += root.val - root.val = s - root = root.left - else: - next = root.right - while next.left and next.left != root: - next = next.left - if next.left is None: - next.left = root - root = root.right - else: - s += root.val - root.val = s - next.left = None - root = root.left - return node -``` - -### **Java** - - - -递归遍历: - ```java /** * Definition for a binary tree node. @@ -194,7 +126,141 @@ class Solution { } ``` -Morris 遍历: +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int s = 0; + + TreeNode* convertBST(TreeNode* root) { + dfs(root); + return root; + } + + void dfs(TreeNode* root) { + if (!root) return; + dfs(root->right); + s += root->val; + root->val = s; + dfs(root->left); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func convertBST(root *TreeNode) *TreeNode { + s := 0 + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return + } + dfs(root.Right) + s += root.Val + root.Val = s + dfs(root.Left) + } + dfs(root) + return root +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {TreeNode} + */ +var convertBST = function (root) { + let s = 0; + function dfs(root) { + if (!root) { + return; + } + dfs(root.right); + s += root.val; + root.val = s; + dfs(root.left); + } + dfs(root); + return root; +}; +``` + + + +### 方法二:Morris 遍历 + +Morris 遍历无需使用栈,时间复杂度 $O(n)$,空间复杂度为 $O(1)$。核心思想是: + +定义 s 表示二叉搜索树节点值累加和。遍历二叉树节点: + +1. 若当前节点 root 的右子树为空,**将当前节点值添加至 s** 中,更新当前节点值为 s,并将当前节点更新为 `root.left`。 +2. 若当前节点 root 的右子树不为空,找到右子树的最左节点 next(也即是 root 节点在中序遍历下的后继节点): + - 若后继节点 next 的左子树为空,将后继节点的左子树指向当前节点 root,并将当前节点更新为 `root.right`。 + - 若后继节点 next 的左子树不为空,**将当前节点值添加 s** 中,更新当前节点值为 s,然后将后继节点左子树指向空(即解除 next 与 root 的指向关系),并将当前节点更新为 `root.left`。 +3. 循环以上步骤,直至二叉树节点为空,遍历结束。 +4. 最后返回二叉搜索树根节点即可。 + +> Morris 反序中序遍历跟 Morris 中序遍历思路一致,只是将中序遍历的“左根右”变为“右根左”。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def convertBST(self, root: TreeNode) -> TreeNode: + s = 0 + node = root + while root: + if root.right is None: + s += root.val + root.val = s + root = root.left + else: + next = root.right + while next.left and next.left != root: + next = next.left + if next.left is None: + next.left = root + root = root.right + else: + s += root.val + root.val = s + next.left = None + root = root.left + return node +``` ```java /** @@ -242,43 +308,6 @@ class Solution { } ``` -### **C++** - -递归遍历: - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int s = 0; - - TreeNode* convertBST(TreeNode* root) { - dfs(root); - return root; - } - - void dfs(TreeNode* root) { - if (!root) return; - dfs(root->right); - s += root->val; - root->val = s; - dfs(root->left); - } -}; -``` - -Morris 遍历: - ```cpp /** * Definition for a binary tree node. @@ -322,38 +351,6 @@ public: }; ``` -### **Go** - -递归遍历: - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func convertBST(root *TreeNode) *TreeNode { - s := 0 - var dfs func(*TreeNode) - dfs = func(root *TreeNode) { - if root == nil { - return - } - dfs(root.Right) - s += root.Val - root.Val = s - dfs(root.Left) - } - dfs(root) - return root -} -``` - -Morris 遍历: - ```go /** * Definition for a binary tree node. @@ -391,41 +388,6 @@ func convertBST(root *TreeNode) *TreeNode { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {TreeNode} - */ -var convertBST = function (root) { - let s = 0; - function dfs(root) { - if (!root) { - return; - } - dfs(root.right); - s += root.val; - root.val = s; - dfs(root.left); - } - dfs(root); - return root; -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0538.Convert BST to Greater Tree/README_EN.md b/solution/0500-0599/0538.Convert BST to Greater Tree/README_EN.md index ecb8455a2a18b..115358a842df2 100644 --- a/solution/0500-0599/0538.Convert BST to Greater Tree/README_EN.md +++ b/solution/0500-0599/0538.Convert BST to Greater Tree/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -71,39 +71,6 @@ class Solution: return root ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def convertBST(self, root: TreeNode) -> TreeNode: - s = 0 - node = root - while root: - if root.right is None: - s += root.val - root.val = s - root = root.left - else: - next = root.right - while next.left and next.left != root: - next = next.left - if next.left is None: - next.left = root - root = root.right - else: - s += root.val - root.val = s - next.left = None - root = root.left - return node -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -140,6 +107,129 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int s = 0; + + TreeNode* convertBST(TreeNode* root) { + dfs(root); + return root; + } + + void dfs(TreeNode* root) { + if (!root) return; + dfs(root->right); + s += root->val; + root->val = s; + dfs(root->left); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func convertBST(root *TreeNode) *TreeNode { + s := 0 + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return + } + dfs(root.Right) + s += root.Val + root.Val = s + dfs(root.Left) + } + dfs(root) + return root +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {TreeNode} + */ +var convertBST = function (root) { + let s = 0; + function dfs(root) { + if (!root) { + return; + } + dfs(root.right); + s += root.val; + root.val = s; + dfs(root.left); + } + dfs(root); + return root; +}; +``` + + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def convertBST(self, root: TreeNode) -> TreeNode: + s = 0 + node = root + while root: + if root.right is None: + s += root.val + root.val = s + root = root.left + else: + next = root.right + while next.left and next.left != root: + next = next.left + if next.left is None: + next.left = root + root = root.right + else: + s += root.val + root.val = s + next.left = None + root = root.left + return node +``` + ```java /** * Definition for a binary tree node. @@ -186,39 +276,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int s = 0; - - TreeNode* convertBST(TreeNode* root) { - dfs(root); - return root; - } - - void dfs(TreeNode* root) { - if (!root) return; - dfs(root->right); - s += root->val; - root->val = s; - dfs(root->left); - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -262,33 +319,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func convertBST(root *TreeNode) *TreeNode { - add := 0 - var dfs func(*TreeNode) - dfs = func(node *TreeNode) { - if node != nil { - dfs(node.Right) - node.Val += add - add = node.Val - dfs(node.Left) - } - } - dfs(root) - return root -} -``` - ```go /** * Definition for a binary tree node. @@ -326,41 +356,6 @@ func convertBST(root *TreeNode) *TreeNode { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {TreeNode} - */ -var convertBST = function (root) { - let s = 0; - function dfs(root) { - if (!root) { - return; - } - dfs(root.right); - s += root.val; - root.val = s; - dfs(root.left); - } - dfs(root); - return root; -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0539.Minimum Time Difference/README.md b/solution/0500-0599/0539.Minimum Time Difference/README.md index 7c2107c5accc3..4b557dc145541 100644 --- a/solution/0500-0599/0539.Minimum Time Difference/README.md +++ b/solution/0500-0599/0539.Minimum Time Difference/README.md @@ -35,24 +35,10 @@ ## 解法 - - -我们注意到,时间点最多只有 `24 * 60` 个,因此,当 timePoints 长度超过 `24 * 60`,说明有重复的时间点,提前返回 0。 - -接下来: - -首先,遍历时间列表,将其转换为“分钟制”列表 `mins`,比如,对于时间点 `13:14`,将其转换为 `13 * 60 + 14`。 - -接着将“分钟制”列表按升序排列,然后将此列表的最小时间 `mins[0]` 加上 `24 * 60` 追加至列表尾部,用于处理最大值、最小值的差值这种特殊情况。 - -最后遍历“分钟制”列表,找出相邻两个时间的最小值即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def findMinDifference(self, timePoints: List[str]) -> int: @@ -66,10 +52,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int findMinDifference(List timePoints) { @@ -92,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +93,6 @@ public: }; ``` -### **Go** - ```go func findMinDifference(timePoints []string) int { if len(timePoints) > 24*60 { @@ -137,8 +115,6 @@ func findMinDifference(timePoints []string) int { } ``` -### **TypeScript** - ```ts function findMinDifference(timePoints: string[]): number { const mins = timePoints @@ -158,10 +134,6 @@ function findMinDifference(timePoints: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0539.Minimum Time Difference/README_EN.md b/solution/0500-0599/0539.Minimum Time Difference/README_EN.md index 7fea6696da7f3..d0461548c7d62 100644 --- a/solution/0500-0599/0539.Minimum Time Difference/README_EN.md +++ b/solution/0500-0599/0539.Minimum Time Difference/README_EN.md @@ -24,15 +24,10 @@ Given a list of 24-hour clock time points in "HH:MM" ## Solutions -1. Convert all the times into minutes values `mins`, i.e. `13:14` => `13 * 60 + 14`. -2. Sort the `mins`. -3. Push the time `mins[0] + 24 * 60` to deal with min and max diff. -4. For each value in `mins[1:]`, calculate the min diff `mins[i] - mins[i - 1]`. +### Solution 1 -### **Python3** - ```python class Solution: def findMinDifference(self, timePoints: List[str]) -> int: @@ -46,8 +41,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public int findMinDifference(List timePoints) { @@ -70,8 +63,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +82,6 @@ public: }; ``` -### **Go** - ```go func findMinDifference(timePoints []string) int { if len(timePoints) > 24*60 { @@ -115,8 +104,6 @@ func findMinDifference(timePoints []string) int { } ``` -### **TypeScript** - ```ts function findMinDifference(timePoints: string[]): number { const mins = timePoints @@ -136,10 +123,6 @@ function findMinDifference(timePoints: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0540.Single Element in a Sorted Array/README.md b/solution/0500-0599/0540.Single Element in a Sorted Array/README.md index 95ebb3c67d4fa..89da2896a4621 100644 --- a/solution/0500-0599/0540.Single Element in a Sorted Array/README.md +++ b/solution/0500-0599/0540.Single Element in a Sorted Array/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 给与的数组是有序的,由此可以使用二分查找,那条件该如何判断呢。 @@ -83,10 +81,6 @@ return nums[l] -### **Python3** - - - ```python class Solution: def singleNonDuplicate(self, nums: List[int]) -> int: @@ -101,10 +95,6 @@ class Solution: return nums[left] ``` -### **Java** - - - ```java class Solution { public int singleNonDuplicate(int[] nums) { @@ -124,44 +114,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function singleNonDuplicate(nums: number[]): number { - let left = 0, - right = nums.length - 1; - while (left < right) { - const mid = (left + right) >> 1; - if (nums[mid] != nums[mid ^ 1]) { - right = mid; - } else { - left = mid + 1; - } - } - return nums[left]; -} -``` - -### **C** - -```c -int singleNonDuplicate(int* nums, int numsSize) { - int left = 0; - int right = numsSize - 1; - while (left < right) { - int mid = left + (right - left) / 2; - if (nums[mid] == nums[mid ^ 1]) { - left = mid + 1; - } else { - right = mid; - } - } - return nums[left]; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -179,8 +131,6 @@ public: }; ``` -### **Go** - ```go func singleNonDuplicate(nums []int) int { left, right := 0, len(nums)-1 @@ -196,7 +146,21 @@ func singleNonDuplicate(nums []int) int { } ``` -### **Rust** +```ts +function singleNonDuplicate(nums: number[]): number { + let left = 0, + right = nums.length - 1; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] != nums[mid ^ 1]) { + right = mid; + } else { + left = mid + 1; + } + } + return nums[left]; +} +``` ```rust impl Solution { @@ -216,10 +180,22 @@ impl Solution { } ``` -### **...** - -``` - +```c +int singleNonDuplicate(int* nums, int numsSize) { + int left = 0; + int right = numsSize - 1; + while (left < right) { + int mid = left + (right - left) / 2; + if (nums[mid] == nums[mid ^ 1]) { + left = mid + 1; + } else { + right = mid; + } + } + return nums[left]; +} ``` + + diff --git a/solution/0500-0599/0540.Single Element in a Sorted Array/README_EN.md b/solution/0500-0599/0540.Single Element in a Sorted Array/README_EN.md index 7b48f732ad962..c203b263d50da 100644 --- a/solution/0500-0599/0540.Single Element in a Sorted Array/README_EN.md +++ b/solution/0500-0599/0540.Single Element in a Sorted Array/README_EN.md @@ -28,12 +28,10 @@ ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python class Solution: def singleNonDuplicate(self, nums: List[int]) -> int: @@ -48,8 +46,6 @@ class Solution: return nums[left] ``` -### **Java** - ```java class Solution { public int singleNonDuplicate(int[] nums) { @@ -69,44 +65,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function singleNonDuplicate(nums: number[]): number { - let left = 0, - right = nums.length - 1; - while (left < right) { - const mid = (left + right) >> 1; - if (nums[mid] != nums[mid ^ 1]) { - right = mid; - } else { - left = mid + 1; - } - } - return nums[left]; -} -``` - -### **C** - -```c -int singleNonDuplicate(int* nums, int numsSize) { - int left = 0; - int right = numsSize - 1; - while (left < right) { - int mid = left + (right - left) / 2; - if (nums[mid] == nums[mid ^ 1]) { - left = mid + 1; - } else { - right = mid; - } - } - return nums[left]; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -124,8 +82,6 @@ public: }; ``` -### **Go** - ```go func singleNonDuplicate(nums []int) int { left, right := 0, len(nums)-1 @@ -141,7 +97,21 @@ func singleNonDuplicate(nums []int) int { } ``` -### **Rust** +```ts +function singleNonDuplicate(nums: number[]): number { + let left = 0, + right = nums.length - 1; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] != nums[mid ^ 1]) { + right = mid; + } else { + left = mid + 1; + } + } + return nums[left]; +} +``` ```rust impl Solution { @@ -161,10 +131,22 @@ impl Solution { } ``` -### **...** - -``` - +```c +int singleNonDuplicate(int* nums, int numsSize) { + int left = 0; + int right = numsSize - 1; + while (left < right) { + int mid = left + (right - left) / 2; + if (nums[mid] == nums[mid ^ 1]) { + left = mid + 1; + } else { + right = mid; + } + } + return nums[left]; +} ``` + + diff --git a/solution/0500-0599/0541.Reverse String II/README.md b/solution/0500-0599/0541.Reverse String II/README.md index 6990077d7e2fb..bfb924df4e867 100644 --- a/solution/0500-0599/0541.Reverse String II/README.md +++ b/solution/0500-0599/0541.Reverse String II/README.md @@ -41,14 +41,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def reverseStr(self, s: str, k: int) -> str: @@ -58,10 +54,6 @@ class Solution: return ''.join(t) ``` -### **Java** - - - ```java class Solution { public String reverseStr(String s, int k) { @@ -78,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -92,8 +82,6 @@ public: }; ``` -### **Go** - ```go func reverseStr(s string, k int) string { t := []byte(s) @@ -106,10 +94,6 @@ func reverseStr(s string, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0541.Reverse String II/README_EN.md b/solution/0500-0599/0541.Reverse String II/README_EN.md index 33dcfa87ab967..4994ae2a36e75 100644 --- a/solution/0500-0599/0541.Reverse String II/README_EN.md +++ b/solution/0500-0599/0541.Reverse String II/README_EN.md @@ -27,9 +27,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -40,8 +40,6 @@ class Solution: return ''.join(t) ``` -### **Java** - ```java class Solution { public String reverseStr(String s, int k) { @@ -58,8 +56,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -72,8 +68,6 @@ public: }; ``` -### **Go** - ```go func reverseStr(s string, k int) string { t := []byte(s) @@ -86,10 +80,6 @@ func reverseStr(s string, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0542.01 Matrix/README.md b/solution/0500-0599/0542.01 Matrix/README.md index 3943b18297a26..4ccd24436596e 100644 --- a/solution/0500-0599/0542.01 Matrix/README.md +++ b/solution/0500-0599/0542.01 Matrix/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:多源 BFS** +### 方法一:多源 BFS 初始化结果矩阵 ans,所有 0 的距离为 0,所以 1 的距离为 -1。初始化队列 q 存储 BFS 需要检查的位置,并将所有 0 的位置入队。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] updateMatrix(int[][] mat) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,62 +142,6 @@ public: }; ``` -### **Rust** - -```rust -use std::collections::VecDeque; - -impl Solution { - #[allow(dead_code)] - pub fn update_matrix(mat: Vec>) -> Vec> { - let n: usize = mat.len(); - let m: usize = mat[0].len(); - let mut ret_vec: Vec> = vec![vec![-1; m]; n]; - // The inner tuple is of - let mut the_q: VecDeque<(usize, usize)> = VecDeque::new(); - let traverse_vec: Vec<(i32, i32)> = vec![(-1, 0), (1, 0), (0, 1), (0, -1)]; - - // Initialize the queue - for i in 0..n { - for j in 0..m { - if mat[i][j] == 0 { - // For the zero cell, enqueue at first - the_q.push_back((i, j)); - // Set to 0 in return vector - ret_vec[i][j] = 0; - } - } - } - - while !the_q.is_empty() { - let (x, y) = the_q.front().unwrap().clone(); - the_q.pop_front(); - for pair in &traverse_vec { - let cur_x = pair.0 + (x as i32); - let cur_y = pair.1 + (y as i32); - if - Solution::check_bounds(cur_x, cur_y, n as i32, m as i32) && - ret_vec[cur_x as usize][cur_y as usize] == -1 - { - // The current cell has not be updated yet, and is also in bound - ret_vec[cur_x as usize][cur_y as usize] = ret_vec[x][y] + 1; - the_q.push_back((cur_x as usize, cur_y as usize)); - } - } - } - - ret_vec - } - - #[allow(dead_code)] - pub fn check_bounds(i: i32, j: i32, n: i32, m: i32) -> bool { - i >= 0 && i < n && j >= 0 && j < m - } -} -``` - -### **Go** - ```go func updateMatrix(mat [][]int) [][]int { m, n := len(mat), len(mat[0]) @@ -246,8 +178,6 @@ func updateMatrix(mat [][]int) [][]int { } ``` -### **TypeScript** - ```ts function updateMatrix(mat: number[][]): number[][] { const [m, n] = [mat.length, mat[0].length]; @@ -276,10 +206,58 @@ function updateMatrix(mat: number[][]): number[][] { } ``` -### **...** +```rust +use std::collections::VecDeque; -``` +impl Solution { + #[allow(dead_code)] + pub fn update_matrix(mat: Vec>) -> Vec> { + let n: usize = mat.len(); + let m: usize = mat[0].len(); + let mut ret_vec: Vec> = vec![vec![-1; m]; n]; + // The inner tuple is of + let mut the_q: VecDeque<(usize, usize)> = VecDeque::new(); + let traverse_vec: Vec<(i32, i32)> = vec![(-1, 0), (1, 0), (0, 1), (0, -1)]; + // Initialize the queue + for i in 0..n { + for j in 0..m { + if mat[i][j] == 0 { + // For the zero cell, enqueue at first + the_q.push_back((i, j)); + // Set to 0 in return vector + ret_vec[i][j] = 0; + } + } + } + + while !the_q.is_empty() { + let (x, y) = the_q.front().unwrap().clone(); + the_q.pop_front(); + for pair in &traverse_vec { + let cur_x = pair.0 + (x as i32); + let cur_y = pair.1 + (y as i32); + if + Solution::check_bounds(cur_x, cur_y, n as i32, m as i32) && + ret_vec[cur_x as usize][cur_y as usize] == -1 + { + // The current cell has not be updated yet, and is also in bound + ret_vec[cur_x as usize][cur_y as usize] = ret_vec[x][y] + 1; + the_q.push_back((cur_x as usize, cur_y as usize)); + } + } + } + + ret_vec + } + + #[allow(dead_code)] + pub fn check_bounds(i: i32, j: i32, n: i32, m: i32) -> bool { + i >= 0 && i < n && j >= 0 && j < m + } +} ``` + + diff --git a/solution/0500-0599/0542.01 Matrix/README_EN.md b/solution/0500-0599/0542.01 Matrix/README_EN.md index a64d858de769e..d6f9476a437e3 100644 --- a/solution/0500-0599/0542.01 Matrix/README_EN.md +++ b/solution/0500-0599/0542.01 Matrix/README_EN.md @@ -37,22 +37,10 @@ ## Solutions -**Method One: Multi-source BFS** - -Initialize the result matrix ans, where the distance of all zeros is 0, and thus the distance of all ones is -1. - -Initialize a queue q to store the positions to be checked by BFS, and enqueue all positions of zeros. - -Continually dequeue elements `p(i, j)` from queue q, inspecting the four neighboring points. - -For each neighbor `(x, y)`, if `ans[x][y] = -1`, then update `ans[x][y] = ans[i][j] + 1`. - -Also, enqueue the position `(x, y)`. +### Solution 1 -### **Python3** - ```python class Solution: def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: @@ -75,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] updateMatrix(int[][] mat) { @@ -111,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,62 +130,6 @@ public: }; ``` -### **Rust** - -```rust -use std::collections::VecDeque; - -impl Solution { - #[allow(dead_code)] - pub fn update_matrix(mat: Vec>) -> Vec> { - let n: usize = mat.len(); - let m: usize = mat[0].len(); - let mut ret_vec: Vec> = vec![vec![-1; m]; n]; - // The inner tuple is of - let mut the_q: VecDeque<(usize, usize)> = VecDeque::new(); - let traverse_vec: Vec<(i32, i32)> = vec![(-1, 0), (1, 0), (0, 1), (0, -1)]; - - // Initialize the queue - for i in 0..n { - for j in 0..m { - if mat[i][j] == 0 { - // For the zero cell, enqueue at first - the_q.push_back((i, j)); - // Set to 0 in return vector - ret_vec[i][j] = 0; - } - } - } - - while !the_q.is_empty() { - let (x, y) = the_q.front().unwrap().clone(); - the_q.pop_front(); - for pair in &traverse_vec { - let cur_x = pair.0 + (x as i32); - let cur_y = pair.1 + (y as i32); - if - Solution::check_bounds(cur_x, cur_y, n as i32, m as i32) && - ret_vec[cur_x as usize][cur_y as usize] == -1 - { - // The current cell has not be updated yet, and is also in bound - ret_vec[cur_x as usize][cur_y as usize] = ret_vec[x][y] + 1; - the_q.push_back((cur_x as usize, cur_y as usize)); - } - } - } - - ret_vec - } - - #[allow(dead_code)] - pub fn check_bounds(i: i32, j: i32, n: i32, m: i32) -> bool { - i >= 0 && i < n && j >= 0 && j < m - } -} -``` - -### **Go** - ```go func updateMatrix(mat [][]int) [][]int { m, n := len(mat), len(mat[0]) @@ -238,8 +166,6 @@ func updateMatrix(mat [][]int) [][]int { } ``` -### **TypeScript** - ```ts function updateMatrix(mat: number[][]): number[][] { const [m, n] = [mat.length, mat[0].length]; @@ -268,10 +194,58 @@ function updateMatrix(mat: number[][]): number[][] { } ``` -### **...** +```rust +use std::collections::VecDeque; -``` +impl Solution { + #[allow(dead_code)] + pub fn update_matrix(mat: Vec>) -> Vec> { + let n: usize = mat.len(); + let m: usize = mat[0].len(); + let mut ret_vec: Vec> = vec![vec![-1; m]; n]; + // The inner tuple is of + let mut the_q: VecDeque<(usize, usize)> = VecDeque::new(); + let traverse_vec: Vec<(i32, i32)> = vec![(-1, 0), (1, 0), (0, 1), (0, -1)]; + + // Initialize the queue + for i in 0..n { + for j in 0..m { + if mat[i][j] == 0 { + // For the zero cell, enqueue at first + the_q.push_back((i, j)); + // Set to 0 in return vector + ret_vec[i][j] = 0; + } + } + } + + while !the_q.is_empty() { + let (x, y) = the_q.front().unwrap().clone(); + the_q.pop_front(); + for pair in &traverse_vec { + let cur_x = pair.0 + (x as i32); + let cur_y = pair.1 + (y as i32); + if + Solution::check_bounds(cur_x, cur_y, n as i32, m as i32) && + ret_vec[cur_x as usize][cur_y as usize] == -1 + { + // The current cell has not be updated yet, and is also in bound + ret_vec[cur_x as usize][cur_y as usize] = ret_vec[x][y] + 1; + the_q.push_back((cur_x as usize, cur_y as usize)); + } + } + } + + ret_vec + } + #[allow(dead_code)] + pub fn check_bounds(i: i32, j: i32, n: i32, m: i32) -> bool { + i >= 0 && i < n && j >= 0 && j < m + } +} ``` + + diff --git a/solution/0500-0599/0543.Diameter of Binary Tree/README.md b/solution/0500-0599/0543.Diameter of Binary Tree/README.md index 5b7ae9e9e89a6..bf19aa918a89e 100644 --- a/solution/0500-0599/0543.Diameter of Binary Tree/README.md +++ b/solution/0500-0599/0543.Diameter of Binary Tree/README.md @@ -40,22 +40,10 @@ ## 解法 - - -**方法一**:后序遍历求每个结点的深度,此过程中获取每个结点左右子树的最长伸展(深度),迭代获取最长路径。 - -相似题目:[687. 最长同值路径](/solution/0600-0699/0687.Longest%20Univalue%20Path/README.md) - -**方法二**:构建图,两次 DFS。 - -相似题目:[1245. 树的直径](/solution/1200-1299/1245.Tree%20Diameter/README.md), [1522. N 叉树的直径](/solution/1500-1599/1522.Diameter%20of%20N-Ary%20Tree/README.md) +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -78,54 +66,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def diameterOfBinaryTree(self, root: TreeNode) -> int: - def build(root): - if root is None: - return - nonlocal d - if root.left: - d[root].add(root.left) - d[root.left].add(root) - if root.right: - d[root].add(root.right) - d[root.right].add(root) - build(root.left) - build(root.right) - - def dfs(u, t): - nonlocal ans, vis, d, next - if u in vis: - return - vis.add(u) - if t > ans: - ans = t - next = u - for v in d[u]: - dfs(v, t + 1) - - d = defaultdict(set) - ans = 0 - next = root - build(root) - vis = set() - dfs(next, 0) - vis.clear() - dfs(next, 0) - return ans -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -163,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -197,8 +135,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -224,39 +160,6 @@ func diameterOfBinaryTree(root *TreeNode) int { } ``` -### **C** - -```c -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int dfs(struct TreeNode* root, int* res) { - if (!root) { - return 0; - } - int left = dfs(root->left, res); - int right = dfs(root->right, res); - *res = max(*res, left + right); - return max(left, right) + 1; -} - -int diameterOfBinaryTree(struct TreeNode* root) { - int res = 0; - dfs(root, &res); - return res; -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -289,8 +192,6 @@ function diameterOfBinaryTree(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -332,10 +233,85 @@ impl Solution { } ``` -### **...** +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +#define max(a, b) (((a) > (b)) ? (a) : (b)) + +int dfs(struct TreeNode* root, int* res) { + if (!root) { + return 0; + } + int left = dfs(root->left, res); + int right = dfs(root->right, res); + *res = max(*res, left + right); + return max(left, right) + 1; +} +int diameterOfBinaryTree(struct TreeNode* root) { + int res = 0; + dfs(root, &res); + return res; +} ``` + + +### 方法二 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def diameterOfBinaryTree(self, root: TreeNode) -> int: + def build(root): + if root is None: + return + nonlocal d + if root.left: + d[root].add(root.left) + d[root.left].add(root) + if root.right: + d[root].add(root.right) + d[root.right].add(root) + build(root.left) + build(root.right) + + def dfs(u, t): + nonlocal ans, vis, d, next + if u in vis: + return + vis.add(u) + if t > ans: + ans = t + next = u + for v in d[u]: + dfs(v, t + 1) + + d = defaultdict(set) + ans = 0 + next = root + build(root) + vis = set() + dfs(next, 0) + vis.clear() + dfs(next, 0) + return ans ``` + + diff --git a/solution/0500-0599/0543.Diameter of Binary Tree/README_EN.md b/solution/0500-0599/0543.Diameter of Binary Tree/README_EN.md index 6e19d42365eeb..8a6ca70daf859 100644 --- a/solution/0500-0599/0543.Diameter of Binary Tree/README_EN.md +++ b/solution/0500-0599/0543.Diameter of Binary Tree/README_EN.md @@ -36,12 +36,10 @@ ## Solutions -Similar to problem [687. Longest Univalue Path](/solution/0600-0699/0687.Longest%20Univalue%20Path/README_EN.md). +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -64,52 +62,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def diameterOfBinaryTree(self, root: TreeNode) -> int: - def build(root): - if root is None: - return - nonlocal d - if root.left: - d[root].add(root.left) - d[root.left].add(root) - if root.right: - d[root].add(root.right) - d[root.right].add(root) - build(root.left) - build(root.right) - - def dfs(u, t): - nonlocal ans, vis, d, next - if u in vis: - return - vis.add(u) - if t > ans: - ans = t - next = u - for v in d[u]: - dfs(v, t + 1) - - d = defaultdict(set) - ans = 0 - next = root - build(root) - vis = set() - dfs(next, 0) - vis.clear() - dfs(next, 0) - return ans -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -147,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -181,8 +131,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -208,39 +156,6 @@ func diameterOfBinaryTree(root *TreeNode) int { } ``` -### **C** - -```c -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int dfs(struct TreeNode* root, int* res) { - if (!root) { - return 0; - } - int left = dfs(root->left, res); - int right = dfs(root->right, res); - *res = max(*res, left + right); - return max(left, right) + 1; -} - -int diameterOfBinaryTree(struct TreeNode* root) { - int res = 0; - dfs(root, &res); - return res; -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -273,8 +188,6 @@ function diameterOfBinaryTree(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -316,10 +229,85 @@ impl Solution { } ``` -### **...** +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +#define max(a, b) (((a) > (b)) ? (a) : (b)) +int dfs(struct TreeNode* root, int* res) { + if (!root) { + return 0; + } + int left = dfs(root->left, res); + int right = dfs(root->right, res); + *res = max(*res, left + right); + return max(left, right) + 1; +} + +int diameterOfBinaryTree(struct TreeNode* root) { + int res = 0; + dfs(root, &res); + return res; +} ``` + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def diameterOfBinaryTree(self, root: TreeNode) -> int: + def build(root): + if root is None: + return + nonlocal d + if root.left: + d[root].add(root.left) + d[root.left].add(root) + if root.right: + d[root].add(root.right) + d[root.right].add(root) + build(root.left) + build(root.right) + + def dfs(u, t): + nonlocal ans, vis, d, next + if u in vis: + return + vis.add(u) + if t > ans: + ans = t + next = u + for v in d[u]: + dfs(v, t + 1) + + d = defaultdict(set) + ans = 0 + next = root + build(root) + vis = set() + dfs(next, 0) + vis.clear() + dfs(next, 0) + return ans ``` + + diff --git a/solution/0500-0599/0544.Output Contest Matches/README.md b/solution/0500-0599/0544.Output Contest Matches/README.md index a87cb4ba9968e..dec5c780f5bc7 100644 --- a/solution/0500-0599/0544.Output Contest Matches/README.md +++ b/solution/0500-0599/0544.Output Contest Matches/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 假设 `team[i]` 为当前轮次中第 i 强的队伍。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def findContestMatch(self, n: int) -> str: @@ -76,10 +70,6 @@ class Solution: return team[0] ``` -### **Java** - - - ```java class Solution { public String findContestMatch(int n) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func findContestMatch(n int) string { team := make([]string, n) @@ -133,10 +119,6 @@ func findContestMatch(n int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0544.Output Contest Matches/README_EN.md b/solution/0500-0599/0544.Output Contest Matches/README_EN.md index 7956e3c245342..55e5c7735567c 100644 --- a/solution/0500-0599/0544.Output Contest Matches/README_EN.md +++ b/solution/0500-0599/0544.Output Contest Matches/README_EN.md @@ -46,9 +46,9 @@ Since the third round will generate the final winner, you need to output the ans ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return team[0] ``` -### **Java** - ```java class Solution { public String findContestMatch(int n) { @@ -80,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +94,6 @@ public: }; ``` -### **Go** - ```go func findContestMatch(n int) string { team := make([]string, n) @@ -116,10 +110,6 @@ func findContestMatch(n int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0545.Boundary of Binary Tree/README.md b/solution/0500-0599/0545.Boundary of Binary Tree/README.md index 3e3b81f6eb7e1..7601a5c8ae6e3 100644 --- a/solution/0500-0599/0545.Boundary of Binary Tree/README.md +++ b/solution/0500-0599/0545.Boundary of Binary Tree/README.md @@ -58,18 +58,10 @@ ## 解法 - - -分别求根节点、左边界、叶子节点、右边界,依次放入结果数组 res 中。 - -注意,求右边界的时候,需要逆序结果,这时可以用栈实现。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -122,10 +114,6 @@ class Solution: return node and node.left is None and node.right is None ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -204,8 +192,6 @@ class Solution { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -273,10 +259,6 @@ var boundaryOfBinaryTree = function (root) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0545.Boundary of Binary Tree/README_EN.md b/solution/0500-0599/0545.Boundary of Binary Tree/README_EN.md index 2222df1b10c13..7ccaeee561bf7 100644 --- a/solution/0500-0599/0545.Boundary of Binary Tree/README_EN.md +++ b/solution/0500-0599/0545.Boundary of Binary Tree/README_EN.md @@ -59,9 +59,9 @@ Concatenating everything results in [1] + [2] + [4,7,8,9,10] + [6,3] = [1,2,4,7, ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -115,8 +115,6 @@ class Solution: return node and node.left is None and node.right is None ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -195,8 +193,6 @@ class Solution { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -264,10 +260,6 @@ var boundaryOfBinaryTree = function (root) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0546.Remove Boxes/README.md b/solution/0500-0599/0546.Remove Boxes/README.md index 65fbf12cf8a1a..388462f02685d 100644 --- a/solution/0500-0599/0546.Remove Boxes/README.md +++ b/solution/0500-0599/0546.Remove Boxes/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 设计递归函数 `dfs(i, j, k)` 表示当前处理的区间为 `[i, j]`,且该区间的右边有 `k` 个与 `boxes[j]` 相同的元素,返回该区间的最大积分。答案即为 `dfs(0, n - 1, 0)`。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def removeBoxes(self, boxes: List[int]) -> int: @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[][][] f; @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go func removeBoxes(boxes []int) int { n := len(boxes) @@ -198,10 +184,6 @@ func removeBoxes(boxes []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0546.Remove Boxes/README_EN.md b/solution/0500-0599/0546.Remove Boxes/README_EN.md index 6fbb7eefa6c88..97eca6bc4df44 100644 --- a/solution/0500-0599/0546.Remove Boxes/README_EN.md +++ b/solution/0500-0599/0546.Remove Boxes/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[][][] f; @@ -110,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +136,6 @@ public: }; ``` -### **Go** - ```go func removeBoxes(boxes []int) int { n := len(boxes) @@ -176,10 +170,6 @@ func removeBoxes(boxes []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0547.Number of Provinces/README.md b/solution/0500-0599/0547.Number of Provinces/README.md index 9fbcf140b6a27..ff17be1d9d1a1 100644 --- a/solution/0500-0599/0547.Number of Provinces/README.md +++ b/solution/0500-0599/0547.Number of Provinces/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们创建一个数组 $vis$,用于记录每个城市是否被访问过。 @@ -61,22 +59,8 @@ 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 是城市的数量。 -**方法二:并查集** - -我们也可以用并查集维护每个连通分量,初始时,每个城市都属于不同的连通分量,所以省份数量为 $n$。 - -接下来,遍历矩阵 $isConnected$,如果两个城市 $(i, j)$ 之间有相连关系,并且处于两个不同的连通分量,则它们将被合并成为一个连通分量,然后将省份数量减去 $1$。 - -最后返回省份数量即可。 - -时间复杂度 $O(n^2 \times \alpha(n))$,空间复杂度 $O(n)$。其中 $n$ 是城市的数量,而 $\alpha$ 是阿克曼函数的反函数,在渐进意义下 $\alpha(n)$ 可以认为是一个很小的常数。 - -### **Python3** - - - ```python class Solution: def findCircleNum(self, isConnected: List[List[int]]) -> int: @@ -96,31 +80,6 @@ class Solution: return ans ``` -```python -class Solution: - def findCircleNum(self, isConnected: List[List[int]]) -> int: - def find(x: int) -> int: - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - n = len(isConnected) - p = list(range(n)) - ans = n - for i in range(n): - for j in range(i + 1, n): - if isConnected[i][j]: - pa, pb = find(i), find(j) - if pa != pb: - p[pa] = pb - ans -= 1 - return ans -``` - -### **Java** - - - ```java class Solution { private int[][] g; @@ -151,6 +110,142 @@ class Solution { } ``` +```cpp +class Solution { +public: + int findCircleNum(vector>& isConnected) { + int n = isConnected.size(); + int ans = 0; + bool vis[n]; + memset(vis, false, sizeof(vis)); + function dfs = [&](int i) { + vis[i] = true; + for (int j = 0; j < n; ++j) { + if (!vis[j] && isConnected[i][j]) { + dfs(j); + } + } + }; + for (int i = 0; i < n; ++i) { + if (!vis[i]) { + dfs(i); + ++ans; + } + } + return ans; + } +}; +``` + +```go +func findCircleNum(isConnected [][]int) (ans int) { + n := len(isConnected) + vis := make([]bool, n) + var dfs func(int) + dfs = func(i int) { + vis[i] = true + for j, x := range isConnected[i] { + if !vis[j] && x == 1 { + dfs(j) + } + } + } + for i, v := range vis { + if !v { + ans++ + dfs(i) + } + } + return +} +``` + +```ts +function findCircleNum(isConnected: number[][]): number { + const n = isConnected.length; + const vis: boolean[] = new Array(n).fill(false); + const dfs = (i: number) => { + vis[i] = true; + for (let j = 0; j < n; ++j) { + if (!vis[j] && isConnected[i][j]) { + dfs(j); + } + } + }; + let ans = 0; + for (let i = 0; i < n; ++i) { + if (!vis[i]) { + dfs(i); + ++ans; + } + } + return ans; +} +``` + +```rust +impl Solution { + fn dfs(is_connected: &mut Vec>, vis: &mut Vec, i: usize) { + vis[i] = true; + for j in 0..is_connected.len() { + if vis[j] || is_connected[i][j] == 0 { + continue; + } + Self::dfs(is_connected, vis, j); + } + } + + pub fn find_circle_num(mut is_connected: Vec>) -> i32 { + let n = is_connected.len(); + let mut vis = vec![false; n]; + let mut res = 0; + for i in 0..n { + if vis[i] { + continue; + } + res += 1; + Self::dfs(&mut is_connected, &mut vis, i); + } + res + } +} +``` + + + +### 方法二:并查集 + +我们也可以用并查集维护每个连通分量,初始时,每个城市都属于不同的连通分量,所以省份数量为 $n$。 + +接下来,遍历矩阵 $isConnected$,如果两个城市 $(i, j)$ 之间有相连关系,并且处于两个不同的连通分量,则它们将被合并成为一个连通分量,然后将省份数量减去 $1$。 + +最后返回省份数量即可。 + +时间复杂度 $O(n^2 \times \alpha(n))$,空间复杂度 $O(n)$。其中 $n$ 是城市的数量,而 $\alpha$ 是阿克曼函数的反函数,在渐进意义下 $\alpha(n)$ 可以认为是一个很小的常数。 + + + +```python +class Solution: + def findCircleNum(self, isConnected: List[List[int]]) -> int: + def find(x: int) -> int: + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + n = len(isConnected) + p = list(range(n)) + ans = n + for i in range(n): + for j in range(i + 1, n): + if isConnected[i][j]: + pa, pb = find(i), find(j) + if pa != pb: + p[pa] = pb + ans -= 1 + return ans +``` + ```java class Solution { private int[] p; @@ -185,35 +280,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int findCircleNum(vector>& isConnected) { - int n = isConnected.size(); - int ans = 0; - bool vis[n]; - memset(vis, false, sizeof(vis)); - function dfs = [&](int i) { - vis[i] = true; - for (int j = 0; j < n; ++j) { - if (!vis[j] && isConnected[i][j]) { - dfs(j); - } - } - }; - for (int i = 0; i < n; ++i) { - if (!vis[i]) { - dfs(i); - ++ans; - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -244,31 +310,6 @@ public: }; ``` -### **Go** - -```go -func findCircleNum(isConnected [][]int) (ans int) { - n := len(isConnected) - vis := make([]bool, n) - var dfs func(int) - dfs = func(i int) { - vis[i] = true - for j, x := range isConnected[i] { - if !vis[j] && x == 1 { - dfs(j) - } - } - } - for i, v := range vis { - if !v { - ans++ - dfs(i) - } - } - return -} -``` - ```go func findCircleNum(isConnected [][]int) (ans int) { n := len(isConnected) @@ -299,31 +340,6 @@ func findCircleNum(isConnected [][]int) (ans int) { } ``` -### **TypeScript** - -```ts -function findCircleNum(isConnected: number[][]): number { - const n = isConnected.length; - const vis: boolean[] = new Array(n).fill(false); - const dfs = (i: number) => { - vis[i] = true; - for (let j = 0; j < n; ++j) { - if (!vis[j] && isConnected[i][j]) { - dfs(j); - } - } - }; - let ans = 0; - for (let i = 0; i < n; ++i) { - if (!vis[i]) { - dfs(i); - ++ans; - } - } - return ans; -} -``` - ```ts function findCircleNum(isConnected: number[][]): number { const n = isConnected.length; @@ -354,40 +370,6 @@ function findCircleNum(isConnected: number[][]): number { } ``` -### **Rust** - -```rust -impl Solution { - fn dfs(is_connected: &mut Vec>, vis: &mut Vec, i: usize) { - vis[i] = true; - for j in 0..is_connected.len() { - if vis[j] || is_connected[i][j] == 0 { - continue; - } - Self::dfs(is_connected, vis, j); - } - } - - pub fn find_circle_num(mut is_connected: Vec>) -> i32 { - let n = is_connected.len(); - let mut vis = vec![false; n]; - let mut res = 0; - for i in 0..n { - if vis[i] { - continue; - } - res += 1; - Self::dfs(&mut is_connected, &mut vis, i); - } - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0547.Number of Provinces/README_EN.md b/solution/0500-0599/0547.Number of Provinces/README_EN.md index 99170dda638f0..127610036e7a0 100644 --- a/solution/0500-0599/0547.Number of Provinces/README_EN.md +++ b/solution/0500-0599/0547.Number of Provinces/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,29 +64,6 @@ class Solution: return ans ``` -```python -class Solution: - def findCircleNum(self, isConnected: List[List[int]]) -> int: - def find(x: int) -> int: - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - n = len(isConnected) - p = list(range(n)) - ans = n - for i in range(n): - for j in range(i + 1, n): - if isConnected[i][j]: - pa, pb = find(i), find(j) - if pa != pb: - p[pa] = pb - ans -= 1 - return ans -``` - -### **Java** - ```java class Solution { private int[][] g; @@ -117,6 +94,134 @@ class Solution { } ``` +```cpp +class Solution { +public: + int findCircleNum(vector>& isConnected) { + int n = isConnected.size(); + int ans = 0; + bool vis[n]; + memset(vis, false, sizeof(vis)); + function dfs = [&](int i) { + vis[i] = true; + for (int j = 0; j < n; ++j) { + if (!vis[j] && isConnected[i][j]) { + dfs(j); + } + } + }; + for (int i = 0; i < n; ++i) { + if (!vis[i]) { + dfs(i); + ++ans; + } + } + return ans; + } +}; +``` + +```go +func findCircleNum(isConnected [][]int) (ans int) { + n := len(isConnected) + vis := make([]bool, n) + var dfs func(int) + dfs = func(i int) { + vis[i] = true + for j, x := range isConnected[i] { + if !vis[j] && x == 1 { + dfs(j) + } + } + } + for i, v := range vis { + if !v { + ans++ + dfs(i) + } + } + return +} +``` + +```ts +function findCircleNum(isConnected: number[][]): number { + const n = isConnected.length; + const vis: boolean[] = new Array(n).fill(false); + const dfs = (i: number) => { + vis[i] = true; + for (let j = 0; j < n; ++j) { + if (!vis[j] && isConnected[i][j]) { + dfs(j); + } + } + }; + let ans = 0; + for (let i = 0; i < n; ++i) { + if (!vis[i]) { + dfs(i); + ++ans; + } + } + return ans; +} +``` + +```rust +impl Solution { + fn dfs(is_connected: &mut Vec>, vis: &mut Vec, i: usize) { + vis[i] = true; + for j in 0..is_connected.len() { + if vis[j] || is_connected[i][j] == 0 { + continue; + } + Self::dfs(is_connected, vis, j); + } + } + + pub fn find_circle_num(mut is_connected: Vec>) -> i32 { + let n = is_connected.len(); + let mut vis = vec![false; n]; + let mut res = 0; + for i in 0..n { + if vis[i] { + continue; + } + res += 1; + Self::dfs(&mut is_connected, &mut vis, i); + } + res + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def findCircleNum(self, isConnected: List[List[int]]) -> int: + def find(x: int) -> int: + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + n = len(isConnected) + p = list(range(n)) + ans = n + for i in range(n): + for j in range(i + 1, n): + if isConnected[i][j]: + pa, pb = find(i), find(j) + if pa != pb: + p[pa] = pb + ans -= 1 + return ans +``` + ```java class Solution { private int[] p; @@ -151,35 +256,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int findCircleNum(vector>& isConnected) { - int n = isConnected.size(); - int ans = 0; - bool vis[n]; - memset(vis, false, sizeof(vis)); - function dfs = [&](int i) { - vis[i] = true; - for (int j = 0; j < n; ++j) { - if (!vis[j] && isConnected[i][j]) { - dfs(j); - } - } - }; - for (int i = 0; i < n; ++i) { - if (!vis[i]) { - dfs(i); - ++ans; - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -210,31 +286,6 @@ public: }; ``` -### **Go** - -```go -func findCircleNum(isConnected [][]int) (ans int) { - n := len(isConnected) - vis := make([]bool, n) - var dfs func(int) - dfs = func(i int) { - vis[i] = true - for j, x := range isConnected[i] { - if !vis[j] && x == 1 { - dfs(j) - } - } - } - for i, v := range vis { - if !v { - ans++ - dfs(i) - } - } - return -} -``` - ```go func findCircleNum(isConnected [][]int) (ans int) { n := len(isConnected) @@ -265,31 +316,6 @@ func findCircleNum(isConnected [][]int) (ans int) { } ``` -### **TypeScript** - -```ts -function findCircleNum(isConnected: number[][]): number { - const n = isConnected.length; - const vis: boolean[] = new Array(n).fill(false); - const dfs = (i: number) => { - vis[i] = true; - for (let j = 0; j < n; ++j) { - if (!vis[j] && isConnected[i][j]) { - dfs(j); - } - } - }; - let ans = 0; - for (let i = 0; i < n; ++i) { - if (!vis[i]) { - dfs(i); - ++ans; - } - } - return ans; -} -``` - ```ts function findCircleNum(isConnected: number[][]): number { const n = isConnected.length; @@ -320,40 +346,6 @@ function findCircleNum(isConnected: number[][]): number { } ``` -### **Rust** - -```rust -impl Solution { - fn dfs(is_connected: &mut Vec>, vis: &mut Vec, i: usize) { - vis[i] = true; - for j in 0..is_connected.len() { - if vis[j] || is_connected[i][j] == 0 { - continue; - } - Self::dfs(is_connected, vis, j); - } - } - - pub fn find_circle_num(mut is_connected: Vec>) -> i32 { - let n = is_connected.len(); - let mut vis = vec![false; n]; - let mut res = 0; - for i in 0..n { - if vis[i] { - continue; - } - res += 1; - Self::dfs(&mut is_connected, &mut vis, i); - } - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0548.Split Array with Equal Sum/README.md b/solution/0500-0599/0548.Split Array with Equal Sum/README.md index e15b9d324e81f..01a26bfa07f5c 100644 --- a/solution/0500-0599/0548.Split Array with Equal Sum/README.md +++ b/solution/0500-0599/0548.Split Array with Equal Sum/README.md @@ -49,9 +49,7 @@ sum(k + 1, n - 1) = sum(6, 6) = 1 ## 解法 - - -**方法一:前缀和 + 哈希表** +### 方法一:前缀和 + 哈希表 先求出前缀和数组 s。 @@ -65,10 +63,6 @@ sum(k + 1, n - 1) = sum(6, 6) = 1 -### **Python3** - - - ```python class Solution: def splitArray(self, nums: List[int]) -> bool: @@ -87,10 +81,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean splitArray(int[] nums) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func splitArray(nums []int) bool { n := len(nums) @@ -166,10 +152,6 @@ func splitArray(nums []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0548.Split Array with Equal Sum/README_EN.md b/solution/0500-0599/0548.Split Array with Equal Sum/README_EN.md index 92ec0a71ac64a..5ab812986b12d 100644 --- a/solution/0500-0599/0548.Split Array with Equal Sum/README_EN.md +++ b/solution/0500-0599/0548.Split Array with Equal Sum/README_EN.md @@ -43,9 +43,9 @@ sum(k + 1, n - 1) = sum(6, 6) = 1 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean splitArray(int[] nums) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +112,6 @@ public: }; ``` -### **Go** - ```go func splitArray(nums []int) bool { n := len(nums) @@ -142,10 +136,6 @@ func splitArray(nums []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/README.md b/solution/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/README.md index d6917d685c95a..082cc85e8abfd 100644 --- a/solution/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/README.md +++ b/solution/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/README.md @@ -50,14 +50,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -92,10 +88,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -150,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -193,8 +183,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -238,10 +226,6 @@ func longestConsecutive(root *TreeNode) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/README_EN.md b/solution/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/README_EN.md index b6a05602c646f..69415767c2961 100644 --- a/solution/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/README_EN.md +++ b/solution/0500-0599/0549.Binary Tree Longest Consecutive Sequence II/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -79,8 +79,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -135,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -178,8 +174,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -223,10 +217,6 @@ func longestConsecutive(root *TreeNode) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0550.Game Play Analysis IV/README.md b/solution/0500-0599/0550.Game Play Analysis IV/README.md index b77e0ab6dbb53..a84a9753497e0 100644 --- a/solution/0500-0599/0550.Game Play Analysis IV/README.md +++ b/solution/0500-0599/0550.Game Play Analysis IV/README.md @@ -56,19 +56,26 @@ Activity table: ## 解法 - - -**方法一:分组取最小值 + 左连接** +### 方法一:分组取最小值 + 左连接 我们可以先找到每个玩家的首次登录日期,然后与原表进行左连接,连接条件为玩家 ID 相同且日期差为 $-1$,即第二天登录。那么,我们只需要统计出第二天登录的玩家数量中,玩家不为空的比率即可。 -**方法二:窗口函数** + -我们也可以使用窗口函数 `LEAD` 获取每个玩家的下一次登录日期,如果下一次登录日期与当前登录日期相差 $1$ 天,则说明该玩家在第二天登录,我们用一个字段 $st$ 记录该信息。然后,我们用窗口函数 `RANK` 对玩家 ID 按照日期升序排列,得到每个玩家的登录排名。最后,我们只需要统计出排名为 $1$ 的玩家中,字段 $st$ 不为空的比率即可。 +```python +import pandas as pd - -### **SQL** +def gameplay_analysis(activity: pd.DataFrame) -> pd.DataFrame: + activity["first"] = activity.groupby("player_id").event_date.transform(min) + activity_2nd_day = activity[ + activity["first"] + pd.DateOffset(1) == activity["event_date"] + ] + + return pd.DataFrame( + {"fraction": [round(len(activity_2nd_day) / activity.player_id.nunique(), 2)]} + ) +``` ```sql # Write your MySQL query statement below @@ -83,6 +90,14 @@ FROM ON a.player_id = b.player_id AND DATEDIFF(a.event_date, b.event_date) = -1; ``` + + +### 方法二:窗口函数 + +我们也可以使用窗口函数 `LEAD` 获取每个玩家的下一次登录日期,如果下一次登录日期与当前登录日期相差 $1$ 天,则说明该玩家在第二天登录,我们用一个字段 $st$ 记录该信息。然后,我们用窗口函数 `RANK` 对玩家 ID 按照日期升序排列,得到每个玩家的登录排名。最后,我们只需要统计出排名为 $1$ 的玩家中,字段 $st$ 不为空的比率即可。 + + + ```sql # Write your MySQL query statement below WITH @@ -107,21 +122,6 @@ FROM T WHERE rk = 1; ``` -### **Pandas** - -```python -import pandas as pd - - -def gameplay_analysis(activity: pd.DataFrame) -> pd.DataFrame: - activity["first"] = activity.groupby("player_id").event_date.transform(min) - activity_2nd_day = activity[ - activity["first"] + pd.DateOffset(1) == activity["event_date"] - ] - - return pd.DataFrame( - {"fraction": [round(len(activity_2nd_day) / activity.player_id.nunique(), 2)]} - ) -``` - + + diff --git a/solution/0500-0599/0550.Game Play Analysis IV/README_EN.md b/solution/0500-0599/0550.Game Play Analysis IV/README_EN.md index 024fb8a04e088..a86900141a372 100644 --- a/solution/0500-0599/0550.Game Play Analysis IV/README_EN.md +++ b/solution/0500-0599/0550.Game Play Analysis IV/README_EN.md @@ -53,17 +53,26 @@ Only the player with id 1 logged back in after the first day he had logged in so ## Solutions -**Solution 1: Grouping and Minimum Value + Left Join** +### Solution 1: Grouping and Minimum Value + Left Join We can first find the first login date of each player, and then perform a left join with the original table, with the join condition being that the player ID is the same and the date difference is $-1$, which means the player logged in on the second day. Then, we only need to calculate the ratio of non-null players among the players who logged in on the second day. -**Solution 2: Window Function** + -We can use the `LEAD` window function to get the next login date of each player. If the next login date is one day after the current login date, it means that the player logged in on the second day, and we use a field $st$ to record this information. Then, we use the `RANK` window function to rank the player IDs in ascending order by date, and get the login ranking of each player. Finally, we only need to calculate the ratio of non-null $st$ values among the players with a ranking of $1$. +```python +import pandas as pd - -### **SQL** +def gameplay_analysis(activity: pd.DataFrame) -> pd.DataFrame: + activity["first"] = activity.groupby("player_id").event_date.transform(min) + activity_2nd_day = activity[ + activity["first"] + pd.DateOffset(1) == activity["event_date"] + ] + + return pd.DataFrame( + {"fraction": [round(len(activity_2nd_day) / activity.player_id.nunique(), 2)]} + ) +``` ```sql # Write your MySQL query statement below @@ -78,6 +87,14 @@ FROM ON a.player_id = b.player_id AND DATEDIFF(a.event_date, b.event_date) = -1; ``` + + +### Solution 2: Window Function + +We can use the `LEAD` window function to get the next login date of each player. If the next login date is one day after the current login date, it means that the player logged in on the second day, and we use a field $st$ to record this information. Then, we use the `RANK` window function to rank the player IDs in ascending order by date, and get the login ranking of each player. Finally, we only need to calculate the ratio of non-null $st$ values among the players with a ranking of $1$. + + + ```sql # Write your MySQL query statement below WITH @@ -102,21 +119,6 @@ FROM T WHERE rk = 1; ``` -### **Pandas** - -```python -import pandas as pd - - -def gameplay_analysis(activity: pd.DataFrame) -> pd.DataFrame: - activity["first"] = activity.groupby("player_id").event_date.transform(min) - activity_2nd_day = activity[ - activity["first"] + pd.DateOffset(1) == activity["event_date"] - ] - - return pd.DataFrame( - {"fraction": [round(len(activity_2nd_day) / activity.player_id.nunique(), 2)]} - ) -``` - + + diff --git a/solution/0500-0599/0551.Student Attendance Record I/README.md b/solution/0500-0599/0551.Student Attendance Record I/README.md index 2d494235dde8f..c4682edacb389 100644 --- a/solution/0500-0599/0551.Student Attendance Record I/README.md +++ b/solution/0500-0599/0551.Student Attendance Record I/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:字符串遍历** +### 方法一:字符串遍历 我们可以遍历字符串 $s$,记录字符 `'A'` 和字符串 `"LLL"` 的出现次数。如果字符 `'A'` 的出现次数小于 $2$,且字符串 `"LLL"` 没有出现过,则可以将该字符串视作记录合法,返回 `true`,否则返回 `false`。 @@ -62,20 +60,12 @@ -### **Python3** - - - ```python class Solution: def checkRecord(self, s: str) -> bool: return s.count('A') < 2 and 'LLL' not in s ``` -### **Java** - - - ```java class Solution { public boolean checkRecord(String s) { @@ -84,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,26 +83,18 @@ public: }; ``` -### **Go** - ```go func checkRecord(s string) bool { return strings.Count(s, "A") < 2 && !strings.Contains(s, "LLL") } ``` -### **TypeScript** - ```ts function checkRecord(s: string): boolean { return s.indexOf('A') === s.lastIndexOf('A') && s.indexOf('LLL') === -1; } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0551.Student Attendance Record I/README_EN.md b/solution/0500-0599/0551.Student Attendance Record I/README_EN.md index 6639abe7f4d03..ca66d1c979849 100644 --- a/solution/0500-0599/0551.Student Attendance Record I/README_EN.md +++ b/solution/0500-0599/0551.Student Attendance Record I/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return s.count('A') < 2 and 'LLL' not in s ``` -### **Java** - ```java class Solution { public boolean checkRecord(String s) { @@ -68,8 +66,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -79,26 +75,18 @@ public: }; ``` -### **Go** - ```go func checkRecord(s string) bool { return strings.Count(s, "A") < 2 && !strings.Contains(s, "LLL") } ``` -### **TypeScript** - ```ts function checkRecord(s: string): boolean { return s.indexOf('A') === s.lastIndexOf('A') && s.indexOf('LLL') === -1; } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0552.Student Attendance Record II/README.md b/solution/0500-0599/0552.Student Attendance Record II/README.md index 733bc0b162aad..52f646e1c1220 100644 --- a/solution/0500-0599/0552.Student Attendance Record II/README.md +++ b/solution/0500-0599/0552.Student Attendance Record II/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j, k)$,表示从第 $i$ 个出勤记录开始,当前缺勤次数为 $j$,目前最后连续迟到次数为 $k$ 时,可获得出勤奖励的情况数量。那么答案就是 $dfs(0, 0, 0)$。 @@ -79,22 +77,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为出勤记录的长度。 -**方法二:动态规划** - -动态规划,定义 `dp[i][j][k]` 表示前 `i` 天,缺勤 `j` 次,连续迟到 `k` 次时,可获得出勤奖励的情况数量 - -状态转移需要对第 `i` 天的出勤情况分别讨论: - -- 缺勤:之前不能有任何缺勤记录,即 `j == 0` -- 迟到:之前最多连续迟到 1 次,即 `k == 0 || k == 1` -- 到场:无限制 - -### **Python3** - - - ```python class Solution: def checkRecord(self, n: int) -> int: @@ -116,40 +100,6 @@ class Solution: return ans ``` -```python -class Solution: - def checkRecord(self, n: int) -> int: - mod = int(1e9 + 7) - dp = [[[0, 0, 0], [0, 0, 0]] for _ in range(n)] - - # base case - dp[0][0][0] = dp[0][0][1] = dp[0][1][0] = 1 - - for i in range(1, n): - # A - dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % mod - # L - dp[i][0][1] = dp[i - 1][0][0] - dp[i][0][2] = dp[i - 1][0][1] - dp[i][1][1] = dp[i - 1][1][0] - dp[i][1][2] = dp[i - 1][1][1] - # P - dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % mod - dp[i][1][0] = ( - dp[i][1][0] + dp[i - 1][1][0] + dp[i - 1][1][1] + dp[i - 1][1][2] - ) % mod - - ans = 0 - for j in range(2): - for k in range(3): - ans = (ans + dp[n - 1][j][k]) % mod - return ans -``` - -### **Java** - - - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -181,43 +131,39 @@ class Solution { } ``` -```java -class Solution { - private static final int MOD = 1000000007; - - public int checkRecord(int n) { - long[][][] dp = new long[n][2][3]; +```cpp +int f[100010][2][3]; +const int mod = 1e9 + 7; - // base case - dp[0][0][0] = 1; - dp[0][0][1] = 1; - dp[0][1][0] = 1; +class Solution { +public: + int checkRecord(int n) { + this->n = n; + memset(f, -1, sizeof(f)); + return dfs(0, 0, 0); + } - for (int i = 1; i < n; i++) { - // A - dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; - // L - dp[i][0][1] = dp[i - 1][0][0]; - dp[i][0][2] = dp[i - 1][0][1]; - dp[i][1][1] = dp[i - 1][1][0]; - dp[i][1][2] = dp[i - 1][1][1]; - // P - dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; - dp[i][1][0] = (dp[i][1][0] + dp[i - 1][1][0] + dp[i - 1][1][1] + dp[i - 1][1][2]) % MOD; + int dfs(int i, int j, int k) { + if (i >= n) { + return 1; } - - long ans = 0; - for (int j = 0; j < 2; j++) { - for (int k = 0; k < 3; k++) { - ans = (ans + dp[n - 1][j][k]) % MOD; - } + if (f[i][j][k] != -1) { + return f[i][j][k]; } - return (int) ans; + int ans = dfs(i + 1, j, 0); + if (j == 0) { + ans = (ans + dfs(i + 1, j + 1, 0)) % mod; + } + if (k < 2) { + ans = (ans + dfs(i + 1, j, k + 1)) % mod; + } + return f[i][j][k] = ans; } -} -``` -### **Go** +private: + int n; +}; +``` ```go func checkRecord(n int) int { @@ -254,80 +200,84 @@ func checkRecord(n int) int { } ``` -```go -const _mod int = 1e9 + 7 + -func checkRecord(n int) int { - dp := make([][][]int, n) - for i := 0; i < n; i++ { - dp[i] = make([][]int, 2) - for j := 0; j < 2; j++ { - dp[i][j] = make([]int, 3) - } - } +### 方法二:动态规划 - // base case - dp[0][0][0] = 1 - dp[0][0][1] = 1 - dp[0][1][0] = 1 +动态规划,定义 `dp[i][j][k]` 表示前 `i` 天,缺勤 `j` 次,连续迟到 `k` 次时,可获得出勤奖励的情况数量 - for i := 1; i < n; i++ { - // A - dp[i][1][0] = (dp[i-1][0][0] + dp[i-1][0][1] + dp[i-1][0][2]) % _mod - // L - dp[i][0][1] = dp[i-1][0][0] - dp[i][0][2] = dp[i-1][0][1] - dp[i][1][1] = dp[i-1][1][0] - dp[i][1][2] = dp[i-1][1][1] - // P - dp[i][0][0] = (dp[i-1][0][0] + dp[i-1][0][1] + dp[i-1][0][2]) % _mod - dp[i][1][0] = (dp[i][1][0] + dp[i-1][1][0] + dp[i-1][1][1] + dp[i-1][1][2]) % _mod - } +状态转移需要对第 `i` 天的出勤情况分别讨论: - var ans int - for j := 0; j < 2; j++ { - for k := 0; k < 3; k++ { - ans = (ans + dp[n-1][j][k]) % _mod - } - } - return ans -} -``` +- 缺勤:之前不能有任何缺勤记录,即 `j == 0` +- 迟到:之前最多连续迟到 1 次,即 `k == 0 || k == 1` +- 到场:无限制 -### **C++** + -```cpp -int f[100010][2][3]; -const int mod = 1e9 + 7; +```python +class Solution: + def checkRecord(self, n: int) -> int: + mod = int(1e9 + 7) + dp = [[[0, 0, 0], [0, 0, 0]] for _ in range(n)] + + # base case + dp[0][0][0] = dp[0][0][1] = dp[0][1][0] = 1 + + for i in range(1, n): + # A + dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % mod + # L + dp[i][0][1] = dp[i - 1][0][0] + dp[i][0][2] = dp[i - 1][0][1] + dp[i][1][1] = dp[i - 1][1][0] + dp[i][1][2] = dp[i - 1][1][1] + # P + dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % mod + dp[i][1][0] = ( + dp[i][1][0] + dp[i - 1][1][0] + dp[i - 1][1][1] + dp[i - 1][1][2] + ) % mod + + ans = 0 + for j in range(2): + for k in range(3): + ans = (ans + dp[n - 1][j][k]) % mod + return ans +``` +```java class Solution { -public: - int checkRecord(int n) { - this->n = n; - memset(f, -1, sizeof(f)); - return dfs(0, 0, 0); - } + private static final int MOD = 1000000007; - int dfs(int i, int j, int k) { - if (i >= n) { - return 1; - } - if (f[i][j][k] != -1) { - return f[i][j][k]; - } - int ans = dfs(i + 1, j, 0); - if (j == 0) { - ans = (ans + dfs(i + 1, j + 1, 0)) % mod; + public int checkRecord(int n) { + long[][][] dp = new long[n][2][3]; + + // base case + dp[0][0][0] = 1; + dp[0][0][1] = 1; + dp[0][1][0] = 1; + + for (int i = 1; i < n; i++) { + // A + dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; + // L + dp[i][0][1] = dp[i - 1][0][0]; + dp[i][0][2] = dp[i - 1][0][1]; + dp[i][1][1] = dp[i - 1][1][0]; + dp[i][1][2] = dp[i - 1][1][1]; + // P + dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; + dp[i][1][0] = (dp[i][1][0] + dp[i - 1][1][0] + dp[i - 1][1][1] + dp[i - 1][1][2]) % MOD; } - if (k < 2) { - ans = (ans + dfs(i + 1, j, k + 1)) % mod; + + long ans = 0; + for (int j = 0; j < 2; j++) { + for (int k = 0; k < 3; k++) { + ans = (ans + dp[n - 1][j][k]) % MOD; + } } - return f[i][j][k] = ans; + return (int) ans; } - -private: - int n; -}; +} ``` ```cpp @@ -366,10 +316,46 @@ public: }; ``` -### **...** +```go +const _mod int = 1e9 + 7 -``` +func checkRecord(n int) int { + dp := make([][][]int, n) + for i := 0; i < n; i++ { + dp[i] = make([][]int, 2) + for j := 0; j < 2; j++ { + dp[i][j] = make([]int, 3) + } + } + // base case + dp[0][0][0] = 1 + dp[0][0][1] = 1 + dp[0][1][0] = 1 + + for i := 1; i < n; i++ { + // A + dp[i][1][0] = (dp[i-1][0][0] + dp[i-1][0][1] + dp[i-1][0][2]) % _mod + // L + dp[i][0][1] = dp[i-1][0][0] + dp[i][0][2] = dp[i-1][0][1] + dp[i][1][1] = dp[i-1][1][0] + dp[i][1][2] = dp[i-1][1][1] + // P + dp[i][0][0] = (dp[i-1][0][0] + dp[i-1][0][1] + dp[i-1][0][2]) % _mod + dp[i][1][0] = (dp[i][1][0] + dp[i-1][1][0] + dp[i-1][1][1] + dp[i-1][1][2]) % _mod + } + + var ans int + for j := 0; j < 2; j++ { + for k := 0; k < 3; k++ { + ans = (ans + dp[n-1][j][k]) % _mod + } + } + return ans +} ``` + + diff --git a/solution/0500-0599/0552.Student Attendance Record II/README_EN.md b/solution/0500-0599/0552.Student Attendance Record II/README_EN.md index c69c77935c36e..d9eb5b8a0fc6e 100644 --- a/solution/0500-0599/0552.Student Attendance Record II/README_EN.md +++ b/solution/0500-0599/0552.Student Attendance Record II/README_EN.md @@ -55,9 +55,9 @@ Only "AA" is not eligible because there are 2 absences (there need to ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,38 +80,6 @@ class Solution: return ans ``` -```python -class Solution: - def checkRecord(self, n: int) -> int: - mod = int(1e9 + 7) - dp = [[[0, 0, 0], [0, 0, 0]] for _ in range(n)] - - # base case - dp[0][0][0] = dp[0][0][1] = dp[0][1][0] = 1 - - for i in range(1, n): - # A - dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % mod - # L - dp[i][0][1] = dp[i - 1][0][0] - dp[i][0][2] = dp[i - 1][0][1] - dp[i][1][1] = dp[i - 1][1][0] - dp[i][1][2] = dp[i - 1][1][1] - # P - dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % mod - dp[i][1][0] = ( - dp[i][1][0] + dp[i - 1][1][0] + dp[i - 1][1][1] + dp[i - 1][1][2] - ) % mod - - ans = 0 - for j in range(2): - for k in range(3): - ans = (ans + dp[n - 1][j][k]) % mod - return ans -``` - -### **Java** - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -143,43 +111,39 @@ class Solution { } ``` -```java -class Solution { - private static final int MOD = 1000000007; - - public int checkRecord(int n) { - long[][][] dp = new long[n][2][3]; +```cpp +int f[100010][2][3]; +const int mod = 1e9 + 7; - // base case - dp[0][0][0] = 1; - dp[0][0][1] = 1; - dp[0][1][0] = 1; +class Solution { +public: + int checkRecord(int n) { + this->n = n; + memset(f, -1, sizeof(f)); + return dfs(0, 0, 0); + } - for (int i = 1; i < n; i++) { - // A - dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; - // L - dp[i][0][1] = dp[i - 1][0][0]; - dp[i][0][2] = dp[i - 1][0][1]; - dp[i][1][1] = dp[i - 1][1][0]; - dp[i][1][2] = dp[i - 1][1][1]; - // P - dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; - dp[i][1][0] = (dp[i][1][0] + dp[i - 1][1][0] + dp[i - 1][1][1] + dp[i - 1][1][2]) % MOD; + int dfs(int i, int j, int k) { + if (i >= n) { + return 1; } - - long ans = 0; - for (int j = 0; j < 2; j++) { - for (int k = 0; k < 3; k++) { - ans = (ans + dp[n - 1][j][k]) % MOD; - } + if (f[i][j][k] != -1) { + return f[i][j][k]; } - return (int) ans; + int ans = dfs(i + 1, j, 0); + if (j == 0) { + ans = (ans + dfs(i + 1, j + 1, 0)) % mod; + } + if (k < 2) { + ans = (ans + dfs(i + 1, j, k + 1)) % mod; + } + return f[i][j][k] = ans; } -} -``` -### **Go** +private: + int n; +}; +``` ```go func checkRecord(n int) int { @@ -216,80 +180,76 @@ func checkRecord(n int) int { } ``` -```go -const _mod int = 1e9 + 7 + -func checkRecord(n int) int { - dp := make([][][]int, n) - for i := 0; i < n; i++ { - dp[i] = make([][]int, 2) - for j := 0; j < 2; j++ { - dp[i][j] = make([]int, 3) - } - } +### Solution 2 - // base case - dp[0][0][0] = 1 - dp[0][0][1] = 1 - dp[0][1][0] = 1 + - for i := 1; i < n; i++ { - // A - dp[i][1][0] = (dp[i-1][0][0] + dp[i-1][0][1] + dp[i-1][0][2]) % _mod - // L - dp[i][0][1] = dp[i-1][0][0] - dp[i][0][2] = dp[i-1][0][1] - dp[i][1][1] = dp[i-1][1][0] - dp[i][1][2] = dp[i-1][1][1] - // P - dp[i][0][0] = (dp[i-1][0][0] + dp[i-1][0][1] + dp[i-1][0][2]) % _mod - dp[i][1][0] = (dp[i][1][0] + dp[i-1][1][0] + dp[i-1][1][1] + dp[i-1][1][2]) % _mod - } +```python +class Solution: + def checkRecord(self, n: int) -> int: + mod = int(1e9 + 7) + dp = [[[0, 0, 0], [0, 0, 0]] for _ in range(n)] - var ans int - for j := 0; j < 2; j++ { - for k := 0; k < 3; k++ { - ans = (ans + dp[n-1][j][k]) % _mod - } - } - return ans -} -``` + # base case + dp[0][0][0] = dp[0][0][1] = dp[0][1][0] = 1 -### **C++** + for i in range(1, n): + # A + dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % mod + # L + dp[i][0][1] = dp[i - 1][0][0] + dp[i][0][2] = dp[i - 1][0][1] + dp[i][1][1] = dp[i - 1][1][0] + dp[i][1][2] = dp[i - 1][1][1] + # P + dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % mod + dp[i][1][0] = ( + dp[i][1][0] + dp[i - 1][1][0] + dp[i - 1][1][1] + dp[i - 1][1][2] + ) % mod -```cpp -int f[100010][2][3]; -const int mod = 1e9 + 7; + ans = 0 + for j in range(2): + for k in range(3): + ans = (ans + dp[n - 1][j][k]) % mod + return ans +``` +```java class Solution { -public: - int checkRecord(int n) { - this->n = n; - memset(f, -1, sizeof(f)); - return dfs(0, 0, 0); - } + private static final int MOD = 1000000007; - int dfs(int i, int j, int k) { - if (i >= n) { - return 1; - } - if (f[i][j][k] != -1) { - return f[i][j][k]; - } - int ans = dfs(i + 1, j, 0); - if (j == 0) { - ans = (ans + dfs(i + 1, j + 1, 0)) % mod; + public int checkRecord(int n) { + long[][][] dp = new long[n][2][3]; + + // base case + dp[0][0][0] = 1; + dp[0][0][1] = 1; + dp[0][1][0] = 1; + + for (int i = 1; i < n; i++) { + // A + dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; + // L + dp[i][0][1] = dp[i - 1][0][0]; + dp[i][0][2] = dp[i - 1][0][1]; + dp[i][1][1] = dp[i - 1][1][0]; + dp[i][1][2] = dp[i - 1][1][1]; + // P + dp[i][0][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + dp[i - 1][0][2]) % MOD; + dp[i][1][0] = (dp[i][1][0] + dp[i - 1][1][0] + dp[i - 1][1][1] + dp[i - 1][1][2]) % MOD; } - if (k < 2) { - ans = (ans + dfs(i + 1, j, k + 1)) % mod; + + long ans = 0; + for (int j = 0; j < 2; j++) { + for (int k = 0; k < 3; k++) { + ans = (ans + dp[n - 1][j][k]) % MOD; + } } - return f[i][j][k] = ans; + return (int) ans; } - -private: - int n; -}; +} ``` ```cpp @@ -328,10 +288,46 @@ public: }; ``` -### **...** +```go +const _mod int = 1e9 + 7 -``` +func checkRecord(n int) int { + dp := make([][][]int, n) + for i := 0; i < n; i++ { + dp[i] = make([][]int, 2) + for j := 0; j < 2; j++ { + dp[i][j] = make([]int, 3) + } + } + + // base case + dp[0][0][0] = 1 + dp[0][0][1] = 1 + dp[0][1][0] = 1 + + for i := 1; i < n; i++ { + // A + dp[i][1][0] = (dp[i-1][0][0] + dp[i-1][0][1] + dp[i-1][0][2]) % _mod + // L + dp[i][0][1] = dp[i-1][0][0] + dp[i][0][2] = dp[i-1][0][1] + dp[i][1][1] = dp[i-1][1][0] + dp[i][1][2] = dp[i-1][1][1] + // P + dp[i][0][0] = (dp[i-1][0][0] + dp[i-1][0][1] + dp[i-1][0][2]) % _mod + dp[i][1][0] = (dp[i][1][0] + dp[i-1][1][0] + dp[i-1][1][1] + dp[i-1][1][2]) % _mod + } + var ans int + for j := 0; j < 2; j++ { + for k := 0; k < 3; k++ { + ans = (ans + dp[n-1][j][k]) % _mod + } + } + return ans +} ``` + + diff --git a/solution/0500-0599/0553.Optimal Division/README.md b/solution/0500-0599/0553.Optimal Division/README.md index 420bc447aceea..51c6b93677015 100644 --- a/solution/0500-0599/0553.Optimal Division/README.md +++ b/solution/0500-0599/0553.Optimal Division/README.md @@ -59,20 +59,10 @@ ## 解法 - - -贪心。 - -要使得除法的结果最大,分子应该尽可能大,而分母应该尽可能小。 - -分子最大应该是 `nums[0]`,而分母最大是 `nums[1] / nums[2] / ... / nums[n - 1]`,此时的除法结果最大。 +### 方法一 -### **Python3** - - - ```python class Solution: def optimalDivision(self, nums: List[int]) -> str: @@ -84,10 +74,6 @@ class Solution: return f'{nums[0]}/({"/".join(map(str, nums[1:]))})' ``` -### **Java** - - - ```java class Solution { public String optimalDivision(int[] nums) { @@ -108,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +109,6 @@ public: }; ``` -### **Go** - ```go func optimalDivision(nums []int) string { n := len(nums) @@ -147,8 +129,6 @@ func optimalDivision(nums []int) string { } ``` -### **TypeScript** - ```ts function optimalDivision(nums: number[]): string { const n = nums.length; @@ -161,8 +141,6 @@ function optimalDivision(nums: number[]): string { } ``` -### **Rust** - ```rust impl Solution { pub fn optimal_division(nums: Vec) -> String { @@ -186,10 +164,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0553.Optimal Division/README_EN.md b/solution/0500-0599/0553.Optimal Division/README_EN.md index bba1c16200c43..1a5ed3bb201c6 100644 --- a/solution/0500-0599/0553.Optimal Division/README_EN.md +++ b/solution/0500-0599/0553.Optimal Division/README_EN.md @@ -52,9 +52,9 @@ It can be shown that after trying all possibilities, we cannot get an expression ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return f'{nums[0]}/({"/".join(map(str, nums[1:]))})' ``` -### **Java** - ```java class Solution { public String optimalDivision(int[] nums) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +102,6 @@ public: }; ``` -### **Go** - ```go func optimalDivision(nums []int) string { n := len(nums) @@ -128,8 +122,6 @@ func optimalDivision(nums []int) string { } ``` -### **TypeScript** - ```ts function optimalDivision(nums: number[]): string { const n = nums.length; @@ -142,8 +134,6 @@ function optimalDivision(nums: number[]): string { } ``` -### **Rust** - ```rust impl Solution { pub fn optimal_division(nums: Vec) -> String { @@ -167,10 +157,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0554.Brick Wall/README.md b/solution/0500-0599/0554.Brick Wall/README.md index a0c285b617e47..d8b949c25d698 100644 --- a/solution/0500-0599/0554.Brick Wall/README.md +++ b/solution/0500-0599/0554.Brick Wall/README.md @@ -41,16 +41,10 @@ ## 解法 - - -题目可以理解为,让垂线尽可能多地穿过砖块边缘,用哈希表处理不同位置的砖块边缘出现的频次(不包括两个垂直边缘),最终的答案就是总行数减去最大频数。 +### 方法一 -### **Python3** - - - ```python class Solution: def leastBricks(self, wall: List[List[int]]) -> int: @@ -65,10 +59,6 @@ class Solution: return len(wall) - cnt[max(cnt, key=cnt.get)] ``` -### **Java** - - - ```java class Solution { public int leastBricks(List> wall) { @@ -86,8 +76,6 @@ class Solution { } ``` -### **Go** - ```go func leastBricks(wall [][]int) int { cnt := make(map[int]int) @@ -108,8 +96,6 @@ func leastBricks(wall [][]int) int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} wall @@ -132,10 +118,6 @@ var leastBricks = function (wall) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0554.Brick Wall/README_EN.md b/solution/0500-0599/0554.Brick Wall/README_EN.md index e50efad17cca4..a3b54f02772e5 100644 --- a/solution/0500-0599/0554.Brick Wall/README_EN.md +++ b/solution/0500-0599/0554.Brick Wall/README_EN.md @@ -39,12 +39,10 @@ ## Solutions -The question can be understood as, let the vertical line pass through the edge of the brick as much as possible, use the hash table to process the frequency of the brick edge in different positions (not including the two vertical edges), and the final answer is the total number of rows minus the maximum Frequency. +### Solution 1 -### **Python3** - ```python class Solution: def leastBricks(self, wall: List[List[int]]) -> int: @@ -59,8 +57,6 @@ class Solution: return len(wall) - cnt[max(cnt, key=cnt.get)] ``` -### **Java** - ```java class Solution { public int leastBricks(List> wall) { @@ -78,8 +74,6 @@ class Solution { } ``` -### **Go** - ```go func leastBricks(wall [][]int) int { cnt := make(map[int]int) @@ -100,8 +94,6 @@ func leastBricks(wall [][]int) int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} wall @@ -124,10 +116,6 @@ var leastBricks = function (wall) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0555.Split Concatenated Strings/README.md b/solution/0500-0599/0555.Split Concatenated Strings/README.md index dca489ad142c8..6501f3a9d7f69 100644 --- a/solution/0500-0599/0555.Split Concatenated Strings/README.md +++ b/solution/0500-0599/0555.Split Concatenated Strings/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们先遍历字符串数组 `strs`,对于每个字符串 $s$,如果 $s$ 的反转字符串 $t$ 比 $s$ 大,那么我们就将 $s$ 替换为 $t$。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def splitLoopedString(self, strs: List[str]) -> str: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public String splitLoopedString(String[] strs) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +158,6 @@ public: }; ``` -### **Go** - ```go func splitLoopedString(strs []string) (ans string) { for i, s := range strs { @@ -213,10 +199,6 @@ func reverse(s string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0555.Split Concatenated Strings/README_EN.md b/solution/0500-0599/0555.Split Concatenated Strings/README_EN.md index 7020646891611..18fbca597487c 100644 --- a/solution/0500-0599/0555.Split Concatenated Strings/README_EN.md +++ b/solution/0500-0599/0555.Split Concatenated Strings/README_EN.md @@ -46,9 +46,9 @@ The answer string came from the fourth looped one, where you could cut from the ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public String splitLoopedString(String[] strs) { @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +148,6 @@ public: }; ``` -### **Go** - ```go func splitLoopedString(strs []string) (ans string) { for i, s := range strs { @@ -195,10 +189,6 @@ func reverse(s string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0556.Next Greater Element III/README.md b/solution/0500-0599/0556.Next Greater Element III/README.md index 6586d150c0491..ecd063ba2c8b3 100644 --- a/solution/0500-0599/0556.Next Greater Element III/README.md +++ b/solution/0500-0599/0556.Next Greater Element III/README.md @@ -36,16 +36,10 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 -### **Python3** - - - ```python class Solution: def nextGreaterElement(self, n: int) -> int: @@ -64,10 +58,6 @@ class Solution: return -1 if ans > 2**31 - 1 else ans ``` -### **Java** - - - ```java class Solution { public int nextGreaterElement(int n) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func nextGreaterElement(n int) int { s := []byte(strconv.Itoa(n)) @@ -149,10 +135,6 @@ func nextGreaterElement(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0556.Next Greater Element III/README_EN.md b/solution/0500-0599/0556.Next Greater Element III/README_EN.md index b9880031e00b9..cf047f7ad5f62 100644 --- a/solution/0500-0599/0556.Next Greater Element III/README_EN.md +++ b/solution/0500-0599/0556.Next Greater Element III/README_EN.md @@ -25,9 +25,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -47,8 +47,6 @@ class Solution: return -1 if ans > 2**31 - 1 else ans ``` -### **Java** - ```java class Solution { public int nextGreaterElement(int n) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +100,6 @@ public: }; ``` -### **Go** - ```go func nextGreaterElement(n int) int { s := []byte(strconv.Itoa(n)) @@ -130,10 +124,6 @@ func nextGreaterElement(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0557.Reverse Words in a String III/README.md b/solution/0500-0599/0557.Reverse Words in a String III/README.md index db4cce4b64360..5668d6c3c42e7 100644 --- a/solution/0500-0599/0557.Reverse Words in a String III/README.md +++ b/solution/0500-0599/0557.Reverse Words in a String III/README.md @@ -38,24 +38,16 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def reverseWords(self, s: str) -> str: return ' '.join([t[::-1] for t in s.split(' ')]) ``` -### **Java** - - - ```java class Solution { public String reverseWords(String s) { @@ -71,8 +63,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,8 +79,6 @@ public: }; ``` -### **Go** - ```go func reverseWords(s string) string { t := []byte(s) @@ -108,8 +96,6 @@ func reverseWords(s string) string { } ``` -### **TypeScript** - ```ts function reverseWords(s: string): string { return s @@ -125,8 +111,6 @@ function reverseWords(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn reverse_words(s: String) -> String { @@ -138,8 +122,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -156,10 +138,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0557.Reverse Words in a String III/README_EN.md b/solution/0500-0599/0557.Reverse Words in a String III/README_EN.md index 01a01dea23681..c1a90546cebc9 100644 --- a/solution/0500-0599/0557.Reverse Words in a String III/README_EN.md +++ b/solution/0500-0599/0557.Reverse Words in a String III/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -44,8 +44,6 @@ class Solution: return ' '.join([t[::-1] for t in s.split(' ')]) ``` -### **Java** - ```java class Solution { public String reverseWords(String s) { @@ -61,8 +59,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -79,8 +75,6 @@ public: }; ``` -### **Go** - ```go func reverseWords(s string) string { t := []byte(s) @@ -98,8 +92,6 @@ func reverseWords(s string) string { } ``` -### **TypeScript** - ```ts function reverseWords(s: string): string { return s @@ -115,8 +107,6 @@ function reverseWords(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn reverse_words(s: String) -> String { @@ -128,8 +118,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -146,10 +134,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/README.md b/solution/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/README.md index efc74772cd92c..85295d5ed02e0 100644 --- a/solution/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/README.md +++ b/solution/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/README.md @@ -112,14 +112,10 @@ class Node { ## 解法 - +### 方法一 -### **Python3** - - - ```python """ # Definition for a QuadTree node. @@ -167,10 +163,6 @@ class Solution: return dfs(quadTree1, quadTree2) ``` -### **Java** - - - ```java /* // Definition for a QuadTree node. @@ -223,8 +215,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a QuadTree node. @@ -289,8 +279,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a QuadTree node. @@ -339,10 +327,6 @@ func intersect(quadTree1 *Node, quadTree2 *Node) *Node { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/README_EN.md b/solution/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/README_EN.md index 2c9efac8f56c7..40c4d49af3e9d 100644 --- a/solution/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/README_EN.md +++ b/solution/0500-0599/0558.Logical OR of Two Binary Grids Represented as Quad-Trees/README_EN.md @@ -79,9 +79,9 @@ The resulting matrix is of size 1*1 with also zero. ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -130,8 +130,6 @@ class Solution: return dfs(quadTree1, quadTree2) ``` -### **Java** - ```java /* // Definition for a QuadTree node. @@ -184,8 +182,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a QuadTree node. @@ -250,8 +246,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a QuadTree node. @@ -300,10 +294,6 @@ func intersect(quadTree1 *Node, quadTree2 *Node) *Node { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0559.Maximum Depth of N-ary Tree/README.md b/solution/0500-0599/0559.Maximum Depth of N-ary Tree/README.md index 8c5d67bf776f9..4394b0372a84b 100644 --- a/solution/0500-0599/0559.Maximum Depth of N-ary Tree/README.md +++ b/solution/0500-0599/0559.Maximum Depth of N-ary Tree/README.md @@ -43,14 +43,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python """ # Definition for a Node. @@ -68,10 +64,6 @@ class Solution: return 1 + max([self.maxDepth(child) for child in root.children], default=0) ``` -### **Java** - - - ```java /* // Definition for a Node. @@ -106,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -140,8 +130,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -163,10 +151,6 @@ func maxDepth(root *Node) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0559.Maximum Depth of N-ary Tree/README_EN.md b/solution/0500-0599/0559.Maximum Depth of N-ary Tree/README_EN.md index 1dabb00e98e99..a1c4230dc6916 100644 --- a/solution/0500-0599/0559.Maximum Depth of N-ary Tree/README_EN.md +++ b/solution/0500-0599/0559.Maximum Depth of N-ary Tree/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -60,8 +60,6 @@ class Solution: return 1 + max([self.maxDepth(child) for child in root.children], default=0) ``` -### **Java** - ```java /* // Definition for a Node. @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -130,8 +126,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -153,10 +147,6 @@ func maxDepth(root *Node) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0560.Subarray Sum Equals K/README.md b/solution/0500-0599/0560.Subarray Sum Equals K/README.md index 5b55d9625b580..97da8d8fb768f 100644 --- a/solution/0500-0599/0560.Subarray Sum Equals K/README.md +++ b/solution/0500-0599/0560.Subarray Sum Equals K/README.md @@ -38,14 +38,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def subarraySum(self, nums: List[int], k: int) -> int: @@ -58,10 +54,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int subarraySum(int[] nums, int k) { @@ -78,25 +70,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function subarraySum(nums: number[], k: number): number { - let ans = 0, - s = 0; - const counter = new Map(); - counter.set(0, 1); - for (const num of nums) { - s += num; - ans += counter.get(s - k) || 0; - counter.set(s, (counter.get(s) || 0) + 1); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -114,8 +87,6 @@ public: }; ``` -### **Go** - ```go func subarraySum(nums []int, k int) int { counter := map[int]int{0: 1} @@ -129,7 +100,20 @@ func subarraySum(nums []int, k int) int { } ``` -### **Rust** +```ts +function subarraySum(nums: number[], k: number): number { + let ans = 0, + s = 0; + const counter = new Map(); + counter.set(0, 1); + for (const num of nums) { + s += num; + ans += counter.get(s - k) || 0; + counter.set(s, (counter.get(s) || 0) + 1); + } + return ans; +} +``` ```rust impl Solution { @@ -153,6 +137,12 @@ impl Solution { } ``` + + +### 方法二 + + + ```rust use std::collections::HashMap; @@ -172,10 +162,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0560.Subarray Sum Equals K/README_EN.md b/solution/0500-0599/0560.Subarray Sum Equals K/README_EN.md index 55b0184e289f6..088a6fad091da 100644 --- a/solution/0500-0599/0560.Subarray Sum Equals K/README_EN.md +++ b/solution/0500-0599/0560.Subarray Sum Equals K/README_EN.md @@ -27,9 +27,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -43,8 +43,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int subarraySum(int[] nums, int k) { @@ -61,25 +59,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function subarraySum(nums: number[], k: number): number { - let ans = 0, - s = 0; - const counter = new Map(); - counter.set(0, 1); - for (const num of nums) { - s += num; - ans += counter.get(s - k) || 0; - counter.set(s, (counter.get(s) || 0) + 1); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -97,8 +76,6 @@ public: }; ``` -### **Go** - ```go func subarraySum(nums []int, k int) int { counter := map[int]int{0: 1} @@ -112,7 +89,20 @@ func subarraySum(nums []int, k int) int { } ``` -### **Rust** +```ts +function subarraySum(nums: number[], k: number): number { + let ans = 0, + s = 0; + const counter = new Map(); + counter.set(0, 1); + for (const num of nums) { + s += num; + ans += counter.get(s - k) || 0; + counter.set(s, (counter.get(s) || 0) + 1); + } + return ans; +} +``` ```rust impl Solution { @@ -136,6 +126,12 @@ impl Solution { } ``` + + +### Solution 2 + + + ```rust use std::collections::HashMap; @@ -155,10 +151,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0561.Array Partition/README.md b/solution/0500-0599/0561.Array Partition/README.md index d93bdd981e24e..f1525d3461817 100644 --- a/solution/0500-0599/0561.Array Partition/README.md +++ b/solution/0500-0599/0561.Array Partition/README.md @@ -43,28 +43,18 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 先排序,然后求相邻的两个元素的最小值,得到的总和即为结果。 -### **Python3** - - - ```python class Solution: def arrayPairSum(self, nums: List[int]) -> int: return sum(sorted(nums)[::2]) ``` -### **Java** - - - ```java class Solution { public int arrayPairSum(int[] nums) { @@ -78,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -92,8 +80,6 @@ public: }; ``` -### **Go** - ```go func arrayPairSum(nums []int) int { sort.Ints(nums) @@ -105,25 +91,6 @@ func arrayPairSum(nums []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var arrayPairSum = function (nums) { - nums.sort((a, b) => a - b); - let ans = 0; - for (let i = 0; i < nums.length; i += 2) { - ans += nums[i]; - } - return ans; -}; -``` - -### **Rust** - ```rust impl Solution { pub fn array_pair_sum(mut nums: Vec) -> i32 { @@ -140,16 +107,21 @@ impl Solution { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - +```js +/** + * @param {number[]} nums + * @return {number} + */ +var arrayPairSum = function (nums) { + nums.sort((a, b) => a - b); + let ans = 0; + for (let i = 0; i < nums.length; i += 2) { + ans += nums[i]; + } + return ans; +}; ``` + + diff --git a/solution/0500-0599/0561.Array Partition/README_EN.md b/solution/0500-0599/0561.Array Partition/README_EN.md index 29456c7efaed2..939d7e88a8ea1 100644 --- a/solution/0500-0599/0561.Array Partition/README_EN.md +++ b/solution/0500-0599/0561.Array Partition/README_EN.md @@ -37,9 +37,9 @@ So the maximum possible sum is 4. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -47,8 +47,6 @@ class Solution: return sum(sorted(nums)[::2]) ``` -### **Java** - ```java class Solution { public int arrayPairSum(int[] nums) { @@ -62,8 +60,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -76,8 +72,6 @@ public: }; ``` -### **Go** - ```go func arrayPairSum(nums []int) int { sort.Ints(nums) @@ -89,25 +83,6 @@ func arrayPairSum(nums []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var arrayPairSum = function (nums) { - nums.sort((a, b) => a - b); - let ans = 0; - for (let i = 0; i < nums.length; i += 2) { - ans += nums[i]; - } - return ans; -}; -``` - -### **Rust** - ```rust impl Solution { pub fn array_pair_sum(mut nums: Vec) -> i32 { @@ -124,16 +99,21 @@ impl Solution { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - +```js +/** + * @param {number[]} nums + * @return {number} + */ +var arrayPairSum = function (nums) { + nums.sort((a, b) => a - b); + let ans = 0; + for (let i = 0; i < nums.length; i += 2) { + ans += nums[i]; + } + return ans; +}; ``` + + diff --git a/solution/0500-0599/0562.Longest Line of Consecutive One in Matrix/README.md b/solution/0500-0599/0562.Longest Line of Consecutive One in Matrix/README.md index 56a357dd52608..2283366d0bb83 100644 --- a/solution/0500-0599/0562.Longest Line of Consecutive One in Matrix/README.md +++ b/solution/0500-0599/0562.Longest Line of Consecutive One in Matrix/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j][k]$ 表示方向为 $k$,且以 $(i, j)$ 结尾的最长连续 $1$ 的长度。其中 $k$ 的取值范围为 $0, 1, 2, 3$,分别表示水平、垂直、对角线、反对角线。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def longestLine(self, mat: List[List[int]]) -> int: @@ -82,10 +76,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestLine(int[][] mat) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +135,6 @@ public: }; ``` -### **Go** - ```go func longestLine(mat [][]int) (ans int) { m, n := len(mat), len(mat[0]) @@ -175,10 +161,6 @@ func longestLine(mat [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0562.Longest Line of Consecutive One in Matrix/README_EN.md b/solution/0500-0599/0562.Longest Line of Consecutive One in Matrix/README_EN.md index d2f3f11475b41..3be493700f938 100644 --- a/solution/0500-0599/0562.Longest Line of Consecutive One in Matrix/README_EN.md +++ b/solution/0500-0599/0562.Longest Line of Consecutive One in Matrix/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestLine(int[][] mat) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func longestLine(mat [][]int) (ans int) { m, n := len(mat), len(mat[0]) @@ -151,10 +145,6 @@ func longestLine(mat [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0563.Binary Tree Tilt/README.md b/solution/0500-0599/0563.Binary Tree Tilt/README.md index c41b8fe5ed629..6ff744b1fd2c3 100644 --- a/solution/0500-0599/0563.Binary Tree Tilt/README.md +++ b/solution/0500-0599/0563.Binary Tree Tilt/README.md @@ -59,14 +59,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -91,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -132,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -165,8 +155,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -201,10 +189,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0563.Binary Tree Tilt/README_EN.md b/solution/0500-0599/0563.Binary Tree Tilt/README_EN.md index 5fa17ec0810c8..39a1226b4dfcf 100644 --- a/solution/0500-0599/0563.Binary Tree Tilt/README_EN.md +++ b/solution/0500-0599/0563.Binary Tree Tilt/README_EN.md @@ -53,9 +53,9 @@ Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15 ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -81,8 +81,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -120,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -153,8 +149,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -189,10 +183,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0564.Find the Closest Palindrome/README.md b/solution/0500-0599/0564.Find the Closest Palindrome/README.md index 9b301d0b20a66..5829cc4ebf6ca 100644 --- a/solution/0500-0599/0564.Find the Closest Palindrome/README.md +++ b/solution/0500-0599/0564.Find the Closest Palindrome/README.md @@ -40,21 +40,10 @@ ## 解法 - - -- 用原数的前半部分替换后半部分得到的回文整数。 -- 用原数的前半部分加一后的结果替换后半部分得到的回文整数。 -- 用原数的前半部分减一后的结果替换后半部分得到的回文整数。 -- 为防止位数变化导致构造的回文整数错误,因此直接构造 999999…999 和 100…001 作为备选答案。 - -求以上数字中,最接近原数且不等于原数的最小数字。 +### 方法一 -### **Python3** - - - ```python class Solution: def nearestPalindromic(self, n: str) -> str: @@ -81,10 +70,6 @@ class Solution: return str(ans) ``` -### **Java** - - - ```java class Solution { public String nearestPalindromic(String n) { @@ -117,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +131,6 @@ public: }; ``` -### **Go** - ```go func nearestPalindromic(n string) string { l := len(n) @@ -185,10 +166,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0564.Find the Closest Palindrome/README_EN.md b/solution/0500-0599/0564.Find the Closest Palindrome/README_EN.md index 1cdf6af10c76b..bca9ac7bc6a44 100644 --- a/solution/0500-0599/0564.Find the Closest Palindrome/README_EN.md +++ b/solution/0500-0599/0564.Find the Closest Palindrome/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return str(ans) ``` -### **Java** - ```java class Solution { public String nearestPalindromic(String n) { @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +127,6 @@ public: }; ``` -### **Go** - ```go func nearestPalindromic(n string) string { l := len(n) @@ -168,10 +162,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0565.Array Nesting/README.md b/solution/0500-0599/0565.Array Nesting/README.md index e583fa56b05f1..e6c9f0b56923d 100644 --- a/solution/0500-0599/0565.Array Nesting/README.md +++ b/solution/0500-0599/0565.Array Nesting/README.md @@ -36,26 +36,14 @@ S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0} ## 解法 - - -**方法一:图** +### 方法一:图 嵌套数组最终一定会形成一个环,在枚举 $nums[i]$ 的过程中,可以用 $vis$ 数组剪枝,避免重复枚举同一个环。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。 -**方法二:原地标记** - -由于 $nums$ 元素均在 $[0..n-1]$ 之间,因此,对于访问过的元素,我们可以令 $nums[i]=n$,从而省略 $vis$ 数组。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def arrayNesting(self, nums: List[int]) -> int: @@ -75,25 +63,6 @@ class Solution: return res ``` -```python -class Solution: - def arrayNesting(self, nums: List[int]) -> int: - ans, n = 0, len(nums) - for i in range(n): - cnt = 0 - while nums[i] != n: - j = nums[i] - nums[i] = n - i = j - cnt += 1 - ans = max(ans, cnt) - return ans -``` - -### **Java** - - - ```java class Solution { public int arrayNesting(int[] nums) { @@ -118,28 +87,6 @@ class Solution { } ``` -```java -class Solution { - public int arrayNesting(int[] nums) { - int ans = 0, n = nums.length; - for (int i = 0; i < n; ++i) { - int cnt = 0; - int j = i; - while (nums[j] < n) { - int k = nums[j]; - nums[j] = n; - j = k; - ++cnt; - } - ans = Math.max(ans, cnt); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -163,29 +110,6 @@ public: }; ``` -```cpp -class Solution { -public: - int arrayNesting(vector& nums) { - int ans = 0, n = nums.size(); - for (int i = 0; i < n; ++i) { - int cnt = 0; - int j = i; - while (nums[j] < n) { - int k = nums[j]; - nums[j] = n; - j = k; - ++cnt; - } - ans = max(ans, cnt); - } - return ans; - } -}; -``` - -### **Go** - ```go func arrayNesting(nums []int) int { n := len(nums) @@ -210,6 +134,72 @@ func arrayNesting(nums []int) int { } ``` + + +### 方法二:原地标记 + +由于 $nums$ 元素均在 $[0..n-1]$ 之间,因此,对于访问过的元素,我们可以令 $nums[i]=n$,从而省略 $vis$ 数组。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def arrayNesting(self, nums: List[int]) -> int: + ans, n = 0, len(nums) + for i in range(n): + cnt = 0 + while nums[i] != n: + j = nums[i] + nums[i] = n + i = j + cnt += 1 + ans = max(ans, cnt) + return ans +``` + +```java +class Solution { + public int arrayNesting(int[] nums) { + int ans = 0, n = nums.length; + for (int i = 0; i < n; ++i) { + int cnt = 0; + int j = i; + while (nums[j] < n) { + int k = nums[j]; + nums[j] = n; + j = k; + ++cnt; + } + ans = Math.max(ans, cnt); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int arrayNesting(vector& nums) { + int ans = 0, n = nums.size(); + for (int i = 0; i < n; ++i) { + int cnt = 0; + int j = i; + while (nums[j] < n) { + int k = nums[j]; + nums[j] = n; + j = k; + ++cnt; + } + ans = max(ans, cnt); + } + return ans; + } +}; +``` + ```go func arrayNesting(nums []int) int { ans, n := 0, len(nums) @@ -229,10 +219,6 @@ func arrayNesting(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0565.Array Nesting/README_EN.md b/solution/0500-0599/0565.Array Nesting/README_EN.md index 265bd43c37608..32917e9926279 100644 --- a/solution/0500-0599/0565.Array Nesting/README_EN.md +++ b/solution/0500-0599/0565.Array Nesting/README_EN.md @@ -46,9 +46,9 @@ s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0} ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,23 +69,6 @@ class Solution: return res ``` -```python -class Solution: - def arrayNesting(self, nums: List[int]) -> int: - ans, n = 0, len(nums) - for i in range(n): - cnt = 0 - while nums[i] != n: - j = nums[i] - nums[i] = n - i = j - cnt += 1 - ans = max(ans, cnt) - return ans -``` - -### **Java** - ```java class Solution { public int arrayNesting(int[] nums) { @@ -110,28 +93,6 @@ class Solution { } ``` -```java -class Solution { - public int arrayNesting(int[] nums) { - int ans = 0, n = nums.length; - for (int i = 0; i < n; ++i) { - int cnt = 0; - int j = i; - while (nums[j] < n) { - int k = nums[j]; - nums[j] = n; - j = k; - ++cnt; - } - ans = Math.max(ans, cnt); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -155,29 +116,6 @@ public: }; ``` -```cpp -class Solution { -public: - int arrayNesting(vector& nums) { - int ans = 0, n = nums.size(); - for (int i = 0; i < n; ++i) { - int cnt = 0; - int j = i; - while (nums[j] < n) { - int k = nums[j]; - nums[j] = n; - j = k; - ++cnt; - } - ans = max(ans, cnt); - } - return ans; - } -}; -``` - -### **Go** - ```go func arrayNesting(nums []int) int { n := len(nums) @@ -202,6 +140,68 @@ func arrayNesting(nums []int) int { } ``` + + +### Solution 2 + + + +```python +class Solution: + def arrayNesting(self, nums: List[int]) -> int: + ans, n = 0, len(nums) + for i in range(n): + cnt = 0 + while nums[i] != n: + j = nums[i] + nums[i] = n + i = j + cnt += 1 + ans = max(ans, cnt) + return ans +``` + +```java +class Solution { + public int arrayNesting(int[] nums) { + int ans = 0, n = nums.length; + for (int i = 0; i < n; ++i) { + int cnt = 0; + int j = i; + while (nums[j] < n) { + int k = nums[j]; + nums[j] = n; + j = k; + ++cnt; + } + ans = Math.max(ans, cnt); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int arrayNesting(vector& nums) { + int ans = 0, n = nums.size(); + for (int i = 0; i < n; ++i) { + int cnt = 0; + int j = i; + while (nums[j] < n) { + int k = nums[j]; + nums[j] = n; + j = k; + ++cnt; + } + ans = max(ans, cnt); + } + return ans; + } +}; +``` + ```go func arrayNesting(nums []int) int { ans, n := 0, len(nums) @@ -221,10 +221,6 @@ func arrayNesting(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0566.Reshape the Matrix/README.md b/solution/0500-0599/0566.Reshape the Matrix/README.md index 58fb6f4aa4049..67171d8c91320 100644 --- a/solution/0500-0599/0566.Reshape the Matrix/README.md +++ b/solution/0500-0599/0566.Reshape the Matrix/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们先获取原矩阵的行数和列数,分别记为 $m$ 和 $n$。如果 $m \times n \neq r \times c$,则无法重塑矩阵,直接返回原矩阵。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]: @@ -74,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] matrixReshape(int[][] mat, int r, int c) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func matrixReshape(mat [][]int, r int, c int) [][]int { m, n := len(mat), len(mat[0]) @@ -132,8 +118,6 @@ func matrixReshape(mat [][]int, r int, c int) [][]int { } ``` -### **TypeScript** - ```ts function matrixReshape(mat: number[][], r: number, c: number): number[][] { let m = mat.length, @@ -151,23 +135,6 @@ function matrixReshape(mat: number[][], r: number, c: number): number[][] { } ``` -```ts -function matrixReshape(mat: number[][], r: number, c: number): number[][] { - const m = mat.length; - const n = mat[0].length; - if (m * n !== r * c) { - return mat; - } - const ans = Array.from({ length: r }, () => new Array(c).fill(0)); - for (let i = 0; i < r * c; i++) { - ans[Math.floor(i / c)][i % c] = mat[Math.floor(i / n)][i % n]; - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn matrix_reshape(mat: Vec>, r: i32, c: i32) -> Vec> { @@ -201,8 +168,6 @@ impl Solution { } ``` -### **C** - ```c /** * Return an array of arrays of size *returnSize. @@ -229,10 +194,27 @@ int** matrixReshape(int** mat, int matSize, int* matColSize, int r, int c, int* } ``` -### **...** + -``` +### 方法二 + + +```ts +function matrixReshape(mat: number[][], r: number, c: number): number[][] { + const m = mat.length; + const n = mat[0].length; + if (m * n !== r * c) { + return mat; + } + const ans = Array.from({ length: r }, () => new Array(c).fill(0)); + for (let i = 0; i < r * c; i++) { + ans[Math.floor(i / c)][i % c] = mat[Math.floor(i / n)][i % n]; + } + return ans; +} ``` + + diff --git a/solution/0500-0599/0566.Reshape the Matrix/README_EN.md b/solution/0500-0599/0566.Reshape the Matrix/README_EN.md index c2ef86092edf3..4c2b74eda13fc 100644 --- a/solution/0500-0599/0566.Reshape the Matrix/README_EN.md +++ b/solution/0500-0599/0566.Reshape the Matrix/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] matrixReshape(int[][] mat, int r, int c) { @@ -74,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +89,6 @@ public: }; ``` -### **Go** - ```go func matrixReshape(mat [][]int, r int, c int) [][]int { m, n := len(mat), len(mat[0]) @@ -112,8 +106,6 @@ func matrixReshape(mat [][]int, r int, c int) [][]int { } ``` -### **TypeScrpt** - ```ts function matrixReshape(mat: number[][], r: number, c: number): number[][] { let m = mat.length, @@ -131,23 +123,6 @@ function matrixReshape(mat: number[][], r: number, c: number): number[][] { } ``` -```ts -function matrixReshape(mat: number[][], r: number, c: number): number[][] { - const m = mat.length; - const n = mat[0].length; - if (m * n !== r * c) { - return mat; - } - const ans = Array.from({ length: r }, () => new Array(c).fill(0)); - for (let i = 0; i < r * c; i++) { - ans[Math.floor(i / c)][i % c] = mat[Math.floor(i / n)][i % n]; - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn matrix_reshape(mat: Vec>, r: i32, c: i32) -> Vec> { @@ -181,8 +156,6 @@ impl Solution { } ``` -### **C** - ```c /** * Return an array of arrays of size *returnSize. @@ -209,10 +182,27 @@ int** matrixReshape(int** mat, int matSize, int* matColSize, int r, int c, int* } ``` -### **...** + -``` +### Solution 2 + + +```ts +function matrixReshape(mat: number[][], r: number, c: number): number[][] { + const m = mat.length; + const n = mat[0].length; + if (m * n !== r * c) { + return mat; + } + const ans = Array.from({ length: r }, () => new Array(c).fill(0)); + for (let i = 0; i < r * c; i++) { + ans[Math.floor(i / c)][i % c] = mat[Math.floor(i / n)][i % n]; + } + return ans; +} ``` + + diff --git a/solution/0500-0599/0567.Permutation in String/README.md b/solution/0500-0599/0567.Permutation in String/README.md index 989be39087096..e088337cfc589 100644 --- a/solution/0500-0599/0567.Permutation in String/README.md +++ b/solution/0500-0599/0567.Permutation in String/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 我们观察发现,题目实际上等价于判断字符串 $s2$ 中是否存在窗口大小为 $n$,且窗口内的字符及其个数与字符串 $s1$ 相同的子串。 @@ -50,18 +48,8 @@ 时间复杂度 $(n + m \times C)$,空间复杂度 $O(C)$。其中 $n$ 和 $m$ 分别为字符串 $s1$ 和 $s2$ 的长度;而 $C$ 为字符集的大小,本题中 $C=26$。 -**方法二:滑动窗口优化** - -在方法一中,我们每次加入和移除一个字符时,都需要比较两个哈希表或数组,时间复杂度较高。我们可以维护一个变量 $diff$,表示两个大小为 $n$ 的字符串中,有多少种字符出现的个数不同。当 $diff=0$ 时,说明两个字符串中的字符个数相同。 - -时间复杂度 $O(n + m)$,空间复杂度 $O(C)$。其中 $n$ 和 $m$ 分别为字符串 $s1$ 和 $s2$ 的长度;而 $C$ 为字符集的大小,本题中 $C=26$。 - -### **Python3** - - - ```python class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: @@ -78,43 +66,6 @@ class Solution: return False ``` -```python -class Solution: - def checkInclusion(self, s1: str, s2: str) -> bool: - n, m = len(s1), len(s2) - if n > m: - return False - cnt = Counter() - for a, b in zip(s1, s2): - cnt[a] -= 1 - cnt[b] += 1 - diff = sum(x != 0 for x in cnt.values()) - if diff == 0: - return True - for i in range(n, m): - a, b = s2[i - n], s2[i] - - if cnt[b] == 0: - diff += 1 - cnt[b] += 1 - if cnt[b] == 0: - diff -= 1 - - if cnt[a] == 0: - diff += 1 - cnt[a] -= 1 - if cnt[a] == 0: - diff -= 1 - - if diff == 0: - return True - return False -``` - -### **Java** - - - ```java class Solution { public boolean checkInclusion(String s1, String s2) { @@ -144,54 +95,6 @@ class Solution { } ``` -```java -class Solution { - public boolean checkInclusion(String s1, String s2) { - int n = s1.length(); - int m = s2.length(); - if (n > m) { - return false; - } - int[] cnt = new int[26]; - for (int i = 0; i < n; ++i) { - --cnt[s1.charAt(i) - 'a']; - ++cnt[s2.charAt(i) - 'a']; - } - int diff = 0; - for (int x : cnt) { - if (x != 0) { - ++diff; - } - } - if (diff == 0) { - return true; - } - for (int i = n; i < m; ++i) { - int a = s2.charAt(i - n) - 'a'; - int b = s2.charAt(i) - 'a'; - if (cnt[b] == 0) { - ++diff; - } - if (++cnt[b] == 0) { - --diff; - } - if (cnt[a] == 0) { - ++diff; - } - if (--cnt[a] == 0) { - --diff; - } - if (diff == 0) { - return true; - } - } - return false; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -220,54 +123,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool checkInclusion(string s1, string s2) { - int n = s1.size(), m = s2.size(); - if (n > m) { - return false; - } - vector cnt(26); - for (int i = 0; i < n; ++i) { - --cnt[s1[i] - 'a']; - ++cnt[s2[i] - 'a']; - } - int diff = 0; - for (int x : cnt) { - if (x) { - ++diff; - } - } - if (diff == 0) { - return true; - } - for (int i = n; i < m; ++i) { - int a = s2[i - n] - 'a'; - int b = s2[i] - 'a'; - if (cnt[b] == 0) { - ++diff; - } - if (++cnt[b] == 0) { - --diff; - } - if (cnt[a] == 0) { - ++diff; - } - if (--cnt[a] == 0) { - --diff; - } - if (diff == 0) { - return true; - } - } - return false; - } -}; -``` - -### **Go** - ```go func checkInclusion(s1 string, s2 string) bool { n, m := len(s1), len(s2) @@ -294,52 +149,6 @@ func checkInclusion(s1 string, s2 string) bool { } ``` -```go -func checkInclusion(s1 string, s2 string) bool { - n, m := len(s1), len(s2) - if n > m { - return false - } - cnt := [26]int{} - for i := range s1 { - cnt[s1[i]-'a']-- - cnt[s2[i]-'a']++ - } - diff := 0 - for _, x := range cnt { - if x != 0 { - diff++ - } - } - if diff == 0 { - return true - } - for i := n; i < m; i++ { - a, b := s2[i-n]-'a', s2[i]-'a' - if cnt[b] == 0 { - diff++ - } - cnt[b]++ - if cnt[b] == 0 { - diff-- - } - if cnt[a] == 0 { - diff++ - } - cnt[a]-- - if cnt[a] == 0 { - diff-- - } - if diff == 0 { - return true - } - } - return false -} -``` - -### **TypeScript** - ```ts function checkInclusion(s1: string, s2: string): boolean { // 滑动窗口方案 @@ -386,8 +195,6 @@ function checkInclusion(s1: string, s2: string): boolean { } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -437,7 +244,190 @@ impl Solution { } ``` -### **Go** + + +### 方法二:滑动窗口优化 + +在方法一中,我们每次加入和移除一个字符时,都需要比较两个哈希表或数组,时间复杂度较高。我们可以维护一个变量 $diff$,表示两个大小为 $n$ 的字符串中,有多少种字符出现的个数不同。当 $diff=0$ 时,说明两个字符串中的字符个数相同。 + +时间复杂度 $O(n + m)$,空间复杂度 $O(C)$。其中 $n$ 和 $m$ 分别为字符串 $s1$ 和 $s2$ 的长度;而 $C$ 为字符集的大小,本题中 $C=26$。 + + + +```python +class Solution: + def checkInclusion(self, s1: str, s2: str) -> bool: + n, m = len(s1), len(s2) + if n > m: + return False + cnt = Counter() + for a, b in zip(s1, s2): + cnt[a] -= 1 + cnt[b] += 1 + diff = sum(x != 0 for x in cnt.values()) + if diff == 0: + return True + for i in range(n, m): + a, b = s2[i - n], s2[i] + + if cnt[b] == 0: + diff += 1 + cnt[b] += 1 + if cnt[b] == 0: + diff -= 1 + + if cnt[a] == 0: + diff += 1 + cnt[a] -= 1 + if cnt[a] == 0: + diff -= 1 + + if diff == 0: + return True + return False +``` + +```java +class Solution { + public boolean checkInclusion(String s1, String s2) { + int n = s1.length(); + int m = s2.length(); + if (n > m) { + return false; + } + int[] cnt = new int[26]; + for (int i = 0; i < n; ++i) { + --cnt[s1.charAt(i) - 'a']; + ++cnt[s2.charAt(i) - 'a']; + } + int diff = 0; + for (int x : cnt) { + if (x != 0) { + ++diff; + } + } + if (diff == 0) { + return true; + } + for (int i = n; i < m; ++i) { + int a = s2.charAt(i - n) - 'a'; + int b = s2.charAt(i) - 'a'; + if (cnt[b] == 0) { + ++diff; + } + if (++cnt[b] == 0) { + --diff; + } + if (cnt[a] == 0) { + ++diff; + } + if (--cnt[a] == 0) { + --diff; + } + if (diff == 0) { + return true; + } + } + return false; + } +} +``` + +```cpp +class Solution { +public: + bool checkInclusion(string s1, string s2) { + int n = s1.size(), m = s2.size(); + if (n > m) { + return false; + } + vector cnt(26); + for (int i = 0; i < n; ++i) { + --cnt[s1[i] - 'a']; + ++cnt[s2[i] - 'a']; + } + int diff = 0; + for (int x : cnt) { + if (x) { + ++diff; + } + } + if (diff == 0) { + return true; + } + for (int i = n; i < m; ++i) { + int a = s2[i - n] - 'a'; + int b = s2[i] - 'a'; + if (cnt[b] == 0) { + ++diff; + } + if (++cnt[b] == 0) { + --diff; + } + if (cnt[a] == 0) { + ++diff; + } + if (--cnt[a] == 0) { + --diff; + } + if (diff == 0) { + return true; + } + } + return false; + } +}; +``` + +```go +func checkInclusion(s1 string, s2 string) bool { + n, m := len(s1), len(s2) + if n > m { + return false + } + cnt := [26]int{} + for i := range s1 { + cnt[s1[i]-'a']-- + cnt[s2[i]-'a']++ + } + diff := 0 + for _, x := range cnt { + if x != 0 { + diff++ + } + } + if diff == 0 { + return true + } + for i := n; i < m; i++ { + a, b := s2[i-n]-'a', s2[i]-'a' + if cnt[b] == 0 { + diff++ + } + cnt[b]++ + if cnt[b] == 0 { + diff-- + } + if cnt[a] == 0 { + diff++ + } + cnt[a]-- + if cnt[a] == 0 { + diff-- + } + if diff == 0 { + return true + } + } + return false +} +``` + + + +### 方法三 + + ```go func checkInclusion(s1 string, s2 string) bool { @@ -468,10 +458,6 @@ func checkInclusion(s1 string, s2 string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0567.Permutation in String/README_EN.md b/solution/0500-0599/0567.Permutation in String/README_EN.md index 6a738cd9bd7c8..509c90cf3591e 100644 --- a/solution/0500-0599/0567.Permutation in String/README_EN.md +++ b/solution/0500-0599/0567.Permutation in String/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,41 +54,6 @@ class Solution: return False ``` -```python -class Solution: - def checkInclusion(self, s1: str, s2: str) -> bool: - n, m = len(s1), len(s2) - if n > m: - return False - cnt = Counter() - for a, b in zip(s1, s2): - cnt[a] -= 1 - cnt[b] += 1 - diff = sum(x != 0 for x in cnt.values()) - if diff == 0: - return True - for i in range(n, m): - a, b = s2[i - n], s2[i] - - if cnt[b] == 0: - diff += 1 - cnt[b] += 1 - if cnt[b] == 0: - diff -= 1 - - if cnt[a] == 0: - diff += 1 - cnt[a] -= 1 - if cnt[a] == 0: - diff -= 1 - - if diff == 0: - return True - return False -``` - -### **Java** - ```java class Solution { public boolean checkInclusion(String s1, String s2) { @@ -118,54 +83,6 @@ class Solution { } ``` -```java -class Solution { - public boolean checkInclusion(String s1, String s2) { - int n = s1.length(); - int m = s2.length(); - if (n > m) { - return false; - } - int[] cnt = new int[26]; - for (int i = 0; i < n; ++i) { - --cnt[s1.charAt(i) - 'a']; - ++cnt[s2.charAt(i) - 'a']; - } - int diff = 0; - for (int x : cnt) { - if (x != 0) { - ++diff; - } - } - if (diff == 0) { - return true; - } - for (int i = n; i < m; ++i) { - int a = s2.charAt(i - n) - 'a'; - int b = s2.charAt(i) - 'a'; - if (cnt[b] == 0) { - ++diff; - } - if (++cnt[b] == 0) { - --diff; - } - if (cnt[a] == 0) { - ++diff; - } - if (--cnt[a] == 0) { - --diff; - } - if (diff == 0) { - return true; - } - } - return false; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -194,54 +111,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool checkInclusion(string s1, string s2) { - int n = s1.size(), m = s2.size(); - if (n > m) { - return false; - } - vector cnt(26); - for (int i = 0; i < n; ++i) { - --cnt[s1[i] - 'a']; - ++cnt[s2[i] - 'a']; - } - int diff = 0; - for (int x : cnt) { - if (x) { - ++diff; - } - } - if (diff == 0) { - return true; - } - for (int i = n; i < m; ++i) { - int a = s2[i - n] - 'a'; - int b = s2[i] - 'a'; - if (cnt[b] == 0) { - ++diff; - } - if (++cnt[b] == 0) { - --diff; - } - if (cnt[a] == 0) { - ++diff; - } - if (--cnt[a] == 0) { - --diff; - } - if (diff == 0) { - return true; - } - } - return false; - } -}; -``` - -### **Go** - ```go func checkInclusion(s1 string, s2 string) bool { n, m := len(s1), len(s2) @@ -268,54 +137,9 @@ func checkInclusion(s1 string, s2 string) bool { } ``` -```go -func checkInclusion(s1 string, s2 string) bool { - n, m := len(s1), len(s2) - if n > m { - return false - } - cnt := [26]int{} - for i := range s1 { - cnt[s1[i]-'a']-- - cnt[s2[i]-'a']++ - } - diff := 0 - for _, x := range cnt { - if x != 0 { - diff++ - } - } - if diff == 0 { - return true - } - for i := n; i < m; i++ { - a, b := s2[i-n]-'a', s2[i]-'a' - if cnt[b] == 0 { - diff++ - } - cnt[b]++ - if cnt[b] == 0 { - diff-- - } - if cnt[a] == 0 { - diff++ - } - cnt[a]-- - if cnt[a] == 0 { - diff-- - } - if diff == 0 { - return true - } - } - return false -} -``` - -### **TypeScript** - ```ts function checkInclusion(s1: string, s2: string): boolean { + // 滑动窗口方案 if (s1.length > s2.length) { return false; } @@ -359,12 +183,11 @@ function checkInclusion(s1: string, s2: string): boolean { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { + // 测试两个哈希表是否匹配 fn is_match(m1: &HashMap, m2: &HashMap) -> bool { for (k, v) in m1.iter() { if m2.get(k).unwrap_or(&0) != v { @@ -379,10 +202,12 @@ impl Solution { } let mut m1 = HashMap::new(); let mut m2 = HashMap::new(); + // 初始化表 1 for c in s1.chars() { m1.insert(c, m1.get(&c).unwrap_or(&0) + 1); } let cs: Vec = s2.chars().collect(); + // 初始化窗口 let mut i = 0; while i < s1.len() { m2.insert(cs[i], m2.get(&cs[i]).unwrap_or(&0) + 1); @@ -391,6 +216,7 @@ impl Solution { if Self::is_match(&m1, &m2) { return true; } + // 持续滑动窗口,直到匹配或超出边界 let mut j = 0; while i < cs.len() { m2.insert(cs[j], m2.get(&cs[j]).unwrap_or(&1) - 1); @@ -406,7 +232,186 @@ impl Solution { } ``` -### **Go** + + +### Solution 2 + + + +```python +class Solution: + def checkInclusion(self, s1: str, s2: str) -> bool: + n, m = len(s1), len(s2) + if n > m: + return False + cnt = Counter() + for a, b in zip(s1, s2): + cnt[a] -= 1 + cnt[b] += 1 + diff = sum(x != 0 for x in cnt.values()) + if diff == 0: + return True + for i in range(n, m): + a, b = s2[i - n], s2[i] + + if cnt[b] == 0: + diff += 1 + cnt[b] += 1 + if cnt[b] == 0: + diff -= 1 + + if cnt[a] == 0: + diff += 1 + cnt[a] -= 1 + if cnt[a] == 0: + diff -= 1 + + if diff == 0: + return True + return False +``` + +```java +class Solution { + public boolean checkInclusion(String s1, String s2) { + int n = s1.length(); + int m = s2.length(); + if (n > m) { + return false; + } + int[] cnt = new int[26]; + for (int i = 0; i < n; ++i) { + --cnt[s1.charAt(i) - 'a']; + ++cnt[s2.charAt(i) - 'a']; + } + int diff = 0; + for (int x : cnt) { + if (x != 0) { + ++diff; + } + } + if (diff == 0) { + return true; + } + for (int i = n; i < m; ++i) { + int a = s2.charAt(i - n) - 'a'; + int b = s2.charAt(i) - 'a'; + if (cnt[b] == 0) { + ++diff; + } + if (++cnt[b] == 0) { + --diff; + } + if (cnt[a] == 0) { + ++diff; + } + if (--cnt[a] == 0) { + --diff; + } + if (diff == 0) { + return true; + } + } + return false; + } +} +``` + +```cpp +class Solution { +public: + bool checkInclusion(string s1, string s2) { + int n = s1.size(), m = s2.size(); + if (n > m) { + return false; + } + vector cnt(26); + for (int i = 0; i < n; ++i) { + --cnt[s1[i] - 'a']; + ++cnt[s2[i] - 'a']; + } + int diff = 0; + for (int x : cnt) { + if (x) { + ++diff; + } + } + if (diff == 0) { + return true; + } + for (int i = n; i < m; ++i) { + int a = s2[i - n] - 'a'; + int b = s2[i] - 'a'; + if (cnt[b] == 0) { + ++diff; + } + if (++cnt[b] == 0) { + --diff; + } + if (cnt[a] == 0) { + ++diff; + } + if (--cnt[a] == 0) { + --diff; + } + if (diff == 0) { + return true; + } + } + return false; + } +}; +``` + +```go +func checkInclusion(s1 string, s2 string) bool { + n, m := len(s1), len(s2) + if n > m { + return false + } + cnt := [26]int{} + for i := range s1 { + cnt[s1[i]-'a']-- + cnt[s2[i]-'a']++ + } + diff := 0 + for _, x := range cnt { + if x != 0 { + diff++ + } + } + if diff == 0 { + return true + } + for i := n; i < m; i++ { + a, b := s2[i-n]-'a', s2[i]-'a' + if cnt[b] == 0 { + diff++ + } + cnt[b]++ + if cnt[b] == 0 { + diff-- + } + if cnt[a] == 0 { + diff++ + } + cnt[a]-- + if cnt[a] == 0 { + diff-- + } + if diff == 0 { + return true + } + } + return false +} +``` + + + +### Solution 3 + + ```go func checkInclusion(s1 string, s2 string) bool { @@ -421,7 +426,6 @@ func checkInclusion(s1 string, s2 string) bool { if need[c] == window[c] { validate++ } - // shrink window for right-left+1 >= len(s1) { if validate == len(need) { return true @@ -438,10 +442,6 @@ func checkInclusion(s1 string, s2 string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0568.Maximum Vacation Days/README.md b/solution/0500-0599/0568.Maximum Vacation Days/README.md index e875855de01fc..13af677725d4f 100644 --- a/solution/0500-0599/0568.Maximum Vacation Days/README.md +++ b/solution/0500-0599/0568.Maximum Vacation Days/README.md @@ -78,9 +78,7 @@ Ans = 7 + 7 + 7 = 21 ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[k][j]$ 表示前 $k$ 周,且最后一周在城市 $j$ 休假的最长天数。初始时 $f[0][0]=0$,其它 $f[0][j]=-\infty$。答案为 $\max_{j=0}^{n-1} f[K][j]$。 @@ -92,10 +90,6 @@ Ans = 7 + 7 + 7 = 21 -### **Python3** - - - ```python class Solution: def maxVacationDays(self, flights: List[List[int]], days: List[List[int]]) -> int: @@ -113,10 +107,6 @@ class Solution: return max(f[-1][j] for j in range(n)) ``` -### **Java** - - - ```java class Solution { public int maxVacationDays(int[][] flights, int[][] days) { @@ -148,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -179,8 +167,6 @@ public: }; ``` -### **Go** - ```go func maxVacationDays(flights [][]int, days [][]int) (ans int) { n, K := len(flights), len(days[0]) @@ -210,10 +196,6 @@ func maxVacationDays(flights [][]int, days [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0568.Maximum Vacation Days/README_EN.md b/solution/0500-0599/0568.Maximum Vacation Days/README_EN.md index e809b03fd994c..d1c55042e9630 100644 --- a/solution/0500-0599/0568.Maximum Vacation Days/README_EN.md +++ b/solution/0500-0599/0568.Maximum Vacation Days/README_EN.md @@ -75,9 +75,9 @@ Ans = 7 + 7 + 7 = 21 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -96,8 +96,6 @@ class Solution: return max(f[-1][j] for j in range(n)) ``` -### **Java** - ```java class Solution { public int maxVacationDays(int[][] flights, int[][] days) { @@ -129,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +156,6 @@ public: }; ``` -### **Go** - ```go func maxVacationDays(flights [][]int, days [][]int) (ans int) { n, K := len(flights), len(days[0]) @@ -191,10 +185,6 @@ func maxVacationDays(flights [][]int, days [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0569.Median Employee Salary/README.md b/solution/0500-0599/0569.Median Employee Salary/README.md index ac794abc51609..57e014753c3de 100644 --- a/solution/0500-0599/0569.Median Employee Salary/README.md +++ b/solution/0500-0599/0569.Median Employee Salary/README.md @@ -74,12 +74,10 @@ Employee 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -102,3 +100,5 @@ WHERE rk >= n / 2 AND rk <= n / 2 + 1; ``` + + diff --git a/solution/0500-0599/0569.Median Employee Salary/README_EN.md b/solution/0500-0599/0569.Median Employee Salary/README_EN.md index 637f9e964a2c0..1a75242023183 100644 --- a/solution/0500-0599/0569.Median Employee Salary/README_EN.md +++ b/solution/0500-0599/0569.Median Employee Salary/README_EN.md @@ -103,9 +103,9 @@ For company C, the rows sorted are as follows: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -129,3 +129,5 @@ WHERE rk >= n / 2 AND rk <= n / 2 + 1; ``` + + diff --git a/solution/0500-0599/0570.Managers with at Least 5 Direct Reports/README.md b/solution/0500-0599/0570.Managers with at Least 5 Direct Reports/README.md index ae4842949cb74..a91df962ccbad 100644 --- a/solution/0500-0599/0570.Managers with at Least 5 Direct Reports/README.md +++ b/solution/0500-0599/0570.Managers with at Least 5 Direct Reports/README.md @@ -57,32 +57,12 @@ Employee 表: ## 解法 - - -**方法一:分组统计 + 连接** +### 方法一:分组统计 + 连接 我们可以先统计每个经理的直接下属人数,然后再连接 `Employee` 表,找出直接下属人数大于等于 $5$ 的经理。 -### **SQL** - -```sql -# Write your MySQL query statement below -SELECT name -FROM - Employee - JOIN ( - SELECT managerId AS id, COUNT(1) AS cnt - FROM Employee - GROUP BY 1 - HAVING cnt >= 5 - ) AS t - USING (id); -``` - -### **Pandas** - ```python import pandas as pd @@ -107,4 +87,20 @@ def find_managers(employee: pd.DataFrame) -> pd.DataFrame: return result ``` +```sql +# Write your MySQL query statement below +SELECT name +FROM + Employee + JOIN ( + SELECT managerId AS id, COUNT(1) AS cnt + FROM Employee + GROUP BY 1 + HAVING cnt >= 5 + ) AS t + USING (id); +``` + + + diff --git a/solution/0500-0599/0570.Managers with at Least 5 Direct Reports/README_EN.md b/solution/0500-0599/0570.Managers with at Least 5 Direct Reports/README_EN.md index b0f12d8fe943e..d2cea770b807a 100644 --- a/solution/0500-0599/0570.Managers with at Least 5 Direct Reports/README_EN.md +++ b/solution/0500-0599/0570.Managers with at Least 5 Direct Reports/README_EN.md @@ -55,30 +55,12 @@ Employee table: ## Solutions -**Solution 1: Grouping and Joining** +### Solution 1: Grouping and Joining We can first count the number of direct subordinates for each manager, and then join the `Employee` table to find the managers whose number of direct subordinates is greater than or equal to $5$. -### **SQL** - -```sql -# Write your MySQL query statement below -SELECT name -FROM - Employee - JOIN ( - SELECT managerId AS id, COUNT(1) AS cnt - FROM Employee - GROUP BY 1 - HAVING cnt >= 5 - ) AS t - USING (id); -``` - -### **Pandas** - ```python import pandas as pd @@ -103,4 +85,20 @@ def find_managers(employee: pd.DataFrame) -> pd.DataFrame: return result ``` +```sql +# Write your MySQL query statement below +SELECT name +FROM + Employee + JOIN ( + SELECT managerId AS id, COUNT(1) AS cnt + FROM Employee + GROUP BY 1 + HAVING cnt >= 5 + ) AS t + USING (id); +``` + + + diff --git a/solution/0500-0599/0571.Find Median Given Frequency of Numbers/README.md b/solution/0500-0599/0571.Find Median Given Frequency of Numbers/README.md index 238e70919bf7a..0a133085d1bcd 100644 --- a/solution/0500-0599/0571.Find Median Given Frequency of Numbers/README.md +++ b/solution/0500-0599/0571.Find Median Given Frequency of Numbers/README.md @@ -58,14 +58,10 @@ Numbers 表: ## 解法 - - -**方法一:开窗函数** +### 方法一:开窗函数 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -83,10 +79,6 @@ FROM t WHERE rk1 >= s / 2 AND rk2 >= s / 2; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0571.Find Median Given Frequency of Numbers/README_EN.md b/solution/0500-0599/0571.Find Median Given Frequency of Numbers/README_EN.md index 4646064a1bf90..aff1d87333f4e 100644 --- a/solution/0500-0599/0571.Find Median Given Frequency of Numbers/README_EN.md +++ b/solution/0500-0599/0571.Find Median Given Frequency of Numbers/README_EN.md @@ -51,9 +51,9 @@ If we decompress the Numbers table, we will get [0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2 ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -72,10 +72,6 @@ FROM t WHERE rk1 >= s / 2 AND rk2 >= s / 2; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0572.Subtree of Another Tree/README.md b/solution/0500-0599/0572.Subtree of Another Tree/README.md index 55584eeaeb997..97f84b12e3d2b 100644 --- a/solution/0500-0599/0572.Subtree of Another Tree/README.md +++ b/solution/0500-0599/0572.Subtree of Another Tree/README.md @@ -43,14 +43,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -80,10 +76,6 @@ class Solution: ) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -122,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -151,8 +141,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -180,41 +168,6 @@ func isSubtree(root *TreeNode, subRoot *TreeNode) bool { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @param {TreeNode} subRoot - * @return {boolean} - */ -var isSubtree = function (root, subRoot) { - if (!root) return false; - let dfs = function (root1, root2) { - if (!root1 && !root2) { - return true; - } - if (!root1 || !root2) { - return false; - } - return ( - root1.val == root2.val && dfs(root1.left, root2.left) && dfs(root1.right, root2.right) - ); - }; - return dfs(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -248,8 +201,6 @@ function isSubtree(root: TreeNode | null, subRoot: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -307,10 +258,37 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} subRoot + * @return {boolean} + */ +var isSubtree = function (root, subRoot) { + if (!root) return false; + let dfs = function (root1, root2) { + if (!root1 && !root2) { + return true; + } + if (!root1 || !root2) { + return false; + } + return ( + root1.val == root2.val && dfs(root1.left, root2.left) && dfs(root1.right, root2.right) + ); + }; + return dfs(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); +}; ``` + + diff --git a/solution/0500-0599/0572.Subtree of Another Tree/README_EN.md b/solution/0500-0599/0572.Subtree of Another Tree/README_EN.md index 4f63dac747f8d..8c0a7d3f0af45 100644 --- a/solution/0500-0599/0572.Subtree of Another Tree/README_EN.md +++ b/solution/0500-0599/0572.Subtree of Another Tree/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -68,8 +68,6 @@ class Solution: ) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -137,8 +133,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -166,41 +160,6 @@ func isSubtree(root *TreeNode, subRoot *TreeNode) bool { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @param {TreeNode} subRoot - * @return {boolean} - */ -var isSubtree = function (root, subRoot) { - if (!root) return false; - let dfs = function (root1, root2) { - if (!root1 && !root2) { - return true; - } - if (!root1 || !root2) { - return false; - } - return ( - root1.val == root2.val && dfs(root1.left, root2.left) && dfs(root1.right, root2.right) - ); - }; - return dfs(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -234,8 +193,6 @@ function isSubtree(root: TreeNode | null, subRoot: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -293,10 +250,37 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} subRoot + * @return {boolean} + */ +var isSubtree = function (root, subRoot) { + if (!root) return false; + let dfs = function (root1, root2) { + if (!root1 && !root2) { + return true; + } + if (!root1 || !root2) { + return false; + } + return ( + root1.val == root2.val && dfs(root1.left, root2.left) && dfs(root1.right, root2.right) + ); + }; + return dfs(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); +}; ``` + + diff --git a/solution/0500-0599/0573.Squirrel Simulation/README.md b/solution/0500-0599/0573.Squirrel Simulation/README.md index 59eebfb752179..f476273d8ab58 100644 --- a/solution/0500-0599/0573.Squirrel Simulation/README.md +++ b/solution/0500-0599/0573.Squirrel Simulation/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:路径分析** +### 方法一:路径分析 我们观察松鼠的移动路径,可以发现,松鼠会首先移动到某个坚果的位置,然后移动到树的位置。接下来,松鼠的移动路径之和等于“其余坚果到树的位置之和”再乘以 $2$。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def minDistance( @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func minDistance(height int, width int, tree []int, squirrel []int, nuts [][]int) int { f := func(a, b []int) int { @@ -171,10 +157,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0573.Squirrel Simulation/README_EN.md b/solution/0500-0599/0573.Squirrel Simulation/README_EN.md index a5152553831b7..41e9b555519e7 100644 --- a/solution/0500-0599/0573.Squirrel Simulation/README_EN.md +++ b/solution/0500-0599/0573.Squirrel Simulation/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) { @@ -98,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +120,6 @@ public: }; ``` -### **Go** - ```go func minDistance(height int, width int, tree []int, squirrel []int, nuts [][]int) int { f := func(a, b []int) int { @@ -153,10 +147,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0574.Winning Candidate/README.md b/solution/0500-0599/0574.Winning Candidate/README.md index e0c7812d1dc14..7d096cd88d7c0 100644 --- a/solution/0500-0599/0574.Winning Candidate/README.md +++ b/solution/0500-0599/0574.Winning Candidate/README.md @@ -79,12 +79,10 @@ Vote table: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -101,6 +99,12 @@ FROM INNER JOIN Candidate AS c ON t.id = c.id; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below SELECT name @@ -113,3 +117,5 @@ LIMIT 1; ``` + + diff --git a/solution/0500-0599/0574.Winning Candidate/README_EN.md b/solution/0500-0599/0574.Winning Candidate/README_EN.md index f3ead4ae5ded0..7390c34853e90 100644 --- a/solution/0500-0599/0574.Winning Candidate/README_EN.md +++ b/solution/0500-0599/0574.Winning Candidate/README_EN.md @@ -79,9 +79,9 @@ The winner is candidate B. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -99,6 +99,12 @@ FROM INNER JOIN Candidate AS c ON t.id = c.id; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below SELECT name @@ -111,3 +117,5 @@ LIMIT 1; ``` + + diff --git a/solution/0500-0599/0575.Distribute Candies/README.md b/solution/0500-0599/0575.Distribute Candies/README.md index 8626434eaf408..5bec11f751e48 100644 --- a/solution/0500-0599/0575.Distribute Candies/README.md +++ b/solution/0500-0599/0575.Distribute Candies/README.md @@ -51,24 +51,16 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def distributeCandies(self, candyType: List[int]) -> int: return min(len(candyType) >> 1, len(set(candyType))) ``` -### **Java** - - - ```java class Solution { public int distributeCandies(int[] candyType) { @@ -81,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +84,6 @@ public: }; ``` -### **Go** - ```go func distributeCandies(candyType []int) int { s := hashset.New() @@ -106,10 +94,6 @@ func distributeCandies(candyType []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0575.Distribute Candies/README_EN.md b/solution/0500-0599/0575.Distribute Candies/README_EN.md index 2cb16427714ab..5ebf227d4eb68 100644 --- a/solution/0500-0599/0575.Distribute Candies/README_EN.md +++ b/solution/0500-0599/0575.Distribute Candies/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return min(len(candyType) >> 1, len(set(candyType))) ``` -### **Java** - ```java class Solution { public int distributeCandies(int[] candyType) { @@ -71,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -84,8 +80,6 @@ public: }; ``` -### **Go** - ```go func distributeCandies(candyType []int) int { s := hashset.New() @@ -96,10 +90,6 @@ func distributeCandies(candyType []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0576.Out of Boundary Paths/README.md b/solution/0500-0599/0576.Out of Boundary Paths/README.md index 73f6ff0757f28..57e4e3260e442 100644 --- a/solution/0500-0599/0576.Out of Boundary Paths/README.md +++ b/solution/0500-0599/0576.Out of Boundary Paths/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 定义 `dfs(i, j, k)` 表示当前位于坐标 $(i, j)$,且剩余移动次数为 $k$ 时,可以出界的路径数。记忆化搜索即可。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def findPaths( @@ -75,10 +69,6 @@ class Solution: return dfs(startRow, startColumn, maxMove) ``` -### **Java** - - - ```java class Solution { private int m; @@ -122,39 +112,6 @@ class Solution { } ``` -```java -class Solution { - public int findPaths(int m, int n, int N, int i, int j) { - final int MOD = (int) (1e9 + 7); - final int[] dirs = new int[] {-1, 0, 1, 0, -1}; - int[][] f = new int[m][n]; - f[i][j] = 1; - int res = 0; - for (int step = 0; step < N; ++step) { - int[][] temp = new int[m][n]; - for (int x = 0; x < m; ++x) { - for (int y = 0; y < n; ++y) { - for (int k = 0; k < 4; ++k) { - int tx = x + dirs[k], ty = y + dirs[k + 1]; - if (tx >= 0 && tx < m && ty >= 0 && ty < n) { - temp[tx][ty] += f[x][y]; - temp[tx][ty] %= MOD; - } else { - res += f[x][y]; - res %= MOD; - } - } - } - } - f = temp; - } - return res; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -187,8 +144,6 @@ public: }; ``` -### **Go** - ```go func findPaths(m int, n int, maxMove int, startRow int, startColumn int) int { f := make([][][]int, m+1) @@ -227,10 +182,43 @@ func findPaths(m int, n int, maxMove int, startRow int, startColumn int) int { } ``` -### **...** + -``` +### 方法二 + + +```java +class Solution { + public int findPaths(int m, int n, int N, int i, int j) { + final int MOD = (int) (1e9 + 7); + final int[] dirs = new int[] {-1, 0, 1, 0, -1}; + int[][] f = new int[m][n]; + f[i][j] = 1; + int res = 0; + for (int step = 0; step < N; ++step) { + int[][] temp = new int[m][n]; + for (int x = 0; x < m; ++x) { + for (int y = 0; y < n; ++y) { + for (int k = 0; k < 4; ++k) { + int tx = x + dirs[k], ty = y + dirs[k + 1]; + if (tx >= 0 && tx < m && ty >= 0 && ty < n) { + temp[tx][ty] += f[x][y]; + temp[tx][ty] %= MOD; + } else { + res += f[x][y]; + res %= MOD; + } + } + } + } + f = temp; + } + return res; + } +} ``` + + diff --git a/solution/0500-0599/0576.Out of Boundary Paths/README_EN.md b/solution/0500-0599/0576.Out of Boundary Paths/README_EN.md index e236e6204ace0..6f2a83cc1617a 100644 --- a/solution/0500-0599/0576.Out of Boundary Paths/README_EN.md +++ b/solution/0500-0599/0576.Out of Boundary Paths/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return dfs(startRow, startColumn, maxMove) ``` -### **Java** - ```java class Solution { private int m; @@ -106,39 +104,6 @@ class Solution { } ``` -```java -class Solution { - public int findPaths(int m, int n, int N, int i, int j) { - final int MOD = (int) (1e9 + 7); - final int[] dirs = new int[] {-1, 0, 1, 0, -1}; - int[][] f = new int[m][n]; - f[i][j] = 1; - int res = 0; - for (int step = 0; step < N; ++step) { - int[][] temp = new int[m][n]; - for (int x = 0; x < m; ++x) { - for (int y = 0; y < n; ++y) { - for (int k = 0; k < 4; ++k) { - int tx = x + dirs[k], ty = y + dirs[k + 1]; - if (tx >= 0 && tx < m && ty >= 0 && ty < n) { - temp[tx][ty] += f[x][y]; - temp[tx][ty] %= MOD; - } else { - res += f[x][y]; - res %= MOD; - } - } - } - } - f = temp; - } - return res; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -171,8 +136,6 @@ public: }; ``` -### **Go** - ```go func findPaths(m int, n int, maxMove int, startRow int, startColumn int) int { f := make([][][]int, m+1) @@ -211,10 +174,43 @@ func findPaths(m int, n int, maxMove int, startRow int, startColumn int) int { } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + public int findPaths(int m, int n, int N, int i, int j) { + final int MOD = (int) (1e9 + 7); + final int[] dirs = new int[] {-1, 0, 1, 0, -1}; + int[][] f = new int[m][n]; + f[i][j] = 1; + int res = 0; + for (int step = 0; step < N; ++step) { + int[][] temp = new int[m][n]; + for (int x = 0; x < m; ++x) { + for (int y = 0; y < n; ++y) { + for (int k = 0; k < 4; ++k) { + int tx = x + dirs[k], ty = y + dirs[k + 1]; + if (tx >= 0 && tx < m && ty >= 0 && ty < n) { + temp[tx][ty] += f[x][y]; + temp[tx][ty] %= MOD; + } else { + res += f[x][y]; + res %= MOD; + } + } + } + } + f = temp; + } + return res; + } +} ``` + + diff --git a/solution/0500-0599/0577.Employee Bonus/README.md b/solution/0500-0599/0577.Employee Bonus/README.md index df4eb6dec64e3..85093291042e7 100644 --- a/solution/0500-0599/0577.Employee Bonus/README.md +++ b/solution/0500-0599/0577.Employee Bonus/README.md @@ -78,16 +78,12 @@ Bonus table: ## 解法 - - -**方法一:左连接** +### 方法一:左连接 我们可以使用左连接,将 `Employee` 表和 `Bonus` 表按照 `empId` 进行连接,然后筛选出奖金小于 $1000$ 的员工。注意,连接后的表中,`bonus` 为 `NULL` 的员工也应该被筛选出来,因此我们需要使用 `IFNULL` 函数将 `NULL` 值转换为 $0$。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT name, bonus @@ -98,3 +94,5 @@ WHERE IFNULL(bonus, 0) < 1000; ``` + + diff --git a/solution/0500-0599/0577.Employee Bonus/README_EN.md b/solution/0500-0599/0577.Employee Bonus/README_EN.md index cd9d18b527fc1..c4408c3ada45d 100644 --- a/solution/0500-0599/0577.Employee Bonus/README_EN.md +++ b/solution/0500-0599/0577.Employee Bonus/README_EN.md @@ -76,14 +76,12 @@ Bonus table: ## Solutions -**Solution 1: Left Join** +### Solution 1: Left Join We can use a left join to join the `Employee` table and the `Bonus` table on `empId`, and then filter out the employees whose bonus is less than $1000$. Note that the employees with `NULL` bonus values after the join should also be filtered out, so we need to use the `IFNULL` function to convert `NULL` values to $0$. -### **SQL** - ```sql # Write your MySQL query statement below SELECT name, bonus @@ -94,3 +92,5 @@ WHERE IFNULL(bonus, 0) < 1000; ``` + + diff --git a/solution/0500-0599/0578.Get Highest Answer Rate Question/README.md b/solution/0500-0599/0578.Get Highest Answer Rate Question/README.md index 12085390e6f2c..70639ec3e4f6b 100644 --- a/solution/0500-0599/0578.Get Highest Answer Rate Question/README.md +++ b/solution/0500-0599/0578.Get Highest Answer Rate Question/README.md @@ -66,12 +66,10 @@ SurveyLog table: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT question_id AS survey_log @@ -81,6 +79,12 @@ ORDER BY SUM(action = 'answer') / SUM(action = 'show') DESC, 1 LIMIT 1; ``` + + +### 方法二 + + + ```sql WITH T AS ( @@ -98,3 +102,5 @@ LIMIT 1; ``` + + diff --git a/solution/0500-0599/0578.Get Highest Answer Rate Question/README_EN.md b/solution/0500-0599/0578.Get Highest Answer Rate Question/README_EN.md index 66c2de49df00e..fadfc51eaee2c 100644 --- a/solution/0500-0599/0578.Get Highest Answer Rate Question/README_EN.md +++ b/solution/0500-0599/0578.Get Highest Answer Rate Question/README_EN.md @@ -59,9 +59,9 @@ Question 285 has the highest answer rate. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -72,6 +72,12 @@ ORDER BY SUM(action = 'answer') / SUM(action = 'show') DESC, 1 LIMIT 1; ``` + + +### Solution 2 + + + ```sql WITH T AS ( @@ -89,3 +95,5 @@ LIMIT 1; ``` + + diff --git a/solution/0500-0599/0579.Find Cumulative Salary of an Employee/README.md b/solution/0500-0599/0579.Find Cumulative Salary of an Employee/README.md index c16c5752a9d52..7bede348a5092 100644 --- a/solution/0500-0599/0579.Find Cumulative Salary of an Employee/README.md +++ b/solution/0500-0599/0579.Find Cumulative Salary of an Employee/README.md @@ -110,12 +110,10 @@ Employee table: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -138,6 +136,12 @@ WHERE ORDER BY id, month DESC; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below WITH @@ -163,3 +167,5 @@ ORDER BY 1, 2 DESC; ``` + + diff --git a/solution/0500-0599/0579.Find Cumulative Salary of an Employee/README_EN.md b/solution/0500-0599/0579.Find Cumulative Salary of an Employee/README_EN.md index aeb53ff54e10f..b92b31f3e1395 100644 --- a/solution/0500-0599/0579.Find Cumulative Salary of an Employee/README_EN.md +++ b/solution/0500-0599/0579.Find Cumulative Salary of an Employee/README_EN.md @@ -108,9 +108,9 @@ So the cumulative salary summary for this employee is: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -134,6 +134,12 @@ WHERE ORDER BY id, month DESC; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below WITH @@ -159,3 +165,5 @@ ORDER BY 1, 2 DESC; ``` + + diff --git a/solution/0500-0599/0580.Count Student Number in Departments/README.md b/solution/0500-0599/0580.Count Student Number in Departments/README.md index f3898d6b11fb8..238a938e6b49e 100644 --- a/solution/0500-0599/0580.Count Student Number in Departments/README.md +++ b/solution/0500-0599/0580.Count Student Number in Departments/README.md @@ -77,16 +77,12 @@ Department 表: ## 解法 - - -**方法一:左连接 + 分组统计** +### 方法一:左连接 + 分组统计 我们可以使用左连接,将 `Department` 表与 `Student` 表按照 `dept_id` 进行连接,然后按照 `dept_id` 分组统计学生人数,最后按照 `student_number` 降序、`dept_name` 升序排序即可。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT dept_name, COUNT(student_id) AS student_number @@ -98,3 +94,5 @@ ORDER BY 2 DESC, 1; ``` + + diff --git a/solution/0500-0599/0580.Count Student Number in Departments/README_EN.md b/solution/0500-0599/0580.Count Student Number in Departments/README_EN.md index a904499eb8a96..c697f392d4f1d 100644 --- a/solution/0500-0599/0580.Count Student Number in Departments/README_EN.md +++ b/solution/0500-0599/0580.Count Student Number in Departments/README_EN.md @@ -76,14 +76,12 @@ Department table: ## Solutions -**Solution 1: Left Join + Grouping** +### Solution 1: Left Join + Grouping We can use a left join to join the `Department` table and the `Student` table on `dept_id`, and then group by `dept_id` to count the number of students in each department. Finally, we can sort the result by `student_number` in descending order and `dept_name` in ascending order. -### **SQL** - ```sql # Write your MySQL query statement below SELECT dept_name, COUNT(student_id) AS student_number @@ -95,3 +93,5 @@ ORDER BY 2 DESC, 1; ``` + + diff --git a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README.md b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README.md index ecb349611540e..32e41eb2d060c 100644 --- a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README.md +++ b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README.md @@ -53,26 +53,14 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们可以先对数组进行排序,然后比较排序后的数组和原数组,找到最左边和最右边不相等的位置,它们之间的长度就是我们要找的最短无序连续子数组的长度。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组的长度。 -**方法二:维护左侧最大值和右侧最小值** - -我们可以从左到右遍历数组,维护一个最大值 $mx$,如果当前值小于 $mx$,说明当前值不在正确的位置上,我们更新右边界 $r$ 为当前位置。同理,我们可以从右到左遍历数组,维护一个最小值 $mi$,如果当前值大于 $mi$,说明当前值不在正确的位置上,我们更新左边界 $l$ 为当前位置。在初始化时,我们将 $l$ 和 $r$ 都初始化为 $-1$,如果 $l$ 和 $r$ 都没有被更新,说明数组已经有序,返回 $0$,否则返回 $r - l + 1$。 - -时间复杂度 $O(n)$,其中 $n$ 是数组的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def findUnsortedSubarray(self, nums: List[int]) -> int: @@ -85,6 +73,115 @@ class Solution: return r - l + 1 ``` +```java +class Solution { + public int findUnsortedSubarray(int[] nums) { + int[] arr = nums.clone(); + Arrays.sort(arr); + int l = 0, r = arr.length - 1; + while (l <= r && nums[l] == arr[l]) { + l++; + } + while (l <= r && nums[r] == arr[r]) { + r--; + } + return r - l + 1; + } +} +``` + +```cpp +class Solution { +public: + int findUnsortedSubarray(vector& nums) { + vector arr = nums; + sort(arr.begin(), arr.end()); + int l = 0, r = arr.size() - 1; + while (l <= r && arr[l] == nums[l]) { + l++; + } + while (l <= r && arr[r] == nums[r]) { + r--; + } + return r - l + 1; + } +}; +``` + +```go +func findUnsortedSubarray(nums []int) int { + arr := make([]int, len(nums)) + copy(arr, nums) + sort.Ints(arr) + l, r := 0, len(arr)-1 + for l <= r && nums[l] == arr[l] { + l++ + } + for l <= r && nums[r] == arr[r] { + r-- + } + return r - l + 1 +} +``` + +```ts +function findUnsortedSubarray(nums: number[]): number { + const arr = [...nums]; + arr.sort((a, b) => a - b); + let [l, r] = [0, arr.length - 1]; + while (l <= r && arr[l] === nums[l]) { + ++l; + } + while (l <= r && arr[r] === nums[r]) { + --r; + } + return r - l + 1; +} +``` + +```rust +impl Solution { + pub fn find_unsorted_subarray(nums: Vec) -> i32 { + let inf = 1 << 30; + let n = nums.len(); + let mut l = -1; + let mut r = -1; + let mut mi = inf; + let mut mx = -inf; + + for i in 0..n { + if mx > nums[i] { + r = i as i32; + } else { + mx = nums[i]; + } + + if mi < nums[n - i - 1] { + l = (n - i - 1) as i32; + } else { + mi = nums[n - i - 1]; + } + } + + if r == -1 { + 0 + } else { + r - l + 1 + } + } +} +``` + + + +### 方法二:维护左侧最大值和右侧最小值 + +我们可以从左到右遍历数组,维护一个最大值 $mx$,如果当前值小于 $mx$,说明当前值不在正确的位置上,我们更新右边界 $r$ 为当前位置。同理,我们可以从右到左遍历数组,维护一个最小值 $mi$,如果当前值大于 $mi$,说明当前值不在正确的位置上,我们更新左边界 $l$ 为当前位置。在初始化时,我们将 $l$ 和 $r$ 都初始化为 $-1$,如果 $l$ 和 $r$ 都没有被更新,说明数组已经有序,返回 $0$,否则返回 $r - l + 1$。 + +时间复杂度 $O(n)$,其中 $n$ 是数组的长度。空间复杂度 $O(1)$。 + + + ```python class Solution: def findUnsortedSubarray(self, nums: List[int]) -> int: @@ -103,27 +200,6 @@ class Solution: return 0 if r == -1 else r - l + 1 ``` -### **Java** - - - -```java -class Solution { - public int findUnsortedSubarray(int[] nums) { - int[] arr = nums.clone(); - Arrays.sort(arr); - int l = 0, r = arr.length - 1; - while (l <= r && nums[l] == arr[l]) { - l++; - } - while (l <= r && nums[r] == arr[r]) { - r--; - } - return r - l + 1; - } -} -``` - ```java class Solution { public int findUnsortedSubarray(int[] nums) { @@ -148,26 +224,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int findUnsortedSubarray(vector& nums) { - vector arr = nums; - sort(arr.begin(), arr.end()); - int l = 0, r = arr.size() - 1; - while (l <= r && arr[l] == nums[l]) { - l++; - } - while (l <= r && arr[r] == nums[r]) { - r--; - } - return r - l + 1; - } -}; -``` - ```cpp class Solution { public: @@ -193,24 +249,6 @@ public: }; ``` -### **Go** - -```go -func findUnsortedSubarray(nums []int) int { - arr := make([]int, len(nums)) - copy(arr, nums) - sort.Ints(arr) - l, r := 0, len(arr)-1 - for l <= r && nums[l] == arr[l] { - l++ - } - for l <= r && nums[r] == arr[r] { - r-- - } - return r - l + 1 -} -``` - ```go func findUnsortedSubarray(nums []int) int { const inf = 1 << 30 @@ -236,23 +274,6 @@ func findUnsortedSubarray(nums []int) int { } ``` -### **TypeScript** - -```ts -function findUnsortedSubarray(nums: number[]): number { - const arr = [...nums]; - arr.sort((a, b) => a - b); - let [l, r] = [0, arr.length - 1]; - while (l <= r && arr[l] === nums[l]) { - ++l; - } - while (l <= r && arr[r] === nums[r]) { - --r; - } - return r - l + 1; -} -``` - ```ts function findUnsortedSubarray(nums: number[]): number { let [l, r] = [-1, -1]; @@ -274,43 +295,6 @@ function findUnsortedSubarray(nums: number[]): number { } ``` -```rust -impl Solution { - pub fn find_unsorted_subarray(nums: Vec) -> i32 { - let inf = 1 << 30; - let n = nums.len(); - let mut l = -1; - let mut r = -1; - let mut mi = inf; - let mut mx = -inf; - - for i in 0..n { - if mx > nums[i] { - r = i as i32; - } else { - mx = nums[i]; - } - - if mi < nums[n - i - 1] { - l = (n - i - 1) as i32; - } else { - mi = nums[n - i - 1]; - } - } - - if r == -1 { - 0 - } else { - r - l + 1 - } - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README_EN.md b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README_EN.md index 818415d5c1940..a2519f8633037 100644 --- a/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README_EN.md +++ b/solution/0500-0599/0581.Shortest Unsorted Continuous Subarray/README_EN.md @@ -44,22 +44,14 @@ ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting We can first sort the array, and then compare the sorted array with the original array to find the leftmost and rightmost positions where they differ. The length between them is the length of the shortest unsorted continuous subarray. The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array. -**Solution 2: Maintaining the Maximum Value on the Left and the Minimum Value on the Right** - -We can traverse the array from left to right and maintain a maximum value $mx$. If the current value is less than $mx$, it means that the current value is not in the correct position, and we update the right boundary $r$ to the current position. Similarly, we can traverse the array from right to left and maintain a minimum value $mi$. If the current value is greater than $mi$, it means that the current value is not in the correct position, and we update the left boundary $l$ to the current position. At initialization, we set $l$ and $r$ to $-1$. If $l$ and $r$ are not updated, it means that the array is already sorted, and we return $0$. Otherwise, we return $r - l + 1$. - -The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array. - -### **Python3** - ```python class Solution: def findUnsortedSubarray(self, nums: List[int]) -> int: @@ -72,6 +64,115 @@ class Solution: return r - l + 1 ``` +```java +class Solution { + public int findUnsortedSubarray(int[] nums) { + int[] arr = nums.clone(); + Arrays.sort(arr); + int l = 0, r = arr.length - 1; + while (l <= r && nums[l] == arr[l]) { + l++; + } + while (l <= r && nums[r] == arr[r]) { + r--; + } + return r - l + 1; + } +} +``` + +```cpp +class Solution { +public: + int findUnsortedSubarray(vector& nums) { + vector arr = nums; + sort(arr.begin(), arr.end()); + int l = 0, r = arr.size() - 1; + while (l <= r && arr[l] == nums[l]) { + l++; + } + while (l <= r && arr[r] == nums[r]) { + r--; + } + return r - l + 1; + } +}; +``` + +```go +func findUnsortedSubarray(nums []int) int { + arr := make([]int, len(nums)) + copy(arr, nums) + sort.Ints(arr) + l, r := 0, len(arr)-1 + for l <= r && nums[l] == arr[l] { + l++ + } + for l <= r && nums[r] == arr[r] { + r-- + } + return r - l + 1 +} +``` + +```ts +function findUnsortedSubarray(nums: number[]): number { + const arr = [...nums]; + arr.sort((a, b) => a - b); + let [l, r] = [0, arr.length - 1]; + while (l <= r && arr[l] === nums[l]) { + ++l; + } + while (l <= r && arr[r] === nums[r]) { + --r; + } + return r - l + 1; +} +``` + +```rust +impl Solution { + pub fn find_unsorted_subarray(nums: Vec) -> i32 { + let inf = 1 << 30; + let n = nums.len(); + let mut l = -1; + let mut r = -1; + let mut mi = inf; + let mut mx = -inf; + + for i in 0..n { + if mx > nums[i] { + r = i as i32; + } else { + mx = nums[i]; + } + + if mi < nums[n - i - 1] { + l = (n - i - 1) as i32; + } else { + mi = nums[n - i - 1]; + } + } + + if r == -1 { + 0 + } else { + r - l + 1 + } + } +} +``` + + + +### Solution 2: Maintaining the Maximum Value on the Left and the Minimum Value on the Right + +We can traverse the array from left to right and maintain a maximum value $mx$. If the current value is less than $mx$, it means that the current value is not in the correct position, and we update the right boundary $r$ to the current position. Similarly, we can traverse the array from right to left and maintain a minimum value $mi$. If the current value is greater than $mi$, it means that the current value is not in the correct position, and we update the left boundary $l$ to the current position. At initialization, we set $l$ and $r$ to $-1$. If $l$ and $r$ are not updated, it means that the array is already sorted, and we return $0$. Otherwise, we return $r - l + 1$. + +The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array. + + + ```python class Solution: def findUnsortedSubarray(self, nums: List[int]) -> int: @@ -90,25 +191,6 @@ class Solution: return 0 if r == -1 else r - l + 1 ``` -### **Java** - -```java -class Solution { - public int findUnsortedSubarray(int[] nums) { - int[] arr = nums.clone(); - Arrays.sort(arr); - int l = 0, r = arr.length - 1; - while (l <= r && nums[l] == arr[l]) { - l++; - } - while (l <= r && nums[r] == arr[r]) { - r--; - } - return r - l + 1; - } -} -``` - ```java class Solution { public int findUnsortedSubarray(int[] nums) { @@ -133,26 +215,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int findUnsortedSubarray(vector& nums) { - vector arr = nums; - sort(arr.begin(), arr.end()); - int l = 0, r = arr.size() - 1; - while (l <= r && arr[l] == nums[l]) { - l++; - } - while (l <= r && arr[r] == nums[r]) { - r--; - } - return r - l + 1; - } -}; -``` - ```cpp class Solution { public: @@ -178,24 +240,6 @@ public: }; ``` -### **Go** - -```go -func findUnsortedSubarray(nums []int) int { - arr := make([]int, len(nums)) - copy(arr, nums) - sort.Ints(arr) - l, r := 0, len(arr)-1 - for l <= r && nums[l] == arr[l] { - l++ - } - for l <= r && nums[r] == arr[r] { - r-- - } - return r - l + 1 -} -``` - ```go func findUnsortedSubarray(nums []int) int { const inf = 1 << 30 @@ -221,23 +265,6 @@ func findUnsortedSubarray(nums []int) int { } ``` -### **TypeScript** - -```ts -function findUnsortedSubarray(nums: number[]): number { - const arr = [...nums]; - arr.sort((a, b) => a - b); - let [l, r] = [0, arr.length - 1]; - while (l <= r && arr[l] === nums[l]) { - ++l; - } - while (l <= r && arr[r] === nums[r]) { - --r; - } - return r - l + 1; -} -``` - ```ts function findUnsortedSubarray(nums: number[]): number { let [l, r] = [-1, -1]; @@ -259,67 +286,6 @@ function findUnsortedSubarray(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn find_unsorted_subarray(nums: Vec) -> i32 { - let mut arr = nums.clone(); - arr.sort(); - - let mut l = 0; - let mut r = (arr.len() as i32) - 1; - - while l <= r && nums[l as usize] == arr[l as usize] { - l += 1; - } - - while l <= r && nums[r as usize] == arr[r as usize] { - r -= 1; - } - - r - l + 1 - } -} -``` - -```rust -impl Solution { - pub fn find_unsorted_subarray(nums: Vec) -> i32 { - let inf = 1 << 30; - let n = nums.len(); - let mut l = -1; - let mut r = -1; - let mut mi = inf; - let mut mx = -inf; - - for i in 0..n { - if mx > nums[i] { - r = i as i32; - } else { - mx = nums[i]; - } - - if mi < nums[n - i - 1] { - l = (n - i - 1) as i32; - } else { - mi = nums[n - i - 1]; - } - } - - if r == -1 { - 0 - } else { - r - l + 1 - } - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0582.Kill Process/README.md b/solution/0500-0599/0582.Kill Process/README.md index e7ae1b121a0ef..c324f5bfb3266 100644 --- a/solution/0500-0599/0582.Kill Process/README.md +++ b/solution/0500-0599/0582.Kill Process/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们先根据 $pid$ 和 $ppid$ 构建出图 $g$,其中 $g[i]$ 表示进程 $i$ 的所有子进程。然后从进程 $kill$ 开始,进行深度优先搜索,即可得到所有被杀掉的进程。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: @@ -77,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private Map> g = new HashMap<>(); @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func killProcess(pid []int, ppid []int, kill int) (ans []int) { g := map[int][]int{} @@ -148,8 +134,6 @@ func killProcess(pid []int, ppid []int, kill int) (ans []int) { } ``` -### **TypeScript** - ```ts function killProcess(pid: number[], ppid: number[], kill: number): number[] { const g: Map = new Map(); @@ -171,8 +155,6 @@ function killProcess(pid: number[], ppid: number[], kill: number): number[] { } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -201,10 +183,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0582.Kill Process/README_EN.md b/solution/0500-0599/0582.Kill Process/README_EN.md index 436ea9f72e25c..0cfa4e5ad1333 100644 --- a/solution/0500-0599/0582.Kill Process/README_EN.md +++ b/solution/0500-0599/0582.Kill Process/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We first construct a graph $g$ based on $pid$ and $ppid$, where $g[i]$ represents all child processes of process $i$. Then, starting from the process $kill$, we perform depth-first search to obtain all killed processes. @@ -52,8 +52,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: @@ -70,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private Map> g = new HashMap<>(); @@ -95,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +113,6 @@ public: }; ``` -### **Go** - ```go func killProcess(pid []int, ppid []int, kill int) (ans []int) { g := map[int][]int{} @@ -139,8 +131,6 @@ func killProcess(pid []int, ppid []int, kill int) (ans []int) { } ``` -### **TypeScript** - ```ts function killProcess(pid: number[], ppid: number[], kill: number): number[] { const g: Map = new Map(); @@ -162,8 +152,6 @@ function killProcess(pid: number[], ppid: number[], kill: number): number[] { } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -192,10 +180,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0583.Delete Operation for Two Strings/README.md b/solution/0500-0599/0583.Delete Operation for Two Strings/README.md index e3f6562a0e0a4..d8c13a3f66bad 100644 --- a/solution/0500-0599/0583.Delete Operation for Two Strings/README.md +++ b/solution/0500-0599/0583.Delete Operation for Two Strings/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 类似[1143. 最长公共子序列](/solution/1100-1199/1143.Longest%20Common%20Subsequence/README.md)。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def minDistance(self, word1: str, word2: str) -> int: @@ -73,10 +67,6 @@ class Solution: return dp[-1][-1] ``` -### **Java** - - - ```java class Solution { public int minDistance(String word1, String word2) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func minDistance(word1 string, word2 string) int { m, n := len(word1), len(word2) @@ -151,8 +137,6 @@ func minDistance(word1 string, word2 string) int { } ``` -### **TypeScript** - ```ts function minDistance(word1: string, word2: string): number { const m = word1.length; @@ -172,8 +156,6 @@ function minDistance(word1: string, word2: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_distance(word1: String, word2: String) -> i32 { @@ -195,10 +177,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0583.Delete Operation for Two Strings/README_EN.md b/solution/0500-0599/0583.Delete Operation for Two Strings/README_EN.md index 4516be1eb325c..88e2a23651ec3 100644 --- a/solution/0500-0599/0583.Delete Operation for Two Strings/README_EN.md +++ b/solution/0500-0599/0583.Delete Operation for Two Strings/README_EN.md @@ -34,12 +34,10 @@ ## Solutions -Dynamic programming. +### Solution 1 -### **Python3** - ```python class Solution: def minDistance(self, word1: str, word2: str) -> int: @@ -58,8 +56,6 @@ class Solution: return dp[-1][-1] ``` -### **Java** - ```java class Solution { public int minDistance(String word1, String word2) { @@ -85,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +102,6 @@ public: }; ``` -### **Go** - ```go func minDistance(word1 string, word2 string) int { m, n := len(word1), len(word2) @@ -134,8 +126,6 @@ func minDistance(word1 string, word2 string) int { } ``` -### **TypeScript** - ```ts function minDistance(word1: string, word2: string): number { const m = word1.length; @@ -155,8 +145,6 @@ function minDistance(word1: string, word2: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_distance(word1: String, word2: String) -> i32 { @@ -178,10 +166,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0584.Find Customer Referee/README.md b/solution/0500-0599/0584.Find Customer Referee/README.md index b2c39fcf8113e..b2ed4bbbf3426 100644 --- a/solution/0500-0599/0584.Find Customer Referee/README.md +++ b/solution/0500-0599/0584.Find Customer Referee/README.md @@ -54,16 +54,12 @@ Customer 表: ## 解法 - - -**方法一:条件过滤** +### 方法一:条件过滤 我们可以直接筛选出 `referee_id` 不为 `2` 的客户姓名。注意,`referee_id` 为 `NULL` 的客户也应该被筛选出来。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT name @@ -72,3 +68,5 @@ WHERE IFNULL(referee_id, 0) != 2; ``` + + diff --git a/solution/0500-0599/0584.Find Customer Referee/README_EN.md b/solution/0500-0599/0584.Find Customer Referee/README_EN.md index a14a4697df340..960b132655eab 100644 --- a/solution/0500-0599/0584.Find Customer Referee/README_EN.md +++ b/solution/0500-0599/0584.Find Customer Referee/README_EN.md @@ -55,14 +55,12 @@ Customer table: ## Solutions -**Solution 1: Conditional Filtering** +### Solution 1: Conditional Filtering We can directly filter out the customer names whose `referee_id` is not `2`. Note that the customers whose `referee_id` is `NULL` should also be filtered out. -### **SQL** - ```sql # Write your MySQL query statement below SELECT name @@ -71,3 +69,5 @@ WHERE IFNULL(referee_id, 0) != 2; ``` + + diff --git a/solution/0500-0599/0585.Investments in 2016/README.md b/solution/0500-0599/0585.Investments in 2016/README.md index fb0f5002173a1..0ce97b650ddd3 100644 --- a/solution/0500-0599/0585.Investments in 2016/README.md +++ b/solution/0500-0599/0585.Investments in 2016/README.md @@ -72,12 +72,10 @@ tiv_2015 值为 10 与第三条和第四条记录相同,且其位置是唯一 ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -94,3 +92,5 @@ WHERE cnt1 > 1 AND cnt2 = 1; ``` + + diff --git a/solution/0500-0599/0585.Investments in 2016/README_EN.md b/solution/0500-0599/0585.Investments in 2016/README_EN.md index 8df8213cc0241..2aeb2edaba966 100644 --- a/solution/0500-0599/0585.Investments in 2016/README_EN.md +++ b/solution/0500-0599/0585.Investments in 2016/README_EN.md @@ -67,9 +67,9 @@ So, the result is the sum of tiv_2016 of the first and last record, which is 45. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -87,3 +87,5 @@ WHERE cnt1 > 1 AND cnt2 = 1; ``` + + diff --git a/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/README.md b/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/README.md index eafc852aec46f..ac999bee2f947 100644 --- a/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/README.md +++ b/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/README.md @@ -59,16 +59,12 @@ customer_number 为 '3' 的顾客有两个订单,比顾客 '1' 或者 '2' 都 ## 解法 - - -**方法一:分组 + 排序** +### 方法一:分组 + 排序 我们可以使用 `GROUP BY` 将数据按照 `customer_number` 进行分组,然后按照 `count(1)` 进行降序排序,最后取第一条记录的 `customer_number` 即可。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -79,6 +75,12 @@ ORDER BY COUNT(1) DESC LIMIT 1; ``` + + +### 方法二 + + + ```sql /* Write your T-SQL query statement below */ SELECT TOP 1 @@ -90,3 +92,5 @@ ORDER BY COUNT(customer_number) DESC; ``` + + diff --git a/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/README_EN.md b/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/README_EN.md index fcbfd4a22f47b..e591756bc243d 100644 --- a/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/README_EN.md +++ b/solution/0500-0599/0586.Customer Placing the Largest Number of Orders/README_EN.md @@ -55,23 +55,28 @@ So the result is customer_number 3. ## Solutions -**Solution 1: Group By + Sorting** +### Solution 1: Group By + Sorting We can use `GROUP BY` to group the data by `customer_number`, and then sort the groups in descending order by `count(1)`. Finally, we can take the `customer_number` of the first record as the result. -### **SQL** - ```sql # Write your MySQL query statement below -SELECT customer_number -FROM Orders -GROUP BY 1 +SELECT + customer_number +FROM orders +GROUP BY customer_number ORDER BY COUNT(1) DESC LIMIT 1; ``` + + +### Solution 2 + + + ```sql /* Write your T-SQL query statement below */ SELECT TOP 1 @@ -83,3 +88,5 @@ ORDER BY COUNT(customer_number) DESC; ``` + + diff --git a/solution/0500-0599/0587.Erect the Fence/README.md b/solution/0500-0599/0587.Erect the Fence/README.md index 5e322853d2c5c..b67a7d1e6c145 100644 --- a/solution/0500-0599/0587.Erect the Fence/README.md +++ b/solution/0500-0599/0587.Erect the Fence/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:Andrew 算法** +### 方法一:Andrew 算法 原理: @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def outerTrees(self, trees: List[List[int]]) -> List[List[int]]: @@ -98,10 +92,6 @@ class Solution: return [trees[i] for i in stk] ``` -### **Java** - - - ```java class Solution { public int[][] outerTrees(int[][] trees) { @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -177,8 +165,6 @@ public: }; ``` -### **Go** - ```go func outerTrees(trees [][]int) [][]int { n := len(trees) @@ -223,10 +209,6 @@ func outerTrees(trees [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0587.Erect the Fence/README_EN.md b/solution/0500-0599/0587.Erect the Fence/README_EN.md index 53371d3cfcf2b..9795d13ce3ca9 100644 --- a/solution/0500-0599/0587.Erect the Fence/README_EN.md +++ b/solution/0500-0599/0587.Erect the Fence/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return [trees[i] for i in stk] ``` -### **Java** - ```java class Solution { public int[][] outerTrees(int[][] trees) { @@ -115,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +145,6 @@ public: }; ``` -### **Go** - ```go func outerTrees(trees [][]int) [][]int { n := len(trees) @@ -195,10 +189,6 @@ func outerTrees(trees [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0588.Design In-Memory File System/README.md b/solution/0500-0599/0588.Design In-Memory File System/README.md index ca07bea132c96..13d772c139bd4 100644 --- a/solution/0500-0599/0588.Design In-Memory File System/README.md +++ b/solution/0500-0599/0588.Design In-Memory File System/README.md @@ -69,18 +69,12 @@ fileSystem.readContentFromFile("/a/b/c/d"); // 返回 "hello" ## 解法 - - -**方法一:前缀树** +### 方法一:前缀树 哈希表实现前缀树。 -### **Python3** - - - ```python class Trie: def __init__(self): @@ -145,10 +139,6 @@ class FileSystem: # param_4 = obj.readContentFromFile(filePath) ``` -### **Java** - - - ```java class Trie { String name; @@ -235,8 +225,6 @@ class FileSystem { */ ``` -### **Go** - ```go type Trie struct { name string @@ -331,10 +319,6 @@ func (this *FileSystem) ReadContentFromFile(filePath string) string { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0588.Design In-Memory File System/README_EN.md b/solution/0500-0599/0588.Design In-Memory File System/README_EN.md index aa2716545f7b0..e1e1ea0dcc8cf 100644 --- a/solution/0500-0599/0588.Design In-Memory File System/README_EN.md +++ b/solution/0500-0599/0588.Design In-Memory File System/README_EN.md @@ -60,9 +60,9 @@ fileSystem.readContentFromFile("/a/b/c/d"); // return "hello" ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -128,8 +128,6 @@ class FileSystem: # param_4 = obj.readContentFromFile(filePath) ``` -### **Java** - ```java class Trie { String name; @@ -216,8 +214,6 @@ class FileSystem { */ ``` -### **Go** - ```go type Trie struct { name string @@ -312,10 +308,6 @@ func (this *FileSystem) ReadContentFromFile(filePath string) string { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0589.N-ary Tree Preorder Traversal/README.md b/solution/0500-0599/0589.N-ary Tree Preorder Traversal/README.md index 9a4b1ff82a390..c9b401f849b9d 100644 --- a/solution/0500-0599/0589.N-ary Tree Preorder Traversal/README.md +++ b/solution/0500-0599/0589.N-ary Tree Preorder Traversal/README.md @@ -45,14 +45,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python """ # Definition for a Node. @@ -77,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /* // Definition for a Node. @@ -122,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -164,8 +154,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -194,8 +182,6 @@ func preorder(root *Node) []int { } ``` -### **TypeScript** - ```ts /** * Definition for node. @@ -227,37 +213,6 @@ function preorder(root: Node | null): number[] { } ``` -```ts -/** - * Definition for node. - * class Node { - * val: number - * children: Node[] - * constructor(val?: number) { - * this.val = (val===undefined ? 0 : val) - * this.children = [] - * } - * } - */ - -function preorder(root: Node | null): number[] { - const ans = []; - const dfs = (root: Node | null) => { - if (root == null) { - return; - } - ans.push(root.val); - for (const node of root.children) { - dfs(node); - } - }; - dfs(root); - return ans; -} -``` - -### **C** - ```c /** * Definition for a Node. @@ -290,10 +245,41 @@ int* preorder(struct Node* root, int* returnSize) { } ``` -### **...** + -``` +### 方法二 + + + +```ts +/** + * Definition for node. + * class Node { + * val: number + * children: Node[] + * constructor(val?: number) { + * this.val = (val===undefined ? 0 : val) + * this.children = [] + * } + * } + */ +function preorder(root: Node | null): number[] { + const ans = []; + const dfs = (root: Node | null) => { + if (root == null) { + return; + } + ans.push(root.val); + for (const node of root.children) { + dfs(node); + } + }; + dfs(root); + return ans; +} ``` + + diff --git a/solution/0500-0599/0589.N-ary Tree Preorder Traversal/README_EN.md b/solution/0500-0599/0589.N-ary Tree Preorder Traversal/README_EN.md index 6f39854910bcc..1b44248e57e1d 100644 --- a/solution/0500-0599/0589.N-ary Tree Preorder Traversal/README_EN.md +++ b/solution/0500-0599/0589.N-ary Tree Preorder Traversal/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -69,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java /* // Definition for a Node. @@ -112,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -154,8 +150,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -184,8 +178,6 @@ func preorder(root *Node) []int { } ``` -### **TypeScript** - ```ts /** * Definition for node. @@ -217,37 +209,6 @@ function preorder(root: Node | null): number[] { } ``` -```ts -/** - * Definition for node. - * class Node { - * val: number - * children: Node[] - * constructor(val?: number) { - * this.val = (val===undefined ? 0 : val) - * this.children = [] - * } - * } - */ - -function preorder(root: Node | null): number[] { - const ans = []; - const dfs = (root: Node | null) => { - if (root == null) { - return; - } - ans.push(root.val); - for (const node of root.children) { - dfs(node); - } - }; - dfs(root); - return ans; -} -``` - -### **C** - ```c /** * Definition for a Node. @@ -280,10 +241,41 @@ int* preorder(struct Node* root, int* returnSize) { } ``` -### **...** + -``` +### Solution 2 + + + +```ts +/** + * Definition for node. + * class Node { + * val: number + * children: Node[] + * constructor(val?: number) { + * this.val = (val===undefined ? 0 : val) + * this.children = [] + * } + * } + */ +function preorder(root: Node | null): number[] { + const ans = []; + const dfs = (root: Node | null) => { + if (root == null) { + return; + } + ans.push(root.val); + for (const node of root.children) { + dfs(node); + } + }; + dfs(root); + return ans; +} ``` + + diff --git a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/README.md b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/README.md index 156fbcc69daf0..5e4caac0f61f9 100644 --- a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/README.md +++ b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/README.md @@ -46,16 +46,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - -递归: - ```python """ # Definition for a Node. @@ -80,38 +74,6 @@ class Solution: return ans ``` -迭代: - -```python -""" -# Definition for a Node. -class Node: - def __init__(self, val=None, children=None): - self.val = val - self.children = children -""" - - -class Solution: - def postorder(self, root: 'Node') -> List[int]: - ans = [] - if root is None: - return ans - stk = [root] - while stk: - node = stk.pop() - ans.append(node.val) - for child in node.children: - stk.append(child) - return ans[::-1] -``` - -### **Java** - - - -递归: - ```java /* // Definition for a Node. @@ -154,22 +116,21 @@ class Solution { } ``` -迭代: - -```java +```cpp /* // Definition for a Node. class Node { - public int val; - public List children; +public: + int val; + vector children; - public Node() {} + Node() {} - public Node(int _val) { + Node(int _val) { val = _val; } - public Node(int _val, List _children) { + Node(int _val, vector _children) { val = _val; children = _children; } @@ -177,44 +138,120 @@ class Node { */ class Solution { - public List postorder(Node root) { - LinkedList ans = new LinkedList<>(); +public: + vector postorder(Node* root) { + vector ans; + dfs(root, ans); + return ans; + } + + void dfs(Node* root, vector& ans) { + if (!root) return; + for (auto& child : root->children) dfs(child, ans); + ans.push_back(root->val); + } +}; +``` + +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Children []*Node + * } + */ + +func postorder(root *Node) []int { + var ans []int + var dfs func(root *Node) + dfs = func(root *Node) { + if root == nil { + return + } + for _, child := range root.Children { + dfs(child) + } + ans = append(ans, root.Val) + } + dfs(root) + return ans +} +``` + +```ts +/** + * Definition for node. + * class Node { + * val: number + * children: Node[] + * constructor(val?: number) { + * this.val = (val===undefined ? 0 : val) + * this.children = [] + * } + * } + */ + +function postorder(root: Node | null): number[] { + const res = []; + const dfs = (root: Node | null) => { if (root == null) { - return ans; + return; } - Deque stk = new ArrayDeque<>(); - stk.offer(root); - while (!stk.isEmpty()) { - root = stk.pollLast(); - ans.addFirst(root.val); - for (Node child : root.children) { - stk.offer(child); - } + for (const node of root.children) { + dfs(node); } - return ans; - } + res.push(root.val); + }; + dfs(root); + return res; } ``` -### **C++** + -递归: +### 方法二 -```cpp + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + + +class Solution: + def postorder(self, root: 'Node') -> List[int]: + ans = [] + if root is None: + return ans + stk = [root] + while stk: + node = stk.pop() + ans.append(node.val) + for child in node.children: + stk.append(child) + return ans[::-1] +``` + +```java /* // Definition for a Node. class Node { -public: - int val; - vector children; + public int val; + public List children; - Node() {} + public Node() {} - Node(int _val) { + public Node(int _val) { val = _val; } - Node(int _val, vector _children) { + public Node(int _val, List _children) { val = _val; children = _children; } @@ -222,23 +259,25 @@ public: */ class Solution { -public: - vector postorder(Node* root) { - vector ans; - dfs(root, ans); + public List postorder(Node root) { + LinkedList ans = new LinkedList<>(); + if (root == null) { + return ans; + } + Deque stk = new ArrayDeque<>(); + stk.offer(root); + while (!stk.isEmpty()) { + root = stk.pollLast(); + ans.addFirst(root.val); + for (Node child : root.children) { + stk.offer(child); + } + } return ans; } - - void dfs(Node* root, vector& ans) { - if (!root) return; - for (auto& child : root->children) dfs(child, ans); - ans.push_back(root->val); - } -}; +} ``` -迭代: - ```cpp /* // Definition for a Node. @@ -278,38 +317,6 @@ public: }; ``` -### **Go** - -递归: - -```go -/** - * Definition for a Node. - * type Node struct { - * Val int - * Children []*Node - * } - */ - -func postorder(root *Node) []int { - var ans []int - var dfs func(root *Node) - dfs = func(root *Node) { - if root == nil { - return - } - for _, child := range root.Children { - dfs(child) - } - ans = append(ans, root.Val) - } - dfs(root) - return ans -} -``` - -迭代: - ```go /** * Definition for a Node. @@ -337,41 +344,6 @@ func postorder(root *Node) []int { } ``` -### **TypeScript** - -递归: - -```ts -/** - * Definition for node. - * class Node { - * val: number - * children: Node[] - * constructor(val?: number) { - * this.val = (val===undefined ? 0 : val) - * this.children = [] - * } - * } - */ - -function postorder(root: Node | null): number[] { - const res = []; - const dfs = (root: Node | null) => { - if (root == null) { - return; - } - for (const node of root.children) { - dfs(node); - } - res.push(root.val); - }; - dfs(root); - return res; -} -``` - -迭代: - ```ts /** * Definition for node. @@ -406,10 +378,6 @@ function postorder(root: Node | null): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/README_EN.md b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/README_EN.md index c6a37ffa50b8e..3aef8edf632ba 100644 --- a/solution/0500-0599/0590.N-ary Tree Postorder Traversal/README_EN.md +++ b/solution/0500-0599/0590.N-ary Tree Postorder Traversal/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -65,32 +65,6 @@ class Solution: return ans ``` -```python -""" -# Definition for a Node. -class Node: - def __init__(self, val=None, children=None): - self.val = val - self.children = children -""" - - -class Solution: - def postorder(self, root: 'Node') -> List[int]: - ans = [] - if root is None: - return ans - stk = [root] - while stk: - node = stk.pop() - ans.append(node.val) - for child in node.children: - stk.append(child) - return ans[::-1] -``` - -### **Java** - ```java /* // Definition for a Node. @@ -133,20 +107,21 @@ class Solution { } ``` -```java +```cpp /* // Definition for a Node. class Node { - public int val; - public List children; +public: + int val; + vector children; - public Node() {} + Node() {} - public Node(int _val) { + Node(int _val) { val = _val; } - public Node(int _val, List _children) { + Node(int _val, vector _children) { val = _val; children = _children; } @@ -154,42 +129,120 @@ class Node { */ class Solution { - public List postorder(Node root) { - LinkedList ans = new LinkedList<>(); +public: + vector postorder(Node* root) { + vector ans; + dfs(root, ans); + return ans; + } + + void dfs(Node* root, vector& ans) { + if (!root) return; + for (auto& child : root->children) dfs(child, ans); + ans.push_back(root->val); + } +}; +``` + +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Children []*Node + * } + */ + +func postorder(root *Node) []int { + var ans []int + var dfs func(root *Node) + dfs = func(root *Node) { + if root == nil { + return + } + for _, child := range root.Children { + dfs(child) + } + ans = append(ans, root.Val) + } + dfs(root) + return ans +} +``` + +```ts +/** + * Definition for node. + * class Node { + * val: number + * children: Node[] + * constructor(val?: number) { + * this.val = (val===undefined ? 0 : val) + * this.children = [] + * } + * } + */ + +function postorder(root: Node | null): number[] { + const res = []; + const dfs = (root: Node | null) => { if (root == null) { - return ans; + return; } - Deque stk = new ArrayDeque<>(); - stk.offer(root); - while (!stk.isEmpty()) { - root = stk.pollLast(); - ans.addFirst(root.val); - for (Node child : root.children) { - stk.offer(child); - } + for (const node of root.children) { + dfs(node); } - return ans; - } + res.push(root.val); + }; + dfs(root); + return res; } ``` -### **C++** + -```cpp +### Solution 2 + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" + + +class Solution: + def postorder(self, root: 'Node') -> List[int]: + ans = [] + if root is None: + return ans + stk = [root] + while stk: + node = stk.pop() + ans.append(node.val) + for child in node.children: + stk.append(child) + return ans[::-1] +``` + +```java /* // Definition for a Node. class Node { -public: - int val; - vector children; + public int val; + public List children; - Node() {} + public Node() {} - Node(int _val) { + public Node(int _val) { val = _val; } - Node(int _val, vector _children) { + public Node(int _val, List _children) { val = _val; children = _children; } @@ -197,19 +250,23 @@ public: */ class Solution { -public: - vector postorder(Node* root) { - vector ans; - dfs(root, ans); + public List postorder(Node root) { + LinkedList ans = new LinkedList<>(); + if (root == null) { + return ans; + } + Deque stk = new ArrayDeque<>(); + stk.offer(root); + while (!stk.isEmpty()) { + root = stk.pollLast(); + ans.addFirst(root.val); + for (Node child : root.children) { + stk.offer(child); + } + } return ans; } - - void dfs(Node* root, vector& ans) { - if (!root) return; - for (auto& child : root->children) dfs(child, ans); - ans.push_back(root->val); - } -}; +} ``` ```cpp @@ -251,34 +308,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a Node. - * type Node struct { - * Val int - * Children []*Node - * } - */ - -func postorder(root *Node) []int { - var ans []int - var dfs func(root *Node) - dfs = func(root *Node) { - if root == nil { - return - } - for _, child := range root.Children { - dfs(child) - } - ans = append(ans, root.Val) - } - dfs(root) - return ans -} -``` - ```go /** * Definition for a Node. @@ -306,37 +335,6 @@ func postorder(root *Node) []int { } ``` -### **TypeScript** - -```ts -/** - * Definition for node. - * class Node { - * val: number - * children: Node[] - * constructor(val?: number) { - * this.val = (val===undefined ? 0 : val) - * this.children = [] - * } - * } - */ - -function postorder(root: Node | null): number[] { - const res = []; - const dfs = (root: Node | null) => { - if (root == null) { - return; - } - for (const node of root.children) { - dfs(node); - } - res.push(root.val); - }; - dfs(root); - return res; -} -``` - ```ts /** * Definition for node. @@ -371,10 +369,6 @@ function postorder(root: Node | null): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0591.Tag Validator/README.md b/solution/0500-0599/0591.Tag Validator/README.md index 73ec94e140173..be9ece7f15f86 100644 --- a/solution/0500-0599/0591.Tag Validator/README.md +++ b/solution/0500-0599/0591.Tag Validator/README.md @@ -93,16 +93,10 @@ cdata "<![CDATA[<div>]>]]>]] ## 解法 - - -**方法一:栈模拟** +### 方法一:栈模拟 -### **Python3** - - - ```python class Solution: def isValid(self, code: str) -> bool: @@ -140,10 +134,6 @@ class Solution: return not stk ``` -### **Java** - - - ```java class Solution { public boolean isValid(String code) { @@ -199,8 +189,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -242,8 +230,6 @@ public: }; ``` -### **Go** - ```go func isValid(code string) bool { var stk []string @@ -304,8 +290,6 @@ func check(tag string) bool { } ``` -### **Rust** - ```rust impl Solution { pub fn is_valid(code: String) -> bool { @@ -370,10 +354,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0591.Tag Validator/README_EN.md b/solution/0500-0599/0591.Tag Validator/README_EN.md index 3163a8b8644b0..f46e8c34283f8 100644 --- a/solution/0500-0599/0591.Tag Validator/README_EN.md +++ b/solution/0500-0599/0591.Tag Validator/README_EN.md @@ -67,9 +67,9 @@ The reason why cdata is NOT "<![CDATA[<div>]>]]>]]>&qu ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -108,8 +108,6 @@ class Solution: return not stk ``` -### **Java** - ```java class Solution { public boolean isValid(String code) { @@ -165,8 +163,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -208,8 +204,6 @@ public: }; ``` -### **Go** - ```go func isValid(code string) bool { var stk []string @@ -270,8 +264,6 @@ func check(tag string) bool { } ``` -### **Rust** - ```rust impl Solution { pub fn is_valid(code: String) -> bool { @@ -336,10 +328,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0592.Fraction Addition and Subtraction/README.md b/solution/0500-0599/0592.Fraction Addition and Subtraction/README.md index 169eb9fc3d705..6dd20c4df75d6 100644 --- a/solution/0500-0599/0592.Fraction Addition and Subtraction/README.md +++ b/solution/0500-0599/0592.Fraction Addition and Subtraction/README.md @@ -47,16 +47,10 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 -### **Python3** - - - ```python class Solution: def fractionAddition(self, expression: str) -> str: @@ -80,10 +74,6 @@ class Solution: return f'{x}/{y}' ``` -### **Java** - - - ```java class Solution { public String fractionAddition(String expression) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **Go** - ```go func fractionAddition(expression string) string { x, y := 0, 6*7*8*9*10 @@ -164,10 +152,6 @@ func gcd(a, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0592.Fraction Addition and Subtraction/README_EN.md b/solution/0500-0599/0592.Fraction Addition and Subtraction/README_EN.md index 49631c1c0a33c..c8e9c76483d00 100644 --- a/solution/0500-0599/0592.Fraction Addition and Subtraction/README_EN.md +++ b/solution/0500-0599/0592.Fraction Addition and Subtraction/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return f'{x}/{y}' ``` -### **Java** - ```java class Solution { public String fractionAddition(String expression) { @@ -105,8 +103,6 @@ class Solution { } ``` -### **Go** - ```go func fractionAddition(expression string) string { x, y := 0, 6*7*8*9*10 @@ -152,10 +148,6 @@ func gcd(a, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0593.Valid Square/README.md b/solution/0500-0599/0593.Valid Square/README.md index 9daa041f79c95..0877c71319d50 100644 --- a/solution/0500-0599/0593.Valid Square/README.md +++ b/solution/0500-0599/0593.Valid Square/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 若任选三个点,都能构成等腰直角三角形,说明是有效的正方形。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def validSquare( @@ -86,10 +80,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func validSquare(p1 []int, p2 []int, p3 []int, p4 []int) bool { check := func(a, b, c []int) bool { @@ -167,10 +153,6 @@ func validSquare(p1 []int, p2 []int, p3 []int, p4 []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0593.Valid Square/README_EN.md b/solution/0500-0599/0593.Valid Square/README_EN.md index 5607ad19fdd9f..f033b06bad68e 100644 --- a/solution/0500-0599/0593.Valid Square/README_EN.md +++ b/solution/0500-0599/0593.Valid Square/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) { @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +121,6 @@ public: }; ``` -### **Go** - ```go func validSquare(p1 []int, p2 []int, p3 []int, p4 []int) bool { check := func(a, b, c []int) bool { @@ -151,10 +145,6 @@ func validSquare(p1 []int, p2 []int, p3 []int, p4 []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0594.Longest Harmonious Subsequence/README.md b/solution/0500-0599/0594.Longest Harmonious Subsequence/README.md index d4a48c625d9d7..549c04894c52e 100644 --- a/solution/0500-0599/0594.Longest Harmonious Subsequence/README.md +++ b/solution/0500-0599/0594.Longest Harmonious Subsequence/README.md @@ -47,16 +47,10 @@ ## 解法 - - -先用哈希表统计每个元素出现的次数。然后遍历数组,判断比每个元素 `num` 大 1 的数字 `num + 1` 是否在哈希表中,若是,累计 `num` 和 `num + 1` 出现的次数,与最大值 ans 比较。若更大,则替换。最后返回 ans 即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def findLHS(self, nums: List[int]) -> int: @@ -68,20 +62,6 @@ class Solution: return ans ``` -```python -class Solution: - def findLHS(self, nums: List[int]) -> int: - counter = Counter(nums) - return max( - [counter[num] + counter[num + 1] for num in nums if num + 1 in counter], - default=0, - ) -``` - -### **Java** - - - ```java class Solution { public int findLHS(int[] nums) { @@ -100,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +99,6 @@ public: }; ``` -### **Go** - ```go func findLHS(nums []int) int { counter := make(map[int]int) @@ -139,10 +115,22 @@ func findLHS(nums []int) int { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def findLHS(self, nums: List[int]) -> int: + counter = Counter(nums) + return max( + [counter[num] + counter[num + 1] for num in nums if num + 1 in counter], + default=0, + ) ``` + + diff --git a/solution/0500-0599/0594.Longest Harmonious Subsequence/README_EN.md b/solution/0500-0599/0594.Longest Harmonious Subsequence/README_EN.md index 9f0d1c6af6631..fbcb41ed9f2f0 100644 --- a/solution/0500-0599/0594.Longest Harmonious Subsequence/README_EN.md +++ b/solution/0500-0599/0594.Longest Harmonious Subsequence/README_EN.md @@ -43,33 +43,21 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: def findLHS(self, nums: List[int]) -> int: - counter = Counter(nums) ans = 0 + counter = Counter(nums) for num in nums: if num + 1 in counter: ans = max(ans, counter[num] + counter[num + 1]) return ans ``` -```python -class Solution: - def findLHS(self, nums: List[int]) -> int: - counter = Counter(nums) - return max( - [counter[num] + counter[num + 1] for num in nums if num + 1 in counter], - default=0, - ) -``` - -### **Java** - ```java class Solution { public int findLHS(int[] nums) { @@ -88,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +95,6 @@ public: }; ``` -### **Go** - ```go func findLHS(nums []int) int { counter := make(map[int]int) @@ -127,10 +111,22 @@ func findLHS(nums []int) int { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def findLHS(self, nums: List[int]) -> int: + counter = Counter(nums) + return max( + [counter[num] + counter[num + 1] for num in nums if num + 1 in counter], + default=0, + ) ``` + + diff --git a/solution/0500-0599/0595.Big Countries/README.md b/solution/0500-0599/0595.Big Countries/README.md index 9fa18f884f317..8746a4d341e11 100644 --- a/solution/0500-0599/0595.Big Countries/README.md +++ b/solution/0500-0599/0595.Big Countries/README.md @@ -70,20 +70,12 @@ World 表: ## 解法 - - -**方法一:使用 WHERE + OR** +### 方法一:使用 WHERE + OR 我们可以使用 `WHERE` + `OR` 查询出所有符合条件的国家。 -**方法二:使用 UNION** - -我们可以查询出所有面积大于等于 300 万平方公里的国家,然后再查询出所有人口大于等于 2500 万的国家,最后使用 `UNION` 将两个结果集合并起来。 - -### **SQL** - ```sql # Write your MySQL query statement below SELECT name, population, area @@ -91,6 +83,14 @@ FROM World WHERE area >= 3000000 OR population >= 25000000; ``` + + +### 方法二:使用 UNION + +我们可以查询出所有面积大于等于 300 万平方公里的国家,然后再查询出所有人口大于等于 2500 万的国家,最后使用 `UNION` 将两个结果集合并起来。 + + + ```sql # Write your MySQL query statement below SELECT name, population, area @@ -103,3 +103,5 @@ WHERE population >= 25000000; ``` + + diff --git a/solution/0500-0599/0595.Big Countries/README_EN.md b/solution/0500-0599/0595.Big Countries/README_EN.md index 557b1ed8201f7..5591d33172619 100644 --- a/solution/0500-0599/0595.Big Countries/README_EN.md +++ b/solution/0500-0599/0595.Big Countries/README_EN.md @@ -61,9 +61,9 @@ World table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -72,6 +72,12 @@ FROM World WHERE area >= 3000000 OR population >= 25000000; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below SELECT name, population, area @@ -84,3 +90,5 @@ WHERE population >= 25000000; ``` + + diff --git a/solution/0500-0599/0596.Classes More Than 5 Students/README.md b/solution/0500-0599/0596.Classes More Than 5 Students/README.md index 17c80e526a80e..0f45f6891264c 100644 --- a/solution/0500-0599/0596.Classes More Than 5 Students/README.md +++ b/solution/0500-0599/0596.Classes More Than 5 Students/README.md @@ -61,16 +61,12 @@ Courses table: ## 解法 - - -**方法一:分组统计** +### 方法一:分组统计 我们可以使用 `GROUP BY` 语句,按照班级分组,然后使用 `HAVING` 语句,筛选出学生数量大于等于 $5$ 的班级。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT class @@ -80,3 +76,5 @@ HAVING COUNT(1) >= 5; ``` + + diff --git a/solution/0500-0599/0596.Classes More Than 5 Students/README_EN.md b/solution/0500-0599/0596.Classes More Than 5 Students/README_EN.md index 58db2069391ca..d0fb4fb2c1e7b 100644 --- a/solution/0500-0599/0596.Classes More Than 5 Students/README_EN.md +++ b/solution/0500-0599/0596.Classes More Than 5 Students/README_EN.md @@ -59,14 +59,12 @@ Courses table: ## Solutions -**Solution 1: Grouping and Aggregation** +### Solution 1: Grouping and Aggregation We can use the `GROUP BY` statement to group by class and then use the `HAVING` statement to filter out the classes with a student count greater than or equal to $5$. -### **SQL** - ```sql # Write your MySQL query statement below SELECT class @@ -76,3 +74,5 @@ HAVING COUNT(1) >= 5; ``` + + diff --git a/solution/0500-0599/0597.Friend Requests I Overall Acceptance Rate/README.md b/solution/0500-0599/0597.Friend Requests I Overall Acceptance Rate/README.md index 88c75eca12e35..85add3d6c76c0 100644 --- a/solution/0500-0599/0597.Friend Requests I Overall Acceptance Rate/README.md +++ b/solution/0500-0599/0597.Friend Requests I Overall Acceptance Rate/README.md @@ -95,12 +95,10 @@ RequestAccepted 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -117,3 +115,5 @@ SELECT ``` + + diff --git a/solution/0500-0599/0597.Friend Requests I Overall Acceptance Rate/README_EN.md b/solution/0500-0599/0597.Friend Requests I Overall Acceptance Rate/README_EN.md index f3234ef182cd2..867c456f565f2 100644 --- a/solution/0500-0599/0597.Friend Requests I Overall Acceptance Rate/README_EN.md +++ b/solution/0500-0599/0597.Friend Requests I Overall Acceptance Rate/README_EN.md @@ -93,9 +93,9 @@ There are 4 unique accepted requests, and there are 5 requests in total. So the ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -113,3 +113,5 @@ SELECT ``` + + diff --git a/solution/0500-0599/0598.Range Addition II/README.md b/solution/0500-0599/0598.Range Addition II/README.md index 3bb2ff06d205c..ba85fcdc25d09 100644 --- a/solution/0500-0599/0598.Range Addition II/README.md +++ b/solution/0500-0599/0598.Range Addition II/README.md @@ -52,14 +52,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int: @@ -69,10 +65,6 @@ class Solution: return m * n ``` -### **Java** - - - ```java class Solution { public int maxCount(int m, int n, int[][] ops) { @@ -85,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +90,6 @@ public: }; ``` -### **Go** - ```go func maxCount(m int, n int, ops [][]int) int { for _, op := range ops { @@ -112,10 +100,6 @@ func maxCount(m int, n int, ops [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0598.Range Addition II/README_EN.md b/solution/0500-0599/0598.Range Addition II/README_EN.md index 178b612ecec42..2bda9e9cdb1af 100644 --- a/solution/0500-0599/0598.Range Addition II/README_EN.md +++ b/solution/0500-0599/0598.Range Addition II/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return m * n ``` -### **Java** - ```java class Solution { public int maxCount(int m, int n, int[][] ops) { @@ -71,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -86,8 +82,6 @@ public: }; ``` -### **Go** - ```go func maxCount(m int, n int, ops [][]int) int { for _, op := range ops { @@ -98,10 +92,6 @@ func maxCount(m int, n int, ops [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0500-0599/0599.Minimum Index Sum of Two Lists/README.md b/solution/0500-0599/0599.Minimum Index Sum of Two Lists/README.md index 120f33c05e7eb..10a4ca1823048 100644 --- a/solution/0500-0599/0599.Minimum Index Sum of Two Lists/README.md +++ b/solution/0500-0599/0599.Minimum Index Sum of Two Lists/README.md @@ -42,20 +42,10 @@ ## 解法 - - -先用哈希表 mp 记录 list2 的每个字符串以及对应的下标。初始化最小的索引和 mi = 2000,ans 表示结果列表,初始值为空。 - -遍历 list1 每个字符串 v,若 v 在 mp 中,则计算两个字符串的索引和 t,并更新 ans 和 mi。 - -最后返回 ans 即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: @@ -73,10 +63,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { @@ -104,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,35 +115,29 @@ public: }; ``` -### **Go** - -```cpp -func findRestaurant(list1[] string, list2[] string)[] string { -mp:= make(map[string]int) +```go +func findRestaurant(list1 []string, list2 []string) []string { + mp := make(map[string]int) for i, v := range list2 { mp[v] = i } mi := 2000 var ans []string for i, v := range list1 { - if _ - , ok : = mp[v]; - ok { - t: - = i + mp[v] if t < mi { - ans = [] string { v } mi = t - } - else if t == mi { - ans = append(ans, v) - } - } - } - return ans + if _, ok := mp[v]; ok { + t := i + mp[v] + if t < mi { + ans = []string{v} + mi = t + } else if t == mi { + ans = append(ans, v) + } + } + } + return ans } ``` -### **TypeScript** - ```ts function findRestaurant(list1: string[], list2: string[]): string[] { let minI = Infinity; @@ -181,8 +159,6 @@ function findRestaurant(list1: string[], list2: string[]): string[] { } ``` -### **Rust** - ```rust use std::collections::HashMap; use std::iter::FromIterator; @@ -212,10 +188,37 @@ impl Solution { } ``` -### **...** + -``` +### 方法二 + + +```cpp +func findRestaurant(list1[] string, list2[] string)[] string { +mp:= make(map[string]int) + for i, v := range list2 { + mp[v] = i + } + mi := 2000 + var ans []string + for i, v := range list1 { + if _ + , ok : = mp[v]; + ok { + t: + = i + mp[v] if t < mi { + ans = [] string { v } mi = t + } + else if t == mi { + ans = append(ans, v) + } + } + } + return ans +} ``` + + diff --git a/solution/0500-0599/0599.Minimum Index Sum of Two Lists/README_EN.md b/solution/0500-0599/0599.Minimum Index Sum of Two Lists/README_EN.md index fb3f73b9f9f03..eac0cf7f035bb 100644 --- a/solution/0500-0599/0599.Minimum Index Sum of Two Lists/README_EN.md +++ b/solution/0500-0599/0599.Minimum Index Sum of Two Lists/README_EN.md @@ -55,9 +55,9 @@ The strings with the least index sum are "sad" and "happy". ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { @@ -105,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,35 +128,29 @@ public: }; ``` -### **Go** - -```cpp -func findRestaurant(list1[] string, list2[] string)[] string { -mp:= make(map[string]int) +```go +func findRestaurant(list1 []string, list2 []string) []string { + mp := make(map[string]int) for i, v := range list2 { mp[v] = i } mi := 2000 var ans []string for i, v := range list1 { - if _ - , ok : = mp[v]; - ok { - t: - = i + mp[v] if t < mi { - ans = [] string { v } mi = t - } - else if t == mi { - ans = append(ans, v) - } - } - } - return ans + if _, ok := mp[v]; ok { + t := i + mp[v] + if t < mi { + ans = []string{v} + mi = t + } else if t == mi { + ans = append(ans, v) + } + } + } + return ans } ``` -### **TypeScript** - ```ts function findRestaurant(list1: string[], list2: string[]): string[] { let minI = Infinity; @@ -182,8 +172,6 @@ function findRestaurant(list1: string[], list2: string[]): string[] { } ``` -### **Rust** - ```rust use std::collections::HashMap; use std::iter::FromIterator; @@ -213,10 +201,37 @@ impl Solution { } ``` -### **...** + -``` +### Solution 2 + + +```cpp +func findRestaurant(list1[] string, list2[] string)[] string { +mp:= make(map[string]int) + for i, v := range list2 { + mp[v] = i + } + mi := 2000 + var ans []string + for i, v := range list1 { + if _ + , ok : = mp[v]; + ok { + t: + = i + mp[v] if t < mi { + ans = [] string { v } mi = t + } + else if t == mi { + ans = append(ans, v) + } + } + } + return ans +} ``` + + diff --git a/solution/0600-0699/0600.Non-negative Integers without Consecutive Ones/README.md b/solution/0600-0699/0600.Non-negative Integers without Consecutive Ones/README.md index 0b9386013e2ae..46809d52be3ca 100644 --- a/solution/0600-0699/0600.Non-negative Integers without Consecutive Ones/README.md +++ b/solution/0600-0699/0600.Non-negative Integers without Consecutive Ones/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:数位 DP** +### 方法一:数位 DP 这道题实际上是求在给定区间 $[l,..r]$ 中,数字的二进制表示不包含连续的 $1$ 的个数。个数与数的位数以及每个二进制位上的数字有关。我们可以用数位 DP 的思路来解决这道题。数位 DP 中,数的大小对复杂度的影响很小。 @@ -91,10 +89,6 @@ $$ -### **Python3** - - - ```python class Solution: def findIntegers(self, n: int) -> int: @@ -119,10 +113,6 @@ class Solution: return dfs(l, 0, True) ``` -### **Java** - - - ```java class Solution { private int[] a = new int[33]; @@ -162,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -202,8 +190,6 @@ public: }; ``` -### **Go** - ```go func findIntegers(n int) int { a := make([]int, 33) @@ -244,10 +230,6 @@ func findIntegers(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0600.Non-negative Integers without Consecutive Ones/README_EN.md b/solution/0600-0699/0600.Non-negative Integers without Consecutive Ones/README_EN.md index 39bfaa32d47ea..c7a8b27d6128e 100644 --- a/solution/0600-0699/0600.Non-negative Integers without Consecutive Ones/README_EN.md +++ b/solution/0600-0699/0600.Non-negative Integers without Consecutive Ones/README_EN.md @@ -46,9 +46,9 @@ Among them, only integer 3 disobeys the rule (two consecutive ones) and the othe ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return dfs(l, 0, True) ``` -### **Java** - ```java class Solution { private int[] a = new int[33]; @@ -115,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +151,6 @@ public: }; ``` -### **Go** - ```go func findIntegers(n int) int { a := make([]int, 33) @@ -197,10 +191,6 @@ func findIntegers(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0601.Human Traffic of Stadium/README.md b/solution/0600-0699/0601.Human Traffic of Stadium/README.md index 5f1edc8b8714e..3e77da71420c6 100644 --- a/solution/0600-0699/0601.Human Traffic of Stadium/README.md +++ b/solution/0600-0699/0601.Human Traffic of Stadium/README.md @@ -64,12 +64,10 @@ id 为 5、6、7、8 的四行 id 连续,并且每行都有 >= 100 ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -88,3 +86,5 @@ ORDER BY 1; ``` + + diff --git a/solution/0600-0699/0601.Human Traffic of Stadium/README_EN.md b/solution/0600-0699/0601.Human Traffic of Stadium/README_EN.md index 6e84bd6abe0ee..db1d16860bb5d 100644 --- a/solution/0600-0699/0601.Human Traffic of Stadium/README_EN.md +++ b/solution/0600-0699/0601.Human Traffic of Stadium/README_EN.md @@ -61,9 +61,9 @@ The rows with ids 2 and 3 are not included because we need at least three consec ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -83,3 +83,5 @@ ORDER BY 1; ``` + + diff --git a/solution/0600-0699/0602.Friend Requests II Who Has the Most Friends/README.md b/solution/0600-0699/0602.Friend Requests II Who Has the Most Friends/README.md index b11e75110824f..34012f0e1dc2c 100644 --- a/solution/0600-0699/0602.Friend Requests II Who Has the Most Friends/README.md +++ b/solution/0600-0699/0602.Friend Requests II Who Has the Most Friends/README.md @@ -62,12 +62,10 @@ RequestAccepted 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -84,3 +82,5 @@ LIMIT 1; ``` + + diff --git a/solution/0600-0699/0602.Friend Requests II Who Has the Most Friends/README_EN.md b/solution/0600-0699/0602.Friend Requests II Who Has the Most Friends/README_EN.md index bceb6e7ee85e3..556a3b5b64c78 100644 --- a/solution/0600-0699/0602.Friend Requests II Who Has the Most Friends/README_EN.md +++ b/solution/0600-0699/0602.Friend Requests II Who Has the Most Friends/README_EN.md @@ -55,9 +55,9 @@ The person with id 3 is a friend of people 1, 2, and 4, so he has three friends ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -75,3 +75,5 @@ LIMIT 1; ``` + + diff --git a/solution/0600-0699/0603.Consecutive Available Seats/README.md b/solution/0600-0699/0603.Consecutive Available Seats/README.md index 7b9657a52cfeb..6ba6afaf1dc73 100644 --- a/solution/0600-0699/0603.Consecutive Available Seats/README.md +++ b/solution/0600-0699/0603.Consecutive Available Seats/README.md @@ -56,20 +56,12 @@ Cinema 表: ## 解法 - - -**方法一:自连接** +### 方法一:自连接 我们可以使用自连接的方式,将相邻的两个座位连接起来,然后筛选出连续空余的座位并去重排序即可。 -**方法二:窗口函数** - -我们也可以使用 `LAG` 和 `LEAD` 函数(或者 `SUM() OVER(ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)`)来获取相邻的座位信息,然后筛选出连续空余的座位并去重排序即可。 - -### **SQL** - ```sql # Write your MySQL query statement below SELECT DISTINCT a.seat_id @@ -79,6 +71,14 @@ FROM ORDER BY 1; ``` + + +### 方法二:窗口函数 + +我们也可以使用 `LAG` 和 `LEAD` 函数(或者 `SUM() OVER(ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)`)来获取相邻的座位信息,然后筛选出连续空余的座位并去重排序即可。 + + + ```sql # Write your MySQL query statement below WITH @@ -94,6 +94,12 @@ FROM T WHERE a = 2 OR b = 2; ``` + + +### 方法三 + + + ```sql # Write your MySQL query statement below WITH @@ -113,3 +119,5 @@ ORDER BY 1; ``` + + diff --git a/solution/0600-0699/0603.Consecutive Available Seats/README_EN.md b/solution/0600-0699/0603.Consecutive Available Seats/README_EN.md index 5e8fe0777303e..20923089c7ece 100644 --- a/solution/0600-0699/0603.Consecutive Available Seats/README_EN.md +++ b/solution/0600-0699/0603.Consecutive Available Seats/README_EN.md @@ -54,18 +54,12 @@ Cinema table: ## Solutions -**Solution 1: Self-Join** +### Solution 1: Self-Join We can use a self-join to join the `Seat` table with itself, and then filter out the records where the `id` of the left seat is equal to the `id` of the right seat minus $1$, and where both seats are empty. -**Solution 2: Window Function** - -We can use the `LAG` and `LEAD` functions (or `SUM() OVER(ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)`) to obtain the information of adjacent seats, and then filter out the consecutive empty seats and sort them in a unique way. - -### **SQL** - ```sql # Write your MySQL query statement below SELECT DISTINCT a.seat_id @@ -75,6 +69,14 @@ FROM ORDER BY 1; ``` + + +### Solution 2: Window Function + +We can use the `LAG` and `LEAD` functions (or `SUM() OVER(ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)`) to obtain the information of adjacent seats, and then filter out the consecutive empty seats and sort them in a unique way. + + + ```sql # Write your MySQL query statement below WITH @@ -90,6 +92,12 @@ FROM T WHERE a = 2 OR b = 2; ``` + + +### Solution 3 + + + ```sql # Write your MySQL query statement below WITH @@ -109,3 +117,5 @@ ORDER BY 1; ``` + + diff --git a/solution/0600-0699/0604.Design Compressed String Iterator/README.md b/solution/0600-0699/0604.Design Compressed String Iterator/README.md index 4d232432b3b5e..abcf9dd76e75f 100644 --- a/solution/0600-0699/0604.Design Compressed String Iterator/README.md +++ b/solution/0600-0699/0604.Design Compressed String Iterator/README.md @@ -51,9 +51,7 @@ stringIterator.hasNext(); // 返回 True ## 解法 - - -**方法一:解析存储** +### 方法一:解析存储 将 `compressedString` 解析成字符 $c$ 和对应的重复次数 $x$,存储在数组或列表 $d$ 中,用 $p$ 指向当前字符。 @@ -63,10 +61,6 @@ stringIterator.hasNext(); // 返回 True -### **Python3** - - - ```python class StringIterator: def __init__(self, compressedString: str): @@ -102,10 +96,6 @@ class StringIterator: # param_2 = obj.hasNext() ``` -### **Java** - - - ```java class StringIterator { private List d = new ArrayList<>(); @@ -158,8 +148,6 @@ class Node { */ ``` -### **C++** - ```cpp class StringIterator { public: @@ -202,8 +190,6 @@ private: */ ``` -### **Go** - ```go type pair struct { c byte @@ -256,10 +242,6 @@ func (this *StringIterator) HasNext() bool { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0604.Design Compressed String Iterator/README_EN.md b/solution/0600-0699/0604.Design Compressed String Iterator/README_EN.md index 1cb70685199f5..f9cede1e9566b 100644 --- a/solution/0600-0699/0604.Design Compressed String Iterator/README_EN.md +++ b/solution/0600-0699/0604.Design Compressed String Iterator/README_EN.md @@ -48,9 +48,9 @@ stringIterator.hasNext(); // return True ## Solutions - +### Solution 1 -### **Python3** + ```python class StringIterator: @@ -87,8 +87,6 @@ class StringIterator: # param_2 = obj.hasNext() ``` -### **Java** - ```java class StringIterator { private List d = new ArrayList<>(); @@ -141,8 +139,6 @@ class Node { */ ``` -### **C++** - ```cpp class StringIterator { public: @@ -185,8 +181,6 @@ private: */ ``` -### **Go** - ```go type pair struct { c byte @@ -239,10 +233,6 @@ func (this *StringIterator) HasNext() bool { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0605.Can Place Flowers/README.md b/solution/0600-0699/0605.Can Place Flowers/README.md index a9be6a2602e8b..33ceb960d09f1 100644 --- a/solution/0600-0699/0605.Can Place Flowers/README.md +++ b/solution/0600-0699/0605.Can Place Flowers/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们直接遍历数组 $flowerbed$,对于每个位置 $i$,如果 $flowerbed[i]=0$,并且其左右相邻位置都为 $0$,则我们可以在该位置种花,否则不能。最后我们统计可以种下的花的数量,如果其不小于 $n$,则返回 $true$,否则返回 $false$。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: @@ -64,10 +58,6 @@ class Solution: return n <= 0 ``` -### **Java** - - - ```java class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { @@ -85,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +93,6 @@ public: }; ``` -### **Go** - ```go func canPlaceFlowers(flowerbed []int, n int) bool { m := len(flowerbed) @@ -127,8 +113,6 @@ func canPlaceFlowers(flowerbed []int, n int) bool { } ``` -### **TypeScript** - ```ts function canPlaceFlowers(flowerbed: number[], n: number): boolean { const m = flowerbed.length; @@ -144,7 +128,24 @@ function canPlaceFlowers(flowerbed: number[], n: number): boolean { } ``` -### **PHP** +```rust +impl Solution { + pub fn can_place_flowers(flowerbed: Vec, n: i32) -> bool { + let (mut flowers, mut cnt) = (vec![0], 0); + flowers.append(&mut flowerbed.clone()); + flowers.push(0); + + for i in 1..flowers.len() - 1 { + let (l, r) = (flowers[i - 1], flowers[i + 1]); + if l + flowers[i] + r == 0 { + flowers[i] = 1; + cnt += 1; + } + } + cnt >= n + } +} +``` ```php class Solution { @@ -169,31 +170,6 @@ class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn can_place_flowers(flowerbed: Vec, n: i32) -> bool { - let (mut flowers, mut cnt) = (vec![0], 0); - flowers.append(&mut flowerbed.clone()); - flowers.push(0); - - for i in 1..flowers.len() - 1 { - let (l, r) = (flowers[i - 1], flowers[i + 1]); - if l + flowers[i] + r == 0 { - flowers[i] = 1; - cnt += 1; - } - } - cnt >= n - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0605.Can Place Flowers/README_EN.md b/solution/0600-0699/0605.Can Place Flowers/README_EN.md index 1a44d5a13982e..01e9e1741ab6c 100644 --- a/solution/0600-0699/0605.Can Place Flowers/README_EN.md +++ b/solution/0600-0699/0605.Can Place Flowers/README_EN.md @@ -28,7 +28,7 @@ ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy We directly traverse the array $flowerbed$. For each position $i$, if $flowerbed[i]=0$ and its adjacent positions on the left and right are also $0$, then we can plant a flower at this position. Otherwise, we cannot. Finally, we count the number of flowers that can be planted. If it is not less than $n$, we return $true$, otherwise we return $false$. @@ -36,8 +36,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $flowerbed$. -### **Python3** - ```python class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: @@ -49,8 +47,6 @@ class Solution: return n <= 0 ``` -### **Java** - ```java class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { @@ -68,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -88,8 +82,6 @@ public: }; ``` -### **Go** - ```go func canPlaceFlowers(flowerbed []int, n int) bool { m := len(flowerbed) @@ -110,8 +102,6 @@ func canPlaceFlowers(flowerbed []int, n int) bool { } ``` -### **TypeScript** - ```ts function canPlaceFlowers(flowerbed: number[], n: number): boolean { const m = flowerbed.length; @@ -127,7 +117,24 @@ function canPlaceFlowers(flowerbed: number[], n: number): boolean { } ``` -### **PHP** +```rust +impl Solution { + pub fn can_place_flowers(flowerbed: Vec, n: i32) -> bool { + let (mut flowers, mut cnt) = (vec![0], 0); + flowers.append(&mut flowerbed.clone()); + flowers.push(0); + + for i in 1..flowers.len() - 1 { + let (l, r) = (flowers[i - 1], flowers[i + 1]); + if l + flowers[i] + r == 0 { + flowers[i] = 1; + cnt += 1; + } + } + cnt >= n + } +} +``` ```php class Solution { @@ -152,31 +159,6 @@ class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn can_place_flowers(flowerbed: Vec, n: i32) -> bool { - let (mut flowers, mut cnt) = (vec![0], 0); - flowers.append(&mut flowerbed.clone()); - flowers.push(0); - - for i in 1..flowers.len() - 1 { - let (l, r) = (flowers[i - 1], flowers[i + 1]); - if l + flowers[i] + r == 0 { - flowers[i] = 1; - cnt += 1; - } - } - cnt >= n - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0606.Construct String from Binary Tree/README.md b/solution/0600-0699/0606.Construct String from Binary Tree/README.md index 1771184171d05..2c917a68d2966 100644 --- a/solution/0600-0699/0606.Construct String from Binary Tree/README.md +++ b/solution/0600-0699/0606.Construct String from Binary Tree/README.md @@ -42,14 +42,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -71,10 +67,6 @@ class Solution: return dfs(root) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -107,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -132,8 +122,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -157,8 +145,6 @@ func tree2str(root *TreeNode) string { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -187,8 +173,6 @@ function tree2str(root: TreeNode | null): string { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -240,10 +224,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0606.Construct String from Binary Tree/README_EN.md b/solution/0600-0699/0606.Construct String from Binary Tree/README_EN.md index 7cd092b546110..47494459bb4d1 100644 --- a/solution/0600-0699/0606.Construct String from Binary Tree/README_EN.md +++ b/solution/0600-0699/0606.Construct String from Binary Tree/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -60,8 +60,6 @@ class Solution: return dfs(root) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -119,8 +115,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -144,8 +138,6 @@ func tree2str(root *TreeNode) string { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -174,8 +166,6 @@ function tree2str(root: TreeNode | null): string { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -227,10 +217,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0607.Sales Person/README.md b/solution/0600-0699/0607.Sales Person/README.md index 9c83e47cd0533..04b21e636af55 100644 --- a/solution/0600-0699/0607.Sales Person/README.md +++ b/solution/0600-0699/0607.Sales Person/README.md @@ -114,16 +114,12 @@ Orders 表: ## 解法 - - -**方法一:左连接 + 分组统计** +### 方法一:左连接 + 分组统计 我们可以使用左连接将 `SalesPerson` 表与 `Orders` 表连接起来,再与 `Company` 表连接起来,然后按照 `sales_id` 分组,每组统计有多少个公司的名字为 `RED` 的订单,最后筛选出没有这样的订单的销售人员的姓名。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT s.name @@ -136,3 +132,5 @@ HAVING IFNULL(SUM(c.name = 'RED'), 0) = 0; ``` + + diff --git a/solution/0600-0699/0607.Sales Person/README_EN.md b/solution/0600-0699/0607.Sales Person/README_EN.md index f909cf2f4cf74..7bcf2f2893a70 100644 --- a/solution/0600-0699/0607.Sales Person/README_EN.md +++ b/solution/0600-0699/0607.Sales Person/README_EN.md @@ -111,14 +111,12 @@ According to orders 3 and 4 in the Orders table, it is easy to tell that only sa ## Solutions -**Solution 1: LEFT JOIN + GROUP BY** +### Solution 1: LEFT JOIN + GROUP BY We can use a left join to join the `SalesPerson` table with the `Orders` table on the condition of sales id, and then join the result with the `Company` table on the condition of company id. After that, we can group by `sales_id` and count the number of orders with the company name `RED`. Finally, we can filter out the salespersons who do not have any orders with the company name `RED`. -### **SQL** - ```sql # Write your MySQL query statement below SELECT s.name @@ -131,3 +129,5 @@ HAVING IFNULL(SUM(c.name = 'RED'), 0) = 0; ``` + + diff --git a/solution/0600-0699/0608.Tree Node/README.md b/solution/0600-0699/0608.Tree Node/README.md index 4d2555b19a6b3..624dfa25e7b6a 100644 --- a/solution/0600-0699/0608.Tree Node/README.md +++ b/solution/0600-0699/0608.Tree Node/README.md @@ -89,9 +89,7 @@ Tree table: ## 解法 - - -**方法一:条件判断 + 子查询** +### 方法一:条件判断 + 子查询 我们可以使用 `CASE WHEN` 条件判断语句来判断每个节点的类型,具体地: @@ -101,8 +99,6 @@ Tree table: -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -116,3 +112,5 @@ FROM Tree; ``` + + diff --git a/solution/0600-0699/0608.Tree Node/README_EN.md b/solution/0600-0699/0608.Tree Node/README_EN.md index c5c4e8c980646..fb3c9544c0651 100644 --- a/solution/0600-0699/0608.Tree Node/README_EN.md +++ b/solution/0600-0699/0608.Tree Node/README_EN.md @@ -86,7 +86,7 @@ Tree table: ## Solutions -**Solution 1: Conditional Statements + Subquery** +### Solution 1: Conditional Statements + Subquery We can use the `CASE WHEN` conditional statement to determine the type of each node as follows: @@ -96,8 +96,6 @@ We can use the `CASE WHEN` conditional statement to determine the type of each n -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -111,3 +109,5 @@ FROM Tree; ``` + + diff --git a/solution/0600-0699/0609.Find Duplicate File in System/README.md b/solution/0600-0699/0609.Find Duplicate File in System/README.md index 2ea1400186acd..463bb68622da2 100644 --- a/solution/0600-0699/0609.Find Duplicate File in System/README.md +++ b/solution/0600-0699/0609.Find Duplicate File in System/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们创建哈希表 `d`,其中键是文件内容,值是具有相同内容的文件路径列表。 @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def findDuplicate(self, paths: List[str]) -> List[List[str]]: @@ -98,10 +92,6 @@ class Solution: return [v for v in d.values() if len(v) > 1] ``` -### **Java** - - - ```java class Solution { public List> findDuplicate(String[] paths) { @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +151,6 @@ public: }; ``` -### **Go** - ```go func findDuplicate(paths []string) [][]string { d := map[string][]string{} @@ -187,8 +173,6 @@ func findDuplicate(paths []string) [][]string { } ``` -### **TypeScript** - ```ts function findDuplicate(paths: string[]): string[][] { const d = new Map(); @@ -205,10 +189,6 @@ function findDuplicate(paths: string[]): string[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0609.Find Duplicate File in System/README_EN.md b/solution/0600-0699/0609.Find Duplicate File in System/README_EN.md index c2532446a82d7..281939416cd04 100644 --- a/solution/0600-0699/0609.Find Duplicate File in System/README_EN.md +++ b/solution/0600-0699/0609.Find Duplicate File in System/README_EN.md @@ -55,9 +55,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return [v for v in d.values() if len(v) > 1] ``` -### **Java** - ```java class Solution { public List> findDuplicate(String[] paths) { @@ -98,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +131,6 @@ public: }; ``` -### **Go** - ```go func findDuplicate(paths []string) [][]string { d := map[string][]string{} @@ -159,8 +153,6 @@ func findDuplicate(paths []string) [][]string { } ``` -### **TypeScript** - ```ts function findDuplicate(paths: string[]): string[][] { const d = new Map(); @@ -177,10 +169,6 @@ function findDuplicate(paths: string[]): string[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0610.Triangle Judgement/README.md b/solution/0600-0699/0610.Triangle Judgement/README.md index 768570a3712c1..e672dd6b2c048 100644 --- a/solution/0600-0699/0610.Triangle Judgement/README.md +++ b/solution/0600-0699/0610.Triangle Judgement/README.md @@ -51,16 +51,12 @@ Triangle 表: ## 解法 - - -**方法一:IF 语句 + 三角形判断条件** +### 方法一:IF 语句 + 三角形判断条件 三条边能否构成三角形的条件是:任意两边之和大于第三边。因此,我们可以使用 `IF` 语句来判断是否满足这个条件,如果满足则返回 `Yes`,否则返回 `No`。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -70,3 +66,5 @@ FROM Triangle; ``` + + diff --git a/solution/0600-0699/0610.Triangle Judgement/README_EN.md b/solution/0600-0699/0610.Triangle Judgement/README_EN.md index 326133cd34639..dd44badde181c 100644 --- a/solution/0600-0699/0610.Triangle Judgement/README_EN.md +++ b/solution/0600-0699/0610.Triangle Judgement/README_EN.md @@ -49,14 +49,12 @@ Triangle table: ## Solutions -**Solution 1: IF Statement + Triangle Inequality** +### Solution 1: IF Statement + Triangle Inequality The condition for whether three sides can form a triangle is that the sum of any two sides is greater than the third side. Therefore, we can use an `IF` statement to determine whether this condition is satisfied. If it is satisfied, we return `Yes`, otherwise we return `No`. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -66,3 +64,5 @@ FROM Triangle; ``` + + diff --git a/solution/0600-0699/0611.Valid Triangle Number/README.md b/solution/0600-0699/0611.Valid Triangle Number/README.md index 05e8e4d31d5d7..50bc8c7913d4a 100644 --- a/solution/0600-0699/0611.Valid Triangle Number/README.md +++ b/solution/0600-0699/0611.Valid Triangle Number/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 一个有效三角形需要满足:**任意两边之和大于第三边**。即:`a + b > c`①, `a + c > b`②, `b + c > a`③。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def triangleNumber(self, nums: List[int]) -> int: @@ -68,10 +62,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int triangleNumber(int[] nums) { @@ -94,55 +84,23 @@ class Solution { } ``` -```java +```cpp class Solution { - public int triangleNumber(int[] nums) { - Arrays.sort(nums); - int ans = 0; - for (int i = 0, n = nums.length; i < n - 2; ++i) { +public: + int triangleNumber(vector& nums) { + sort(nums.begin(), nums.end()); + int ans = 0, n = nums.size(); + for (int i = 0; i < n - 2; ++i) { for (int j = i + 1; j < n - 1; ++j) { - int left = j + 1, right = n; - while (left < right) { - int mid = (left + right) >> 1; - if (nums[mid] >= nums[i] + nums[j]) { - right = mid; - } else { - left = mid + 1; - } - } - ans += left - j - 1; + int k = lower_bound(nums.begin() + j + 1, nums.end(), nums[i] + nums[j]) - nums.begin() - 1; + ans += k - j; } } return ans; } -} -``` - -### **TypeScript** - -```ts -function triangleNumber(nums: number[]): number { - nums.sort((a, b) => a - b); - let n = nums.length; - let ans = 0; - for (let i = n - 1; i >= 2; i--) { - let left = 0, - right = i - 1; - while (left < right) { - if (nums[left] + nums[right] > nums[i]) { - ans += right - left; - right--; - } else { - left++; - } - } - } - return ans; -} +}; ``` -### **Go** - ```go func triangleNumber(nums []int) int { sort.Ints(nums) @@ -165,27 +123,27 @@ func triangleNumber(nums []int) int { } ``` -### **C++** - -```cpp -class Solution { -public: - int triangleNumber(vector& nums) { - sort(nums.begin(), nums.end()); - int ans = 0, n = nums.size(); - for (int i = 0; i < n - 2; ++i) { - for (int j = i + 1; j < n - 1; ++j) { - int k = lower_bound(nums.begin() + j + 1, nums.end(), nums[i] + nums[j]) - nums.begin() - 1; - ans += k - j; +```ts +function triangleNumber(nums: number[]): number { + nums.sort((a, b) => a - b); + let n = nums.length; + let ans = 0; + for (let i = n - 1; i >= 2; i--) { + let left = 0, + right = i - 1; + while (left < right) { + if (nums[left] + nums[right] > nums[i]) { + ans += right - left; + right--; + } else { + left++; } } - return ans; } -}; + return ans; +} ``` -### **Rust** - ```rust impl Solution { pub fn triangle_number(mut nums: Vec) -> i32 { @@ -209,10 +167,36 @@ impl Solution { } ``` -### **...** + -``` +### 方法二 + + +```java +class Solution { + public int triangleNumber(int[] nums) { + Arrays.sort(nums); + int ans = 0; + for (int i = 0, n = nums.length; i < n - 2; ++i) { + for (int j = i + 1; j < n - 1; ++j) { + int left = j + 1, right = n; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] >= nums[i] + nums[j]) { + right = mid; + } else { + left = mid + 1; + } + } + ans += left - j - 1; + } + } + return ans; + } +} ``` + + diff --git a/solution/0600-0699/0611.Valid Triangle Number/README_EN.md b/solution/0600-0699/0611.Valid Triangle Number/README_EN.md index a7f943e54b621..0463c1b3bb75a 100644 --- a/solution/0600-0699/0611.Valid Triangle Number/README_EN.md +++ b/solution/0600-0699/0611.Valid Triangle Number/README_EN.md @@ -35,12 +35,10 @@ ## Solutions -First enumerate two edges, and then use binary search to locate the third edge. +### Solution 1 -### **Python3** - ```python class Solution: def triangleNumber(self, nums: List[int]) -> int: @@ -53,8 +51,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int triangleNumber(int[] nums) { @@ -77,55 +73,23 @@ class Solution { } ``` -```java +```cpp class Solution { - public int triangleNumber(int[] nums) { - Arrays.sort(nums); - int ans = 0; - for (int i = 0, n = nums.length; i < n - 2; ++i) { +public: + int triangleNumber(vector& nums) { + sort(nums.begin(), nums.end()); + int ans = 0, n = nums.size(); + for (int i = 0; i < n - 2; ++i) { for (int j = i + 1; j < n - 1; ++j) { - int left = j + 1, right = n; - while (left < right) { - int mid = (left + right) >> 1; - if (nums[mid] >= nums[i] + nums[j]) { - right = mid; - } else { - left = mid + 1; - } - } - ans += left - j - 1; + int k = lower_bound(nums.begin() + j + 1, nums.end(), nums[i] + nums[j]) - nums.begin() - 1; + ans += k - j; } } return ans; } -} -``` - -### **TypeScript** - -```ts -function triangleNumber(nums: number[]): number { - nums.sort((a, b) => a - b); - let n = nums.length; - let ans = 0; - for (let i = n - 1; i >= 2; i--) { - let left = 0, - right = i - 1; - while (left < right) { - if (nums[left] + nums[right] > nums[i]) { - ans += right - left; - right--; - } else { - left++; - } - } - } - return ans; -} +}; ``` -### **Go** - ```go func triangleNumber(nums []int) int { sort.Ints(nums) @@ -148,27 +112,27 @@ func triangleNumber(nums []int) int { } ``` -### **C++** - -```cpp -class Solution { -public: - int triangleNumber(vector& nums) { - sort(nums.begin(), nums.end()); - int ans = 0, n = nums.size(); - for (int i = 0; i < n - 2; ++i) { - for (int j = i + 1; j < n - 1; ++j) { - int k = lower_bound(nums.begin() + j + 1, nums.end(), nums[i] + nums[j]) - nums.begin() - 1; - ans += k - j; +```ts +function triangleNumber(nums: number[]): number { + nums.sort((a, b) => a - b); + let n = nums.length; + let ans = 0; + for (let i = n - 1; i >= 2; i--) { + let left = 0, + right = i - 1; + while (left < right) { + if (nums[left] + nums[right] > nums[i]) { + ans += right - left; + right--; + } else { + left++; } } - return ans; } -}; + return ans; +} ``` -### **Rust** - ```rust impl Solution { pub fn triangle_number(mut nums: Vec) -> i32 { @@ -192,10 +156,36 @@ impl Solution { } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + public int triangleNumber(int[] nums) { + Arrays.sort(nums); + int ans = 0; + for (int i = 0, n = nums.length; i < n - 2; ++i) { + for (int j = i + 1; j < n - 1; ++j) { + int left = j + 1, right = n; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] >= nums[i] + nums[j]) { + right = mid; + } else { + left = mid + 1; + } + } + ans += left - j - 1; + } + } + return ans; + } +} ``` + + diff --git a/solution/0600-0699/0612.Shortest Distance in a Plane/README.md b/solution/0600-0699/0612.Shortest Distance in a Plane/README.md index cc0a8030c4b88..3277bff33f316 100644 --- a/solution/0600-0699/0612.Shortest Distance in a Plane/README.md +++ b/solution/0600-0699/0612.Shortest Distance in a Plane/README.md @@ -58,12 +58,10 @@ Point2D table: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT ROUND(SQRT(POW(p1.x - p2.x, 2) + POW(p1.y - p2.y, 2)), 2) AS shortest @@ -75,3 +73,5 @@ LIMIT 1; ``` + + diff --git a/solution/0600-0699/0612.Shortest Distance in a Plane/README_EN.md b/solution/0600-0699/0612.Shortest Distance in a Plane/README_EN.md index a1ab71cb5990e..6f55e03767b9e 100644 --- a/solution/0600-0699/0612.Shortest Distance in a Plane/README_EN.md +++ b/solution/0600-0699/0612.Shortest Distance in a Plane/README_EN.md @@ -49,9 +49,9 @@ Point2D table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -64,3 +64,5 @@ LIMIT 1; ``` + + diff --git a/solution/0600-0699/0613.Shortest Distance in a Line/README.md b/solution/0600-0699/0613.Shortest Distance in a Line/README.md index 61fecefd34955..71793cb8d67b9 100644 --- a/solution/0600-0699/0613.Shortest Distance in a Line/README.md +++ b/solution/0600-0699/0613.Shortest Distance in a Line/README.md @@ -53,20 +53,12 @@ Point 表: ## 解法 - - -**方法一:自连接** +### 方法一:自连接 我们可以使用自连接,将表中的每个点与其他更大的点进行连接,然后计算两点之间的距离,最后取最小值。 -**方法二:窗口函数** - -我们也可以使用窗口函数,将表中的点按照 $x$ 排序,然后计算相邻两点之间的距离,最后取最小值。 - -### **SQL** - ```sql # Write your MySQL query statement below SELECT MIN(p2.x - p1.x) AS shortest @@ -75,6 +67,14 @@ FROM JOIN Point AS p2 ON p1.x < p2.x; ``` + + +### 方法二:窗口函数 + +我们也可以使用窗口函数,将表中的点按照 $x$ 排序,然后计算相邻两点之间的距离,最后取最小值。 + + + ```sql # Write your MySQL query statement below SELECT x - LAG(x) OVER (ORDER BY x) AS shortest @@ -84,3 +84,5 @@ LIMIT 1, 1; ``` + + diff --git a/solution/0600-0699/0613.Shortest Distance in a Line/README_EN.md b/solution/0600-0699/0613.Shortest Distance in a Line/README_EN.md index 0b74932392d10..860605efa0458 100644 --- a/solution/0600-0699/0613.Shortest Distance in a Line/README_EN.md +++ b/solution/0600-0699/0613.Shortest Distance in a Line/README_EN.md @@ -49,18 +49,12 @@ Point table: ## Solutions -**Solution 1: Self-Join** +### Solution 1: Self-Join We can use a self-join to join each point in the table with the larger points, and then calculate the distance between the two points. Finally, we can take the minimum distance. -**Solution 2: Window Function** - -We can use a window function to sort the points in the table by their $x$ values, and then calculate the distance between adjacent points. Finally, we can take the minimum distance. - -### **SQL** - ```sql # Write your MySQL query statement below SELECT MIN(p2.x - p1.x) AS shortest @@ -69,6 +63,14 @@ FROM JOIN Point AS p2 ON p1.x < p2.x; ``` + + +### Solution 2: Window Function + +We can use a window function to sort the points in the table by their $x$ values, and then calculate the distance between adjacent points. Finally, we can take the minimum distance. + + + ```sql # Write your MySQL query statement below SELECT x - LAG(x) OVER (ORDER BY x) AS shortest @@ -78,3 +80,5 @@ LIMIT 1, 1; ``` + + diff --git a/solution/0600-0699/0614.Second Degree Follower/README.md b/solution/0600-0699/0614.Second Degree Follower/README.md index fdf748c1f7f88..e2a1124b795de 100644 --- a/solution/0600-0699/0614.Second Degree Follower/README.md +++ b/solution/0600-0699/0614.Second Degree Follower/README.md @@ -64,12 +64,10 @@ Follow table: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -86,3 +84,5 @@ ORDER BY 1; ``` + + diff --git a/solution/0600-0699/0614.Second Degree Follower/README_EN.md b/solution/0600-0699/0614.Second Degree Follower/README_EN.md index eea159abdaaa9..9761e349fb52d 100644 --- a/solution/0600-0699/0614.Second Degree Follower/README_EN.md +++ b/solution/0600-0699/0614.Second Degree Follower/README_EN.md @@ -62,9 +62,9 @@ User Alice has 1 follower. Alice is not a second-degree follower because she doe ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -82,3 +82,5 @@ ORDER BY 1; ``` + + diff --git a/solution/0600-0699/0615.Average Salary Departments VS Company/README.md b/solution/0600-0699/0615.Average Salary Departments VS Company/README.md index 7cdcc605fb0ce..cb1d12c4daaba 100644 --- a/solution/0600-0699/0615.Average Salary Departments VS Company/README.md +++ b/solution/0600-0699/0615.Average Salary Departments VS Company/README.md @@ -86,12 +86,10 @@ Employee 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -116,6 +114,12 @@ SELECT DISTINCT FROM t; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below WITH @@ -146,3 +150,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/0600-0699/0615.Average Salary Departments VS Company/README_EN.md b/solution/0600-0699/0615.Average Salary Departments VS Company/README_EN.md index 2ac2c26fae64e..26b027a8956c8 100644 --- a/solution/0600-0699/0615.Average Salary Departments VS Company/README_EN.md +++ b/solution/0600-0699/0615.Average Salary Departments VS Company/README_EN.md @@ -86,9 +86,9 @@ With he same formula for the average salary comparison in February, the result i ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -114,6 +114,12 @@ SELECT DISTINCT FROM t; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below WITH @@ -144,3 +150,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/0600-0699/0616.Add Bold Tag in String/README.md b/solution/0600-0699/0616.Add Bold Tag in String/README.md index 2255c677ab0f3..639249bceeec1 100644 --- a/solution/0600-0699/0616.Add Bold Tag in String/README.md +++ b/solution/0600-0699/0616.Add Bold Tag in String/README.md @@ -61,18 +61,12 @@ ## 解法 - - -**方法一:前缀树 + 区间合并** +### 方法一:前缀树 + 区间合并 相似题目:[1065. 字符串的索引对](/solution/1000-1099/1065.Index%20Pairs%20of%20a%20String/README.md)、[758. 字符串中的加粗单词](/solution/0700-0799/0758.Bold%20Words%20in%20String/README.md) -### **Python3** - - - ```python class Trie: def __init__(self): @@ -135,10 +129,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Trie { Trie[] children = new Trie[128]; @@ -216,8 +206,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -287,8 +275,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [128]*Trie @@ -365,10 +351,6 @@ func addBoldTag(s string, words []string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0616.Add Bold Tag in String/README_EN.md b/solution/0600-0699/0616.Add Bold Tag in String/README_EN.md index b74499f357ef1..dabe1db3869fd 100644 --- a/solution/0600-0699/0616.Add Bold Tag in String/README_EN.md +++ b/solution/0600-0699/0616.Add Bold Tag in String/README_EN.md @@ -54,9 +54,9 @@ Since now the four <b>'s are consecutive, we merge them: "<b&g ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -120,8 +120,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Trie { Trie[] children = new Trie[128]; @@ -199,8 +197,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -270,8 +266,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [128]*Trie @@ -348,10 +342,6 @@ func addBoldTag(s string, words []string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0617.Merge Two Binary Trees/README.md b/solution/0600-0699/0617.Merge Two Binary Trees/README.md index 4338087371931..9598b6e4954a4 100644 --- a/solution/0600-0699/0617.Merge Two Binary Trees/README.md +++ b/solution/0600-0699/0617.Merge Two Binary Trees/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 递归合并两棵树的节点。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -79,10 +73,6 @@ class Solution: return node ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -167,8 +153,6 @@ func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -194,8 +178,6 @@ function mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode | } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -241,8 +223,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -271,10 +251,6 @@ var mergeTrees = function (root1, root2) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0617.Merge Two Binary Trees/README_EN.md b/solution/0600-0699/0617.Merge Two Binary Trees/README_EN.md index 4d8ea23f827b3..b05e48464f987 100644 --- a/solution/0600-0699/0617.Merge Two Binary Trees/README_EN.md +++ b/solution/0600-0699/0617.Merge Two Binary Trees/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -62,8 +62,6 @@ class Solution: return node ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -148,8 +142,6 @@ func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -175,8 +167,6 @@ function mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode | } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -222,8 +212,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -252,10 +240,6 @@ var mergeTrees = function (root1, root2) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0618.Students Report By Geography/README.md b/solution/0600-0699/0618.Students Report By Geography/README.md index ad9cf0de0152f..370b22ad452f0 100644 --- a/solution/0600-0699/0618.Students Report By Geography/README.md +++ b/solution/0600-0699/0618.Students Report By Geography/README.md @@ -58,16 +58,12 @@ Student table: ## 解法 - - -**方法一:窗口函数 + GROUP BY** +### 方法一:窗口函数 + GROUP BY 我们可以使用窗口函数 `row_number()` 来为每个大洲的学生编号,然后使用 `GROUP BY` 来将同一编号的学生聚合到一行中。 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -89,3 +85,5 @@ GROUP BY rk; ``` + + diff --git a/solution/0600-0699/0618.Students Report By Geography/README_EN.md b/solution/0600-0699/0618.Students Report By Geography/README_EN.md index bfb9b28981bc0..60be848471344 100644 --- a/solution/0600-0699/0618.Students Report By Geography/README_EN.md +++ b/solution/0600-0699/0618.Students Report By Geography/README_EN.md @@ -55,9 +55,9 @@ Student table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -80,3 +80,5 @@ GROUP BY rk; ``` + + diff --git a/solution/0600-0699/0619.Biggest Single Number/README.md b/solution/0600-0699/0619.Biggest Single Number/README.md index 3782e0f502a45..210e2e55bccdf 100644 --- a/solution/0600-0699/0619.Biggest Single Number/README.md +++ b/solution/0600-0699/0619.Biggest Single Number/README.md @@ -89,20 +89,12 @@ MyNumbers table: ## 解法 - - -**方法一:分组 + 子查询** +### 方法一:分组 + 子查询 我们可以先将 `MyNumbers` 表按照 `num` 进行分组统计,找出只出现一次的数字,然后使用子查询找出最大的数字即可。 -**方法二:分组 + `CASE` 表达式** - -与方法一类似,我们可以先将 `MyNumbers` 表按照 `num` 进行分组统计,然后使用 `CASE` 表达式,找出只出现一次的数字,然后按数字降序排序,取第一个即可。 - -### **SQL** - ```sql # Write your MySQL query statement below SELECT MAX(num) AS num @@ -115,6 +107,14 @@ FROM ) AS t; ``` + + +### 方法二:分组 + `CASE` 表达式 + +与方法一类似,我们可以先将 `MyNumbers` 表按照 `num` 进行分组统计,然后使用 `CASE` 表达式,找出只出现一次的数字,然后按数字降序排序,取第一个即可。 + + + ```sql # Write your MySQL query statement below SELECT @@ -129,3 +129,5 @@ LIMIT 1; ``` + + diff --git a/solution/0600-0699/0619.Biggest Single Number/README_EN.md b/solution/0600-0699/0619.Biggest Single Number/README_EN.md index 1c4c14625052f..d2cd74499989b 100644 --- a/solution/0600-0699/0619.Biggest Single Number/README_EN.md +++ b/solution/0600-0699/0619.Biggest Single Number/README_EN.md @@ -79,18 +79,12 @@ MyNumbers table: ## Solutions -**Solution 1: Grouping and Subquery** +### Solution 1: Grouping and Subquery We can first group the `MyNumbers` table by `num` and count the number of occurrences of each number. Then, we can use a subquery to find the maximum number among the numbers that appear only once. -**Solution 2: Grouping and `CASE` Expression** - -Similar to Solution 1, we can first group the `MyNumbers` table by `num` and count the number of occurrences of each number. Then, we can use a `CASE` expression to find the numbers that appear only once, sort them in descending order by number, and take the first one. - -### **SQL** - ```sql # Write your MySQL query statement below SELECT MAX(num) AS num @@ -103,6 +97,14 @@ FROM ) AS t; ``` + + +### Solution 2: Grouping and `CASE` Expression + +Similar to Solution 1, we can first group the `MyNumbers` table by `num` and count the number of occurrences of each number. Then, we can use a `CASE` expression to find the numbers that appear only once, sort them in descending order by number, and take the first one. + + + ```sql # Write your MySQL query statement below SELECT @@ -117,3 +119,5 @@ LIMIT 1; ``` + + diff --git a/solution/0600-0699/0620.Not Boring Movies/README.md b/solution/0600-0699/0620.Not Boring Movies/README.md index 698705e286882..a3cd9c1e5dcc0 100644 --- a/solution/0600-0699/0620.Not Boring Movies/README.md +++ b/solution/0600-0699/0620.Not Boring Movies/README.md @@ -58,16 +58,12 @@ id 是该表的主键(具有唯一值的列)。 ## 解法 - - -**方法一:条件筛选 + 排序** +### 方法一:条件筛选 + 排序 我们可以使用 `WHERE` 子句筛选出 `description` 不为 `boring`,并且 `id` 为奇数的记录,然后使用 `ORDER BY` 子句对结果按照 `rating` 降序排序。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT * @@ -77,3 +73,5 @@ ORDER BY 4 DESC; ``` + + diff --git a/solution/0600-0699/0620.Not Boring Movies/README_EN.md b/solution/0600-0699/0620.Not Boring Movies/README_EN.md index fb69a267f1daa..a7699e1102f15 100644 --- a/solution/0600-0699/0620.Not Boring Movies/README_EN.md +++ b/solution/0600-0699/0620.Not Boring Movies/README_EN.md @@ -56,14 +56,12 @@ We have three movies with odd-numbered IDs: 1, 3, and 5. The movie with ID = 3 i ## Solutions -**Solution 1: Conditional Filtering + Sorting** +### Solution 1: Conditional Filtering + Sorting We can use the `WHERE` clause to filter out the records where `description` is not `boring` and `id` is odd, and then use the `ORDER BY` clause to sort the result in descending order by `rating`. -### **SQL** - ```sql # Write your MySQL query statement below SELECT * @@ -73,3 +71,5 @@ ORDER BY 4 DESC; ``` + + diff --git a/solution/0600-0699/0621.Task Scheduler/README.md b/solution/0600-0699/0621.Task Scheduler/README.md index d219b1f6ec551..8aab024556ccc 100644 --- a/solution/0600-0699/0621.Task Scheduler/README.md +++ b/solution/0600-0699/0621.Task Scheduler/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:贪心 + 构造** +### 方法一:贪心 + 构造 不妨设 $m$ 是任务的个数,统计每种任务出现的次数,记录在数组 `cnt` 中。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: @@ -83,10 +77,6 @@ class Solution: return max(len(tasks), (x - 1) * (n + 1) + s) ``` -### **Java** - - - ```java class Solution { public int leastInterval(char[] tasks, int n) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func leastInterval(tasks []byte, n int) int { cnt := make([]int, 26) @@ -151,8 +137,6 @@ func leastInterval(tasks []byte, n int) int { } ``` -### **C#** - ```cs public class Solution { public int LeastInterval(char[] tasks, int n) { @@ -171,10 +155,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0621.Task Scheduler/README_EN.md b/solution/0600-0699/0621.Task Scheduler/README_EN.md index 343bd845471e3..43990cbc49125 100644 --- a/solution/0600-0699/0621.Task Scheduler/README_EN.md +++ b/solution/0600-0699/0621.Task Scheduler/README_EN.md @@ -55,9 +55,9 @@ A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return max(len(tasks), (x - 1) * (n + 1) + s) ``` -### **Java** - ```java class Solution { public int leastInterval(char[] tasks, int n) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func leastInterval(tasks []byte, n int) int { cnt := make([]int, 26) @@ -134,8 +128,6 @@ func leastInterval(tasks []byte, n int) int { } ``` -### **C#** - ```cs public class Solution { public int LeastInterval(char[] tasks, int n) { @@ -154,10 +146,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0622.Design Circular Queue/README.md b/solution/0600-0699/0622.Design Circular Queue/README.md index 41d5fed99acf2..1b3ff8a19b4f8 100644 --- a/solution/0600-0699/0622.Design Circular Queue/README.md +++ b/solution/0600-0699/0622.Design Circular Queue/README.md @@ -49,16 +49,10 @@ circularQueue.Rear();  // 返回 4 ## 解法 - - -“循环数组”实现。 +### 方法一 -### **Python3** - - - ```python class MyCircularQueue: def __init__(self, k: int): @@ -108,10 +102,6 @@ class MyCircularQueue: # param_6 = obj.isFull() ``` -### **Java** - - - ```java class MyCircularQueue { private int[] q; @@ -179,8 +169,6 @@ class MyCircularQueue { */ ``` -### **C++** - ```cpp class MyCircularQueue { private: @@ -243,8 +231,6 @@ public: */ ``` -### **Go** - ```go type MyCircularQueue struct { front int @@ -312,8 +298,6 @@ func (this *MyCircularQueue) IsFull() bool { */ ``` -### **TypeScript** - ```ts class MyCircularQueue { private queue: number[]; @@ -380,8 +364,6 @@ class MyCircularQueue { */ ``` -### **Rust** - ```rust struct MyCircularQueue { queue: Vec, @@ -455,10 +437,6 @@ impl MyCircularQueue { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0622.Design Circular Queue/README_EN.md b/solution/0600-0699/0622.Design Circular Queue/README_EN.md index b5c2f2ff632d1..f8abcc4242d9c 100644 --- a/solution/0600-0699/0622.Design Circular Queue/README_EN.md +++ b/solution/0600-0699/0622.Design Circular Queue/README_EN.md @@ -56,9 +56,9 @@ myCircularQueue.Rear(); // return 4 ## Solutions - +### Solution 1 -### **Python3** + ```python class MyCircularQueue: @@ -109,8 +109,6 @@ class MyCircularQueue: # param_6 = obj.isFull() ``` -### **Java** - ```java class MyCircularQueue { private int[] q; @@ -178,8 +176,6 @@ class MyCircularQueue { */ ``` -### **C++** - ```cpp class MyCircularQueue { private: @@ -242,8 +238,6 @@ public: */ ``` -### **Go** - ```go type MyCircularQueue struct { front int @@ -311,8 +305,6 @@ func (this *MyCircularQueue) IsFull() bool { */ ``` -### **TypeScript** - ```ts class MyCircularQueue { private queue: number[]; @@ -379,8 +371,6 @@ class MyCircularQueue { */ ``` -### **Rust** - ```rust struct MyCircularQueue { queue: Vec, @@ -454,10 +444,6 @@ impl MyCircularQueue { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0623.Add One Row to Tree/README.md b/solution/0600-0699/0623.Add One Row to Tree/README.md index f12a93743c1f5..f770b33500003 100644 --- a/solution/0600-0699/0623.Add One Row to Tree/README.md +++ b/solution/0600-0699/0623.Add One Row to Tree/README.md @@ -52,18 +52,10 @@ ## 解法 - - -**方法一:DFS** - -**方法二:BFS** +### 方法一:DFS -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -91,39 +83,6 @@ class Solution: return root ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def addOneRow( - self, root: Optional[TreeNode], val: int, depth: int - ) -> Optional[TreeNode]: - if depth == 1: - return TreeNode(val, root) - q = deque([root]) - i = 0 - while q: - i += 1 - for _ in range(len(q)): - node = q.popleft() - if node.left: - q.append(node.left) - if node.right: - q.append(node.right) - if i == depth - 1: - node.left = TreeNode(val, node.left, None) - node.right = TreeNode(val, None, node.right) - return root -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -171,6 +130,148 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int val; + int depth; + + TreeNode* addOneRow(TreeNode* root, int val, int depth) { + if (depth == 1) return new TreeNode(val, root, nullptr); + this->val = val; + this->depth = depth; + dfs(root, 1); + return root; + } + + void dfs(TreeNode* root, int d) { + if (!root) return; + if (d == depth - 1) { + auto l = new TreeNode(val, root->left, nullptr); + auto r = new TreeNode(val, nullptr, root->right); + root->left = l; + root->right = r; + return; + } + dfs(root->left, d + 1); + dfs(root->right, d + 1); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func addOneRow(root *TreeNode, val int, depth int) *TreeNode { + if depth == 1 { + return &TreeNode{Val: val, Left: root} + } + var dfs func(root *TreeNode, d int) + dfs = func(root *TreeNode, d int) { + if root == nil { + return + } + if d == depth-1 { + l, r := &TreeNode{Val: val, Left: root.Left}, &TreeNode{Val: val, Right: root.Right} + root.Left, root.Right = l, r + return + } + dfs(root.Left, d+1) + dfs(root.Right, d+1) + } + dfs(root, 1) + return root +} +``` + +```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 addOneRow(root: TreeNode | null, val: number, depth: number): TreeNode | null { + function dfs(root, d) { + if (!root) { + return; + } + if (d == depth - 1) { + root.left = new TreeNode(val, root.left, null); + root.right = new TreeNode(val, null, root.right); + return; + } + dfs(root.left, d + 1); + dfs(root.right, d + 1); + } + if (depth == 1) { + return new TreeNode(val, root); + } + dfs(root, 1); + return root; +} +``` + + + +### 方法二:BFS + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def addOneRow( + self, root: Optional[TreeNode], val: int, depth: int + ) -> Optional[TreeNode]: + if depth == 1: + return TreeNode(val, root) + q = deque([root]) + i = 0 + while q: + i += 1 + for _ in range(len(q)): + node = q.popleft() + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + if i == depth - 1: + node.left = TreeNode(val, node.left, None) + node.right = TreeNode(val, None, node.right) + return root +``` + ```java /** * Definition for a binary tree node. @@ -216,48 +317,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int val; - int depth; - - TreeNode* addOneRow(TreeNode* root, int val, int depth) { - if (depth == 1) return new TreeNode(val, root, nullptr); - this->val = val; - this->depth = depth; - dfs(root, 1); - return root; - } - - void dfs(TreeNode* root, int d) { - if (!root) return; - if (d == depth - 1) { - auto l = new TreeNode(val, root->left, nullptr); - auto r = new TreeNode(val, nullptr, root->right); - root->left = l; - root->right = r; - return; - } - dfs(root->left, d + 1); - dfs(root->right, d + 1); - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -294,39 +353,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func addOneRow(root *TreeNode, val int, depth int) *TreeNode { - if depth == 1 { - return &TreeNode{Val: val, Left: root} - } - var dfs func(root *TreeNode, d int) - dfs = func(root *TreeNode, d int) { - if root == nil { - return - } - if d == depth-1 { - l, r := &TreeNode{Val: val, Left: root.Left}, &TreeNode{Val: val, Right: root.Right} - root.Left, root.Right = l, r - return - } - dfs(root.Left, d+1) - dfs(root.Right, d+1) - } - dfs(root, 1) - return root -} -``` - ```go /** * Definition for a binary tree node. @@ -363,44 +389,6 @@ func addOneRow(root *TreeNode, val int, depth int) *TreeNode { } ``` -### **TypeScript** - -```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 addOneRow(root: TreeNode | null, val: number, depth: number): TreeNode | null { - function dfs(root, d) { - if (!root) { - return; - } - if (d == depth - 1) { - root.left = new TreeNode(val, root.left, null); - root.right = new TreeNode(val, null, root.right); - return; - } - dfs(root.left, d + 1); - dfs(root.right, d + 1); - } - if (depth == 1) { - return new TreeNode(val, root); - } - dfs(root, 1); - return root; -} -``` - ```ts /** * Definition for a binary tree node. @@ -438,10 +426,6 @@ function addOneRow(root: TreeNode | null, val: number, depth: number): TreeNode } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0623.Add One Row to Tree/README_EN.md b/solution/0600-0699/0623.Add One Row to Tree/README_EN.md index d30cd07c5f31e..ea5c814a55c80 100644 --- a/solution/0600-0699/0623.Add One Row to Tree/README_EN.md +++ b/solution/0600-0699/0623.Add One Row to Tree/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -76,37 +76,6 @@ class Solution: return root ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def addOneRow( - self, root: Optional[TreeNode], val: int, depth: int - ) -> Optional[TreeNode]: - if depth == 1: - return TreeNode(val, root) - q = deque([root]) - i = 0 - while q: - i += 1 - for _ in range(len(q)): - node = q.popleft() - if node.left: - q.append(node.left) - if node.right: - q.append(node.right) - if i == depth - 1: - node.left = TreeNode(val, node.left, None) - node.right = TreeNode(val, None, node.right) - return root -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -154,6 +123,148 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int val; + int depth; + + TreeNode* addOneRow(TreeNode* root, int val, int depth) { + if (depth == 1) return new TreeNode(val, root, nullptr); + this->val = val; + this->depth = depth; + dfs(root, 1); + return root; + } + + void dfs(TreeNode* root, int d) { + if (!root) return; + if (d == depth - 1) { + auto l = new TreeNode(val, root->left, nullptr); + auto r = new TreeNode(val, nullptr, root->right); + root->left = l; + root->right = r; + return; + } + dfs(root->left, d + 1); + dfs(root->right, d + 1); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func addOneRow(root *TreeNode, val int, depth int) *TreeNode { + if depth == 1 { + return &TreeNode{Val: val, Left: root} + } + var dfs func(root *TreeNode, d int) + dfs = func(root *TreeNode, d int) { + if root == nil { + return + } + if d == depth-1 { + l, r := &TreeNode{Val: val, Left: root.Left}, &TreeNode{Val: val, Right: root.Right} + root.Left, root.Right = l, r + return + } + dfs(root.Left, d+1) + dfs(root.Right, d+1) + } + dfs(root, 1) + return root +} +``` + +```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 addOneRow(root: TreeNode | null, val: number, depth: number): TreeNode | null { + function dfs(root, d) { + if (!root) { + return; + } + if (d == depth - 1) { + root.left = new TreeNode(val, root.left, null); + root.right = new TreeNode(val, null, root.right); + return; + } + dfs(root.left, d + 1); + dfs(root.right, d + 1); + } + if (depth == 1) { + return new TreeNode(val, root); + } + dfs(root, 1); + return root; +} +``` + + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def addOneRow( + self, root: Optional[TreeNode], val: int, depth: int + ) -> Optional[TreeNode]: + if depth == 1: + return TreeNode(val, root) + q = deque([root]) + i = 0 + while q: + i += 1 + for _ in range(len(q)): + node = q.popleft() + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + if i == depth - 1: + node.left = TreeNode(val, node.left, None) + node.right = TreeNode(val, None, node.right) + return root +``` + ```java /** * Definition for a binary tree node. @@ -199,48 +310,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int val; - int depth; - - TreeNode* addOneRow(TreeNode* root, int val, int depth) { - if (depth == 1) return new TreeNode(val, root, nullptr); - this->val = val; - this->depth = depth; - dfs(root, 1); - return root; - } - - void dfs(TreeNode* root, int d) { - if (!root) return; - if (d == depth - 1) { - auto l = new TreeNode(val, root->left, nullptr); - auto r = new TreeNode(val, nullptr, root->right); - root->left = l; - root->right = r; - return; - } - dfs(root->left, d + 1); - dfs(root->right, d + 1); - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -277,39 +346,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func addOneRow(root *TreeNode, val int, depth int) *TreeNode { - if depth == 1 { - return &TreeNode{Val: val, Left: root} - } - var dfs func(root *TreeNode, d int) - dfs = func(root *TreeNode, d int) { - if root == nil { - return - } - if d == depth-1 { - l, r := &TreeNode{Val: val, Left: root.Left}, &TreeNode{Val: val, Right: root.Right} - root.Left, root.Right = l, r - return - } - dfs(root.Left, d+1) - dfs(root.Right, d+1) - } - dfs(root, 1) - return root -} -``` - ```go /** * Definition for a binary tree node. @@ -346,44 +382,6 @@ func addOneRow(root *TreeNode, val int, depth int) *TreeNode { } ``` -### **TypeScript** - -```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 addOneRow(root: TreeNode | null, val: number, depth: number): TreeNode | null { - function dfs(root, d) { - if (!root) { - return; - } - if (d == depth - 1) { - root.left = new TreeNode(val, root.left, null); - root.right = new TreeNode(val, null, root.right); - return; - } - dfs(root.left, d + 1); - dfs(root.right, d + 1); - } - if (depth == 1) { - return new TreeNode(val, root); - } - dfs(root, 1); - return root; -} -``` - ```ts /** * Definition for a binary tree node. @@ -421,10 +419,6 @@ function addOneRow(root: TreeNode | null, val: number, depth: number): TreeNode } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0624.Maximum Distance in Arrays/README.md b/solution/0600-0699/0624.Maximum Distance in Arrays/README.md index 15dcf4daff40e..bf2ecd725f296 100644 --- a/solution/0600-0699/0624.Maximum Distance in Arrays/README.md +++ b/solution/0600-0699/0624.Maximum Distance in Arrays/README.md @@ -33,9 +33,7 @@ ## 解法 - - -**方法一:维护最大值和最小值** +### 方法一:维护最大值和最小值 我们注意到,最大距离一定是两个数组中的一个最大值和另一个最小值之间的距离。因此,我们可以维护两个变量,分别表示当前数组中的最大值和最小值,然后遍历数组,更新最大距离,同时更新最大值和最小值。 @@ -45,10 +43,6 @@ -### **Python3** - - - ```python class Solution: def maxDistance(self, arrays: List[List[int]]) -> int: @@ -62,10 +56,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxDistance(List> arrays) { @@ -85,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +93,6 @@ public: }; ``` -### **Go** - ```go func maxDistance(arrays [][]int) (ans int) { mi, mx := arrays[0][0], arrays[0][len(arrays[0])-1] @@ -127,10 +113,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0624.Maximum Distance in Arrays/README_EN.md b/solution/0600-0699/0624.Maximum Distance in Arrays/README_EN.md index 9e983bf14a588..3732f6c9529c1 100644 --- a/solution/0600-0699/0624.Maximum Distance in Arrays/README_EN.md +++ b/solution/0600-0699/0624.Maximum Distance in Arrays/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxDistance(List> arrays) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +94,6 @@ public: }; ``` -### **Go** - ```go func maxDistance(arrays [][]int) (ans int) { mi, mx := arrays[0][0], arrays[0][len(arrays[0])-1] @@ -120,10 +114,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0625.Minimum Factorization/README.md b/solution/0600-0699/0625.Minimum Factorization/README.md index 4dd61d3845271..6006e2f6bc172 100644 --- a/solution/0600-0699/0625.Minimum Factorization/README.md +++ b/solution/0600-0699/0625.Minimum Factorization/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:贪心 + 因式分解** +### 方法一:贪心 + 因式分解 我们先判断 $num$ 是否小于 $2$,如果是,直接返回 $num$。然后从 $9$ 开始,尽可能多地将数字分解为 $9$,然后分解为 $8$,以此类推,直到分解为 $2$。如果最后剩下的数字不是 $1$,或者结果超过了 $2^{31} - 1$,则返回 $0$。否则,我们返回结果。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def smallestFactorization(self, num: int) -> int: @@ -70,10 +64,6 @@ class Solution: return ans if num < 2 and ans <= 2**31 - 1 else 0 ``` -### **Java** - - - ```java class Solution { public int smallestFactorization(int num) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func smallestFactorization(num int) int { if num < 2 { @@ -143,10 +129,6 @@ func smallestFactorization(num int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0625.Minimum Factorization/README_EN.md b/solution/0600-0699/0625.Minimum Factorization/README_EN.md index 5a8f1fa47076e..b2234ecaeeb0c 100644 --- a/solution/0600-0699/0625.Minimum Factorization/README_EN.md +++ b/solution/0600-0699/0625.Minimum Factorization/README_EN.md @@ -23,9 +23,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -41,8 +41,6 @@ class Solution: return ans if num < 2 and ans <= 2**31 - 1 else 0 ``` -### **Java** - ```java class Solution { public int smallestFactorization(int num) { @@ -64,8 +62,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -88,8 +84,6 @@ public: }; ``` -### **Go** - ```go func smallestFactorization(num int) int { if num < 2 { @@ -112,10 +106,6 @@ func smallestFactorization(num int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0626.Exchange Seats/README.md b/solution/0600-0699/0626.Exchange Seats/README.md index 74a4392ede2a8..2bd19ba71cfb0 100644 --- a/solution/0600-0699/0626.Exchange Seats/README.md +++ b/solution/0600-0699/0626.Exchange Seats/README.md @@ -59,12 +59,10 @@ Seat 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT s1.id, COALESCE(s2.student, s1.student) AS student @@ -74,6 +72,12 @@ FROM ORDER BY 1; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below SELECT @@ -90,6 +94,12 @@ FROM Seat ORDER BY 1; ``` + + +### 方法三 + + + ```sql # Write your MySQL query statement below SELECT @@ -98,6 +108,12 @@ SELECT FROM Seat; ``` + + +### 方法四 + + + ```sql # Write your MySQL query statement below SELECT @@ -112,3 +128,5 @@ ORDER BY 1; ``` + + diff --git a/solution/0600-0699/0626.Exchange Seats/README_EN.md b/solution/0600-0699/0626.Exchange Seats/README_EN.md index 1d358fa983b60..521a55d7c694d 100644 --- a/solution/0600-0699/0626.Exchange Seats/README_EN.md +++ b/solution/0600-0699/0626.Exchange Seats/README_EN.md @@ -57,9 +57,9 @@ Note that if the number of students is odd, there is no need to change the last ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -70,6 +70,12 @@ FROM ORDER BY 1; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below SELECT @@ -86,6 +92,12 @@ FROM Seat ORDER BY 1; ``` + + +### Solution 3 + + + ```sql # Write your MySQL query statement below SELECT @@ -94,6 +106,12 @@ SELECT FROM Seat; ``` + + +### Solution 4 + + + ```sql # Write your MySQL query statement below SELECT @@ -108,3 +126,5 @@ ORDER BY 1; ``` + + diff --git a/solution/0600-0699/0627.Swap Salary/README.md b/solution/0600-0699/0627.Swap Salary/README.md index f700b7450ebdd..d1526e5449282 100644 --- a/solution/0600-0699/0627.Swap Salary/README.md +++ b/solution/0600-0699/0627.Swap Salary/README.md @@ -64,12 +64,10 @@ Salary 表: ## 解法 - +### 方法一 -### **SQL** - ```sql UPDATE salary SET sex = CASE sex @@ -78,6 +76,12 @@ SET sex = CASE sex END; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below UPDATE Salary @@ -85,3 +89,5 @@ SET sex = IF(sex = 'f', 'm', 'f'); ``` + + diff --git a/solution/0600-0699/0627.Swap Salary/README_EN.md b/solution/0600-0699/0627.Swap Salary/README_EN.md index d761752363b0c..51c0604971369 100644 --- a/solution/0600-0699/0627.Swap Salary/README_EN.md +++ b/solution/0600-0699/0627.Swap Salary/README_EN.md @@ -58,9 +58,9 @@ Salary table: ## Solutions - +### Solution 1 -### **SQL** + ```sql UPDATE salary @@ -70,6 +70,12 @@ SET sex = CASE sex END; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below UPDATE Salary @@ -77,3 +83,5 @@ SET sex = IF(sex = 'f', 'm', 'f'); ``` + + diff --git a/solution/0600-0699/0628.Maximum Product of Three Numbers/README.md b/solution/0600-0699/0628.Maximum Product of Three Numbers/README.md index e664fb8931555..581fc0a8a45bf 100644 --- a/solution/0600-0699/0628.Maximum Product of Three Numbers/README.md +++ b/solution/0600-0699/0628.Maximum Product of Three Numbers/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:排序 + 分类讨论** +### 方法一:排序 + 分类讨论 我们先对数组 $nums$ 进行排序,接下来分两种情况讨论: @@ -55,20 +53,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 $nums$ 的长度。 -**方法二:一次遍历** - -我们可以不用对数组进行排序,而是维护五个变量,其中 $mi1$ 和 $mi2$ 表示数组中最小的两个数,而 $mx1$、$mx2$ 和 $mx3$ 表示数组中最大的三个数。 - -最后返回 $max(mi1 \times mi2 \times mx1, mx1 \times mx2 \times mx3)$ 即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def maximumProduct(self, nums: List[int]) -> int: @@ -78,18 +64,6 @@ class Solution: return max(a, b) ``` -```python -class Solution: - def maximumProduct(self, nums: List[int]) -> int: - top3 = nlargest(3, nums) - bottom2 = nlargest(2, nums, key=lambda x: -x) - return max(top3[0] * top3[1] * top3[2], top3[0] * bottom2[0] * bottom2[1]) -``` - -### **Java** - - - ```java class Solution { public int maximumProduct(int[] nums) { @@ -102,6 +76,62 @@ class Solution { } ``` +```cpp +class Solution { +public: + int maximumProduct(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + int a = nums[n - 1] * nums[n - 2] * nums[n - 3]; + int b = nums[n - 1] * nums[0] * nums[1]; + return max(a, b); + } +}; +``` + +```go +func maximumProduct(nums []int) int { + sort.Ints(nums) + n := len(nums) + a := nums[n-1] * nums[n-2] * nums[n-3] + b := nums[n-1] * nums[0] * nums[1] + if a > b { + return a + } + return b +} +``` + +```ts +function maximumProduct(nums: number[]): number { + nums.sort((a, b) => a - b); + const n = nums.length; + const a = nums[n - 1] * nums[n - 2] * nums[n - 3]; + const b = nums[n - 1] * nums[0] * nums[1]; + return Math.max(a, b); +} +``` + + + +### 方法二:一次遍历 + +我们可以不用对数组进行排序,而是维护五个变量,其中 $mi1$ 和 $mi2$ 表示数组中最小的两个数,而 $mx1$、$mx2$ 和 $mx3$ 表示数组中最大的三个数。 + +最后返回 $max(mi1 \times mi2 \times mx1, mx1 \times mx2 \times mx3)$ 即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def maximumProduct(self, nums: List[int]) -> int: + top3 = nlargest(3, nums) + bottom2 = nlargest(2, nums, key=lambda x: -x) + return max(top3[0] * top3[1] * top3[2], top3[0] * bottom2[0] * bottom2[1]) +``` + ```java class Solution { public int maximumProduct(int[] nums) { @@ -131,21 +161,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maximumProduct(vector& nums) { - sort(nums.begin(), nums.end()); - int n = nums.size(); - int a = nums[n - 1] * nums[n - 2] * nums[n - 3]; - int b = nums[n - 1] * nums[0] * nums[1]; - return max(a, b); - } -}; -``` - ```cpp class Solution { public: @@ -176,21 +191,6 @@ public: }; ``` -### **Go** - -```go -func maximumProduct(nums []int) int { - sort.Ints(nums) - n := len(nums) - a := nums[n-1] * nums[n-2] * nums[n-3] - b := nums[n-1] * nums[0] * nums[1] - if a > b { - return a - } - return b -} -``` - ```go func maximumProduct(nums []int) int { const inf = 1 << 30 @@ -214,18 +214,6 @@ func maximumProduct(nums []int) int { } ``` -### **TypeScript** - -```ts -function maximumProduct(nums: number[]): number { - nums.sort((a, b) => a - b); - const n = nums.length; - const a = nums[n - 1] * nums[n - 2] * nums[n - 3]; - const b = nums[n - 1] * nums[0] * nums[1]; - return Math.max(a, b); -} -``` - ```ts function maximumProduct(nums: number[]): number { const inf = 1 << 30; @@ -256,10 +244,6 @@ function maximumProduct(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0628.Maximum Product of Three Numbers/README_EN.md b/solution/0600-0699/0628.Maximum Product of Three Numbers/README_EN.md index 170e723043d7b..e2294f4d07574 100644 --- a/solution/0600-0699/0628.Maximum Product of Three Numbers/README_EN.md +++ b/solution/0600-0699/0628.Maximum Product of Three Numbers/README_EN.md @@ -27,9 +27,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -40,16 +40,6 @@ class Solution: return max(a, b) ``` -```python -class Solution: - def maximumProduct(self, nums: List[int]) -> int: - top3 = nlargest(3, nums) - bottom2 = nlargest(2, nums, key=lambda x: -x) - return max(top3[0] * top3[1] * top3[2], top3[0] * bottom2[0] * bottom2[1]) -``` - -### **Java** - ```java class Solution { public int maximumProduct(int[] nums) { @@ -62,6 +52,56 @@ class Solution { } ``` +```cpp +class Solution { +public: + int maximumProduct(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + int a = nums[n - 1] * nums[n - 2] * nums[n - 3]; + int b = nums[n - 1] * nums[0] * nums[1]; + return max(a, b); + } +}; +``` + +```go +func maximumProduct(nums []int) int { + sort.Ints(nums) + n := len(nums) + a := nums[n-1] * nums[n-2] * nums[n-3] + b := nums[n-1] * nums[0] * nums[1] + if a > b { + return a + } + return b +} +``` + +```ts +function maximumProduct(nums: number[]): number { + nums.sort((a, b) => a - b); + const n = nums.length; + const a = nums[n - 1] * nums[n - 2] * nums[n - 3]; + const b = nums[n - 1] * nums[0] * nums[1]; + return Math.max(a, b); +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def maximumProduct(self, nums: List[int]) -> int: + top3 = nlargest(3, nums) + bottom2 = nlargest(2, nums, key=lambda x: -x) + return max(top3[0] * top3[1] * top3[2], top3[0] * bottom2[0] * bottom2[1]) +``` + ```java class Solution { public int maximumProduct(int[] nums) { @@ -91,21 +131,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maximumProduct(vector& nums) { - sort(nums.begin(), nums.end()); - int n = nums.size(); - int a = nums[n - 1] * nums[n - 2] * nums[n - 3]; - int b = nums[n - 1] * nums[0] * nums[1]; - return max(a, b); - } -}; -``` - ```cpp class Solution { public: @@ -136,21 +161,6 @@ public: }; ``` -### **Go** - -```go -func maximumProduct(nums []int) int { - sort.Ints(nums) - n := len(nums) - a := nums[n-1] * nums[n-2] * nums[n-3] - b := nums[n-1] * nums[0] * nums[1] - if a > b { - return a - } - return b -} -``` - ```go func maximumProduct(nums []int) int { const inf = 1 << 30 @@ -174,18 +184,6 @@ func maximumProduct(nums []int) int { } ``` -### **TypeScript** - -```ts -function maximumProduct(nums: number[]): number { - nums.sort((a, b) => a - b); - const n = nums.length; - const a = nums[n - 1] * nums[n - 2] * nums[n - 3]; - const b = nums[n - 1] * nums[0] * nums[1]; - return Math.max(a, b); -} -``` - ```ts function maximumProduct(nums: number[]): number { const inf = 1 << 30; @@ -216,10 +214,6 @@ function maximumProduct(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0629.K Inverse Pairs Array/README.md b/solution/0600-0699/0629.K Inverse Pairs Array/README.md index 4a1d164061ccf..19b490b434773 100644 --- a/solution/0600-0699/0629.K Inverse Pairs Array/README.md +++ b/solution/0600-0699/0629.K Inverse Pairs Array/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:动态规划 + 前缀和** +### 方法一:动态规划 + 前缀和 我们定义 $f[i][j]$ 表示数组长度为 $i$,逆序对数为 $j$ 的数组个数。初始时 $f[0][0] = 1$,其余 $f[i][j] = 0$。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def kInversePairs(self, n: int, k: int) -> int: @@ -83,10 +77,6 @@ class Solution: return f[k] ``` -### **Java** - - - ```java class Solution { public int kInversePairs(int n, int k) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func kInversePairs(n int, k int) int { f := make([]int, k+1) @@ -158,8 +144,6 @@ func kInversePairs(n int, k int) int { } ``` -### **TypeScript** - ```ts function kInversePairs(n: number, k: number): number { const f: number[] = new Array(k + 1).fill(0); @@ -179,10 +163,6 @@ function kInversePairs(n: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0629.K Inverse Pairs Array/README_EN.md b/solution/0600-0699/0629.K Inverse Pairs Array/README_EN.md index 5841bd35548cc..6f902a318bbea 100644 --- a/solution/0600-0699/0629.K Inverse Pairs Array/README_EN.md +++ b/solution/0600-0699/0629.K Inverse Pairs Array/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return f[k] ``` -### **Java** - ```java class Solution { public int kInversePairs(int n, int k) { @@ -77,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +99,6 @@ public: }; ``` -### **Go** - ```go func kInversePairs(n int, k int) int { f := make([]int, k+1) @@ -126,8 +120,6 @@ func kInversePairs(n int, k int) int { } ``` -### **TypeScript** - ```ts function kInversePairs(n: number, k: number): number { const f: number[] = new Array(k + 1).fill(0); @@ -147,10 +139,6 @@ function kInversePairs(n: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0630.Course Schedule III/README.md b/solution/0600-0699/0630.Course Schedule III/README.md index 3277eec5485fb..b9421301a8b57 100644 --- a/solution/0600-0699/0630.Course Schedule III/README.md +++ b/solution/0600-0699/0630.Course Schedule III/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列(大根堆)** +### 方法一:贪心 + 优先队列(大根堆) 我们可以按照课程的结束时间进行升序排序,每次选择结束时间最早的课程进行上课。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def scheduleCourse(self, courses: List[List[int]]) -> int: @@ -83,10 +77,6 @@ class Solution: return len(pq) ``` -### **Java** - - - ```java class Solution { public int scheduleCourse(int[][] courses) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func scheduleCourse(courses [][]int) int { sort.Slice(courses, func(i, j int) bool { return courses[i][1] < courses[j][1] }) @@ -163,8 +149,6 @@ func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) } ``` -### **TypeScript** - ```ts function scheduleCourse(courses: number[][]): number { courses.sort((a, b) => a[1] - b[1]); @@ -181,10 +165,6 @@ function scheduleCourse(courses: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0630.Course Schedule III/README_EN.md b/solution/0600-0699/0630.Course Schedule III/README_EN.md index 5f2c8d2d4ee76..20d2ab48a31b2 100644 --- a/solution/0600-0699/0630.Course Schedule III/README_EN.md +++ b/solution/0600-0699/0630.Course Schedule III/README_EN.md @@ -48,9 +48,9 @@ The 4th course cannot be taken now, since you will finish it on the 3 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return len(pq) ``` -### **Java** - ```java class Solution { public int scheduleCourse(int[][] courses) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func scheduleCourse(courses [][]int) int { sort.Slice(courses, func(i, j int) bool { return courses[i][1] < courses[j][1] }) @@ -144,8 +138,6 @@ func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) } ``` -### **TypeScript** - ```ts function scheduleCourse(courses: number[][]): number { courses.sort((a, b) => a[1] - b[1]); @@ -162,10 +154,6 @@ function scheduleCourse(courses: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0631.Design Excel Sum Formula/README.md b/solution/0600-0699/0631.Design Excel Sum Formula/README.md index 4c6602ebd40cd..01061a6dd97c6 100644 --- a/solution/0600-0699/0631.Design Excel Sum Formula/README.md +++ b/solution/0600-0699/0631.Design Excel Sum Formula/README.md @@ -93,30 +93,4 @@ excel.get(3, "C"); // 返回 6 ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0600-0699/0631.Design Excel Sum Formula/README_EN.md b/solution/0600-0699/0631.Design Excel Sum Formula/README_EN.md index 179657e5ea351..76aa3ff1eff60 100644 --- a/solution/0600-0699/0631.Design Excel Sum Formula/README_EN.md +++ b/solution/0600-0699/0631.Design Excel Sum Formula/README_EN.md @@ -88,24 +88,4 @@ excel.get(3, "C"); // return 6 ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0600-0699/0632.Smallest Range Covering Elements from K Lists/README.md b/solution/0600-0699/0632.Smallest Range Covering Elements from K Lists/README.md index be64e58996ff0..0ae39bc27f62f 100644 --- a/solution/0600-0699/0632.Smallest Range Covering Elements from K Lists/README.md +++ b/solution/0600-0699/0632.Smallest Range Covering Elements from K Lists/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:排序 + 滑动窗口** +### 方法一:排序 + 滑动窗口 将每个数字 $v$ 及其所在的组 $i$,构成数据项 $(v, i)$,存放在一个新的列表或者数组中,记为 `t`。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def smallestRange(self, nums: List[List[int]]) -> List[int]: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] smallestRange(List> nums) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +163,6 @@ public: }; ``` -### **Go** - ```go func smallestRange(nums [][]int) []int { t := [][]int{} @@ -209,8 +195,6 @@ func smallestRange(nums [][]int) []int { } ``` -### **Rust** - ```rust impl Solution { pub fn smallest_range(nums: Vec>) -> Vec { @@ -252,10 +236,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0632.Smallest Range Covering Elements from K Lists/README_EN.md b/solution/0600-0699/0632.Smallest Range Covering Elements from K Lists/README_EN.md index 9e1487bfc94ef..ce417c6a52c96 100644 --- a/solution/0600-0699/0632.Smallest Range Covering Elements from K Lists/README_EN.md +++ b/solution/0600-0699/0632.Smallest Range Covering Elements from K Lists/README_EN.md @@ -40,9 +40,9 @@ List 3: [5, 18, 22, 30], 22 is in range [20,24]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,7 +52,7 @@ class Solution: cnt = Counter() ans = [-inf, inf] j = 0 - for b, v in t: + for i, (b, v) in enumerate(t): cnt[v] += 1 while len(cnt) == len(nums): a = t[j][0] @@ -67,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] smallestRange(List> nums) { @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +149,6 @@ public: }; ``` -### **Go** - ```go func smallestRange(nums [][]int) []int { t := [][]int{} @@ -187,8 +181,6 @@ func smallestRange(nums [][]int) []int { } ``` -### **Rust** - ```rust impl Solution { pub fn smallest_range(nums: Vec>) -> Vec { @@ -230,10 +222,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0633.Sum of Square Numbers/README.md b/solution/0600-0699/0633.Sum of Square Numbers/README.md index 0326b85456c9d..60ee66ec4e1e1 100644 --- a/solution/0600-0699/0633.Sum of Square Numbers/README.md +++ b/solution/0600-0699/0633.Sum of Square Numbers/README.md @@ -35,20 +35,10 @@ ## 解法 - - -![](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0633.Sum%20of%20Square%20Numbers/images/table.png) - -上图为 a,b,c 之间的关系,这题其实就是在这张“表”里查找 c。 - -从表的右上角看,不难发现它类似一棵二叉查找树,所以只需从右上角开始,按照二叉查找树的规律进行搜索。 +### 方法一 -### **Python3** - - - ```python class Solution: def judgeSquareSum(self, c: int) -> bool: @@ -64,10 +54,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean judgeSquareSum(int c) { @@ -88,27 +74,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function judgeSquareSum(c: number): boolean { - let a = 0, - b = Math.floor(Math.sqrt(c)); - while (a <= b) { - let sum = a ** 2 + b ** 2; - if (sum == c) return true; - if (sum < c) { - ++a; - } else { - --b; - } - } - return false; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -127,8 +92,6 @@ public: }; ``` -### **Go** - ```go func judgeSquareSum(c int) bool { a, b := 0, int(math.Sqrt(float64(c))) @@ -147,7 +110,22 @@ func judgeSquareSum(c int) bool { } ``` -### **Rust** +```ts +function judgeSquareSum(c: number): boolean { + let a = 0, + b = Math.floor(Math.sqrt(c)); + while (a <= b) { + let sum = a ** 2 + b ** 2; + if (sum == c) return true; + if (sum < c) { + ++a; + } else { + --b; + } + } + return false; +} +``` ```rust use std::cmp::Ordering; @@ -175,10 +153,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0633.Sum of Square Numbers/README_EN.md b/solution/0600-0699/0633.Sum of Square Numbers/README_EN.md index 51cde72d049f3..b34ebe1e869dd 100644 --- a/solution/0600-0699/0633.Sum of Square Numbers/README_EN.md +++ b/solution/0600-0699/0633.Sum of Square Numbers/README_EN.md @@ -31,16 +31,10 @@ ## Solutions -![](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0633.Sum%20of%20Square%20Numbers/images/table.png) - -The picture above shows the relationship between `a`, `b`, and `c`. This question is actually looking up `c` in this table - -From the upper right corner of the table, it is not difficult to find that it is similar to a binary search tree, so just start from the upper right corner and search according to the law of the binary search tree +### Solution 1 -### **Python3** - ```python class Solution: def judgeSquareSum(self, c: int) -> bool: @@ -56,8 +50,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean judgeSquareSum(int c) { @@ -78,27 +70,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function judgeSquareSum(c: number): boolean { - let a = 0, - b = Math.floor(Math.sqrt(c)); - while (a <= b) { - let sum = a ** 2 + b ** 2; - if (sum == c) return true; - if (sum < c) { - ++a; - } else { - --b; - } - } - return false; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -117,8 +88,6 @@ public: }; ``` -### **Go** - ```go func judgeSquareSum(c int) bool { a, b := 0, int(math.Sqrt(float64(c))) @@ -137,7 +106,22 @@ func judgeSquareSum(c int) bool { } ``` -### **Rust** +```ts +function judgeSquareSum(c: number): boolean { + let a = 0, + b = Math.floor(Math.sqrt(c)); + while (a <= b) { + let sum = a ** 2 + b ** 2; + if (sum == c) return true; + if (sum < c) { + ++a; + } else { + --b; + } + } + return false; +} +``` ```rust use std::cmp::Ordering; @@ -165,10 +149,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0634.Find the Derangement of An Array/README.md b/solution/0600-0699/0634.Find the Derangement of An Array/README.md index 1d8ddf3ca3b5f..c808ff7d26af5 100644 --- a/solution/0600-0699/0634.Find the Derangement of An Array/README.md +++ b/solution/0600-0699/0634.Find the Derangement of An Array/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示长度为 $i$ 的数组的错位排列的数量。初始时 $f[0] = 1$, $f[1] = 0$。答案即为 $f[n]$。 @@ -62,10 +60,6 @@ $$ -### **Python3** - - - ```python class Solution: def findDerangement(self, n: int) -> int: @@ -76,20 +70,6 @@ class Solution: return f[n] ``` -```python -class Solution: - def findDerangement(self, n: int) -> int: - mod = 10**9 + 7 - a, b = 1, 0 - for i in range(2, n + 1): - a, b = b, ((i - 1) * (a + b)) % mod - return b -``` - -### **Java** - - - ```java class Solution { public int findDerangement(int n) { @@ -104,23 +84,6 @@ class Solution { } ``` -```java -class Solution { - public int findDerangement(int n) { - final int mod = (int) 1e9 + 7; - long a = 1, b = 0; - for (int i = 2; i <= n; ++i) { - long c = (i - 1) * (a + b) % mod; - a = b; - b = c; - } - return (int) b; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -137,6 +100,49 @@ public: }; ``` +```go +func findDerangement(n int) int { + f := make([]int, n+1) + f[0] = 1 + const mod = 1e9 + 7 + for i := 2; i <= n; i++ { + f[i] = (i - 1) * (f[i-1] + f[i-2]) % mod + } + return f[n] +} +``` + + + +### 方法二 + + + +```python +class Solution: + def findDerangement(self, n: int) -> int: + mod = 10**9 + 7 + a, b = 1, 0 + for i in range(2, n + 1): + a, b = b, ((i - 1) * (a + b)) % mod + return b +``` + +```java +class Solution { + public int findDerangement(int n) { + final int mod = (int) 1e9 + 7; + long a = 1, b = 0; + for (int i = 2; i <= n; ++i) { + long c = (i - 1) * (a + b) % mod; + a = b; + b = c; + } + return (int) b; + } +} +``` + ```cpp class Solution { public: @@ -153,20 +159,6 @@ public: }; ``` -### **Go** - -```go -func findDerangement(n int) int { - f := make([]int, n+1) - f[0] = 1 - const mod = 1e9 + 7 - for i := 2; i <= n; i++ { - f[i] = (i - 1) * (f[i-1] + f[i-2]) % mod - } - return f[n] -} -``` - ```go func findDerangement(n int) int { a, b := 1, 0 @@ -178,10 +170,6 @@ func findDerangement(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0634.Find the Derangement of An Array/README_EN.md b/solution/0600-0699/0634.Find the Derangement of An Array/README_EN.md index 619976592a0d0..b950998bba5aa 100644 --- a/solution/0600-0699/0634.Find the Derangement of An Array/README_EN.md +++ b/solution/0600-0699/0634.Find the Derangement of An Array/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -47,18 +47,6 @@ class Solution: return f[n] ``` -```python -class Solution: - def findDerangement(self, n: int) -> int: - mod = 10**9 + 7 - a, b = 1, 0 - for i in range(2, n + 1): - a, b = b, ((i - 1) * (a + b)) % mod - return b -``` - -### **Java** - ```java class Solution { public int findDerangement(int n) { @@ -73,23 +61,6 @@ class Solution { } ``` -```java -class Solution { - public int findDerangement(int n) { - final int mod = (int) 1e9 + 7; - long a = 1, b = 0; - for (int i = 2; i <= n; ++i) { - long c = (i - 1) * (a + b) % mod; - a = b; - b = c; - } - return (int) b; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -106,6 +77,49 @@ public: }; ``` +```go +func findDerangement(n int) int { + f := make([]int, n+1) + f[0] = 1 + const mod = 1e9 + 7 + for i := 2; i <= n; i++ { + f[i] = (i - 1) * (f[i-1] + f[i-2]) % mod + } + return f[n] +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def findDerangement(self, n: int) -> int: + mod = 10**9 + 7 + a, b = 1, 0 + for i in range(2, n + 1): + a, b = b, ((i - 1) * (a + b)) % mod + return b +``` + +```java +class Solution { + public int findDerangement(int n) { + final int mod = (int) 1e9 + 7; + long a = 1, b = 0; + for (int i = 2; i <= n; ++i) { + long c = (i - 1) * (a + b) % mod; + a = b; + b = c; + } + return (int) b; + } +} +``` + ```cpp class Solution { public: @@ -122,20 +136,6 @@ public: }; ``` -### **Go** - -```go -func findDerangement(n int) int { - f := make([]int, n+1) - f[0] = 1 - const mod = 1e9 + 7 - for i := 2; i <= n; i++ { - f[i] = (i - 1) * (f[i-1] + f[i-2]) % mod - } - return f[n] -} -``` - ```go func findDerangement(n int) int { a, b := 1, 0 @@ -147,10 +147,6 @@ func findDerangement(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0635.Design Log Storage System/README.md b/solution/0600-0699/0635.Design Log Storage System/README.md index fbbc3d273bb8e..f05295842a5dd 100644 --- a/solution/0600-0699/0635.Design Log Storage System/README.md +++ b/solution/0600-0699/0635.Design Log Storage System/README.md @@ -57,9 +57,7 @@ logSystem.retrieve("2016:01:01:01:01:01", "2017:01:01:23:00:00", "Hour"); ## 解法 - - -**方法一:字符串比较** +### 方法一:字符串比较 将日志的 `id` 和 `timestamp` 作为元组存入数组中,然后在 `retrieve()` 方法中,根据 `granularity` 截取 `start` 和 `end` 的相应部分,然后遍历数组,将符合条件的 `id` 加入结果数组中。 @@ -67,10 +65,6 @@ logSystem.retrieve("2016:01:01:01:01:01", "2017:01:01:23:00:00", "Hour"); -### **Python3** - - - ```python class LogSystem: def __init__(self): @@ -98,10 +92,6 @@ class LogSystem: # param_2 = obj.retrieve(start,end,granularity) ``` -### **Java** - - - ```java class LogSystem { private List logs = new ArrayList<>(); @@ -153,8 +143,6 @@ class Log { */ ``` -### **C++** - ```cpp class LogSystem { public: @@ -198,8 +186,6 @@ private: */ ``` -### **Go** - ```go type LogSystem struct { logs []pair @@ -247,10 +233,6 @@ type pair struct { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0635.Design Log Storage System/README_EN.md b/solution/0600-0699/0635.Design Log Storage System/README_EN.md index ce21d1efa45cf..a684893ab2088 100644 --- a/solution/0600-0699/0635.Design Log Storage System/README_EN.md +++ b/solution/0600-0699/0635.Design Log Storage System/README_EN.md @@ -54,9 +54,9 @@ logSystem.retrieve("2016:01:01:01:01:01", "2017:01:01:23:00:00&qu ## Solutions - +### Solution 1 -### **Python3** + ```python class LogSystem: @@ -85,8 +85,6 @@ class LogSystem: # param_2 = obj.retrieve(start,end,granularity) ``` -### **Java** - ```java class LogSystem { private List logs = new ArrayList<>(); @@ -138,8 +136,6 @@ class Log { */ ``` -### **C++** - ```cpp class LogSystem { public: @@ -183,8 +179,6 @@ private: */ ``` -### **Go** - ```go type LogSystem struct { logs []pair @@ -232,10 +226,6 @@ type pair struct { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0636.Exclusive Time of Functions/README.md b/solution/0600-0699/0636.Exclusive Time of Functions/README.md index 5068602c6433c..aded7b1761197 100644 --- a/solution/0600-0699/0636.Exclusive Time of Functions/README.md +++ b/solution/0600-0699/0636.Exclusive Time of Functions/README.md @@ -86,18 +86,12 @@ ## 解法 - - -**方法一:栈模拟** +### 方法一:栈模拟 时间复杂度 $O(n)$,空间复杂度 $O(n)$。 -### **Python3** - - - ```python class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: @@ -120,10 +114,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] exclusiveTime(int n, List logs) { @@ -151,38 +141,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function exclusiveTime(n: number, logs: string[]): number[] { - const res = new Array(n).fill(0); - const stack: [number, number][] = []; - - for (const log of logs) { - const t = log.split(':'); - const [id, state, time] = [Number(t[0]), t[1], Number(t[2])]; - - if (state === 'start') { - if (stack.length !== 0) { - const pre = stack[stack.length - 1]; - res[pre[0]] += time - pre[1]; - } - stack.push([id, time]); - } else { - const pre = stack.pop(); - res[pre[0]] += time - pre[1] + 1; - if (stack.length !== 0) { - stack[stack.length - 1][1] = time + 1; - } - } - } - - return res; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -210,8 +168,6 @@ public: }; ``` -### **Go** - ```go func exclusiveTime(n int, logs []string) []int { ans := make([]int, n) @@ -238,10 +194,34 @@ func exclusiveTime(n int, logs []string) []int { } ``` -### **...** +```ts +function exclusiveTime(n: number, logs: string[]): number[] { + const res = new Array(n).fill(0); + const stack: [number, number][] = []; -``` + for (const log of logs) { + const t = log.split(':'); + const [id, state, time] = [Number(t[0]), t[1], Number(t[2])]; + if (state === 'start') { + if (stack.length !== 0) { + const pre = stack[stack.length - 1]; + res[pre[0]] += time - pre[1]; + } + stack.push([id, time]); + } else { + const pre = stack.pop(); + res[pre[0]] += time - pre[1] + 1; + if (stack.length !== 0) { + stack[stack.length - 1][1] = time + 1; + } + } + } + + return res; +} ``` + + diff --git a/solution/0600-0699/0636.Exclusive Time of Functions/README_EN.md b/solution/0600-0699/0636.Exclusive Time of Functions/README_EN.md index ab1b2ee870a55..26ffe164540e1 100644 --- a/solution/0600-0699/0636.Exclusive Time of Functions/README_EN.md +++ b/solution/0600-0699/0636.Exclusive Time of Functions/README_EN.md @@ -70,9 +70,9 @@ So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -96,8 +96,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] exclusiveTime(int n, List logs) { @@ -125,38 +123,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function exclusiveTime(n: number, logs: string[]): number[] { - const res = new Array(n).fill(0); - const stack: [number, number][] = []; - - for (const log of logs) { - const t = log.split(':'); - const [id, state, time] = [Number(t[0]), t[1], Number(t[2])]; - - if (state === 'start') { - if (stack.length !== 0) { - const pre = stack[stack.length - 1]; - res[pre[0]] += time - pre[1]; - } - stack.push([id, time]); - } else { - const pre = stack.pop(); - res[pre[0]] += time - pre[1] + 1; - if (stack.length !== 0) { - stack[stack.length - 1][1] = time + 1; - } - } - } - - return res; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -184,8 +150,6 @@ public: }; ``` -### **Go** - ```go func exclusiveTime(n int, logs []string) []int { ans := make([]int, n) @@ -212,10 +176,34 @@ func exclusiveTime(n int, logs []string) []int { } ``` -### **...** +```ts +function exclusiveTime(n: number, logs: string[]): number[] { + const res = new Array(n).fill(0); + const stack: [number, number][] = []; -``` + for (const log of logs) { + const t = log.split(':'); + const [id, state, time] = [Number(t[0]), t[1], Number(t[2])]; + + if (state === 'start') { + if (stack.length !== 0) { + const pre = stack[stack.length - 1]; + res[pre[0]] += time - pre[1]; + } + stack.push([id, time]); + } else { + const pre = stack.pop(); + res[pre[0]] += time - pre[1] + 1; + if (stack.length !== 0) { + stack[stack.length - 1][1] = time + 1; + } + } + } + return res; +} ``` + + diff --git a/solution/0600-0699/0637.Average of Levels in Binary Tree/README.md b/solution/0600-0699/0637.Average of Levels in Binary Tree/README.md index 37a4d0880359c..f6aa017feaa07 100644 --- a/solution/0600-0699/0637.Average of Levels in Binary Tree/README.md +++ b/solution/0600-0699/0637.Average of Levels in Binary Tree/README.md @@ -43,16 +43,10 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -77,35 +71,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: - def dfs(root, i): - if root is None: - return - if len(s) == i: - s.append([root.val, 1]) - else: - s[i][0] += root.val - s[i][1] += 1 - dfs(root.left, i + 1) - dfs(root.right, i + 1) - - s = [] - dfs(root, 0) - return [a / b for a, b in s] -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -147,54 +112,123 @@ class Solution { } ``` -```java +```cpp /** * Definition for a binary tree node. - * public class TreeNode { + * struct TreeNode { * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; */ class Solution { - private List s = new ArrayList<>(); - private List cnt = new ArrayList<>(); - - public List averageOfLevels(TreeNode root) { - dfs(root, 0); - List ans = new ArrayList<>(); - for (int i = 0; i < s.size(); ++i) { - ans.add(s.get(i) * 1.0 / cnt.get(i)); +public: + vector averageOfLevels(TreeNode* root) { + queue q{{root}}; + vector ans; + while (!q.empty()) { + int n = q.size(); + long long s = 0; + for (int i = 0; i < n; ++i) { + root = q.front(); + q.pop(); + s += root->val; + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + ans.push_back(s * 1.0 / n); } return ans; } +}; +``` - private void dfs(TreeNode root, int i) { - if (root == null) { - return; +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func averageOfLevels(root *TreeNode) []float64 { + q := []*TreeNode{root} + ans := []float64{} + for len(q) > 0 { + n := len(q) + s := 0 + for i := 0; i < n; i++ { + root = q[0] + q = q[1:] + s += root.Val + if root.Left != nil { + q = append(q, root.Left) + } + if root.Right != nil { + q = append(q, root.Right) + } + } + ans = append(ans, float64(s)/float64(n)) + } + return ans +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +use std::collections::VecDeque; +impl Solution { + pub fn average_of_levels(root: Option>>) -> Vec { + if root.is_none() { + return Vec::new(); } - if (s.size() == i) { - s.add((long) root.val); - cnt.add(1); - } else { - s.set(i, s.get(i) + root.val); - cnt.set(i, cnt.get(i) + 1); + + let mut q = VecDeque::new(); + q.push_back(Rc::clone(&root.unwrap())); + let mut ans = Vec::new(); + while !q.is_empty() { + let n = q.len(); + let mut sum = 0.0; + for _ in 0..n { + let node = q.pop_front().unwrap(); + sum += node.borrow().val as f64; + if node.borrow().left.is_some() { + q.push_back(Rc::clone(node.borrow().left.as_ref().unwrap())); + } + if node.borrow().right.is_some() { + q.push_back(Rc::clone(node.borrow().right.as_ref().unwrap())); + } + } + ans.push(sum / (n as f64)); } - dfs(root.left, i + 1); - dfs(root.right, i + 1); + ans } } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -230,77 +264,125 @@ var averageOfLevels = function (root) { }; ``` -```js + + +### 方法二 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: + def dfs(root, i): + if root is None: + return + if len(s) == i: + s.append([root.val, 1]) + else: + s[i][0] += root.val + s[i][1] += 1 + dfs(root.left, i + 1) + dfs(root.right, i + 1) + + s = [] + dfs(root, 0) + return [a / b for a, b in s] +``` + +```java /** * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } * } */ -/** - * @param {TreeNode} root - * @return {number[]} - */ -var averageOfLevels = function (root) { - let s = []; - let cnt = []; - function dfs(root, i) { - if (!root) { +class Solution { + private List s = new ArrayList<>(); + private List cnt = new ArrayList<>(); + + public List averageOfLevels(TreeNode root) { + dfs(root, 0); + List ans = new ArrayList<>(); + for (int i = 0; i < s.size(); ++i) { + ans.add(s.get(i) * 1.0 / cnt.get(i)); + } + return ans; + } + + private void dfs(TreeNode root, int i) { + if (root == null) { return; } - if (s.length == i) { - s.push(root.val); - cnt.push(1); + if (s.size() == i) { + s.add((long) root.val); + cnt.add(1); } else { - s[i] += root.val; - cnt[i]++; + s.set(i, s.get(i) + root.val); + cnt.set(i, cnt.get(i) + 1); } dfs(root.left, i + 1); dfs(root.right, i + 1); } - dfs(root, 0); - let ans = []; - for (let i = 0; i < s.length; ++i) { - ans.push(s[i] / cnt[i]); - } - return ans; -}; +} ``` -### **Go** - -```go +```cpp /** * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; */ -func averageOfLevels(root *TreeNode) []float64 { - q := []*TreeNode{root} - ans := []float64{} - for len(q) > 0 { - n := len(q) - s := 0 - for i := 0; i < n; i++ { - root = q[0] - q = q[1:] - s += root.Val - if root.Left != nil { - q = append(q, root.Left) - } - if root.Right != nil { - q = append(q, root.Right) - } - } - ans = append(ans, float64(s)/float64(n)) - } - return ans -} + +using ll = long long; + +class Solution { +public: + vector s; + vector cnt; + + vector averageOfLevels(TreeNode* root) { + dfs(root, 0); + vector ans(s.size()); + for (int i = 0; i < s.size(); ++i) { + ans[i] = (s[i] * 1.0 / cnt[i]); + } + return ans; + } + + void dfs(TreeNode* root, int i) { + if (!root) return; + if (s.size() == i) { + s.push_back(root->val); + cnt.push_back(1); + } else { + s[i] += root->val; + cnt[i]++; + } + dfs(root->left, i + 1); + dfs(root->right, i + 1); + } +}; ``` ```go @@ -339,143 +421,45 @@ func averageOfLevels(root *TreeNode) []float64 { } ``` -### **C++** - -```cpp +```js /** * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } */ -class Solution { -public: - vector averageOfLevels(TreeNode* root) { - queue q{{root}}; - vector ans; - while (!q.empty()) { - int n = q.size(); - long long s = 0; - for (int i = 0; i < n; ++i) { - root = q.front(); - q.pop(); - s += root->val; - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } - ans.push_back(s * 1.0 / n); - } - return ans; - } -}; -``` - -```cpp /** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; + * @param {TreeNode} root + * @return {number[]} */ - -using ll = long long; - -class Solution { -public: - vector s; - vector cnt; - - vector averageOfLevels(TreeNode* root) { - dfs(root, 0); - vector ans(s.size()); - for (int i = 0; i < s.size(); ++i) { - ans[i] = (s[i] * 1.0 / cnt[i]); +var averageOfLevels = function (root) { + let s = []; + let cnt = []; + function dfs(root, i) { + if (!root) { + return; } - return ans; - } - - void dfs(TreeNode* root, int i) { - if (!root) return; - if (s.size() == i) { - s.push_back(root->val); - cnt.push_back(1); + if (s.length == i) { + s.push(root.val); + cnt.push(1); } else { - s[i] += root->val; + s[i] += root.val; cnt[i]++; } - dfs(root->left, i + 1); - dfs(root->right, i + 1); + dfs(root.left, i + 1); + dfs(root.right, i + 1); } -}; -``` - -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -use std::collections::VecDeque; -impl Solution { - pub fn average_of_levels(root: Option>>) -> Vec { - if root.is_none() { - return Vec::new(); - } - - let mut q = VecDeque::new(); - q.push_back(Rc::clone(&root.unwrap())); - let mut ans = Vec::new(); - while !q.is_empty() { - let n = q.len(); - let mut sum = 0.0; - for _ in 0..n { - let node = q.pop_front().unwrap(); - sum += node.borrow().val as f64; - if node.borrow().left.is_some() { - q.push_back(Rc::clone(node.borrow().left.as_ref().unwrap())); - } - if node.borrow().right.is_some() { - q.push_back(Rc::clone(node.borrow().right.as_ref().unwrap())); - } - } - ans.push(sum / (n as f64)); - } - ans + dfs(root, 0); + let ans = []; + for (let i = 0; i < s.length; ++i) { + ans.push(s[i] / cnt[i]); } -} -``` - -### **...** - -``` - + return ans; +}; ``` + + diff --git a/solution/0600-0699/0637.Average of Levels in Binary Tree/README_EN.md b/solution/0600-0699/0637.Average of Levels in Binary Tree/README_EN.md index 41ec84557555a..baa73ac377000 100644 --- a/solution/0600-0699/0637.Average of Levels in Binary Tree/README_EN.md +++ b/solution/0600-0699/0637.Average of Levels in Binary Tree/README_EN.md @@ -33,9 +33,9 @@ Hence return [3, 14.5, 11]. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -61,33 +61,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: - def dfs(root, i): - if root is None: - return - if len(s) == i: - s.append([root.val, 1]) - else: - s[i][0] += root.val - s[i][1] += 1 - dfs(root.left, i + 1) - dfs(root.right, i + 1) - - s = [] - dfs(root, 0) - return [a / b for a, b in s] -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -129,54 +102,123 @@ class Solution { } ``` -```java +```cpp /** * Definition for a binary tree node. - * public class TreeNode { + * struct TreeNode { * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; */ class Solution { - private List s = new ArrayList<>(); - private List cnt = new ArrayList<>(); - - public List averageOfLevels(TreeNode root) { - dfs(root, 0); - List ans = new ArrayList<>(); - for (int i = 0; i < s.size(); ++i) { - ans.add(s.get(i) * 1.0 / cnt.get(i)); +public: + vector averageOfLevels(TreeNode* root) { + queue q{{root}}; + vector ans; + while (!q.empty()) { + int n = q.size(); + long long s = 0; + for (int i = 0; i < n; ++i) { + root = q.front(); + q.pop(); + s += root->val; + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + ans.push_back(s * 1.0 / n); } return ans; } +}; +``` - private void dfs(TreeNode root, int i) { - if (root == null) { - return; +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func averageOfLevels(root *TreeNode) []float64 { + q := []*TreeNode{root} + ans := []float64{} + for len(q) > 0 { + n := len(q) + s := 0 + for i := 0; i < n; i++ { + root = q[0] + q = q[1:] + s += root.Val + if root.Left != nil { + q = append(q, root.Left) + } + if root.Right != nil { + q = append(q, root.Right) + } + } + ans = append(ans, float64(s)/float64(n)) + } + return ans +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +use std::collections::VecDeque; +impl Solution { + pub fn average_of_levels(root: Option>>) -> Vec { + if root.is_none() { + return Vec::new(); } - if (s.size() == i) { - s.add((long) root.val); - cnt.add(1); - } else { - s.set(i, s.get(i) + root.val); - cnt.set(i, cnt.get(i) + 1); + + let mut q = VecDeque::new(); + q.push_back(Rc::clone(&root.unwrap())); + let mut ans = Vec::new(); + while !q.is_empty() { + let n = q.len(); + let mut sum = 0.0; + for _ in 0..n { + let node = q.pop_front().unwrap(); + sum += node.borrow().val as f64; + if node.borrow().left.is_some() { + q.push_back(Rc::clone(node.borrow().left.as_ref().unwrap())); + } + if node.borrow().right.is_some() { + q.push_back(Rc::clone(node.borrow().right.as_ref().unwrap())); + } + } + ans.push(sum / (n as f64)); } - dfs(root.left, i + 1); - dfs(root.right, i + 1); + ans } } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -212,77 +254,125 @@ var averageOfLevels = function (root) { }; ``` -```js + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: + def dfs(root, i): + if root is None: + return + if len(s) == i: + s.append([root.val, 1]) + else: + s[i][0] += root.val + s[i][1] += 1 + dfs(root.left, i + 1) + dfs(root.right, i + 1) + + s = [] + dfs(root, 0) + return [a / b for a, b in s] +``` + +```java /** * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } * } */ -/** - * @param {TreeNode} root - * @return {number[]} - */ -var averageOfLevels = function (root) { - let s = []; - let cnt = []; - function dfs(root, i) { - if (!root) { +class Solution { + private List s = new ArrayList<>(); + private List cnt = new ArrayList<>(); + + public List averageOfLevels(TreeNode root) { + dfs(root, 0); + List ans = new ArrayList<>(); + for (int i = 0; i < s.size(); ++i) { + ans.add(s.get(i) * 1.0 / cnt.get(i)); + } + return ans; + } + + private void dfs(TreeNode root, int i) { + if (root == null) { return; } - if (s.length == i) { - s.push(root.val); - cnt.push(1); + if (s.size() == i) { + s.add((long) root.val); + cnt.add(1); } else { - s[i] += root.val; - cnt[i]++; + s.set(i, s.get(i) + root.val); + cnt.set(i, cnt.get(i) + 1); } dfs(root.left, i + 1); dfs(root.right, i + 1); } - dfs(root, 0); - let ans = []; - for (let i = 0; i < s.length; ++i) { - ans.push(s[i] / cnt[i]); - } - return ans; -}; +} ``` -### **Go** - -```go +```cpp /** * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; */ -func averageOfLevels(root *TreeNode) []float64 { - q := []*TreeNode{root} - ans := []float64{} - for len(q) > 0 { - n := len(q) - s := 0 - for i := 0; i < n; i++ { - root = q[0] - q = q[1:] - s += root.Val - if root.Left != nil { - q = append(q, root.Left) - } - if root.Right != nil { - q = append(q, root.Right) - } - } - ans = append(ans, float64(s)/float64(n)) - } - return ans -} + +using ll = long long; + +class Solution { +public: + vector s; + vector cnt; + + vector averageOfLevels(TreeNode* root) { + dfs(root, 0); + vector ans(s.size()); + for (int i = 0; i < s.size(); ++i) { + ans[i] = (s[i] * 1.0 / cnt[i]); + } + return ans; + } + + void dfs(TreeNode* root, int i) { + if (!root) return; + if (s.size() == i) { + s.push_back(root->val); + cnt.push_back(1); + } else { + s[i] += root->val; + cnt[i]++; + } + dfs(root->left, i + 1); + dfs(root->right, i + 1); + } +}; ``` ```go @@ -321,143 +411,45 @@ func averageOfLevels(root *TreeNode) []float64 { } ``` -### **C++** - -```cpp +```js /** * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } */ -class Solution { -public: - vector averageOfLevels(TreeNode* root) { - queue q{{root}}; - vector ans; - while (!q.empty()) { - int n = q.size(); - long long s = 0; - for (int i = 0; i < n; ++i) { - root = q.front(); - q.pop(); - s += root->val; - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } - ans.push_back(s * 1.0 / n); - } - return ans; - } -}; -``` - -```cpp /** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; + * @param {TreeNode} root + * @return {number[]} */ - -using ll = long long; - -class Solution { -public: - vector s; - vector cnt; - - vector averageOfLevels(TreeNode* root) { - dfs(root, 0); - vector ans(s.size()); - for (int i = 0; i < s.size(); ++i) { - ans[i] = (s[i] * 1.0 / cnt[i]); +var averageOfLevels = function (root) { + let s = []; + let cnt = []; + function dfs(root, i) { + if (!root) { + return; } - return ans; - } - - void dfs(TreeNode* root, int i) { - if (!root) return; - if (s.size() == i) { - s.push_back(root->val); - cnt.push_back(1); + if (s.length == i) { + s.push(root.val); + cnt.push(1); } else { - s[i] += root->val; + s[i] += root.val; cnt[i]++; } - dfs(root->left, i + 1); - dfs(root->right, i + 1); + dfs(root.left, i + 1); + dfs(root.right, i + 1); } -}; -``` - -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -use std::collections::VecDeque; -impl Solution { - pub fn average_of_levels(root: Option>>) -> Vec { - if root.is_none() { - return Vec::new(); - } - - let mut q = VecDeque::new(); - q.push_back(Rc::clone(&root.unwrap())); - let mut ans = Vec::new(); - while !q.is_empty() { - let n = q.len(); - let mut sum = 0.0; - for _ in 0..n { - let node = q.pop_front().unwrap(); - sum += node.borrow().val as f64; - if node.borrow().left.is_some() { - q.push_back(Rc::clone(node.borrow().left.as_ref().unwrap())); - } - if node.borrow().right.is_some() { - q.push_back(Rc::clone(node.borrow().right.as_ref().unwrap())); - } - } - ans.push(sum / (n as f64)); - } - ans + dfs(root, 0); + let ans = []; + for (let i = 0; i < s.length; ++i) { + ans.push(s[i] / cnt[i]); } -} -``` - -### **...** - -``` - + return ans; +}; ``` + + diff --git a/solution/0600-0699/0638.Shopping Offers/README.md b/solution/0600-0699/0638.Shopping Offers/README.md index d5aed52b59490..e23263d2ae49d 100644 --- a/solution/0600-0699/0638.Shopping Offers/README.md +++ b/solution/0600-0699/0638.Shopping Offers/README.md @@ -53,14 +53,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def shoppingOffers( @@ -83,10 +79,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int shoppingOffers( @@ -120,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +140,6 @@ public: }; ``` -### **Go** - ```go func shoppingOffers(price []int, special [][]int, needs []int) int { total := func(price, needs []int) int { @@ -188,10 +176,6 @@ func shoppingOffers(price []int, special [][]int, needs []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0638.Shopping Offers/README_EN.md b/solution/0600-0699/0638.Shopping Offers/README_EN.md index 672f72b89ce97..b401b5e3aa1dd 100644 --- a/solution/0600-0699/0638.Shopping Offers/README_EN.md +++ b/solution/0600-0699/0638.Shopping Offers/README_EN.md @@ -49,9 +49,9 @@ You cannot add more items, though only 9 for 2A ,2B and 1C. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int shoppingOffers( @@ -110,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +136,6 @@ public: }; ``` -### **Go** - ```go func shoppingOffers(price []int, special [][]int, needs []int) int { total := func(price, needs []int) int { @@ -178,10 +172,6 @@ func shoppingOffers(price []int, special [][]int, needs []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0639.Decode Ways II/README.md b/solution/0600-0699/0639.Decode Ways II/README.md index 4e293cc71c9bd..7b5b693d0d8b7 100644 --- a/solution/0600-0699/0639.Decode Ways II/README.md +++ b/solution/0600-0699/0639.Decode Ways II/README.md @@ -72,16 +72,10 @@ ## 解法 - - -只是在 [91. 解码方法](/solution/0000-0099/0091.Decode%20Ways/README.md) 的基础上加了些关于 `*` 的条件判断 +### 方法一 -### **Python3** - - - ```python class Solution: def numDecodings(self, s: str) -> int: @@ -124,10 +118,6 @@ class Solution: return c ``` -### **Java** - - - ```java class Solution { @@ -179,8 +169,6 @@ class Solution { } ``` -### **Go** - ```go const mod int = 1e9 + 7 @@ -226,10 +214,6 @@ func numDecodings(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0639.Decode Ways II/README_EN.md b/solution/0600-0699/0639.Decode Ways II/README_EN.md index 9c696ece15b6a..fbd6653c95eca 100644 --- a/solution/0600-0699/0639.Decode Ways II/README_EN.md +++ b/solution/0600-0699/0639.Decode Ways II/README_EN.md @@ -69,12 +69,10 @@ Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode " ## Solutions -It's just that some conditional judgments about `*` have been added to the [91. Decode Ways](/solution/0000-0099/0091.Decode%20Ways/README_EN.md). +### Solution 1 -### **Python3** - ```python class Solution: def numDecodings(self, s: str) -> int: @@ -117,8 +115,6 @@ class Solution: return c ``` -### **Java** - ```java class Solution { @@ -170,8 +166,6 @@ class Solution { } ``` -### **Go** - ```go const mod int = 1e9 + 7 @@ -217,10 +211,6 @@ func numDecodings(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0640.Solve the Equation/README.md b/solution/0600-0699/0640.Solve the Equation/README.md index 9accc6dda707a..acdea8b1ca560 100644 --- a/solution/0600-0699/0640.Solve the Equation/README.md +++ b/solution/0600-0699/0640.Solve the Equation/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 将方程 $equation$ 按照等号 “=” 切分为左右两个式子,分别算出左右两个式子中 "x" 的系数 $x_i$,以及常数的值 $y_i$。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def solveEquation(self, equation: str) -> str: @@ -96,10 +90,6 @@ class Solution: return f'x={(y2 - y1) // (x1 - x2)}' ``` -### **Java** - - - ```java class Solution { public String solveEquation(String equation) { @@ -139,8 +129,6 @@ class Solution { } ``` -### **Go** - ```go func solveEquation(equation string) string { f := func(s string) []int { @@ -190,8 +178,6 @@ func solveEquation(equation string) string { } ``` -### **TypeScript** - ```ts function solveEquation(equation: string): string { const [left, right] = equation.split('='); @@ -250,10 +236,6 @@ function solveEquation(equation: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0640.Solve the Equation/README_EN.md b/solution/0600-0699/0640.Solve the Equation/README_EN.md index bc5ca8666f166..51f0a853c20c1 100644 --- a/solution/0600-0699/0640.Solve the Equation/README_EN.md +++ b/solution/0600-0699/0640.Solve the Equation/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return f'x={(y2 - y1) // (x1 - x2)}' ``` -### **Java** - ```java class Solution { public String solveEquation(String equation) { @@ -116,8 +114,6 @@ class Solution { } ``` -### **Go** - ```go func solveEquation(equation string) string { f := func(s string) []int { @@ -167,8 +163,6 @@ func solveEquation(equation string) string { } ``` -### **TypeScript** - ```ts function solveEquation(equation: string): string { const [left, right] = equation.split('='); @@ -227,10 +221,6 @@ function solveEquation(equation: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0641.Design Circular Deque/README.md b/solution/0600-0699/0641.Design Circular Deque/README.md index 5e9a503409ad7..bcb24b26a4770 100644 --- a/solution/0600-0699/0641.Design Circular Deque/README.md +++ b/solution/0600-0699/0641.Design Circular Deque/README.md @@ -58,9 +58,7 @@ circularDeque.getFront(); // 返回 4 ## 解法 - - -**方法一:数组** +### 方法一:数组 利用循环数组,实现循环双端队列。 @@ -75,10 +73,6 @@ circularDeque.getFront(); // 返回 4 -### **Python3** - - - ```python class MyCircularDeque: def __init__(self, k: int): @@ -174,10 +168,6 @@ class MyCircularDeque: # param_8 = obj.isFull() ``` -### **Java** - - - ```java class MyCircularDeque { private int[] q; @@ -276,8 +266,6 @@ class MyCircularDeque { */ ``` -### **C++** - ```cpp class MyCircularDeque { public: @@ -361,8 +349,6 @@ public: */ ``` -### **Go** - ```go type MyCircularDeque struct { q []int @@ -451,8 +437,6 @@ func (this *MyCircularDeque) IsFull() bool { */ ``` -### **TypeScript** - ```ts class MyCircularDeque { private vals: number[]; @@ -569,10 +553,6 @@ class MyCircularDeque { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0641.Design Circular Deque/README_EN.md b/solution/0600-0699/0641.Design Circular Deque/README_EN.md index 1b03e8bf51713..0e5699d674071 100644 --- a/solution/0600-0699/0641.Design Circular Deque/README_EN.md +++ b/solution/0600-0699/0641.Design Circular Deque/README_EN.md @@ -54,9 +54,9 @@ myCircularDeque.getFront(); // return 4 ## Solutions - +### Solution 1 -### **Python3** + ```python class MyCircularDeque: @@ -153,8 +153,6 @@ class MyCircularDeque: # param_8 = obj.isFull() ``` -### **Java** - ```java class MyCircularDeque { private int[] q; @@ -253,8 +251,6 @@ class MyCircularDeque { */ ``` -### **C++** - ```cpp class MyCircularDeque { public: @@ -338,8 +334,6 @@ public: */ ``` -### **Go** - ```go type MyCircularDeque struct { q []int @@ -428,8 +422,6 @@ func (this *MyCircularDeque) IsFull() bool { */ ``` -### **TypeScript** - ```ts class MyCircularDeque { private vals: number[]; @@ -546,10 +538,6 @@ class MyCircularDeque { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0642.Design Search Autocomplete System/README.md b/solution/0600-0699/0642.Design Search Autocomplete System/README.md index 7263eefc2cf4a..8ee5aaca0dd09 100644 --- a/solution/0600-0699/0642.Design Search Autocomplete System/README.md +++ b/solution/0600-0699/0642.Design Search Autocomplete System/README.md @@ -69,16 +69,10 @@ obj.input("#"); // return []. The user finished the input, the sentence "i a" sh ## 解法 - - -**方法一:前缀树 + 排序/优先队列** +### 方法一:前缀树 + 排序/优先队列 -### **Python3** - - - ```python class Trie: def __init__(self): @@ -143,10 +137,6 @@ class AutocompleteSystem: # param_1 = obj.input(c) ``` -### **Java** - - - ```java class Trie { Trie[] children = new Trie[27]; @@ -234,10 +224,6 @@ class AutocompleteSystem { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0642.Design Search Autocomplete System/README_EN.md b/solution/0600-0699/0642.Design Search Autocomplete System/README_EN.md index 5af30b1047e14..119d171b1a9fc 100644 --- a/solution/0600-0699/0642.Design Search Autocomplete System/README_EN.md +++ b/solution/0600-0699/0642.Design Search Autocomplete System/README_EN.md @@ -65,9 +65,9 @@ obj.input("#"); // return []. The user finished the input, the sentenc ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -133,8 +133,6 @@ class AutocompleteSystem: # param_1 = obj.input(c) ``` -### **Java** - ```java class Trie { Trie[] children = new Trie[27]; @@ -222,10 +220,6 @@ class AutocompleteSystem { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0643.Maximum Average Subarray I/README.md b/solution/0600-0699/0643.Maximum Average Subarray I/README.md index 80e89d16787b7..f18cdc174690d 100644 --- a/solution/0600-0699/0643.Maximum Average Subarray I/README.md +++ b/solution/0600-0699/0643.Maximum Average Subarray I/README.md @@ -41,16 +41,10 @@ ## 解法 - - -滑动窗口。 +### 方法一 -### **Python3** - - - ```python class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: @@ -62,10 +56,6 @@ class Solution: return ans / k ``` -### **Java** - - - ```java class Solution { public double findMaxAverage(int[] nums, int k) { @@ -83,8 +73,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function findMaxAverage(nums: number[], k: number): number { let n = nums.length; @@ -103,8 +91,6 @@ function findMaxAverage(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn find_max_average(nums: Vec, k: i32) -> f64 { @@ -121,8 +107,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -145,10 +129,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0643.Maximum Average Subarray I/README_EN.md b/solution/0600-0699/0643.Maximum Average Subarray I/README_EN.md index f7fab0a827363..8e8216a7a00ee 100644 --- a/solution/0600-0699/0643.Maximum Average Subarray I/README_EN.md +++ b/solution/0600-0699/0643.Maximum Average Subarray I/README_EN.md @@ -35,12 +35,10 @@ ## Solutions -Slide window. +### Solution 1 -### **Python3** - ```python class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: @@ -52,8 +50,6 @@ class Solution: return ans / k ``` -### **Java** - ```java class Solution { public double findMaxAverage(int[] nums, int k) { @@ -71,8 +67,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function findMaxAverage(nums: number[], k: number): number { let n = nums.length; @@ -91,8 +85,6 @@ function findMaxAverage(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn find_max_average(nums: Vec, k: i32) -> f64 { @@ -109,8 +101,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -133,10 +123,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0644.Maximum Average Subarray II/README.md b/solution/0600-0699/0644.Maximum Average Subarray II/README.md index add6389c987cd..829b9b9423cbe 100644 --- a/solution/0600-0699/0644.Maximum Average Subarray II/README.md +++ b/solution/0600-0699/0644.Maximum Average Subarray II/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们注意到,如果一个长度大于等于 $k$ 的子数组的平均值为 $v$,那么最大平均数一定大于等于 $v$,否则最大平均数一定小于 $v$。因此,我们可以使用二分查找的方法找出最大平均数。 @@ -84,10 +82,6 @@ $$ -### **Python3** - - - ```python class Solution: def findMaxAverage(self, nums: List[int], k: int) -> float: @@ -115,10 +109,6 @@ class Solution: return l ``` -### **Java** - - - ```java class Solution { public double findMaxAverage(int[] nums, int k) { @@ -162,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -204,8 +192,6 @@ public: }; ``` -### **Go** - ```go func findMaxAverage(nums []int, k int) float64 { eps := 1e-5 @@ -243,8 +229,6 @@ func findMaxAverage(nums []int, k int) float64 { } ``` -### **TypeScript** - ```ts function findMaxAverage(nums: number[], k: number): number { const eps = 1e-5; @@ -279,10 +263,6 @@ function findMaxAverage(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0644.Maximum Average Subarray II/README_EN.md b/solution/0600-0699/0644.Maximum Average Subarray II/README_EN.md index 4dc73dfdbfdca..41f6e8145001a 100644 --- a/solution/0600-0699/0644.Maximum Average Subarray II/README_EN.md +++ b/solution/0600-0699/0644.Maximum Average Subarray II/README_EN.md @@ -40,9 +40,9 @@ Note that we do not consider the subarrays of length < 4. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return l ``` -### **Java** - ```java class Solution { public double findMaxAverage(int[] nums, int k) { @@ -116,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +154,6 @@ public: }; ``` -### **Go** - ```go func findMaxAverage(nums []int, k int) float64 { eps := 1e-5 @@ -197,8 +191,6 @@ func findMaxAverage(nums []int, k int) float64 { } ``` -### **TypeScript** - ```ts function findMaxAverage(nums: number[], k: number): number { const eps = 1e-5; @@ -233,10 +225,6 @@ function findMaxAverage(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0645.Set Mismatch/README.md b/solution/0600-0699/0645.Set Mismatch/README.md index 44716a4689027..cc447c79c6b4b 100644 --- a/solution/0600-0699/0645.Set Mismatch/README.md +++ b/solution/0600-0699/0645.Set Mismatch/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 我们用 $s_1$ 表示 $[1,..n]$ 所有数字的和,用 $s_2$ 表示数组 $nums$ 去重后的数字和,用 $s$ 表示数组 $nums$ 的数字和。 @@ -49,30 +47,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。需要额外的空间对数组去重。 -**方法二:哈希表** - -我们也可以一种更加直观的方法,直接用哈希表 $cnt$ 统计数组 $nums$ 中每个数字出现的次数。 - -接下来遍历 $x \in [1, n]$,如果 $cnt[x] = 2$,那么 $x$ 就是重复的数字,如果 $cnt[x] = 0$,那么 $x$ 就是缺失的数字。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。 - -**方法三:位运算** - -根据异或运算的性质,对于整数 $x$,有 $x \oplus x = 0$ 以及 $x \oplus 0 = x$,因此我们对数组 $nums$ 中的所有元素以及 $i \in [1, n]$ 的所有数字进行异或运算,可以消除出现两次的数字,最终只留下缺失的数字和重复的数字的异或结果,即 $xs = a \oplus b$。 - -由于这两个数字不相等,因此异或结果中至少存在一位为 $1$。我们通过 $lowbit$ 运算找到异或结果中最低位的 $1$,然后将数组 $nums$ 中所有数字以及 $i \in [1, n]$ 的所有数字按照该位是否为 $1$ 分为两组,这样两个数字就被分到了不同的组中。其中一组数字的异或结果为 $a$,另一组数字的异或结果为 $b$。那么这两个数字就是我们要找的答案。 - -接下来我们只需要判断 $a$ 和 $b$ 哪个数字是重复的数字,哪个数字是缺失的数字即可。因此,遍历数组 $nums$,对于遍历到的数字 $x$,如果 $x=a$,那么 $a$ 就是重复的数字,返回 $[a, b]$,否则遍历结束,返回 $[b, a]$。 - -时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$,仅使用常数大小的额外空间。 - -### **Python3** - - - ```python class Solution: def findErrorNums(self, nums: List[int]) -> List[int]: @@ -83,44 +59,6 @@ class Solution: return [s - s2, s1 - s2] ``` -```python -class Solution: - def findErrorNums(self, nums: List[int]) -> List[int]: - cnt = Counter(nums) - n = len(nums) - ans = [0] * 2 - for x in range(1, n + 1): - if cnt[x] == 2: - ans[0] = x - if cnt[x] == 0: - ans[1] = x - return ans -``` - -```python -class Solution: - def findErrorNums(self, nums: List[int]) -> List[int]: - xs = 0 - for i, x in enumerate(nums, 1): - xs ^= i ^ x - a = 0 - lb = xs & -xs - for i, x in enumerate(nums, 1): - if i & lb: - a ^= i - if x & lb: - a ^= x - b = xs ^ a - for x in nums: - if x == a: - return [a, b] - return [b, a] -``` - -### **Java** - - - ```java class Solution { public int[] findErrorNums(int[] nums) { @@ -140,6 +78,89 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector findErrorNums(vector& nums) { + int n = nums.size(); + int s1 = (1 + n) * n / 2; + int s2 = 0; + unordered_set set(nums.begin(), nums.end()); + for (int x : set) { + s2 += x; + } + int s = accumulate(nums.begin(), nums.end(), 0); + return {s - s2, s1 - s2}; + } +}; +``` + +```go +func findErrorNums(nums []int) []int { + n := len(nums) + s1 := (1 + n) * n / 2 + s2, s := 0, 0 + set := map[int]bool{} + for _, x := range nums { + if !set[x] { + set[x] = true + s2 += x + } + s += x + } + return []int{s - s2, s1 - s2} +} +``` + +```ts +function findErrorNums(nums: number[]): number[] { + const n = nums.length; + const s1 = (n * (n + 1)) >> 1; + const s2 = [...new Set(nums)].reduce((a, b) => a + b); + const s = nums.reduce((a, b) => a + b); + return [s - s2, s1 - s2]; +} +``` + +```rust +use std::collections::HashSet; +impl Solution { + pub fn find_error_nums(nums: Vec) -> Vec { + let n = nums.len() as i32; + let s1 = ((1 + n) * n) / 2; + let s2 = nums.iter().cloned().collect::>().iter().sum::(); + let s: i32 = nums.iter().sum(); + vec![s - s2, s1 - s2] + } +} +``` + + + +### 方法二:哈希表 + +我们也可以一种更加直观的方法,直接用哈希表 $cnt$ 统计数组 $nums$ 中每个数字出现的次数。 + +接下来遍历 $x \in [1, n]$,如果 $cnt[x] = 2$,那么 $x$ 就是重复的数字,如果 $cnt[x] = 0$,那么 $x$ 就是缺失的数字。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。 + + + +```python +class Solution: + def findErrorNums(self, nums: List[int]) -> List[int]: + cnt = Counter(nums) + n = len(nums) + ans = [0] * 2 + for x in range(1, n + 1): + if cnt[x] == 2: + ans[0] = x + if cnt[x] == 0: + ans[1] = x + return ans +``` + ```java class Solution { public int[] findErrorNums(int[] nums) { @@ -162,6 +183,129 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector findErrorNums(vector& nums) { + int n = nums.size(); + unordered_map cnt; + for (int x : nums) { + ++cnt[x]; + } + vector ans(2); + for (int x = 1; x <= n; ++x) { + if (cnt[x] == 2) { + ans[0] = x; + } else if (cnt[x] == 0) { + ans[1] = x; + } + } + return ans; + } +}; +``` + +```go +func findErrorNums(nums []int) []int { + n := len(nums) + cnt := map[int]int{} + for _, x := range nums { + cnt[x]++ + } + ans := make([]int, 2) + for x := 1; x <= n; x++ { + if cnt[x] == 2 { + ans[0] = x + } else if cnt[x] == 0 { + ans[1] = x + } + } + return ans +} +``` + +```ts +function findErrorNums(nums: number[]): number[] { + const n = nums.length; + const cnt: Map = new Map(); + for (const x of nums) { + cnt.set(x, (cnt.get(x) || 0) + 1); + } + const ans: number[] = new Array(2).fill(0); + for (let x = 1; x <= n; ++x) { + const t = cnt.get(x) || 0; + if (t === 2) { + ans[0] = x; + } else if (t === 0) { + ans[1] = x; + } + } + return ans; +} +``` + +```rust +impl Solution { + pub fn find_error_nums(nums: Vec) -> Vec { + let mut xs = 0; + for (i, x) in nums.iter().enumerate() { + xs ^= ((i + 1) as i32) ^ x; + } + let mut a = 0; + let lb = xs & -xs; + for (i, x) in nums.iter().enumerate() { + if (((i + 1) as i32) & lb) != 0 { + a ^= (i + 1) as i32; + } + if (*x & lb) != 0 { + a ^= *x; + } + } + let b = xs ^ a; + for x in nums.iter() { + if *x == a { + return vec![a, b]; + } + } + vec![b, a] + } +} +``` + + + +### 方法三:位运算 + +根据异或运算的性质,对于整数 $x$,有 $x \oplus x = 0$ 以及 $x \oplus 0 = x$,因此我们对数组 $nums$ 中的所有元素以及 $i \in [1, n]$ 的所有数字进行异或运算,可以消除出现两次的数字,最终只留下缺失的数字和重复的数字的异或结果,即 $xs = a \oplus b$。 + +由于这两个数字不相等,因此异或结果中至少存在一位为 $1$。我们通过 $lowbit$ 运算找到异或结果中最低位的 $1$,然后将数组 $nums$ 中所有数字以及 $i \in [1, n]$ 的所有数字按照该位是否为 $1$ 分为两组,这样两个数字就被分到了不同的组中。其中一组数字的异或结果为 $a$,另一组数字的异或结果为 $b$。那么这两个数字就是我们要找的答案。 + +接下来我们只需要判断 $a$ 和 $b$ 哪个数字是重复的数字,哪个数字是缺失的数字即可。因此,遍历数组 $nums$,对于遍历到的数字 $x$,如果 $x=a$,那么 $a$ 就是重复的数字,返回 $[a, b]$,否则遍历结束,返回 $[b, a]$。 + +时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$,仅使用常数大小的额外空间。 + + + +```python +class Solution: + def findErrorNums(self, nums: List[int]) -> List[int]: + xs = 0 + for i, x in enumerate(nums, 1): + xs ^= i ^ x + a = 0 + lb = xs & -xs + for i, x in enumerate(nums, 1): + if i & lb: + a ^= i + if x & lb: + a ^= x + b = xs ^ a + for x in nums: + if x == a: + return [a, b] + return [b, a] +``` + ```java class Solution { public int[] findErrorNums(int[] nums) { @@ -191,47 +335,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector findErrorNums(vector& nums) { - int n = nums.size(); - int s1 = (1 + n) * n / 2; - int s2 = 0; - unordered_set set(nums.begin(), nums.end()); - for (int x : set) { - s2 += x; - } - int s = accumulate(nums.begin(), nums.end(), 0); - return {s - s2, s1 - s2}; - } -}; -``` - -```cpp -class Solution { -public: - vector findErrorNums(vector& nums) { - int n = nums.size(); - unordered_map cnt; - for (int x : nums) { - ++cnt[x]; - } - vector ans(2); - for (int x = 1; x <= n; ++x) { - if (cnt[x] == 2) { - ans[0] = x; - } else if (cnt[x] == 0) { - ans[1] = x; - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -262,44 +365,6 @@ public: }; ``` -### **Go** - -```go -func findErrorNums(nums []int) []int { - n := len(nums) - s1 := (1 + n) * n / 2 - s2, s := 0, 0 - set := map[int]bool{} - for _, x := range nums { - if !set[x] { - set[x] = true - s2 += x - } - s += x - } - return []int{s - s2, s1 - s2} -} -``` - -```go -func findErrorNums(nums []int) []int { - n := len(nums) - cnt := map[int]int{} - for _, x := range nums { - cnt[x]++ - } - ans := make([]int, 2) - for x := 1; x <= n; x++ { - if cnt[x] == 2 { - ans[0] = x - } else if cnt[x] == 0 { - ans[1] = x - } - } - return ans -} -``` - ```go func findErrorNums(nums []int) []int { xs := 0 @@ -326,81 +391,6 @@ func findErrorNums(nums []int) []int { } ``` -### **Rust** - -```rust -use std::collections::HashSet; -impl Solution { - pub fn find_error_nums(nums: Vec) -> Vec { - let n = nums.len() as i32; - let s1 = ((1 + n) * n) / 2; - let s2 = nums.iter().cloned().collect::>().iter().sum::(); - let s: i32 = nums.iter().sum(); - vec![s - s2, s1 - s2] - } -} -``` - -```rust -impl Solution { - pub fn find_error_nums(nums: Vec) -> Vec { - let mut xs = 0; - for (i, x) in nums.iter().enumerate() { - xs ^= ((i + 1) as i32) ^ x; - } - let mut a = 0; - let lb = xs & -xs; - for (i, x) in nums.iter().enumerate() { - if (((i + 1) as i32) & lb) != 0 { - a ^= (i + 1) as i32; - } - if (*x & lb) != 0 { - a ^= *x; - } - } - let b = xs ^ a; - for x in nums.iter() { - if *x == a { - return vec![a, b]; - } - } - vec![b, a] - } -} -``` - -### **TypeScript** - -```ts -function findErrorNums(nums: number[]): number[] { - const n = nums.length; - const s1 = (n * (n + 1)) >> 1; - const s2 = [...new Set(nums)].reduce((a, b) => a + b); - const s = nums.reduce((a, b) => a + b); - return [s - s2, s1 - s2]; -} -``` - -```ts -function findErrorNums(nums: number[]): number[] { - const n = nums.length; - const cnt: Map = new Map(); - for (const x of nums) { - cnt.set(x, (cnt.get(x) || 0) + 1); - } - const ans: number[] = new Array(2).fill(0); - for (let x = 1; x <= n; ++x) { - const t = cnt.get(x) || 0; - if (t === 2) { - ans[0] = x; - } else if (t === 0) { - ans[1] = x; - } - } - return ans; -} -``` - ```ts function findErrorNums(nums: number[]): number[] { const n = nums.length; @@ -423,10 +413,6 @@ function findErrorNums(nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0645.Set Mismatch/README_EN.md b/solution/0600-0699/0645.Set Mismatch/README_EN.md index 0e60dda1fa707..32e506e2366ed 100644 --- a/solution/0600-0699/0645.Set Mismatch/README_EN.md +++ b/solution/0600-0699/0645.Set Mismatch/README_EN.md @@ -28,7 +28,7 @@ ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics We denote $s_1$ as the sum of all numbers from $[1,..n]$, $s_2$ as the sum of the numbers in the array $nums$ after removing duplicates, and $s$ as the sum of the numbers in the array $nums$. @@ -36,28 +36,8 @@ Then $s - s_2$ is the duplicate number, and $s_1 - s_2$ is the missing number. The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $nums$. Extra space is needed to store the array after de-duplication. -**Solution 2: Hash Table** - -We can also use a more intuitive method, using a hash table $cnt$ to count the occurrence of each number in the array $nums$. - -Next, iterate through $x \in [1, n]$, if $cnt[x] = 2$, then $x$ is the duplicate number, if $cnt[x] = 0$, then $x$ is the missing number. - -The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $nums$. - -**Solution 3: Bit Operation** - -According to the properties of the XOR operation, for integer $x$, we have $x \oplus x = 0$ and $x \oplus 0 = x$. Therefore, if we perform the XOR operation on all elements in the array $nums$ and all numbers $i \in [1, n]$, we can eliminate the numbers that appear twice, leaving only the XOR result of the missing number and the duplicate number, i.e., $xs = a \oplus b$. - -Since these two numbers are not equal, there must be at least one bit in the XOR result that is $1$. We find the lowest bit of $1$ in the XOR result through the $lowbit$ operation, and then divide all numbers in the array $nums$ and all numbers $i \in [1, n]$ into two groups according to whether this bit is $1$. In this way, the two numbers are divided into different groups. The XOR result of one group of numbers is $a$, and the XOR result of the other group is $b$. These two numbers are the answers we are looking for. - -Next, we only need to determine which of $a$ and $b$ is the duplicate number and which is the missing number. Therefore, iterate through the array $nums$, for the traversed number $x$, if $x=a$, then $a$ is the duplicate number, return $[a, b]$, otherwise, at the end of the iteration, return $[b, a]$. - -The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$, only using a constant size of extra space. - -### **Python3** - ```python class Solution: def findErrorNums(self, nums: List[int]) -> List[int]: @@ -68,42 +48,6 @@ class Solution: return [s - s2, s1 - s2] ``` -```python -class Solution: - def findErrorNums(self, nums: List[int]) -> List[int]: - cnt = Counter(nums) - n = len(nums) - ans = [0] * 2 - for x in range(1, n + 1): - if cnt[x] == 2: - ans[0] = x - if cnt[x] == 0: - ans[1] = x - return ans -``` - -```python -class Solution: - def findErrorNums(self, nums: List[int]) -> List[int]: - xs = 0 - for i, x in enumerate(nums, 1): - xs ^= i ^ x - a = 0 - lb = xs & -xs - for i, x in enumerate(nums, 1): - if i & lb: - a ^= i - if x & lb: - a ^= x - b = xs ^ a - for x in nums: - if x == a: - return [a, b] - return [b, a] -``` - -### **Java** - ```java class Solution { public int[] findErrorNums(int[] nums) { @@ -123,6 +67,89 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector findErrorNums(vector& nums) { + int n = nums.size(); + int s1 = (1 + n) * n / 2; + int s2 = 0; + unordered_set set(nums.begin(), nums.end()); + for (int x : set) { + s2 += x; + } + int s = accumulate(nums.begin(), nums.end(), 0); + return {s - s2, s1 - s2}; + } +}; +``` + +```go +func findErrorNums(nums []int) []int { + n := len(nums) + s1 := (1 + n) * n / 2 + s2, s := 0, 0 + set := map[int]bool{} + for _, x := range nums { + if !set[x] { + set[x] = true + s2 += x + } + s += x + } + return []int{s - s2, s1 - s2} +} +``` + +```ts +function findErrorNums(nums: number[]): number[] { + const n = nums.length; + const s1 = (n * (n + 1)) >> 1; + const s2 = [...new Set(nums)].reduce((a, b) => a + b); + const s = nums.reduce((a, b) => a + b); + return [s - s2, s1 - s2]; +} +``` + +```rust +use std::collections::HashSet; +impl Solution { + pub fn find_error_nums(nums: Vec) -> Vec { + let n = nums.len() as i32; + let s1 = ((1 + n) * n) / 2; + let s2 = nums.iter().cloned().collect::>().iter().sum::(); + let s: i32 = nums.iter().sum(); + vec![s - s2, s1 - s2] + } +} +``` + + + +### Solution 2: Hash Table + +We can also use a more intuitive method, using a hash table $cnt$ to count the occurrence of each number in the array $nums$. + +Next, iterate through $x \in [1, n]$, if $cnt[x] = 2$, then $x$ is the duplicate number, if $cnt[x] = 0$, then $x$ is the missing number. + +The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $nums$. + + + +```python +class Solution: + def findErrorNums(self, nums: List[int]) -> List[int]: + cnt = Counter(nums) + n = len(nums) + ans = [0] * 2 + for x in range(1, n + 1): + if cnt[x] == 2: + ans[0] = x + if cnt[x] == 0: + ans[1] = x + return ans +``` + ```java class Solution { public int[] findErrorNums(int[] nums) { @@ -145,6 +172,129 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector findErrorNums(vector& nums) { + int n = nums.size(); + unordered_map cnt; + for (int x : nums) { + ++cnt[x]; + } + vector ans(2); + for (int x = 1; x <= n; ++x) { + if (cnt[x] == 2) { + ans[0] = x; + } else if (cnt[x] == 0) { + ans[1] = x; + } + } + return ans; + } +}; +``` + +```go +func findErrorNums(nums []int) []int { + n := len(nums) + cnt := map[int]int{} + for _, x := range nums { + cnt[x]++ + } + ans := make([]int, 2) + for x := 1; x <= n; x++ { + if cnt[x] == 2 { + ans[0] = x + } else if cnt[x] == 0 { + ans[1] = x + } + } + return ans +} +``` + +```ts +function findErrorNums(nums: number[]): number[] { + const n = nums.length; + const cnt: Map = new Map(); + for (const x of nums) { + cnt.set(x, (cnt.get(x) || 0) + 1); + } + const ans: number[] = new Array(2).fill(0); + for (let x = 1; x <= n; ++x) { + const t = cnt.get(x) || 0; + if (t === 2) { + ans[0] = x; + } else if (t === 0) { + ans[1] = x; + } + } + return ans; +} +``` + +```rust +impl Solution { + pub fn find_error_nums(nums: Vec) -> Vec { + let mut xs = 0; + for (i, x) in nums.iter().enumerate() { + xs ^= ((i + 1) as i32) ^ x; + } + let mut a = 0; + let lb = xs & -xs; + for (i, x) in nums.iter().enumerate() { + if (((i + 1) as i32) & lb) != 0 { + a ^= (i + 1) as i32; + } + if (*x & lb) != 0 { + a ^= *x; + } + } + let b = xs ^ a; + for x in nums.iter() { + if *x == a { + return vec![a, b]; + } + } + vec![b, a] + } +} +``` + + + +### Solution 3: Bit Operation + +According to the properties of the XOR operation, for integer $x$, we have $x \oplus x = 0$ and $x \oplus 0 = x$. Therefore, if we perform the XOR operation on all elements in the array $nums$ and all numbers $i \in [1, n]$, we can eliminate the numbers that appear twice, leaving only the XOR result of the missing number and the duplicate number, i.e., $xs = a \oplus b$. + +Since these two numbers are not equal, there must be at least one bit in the XOR result that is $1$. We find the lowest bit of $1$ in the XOR result through the $lowbit$ operation, and then divide all numbers in the array $nums$ and all numbers $i \in [1, n]$ into two groups according to whether this bit is $1$. In this way, the two numbers are divided into different groups. The XOR result of one group of numbers is $a$, and the XOR result of the other group is $b$. These two numbers are the answers we are looking for. + +Next, we only need to determine which of $a$ and $b$ is the duplicate number and which is the missing number. Therefore, iterate through the array $nums$, for the traversed number $x$, if $x=a$, then $a$ is the duplicate number, return $[a, b]$, otherwise, at the end of the iteration, return $[b, a]$. + +The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$, only using a constant size of extra space. + + + +```python +class Solution: + def findErrorNums(self, nums: List[int]) -> List[int]: + xs = 0 + for i, x in enumerate(nums, 1): + xs ^= i ^ x + a = 0 + lb = xs & -xs + for i, x in enumerate(nums, 1): + if i & lb: + a ^= i + if x & lb: + a ^= x + b = xs ^ a + for x in nums: + if x == a: + return [a, b] + return [b, a] +``` + ```java class Solution { public int[] findErrorNums(int[] nums) { @@ -174,47 +324,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector findErrorNums(vector& nums) { - int n = nums.size(); - int s1 = (1 + n) * n / 2; - int s2 = 0; - unordered_set set(nums.begin(), nums.end()); - for (int x : set) { - s2 += x; - } - int s = accumulate(nums.begin(), nums.end(), 0); - return {s - s2, s1 - s2}; - } -}; -``` - -```cpp -class Solution { -public: - vector findErrorNums(vector& nums) { - int n = nums.size(); - unordered_map cnt; - for (int x : nums) { - ++cnt[x]; - } - vector ans(2); - for (int x = 1; x <= n; ++x) { - if (cnt[x] == 2) { - ans[0] = x; - } else if (cnt[x] == 0) { - ans[1] = x; - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -245,44 +354,6 @@ public: }; ``` -### **Go** - -```go -func findErrorNums(nums []int) []int { - n := len(nums) - s1 := (1 + n) * n / 2 - s2, s := 0, 0 - set := map[int]bool{} - for _, x := range nums { - if !set[x] { - set[x] = true - s2 += x - } - s += x - } - return []int{s - s2, s1 - s2} -} -``` - -```go -func findErrorNums(nums []int) []int { - n := len(nums) - cnt := map[int]int{} - for _, x := range nums { - cnt[x]++ - } - ans := make([]int, 2) - for x := 1; x <= n; x++ { - if cnt[x] == 2 { - ans[0] = x - } else if cnt[x] == 0 { - ans[1] = x - } - } - return ans -} -``` - ```go func findErrorNums(nums []int) []int { xs := 0 @@ -309,81 +380,6 @@ func findErrorNums(nums []int) []int { } ``` -### **Rust** - -```rust -use std::collections::HashSet; -impl Solution { - pub fn find_error_nums(nums: Vec) -> Vec { - let n = nums.len() as i32; - let s1 = ((1 + n) * n) / 2; - let s2 = nums.iter().cloned().collect::>().iter().sum::(); - let s: i32 = nums.iter().sum(); - vec![s - s2, s1 - s2] - } -} -``` - -```rust -impl Solution { - pub fn find_error_nums(nums: Vec) -> Vec { - let mut xs = 0; - for (i, x) in nums.iter().enumerate() { - xs ^= ((i + 1) as i32) ^ x; - } - let mut a = 0; - let lb = xs & -xs; - for (i, x) in nums.iter().enumerate() { - if (((i + 1) as i32) & lb) != 0 { - a ^= (i + 1) as i32; - } - if (*x & lb) != 0 { - a ^= *x; - } - } - let b = xs ^ a; - for x in nums.iter() { - if *x == a { - return vec![a, b]; - } - } - vec![b, a] - } -} -``` - -### **TypeScript** - -```ts -function findErrorNums(nums: number[]): number[] { - const n = nums.length; - const s1 = (n * (n + 1)) >> 1; - const s2 = [...new Set(nums)].reduce((a, b) => a + b); - const s = nums.reduce((a, b) => a + b); - return [s - s2, s1 - s2]; -} -``` - -```ts -function findErrorNums(nums: number[]): number[] { - const n = nums.length; - const cnt: Map = new Map(); - for (const x of nums) { - cnt.set(x, (cnt.get(x) || 0) + 1); - } - const ans: number[] = new Array(2).fill(0); - for (let x = 1; x <= n; ++x) { - const t = cnt.get(x) || 0; - if (t === 2) { - ans[0] = x; - } else if (t === 0) { - ans[1] = x; - } - } - return ans; -} -``` - ```ts function findErrorNums(nums: number[]): number[] { const n = nums.length; @@ -406,10 +402,6 @@ function findErrorNums(nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0646.Maximum Length of Pair Chain/README.md b/solution/0600-0699/0646.Maximum Length of Pair Chain/README.md index 94d9dedec94ce..b290a24bdf795 100644 --- a/solution/0600-0699/0646.Maximum Length of Pair Chain/README.md +++ b/solution/0600-0699/0646.Maximum Length of Pair Chain/README.md @@ -43,26 +43,14 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 先将 pairs 按照第一个数字升序排列,然后转换为最长上升子序列问题。 朴素做法,时间复杂度 $O(n^2)$。 -**方法二:贪心** - -在所有可作为下一个数对的集合中,选择第二个数最小的数对添加到数对链。因此可以按照第二个数升序排列的顺序遍历所有数对,如果当前数能加入链,则加入。 - -时间复杂度 $O(n\log n)$。 - -### **Python3** - - - ```python class Solution: def findLongestChain(self, pairs: List[List[int]]) -> int: @@ -75,21 +63,6 @@ class Solution: return max(dp) ``` -```python -class Solution: - def findLongestChain(self, pairs: List[List[int]]) -> int: - ans, cur = 0, -inf - for a, b in sorted(pairs, key=lambda x: x[1]): - if cur < a: - cur = b - ans += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int findLongestChain(int[][] pairs) { @@ -113,25 +86,6 @@ class Solution { } ``` -```java -class Solution { - public int findLongestChain(int[][] pairs) { - Arrays.sort(pairs, Comparator.comparingInt(a -> a[1])); - int ans = 0; - int cur = Integer.MIN_VALUE; - for (int[] p : pairs) { - if (cur < p[0]) { - cur = p[1]; - ++ans; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -151,27 +105,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findLongestChain(vector>& pairs) { - sort(pairs.begin(), pairs.end(), [](vector& a, vector b) { - return a[1] < b[1]; - }); - int ans = 0, cur = INT_MIN; - for (auto& p : pairs) { - if (cur < p[0]) { - cur = p[1]; - ++ans; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func findLongestChain(pairs [][]int) int { sort.Slice(pairs, func(i, j int) bool { @@ -195,24 +128,6 @@ func findLongestChain(pairs [][]int) int { } ``` -```go -func findLongestChain(pairs [][]int) int { - sort.Slice(pairs, func(i, j int) bool { - return pairs[i][1] < pairs[j][1] - }) - ans, cur := 0, math.MinInt32 - for _, p := range pairs { - if cur < p[0] { - cur = p[1] - ans++ - } - } - return ans -} -``` - -### **TypeScript** - ```ts function findLongestChain(pairs: number[][]): number { pairs.sort((a, b) => a[0] - b[0]); @@ -229,23 +144,6 @@ function findLongestChain(pairs: number[][]): number { } ``` -```ts -function findLongestChain(pairs: number[][]): number { - pairs.sort((a, b) => a[1] - b[1]); - let res = 0; - let pre = -Infinity; - for (const [a, b] of pairs) { - if (pre < a) { - pre = b; - res++; - } - } - return res; -} -``` - -### **Rust** - ```rust impl Solution { pub fn find_longest_chain(mut pairs: Vec>) -> i32 { @@ -264,6 +162,94 @@ impl Solution { } ``` + + +### 方法二:贪心 + +在所有可作为下一个数对的集合中,选择第二个数最小的数对添加到数对链。因此可以按照第二个数升序排列的顺序遍历所有数对,如果当前数能加入链,则加入。 + +时间复杂度 $O(n\log n)$。 + + + +```python +class Solution: + def findLongestChain(self, pairs: List[List[int]]) -> int: + ans, cur = 0, -inf + for a, b in sorted(pairs, key=lambda x: x[1]): + if cur < a: + cur = b + ans += 1 + return ans +``` + +```java +class Solution { + public int findLongestChain(int[][] pairs) { + Arrays.sort(pairs, Comparator.comparingInt(a -> a[1])); + int ans = 0; + int cur = Integer.MIN_VALUE; + for (int[] p : pairs) { + if (cur < p[0]) { + cur = p[1]; + ++ans; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int findLongestChain(vector>& pairs) { + sort(pairs.begin(), pairs.end(), [](vector& a, vector b) { + return a[1] < b[1]; + }); + int ans = 0, cur = INT_MIN; + for (auto& p : pairs) { + if (cur < p[0]) { + cur = p[1]; + ++ans; + } + } + return ans; + } +}; +``` + +```go +func findLongestChain(pairs [][]int) int { + sort.Slice(pairs, func(i, j int) bool { + return pairs[i][1] < pairs[j][1] + }) + ans, cur := 0, math.MinInt32 + for _, p := range pairs { + if cur < p[0] { + cur = p[1] + ans++ + } + } + return ans +} +``` + +```ts +function findLongestChain(pairs: number[][]): number { + pairs.sort((a, b) => a[1] - b[1]); + let res = 0; + let pre = -Infinity; + for (const [a, b] of pairs) { + if (pre < a) { + pre = b; + res++; + } + } + return res; +} +``` + ```rust impl Solution { pub fn find_longest_chain(mut pairs: Vec>) -> i32 { @@ -283,10 +269,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0646.Maximum Length of Pair Chain/README_EN.md b/solution/0600-0699/0646.Maximum Length of Pair Chain/README_EN.md index 63f232177dabb..43735a3f3033f 100644 --- a/solution/0600-0699/0646.Maximum Length of Pair Chain/README_EN.md +++ b/solution/0600-0699/0646.Maximum Length of Pair Chain/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,19 +56,6 @@ class Solution: return max(dp) ``` -```python -class Solution: - def findLongestChain(self, pairs: List[List[int]]) -> int: - ans, cur = 0, -inf - for a, b in sorted(pairs, key=lambda x: x[1]): - if cur < a: - cur = b - ans += 1 - return ans -``` - -### **Java** - ```java class Solution { public int findLongestChain(int[][] pairs) { @@ -92,25 +79,6 @@ class Solution { } ``` -```java -class Solution { - public int findLongestChain(int[][] pairs) { - Arrays.sort(pairs, Comparator.comparingInt(a -> a[1])); - int ans = 0; - int cur = Integer.MIN_VALUE; - for (int[] p : pairs) { - if (cur < p[0]) { - cur = p[1]; - ++ans; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -130,27 +98,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findLongestChain(vector>& pairs) { - sort(pairs.begin(), pairs.end(), [](vector& a, vector b) { - return a[1] < b[1]; - }); - int ans = 0, cur = INT_MIN; - for (auto& p : pairs) { - if (cur < p[0]) { - cur = p[1]; - ++ans; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func findLongestChain(pairs [][]int) int { sort.Slice(pairs, func(i, j int) bool { @@ -174,24 +121,6 @@ func findLongestChain(pairs [][]int) int { } ``` -```go -func findLongestChain(pairs [][]int) int { - sort.Slice(pairs, func(i, j int) bool { - return pairs[i][1] < pairs[j][1] - }) - ans, cur := 0, math.MinInt32 - for _, p := range pairs { - if cur < p[0] { - cur = p[1] - ans++ - } - } - return ans -} -``` - -### **TypeScript** - ```ts function findLongestChain(pairs: number[][]): number { pairs.sort((a, b) => a[0] - b[0]); @@ -208,23 +137,6 @@ function findLongestChain(pairs: number[][]): number { } ``` -```ts -function findLongestChain(pairs: number[][]): number { - pairs.sort((a, b) => a[1] - b[1]); - let res = 0; - let pre = -Infinity; - for (const [a, b] of pairs) { - if (pre < a) { - pre = b; - res++; - } - } - return res; -} -``` - -### **Rust** - ```rust impl Solution { pub fn find_longest_chain(mut pairs: Vec>) -> i32 { @@ -243,6 +155,90 @@ impl Solution { } ``` + + +### Solution 2 + + + +```python +class Solution: + def findLongestChain(self, pairs: List[List[int]]) -> int: + ans, cur = 0, -inf + for a, b in sorted(pairs, key=lambda x: x[1]): + if cur < a: + cur = b + ans += 1 + return ans +``` + +```java +class Solution { + public int findLongestChain(int[][] pairs) { + Arrays.sort(pairs, Comparator.comparingInt(a -> a[1])); + int ans = 0; + int cur = Integer.MIN_VALUE; + for (int[] p : pairs) { + if (cur < p[0]) { + cur = p[1]; + ++ans; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int findLongestChain(vector>& pairs) { + sort(pairs.begin(), pairs.end(), [](vector& a, vector b) { + return a[1] < b[1]; + }); + int ans = 0, cur = INT_MIN; + for (auto& p : pairs) { + if (cur < p[0]) { + cur = p[1]; + ++ans; + } + } + return ans; + } +}; +``` + +```go +func findLongestChain(pairs [][]int) int { + sort.Slice(pairs, func(i, j int) bool { + return pairs[i][1] < pairs[j][1] + }) + ans, cur := 0, math.MinInt32 + for _, p := range pairs { + if cur < p[0] { + cur = p[1] + ans++ + } + } + return ans +} +``` + +```ts +function findLongestChain(pairs: number[][]): number { + pairs.sort((a, b) => a[1] - b[1]); + let res = 0; + let pre = -Infinity; + for (const [a, b] of pairs) { + if (pre < a) { + pre = b; + res++; + } + } + return res; +} +``` + ```rust impl Solution { pub fn find_longest_chain(mut pairs: Vec>) -> i32 { @@ -262,10 +258,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0647.Palindromic Substrings/README.md b/solution/0600-0699/0647.Palindromic Substrings/README.md index 0ac0a9428f6bf..1e39faaa50e63 100644 --- a/solution/0600-0699/0647.Palindromic Substrings/README.md +++ b/solution/0600-0699/0647.Palindromic Substrings/README.md @@ -42,24 +42,12 @@ ## 解法 - - -**方法一:从中心向两侧扩展回文串** +### 方法一:从中心向两侧扩展回文串 时间复杂度 $O(n^2)$,其中 $n$ 是字符串 `s` 的长度。 -**方法二:Manacher 算法** - -在 Manacher 算法的计算过程中,用 $p[i]-1$ 表示以第 $i$ 位为中心的最大回文长度,以第 $i$ 位为中心的回文串数量为 $\left \lceil \frac{p[i]-1}{2} \right \rceil$。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 `s` 的长度。 - -### **Python3** - - - ```python class Solution: def countSubstrings(self, s: str) -> int: @@ -72,29 +60,6 @@ class Solution: return ans ``` -```python -class Solution: - def countSubstrings(self, s: str) -> int: - t = '^#' + '#'.join(s) + '#$' - n = len(t) - p = [0 for _ in range(n)] - pos, maxRight = 0, 0 - ans = 0 - for i in range(1, n - 1): - p[i] = min(maxRight - i, p[2 * pos - i]) if maxRight > i else 1 - while t[i - p[i]] == t[i + p[i]]: - p[i] += 1 - if i + p[i] > maxRight: - maxRight = i + p[i] - pos = i - ans += p[i] // 2 - return ans -``` - -### **Java** - - - ```java class Solution { public int countSubstrings(String s) { @@ -113,36 +78,6 @@ class Solution { } ``` -```java -class Solution { - public int countSubstrings(String s) { - StringBuilder sb = new StringBuilder("^#"); - for (char ch : s.toCharArray()) { - sb.append(ch).append('#'); - } - String t = sb.append('$').toString(); - int n = t.length(); - int[] p = new int[n]; - int pos = 0, maxRight = 0; - int ans = 0; - for (int i = 1; i < n - 1; i++) { - p[i] = maxRight > i ? Math.min(maxRight - i, p[2 * pos - i]) : 1; - while (t.charAt(i - p[i]) == t.charAt(i + p[i])) { - p[i]++; - } - if (i + p[i] > maxRight) { - maxRight = i + p[i]; - pos = i; - } - ans += p[i] / 2; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -162,8 +97,6 @@ public: }; ``` -### **Go** - ```go func countSubstrings(s string) int { ans, n := 0, len(s) @@ -178,8 +111,6 @@ func countSubstrings(s string) int { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -201,10 +132,63 @@ var countSubstrings = function (s) { }; ``` -### **...** + + +### 方法二:Manacher 算法 + +在 Manacher 算法的计算过程中,用 $p[i]-1$ 表示以第 $i$ 位为中心的最大回文长度,以第 $i$ 位为中心的回文串数量为 $\left \lceil \frac{p[i]-1}{2} \right \rceil$。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 `s` 的长度。 + + +```python +class Solution: + def countSubstrings(self, s: str) -> int: + t = '^#' + '#'.join(s) + '#$' + n = len(t) + p = [0 for _ in range(n)] + pos, maxRight = 0, 0 + ans = 0 + for i in range(1, n - 1): + p[i] = min(maxRight - i, p[2 * pos - i]) if maxRight > i else 1 + while t[i - p[i]] == t[i + p[i]]: + p[i] += 1 + if i + p[i] > maxRight: + maxRight = i + p[i] + pos = i + ans += p[i] // 2 + return ans ``` +```java +class Solution { + public int countSubstrings(String s) { + StringBuilder sb = new StringBuilder("^#"); + for (char ch : s.toCharArray()) { + sb.append(ch).append('#'); + } + String t = sb.append('$').toString(); + int n = t.length(); + int[] p = new int[n]; + int pos = 0, maxRight = 0; + int ans = 0; + for (int i = 1; i < n - 1; i++) { + p[i] = maxRight > i ? Math.min(maxRight - i, p[2 * pos - i]) : 1; + while (t.charAt(i - p[i]) == t.charAt(i + p[i])) { + p[i]++; + } + if (i + p[i] > maxRight) { + maxRight = i + p[i]; + pos = i; + } + ans += p[i] / 2; + } + return ans; + } +} ``` + + diff --git a/solution/0600-0699/0647.Palindromic Substrings/README_EN.md b/solution/0600-0699/0647.Palindromic Substrings/README_EN.md index e2607f1b0db66..e0de36d76dd59 100644 --- a/solution/0600-0699/0647.Palindromic Substrings/README_EN.md +++ b/solution/0600-0699/0647.Palindromic Substrings/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,27 +53,6 @@ class Solution: return ans ``` -```python -class Solution: - def countSubstrings(self, s: str) -> int: - t = '^#' + '#'.join(s) + '#$' - n = len(t) - p = [0 for _ in range(n)] - pos, maxRight = 0, 0 - ans = 0 - for i in range(1, n - 1): - p[i] = min(maxRight - i, p[2 * pos - i]) if maxRight > i else 1 - while t[i - p[i]] == t[i + p[i]]: - p[i] += 1 - if i + p[i] > maxRight: - maxRight = i + p[i] - pos = i - ans += p[i] // 2 - return ans -``` - -### **Java** - ```java class Solution { public int countSubstrings(String s) { @@ -92,36 +71,6 @@ class Solution { } ``` -```java -class Solution { - public int countSubstrings(String s) { - StringBuilder sb = new StringBuilder("^#"); - for (char ch : s.toCharArray()) { - sb.append(ch).append('#'); - } - String t = sb.append('$').toString(); - int n = t.length(); - int[] p = new int[n]; - int pos = 0, maxRight = 0; - int ans = 0; - for (int i = 1; i < n - 1; i++) { - p[i] = maxRight > i ? Math.min(maxRight - i, p[2 * pos - i]) : 1; - while (t.charAt(i - p[i]) == t.charAt(i + p[i])) { - p[i]++; - } - if (i + p[i] > maxRight) { - maxRight = i + p[i]; - pos = i; - } - ans += p[i] / 2; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -141,8 +90,6 @@ public: }; ``` -### **Go** - ```go func countSubstrings(s string) int { ans, n := 0, len(s) @@ -157,8 +104,6 @@ func countSubstrings(s string) int { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -180,10 +125,59 @@ var countSubstrings = function (s) { }; ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def countSubstrings(self, s: str) -> int: + t = '^#' + '#'.join(s) + '#$' + n = len(t) + p = [0 for _ in range(n)] + pos, maxRight = 0, 0 + ans = 0 + for i in range(1, n - 1): + p[i] = min(maxRight - i, p[2 * pos - i]) if maxRight > i else 1 + while t[i - p[i]] == t[i + p[i]]: + p[i] += 1 + if i + p[i] > maxRight: + maxRight = i + p[i] + pos = i + ans += p[i] // 2 + return ans ``` +```java +class Solution { + public int countSubstrings(String s) { + StringBuilder sb = new StringBuilder("^#"); + for (char ch : s.toCharArray()) { + sb.append(ch).append('#'); + } + String t = sb.append('$').toString(); + int n = t.length(); + int[] p = new int[n]; + int pos = 0, maxRight = 0; + int ans = 0; + for (int i = 1; i < n - 1; i++) { + p[i] = maxRight > i ? Math.min(maxRight - i, p[2 * pos - i]) : 1; + while (t.charAt(i - p[i]) == t.charAt(i + p[i])) { + p[i]++; + } + if (i + p[i] > maxRight) { + maxRight = i + p[i]; + pos = i; + } + ans += p[i] / 2; + } + return ans; + } +} ``` + + diff --git a/solution/0600-0699/0648.Replace Words/README.md b/solution/0600-0699/0648.Replace Words/README.md index 8ac83d2096726..5bd7992e48bb0 100644 --- a/solution/0600-0699/0648.Replace Words/README.md +++ b/solution/0600-0699/0648.Replace Words/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:前缀树** +### 方法一:前缀树 我们定义前缀树的节点数据结构如下: @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Trie: def __init__(self): @@ -106,10 +100,6 @@ class Solution: return " ".join(ans) ``` -### **Java** - - - ```java class Solution { public String replaceWords(List dictionary, String sentence) { @@ -130,57 +120,6 @@ class Solution { } ``` -```java -class Trie { - private Trie[] children = new Trie[26]; - private int ref = -1; - - public void insert(String w, int i) { - Trie node = this; - for (int j = 0; j < w.length(); ++j) { - int idx = w.charAt(j) - 'a'; - if (node.children[idx] == null) { - node.children[idx] = new Trie(); - } - node = node.children[idx]; - } - node.ref = i; - } - - public int search(String w) { - Trie node = this; - for (int j = 0; j < w.length(); ++j) { - int idx = w.charAt(j) - 'a'; - if (node.children[idx] == null) { - return -1; - } - node = node.children[idx]; - if (node.ref != -1) { - return node.ref; - } - } - return -1; - } -} - -class Solution { - public String replaceWords(List dictionary, String sentence) { - Trie trie = new Trie(); - for (int i = 0; i < dictionary.size(); ++i) { - trie.insert(dictionary.get(i), i); - } - List ans = new ArrayList<>(); - for (String w : sentence.split("\\s")) { - int idx = trie.search(w); - ans.add(idx == -1 ? w : dictionary.get(idx)); - } - return String.join(" ", ans); - } -} -``` - -### **C++** - ```cpp class Trie { private: @@ -241,8 +180,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -298,8 +235,6 @@ func replaceWords(dictionary []string, sentence string) string { } ``` -### **TypeScript** - ```ts class Trie { private children: Trie[]; @@ -353,10 +288,61 @@ function replaceWords(dictionary: string[], sentence: string): string { } ``` -### **...** + -``` +### 方法二 + + + +```java +class Trie { + private Trie[] children = new Trie[26]; + private int ref = -1; + + public void insert(String w, int i) { + Trie node = this; + for (int j = 0; j < w.length(); ++j) { + int idx = w.charAt(j) - 'a'; + if (node.children[idx] == null) { + node.children[idx] = new Trie(); + } + node = node.children[idx]; + } + node.ref = i; + } + + public int search(String w) { + Trie node = this; + for (int j = 0; j < w.length(); ++j) { + int idx = w.charAt(j) - 'a'; + if (node.children[idx] == null) { + return -1; + } + node = node.children[idx]; + if (node.ref != -1) { + return node.ref; + } + } + return -1; + } +} +class Solution { + public String replaceWords(List dictionary, String sentence) { + Trie trie = new Trie(); + for (int i = 0; i < dictionary.size(); ++i) { + trie.insert(dictionary.get(i), i); + } + List ans = new ArrayList<>(); + for (String w : sentence.split("\\s")) { + int idx = trie.search(w); + ans.add(idx == -1 ? w : dictionary.get(idx)); + } + return String.join(" ", ans); + } +} ``` + + diff --git a/solution/0600-0699/0648.Replace Words/README_EN.md b/solution/0600-0699/0648.Replace Words/README_EN.md index cbea51654e381..06cc915189ba9 100644 --- a/solution/0600-0699/0648.Replace Words/README_EN.md +++ b/solution/0600-0699/0648.Replace Words/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -85,8 +85,6 @@ class Solution: return " ".join(ans) ``` -### **Java** - ```java class Solution { public String replaceWords(List dictionary, String sentence) { @@ -107,57 +105,6 @@ class Solution { } ``` -```java -class Trie { - private Trie[] children = new Trie[26]; - private int ref = -1; - - public void insert(String w, int i) { - Trie node = this; - for (int j = 0; j < w.length(); ++j) { - int idx = w.charAt(j) - 'a'; - if (node.children[idx] == null) { - node.children[idx] = new Trie(); - } - node = node.children[idx]; - } - node.ref = i; - } - - public int search(String w) { - Trie node = this; - for (int j = 0; j < w.length(); ++j) { - int idx = w.charAt(j) - 'a'; - if (node.children[idx] == null) { - return -1; - } - node = node.children[idx]; - if (node.ref != -1) { - return node.ref; - } - } - return -1; - } -} - -class Solution { - public String replaceWords(List dictionary, String sentence) { - Trie trie = new Trie(); - for (int i = 0; i < dictionary.size(); ++i) { - trie.insert(dictionary.get(i), i); - } - List ans = new ArrayList<>(); - for (String w : sentence.split("\\s")) { - int idx = trie.search(w); - ans.add(idx == -1 ? w : dictionary.get(idx)); - } - return String.join(" ", ans); - } -} -``` - -### **C++** - ```cpp class Trie { private: @@ -218,8 +165,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -275,8 +220,6 @@ func replaceWords(dictionary []string, sentence string) string { } ``` -### **TypeScript** - ```ts class Trie { private children: Trie[]; @@ -330,10 +273,61 @@ function replaceWords(dictionary: string[], sentence: string): string { } ``` -### **...** + + +### Solution 2 -``` + + +```java +class Trie { + private Trie[] children = new Trie[26]; + private int ref = -1; + public void insert(String w, int i) { + Trie node = this; + for (int j = 0; j < w.length(); ++j) { + int idx = w.charAt(j) - 'a'; + if (node.children[idx] == null) { + node.children[idx] = new Trie(); + } + node = node.children[idx]; + } + node.ref = i; + } + + public int search(String w) { + Trie node = this; + for (int j = 0; j < w.length(); ++j) { + int idx = w.charAt(j) - 'a'; + if (node.children[idx] == null) { + return -1; + } + node = node.children[idx]; + if (node.ref != -1) { + return node.ref; + } + } + return -1; + } +} + +class Solution { + public String replaceWords(List dictionary, String sentence) { + Trie trie = new Trie(); + for (int i = 0; i < dictionary.size(); ++i) { + trie.insert(dictionary.get(i), i); + } + List ans = new ArrayList<>(); + for (String w : sentence.split("\\s")) { + int idx = trie.search(w); + ans.add(idx == -1 ? w : dictionary.get(idx)); + } + return String.join(" ", ans); + } +} ``` + + diff --git a/solution/0600-0699/0649.Dota2 Senate/README.md b/solution/0600-0699/0649.Dota2 Senate/README.md index 91499f99fd5a3..a987038dfcede 100644 --- a/solution/0600-0699/0649.Dota2 Senate/README.md +++ b/solution/0600-0699/0649.Dota2 Senate/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:队列 + 模拟** +### 方法一:队列 + 模拟 我们创建两个队列 $qr$ 和 $qd$,分别记录天辉和夜魇阵营的参议员的下标。然后我们开始进行模拟,每一轮各从队首取出一位参议员,然后根据他的阵营进行不同的操作: @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def predictPartyVictory(self, senate: str) -> str: @@ -98,10 +92,6 @@ class Solution: return "Radiant" if qr else "Dire" ``` -### **Java** - - - ```java class Solution { public String predictPartyVictory(String senate) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go func predictPartyVictory(senate string) string { n := len(senate) @@ -191,8 +177,6 @@ func predictPartyVictory(senate string) string { } ``` -### **TypeScript** - ```ts function predictPartyVictory(senate: string): string { const n = senate.length; @@ -218,8 +202,6 @@ function predictPartyVictory(senate: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn predict_party_victory(senate: String) -> String { @@ -253,10 +235,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0649.Dota2 Senate/README_EN.md b/solution/0600-0699/0649.Dota2 Senate/README_EN.md index 4cdede9454c8b..9d68530ed5335 100644 --- a/solution/0600-0699/0649.Dota2 Senate/README_EN.md +++ b/solution/0600-0699/0649.Dota2 Senate/README_EN.md @@ -54,9 +54,9 @@ And in round 2, the third senator can just announce the victory since he is the ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,8 +79,6 @@ class Solution: return "Radiant" if qr else "Dire" ``` -### **Java** - ```java class Solution { public String predictPartyVictory(String senate) { @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +136,6 @@ public: }; ``` -### **Go** - ```go func predictPartyVictory(senate string) string { n := len(senate) @@ -170,8 +164,6 @@ func predictPartyVictory(senate string) string { } ``` -### **TypeScript** - ```ts function predictPartyVictory(senate: string): string { const n = senate.length; @@ -197,8 +189,6 @@ function predictPartyVictory(senate: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn predict_party_victory(senate: String) -> String { @@ -232,10 +222,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0650.2 Keys Keyboard/README.md b/solution/0600-0699/0650.2 Keys Keyboard/README.md index 5e2b256f53e46..8b01405383396 100644 --- a/solution/0600-0699/0650.2 Keys Keyboard/README.md +++ b/solution/0600-0699/0650.2 Keys Keyboard/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 定义 $dfs(i)$ 为输出 $i$ 个字符的最少操作次数。初始化 `dfs(1)=0`。 @@ -60,22 +58,8 @@ $$ 时间复杂度 $O(n\sqrt{n})$。 -**方法二:动态规划** - -记忆化搜索也可以改成动态规划。 - -$$ -dp[i]=\min _{j \mid i} (dp[\frac{i}{j}]+j, i), 2\leq j\lt i -$$ - -时间复杂度 $O(n\sqrt{n})$。 - -### **Python3** - - - ```python class Solution: def minSteps(self, n: int) -> int: @@ -93,24 +77,6 @@ class Solution: return dfs(n) ``` -```python -class Solution: - def minSteps(self, n: int) -> int: - dp = list(range(n + 1)) - dp[1] = 0 - for i in range(2, n + 1): - j = 2 - while j * j <= i: - if i % j == 0: - dp[i] = min(dp[i], dp[i // j] + j) - j += 1 - return dp[-1] -``` - -### **Java** - - - ```java class Solution { private int[] f; @@ -140,43 +106,6 @@ class Solution { } ``` -```java -class Solution { - public int minSteps(int n) { - int[] dp = new int[n + 1]; - for (int i = 0; i < n + 1; ++i) { - dp[i] = i; - } - dp[1] = 0; - for (int i = 2; i < n + 1; ++i) { - for (int j = 2; j * j <= i; ++j) { - if (i % j == 0) { - dp[i] = Math.min(dp[i], dp[i / j] + j); - } - } - } - return dp[n]; - } -} -``` - -```java -class Solution { - public int minSteps(int n) { - int res = 0; - for (int i = 2; n > 1; ++i) { - while (n % i == 0) { - res += i; - n /= i; - } - } - return res; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -202,27 +131,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minSteps(int n) { - vector dp(n + 1); - iota(dp.begin(), dp.end(), 0); - dp[1] = 0; - for (int i = 2; i < n + 1; ++i) { - for (int j = 2; j * j <= i; ++j) { - if (i % j == 0) { - dp[i] = min(dp[i], dp[i / j] + j); - } - } - } - return dp[n]; - } -}; -``` - -### **Go** - ```go func minSteps(n int) int { f := make([]int, n+1) @@ -249,6 +157,73 @@ func minSteps(n int) int { } ``` + + +### 方法二:动态规划 + +记忆化搜索也可以改成动态规划。 + +$$ +dp[i]=\min _{j \mid i} (dp[\frac{i}{j}]+j, i), 2\leq j\lt i +$$ + +时间复杂度 $O(n\sqrt{n})$。 + + + +```python +class Solution: + def minSteps(self, n: int) -> int: + dp = list(range(n + 1)) + dp[1] = 0 + for i in range(2, n + 1): + j = 2 + while j * j <= i: + if i % j == 0: + dp[i] = min(dp[i], dp[i // j] + j) + j += 1 + return dp[-1] +``` + +```java +class Solution { + public int minSteps(int n) { + int[] dp = new int[n + 1]; + for (int i = 0; i < n + 1; ++i) { + dp[i] = i; + } + dp[1] = 0; + for (int i = 2; i < n + 1; ++i) { + for (int j = 2; j * j <= i; ++j) { + if (i % j == 0) { + dp[i] = Math.min(dp[i], dp[i / j] + j); + } + } + } + return dp[n]; + } +} +``` + +```cpp +class Solution { +public: + int minSteps(int n) { + vector dp(n + 1); + iota(dp.begin(), dp.end(), 0); + dp[1] = 0; + for (int i = 2; i < n + 1; ++i) { + for (int j = 2; j * j <= i; ++j) { + if (i % j == 0) { + dp[i] = min(dp[i], dp[i / j] + j); + } + } + } + return dp[n]; + } +}; +``` + ```go func minSteps(n int) int { dp := make([]int, n+1) @@ -267,10 +242,27 @@ func minSteps(n int) int { } ``` -### **...** + -``` +### 方法三 + + +```java +class Solution { + public int minSteps(int n) { + int res = 0; + for (int i = 2; n > 1; ++i) { + while (n % i == 0) { + res += i; + n /= i; + } + } + return res; + } +} ``` + + diff --git a/solution/0600-0699/0650.2 Keys Keyboard/README_EN.md b/solution/0600-0699/0650.2 Keys Keyboard/README_EN.md index fa2e1f309a952..3646886016d45 100644 --- a/solution/0600-0699/0650.2 Keys Keyboard/README_EN.md +++ b/solution/0600-0699/0650.2 Keys Keyboard/README_EN.md @@ -41,9 +41,9 @@ In step 3, we use Paste operation to get 'AAA'. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,22 +62,6 @@ class Solution: return dfs(n) ``` -```python -class Solution: - def minSteps(self, n: int) -> int: - dp = list(range(n + 1)) - dp[1] = 0 - for i in range(2, n + 1): - j = 2 - while j * j <= i: - if i % j == 0: - dp[i] = min(dp[i], dp[i // j] + j) - j += 1 - return dp[-1] -``` - -### **Java** - ```java class Solution { private int[] f; @@ -107,43 +91,6 @@ class Solution { } ``` -```java -class Solution { - public int minSteps(int n) { - int[] dp = new int[n + 1]; - for (int i = 0; i < n + 1; ++i) { - dp[i] = i; - } - dp[1] = 0; - for (int i = 2; i < n + 1; ++i) { - for (int j = 2; j * j <= i; ++j) { - if (i % j == 0) { - dp[i] = Math.min(dp[i], dp[i / j] + j); - } - } - } - return dp[n]; - } -} -``` - -```java -class Solution { - public int minSteps(int n) { - int res = 0; - for (int i = 2; n > 1; ++i) { - while (n % i == 0) { - res += i; - n /= i; - } - } - return res; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -169,27 +116,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minSteps(int n) { - vector dp(n + 1); - iota(dp.begin(), dp.end(), 0); - dp[1] = 0; - for (int i = 2; i < n + 1; ++i) { - for (int j = 2; j * j <= i; ++j) { - if (i % j == 0) { - dp[i] = min(dp[i], dp[i / j] + j); - } - } - } - return dp[n]; - } -}; -``` - -### **Go** - ```go func minSteps(n int) int { f := make([]int, n+1) @@ -216,6 +142,65 @@ func minSteps(n int) int { } ``` + + +### Solution 2 + + + +```python +class Solution: + def minSteps(self, n: int) -> int: + dp = list(range(n + 1)) + dp[1] = 0 + for i in range(2, n + 1): + j = 2 + while j * j <= i: + if i % j == 0: + dp[i] = min(dp[i], dp[i // j] + j) + j += 1 + return dp[-1] +``` + +```java +class Solution { + public int minSteps(int n) { + int[] dp = new int[n + 1]; + for (int i = 0; i < n + 1; ++i) { + dp[i] = i; + } + dp[1] = 0; + for (int i = 2; i < n + 1; ++i) { + for (int j = 2; j * j <= i; ++j) { + if (i % j == 0) { + dp[i] = Math.min(dp[i], dp[i / j] + j); + } + } + } + return dp[n]; + } +} +``` + +```cpp +class Solution { +public: + int minSteps(int n) { + vector dp(n + 1); + iota(dp.begin(), dp.end(), 0); + dp[1] = 0; + for (int i = 2; i < n + 1; ++i) { + for (int j = 2; j * j <= i; ++j) { + if (i % j == 0) { + dp[i] = min(dp[i], dp[i / j] + j); + } + } + } + return dp[n]; + } +}; +``` + ```go func minSteps(n int) int { dp := make([]int, n+1) @@ -234,10 +219,27 @@ func minSteps(n int) int { } ``` -### **...** + -``` +### Solution 3 + + +```java +class Solution { + public int minSteps(int n) { + int res = 0; + for (int i = 2; n > 1; ++i) { + while (n % i == 0) { + res += i; + n /= i; + } + } + return res; + } +} ``` + + diff --git a/solution/0600-0699/0651.4 Keys Keyboard/README.md b/solution/0600-0699/0651.4 Keys Keyboard/README.md index 58e4994dad05f..c9694f631431b 100644 --- a/solution/0600-0699/0651.4 Keys Keyboard/README.md +++ b/solution/0600-0699/0651.4 Keys Keyboard/README.md @@ -49,9 +49,7 @@ A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 定义 $dp[i]$ 表示前 $i$ 个按键可以显示的最大个数。 @@ -64,10 +62,6 @@ A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V -### **Python3** - - - ```python class Solution: def maxA(self, n: int) -> int: @@ -78,10 +72,6 @@ class Solution: return dp[-1] ``` -### **Java** - - - ```java class Solution { public int maxA(int n) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func maxA(n int) int { dp := make([]int, n+1) @@ -134,10 +120,6 @@ func maxA(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0651.4 Keys Keyboard/README_EN.md b/solution/0600-0699/0651.4 Keys Keyboard/README_EN.md index e42183b52e70b..96d13c631499b 100644 --- a/solution/0600-0699/0651.4 Keys Keyboard/README_EN.md +++ b/solution/0600-0699/0651.4 Keys Keyboard/README_EN.md @@ -43,9 +43,9 @@ A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return dp[-1] ``` -### **Java** - ```java class Solution { public int maxA(int n) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +90,6 @@ public: }; ``` -### **Go** - ```go func maxA(n int) int { dp := make([]int, n+1) @@ -111,10 +105,6 @@ func maxA(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0652.Find Duplicate Subtrees/README.md b/solution/0600-0699/0652.Find Duplicate Subtrees/README.md index 810419a2cc6ab..426b9a7d1e4fc 100644 --- a/solution/0600-0699/0652.Find Duplicate Subtrees/README.md +++ b/solution/0600-0699/0652.Find Duplicate Subtrees/README.md @@ -49,18 +49,12 @@ ## 解法 - - -**方法一:后序遍历** +### 方法一:后序遍历 后序遍历,序列化每个子树,用哈希表判断序列化的字符串出现次数是否等于 `2`,若是,说明这棵子树重复。 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -166,8 +154,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -197,8 +183,6 @@ func findDuplicateSubtrees(root *TreeNode) []*TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -234,8 +218,6 @@ function findDuplicateSubtrees(root: TreeNode | null): Array { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -295,10 +277,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0652.Find Duplicate Subtrees/README_EN.md b/solution/0600-0699/0652.Find Duplicate Subtrees/README_EN.md index d269b14006752..8c25c83cf9b34 100644 --- a/solution/0600-0699/0652.Find Duplicate Subtrees/README_EN.md +++ b/solution/0600-0699/0652.Find Duplicate Subtrees/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -72,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -115,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -149,8 +145,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -180,8 +174,6 @@ func findDuplicateSubtrees(root *TreeNode) []*TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -217,8 +209,6 @@ function findDuplicateSubtrees(root: TreeNode | null): Array { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -278,10 +268,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0653.Two Sum IV - Input is a BST/README.md b/solution/0600-0699/0653.Two Sum IV - Input is a BST/README.md index b7d1ceb4ad7e7..466f8e35708da 100644 --- a/solution/0600-0699/0653.Two Sum IV - Input is a BST/README.md +++ b/solution/0600-0699/0653.Two Sum IV - Input is a BST/README.md @@ -37,26 +37,14 @@ ## 解法 - - -**方法一:哈希表 + DFS** +### 方法一:哈希表 + DFS DFS 遍历二叉搜索树,对于每个节点,判断 `k - node.val` 是否在哈希表中,如果在,则返回 `true`,否则将 `node.val` 加入哈希表中。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉搜索树的节点个数。 -**方法二:哈希表 + BFS** - -与方法一类似,只是使用 BFS 遍历二叉搜索树。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉搜索树的节点个数。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -78,34 +66,6 @@ class Solution: return dfs(root) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def findTarget(self, root: Optional[TreeNode], k: int) -> bool: - q = deque([root]) - vis = set() - while q: - for _ in range(len(q)): - node = q.popleft() - if k - node.val in vis: - return True - vis.add(node.val) - if node.left: - q.append(node.left) - if node.right: - q.append(node.right) - return False -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -144,6 +104,172 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool findTarget(TreeNode* root, int k) { + unordered_set vis; + + function dfs = [&](TreeNode* root) { + if (!root) { + return false; + } + if (vis.count(k - root->val)) { + return true; + } + vis.insert(root->val); + return dfs(root->left) || dfs(root->right); + }; + return dfs(root); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func findTarget(root *TreeNode, k int) bool { + vis := map[int]bool{} + var dfs func(*TreeNode) bool + dfs = func(root *TreeNode) bool { + if root == nil { + return false + } + if vis[k-root.Val] { + return true + } + vis[root.Val] = true + return dfs(root.Left) || dfs(root.Right) + } + return dfs(root) +} +``` + +```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 findTarget(root: TreeNode | null, k: number): boolean { + const dfs = (root: TreeNode | null) => { + if (!root) { + return false; + } + if (vis.has(k - root.val)) { + return true; + } + vis.add(root.val); + return dfs(root.left) || dfs(root.right); + }; + const vis = new Set(); + return dfs(root); +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +use std::collections::{ HashSet, VecDeque }; +impl Solution { + pub fn find_target(root: Option>>, k: i32) -> bool { + let mut set = HashSet::new(); + let mut q = VecDeque::new(); + q.push_back(root); + while let Some(node) = q.pop_front() { + if let Some(node) = node { + let mut node = node.as_ref().borrow_mut(); + if set.contains(&node.val) { + return true; + } + set.insert(k - node.val); + q.push_back(node.left.take()); + q.push_back(node.right.take()); + } + } + false + } +} +``` + + + +### 方法二:哈希表 + BFS + +与方法一类似,只是使用 BFS 遍历二叉搜索树。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉搜索树的节点个数。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def findTarget(self, root: Optional[TreeNode], k: int) -> bool: + q = deque([root]) + vis = set() + while q: + for _ in range(len(q)): + node = q.popleft() + if k - node.val in vis: + return True + vis.add(node.val) + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + return False +``` + ```java /** * Definition for a binary tree node. @@ -185,40 +311,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool findTarget(TreeNode* root, int k) { - unordered_set vis; - - function dfs = [&](TreeNode* root) { - if (!root) { - return false; - } - if (vis.count(k - root->val)) { - return true; - } - vis.insert(root->val); - return dfs(root->left) || dfs(root->right); - }; - return dfs(root); - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -257,34 +349,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func findTarget(root *TreeNode, k int) bool { - vis := map[int]bool{} - var dfs func(*TreeNode) bool - dfs = func(root *TreeNode) bool { - if root == nil { - return false - } - if vis[k-root.Val] { - return true - } - vis[root.Val] = true - return dfs(root.Left) || dfs(root.Right) - } - return dfs(root) -} -``` - ```go /** * Definition for a binary tree node. @@ -317,39 +381,6 @@ func findTarget(root *TreeNode, k int) bool { } ``` -### **TypeScript** - -```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 findTarget(root: TreeNode | null, k: number): boolean { - const dfs = (root: TreeNode | null) => { - if (!root) { - return false; - } - if (vis.has(k - root.val)) { - return true; - } - vis.add(root.val); - return dfs(root.left) || dfs(root.right); - }; - const vis = new Set(); - return dfs(root); -} -``` - ```ts /** * Definition for a binary tree node. @@ -383,55 +414,6 @@ function findTarget(root: TreeNode | null, k: number): boolean { } ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -use std::collections::{ HashSet, VecDeque }; -impl Solution { - pub fn find_target(root: Option>>, k: i32) -> bool { - let mut set = HashSet::new(); - let mut q = VecDeque::new(); - q.push_back(root); - while let Some(node) = q.pop_front() { - if let Some(node) = node { - let mut node = node.as_ref().borrow_mut(); - if set.contains(&node.val) { - return true; - } - set.insert(k - node.val); - q.push_back(node.left.take()); - q.push_back(node.right.take()); - } - } - false - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0653.Two Sum IV - Input is a BST/README_EN.md b/solution/0600-0699/0653.Two Sum IV - Input is a BST/README_EN.md index 1be43ca96ede0..f8b46901d1a33 100644 --- a/solution/0600-0699/0653.Two Sum IV - Input is a BST/README_EN.md +++ b/solution/0600-0699/0653.Two Sum IV - Input is a BST/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -58,32 +58,6 @@ class Solution: return dfs(root) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def findTarget(self, root: Optional[TreeNode], k: int) -> bool: - q = deque([root]) - vis = set() - while q: - for _ in range(len(q)): - node = q.popleft() - if k - node.val in vis: - return True - vis.add(node.val) - if node.left: - q.append(node.left) - if node.right: - q.append(node.right) - return False -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -122,6 +96,168 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool findTarget(TreeNode* root, int k) { + unordered_set vis; + + function dfs = [&](TreeNode* root) { + if (!root) { + return false; + } + if (vis.count(k - root->val)) { + return true; + } + vis.insert(root->val); + return dfs(root->left) || dfs(root->right); + }; + return dfs(root); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func findTarget(root *TreeNode, k int) bool { + vis := map[int]bool{} + var dfs func(*TreeNode) bool + dfs = func(root *TreeNode) bool { + if root == nil { + return false + } + if vis[k-root.Val] { + return true + } + vis[root.Val] = true + return dfs(root.Left) || dfs(root.Right) + } + return dfs(root) +} +``` + +```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 findTarget(root: TreeNode | null, k: number): boolean { + const dfs = (root: TreeNode | null) => { + if (!root) { + return false; + } + if (vis.has(k - root.val)) { + return true; + } + vis.add(root.val); + return dfs(root.left) || dfs(root.right); + }; + const vis = new Set(); + return dfs(root); +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +use std::collections::{ HashSet, VecDeque }; +impl Solution { + pub fn find_target(root: Option>>, k: i32) -> bool { + let mut set = HashSet::new(); + let mut q = VecDeque::new(); + q.push_back(root); + while let Some(node) = q.pop_front() { + if let Some(node) = node { + let mut node = node.as_ref().borrow_mut(); + if set.contains(&node.val) { + return true; + } + set.insert(k - node.val); + q.push_back(node.left.take()); + q.push_back(node.right.take()); + } + } + false + } +} +``` + + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def findTarget(self, root: Optional[TreeNode], k: int) -> bool: + q = deque([root]) + vis = set() + while q: + for _ in range(len(q)): + node = q.popleft() + if k - node.val in vis: + return True + vis.add(node.val) + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + return False +``` + ```java /** * Definition for a binary tree node. @@ -163,40 +299,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool findTarget(TreeNode* root, int k) { - unordered_set vis; - - function dfs = [&](TreeNode* root) { - if (!root) { - return false; - } - if (vis.count(k - root->val)) { - return true; - } - vis.insert(root->val); - return dfs(root->left) || dfs(root->right); - }; - return dfs(root); - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -235,34 +337,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func findTarget(root *TreeNode, k int) bool { - vis := map[int]bool{} - var dfs func(*TreeNode) bool - dfs = func(root *TreeNode) bool { - if root == nil { - return false - } - if vis[k-root.Val] { - return true - } - vis[root.Val] = true - return dfs(root.Left) || dfs(root.Right) - } - return dfs(root) -} -``` - ```go /** * Definition for a binary tree node. @@ -295,39 +369,6 @@ func findTarget(root *TreeNode, k int) bool { } ``` -### **TypeScript** - -```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 findTarget(root: TreeNode | null, k: number): boolean { - const dfs = (root: TreeNode | null) => { - if (!root) { - return false; - } - if (vis.has(k - root.val)) { - return true; - } - vis.add(root.val); - return dfs(root.left) || dfs(root.right); - }; - const vis = new Set(); - return dfs(root); -} -``` - ```ts /** * Definition for a binary tree node. @@ -361,55 +402,6 @@ function findTarget(root: TreeNode | null, k: number): boolean { } ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -use std::collections::{ HashSet, VecDeque }; -impl Solution { - pub fn find_target(root: Option>>, k: i32) -> bool { - let mut set = HashSet::new(); - let mut q = VecDeque::new(); - q.push_back(root); - while let Some(node) = q.pop_front() { - if let Some(node) = node { - let mut node = node.as_ref().borrow_mut(); - if set.contains(&node.val) { - return true; - } - set.insert(k - node.val); - q.push_back(node.left.take()); - q.push_back(node.right.take()); - } - } - false - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0654.Maximum Binary Tree/README.md b/solution/0600-0699/0654.Maximum Binary Tree/README.md index 2c0cccfb4257b..c05916de768aa 100644 --- a/solution/0600-0699/0654.Maximum Binary Tree/README.md +++ b/solution/0600-0699/0654.Maximum Binary Tree/README.md @@ -54,40 +54,14 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 先找到数组 $nums$ 的最大元素所在的位置 $i$,将 $nums[i]$ 作为根节点,然后递归左右两侧的子数组,构建左右子树。 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$,其中 $n$ 是数组的长度。 -**方法二:线段树** - -方法一中,每次查找区间最大值,需要 $O(n)$ 的时间,我们可以借助线段树,将每次查询区间最大值的时间降至 $O(\log n)$。 - -最多需要查询 $n$ 次,因此,总的时间复杂度为 $O(n \times \log n)$,空间复杂度 $O(n)$,其中 $n$ 是数组的长度。 - -**方法三:单调栈** - -题目表达了一个意思:如果 $nums$ 中间有一个数字 $v$,找出它左右两侧最大的数,这两个最大的数应该比 $v$ 小。 - -了解单调栈的朋友,或许会注意到: - -当我们尝试向栈中压入一个数字 $v$ 时,如果栈顶元素比 $v$ 小,则循环弹出栈顶元素,并记录最后一个弹出的元素 $last$。那么循环结束,$last$ 必须位于 $v$ 的左侧,因为 $last$ 是 $v$ 的左侧最大的数。令 $node(val=v).left$ 指向 $last$。 - -如果此时存在栈顶元素,栈顶元素一定大于 $v$。$v$ 成为栈顶元素的候选右子树节点。令 $stk.top().right$ 指向 $v$。然后 $v$ 入栈。 - -遍历结束,栈底元素成为树的根节点。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -110,6 +84,236 @@ class Solution: return dfs(nums) ``` +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int[] nums; + + public TreeNode constructMaximumBinaryTree(int[] nums) { + this.nums = nums; + return dfs(0, nums.length - 1); + } + + private TreeNode dfs(int l, int r) { + if (l > r) { + return null; + } + int i = l; + for (int j = l; j <= r; ++j) { + if (nums[i] < nums[j]) { + i = j; + } + } + TreeNode root = new TreeNode(nums[i]); + root.left = dfs(l, i - 1); + root.right = dfs(i + 1, r); + return root; + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* constructMaximumBinaryTree(vector& nums) { + return dfs(nums, 0, nums.size() - 1); + } + + TreeNode* dfs(vector& nums, int l, int r) { + if (l > r) return nullptr; + int i = l; + for (int j = l; j <= r; ++j) { + if (nums[i] < nums[j]) { + i = j; + } + } + TreeNode* root = new TreeNode(nums[i]); + root->left = dfs(nums, l, i - 1); + root->right = dfs(nums, i + 1, r); + return root; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func constructMaximumBinaryTree(nums []int) *TreeNode { + var dfs func(l, r int) *TreeNode + dfs = func(l, r int) *TreeNode { + if l > r { + return nil + } + i := l + for j := l; j <= r; j++ { + if nums[i] < nums[j] { + i = j + } + } + root := &TreeNode{Val: nums[i]} + root.Left = dfs(l, i-1) + root.Right = dfs(i+1, r) + return root + } + return dfs(0, len(nums)-1) +} +``` + +```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 constructMaximumBinaryTree(nums: number[]): TreeNode | null { + const n = nums.length; + if (n === 0) { + return null; + } + const [val, i] = nums.reduce((r, v, i) => (r[0] < v ? [v, i] : r), [-1, 0]); + return new TreeNode( + val, + constructMaximumBinaryTree(nums.slice(0, i)), + constructMaximumBinaryTree(nums.slice(i + 1)), + ); +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn construct(nums: &Vec, start: usize, end: usize) -> Option>> { + if start >= end { + return None; + } + let mut idx = 0; + let mut max_val = -1; + for i in start..end { + if nums[i] > max_val { + idx = i; + max_val = nums[i]; + } + } + Some( + Rc::new( + RefCell::new(TreeNode { + val: max_val, + left: Self::construct(nums, start, idx), + right: Self::construct(nums, idx + 1, end), + }) + ) + ) + } + + pub fn construct_maximum_binary_tree(nums: Vec) -> Option>> { + Self::construct(&nums, 0, nums.len()) + } +} +``` + +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +struct TreeNode* construct(int* nums, int start, int end) { + if (start >= end) { + return NULL; + } + int idx = 0; + int maxVal = -1; + for (int i = start; i < end; i++) { + if (nums[i] > maxVal) { + idx = i; + maxVal = nums[i]; + } + } + struct TreeNode* res = (struct TreeNode*) malloc(sizeof(struct TreeNode)); + res->val = maxVal; + res->left = construct(nums, start, idx); + res->right = construct(nums, idx + 1, end); + return res; +} + +struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize) { + return construct(nums, 0, numsSize); +} +``` + + + +### 方法二:线段树 + +方法一中,每次查找区间最大值,需要 $O(n)$ 的时间,我们可以借助线段树,将每次查询区间最大值的时间降至 $O(\log n)$。 + +最多需要查询 $n$ 次,因此,总的时间复杂度为 $O(n \times \log n)$,空间复杂度 $O(n)$,其中 $n$ 是数组的长度。 + + + ```python # Definition for a binary tree node. # class TreeNode: @@ -172,74 +376,6 @@ class SegmentTree: self.tr[u].v = max(self.tr[u << 1].v, self.tr[u << 1 | 1].v) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]: - stk = [] - for v in nums: - node = TreeNode(v) - last = None - while stk and stk[-1].val < v: - last = stk.pop() - node.left = last - if stk: - stk[-1].right = node - stk.append(node) - return stk[0] -``` - -### **Java** - - - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private int[] nums; - - public TreeNode constructMaximumBinaryTree(int[] nums) { - this.nums = nums; - return dfs(0, nums.length - 1); - } - - private TreeNode dfs(int l, int r) { - if (l > r) { - return null; - } - int i = l; - for (int j = l; j <= r; ++j) { - if (nums[i] < nums[j]) { - i = j; - } - } - TreeNode root = new TreeNode(nums[i]); - root.left = dfs(l, i - 1); - root.right = dfs(i + 1, r); - return root; - } -} -``` - ```java /** * Definition for a binary tree node. @@ -337,78 +473,6 @@ class SegmentTree { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public TreeNode constructMaximumBinaryTree(int[] nums) { - Deque stk = new ArrayDeque<>(); - for (int v : nums) { - TreeNode node = new TreeNode(v); - TreeNode last = null; - while (!stk.isEmpty() && stk.peek().val < v) { - last = stk.pop(); - } - node.left = last; - if (!stk.isEmpty()) { - stk.peek().right = node; - } - stk.push(node); - } - return stk.getLast(); - } -} -``` - -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* constructMaximumBinaryTree(vector& nums) { - return dfs(nums, 0, nums.size() - 1); - } - - TreeNode* dfs(vector& nums, int l, int r) { - if (l > r) return nullptr; - int i = l; - for (int j = l; j <= r; ++j) { - if (nums[i] < nums[j]) { - i = j; - } - } - TreeNode* root = new TreeNode(nums[i]); - root->left = dfs(nums, l, i - 1); - root->right = dfs(nums, i + 1, r); - return root; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -471,96 +535,27 @@ public: SegmentTree* tree; vector nums; vector d; - - TreeNode* constructMaximumBinaryTree(vector& nums) { - tree = new SegmentTree(nums); - this->nums = nums; - d.assign(1010, 0); - int n = nums.size(); - for (int i = 0; i < n; ++i) d[nums[i]] = i + 1; - return dfs(1, nums.size()); - } - - TreeNode* dfs(int l, int r) { - if (l > r) { - return nullptr; - } - int val = tree->query(1, l, r); - TreeNode* root = new TreeNode(val); - root->left = dfs(l, d[val] - 1); - root->right = dfs(d[val] + 1, r); - return root; - } -}; -``` - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* constructMaximumBinaryTree(vector& nums) { - stack stk; - for (int v : nums) { - TreeNode* node = new TreeNode(v); - TreeNode* last = nullptr; - while (!stk.empty() && stk.top()->val < v) { - last = stk.top(); - stk.pop(); - } - node->left = last; - if (!stk.empty()) { - stk.top()->right = node; - } - stk.push(node); - } - while (stk.size() > 1) { - stk.pop(); - } - return stk.top(); - } -}; -``` - -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func constructMaximumBinaryTree(nums []int) *TreeNode { - var dfs func(l, r int) *TreeNode - dfs = func(l, r int) *TreeNode { - if l > r { - return nil - } - i := l - for j := l; j <= r; j++ { - if nums[i] < nums[j] { - i = j - } - } - root := &TreeNode{Val: nums[i]} - root.Left = dfs(l, i-1) - root.Right = dfs(i+1, r) - return root - } - return dfs(0, len(nums)-1) -} + + TreeNode* constructMaximumBinaryTree(vector& nums) { + tree = new SegmentTree(nums); + this->nums = nums; + d.assign(1010, 0); + int n = nums.size(); + for (int i = 0; i < n; ++i) d[nums[i]] = i + 1; + return dfs(1, nums.size()); + } + + TreeNode* dfs(int l, int r) { + if (l > r) { + return nullptr; + } + int val = tree->query(1, l, r); + TreeNode* root = new TreeNode(val); + root->left = dfs(l, d[val] - 1); + root->right = dfs(d[val] + 1, r); + return root; + } +}; ``` ```go @@ -647,6 +642,119 @@ func (t *segmentTree) pushup(u int) { } ``` + + +### 方法三:单调栈 + +题目表达了一个意思:如果 $nums$ 中间有一个数字 $v$,找出它左右两侧最大的数,这两个最大的数应该比 $v$ 小。 + +了解单调栈的朋友,或许会注意到: + +当我们尝试向栈中压入一个数字 $v$ 时,如果栈顶元素比 $v$ 小,则循环弹出栈顶元素,并记录最后一个弹出的元素 $last$。那么循环结束,$last$ 必须位于 $v$ 的左侧,因为 $last$ 是 $v$ 的左侧最大的数。令 $node(val=v).left$ 指向 $last$。 + +如果此时存在栈顶元素,栈顶元素一定大于 $v$。$v$ 成为栈顶元素的候选右子树节点。令 $stk.top().right$ 指向 $v$。然后 $v$ 入栈。 + +遍历结束,栈底元素成为树的根节点。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]: + stk = [] + for v in nums: + node = TreeNode(v) + last = None + while stk and stk[-1].val < v: + last = stk.pop() + node.left = last + if stk: + stk[-1].right = node + stk.append(node) + return stk[0] +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode constructMaximumBinaryTree(int[] nums) { + Deque stk = new ArrayDeque<>(); + for (int v : nums) { + TreeNode node = new TreeNode(v); + TreeNode last = null; + while (!stk.isEmpty() && stk.peek().val < v) { + last = stk.pop(); + } + node.left = last; + if (!stk.isEmpty()) { + stk.peek().right = node; + } + stk.push(node); + } + return stk.getLast(); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* constructMaximumBinaryTree(vector& nums) { + stack stk; + for (int v : nums) { + TreeNode* node = new TreeNode(v); + TreeNode* last = nullptr; + while (!stk.empty() && stk.top()->val < v) { + last = stk.top(); + stk.pop(); + } + node->left = last; + if (!stk.empty()) { + stk.top()->right = node; + } + stk.push(node); + } + while (stk.size() > 1) { + stk.pop(); + } + return stk.top(); + } +}; +``` + ```go /** * Definition for a binary tree node. @@ -675,130 +783,6 @@ func constructMaximumBinaryTree(nums []int) *TreeNode { } ``` -### **C** - -```c -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -struct TreeNode* construct(int* nums, int start, int end) { - if (start >= end) { - return NULL; - } - int idx = 0; - int maxVal = -1; - for (int i = start; i < end; i++) { - if (nums[i] > maxVal) { - idx = i; - maxVal = nums[i]; - } - } - struct TreeNode* res = (struct TreeNode*) malloc(sizeof(struct TreeNode)); - res->val = maxVal; - res->left = construct(nums, start, idx); - res->right = construct(nums, idx + 1, end); - return res; -} - -struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize) { - return construct(nums, 0, numsSize); -} -``` - -### **TypeScript** - -```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 constructMaximumBinaryTree(nums: number[]): TreeNode | null { - const n = nums.length; - if (n === 0) { - return null; - } - const [val, i] = nums.reduce((r, v, i) => (r[0] < v ? [v, i] : r), [-1, 0]); - return new TreeNode( - val, - constructMaximumBinaryTree(nums.slice(0, i)), - constructMaximumBinaryTree(nums.slice(i + 1)), - ); -} -``` - -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn construct(nums: &Vec, start: usize, end: usize) -> Option>> { - if start >= end { - return None; - } - let mut idx = 0; - let mut max_val = -1; - for i in start..end { - if nums[i] > max_val { - idx = i; - max_val = nums[i]; - } - } - Some( - Rc::new( - RefCell::new(TreeNode { - val: max_val, - left: Self::construct(nums, start, idx), - right: Self::construct(nums, idx + 1, end), - }) - ) - ) - } - - pub fn construct_maximum_binary_tree(nums: Vec) -> Option>> { - Self::construct(&nums, 0, nums.len()) - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0654.Maximum Binary Tree/README_EN.md b/solution/0600-0699/0654.Maximum Binary Tree/README_EN.md index 9f1b2c4120548..fe8374b95e377 100644 --- a/solution/0600-0699/0654.Maximum Binary Tree/README_EN.md +++ b/solution/0600-0699/0654.Maximum Binary Tree/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -76,6 +76,232 @@ class Solution: return dfs(nums) ``` +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int[] nums; + + public TreeNode constructMaximumBinaryTree(int[] nums) { + this.nums = nums; + return dfs(0, nums.length - 1); + } + + private TreeNode dfs(int l, int r) { + if (l > r) { + return null; + } + int i = l; + for (int j = l; j <= r; ++j) { + if (nums[i] < nums[j]) { + i = j; + } + } + TreeNode root = new TreeNode(nums[i]); + root.left = dfs(l, i - 1); + root.right = dfs(i + 1, r); + return root; + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* constructMaximumBinaryTree(vector& nums) { + return dfs(nums, 0, nums.size() - 1); + } + + TreeNode* dfs(vector& nums, int l, int r) { + if (l > r) return nullptr; + int i = l; + for (int j = l; j <= r; ++j) { + if (nums[i] < nums[j]) { + i = j; + } + } + TreeNode* root = new TreeNode(nums[i]); + root->left = dfs(nums, l, i - 1); + root->right = dfs(nums, i + 1, r); + return root; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func constructMaximumBinaryTree(nums []int) *TreeNode { + var dfs func(l, r int) *TreeNode + dfs = func(l, r int) *TreeNode { + if l > r { + return nil + } + i := l + for j := l; j <= r; j++ { + if nums[i] < nums[j] { + i = j + } + } + root := &TreeNode{Val: nums[i]} + root.Left = dfs(l, i-1) + root.Right = dfs(i+1, r) + return root + } + return dfs(0, len(nums)-1) +} +``` + +```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 constructMaximumBinaryTree(nums: number[]): TreeNode | null { + const n = nums.length; + if (n === 0) { + return null; + } + const [val, i] = nums.reduce((r, v, i) => (r[0] < v ? [v, i] : r), [-1, 0]); + return new TreeNode( + val, + constructMaximumBinaryTree(nums.slice(0, i)), + constructMaximumBinaryTree(nums.slice(i + 1)), + ); +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn construct(nums: &Vec, start: usize, end: usize) -> Option>> { + if start >= end { + return None; + } + let mut idx = 0; + let mut max_val = -1; + for i in start..end { + if nums[i] > max_val { + idx = i; + max_val = nums[i]; + } + } + Some( + Rc::new( + RefCell::new(TreeNode { + val: max_val, + left: Self::construct(nums, start, idx), + right: Self::construct(nums, idx + 1, end), + }) + ) + ) + } + + pub fn construct_maximum_binary_tree(nums: Vec) -> Option>> { + Self::construct(&nums, 0, nums.len()) + } +} +``` + +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +struct TreeNode* construct(int* nums, int start, int end) { + if (start >= end) { + return NULL; + } + int idx = 0; + int maxVal = -1; + for (int i = start; i < end; i++) { + if (nums[i] > maxVal) { + idx = i; + maxVal = nums[i]; + } + } + struct TreeNode* res = (struct TreeNode*) malloc(sizeof(struct TreeNode)); + res->val = maxVal; + res->left = construct(nums, start, idx); + res->right = construct(nums, idx + 1, end); + return res; +} + +struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize) { + return construct(nums, 0, numsSize); +} +``` + + + +### Solution 2 + + + ```python # Definition for a binary tree node. # class TreeNode: @@ -138,72 +364,6 @@ class SegmentTree: self.tr[u].v = max(self.tr[u << 1].v, self.tr[u << 1 | 1].v) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]: - stk = [] - for v in nums: - node = TreeNode(v) - last = None - while stk and stk[-1].val < v: - last = stk.pop() - node.left = last - if stk: - stk[-1].right = node - stk.append(node) - return stk[0] -``` - -### **Java** - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private int[] nums; - - public TreeNode constructMaximumBinaryTree(int[] nums) { - this.nums = nums; - return dfs(0, nums.length - 1); - } - - private TreeNode dfs(int l, int r) { - if (l > r) { - return null; - } - int i = l; - for (int j = l; j <= r; ++j) { - if (nums[i] < nums[j]) { - i = j; - } - } - TreeNode root = new TreeNode(nums[i]); - root.left = dfs(l, i - 1); - root.right = dfs(i + 1, r); - return root; - } -} -``` - ```java /** * Definition for a binary tree node. @@ -301,78 +461,6 @@ class SegmentTree { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public TreeNode constructMaximumBinaryTree(int[] nums) { - Deque stk = new ArrayDeque<>(); - for (int v : nums) { - TreeNode node = new TreeNode(v); - TreeNode last = null; - while (!stk.isEmpty() && stk.peek().val < v) { - last = stk.pop(); - } - node.left = last; - if (!stk.isEmpty()) { - stk.peek().right = node; - } - stk.push(node); - } - return stk.getLast(); - } -} -``` - -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* constructMaximumBinaryTree(vector& nums) { - return dfs(nums, 0, nums.size() - 1); - } - - TreeNode* dfs(vector& nums, int l, int r) { - if (l > r) return nullptr; - int i = l; - for (int j = l; j <= r; ++j) { - if (nums[i] < nums[j]) { - i = j; - } - } - TreeNode* root = new TreeNode(nums[i]); - root->left = dfs(nums, l, i - 1); - root->right = dfs(nums, i + 1, r); - return root; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -452,81 +540,12 @@ public: int val = tree->query(1, l, r); TreeNode* root = new TreeNode(val); root->left = dfs(l, d[val] - 1); - root->right = dfs(d[val] + 1, r); - return root; - } -}; -``` - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* constructMaximumBinaryTree(vector& nums) { - stack stk; - for (int v : nums) { - TreeNode* node = new TreeNode(v); - TreeNode* last = nullptr; - while (!stk.empty() && stk.top()->val < v) { - last = stk.top(); - stk.pop(); - } - node->left = last; - if (!stk.empty()) { - stk.top()->right = node; - } - stk.push(node); - } - while (stk.size() > 1) { - stk.pop(); - } - return stk.top(); + root->right = dfs(d[val] + 1, r); + return root; } }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func constructMaximumBinaryTree(nums []int) *TreeNode { - var dfs func(l, r int) *TreeNode - dfs = func(l, r int) *TreeNode { - if l > r { - return nil - } - i := l - for j := l; j <= r; j++ { - if nums[i] < nums[j] { - i = j - } - } - root := &TreeNode{Val: nums[i]} - root.Left = dfs(l, i-1) - root.Right = dfs(i+1, r) - return root - } - return dfs(0, len(nums)-1) -} -``` - ```go /** * Definition for a binary tree node. @@ -611,6 +630,107 @@ func (t *segmentTree) pushup(u int) { } ``` + + +### Solution 3 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]: + stk = [] + for v in nums: + node = TreeNode(v) + last = None + while stk and stk[-1].val < v: + last = stk.pop() + node.left = last + if stk: + stk[-1].right = node + stk.append(node) + return stk[0] +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode constructMaximumBinaryTree(int[] nums) { + Deque stk = new ArrayDeque<>(); + for (int v : nums) { + TreeNode node = new TreeNode(v); + TreeNode last = null; + while (!stk.isEmpty() && stk.peek().val < v) { + last = stk.pop(); + } + node.left = last; + if (!stk.isEmpty()) { + stk.peek().right = node; + } + stk.push(node); + } + return stk.getLast(); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* constructMaximumBinaryTree(vector& nums) { + stack stk; + for (int v : nums) { + TreeNode* node = new TreeNode(v); + TreeNode* last = nullptr; + while (!stk.empty() && stk.top()->val < v) { + last = stk.top(); + stk.pop(); + } + node->left = last; + if (!stk.empty()) { + stk.top()->right = node; + } + stk.push(node); + } + while (stk.size() > 1) { + stk.pop(); + } + return stk.top(); + } +}; +``` + ```go /** * Definition for a binary tree node. @@ -639,130 +759,6 @@ func constructMaximumBinaryTree(nums []int) *TreeNode { } ``` -### **C** - -```c -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -struct TreeNode* construct(int* nums, int start, int end) { - if (start >= end) { - return NULL; - } - int idx = 0; - int maxVal = -1; - for (int i = start; i < end; i++) { - if (nums[i] > maxVal) { - idx = i; - maxVal = nums[i]; - } - } - struct TreeNode* res = (struct TreeNode*) malloc(sizeof(struct TreeNode)); - res->val = maxVal; - res->left = construct(nums, start, idx); - res->right = construct(nums, idx + 1, end); - return res; -} - -struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize) { - return construct(nums, 0, numsSize); -} -``` - -### **TypeScript** - -```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 constructMaximumBinaryTree(nums: number[]): TreeNode | null { - const n = nums.length; - if (n === 0) { - return null; - } - const [val, i] = nums.reduce((r, v, i) => (r[0] < v ? [v, i] : r), [-1, 0]); - return new TreeNode( - val, - constructMaximumBinaryTree(nums.slice(0, i)), - constructMaximumBinaryTree(nums.slice(i + 1)), - ); -} -``` - -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn construct(nums: &Vec, start: usize, end: usize) -> Option>> { - if start >= end { - return None; - } - let mut idx = 0; - let mut max_val = -1; - for i in start..end { - if nums[i] > max_val { - idx = i; - max_val = nums[i]; - } - } - Some( - Rc::new( - RefCell::new(TreeNode { - val: max_val, - left: Self::construct(nums, start, idx), - right: Self::construct(nums, idx + 1, end), - }) - ) - ) - } - - pub fn construct_maximum_binary_tree(nums: Vec) -> Option>> { - Self::construct(&nums, 0, nums.len()) - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0655.Print Binary Tree/README.md b/solution/0600-0699/0655.Print Binary Tree/README.md index 5e313dd1a77e5..e6f6f49b04a8c 100644 --- a/solution/0600-0699/0655.Print Binary Tree/README.md +++ b/solution/0600-0699/0655.Print Binary Tree/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:两次 DFS** +### 方法一:两次 DFS 先通过 `DFS` 求二叉树的高度 $h$(高度从 `0` 开始),然后根据 $h$ 求得结果列表的行数 $m$ 和列数 $n$。 @@ -64,20 +62,8 @@ 时间复杂度 $O(h\times 2^h)$,空间复杂度 $O(h)$。其中 $h$ 是二叉树的高度。忽略结果返回值的空间消耗。 -**方法二:两次 BFS** - -方法一中,我们是通过 `DFS` 来求二叉树的高度,我们也可以改成 `BFS` 的方式,逐层往下扩展,那么扩展的层数就是二叉树的高度。 - -同样,我们初始化结果列表 `ans`,然后 `BFS` 遍历二叉树,依次在每个位置填入二叉树节点值(字符串形式)即可。 - -时间复杂度 $O(h\times 2^h)$,空间复杂度 $O(h)$。其中 $h$ 是二叉树的高度。忽略结果返回值的空间消耗。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -106,46 +92,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def printTree(self, root: Optional[TreeNode]) -> List[List[str]]: - def height(root): - q = deque([root]) - h = -1 - while q: - h += 1 - for _ in range(len(q)): - root = q.popleft() - if root.left: - q.append(root.left) - if root.right: - q.append(root.right) - return h - - h = height(root) - m, n = h + 1, 2 ** (h + 1) - 1 - ans = [[""] * n for _ in range(m)] - q = deque([(root, 0, (n - 1) // 2)]) - while q: - node, r, c = q.popleft() - ans[r][c] = str(node.val) - if node.left: - q.append((node.left, r + 1, c - 2 ** (h - r - 1))) - if node.right: - q.append((node.right, r + 1, c + 2 ** (h - r - 1))) - return ans -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -196,6 +142,229 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> printTree(TreeNode* root) { + int h = height(root); + int m = h + 1, n = (1 << (h + 1)) - 1; + vector> ans(m, vector(n, "")); + dfs(root, ans, h, 0, (n - 1) / 2); + return ans; + } + + void dfs(TreeNode* root, vector>& ans, int h, int r, int c) { + if (!root) return; + ans[r][c] = to_string(root->val); + dfs(root->left, ans, h, r + 1, c - pow(2, h - r - 1)); + dfs(root->right, ans, h, r + 1, c + pow(2, h - r - 1)); + } + + int height(TreeNode* root) { + if (!root) return -1; + return 1 + max(height(root->left), height(root->right)); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func printTree(root *TreeNode) [][]string { + var height func(root *TreeNode) int + height = func(root *TreeNode) int { + if root == nil { + return -1 + } + return 1 + max(height(root.Left), height(root.Right)) + } + h := height(root) + m, n := h+1, (1<<(h+1))-1 + ans := make([][]string, m) + for i := range ans { + ans[i] = make([]string, n) + for j := range ans[i] { + ans[i][j] = "" + } + } + var dfs func(root *TreeNode, r, c int) + dfs = func(root *TreeNode, r, c int) { + if root == nil { + return + } + ans[r][c] = strconv.Itoa(root.Val) + dfs(root.Left, r+1, c-int(math.Pow(float64(2), float64(h-r-1)))) + dfs(root.Right, r+1, c+int(math.Pow(float64(2), float64(h-r-1)))) + } + + dfs(root, 0, (n-1)/2) + return ans +} +``` + +```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 printTree(root: TreeNode | null): string[][] { + const getHeight = (root: TreeNode | null, h: number) => { + if (root == null) { + return h - 1; + } + return Math.max(getHeight(root.left, h + 1), getHeight(root.right, h + 1)); + }; + + const height = getHeight(root, 0); + const m = height + 1; + const n = 2 ** (height + 1) - 1; + const res: string[][] = Array.from({ length: m }, () => new Array(n).fill('')); + const dfs = (root: TreeNode | null, i: number, j: number) => { + if (root === null) { + return; + } + const { val, left, right } = root; + res[i][j] = val + ''; + dfs(left, i + 1, j - 2 ** (height - i - 1)); + dfs(right, i + 1, j + 2 ** (height - i - 1)); + }; + dfs(root, 0, (n - 1) >>> 1); + return res; +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn get_height(root: &Option>>, h: u32) -> u32 { + if let Some(node) = root { + let node = node.borrow(); + return Self::get_height(&node.left, h + 1).max(Self::get_height(&node.right, h + 1)); + } + h - 1 + } + + fn dfs( + root: &Option>>, + i: usize, + j: usize, + res: &mut Vec>, + height: u32 + ) { + if root.is_none() { + return; + } + let node = root.as_ref().unwrap().borrow(); + res[i][j] = node.val.to_string(); + Self::dfs(&node.left, i + 1, j - (2usize).pow(height - (i as u32) - 1), res, height); + Self::dfs(&node.right, i + 1, j + (2usize).pow(height - (i as u32) - 1), res, height); + } + + pub fn print_tree(root: Option>>) -> Vec> { + let height = Self::get_height(&root, 0); + let m = (height + 1) as usize; + let n = (2usize).pow(height + 1) - 1; + let mut res = vec![vec![String::new(); n]; m]; + Self::dfs(&root, 0, (n - 1) >> 1, &mut res, height); + res + } +} +``` + + + +### 方法二:两次 BFS + +方法一中,我们是通过 `DFS` 来求二叉树的高度,我们也可以改成 `BFS` 的方式,逐层往下扩展,那么扩展的层数就是二叉树的高度。 + +同样,我们初始化结果列表 `ans`,然后 `BFS` 遍历二叉树,依次在每个位置填入二叉树节点值(字符串形式)即可。 + +时间复杂度 $O(h\times 2^h)$,空间复杂度 $O(h)$。其中 $h$ 是二叉树的高度。忽略结果返回值的空间消耗。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def printTree(self, root: Optional[TreeNode]) -> List[List[str]]: + def height(root): + q = deque([root]) + h = -1 + while q: + h += 1 + for _ in range(len(q)): + root = q.popleft() + if root.left: + q.append(root.left) + if root.right: + q.append(root.right) + return h + + h = height(root) + m, n = h + 1, 2 ** (h + 1) - 1 + ans = [[""] * n for _ in range(m)] + q = deque([(root, 0, (n - 1) // 2)]) + while q: + node, r, c = q.popleft() + ans[r][c] = str(node.val) + if node.left: + q.append((node.left, r + 1, c - 2 ** (h - r - 1))) + if node.right: + q.append((node.right, r + 1, c + 2 ** (h - r - 1))) + return ans +``` + ```java /** * Definition for a binary tree node. @@ -274,44 +443,6 @@ class Tuple { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector> printTree(TreeNode* root) { - int h = height(root); - int m = h + 1, n = (1 << (h + 1)) - 1; - vector> ans(m, vector(n, "")); - dfs(root, ans, h, 0, (n - 1) / 2); - return ans; - } - - void dfs(TreeNode* root, vector>& ans, int h, int r, int c) { - if (!root) return; - ans[r][c] = to_string(root->val); - dfs(root->left, ans, h, r + 1, c - pow(2, h - r - 1)); - dfs(root->right, ans, h, r + 1, c + pow(2, h - r - 1)); - } - - int height(TreeNode* root) { - if (!root) return -1; - return 1 + max(height(root->left), height(root->right)); - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -361,49 +492,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func printTree(root *TreeNode) [][]string { - var height func(root *TreeNode) int - height = func(root *TreeNode) int { - if root == nil { - return -1 - } - return 1 + max(height(root.Left), height(root.Right)) - } - h := height(root) - m, n := h+1, (1<<(h+1))-1 - ans := make([][]string, m) - for i := range ans { - ans[i] = make([]string, n) - for j := range ans[i] { - ans[i][j] = "" - } - } - var dfs func(root *TreeNode, r, c int) - dfs = func(root *TreeNode, r, c int) { - if root == nil { - return - } - ans[r][c] = strconv.Itoa(root.Val) - dfs(root.Left, r+1, c-int(math.Pow(float64(2), float64(h-r-1)))) - dfs(root.Right, r+1, c+int(math.Pow(float64(2), float64(h-r-1)))) - } - - dfs(root, 0, (n-1)/2) - return ans -} -``` - ```go /** * Definition for a binary tree node. @@ -466,112 +554,6 @@ type tuple struct { } ``` -### **TypeScript** - -```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 printTree(root: TreeNode | null): string[][] { - const getHeight = (root: TreeNode | null, h: number) => { - if (root == null) { - return h - 1; - } - return Math.max(getHeight(root.left, h + 1), getHeight(root.right, h + 1)); - }; - - const height = getHeight(root, 0); - const m = height + 1; - const n = 2 ** (height + 1) - 1; - const res: string[][] = Array.from({ length: m }, () => new Array(n).fill('')); - const dfs = (root: TreeNode | null, i: number, j: number) => { - if (root === null) { - return; - } - const { val, left, right } = root; - res[i][j] = val + ''; - dfs(left, i + 1, j - 2 ** (height - i - 1)); - dfs(right, i + 1, j + 2 ** (height - i - 1)); - }; - dfs(root, 0, (n - 1) >>> 1); - return res; -} -``` - -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn get_height(root: &Option>>, h: u32) -> u32 { - if let Some(node) = root { - let node = node.borrow(); - return Self::get_height(&node.left, h + 1).max(Self::get_height(&node.right, h + 1)); - } - h - 1 - } - - fn dfs( - root: &Option>>, - i: usize, - j: usize, - res: &mut Vec>, - height: u32 - ) { - if root.is_none() { - return; - } - let node = root.as_ref().unwrap().borrow(); - res[i][j] = node.val.to_string(); - Self::dfs(&node.left, i + 1, j - (2usize).pow(height - (i as u32) - 1), res, height); - Self::dfs(&node.right, i + 1, j + (2usize).pow(height - (i as u32) - 1), res, height); - } - - pub fn print_tree(root: Option>>) -> Vec> { - let height = Self::get_height(&root, 0); - let m = (height + 1) as usize; - let n = (2usize).pow(height + 1) - 1; - let mut res = vec![vec![String::new(); n]; m]; - Self::dfs(&root, 0, (n - 1) >> 1, &mut res, height); - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0655.Print Binary Tree/README_EN.md b/solution/0600-0699/0655.Print Binary Tree/README_EN.md index ee288a40e56e5..38008817c2460 100644 --- a/solution/0600-0699/0655.Print Binary Tree/README_EN.md +++ b/solution/0600-0699/0655.Print Binary Tree/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -80,44 +80,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def printTree(self, root: Optional[TreeNode]) -> List[List[str]]: - def height(root): - q = deque([root]) - h = -1 - while q: - h += 1 - for _ in range(len(q)): - root = q.popleft() - if root.left: - q.append(root.left) - if root.right: - q.append(root.right) - return h - - h = height(root) - m, n = h + 1, 2 ** (h + 1) - 1 - ans = [[""] * n for _ in range(m)] - q = deque([(root, 0, (n - 1) // 2)]) - while q: - node, r, c = q.popleft() - ans[r][c] = str(node.val) - if node.left: - q.append((node.left, r + 1, c - 2 ** (h - r - 1))) - if node.right: - q.append((node.right, r + 1, c + 2 ** (h - r - 1))) - return ans -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -168,6 +130,223 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> printTree(TreeNode* root) { + int h = height(root); + int m = h + 1, n = (1 << (h + 1)) - 1; + vector> ans(m, vector(n, "")); + dfs(root, ans, h, 0, (n - 1) / 2); + return ans; + } + + void dfs(TreeNode* root, vector>& ans, int h, int r, int c) { + if (!root) return; + ans[r][c] = to_string(root->val); + dfs(root->left, ans, h, r + 1, c - pow(2, h - r - 1)); + dfs(root->right, ans, h, r + 1, c + pow(2, h - r - 1)); + } + + int height(TreeNode* root) { + if (!root) return -1; + return 1 + max(height(root->left), height(root->right)); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func printTree(root *TreeNode) [][]string { + var height func(root *TreeNode) int + height = func(root *TreeNode) int { + if root == nil { + return -1 + } + return 1 + max(height(root.Left), height(root.Right)) + } + h := height(root) + m, n := h+1, (1<<(h+1))-1 + ans := make([][]string, m) + for i := range ans { + ans[i] = make([]string, n) + for j := range ans[i] { + ans[i][j] = "" + } + } + var dfs func(root *TreeNode, r, c int) + dfs = func(root *TreeNode, r, c int) { + if root == nil { + return + } + ans[r][c] = strconv.Itoa(root.Val) + dfs(root.Left, r+1, c-int(math.Pow(float64(2), float64(h-r-1)))) + dfs(root.Right, r+1, c+int(math.Pow(float64(2), float64(h-r-1)))) + } + + dfs(root, 0, (n-1)/2) + return ans +} +``` + +```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 printTree(root: TreeNode | null): string[][] { + const getHeight = (root: TreeNode | null, h: number) => { + if (root == null) { + return h - 1; + } + return Math.max(getHeight(root.left, h + 1), getHeight(root.right, h + 1)); + }; + + const height = getHeight(root, 0); + const m = height + 1; + const n = 2 ** (height + 1) - 1; + const res: string[][] = Array.from({ length: m }, () => new Array(n).fill('')); + const dfs = (root: TreeNode | null, i: number, j: number) => { + if (root === null) { + return; + } + const { val, left, right } = root; + res[i][j] = val + ''; + dfs(left, i + 1, j - 2 ** (height - i - 1)); + dfs(right, i + 1, j + 2 ** (height - i - 1)); + }; + dfs(root, 0, (n - 1) >>> 1); + return res; +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn get_height(root: &Option>>, h: u32) -> u32 { + if let Some(node) = root { + let node = node.borrow(); + return Self::get_height(&node.left, h + 1).max(Self::get_height(&node.right, h + 1)); + } + h - 1 + } + + fn dfs( + root: &Option>>, + i: usize, + j: usize, + res: &mut Vec>, + height: u32 + ) { + if root.is_none() { + return; + } + let node = root.as_ref().unwrap().borrow(); + res[i][j] = node.val.to_string(); + Self::dfs(&node.left, i + 1, j - (2usize).pow(height - (i as u32) - 1), res, height); + Self::dfs(&node.right, i + 1, j + (2usize).pow(height - (i as u32) - 1), res, height); + } + + pub fn print_tree(root: Option>>) -> Vec> { + let height = Self::get_height(&root, 0); + let m = (height + 1) as usize; + let n = (2usize).pow(height + 1) - 1; + let mut res = vec![vec![String::new(); n]; m]; + Self::dfs(&root, 0, (n - 1) >> 1, &mut res, height); + res + } +} +``` + + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def printTree(self, root: Optional[TreeNode]) -> List[List[str]]: + def height(root): + q = deque([root]) + h = -1 + while q: + h += 1 + for _ in range(len(q)): + root = q.popleft() + if root.left: + q.append(root.left) + if root.right: + q.append(root.right) + return h + + h = height(root) + m, n = h + 1, 2 ** (h + 1) - 1 + ans = [[""] * n for _ in range(m)] + q = deque([(root, 0, (n - 1) // 2)]) + while q: + node, r, c = q.popleft() + ans[r][c] = str(node.val) + if node.left: + q.append((node.left, r + 1, c - 2 ** (h - r - 1))) + if node.right: + q.append((node.right, r + 1, c + 2 ** (h - r - 1))) + return ans +``` + ```java /** * Definition for a binary tree node. @@ -246,44 +425,6 @@ class Tuple { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - vector> printTree(TreeNode* root) { - int h = height(root); - int m = h + 1, n = (1 << (h + 1)) - 1; - vector> ans(m, vector(n, "")); - dfs(root, ans, h, 0, (n - 1) / 2); - return ans; - } - - void dfs(TreeNode* root, vector>& ans, int h, int r, int c) { - if (!root) return; - ans[r][c] = to_string(root->val); - dfs(root->left, ans, h, r + 1, c - pow(2, h - r - 1)); - dfs(root->right, ans, h, r + 1, c + pow(2, h - r - 1)); - } - - int height(TreeNode* root) { - if (!root) return -1; - return 1 + max(height(root->left), height(root->right)); - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -333,49 +474,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func printTree(root *TreeNode) [][]string { - var height func(root *TreeNode) int - height = func(root *TreeNode) int { - if root == nil { - return -1 - } - return 1 + max(height(root.Left), height(root.Right)) - } - h := height(root) - m, n := h+1, (1<<(h+1))-1 - ans := make([][]string, m) - for i := range ans { - ans[i] = make([]string, n) - for j := range ans[i] { - ans[i][j] = "" - } - } - var dfs func(root *TreeNode, r, c int) - dfs = func(root *TreeNode, r, c int) { - if root == nil { - return - } - ans[r][c] = strconv.Itoa(root.Val) - dfs(root.Left, r+1, c-int(math.Pow(float64(2), float64(h-r-1)))) - dfs(root.Right, r+1, c+int(math.Pow(float64(2), float64(h-r-1)))) - } - - dfs(root, 0, (n-1)/2) - return ans -} -``` - ```go /** * Definition for a binary tree node. @@ -438,112 +536,6 @@ type tuple struct { } ``` -### **TypeScript** - -```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 printTree(root: TreeNode | null): string[][] { - const getHeight = (root: TreeNode | null, h: number) => { - if (root == null) { - return h - 1; - } - return Math.max(getHeight(root.left, h + 1), getHeight(root.right, h + 1)); - }; - - const height = getHeight(root, 0); - const m = height + 1; - const n = 2 ** (height + 1) - 1; - const res: string[][] = Array.from({ length: m }, () => new Array(n).fill('')); - const dfs = (root: TreeNode | null, i: number, j: number) => { - if (root === null) { - return; - } - const { val, left, right } = root; - res[i][j] = val + ''; - dfs(left, i + 1, j - 2 ** (height - i - 1)); - dfs(right, i + 1, j + 2 ** (height - i - 1)); - }; - dfs(root, 0, (n - 1) >>> 1); - return res; -} -``` - -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn get_height(root: &Option>>, h: u32) -> u32 { - if let Some(node) = root { - let node = node.borrow(); - return Self::get_height(&node.left, h + 1).max(Self::get_height(&node.right, h + 1)); - } - h - 1 - } - - fn dfs( - root: &Option>>, - i: usize, - j: usize, - res: &mut Vec>, - height: u32 - ) { - if root.is_none() { - return; - } - let node = root.as_ref().unwrap().borrow(); - res[i][j] = node.val.to_string(); - Self::dfs(&node.left, i + 1, j - (2usize).pow(height - (i as u32) - 1), res, height); - Self::dfs(&node.right, i + 1, j + (2usize).pow(height - (i as u32) - 1), res, height); - } - - pub fn print_tree(root: Option>>) -> Vec> { - let height = Self::get_height(&root, 0); - let m = (height + 1) as usize; - let n = (2usize).pow(height + 1) - 1; - let mut res = vec![vec![String::new(); n]; m]; - Self::dfs(&root, 0, (n - 1) >> 1, &mut res, height); - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0656.Coin Path/README.md b/solution/0600-0699/0656.Coin Path/README.md index 3abcd2a9d2d71..7ab45f9184607 100644 --- a/solution/0600-0699/0656.Coin Path/README.md +++ b/solution/0600-0699/0656.Coin Path/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:动态规划(逆向)** +### 方法一:动态规划(逆向) 题目需要我们找到从下标 1 到下标 n 的最小花费路径,且字典序最小,我们可以使用动态规划求解。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def cheapestJump(self, coins: List[int], maxJump: int) -> List[int]: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List cheapestJump(int[] coins, int maxJump) { @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +152,6 @@ public: }; ``` -### **Go** - ```go func cheapestJump(coins []int, maxJump int) (ans []int) { n := len(coins) @@ -198,8 +184,6 @@ func cheapestJump(coins []int, maxJump int) (ans []int) { } ``` -### **TypeScript** - ```ts function cheapestJump(coins: number[], maxJump: number): number[] { const n = coins.length; @@ -230,10 +214,6 @@ function cheapestJump(coins: number[], maxJump: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0656.Coin Path/README_EN.md b/solution/0600-0699/0656.Coin Path/README_EN.md index db06a9bfa9de3..60c0c49257745 100644 --- a/solution/0600-0699/0656.Coin Path/README_EN.md +++ b/solution/0600-0699/0656.Coin Path/README_EN.md @@ -32,9 +32,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List cheapestJump(int[] coins, int maxJump) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +129,6 @@ public: }; ``` -### **Go** - ```go func cheapestJump(coins []int, maxJump int) (ans []int) { n := len(coins) @@ -167,8 +161,6 @@ func cheapestJump(coins []int, maxJump int) (ans []int) { } ``` -### **TypeScript** - ```ts function cheapestJump(coins: number[], maxJump: number): number[] { const n = coins.length; @@ -199,10 +191,6 @@ function cheapestJump(coins: number[], maxJump: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0657.Robot Return to Origin/README.md b/solution/0600-0699/0657.Robot Return to Origin/README.md index 3de316fb18f47..f5121834c8ee2 100644 --- a/solution/0600-0699/0657.Robot Return to Origin/README.md +++ b/solution/0600-0699/0657.Robot Return to Origin/README.md @@ -41,14 +41,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def judgeCircle(self, moves: str) -> bool: @@ -65,10 +61,6 @@ class Solution: return x == 0 and y == 0 ``` -### **Java** - - - ```java class Solution { public boolean judgeCircle(String moves) { @@ -89,8 +81,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function judgeCircle(moves: string): boolean { let x = 0, @@ -110,10 +100,6 @@ function judgeCircle(moves: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0657.Robot Return to Origin/README_EN.md b/solution/0600-0699/0657.Robot Return to Origin/README_EN.md index a45d1f6368e6e..9b5b3c2291b78 100644 --- a/solution/0600-0699/0657.Robot Return to Origin/README_EN.md +++ b/solution/0600-0699/0657.Robot Return to Origin/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return x == 0 and y == 0 ``` -### **Java** - ```java class Solution { public boolean judgeCircle(String moves) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function judgeCircle(moves: string): boolean { let x = 0, @@ -102,10 +98,6 @@ function judgeCircle(moves: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0658.Find K Closest Elements/README.md b/solution/0600-0699/0658.Find K Closest Elements/README.md index 1b8a0612ecf76..eda6ace213de9 100644 --- a/solution/0600-0699/0658.Find K Closest Elements/README.md +++ b/solution/0600-0699/0658.Find K Closest Elements/README.md @@ -44,34 +44,14 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 将 $arr$ 中的所有元素按照与 $x$ 的距离从小到大进行排列。取前 $k$ 个元素排序后返回。 时间复杂度 $O(nlogn)$。 -**方法二:双指针** - -直觉上,有序数组 $arr$ 最靠近 $x$ 的 $k$ 个数必然是一段连续的子数组。 - -我们可以声明头尾指针,记为 $l$ 和 $r$,然后根据 $x-arr[l]$ 与 $arr[r-1] - x$ 的大小比较结果缩小范围,直到 $r - l = k$。 - -时间复杂度 $O(n)$。 - -**方法三:二分查找** - -在方法二的基础上,我们更进一步,查找大小为 $k$ 的窗口的左边界。 - -时间复杂度 $O(logn)$。 - -### **Python3** - - - ```python class Solution: def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: @@ -79,35 +59,6 @@ class Solution: return sorted(arr[:k]) ``` -```python -class Solution: - def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: - l, r = 0, len(arr) - while r - l > k: - if x - arr[l] <= arr[r - 1] - x: - r -= 1 - else: - l += 1 - return arr[l:r] -``` - -```python -class Solution: - def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: - left, right = 0, len(arr) - k - while left < right: - mid = (left + right) >> 1 - if x - arr[mid] <= arr[mid + k] - x: - right = mid - else: - left = mid + 1 - return arr[left : left + k] -``` - -### **Java** - - - ```java class Solution { public List findClosestElements(int[] arr, int k, int x) { @@ -125,50 +76,6 @@ class Solution { } ``` -```java -class Solution { - public List findClosestElements(int[] arr, int k, int x) { - int l = 0, r = arr.length; - while (r - l > k) { - if (x - arr[l] <= arr[r - 1] - x) { - --r; - } else { - ++l; - } - } - List ans = new ArrayList<>(); - for (int i = l; i < r; ++i) { - ans.add(arr[i]); - } - return ans; - } -} -``` - -```java -class Solution { - public List findClosestElements(int[] arr, int k, int x) { - int left = 0; - int right = arr.length - k; - while (left < right) { - int mid = (left + right) >> 1; - if (x - arr[mid] <= arr[mid + k] - x) { - right = mid; - } else { - left = mid + 1; - } - } - List ans = new ArrayList<>(); - for (int i = left; i < left + k; ++i) { - ans.add(arr[i]); - } - return ans; - } -} -``` - -### **C++** - ```cpp int target; @@ -189,42 +96,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector findClosestElements(vector& arr, int k, int x) { - int l = 0, r = arr.size(); - while (r - l > k) { - if (x - arr[l] <= arr[r - 1] - x) { - --r; - } else { - ++l; - } - } - return vector(arr.begin() + l, arr.begin() + r); - } -}; -``` - -```cpp -class Solution { -public: - vector findClosestElements(vector& arr, int k, int x) { - int left = 0, right = arr.size() - k; - while (left < right) { - int mid = (left + right) >> 1; - if (x - arr[mid] <= arr[mid + k] - x) - right = mid; - else - left = mid + 1; - } - return vector(arr.begin() + left, arr.begin() + left + k); - } -}; -``` - -### **Go** - ```go func findClosestElements(arr []int, k int, x int) []int { sort.Slice(arr, func(i, j int) bool { @@ -247,37 +118,21 @@ func abs(x int) int { } ``` -```go -func findClosestElements(arr []int, k int, x int) []int { - l, r := 0, len(arr) - for r-l > k { - if x-arr[l] <= arr[r-1]-x { - r-- - } else { - l++ - } - } - return arr[l:r] -} -``` - -```go -func findClosestElements(arr []int, k int, x int) []int { - left, right := 0, len(arr)-k - for left < right { - mid := (left + right) >> 1 - if x-arr[mid] <= arr[mid+k]-x { - right = mid - } else { - left = mid + 1 - } - } - return arr[left : left+k] +```ts +function findClosestElements(arr: number[], k: number, x: number): number[] { + let l = 0; + let r = arr.length; + while (r - l > k) { + if (x - arr[l] <= arr[r - 1] - x) { + --r; + } else { + ++l; + } + } + return arr.slice(l, r); } ``` -### **Rust** - ```rust impl Solution { pub fn find_closest_elements(arr: Vec, k: i32, x: i32) -> Vec { @@ -296,40 +151,78 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn find_closest_elements(arr: Vec, k: i32, x: i32) -> Vec { - let k = k as usize; - let n = arr.len(); - let mut left = 0; - let mut right = n - k; - while left < right { - let mid = left + (right - left) / 2; - if x - arr[mid] > arr[mid + k] - x { - left = mid + 1; + + +### 方法二:双指针 + +直觉上,有序数组 $arr$ 最靠近 $x$ 的 $k$ 个数必然是一段连续的子数组。 + +我们可以声明头尾指针,记为 $l$ 和 $r$,然后根据 $x-arr[l]$ 与 $arr[r-1] - x$ 的大小比较结果缩小范围,直到 $r - l = k$。 + +时间复杂度 $O(n)$。 + + + +```python +class Solution: + def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: + l, r = 0, len(arr) + while r - l > k: + if x - arr[l] <= arr[r - 1] - x: + r -= 1 + else: + l += 1 + return arr[l:r] +``` + +```java +class Solution { + public List findClosestElements(int[] arr, int k, int x) { + int l = 0, r = arr.length; + while (r - l > k) { + if (x - arr[l] <= arr[r - 1] - x) { + --r; } else { - right = mid; + ++l; } } - arr[left..left + k].to_vec() + List ans = new ArrayList<>(); + for (int i = l; i < r; ++i) { + ans.add(arr[i]); + } + return ans; } } ``` -### **TypeScript** - -```ts -function findClosestElements(arr: number[], k: number, x: number): number[] { - let l = 0; - let r = arr.length; - while (r - l > k) { - if (x - arr[l] <= arr[r - 1] - x) { - --r; - } else { - ++l; +```cpp +class Solution { +public: + vector findClosestElements(vector& arr, int k, int x) { + int l = 0, r = arr.size(); + while (r - l > k) { + if (x - arr[l] <= arr[r - 1] - x) { + --r; + } else { + ++l; + } } + return vector(arr.begin() + l, arr.begin() + r); } - return arr.slice(l, r); +}; +``` + +```go +func findClosestElements(arr []int, k int, x int) []int { + l, r := 0, len(arr) + for r-l > k { + if x-arr[l] <= arr[r-1]-x { + r-- + } else { + l++ + } + } + return arr[l:r] } ``` @@ -349,10 +242,103 @@ function findClosestElements(arr: number[], k: number, x: number): number[] { } ``` -### **...** +```rust +impl Solution { + pub fn find_closest_elements(arr: Vec, k: i32, x: i32) -> Vec { + let k = k as usize; + let n = arr.len(); + let mut left = 0; + let mut right = n - k; + while left < right { + let mid = left + (right - left) / 2; + if x - arr[mid] > arr[mid + k] - x { + left = mid + 1; + } else { + right = mid; + } + } + arr[left..left + k].to_vec() + } +} +``` + + + +### 方法三:二分查找 + +在方法二的基础上,我们更进一步,查找大小为 $k$ 的窗口的左边界。 + +时间复杂度 $O(logn)$。 + + + +```python +class Solution: + def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: + left, right = 0, len(arr) - k + while left < right: + mid = (left + right) >> 1 + if x - arr[mid] <= arr[mid + k] - x: + right = mid + else: + left = mid + 1 + return arr[left : left + k] +``` + +```java +class Solution { + public List findClosestElements(int[] arr, int k, int x) { + int left = 0; + int right = arr.length - k; + while (left < right) { + int mid = (left + right) >> 1; + if (x - arr[mid] <= arr[mid + k] - x) { + right = mid; + } else { + left = mid + 1; + } + } + List ans = new ArrayList<>(); + for (int i = left; i < left + k; ++i) { + ans.add(arr[i]); + } + return ans; + } +} +``` +```cpp +class Solution { +public: + vector findClosestElements(vector& arr, int k, int x) { + int left = 0, right = arr.size() - k; + while (left < right) { + int mid = (left + right) >> 1; + if (x - arr[mid] <= arr[mid + k] - x) + right = mid; + else + left = mid + 1; + } + return vector(arr.begin() + left, arr.begin() + left + k); + } +}; ``` +```go +func findClosestElements(arr []int, k int, x int) []int { + left, right := 0, len(arr)-k + for left < right { + mid := (left + right) >> 1 + if x-arr[mid] <= arr[mid+k]-x { + right = mid + } else { + left = mid + 1 + } + } + return arr[left : left+k] +} ``` + + diff --git a/solution/0600-0699/0658.Find K Closest Elements/README_EN.md b/solution/0600-0699/0658.Find K Closest Elements/README_EN.md index 37e446247019c..c7be3c2a3bd5d 100644 --- a/solution/0600-0699/0658.Find K Closest Elements/README_EN.md +++ b/solution/0600-0699/0658.Find K Closest Elements/README_EN.md @@ -33,14 +33,10 @@ ## Solutions -**Solution 1: Sort** - -**Solution 2: Binary search** +### Solution 1: Sort -### **Python3** - ```python class Solution: def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: @@ -48,33 +44,6 @@ class Solution: return sorted(arr[:k]) ``` -```python -class Solution: - def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: - l, r = 0, len(arr) - while r - l > k: - if x - arr[l] <= arr[r - 1] - x: - r -= 1 - else: - l += 1 - return arr[l:r] -``` - -```python -class Solution: - def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: - left, right = 0, len(arr) - k - while left < right: - mid = (left + right) >> 1 - if x - arr[mid] <= arr[mid + k] - x: - right = mid - else: - left = mid + 1 - return arr[left : left + k] -``` - -### **Java** - ```java class Solution { public List findClosestElements(int[] arr, int k, int x) { @@ -92,50 +61,6 @@ class Solution { } ``` -```java -class Solution { - public List findClosestElements(int[] arr, int k, int x) { - int l = 0, r = arr.length; - while (r - l > k) { - if (x - arr[l] <= arr[r - 1] - x) { - --r; - } else { - ++l; - } - } - List ans = new ArrayList<>(); - for (int i = l; i < r; ++i) { - ans.add(arr[i]); - } - return ans; - } -} -``` - -```java -class Solution { - public List findClosestElements(int[] arr, int k, int x) { - int left = 0; - int right = arr.length - k; - while (left < right) { - int mid = (left + right) >> 1; - if (x - arr[mid] <= arr[mid + k] - x) { - right = mid; - } else { - left = mid + 1; - } - } - List ans = new ArrayList<>(); - for (int i = left; i < left + k; ++i) { - ans.add(arr[i]); - } - return ans; - } -} -``` - -### **C++** - ```cpp int target; @@ -156,42 +81,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector findClosestElements(vector& arr, int k, int x) { - int l = 0, r = arr.size(); - while (r - l > k) { - if (x - arr[l] <= arr[r - 1] - x) { - --r; - } else { - ++l; - } - } - return vector(arr.begin() + l, arr.begin() + r); - } -}; -``` - -```cpp -class Solution { -public: - vector findClosestElements(vector& arr, int k, int x) { - int left = 0, right = arr.size() - k; - while (left < right) { - int mid = (left + right) >> 1; - if (x - arr[mid] <= arr[mid + k] - x) - right = mid; - else - left = mid + 1; - } - return vector(arr.begin() + left, arr.begin() + left + k); - } -}; -``` - -### **Go** - ```go func findClosestElements(arr []int, k int, x int) []int { sort.Slice(arr, func(i, j int) bool { @@ -214,37 +103,21 @@ func abs(x int) int { } ``` -```go -func findClosestElements(arr []int, k int, x int) []int { - l, r := 0, len(arr) - for r-l > k { - if x-arr[l] <= arr[r-1]-x { - r-- - } else { - l++ - } - } - return arr[l:r] -} -``` - -```go -func findClosestElements(arr []int, k int, x int) []int { - left, right := 0, len(arr)-k - for left < right { - mid := (left + right) >> 1 - if x-arr[mid] <= arr[mid+k]-x { - right = mid - } else { - left = mid + 1 - } - } - return arr[left : left+k] +```ts +function findClosestElements(arr: number[], k: number, x: number): number[] { + let l = 0; + let r = arr.length; + while (r - l > k) { + if (x - arr[l] <= arr[r - 1] - x) { + --r; + } else { + ++l; + } + } + return arr.slice(l, r); } ``` -### **Rust** - ```rust impl Solution { pub fn find_closest_elements(arr: Vec, k: i32, x: i32) -> Vec { @@ -263,40 +136,72 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn find_closest_elements(arr: Vec, k: i32, x: i32) -> Vec { - let k = k as usize; - let n = arr.len(); - let mut left = 0; - let mut right = n - k; - while left < right { - let mid = left + (right - left) / 2; - if x - arr[mid] > arr[mid + k] - x { - left = mid + 1; + + +### Solution 2: Binary search + + + +```python +class Solution: + def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: + l, r = 0, len(arr) + while r - l > k: + if x - arr[l] <= arr[r - 1] - x: + r -= 1 + else: + l += 1 + return arr[l:r] +``` + +```java +class Solution { + public List findClosestElements(int[] arr, int k, int x) { + int l = 0, r = arr.length; + while (r - l > k) { + if (x - arr[l] <= arr[r - 1] - x) { + --r; } else { - right = mid; + ++l; } } - arr[left..left + k].to_vec() + List ans = new ArrayList<>(); + for (int i = l; i < r; ++i) { + ans.add(arr[i]); + } + return ans; } } ``` -### **TypeScript** - -```ts -function findClosestElements(arr: number[], k: number, x: number): number[] { - let l = 0; - let r = arr.length; - while (r - l > k) { - if (x - arr[l] <= arr[r - 1] - x) { - --r; - } else { - ++l; +```cpp +class Solution { +public: + vector findClosestElements(vector& arr, int k, int x) { + int l = 0, r = arr.size(); + while (r - l > k) { + if (x - arr[l] <= arr[r - 1] - x) { + --r; + } else { + ++l; + } } + return vector(arr.begin() + l, arr.begin() + r); } - return arr.slice(l, r); +}; +``` + +```go +func findClosestElements(arr []int, k int, x int) []int { + l, r := 0, len(arr) + for r-l > k { + if x-arr[l] <= arr[r-1]-x { + r-- + } else { + l++ + } + } + return arr[l:r] } ``` @@ -316,10 +221,99 @@ function findClosestElements(arr: number[], k: number, x: number): number[] { } ``` -### **...** +```rust +impl Solution { + pub fn find_closest_elements(arr: Vec, k: i32, x: i32) -> Vec { + let k = k as usize; + let n = arr.len(); + let mut left = 0; + let mut right = n - k; + while left < right { + let mid = left + (right - left) / 2; + if x - arr[mid] > arr[mid + k] - x { + left = mid + 1; + } else { + right = mid; + } + } + arr[left..left + k].to_vec() + } +} +``` + + + +### Solution 3 + + + +```python +class Solution: + def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: + left, right = 0, len(arr) - k + while left < right: + mid = (left + right) >> 1 + if x - arr[mid] <= arr[mid + k] - x: + right = mid + else: + left = mid + 1 + return arr[left : left + k] +``` + +```java +class Solution { + public List findClosestElements(int[] arr, int k, int x) { + int left = 0; + int right = arr.length - k; + while (left < right) { + int mid = (left + right) >> 1; + if (x - arr[mid] <= arr[mid + k] - x) { + right = mid; + } else { + left = mid + 1; + } + } + List ans = new ArrayList<>(); + for (int i = left; i < left + k; ++i) { + ans.add(arr[i]); + } + return ans; + } +} +``` +```cpp +class Solution { +public: + vector findClosestElements(vector& arr, int k, int x) { + int left = 0, right = arr.size() - k; + while (left < right) { + int mid = (left + right) >> 1; + if (x - arr[mid] <= arr[mid + k] - x) + right = mid; + else + left = mid + 1; + } + return vector(arr.begin() + left, arr.begin() + left + k); + } +}; ``` +```go +func findClosestElements(arr []int, k int, x int) []int { + left, right := 0, len(arr)-k + for left < right { + mid := (left + right) >> 1 + if x-arr[mid] <= arr[mid+k]-x { + right = mid + } else { + left = mid + 1 + } + } + return arr[left : left+k] +} ``` + + diff --git a/solution/0600-0699/0659.Split Array into Consecutive Subsequences/README.md b/solution/0600-0699/0659.Split Array into Consecutive Subsequences/README.md index d37ca74bfbfee..ef8be5f799d62 100644 --- a/solution/0600-0699/0659.Split Array into Consecutive Subsequences/README.md +++ b/solution/0600-0699/0659.Split Array into Consecutive Subsequences/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:哈希表 + 优先队列(小根堆)** +### 方法一:哈希表 + 优先队列(小根堆) 由于题目中的子序列是由连续整数组成的,因此,只要知道子序列的最后一个数以及子序列的长度,就能够确定子序列。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def isPossible(self, nums: List[int]) -> bool: @@ -95,10 +89,6 @@ class Solution: return all(not v or v and v[0] > 2 for v in d.values()) ``` -### **Java** - - - ```java class Solution { public boolean isPossible(int[] nums) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func isPossible(nums []int) bool { d := map[int]*hp{} @@ -190,10 +176,6 @@ func (h *hp) Pop() any { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0659.Split Array into Consecutive Subsequences/README_EN.md b/solution/0600-0699/0659.Split Array into Consecutive Subsequences/README_EN.md index 246a9e0620c08..318a1ab971e78 100644 --- a/solution/0600-0699/0659.Split Array into Consecutive Subsequences/README_EN.md +++ b/solution/0600-0699/0659.Split Array into Consecutive Subsequences/README_EN.md @@ -57,9 +57,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return all(not v or v and v[0] > 2 for v in d.values()) ``` -### **Java** - ```java class Solution { public boolean isPossible(int[] nums) { @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +125,6 @@ public: }; ``` -### **Go** - ```go func isPossible(nums []int) bool { d := map[int]*hp{} @@ -166,10 +160,6 @@ func (h *hp) Pop() any { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0660.Remove 9/README.md b/solution/0600-0699/0660.Remove 9/README.md index 556299d978a72..e9d64cf1b7cc7 100644 --- a/solution/0600-0699/0660.Remove 9/README.md +++ b/solution/0600-0699/0660.Remove 9/README.md @@ -38,30 +38,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0600-0699/0660.Remove 9/README_EN.md b/solution/0600-0699/0660.Remove 9/README_EN.md index 179789c1b6e64..39b9dcf0d9d99 100644 --- a/solution/0600-0699/0660.Remove 9/README_EN.md +++ b/solution/0600-0699/0660.Remove 9/README_EN.md @@ -34,24 +34,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0600-0699/0661.Image Smoother/README.md b/solution/0600-0699/0661.Image Smoother/README.md index 42dea7284bcc0..099c990b904a7 100644 --- a/solution/0600-0699/0661.Image Smoother/README.md +++ b/solution/0600-0699/0661.Image Smoother/README.md @@ -55,14 +55,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def imageSmoother(self, img: List[List[int]]) -> List[List[int]]: @@ -80,10 +76,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] imageSmoother(int[][] img) { @@ -110,7 +102,52 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + vector> imageSmoother(vector>& img) { + int m = img.size(), n = img[0].size(); + vector> ans(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int s = 0, cnt = 0; + for (int x = i - 1; x <= i + 1; ++x) { + for (int y = j - 1; y <= j + 1; ++y) { + if (x < 0 || x >= m || y < 0 || y >= n) continue; + ++cnt; + s += img[x][y]; + } + } + ans[i][j] = s / cnt; + } + } + return ans; + } +}; +``` + +```go +func imageSmoother(img [][]int) [][]int { + m, n := len(img), len(img[0]) + ans := make([][]int, m) + for i, row := range img { + ans[i] = make([]int, n) + for j := range row { + s, cnt := 0, 0 + for x := i - 1; x <= i+1; x++ { + for y := j - 1; y <= j+1; y++ { + if x >= 0 && x < m && y >= 0 && y < n { + cnt++ + s += img[x][y] + } + } + } + ans[i][j] = s / cnt + } + } + return ans +} +``` ```ts function imageSmoother(img: number[][]): number[][] { @@ -147,8 +184,6 @@ function imageSmoother(img: number[][]): number[][] { } ``` -### **Rust** - ```rust impl Solution { pub fn image_smoother(img: Vec>) -> Vec> { @@ -189,61 +224,6 @@ impl Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector> imageSmoother(vector>& img) { - int m = img.size(), n = img[0].size(); - vector> ans(m, vector(n)); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - int s = 0, cnt = 0; - for (int x = i - 1; x <= i + 1; ++x) { - for (int y = j - 1; y <= j + 1; ++y) { - if (x < 0 || x >= m || y < 0 || y >= n) continue; - ++cnt; - s += img[x][y]; - } - } - ans[i][j] = s / cnt; - } - } - return ans; - } -}; -``` - -### **Go** - -```go -func imageSmoother(img [][]int) [][]int { - m, n := len(img), len(img[0]) - ans := make([][]int, m) - for i, row := range img { - ans[i] = make([]int, n) - for j := range row { - s, cnt := 0, 0 - for x := i - 1; x <= i+1; x++ { - for y := j - 1; y <= j+1; y++ { - if x >= 0 && x < m && y >= 0 && y < n { - cnt++ - s += img[x][y] - } - } - } - ans[i][j] = s / cnt - } - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0661.Image Smoother/README_EN.md b/solution/0600-0699/0661.Image Smoother/README_EN.md index b9bd2adf62b03..2a05ea74c9ebf 100644 --- a/solution/0600-0699/0661.Image Smoother/README_EN.md +++ b/solution/0600-0699/0661.Image Smoother/README_EN.md @@ -43,9 +43,9 @@ For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.8 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] imageSmoother(int[][] img) { @@ -92,7 +90,52 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + vector> imageSmoother(vector>& img) { + int m = img.size(), n = img[0].size(); + vector> ans(m, vector(n)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + int s = 0, cnt = 0; + for (int x = i - 1; x <= i + 1; ++x) { + for (int y = j - 1; y <= j + 1; ++y) { + if (x < 0 || x >= m || y < 0 || y >= n) continue; + ++cnt; + s += img[x][y]; + } + } + ans[i][j] = s / cnt; + } + } + return ans; + } +}; +``` + +```go +func imageSmoother(img [][]int) [][]int { + m, n := len(img), len(img[0]) + ans := make([][]int, m) + for i, row := range img { + ans[i] = make([]int, n) + for j := range row { + s, cnt := 0, 0 + for x := i - 1; x <= i+1; x++ { + for y := j - 1; y <= j+1; y++ { + if x >= 0 && x < m && y >= 0 && y < n { + cnt++ + s += img[x][y] + } + } + } + ans[i][j] = s / cnt + } + } + return ans +} +``` ```ts function imageSmoother(img: number[][]): number[][] { @@ -129,8 +172,6 @@ function imageSmoother(img: number[][]): number[][] { } ``` -### **Rust** - ```rust impl Solution { pub fn image_smoother(img: Vec>) -> Vec> { @@ -171,61 +212,6 @@ impl Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector> imageSmoother(vector>& img) { - int m = img.size(), n = img[0].size(); - vector> ans(m, vector(n)); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - int s = 0, cnt = 0; - for (int x = i - 1; x <= i + 1; ++x) { - for (int y = j - 1; y <= j + 1; ++y) { - if (x < 0 || x >= m || y < 0 || y >= n) continue; - ++cnt; - s += img[x][y]; - } - } - ans[i][j] = s / cnt; - } - } - return ans; - } -}; -``` - -### **Go** - -```go -func imageSmoother(img [][]int) [][]int { - m, n := len(img), len(img[0]) - ans := make([][]int, m) - for i, row := range img { - ans[i] = make([]int, n) - for j := range row { - s, cnt := 0, 0 - for x := i - 1; x <= i+1; x++ { - for y := j - 1; y <= j+1; y++ { - if x >= 0 && x < m && y >= 0 && y < n { - cnt++ - s += img[x][y] - } - } - } - ans[i][j] = s / cnt - } - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0662.Maximum Width of Binary Tree/README.md b/solution/0600-0699/0662.Maximum Width of Binary Tree/README.md index effbbbc5a9993..3870a3d8c28e1 100644 --- a/solution/0600-0699/0662.Maximum Width of Binary Tree/README.md +++ b/solution/0600-0699/0662.Maximum Width of Binary Tree/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 对节点进行编号,初始根节点编号为 $1$。 @@ -67,18 +65,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。 -**方法二:DFS** - -定义 `dfs(root, depth, i)` 表示从深度为 `depth`,且编号为 `i` 的节点 `root` 开始往下搜索。记录每一层最先访问到的节点的编号。访问到当前层其它节点时,求当前节点编号与当前层最小编号的差再加一,更新当前层的最大宽度。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -101,36 +89,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int: - def dfs(root, depth, i): - if root is None: - return - if len(t) == depth: - t.append(i) - else: - nonlocal ans - ans = max(ans, i - t[depth] + 1) - dfs(root.left, depth + 1, i << 1) - dfs(root.right, depth + 1, i << 1 | 1) - - ans = 1 - t = [] - dfs(root, 0, 1) - return ans -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -171,6 +129,112 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int widthOfBinaryTree(TreeNode* root) { + queue> q; + q.push({root, 1}); + int ans = 0; + while (!q.empty()) { + ans = max(ans, q.back().second - q.front().second + 1); + int i = q.front().second; + for (int n = q.size(); n; --n) { + auto p = q.front(); + q.pop(); + root = p.first; + int j = p.second; + if (root->left) q.push({root->left, (j << 1) - (i << 1)}); + if (root->right) q.push({root->right, (j << 1 | 1) - (i << 1)}); + } + } + return ans; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func widthOfBinaryTree(root *TreeNode) int { + q := []pair{{root, 1}} + ans := 0 + for len(q) > 0 { + ans = max(ans, q[len(q)-1].i-q[0].i+1) + for n := len(q); n > 0; n-- { + p := q[0] + q = q[1:] + root = p.node + if root.Left != nil { + q = append(q, pair{root.Left, p.i << 1}) + } + if root.Right != nil { + q = append(q, pair{root.Right, p.i<<1 | 1}) + } + } + } + return ans +} + +type pair struct { + node *TreeNode + i int +} +``` + + + +### 方法二:DFS + +定义 `dfs(root, depth, i)` 表示从深度为 `depth`,且编号为 `i` 的节点 `root` 开始往下搜索。记录每一层最先访问到的节点的编号。访问到当前层其它节点时,求当前节点编号与当前层最小编号的差再加一,更新当前层的最大宽度。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int: + def dfs(root, depth, i): + if root is None: + return + if len(t) == depth: + t.append(i) + else: + nonlocal ans + ans = max(ans, i - t[depth] + 1) + dfs(root.left, depth + 1, i << 1) + dfs(root.right, depth + 1, i << 1 | 1) + + ans = 1 + t = [] + dfs(root, 0, 1) + return ans +``` + ```java /** * Definition for a binary tree node. @@ -211,45 +275,6 @@ class Solution { } ``` -### **C++** - -`i << 1` 表示下一层的起点。计算下一层左右子树索引时,减去 `i << 1`,可以防止溢出。 - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int widthOfBinaryTree(TreeNode* root) { - queue> q; - q.push({root, 1}); - int ans = 0; - while (!q.empty()) { - ans = max(ans, q.back().second - q.front().second + 1); - int i = q.front().second; - for (int n = q.size(); n; --n) { - auto p = q.front(); - q.pop(); - root = p.first; - int j = p.second; - if (root->left) q.push({root->left, (j << 1) - (i << 1)}); - if (root->right) q.push({root->right, (j << 1 | 1) - (i << 1)}); - } - } - return ans; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -286,43 +311,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func widthOfBinaryTree(root *TreeNode) int { - q := []pair{{root, 1}} - ans := 0 - for len(q) > 0 { - ans = max(ans, q[len(q)-1].i-q[0].i+1) - for n := len(q); n > 0; n-- { - p := q[0] - q = q[1:] - root = p.node - if root.Left != nil { - q = append(q, pair{root.Left, p.i << 1}) - } - if root.Right != nil { - q = append(q, pair{root.Right, p.i<<1 | 1}) - } - } - } - return ans -} - -type pair struct { - node *TreeNode - i int -} -``` - ```go /** * Definition for a binary tree node. @@ -353,10 +341,6 @@ func widthOfBinaryTree(root *TreeNode) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0662.Maximum Width of Binary Tree/README_EN.md b/solution/0600-0699/0662.Maximum Width of Binary Tree/README_EN.md index f66f0c46b27a0..49a6e199c370e 100644 --- a/solution/0600-0699/0662.Maximum Width of Binary Tree/README_EN.md +++ b/solution/0600-0699/0662.Maximum Width of Binary Tree/README_EN.md @@ -47,12 +47,10 @@ ## Solutions -BFS or DFS. +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -75,34 +73,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int: - def dfs(root, depth, i): - if root is None: - return - if len(t) == depth: - t.append(i) - else: - nonlocal ans - ans = max(ans, i - t[depth] + 1) - dfs(root.left, depth + 1, i << 1) - dfs(root.right, depth + 1, i << 1 | 1) - - ans = 1 - t = [] - dfs(root, 0, 1) - return ans -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -143,6 +113,108 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int widthOfBinaryTree(TreeNode* root) { + queue> q; + q.push({root, 1}); + int ans = 0; + while (!q.empty()) { + ans = max(ans, q.back().second - q.front().second + 1); + int i = q.front().second; + for (int n = q.size(); n; --n) { + auto p = q.front(); + q.pop(); + root = p.first; + int j = p.second; + if (root->left) q.push({root->left, (j << 1) - (i << 1)}); + if (root->right) q.push({root->right, (j << 1 | 1) - (i << 1)}); + } + } + return ans; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func widthOfBinaryTree(root *TreeNode) int { + q := []pair{{root, 1}} + ans := 0 + for len(q) > 0 { + ans = max(ans, q[len(q)-1].i-q[0].i+1) + for n := len(q); n > 0; n-- { + p := q[0] + q = q[1:] + root = p.node + if root.Left != nil { + q = append(q, pair{root.Left, p.i << 1}) + } + if root.Right != nil { + q = append(q, pair{root.Right, p.i<<1 | 1}) + } + } + } + return ans +} + +type pair struct { + node *TreeNode + i int +} +``` + + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int: + def dfs(root, depth, i): + if root is None: + return + if len(t) == depth: + t.append(i) + else: + nonlocal ans + ans = max(ans, i - t[depth] + 1) + dfs(root.left, depth + 1, i << 1) + dfs(root.right, depth + 1, i << 1 | 1) + + ans = 1 + t = [] + dfs(root, 0, 1) + return ans +``` + ```java /** * Definition for a binary tree node. @@ -183,43 +255,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int widthOfBinaryTree(TreeNode* root) { - queue> q; - q.push({root, 1}); - int ans = 0; - while (!q.empty()) { - ans = max(ans, q.back().second - q.front().second + 1); - int i = q.front().second; - for (int n = q.size(); n; --n) { - auto p = q.front(); - q.pop(); - root = p.first; - int j = p.second; - if (root->left) q.push({root->left, (j << 1) - (i << 1)}); - if (root->right) q.push({root->right, (j << 1 | 1) - (i << 1)}); - } - } - return ans; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -256,43 +291,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func widthOfBinaryTree(root *TreeNode) int { - q := []pair{{root, 1}} - ans := 0 - for len(q) > 0 { - ans = max(ans, q[len(q)-1].i-q[0].i+1) - for n := len(q); n > 0; n-- { - p := q[0] - q = q[1:] - root = p.node - if root.Left != nil { - q = append(q, pair{root.Left, p.i << 1}) - } - if root.Right != nil { - q = append(q, pair{root.Right, p.i<<1 | 1}) - } - } - } - return ans -} - -type pair struct { - node *TreeNode - i int -} -``` - ```go /** * Definition for a binary tree node. @@ -323,10 +321,6 @@ func widthOfBinaryTree(root *TreeNode) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0663.Equal Tree Partition/README.md b/solution/0600-0699/0663.Equal Tree Partition/README.md index 7b9ebb294e457..fb743d57894f7 100644 --- a/solution/0600-0699/0663.Equal Tree Partition/README.md +++ b/solution/0600-0699/0663.Equal Tree Partition/README.md @@ -36,16 +36,10 @@ ## 解法 - - -后序遍历,记录每个子树的和。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -70,10 +64,6 @@ class Solution: return s // 2 in seen ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -189,10 +175,6 @@ func checkEqualTree(root *TreeNode) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0663.Equal Tree Partition/README_EN.md b/solution/0600-0699/0663.Equal Tree Partition/README_EN.md index 89f76156f1d7b..7e5dd98d4b5ed 100644 --- a/solution/0600-0699/0663.Equal Tree Partition/README_EN.md +++ b/solution/0600-0699/0663.Equal Tree Partition/README_EN.md @@ -32,9 +32,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -60,8 +60,6 @@ class Solution: return s // 2 in seen ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -139,8 +135,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -177,10 +171,6 @@ func checkEqualTree(root *TreeNode) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0664.Strange Printer/README.md b/solution/0600-0699/0664.Strange Printer/README.md index bc9fb5fadf4e5..a653aae4b658d 100644 --- a/solution/0600-0699/0664.Strange Printer/README.md +++ b/solution/0600-0699/0664.Strange Printer/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示打印完成区间 $s[i..j]$ 的最少操作数,初始时 $f[i][j]=\infty$,答案为 $f[0][n-1]$,其中 $n$ 是字符串 $s$ 的长度。 @@ -66,10 +64,6 @@ $$ -### **Python3** - - - ```python class Solution: def strangePrinter(self, s: str) -> int: @@ -86,10 +80,6 @@ class Solution: return f[0][-1] ``` -### **Java** - - - ```java class Solution { public int strangePrinter(String s) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func strangePrinter(s string) int { n := len(s) @@ -170,8 +156,6 @@ func strangePrinter(s string) int { } ``` -### **TypeScript** - ```ts function strangePrinter(s: string): number { const n = s.length; @@ -192,10 +176,6 @@ function strangePrinter(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0664.Strange Printer/README_EN.md b/solution/0600-0699/0664.Strange Printer/README_EN.md index 2c160d7ee4e3b..56106c62d1341 100644 --- a/solution/0600-0699/0664.Strange Printer/README_EN.md +++ b/solution/0600-0699/0664.Strange Printer/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ as the minimum operations to print $s[i..j]$, with the initial value $f[i][j]=\infty$, and the answer is $f[0][n-1]$, where $n$ is the length of string $s$. @@ -61,8 +61,6 @@ The time complexity is $O(n^3)$ and the space complexity is $O(n^2)$. Where $n$ -### **Python3** - ```python class Solution: def strangePrinter(self, s: str) -> int: @@ -79,8 +77,6 @@ class Solution: return f[0][-1] ``` -### **Java** - ```java class Solution { public int strangePrinter(String s) { @@ -107,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +127,6 @@ public: }; ``` -### **Go** - ```go func strangePrinter(s string) int { n := len(s) @@ -161,8 +153,6 @@ func strangePrinter(s string) int { } ``` -### **TypeScript** - ```ts function strangePrinter(s: string): number { const n = s.length; @@ -183,10 +173,6 @@ function strangePrinter(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0665.Non-decreasing Array/README.md b/solution/0600-0699/0665.Non-decreasing Array/README.md index 5331eee6e74a0..f86082ffc1114 100644 --- a/solution/0600-0699/0665.Non-decreasing Array/README.md +++ b/solution/0600-0699/0665.Non-decreasing Array/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:两次遍历** +### 方法一:两次遍历 在最多改变一个元素的情况下,若要将数组变成非递减数列,那么数组最多只能有一个位置,其左右两侧的元素不满足非递减数列的要求。也即数组中只会存在一个位置 $i$,使得 $nums[i] \gt nums[i+1]$。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def checkPossibility(self, nums: List[int]) -> bool: @@ -77,10 +71,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean checkPossibility(int[] nums) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func checkPossibility(nums []int) bool { isSorted := func(nums []int) bool { @@ -162,8 +148,6 @@ func checkPossibility(nums []int) bool { } ``` -### **TypeScript** - ```ts function checkPossibility(nums: number[]): boolean { const isSorted = (nums: number[]) => { @@ -191,10 +175,6 @@ function checkPossibility(nums: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0665.Non-decreasing Array/README_EN.md b/solution/0600-0699/0665.Non-decreasing Array/README_EN.md index cff20c9edeeff..de8051e166d8a 100644 --- a/solution/0600-0699/0665.Non-decreasing Array/README_EN.md +++ b/solution/0600-0699/0665.Non-decreasing Array/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean checkPossibility(int[] nums) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func checkPossibility(nums []int) bool { isSorted := func(nums []int) bool { @@ -141,8 +135,6 @@ func checkPossibility(nums []int) bool { } ``` -### **TypeScript** - ```ts function checkPossibility(nums: number[]): boolean { const isSorted = (nums: number[]) => { @@ -170,10 +162,6 @@ function checkPossibility(nums: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0666.Path Sum IV/README.md b/solution/0600-0699/0666.Path Sum IV/README.md index 836e251f46ac5..b8ed3083721e5 100644 --- a/solution/0600-0699/0666.Path Sum IV/README.md +++ b/solution/0600-0699/0666.Path Sum IV/README.md @@ -54,16 +54,10 @@ ## 解法 - - -DFS。 +### 方法一 -### **Python3** - - - ```python class Solution: def pathSum(self, nums: List[int]) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int ans; @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func pathSum(nums []int) int { ans := 0 @@ -187,10 +173,6 @@ func pathSum(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0666.Path Sum IV/README_EN.md b/solution/0600-0699/0666.Path Sum IV/README_EN.md index ee7b7594370c8..ef63b989c822d 100644 --- a/solution/0600-0699/0666.Path Sum IV/README_EN.md +++ b/solution/0600-0699/0666.Path Sum IV/README_EN.md @@ -46,12 +46,10 @@ The path sum is (3 + 1) = 4. ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python class Solution: def pathSum(self, nums: List[int]) -> int: @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int ans; @@ -110,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go func pathSum(nums []int) int { ans := 0 @@ -173,10 +165,6 @@ func pathSum(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0667.Beautiful Arrangement II/README.md b/solution/0600-0699/0667.Beautiful Arrangement II/README.md index cbb23b5fd2786..eeddcbdea0819 100644 --- a/solution/0600-0699/0667.Beautiful Arrangement II/README.md +++ b/solution/0600-0699/0667.Beautiful Arrangement II/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:构造** +### 方法一:构造 先按照 `1, n, 2, n-1, 3,...` 构造答案数据 `ans` 的前 $k$ 个数,共产生 $k-1$ 个不同的整数。然后根据 $k$ 的奇偶性确定从哪个数开始构造下一个数。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def constructArray(self, n: int, k: int) -> List[int]: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] constructArray(int n, int k) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func constructArray(n int, k int) []int { l, r := 1, n @@ -147,8 +133,6 @@ func constructArray(n int, k int) []int { } ``` -### **TypeScript** - ```ts function constructArray(n: number, k: number): number[] { let l = 1; @@ -164,10 +148,6 @@ function constructArray(n: number, k: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0667.Beautiful Arrangement II/README_EN.md b/solution/0600-0699/0667.Beautiful Arrangement II/README_EN.md index abf584435aeda..7831741a4aa99 100644 --- a/solution/0600-0699/0667.Beautiful Arrangement II/README_EN.md +++ b/solution/0600-0699/0667.Beautiful Arrangement II/README_EN.md @@ -38,9 +38,9 @@ Explanation: The [1,3,2] has three different positive integers ranging from 1 to ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] constructArray(int n, int k) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +97,6 @@ public: }; ``` -### **Go** - ```go func constructArray(n int, k int) []int { l, r := 1, n @@ -129,8 +123,6 @@ func constructArray(n int, k int) []int { } ``` -### **TypeScript** - ```ts function constructArray(n: number, k: number): number[] { let l = 1; @@ -146,10 +138,6 @@ function constructArray(n: number, k: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0668.Kth Smallest Number in Multiplication Table/README.md b/solution/0600-0699/0668.Kth Smallest Number in Multiplication Table/README.md index 3bdb879c7c9d0..b66e053c55e93 100644 --- a/solution/0600-0699/0668.Kth Smallest Number in Multiplication Table/README.md +++ b/solution/0600-0699/0668.Kth Smallest Number in Multiplication Table/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 题目可以转换为,求有多少个数不超过 x。对于每一行 i,所有数都是 i 的倍数,不超过 x 的个数有 `x / i` 个。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def findKthNumber(self, m: int, n: int, k: int) -> int: @@ -75,10 +69,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int findKthNumber(int m, int n, int k) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func findKthNumber(m int, n int, k int) int { left, right := 1, m*n @@ -142,10 +128,6 @@ func findKthNumber(m int, n int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0668.Kth Smallest Number in Multiplication Table/README_EN.md b/solution/0600-0699/0668.Kth Smallest Number in Multiplication Table/README_EN.md index 5ebb7c4bea4f9..e38d54a0714e1 100644 --- a/solution/0600-0699/0668.Kth Smallest Number in Multiplication Table/README_EN.md +++ b/solution/0600-0699/0668.Kth Smallest Number in Multiplication Table/README_EN.md @@ -35,12 +35,10 @@ ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python class Solution: def findKthNumber(self, m: int, n: int, k: int) -> int: @@ -57,8 +55,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { public int findKthNumber(int m, int n, int k) { @@ -80,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +95,6 @@ public: }; ``` -### **Go** - ```go func findKthNumber(m int, n int, k int) int { left, right := 1, m*n @@ -122,10 +114,6 @@ func findKthNumber(m int, n int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0669.Trim a Binary Search Tree/README.md b/solution/0600-0699/0669.Trim a Binary Search Tree/README.md index 96ee8c44f1228..578f55c5ce586 100644 --- a/solution/0600-0699/0669.Trim a Binary Search Tree/README.md +++ b/solution/0600-0699/0669.Trim a Binary Search Tree/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 判断 `root.val` 与 `low` 和 `high` 的大小关系: @@ -54,28 +52,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉搜索树的节点个数。 -**方法二:迭代** - -我们先循环判断 `root`,若 `root.val` 不在 `[low, high]` 之间,那么直接将 `root` 置为对应的左孩子或右孩子,循环直至 `root` 为空或者 `root.val` 在 `[low, high]` 之间。 - -若此时 `root` 为空,直接返回。否则,说明 `root` 是一个需要保留的节点。接下来只需要分别迭代修剪 `root` 的左右子树。 - -以左子树 `node = root.left` 为例: - -- 若 `node.left.val` 小于 `low`,那么 `node.left` 及其左孩子均不满足条件,我们直接将 `node.left` 置为 `node.left.right`; -- 否则,我们将 `node` 置为 `node.left`; -- 循环判断,直至 `node.left` 为空。 - -右子树的修剪过程与之类似。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是二叉搜索树的节点个数。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -101,40 +79,6 @@ class Solution: return dfs(root) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def trimBST( - self, root: Optional[TreeNode], low: int, high: int - ) -> Optional[TreeNode]: - while root and (root.val < low or root.val > high): - root = root.left if root.val > high else root.right - if root is None: - return None - node = root - while node.left: - if node.left.val < low: - node.left = node.left.right - else: - node = node.left - node = root - while node.right: - if node.right.val > high: - node.right = node.right.left - else: - node = node.right - return root -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -169,6 +113,244 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* trimBST(TreeNode* root, int low, int high) { + if (!root) return root; + if (root->val > high) return trimBST(root->left, low, high); + if (root->val < low) return trimBST(root->right, low, high); + root->left = trimBST(root->left, low, high); + root->right = trimBST(root->right, low, high); + return root; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func trimBST(root *TreeNode, low int, high int) *TreeNode { + if root == nil { + return root + } + if root.Val > high { + return trimBST(root.Left, low, high) + } + if root.Val < low { + return trimBST(root.Right, low, high) + } + root.Left = trimBST(root.Left, low, high) + root.Right = trimBST(root.Right, low, high) + return root +} +``` + +```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 trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null { + const dfs = (root: TreeNode | null) => { + if (root == null) { + return root; + } + const { val, left, right } = root; + if (val < low || val > high) { + return dfs(left) || dfs(right); + } + root.left = dfs(left); + root.right = dfs(right); + return root; + }; + return dfs(root); +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn trim_bst( + mut root: Option>>, + low: i32, + high: i32 + ) -> Option>> { + if root.is_none() { + return root; + } + { + let mut node = root.as_mut().unwrap().borrow_mut(); + if node.val < low { + return Self::trim_bst(node.right.take(), low, high); + } + if node.val > high { + return Self::trim_bst(node.left.take(), low, high); + } + node.left = Self::trim_bst(node.left.take(), low, high); + node.right = Self::trim_bst(node.right.take(), low, high); + } + root + } +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} low + * @param {number} high + * @return {TreeNode} + */ +var trimBST = function (root, low, high) { + function dfs(root) { + if (!root) { + return root; + } + if (root.val < low) { + return dfs(root.right); + } + if (root.val > high) { + return dfs(root.left); + } + root.left = dfs(root.left); + root.right = dfs(root.right); + return root; + } + return dfs(root); +}; +``` + +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +struct TreeNode* trimBST(struct TreeNode* root, int low, int high) { + if (!root) { + return root; + } + if (root->val < low) { + return trimBST(root->right, low, high); + } + if (root->val > high) { + return trimBST(root->left, low, high); + } + root->left = trimBST(root->left, low, high); + root->right = trimBST(root->right, low, high); + return root; +} +``` + + + +### 方法二:迭代 + +我们先循环判断 `root`,若 `root.val` 不在 `[low, high]` 之间,那么直接将 `root` 置为对应的左孩子或右孩子,循环直至 `root` 为空或者 `root.val` 在 `[low, high]` 之间。 + +若此时 `root` 为空,直接返回。否则,说明 `root` 是一个需要保留的节点。接下来只需要分别迭代修剪 `root` 的左右子树。 + +以左子树 `node = root.left` 为例: + +- 若 `node.left.val` 小于 `low`,那么 `node.left` 及其左孩子均不满足条件,我们直接将 `node.left` 置为 `node.left.right`; +- 否则,我们将 `node` 置为 `node.left`; +- 循环判断,直至 `node.left` 为空。 + +右子树的修剪过程与之类似。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是二叉搜索树的节点个数。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def trimBST( + self, root: Optional[TreeNode], low: int, high: int + ) -> Optional[TreeNode]: + while root and (root.val < low or root.val > high): + root = root.left if root.val > high else root.right + if root is None: + return None + node = root + while node.left: + if node.left.val < low: + node.left = node.left.right + else: + node = node.left + node = root + while node.right: + if node.right.val > high: + node.right = node.right.left + else: + node = node.right + return root +``` + ```java /** * Definition for a binary tree node. @@ -214,33 +396,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* trimBST(TreeNode* root, int low, int high) { - if (!root) return root; - if (root->val > high) return trimBST(root->left, low, high); - if (root->val < low) return trimBST(root->right, low, high); - root->left = trimBST(root->left, low, high); - root->right = trimBST(root->right, low, high); - return root; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -283,33 +438,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func trimBST(root *TreeNode, low int, high int) *TreeNode { - if root == nil { - return root - } - if root.Val > high { - return trimBST(root.Left, low, high) - } - if root.Val < low { - return trimBST(root.Right, low, high) - } - root.Left = trimBST(root.Left, low, high) - root.Right = trimBST(root.Right, low, high) - return root -} -``` - ```go /** * Definition for a binary tree node. @@ -350,42 +478,6 @@ func trimBST(root *TreeNode, low int, high int) *TreeNode { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @param {number} low - * @param {number} high - * @return {TreeNode} - */ -var trimBST = function (root, low, high) { - function dfs(root) { - if (!root) { - return root; - } - if (root.val < low) { - return dfs(root.right); - } - if (root.val > high) { - return dfs(root.left); - } - root.left = dfs(root.left); - root.right = dfs(root.right); - return root; - } - return dfs(root); -}; -``` - ```js /** * Definition for a binary tree node. @@ -428,120 +520,6 @@ var trimBST = function (root, low, high) { }; ``` -### **C** - -```c -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -struct TreeNode* trimBST(struct TreeNode* root, int low, int high) { - if (!root) { - return root; - } - if (root->val < low) { - return trimBST(root->right, low, high); - } - if (root->val > high) { - return trimBST(root->left, low, high); - } - root->left = trimBST(root->left, low, high); - root->right = trimBST(root->right, low, high); - return root; -} -``` - -### **TypeScript** - -```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 trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null { - const dfs = (root: TreeNode | null) => { - if (root == null) { - return root; - } - const { val, left, right } = root; - if (val < low || val > high) { - return dfs(left) || dfs(right); - } - root.left = dfs(left); - root.right = dfs(right); - return root; - }; - return dfs(root); -} -``` - -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - pub fn trim_bst( - mut root: Option>>, - low: i32, - high: i32 - ) -> Option>> { - if root.is_none() { - return root; - } - { - let mut node = root.as_mut().unwrap().borrow_mut(); - if node.val < low { - return Self::trim_bst(node.right.take(), low, high); - } - if node.val > high { - return Self::trim_bst(node.left.take(), low, high); - } - node.left = Self::trim_bst(node.left.take(), low, high); - node.right = Self::trim_bst(node.right.take(), low, high); - } - root - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0669.Trim a Binary Search Tree/README_EN.md b/solution/0600-0699/0669.Trim a Binary Search Tree/README_EN.md index d8390b8d23cc8..6cd371c897ead 100644 --- a/solution/0600-0699/0669.Trim a Binary Search Tree/README_EN.md +++ b/solution/0600-0699/0669.Trim a Binary Search Tree/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -65,38 +65,6 @@ class Solution: return dfs(root) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def trimBST( - self, root: Optional[TreeNode], low: int, high: int - ) -> Optional[TreeNode]: - while root and (root.val < low or root.val > high): - root = root.left if root.val > high else root.right - if root is None: - return None - node = root - while node.left: - if node.left.val < low: - node.left = node.left.right - else: - node = node.left - node = root - while node.right: - if node.right.val > high: - node.right = node.right.left - else: - node = node.right - return root -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -131,6 +99,230 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* trimBST(TreeNode* root, int low, int high) { + if (!root) return root; + if (root->val > high) return trimBST(root->left, low, high); + if (root->val < low) return trimBST(root->right, low, high); + root->left = trimBST(root->left, low, high); + root->right = trimBST(root->right, low, high); + return root; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func trimBST(root *TreeNode, low int, high int) *TreeNode { + if root == nil { + return root + } + if root.Val > high { + return trimBST(root.Left, low, high) + } + if root.Val < low { + return trimBST(root.Right, low, high) + } + root.Left = trimBST(root.Left, low, high) + root.Right = trimBST(root.Right, low, high) + return root +} +``` + +```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 trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null { + const dfs = (root: TreeNode | null) => { + if (root == null) { + return root; + } + const { val, left, right } = root; + if (val < low || val > high) { + return dfs(left) || dfs(right); + } + root.left = dfs(left); + root.right = dfs(right); + return root; + }; + return dfs(root); +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn trim_bst( + mut root: Option>>, + low: i32, + high: i32 + ) -> Option>> { + if root.is_none() { + return root; + } + { + let mut node = root.as_mut().unwrap().borrow_mut(); + if node.val < low { + return Self::trim_bst(node.right.take(), low, high); + } + if node.val > high { + return Self::trim_bst(node.left.take(), low, high); + } + node.left = Self::trim_bst(node.left.take(), low, high); + node.right = Self::trim_bst(node.right.take(), low, high); + } + root + } +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} low + * @param {number} high + * @return {TreeNode} + */ +var trimBST = function (root, low, high) { + function dfs(root) { + if (!root) { + return root; + } + if (root.val < low) { + return dfs(root.right); + } + if (root.val > high) { + return dfs(root.left); + } + root.left = dfs(root.left); + root.right = dfs(root.right); + return root; + } + return dfs(root); +}; +``` + +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +struct TreeNode* trimBST(struct TreeNode* root, int low, int high) { + if (!root) { + return root; + } + if (root->val < low) { + return trimBST(root->right, low, high); + } + if (root->val > high) { + return trimBST(root->left, low, high); + } + root->left = trimBST(root->left, low, high); + root->right = trimBST(root->right, low, high); + return root; +} +``` + + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def trimBST( + self, root: Optional[TreeNode], low: int, high: int + ) -> Optional[TreeNode]: + while root and (root.val < low or root.val > high): + root = root.left if root.val > high else root.right + if root is None: + return None + node = root + while node.left: + if node.left.val < low: + node.left = node.left.right + else: + node = node.left + node = root + while node.right: + if node.right.val > high: + node.right = node.right.left + else: + node = node.right + return root +``` + ```java /** * Definition for a binary tree node. @@ -176,33 +368,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* trimBST(TreeNode* root, int low, int high) { - if (!root) return root; - if (root->val > high) return trimBST(root->left, low, high); - if (root->val < low) return trimBST(root->right, low, high); - root->left = trimBST(root->left, low, high); - root->right = trimBST(root->right, low, high); - return root; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -245,33 +410,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func trimBST(root *TreeNode, low int, high int) *TreeNode { - if root == nil { - return root - } - if root.Val > high { - return trimBST(root.Left, low, high) - } - if root.Val < low { - return trimBST(root.Right, low, high) - } - root.Left = trimBST(root.Left, low, high) - root.Right = trimBST(root.Right, low, high) - return root -} -``` - ```go /** * Definition for a binary tree node. @@ -312,42 +450,6 @@ func trimBST(root *TreeNode, low int, high int) *TreeNode { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @param {number} low - * @param {number} high - * @return {TreeNode} - */ -var trimBST = function (root, low, high) { - function dfs(root) { - if (!root) { - return root; - } - if (root.val < low) { - return dfs(root.right); - } - if (root.val > high) { - return dfs(root.left); - } - root.left = dfs(root.left); - root.right = dfs(root.right); - return root; - } - return dfs(root); -}; -``` - ```js /** * Definition for a binary tree node. @@ -390,120 +492,6 @@ var trimBST = function (root, low, high) { }; ``` -### **C** - -```c -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -struct TreeNode* trimBST(struct TreeNode* root, int low, int high) { - if (!root) { - return root; - } - if (root->val < low) { - return trimBST(root->right, low, high); - } - if (root->val > high) { - return trimBST(root->left, low, high); - } - root->left = trimBST(root->left, low, high); - root->right = trimBST(root->right, low, high); - return root; -} -``` - -### **TypeScript** - -```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 trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null { - const dfs = (root: TreeNode | null) => { - if (root == null) { - return root; - } - const { val, left, right } = root; - if (val < low || val > high) { - return dfs(left) || dfs(right); - } - root.left = dfs(left); - root.right = dfs(right); - return root; - }; - return dfs(root); -} -``` - -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - pub fn trim_bst( - mut root: Option>>, - low: i32, - high: i32 - ) -> Option>> { - if root.is_none() { - return root; - } - { - let mut node = root.as_mut().unwrap().borrow_mut(); - if node.val < low { - return Self::trim_bst(node.right.take(), low, high); - } - if node.val > high { - return Self::trim_bst(node.left.take(), low, high); - } - node.left = Self::trim_bst(node.left.take(), low, high); - node.right = Self::trim_bst(node.right.take(), low, high); - } - root - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0670.Maximum Swap/README.md b/solution/0600-0699/0670.Maximum Swap/README.md index 5ad15353091e3..209fdaa95094e 100644 --- a/solution/0600-0699/0670.Maximum Swap/README.md +++ b/solution/0600-0699/0670.Maximum Swap/README.md @@ -32,9 +32,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 先将数字转为字符串 `s`,然后从右往左遍历字符串 `s`,用数组或哈希表 `d` 记录每个数字右侧的最大数字的位置(可以是字符本身的位置)。 @@ -46,10 +44,6 @@ -### **Python3** - - - ```python class Solution: def maximumSwap(self, num: int) -> int: @@ -66,10 +60,6 @@ class Solution: return int(''.join(s)) ``` -### **Java** - - - ```java class Solution { public int maximumSwap(int num) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func maximumSwap(num int) int { s := []byte(strconv.Itoa(num)) @@ -151,8 +137,6 @@ func maximumSwap(num int) int { } ``` -### **TypeScript** - ```ts function maximumSwap(num: number): number { const list = new Array(); @@ -182,8 +166,6 @@ function maximumSwap(num: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn maximum_swap(mut num: i32) -> i32 { @@ -222,10 +204,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0670.Maximum Swap/README_EN.md b/solution/0600-0699/0670.Maximum Swap/README_EN.md index efa97e199b7e2..e75e946dfe4d5 100644 --- a/solution/0600-0699/0670.Maximum Swap/README_EN.md +++ b/solution/0600-0699/0670.Maximum Swap/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return int(''.join(s)) ``` -### **Java** - ```java class Solution { public int maximumSwap(int num) { @@ -84,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +107,6 @@ public: }; ``` -### **Go** - ```go func maximumSwap(num int) int { s := []byte(strconv.Itoa(num)) @@ -137,8 +131,6 @@ func maximumSwap(num int) int { } ``` -### **TypeScript** - ```ts function maximumSwap(num: number): number { const list = new Array(); @@ -168,8 +160,6 @@ function maximumSwap(num: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn maximum_swap(mut num: i32) -> i32 { @@ -208,10 +198,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0671.Second Minimum Node In a Binary Tree/README.md b/solution/0600-0699/0671.Second Minimum Node In a Binary Tree/README.md index ca27334e71af3..2f994b87b80bb 100644 --- a/solution/0600-0699/0671.Second Minimum Node In a Binary Tree/README.md +++ b/solution/0600-0699/0671.Second Minimum Node In a Binary Tree/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 直接 DFS 遍历二叉树,找到大于 `root.val` 的最小值。若不存在,则返回 -1。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -152,8 +140,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -183,8 +169,6 @@ func findSecondMinimumValue(root *TreeNode) int { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -218,10 +202,6 @@ var findSecondMinimumValue = function (root) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0671.Second Minimum Node In a Binary Tree/README_EN.md b/solution/0600-0699/0671.Second Minimum Node In a Binary Tree/README_EN.md index 932561d3a4ef5..0a5644c884116 100644 --- a/solution/0600-0699/0671.Second Minimum Node In a Binary Tree/README_EN.md +++ b/solution/0600-0699/0671.Second Minimum Node In a Binary Tree/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -66,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -136,8 +132,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -167,8 +161,6 @@ func findSecondMinimumValue(root *TreeNode) int { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -202,10 +194,6 @@ var findSecondMinimumValue = function (root) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0672.Bulb Switcher II/README.md b/solution/0600-0699/0672.Bulb Switcher II/README.md index 66571f6871fd5..309024cf8ca61 100644 --- a/solution/0600-0699/0672.Bulb Switcher II/README.md +++ b/solution/0600-0699/0672.Bulb Switcher II/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 观察灯泡开关随按钮操作的变化规律,我们可以发现,位置 $i$ 与 $i+6$ 的灯泡,开关状态始终保持一致,因此,我们只需要考虑最多前 $n=6$ 个灯泡的开关状态。 @@ -83,10 +81,6 @@ -### **Python3** - - - ```python class Solution: def flipLights(self, n: int, presses: int) -> int: @@ -106,10 +100,6 @@ class Solution: return len(vis) ``` -### **Java** - - - ```java class Solution { public int flipLights(int n, int presses) { @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go func flipLights(n int, presses int) int { if n > 6 { @@ -189,10 +175,6 @@ func flipLights(n int, presses int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0672.Bulb Switcher II/README_EN.md b/solution/0600-0699/0672.Bulb Switcher II/README_EN.md index 526069a20a339..2edf02b0939f7 100644 --- a/solution/0600-0699/0672.Bulb Switcher II/README_EN.md +++ b/solution/0600-0699/0672.Bulb Switcher II/README_EN.md @@ -61,9 +61,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: return len(vis) ``` -### **Java** - ```java class Solution { public int flipLights(int n, int presses) { @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +134,6 @@ public: }; ``` -### **Go** - ```go func flipLights(n int, presses int) int { if n > 6 { @@ -165,10 +159,6 @@ func flipLights(n int, presses int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/README.md b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/README.md index d4c94adb67c50..b011854b7465d 100644 --- a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/README.md +++ b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示以 $nums[i]$ 结尾的最长递增子序列的长度,定义 $cnt[i]$ 表示以 $nums[i]$ 结尾的最长递增子序列的个数。初始时 $f[i]=1$, $cnt[i]=1$。另外,定义 $mx$ 表示最长递增子序列的长度,定义 $ans$ 表示最长递增子序列的个数。 @@ -53,18 +51,8 @@ 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。 -**方法二:树状数组** - -我们可以用树状数组维护前缀区间的最长递增子序列的长度和个数。我们将数组 $nums$ 中的元素去重并排序,得到数组 $arr$,然后我们枚举 $nums$ 中的每一个元素 $x$,在数组 $arr$ 中二分查找 $x$ 的位置 $i$,然后查询 $[1,i-1]$ 的最长递增子序列的长度和个数,记为 $v$ 和 $cnt$,然后更新 $[i]$ 的最长递增子序列的长度和个数为 $v+1$ 和 $\max(cnt,1)$。最后,我们查询 $[1,m]$ 的最长递增子序列的长度和个数,其中 $m$ 是数组 $arr$ 的长度,即为答案。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。 - -### **Python3** - - - ```python class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: @@ -88,6 +76,165 @@ class Solution: return ans ``` +```java +class Solution { + public int findNumberOfLIS(int[] nums) { + int n = nums.length; + int[] f = new int[n]; + int[] cnt = new int[n]; + int mx = 0, ans = 0; + for (int i = 0; i < n; ++i) { + f[i] = 1; + cnt[i] = 1; + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + if (f[i] < f[j] + 1) { + f[i] = f[j] + 1; + cnt[i] = cnt[j]; + } else if (f[i] == f[j] + 1) { + cnt[i] += cnt[j]; + } + } + } + if (mx < f[i]) { + mx = f[i]; + ans = cnt[i]; + } else if (mx == f[i]) { + ans += cnt[i]; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int findNumberOfLIS(vector& nums) { + int n = nums.size(); + int mx = 0, ans = 0; + vector f(n, 1); + vector cnt(n, 1); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + if (f[i] < f[j] + 1) { + f[i] = f[j] + 1; + cnt[i] = cnt[j]; + } else if (f[i] == f[j] + 1) { + cnt[i] += cnt[j]; + } + } + } + if (mx < f[i]) { + mx = f[i]; + ans = cnt[i]; + } else if (mx == f[i]) { + ans += cnt[i]; + } + } + return ans; + } +}; +``` + +```go +func findNumberOfLIS(nums []int) (ans int) { + n, mx := len(nums), 0 + f := make([]int, n) + cnt := make([]int, n) + for i, x := range nums { + for j, y := range nums[:i] { + if y < x { + if f[i] < f[j]+1 { + f[i] = f[j] + 1 + cnt[i] = cnt[j] + } else if f[i] == f[j]+1 { + cnt[i] += cnt[j] + } + } + } + if mx < f[i] { + mx = f[i] + ans = cnt[i] + } else if mx == f[i] { + ans += cnt[i] + } + } + return +} +``` + +```ts +function findNumberOfLIS(nums: number[]): number { + const n = nums.length; + let [ans, mx] = [0, 0]; + const f: number[] = Array(n).fill(1); + const cnt: number[] = Array(n).fill(1); + for (let i = 0; i < n; ++i) { + for (let j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + if (f[i] < f[j] + 1) { + f[i] = f[j] + 1; + cnt[i] = cnt[j]; + } else if (f[i] === f[j] + 1) { + cnt[i] += cnt[j]; + } + } + } + if (mx < f[i]) { + mx = f[i]; + ans = cnt[i]; + } else if (mx === f[i]) { + ans += cnt[i]; + } + } + return ans; +} +``` + +```rust +impl Solution { + pub fn find_number_of_lis(nums: Vec) -> i32 { + let n = nums.len(); + let mut ans = 0; + let mut mx = 0; + let mut f = vec![1; n]; + let mut cnt = vec![1; n]; + for i in 0..n { + for j in 0..i { + if nums[j] < nums[i] { + if f[i] < f[j] + 1 { + f[i] = f[j] + 1; + cnt[i] = cnt[j]; + } else if f[i] == f[j] + 1 { + cnt[i] += cnt[j]; + } + } + } + if mx < f[i] { + mx = f[i]; + ans = cnt[i]; + } else if mx == f[i] { + ans += cnt[i]; + } + } + ans + } +} +``` + + + +### 方法二:树状数组 + +我们可以用树状数组维护前缀区间的最长递增子序列的长度和个数。我们将数组 $nums$ 中的元素去重并排序,得到数组 $arr$,然后我们枚举 $nums$ 中的每一个元素 $x$,在数组 $arr$ 中二分查找 $x$ 的位置 $i$,然后查询 $[1,i-1]$ 的最长递增子序列的长度和个数,记为 $v$ 和 $cnt$,然后更新 $[i]$ 的最长递增子序列的长度和个数为 $v+1$ 和 $\max(cnt,1)$。最后,我们查询 $[1,m]$ 的最长递增子序列的长度和个数,其中 $m$ 是数组 $arr$ 的长度,即为答案。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。 + + + ```python class BinaryIndexedTree: __slots__ = ["n", "c", "d"] @@ -130,42 +277,6 @@ class Solution: return tree.query(m)[1] ``` -### **Java** - - - -```java -class Solution { - public int findNumberOfLIS(int[] nums) { - int n = nums.length; - int[] f = new int[n]; - int[] cnt = new int[n]; - int mx = 0, ans = 0; - for (int i = 0; i < n; ++i) { - f[i] = 1; - cnt[i] = 1; - for (int j = 0; j < i; ++j) { - if (nums[j] < nums[i]) { - if (f[i] < f[j] + 1) { - f[i] = f[j] + 1; - cnt[i] = cnt[j]; - } else if (f[i] == f[j] + 1) { - cnt[i] += cnt[j]; - } - } - } - if (mx < f[i]) { - mx = f[i]; - ans = cnt[i]; - } else if (mx == f[i]) { - ans += cnt[i]; - } - } - return ans; - } -} -``` - ```java class BinaryIndexedTree { private int n; @@ -224,39 +335,6 @@ public class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int findNumberOfLIS(vector& nums) { - int n = nums.size(); - int mx = 0, ans = 0; - vector f(n, 1); - vector cnt(n, 1); - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (nums[j] < nums[i]) { - if (f[i] < f[j] + 1) { - f[i] = f[j] + 1; - cnt[i] = cnt[j]; - } else if (f[i] == f[j] + 1) { - cnt[i] += cnt[j]; - } - } - } - if (mx < f[i]) { - mx = f[i]; - ans = cnt[i]; - } else if (mx == f[i]) { - ans += cnt[i]; - } - } - return ans; - } -}; -``` - ```cpp class BinaryIndexedTree { private: @@ -316,35 +394,6 @@ public: }; ``` -### **Go** - -```go -func findNumberOfLIS(nums []int) (ans int) { - n, mx := len(nums), 0 - f := make([]int, n) - cnt := make([]int, n) - for i, x := range nums { - for j, y := range nums[:i] { - if y < x { - if f[i] < f[j]+1 { - f[i] = f[j] + 1 - cnt[i] = cnt[j] - } else if f[i] == f[j]+1 { - cnt[i] += cnt[j] - } - } - } - if mx < f[i] { - mx = f[i] - ans = cnt[i] - } else if mx == f[i] { - ans += cnt[i] - } - } - return -} -``` - ```go type BinaryIndexedTree struct { n int @@ -402,131 +451,6 @@ func findNumberOfLIS(nums []int) int { } ``` -### **Rust** - -```rust -impl Solution { - pub fn find_number_of_lis(nums: Vec) -> i32 { - let n = nums.len(); - let mut ans = 0; - let mut mx = 0; - let mut f = vec![1; n]; - let mut cnt = vec![1; n]; - for i in 0..n { - for j in 0..i { - if nums[j] < nums[i] { - if f[i] < f[j] + 1 { - f[i] = f[j] + 1; - cnt[i] = cnt[j]; - } else if f[i] == f[j] + 1 { - cnt[i] += cnt[j]; - } - } - } - if mx < f[i] { - mx = f[i]; - ans = cnt[i]; - } else if mx == f[i] { - ans += cnt[i]; - } - } - ans - } -} -``` - -```rust -struct BinaryIndexedTree { - n: usize, - c: Vec, - d: Vec, -} - -impl BinaryIndexedTree { - fn new(n: usize) -> BinaryIndexedTree { - BinaryIndexedTree { - n, - c: vec![0; n + 1], - d: vec![0; n + 1], - } - } - - fn update(&mut self, x: usize, v: i32, cnt: i32) { - let mut x = x as usize; - while x <= self.n { - if self.c[x] < v { - self.c[x] = v; - self.d[x] = cnt; - } else if self.c[x] == v { - self.d[x] += cnt; - } - x += x & x.wrapping_neg(); - } - } - - fn query(&self, mut x: usize) -> (i32, i32) { - let (mut v, mut cnt) = (0, 0); - while x > 0 { - if self.c[x] > v { - v = self.c[x]; - cnt = self.d[x]; - } else if self.c[x] == v { - cnt += self.d[x]; - } - x -= x & x.wrapping_neg(); - } - (v, cnt) - } -} - -impl Solution { - pub fn find_number_of_lis(nums: Vec) -> i32 { - let mut arr: Vec = nums.iter().cloned().collect(); - arr.sort(); - let m = arr.len(); - let mut tree = BinaryIndexedTree::new(m); - for x in nums.iter() { - if let Ok(i) = arr.binary_search(x) { - let (v, cnt) = tree.query(i); - tree.update(i + 1, v + 1, cnt.max(1)); - } - } - let (_, ans) = tree.query(m); - ans - } -} -``` - -### **TypeScript** - -```ts -function findNumberOfLIS(nums: number[]): number { - const n = nums.length; - let [ans, mx] = [0, 0]; - const f: number[] = Array(n).fill(1); - const cnt: number[] = Array(n).fill(1); - for (let i = 0; i < n; ++i) { - for (let j = 0; j < i; ++j) { - if (nums[j] < nums[i]) { - if (f[i] < f[j] + 1) { - f[i] = f[j] + 1; - cnt[i] = cnt[j]; - } else if (f[i] === f[j] + 1) { - cnt[i] += cnt[j]; - } - } - } - if (mx < f[i]) { - mx = f[i]; - ans = cnt[i]; - } else if (mx === f[i]) { - ans += cnt[i]; - } - } - return ans; -} -``` - ```ts class BinaryIndexedTree { private n: number; @@ -593,10 +517,68 @@ function findNumberOfLIS(nums: number[]): number { } ``` -### **...** +```rust +struct BinaryIndexedTree { + n: usize, + c: Vec, + d: Vec, +} + +impl BinaryIndexedTree { + fn new(n: usize) -> BinaryIndexedTree { + BinaryIndexedTree { + n, + c: vec![0; n + 1], + d: vec![0; n + 1], + } + } -``` + fn update(&mut self, x: usize, v: i32, cnt: i32) { + let mut x = x as usize; + while x <= self.n { + if self.c[x] < v { + self.c[x] = v; + self.d[x] = cnt; + } else if self.c[x] == v { + self.d[x] += cnt; + } + x += x & x.wrapping_neg(); + } + } + fn query(&self, mut x: usize) -> (i32, i32) { + let (mut v, mut cnt) = (0, 0); + while x > 0 { + if self.c[x] > v { + v = self.c[x]; + cnt = self.d[x]; + } else if self.c[x] == v { + cnt += self.d[x]; + } + x -= x & x.wrapping_neg(); + } + (v, cnt) + } +} + +impl Solution { + pub fn find_number_of_lis(nums: Vec) -> i32 { + let mut arr: Vec = nums.iter().cloned().collect(); + arr.sort(); + let m = arr.len(); + let mut tree = BinaryIndexedTree::new(m); + for x in nums.iter() { + if let Ok(i) = arr.binary_search(x) { + let (v, cnt) = tree.query(i); + tree.update(i + 1, v + 1, cnt.max(1)); + } + } + let (_, ans) = tree.query(m); + ans + } +} ``` + + diff --git a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/README_EN.md b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/README_EN.md index 55637adeefda2..bd59d42faa096 100644 --- a/solution/0600-0699/0673.Number of Longest Increasing Subsequence/README_EN.md +++ b/solution/0600-0699/0673.Number of Longest Increasing Subsequence/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i]$ as the length of the longest increasing subsequence ending with $nums[i]$, and $cnt[i]$ as the number of longest increasing subsequences ending with $nums[i]$. Initially, $f[i]=1$, $cnt[i]=1$. Also, we define $mx$ as the length of the longest increasing subsequence, and $ans$ as the number of longest increasing subsequences. @@ -45,16 +45,8 @@ Finally, we return $ans$. The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. -**Solution 2: Binary Indexed Tree** - -We can use a binary indexed tree to maintain the length and count of the longest increasing subsequence in the prefix interval. We remove duplicates from the array $nums$ and sort it to get the array $arr$. Then we enumerate each element $x$ in $nums$, find the position $i$ of $x$ in the array $arr$ by binary search, then query the length and count of the longest increasing subsequence in $[1,i-1]$, denoted as $v$ and $cnt$, then update the length and count of the longest increasing subsequence in $[i]$ to $v+1$ and $\max(cnt,1)$. Finally, we query the length and count of the longest increasing subsequence in $[1,m]$, where $m$ is the length of the array $arr$, which is the answer. - -The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. - -### **Python3** - ```python class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: @@ -78,6 +70,165 @@ class Solution: return ans ``` +```java +class Solution { + public int findNumberOfLIS(int[] nums) { + int n = nums.length; + int[] f = new int[n]; + int[] cnt = new int[n]; + int mx = 0, ans = 0; + for (int i = 0; i < n; ++i) { + f[i] = 1; + cnt[i] = 1; + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + if (f[i] < f[j] + 1) { + f[i] = f[j] + 1; + cnt[i] = cnt[j]; + } else if (f[i] == f[j] + 1) { + cnt[i] += cnt[j]; + } + } + } + if (mx < f[i]) { + mx = f[i]; + ans = cnt[i]; + } else if (mx == f[i]) { + ans += cnt[i]; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int findNumberOfLIS(vector& nums) { + int n = nums.size(); + int mx = 0, ans = 0; + vector f(n, 1); + vector cnt(n, 1); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + if (f[i] < f[j] + 1) { + f[i] = f[j] + 1; + cnt[i] = cnt[j]; + } else if (f[i] == f[j] + 1) { + cnt[i] += cnt[j]; + } + } + } + if (mx < f[i]) { + mx = f[i]; + ans = cnt[i]; + } else if (mx == f[i]) { + ans += cnt[i]; + } + } + return ans; + } +}; +``` + +```go +func findNumberOfLIS(nums []int) (ans int) { + n, mx := len(nums), 0 + f := make([]int, n) + cnt := make([]int, n) + for i, x := range nums { + for j, y := range nums[:i] { + if y < x { + if f[i] < f[j]+1 { + f[i] = f[j] + 1 + cnt[i] = cnt[j] + } else if f[i] == f[j]+1 { + cnt[i] += cnt[j] + } + } + } + if mx < f[i] { + mx = f[i] + ans = cnt[i] + } else if mx == f[i] { + ans += cnt[i] + } + } + return +} +``` + +```ts +function findNumberOfLIS(nums: number[]): number { + const n = nums.length; + let [ans, mx] = [0, 0]; + const f: number[] = Array(n).fill(1); + const cnt: number[] = Array(n).fill(1); + for (let i = 0; i < n; ++i) { + for (let j = 0; j < i; ++j) { + if (nums[j] < nums[i]) { + if (f[i] < f[j] + 1) { + f[i] = f[j] + 1; + cnt[i] = cnt[j]; + } else if (f[i] === f[j] + 1) { + cnt[i] += cnt[j]; + } + } + } + if (mx < f[i]) { + mx = f[i]; + ans = cnt[i]; + } else if (mx === f[i]) { + ans += cnt[i]; + } + } + return ans; +} +``` + +```rust +impl Solution { + pub fn find_number_of_lis(nums: Vec) -> i32 { + let n = nums.len(); + let mut ans = 0; + let mut mx = 0; + let mut f = vec![1; n]; + let mut cnt = vec![1; n]; + for i in 0..n { + for j in 0..i { + if nums[j] < nums[i] { + if f[i] < f[j] + 1 { + f[i] = f[j] + 1; + cnt[i] = cnt[j]; + } else if f[i] == f[j] + 1 { + cnt[i] += cnt[j]; + } + } + } + if mx < f[i] { + mx = f[i]; + ans = cnt[i]; + } else if mx == f[i] { + ans += cnt[i]; + } + } + ans + } +} +``` + + + +### Solution 2: Binary Indexed Tree + +We can use a binary indexed tree to maintain the length and count of the longest increasing subsequence in the prefix interval. We remove duplicates from the array $nums$ and sort it to get the array $arr$. Then we enumerate each element $x$ in $nums$, find the position $i$ of $x$ in the array $arr$ by binary search, then query the length and count of the longest increasing subsequence in $[1,i-1]$, denoted as $v$ and $cnt$, then update the length and count of the longest increasing subsequence in $[i]$ to $v+1$ and $\max(cnt,1)$. Finally, we query the length and count of the longest increasing subsequence in $[1,m]$, where $m$ is the length of the array $arr$, which is the answer. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. + + + ```python class BinaryIndexedTree: __slots__ = ["n", "c", "d"] @@ -120,40 +271,6 @@ class Solution: return tree.query(m)[1] ``` -### **Java** - -```java -class Solution { - public int findNumberOfLIS(int[] nums) { - int n = nums.length; - int[] f = new int[n]; - int[] cnt = new int[n]; - int mx = 0, ans = 0; - for (int i = 0; i < n; ++i) { - f[i] = 1; - cnt[i] = 1; - for (int j = 0; j < i; ++j) { - if (nums[j] < nums[i]) { - if (f[i] < f[j] + 1) { - f[i] = f[j] + 1; - cnt[i] = cnt[j]; - } else if (f[i] == f[j] + 1) { - cnt[i] += cnt[j]; - } - } - } - if (mx < f[i]) { - mx = f[i]; - ans = cnt[i]; - } else if (mx == f[i]) { - ans += cnt[i]; - } - } - return ans; - } -} -``` - ```java class BinaryIndexedTree { private int n; @@ -212,39 +329,6 @@ public class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int findNumberOfLIS(vector& nums) { - int n = nums.size(); - int mx = 0, ans = 0; - vector f(n, 1); - vector cnt(n, 1); - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (nums[j] < nums[i]) { - if (f[i] < f[j] + 1) { - f[i] = f[j] + 1; - cnt[i] = cnt[j]; - } else if (f[i] == f[j] + 1) { - cnt[i] += cnt[j]; - } - } - } - if (mx < f[i]) { - mx = f[i]; - ans = cnt[i]; - } else if (mx == f[i]) { - ans += cnt[i]; - } - } - return ans; - } -}; -``` - ```cpp class BinaryIndexedTree { private: @@ -304,35 +388,6 @@ public: }; ``` -### **Go** - -```go -func findNumberOfLIS(nums []int) (ans int) { - n, mx := len(nums), 0 - f := make([]int, n) - cnt := make([]int, n) - for i, x := range nums { - for j, y := range nums[:i] { - if y < x { - if f[i] < f[j]+1 { - f[i] = f[j] + 1 - cnt[i] = cnt[j] - } else if f[i] == f[j]+1 { - cnt[i] += cnt[j] - } - } - } - if mx < f[i] { - mx = f[i] - ans = cnt[i] - } else if mx == f[i] { - ans += cnt[i] - } - } - return -} -``` - ```go type BinaryIndexedTree struct { n int @@ -390,131 +445,6 @@ func findNumberOfLIS(nums []int) int { } ``` -### **Rust** - -```rust -impl Solution { - pub fn find_number_of_lis(nums: Vec) -> i32 { - let n = nums.len(); - let mut ans = 0; - let mut mx = 0; - let mut f = vec![1; n]; - let mut cnt = vec![1; n]; - for i in 0..n { - for j in 0..i { - if nums[j] < nums[i] { - if f[i] < f[j] + 1 { - f[i] = f[j] + 1; - cnt[i] = cnt[j]; - } else if f[i] == f[j] + 1 { - cnt[i] += cnt[j]; - } - } - } - if mx < f[i] { - mx = f[i]; - ans = cnt[i]; - } else if mx == f[i] { - ans += cnt[i]; - } - } - ans - } -} -``` - -```rust -struct BinaryIndexedTree { - n: usize, - c: Vec, - d: Vec, -} - -impl BinaryIndexedTree { - fn new(n: usize) -> BinaryIndexedTree { - BinaryIndexedTree { - n, - c: vec![0; n + 1], - d: vec![0; n + 1], - } - } - - fn update(&mut self, x: usize, v: i32, cnt: i32) { - let mut x = x as usize; - while x <= self.n { - if self.c[x] < v { - self.c[x] = v; - self.d[x] = cnt; - } else if self.c[x] == v { - self.d[x] += cnt; - } - x += x & x.wrapping_neg(); - } - } - - fn query(&self, mut x: usize) -> (i32, i32) { - let (mut v, mut cnt) = (0, 0); - while x > 0 { - if self.c[x] > v { - v = self.c[x]; - cnt = self.d[x]; - } else if self.c[x] == v { - cnt += self.d[x]; - } - x -= x & x.wrapping_neg(); - } - (v, cnt) - } -} - -impl Solution { - pub fn find_number_of_lis(nums: Vec) -> i32 { - let mut arr: Vec = nums.iter().cloned().collect(); - arr.sort(); - let m = arr.len(); - let mut tree = BinaryIndexedTree::new(m); - for x in nums.iter() { - if let Ok(i) = arr.binary_search(x) { - let (v, cnt) = tree.query(i); - tree.update(i + 1, v + 1, cnt.max(1)); - } - } - let (_, ans) = tree.query(m); - ans - } -} -``` - -### **TypeScript** - -```ts -function findNumberOfLIS(nums: number[]): number { - const n = nums.length; - let [ans, mx] = [0, 0]; - const f: number[] = Array(n).fill(1); - const cnt: number[] = Array(n).fill(1); - for (let i = 0; i < n; ++i) { - for (let j = 0; j < i; ++j) { - if (nums[j] < nums[i]) { - if (f[i] < f[j] + 1) { - f[i] = f[j] + 1; - cnt[i] = cnt[j]; - } else if (f[i] === f[j] + 1) { - cnt[i] += cnt[j]; - } - } - } - if (mx < f[i]) { - mx = f[i]; - ans = cnt[i]; - } else if (mx === f[i]) { - ans += cnt[i]; - } - } - return ans; -} -``` - ```ts class BinaryIndexedTree { private n: number; @@ -581,10 +511,68 @@ function findNumberOfLIS(nums: number[]): number { } ``` -### **...** +```rust +struct BinaryIndexedTree { + n: usize, + c: Vec, + d: Vec, +} + +impl BinaryIndexedTree { + fn new(n: usize) -> BinaryIndexedTree { + BinaryIndexedTree { + n, + c: vec![0; n + 1], + d: vec![0; n + 1], + } + } -``` + fn update(&mut self, x: usize, v: i32, cnt: i32) { + let mut x = x as usize; + while x <= self.n { + if self.c[x] < v { + self.c[x] = v; + self.d[x] = cnt; + } else if self.c[x] == v { + self.d[x] += cnt; + } + x += x & x.wrapping_neg(); + } + } + fn query(&self, mut x: usize) -> (i32, i32) { + let (mut v, mut cnt) = (0, 0); + while x > 0 { + if self.c[x] > v { + v = self.c[x]; + cnt = self.d[x]; + } else if self.c[x] == v { + cnt += self.d[x]; + } + x -= x & x.wrapping_neg(); + } + (v, cnt) + } +} + +impl Solution { + pub fn find_number_of_lis(nums: Vec) -> i32 { + let mut arr: Vec = nums.iter().cloned().collect(); + arr.sort(); + let m = arr.len(); + let mut tree = BinaryIndexedTree::new(m); + for x in nums.iter() { + if let Ok(i) = arr.binary_search(x) { + let (v, cnt) = tree.query(i); + tree.update(i + 1, v + 1, cnt.max(1)); + } + } + let (_, ans) = tree.query(m); + ans + } +} ``` + + diff --git a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/README.md b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/README.md index f7786d5681847..f7b0d22d8b861 100644 --- a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/README.md +++ b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们可以遍历数组 $nums$,用变量 $cnt$ 记录当前连续递增序列的长度。初始时 $cnt = 1$。 @@ -52,18 +50,8 @@ 时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 -**方法二:双指针** - -我们也可以用双指针 $i$ 和 $j$ 找到每一段连续递增序列,找出最长的连续递增序列的长度作为答案。 - -时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: @@ -77,24 +65,6 @@ class Solution: return ans ``` -```python -class Solution: - def findLengthOfLCIS(self, nums: List[int]) -> int: - ans, n = 1, len(nums) - i = 0 - while i < n: - j = i + 1 - while j < n and nums[j - 1] < nums[j]: - j += 1 - ans = max(ans, j - i) - i = j - return ans -``` - -### **Java** - - - ```java class Solution { public int findLengthOfLCIS(int[] nums) { @@ -111,26 +81,6 @@ class Solution { } ``` -```java -class Solution { - public int findLengthOfLCIS(int[] nums) { - int ans = 1; - int n = nums.length; - for (int i = 0; i < n;) { - int j = i + 1; - while (j < n && nums[j - 1] < nums[j]) { - ++j; - } - ans = Math.max(ans, j - i); - i = j; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -148,27 +98,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findLengthOfLCIS(vector& nums) { - int ans = 1; - int n = nums.size(); - for (int i = 0; i < n;) { - int j = i + 1; - while (j < n && nums[j - 1] < nums[j]) { - ++j; - } - ans = max(ans, j - i); - i = j; - } - return ans; - } -}; -``` - -### **Go** - ```go func findLengthOfLCIS(nums []int) int { ans, cnt := 1, 1 @@ -184,24 +113,20 @@ func findLengthOfLCIS(nums []int) int { } ``` -```go -func findLengthOfLCIS(nums []int) int { - ans := 1 - n := len(nums) - for i := 0; i < n; { - j := i + 1 - for j < n && nums[j-1] < nums[j] { - j++ - } - ans = max(ans, j-i) - i = j - } - return ans +```ts +function findLengthOfLCIS(nums: number[]): number { + let [ans, cnt] = [1, 1]; + for (let i = 1; i < nums.length; ++i) { + if (nums[i - 1] < nums[i]) { + ans = Math.max(ans, ++cnt); + } else { + cnt = 1; + } + } + return ans; } ``` -### **Rust** - ```rust impl Solution { pub fn find_length_of_lcis(nums: Vec) -> i32 { @@ -220,38 +145,101 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn find_length_of_lcis(nums: Vec) -> i32 { - let mut ans = 1; - let n = nums.len(); - let mut i = 0; - while i < n { - let mut j = i + 1; - while j < n && nums[j - 1] < nums[j] { - j += 1; +```php +class Solution { + /** + * @param Integer[] $nums + * @return Integer + */ + function findLengthOfLCIS($nums) { + $ans = 1; + $cnt = 1; + for ($i = 1; $i < count($nums); ++$i) { + if ($nums[$i - 1] < $nums[$i]) { + $ans = max($ans, ++$cnt); + } else { + $cnt = 1; } - ans = ans.max(j - i); - i = j; } - ans as i32 + return $ans; } } ``` -### **TypeScript** + -```ts -function findLengthOfLCIS(nums: number[]): number { - let [ans, cnt] = [1, 1]; - for (let i = 1; i < nums.length; ++i) { - if (nums[i - 1] < nums[i]) { - ans = Math.max(ans, ++cnt); - } else { - cnt = 1; +### 方法二:双指针 + +我们也可以用双指针 $i$ 和 $j$ 找到每一段连续递增序列,找出最长的连续递增序列的长度作为答案。 + +时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def findLengthOfLCIS(self, nums: List[int]) -> int: + ans, n = 1, len(nums) + i = 0 + while i < n: + j = i + 1 + while j < n and nums[j - 1] < nums[j]: + j += 1 + ans = max(ans, j - i) + i = j + return ans +``` + +```java +class Solution { + public int findLengthOfLCIS(int[] nums) { + int ans = 1; + int n = nums.length; + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[j - 1] < nums[j]) { + ++j; + } + ans = Math.max(ans, j - i); + i = j; } + return ans; } - return ans; +} +``` + +```cpp +class Solution { +public: + int findLengthOfLCIS(vector& nums) { + int ans = 1; + int n = nums.size(); + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[j - 1] < nums[j]) { + ++j; + } + ans = max(ans, j - i); + i = j; + } + return ans; + } +}; +``` + +```go +func findLengthOfLCIS(nums []int) int { + ans := 1 + n := len(nums) + for i := 0; i < n; { + j := i + 1 + for j < n && nums[j-1] < nums[j] { + j++ + } + ans = max(ans, j-i) + i = j + } + return ans } ``` @@ -271,25 +259,21 @@ function findLengthOfLCIS(nums: number[]): number { } ``` -### **PHP** - -```php -class Solution { - /** - * @param Integer[] $nums - * @return Integer - */ - function findLengthOfLCIS($nums) { - $ans = 1; - $cnt = 1; - for ($i = 1; $i < count($nums); ++$i) { - if ($nums[$i - 1] < $nums[$i]) { - $ans = max($ans, ++$cnt); - } else { - $cnt = 1; +```rust +impl Solution { + pub fn find_length_of_lcis(nums: Vec) -> i32 { + let mut ans = 1; + let n = nums.len(); + let mut i = 0; + while i < n { + let mut j = i + 1; + while j < n && nums[j - 1] < nums[j] { + j += 1; } + ans = ans.max(j - i); + i = j; } - return $ans; + ans as i32 } } ``` @@ -317,10 +301,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/README_EN.md b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/README_EN.md index 8ef2c21712429..140a30f300a85 100644 --- a/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/README_EN.md +++ b/solution/0600-0699/0674.Longest Continuous Increasing Subsequence/README_EN.md @@ -38,7 +38,7 @@ increasing. ## Solutions -**Solution 1: One-pass Scan** +### Solution 1: One-pass Scan We can traverse the array $nums$, using a variable $cnt$ to record the length of the current consecutive increasing sequence. Initially, $cnt = 1$. @@ -48,16 +48,8 @@ After the traversal ends, we return the answer $ans$. The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. -**Solution 2: Two Pointers** - -We can also use two pointers $i$ and $j$ to find each consecutive increasing sequence, and find the length of the longest consecutive increasing sequence as the answer. - -The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: @@ -71,22 +63,6 @@ class Solution: return ans ``` -```python -class Solution: - def findLengthOfLCIS(self, nums: List[int]) -> int: - ans, n = 1, len(nums) - i = 0 - while i < n: - j = i + 1 - while j < n and nums[j - 1] < nums[j]: - j += 1 - ans = max(ans, j - i) - i = j - return ans -``` - -### **Java** - ```java class Solution { public int findLengthOfLCIS(int[] nums) { @@ -103,26 +79,6 @@ class Solution { } ``` -```java -class Solution { - public int findLengthOfLCIS(int[] nums) { - int ans = 1; - int n = nums.length; - for (int i = 0; i < n;) { - int j = i + 1; - while (j < n && nums[j - 1] < nums[j]) { - ++j; - } - ans = Math.max(ans, j - i); - i = j; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -140,27 +96,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findLengthOfLCIS(vector& nums) { - int ans = 1; - int n = nums.size(); - for (int i = 0; i < n;) { - int j = i + 1; - while (j < n && nums[j - 1] < nums[j]) { - ++j; - } - ans = max(ans, j - i); - i = j; - } - return ans; - } -}; -``` - -### **Go** - ```go func findLengthOfLCIS(nums []int) int { ans, cnt := 1, 1 @@ -176,24 +111,20 @@ func findLengthOfLCIS(nums []int) int { } ``` -```go -func findLengthOfLCIS(nums []int) int { - ans := 1 - n := len(nums) - for i := 0; i < n; { - j := i + 1 - for j < n && nums[j-1] < nums[j] { - j++ - } - ans = max(ans, j-i) - i = j - } - return ans +```ts +function findLengthOfLCIS(nums: number[]): number { + let [ans, cnt] = [1, 1]; + for (let i = 1; i < nums.length; ++i) { + if (nums[i - 1] < nums[i]) { + ans = Math.max(ans, ++cnt); + } else { + cnt = 1; + } + } + return ans; } ``` -### **Rust** - ```rust impl Solution { pub fn find_length_of_lcis(nums: Vec) -> i32 { @@ -212,38 +143,101 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn find_length_of_lcis(nums: Vec) -> i32 { - let mut ans = 1; - let n = nums.len(); - let mut i = 0; - while i < n { - let mut j = i + 1; - while j < n && nums[j - 1] < nums[j] { - j += 1; +```php +class Solution { + /** + * @param Integer[] $nums + * @return Integer + */ + function findLengthOfLCIS($nums) { + $ans = 1; + $cnt = 1; + for ($i = 1; $i < count($nums); ++$i) { + if ($nums[$i - 1] < $nums[$i]) { + $ans = max($ans, ++$cnt); + } else { + $cnt = 1; } - ans = ans.max(j - i); - i = j; } - ans as i32 + return $ans; } } ``` -### **TypeScript** + -```ts -function findLengthOfLCIS(nums: number[]): number { - let [ans, cnt] = [1, 1]; - for (let i = 1; i < nums.length; ++i) { - if (nums[i - 1] < nums[i]) { - ans = Math.max(ans, ++cnt); - } else { - cnt = 1; +### Solution 2: Two Pointers + +We can also use two pointers $i$ and $j$ to find each consecutive increasing sequence, and find the length of the longest consecutive increasing sequence as the answer. + +The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. + + + +```python +class Solution: + def findLengthOfLCIS(self, nums: List[int]) -> int: + ans, n = 1, len(nums) + i = 0 + while i < n: + j = i + 1 + while j < n and nums[j - 1] < nums[j]: + j += 1 + ans = max(ans, j - i) + i = j + return ans +``` + +```java +class Solution { + public int findLengthOfLCIS(int[] nums) { + int ans = 1; + int n = nums.length; + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[j - 1] < nums[j]) { + ++j; + } + ans = Math.max(ans, j - i); + i = j; } + return ans; } - return ans; +} +``` + +```cpp +class Solution { +public: + int findLengthOfLCIS(vector& nums) { + int ans = 1; + int n = nums.size(); + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[j - 1] < nums[j]) { + ++j; + } + ans = max(ans, j - i); + i = j; + } + return ans; + } +}; +``` + +```go +func findLengthOfLCIS(nums []int) int { + ans := 1 + n := len(nums) + for i := 0; i < n; { + j := i + 1 + for j < n && nums[j-1] < nums[j] { + j++ + } + ans = max(ans, j-i) + i = j + } + return ans } ``` @@ -263,25 +257,21 @@ function findLengthOfLCIS(nums: number[]): number { } ``` -### **PHP** - -```php -class Solution { - /** - * @param Integer[] $nums - * @return Integer - */ - function findLengthOfLCIS($nums) { - $ans = 1; - $cnt = 1; - for ($i = 1; $i < count($nums); ++$i) { - if ($nums[$i - 1] < $nums[$i]) { - $ans = max($ans, ++$cnt); - } else { - $cnt = 1; +```rust +impl Solution { + pub fn find_length_of_lcis(nums: Vec) -> i32 { + let mut ans = 1; + let n = nums.len(); + let mut i = 0; + while i < n { + let mut j = i + 1; + while j < n && nums[j - 1] < nums[j] { + j += 1; } + ans = ans.max(j - i); + i = j; } - return $ans; + ans as i32 } } ``` @@ -309,10 +299,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0675.Cut Off Trees for Golf Event/README.md b/solution/0600-0699/0675.Cut Off Trees for Golf Event/README.md index 71103bdc750d2..025d27322aeb5 100644 --- a/solution/0600-0699/0675.Cut Off Trees for Golf Event/README.md +++ b/solution/0600-0699/0675.Cut Off Trees for Golf Event/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:BFS + 优先队列(A\* 算法)** +### 方法一:BFS + 优先队列(A\* 算法) 题目的一个关键信息是“所有树的高度都不同”,要按照从小到大的顺序依次砍树,因此,我们先遍历树林,找出所有树及对应的坐标点。然后将树按照高度升序排列。 @@ -79,10 +77,6 @@ A\* 算法主要思想如下: -### **Python3** - - - ```python class Solution: def cutOffTree(self, forest: List[List[int]]) -> int: @@ -121,10 +115,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] dist = new int[3600]; @@ -194,8 +184,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -254,8 +242,6 @@ public: }; ``` -### **Go** - ```go var dirs = [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} @@ -319,8 +305,6 @@ func cutOffTree(forest [][]int) int { } ``` -### **Rust** - ```rust use std::collections::HashSet; use std::collections::VecDeque; @@ -397,10 +381,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0675.Cut Off Trees for Golf Event/README_EN.md b/solution/0600-0699/0675.Cut Off Trees for Golf Event/README_EN.md index e49005551c6dd..f6ab13193dcac 100644 --- a/solution/0600-0699/0675.Cut Off Trees for Golf Event/README_EN.md +++ b/solution/0600-0699/0675.Cut Off Trees for Golf Event/README_EN.md @@ -59,9 +59,9 @@ Note that you can cut off the first tree at (0, 0) before making any steps. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -101,8 +101,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] dist = new int[3600]; @@ -172,8 +170,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -232,8 +228,6 @@ public: }; ``` -### **Go** - ```go var dirs = [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} @@ -297,8 +291,6 @@ func cutOffTree(forest [][]int) int { } ``` -### **Rust** - ```rust use std::collections::HashSet; use std::collections::VecDeque; @@ -375,10 +367,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0676.Implement Magic Dictionary/README.md b/solution/0600-0699/0676.Implement Magic Dictionary/README.md index 1e240cecc80ba..1b0ba3298ff92 100644 --- a/solution/0600-0699/0676.Implement Magic Dictionary/README.md +++ b/solution/0600-0699/0676.Implement Magic Dictionary/README.md @@ -59,9 +59,7 @@ magicDictionary.search("leetcoded"); // 返回 False ## 解法 - - -**方法一:前缀树 + DFS** +### 方法一:前缀树 + DFS 我们可以使用前缀树来存储字典中的所有单词,然后对于每个搜索的单词,我们使用深度优先搜索的方法,具体地,我们从前缀树的根节点开始,对于当前遍历到的字母,我们首先判断是否存在与其相同的子节点,如果存在,则继续向下遍历,否则我们需要判断是否还有剩余的修改次数,如果没有,则说明无法匹配,返回 false。如果有剩余的修改次数,我们可以尝试对当前的字母进行修改,然后继续向下遍历,如果当前的字母修改后对应的子节点存在,则说明可以匹配,否则说明无法匹配,返回 false。如果我们遍历到了单词的结尾,且修改次数恰好为 1,那么说明可以匹配,返回 true。 @@ -69,10 +67,6 @@ magicDictionary.search("leetcoded"); // 返回 False -### **Python3** - - - ```python class Trie: __slots__ = ["children", "is_end"] @@ -120,61 +114,6 @@ class MagicDictionary: # param_2 = obj.search(searchWord) ``` -```python -class Trie: - __slots__ = ["children", "is_end"] - - def __init__(self): - self.children: [Trie | None] = [None] * 26 - self.is_end = False - - def insert(self, w: str) -> None: - node = self - for c in w: - idx = ord(c) - ord("a") - if node.children[idx] is None: - node.children[idx] = Trie() - node = node.children[idx] - node.is_end = True - - def search(self, w: str) -> bool: - def dfs(i: int, node: [Trie | None], diff: int) -> bool: - if i == len(w): - return diff == 1 and node.is_end - j = ord(w[i]) - ord("a") - if node.children[j] and dfs(i + 1, node.children[j], diff): - return True - return diff == 0 and any( - node.children[k] and dfs(i + 1, node.children[k], 1) - for k in range(26) - if k != j - ) - - return dfs(0, self, 0) - - -class MagicDictionary: - def __init__(self): - self.trie = Trie() - - def buildDict(self, dictionary: List[str]) -> None: - for w in dictionary: - self.trie.insert(w) - - def search(self, searchWord: str) -> bool: - return self.trie.search(searchWord) - - -# Your MagicDictionary object will be instantiated and called as such: -# obj = MagicDictionary() -# obj.buildDict(dictionary) -# param_2 = obj.search(searchWord) -``` - -### **Java** - - - ```java class Trie { private Trie[] children = new Trie[26]; @@ -244,8 +183,6 @@ class MagicDictionary { */ ``` -### **C++** - ```cpp class Trie { private: @@ -321,8 +258,6 @@ private: */ ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -393,8 +328,6 @@ func (md *MagicDictionary) Search(searchWord string) bool { */ ``` -### **TypeScript** - ```ts class Trie { private children: Trie[] = Array(26).fill(null); @@ -462,8 +395,6 @@ class MagicDictionary { */ ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -551,10 +482,63 @@ impl MagicDictionary { */ ``` -### **...** + + +### 方法二 -``` + + +```python +class Trie: + __slots__ = ["children", "is_end"] + + def __init__(self): + self.children: [Trie | None] = [None] * 26 + self.is_end = False + def insert(self, w: str) -> None: + node = self + for c in w: + idx = ord(c) - ord("a") + if node.children[idx] is None: + node.children[idx] = Trie() + node = node.children[idx] + node.is_end = True + + def search(self, w: str) -> bool: + def dfs(i: int, node: [Trie | None], diff: int) -> bool: + if i == len(w): + return diff == 1 and node.is_end + j = ord(w[i]) - ord("a") + if node.children[j] and dfs(i + 1, node.children[j], diff): + return True + return diff == 0 and any( + node.children[k] and dfs(i + 1, node.children[k], 1) + for k in range(26) + if k != j + ) + + return dfs(0, self, 0) + + +class MagicDictionary: + def __init__(self): + self.trie = Trie() + + def buildDict(self, dictionary: List[str]) -> None: + for w in dictionary: + self.trie.insert(w) + + def search(self, searchWord: str) -> bool: + return self.trie.search(searchWord) + + +# Your MagicDictionary object will be instantiated and called as such: +# obj = MagicDictionary() +# obj.buildDict(dictionary) +# param_2 = obj.search(searchWord) ``` + + diff --git a/solution/0600-0699/0676.Implement Magic Dictionary/README_EN.md b/solution/0600-0699/0676.Implement Magic Dictionary/README_EN.md index 79e80647bf0a8..36dcc36ff7de8 100644 --- a/solution/0600-0699/0676.Implement Magic Dictionary/README_EN.md +++ b/solution/0600-0699/0676.Implement Magic Dictionary/README_EN.md @@ -49,7 +49,7 @@ magicDictionary.search("leetcoded"); // return False ## Solutions -**Solution 1: Trie + DFS** +### Solution 1: Trie + DFS We can use a trie to store all the words in the dictionary. For each word we search, we use depth-first search. Specifically, we start from the root of the trie. For the current letter we are traversing, we first check whether there is a child node that is the same as it. If there is, we continue to traverse downwards. Otherwise, we need to check whether there are remaining modification times. If not, it means that it cannot be matched, so we return false. If there are remaining modification times, we can try to modify the current letter and continue to traverse downwards. If the child node corresponding to the modified letter exists, it means that it can be matched, otherwise it means that it cannot be matched, so we return false. If we traverse to the end of the word and the number of modifications is exactly 1, it means that it can be matched, so we return true. @@ -57,8 +57,6 @@ The time complexity is $O(n \times l + q \times l \times |\Sigma|)$, and the spa -### **Python3** - ```python class Trie: __slots__ = ["children", "is_end"] @@ -106,59 +104,6 @@ class MagicDictionary: # param_2 = obj.search(searchWord) ``` -```python -class Trie: - __slots__ = ["children", "is_end"] - - def __init__(self): - self.children: [Trie | None] = [None] * 26 - self.is_end = False - - def insert(self, w: str) -> None: - node = self - for c in w: - idx = ord(c) - ord("a") - if node.children[idx] is None: - node.children[idx] = Trie() - node = node.children[idx] - node.is_end = True - - def search(self, w: str) -> bool: - def dfs(i: int, node: [Trie | None], diff: int) -> bool: - if i == len(w): - return diff == 1 and node.is_end - j = ord(w[i]) - ord("a") - if node.children[j] and dfs(i + 1, node.children[j], diff): - return True - return diff == 0 and any( - node.children[k] and dfs(i + 1, node.children[k], 1) - for k in range(26) - if k != j - ) - - return dfs(0, self, 0) - - -class MagicDictionary: - def __init__(self): - self.trie = Trie() - - def buildDict(self, dictionary: List[str]) -> None: - for w in dictionary: - self.trie.insert(w) - - def search(self, searchWord: str) -> bool: - return self.trie.search(searchWord) - - -# Your MagicDictionary object will be instantiated and called as such: -# obj = MagicDictionary() -# obj.buildDict(dictionary) -# param_2 = obj.search(searchWord) -``` - -### **Java** - ```java class Trie { private Trie[] children = new Trie[26]; @@ -228,8 +173,6 @@ class MagicDictionary { */ ``` -### **C++** - ```cpp class Trie { private: @@ -305,8 +248,6 @@ private: */ ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -377,8 +318,6 @@ func (md *MagicDictionary) Search(searchWord string) bool { */ ``` -### **TypeScript** - ```ts class Trie { private children: Trie[] = Array(26).fill(null); @@ -446,8 +385,6 @@ class MagicDictionary { */ ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -535,10 +472,63 @@ impl MagicDictionary { */ ``` -### **...** + + +### Solution 2 -``` + + +```python +class Trie: + __slots__ = ["children", "is_end"] + + def __init__(self): + self.children: [Trie | None] = [None] * 26 + self.is_end = False + + def insert(self, w: str) -> None: + node = self + for c in w: + idx = ord(c) - ord("a") + if node.children[idx] is None: + node.children[idx] = Trie() + node = node.children[idx] + node.is_end = True + def search(self, w: str) -> bool: + def dfs(i: int, node: [Trie | None], diff: int) -> bool: + if i == len(w): + return diff == 1 and node.is_end + j = ord(w[i]) - ord("a") + if node.children[j] and dfs(i + 1, node.children[j], diff): + return True + return diff == 0 and any( + node.children[k] and dfs(i + 1, node.children[k], 1) + for k in range(26) + if k != j + ) + + return dfs(0, self, 0) + + +class MagicDictionary: + def __init__(self): + self.trie = Trie() + + def buildDict(self, dictionary: List[str]) -> None: + for w in dictionary: + self.trie.insert(w) + + def search(self, searchWord: str) -> bool: + return self.trie.search(searchWord) + + +# Your MagicDictionary object will be instantiated and called as such: +# obj = MagicDictionary() +# obj.buildDict(dictionary) +# param_2 = obj.search(searchWord) ``` + + diff --git a/solution/0600-0699/0677.Map Sum Pairs/README.md b/solution/0600-0699/0677.Map Sum Pairs/README.md index 1d1437a2e26dd..5a042db9efa7c 100644 --- a/solution/0600-0699/0677.Map Sum Pairs/README.md +++ b/solution/0600-0699/0677.Map Sum Pairs/README.md @@ -53,9 +53,7 @@ mapSum.sum("ap"); // 返回 5 (apple + app = 3 + 2 = 5) ## 解法 - - -**方法一:哈希表 + 前缀树** +### 方法一:哈希表 + 前缀树 我们用哈希表 $d$ 存放键值对,用前缀树 $t$ 存放键值对的前缀和。前缀树的每个节点包含两个信息: @@ -72,10 +70,6 @@ mapSum.sum("ap"); // 返回 5 (apple + app = 3 + 2 = 5) -### **Python3** - - - ```python class Trie: def __init__(self): @@ -121,10 +115,6 @@ class MapSum: # param_2 = obj.sum(prefix) ``` -### **Java** - - - ```java class Trie { private Trie[] children = new Trie[26]; @@ -181,8 +171,6 @@ class MapSum { */ ``` -### **C++** - ```cpp class Trie { public: @@ -247,8 +235,6 @@ private: */ ``` -### **Go** - ```go type trie struct { children [26]*trie @@ -304,8 +290,6 @@ func (this *MapSum) Sum(prefix string) int { */ ``` -### **TypeScript** - ```ts class Trie { children: Trie[]; @@ -368,10 +352,6 @@ class MapSum { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0677.Map Sum Pairs/README_EN.md b/solution/0600-0699/0677.Map Sum Pairs/README_EN.md index 71b046b082d01..114b48f7998e9 100644 --- a/solution/0600-0699/0677.Map Sum Pairs/README_EN.md +++ b/solution/0600-0699/0677.Map Sum Pairs/README_EN.md @@ -49,9 +49,9 @@ mapSum.sum("ap"); // return 5 (apple + app = 3 ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -98,8 +98,6 @@ class MapSum: # param_2 = obj.sum(prefix) ``` -### **Java** - ```java class Trie { private Trie[] children = new Trie[26]; @@ -156,8 +154,6 @@ class MapSum { */ ``` -### **C++** - ```cpp class Trie { public: @@ -222,8 +218,6 @@ private: */ ``` -### **Go** - ```go type trie struct { children [26]*trie @@ -279,8 +273,6 @@ func (this *MapSum) Sum(prefix string) int { */ ``` -### **TypeScript** - ```ts class Trie { children: Trie[]; @@ -343,10 +335,6 @@ class MapSum { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0678.Valid Parenthesis String/README.md b/solution/0600-0699/0678.Valid Parenthesis String/README.md index 6d1393c18fa0b..3de1472a0f321 100644 --- a/solution/0600-0699/0678.Valid Parenthesis String/README.md +++ b/solution/0600-0699/0678.Valid Parenthesis String/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 定义 $dp[i][j]$ 表示字符串 $s$ 中下标范围 $[i..j]$ 内的子串是否为有效括号字符串。答案为 $dp[0][n - 1]$。 @@ -67,20 +65,8 @@ 时间复杂度 $O(n^3)$,空间复杂度 $O(n^2)$。其中 $n$ 为字符串 `s` 的长度。 -**方法二:贪心 + 两遍扫描** - -两遍扫描,第一遍从左往右,确定每一个右括号都可以成功配对,第二遍从右往左,确定每一个左括号都可以成功配对。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 `s` 的长度。 - -相似题目:[2116. 判断一个括号字符串是否有效](/solution/2100-2199/2116.Check%20if%20a%20Parentheses%20String%20Can%20Be%20Valid/README.md) - -### **Python3** - - - ```python class Solution: def checkValidString(self, s: str) -> bool: @@ -99,32 +85,6 @@ class Solution: return dp[0][-1] ``` -```python -class Solution: - def checkValidString(self, s: str) -> bool: - x = 0 - for c in s: - if c in '(*': - x += 1 - elif x: - x -= 1 - else: - return False - x = 0 - for c in s[::-1]: - if c in '*)': - x += 1 - elif x: - x -= 1 - else: - return False - return True -``` - -### **Java** - - - ```java class Solution { public boolean checkValidString(String s) { @@ -148,6 +108,84 @@ class Solution { } ``` +```cpp +class Solution { +public: + bool checkValidString(string s) { + int n = s.size(); + vector> dp(n, vector(n)); + for (int i = 0; i < n; ++i) { + dp[i][i] = s[i] == '*'; + } + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + char a = s[i], b = s[j]; + dp[i][j] = (a == '(' || a == '*') && (b == '*' || b == ')') && (i + 1 == j || dp[i + 1][j - 1]); + for (int k = i; k < j && !dp[i][j]; ++k) { + dp[i][j] = dp[i][k] && dp[k + 1][j]; + } + } + } + return dp[0][n - 1]; + } +}; +``` + +```go +func checkValidString(s string) bool { + n := len(s) + dp := make([][]bool, n) + for i := range dp { + dp[i] = make([]bool, n) + dp[i][i] = s[i] == '*' + } + for i := n - 2; i >= 0; i-- { + for j := i + 1; j < n; j++ { + a, b := s[i], s[j] + dp[i][j] = (a == '(' || a == '*') && (b == '*' || b == ')') && (i+1 == j || dp[i+1][j-1]) + for k := i; k < j && !dp[i][j]; k++ { + dp[i][j] = dp[i][k] && dp[k+1][j] + } + } + } + return dp[0][n-1] +} +``` + + + +### 方法二:贪心 + 两遍扫描 + +两遍扫描,第一遍从左往右,确定每一个右括号都可以成功配对,第二遍从右往左,确定每一个左括号都可以成功配对。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 `s` 的长度。 + +相似题目:[2116. 判断一个括号字符串是否有效](/solution/2100-2199/2116.Check%20if%20a%20Parentheses%20String%20Can%20Be%20Valid/README.md) + + + +```python +class Solution: + def checkValidString(self, s: str) -> bool: + x = 0 + for c in s: + if c in '(*': + x += 1 + elif x: + x -= 1 + else: + return False + x = 0 + for c in s[::-1]: + if c in '*)': + x += 1 + elif x: + x -= 1 + else: + return False + return True +``` + ```java class Solution { public boolean checkValidString(String s) { @@ -177,31 +215,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool checkValidString(string s) { - int n = s.size(); - vector> dp(n, vector(n)); - for (int i = 0; i < n; ++i) { - dp[i][i] = s[i] == '*'; - } - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - char a = s[i], b = s[j]; - dp[i][j] = (a == '(' || a == '*') && (b == '*' || b == ')') && (i + 1 == j || dp[i + 1][j - 1]); - for (int k = i; k < j && !dp[i][j]; ++k) { - dp[i][j] = dp[i][k] && dp[k + 1][j]; - } - } - } - return dp[0][n - 1]; - } -}; -``` - ```cpp class Solution { public: @@ -231,29 +244,6 @@ public: }; ``` -### **Go** - -```go -func checkValidString(s string) bool { - n := len(s) - dp := make([][]bool, n) - for i := range dp { - dp[i] = make([]bool, n) - dp[i][i] = s[i] == '*' - } - for i := n - 2; i >= 0; i-- { - for j := i + 1; j < n; j++ { - a, b := s[i], s[j] - dp[i][j] = (a == '(' || a == '*') && (b == '*' || b == ')') && (i+1 == j || dp[i+1][j-1]) - for k := i; k < j && !dp[i][j]; k++ { - dp[i][j] = dp[i][k] && dp[k+1][j] - } - } - } - return dp[0][n-1] -} -``` - ```go func checkValidString(s string) bool { x := 0 @@ -280,10 +270,6 @@ func checkValidString(s string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0678.Valid Parenthesis String/README_EN.md b/solution/0600-0699/0678.Valid Parenthesis String/README_EN.md index 725bf5954a6e6..9a4d0e2f57a0a 100644 --- a/solution/0600-0699/0678.Valid Parenthesis String/README_EN.md +++ b/solution/0600-0699/0678.Valid Parenthesis String/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming Let `dp[i][j]` be true if and only if the interval `s[i], s[i+1], ..., s[j]` can be made valid. Then `dp[i][j]` is true only if: @@ -46,17 +46,8 @@ Let `dp[i][j]` be true if and only if the interval `s[i], s[i+1], ..., s[j]` can - Time Complexity: $O(n^3)$, where $n$ is the length of the string. There are $O(n^2)$ states corresponding to entries of dp, and we do an average of $O(n)$ work on each state. - Space Complexity: $O(n^2)$. -**Solution 2: Greedy** - -Scan twice, first from left to right to make sure that each of the closing brackets is matched successfully, and second from right to left to make sure that each of the opening brackets is matched successfully. - -- Time Complexity: $O(n)$, where $n$ is the length of the string. -- Space Complexity: $O(1)$. - -### **Python3** - ```python class Solution: def checkValidString(self, s: str) -> bool: @@ -75,30 +66,6 @@ class Solution: return dp[0][-1] ``` -```python -class Solution: - def checkValidString(self, s: str) -> bool: - x = 0 - for c in s: - if c in '(*': - x += 1 - elif x: - x -= 1 - else: - return False - x = 0 - for c in s[::-1]: - if c in '*)': - x += 1 - elif x: - x -= 1 - else: - return False - return True -``` - -### **Java** - ```java class Solution { public boolean checkValidString(String s) { @@ -122,6 +89,83 @@ class Solution { } ``` +```cpp +class Solution { +public: + bool checkValidString(string s) { + int n = s.size(); + vector> dp(n, vector(n)); + for (int i = 0; i < n; ++i) { + dp[i][i] = s[i] == '*'; + } + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + char a = s[i], b = s[j]; + dp[i][j] = (a == '(' || a == '*') && (b == '*' || b == ')') && (i + 1 == j || dp[i + 1][j - 1]); + for (int k = i; k < j && !dp[i][j]; ++k) { + dp[i][j] = dp[i][k] && dp[k + 1][j]; + } + } + } + return dp[0][n - 1]; + } +}; +``` + +```go +func checkValidString(s string) bool { + n := len(s) + dp := make([][]bool, n) + for i := range dp { + dp[i] = make([]bool, n) + dp[i][i] = s[i] == '*' + } + for i := n - 2; i >= 0; i-- { + for j := i + 1; j < n; j++ { + a, b := s[i], s[j] + dp[i][j] = (a == '(' || a == '*') && (b == '*' || b == ')') && (i+1 == j || dp[i+1][j-1]) + for k := i; k < j && !dp[i][j]; k++ { + dp[i][j] = dp[i][k] && dp[k+1][j] + } + } + } + return dp[0][n-1] +} +``` + + + +### Solution 2: Greedy + +Scan twice, first from left to right to make sure that each of the closing brackets is matched successfully, and second from right to left to make sure that each of the opening brackets is matched successfully. + +- Time Complexity: $O(n)$, where $n$ is the length of the string. +- Space Complexity: $O(1)$. + + + +```python +class Solution: + def checkValidString(self, s: str) -> bool: + x = 0 + for c in s: + if c in '(*': + x += 1 + elif x: + x -= 1 + else: + return False + x = 0 + for c in s[::-1]: + if c in '*)': + x += 1 + elif x: + x -= 1 + else: + return False + return True +``` + ```java class Solution { public boolean checkValidString(String s) { @@ -151,31 +195,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool checkValidString(string s) { - int n = s.size(); - vector> dp(n, vector(n)); - for (int i = 0; i < n; ++i) { - dp[i][i] = s[i] == '*'; - } - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - char a = s[i], b = s[j]; - dp[i][j] = (a == '(' || a == '*') && (b == '*' || b == ')') && (i + 1 == j || dp[i + 1][j - 1]); - for (int k = i; k < j && !dp[i][j]; ++k) { - dp[i][j] = dp[i][k] && dp[k + 1][j]; - } - } - } - return dp[0][n - 1]; - } -}; -``` - ```cpp class Solution { public: @@ -205,29 +224,6 @@ public: }; ``` -### **Go** - -```go -func checkValidString(s string) bool { - n := len(s) - dp := make([][]bool, n) - for i := range dp { - dp[i] = make([]bool, n) - dp[i][i] = s[i] == '*' - } - for i := n - 2; i >= 0; i-- { - for j := i + 1; j < n; j++ { - a, b := s[i], s[j] - dp[i][j] = (a == '(' || a == '*') && (b == '*' || b == ')') && (i+1 == j || dp[i+1][j-1]) - for k := i; k < j && !dp[i][j]; k++ { - dp[i][j] = dp[i][k] && dp[k+1][j] - } - } - } - return dp[0][n-1] -} -``` - ```go func checkValidString(s string) bool { x := 0 @@ -254,10 +250,6 @@ func checkValidString(s string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0679.24 Game/README.md b/solution/0600-0699/0679.24 Game/README.md index cdd943aa53ae4..8d35008eaf38d 100644 --- a/solution/0600-0699/0679.24 Game/README.md +++ b/solution/0600-0699/0679.24 Game/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们设计一个函数 $dfs(nums)$,其中 $nums$ 表示当前的数字序列,函数返回一个布尔值,表示是否存在一种排列方式,使得这个数字序列可以得到 $24$。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def judgePoint24(self, cards: List[int]) -> bool: @@ -111,10 +105,6 @@ class Solution: return dfs(nums) ``` -### **Java** - - - ```java class Solution { private final char[] ops = {'+', '-', '*', '/'}; @@ -174,8 +164,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -237,8 +225,6 @@ private: }; ``` -### **Go** - ```go func judgePoint24(cards []int) bool { ops := [4]rune{'+', '-', '*', '/'} @@ -292,8 +278,6 @@ func judgePoint24(cards []int) bool { } ``` -### **TypeScript** - ```ts function judgePoint24(cards: number[]): boolean { const ops: string[] = ['+', '-', '*', '/']; @@ -346,10 +330,6 @@ function judgePoint24(cards: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0679.24 Game/README_EN.md b/solution/0600-0699/0679.24 Game/README_EN.md index e231b6d76d8de..912fcee72861f 100644 --- a/solution/0600-0699/0679.24 Game/README_EN.md +++ b/solution/0600-0699/0679.24 Game/README_EN.md @@ -54,7 +54,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We design a function $dfs(nums)$, where $nums$ represents the current number sequence. The function returns a boolean value indicating whether there exists a permutation that makes this number sequence equal to $24$. @@ -66,8 +66,6 @@ If none of the enumerated cases return $true$, we return $false$. -### **Python3** - ```python class Solution: def judgePoint24(self, cards: List[int]) -> bool: @@ -103,8 +101,6 @@ class Solution: return dfs(nums) ``` -### **Java** - ```java class Solution { private final char[] ops = {'+', '-', '*', '/'}; @@ -164,8 +160,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -227,8 +221,6 @@ private: }; ``` -### **Go** - ```go func judgePoint24(cards []int) bool { ops := [4]rune{'+', '-', '*', '/'} @@ -282,8 +274,6 @@ func judgePoint24(cards []int) bool { } ``` -### **TypeScript** - ```ts function judgePoint24(cards: number[]): boolean { const ops: string[] = ['+', '-', '*', '/']; @@ -336,10 +326,6 @@ function judgePoint24(cards: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0680.Valid Palindrome II/README.md b/solution/0600-0699/0680.Valid Palindrome II/README.md index 9378fb2619ed9..be372e51d5ee9 100644 --- a/solution/0600-0699/0680.Valid Palindrome II/README.md +++ b/solution/0600-0699/0680.Valid Palindrome II/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们用两个指针分别指向字符串的左右两端,每次判断两个指针指向的字符是否相同,如果不相同,则判断删除左指针对应的字符后字符串是否是回文字符串,或者判断删除右指针对应的字符后字符串是否是回文字符串。如果两个指针指向的字符相同,则将左右指针都往中间移动一位,直到两个指针相遇为止。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def validPalindrome(self, s: str) -> bool: @@ -78,10 +72,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean validPalindrome(String s) { @@ -104,30 +94,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function validPalindrome(s: string): boolean { - for (let i: number = 0, j = s.length - 1; i < j; ++i, --j) { - if (s.charAt(i) != s.charAt(j)) { - return isPalinddrome(s.slice(i, j)) || isPalinddrome(s.slice(i + 1, j + 1)); - } - } - return true; -} - -function isPalinddrome(s: string): boolean { - for (let i: number = 0, j = s.length - 1; i < j; ++i, --j) { - if (s.charAt(i) != s.charAt(j)) { - return false; - } - } - return true; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -151,8 +117,6 @@ public: }; ``` -### **Go** - ```go func validPalindrome(s string) bool { check := func(i, j int) bool { @@ -172,7 +136,25 @@ func validPalindrome(s string) bool { } ``` -### **JavaScript** +```ts +function validPalindrome(s: string): boolean { + for (let i: number = 0, j = s.length - 1; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return isPalinddrome(s.slice(i, j)) || isPalinddrome(s.slice(i + 1, j + 1)); + } + } + return true; +} + +function isPalinddrome(s: string): boolean { + for (let i: number = 0, j = s.length - 1; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return false; + } + } + return true; +} +``` ```js /** @@ -197,8 +179,6 @@ var validPalindrome = function (s) { }; ``` -### **C#** - ```cs public class Solution { public bool ValidPalindrome(string s) { @@ -226,10 +206,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0680.Valid Palindrome II/README_EN.md b/solution/0600-0699/0680.Valid Palindrome II/README_EN.md index 7c6f4bdb3b090..b3dd9e7bfaf1d 100644 --- a/solution/0600-0699/0680.Valid Palindrome II/README_EN.md +++ b/solution/0600-0699/0680.Valid Palindrome II/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We use two pointers to point to the left and right ends of the string, respectively. Each time, we check whether the characters pointed to by the two pointers are the same. If they are not the same, we check whether the string is a palindrome after deleting the character corresponding to the left pointer, or we check whether the string is a palindrome after deleting the character corresponding to the right pointer. If the characters pointed to by the two pointers are the same, we move both pointers towards the middle by one position, until the two pointers meet. @@ -49,8 +49,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. The sp -### **Python3** - ```python class Solution: def validPalindrome(self, s: str) -> bool: @@ -69,8 +67,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean validPalindrome(String s) { @@ -93,30 +89,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function validPalindrome(s: string): boolean { - for (let i: number = 0, j = s.length - 1; i < j; ++i, --j) { - if (s.charAt(i) != s.charAt(j)) { - return isPalinddrome(s.slice(i, j)) || isPalinddrome(s.slice(i + 1, j + 1)); - } - } - return true; -} - -function isPalinddrome(s: string): boolean { - for (let i: number = 0, j = s.length - 1; i < j; ++i, --j) { - if (s.charAt(i) != s.charAt(j)) { - return false; - } - } - return true; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -140,8 +112,6 @@ public: }; ``` -### **Go** - ```go func validPalindrome(s string) bool { check := func(i, j int) bool { @@ -161,7 +131,25 @@ func validPalindrome(s string) bool { } ``` -### **JavaScript** +```ts +function validPalindrome(s: string): boolean { + for (let i: number = 0, j = s.length - 1; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return isPalinddrome(s.slice(i, j)) || isPalinddrome(s.slice(i + 1, j + 1)); + } + } + return true; +} + +function isPalinddrome(s: string): boolean { + for (let i: number = 0, j = s.length - 1; i < j; ++i, --j) { + if (s.charAt(i) != s.charAt(j)) { + return false; + } + } + return true; +} +``` ```js /** @@ -186,8 +174,6 @@ var validPalindrome = function (s) { }; ``` -### **C#** - ```cs public class Solution { public bool ValidPalindrome(string s) { @@ -215,10 +201,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0681.Next Closest Time/README.md b/solution/0600-0699/0681.Next Closest Time/README.md index 33f2e8892c4b9..24320f9d3de82 100644 --- a/solution/0600-0699/0681.Next Closest Time/README.md +++ b/solution/0600-0699/0681.Next Closest Time/README.md @@ -45,14 +45,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def nextClosestTime(self, time: str) -> str: @@ -84,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int t; @@ -142,10 +134,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0681.Next Closest Time/README_EN.md b/solution/0600-0699/0681.Next Closest Time/README_EN.md index dbbadfa752de4..c32485e561912 100644 --- a/solution/0600-0699/0681.Next Closest Time/README_EN.md +++ b/solution/0600-0699/0681.Next Closest Time/README_EN.md @@ -39,9 +39,9 @@ It may be assumed that the returned time is next day's time since it is smal ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int t; @@ -130,10 +128,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0682.Baseball Game/README.md b/solution/0600-0699/0682.Baseball Game/README.md index db3a14f3f9d12..f5defb9681ead 100644 --- a/solution/0600-0699/0682.Baseball Game/README.md +++ b/solution/0600-0699/0682.Baseball Game/README.md @@ -72,16 +72,10 @@ ## 解法 - - -利用栈简单模拟即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def calPoints(self, ops: List[str]) -> int: @@ -98,10 +92,6 @@ class Solution: return sum(stk) ``` -### **Java** - - - ```java class Solution { public int calPoints(String[] ops) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func calPoints(ops []string) int { var stk []int @@ -177,8 +163,6 @@ func calPoints(ops []string) int { } ``` -### **TypeScript** - ```ts function calPoints(ops: string[]): number { const stack = []; @@ -198,8 +182,6 @@ function calPoints(ops: string[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn cal_points(ops: Vec) -> i32 { @@ -226,10 +208,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0682.Baseball Game/README_EN.md b/solution/0600-0699/0682.Baseball Game/README_EN.md index ae5f06bb228ca..0378dc739c13b 100644 --- a/solution/0600-0699/0682.Baseball Game/README_EN.md +++ b/solution/0600-0699/0682.Baseball Game/README_EN.md @@ -90,9 +90,9 @@ Since the record is empty, the total sum is 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -110,8 +110,6 @@ class Solution: return sum(stk) ``` -### **Java** - ```java class Solution { public int calPoints(String[] ops) { @@ -135,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +156,6 @@ public: }; ``` -### **Go** - ```go func calPoints(ops []string) int { var stk []int @@ -187,8 +181,6 @@ func calPoints(ops []string) int { } ``` -### **TypeScript** - ```ts function calPoints(ops: string[]): number { const stack = []; @@ -208,8 +200,6 @@ function calPoints(ops: string[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn cal_points(ops: Vec) -> i32 { @@ -236,10 +226,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0683.K Empty Slots/README.md b/solution/0600-0699/0683.K Empty Slots/README.md index f8d2a34127325..a0cbb1b6b1983 100644 --- a/solution/0600-0699/0683.K Empty Slots/README.md +++ b/solution/0600-0699/0683.K Empty Slots/README.md @@ -48,9 +48,7 @@ bulbs = [1,3,2],k = 1 ## 解法 - - -**方法一:树状数组** +### 方法一:树状数组 我们可以使用树状数组来维护区间和,每一次打开灯泡,我们就在树状数组中更新对应位置的值,然后查询当前位置左边 $k$ 个灯泡是否都是关闭的,并且第 $k+1$ 个灯泡是否已经打开;或者查询当前位置右边 $k$ 个灯泡是否都是关闭的,并且第 $k+1$ 个灯泡是否已经打开。如果满足这两个条件之一,那么就说明当前位置是一个符合要求的位置,我们就可以返回当前的天数。 @@ -58,10 +56,6 @@ bulbs = [1,3,2],k = 1 -### **Python3** - - - ```python class BinaryIndexedTree: def __init__(self, n): @@ -98,10 +92,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int kEmptySlots(int[] bulbs, int k) { @@ -150,8 +140,6 @@ class BinaryIndexedTree { } ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -202,8 +190,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -249,8 +235,6 @@ func kEmptySlots(bulbs []int, k int) int { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -297,10 +281,6 @@ function kEmptySlots(bulbs: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0683.K Empty Slots/README_EN.md b/solution/0600-0699/0683.K Empty Slots/README_EN.md index 1c15dfa918217..2715d761c840c 100644 --- a/solution/0600-0699/0683.K Empty Slots/README_EN.md +++ b/solution/0600-0699/0683.K Empty Slots/README_EN.md @@ -42,7 +42,7 @@ We return 2 because on the second day, there were two on bulbs with one off bulb ## Solutions -**Solution 1: Binary Indexed Tree** +### Solution 1: Binary Indexed Tree We can use a Binary Indexed Tree to maintain the prefix sum of the bulbs. Every time we turn on a bulb, we update the corresponding position in the Binary Indexed Tree. Then we check if the $k$ bulbs to the left or right of the current bulb are all turned off and the $(k+1)$-th bulb is already turned on. If either of these conditions is met, we return the current day. @@ -50,8 +50,6 @@ The time complexity is $O(n \times \log n)$ and the space complexity is $O(n)$, -### **Python3** - ```python class BinaryIndexedTree: def __init__(self, n): @@ -88,8 +86,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int kEmptySlots(int[] bulbs, int k) { @@ -138,8 +134,6 @@ class BinaryIndexedTree { } ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -190,8 +184,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -237,8 +229,6 @@ func kEmptySlots(bulbs []int, k int) int { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -285,10 +275,6 @@ function kEmptySlots(bulbs: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0684.Redundant Connection/README.md b/solution/0600-0699/0684.Redundant Connection/README.md index 3726c9b8a9a30..0c69f53a22a6a 100644 --- a/solution/0600-0699/0684.Redundant Connection/README.md +++ b/solution/0600-0699/0684.Redundant Connection/README.md @@ -48,81 +48,10 @@ ## 解法 - - -并查集。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` - -对于本题,先遍历所有的边,如果边的两个节点已经属于同个集合,说明两个节点已经相连,若再将这条件加入集合中,就会出现环,因此可以直接返回这条边。 +### 方法一 -### **Python3** - - - ```python class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: @@ -139,10 +68,6 @@ class Solution: return [] ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -171,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -196,8 +119,6 @@ public: }; ``` -### **Go** - ```go func findRedundantConnection(edges [][]int) []int { p := make([]int, 1010) @@ -222,8 +143,6 @@ func findRedundantConnection(edges [][]int) []int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} edges @@ -247,10 +166,6 @@ var findRedundantConnection = function (edges) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0684.Redundant Connection/README_EN.md b/solution/0600-0699/0684.Redundant Connection/README_EN.md index aaf3fa30dfdbf..9e3b81a3891e5 100644 --- a/solution/0600-0699/0684.Redundant Connection/README_EN.md +++ b/solution/0600-0699/0684.Redundant Connection/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return [] ``` -### **Java** - ```java class Solution { private int[] p; @@ -90,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +111,6 @@ public: }; ``` -### **Go** - ```go func findRedundantConnection(edges [][]int) []int { p := make([]int, 1010) @@ -141,8 +135,6 @@ func findRedundantConnection(edges [][]int) []int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} edges @@ -166,10 +158,6 @@ var findRedundantConnection = function (edges) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0685.Redundant Connection II/README.md b/solution/0600-0699/0685.Redundant Connection II/README.md index 97ae6bffad58c..345da14ee93dc 100644 --- a/solution/0600-0699/0685.Redundant Connection II/README.md +++ b/solution/0600-0699/0685.Redundant Connection II/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:并查集** +### 方法一:并查集 有两个入度时,当一条边被记为 conflict,就相当于删掉了这条边,因为并没有调用并查集 union 进行合并,如果还出现了无向环,则说明是要删另一条入度的边。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class UnionFind: def __init__(self, n): @@ -97,10 +91,6 @@ class Solution: return edges[conflict] ``` -### **Java** - - - ```java class Solution { public int[] findRedundantDirectedConnection(int[][] edges) { @@ -165,8 +155,6 @@ class UnionFind { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -218,8 +206,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p []int @@ -280,10 +266,6 @@ func findRedundantDirectedConnection(edges [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0685.Redundant Connection II/README_EN.md b/solution/0600-0699/0685.Redundant Connection II/README_EN.md index a6d1bf7e86a9c..b9930e5e4e5c5 100644 --- a/solution/0600-0699/0685.Redundant Connection II/README_EN.md +++ b/solution/0600-0699/0685.Redundant Connection II/README_EN.md @@ -40,12 +40,10 @@ ## Solutions -Union find. +### Solution 1 -### **Python3** - ```python class UnionFind: def __init__(self, n): @@ -86,8 +84,6 @@ class Solution: return edges[conflict] ``` -### **Java** - ```java class Solution { public int[] findRedundantDirectedConnection(int[][] edges) { @@ -152,8 +148,6 @@ class UnionFind { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -205,8 +199,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p []int @@ -267,10 +259,6 @@ func findRedundantDirectedConnection(edges [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0686.Repeated String Match/README.md b/solution/0600-0699/0686.Repeated String Match/README.md index 46735f858f32d..c010d432396ae 100644 --- a/solution/0600-0699/0686.Repeated String Match/README.md +++ b/solution/0600-0699/0686.Repeated String Match/README.md @@ -49,16 +49,10 @@ ## 解法 - - -新串由 a 通过重复最小 ans 次得来,假设新串包含子字符串 b,那么新串的起始匹配位置一定不超过 a。 +### 方法一 -### **Python3** - - - ```python class Solution: def repeatedStringMatch(self, a: str, b: str) -> int: @@ -73,10 +67,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int repeatedStringMatch(String a, String b) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func repeatedStringMatch(a string, b string) int { m, n := len(a), len(b) @@ -133,8 +119,6 @@ func repeatedStringMatch(a string, b string) int { } ``` -### **TypeScript** - ```ts function repeatedStringMatch(a: string, b: string): number { const m: number = a.length, @@ -154,10 +138,6 @@ function repeatedStringMatch(a: string, b: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0686.Repeated String Match/README_EN.md b/solution/0600-0699/0686.Repeated String Match/README_EN.md index 1cdf73c5c49c3..958da838c68ae 100644 --- a/solution/0600-0699/0686.Repeated String Match/README_EN.md +++ b/solution/0600-0699/0686.Repeated String Match/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int repeatedStringMatch(String a, String b) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -92,8 +88,6 @@ public: }; ``` -### **Go** - ```go func repeatedStringMatch(a string, b string) int { m, n := len(a), len(b) @@ -110,8 +104,6 @@ func repeatedStringMatch(a string, b string) int { } ``` -### **TypeScript** - ```ts function repeatedStringMatch(a: string, b: string): number { const m: number = a.length, @@ -131,10 +123,6 @@ function repeatedStringMatch(a: string, b: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0687.Longest Univalue Path/README.md b/solution/0600-0699/0687.Longest Univalue Path/README.md index 7d9bf02e5301c..0142e941ac33f 100644 --- a/solution/0600-0699/0687.Longest Univalue Path/README.md +++ b/solution/0600-0699/0687.Longest Univalue Path/README.md @@ -42,18 +42,12 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 相似题目:[543. 二叉树的直径](/solution/0500-0599/0543.Diameter%20of%20Binary%20Tree/README.md) -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -78,10 +72,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. @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -193,78 +179,6 @@ func longestUnivaluePath(root *TreeNode) int { } ``` -### **C** - -```c -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int dfs(struct TreeNode* root, int target, int* res) { - if (!root) { - return 0; - } - int left = dfs(root->left, root->val, res); - int right = dfs(root->right, root->val, res); - *res = max(*res, left + right); - if (root->val == target) { - return max(left, right) + 1; - } - return 0; -} - -int longestUnivaluePath(struct TreeNode* root) { - if (!root) { - return 0; - } - int res = 0; - dfs(root, root->val, &res); - return res; -} -``` - -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number} - */ -var longestUnivaluePath = function (root) { - let ans = 0; - let dfs = function (root) { - if (!root) { - return 0; - } - let left = dfs(root.left), - right = dfs(root.right); - left = root.left?.val == root.val ? left + 1 : 0; - right = root.right?.val == root.val ? right + 1 : 0; - ans = Math.max(ans, left + right); - return Math.max(left, right); - }; - dfs(root); - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -306,8 +220,6 @@ function longestUnivaluePath(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -357,10 +269,72 @@ impl Solution { } ``` -### **...** - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var longestUnivaluePath = function (root) { + let ans = 0; + let dfs = function (root) { + if (!root) { + return 0; + } + let left = dfs(root.left), + right = dfs(root.right); + left = root.left?.val == root.val ? left + 1 : 0; + right = root.right?.val == root.val ? right + 1 : 0; + ans = Math.max(ans, left + right); + return Math.max(left, right); + }; + dfs(root); + return ans; +}; ``` +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +#define max(a, b) (((a) > (b)) ? (a) : (b)) + +int dfs(struct TreeNode* root, int target, int* res) { + if (!root) { + return 0; + } + int left = dfs(root->left, root->val, res); + int right = dfs(root->right, root->val, res); + *res = max(*res, left + right); + if (root->val == target) { + return max(left, right) + 1; + } + return 0; +} + +int longestUnivaluePath(struct TreeNode* root) { + if (!root) { + return 0; + } + int res = 0; + dfs(root, root->val, &res); + return res; +} ``` + + diff --git a/solution/0600-0699/0687.Longest Univalue Path/README_EN.md b/solution/0600-0699/0687.Longest Univalue Path/README_EN.md index d2e4fa26aef27..6fda5172264fc 100644 --- a/solution/0600-0699/0687.Longest Univalue Path/README_EN.md +++ b/solution/0600-0699/0687.Longest Univalue Path/README_EN.md @@ -36,12 +36,10 @@ ## Solutions -Similar to problem [543. Diameter of Binary Tree](/solution/0500-0599/0543.Diameter%20of%20Binary%20Tree/README_EN.md). +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -66,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -107,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -179,78 +171,6 @@ func longestUnivaluePath(root *TreeNode) int { } ``` -### **C** - -```c -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int dfs(struct TreeNode* root, int target, int* res) { - if (!root) { - return 0; - } - int left = dfs(root->left, root->val, res); - int right = dfs(root->right, root->val, res); - *res = max(*res, left + right); - if (root->val == target) { - return max(left, right) + 1; - } - return 0; -} - -int longestUnivaluePath(struct TreeNode* root) { - if (!root) { - return 0; - } - int res = 0; - dfs(root, root->val, &res); - return res; -} -``` - -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number} - */ -var longestUnivaluePath = function (root) { - let ans = 0; - let dfs = function (root) { - if (!root) { - return 0; - } - let left = dfs(root.left), - right = dfs(root.right); - left = root.left?.val == root.val ? left + 1 : 0; - right = root.right?.val == root.val ? right + 1 : 0; - ans = Math.max(ans, left + right); - return Math.max(left, right); - }; - dfs(root); - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -292,8 +212,6 @@ function longestUnivaluePath(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -343,10 +261,72 @@ impl Solution { } ``` -### **...** - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var longestUnivaluePath = function (root) { + let ans = 0; + let dfs = function (root) { + if (!root) { + return 0; + } + let left = dfs(root.left), + right = dfs(root.right); + left = root.left?.val == root.val ? left + 1 : 0; + right = root.right?.val == root.val ? right + 1 : 0; + ans = Math.max(ans, left + right); + return Math.max(left, right); + }; + dfs(root); + return ans; +}; ``` +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +#define max(a, b) (((a) > (b)) ? (a) : (b)) + +int dfs(struct TreeNode* root, int target, int* res) { + if (!root) { + return 0; + } + int left = dfs(root->left, root->val, res); + int right = dfs(root->right, root->val, res); + *res = max(*res, left + right); + if (root->val == target) { + return max(left, right) + 1; + } + return 0; +} + +int longestUnivaluePath(struct TreeNode* root) { + if (!root) { + return 0; + } + int res = 0; + dfs(root, root->val, &res); + return res; +} ``` + + diff --git a/solution/0600-0699/0688.Knight Probability in Chessboard/README.md b/solution/0600-0699/0688.Knight Probability in Chessboard/README.md index 28e198ec48101..cc8245de18e88 100644 --- a/solution/0600-0699/0688.Knight Probability in Chessboard/README.md +++ b/solution/0600-0699/0688.Knight Probability in Chessboard/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[h][i][j]$ 表示骑士从 $(i, j)$ 位置出发,走了 $h$ 步以后还留在棋盘上的概率。那么最终答案就是 $f[k][row][column]$。 @@ -71,10 +69,6 @@ $$ -### **Python3** - - - ```python class Solution: def knightProbability(self, n: int, k: int, row: int, column: int) -> float: @@ -92,10 +86,6 @@ class Solution: return f[k][row][column] ``` -### **Java** - - - ```java class Solution { public double knightProbability(int n, int k, int row, int column) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,64 +142,6 @@ public: }; ``` -### **Rust** - -```rust -const DIR: [(i32, i32); 8] = [ - (-2, -1), - (2, -1), - (-1, -2), - (1, -2), - (2, 1), - (-2, 1), - (1, 2), - (-1, 2), -]; -const P: f64 = 1.0 / 8.0; - -impl Solution { - #[allow(dead_code)] - pub fn knight_probability(n: i32, k: i32, row: i32, column: i32) -> f64 { - // Here dp[i][j][k] represents through `i` steps, the probability that the knight stays on the board - // Starts from row: `j`, column: `k` - let mut dp: Vec>> = - vec![vec![vec![0 as f64; n as usize]; n as usize]; k as usize + 1]; - - // Initialize the dp vector, since dp[0][j][k] should be 1 - for j in 0..n as usize { - for k in 0..n as usize { - dp[0][j][k] = 1.0; - } - } - - // Begin the actual dp process - for i in 1..=k { - for j in 0..n { - for k in 0..n { - for (dx, dy) in DIR { - let x = j + dx; - let y = k + dy; - if Self::check_bounds(x, y, n, n) { - dp[i as usize][j as usize][k as usize] += - P * dp[(i as usize) - 1][x as usize][y as usize]; - } - } - } - } - } - - dp[k as usize][row as usize][column as usize] - } - - #[allow(dead_code)] - fn check_bounds(i: i32, j: i32, n: i32, m: i32) -> bool { - i >= 0 && i < n && j >= 0 && j < m - } -} -``` - -### **Go** - ```go func knightProbability(n int, k int, row int, column int) float64 { f := make([][][]float64, k+1) @@ -241,8 +171,6 @@ func knightProbability(n int, k int, row int, column int) float64 { } ``` -### **TypeScript** - ```ts function knightProbability(n: number, k: number, row: number, column: number): number { const f = new Array(k + 1) @@ -271,10 +199,60 @@ function knightProbability(n: number, k: number, row: number, column: number): n } ``` -### **...** +```rust +const DIR: [(i32, i32); 8] = [ + (-2, -1), + (2, -1), + (-1, -2), + (1, -2), + (2, 1), + (-2, 1), + (1, 2), + (-1, 2), +]; +const P: f64 = 1.0 / 8.0; -``` +impl Solution { + #[allow(dead_code)] + pub fn knight_probability(n: i32, k: i32, row: i32, column: i32) -> f64 { + // Here dp[i][j][k] represents through `i` steps, the probability that the knight stays on the board + // Starts from row: `j`, column: `k` + let mut dp: Vec>> = + vec![vec![vec![0 as f64; n as usize]; n as usize]; k as usize + 1]; + // Initialize the dp vector, since dp[0][j][k] should be 1 + for j in 0..n as usize { + for k in 0..n as usize { + dp[0][j][k] = 1.0; + } + } + + // Begin the actual dp process + for i in 1..=k { + for j in 0..n { + for k in 0..n { + for (dx, dy) in DIR { + let x = j + dx; + let y = k + dy; + if Self::check_bounds(x, y, n, n) { + dp[i as usize][j as usize][k as usize] += + P * dp[(i as usize) - 1][x as usize][y as usize]; + } + } + } + } + } + + dp[k as usize][row as usize][column as usize] + } + + #[allow(dead_code)] + fn check_bounds(i: i32, j: i32, n: i32, m: i32) -> bool { + i >= 0 && i < n && j >= 0 && j < m + } +} ``` + + diff --git a/solution/0600-0699/0688.Knight Probability in Chessboard/README_EN.md b/solution/0600-0699/0688.Knight Probability in Chessboard/README_EN.md index 63f551d567913..c455dd3ceb507 100644 --- a/solution/0600-0699/0688.Knight Probability in Chessboard/README_EN.md +++ b/solution/0600-0699/0688.Knight Probability in Chessboard/README_EN.md @@ -43,7 +43,7 @@ The total probability the knight stays on the board is 0.0625. ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming Let $f[h][i][j]$ denotes the probability that the knight is still on the chessboard after $h$ steps starting from the position $(i, j)$. Then the final answer is $f[k][row][column]$. @@ -63,8 +63,6 @@ The time complexity is $O(k \times n^2)$, and the space complexity is $O(k \time -### **Python3** - ```python class Solution: def knightProbability(self, n: int, k: int, row: int, column: int) -> float: @@ -82,8 +80,6 @@ class Solution: return f[k][row][column] ``` -### **Java** - ```java class Solution { public double knightProbability(int n, int k, int row, int column) { @@ -111,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,64 +136,6 @@ public: }; ``` -### **Rust** - -```rust -const DIR: [(i32, i32); 8] = [ - (-2, -1), - (2, -1), - (-1, -2), - (1, -2), - (2, 1), - (-2, 1), - (1, 2), - (-1, 2), -]; -const P: f64 = 1.0 / 8.0; - -impl Solution { - #[allow(dead_code)] - pub fn knight_probability(n: i32, k: i32, row: i32, column: i32) -> f64 { - // Here dp[i][j][k] represents through `i` steps, the probability that the knight stays on the board - // Starts from row: `j`, column: `k` - let mut dp: Vec>> = - vec![vec![vec![0 as f64; n as usize]; n as usize]; k as usize + 1]; - - // Initialize the dp vector, since dp[0][j][k] should be 1 - for j in 0..n as usize { - for k in 0..n as usize { - dp[0][j][k] = 1.0; - } - } - - // Begin the actual dp process - for i in 1..=k { - for j in 0..n { - for k in 0..n { - for (dx, dy) in DIR { - let x = j + dx; - let y = k + dy; - if Self::check_bounds(x, y, n, n) { - dp[i as usize][j as usize][k as usize] += - P * dp[(i as usize) - 1][x as usize][y as usize]; - } - } - } - } - } - - dp[k as usize][row as usize][column as usize] - } - - #[allow(dead_code)] - fn check_bounds(i: i32, j: i32, n: i32, m: i32) -> bool { - i >= 0 && i < n && j >= 0 && j < m - } -} -``` - -### **Go** - ```go func knightProbability(n int, k int, row int, column int) float64 { f := make([][][]float64, k+1) @@ -229,8 +165,6 @@ func knightProbability(n int, k int, row int, column int) float64 { } ``` -### **TypeScript** - ```ts function knightProbability(n: number, k: number, row: number, column: number): number { const f = new Array(k + 1) @@ -259,10 +193,60 @@ function knightProbability(n: number, k: number, row: number, column: number): n } ``` -### **...** +```rust +const DIR: [(i32, i32); 8] = [ + (-2, -1), + (2, -1), + (-1, -2), + (1, -2), + (2, 1), + (-2, 1), + (1, 2), + (-1, 2), +]; +const P: f64 = 1.0 / 8.0; + +impl Solution { + #[allow(dead_code)] + pub fn knight_probability(n: i32, k: i32, row: i32, column: i32) -> f64 { + // Here dp[i][j][k] represents through `i` steps, the probability that the knight stays on the board + // Starts from row: `j`, column: `k` + let mut dp: Vec>> = + vec![vec![vec![0 as f64; n as usize]; n as usize]; k as usize + 1]; -``` + // Initialize the dp vector, since dp[0][j][k] should be 1 + for j in 0..n as usize { + for k in 0..n as usize { + dp[0][j][k] = 1.0; + } + } + + // Begin the actual dp process + for i in 1..=k { + for j in 0..n { + for k in 0..n { + for (dx, dy) in DIR { + let x = j + dx; + let y = k + dy; + if Self::check_bounds(x, y, n, n) { + dp[i as usize][j as usize][k as usize] += + P * dp[(i as usize) - 1][x as usize][y as usize]; + } + } + } + } + } + + dp[k as usize][row as usize][column as usize] + } + #[allow(dead_code)] + fn check_bounds(i: i32, j: i32, n: i32, m: i32) -> bool { + i >= 0 && i < n && j >= 0 && j < m + } +} ``` + + diff --git a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README.md b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README.md index 5037dd53039bd..dcc1e6f95a437 100644 --- a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README.md +++ b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README.md @@ -40,30 +40,14 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 滑动窗口,枚举第三个子数组的位置,同时维护前两个无重叠子数组的最大和及其位置。 时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 -**方法二:预处理前后缀 + 枚举中间子数组** - -我们可以预处理得到数组 $nums$ 的前缀和数组 $s$,其中 $s[i] = \sum_{j=0}^{i-1} nums[j]$,那么对于任意的 $i$,$j$,$s[j] - s[i]$ 就是子数组 $[i, j)$ 的和。 - -接下来,我们使用动态规划的方法,维护两个长度为 $n$ 的数组 $pre$ 和 $suf$,其中 $pre[i]$ 表示 $[0, i]$ 范围内长度为 $k$ 的子数组的最大和及其起始位置,$suf[i]$ 表示 $[i, n)$ 范围内长度为 $k$ 的子数组的最大和及其起始位置。 - -然后,我们枚举中间子数组的起始位置 $i$,那么三个子数组的和就是 $pre[i-1][0] + suf[i+k][0] + (s[i+k] - s[i])$,其中 $pre[i-1][0]$ 表示 $[0, i-1]$ 范围内长度为 $k$ 的子数组的最大和,$suf[i+k][0]$ 表示 $[i+k, n)$ 范围内长度为 $k$ 的子数组的最大和,$(s[i+k] - s[i])$ 表示 $[i, i+k)$ 范围内长度为 $k$ 的子数组的和。我们找出和的最大值对应的三个子数组的起始位置即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。 - -### **Python3** - - - ```python class Solution: def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: @@ -91,40 +75,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: - n = len(nums) - s = list(accumulate(nums, initial=0)) - pre = [[] for _ in range(n)] - suf = [[] for _ in range(n)] - t = idx = 0 - for i in range(n - k + 1): - if (cur := s[i + k] - s[i]) > t: - pre[i + k - 1] = [cur, i] - t, idx = pre[i + k - 1] - else: - pre[i + k - 1] = [t, idx] - t = idx = 0 - for i in range(n - k, -1, -1): - if (cur := s[i + k] - s[i]) >= t: - suf[i] = [cur, i] - t, idx = suf[i] - else: - suf[i] = [t, idx] - t = 0 - ans = [] - for i in range(k, n - 2 * k + 1): - if (cur := s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0]) > t: - ans = [pre[i - 1][1], i, suf[i + k][1]] - t = cur - return ans -``` - -### **Java** - - - ```java class Solution { public int[] maxSumOfThreeSubarrays(int[] nums, int k) { @@ -160,6 +110,170 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector maxSumOfThreeSubarrays(vector& nums, int k) { + vector ans(3); + int s = 0, s1 = 0, s2 = 0, s3 = 0; + int mx1 = 0, mx12 = 0; + int idx1 = 0, idx121 = 0, idx122 = 0; + for (int i = k * 2; i < nums.size(); ++i) { + s1 += nums[i - k * 2]; + s2 += nums[i - k]; + s3 += nums[i]; + if (i >= k * 3 - 1) { + if (s1 > mx1) { + mx1 = s1; + idx1 = i - k * 3 + 1; + } + if (mx1 + s2 > mx12) { + mx12 = mx1 + s2; + idx121 = idx1; + idx122 = i - k * 2 + 1; + } + if (mx12 + s3 > s) { + s = mx12 + s3; + ans = {idx121, idx122, i - k + 1}; + } + s1 -= nums[i - k * 3 + 1]; + s2 -= nums[i - k * 2 + 1]; + s3 -= nums[i - k + 1]; + } + } + return ans; + } +}; +``` + +```go +func maxSumOfThreeSubarrays(nums []int, k int) []int { + ans := make([]int, 3) + s, s1, s2, s3 := 0, 0, 0, 0 + mx1, mx12 := 0, 0 + idx1, idx121, idx122 := 0, 0, 0 + for i := k * 2; i < len(nums); i++ { + s1 += nums[i-k*2] + s2 += nums[i-k] + s3 += nums[i] + if i >= k*3-1 { + if s1 > mx1 { + mx1 = s1 + idx1 = i - k*3 + 1 + } + if mx1+s2 > mx12 { + mx12 = mx1 + s2 + idx121 = idx1 + idx122 = i - k*2 + 1 + } + if mx12+s3 > s { + s = mx12 + s3 + ans = []int{idx121, idx122, i - k + 1} + } + s1 -= nums[i-k*3+1] + s2 -= nums[i-k*2+1] + s3 -= nums[i-k+1] + } + } + return ans +} +``` + +```ts +function maxSumOfThreeSubarrays(nums: number[], k: number): number[] { + const n: number = nums.length; + const s: number[] = Array(n + 1).fill(0); + + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + + const pre: number[][] = Array(n) + .fill([]) + .map(() => new Array(2).fill(0)); + const suf: number[][] = Array(n) + .fill([]) + .map(() => new Array(2).fill(0)); + + for (let i = 0, t = 0, idx = 0; i < n - k + 1; ++i) { + const cur: number = s[i + k] - s[i]; + if (cur > t) { + pre[i + k - 1] = [cur, i]; + t = cur; + idx = i; + } else { + pre[i + k - 1] = [t, idx]; + } + } + + for (let i = n - k, t = 0, idx = 0; i >= 0; --i) { + const cur: number = s[i + k] - s[i]; + if (cur >= t) { + suf[i] = [cur, i]; + t = cur; + idx = i; + } else { + suf[i] = [t, idx]; + } + } + + let ans: number[] = []; + for (let i = k, t = 0; i < n - 2 * k + 1; ++i) { + const cur: number = s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0]; + if (cur > t) { + ans = [pre[i - 1][1], i, suf[i + k][1]]; + t = cur; + } + } + + return ans; +} +``` + + + +### 方法二:预处理前后缀 + 枚举中间子数组 + +我们可以预处理得到数组 $nums$ 的前缀和数组 $s$,其中 $s[i] = \sum_{j=0}^{i-1} nums[j]$,那么对于任意的 $i$,$j$,$s[j] - s[i]$ 就是子数组 $[i, j)$ 的和。 + +接下来,我们使用动态规划的方法,维护两个长度为 $n$ 的数组 $pre$ 和 $suf$,其中 $pre[i]$ 表示 $[0, i]$ 范围内长度为 $k$ 的子数组的最大和及其起始位置,$suf[i]$ 表示 $[i, n)$ 范围内长度为 $k$ 的子数组的最大和及其起始位置。 + +然后,我们枚举中间子数组的起始位置 $i$,那么三个子数组的和就是 $pre[i-1][0] + suf[i+k][0] + (s[i+k] - s[i])$,其中 $pre[i-1][0]$ 表示 $[0, i-1]$ 范围内长度为 $k$ 的子数组的最大和,$suf[i+k][0]$ 表示 $[i+k, n)$ 范围内长度为 $k$ 的子数组的最大和,$(s[i+k] - s[i])$ 表示 $[i, i+k)$ 范围内长度为 $k$ 的子数组的和。我们找出和的最大值对应的三个子数组的起始位置即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。 + + + +```python +class Solution: + def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: + n = len(nums) + s = list(accumulate(nums, initial=0)) + pre = [[] for _ in range(n)] + suf = [[] for _ in range(n)] + t = idx = 0 + for i in range(n - k + 1): + if (cur := s[i + k] - s[i]) > t: + pre[i + k - 1] = [cur, i] + t, idx = pre[i + k - 1] + else: + pre[i + k - 1] = [t, idx] + t = idx = 0 + for i in range(n - k, -1, -1): + if (cur := s[i + k] - s[i]) >= t: + suf[i] = [cur, i] + t, idx = suf[i] + else: + suf[i] = [t, idx] + t = 0 + ans = [] + for i in range(k, n - 2 * k + 1): + if (cur := s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0]) > t: + ans = [pre[i - 1][1], i, suf[i + k][1]] + t = cur + return ans +``` + ```java class Solution { public int[] maxSumOfThreeSubarrays(int[] nums, int k) { @@ -203,44 +317,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector maxSumOfThreeSubarrays(vector& nums, int k) { - vector ans(3); - int s = 0, s1 = 0, s2 = 0, s3 = 0; - int mx1 = 0, mx12 = 0; - int idx1 = 0, idx121 = 0, idx122 = 0; - for (int i = k * 2; i < nums.size(); ++i) { - s1 += nums[i - k * 2]; - s2 += nums[i - k]; - s3 += nums[i]; - if (i >= k * 3 - 1) { - if (s1 > mx1) { - mx1 = s1; - idx1 = i - k * 3 + 1; - } - if (mx1 + s2 > mx12) { - mx12 = mx1 + s2; - idx121 = idx1; - idx122 = i - k * 2 + 1; - } - if (mx12 + s3 > s) { - s = mx12 + s3; - ans = {idx121, idx122, i - k + 1}; - } - s1 -= nums[i - k * 3 + 1]; - s2 -= nums[i - k * 2 + 1]; - s3 -= nums[i - k + 1]; - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -290,41 +366,6 @@ public: }; ``` -### **Go** - -```go -func maxSumOfThreeSubarrays(nums []int, k int) []int { - ans := make([]int, 3) - s, s1, s2, s3 := 0, 0, 0, 0 - mx1, mx12 := 0, 0 - idx1, idx121, idx122 := 0, 0, 0 - for i := k * 2; i < len(nums); i++ { - s1 += nums[i-k*2] - s2 += nums[i-k] - s3 += nums[i] - if i >= k*3-1 { - if s1 > mx1 { - mx1 = s1 - idx1 = i - k*3 + 1 - } - if mx1+s2 > mx12 { - mx12 = mx1 + s2 - idx121 = idx1 - idx122 = i - k*2 + 1 - } - if mx12+s3 > s { - s = mx12 + s3 - ans = []int{idx121, idx122, i - k + 1} - } - s1 -= nums[i-k*3+1] - s2 -= nums[i-k*2+1] - s3 -= nums[i-k+1] - } - } - return ans -} -``` - ```go func maxSumOfThreeSubarrays(nums []int, k int) (ans []int) { n := len(nums) @@ -368,63 +409,6 @@ func maxSumOfThreeSubarrays(nums []int, k int) (ans []int) { } ``` -### **TypeScript** - -```ts -function maxSumOfThreeSubarrays(nums: number[], k: number): number[] { - const n: number = nums.length; - const s: number[] = Array(n + 1).fill(0); - - for (let i = 0; i < n; ++i) { - s[i + 1] = s[i] + nums[i]; - } - - const pre: number[][] = Array(n) - .fill([]) - .map(() => new Array(2).fill(0)); - const suf: number[][] = Array(n) - .fill([]) - .map(() => new Array(2).fill(0)); - - for (let i = 0, t = 0, idx = 0; i < n - k + 1; ++i) { - const cur: number = s[i + k] - s[i]; - if (cur > t) { - pre[i + k - 1] = [cur, i]; - t = cur; - idx = i; - } else { - pre[i + k - 1] = [t, idx]; - } - } - - for (let i = n - k, t = 0, idx = 0; i >= 0; --i) { - const cur: number = s[i + k] - s[i]; - if (cur >= t) { - suf[i] = [cur, i]; - t = cur; - idx = i; - } else { - suf[i] = [t, idx]; - } - } - - let ans: number[] = []; - for (let i = k, t = 0; i < n - 2 * k + 1; ++i) { - const cur: number = s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0]; - if (cur > t) { - ans = [pre[i - 1][1], i, suf[i + k][1]]; - t = cur; - } - } - - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md index 96b60968443fc..16810b8ffa615 100644 --- a/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md +++ b/solution/0600-0699/0689.Maximum Sum of 3 Non-Overlapping Subarrays/README_EN.md @@ -36,26 +36,14 @@ We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicograph ## Solutions -**Solution 1: Sliding Window** +### Solution 1: Sliding Window We use a sliding window to enumerate the position of the third subarray, while maintaining the maximum sum and its position of the first two non-overlapping subarrays. The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. -**Solution 2: Preprocessing Prefix and Suffix + Enumerating Middle Subarray** - -We can preprocess to get the prefix sum array $s$ of the array $nums$, where $s[i] = \sum_{j=0}^{i-1} nums[j]$. Then for any $i$, $j$, $s[j] - s[i]$ is the sum of the subarray $[i, j)$. - -Next, we use dynamic programming to maintain two arrays $pre$ and $suf$ of length $n$, where $pre[i]$ represents the maximum sum and its starting position of the subarray of length $k$ within the range $[0, i]$, and $suf[i]$ represents the maximum sum and its starting position of the subarray of length $k$ within the range $[i, n)$. - -Then, we enumerate the starting position $i$ of the middle subarray. The sum of the three subarrays is $pre[i-1][0] + suf[i+k][0] + (s[i+k] - s[i])$, where $pre[i-1][0]$ represents the maximum sum of the subarray of length $k$ within the range $[0, i-1]$, $suf[i+k][0]$ represents the maximum sum of the subarray of length $k$ within the range $[i+k, n)$, and $(s[i+k] - s[i])$ represents the sum of the subarray of length $k$ within the range $[i, i+k)$. We find the starting positions of the three subarrays corresponding to the maximum sum. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. - -### **Python3** - ```python class Solution: def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: @@ -83,38 +71,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: - n = len(nums) - s = list(accumulate(nums, initial=0)) - pre = [[] for _ in range(n)] - suf = [[] for _ in range(n)] - t = idx = 0 - for i in range(n - k + 1): - if (cur := s[i + k] - s[i]) > t: - pre[i + k - 1] = [cur, i] - t, idx = pre[i + k - 1] - else: - pre[i + k - 1] = [t, idx] - t = idx = 0 - for i in range(n - k, -1, -1): - if (cur := s[i + k] - s[i]) >= t: - suf[i] = [cur, i] - t, idx = suf[i] - else: - suf[i] = [t, idx] - t = 0 - ans = [] - for i in range(k, n - 2 * k + 1): - if (cur := s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0]) > t: - ans = [pre[i - 1][1], i, suf[i + k][1]] - t = cur - return ans -``` - -### **Java** - ```java class Solution { public int[] maxSumOfThreeSubarrays(int[] nums, int k) { @@ -150,6 +106,170 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector maxSumOfThreeSubarrays(vector& nums, int k) { + vector ans(3); + int s = 0, s1 = 0, s2 = 0, s3 = 0; + int mx1 = 0, mx12 = 0; + int idx1 = 0, idx121 = 0, idx122 = 0; + for (int i = k * 2; i < nums.size(); ++i) { + s1 += nums[i - k * 2]; + s2 += nums[i - k]; + s3 += nums[i]; + if (i >= k * 3 - 1) { + if (s1 > mx1) { + mx1 = s1; + idx1 = i - k * 3 + 1; + } + if (mx1 + s2 > mx12) { + mx12 = mx1 + s2; + idx121 = idx1; + idx122 = i - k * 2 + 1; + } + if (mx12 + s3 > s) { + s = mx12 + s3; + ans = {idx121, idx122, i - k + 1}; + } + s1 -= nums[i - k * 3 + 1]; + s2 -= nums[i - k * 2 + 1]; + s3 -= nums[i - k + 1]; + } + } + return ans; + } +}; +``` + +```go +func maxSumOfThreeSubarrays(nums []int, k int) []int { + ans := make([]int, 3) + s, s1, s2, s3 := 0, 0, 0, 0 + mx1, mx12 := 0, 0 + idx1, idx121, idx122 := 0, 0, 0 + for i := k * 2; i < len(nums); i++ { + s1 += nums[i-k*2] + s2 += nums[i-k] + s3 += nums[i] + if i >= k*3-1 { + if s1 > mx1 { + mx1 = s1 + idx1 = i - k*3 + 1 + } + if mx1+s2 > mx12 { + mx12 = mx1 + s2 + idx121 = idx1 + idx122 = i - k*2 + 1 + } + if mx12+s3 > s { + s = mx12 + s3 + ans = []int{idx121, idx122, i - k + 1} + } + s1 -= nums[i-k*3+1] + s2 -= nums[i-k*2+1] + s3 -= nums[i-k+1] + } + } + return ans +} +``` + +```ts +function maxSumOfThreeSubarrays(nums: number[], k: number): number[] { + const n: number = nums.length; + const s: number[] = Array(n + 1).fill(0); + + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + + const pre: number[][] = Array(n) + .fill([]) + .map(() => new Array(2).fill(0)); + const suf: number[][] = Array(n) + .fill([]) + .map(() => new Array(2).fill(0)); + + for (let i = 0, t = 0, idx = 0; i < n - k + 1; ++i) { + const cur: number = s[i + k] - s[i]; + if (cur > t) { + pre[i + k - 1] = [cur, i]; + t = cur; + idx = i; + } else { + pre[i + k - 1] = [t, idx]; + } + } + + for (let i = n - k, t = 0, idx = 0; i >= 0; --i) { + const cur: number = s[i + k] - s[i]; + if (cur >= t) { + suf[i] = [cur, i]; + t = cur; + idx = i; + } else { + suf[i] = [t, idx]; + } + } + + let ans: number[] = []; + for (let i = k, t = 0; i < n - 2 * k + 1; ++i) { + const cur: number = s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0]; + if (cur > t) { + ans = [pre[i - 1][1], i, suf[i + k][1]]; + t = cur; + } + } + + return ans; +} +``` + + + +### Solution 2: Preprocessing Prefix and Suffix + Enumerating Middle Subarray + +We can preprocess to get the prefix sum array $s$ of the array $nums$, where $s[i] = \sum_{j=0}^{i-1} nums[j]$. Then for any $i$, $j$, $s[j] - s[i]$ is the sum of the subarray $[i, j)$. + +Next, we use dynamic programming to maintain two arrays $pre$ and $suf$ of length $n$, where $pre[i]$ represents the maximum sum and its starting position of the subarray of length $k$ within the range $[0, i]$, and $suf[i]$ represents the maximum sum and its starting position of the subarray of length $k$ within the range $[i, n)$. + +Then, we enumerate the starting position $i$ of the middle subarray. The sum of the three subarrays is $pre[i-1][0] + suf[i+k][0] + (s[i+k] - s[i])$, where $pre[i-1][0]$ represents the maximum sum of the subarray of length $k$ within the range $[0, i-1]$, $suf[i+k][0]$ represents the maximum sum of the subarray of length $k$ within the range $[i+k, n)$, and $(s[i+k] - s[i])$ represents the sum of the subarray of length $k$ within the range $[i, i+k)$. We find the starting positions of the three subarrays corresponding to the maximum sum. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. + + + +```python +class Solution: + def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: + n = len(nums) + s = list(accumulate(nums, initial=0)) + pre = [[] for _ in range(n)] + suf = [[] for _ in range(n)] + t = idx = 0 + for i in range(n - k + 1): + if (cur := s[i + k] - s[i]) > t: + pre[i + k - 1] = [cur, i] + t, idx = pre[i + k - 1] + else: + pre[i + k - 1] = [t, idx] + t = idx = 0 + for i in range(n - k, -1, -1): + if (cur := s[i + k] - s[i]) >= t: + suf[i] = [cur, i] + t, idx = suf[i] + else: + suf[i] = [t, idx] + t = 0 + ans = [] + for i in range(k, n - 2 * k + 1): + if (cur := s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0]) > t: + ans = [pre[i - 1][1], i, suf[i + k][1]] + t = cur + return ans +``` + ```java class Solution { public int[] maxSumOfThreeSubarrays(int[] nums, int k) { @@ -193,44 +313,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector maxSumOfThreeSubarrays(vector& nums, int k) { - vector ans(3); - int s = 0, s1 = 0, s2 = 0, s3 = 0; - int mx1 = 0, mx12 = 0; - int idx1 = 0, idx121 = 0, idx122 = 0; - for (int i = k * 2; i < nums.size(); ++i) { - s1 += nums[i - k * 2]; - s2 += nums[i - k]; - s3 += nums[i]; - if (i >= k * 3 - 1) { - if (s1 > mx1) { - mx1 = s1; - idx1 = i - k * 3 + 1; - } - if (mx1 + s2 > mx12) { - mx12 = mx1 + s2; - idx121 = idx1; - idx122 = i - k * 2 + 1; - } - if (mx12 + s3 > s) { - s = mx12 + s3; - ans = {idx121, idx122, i - k + 1}; - } - s1 -= nums[i - k * 3 + 1]; - s2 -= nums[i - k * 2 + 1]; - s3 -= nums[i - k + 1]; - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -280,41 +362,6 @@ public: }; ``` -### **Go** - -```go -func maxSumOfThreeSubarrays(nums []int, k int) []int { - ans := make([]int, 3) - s, s1, s2, s3 := 0, 0, 0, 0 - mx1, mx12 := 0, 0 - idx1, idx121, idx122 := 0, 0, 0 - for i := k * 2; i < len(nums); i++ { - s1 += nums[i-k*2] - s2 += nums[i-k] - s3 += nums[i] - if i >= k*3-1 { - if s1 > mx1 { - mx1 = s1 - idx1 = i - k*3 + 1 - } - if mx1+s2 > mx12 { - mx12 = mx1 + s2 - idx121 = idx1 - idx122 = i - k*2 + 1 - } - if mx12+s3 > s { - s = mx12 + s3 - ans = []int{idx121, idx122, i - k + 1} - } - s1 -= nums[i-k*3+1] - s2 -= nums[i-k*2+1] - s3 -= nums[i-k+1] - } - } - return ans -} -``` - ```go func maxSumOfThreeSubarrays(nums []int, k int) (ans []int) { n := len(nums) @@ -358,63 +405,6 @@ func maxSumOfThreeSubarrays(nums []int, k int) (ans []int) { } ``` -### **TypeScript** - -```ts -function maxSumOfThreeSubarrays(nums: number[], k: number): number[] { - const n: number = nums.length; - const s: number[] = Array(n + 1).fill(0); - - for (let i = 0; i < n; ++i) { - s[i + 1] = s[i] + nums[i]; - } - - const pre: number[][] = Array(n) - .fill([]) - .map(() => new Array(2).fill(0)); - const suf: number[][] = Array(n) - .fill([]) - .map(() => new Array(2).fill(0)); - - for (let i = 0, t = 0, idx = 0; i < n - k + 1; ++i) { - const cur: number = s[i + k] - s[i]; - if (cur > t) { - pre[i + k - 1] = [cur, i]; - t = cur; - idx = i; - } else { - pre[i + k - 1] = [t, idx]; - } - } - - for (let i = n - k, t = 0, idx = 0; i >= 0; --i) { - const cur: number = s[i + k] - s[i]; - if (cur >= t) { - suf[i] = [cur, i]; - t = cur; - idx = i; - } else { - suf[i] = [t, idx]; - } - } - - let ans: number[] = []; - for (let i = k, t = 0; i < n - 2 * k + 1; ++i) { - const cur: number = s[i + k] - s[i] + pre[i - 1][0] + suf[i + k][0]; - if (cur > t) { - ans = [pre[i - 1][1], i, suf[i + k][1]]; - t = cur; - } - } - - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0690.Employee Importance/README.md b/solution/0600-0699/0690.Employee Importance/README.md index 214996554569c..0a24bd5bdb1dd 100644 --- a/solution/0600-0699/0690.Employee Importance/README.md +++ b/solution/0600-0699/0690.Employee Importance/README.md @@ -34,16 +34,10 @@ ## 解法 - - -“所有下属” 包括了 “下属的下属”,先用哈希表存储员工 id 和员工之间的映射关系,然后再递归求解即可(也能用 BFS 实现) +### 方法一 -### **Python3** - - - ```python """ # Definition for Employee. @@ -69,10 +63,6 @@ class Solution: return dfs(id) ``` -### **Java** - - - ```java /* // Definition for Employee. @@ -105,8 +95,6 @@ class Solution { } ``` -### **JavaScript** - ```js /** * Definition for Employee. @@ -139,10 +127,6 @@ var GetImportance = function (employees, id) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0690.Employee Importance/README_EN.md b/solution/0600-0699/0690.Employee Importance/README_EN.md index e4cf656b5faf3..6e3b747152145 100644 --- a/solution/0600-0699/0690.Employee Importance/README_EN.md +++ b/solution/0600-0699/0690.Employee Importance/README_EN.md @@ -50,12 +50,10 @@ Thus, the total importance value of employee 5 is -3. ## Solutions -"all their subordinates" include "subordinates of subordinates", first use a hash table to store the mapping relationship between `employee.id` and `employee`, and then recursively solve it (it can also be implemented with BFS) +### Solution 1 -### **Python3** - ```python """ # Definition for Employee. @@ -81,8 +79,6 @@ class Solution: return dfs(id) ``` -### **Java** - ```java /* // Definition for Employee. @@ -115,8 +111,6 @@ class Solution { } ``` -### **JavaScript** - ```js /** * Definition for Employee. @@ -149,10 +143,6 @@ var GetImportance = function (employees, id) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0691.Stickers to Spell Word/README.md b/solution/0600-0699/0691.Stickers to Spell Word/README.md index 8a1ebdcc7f45f..a8e9403e6ace8 100644 --- a/solution/0600-0699/0691.Stickers to Spell Word/README.md +++ b/solution/0600-0699/0691.Stickers to Spell Word/README.md @@ -48,16 +48,10 @@ ## 解法 - - -**方法一:BFS + 状态压缩** +### 方法一:BFS + 状态压缩 -### **Python3** - - - ```python class Solution: def minStickers(self, stickers: List[str], target: str) -> int: @@ -85,10 +79,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int minStickers(String[] stickers, String target) { @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +158,6 @@ public: }; ``` -### **Go** - ```go func minStickers(stickers []string, target string) int { q := []int{0} @@ -211,8 +197,6 @@ func minStickers(stickers []string, target string) int { } ``` -### **Rust** - ```rust use std::collections::{ HashSet, VecDeque }; @@ -256,10 +240,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0691.Stickers to Spell Word/README_EN.md b/solution/0600-0699/0691.Stickers to Spell Word/README_EN.md index 089445b57eafb..481151155db30 100644 --- a/solution/0600-0699/0691.Stickers to Spell Word/README_EN.md +++ b/solution/0600-0699/0691.Stickers to Spell Word/README_EN.md @@ -46,12 +46,10 @@ We cannot form the target "basicbasic" from cutting letters from the g ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def minStickers(self, stickers: List[str], target: str) -> int: @@ -79,8 +77,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int minStickers(String[] stickers, String target) { @@ -122,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +156,6 @@ public: }; ``` -### **Go** - ```go func minStickers(stickers []string, target string) int { q := []int{0} @@ -203,8 +195,6 @@ func minStickers(stickers []string, target string) int { } ``` -### **Rust** - ```rust use std::collections::{ HashSet, VecDeque }; @@ -248,10 +238,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0692.Top K Frequent Words/README.md b/solution/0600-0699/0692.Top K Frequent Words/README.md index 51836e1c55465..b2795d56bf68b 100644 --- a/solution/0600-0699/0692.Top K Frequent Words/README.md +++ b/solution/0600-0699/0692.Top K Frequent Words/README.md @@ -47,16 +47,10 @@ ## 解法 - - -**方法一:哈希表 + 排序** +### 方法一:哈希表 + 排序 -### **Python3** - - - ```python class Solution: def topKFrequent(self, words: List[str], k: int) -> List[str]: @@ -64,10 +58,6 @@ class Solution: return sorted(cnt, key=lambda x: (-cnt[x], x))[:k] ``` -### **Java** - - - ```java class Solution { public List topKFrequent(String[] words, int k) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func topKFrequent(words []string, k int) []string { cnt := map[string]int{} @@ -133,10 +119,6 @@ func topKFrequent(words []string, k int) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0692.Top K Frequent Words/README_EN.md b/solution/0600-0699/0692.Top K Frequent Words/README_EN.md index b1cc5df8ffc6c..45eb2187de8bc 100644 --- a/solution/0600-0699/0692.Top K Frequent Words/README_EN.md +++ b/solution/0600-0699/0692.Top K Frequent Words/README_EN.md @@ -41,9 +41,9 @@ Note that "i" comes before "love" due to a lower alphabetica ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return sorted(cnt, key=lambda x: (-cnt[x], x))[:k] ``` -### **Java** - ```java class Solution { public List topKFrequent(String[] words, int k) { @@ -80,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +95,6 @@ public: }; ``` -### **Go** - ```go func topKFrequent(words []string, k int) []string { cnt := map[string]int{} @@ -119,10 +113,6 @@ func topKFrequent(words []string, k int) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0693.Binary Number with Alternating Bits/README.md b/solution/0600-0699/0693.Binary Number with Alternating Bits/README.md index 5fa8455f1916d..ca76048215fe6 100644 --- a/solution/0600-0699/0693.Binary Number with Alternating Bits/README.md +++ b/solution/0600-0699/0693.Binary Number with Alternating Bits/README.md @@ -42,24 +42,12 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 n 循环右移直至为 0,依次检测 n 的二进制位是否交替出现。若循环过程中发现 0、1 没有交替出现,直接返回 false。否则循环结束返回 true。 -**方法二:位运算** - -假设 01 交替出现,那么我们可以通过错位异或将尾部全部转为 1,加 1 可以得到 2 的幂次的一个数 n(n 中只有一个位是 1),接着利用 `n & (n + 1)` 可以消除最后一位的 1。 - -此时判断是否为 0,若是,说明假设成立,是 01 交替串。 - -### **Python3** - - - ```python class Solution: def hasAlternatingBits(self, n: int) -> bool: @@ -73,17 +61,6 @@ class Solution: return True ``` -```python -class Solution: - def hasAlternatingBits(self, n: int) -> bool: - n ^= n >> 1 - return (n & (n + 1)) == 0 -``` - -### **Java** - - - ```java class Solution { public boolean hasAlternatingBits(int n) { @@ -101,17 +78,6 @@ class Solution { } ``` -```java -class Solution { - public boolean hasAlternatingBits(int n) { - n ^= (n >> 1); - return (n & (n + 1)) == 0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -128,18 +94,21 @@ public: }; ``` -```cpp -class Solution { -public: - bool hasAlternatingBits(int n) { - n ^= (n >> 1); - return (n & ((long) n + 1)) == 0; - } -}; +```go +func hasAlternatingBits(n int) bool { + prev := -1 + for n != 0 { + curr := n & 1 + if prev == curr { + return false + } + prev = curr + n >>= 1 + } + return true +} ``` -### **Rust** - ```rust impl Solution { pub fn has_alternating_bits(mut n: i32) -> bool { @@ -158,30 +127,40 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn has_alternating_bits(n: i32) -> bool { - let t = n ^ (n >> 1); - (t & (t + 1)) == 0 + + +### 方法二:位运算 + +假设 01 交替出现,那么我们可以通过错位异或将尾部全部转为 1,加 1 可以得到 2 的幂次的一个数 n(n 中只有一个位是 1),接着利用 `n & (n + 1)` 可以消除最后一位的 1。 + +此时判断是否为 0,若是,说明假设成立,是 01 交替串。 + + + +```python +class Solution: + def hasAlternatingBits(self, n: int) -> bool: + n ^= n >> 1 + return (n & (n + 1)) == 0 +``` + +```java +class Solution { + public boolean hasAlternatingBits(int n) { + n ^= (n >> 1); + return (n & (n + 1)) == 0; } } ``` -### **Go** - -```go -func hasAlternatingBits(n int) bool { - prev := -1 - for n != 0 { - curr := n & 1 - if prev == curr { - return false - } - prev = curr - n >>= 1 - } - return true -} +```cpp +class Solution { +public: + bool hasAlternatingBits(int n) { + n ^= (n >> 1); + return (n & ((long) n + 1)) == 0; + } +}; ``` ```go @@ -191,10 +170,15 @@ func hasAlternatingBits(n int) bool { } ``` -### **...** - -``` - +```rust +impl Solution { + pub fn has_alternating_bits(n: i32) -> bool { + let t = n ^ (n >> 1); + (t & (t + 1)) == 0 + } +} ``` + + diff --git a/solution/0600-0699/0693.Binary Number with Alternating Bits/README_EN.md b/solution/0600-0699/0693.Binary Number with Alternating Bits/README_EN.md index ced719eb18a68..594749d633f11 100644 --- a/solution/0600-0699/0693.Binary Number with Alternating Bits/README_EN.md +++ b/solution/0600-0699/0693.Binary Number with Alternating Bits/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,15 +55,6 @@ class Solution: return True ``` -```python -class Solution: - def hasAlternatingBits(self, n: int) -> bool: - n ^= n >> 1 - return (n & (n + 1)) == 0 -``` - -### **Java** - ```java class Solution { public boolean hasAlternatingBits(int n) { @@ -81,17 +72,6 @@ class Solution { } ``` -```java -class Solution { - public boolean hasAlternatingBits(int n) { - n ^= (n >> 1); - return (n & (n + 1)) == 0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -108,18 +88,21 @@ public: }; ``` -```cpp -class Solution { -public: - bool hasAlternatingBits(int n) { - n ^= (n >> 1); - return (n & ((long) n + 1)) == 0; - } -}; +```go +func hasAlternatingBits(n int) bool { + prev := -1 + for n != 0 { + curr := n & 1 + if prev == curr { + return false + } + prev = curr + n >>= 1 + } + return true +} ``` -### **Rust** - ```rust impl Solution { pub fn has_alternating_bits(mut n: i32) -> bool { @@ -138,30 +121,36 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn has_alternating_bits(n: i32) -> bool { - let t = n ^ (n >> 1); - (t & (t + 1)) == 0 + + +### Solution 2 + + + +```python +class Solution: + def hasAlternatingBits(self, n: int) -> bool: + n ^= n >> 1 + return (n & (n + 1)) == 0 +``` + +```java +class Solution { + public boolean hasAlternatingBits(int n) { + n ^= (n >> 1); + return (n & (n + 1)) == 0; } } ``` -### **Go** - -```go -func hasAlternatingBits(n int) bool { - prev := -1 - for n != 0 { - curr := n & 1 - if prev == curr { - return false - } - prev = curr - n >>= 1 - } - return true -} +```cpp +class Solution { +public: + bool hasAlternatingBits(int n) { + n ^= (n >> 1); + return (n & ((long) n + 1)) == 0; + } +}; ``` ```go @@ -171,10 +160,15 @@ func hasAlternatingBits(n int) bool { } ``` -### **...** - -``` - +```rust +impl Solution { + pub fn has_alternating_bits(n: i32) -> bool { + let t = n ^ (n >> 1); + (t & (t + 1)) == 0 + } +} ``` + + diff --git a/solution/0600-0699/0694.Number of Distinct Islands/README.md b/solution/0600-0699/0694.Number of Distinct Islands/README.md index 60f73d3d46c1e..017f67d3ec374 100644 --- a/solution/0600-0699/0694.Number of Distinct Islands/README.md +++ b/solution/0600-0699/0694.Number of Distinct Islands/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:哈希表 + DFS** +### 方法一:哈希表 + DFS 我们遍历网格中的每个位置 $(i, j)$,如果该位置为 $1$,则以其为起始节点开始进行深度优先搜索,过程中将 $1$ 修改为 $0$,并且将搜索的方向记录下来,等搜索结束后将方向序列加入哈希表中,最后返回哈希表中不同方向序列的数量即可。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def numDistinctIslands(self, grid: List[List[int]]) -> int: @@ -81,10 +75,6 @@ class Solution: return len(paths) ``` -### **Java** - - - ```java class Solution { private int m; @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go func numDistinctIslands(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -195,8 +181,6 @@ func numDistinctIslands(grid [][]int) int { } ``` -### **TypeScript** - ```ts function numDistinctIslands(grid: number[][]): number { const m = grid.length; @@ -228,10 +212,6 @@ function numDistinctIslands(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0694.Number of Distinct Islands/README_EN.md b/solution/0600-0699/0694.Number of Distinct Islands/README_EN.md index 9e21aac56bd08..9fbeb666a565d 100644 --- a/solution/0600-0699/0694.Number of Distinct Islands/README_EN.md +++ b/solution/0600-0699/0694.Number of Distinct Islands/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return len(paths) ``` -### **Java** - ```java class Solution { private int m; @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +141,6 @@ public: }; ``` -### **Go** - ```go func numDistinctIslands(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -178,8 +172,6 @@ func numDistinctIslands(grid [][]int) int { } ``` -### **TypeScript** - ```ts function numDistinctIslands(grid: number[][]): number { const m = grid.length; @@ -211,10 +203,6 @@ function numDistinctIslands(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0695.Max Area of Island/README.md b/solution/0600-0699/0695.Max Area of Island/README.md index e7bee536181e1..2d5a2a4fc4d49 100644 --- a/solution/0600-0699/0695.Max Area of Island/README.md +++ b/solution/0600-0699/0695.Max Area of Island/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们可以遍历每一个格子 $(i, j)$,从每个格子开始进行深度优先搜索,如果搜索到的格子是陆地,就将当前格子标记为已访问,并且继续搜索上、下、左、右四个方向的格子。搜索结束后,计算标记的陆地的数量,即为岛屿的面积。我们找出最大的岛屿面积即为答案。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def maxAreaOfIsland(self, grid: List[List[int]]) -> int: @@ -77,10 +71,6 @@ class Solution: return max(dfs(i, j) for i in range(m) for j in range(n)) ``` -### **Java** - - - ```java class Solution { private int m; @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go func maxAreaOfIsland(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -181,8 +167,6 @@ func maxAreaOfIsland(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function maxAreaOfIsland(grid: number[][]): number { const m = grid.length; @@ -212,8 +196,6 @@ function maxAreaOfIsland(grid: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { fn dfs(grid: &mut Vec>, i: usize, j: usize) -> i32 { @@ -245,10 +227,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0695.Max Area of Island/README_EN.md b/solution/0600-0699/0695.Max Area of Island/README_EN.md index 5c13a84dfd177..5f611653608e3 100644 --- a/solution/0600-0699/0695.Max Area of Island/README_EN.md +++ b/solution/0600-0699/0695.Max Area of Island/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return max(dfs(i, j) for i in range(m) for j in range(n)) ``` -### **Java** - ```java class Solution { private int m; @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +129,6 @@ public: }; ``` -### **Go** - ```go func maxAreaOfIsland(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -163,8 +157,6 @@ func maxAreaOfIsland(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function maxAreaOfIsland(grid: number[][]): number { const m = grid.length; @@ -194,8 +186,6 @@ function maxAreaOfIsland(grid: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { fn dfs(grid: &mut Vec>, i: usize, j: usize) -> i32 { @@ -227,10 +217,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0696.Count Binary Substrings/README.md b/solution/0600-0699/0696.Count Binary Substrings/README.md index 1d131ff4c7591..f5f635943eab3 100644 --- a/solution/0600-0699/0696.Count Binary Substrings/README.md +++ b/solution/0600-0699/0696.Count Binary Substrings/README.md @@ -39,14 +39,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def countBinarySubstrings(self, s: str) -> int: @@ -65,10 +61,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countBinarySubstrings(String s) { @@ -92,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +106,6 @@ public: }; ``` -### **Go** - ```go func countBinarySubstrings(s string) int { i, n := 0, len(s) @@ -139,10 +127,6 @@ func countBinarySubstrings(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0696.Count Binary Substrings/README_EN.md b/solution/0600-0699/0696.Count Binary Substrings/README_EN.md index 4418897202f7e..90cb923c03e13 100644 --- a/solution/0600-0699/0696.Count Binary Substrings/README_EN.md +++ b/solution/0600-0699/0696.Count Binary Substrings/README_EN.md @@ -37,9 +37,9 @@ Also, "00110011" is not a valid substring because all the 0's (and ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countBinarySubstrings(String s) { @@ -84,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +104,6 @@ public: }; ``` -### **Go** - ```go func countBinarySubstrings(s string) int { i, n := 0, len(s) @@ -131,10 +125,6 @@ func countBinarySubstrings(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0697.Degree of an Array/README.md b/solution/0600-0699/0697.Degree of an Array/README.md index 77e525ad8534d..aadfb3f19d708 100644 --- a/solution/0600-0699/0697.Degree of an Array/README.md +++ b/solution/0600-0699/0697.Degree of an Array/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 遍历数组,用哈希表记录数组每个元素出现的次数,以及首次、末次出现的位置。然后遍历哈希表,获取元素出现次数最多(可能有多个)且首末位置差最小的数。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def findShortestSubArray(self, nums: List[int]) -> int: @@ -78,10 +72,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int findShortestSubArray(int[] nums) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func findShortestSubArray(nums []int) int { cnt := map[int]int{} @@ -175,6 +161,12 @@ func findShortestSubArray(nums []int) int { } ``` + + +### 方法二 + + + ```go func findShortestSubArray(nums []int) (ans int) { ans = 50000 @@ -231,10 +223,6 @@ func getMaxDegreeElem(maxDegree int, numsMap map[int]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0697.Degree of an Array/README_EN.md b/solution/0600-0699/0697.Degree of an Array/README_EN.md index 749416b5a1662..649fa9e6ca388 100644 --- a/solution/0600-0699/0697.Degree of an Array/README_EN.md +++ b/solution/0600-0699/0697.Degree of an Array/README_EN.md @@ -41,9 +41,9 @@ So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int findShortestSubArray(int[] nums) { @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +124,6 @@ public: }; ``` -### **Go** - ```go func findShortestSubArray(nums []int) int { cnt := map[int]int{} @@ -159,6 +153,12 @@ func findShortestSubArray(nums []int) int { } ``` + + +### Solution 2 + + + ```go func findShortestSubArray(nums []int) (ans int) { ans = 50000 @@ -215,10 +215,6 @@ func getMaxDegreeElem(maxDegree int, numsMap map[int]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0698.Partition to K Equal Sum Subsets/README.md b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/README.md index 7f2d04dc9e7a8..8573818591fe1 100644 --- a/solution/0600-0699/0698.Partition to K Equal Sum Subsets/README.md +++ b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/README.md @@ -35,9 +35,7 @@ ## 解法 - - -**方法一:DFS + 剪枝** +### 方法一:DFS + 剪枝 根据题意,我们需要将数组 `nums` 划分为 $k$ 个子集,且每个子集的和相等。因此,先累加 `nums` 中所有元素的和,如果不能被 $k$ 整除,说明无法划分为 $k$ 个子集,提前返回 `false`。 @@ -47,43 +45,8 @@ 如果能将所有元素都加入到 `cur` 中,说明可以划分为 $k$ 个子集,返回 `true`。 -**方法二:状态压缩 + 记忆化搜索** - -与方法一相同,我们依然先判断数组 `nums` 是否有可能被划分为 $k$ 个子集。如果不能被 $k$ 整除,直接返回 `false`。 - -我们记 $s$ 为每个子集期望的和,当前元素被划分的情况为 `state`。对于第 $i$ 个数,若 `((state >> i) & 1)` 等于 $0$,说明第 $i$ 个元素未被划分。 - -我们的目标是从全部元素中凑出 $k$ 个和为 $s$ 的子集。记当前子集的和为 $t$。在未划分第 $i$ 个元素时: - -- 若 $t + nums[i] \gt s$,说明第 $i$ 个元素不能被添加到当前子集中,由于我们对 `nums` 数组进行升序排列,因此数组 `nums` 从位置 $i$ 开始的所有元素都不能被添加到当前子集,直接返回 `false`。 -- 否则,将第 $i$ 个元素添加到当前子集中,状态变为 `state | (1 << i)`,然后继续对未划分的元素进行搜索。需要注意的是,若 $t + nums[i] = s$,说明恰好可以得到一个和为 $s$ 的子集,下一步将 $t$ 归零(可以通过 `(t + nums[i]) % s` 实现),并继续划分下一个子集。 - -为了避免重复搜索,我们使用一个长度为 $2^n$ 的数组 `f` 记录每个状态下的搜索结果。数组 `f` 有三个可能的值: - -- `0`:表示当前状态还未搜索过; -- `-1`:表示当前状态下无法划分为 $k$ 个子集; -- `1`:表示当前状态下可以划分为 $k$ 个子集。 - -时间复杂度 $O(n\times 2^n)$,空间复杂度 $O(2^n)$。其中 $n$ 表示数组 $nums$ 的长度。对于每个状态,我们需要遍历数组 `nums`,时间复杂度为 $O(n)$;状态总数为 $2^n$,因此总的时间复杂度为 $O(n\times 2^n)$。 - -**方法三:动态规划** - -我们可以使用动态规划的方法求解本题。 - -我们定义 $f[i]$ 表示当前选取的数字的状态为 $i$ 时,是否存在 $k$ 个子集满足题目要求。初始时 $f[0]=true$,答案为 $f[2^n-1]$。其中 $n$ 表示数组 $nums$ 的长度。另外,我们定义 $cur[i]$ 表示当前选取的数字的状态为 $i$ 时,最后一个子集的和。 - -我们在 $[0,2^n)$ 的范围内枚举状态 $i$,对于每个状态 $i$,如果 $f[i]$ 为 `false`,我们直接跳过即可。否则,我们枚举 $nums$ 数组中的任意一个数 $nums[j]$,如果 $cur[i] + nums[j] \gt s$,我们直接跳出枚举循环,因为后面的数更大,无法放入当前子集;否则,如果 $i$ 的二进制表示的第 $j$ 位为 $0$,说明当前 $nums[j]$ 还没有被选取,我们可以将其放入当前子集中,此时状态变为 $i | 2^j$,并更新 $cur[i | 2^j] = (cur[i] + nums[j]) \bmod s$,并且 $f[i | 2^j] = true$。 - -最后,我们返回 $f[2^n-1]$ 即可。 - -时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(2^n)$。其中 $n$ 表示数组 $nums$ 的长度。 - -### **Python3** - - - ```python class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: @@ -107,59 +70,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: - @cache - def dfs(state, t): - if state == mask: - return True - for i, v in enumerate(nums): - if (state >> i) & 1: - continue - if t + v > s: - break - if dfs(state | 1 << i, (t + v) % s): - return True - return False - - s, mod = divmod(sum(nums), k) - if mod: - return False - nums.sort() - mask = (1 << len(nums)) - 1 - return dfs(0, 0) -``` - -```python -class Solution: - def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: - s = sum(nums) - if s % k: - return False - s //= k - nums.sort() - n = len(nums) - f = [False] * (1 << n) - cur = [0] * (1 << n) - f[0] = True - for i in range(1 << n): - if not f[i]: - continue - for j in range(n): - if cur[i] + nums[j] > s: - break - if (i >> j & 1) == 0: - if not f[i | 1 << j]: - cur[i | 1 << j] = (cur[i] + nums[j]) % s - f[i | 1 << j] = True - return f[-1] -``` - -### **Java** - - - ```java class Solution { private int[] nums; @@ -199,90 +109,6 @@ class Solution { } ``` -```java -class Solution { - private int[] f; - private int[] nums; - private int n; - private int s; - - public boolean canPartitionKSubsets(int[] nums, int k) { - for (int v : nums) { - s += v; - } - if (s % k != 0) { - return false; - } - s /= k; - Arrays.sort(nums); - this.nums = nums; - n = nums.length; - f = new int[1 << n]; - return dfs(0, 0); - } - - private boolean dfs(int state, int t) { - if (state == (1 << n) - 1) { - return true; - } - if (f[state] != 0) { - return f[state] == 1; - } - for (int i = 0; i < n; ++i) { - if (((state >> i) & 1) == 1) { - continue; - } - if (t + nums[i] > s) { - break; - } - if (dfs(state | 1 << i, (t + nums[i]) % s)) { - f[state] = 1; - return true; - } - } - f[state] = -1; - return false; - } -} -``` - -```java -class Solution { - public boolean canPartitionKSubsets(int[] nums, int k) { - int s = 0; - for (int x : nums) { - s += x; - } - if (s % k != 0) { - return false; - } - s /= k; - Arrays.sort(nums); - int n = nums.length; - boolean[] f = new boolean[1 << n]; - f[0] = true; - int[] cur = new int[1 << n]; - for (int i = 0; i < 1 << n; ++i) { - if (!f[i]) { - continue; - } - for (int j = 0; j < n; ++j) { - if (cur[i] + nums[j] > s) { - break; - } - if ((i >> j & 1) == 0) { - cur[i | 1 << j] = (cur[i] + nums[j]) % s; - f[i | 1 << j] = true; - } - } - } - return f[(1 << n) - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -317,84 +143,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool canPartitionKSubsets(vector& nums, int k) { - int s = accumulate(nums.begin(), nums.end(), 0); - if (s % k) { - return false; - } - s /= k; - sort(nums.begin(), nums.end()); - int n = nums.size(); - int mask = (1 << n) - 1; - vector f(1 << n); - function dfs; - dfs = [&](int state, int t) { - if (state == mask) { - return true; - } - if (f[state]) { - return f[state] == 1; - } - for (int i = 0; i < n; ++i) { - if (state >> i & 1) { - continue; - } - if (t + nums[i] > s) { - break; - } - if (dfs(state | 1 << i, (t + nums[i]) % s)) { - f[state] = 1; - return true; - } - } - f[state] = -1; - return false; - }; - return dfs(0, 0); - } -}; -``` - -```cpp -class Solution { -public: - bool canPartitionKSubsets(vector& nums, int k) { - int s = accumulate(nums.begin(), nums.end(), 0); - if (s % k) { - return false; - } - s /= k; - sort(nums.begin(), nums.end()); - int n = nums.size(); - bool f[1 << n]; - int cur[1 << n]; - memset(f, false, sizeof(f)); - memset(cur, 0, sizeof(cur)); - f[0] = 1; - for (int i = 0; i < 1 << n; ++i) { - if (!f[i]) { - continue; - } - for (int j = 0; j < n; ++j) { - if (cur[i] + nums[j] > s) { - break; - } - if ((i >> j & 1) == 0) { - f[i | 1 << j] = true; - cur[i | 1 << j] = (cur[i] + nums[j]) % s; - } - } - } - return f[(1 << n) - 1]; - } -}; -``` - -### **Go** - ```go func canPartitionKSubsets(nums []int, k int) bool { s := 0 @@ -431,19 +179,184 @@ func canPartitionKSubsets(nums []int, k int) bool { } ``` -```go -func canPartitionKSubsets(nums []int, k int) bool { - s := 0 - for _, v := range nums { - s += v - } - if s%k != 0 { - return false - } - s /= k - n := len(nums) - f := make([]int, 1< a + b); + if (s % k !== 0) { + return false; + } + s /= k; + nums.sort((a, b) => a - b); + const n = nums.length; + const f: boolean[] = new Array(1 << n).fill(false); + f[0] = true; + const cur: number[] = new Array(n).fill(0); + for (let i = 0; i < 1 << n; ++i) { + if (!f[i]) { + continue; + } + for (let j = 0; j < n; ++j) { + if (cur[i] + nums[j] > s) { + break; + } + if (((i >> j) & 1) === 0) { + f[i | (1 << j)] = true; + cur[i | (1 << j)] = (cur[i] + nums[j]) % s; + } + } + } + return f[(1 << n) - 1]; +} +``` + + + +### 方法二:状态压缩 + 记忆化搜索 + +与方法一相同,我们依然先判断数组 `nums` 是否有可能被划分为 $k$ 个子集。如果不能被 $k$ 整除,直接返回 `false`。 + +我们记 $s$ 为每个子集期望的和,当前元素被划分的情况为 `state`。对于第 $i$ 个数,若 `((state >> i) & 1)` 等于 $0$,说明第 $i$ 个元素未被划分。 + +我们的目标是从全部元素中凑出 $k$ 个和为 $s$ 的子集。记当前子集的和为 $t$。在未划分第 $i$ 个元素时: + +- 若 $t + nums[i] \gt s$,说明第 $i$ 个元素不能被添加到当前子集中,由于我们对 `nums` 数组进行升序排列,因此数组 `nums` 从位置 $i$ 开始的所有元素都不能被添加到当前子集,直接返回 `false`。 +- 否则,将第 $i$ 个元素添加到当前子集中,状态变为 `state | (1 << i)`,然后继续对未划分的元素进行搜索。需要注意的是,若 $t + nums[i] = s$,说明恰好可以得到一个和为 $s$ 的子集,下一步将 $t$ 归零(可以通过 `(t + nums[i]) % s` 实现),并继续划分下一个子集。 + +为了避免重复搜索,我们使用一个长度为 $2^n$ 的数组 `f` 记录每个状态下的搜索结果。数组 `f` 有三个可能的值: + +- `0`:表示当前状态还未搜索过; +- `-1`:表示当前状态下无法划分为 $k$ 个子集; +- `1`:表示当前状态下可以划分为 $k$ 个子集。 + +时间复杂度 $O(n\times 2^n)$,空间复杂度 $O(2^n)$。其中 $n$ 表示数组 $nums$ 的长度。对于每个状态,我们需要遍历数组 `nums`,时间复杂度为 $O(n)$;状态总数为 $2^n$,因此总的时间复杂度为 $O(n\times 2^n)$。 + + + +```python +class Solution: + def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: + @cache + def dfs(state, t): + if state == mask: + return True + for i, v in enumerate(nums): + if (state >> i) & 1: + continue + if t + v > s: + break + if dfs(state | 1 << i, (t + v) % s): + return True + return False + + s, mod = divmod(sum(nums), k) + if mod: + return False + nums.sort() + mask = (1 << len(nums)) - 1 + return dfs(0, 0) +``` + +```java +class Solution { + private int[] f; + private int[] nums; + private int n; + private int s; + + public boolean canPartitionKSubsets(int[] nums, int k) { + for (int v : nums) { + s += v; + } + if (s % k != 0) { + return false; + } + s /= k; + Arrays.sort(nums); + this.nums = nums; + n = nums.length; + f = new int[1 << n]; + return dfs(0, 0); + } + + private boolean dfs(int state, int t) { + if (state == (1 << n) - 1) { + return true; + } + if (f[state] != 0) { + return f[state] == 1; + } + for (int i = 0; i < n; ++i) { + if (((state >> i) & 1) == 1) { + continue; + } + if (t + nums[i] > s) { + break; + } + if (dfs(state | 1 << i, (t + nums[i]) % s)) { + f[state] = 1; + return true; + } + } + f[state] = -1; + return false; + } +} +``` + +```cpp +class Solution { +public: + bool canPartitionKSubsets(vector& nums, int k) { + int s = accumulate(nums.begin(), nums.end(), 0); + if (s % k) { + return false; + } + s /= k; + sort(nums.begin(), nums.end()); + int n = nums.size(); + int mask = (1 << n) - 1; + vector f(1 << n); + function dfs; + dfs = [&](int state, int t) { + if (state == mask) { + return true; + } + if (f[state]) { + return f[state] == 1; + } + for (int i = 0; i < n; ++i) { + if (state >> i & 1) { + continue; + } + if (t + nums[i] > s) { + break; + } + if (dfs(state | 1 << i, (t + nums[i]) % s)) { + f[state] = 1; + return true; + } + } + f[state] = -1; + return false; + }; + return dfs(0, 0); + } +}; +``` + +```go +func canPartitionKSubsets(nums []int, k int) bool { + s := 0 + for _, v := range nums { + s += v + } + if s%k != 0 { + return false + } + s /= k + n := len(nums) + f := make([]int, 1< + +### 方法三:动态规划 + +我们可以使用动态规划的方法求解本题。 + +我们定义 $f[i]$ 表示当前选取的数字的状态为 $i$ 时,是否存在 $k$ 个子集满足题目要求。初始时 $f[0]=true$,答案为 $f[2^n-1]$。其中 $n$ 表示数组 $nums$ 的长度。另外,我们定义 $cur[i]$ 表示当前选取的数字的状态为 $i$ 时,最后一个子集的和。 + +我们在 $[0,2^n)$ 的范围内枚举状态 $i$,对于每个状态 $i$,如果 $f[i]$ 为 `false`,我们直接跳过即可。否则,我们枚举 $nums$ 数组中的任意一个数 $nums[j]$,如果 $cur[i] + nums[j] \gt s$,我们直接跳出枚举循环,因为后面的数更大,无法放入当前子集;否则,如果 $i$ 的二进制表示的第 $j$ 位为 $0$,说明当前 $nums[j]$ 还没有被选取,我们可以将其放入当前子集中,此时状态变为 $i | 2^j$,并更新 $cur[i | 2^j] = (cur[i] + nums[j]) \bmod s$,并且 $f[i | 2^j] = true$。 + +最后,我们返回 $f[2^n-1]$ 即可。 + +时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(2^n)$。其中 $n$ 表示数组 $nums$ 的长度。 + + + +```python +class Solution: + def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: + s = sum(nums) + if s % k: + return False + s //= k + nums.sort() + n = len(nums) + f = [False] * (1 << n) + cur = [0] * (1 << n) + f[0] = True + for i in range(1 << n): + if not f[i]: + continue + for j in range(n): + if cur[i] + nums[j] > s: + break + if (i >> j & 1) == 0: + if not f[i | 1 << j]: + cur[i | 1 << j] = (cur[i] + nums[j]) % s + f[i | 1 << j] = True + return f[-1] +``` + +```java +class Solution { + public boolean canPartitionKSubsets(int[] nums, int k) { + int s = 0; + for (int x : nums) { + s += x; + } + if (s % k != 0) { + return false; + } + s /= k; + Arrays.sort(nums); + int n = nums.length; + boolean[] f = new boolean[1 << n]; + f[0] = true; + int[] cur = new int[1 << n]; + for (int i = 0; i < 1 << n; ++i) { + if (!f[i]) { + continue; + } + for (int j = 0; j < n; ++j) { + if (cur[i] + nums[j] > s) { + break; + } + if ((i >> j & 1) == 0) { + cur[i | 1 << j] = (cur[i] + nums[j]) % s; + f[i | 1 << j] = true; + } + } + } + return f[(1 << n) - 1]; + } +} +``` + +```cpp +class Solution { +public: + bool canPartitionKSubsets(vector& nums, int k) { + int s = accumulate(nums.begin(), nums.end(), 0); + if (s % k) { + return false; + } + s /= k; + sort(nums.begin(), nums.end()); + int n = nums.size(); + bool f[1 << n]; + int cur[1 << n]; + memset(f, false, sizeof(f)); + memset(cur, 0, sizeof(cur)); + f[0] = 1; + for (int i = 0; i < 1 << n; ++i) { + if (!f[i]) { + continue; + } + for (int j = 0; j < n; ++j) { + if (cur[i] + nums[j] > s) { + break; + } + if ((i >> j & 1) == 0) { + f[i | 1 << j] = true; + cur[i | 1 << j] = (cur[i] + nums[j]) % s; + } + } + } + return f[(1 << n) - 1]; + } +}; +``` + ```go func canPartitionKSubsets(nums []int, k int) bool { s := 0 @@ -507,42 +531,6 @@ func canPartitionKSubsets(nums []int, k int) bool { } ``` -### **TypeScript** - -```ts -function canPartitionKSubsets(nums: number[], k: number): boolean { - let s = nums.reduce((a, b) => a + b); - if (s % k !== 0) { - return false; - } - s /= k; - nums.sort((a, b) => a - b); - const n = nums.length; - const f: boolean[] = new Array(1 << n).fill(false); - f[0] = true; - const cur: number[] = new Array(n).fill(0); - for (let i = 0; i < 1 << n; ++i) { - if (!f[i]) { - continue; - } - for (let j = 0; j < n; ++j) { - if (cur[i] + nums[j] > s) { - break; - } - if (((i >> j) & 1) === 0) { - f[i | (1 << j)] = true; - cur[i | (1 << j)] = (cur[i] + nums[j]) % s; - } - } - } - return f[(1 << n) - 1]; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0698.Partition to K Equal Sum Subsets/README_EN.md b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/README_EN.md index e0bf2df7e087c..1399e2ffbca7d 100644 --- a/solution/0600-0699/0698.Partition to K Equal Sum Subsets/README_EN.md +++ b/solution/0600-0699/0698.Partition to K Equal Sum Subsets/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,57 +60,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: - @cache - def dfs(state, t): - if state == mask: - return True - for i, v in enumerate(nums): - if (state >> i) & 1: - continue - if t + v > s: - break - if dfs(state | 1 << i, (t + v) % s): - return True - return False - - s, mod = divmod(sum(nums), k) - if mod: - return False - nums.sort() - mask = (1 << len(nums)) - 1 - return dfs(0, 0) -``` - -```python -class Solution: - def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: - s = sum(nums) - if s % k: - return False - s //= k - nums.sort() - n = len(nums) - f = [False] * (1 << n) - cur = [0] * (1 << n) - f[0] = True - for i in range(1 << n): - if not f[i]: - continue - for j in range(n): - if cur[i] + nums[j] > s: - break - if (i >> j & 1) == 0: - if not f[i | 1 << j]: - cur[i | 1 << j] = (cur[i] + nums[j]) % s - f[i | 1 << j] = True - return f[-1] -``` - -### **Java** - ```java class Solution { private int[] nums; @@ -150,6 +99,136 @@ class Solution { } ``` +```cpp +class Solution { +public: + bool canPartitionKSubsets(vector& nums, int k) { + int s = accumulate(nums.begin(), nums.end(), 0); + if (s % k) { + return false; + } + s /= k; + int n = nums.size(); + vector cur(k); + function dfs; + dfs = [&](int i) { + if (i == n) { + return true; + } + for (int j = 0; j < k; ++j) { + if (j && cur[j] == cur[j - 1]) { + continue; + } + cur[j] += nums[i]; + if (cur[j] <= s && dfs(i + 1)) { + return true; + } + cur[j] -= nums[i]; + } + return false; + }; + sort(nums.begin(), nums.end(), greater()); + return dfs(0); + } +}; +``` + +```go +func canPartitionKSubsets(nums []int, k int) bool { + s := 0 + for _, v := range nums { + s += v + } + if s%k != 0 { + return false + } + s /= k + cur := make([]int, k) + n := len(nums) + + var dfs func(int) bool + dfs = func(i int) bool { + if i == n { + return true + } + for j := 0; j < k; j++ { + if j > 0 && cur[j] == cur[j-1] { + continue + } + cur[j] += nums[i] + if cur[j] <= s && dfs(i+1) { + return true + } + cur[j] -= nums[i] + } + return false + } + + sort.Sort(sort.Reverse(sort.IntSlice(nums))) + return dfs(0) +} +``` + +```ts +function canPartitionKSubsets(nums: number[], k: number): boolean { + let s = nums.reduce((a, b) => a + b); + if (s % k !== 0) { + return false; + } + s /= k; + nums.sort((a, b) => a - b); + const n = nums.length; + const f: boolean[] = new Array(1 << n).fill(false); + f[0] = true; + const cur: number[] = new Array(n).fill(0); + for (let i = 0; i < 1 << n; ++i) { + if (!f[i]) { + continue; + } + for (let j = 0; j < n; ++j) { + if (cur[i] + nums[j] > s) { + break; + } + if (((i >> j) & 1) === 0) { + f[i | (1 << j)] = true; + cur[i | (1 << j)] = (cur[i] + nums[j]) % s; + } + } + } + return f[(1 << n) - 1]; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: + @cache + def dfs(state, t): + if state == mask: + return True + for i, v in enumerate(nums): + if (state >> i) & 1: + continue + if t + v > s: + break + if dfs(state | 1 << i, (t + v) % s): + return True + return False + + s, mod = divmod(sum(nums), k) + if mod: + return False + nums.sort() + mask = (1 << len(nums)) - 1 + return dfs(0, 0) +``` + ```java class Solution { private int[] f; @@ -197,77 +276,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canPartitionKSubsets(int[] nums, int k) { - int s = 0; - for (int x : nums) { - s += x; - } - if (s % k != 0) { - return false; - } - s /= k; - Arrays.sort(nums); - int n = nums.length; - boolean[] f = new boolean[1 << n]; - f[0] = true; - int[] cur = new int[1 << n]; - for (int i = 0; i < 1 << n; ++i) { - if (!f[i]) { - continue; - } - for (int j = 0; j < n; ++j) { - if (cur[i] + nums[j] > s) { - break; - } - if ((i >> j & 1) == 0) { - cur[i | 1 << j] = (cur[i] + nums[j]) % s; - f[i | 1 << j] = true; - } - } - } - return f[(1 << n) - 1]; - } -} -``` - -### **C++** - -```cpp -class Solution { -public: - bool canPartitionKSubsets(vector& nums, int k) { - int s = accumulate(nums.begin(), nums.end(), 0); - if (s % k) { - return false; - } - s /= k; - int n = nums.size(); - vector cur(k); - function dfs; - dfs = [&](int i) { - if (i == n) { - return true; - } - for (int j = 0; j < k; ++j) { - if (j && cur[j] == cur[j - 1]) { - continue; - } - cur[j] += nums[i]; - if (cur[j] <= s && dfs(i + 1)) { - return true; - } - cur[j] -= nums[i]; - } - return false; - }; - sort(nums.begin(), nums.end(), greater()); - return dfs(0); - } -}; -``` - ```cpp class Solution { public: @@ -309,79 +317,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool canPartitionKSubsets(vector& nums, int k) { - int s = accumulate(nums.begin(), nums.end(), 0); - if (s % k) { - return false; - } - s /= k; - sort(nums.begin(), nums.end()); - int n = nums.size(); - bool f[1 << n]; - int cur[1 << n]; - memset(f, false, sizeof(f)); - memset(cur, 0, sizeof(cur)); - f[0] = 1; - for (int i = 0; i < 1 << n; ++i) { - if (!f[i]) { - continue; - } - for (int j = 0; j < n; ++j) { - if (cur[i] + nums[j] > s) { - break; - } - if ((i >> j & 1) == 0) { - f[i | 1 << j] = true; - cur[i | 1 << j] = (cur[i] + nums[j]) % s; - } - } - } - return f[(1 << n) - 1]; - } -}; -``` - -### **Go** - -```go -func canPartitionKSubsets(nums []int, k int) bool { - s := 0 - for _, v := range nums { - s += v - } - if s%k != 0 { - return false - } - s /= k - cur := make([]int, k) - n := len(nums) - - var dfs func(int) bool - dfs = func(i int) bool { - if i == n { - return true - } - for j := 0; j < k; j++ { - if j > 0 && cur[j] == cur[j-1] { - continue - } - cur[j] += nums[i] - if cur[j] <= s && dfs(i+1) { - return true - } - cur[j] -= nums[i] - } - return false - } - - sort.Sort(sort.Reverse(sort.IntSlice(nums))) - return dfs(0) -} -``` - ```go func canPartitionKSubsets(nums []int, k int) bool { s := 0 @@ -425,6 +360,107 @@ func canPartitionKSubsets(nums []int, k int) bool { } ``` + + +### Solution 3 + + + +```python +class Solution: + def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: + s = sum(nums) + if s % k: + return False + s //= k + nums.sort() + n = len(nums) + f = [False] * (1 << n) + cur = [0] * (1 << n) + f[0] = True + for i in range(1 << n): + if not f[i]: + continue + for j in range(n): + if cur[i] + nums[j] > s: + break + if (i >> j & 1) == 0: + if not f[i | 1 << j]: + cur[i | 1 << j] = (cur[i] + nums[j]) % s + f[i | 1 << j] = True + return f[-1] +``` + +```java +class Solution { + public boolean canPartitionKSubsets(int[] nums, int k) { + int s = 0; + for (int x : nums) { + s += x; + } + if (s % k != 0) { + return false; + } + s /= k; + Arrays.sort(nums); + int n = nums.length; + boolean[] f = new boolean[1 << n]; + f[0] = true; + int[] cur = new int[1 << n]; + for (int i = 0; i < 1 << n; ++i) { + if (!f[i]) { + continue; + } + for (int j = 0; j < n; ++j) { + if (cur[i] + nums[j] > s) { + break; + } + if ((i >> j & 1) == 0) { + cur[i | 1 << j] = (cur[i] + nums[j]) % s; + f[i | 1 << j] = true; + } + } + } + return f[(1 << n) - 1]; + } +} +``` + +```cpp +class Solution { +public: + bool canPartitionKSubsets(vector& nums, int k) { + int s = accumulate(nums.begin(), nums.end(), 0); + if (s % k) { + return false; + } + s /= k; + sort(nums.begin(), nums.end()); + int n = nums.size(); + bool f[1 << n]; + int cur[1 << n]; + memset(f, false, sizeof(f)); + memset(cur, 0, sizeof(cur)); + f[0] = 1; + for (int i = 0; i < 1 << n; ++i) { + if (!f[i]) { + continue; + } + for (int j = 0; j < n; ++j) { + if (cur[i] + nums[j] > s) { + break; + } + if ((i >> j & 1) == 0) { + f[i | 1 << j] = true; + cur[i | 1 << j] = (cur[i] + nums[j]) % s; + } + } + } + return f[(1 << n) - 1]; + } +}; +``` + ```go func canPartitionKSubsets(nums []int, k int) bool { s := 0 @@ -458,42 +494,6 @@ func canPartitionKSubsets(nums []int, k int) bool { } ``` -### **TypeScript** - -```ts -function canPartitionKSubsets(nums: number[], k: number): boolean { - let s = nums.reduce((a, b) => a + b); - if (s % k !== 0) { - return false; - } - s /= k; - nums.sort((a, b) => a - b); - const n = nums.length; - const f: boolean[] = new Array(1 << n).fill(false); - f[0] = true; - const cur: number[] = new Array(n).fill(0); - for (let i = 0; i < 1 << n; ++i) { - if (!f[i]) { - continue; - } - for (let j = 0; j < n; ++j) { - if (cur[i] + nums[j] > s) { - break; - } - if (((i >> j) & 1) === 0) { - f[i | (1 << j)] = true; - cur[i | (1 << j)] = (cur[i] + nums[j]) % s; - } - } - } - return f[(1 << n) - 1]; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0699.Falling Squares/README.md b/solution/0600-0699/0699.Falling Squares/README.md index 025776576f3c1..35d0d5d9fe1f2 100644 --- a/solution/0600-0699/0699.Falling Squares/README.md +++ b/solution/0600-0699/0699.Falling Squares/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:线段树** +### 方法一:线段树 线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 $log(width)$。更新某个元素的值,只需要更新 $log(width)$ 个区间,并且这些区间都包含在一个包含该元素的大区间内。区间修改时,需要使用**懒标记**保证效率。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Node: def __init__(self, l, r): @@ -155,10 +149,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Node { Node left; @@ -265,8 +255,6 @@ class Solution { } ``` -### **C++** - ```cpp class Node { public: @@ -364,8 +352,6 @@ public: }; ``` -### **Go** - ```go type node struct { left *node @@ -464,10 +450,6 @@ func fallingSquares(positions [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0600-0699/0699.Falling Squares/README_EN.md b/solution/0600-0699/0699.Falling Squares/README_EN.md index f5c3bf62d9f90..d4ee65830812f 100644 --- a/solution/0600-0699/0699.Falling Squares/README_EN.md +++ b/solution/0600-0699/0699.Falling Squares/README_EN.md @@ -50,12 +50,10 @@ Note that square 2 only brushes the right side of square 1, which does not count ## Solutions -Segment Tree. +### Solution 1 -### **Python3** - ```python class Node: def __init__(self, l, r): @@ -133,8 +131,6 @@ class Solution: return ans ``` -### **Java** - ```java class Node { Node left; @@ -241,8 +237,6 @@ class Solution { } ``` -### **C++** - ```cpp class Node { public: @@ -340,8 +334,6 @@ public: }; ``` -### **Go** - ```go type node struct { left *node @@ -440,10 +432,6 @@ func fallingSquares(positions [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0700.Search in a Binary Search Tree/README.md b/solution/0700-0799/0700.Search in a Binary Search Tree/README.md index daeb1340c0767..413cf1a635eb2 100644 --- a/solution/0700-0799/0700.Search in a Binary Search Tree/README.md +++ b/solution/0700-0799/0700.Search in a Binary Search Tree/README.md @@ -41,14 +41,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -67,10 +63,6 @@ class Solution: ) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -97,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -120,8 +110,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -142,10 +130,6 @@ func searchBST(root *TreeNode, val int) *TreeNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0700.Search in a Binary Search Tree/README_EN.md b/solution/0700-0799/0700.Search in a Binary Search Tree/README_EN.md index 78e6cd89461c3..fc299db2c7f68 100644 --- a/solution/0700-0799/0700.Search in a Binary Search Tree/README_EN.md +++ b/solution/0700-0799/0700.Search in a Binary Search Tree/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -57,8 +57,6 @@ class Solution: ) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -108,8 +104,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -130,10 +124,6 @@ func searchBST(root *TreeNode, val int) *TreeNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0701.Insert into a Binary Search Tree/README.md b/solution/0700-0799/0701.Insert into a Binary Search Tree/README.md index fafee03856e6d..59bd1535739e6 100644 --- a/solution/0700-0799/0701.Insert into a Binary Search Tree/README.md +++ b/solution/0700-0799/0701.Insert into a Binary Search Tree/README.md @@ -49,16 +49,10 @@ ## 解法 - - -DFS。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -80,10 +74,6 @@ class Solution: return dfs(root) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -167,10 +153,6 @@ func insertIntoBST(root *TreeNode, val int) *TreeNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0701.Insert into a Binary Search Tree/README_EN.md b/solution/0700-0799/0701.Insert into a Binary Search Tree/README_EN.md index d5d284a3c0d86..48e5f7fdba74c 100644 --- a/solution/0700-0799/0701.Insert into a Binary Search Tree/README_EN.md +++ b/solution/0700-0799/0701.Insert into a Binary Search Tree/README_EN.md @@ -45,12 +45,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -72,8 +70,6 @@ class Solution: return dfs(root) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -106,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -133,8 +127,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -157,10 +149,6 @@ func insertIntoBST(root *TreeNode, val int) *TreeNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0702.Search in a Sorted Array of Unknown Size/README.md b/solution/0700-0799/0702.Search in a Sorted Array of Unknown Size/README.md index 7e1042332505a..da4ad60469ef4 100644 --- a/solution/0700-0799/0702.Search in a Sorted Array of Unknown Size/README.md +++ b/solution/0700-0799/0702.Search in a Sorted Array of Unknown Size/README.md @@ -54,16 +54,10 @@ ## 解法 - - -二分法。 +### 方法一 -### **Python3** - - - ```python # """ # This is ArrayReader's API interface. @@ -90,10 +84,6 @@ class Solution: return left if reader.get(left) == target else -1 ``` -### **Java** - - - ```java /** * // This is ArrayReader's API interface. @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the ArrayReader's API interface. @@ -148,8 +136,6 @@ public: }; ``` -### **Go** - ```go /** * // This is the ArrayReader's API interface. @@ -177,10 +163,6 @@ func search(reader ArrayReader, target int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0702.Search in a Sorted Array of Unknown Size/README_EN.md b/solution/0700-0799/0702.Search in a Sorted Array of Unknown Size/README_EN.md index c2f073d0dc45c..5a037cf58ef78 100644 --- a/solution/0700-0799/0702.Search in a Sorted Array of Unknown Size/README_EN.md +++ b/solution/0700-0799/0702.Search in a Sorted Array of Unknown Size/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # """ @@ -77,8 +77,6 @@ class Solution: return left if reader.get(left) == target else -1 ``` -### **Java** - ```java /** * // This is ArrayReader's API interface. @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the ArrayReader's API interface. @@ -133,8 +129,6 @@ public: }; ``` -### **Go** - ```go /** * // This is the ArrayReader's API interface. @@ -162,10 +156,6 @@ func search(reader ArrayReader, target int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0703.Kth Largest Element in a Stream/README.md b/solution/0700-0799/0703.Kth Largest Element in a Stream/README.md index ce6a907e60b4d..c489922e539a8 100644 --- a/solution/0700-0799/0703.Kth Largest Element in a Stream/README.md +++ b/solution/0700-0799/0703.Kth Largest Element in a Stream/README.md @@ -49,16 +49,10 @@ kthLargest.add(4); // return 8 ## 解法 - - -小根堆存放最大的 k 个元素,那么堆顶就是第 k 大的元素。 +### 方法一 -### **Python3** - - - ```python class KthLargest: def __init__(self, k: int, nums: List[int]): @@ -79,10 +73,6 @@ class KthLargest: # param_1 = obj.add(val) ``` -### **Java** - - - ```java class KthLargest { private PriorityQueue q; @@ -112,8 +102,6 @@ class KthLargest { */ ``` -### **C++** - ```cpp class KthLargest { public: @@ -139,7 +127,81 @@ public: */ ``` -### **JavaScript** +```go +type KthLargest struct { + h *IntHeap + k int +} + +func Constructor(k int, nums []int) KthLargest { + h := &IntHeap{} + heap.Init(h) + for _, v := range nums { + heap.Push(h, v) + } + + for h.Len() > k { + heap.Pop(h) + } + + return KthLargest{ + h: h, + k: k, + } +} + +func (this *KthLargest) Add(val int) int { + heap.Push(this.h, val) + for this.h.Len() > this.k { + heap.Pop(this.h) + } + + return this.h.Top() +} + +func connectSticks(sticks []int) int { + h := IntHeap(sticks) + heap.Init(&h) + res := 0 + for h.Len() > 1 { + val := heap.Pop(&h).(int) + val += heap.Pop(&h).(int) + res += val + heap.Push(&h, val) + } + return res +} + +type IntHeap []int + +func (h IntHeap) Len() int { return len(h) } +func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } +func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *IntHeap) Push(x any) { + *h = append(*h, x.(int)) +} +func (h *IntHeap) Pop() any { + old := *h + n := len(old) + x := old[n-1] + *h = old[0 : n-1] + return x +} + +func (h *IntHeap) Top() int { + if (*h).Len() == 0 { + return 0 + } + + return (*h)[0] +} + +/** + * Your KthLargest object will be instantiated and called as such: + * obj := Constructor(k, nums); + * param_1 := obj.Add(val); + */ +``` ```js /** @@ -258,88 +320,6 @@ class MinHeap { */ ``` -### **Go** - -```go -type KthLargest struct { - h *IntHeap - k int -} - -func Constructor(k int, nums []int) KthLargest { - h := &IntHeap{} - heap.Init(h) - for _, v := range nums { - heap.Push(h, v) - } - - for h.Len() > k { - heap.Pop(h) - } - - return KthLargest{ - h: h, - k: k, - } -} - -func (this *KthLargest) Add(val int) int { - heap.Push(this.h, val) - for this.h.Len() > this.k { - heap.Pop(this.h) - } - - return this.h.Top() -} - -func connectSticks(sticks []int) int { - h := IntHeap(sticks) - heap.Init(&h) - res := 0 - for h.Len() > 1 { - val := heap.Pop(&h).(int) - val += heap.Pop(&h).(int) - res += val - heap.Push(&h, val) - } - return res -} - -type IntHeap []int - -func (h IntHeap) Len() int { return len(h) } -func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } -func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *IntHeap) Push(x any) { - *h = append(*h, x.(int)) -} -func (h *IntHeap) Pop() any { - old := *h - n := len(old) - x := old[n-1] - *h = old[0 : n-1] - return x -} - -func (h *IntHeap) Top() int { - if (*h).Len() == 0 { - return 0 - } - - return (*h)[0] -} - -/** - * Your KthLargest object will be instantiated and called as such: - * obj := Constructor(k, nums); - * param_1 := obj.Add(val); - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0703.Kth Largest Element in a Stream/README_EN.md b/solution/0700-0799/0703.Kth Largest Element in a Stream/README_EN.md index 90db54141153c..c5eddba8a182e 100644 --- a/solution/0700-0799/0703.Kth Largest Element in a Stream/README_EN.md +++ b/solution/0700-0799/0703.Kth Largest Element in a Stream/README_EN.md @@ -46,9 +46,9 @@ kthLargest.add(4); // return 8 ## Solutions - +### Solution 1 -### **Python3** + ```python class KthLargest: @@ -70,8 +70,6 @@ class KthLargest: # param_1 = obj.add(val) ``` -### **Java** - ```java class KthLargest { private PriorityQueue q; @@ -101,7 +99,106 @@ class KthLargest { */ ``` -### **JavaScript** +```cpp +class KthLargest { +public: + priority_queue, greater> q; + int size; + + KthLargest(int k, vector& nums) { + size = k; + for (int num : nums) add(num); + } + + int add(int val) { + q.push(val); + if (q.size() > size) q.pop(); + return q.top(); + } +}; + +/** + * Your KthLargest object will be instantiated and called as such: + * KthLargest* obj = new KthLargest(k, nums); + * int param_1 = obj->add(val); + */ +``` + +```go +type KthLargest struct { + h *IntHeap + k int +} + +func Constructor(k int, nums []int) KthLargest { + h := &IntHeap{} + heap.Init(h) + for _, v := range nums { + heap.Push(h, v) + } + + for h.Len() > k { + heap.Pop(h) + } + + return KthLargest{ + h: h, + k: k, + } +} + +func (this *KthLargest) Add(val int) int { + heap.Push(this.h, val) + for this.h.Len() > this.k { + heap.Pop(this.h) + } + + return this.h.Top() +} + +func connectSticks(sticks []int) int { + h := IntHeap(sticks) + heap.Init(&h) + res := 0 + for h.Len() > 1 { + val := heap.Pop(&h).(int) + val += heap.Pop(&h).(int) + res += val + heap.Push(&h, val) + } + return res +} + +type IntHeap []int + +func (h IntHeap) Len() int { return len(h) } +func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } +func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *IntHeap) Push(x any) { + *h = append(*h, x.(int)) +} +func (h *IntHeap) Pop() any { + old := *h + n := len(old) + x := old[n-1] + *h = old[0 : n-1] + return x +} + +func (h *IntHeap) Top() int { + if (*h).Len() == 0 { + return 0 + } + + return (*h)[0] +} + +/** + * Your KthLargest object will be instantiated and called as such: + * obj := Constructor(k, nums); + * param_1 := obj.Add(val); + */ +``` ```js /** @@ -220,115 +317,6 @@ class MinHeap { */ ``` -### **C++** - -```cpp -class KthLargest { -public: - priority_queue, greater> q; - int size; - - KthLargest(int k, vector& nums) { - size = k; - for (int num : nums) add(num); - } - - int add(int val) { - q.push(val); - if (q.size() > size) q.pop(); - return q.top(); - } -}; - -/** - * Your KthLargest object will be instantiated and called as such: - * KthLargest* obj = new KthLargest(k, nums); - * int param_1 = obj->add(val); - */ -``` - -### **Go** - -```go -type KthLargest struct { - h *IntHeap - k int -} - -func Constructor(k int, nums []int) KthLargest { - h := &IntHeap{} - heap.Init(h) - for _, v := range nums { - heap.Push(h, v) - } - - for h.Len() > k { - heap.Pop(h) - } - - return KthLargest{ - h: h, - k: k, - } -} - -func (this *KthLargest) Add(val int) int { - heap.Push(this.h, val) - for this.h.Len() > this.k { - heap.Pop(this.h) - } - - return this.h.Top() -} - -func connectSticks(sticks []int) int { - h := IntHeap(sticks) - heap.Init(&h) - res := 0 - for h.Len() > 1 { - val := heap.Pop(&h).(int) - val += heap.Pop(&h).(int) - res += val - heap.Push(&h, val) - } - return res -} - -type IntHeap []int - -func (h IntHeap) Len() int { return len(h) } -func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } -func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *IntHeap) Push(x any) { - *h = append(*h, x.(int)) -} -func (h *IntHeap) Pop() any { - old := *h - n := len(old) - x := old[n-1] - *h = old[0 : n-1] - return x -} - -func (h *IntHeap) Top() int { - if (*h).Len() == 0 { - return 0 - } - - return (*h)[0] -} - -/** - * Your KthLargest object will be instantiated and called as such: - * obj := Constructor(k, nums); - * param_1 := obj.Add(val); - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0704.Binary Search/README.md b/solution/0700-0799/0704.Binary Search/README.md index 7e190c209aa4f..52c576259b13b 100644 --- a/solution/0700-0799/0704.Binary Search/README.md +++ b/solution/0700-0799/0704.Binary Search/README.md @@ -35,14 +35,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def search(self, nums: List[int], target: int) -> int: @@ -56,10 +52,6 @@ class Solution: return left if nums[left] == target else -1 ``` -### **Java** - - - ```java class Solution { public int search(int[] nums, int target) { @@ -77,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +86,6 @@ public: }; ``` -### **Go** - ```go func search(nums []int, target int) int { left, right := 0, len(nums)-1 @@ -116,33 +104,6 @@ func search(nums []int, target int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} target - * @return {number} - */ -var search = function (nums, target) { - let left = 0; - let right = nums.length - 1; - while (left < right) { - const mid = (left + right) >> 1; - if (nums[mid] >= target) { - right = mid; - } else { - left = mid + 1; - } - } - return nums[left] == target ? left : -1; -}; -``` - -### **Rust** - -循环: - ```rust use std::cmp::Ordering; @@ -169,7 +130,32 @@ impl Solution { } ``` -递归: +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function (nums, target) { + let left = 0; + let right = nums.length - 1; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return nums[left] == target ? left : -1; +}; +``` + + + +### 方法二 + + ```rust use std::cmp::Ordering; @@ -194,10 +180,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0704.Binary Search/README_EN.md b/solution/0700-0799/0704.Binary Search/README_EN.md index 0ccc59e5717fd..a6ecd23cd73ee 100644 --- a/solution/0700-0799/0704.Binary Search/README_EN.md +++ b/solution/0700-0799/0704.Binary Search/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return left if nums[left] == target else -1 ``` -### **Java** - ```java class Solution { public int search(int[] nums, int target) { @@ -73,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -92,8 +88,6 @@ public: }; ``` -### **Go** - ```go func search(nums []int, target int) int { left, right := 0, len(nums)-1 @@ -112,33 +106,6 @@ func search(nums []int, target int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} target - * @return {number} - */ -var search = function (nums, target) { - let left = 0; - let right = nums.length - 1; - while (left < right) { - const mid = (left + right) >> 1; - if (nums[mid] >= target) { - right = mid; - } else { - left = mid + 1; - } - } - return nums[left] == target ? left : -1; -}; -``` - -### **Rust** - -Cycle: - ```rust use std::cmp::Ordering; @@ -165,7 +132,32 @@ impl Solution { } ``` -Recursion: +```js +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function (nums, target) { + let left = 0; + let right = nums.length - 1; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return nums[left] == target ? left : -1; +}; +``` + + + +### Solution 2 + + ```rust use std::cmp::Ordering; @@ -190,10 +182,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0705.Design HashSet/README.md b/solution/0700-0799/0705.Design HashSet/README.md index c9341bd9e9435..3713ca5b7c358 100644 --- a/solution/0700-0799/0705.Design HashSet/README.md +++ b/solution/0700-0799/0705.Design HashSet/README.md @@ -48,9 +48,7 @@ myHashSet.contains(2); // 返回 False ,(已移除) ## 解法 - - -**方法一:静态数组实现** +### 方法一:静态数组实现 直接创建一个大小为 $1000001$ 的数组,初始时数组中的每个元素都为 `false`,表示哈希集合中不存在该元素。 @@ -58,16 +56,8 @@ myHashSet.contains(2); // 返回 False ,(已移除) 以上操作的时间复杂度均为 $O(1)$。 -**方法二:数组嵌套链表** - -我们也可以开辟一个大小为 `SIZE=1000` 的数组,数组的每个位置是一个链表。 - -### **Python3** - - - ```python class MyHashSet: def __init__(self): @@ -90,6 +80,134 @@ class MyHashSet: # param_3 = obj.contains(key) ``` +```java +class MyHashSet { + private boolean[] data = new boolean[1000001]; + + public MyHashSet() { + } + + public void add(int key) { + data[key] = true; + } + + public void remove(int key) { + data[key] = false; + } + + public boolean contains(int key) { + return data[key]; + } +} + +/** + * Your MyHashSet object will be instantiated and called as such: + * MyHashSet obj = new MyHashSet(); + * obj.add(key); + * obj.remove(key); + * boolean param_3 = obj.contains(key); + */ +``` + +```cpp +class MyHashSet { +public: + bool data[1000001]; + + MyHashSet() { + memset(data, false, sizeof data); + } + + void add(int key) { + data[key] = true; + } + + void remove(int key) { + data[key] = false; + } + + bool contains(int key) { + return data[key]; + } +}; + +/** + * Your MyHashSet object will be instantiated and called as such: + * MyHashSet* obj = new MyHashSet(); + * obj->add(key); + * obj->remove(key); + * bool param_3 = obj->contains(key); + */ +``` + +```go +type MyHashSet struct { + data []bool +} + +func Constructor() MyHashSet { + data := make([]bool, 1000010) + return MyHashSet{data} +} + +func (this *MyHashSet) Add(key int) { + this.data[key] = true +} + +func (this *MyHashSet) Remove(key int) { + this.data[key] = false +} + +func (this *MyHashSet) Contains(key int) bool { + return this.data[key] +} + +/** + * Your MyHashSet object will be instantiated and called as such: + * obj := Constructor(); + * obj.Add(key); + * obj.Remove(key); + * param_3 := obj.Contains(key); + */ +``` + +```ts +class MyHashSet { + data: Array; + constructor() { + this.data = new Array(10 ** 6 + 1).fill(false); + } + + add(key: number): void { + this.data[key] = true; + } + + remove(key: number): void { + this.data[key] = false; + } + + contains(key: number): boolean { + return this.data[key]; + } +} + +/** + * Your MyHashSet object will be instantiated and called as such: + * var obj = new MyHashSet() + * obj.add(key) + * obj.remove(key) + * var param_3 = obj.contains(key) + */ +``` + + + +### 方法二:数组嵌套链表 + +我们也可以开辟一个大小为 `SIZE=1000` 的数组,数组的每个位置是一个链表。 + + + ```python class MyHashSet: def __init__(self): @@ -123,39 +241,6 @@ class MyHashSet: # param_3 = obj.contains(key) ``` -### **Java** - - - -```java -class MyHashSet { - private boolean[] data = new boolean[1000001]; - - public MyHashSet() { - } - - public void add(int key) { - data[key] = true; - } - - public void remove(int key) { - data[key] = false; - } - - public boolean contains(int key) { - return data[key]; - } -} - -/** - * Your MyHashSet object will be instantiated and called as such: - * MyHashSet obj = new MyHashSet(); - * obj.add(key); - * obj.remove(key); - * boolean param_3 = obj.contains(key); - */ -``` - ```java class MyHashSet { private static final int SIZE = 1000; @@ -210,39 +295,6 @@ class MyHashSet { */ ``` -### **C++** - -```cpp -class MyHashSet { -public: - bool data[1000001]; - - MyHashSet() { - memset(data, false, sizeof data); - } - - void add(int key) { - data[key] = true; - } - - void remove(int key) { - data[key] = false; - } - - bool contains(int key) { - return data[key]; - } -}; - -/** - * Your MyHashSet object will be instantiated and called as such: - * MyHashSet* obj = new MyHashSet(); - * obj->add(key); - * obj->remove(key); - * bool param_3 = obj->contains(key); - */ -``` - ```cpp class MyHashSet { private: @@ -294,39 +346,6 @@ public: */ ``` -### **Go** - -```go -type MyHashSet struct { - data []bool -} - -func Constructor() MyHashSet { - data := make([]bool, 1000010) - return MyHashSet{data} -} - -func (this *MyHashSet) Add(key int) { - this.data[key] = true -} - -func (this *MyHashSet) Remove(key int) { - this.data[key] = false -} - -func (this *MyHashSet) Contains(key int) bool { - return this.data[key] -} - -/** - * Your MyHashSet object will be instantiated and called as such: - * obj := Constructor(); - * obj.Add(key); - * obj.Remove(key); - * param_3 := obj.Contains(key); - */ -``` - ```go type MyHashSet struct { data []list.List @@ -376,41 +395,6 @@ func (this *MyHashSet) hash(key int) int { */ ``` -### **TypeScript** - -```ts -class MyHashSet { - data: Array; - constructor() { - this.data = new Array(10 ** 6 + 1).fill(false); - } - - add(key: number): void { - this.data[key] = true; - } - - remove(key: number): void { - this.data[key] = false; - } - - contains(key: number): boolean { - return this.data[key]; - } -} - -/** - * Your MyHashSet object will be instantiated and called as such: - * var obj = new MyHashSet() - * obj.add(key) - * obj.remove(key) - * var param_3 = obj.contains(key) - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0705.Design HashSet/README_EN.md b/solution/0700-0799/0705.Design HashSet/README_EN.md index 9284fab5b5661..ad8f079a0b953 100644 --- a/solution/0700-0799/0705.Design HashSet/README_EN.md +++ b/solution/0700-0799/0705.Design HashSet/README_EN.md @@ -45,9 +45,9 @@ myHashSet.contains(2); // return False, (already removed) ## Solutions - +### Solution 1 -### **Python3** + ```python class MyHashSet: @@ -71,6 +71,132 @@ class MyHashSet: # param_3 = obj.contains(key) ``` +```java +class MyHashSet { + private boolean[] data = new boolean[1000001]; + + public MyHashSet() { + } + + public void add(int key) { + data[key] = true; + } + + public void remove(int key) { + data[key] = false; + } + + public boolean contains(int key) { + return data[key]; + } +} + +/** + * Your MyHashSet object will be instantiated and called as such: + * MyHashSet obj = new MyHashSet(); + * obj.add(key); + * obj.remove(key); + * boolean param_3 = obj.contains(key); + */ +``` + +```cpp +class MyHashSet { +public: + bool data[1000001]; + + MyHashSet() { + memset(data, false, sizeof data); + } + + void add(int key) { + data[key] = true; + } + + void remove(int key) { + data[key] = false; + } + + bool contains(int key) { + return data[key]; + } +}; + +/** + * Your MyHashSet object will be instantiated and called as such: + * MyHashSet* obj = new MyHashSet(); + * obj->add(key); + * obj->remove(key); + * bool param_3 = obj->contains(key); + */ +``` + +```go +type MyHashSet struct { + data []bool +} + +func Constructor() MyHashSet { + data := make([]bool, 1000010) + return MyHashSet{data} +} + +func (this *MyHashSet) Add(key int) { + this.data[key] = true +} + +func (this *MyHashSet) Remove(key int) { + this.data[key] = false +} + +func (this *MyHashSet) Contains(key int) bool { + return this.data[key] +} + +/** + * Your MyHashSet object will be instantiated and called as such: + * obj := Constructor(); + * obj.Add(key); + * obj.Remove(key); + * param_3 := obj.Contains(key); + */ +``` + +```ts +class MyHashSet { + data: Array; + constructor() { + this.data = new Array(10 ** 6 + 1).fill(false); + } + + add(key: number): void { + this.data[key] = true; + } + + remove(key: number): void { + this.data[key] = false; + } + + contains(key: number): boolean { + return this.data[key]; + } +} + +/** + * Your MyHashSet object will be instantiated and called as such: + * var obj = new MyHashSet() + * obj.add(key) + * obj.remove(key) + * var param_3 = obj.contains(key) + */ +``` + + + +### Solution 2 + + + ```python class MyHashSet: def __init__(self): @@ -104,37 +230,6 @@ class MyHashSet: # param_3 = obj.contains(key) ``` -### **Java** - -```java -class MyHashSet { - private boolean[] data = new boolean[1000001]; - - public MyHashSet() { - } - - public void add(int key) { - data[key] = true; - } - - public void remove(int key) { - data[key] = false; - } - - public boolean contains(int key) { - return data[key]; - } -} - -/** - * Your MyHashSet object will be instantiated and called as such: - * MyHashSet obj = new MyHashSet(); - * obj.add(key); - * obj.remove(key); - * boolean param_3 = obj.contains(key); - */ -``` - ```java class MyHashSet { private static final int SIZE = 1000; @@ -189,39 +284,6 @@ class MyHashSet { */ ``` -### **C++** - -```cpp -class MyHashSet { -public: - bool data[1000001]; - - MyHashSet() { - memset(data, false, sizeof data); - } - - void add(int key) { - data[key] = true; - } - - void remove(int key) { - data[key] = false; - } - - bool contains(int key) { - return data[key]; - } -}; - -/** - * Your MyHashSet object will be instantiated and called as such: - * MyHashSet* obj = new MyHashSet(); - * obj->add(key); - * obj->remove(key); - * bool param_3 = obj->contains(key); - */ -``` - ```cpp class MyHashSet { private: @@ -273,39 +335,6 @@ public: */ ``` -### **Go** - -```go -type MyHashSet struct { - data []bool -} - -func Constructor() MyHashSet { - data := make([]bool, 1000010) - return MyHashSet{data} -} - -func (this *MyHashSet) Add(key int) { - this.data[key] = true -} - -func (this *MyHashSet) Remove(key int) { - this.data[key] = false -} - -func (this *MyHashSet) Contains(key int) bool { - return this.data[key] -} - -/** - * Your MyHashSet object will be instantiated and called as such: - * obj := Constructor(); - * obj.Add(key); - * obj.Remove(key); - * param_3 := obj.Contains(key); - */ -``` - ```go type MyHashSet struct { data []list.List @@ -355,41 +384,6 @@ func (this *MyHashSet) hash(key int) int { */ ``` -### **TypeScript** - -```ts -class MyHashSet { - data: Array; - constructor() { - this.data = new Array(10 ** 6 + 1).fill(false); - } - - add(key: number): void { - this.data[key] = true; - } - - remove(key: number): void { - this.data[key] = false; - } - - contains(key: number): boolean { - return this.data[key]; - } -} - -/** - * Your MyHashSet object will be instantiated and called as such: - * var obj = new MyHashSet() - * obj.add(key) - * obj.remove(key) - * var param_3 = obj.contains(key) - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0706.Design HashMap/README.md b/solution/0700-0799/0706.Design HashMap/README.md index b4942cbec3393..0cb466dc82a6b 100644 --- a/solution/0700-0799/0706.Design HashMap/README.md +++ b/solution/0700-0799/0706.Design HashMap/README.md @@ -51,9 +51,7 @@ myHashMap.get(2); // 返回 -1(未找到),myHashMap 现在为 [[1,1]] ## 解法 - - -**方法一:静态数组实现** +### 方法一:静态数组实现 直接创建一个大小为 $1000001$ 的数组,初始时数组中的每个元素都为 $-1$,表示哈希表中不存在该键值对。 @@ -63,10 +61,6 @@ myHashMap.get(2); // 返回 -1(未找到),myHashMap 现在为 [[1,1]] -### **Python3** - - - ```python class MyHashMap: def __init__(self): @@ -89,10 +83,6 @@ class MyHashMap: # obj.remove(key) ``` -### **Java** - - - ```java class MyHashMap { private int[] data = new int[1000001]; @@ -123,39 +113,6 @@ class MyHashMap { */ ``` -### **TypeScript** - -```ts -class MyHashMap { - data: Array; - constructor() { - this.data = new Array(10 ** 6 + 1).fill(-1); - } - - put(key: number, value: number): void { - this.data[key] = value; - } - - get(key: number): number { - return this.data[key]; - } - - remove(key: number): void { - this.data[key] = -1; - } -} - -/** - * Your MyHashMap object will be instantiated and called as such: - * var obj = new MyHashMap() - * obj.put(key,value) - * var param_2 = obj.get(key) - * obj.remove(key) - */ -``` - -### **C++** - ```cpp class MyHashMap { public: @@ -187,8 +144,6 @@ public: */ ``` -### **Go** - ```go type MyHashMap struct { data []int @@ -223,4 +178,35 @@ func (this *MyHashMap) Remove(key int) { */ ``` +```ts +class MyHashMap { + data: Array; + constructor() { + this.data = new Array(10 ** 6 + 1).fill(-1); + } + + put(key: number, value: number): void { + this.data[key] = value; + } + + get(key: number): number { + return this.data[key]; + } + + remove(key: number): void { + this.data[key] = -1; + } +} + +/** + * Your MyHashMap object will be instantiated and called as such: + * var obj = new MyHashMap() + * obj.put(key,value) + * var param_2 = obj.get(key) + * obj.remove(key) + */ +``` + + + diff --git a/solution/0700-0799/0706.Design HashMap/README_EN.md b/solution/0700-0799/0706.Design HashMap/README_EN.md index 46e19395b6910..b207863d010ac 100644 --- a/solution/0700-0799/0706.Design HashMap/README_EN.md +++ b/solution/0700-0799/0706.Design HashMap/README_EN.md @@ -47,9 +47,9 @@ myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]] ## Solutions - +### Solution 1 -### **Python3** + ```python class MyHashMap: @@ -73,8 +73,6 @@ class MyHashMap: # obj.remove(key) ``` -### **Java** - ```java class MyHashMap { private int[] data = new int[1000001]; @@ -105,39 +103,6 @@ class MyHashMap { */ ``` -### **TypeScript** - -```ts -class MyHashMap { - data: Array; - constructor() { - this.data = new Array(10 ** 6 + 1).fill(-1); - } - - put(key: number, value: number): void { - this.data[key] = value; - } - - get(key: number): number { - return this.data[key]; - } - - remove(key: number): void { - this.data[key] = -1; - } -} - -/** - * Your MyHashMap object will be instantiated and called as such: - * var obj = new MyHashMap() - * obj.put(key,value) - * var param_2 = obj.get(key) - * obj.remove(key) - */ -``` - -### **C++** - ```cpp class MyHashMap { public: @@ -169,8 +134,6 @@ public: */ ``` -### **Go** - ```go type MyHashMap struct { data []int @@ -205,4 +168,35 @@ func (this *MyHashMap) Remove(key int) { */ ``` +```ts +class MyHashMap { + data: Array; + constructor() { + this.data = new Array(10 ** 6 + 1).fill(-1); + } + + put(key: number, value: number): void { + this.data[key] = value; + } + + get(key: number): number { + return this.data[key]; + } + + remove(key: number): void { + this.data[key] = -1; + } +} + +/** + * Your MyHashMap object will be instantiated and called as such: + * var obj = new MyHashMap() + * obj.put(key,value) + * var param_2 = obj.get(key) + * obj.remove(key) + */ +``` + + + diff --git a/solution/0700-0799/0707.Design Linked List/README.md b/solution/0700-0799/0707.Design Linked List/README.md index b49378dc65629..1489cfbd0173d 100644 --- a/solution/0700-0799/0707.Design Linked List/README.md +++ b/solution/0700-0799/0707.Design Linked List/README.md @@ -56,9 +56,7 @@ myLinkedList.get(1); // 返回 3 ## 解法 - - -**方法一:指针引用实现单链表** +### 方法一:指针引用实现单链表 我们创建链表虚拟头节点 `dummy`,用变量 `cnt` 记录当前链表节点个数。 @@ -74,28 +72,8 @@ myLinkedList.get(1); // 返回 3 注意:LeetCode 平台已经内置 ListNode 单链表节点类,可以直接使用。 -**方法二:静态数组实现单链表** - -在方法一中,我们使用了指针引用的方式,每次动态创建一个链表节点。在链表节点数量达到 $10^5$ 甚至更大时,频繁执行 new 操作,会大大增加程序的执行耗时。 - -因此,我们可以使用静态数组来实现单链表,预先申请一块大小略大于数据范围的内存空间,每次插入节点时,从数组中取出一个空闲的位置,将新节点插入到该位置,同时更新该位置的前驱和后继节点的指针引用。 - -我们定义以下几个变量,其中: - -- `head` 存放链表头节点的索引,初始时指向 $-1$。 -- `e` 存放链表所有节点的值(预先申请)。 -- `ne` 存放链表所有节点的 `next` 指针(预先申请)。 -- `idx` 指向当前可分配的节点索引,初始时指向索引 $0$。 -- `cnt` 记录当前链表节点个数,初始时为 $0$。 - -具体操作可参考以下代码。时间复杂度与方法一相同。 - -### **Python3** - - - ```python class MyLinkedList: def __init__(self): @@ -146,74 +124,6 @@ class MyLinkedList: # obj.deleteAtIndex(index) ``` -```python -class MyLinkedList: - def __init__(self): - self.e = [0] * 1010 - self.ne = [0] * 1010 - self.idx = 0 - self.head = -1 - self.cnt = 0 - - def get(self, index: int) -> int: - if index < 0 or index >= self.cnt: - return -1 - i = self.head - for _ in range(index): - i = self.ne[i] - return self.e[i] - - def addAtHead(self, val: int) -> None: - self.e[self.idx] = val - self.ne[self.idx] = self.head - self.head = self.idx - self.idx += 1 - self.cnt += 1 - - def addAtTail(self, val: int) -> None: - self.addAtIndex(self.cnt, val) - - def addAtIndex(self, index: int, val: int) -> None: - if index > self.cnt: - return - if index <= 0: - self.addAtHead(val) - return - i = self.head - for _ in range(index - 1): - i = self.ne[i] - self.e[self.idx] = val - self.ne[self.idx] = self.ne[i] - self.ne[i] = self.idx - self.idx += 1 - self.cnt += 1 - - def deleteAtIndex(self, index: int) -> None: - if index < 0 or index >= self.cnt: - return -1 - self.cnt -= 1 - if index == 0: - self.head = self.ne[self.head] - return - i = self.head - for _ in range(index - 1): - i = self.ne[i] - self.ne[i] = self.ne[self.ne[i]] - - -# Your MyLinkedList object will be instantiated and called as such: -# obj = MyLinkedList() -# param_1 = obj.get(index) -# obj.addAtHead(val) -# obj.addAtTail(val) -# obj.addAtIndex(index,val) -# obj.deleteAtIndex(index) -``` - -### **Java** - - - ```java class MyLinkedList { private ListNode dummy = new ListNode(); @@ -279,87 +189,6 @@ class MyLinkedList { */ ``` -```java -class MyLinkedList { - private int[] e = new int[1010]; - private int[] ne = new int[1010]; - private int head = -1; - private int idx; - private int cnt; - - public MyLinkedList() { - } - - public int get(int index) { - if (index < 0 || index >= cnt) { - return -1; - } - int i = head; - while (index-- > 0) { - i = ne[i]; - } - return e[i]; - } - - public void addAtHead(int val) { - e[idx] = val; - ne[idx] = head; - head = idx++; - ++cnt; - } - - public void addAtTail(int val) { - addAtIndex(cnt, val); - } - - public void addAtIndex(int index, int val) { - if (index > cnt) { - return; - } - if (index <= 0) { - addAtHead(val); - return; - } - int i = head; - while (--index > 0) { - i = ne[i]; - } - e[idx] = val; - ne[idx] = ne[i]; - ne[i] = idx++; - ++cnt; - } - - public void deleteAtIndex(int index) { - if (index < 0 || index >= cnt) { - return; - } - --cnt; - if (index == 0) { - head = ne[head]; - return; - } - int i = head; - while (--index > 0) { - i = ne[i]; - } - ne[i] = ne[ne[i]]; - } -} - -/** - * Your MyLinkedList object will be instantiated and called as such: - * MyLinkedList obj = new MyLinkedList(); - * int param_1 = obj.get(index); - * obj.addAtHead(val); - * obj.addAtTail(val); - * obj.addAtIndex(index,val); - * obj.deleteAtIndex(index); - */ -``` - -### **C++** - ```cpp class MyLinkedList { private: @@ -427,86 +256,6 @@ public: */ ``` -```cpp -class MyLinkedList { -private: - int e[1010], ne[1010]; - int head = -1, idx = 0, cnt = 0; - -public: - MyLinkedList() { - } - - int get(int index) { - if (index < 0 || index >= cnt) { - return -1; - } - int i = head; - while (index--) { - i = ne[i]; - } - return e[i]; - } - - void addAtHead(int val) { - e[idx] = val; - ne[idx] = head; - head = idx++; - ++cnt; - } - - void addAtTail(int val) { - addAtIndex(cnt, val); - } - - void addAtIndex(int index, int val) { - if (index > cnt) { - return; - } - if (index <= 0) { - addAtHead(val); - return; - } - int i = head; - while (--index) { - i = ne[i]; - } - e[idx] = val; - ne[idx] = ne[i]; - ne[i] = idx++; - ++cnt; - } - - void deleteAtIndex(int index) { - if (index < 0 || index >= cnt) { - return; - } - --cnt; - if (index == 0) { - head = ne[head]; - return; - } - int i = head; - while (--index) { - i = ne[i]; - } - ne[i] = ne[ne[i]]; - } -}; - -/** - * Your MyLinkedList object will be instantiated and called as such: - * MyLinkedList* obj = new MyLinkedList(); - * int param_1 = obj->get(index); - * obj->addAtHead(val); - * obj->addAtTail(val); - * obj->addAtIndex(index,val); - * obj->deleteAtIndex(index); - */ -``` - -### **Go** - ```go type MyLinkedList struct { dummy *ListNode @@ -573,96 +322,10 @@ func (this *MyLinkedList) DeleteAtIndex(index int) { */ ``` -```go -type MyLinkedList struct { - e []int - ne []int - idx int - head int - cnt int -} - -func Constructor() MyLinkedList { - e := make([]int, 1010) - ne := make([]int, 1010) - return MyLinkedList{e, ne, 0, -1, 0} -} - -func (this *MyLinkedList) Get(index int) int { - if index < 0 || index >= this.cnt { - return -1 - } - i := this.head - for ; index > 0; index-- { - i = this.ne[i] - } - return this.e[i] -} - -func (this *MyLinkedList) AddAtHead(val int) { - this.e[this.idx] = val - this.ne[this.idx] = this.head - this.head = this.idx - this.idx++ - this.cnt++ -} - -func (this *MyLinkedList) AddAtTail(val int) { - this.AddAtIndex(this.cnt, val) -} - -func (this *MyLinkedList) AddAtIndex(index int, val int) { - if index > this.cnt { - return - } - if index <= 0 { - this.AddAtHead(val) - return - } - i := this.head - for ; index > 1; index-- { - i = this.ne[i] - } - this.e[this.idx] = val - this.ne[this.idx] = this.ne[i] - this.ne[i] = this.idx - this.idx++ - this.cnt++ -} - -func (this *MyLinkedList) DeleteAtIndex(index int) { - if index < 0 || index >= this.cnt { - return - } - this.cnt-- - if index == 0 { - this.head = this.ne[this.head] - return - } - i := this.head - for ; index > 1; index-- { - i = this.ne[i] - } - this.ne[i] = this.ne[this.ne[i]] -} - -/** - * Your MyLinkedList object will be instantiated and called as such: - * obj := Constructor(); - * param_1 := obj.Get(index); - * obj.AddAtHead(val); - * obj.AddAtTail(val); - * obj.AddAtIndex(index,val); - * obj.DeleteAtIndex(index); - */ -``` - -### **TypeScript** - -```ts -class LinkNode { - public val: number; - public next: LinkNode; +```ts +class LinkNode { + public val: number; + public next: LinkNode; constructor(val: number, next: LinkNode = null) { this.val = val; @@ -757,92 +420,6 @@ class MyLinkedList { */ ``` -```ts -class MyLinkedList { - e: Array; - ne: Array; - idx: number; - head: number; - cnt: number; - - constructor() { - this.e = new Array(1010).fill(0); - this.ne = new Array(1010).fill(0); - this.head = -1; - this.idx = 0; - this.cnt = 0; - } - - get(index: number): number { - if (index < 0 || index >= this.cnt) { - return -1; - } - let i = this.head; - while (index--) { - i = this.ne[i]; - } - return this.e[i]; - } - - addAtHead(val: number): void { - this.e[this.idx] = val; - this.ne[this.idx] = this.head; - this.head = this.idx++; - this.cnt++; - } - - addAtTail(val: number): void { - this.addAtIndex(this.cnt, val); - } - - addAtIndex(index: number, val: number): void { - if (index > this.cnt) { - return; - } - if (index <= 0) { - this.addAtHead(val); - return; - } - let i = this.head; - while (--index) { - i = this.ne[i]; - } - this.e[this.idx] = val; - this.ne[this.idx] = this.ne[i]; - this.ne[i] = this.idx++; - this.cnt++; - } - - deleteAtIndex(index: number): void { - if (index < 0 || index >= this.cnt) { - return; - } - this.cnt--; - if (index == 0) { - this.head = this.ne[this.head]; - return; - } - let i = this.head; - while (--index) { - i = this.ne[i]; - } - this.ne[i] = this.ne[this.ne[i]]; - } -} - -/** - * Your MyLinkedList object will be instantiated and called as such: - * var obj = new MyLinkedList() - * var param_1 = obj.get(index) - * obj.addAtHead(val) - * obj.addAtTail(val) - * obj.addAtIndex(index,val) - * obj.deleteAtIndex(index) - */ -``` - -### **Rust** - ```rust #[derive(Default)] struct MyLinkedList { @@ -947,10 +524,415 @@ impl MyLinkedList { */ ``` -### **...** + + +### 方法二:静态数组实现单链表 -``` +在方法一中,我们使用了指针引用的方式,每次动态创建一个链表节点。在链表节点数量达到 $10^5$ 甚至更大时,频繁执行 new 操作,会大大增加程序的执行耗时。 + +因此,我们可以使用静态数组来实现单链表,预先申请一块大小略大于数据范围的内存空间,每次插入节点时,从数组中取出一个空闲的位置,将新节点插入到该位置,同时更新该位置的前驱和后继节点的指针引用。 + +我们定义以下几个变量,其中: + +- `head` 存放链表头节点的索引,初始时指向 $-1$。 +- `e` 存放链表所有节点的值(预先申请)。 +- `ne` 存放链表所有节点的 `next` 指针(预先申请)。 +- `idx` 指向当前可分配的节点索引,初始时指向索引 $0$。 +- `cnt` 记录当前链表节点个数,初始时为 $0$。 + +具体操作可参考以下代码。时间复杂度与方法一相同。 + + + +```python +class MyLinkedList: + def __init__(self): + self.e = [0] * 1010 + self.ne = [0] * 1010 + self.idx = 0 + self.head = -1 + self.cnt = 0 + def get(self, index: int) -> int: + if index < 0 or index >= self.cnt: + return -1 + i = self.head + for _ in range(index): + i = self.ne[i] + return self.e[i] + + def addAtHead(self, val: int) -> None: + self.e[self.idx] = val + self.ne[self.idx] = self.head + self.head = self.idx + self.idx += 1 + self.cnt += 1 + + def addAtTail(self, val: int) -> None: + self.addAtIndex(self.cnt, val) + + def addAtIndex(self, index: int, val: int) -> None: + if index > self.cnt: + return + if index <= 0: + self.addAtHead(val) + return + i = self.head + for _ in range(index - 1): + i = self.ne[i] + self.e[self.idx] = val + self.ne[self.idx] = self.ne[i] + self.ne[i] = self.idx + self.idx += 1 + self.cnt += 1 + + def deleteAtIndex(self, index: int) -> None: + if index < 0 or index >= self.cnt: + return -1 + self.cnt -= 1 + if index == 0: + self.head = self.ne[self.head] + return + i = self.head + for _ in range(index - 1): + i = self.ne[i] + self.ne[i] = self.ne[self.ne[i]] + + +# Your MyLinkedList object will be instantiated and called as such: +# obj = MyLinkedList() +# param_1 = obj.get(index) +# obj.addAtHead(val) +# obj.addAtTail(val) +# obj.addAtIndex(index,val) +# obj.deleteAtIndex(index) ``` - +```java +class MyLinkedList { + private int[] e = new int[1010]; + private int[] ne = new int[1010]; + private int head = -1; + private int idx; + private int cnt; + + public MyLinkedList() { + } + + public int get(int index) { + if (index < 0 || index >= cnt) { + return -1; + } + int i = head; + while (index-- > 0) { + i = ne[i]; + } + return e[i]; + } + + public void addAtHead(int val) { + e[idx] = val; + ne[idx] = head; + head = idx++; + ++cnt; + } + + public void addAtTail(int val) { + addAtIndex(cnt, val); + } + + public void addAtIndex(int index, int val) { + if (index > cnt) { + return; + } + if (index <= 0) { + addAtHead(val); + return; + } + int i = head; + while (--index > 0) { + i = ne[i]; + } + e[idx] = val; + ne[idx] = ne[i]; + ne[i] = idx++; + ++cnt; + } + + public void deleteAtIndex(int index) { + if (index < 0 || index >= cnt) { + return; + } + --cnt; + if (index == 0) { + head = ne[head]; + return; + } + int i = head; + while (--index > 0) { + i = ne[i]; + } + ne[i] = ne[ne[i]]; + } +} + +/** + * Your MyLinkedList object will be instantiated and called as such: + * MyLinkedList obj = new MyLinkedList(); + * int param_1 = obj.get(index); + * obj.addAtHead(val); + * obj.addAtTail(val); + * obj.addAtIndex(index,val); + * obj.deleteAtIndex(index); + */ +``` + +```cpp +class MyLinkedList { +private: + int e[1010], ne[1010]; + int head = -1, idx = 0, cnt = 0; + +public: + MyLinkedList() { + } + + int get(int index) { + if (index < 0 || index >= cnt) { + return -1; + } + int i = head; + while (index--) { + i = ne[i]; + } + return e[i]; + } + + void addAtHead(int val) { + e[idx] = val; + ne[idx] = head; + head = idx++; + ++cnt; + } + + void addAtTail(int val) { + addAtIndex(cnt, val); + } + + void addAtIndex(int index, int val) { + if (index > cnt) { + return; + } + if (index <= 0) { + addAtHead(val); + return; + } + int i = head; + while (--index) { + i = ne[i]; + } + e[idx] = val; + ne[idx] = ne[i]; + ne[i] = idx++; + ++cnt; + } + + void deleteAtIndex(int index) { + if (index < 0 || index >= cnt) { + return; + } + --cnt; + if (index == 0) { + head = ne[head]; + return; + } + int i = head; + while (--index) { + i = ne[i]; + } + ne[i] = ne[ne[i]]; + } +}; + +/** + * Your MyLinkedList object will be instantiated and called as such: + * MyLinkedList* obj = new MyLinkedList(); + * int param_1 = obj->get(index); + * obj->addAtHead(val); + * obj->addAtTail(val); + * obj->addAtIndex(index,val); + * obj->deleteAtIndex(index); + */ +``` + +```go +type MyLinkedList struct { + e []int + ne []int + idx int + head int + cnt int +} + +func Constructor() MyLinkedList { + e := make([]int, 1010) + ne := make([]int, 1010) + return MyLinkedList{e, ne, 0, -1, 0} +} + +func (this *MyLinkedList) Get(index int) int { + if index < 0 || index >= this.cnt { + return -1 + } + i := this.head + for ; index > 0; index-- { + i = this.ne[i] + } + return this.e[i] +} + +func (this *MyLinkedList) AddAtHead(val int) { + this.e[this.idx] = val + this.ne[this.idx] = this.head + this.head = this.idx + this.idx++ + this.cnt++ +} + +func (this *MyLinkedList) AddAtTail(val int) { + this.AddAtIndex(this.cnt, val) +} + +func (this *MyLinkedList) AddAtIndex(index int, val int) { + if index > this.cnt { + return + } + if index <= 0 { + this.AddAtHead(val) + return + } + i := this.head + for ; index > 1; index-- { + i = this.ne[i] + } + this.e[this.idx] = val + this.ne[this.idx] = this.ne[i] + this.ne[i] = this.idx + this.idx++ + this.cnt++ +} + +func (this *MyLinkedList) DeleteAtIndex(index int) { + if index < 0 || index >= this.cnt { + return + } + this.cnt-- + if index == 0 { + this.head = this.ne[this.head] + return + } + i := this.head + for ; index > 1; index-- { + i = this.ne[i] + } + this.ne[i] = this.ne[this.ne[i]] +} + +/** + * Your MyLinkedList object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Get(index); + * obj.AddAtHead(val); + * obj.AddAtTail(val); + * obj.AddAtIndex(index,val); + * obj.DeleteAtIndex(index); + */ +``` + +```ts +class MyLinkedList { + e: Array; + ne: Array; + idx: number; + head: number; + cnt: number; + + constructor() { + this.e = new Array(1010).fill(0); + this.ne = new Array(1010).fill(0); + this.head = -1; + this.idx = 0; + this.cnt = 0; + } + + get(index: number): number { + if (index < 0 || index >= this.cnt) { + return -1; + } + let i = this.head; + while (index--) { + i = this.ne[i]; + } + return this.e[i]; + } + + addAtHead(val: number): void { + this.e[this.idx] = val; + this.ne[this.idx] = this.head; + this.head = this.idx++; + this.cnt++; + } + + addAtTail(val: number): void { + this.addAtIndex(this.cnt, val); + } + + addAtIndex(index: number, val: number): void { + if (index > this.cnt) { + return; + } + if (index <= 0) { + this.addAtHead(val); + return; + } + let i = this.head; + while (--index) { + i = this.ne[i]; + } + this.e[this.idx] = val; + this.ne[this.idx] = this.ne[i]; + this.ne[i] = this.idx++; + this.cnt++; + } + + deleteAtIndex(index: number): void { + if (index < 0 || index >= this.cnt) { + return; + } + this.cnt--; + if (index == 0) { + this.head = this.ne[this.head]; + return; + } + let i = this.head; + while (--index) { + i = this.ne[i]; + } + this.ne[i] = this.ne[this.ne[i]]; + } +} + +/** + * Your MyLinkedList object will be instantiated and called as such: + * var obj = new MyLinkedList() + * var param_1 = obj.get(index) + * obj.addAtHead(val) + * obj.addAtTail(val) + * obj.addAtIndex(index,val) + * obj.deleteAtIndex(index) + */ +``` + + + + diff --git a/solution/0700-0799/0707.Design Linked List/README_EN.md b/solution/0700-0799/0707.Design Linked List/README_EN.md index 1d6b3125d27ff..4c58c6f40fb18 100644 --- a/solution/0700-0799/0707.Design Linked List/README_EN.md +++ b/solution/0700-0799/0707.Design Linked List/README_EN.md @@ -50,9 +50,9 @@ myLinkedList.get(1); // return 3 ## Solutions - +### Solution 1 -### **Python3** + ```python class MyLinkedList: @@ -104,72 +104,6 @@ class MyLinkedList: # obj.deleteAtIndex(index) ``` -```python -class MyLinkedList: - def __init__(self): - self.e = [0] * 1010 - self.ne = [0] * 1010 - self.idx = 0 - self.head = -1 - self.cnt = 0 - - def get(self, index: int) -> int: - if index < 0 or index >= self.cnt: - return -1 - i = self.head - for _ in range(index): - i = self.ne[i] - return self.e[i] - - def addAtHead(self, val: int) -> None: - self.e[self.idx] = val - self.ne[self.idx] = self.head - self.head = self.idx - self.idx += 1 - self.cnt += 1 - - def addAtTail(self, val: int) -> None: - self.addAtIndex(self.cnt, val) - - def addAtIndex(self, index: int, val: int) -> None: - if index > self.cnt: - return - if index <= 0: - self.addAtHead(val) - return - i = self.head - for _ in range(index - 1): - i = self.ne[i] - self.e[self.idx] = val - self.ne[self.idx] = self.ne[i] - self.ne[i] = self.idx - self.idx += 1 - self.cnt += 1 - - def deleteAtIndex(self, index: int) -> None: - if index < 0 or index >= self.cnt: - return -1 - self.cnt -= 1 - if index == 0: - self.head = self.ne[self.head] - return - i = self.head - for _ in range(index - 1): - i = self.ne[i] - self.ne[i] = self.ne[self.ne[i]] - - -# Your MyLinkedList object will be instantiated and called as such: -# obj = MyLinkedList() -# param_1 = obj.get(index) -# obj.addAtHead(val) -# obj.addAtTail(val) -# obj.addAtIndex(index,val) -# obj.deleteAtIndex(index) -``` - -### **Java** - ```java class MyLinkedList { private ListNode dummy = new ListNode(); @@ -235,87 +169,6 @@ class MyLinkedList { */ ``` -```java -class MyLinkedList { - private int[] e = new int[1010]; - private int[] ne = new int[1010]; - private int head = -1; - private int idx; - private int cnt; - - public MyLinkedList() { - } - - public int get(int index) { - if (index < 0 || index >= cnt) { - return -1; - } - int i = head; - while (index-- > 0) { - i = ne[i]; - } - return e[i]; - } - - public void addAtHead(int val) { - e[idx] = val; - ne[idx] = head; - head = idx++; - ++cnt; - } - - public void addAtTail(int val) { - addAtIndex(cnt, val); - } - - public void addAtIndex(int index, int val) { - if (index > cnt) { - return; - } - if (index <= 0) { - addAtHead(val); - return; - } - int i = head; - while (--index > 0) { - i = ne[i]; - } - e[idx] = val; - ne[idx] = ne[i]; - ne[i] = idx++; - ++cnt; - } - - public void deleteAtIndex(int index) { - if (index < 0 || index >= cnt) { - return; - } - --cnt; - if (index == 0) { - head = ne[head]; - return; - } - int i = head; - while (--index > 0) { - i = ne[i]; - } - ne[i] = ne[ne[i]]; - } -} - -/** - * Your MyLinkedList object will be instantiated and called as such: - * MyLinkedList obj = new MyLinkedList(); - * int param_1 = obj.get(index); - * obj.addAtHead(val); - * obj.addAtTail(val); - * obj.addAtIndex(index,val); - * obj.deleteAtIndex(index); - */ -``` - -### **C++** - ```cpp class MyLinkedList { private: @@ -383,86 +236,6 @@ public: */ ``` -```cpp -class MyLinkedList { -private: - int e[1010], ne[1010]; - int head = -1, idx = 0, cnt = 0; - -public: - MyLinkedList() { - } - - int get(int index) { - if (index < 0 || index >= cnt) { - return -1; - } - int i = head; - while (index--) { - i = ne[i]; - } - return e[i]; - } - - void addAtHead(int val) { - e[idx] = val; - ne[idx] = head; - head = idx++; - ++cnt; - } - - void addAtTail(int val) { - addAtIndex(cnt, val); - } - - void addAtIndex(int index, int val) { - if (index > cnt) { - return; - } - if (index <= 0) { - addAtHead(val); - return; - } - int i = head; - while (--index) { - i = ne[i]; - } - e[idx] = val; - ne[idx] = ne[i]; - ne[i] = idx++; - ++cnt; - } - - void deleteAtIndex(int index) { - if (index < 0 || index >= cnt) { - return; - } - --cnt; - if (index == 0) { - head = ne[head]; - return; - } - int i = head; - while (--index) { - i = ne[i]; - } - ne[i] = ne[ne[i]]; - } -}; - -/** - * Your MyLinkedList object will be instantiated and called as such: - * MyLinkedList* obj = new MyLinkedList(); - * int param_1 = obj->get(index); - * obj->addAtHead(val); - * obj->addAtTail(val); - * obj->addAtIndex(index,val); - * obj->deleteAtIndex(index); - */ -``` - -### **Go** - ```go type MyLinkedList struct { dummy *ListNode @@ -529,101 +302,15 @@ func (this *MyLinkedList) DeleteAtIndex(index int) { */ ``` -```go -type MyLinkedList struct { - e []int - ne []int - idx int - head int - cnt int -} +```ts +class LinkNode { + public val: number; + public next: LinkNode; -func Constructor() MyLinkedList { - e := make([]int, 1010) - ne := make([]int, 1010) - return MyLinkedList{e, ne, 0, -1, 0} -} - -func (this *MyLinkedList) Get(index int) int { - if index < 0 || index >= this.cnt { - return -1 - } - i := this.head - for ; index > 0; index-- { - i = this.ne[i] - } - return this.e[i] -} - -func (this *MyLinkedList) AddAtHead(val int) { - this.e[this.idx] = val - this.ne[this.idx] = this.head - this.head = this.idx - this.idx++ - this.cnt++ -} - -func (this *MyLinkedList) AddAtTail(val int) { - this.AddAtIndex(this.cnt, val) -} - -func (this *MyLinkedList) AddAtIndex(index int, val int) { - if index > this.cnt { - return - } - if index <= 0 { - this.AddAtHead(val) - return - } - i := this.head - for ; index > 1; index-- { - i = this.ne[i] - } - this.e[this.idx] = val - this.ne[this.idx] = this.ne[i] - this.ne[i] = this.idx - this.idx++ - this.cnt++ -} - -func (this *MyLinkedList) DeleteAtIndex(index int) { - if index < 0 || index >= this.cnt { - return - } - this.cnt-- - if index == 0 { - this.head = this.ne[this.head] - return - } - i := this.head - for ; index > 1; index-- { - i = this.ne[i] - } - this.ne[i] = this.ne[this.ne[i]] -} - -/** - * Your MyLinkedList object will be instantiated and called as such: - * obj := Constructor(); - * param_1 := obj.Get(index); - * obj.AddAtHead(val); - * obj.AddAtTail(val); - * obj.AddAtIndex(index,val); - * obj.DeleteAtIndex(index); - */ -``` - -### **TypeScript** - -```ts -class LinkNode { - public val: number; - public next: LinkNode; - - constructor(val: number, next: LinkNode = null) { - this.val = val; - this.next = next; - } + constructor(val: number, next: LinkNode = null) { + this.val = val; + this.next = next; + } } class MyLinkedList { @@ -713,92 +400,6 @@ class MyLinkedList { */ ``` -```ts -class MyLinkedList { - e: Array; - ne: Array; - idx: number; - head: number; - cnt: number; - - constructor() { - this.e = new Array(1010).fill(0); - this.ne = new Array(1010).fill(0); - this.head = -1; - this.idx = 0; - this.cnt = 0; - } - - get(index: number): number { - if (index < 0 || index >= this.cnt) { - return -1; - } - let i = this.head; - while (index--) { - i = this.ne[i]; - } - return this.e[i]; - } - - addAtHead(val: number): void { - this.e[this.idx] = val; - this.ne[this.idx] = this.head; - this.head = this.idx++; - this.cnt++; - } - - addAtTail(val: number): void { - this.addAtIndex(this.cnt, val); - } - - addAtIndex(index: number, val: number): void { - if (index > this.cnt) { - return; - } - if (index <= 0) { - this.addAtHead(val); - return; - } - let i = this.head; - while (--index) { - i = this.ne[i]; - } - this.e[this.idx] = val; - this.ne[this.idx] = this.ne[i]; - this.ne[i] = this.idx++; - this.cnt++; - } - - deleteAtIndex(index: number): void { - if (index < 0 || index >= this.cnt) { - return; - } - this.cnt--; - if (index == 0) { - this.head = this.ne[this.head]; - return; - } - let i = this.head; - while (--index) { - i = this.ne[i]; - } - this.ne[i] = this.ne[this.ne[i]]; - } -} - -/** - * Your MyLinkedList object will be instantiated and called as such: - * var obj = new MyLinkedList() - * var param_1 = obj.get(index) - * obj.addAtHead(val) - * obj.addAtTail(val) - * obj.addAtIndex(index,val) - * obj.deleteAtIndex(index) - */ -``` - -### **Rust** - ```rust #[derive(Default)] struct MyLinkedList { @@ -903,10 +504,401 @@ impl MyLinkedList { */ ``` -### **...** + -``` +### Solution 2 + + + +```python +class MyLinkedList: + def __init__(self): + self.e = [0] * 1010 + self.ne = [0] * 1010 + self.idx = 0 + self.head = -1 + self.cnt = 0 + + def get(self, index: int) -> int: + if index < 0 or index >= self.cnt: + return -1 + i = self.head + for _ in range(index): + i = self.ne[i] + return self.e[i] + + def addAtHead(self, val: int) -> None: + self.e[self.idx] = val + self.ne[self.idx] = self.head + self.head = self.idx + self.idx += 1 + self.cnt += 1 + + def addAtTail(self, val: int) -> None: + self.addAtIndex(self.cnt, val) + + def addAtIndex(self, index: int, val: int) -> None: + if index > self.cnt: + return + if index <= 0: + self.addAtHead(val) + return + i = self.head + for _ in range(index - 1): + i = self.ne[i] + self.e[self.idx] = val + self.ne[self.idx] = self.ne[i] + self.ne[i] = self.idx + self.idx += 1 + self.cnt += 1 + + def deleteAtIndex(self, index: int) -> None: + if index < 0 or index >= self.cnt: + return -1 + self.cnt -= 1 + if index == 0: + self.head = self.ne[self.head] + return + i = self.head + for _ in range(index - 1): + i = self.ne[i] + self.ne[i] = self.ne[self.ne[i]] + +# Your MyLinkedList object will be instantiated and called as such: +# obj = MyLinkedList() +# param_1 = obj.get(index) +# obj.addAtHead(val) +# obj.addAtTail(val) +# obj.addAtIndex(index,val) +# obj.deleteAtIndex(index) ``` - +```java +class MyLinkedList { + private int[] e = new int[1010]; + private int[] ne = new int[1010]; + private int head = -1; + private int idx; + private int cnt; + + public MyLinkedList() { + } + + public int get(int index) { + if (index < 0 || index >= cnt) { + return -1; + } + int i = head; + while (index-- > 0) { + i = ne[i]; + } + return e[i]; + } + + public void addAtHead(int val) { + e[idx] = val; + ne[idx] = head; + head = idx++; + ++cnt; + } + + public void addAtTail(int val) { + addAtIndex(cnt, val); + } + + public void addAtIndex(int index, int val) { + if (index > cnt) { + return; + } + if (index <= 0) { + addAtHead(val); + return; + } + int i = head; + while (--index > 0) { + i = ne[i]; + } + e[idx] = val; + ne[idx] = ne[i]; + ne[i] = idx++; + ++cnt; + } + + public void deleteAtIndex(int index) { + if (index < 0 || index >= cnt) { + return; + } + --cnt; + if (index == 0) { + head = ne[head]; + return; + } + int i = head; + while (--index > 0) { + i = ne[i]; + } + ne[i] = ne[ne[i]]; + } +} + +/** + * Your MyLinkedList object will be instantiated and called as such: + * MyLinkedList obj = new MyLinkedList(); + * int param_1 = obj.get(index); + * obj.addAtHead(val); + * obj.addAtTail(val); + * obj.addAtIndex(index,val); + * obj.deleteAtIndex(index); + */ +``` + +```cpp +class MyLinkedList { +private: + int e[1010], ne[1010]; + int head = -1, idx = 0, cnt = 0; + +public: + MyLinkedList() { + } + + int get(int index) { + if (index < 0 || index >= cnt) { + return -1; + } + int i = head; + while (index--) { + i = ne[i]; + } + return e[i]; + } + + void addAtHead(int val) { + e[idx] = val; + ne[idx] = head; + head = idx++; + ++cnt; + } + + void addAtTail(int val) { + addAtIndex(cnt, val); + } + + void addAtIndex(int index, int val) { + if (index > cnt) { + return; + } + if (index <= 0) { + addAtHead(val); + return; + } + int i = head; + while (--index) { + i = ne[i]; + } + e[idx] = val; + ne[idx] = ne[i]; + ne[i] = idx++; + ++cnt; + } + + void deleteAtIndex(int index) { + if (index < 0 || index >= cnt) { + return; + } + --cnt; + if (index == 0) { + head = ne[head]; + return; + } + int i = head; + while (--index) { + i = ne[i]; + } + ne[i] = ne[ne[i]]; + } +}; + +/** + * Your MyLinkedList object will be instantiated and called as such: + * MyLinkedList* obj = new MyLinkedList(); + * int param_1 = obj->get(index); + * obj->addAtHead(val); + * obj->addAtTail(val); + * obj->addAtIndex(index,val); + * obj->deleteAtIndex(index); + */ +``` + +```go +type MyLinkedList struct { + e []int + ne []int + idx int + head int + cnt int +} + +func Constructor() MyLinkedList { + e := make([]int, 1010) + ne := make([]int, 1010) + return MyLinkedList{e, ne, 0, -1, 0} +} + +func (this *MyLinkedList) Get(index int) int { + if index < 0 || index >= this.cnt { + return -1 + } + i := this.head + for ; index > 0; index-- { + i = this.ne[i] + } + return this.e[i] +} + +func (this *MyLinkedList) AddAtHead(val int) { + this.e[this.idx] = val + this.ne[this.idx] = this.head + this.head = this.idx + this.idx++ + this.cnt++ +} + +func (this *MyLinkedList) AddAtTail(val int) { + this.AddAtIndex(this.cnt, val) +} + +func (this *MyLinkedList) AddAtIndex(index int, val int) { + if index > this.cnt { + return + } + if index <= 0 { + this.AddAtHead(val) + return + } + i := this.head + for ; index > 1; index-- { + i = this.ne[i] + } + this.e[this.idx] = val + this.ne[this.idx] = this.ne[i] + this.ne[i] = this.idx + this.idx++ + this.cnt++ +} + +func (this *MyLinkedList) DeleteAtIndex(index int) { + if index < 0 || index >= this.cnt { + return + } + this.cnt-- + if index == 0 { + this.head = this.ne[this.head] + return + } + i := this.head + for ; index > 1; index-- { + i = this.ne[i] + } + this.ne[i] = this.ne[this.ne[i]] +} + +/** + * Your MyLinkedList object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Get(index); + * obj.AddAtHead(val); + * obj.AddAtTail(val); + * obj.AddAtIndex(index,val); + * obj.DeleteAtIndex(index); + */ +``` + +```ts +class MyLinkedList { + e: Array; + ne: Array; + idx: number; + head: number; + cnt: number; + + constructor() { + this.e = new Array(1010).fill(0); + this.ne = new Array(1010).fill(0); + this.head = -1; + this.idx = 0; + this.cnt = 0; + } + + get(index: number): number { + if (index < 0 || index >= this.cnt) { + return -1; + } + let i = this.head; + while (index--) { + i = this.ne[i]; + } + return this.e[i]; + } + + addAtHead(val: number): void { + this.e[this.idx] = val; + this.ne[this.idx] = this.head; + this.head = this.idx++; + this.cnt++; + } + + addAtTail(val: number): void { + this.addAtIndex(this.cnt, val); + } + + addAtIndex(index: number, val: number): void { + if (index > this.cnt) { + return; + } + if (index <= 0) { + this.addAtHead(val); + return; + } + let i = this.head; + while (--index) { + i = this.ne[i]; + } + this.e[this.idx] = val; + this.ne[this.idx] = this.ne[i]; + this.ne[i] = this.idx++; + this.cnt++; + } + + deleteAtIndex(index: number): void { + if (index < 0 || index >= this.cnt) { + return; + } + this.cnt--; + if (index == 0) { + this.head = this.ne[this.head]; + return; + } + let i = this.head; + while (--index) { + i = this.ne[i]; + } + this.ne[i] = this.ne[this.ne[i]]; + } +} + +/** + * Your MyLinkedList object will be instantiated and called as such: + * var obj = new MyLinkedList() + * var param_1 = obj.get(index) + * obj.addAtHead(val) + * obj.addAtTail(val) + * obj.addAtIndex(index,val) + * obj.deleteAtIndex(index) + */ +``` + + + + diff --git a/solution/0700-0799/0708.Insert into a Sorted Circular Linked List/README.md b/solution/0700-0799/0708.Insert into a Sorted Circular Linked List/README.md index c3208be2d89a9..6e067c693d070 100644 --- a/solution/0700-0799/0708.Insert into a Sorted Circular Linked List/README.md +++ b/solution/0700-0799/0708.Insert into a Sorted Circular Linked List/README.md @@ -53,14 +53,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python """ # Definition for a Node. @@ -89,10 +85,6 @@ class Solution: return head ``` -### **Java** - - - ```java /* // Definition for a Node. @@ -136,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -181,8 +171,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -211,10 +199,6 @@ func insert(head *Node, x int) *Node { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0708.Insert into a Sorted Circular Linked List/README_EN.md b/solution/0700-0799/0708.Insert into a Sorted Circular Linked List/README_EN.md index 1df5405253e53..0c2a5388eed8e 100644 --- a/solution/0700-0799/0708.Insert into a Sorted Circular Linked List/README_EN.md +++ b/solution/0700-0799/0708.Insert into a Sorted Circular Linked List/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -80,8 +80,6 @@ class Solution: return head ``` -### **Java** - ```java /* // Definition for a Node. @@ -125,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -170,8 +166,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -200,10 +194,6 @@ func insert(head *Node, x int) *Node { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0709.To Lower Case/README.md b/solution/0700-0799/0709.To Lower Case/README.md index 9ef0a8fa392c6..5825598d688ea 100644 --- a/solution/0700-0799/0709.To Lower Case/README.md +++ b/solution/0700-0799/0709.To Lower Case/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以遍历字符串,对于每个大写字母,将其转换为小写字母。最后返回转换后的字符串即可。 @@ -52,20 +50,12 @@ -### **Python3** - - - ```python class Solution: def toLowerCase(self, s: str) -> str: return "".join([chr(ord(c) | 32) if c.isupper() else c for c in s]) ``` -### **Java** - - - ```java class Solution { public String toLowerCase(String s) { @@ -80,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +84,6 @@ public: }; ``` -### **Go** - ```go func toLowerCase(s string) string { cs := []byte(s) @@ -110,22 +96,12 @@ func toLowerCase(s string) string { } ``` -### **TypeScript** - ```ts function toLowerCase(s: string): string { return s.toLowerCase(); } ``` -```ts -function toLowerCase(s: string): string { - return [...s].map(c => String.fromCharCode(c.charCodeAt(0) | 32)).join(''); -} -``` - -### **Rust** - ```rust impl Solution { pub fn to_lower_case(s: String) -> String { @@ -134,19 +110,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn to_lower_case(s: String) -> String { - s.as_bytes() - .iter() - .map(|&c| char::from(if c >= b'A' && c <= b'Z' { c | 32 } else { c })) - .collect() - } -} -``` - -### **C** - ```c char* toLowerCase(char* s) { int n = strlen(s); @@ -159,10 +122,29 @@ char* toLowerCase(char* s) { } ``` -### **...** + + +### 方法二 + + +```ts +function toLowerCase(s: string): string { + return [...s].map(c => String.fromCharCode(c.charCodeAt(0) | 32)).join(''); +} ``` +```rust +impl Solution { + pub fn to_lower_case(s: String) -> String { + s.as_bytes() + .iter() + .map(|&c| char::from(if c >= b'A' && c <= b'Z' { c | 32 } else { c })) + .collect() + } +} ``` + + diff --git a/solution/0700-0799/0709.To Lower Case/README_EN.md b/solution/0700-0799/0709.To Lower Case/README_EN.md index 774fef0689ddf..f82469c2cb95a 100644 --- a/solution/0700-0799/0709.To Lower Case/README_EN.md +++ b/solution/0700-0799/0709.To Lower Case/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -48,8 +48,6 @@ class Solution: return "".join([chr(ord(c) | 32) if c.isupper() else c for c in s]) ``` -### **Java** - ```java class Solution { public String toLowerCase(String s) { @@ -64,8 +62,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -80,8 +76,6 @@ public: }; ``` -### **Go** - ```go func toLowerCase(s string) string { cs := []byte(s) @@ -94,22 +88,12 @@ func toLowerCase(s string) string { } ``` -### **TypeScript** - ```ts function toLowerCase(s: string): string { return s.toLowerCase(); } ``` -```ts -function toLowerCase(s: string): string { - return [...s].map(c => String.fromCharCode(c.charCodeAt(0) | 32)).join(''); -} -``` - -### **Rust** - ```rust impl Solution { pub fn to_lower_case(s: String) -> String { @@ -118,19 +102,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn to_lower_case(s: String) -> String { - s.as_bytes() - .iter() - .map(|&c| char::from(if c >= b'A' && c <= b'Z' { c | 32 } else { c })) - .collect() - } -} -``` - -### **C** - ```c char* toLowerCase(char* s) { int n = strlen(s); @@ -143,10 +114,29 @@ char* toLowerCase(char* s) { } ``` -### **...** + + +### Solution 2 + + +```ts +function toLowerCase(s: string): string { + return [...s].map(c => String.fromCharCode(c.charCodeAt(0) | 32)).join(''); +} ``` +```rust +impl Solution { + pub fn to_lower_case(s: String) -> String { + s.as_bytes() + .iter() + .map(|&c| char::from(if c >= b'A' && c <= b'Z' { c | 32 } else { c })) + .collect() + } +} ``` + + diff --git a/solution/0700-0799/0710.Random Pick with Blacklist/README.md b/solution/0700-0799/0710.Random Pick with Blacklist/README.md index 73bcd0a9a956a..9761ad5a877a2 100644 --- a/solution/0700-0799/0710.Random Pick with Blacklist/README.md +++ b/solution/0700-0799/0710.Random Pick with Blacklist/README.md @@ -54,16 +54,10 @@ solution.pick(); // 返回 4 ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 -### **Python3** - - - ```python class Solution: def __init__(self, n: int, blacklist: List[int]): @@ -88,10 +82,6 @@ class Solution: # param_1 = obj.pick() ``` -### **Java** - - - ```java class Solution { private Map d = new HashMap<>(); @@ -128,8 +118,6 @@ class Solution { */ ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +149,6 @@ public: */ ``` -### **Go** - ```go type Solution struct { d map[int]int @@ -204,10 +190,6 @@ func (this *Solution) Pick() int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0710.Random Pick with Blacklist/README_EN.md b/solution/0700-0799/0710.Random Pick with Blacklist/README_EN.md index 22d90484cd644..fdceda158a92f 100644 --- a/solution/0700-0799/0710.Random Pick with Blacklist/README_EN.md +++ b/solution/0700-0799/0710.Random Pick with Blacklist/README_EN.md @@ -50,9 +50,9 @@ solution.pick(); // return 4 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,8 +78,6 @@ class Solution: # param_1 = obj.pick() ``` -### **Java** - ```java class Solution { private Map d = new HashMap<>(); @@ -116,8 +114,6 @@ class Solution { */ ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +145,6 @@ public: */ ``` -### **Go** - ```go type Solution struct { d map[int]int @@ -192,10 +186,6 @@ func (this *Solution) Pick() int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0711.Number of Distinct Islands II/README.md b/solution/0700-0799/0711.Number of Distinct Islands II/README.md index 8ea8046bb04a2..175df43a9b2b7 100644 --- a/solution/0700-0799/0711.Number of Distinct Islands II/README.md +++ b/solution/0700-0799/0711.Number of Distinct Islands II/README.md @@ -46,29 +46,10 @@ ## 解法 - - -先利用 DFS 找出每个岛屿,随后对岛屿进行翻转、旋转等操作,得到以下 8 种不同的情况,并对这些情况进行标准化 `normalize` 处理,得到该岛屿的特征值,放到哈希表中。最后返回哈希表的元素数量即可。 - -``` -原坐标: (i, j) -上下翻转: (i, -j) -左右翻转: (-i, j) -90°旋转: (j, -i) -180°旋转: (-i, -j) -270°旋转: (-j, -i) -90°旋转+左右翻转: (-j, -i) -90°旋转+上下翻转: (j, i) -``` - -标准化 `normalize` 的思路是:对于岛屿的每一种情况,先按照横、纵坐标升序排列坐标点,得到的第一个点 `(a, b)` 是最小的点,将其化为 `(0, 0)`,对于其他点 `(x, y)`,则化为 `(x - a, y - b)`。然后排序这 8 种情况,获取最小的一种,作为该岛屿的标准化值。 +### 方法一 -### **Python3** - - - ```python class Solution: def numDistinctIslands2(self, grid: List[List[int]]) -> int: @@ -110,10 +91,6 @@ class Solution: return len(s) ``` -### **Java** - - - ```java class Solution { private int m; @@ -210,8 +187,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef pair PII; @@ -268,10 +243,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0711.Number of Distinct Islands II/README_EN.md b/solution/0700-0799/0711.Number of Distinct Islands II/README_EN.md index 529ef0bebefeb..619795d19b410 100644 --- a/solution/0700-0799/0711.Number of Distinct Islands II/README_EN.md +++ b/solution/0700-0799/0711.Number of Distinct Islands II/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,8 +83,6 @@ class Solution: return len(s) ``` -### **Java** - ```java class Solution { private int m; @@ -181,8 +179,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef pair PII; @@ -239,10 +235,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/README.md b/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/README.md index b58a3e20cefb9..1876e9205ce54 100644 --- a/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/README.md +++ b/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示使得 $s_1$ 的前 $i$ 个字符和 $s_2$ 的前 $j$ 个字符相等所需删除字符的 ASCII 值的最小和。那么答案就是 $f[m][n]$。 @@ -70,10 +68,6 @@ $$ -### **Python3** - - - ```python class Solution: def minimumDeleteSum(self, s1: str, s2: str) -> int: @@ -94,10 +88,6 @@ class Solution: return f[m][n] ``` -### **Java** - - - ```java class Solution { public int minimumDeleteSum(String s1, String s2) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func minimumDeleteSum(s1 string, s2 string) int { m, n := len(s1), len(s2) @@ -181,8 +167,6 @@ func minimumDeleteSum(s1 string, s2 string) int { } ``` -### **TypeScript** - ```ts function minimumDeleteSum(s1: string, s2: string): number { const m = s1.length; @@ -210,8 +194,6 @@ function minimumDeleteSum(s1: string, s2: string): number { } ``` -### **JavaScript** - ```js /** * @param {string} s1 @@ -244,10 +226,6 @@ var minimumDeleteSum = function (s1, s2) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/README_EN.md b/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/README_EN.md index 3399dce5e15e7..d2177d9424829 100644 --- a/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/README_EN.md +++ b/solution/0700-0799/0712.Minimum ASCII Delete Sum for Two Strings/README_EN.md @@ -39,12 +39,10 @@ If instead we turned both strings into "lee" or "eet", we wo ## Solutions -Dynamic programming. +### Solution 1 -### **Python3** - ```python class Solution: def minimumDeleteSum(self, s1: str, s2: str) -> int: @@ -65,8 +63,6 @@ class Solution: return f[m][n] ``` -### **Java** - ```java class Solution { public int minimumDeleteSum(String s1, String s2) { @@ -93,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func minimumDeleteSum(s1 string, s2 string) int { m, n := len(s1), len(s2) @@ -150,8 +142,6 @@ func minimumDeleteSum(s1 string, s2 string) int { } ``` -### **TypeScript** - ```ts function minimumDeleteSum(s1: string, s2: string): number { const m = s1.length; @@ -179,8 +169,6 @@ function minimumDeleteSum(s1: string, s2: string): number { } ``` -### **JavaScript** - ```js /** * @param {string} s1 @@ -213,10 +201,6 @@ var minimumDeleteSum = function (s1, s2) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0713.Subarray Product Less Than K/README.md b/solution/0700-0799/0713.Subarray Product Less Than K/README.md index 140be49362d7a..dae6606196c3c 100644 --- a/solution/0700-0799/0713.Subarray Product Less Than K/README.md +++ b/solution/0700-0799/0713.Subarray Product Less Than K/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们可以用双指针维护一个滑动窗口,窗口内所有元素的乘积小于 $k$。 @@ -62,10 +60,6 @@ for (int i = 0, j = 0; i < n; ++i) { -### **Python3** - - - ```python class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numSubarrayProductLessThanK(int[] nums, int k) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func numSubarrayProductLessThanK(nums []int, k int) int { ans := 0 @@ -132,8 +118,6 @@ func numSubarrayProductLessThanK(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function numSubarrayProductLessThanK(nums: number[], k: number): number { let ans = 0; @@ -148,8 +132,6 @@ function numSubarrayProductLessThanK(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn num_subarray_product_less_than_k(nums: Vec, k: i32) -> i32 { @@ -175,8 +157,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -198,10 +178,6 @@ var numSubarrayProductLessThanK = function (nums, k) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0713.Subarray Product Less Than K/README_EN.md b/solution/0700-0799/0713.Subarray Product Less Than K/README_EN.md index aad4de8ce1377..53d584c914e5d 100644 --- a/solution/0700-0799/0713.Subarray Product Less Than K/README_EN.md +++ b/solution/0700-0799/0713.Subarray Product Less Than K/README_EN.md @@ -35,9 +35,9 @@ Note that [10, 5, 2] is not included as the product of 100 is not strictly less ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numSubarrayProductLessThanK(int[] nums, int k) { @@ -70,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +83,6 @@ public: }; ``` -### **Go** - ```go func numSubarrayProductLessThanK(nums []int, k int) int { ans := 0 @@ -103,8 +97,6 @@ func numSubarrayProductLessThanK(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function numSubarrayProductLessThanK(nums: number[], k: number): number { let ans = 0; @@ -119,8 +111,6 @@ function numSubarrayProductLessThanK(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn num_subarray_product_less_than_k(nums: Vec, k: i32) -> i32 { @@ -146,8 +136,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -169,10 +157,6 @@ var numSubarrayProductLessThanK = function (nums, k) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/README.md b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/README.md index c260394e47055..bcc351eeb48d7 100644 --- a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/README.md +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j)$,表示从第 $i$ 天开始,状态为 $j$ 时,能够获得的最大利润。其中 $j$ 的取值为 $0, 1$,分别表示当前不持有股票和持有股票。答案即为 $dfs(0, 0)$。 @@ -65,22 +63,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $prices$ 的长度。 -**方法二:动态规划** - -我们定义 $f[i][j]$ 表示到第 $i$ 天,且状态为 $j$ 时,能够获得的最大利润。其中 $j$ 的取值为 $0, 1$,分别表示当前不持有股票和持有股票。初始时 $f[0][0] = 0$, $f[0][1] = -prices[0]$。 - -当 $i \geq 1$ 时,如果当前不持有股票,那么 $f[i][0]$ 可以由 $f[i - 1][0]$ 和 $f[i - 1][1] + prices[i] - fee$ 转移得到,即 $f[i][0] = \max(f[i - 1][0], f[i - 1][1] + prices[i] - fee)$;如果当前持有股票,那么 $f[i][1]$ 可以由 $f[i - 1][1]$ 和 $f[i - 1][0] - prices[i]$ 转移得到,即 $f[i][1] = \max(f[i - 1][1], f[i - 1][0] - prices[i])$。最终答案为 $f[n - 1][0]$。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $prices$ 的长度。 - -我们注意到,状态 $f[i][]$ 的转移只与 $f[i - 1][]$ 和 $f[i - 1][]$ 有关,因此我们可以用两个变量 $f_0, f_1$ 代替数组 $f$,将空间复杂度优化到 $O(1)$。 - -### **Python3** - - - ```python class Solution: def maxProfit(self, prices: List[int], fee: int) -> int: @@ -98,31 +82,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def maxProfit(self, prices: List[int], fee: int) -> int: - n = len(prices) - f = [[0] * 2 for _ in range(n)] - f[0][1] = -prices[0] - for i in range(1, n): - f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i] - fee) - f[i][1] = max(f[i - 1][1], f[i - 1][0] - prices[i]) - return f[n - 1][0] -``` - -```python -class Solution: - def maxProfit(self, prices: List[int], fee: int) -> int: - f0, f1 = 0, -prices[0] - for x in prices[1:]: - f0, f1 = max(f0, f1 + x - fee), max(f1, f0 - x) - return f0 -``` - -### **Java** - - - ```java class Solution { private Integer[][] f; @@ -154,37 +113,6 @@ class Solution { } ``` -```java -class Solution { - public int maxProfit(int[] prices, int fee) { - int n = prices.length; - int[][] f = new int[n][2]; - f[0][1] = -prices[0]; - for (int i = 1; i < n; ++i) { - f[i][0] = Math.max(f[i - 1][0], f[i - 1][1] + prices[i] - fee); - f[i][1] = Math.max(f[i - 1][1], f[i - 1][0] - prices[i]); - } - return f[n - 1][0]; - } -} -``` - -```java -class Solution { - public int maxProfit(int[] prices, int fee) { - int f0 = 0, f1 = -prices[0]; - for (int i = 1; i < prices.length; ++i) { - int g0 = Math.max(f0, f1 + prices[i] - fee); - f1 = Math.max(f1, f0 - prices[i]); - f0 = g0; - } - return f0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -212,40 +140,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxProfit(vector& prices, int fee) { - int n = prices.size(); - int f[n][2]; - memset(f, 0, sizeof(f)); - f[0][1] = -prices[0]; - for (int i = 1; i < n; ++i) { - f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i] - fee); - f[i][1] = max(f[i - 1][1], f[i - 1][0] - prices[i]); - } - return f[n - 1][0]; - } -}; -``` - -```cpp -class Solution { -public: - int maxProfit(vector& prices, int fee) { - int f0 = 0, f1 = -prices[0]; - for (int i = 1; i < prices.size(); ++i) { - int g0 = max(f0, f1 + prices[i] - fee); - f1 = max(f1, f0 - prices[i]); - f0 = g0; - } - return f0; - } -}; -``` - -### **Go** - ```go func maxProfit(prices []int, fee int) int { n := len(prices) @@ -274,31 +168,6 @@ func maxProfit(prices []int, fee int) int { } ``` -```go -func maxProfit(prices []int, fee int) int { - n := len(prices) - f := make([][2]int, n) - f[0][1] = -prices[0] - for i := 1; i < n; i++ { - f[i][0] = max(f[i-1][0], f[i-1][1]+prices[i]-fee) - f[i][1] = max(f[i-1][1], f[i-1][0]-prices[i]) - } - return f[n-1][0] -} -``` - -```go -func maxProfit(prices []int, fee int) int { - f0, f1 := 0, -prices[0] - for _, x := range prices[1:] { - f0, f1 = max(f0, f1+x-fee), max(f1, f0-x) - } - return f0 -} -``` - -### **TypeScript** - ```ts function maxProfit(prices: number[], fee: number): number { const n = prices.length; @@ -322,6 +191,77 @@ function maxProfit(prices: number[], fee: number): number { } ``` + + +### 方法二:动态规划 + +我们定义 $f[i][j]$ 表示到第 $i$ 天,且状态为 $j$ 时,能够获得的最大利润。其中 $j$ 的取值为 $0, 1$,分别表示当前不持有股票和持有股票。初始时 $f[0][0] = 0$, $f[0][1] = -prices[0]$。 + +当 $i \geq 1$ 时,如果当前不持有股票,那么 $f[i][0]$ 可以由 $f[i - 1][0]$ 和 $f[i - 1][1] + prices[i] - fee$ 转移得到,即 $f[i][0] = \max(f[i - 1][0], f[i - 1][1] + prices[i] - fee)$;如果当前持有股票,那么 $f[i][1]$ 可以由 $f[i - 1][1]$ 和 $f[i - 1][0] - prices[i]$ 转移得到,即 $f[i][1] = \max(f[i - 1][1], f[i - 1][0] - prices[i])$。最终答案为 $f[n - 1][0]$。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $prices$ 的长度。 + +我们注意到,状态 $f[i][]$ 的转移只与 $f[i - 1][]$ 和 $f[i - 1][]$ 有关,因此我们可以用两个变量 $f_0, f_1$ 代替数组 $f$,将空间复杂度优化到 $O(1)$。 + + + +```python +class Solution: + def maxProfit(self, prices: List[int], fee: int) -> int: + n = len(prices) + f = [[0] * 2 for _ in range(n)] + f[0][1] = -prices[0] + for i in range(1, n): + f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i] - fee) + f[i][1] = max(f[i - 1][1], f[i - 1][0] - prices[i]) + return f[n - 1][0] +``` + +```java +class Solution { + public int maxProfit(int[] prices, int fee) { + int n = prices.length; + int[][] f = new int[n][2]; + f[0][1] = -prices[0]; + for (int i = 1; i < n; ++i) { + f[i][0] = Math.max(f[i - 1][0], f[i - 1][1] + prices[i] - fee); + f[i][1] = Math.max(f[i - 1][1], f[i - 1][0] - prices[i]); + } + return f[n - 1][0]; + } +} +``` + +```cpp +class Solution { +public: + int maxProfit(vector& prices, int fee) { + int n = prices.size(); + int f[n][2]; + memset(f, 0, sizeof(f)); + f[0][1] = -prices[0]; + for (int i = 1; i < n; ++i) { + f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i] - fee); + f[i][1] = max(f[i - 1][1], f[i - 1][0] - prices[i]); + } + return f[n - 1][0]; + } +}; +``` + +```go +func maxProfit(prices []int, fee int) int { + n := len(prices) + f := make([][2]int, n) + f[0][1] = -prices[0] + for i := 1; i < n; i++ { + f[i][0] = max(f[i-1][0], f[i-1][1]+prices[i]-fee) + f[i][1] = max(f[i-1][1], f[i-1][0]-prices[i]) + } + return f[n-1][0] +} +``` + ```ts function maxProfit(prices: number[], fee: number): number { const n = prices.length; @@ -335,6 +275,60 @@ function maxProfit(prices: number[], fee: number): number { } ``` + + +### 方法三 + + + +```python +class Solution: + def maxProfit(self, prices: List[int], fee: int) -> int: + f0, f1 = 0, -prices[0] + for x in prices[1:]: + f0, f1 = max(f0, f1 + x - fee), max(f1, f0 - x) + return f0 +``` + +```java +class Solution { + public int maxProfit(int[] prices, int fee) { + int f0 = 0, f1 = -prices[0]; + for (int i = 1; i < prices.length; ++i) { + int g0 = Math.max(f0, f1 + prices[i] - fee); + f1 = Math.max(f1, f0 - prices[i]); + f0 = g0; + } + return f0; + } +} +``` + +```cpp +class Solution { +public: + int maxProfit(vector& prices, int fee) { + int f0 = 0, f1 = -prices[0]; + for (int i = 1; i < prices.size(); ++i) { + int g0 = max(f0, f1 + prices[i] - fee); + f1 = max(f1, f0 - prices[i]); + f0 = g0; + } + return f0; + } +}; +``` + +```go +func maxProfit(prices []int, fee int) int { + f0, f1 := 0, -prices[0] + for _, x := range prices[1:] { + f0, f1 = max(f0, f1+x-fee), max(f1, f0-x) + } + return f0 +} +``` + ```ts function maxProfit(prices: number[], fee: number): number { const n = prices.length; @@ -346,10 +340,6 @@ function maxProfit(prices: number[], fee: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/README_EN.md b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/README_EN.md index 123b8676e2d23..7c737519efd54 100644 --- a/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/README_EN.md +++ b/solution/0700-0799/0714.Best Time to Buy and Sell Stock with Transaction Fee/README_EN.md @@ -47,7 +47,7 @@ The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8. ## Solutions -**Solution 1: Memoization** +### Solution 1: Memoization We design a function $dfs(i, j)$, which represents the maximum profit that can be obtained starting from day $i$ with state $j$. Here, $j$ can take the values $0$ and $1$, representing not holding and holding a stock, respectively. The answer is $dfs(0, 0)$. @@ -63,20 +63,8 @@ To avoid redundant calculations, we use memoization to record the return value o The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $prices$. -**Solution 2: Dynamic Programming** - -We define $f[i][j]$ as the maximum profit that can be obtained up to day $i$ with state $j$. Here, $j$ can take the values $0$ and $1$, representing not holding and holding a stock, respectively. We initialize $f[0][0] = 0$ and $f[0][1] = -prices[0]$. - -When $i \geq 1$, if we do not hold a stock at the current day, then $f[i][0]$ can be obtained by transitioning from $f[i - 1][0]$ and $f[i - 1][1] + prices[i] - fee$, i.e., $f[i][0] = \max(f[i - 1][0], f[i - 1][1] + prices[i] - fee)$. If we hold a stock at the current day, then $f[i][1]$ can be obtained by transitioning from $f[i - 1][1]$ and $f[i - 1][0] - prices[i]$, i.e., $f[i][1] = \max(f[i - 1][1], f[i - 1][0] - prices[i])$. The final answer is $f[n - 1][0]$. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $prices$. - -We notice that the transition of the state $f[i][]$ only depends on $f[i - 1][]$ and $f[i - 2][]$. Therefore, we can use two variables $f_0$ and $f_1$ to replace the array $f$, reducing the space complexity to $O(1)$. - -### **Python3** - ```python class Solution: def maxProfit(self, prices: List[int], fee: int) -> int: @@ -94,29 +82,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def maxProfit(self, prices: List[int], fee: int) -> int: - n = len(prices) - f = [[0] * 2 for _ in range(n)] - f[0][1] = -prices[0] - for i in range(1, n): - f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i] - fee) - f[i][1] = max(f[i - 1][1], f[i - 1][0] - prices[i]) - return f[n - 1][0] -``` - -```python -class Solution: - def maxProfit(self, prices: List[int], fee: int) -> int: - f0, f1 = 0, -prices[0] - for x in prices[1:]: - f0, f1 = max(f0, f1 + x - fee), max(f1, f0 - x) - return f0 -``` - -### **Java** - ```java class Solution { private Integer[][] f; @@ -148,37 +113,6 @@ class Solution { } ``` -```java -class Solution { - public int maxProfit(int[] prices, int fee) { - int n = prices.length; - int[][] f = new int[n][2]; - f[0][1] = -prices[0]; - for (int i = 1; i < n; ++i) { - f[i][0] = Math.max(f[i - 1][0], f[i - 1][1] + prices[i] - fee); - f[i][1] = Math.max(f[i - 1][1], f[i - 1][0] - prices[i]); - } - return f[n - 1][0]; - } -} -``` - -```java -class Solution { - public int maxProfit(int[] prices, int fee) { - int f0 = 0, f1 = -prices[0]; - for (int i = 1; i < prices.length; ++i) { - int g0 = Math.max(f0, f1 + prices[i] - fee); - f1 = Math.max(f1, f0 - prices[i]); - f0 = g0; - } - return f0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -206,40 +140,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxProfit(vector& prices, int fee) { - int n = prices.size(); - int f[n][2]; - memset(f, 0, sizeof(f)); - f[0][1] = -prices[0]; - for (int i = 1; i < n; ++i) { - f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i] - fee); - f[i][1] = max(f[i - 1][1], f[i - 1][0] - prices[i]); - } - return f[n - 1][0]; - } -}; -``` - -```cpp -class Solution { -public: - int maxProfit(vector& prices, int fee) { - int f0 = 0, f1 = -prices[0]; - for (int i = 1; i < prices.size(); ++i) { - int g0 = max(f0, f1 + prices[i] - fee); - f1 = max(f1, f0 - prices[i]); - f0 = g0; - } - return f0; - } -}; -``` - -### **Go** - ```go func maxProfit(prices []int, fee int) int { n := len(prices) @@ -268,31 +168,6 @@ func maxProfit(prices []int, fee int) int { } ``` -```go -func maxProfit(prices []int, fee int) int { - n := len(prices) - f := make([][2]int, n) - f[0][1] = -prices[0] - for i := 1; i < n; i++ { - f[i][0] = max(f[i-1][0], f[i-1][1]+prices[i]-fee) - f[i][1] = max(f[i-1][1], f[i-1][0]-prices[i]) - } - return f[n-1][0] -} -``` - -```go -func maxProfit(prices []int, fee int) int { - f0, f1 := 0, -prices[0] - for _, x := range prices[1:] { - f0, f1 = max(f0, f1+x-fee), max(f1, f0-x) - } - return f0 -} -``` - -### **TypeScript** - ```ts function maxProfit(prices: number[], fee: number): number { const n = prices.length; @@ -316,6 +191,77 @@ function maxProfit(prices: number[], fee: number): number { } ``` + + +### Solution 2: Dynamic Programming + +We define $f[i][j]$ as the maximum profit that can be obtained up to day $i$ with state $j$. Here, $j$ can take the values $0$ and $1$, representing not holding and holding a stock, respectively. We initialize $f[0][0] = 0$ and $f[0][1] = -prices[0]$. + +When $i \geq 1$, if we do not hold a stock at the current day, then $f[i][0]$ can be obtained by transitioning from $f[i - 1][0]$ and $f[i - 1][1] + prices[i] - fee$, i.e., $f[i][0] = \max(f[i - 1][0], f[i - 1][1] + prices[i] - fee)$. If we hold a stock at the current day, then $f[i][1]$ can be obtained by transitioning from $f[i - 1][1]$ and $f[i - 1][0] - prices[i]$, i.e., $f[i][1] = \max(f[i - 1][1], f[i - 1][0] - prices[i])$. The final answer is $f[n - 1][0]$. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $prices$. + +We notice that the transition of the state $f[i][]$ only depends on $f[i - 1][]$ and $f[i - 2][]$. Therefore, we can use two variables $f_0$ and $f_1$ to replace the array $f$, reducing the space complexity to $O(1)$. + + + +```python +class Solution: + def maxProfit(self, prices: List[int], fee: int) -> int: + n = len(prices) + f = [[0] * 2 for _ in range(n)] + f[0][1] = -prices[0] + for i in range(1, n): + f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i] - fee) + f[i][1] = max(f[i - 1][1], f[i - 1][0] - prices[i]) + return f[n - 1][0] +``` + +```java +class Solution { + public int maxProfit(int[] prices, int fee) { + int n = prices.length; + int[][] f = new int[n][2]; + f[0][1] = -prices[0]; + for (int i = 1; i < n; ++i) { + f[i][0] = Math.max(f[i - 1][0], f[i - 1][1] + prices[i] - fee); + f[i][1] = Math.max(f[i - 1][1], f[i - 1][0] - prices[i]); + } + return f[n - 1][0]; + } +} +``` + +```cpp +class Solution { +public: + int maxProfit(vector& prices, int fee) { + int n = prices.size(); + int f[n][2]; + memset(f, 0, sizeof(f)); + f[0][1] = -prices[0]; + for (int i = 1; i < n; ++i) { + f[i][0] = max(f[i - 1][0], f[i - 1][1] + prices[i] - fee); + f[i][1] = max(f[i - 1][1], f[i - 1][0] - prices[i]); + } + return f[n - 1][0]; + } +}; +``` + +```go +func maxProfit(prices []int, fee int) int { + n := len(prices) + f := make([][2]int, n) + f[0][1] = -prices[0] + for i := 1; i < n; i++ { + f[i][0] = max(f[i-1][0], f[i-1][1]+prices[i]-fee) + f[i][1] = max(f[i-1][1], f[i-1][0]-prices[i]) + } + return f[n-1][0] +} +``` + ```ts function maxProfit(prices: number[], fee: number): number { const n = prices.length; @@ -329,6 +275,60 @@ function maxProfit(prices: number[], fee: number): number { } ``` + + +### Solution 3 + + + +```python +class Solution: + def maxProfit(self, prices: List[int], fee: int) -> int: + f0, f1 = 0, -prices[0] + for x in prices[1:]: + f0, f1 = max(f0, f1 + x - fee), max(f1, f0 - x) + return f0 +``` + +```java +class Solution { + public int maxProfit(int[] prices, int fee) { + int f0 = 0, f1 = -prices[0]; + for (int i = 1; i < prices.length; ++i) { + int g0 = Math.max(f0, f1 + prices[i] - fee); + f1 = Math.max(f1, f0 - prices[i]); + f0 = g0; + } + return f0; + } +} +``` + +```cpp +class Solution { +public: + int maxProfit(vector& prices, int fee) { + int f0 = 0, f1 = -prices[0]; + for (int i = 1; i < prices.size(); ++i) { + int g0 = max(f0, f1 + prices[i] - fee); + f1 = max(f1, f0 - prices[i]); + f0 = g0; + } + return f0; + } +}; +``` + +```go +func maxProfit(prices []int, fee int) int { + f0, f1 := 0, -prices[0] + for _, x := range prices[1:] { + f0, f1 = max(f0, f1+x-fee), max(f1, f0-x) + } + return f0 +} +``` + ```ts function maxProfit(prices: number[], fee: number): number { const n = prices.length; @@ -340,10 +340,6 @@ function maxProfit(prices: number[], fee: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0715.Range Module/README.md b/solution/0700-0799/0715.Range Module/README.md index 496c9e6a7c642..2c38af4591fa1 100644 --- a/solution/0700-0799/0715.Range Module/README.md +++ b/solution/0700-0799/0715.Range Module/README.md @@ -50,9 +50,7 @@ rangeModule.queryRange(16, 17); 返回 true (尽管执行了删除操作,区 ## 解法 - - -**方法一:线段树** +### 方法一:线段树 根据题目描述,我们需要维护一个区间集合,支持区间的添加、删除和查询操作。对于区间的添加和删除操作,我们可以使用线段树来维护区间集合。 @@ -69,10 +67,6 @@ rangeModule.queryRange(16, 17); 返回 true (尽管执行了删除操作,区 -### **Python3** - - - ```python class Node: __slots__ = ['left', 'right', 'add', 'v'] @@ -159,10 +153,6 @@ class RangeModule: # obj.removeRange(left,right) ``` -### **Java** - - - ```java class Node { Node left; @@ -267,8 +257,6 @@ class RangeModule { */ ``` -### **C++** - ```cpp template class CachedObj { @@ -396,8 +384,6 @@ public: */ ``` -### **Go** - ```go const N int = 1e9 @@ -502,8 +488,6 @@ func (this *RangeModule) RemoveRange(left int, right int) { */ ``` -### **TypeScript** - ```ts class Node { left: Node | null; @@ -642,10 +626,6 @@ class RangeModule { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0715.Range Module/README_EN.md b/solution/0700-0799/0715.Range Module/README_EN.md index a43325df771ab..ea994c6a20c8d 100644 --- a/solution/0700-0799/0715.Range Module/README_EN.md +++ b/solution/0700-0799/0715.Range Module/README_EN.md @@ -46,7 +46,7 @@ rangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is st ## Solutions -**Solution 1: Segment Tree** +### Solution 1: Segment Tree According to the problem description, we need to maintain a set of intervals, supporting operations of interval addition, deletion, and query. For the addition and deletion of intervals, we can use a segment tree to maintain the set of intervals. @@ -63,8 +63,6 @@ In terms of time complexity, the time complexity of each operation is $O(\log n) -### **Python3** - ```python class Node: __slots__ = ['left', 'right', 'add', 'v'] @@ -151,8 +149,6 @@ class RangeModule: # obj.removeRange(left,right) ``` -### **Java** - ```java class Node { Node left; @@ -257,8 +253,6 @@ class RangeModule { */ ``` -### **C++** - ```cpp template class CachedObj { @@ -386,8 +380,6 @@ public: */ ``` -### **Go** - ```go const N int = 1e9 @@ -492,8 +484,6 @@ func (this *RangeModule) RemoveRange(left int, right int) { */ ``` -### **TypeScript** - ```ts class Node { left: Node | null; @@ -632,10 +622,6 @@ class RangeModule { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0716.Max Stack/README.md b/solution/0700-0799/0716.Max Stack/README.md index eb978f922d629..174f9c6114bbb 100644 --- a/solution/0700-0799/0716.Max Stack/README.md +++ b/solution/0700-0799/0716.Max Stack/README.md @@ -63,9 +63,7 @@ stk.top(); // 返回 5,[5] - 栈没有改变 ## 解法 - - -**方法一:双向链表 + 有序集合** +### 方法一:双向链表 + 有序集合 使用双向链表存储栈中的元素,使用有序集合存储栈中的元素,有序集合中的元素按照从小到大的顺序存储,每个元素都对应着双向链表中的一个节点。 @@ -79,10 +77,6 @@ stk.top(); // 返回 5,[5] - 栈没有改变 -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -157,10 +151,6 @@ class MaxStack: # param_5 = obj.popMax() ``` -### **Java** - - - ```java class Node { public int val; @@ -260,8 +250,6 @@ class MaxStack { */ ``` -### **C++** - ```cpp class MaxStack { public: @@ -315,10 +303,6 @@ private: */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0716.Max Stack/README_EN.md b/solution/0700-0799/0716.Max Stack/README_EN.md index a934d26f4cbcc..33f823184429f 100644 --- a/solution/0700-0799/0716.Max Stack/README_EN.md +++ b/solution/0700-0799/0716.Max Stack/README_EN.md @@ -53,9 +53,9 @@ stk.top(); // return 5, [5] the stack did not change ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedList @@ -131,8 +131,6 @@ class MaxStack: # param_5 = obj.popMax() ``` -### **Java** - ```java class Node { public int val; @@ -232,8 +230,6 @@ class MaxStack { */ ``` -### **C++** - ```cpp class MaxStack { public: @@ -287,10 +283,6 @@ private: */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0717.1-bit and 2-bit Characters/README.md b/solution/0700-0799/0717.1-bit and 2-bit Characters/README.md index 8bf5b63b5dad7..99fb3a5774c33 100644 --- a/solution/0700-0799/0717.1-bit and 2-bit Characters/README.md +++ b/solution/0700-0799/0717.1-bit and 2-bit Characters/README.md @@ -46,14 +46,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def isOneBitCharacter(self, bits: List[int]) -> bool: @@ -63,10 +59,6 @@ class Solution: return i == n - 1 ``` -### **Java** - - - ```java class Solution { public boolean isOneBitCharacter(int[] bits) { @@ -79,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -92,8 +82,6 @@ public: }; ``` -### **Go** - ```go func isOneBitCharacter(bits []int) bool { i, n := 0, len(bits) @@ -104,8 +92,6 @@ func isOneBitCharacter(bits []int) bool { } ``` -### **JavaScript** - ```js /** * @param {number[]} bits @@ -121,10 +107,6 @@ var isOneBitCharacter = function (bits) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0717.1-bit and 2-bit Characters/README_EN.md b/solution/0700-0799/0717.1-bit and 2-bit Characters/README_EN.md index 48a240dec1dfb..875b392495bdf 100644 --- a/solution/0700-0799/0717.1-bit and 2-bit Characters/README_EN.md +++ b/solution/0700-0799/0717.1-bit and 2-bit Characters/README_EN.md @@ -42,9 +42,9 @@ So the last character is not one-bit character. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return i == n - 1 ``` -### **Java** - ```java class Solution { public boolean isOneBitCharacter(int[] bits) { @@ -69,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -82,8 +78,6 @@ public: }; ``` -### **Go** - ```go func isOneBitCharacter(bits []int) bool { i, n := 0, len(bits) @@ -94,8 +88,6 @@ func isOneBitCharacter(bits []int) bool { } ``` -### **JavaScript** - ```js /** * @param {number[]} bits @@ -111,10 +103,6 @@ var isOneBitCharacter = function (bits) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0718.Maximum Length of Repeated Subarray/README.md b/solution/0700-0799/0718.Maximum Length of Repeated Subarray/README.md index 5b6df31f58df1..dbe440dd164ea 100644 --- a/solution/0700-0799/0718.Maximum Length of Repeated Subarray/README.md +++ b/solution/0700-0799/0718.Maximum Length of Repeated Subarray/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示以 $nums1[i - 1]$ 和 $nums2[j - 1]$ 结尾的最长公共子数组的长度,那么我们可以得到状态转移方程: @@ -56,10 +54,6 @@ $$ -### **Python3** - - - ```python class Solution: def findLength(self, nums1: List[int], nums2: List[int]) -> int: @@ -74,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int findLength(int[] nums1, int[] nums2) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func findLength(nums1 []int, nums2 []int) (ans int) { m, n := len(nums1), len(nums2) @@ -143,8 +129,6 @@ func findLength(nums1 []int, nums2 []int) (ans int) { } ``` -### **TypeScript** - ```ts function findLength(nums1: number[], nums2: number[]): number { const m = nums1.length; @@ -163,8 +147,6 @@ function findLength(nums1: number[], nums2: number[]): number { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums1 @@ -188,10 +170,6 @@ var findLength = function (nums1, nums2) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0718.Maximum Length of Repeated Subarray/README_EN.md b/solution/0700-0799/0718.Maximum Length of Repeated Subarray/README_EN.md index 91b00b4f32d19..fcfd54ec6b0d4 100644 --- a/solution/0700-0799/0718.Maximum Length of Repeated Subarray/README_EN.md +++ b/solution/0700-0799/0718.Maximum Length of Repeated Subarray/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int findLength(int[] nums1, int[] nums2) { @@ -73,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +91,6 @@ public: }; ``` -### **Go** - ```go func findLength(nums1 []int, nums2 []int) (ans int) { m, n := len(nums1), len(nums2) @@ -118,8 +112,6 @@ func findLength(nums1 []int, nums2 []int) (ans int) { } ``` -### **TypeScript** - ```ts function findLength(nums1: number[], nums2: number[]): number { const m = nums1.length; @@ -138,8 +130,6 @@ function findLength(nums1: number[], nums2: number[]): number { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums1 @@ -163,10 +153,6 @@ var findLength = function (nums1, nums2) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0719.Find K-th Smallest Pair Distance/README.md b/solution/0700-0799/0719.Find K-th Smallest Pair Distance/README.md index 475ff333ed9d0..28e3ce2345e36 100644 --- a/solution/0700-0799/0719.Find K-th Smallest Pair Distance/README.md +++ b/solution/0700-0799/0719.Find K-th Smallest Pair Distance/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 先对 $nums$ 数组进行排序,然后在 $[0, nums[n-1]-nums[0]]$ 范围内二分枚举数对距离 $dist$,若 $nums$ 中数对距离小于等于 $dist$ 的数量 $cnt$ 大于等于 $k$,则尝试缩小 $dist$,否则尝试扩大 $dist$。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def smallestDistancePair(self, nums: List[int], k: int) -> int: @@ -80,10 +74,6 @@ class Solution: return bisect_left(range(nums[-1] - nums[0]), k, key=count) ``` -### **Java** - - - ```java class Solution { public int smallestDistancePair(int[] nums, int k) { @@ -120,37 +110,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function smallestDistancePair(nums: number[], k: number): number { - nums.sort((a, b) => a - b); - const n = nums.length; - let left = 0, - right = nums[n - 1] - nums[0]; - while (left < right) { - let mid = (left + right) >> 1; - let count = 0, - i = 0; - for (let j = 0; j < n; j++) { - // 索引[i, j]距离nums[j]的距离<=mid - while (nums[j] - nums[i] > mid) { - i++; - } - count += j - i; - } - if (count >= k) { - right = mid; - } else { - left = mid + 1; - } - } - return left; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -179,8 +138,6 @@ public: }; ``` -### **Go** - ```go func smallestDistancePair(nums []int, k int) int { sort.Ints(nums) @@ -215,10 +172,33 @@ func smallestDistancePair(nums []int, k int) int { } ``` -### **...** - -``` - +```ts +function smallestDistancePair(nums: number[], k: number): number { + nums.sort((a, b) => a - b); + const n = nums.length; + let left = 0, + right = nums[n - 1] - nums[0]; + while (left < right) { + let mid = (left + right) >> 1; + let count = 0, + i = 0; + for (let j = 0; j < n; j++) { + // 索引[i, j]距离nums[j]的距离<=mid + while (nums[j] - nums[i] > mid) { + i++; + } + count += j - i; + } + if (count >= k) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +} ``` + + diff --git a/solution/0700-0799/0719.Find K-th Smallest Pair Distance/README_EN.md b/solution/0700-0799/0719.Find K-th Smallest Pair Distance/README_EN.md index 5b880cebd8bfc..f56cd9b900d2f 100644 --- a/solution/0700-0799/0719.Find K-th Smallest Pair Distance/README_EN.md +++ b/solution/0700-0799/0719.Find K-th Smallest Pair Distance/README_EN.md @@ -47,9 +47,9 @@ Then the 1st smallest distance pair is (1,1), and its distance is 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return bisect_left(range(nums[-1] - nums[0]), k, key=count) ``` -### **Java** - ```java class Solution { public int smallestDistancePair(int[] nums, int k) { @@ -104,36 +102,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function smallestDistancePair(nums: number[], k: number): number { - nums.sort((a, b) => a - b); - const n = nums.length; - let left = 0, - right = nums[n - 1] - nums[0]; - while (left < right) { - let mid = (left + right) >> 1; - let count = 0, - i = 0; - for (let j = 0; j < n; j++) { - while (nums[j] - nums[i] > mid) { - i++; - } - count += j - i; - } - if (count >= k) { - right = mid; - } else { - left = mid + 1; - } - } - return left; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -162,8 +130,6 @@ public: }; ``` -### **Go** - ```go func smallestDistancePair(nums []int, k int) int { sort.Ints(nums) @@ -198,10 +164,33 @@ func smallestDistancePair(nums []int, k int) int { } ``` -### **...** - -``` - +```ts +function smallestDistancePair(nums: number[], k: number): number { + nums.sort((a, b) => a - b); + const n = nums.length; + let left = 0, + right = nums[n - 1] - nums[0]; + while (left < right) { + let mid = (left + right) >> 1; + let count = 0, + i = 0; + for (let j = 0; j < n; j++) { + // 索引[i, j]距离nums[j]的距离<=mid + while (nums[j] - nums[i] > mid) { + i++; + } + count += j - i; + } + if (count >= k) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +} ``` + + diff --git a/solution/0700-0799/0720.Longest Word in Dictionary/README.md b/solution/0700-0799/0720.Longest Word in Dictionary/README.md index ec0657e2e51cf..bd00bccf8d585 100644 --- a/solution/0700-0799/0720.Longest Word in Dictionary/README.md +++ b/solution/0700-0799/0720.Longest Word in Dictionary/README.md @@ -40,22 +40,12 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 用哈希表存放所有单词。遍历这些单词,找出**长度最长且字典序最小**的单词。 -**方法二:排序** - -优先返回符合条件、**长度最长且字典序最小**的单词,那么可以进行依照该规则,先对 `words` 进行排序,免去多个结果之间的比较。 - -### **Python3** - - - ```python class Solution: def longestWord(self, words: List[str]) -> str: @@ -71,10 +61,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private Set s; @@ -108,59 +94,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function longestWord(words: string[]): string { - words.sort((a, b) => { - const n = a.length; - const m = b.length; - if (n === m) { - return a < b ? -1 : 1; - } - return m - n; - }); - for (const word of words) { - let isPass = true; - for (let i = 1; i <= word.length; i++) { - if (!words.includes(word.slice(0, i))) { - isPass = false; - break; - } - } - if (isPass) { - return word; - } - } - return ''; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn longest_word(mut words: Vec) -> String { - words.sort_unstable_by(|a, b| (b.len(), a).cmp(&(a.len(), b))); - for word in words.iter() { - let mut is_pass = true; - for i in 1..=word.len() { - if !words.contains(&word[..i].to_string()) { - is_pass = false; - break; - } - } - if is_pass { - return word.clone(); - } - } - String::new() - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -190,8 +123,6 @@ public: }; ``` -### **Go** - ```go func longestWord(words []string) string { s := make(map[string]bool) @@ -222,10 +153,57 @@ func longestWord(words []string) string { } ``` -### **...** - +```ts +function longestWord(words: string[]): string { + words.sort((a, b) => { + const n = a.length; + const m = b.length; + if (n === m) { + return a < b ? -1 : 1; + } + return m - n; + }); + for (const word of words) { + let isPass = true; + for (let i = 1; i <= word.length; i++) { + if (!words.includes(word.slice(0, i))) { + isPass = false; + break; + } + } + if (isPass) { + return word; + } + } + return ''; +} ``` +```rust +impl Solution { + pub fn longest_word(mut words: Vec) -> String { + words.sort_unstable_by(|a, b| (b.len(), a).cmp(&(a.len(), b))); + for word in words.iter() { + let mut is_pass = true; + for i in 1..=word.len() { + if !words.contains(&word[..i].to_string()) { + is_pass = false; + break; + } + } + if is_pass { + return word.clone(); + } + } + String::new() + } +} ``` + +### 方法二:排序 + +优先返回符合条件、**长度最长且字典序最小**的单词,那么可以进行依照该规则,先对 `words` 进行排序,免去多个结果之间的比较。 + + diff --git a/solution/0700-0799/0720.Longest Word in Dictionary/README_EN.md b/solution/0700-0799/0720.Longest Word in Dictionary/README_EN.md index 1e9f7dfc9fc39..b1d723cb989b0 100644 --- a/solution/0700-0799/0720.Longest Word in Dictionary/README_EN.md +++ b/solution/0700-0799/0720.Longest Word in Dictionary/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private Set s; @@ -92,59 +90,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function longestWord(words: string[]): string { - words.sort((a, b) => { - const n = a.length; - const m = b.length; - if (n === m) { - return a < b ? -1 : 1; - } - return m - n; - }); - for (const word of words) { - let isPass = true; - for (let i = 1; i <= word.length; i++) { - if (!words.includes(word.slice(0, i))) { - isPass = false; - break; - } - } - if (isPass) { - return word; - } - } - return ''; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn longest_word(mut words: Vec) -> String { - words.sort_unstable_by(|a, b| (b.len(), a).cmp(&(a.len(), b))); - for word in words.iter() { - let mut is_pass = true; - for i in 1..=word.len() { - if !words.contains(&word[..i].to_string()) { - is_pass = false; - break; - } - } - if is_pass { - return word.clone(); - } - } - String::new() - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -174,8 +119,6 @@ public: }; ``` -### **Go** - ```go func longestWord(words []string) string { s := make(map[string]bool) @@ -206,10 +149,53 @@ func longestWord(words []string) string { } ``` -### **...** - +```ts +function longestWord(words: string[]): string { + words.sort((a, b) => { + const n = a.length; + const m = b.length; + if (n === m) { + return a < b ? -1 : 1; + } + return m - n; + }); + for (const word of words) { + let isPass = true; + for (let i = 1; i <= word.length; i++) { + if (!words.includes(word.slice(0, i))) { + isPass = false; + break; + } + } + if (isPass) { + return word; + } + } + return ''; +} ``` +```rust +impl Solution { + pub fn longest_word(mut words: Vec) -> String { + words.sort_unstable_by(|a, b| (b.len(), a).cmp(&(a.len(), b))); + for word in words.iter() { + let mut is_pass = true; + for i in 1..=word.len() { + if !words.contains(&word[..i].to_string()) { + is_pass = false; + break; + } + } + if is_pass { + return word.clone(); + } + } + String::new() + } +} ``` + + diff --git a/solution/0700-0799/0721.Accounts Merge/README.md b/solution/0700-0799/0721.Accounts Merge/README.md index 1b5eb0adb1f63..f874b8e8f50f0 100644 --- a/solution/0700-0799/0721.Accounts Merge/README.md +++ b/solution/0700-0799/0721.Accounts Merge/README.md @@ -47,83 +47,10 @@ ## 解法 - - -并查集。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` - -对于本题,初始每个 account 是一个独立的集合。遍历 accounts 列表,若遇到相同的 email,则将两账户进行合并,遍历完毕得到并查集。 - -接着对每个集合进行中的所有账户邮箱进行合并排序,最后返回账户名称以及对应的邮箱列表。 +### 方法一 -### **Python3** - - - ```python class Solution: def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]: @@ -155,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -210,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -261,10 +182,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0721.Accounts Merge/README_EN.md b/solution/0700-0799/0721.Accounts Merge/README_EN.md index f2ba7f740f3c6..950f5857e83ec 100644 --- a/solution/0700-0799/0721.Accounts Merge/README_EN.md +++ b/solution/0700-0799/0721.Accounts Merge/README_EN.md @@ -43,9 +43,9 @@ We could return these lists in any order, for example the answer [['Mary' ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] p; @@ -131,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,10 +178,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0722.Remove Comments/README.md b/solution/0700-0799/0722.Remove Comments/README.md index a567d904ba43f..77e03196f5b56 100644 --- a/solution/0700-0799/0722.Remove Comments/README.md +++ b/solution/0700-0799/0722.Remove Comments/README.md @@ -89,9 +89,7 @@ a = b + c; ## 解法 - - -**方法一:分情况讨论** +### 方法一:分情况讨论 我们用一个变量 $blockComment$ 来表示当前是否处于块注释中,初始时 $blockComment$ 为 `false`;用一个变量 $t$ 来存储当前行的有效字符。 @@ -107,10 +105,6 @@ a = b + c; -### **Python3** - - - ```python class Solution: def removeComments(self, source: List[str]) -> List[str]: @@ -139,10 +133,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List removeComments(String[] source) { @@ -178,8 +168,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -216,8 +204,6 @@ public: }; ``` -### **Go** - ```go func removeComments(source []string) (ans []string) { t := []byte{} @@ -250,8 +236,6 @@ func removeComments(source []string) (ans []string) { } ``` -### **TypeScript** - ```ts function removeComments(source: string[]): string[] { const ans: string[] = []; @@ -285,8 +269,6 @@ function removeComments(source: string[]): string[] { } ``` -### **Rust** - ```rust impl Solution { pub fn remove_comments(source: Vec) -> Vec { @@ -327,10 +309,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0722.Remove Comments/README_EN.md b/solution/0700-0799/0722.Remove Comments/README_EN.md index 56af4d0ae2386..229c8a85c9d05 100644 --- a/solution/0700-0799/0722.Remove Comments/README_EN.md +++ b/solution/0700-0799/0722.Remove Comments/README_EN.md @@ -85,9 +85,9 @@ a = b + c; ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -117,8 +117,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List removeComments(String[] source) { @@ -154,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -192,8 +188,6 @@ public: }; ``` -### **Go** - ```go func removeComments(source []string) (ans []string) { t := []byte{} @@ -226,8 +220,6 @@ func removeComments(source []string) (ans []string) { } ``` -### **TypeScript** - ```ts function removeComments(source: string[]): string[] { const ans: string[] = []; @@ -261,8 +253,6 @@ function removeComments(source: string[]): string[] { } ``` -### **Rust** - ```rust impl Solution { pub fn remove_comments(source: Vec) -> Vec { @@ -303,10 +293,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0723.Candy Crush/README.md b/solution/0700-0799/0723.Candy Crush/README.md index 8f225798a3d58..81f52d7cdb1ad 100644 --- a/solution/0700-0799/0723.Candy Crush/README.md +++ b/solution/0700-0799/0723.Candy Crush/README.md @@ -54,16 +54,10 @@ ## 解法 - - -循环消除,先标记每一行需要消除的元素,再标记每一列需要消除的元素(使用元素的负相反数进行标记),然后执行消除。 +### 方法一 -### **Python3** - - - ```python class Solution: def candyCrush(self, board: List[List[int]]) -> List[List[int]]: @@ -106,10 +100,6 @@ class Solution: return board ``` -### **Java** - - - ```java class Solution { public int[][] candyCrush(int[][] board) { @@ -156,8 +146,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -203,8 +191,6 @@ public: }; ``` -### **Go** - ```go func candyCrush(board [][]int) [][]int { m, n := len(board), len(board[0]) @@ -256,10 +242,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0723.Candy Crush/README_EN.md b/solution/0700-0799/0723.Candy Crush/README_EN.md index 307d063ed3b5f..f3f871cf53106 100644 --- a/solution/0700-0799/0723.Candy Crush/README_EN.md +++ b/solution/0700-0799/0723.Candy Crush/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -92,8 +92,6 @@ class Solution: return board ``` -### **Java** - ```java class Solution { public int[][] candyCrush(int[][] board) { @@ -140,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -187,8 +183,6 @@ public: }; ``` -### **Go** - ```go func candyCrush(board [][]int) [][]int { m, n := len(board), len(board[0]) @@ -240,10 +234,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0724.Find Pivot Index/README.md b/solution/0700-0799/0724.Find Pivot Index/README.md index a5f8c74987594..f992042d32910 100644 --- a/solution/0700-0799/0724.Find Pivot Index/README.md +++ b/solution/0700-0799/0724.Find Pivot Index/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:前缀和** +### 方法一:前缀和 我们定义变量 $left$ 表示数组 `nums` 中下标 $i$ 左侧元素之和,变量 $right$ 表示数组 `nums` 中下标 $i$ 右侧元素之和。初始时 $left = 0$, $right = \sum_{i = 0}^{n - 1} nums[i]$。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def pivotIndex(self, nums: List[int]) -> int: @@ -95,10 +89,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int pivotIndex(int[] nums) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func pivotIndex(nums []int) int { var left, right int @@ -153,29 +139,6 @@ func pivotIndex(nums []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var pivotIndex = function (nums) { - let left = 0, - right = nums.reduce((a, b) => a + b); - for (let i = 0; i < nums.length; ++i) { - right -= nums[i]; - if (left == right) { - return i; - } - left += nums[i]; - } - return -1; -}; -``` - -### **TypeScript** - ```ts function pivotIndex(nums: number[]): number { let left = 0, @@ -191,8 +154,6 @@ function pivotIndex(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn pivot_index(nums: Vec) -> i32 { @@ -209,10 +170,25 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums + * @return {number} + */ +var pivotIndex = function (nums) { + let left = 0, + right = nums.reduce((a, b) => a + b); + for (let i = 0; i < nums.length; ++i) { + right -= nums[i]; + if (left == right) { + return i; + } + left += nums[i]; + } + return -1; +}; ``` + + diff --git a/solution/0700-0799/0724.Find Pivot Index/README_EN.md b/solution/0700-0799/0724.Find Pivot Index/README_EN.md index 95486d95477da..819f42af76fb8 100644 --- a/solution/0700-0799/0724.Find Pivot Index/README_EN.md +++ b/solution/0700-0799/0724.Find Pivot Index/README_EN.md @@ -56,9 +56,9 @@ Right sum = nums[1] + nums[2] = 1 + -1 = 0 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int pivotIndex(int[] nums) { @@ -90,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +105,6 @@ public: }; ``` -### **Go** - ```go func pivotIndex(nums []int) int { var left, right int @@ -128,29 +122,6 @@ func pivotIndex(nums []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var pivotIndex = function (nums) { - let left = 0, - right = nums.reduce((a, b) => a + b); - for (let i = 0; i < nums.length; ++i) { - right -= nums[i]; - if (left == right) { - return i; - } - left += nums[i]; - } - return -1; -}; -``` - -### **TypeScript** - ```ts function pivotIndex(nums: number[]): number { let left = 0, @@ -166,8 +137,6 @@ function pivotIndex(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn pivot_index(nums: Vec) -> i32 { @@ -184,10 +153,25 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums + * @return {number} + */ +var pivotIndex = function (nums) { + let left = 0, + right = nums.reduce((a, b) => a + b); + for (let i = 0; i < nums.length; ++i) { + right -= nums[i]; + if (left == right) { + return i; + } + left += nums[i]; + } + return -1; +}; ``` + + diff --git a/solution/0700-0799/0725.Split Linked List in Parts/README.md b/solution/0700-0799/0725.Split Linked List in Parts/README.md index 94006e01f2faf..1bd2697b361cc 100644 --- a/solution/0700-0799/0725.Split Linked List in Parts/README.md +++ b/solution/0700-0799/0725.Split Linked List in Parts/README.md @@ -46,20 +46,10 @@ ## 解法 - - -先遍历链表,统计结点总个数。 - -接着将链表拆分,`width` 表示每一部分至少含有的结点个数,而 `remainder` 表示前 `remainder` 部分,每一部分多出一个数。 - -然后遍历链表,依次拆出每一部分,添加到结果数组 `res` 即可。 +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -88,10 +78,6 @@ class Solution: return res ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -133,10 +119,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0725.Split Linked List in Parts/README_EN.md b/solution/0700-0799/0725.Split Linked List in Parts/README_EN.md index e4c0e4da14f28..6873c2cfbbfcf 100644 --- a/solution/0700-0799/0725.Split Linked List in Parts/README_EN.md +++ b/solution/0700-0799/0725.Split Linked List in Parts/README_EN.md @@ -43,9 +43,9 @@ The input has been split into consecutive parts with size difference at most 1, ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -75,8 +75,6 @@ class Solution: return res ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -94,6 +92,8 @@ class Solution { ++n; cur = cur.next; } + // width 表示每一部分至少含有的结点个数 + // remainder 表示前 remainder 部分,每一部分多出一个数 int width = n / k, remainder = n % k; ListNode[] res = new ListNode[k]; cur = root; @@ -116,10 +116,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0726.Number of Atoms/README.md b/solution/0700-0799/0726.Number of Atoms/README.md index e965ca3666ffe..c5cf13ea21e9e 100644 --- a/solution/0700-0799/0726.Number of Atoms/README.md +++ b/solution/0700-0799/0726.Number of Atoms/README.md @@ -68,30 +68,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0700-0799/0726.Number of Atoms/README_EN.md b/solution/0700-0799/0726.Number of Atoms/README_EN.md index 8d36261c973f4..b093e47acee50 100644 --- a/solution/0700-0799/0726.Number of Atoms/README_EN.md +++ b/solution/0700-0799/0726.Number of Atoms/README_EN.md @@ -66,24 +66,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0700-0799/0727.Minimum Window Subsequence/README.md b/solution/0700-0799/0727.Minimum Window Subsequence/README.md index 853d53d4d04f2..21a2d50edf24e 100644 --- a/solution/0700-0799/0727.Minimum Window Subsequence/README.md +++ b/solution/0700-0799/0727.Minimum Window Subsequence/README.md @@ -33,9 +33,7 @@ S = "abcdebdde", T = "bde" ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示字符串 $s1$ 的前 $i$ 个字符包含字符串 $s2$ 的前 $j$ 个字符时的最短子串的起始位置,如果不存在则为 $0$。 @@ -55,10 +53,6 @@ $$ -### **Python3** - - - ```python class Solution: def minWindow(self, s1: str, s2: str) -> str: @@ -80,10 +74,6 @@ class Solution: return "" if k > m else s1[p : p + k] ``` -### **Java** - - - ```java class Solution { public String minWindow(String s1, String s2) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func minWindow(s1 string, s2 string) string { m, n := len(s1), len(s2) @@ -185,8 +171,6 @@ func minWindow(s1 string, s2 string) string { } ``` -### **TypeScript** - ```ts function minWindow(s1: string, s2: string): string { const m = s1.length; @@ -218,10 +202,6 @@ function minWindow(s1: string, s2: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0727.Minimum Window Subsequence/README_EN.md b/solution/0700-0799/0727.Minimum Window Subsequence/README_EN.md index d87749c080544..ed9511c733667 100644 --- a/solution/0700-0799/0727.Minimum Window Subsequence/README_EN.md +++ b/solution/0700-0799/0727.Minimum Window Subsequence/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return "" if k > m else s1[p : p + k] ``` -### **Java** - ```java class Solution { public String minWindow(String s1, String s2) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +122,6 @@ public: }; ``` -### **Go** - ```go func minWindow(s1 string, s2 string) string { m, n := len(s1), len(s2) @@ -165,8 +159,6 @@ func minWindow(s1 string, s2 string) string { } ``` -### **TypeScript** - ```ts function minWindow(s1: string, s2: string): string { const m = s1.length; @@ -198,10 +190,6 @@ function minWindow(s1: string, s2: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0728.Self Dividing Numbers/README.md b/solution/0700-0799/0728.Self Dividing Numbers/README.md index bf8fd6126f298..95b2ba43e3a43 100644 --- a/solution/0700-0799/0728.Self Dividing Numbers/README.md +++ b/solution/0700-0799/0728.Self Dividing Numbers/README.md @@ -42,14 +42,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def selfDividingNumbers(self, left: int, right: int) -> List[int]: @@ -60,10 +56,6 @@ class Solution: ] ``` -### **Java** - - - ```java class Solution { public List selfDividingNumbers(int left, int right) { @@ -88,36 +80,6 @@ class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn self_dividing_numbers(left: i32, right: i32) -> Vec { - let mut res = vec![]; - for i in left..=right { - let mut num = i; - if ( - loop { - if num == 0 { - break true; - } - let j = num % 10; - if j == 0 || i % j != 0 { - break false; - } - num /= 10; - } - ) { - res.push(i); - } - } - res - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -139,8 +101,6 @@ public: }; ``` -### **Go** - ```go func selfDividingNumbers(left int, right int) []int { check := func(num int) bool { @@ -163,10 +123,32 @@ func selfDividingNumbers(left int, right int) []int { } ``` -### **...** - -``` - +```rust +impl Solution { + pub fn self_dividing_numbers(left: i32, right: i32) -> Vec { + let mut res = vec![]; + for i in left..=right { + let mut num = i; + if ( + loop { + if num == 0 { + break true; + } + let j = num % 10; + if j == 0 || i % j != 0 { + break false; + } + num /= 10; + } + ) { + res.push(i); + } + } + res + } +} ``` + + diff --git a/solution/0700-0799/0728.Self Dividing Numbers/README_EN.md b/solution/0700-0799/0728.Self Dividing Numbers/README_EN.md index 2366c132f4aec..70a19dd1622df 100644 --- a/solution/0700-0799/0728.Self Dividing Numbers/README_EN.md +++ b/solution/0700-0799/0728.Self Dividing Numbers/README_EN.md @@ -31,9 +31,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -45,8 +45,6 @@ class Solution: ] ``` -### **Java** - ```java class Solution { public List selfDividingNumbers(int left, int right) { @@ -71,36 +69,6 @@ class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn self_dividing_numbers(left: i32, right: i32) -> Vec { - let mut res = vec![]; - for i in left..=right { - let mut num = i; - if ( - loop { - if num == 0 { - break true; - } - let j = num % 10; - if j == 0 || i % j != 0 { - break false; - } - num /= 10; - } - ) { - res.push(i); - } - } - res - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -122,8 +90,6 @@ public: }; ``` -### **Go** - ```go func selfDividingNumbers(left int, right int) []int { check := func(num int) bool { @@ -146,10 +112,32 @@ func selfDividingNumbers(left int, right int) []int { } ``` -### **...** - -``` - +```rust +impl Solution { + pub fn self_dividing_numbers(left: i32, right: i32) -> Vec { + let mut res = vec![]; + for i in left..=right { + let mut num = i; + if ( + loop { + if num == 0 { + break true; + } + let j = num % 10; + if j == 0 || i % j != 0 { + break false; + } + num /= 10; + } + ) { + res.push(i); + } + } + res + } +} ``` + + diff --git a/solution/0700-0799/0729.My Calendar I/README.md b/solution/0700-0799/0729.My Calendar I/README.md index ecd5be5e996eb..b0d57c4ffa680 100644 --- a/solution/0700-0799/0729.My Calendar I/README.md +++ b/solution/0700-0799/0729.My Calendar I/README.md @@ -47,14 +47,10 @@ myCalendar.book(20, 30); // return True ,这个日程安排可以添加到日 ## 解法 - +### 方法一 -### **Python3** - - - ```python from sortedcontainers import SortedDict @@ -76,10 +72,6 @@ class MyCalendar: # param_1 = obj.book(start,end) ``` -### **Java** - - - ```java import java.util.Map; import java.util.TreeMap; @@ -111,39 +103,6 @@ class MyCalendar { */ ``` -### **Go** - -```go -type MyCalendar struct { - rbt *redblacktree.Tree -} - -func Constructor() MyCalendar { - return MyCalendar{ - rbt: redblacktree.NewWithIntComparator(), - } -} - -func (this *MyCalendar) Book(start int, end int) bool { - if p, ok := this.rbt.Floor(start); ok && p.Value.(int) > start { - return false - } - if p, ok := this.rbt.Ceiling(start); ok && p.Key.(int) < end { - return false - } - this.rbt.Put(start, end) - return true -} - -/** - * Your MyCalendar object will be instantiated and called as such: - * obj := Constructor(); - * param_1 := obj.Book(start,end); - */ -``` - -### **C++** - ```cpp class MyCalendar { public: @@ -175,7 +134,34 @@ public: */ ``` -### **TypeScript** +```go +type MyCalendar struct { + rbt *redblacktree.Tree +} + +func Constructor() MyCalendar { + return MyCalendar{ + rbt: redblacktree.NewWithIntComparator(), + } +} + +func (this *MyCalendar) Book(start int, end int) bool { + if p, ok := this.rbt.Floor(start); ok && p.Value.(int) > start { + return false + } + if p, ok := this.rbt.Ceiling(start); ok && p.Key.(int) < end { + return false + } + this.rbt.Put(start, end) + return true +} + +/** + * Your MyCalendar object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Book(start,end); + */ +``` ```ts class MyCalendar { @@ -204,8 +190,6 @@ class MyCalendar { */ ``` -### **Rust** - ```rust use std::collections::BTreeMap; @@ -246,10 +230,6 @@ impl MyCalendar { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0729.My Calendar I/README_EN.md b/solution/0700-0799/0729.My Calendar I/README_EN.md index 54d5bfc8b6262..500b285947c58 100644 --- a/solution/0700-0799/0729.My Calendar I/README_EN.md +++ b/solution/0700-0799/0729.My Calendar I/README_EN.md @@ -43,9 +43,9 @@ myCalendar.book(20, 30); // return True, The event can be booked, as the first e ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedDict @@ -68,8 +68,6 @@ class MyCalendar: # param_1 = obj.book(start,end) ``` -### **Java** - ```java import java.util.Map; import java.util.TreeMap; @@ -101,39 +99,6 @@ class MyCalendar { */ ``` -### **Go** - -```go -type MyCalendar struct { - rbt *redblacktree.Tree -} - -func Constructor() MyCalendar { - return MyCalendar{ - rbt: redblacktree.NewWithIntComparator(), - } -} - -func (this *MyCalendar) Book(start int, end int) bool { - if p, ok := this.rbt.Floor(start); ok && p.Value.(int) > start { - return false - } - if p, ok := this.rbt.Ceiling(start); ok && p.Key.(int) < end { - return false - } - this.rbt.Put(start, end) - return true -} - -/** - * Your MyCalendar object will be instantiated and called as such: - * obj := Constructor(); - * param_1 := obj.Book(start,end); - */ -``` - -### **C++** - ```cpp class MyCalendar { public: @@ -165,7 +130,34 @@ public: */ ``` -### **TypeScript** +```go +type MyCalendar struct { + rbt *redblacktree.Tree +} + +func Constructor() MyCalendar { + return MyCalendar{ + rbt: redblacktree.NewWithIntComparator(), + } +} + +func (this *MyCalendar) Book(start int, end int) bool { + if p, ok := this.rbt.Floor(start); ok && p.Value.(int) > start { + return false + } + if p, ok := this.rbt.Ceiling(start); ok && p.Key.(int) < end { + return false + } + this.rbt.Put(start, end) + return true +} + +/** + * Your MyCalendar object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Book(start,end); + */ +``` ```ts class MyCalendar { @@ -194,8 +186,6 @@ class MyCalendar { */ ``` -### **Rust** - ```rust use std::collections::BTreeMap; @@ -236,10 +226,6 @@ impl MyCalendar { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0730.Count Different Palindromic Subsequences/README.md b/solution/0700-0799/0730.Count Different Palindromic Subsequences/README.md index 974d8bad2dad2..c6e13bffd6b80 100644 --- a/solution/0700-0799/0730.Count Different Palindromic Subsequences/README.md +++ b/solution/0700-0799/0730.Count Different Palindromic Subsequences/README.md @@ -44,16 +44,10 @@ ## 解法 - - -**方法一:区间 DP** +### 方法一:区间 DP -### **Python3** - - - ```python class Solution: def countPalindromicSubsequences(self, s: str) -> int: @@ -78,10 +72,6 @@ class Solution: return sum(dp[0][-1]) % mod ``` -### **Java** - - - ```java class Solution { private final int MOD = (int) 1e9 + 7; @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func countPalindromicSubsequences(s string) int { mod := int(1e9) + 7 @@ -195,10 +181,6 @@ func countPalindromicSubsequences(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0730.Count Different Palindromic Subsequences/README_EN.md b/solution/0700-0799/0730.Count Different Palindromic Subsequences/README_EN.md index ec6b02d09183d..61f6a396944f3 100644 --- a/solution/0700-0799/0730.Count Different Palindromic Subsequences/README_EN.md +++ b/solution/0700-0799/0730.Count Different Palindromic Subsequences/README_EN.md @@ -40,9 +40,9 @@ Note that 'bcb' is counted only once, even though it occurs twice. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return sum(dp[0][-1]) % mod ``` -### **Java** - ```java class Solution { private final int MOD = (int) 1e9 + 7; @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -142,8 +138,6 @@ public: }; ``` -### **Go** - ```go func countPalindromicSubsequences(s string) int { mod := int(1e9) + 7 @@ -183,10 +177,6 @@ func countPalindromicSubsequences(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0731.My Calendar II/README.md b/solution/0700-0799/0731.My Calendar II/README.md index 773b81b518364..7e27883d2a1ab 100644 --- a/solution/0700-0799/0731.My Calendar II/README.md +++ b/solution/0700-0799/0731.My Calendar II/README.md @@ -46,38 +46,14 @@ MyCalendar.book(25, 55); // returns true ## 解法 - - -**方法一:差分** +### 方法一:差分 利用有序哈希表实现。 时间复杂度 $O(n^2)$,其中 $n$ 表示日程安排的数量。 -**方法二:线段树** - -线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 $log(width)$。更新某个元素的值,只需要更新 $log(width)$ 个区间,并且这些区间都包含在一个包含该元素的大区间内。区间修改时,需要使用**懒标记**保证效率。 - -- 线段树的每个节点代表一个区间; -- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 $[1,N]$; -- 线段树的每个叶子节点代表一个长度为 $1$ 的元区间 $[x, x]$; -- 对于每个内部节点 $[l,r]$,它的左儿子是 $[l,mid]$,右儿子是 $[mid+1,r]$, 其中 $mid = ⌊(l+r)/2⌋$ (即向下取整)。 - -对于本题,线段树节点维护的信息有: - -1. 区间范围内被预定的次数的最大值 $v$ -1. 懒标记 $add$ - -由于时间范围为 $10^9$,非常大,因此我们采用动态开点。 - -时间复杂度 $O(nlogn)$,其中 $n$ 表示日程安排的数量。 - -### **Python3** - - - ```python from sortedcontainers import SortedDict @@ -104,6 +80,128 @@ class MyCalendarTwo: # param_1 = obj.book(start,end) ``` +```java +class MyCalendarTwo { + private Map tm = new TreeMap<>(); + + public MyCalendarTwo() { + } + + public boolean book(int start, int end) { + tm.put(start, tm.getOrDefault(start, 0) + 1); + tm.put(end, tm.getOrDefault(end, 0) - 1); + int s = 0; + for (int v : tm.values()) { + s += v; + if (s > 2) { + tm.put(start, tm.get(start) - 1); + tm.put(end, tm.get(end) + 1); + return false; + } + } + return true; + } +} + +/** + * Your MyCalendarTwo object will be instantiated and called as such: + * MyCalendarTwo obj = new MyCalendarTwo(); + * boolean param_1 = obj.book(start,end); + */ +``` + +```cpp +class MyCalendarTwo { +public: + map m; + + MyCalendarTwo() { + } + + bool book(int start, int end) { + ++m[start]; + --m[end]; + int s = 0; + for (auto& [_, v] : m) { + s += v; + if (s > 2) { + --m[start]; + ++m[end]; + return false; + } + } + return true; + } +}; + +/** + * Your MyCalendarTwo object will be instantiated and called as such: + * MyCalendarTwo* obj = new MyCalendarTwo(); + * bool param_1 = obj->book(start,end); + */ +``` + +```go +type MyCalendarTwo struct { + *redblacktree.Tree +} + +func Constructor() MyCalendarTwo { + return MyCalendarTwo{redblacktree.NewWithIntComparator()} +} + +func (this *MyCalendarTwo) Book(start int, end int) bool { + add := func(key, val int) { + if v, ok := this.Get(key); ok { + this.Put(key, v.(int)+val) + } else { + this.Put(key, val) + } + } + add(start, 1) + add(end, -1) + s := 0 + it := this.Iterator() + for it.Next() { + s += it.Value().(int) + if s > 2 { + add(start, -1) + add(end, 1) + return false + } + } + return true +} + +/** + * Your MyCalendarTwo object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Book(start,end); + */ +``` + + + +### 方法二:线段树 + +线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 $log(width)$。更新某个元素的值,只需要更新 $log(width)$ 个区间,并且这些区间都包含在一个包含该元素的大区间内。区间修改时,需要使用**懒标记**保证效率。 + +- 线段树的每个节点代表一个区间; +- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 $[1,N]$; +- 线段树的每个叶子节点代表一个长度为 $1$ 的元区间 $[x, x]$; +- 对于每个内部节点 $[l,r]$,它的左儿子是 $[l,mid]$,右儿子是 $[mid+1,r]$, 其中 $mid = ⌊(l+r)/2⌋$ (即向下取整)。 + +对于本题,线段树节点维护的信息有: + +1. 区间范围内被预定的次数的最大值 $v$ +1. 懒标记 $add$ + +由于时间范围为 $10^9$,非常大,因此我们采用动态开点。 + +时间复杂度 $O(nlogn)$,其中 $n$ 表示日程安排的数量。 + + + ```python class Node: def __init__(self, l, r): @@ -183,40 +281,6 @@ class MyCalendarTwo: # param_1 = obj.book(start,end) ``` -### **Java** - - - -```java -class MyCalendarTwo { - private Map tm = new TreeMap<>(); - - public MyCalendarTwo() { - } - - public boolean book(int start, int end) { - tm.put(start, tm.getOrDefault(start, 0) + 1); - tm.put(end, tm.getOrDefault(end, 0) - 1); - int s = 0; - for (int v : tm.values()) { - s += v; - if (s > 2) { - tm.put(start, tm.get(start) - 1); - tm.put(end, tm.get(end) + 1); - return false; - } - } - return true; - } -} - -/** - * Your MyCalendarTwo object will be instantiated and called as such: - * MyCalendarTwo obj = new MyCalendarTwo(); - * boolean param_1 = obj.book(start,end); - */ -``` - ```java class Node { Node left; @@ -328,39 +392,6 @@ class MyCalendarTwo { */ ``` -### **C++** - -```cpp -class MyCalendarTwo { -public: - map m; - - MyCalendarTwo() { - } - - bool book(int start, int end) { - ++m[start]; - --m[end]; - int s = 0; - for (auto& [_, v] : m) { - s += v; - if (s > 2) { - --m[start]; - ++m[end]; - return false; - } - } - return true; - } -}; - -/** - * Your MyCalendarTwo object will be instantiated and called as such: - * MyCalendarTwo* obj = new MyCalendarTwo(); - * bool param_1 = obj->book(start,end); - */ -``` - ```cpp class Node { public: @@ -461,47 +492,6 @@ public: */ ``` -### **Go** - -```go -type MyCalendarTwo struct { - *redblacktree.Tree -} - -func Constructor() MyCalendarTwo { - return MyCalendarTwo{redblacktree.NewWithIntComparator()} -} - -func (this *MyCalendarTwo) Book(start int, end int) bool { - add := func(key, val int) { - if v, ok := this.Get(key); ok { - this.Put(key, v.(int)+val) - } else { - this.Put(key, val) - } - } - add(start, 1) - add(end, -1) - s := 0 - it := this.Iterator() - for it.Next() { - s += it.Value().(int) - if s > 2 { - add(start, -1) - add(end, 1) - return false - } - } - return true -} - -/** - * Your MyCalendarTwo object will be instantiated and called as such: - * obj := Constructor(); - * param_1 := obj.Book(start,end); - */ -``` - ```go type node struct { left *node @@ -608,10 +598,6 @@ func (this *MyCalendarTwo) Book(start int, end int) bool { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0731.My Calendar II/README_EN.md b/solution/0700-0799/0731.My Calendar II/README_EN.md index 381204055e434..8863b5259f405 100644 --- a/solution/0700-0799/0731.My Calendar II/README_EN.md +++ b/solution/0700-0799/0731.My Calendar II/README_EN.md @@ -47,9 +47,9 @@ myCalendarTwo.book(25, 55); // return True, The event can be booked, as the time ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedDict @@ -77,6 +77,112 @@ class MyCalendarTwo: # param_1 = obj.book(start,end) ``` +```java +class MyCalendarTwo { + private Map tm = new TreeMap<>(); + + public MyCalendarTwo() { + } + + public boolean book(int start, int end) { + tm.put(start, tm.getOrDefault(start, 0) + 1); + tm.put(end, tm.getOrDefault(end, 0) - 1); + int s = 0; + for (int v : tm.values()) { + s += v; + if (s > 2) { + tm.put(start, tm.get(start) - 1); + tm.put(end, tm.get(end) + 1); + return false; + } + } + return true; + } +} + +/** + * Your MyCalendarTwo object will be instantiated and called as such: + * MyCalendarTwo obj = new MyCalendarTwo(); + * boolean param_1 = obj.book(start,end); + */ +``` + +```cpp +class MyCalendarTwo { +public: + map m; + + MyCalendarTwo() { + } + + bool book(int start, int end) { + ++m[start]; + --m[end]; + int s = 0; + for (auto& [_, v] : m) { + s += v; + if (s > 2) { + --m[start]; + ++m[end]; + return false; + } + } + return true; + } +}; + +/** + * Your MyCalendarTwo object will be instantiated and called as such: + * MyCalendarTwo* obj = new MyCalendarTwo(); + * bool param_1 = obj->book(start,end); + */ +``` + +```go +type MyCalendarTwo struct { + *redblacktree.Tree +} + +func Constructor() MyCalendarTwo { + return MyCalendarTwo{redblacktree.NewWithIntComparator()} +} + +func (this *MyCalendarTwo) Book(start int, end int) bool { + add := func(key, val int) { + if v, ok := this.Get(key); ok { + this.Put(key, v.(int)+val) + } else { + this.Put(key, val) + } + } + add(start, 1) + add(end, -1) + s := 0 + it := this.Iterator() + for it.Next() { + s += it.Value().(int) + if s > 2 { + add(start, -1) + add(end, 1) + return false + } + } + return true +} + +/** + * Your MyCalendarTwo object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Book(start,end); + */ +``` + + + +### Solution 2 + + + ```python class Node: def __init__(self, l, r): @@ -156,38 +262,6 @@ class MyCalendarTwo: # param_1 = obj.book(start,end) ``` -### **Java** - -```java -class MyCalendarTwo { - private Map tm = new TreeMap<>(); - - public MyCalendarTwo() { - } - - public boolean book(int start, int end) { - tm.put(start, tm.getOrDefault(start, 0) + 1); - tm.put(end, tm.getOrDefault(end, 0) - 1); - int s = 0; - for (int v : tm.values()) { - s += v; - if (s > 2) { - tm.put(start, tm.get(start) - 1); - tm.put(end, tm.get(end) + 1); - return false; - } - } - return true; - } -} - -/** - * Your MyCalendarTwo object will be instantiated and called as such: - * MyCalendarTwo obj = new MyCalendarTwo(); - * boolean param_1 = obj.book(start,end); - */ -``` - ```java class Node { Node left; @@ -299,39 +373,6 @@ class MyCalendarTwo { */ ``` -### **C++** - -```cpp -class MyCalendarTwo { -public: - map m; - - MyCalendarTwo() { - } - - bool book(int start, int end) { - ++m[start]; - --m[end]; - int s = 0; - for (auto& [_, v] : m) { - s += v; - if (s > 2) { - --m[start]; - ++m[end]; - return false; - } - } - return true; - } -}; - -/** - * Your MyCalendarTwo object will be instantiated and called as such: - * MyCalendarTwo* obj = new MyCalendarTwo(); - * bool param_1 = obj->book(start,end); - */ -``` - ```cpp class Node { public: @@ -432,47 +473,6 @@ public: */ ``` -### **Go** - -```go -type MyCalendarTwo struct { - *redblacktree.Tree -} - -func Constructor() MyCalendarTwo { - return MyCalendarTwo{redblacktree.NewWithIntComparator()} -} - -func (this *MyCalendarTwo) Book(start int, end int) bool { - add := func(key, val int) { - if v, ok := this.Get(key); ok { - this.Put(key, v.(int)+val) - } else { - this.Put(key, val) - } - } - add(start, 1) - add(end, -1) - s := 0 - it := this.Iterator() - for it.Next() { - s += it.Value().(int) - if s > 2 { - add(start, -1) - add(end, 1) - return false - } - } - return true -} - -/** - * Your MyCalendarTwo object will be instantiated and called as such: - * obj := Constructor(); - * param_1 := obj.Book(start,end); - */ -``` - ```go type node struct { left *node @@ -579,10 +579,6 @@ func (this *MyCalendarTwo) Book(start int, end int) bool { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0732.My Calendar III/README.md b/solution/0700-0799/0732.My Calendar III/README.md index ac8f3b6240dc7..29120cd44f980 100644 --- a/solution/0700-0799/0732.My Calendar III/README.md +++ b/solution/0700-0799/0732.My Calendar III/README.md @@ -49,9 +49,7 @@ myCalendarThree.book(25, 55); // 返回 3 ## 解法 - - -**方法一:线段树** +### 方法一:线段树 线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 $log(width)$。更新某个元素的值,只需要更新 $log(width)$ 个区间,并且这些区间都包含在一个包含该元素的大区间内。区间修改时,需要使用**懒标记**保证效率。 @@ -71,10 +69,6 @@ myCalendarThree.book(25, 55); // 返回 3 -### **Python3** - - - ```python class Node: def __init__(self, l, r): @@ -152,10 +146,6 @@ class MyCalendarThree: # param_1 = obj.book(start,end) ``` -### **Java** - - - ```java class Node { Node left; @@ -264,8 +254,6 @@ class MyCalendarThree { */ ``` -### **C++** - ```cpp class Node { public: @@ -366,8 +354,6 @@ public: */ ``` -### **Go** - ```go type node struct { left *node @@ -471,10 +457,6 @@ func (this *MyCalendarThree) Book(start int, end int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0732.My Calendar III/README_EN.md b/solution/0700-0799/0732.My Calendar III/README_EN.md index 17464611ead80..2d5b4881a63b3 100644 --- a/solution/0700-0799/0732.My Calendar III/README_EN.md +++ b/solution/0700-0799/0732.My Calendar III/README_EN.md @@ -46,9 +46,9 @@ myCalendarThree.book(25, 55); // return 3 ## Solutions - +### Solution 1 -### **Python3** + ```python class Node: @@ -127,8 +127,6 @@ class MyCalendarThree: # param_1 = obj.book(start,end) ``` -### **Java** - ```java class Node { Node left; @@ -237,8 +235,6 @@ class MyCalendarThree { */ ``` -### **C++** - ```cpp class Node { public: @@ -339,8 +335,6 @@ public: */ ``` -### **Go** - ```go type node struct { left *node @@ -444,10 +438,6 @@ func (this *MyCalendarThree) Book(start int, end int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0733.Flood Fill/README.md b/solution/0700-0799/0733.Flood Fill/README.md index 91b22210ac109..f2e00f640e9b3 100644 --- a/solution/0700-0799/0733.Flood Fill/README.md +++ b/solution/0700-0799/0733.Flood Fill/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:Flood fill 算法** +### 方法一:Flood fill 算法 Flood fill 算法是从一个区域中提取若干个连通的点与其他相邻区域区分开(或分别染成不同颜色)的经典算法。因为其思路类似洪水从一个区域扩散到所有能到达的区域而得名。 @@ -61,12 +59,6 @@ Flood fill 算法是从一个区域中提取若干个连通的点与其他相邻 -### **Python3** - - - -DFS: - ```python class Solution: def floodFill( @@ -91,35 +83,6 @@ class Solution: return image ``` -BFS: - -```python -class Solution: - def floodFill( - self, image: List[List[int]], sr: int, sc: int, color: int - ) -> List[List[int]]: - if image[sr][sc] == color: - return image - q = deque([(sr, sc)]) - oc = image[sr][sc] - image[sr][sc] = color - 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] = color - return image -``` - -### **Java** - - - -DFS: - ```java class Solution { private int[] dirs = {-1, 0, 1, 0, -1}; @@ -148,40 +111,6 @@ class Solution { } ``` -BFS: - -```java -class Solution { - public int[][] floodFill(int[][] image, int sr, int sc, int color) { - if (image[sr][sc] == color) { - return image; - } - Deque q = new ArrayDeque<>(); - q.offer(new int[] {sr, sc}); - int oc = image[sr][sc]; - image[sr][sc] = color; - 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] = color; - } - } - } - return image; - } -} -``` - -### **C++** - -DFS: - ```cpp class Solution { public: @@ -204,39 +133,6 @@ public: }; ``` -BFS: - -```cpp -class Solution { -public: - vector> floodFill(vector>& image, int sr, int sc, int color) { - if (image[sr][sc] == color) return image; - int oc = image[sr][sc]; - image[sr][sc] = color; - 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] = color; - } - } - } - return image; - } -}; -``` - -### **Go** - -DFS: - ```go func floodFill(image [][]int, sr int, sc int, color int) [][]int { oc := image[sr][sc] @@ -257,34 +153,6 @@ func floodFill(image [][]int, sr int, sc int, color int) [][]int { } ``` -BFS: - -```go -func floodFill(image [][]int, sr int, sc int, color int) [][]int { - if image[sr][sc] == color { - return image - } - oc := image[sr][sc] - q := [][]int{[]int{sr, sc}} - image[sr][sc] = color - 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] = color - } - } - } - return image -} -``` - -### **TypeScript** - ```ts function floodFill(image: number[][], sr: number, sc: number, newColor: number): number[][] { const m = image.length; @@ -312,8 +180,6 @@ function floodFill(image: number[][], sr: number, sc: number, newColor: number): } ``` -### **Rust** - ```rust impl Solution { fn dfs(image: &mut Vec>, sr: i32, sc: i32, new_color: i32, target: i32) { @@ -341,10 +207,112 @@ impl Solution { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def floodFill( + self, image: List[List[int]], sr: int, sc: int, color: int + ) -> List[List[int]]: + if image[sr][sc] == color: + return image + q = deque([(sr, sc)]) + oc = image[sr][sc] + image[sr][sc] = color + 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] = color + return image ``` +```java +class Solution { + public int[][] floodFill(int[][] image, int sr, int sc, int color) { + if (image[sr][sc] == color) { + return image; + } + Deque q = new ArrayDeque<>(); + q.offer(new int[] {sr, sc}); + int oc = image[sr][sc]; + image[sr][sc] = color; + 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] = color; + } + } + } + return image; + } +} +``` + +```cpp +class Solution { +public: + vector> floodFill(vector>& image, int sr, int sc, int color) { + if (image[sr][sc] == color) return image; + int oc = image[sr][sc]; + image[sr][sc] = color; + 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] = color; + } + } + } + return image; + } +}; +``` + +```go +func floodFill(image [][]int, sr int, sc int, color int) [][]int { + if image[sr][sc] == color { + return image + } + oc := image[sr][sc] + q := [][]int{[]int{sr, sc}} + image[sr][sc] = color + 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] = color + } + } + } + return image +} ``` + + diff --git a/solution/0700-0799/0733.Flood Fill/README_EN.md b/solution/0700-0799/0733.Flood Fill/README_EN.md index 1b3ae43541946..a9270a28470e0 100644 --- a/solution/0700-0799/0733.Flood Fill/README_EN.md +++ b/solution/0700-0799/0733.Flood Fill/README_EN.md @@ -44,16 +44,10 @@ Note the bottom corner is not colored 2, because it is not 4-directionally conne ## Solutions -DFS or BFS. - -> Flood fill, also called seed fill, is a flooding algorithm that determines and alters the area connected to a given node in a multi-dimensional array with some matching attribute. It is used in the "bucket" fill tool of paint programs to fill connected, similarly-colored areas with a different color. +### Solution 1 -### **Python3** - -DFS: - ```python class Solution: def floodFill( @@ -78,33 +72,6 @@ class Solution: return image ``` -BFS: - -```python -class Solution: - def floodFill( - self, image: List[List[int]], sr: int, sc: int, color: int - ) -> List[List[int]]: - if image[sr][sc] == color: - return image - q = deque([(sr, sc)]) - oc = image[sr][sc] - image[sr][sc] = color - 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] = color - return image -``` - -### **Java** - -DFS: - ```java class Solution { private int[] dirs = {-1, 0, 1, 0, -1}; @@ -133,40 +100,6 @@ class Solution { } ``` -BFS: - -```java -class Solution { - public int[][] floodFill(int[][] image, int sr, int sc, int color) { - if (image[sr][sc] == color) { - return image; - } - Deque q = new ArrayDeque<>(); - q.offer(new int[] {sr, sc}); - int oc = image[sr][sc]; - image[sr][sc] = color; - 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] = color; - } - } - } - return image; - } -} -``` - -### **C++** - -DFS: - ```cpp class Solution { public: @@ -189,39 +122,6 @@ public: }; ``` -BFS: - -```cpp -class Solution { -public: - vector> floodFill(vector>& image, int sr, int sc, int color) { - if (image[sr][sc] == color) return image; - int oc = image[sr][sc]; - image[sr][sc] = color; - 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] = color; - } - } - } - return image; - } -}; -``` - -### **Go** - -DFS: - ```go func floodFill(image [][]int, sr int, sc int, color int) [][]int { oc := image[sr][sc] @@ -242,34 +142,6 @@ func floodFill(image [][]int, sr int, sc int, color int) [][]int { } ``` -BFS: - -```go -func floodFill(image [][]int, sr int, sc int, color int) [][]int { - if image[sr][sc] == color { - return image - } - oc := image[sr][sc] - q := [][]int{[]int{sr, sc}} - image[sr][sc] = color - 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] = color - } - } - } - return image -} -``` - -### **TypeScript** - ```ts function floodFill(image: number[][], sr: number, sc: number, newColor: number): number[][] { const m = image.length; @@ -297,8 +169,6 @@ function floodFill(image: number[][], sr: number, sc: number, newColor: number): } ``` -### **Rust** - ```rust impl Solution { fn dfs(image: &mut Vec>, sr: i32, sc: i32, new_color: i32, target: i32) { @@ -326,10 +196,112 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def floodFill( + self, image: List[List[int]], sr: int, sc: int, color: int + ) -> List[List[int]]: + if image[sr][sc] == color: + return image + q = deque([(sr, sc)]) + oc = image[sr][sc] + image[sr][sc] = color + 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] = color + return image +``` + +```java +class Solution { + public int[][] floodFill(int[][] image, int sr, int sc, int color) { + if (image[sr][sc] == color) { + return image; + } + Deque q = new ArrayDeque<>(); + q.offer(new int[] {sr, sc}); + int oc = image[sr][sc]; + image[sr][sc] = color; + 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] = color; + } + } + } + return image; + } +} +``` +```cpp +class Solution { +public: + vector> floodFill(vector>& image, int sr, int sc, int color) { + if (image[sr][sc] == color) return image; + int oc = image[sr][sc]; + image[sr][sc] = color; + 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] = color; + } + } + } + return image; + } +}; ``` +```go +func floodFill(image [][]int, sr int, sc int, color int) [][]int { + if image[sr][sc] == color { + return image + } + oc := image[sr][sc] + q := [][]int{[]int{sr, sc}} + image[sr][sc] = color + 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] = color + } + } + } + return image +} ``` + + diff --git a/solution/0700-0799/0734.Sentence Similarity/README.md b/solution/0700-0799/0734.Sentence Similarity/README.md index 9e1cc1ca61e59..e49e9e60ee97d 100644 --- a/solution/0700-0799/0734.Sentence Similarity/README.md +++ b/solution/0700-0799/0734.Sentence Similarity/README.md @@ -62,16 +62,10 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 -### **Python3** - - - ```python class Solution: def areSentencesSimilar( @@ -85,10 +79,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public boolean areSentencesSimilar( @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func areSentencesSimilar(sentence1 []string, sentence2 []string, similarPairs [][]string) bool { if len(sentence1) != len(sentence2) { @@ -151,10 +137,6 @@ func areSentencesSimilar(sentence1 []string, sentence2 []string, similarPairs [] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0734.Sentence Similarity/README_EN.md b/solution/0700-0799/0734.Sentence Similarity/README_EN.md index 6e5b3da99ebac..7951e0d19d631 100644 --- a/solution/0700-0799/0734.Sentence Similarity/README_EN.md +++ b/solution/0700-0799/0734.Sentence Similarity/README_EN.md @@ -60,9 +60,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public boolean areSentencesSimilar( @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +116,6 @@ public: }; ``` -### **Go** - ```go func areSentencesSimilar(sentence1 []string, sentence2 []string, similarPairs [][]string) bool { if len(sentence1) != len(sentence2) { @@ -141,10 +135,6 @@ func areSentencesSimilar(sentence1 []string, sentence2 []string, similarPairs [] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0735.Asteroid Collision/README.md b/solution/0700-0799/0735.Asteroid Collision/README.md index 7edf7fafa3d7b..47556633a1457 100644 --- a/solution/0700-0799/0735.Asteroid Collision/README.md +++ b/solution/0700-0799/0735.Asteroid Collision/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 我们从左到右遍历每个小行星 $x$,由于每个小行星可能与之前的多个小行星发生碰撞,考虑用栈来存储。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def asteroidCollision(self, asteroids: List[int]) -> List[int]: @@ -83,10 +77,6 @@ class Solution: return stk ``` -### **Java** - - - ```java class Solution { public int[] asteroidCollision(int[] asteroids) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func asteroidCollision(asteroids []int) (stk []int) { for _, x := range asteroids { @@ -158,8 +144,6 @@ func asteroidCollision(asteroids []int) (stk []int) { } ``` -### **TypeScript** - ```ts function asteroidCollision(asteroids: number[]): number[] { const stk: number[] = []; @@ -181,8 +165,6 @@ function asteroidCollision(asteroids: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -207,10 +189,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0735.Asteroid Collision/README_EN.md b/solution/0700-0799/0735.Asteroid Collision/README_EN.md index 6b1f830c99a3c..860aa3dca081e 100644 --- a/solution/0700-0799/0735.Asteroid Collision/README_EN.md +++ b/solution/0700-0799/0735.Asteroid Collision/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Stack** +### Solution 1: Stack We traverse each asteroid $x$ from left to right. Since each asteroid may collide with multiple asteroids before it, we consider using a stack to store. @@ -59,8 +59,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def asteroidCollision(self, asteroids: List[int]) -> List[int]: @@ -78,8 +76,6 @@ class Solution: return stk ``` -### **Java** - ```java class Solution { public int[] asteroidCollision(int[] asteroids) { @@ -103,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +123,6 @@ public: }; ``` -### **Go** - ```go func asteroidCollision(asteroids []int) (stk []int) { for _, x := range asteroids { @@ -151,8 +143,6 @@ func asteroidCollision(asteroids []int) (stk []int) { } ``` -### TypeScript - ```ts function asteroidCollision(asteroids: number[]): number[] { const stk: number[] = []; @@ -174,8 +164,6 @@ function asteroidCollision(asteroids: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -200,10 +188,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0736.Parse Lisp Expression/README.md b/solution/0700-0799/0736.Parse Lisp Expression/README.md index 35cbb6547b168..237cbfba2862e 100644 --- a/solution/0700-0799/0736.Parse Lisp Expression/README.md +++ b/solution/0700-0799/0736.Parse Lisp Expression/README.md @@ -64,18 +64,12 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 时间复杂度 $O(n)$。 -### **Python3** - - - ```python class Solution: def evaluate(self, expression: str) -> int: @@ -134,10 +128,6 @@ class Solution: return eval() ``` -### **Java** - - - ```java class Solution { private int i; @@ -214,8 +204,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -284,8 +272,6 @@ public: }; ``` -### **Go** - ```go func evaluate(expression string) int { i, n := 0, len(expression) @@ -366,10 +352,6 @@ func evaluate(expression string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0736.Parse Lisp Expression/README_EN.md b/solution/0700-0799/0736.Parse Lisp Expression/README_EN.md index 9b0eda9c3d7ba..b782400559fdd 100644 --- a/solution/0700-0799/0736.Parse Lisp Expression/README_EN.md +++ b/solution/0700-0799/0736.Parse Lisp Expression/README_EN.md @@ -59,9 +59,9 @@ The second (add x y) evaluates as 3+2 = 5. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -121,8 +121,6 @@ class Solution: return eval() ``` -### **Java** - ```java class Solution { private int i; @@ -199,8 +197,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -269,8 +265,6 @@ public: }; ``` -### **Go** - ```go func evaluate(expression string) int { i, n := 0, len(expression) @@ -351,10 +345,6 @@ func evaluate(expression string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0737.Sentence Similarity II/README.md b/solution/0700-0799/0737.Sentence Similarity II/README.md index f2eef05adfd99..65297bc0156e2 100644 --- a/solution/0700-0799/0737.Sentence Similarity II/README.md +++ b/solution/0700-0799/0737.Sentence Similarity II/README.md @@ -63,83 +63,10 @@ ## 解法 - - -并查集。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` - -对于本题,将相似对的所有单词转换为下标,然后套用并查集模板,将相似对合并。 - -接着遍历 `sentence1`, `sentence2`,若对应的单词相同,直接 continue;若对应的单词不在相似对单词中,或者两单词不在同一个集合中,直接返回 false。否则遍历结束返回 true。 +### 方法一 -### **Python3** - - - ```python class Solution: def areSentencesSimilarTwo( @@ -178,10 +105,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -229,7 +152,43 @@ class Solution { } ``` -### **Go** +```cpp +class Solution { +public: + vector p; + bool areSentencesSimilarTwo(vector& sentence1, vector& sentence2, vector>& similarPairs) { + if (sentence1.size() != sentence2.size()) + return false; + int n = similarPairs.size(); + p.resize(n << 1); + for (int i = 0; i < p.size(); ++i) + p[i] = i; + unordered_map words; + int idx = 0; + for (auto e : similarPairs) { + string a = e[0], b = e[1]; + if (!words.count(a)) + words[a] = idx++; + if (!words.count(b)) + words[b] = idx++; + p[find(words[a])] = find(words[b]); + } + for (int i = 0; i < sentence1.size(); ++i) { + if (sentence1[i] == sentence2[i]) + continue; + if (!words.count(sentence1[i]) || !words.count(sentence2[i]) || find(words[sentence1[i]]) != find(words[sentence2[i]])) + return false; + } + return true; + } + + int find(int x) { + if (p[x] != x) + p[x] = find(p[x]); + return p[x]; + } +}; +``` ```go var p []int @@ -276,10 +235,6 @@ func find(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0737.Sentence Similarity II/README_EN.md b/solution/0700-0799/0737.Sentence Similarity II/README_EN.md index dc0c0c8c525bc..4c574493256e6 100644 --- a/solution/0700-0799/0737.Sentence Similarity II/README_EN.md +++ b/solution/0700-0799/0737.Sentence Similarity II/README_EN.md @@ -59,9 +59,9 @@ Since "leetcode is similar to "onepiece" and the first two words ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -101,8 +101,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { private int[] p; @@ -150,7 +148,43 @@ class Solution { } ``` -### **Go** +```cpp +class Solution { +public: + vector p; + bool areSentencesSimilarTwo(vector& sentence1, vector& sentence2, vector>& similarPairs) { + if (sentence1.size() != sentence2.size()) + return false; + int n = similarPairs.size(); + p.resize(n << 1); + for (int i = 0; i < p.size(); ++i) + p[i] = i; + unordered_map words; + int idx = 0; + for (auto e : similarPairs) { + string a = e[0], b = e[1]; + if (!words.count(a)) + words[a] = idx++; + if (!words.count(b)) + words[b] = idx++; + p[find(words[a])] = find(words[b]); + } + for (int i = 0; i < sentence1.size(); ++i) { + if (sentence1[i] == sentence2[i]) + continue; + if (!words.count(sentence1[i]) || !words.count(sentence2[i]) || find(words[sentence1[i]]) != find(words[sentence2[i]])) + return false; + } + return true; + } + + int find(int x) { + if (p[x] != x) + p[x] = find(p[x]); + return p[x]; + } +}; +``` ```go var p []int @@ -197,10 +231,6 @@ func find(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0738.Monotone Increasing Digits/README.md b/solution/0700-0799/0738.Monotone Increasing Digits/README.md index 1e8c968fd4610..4df43b3efe7b4 100644 --- a/solution/0700-0799/0738.Monotone Increasing Digits/README.md +++ b/solution/0700-0799/0738.Monotone Increasing Digits/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 从数字 `n` 的高位开始,找到第一个不满足 $n_{i-1} \le n_i$ 的位置 $i$。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def monotoneIncreasingDigits(self, n: int) -> int: @@ -79,10 +73,6 @@ class Solution: return int(''.join(s)) ``` -### **Java** - - - ```java class Solution { public int monotoneIncreasingDigits(int n) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func monotoneIncreasingDigits(n int) int { s := []byte(strconv.Itoa(n)) @@ -150,10 +136,6 @@ func monotoneIncreasingDigits(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0738.Monotone Increasing Digits/README_EN.md b/solution/0700-0799/0738.Monotone Increasing Digits/README_EN.md index 31a20d67a18e8..86ee0efcc0054 100644 --- a/solution/0700-0799/0738.Monotone Increasing Digits/README_EN.md +++ b/solution/0700-0799/0738.Monotone Increasing Digits/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return int(''.join(s)) ``` -### **Java** - ```java class Solution { public int monotoneIncreasingDigits(int n) { @@ -84,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +104,6 @@ public: }; ``` -### **Go** - ```go func monotoneIncreasingDigits(n int) int { s := []byte(strconv.Itoa(n)) @@ -130,10 +124,6 @@ func monotoneIncreasingDigits(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0739.Daily Temperatures/README.md b/solution/0700-0799/0739.Daily Temperatures/README.md index 0851b60952c74..95c19cff67ad7 100644 --- a/solution/0700-0799/0739.Daily Temperatures/README.md +++ b/solution/0700-0799/0739.Daily Temperatures/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 单调栈常见模型:找出每个数左/右边**离它最近的**且**比它大/小的数**。模板: @@ -63,10 +61,6 @@ for i in range(n): -### **Python3** - - - ```python class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: @@ -80,25 +74,6 @@ class Solution: return ans ``` -```python -class Solution: - def dailyTemperatures(self, temperatures: List[int]) -> List[int]: - n = len(temperatures) - stk = [] - ans = [0] * n - for i in range(n - 1, -1, -1): - while stk and temperatures[stk[-1]] <= temperatures[i]: - stk.pop() - if stk: - ans[i] = stk[-1] - i - stk.append(i) - return ans -``` - -### **Java** - - - ```java class Solution { public int[] dailyTemperatures(int[] temperatures) { @@ -117,30 +92,6 @@ class Solution { } ``` -```java -class Solution { - public int[] dailyTemperatures(int[] temperatures) { - int n = temperatures.length; - Deque stk = new ArrayDeque<>(); - int[] ans = new int[n]; - for (int i = n - 1; i >= 0; --i) { - while (!stk.isEmpty() && temperatures[stk.peek()] <= temperatures[i]) { - stk.pop(); - } - if (!stk.isEmpty()) { - ans[i] = stk.peek() - i; - } - stk.push(i); - } - return ans; - } -} -``` - -### **C++** - - - ```cpp class Solution { public: @@ -160,25 +111,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector dailyTemperatures(vector& temperatures) { - int n = temperatures.size(); - vector ans(n); - stack stk; - for (int i = n - 1; ~i; --i) { - while (!stk.empty() && temperatures[stk.top()] <= temperatures[i]) stk.pop(); - if (!stk.empty()) ans[i] = stk.top() - i; - stk.push(i); - } - return ans; - } -}; -``` - -### **Go** - ```go func dailyTemperatures(temperatures []int) []int { ans := make([]int, len(temperatures)) @@ -195,35 +127,11 @@ func dailyTemperatures(temperatures []int) []int { } ``` -```go -func dailyTemperatures(temperatures []int) []int { - n := len(temperatures) - ans := make([]int, n) - var stk []int - for i := n - 1; i >= 0; i-- { - for len(stk) > 0 && temperatures[stk[len(stk)-1]] <= temperatures[i] { - stk = stk[:len(stk)-1] - } - if len(stk) > 0 { - ans[i] = stk[len(stk)-1] - i - } - stk = append(stk, i) - } - return ans -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} temperatures - * @return {number[]} - */ -var dailyTemperatures = function (temperatures) { +```ts +function dailyTemperatures(temperatures: number[]): number[] { const n = temperatures.length; const ans = new Array(n).fill(0); - const stk = []; + const stk: number[] = []; for (let i = n - 1; i >= 0; --i) { while (stk.length && temperatures[stk[stk.length - 1]] <= temperatures[i]) { stk.pop(); @@ -234,11 +142,9 @@ var dailyTemperatures = function (temperatures) { stk.push(i); } return ans; -}; +} ``` -### **Rust** - ```rust impl Solution { pub fn daily_temperatures(temperatures: Vec) -> Vec { @@ -257,13 +163,15 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function dailyTemperatures(temperatures: number[]): number[] { +```js +/** + * @param {number[]} temperatures + * @return {number[]} + */ +var dailyTemperatures = function (temperatures) { const n = temperatures.length; const ans = new Array(n).fill(0); - const stk: number[] = []; + const stk = []; for (let i = n - 1; i >= 0; --i) { while (stk.length && temperatures[stk[stk.length - 1]] <= temperatures[i]) { stk.pop(); @@ -274,13 +182,85 @@ function dailyTemperatures(temperatures: number[]): number[] { stk.push(i); } return ans; -} +}; +``` + + + +### 方法二 + + + +```python +class Solution: + def dailyTemperatures(self, temperatures: List[int]) -> List[int]: + n = len(temperatures) + stk = [] + ans = [0] * n + for i in range(n - 1, -1, -1): + while stk and temperatures[stk[-1]] <= temperatures[i]: + stk.pop() + if stk: + ans[i] = stk[-1] - i + stk.append(i) + return ans ``` -### **...** +```java +class Solution { + public int[] dailyTemperatures(int[] temperatures) { + int n = temperatures.length; + Deque stk = new ArrayDeque<>(); + int[] ans = new int[n]; + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && temperatures[stk.peek()] <= temperatures[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + ans[i] = stk.peek() - i; + } + stk.push(i); + } + return ans; + } +} +``` +```cpp +class Solution { +public: + vector dailyTemperatures(vector& temperatures) { + int n = temperatures.size(); + vector ans(n); + stack stk; + for (int i = n - 1; ~i; --i) { + while (!stk.empty() && temperatures[stk.top()] <= temperatures[i]) stk.pop(); + if (!stk.empty()) ans[i] = stk.top() - i; + stk.push(i); + } + return ans; + } +}; ``` +```go +func dailyTemperatures(temperatures []int) []int { + n := len(temperatures) + ans := make([]int, n) + var stk []int + for i := n - 1; i >= 0; i-- { + for len(stk) > 0 && temperatures[stk[len(stk)-1]] <= temperatures[i] { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + ans[i] = stk[len(stk)-1] - i + } + stk = append(stk, i) + } + return ans +} ``` + + diff --git a/solution/0700-0799/0739.Daily Temperatures/README_EN.md b/solution/0700-0799/0739.Daily Temperatures/README_EN.md index 6e8d84f727a46..bd75f00d597ff 100644 --- a/solution/0700-0799/0739.Daily Temperatures/README_EN.md +++ b/solution/0700-0799/0739.Daily Temperatures/README_EN.md @@ -27,16 +27,10 @@ ## Solutions -Easy solution with stack. - -Everytime a higher temperature is found, we update answer of the peak one in the stack. - -If the day with higher temperature is not found, we leave the ans to be the default `0`. +### Solution 1 -### **Python3** - ```python class Solution: def dailyTemperatures(self, temperatures: List[int]) -> List[int]: @@ -50,23 +44,6 @@ class Solution: return ans ``` -```python -class Solution: - def dailyTemperatures(self, temperatures: List[int]) -> List[int]: - n = len(temperatures) - stk = [] - ans = [0] * n - for i in range(n - 1, -1, -1): - while stk and temperatures[stk[-1]] <= temperatures[i]: - stk.pop() - if stk: - ans[i] = stk[-1] - i - stk.append(i) - return ans -``` - -### **Java** - ```java class Solution { public int[] dailyTemperatures(int[] temperatures) { @@ -85,30 +62,6 @@ class Solution { } ``` -```java -class Solution { - public int[] dailyTemperatures(int[] temperatures) { - int n = temperatures.length; - Deque stk = new ArrayDeque<>(); - int[] ans = new int[n]; - for (int i = n - 1; i >= 0; --i) { - while (!stk.isEmpty() && temperatures[stk.peek()] <= temperatures[i]) { - stk.pop(); - } - if (!stk.isEmpty()) { - ans[i] = stk.peek() - i; - } - stk.push(i); - } - return ans; - } -} -``` - -### **C++** - - - ```cpp class Solution { public: @@ -128,25 +81,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector dailyTemperatures(vector& temperatures) { - int n = temperatures.size(); - vector ans(n); - stack stk; - for (int i = n - 1; ~i; --i) { - while (!stk.empty() && temperatures[stk.top()] <= temperatures[i]) stk.pop(); - if (!stk.empty()) ans[i] = stk.top() - i; - stk.push(i); - } - return ans; - } -}; -``` - -### **Go** - ```go func dailyTemperatures(temperatures []int) []int { ans := make([]int, len(temperatures)) @@ -163,35 +97,11 @@ func dailyTemperatures(temperatures []int) []int { } ``` -```go -func dailyTemperatures(temperatures []int) []int { - n := len(temperatures) - ans := make([]int, n) - var stk []int - for i := n - 1; i >= 0; i-- { - for len(stk) > 0 && temperatures[stk[len(stk)-1]] <= temperatures[i] { - stk = stk[:len(stk)-1] - } - if len(stk) > 0 { - ans[i] = stk[len(stk)-1] - i - } - stk = append(stk, i) - } - return ans -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} temperatures - * @return {number[]} - */ -var dailyTemperatures = function (temperatures) { +```ts +function dailyTemperatures(temperatures: number[]): number[] { const n = temperatures.length; const ans = new Array(n).fill(0); - const stk = []; + const stk: number[] = []; for (let i = n - 1; i >= 0; --i) { while (stk.length && temperatures[stk[stk.length - 1]] <= temperatures[i]) { stk.pop(); @@ -202,11 +112,9 @@ var dailyTemperatures = function (temperatures) { stk.push(i); } return ans; -}; +} ``` -### **Rust** - ```rust impl Solution { pub fn daily_temperatures(temperatures: Vec) -> Vec { @@ -225,13 +133,15 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function dailyTemperatures(temperatures: number[]): number[] { +```js +/** + * @param {number[]} temperatures + * @return {number[]} + */ +var dailyTemperatures = function (temperatures) { const n = temperatures.length; const ans = new Array(n).fill(0); - const stk: number[] = []; + const stk = []; for (let i = n - 1; i >= 0; --i) { while (stk.length && temperatures[stk[stk.length - 1]] <= temperatures[i]) { stk.pop(); @@ -242,13 +152,85 @@ function dailyTemperatures(temperatures: number[]): number[] { stk.push(i); } return ans; -} +}; ``` -### **...** + +### Solution 2 + + + +```python +class Solution: + def dailyTemperatures(self, temperatures: List[int]) -> List[int]: + n = len(temperatures) + stk = [] + ans = [0] * n + for i in range(n - 1, -1, -1): + while stk and temperatures[stk[-1]] <= temperatures[i]: + stk.pop() + if stk: + ans[i] = stk[-1] - i + stk.append(i) + return ans ``` +```java +class Solution { + public int[] dailyTemperatures(int[] temperatures) { + int n = temperatures.length; + Deque stk = new ArrayDeque<>(); + int[] ans = new int[n]; + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && temperatures[stk.peek()] <= temperatures[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + ans[i] = stk.peek() - i; + } + stk.push(i); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector dailyTemperatures(vector& temperatures) { + int n = temperatures.size(); + vector ans(n); + stack stk; + for (int i = n - 1; ~i; --i) { + while (!stk.empty() && temperatures[stk.top()] <= temperatures[i]) stk.pop(); + if (!stk.empty()) ans[i] = stk.top() - i; + stk.push(i); + } + return ans; + } +}; +``` + +```go +func dailyTemperatures(temperatures []int) []int { + n := len(temperatures) + ans := make([]int, n) + var stk []int + for i := n - 1; i >= 0; i-- { + for len(stk) > 0 && temperatures[stk[len(stk)-1]] <= temperatures[i] { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + ans[i] = stk[len(stk)-1] - i + } + stk = append(stk, i) + } + return ans +} ``` + + diff --git a/solution/0700-0799/0740.Delete and Earn/README.md b/solution/0700-0799/0740.Delete and Earn/README.md index cecee862ead52..9d4d1679ab6fc 100644 --- a/solution/0700-0799/0740.Delete and Earn/README.md +++ b/solution/0700-0799/0740.Delete and Earn/README.md @@ -46,32 +46,10 @@ ## 解法 - - -核心思路: **一个数字要么不选,要么全选** - -首先计算出每个数字的总和 sums,并维护两个 dp 数组:select 和 nonSelect - -- `sums[i]` 代表值为 i 的元素总和 -- `select[i]` 代表如果选数字 i,从 0 处理到 i 的最大和 -- `nonSelect[i]` 代表如果不选数字 i,从 0 处理到 i 的最大和 - -那么我们有以下逻辑: - -- 如果选 i,那么 i-1 肯定不能选; -- 如果不选 i,那么 i-1 选不选都可以,因此我们选择其中较大的选法 - -```java -select[i] = nonSelect[i - 1] + sums[i]; -nonSelect[i] = Math.max(select[i - 1], nonSelect[i - 1]); -``` +### 方法一 -### **Python3** - - - ```python class Solution: def deleteAndEarn(self, nums: List[int]) -> int: @@ -90,10 +68,6 @@ class Solution: return second ``` -### **Java** - - - ```java class Solution { public int deleteAndEarn(int[] nums) { @@ -120,7 +94,28 @@ class Solution { } ``` -### **Go** +```cpp +class Solution { +public: + int deleteAndEarn(vector& nums) { + vector vals(10010); + for (int& num : nums) { + vals[num] += num; + } + return rob(vals); + } + + int rob(vector& nums) { + int a = 0, b = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + int c = max(nums[i] + a, b); + a = b; + b = c; + } + return b; + } +}; +``` ```go func deleteAndEarn(nums []int) int { @@ -151,35 +146,6 @@ func deleteAndEarn(nums []int) int { } ``` -### **C++** - -```cpp -class Solution { -public: - int deleteAndEarn(vector& nums) { - vector vals(10010); - for (int& num : nums) { - vals[num] += num; - } - return rob(vals); - } - - int rob(vector& nums) { - int a = 0, b = nums[0]; - for (int i = 1; i < nums.size(); ++i) { - int c = max(nums[i] + a, b); - a = b; - b = c; - } - return b; - } -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0740.Delete and Earn/README_EN.md b/solution/0700-0799/0740.Delete and Earn/README_EN.md index b1108227aa78b..023661272c4bf 100644 --- a/solution/0700-0799/0740.Delete and Earn/README_EN.md +++ b/solution/0700-0799/0740.Delete and Earn/README_EN.md @@ -45,28 +45,10 @@ You earn a total of 9 points. ## Solutions -Intuition: **If we take a number, we will take all of the copies of it**. - -First calculate the sum of each number as **sums**, and keep updating two dp arrays: **select** and **nonSelect** - -- `sums[i]` represents the sum of elements whose value is i; -- `select[i]` represents the maximum sum of processing from 0 to i if the number i is selected; -- `nonSelect[i]` represents the maximum sum of processing from 0 to i if the number i is not selected; - -Then we have the following conclusions: - -- If i is selected, then i-1 must not be selected; -- If you do not choose i, then i-1 can choose or not, so we choose the larger one; - -```java -select[i] = nonSelect[i - 1] + sums[i]; -nonSelect[i] = Math.max(select[i - 1], nonSelect[i - 1]); -``` +### Solution 1 -### **Python3** - ```python class Solution: def deleteAndEarn(self, nums: List[int]) -> int: @@ -85,8 +67,6 @@ class Solution: return second ``` -### **Java** - ```java class Solution { public int deleteAndEarn(int[] nums) { @@ -113,7 +93,28 @@ class Solution { } ``` -### **Go** +```cpp +class Solution { +public: + int deleteAndEarn(vector& nums) { + vector vals(10010); + for (int& num : nums) { + vals[num] += num; + } + return rob(vals); + } + + int rob(vector& nums) { + int a = 0, b = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + int c = max(nums[i] + a, b); + a = b; + b = c; + } + return b; + } +}; +``` ```go func deleteAndEarn(nums []int) int { @@ -144,35 +145,6 @@ func deleteAndEarn(nums []int) int { } ``` -### **C++** - -```cpp -class Solution { -public: - int deleteAndEarn(vector& nums) { - vector vals(10010); - for (int& num : nums) { - vals[num] += num; - } - return rob(vals); - } - - int rob(vector& nums) { - int a = 0, b = nums[0]; - for (int i = 1; i < nums.size(); ++i) { - int c = max(nums[i] + a, b); - a = b; - b = c; - } - return b; - } -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0741.Cherry Pickup/README.md b/solution/0700-0799/0741.Cherry Pickup/README.md index 68c843010f303..bde39914bd316 100644 --- a/solution/0700-0799/0741.Cherry Pickup/README.md +++ b/solution/0700-0799/0741.Cherry Pickup/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 线性 DP。题目中,玩家从 `(0, 0)` 到 `(N-1, N-1)` 后又重新返回到起始点 `(0, 0)`,我们可以视为玩家两次从 `(0, 0)` 出发到 `(N-1, N-1)`。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: @@ -103,10 +97,6 @@ class Solution: return max(0, dp[-1][-1][-1]) ``` -### **Java** - - - ```java class Solution { public int cherryPickup(int[][] grid) { @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go func cherryPickup(grid [][]int) int { n := len(grid) @@ -208,8 +194,6 @@ func cherryPickup(grid [][]int) int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} grid @@ -258,10 +242,6 @@ var cherryPickup = function (grid) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0741.Cherry Pickup/README_EN.md b/solution/0700-0799/0741.Cherry Pickup/README_EN.md index 57d6cfc3b1875..782c787ab41d1 100644 --- a/solution/0700-0799/0741.Cherry Pickup/README_EN.md +++ b/solution/0700-0799/0741.Cherry Pickup/README_EN.md @@ -54,12 +54,10 @@ The total number of cherries picked up is 5, and this is the maximum possible. ## Solutions -Dynamic programming. +### Solution 1 -### **Python3** - ```python class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: @@ -89,8 +87,6 @@ class Solution: return max(0, dp[-1][-1][-1]) ``` -### **Java** - ```java class Solution { public int cherryPickup(int[][] grid) { @@ -125,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +147,6 @@ public: }; ``` -### **Go** - ```go func cherryPickup(grid [][]int) int { n := len(grid) @@ -192,8 +184,6 @@ func cherryPickup(grid [][]int) int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} grid @@ -242,10 +232,6 @@ var cherryPickup = function (grid) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0742.Closest Leaf in a Binary Tree/README.md b/solution/0700-0799/0742.Closest Leaf in a Binary Tree/README.md index bc9aea6d9a947..c571331aea1c0 100644 --- a/solution/0700-0799/0742.Closest Leaf in a Binary Tree/README.md +++ b/solution/0700-0799/0742.Closest Leaf in a Binary Tree/README.md @@ -55,18 +55,10 @@ ## 解法 - - -DFS 和 BFS。 - -先通过 DFS 构建图,然后 BFS 找距离值为 k 的结点最近的叶子结点。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -98,10 +90,6 @@ class Solution: q.append(next) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -160,8 +148,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -213,8 +199,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -264,10 +248,6 @@ func findClosestLeaf(root *TreeNode, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0742.Closest Leaf in a Binary Tree/README_EN.md b/solution/0700-0799/0742.Closest Leaf in a Binary Tree/README_EN.md index a906681df8e2b..14e978d1cea69 100644 --- a/solution/0700-0799/0742.Closest Leaf in a Binary Tree/README_EN.md +++ b/solution/0700-0799/0742.Closest Leaf in a Binary Tree/README_EN.md @@ -45,12 +45,10 @@ ## Solutions -DFS & BFS. +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -82,8 +80,6 @@ class Solution: q.append(next) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -142,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -195,8 +189,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -246,10 +238,6 @@ func findClosestLeaf(root *TreeNode, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0743.Network Delay Time/README.md b/solution/0700-0799/0743.Network Delay Time/README.md index c1cd84b916c21..caba4681deff6 100644 --- a/solution/0700-0799/0743.Network Delay Time/README.md +++ b/solution/0700-0799/0743.Network Delay Time/README.md @@ -53,34 +53,12 @@ ## 解法 - - -设 n 表示点数,m 表示边数。 - -**方法一:朴素 Dijkstra 算法** +### 方法一:朴素 Dijkstra 算法 时间复杂度 $O(n^2+m)$。 -**方法二:堆优化 Dijkstra 算法** - -时间复杂度 $O(m\log n)$。 - -**方法三:Bellman Ford 算法** - -时间复杂度 $O(nm)$。 - -**方法四:SPFA 算法** - -时间复杂度,平均情况下 $O(m)$,最坏情况下 $O(nm)$。 - -### **Python3** - - - -朴素 Dijkstra 算法: - ```python class Solution: def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: @@ -103,78 +81,6 @@ class Solution: return -1 if ans == INF else ans ``` -堆优化 Dijkstra 算法: - -```python -class Solution: - def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: - INF = 0x3F3F - g = defaultdict(list) - for u, v, w in times: - g[u - 1].append((v - 1, w)) - dist = [INF] * n - dist[k - 1] = 0 - q = [(0, k - 1)] - while q: - _, u = heappop(q) - for v, w in g[u]: - if dist[v] > dist[u] + w: - dist[v] = dist[u] + w - heappush(q, (dist[v], v)) - ans = max(dist) - return -1 if ans == INF else ans -``` - -Bellman Ford 算法: - -```python -class Solution: - def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: - INF = 0x3F3F - dist = [INF] * n - dist[k - 1] = 0 - for _ in range(n): - backup = dist[:] - for u, v, w in times: - dist[v - 1] = min(dist[v - 1], dist[u - 1] + w) - ans = max(dist) - return -1 if ans == INF else ans -``` - -SPFA 算法: - -```python -class Solution: - def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: - INF = 0x3F3F - dist = [INF] * n - vis = [False] * n - g = defaultdict(list) - for u, v, w in times: - g[u - 1].append((v - 1, w)) - k -= 1 - dist[k] = 0 - q = deque([k]) - vis[k] = True - while q: - u = q.popleft() - vis[u] = False - for v, w in g[u]: - if dist[v] > dist[u] + w: - dist[v] = dist[u] + w - if not vis[v]: - q.append(v) - vis[v] = True - ans = max(dist) - return -1 if ans == INF else ans -``` - -### **Java** - - - -朴素 Dijkstra 算法: - ```java class Solution { private static final int INF = 0x3f3f; @@ -212,122 +118,35 @@ class Solution { } ``` -堆优化 Dijkstra 算法: - -```java -class Solution { - private static final int INF = 0x3f3f; - - public int networkDelayTime(int[][] times, int n, int k) { - List[] g = new List[n]; - int[] dist = new int[n]; - for (int i = 0; i < n; ++i) { - dist[i] = INF; - g[i] = new ArrayList<>(); - } - for (int[] t : times) { - g[t[0] - 1].add(new int[] {t[1] - 1, t[2]}); - } - dist[k - 1] = 0; - PriorityQueue q = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); - q.offer(new int[] {0, k - 1}); - while (!q.isEmpty()) { - int[] p = q.poll(); - int u = p[1]; - for (int[] ne : g[u]) { - int v = ne[0], w = ne[1]; - if (dist[v] > dist[u] + w) { - dist[v] = dist[u] + w; - q.offer(new int[] {dist[v], v}); - } - } - } - int ans = 0; - for (int d : dist) { - ans = Math.max(ans, d); - } - return ans == INF ? -1 : ans; - } -} -``` - -Bellman Ford 算法: - -```java +```cpp class Solution { - private static final int INF = 0x3f3f; +public: + const int inf = 0x3f3f; - public int networkDelayTime(int[][] times, int n, int k) { - int[] dist = new int[n]; - int[] backup = new int[n]; - Arrays.fill(dist, INF); + int networkDelayTime(vector>& times, int n, int k) { + vector> g(n, vector(n, inf)); + for (auto& t : times) g[t[0] - 1][t[1] - 1] = t[2]; + vector vis(n); + vector dist(n, inf); dist[k - 1] = 0; for (int i = 0; i < n; ++i) { - System.arraycopy(dist, 0, backup, 0, n); - for (int[] t : times) { - int u = t[0] - 1, v = t[1] - 1, w = t[2]; - dist[v] = Math.min(dist[v], backup[u] + w); - } - } - int ans = 0; - for (int i = 0; i < n; ++i) { - ans = Math.max(ans, dist[i]); - } - return ans == INF ? -1 : ans; - } -} -``` - -SPFA 算法: - -```java -class Solution { - private static final int INF = 0x3f3f; - - public int networkDelayTime(int[][] times, int n, int k) { - int[] dist = new int[n]; - boolean[] vis = new boolean[n]; - List[] g = new List[n]; - for (int i = 0; i < n; ++i) { - dist[i] = INF; - g[i] = new ArrayList<>(); - } - for (int[] t : times) { - int u = t[0] - 1, v = t[1] - 1, w = t[2]; - g[u].add(new int[] {v, w}); - } - --k; - dist[k] = 0; - Deque q = new ArrayDeque<>(); - q.offer(k); - vis[k] = true; - while (!q.isEmpty()) { - int u = q.poll(); - vis[u] = false; - for (int[] ne : g[u]) { - int v = ne[0], w = ne[1]; - if (dist[v] > dist[u] + w) { - dist[v] = dist[u] + w; - if (!vis[v]) { - q.offer(v); - vis[v] = true; - } + int t = -1; + for (int j = 0; j < n; ++j) { + if (!vis[j] && (t == -1 || dist[t] > dist[j])) { + t = j; } } + vis[t] = true; + for (int j = 0; j < n; ++j) { + dist[j] = min(dist[j], dist[t] + g[t][j]); + } } - int ans = 0; - for (int i = 0; i < n; ++i) { - ans = Math.max(ans, dist[i]); - } - return ans == INF ? -1 : ans; + int ans = *max_element(dist.begin(), dist.end()); + return ans == inf ? -1 : ans; } -} +}; ``` -### **Go** - -朴素 Dijkstra 算法: - ```go func networkDelayTime(times [][]int, n int, k int) int { const inf = 0x3f3f @@ -365,45 +184,138 @@ func networkDelayTime(times [][]int, n int, k int) int { } ``` -堆优化 Dijkstra 算法: - -```go -const Inf = 0x3f3f3f3f - -type pair struct { - first int - second int -} + -var _ heap.Interface = (*pairs)(nil) +### 方法二:堆优化 Dijkstra 算法 -type pairs []pair +时间复杂度 $O(m\log n)$。 -func (a pairs) Len() int { return len(a) } -func (a pairs) Less(i int, j int) bool { - return a[i].first < a[j].first || a[i].first == a[j].first && a[i].second < a[j].second -} -func (a pairs) Swap(i int, j int) { a[i], a[j] = a[j], a[i] } -func (a *pairs) Push(x any) { *a = append(*a, x.(pair)) } -func (a *pairs) Pop() any { l := len(*a); t := (*a)[l-1]; *a = (*a)[:l-1]; return t } + -func networkDelayTime(times [][]int, n int, k int) int { - graph := make([]pairs, n) - for _, time := range times { - from, to, time := time[0]-1, time[1]-1, time[2] - graph[from] = append(graph[from], pair{to, time}) - } +```python +class Solution: + def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: + INF = 0x3F3F + g = defaultdict(list) + for u, v, w in times: + g[u - 1].append((v - 1, w)) + dist = [INF] * n + dist[k - 1] = 0 + q = [(0, k - 1)] + while q: + _, u = heappop(q) + for v, w in g[u]: + if dist[v] > dist[u] + w: + dist[v] = dist[u] + w + heappush(q, (dist[v], v)) + ans = max(dist) + return -1 if ans == INF else ans +``` - dis := make([]int, n) - for i := range dis { - dis[i] = Inf - } - dis[k-1] = 0 +```java +class Solution { + private static final int INF = 0x3f3f; - vis := make([]bool, n) - h := make(pairs, 0) - heap.Push(&h, pair{0, k - 1}) - for len(h) > 0 { + public int networkDelayTime(int[][] times, int n, int k) { + List[] g = new List[n]; + int[] dist = new int[n]; + for (int i = 0; i < n; ++i) { + dist[i] = INF; + g[i] = new ArrayList<>(); + } + for (int[] t : times) { + g[t[0] - 1].add(new int[] {t[1] - 1, t[2]}); + } + dist[k - 1] = 0; + PriorityQueue q = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); + q.offer(new int[] {0, k - 1}); + while (!q.isEmpty()) { + int[] p = q.poll(); + int u = p[1]; + for (int[] ne : g[u]) { + int v = ne[0], w = ne[1]; + if (dist[v] > dist[u] + w) { + dist[v] = dist[u] + w; + q.offer(new int[] {dist[v], v}); + } + } + } + int ans = 0; + for (int d : dist) { + ans = Math.max(ans, d); + } + return ans == INF ? -1 : ans; + } +} +``` + +```cpp +class Solution { +public: + const int inf = 0x3f3f; + + int networkDelayTime(vector>& times, int n, int k) { + vector>> g(n); + for (auto& t : times) g[t[0] - 1].push_back({t[1] - 1, t[2]}); + vector dist(n, inf); + dist[k - 1] = 0; + priority_queue, vector>, greater>> q; + q.push({0, k - 1}); + while (!q.empty()) { + auto p = q.top(); + q.pop(); + int u = p[1]; + for (auto& ne : g[u]) { + int v = ne[0], w = ne[1]; + if (dist[v] > dist[u] + w) { + dist[v] = dist[u] + w; + q.push({dist[v], v}); + } + } + } + int ans = *max_element(dist.begin(), dist.end()); + return ans == inf ? -1 : ans; + } +}; +``` + +```go +const Inf = 0x3f3f3f3f + +type pair struct { + first int + second int +} + +var _ heap.Interface = (*pairs)(nil) + +type pairs []pair + +func (a pairs) Len() int { return len(a) } +func (a pairs) Less(i int, j int) bool { + return a[i].first < a[j].first || a[i].first == a[j].first && a[i].second < a[j].second +} +func (a pairs) Swap(i int, j int) { a[i], a[j] = a[j], a[i] } +func (a *pairs) Push(x any) { *a = append(*a, x.(pair)) } +func (a *pairs) Pop() any { l := len(*a); t := (*a)[l-1]; *a = (*a)[:l-1]; return t } + +func networkDelayTime(times [][]int, n int, k int) int { + graph := make([]pairs, n) + for _, time := range times { + from, to, time := time[0]-1, time[1]-1, time[2] + graph[from] = append(graph[from], pair{to, time}) + } + + dis := make([]int, n) + for i := range dis { + dis[i] = Inf + } + dis[k-1] = 0 + + vis := make([]bool, n) + h := make(pairs, 0) + heap.Push(&h, pair{0, k - 1}) + for len(h) > 0 { from := heap.Pop(&h).(pair).second if vis[from] { continue @@ -425,7 +337,73 @@ func networkDelayTime(times [][]int, n int, k int) int { } ``` -Bellman Ford 算法: + + +### 方法三:Bellman Ford 算法 + +时间复杂度 $O(nm)$。 + + + +```python +class Solution: + def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: + INF = 0x3F3F + dist = [INF] * n + dist[k - 1] = 0 + for _ in range(n): + backup = dist[:] + for u, v, w in times: + dist[v - 1] = min(dist[v - 1], dist[u - 1] + w) + ans = max(dist) + return -1 if ans == INF else ans +``` + +```java +class Solution { + private static final int INF = 0x3f3f; + + public int networkDelayTime(int[][] times, int n, int k) { + int[] dist = new int[n]; + int[] backup = new int[n]; + Arrays.fill(dist, INF); + dist[k - 1] = 0; + for (int i = 0; i < n; ++i) { + System.arraycopy(dist, 0, backup, 0, n); + for (int[] t : times) { + int u = t[0] - 1, v = t[1] - 1, w = t[2]; + dist[v] = Math.min(dist[v], backup[u] + w); + } + } + int ans = 0; + for (int i = 0; i < n; ++i) { + ans = Math.max(ans, dist[i]); + } + return ans == INF ? -1 : ans; + } +} +``` + +```cpp +class Solution { +public: + int inf = 0x3f3f; + + int networkDelayTime(vector>& times, int n, int k) { + vector dist(n, inf); + dist[k - 1] = 0; + for (int i = 0; i < n; ++i) { + vector backup = dist; + for (auto& e : times) { + int u = e[0] - 1, v = e[1] - 1, w = e[2]; + dist[v] = min(dist[v], backup[u] + w); + } + } + int ans = *max_element(dist.begin(), dist.end()); + return ans == inf ? -1 : ans; + } +}; +``` ```go func networkDelayTime(times [][]int, n int, k int) int { @@ -451,138 +429,82 @@ func networkDelayTime(times [][]int, n int, k int) int { } ``` -SPFA 算法: + -```go -func networkDelayTime(times [][]int, n int, k int) int { - const inf = 0x3f3f - dist := make([]int, n) - vis := make([]bool, n) - g := make([][][]int, n) - for i := range dist { - dist[i] = inf - } - for _, t := range times { - u, v, w := t[0]-1, t[1]-1, t[2] - g[u] = append(g[u], []int{v, w}) - } - k-- - dist[k] = 0 - q := []int{k} - vis[k] = true - for len(q) > 0 { - u := q[0] - q = q[1:] - vis[u] = false - for _, ne := range g[u] { - v, w := ne[0], ne[1] - if dist[v] > dist[u]+w { - dist[v] = dist[u] + w - if !vis[v] { - q = append(q, v) - vis[v] = true - } - } - } - } - ans := slices.Max(dist) - if ans == inf { - return -1 - } - return ans -} -``` +### 方法四 -### **C++** + -朴素 Dijkstra 算法: +```python +class Solution: + def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: + INF = 0x3F3F + dist = [INF] * n + vis = [False] * n + g = defaultdict(list) + for u, v, w in times: + g[u - 1].append((v - 1, w)) + k -= 1 + dist[k] = 0 + q = deque([k]) + vis[k] = True + while q: + u = q.popleft() + vis[u] = False + for v, w in g[u]: + if dist[v] > dist[u] + w: + dist[v] = dist[u] + w + if not vis[v]: + q.append(v) + vis[v] = True + ans = max(dist) + return -1 if ans == INF else ans +``` -```cpp +```java class Solution { -public: - const int inf = 0x3f3f; + private static final int INF = 0x3f3f; - int networkDelayTime(vector>& times, int n, int k) { - vector> g(n, vector(n, inf)); - for (auto& t : times) g[t[0] - 1][t[1] - 1] = t[2]; - vector vis(n); - vector dist(n, inf); - dist[k - 1] = 0; + public int networkDelayTime(int[][] times, int n, int k) { + int[] dist = new int[n]; + boolean[] vis = new boolean[n]; + List[] g = new List[n]; for (int i = 0; i < n; ++i) { - int t = -1; - for (int j = 0; j < n; ++j) { - if (!vis[j] && (t == -1 || dist[t] > dist[j])) { - t = j; - } - } - vis[t] = true; - for (int j = 0; j < n; ++j) { - dist[j] = min(dist[j], dist[t] + g[t][j]); - } + dist[i] = INF; + g[i] = new ArrayList<>(); } - int ans = *max_element(dist.begin(), dist.end()); - return ans == inf ? -1 : ans; - } -}; -``` - -堆优化 Dijkstra 算法: - -```cpp -class Solution { -public: - const int inf = 0x3f3f; - - int networkDelayTime(vector>& times, int n, int k) { - vector>> g(n); - for (auto& t : times) g[t[0] - 1].push_back({t[1] - 1, t[2]}); - vector dist(n, inf); - dist[k - 1] = 0; - priority_queue, vector>, greater>> q; - q.push({0, k - 1}); - while (!q.empty()) { - auto p = q.top(); - q.pop(); - int u = p[1]; - for (auto& ne : g[u]) { + for (int[] t : times) { + int u = t[0] - 1, v = t[1] - 1, w = t[2]; + g[u].add(new int[] {v, w}); + } + --k; + dist[k] = 0; + Deque q = new ArrayDeque<>(); + q.offer(k); + vis[k] = true; + while (!q.isEmpty()) { + int u = q.poll(); + vis[u] = false; + for (int[] ne : g[u]) { int v = ne[0], w = ne[1]; if (dist[v] > dist[u] + w) { dist[v] = dist[u] + w; - q.push({dist[v], v}); + if (!vis[v]) { + q.offer(v); + vis[v] = true; + } } } } - int ans = *max_element(dist.begin(), dist.end()); - return ans == inf ? -1 : ans; - } -}; -``` - -Bellman Ford 算法: - -```cpp -class Solution { -public: - int inf = 0x3f3f; - - int networkDelayTime(vector>& times, int n, int k) { - vector dist(n, inf); - dist[k - 1] = 0; + int ans = 0; for (int i = 0; i < n; ++i) { - vector backup = dist; - for (auto& e : times) { - int u = e[0] - 1, v = e[1] - 1, w = e[2]; - dist[v] = min(dist[v], backup[u] + w); - } + ans = Math.max(ans, dist[i]); } - int ans = *max_element(dist.begin(), dist.end()); - return ans == inf ? -1 : ans; + return ans == INF ? -1 : ans; } -}; +} ``` -SPFA 算法: - ```cpp class Solution { public: @@ -621,10 +543,46 @@ public: }; ``` -### **...** - -``` - +```go +func networkDelayTime(times [][]int, n int, k int) int { + const inf = 0x3f3f + dist := make([]int, n) + vis := make([]bool, n) + g := make([][][]int, n) + for i := range dist { + dist[i] = inf + } + for _, t := range times { + u, v, w := t[0]-1, t[1]-1, t[2] + g[u] = append(g[u], []int{v, w}) + } + k-- + dist[k] = 0 + q := []int{k} + vis[k] = true + for len(q) > 0 { + u := q[0] + q = q[1:] + vis[u] = false + for _, ne := range g[u] { + v, w := ne[0], ne[1] + if dist[v] > dist[u]+w { + dist[v] = dist[u] + w + if !vis[v] { + q = append(q, v) + vis[v] = true + } + } + } + } + ans := slices.Max(dist) + if ans == inf { + return -1 + } + return ans +} ``` + + diff --git a/solution/0700-0799/0743.Network Delay Time/README_EN.md b/solution/0700-0799/0743.Network Delay Time/README_EN.md index 17f22535bae51..235cb86473e75 100644 --- a/solution/0700-0799/0743.Network Delay Time/README_EN.md +++ b/solution/0700-0799/0743.Network Delay Time/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,68 +71,6 @@ class Solution: return -1 if ans == INF else ans ``` -```python -class Solution: - def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: - INF = 0x3F3F - g = defaultdict(list) - for u, v, w in times: - g[u - 1].append((v - 1, w)) - dist = [INF] * n - dist[k - 1] = 0 - q = [(0, k - 1)] - while q: - _, u = heappop(q) - for v, w in g[u]: - if dist[v] > dist[u] + w: - dist[v] = dist[u] + w - heappush(q, (dist[v], v)) - ans = max(dist) - return -1 if ans == INF else ans -``` - -```python -class Solution: - def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: - INF = 0x3F3F - dist = [INF] * n - dist[k - 1] = 0 - for _ in range(n): - backup = dist[:] - for u, v, w in times: - dist[v - 1] = min(dist[v - 1], dist[u - 1] + w) - ans = max(dist) - return -1 if ans == INF else ans -``` - -```python -class Solution: - def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: - INF = 0x3F3F - dist = [INF] * n - vis = [False] * n - g = defaultdict(list) - for u, v, w in times: - g[u - 1].append((v - 1, w)) - k -= 1 - dist[k] = 0 - q = deque([k]) - vis[k] = True - while q: - u = q.popleft() - vis[u] = False - for v, w in g[u]: - if dist[v] > dist[u] + w: - dist[v] = dist[u] + w - if not vis[v]: - q.append(v) - vis[v] = True - ans = max(dist) - return -1 if ans == INF else ans -``` - -### **Java** - ```java class Solution { private static final int INF = 0x3f3f; @@ -170,6 +108,98 @@ class Solution { } ``` +```cpp +class Solution { +public: + const int inf = 0x3f3f; + + int networkDelayTime(vector>& times, int n, int k) { + vector> g(n, vector(n, inf)); + for (auto& t : times) g[t[0] - 1][t[1] - 1] = t[2]; + vector vis(n); + vector dist(n, inf); + dist[k - 1] = 0; + for (int i = 0; i < n; ++i) { + int t = -1; + for (int j = 0; j < n; ++j) { + if (!vis[j] && (t == -1 || dist[t] > dist[j])) { + t = j; + } + } + vis[t] = true; + for (int j = 0; j < n; ++j) { + dist[j] = min(dist[j], dist[t] + g[t][j]); + } + } + int ans = *max_element(dist.begin(), dist.end()); + return ans == inf ? -1 : ans; + } +}; +``` + +```go +func networkDelayTime(times [][]int, n int, k int) int { + const inf = 0x3f3f + dist := make([]int, n) + vis := make([]bool, n) + g := make([][]int, n) + for i := range dist { + dist[i] = inf + g[i] = make([]int, n) + for j := range g[i] { + g[i][j] = inf + } + } + for _, t := range times { + g[t[0]-1][t[1]-1] = t[2] + } + dist[k-1] = 0 + for i := 0; i < n; i++ { + t := -1 + for j := 0; j < n; j++ { + if !vis[j] && (t == -1 || dist[t] > dist[j]) { + t = j + } + } + vis[t] = true + for j := 0; j < n; j++ { + dist[j] = min(dist[j], dist[t]+g[t][j]) + } + } + ans := slices.Max(dist) + if ans == inf { + return -1 + } + return ans +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: + INF = 0x3F3F + g = defaultdict(list) + for u, v, w in times: + g[u - 1].append((v - 1, w)) + dist = [INF] * n + dist[k - 1] = 0 + q = [(0, k - 1)] + while q: + _, u = heappop(q) + for v, w in g[u]: + if dist[v] > dist[u] + w: + dist[v] = dist[u] + w + heappush(q, (dist[v], v)) + ans = max(dist) + return -1 if ans == INF else ans +``` + ```java class Solution { private static final int INF = 0x3f3f; @@ -207,112 +237,34 @@ class Solution { } ``` -```java +```cpp class Solution { - private static final int INF = 0x3f3f; +public: + const int inf = 0x3f3f; - public int networkDelayTime(int[][] times, int n, int k) { - int[] dist = new int[n]; - int[] backup = new int[n]; - Arrays.fill(dist, INF); + int networkDelayTime(vector>& times, int n, int k) { + vector>> g(n); + for (auto& t : times) g[t[0] - 1].push_back({t[1] - 1, t[2]}); + vector dist(n, inf); dist[k - 1] = 0; - for (int i = 0; i < n; ++i) { - System.arraycopy(dist, 0, backup, 0, n); - for (int[] t : times) { - int u = t[0] - 1, v = t[1] - 1, w = t[2]; - dist[v] = Math.min(dist[v], backup[u] + w); - } - } - int ans = 0; - for (int i = 0; i < n; ++i) { - ans = Math.max(ans, dist[i]); - } - return ans == INF ? -1 : ans; - } -} -``` - -```java -class Solution { - private static final int INF = 0x3f3f; - - public int networkDelayTime(int[][] times, int n, int k) { - int[] dist = new int[n]; - boolean[] vis = new boolean[n]; - List[] g = new List[n]; - for (int i = 0; i < n; ++i) { - dist[i] = INF; - g[i] = new ArrayList<>(); - } - for (int[] t : times) { - int u = t[0] - 1, v = t[1] - 1, w = t[2]; - g[u].add(new int[] {v, w}); - } - --k; - dist[k] = 0; - Deque q = new ArrayDeque<>(); - q.offer(k); - vis[k] = true; - while (!q.isEmpty()) { - int u = q.poll(); - vis[u] = false; - for (int[] ne : g[u]) { + priority_queue, vector>, greater>> q; + q.push({0, k - 1}); + while (!q.empty()) { + auto p = q.top(); + q.pop(); + int u = p[1]; + for (auto& ne : g[u]) { int v = ne[0], w = ne[1]; if (dist[v] > dist[u] + w) { dist[v] = dist[u] + w; - if (!vis[v]) { - q.offer(v); - vis[v] = true; - } + q.push({dist[v], v}); } } } - int ans = 0; - for (int i = 0; i < n; ++i) { - ans = Math.max(ans, dist[i]); - } - return ans == INF ? -1 : ans; + int ans = *max_element(dist.begin(), dist.end()); + return ans == inf ? -1 : ans; } -} -``` - -### **Go** - -```go -func networkDelayTime(times [][]int, n int, k int) int { - const inf = 0x3f3f - dist := make([]int, n) - vis := make([]bool, n) - g := make([][]int, n) - for i := range dist { - dist[i] = inf - g[i] = make([]int, n) - for j := range g[i] { - g[i][j] = inf - } - } - for _, t := range times { - g[t[0]-1][t[1]-1] = t[2] - } - dist[k-1] = 0 - for i := 0; i < n; i++ { - t := -1 - for j := 0; j < n; j++ { - if !vis[j] && (t == -1 || dist[t] > dist[j]) { - t = j - } - } - vis[t] = true - for j := 0; j < n; j++ { - dist[j] = min(dist[j], dist[t]+g[t][j]) - } - } - ans := slices.Max(dist) - if ans == inf { - return -1 - } - return ans -} +}; ``` ```go @@ -373,6 +325,72 @@ func networkDelayTime(times [][]int, n int, k int) int { } ``` + + +### Solution 3 + + + +```python +class Solution: + def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: + INF = 0x3F3F + dist = [INF] * n + dist[k - 1] = 0 + for _ in range(n): + backup = dist[:] + for u, v, w in times: + dist[v - 1] = min(dist[v - 1], dist[u - 1] + w) + ans = max(dist) + return -1 if ans == INF else ans +``` + +```java +class Solution { + private static final int INF = 0x3f3f; + + public int networkDelayTime(int[][] times, int n, int k) { + int[] dist = new int[n]; + int[] backup = new int[n]; + Arrays.fill(dist, INF); + dist[k - 1] = 0; + for (int i = 0; i < n; ++i) { + System.arraycopy(dist, 0, backup, 0, n); + for (int[] t : times) { + int u = t[0] - 1, v = t[1] - 1, w = t[2]; + dist[v] = Math.min(dist[v], backup[u] + w); + } + } + int ans = 0; + for (int i = 0; i < n; ++i) { + ans = Math.max(ans, dist[i]); + } + return ans == INF ? -1 : ans; + } +} +``` + +```cpp +class Solution { +public: + int inf = 0x3f3f; + + int networkDelayTime(vector>& times, int n, int k) { + vector dist(n, inf); + dist[k - 1] = 0; + for (int i = 0; i < n; ++i) { + vector backup = dist; + for (auto& e : times) { + int u = e[0] - 1, v = e[1] - 1, w = e[2]; + dist[v] = min(dist[v], backup[u] + w); + } + } + int ans = *max_element(dist.begin(), dist.end()); + return ans == inf ? -1 : ans; + } +}; +``` + ```go func networkDelayTime(times [][]int, n int, k int) int { const inf = 0x3f3f @@ -397,96 +415,80 @@ func networkDelayTime(times [][]int, n int, k int) int { } ``` -```go -func networkDelayTime(times [][]int, n int, k int) int { - const inf = 0x3f3f - dist := make([]int, n) - vis := make([]bool, n) - g := make([][][]int, n) - for i := range dist { - dist[i] = inf - } - for _, t := range times { - u, v, w := t[0]-1, t[1]-1, t[2] - g[u] = append(g[u], []int{v, w}) - } - k-- - dist[k] = 0 - q := []int{k} - vis[k] = true - for len(q) > 0 { - u := q[0] - q = q[1:] - vis[u] = false - for _, ne := range g[u] { - v, w := ne[0], ne[1] - if dist[v] > dist[u]+w { - dist[v] = dist[u] + w - if !vis[v] { - q = append(q, v) - vis[v] = true - } - } - } - } - ans := slices.Max(dist) - if ans == inf { - return -1 - } - return ans -} -``` + -### **C++** +### Solution 4 -```cpp -class Solution { -public: - const int inf = 0x3f3f; + - int networkDelayTime(vector>& times, int n, int k) { - vector> g(n, vector(n, inf)); - for (auto& t : times) g[t[0] - 1][t[1] - 1] = t[2]; - vector vis(n); - vector dist(n, inf); - dist[k - 1] = 0; - for (int i = 0; i < n; ++i) { - int t = -1; - for (int j = 0; j < n; ++j) { - if (!vis[j] && (t == -1 || dist[t] > dist[j])) { - t = j; - } - } - vis[t] = true; - for (int j = 0; j < n; ++j) { - dist[j] = min(dist[j], dist[t] + g[t][j]); - } - } - int ans = *max_element(dist.begin(), dist.end()); - return ans == inf ? -1 : ans; - } -}; +```python +class Solution: + def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: + INF = 0x3F3F + dist = [INF] * n + vis = [False] * n + g = defaultdict(list) + for u, v, w in times: + g[u - 1].append((v - 1, w)) + k -= 1 + dist[k] = 0 + q = deque([k]) + vis[k] = True + while q: + u = q.popleft() + vis[u] = False + for v, w in g[u]: + if dist[v] > dist[u] + w: + dist[v] = dist[u] + w + if not vis[v]: + q.append(v) + vis[v] = True + ans = max(dist) + return -1 if ans == INF else ans ``` -```cpp +```java class Solution { -public: - int inf = 0x3f3f; + private static final int INF = 0x3f3f; - int networkDelayTime(vector>& times, int n, int k) { - vector dist(n, inf); - dist[k - 1] = 0; + public int networkDelayTime(int[][] times, int n, int k) { + int[] dist = new int[n]; + boolean[] vis = new boolean[n]; + List[] g = new List[n]; for (int i = 0; i < n; ++i) { - vector backup = dist; - for (auto& e : times) { - int u = e[0] - 1, v = e[1] - 1, w = e[2]; - dist[v] = min(dist[v], backup[u] + w); + dist[i] = INF; + g[i] = new ArrayList<>(); + } + for (int[] t : times) { + int u = t[0] - 1, v = t[1] - 1, w = t[2]; + g[u].add(new int[] {v, w}); + } + --k; + dist[k] = 0; + Deque q = new ArrayDeque<>(); + q.offer(k); + vis[k] = true; + while (!q.isEmpty()) { + int u = q.poll(); + vis[u] = false; + for (int[] ne : g[u]) { + int v = ne[0], w = ne[1]; + if (dist[v] > dist[u] + w) { + dist[v] = dist[u] + w; + if (!vis[v]) { + q.offer(v); + vis[v] = true; + } + } } } - int ans = *max_element(dist.begin(), dist.end()); - return ans == inf ? -1 : ans; + int ans = 0; + for (int i = 0; i < n; ++i) { + ans = Math.max(ans, dist[i]); + } + return ans == INF ? -1 : ans; } -}; +} ``` ```cpp @@ -527,10 +529,46 @@ public: }; ``` -### **...** - -``` - +```go +func networkDelayTime(times [][]int, n int, k int) int { + const inf = 0x3f3f + dist := make([]int, n) + vis := make([]bool, n) + g := make([][][]int, n) + for i := range dist { + dist[i] = inf + } + for _, t := range times { + u, v, w := t[0]-1, t[1]-1, t[2] + g[u] = append(g[u], []int{v, w}) + } + k-- + dist[k] = 0 + q := []int{k} + vis[k] = true + for len(q) > 0 { + u := q[0] + q = q[1:] + vis[u] = false + for _, ne := range g[u] { + v, w := ne[0], ne[1] + if dist[v] > dist[u]+w { + dist[v] = dist[u] + w + if !vis[v] { + q = append(q, v) + vis[v] = true + } + } + } + } + ans := slices.Max(dist) + if ans == inf { + return -1 + } + return ans +} ``` + + diff --git a/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/README.md b/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/README.md index 8868e2bc6c49b..6121eae170f7b 100644 --- a/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/README.md +++ b/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:遍历** +### 方法一:遍历 遍历 `letters`,返回第一个满足 `letters[i] > target` 条件的元素。若是遍历结束还未找到,则返回 `letters[0]`。 @@ -57,31 +55,8 @@ 时间复杂度:$O(N)$。 -**方法二:二分** - -利用 `letters` 有序的特点,可以使用二分来快速查找。 - -在返回值方面相比传统二分不一样,需要对结果进行取余操作:`letters[l % n]`。 - -为什么?如题描述,字母是重复出现的,当索引过界时,不是没有结果,而是需要返回前面的元素。 - -一个容易理解的版本,使用减法: - -```c -if (l < n) { - return letters[l]; -} -return letters[l - n]; -``` - -时间复杂度:$O(logN)$。 - -### **Python3** - - - ```python class Solution: def nextGreatestLetter(self, letters: List[str], target: str) -> str: @@ -95,10 +70,6 @@ class Solution: return letters[left % len(letters)] ``` -### **Java** - - - ```java class Solution { public char nextGreatestLetter(char[] letters, char target) { @@ -116,27 +87,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function nextGreatestLetter(letters: string[], target: string): string { - const n = letters.length; - let left = 0; - let right = letters.length; - while (left < right) { - let mid = (left + right) >>> 1; - if (letters[mid] > target) { - right = mid; - } else { - left = mid + 1; - } - } - return letters[left % n]; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -155,8 +105,6 @@ public: }; ``` -### **Go** - ```go func nextGreatestLetter(letters []byte, target byte) byte { left, right := 0, len(letters) @@ -172,7 +120,22 @@ func nextGreatestLetter(letters []byte, target byte) byte { } ``` -### **Rust** +```ts +function nextGreatestLetter(letters: string[], target: string): string { + const n = letters.length; + let left = 0; + let right = letters.length; + while (left < right) { + let mid = (left + right) >>> 1; + if (letters[mid] > target) { + right = mid; + } else { + left = mid + 1; + } + } + return letters[left % n]; +} +``` ```rust impl Solution { @@ -185,27 +148,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn next_greatest_letter(letters: Vec, target: char) -> char { - let n = letters.len(); - let mut left = 0; - let mut right = n; - while left < right { - let mid = left + (right - left) / 2; - if letters[mid] > target { - right = mid; - } else { - left = mid + 1; - } - } - letters[left % n] - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -233,10 +175,48 @@ class Solution { } ``` -### **...** + + +### 方法二:二分 + +利用 `letters` 有序的特点,可以使用二分来快速查找。 + +在返回值方面相比传统二分不一样,需要对结果进行取余操作:`letters[l % n]`。 + +为什么?如题描述,字母是重复出现的,当索引过界时,不是没有结果,而是需要返回前面的元素。 + +一个容易理解的版本,使用减法: +```c +if (l < n) { + return letters[l]; +} +return letters[l - n]; ``` +时间复杂度:$O(logN)$。 + + + +```rust +impl Solution { + pub fn next_greatest_letter(letters: Vec, target: char) -> char { + let n = letters.len(); + let mut left = 0; + let mut right = n; + while left < right { + let mid = left + (right - left) / 2; + if letters[mid] > target { + right = mid; + } else { + left = mid + 1; + } + } + letters[left % n] + } +} ``` + + diff --git a/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/README_EN.md b/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/README_EN.md index 36e44a793e83a..3ed22a9d146e5 100644 --- a/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/README_EN.md +++ b/solution/0700-0799/0744.Find Smallest Letter Greater Than Target/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return letters[left % len(letters)] ``` -### **Java** - ```java class Solution { public char nextGreatestLetter(char[] letters, char target) { @@ -82,27 +80,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function nextGreatestLetter(letters: string[], target: string): string { - const n = letters.length; - let left = 0; - let right = letters.length; - while (left < right) { - let mid = (left + right) >>> 1; - if (letters[mid] > target) { - right = mid; - } else { - left = mid + 1; - } - } - return letters[left % n]; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -121,8 +98,6 @@ public: }; ``` -### **Go** - ```go func nextGreatestLetter(letters []byte, target byte) byte { left, right := 0, len(letters) @@ -138,7 +113,22 @@ func nextGreatestLetter(letters []byte, target byte) byte { } ``` -### **Rust** +```ts +function nextGreatestLetter(letters: string[], target: string): string { + const n = letters.length; + let left = 0; + let right = letters.length; + while (left < right) { + let mid = (left + right) >>> 1; + if (letters[mid] > target) { + right = mid; + } else { + left = mid + 1; + } + } + return letters[left % n]; +} +``` ```rust impl Solution { @@ -151,27 +141,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn next_greatest_letter(letters: Vec, target: char) -> char { - let n = letters.len(); - let mut left = 0; - let mut right = n; - while left < right { - let mid = left + (right - left) / 2; - if letters[mid] > target { - right = mid; - } else { - left = mid + 1; - } - } - letters[left % n] - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -199,10 +168,31 @@ class Solution { } ``` -### **...** + -``` +### Solution 2 + + +```rust +impl Solution { + pub fn next_greatest_letter(letters: Vec, target: char) -> char { + let n = letters.len(); + let mut left = 0; + let mut right = n; + while left < right { + let mid = left + (right - left) / 2; + if letters[mid] > target { + right = mid; + } else { + left = mid + 1; + } + } + letters[left % n] + } +} ``` + + diff --git a/solution/0700-0799/0745.Prefix and Suffix Search/README.md b/solution/0700-0799/0745.Prefix and Suffix Search/README.md index 21ced665900fb..ea4f0fbb45b7a 100644 --- a/solution/0700-0799/0745.Prefix and Suffix Search/README.md +++ b/solution/0700-0799/0745.Prefix and Suffix Search/README.md @@ -44,20 +44,12 @@ wordFilter.f("a", "e"); // 返回 0 ,因为下标为 0 的单词:前缀 pref ## 解法 - - -**方法一:暴力哈希** +### 方法一:暴力哈希 遍历 $words$ 的每个单词 $w$,将 $w$ 的所有前缀、后缀对存放到哈希表中。 -**方法二:双前缀树** - -### **Python3** - - - ```python class WordFilter: def __init__(self, words: List[str]): @@ -79,6 +71,109 @@ class WordFilter: # param_1 = obj.f(pref,suff) ``` +```java +class WordFilter { + private Map d = new HashMap<>(); + + public WordFilter(String[] words) { + for (int k = 0; k < words.length; ++k) { + String w = words[k]; + int n = w.length(); + for (int i = 0; i <= n; ++i) { + String a = w.substring(0, i); + for (int j = 0; j <= n; ++j) { + String b = w.substring(j); + d.put(a + "." + b, k); + } + } + } + } + + public int f(String pref, String suff) { + return d.getOrDefault(pref + "." + suff, -1); + } +} + +/** + * Your WordFilter object will be instantiated and called as such: + * WordFilter obj = new WordFilter(words); + * int param_1 = obj.f(pref,suff); + */ +``` + +```cpp +class WordFilter { +public: + unordered_map d; + + WordFilter(vector& words) { + for (int k = 0; k < words.size(); ++k) { + string w = words[k]; + int n = w.size(); + for (int i = 0; i <= n; ++i) { + string a = w.substr(0, i); + for (int j = 0; j <= n; ++j) { + string b = w.substr(j, n - j); + d[a + "." + b] = k; + } + } + } + } + + int f(string pref, string suff) { + string key = pref + "." + suff; + if (d.count(key)) return d[key]; + return -1; + } +}; + +/** + * Your WordFilter object will be instantiated and called as such: + * WordFilter* obj = new WordFilter(words); + * int param_1 = obj->f(pref,suff); + */ +``` + +```go +type WordFilter struct { + d map[string]int +} + +func Constructor(words []string) WordFilter { + d := map[string]int{} + for k, w := range words { + n := len(w) + for i := 0; i <= n; i++ { + a := w[:i] + for j := 0; j <= n; j++ { + b := w[j:] + d[a+"."+b] = k + } + } + } + return WordFilter{d} +} + +func (this *WordFilter) F(pref string, suff string) int { + if v, ok := this.d[pref+"."+suff]; ok { + return v + } + return -1 +} + +/** + * Your WordFilter object will be instantiated and called as such: + * obj := Constructor(words); + * param_1 := obj.F(pref,suff); + */ +``` + + + +### 方法二:双前缀树 + + + ```python class Trie: def __init__(self): @@ -133,40 +228,6 @@ class WordFilter: # param_1 = obj.f(pref,suff) ``` -### **Java** - - - -```java -class WordFilter { - private Map d = new HashMap<>(); - - public WordFilter(String[] words) { - for (int k = 0; k < words.length; ++k) { - String w = words[k]; - int n = w.length(); - for (int i = 0; i <= n; ++i) { - String a = w.substring(0, i); - for (int j = 0; j <= n; ++j) { - String b = w.substring(j); - d.put(a + "." + b, k); - } - } - } - } - - public int f(String pref, String suff) { - return d.getOrDefault(pref + "." + suff, -1); - } -} - -/** - * Your WordFilter object will be instantiated and called as such: - * WordFilter obj = new WordFilter(words); - * int param_1 = obj.f(pref,suff); - */ -``` - ```java class Trie { Trie[] children = new Trie[26]; @@ -239,77 +300,6 @@ class WordFilter { */ ``` -### **C++** - -```cpp -class WordFilter { -public: - unordered_map d; - - WordFilter(vector& words) { - for (int k = 0; k < words.size(); ++k) { - string w = words[k]; - int n = w.size(); - for (int i = 0; i <= n; ++i) { - string a = w.substr(0, i); - for (int j = 0; j <= n; ++j) { - string b = w.substr(j, n - j); - d[a + "." + b] = k; - } - } - } - } - - int f(string pref, string suff) { - string key = pref + "." + suff; - if (d.count(key)) return d[key]; - return -1; - } -}; - -/** - * Your WordFilter object will be instantiated and called as such: - * WordFilter* obj = new WordFilter(words); - * int param_1 = obj->f(pref,suff); - */ -``` - -### **Go** - -```go -type WordFilter struct { - d map[string]int -} - -func Constructor(words []string) WordFilter { - d := map[string]int{} - for k, w := range words { - n := len(w) - for i := 0; i <= n; i++ { - a := w[:i] - for j := 0; j <= n; j++ { - b := w[j:] - d[a+"."+b] = k - } - } - } - return WordFilter{d} -} - -func (this *WordFilter) F(pref string, suff string) int { - if v, ok := this.d[pref+"."+suff]; ok { - return v - } - return -1 -} - -/** - * Your WordFilter object will be instantiated and called as such: - * obj := Constructor(words); - * param_1 := obj.F(pref,suff); - */ -``` - ```go type Trie struct { children [26]*Trie @@ -394,10 +384,6 @@ func reverse(w string) string { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0745.Prefix and Suffix Search/README_EN.md b/solution/0700-0799/0745.Prefix and Suffix Search/README_EN.md index 6a5203c0d5519..c5c55c62f3c77 100644 --- a/solution/0700-0799/0745.Prefix and Suffix Search/README_EN.md +++ b/solution/0700-0799/0745.Prefix and Suffix Search/README_EN.md @@ -40,9 +40,9 @@ wordFilter.f("a", "e"); // return 0, because the word at ind ## Solutions - +### Solution 1 -### **Python3** + ```python class WordFilter: @@ -65,6 +65,109 @@ class WordFilter: # param_1 = obj.f(pref,suff) ``` +```java +class WordFilter { + private Map d = new HashMap<>(); + + public WordFilter(String[] words) { + for (int k = 0; k < words.length; ++k) { + String w = words[k]; + int n = w.length(); + for (int i = 0; i <= n; ++i) { + String a = w.substring(0, i); + for (int j = 0; j <= n; ++j) { + String b = w.substring(j); + d.put(a + "." + b, k); + } + } + } + } + + public int f(String pref, String suff) { + return d.getOrDefault(pref + "." + suff, -1); + } +} + +/** + * Your WordFilter object will be instantiated and called as such: + * WordFilter obj = new WordFilter(words); + * int param_1 = obj.f(pref,suff); + */ +``` + +```cpp +class WordFilter { +public: + unordered_map d; + + WordFilter(vector& words) { + for (int k = 0; k < words.size(); ++k) { + string w = words[k]; + int n = w.size(); + for (int i = 0; i <= n; ++i) { + string a = w.substr(0, i); + for (int j = 0; j <= n; ++j) { + string b = w.substr(j, n - j); + d[a + "." + b] = k; + } + } + } + } + + int f(string pref, string suff) { + string key = pref + "." + suff; + if (d.count(key)) return d[key]; + return -1; + } +}; + +/** + * Your WordFilter object will be instantiated and called as such: + * WordFilter* obj = new WordFilter(words); + * int param_1 = obj->f(pref,suff); + */ +``` + +```go +type WordFilter struct { + d map[string]int +} + +func Constructor(words []string) WordFilter { + d := map[string]int{} + for k, w := range words { + n := len(w) + for i := 0; i <= n; i++ { + a := w[:i] + for j := 0; j <= n; j++ { + b := w[j:] + d[a+"."+b] = k + } + } + } + return WordFilter{d} +} + +func (this *WordFilter) F(pref string, suff string) int { + if v, ok := this.d[pref+"."+suff]; ok { + return v + } + return -1 +} + +/** + * Your WordFilter object will be instantiated and called as such: + * obj := Constructor(words); + * param_1 := obj.F(pref,suff); + */ +``` + + + +### Solution 2 + + + ```python class Trie: def __init__(self): @@ -119,38 +222,6 @@ class WordFilter: # param_1 = obj.f(pref,suff) ``` -### **Java** - -```java -class WordFilter { - private Map d = new HashMap<>(); - - public WordFilter(String[] words) { - for (int k = 0; k < words.length; ++k) { - String w = words[k]; - int n = w.length(); - for (int i = 0; i <= n; ++i) { - String a = w.substring(0, i); - for (int j = 0; j <= n; ++j) { - String b = w.substring(j); - d.put(a + "." + b, k); - } - } - } - } - - public int f(String pref, String suff) { - return d.getOrDefault(pref + "." + suff, -1); - } -} - -/** - * Your WordFilter object will be instantiated and called as such: - * WordFilter obj = new WordFilter(words); - * int param_1 = obj.f(pref,suff); - */ -``` - ```java class Trie { Trie[] children = new Trie[26]; @@ -223,77 +294,6 @@ class WordFilter { */ ``` -### **C++** - -```cpp -class WordFilter { -public: - unordered_map d; - - WordFilter(vector& words) { - for (int k = 0; k < words.size(); ++k) { - string w = words[k]; - int n = w.size(); - for (int i = 0; i <= n; ++i) { - string a = w.substr(0, i); - for (int j = 0; j <= n; ++j) { - string b = w.substr(j, n - j); - d[a + "." + b] = k; - } - } - } - } - - int f(string pref, string suff) { - string key = pref + "." + suff; - if (d.count(key)) return d[key]; - return -1; - } -}; - -/** - * Your WordFilter object will be instantiated and called as such: - * WordFilter* obj = new WordFilter(words); - * int param_1 = obj->f(pref,suff); - */ -``` - -### **Go** - -```go -type WordFilter struct { - d map[string]int -} - -func Constructor(words []string) WordFilter { - d := map[string]int{} - for k, w := range words { - n := len(w) - for i := 0; i <= n; i++ { - a := w[:i] - for j := 0; j <= n; j++ { - b := w[j:] - d[a+"."+b] = k - } - } - } - return WordFilter{d} -} - -func (this *WordFilter) F(pref string, suff string) int { - if v, ok := this.d[pref+"."+suff]; ok { - return v - } - return -1 -} - -/** - * Your WordFilter object will be instantiated and called as such: - * obj := Constructor(words); - * param_1 := obj.F(pref,suff); - */ -``` - ```go type Trie struct { children [26]*Trie @@ -378,10 +378,6 @@ func reverse(w string) string { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0746.Min Cost Climbing Stairs/README.md b/solution/0700-0799/0746.Min Cost Climbing Stairs/README.md index d200638b31aa2..5db6474582ec9 100644 --- a/solution/0700-0799/0746.Min Cost Climbing Stairs/README.md +++ b/solution/0700-0799/0746.Min Cost Climbing Stairs/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示到达第 $i$ 个阶梯所需要的最小花费,初始时 $f[0] = f[1] = 0$,答案即为 $f[n]$。 @@ -70,10 +68,6 @@ $$ -### **Python3** - - - ```python class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: @@ -84,19 +78,6 @@ class Solution: return f[n] ``` -```python -class Solution: - def minCostClimbingStairs(self, cost: List[int]) -> int: - f = g = 0 - for i in range(2, len(cost) + 1): - f, g = g, min(f + cost[i - 2], g + cost[i - 1]) - return g -``` - -### **Java** - - - ```java class Solution { public int minCostClimbingStairs(int[] cost) { @@ -110,22 +91,6 @@ class Solution { } ``` -```java -class Solution { - public int minCostClimbingStairs(int[] cost) { - int f = 0, g = 0; - for (int i = 2; i <= cost.length; ++i) { - int gg = Math.min(f + cost[i - 2], g + cost[i - 1]); - f = g; - g = gg; - } - return g; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -140,6 +105,70 @@ public: }; ``` +```go +func minCostClimbingStairs(cost []int) int { + n := len(cost) + f := make([]int, n+1) + for i := 2; i <= n; i++ { + f[i] = min(f[i-1]+cost[i-1], f[i-2]+cost[i-2]) + } + return f[n] +} +``` + +```ts +function minCostClimbingStairs(cost: number[]): number { + const n = cost.length; + const f: number[] = Array(n + 1).fill(0); + for (let i = 2; i <= n; ++i) { + f[i] = Math.min(f[i - 1] + cost[i - 1], f[i - 2] + cost[i - 2]); + } + return f[n]; +} +``` + +```rust +impl Solution { + pub fn min_cost_climbing_stairs(cost: Vec) -> i32 { + let n = cost.len(); + let mut f = vec![0; n + 1]; + for i in 2..=n { + f[i] = std::cmp::min(f[i - 2] + cost[i - 2], f[i - 1] + cost[i - 1]); + } + f[n] + } +} +``` + + + +### 方法二 + + + +```python +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: + f = g = 0 + for i in range(2, len(cost) + 1): + f, g = g, min(f + cost[i - 2], g + cost[i - 1]) + return g +``` + +```java +class Solution { + public int minCostClimbingStairs(int[] cost) { + int f = 0, g = 0; + for (int i = 2; i <= cost.length; ++i) { + int gg = Math.min(f + cost[i - 2], g + cost[i - 1]); + f = g; + g = gg; + } + return g; + } +} +``` + ```cpp class Solution { public: @@ -155,19 +184,6 @@ public: }; ``` -### **Go** - -```go -func minCostClimbingStairs(cost []int) int { - n := len(cost) - f := make([]int, n+1) - for i := 2; i <= n; i++ { - f[i] = min(f[i-1]+cost[i-1], f[i-2]+cost[i-2]) - } - return f[n] -} -``` - ```go func minCostClimbingStairs(cost []int) int { var f, g int @@ -178,19 +194,6 @@ func minCostClimbingStairs(cost []int) int { } ``` -### **TypeScript** - -```ts -function minCostClimbingStairs(cost: number[]): number { - const n = cost.length; - const f: number[] = Array(n + 1).fill(0); - for (let i = 2; i <= n; ++i) { - f[i] = Math.min(f[i - 1] + cost[i - 1], f[i - 2] + cost[i - 2]); - } - return f[n]; -} -``` - ```ts function minCostClimbingStairs(cost: number[]): number { let a = 0, @@ -202,21 +205,6 @@ function minCostClimbingStairs(cost: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn min_cost_climbing_stairs(cost: Vec) -> i32 { - let n = cost.len(); - let mut f = vec![0; n + 1]; - for i in 2..=n { - f[i] = std::cmp::min(f[i - 2] + cost[i - 2], f[i - 1] + cost[i - 1]); - } - f[n] - } -} -``` - ```rust impl Solution { pub fn min_cost_climbing_stairs(cost: Vec) -> i32 { @@ -231,10 +219,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0746.Min Cost Climbing Stairs/README_EN.md b/solution/0700-0799/0746.Min Cost Climbing Stairs/README_EN.md index 583c3645935ba..2e259d8ea7cf8 100644 --- a/solution/0700-0799/0746.Min Cost Climbing Stairs/README_EN.md +++ b/solution/0700-0799/0746.Min Cost Climbing Stairs/README_EN.md @@ -46,7 +46,7 @@ The total cost is 6. ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i]$ as the minimum cost required to reach the $i$th step, initially $f[0] = f[1] = 0$. The answer is $f[n]$. @@ -64,8 +64,6 @@ We notice that $f[i]$ in the state transition equation is only related to $f[i - -### **Python3** - ```python class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: @@ -76,17 +74,6 @@ class Solution: return f[n] ``` -```python -class Solution: - def minCostClimbingStairs(self, cost: List[int]) -> int: - f = g = 0 - for i in range(2, len(cost) + 1): - f, g = g, min(f + cost[i - 2], g + cost[i - 1]) - return g -``` - -### **Java** - ```java class Solution { public int minCostClimbingStairs(int[] cost) { @@ -100,22 +87,6 @@ class Solution { } ``` -```java -class Solution { - public int minCostClimbingStairs(int[] cost) { - int f = 0, g = 0; - for (int i = 2; i <= cost.length; ++i) { - int gg = Math.min(f + cost[i - 2], g + cost[i - 1]); - f = g; - g = gg; - } - return g; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -130,23 +101,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minCostClimbingStairs(vector& cost) { - int f = 0, g = 0; - for (int i = 2; i <= cost.size(); ++i) { - int gg = min(f + cost[i - 2], g + cost[i - 1]); - f = g; - g = gg; - } - return g; - } -}; -``` - -### **Go** - ```go func minCostClimbingStairs(cost []int) int { n := len(cost) @@ -158,18 +112,6 @@ func minCostClimbingStairs(cost []int) int { } ``` -```go -func minCostClimbingStairs(cost []int) int { - var f, g int - for i := 2; i <= n; i++ { - f, g = g, min(f+cost[i-2], g+cost[i-1]) - } - return g -} -``` - -### **TypeScript** - ```ts function minCostClimbingStairs(cost: number[]): number { const n = cost.length; @@ -181,18 +123,6 @@ function minCostClimbingStairs(cost: number[]): number { } ``` -```ts -function minCostClimbingStairs(cost: number[]): number { - let [f, g] = [0, 0]; - for (let i = 2; i <= cost.length; ++i) { - [f, g] = [g, Math.min(f + cost[i - 2], g + cost[i - 1])]; - } - return g; -} -``` - -### **Rust** - ```rust impl Solution { pub fn min_cost_climbing_stairs(cost: Vec) -> i32 { @@ -206,6 +136,71 @@ impl Solution { } ``` + + +### Solution 2 + + + +```python +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: + f = g = 0 + for i in range(2, len(cost) + 1): + f, g = g, min(f + cost[i - 2], g + cost[i - 1]) + return g +``` + +```java +class Solution { + public int minCostClimbingStairs(int[] cost) { + int f = 0, g = 0; + for (int i = 2; i <= cost.length; ++i) { + int gg = Math.min(f + cost[i - 2], g + cost[i - 1]); + f = g; + g = gg; + } + return g; + } +} +``` + +```cpp +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + int f = 0, g = 0; + for (int i = 2; i <= cost.size(); ++i) { + int gg = min(f + cost[i - 2], g + cost[i - 1]); + f = g; + g = gg; + } + return g; + } +}; +``` + +```go +func minCostClimbingStairs(cost []int) int { + var f, g int + for i := 2; i <= n; i++ { + f, g = g, min(f+cost[i-2], g+cost[i-1]) + } + return g +} +``` + +```ts +function minCostClimbingStairs(cost: number[]): number { + let a = 0, + b = 0; + for (let i = 1; i < cost.length; ++i) { + [a, b] = [b, Math.min(a + cost[i - 1], b + cost[i])]; + } + return b; +} +``` + ```rust impl Solution { pub fn min_cost_climbing_stairs(cost: Vec) -> i32 { @@ -220,10 +215,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0747.Largest Number At Least Twice of Others/README.md b/solution/0700-0799/0747.Largest Number At Least Twice of Others/README.md index aeb3d49369c01..2578c8f469b03 100644 --- a/solution/0700-0799/0747.Largest Number At Least Twice of Others/README.md +++ b/solution/0700-0799/0747.Largest Number At Least Twice of Others/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:遍历** +### 方法一:遍历 我们可以遍历数组 $nums$,找到数组中的最大值 $x$ 和第二大的值 $y$,如果 $x \ge 2y$,则返回 $x$ 的下标,否则返回 $-1$。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def dominantIndex(self, nums: List[int]) -> int: @@ -63,10 +57,6 @@ class Solution: return nums.index(x) if x >= 2 * y else -1 ``` -### **Java** - - - ```java class Solution { public int dominantIndex(int[] nums) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +98,6 @@ public: }; ``` -### **Go** - ```go func dominantIndex(nums []int) int { k := 0 @@ -129,8 +115,6 @@ func dominantIndex(nums []int) int { } ``` -### **TypeScript** - ```ts function dominantIndex(nums: number[]): number { let k = 0; @@ -148,8 +132,6 @@ function dominantIndex(nums: number[]): number { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -171,10 +153,6 @@ var dominantIndex = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0747.Largest Number At Least Twice of Others/README_EN.md b/solution/0700-0799/0747.Largest Number At Least Twice of Others/README_EN.md index 098ab39966fff..a47b67cf55edb 100644 --- a/solution/0700-0799/0747.Largest Number At Least Twice of Others/README_EN.md +++ b/solution/0700-0799/0747.Largest Number At Least Twice of Others/README_EN.md @@ -38,7 +38,7 @@ The index of value 6 is 1, so we return 1. ## Solutions -**Solution 1: Traversal** +### Solution 1: Traversal We can traverse the array $nums$ to find the maximum value $x$ and the second largest value $y$ in the array. If $x \ge 2y$, then return the index of $x$, otherwise return $-1$. @@ -48,8 +48,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def dominantIndex(self, nums: List[int]) -> int: @@ -57,8 +55,6 @@ class Solution: return nums.index(x) if x >= 2 * y else -1 ``` -### **Java** - ```java class Solution { public int dominantIndex(int[] nums) { @@ -79,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +96,6 @@ public: }; ``` -### **Go** - ```go func dominantIndex(nums []int) int { k := 0 @@ -121,8 +113,6 @@ func dominantIndex(nums []int) int { } ``` -### **TypeScript** - ```ts function dominantIndex(nums: number[]): number { let k = 0; @@ -140,8 +130,6 @@ function dominantIndex(nums: number[]): number { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -163,10 +151,6 @@ var dominantIndex = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0748.Shortest Completing Word/README.md b/solution/0700-0799/0748.Shortest Completing Word/README.md index f25b4ee1a2d6b..f8e8d783e941b 100644 --- a/solution/0700-0799/0748.Shortest Completing Word/README.md +++ b/solution/0700-0799/0748.Shortest Completing Word/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们先用哈希表或者一个长度为 $26$ 的数组 $cnt$ 统计字符串 `licensePlate` 中每个字母出现的次数,注意这里我们统一将字母转换为小写进行计数。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public String shortestCompletingWord(String licensePlate, String[] words) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func shortestCompletingWord(licensePlate string, words []string) (ans string) { cnt := [26]int{} @@ -189,8 +175,6 @@ func shortestCompletingWord(licensePlate string, words []string) (ans string) { } ``` -### **TypeScript** - ```ts function shortestCompletingWord(licensePlate: string, words: string[]): string { const cnt: number[] = Array(26).fill(0); @@ -224,8 +208,6 @@ function shortestCompletingWord(licensePlate: string, words: string[]): string { } ``` -### **Rust** - ```rust impl Solution { pub fn shortest_completing_word(license_plate: String, words: Vec) -> String { @@ -260,10 +242,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0748.Shortest Completing Word/README_EN.md b/solution/0700-0799/0748.Shortest Completing Word/README_EN.md index c4e611d0e741c..be6ff858de1b5 100644 --- a/solution/0700-0799/0748.Shortest Completing Word/README_EN.md +++ b/solution/0700-0799/0748.Shortest Completing Word/README_EN.md @@ -47,7 +47,7 @@ Since "steps" is the only word containing all the letters, that is the ## Solutions -**Solution 1: Counting** +### Solution 1: Counting First, we use a hash table or an array $cnt$ of length $26$ to count the frequency of each letter in the string `licensePlate`. Note that we convert all letters to lowercase for counting. @@ -57,8 +57,6 @@ The time complexity is $O(n \times |\Sigma|)$, and the space complexity is $O(|\ -### **Python3** - ```python class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: @@ -73,8 +71,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public String shortestCompletingWord(String licensePlate, String[] words) { @@ -110,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +141,6 @@ public: }; ``` -### **Go** - ```go func shortestCompletingWord(licensePlate string, words []string) (ans string) { cnt := [26]int{} @@ -180,8 +172,6 @@ func shortestCompletingWord(licensePlate string, words []string) (ans string) { } ``` -### **TypeScript** - ```ts function shortestCompletingWord(licensePlate: string, words: string[]): string { const cnt: number[] = Array(26).fill(0); @@ -215,8 +205,6 @@ function shortestCompletingWord(licensePlate: string, words: string[]): string { } ``` -### **Rust** - ```rust impl Solution { pub fn shortest_completing_word(license_plate: String, words: Vec) -> String { @@ -251,10 +239,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0749.Contain Virus/README.md b/solution/0700-0799/0749.Contain Virus/README.md index 38bd3e235c660..b675aecbc2015 100644 --- a/solution/0700-0799/0749.Contain Virus/README.md +++ b/solution/0700-0799/0749.Contain Virus/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:DFS 暴力模拟** +### 方法一:DFS 暴力模拟 DFS 找到每个病毒区域 `areas[i]`,同时记录每个区域边界节点 `boundaries[i]` 以及周长 `c[i]`。 @@ -77,10 +75,6 @@ DFS 找到每个病毒区域 `areas[i]`,同时记录每个区域边界节点 ` -### **Python3** - - - ```python class Solution: def containVirus(self, isInfected: List[List[int]]) -> int: @@ -127,10 +121,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int[] DIRS = {-1, 0, 1, 0, -1}; @@ -224,8 +214,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -314,8 +302,6 @@ public: }; ``` -### **Go** - ```go func containVirus(isInfected [][]int) int { m, n := len(isInfected), len(isInfected[0]) @@ -400,10 +386,6 @@ func containVirus(isInfected [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0749.Contain Virus/README_EN.md b/solution/0700-0799/0749.Contain Virus/README_EN.md index 5948720ffb155..c57c9d2a968f8 100644 --- a/solution/0700-0799/0749.Contain Virus/README_EN.md +++ b/solution/0700-0799/0749.Contain Virus/README_EN.md @@ -55,9 +55,9 @@ Notice that walls are only built on the shared boundary of two different cells. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -105,8 +105,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int[] DIRS = {-1, 0, 1, 0, -1}; @@ -200,8 +198,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -290,8 +286,6 @@ public: }; ``` -### **Go** - ```go func containVirus(isInfected [][]int) int { m, n := len(isInfected), len(isInfected[0]) @@ -376,10 +370,6 @@ func containVirus(isInfected [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0750.Number Of Corner Rectangles/README.md b/solution/0700-0799/0750.Number Of Corner Rectangles/README.md index 5683fb151d3f3..c239ec2763290 100644 --- a/solution/0700-0799/0750.Number Of Corner Rectangles/README.md +++ b/solution/0700-0799/0750.Number Of Corner Rectangles/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:哈希表 + 枚举** +### 方法一:哈希表 + 枚举 我们枚举每一行作为矩形的下边,对于当前行,如果列 $i$ 和列 $j$ 都是 $1$,那么我们用哈希表找出此前的所有行中,有多少行的 $i$ 和 $j$ 列都是 $1$,那么就有多少个以 $(i, j)$ 为右下角的矩形,我们将其数量加入答案。然后将 $(i, j)$ 加入哈希表,继续枚举下一对 $(i, j)$。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countCornerRectangles(int[][] grid) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func countCornerRectangles(grid [][]int) (ans int) { n := len(grid[0]) @@ -166,8 +152,6 @@ func countCornerRectangles(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function countCornerRectangles(grid: number[][]): number { const n = grid[0].length; @@ -190,10 +174,6 @@ function countCornerRectangles(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0750.Number Of Corner Rectangles/README_EN.md b/solution/0700-0799/0750.Number Of Corner Rectangles/README_EN.md index c7319e005b52b..78462b231d659 100644 --- a/solution/0700-0799/0750.Number Of Corner Rectangles/README_EN.md +++ b/solution/0700-0799/0750.Number Of Corner Rectangles/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Hash Table + Enumeration** +### Solution 1: Hash Table + Enumeration We enumerate each row as the bottom of the rectangle. For the current row, if both column $i$ and column $j$ are $1$, then we use a hash table to find out how many of the previous rows have both columns $i$ and $j$ as $1$. This is the number of rectangles with $(i, j)$ as the bottom right corner, and we add this number to the answer. Then we add $(i, j)$ to the hash table and continue to enumerate the next pair $(i, j)$. @@ -54,8 +54,6 @@ The time complexity is $O(m \times n^2)$, and the space complexity is $O(n^2)$. -### **Python3** - ```python class Solution: def countCornerRectangles(self, grid: List[List[int]]) -> int: @@ -72,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countCornerRectangles(int[][] grid) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +118,6 @@ public: }; ``` -### **Go** - ```go func countCornerRectangles(grid [][]int) (ans int) { n := len(grid[0]) @@ -148,8 +140,6 @@ func countCornerRectangles(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function countCornerRectangles(grid: number[][]): number { const n = grid[0].length; @@ -172,10 +162,6 @@ function countCornerRectangles(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0751.IP to CIDR/README.md b/solution/0700-0799/0751.IP to CIDR/README.md index c9d08f9f94b87..536ddc7565b2f 100644 --- a/solution/0700-0799/0751.IP to CIDR/README.md +++ b/solution/0700-0799/0751.IP to CIDR/README.md @@ -67,30 +67,4 @@ CIDR区块“255.0.0.16/32”包含最后一个地址。 ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0700-0799/0751.IP to CIDR/README_EN.md b/solution/0700-0799/0751.IP to CIDR/README_EN.md index 13f92b4a83bcb..d41b0b5a68cb2 100644 --- a/solution/0700-0799/0751.IP to CIDR/README_EN.md +++ b/solution/0700-0799/0751.IP to CIDR/README_EN.md @@ -63,24 +63,4 @@ Note that while the CIDR block "255.0.0.0/28" does cover all the addre ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0700-0799/0752.Open the Lock/README.md b/solution/0700-0799/0752.Open the Lock/README.md index 83d6c1a9ed93c..a181d5de798cc 100644 --- a/solution/0700-0799/0752.Open the Lock/README.md +++ b/solution/0700-0799/0752.Open the Lock/README.md @@ -57,68 +57,12 @@ ## 解法 - - -BFS 最小步数模型。 - -**方法一:朴素 BFS** +### 方法一:朴素 BFS 直接用朴素 BFS。 -**方法二:双向 BFS** - -本题也可以用双向 BFS 优化搜索空间,从而提升效率。 - -双向 BFS 是 BFS 常见的一个优化方法,主要实现思路如下: - -1. 创建两个队列 q1, q2 分别用于“起点 -> 终点”、“终点 -> 起点”两个方向的搜索; -2. 创建两个哈希表 m1, m2 分别记录访问过的节点以及对应的扩展次数(步数); -3. 每次搜索时,优先选择元素数量较少的队列进行搜索扩展,如果在扩展过程中,搜索到另一个方向已经访问过的节点,说明找到了最短路径; -4. 只要其中一个队列为空,说明当前方向的搜索已经进行不下去了,说明起点到终点不连通,无需继续搜索。 - -```python -while q1 and q2: - if len(q1) <= len(q2): - # 优先选择较少元素的队列进行扩展 - extend(m1, m2, q1) - else: - extend(m2, m1, q2) - - -def extend(m1, m2, q): - # 新一轮扩展 - for _ in range(len(q)): - p = q.popleft() - step = m1[p] - for t in next(p): - if t in m1: - # 此前已经访问过 - continue - if t in m2: - # 另一个方向已经搜索过,说明找到了一条最短的连通路径 - return step + 1 + m2[t] - q.append(t) - m1[t] = step + 1 -``` - -**方法三:A\*算法** - -A\* 算法主要思想如下: - -1. 将 BFS 队列转换为优先队列(小根堆); -1. 队列中的每个元素为 `(dist[state] + f(state), state)`,`dist[state]` 表示从起点到当前 state 的距离,`f(state)` 表示从当前 state 到终点的估计距离,这两个距离之和作为堆排序的依据; -1. 当终点第一次出队时,说明找到了从起点到终点的最短路径,直接返回对应的 step; -1. `f(state)` 是估价函数,并且估价函数要满足 `f(state) <= g(state)`,其中 `g(state)` 表示 state 到终点的真实距离; -1. A\* 算法只能保证终点第一次出队时,即找到了一条从起点到终点的最小路径,不能保证其他点出队时也是从起点到当前点的最短路径。 - -### **Python3** - - - -朴素 BFS: - ```python class Solution: def openLock(self, deadends: List[str], target: str) -> int: @@ -155,107 +99,6 @@ class Solution: return -1 ``` -双向 BFS 优化搜索: - -```python -class Solution: - def openLock(self, deadends: List[str], target: str) -> int: - def next(s): - res = [] - s = list(s) - for i in range(4): - c = s[i] - s[i] = '9' if c == '0' else str(int(c) - 1) - res.append(''.join(s)) - s[i] = '0' if c == '9' else str(int(c) + 1) - res.append(''.join(s)) - s[i] = c - return res - - def extend(m1, m2, q): - for _ in range(len(q)): - p = q.popleft() - step = m1[p] - for t in next(p): - if t in s or t in m1: - continue - if t in m2: - return step + 1 + m2[t] - m1[t] = step + 1 - q.append(t) - return -1 - - def bfs(): - m1, m2 = {"0000": 0}, {target: 0} - q1, q2 = deque([('0000')]), deque([(target)]) - while q1 and q2: - t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) - if t != -1: - return t - return -1 - - if target == '0000': - return 0 - s = set(deadends) - if '0000' in s: - return -1 - return bfs() -``` - -A\* 算法: - -```python -class Solution: - def openLock(self, deadends: List[str], target: str) -> int: - def next(s): - res = [] - s = list(s) - for i in range(4): - c = s[i] - s[i] = '9' if c == '0' else str(int(c) - 1) - res.append(''.join(s)) - s[i] = '0' if c == '9' else str(int(c) + 1) - res.append(''.join(s)) - s[i] = c - return res - - def f(s): - ans = 0 - for i in range(4): - a = ord(s[i]) - ord('0') - b = ord(target[i]) - ord('0') - if a > b: - a, b = b, a - ans += min(b - a, a + 10 - b) - return ans - - if target == '0000': - return 0 - s = set(deadends) - if '0000' in s: - return -1 - start = '0000' - q = [(f(start), start)] - dist = {start: 0} - while q: - _, state = heappop(q) - if state == target: - return dist[state] - for t in next(state): - if t in s: - continue - if t not in dist or dist[t] > dist[state] + 1: - dist[t] = dist[state] + 1 - heappush(q, (dist[t] + f(t), t)) - return -1 -``` - -### **Java** - - - -朴素 BFS: - ```java class Solution { public int openLock(String[] deadends, String target) { @@ -304,7 +147,185 @@ class Solution { } ``` -双向 BFS 优化搜索: +```cpp +class Solution { +public: + int openLock(vector& deadends, string target) { + unordered_set s(deadends.begin(), deadends.end()); + if (s.count("0000")) return -1; + if (target == "0000") return 0; + queue q{{"0000"}}; + s.insert("0000"); + int ans = 0; + while (!q.empty()) { + ++ans; + for (int n = q.size(); n > 0; --n) { + string p = q.front(); + q.pop(); + for (string t : next(p)) { + if (target == t) return ans; + if (!s.count(t)) { + q.push(t); + s.insert(t); + } + } + } + } + return -1; + } + + vector next(string& t) { + vector res; + for (int i = 0; i < 4; ++i) { + char c = t[i]; + t[i] = c == '0' ? '9' : (char) (c - 1); + res.push_back(t); + t[i] = c == '9' ? '0' : (char) (c + 1); + res.push_back(t); + t[i] = c; + } + return res; + } +}; +``` + +```go +func openLock(deadends []string, target string) int { + if target == "0000" { + return 0 + } + s := make(map[string]bool) + for _, d := range deadends { + s[d] = true + } + if s["0000"] { + return -1 + } + q := []string{"0000"} + s["0000"] = true + ans := 0 + next := func(t string) []string { + s := []byte(t) + var res []string + for i, b := range s { + s[i] = b - 1 + if s[i] < '0' { + s[i] = '9' + } + res = append(res, string(s)) + s[i] = b + 1 + if s[i] > '9' { + s[i] = '0' + } + res = append(res, string(s)) + s[i] = b + } + return res + } + for len(q) > 0 { + ans++ + for n := len(q); n > 0; n-- { + p := q[0] + q = q[1:] + for _, t := range next(p) { + if target == t { + return ans + } + if !s[t] { + q = append(q, t) + s[t] = true + } + } + } + } + return -1 +} +``` + + + +### 方法二:双向 BFS + +本题也可以用双向 BFS 优化搜索空间,从而提升效率。 + +双向 BFS 是 BFS 常见的一个优化方法,主要实现思路如下: + +1. 创建两个队列 q1, q2 分别用于“起点 -> 终点”、“终点 -> 起点”两个方向的搜索; +2. 创建两个哈希表 m1, m2 分别记录访问过的节点以及对应的扩展次数(步数); +3. 每次搜索时,优先选择元素数量较少的队列进行搜索扩展,如果在扩展过程中,搜索到另一个方向已经访问过的节点,说明找到了最短路径; +4. 只要其中一个队列为空,说明当前方向的搜索已经进行不下去了,说明起点到终点不连通,无需继续搜索。 + +```python +while q1 and q2: + if len(q1) <= len(q2): + # 优先选择较少元素的队列进行扩展 + extend(m1, m2, q1) + else: + extend(m2, m1, q2) + + +def extend(m1, m2, q): + # 新一轮扩展 + for _ in range(len(q)): + p = q.popleft() + step = m1[p] + for t in next(p): + if t in m1: + # 此前已经访问过 + continue + if t in m2: + # 另一个方向已经搜索过,说明找到了一条最短的连通路径 + return step + 1 + m2[t] + q.append(t) + m1[t] = step + 1 +``` + + + +```python +class Solution: + def openLock(self, deadends: List[str], target: str) -> int: + def next(s): + res = [] + s = list(s) + for i in range(4): + c = s[i] + s[i] = '9' if c == '0' else str(int(c) - 1) + res.append(''.join(s)) + s[i] = '0' if c == '9' else str(int(c) + 1) + res.append(''.join(s)) + s[i] = c + return res + + def extend(m1, m2, q): + for _ in range(len(q)): + p = q.popleft() + step = m1[p] + for t in next(p): + if t in s or t in m1: + continue + if t in m2: + return step + 1 + m2[t] + m1[t] = step + 1 + q.append(t) + return -1 + + def bfs(): + m1, m2 = {"0000": 0}, {target: 0} + q1, q2 = deque([('0000')]), deque([(target)]) + while q1 and q2: + t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) + if t != -1: + return t + return -1 + + if target == '0000': + return 0 + s = set(deadends) + if '0000' in s: + return -1 + return bfs() +``` ```java class Solution { @@ -379,8 +400,202 @@ class Solution { } ``` -A\* 算法: - +```cpp +class Solution { +public: + unordered_set s; + string start; + string target; + + int openLock(vector& deadends, string target) { + if (target == "0000") return 0; + for (auto d : deadends) s.insert(d); + if (s.count("0000")) return -1; + this->start = "0000"; + this->target = target; + return bfs(); + } + + int bfs() { + unordered_map m1; + unordered_map m2; + m1[start] = 0; + m2[target] = 0; + queue q1{{start}}; + queue q2{{target}}; + while (!q1.empty() && !q2.empty()) { + int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); + if (t != -1) return t; + } + return -1; + } + + int extend(unordered_map& m1, unordered_map& m2, queue& q) { + for (int n = q.size(); n > 0; --n) { + string p = q.front(); + int step = m1[p]; + q.pop(); + for (string t : next(p)) { + if (s.count(t) || m1.count(t)) continue; + if (m2.count(t)) return step + 1 + m2[t]; + m1[t] = step + 1; + q.push(t); + } + } + return -1; + } + + vector next(string& t) { + vector res; + for (int i = 0; i < 4; ++i) { + char c = t[i]; + t[i] = c == '0' ? '9' : (char) (c - 1); + res.push_back(t); + t[i] = c == '9' ? '0' : (char) (c + 1); + res.push_back(t); + t[i] = c; + } + return res; + } +}; +``` + +```go +func openLock(deadends []string, target string) int { + if target == "0000" { + return 0 + } + s := make(map[string]bool) + for _, d := range deadends { + s[d] = true + } + if s["0000"] { + return -1 + } + next := func(t string) []string { + s := []byte(t) + var res []string + for i, b := range s { + s[i] = b - 1 + if s[i] < '0' { + s[i] = '9' + } + res = append(res, string(s)) + s[i] = b + 1 + if s[i] > '9' { + s[i] = '0' + } + res = append(res, string(s)) + s[i] = b + } + return res + } + + extend := func(m1, m2 map[string]int, q *[]string) int { + for n := len(*q); n > 0; n-- { + p := (*q)[0] + *q = (*q)[1:] + step, _ := m1[p] + for _, t := range next(p) { + if s[t] { + continue + } + if _, ok := m1[t]; ok { + continue + } + if v, ok := m2[t]; ok { + return step + 1 + v + } + m1[t] = step + 1 + *q = append(*q, t) + } + } + return -1 + } + + bfs := func() int { + q1 := []string{"0000"} + q2 := []string{target} + m1 := map[string]int{"0000": 0} + m2 := map[string]int{target: 0} + for len(q1) > 0 && len(q2) > 0 { + t := -1 + if len(q1) <= len(q2) { + t = extend(m1, m2, &q1) + } else { + t = extend(m2, m1, &q2) + } + if t != -1 { + return t + } + } + return -1 + } + + return bfs() +} +``` + + + +### 方法三:A\*算法 + +A\* 算法主要思想如下: + +1. 将 BFS 队列转换为优先队列(小根堆); +1. 队列中的每个元素为 `(dist[state] + f(state), state)`,`dist[state]` 表示从起点到当前 state 的距离,`f(state)` 表示从当前 state 到终点的估计距离,这两个距离之和作为堆排序的依据; +1. 当终点第一次出队时,说明找到了从起点到终点的最短路径,直接返回对应的 step; +1. `f(state)` 是估价函数,并且估价函数要满足 `f(state) <= g(state)`,其中 `g(state)` 表示 state 到终点的真实距离; +1. A\* 算法只能保证终点第一次出队时,即找到了一条从起点到终点的最小路径,不能保证其他点出队时也是从起点到当前点的最短路径。 + + + +```python +class Solution: + def openLock(self, deadends: List[str], target: str) -> int: + def next(s): + res = [] + s = list(s) + for i in range(4): + c = s[i] + s[i] = '9' if c == '0' else str(int(c) - 1) + res.append(''.join(s)) + s[i] = '0' if c == '9' else str(int(c) + 1) + res.append(''.join(s)) + s[i] = c + return res + + def f(s): + ans = 0 + for i in range(4): + a = ord(s[i]) - ord('0') + b = ord(target[i]) - ord('0') + if a > b: + a, b = b, a + ans += min(b - a, a + 10 - b) + return ans + + if target == '0000': + return 0 + s = set(deadends) + if '0000' in s: + return -1 + start = '0000' + q = [(f(start), start)] + dist = {start: 0} + while q: + _, state = heappop(q) + if state == target: + return dist[state] + for t in next(state): + if t in s: + continue + if t not in dist or dist[t] > dist[state] + 1: + dist[t] = dist[state] + 1 + heappush(q, (dist[t] + f(t), t)) + return -1 +``` + ```java class Solution { private String target; @@ -453,116 +668,6 @@ class Solution { } ``` -### **C++** - -朴素 BFS: - -```cpp -class Solution { -public: - int openLock(vector& deadends, string target) { - unordered_set s(deadends.begin(), deadends.end()); - if (s.count("0000")) return -1; - if (target == "0000") return 0; - queue q{{"0000"}}; - s.insert("0000"); - int ans = 0; - while (!q.empty()) { - ++ans; - for (int n = q.size(); n > 0; --n) { - string p = q.front(); - q.pop(); - for (string t : next(p)) { - if (target == t) return ans; - if (!s.count(t)) { - q.push(t); - s.insert(t); - } - } - } - } - return -1; - } - - vector next(string& t) { - vector res; - for (int i = 0; i < 4; ++i) { - char c = t[i]; - t[i] = c == '0' ? '9' : (char) (c - 1); - res.push_back(t); - t[i] = c == '9' ? '0' : (char) (c + 1); - res.push_back(t); - t[i] = c; - } - return res; - } -}; -``` - -双向 BFS 优化搜索: - -```cpp -class Solution { -public: - unordered_set s; - string start; - string target; - - int openLock(vector& deadends, string target) { - if (target == "0000") return 0; - for (auto d : deadends) s.insert(d); - if (s.count("0000")) return -1; - this->start = "0000"; - this->target = target; - return bfs(); - } - - int bfs() { - unordered_map m1; - unordered_map m2; - m1[start] = 0; - m2[target] = 0; - queue q1{{start}}; - queue q2{{target}}; - while (!q1.empty() && !q2.empty()) { - int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); - if (t != -1) return t; - } - return -1; - } - - int extend(unordered_map& m1, unordered_map& m2, queue& q) { - for (int n = q.size(); n > 0; --n) { - string p = q.front(); - int step = m1[p]; - q.pop(); - for (string t : next(p)) { - if (s.count(t) || m1.count(t)) continue; - if (m2.count(t)) return step + 1 + m2[t]; - m1[t] = step + 1; - q.push(t); - } - } - return -1; - } - - vector next(string& t) { - vector res; - for (int i = 0; i < 4; ++i) { - char c = t[i]; - t[i] = c == '0' ? '9' : (char) (c - 1); - res.push_back(t); - t[i] = c == '9' ? '0' : (char) (c + 1); - res.push_back(t); - t[i] = c; - } - return res; - } -}; -``` - -A\* 算法: - ```cpp class Solution { public: @@ -626,145 +731,6 @@ public: }; ``` -### **Go** - -朴素 BFS: - -```go -func openLock(deadends []string, target string) int { - if target == "0000" { - return 0 - } - s := make(map[string]bool) - for _, d := range deadends { - s[d] = true - } - if s["0000"] { - return -1 - } - q := []string{"0000"} - s["0000"] = true - ans := 0 - next := func(t string) []string { - s := []byte(t) - var res []string - for i, b := range s { - s[i] = b - 1 - if s[i] < '0' { - s[i] = '9' - } - res = append(res, string(s)) - s[i] = b + 1 - if s[i] > '9' { - s[i] = '0' - } - res = append(res, string(s)) - s[i] = b - } - return res - } - for len(q) > 0 { - ans++ - for n := len(q); n > 0; n-- { - p := q[0] - q = q[1:] - for _, t := range next(p) { - if target == t { - return ans - } - if !s[t] { - q = append(q, t) - s[t] = true - } - } - } - } - return -1 -} -``` - -双向 BFS 优化搜索: - -```go -func openLock(deadends []string, target string) int { - if target == "0000" { - return 0 - } - s := make(map[string]bool) - for _, d := range deadends { - s[d] = true - } - if s["0000"] { - return -1 - } - next := func(t string) []string { - s := []byte(t) - var res []string - for i, b := range s { - s[i] = b - 1 - if s[i] < '0' { - s[i] = '9' - } - res = append(res, string(s)) - s[i] = b + 1 - if s[i] > '9' { - s[i] = '0' - } - res = append(res, string(s)) - s[i] = b - } - return res - } - - extend := func(m1, m2 map[string]int, q *[]string) int { - for n := len(*q); n > 0; n-- { - p := (*q)[0] - *q = (*q)[1:] - step, _ := m1[p] - for _, t := range next(p) { - if s[t] { - continue - } - if _, ok := m1[t]; ok { - continue - } - if v, ok := m2[t]; ok { - return step + 1 + v - } - m1[t] = step + 1 - *q = append(*q, t) - } - } - return -1 - } - - bfs := func() int { - q1 := []string{"0000"} - q2 := []string{target} - m1 := map[string]int{"0000": 0} - m2 := map[string]int{target: 0} - for len(q1) > 0 && len(q2) > 0 { - t := -1 - if len(q1) <= len(q2) { - t = extend(m1, m2, &q1) - } else { - t = extend(m2, m1, &q2) - } - if t != -1 { - return t - } - } - return -1 - } - - return bfs() -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0752.Open the Lock/README_EN.md b/solution/0700-0799/0752.Open the Lock/README_EN.md index d6bfbd884cf52..542d1f960330d 100644 --- a/solution/0700-0799/0752.Open the Lock/README_EN.md +++ b/solution/0700-0799/0752.Open the Lock/README_EN.md @@ -53,14 +53,10 @@ because the wheels of the lock become stuck after the display becomes the dead e ## Solutions -BFS. +### Solution 1 -### **Python3** - -BFS: - ```python class Solution: def openLock(self, deadends: List[str], target: str) -> int: @@ -97,57 +93,6 @@ class Solution: return -1 ``` -Two-end BFS: - -```python -class Solution: - def openLock(self, deadends: List[str], target: str) -> int: - def next(s): - res = [] - s = list(s) - for i in range(4): - c = s[i] - s[i] = '9' if c == '0' else str(int(c) - 1) - res.append(''.join(s)) - s[i] = '0' if c == '9' else str(int(c) + 1) - res.append(''.join(s)) - s[i] = c - return res - - def extend(m1, m2, q): - for _ in range(len(q)): - p = q.popleft() - step = m1[p] - for t in next(p): - if t in s or t in m1: - continue - if t in m2: - return step + 1 + m2[t] - m1[t] = step + 1 - q.append(t) - return -1 - - def bfs(): - m1, m2 = {"0000": 0}, {target: 0} - q1, q2 = deque([('0000')]), deque([(target)]) - while q1 and q2: - t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) - if t != -1: - return t - return -1 - - if target == '0000': - return 0 - s = set(deadends) - if '0000' in s: - return -1 - return bfs() -``` - -### **Java** - -BFS: - ```java class Solution { public int openLock(String[] deadends, String target) { @@ -196,7 +141,151 @@ class Solution { } ``` -Two-end BFS: +```cpp +class Solution { +public: + int openLock(vector& deadends, string target) { + unordered_set s(deadends.begin(), deadends.end()); + if (s.count("0000")) return -1; + if (target == "0000") return 0; + queue q{{"0000"}}; + s.insert("0000"); + int ans = 0; + while (!q.empty()) { + ++ans; + for (int n = q.size(); n > 0; --n) { + string p = q.front(); + q.pop(); + for (string t : next(p)) { + if (target == t) return ans; + if (!s.count(t)) { + q.push(t); + s.insert(t); + } + } + } + } + return -1; + } + + vector next(string& t) { + vector res; + for (int i = 0; i < 4; ++i) { + char c = t[i]; + t[i] = c == '0' ? '9' : (char) (c - 1); + res.push_back(t); + t[i] = c == '9' ? '0' : (char) (c + 1); + res.push_back(t); + t[i] = c; + } + return res; + } +}; +``` + +```go +func openLock(deadends []string, target string) int { + if target == "0000" { + return 0 + } + s := make(map[string]bool) + for _, d := range deadends { + s[d] = true + } + if s["0000"] { + return -1 + } + q := []string{"0000"} + s["0000"] = true + ans := 0 + next := func(t string) []string { + s := []byte(t) + var res []string + for i, b := range s { + s[i] = b - 1 + if s[i] < '0' { + s[i] = '9' + } + res = append(res, string(s)) + s[i] = b + 1 + if s[i] > '9' { + s[i] = '0' + } + res = append(res, string(s)) + s[i] = b + } + return res + } + for len(q) > 0 { + ans++ + for n := len(q); n > 0; n-- { + p := q[0] + q = q[1:] + for _, t := range next(p) { + if target == t { + return ans + } + if !s[t] { + q = append(q, t) + s[t] = true + } + } + } + } + return -1 +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def openLock(self, deadends: List[str], target: str) -> int: + def next(s): + res = [] + s = list(s) + for i in range(4): + c = s[i] + s[i] = '9' if c == '0' else str(int(c) - 1) + res.append(''.join(s)) + s[i] = '0' if c == '9' else str(int(c) + 1) + res.append(''.join(s)) + s[i] = c + return res + + def extend(m1, m2, q): + for _ in range(len(q)): + p = q.popleft() + step = m1[p] + for t in next(p): + if t in s or t in m1: + continue + if t in m2: + return step + 1 + m2[t] + m1[t] = step + 1 + q.append(t) + return -1 + + def bfs(): + m1, m2 = {"0000": 0}, {target: 0} + q1, q2 = deque([('0000')]), deque([(target)]) + while q1 and q2: + t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) + if t != -1: + return t + return -1 + + if target == '0000': + return 0 + s = set(deadends) + if '0000' in s: + return -1 + return bfs() +``` ```java class Solution { @@ -271,154 +360,32 @@ class Solution { } ``` -A\* search: - -```java +```cpp class Solution { - private String target; +public: + unordered_set s; + string start; + string target; - public int openLock(String[] deadends, String target) { - if ("0000".equals(target)) { - return 0; - } - String start = "0000"; - this.target = target; - Set s = new HashSet<>(); - for (String d : deadends) { - s.add(d); - } - if (s.contains(start)) { - return -1; - } - PriorityQueue> q - = new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)); - q.offer(new Pair<>(f(start), start)); - Map dist = new HashMap<>(); - dist.put(start, 0); - while (!q.isEmpty()) { - String state = q.poll().getValue(); - int step = dist.get(state); - if (target.equals(state)) { - return step; - } - for (String t : next(state)) { - if (s.contains(t)) { - continue; - } - if (!dist.containsKey(t) || dist.get(t) > step + 1) { - dist.put(t, step + 1); - q.offer(new Pair<>(step + 1 + f(t), t)); - } - } - } - return -1; - } - - private int f(String s) { - int ans = 0; - for (int i = 0; i < 4; ++i) { - int a = s.charAt(i) - '0'; - int b = target.charAt(i) - '0'; - if (a > b) { - int t = a; - a = b; - b = a; - } - ans += Math.min(b - a, a + 10 - b); - } - return ans; - } - - private List next(String t) { - List res = new ArrayList<>(); - char[] chars = t.toCharArray(); - for (int i = 0; i < 4; ++i) { - char c = chars[i]; - chars[i] = c == '0' ? '9' : (char) (c - 1); - res.add(String.valueOf(chars)); - chars[i] = c == '9' ? '0' : (char) (c + 1); - res.add(String.valueOf(chars)); - chars[i] = c; - } - return res; - } -} -``` - -### **C++** - -BFS: - -```cpp -class Solution { -public: - int openLock(vector& deadends, string target) { - unordered_set s(deadends.begin(), deadends.end()); - if (s.count("0000")) return -1; - if (target == "0000") return 0; - queue q{{"0000"}}; - s.insert("0000"); - int ans = 0; - while (!q.empty()) { - ++ans; - for (int n = q.size(); n > 0; --n) { - string p = q.front(); - q.pop(); - for (string t : next(p)) { - if (target == t) return ans; - if (!s.count(t)) { - q.push(t); - s.insert(t); - } - } - } - } - return -1; - } - - vector next(string& t) { - vector res; - for (int i = 0; i < 4; ++i) { - char c = t[i]; - t[i] = c == '0' ? '9' : (char) (c - 1); - res.push_back(t); - t[i] = c == '9' ? '0' : (char) (c + 1); - res.push_back(t); - t[i] = c; - } - return res; - } -}; -``` - -Two-end BFS: - -```cpp -class Solution { -public: - unordered_set s; - string start; - string target; - - int openLock(vector& deadends, string target) { - if (target == "0000") return 0; - for (auto d : deadends) s.insert(d); - if (s.count("0000")) return -1; - this->start = "0000"; - this->target = target; - return bfs(); - } - - int bfs() { - unordered_map m1; - unordered_map m2; - m1[start] = 0; - m2[target] = 0; - queue q1{{start}}; - queue q2{{target}}; - while (!q1.empty() && !q2.empty()) { - int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); - if (t != -1) return t; + int openLock(vector& deadends, string target) { + if (target == "0000") return 0; + for (auto d : deadends) s.insert(d); + if (s.count("0000")) return -1; + this->start = "0000"; + this->target = target; + return bfs(); + } + + int bfs() { + unordered_map m1; + unordered_map m2; + m1[start] = 0; + m2[target] = 0; + queue q1{{start}}; + queue q2{{target}}; + while (!q1.empty() && !q2.empty()) { + int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); + if (t != -1) return t; } return -1; } @@ -453,130 +420,6 @@ public: }; ``` -A\* search: - -```cpp -class Solution { -public: - string target; - - int openLock(vector& deadends, string target) { - if (target == "0000") return 0; - unordered_set s(deadends.begin(), deadends.end()); - if (s.count("0000")) return -1; - string start = "0000"; - this->target = target; - typedef pair PIS; - priority_queue, greater> q; - unordered_map dist; - dist[start] = 0; - q.push({f(start), start}); - while (!q.empty()) { - PIS t = q.top(); - q.pop(); - string state = t.second; - int step = dist[state]; - if (state == target) return step; - for (string& t : next(state)) { - if (s.count(t)) continue; - if (!dist.count(t) || dist[t] > step + 1) { - dist[t] = step + 1; - q.push({step + 1 + f(t), t}); - } - } - } - return -1; - } - - int f(string s) { - int ans = 0; - for (int i = 0; i < 4; ++i) { - int a = s[i] - '0'; - int b = target[i] - '0'; - if (a < b) { - int t = a; - a = b; - b = t; - } - ans += min(b - a, a + 10 - b); - } - return ans; - } - - vector next(string& t) { - vector res; - for (int i = 0; i < 4; ++i) { - char c = t[i]; - t[i] = c == '0' ? '9' : (char) (c - 1); - res.push_back(t); - t[i] = c == '9' ? '0' : (char) (c + 1); - res.push_back(t); - t[i] = c; - } - return res; - } -}; -``` - -### **Go** - -BFS: - -```go -func openLock(deadends []string, target string) int { - if target == "0000" { - return 0 - } - s := make(map[string]bool) - for _, d := range deadends { - s[d] = true - } - if s["0000"] { - return -1 - } - q := []string{"0000"} - s["0000"] = true - ans := 0 - next := func(t string) []string { - s := []byte(t) - var res []string - for i, b := range s { - s[i] = b - 1 - if s[i] < '0' { - s[i] = '9' - } - res = append(res, string(s)) - s[i] = b + 1 - if s[i] > '9' { - s[i] = '0' - } - res = append(res, string(s)) - s[i] = b - } - return res - } - for len(q) > 0 { - ans++ - for n := len(q); n > 0; n-- { - p := q[0] - q = q[1:] - for _, t := range next(p) { - if target == t { - return ans - } - if !s[t] { - q = append(q, t) - s[t] = true - } - } - } - } - return -1 -} -``` - -Two-end BFS: - ```go func openLock(deadends []string, target string) int { if target == "0000" { @@ -653,10 +496,193 @@ func openLock(deadends []string, target string) int { } ``` -### **...** + + +### Solution 3 + + +```python +class Solution: + def openLock(self, deadends: List[str], target: str) -> int: + def next(s): + res = [] + s = list(s) + for i in range(4): + c = s[i] + s[i] = '9' if c == '0' else str(int(c) - 1) + res.append(''.join(s)) + s[i] = '0' if c == '9' else str(int(c) + 1) + res.append(''.join(s)) + s[i] = c + return res + + def f(s): + ans = 0 + for i in range(4): + a = ord(s[i]) - ord('0') + b = ord(target[i]) - ord('0') + if a > b: + a, b = b, a + ans += min(b - a, a + 10 - b) + return ans + + if target == '0000': + return 0 + s = set(deadends) + if '0000' in s: + return -1 + start = '0000' + q = [(f(start), start)] + dist = {start: 0} + while q: + _, state = heappop(q) + if state == target: + return dist[state] + for t in next(state): + if t in s: + continue + if t not in dist or dist[t] > dist[state] + 1: + dist[t] = dist[state] + 1 + heappush(q, (dist[t] + f(t), t)) + return -1 ``` +```java +class Solution { + private String target; + + public int openLock(String[] deadends, String target) { + if ("0000".equals(target)) { + return 0; + } + String start = "0000"; + this.target = target; + Set s = new HashSet<>(); + for (String d : deadends) { + s.add(d); + } + if (s.contains(start)) { + return -1; + } + PriorityQueue> q + = new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)); + q.offer(new Pair<>(f(start), start)); + Map dist = new HashMap<>(); + dist.put(start, 0); + while (!q.isEmpty()) { + String state = q.poll().getValue(); + int step = dist.get(state); + if (target.equals(state)) { + return step; + } + for (String t : next(state)) { + if (s.contains(t)) { + continue; + } + if (!dist.containsKey(t) || dist.get(t) > step + 1) { + dist.put(t, step + 1); + q.offer(new Pair<>(step + 1 + f(t), t)); + } + } + } + return -1; + } + + private int f(String s) { + int ans = 0; + for (int i = 0; i < 4; ++i) { + int a = s.charAt(i) - '0'; + int b = target.charAt(i) - '0'; + if (a > b) { + int t = a; + a = b; + b = a; + } + ans += Math.min(b - a, a + 10 - b); + } + return ans; + } + + private List next(String t) { + List res = new ArrayList<>(); + char[] chars = t.toCharArray(); + for (int i = 0; i < 4; ++i) { + char c = chars[i]; + chars[i] = c == '0' ? '9' : (char) (c - 1); + res.add(String.valueOf(chars)); + chars[i] = c == '9' ? '0' : (char) (c + 1); + res.add(String.valueOf(chars)); + chars[i] = c; + } + return res; + } +} +``` + +```cpp +class Solution { +public: + string target; + + int openLock(vector& deadends, string target) { + if (target == "0000") return 0; + unordered_set s(deadends.begin(), deadends.end()); + if (s.count("0000")) return -1; + string start = "0000"; + this->target = target; + typedef pair PIS; + priority_queue, greater> q; + unordered_map dist; + dist[start] = 0; + q.push({f(start), start}); + while (!q.empty()) { + PIS t = q.top(); + q.pop(); + string state = t.second; + int step = dist[state]; + if (state == target) return step; + for (string& t : next(state)) { + if (s.count(t)) continue; + if (!dist.count(t) || dist[t] > step + 1) { + dist[t] = step + 1; + q.push({step + 1 + f(t), t}); + } + } + } + return -1; + } + + int f(string s) { + int ans = 0; + for (int i = 0; i < 4; ++i) { + int a = s[i] - '0'; + int b = target[i] - '0'; + if (a < b) { + int t = a; + a = b; + b = t; + } + ans += min(b - a, a + 10 - b); + } + return ans; + } + + vector next(string& t) { + vector res; + for (int i = 0; i < 4; ++i) { + char c = t[i]; + t[i] = c == '0' ? '9' : (char) (c - 1); + res.push_back(t); + t[i] = c == '9' ? '0' : (char) (c + 1); + res.push_back(t); + t[i] = c; + } + return res; + } +}; ``` + + diff --git a/solution/0700-0799/0753.Cracking the Safe/README.md b/solution/0700-0799/0753.Cracking the Safe/README.md index 6fbfb035f2e92..7b4615cb14a9d 100644 --- a/solution/0700-0799/0753.Cracking the Safe/README.md +++ b/solution/0700-0799/0753.Cracking the Safe/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:欧拉回路** +### 方法一:欧拉回路 我们可以对题目中所描述的内容构建有向图:将每个点看作一个长度为 $n-1$ 的 $k$ 字符串,每条边都带有一个从 $0$ 到 $k-1$ 的字符。如果点 $u$ 到点 $v$ 之间有一条有向边 $e$,假设 $e$ 携带的字符为 $c$,那么 $u+c$ 的末尾 $k-1$ 个字符形成的字符串等于 $v$,此时边 $u+c$ 就表示了一个长度为 $n$ 的密码。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def crackSafe(self, n: int, k: int) -> str: @@ -98,10 +92,6 @@ class Solution: return "".join(ans) ``` -### **Java** - - - ```java class Solution { private Set vis = new HashSet<>(); @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func crackSafe(n int, k int) string { mod := int(math.Pow(10, float64(n-1))) @@ -179,10 +165,6 @@ func crackSafe(n int, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0753.Cracking the Safe/README_EN.md b/solution/0700-0799/0753.Cracking the Safe/README_EN.md index 49394ca1ebeec..682c527424f33 100644 --- a/solution/0700-0799/0753.Cracking the Safe/README_EN.md +++ b/solution/0700-0799/0753.Cracking the Safe/README_EN.md @@ -56,9 +56,9 @@ Thus "01100" will unlock the safe. "01100", "10011" ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return "".join(ans) ``` -### **Java** - ```java class Solution { private Set vis = new HashSet<>(); @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +130,6 @@ public: }; ``` -### **Go** - ```go func crackSafe(n int, k int) string { mod := int(math.Pow(10, float64(n-1))) @@ -159,10 +153,6 @@ func crackSafe(n int, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0754.Reach a Number/README.md b/solution/0700-0799/0754.Reach a Number/README.md index 20d87e5cf8fa6..1ad8a5b802624 100644 --- a/solution/0700-0799/0754.Reach a Number/README.md +++ b/solution/0700-0799/0754.Reach a Number/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:数学分析** +### 方法一:数学分析 由于对称性,每次可以选择向左或向右移动,因此,我们可以将 $target$ 统一取绝对值。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def reachNumber(self, target: int) -> int: @@ -83,10 +77,6 @@ class Solution: s += k ``` -### **Java** - - - ```java class Solution { public int reachNumber(int target) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func reachNumber(target int) int { if target < 0 { @@ -138,8 +124,6 @@ func reachNumber(target int) int { } ``` -### **JavaScript** - ```js /** * @param {number} target @@ -158,10 +142,6 @@ var reachNumber = function (target) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0754.Reach a Number/README_EN.md b/solution/0700-0799/0754.Reach a Number/README_EN.md index c195bc5637822..7679a7148ca5d 100644 --- a/solution/0700-0799/0754.Reach a Number/README_EN.md +++ b/solution/0700-0799/0754.Reach a Number/README_EN.md @@ -47,9 +47,9 @@ On the 2nd move, we step from 1 to 3 (2 steps). ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: s += k ``` -### **Java** - ```java class Solution { public int reachNumber(int target) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +94,6 @@ public: }; ``` -### **Go** - ```go func reachNumber(target int) int { if target < 0 { @@ -116,8 +110,6 @@ func reachNumber(target int) int { } ``` -### **JavaScript** - ```js /** * @param {number} target @@ -136,10 +128,6 @@ var reachNumber = function (target) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0755.Pour Water/README.md b/solution/0700-0799/0755.Pour Water/README.md index fd7b99812c85e..0f0e68a09e057 100644 --- a/solution/0700-0799/0755.Pour Water/README.md +++ b/solution/0700-0799/0755.Pour Water/README.md @@ -141,9 +141,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以模拟每一单位的水滴下落的过程,每次下落时,我们首先尝试向左移动,如果可以移动到更低的高度,则移动到最低的高度处;如果不能移动到更低的高度,则尝试向右移动,如果可以移动到更低的高度,则移动到最低的高度处;如果不能移动到更低的高度,则在当前位置上升。 @@ -151,10 +149,6 @@ -### **Python3** - - - ```python class Solution: def pourWater(self, heights: List[int], volume: int, k: int) -> List[int]: @@ -173,10 +167,6 @@ class Solution: return heights ``` -### **Java** - - - ```java class Solution { public int[] pourWater(int[] heights, int volume, int k) { @@ -204,8 +194,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -234,10 +222,32 @@ public: }; ``` -### **...** - -``` - +```go +func pourWater(heights []int, volume int, k int) []int { + for ; volume > 0; volume-- { + find := false + for _, d := range [2]int{-1, 1} { + i, j := k, k + for i+d >= 0 && i+d < len(heights) && heights[i+d] <= heights[i] { + if heights[i+d] < heights[i] { + j = i + d + } + i += d + } + if j != k { + find = true + heights[j]++ + break + } + } + if !find { + heights[k]++ + } + } + return heights +} ``` + + diff --git a/solution/0700-0799/0755.Pour Water/README_EN.md b/solution/0700-0799/0755.Pour Water/README_EN.md index 2ef2a88aa3b3f..b69eadd104575 100644 --- a/solution/0700-0799/0755.Pour Water/README_EN.md +++ b/solution/0700-0799/0755.Pour Water/README_EN.md @@ -63,9 +63,9 @@ Finally, the fourth droplet falls at index k = 3. Since moving left would not ev ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -85,8 +85,6 @@ class Solution: return heights ``` -### **Java** - ```java class Solution { public int[] pourWater(int[] heights, int volume, int k) { @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,10 +140,32 @@ public: }; ``` -### **...** - -``` - +```go +func pourWater(heights []int, volume int, k int) []int { + for ; volume > 0; volume-- { + find := false + for _, d := range [2]int{-1, 1} { + i, j := k, k + for i+d >= 0 && i+d < len(heights) && heights[i+d] <= heights[i] { + if heights[i+d] < heights[i] { + j = i + d + } + i += d + } + if j != k { + find = true + heights[j]++ + break + } + } + if !find { + heights[k]++ + } + } + return heights +} ``` + + diff --git a/solution/0700-0799/0756.Pyramid Transition Matrix/README.md b/solution/0700-0799/0756.Pyramid Transition Matrix/README.md index ac2338f8d9f85..6c0b06784c537 100644 --- a/solution/0700-0799/0756.Pyramid Transition Matrix/README.md +++ b/solution/0700-0799/0756.Pyramid Transition Matrix/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 定义哈希表 $d$ 存放允许的三角形图案,其中键为两个字符,值为对应的字符列表,表示两个字符可以组成一个三角形图案,三角形图案的顶部为值列表的每一项。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool: @@ -94,10 +88,6 @@ class Solution: return dfs(bottom) ``` -### **Java** - - - ```java class Solution { private int[][] f = new int[7][7]; @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -184,8 +172,6 @@ public: }; ``` -### **Go** - ```go func pyramidTransition(bottom string, allowed []string) bool { f := make([][]int, 7) @@ -228,10 +214,6 @@ func pyramidTransition(bottom string, allowed []string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0756.Pyramid Transition Matrix/README_EN.md b/solution/0700-0799/0756.Pyramid Transition Matrix/README_EN.md index a7068818f49aa..1a0b82173bf48 100644 --- a/solution/0700-0799/0756.Pyramid Transition Matrix/README_EN.md +++ b/solution/0700-0799/0756.Pyramid Transition Matrix/README_EN.md @@ -49,9 +49,9 @@ Starting from the bottom (level 4), there are multiple ways to build level 3, bu ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return dfs(bottom) ``` -### **Java** - ```java class Solution { private int[][] f = new int[7][7]; @@ -118,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +158,6 @@ public: }; ``` -### **Go** - ```go func pyramidTransition(bottom string, allowed []string) bool { f := make([][]int, 7) @@ -206,10 +200,6 @@ func pyramidTransition(bottom string, allowed []string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0757.Set Intersection Size At Least Two/README.md b/solution/0700-0799/0757.Set Intersection Size At Least Two/README.md index a9d1ec26dc548..eaf9cef02c9d7 100644 --- a/solution/0700-0799/0757.Set Intersection Size At Least Two/README.md +++ b/solution/0700-0799/0757.Set Intersection Size At Least Two/README.md @@ -57,18 +57,12 @@ ## 解法 - - -**方法一:排序 + 贪心** +### 方法一:排序 + 贪心 相似题目: [452. 用最少数量的箭引爆气球](/solution/0400-0499/0452.Minimum%20Number%20of%20Arrows%20to%20Burst%20Balloons/README.md) -### **Python3** - - - ```python class Solution: def intersectionSizeTwo(self, intervals: List[List[int]]) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int intersectionSizeTwo(int[][] intervals) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func intersectionSizeTwo(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { @@ -176,10 +162,6 @@ func intersectionSizeTwo(intervals [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0757.Set Intersection Size At Least Two/README_EN.md b/solution/0700-0799/0757.Set Intersection Size At Least Two/README_EN.md index 257fd3e1dd38d..6e5df9b473ce5 100644 --- a/solution/0700-0799/0757.Set Intersection Size At Least Two/README_EN.md +++ b/solution/0700-0799/0757.Set Intersection Size At Least Two/README_EN.md @@ -53,9 +53,9 @@ It can be shown that there cannot be any containing array of size 4. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int intersectionSizeTwo(int[][] intervals) { @@ -103,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +128,6 @@ public: }; ``` -### **Go** - ```go func intersectionSizeTwo(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { @@ -162,10 +156,6 @@ func intersectionSizeTwo(intervals [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0758.Bold Words in String/README.md b/solution/0700-0799/0758.Bold Words in String/README.md index c4b5c431f1869..2e711406840f2 100644 --- a/solution/0700-0799/0758.Bold Words in String/README.md +++ b/solution/0700-0799/0758.Bold Words in String/README.md @@ -44,18 +44,12 @@ ## 解法 - - -**方法一:前缀树 + 区间合并** +### 方法一:前缀树 + 区间合并 相似题目:[1065. 字符串的索引对](/solution/1000-1099/1065.Index%20Pairs%20of%20a%20String/README.md)、[616. 给字符串添加加粗标签](/solution/0600-0699/0616.Add%20Bold%20Tag%20in%20String/README.md) -### **Python3** - - - ```python class Trie: def __init__(self): @@ -118,10 +112,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Trie { Trie[] children = new Trie[128]; @@ -199,8 +189,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -270,8 +258,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [128]*Trie @@ -348,10 +334,6 @@ func boldWords(words []string, s string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0758.Bold Words in String/README_EN.md b/solution/0700-0799/0758.Bold Words in String/README_EN.md index 7d49cab7e2eeb..f565e88dbda2c 100644 --- a/solution/0700-0799/0758.Bold Words in String/README_EN.md +++ b/solution/0700-0799/0758.Bold Words in String/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -105,8 +105,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Trie { Trie[] children = new Trie[128]; @@ -184,8 +182,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -255,8 +251,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [128]*Trie @@ -333,10 +327,6 @@ func boldWords(words []string, s string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0759.Employee Free Time/README.md b/solution/0700-0799/0759.Employee Free Time/README.md index 82815b1005796..1c45b77e9d7c8 100644 --- a/solution/0700-0799/0759.Employee Free Time/README.md +++ b/solution/0700-0799/0759.Employee Free Time/README.md @@ -51,30 +51,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0700-0799/0759.Employee Free Time/README_EN.md b/solution/0700-0799/0759.Employee Free Time/README_EN.md index 318709dd28593..245986f30d2e9 100644 --- a/solution/0700-0799/0759.Employee Free Time/README_EN.md +++ b/solution/0700-0799/0759.Employee Free Time/README_EN.md @@ -40,24 +40,4 @@ We discard any intervals that contain inf as they aren't finite. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0700-0799/0760.Find Anagram Mappings/README.md b/solution/0700-0799/0760.Find Anagram Mappings/README.md index 5953360cf81b8..7e9a89326bdc4 100644 --- a/solution/0700-0799/0760.Find Anagram Mappings/README.md +++ b/solution/0700-0799/0760.Find Anagram Mappings/README.md @@ -40,14 +40,10 @@ B = [50, 12, 32, 46, 28] ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def anagramMappings(self, nums1: List[int], nums2: List[int]) -> List[int]: @@ -57,10 +53,6 @@ class Solution: return [mapper[num].pop() for num in nums1] ``` -### **Java** - - - ```java class Solution { public int[] anagramMappings(int[] nums1, int[] nums2) { @@ -79,10 +71,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0760.Find Anagram Mappings/README_EN.md b/solution/0700-0799/0760.Find Anagram Mappings/README_EN.md index debbded830380..3bbfb72aed861 100644 --- a/solution/0700-0799/0760.Find Anagram Mappings/README_EN.md +++ b/solution/0700-0799/0760.Find Anagram Mappings/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return [mapper[num].pop() for num in nums1] ``` -### **Java** - ```java class Solution { public int[] anagramMappings(int[] nums1, int[] nums2) { @@ -71,10 +69,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0761.Special Binary String/README.md b/solution/0700-0799/0761.Special Binary String/README.md index 9b930b4c4f996..193276fb457f2 100644 --- a/solution/0700-0799/0761.Special Binary String/README.md +++ b/solution/0700-0799/0761.Special Binary String/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:递归 + 排序** +### 方法一:递归 + 排序 我们可以把特殊的二进制序列看作“有效的括号”,$1$ 代表左括号,$0$ 代表右括号。例如,"11011000" 可以看作:"(()(()))"。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python class Solution: def makeLargestSpecial(self, s: str) -> str: @@ -72,10 +66,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String makeLargestSpecial(String s) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func makeLargestSpecial(s string) string { if s == "" { @@ -145,10 +131,6 @@ func makeLargestSpecial(s string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0761.Special Binary String/README_EN.md b/solution/0700-0799/0761.Special Binary String/README_EN.md index a2b67d1f7b453..8a82f326971a2 100644 --- a/solution/0700-0799/0761.Special Binary String/README_EN.md +++ b/solution/0700-0799/0761.Special Binary String/README_EN.md @@ -45,9 +45,9 @@ This is the lexicographically largest string possible after some number of swaps ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String makeLargestSpecial(String s) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func makeLargestSpecial(s string) string { if s == "" { @@ -138,10 +132,6 @@ func makeLargestSpecial(s string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/README.md b/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/README.md index 6c23de113d8b4..fdd8cee5e83c6 100644 --- a/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/README.md +++ b/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:数学 + 位运算** +### 方法一:数学 + 位运算 题目中 $left$ 和 $right$ 的范围均在 $10^6$ 以内,而 $2^{20} = 1048576$,因此,二进制中 $1$ 的个数最多也就 $20$ 个,而 $20$ 以内的质数有 `[2, 3, 5, 7, 11, 13, 17, 19]`。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: @@ -78,10 +72,6 @@ class Solution: return sum(i.bit_count() in primes for i in range(left, right + 1)) ``` -### **Java** - - - ```java class Solution { private static Set primes = Set.of(2, 3, 5, 7, 11, 13, 17, 19); @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +100,6 @@ public: }; ``` -### **Go** - ```go func countPrimeSetBits(left int, right int) (ans int) { primes := map[int]int{} @@ -127,10 +113,6 @@ func countPrimeSetBits(left int, right int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/README_EN.md b/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/README_EN.md index 0c7c266688808..c578b1c2c0bf0 100644 --- a/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/README_EN.md +++ b/solution/0700-0799/0762.Prime Number of Set Bits in Binary Representation/README_EN.md @@ -52,9 +52,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return sum(i.bit_count() in primes for i in range(left, right + 1)) ``` -### **Java** - ```java class Solution { private static Set primes = Set.of(2, 3, 5, 7, 11, 13, 17, 19); @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +91,6 @@ public: }; ``` -### **Go** - ```go func countPrimeSetBits(left int, right int) (ans int) { primes := map[int]int{} @@ -110,10 +104,6 @@ func countPrimeSetBits(left int, right int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0763.Partition Labels/README.md b/solution/0700-0799/0763.Partition Labels/README.md index a2c0cc6d85f52..fbce6339b1efc 100644 --- a/solution/0700-0799/0763.Partition Labels/README.md +++ b/solution/0700-0799/0763.Partition Labels/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们先用数组或哈希表 $last$ 记录字符串 $s$ 中每个字母最后一次出现的位置。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def partitionLabels(self, s: str) -> List[int]: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List partitionLabels(String s) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func partitionLabels(s string) (ans []int) { last := [26]int{} @@ -150,8 +136,6 @@ func partitionLabels(s string) (ans []int) { } ``` -### **TypeScript** - ```ts function partitionLabels(s: string): number[] { const last: number[] = Array(26).fill(0); @@ -172,8 +156,6 @@ function partitionLabels(s: string): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn partition_labels(s: String) -> Vec { @@ -198,8 +180,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -224,8 +204,6 @@ var partitionLabels = function (s) { }; ``` -### **C#** - ```cs public class Solution { public IList PartitionLabels(string s) { @@ -247,10 +225,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0763.Partition Labels/README_EN.md b/solution/0700-0799/0763.Partition Labels/README_EN.md index a6c5dd71b1000..ceac010263f39 100644 --- a/solution/0700-0799/0763.Partition Labels/README_EN.md +++ b/solution/0700-0799/0763.Partition Labels/README_EN.md @@ -39,9 +39,9 @@ A partition like "ababcbacadefegde", "hijhklij" is incorrect ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List partitionLabels(String s) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +102,6 @@ public: }; ``` -### **Go** - ```go func partitionLabels(s string) (ans []int) { last := [26]int{} @@ -126,8 +120,6 @@ func partitionLabels(s string) (ans []int) { } ``` -### **TypeScript** - ```ts function partitionLabels(s: string): number[] { const last: number[] = Array(26).fill(0); @@ -148,8 +140,6 @@ function partitionLabels(s: string): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn partition_labels(s: String) -> Vec { @@ -174,8 +164,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -200,8 +188,6 @@ var partitionLabels = function (s) { }; ``` -### **C#** - ```cs public class Solution { public IList PartitionLabels(string s) { @@ -223,10 +209,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0764.Largest Plus Sign/README.md b/solution/0700-0799/0764.Largest Plus Sign/README.md index 6ac581f3829c3..73384c52f0f8c 100644 --- a/solution/0700-0799/0764.Largest Plus Sign/README.md +++ b/solution/0700-0799/0764.Largest Plus Sign/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $dp[i][j]$ 表示以 $(i, j)$ 为中心的最大加号标志的阶数,答案即为所有 $dp[i][j]$ 的最大值。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int: @@ -83,10 +77,6 @@ class Solution: return max(max(v) for v in dp) ``` -### **Java** - - - ```java class Solution { public int orderOfLargestPlusSign(int n, int[][] mines) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func orderOfLargestPlusSign(n int, mines [][]int) (ans int) { dp := make([][]int, n) @@ -186,10 +172,6 @@ func orderOfLargestPlusSign(n int, mines [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0764.Largest Plus Sign/README_EN.md b/solution/0700-0799/0764.Largest Plus Sign/README_EN.md index 79d5c0b73300f..17822b1984d4e 100644 --- a/solution/0700-0799/0764.Largest Plus Sign/README_EN.md +++ b/solution/0700-0799/0764.Largest Plus Sign/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return max(max(v) for v in dp) ``` -### **Java** - ```java class Solution { public int orderOfLargestPlusSign(int n, int[][] mines) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +117,6 @@ public: }; ``` -### **Go** - ```go func orderOfLargestPlusSign(n int, mines [][]int) (ans int) { dp := make([][]int, n) @@ -164,10 +158,6 @@ func orderOfLargestPlusSign(n int, mines [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0765.Couples Holding Hands/README.md b/solution/0700-0799/0765.Couples Holding Hands/README.md index 358ccb86f7261..aca9da348e75c 100644 --- a/solution/0700-0799/0765.Couples Holding Hands/README.md +++ b/solution/0700-0799/0765.Couples Holding Hands/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:并查集** +### 方法一:并查集 我们可以给每一对情侣编号,编号 $0$ 和 $1$ 的人对应情侣 $0$,编号 $2$ 和 $3$ 的人对应情侣 $1$...即编号为 $row[i]$ 对应的情侣编号为 $\lfloor \frac{row[i]}{2} \rfloor$。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def minSwapsCouples(self, row: List[int]) -> int: @@ -80,10 +74,6 @@ class Solution: return n - sum(i == find(i) for i in range(n)) ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func minSwapsCouples(row []int) int { n := len(row) >> 1 @@ -174,8 +160,6 @@ func minSwapsCouples(row []int) int { } ``` -### **TypeScript** - ```ts function minSwapsCouples(row: number[]): number { const n = row.length >> 1; @@ -203,8 +187,6 @@ function minSwapsCouples(row: number[]): number { } ``` -### **C#** - ```cs public class Solution { private int[] p; @@ -238,10 +220,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0765.Couples Holding Hands/README_EN.md b/solution/0700-0799/0765.Couples Holding Hands/README_EN.md index 7c2b44b5cb4dc..4fd82c1aa07c5 100644 --- a/solution/0700-0799/0765.Couples Holding Hands/README_EN.md +++ b/solution/0700-0799/0765.Couples Holding Hands/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return n - sum(i == find(i) for i in range(n)) ``` -### **Java** - ```java class Solution { private int[] p; @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +118,6 @@ public: }; ``` -### **Go** - ```go func minSwapsCouples(row []int) int { n := len(row) >> 1 @@ -152,8 +146,6 @@ func minSwapsCouples(row []int) int { } ``` -### **TypeScript** - ```ts function minSwapsCouples(row: number[]): number { const n = row.length >> 1; @@ -181,8 +173,6 @@ function minSwapsCouples(row: number[]): number { } ``` -### **C#** - ```cs public class Solution { private int[] p; @@ -216,10 +206,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0766.Toeplitz Matrix/README.md b/solution/0700-0799/0766.Toeplitz Matrix/README.md index 44b295f937412..f99061bce488e 100644 --- a/solution/0700-0799/0766.Toeplitz Matrix/README.md +++ b/solution/0700-0799/0766.Toeplitz Matrix/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 遍历矩阵,若出现元素与其左上角的元素不等的情况,返回 `false`。否则,遍历结束后返回 `true`。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: @@ -78,10 +72,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public boolean isToeplitzMatrix(int[][] matrix) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func isToeplitzMatrix(matrix [][]int) bool { m, n := len(matrix), len(matrix[0]) @@ -133,8 +119,6 @@ func isToeplitzMatrix(matrix [][]int) bool { } ``` -### **JavaScript** - ```js /** * @param {number[][]} matrix @@ -154,10 +138,6 @@ var isToeplitzMatrix = function (matrix) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0766.Toeplitz Matrix/README_EN.md b/solution/0700-0799/0766.Toeplitz Matrix/README_EN.md index 82a81e4df1332..0f8ecd49c70d4 100644 --- a/solution/0700-0799/0766.Toeplitz Matrix/README_EN.md +++ b/solution/0700-0799/0766.Toeplitz Matrix/README_EN.md @@ -49,9 +49,9 @@ The diagonal "[1, 2]" has different elements. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public boolean isToeplitzMatrix(int[][] matrix) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +97,6 @@ public: }; ``` -### **Go** - ```go func isToeplitzMatrix(matrix [][]int) bool { m, n := len(matrix), len(matrix[0]) @@ -117,8 +111,6 @@ func isToeplitzMatrix(matrix [][]int) bool { } ``` -### **JavaScript** - ```js /** * @param {number[][]} matrix @@ -138,10 +130,6 @@ var isToeplitzMatrix = function (matrix) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0767.Reorganize String/README.md b/solution/0700-0799/0767.Reorganize String/README.md index 74f6644950186..0326377376072 100644 --- a/solution/0700-0799/0767.Reorganize String/README.md +++ b/solution/0700-0799/0767.Reorganize String/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 利用哈希表 cnt 统计字符串 s 中每个字符出现的次数。 @@ -47,27 +45,8 @@ 否则,按字符出现频率从大到小遍历,依次间隔 1 个位置填充字符。若位置大于等于 n,则重置为 1 继续填充。 -**方法二:贪心 + 哈希表 + 优先队列(大根堆)** - -先用哈希表 `cnt` 统计每个字母出现的次数,然后构建一个大根堆 `pq`,其中每个元素是一个 `(v, c)` 的元组,其中 `c` 是字母,`v` 是字母出现的次数。 - -重排字符串时,我们每次从堆顶弹出一个元素 `(v, c)`,将 `c` 添加到结果字符串中,并将 `(v-1, c)` 放入队列 `q` 中。当队列 `q` 的长度达到 $k$ (本题中 $k$ 为 2)及以上时,弹出队首元素,若此时 `v` 大于 0,则将队首元素放入堆中。循环,直至堆为空。 - -最后判断结果字符串的长度,若与 `s` 长度相等,则返回结果字符串,否则返回空串。 - -时间复杂度 $O(n\log n)$,其中 $n$ 是字符串 `s` 的长度。 - -相似题目: - -- [358. K 距离间隔重排字符串](/solution/0300-0399/0358.Rearrange%20String%20k%20Distance%20Apart/README.md) -- [1054. 距离相等的条形码](/solution/1000-1099/1054.Distant%20Barcodes/README.md) - -### **Python3** - - - ```python class Solution: def reorganizeString(self, s: str) -> str: @@ -88,32 +67,6 @@ class Solution: return ''.join(ans) ``` -```python -class Solution: - def reorganizeString(self, s: str) -> str: - return self.rearrangeString(s, 2) - - def rearrangeString(self, s: str, k: int) -> str: - h = [(-v, c) for c, v in Counter(s).items()] - heapify(h) - q = deque() - ans = [] - while h: - v, c = heappop(h) - v *= -1 - ans.append(c) - q.append((v - 1, c)) - if len(q) >= k: - w, c = q.popleft() - if w: - heappush(h, (-w, c)) - return "" if len(ans) != len(s) else "".join(ans) -``` - -### **Java** - - - ```java class Solution { public String reorganizeString(String s) { @@ -159,45 +112,6 @@ class Solution { } ``` -```java -class Solution { - public String reorganizeString(String s) { - return rearrangeString(s, 2); - } - - public String rearrangeString(String s, int k) { - int n = s.length(); - int[] cnt = new int[26]; - for (char c : s.toCharArray()) { - ++cnt[c - 'a']; - } - PriorityQueue pq = new PriorityQueue<>((a, b) -> b[0] - a[0]); - for (int i = 0; i < 26; ++i) { - if (cnt[i] > 0) { - pq.offer(new int[] {cnt[i], i}); - } - } - Deque q = new ArrayDeque<>(); - StringBuilder ans = new StringBuilder(); - while (!pq.isEmpty()) { - var p = pq.poll(); - int v = p[0], c = p[1]; - ans.append((char) ('a' + c)); - q.offer(new int[] {v - 1, c}); - if (q.size() >= k) { - p = q.pollFirst(); - if (p[0] > 0) { - pq.offer(p); - } - } - } - return ans.length() == n ? ans.toString() : ""; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -228,40 +142,44 @@ public: }; ``` -```cpp -class Solution { -public: - string reorganizeString(string s) { - return rearrangeString(s, 2); - } - - string rearrangeString(string s, int k) { - unordered_map cnt; - for (char c : s) ++cnt[c]; - priority_queue> pq; - for (auto& [c, v] : cnt) pq.push({v, c}); - queue> q; - string ans; - while (!pq.empty()) { - auto [v, c] = pq.top(); - pq.pop(); - ans += c; - q.push({v - 1, c}); - if (q.size() >= k) { - auto p = q.front(); - q.pop(); - if (p.first) { - pq.push(p); - } - } - } - return ans.size() == s.size() ? ans : ""; - } -}; +```go +func reorganizeString(s string) string { + cnt := make([]int, 26) + for _, c := range s { + t := c - 'a' + cnt[t]++ + } + mx := slices.Max(cnt) + n := len(s) + if mx > (n+1)/2 { + return "" + } + m := [][]int{} + for i, v := range cnt { + if v > 0 { + m = append(m, []int{v, i}) + } + } + sort.Slice(m, func(i, j int) bool { + return m[i][0] > m[j][0] + }) + ans := make([]byte, n) + k := 0 + for _, e := range m { + v, i := e[0], e[1] + for v > 0 { + ans[k] = byte('a' + i) + k += 2 + if k >= n { + k = 1 + } + v-- + } + } + return string(ans) +} ``` -### **Rust** - ```rust use std::collections::{ HashMap, BinaryHeap, VecDeque }; @@ -313,46 +231,116 @@ impl Solution { } ``` -### **Go** + -```go -func reorganizeString(s string) string { - cnt := make([]int, 26) - for _, c := range s { - t := c - 'a' - cnt[t]++ - } - mx := slices.Max(cnt) - n := len(s) - if mx > (n+1)/2 { - return "" - } - m := [][]int{} - for i, v := range cnt { - if v > 0 { - m = append(m, []int{v, i}) - } - } - sort.Slice(m, func(i, j int) bool { - return m[i][0] > m[j][0] - }) - ans := make([]byte, n) - k := 0 - for _, e := range m { - v, i := e[0], e[1] - for v > 0 { - ans[k] = byte('a' + i) - k += 2 - if k >= n { - k = 1 - } - v-- - } - } - return string(ans) +### 方法二:贪心 + 哈希表 + 优先队列(大根堆) + +先用哈希表 `cnt` 统计每个字母出现的次数,然后构建一个大根堆 `pq`,其中每个元素是一个 `(v, c)` 的元组,其中 `c` 是字母,`v` 是字母出现的次数。 + +重排字符串时,我们每次从堆顶弹出一个元素 `(v, c)`,将 `c` 添加到结果字符串中,并将 `(v-1, c)` 放入队列 `q` 中。当队列 `q` 的长度达到 $k$ (本题中 $k$ 为 2)及以上时,弹出队首元素,若此时 `v` 大于 0,则将队首元素放入堆中。循环,直至堆为空。 + +最后判断结果字符串的长度,若与 `s` 长度相等,则返回结果字符串,否则返回空串。 + +时间复杂度 $O(n\log n)$,其中 $n$ 是字符串 `s` 的长度。 + +相似题目: + +- [358. K 距离间隔重排字符串](/solution/0300-0399/0358.Rearrange%20String%20k%20Distance%20Apart/README.md) +- [1054. 距离相等的条形码](/solution/1000-1099/1054.Distant%20Barcodes/README.md) + + + +```python +class Solution: + def reorganizeString(self, s: str) -> str: + return self.rearrangeString(s, 2) + + def rearrangeString(self, s: str, k: int) -> str: + h = [(-v, c) for c, v in Counter(s).items()] + heapify(h) + q = deque() + ans = [] + while h: + v, c = heappop(h) + v *= -1 + ans.append(c) + q.append((v - 1, c)) + if len(q) >= k: + w, c = q.popleft() + if w: + heappush(h, (-w, c)) + return "" if len(ans) != len(s) else "".join(ans) +``` + +```java +class Solution { + public String reorganizeString(String s) { + return rearrangeString(s, 2); + } + + public String rearrangeString(String s, int k) { + int n = s.length(); + int[] cnt = new int[26]; + for (char c : s.toCharArray()) { + ++cnt[c - 'a']; + } + PriorityQueue pq = new PriorityQueue<>((a, b) -> b[0] - a[0]); + for (int i = 0; i < 26; ++i) { + if (cnt[i] > 0) { + pq.offer(new int[] {cnt[i], i}); + } + } + Deque q = new ArrayDeque<>(); + StringBuilder ans = new StringBuilder(); + while (!pq.isEmpty()) { + var p = pq.poll(); + int v = p[0], c = p[1]; + ans.append((char) ('a' + c)); + q.offer(new int[] {v - 1, c}); + if (q.size() >= k) { + p = q.pollFirst(); + if (p[0] > 0) { + pq.offer(p); + } + } + } + return ans.length() == n ? ans.toString() : ""; + } } ``` +```cpp +class Solution { +public: + string reorganizeString(string s) { + return rearrangeString(s, 2); + } + + string rearrangeString(string s, int k) { + unordered_map cnt; + for (char c : s) ++cnt[c]; + priority_queue> pq; + for (auto& [c, v] : cnt) pq.push({v, c}); + queue> q; + string ans; + while (!pq.empty()) { + auto [v, c] = pq.top(); + pq.pop(); + ans += c; + q.push({v - 1, c}); + if (q.size() >= k) { + auto p = q.front(); + q.pop(); + if (p.first) { + pq.push(p); + } + } + } + return ans.size() == s.size() ? ans : ""; + } +}; +``` + ```go func reorganizeString(s string) string { return rearrangeString(s, 2) @@ -405,10 +393,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0767.Reorganize String/README_EN.md b/solution/0700-0799/0767.Reorganize String/README_EN.md index a41610a2c028c..32e87c6c0bbb9 100644 --- a/solution/0700-0799/0767.Reorganize String/README_EN.md +++ b/solution/0700-0799/0767.Reorganize String/README_EN.md @@ -26,9 +26,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -50,30 +50,6 @@ class Solution: return ''.join(ans) ``` -```python -class Solution: - def reorganizeString(self, s: str) -> str: - return self.rearrangeString(s, 2) - - def rearrangeString(self, s: str, k: int) -> str: - h = [(-v, c) for c, v in Counter(s).items()] - heapify(h) - q = deque() - ans = [] - while h: - v, c = heappop(h) - v *= -1 - ans.append(c) - q.append((v - 1, c)) - if len(q) >= k: - w, c = q.popleft() - if w: - heappush(h, (-w, c)) - return "" if len(ans) != len(s) else "".join(ans) -``` - -### **Java** - ```java class Solution { public String reorganizeString(String s) { @@ -119,45 +95,6 @@ class Solution { } ``` -```java -class Solution { - public String reorganizeString(String s) { - return rearrangeString(s, 2); - } - - public String rearrangeString(String s, int k) { - int n = s.length(); - int[] cnt = new int[26]; - for (char c : s.toCharArray()) { - ++cnt[c - 'a']; - } - PriorityQueue pq = new PriorityQueue<>((a, b) -> b[0] - a[0]); - for (int i = 0; i < 26; ++i) { - if (cnt[i] > 0) { - pq.offer(new int[] {cnt[i], i}); - } - } - Deque q = new ArrayDeque<>(); - StringBuilder ans = new StringBuilder(); - while (!pq.isEmpty()) { - var p = pq.poll(); - int v = p[0], c = p[1]; - ans.append((char) ('a' + c)); - q.offer(new int[] {v - 1, c}); - if (q.size() >= k) { - p = q.pollFirst(); - if (p[0] > 0) { - pq.offer(p); - } - } - } - return ans.length() == n ? ans.toString() : ""; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -188,40 +125,44 @@ public: }; ``` -```cpp -class Solution { -public: - string reorganizeString(string s) { - return rearrangeString(s, 2); - } - - string rearrangeString(string s, int k) { - unordered_map cnt; - for (char c : s) ++cnt[c]; - priority_queue> pq; - for (auto& [c, v] : cnt) pq.push({v, c}); - queue> q; - string ans; - while (!pq.empty()) { - auto [v, c] = pq.top(); - pq.pop(); - ans += c; - q.push({v - 1, c}); - if (q.size() >= k) { - auto p = q.front(); - q.pop(); - if (p.first) { - pq.push(p); - } - } - } - return ans.size() == s.size() ? ans : ""; - } -}; +```go +func reorganizeString(s string) string { + cnt := make([]int, 26) + for _, c := range s { + t := c - 'a' + cnt[t]++ + } + mx := slices.Max(cnt) + n := len(s) + if mx > (n+1)/2 { + return "" + } + m := [][]int{} + for i, v := range cnt { + if v > 0 { + m = append(m, []int{v, i}) + } + } + sort.Slice(m, func(i, j int) bool { + return m[i][0] > m[j][0] + }) + ans := make([]byte, n) + k := 0 + for _, e := range m { + v, i := e[0], e[1] + for v > 0 { + ans[k] = byte('a' + i) + k += 2 + if k >= n { + k = 1 + } + v-- + } + } + return string(ans) +} ``` -### **Rust** - ```rust use std::collections::{ HashMap, BinaryHeap, VecDeque }; @@ -273,46 +214,103 @@ impl Solution { } ``` -### **Go** + -```go -func reorganizeString(s string) string { - cnt := make([]int, 26) - for _, c := range s { - t := c - 'a' - cnt[t]++ - } - mx := slices.Max(cnt) - n := len(s) - if mx > (n+1)/2 { - return "" - } - m := [][]int{} - for i, v := range cnt { - if v > 0 { - m = append(m, []int{v, i}) - } - } - sort.Slice(m, func(i, j int) bool { - return m[i][0] > m[j][0] - }) - ans := make([]byte, n) - k := 0 - for _, e := range m { - v, i := e[0], e[1] - for v > 0 { - ans[k] = byte('a' + i) - k += 2 - if k >= n { - k = 1 - } - v-- - } - } - return string(ans) +### Solution 2 + + + +```python +class Solution: + def reorganizeString(self, s: str) -> str: + return self.rearrangeString(s, 2) + + def rearrangeString(self, s: str, k: int) -> str: + h = [(-v, c) for c, v in Counter(s).items()] + heapify(h) + q = deque() + ans = [] + while h: + v, c = heappop(h) + v *= -1 + ans.append(c) + q.append((v - 1, c)) + if len(q) >= k: + w, c = q.popleft() + if w: + heappush(h, (-w, c)) + return "" if len(ans) != len(s) else "".join(ans) +``` + +```java +class Solution { + public String reorganizeString(String s) { + return rearrangeString(s, 2); + } + + public String rearrangeString(String s, int k) { + int n = s.length(); + int[] cnt = new int[26]; + for (char c : s.toCharArray()) { + ++cnt[c - 'a']; + } + PriorityQueue pq = new PriorityQueue<>((a, b) -> b[0] - a[0]); + for (int i = 0; i < 26; ++i) { + if (cnt[i] > 0) { + pq.offer(new int[] {cnt[i], i}); + } + } + Deque q = new ArrayDeque<>(); + StringBuilder ans = new StringBuilder(); + while (!pq.isEmpty()) { + var p = pq.poll(); + int v = p[0], c = p[1]; + ans.append((char) ('a' + c)); + q.offer(new int[] {v - 1, c}); + if (q.size() >= k) { + p = q.pollFirst(); + if (p[0] > 0) { + pq.offer(p); + } + } + } + return ans.length() == n ? ans.toString() : ""; + } } ``` +```cpp +class Solution { +public: + string reorganizeString(string s) { + return rearrangeString(s, 2); + } + + string rearrangeString(string s, int k) { + unordered_map cnt; + for (char c : s) ++cnt[c]; + priority_queue> pq; + for (auto& [c, v] : cnt) pq.push({v, c}); + queue> q; + string ans; + while (!pq.empty()) { + auto [v, c] = pq.top(); + pq.pop(); + ans += c; + q.push({v - 1, c}); + if (q.size() >= k) { + auto p = q.front(); + q.pop(); + if (p.first) { + pq.push(p); + } + } + } + return ans.size() == s.size() ? ans : ""; + } +}; +``` + ```go func reorganizeString(s string) string { return rearrangeString(s, 2) @@ -365,10 +363,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0768.Max Chunks To Make Sorted II/README.md b/solution/0700-0799/0768.Max Chunks To Make Sorted II/README.md index f1a2495404562..18d16018c60f8 100644 --- a/solution/0700-0799/0768.Max Chunks To Make Sorted II/README.md +++ b/solution/0700-0799/0768.Max Chunks To Make Sorted II/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 根据题目,我们可以发现,从左到右,每个分块都有一个最大值,并且这些分块的最大值呈单调递增(非严格递增)。我们可以用一个栈来存储这些分块的最大值。最后得到的栈的大小,也就是题目所求的最多能完成排序的块。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: @@ -73,10 +67,6 @@ class Solution: return len(stk) ``` -### **Java** - - - ```java class Solution { public int maxChunksToSorted(int[] arr) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func maxChunksToSorted(arr []int) int { var stk []int @@ -140,8 +126,6 @@ func maxChunksToSorted(arr []int) int { } ``` -### **TypeScript** - ```ts function maxChunksToSorted(arr: number[]): number { const stack = []; @@ -160,8 +144,6 @@ function maxChunksToSorted(arr: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_chunks_to_sorted(arr: Vec) -> i32 { @@ -182,10 +164,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0768.Max Chunks To Make Sorted II/README_EN.md b/solution/0700-0799/0768.Max Chunks To Make Sorted II/README_EN.md index 662082afa7370..bb2572e2aa322 100644 --- a/solution/0700-0799/0768.Max Chunks To Make Sorted II/README_EN.md +++ b/solution/0700-0799/0768.Max Chunks To Make Sorted II/README_EN.md @@ -41,9 +41,9 @@ However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks po ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return len(stk) ``` -### **Java** - ```java class Solution { public int maxChunksToSorted(int[] arr) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +100,6 @@ public: }; ``` -### **Go** - ```go func maxChunksToSorted(arr []int) int { var stk []int @@ -125,8 +119,6 @@ func maxChunksToSorted(arr []int) int { } ``` -### **TypeScript** - ```ts function maxChunksToSorted(arr: number[]): number { const stack = []; @@ -145,8 +137,6 @@ function maxChunksToSorted(arr: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_chunks_to_sorted(arr: Vec) -> i32 { @@ -167,10 +157,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0769.Max Chunks To Make Sorted/README.md b/solution/0700-0799/0769.Max Chunks To Make Sorted/README.md index c2640a4950a72..9529c0a55b0d2 100644 --- a/solution/0700-0799/0769.Max Chunks To Make Sorted/README.md +++ b/solution/0700-0799/0769.Max Chunks To Make Sorted/README.md @@ -48,30 +48,14 @@ ## 解法 - - -**方法一:贪心 + 一次遍历** +### 方法一:贪心 + 一次遍历 由于 $arr$ 是 $[0,..,n-1]$ 的一个排列,若已遍历过的数中的最大值 $mx$ 与当前遍历到的下标 $i$ 相等,说明可以进行一次分割,累加答案。 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $arr$ 的长度。 -**方法二:单调栈** - -方法一的解法有一定的局限性,若数组中存在重复元素,就无法得到正确的答案。 - -根据题目,我们可以发现,从左到右,每个分块都有一个最大值,并且这些分块的最大值呈单调递增。我们可以用一个栈来存储这些分块的最大值。最后得到的栈的大小,也就是题目所求的最多能完成排序的块。 - -以上这种解法,不仅可以解决本题,也可以解决 [768. 最多能完成排序的块 II](/solution/0700-0799/0768.Max%20Chunks%20To%20Make%20Sorted%20II/README.md) 这道困难题。大家可以自行尝试。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $arr$ 的长度。 - -### **Python3** - - - ```python class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: @@ -83,25 +67,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxChunksToSorted(self, arr: List[int]) -> int: - stk = [] - for v in arr: - if not stk or v >= stk[-1]: - stk.append(v) - else: - mx = stk.pop() - while stk and stk[-1] > v: - stk.pop() - stk.append(mx) - return len(stk) -``` - -### **Java** - - - ```java class Solution { public int maxChunksToSorted(int[] arr) { @@ -117,28 +82,6 @@ class Solution { } ``` -```java -class Solution { - public int maxChunksToSorted(int[] arr) { - Deque stk = new ArrayDeque<>(); - for (int v : arr) { - if (stk.isEmpty() || v >= stk.peek()) { - stk.push(v); - } else { - int mx = stk.pop(); - while (!stk.isEmpty() && stk.peek() > v) { - stk.pop(); - } - stk.push(mx); - } - } - return stk.size(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -153,30 +96,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxChunksToSorted(vector& arr) { - stack stk; - for (int v : arr) { - if (stk.empty() || v >= stk.top()) { - stk.push(v); - } else { - int mx = stk.top(); - stk.pop(); - while (!stk.empty() && stk.top() > v) { - stk.pop(); - } - stk.push(mx); - } - } - return stk.size(); - } -}; -``` - -### **Go** - ```go func maxChunksToSorted(arr []int) int { ans, mx := 0, 0 @@ -190,45 +109,6 @@ func maxChunksToSorted(arr []int) int { } ``` -```go -func maxChunksToSorted(arr []int) int { - stk := []int{} - for _, v := range arr { - if len(stk) == 0 || v >= stk[len(stk)-1] { - stk = append(stk, v) - } else { - mx := stk[len(stk)-1] - stk = stk[:len(stk)-1] - for len(stk) > 0 && stk[len(stk)-1] > v { - stk = stk[:len(stk)-1] - } - stk = append(stk, mx) - } - } - return len(stk) -} -``` - -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int maxChunksToSorted(int* arr, int arrSize) { - int res = 0; - int mx = -1; - for (int i = 0; i < arrSize; i++) { - mx = max(mx, arr[i]); - if (mx == i) { - res++; - } - } - return res; -} -``` - -### **TypeScript** - ```ts function maxChunksToSorted(arr: number[]): number { const n = arr.length; @@ -244,8 +124,6 @@ function maxChunksToSorted(arr: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_chunks_to_sorted(arr: Vec) -> i32 { @@ -262,10 +140,112 @@ impl Solution { } ``` -### **...** +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) + +int maxChunksToSorted(int* arr, int arrSize) { + int res = 0; + int mx = -1; + for (int i = 0; i < arrSize; i++) { + mx = max(mx, arr[i]); + if (mx == i) { + res++; + } + } + return res; +} +``` + + + +### 方法二:单调栈 + +方法一的解法有一定的局限性,若数组中存在重复元素,就无法得到正确的答案。 + +根据题目,我们可以发现,从左到右,每个分块都有一个最大值,并且这些分块的最大值呈单调递增。我们可以用一个栈来存储这些分块的最大值。最后得到的栈的大小,也就是题目所求的最多能完成排序的块。 + +以上这种解法,不仅可以解决本题,也可以解决 [768. 最多能完成排序的块 II](/solution/0700-0799/0768.Max%20Chunks%20To%20Make%20Sorted%20II/README.md) 这道困难题。大家可以自行尝试。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $arr$ 的长度。 + + + +```python +class Solution: + def maxChunksToSorted(self, arr: List[int]) -> int: + stk = [] + for v in arr: + if not stk or v >= stk[-1]: + stk.append(v) + else: + mx = stk.pop() + while stk and stk[-1] > v: + stk.pop() + stk.append(mx) + return len(stk) +``` + +```java +class Solution { + public int maxChunksToSorted(int[] arr) { + Deque stk = new ArrayDeque<>(); + for (int v : arr) { + if (stk.isEmpty() || v >= stk.peek()) { + stk.push(v); + } else { + int mx = stk.pop(); + while (!stk.isEmpty() && stk.peek() > v) { + stk.pop(); + } + stk.push(mx); + } + } + return stk.size(); + } +} +``` +```cpp +class Solution { +public: + int maxChunksToSorted(vector& arr) { + stack stk; + for (int v : arr) { + if (stk.empty() || v >= stk.top()) { + stk.push(v); + } else { + int mx = stk.top(); + stk.pop(); + while (!stk.empty() && stk.top() > v) { + stk.pop(); + } + stk.push(mx); + } + } + return stk.size(); + } +}; ``` +```go +func maxChunksToSorted(arr []int) int { + stk := []int{} + for _, v := range arr { + if len(stk) == 0 || v >= stk[len(stk)-1] { + stk = append(stk, v) + } else { + mx := stk[len(stk)-1] + stk = stk[:len(stk)-1] + for len(stk) > 0 && stk[len(stk)-1] > v { + stk = stk[:len(stk)-1] + } + stk = append(stk, mx) + } + } + return len(stk) +} ``` + + diff --git a/solution/0700-0799/0769.Max Chunks To Make Sorted/README_EN.md b/solution/0700-0799/0769.Max Chunks To Make Sorted/README_EN.md index 1c3315bd61417..53204f2b43825 100644 --- a/solution/0700-0799/0769.Max Chunks To Make Sorted/README_EN.md +++ b/solution/0700-0799/0769.Max Chunks To Make Sorted/README_EN.md @@ -43,9 +43,9 @@ However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks po ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,23 +58,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxChunksToSorted(self, arr: List[int]) -> int: - stk = [] - for v in arr: - if not stk or v >= stk[-1]: - stk.append(v) - else: - mx = stk.pop() - while stk and stk[-1] > v: - stk.pop() - stk.append(mx) - return len(stk) -``` - -### **Java** - ```java class Solution { public int maxChunksToSorted(int[] arr) { @@ -90,28 +73,6 @@ class Solution { } ``` -```java -class Solution { - public int maxChunksToSorted(int[] arr) { - Deque stk = new ArrayDeque<>(); - for (int v : arr) { - if (stk.isEmpty() || v >= stk.peek()) { - stk.push(v); - } else { - int mx = stk.pop(); - while (!stk.isEmpty() && stk.peek() > v) { - stk.pop(); - } - stk.push(mx); - } - } - return stk.size(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -126,30 +87,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxChunksToSorted(vector& arr) { - stack stk; - for (int v : arr) { - if (stk.empty() || v >= stk.top()) { - stk.push(v); - } else { - int mx = stk.top(); - stk.pop(); - while (!stk.empty() && stk.top() > v) { - stk.pop(); - } - stk.push(mx); - } - } - return stk.size(); - } -}; -``` - -### **Go** - ```go func maxChunksToSorted(arr []int) int { ans, mx := 0, 0 @@ -163,45 +100,6 @@ func maxChunksToSorted(arr []int) int { } ``` -```go -func maxChunksToSorted(arr []int) int { - stk := []int{} - for _, v := range arr { - if len(stk) == 0 || v >= stk[len(stk)-1] { - stk = append(stk, v) - } else { - mx := stk[len(stk)-1] - stk = stk[:len(stk)-1] - for len(stk) > 0 && stk[len(stk)-1] > v { - stk = stk[:len(stk)-1] - } - stk = append(stk, mx) - } - } - return len(stk) -} -``` - -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int maxChunksToSorted(int* arr, int arrSize) { - int res = 0; - int mx = -1; - for (int i = 0; i < arrSize; i++) { - mx = max(mx, arr[i]); - if (mx == i) { - res++; - } - } - return res; -} -``` - -### **TypeScript** - ```ts function maxChunksToSorted(arr: number[]): number { const n = arr.length; @@ -217,8 +115,6 @@ function maxChunksToSorted(arr: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_chunks_to_sorted(arr: Vec) -> i32 { @@ -235,10 +131,104 @@ impl Solution { } ``` -### **...** +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) + +int maxChunksToSorted(int* arr, int arrSize) { + int res = 0; + int mx = -1; + for (int i = 0; i < arrSize; i++) { + mx = max(mx, arr[i]); + if (mx == i) { + res++; + } + } + return res; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def maxChunksToSorted(self, arr: List[int]) -> int: + stk = [] + for v in arr: + if not stk or v >= stk[-1]: + stk.append(v) + else: + mx = stk.pop() + while stk and stk[-1] > v: + stk.pop() + stk.append(mx) + return len(stk) +``` + +```java +class Solution { + public int maxChunksToSorted(int[] arr) { + Deque stk = new ArrayDeque<>(); + for (int v : arr) { + if (stk.isEmpty() || v >= stk.peek()) { + stk.push(v); + } else { + int mx = stk.pop(); + while (!stk.isEmpty() && stk.peek() > v) { + stk.pop(); + } + stk.push(mx); + } + } + return stk.size(); + } +} +``` +```cpp +class Solution { +public: + int maxChunksToSorted(vector& arr) { + stack stk; + for (int v : arr) { + if (stk.empty() || v >= stk.top()) { + stk.push(v); + } else { + int mx = stk.top(); + stk.pop(); + while (!stk.empty() && stk.top() > v) { + stk.pop(); + } + stk.push(mx); + } + } + return stk.size(); + } +}; ``` +```go +func maxChunksToSorted(arr []int) int { + stk := []int{} + for _, v := range arr { + if len(stk) == 0 || v >= stk[len(stk)-1] { + stk = append(stk, v) + } else { + mx := stk[len(stk)-1] + stk = stk[:len(stk)-1] + for len(stk) > 0 && stk[len(stk)-1] > v { + stk = stk[:len(stk)-1] + } + stk = append(stk, mx) + } + } + return len(stk) +} ``` + + diff --git a/solution/0700-0799/0770.Basic Calculator IV/README.md b/solution/0700-0799/0770.Basic Calculator IV/README.md index 08cc917a65cd4..77c7dfce2dfd8 100644 --- a/solution/0700-0799/0770.Basic Calculator IV/README.md +++ b/solution/0700-0799/0770.Basic Calculator IV/README.md @@ -86,30 +86,4 @@ evalvars = ["e", "temperature"], evalints = [1, 12] ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0700-0799/0770.Basic Calculator IV/README_EN.md b/solution/0700-0799/0770.Basic Calculator IV/README_EN.md index 9af4f8b2afa68..089732f5d64c7 100644 --- a/solution/0700-0799/0770.Basic Calculator IV/README_EN.md +++ b/solution/0700-0799/0770.Basic Calculator IV/README_EN.md @@ -81,24 +81,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0700-0799/0771.Jewels and Stones/README.md b/solution/0700-0799/0771.Jewels and Stones/README.md index ff12b38653529..b4ed4d5fa9500 100644 --- a/solution/0700-0799/0771.Jewels and Stones/README.md +++ b/solution/0700-0799/0771.Jewels and Stones/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:哈希表或数组** +### 方法一:哈希表或数组 我们可以先用一个哈希表或数组 $s$ 记录所有宝石的类型。然后遍历所有石头,如果当前石头是宝石,就将答案加一。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: @@ -59,10 +53,6 @@ class Solution: return sum(c in s for c in stones) ``` -### **Java** - - - ```java class Solution { public int numJewelsInStones(String jewels, String stones) { @@ -79,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +82,6 @@ public: }; ``` -### **Go** - ```go func numJewelsInStones(jewels string, stones string) (ans int) { s := [128]int{} @@ -109,22 +95,6 @@ func numJewelsInStones(jewels string, stones string) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {string} jewels - * @param {string} stones - * @return {number} - */ -var numJewelsInStones = function (jewels, stones) { - const s = new Set(jewels.split('')); - return stones.split('').reduce((prev, val) => prev + s.has(val), 0); -}; -``` - -### **TypeScript** - ```ts function numJewelsInStones(jewels: string, stones: string): number { const s = new Set([...jewels]); @@ -136,8 +106,6 @@ function numJewelsInStones(jewels: string, stones: string): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -154,7 +122,17 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {string} jewels + * @param {string} stones + * @return {number} + */ +var numJewelsInStones = function (jewels, stones) { + const s = new Set(jewels.split('')); + return stones.split('').reduce((prev, val) => prev + s.has(val), 0); +}; +``` ```c int numJewelsInStones(char* jewels, char* stones) { @@ -170,10 +148,6 @@ int numJewelsInStones(char* jewels, char* stones) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0771.Jewels and Stones/README_EN.md b/solution/0700-0799/0771.Jewels and Stones/README_EN.md index 6ae4bbee721e1..d6f14f21b5508 100644 --- a/solution/0700-0799/0771.Jewels and Stones/README_EN.md +++ b/solution/0700-0799/0771.Jewels and Stones/README_EN.md @@ -27,9 +27,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -38,8 +38,6 @@ class Solution: return sum(c in s for c in stones) ``` -### **Java** - ```java class Solution { public int numJewelsInStones(String jewels, String stones) { @@ -56,8 +54,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -71,8 +67,6 @@ public: }; ``` -### **Go** - ```go func numJewelsInStones(jewels string, stones string) (ans int) { s := [128]int{} @@ -86,22 +80,6 @@ func numJewelsInStones(jewels string, stones string) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {string} jewels - * @param {string} stones - * @return {number} - */ -var numJewelsInStones = function (jewels, stones) { - const s = new Set(jewels.split('')); - return stones.split('').reduce((prev, val) => prev + s.has(val), 0); -}; -``` - -### **TypeScript** - ```ts function numJewelsInStones(jewels: string, stones: string): number { const s = new Set([...jewels]); @@ -113,8 +91,6 @@ function numJewelsInStones(jewels: string, stones: string): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -131,7 +107,17 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {string} jewels + * @param {string} stones + * @return {number} + */ +var numJewelsInStones = function (jewels, stones) { + const s = new Set(jewels.split('')); + return stones.split('').reduce((prev, val) => prev + s.has(val), 0); +}; +``` ```c int numJewelsInStones(char* jewels, char* stones) { @@ -147,10 +133,6 @@ int numJewelsInStones(char* jewels, char* stones) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0772.Basic Calculator III/README.md b/solution/0700-0799/0772.Basic Calculator III/README.md index 57acce68ed8c9..f742fa10a9b6a 100644 --- a/solution/0700-0799/0772.Basic Calculator III/README.md +++ b/solution/0700-0799/0772.Basic Calculator III/README.md @@ -49,30 +49,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0700-0799/0772.Basic Calculator III/README_EN.md b/solution/0700-0799/0772.Basic Calculator III/README_EN.md index 0cd3b79469b61..dc7999f4d2b11 100644 --- a/solution/0700-0799/0772.Basic Calculator III/README_EN.md +++ b/solution/0700-0799/0772.Basic Calculator III/README_EN.md @@ -45,24 +45,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0700-0799/0773.Sliding Puzzle/README.md b/solution/0700-0799/0773.Sliding Puzzle/README.md index 88726f8e5f3da..9379d4a696245 100644 --- a/solution/0700-0799/0773.Sliding Puzzle/README.md +++ b/solution/0700-0799/0773.Sliding Puzzle/README.md @@ -65,24 +65,10 @@ ## 解法 - - -BFS 最小步数模型。可以使用朴素 BFS 直接搜索,也可以使用 A\* 算法优化搜索。 - -A\* 算法主要思想如下: - -1. 将 BFS 队列转换为优先队列(小根堆); -1. 队列中的每个元素为 `(dist[state] + f(state), state)`,`dist[state]` 表示从起点到当前 state 的距离,`f(state)` 表示从当前 state 到终点的估计距离,这两个距离之和作为堆排序的依据; -1. 当终点第一次出队时,说明找到了从起点到终点的最短路径,直接返回对应的 step; -1. `f(state)` 是估价函数,并且估价函数要满足 `f(state) <= g(state)`,其中 `g(state)` 表示 state 到终点的真实距离; -1. A\* 算法只能保证终点第一次出队时,即找到了一条从起点到终点的最小路径,不能保证其他点出队时也是从起点到当前点的最短路径。 +### 方法一 -### **Python3** - - - ```python class Solution: def slidingPuzzle(self, board: List[List[int]]) -> int: @@ -131,61 +117,6 @@ class Solution: return -1 ``` -A\* 算法: - -```python -class Solution: - def slidingPuzzle(self, board: List[List[int]]) -> int: - m, n = 2, 3 - seq = [] - start, end = '', '123450' - for i in range(m): - for j in range(n): - if board[i][j] != 0: - seq.append(board[i][j]) - start += str(board[i][j]) - - def check(seq): - n = len(seq) - cnt = sum(seq[i] > seq[j] for i in range(n) for j in range(i, n)) - return cnt % 2 == 0 - - def f(s): - ans = 0 - for i in range(m * n): - if s[i] != '0': - num = ord(s[i]) - ord('1') - ans += abs(i // n - num // n) + abs(i % n - num % n) - return ans - - if not check(seq): - return -1 - q = [(f(start), start)] - dist = {start: 0} - while q: - _, state = heappop(q) - if state == end: - return dist[state] - p1 = state.index('0') - i, j = p1 // n, p1 % n - s = list(state) - for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]: - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n: - p2 = x * n + y - s[p1], s[p2] = s[p2], s[p1] - next = ''.join(s) - s[p1], s[p2] = s[p2], s[p1] - if next not in dist or dist[next] > dist[state] + 1: - dist[next] = dist[state] + 1 - heappush(q, (dist[next] + f(next), next)) - return -1 -``` - -### **Java** - - - ```java class Solution { private String[] t = new String[6]; @@ -275,7 +206,135 @@ class Solution { } ``` -A\* 算法: +```cpp +class Solution { +public: + int slidingPuzzle(vector>& board) { + string start = gets(board); + string end = "123450"; + if (start == end) return 0; + unordered_set vis; + vis.insert(start); + queue q{{start}}; + int ans = 0; + while (!q.empty()) { + ++ans; + for (int n = q.size(); n > 0; --n) { + string x = q.front(); + q.pop(); + setb(x, board); + for (string y : next(board)) { + if (y == end) return ans; + if (!vis.count(y)) { + vis.insert(y); + q.push(y); + } + } + } + } + return -1; + } + + string gets(vector>& board) { + string s = ""; + for (int i = 0; i < 2; ++i) + for (int j = 0; j < 3; ++j) + s.push_back('0' + board[i][j]); + return s; + } + + void setb(string s, vector>& board) { + for (int i = 0; i < 2; ++i) + for (int j = 0; j < 3; ++j) + board[i][j] = s[i * 3 + j] - '0'; + } + + vector next(vector>& board) { + vector res; + auto p = find0(board); + int i = p.first, j = p.second; + vector dirs = {-1, 0, 1, 0, -1}; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < 2 && y >= 0 && y < 3) { + swap(i, j, x, y, board); + res.push_back(gets(board)); + swap(i, j, x, y, board); + } + } + return res; + } + + void swap(int i, int j, int x, int y, vector>& board) { + int t = board[i][j]; + board[i][j] = board[x][y]; + board[x][y] = t; + } + + pair find0(vector>& board) { + for (int i = 0; i < 2; ++i) + for (int j = 0; j < 3; ++j) + if (board[i][j] == 0) + return {i, j}; + return {0, 0}; + } +}; +``` + + + +### 方法二 + + + +```python +class Solution: + def slidingPuzzle(self, board: List[List[int]]) -> int: + m, n = 2, 3 + seq = [] + start, end = '', '123450' + for i in range(m): + for j in range(n): + if board[i][j] != 0: + seq.append(board[i][j]) + start += str(board[i][j]) + + def check(seq): + n = len(seq) + cnt = sum(seq[i] > seq[j] for i in range(n) for j in range(i, n)) + return cnt % 2 == 0 + + def f(s): + ans = 0 + for i in range(m * n): + if s[i] != '0': + num = ord(s[i]) - ord('1') + ans += abs(i // n - num // n) + abs(i % n - num % n) + return ans + + if not check(seq): + return -1 + q = [(f(start), start)] + dist = {start: 0} + while q: + _, state = heappop(q) + if state == end: + return dist[state] + p1 = state.index('0') + i, j = p1 // n, p1 % n + s = list(state) + for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]: + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n: + p2 = x * n + y + s[p1], s[p2] = s[p2], s[p1] + next = ''.join(s) + s[p1], s[p2] = s[p2], s[p1] + if next not in dist or dist[next] > dist[state] + 1: + dist[next] = dist[state] + 1 + heappush(q, (dist[next] + f(next), next)) + return -1 +``` ```java class Solution { @@ -361,85 +420,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int slidingPuzzle(vector>& board) { - string start = gets(board); - string end = "123450"; - if (start == end) return 0; - unordered_set vis; - vis.insert(start); - queue q{{start}}; - int ans = 0; - while (!q.empty()) { - ++ans; - for (int n = q.size(); n > 0; --n) { - string x = q.front(); - q.pop(); - setb(x, board); - for (string y : next(board)) { - if (y == end) return ans; - if (!vis.count(y)) { - vis.insert(y); - q.push(y); - } - } - } - } - return -1; - } - - string gets(vector>& board) { - string s = ""; - for (int i = 0; i < 2; ++i) - for (int j = 0; j < 3; ++j) - s.push_back('0' + board[i][j]); - return s; - } - - void setb(string s, vector>& board) { - for (int i = 0; i < 2; ++i) - for (int j = 0; j < 3; ++j) - board[i][j] = s[i * 3 + j] - '0'; - } - - vector next(vector>& board) { - vector res; - auto p = find0(board); - int i = p.first, j = p.second; - vector dirs = {-1, 0, 1, 0, -1}; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < 2 && y >= 0 && y < 3) { - swap(i, j, x, y, board); - res.push_back(gets(board)); - swap(i, j, x, y, board); - } - } - return res; - } - - void swap(int i, int j, int x, int y, vector>& board) { - int t = board[i][j]; - board[i][j] = board[x][y]; - board[x][y] = t; - } - - pair find0(vector>& board) { - for (int i = 0; i < 2; ++i) - for (int j = 0; j < 3; ++j) - if (board[i][j] == 0) - return {i, j}; - return {0, 0}; - } -}; -``` - -A\* 算法: - ```cpp class Solution { public: @@ -507,10 +487,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0773.Sliding Puzzle/README_EN.md b/solution/0700-0799/0773.Sliding Puzzle/README_EN.md index 2ccdb02d6c45a..62bf84eb7c9fe 100644 --- a/solution/0700-0799/0773.Sliding Puzzle/README_EN.md +++ b/solution/0700-0799/0773.Sliding Puzzle/README_EN.md @@ -54,12 +54,10 @@ After move 5: [[1,2,3],[4,5,0]] ## Solutions -A\* search. +### Solution 1 -### **Python3** - ```python class Solution: def slidingPuzzle(self, board: List[List[int]]) -> int: @@ -108,59 +106,6 @@ class Solution: return -1 ``` -A\* search: - -```python -class Solution: - def slidingPuzzle(self, board: List[List[int]]) -> int: - m, n = 2, 3 - seq = [] - start, end = '', '123450' - for i in range(m): - for j in range(n): - if board[i][j] != 0: - seq.append(board[i][j]) - start += str(board[i][j]) - - def check(seq): - n = len(seq) - cnt = sum(seq[i] > seq[j] for i in range(n) for j in range(i, n)) - return cnt % 2 == 0 - - def f(s): - ans = 0 - for i in range(m * n): - if s[i] != '0': - num = ord(s[i]) - ord('1') - ans += abs(i // n - num // n) + abs(i % n - num % n) - return ans - - if not check(seq): - return -1 - q = [(f(start), start)] - dist = {start: 0} - while q: - _, state = heappop(q) - if state == end: - return dist[state] - p1 = state.index('0') - i, j = p1 // n, p1 % n - s = list(state) - for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]: - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n: - p2 = x * n + y - s[p1], s[p2] = s[p2], s[p1] - next = ''.join(s) - s[p1], s[p2] = s[p2], s[p1] - if next not in dist or dist[next] > dist[state] + 1: - dist[next] = dist[state] + 1 - heappush(q, (dist[next] + f(next), next)) - return -1 -``` - -### **Java** - ```java class Solution { private String[] t = new String[6]; @@ -250,7 +195,135 @@ class Solution { } ``` -A\* search: +```cpp +class Solution { +public: + int slidingPuzzle(vector>& board) { + string start = gets(board); + string end = "123450"; + if (start == end) return 0; + unordered_set vis; + vis.insert(start); + queue q{{start}}; + int ans = 0; + while (!q.empty()) { + ++ans; + for (int n = q.size(); n > 0; --n) { + string x = q.front(); + q.pop(); + setb(x, board); + for (string y : next(board)) { + if (y == end) return ans; + if (!vis.count(y)) { + vis.insert(y); + q.push(y); + } + } + } + } + return -1; + } + + string gets(vector>& board) { + string s = ""; + for (int i = 0; i < 2; ++i) + for (int j = 0; j < 3; ++j) + s.push_back('0' + board[i][j]); + return s; + } + + void setb(string s, vector>& board) { + for (int i = 0; i < 2; ++i) + for (int j = 0; j < 3; ++j) + board[i][j] = s[i * 3 + j] - '0'; + } + + vector next(vector>& board) { + vector res; + auto p = find0(board); + int i = p.first, j = p.second; + vector dirs = {-1, 0, 1, 0, -1}; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < 2 && y >= 0 && y < 3) { + swap(i, j, x, y, board); + res.push_back(gets(board)); + swap(i, j, x, y, board); + } + } + return res; + } + + void swap(int i, int j, int x, int y, vector>& board) { + int t = board[i][j]; + board[i][j] = board[x][y]; + board[x][y] = t; + } + + pair find0(vector>& board) { + for (int i = 0; i < 2; ++i) + for (int j = 0; j < 3; ++j) + if (board[i][j] == 0) + return {i, j}; + return {0, 0}; + } +}; +``` + + + +### Solution 2 + + + +```python +class Solution: + def slidingPuzzle(self, board: List[List[int]]) -> int: + m, n = 2, 3 + seq = [] + start, end = '', '123450' + for i in range(m): + for j in range(n): + if board[i][j] != 0: + seq.append(board[i][j]) + start += str(board[i][j]) + + def check(seq): + n = len(seq) + cnt = sum(seq[i] > seq[j] for i in range(n) for j in range(i, n)) + return cnt % 2 == 0 + + def f(s): + ans = 0 + for i in range(m * n): + if s[i] != '0': + num = ord(s[i]) - ord('1') + ans += abs(i // n - num // n) + abs(i % n - num % n) + return ans + + if not check(seq): + return -1 + q = [(f(start), start)] + dist = {start: 0} + while q: + _, state = heappop(q) + if state == end: + return dist[state] + p1 = state.index('0') + i, j = p1 // n, p1 % n + s = list(state) + for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]: + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n: + p2 = x * n + y + s[p1], s[p2] = s[p2], s[p1] + next = ''.join(s) + s[p1], s[p2] = s[p2], s[p1] + if next not in dist or dist[next] > dist[state] + 1: + dist[next] = dist[state] + 1 + heappush(q, (dist[next] + f(next), next)) + return -1 +``` ```java class Solution { @@ -336,85 +409,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int slidingPuzzle(vector>& board) { - string start = gets(board); - string end = "123450"; - if (start == end) return 0; - unordered_set vis; - vis.insert(start); - queue q{{start}}; - int ans = 0; - while (!q.empty()) { - ++ans; - for (int n = q.size(); n > 0; --n) { - string x = q.front(); - q.pop(); - setb(x, board); - for (string y : next(board)) { - if (y == end) return ans; - if (!vis.count(y)) { - vis.insert(y); - q.push(y); - } - } - } - } - return -1; - } - - string gets(vector>& board) { - string s = ""; - for (int i = 0; i < 2; ++i) - for (int j = 0; j < 3; ++j) - s.push_back('0' + board[i][j]); - return s; - } - - void setb(string s, vector>& board) { - for (int i = 0; i < 2; ++i) - for (int j = 0; j < 3; ++j) - board[i][j] = s[i * 3 + j] - '0'; - } - - vector next(vector>& board) { - vector res; - auto p = find0(board); - int i = p.first, j = p.second; - vector dirs = {-1, 0, 1, 0, -1}; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < 2 && y >= 0 && y < 3) { - swap(i, j, x, y, board); - res.push_back(gets(board)); - swap(i, j, x, y, board); - } - } - return res; - } - - void swap(int i, int j, int x, int y, vector>& board) { - int t = board[i][j]; - board[i][j] = board[x][y]; - board[x][y] = t; - } - - pair find0(vector>& board) { - for (int i = 0; i < 2; ++i) - for (int j = 0; j < 3; ++j) - if (board[i][j] == 0) - return {i, j}; - return {0, 0}; - } -}; -``` - -A\* search: - ```cpp class Solution { public: @@ -482,10 +476,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0774.Minimize Max Distance to Gas Station/README.md b/solution/0700-0799/0774.Minimize Max Distance to Gas Station/README.md index bc5a55bb341f0..33c0fce9b3eb8 100644 --- a/solution/0700-0799/0774.Minimize Max Distance to Gas Station/README.md +++ b/solution/0700-0799/0774.Minimize Max Distance to Gas Station/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:二分查找(浮点数二分)** +### 方法一:二分查找(浮点数二分) 我们二分枚举相邻两个加油站间的距离,找到最小的距离,使得加油站的数量不超过 $k$。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def minmaxGasDist(self, stations: List[int], k: int) -> float: @@ -72,10 +66,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public double minmaxGasDist(int[] stations, int k) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func minmaxGasDist(stations []int, k int) float64 { check := func(x float64) bool { @@ -152,10 +138,6 @@ func minmaxGasDist(stations []int, k int) float64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0774.Minimize Max Distance to Gas Station/README_EN.md b/solution/0700-0799/0774.Minimize Max Distance to Gas Station/README_EN.md index f5e8cafbb80af..033e4ed547652 100644 --- a/solution/0700-0799/0774.Minimize Max Distance to Gas Station/README_EN.md +++ b/solution/0700-0799/0774.Minimize Max Distance to Gas Station/README_EN.md @@ -32,9 +32,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { public double minmaxGasDist(int[] stations, int k) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +102,6 @@ public: }; ``` -### **Go** - ```go func minmaxGasDist(stations []int, k int) float64 { check := func(x float64) bool { @@ -130,10 +124,6 @@ func minmaxGasDist(stations []int, k int) float64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0775.Global and Local Inversions/README.md b/solution/0700-0799/0775.Global and Local Inversions/README.md index 0888c7e6745ae..8634b5895b98f 100644 --- a/solution/0700-0799/0775.Global and Local Inversions/README.md +++ b/solution/0700-0799/0775.Global and Local Inversions/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:维护前缀最大值** +### 方法一:维护前缀最大值 根据题意,我们可以发现,一个数组中的局部倒置一定是全局倒置,但是全局倒置不一定是局部倒置。也就是说,全局倒置的数量一定大于等于局部倒置的数量。 @@ -68,7 +66,63 @@ 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。 -**方法二:树状数组** + + +```python +class Solution: + def isIdealPermutation(self, nums: List[int]) -> bool: + mx = 0 + for i in range(2, len(nums)): + if (mx := max(mx, nums[i - 2])) > nums[i]: + return False + return True +``` + +```java +class Solution { + public boolean isIdealPermutation(int[] nums) { + int mx = 0; + for (int i = 2; i < nums.length; ++i) { + mx = Math.max(mx, nums[i - 2]); + if (mx > nums[i]) { + return false; + } + } + return true; + } +} +``` + +```cpp +class Solution { +public: + bool isIdealPermutation(vector& nums) { + int mx = 0; + for (int i = 2; i < nums.size(); ++i) { + mx = max(mx, nums[i - 2]); + if (mx > nums[i]) return false; + } + return true; + } +}; +``` + +```go +func isIdealPermutation(nums []int) bool { + mx := 0 + for i := 2; i < len(nums); i++ { + mx = max(mx, nums[i-2]) + if mx > nums[i] { + return false + } + } + return true +} +``` + + + +### 方法二:树状数组 这道题目实际上是一个“逆序对”问题。 @@ -85,20 +139,6 @@ -### **Python3** - - - -```python -class Solution: - def isIdealPermutation(self, nums: List[int]) -> bool: - mx = 0 - for i in range(2, len(nums)): - if (mx := max(mx, nums[i - 2])) > nums[i]: - return False - return True -``` - ```python class BinaryIndexedTree: def __init__(self, n): @@ -132,25 +172,6 @@ class Solution: return True ``` -### **Java** - - - -```java -class Solution { - public boolean isIdealPermutation(int[] nums) { - int mx = 0; - for (int i = 2; i < nums.length; ++i) { - mx = Math.max(mx, nums[i - 2]); - if (mx > nums[i]) { - return false; - } - } - return true; - } -} -``` - ```java class BinaryIndexedTree { private int n; @@ -193,22 +214,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool isIdealPermutation(vector& nums) { - int mx = 0; - for (int i = 2; i < nums.size(); ++i) { - mx = max(mx, nums[i - 2]); - if (mx > nums[i]) return false; - } - return true; - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -253,21 +258,6 @@ public: }; ``` -### **Go** - -```go -func isIdealPermutation(nums []int) bool { - mx := 0 - for i := 2; i < len(nums); i++ { - mx = max(mx, nums[i-2]) - if mx > nums[i] { - return false - } - } - return true -} -``` - ```go func isIdealPermutation(nums []int) bool { n := len(nums) @@ -313,10 +303,6 @@ func (this BinaryIndexedTree) query(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0775.Global and Local Inversions/README_EN.md b/solution/0700-0799/0775.Global and Local Inversions/README_EN.md index 3b0428584de46..b9478851c9a7c 100644 --- a/solution/0700-0799/0775.Global and Local Inversions/README_EN.md +++ b/solution/0700-0799/0775.Global and Local Inversions/README_EN.md @@ -52,9 +52,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,6 +66,54 @@ class Solution: return True ``` +```java +class Solution { + public boolean isIdealPermutation(int[] nums) { + int mx = 0; + for (int i = 2; i < nums.length; ++i) { + mx = Math.max(mx, nums[i - 2]); + if (mx > nums[i]) { + return false; + } + } + return true; + } +} +``` + +```cpp +class Solution { +public: + bool isIdealPermutation(vector& nums) { + int mx = 0; + for (int i = 2; i < nums.size(); ++i) { + mx = max(mx, nums[i - 2]); + if (mx > nums[i]) return false; + } + return true; + } +}; +``` + +```go +func isIdealPermutation(nums []int) bool { + mx := 0 + for i := 2; i < len(nums); i++ { + mx = max(mx, nums[i-2]) + if mx > nums[i] { + return false + } + } + return true +} +``` + + + +### Solution 2 + + + ```python class BinaryIndexedTree: def __init__(self, n): @@ -99,23 +147,6 @@ class Solution: return True ``` -### **Java** - -```java -class Solution { - public boolean isIdealPermutation(int[] nums) { - int mx = 0; - for (int i = 2; i < nums.length; ++i) { - mx = Math.max(mx, nums[i - 2]); - if (mx > nums[i]) { - return false; - } - } - return true; - } -} -``` - ```java class BinaryIndexedTree { private int n; @@ -158,22 +189,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool isIdealPermutation(vector& nums) { - int mx = 0; - for (int i = 2; i < nums.size(); ++i) { - mx = max(mx, nums[i - 2]); - if (mx > nums[i]) return false; - } - return true; - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -218,21 +233,6 @@ public: }; ``` -### **Go** - -```go -func isIdealPermutation(nums []int) bool { - mx := 0 - for i := 2; i < len(nums); i++ { - mx = max(mx, nums[i-2]) - if mx > nums[i] { - return false - } - } - return true -} -``` - ```go func isIdealPermutation(nums []int) bool { n := len(nums) @@ -278,10 +278,6 @@ func (this BinaryIndexedTree) query(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0776.Split BST/README.md b/solution/0700-0799/0776.Split BST/README.md index fecebbb4f5fc4..458a0cd440f7b 100644 --- a/solution/0700-0799/0776.Split BST/README.md +++ b/solution/0700-0799/0776.Split BST/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 判断 `root` 节点的情况: @@ -55,10 +53,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -85,10 +79,6 @@ class Solution: return dfs(root) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -172,8 +160,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -201,8 +187,6 @@ func splitBST(root *TreeNode, target int) []*TreeNode { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -235,10 +219,6 @@ var splitBST = function (root, target) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0776.Split BST/README_EN.md b/solution/0700-0799/0776.Split BST/README_EN.md index b707f1216c764..60bb3c4dc7f72 100644 --- a/solution/0700-0799/0776.Split BST/README_EN.md +++ b/solution/0700-0799/0776.Split BST/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -65,8 +65,6 @@ class Solution: return dfs(root) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -110,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -150,8 +146,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -179,8 +173,6 @@ func splitBST(root *TreeNode, target int) []*TreeNode { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -213,10 +205,6 @@ var splitBST = function (root, target) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0777.Swap Adjacent in LR String/README.md b/solution/0700-0799/0777.Swap Adjacent in LR String/README.md index 0f342ff42fbe4..157dbc9793574 100644 --- a/solution/0700-0799/0777.Swap Adjacent in LR String/README.md +++ b/solution/0700-0799/0777.Swap Adjacent in LR String/README.md @@ -34,9 +34,7 @@ XRLXXRRLX ## 解法 - - -**方法一:双指针** +### 方法一:双指针 替换操作实际上是将 `L` 往左移动(`L` 左边为 `X` 时才能移动),`R` 往右移动(`R` 右边是 `X` 时才能移动),但 `L` 无法穿过 `R`。所以,如果去掉 `start` 和 `end` 中的所有 `X`,剩下的字符应该是相同的,否则返回 `false`。 @@ -53,10 +51,6 @@ XRLXXRRLX -### **Python3** - - - ```python class Solution: def canTransform(self, start: str, end: str) -> bool: @@ -78,10 +72,6 @@ class Solution: i, j = i + 1, j + 1 ``` -### **Java** - - - ```java class Solution { public boolean canTransform(String start, String end) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go func canTransform(start string, end string) bool { n := len(start) @@ -162,10 +148,6 @@ func canTransform(start string, end string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0777.Swap Adjacent in LR String/README_EN.md b/solution/0700-0799/0777.Swap Adjacent in LR String/README_EN.md index ffe8cd7169ba3..b3872193e244a 100644 --- a/solution/0700-0799/0777.Swap Adjacent in LR String/README_EN.md +++ b/solution/0700-0799/0777.Swap Adjacent in LR String/README_EN.md @@ -38,9 +38,9 @@ XRLXXRRLX ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: i, j = i + 1, j + 1 ``` -### **Java** - ```java class Solution { public boolean canTransform(String start, String end) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +111,6 @@ public: }; ``` -### **Go** - ```go func canTransform(start string, end string) bool { n := len(start) @@ -145,10 +139,6 @@ func canTransform(start string, end string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0778.Swim in Rising Water/README.md b/solution/0700-0799/0778.Swim in Rising Water/README.md index 06f0becb9a911..89af02dac6eaa 100644 --- a/solution/0700-0799/0778.Swim in Rising Water/README.md +++ b/solution/0700-0799/0778.Swim in Rising Water/README.md @@ -52,81 +52,10 @@ ## 解法 - - -并查集。每经过一个时刻 t,找到此时和雨水高度相等的单元格 `(i, j)`,如果与 `(i, j)` 相邻的单元格 `(x, y)` 满足高度不超过 t,则将这两个单元格进行合并。如果在某个时刻合并之后,单元格 `(0, 0)` 与单元格 `(n - 1, n - 1)` 连通,则返回该时刻。 - -以下是并查集的几个常用模板。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` +### 方法一 -### **Python3** - - - ```python class Solution: def swimInWater(self, grid: List[List[int]]) -> int: @@ -152,10 +81,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -199,42 +124,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function swimInWater(grid: number[][]): number { - const m = grid.length, - n = grid[0].length; - let visited = Array.from({ length: m }, () => new Array(n).fill(false)); - let ans = 0; - let stack = [[0, 0, grid[0][0]]]; - const dir = [ - [0, 1], - [0, -1], - [1, 0], - [-1, 0], - ]; - - while (stack.length) { - let [i, j] = stack.shift(); - ans = Math.max(grid[i][j], ans); - if (i == m - 1 && j == n - 1) break; - for (let [dx, dy] of dir) { - let x = i + dx, - y = j + dy; - if (x < m && x > -1 && y < n && y > -1 && !visited[x][y]) { - visited[x][y] = true; - stack.push([x, y, grid[x][y]]); - } - } - stack.sort((a, b) => a[2] - b[2]); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -268,7 +157,74 @@ public: }; ``` -### **Rust** +```go +func swimInWater(grid [][]int) int { + n := len(grid) + p := make([]int, n*n) + for i := range p { + p[i] = i + } + hi := make([]int, n*n) + for i, row := range grid { + for j, h := range row { + hi[h] = i*n + j + } + } + var find func(x int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + dirs := []int{-1, 0, 1, 0, -1} + for t := 0; t < n*n; t++ { + i, j := hi[t]/n, hi[t]%n + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < n && y >= 0 && y < n && grid[x][y] <= t { + p[find(x*n+y)] = find(hi[t]) + } + if find(0) == find(n*n-1) { + return t + } + } + } + return -1 +} +``` + +```ts +function swimInWater(grid: number[][]): number { + const m = grid.length, + n = grid[0].length; + let visited = Array.from({ length: m }, () => new Array(n).fill(false)); + let ans = 0; + let stack = [[0, 0, grid[0][0]]]; + const dir = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; + + while (stack.length) { + let [i, j] = stack.shift(); + ans = Math.max(grid[i][j], ans); + if (i == m - 1 && j == n - 1) break; + for (let [dx, dy] of dir) { + let x = i + dx, + y = j + dy; + if (x < m && x > -1 && y < n && y > -1 && !visited[x][y]) { + visited[x][y] = true; + stack.push([x, y, grid[x][y]]); + } + } + stack.sort((a, b) => a[2] - b[2]); + } + return ans; +} +``` ```rust const DIR: [(i32, i32); 4] = [ @@ -351,49 +307,6 @@ impl Solution { } ``` -### **Go** - -```go -func swimInWater(grid [][]int) int { - n := len(grid) - p := make([]int, n*n) - for i := range p { - p[i] = i - } - hi := make([]int, n*n) - for i, row := range grid { - for j, h := range row { - hi[h] = i*n + j - } - } - var find func(x int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - dirs := []int{-1, 0, 1, 0, -1} - for t := 0; t < n*n; t++ { - i, j := hi[t]/n, hi[t]%n - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < n && y >= 0 && y < n && grid[x][y] <= t { - p[find(x*n+y)] = find(hi[t]) - } - if find(0) == find(n*n-1) { - return t - } - } - } - return -1 -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0778.Swim in Rising Water/README_EN.md b/solution/0700-0799/0778.Swim in Rising Water/README_EN.md index 1ed2a2dbf963c..f94d22e0fcccc 100644 --- a/solution/0700-0799/0778.Swim in Rising Water/README_EN.md +++ b/solution/0700-0799/0778.Swim in Rising Water/README_EN.md @@ -45,9 +45,9 @@ We need to wait until time 16 so that (0, 0) and (4, 4) are connected. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { private int[] p; @@ -119,42 +117,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function swimInWater(grid: number[][]): number { - const m = grid.length, - n = grid[0].length; - let visited = Array.from({ length: m }, () => new Array(n).fill(false)); - let ans = 0; - let stack = [[0, 0, grid[0][0]]]; - const dir = [ - [0, 1], - [0, -1], - [1, 0], - [-1, 0], - ]; - - while (stack.length) { - let [i, j] = stack.shift(); - ans = Math.max(grid[i][j], ans); - if (i == m - 1 && j == n - 1) break; - for (let [dx, dy] of dir) { - let x = i + dx, - y = j + dy; - if (x < m && x > -1 && y < n && y > -1 && !visited[x][y]) { - visited[x][y] = true; - stack.push([x, y, grid[x][y]]); - } - } - stack.sort((a, b) => a[2] - b[2]); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -188,7 +150,74 @@ public: }; ``` -### **Rust** +```go +func swimInWater(grid [][]int) int { + n := len(grid) + p := make([]int, n*n) + for i := range p { + p[i] = i + } + hi := make([]int, n*n) + for i, row := range grid { + for j, h := range row { + hi[h] = i*n + j + } + } + var find func(x int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + dirs := []int{-1, 0, 1, 0, -1} + for t := 0; t < n*n; t++ { + i, j := hi[t]/n, hi[t]%n + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < n && y >= 0 && y < n && grid[x][y] <= t { + p[find(x*n+y)] = find(hi[t]) + } + if find(0) == find(n*n-1) { + return t + } + } + } + return -1 +} +``` + +```ts +function swimInWater(grid: number[][]): number { + const m = grid.length, + n = grid[0].length; + let visited = Array.from({ length: m }, () => new Array(n).fill(false)); + let ans = 0; + let stack = [[0, 0, grid[0][0]]]; + const dir = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; + + while (stack.length) { + let [i, j] = stack.shift(); + ans = Math.max(grid[i][j], ans); + if (i == m - 1 && j == n - 1) break; + for (let [dx, dy] of dir) { + let x = i + dx, + y = j + dy; + if (x < m && x > -1 && y < n && y > -1 && !visited[x][y]) { + visited[x][y] = true; + stack.push([x, y, grid[x][y]]); + } + } + stack.sort((a, b) => a[2] - b[2]); + } + return ans; +} +``` ```rust const DIR: [(i32, i32); 4] = [ @@ -271,49 +300,6 @@ impl Solution { } ``` -### **Go** - -```go -func swimInWater(grid [][]int) int { - n := len(grid) - p := make([]int, n*n) - for i := range p { - p[i] = i - } - hi := make([]int, n*n) - for i, row := range grid { - for j, h := range row { - hi[h] = i*n + j - } - } - var find func(x int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - dirs := []int{-1, 0, 1, 0, -1} - for t := 0; t < n*n; t++ { - i, j := hi[t]/n, hi[t]%n - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < n && y >= 0 && y < n && grid[x][y] <= t { - p[find(x*n+y)] = find(hi[t]) - } - if find(0) == find(n*n-1) { - return t - } - } - } - return -1 -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0779.K-th Symbol in Grammar/README.md b/solution/0700-0799/0779.K-th Symbol in Grammar/README.md index 3550adacb495a..796dfab752361 100644 --- a/solution/0700-0799/0779.K-th Symbol in Grammar/README.md +++ b/solution/0700-0799/0779.K-th Symbol in Grammar/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们先来看一下前几行的规律: @@ -77,7 +75,58 @@ n = 5: 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 时间复杂度 $O(n)$,空间复杂度 $O(n)$。 -**方法二:位运算 + 脑筋急转弯** + + +```python +class Solution: + def kthGrammar(self, n: int, k: int) -> int: + if n == 1: + return 0 + if k <= (1 << (n - 2)): + return self.kthGrammar(n - 1, k) + return self.kthGrammar(n - 1, k - (1 << (n - 2))) ^ 1 +``` + +```java +class Solution { + public int kthGrammar(int n, int k) { + if (n == 1) { + return 0; + } + if (k <= (1 << (n - 2))) { + return kthGrammar(n - 1, k); + } + return kthGrammar(n - 1, k - (1 << (n - 2))) ^ 1; + } +} +``` + +```cpp +class Solution { +public: + int kthGrammar(int n, int k) { + if (n == 1) return 0; + if (k <= (1 << (n - 2))) return kthGrammar(n - 1, k); + return kthGrammar(n - 1, k - (1 << (n - 2))) ^ 1; + } +}; +``` + +```go +func kthGrammar(n int, k int) int { + if n == 1 { + return 0 + } + if k <= (1 << (n - 2)) { + return kthGrammar(n-1, k) + } + return kthGrammar(n-1, k-(1<<(n-2))) ^ 1 +} +``` + + + +### 方法二:位运算 + 脑筋急转弯 题目中索引从 $1$ 开始,我们将 $k$ 改成 $k-1$,将索引转换为从 $0$ 开始。在接下来的讨论中,索引均从 $0$ 开始。 @@ -111,44 +160,12 @@ n = 5: 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 -### **Python3** - - - -```python -class Solution: - def kthGrammar(self, n: int, k: int) -> int: - if n == 1: - return 0 - if k <= (1 << (n - 2)): - return self.kthGrammar(n - 1, k) - return self.kthGrammar(n - 1, k - (1 << (n - 2))) ^ 1 -``` - ```python class Solution: def kthGrammar(self, n: int, k: int) -> int: return (k - 1).bit_count() & 1 ``` -### **Java** - - - -```java -class Solution { - public int kthGrammar(int n, int k) { - if (n == 1) { - return 0; - } - if (k <= (1 << (n - 2))) { - return kthGrammar(n - 1, k); - } - return kthGrammar(n - 1, k - (1 << (n - 2))) ^ 1; - } -} -``` - ```java class Solution { public int kthGrammar(int n, int k) { @@ -157,19 +174,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int kthGrammar(int n, int k) { - if (n == 1) return 0; - if (k <= (1 << (n - 2))) return kthGrammar(n - 1, k); - return kthGrammar(n - 1, k - (1 << (n - 2))) ^ 1; - } -}; -``` - ```cpp class Solution { public: @@ -179,30 +183,12 @@ public: }; ``` -### **Go** - -```go -func kthGrammar(n int, k int) int { - if n == 1 { - return 0 - } - if k <= (1 << (n - 2)) { - return kthGrammar(n-1, k) - } - return kthGrammar(n-1, k-(1<<(n-2))) ^ 1 -} -``` - ```go func kthGrammar(n int, k int) int { return bits.OnesCount(uint(k-1)) & 1 } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0779.K-th Symbol in Grammar/README_EN.md b/solution/0700-0799/0779.K-th Symbol in Grammar/README_EN.md index fb5eb2ccaf001..856e54295b113 100644 --- a/solution/0700-0799/0779.K-th Symbol in Grammar/README_EN.md +++ b/solution/0700-0799/0779.K-th Symbol in Grammar/README_EN.md @@ -51,9 +51,9 @@ row 2: 01 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,14 +65,6 @@ class Solution: return self.kthGrammar(n - 1, k - (1 << (n - 2))) ^ 1 ``` -```python -class Solution: - def kthGrammar(self, n: int, k: int) -> int: - return (k - 1).bit_count() & 1 -``` - -### **Java** - ```java class Solution { public int kthGrammar(int n, int k) { @@ -87,16 +79,6 @@ class Solution { } ``` -```java -class Solution { - public int kthGrammar(int n, int k) { - return Integer.bitCount(k - 1) & 1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -108,17 +90,6 @@ public: }; ``` -```cpp -class Solution { -public: - int kthGrammar(int n, int k) { - return __builtin_popcount(k - 1) & 1; - } -}; -``` - -### **Go** - ```go func kthGrammar(n int, k int) int { if n == 1 { @@ -131,16 +102,41 @@ func kthGrammar(n int, k int) int { } ``` -```go -func kthGrammar(n int, k int) int { - return bits.OnesCount(uint(k-1)) & 1 -} + + +### Solution 2 + + + +```python +class Solution: + def kthGrammar(self, n: int, k: int) -> int: + return (k - 1).bit_count() & 1 ``` -### **...** +```java +class Solution { + public int kthGrammar(int n, int k) { + return Integer.bitCount(k - 1) & 1; + } +} +``` +```cpp +class Solution { +public: + int kthGrammar(int n, int k) { + return __builtin_popcount(k - 1) & 1; + } +}; ``` +```go +func kthGrammar(n int, k int) int { + return bits.OnesCount(uint(k-1)) & 1 +} ``` + + diff --git a/solution/0700-0799/0780.Reaching Points/README.md b/solution/0700-0799/0780.Reaching Points/README.md index b2ae8c0bb497e..1c68c3a25de91 100644 --- a/solution/0700-0799/0780.Reaching Points/README.md +++ b/solution/0700-0799/0780.Reaching Points/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:逆向计算** +### 方法一:逆向计算 从 `(tx, ty)` 开始逆向计算,判断是否可以到达状态 `(sx, sy)`。由于逆向计算是将 tx, ty 中的较大值减少,因此当 `tx > ty` 时可以直接将 tx 的值更新为 `tx % ty`,当 `tx < ty` 时可以将 ty 的值更新为 `ty % tx`。逆向计算需要满足 `tx > sx && ty > sy && tx != ty`。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool: @@ -84,10 +78,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean reachingPoints(int sx, int sy, int tx, int ty) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go func reachingPoints(sx int, sy int, tx int, ty int) bool { for tx > sx && ty > sy && tx != ty { @@ -156,10 +142,6 @@ func reachingPoints(sx int, sy int, tx int, ty int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0780.Reaching Points/README_EN.md b/solution/0700-0799/0780.Reaching Points/README_EN.md index 84df2491b5cb1..fddb8e071a9b0 100644 --- a/solution/0700-0799/0780.Reaching Points/README_EN.md +++ b/solution/0700-0799/0780.Reaching Points/README_EN.md @@ -44,9 +44,9 @@ One series of moves that transforms the starting point to the target is: ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean reachingPoints(int sx, int sy, int tx, int ty) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +107,6 @@ public: }; ``` -### **Go** - ```go func reachingPoints(sx int, sy int, tx int, ty int) bool { for tx > sx && ty > sy && tx != ty { @@ -135,10 +129,6 @@ func reachingPoints(sx int, sy int, tx int, ty int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0781.Rabbits in Forest/README.md b/solution/0700-0799/0781.Rabbits in Forest/README.md index 8adcb4cc00ee0..dc5b9be58a64f 100644 --- a/solution/0700-0799/0781.Rabbits in Forest/README.md +++ b/solution/0700-0799/0781.Rabbits in Forest/README.md @@ -43,20 +43,10 @@ ## 解法 - - -两只相同颜色的兔子看到的其他同色兔子数一定相同,若两只兔子看到的其它同色兔子数不同,那么这两只兔子颜色也不同。 - -因此,将 `answers` 中值相同的元素分为一组,对于每一组,计算出兔子的最少数量,然后将所有组的计算结果累加,就是最终的答案。 - -如果有 x 只兔子都回答 y,则至少有 `⌈x / (y + 1)⌉` 种不同的颜色,且每种颜色有 `y + 1` 只兔子。 +### 方法一 -### **Python3** - - - ```python class Solution: def numRabbits(self, answers: List[int]) -> int: @@ -64,10 +54,6 @@ class Solution: return sum([math.ceil(v / (k + 1)) * (k + 1) for k, v in counter.items()]) ``` -### **Java** - - - ```java class Solution { public int numRabbits(int[] answers) { @@ -85,10 +71,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0781.Rabbits in Forest/README_EN.md b/solution/0700-0799/0781.Rabbits in Forest/README_EN.md index cf400806cc3ec..2d3f6a98e9a7c 100644 --- a/solution/0700-0799/0781.Rabbits in Forest/README_EN.md +++ b/solution/0700-0799/0781.Rabbits in Forest/README_EN.md @@ -39,9 +39,9 @@ The smallest possible number of rabbits in the forest is therefore 5: 3 that ans ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -50,8 +50,6 @@ class Solution: return sum([math.ceil(v / (k + 1)) * (k + 1) for k, v in counter.items()]) ``` -### **Java** - ```java class Solution { public int numRabbits(int[] answers) { @@ -69,10 +67,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0782.Transform to Chessboard/README.md b/solution/0700-0799/0782.Transform to Chessboard/README.md index f931de3d6625c..6a09762372918 100644 --- a/solution/0700-0799/0782.Transform to Chessboard/README.md +++ b/solution/0700-0799/0782.Transform to Chessboard/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:规律观察 + 状态压缩** +### 方法一:规律观察 + 状态压缩 在一个有效的棋盘中,有且仅有两种“行”。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def movesToChessboard(self, board: List[List[int]]) -> int: @@ -130,10 +124,6 @@ class Solution: return -1 if t1 == -1 or t2 == -1 else t1 + t2 ``` -### **Java** - - - ```java class Solution { private int n; @@ -191,8 +181,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -240,8 +228,6 @@ public: }; ``` -### **Go** - ```go func movesToChessboard(board [][]int) int { n := len(board) @@ -308,10 +294,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0782.Transform to Chessboard/README_EN.md b/solution/0700-0799/0782.Transform to Chessboard/README_EN.md index 1233582141ddf..bba9a53a66135 100644 --- a/solution/0700-0799/0782.Transform to Chessboard/README_EN.md +++ b/solution/0700-0799/0782.Transform to Chessboard/README_EN.md @@ -49,9 +49,9 @@ The second move swaps the second and third row. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -97,8 +97,6 @@ class Solution: return -1 if t1 == -1 or t2 == -1 else t1 + t2 ``` -### **Java** - ```java class Solution { private int n; @@ -156,8 +154,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -205,8 +201,6 @@ public: }; ``` -### **Go** - ```go func movesToChessboard(board [][]int) int { n := len(board) @@ -273,10 +267,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README.md b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README.md index 86b54bb1f6b15..7b7617e3a99f2 100644 --- a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README.md +++ b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README.md @@ -45,18 +45,12 @@ ## 解法 - - -**方法一:中序遍历** +### 方法一:中序遍历 中序遍历二叉搜索树,获取当前节点与上个节点差值的最小值即可。 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -160,8 +148,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -197,3 +183,5 @@ func abs(x int) int { ``` + + diff --git a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README_EN.md b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README_EN.md index 1344443c4649a..e9ab54a6e264e 100644 --- a/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README_EN.md +++ b/solution/0700-0799/0783.Minimum Distance Between BST Nodes/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -103,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -139,8 +135,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -175,10 +169,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0784.Letter Case Permutation/README.md b/solution/0700-0799/0784.Letter Case Permutation/README.md index ee3f444fd8190..5c65d1a85a3ee 100644 --- a/solution/0700-0799/0784.Letter Case Permutation/README.md +++ b/solution/0700-0799/0784.Letter Case Permutation/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 由于 $s$ 中的每个字母都可以转换为大写或小写,因此可以使用 DFS 深度优先搜索的方法,枚举所有可能的情况。 @@ -49,22 +47,8 @@ 时间复杂度 $O(n\times 2^n)$,其中 $n$ 是字符串 $s$ 的长度。对于每个字母,我们可以选择将其转换为大写或小写,因此一共有 $2^n$ 种转换方案。对于每种转换方案,我们需要 $O(n)$ 的时间生成一个新的字符串。 -**方法二:二进制枚举** - -对于一个字母,我们可以将其转换为大写或小写,因此对于每个字母,我们可以使用一个二进制位表示其转换的方案,其中 $1$ 表示小写,而 $0$ 表示大写。 - -我们先统计字符串 $s$ 中字母的个数,记为 $n$,那么一共有 $2^n$ 种转换方案,我们可以使用二进制数的每一位表示每个字母的转换方案,从 $0$ 到 $2^n-1$ 进行枚举。 - -具体地,我们可以使用一个变量 $i$ 表示当前枚举到的二进制数,其中 $i$ 的第 $j$ 位表示第 $j$ 个字母的转换方案。即 $i$ 的第 $j$ 位为 $1$ 表示第 $j$ 个字母转换为小写,而 $i$ 的第 $j$ 位为 $0$ 表示第 $j$ 个字母转换为大写。 - -时间复杂度 $O(n\times 2^n)$,其中 $n$ 是字符串 $s$ 的长度。对于每个字母,我们可以选择将其转换为大写或小写,因此一共有 $2^n$ 种转换方案。对于每种转换方案,我们需要 $O(n)$ 的时间生成一个新的字符串。 - -### **Python3** - - - ```python class Solution: def letterCasePermutation(self, s: str) -> List[str]: @@ -83,26 +67,6 @@ class Solution: return ans ``` -```python -class Solution: - def letterCasePermutation(self, s: str) -> List[str]: - ans = [] - n = sum(c.isalpha() for c in s) - for i in range(1 << n): - j, t = 0, [] - for c in s: - if c.isalpha(): - c = c.lower() if (i >> j) & 1 else c.upper() - j += 1 - t.append(c) - ans.append(''.join(t)) - return ans -``` - -### **Java** - - - ```java class Solution { private List ans = new ArrayList<>(); @@ -128,36 +92,6 @@ class Solution { } ``` -```java -class Solution { - public List letterCasePermutation(String s) { - int n = 0; - for (int i = 0; i < s.length(); ++i) { - if (s.charAt(i) >= 'A') { - ++n; - } - } - List ans = new ArrayList<>(); - for (int i = 0; i < 1 << n; ++i) { - int j = 0; - StringBuilder t = new StringBuilder(); - for (int k = 0; k < s.length(); ++k) { - char x = s.charAt(k); - if (x >= 'A') { - x = ((i >> j) & 1) == 1 ? Character.toLowerCase(x) : Character.toUpperCase(x); - ++j; - } - t.append(x); - } - ans.add(t.toString()); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -180,33 +114,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector letterCasePermutation(string s) { - int n = 0; - for (char c : s) - if (isalpha(c)) ++n; - vector ans; - for (int i = 0; i < 1 << n; ++i) { - int j = 0; - string t; - for (char c : s) { - if (isalpha(c)) { - c = (i >> j & 1) ? tolower(c) : toupper(c); - ++j; - } - t += c; - } - ans.emplace_back(t); - } - return ans; - } -}; -``` - -### **Go** - ```go func letterCasePermutation(s string) (ans []string) { t := []byte(s) @@ -228,36 +135,6 @@ func letterCasePermutation(s string) (ans []string) { } ``` -```go -func letterCasePermutation(s string) (ans []string) { - n := 0 - for _, c := range s { - if c >= 'A' { - n++ - } - } - for i := 0; i < 1<= 'A' { - if ((i >> j) & 1) == 1 { - c = unicode.ToLower(c) - } else { - c = unicode.ToUpper(c) - } - j++ - } - t = append(t, c) - } - ans = append(ans, string(t)) - } - return ans -} -``` - -### **TypeScript** - ```ts function letterCasePermutation(s: string): string[] { const n = s.length; @@ -279,8 +156,6 @@ function letterCasePermutation(s: string): string[] { } ``` -### **Rust** - ```rust impl Solution { fn dfs(i: usize, cs: &mut Vec, res: &mut Vec) { @@ -304,10 +179,117 @@ impl Solution { } ``` -### **...** + + +### 方法二:二进制枚举 + +对于一个字母,我们可以将其转换为大写或小写,因此对于每个字母,我们可以使用一个二进制位表示其转换的方案,其中 $1$ 表示小写,而 $0$ 表示大写。 + +我们先统计字符串 $s$ 中字母的个数,记为 $n$,那么一共有 $2^n$ 种转换方案,我们可以使用二进制数的每一位表示每个字母的转换方案,从 $0$ 到 $2^n-1$ 进行枚举。 + +具体地,我们可以使用一个变量 $i$ 表示当前枚举到的二进制数,其中 $i$ 的第 $j$ 位表示第 $j$ 个字母的转换方案。即 $i$ 的第 $j$ 位为 $1$ 表示第 $j$ 个字母转换为小写,而 $i$ 的第 $j$ 位为 $0$ 表示第 $j$ 个字母转换为大写。 + +时间复杂度 $O(n\times 2^n)$,其中 $n$ 是字符串 $s$ 的长度。对于每个字母,我们可以选择将其转换为大写或小写,因此一共有 $2^n$ 种转换方案。对于每种转换方案,我们需要 $O(n)$ 的时间生成一个新的字符串。 + + + +```python +class Solution: + def letterCasePermutation(self, s: str) -> List[str]: + ans = [] + n = sum(c.isalpha() for c in s) + for i in range(1 << n): + j, t = 0, [] + for c in s: + if c.isalpha(): + c = c.lower() if (i >> j) & 1 else c.upper() + j += 1 + t.append(c) + ans.append(''.join(t)) + return ans +``` + +```java +class Solution { + public List letterCasePermutation(String s) { + int n = 0; + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) >= 'A') { + ++n; + } + } + List ans = new ArrayList<>(); + for (int i = 0; i < 1 << n; ++i) { + int j = 0; + StringBuilder t = new StringBuilder(); + for (int k = 0; k < s.length(); ++k) { + char x = s.charAt(k); + if (x >= 'A') { + x = ((i >> j) & 1) == 1 ? Character.toLowerCase(x) : Character.toUpperCase(x); + ++j; + } + t.append(x); + } + ans.add(t.toString()); + } + return ans; + } +} +``` +```cpp +class Solution { +public: + vector letterCasePermutation(string s) { + int n = 0; + for (char c : s) + if (isalpha(c)) ++n; + vector ans; + for (int i = 0; i < 1 << n; ++i) { + int j = 0; + string t; + for (char c : s) { + if (isalpha(c)) { + c = (i >> j & 1) ? tolower(c) : toupper(c); + ++j; + } + t += c; + } + ans.emplace_back(t); + } + return ans; + } +}; ``` +```go +func letterCasePermutation(s string) (ans []string) { + n := 0 + for _, c := range s { + if c >= 'A' { + n++ + } + } + for i := 0; i < 1<= 'A' { + if ((i >> j) & 1) == 1 { + c = unicode.ToLower(c) + } else { + c = unicode.ToUpper(c) + } + j++ + } + t = append(t, c) + } + ans = append(ans, string(t)) + } + return ans +} ``` + + diff --git a/solution/0700-0799/0784.Letter Case Permutation/README_EN.md b/solution/0700-0799/0784.Letter Case Permutation/README_EN.md index 507bbc2b11415..6bf0d9728a9a4 100644 --- a/solution/0700-0799/0784.Letter Case Permutation/README_EN.md +++ b/solution/0700-0799/0784.Letter Case Permutation/README_EN.md @@ -33,12 +33,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python class Solution: def letterCasePermutation(self, s: str) -> List[str]: @@ -57,24 +55,6 @@ class Solution: return ans ``` -```python -class Solution: - def letterCasePermutation(self, s: str) -> List[str]: - ans = [] - n = sum(c.isalpha() for c in s) - for i in range(1 << n): - j, t = 0, [] - for c in s: - if c.isalpha(): - c = c.lower() if (i >> j) & 1 else c.upper() - j += 1 - t.append(c) - ans.append(''.join(t)) - return ans -``` - -### **Java** - ```java class Solution { private List ans = new ArrayList<>(); @@ -100,36 +80,6 @@ class Solution { } ``` -```java -class Solution { - public List letterCasePermutation(String s) { - int n = 0; - for (int i = 0; i < s.length(); ++i) { - if (s.charAt(i) >= 'A') { - ++n; - } - } - List ans = new ArrayList<>(); - for (int i = 0; i < 1 << n; ++i) { - int j = 0; - StringBuilder t = new StringBuilder(); - for (int k = 0; k < s.length(); ++k) { - char x = s.charAt(k); - if (x >= 'A') { - x = ((i >> j) & 1) == 1 ? Character.toLowerCase(x) : Character.toUpperCase(x); - ++j; - } - t.append(x); - } - ans.add(t.toString()); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -152,33 +102,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector letterCasePermutation(string s) { - int n = 0; - for (char c : s) - if (isalpha(c)) ++n; - vector ans; - for (int i = 0; i < 1 << n; ++i) { - int j = 0; - string t; - for (char c : s) { - if (isalpha(c)) { - c = (i >> j & 1) ? tolower(c) : toupper(c); - ++j; - } - t += c; - } - ans.emplace_back(t); - } - return ans; - } -}; -``` - -### **Go** - ```go func letterCasePermutation(s string) (ans []string) { t := []byte(s) @@ -200,36 +123,6 @@ func letterCasePermutation(s string) (ans []string) { } ``` -```go -func letterCasePermutation(s string) (ans []string) { - n := 0 - for _, c := range s { - if c >= 'A' { - n++ - } - } - for i := 0; i < 1<= 'A' { - if ((i >> j) & 1) == 1 { - c = unicode.ToLower(c) - } else { - c = unicode.ToUpper(c) - } - j++ - } - t = append(t, c) - } - ans = append(ans, string(t)) - } - return ans -} -``` - -### **TypeScript** - ```ts function letterCasePermutation(s: string): string[] { const n = s.length; @@ -251,8 +144,6 @@ function letterCasePermutation(s: string): string[] { } ``` -### **Rust** - ```rust impl Solution { fn dfs(i: usize, cs: &mut Vec, res: &mut Vec) { @@ -276,10 +167,109 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def letterCasePermutation(self, s: str) -> List[str]: + ans = [] + n = sum(c.isalpha() for c in s) + for i in range(1 << n): + j, t = 0, [] + for c in s: + if c.isalpha(): + c = c.lower() if (i >> j) & 1 else c.upper() + j += 1 + t.append(c) + ans.append(''.join(t)) + return ans +``` + +```java +class Solution { + public List letterCasePermutation(String s) { + int n = 0; + for (int i = 0; i < s.length(); ++i) { + if (s.charAt(i) >= 'A') { + ++n; + } + } + List ans = new ArrayList<>(); + for (int i = 0; i < 1 << n; ++i) { + int j = 0; + StringBuilder t = new StringBuilder(); + for (int k = 0; k < s.length(); ++k) { + char x = s.charAt(k); + if (x >= 'A') { + x = ((i >> j) & 1) == 1 ? Character.toLowerCase(x) : Character.toUpperCase(x); + ++j; + } + t.append(x); + } + ans.add(t.toString()); + } + return ans; + } +} +``` +```cpp +class Solution { +public: + vector letterCasePermutation(string s) { + int n = 0; + for (char c : s) + if (isalpha(c)) ++n; + vector ans; + for (int i = 0; i < 1 << n; ++i) { + int j = 0; + string t; + for (char c : s) { + if (isalpha(c)) { + c = (i >> j & 1) ? tolower(c) : toupper(c); + ++j; + } + t += c; + } + ans.emplace_back(t); + } + return ans; + } +}; ``` +```go +func letterCasePermutation(s string) (ans []string) { + n := 0 + for _, c := range s { + if c >= 'A' { + n++ + } + } + for i := 0; i < 1<= 'A' { + if ((i >> j) & 1) == 1 { + c = unicode.ToLower(c) + } else { + c = unicode.ToUpper(c) + } + j++ + } + t = append(t, c) + } + ans = append(ans, string(t)) + } + return ans +} ``` + + diff --git a/solution/0700-0799/0785.Is Graph Bipartite/README.md b/solution/0700-0799/0785.Is Graph Bipartite/README.md index a72ef40f456cc..6c62158bed60f 100644 --- a/solution/0700-0799/0785.Is Graph Bipartite/README.md +++ b/solution/0700-0799/0785.Is Graph Bipartite/README.md @@ -51,13 +51,189 @@ ## 解法 - - -**方法一:染色法判定二分图** +### 方法一:染色法判定二分图 遍历所有节点进行染色,比如初始为白色,DFS 对节点相邻的点染上另外一种颜色。如果要染色某节点时,要染的目标颜色和该节点的已经染过的颜色不同,则说明不能构成二分图。 -**方法二:并查集** + + +```python +class Solution: + def isBipartite(self, graph: List[List[int]]) -> bool: + def dfs(u, c): + color[u] = c + for v in graph[u]: + if not color[v]: + if not dfs(v, 3 - c): + return False + elif color[v] == c: + return False + return True + + n = len(graph) + color = [0] * n + for i in range(n): + if not color[i] and not dfs(i, 1): + return False + return True +``` + +```java +class Solution { + private int[] color; + private int[][] g; + + public boolean isBipartite(int[][] graph) { + int n = graph.length; + color = new int[n]; + g = graph; + for (int i = 0; i < n; ++i) { + if (color[i] == 0 && !dfs(i, 1)) { + return false; + } + } + return true; + } + + private boolean dfs(int u, int c) { + color[u] = c; + for (int v : g[u]) { + if (color[v] == 0) { + if (!dfs(v, 3 - c)) { + return false; + } + } else if (color[v] == c) { + return false; + } + } + return true; + } +} +``` + +```cpp +class Solution { +public: + bool isBipartite(vector>& graph) { + int n = graph.size(); + vector color(n); + for (int i = 0; i < n; ++i) + if (!color[i] && !dfs(i, 1, color, graph)) + return false; + return true; + } + + bool dfs(int u, int c, vector& color, vector>& g) { + color[u] = c; + for (int& v : g[u]) { + if (!color[v]) { + if (!dfs(v, 3 - c, color, g)) return false; + } else if (color[v] == c) + return false; + } + return true; + } +}; +``` + +```go +func isBipartite(graph [][]int) bool { + n := len(graph) + color := make([]int, n) + var dfs func(u, c int) bool + dfs = func(u, c int) bool { + color[u] = c + for _, v := range graph[u] { + if color[v] == 0 { + if !dfs(v, 3-c) { + return false + } + } else if color[v] == c { + return false + } + } + return true + } + for i := range graph { + if color[i] == 0 && !dfs(i, 1) { + return false + } + } + return true +} +``` + +```ts +function isBipartite(graph: number[][]): boolean { + const n = graph.length; + let valid = true; + // 0 未遍历, 1 红色标记, 2 绿色标记 + let colors = new Array(n).fill(0); + function dfs(idx: number, color: number, graph: number[][]) { + colors[idx] = color; + const nextColor = 3 - color; + for (let j of graph[idx]) { + if (!colors[j]) { + dfs(j, nextColor, graph); + if (!valid) return; + } else if (colors[j] != nextColor) { + valid = false; + return; + } + } + } + + for (let i = 0; i < n && valid; i++) { + if (!colors[i]) { + dfs(i, 1, graph); + } + } + return valid; +} +``` + +```rust +impl Solution { + #[allow(dead_code)] + pub fn is_bipartite(graph: Vec>) -> bool { + let mut graph = graph; + let n = graph.len(); + let mut color_vec: Vec = vec![0; n]; + for i in 0..n { + if color_vec[i] == 0 && !Self::traverse(i, 1, &mut color_vec, &mut graph) { + return false; + } + } + true + } + + #[allow(dead_code)] + fn traverse( + v: usize, + color: usize, + color_vec: &mut Vec, + graph: &mut Vec> + ) -> bool { + color_vec[v] = color; + for n in graph[v].clone() { + if color_vec[n as usize] == 0 { + // This node hasn't been colored + if !Self::traverse(n as usize, 3 - color, color_vec, graph) { + return false; + } + } else if color_vec[n as usize] == color { + // The color is the same + return false; + } + } + true + } +} +``` + + + +### 方法二:并查集 对于本题,如果是二分图,那么图中每个顶点的所有邻接点都应该属于同一集合,且不与顶点处于同一集合,因此我们可以使用并查集。遍历图中每个顶点,如果发现存在当前顶点与对应的邻接点处于同一个集合,说明不是二分图。否则将当前节点的邻接点相互进行合并。以下是并查集模板。 @@ -126,35 +302,6 @@ d[find(a)] = distance -### **Python3** - - - -染色法: - -```python -class Solution: - def isBipartite(self, graph: List[List[int]]) -> bool: - def dfs(u, c): - color[u] = c - for v in graph[u]: - if not color[v]: - if not dfs(v, 3 - c): - return False - elif color[v] == c: - return False - return True - - n = len(graph) - color = [0] * n - for i in range(n): - if not color[i] and not dfs(i, 1): - return False - return True -``` - -并查集: - ```python class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: @@ -172,47 +319,6 @@ class Solution: return True ``` -### **Java** - - - -染色法: - -```java -class Solution { - private int[] color; - private int[][] g; - - public boolean isBipartite(int[][] graph) { - int n = graph.length; - color = new int[n]; - g = graph; - for (int i = 0; i < n; ++i) { - if (color[i] == 0 && !dfs(i, 1)) { - return false; - } - } - return true; - } - - private boolean dfs(int u, int c) { - color[u] = c; - for (int v : g[u]) { - if (color[v] == 0) { - if (!dfs(v, 3 - c)) { - return false; - } - } else if (color[v] == c) { - return false; - } - } - return true; - } -} -``` - -并查集: - ```java class Solution { private int[] p; @@ -244,37 +350,6 @@ class Solution { } ``` -### **C++** - -染色法: - -```cpp -class Solution { -public: - bool isBipartite(vector>& graph) { - int n = graph.size(); - vector color(n); - for (int i = 0; i < n; ++i) - if (!color[i] && !dfs(i, 1, color, graph)) - return false; - return true; - } - - bool dfs(int u, int c, vector& color, vector>& g) { - color[u] = c; - for (int& v : g[u]) { - if (!color[v]) { - if (!dfs(v, 3 - c, color, g)) return false; - } else if (color[v] == c) - return false; - } - return true; - } -}; -``` - -并查集: - ```cpp class Solution { public: @@ -301,51 +376,57 @@ public: }; ``` -### **Rust** - -染色法: +```go +func isBipartite(graph [][]int) bool { + n := len(graph) + p := make([]int, n) + for i := range p { + p[i] = i + } + var find func(x int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + for u, g := range graph { + for _, v := range g { + if find(u) == find(v) { + return false + } + p[find(v)] = find(g[0]) + } + } + return true +} +``` -```rust -impl Solution { - #[allow(dead_code)] - pub fn is_bipartite(graph: Vec>) -> bool { - let mut graph = graph; - let n = graph.len(); - let mut color_vec: Vec = vec![0; n]; - for i in 0..n { - if color_vec[i] == 0 && !Self::traverse(i, 1, &mut color_vec, &mut graph) { - return false; - } +```ts +function isBipartite(graph: number[][]): boolean { + const n = graph.length; + let p = new Array(n); + for (let i = 0; i < n; ++i) { + p[i] = i; + } + function find(x) { + if (p[x] != x) { + p[x] = find(p[x]); } - true + return p[x]; } - - #[allow(dead_code)] - fn traverse( - v: usize, - color: usize, - color_vec: &mut Vec, - graph: &mut Vec> - ) -> bool { - color_vec[v] = color; - for n in graph[v].clone() { - if color_vec[n as usize] == 0 { - // This node hasn't been colored - if !Self::traverse(n as usize, 3 - color, color_vec, graph) { - return false; - } - } else if color_vec[n as usize] == color { - // The color is the same + for (let u = 0; u < n; ++u) { + for (let v of graph[u]) { + if (find(u) == find(v)) { return false; } + p[find(v)] = find(graph[u][0]); } - true } + return true; } ``` -并查集: - ```rust impl Solution { #[allow(dead_code)] @@ -395,129 +476,6 @@ impl Solution { } ``` -### **Go** - -染色法: - -```go -func isBipartite(graph [][]int) bool { - n := len(graph) - color := make([]int, n) - var dfs func(u, c int) bool - dfs = func(u, c int) bool { - color[u] = c - for _, v := range graph[u] { - if color[v] == 0 { - if !dfs(v, 3-c) { - return false - } - } else if color[v] == c { - return false - } - } - return true - } - for i := range graph { - if color[i] == 0 && !dfs(i, 1) { - return false - } - } - return true -} -``` - -并查集: - -```go -func isBipartite(graph [][]int) bool { - n := len(graph) - p := make([]int, n) - for i := range p { - p[i] = i - } - var find func(x int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - for u, g := range graph { - for _, v := range g { - if find(u) == find(v) { - return false - } - p[find(v)] = find(g[0]) - } - } - return true -} -``` - -### **TypeScript** - -染色法: - -```ts -function isBipartite(graph: number[][]): boolean { - const n = graph.length; - let valid = true; - // 0 未遍历, 1 红色标记, 2 绿色标记 - let colors = new Array(n).fill(0); - function dfs(idx: number, color: number, graph: number[][]) { - colors[idx] = color; - const nextColor = 3 - color; - for (let j of graph[idx]) { - if (!colors[j]) { - dfs(j, nextColor, graph); - if (!valid) return; - } else if (colors[j] != nextColor) { - valid = false; - return; - } - } - } - - for (let i = 0; i < n && valid; i++) { - if (!colors[i]) { - dfs(i, 1, graph); - } - } - return valid; -} -``` - -并查集: - -```ts -function isBipartite(graph: number[][]): boolean { - const n = graph.length; - let p = new Array(n); - for (let i = 0; i < n; ++i) { - p[i] = i; - } - function find(x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } - for (let u = 0; u < n; ++u) { - for (let v of graph[u]) { - if (find(u) == find(v)) { - return false; - } - p[find(v)] = find(graph[u][0]); - } - } - return true; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0785.Is Graph Bipartite/README_EN.md b/solution/0700-0799/0785.Is Graph Bipartite/README_EN.md index b5e982e513378..c1ae559ba4137 100644 --- a/solution/0700-0799/0785.Is Graph Bipartite/README_EN.md +++ b/solution/0700-0799/0785.Is Graph Bipartite/README_EN.md @@ -47,11 +47,9 @@ ## Solutions - - -### **Python3** +### Solution 1 -Graph coloring: + ```python class Solution: @@ -74,29 +72,6 @@ class Solution: return True ``` -Union find: - -```python -class Solution: - def isBipartite(self, graph: List[List[int]]) -> bool: - def find(x): - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - p = list(range(len(graph))) - for u, g in enumerate(graph): - for v in g: - if find(u) == find(v): - return False - p[find(v)] = find(g[0]) - return True -``` - -### **Java** - -Graph coloring: - ```java class Solution { private int[] color; @@ -130,43 +105,6 @@ class Solution { } ``` -Union find: - -```java -class Solution { - private int[] p; - - public boolean isBipartite(int[][] graph) { - int n = graph.length; - p = new int[n]; - for (int i = 0; i < n; ++i) { - p[i] = i; - } - for (int u = 0; u < n; ++u) { - int[] g = graph[u]; - for (int v : g) { - if (find(u) == find(v)) { - return false; - } - p[find(v)] = find(g[0]); - } - } - return true; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } -} -``` - -### **C++** - -Graph coloring: - ```cpp class Solution { public: @@ -192,38 +130,62 @@ public: }; ``` -Union find: - -```cpp -class Solution { -public: - vector p; +```go +func isBipartite(graph [][]int) bool { + n := len(graph) + color := make([]int, n) + var dfs func(u, c int) bool + dfs = func(u, c int) bool { + color[u] = c + for _, v := range graph[u] { + if color[v] == 0 { + if !dfs(v, 3-c) { + return false + } + } else if color[v] == c { + return false + } + } + return true + } + for i := range graph { + if color[i] == 0 && !dfs(i, 1) { + return false + } + } + return true +} +``` - bool isBipartite(vector>& graph) { - int n = graph.size(); - p.resize(n); - for (int i = 0; i < n; ++i) p[i] = i; - for (int u = 0; u < n; ++u) { - auto& g = graph[u]; - for (int v : g) { - if (find(u) == find(v)) return 0; - p[find(v)] = find(g[0]); +```ts +function isBipartite(graph: number[][]): boolean { + const n = graph.length; + let valid = true; + // 0 未遍历, 1 红色标记, 2 绿色标记 + let colors = new Array(n).fill(0); + function dfs(idx: number, color: number, graph: number[][]) { + colors[idx] = color; + const nextColor = 3 - color; + for (let j of graph[idx]) { + if (!colors[j]) { + dfs(j, nextColor, graph); + if (!valid) return; + } else if (colors[j] != nextColor) { + valid = false; + return; } } - return 1; } - int find(int x) { - if (p[x] != x) p[x] = find(p[x]); - return p[x]; + for (let i = 0; i < n && valid; i++) { + if (!colors[i]) { + dfs(i, 1, graph); + } } -}; + return valid; +} ``` -### **Rust** - -Graph coloring: - ```rust impl Solution { #[allow(dead_code)] @@ -263,90 +225,86 @@ impl Solution { } ``` -Union find: + -```rust -impl Solution { - #[allow(dead_code)] - pub fn is_bipartite(graph: Vec>) -> bool { - let n = graph.len(); - let mut disjoint_set: Vec = vec![0; n]; - // Initialize the disjoint set - for i in 0..n { - disjoint_set[i] = i; - } +### Solution 2 - // Traverse the graph - for i in 0..n { - if graph[i].is_empty() { - continue; - } - let first = graph[i][0] as usize; - for v in &graph[i] { - let v = *v as usize; - let i_p = Self::find(i, &mut disjoint_set); - let v_p = Self::find(v, &mut disjoint_set); - if i_p == v_p { + + +```python +class Solution: + def isBipartite(self, graph: List[List[int]]) -> bool: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + p = list(range(len(graph))) + for u, g in enumerate(graph): + for v in g: + if find(u) == find(v): + return False + p[find(v)] = find(g[0]) + return True +``` + +```java +class Solution { + private int[] p; + + public boolean isBipartite(int[][] graph) { + int n = graph.length; + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + for (int u = 0; u < n; ++u) { + int[] g = graph[u]; + for (int v : g) { + if (find(u) == find(v)) { return false; } - // Otherwise, union the node - Self::union(first, v, &mut disjoint_set); + p[find(v)] = find(g[0]); } } - - true + return true; } - #[allow(dead_code)] - fn find(x: usize, d_set: &mut Vec) -> usize { - if d_set[x] != x { - d_set[x] = Self::find(d_set[x], d_set); + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); } - d_set[x] - } - - #[allow(dead_code)] - fn union(x: usize, y: usize, d_set: &mut Vec) { - let p_x = Self::find(x, d_set); - let p_y = Self::find(y, d_set); - d_set[p_x] = p_y; + return p[x]; } } ``` -### **Go** +```cpp +class Solution { +public: + vector p; -Graph coloring: + bool isBipartite(vector>& graph) { + int n = graph.size(); + p.resize(n); + for (int i = 0; i < n; ++i) p[i] = i; + for (int u = 0; u < n; ++u) { + auto& g = graph[u]; + for (int v : g) { + if (find(u) == find(v)) return 0; + p[find(v)] = find(g[0]); + } + } + return 1; + } -```go -func isBipartite(graph [][]int) bool { - n := len(graph) - color := make([]int, n) - var dfs func(u, c int) bool - dfs = func(u, c int) bool { - color[u] = c - for _, v := range graph[u] { - if color[v] == 0 { - if !dfs(v, 3-c) { - return false - } - } else if color[v] == c { - return false - } - } - return true - } - for i := range graph { - if color[i] == 0 && !dfs(i, 1) { - return false - } - } - return true -} + int find(int x) { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + } +}; ``` -Union find: - ```go func isBipartite(graph [][]int) bool { n := len(graph) @@ -373,40 +331,6 @@ func isBipartite(graph [][]int) bool { } ``` -### **TypeScript** - -Graph coloring: - -```ts -function isBipartite(graph: number[][]): boolean { - const n = graph.length; - let valid = true; - let colors = new Array(n).fill(0); - function dfs(idx: number, color: number, graph: number[][]) { - colors[idx] = color; - const nextColor = 3 - color; - for (let j of graph[idx]) { - if (!colors[j]) { - dfs(j, nextColor, graph); - if (!valid) return; - } else if (colors[j] != nextColor) { - valid = false; - return; - } - } - } - - for (let i = 0; i < n && valid; i++) { - if (!colors[i]) { - dfs(i, 1, graph); - } - } - return valid; -} -``` - -Union find: - ```ts function isBipartite(graph: number[][]): boolean { const n = graph.length; @@ -432,10 +356,55 @@ function isBipartite(graph: number[][]): boolean { } ``` -### **...** +```rust +impl Solution { + #[allow(dead_code)] + pub fn is_bipartite(graph: Vec>) -> bool { + let n = graph.len(); + let mut disjoint_set: Vec = vec![0; n]; + // Initialize the disjoint set + for i in 0..n { + disjoint_set[i] = i; + } + + // Traverse the graph + for i in 0..n { + if graph[i].is_empty() { + continue; + } + let first = graph[i][0] as usize; + for v in &graph[i] { + let v = *v as usize; + let i_p = Self::find(i, &mut disjoint_set); + let v_p = Self::find(v, &mut disjoint_set); + if i_p == v_p { + return false; + } + // Otherwise, union the node + Self::union(first, v, &mut disjoint_set); + } + } -``` + true + } + + #[allow(dead_code)] + fn find(x: usize, d_set: &mut Vec) -> usize { + if d_set[x] != x { + d_set[x] = Self::find(d_set[x], d_set); + } + d_set[x] + } + #[allow(dead_code)] + fn union(x: usize, y: usize, d_set: &mut Vec) { + let p_x = Self::find(x, d_set); + let p_y = Self::find(y, d_set); + d_set[p_x] = p_y; + } +} ``` + + diff --git a/solution/0700-0799/0786.K-th Smallest Prime Fraction/README.md b/solution/0700-0799/0786.K-th Smallest Prime Fraction/README.md index b7cb69c698229..f9a576ff4db98 100644 --- a/solution/0700-0799/0786.K-th Smallest Prime Fraction/README.md +++ b/solution/0700-0799/0786.K-th Smallest Prime Fraction/README.md @@ -49,14 +49,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]: @@ -69,10 +65,6 @@ class Solution: return [arr[h[0][1]], arr[h[0][2]]] ``` -### **Java** - - - ```java class Solution { public int[] kthSmallestPrimeFraction(int[] arr, int k) { @@ -109,37 +101,6 @@ class Solution { } ``` -### **Go** - -```go -type frac struct{ x, y, i, j int } -type hp []frac - -func (a hp) Len() int { return len(a) } -func (a hp) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a hp) Less(i, j int) bool { return a[i].x*a[j].y < a[j].x*a[i].y } -func (a *hp) Push(x any) { *a = append(*a, x.(frac)) } -func (a *hp) Pop() any { l := len(*a); tmp := (*a)[l-1]; *a = (*a)[:l-1]; return tmp } - -func kthSmallestPrimeFraction(arr []int, k int) []int { - n := len(arr) - h := make(hp, 0, n-1) - for i := 1; i < n; i++ { - h = append(h, frac{1, arr[i], 0, i}) - } - heap.Init(&h) - for i := 1; i < k; i++ { - f := heap.Pop(&h).(frac) - if f.i+1 < f.j { - heap.Push(&h, frac{arr[f.i+1], arr[f.j], f.i + 1, f.j}) - } - } - return []int{h[0].x, h[0].y} -} -``` - -### **C++** - ```cpp class Solution { public: @@ -165,10 +126,33 @@ public: }; ``` -### **...** +```go +type frac struct{ x, y, i, j int } +type hp []frac -``` +func (a hp) Len() int { return len(a) } +func (a hp) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a hp) Less(i, j int) bool { return a[i].x*a[j].y < a[j].x*a[i].y } +func (a *hp) Push(x any) { *a = append(*a, x.(frac)) } +func (a *hp) Pop() any { l := len(*a); tmp := (*a)[l-1]; *a = (*a)[:l-1]; return tmp } +func kthSmallestPrimeFraction(arr []int, k int) []int { + n := len(arr) + h := make(hp, 0, n-1) + for i := 1; i < n; i++ { + h = append(h, frac{1, arr[i], 0, i}) + } + heap.Init(&h) + for i := 1; i < k; i++ { + f := heap.Pop(&h).(frac) + if f.i+1 < f.j { + heap.Push(&h, frac{arr[f.i+1], arr[f.j], f.i + 1, f.j}) + } + } + return []int{h[0].x, h[0].y} +} ``` + + diff --git a/solution/0700-0799/0786.K-th Smallest Prime Fraction/README_EN.md b/solution/0700-0799/0786.K-th Smallest Prime Fraction/README_EN.md index 1e0dd3c7cbc55..3bb7b78bd3651 100644 --- a/solution/0700-0799/0786.K-th Smallest Prime Fraction/README_EN.md +++ b/solution/0700-0799/0786.K-th Smallest Prime Fraction/README_EN.md @@ -45,9 +45,9 @@ The third fraction is 2/5. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return [arr[h[0][1]], arr[h[0][2]]] ``` -### **Java** - ```java class Solution { public int[] kthSmallestPrimeFraction(int[] arr, int k) { @@ -99,37 +97,6 @@ class Solution { } ``` -### **Go** - -```go -type frac struct{ x, y, i, j int } -type hp []frac - -func (a hp) Len() int { return len(a) } -func (a hp) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a hp) Less(i, j int) bool { return a[i].x*a[j].y < a[j].x*a[i].y } -func (a *hp) Push(x any) { *a = append(*a, x.(frac)) } -func (a *hp) Pop() any { l := len(*a); tmp := (*a)[l-1]; *a = (*a)[:l-1]; return tmp } - -func kthSmallestPrimeFraction(arr []int, k int) []int { - n := len(arr) - h := make(hp, 0, n-1) - for i := 1; i < n; i++ { - h = append(h, frac{1, arr[i], 0, i}) - } - heap.Init(&h) - for i := 1; i < k; i++ { - f := heap.Pop(&h).(frac) - if f.i+1 < f.j { - heap.Push(&h, frac{arr[f.i+1], arr[f.j], f.i + 1, f.j}) - } - } - return []int{h[0].x, h[0].y} -} -``` - -### **C++** - ```cpp class Solution { public: @@ -155,10 +122,33 @@ public: }; ``` -### **...** +```go +type frac struct{ x, y, i, j int } +type hp []frac -``` +func (a hp) Len() int { return len(a) } +func (a hp) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a hp) Less(i, j int) bool { return a[i].x*a[j].y < a[j].x*a[i].y } +func (a *hp) Push(x any) { *a = append(*a, x.(frac)) } +func (a *hp) Pop() any { l := len(*a); tmp := (*a)[l-1]; *a = (*a)[:l-1]; return tmp } +func kthSmallestPrimeFraction(arr []int, k int) []int { + n := len(arr) + h := make(hp, 0, n-1) + for i := 1; i < n; i++ { + h = append(h, frac{1, arr[i], 0, i}) + } + heap.Init(&h) + for i := 1; i < k; i++ { + f := heap.Pop(&h).(frac) + if f.i+1 < f.j { + heap.Push(&h, frac{arr[f.i+1], arr[f.j], f.i + 1, f.j}) + } + } + return []int{h[0].x, h[0].y} +} ``` + + diff --git a/solution/0700-0799/0787.Cheapest Flights Within K Stops/README.md b/solution/0700-0799/0787.Cheapest Flights Within K Stops/README.md index 312c5cebf2b6b..d1ca8515e2f53 100644 --- a/solution/0700-0799/0787.Cheapest Flights Within K Stops/README.md +++ b/solution/0700-0799/0787.Cheapest Flights Within K Stops/README.md @@ -56,18 +56,10 @@ src = 0, dst = 2, k = 0 ## 解法 - - -**方法一:Bellman Ford 算法** - -**方法二:DFS + 记忆化搜索** +### 方法一:Bellman Ford 算法 -### **Python3** - - - ```python class Solution: def findCheapestPrice( @@ -83,6 +75,76 @@ class Solution: return -1 if dist[dst] == INF else dist[dst] ``` +```java +class Solution { + private static final int INF = 0x3f3f3f3f; + + public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { + int[] dist = new int[n]; + int[] backup = new int[n]; + Arrays.fill(dist, INF); + dist[src] = 0; + for (int i = 0; i < k + 1; ++i) { + System.arraycopy(dist, 0, backup, 0, n); + for (int[] e : flights) { + int f = e[0], t = e[1], p = e[2]; + dist[t] = Math.min(dist[t], backup[f] + p); + } + } + return dist[dst] == INF ? -1 : dist[dst]; + } +} +``` + +```cpp +class Solution { +public: + int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) { + const int inf = 0x3f3f3f3f; + vector dist(n, inf); + vector backup; + dist[src] = 0; + for (int i = 0; i < k + 1; ++i) { + backup = dist; + for (auto& e : flights) { + int f = e[0], t = e[1], p = e[2]; + dist[t] = min(dist[t], backup[f] + p); + } + } + return dist[dst] == inf ? -1 : dist[dst]; + } +}; +``` + +```go +func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int { + const inf = 0x3f3f3f3f + dist := make([]int, n) + backup := make([]int, n) + for i := range dist { + dist[i] = inf + } + dist[src] = 0 + for i := 0; i < k+1; i++ { + copy(backup, dist) + for _, e := range flights { + f, t, p := e[0], e[1], e[2] + dist[t] = min(dist[t], backup[f]+p) + } + } + if dist[dst] == inf { + return -1 + } + return dist[dst] +} +``` + + + +### 方法二:DFS + 记忆化搜索 + + + ```python class Solution: def findCheapestPrice( @@ -107,31 +169,6 @@ class Solution: return -1 if ans >= inf else ans ``` -### **Java** - - - -```java -class Solution { - private static final int INF = 0x3f3f3f3f; - - public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { - int[] dist = new int[n]; - int[] backup = new int[n]; - Arrays.fill(dist, INF); - dist[src] = 0; - for (int i = 0; i < k + 1; ++i) { - System.arraycopy(dist, 0, backup, 0, n); - for (int[] e : flights) { - int f = e[0], t = e[1], p = e[2]; - dist[t] = Math.min(dist[t], backup[f] + p); - } - } - return dist[dst] == INF ? -1 : dist[dst]; - } -} -``` - ```java class Solution { private int[][] memo; @@ -176,28 +213,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) { - const int inf = 0x3f3f3f3f; - vector dist(n, inf); - vector backup; - dist[src] = 0; - for (int i = 0; i < k + 1; ++i) { - backup = dist; - for (auto& e : flights) { - int f = e[0], t = e[1], p = e[2]; - dist[t] = min(dist[t], backup[f] + p); - } - } - return dist[dst] == inf ? -1 : dist[dst]; - } -}; -``` - ```cpp class Solution { public: @@ -230,31 +245,6 @@ public: }; ``` -### **Go** - -```go -func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int { - const inf = 0x3f3f3f3f - dist := make([]int, n) - backup := make([]int, n) - for i := range dist { - dist[i] = inf - } - dist[src] = 0 - for i := 0; i < k+1; i++ { - copy(backup, dist) - for _, e := range flights { - f, t, p := e[0], e[1], e[2] - dist[t] = min(dist[t], backup[f]+p) - } - } - if dist[dst] == inf { - return -1 - } - return dist[dst] -} -``` - ```go func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int { n += 10 @@ -300,10 +290,6 @@ func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0787.Cheapest Flights Within K Stops/README_EN.md b/solution/0700-0799/0787.Cheapest Flights Within K Stops/README_EN.md index 17e5cc8cc21ee..5e70b37095e83 100644 --- a/solution/0700-0799/0787.Cheapest Flights Within K Stops/README_EN.md +++ b/solution/0700-0799/0787.Cheapest Flights Within K Stops/README_EN.md @@ -57,9 +57,9 @@ The optimal path with no stops from city 0 to 2 is marked in red and has cost 50 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,6 +76,76 @@ class Solution: return -1 if dist[dst] == INF else dist[dst] ``` +```java +class Solution { + private static final int INF = 0x3f3f3f3f; + + public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { + int[] dist = new int[n]; + int[] backup = new int[n]; + Arrays.fill(dist, INF); + dist[src] = 0; + for (int i = 0; i < k + 1; ++i) { + System.arraycopy(dist, 0, backup, 0, n); + for (int[] e : flights) { + int f = e[0], t = e[1], p = e[2]; + dist[t] = Math.min(dist[t], backup[f] + p); + } + } + return dist[dst] == INF ? -1 : dist[dst]; + } +} +``` + +```cpp +class Solution { +public: + int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) { + const int inf = 0x3f3f3f3f; + vector dist(n, inf); + vector backup; + dist[src] = 0; + for (int i = 0; i < k + 1; ++i) { + backup = dist; + for (auto& e : flights) { + int f = e[0], t = e[1], p = e[2]; + dist[t] = min(dist[t], backup[f] + p); + } + } + return dist[dst] == inf ? -1 : dist[dst]; + } +}; +``` + +```go +func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int { + const inf = 0x3f3f3f3f + dist := make([]int, n) + backup := make([]int, n) + for i := range dist { + dist[i] = inf + } + dist[src] = 0 + for i := 0; i < k+1; i++ { + copy(backup, dist) + for _, e := range flights { + f, t, p := e[0], e[1], e[2] + dist[t] = min(dist[t], backup[f]+p) + } + } + if dist[dst] == inf { + return -1 + } + return dist[dst] +} +``` + + + +### Solution 2 + + + ```python class Solution: def findCheapestPrice( @@ -100,29 +170,6 @@ class Solution: return -1 if ans >= inf else ans ``` -### **Java** - -```java -class Solution { - private static final int INF = 0x3f3f3f3f; - - public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { - int[] dist = new int[n]; - int[] backup = new int[n]; - Arrays.fill(dist, INF); - dist[src] = 0; - for (int i = 0; i < k + 1; ++i) { - System.arraycopy(dist, 0, backup, 0, n); - for (int[] e : flights) { - int f = e[0], t = e[1], p = e[2]; - dist[t] = Math.min(dist[t], backup[f] + p); - } - } - return dist[dst] == INF ? -1 : dist[dst]; - } -} -``` - ```java class Solution { private int[][] memo; @@ -167,28 +214,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) { - const int inf = 0x3f3f3f3f; - vector dist(n, inf); - vector backup; - dist[src] = 0; - for (int i = 0; i < k + 1; ++i) { - backup = dist; - for (auto& e : flights) { - int f = e[0], t = e[1], p = e[2]; - dist[t] = min(dist[t], backup[f] + p); - } - } - return dist[dst] == inf ? -1 : dist[dst]; - } -}; -``` - ```cpp class Solution { public: @@ -221,31 +246,6 @@ public: }; ``` -### **Go** - -```go -func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int { - const inf = 0x3f3f3f3f - dist := make([]int, n) - backup := make([]int, n) - for i := range dist { - dist[i] = inf - } - dist[src] = 0 - for i := 0; i < k+1; i++ { - copy(backup, dist) - for _, e := range flights { - f, t, p := e[0], e[1], e[2] - dist[t] = min(dist[t], backup[f]+p) - } - } - if dist[dst] == inf { - return -1 - } - return dist[dst] -} -``` - ```go func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int { n += 10 @@ -291,10 +291,6 @@ func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0788.Rotated Digits/README.md b/solution/0700-0799/0788.Rotated Digits/README.md index b080a88b403fb..63bbd4ceaf07f 100644 --- a/solution/0700-0799/0788.Rotated Digits/README.md +++ b/solution/0700-0799/0788.Rotated Digits/README.md @@ -33,9 +33,7 @@ ## 解法 - - -**方法一:直接枚举** +### 方法一:直接枚举 一种直观且有效的思路是,直接枚举 $[1,2,..n]$ 中的每个数,判断其是否为好数,若为好数,则答案加一。 @@ -49,7 +47,117 @@ 相似题目:[1056. 易混淆数](/solution/1000-1099/1056.Confusing%20Number/README.md) -**方法二:数位 DP** + + +```python +class Solution: + def rotatedDigits(self, n: int) -> int: + def check(x): + y, t = 0, x + k = 1 + while t: + v = t % 10 + if d[v] == -1: + return False + y = d[v] * k + y + k *= 10 + t //= 10 + return x != y + + d = [0, 1, 5, -1, -1, 2, 9, -1, 8, 6] + return sum(check(i) for i in range(1, n + 1)) +``` + +```java +class Solution { + private int[] d = new int[] {0, 1, 5, -1, -1, 2, 9, -1, 8, 6}; + + public int rotatedDigits(int n) { + int ans = 0; + for (int i = 1; i <= n; ++i) { + if (check(i)) { + ++ans; + } + } + return ans; + } + + private boolean check(int x) { + int y = 0, t = x; + int k = 1; + while (t > 0) { + int v = t % 10; + if (d[v] == -1) { + return false; + } + y = d[v] * k + y; + k *= 10; + t /= 10; + } + return x != y; + } +} +``` + +```cpp +class Solution { +public: + const vector d = {0, 1, 5, -1, -1, 2, 9, -1, 8, 6}; + + int rotatedDigits(int n) { + int ans = 0; + for (int i = 1; i <= n; ++i) { + ans += check(i); + } + return ans; + } + + bool check(int x) { + int y = 0, t = x; + int k = 1; + while (t) { + int v = t % 10; + if (d[v] == -1) { + return false; + } + y = d[v] * k + y; + k *= 10; + t /= 10; + } + return x != y; + } +}; +``` + +```go +func rotatedDigits(n int) int { + d := []int{0, 1, 5, -1, -1, 2, 9, -1, 8, 6} + check := func(x int) bool { + y, t := 0, x + k := 1 + for ; t > 0; t /= 10 { + v := t % 10 + if d[v] == -1 { + return false + } + y = d[v]*k + y + k *= 10 + } + return x != y + } + ans := 0 + for i := 1; i <= n; i++ { + if check(i) { + ans++ + } + } + return ans +} +``` + + + +### 方法二:数位 DP 方法一的做法足以通过本题,但时间复杂度较高。如果题目的数据范围达到 $10^9$ 级别,则方法一的做法会超出时间限制。 @@ -91,29 +199,6 @@ $$ -### **Python3** - - - -```python -class Solution: - def rotatedDigits(self, n: int) -> int: - def check(x): - y, t = 0, x - k = 1 - while t: - v = t % 10 - if d[v] == -1: - return False - y = d[v] * k + y - k *= 10 - t //= 10 - return x != y - - d = [0, 1, 5, -1, -1, 2, 9, -1, 8, 6] - return sum(check(i) for i in range(1, n + 1)) -``` - ```python class Solution: def rotatedDigits(self, n: int) -> int: @@ -139,41 +224,6 @@ class Solution: return dfs(l, 0, True) ``` -### **Java** - - - -```java -class Solution { - private int[] d = new int[] {0, 1, 5, -1, -1, 2, 9, -1, 8, 6}; - - public int rotatedDigits(int n) { - int ans = 0; - for (int i = 1; i <= n; ++i) { - if (check(i)) { - ++ans; - } - } - return ans; - } - - private boolean check(int x) { - int y = 0, t = x; - int k = 1; - while (t > 0) { - int v = t % 10; - if (d[v] == -1) { - return false; - } - y = d[v] * k + y; - k *= 10; - t /= 10; - } - return x != y; - } -} -``` - ```java class Solution { private int[] a = new int[6]; @@ -216,38 +266,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - const vector d = {0, 1, 5, -1, -1, 2, 9, -1, 8, 6}; - - int rotatedDigits(int n) { - int ans = 0; - for (int i = 1; i <= n; ++i) { - ans += check(i); - } - return ans; - } - - bool check(int x) { - int y = 0, t = x; - int k = 1; - while (t) { - int v = t % 10; - if (d[v] == -1) { - return false; - } - y = d[v] * k + y; - k *= 10; - t /= 10; - } - return x != y; - } -}; -``` - ```cpp class Solution { public: @@ -289,34 +307,6 @@ public: }; ``` -### **Go** - -```go -func rotatedDigits(n int) int { - d := []int{0, 1, 5, -1, -1, 2, 9, -1, 8, 6} - check := func(x int) bool { - y, t := 0, x - k := 1 - for ; t > 0; t /= 10 { - v := t % 10 - if d[v] == -1 { - return false - } - y = d[v]*k + y - k *= 10 - } - return x != y - } - ans := 0 - for i := 1; i <= n; i++ { - if check(i) { - ans++ - } - } - return ans -} -``` - ```go func rotatedDigits(n int) int { a := make([]int, 6) @@ -362,10 +352,6 @@ func rotatedDigits(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0788.Rotated Digits/README_EN.md b/solution/0700-0799/0788.Rotated Digits/README_EN.md index 0d0f193be1308..2e2b1d600ac87 100644 --- a/solution/0700-0799/0788.Rotated Digits/README_EN.md +++ b/solution/0700-0799/0788.Rotated Digits/README_EN.md @@ -50,9 +50,9 @@ Note that 1 and 10 are not good numbers, since they remain unchanged after rotat ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,33 +73,6 @@ class Solution: return sum(check(i) for i in range(1, n + 1)) ``` -```python -class Solution: - def rotatedDigits(self, n: int) -> int: - @cache - def dfs(pos, ok, limit): - if pos <= 0: - return ok - up = a[pos] if limit else 9 - ans = 0 - for i in range(up + 1): - if i in (0, 1, 8): - ans += dfs(pos - 1, ok, limit and i == up) - if i in (2, 5, 6, 9): - ans += dfs(pos - 1, 1, limit and i == up) - return ans - - a = [0] * 6 - l = 1 - while n: - a[l] = n % 10 - n //= 10 - l += 1 - return dfs(l, 0, True) -``` - -### **Java** - ```java class Solution { private int[] d = new int[] {0, 1, 5, -1, -1, 2, 9, -1, 8, 6}; @@ -131,6 +104,93 @@ class Solution { } ``` +```cpp +class Solution { +public: + const vector d = {0, 1, 5, -1, -1, 2, 9, -1, 8, 6}; + + int rotatedDigits(int n) { + int ans = 0; + for (int i = 1; i <= n; ++i) { + ans += check(i); + } + return ans; + } + + bool check(int x) { + int y = 0, t = x; + int k = 1; + while (t) { + int v = t % 10; + if (d[v] == -1) { + return false; + } + y = d[v] * k + y; + k *= 10; + t /= 10; + } + return x != y; + } +}; +``` + +```go +func rotatedDigits(n int) int { + d := []int{0, 1, 5, -1, -1, 2, 9, -1, 8, 6} + check := func(x int) bool { + y, t := 0, x + k := 1 + for ; t > 0; t /= 10 { + v := t % 10 + if d[v] == -1 { + return false + } + y = d[v]*k + y + k *= 10 + } + return x != y + } + ans := 0 + for i := 1; i <= n; i++ { + if check(i) { + ans++ + } + } + return ans +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def rotatedDigits(self, n: int) -> int: + @cache + def dfs(pos, ok, limit): + if pos <= 0: + return ok + up = a[pos] if limit else 9 + ans = 0 + for i in range(up + 1): + if i in (0, 1, 8): + ans += dfs(pos - 1, ok, limit and i == up) + if i in (2, 5, 6, 9): + ans += dfs(pos - 1, 1, limit and i == up) + return ans + + a = [0] * 6 + l = 1 + while n: + a[l] = n % 10 + n //= 10 + l += 1 + return dfs(l, 0, True) +``` + ```java class Solution { private int[] a = new int[6]; @@ -173,38 +233,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - const vector d = {0, 1, 5, -1, -1, 2, 9, -1, 8, 6}; - - int rotatedDigits(int n) { - int ans = 0; - for (int i = 1; i <= n; ++i) { - ans += check(i); - } - return ans; - } - - bool check(int x) { - int y = 0, t = x; - int k = 1; - while (t) { - int v = t % 10; - if (d[v] == -1) { - return false; - } - y = d[v] * k + y; - k *= 10; - t /= 10; - } - return x != y; - } -}; -``` - ```cpp class Solution { public: @@ -246,34 +274,6 @@ public: }; ``` -### **Go** - -```go -func rotatedDigits(n int) int { - d := []int{0, 1, 5, -1, -1, 2, 9, -1, 8, 6} - check := func(x int) bool { - y, t := 0, x - k := 1 - for ; t > 0; t /= 10 { - v := t % 10 - if d[v] == -1 { - return false - } - y = d[v]*k + y - k *= 10 - } - return x != y - } - ans := 0 - for i := 1; i <= n; i++ { - if check(i) { - ans++ - } - } - return ans -} -``` - ```go func rotatedDigits(n int) int { a := make([]int, 6) @@ -319,10 +319,6 @@ func rotatedDigits(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0789.Escape The Ghosts/README.md b/solution/0700-0799/0789.Escape The Ghosts/README.md index fa537c839716d..e7b7da41faeda 100644 --- a/solution/0700-0799/0789.Escape The Ghosts/README.md +++ b/solution/0700-0799/0789.Escape The Ghosts/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:曼哈顿距离** +### 方法一:曼哈顿距离 对于任意一个阻碍者,如果它到目的地的曼哈顿距离小于等于你到目的地的曼哈顿距离,那么它就可以在你到达目的地之前抓住你。因此,我们只需要判断所有阻碍者到目的地的曼哈顿距离是否都大于你到目的地的曼哈顿距离即可。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool: @@ -75,10 +69,6 @@ class Solution: return all(abs(tx - x) + abs(ty - y) > abs(tx) + abs(ty) for x, y in ghosts) ``` -### **Java** - - - ```java class Solution { public boolean escapeGhosts(int[][] ghosts, int[] target) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +100,6 @@ public: }; ``` -### **Go** - ```go func escapeGhosts(ghosts [][]int, target []int) bool { tx, ty := target[0], target[1] @@ -134,8 +120,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function escapeGhosts(ghosts: number[][], target: number[]): boolean { const [tx, ty] = target; @@ -148,10 +132,6 @@ function escapeGhosts(ghosts: number[][], target: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0789.Escape The Ghosts/README_EN.md b/solution/0700-0799/0789.Escape The Ghosts/README_EN.md index e0611b7b481be..6322356747c70 100644 --- a/solution/0700-0799/0789.Escape The Ghosts/README_EN.md +++ b/solution/0700-0799/0789.Escape The Ghosts/README_EN.md @@ -51,9 +51,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return all(abs(tx - x) + abs(ty - y) > abs(tx) + abs(ty) for x, y in ghosts) ``` -### **Java** - ```java class Solution { public boolean escapeGhosts(int[][] ghosts, int[] target) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +93,6 @@ public: }; ``` -### **Go** - ```go func escapeGhosts(ghosts [][]int, target []int) bool { tx, ty := target[0], target[1] @@ -119,8 +113,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function escapeGhosts(ghosts: number[][], target: number[]): boolean { const [tx, ty] = target; @@ -133,10 +125,6 @@ function escapeGhosts(ghosts: number[][], target: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0790.Domino and Tromino Tiling/README.md b/solution/0700-0799/0790.Domino and Tromino Tiling/README.md index 9ad2957804c4c..0cfd8cef27fc5 100644 --- a/solution/0700-0799/0790.Domino and Tromino Tiling/README.md +++ b/solution/0700-0799/0790.Domino and Tromino Tiling/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们首先要读懂题意,题目实际上是让我们求铺满 $2\times n$ 的面板的方案数,其中面板上的每个正方形只能被一个瓷砖覆盖。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def numTilings(self, n: int) -> int: @@ -109,25 +103,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def numTilings(self, n: int) -> int: - f = [1, 0, 0, 0] - mod = 10**9 + 7 - for i in range(1, n + 1): - g = [0] * 4 - g[0] = (f[0] + f[1] + f[2] + f[3]) % mod - g[1] = (f[2] + f[3]) % mod - g[2] = (f[1] + f[3]) % mod - g[3] = f[0] - f = g - return f[0] -``` - -### **Java** - - - ```java class Solution { public int numTilings(int n) { @@ -146,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +141,6 @@ public: }; ``` -### **Go** - ```go func numTilings(n int) int { f := [4]int{} @@ -187,10 +158,27 @@ func numTilings(n int) int { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def numTilings(self, n: int) -> int: + f = [1, 0, 0, 0] + mod = 10**9 + 7 + for i in range(1, n + 1): + g = [0] * 4 + g[0] = (f[0] + f[1] + f[2] + f[3]) % mod + g[1] = (f[2] + f[3]) % mod + g[2] = (f[1] + f[3]) % mod + g[3] = f[0] + f = g + return f[0] ``` + + diff --git a/solution/0700-0799/0790.Domino and Tromino Tiling/README_EN.md b/solution/0700-0799/0790.Domino and Tromino Tiling/README_EN.md index 87d619f8d4838..c1364bc1afdd3 100644 --- a/solution/0700-0799/0790.Domino and Tromino Tiling/README_EN.md +++ b/solution/0700-0799/0790.Domino and Tromino Tiling/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,23 +66,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def numTilings(self, n: int) -> int: - f = [1, 0, 0, 0] - mod = 10**9 + 7 - for i in range(1, n + 1): - g = [0] * 4 - g[0] = (f[0] + f[1] + f[2] + f[3]) % mod - g[1] = (f[2] + f[3]) % mod - g[2] = (f[1] + f[3]) % mod - g[3] = f[0] - f = g - return f[0] -``` - -### **Java** - ```java class Solution { public int numTilings(int n) { @@ -101,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +104,6 @@ public: }; ``` -### **Go** - ```go func numTilings(n int) int { f := [4]int{} @@ -142,10 +121,27 @@ func numTilings(n int) int { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def numTilings(self, n: int) -> int: + f = [1, 0, 0, 0] + mod = 10**9 + 7 + for i in range(1, n + 1): + g = [0] * 4 + g[0] = (f[0] + f[1] + f[2] + f[3]) % mod + g[1] = (f[2] + f[3]) % mod + g[2] = (f[1] + f[3]) % mod + g[3] = f[0] + f = g + return f[0] ``` + + diff --git a/solution/0700-0799/0791.Custom Sort String/README.md b/solution/0700-0799/0791.Custom Sort String/README.md index 9ec50eeee4fca..7c5a303a21839 100644 --- a/solution/0700-0799/0791.Custom Sort String/README.md +++ b/solution/0700-0799/0791.Custom Sort String/README.md @@ -43,28 +43,14 @@ ## 解法 - - -**方法一:自定义排序** +### 方法一:自定义排序 一种比较直接的思路是,用哈希表或数组 $d$ 记录字符串 $order$ 中每个字符的位置,然后对字符串 $s$ 中每个字符按照其在 $d$ 中的位置进行排序。如果某个字符不在 $d$ 中,我们可以将其位置置为 $0$。 时间复杂度 $O(m + n\times \log n)$,空间复杂度 $O(m)$。其中 $m$ 和 $n$ 分别是字符串 $order$ 和 $s$ 的长度。 -**方法二:字符计数** - -我们还可以先统计 $s$ 中每个字符的出现次数,存储在 $cnt$ 数组中。 - -然后把字符串 $s$ 在 $order$ 中出现的字符按照 $order$ 中的顺序排序,添加到结果字符串中。最后把剩余的字符直接追加到结果字符串中。 - -时间复杂度 $O(m+n)$,空间复杂度 $O(m)$。其中 $m$ 和 $n$ 分别是字符串 $order$ 和 $s$ 的长度。 - -### **Python3** - - - ```python class Solution: def customSortString(self, order: str, s: str) -> str: @@ -72,23 +58,6 @@ class Solution: return ''.join(sorted(s, key=lambda x: d.get(x, 0))) ``` -```python -class Solution: - def customSortString(self, order: str, s: str) -> str: - cnt = Counter(s) - ans = [] - for c in order: - ans.append(c * cnt[c]) - cnt[c] = 0 - for c, v in cnt.items(): - ans.append(c * v) - return ''.join(ans) -``` - -### **Java** - - - ```java class Solution { public String customSortString(String order, String s) { @@ -106,6 +75,84 @@ class Solution { } ``` +```cpp +class Solution { +public: + string customSortString(string order, string s) { + int d[26] = {0}; + for (int i = 0; i < order.size(); ++i) d[order[i] - 'a'] = i; + sort(s.begin(), s.end(), [&](auto a, auto b) { return d[a - 'a'] < d[b - 'a']; }); + return s; + } +}; +``` + +```go +func customSortString(order string, s string) string { + d := [26]int{} + for i := range order { + d[order[i]-'a'] = i + } + cs := []byte(s) + sort.Slice(cs, func(i, j int) bool { return d[cs[i]-'a'] < d[cs[j]-'a'] }) + return string(cs) +} +``` + +```ts +function customSortString(order: string, s: string): string { + const toIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); + const n = order.length; + const d = new Array(26).fill(n); + for (let i = 0; i < n; i++) { + d[toIndex(order[i])] = i; + } + return [...s].sort((a, b) => d[toIndex(a)] - d[toIndex(b)]).join(''); +} +``` + +```rust +impl Solution { + pub fn custom_sort_string(order: String, s: String) -> String { + let n = order.len(); + let mut d = [n; 26]; + for (i, c) in order.as_bytes().iter().enumerate() { + d[(c - b'a') as usize] = i; + } + let mut ans = s.chars().collect::>(); + ans.sort_by(|&a, &b| + d[((a as u8) - ('a' as u8)) as usize].cmp(&d[((b as u8) - ('a' as u8)) as usize]) + ); + ans.into_iter().collect() + } +} +``` + + + +### 方法二:字符计数 + +我们还可以先统计 $s$ 中每个字符的出现次数,存储在 $cnt$ 数组中。 + +然后把字符串 $s$ 在 $order$ 中出现的字符按照 $order$ 中的顺序排序,添加到结果字符串中。最后把剩余的字符直接追加到结果字符串中。 + +时间复杂度 $O(m+n)$,空间复杂度 $O(m)$。其中 $m$ 和 $n$ 分别是字符串 $order$ 和 $s$ 的长度。 + + + +```python +class Solution: + def customSortString(self, order: str, s: str) -> str: + cnt = Counter(s) + ans = [] + for c in order: + ans.append(c * cnt[c]) + cnt[c] = 0 + for c, v in cnt.items(): + ans.append(c * v) + return ''.join(ans) +``` + ```java class Solution { public String customSortString(String order, String s) { @@ -130,20 +177,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string customSortString(string order, string s) { - int d[26] = {0}; - for (int i = 0; i < order.size(); ++i) d[order[i] - 'a'] = i; - sort(s.begin(), s.end(), [&](auto a, auto b) { return d[a - 'a'] < d[b - 'a']; }); - return s; - } -}; -``` - ```cpp class Solution { public: @@ -160,20 +193,6 @@ public: }; ``` -### **Go** - -```go -func customSortString(order string, s string) string { - d := [26]int{} - for i := range order { - d[order[i]-'a'] = i - } - cs := []byte(s) - sort.Slice(cs, func(i, j int) bool { return d[cs[i]-'a'] < d[cs[j]-'a'] }) - return string(cs) -} -``` - ```go func customSortString(order string, s string) string { cnt := [26]int{} @@ -196,20 +215,6 @@ func customSortString(order string, s string) string { } ``` -### **TypeScript** - -```ts -function customSortString(order: string, s: string): string { - const toIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); - const n = order.length; - const d = new Array(26).fill(n); - for (let i = 0; i < n; i++) { - d[toIndex(order[i])] = i; - } - return [...s].sort((a, b) => d[toIndex(a)] - d[toIndex(b)]).join(''); -} -``` - ```ts function customSortString(order: string, s: string): string { const toIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); @@ -231,25 +236,6 @@ function customSortString(order: string, s: string): string { } ``` -### **Rust** - -```rust -impl Solution { - pub fn custom_sort_string(order: String, s: String) -> String { - let n = order.len(); - let mut d = [n; 26]; - for (i, c) in order.as_bytes().iter().enumerate() { - d[(c - b'a') as usize] = i; - } - let mut ans = s.chars().collect::>(); - ans.sort_by(|&a, &b| - d[((a as u8) - ('a' as u8)) as usize].cmp(&d[((b as u8) - ('a' as u8)) as usize]) - ); - ans.into_iter().collect() - } -} -``` - ```rust impl Solution { pub fn custom_sort_string(order: String, s: String) -> String { @@ -274,10 +260,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0791.Custom Sort String/README_EN.md b/solution/0700-0799/0791.Custom Sort String/README_EN.md index c25a13000998c..27ff5607e1eaa 100644 --- a/solution/0700-0799/0791.Custom Sort String/README_EN.md +++ b/solution/0700-0799/0791.Custom Sort String/README_EN.md @@ -40,9 +40,9 @@ Since "d" does not appear in order, it can be at any position in the r ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,21 +51,6 @@ class Solution: return ''.join(sorted(s, key=lambda x: d.get(x, 0))) ``` -```python -class Solution: - def customSortString(self, order: str, s: str) -> str: - cnt = Counter(s) - ans = [] - for c in order: - ans.append(c * cnt[c]) - cnt[c] = 0 - for c, v in cnt.items(): - ans.append(c * v) - return ''.join(ans) -``` - -### **Java** - ```java class Solution { public String customSortString(String order, String s) { @@ -83,6 +68,78 @@ class Solution { } ``` +```cpp +class Solution { +public: + string customSortString(string order, string s) { + int d[26] = {0}; + for (int i = 0; i < order.size(); ++i) d[order[i] - 'a'] = i; + sort(s.begin(), s.end(), [&](auto a, auto b) { return d[a - 'a'] < d[b - 'a']; }); + return s; + } +}; +``` + +```go +func customSortString(order string, s string) string { + d := [26]int{} + for i := range order { + d[order[i]-'a'] = i + } + cs := []byte(s) + sort.Slice(cs, func(i, j int) bool { return d[cs[i]-'a'] < d[cs[j]-'a'] }) + return string(cs) +} +``` + +```ts +function customSortString(order: string, s: string): string { + const toIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); + const n = order.length; + const d = new Array(26).fill(n); + for (let i = 0; i < n; i++) { + d[toIndex(order[i])] = i; + } + return [...s].sort((a, b) => d[toIndex(a)] - d[toIndex(b)]).join(''); +} +``` + +```rust +impl Solution { + pub fn custom_sort_string(order: String, s: String) -> String { + let n = order.len(); + let mut d = [n; 26]; + for (i, c) in order.as_bytes().iter().enumerate() { + d[(c - b'a') as usize] = i; + } + let mut ans = s.chars().collect::>(); + ans.sort_by(|&a, &b| + d[((a as u8) - ('a' as u8)) as usize].cmp(&d[((b as u8) - ('a' as u8)) as usize]) + ); + ans.into_iter().collect() + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def customSortString(self, order: str, s: str) -> str: + cnt = Counter(s) + ans = [] + for c in order: + ans.append(c * cnt[c]) + cnt[c] = 0 + for c, v in cnt.items(): + ans.append(c * v) + return ''.join(ans) +``` + ```java class Solution { public String customSortString(String order, String s) { @@ -107,20 +164,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string customSortString(string order, string s) { - int d[26] = {0}; - for (int i = 0; i < order.size(); ++i) d[order[i] - 'a'] = i; - sort(s.begin(), s.end(), [&](auto a, auto b) { return d[a - 'a'] < d[b - 'a']; }); - return s; - } -}; -``` - ```cpp class Solution { public: @@ -137,20 +180,6 @@ public: }; ``` -### **Go** - -```go -func customSortString(order string, s string) string { - d := [26]int{} - for i := range order { - d[order[i]-'a'] = i - } - cs := []byte(s) - sort.Slice(cs, func(i, j int) bool { return d[cs[i]-'a'] < d[cs[j]-'a'] }) - return string(cs) -} -``` - ```go func customSortString(order string, s string) string { cnt := [26]int{} @@ -173,20 +202,6 @@ func customSortString(order string, s string) string { } ``` -### **TypeScript** - -```ts -function customSortString(order: string, s: string): string { - const toIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); - const n = order.length; - const d = new Array(26).fill(n); - for (let i = 0; i < n; i++) { - d[toIndex(order[i])] = i; - } - return [...s].sort((a, b) => d[toIndex(a)] - d[toIndex(b)]).join(''); -} -``` - ```ts function customSortString(order: string, s: string): string { const toIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); @@ -208,25 +223,6 @@ function customSortString(order: string, s: string): string { } ``` -### **Rust** - -```rust -impl Solution { - pub fn custom_sort_string(order: String, s: String) -> String { - let n = order.len(); - let mut d = [n; 26]; - for (i, c) in order.as_bytes().iter().enumerate() { - d[(c - b'a') as usize] = i; - } - let mut ans = s.chars().collect::>(); - ans.sort_by(|&a, &b| - d[((a as u8) - ('a' as u8)) as usize].cmp(&d[((b as u8) - ('a' as u8)) as usize]) - ); - ans.into_iter().collect() - } -} -``` - ```rust impl Solution { pub fn custom_sort_string(order: String, s: String) -> String { @@ -251,10 +247,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0792.Number of Matching Subsequences/README.md b/solution/0700-0799/0792.Number of Matching Subsequences/README.md index 6afc508db1348..f7af1e3fb3a57 100644 --- a/solution/0700-0799/0792.Number of Matching Subsequences/README.md +++ b/solution/0700-0799/0792.Number of Matching Subsequences/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:分桶** +### 方法一:分桶 题目中字符串 $s$ 的数据规模最高达到 $5 \times 10^4$,如果暴力枚举 $words$ 中的每个字符串 $w$,判断其是否为 $s$ 的子序列,很有可能会超时。 @@ -73,24 +71,8 @@ b: ["bb"] 时间复杂度 $O(n + \sum_{i=0}^{m-1} |w_i|)$,空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别为 $s$ 和 $words$ 的长度,而 $|w_i|$ 为 $words[i]$ 的长度。 -**方法二:二分查找** - -我们还可以先用数组或哈希表 $d$ 存放字符串 $s$ 每个字符的下标,即 $d[c]$ 为 $s$ 中所有字符 $c$ 的下标组成的数组。 - -然后我们遍历 $words$ 中的每个单词 $w$,我们通过二分查找的方法,判断 $w$ 是否为 $s$ 的子序列,是则答案加 $1$。判断逻辑如下: - -1. 定义指针 $i$ 表示当前指向字符串 $s$ 的第 $i$ 个字符,初始化为 $-1$。 -1. 遍历字符串 $w$ 中的每个字符 $c$,在 $d[c]$ 中二分查找第一个大于 $i$ 的位置 $j$,如果不存在,则说明 $w$ 不是 $s$ 的子序列,直接跳出循环;否则,将 $i$ 更新为 $d[c][j]$,继续遍历下一个字符。 -1. 如果遍历完 $w$ 中的所有字符,说明 $w$ 是 $s$ 的子序列。 - -时间复杂度 $O(\sum_{i=0}^{m-1} |w_i| \times \log n)$,空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别为 $s$ 和 $words$ 的长度,而 $|w_i|$ 为 $words[i]$ 的长度。 - -### **Python3** - - - ```python class Solution: def numMatchingSubseq(self, s: str, words: List[str]) -> int: @@ -108,46 +90,6 @@ class Solution: return ans ``` -```python -class Solution: - def numMatchingSubseq(self, s: str, words: List[str]) -> int: - d = defaultdict(deque) - for i, w in enumerate(words): - d[w[0]].append((i, 0)) - ans = 0 - for c in s: - for _ in range(len(d[c])): - i, j = d[c].popleft() - j += 1 - if j == len(words[i]): - ans += 1 - else: - d[words[i][j]].append((i, j)) - return ans -``` - -```python -class Solution: - def numMatchingSubseq(self, s: str, words: List[str]) -> int: - def check(w): - i = -1 - for c in w: - j = bisect_right(d[c], i) - if j == len(d[c]): - return False - i = d[c][j] - return True - - d = defaultdict(list) - for i, c in enumerate(s): - d[c].append(i) - return sum(check(w) for w in words) -``` - -### **Java** - - - ```java class Solution { public int numMatchingSubseq(String s, String[] words) { @@ -173,6 +115,84 @@ class Solution { } ``` +```cpp +class Solution { +public: + int numMatchingSubseq(string s, vector& words) { + vector> d(26); + for (auto& w : words) d[w[0] - 'a'].emplace(w); + int ans = 0; + for (char& c : s) { + auto& q = d[c - 'a']; + for (int k = q.size(); k; --k) { + auto t = q.front(); + q.pop(); + if (t.size() == 1) + ++ans; + else + d[t[1] - 'a'].emplace(t.substr(1)); + } + } + return ans; + } +}; +``` + +```go +func numMatchingSubseq(s string, words []string) (ans int) { + d := [26][]string{} + for _, w := range words { + d[w[0]-'a'] = append(d[w[0]-'a'], w) + } + for _, c := range s { + q := d[c-'a'] + d[c-'a'] = nil + for _, t := range q { + if len(t) == 1 { + ans++ + } else { + d[t[1]-'a'] = append(d[t[1]-'a'], t[1:]) + } + } + } + return +} +``` + + + +### 方法二:二分查找 + +我们还可以先用数组或哈希表 $d$ 存放字符串 $s$ 每个字符的下标,即 $d[c]$ 为 $s$ 中所有字符 $c$ 的下标组成的数组。 + +然后我们遍历 $words$ 中的每个单词 $w$,我们通过二分查找的方法,判断 $w$ 是否为 $s$ 的子序列,是则答案加 $1$。判断逻辑如下: + +1. 定义指针 $i$ 表示当前指向字符串 $s$ 的第 $i$ 个字符,初始化为 $-1$。 +1. 遍历字符串 $w$ 中的每个字符 $c$,在 $d[c]$ 中二分查找第一个大于 $i$ 的位置 $j$,如果不存在,则说明 $w$ 不是 $s$ 的子序列,直接跳出循环;否则,将 $i$ 更新为 $d[c][j]$,继续遍历下一个字符。 +1. 如果遍历完 $w$ 中的所有字符,说明 $w$ 是 $s$ 的子序列。 + +时间复杂度 $O(\sum_{i=0}^{m-1} |w_i| \times \log n)$,空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别为 $s$ 和 $words$ 的长度,而 $|w_i|$ 为 $words[i]$ 的长度。 + + + +```python +class Solution: + def numMatchingSubseq(self, s: str, words: List[str]) -> int: + d = defaultdict(deque) + for i, w in enumerate(words): + d[w[0]].append((i, 0)) + ans = 0 + for c in s: + for _ in range(len(d[c])): + i, j = d[c].popleft() + j += 1 + if j == len(words[i]): + ans += 1 + else: + d[words[i][j]].append((i, j)) + return ans +``` + ```java class Solution { public int numMatchingSubseq(String s, String[] words) { @@ -199,6 +219,76 @@ class Solution { } ``` +```cpp +class Solution { +public: + int numMatchingSubseq(string s, vector& words) { + vector>> d(26); + for (int i = 0; i < words.size(); ++i) d[words[i][0] - 'a'].emplace(i, 0); + int ans = 0; + for (char& c : s) { + auto& q = d[c - 'a']; + for (int t = q.size(); t; --t) { + auto [i, j] = q.front(); + q.pop(); + if (++j == words[i].size()) + ++ans; + else + d[words[i][j] - 'a'].emplace(i, j); + } + } + return ans; + } +}; +``` + +```go +func numMatchingSubseq(s string, words []string) (ans int) { + type pair struct{ i, j int } + d := [26][]pair{} + for i, w := range words { + d[w[0]-'a'] = append(d[w[0]-'a'], pair{i, 0}) + } + for _, c := range s { + q := d[c-'a'] + d[c-'a'] = nil + for _, p := range q { + i, j := p.i, p.j+1 + if j == len(words[i]) { + ans++ + } else { + d[words[i][j]-'a'] = append(d[words[i][j]-'a'], pair{i, j}) + } + } + } + return +} +``` + + + +### 方法三 + + + +```python +class Solution: + def numMatchingSubseq(self, s: str, words: List[str]) -> int: + def check(w): + i = -1 + for c in w: + j = bisect_right(d[c], i) + if j == len(d[c]): + return False + i = d[c][j] + return True + + d = defaultdict(list) + for i, c in enumerate(s): + d[c].append(i) + return sum(check(w) for w in words) +``` + ```java class Solution { private List[] d = new List[26]; @@ -245,54 +335,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numMatchingSubseq(string s, vector& words) { - vector> d(26); - for (auto& w : words) d[w[0] - 'a'].emplace(w); - int ans = 0; - for (char& c : s) { - auto& q = d[c - 'a']; - for (int k = q.size(); k; --k) { - auto t = q.front(); - q.pop(); - if (t.size() == 1) - ++ans; - else - d[t[1] - 'a'].emplace(t.substr(1)); - } - } - return ans; - } -}; -``` - -```cpp -class Solution { -public: - int numMatchingSubseq(string s, vector& words) { - vector>> d(26); - for (int i = 0; i < words.size(); ++i) d[words[i][0] - 'a'].emplace(i, 0); - int ans = 0; - for (char& c : s) { - auto& q = d[c - 'a']; - for (int t = q.size(); t; --t) { - auto [i, j] = q.front(); - q.pop(); - if (++j == words[i].size()) - ++ans; - else - d[words[i][j] - 'a'].emplace(i, j); - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -316,52 +358,6 @@ public: }; ``` -### **Go** - -```go -func numMatchingSubseq(s string, words []string) (ans int) { - d := [26][]string{} - for _, w := range words { - d[w[0]-'a'] = append(d[w[0]-'a'], w) - } - for _, c := range s { - q := d[c-'a'] - d[c-'a'] = nil - for _, t := range q { - if len(t) == 1 { - ans++ - } else { - d[t[1]-'a'] = append(d[t[1]-'a'], t[1:]) - } - } - } - return -} -``` - -```go -func numMatchingSubseq(s string, words []string) (ans int) { - type pair struct{ i, j int } - d := [26][]pair{} - for i, w := range words { - d[w[0]-'a'] = append(d[w[0]-'a'], pair{i, 0}) - } - for _, c := range s { - q := d[c-'a'] - d[c-'a'] = nil - for _, p := range q { - i, j := p.i, p.j+1 - if j == len(words[i]) { - ans++ - } else { - d[words[i][j]-'a'] = append(d[words[i][j]-'a'], pair{i, j}) - } - } - } - return -} -``` - ```go func numMatchingSubseq(s string, words []string) (ans int) { d := [26][]int{} @@ -389,10 +385,6 @@ func numMatchingSubseq(s string, words []string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0792.Number of Matching Subsequences/README_EN.md b/solution/0700-0799/0792.Number of Matching Subsequences/README_EN.md index e154d014248a9..bf2a37f01cbd5 100644 --- a/solution/0700-0799/0792.Number of Matching Subsequences/README_EN.md +++ b/solution/0700-0799/0792.Number of Matching Subsequences/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,44 +61,6 @@ class Solution: return ans ``` -```python -class Solution: - def numMatchingSubseq(self, s: str, words: List[str]) -> int: - d = defaultdict(deque) - for i, w in enumerate(words): - d[w[0]].append((i, 0)) - ans = 0 - for c in s: - for _ in range(len(d[c])): - i, j = d[c].popleft() - j += 1 - if j == len(words[i]): - ans += 1 - else: - d[words[i][j]].append((i, j)) - return ans -``` - -```python -class Solution: - def numMatchingSubseq(self, s: str, words: List[str]) -> int: - def check(w): - i = -1 - for c in w: - j = bisect_right(d[c], i) - if j == len(d[c]): - return False - i = d[c][j] - return True - - d = defaultdict(list) - for i, c in enumerate(s): - d[c].append(i) - return sum(check(w) for w in words) -``` - -### **Java** - ```java class Solution { public int numMatchingSubseq(String s, String[] words) { @@ -124,6 +86,74 @@ class Solution { } ``` +```cpp +class Solution { +public: + int numMatchingSubseq(string s, vector& words) { + vector> d(26); + for (auto& w : words) d[w[0] - 'a'].emplace(w); + int ans = 0; + for (char& c : s) { + auto& q = d[c - 'a']; + for (int k = q.size(); k; --k) { + auto t = q.front(); + q.pop(); + if (t.size() == 1) + ++ans; + else + d[t[1] - 'a'].emplace(t.substr(1)); + } + } + return ans; + } +}; +``` + +```go +func numMatchingSubseq(s string, words []string) (ans int) { + d := [26][]string{} + for _, w := range words { + d[w[0]-'a'] = append(d[w[0]-'a'], w) + } + for _, c := range s { + q := d[c-'a'] + d[c-'a'] = nil + for _, t := range q { + if len(t) == 1 { + ans++ + } else { + d[t[1]-'a'] = append(d[t[1]-'a'], t[1:]) + } + } + } + return +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def numMatchingSubseq(self, s: str, words: List[str]) -> int: + d = defaultdict(deque) + for i, w in enumerate(words): + d[w[0]].append((i, 0)) + ans = 0 + for c in s: + for _ in range(len(d[c])): + i, j = d[c].popleft() + j += 1 + if j == len(words[i]): + ans += 1 + else: + d[words[i][j]].append((i, j)) + return ans +``` + ```java class Solution { public int numMatchingSubseq(String s, String[] words) { @@ -150,6 +180,76 @@ class Solution { } ``` +```cpp +class Solution { +public: + int numMatchingSubseq(string s, vector& words) { + vector>> d(26); + for (int i = 0; i < words.size(); ++i) d[words[i][0] - 'a'].emplace(i, 0); + int ans = 0; + for (char& c : s) { + auto& q = d[c - 'a']; + for (int t = q.size(); t; --t) { + auto [i, j] = q.front(); + q.pop(); + if (++j == words[i].size()) + ++ans; + else + d[words[i][j] - 'a'].emplace(i, j); + } + } + return ans; + } +}; +``` + +```go +func numMatchingSubseq(s string, words []string) (ans int) { + type pair struct{ i, j int } + d := [26][]pair{} + for i, w := range words { + d[w[0]-'a'] = append(d[w[0]-'a'], pair{i, 0}) + } + for _, c := range s { + q := d[c-'a'] + d[c-'a'] = nil + for _, p := range q { + i, j := p.i, p.j+1 + if j == len(words[i]) { + ans++ + } else { + d[words[i][j]-'a'] = append(d[words[i][j]-'a'], pair{i, j}) + } + } + } + return +} +``` + + + +### Solution 3 + + + +```python +class Solution: + def numMatchingSubseq(self, s: str, words: List[str]) -> int: + def check(w): + i = -1 + for c in w: + j = bisect_right(d[c], i) + if j == len(d[c]): + return False + i = d[c][j] + return True + + d = defaultdict(list) + for i, c in enumerate(s): + d[c].append(i) + return sum(check(w) for w in words) +``` + ```java class Solution { private List[] d = new List[26]; @@ -196,54 +296,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numMatchingSubseq(string s, vector& words) { - vector> d(26); - for (auto& w : words) d[w[0] - 'a'].emplace(w); - int ans = 0; - for (char& c : s) { - auto& q = d[c - 'a']; - for (int k = q.size(); k; --k) { - auto t = q.front(); - q.pop(); - if (t.size() == 1) - ++ans; - else - d[t[1] - 'a'].emplace(t.substr(1)); - } - } - return ans; - } -}; -``` - -```cpp -class Solution { -public: - int numMatchingSubseq(string s, vector& words) { - vector>> d(26); - for (int i = 0; i < words.size(); ++i) d[words[i][0] - 'a'].emplace(i, 0); - int ans = 0; - for (char& c : s) { - auto& q = d[c - 'a']; - for (int t = q.size(); t; --t) { - auto [i, j] = q.front(); - q.pop(); - if (++j == words[i].size()) - ++ans; - else - d[words[i][j] - 'a'].emplace(i, j); - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -267,52 +319,6 @@ public: }; ``` -### **Go** - -```go -func numMatchingSubseq(s string, words []string) (ans int) { - d := [26][]string{} - for _, w := range words { - d[w[0]-'a'] = append(d[w[0]-'a'], w) - } - for _, c := range s { - q := d[c-'a'] - d[c-'a'] = nil - for _, t := range q { - if len(t) == 1 { - ans++ - } else { - d[t[1]-'a'] = append(d[t[1]-'a'], t[1:]) - } - } - } - return -} -``` - -```go -func numMatchingSubseq(s string, words []string) (ans int) { - type pair struct{ i, j int } - d := [26][]pair{} - for i, w := range words { - d[w[0]-'a'] = append(d[w[0]-'a'], pair{i, 0}) - } - for _, c := range s { - q := d[c-'a'] - d[c-'a'] = nil - for _, p := range q { - i, j := p.i, p.j+1 - if j == len(words[i]) { - ans++ - } else { - d[words[i][j]-'a'] = append(d[words[i][j]-'a'], pair{i, j}) - } - } - } - return -} -``` - ```go func numMatchingSubseq(s string, words []string) (ans int) { d := [26][]int{} @@ -340,10 +346,6 @@ func numMatchingSubseq(s string, words []string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0793.Preimage Size of Factorial Zeroes Function/README.md b/solution/0700-0799/0793.Preimage Size of Factorial Zeroes Function/README.md index 0fa633e85c204..eac0f1892b7b4 100644 --- a/solution/0700-0799/0793.Preimage Size of Factorial Zeroes Function/README.md +++ b/solution/0700-0799/0793.Preimage Size of Factorial Zeroes Function/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 定义 $f(x)$ 为 $x!$ 末尾零的个数,那么 @@ -72,10 +70,6 @@ $$ -### **Python3** - - - ```python class Solution: def preimageSizeFZF(self, k: int) -> int: @@ -90,10 +84,6 @@ class Solution: return g(k + 1) - g(k) ``` -### **Java** - - - ```java class Solution { public int preimageSizeFZF(int k) { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func preimageSizeFZF(k int) int { f := func(x int) int { @@ -185,10 +171,6 @@ func preimageSizeFZF(k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0793.Preimage Size of Factorial Zeroes Function/README_EN.md b/solution/0700-0799/0793.Preimage Size of Factorial Zeroes Function/README_EN.md index bba364d71ff3c..f044d02978235 100644 --- a/solution/0700-0799/0793.Preimage Size of Factorial Zeroes Function/README_EN.md +++ b/solution/0700-0799/0793.Preimage Size of Factorial Zeroes Function/README_EN.md @@ -45,12 +45,10 @@ ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python class Solution: def preimageSizeFZF(self, k: int) -> int: @@ -65,8 +63,6 @@ class Solution: return g(k + 1) - g(k) ``` -### **Java** - ```java class Solution { public int preimageSizeFZF(int k) { @@ -95,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +122,6 @@ public: }; ``` -### **Go** - ```go func preimageSizeFZF(k int) int { f := func(x int) int { @@ -158,10 +150,6 @@ func preimageSizeFZF(k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0794.Valid Tic-Tac-Toe State/README.md b/solution/0700-0799/0794.Valid Tic-Tac-Toe State/README.md index dd01459093a88..39c8b222a03d7 100644 --- a/solution/0700-0799/0794.Valid Tic-Tac-Toe State/README.md +++ b/solution/0700-0799/0794.Valid Tic-Tac-Toe State/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:分类讨论** +### 方法一:分类讨论 我们先统计当前棋盘上 `'X'` 和 `'O'` 的数量,记为 $x$ 和 $o$。接下来,我们分情况讨论: @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def validTicTacToe(self, board: List[str]) -> bool: @@ -99,10 +93,6 @@ class Solution: return not (win('O') and x != o) ``` -### **Java** - - - ```java class Solution { private String[] board; @@ -148,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +164,6 @@ public: }; ``` -### **Go** - ```go func validTicTacToe(board []string) bool { var x, o int @@ -214,8 +200,6 @@ func validTicTacToe(board []string) bool { } ``` -### **JavaScript** - ```js /** * @param {string[]} board @@ -256,10 +240,6 @@ var validTicTacToe = function (board) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0794.Valid Tic-Tac-Toe State/README_EN.md b/solution/0700-0799/0794.Valid Tic-Tac-Toe State/README_EN.md index 7f42e7804bec3..0f923904cdb14 100644 --- a/solution/0700-0799/0794.Valid Tic-Tac-Toe State/README_EN.md +++ b/solution/0700-0799/0794.Valid Tic-Tac-Toe State/README_EN.md @@ -54,9 +54,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return not (win('O') and x != o) ``` -### **Java** - ```java class Solution { private String[] board; @@ -127,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +151,6 @@ public: }; ``` -### **Go** - ```go func validTicTacToe(board []string) bool { var x, o int @@ -193,8 +187,6 @@ func validTicTacToe(board []string) bool { } ``` -### **JavaScript** - ```js /** * @param {string[]} board @@ -235,10 +227,6 @@ var validTicTacToe = function (board) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/README.md b/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/README.md index 35baf6b8baf6a..df24a49ad61a9 100644 --- a/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/README.md +++ b/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:区间计数** +### 方法一:区间计数 题目要我们统计数组 `nums` 中,最大值在区间 $[left, right]$ 范围内的子数组个数。 @@ -59,22 +57,8 @@ $$ 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。 -**方法二:单调栈 + 枚举元素计算贡献** - -我们还可以枚举数组中每个元素 $nums[i]$ 作为子数组的最大值,然后统计以该元素为最大值的子数组的个数。问题转化为求出每个元素 $nums[i]$ 左侧第一个大于该元素的下标 $l[i]$,右侧第一个大于等于该元素的下标 $r[i]$,则以该元素为最大值的子数组的个数为 $(i - l[i]) \times (r[i] - i)$。 - -我们可以使用单调栈方便地求出 $l[i]$ 和 $r[i]$。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。 - -相似题目:[907. 子数组的最小值之和](/solution/0900-0999/0907.Sum%20of%20Subarray%20Minimums/README.md) - -### **Python3** - - - ```python class Solution: def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: @@ -88,6 +72,71 @@ class Solution: return f(right) - f(left - 1) ``` +```java +class Solution { + public int numSubarrayBoundedMax(int[] nums, int left, int right) { + return f(nums, right) - f(nums, left - 1); + } + + private int f(int[] nums, int x) { + int cnt = 0, t = 0; + for (int v : nums) { + t = v > x ? 0 : t + 1; + cnt += t; + } + return cnt; + } +} +``` + +```cpp +class Solution { +public: + int numSubarrayBoundedMax(vector& nums, int left, int right) { + auto f = [&](int x) { + int cnt = 0, t = 0; + for (int& v : nums) { + t = v > x ? 0 : t + 1; + cnt += t; + } + return cnt; + }; + return f(right) - f(left - 1); + } +}; +``` + +```go +func numSubarrayBoundedMax(nums []int, left int, right int) int { + f := func(x int) (cnt int) { + t := 0 + for _, v := range nums { + t++ + if v > x { + t = 0 + } + cnt += t + } + return + } + return f(right) - f(left-1) +} +``` + + + +### 方法二:单调栈 + 枚举元素计算贡献 + +我们还可以枚举数组中每个元素 $nums[i]$ 作为子数组的最大值,然后统计以该元素为最大值的子数组的个数。问题转化为求出每个元素 $nums[i]$ 左侧第一个大于该元素的下标 $l[i]$,右侧第一个大于等于该元素的下标 $r[i]$,则以该元素为最大值的子数组的个数为 $(i - l[i]) \times (r[i] - i)$。 + +我们可以使用单调栈方便地求出 $l[i]$ 和 $r[i]$。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。 + +相似题目:[907. 子数组的最小值之和](/solution/0900-0999/0907.Sum%20of%20Subarray%20Minimums/README.md) + + + ```python class Solution: def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: @@ -112,27 +161,6 @@ class Solution: ) ``` -### **Java** - - - -```java -class Solution { - public int numSubarrayBoundedMax(int[] nums, int left, int right) { - return f(nums, right) - f(nums, left - 1); - } - - private int f(int[] nums, int x) { - int cnt = 0, t = 0; - for (int v : nums) { - t = v > x ? 0 : t + 1; - cnt += t; - } - return cnt; - } -} -``` - ```java class Solution { public int numSubarrayBoundedMax(int[] nums, int left, int right) { @@ -174,25 +202,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numSubarrayBoundedMax(vector& nums, int left, int right) { - auto f = [&](int x) { - int cnt = 0, t = 0; - for (int& v : nums) { - t = v > x ? 0 : t + 1; - cnt += t; - } - return cnt; - }; - return f(right) - f(left - 1); - } -}; -``` - ```cpp class Solution { public: @@ -225,25 +234,6 @@ public: }; ``` -### **Go** - -```go -func numSubarrayBoundedMax(nums []int, left int, right int) int { - f := func(x int) (cnt int) { - t := 0 - for _, v := range nums { - t++ - if v > x { - t = 0 - } - cnt += t - } - return - } - return f(right) - f(left-1) -} -``` - ```go func numSubarrayBoundedMax(nums []int, left int, right int) (ans int) { n := len(nums) @@ -282,10 +272,6 @@ func numSubarrayBoundedMax(nums []int, left int, right int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/README_EN.md b/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/README_EN.md index 2bfc137181e77..844bc023be23d 100644 --- a/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/README_EN.md +++ b/solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,6 +52,63 @@ class Solution: return f(right) - f(left - 1) ``` +```java +class Solution { + public int numSubarrayBoundedMax(int[] nums, int left, int right) { + return f(nums, right) - f(nums, left - 1); + } + + private int f(int[] nums, int x) { + int cnt = 0, t = 0; + for (int v : nums) { + t = v > x ? 0 : t + 1; + cnt += t; + } + return cnt; + } +} +``` + +```cpp +class Solution { +public: + int numSubarrayBoundedMax(vector& nums, int left, int right) { + auto f = [&](int x) { + int cnt = 0, t = 0; + for (int& v : nums) { + t = v > x ? 0 : t + 1; + cnt += t; + } + return cnt; + }; + return f(right) - f(left - 1); + } +}; +``` + +```go +func numSubarrayBoundedMax(nums []int, left int, right int) int { + f := func(x int) (cnt int) { + t := 0 + for _, v := range nums { + t++ + if v > x { + t = 0 + } + cnt += t + } + return + } + return f(right) - f(left-1) +} +``` + + + +### Solution 2 + + + ```python class Solution: def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: @@ -76,25 +133,6 @@ class Solution: ) ``` -### **Java** - -```java -class Solution { - public int numSubarrayBoundedMax(int[] nums, int left, int right) { - return f(nums, right) - f(nums, left - 1); - } - - private int f(int[] nums, int x) { - int cnt = 0, t = 0; - for (int v : nums) { - t = v > x ? 0 : t + 1; - cnt += t; - } - return cnt; - } -} -``` - ```java class Solution { public int numSubarrayBoundedMax(int[] nums, int left, int right) { @@ -136,25 +174,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numSubarrayBoundedMax(vector& nums, int left, int right) { - auto f = [&](int x) { - int cnt = 0, t = 0; - for (int& v : nums) { - t = v > x ? 0 : t + 1; - cnt += t; - } - return cnt; - }; - return f(right) - f(left - 1); - } -}; -``` - ```cpp class Solution { public: @@ -187,25 +206,6 @@ public: }; ``` -### **Go** - -```go -func numSubarrayBoundedMax(nums []int, left int, right int) int { - f := func(x int) (cnt int) { - t := 0 - for _, v := range nums { - t++ - if v > x { - t = 0 - } - cnt += t - } - return - } - return f(right) - f(left-1) -} -``` - ```go func numSubarrayBoundedMax(nums []int, left int, right int) (ans int) { n := len(nums) @@ -244,10 +244,6 @@ func numSubarrayBoundedMax(nums []int, left int, right int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0796.Rotate String/README.md b/solution/0700-0799/0796.Rotate String/README.md index d7a5cd540d8e6..347edefb6eb00 100644 --- a/solution/0700-0799/0796.Rotate String/README.md +++ b/solution/0700-0799/0796.Rotate String/README.md @@ -41,24 +41,16 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def rotateString(self, s: str, goal: str) -> bool: return len(s) == len(goal) and goal in s + s ``` -### **Java** - - - ```java class Solution { public boolean rotateString(String s, String goal) { @@ -67,8 +59,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -78,24 +68,18 @@ public: }; ``` -### **Go** - ```go func rotateString(s string, goal string) bool { return len(s) == len(goal) && strings.Contains(s+s, goal) } ``` -### **TypeScript** - ```ts function rotateString(s: string, goal: string): boolean { return s.length === goal.length && (goal + goal).includes(s); } ``` -### **Rust** - ```rust impl Solution { pub fn rotate_string(s: String, goal: String) -> bool { @@ -104,8 +88,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -119,10 +101,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0796.Rotate String/README_EN.md b/solution/0700-0799/0796.Rotate String/README_EN.md index dc5cc4361b826..c37784ee2a836 100644 --- a/solution/0700-0799/0796.Rotate String/README_EN.md +++ b/solution/0700-0799/0796.Rotate String/README_EN.md @@ -30,9 +30,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -40,8 +40,6 @@ class Solution: return len(s) == len(goal) and goal in s + s ``` -### **Java** - ```java class Solution { public boolean rotateString(String s, String goal) { @@ -50,8 +48,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -61,24 +57,18 @@ public: }; ``` -### **Go** - ```go func rotateString(s string, goal string) bool { return len(s) == len(goal) && strings.Contains(s+s, goal) } ``` -### **TypeScript** - ```ts function rotateString(s: string, goal: string): boolean { return s.length === goal.length && (goal + goal).includes(s); } ``` -### **Rust** - ```rust impl Solution { pub fn rotate_string(s: String, goal: String) -> bool { @@ -87,8 +77,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -102,10 +90,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0797.All Paths From Source to Target/README.md b/solution/0700-0799/0797.All Paths From Source to Target/README.md index af7948935127a..062cec7434ece 100644 --- a/solution/0700-0799/0797.All Paths From Source to Target/README.md +++ b/solution/0700-0799/0797.All Paths From Source to Target/README.md @@ -48,18 +48,10 @@ ## 解法 - - -因为图中不存在环,所以直接用 DFS 或 BFS 遍历即可 +### 方法一 -### **Python3** - - - -BFS: - ```python class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: @@ -77,31 +69,6 @@ class Solution: return ans ``` -DFS: - -```python -class Solution: - def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: - def dfs(t): - if t[-1] == len(graph) - 1: - ans.append(t[:]) - return - for v in graph[t[-1]]: - t.append(v) - dfs(t) - t.pop() - - ans = [] - dfs([0]) - return ans -``` - -### **Java** - - - -BFS: - ```java class Solution { public List> allPathsSourceTarget(int[][] graph) { @@ -127,41 +94,6 @@ class Solution { } ``` -DFS: - -```java -class Solution { - private List> ans; - private int[][] graph; - - public List> allPathsSourceTarget(int[][] graph) { - ans = new ArrayList<>(); - this.graph = graph; - List t = new ArrayList<>(); - t.add(0); - dfs(t); - return ans; - } - - private void dfs(List t) { - int cur = t.get(t.size() - 1); - if (cur == graph.length - 1) { - ans.add(new ArrayList<>(t)); - return; - } - for (int v : graph[cur]) { - t.add(v); - dfs(t); - t.remove(t.size() - 1); - } - } -} -``` - -### **C++** - -DFS: - ```cpp class Solution { public: @@ -190,10 +122,6 @@ public: }; ``` -DFS: - -### **Go** - ```go func allPathsSourceTarget(graph [][]int) [][]int { var path []int @@ -218,7 +146,26 @@ func allPathsSourceTarget(graph [][]int) [][]int { } ``` -### **JavaScript** +```rust +impl Solution { + fn dfs(i: usize, path: &mut Vec, res: &mut Vec>, graph: &Vec>) { + path.push(i as i32); + if i == graph.len() - 1 { + res.push(path.clone()); + } + for j in graph[i].iter() { + Self::dfs(*j as usize, path, res, graph); + } + path.pop(); + } + + pub fn all_paths_source_target(graph: Vec>) -> Vec> { + let mut res = Vec::new(); + Self::dfs(0, &mut vec![], &mut res, &graph); + res + } +} +``` ```js /** @@ -247,33 +194,58 @@ var allPathsSourceTarget = function (graph) { }; ``` -### **Rust** + -```rust -impl Solution { - fn dfs(i: usize, path: &mut Vec, res: &mut Vec>, graph: &Vec>) { - path.push(i as i32); - if i == graph.len() - 1 { - res.push(path.clone()); - } - for j in graph[i].iter() { - Self::dfs(*j as usize, path, res, graph); - } - path.pop(); - } +### 方法二 - pub fn all_paths_source_target(graph: Vec>) -> Vec> { - let mut res = Vec::new(); - Self::dfs(0, &mut vec![], &mut res, &graph); - res - } -} -``` + -### **...** +```python +class Solution: + def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: + def dfs(t): + if t[-1] == len(graph) - 1: + ans.append(t[:]) + return + for v in graph[t[-1]]: + t.append(v) + dfs(t) + t.pop() + ans = [] + dfs([0]) + return ans ``` +```java +class Solution { + private List> ans; + private int[][] graph; + + public List> allPathsSourceTarget(int[][] graph) { + ans = new ArrayList<>(); + this.graph = graph; + List t = new ArrayList<>(); + t.add(0); + dfs(t); + return ans; + } + + private void dfs(List t) { + int cur = t.get(t.size() - 1); + if (cur == graph.length - 1) { + ans.add(new ArrayList<>(t)); + return; + } + for (int v : graph[cur]) { + t.add(v); + dfs(t); + t.remove(t.size() - 1); + } + } +} ``` + + diff --git a/solution/0700-0799/0797.All Paths From Source to Target/README_EN.md b/solution/0700-0799/0797.All Paths From Source to Target/README_EN.md index 3d97022674661..505430c45cbe2 100644 --- a/solution/0700-0799/0797.All Paths From Source to Target/README_EN.md +++ b/solution/0700-0799/0797.All Paths From Source to Target/README_EN.md @@ -38,14 +38,10 @@ ## Solutions -Since there is no ring in the graph, you can simply use DFS or BFS to traverse it. +### Solution 1 -### **Python3** - -BFS. - ```python class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: @@ -63,29 +59,6 @@ class Solution: return ans ``` -DFS: - -```python -class Solution: - def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: - def dfs(t): - if t[-1] == len(graph) - 1: - ans.append(t[:]) - return - for v in graph[t[-1]]: - t.append(v) - dfs(t) - t.pop() - - ans = [] - dfs([0]) - return ans -``` - -### **Java** - -BFS: - ```java class Solution { public List> allPathsSourceTarget(int[][] graph) { @@ -111,41 +84,6 @@ class Solution { } ``` -DFS: - -```java -class Solution { - private List> ans; - private int[][] graph; - - public List> allPathsSourceTarget(int[][] graph) { - ans = new ArrayList<>(); - this.graph = graph; - List t = new ArrayList<>(); - t.add(0); - dfs(t); - return ans; - } - - private void dfs(List t) { - int cur = t.get(t.size() - 1); - if (cur == graph.length - 1) { - ans.add(new ArrayList<>(t)); - return; - } - for (int v : graph[cur]) { - t.add(v); - dfs(t); - t.remove(t.size() - 1); - } - } -} -``` - -### **C++** - -DFS: - ```cpp class Solution { public: @@ -174,10 +112,6 @@ public: }; ``` -### **Go** - -DFS: - ```go func allPathsSourceTarget(graph [][]int) [][]int { var path []int @@ -202,7 +136,26 @@ func allPathsSourceTarget(graph [][]int) [][]int { } ``` -### **JavaScript** +```rust +impl Solution { + fn dfs(i: usize, path: &mut Vec, res: &mut Vec>, graph: &Vec>) { + path.push(i as i32); + if i == graph.len() - 1 { + res.push(path.clone()); + } + for j in graph[i].iter() { + Self::dfs(*j as usize, path, res, graph); + } + path.pop(); + } + + pub fn all_paths_source_target(graph: Vec>) -> Vec> { + let mut res = Vec::new(); + Self::dfs(0, &mut vec![], &mut res, &graph); + res + } +} +``` ```js /** @@ -231,33 +184,58 @@ var allPathsSourceTarget = function (graph) { }; ``` -### **Rust** + -```rust -impl Solution { - fn dfs(i: usize, path: &mut Vec, res: &mut Vec>, graph: &Vec>) { - path.push(i as i32); - if i == graph.len() - 1 { - res.push(path.clone()); - } - for j in graph[i].iter() { - Self::dfs(*j as usize, path, res, graph); - } - path.pop(); - } +### Solution 2 - pub fn all_paths_source_target(graph: Vec>) -> Vec> { - let mut res = Vec::new(); - Self::dfs(0, &mut vec![], &mut res, &graph); - res - } -} -``` + -### **...** +```python +class Solution: + def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: + def dfs(t): + if t[-1] == len(graph) - 1: + ans.append(t[:]) + return + for v in graph[t[-1]]: + t.append(v) + dfs(t) + t.pop() + ans = [] + dfs([0]) + return ans ``` +```java +class Solution { + private List> ans; + private int[][] graph; + + public List> allPathsSourceTarget(int[][] graph) { + ans = new ArrayList<>(); + this.graph = graph; + List t = new ArrayList<>(); + t.add(0); + dfs(t); + return ans; + } + + private void dfs(List t) { + int cur = t.get(t.size() - 1); + if (cur == graph.length - 1) { + ans.add(new ArrayList<>(t)); + return; + } + for (int v : graph[cur]) { + t.add(v); + dfs(t); + t.remove(t.size() - 1); + } + } +} ``` + + diff --git a/solution/0700-0799/0798.Smallest Rotation with Highest Score/README.md b/solution/0700-0799/0798.Smallest Rotation with Highest Score/README.md index df8b719704daa..2753e6f7913a3 100644 --- a/solution/0700-0799/0798.Smallest Rotation with Highest Score/README.md +++ b/solution/0700-0799/0798.Smallest Rotation with Highest Score/README.md @@ -51,18 +51,12 @@ nums 无论怎么变化总是有 3 分。 ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 对于每个数,都有一个固定的 k 生效区间。我们先利用差分,预处理每个数的 k 生效区间。有最多个数能覆盖到的 k 即是答案。 -### **Python3** - - - ```python class Solution: def bestRotation(self, nums: List[int]) -> int: @@ -82,10 +76,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int bestRotation(int[] nums) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func bestRotation(nums []int) int { n := len(nums) @@ -163,10 +149,6 @@ func bestRotation(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0798.Smallest Rotation with Highest Score/README_EN.md b/solution/0700-0799/0798.Smallest Rotation with Highest Score/README_EN.md index 546b05698e0f1..ed021ad3999c6 100644 --- a/solution/0700-0799/0798.Smallest Rotation with Highest Score/README_EN.md +++ b/solution/0700-0799/0798.Smallest Rotation with Highest Score/README_EN.md @@ -46,9 +46,9 @@ So we will choose the smallest k, which is 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int bestRotation(int[] nums) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +121,6 @@ public: }; ``` -### **Go** - ```go func bestRotation(nums []int) int { n := len(nums) @@ -148,10 +142,6 @@ func bestRotation(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0700-0799/0799.Champagne Tower/README.md b/solution/0700-0799/0799.Champagne Tower/README.md index 8b21bc4cede4d..112c2b72dc842 100644 --- a/solution/0700-0799/0799.Champagne Tower/README.md +++ b/solution/0700-0799/0799.Champagne Tower/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们直接模拟倒香槟的过程。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: @@ -87,25 +81,6 @@ class Solution: return f[query_row][query_glass] ``` -```python -class Solution: - def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: - f = [poured] - for i in range(1, query_row + 1): - g = [0] * (i + 1) - for j, v in enumerate(f): - if v > 1: - half = (v - 1) / 2 - g[j] += half - g[j + 1] += half - f = g - return min(1, f[query_glass]) -``` - -### **Java** - - - ```java class Solution { public double champagneTower(int poured, int query_row, int query_glass) { @@ -126,28 +101,6 @@ class Solution { } ``` -```java -class Solution { - public double champagneTower(int poured, int query_row, int query_glass) { - double[] f = {poured}; - for (int i = 1; i <= query_row; ++i) { - double[] g = new double[i + 1]; - for (int j = 0; j < i; ++j) { - if (f[j] > 1) { - double half = (f[j] - 1) / 2.0; - g[j] += half; - g[j + 1] += half; - } - } - f = g; - } - return Math.min(1, f[query_glass]); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -169,30 +122,6 @@ public: }; ``` -```cpp -class Solution { -public: - double champagneTower(int poured, int query_row, int query_glass) { - double f[101] = {(double) poured}; - double g[101]; - for (int i = 1; i <= query_row; ++i) { - memset(g, 0, sizeof g); - for (int j = 0; j < i; ++j) { - if (f[j] > 1) { - double half = (f[j] - 1) / 2.0; - g[j] += half; - g[j + 1] += half; - } - } - memcpy(f, g, sizeof g); - } - return min(1.0, f[query_glass]); - } -}; -``` - -### **Go** - ```go func champagneTower(poured int, query_row int, query_glass int) float64 { f := [101][101]float64{} @@ -211,26 +140,6 @@ func champagneTower(poured int, query_row int, query_glass int) float64 { } ``` -```go -func champagneTower(poured int, query_row int, query_glass int) float64 { - f := []float64{float64(poured)} - for i := 1; i <= query_row; i++ { - g := make([]float64, i+1) - for j, v := range f { - if v > 1 { - half := (v - 1) / 2.0 - g[j] += half - g[j+1] += half - } - } - f = g - } - return math.Min(1, f[query_glass]) -} -``` - -### **TypeScipt** - ```ts function champagneTower(poured: number, query_row: number, query_glass: number): number { let row = [poured]; @@ -248,8 +157,6 @@ function champagneTower(poured: number, query_row: number, query_glass: number): } ``` -### **Rust** - ```rust impl Solution { pub fn champagne_tower(poured: i32, query_row: i32, query_glass: i32) -> f64 { @@ -271,10 +178,87 @@ impl Solution { } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: + f = [poured] + for i in range(1, query_row + 1): + g = [0] * (i + 1) + for j, v in enumerate(f): + if v > 1: + half = (v - 1) / 2 + g[j] += half + g[j + 1] += half + f = g + return min(1, f[query_glass]) +``` + +```java +class Solution { + public double champagneTower(int poured, int query_row, int query_glass) { + double[] f = {poured}; + for (int i = 1; i <= query_row; ++i) { + double[] g = new double[i + 1]; + for (int j = 0; j < i; ++j) { + if (f[j] > 1) { + double half = (f[j] - 1) / 2.0; + g[j] += half; + g[j + 1] += half; + } + } + f = g; + } + return Math.min(1, f[query_glass]); + } +} +``` +```cpp +class Solution { +public: + double champagneTower(int poured, int query_row, int query_glass) { + double f[101] = {(double) poured}; + double g[101]; + for (int i = 1; i <= query_row; ++i) { + memset(g, 0, sizeof g); + for (int j = 0; j < i; ++j) { + if (f[j] > 1) { + double half = (f[j] - 1) / 2.0; + g[j] += half; + g[j + 1] += half; + } + } + memcpy(f, g, sizeof g); + } + return min(1.0, f[query_glass]); + } +}; ``` +```go +func champagneTower(poured int, query_row int, query_glass int) float64 { + f := []float64{float64(poured)} + for i := 1; i <= query_row; i++ { + g := make([]float64, i+1) + for j, v := range f { + if v > 1 { + half := (v - 1) / 2.0 + g[j] += half + g[j+1] += half + } + } + f = g + } + return math.Min(1, f[query_glass]) +} ``` + + diff --git a/solution/0700-0799/0799.Champagne Tower/README_EN.md b/solution/0700-0799/0799.Champagne Tower/README_EN.md index 9e0bfa94a95f0..24cfbee2fd0ec 100644 --- a/solution/0700-0799/0799.Champagne Tower/README_EN.md +++ b/solution/0700-0799/0799.Champagne Tower/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,23 +67,6 @@ class Solution: return f[query_row][query_glass] ``` -```python -class Solution: - def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: - f = [poured] - for i in range(1, query_row + 1): - g = [0] * (i + 1) - for j, v in enumerate(f): - if v > 1: - half = (v - 1) / 2 - g[j] += half - g[j + 1] += half - f = g - return min(1, f[query_glass]) -``` - -### **Java** - ```java class Solution { public double champagneTower(int poured, int query_row, int query_glass) { @@ -104,28 +87,6 @@ class Solution { } ``` -```java -class Solution { - public double champagneTower(int poured, int query_row, int query_glass) { - double[] f = {poured}; - for (int i = 1; i <= query_row; ++i) { - double[] g = new double[i + 1]; - for (int j = 0; j < i; ++j) { - if (f[j] > 1) { - double half = (f[j] - 1) / 2.0; - g[j] += half; - g[j + 1] += half; - } - } - f = g; - } - return Math.min(1, f[query_glass]); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -147,30 +108,6 @@ public: }; ``` -```cpp -class Solution { -public: - double champagneTower(int poured, int query_row, int query_glass) { - double f[101] = {(double) poured}; - double g[101]; - for (int i = 1; i <= query_row; ++i) { - memset(g, 0, sizeof g); - for (int j = 0; j < i; ++j) { - if (f[j] > 1) { - double half = (f[j] - 1) / 2.0; - g[j] += half; - g[j + 1] += half; - } - } - memcpy(f, g, sizeof g); - } - return min(1.0, f[query_glass]); - } -}; -``` - -### **Go** - ```go func champagneTower(poured int, query_row int, query_glass int) float64 { f := [101][101]float64{} @@ -189,26 +126,6 @@ func champagneTower(poured int, query_row int, query_glass int) float64 { } ``` -```go -func champagneTower(poured int, query_row int, query_glass int) float64 { - f := []float64{float64(poured)} - for i := 1; i <= query_row; i++ { - g := make([]float64, i+1) - for j, v := range f { - if v > 1 { - half := (v - 1) / 2.0 - g[j] += half - g[j+1] += half - } - } - f = g - } - return math.Min(1, f[query_glass]) -} -``` - -### **TypeScipt** - ```ts function champagneTower(poured: number, query_row: number, query_glass: number): number { let row = [poured]; @@ -226,8 +143,6 @@ function champagneTower(poured: number, query_row: number, query_glass: number): } ``` -### **Rust** - ```rust impl Solution { pub fn champagne_tower(poured: i32, query_row: i32, query_glass: i32) -> f64 { @@ -249,10 +164,87 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: + f = [poured] + for i in range(1, query_row + 1): + g = [0] * (i + 1) + for j, v in enumerate(f): + if v > 1: + half = (v - 1) / 2 + g[j] += half + g[j + 1] += half + f = g + return min(1, f[query_glass]) ``` +```java +class Solution { + public double champagneTower(int poured, int query_row, int query_glass) { + double[] f = {poured}; + for (int i = 1; i <= query_row; ++i) { + double[] g = new double[i + 1]; + for (int j = 0; j < i; ++j) { + if (f[j] > 1) { + double half = (f[j] - 1) / 2.0; + g[j] += half; + g[j + 1] += half; + } + } + f = g; + } + return Math.min(1, f[query_glass]); + } +} +``` + +```cpp +class Solution { +public: + double champagneTower(int poured, int query_row, int query_glass) { + double f[101] = {(double) poured}; + double g[101]; + for (int i = 1; i <= query_row; ++i) { + memset(g, 0, sizeof g); + for (int j = 0; j < i; ++j) { + if (f[j] > 1) { + double half = (f[j] - 1) / 2.0; + g[j] += half; + g[j + 1] += half; + } + } + memcpy(f, g, sizeof g); + } + return min(1.0, f[query_glass]); + } +}; +``` + +```go +func champagneTower(poured int, query_row int, query_glass int) float64 { + f := []float64{float64(poured)} + for i := 1; i <= query_row; i++ { + g := make([]float64, i+1) + for j, v := range f { + if v > 1 { + half := (v - 1) / 2.0 + g[j] += half + g[j+1] += half + } + } + f = g + } + return math.Min(1, f[query_glass]) +} ``` + + diff --git a/solution/0800-0899/0800.Similar RGB Color/README.md b/solution/0800-0899/0800.Similar RGB Color/README.md index 5947c56f8c6b8..73766fb41c9b1 100644 --- a/solution/0800-0899/0800.Similar RGB Color/README.md +++ b/solution/0800-0899/0800.Similar RGB Color/README.md @@ -49,14 +49,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def similarRGB(self, color: str) -> str: @@ -70,10 +66,6 @@ class Solution: return f'#{f(a)}{f(b)}{f(c)}' ``` -### **Java** - - - ```java class Solution { public String similarRGB(String color) { @@ -89,8 +81,6 @@ class Solution { } ``` -### **Go** - ```go func similarRGB(color string) string { f := func(x string) string { @@ -108,10 +98,6 @@ func similarRGB(color string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0800.Similar RGB Color/README_EN.md b/solution/0800-0899/0800.Similar RGB Color/README_EN.md index c991997e98967..fec9ae721b9c7 100644 --- a/solution/0800-0899/0800.Similar RGB Color/README_EN.md +++ b/solution/0800-0899/0800.Similar RGB Color/README_EN.md @@ -45,9 +45,9 @@ This is the highest among any shorthand color. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return f'#{f(a)}{f(b)}{f(c)}' ``` -### **Java** - ```java class Solution { public String similarRGB(String color) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **Go** - ```go func similarRGB(color string) string { f := func(x string) string { @@ -98,10 +94,6 @@ func similarRGB(color string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0801.Minimum Swaps To Make Sequences Increasing/README.md b/solution/0800-0899/0801.Minimum Swaps To Make Sequences Increasing/README.md index ff856db1304c0..a4de8b802d5b9 100644 --- a/solution/0800-0899/0801.Minimum Swaps To Make Sequences Increasing/README.md +++ b/solution/0800-0899/0801.Minimum Swaps To Make Sequences Increasing/README.md @@ -53,9 +53,7 @@ A = [1, 3, 5, 7] , B = [1, 2, 3, 4] ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 定义 $a$, $b$ 分别表示使得下标 $[0..i]$ 的元素序列严格递增,且第 $i$ 个元素不交换、交换的最小交换次数。下标从 $0$ 开始。 @@ -73,10 +71,6 @@ A = [1, 3, 5, 7] , B = [1, 2, 3, 4] -### **Python3** - - - ```python class Solution: def minSwap(self, nums1: List[int], nums2: List[int]) -> int: @@ -92,10 +86,6 @@ class Solution: return min(a, b) ``` -### **Java** - - - ```java class Solution { public int minSwap(int[] nums1, int[] nums2) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func minSwap(nums1 []int, nums2 []int) int { a, b, n := 0, 1, len(nums1) @@ -163,10 +149,6 @@ func minSwap(nums1 []int, nums2 []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0801.Minimum Swaps To Make Sequences Increasing/README_EN.md b/solution/0800-0899/0801.Minimum Swaps To Make Sequences Increasing/README_EN.md index b3cd91651527d..64ae5c5b1e2a5 100644 --- a/solution/0800-0899/0801.Minimum Swaps To Make Sequences Increasing/README_EN.md +++ b/solution/0800-0899/0801.Minimum Swaps To Make Sequences Increasing/README_EN.md @@ -44,9 +44,9 @@ which are both strictly increasing. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return min(a, b) ``` -### **Java** - ```java class Solution { public int minSwap(int[] nums1, int[] nums2) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +107,6 @@ public: }; ``` -### **Go** - ```go func minSwap(nums1 []int, nums2 []int) int { a, b, n := 0, 1, len(nums1) @@ -132,10 +126,6 @@ func minSwap(nums1 []int, nums2 []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0802.Find Eventual Safe States/README.md b/solution/0800-0899/0802.Find Eventual Safe States/README.md index aaf203d26081d..5fbdbf9b111b4 100644 --- a/solution/0800-0899/0802.Find Eventual Safe States/README.md +++ b/solution/0800-0899/0802.Find Eventual Safe States/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:拓扑排序** +### 方法一:拓扑排序 出度为零的点是安全的,如果一个点**只能**到达安全的点,那么它同样是安全的,所以问题转换成了拓扑排序。 @@ -61,20 +59,8 @@ 时间复杂度 $O(n+m)$,其中 $n$ 表示图中的点数,$m$ 表示图中的边数。 -**方法二:DFS + 三色标记法** - -若起始节点位于一个环内,或者能到达一个环,则该节点不是安全的。否则,该节点是安全的。 - -- 白色(用 0 表示):该节点尚未被访问; -- 灰色(用 1 表示):该节点位于递归栈中,或者在某个环上; -- 黑色(用 2 表示):该节点搜索完毕,是一个安全节点。 - -### **Python3** - - - ```python class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: @@ -94,28 +80,6 @@ class Solution: return [i for i, v in enumerate(indeg) if v == 0] ``` -```python -class Solution: - def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: - def dfs(i): - if color[i]: - return color[i] == 2 - color[i] = 1 - for j in graph[i]: - if not dfs(j): - return False - color[i] = 2 - return True - - n = len(graph) - color = [0] * n - return [i for i in range(n) if dfs(i)] -``` - -### **Java** - - - ```java class Solution { public List eventualSafeNodes(int[][] graph) { @@ -152,42 +116,33 @@ class Solution { } ``` -```java +```cpp class Solution { - private int[] color; - private int[][] g; - - public List eventualSafeNodes(int[][] graph) { - int n = graph.length; - color = new int[n]; - g = graph; - List ans = new ArrayList<>(); +public: + vector eventualSafeNodes(vector>& graph) { + int n = graph.size(); + vector indeg(n); + vector> rg(n); + queue q; for (int i = 0; i < n; ++i) { - if (dfs(i)) { - ans.add(i); - } - } - return ans; - } - - private boolean dfs(int i) { - if (color[i] > 0) { - return color[i] == 2; + for (int j : graph[i]) rg[j].push_back(i); + indeg[i] = graph[i].size(); + if (indeg[i] == 0) q.push(i); } - color[i] = 1; - for (int j : g[i]) { - if (!dfs(j)) { - return false; - } + while (!q.empty()) { + int i = q.front(); + q.pop(); + for (int j : rg[i]) + if (--indeg[j] == 0) q.push(j); } - color[i] = 2; - return true; + vector ans; + for (int i = 0; i < n; ++i) + if (indeg[i] == 0) ans.push_back(i); + return ans; } -} +}; ``` -### **Go** - ```go func eventualSafeNodes(graph [][]int) []int { n := len(graph) @@ -223,90 +178,6 @@ func eventualSafeNodes(graph [][]int) []int { } ``` -```go -func eventualSafeNodes(graph [][]int) []int { - n := len(graph) - color := make([]int, n) - var dfs func(int) bool - dfs = func(i int) bool { - if color[i] > 0 { - return color[i] == 2 - } - color[i] = 1 - for _, j := range graph[i] { - if !dfs(j) { - return false - } - } - color[i] = 2 - return true - } - ans := []int{} - for i := range graph { - if dfs(i) { - ans = append(ans, i) - } - } - return ans -} -``` - -### **C++** - -```cpp -class Solution { -public: - vector eventualSafeNodes(vector>& graph) { - int n = graph.size(); - vector indeg(n); - vector> rg(n); - queue q; - for (int i = 0; i < n; ++i) { - for (int j : graph[i]) rg[j].push_back(i); - indeg[i] = graph[i].size(); - if (indeg[i] == 0) q.push(i); - } - while (!q.empty()) { - int i = q.front(); - q.pop(); - for (int j : rg[i]) - if (--indeg[j] == 0) q.push(j); - } - vector ans; - for (int i = 0; i < n; ++i) - if (indeg[i] == 0) ans.push_back(i); - return ans; - } -}; -``` - -```cpp -class Solution { -public: - vector color; - - vector eventualSafeNodes(vector>& graph) { - int n = graph.size(); - color.assign(n, 0); - vector ans; - for (int i = 0; i < n; ++i) - if (dfs(i, graph)) ans.push_back(i); - return ans; - } - - bool dfs(int i, vector>& g) { - if (color[i]) return color[i] == 2; - color[i] = 1; - for (int j : g[i]) - if (!dfs(j, g)) return false; - color[i] = 2; - return true; - } -}; -``` - -### **JavaScript** - ```js /** * @param {number[][]} graph @@ -344,6 +215,123 @@ var eventualSafeNodes = function (graph) { }; ``` + + +### 方法二:DFS + 三色标记法 + +若起始节点位于一个环内,或者能到达一个环,则该节点不是安全的。否则,该节点是安全的。 + +- 白色(用 0 表示):该节点尚未被访问; +- 灰色(用 1 表示):该节点位于递归栈中,或者在某个环上; +- 黑色(用 2 表示):该节点搜索完毕,是一个安全节点。 + + + +```python +class Solution: + def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: + def dfs(i): + if color[i]: + return color[i] == 2 + color[i] = 1 + for j in graph[i]: + if not dfs(j): + return False + color[i] = 2 + return True + + n = len(graph) + color = [0] * n + return [i for i in range(n) if dfs(i)] +``` + +```java +class Solution { + private int[] color; + private int[][] g; + + public List eventualSafeNodes(int[][] graph) { + int n = graph.length; + color = new int[n]; + g = graph; + List ans = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + if (dfs(i)) { + ans.add(i); + } + } + return ans; + } + + private boolean dfs(int i) { + if (color[i] > 0) { + return color[i] == 2; + } + color[i] = 1; + for (int j : g[i]) { + if (!dfs(j)) { + return false; + } + } + color[i] = 2; + return true; + } +} +``` + +```cpp +class Solution { +public: + vector color; + + vector eventualSafeNodes(vector>& graph) { + int n = graph.size(); + color.assign(n, 0); + vector ans; + for (int i = 0; i < n; ++i) + if (dfs(i, graph)) ans.push_back(i); + return ans; + } + + bool dfs(int i, vector>& g) { + if (color[i]) return color[i] == 2; + color[i] = 1; + for (int j : g[i]) + if (!dfs(j, g)) return false; + color[i] = 2; + return true; + } +}; +``` + +```go +func eventualSafeNodes(graph [][]int) []int { + n := len(graph) + color := make([]int, n) + var dfs func(int) bool + dfs = func(i int) bool { + if color[i] > 0 { + return color[i] == 2 + } + color[i] = 1 + for _, j := range graph[i] { + if !dfs(j) { + return false + } + } + color[i] = 2 + return true + } + ans := []int{} + for i := range graph { + if dfs(i) { + ans = append(ans, i) + } + } + return ans +} +``` + ```js /** * @param {number[][]} graph @@ -375,10 +363,6 @@ var eventualSafeNodes = function (graph) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0802.Find Eventual Safe States/README_EN.md b/solution/0800-0899/0802.Find Eventual Safe States/README_EN.md index 888c8c1a83eeb..c193593fc75d4 100644 --- a/solution/0800-0899/0802.Find Eventual Safe States/README_EN.md +++ b/solution/0800-0899/0802.Find Eventual Safe States/README_EN.md @@ -44,12 +44,10 @@ Only node 4 is a terminal node, and every path starting at node 4 leads to node ## Solutions -The point with zero out-degree is safe, and if a point can **only** reach the safe point, then it is also safe, so the problem can be converted to topological sorting. +### Solution 1 -### **Python3** - ```python class Solution: def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: @@ -69,26 +67,6 @@ class Solution: return [i for i, v in enumerate(indeg) if v == 0] ``` -```python -class Solution: - def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: - def dfs(i): - if color[i]: - return color[i] == 2 - color[i] = 1 - for j in graph[i]: - if not dfs(j): - return False - color[i] = 2 - return True - - n = len(graph) - color = [0] * n - return [i for i in range(n) if dfs(i)] -``` - -### **Java** - ```java class Solution { public List eventualSafeNodes(int[][] graph) { @@ -125,42 +103,33 @@ class Solution { } ``` -```java +```cpp class Solution { - private int[] color; - private int[][] g; - - public List eventualSafeNodes(int[][] graph) { - int n = graph.length; - color = new int[n]; - g = graph; - List ans = new ArrayList<>(); +public: + vector eventualSafeNodes(vector>& graph) { + int n = graph.size(); + vector indeg(n); + vector> rg(n); + queue q; for (int i = 0; i < n; ++i) { - if (dfs(i)) { - ans.add(i); - } - } - return ans; - } - - private boolean dfs(int i) { - if (color[i] > 0) { - return color[i] == 2; + for (int j : graph[i]) rg[j].push_back(i); + indeg[i] = graph[i].size(); + if (indeg[i] == 0) q.push(i); } - color[i] = 1; - for (int j : g[i]) { - if (!dfs(j)) { - return false; - } + while (!q.empty()) { + int i = q.front(); + q.pop(); + for (int j : rg[i]) + if (--indeg[j] == 0) q.push(j); } - color[i] = 2; - return true; + vector ans; + for (int i = 0; i < n; ++i) + if (indeg[i] == 0) ans.push_back(i); + return ans; } -} +}; ``` -### **Go** - ```go func eventualSafeNodes(graph [][]int) []int { n := len(graph) @@ -196,90 +165,6 @@ func eventualSafeNodes(graph [][]int) []int { } ``` -```go -func eventualSafeNodes(graph [][]int) []int { - n := len(graph) - color := make([]int, n) - var dfs func(int) bool - dfs = func(i int) bool { - if color[i] > 0 { - return color[i] == 2 - } - color[i] = 1 - for _, j := range graph[i] { - if !dfs(j) { - return false - } - } - color[i] = 2 - return true - } - ans := []int{} - for i := range graph { - if dfs(i) { - ans = append(ans, i) - } - } - return ans -} -``` - -### **C++** - -```cpp -class Solution { -public: - vector eventualSafeNodes(vector>& graph) { - int n = graph.size(); - vector indeg(n); - vector> rg(n); - queue q; - for (int i = 0; i < n; ++i) { - for (int j : graph[i]) rg[j].push_back(i); - indeg[i] = graph[i].size(); - if (indeg[i] == 0) q.push(i); - } - while (!q.empty()) { - int i = q.front(); - q.pop(); - for (int j : rg[i]) - if (--indeg[j] == 0) q.push(j); - } - vector ans; - for (int i = 0; i < n; ++i) - if (indeg[i] == 0) ans.push_back(i); - return ans; - } -}; -``` - -```cpp -class Solution { -public: - vector color; - - vector eventualSafeNodes(vector>& graph) { - int n = graph.size(); - color.assign(n, 0); - vector ans; - for (int i = 0; i < n; ++i) - if (dfs(i, graph)) ans.push_back(i); - return ans; - } - - bool dfs(int i, vector>& g) { - if (color[i]) return color[i] == 2; - color[i] = 1; - for (int j : g[i]) - if (!dfs(j, g)) return false; - color[i] = 2; - return true; - } -}; -``` - -### **JavaScript** - ```js /** * @param {number[][]} graph @@ -317,6 +202,117 @@ var eventualSafeNodes = function (graph) { }; ``` + + +### Solution 2 + + + +```python +class Solution: + def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]: + def dfs(i): + if color[i]: + return color[i] == 2 + color[i] = 1 + for j in graph[i]: + if not dfs(j): + return False + color[i] = 2 + return True + + n = len(graph) + color = [0] * n + return [i for i in range(n) if dfs(i)] +``` + +```java +class Solution { + private int[] color; + private int[][] g; + + public List eventualSafeNodes(int[][] graph) { + int n = graph.length; + color = new int[n]; + g = graph; + List ans = new ArrayList<>(); + for (int i = 0; i < n; ++i) { + if (dfs(i)) { + ans.add(i); + } + } + return ans; + } + + private boolean dfs(int i) { + if (color[i] > 0) { + return color[i] == 2; + } + color[i] = 1; + for (int j : g[i]) { + if (!dfs(j)) { + return false; + } + } + color[i] = 2; + return true; + } +} +``` + +```cpp +class Solution { +public: + vector color; + + vector eventualSafeNodes(vector>& graph) { + int n = graph.size(); + color.assign(n, 0); + vector ans; + for (int i = 0; i < n; ++i) + if (dfs(i, graph)) ans.push_back(i); + return ans; + } + + bool dfs(int i, vector>& g) { + if (color[i]) return color[i] == 2; + color[i] = 1; + for (int j : g[i]) + if (!dfs(j, g)) return false; + color[i] = 2; + return true; + } +}; +``` + +```go +func eventualSafeNodes(graph [][]int) []int { + n := len(graph) + color := make([]int, n) + var dfs func(int) bool + dfs = func(i int) bool { + if color[i] > 0 { + return color[i] == 2 + } + color[i] = 1 + for _, j := range graph[i] { + if !dfs(j) { + return false + } + } + color[i] = 2 + return true + } + ans := []int{} + for i := range graph { + if dfs(i) { + ans = append(ans, i) + } + } + return ans +} +``` + ```js /** * @param {number[][]} graph @@ -348,10 +344,6 @@ var eventualSafeNodes = function (graph) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0803.Bricks Falling When Hit/README.md b/solution/0800-0899/0803.Bricks Falling When Hit/README.md index 63a47469e9cad..76bbad1b71aa7 100644 --- a/solution/0800-0899/0803.Bricks Falling When Hit/README.md +++ b/solution/0800-0899/0803.Bricks Falling When Hit/README.md @@ -76,85 +76,10 @@ ## 解法 - - -逆向并查集,考虑补上被击碎的砖块以后,有多少个砖块因为这个补上的这个砖块而与屋顶的砖块相连。每一次击碎一个砖块,因击碎砖块而消失的砖块只会越来越少。因此可以按照数组 hits 的顺序**逆序地**把这些砖块依次补上。 - -在实现上,设置一个特殊的节点 m\*n,表示屋顶;逆序补回时,增加的连接到屋顶的砖块为 `ans[i] = max(0, curr - prev - 1)`。因为有可能补回后,连接到屋顶的砖块数量没有发生变化。 - -此过程中用 size 数组维护每个连通分量的大小。 - -以下是并查集的几个常用模板。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` +### 方法一 -### **Python3** - - - ```python class Solution: def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]: @@ -204,10 +129,6 @@ class Solution: return ans[::-1] ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -293,8 +214,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -358,8 +277,6 @@ public: }; ``` -### **Go** - ```go func hitBricks(grid [][]int, hits [][]int) []int { m, n := len(grid), len(grid[0]) @@ -438,10 +355,6 @@ func hitBricks(grid [][]int, hits [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0803.Bricks Falling When Hit/README_EN.md b/solution/0800-0899/0803.Bricks Falling When Hit/README_EN.md index 3856074de073a..b5bf3c8a7748d 100644 --- a/solution/0800-0899/0803.Bricks Falling When Hit/README_EN.md +++ b/solution/0800-0899/0803.Bricks Falling When Hit/README_EN.md @@ -73,12 +73,10 @@ Hence the result is [0,0]. ## Solutions -Union find. +### Solution 1 -### **Python3** - ```python class Solution: def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]: @@ -128,8 +126,6 @@ class Solution: return ans[::-1] ``` -### **Java** - ```java class Solution { private int[] p; @@ -215,8 +211,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -280,8 +274,6 @@ public: }; ``` -### **Go** - ```go func hitBricks(grid [][]int, hits [][]int) []int { m, n := len(grid), len(grid[0]) @@ -360,10 +352,6 @@ func hitBricks(grid [][]int, hits [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0804.Unique Morse Code Words/README.md b/solution/0800-0899/0804.Unique Morse Code Words/README.md index 94813f3005af8..ec39694683f53 100644 --- a/solution/0800-0899/0804.Unique Morse Code Words/README.md +++ b/solution/0800-0899/0804.Unique Morse Code Words/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 将 words 所有单词翻译成对应的摩尔斯密码,加入到哈希表中,最后返回哈希表的 size。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: @@ -112,10 +106,6 @@ class Solution: return len(s) ``` -### **Java** - - - ```java class Solution { public int uniqueMorseRepresentations(String[] words) { @@ -135,7 +125,38 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + int uniqueMorseRepresentations(vector& words) { + vector codes = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", + "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; + unordered_set s; + for (auto& word : words) { + string t; + for (char& c : word) t += codes[c - 'a']; + s.insert(t); + } + return s.size(); + } +}; +``` + +```go +func uniqueMorseRepresentations(words []string) int { + codes := []string{".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", + "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."} + s := make(map[string]bool) + for _, word := range words { + t := &strings.Builder{} + for _, c := range word { + t.WriteString(codes[c-'a']) + } + s[t.String()] = true + } + return len(s) +} +``` ```ts const codes = [ @@ -179,8 +200,6 @@ function uniqueMorseRepresentations(words: string[]): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -227,47 +246,6 @@ impl Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int uniqueMorseRepresentations(vector& words) { - vector codes = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", - "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; - unordered_set s; - for (auto& word : words) { - string t; - for (char& c : word) t += codes[c - 'a']; - s.insert(t); - } - return s.size(); - } -}; -``` - -### **Go** - -```go -func uniqueMorseRepresentations(words []string) int { - codes := []string{".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", - "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."} - s := make(map[string]bool) - for _, word := range words { - t := &strings.Builder{} - for _, c := range word { - t.WriteString(codes[c-'a']) - } - s[t.String()] = true - } - return len(s) -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0804.Unique Morse Code Words/README_EN.md b/solution/0800-0899/0804.Unique Morse Code Words/README_EN.md index a5aa3f7bb7493..28b0e6d87cdc2 100644 --- a/solution/0800-0899/0804.Unique Morse Code Words/README_EN.md +++ b/solution/0800-0899/0804.Unique Morse Code Words/README_EN.md @@ -57,9 +57,9 @@ There are 2 different transformations: "--...-." and "--...--.&qu ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -96,8 +96,6 @@ class Solution: return len(s) ``` -### **Java** - ```java class Solution { public int uniqueMorseRepresentations(String[] words) { @@ -117,7 +115,38 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + int uniqueMorseRepresentations(vector& words) { + vector codes = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", + "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; + unordered_set s; + for (auto& word : words) { + string t; + for (char& c : word) t += codes[c - 'a']; + s.insert(t); + } + return s.size(); + } +}; +``` + +```go +func uniqueMorseRepresentations(words []string) int { + codes := []string{".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", + "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."} + s := make(map[string]bool) + for _, word := range words { + t := &strings.Builder{} + for _, c := range word { + t.WriteString(codes[c-'a']) + } + s[t.String()] = true + } + return len(s) +} +``` ```ts const codes = [ @@ -161,8 +190,6 @@ function uniqueMorseRepresentations(words: string[]): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -209,47 +236,6 @@ impl Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int uniqueMorseRepresentations(vector& words) { - vector codes = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", - "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; - unordered_set s; - for (auto& word : words) { - string t; - for (char& c : word) t += codes[c - 'a']; - s.insert(t); - } - return s.size(); - } -}; -``` - -### **Go** - -```go -func uniqueMorseRepresentations(words []string) int { - codes := []string{".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", - "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."} - s := make(map[string]bool) - for _, word := range words { - t := &strings.Builder{} - for _, c := range word { - t.WriteString(codes[c-'a']) - } - s[t.String()] = true - } - return len(s) -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0805.Split Array With Same Average/README.md b/solution/0800-0899/0805.Split Array With Same Average/README.md index 8924e64087e07..525c8fc066792 100644 --- a/solution/0800-0899/0805.Split Array With Same Average/README.md +++ b/solution/0800-0899/0805.Split Array With Same Average/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:折半查找 + 二进制枚举** +### 方法一:折半查找 + 二进制枚举 根据题目要求,要判断是否可以将数组 `nums` 划分为两个子数组 $A$ 和 $B$,使得两个子数组的平均值相等。 @@ -92,10 +90,6 @@ $$ -### **Python3** - - - ```python class Solution: def splitArraySameAverage(self, nums: List[int]) -> bool: @@ -119,10 +113,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean splitArraySameAverage(int[] nums) { @@ -164,8 +154,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -194,8 +182,6 @@ public: }; ``` -### **Go** - ```go func splitArraySameAverage(nums []int) bool { n := len(nums) @@ -238,10 +224,6 @@ func splitArraySameAverage(nums []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0805.Split Array With Same Average/README_EN.md b/solution/0800-0899/0805.Split Array With Same Average/README_EN.md index 103beed4f76ce..bbebaff9acb11 100644 --- a/solution/0800-0899/0805.Split Array With Same Average/README_EN.md +++ b/solution/0800-0899/0805.Split Array With Same Average/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean splitArraySameAverage(int[] nums) { @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +134,6 @@ public: }; ``` -### **Go** - ```go func splitArraySameAverage(nums []int) bool { n := len(nums) @@ -182,10 +176,6 @@ func splitArraySameAverage(nums []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0806.Number of Lines To Write String/README.md b/solution/0800-0899/0806.Number of Lines To Write String/README.md index 408e7d8eee83b..bb24f39374247 100644 --- a/solution/0800-0899/0806.Number of Lines To Write String/README.md +++ b/solution/0800-0899/0806.Number of Lines To Write String/README.md @@ -46,16 +46,10 @@ S = "bbbcccdddaaa" ## 解法 - - -**方法一:模拟** +### 方法一:模拟 -### **Python3** - - - ```python class Solution: def numberOfLines(self, widths: List[int], s: str) -> List[int]: @@ -70,10 +64,6 @@ class Solution: return [row, last] ``` -### **Java** - - - ```java class Solution { private static final int MAX_WIDTH = 100; @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func numberOfLines(widths []int, s string) []int { last, row := 0, 1 @@ -135,8 +121,6 @@ func numberOfLines(widths []int, s string) []int { } ``` -### **Rust** - ```rust impl Solution { pub fn number_of_lines(widths: Vec, s: String) -> Vec { @@ -155,10 +139,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0806.Number of Lines To Write String/README_EN.md b/solution/0800-0899/0806.Number of Lines To Write String/README_EN.md index 5f548bf1c8a45..7151768173ae2 100644 --- a/solution/0800-0899/0806.Number of Lines To Write String/README_EN.md +++ b/solution/0800-0899/0806.Number of Lines To Write String/README_EN.md @@ -49,9 +49,9 @@ There are a total of 2 lines, and the last line is 4 pixels wide. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return [row, last] ``` -### **Java** - ```java class Solution { private static final int MAX_WIDTH = 100; @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func numberOfLines(widths []int, s string) []int { last, row := 0, 1 @@ -130,8 +124,6 @@ func numberOfLines(widths []int, s string) []int { } ``` -### **Rust** - ```rust impl Solution { pub fn number_of_lines(widths: Vec, s: String) -> Vec { @@ -150,10 +142,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0807.Max Increase to Keep City Skyline/README.md b/solution/0800-0899/0807.Max Increase to Keep City Skyline/README.md index 4884da5a9963d..939450d044f64 100644 --- a/solution/0800-0899/0807.Max Increase to Keep City Skyline/README.md +++ b/solution/0800-0899/0807.Max Increase to Keep City Skyline/README.md @@ -51,16 +51,10 @@ gridNew = [ [8, 4, 8, 7], ## 解法 - - -先求每一行、每一列的最大值 `rmx`, `cmx`,然后对于每个元素 `grid[i][j]`,能增加的高度是 `min(rmx[i], cmx[j]) - grid[i][j]`。累加所有能增加的高度即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: @@ -73,10 +67,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public int maxIncreaseKeepingSkyline(int[][] grid) { @@ -100,33 +90,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function maxIncreaseKeepingSkyline(grid: number[][]): number { - let rows = grid.map(arr => Math.max(...arr)), - cols = []; - let m = grid.length, - n = grid[0].length; - for (let j = 0; j < n; ++j) { - cols[j] = grid[0][j]; - for (let i = 1; i < m; ++i) { - cols[j] = Math.max(cols[j], grid[i][j]); - } - } - - let ans = 0; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - ans += Math.min(rows[i], cols[j]) - grid[i][j]; - } - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -149,8 +112,6 @@ public: }; ``` -### **Go** - ```go func maxIncreaseKeepingSkyline(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -172,10 +133,29 @@ func maxIncreaseKeepingSkyline(grid [][]int) int { } ``` -### **...** - -``` +```ts +function maxIncreaseKeepingSkyline(grid: number[][]): number { + let rows = grid.map(arr => Math.max(...arr)), + cols = []; + let m = grid.length, + n = grid[0].length; + for (let j = 0; j < n; ++j) { + cols[j] = grid[0][j]; + for (let i = 1; i < m; ++i) { + cols[j] = Math.max(cols[j], grid[i][j]); + } + } + let ans = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + ans += Math.min(rows[i], cols[j]) - grid[i][j]; + } + } + return ans; +} ``` + + diff --git a/solution/0800-0899/0807.Max Increase to Keep City Skyline/README_EN.md b/solution/0800-0899/0807.Max Increase to Keep City Skyline/README_EN.md index 433f6c1e95bb6..d587261e98ed6 100644 --- a/solution/0800-0899/0807.Max Increase to Keep City Skyline/README_EN.md +++ b/solution/0800-0899/0807.Max Increase to Keep City Skyline/README_EN.md @@ -47,9 +47,9 @@ gridNew = [ [8, 4, 8, 7], ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public int maxIncreaseKeepingSkyline(int[][] grid) { @@ -88,33 +86,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function maxIncreaseKeepingSkyline(grid: number[][]): number { - let rows = grid.map(arr => Math.max(...arr)), - cols = []; - let m = grid.length, - n = grid[0].length; - for (let j = 0; j < n; ++j) { - cols[j] = grid[0][j]; - for (let i = 1; i < m; ++i) { - cols[j] = Math.max(cols[j], grid[i][j]); - } - } - - let ans = 0; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - ans += Math.min(rows[i], cols[j]) - grid[i][j]; - } - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -137,8 +108,6 @@ public: }; ``` -### **Go** - ```go func maxIncreaseKeepingSkyline(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -160,10 +129,29 @@ func maxIncreaseKeepingSkyline(grid [][]int) int { } ``` -### **...** - -``` +```ts +function maxIncreaseKeepingSkyline(grid: number[][]): number { + let rows = grid.map(arr => Math.max(...arr)), + cols = []; + let m = grid.length, + n = grid[0].length; + for (let j = 0; j < n; ++j) { + cols[j] = grid[0][j]; + for (let i = 1; i < m; ++i) { + cols[j] = Math.max(cols[j], grid[i][j]); + } + } + let ans = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + ans += Math.min(rows[i], cols[j]) - grid[i][j]; + } + } + return ans; +} ``` + + diff --git a/solution/0800-0899/0808.Soup Servings/README.md b/solution/0800-0899/0808.Soup Servings/README.md index 7ee3276dfd322..29f55516f7e84 100644 --- a/solution/0800-0899/0808.Soup Servings/README.md +++ b/solution/0800-0899/0808.Soup Servings/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 在这道题中,由于每次操作都是 $25$ 的倍数,因此,我们可以将每 $25ml$ 的汤视为一份。这样就能将数据规模缩小到 $\left \lceil \frac{n}{25} \right \rceil$。 @@ -82,10 +80,6 @@ $$ -### **Python3** - - - ```python class Solution: def soupServings(self, n: int) -> float: @@ -107,10 +101,6 @@ class Solution: return 1 if n > 4800 else dfs((n + 24) // 25, (n + 24) // 25) ``` -### **Java** - - - ```java class Solution { private double[][] f = new double[200][200]; @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go func soupServings(n int) float64 { if n > 4800 { @@ -191,8 +177,6 @@ func soupServings(n int) float64 { } ``` -### **TypeScript** - ```ts function soupServings(n: number): number { const f = new Array(200).fill(0).map(() => new Array(200).fill(-1)); @@ -217,10 +201,6 @@ function soupServings(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0808.Soup Servings/README_EN.md b/solution/0800-0899/0808.Soup Servings/README_EN.md index 417cea63e4577..fae80e7bea28a 100644 --- a/solution/0800-0899/0808.Soup Servings/README_EN.md +++ b/solution/0800-0899/0808.Soup Servings/README_EN.md @@ -47,9 +47,9 @@ So the total probability of A becoming empty first plus half the probability tha ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return 1 if n > 4800 else dfs((n + 24) // 25, (n + 24) // 25) ``` -### **Java** - ```java class Solution { private double[][] f = new double[200][200]; @@ -103,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +120,6 @@ public: }; ``` -### **Go** - ```go func soupServings(n int) float64 { if n > 4800 { @@ -154,8 +148,6 @@ func soupServings(n int) float64 { } ``` -### **TypeScript** - ```ts function soupServings(n: number): number { const f = new Array(200).fill(0).map(() => new Array(200).fill(-1)); @@ -180,10 +172,6 @@ function soupServings(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0809.Expressive Words/README.md b/solution/0800-0899/0809.Expressive Words/README.md index b1401270b9209..7834225d55899 100644 --- a/solution/0800-0899/0809.Expressive Words/README.md +++ b/solution/0800-0899/0809.Expressive Words/README.md @@ -40,9 +40,7 @@ words = ["hello", "hi", "helo"] ## 解法 - - -**方法一:遍历计数 + 双指针** +### 方法一:遍历计数 + 双指针 我们可以遍历数组 `words`,对于数组中的每个单词 $t$,判断 $t$ 是否可以通过扩张得到 $s$,如果可以,那么答案加一。 @@ -58,10 +56,6 @@ words = ["hello", "hi", "helo"] -### **Python3** - - - ```python class Solution: def expressiveWords(self, s: str, words: List[str]) -> int: @@ -89,10 +83,6 @@ class Solution: return sum(check(s, t) for t in words) ``` -### **Java** - - - ```java class Solution { public int expressiveWords(String s, String[] words) { @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +155,6 @@ public: }; ``` -### **Go** - ```go func expressiveWords(s string, words []string) (ans int) { check := func(s, t string) bool { @@ -207,10 +193,6 @@ func expressiveWords(s string, words []string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0809.Expressive Words/README_EN.md b/solution/0800-0899/0809.Expressive Words/README_EN.md index 39e18330b61f6..108a96beb5a67 100644 --- a/solution/0800-0899/0809.Expressive Words/README_EN.md +++ b/solution/0800-0899/0809.Expressive Words/README_EN.md @@ -50,9 +50,9 @@ We can't extend "helo" to get "heeellooo" because the gr ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -81,8 +81,6 @@ class Solution: return sum(check(s, t) for t in words) ``` -### **Java** - ```java class Solution { public int expressiveWords(String s, String[] words) { @@ -126,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +153,6 @@ public: }; ``` -### **Go** - ```go func expressiveWords(s string, words []string) (ans int) { check := func(s, t string) bool { @@ -197,10 +191,6 @@ func expressiveWords(s string, words []string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0810.Chalkboard XOR Game/README.md b/solution/0800-0899/0810.Chalkboard XOR Game/README.md index 73c56e7eab799..f9b1ec9fa652e 100644 --- a/solution/0800-0899/0810.Chalkboard XOR Game/README.md +++ b/solution/0800-0899/0810.Chalkboard XOR Game/README.md @@ -52,9 +52,7 @@ Alice 有两个选择: 擦掉数字 1 或 2。 ## 解法 - - -**方法一:位运算** +### 方法一:位运算 根据游戏规则,轮到某个玩家时,如果当前黑板上所有数字按位异或运算结果为 $0$,这个玩家获胜。由于 Alice 先手,因此当 `nums` 中所有数字的异或结果为 $0$ 时,Alice 可以获胜。 @@ -102,20 +100,12 @@ $$ -### **Python3** - - - ```python class Solution: def xorGame(self, nums: List[int]) -> bool: return len(nums) % 2 == 0 or reduce(xor, nums) == 0 ``` -### **Java** - - - ```java class Solution { public boolean xorGame(int[] nums) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func xorGame(nums []int) bool { if len(nums)%2 == 0 { @@ -153,10 +139,6 @@ func xorGame(nums []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0810.Chalkboard XOR Game/README_EN.md b/solution/0800-0899/0810.Chalkboard XOR Game/README_EN.md index cbdec7084296a..d793a6e40224f 100644 --- a/solution/0800-0899/0810.Chalkboard XOR Game/README_EN.md +++ b/solution/0800-0899/0810.Chalkboard XOR Game/README_EN.md @@ -48,9 +48,9 @@ If Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elem ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return len(nums) % 2 == 0 or reduce(xor, nums) == 0 ``` -### **Java** - ```java class Solution { public boolean xorGame(int[] nums) { @@ -68,8 +66,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -82,8 +78,6 @@ public: }; ``` -### **Go** - ```go func xorGame(nums []int) bool { if len(nums)%2 == 0 { @@ -97,10 +91,6 @@ func xorGame(nums []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0811.Subdomain Visit Count/README.md b/solution/0800-0899/0811.Subdomain Visit Count/README.md index ae8ed093ef630..5be0976043290 100644 --- a/solution/0800-0899/0811.Subdomain Visit Count/README.md +++ b/solution/0800-0899/0811.Subdomain Visit Count/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们用哈希表 `cnt` 存储每个域名(子域名)对应的访问次数。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def subdomainVisits(self, cpdomains: List[str]) -> List[str]: @@ -79,10 +73,6 @@ class Solution: return [f'{v} {s}' for s, v in cnt.items()] ``` -### **Java** - - - ```java class Solution { public List subdomainVisits(String[] cpdomains) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func subdomainVisits(cpdomains []string) []string { cnt := map[string]int{} @@ -153,10 +139,6 @@ func subdomainVisits(cpdomains []string) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0811.Subdomain Visit Count/README_EN.md b/solution/0800-0899/0811.Subdomain Visit Count/README_EN.md index c568286668aef..13563786d1749 100644 --- a/solution/0800-0899/0811.Subdomain Visit Count/README_EN.md +++ b/solution/0800-0899/0811.Subdomain Visit Count/README_EN.md @@ -46,9 +46,9 @@ For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, &quo ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return [f'{v} {s}' for s, v in cnt.items()] ``` -### **Java** - ```java class Solution { public List subdomainVisits(String[] cpdomains) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func subdomainVisits(cpdomains []string) []string { cnt := map[string]int{} @@ -134,10 +128,6 @@ func subdomainVisits(cpdomains []string) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0812.Largest Triangle Area/README.md b/solution/0800-0899/0812.Largest Triangle Area/README.md index e460a71a1bb48..0a25b3de3150d 100644 --- a/solution/0800-0899/0812.Largest Triangle Area/README.md +++ b/solution/0800-0899/0812.Largest Triangle Area/README.md @@ -37,14 +37,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def largestTriangleArea(self, points: List[List[int]]) -> float: @@ -59,10 +55,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public double largestTriangleArea(int[][] points) { @@ -85,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +100,6 @@ public: }; ``` -### **Go** - ```go func largestTriangleArea(points [][]int) float64 { ans := 0.0 @@ -139,10 +127,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0812.Largest Triangle Area/README_EN.md b/solution/0800-0899/0812.Largest Triangle Area/README_EN.md index 045cf141da74a..888e44a49a81a 100644 --- a/solution/0800-0899/0812.Largest Triangle Area/README_EN.md +++ b/solution/0800-0899/0812.Largest Triangle Area/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public double largestTriangleArea(int[][] points) { @@ -75,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +96,6 @@ public: }; ``` -### **Go** - ```go func largestTriangleArea(points [][]int) float64 { ans := 0.0 @@ -129,10 +123,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0813.Largest Sum of Averages/README.md b/solution/0800-0899/0813.Largest Sum of Averages/README.md index 02e1a4102139e..2b5b6be946b97 100644 --- a/solution/0800-0899/0813.Largest Sum of Averages/README.md +++ b/solution/0800-0899/0813.Largest Sum of Averages/README.md @@ -44,9 +44,7 @@ nums 的最优分组是[9], [1, 2, 3], [9]. 得到的分数是 9 + (1 + 2 + 3) / ## 解法 - - -**方法一:前缀和 + 记忆化搜索** +### 方法一:前缀和 + 记忆化搜索 我们可以先预处理得到前缀和数组 $s$,方便快速得到子数组的和。 @@ -64,10 +62,6 @@ nums 的最优分组是[9], [1, 2, 3], [9]. 得到的分数是 9 + (1 + 2 + 3) / -### **Python3** - - - ```python class Solution: def largestSumOfAverages(self, nums: List[int], k: int) -> float: @@ -88,10 +82,6 @@ class Solution: return dfs(0, k) ``` -### **Java** - - - ```java class Solution { private Double[][] f; @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func largestSumOfAverages(nums []int, k int) float64 { n := len(nums) @@ -189,10 +175,6 @@ func largestSumOfAverages(nums []int, k int) float64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0813.Largest Sum of Averages/README_EN.md b/solution/0800-0899/0813.Largest Sum of Averages/README_EN.md index 506a709f4ba70..5161097dc00e9 100644 --- a/solution/0800-0899/0813.Largest Sum of Averages/README_EN.md +++ b/solution/0800-0899/0813.Largest Sum of Averages/README_EN.md @@ -40,9 +40,9 @@ That partition would lead to a score of 5 + 2 + 6 = 13, which is worse. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return dfs(0, k) ``` -### **Java** - ```java class Solution { private Double[][] f; @@ -102,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +126,6 @@ public: }; ``` -### **Go** - ```go func largestSumOfAverages(nums []int, k int) float64 { n := len(nums) @@ -163,10 +157,6 @@ func largestSumOfAverages(nums []int, k int) float64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0814.Binary Tree Pruning/README.md b/solution/0800-0899/0814.Binary Tree Pruning/README.md index 3fba9ae168863..daed9d41d317d 100644 --- a/solution/0800-0899/0814.Binary Tree Pruning/README.md +++ b/solution/0800-0899/0814.Binary Tree Pruning/README.md @@ -48,18 +48,12 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 观察叶节点,当叶节点 `val` 为 0 时,便将该节点抹去。回溯,查看其父节点是否成为了新的叶节点,依照此规则自底向上。 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -78,10 +72,6 @@ class Solution: return root ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -113,32 +103,6 @@ class Solution { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func pruneTree(root *TreeNode) *TreeNode { - if root == nil { - return nil - } - root.Left = pruneTree(root.Left) - root.Right = pruneTree(root.Right) - if root.Val == 0 && root.Left == nil && root.Right == nil { - return nil - } - return root -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -163,34 +127,28 @@ public: }; ``` -### **JavaScript** - -```js +```go /** * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode * } */ -/** - * @param {TreeNode} root - * @return {TreeNode} - */ -var pruneTree = function (root) { - if (!root) return null; - root.left = pruneTree(root.left); - root.right = pruneTree(root.right); - if (root.val == 0 && !root.left && !root.right) { - return null; - } - return root; -}; +func pruneTree(root *TreeNode) *TreeNode { + if root == nil { + return nil + } + root.Left = pruneTree(root.Left) + root.Right = pruneTree(root.Right) + if root.Val == 0 && root.Left == nil && root.Right == nil { + return nil + } + return root +} ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -219,8 +177,6 @@ function pruneTree(root: TreeNode | null): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -262,10 +218,30 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {TreeNode} + */ +var pruneTree = function (root) { + if (!root) return null; + root.left = pruneTree(root.left); + root.right = pruneTree(root.right); + if (root.val == 0 && !root.left && !root.right) { + return null; + } + return root; +}; ``` + + diff --git a/solution/0800-0899/0814.Binary Tree Pruning/README_EN.md b/solution/0800-0899/0814.Binary Tree Pruning/README_EN.md index 81fa7e587d73c..505baee13f3dc 100644 --- a/solution/0800-0899/0814.Binary Tree Pruning/README_EN.md +++ b/solution/0800-0899/0814.Binary Tree Pruning/README_EN.md @@ -43,9 +43,9 @@ The diagram on the right represents the answer. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -65,8 +65,6 @@ class Solution: return root ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -98,32 +96,6 @@ class Solution { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func pruneTree(root *TreeNode) *TreeNode { - if root == nil { - return nil - } - root.Left = pruneTree(root.Left) - root.Right = pruneTree(root.Right) - if root.Val == 0 && root.Left == nil && root.Right == nil { - return nil - } - return root -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -148,34 +120,28 @@ public: }; ``` -### **JavaScript** - -```js +```go /** * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode * } */ -/** - * @param {TreeNode} root - * @return {TreeNode} - */ -var pruneTree = function (root) { - if (!root) return null; - root.left = pruneTree(root.left); - root.right = pruneTree(root.right); - if (root.val == 0 && !root.left && !root.right) { - return null; - } - return root; -}; +func pruneTree(root *TreeNode) *TreeNode { + if root == nil { + return nil + } + root.Left = pruneTree(root.Left) + root.Right = pruneTree(root.Right) + if root.Val == 0 && root.Left == nil && root.Right == nil { + return nil + } + return root +} ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -204,8 +170,6 @@ function pruneTree(root: TreeNode | null): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -247,10 +211,30 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {TreeNode} + */ +var pruneTree = function (root) { + if (!root) return null; + root.left = pruneTree(root.left); + root.right = pruneTree(root.right); + if (root.val == 0 && !root.left && !root.right) { + return null; + } + return root; +}; ``` + + diff --git a/solution/0800-0899/0815.Bus Routes/README.md b/solution/0800-0899/0815.Bus Routes/README.md index 344649bce6301..2ebb40184aff7 100644 --- a/solution/0800-0899/0815.Bus Routes/README.md +++ b/solution/0800-0899/0815.Bus Routes/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:建图 + BFS** +### 方法一:建图 + BFS 对于本题,我们可以将公交线路看成图中的节点,对于任意两条公交线路,如果它们有公共的公交站点,那么这两个公交线路之间就有一条边。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def numBusesToDestination( @@ -109,10 +103,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int numBusesToDestination(int[][] routes, int source, int target) { @@ -168,8 +158,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -225,8 +213,6 @@ public: }; ``` -### **Go** - ```go func numBusesToDestination(routes [][]int, source int, target int) int { if source == target { @@ -281,8 +267,6 @@ func numBusesToDestination(routes [][]int, source int, target int) int { } ``` -### **C#** - ```cs public class Solution { public int NumBusesToDestination(int[][] routes, int source, int target) { @@ -340,10 +324,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0815.Bus Routes/README_EN.md b/solution/0800-0899/0815.Bus Routes/README_EN.md index d8e85e003583d..dd2f8b5e712e7 100644 --- a/solution/0800-0899/0815.Bus Routes/README_EN.md +++ b/solution/0800-0899/0815.Bus Routes/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,7 +58,10 @@ class Solution: if source == target: return 0 + # 一条公交线路有哪些公交站 s = [set(r) for r in routes] + + # 一个公交站在哪些公交线路有 d = defaultdict(list) for i, r in enumerate(routes): for v in r: @@ -88,8 +91,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int numBusesToDestination(int[][] routes, int source, int target) { @@ -145,8 +146,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -202,8 +201,6 @@ public: }; ``` -### **Go** - ```go func numBusesToDestination(routes [][]int, source int, target int) int { if source == target { @@ -258,8 +255,6 @@ func numBusesToDestination(routes [][]int, source int, target int) int { } ``` -### **C#** - ```cs public class Solution { public int NumBusesToDestination(int[][] routes, int source, int target) { @@ -317,10 +312,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0816.Ambiguous Coordinates/README.md b/solution/0800-0899/0816.Ambiguous Coordinates/README.md index c89f2e1e88347..a8672672dab01 100644 --- a/solution/0800-0899/0816.Ambiguous Coordinates/README.md +++ b/solution/0800-0899/0816.Ambiguous Coordinates/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:暴力模拟** +### 方法一:暴力模拟 枚举纵坐标的起始位置,然后分别获取横、纵坐标的所有可能的表示形式,最后将横、纵坐标的所有可能的表示形式组合起来。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def ambiguousCoordinates(self, s: str) -> List[str]: @@ -92,10 +86,6 @@ class Solution: ] ``` -### **Java** - - - ```java class Solution { public List ambiguousCoordinates(String s) { @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func ambiguousCoordinates(s string) []string { f := func(i, j int) []string { @@ -191,8 +177,6 @@ func ambiguousCoordinates(s string) []string { } ``` -### **TypeScript** - ```ts function ambiguousCoordinates(s: string): string[] { s = s.slice(1, s.length - 1); @@ -222,10 +206,6 @@ function ambiguousCoordinates(s: string): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0816.Ambiguous Coordinates/README_EN.md b/solution/0800-0899/0816.Ambiguous Coordinates/README_EN.md index bb9cf06cb5c1e..e4afc0521e422 100644 --- a/solution/0800-0899/0816.Ambiguous Coordinates/README_EN.md +++ b/solution/0800-0899/0816.Ambiguous Coordinates/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: ] ``` -### **Java** - ```java class Solution { public List ambiguousCoordinates(String s) { @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +132,6 @@ public: }; ``` -### **Go** - ```go func ambiguousCoordinates(s string) []string { f := func(i, j int) []string { @@ -169,8 +163,6 @@ func ambiguousCoordinates(s string) []string { } ``` -### **TypeScript** - ```ts function ambiguousCoordinates(s: string): string[] { s = s.slice(1, s.length - 1); @@ -200,10 +192,6 @@ function ambiguousCoordinates(s: string): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0817.Linked List Components/README.md b/solution/0800-0899/0817.Linked List Components/README.md index 3d11e2ab0fde5..916be5f8de391 100644 --- a/solution/0800-0899/0817.Linked List Components/README.md +++ b/solution/0800-0899/0817.Linked List Components/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:哈希表 + 链表一次遍历** +### 方法一:哈希表 + 链表一次遍历 题目中需要判断链表中节点的值是否在数组 `nums` 中,因此我们可以使用哈希表 $s$ 存储数组 `nums` 中的值。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -176,39 +162,6 @@ func numComponents(head *ListNode, nums []int) int { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @param {number[]} nums - * @return {number} - */ -var numComponents = function (head, nums) { - const s = new Set(nums); - let ans = 0; - while (head) { - while (head && !s.has(head.val)) { - head = head.next; - } - ans += head != null; - while (head && s.has(head.val)) { - head = head.next; - } - } - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -242,8 +195,6 @@ function numComponents(head: ListNode | null, nums: number[]): number { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -284,10 +235,35 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number[]} nums + * @return {number} + */ +var numComponents = function (head, nums) { + const s = new Set(nums); + let ans = 0; + while (head) { + while (head && !s.has(head.val)) { + head = head.next; + } + ans += head != null; + while (head && s.has(head.val)) { + head = head.next; + } + } + return ans; +}; ``` + + diff --git a/solution/0800-0899/0817.Linked List Components/README_EN.md b/solution/0800-0899/0817.Linked List Components/README_EN.md index 793384b2aaf99..b64914b356355 100644 --- a/solution/0800-0899/0817.Linked List Components/README_EN.md +++ b/solution/0800-0899/0817.Linked List Components/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -125,8 +121,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -156,39 +150,6 @@ func numComponents(head *ListNode, nums []int) int { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @param {number[]} nums - * @return {number} - */ -var numComponents = function (head, nums) { - const s = new Set(nums); - let ans = 0; - while (head) { - while (head && !s.has(head.val)) { - head = head.next; - } - ans += head != null; - while (head && s.has(head.val)) { - head = head.next; - } - } - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -222,8 +183,6 @@ function numComponents(head: ListNode | null, nums: number[]): number { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -264,10 +223,35 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number[]} nums + * @return {number} + */ +var numComponents = function (head, nums) { + const s = new Set(nums); + let ans = 0; + while (head) { + while (head && !s.has(head.val)) { + head = head.next; + } + ans += head != null; + while (head && s.has(head.val)) { + head = head.next; + } + } + return ans; +}; ``` + + diff --git a/solution/0800-0899/0818.Race Car/README.md b/solution/0800-0899/0818.Race Car/README.md index 8d46f5209c554..6fab7601b6579 100644 --- a/solution/0800-0899/0818.Race Car/README.md +++ b/solution/0800-0899/0818.Race Car/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 设 $dp[i]$ 表示到达位置 $i$ 的最短指令序列的长度。答案为 $dp[target]$。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def racecar(self, target: int) -> int: @@ -93,10 +87,6 @@ class Solution: return dp[target] ``` -### **Java** - - - ```java class Solution { public int racecar(int target) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func racecar(target int) int { dp := make([]int, target+1) @@ -160,10 +146,6 @@ func racecar(target int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0818.Race Car/README_EN.md b/solution/0800-0899/0818.Race Car/README_EN.md index c02d0d6f65c81..fa23005bce7c9 100644 --- a/solution/0800-0899/0818.Race Car/README_EN.md +++ b/solution/0800-0899/0818.Race Car/README_EN.md @@ -55,9 +55,9 @@ Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return dp[target] ``` -### **Java** - ```java class Solution { public int racecar(int target) { @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +115,6 @@ public: }; ``` -### **Go** - ```go func racecar(target int) int { dp := make([]int, target+1) @@ -139,10 +133,6 @@ func racecar(target int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0819.Most Common Word/README.md b/solution/0800-0899/0819.Most Common Word/README.md index 07e8be75b9bc0..bcfcd633c0f49 100644 --- a/solution/0800-0899/0819.Most Common Word/README.md +++ b/solution/0800-0899/0819.Most Common Word/README.md @@ -46,18 +46,12 @@ ## 解法 - - -**方法一:正则匹配/双指针 + 哈希表** +### 方法一:正则匹配/双指针 + 哈希表 正则匹配(或双指针)找出所有单词,用哈希表统计每个单词出现的频率,找到出现未在 banned 中出现且频率最大的单词。 -### **Python3** - - - ```python class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: @@ -66,10 +60,6 @@ class Solution: return next(word for word, _ in p.most_common() if word not in s) ``` -### **Java** - - - ```java import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -104,49 +94,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function mostCommonWord(paragraph: string, banned: string[]): string { - const s = paragraph.toLocaleLowerCase(); - const map = new Map(); - const set = new Set(banned); - for (const word of s.split(/[^A-z]/)) { - if (word === '' || set.has(word)) { - continue; - } - map.set(word, (map.get(word) ?? 0) + 1); - } - return [...map.entries()].reduce((r, v) => (v[1] > r[1] ? v : r), ['', 0])[0]; -} -``` - -### **Rust** - -```rust -use std::collections::{ HashMap, HashSet }; -impl Solution { - pub fn most_common_word(mut paragraph: String, banned: Vec) -> String { - paragraph.make_ascii_lowercase(); - let banned: HashSet<&str> = banned.iter().map(String::as_str).collect(); - let mut map = HashMap::new(); - for word in paragraph.split(|c| !matches!(c, 'a'..='z')) { - if word.is_empty() || banned.contains(word) { - continue; - } - let val = map.get(&word).unwrap_or(&0) + 1; - map.insert(word, val); - } - map.into_iter() - .max_by_key(|&(_, v)| v) - .unwrap() - .0.to_string() - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -175,8 +122,6 @@ public: }; ``` -### **Go** - ```go func mostCommonWord(paragraph string, banned []string) string { s := make(map[string]bool) @@ -211,10 +156,43 @@ func mostCommonWord(paragraph string, banned []string) string { } ``` -### **...** - +```ts +function mostCommonWord(paragraph: string, banned: string[]): string { + const s = paragraph.toLocaleLowerCase(); + const map = new Map(); + const set = new Set(banned); + for (const word of s.split(/[^A-z]/)) { + if (word === '' || set.has(word)) { + continue; + } + map.set(word, (map.get(word) ?? 0) + 1); + } + return [...map.entries()].reduce((r, v) => (v[1] > r[1] ? v : r), ['', 0])[0]; +} ``` +```rust +use std::collections::{ HashMap, HashSet }; +impl Solution { + pub fn most_common_word(mut paragraph: String, banned: Vec) -> String { + paragraph.make_ascii_lowercase(); + let banned: HashSet<&str> = banned.iter().map(String::as_str).collect(); + let mut map = HashMap::new(); + for word in paragraph.split(|c| !matches!(c, 'a'..='z')) { + if word.is_empty() || banned.contains(word) { + continue; + } + let val = map.get(&word).unwrap_or(&0) + 1; + map.insert(word, val); + } + map.into_iter() + .max_by_key(|&(_, v)| v) + .unwrap() + .0.to_string() + } +} ``` + + diff --git a/solution/0800-0899/0819.Most Common Word/README_EN.md b/solution/0800-0899/0819.Most Common Word/README_EN.md index 7162cc5094d53..854998e79a2e4 100644 --- a/solution/0800-0899/0819.Most Common Word/README_EN.md +++ b/solution/0800-0899/0819.Most Common Word/README_EN.md @@ -42,9 +42,9 @@ and that "hit" isn't the answer even though it occurs more because ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return next(word for word, _ in p.most_common() if word not in s) ``` -### **Java** - ```java import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -90,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +116,6 @@ public: }; ``` -### **Go** - ```go func mostCommonWord(paragraph string, banned []string) string { s := make(map[string]bool) @@ -156,8 +150,6 @@ func mostCommonWord(paragraph string, banned []string) string { } ``` -### **TypeScript** - ```ts function mostCommonWord(paragraph: string, banned: string[]): string { const s = paragraph.toLocaleLowerCase(); @@ -173,8 +165,6 @@ function mostCommonWord(paragraph: string, banned: string[]): string { } ``` -### **Rust** - ```rust use std::collections::{ HashMap, HashSet }; impl Solution { @@ -197,10 +187,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0820.Short Encoding of Words/README.md b/solution/0800-0899/0820.Short Encoding of Words/README.md index 8b290701f2c80..45244a563c335 100644 --- a/solution/0800-0899/0820.Short Encoding of Words/README.md +++ b/solution/0800-0899/0820.Short Encoding of Words/README.md @@ -49,9 +49,7 @@ words[2] = "bell" ,s 开始于 indices[2] = 5 到下一个 '#' 结束的子字 ## 解法 - - -**方法一:前缀树** +### 方法一:前缀树 题目大意:充分利用重叠的后缀,使有效编码尽可能短。 @@ -59,10 +57,6 @@ words[2] = "bell" ,s 开始于 indices[2] = 5 到下一个 '#' 结束的子字 -### **Python3** - - - ```python class Trie: def __init__(self) -> None: @@ -92,34 +86,6 @@ class Solution: return ans ``` -```python -class Trie: - def __init__(self): - self.children = [None] * 26 - - def insert(self, w): - node = self - pref = True - for c in w: - idx = ord(c) - ord("a") - if node.children[idx] is None: - node.children[idx] = Trie() - pref = False - node = node.children[idx] - return 0 if pref else len(w) + 1 - - -class Solution: - def minimumLengthEncoding(self, words: List[str]) -> int: - words.sort(key=lambda x: -len(x)) - trie = Trie() - return sum(trie.insert(w[::-1]) for w in words) -``` - -### **Java** - - - ```java class Trie { Trie[] children = new Trie[26]; @@ -158,40 +124,45 @@ class Solution { } ``` -```java -class Trie { - Trie[] children = new Trie[26]; +```cpp +struct Trie { + Trie* children[26] = {nullptr}; +}; - int insert(String w) { - Trie node = this; - boolean pref = true; - for (int i = w.length() - 1; i >= 0; --i) { - int idx = w.charAt(i) - 'a'; - if (node.children[idx] == null) { - pref = false; - node.children[idx] = new Trie(); +class Solution { +public: + int minimumLengthEncoding(vector& words) { + auto root = new Trie(); + for (auto& w : words) { + auto cur = root; + for (int i = w.size() - 1; i >= 0; --i) { + if (cur->children[w[i] - 'a'] == nullptr) { + cur->children[w[i] - 'a'] = new Trie(); + } + cur = cur->children[w[i] - 'a']; } - node = node.children[idx]; } - return pref ? 0 : w.length() + 1; + return dfs(root, 1); } -} -class Solution { - public int minimumLengthEncoding(String[] words) { - Arrays.sort(words, (a, b) -> b.length() - a.length()); +private: + int dfs(Trie* cur, int l) { + bool isLeaf = true; int ans = 0; - Trie trie = new Trie(); - for (String w : words) { - ans += trie.insert(w); + for (int i = 0; i < 26; ++i) { + if (cur->children[i] != nullptr) { + isLeaf = false; + ans += dfs(cur->children[i], l + 1); + } + } + if (isLeaf) { + ans += l; } return ans; } -} +}; ``` -### **Go** - ```go type trie struct { children [26]*trie @@ -226,82 +197,66 @@ func dfs(cur *trie, l int) int { } ``` -```go -type Trie struct { - children [26]*Trie -} + -func newTrie() *Trie { - return &Trie{} -} +### 方法二 -func (this *Trie) insert(w string) int { - node := this - pref := true - for i := len(w) - 1; i >= 0; i-- { - idx := w[i] - 'a' - if node.children[idx] == nil { - pref = false - node.children[idx] = newTrie() - } - node = node.children[idx] - } - if pref { - return 0 - } - return len(w) + 1 -} + -func minimumLengthEncoding(words []string) int { - sort.Slice(words, func(i, j int) bool { return len(words[i]) > len(words[j]) }) - trie := newTrie() - ans := 0 - for _, w := range words { - ans += trie.insert(w) - } - return ans -} -``` +```python +class Trie: + def __init__(self): + self.children = [None] * 26 -### **C++** + def insert(self, w): + node = self + pref = True + for c in w: + idx = ord(c) - ord("a") + if node.children[idx] is None: + node.children[idx] = Trie() + pref = False + node = node.children[idx] + return 0 if pref else len(w) + 1 -```cpp -struct Trie { - Trie* children[26] = {nullptr}; -}; -class Solution { -public: - int minimumLengthEncoding(vector& words) { - auto root = new Trie(); - for (auto& w : words) { - auto cur = root; - for (int i = w.size() - 1; i >= 0; --i) { - if (cur->children[w[i] - 'a'] == nullptr) { - cur->children[w[i] - 'a'] = new Trie(); - } - cur = cur->children[w[i] - 'a']; +class Solution: + def minimumLengthEncoding(self, words: List[str]) -> int: + words.sort(key=lambda x: -len(x)) + trie = Trie() + return sum(trie.insert(w[::-1]) for w in words) +``` + +```java +class Trie { + Trie[] children = new Trie[26]; + + int insert(String w) { + Trie node = this; + boolean pref = true; + for (int i = w.length() - 1; i >= 0; --i) { + int idx = w.charAt(i) - 'a'; + if (node.children[idx] == null) { + pref = false; + node.children[idx] = new Trie(); } + node = node.children[idx]; } - return dfs(root, 1); + return pref ? 0 : w.length() + 1; } +} -private: - int dfs(Trie* cur, int l) { - bool isLeaf = true; +class Solution { + public int minimumLengthEncoding(String[] words) { + Arrays.sort(words, (a, b) -> b.length() - a.length()); int ans = 0; - for (int i = 0; i < 26; ++i) { - if (cur->children[i] != nullptr) { - isLeaf = false; - ans += dfs(cur->children[i], l + 1); - } - } - if (isLeaf) { - ans += l; + Trie trie = new Trie(); + for (String w : words) { + ans += trie.insert(w); } return ans; } -}; +} ``` ```cpp @@ -341,10 +296,43 @@ public: }; ``` -### **...** +```go +type Trie struct { + children [26]*Trie +} -``` +func newTrie() *Trie { + return &Trie{} +} +func (this *Trie) insert(w string) int { + node := this + pref := true + for i := len(w) - 1; i >= 0; i-- { + idx := w[i] - 'a' + if node.children[idx] == nil { + pref = false + node.children[idx] = newTrie() + } + node = node.children[idx] + } + if pref { + return 0 + } + return len(w) + 1 +} + +func minimumLengthEncoding(words []string) int { + sort.Slice(words, func(i, j int) bool { return len(words[i]) > len(words[j]) }) + trie := newTrie() + ans := 0 + for _, w := range words { + ans += trie.insert(w) + } + return ans +} ``` + + diff --git a/solution/0800-0899/0820.Short Encoding of Words/README_EN.md b/solution/0800-0899/0820.Short Encoding of Words/README_EN.md index 9f5a8c8593b89..3753320eae954 100644 --- a/solution/0800-0899/0820.Short Encoding of Words/README_EN.md +++ b/solution/0800-0899/0820.Short Encoding of Words/README_EN.md @@ -45,9 +45,9 @@ words[2] = "bell", the substring of s starting from indices[2] = 5 to ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -60,8 +60,8 @@ class Solution: root = Trie() for w in words: cur = root - for i in range(len(w) - 1, -1, -1): - idx = ord(w[i]) - ord('a') + for c in w[::-1]: + idx = ord(c) - ord("a") if cur.children[idx] == None: cur.children[idx] = Trie() cur = cur.children[idx] @@ -78,18 +78,6 @@ class Solution: return ans ``` -```python -class Solution: - def minimumLengthEncoding(self, words: List[str]) -> int: - s = set(words) - for word in words: - for i in range(1, len(word)): - s.discard(word[i:]) - return sum(len(word) + 1 for word in s) -``` - -### **Java** - ```java class Trie { Trie[] children = new Trie[26]; @@ -128,26 +116,45 @@ class Solution { } ``` -```java +```cpp +struct Trie { + Trie* children[26] = {nullptr}; +}; + class Solution { - public int minimumLengthEncoding(String[] words) { - Set s = new HashSet<>(Arrays.asList(words)); - for (String word : words) { - for (int i = 1; i < word.length(); ++i) { - s.remove(word.substring(i)); +public: + int minimumLengthEncoding(vector& words) { + auto root = new Trie(); + for (auto& w : words) { + auto cur = root; + for (int i = w.size() - 1; i >= 0; --i) { + if (cur->children[w[i] - 'a'] == nullptr) { + cur->children[w[i] - 'a'] = new Trie(); + } + cur = cur->children[w[i] - 'a']; } } + return dfs(root, 1); + } + +private: + int dfs(Trie* cur, int l) { + bool isLeaf = true; int ans = 0; - for (String word : s) { - ans += word.length() + 1; + for (int i = 0; i < 26; ++i) { + if (cur->children[i] != nullptr) { + isLeaf = false; + ans += dfs(cur->children[i], l + 1); + } + } + if (isLeaf) { + ans += l; } return ans; } -} +}; ``` -### **Go** - ```go type trie struct { children [26]*trie @@ -182,86 +189,142 @@ func dfs(cur *trie, l int) int { } ``` -### **C++** + -```cpp -struct Trie { - Trie* children[26] = {nullptr}; -}; +### Solution 2 -class Solution { -public: - int minimumLengthEncoding(vector& words) { - auto root = new Trie(); - for (auto& w : words) { - auto cur = root; - for (int i = w.size() - 1; i >= 0; --i) { - if (cur->children[w[i] - 'a'] == nullptr) { - cur->children[w[i] - 'a'] = new Trie(); - } - cur = cur->children[w[i] - 'a']; + + +```python +class Trie: + def __init__(self): + self.children = [None] * 26 + + def insert(self, w): + node = self + pref = True + for c in w: + idx = ord(c) - ord("a") + if node.children[idx] is None: + node.children[idx] = Trie() + pref = False + node = node.children[idx] + return 0 if pref else len(w) + 1 + + +class Solution: + def minimumLengthEncoding(self, words: List[str]) -> int: + words.sort(key=lambda x: -len(x)) + trie = Trie() + return sum(trie.insert(w[::-1]) for w in words) +``` + +```java +class Trie { + Trie[] children = new Trie[26]; + + int insert(String w) { + Trie node = this; + boolean pref = true; + for (int i = w.length() - 1; i >= 0; --i) { + int idx = w.charAt(i) - 'a'; + if (node.children[idx] == null) { + pref = false; + node.children[idx] = new Trie(); } + node = node.children[idx]; } - return dfs(root, 1); + return pref ? 0 : w.length() + 1; } +} -private: - int dfs(Trie* cur, int l) { - bool isLeaf = true; +class Solution { + public int minimumLengthEncoding(String[] words) { + Arrays.sort(words, (a, b) -> b.length() - a.length()); int ans = 0; - for (int i = 0; i < 26; ++i) { - if (cur->children[i] != nullptr) { - isLeaf = false; - ans += dfs(cur->children[i], l + 1); - } - } - if (isLeaf) { - ans += l; + Trie trie = new Trie(); + for (String w : words) { + ans += trie.insert(w); } return ans; } -}; -``` - -```go -func minimumLengthEncoding(words []string) int { - s := make(map[string]bool) - for _, word := range words { - s[word] = true - } - for _, word := range words { - for i, n := 1, len(word); i < n; i++ { - delete(s, word[i:n]) - } - } - ans := 0 - for word := range s { - ans += len(word) + 1 - } - return ans } ``` ```cpp +class Trie { +public: + vector children; + Trie() + : children(26) {} + + int insert(string w) { + Trie* node = this; + bool pref = true; + for (char c : w) { + c -= 'a'; + if (!node->children[c]) { + pref = false; + node->children[c] = new Trie(); + } + node = node->children[c]; + } + return pref ? 0 : w.size() + 1; + } +}; + class Solution { public: int minimumLengthEncoding(vector& words) { - unordered_set s(words.begin(), words.end()); - for (auto& word : words) - for (int i = 1; i < word.size(); ++i) - s.erase(word.substr(i)); + sort(words.begin(), words.end(), [](string& a, string& b) { return a.size() > b.size(); }); + Trie* trie = new Trie(); int ans = 0; - for (auto& word : s) - ans += word.size() + 1; + for (auto& w : words) { + reverse(w.begin(), w.end()); + ans += trie->insert(w); + } return ans; } }; ``` -### **...** +```go +type Trie struct { + children [26]*Trie +} -``` +func newTrie() *Trie { + return &Trie{} +} + +func (this *Trie) insert(w string) int { + node := this + pref := true + for i := len(w) - 1; i >= 0; i-- { + idx := w[i] - 'a' + if node.children[idx] == nil { + pref = false + node.children[idx] = newTrie() + } + node = node.children[idx] + } + if pref { + return 0 + } + return len(w) + 1 +} +func minimumLengthEncoding(words []string) int { + sort.Slice(words, func(i, j int) bool { return len(words[i]) > len(words[j]) }) + trie := newTrie() + ans := 0 + for _, w := range words { + ans += trie.insert(w) + } + return ans +} ``` + + diff --git a/solution/0800-0899/0821.Shortest Distance to a Character/README.md b/solution/0800-0899/0821.Shortest Distance to a Character/README.md index 610c3c26fa552..06f934db74936 100644 --- a/solution/0800-0899/0821.Shortest Distance to a Character/README.md +++ b/solution/0800-0899/0821.Shortest Distance to a Character/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:两次遍历** +### 方法一:两次遍历 我们先创建一个长度为 $n$ 的答案数组 $ans$。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def shortestToChar(self, s: str, c: str) -> List[int]: @@ -82,10 +76,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] shortestToChar(String s, char c) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func shortestToChar(s string, c byte) []int { n := len(s) @@ -161,8 +147,6 @@ func shortestToChar(s string, c byte) []int { } ``` -### **TypeScript** - ```ts function shortestToChar(s: string, c: string): number[] { const n = s.length; @@ -184,8 +168,6 @@ function shortestToChar(s: string, c: string): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn shortest_to_char(s: String, c: char) -> Vec { @@ -212,10 +194,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0821.Shortest Distance to a Character/README_EN.md b/solution/0800-0899/0821.Shortest Distance to a Character/README_EN.md index e35a0e228b97b..ffde395fe1c30 100644 --- a/solution/0800-0899/0821.Shortest Distance to a Character/README_EN.md +++ b/solution/0800-0899/0821.Shortest Distance to a Character/README_EN.md @@ -39,9 +39,9 @@ The closest occurrence of 'e' for index 8 is at index 6, so the distance ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] shortestToChar(String s, char c) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func shortestToChar(s string, c byte) []int { n := len(s) @@ -138,8 +132,6 @@ func shortestToChar(s string, c byte) []int { } ``` -### **TypeScript** - ```ts function shortestToChar(s: string, c: string): number[] { const n = s.length; @@ -161,8 +153,6 @@ function shortestToChar(s: string, c: string): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn shortest_to_char(s: String, c: char) -> Vec { @@ -189,10 +179,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0822.Card Flipping Game/README.md b/solution/0800-0899/0822.Card Flipping Game/README.md index 4fca93de850d8..1dfe519be93fd 100644 --- a/solution/0800-0899/0822.Card Flipping Game/README.md +++ b/solution/0800-0899/0822.Card Flipping Game/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们注意到,对于位置 $i$,若 $fronts[i]$ 与 $backs[i]$ 元素相同,则一定不满足条件。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def flipgame(self, fronts: List[int], backs: List[int]) -> int: @@ -76,10 +70,6 @@ class Solution: return min((x for x in chain(fronts, backs) if x not in s), default=0) ``` -### **Java** - - - ```java class Solution { public int flipgame(int[] fronts, int[] backs) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func flipgame(fronts []int, backs []int) int { s := map[int]struct{}{} @@ -160,8 +146,6 @@ func flipgame(fronts []int, backs []int) int { } ``` -### **TypeScript** - ```ts function flipgame(fronts: number[], backs: number[]): number { const s: Set = new Set(); @@ -186,8 +170,6 @@ function flipgame(fronts: number[], backs: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int Flipgame(int[] fronts, int[] backs) { @@ -212,10 +194,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0822.Card Flipping Game/README_EN.md b/solution/0800-0899/0822.Card Flipping Game/README_EN.md index d3de03b6c7f7c..a13022b597834 100644 --- a/solution/0800-0899/0822.Card Flipping Game/README_EN.md +++ b/solution/0800-0899/0822.Card Flipping Game/README_EN.md @@ -42,9 +42,9 @@ There are no good integers no matter how we flip the cards, so we return 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return min((x for x in chain(fronts, backs) if x not in s), default=0) ``` -### **Java** - ```java class Solution { public int flipgame(int[] fronts, int[] backs) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +106,6 @@ public: }; ``` -### **Go** - ```go func flipgame(fronts []int, backs []int) int { s := map[int]struct{}{} @@ -135,8 +129,6 @@ func flipgame(fronts []int, backs []int) int { } ``` -### **TypeScript** - ```ts function flipgame(fronts: number[], backs: number[]): number { const s: Set = new Set(); @@ -161,8 +153,6 @@ function flipgame(fronts: number[], backs: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int Flipgame(int[] fronts, int[] backs) { @@ -187,10 +177,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0823.Binary Trees With Factors/README.md b/solution/0800-0899/0823.Binary Trees With Factors/README.md index bf957c7cc0212..6feb9366fda96 100644 --- a/solution/0800-0899/0823.Binary Trees With Factors/README.md +++ b/solution/0800-0899/0823.Binary Trees With Factors/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们可以枚举 $arr$ 中的每一个数 $a$ 作为二叉树的根节点(根节点一定最大),然后枚举枚举左子树的值 $b$,若 $a$ 能被 $b$ 整除,则右子树的值为 $a / b$,若 $a / b$ 也在 $arr$ 中,则可以构成一棵二叉树。此时,以 $a$ 为根节点的二叉树的个数为 $f(a) = f(b) \times f(a / b)$,其中 $f(b)$ 和 $f(a / b)$ 分别为左子树和右子树的二叉树个数。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def numFactoredBinaryTrees(self, arr: List[int]) -> int: @@ -72,10 +66,6 @@ class Solution: return sum(f) % mod ``` -### **Java** - - - ```java class Solution { public int numFactoredBinaryTrees(int[] arr) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func numFactoredBinaryTrees(arr []int) int { const mod int = 1e9 + 7 @@ -176,8 +162,6 @@ func numFactoredBinaryTrees(arr []int) int { } ``` -### **TypeScript** - ```ts function numFactoredBinaryTrees(arr: number[]): number { const mod = 10 ** 9 + 7; @@ -205,10 +189,6 @@ function numFactoredBinaryTrees(arr: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0823.Binary Trees With Factors/README_EN.md b/solution/0800-0899/0823.Binary Trees With Factors/README_EN.md index 5a93c927da94c..bf02e99739be4 100644 --- a/solution/0800-0899/0823.Binary Trees With Factors/README_EN.md +++ b/solution/0800-0899/0823.Binary Trees With Factors/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return sum(f) % mod ``` -### **Java** - ```java class Solution { public int numFactoredBinaryTrees(int[] arr) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +124,6 @@ public: }; ``` -### **Go** - ```go func numFactoredBinaryTrees(arr []int) int { const mod int = 1e9 + 7 @@ -158,8 +152,6 @@ func numFactoredBinaryTrees(arr []int) int { } ``` -### **TypeScript** - ```ts function numFactoredBinaryTrees(arr: number[]): number { const mod = 10 ** 9 + 7; @@ -187,10 +179,6 @@ function numFactoredBinaryTrees(arr: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0824.Goat Latin/README.md b/solution/0800-0899/0824.Goat Latin/README.md index 739de1ea7b8e5..c4e683e514402 100644 --- a/solution/0800-0899/0824.Goat Latin/README.md +++ b/solution/0800-0899/0824.Goat Latin/README.md @@ -59,14 +59,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def toGoatLatin(self, sentence: str) -> str: @@ -80,10 +76,6 @@ class Solution: return ' '.join(ans) ``` -### **Java** - - - ```java class Solution { public String toGoatLatin(String sentence) { @@ -111,8 +103,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function toGoatLatin(sentence: string): string { return sentence @@ -130,8 +120,6 @@ function toGoatLatin(sentence: string): string { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -158,10 +146,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0824.Goat Latin/README_EN.md b/solution/0800-0899/0824.Goat Latin/README_EN.md index bbe846cb9f11d..0f2caad2d1933 100644 --- a/solution/0800-0899/0824.Goat Latin/README_EN.md +++ b/solution/0800-0899/0824.Goat Latin/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ' '.join(ans) ``` -### **Java** - ```java class Solution { public String toGoatLatin(String sentence) { @@ -94,8 +92,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function toGoatLatin(sentence: string): string { return sentence @@ -113,8 +109,6 @@ function toGoatLatin(sentence: string): string { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -141,10 +135,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0825.Friends Of Appropriate Ages/README.md b/solution/0800-0899/0825.Friends Of Appropriate Ages/README.md index 5a47ac0ab753b..e0d4b2d65dc1f 100644 --- a/solution/0800-0899/0825.Friends Of Appropriate Ages/README.md +++ b/solution/0800-0899/0825.Friends Of Appropriate Ages/README.md @@ -60,16 +60,10 @@ ## 解法 - - -对年龄计数。 +### 方法一 -### **Python3** - - - ```python class Solution: def numFriendRequests(self, ages: List[int]) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numFriendRequests(int[] ages) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +127,6 @@ public: }; ``` -### **Go** - ```go func numFriendRequests(ages []int) int { counter := make([]int, 121) @@ -164,10 +150,6 @@ func numFriendRequests(ages []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0825.Friends Of Appropriate Ages/README_EN.md b/solution/0800-0899/0825.Friends Of Appropriate Ages/README_EN.md index 5a29fcd211e9c..0f4b00ecc3e0b 100644 --- a/solution/0800-0899/0825.Friends Of Appropriate Ages/README_EN.md +++ b/solution/0800-0899/0825.Friends Of Appropriate Ages/README_EN.md @@ -56,9 +56,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numFriendRequests(int[] ages) { @@ -103,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +123,6 @@ public: }; ``` -### **Go** - ```go func numFriendRequests(ages []int) int { counter := make([]int, 121) @@ -152,10 +146,6 @@ func numFriendRequests(ages []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0826.Most Profit Assigning Work/README.md b/solution/0800-0899/0826.Most Profit Assigning Work/README.md index 508221e9f57fd..8245414128b8b 100644 --- a/solution/0800-0899/0826.Most Profit Assigning Work/README.md +++ b/solution/0800-0899/0826.Most Profit Assigning Work/README.md @@ -50,16 +50,10 @@ ## 解法 - - -“排序 + 双指针”。 +### 方法一 -### **Python3** - - - ```python class Solution: def maxProfitAssignment( @@ -78,10 +72,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func maxProfitAssignment(difficulty []int, profit []int, worker []int) int { var job [][2]int @@ -154,10 +140,6 @@ func maxProfitAssignment(difficulty []int, profit []int, worker []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0826.Most Profit Assigning Work/README_EN.md b/solution/0800-0899/0826.Most Profit Assigning Work/README_EN.md index 81bcdeb2972b7..7a0d8b0558d71 100644 --- a/solution/0800-0899/0826.Most Profit Assigning Work/README_EN.md +++ b/solution/0800-0899/0826.Most Profit Assigning Work/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +117,6 @@ public: }; ``` -### **Go** - ```go func maxProfitAssignment(difficulty []int, profit []int, worker []int) int { var job [][2]int @@ -144,10 +138,6 @@ func maxProfitAssignment(difficulty []int, profit []int, worker []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0827.Making A Large Island/README.md b/solution/0800-0899/0827.Making A Large Island/README.md index d0cfe4378783d..ead89263fb7dc 100644 --- a/solution/0800-0899/0827.Making A Large Island/README.md +++ b/solution/0800-0899/0827.Making A Large Island/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:并查集** +### 方法一:并查集 并查集是一种树形的数据结构,顾名思义,它用于处理一些不交集的**合并**及**查询**问题。 它支持两种操作: @@ -96,22 +94,8 @@ def union(a, b): 时间复杂度 $O(n^2\times \alpha(n))$。其中 $n$ 为矩阵 `grid` 的边长。 -**方法二:DFS** - -我们也可以通过 DFS,找到每个岛屿。 - -同一个岛屿中的所有点都属于同一个集合,我们可以用不同的 `root` 值标识不同的岛屿,用 $p$ 记录每个 $grid[i][j]$ 对应的 `root` 值,用 $cnt$ 记录每个岛屿的面积。 - -遍历 `grid`,对于每个 $0$,我们统计相邻的四个点中 $1$ 所在的岛屿(与方法一不同的是,我们这里直接取 $p[i][j]$ 作为 `root`),累加去重后的岛屿面积,更新最大值。 - -时间复杂度 $O(n^2)$。其中 $n$ 为矩阵 `grid` 的边长。 - -### **Python3** - - - ```python class Solution: def largestIsland(self, grid: List[List[int]]) -> int: @@ -154,48 +138,6 @@ class Solution: return ans ``` -```python -class Solution: - def largestIsland(self, grid: List[List[int]]) -> int: - def dfs(i, j): - p[i][j] = root - cnt[root] += 1 - for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: - x, y = i + a, j + b - if 0 <= x < n and 0 <= y < n and grid[x][y] and p[x][y] == 0: - dfs(x, y) - - n = len(grid) - cnt = Counter() - p = [[0] * n for _ in range(n)] - root = 0 - for i, row in enumerate(grid): - for j, v in enumerate(row): - if v and p[i][j] == 0: - root += 1 - dfs(i, j) - - ans = max(cnt.values(), default=0) - for i, row in enumerate(grid): - for j, v in enumerate(row): - if v == 0: - t = 1 - vis = set() - for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: - x, y = i + a, j + b - if 0 <= x < n and 0 <= y < n: - root = p[x][y] - if root not in vis: - vis.add(root) - t += cnt[root] - ans = max(ans, t) - return ans -``` - -### **Java** - - - ```java class Solution { private int n; @@ -261,67 +203,6 @@ class Solution { } ``` -```java -class Solution { - private int n; - private int ans; - private int root; - private int[][] p; - private int[][] grid; - private int[] cnt; - private int[] dirs = new int[] {-1, 0, 1, 0, -1}; - - public int largestIsland(int[][] grid) { - n = grid.length; - cnt = new int[n * n + 1]; - p = new int[n][n]; - this.grid = grid; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == 1 && p[i][j] == 0) { - ++root; - dfs(i, j); - } - } - } - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == 0) { - int t = 1; - Set vis = new HashSet<>(); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < n && y >= 0 && y < n) { - int root = p[x][y]; - if (!vis.contains(root)) { - vis.add(root); - t += cnt[root]; - } - } - } - ans = Math.max(ans, t); - } - } - } - return ans; - } - - private void dfs(int i, int j) { - p[i][j] = root; - ++cnt[root]; - ans = Math.max(ans, cnt[root]); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 1 && p[x][y] == 0) { - dfs(x, y); - } - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -382,66 +263,6 @@ public: }; ``` -```cpp -class Solution { -public: - const static inline vector dirs = {-1, 0, 1, 0, -1}; - - int largestIsland(vector>& grid) { - int n = grid.size(); - int ans = 0; - int root = 0; - vector> p(n, vector(n)); - vector cnt(n * n + 1); - - function dfs; - dfs = [&](int i, int j) { - p[i][j] = root; - ++cnt[root]; - ans = max(ans, cnt[root]); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] && p[x][y] == 0) { - dfs(x, y); - } - } - }; - - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] && p[i][j] == 0) { - ++root; - dfs(i, j); - } - } - } - - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (!grid[i][j]) { - int t = 1; - unordered_set vis; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < n && y >= 0 && y < n) { - int root = p[x][y]; - if (!vis.count(root)) { - vis.insert(root); - t += cnt[root]; - } - } - } - ans = max(ans, t); - } - } - } - return ans; - } -}; -``` - -### **Go** - ```go func largestIsland(grid [][]int) int { n := len(grid) @@ -500,63 +321,6 @@ func largestIsland(grid [][]int) int { } ``` -```go -func largestIsland(grid [][]int) int { - n := len(grid) - p := make([][]int, n) - for i := range p { - p[i] = make([]int, n) - } - cnt := make([]int, n*n+1) - dirs := []int{-1, 0, 1, 0, -1} - ans, root := 0, 0 - - var dfs func(i, j int) - dfs = func(i, j int) { - p[i][j] = root - cnt[root]++ - ans = max(ans, cnt[root]) - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 1 && p[x][y] == 0 { - dfs(x, y) - } - } - } - - for i, row := range grid { - for j, v := range row { - if v == 1 && p[i][j] == 0 { - root++ - dfs(i, j) - } - } - } - for i, row := range grid { - for j, v := range row { - if v == 0 { - t := 1 - vis := map[int]struct{}{} - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < n && y >= 0 && y < n { - root := p[x][y] - if _, ok := vis[root]; !ok { - vis[root] = struct{}{} - t += cnt[root] - } - } - } - ans = max(ans, t) - } - } - } - return ans -} -``` - -### **TypeScript** - ```ts function largestIsland(grid: number[][]): number { const n = grid.length; @@ -618,8 +382,6 @@ function largestIsland(grid: number[][]): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -701,10 +463,230 @@ impl Solution { } ``` -### **...** + + +### 方法二:DFS + +我们也可以通过 DFS,找到每个岛屿。 + +同一个岛屿中的所有点都属于同一个集合,我们可以用不同的 `root` 值标识不同的岛屿,用 $p$ 记录每个 $grid[i][j]$ 对应的 `root` 值,用 $cnt$ 记录每个岛屿的面积。 + +遍历 `grid`,对于每个 $0$,我们统计相邻的四个点中 $1$ 所在的岛屿(与方法一不同的是,我们这里直接取 $p[i][j]$ 作为 `root`),累加去重后的岛屿面积,更新最大值。 + +时间复杂度 $O(n^2)$。其中 $n$ 为矩阵 `grid` 的边长。 + + + +```python +class Solution: + def largestIsland(self, grid: List[List[int]]) -> int: + def dfs(i, j): + p[i][j] = root + cnt[root] += 1 + for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: + x, y = i + a, j + b + if 0 <= x < n and 0 <= y < n and grid[x][y] and p[x][y] == 0: + dfs(x, y) + + n = len(grid) + cnt = Counter() + p = [[0] * n for _ in range(n)] + root = 0 + for i, row in enumerate(grid): + for j, v in enumerate(row): + if v and p[i][j] == 0: + root += 1 + dfs(i, j) + ans = max(cnt.values(), default=0) + for i, row in enumerate(grid): + for j, v in enumerate(row): + if v == 0: + t = 1 + vis = set() + for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: + x, y = i + a, j + b + if 0 <= x < n and 0 <= y < n: + root = p[x][y] + if root not in vis: + vis.add(root) + t += cnt[root] + ans = max(ans, t) + return ans ``` +```java +class Solution { + private int n; + private int ans; + private int root; + private int[][] p; + private int[][] grid; + private int[] cnt; + private int[] dirs = new int[] {-1, 0, 1, 0, -1}; + + public int largestIsland(int[][] grid) { + n = grid.length; + cnt = new int[n * n + 1]; + p = new int[n][n]; + this.grid = grid; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 1 && p[i][j] == 0) { + ++root; + dfs(i, j); + } + } + } + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 0) { + int t = 1; + Set vis = new HashSet<>(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n) { + int root = p[x][y]; + if (!vis.contains(root)) { + vis.add(root); + t += cnt[root]; + } + } + } + ans = Math.max(ans, t); + } + } + } + return ans; + } + + private void dfs(int i, int j) { + p[i][j] = root; + ++cnt[root]; + ans = Math.max(ans, cnt[root]); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 1 && p[x][y] == 0) { + dfs(x, y); + } + } + } +} +``` + +```cpp +class Solution { +public: + const static inline vector dirs = {-1, 0, 1, 0, -1}; + + int largestIsland(vector>& grid) { + int n = grid.size(); + int ans = 0; + int root = 0; + vector> p(n, vector(n)); + vector cnt(n * n + 1); + + function dfs; + dfs = [&](int i, int j) { + p[i][j] = root; + ++cnt[root]; + ans = max(ans, cnt[root]); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] && p[x][y] == 0) { + dfs(x, y); + } + } + }; + + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] && p[i][j] == 0) { + ++root; + dfs(i, j); + } + } + } + + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (!grid[i][j]) { + int t = 1; + unordered_set vis; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n) { + int root = p[x][y]; + if (!vis.count(root)) { + vis.insert(root); + t += cnt[root]; + } + } + } + ans = max(ans, t); + } + } + } + return ans; + } +}; +``` + +```go +func largestIsland(grid [][]int) int { + n := len(grid) + p := make([][]int, n) + for i := range p { + p[i] = make([]int, n) + } + cnt := make([]int, n*n+1) + dirs := []int{-1, 0, 1, 0, -1} + ans, root := 0, 0 + + var dfs func(i, j int) + dfs = func(i, j int) { + p[i][j] = root + cnt[root]++ + ans = max(ans, cnt[root]) + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 1 && p[x][y] == 0 { + dfs(x, y) + } + } + } + + for i, row := range grid { + for j, v := range row { + if v == 1 && p[i][j] == 0 { + root++ + dfs(i, j) + } + } + } + for i, row := range grid { + for j, v := range row { + if v == 0 { + t := 1 + vis := map[int]struct{}{} + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < n && y >= 0 && y < n { + root := p[x][y] + if _, ok := vis[root]; !ok { + vis[root] = struct{}{} + t += cnt[root] + } + } + } + ans = max(ans, t) + } + } + } + return ans +} ``` + + diff --git a/solution/0800-0899/0827.Making A Large Island/README_EN.md b/solution/0800-0899/0827.Making A Large Island/README_EN.md index 65279c9011f69..021bb0aa2090f 100644 --- a/solution/0800-0899/0827.Making A Large Island/README_EN.md +++ b/solution/0800-0899/0827.Making A Large Island/README_EN.md @@ -46,12 +46,10 @@ ## Solutions -Union find. +### Solution 1 -### **Python3** - ```python class Solution: def largestIsland(self, grid: List[List[int]]) -> int: @@ -94,46 +92,6 @@ class Solution: return ans ``` -```python -class Solution: - def largestIsland(self, grid: List[List[int]]) -> int: - def dfs(i, j): - p[i][j] = root - cnt[root] += 1 - for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: - x, y = i + a, j + b - if 0 <= x < n and 0 <= y < n and grid[x][y] and p[x][y] == 0: - dfs(x, y) - - n = len(grid) - cnt = Counter() - p = [[0] * n for _ in range(n)] - root = 0 - for i, row in enumerate(grid): - for j, v in enumerate(row): - if v and p[i][j] == 0: - root += 1 - dfs(i, j) - - ans = max(cnt.values(), default=0) - for i, row in enumerate(grid): - for j, v in enumerate(row): - if v == 0: - t = 1 - vis = set() - for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: - x, y = i + a, j + b - if 0 <= x < n and 0 <= y < n: - root = p[x][y] - if root not in vis: - vis.add(root) - t += cnt[root] - ans = max(ans, t) - return ans -``` - -### **Java** - ```java class Solution { private int n; @@ -199,67 +157,6 @@ class Solution { } ``` -```java -class Solution { - private int n; - private int ans; - private int root; - private int[][] p; - private int[][] grid; - private int[] cnt; - private int[] dirs = new int[] {-1, 0, 1, 0, -1}; - - public int largestIsland(int[][] grid) { - n = grid.length; - cnt = new int[n * n + 1]; - p = new int[n][n]; - this.grid = grid; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == 1 && p[i][j] == 0) { - ++root; - dfs(i, j); - } - } - } - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == 0) { - int t = 1; - Set vis = new HashSet<>(); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < n && y >= 0 && y < n) { - int root = p[x][y]; - if (!vis.contains(root)) { - vis.add(root); - t += cnt[root]; - } - } - } - ans = Math.max(ans, t); - } - } - } - return ans; - } - - private void dfs(int i, int j) { - p[i][j] = root; - ++cnt[root]; - ans = Math.max(ans, cnt[root]); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 1 && p[x][y] == 0) { - dfs(x, y); - } - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -320,66 +217,6 @@ public: }; ``` -```cpp -class Solution { -public: - const static inline vector dirs = {-1, 0, 1, 0, -1}; - - int largestIsland(vector>& grid) { - int n = grid.size(); - int ans = 0; - int root = 0; - vector> p(n, vector(n)); - vector cnt(n * n + 1); - - function dfs; - dfs = [&](int i, int j) { - p[i][j] = root; - ++cnt[root]; - ans = max(ans, cnt[root]); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] && p[x][y] == 0) { - dfs(x, y); - } - } - }; - - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] && p[i][j] == 0) { - ++root; - dfs(i, j); - } - } - } - - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (!grid[i][j]) { - int t = 1; - unordered_set vis; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < n && y >= 0 && y < n) { - int root = p[x][y]; - if (!vis.count(root)) { - vis.insert(root); - t += cnt[root]; - } - } - } - ans = max(ans, t); - } - } - } - return ans; - } -}; -``` - -### **Go** - ```go func largestIsland(grid [][]int) int { n := len(grid) @@ -438,63 +275,6 @@ func largestIsland(grid [][]int) int { } ``` -```go -func largestIsland(grid [][]int) int { - n := len(grid) - p := make([][]int, n) - for i := range p { - p[i] = make([]int, n) - } - cnt := make([]int, n*n+1) - dirs := []int{-1, 0, 1, 0, -1} - ans, root := 0, 0 - - var dfs func(i, j int) - dfs = func(i, j int) { - p[i][j] = root - cnt[root]++ - ans = max(ans, cnt[root]) - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 1 && p[x][y] == 0 { - dfs(x, y) - } - } - } - - for i, row := range grid { - for j, v := range row { - if v == 1 && p[i][j] == 0 { - root++ - dfs(i, j) - } - } - } - for i, row := range grid { - for j, v := range row { - if v == 0 { - t := 1 - vis := map[int]struct{}{} - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < n && y >= 0 && y < n { - root := p[x][y] - if _, ok := vis[root]; !ok { - vis[root] = struct{}{} - t += cnt[root] - } - } - } - ans = max(ans, t) - } - } - } - return ans -} -``` - -### **TypeScript** - ```ts function largestIsland(grid: number[][]): number { const n = grid.length; @@ -556,8 +336,6 @@ function largestIsland(grid: number[][]): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -639,10 +417,222 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def largestIsland(self, grid: List[List[int]]) -> int: + def dfs(i, j): + p[i][j] = root + cnt[root] += 1 + for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: + x, y = i + a, j + b + if 0 <= x < n and 0 <= y < n and grid[x][y] and p[x][y] == 0: + dfs(x, y) + + n = len(grid) + cnt = Counter() + p = [[0] * n for _ in range(n)] + root = 0 + for i, row in enumerate(grid): + for j, v in enumerate(row): + if v and p[i][j] == 0: + root += 1 + dfs(i, j) + ans = max(cnt.values(), default=0) + for i, row in enumerate(grid): + for j, v in enumerate(row): + if v == 0: + t = 1 + vis = set() + for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: + x, y = i + a, j + b + if 0 <= x < n and 0 <= y < n: + root = p[x][y] + if root not in vis: + vis.add(root) + t += cnt[root] + ans = max(ans, t) + return ans ``` +```java +class Solution { + private int n; + private int ans; + private int root; + private int[][] p; + private int[][] grid; + private int[] cnt; + private int[] dirs = new int[] {-1, 0, 1, 0, -1}; + + public int largestIsland(int[][] grid) { + n = grid.length; + cnt = new int[n * n + 1]; + p = new int[n][n]; + this.grid = grid; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 1 && p[i][j] == 0) { + ++root; + dfs(i, j); + } + } + } + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 0) { + int t = 1; + Set vis = new HashSet<>(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n) { + int root = p[x][y]; + if (!vis.contains(root)) { + vis.add(root); + t += cnt[root]; + } + } + } + ans = Math.max(ans, t); + } + } + } + return ans; + } + + private void dfs(int i, int j) { + p[i][j] = root; + ++cnt[root]; + ans = Math.max(ans, cnt[root]); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 1 && p[x][y] == 0) { + dfs(x, y); + } + } + } +} +``` + +```cpp +class Solution { +public: + const static inline vector dirs = {-1, 0, 1, 0, -1}; + + int largestIsland(vector>& grid) { + int n = grid.size(); + int ans = 0; + int root = 0; + vector> p(n, vector(n)); + vector cnt(n * n + 1); + + function dfs; + dfs = [&](int i, int j) { + p[i][j] = root; + ++cnt[root]; + ans = max(ans, cnt[root]); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] && p[x][y] == 0) { + dfs(x, y); + } + } + }; + + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] && p[i][j] == 0) { + ++root; + dfs(i, j); + } + } + } + + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (!grid[i][j]) { + int t = 1; + unordered_set vis; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < n && y >= 0 && y < n) { + int root = p[x][y]; + if (!vis.count(root)) { + vis.insert(root); + t += cnt[root]; + } + } + } + ans = max(ans, t); + } + } + } + return ans; + } +}; +``` + +```go +func largestIsland(grid [][]int) int { + n := len(grid) + p := make([][]int, n) + for i := range p { + p[i] = make([]int, n) + } + cnt := make([]int, n*n+1) + dirs := []int{-1, 0, 1, 0, -1} + ans, root := 0, 0 + + var dfs func(i, j int) + dfs = func(i, j int) { + p[i][j] = root + cnt[root]++ + ans = max(ans, cnt[root]) + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 1 && p[x][y] == 0 { + dfs(x, y) + } + } + } + + for i, row := range grid { + for j, v := range row { + if v == 1 && p[i][j] == 0 { + root++ + dfs(i, j) + } + } + } + for i, row := range grid { + for j, v := range row { + if v == 0 { + t := 1 + vis := map[int]struct{}{} + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < n && y >= 0 && y < n { + root := p[x][y] + if _, ok := vis[root]; !ok { + vis[root] = struct{}{} + t += cnt[root] + } + } + } + ans = max(ans, t) + } + } + } + return ans +} ``` + + diff --git a/solution/0800-0899/0828.Count Unique Characters of All Substrings of a Given String/README.md b/solution/0800-0899/0828.Count Unique Characters of All Substrings of a Given String/README.md index 2a17c2cfad008..55d08aacbbed2 100644 --- a/solution/0800-0899/0828.Count Unique Characters of All Substrings of a Given String/README.md +++ b/solution/0800-0899/0828.Count Unique Characters of All Substrings of a Given String/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:计算每个字符的贡献** +### 方法一:计算每个字符的贡献 对于字符串 $s$ 的每个字符 $c_i$,当它在某个子字符串中仅出现一次时,它会对这个子字符串统计唯一字符时有贡献。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def uniqueLetterString(self, s: str) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int uniqueLetterString(String s) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func uniqueLetterString(s string) (ans int) { d := make([][]int, 26) @@ -156,8 +142,6 @@ func uniqueLetterString(s string) (ans int) { } ``` -### **TypeScript** - ```ts function uniqueLetterString(s: string): number { const d: number[][] = Array.from({ length: 26 }, () => [-1]); @@ -176,8 +160,6 @@ function uniqueLetterString(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn unique_letter_string(s: String) -> i32 { @@ -197,10 +179,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0828.Count Unique Characters of All Substrings of a Given String/README_EN.md b/solution/0800-0899/0828.Count Unique Characters of All Substrings of a Given String/README_EN.md index 2a79ae28bf477..760e56f66e596 100644 --- a/solution/0800-0899/0828.Count Unique Characters of All Substrings of a Given String/README_EN.md +++ b/solution/0800-0899/0828.Count Unique Characters of All Substrings of a Given String/README_EN.md @@ -50,7 +50,7 @@ Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 ## Solutions -**Solution 1: Calculate the Contribution of Each Character** +### Solution 1: Calculate the Contribution of Each Character For each character $c_i$ in the string $s$, when it appears only once in a substring, it contributes to the count of unique characters in that substring. @@ -64,8 +64,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def uniqueLetterString(self, s: str) -> int: @@ -80,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int uniqueLetterString(String s) { @@ -105,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +121,6 @@ public: }; ``` -### **Go** - ```go func uniqueLetterString(s string) (ans int) { d := make([][]int, 26) @@ -148,8 +140,6 @@ func uniqueLetterString(s string) (ans int) { } ``` -### **TypeScript** - ```ts function uniqueLetterString(s: string): number { const d: number[][] = Array.from({ length: 26 }, () => [-1]); @@ -168,8 +158,6 @@ function uniqueLetterString(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn unique_letter_string(s: String) -> i32 { @@ -189,10 +177,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0829.Consecutive Numbers Sum/README.md b/solution/0800-0899/0829.Consecutive Numbers Sum/README.md index f882a6dca2574..12f1c2f0932df 100644 --- a/solution/0800-0899/0829.Consecutive Numbers Sum/README.md +++ b/solution/0800-0899/0829.Consecutive Numbers Sum/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:数学推导** +### 方法一:数学推导 连续正整数构成一个等差数列($d=1$)。我们假设等差数列的第一项为 $a$,项数为 $k$,则 $n=(a+a+k-1)*k/2$,即 $n*2=(a*2+k-1)*k$ ①。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def consecutiveNumbersSum(self, n: int) -> int: @@ -73,10 +67,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +99,6 @@ public: }; ``` -### **Go** - ```go func consecutiveNumbersSum(n int) int { n <<= 1 @@ -126,10 +112,6 @@ func consecutiveNumbersSum(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0829.Consecutive Numbers Sum/README_EN.md b/solution/0800-0899/0829.Consecutive Numbers Sum/README_EN.md index d7bcd40a7725c..dfed1c5c43980 100644 --- a/solution/0800-0899/0829.Consecutive Numbers Sum/README_EN.md +++ b/solution/0800-0899/0829.Consecutive Numbers Sum/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,10 +56,9 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { + public int consecutiveNumbersSum(int n) { n <<= 1; int ans = 0; @@ -73,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +88,6 @@ public: }; ``` -### **Go** - ```go func consecutiveNumbersSum(n int) int { n <<= 1 @@ -106,10 +101,6 @@ func consecutiveNumbersSum(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0830.Positions of Large Groups/README.md b/solution/0800-0899/0830.Positions of Large Groups/README.md index 3d8368261b438..4b73ea5e16a41 100644 --- a/solution/0800-0899/0830.Positions of Large Groups/README.md +++ b/solution/0800-0899/0830.Positions of Large Groups/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们用双指针 $i$ 和 $j$ 找到每个分组的起始位置和终止位置,然后判断分组长度是否大于等于 $3$,若是则将其加入结果数组。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> largeGroupPositions(String s) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func largeGroupPositions(s string) [][]int { i, n := 0, len(s) @@ -155,10 +141,6 @@ func largeGroupPositions(s string) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0830.Positions of Large Groups/README_EN.md b/solution/0800-0899/0830.Positions of Large Groups/README_EN.md index c3d554dadde40..089fd1b7fa5c9 100644 --- a/solution/0800-0899/0830.Positions of Large Groups/README_EN.md +++ b/solution/0800-0899/0830.Positions of Large Groups/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List> largeGroupPositions(String s) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +111,6 @@ public: }; ``` -### **Go** - ```go func largeGroupPositions(s string) [][]int { i, n := 0, len(s) @@ -135,10 +129,6 @@ func largeGroupPositions(s string) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0831.Masking Personal Information/README.md b/solution/0800-0899/0831.Masking Personal Information/README.md index 851e0fe4d24ff..ed52f3df3e09f 100644 --- a/solution/0800-0899/0831.Masking Personal Information/README.md +++ b/solution/0800-0899/0831.Masking Personal Information/README.md @@ -109,9 +109,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 根据题目描述,我们可以先判断字符串 $s$ 是电子邮件还是电话号码,然后分别处理。 @@ -119,10 +117,6 @@ -### **Python3** - - - ```python class Solution: def maskPII(self, s: str) -> str: @@ -135,10 +129,6 @@ class Solution: return suf if cnt == 0 else f'+{"*" * cnt}-{suf}' ``` -### **Java** - - - ```java class Solution { public String maskPII(String s) { @@ -163,8 +153,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -192,8 +180,6 @@ public: }; ``` -### **Go** - ```go func maskPII(s string) string { i := strings.Index(s, "@") @@ -217,8 +203,6 @@ func maskPII(s string) string { } ``` -### **TypeScript** - ```ts function maskPII(s: string): string { const i = s.indexOf('@'); @@ -241,10 +225,6 @@ function maskPII(s: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0831.Masking Personal Information/README_EN.md b/solution/0800-0899/0831.Masking Personal Information/README_EN.md index f0cdb4bb6d611..ca783a3d17344 100644 --- a/solution/0800-0899/0831.Masking Personal Information/README_EN.md +++ b/solution/0800-0899/0831.Masking Personal Information/README_EN.md @@ -100,9 +100,9 @@ Thus, the resulting masked number is "***-***-7890". ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -116,8 +116,6 @@ class Solution: return suf if cnt == 0 else f'+{"*" * cnt}-{suf}' ``` -### **Java** - ```java class Solution { public String maskPII(String s) { @@ -142,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +167,6 @@ public: }; ``` -### **Go** - ```go func maskPII(s string) string { i := strings.Index(s, "@") @@ -196,8 +190,6 @@ func maskPII(s string) string { } ``` -### **TypeScript** - ```ts function maskPII(s: string): string { const i = s.indexOf('@'); @@ -220,10 +212,6 @@ function maskPII(s: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0832.Flipping an Image/README.md b/solution/0800-0899/0832.Flipping an Image/README.md index dd8fda26c6eaa..42c2be6147045 100644 --- a/solution/0800-0899/0832.Flipping an Image/README.md +++ b/solution/0800-0899/0832.Flipping an Image/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们可以遍历矩阵,对于遍历到的每一行 $row$: @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: @@ -89,10 +83,6 @@ class Solution: return image ``` -### **Java** - - - ```java class Solution { public int[][] flipAndInvertImage(int[][] image) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func flipAndInvertImage(image [][]int) [][]int { for _, row := range image { @@ -156,8 +142,6 @@ func flipAndInvertImage(image [][]int) [][]int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} image @@ -181,10 +165,6 @@ var flipAndInvertImage = function (image) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0832.Flipping an Image/README_EN.md b/solution/0800-0899/0832.Flipping an Image/README_EN.md index 3c0e111a4b5fa..f3d3a3161853a 100644 --- a/solution/0800-0899/0832.Flipping an Image/README_EN.md +++ b/solution/0800-0899/0832.Flipping an Image/README_EN.md @@ -49,9 +49,9 @@ Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return image ``` -### **Java** - ```java class Solution { public int[][] flipAndInvertImage(int[][] image) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +110,6 @@ public: }; ``` -### **Go** - ```go func flipAndInvertImage(image [][]int) [][]int { for _, row := range image { @@ -134,8 +128,6 @@ func flipAndInvertImage(image [][]int) [][]int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} image @@ -159,10 +151,6 @@ var flipAndInvertImage = function (image) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0833.Find And Replace in String/README.md b/solution/0800-0899/0833.Find And Replace in String/README.md index 624183e777c3f..6a7b923e0e7ea 100644 --- a/solution/0800-0899/0833.Find And Replace in String/README.md +++ b/solution/0800-0899/0833.Find And Replace in String/README.md @@ -68,9 +68,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们遍历每个替换操作,对于当前第 $k$ 个替换操作 $(i, src)$,如果 $s[i..i+|src|-1]$ 与 $src$ 相等,此时我们记录下标 $i$ 处需要替换的是 $targets$ 的第 $k$ 个字符串,否则不需要替换。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def findReplaceString( @@ -106,10 +100,6 @@ class Solution: return "".join(ans) ``` -### **Java** - - - ```java class Solution { public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) { @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +152,6 @@ public: }; ``` -### **Go** - ```go func findReplaceString(s string, indices []int, sources []string, targets []string) string { n := len(s) @@ -189,8 +175,6 @@ func findReplaceString(s string, indices []int, sources []string, targets []stri } ``` -### **TypeScript** - ```ts function findReplaceString( s: string, @@ -219,10 +203,6 @@ function findReplaceString( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0833.Find And Replace in String/README_EN.md b/solution/0800-0899/0833.Find And Replace in String/README_EN.md index 35d79f6e5de62..5fc579039c20d 100644 --- a/solution/0800-0899/0833.Find And Replace in String/README_EN.md +++ b/solution/0800-0899/0833.Find And Replace in String/README_EN.md @@ -62,9 +62,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -88,8 +88,6 @@ class Solution: return "".join(ans) ``` -### **Java** - ```java class Solution { public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) { @@ -116,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +140,6 @@ public: }; ``` -### **Go** - ```go func findReplaceString(s string, indices []int, sources []string, targets []string) string { n := len(s) @@ -169,8 +163,6 @@ func findReplaceString(s string, indices []int, sources []string, targets []stri } ``` -### **TypeScript** - ```ts function findReplaceString( s: string, @@ -199,10 +191,6 @@ function findReplaceString( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0834.Sum of Distances in Tree/README.md b/solution/0800-0899/0834.Sum of Distances in Tree/README.md index ad8b0636a94a3..37e0f939b7dad 100644 --- a/solution/0800-0899/0834.Sum of Distances in Tree/README.md +++ b/solution/0800-0899/0834.Sum of Distances in Tree/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:树形 DP(换根)** +### 方法一:树形 DP(换根) 我们先跑一遍 DFS,计算出每个节点的子树大小,记录在数组 $size$ 中,并且统计出节点 $0$ 到其他节点的距离之和,记录在 $ans[0]$ 中。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]: @@ -104,10 +98,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int n; @@ -153,8 +143,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -195,8 +183,6 @@ public: }; ``` -### **Go** - ```go func sumOfDistancesInTree(n int, edges [][]int) []int { g := make([][]int, n) @@ -233,8 +219,6 @@ func sumOfDistancesInTree(n int, edges [][]int) []int { } ``` -### **TypeScript** - ```ts function sumOfDistancesInTree(n: number, edges: number[][]): number[] { const g: number[][] = Array.from({ length: n }, () => []); @@ -268,10 +252,6 @@ function sumOfDistancesInTree(n: number, edges: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0834.Sum of Distances in Tree/README_EN.md b/solution/0800-0899/0834.Sum of Distances in Tree/README_EN.md index 3d409405bc735..0c671e360a4ed 100644 --- a/solution/0800-0899/0834.Sum of Distances in Tree/README_EN.md +++ b/solution/0800-0899/0834.Sum of Distances in Tree/README_EN.md @@ -50,9 +50,9 @@ Hence, answer[0] = 8, and so on. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,8 +83,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int n; @@ -130,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -172,8 +168,6 @@ public: }; ``` -### **Go** - ```go func sumOfDistancesInTree(n int, edges [][]int) []int { g := make([][]int, n) @@ -210,8 +204,6 @@ func sumOfDistancesInTree(n int, edges [][]int) []int { } ``` -### **TypeScript** - ```ts function sumOfDistancesInTree(n: number, edges: number[][]): number[] { const g: number[][] = Array.from({ length: n }, () => []); @@ -245,10 +237,6 @@ function sumOfDistancesInTree(n: number, edges: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0835.Image Overlap/README.md b/solution/0800-0899/0835.Image Overlap/README.md index 7e26dcd792d5c..da288592240fd 100644 --- a/solution/0800-0899/0835.Image Overlap/README.md +++ b/solution/0800-0899/0835.Image Overlap/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举 $img1$ 和 $img2$ 的每个 $1$ 的位置,分别记为 $(i, j)$ 和 $(h, k)$。然后我们计算得到偏移量 $(i - h, j - k)$,记为 $(dx, dy)$,用哈希表 $cnt$ 记录每个偏移量出现的次数。最后我们遍历哈希表 $cnt$,找到出现次数最多的偏移量,即为答案。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int: @@ -88,10 +82,6 @@ class Solution: return max(cnt.values()) if cnt else 0 ``` -### **Java** - - - ```java class Solution { public int largestOverlap(int[][] img1, int[][] img2) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func largestOverlap(img1 [][]int, img2 [][]int) (ans int) { type pair struct{ x, y int } @@ -169,8 +155,6 @@ func largestOverlap(img1 [][]int, img2 [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function largestOverlap(img1: number[][], img2: number[][]): number { const n = img1.length; @@ -195,10 +179,6 @@ function largestOverlap(img1: number[][], img2: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0835.Image Overlap/README_EN.md b/solution/0800-0899/0835.Image Overlap/README_EN.md index 82aec579704bc..871f5e4fd09e2 100644 --- a/solution/0800-0899/0835.Image Overlap/README_EN.md +++ b/solution/0800-0899/0835.Image Overlap/README_EN.md @@ -51,9 +51,9 @@ The number of positions that have a 1 in both images is 3 (shown in red). ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return max(cnt.values()) if cnt else 0 ``` -### **Java** - ```java class Solution { public int largestOverlap(int[][] img1, int[][] img2) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +120,6 @@ public: }; ``` -### **Go** - ```go func largestOverlap(img1 [][]int, img2 [][]int) (ans int) { type pair struct{ x, y int } @@ -149,8 +143,6 @@ func largestOverlap(img1 [][]int, img2 [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function largestOverlap(img1: number[][], img2: number[][]): number { const n = img1.length; @@ -175,10 +167,6 @@ function largestOverlap(img1: number[][], img2: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0836.Rectangle Overlap/README.md b/solution/0800-0899/0836.Rectangle Overlap/README.md index 8ea99ed24e464..161bc8529f4d4 100644 --- a/solution/0800-0899/0836.Rectangle Overlap/README.md +++ b/solution/0800-0899/0836.Rectangle Overlap/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:判断不重叠的情况** +### 方法一:判断不重叠的情况 我们记矩形 $rec1$ 的坐标点为 $(x_1, y_1, x_2, y_2)$,矩形 $rec2$ 的坐标点为 $(x_3, y_3, x_4, y_4)$。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool: @@ -79,10 +73,6 @@ class Solution: return not (y3 >= y2 or y4 <= y1 or x3 >= x2 or x4 <= x1) ``` -### **Java** - - - ```java class Solution { public boolean isRectangleOverlap(int[] rec1, int[] rec2) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +94,6 @@ public: }; ``` -### **Go** - ```go func isRectangleOverlap(rec1 []int, rec2 []int) bool { x1, y1, x2, y2 := rec1[0], rec1[1], rec1[2], rec1[3] @@ -116,10 +102,6 @@ func isRectangleOverlap(rec1 []int, rec2 []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0836.Rectangle Overlap/README_EN.md b/solution/0800-0899/0836.Rectangle Overlap/README_EN.md index ccbab1255bbac..30499d950ebbc 100644 --- a/solution/0800-0899/0836.Rectangle Overlap/README_EN.md +++ b/solution/0800-0899/0836.Rectangle Overlap/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -45,8 +45,6 @@ class Solution: return not (y3 >= y2 or y4 <= y1 or x3 >= x2 or x4 <= x1) ``` -### **Java** - ```java class Solution { public boolean isRectangleOverlap(int[] rec1, int[] rec2) { @@ -57,8 +55,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -70,8 +66,6 @@ public: }; ``` -### **Go** - ```go func isRectangleOverlap(rec1 []int, rec2 []int) bool { x1, y1, x2, y2 := rec1[0], rec1[1], rec1[2], rec1[3] @@ -80,10 +74,6 @@ func isRectangleOverlap(rec1 []int, rec2 []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0837.New 21 Game/README.md b/solution/0800-0899/0837.New 21 Game/README.md index ef940e7e4a0bc..2aa56abb638d0 100644 --- a/solution/0800-0899/0837.New 21 Game/README.md +++ b/solution/0800-0899/0837.New 21 Game/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i)$,表示当前分数为 $i$ 时,到最终停止抽取数字时,分数不超过 $n$ 的概率。那么答案就是 $dfs(0)$。 @@ -129,26 +127,8 @@ $$ 时间复杂度 $O(k + maxPts)$,空间复杂度 $O(k + maxPts)$。其中 $k$ 为最大分数。 -**方法二:动态规划** - -我们可以将方法一中的记忆化搜索改成动态规划。 - -定义 $f[i]$ 表示当前分数为 $i$ 时,到最终停止抽取数字时,分数不超过 $n$ 的概率。那么答案就是 $f[0]$。 - -当 $k \leq i \leq \min(n, k + maxPts - 1)$ 时,有 $f[i] = 1$。 - -当 $i = k - 1$ 时,有 $f[i] = \min(n-k+1, maxPts) / maxPts$。 - -当 $i \lt k - 1$ 时,有 $f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts$。 - -时间复杂度 $O(k + maxPts)$,空间复杂度 $O(k + maxPts)$。其中 $k$ 为最大分数。 - -### **Python3** - - - ```python class Solution: def new21Game(self, n: int, k: int, maxPts: int) -> float: @@ -163,22 +143,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def new21Game(self, n: int, k: int, maxPts: int) -> float: - f = [0] * (k + maxPts) - for i in range(k, min(n + 1, k + maxPts)): - f[i] = 1 - f[k - 1] = min(n - k + 1, maxPts) / maxPts - for i in range(k - 2, -1, -1): - f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts - return f[0] -``` - -### **Java** - - - ```java class Solution { private double[] f; @@ -207,27 +171,6 @@ class Solution { } ``` -```java -class Solution { - public double new21Game(int n, int k, int maxPts) { - if (k == 0) { - return 1.0; - } - double[] f = new double[k + maxPts]; - for (int i = k; i < Math.min(n + 1, k + maxPts); ++i) { - f[i] = 1; - } - f[k - 1] = Math.min(n - k + 1, maxPts) * 1.0 / maxPts; - for (int i = k - 2; i >= 0; --i) { - f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts; - } - return f[0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -250,29 +193,6 @@ public: }; ``` -```cpp -class Solution { -public: - double new21Game(int n, int k, int maxPts) { - if (k == 0) { - return 1.0; - } - double f[k + maxPts]; - memset(f, 0, sizeof(f)); - for (int i = k; i < min(n + 1, k + maxPts); ++i) { - f[i] = 1; - } - f[k - 1] = min(n - k + 1, maxPts) * 1.0 / maxPts; - for (int i = k - 2; i >= 0; --i) { - f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts; - } - return f[0]; - } -}; -``` - -### **Go** - ```go func new21Game(n int, k int, maxPts int) float64 { f := make([]float64, k) @@ -297,25 +217,6 @@ func new21Game(n int, k int, maxPts int) float64 { } ``` -```go -func new21Game(n int, k int, maxPts int) float64 { - if k == 0 { - return 1 - } - f := make([]float64, k+maxPts) - for i := k; i < min(n+1, k+maxPts); i++ { - f[i] = 1 - } - f[k-1] = float64(min(n-k+1, maxPts)) / float64(maxPts) - for i := k - 2; i >= 0; i-- { - f[i] = f[i+1] + (f[i+1]-f[i+maxPts+1])/float64(maxPts) - } - return f[0] -} -``` - -### **TypeScript** - ```ts function new21Game(n: number, k: number, maxPts: number): number { const f = new Array(k).fill(0); @@ -335,6 +236,93 @@ function new21Game(n: number, k: number, maxPts: number): number { } ``` + + +### 方法二:动态规划 + +我们可以将方法一中的记忆化搜索改成动态规划。 + +定义 $f[i]$ 表示当前分数为 $i$ 时,到最终停止抽取数字时,分数不超过 $n$ 的概率。那么答案就是 $f[0]$。 + +当 $k \leq i \leq \min(n, k + maxPts - 1)$ 时,有 $f[i] = 1$。 + +当 $i = k - 1$ 时,有 $f[i] = \min(n-k+1, maxPts) / maxPts$。 + +当 $i \lt k - 1$ 时,有 $f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts$。 + +时间复杂度 $O(k + maxPts)$,空间复杂度 $O(k + maxPts)$。其中 $k$ 为最大分数。 + + + +```python +class Solution: + def new21Game(self, n: int, k: int, maxPts: int) -> float: + f = [0] * (k + maxPts) + for i in range(k, min(n + 1, k + maxPts)): + f[i] = 1 + f[k - 1] = min(n - k + 1, maxPts) / maxPts + for i in range(k - 2, -1, -1): + f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts + return f[0] +``` + +```java +class Solution { + public double new21Game(int n, int k, int maxPts) { + if (k == 0) { + return 1.0; + } + double[] f = new double[k + maxPts]; + for (int i = k; i < Math.min(n + 1, k + maxPts); ++i) { + f[i] = 1; + } + f[k - 1] = Math.min(n - k + 1, maxPts) * 1.0 / maxPts; + for (int i = k - 2; i >= 0; --i) { + f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts; + } + return f[0]; + } +} +``` + +```cpp +class Solution { +public: + double new21Game(int n, int k, int maxPts) { + if (k == 0) { + return 1.0; + } + double f[k + maxPts]; + memset(f, 0, sizeof(f)); + for (int i = k; i < min(n + 1, k + maxPts); ++i) { + f[i] = 1; + } + f[k - 1] = min(n - k + 1, maxPts) * 1.0 / maxPts; + for (int i = k - 2; i >= 0; --i) { + f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts; + } + return f[0]; + } +}; +``` + +```go +func new21Game(n int, k int, maxPts int) float64 { + if k == 0 { + return 1 + } + f := make([]float64, k+maxPts) + for i := k; i < min(n+1, k+maxPts); i++ { + f[i] = 1 + } + f[k-1] = float64(min(n-k+1, maxPts)) / float64(maxPts) + for i := k - 2; i >= 0; i-- { + f[i] = f[i+1] + (f[i+1]-f[i+maxPts+1])/float64(maxPts) + } + return f[0] +} +``` + ```ts function new21Game(n: number, k: number, maxPts: number): number { if (k === 0) { @@ -352,10 +340,6 @@ function new21Game(n: number, k: number, maxPts: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0837.New 21 Game/README_EN.md b/solution/0800-0899/0837.New 21 Game/README_EN.md index 81664f08a2529..8bd18ae86b897 100644 --- a/solution/0800-0899/0837.New 21 Game/README_EN.md +++ b/solution/0800-0899/0837.New 21 Game/README_EN.md @@ -49,9 +49,9 @@ In 6 out of 10 possibilities, she is at or below 6 points. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,20 +67,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def new21Game(self, n: int, k: int, maxPts: int) -> float: - f = [0] * (k + maxPts) - for i in range(k, min(n + 1, k + maxPts)): - f[i] = 1 - f[k - 1] = min(n - k + 1, maxPts) / maxPts - for i in range(k - 2, -1, -1): - f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts - return f[0] -``` - -### **Java** - ```java class Solution { private double[] f; @@ -109,27 +95,6 @@ class Solution { } ``` -```java -class Solution { - public double new21Game(int n, int k, int maxPts) { - if (k == 0) { - return 1.0; - } - double[] f = new double[k + maxPts]; - for (int i = k; i < Math.min(n + 1, k + maxPts); ++i) { - f[i] = 1; - } - f[k - 1] = Math.min(n - k + 1, maxPts) * 1.0 / maxPts; - for (int i = k - 2; i >= 0; --i) { - f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts; - } - return f[0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -152,29 +117,6 @@ public: }; ``` -```cpp -class Solution { -public: - double new21Game(int n, int k, int maxPts) { - if (k == 0) { - return 1.0; - } - double f[k + maxPts]; - memset(f, 0, sizeof(f)); - for (int i = k; i < min(n + 1, k + maxPts); ++i) { - f[i] = 1; - } - f[k - 1] = min(n - k + 1, maxPts) * 1.0 / maxPts; - for (int i = k - 2; i >= 0; --i) { - f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts; - } - return f[0]; - } -}; -``` - -### **Go** - ```go func new21Game(n int, k int, maxPts int) float64 { f := make([]float64, k) @@ -199,25 +141,6 @@ func new21Game(n int, k int, maxPts int) float64 { } ``` -```go -func new21Game(n int, k int, maxPts int) float64 { - if k == 0 { - return 1 - } - f := make([]float64, k+maxPts) - for i := k; i < min(n+1, k+maxPts); i++ { - f[i] = 1 - } - f[k-1] = float64(min(n-k+1, maxPts)) / float64(maxPts) - for i := k - 2; i >= 0; i-- { - f[i] = f[i+1] + (f[i+1]-f[i+maxPts+1])/float64(maxPts) - } - return f[0] -} -``` - -### **TypeScript** - ```ts function new21Game(n: number, k: number, maxPts: number): number { const f = new Array(k).fill(0); @@ -237,6 +160,81 @@ function new21Game(n: number, k: number, maxPts: number): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def new21Game(self, n: int, k: int, maxPts: int) -> float: + f = [0] * (k + maxPts) + for i in range(k, min(n + 1, k + maxPts)): + f[i] = 1 + f[k - 1] = min(n - k + 1, maxPts) / maxPts + for i in range(k - 2, -1, -1): + f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts + return f[0] +``` + +```java +class Solution { + public double new21Game(int n, int k, int maxPts) { + if (k == 0) { + return 1.0; + } + double[] f = new double[k + maxPts]; + for (int i = k; i < Math.min(n + 1, k + maxPts); ++i) { + f[i] = 1; + } + f[k - 1] = Math.min(n - k + 1, maxPts) * 1.0 / maxPts; + for (int i = k - 2; i >= 0; --i) { + f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts; + } + return f[0]; + } +} +``` + +```cpp +class Solution { +public: + double new21Game(int n, int k, int maxPts) { + if (k == 0) { + return 1.0; + } + double f[k + maxPts]; + memset(f, 0, sizeof(f)); + for (int i = k; i < min(n + 1, k + maxPts); ++i) { + f[i] = 1; + } + f[k - 1] = min(n - k + 1, maxPts) * 1.0 / maxPts; + for (int i = k - 2; i >= 0; --i) { + f[i] = f[i + 1] + (f[i + 1] - f[i + maxPts + 1]) / maxPts; + } + return f[0]; + } +}; +``` + +```go +func new21Game(n int, k int, maxPts int) float64 { + if k == 0 { + return 1 + } + f := make([]float64, k+maxPts) + for i := k; i < min(n+1, k+maxPts); i++ { + f[i] = 1 + } + f[k-1] = float64(min(n-k+1, maxPts)) / float64(maxPts) + for i := k - 2; i >= 0; i-- { + f[i] = f[i+1] + (f[i+1]-f[i+maxPts+1])/float64(maxPts) + } + return f[0] +} +``` + ```ts function new21Game(n: number, k: number, maxPts: number): number { if (k === 0) { @@ -254,10 +252,6 @@ function new21Game(n: number, k: number, maxPts: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0838.Push Dominoes/README.md b/solution/0800-0899/0838.Push Dominoes/README.md index 34a799df34db7..5025811bdb24c 100644 --- a/solution/0800-0899/0838.Push Dominoes/README.md +++ b/solution/0800-0899/0838.Push Dominoes/README.md @@ -52,18 +52,10 @@ ## 解法 - - -BFS。设 time 记录骨牌翻倒或者确定不翻倒的时间,翻倒的骨牌不会对正在翻倒或者已经翻倒的骨牌施加力,force 记录骨牌受到的力,骨牌仅在受到单侧的力时会翻倒。 - -初始时,将所有受力点 i (`dominoes[i] != '.'`)入队,并设置 `time[i] = 0`。 +### 方法一 -### **Python3** - - - ```python class Solution: def pushDominoes(self, dominoes: str) -> str: @@ -93,10 +85,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String pushDominoes(String dominoes) { @@ -141,54 +129,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function pushDominoes(dominoes: string): string { - const n = dominoes.length; - const map = { - L: -1, - R: 1, - '.': 0, - }; - let ans = new Array(n).fill(0); - let visited = new Array(n).fill(0); - let queue = []; - let depth = 1; - for (let i = 0; i < n; i++) { - let cur = map[dominoes.charAt(i)]; - if (cur) { - queue.push(i); - visited[i] = depth; - ans[i] = cur; - } - } - while (queue.length) { - depth++; - let nextLevel = []; - for (let i of queue) { - const dx = ans[i]; - let x = i + dx; - if (x >= 0 && x < n && [0, depth].includes(visited[x])) { - ans[x] += dx; - visited[x] = depth; - nextLevel.push(x); - } - } - queue = nextLevel; - } - return ans - .map(d => { - if (!d) return '.'; - else if (d < 0) return 'L'; - else return 'R'; - }) - .join(''); -} -``` - -### **C++** - ```cpp class Solution { public: @@ -228,8 +168,6 @@ public: }; ``` -### **Go** - ```go func pushDominoes(dominoes string) string { n := len(dominoes) @@ -275,10 +213,50 @@ func pushDominoes(dominoes string) string { } ``` -### **...** - -``` - +```ts +function pushDominoes(dominoes: string): string { + const n = dominoes.length; + const map = { + L: -1, + R: 1, + '.': 0, + }; + let ans = new Array(n).fill(0); + let visited = new Array(n).fill(0); + let queue = []; + let depth = 1; + for (let i = 0; i < n; i++) { + let cur = map[dominoes.charAt(i)]; + if (cur) { + queue.push(i); + visited[i] = depth; + ans[i] = cur; + } + } + while (queue.length) { + depth++; + let nextLevel = []; + for (let i of queue) { + const dx = ans[i]; + let x = i + dx; + if (x >= 0 && x < n && [0, depth].includes(visited[x])) { + ans[x] += dx; + visited[x] = depth; + nextLevel.push(x); + } + } + queue = nextLevel; + } + return ans + .map(d => { + if (!d) return '.'; + else if (d < 0) return 'L'; + else return 'R'; + }) + .join(''); +} ``` + + diff --git a/solution/0800-0899/0838.Push Dominoes/README_EN.md b/solution/0800-0899/0838.Push Dominoes/README_EN.md index f1836aeb095b2..571c4f6f98148 100644 --- a/solution/0800-0899/0838.Push Dominoes/README_EN.md +++ b/solution/0800-0899/0838.Push Dominoes/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,8 +82,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String pushDominoes(String dominoes) { @@ -128,54 +126,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function pushDominoes(dominoes: string): string { - const n = dominoes.length; - const map = { - L: -1, - R: 1, - '.': 0, - }; - let ans = new Array(n).fill(0); - let visited = new Array(n).fill(0); - let queue = []; - let depth = 1; - for (let i = 0; i < n; i++) { - let cur = map[dominoes.charAt(i)]; - if (cur) { - queue.push(i); - visited[i] = depth; - ans[i] = cur; - } - } - while (queue.length) { - depth++; - let nextLevel = []; - for (let i of queue) { - const dx = ans[i]; - let x = i + dx; - if (x >= 0 && x < n && [0, depth].includes(visited[x])) { - ans[x] += dx; - visited[x] = depth; - nextLevel.push(x); - } - } - queue = nextLevel; - } - return ans - .map(d => { - if (!d) return '.'; - else if (d < 0) return 'L'; - else return 'R'; - }) - .join(''); -} -``` - -### **C++** - ```cpp class Solution { public: @@ -215,8 +165,6 @@ public: }; ``` -### **Go** - ```go func pushDominoes(dominoes string) string { n := len(dominoes) @@ -262,10 +210,50 @@ func pushDominoes(dominoes string) string { } ``` -### **...** - -``` - +```ts +function pushDominoes(dominoes: string): string { + const n = dominoes.length; + const map = { + L: -1, + R: 1, + '.': 0, + }; + let ans = new Array(n).fill(0); + let visited = new Array(n).fill(0); + let queue = []; + let depth = 1; + for (let i = 0; i < n; i++) { + let cur = map[dominoes.charAt(i)]; + if (cur) { + queue.push(i); + visited[i] = depth; + ans[i] = cur; + } + } + while (queue.length) { + depth++; + let nextLevel = []; + for (let i of queue) { + const dx = ans[i]; + let x = i + dx; + if (x >= 0 && x < n && [0, depth].includes(visited[x])) { + ans[x] += dx; + visited[x] = depth; + nextLevel.push(x); + } + } + queue = nextLevel; + } + return ans + .map(d => { + if (!d) return '.'; + else if (d < 0) return 'L'; + else return 'R'; + }) + .join(''); +} ``` + + diff --git a/solution/0800-0899/0839.Similar String Groups/README.md b/solution/0800-0899/0839.Similar String Groups/README.md index 214dc42b47069..d20a8a9652533 100644 --- a/solution/0800-0899/0839.Similar String Groups/README.md +++ b/solution/0800-0899/0839.Similar String Groups/README.md @@ -43,81 +43,10 @@ ## 解法 - - -并查集模板题。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` - -对于本题,先遍历所有字符串对,判断两字符串是否相似,若相似,则将两字符串合并到同一个集合中,从而形成并查集。最后统计集合的数量即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def numSimilarGroups(self, strs: List[str]) -> int: @@ -135,10 +64,6 @@ class Solution: return sum(i == find(i) for i in range(n)) ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -185,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -222,8 +145,6 @@ public: }; ``` -### **Go** - ```go func numSimilarGroups(strs []string) int { n := len(strs) @@ -264,10 +185,6 @@ func numSimilarGroups(strs []string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0839.Similar String Groups/README_EN.md b/solution/0800-0899/0839.Similar String Groups/README_EN.md index 24644f5fb84d0..fcb8163a3217c 100644 --- a/solution/0800-0899/0839.Similar String Groups/README_EN.md +++ b/solution/0800-0899/0839.Similar String Groups/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return sum(i == find(i) for i in range(n)) ``` -### **Java** - ```java class Solution { private int[] p; @@ -79,36 +77,35 @@ class Solution { } } } - int ans = 0; + int res = 0; for (int i = 0; i < n; ++i) { if (i == find(i)) { - ++ans; + ++res; } } - return ans; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; + return res; } private boolean check(String a, String b) { int cnt = 0; - for (int i = 0; i < a.length(); ++i) { + int n = a.length(); + for (int i = 0; i < n; ++i) { if (a.charAt(i) != b.charAt(i)) { ++cnt; } } return cnt <= 2; } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +141,6 @@ public: }; ``` -### **Go** - ```go func numSimilarGroups(strs []string) int { n := len(strs) @@ -186,10 +181,6 @@ func numSimilarGroups(strs []string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0840.Magic Squares In Grid/README.md b/solution/0800-0899/0840.Magic Squares In Grid/README.md index 36df6f749da4b..7203a1536ff54 100644 --- a/solution/0800-0899/0840.Magic Squares In Grid/README.md +++ b/solution/0800-0899/0840.Magic Squares In Grid/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们直接枚举每个 $3 \times 3$ 子矩阵的左上角坐标 $(i, j)$,然后判断该子矩阵是否满足“幻方矩阵”,若是,答案加一。枚举结束后,返回答案即可。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def numMagicSquaresInside(self, grid: List[List[int]]) -> int: @@ -93,10 +87,6 @@ class Solution: return sum(check(i, j) for i in range(m) for j in range(n)) ``` -### **Java** - - - ```java class Solution { private int m; @@ -153,8 +143,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -206,8 +194,6 @@ public: }; ``` -### **Go** - ```go func numMagicSquaresInside(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -255,8 +241,6 @@ func numMagicSquaresInside(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function numMagicSquaresInside(grid: number[][]): number { const m = grid.length; @@ -305,10 +289,6 @@ function numMagicSquaresInside(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0840.Magic Squares In Grid/README_EN.md b/solution/0800-0899/0840.Magic Squares In Grid/README_EN.md index aa1066e405669..4137e6b1696ec 100644 --- a/solution/0800-0899/0840.Magic Squares In Grid/README_EN.md +++ b/solution/0800-0899/0840.Magic Squares In Grid/README_EN.md @@ -41,9 +41,9 @@ In total, there is only one magic square inside the given grid. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return sum(check(i, j) for i in range(m) for j in range(n)) ``` -### **Java** - ```java class Solution { private int m; @@ -135,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -188,8 +184,6 @@ public: }; ``` -### **Go** - ```go func numMagicSquaresInside(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -237,8 +231,6 @@ func numMagicSquaresInside(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function numMagicSquaresInside(grid: number[][]): number { const m = grid.length; @@ -287,10 +279,6 @@ function numMagicSquaresInside(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0841.Keys and Rooms/README.md b/solution/0800-0899/0841.Keys and Rooms/README.md index 83f99a0ec964b..e4ae82cc7ec35 100644 --- a/solution/0800-0899/0841.Keys and Rooms/README.md +++ b/solution/0800-0899/0841.Keys and Rooms/README.md @@ -53,16 +53,10 @@ ## 解法 - - -DFS。 +### 方法一 -### **Python3** - - - ```python class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: @@ -78,10 +72,6 @@ class Solution: return len(vis) == len(rooms) ``` -### **Java** - - - ```java class Solution { private List> rooms; @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func canVisitAllRooms(rooms [][]int) bool { vis := make(map[int]bool) @@ -149,8 +135,6 @@ func canVisitAllRooms(rooms [][]int) bool { } ``` -### **TypeScript** - ```ts function canVisitAllRooms(rooms: number[][]): boolean { const n = rooms.length; @@ -167,25 +151,6 @@ function canVisitAllRooms(rooms: number[][]): boolean { } ``` -```ts -function canVisitAllRooms(rooms: number[][]): boolean { - const n = rooms.length; - const isOpen = new Array(n).fill(false); - const keys = [0]; - while (keys.length !== 0) { - const i = keys.pop(); - if (isOpen[i]) { - continue; - } - isOpen[i] = true; - keys.push(...rooms[i]); - } - return isOpen.every(v => v); -} -``` - -### **Rust** - ```rust impl Solution { pub fn can_visit_all_rooms(rooms: Vec>) -> bool { @@ -205,10 +170,29 @@ impl Solution { } ``` -### **...** + -``` +### 方法二 + + +```ts +function canVisitAllRooms(rooms: number[][]): boolean { + const n = rooms.length; + const isOpen = new Array(n).fill(false); + const keys = [0]; + while (keys.length !== 0) { + const i = keys.pop(); + if (isOpen[i]) { + continue; + } + isOpen[i] = true; + keys.push(...rooms[i]); + } + return isOpen.every(v => v); +} ``` + + diff --git a/solution/0800-0899/0841.Keys and Rooms/README_EN.md b/solution/0800-0899/0841.Keys and Rooms/README_EN.md index d12c56fb95efb..8e779b80242ce 100644 --- a/solution/0800-0899/0841.Keys and Rooms/README_EN.md +++ b/solution/0800-0899/0841.Keys and Rooms/README_EN.md @@ -46,12 +46,10 @@ Since we were able to visit every room, we return true. ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: @@ -67,8 +65,6 @@ class Solution: return len(vis) == len(rooms) ``` -### **Java** - ```java class Solution { private List> rooms; @@ -93,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +110,6 @@ public: }; ``` -### **Go** - ```go func canVisitAllRooms(rooms [][]int) bool { vis := make(map[int]bool) @@ -136,8 +128,6 @@ func canVisitAllRooms(rooms [][]int) bool { } ``` -### **TypeScript** - ```ts function canVisitAllRooms(rooms: number[][]): boolean { const n = rooms.length; @@ -154,25 +144,6 @@ function canVisitAllRooms(rooms: number[][]): boolean { } ``` -```ts -function canVisitAllRooms(rooms: number[][]): boolean { - const n = rooms.length; - const isOpen = new Array(n).fill(false); - const keys = [0]; - while (keys.length !== 0) { - const i = keys.pop(); - if (isOpen[i]) { - continue; - } - isOpen[i] = true; - keys.push(...rooms[i]); - } - return isOpen.every(v => v); -} -``` - -### **Rust** - ```rust impl Solution { pub fn can_visit_all_rooms(rooms: Vec>) -> bool { @@ -192,10 +163,29 @@ impl Solution { } ``` -### **...** + -``` +### Solution 2 + + +```ts +function canVisitAllRooms(rooms: number[][]): boolean { + const n = rooms.length; + const isOpen = new Array(n).fill(false); + const keys = [0]; + while (keys.length !== 0) { + const i = keys.pop(); + if (isOpen[i]) { + continue; + } + isOpen[i] = true; + keys.push(...rooms[i]); + } + return isOpen.every(v => v); +} ``` + + diff --git a/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README.md b/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README.md index 5ff9be63e4aea..5a682853a3426 100644 --- a/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README.md +++ b/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:回溯 + 剪枝** +### 方法一:回溯 + 剪枝 我们设计一个函数 $dfs(i)$,表示从字符串 $num$ 的第 $i$ 个字符开始拆分,拆分出的斐波那契式序列是否满足题目要求。如果满足,我们就返回 $true$,否则返回 $false$。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def splitIntoFibonacci(self, num: str) -> List[int]: @@ -102,10 +96,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List ans = new ArrayList<>(); @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -181,8 +169,6 @@ public: }; ``` -### **Go** - ```go func splitIntoFibonacci(num string) []int { n := len(num) @@ -216,10 +202,6 @@ func splitIntoFibonacci(num string) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README_EN.md b/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README_EN.md index 22cf85eeb7517..279acc4c5d406 100644 --- a/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README_EN.md +++ b/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README_EN.md @@ -53,9 +53,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,8 +83,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List ans = new ArrayList<>(); @@ -123,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +156,6 @@ public: }; ``` -### **Go** - ```go func splitIntoFibonacci(num string) []int { n := len(num) @@ -195,10 +189,6 @@ func splitIntoFibonacci(num string) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0843.Guess the Word/README.md b/solution/0800-0899/0843.Guess the Word/README.md index fac01e8bf4aee..55d07843f0bb6 100644 --- a/solution/0800-0899/0843.Guess the Word/README.md +++ b/solution/0800-0899/0843.Guess the Word/README.md @@ -65,30 +65,4 @@ master.guess("abcczz") 返回 4 ,因为 "abcczz" 共有 4 个字母匹配。 ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0800-0899/0843.Guess the Word/README_EN.md b/solution/0800-0899/0843.Guess the Word/README_EN.md index 7df862bb30811..c28b9efc6f85d 100644 --- a/solution/0800-0899/0843.Guess the Word/README_EN.md +++ b/solution/0800-0899/0843.Guess the Word/README_EN.md @@ -61,24 +61,4 @@ We made 5 calls to master.guess, and one of them was the secret, so we pass the ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0800-0899/0844.Backspace String Compare/README.md b/solution/0800-0899/0844.Backspace String Compare/README.md index 7f04a640469b3..48614b3975dd4 100644 --- a/solution/0800-0899/0844.Backspace String Compare/README.md +++ b/solution/0800-0899/0844.Backspace String Compare/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们用双指针 $i$ 和 $j$ 分别指向字符串 $s$ 和 $t$ 的末尾。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def backspaceCompare(self, s: str, t: str) -> bool: @@ -104,10 +98,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean backspaceCompare(String s, String t) { @@ -149,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -188,8 +176,6 @@ public: }; ``` -### **Go** - ```go func backspaceCompare(s string, t string) bool { i, j := len(s)-1, len(t)-1 @@ -229,8 +215,6 @@ func backspaceCompare(s string, t string) bool { } ``` -### **TypeScript** - ```ts function backspaceCompare(s: string, t: string): boolean { let i = s.length - 1; @@ -268,8 +252,6 @@ function backspaceCompare(s: string, t: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn backspace_compare(s: String, t: String) -> bool { @@ -315,10 +297,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0844.Backspace String Compare/README_EN.md b/solution/0800-0899/0844.Backspace String Compare/README_EN.md index b25c8638fdd66..2250add6968af 100644 --- a/solution/0800-0899/0844.Backspace String Compare/README_EN.md +++ b/solution/0800-0899/0844.Backspace String Compare/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,8 +82,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean backspaceCompare(String s, String t) { @@ -125,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +160,6 @@ public: }; ``` -### **Go** - ```go func backspaceCompare(s string, t string) bool { i, j := len(s)-1, len(t)-1 @@ -205,8 +199,6 @@ func backspaceCompare(s string, t string) bool { } ``` -### **TypeScript** - ```ts function backspaceCompare(s: string, t: string): boolean { let i = s.length - 1; @@ -244,8 +236,6 @@ function backspaceCompare(s: string, t: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn backspace_compare(s: String, t: String) -> bool { @@ -291,10 +281,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0845.Longest Mountain in Array/README.md b/solution/0800-0899/0845.Longest Mountain in Array/README.md index 0ce08ed08e56d..010271c4b5368 100644 --- a/solution/0800-0899/0845.Longest Mountain in Array/README.md +++ b/solution/0800-0899/0845.Longest Mountain in Array/README.md @@ -58,26 +58,14 @@ ## 解法 - - -**方法一:预处理 + 枚举** +### 方法一:预处理 + 枚举 我们定义两个数组 $f$ 和 $g$,其中 $f[i]$ 表示以 $arr[i]$ 结尾的最长上升子序列的长度,而 $g[i]$ 表示以 $arr[i]$ 开头的最长下降子序列的长度。那么对于每个下标 $i$,如果 $f[i] \gt 1$ 且 $g[i] \gt 1$,那么以 $arr[i]$ 为山顶的山脉的长度为 $f[i] + g[i] - 1$,我们只需要枚举所有的 $i$,找出最大的那个值即可。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $arr$ 的长度。 -**方法二:一次遍历(枚举左侧山脚)** - -我们可以枚举山脉的左侧山脚,然后向右寻找山脉的右侧山脚。我们可以使用两个指针 $l$ 和 $r$,其中 $l$ 表示左侧山脚的下标,$r$ 表示右侧山脚的下标,初始时 $l=0$,$r=0$,然后我们向右移动 $r$,找到山顶的位置,此时判断 $r$ 是否满足 $r + 1 \lt n$ 并且 $arr[r] \gt arr[r + 1]$,如果满足,我们向右继续移动 $r$,直到找到右侧山脚的位置,此时山脉的长度为 $r - l + 1$,我们更新答案,然后将 $l$ 的值更新为 $r$,继续寻找下一个山脉。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $arr$ 的长度。 - -### **Python3** - - - ```python class Solution: def longestMountain(self, arr: List[int]) -> int: @@ -96,30 +84,6 @@ class Solution: return ans ``` -```python -class Solution: - def longestMountain(self, arr: List[int]) -> int: - n = len(arr) - ans = l = 0 - while l + 2 < n: - r = l + 1 - if arr[l] < arr[r]: - while r + 1 < n and arr[r] < arr[r + 1]: - r += 1 - if r < n - 1 and arr[r] > arr[r + 1]: - while r < n - 1 and arr[r] > arr[r + 1]: - r += 1 - ans = max(ans, r - l + 1) - else: - r += 1 - l = r - return ans -``` - -### **Java** - - - ```java class Solution { public int longestMountain(int[] arr) { @@ -147,34 +111,6 @@ class Solution { } ``` -```java -class Solution { - public int longestMountain(int[] arr) { - int n = arr.length; - int ans = 0; - for (int l = 0, r = 0; l + 2 < n; l = r) { - r = l + 1; - if (arr[l] < arr[r]) { - while (r + 1 < n && arr[r] < arr[r + 1]) { - ++r; - } - if (r + 1 < n && arr[r] > arr[r + 1]) { - while (r + 1 < n && arr[r] > arr[r + 1]) { - ++r; - } - ans = Math.max(ans, r - l + 1); - } else { - ++r; - } - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -203,6 +139,88 @@ public: }; ``` +```go +func longestMountain(arr []int) (ans int) { + n := len(arr) + f := make([]int, n) + g := make([]int, n) + for i := range f { + f[i] = 1 + g[i] = 1 + } + for i := 1; i < n; i++ { + if arr[i] > arr[i-1] { + f[i] = f[i-1] + 1 + } + } + for i := n - 2; i >= 0; i-- { + if arr[i] > arr[i+1] { + g[i] = g[i+1] + 1 + if f[i] > 1 { + ans = max(ans, f[i]+g[i]-1) + } + } + } + return +} +``` + + + +### 方法二:一次遍历(枚举左侧山脚) + +我们可以枚举山脉的左侧山脚,然后向右寻找山脉的右侧山脚。我们可以使用两个指针 $l$ 和 $r$,其中 $l$ 表示左侧山脚的下标,$r$ 表示右侧山脚的下标,初始时 $l=0$,$r=0$,然后我们向右移动 $r$,找到山顶的位置,此时判断 $r$ 是否满足 $r + 1 \lt n$ 并且 $arr[r] \gt arr[r + 1]$,如果满足,我们向右继续移动 $r$,直到找到右侧山脚的位置,此时山脉的长度为 $r - l + 1$,我们更新答案,然后将 $l$ 的值更新为 $r$,继续寻找下一个山脉。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $arr$ 的长度。 + + + +```python +class Solution: + def longestMountain(self, arr: List[int]) -> int: + n = len(arr) + ans = l = 0 + while l + 2 < n: + r = l + 1 + if arr[l] < arr[r]: + while r + 1 < n and arr[r] < arr[r + 1]: + r += 1 + if r < n - 1 and arr[r] > arr[r + 1]: + while r < n - 1 and arr[r] > arr[r + 1]: + r += 1 + ans = max(ans, r - l + 1) + else: + r += 1 + l = r + return ans +``` + +```java +class Solution { + public int longestMountain(int[] arr) { + int n = arr.length; + int ans = 0; + for (int l = 0, r = 0; l + 2 < n; l = r) { + r = l + 1; + if (arr[l] < arr[r]) { + while (r + 1 < n && arr[r] < arr[r + 1]) { + ++r; + } + if (r + 1 < n && arr[r] > arr[r + 1]) { + while (r + 1 < n && arr[r] > arr[r + 1]) { + ++r; + } + ans = Math.max(ans, r - l + 1); + } else { + ++r; + } + } + } + return ans; + } +} +``` + ```cpp class Solution { public: @@ -230,34 +248,6 @@ public: }; ``` -### **Go** - -```go -func longestMountain(arr []int) (ans int) { - n := len(arr) - f := make([]int, n) - g := make([]int, n) - for i := range f { - f[i] = 1 - g[i] = 1 - } - for i := 1; i < n; i++ { - if arr[i] > arr[i-1] { - f[i] = f[i-1] + 1 - } - } - for i := n - 2; i >= 0; i-- { - if arr[i] > arr[i+1] { - g[i] = g[i+1] + 1 - if f[i] > 1 { - ans = max(ans, f[i]+g[i]-1) - } - } - } - return -} -``` - ```go func longestMountain(arr []int) (ans int) { n := len(arr) @@ -281,10 +271,6 @@ func longestMountain(arr []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0845.Longest Mountain in Array/README_EN.md b/solution/0800-0899/0845.Longest Mountain in Array/README_EN.md index 608032903215c..0a076edd53543 100644 --- a/solution/0800-0899/0845.Longest Mountain in Array/README_EN.md +++ b/solution/0800-0899/0845.Longest Mountain in Array/README_EN.md @@ -53,9 +53,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,28 +75,6 @@ class Solution: return ans ``` -```python -class Solution: - def longestMountain(self, arr: List[int]) -> int: - n = len(arr) - ans = l = 0 - while l + 2 < n: - r = l + 1 - if arr[l] < arr[r]: - while r + 1 < n and arr[r] < arr[r + 1]: - r += 1 - if r < n - 1 and arr[r] > arr[r + 1]: - while r < n - 1 and arr[r] > arr[r + 1]: - r += 1 - ans = max(ans, r - l + 1) - else: - r += 1 - l = r - return ans -``` - -### **Java** - ```java class Solution { public int longestMountain(int[] arr) { @@ -124,34 +102,6 @@ class Solution { } ``` -```java -class Solution { - public int longestMountain(int[] arr) { - int n = arr.length; - int ans = 0; - for (int l = 0, r = 0; l + 2 < n; l = r) { - r = l + 1; - if (arr[l] < arr[r]) { - while (r + 1 < n && arr[r] < arr[r + 1]) { - ++r; - } - if (r + 1 < n && arr[r] > arr[r + 1]) { - while (r + 1 < n && arr[r] > arr[r + 1]) { - ++r; - } - ans = Math.max(ans, r - l + 1); - } else { - ++r; - } - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -180,6 +130,84 @@ public: }; ``` +```go +func longestMountain(arr []int) (ans int) { + n := len(arr) + f := make([]int, n) + g := make([]int, n) + for i := range f { + f[i] = 1 + g[i] = 1 + } + for i := 1; i < n; i++ { + if arr[i] > arr[i-1] { + f[i] = f[i-1] + 1 + } + } + for i := n - 2; i >= 0; i-- { + if arr[i] > arr[i+1] { + g[i] = g[i+1] + 1 + if f[i] > 1 { + ans = max(ans, f[i]+g[i]-1) + } + } + } + return +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def longestMountain(self, arr: List[int]) -> int: + n = len(arr) + ans = l = 0 + while l + 2 < n: + r = l + 1 + if arr[l] < arr[r]: + while r + 1 < n and arr[r] < arr[r + 1]: + r += 1 + if r < n - 1 and arr[r] > arr[r + 1]: + while r < n - 1 and arr[r] > arr[r + 1]: + r += 1 + ans = max(ans, r - l + 1) + else: + r += 1 + l = r + return ans +``` + +```java +class Solution { + public int longestMountain(int[] arr) { + int n = arr.length; + int ans = 0; + for (int l = 0, r = 0; l + 2 < n; l = r) { + r = l + 1; + if (arr[l] < arr[r]) { + while (r + 1 < n && arr[r] < arr[r + 1]) { + ++r; + } + if (r + 1 < n && arr[r] > arr[r + 1]) { + while (r + 1 < n && arr[r] > arr[r + 1]) { + ++r; + } + ans = Math.max(ans, r - l + 1); + } else { + ++r; + } + } + } + return ans; + } +} +``` + ```cpp class Solution { public: @@ -207,34 +235,6 @@ public: }; ``` -### **Go** - -```go -func longestMountain(arr []int) (ans int) { - n := len(arr) - f := make([]int, n) - g := make([]int, n) - for i := range f { - f[i] = 1 - g[i] = 1 - } - for i := 1; i < n; i++ { - if arr[i] > arr[i-1] { - f[i] = f[i-1] + 1 - } - } - for i := n - 2; i >= 0; i-- { - if arr[i] > arr[i+1] { - g[i] = g[i+1] + 1 - if f[i] > 1 { - ans = max(ans, f[i]+g[i]-1) - } - } - } - return -} -``` - ```go func longestMountain(arr []int) (ans int) { n := len(arr) @@ -258,10 +258,6 @@ func longestMountain(arr []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0846.Hand of Straights/README.md b/solution/0800-0899/0846.Hand of Straights/README.md index 4faaf9a827552..b6cb2f39b066a 100644 --- a/solution/0800-0899/0846.Hand of Straights/README.md +++ b/solution/0800-0899/0846.Hand of Straights/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:哈希表 + 排序** +### 方法一:哈希表 + 排序 我们先用哈希表 `cnt` 统计数组 `hand` 中每个数字出现的次数,然后对数组 `hand` 进行排序。 @@ -55,20 +53,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `hand` 的长度。 -**方法二:有序集合** - -我们也可以使用有序集合统计数组 `hand` 中每个数字出现的次数。 - -接下来,循环取出有序集合中的最小值 $v$,然后枚举 $v$ 到 $v+groupSize-1$ 的每个数字,如果这些数字在有序集合中出现的次数都不为 $0$,则我们将这些数字的出现次数减 $1$,如果出现次数减 $1$ 后为 $0$,则将该数字从有序集合中删除,否则说明无法将数组划分成若干个长度为 $groupSize$ 的子数组,返回 `false`。如果可以将数组划分成若干个长度为 $groupSize$ 的子数组,则遍历结束后返回 `true`。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `hand` 的长度。 - -### **Python3** - - - ```python class Solution: def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: @@ -84,36 +70,6 @@ class Solution: return True ``` -```python -from sortedcontainers import SortedDict - - -class Solution: - def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: - if len(hand) % groupSize != 0: - return False - sd = SortedDict() - for h in hand: - if h in sd: - sd[h] += 1 - else: - sd[h] = 1 - while sd: - v = sd.peekitem(0)[0] - for i in range(v, v + groupSize): - if i not in sd: - return False - if sd[i] == 1: - sd.pop(i) - else: - sd[i] -= 1 - return True -``` - -### **Java** - - - ```java class Solution { public boolean isNStraightHand(int[] hand, int groupSize) { @@ -140,6 +96,92 @@ class Solution { } ``` +```cpp +class Solution { +public: + bool isNStraightHand(vector& hand, int groupSize) { + unordered_map cnt; + for (int& v : hand) ++cnt[v]; + sort(hand.begin(), hand.end()); + for (int& v : hand) { + if (cnt.count(v)) { + for (int x = v; x < v + groupSize; ++x) { + if (!cnt.count(x)) { + return false; + } + if (--cnt[x] == 0) { + cnt.erase(x); + } + } + } + } + return true; + } +}; +``` + +```go +func isNStraightHand(hand []int, groupSize int) bool { + cnt := map[int]int{} + for _, v := range hand { + cnt[v]++ + } + sort.Ints(hand) + for _, v := range hand { + if _, ok := cnt[v]; ok { + for x := v; x < v+groupSize; x++ { + if _, ok := cnt[x]; !ok { + return false + } + cnt[x]-- + if cnt[x] == 0 { + delete(cnt, x) + } + } + } + } + return true +} +``` + + + +### 方法二:有序集合 + +我们也可以使用有序集合统计数组 `hand` 中每个数字出现的次数。 + +接下来,循环取出有序集合中的最小值 $v$,然后枚举 $v$ 到 $v+groupSize-1$ 的每个数字,如果这些数字在有序集合中出现的次数都不为 $0$,则我们将这些数字的出现次数减 $1$,如果出现次数减 $1$ 后为 $0$,则将该数字从有序集合中删除,否则说明无法将数组划分成若干个长度为 $groupSize$ 的子数组,返回 `false`。如果可以将数组划分成若干个长度为 $groupSize$ 的子数组,则遍历结束后返回 `true`。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `hand` 的长度。 + + + +```python +from sortedcontainers import SortedDict + + +class Solution: + def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: + if len(hand) % groupSize != 0: + return False + sd = SortedDict() + for h in hand: + if h in sd: + sd[h] += 1 + else: + sd[h] = 1 + while sd: + v = sd.peekitem(0)[0] + for i in range(v, v + groupSize): + if i not in sd: + return False + if sd[i] == 1: + sd.pop(i) + else: + sd[i] -= 1 + return True +``` + ```java class Solution { public boolean isNStraightHand(int[] hand, int groupSize) { @@ -168,32 +210,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool isNStraightHand(vector& hand, int groupSize) { - unordered_map cnt; - for (int& v : hand) ++cnt[v]; - sort(hand.begin(), hand.end()); - for (int& v : hand) { - if (cnt.count(v)) { - for (int x = v; x < v + groupSize; ++x) { - if (!cnt.count(x)) { - return false; - } - if (--cnt[x] == 0) { - cnt.erase(x); - } - } - } - } - return true; - } -}; -``` - ```cpp class Solution { public: @@ -216,32 +232,6 @@ public: }; ``` -### **Go** - -```go -func isNStraightHand(hand []int, groupSize int) bool { - cnt := map[int]int{} - for _, v := range hand { - cnt[v]++ - } - sort.Ints(hand) - for _, v := range hand { - if _, ok := cnt[v]; ok { - for x := v; x < v+groupSize; x++ { - if _, ok := cnt[x]; !ok { - return false - } - cnt[x]-- - if cnt[x] == 0 { - delete(cnt, x) - } - } - } - } - return true -} -``` - ```go func isNStraightHand(hand []int, groupSize int) bool { if len(hand)%groupSize != 0 { @@ -272,10 +262,6 @@ func isNStraightHand(hand []int, groupSize int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0846.Hand of Straights/README_EN.md b/solution/0800-0899/0846.Hand of Straights/README_EN.md index 7516e5eb765cc..3379fc102c663 100644 --- a/solution/0800-0899/0846.Hand of Straights/README_EN.md +++ b/solution/0800-0899/0846.Hand of Straights/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,34 +59,6 @@ class Solution: return True ``` -```python -from sortedcontainers import SortedDict - - -class Solution: - def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: - if len(hand) % groupSize != 0: - return False - sd = SortedDict() - for h in hand: - if h in sd: - sd[h] += 1 - else: - sd[h] = 1 - while sd: - v = sd.peekitem(0)[0] - for i in range(v, v + groupSize): - if i not in sd: - return False - if sd[i] == 1: - sd.pop(i) - else: - sd[i] -= 1 - return True -``` - -### **Java** - ```java class Solution { public boolean isNStraightHand(int[] hand, int groupSize) { @@ -113,6 +85,86 @@ class Solution { } ``` +```cpp +class Solution { +public: + bool isNStraightHand(vector& hand, int groupSize) { + unordered_map cnt; + for (int& v : hand) ++cnt[v]; + sort(hand.begin(), hand.end()); + for (int& v : hand) { + if (cnt.count(v)) { + for (int x = v; x < v + groupSize; ++x) { + if (!cnt.count(x)) { + return false; + } + if (--cnt[x] == 0) { + cnt.erase(x); + } + } + } + } + return true; + } +}; +``` + +```go +func isNStraightHand(hand []int, groupSize int) bool { + cnt := map[int]int{} + for _, v := range hand { + cnt[v]++ + } + sort.Ints(hand) + for _, v := range hand { + if _, ok := cnt[v]; ok { + for x := v; x < v+groupSize; x++ { + if _, ok := cnt[x]; !ok { + return false + } + cnt[x]-- + if cnt[x] == 0 { + delete(cnt, x) + } + } + } + } + return true +} +``` + + + +### Solution 2 + + + +```python +from sortedcontainers import SortedDict + + +class Solution: + def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: + if len(hand) % groupSize != 0: + return False + sd = SortedDict() + for h in hand: + if h in sd: + sd[h] += 1 + else: + sd[h] = 1 + while sd: + v = sd.peekitem(0)[0] + for i in range(v, v + groupSize): + if i not in sd: + return False + if sd[i] == 1: + sd.pop(i) + else: + sd[i] -= 1 + return True +``` + ```java class Solution { public boolean isNStraightHand(int[] hand, int groupSize) { @@ -141,32 +193,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool isNStraightHand(vector& hand, int groupSize) { - unordered_map cnt; - for (int& v : hand) ++cnt[v]; - sort(hand.begin(), hand.end()); - for (int& v : hand) { - if (cnt.count(v)) { - for (int x = v; x < v + groupSize; ++x) { - if (!cnt.count(x)) { - return false; - } - if (--cnt[x] == 0) { - cnt.erase(x); - } - } - } - } - return true; - } -}; -``` - ```cpp class Solution { public: @@ -189,32 +215,6 @@ public: }; ``` -### **Go** - -```go -func isNStraightHand(hand []int, groupSize int) bool { - cnt := map[int]int{} - for _, v := range hand { - cnt[v]++ - } - sort.Ints(hand) - for _, v := range hand { - if _, ok := cnt[v]; ok { - for x := v; x < v+groupSize; x++ { - if _, ok := cnt[x]; !ok { - return false - } - cnt[x]-- - if cnt[x] == 0 { - delete(cnt, x) - } - } - } - } - return true -} -``` - ```go func isNStraightHand(hand []int, groupSize int) bool { if len(hand)%groupSize != 0 { @@ -245,10 +245,6 @@ func isNStraightHand(hand []int, groupSize int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0847.Shortest Path Visiting All Nodes/README.md b/solution/0800-0899/0847.Shortest Path Visiting All Nodes/README.md index d16604f00afc0..a8a3991ee47f6 100644 --- a/solution/0800-0899/0847.Shortest Path Visiting All Nodes/README.md +++ b/solution/0800-0899/0847.Shortest Path Visiting All Nodes/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:状态压缩 + BFS** +### 方法一:状态压缩 + BFS 我们注意到 $n$ 的范围不超过 $12$,因此,我们可以用一个 $12$ 位的二进制数来表示每个节点的访问情况,其中第 $i$ 位为 $1$ 表示第 $i$ 个节点已经被访问过,为 $0$ 表示该节点还没有被访问过。 @@ -61,26 +59,8 @@ 时间复杂度 $(n^2 \times 2^n)$,空间复杂度 $O(n \times 2^n)$。其中 $n$ 是图中的节点数。 -**方法二:BFS(A\* 算法)** - -因为每条边权值一样,所以用 BFS 就能得出最短路径,过程中可以用**状态压缩**记录节点的访问情况。另外,同一个节点 u 以及对应的节点访问情况需要保证只被搜索过一次,因此可以用 `vis(u, state)` 表示是否已经被搜索过,防止无效的重复搜索。 - -本题也属于 BFS 最小步数模型,可以使用 A\* 算法优化搜索。 - -A\* 算法主要思想如下: - -1. 将 BFS 队列转换为优先队列(小根堆); -1. 队列中的每个元素为 `(dist[state] + f(state), state)`,`dist[state]` 表示从起点到当前 state 的距离,`f(state)` 表示从当前 state 到终点的估计距离,这两个距离之和作为堆排序的依据; -1. 当终点第一次出队时,说明找到了从起点到终点的最短路径,直接返回对应的 step; -1. `f(state)` 是估价函数,并且估价函数要满足 `f(state) <= g(state)`,其中 `g(state)` 表示 state 到终点的真实距离; -1. A\* 算法只能保证终点第一次出队时,即找到了一条从起点到终点的最小路径,不能保证其他点出队时也是从起点到当前点的最短路径。 - -### **Python3** - - - ```python class Solution: def shortestPathLength(self, graph: List[List[int]]) -> int: @@ -104,37 +84,6 @@ class Solution: ans += 1 ``` -A\* 算法: - -```python -class Solution: - def shortestPathLength(self, graph: List[List[int]]) -> int: - n = len(graph) - - def f(state): - return sum(((state >> i) & 1) == 0 for i in range(n)) - - q = [] - dist = [[inf] * (1 << n) for _ in range(n)] - for i in range(n): - heappush(q, (f(1 << i), i, 1 << i)) - dist[i][1 << i] = 0 - while q: - _, u, state = heappop(q) - if state == (1 << n) - 1: - return dist[u][state] - for v in graph[u]: - nxt = state | (1 << v) - if dist[v][nxt] > dist[u][state] + 1: - dist[v][nxt] = dist[u][state] + 1 - heappush(q, (dist[v][nxt] + f(nxt), v, nxt)) - return 0 -``` - -### **Java** - - - ```java class Solution { public int shortestPathLength(int[][] graph) { @@ -165,54 +114,6 @@ class Solution { } ``` -A\* 算法: - -```java -class Solution { - private int n; - - public int shortestPathLength(int[][] graph) { - n = graph.length; - int[][] dist = new int[n][1 << n]; - for (int i = 0; i < n; ++i) { - Arrays.fill(dist[i], Integer.MAX_VALUE); - } - PriorityQueue q = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); - for (int i = 0; i < n; ++i) { - q.offer(new int[] {f(1 << i), i, 1 << i}); - dist[i][1 << i] = 0; - } - while (!q.isEmpty()) { - int[] p = q.poll(); - int u = p[1], state = p[2]; - if (state == (1 << n) - 1) { - return dist[u][state]; - } - for (int v : graph[u]) { - int nxt = state | (1 << v); - if (dist[v][nxt] > dist[u][state] + 1) { - dist[v][nxt] = dist[u][state] + 1; - q.offer(new int[] {dist[v][nxt] + f(nxt), v, nxt}); - } - } - } - return 0; - } - - private int f(int state) { - int ans = 0; - for (int i = 0; i < n; ++i) { - if (((state >> i) & 1) == 0) { - ++ans; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -245,87 +146,6 @@ public: }; ``` -A\* 算法: - -```cpp -class Solution { -public: - int n; - - int shortestPathLength(vector>& graph) { - n = graph.size(); - priority_queue, vector>, greater>> q; - vector> dist(n, vector(1 << n, INT_MAX)); - for (int i = 0; i < n; ++i) { - q.push({f(1 << i), i, 1 << i}); - dist[i][1 << i] = 0; - } - while (!q.empty()) { - auto [_, u, state] = q.top(); - q.pop(); - if (state == (1 << n) - 1) return dist[u][state]; - for (int v : graph[u]) { - int nxt = state | (1 << v); - if (dist[v][nxt] > dist[u][state] + 1) { - dist[v][nxt] = dist[u][state] + 1; - q.push({dist[v][nxt] + f(nxt), v, nxt}); - } - } - } - return 0; - } - - int f(int state) { - int ans = 0; - for (int i = 0; i < n; ++i) - if (((state >> i) & 1) == 0) - ++ans; - return ans; - } -}; -``` - -### **Rust** - -```rust -use std::collections::VecDeque; - -impl Solution { - #[allow(dead_code)] - pub fn shortest_path_length(graph: Vec>) -> i32 { - let n = graph.len(); - let mut vis = vec![vec![false; 1 << n]; n]; - let mut q = VecDeque::new(); - - // Initialize the queue - for i in 0..n { - q.push_back(((i, 1 << i), 0)); - vis[i][1 << i] = true; - } - - // Begin BFS - while !q.is_empty() { - let ((i, st), count) = q.pop_front().unwrap(); - if st == (1 << n) - 1 { - return count; - } - // If the path has not been visited - for j in &graph[i] { - let nst = st | (1 << *j); - if !vis[*j as usize][nst] { - q.push_back(((*j as usize, nst), count + 1)); - vis[*j as usize][nst] = true; - } - } - } - - -1 - } -} -``` - -### **Go** - ```go func shortestPathLength(graph [][]int) int { n := len(graph) @@ -356,8 +176,6 @@ func shortestPathLength(graph [][]int) int { } ``` -### **TypeScript** - ```ts function shortestPathLength(graph: number[][]): number { const n = graph.length; @@ -385,10 +203,168 @@ function shortestPathLength(graph: number[][]): number { } ``` -### **...** +```rust +use std::collections::VecDeque; + +impl Solution { + #[allow(dead_code)] + pub fn shortest_path_length(graph: Vec>) -> i32 { + let n = graph.len(); + let mut vis = vec![vec![false; 1 << n]; n]; + let mut q = VecDeque::new(); + + // Initialize the queue + for i in 0..n { + q.push_back(((i, 1 << i), 0)); + vis[i][1 << i] = true; + } + // Begin BFS + while !q.is_empty() { + let ((i, st), count) = q.pop_front().unwrap(); + if st == (1 << n) - 1 { + return count; + } + // If the path has not been visited + for j in &graph[i] { + let nst = st | (1 << *j); + if !vis[*j as usize][nst] { + q.push_back(((*j as usize, nst), count + 1)); + vis[*j as usize][nst] = true; + } + } + } + + -1 + } +} ``` + + +### 方法二:BFS(A\* 算法) + +因为每条边权值一样,所以用 BFS 就能得出最短路径,过程中可以用**状态压缩**记录节点的访问情况。另外,同一个节点 u 以及对应的节点访问情况需要保证只被搜索过一次,因此可以用 `vis(u, state)` 表示是否已经被搜索过,防止无效的重复搜索。 + +本题也属于 BFS 最小步数模型,可以使用 A\* 算法优化搜索。 + +A\* 算法主要思想如下: + +1. 将 BFS 队列转换为优先队列(小根堆); +1. 队列中的每个元素为 `(dist[state] + f(state), state)`,`dist[state]` 表示从起点到当前 state 的距离,`f(state)` 表示从当前 state 到终点的估计距离,这两个距离之和作为堆排序的依据; +1. 当终点第一次出队时,说明找到了从起点到终点的最短路径,直接返回对应的 step; +1. `f(state)` 是估价函数,并且估价函数要满足 `f(state) <= g(state)`,其中 `g(state)` 表示 state 到终点的真实距离; +1. A\* 算法只能保证终点第一次出队时,即找到了一条从起点到终点的最小路径,不能保证其他点出队时也是从起点到当前点的最短路径。 + + + +```python +class Solution: + def shortestPathLength(self, graph: List[List[int]]) -> int: + n = len(graph) + + def f(state): + return sum(((state >> i) & 1) == 0 for i in range(n)) + + q = [] + dist = [[inf] * (1 << n) for _ in range(n)] + for i in range(n): + heappush(q, (f(1 << i), i, 1 << i)) + dist[i][1 << i] = 0 + while q: + _, u, state = heappop(q) + if state == (1 << n) - 1: + return dist[u][state] + for v in graph[u]: + nxt = state | (1 << v) + if dist[v][nxt] > dist[u][state] + 1: + dist[v][nxt] = dist[u][state] + 1 + heappush(q, (dist[v][nxt] + f(nxt), v, nxt)) + return 0 +``` + +```java +class Solution { + private int n; + + public int shortestPathLength(int[][] graph) { + n = graph.length; + int[][] dist = new int[n][1 << n]; + for (int i = 0; i < n; ++i) { + Arrays.fill(dist[i], Integer.MAX_VALUE); + } + PriorityQueue q = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); + for (int i = 0; i < n; ++i) { + q.offer(new int[] {f(1 << i), i, 1 << i}); + dist[i][1 << i] = 0; + } + while (!q.isEmpty()) { + int[] p = q.poll(); + int u = p[1], state = p[2]; + if (state == (1 << n) - 1) { + return dist[u][state]; + } + for (int v : graph[u]) { + int nxt = state | (1 << v); + if (dist[v][nxt] > dist[u][state] + 1) { + dist[v][nxt] = dist[u][state] + 1; + q.offer(new int[] {dist[v][nxt] + f(nxt), v, nxt}); + } + } + } + return 0; + } + + private int f(int state) { + int ans = 0; + for (int i = 0; i < n; ++i) { + if (((state >> i) & 1) == 0) { + ++ans; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int n; + + int shortestPathLength(vector>& graph) { + n = graph.size(); + priority_queue, vector>, greater>> q; + vector> dist(n, vector(1 << n, INT_MAX)); + for (int i = 0; i < n; ++i) { + q.push({f(1 << i), i, 1 << i}); + dist[i][1 << i] = 0; + } + while (!q.empty()) { + auto [_, u, state] = q.top(); + q.pop(); + if (state == (1 << n) - 1) return dist[u][state]; + for (int v : graph[u]) { + int nxt = state | (1 << v); + if (dist[v][nxt] > dist[u][state] + 1) { + dist[v][nxt] = dist[u][state] + 1; + q.push({dist[v][nxt] + f(nxt), v, nxt}); + } + } + } + return 0; + } + + int f(int state) { + int ans = 0; + for (int i = 0; i < n; ++i) + if (((state >> i) & 1) == 0) + ++ans; + return ans; + } +}; ``` + + diff --git a/solution/0800-0899/0847.Shortest Path Visiting All Nodes/README_EN.md b/solution/0800-0899/0847.Shortest Path Visiting All Nodes/README_EN.md index 6d5c04121980d..b8a5bdc06141f 100644 --- a/solution/0800-0899/0847.Shortest Path Visiting All Nodes/README_EN.md +++ b/solution/0800-0899/0847.Shortest Path Visiting All Nodes/README_EN.md @@ -39,12 +39,10 @@ ## Solutions -Because each edge has the same weight, the shortest path can be solution by using BFS, and the access of the point can be recorded by state compression. +### Solution 1 -### **Python3** - ```python class Solution: def shortestPathLength(self, graph: List[List[int]]) -> int: @@ -68,35 +66,6 @@ class Solution: ans += 1 ``` -A\* search: - -```python -class Solution: - def shortestPathLength(self, graph: List[List[int]]) -> int: - n = len(graph) - - def f(state): - return sum(((state >> i) & 1) == 0 for i in range(n)) - - q = [] - dist = [[inf] * (1 << n) for _ in range(n)] - for i in range(n): - heappush(q, (f(1 << i), i, 1 << i)) - dist[i][1 << i] = 0 - while q: - _, u, state = heappop(q) - if state == (1 << n) - 1: - return dist[u][state] - for v in graph[u]: - nxt = state | (1 << v) - if dist[v][nxt] > dist[u][state] + 1: - dist[v][nxt] = dist[u][state] + 1 - heappush(q, (dist[v][nxt] + f(nxt), v, nxt)) - return 0 -``` - -### **Java** - ```java class Solution { public int shortestPathLength(int[][] graph) { @@ -127,54 +96,6 @@ class Solution { } ``` -A\* search: - -```java -class Solution { - private int n; - - public int shortestPathLength(int[][] graph) { - n = graph.length; - int[][] dist = new int[n][1 << n]; - for (int i = 0; i < n; ++i) { - Arrays.fill(dist[i], Integer.MAX_VALUE); - } - PriorityQueue q = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); - for (int i = 0; i < n; ++i) { - q.offer(new int[] {f(1 << i), i, 1 << i}); - dist[i][1 << i] = 0; - } - while (!q.isEmpty()) { - int[] p = q.poll(); - int u = p[1], state = p[2]; - if (state == (1 << n) - 1) { - return dist[u][state]; - } - for (int v : graph[u]) { - int nxt = state | (1 << v); - if (dist[v][nxt] > dist[u][state] + 1) { - dist[v][nxt] = dist[u][state] + 1; - q.offer(new int[] {dist[v][nxt] + f(nxt), v, nxt}); - } - } - } - return 0; - } - - private int f(int state) { - int ans = 0; - for (int i = 0; i < n; ++i) { - if (((state >> i) & 1) == 0) { - ++ans; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -207,87 +128,6 @@ public: }; ``` -A\* search: - -```cpp -class Solution { -public: - int n; - - int shortestPathLength(vector>& graph) { - n = graph.size(); - priority_queue, vector>, greater>> q; - vector> dist(n, vector(1 << n, INT_MAX)); - for (int i = 0; i < n; ++i) { - q.push({f(1 << i), i, 1 << i}); - dist[i][1 << i] = 0; - } - while (!q.empty()) { - auto [_, u, state] = q.top(); - q.pop(); - if (state == (1 << n) - 1) return dist[u][state]; - for (int v : graph[u]) { - int nxt = state | (1 << v); - if (dist[v][nxt] > dist[u][state] + 1) { - dist[v][nxt] = dist[u][state] + 1; - q.push({dist[v][nxt] + f(nxt), v, nxt}); - } - } - } - return 0; - } - - int f(int state) { - int ans = 0; - for (int i = 0; i < n; ++i) - if (((state >> i) & 1) == 0) - ++ans; - return ans; - } -}; -``` - -### **Rust** - -```rust -use std::collections::VecDeque; - -impl Solution { - #[allow(dead_code)] - pub fn shortest_path_length(graph: Vec>) -> i32 { - let n = graph.len(); - let mut vis = vec![vec![false; 1 << n]; n]; - let mut q = VecDeque::new(); - - // Initialize the queue - for i in 0..n { - q.push_back(((i, 1 << i), 0)); - vis[i][1 << i] = true; - } - - // Begin BFS - while !q.is_empty() { - let ((i, st), count) = q.pop_front().unwrap(); - if st == (1 << n) - 1 { - return count; - } - // If the path has not been visited - for j in &graph[i] { - let nst = st | (1 << *j); - if !vis[*j as usize][nst] { - q.push_back(((*j as usize, nst), count + 1)); - vis[*j as usize][nst] = true; - } - } - } - - -1 - } -} -``` - -### **Go** - ```go func shortestPathLength(graph [][]int) int { n := len(graph) @@ -318,8 +158,6 @@ func shortestPathLength(graph [][]int) int { } ``` -### **TypeScript** - ```ts function shortestPathLength(graph: number[][]): number { const n = graph.length; @@ -347,10 +185,156 @@ function shortestPathLength(graph: number[][]): number { } ``` -### **...** +```rust +use std::collections::VecDeque; + +impl Solution { + #[allow(dead_code)] + pub fn shortest_path_length(graph: Vec>) -> i32 { + let n = graph.len(); + let mut vis = vec![vec![false; 1 << n]; n]; + let mut q = VecDeque::new(); + + // Initialize the queue + for i in 0..n { + q.push_back(((i, 1 << i), 0)); + vis[i][1 << i] = true; + } + + // Begin BFS + while !q.is_empty() { + let ((i, st), count) = q.pop_front().unwrap(); + if st == (1 << n) - 1 { + return count; + } + // If the path has not been visited + for j in &graph[i] { + let nst = st | (1 << *j); + if !vis[*j as usize][nst] { + q.push_back(((*j as usize, nst), count + 1)); + vis[*j as usize][nst] = true; + } + } + } + -1 + } +} ``` + + +### Solution 2 + + + +```python +class Solution: + def shortestPathLength(self, graph: List[List[int]]) -> int: + n = len(graph) + + def f(state): + return sum(((state >> i) & 1) == 0 for i in range(n)) + + q = [] + dist = [[inf] * (1 << n) for _ in range(n)] + for i in range(n): + heappush(q, (f(1 << i), i, 1 << i)) + dist[i][1 << i] = 0 + while q: + _, u, state = heappop(q) + if state == (1 << n) - 1: + return dist[u][state] + for v in graph[u]: + nxt = state | (1 << v) + if dist[v][nxt] > dist[u][state] + 1: + dist[v][nxt] = dist[u][state] + 1 + heappush(q, (dist[v][nxt] + f(nxt), v, nxt)) + return 0 +``` + +```java +class Solution { + private int n; + + public int shortestPathLength(int[][] graph) { + n = graph.length; + int[][] dist = new int[n][1 << n]; + for (int i = 0; i < n; ++i) { + Arrays.fill(dist[i], Integer.MAX_VALUE); + } + PriorityQueue q = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); + for (int i = 0; i < n; ++i) { + q.offer(new int[] {f(1 << i), i, 1 << i}); + dist[i][1 << i] = 0; + } + while (!q.isEmpty()) { + int[] p = q.poll(); + int u = p[1], state = p[2]; + if (state == (1 << n) - 1) { + return dist[u][state]; + } + for (int v : graph[u]) { + int nxt = state | (1 << v); + if (dist[v][nxt] > dist[u][state] + 1) { + dist[v][nxt] = dist[u][state] + 1; + q.offer(new int[] {dist[v][nxt] + f(nxt), v, nxt}); + } + } + } + return 0; + } + + private int f(int state) { + int ans = 0; + for (int i = 0; i < n; ++i) { + if (((state >> i) & 1) == 0) { + ++ans; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int n; + + int shortestPathLength(vector>& graph) { + n = graph.size(); + priority_queue, vector>, greater>> q; + vector> dist(n, vector(1 << n, INT_MAX)); + for (int i = 0; i < n; ++i) { + q.push({f(1 << i), i, 1 << i}); + dist[i][1 << i] = 0; + } + while (!q.empty()) { + auto [_, u, state] = q.top(); + q.pop(); + if (state == (1 << n) - 1) return dist[u][state]; + for (int v : graph[u]) { + int nxt = state | (1 << v); + if (dist[v][nxt] > dist[u][state] + 1) { + dist[v][nxt] = dist[u][state] + 1; + q.push({dist[v][nxt] + f(nxt), v, nxt}); + } + } + } + return 0; + } + + int f(int state) { + int ans = 0; + for (int i = 0; i < n; ++i) + if (((state >> i) & 1) == 0) + ++ans; + return ans; + } +}; ``` + + diff --git a/solution/0800-0899/0848.Shifting Letters/README.md b/solution/0800-0899/0848.Shifting Letters/README.md index 3abbe2f20368f..c22b87517f3ab 100644 --- a/solution/0800-0899/0848.Shifting Letters/README.md +++ b/solution/0800-0899/0848.Shifting Letters/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:后缀和** +### 方法一:后缀和 对于字符串 $s$ 中的每个字符,我们需要计算其最终的偏移量,即 `shifts[i]` 与 `shifts[i + 1]` 与 `shifts[i + 2]` ... 的和。我们可以使用后缀和的思想,从后往前遍历 `shifts`,计算每个字符的最终偏移量,然后对 $26$ 取模,得到最终的字符。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def shiftingLetters(self, s: str, shifts: List[int]) -> str: @@ -88,22 +82,6 @@ class Solution: return ''.join(ans) ``` -```python -class Solution: - def shiftingLetters(self, s: str, shifts: List[int]) -> str: - n, t = len(s), 0 - s = list(s) - for i in range(n - 1, -1, -1): - t += shifts[i] - j = (ord(s[i]) - ord('a') + t) % 26 - s[i] = ascii_lowercase[j] - return ''.join(s) -``` - -### **Java** - - - ```java class Solution { public String shiftingLetters(String s, int[] shifts) { @@ -120,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +114,6 @@ public: }; ``` -### **Go** - ```go func shiftingLetters(s string, shifts []int) string { t := 0 @@ -154,10 +128,24 @@ func shiftingLetters(s string, shifts []int) string { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def shiftingLetters(self, s: str, shifts: List[int]) -> str: + n, t = len(s), 0 + s = list(s) + for i in range(n - 1, -1, -1): + t += shifts[i] + j = (ord(s[i]) - ord('a') + t) % 26 + s[i] = ascii_lowercase[j] + return ''.join(s) ``` + + diff --git a/solution/0800-0899/0848.Shifting Letters/README_EN.md b/solution/0800-0899/0848.Shifting Letters/README_EN.md index caa5ab4abf075..92d7459c98463 100644 --- a/solution/0800-0899/0848.Shifting Letters/README_EN.md +++ b/solution/0800-0899/0848.Shifting Letters/README_EN.md @@ -47,9 +47,9 @@ After shifting the first 3 letters of s by 9, we have "rpl", the answe ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,20 +72,6 @@ class Solution: return ''.join(ans) ``` -```python -class Solution: - def shiftingLetters(self, s: str, shifts: List[int]) -> str: - n, t = len(s), 0 - s = list(s) - for i in range(n - 1, -1, -1): - t += shifts[i] - j = (ord(s[i]) - ord('a') + t) % 26 - s[i] = ascii_lowercase[j] - return ''.join(s) -``` - -### **Java** - ```java class Solution { public String shiftingLetters(String s, int[] shifts) { @@ -102,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +104,6 @@ public: }; ``` -### **Go** - ```go func shiftingLetters(s string, shifts []int) string { t := 0 @@ -136,10 +118,24 @@ func shiftingLetters(s string, shifts []int) string { } ``` -### **...** + + +### Solution 2 -``` + +```python +class Solution: + def shiftingLetters(self, s: str, shifts: List[int]) -> str: + n, t = len(s), 0 + s = list(s) + for i in range(n - 1, -1, -1): + t += shifts[i] + j = (ord(s[i]) - ord('a') + t) % 26 + s[i] = ascii_lowercase[j] + return ''.join(s) ``` + + diff --git a/solution/0800-0899/0849.Maximize Distance to Closest Person/README.md b/solution/0800-0899/0849.Maximize Distance to Closest Person/README.md index 44052cc6a1bde..88fd4c4340c93 100644 --- a/solution/0800-0899/0849.Maximize Distance to Closest Person/README.md +++ b/solution/0800-0899/0849.Maximize Distance to Closest Person/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们定义两个变量 $first$ 和 $last$ 分别表示第一个人和最后一个人的位置,用变量 $d$ 表示两个人之间的最大距离。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def maxDistToClosest(self, seats: List[int]) -> int: @@ -90,10 +84,6 @@ class Solution: return max(first, len(seats) - last - 1, d // 2) ``` -### **Java** - - - ```java class Solution { public int maxDistToClosest(int[] seats) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +127,6 @@ public: }; ``` -### **Go** - ```go func maxDistToClosest(seats []int) int { first, last := -1, -1 @@ -160,8 +146,6 @@ func maxDistToClosest(seats []int) int { } ``` -### **TypeScript** - ```ts function maxDistToClosest(seats: number[]): number { let first = -1, @@ -183,10 +167,6 @@ function maxDistToClosest(seats: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0849.Maximize Distance to Closest Person/README_EN.md b/solution/0800-0899/0849.Maximize Distance to Closest Person/README_EN.md index e459a09fd99c1..8b971946b8049 100644 --- a/solution/0800-0899/0849.Maximize Distance to Closest Person/README_EN.md +++ b/solution/0800-0899/0849.Maximize Distance to Closest Person/README_EN.md @@ -53,9 +53,9 @@ This is the maximum distance possible, so the answer is 3. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return max(first, len(seats) - last - 1, d // 2) ``` -### **Java** - ```java class Solution { public int maxDistToClosest(int[] seats) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +115,6 @@ public: }; ``` -### **Go** - ```go func maxDistToClosest(seats []int) int { first, last := -1, -1 @@ -140,8 +134,6 @@ func maxDistToClosest(seats []int) int { } ``` -### **TypeScript** - ```ts function maxDistToClosest(seats: number[]): number { let first = -1, @@ -163,10 +155,6 @@ function maxDistToClosest(seats: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0850.Rectangle Area II/README.md b/solution/0800-0899/0850.Rectangle Area II/README.md index 78b776bf6d903..d2cfe9623a322 100644 --- a/solution/0800-0899/0850.Rectangle Area II/README.md +++ b/solution/0800-0899/0850.Rectangle Area II/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:离散化 + 线段树 + 扫描线** +### 方法一:离散化 + 线段树 + 扫描线 线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 $log(width)$。更新某个元素的值,只需要更新 $log(width)$ 个区间,并且这些区间都包含在一个包含该元素的大区间内。区间修改时,需要使用**懒标记**保证效率。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Node: def __init__(self): @@ -137,10 +131,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Node { int l, r, cnt, length; @@ -240,8 +230,6 @@ class Solution { } ``` -### **C++** - ```cpp class Node { public: @@ -331,8 +319,6 @@ public: }; ``` -### **Go** - ```go func rectangleArea(rectangles [][]int) int { var mod int = 1e9 + 7 @@ -431,10 +417,6 @@ func (t *segmentTree) pushup(u int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0850.Rectangle Area II/README_EN.md b/solution/0800-0899/0850.Rectangle Area II/README_EN.md index bb14ac41c5a11..28c269cb5a0d5 100644 --- a/solution/0800-0899/0850.Rectangle Area II/README_EN.md +++ b/solution/0800-0899/0850.Rectangle Area II/README_EN.md @@ -42,9 +42,9 @@ From (1,0) to (2,3), all three rectangles overlap. ## Solutions - +### Solution 1 -### **Python3** + ```python class Node: @@ -113,8 +113,6 @@ class Solution: return ans ``` -### **Java** - ```java class Node { int l, r, cnt, length; @@ -214,8 +212,6 @@ class Solution { } ``` -### **C++** - ```cpp class Node { public: @@ -305,8 +301,6 @@ public: }; ``` -### **Go** - ```go func rectangleArea(rectangles [][]int) int { var mod int = 1e9 + 7 @@ -405,10 +399,6 @@ func (t *segmentTree) pushup(u int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0851.Loud and Rich/README.md b/solution/0800-0899/0851.Loud and Rich/README.md index ea165526c9331..5fae69c7a61e1 100644 --- a/solution/0800-0899/0851.Loud and Rich/README.md +++ b/solution/0800-0899/0851.Loud and Rich/README.md @@ -55,9 +55,7 @@ answer[7] = 7, ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们先用邻接表 $g$ 存储 $richer$ 数组中的信息,其中 $g[i]$ 表示所有比 $i$ 更有钱的人的集合。 @@ -67,10 +65,6 @@ answer[7] = 7, -### **Python3** - - - ```python class Solution: def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]: @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +155,6 @@ public: }; ``` -### **Go** - ```go func loudAndRich(richer [][]int, quiet []int) []int { n := len(quiet) @@ -201,8 +187,6 @@ func loudAndRich(richer [][]int, quiet []int) []int { } ``` -### **TypeScript** - ```ts function loudAndRich(richer: number[][], quiet: number[]): number[] { const n = quiet.length; @@ -230,10 +214,6 @@ function loudAndRich(richer: number[][], quiet: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0851.Loud and Rich/README_EN.md b/solution/0800-0899/0851.Loud and Rich/README_EN.md index 34b24052a89ae..07803ba26cc57 100644 --- a/solution/0800-0899/0851.Loud and Rich/README_EN.md +++ b/solution/0800-0899/0851.Loud and Rich/README_EN.md @@ -49,9 +49,9 @@ The other answers can be filled out with similar reasoning. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -115,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +143,6 @@ public: }; ``` -### **Go** - ```go func loudAndRich(richer [][]int, quiet []int) []int { n := len(quiet) @@ -181,8 +175,6 @@ func loudAndRich(richer [][]int, quiet []int) []int { } ``` -### **TypeScript** - ```ts function loudAndRich(richer: number[][], quiet: number[]): number[] { const n = quiet.length; @@ -210,10 +202,6 @@ function loudAndRich(richer: number[][], quiet: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0852.Peak Index in a Mountain Array/README.md b/solution/0800-0899/0852.Peak Index in a Mountain Array/README.md index 758d9fffd8f12..d0c7e0a0a3ee2 100644 --- a/solution/0800-0899/0852.Peak Index in a Mountain Array/README.md +++ b/solution/0800-0899/0852.Peak Index in a Mountain Array/README.md @@ -57,16 +57,10 @@ ## 解法 - - -二分查找。 +### 方法一 -### **Python3** - - - ```python class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: @@ -80,10 +74,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int peakIndexInMountainArray(int[] arr) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func peakIndexInMountainArray(arr []int) int { left, right := 1, len(arr)-2 @@ -137,30 +123,6 @@ func peakIndexInMountainArray(arr []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} arr - * @return {number} - */ -var peakIndexInMountainArray = function (arr) { - let left = 1; - let right = arr.length - 2; - while (left < right) { - const mid = (left + right) >> 1; - if (arr[mid] < arr[mid + 1]) { - left = mid + 1; - } else { - right = mid; - } - } - return left; -}; -``` - -### **TypeScript** - ```ts function peakIndexInMountainArray(arr: number[]): number { let left = 1, @@ -177,8 +139,6 @@ function peakIndexInMountainArray(arr: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn peak_index_in_mountain_array(arr: Vec) -> i32 { @@ -197,10 +157,26 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} arr + * @return {number} + */ +var peakIndexInMountainArray = function (arr) { + let left = 1; + let right = arr.length - 2; + while (left < right) { + const mid = (left + right) >> 1; + if (arr[mid] < arr[mid + 1]) { + left = mid + 1; + } else { + right = mid; + } + } + return left; +}; ``` + + diff --git a/solution/0800-0899/0852.Peak Index in a Mountain Array/README_EN.md b/solution/0800-0899/0852.Peak Index in a Mountain Array/README_EN.md index b91019ee3b13d..d1f7f1e1c9f1c 100644 --- a/solution/0800-0899/0852.Peak Index in a Mountain Array/README_EN.md +++ b/solution/0800-0899/0852.Peak Index in a Mountain Array/README_EN.md @@ -53,12 +53,10 @@ ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: @@ -72,8 +70,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { public int peakIndexInMountainArray(int[] arr) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func peakIndexInMountainArray(arr []int) int { left, right := 1, len(arr)-2 @@ -127,30 +119,6 @@ func peakIndexInMountainArray(arr []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} arr - * @return {number} - */ -var peakIndexInMountainArray = function (arr) { - let left = 1; - let right = arr.length - 2; - while (left < right) { - const mid = (left + right) >> 1; - if (arr[mid] > arr[mid + 1]) { - right = mid; - } else { - left = mid + 1; - } - } - return left; -}; -``` - -### **TypeScript** - ```ts function peakIndexInMountainArray(arr: number[]): number { let left = 1, @@ -167,8 +135,6 @@ function peakIndexInMountainArray(arr: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn peak_index_in_mountain_array(arr: Vec) -> i32 { @@ -187,10 +153,26 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} arr + * @return {number} + */ +var peakIndexInMountainArray = function (arr) { + let left = 1; + let right = arr.length - 2; + while (left < right) { + const mid = (left + right) >> 1; + if (arr[mid] < arr[mid + 1]) { + left = mid + 1; + } else { + right = mid; + } + } + return left; +}; ``` + + diff --git a/solution/0800-0899/0853.Car Fleet/README.md b/solution/0800-0899/0853.Car Fleet/README.md index 72a06e3802c88..1f383a9d9bf38 100644 --- a/solution/0800-0899/0853.Car Fleet/README.md +++ b/solution/0800-0899/0853.Car Fleet/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们将车辆按照位置降序排序,这样我们只需要比较相邻两辆车的到达时间即可。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int carFleet(int target, int[] position, int[] speed) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func carFleet(target int, position []int, speed []int) (ans int) { n := len(position) @@ -168,8 +154,6 @@ func carFleet(target int, position []int, speed []int) (ans int) { } ``` -### **TypeScript** - ```ts function carFleet(target: number, position: number[], speed: number[]): number { const n = position.length; @@ -190,10 +174,6 @@ function carFleet(target: number, position: number[], speed: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0853.Car Fleet/README_EN.md b/solution/0800-0899/0853.Car Fleet/README_EN.md index fa705811cfa78..f60c93d179b28 100644 --- a/solution/0800-0899/0853.Car Fleet/README_EN.md +++ b/solution/0800-0899/0853.Car Fleet/README_EN.md @@ -61,9 +61,9 @@ Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int carFleet(int target, int[] position, int[] speed) { @@ -103,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +125,6 @@ public: }; ``` -### **Go** - ```go func carFleet(target int, position []int, speed []int) (ans int) { n := len(position) @@ -151,8 +145,6 @@ func carFleet(target int, position []int, speed []int) (ans int) { } ``` -### **TypeScript** - ```ts function carFleet(target: number, position: number[], speed: number[]): number { const n = position.length; @@ -173,10 +165,6 @@ function carFleet(target: number, position: number[], speed: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0854.K-Similar Strings/README.md b/solution/0800-0899/0854.K-Similar Strings/README.md index 02c8790f55e31..ebaf0db510f27 100644 --- a/solution/0800-0899/0854.K-Similar Strings/README.md +++ b/solution/0800-0899/0854.K-Similar Strings/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 本题实际上是一类经典的问题:求解最小操作次数。从一个初始状态 $s_1$,经过最少 $k$ 次状态转换,变成目标状态 $s_2$。字符串长度不超过 $20$,我们考虑使用 BFS 搜索来求解。 @@ -53,27 +51,8 @@ 复杂度分析:BFS 剪枝不讨论时空复杂度。 -**方法二:A\* 算法(进阶)** - -A\* 搜索算法(A\* 读作 A-star),简称 A\* 算法,是一种在图形平面上,对于有多个节点的路径求出最低通过成本的算法。它属于图遍历和最佳优先搜索算法(英文:Best-first search),亦是 BFS 的改进。 - -A\* 算法主要步骤如下: - -1. 将方法一中的 BFS 队列转换为优先队列(小根堆); -1. 队列中的每个元素为 `(dist[s] + f(s), s)`,`dist[s]` 表示从初始状态 $s_1$ 到当前状态 $s$ 的距离,`f(s)` 表示从当前状态 $s$ 到目标状态 $s_2$ 的估计距离,这两个距离之和作为堆排序的依据; -1. 当终点第一次出队时,说明找到了从起点 $s_1$ 到终点 $s_2$ 的最短路径,直接返回对应的距离; -1. `f(s)` 是估价函数,并且估价函数要满足 `f(s) <= g(s)`,其中 `g(s)` 表示 $s$ 到终点 $s_2$ 的真实距离; - -需要注意的是,A\* 算法只能保证终点第一次出队时,即找到了一条从起点到终点的最小路径,不能保证其他点出队时也是从起点到当前点的最短路径。 - -复杂度分析:启发式搜索不讨论时空复杂度。 - -### **Python3** - - - ```python class Solution: def kSimilarity(self, s1: str, s2: str) -> int: @@ -102,40 +81,6 @@ class Solution: ans += 1 ``` -```python -class Solution: - def kSimilarity(self, s1: str, s2: str) -> int: - def f(s): - cnt = sum(c != s2[i] for i, c in enumerate(s)) - return (cnt + 1) >> 1 - - def next(s): - i = 0 - while s[i] == s2[i]: - i += 1 - res = [] - for j in range(i + 1, n): - if s[j] == s2[i] and s[j] != s2[j]: - res.append(s2[: i + 1] + s[i + 1 : j] + s[i] + s[j + 1 :]) - return res - - q = [(f(s1), s1)] - dist = {s1: 0} - n = len(s1) - while 1: - _, s = heappop(q) - if s == s2: - return dist[s] - for nxt in next(s): - if nxt not in dist or dist[nxt] > dist[s] + 1: - dist[nxt] = dist[s] + 1 - heappush(q, (dist[nxt] + f(nxt), nxt)) -``` - -### **Java** - - - ```java class Solution { public int kSimilarity(String s1, String s2) { @@ -186,6 +131,133 @@ class Solution { } ``` +```cpp +class Solution { +public: + int kSimilarity(string s1, string s2) { + queue q{{s1}}; + unordered_set vis{{s1}}; + int ans = 0; + while (1) { + for (int i = q.size(); i; --i) { + auto s = q.front(); + q.pop(); + if (s == s2) { + return ans; + } + for (auto& nxt : next(s, s2)) { + if (!vis.count(nxt)) { + vis.insert(nxt); + q.push(nxt); + } + } + } + ++ans; + } + } + + vector next(string& s, string& s2) { + int i = 0, n = s.size(); + for (; s[i] == s2[i]; ++i) {} + vector res; + for (int j = i + 1; j < n; ++j) { + if (s[j] == s2[i] && s[j] != s2[j]) { + swap(s[i], s[j]); + res.push_back(s); + swap(s[i], s[j]); + } + } + return res; + } +}; +``` + +```go +func kSimilarity(s1 string, s2 string) int { + next := func(s string) []string { + i := 0 + res := []string{} + for ; s[i] == s2[i]; i++ { + } + for j := i + 1; j < len(s1); j++ { + if s[j] == s2[i] && s[j] != s2[j] { + res = append(res, s[:i]+string(s[j])+s[i+1:j]+string(s[i])+s[j+1:]) + } + } + return res + } + + q := []string{s1} + vis := map[string]bool{s1: true} + ans := 0 + for { + for i := len(q); i > 0; i-- { + s := q[0] + q = q[1:] + if s == s2 { + return ans + } + for _, nxt := range next(s) { + if !vis[nxt] { + vis[nxt] = true + q = append(q, nxt) + } + } + } + ans++ + } +} +``` + + + +### 方法二:A\* 算法(进阶) + +A\* 搜索算法(A\* 读作 A-star),简称 A\* 算法,是一种在图形平面上,对于有多个节点的路径求出最低通过成本的算法。它属于图遍历和最佳优先搜索算法(英文:Best-first search),亦是 BFS 的改进。 + +A\* 算法主要步骤如下: + +1. 将方法一中的 BFS 队列转换为优先队列(小根堆); +1. 队列中的每个元素为 `(dist[s] + f(s), s)`,`dist[s]` 表示从初始状态 $s_1$ 到当前状态 $s$ 的距离,`f(s)` 表示从当前状态 $s$ 到目标状态 $s_2$ 的估计距离,这两个距离之和作为堆排序的依据; +1. 当终点第一次出队时,说明找到了从起点 $s_1$ 到终点 $s_2$ 的最短路径,直接返回对应的距离; +1. `f(s)` 是估价函数,并且估价函数要满足 `f(s) <= g(s)`,其中 `g(s)` 表示 $s$ 到终点 $s_2$ 的真实距离; + +需要注意的是,A\* 算法只能保证终点第一次出队时,即找到了一条从起点到终点的最小路径,不能保证其他点出队时也是从起点到当前点的最短路径。 + +复杂度分析:启发式搜索不讨论时空复杂度。 + + + +```python +class Solution: + def kSimilarity(self, s1: str, s2: str) -> int: + def f(s): + cnt = sum(c != s2[i] for i, c in enumerate(s)) + return (cnt + 1) >> 1 + + def next(s): + i = 0 + while s[i] == s2[i]: + i += 1 + res = [] + for j in range(i + 1, n): + if s[j] == s2[i] and s[j] != s2[j]: + res.append(s2[: i + 1] + s[i + 1 : j] + s[i] + s[j + 1 :]) + return res + + q = [(f(s1), s1)] + dist = {s1: 0} + n = len(s1) + while 1: + _, s = heappop(q) + if s == s2: + return dist[s] + for nxt in next(s): + if nxt not in dist or dist[nxt] > dist[s] + 1: + dist[nxt] = dist[s] + 1 + heappush(q, (dist[nxt] + f(nxt), nxt)) +``` + ```java class Solution { public int kSimilarity(String s1, String s2) { @@ -243,49 +315,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int kSimilarity(string s1, string s2) { - queue q{{s1}}; - unordered_set vis{{s1}}; - int ans = 0; - while (1) { - for (int i = q.size(); i; --i) { - auto s = q.front(); - q.pop(); - if (s == s2) { - return ans; - } - for (auto& nxt : next(s, s2)) { - if (!vis.count(nxt)) { - vis.insert(nxt); - q.push(nxt); - } - } - } - ++ans; - } - } - - vector next(string& s, string& s2) { - int i = 0, n = s.size(); - for (; s[i] == s2[i]; ++i) {} - vector res; - for (int j = i + 1; j < n; ++j) { - if (s[j] == s2[i] && s[j] != s2[j]) { - swap(s[i], s[j]); - res.push_back(s); - swap(s[i], s[j]); - } - } - return res; - } -}; -``` - ```cpp using pis = pair; @@ -335,45 +364,6 @@ public: }; ``` -### **Go** - -```go -func kSimilarity(s1 string, s2 string) int { - next := func(s string) []string { - i := 0 - res := []string{} - for ; s[i] == s2[i]; i++ { - } - for j := i + 1; j < len(s1); j++ { - if s[j] == s2[i] && s[j] != s2[j] { - res = append(res, s[:i]+string(s[j])+s[i+1:j]+string(s[i])+s[j+1:]) - } - } - return res - } - - q := []string{s1} - vis := map[string]bool{s1: true} - ans := 0 - for { - for i := len(q); i > 0; i-- { - s := q[0] - q = q[1:] - if s == s2 { - return ans - } - for _, nxt := range next(s) { - if !vis[nxt] { - vis[nxt] = true - q = append(q, nxt) - } - } - } - ans++ - } -} -``` - ```go func kSimilarity(s1 string, s2 string) int { next := func(s string) []string { @@ -431,10 +421,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0854.K-Similar Strings/README_EN.md b/solution/0800-0899/0854.K-Similar Strings/README_EN.md index 9d2c884378af8..86f6cb805816f 100644 --- a/solution/0800-0899/0854.K-Similar Strings/README_EN.md +++ b/solution/0800-0899/0854.K-Similar Strings/README_EN.md @@ -37,12 +37,10 @@ ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def kSimilarity(self, s1: str, s2: str) -> int: @@ -71,38 +69,6 @@ class Solution: ans += 1 ``` -```python -class Solution: - def kSimilarity(self, s1: str, s2: str) -> int: - def f(s): - cnt = sum(c != s2[i] for i, c in enumerate(s)) - return (cnt + 1) >> 1 - - def next(s): - i = 0 - while s[i] == s2[i]: - i += 1 - res = [] - for j in range(i + 1, n): - if s[j] == s2[i] and s[j] != s2[j]: - res.append(s2[: i + 1] + s[i + 1 : j] + s[i] + s[j + 1 :]) - return res - - q = [(f(s1), s1)] - dist = {s1: 0} - n = len(s1) - while 1: - _, s = heappop(q) - if s == s2: - return dist[s] - for nxt in next(s): - if nxt not in dist or dist[nxt] > dist[s] + 1: - dist[nxt] = dist[s] + 1 - heappush(q, (dist[nxt] + f(nxt), nxt)) -``` - -### **Java** - ```java class Solution { public int kSimilarity(String s1, String s2) { @@ -153,6 +119,120 @@ class Solution { } ``` +```cpp +class Solution { +public: + int kSimilarity(string s1, string s2) { + queue q{{s1}}; + unordered_set vis{{s1}}; + int ans = 0; + while (1) { + for (int i = q.size(); i; --i) { + auto s = q.front(); + q.pop(); + if (s == s2) { + return ans; + } + for (auto& nxt : next(s, s2)) { + if (!vis.count(nxt)) { + vis.insert(nxt); + q.push(nxt); + } + } + } + ++ans; + } + } + + vector next(string& s, string& s2) { + int i = 0, n = s.size(); + for (; s[i] == s2[i]; ++i) {} + vector res; + for (int j = i + 1; j < n; ++j) { + if (s[j] == s2[i] && s[j] != s2[j]) { + swap(s[i], s[j]); + res.push_back(s); + swap(s[i], s[j]); + } + } + return res; + } +}; +``` + +```go +func kSimilarity(s1 string, s2 string) int { + next := func(s string) []string { + i := 0 + res := []string{} + for ; s[i] == s2[i]; i++ { + } + for j := i + 1; j < len(s1); j++ { + if s[j] == s2[i] && s[j] != s2[j] { + res = append(res, s[:i]+string(s[j])+s[i+1:j]+string(s[i])+s[j+1:]) + } + } + return res + } + + q := []string{s1} + vis := map[string]bool{s1: true} + ans := 0 + for { + for i := len(q); i > 0; i-- { + s := q[0] + q = q[1:] + if s == s2 { + return ans + } + for _, nxt := range next(s) { + if !vis[nxt] { + vis[nxt] = true + q = append(q, nxt) + } + } + } + ans++ + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def kSimilarity(self, s1: str, s2: str) -> int: + def f(s): + cnt = sum(c != s2[i] for i, c in enumerate(s)) + return (cnt + 1) >> 1 + + def next(s): + i = 0 + while s[i] == s2[i]: + i += 1 + res = [] + for j in range(i + 1, n): + if s[j] == s2[i] and s[j] != s2[j]: + res.append(s2[: i + 1] + s[i + 1 : j] + s[i] + s[j + 1 :]) + return res + + q = [(f(s1), s1)] + dist = {s1: 0} + n = len(s1) + while 1: + _, s = heappop(q) + if s == s2: + return dist[s] + for nxt in next(s): + if nxt not in dist or dist[nxt] > dist[s] + 1: + dist[nxt] = dist[s] + 1 + heappush(q, (dist[nxt] + f(nxt), nxt)) +``` + ```java class Solution { public int kSimilarity(String s1, String s2) { @@ -210,49 +290,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int kSimilarity(string s1, string s2) { - queue q{{s1}}; - unordered_set vis{{s1}}; - int ans = 0; - while (1) { - for (int i = q.size(); i; --i) { - auto s = q.front(); - q.pop(); - if (s == s2) { - return ans; - } - for (auto& nxt : next(s, s2)) { - if (!vis.count(nxt)) { - vis.insert(nxt); - q.push(nxt); - } - } - } - ++ans; - } - } - - vector next(string& s, string& s2) { - int i = 0, n = s.size(); - for (; s[i] == s2[i]; ++i) {} - vector res; - for (int j = i + 1; j < n; ++j) { - if (s[j] == s2[i] && s[j] != s2[j]) { - swap(s[i], s[j]); - res.push_back(s); - swap(s[i], s[j]); - } - } - return res; - } -}; -``` - ```cpp using pis = pair; @@ -302,45 +339,6 @@ public: }; ``` -### **Go** - -```go -func kSimilarity(s1 string, s2 string) int { - next := func(s string) []string { - i := 0 - res := []string{} - for ; s[i] == s2[i]; i++ { - } - for j := i + 1; j < len(s1); j++ { - if s[j] == s2[i] && s[j] != s2[j] { - res = append(res, s[:i]+string(s[j])+s[i+1:j]+string(s[i])+s[j+1:]) - } - } - return res - } - - q := []string{s1} - vis := map[string]bool{s1: true} - ans := 0 - for { - for i := len(q); i > 0; i-- { - s := q[0] - q = q[1:] - if s == s2 { - return ans - } - for _, nxt := range next(s) { - if !vis[nxt] { - vis[nxt] = true - q = append(q, nxt) - } - } - } - ans++ - } -} -``` - ```go func kSimilarity(s1 string, s2 string) int { next := func(s string) []string { @@ -398,10 +396,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0855.Exam Room/README.md b/solution/0800-0899/0855.Exam Room/README.md index 13369b9394393..817ebcd0b9215 100644 --- a/solution/0800-0899/0855.Exam Room/README.md +++ b/solution/0800-0899/0855.Exam Room/README.md @@ -40,9 +40,7 @@ seat() -> 5,学生最后坐在 5 号座位上。 ## 解法 - - -**方法一:有序集合 + 哈希表** +### 方法一:有序集合 + 哈希表 考虑到每次 $seat()$ 时都需要找到最大距离的座位,我们可以使用有序集合来保存座位区间。有序集合的每个元素为一个二元组 $(l, r)$,表示 $l$ 和 $r$ 之间(不包括 $l$ 和 $r$)的座位可以坐学生。初始时有序集合中只有一个元素 $(-1, n)$,表示 $(-1, n)$ 之间的座位可以坐学生。 @@ -52,10 +50,6 @@ seat() -> 5,学生最后坐在 5 号座位上。 -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -107,10 +101,6 @@ class ExamRoom: # obj.leave(p) ``` -### **Java** - - - ```java class ExamRoom { private TreeSet ts = new TreeSet<>((a, b) -> { @@ -173,8 +163,6 @@ class ExamRoom { */ ``` -### **C++** - ```cpp int N; @@ -247,8 +235,6 @@ private: */ ``` -### **Go** - ```go type ExamRoom struct { rbt *redblacktree.Tree @@ -319,10 +305,6 @@ func (this *ExamRoom) del(s []int) { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0855.Exam Room/README_EN.md b/solution/0800-0899/0855.Exam Room/README_EN.md index 688970f00ff08..dc78bb96b197b 100644 --- a/solution/0800-0899/0855.Exam Room/README_EN.md +++ b/solution/0800-0899/0855.Exam Room/README_EN.md @@ -50,9 +50,9 @@ examRoom.seat(); // return 5, the student sits at the last seat number 5. ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedList @@ -105,8 +105,6 @@ class ExamRoom: # obj.leave(p) ``` -### **Java** - ```java class ExamRoom { private TreeSet ts = new TreeSet<>((a, b) -> { @@ -169,8 +167,6 @@ class ExamRoom { */ ``` -### **C++** - ```cpp int N; @@ -243,8 +239,6 @@ private: */ ``` -### **Go** - ```go type ExamRoom struct { rbt *redblacktree.Tree @@ -315,10 +309,6 @@ func (this *ExamRoom) del(s []int) { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0856.Score of Parentheses/README.md b/solution/0800-0899/0856.Score of Parentheses/README.md index 8e860110a438c..63fc020a9ab26 100644 --- a/solution/0800-0899/0856.Score of Parentheses/README.md +++ b/solution/0800-0899/0856.Score of Parentheses/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们通过观察发现,`()` 是唯一贡献分数的结构,外括号只是为该结构添加了一些乘数。所以我们只需要关心 `()`。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def scoreOfParentheses(self, s: str) -> int: @@ -100,10 +94,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int scoreOfParentheses(String s) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go func scoreOfParentheses(s string) int { ans, d := 0, 0 @@ -164,10 +150,6 @@ func scoreOfParentheses(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0856.Score of Parentheses/README_EN.md b/solution/0800-0899/0856.Score of Parentheses/README_EN.md index 07b43d7ea9275..1756a6c1b6609 100644 --- a/solution/0800-0899/0856.Score of Parentheses/README_EN.md +++ b/solution/0800-0899/0856.Score of Parentheses/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int scoreOfParentheses(String s) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +104,6 @@ public: }; ``` -### **Go** - ```go func scoreOfParentheses(s string) int { ans, d := 0, 0 @@ -127,10 +121,6 @@ func scoreOfParentheses(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README.md b/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README.md index 3658cea3b1446..d1bc877304d3f 100644 --- a/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README.md +++ b/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列(大根堆)** +### 方法一:贪心 + 优先队列(大根堆) 我们假设选取了某一个工资组,总工作质量为 `tot`,总支付金额为 `c`。每个工人的工作质量为 $q_i$,工资为 $w_i$。那么,对于此工资组的每个工人,均满足 $c\times \frac{q_i}{tot} \ge w_i$。即 $c\ge tot\times \frac{w_i}{q_i}$。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def mincostToHireWorkers( @@ -85,10 +79,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public double mincostToHireWorkers(int[] quality, int[] wage, int k) { @@ -124,8 +114,6 @@ class Pair { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func mincostToHireWorkers(quality []int, wage []int, k int) float64 { t := []pair{} @@ -193,10 +179,6 @@ func (h *hp) Pop() any { func (h *hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README_EN.md b/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README_EN.md index 29a4b7da1d20f..4ccf14d8b51e4 100644 --- a/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README_EN.md +++ b/solution/0800-0899/0857.Minimum Cost to Hire K Workers/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public double mincostToHireWorkers(int[] quality, int[] wage, int k) { @@ -101,8 +99,6 @@ class Pair { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +126,6 @@ public: }; ``` -### **Go** - ```go func mincostToHireWorkers(quality []int, wage []int, k int) float64 { t := []pair{} @@ -170,10 +164,6 @@ func (h *hp) Pop() any { func (h *hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0858.Mirror Reflection/README.md b/solution/0800-0899/0858.Mirror Reflection/README.md index d07d65e48a445..3ff7e575952d8 100644 --- a/solution/0800-0899/0858.Mirror Reflection/README.md +++ b/solution/0800-0899/0858.Mirror Reflection/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 根据题意,光线在每次反射时,都会向上或向下移动 $q$ 的距离,向右移动 $p$ 的距离。而由于光线最后一定会遇到接收器,因此,我们需要找到一个最小的 $k$,使得 $k \times q$ 是 $p$ 的倍数。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def mirrorReflection(self, p: int, q: int) -> int: @@ -67,10 +61,6 @@ class Solution: return 0 if p == 1 else 2 ``` -### **Java** - - - ```java class Solution { public int mirrorReflection(int p, int q) { @@ -89,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +94,6 @@ public: }; ``` -### **Go** - ```go func mirrorReflection(p int, q int) int { g := gcd(p, q) @@ -130,8 +116,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function mirrorReflection(p: number, q: number): number { const g = gcd(p, q); @@ -148,10 +132,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0858.Mirror Reflection/README_EN.md b/solution/0800-0899/0858.Mirror Reflection/README_EN.md index 5c7c98c1e5e47..a66f506d47b79 100644 --- a/solution/0800-0899/0858.Mirror Reflection/README_EN.md +++ b/solution/0800-0899/0858.Mirror Reflection/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return 0 if p == 1 else 2 ``` -### **Java** - ```java class Solution { public int mirrorReflection(int p, int q) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,8 +85,6 @@ public: }; ``` -### **Go** - ```go func mirrorReflection(p int, q int) int { g := gcd(p, q) @@ -113,8 +107,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function mirrorReflection(p: number, q: number): number { const g = gcd(p, q); @@ -131,10 +123,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0859.Buddy Strings/README.md b/solution/0800-0899/0859.Buddy Strings/README.md index dc50c3505151d..9441a5a9d995f 100644 --- a/solution/0800-0899/0859.Buddy Strings/README.md +++ b/solution/0800-0899/0859.Buddy Strings/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:字符统计** +### 方法一:字符统计 首先,先理解亲密字符串的意思: @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def buddyStrings(self, s: str, goal: str) -> bool: @@ -85,10 +79,6 @@ class Solution: return diff == 2 or (diff == 0 and any(v > 1 for v in cnt1.values())) ``` -### **Java** - - - ```java class Solution { public boolean buddyStrings(String s, String goal) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +135,6 @@ public: }; ``` -### **Go** - ```go func buddyStrings(s string, goal string) bool { m, n := len(s), len(goal) @@ -178,8 +164,6 @@ func buddyStrings(s string, goal string) bool { } ``` -### **TypeScript** - ```ts function buddyStrings(s: string, goal: string): boolean { const m = s.length; @@ -206,10 +190,6 @@ function buddyStrings(s: string, goal: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0859.Buddy Strings/README_EN.md b/solution/0800-0899/0859.Buddy Strings/README_EN.md index e24b3cae001ea..b434a6a70f382 100644 --- a/solution/0800-0899/0859.Buddy Strings/README_EN.md +++ b/solution/0800-0899/0859.Buddy Strings/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return diff == 2 or (diff == 0 and any(v > 1 for v in cnt1.values())) ``` -### **Java** - ```java class Solution { public boolean buddyStrings(String s, String goal) { @@ -98,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +120,6 @@ public: }; ``` -### **Go** - ```go func buddyStrings(s string, goal string) bool { m, n := len(s), len(goal) @@ -155,8 +149,6 @@ func buddyStrings(s string, goal string) bool { } ``` -### **TypeScript** - ```ts function buddyStrings(s: string, goal: string): boolean { const m = s.length; @@ -183,10 +175,6 @@ function buddyStrings(s: string, goal: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0860.Lemonade Change/README.md b/solution/0800-0899/0860.Lemonade Change/README.md index 52c8d8f7c609b..f48d9c2ce4bb1 100644 --- a/solution/0800-0899/0860.Lemonade Change/README.md +++ b/solution/0800-0899/0860.Lemonade Change/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:贪心 + 模拟** +### 方法一:贪心 + 模拟 我们从前往后遍历账单数组 $bills$,对于当前遍历到的账单: @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def lemonadeChange(self, bills: List[int]) -> bool: @@ -93,10 +87,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean lemonadeChange(int[] bills) { @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func lemonadeChange(bills []int) bool { five, ten := 0, 0 @@ -183,8 +169,6 @@ func lemonadeChange(bills []int) bool { } ``` -### **TypeScript** - ```ts function lemonadeChange(bills: number[]): boolean { let five = 0; @@ -215,8 +199,6 @@ function lemonadeChange(bills: number[]): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn lemonade_change(bills: Vec) -> bool { @@ -249,10 +231,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0860.Lemonade Change/README_EN.md b/solution/0800-0899/0860.Lemonade Change/README_EN.md index 23eef92cc6266..c134066f49bba 100644 --- a/solution/0800-0899/0860.Lemonade Change/README_EN.md +++ b/solution/0800-0899/0860.Lemonade Change/README_EN.md @@ -45,9 +45,9 @@ Since not every customer received the correct change, the answer is false. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean lemonadeChange(int[] bills) { @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +127,6 @@ public: }; ``` -### **Go** - ```go func lemonadeChange(bills []int) bool { five, ten := 0, 0 @@ -158,8 +152,6 @@ func lemonadeChange(bills []int) bool { } ``` -### **TypeScript** - ```ts function lemonadeChange(bills: number[]): boolean { let five = 0; @@ -190,8 +182,6 @@ function lemonadeChange(bills: number[]): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn lemonade_change(bills: Vec) -> bool { @@ -224,10 +214,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0861.Score After Flipping Matrix/README.md b/solution/0800-0899/0861.Score After Flipping Matrix/README.md index b10c0c7c20cb8..d8911dba48ca4 100644 --- a/solution/0800-0899/0861.Score After Flipping Matrix/README.md +++ b/solution/0800-0899/0861.Score After Flipping Matrix/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们注意到,对于任意一个翻转方案,翻转的次序不影响最后的结果。因此我们可以先考虑所有的行翻转,再考虑所有的列翻转。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def matrixScore(self, grid: List[List[int]]) -> int: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int matrixScore(int[][] grid) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func matrixScore(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -162,8 +148,6 @@ func matrixScore(grid [][]int) int { } ``` -### **TypeScript** - ```ts function matrixScore(grid: number[][]): number { const m = grid.length; @@ -187,8 +171,6 @@ function matrixScore(grid: number[][]): number { } ``` -### **C#** - ```cs public class Solution { public int MatrixScore(int[][] grid) { @@ -215,10 +197,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0861.Score After Flipping Matrix/README_EN.md b/solution/0800-0899/0861.Score After Flipping Matrix/README_EN.md index a581b0b7c30a2..90d6cedea1b81 100644 --- a/solution/0800-0899/0861.Score After Flipping Matrix/README_EN.md +++ b/solution/0800-0899/0861.Score After Flipping Matrix/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int matrixScore(int[][] grid) { @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func matrixScore(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -139,8 +133,6 @@ func matrixScore(grid [][]int) int { } ``` -### **TypeScript** - ```ts function matrixScore(grid: number[][]): number { const m = grid.length; @@ -164,8 +156,6 @@ function matrixScore(grid: number[][]): number { } ``` -### **C#** - ```cs public class Solution { public int MatrixScore(int[][] grid) { @@ -192,10 +182,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0862.Shortest Subarray with Sum at Least K/README.md b/solution/0800-0899/0862.Shortest Subarray with Sum at Least K/README.md index 2130f5ed05134..341f2af0ff656 100644 --- a/solution/0800-0899/0862.Shortest Subarray with Sum at Least K/README.md +++ b/solution/0800-0899/0862.Shortest Subarray with Sum at Least K/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:前缀和 + 单调队列** +### 方法一:前缀和 + 单调队列 题目要求找到一个最短的子数组,使得子数组的和大于等于 $k$。不难想到,可以使用前缀和快速计算子数组的和。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def shortestSubarray(self, nums: List[int], k: int) -> int: @@ -91,10 +85,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - - - ```java class Solution { public int shortestSubarray(int[] nums, int k) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func shortestSubarray(nums []int, k int) int { n := len(nums) @@ -171,10 +157,6 @@ func shortestSubarray(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0862.Shortest Subarray with Sum at Least K/README_EN.md b/solution/0800-0899/0862.Shortest Subarray with Sum at Least K/README_EN.md index f386d03fcc8f6..5177d0e72af75 100644 --- a/solution/0800-0899/0862.Shortest Subarray with Sum at Least K/README_EN.md +++ b/solution/0800-0899/0862.Shortest Subarray with Sum at Least K/README_EN.md @@ -30,9 +30,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -49,8 +49,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - ```java class Solution { public int shortestSubarray(int[] nums, int k) { @@ -75,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +95,6 @@ public: }; ``` -### **Go** - ```go func shortestSubarray(nums []int, k int) int { n := len(nums) @@ -127,10 +121,6 @@ func shortestSubarray(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0863.All Nodes Distance K in Binary Tree/README.md b/solution/0800-0899/0863.All Nodes Distance K in Binary Tree/README.md index 50be42e1ae4a1..da76c24a5902f 100644 --- a/solution/0800-0899/0863.All Nodes Distance K in Binary Tree/README.md +++ b/solution/0800-0899/0863.All Nodes Distance K in Binary Tree/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:DFS + 哈希表** +### 方法一:DFS + 哈希表 我们先用 DFS 遍历整棵树,记录每个结点的父结点,然后从目标结点开始,向上、向下分别搜索距离为 $k$ 的结点,添加到答案数组中。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -101,45 +95,6 @@ class Solution: return ans ``` -```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 distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]: - def dfs1(root, fa): - if root is None: - return - p[root] = fa - dfs1(root.left, root) - dfs1(root.right, root) - - def dfs2(root, fa, k): - if root is None: - return - if k == 0: - ans.append(root.val) - return - for nxt in (root.left, root.right, p[root]): - if nxt != fa: - dfs2(nxt, root, k - 1) - - p = {} - dfs1(root, None) - ans = [] - dfs2(target, None, k) - return ans -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -189,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -234,8 +187,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -278,10 +229,47 @@ func distanceK(root *TreeNode, target *TreeNode, k int) []int { } ``` -### **...** + -``` +### 方法二 + + + +```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 distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]: + def dfs1(root, fa): + if root is None: + return + p[root] = fa + dfs1(root.left, root) + dfs1(root.right, root) + + def dfs2(root, fa, k): + if root is None: + return + if k == 0: + ans.append(root.val) + return + for nxt in (root.left, root.right, p[root]): + if nxt != fa: + dfs2(nxt, root, k - 1) + p = {} + dfs1(root, None) + ans = [] + dfs2(target, None, k) + return ans ``` + + diff --git a/solution/0800-0899/0863.All Nodes Distance K in Binary Tree/README_EN.md b/solution/0800-0899/0863.All Nodes Distance K in Binary Tree/README_EN.md index a03c953ca5a14..15cc494c3bccd 100644 --- a/solution/0800-0899/0863.All Nodes Distance K in Binary Tree/README_EN.md +++ b/solution/0800-0899/0863.All Nodes Distance K in Binary Tree/README_EN.md @@ -37,9 +37,9 @@ Explanation: The nodes that are a distance 2 from the target node (with value 5) ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -80,43 +80,6 @@ class Solution: return ans ``` -```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 distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]: - def dfs1(root, fa): - if root is None: - return - p[root] = fa - dfs1(root.left, root) - dfs1(root.right, root) - - def dfs2(root, fa, k): - if root is None: - return - if k == 0: - ans.append(root.val) - return - for nxt in (root.left, root.right, p[root]): - if nxt != fa: - dfs2(nxt, root, k - 1) - - p = {} - dfs1(root, None) - ans = [] - dfs2(target, None, k) - return ans -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -166,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -211,8 +172,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -255,10 +214,47 @@ func distanceK(root *TreeNode, target *TreeNode, k int) []int { } ``` -### **...** + -``` +### 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 distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]: + def dfs1(root, fa): + if root is None: + return + p[root] = fa + dfs1(root.left, root) + dfs1(root.right, root) + + def dfs2(root, fa, k): + if root is None: + return + if k == 0: + ans.append(root.val) + return + for nxt in (root.left, root.right, p[root]): + if nxt != fa: + dfs2(nxt, root, k - 1) + + p = {} + dfs1(root, None) + ans = [] + dfs2(target, None, k) + return ans ``` + + diff --git a/solution/0800-0899/0864.Shortest Path to Get All Keys/README.md b/solution/0800-0899/0864.Shortest Path to Get All Keys/README.md index 347c8b244c67a..83b5abb954b0b 100644 --- a/solution/0800-0899/0864.Shortest Path to Get All Keys/README.md +++ b/solution/0800-0899/0864.Shortest Path to Get All Keys/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:状态压缩 + BFS** +### 方法一:状态压缩 + BFS 根据题意,我们需要从起点出发,往上下左右四个方向走,获取所有钥匙,最后返回获取所有钥匙所需要的移动的最少次数。若无法获取所有钥匙,返回 $-1$。 @@ -101,10 +99,6 @@ f d c b -### **Python3** - - - ```python class Solution: def shortestPathAllKeys(self, grid: List[str]) -> int: @@ -151,10 +145,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { private int[] dirs = {-1, 0, 1, 0, -1}; @@ -222,8 +212,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -280,8 +268,6 @@ public: }; ``` -### **Go** - ```go func shortestPathAllKeys(grid []string) int { m, n := len(grid), len(grid[0]) @@ -341,10 +327,6 @@ func shortestPathAllKeys(grid []string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0864.Shortest Path to Get All Keys/README_EN.md b/solution/0800-0899/0864.Shortest Path to Get All Keys/README_EN.md index 651d580f9a07b..58c600fae4692 100644 --- a/solution/0800-0899/0864.Shortest Path to Get All Keys/README_EN.md +++ b/solution/0800-0899/0864.Shortest Path to Get All Keys/README_EN.md @@ -61,15 +61,17 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: def shortestPathAllKeys(self, grid: List[str]) -> int: m, n = len(grid), len(grid[0]) + # 找起点 (si, sj) si, sj = next((i, j) for i in range(m) for j in range(n) if grid[i][j] == '@') + # 统计钥匙数量 k = sum(v.islower() for row in grid for v in row) dirs = (-1, 0, 1, 0, -1) q = deque([(si, sj, 0)]) @@ -78,30 +80,37 @@ class Solution: while q: for _ in range(len(q)): i, j, state = q.popleft() + # 找到所有钥匙,返回当前步数 if state == (1 << k) - 1: return ans + + # 往四个方向搜索 for a, b in pairwise(dirs): x, y = i + a, j + b nxt = state + # 在边界范围内 if 0 <= x < m and 0 <= y < n: c = grid[x][y] + # 是墙,或者是锁,但此时没有对应的钥匙,无法通过 if ( c == '#' or c.isupper() and (state & (1 << (ord(c) - ord('A')))) == 0 ): continue + # 是钥匙 if c.islower(): + # 更新状态 nxt |= 1 << (ord(c) - ord('a')) + # 此状态未访问过,入队 if (x, y, nxt) not in vis: vis.add((x, y, nxt)) q.append((x, y, nxt)) + # 步数加一 ans += 1 return -1 ``` -### **Java** - ```java class Solution { private int[] dirs = {-1, 0, 1, 0, -1}; @@ -114,8 +123,10 @@ class Solution { for (int j = 0; j < n; ++j) { char c = grid[i].charAt(j); if (Character.isLowerCase(c)) { + // 累加钥匙数量 ++k; } else if (c == '@') { + // 起点 si = i; sj = j; } @@ -130,21 +141,28 @@ class Solution { for (int t = q.size(); t > 0; --t) { var p = q.poll(); int i = p[0], j = p[1], state = p[2]; + // 找到所有钥匙,返回当前步数 if (state == (1 << k) - 1) { return ans; } + // 往四个方向搜索 for (int h = 0; h < 4; ++h) { int x = i + dirs[h], y = j + dirs[h + 1]; + // 在边界范围内 if (x >= 0 && x < m && y >= 0 && y < n) { char c = grid[x].charAt(y); + // 是墙,或者是锁,但此时没有对应的钥匙,无法通过 if (c == '#' || (Character.isUpperCase(c) && ((state >> (c - 'A')) & 1) == 0)) { continue; } int nxt = state; + // 是钥匙 if (Character.isLowerCase(c)) { + // 更新状态 nxt |= 1 << (c - 'a'); } + // 此状态未访问过,入队 if (!vis[x][y][nxt]) { vis[x][y][nxt] = true; q.offer(new int[] {x, y, nxt}); @@ -152,6 +170,7 @@ class Solution { } } } + // 步数加一 ++ans; } return -1; @@ -159,8 +178,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -173,8 +190,9 @@ public: for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { char c = grid[i][j]; - if (islower(c)) - ++k; + // 累加钥匙数量 + if (islower(c)) ++k; + // 起点 else if (c == '@') si = i, sj = j; } @@ -187,14 +205,20 @@ public: for (int t = q.size(); t; --t) { auto [i, j, state] = q.front(); q.pop(); + // 找到所有钥匙,返回当前步数 if (state == (1 << k) - 1) return ans; + // 往四个方向搜索 for (int h = 0; h < 4; ++h) { int x = i + dirs[h], y = j + dirs[h + 1]; + // 在边界范围内 if (x >= 0 && x < m && y >= 0 && y < n) { char c = grid[x][y]; + // 是墙,或者是锁,但此时没有对应的钥匙,无法通过 if (c == '#' || (isupper(c) && (state >> (c - 'A') & 1) == 0)) continue; int nxt = state; + // 是钥匙,更新状态 if (islower(c)) nxt |= 1 << (c - 'a'); + // 此状态未访问过,入队 if (!vis[x][y][nxt]) { vis[x][y][nxt] = true; q.push({x, y, nxt}); @@ -202,6 +226,7 @@ public: } } } + // 步数加一 ++ans; } return -1; @@ -209,8 +234,6 @@ public: }; ``` -### **Go** - ```go func shortestPathAllKeys(grid []string) int { m, n := len(grid), len(grid[0]) @@ -218,8 +241,10 @@ func shortestPathAllKeys(grid []string) int { for i, row := range grid { for j, c := range row { if c >= 'a' && c <= 'z' { + // 累加钥匙数量 k++ } else if c == '@' { + // 起点 si, sj = i, j } } @@ -234,20 +259,26 @@ func shortestPathAllKeys(grid []string) int { p := q[0] q = q[1:] i, j, state := p.i, p.j, p.state + // 找到所有钥匙,返回当前步数 if state == 1<= 0 && x < m && y >= 0 && y < n { c := grid[x][y] + // 是墙,或者是锁,但此时没有对应的钥匙,无法通过 if c == '#' || (c >= 'A' && c <= 'Z' && (state>>(c-'A')&1 == 0)) { continue } nxt := state + // 是钥匙,更新状态 if c >= 'a' && c <= 'z' { nxt |= 1 << (c - 'a') } + // 此状态未访问过,入队 if !vis[tuple{x, y, nxt}] { vis[tuple{x, y, nxt}] = true q = append(q, tuple{x, y, nxt}) @@ -255,16 +286,13 @@ func shortestPathAllKeys(grid []string) int { } } } + // 步数加一 ans++ } return -1 } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0865.Smallest Subtree with all the Deepest Nodes/README.md b/solution/0800-0899/0865.Smallest Subtree with all the Deepest Nodes/README.md index 2d23902e15dfe..3f3c7de628ef6 100644 --- a/solution/0800-0899/0865.Smallest Subtree with all the Deepest Nodes/README.md +++ b/solution/0800-0899/0865.Smallest Subtree with all the Deepest Nodes/README.md @@ -59,14 +59,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -90,10 +86,6 @@ class Solution: return dfs(root)[0] ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -133,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -166,8 +156,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -202,10 +190,6 @@ func subtreeWithAllDeepest(root *TreeNode) *TreeNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0865.Smallest Subtree with all the Deepest Nodes/README_EN.md b/solution/0800-0899/0865.Smallest Subtree with all the Deepest Nodes/README_EN.md index 8c8685b48e0f2..f2acee295226d 100644 --- a/solution/0800-0899/0865.Smallest Subtree with all the Deepest Nodes/README_EN.md +++ b/solution/0800-0899/0865.Smallest Subtree with all the Deepest Nodes/README_EN.md @@ -53,9 +53,9 @@ Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -80,8 +80,6 @@ class Solution: return dfs(root)[0] ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -121,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -154,8 +150,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -190,10 +184,6 @@ func subtreeWithAllDeepest(root *TreeNode) *TreeNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0866.Prime Palindrome/README.md b/solution/0800-0899/0866.Prime Palindrome/README.md index 694cbb3ac8b14..e3a03123ddfcd 100644 --- a/solution/0800-0899/0866.Prime Palindrome/README.md +++ b/solution/0800-0899/0866.Prime Palindrome/README.md @@ -50,14 +50,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def primePalindrome(self, n: int) -> int: @@ -86,10 +82,6 @@ class Solution: n += 1 ``` -### **Java** - - - ```java class Solution { public int primePalindrome(int n) { @@ -127,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +149,6 @@ public: }; ``` -### **Go** - ```go func primePalindrome(n int) int { isPrime := func(x int) bool { @@ -195,10 +183,6 @@ func primePalindrome(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0866.Prime Palindrome/README_EN.md b/solution/0800-0899/0866.Prime Palindrome/README_EN.md index ea3e1e6e01499..8bb7ac58c15ea 100644 --- a/solution/0800-0899/0866.Prime Palindrome/README_EN.md +++ b/solution/0800-0899/0866.Prime Palindrome/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: n += 1 ``` -### **Java** - ```java class Solution { public int primePalindrome(int n) { @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +139,6 @@ public: }; ``` -### **Go** - ```go func primePalindrome(n int) int { isPrime := func(x int) bool { @@ -179,10 +173,6 @@ func primePalindrome(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0867.Transpose Matrix/README.md b/solution/0800-0899/0867.Transpose Matrix/README.md index 0c27eb4713ac5..db49acaeaf8a6 100644 --- a/solution/0800-0899/0867.Transpose Matrix/README.md +++ b/solution/0800-0899/0867.Transpose Matrix/README.md @@ -42,24 +42,16 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def transpose(self, matrix: List[List[int]]) -> List[List[int]]: return list(zip(*matrix)) ``` -### **Java** - - - ```java class Solution { public int[][] transpose(int[][] matrix) { @@ -75,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +81,6 @@ public: }; ``` -### **Go** - ```go func transpose(matrix [][]int) [][]int { m, n := len(matrix), len(matrix[0]) @@ -107,8 +95,6 @@ func transpose(matrix [][]int) [][]int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} matrix @@ -127,10 +113,6 @@ var transpose = function (matrix) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0867.Transpose Matrix/README_EN.md b/solution/0800-0899/0867.Transpose Matrix/README_EN.md index 4aec713bf9901..85691c4ecfff8 100644 --- a/solution/0800-0899/0867.Transpose Matrix/README_EN.md +++ b/solution/0800-0899/0867.Transpose Matrix/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -48,8 +48,6 @@ class Solution: return list(zip(*matrix)) ``` -### **Java** - ```java class Solution { public int[][] transpose(int[][] matrix) { @@ -65,8 +63,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -81,8 +77,6 @@ public: }; ``` -### **Go** - ```go func transpose(matrix [][]int) [][]int { m, n := len(matrix), len(matrix[0]) @@ -97,8 +91,6 @@ func transpose(matrix [][]int) [][]int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} matrix @@ -117,10 +109,6 @@ var transpose = function (matrix) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0868.Binary Gap/README.md b/solution/0800-0899/0868.Binary Gap/README.md index 31b1104fb5900..e5fc51de3948e 100644 --- a/solution/0800-0899/0868.Binary Gap/README.md +++ b/solution/0800-0899/0868.Binary Gap/README.md @@ -54,14 +54,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def binaryGap(self, n: int) -> int: @@ -75,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int binaryGap(int n) { @@ -96,7 +88,36 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + int binaryGap(int n) { + int ans = 0; + for (int i = 0, j = -1; n; ++i, n >>= 1) { + if (n & 1) { + if (j != -1) ans = max(ans, i - j); + j = i; + } + } + return ans; + } +}; +``` + +```go +func binaryGap(n int) int { + ans := 0 + for i, j := 0, -1; n != 0; i, n = i+1, n>>1 { + if (n & 1) == 1 { + if j != -1 && ans < i-j { + ans = i - j + } + j = i + } + } + return ans +} +``` ```ts function binaryGap(n: number): number { @@ -115,8 +136,6 @@ function binaryGap(n: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn binary_gap(mut n: i32) -> i32 { @@ -138,45 +157,6 @@ impl Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int binaryGap(int n) { - int ans = 0; - for (int i = 0, j = -1; n; ++i, n >>= 1) { - if (n & 1) { - if (j != -1) ans = max(ans, i - j); - j = i; - } - } - return ans; - } -}; -``` - -### **Go** - -```go -func binaryGap(n int) int { - ans := 0 - for i, j := 0, -1; n != 0; i, n = i+1, n>>1 { - if (n & 1) == 1 { - if j != -1 && ans < i-j { - ans = i - j - } - j = i - } - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0868.Binary Gap/README_EN.md b/solution/0800-0899/0868.Binary Gap/README_EN.md index eacd274fe0cea..880d7e706069f 100644 --- a/solution/0800-0899/0868.Binary Gap/README_EN.md +++ b/solution/0800-0899/0868.Binary Gap/README_EN.md @@ -47,9 +47,9 @@ There are not any adjacent pairs of 1's in the binary representation of 8, s ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int binaryGap(int n) { @@ -83,7 +81,36 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + int binaryGap(int n) { + int ans = 0; + for (int i = 0, j = -1; n; ++i, n >>= 1) { + if (n & 1) { + if (j != -1) ans = max(ans, i - j); + j = i; + } + } + return ans; + } +}; +``` + +```go +func binaryGap(n int) int { + ans := 0 + for i, j := 0, -1; n != 0; i, n = i+1, n>>1 { + if (n & 1) == 1 { + if j != -1 && ans < i-j { + ans = i - j + } + j = i + } + } + return ans +} +``` ```ts function binaryGap(n: number): number { @@ -102,8 +129,6 @@ function binaryGap(n: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn binary_gap(mut n: i32) -> i32 { @@ -125,45 +150,6 @@ impl Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int binaryGap(int n) { - int ans = 0; - for (int i = 0, j = -1; n; ++i, n >>= 1) { - if (n & 1) { - if (j != -1) ans = max(ans, i - j); - j = i; - } - } - return ans; - } -}; -``` - -### **Go** - -```go -func binaryGap(n int) int { - ans := 0 - for i, j := 0, -1; n != 0; i, n = i+1, n>>1 { - if (n & 1) == 1 { - if j != -1 && ans < i-j { - ans = i - j - } - j = i - } - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0869.Reordered Power of 2/README.md b/solution/0800-0899/0869.Reordered Power of 2/README.md index aa91d4b132305..89b80578542d5 100644 --- a/solution/0800-0899/0869.Reordered Power of 2/README.md +++ b/solution/0800-0899/0869.Reordered Power of 2/README.md @@ -39,14 +39,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def reorderedPowerOf2(self, n: int) -> bool: @@ -65,10 +61,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean reorderedPowerOf2(int n) { @@ -91,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +102,6 @@ public: }; ``` -### **Go** - ```go func reorderedPowerOf2(n int) bool { convert := func(n int) []byte { @@ -133,10 +121,6 @@ func reorderedPowerOf2(n int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0869.Reordered Power of 2/README_EN.md b/solution/0800-0899/0869.Reordered Power of 2/README_EN.md index 4b72bc9a75090..e5163ffade8ab 100644 --- a/solution/0800-0899/0869.Reordered Power of 2/README_EN.md +++ b/solution/0800-0899/0869.Reordered Power of 2/README_EN.md @@ -32,9 +32,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean reorderedPowerOf2(int n) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +95,6 @@ public: }; ``` -### **Go** - ```go func reorderedPowerOf2(n int) bool { convert := func(n int) []byte { @@ -120,10 +114,6 @@ func reorderedPowerOf2(n int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0870.Advantage Shuffle/README.md b/solution/0800-0899/0870.Advantage Shuffle/README.md index 05e8325ab8f7f..3579acd0631c0 100644 --- a/solution/0800-0899/0870.Advantage Shuffle/README.md +++ b/solution/0800-0899/0870.Advantage Shuffle/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 类似田忌赛马。将 $nums1$, $nums2$ 按照升序排列。然后遍历 $nums1$ 中的每个元素 $v$,若在 $nums2[i..j]$ 中找不到比 $v$ 小的,则将 $v$ 与当前 $nums2[i..j]$ 中的最大元素匹配。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python class Solution: def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] advantageCount(int[] nums1, int[] nums2) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func advantageCount(nums1 []int, nums2 []int) []int { n := len(nums1) @@ -150,8 +136,6 @@ func advantageCount(nums1 []int, nums2 []int) []int { } ``` -### **TypeScript** - ```ts function advantageCount(nums1: number[], nums2: number[]): number[] { const n = nums1.length; @@ -175,8 +159,6 @@ function advantageCount(nums1: number[], nums2: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn advantage_count(mut nums1: Vec, nums2: Vec) -> Vec { @@ -201,10 +183,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0870.Advantage Shuffle/README_EN.md b/solution/0800-0899/0870.Advantage Shuffle/README_EN.md index 5a6ae2d964ad2..e1cd578d3f215 100644 --- a/solution/0800-0899/0870.Advantage Shuffle/README_EN.md +++ b/solution/0800-0899/0870.Advantage Shuffle/README_EN.md @@ -27,9 +27,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -49,8 +49,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] advantageCount(int[] nums1, int[] nums2) { @@ -75,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +95,6 @@ public: }; ``` -### **Go** - ```go func advantageCount(nums1 []int, nums2 []int) []int { n := len(nums1) @@ -127,8 +121,6 @@ func advantageCount(nums1 []int, nums2 []int) []int { } ``` -### **TypeScript** - ```ts function advantageCount(nums1: number[], nums2: number[]): number[] { const n = nums1.length; @@ -152,8 +144,6 @@ function advantageCount(nums1: number[], nums2: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn advantage_count(mut nums1: Vec, nums2: Vec) -> Vec { @@ -178,10 +168,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0871.Minimum Number of Refueling Stops/README.md b/solution/0800-0899/0871.Minimum Number of Refueling Stops/README.md index a2b3b6bc80196..ce7b975a2d483 100644 --- a/solution/0800-0899/0871.Minimum Number of Refueling Stops/README.md +++ b/solution/0800-0899/0871.Minimum Number of Refueling Stops/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列(大根堆)** +### 方法一:贪心 + 优先队列(大根堆) 利用优先队列记录所有已经到达过的加油站的加油量,每次当油量不足时,从队列中取出最大加油量,并累计加油次数 ans。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def minRefuelStops( @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minRefuelStops(int target, int startFuel, int[][] stations) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go func minRefuelStops(target int, startFuel int, stations [][]int) int { stations = append(stations, []int{target, 0}) @@ -189,10 +175,6 @@ func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0871.Minimum Number of Refueling Stops/README_EN.md b/solution/0800-0899/0871.Minimum Number of Refueling Stops/README_EN.md index efd3741cd8a7c..616ee2938f13e 100644 --- a/solution/0800-0899/0871.Minimum Number of Refueling Stops/README_EN.md +++ b/solution/0800-0899/0871.Minimum Number of Refueling Stops/README_EN.md @@ -55,9 +55,9 @@ We made 2 refueling stops along the way, so we return 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minRefuelStops(int target, int startFuel, int[][] stations) { @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +130,6 @@ public: }; ``` -### **Go** - ```go func minRefuelStops(target int, startFuel int, stations [][]int) int { stations = append(stations, []int{target, 0}) @@ -172,10 +166,6 @@ func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0872.Leaf-Similar Trees/README.md b/solution/0800-0899/0872.Leaf-Similar Trees/README.md index f96dfbe665190..9ff4462c4ee9e 100644 --- a/solution/0800-0899/0872.Leaf-Similar Trees/README.md +++ b/solution/0800-0899/0872.Leaf-Similar Trees/README.md @@ -47,18 +47,12 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 后序遍历。 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -77,10 +71,6 @@ class Solution: return dfs(root1) == dfs(root2) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -149,7 +137,31 @@ public: }; ``` -### **Rust** +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool { + var dfs func(*TreeNode) []int + dfs = func(root *TreeNode) []int { + if root == nil { + return []int{} + } + ans := dfs(root.Left) + ans = append(ans, dfs(root.Right)...) + if len(ans) == 0 { + ans = append(ans, root.Val) + } + return ans + } + return reflect.DeepEqual(dfs(root1), dfs(root2)) +} +``` ```rust // Definition for a binary tree node. @@ -210,38 +222,6 @@ impl Solution { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool { - var dfs func(*TreeNode) []int - dfs = func(root *TreeNode) []int { - if root == nil { - return []int{} - } - ans := dfs(root.Left) - ans = append(ans, dfs(root.Right)...) - if len(ans) == 0 { - ans = append(ans, root.Val) - } - return ans - } - return reflect.DeepEqual(dfs(root1), dfs(root2)) -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0872.Leaf-Similar Trees/README_EN.md b/solution/0800-0899/0872.Leaf-Similar Trees/README_EN.md index 240b5b15f2872..008a42c84bc7f 100644 --- a/solution/0800-0899/0872.Leaf-Similar Trees/README_EN.md +++ b/solution/0800-0899/0872.Leaf-Similar Trees/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -61,8 +61,6 @@ class Solution: return dfs(root1) == dfs(root2) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -131,7 +127,31 @@ public: }; ``` -### **Rust** +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool { + var dfs func(*TreeNode) []int + dfs = func(root *TreeNode) []int { + if root == nil { + return []int{} + } + ans := dfs(root.Left) + ans = append(ans, dfs(root.Right)...) + if len(ans) == 0 { + ans = append(ans, root.Val) + } + return ans + } + return reflect.DeepEqual(dfs(root1), dfs(root2)) +} +``` ```rust // Definition for a binary tree node. @@ -192,38 +212,6 @@ impl Solution { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool { - var dfs func(*TreeNode) []int - dfs = func(root *TreeNode) []int { - if root == nil { - return []int{} - } - ans := dfs(root.Left) - ans = append(ans, dfs(root.Right)...) - if len(ans) == 0 { - ans = append(ans, root.Val) - } - return ans - } - return reflect.DeepEqual(dfs(root1), dfs(root2)) -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README.md b/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README.md index 0aa208e03618e..dcc58e8cbb8a9 100644 --- a/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README.md +++ b/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README.md @@ -51,19 +51,13 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 - 状态表示:`dp[j][i]` 表示斐波那契式最后两项为 `arr[j]`, `arr[i]` 时的最大子序列长度。 - 状态计算:`dp[j][i] = dp[k][j] + 1`(当且仅当 `k < j < i`,并且 `arr[k] + arr[j] == arr[i]`), `ans = max(ans, dp[j][i])`。 -### **Python3** - - - ```python class Solution: def lenLongestFibSubseq(self, arr: List[int]) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int lenLongestFibSubseq(int[] arr) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func lenLongestFibSubseq(arr []int) int { n := len(arr) @@ -181,8 +167,6 @@ func lenLongestFibSubseq(arr []int) int { } ``` -### **JavaScript** - ```js /** * @param {number[]} arr @@ -215,10 +199,6 @@ var lenLongestFibSubseq = function (arr) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README_EN.md b/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README_EN.md index 1cb60ded42db4..322eba2b7ffe8 100644 --- a/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README_EN.md +++ b/solution/0800-0899/0873.Length of Longest Fibonacci Subsequence/README_EN.md @@ -40,12 +40,10 @@ ## Solutions -Dynamic programming. +### Solution 1 -### **Python3** - ```python class Solution: def lenLongestFibSubseq(self, arr: List[int]) -> int: @@ -65,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int lenLongestFibSubseq(int[] arr) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +124,6 @@ public: }; ``` -### **Go** - ```go func lenLongestFibSubseq(arr []int) int { n := len(arr) @@ -161,8 +153,6 @@ func lenLongestFibSubseq(arr []int) int { } ``` -### **JavaScript** - ```js /** * @param {number[]} arr @@ -195,10 +185,6 @@ var lenLongestFibSubseq = function (arr) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0874.Walking Robot Simulation/README.md b/solution/0800-0899/0874.Walking Robot Simulation/README.md index c2c8237a2bfb8..05350c4455386 100644 --- a/solution/0800-0899/0874.Walking Robot Simulation/README.md +++ b/solution/0800-0899/0874.Walking Robot Simulation/README.md @@ -93,9 +93,7 @@ ## 解法 - - -**方法一:哈希表 + 模拟** +### 方法一:哈希表 + 模拟 我们定义一个长度为 $5$ 的方向数组 $dirs=[0, 1, 0, -1, 0]$,数组中的相邻两个元素表示一个方向。即 $(dirs[0], dirs[1])$ 表示向北,而 $(dirs[1], dirs[2])$ 表示向东,以此类推。 @@ -115,10 +113,6 @@ -### **Python3** - - - ```python class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: @@ -141,10 +135,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int robotSim(int[] commands, int[][] obstacles) { @@ -181,8 +171,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -219,8 +207,6 @@ public: }; ``` -### **Go** - ```go func robotSim(commands []int, obstacles [][]int) (ans int) { dirs := [5]int{0, 1, 0, -1, 0} @@ -247,8 +233,6 @@ func robotSim(commands []int, obstacles [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function robotSim(commands: number[], obstacles: number[][]): number { const dirs = [0, 1, 0, -1, 0]; @@ -278,10 +262,6 @@ function robotSim(commands: number[], obstacles: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0874.Walking Robot Simulation/README_EN.md b/solution/0800-0899/0874.Walking Robot Simulation/README_EN.md index 82a1354a4da58..c944b623db5e0 100644 --- a/solution/0800-0899/0874.Walking Robot Simulation/README_EN.md +++ b/solution/0800-0899/0874.Walking Robot Simulation/README_EN.md @@ -79,7 +79,7 @@ The furthest point the robot ever gets from the origin is (0, 6), which squared ## Solutions -**Solution 1: Hash table + simulation** +### Solution 1: Hash table + simulation We define a direction array $dirs=[0, 1, 0, -1, 0]$ of length $5$, where adjacent elements in the array represent a direction. That is, $(dirs[0], dirs[1])$ represents north, and $(dirs[1], dirs[2])$ represents east, and so on. @@ -99,8 +99,6 @@ Time complexity is $O(C \times n + m)$, space complexity is $O(m)$. Where $C$ re -### **Python3** - ```python class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: @@ -123,8 +121,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int robotSim(int[] commands, int[][] obstacles) { @@ -161,8 +157,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -199,8 +193,6 @@ public: }; ``` -### **Go** - ```go func robotSim(commands []int, obstacles [][]int) (ans int) { dirs := [5]int{0, 1, 0, -1, 0} @@ -227,8 +219,6 @@ func robotSim(commands []int, obstacles [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function robotSim(commands: number[], obstacles: number[][]): number { const dirs = [0, 1, 0, -1, 0]; @@ -258,10 +248,6 @@ function robotSim(commands: number[], obstacles: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0875.Koko Eating Bananas/README.md b/solution/0800-0899/0875.Koko Eating Bananas/README.md index b6e9bf371f312..53d51f7eeadea 100644 --- a/solution/0800-0899/0875.Koko Eating Bananas/README.md +++ b/solution/0800-0899/0875.Koko Eating Bananas/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 二分枚举速度值,找到能在 $h$ 小时内吃完所有香蕉的最小速度值。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: @@ -80,10 +74,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int minEatingSpeed(int[] piles, int h) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func minEatingSpeed(piles []int, h int) int { return sort.Search(1e9, func(i int) bool { @@ -143,8 +129,6 @@ func minEatingSpeed(piles []int, h int) int { } ``` -### **TypeScript** - ```ts function minEatingSpeed(piles: number[], h: number): number { let left = 1; @@ -165,8 +149,6 @@ function minEatingSpeed(piles: number[], h: number): number { } ``` -### **C#** - ```cs public class Solution { public int MinEatingSpeed(int[] piles, int h) { @@ -193,10 +175,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0875.Koko Eating Bananas/README_EN.md b/solution/0800-0899/0875.Koko Eating Bananas/README_EN.md index 09b9bf5724b75..3c7927bccb523 100644 --- a/solution/0800-0899/0875.Koko Eating Bananas/README_EN.md +++ b/solution/0800-0899/0875.Koko Eating Bananas/README_EN.md @@ -45,12 +45,10 @@ ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: @@ -65,8 +63,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { public int minEatingSpeed(int[] piles, int h) { @@ -88,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +103,6 @@ public: }; ``` -### **Go** - ```go func minEatingSpeed(piles []int, h int) int { return sort.Search(1e9, func(i int) bool { @@ -126,8 +118,6 @@ func minEatingSpeed(piles []int, h int) int { } ``` -### **TypeScript** - ```ts function minEatingSpeed(piles: number[], h: number): number { let left = 1; @@ -148,8 +138,6 @@ function minEatingSpeed(piles: number[], h: number): number { } ``` -### **C#** - ```cs public class Solution { public int MinEatingSpeed(int[] piles, int h) { @@ -176,10 +164,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0876.Middle of the Linked List/README.md b/solution/0800-0899/0876.Middle of the Linked List/README.md index 2bbf38c2e85b5..e578b2a85c4b4 100644 --- a/solution/0800-0899/0876.Middle of the Linked List/README.md +++ b/solution/0800-0899/0876.Middle of the Linked List/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:快慢指针** +### 方法一:快慢指针 定义快慢指针 `fast` 和 `slow`,初始时均指向链表的头结点。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -69,10 +63,6 @@ class Solution: return slow ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -141,8 +127,6 @@ func middleNode(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -167,8 +151,6 @@ function middleNode(head: ListNode | null): ListNode | null { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -199,30 +181,6 @@ impl Solution { } ``` -### **C** - -```c -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * struct ListNode *next; - * }; - */ - -struct ListNode* middleNode(struct ListNode* head) { - struct ListNode* fast = head; - struct ListNode* slow = head; - while (fast && fast->next) { - fast = fast->next->next; - slow = slow->next; - } - return slow; -} -``` - -### **PHP** - ```php /** * Definition for a singly-linked list. @@ -257,10 +215,26 @@ class Solution { } ``` -### **...** - -``` +```c +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ +struct ListNode* middleNode(struct ListNode* head) { + struct ListNode* fast = head; + struct ListNode* slow = head; + while (fast && fast->next) { + fast = fast->next->next; + slow = slow->next; + } + return slow; +} ``` + + diff --git a/solution/0800-0899/0876.Middle of the Linked List/README_EN.md b/solution/0800-0899/0876.Middle of the Linked List/README_EN.md index 59261ec31a0f7..0f4fd1cc19754 100644 --- a/solution/0800-0899/0876.Middle of the Linked List/README_EN.md +++ b/solution/0800-0899/0876.Middle of the Linked List/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -53,8 +53,6 @@ class Solution: return slow ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -104,8 +100,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -123,8 +117,6 @@ func middleNode(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -149,8 +141,6 @@ function middleNode(head: ListNode | null): ListNode | null { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -181,30 +171,6 @@ impl Solution { } ``` -### **C** - -```c -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * struct ListNode *next; - * }; - */ - -struct ListNode* middleNode(struct ListNode* head) { - struct ListNode* fast = head; - struct ListNode* slow = head; - while (fast && fast->next) { - fast = fast->next->next; - slow = slow->next; - } - return slow; -} -``` - -### **PHP** - ```php /** * Definition for a singly-linked list. @@ -239,10 +205,26 @@ class Solution { } ``` -### **...** - -``` +```c +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ +struct ListNode* middleNode(struct ListNode* head) { + struct ListNode* fast = head; + struct ListNode* slow = head; + while (fast && fast->next) { + fast = fast->next->next; + slow = slow->next; + } + return slow; +} ``` + + diff --git a/solution/0800-0899/0877.Stone Game/README.md b/solution/0800-0899/0877.Stone Game/README.md index 052d3939d0bb9..0423eee3d0430 100644 --- a/solution/0800-0899/0877.Stone Game/README.md +++ b/solution/0800-0899/0877.Stone Game/README.md @@ -49,9 +49,7 @@ Alice 先开始,只能拿前 5 颗或后 5 颗石子 。 ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j)$,表示从第 $i$ 堆石子到第 $j$ 堆石子,当前玩家与另一个玩家的石子数量之差的最大值。那么答案就是 $dfs(0, n - 1) \gt 0$。 @@ -66,33 +64,8 @@ Alice 先开始,只能拿前 5 颗或后 5 颗石子 。 时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是石子的堆数。 -**方法二:动态规划** - -我们也可以使用动态规划的方法,定义 $f[i][j]$ 表示当前玩家在 $piles[i..j]$ 这部分石子中能够获得的最大石子数的差值。那么最后答案就是 $f[0][n - 1] \gt 0$。 - -初始时 $f[i][i]=piles[i]$,因为只有一堆石子,所以当前玩家只能拿取这堆石子,差值为 $piles[i]$。 - -考虑 $f[i][j]$,其中 $i \lt j$,有两种情况: - -- 如果当前玩家拿走了石子堆 $piles[i]$,那么剩下的石子堆为 $piles[i + 1..j]$,此时轮到另一个玩家进行游戏,所以 $f[i][j] = piles[i] - f[i + 1][j]$。 -- 如果当前玩家拿走了石子堆 $piles[j]$,那么剩下的石子堆为 $piles[i..j - 1]$,此时轮到另一个玩家进行游戏,所以 $f[i][j] = piles[j] - f[i][j - 1]$。 - -因此,最终的状态转移方程为 $f[i][j] = \max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1])$。 - -最后,我们只需要判断 $f[0][n - 1] \gt 0$ 即可。 - -时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是石子的堆数。 - -相似题目: - -- [486. 预测赢家](/solution/0400-0499/0486.Predict%20the%20Winner/README.md) - -### **Python3** - - - ```python class Solution: def stoneGame(self, piles: List[int]) -> bool: @@ -105,23 +78,6 @@ class Solution: return dfs(0, len(piles) - 1) > 0 ``` -```python -class Solution: - def stoneGame(self, piles: List[int]) -> bool: - n = len(piles) - f = [[0] * n for _ in range(n)] - for i, x in enumerate(piles): - f[i][i] = x - for i in range(n - 2, -1, -1): - for j in range(i + 1, n): - f[i][j] = max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]) - return f[0][n - 1] > 0 -``` - -### **Java** - - - ```java class Solution { private int[] piles; @@ -146,26 +102,6 @@ class Solution { } ``` -```java -class Solution { - public boolean stoneGame(int[] piles) { - int n = piles.length; - int[][] f = new int[n][n]; - for (int i = 0; i < n; ++i) { - f[i][i] = piles[i]; - } - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = Math.max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]); - } - } - return f[0][n - 1] > 0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -187,28 +123,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool stoneGame(vector& piles) { - int n = piles.size(); - int f[n][n]; - memset(f, 0, sizeof(f)); - for (int i = 0; i < n; ++i) { - f[i][i] = piles[i]; - } - for (int i = n - 2; ~i; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]); - } - } - return f[0][n - 1] > 0; - } -}; -``` - -### **Go** - ```go func stoneGame(piles []int) bool { n := len(piles) @@ -230,25 +144,6 @@ func stoneGame(piles []int) bool { } ``` -```go -func stoneGame(piles []int) bool { - n := len(piles) - f := make([][]int, n) - for i, x := range piles { - f[i] = make([]int, n) - f[i][i] = x - } - for i := n - 2; i >= 0; i-- { - for j := i + 1; j < n; j++ { - f[i][j] = max(piles[i]-f[i+1][j], piles[j]-f[i][j-1]) - } - } - return f[0][n-1] > 0 -} -``` - -### **TypeScript** - ```ts function stoneGame(piles: number[]): boolean { const n = piles.length; @@ -266,6 +161,99 @@ function stoneGame(piles: number[]): boolean { } ``` + + +### 方法二:动态规划 + +我们也可以使用动态规划的方法,定义 $f[i][j]$ 表示当前玩家在 $piles[i..j]$ 这部分石子中能够获得的最大石子数的差值。那么最后答案就是 $f[0][n - 1] \gt 0$。 + +初始时 $f[i][i]=piles[i]$,因为只有一堆石子,所以当前玩家只能拿取这堆石子,差值为 $piles[i]$。 + +考虑 $f[i][j]$,其中 $i \lt j$,有两种情况: + +- 如果当前玩家拿走了石子堆 $piles[i]$,那么剩下的石子堆为 $piles[i + 1..j]$,此时轮到另一个玩家进行游戏,所以 $f[i][j] = piles[i] - f[i + 1][j]$。 +- 如果当前玩家拿走了石子堆 $piles[j]$,那么剩下的石子堆为 $piles[i..j - 1]$,此时轮到另一个玩家进行游戏,所以 $f[i][j] = piles[j] - f[i][j - 1]$。 + +因此,最终的状态转移方程为 $f[i][j] = \max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1])$。 + +最后,我们只需要判断 $f[0][n - 1] \gt 0$ 即可。 + +时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是石子的堆数。 + +相似题目: + +- [486. 预测赢家](/solution/0400-0499/0486.Predict%20the%20Winner/README.md) + + + +```python +class Solution: + def stoneGame(self, piles: List[int]) -> bool: + n = len(piles) + f = [[0] * n for _ in range(n)] + for i, x in enumerate(piles): + f[i][i] = x + for i in range(n - 2, -1, -1): + for j in range(i + 1, n): + f[i][j] = max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]) + return f[0][n - 1] > 0 +``` + +```java +class Solution { + public boolean stoneGame(int[] piles) { + int n = piles.length; + int[][] f = new int[n][n]; + for (int i = 0; i < n; ++i) { + f[i][i] = piles[i]; + } + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = Math.max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]); + } + } + return f[0][n - 1] > 0; + } +} +``` + +```cpp +class Solution { +public: + bool stoneGame(vector& piles) { + int n = piles.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int i = 0; i < n; ++i) { + f[i][i] = piles[i]; + } + for (int i = n - 2; ~i; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]); + } + } + return f[0][n - 1] > 0; + } +}; +``` + +```go +func stoneGame(piles []int) bool { + n := len(piles) + f := make([][]int, n) + for i, x := range piles { + f[i] = make([]int, n) + f[i][i] = x + } + for i := n - 2; i >= 0; i-- { + for j := i + 1; j < n; j++ { + f[i][j] = max(piles[i]-f[i+1][j], piles[j]-f[i][j-1]) + } + } + return f[0][n-1] > 0 +} +``` + ```ts function stoneGame(piles: number[]): boolean { const n = piles.length; @@ -282,10 +270,6 @@ function stoneGame(piles: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0877.Stone Game/README_EN.md b/solution/0800-0899/0877.Stone Game/README_EN.md index 85b77531e0a38..f47a244290a85 100644 --- a/solution/0800-0899/0877.Stone Game/README_EN.md +++ b/solution/0800-0899/0877.Stone Game/README_EN.md @@ -45,9 +45,9 @@ This demonstrated that taking the first 5 was a winning move for Alice, so we re ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,21 +61,6 @@ class Solution: return dfs(0, len(piles) - 1) > 0 ``` -```python -class Solution: - def stoneGame(self, piles: List[int]) -> bool: - n = len(piles) - f = [[0] * n for _ in range(n)] - for i, x in enumerate(piles): - f[i][i] = x - for i in range(n - 2, -1, -1): - for j in range(i + 1, n): - f[i][j] = max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]) - return f[0][n - 1] > 0 -``` - -### **Java** - ```java class Solution { private int[] piles; @@ -100,26 +85,6 @@ class Solution { } ``` -```java -class Solution { - public boolean stoneGame(int[] piles) { - int n = piles.length; - int[][] f = new int[n][n]; - for (int i = 0; i < n; ++i) { - f[i][i] = piles[i]; - } - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = Math.max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]); - } - } - return f[0][n - 1] > 0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -141,28 +106,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool stoneGame(vector& piles) { - int n = piles.size(); - int f[n][n]; - memset(f, 0, sizeof(f)); - for (int i = 0; i < n; ++i) { - f[i][i] = piles[i]; - } - for (int i = n - 2; ~i; --i) { - for (int j = i + 1; j < n; ++j) { - f[i][j] = max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]); - } - } - return f[0][n - 1] > 0; - } -}; -``` - -### **Go** - ```go func stoneGame(piles []int) bool { n := len(piles) @@ -184,25 +127,6 @@ func stoneGame(piles []int) bool { } ``` -```go -func stoneGame(piles []int) bool { - n := len(piles) - f := make([][]int, n) - for i, x := range piles { - f[i] = make([]int, n) - f[i][i] = x - } - for i := n - 2; i >= 0; i-- { - for j := i + 1; j < n; j++ { - f[i][j] = max(piles[i]-f[i+1][j], piles[j]-f[i][j-1]) - } - } - return f[0][n-1] > 0 -} -``` - -### **TypeScript** - ```ts function stoneGame(piles: number[]): boolean { const n = piles.length; @@ -220,6 +144,80 @@ function stoneGame(piles: number[]): boolean { } ``` + + +### Solution 2 + + + +```python +class Solution: + def stoneGame(self, piles: List[int]) -> bool: + n = len(piles) + f = [[0] * n for _ in range(n)] + for i, x in enumerate(piles): + f[i][i] = x + for i in range(n - 2, -1, -1): + for j in range(i + 1, n): + f[i][j] = max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]) + return f[0][n - 1] > 0 +``` + +```java +class Solution { + public boolean stoneGame(int[] piles) { + int n = piles.length; + int[][] f = new int[n][n]; + for (int i = 0; i < n; ++i) { + f[i][i] = piles[i]; + } + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = Math.max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]); + } + } + return f[0][n - 1] > 0; + } +} +``` + +```cpp +class Solution { +public: + bool stoneGame(vector& piles) { + int n = piles.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int i = 0; i < n; ++i) { + f[i][i] = piles[i]; + } + for (int i = n - 2; ~i; --i) { + for (int j = i + 1; j < n; ++j) { + f[i][j] = max(piles[i] - f[i + 1][j], piles[j] - f[i][j - 1]); + } + } + return f[0][n - 1] > 0; + } +}; +``` + +```go +func stoneGame(piles []int) bool { + n := len(piles) + f := make([][]int, n) + for i, x := range piles { + f[i] = make([]int, n) + f[i][i] = x + } + for i := n - 2; i >= 0; i-- { + for j := i + 1; j < n; j++ { + f[i][j] = max(piles[i]-f[i+1][j], piles[j]-f[i][j-1]) + } + } + return f[0][n-1] > 0 +} +``` + ```ts function stoneGame(piles: number[]): boolean { const n = piles.length; @@ -236,10 +234,6 @@ function stoneGame(piles: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0878.Nth Magical Number/README.md b/solution/0800-0899/0878.Nth Magical Number/README.md index dfaf147256f3c..afa5f32507c12 100644 --- a/solution/0800-0899/0878.Nth Magical Number/README.md +++ b/solution/0800-0899/0878.Nth Magical Number/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:数学 + 二分查找** +### 方法一:数学 + 二分查找 根据题目描述,神奇数字是能被 $a$ 或 $b$ 整除的正整数。 @@ -72,10 +70,6 @@ $$ -### **Python3** - - - ```python class Solution: def nthMagicalNumber(self, n: int, a: int, b: int) -> int: @@ -85,10 +79,6 @@ class Solution: return bisect_left(range(r), x=n, key=lambda x: x // a + x // b - x // c) % mod ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func nthMagicalNumber(n int, a int, b int) int { c := a * b / gcd(a, b) @@ -155,10 +141,6 @@ func gcd(a, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0878.Nth Magical Number/README_EN.md b/solution/0800-0899/0878.Nth Magical Number/README_EN.md index b2b3952f5bbf2..85553d2b530ea 100644 --- a/solution/0800-0899/0878.Nth Magical Number/README_EN.md +++ b/solution/0800-0899/0878.Nth Magical Number/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -46,8 +46,6 @@ class Solution: return bisect_left(range(r), x=n, key=lambda x: x // a + x // b - x // c) % mod ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func nthMagicalNumber(n int, a int, b int) int { c := a * b / gcd(a, b) @@ -114,10 +108,6 @@ func gcd(a, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0879.Profitable Schemes/README.md b/solution/0800-0899/0879.Profitable Schemes/README.md index 292edcd7bfbe8..6a4dad5e9a4d7 100644 --- a/solution/0800-0899/0879.Profitable Schemes/README.md +++ b/solution/0800-0899/0879.Profitable Schemes/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j, k)$,表示从第 $i$ 个工作开始,且当前已经选择了 $j$ 个员工,且当前产生的利润为 $k$,这种情况下的方案数。那么答案就是 $dfs(0, 0, 0)$。 @@ -68,22 +66,8 @@ 时间复杂度 $O(m \times n \times minProfit)$,空间复杂度 $O(m \times n \times minProfit)$。其中 $m$ 和 $n$ 分别为工作的数量和员工的数量,而 $minProfit$ 为至少产生的利润。 -**方法二:动态规划** - -我们定义 $f[i][j][k]$ 表示前 $i$ 个工作中,选择了不超过 $j$ 个员工,且至少产生 $k$ 的利润的方案数。初始时 $f[0][j][0] = 1$,表示不选择任何工作,且至少产生 $0$ 的利润的方案数为 $1$。答案即为 $f[m][n][minProfit]$。 - -对于第 $i$ 个工作,我们可以选择参与或不参与。如果不参与,则 $f[i][j][k] = f[i - 1][j][k]$;如果参与,则 $f[i][j][k] = f[i - 1][j - group[i - 1]][max(0, k - profit[i - 1])]$。我们需要枚举 $j$ 和 $k$,并将所有的方案数相加。 - -最终的答案即为 $f[m][n][minProfit]$。 - -时间复杂度 $O(m \times n \times minProfit)$,空间复杂度 $O(m \times n \times minProfit)$。其中 $m$ 和 $n$ 分别为工作的数量和员工的数量,而 $minProfit$ 为至少产生的利润。 - -### **Python3** - - - ```python class Solution: def profitableSchemes( @@ -101,29 +85,6 @@ class Solution: return dfs(0, 0, 0) ``` -```python -class Solution: - def profitableSchemes( - self, n: int, minProfit: int, group: List[int], profit: List[int] - ) -> int: - mod = 10**9 + 7 - m = len(group) - f = [[[0] * (minProfit + 1) for _ in range(n + 1)] for _ in range(m + 1)] - for j in range(n + 1): - f[0][j][0] = 1 - for i, (x, p) in enumerate(zip(group, profit), 1): - for j in range(n + 1): - for k in range(minProfit + 1): - f[i][j][k] = f[i - 1][j][k] - if j >= x: - f[i][j][k] = (f[i][j][k] + f[i - 1][j - x][max(0, k - p)]) % mod - return f[m][n][minProfit] -``` - -### **Java** - - - ```java class Solution { private Integer[][][] f; @@ -161,35 +122,6 @@ class Solution { } ``` -```java -class Solution { - public int profitableSchemes(int n, int minProfit, int[] group, int[] profit) { - final int mod = (int) 1e9 + 7; - int m = group.length; - int[][][] f = new int[m + 1][n + 1][minProfit + 1]; - for (int j = 0; j <= n; ++j) { - f[0][j][0] = 1; - } - for (int i = 1; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - for (int k = 0; k <= minProfit; ++k) { - f[i][j][k] = f[i - 1][j][k]; - if (j >= group[i - 1]) { - f[i][j][k] - = (f[i][j][k] - + f[i - 1][j - group[i - 1]][Math.max(0, k - profit[i - 1])]) - % mod; - } - } - } - } - return f[m][n][minProfit]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -217,34 +149,6 @@ public: }; ``` -```cpp -class Solution { -public: - int profitableSchemes(int n, int minProfit, vector& group, vector& profit) { - int m = group.size(); - int f[m + 1][n + 1][minProfit + 1]; - memset(f, 0, sizeof(f)); - for (int j = 0; j <= n; ++j) { - f[0][j][0] = 1; - } - const int mod = 1e9 + 7; - for (int i = 1; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - for (int k = 0; k <= minProfit; ++k) { - f[i][j][k] = f[i - 1][j][k]; - if (j >= group[i - 1]) { - f[i][j][k] = (f[i][j][k] + f[i - 1][j - group[i - 1]][max(0, k - profit[i - 1])]) % mod; - } - } - } - } - return f[m][n][minProfit]; - } -}; -``` - -### **Go** - ```go func profitableSchemes(n int, minProfit int, group []int, profit []int) int { m := len(group) @@ -282,7 +186,91 @@ func profitableSchemes(n int, minProfit int, group []int, profit []int) int { } ``` -### **Go** + + +### 方法二:动态规划 + +我们定义 $f[i][j][k]$ 表示前 $i$ 个工作中,选择了不超过 $j$ 个员工,且至少产生 $k$ 的利润的方案数。初始时 $f[0][j][0] = 1$,表示不选择任何工作,且至少产生 $0$ 的利润的方案数为 $1$。答案即为 $f[m][n][minProfit]$。 + +对于第 $i$ 个工作,我们可以选择参与或不参与。如果不参与,则 $f[i][j][k] = f[i - 1][j][k]$;如果参与,则 $f[i][j][k] = f[i - 1][j - group[i - 1]][max(0, k - profit[i - 1])]$。我们需要枚举 $j$ 和 $k$,并将所有的方案数相加。 + +最终的答案即为 $f[m][n][minProfit]$。 + +时间复杂度 $O(m \times n \times minProfit)$,空间复杂度 $O(m \times n \times minProfit)$。其中 $m$ 和 $n$ 分别为工作的数量和员工的数量,而 $minProfit$ 为至少产生的利润。 + + + +```python +class Solution: + def profitableSchemes( + self, n: int, minProfit: int, group: List[int], profit: List[int] + ) -> int: + mod = 10**9 + 7 + m = len(group) + f = [[[0] * (minProfit + 1) for _ in range(n + 1)] for _ in range(m + 1)] + for j in range(n + 1): + f[0][j][0] = 1 + for i, (x, p) in enumerate(zip(group, profit), 1): + for j in range(n + 1): + for k in range(minProfit + 1): + f[i][j][k] = f[i - 1][j][k] + if j >= x: + f[i][j][k] = (f[i][j][k] + f[i - 1][j - x][max(0, k - p)]) % mod + return f[m][n][minProfit] +``` + +```java +class Solution { + public int profitableSchemes(int n, int minProfit, int[] group, int[] profit) { + final int mod = (int) 1e9 + 7; + int m = group.length; + int[][][] f = new int[m + 1][n + 1][minProfit + 1]; + for (int j = 0; j <= n; ++j) { + f[0][j][0] = 1; + } + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + for (int k = 0; k <= minProfit; ++k) { + f[i][j][k] = f[i - 1][j][k]; + if (j >= group[i - 1]) { + f[i][j][k] + = (f[i][j][k] + + f[i - 1][j - group[i - 1]][Math.max(0, k - profit[i - 1])]) + % mod; + } + } + } + } + return f[m][n][minProfit]; + } +} +``` + +```cpp +class Solution { +public: + int profitableSchemes(int n, int minProfit, vector& group, vector& profit) { + int m = group.size(); + int f[m + 1][n + 1][minProfit + 1]; + memset(f, 0, sizeof(f)); + for (int j = 0; j <= n; ++j) { + f[0][j][0] = 1; + } + const int mod = 1e9 + 7; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + for (int k = 0; k <= minProfit; ++k) { + f[i][j][k] = f[i - 1][j][k]; + if (j >= group[i - 1]) { + f[i][j][k] = (f[i][j][k] + f[i - 1][j - group[i - 1]][max(0, k - profit[i - 1])]) % mod; + } + } + } + } + return f[m][n][minProfit]; + } +}; +``` ```go func profitableSchemes(n int, minProfit int, group []int, profit []int) int { @@ -313,10 +301,6 @@ func profitableSchemes(n int, minProfit int, group []int, profit []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0879.Profitable Schemes/README_EN.md b/solution/0800-0899/0879.Profitable Schemes/README_EN.md index d1475dcc60527..47844d4dc7ffe 100644 --- a/solution/0800-0899/0879.Profitable Schemes/README_EN.md +++ b/solution/0800-0899/0879.Profitable Schemes/README_EN.md @@ -41,7 +41,7 @@ There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2). -### **Python3** - ```python class Solution: def profitableSchemes( @@ -87,27 +75,6 @@ class Solution: return dfs(0, 0, 0) ``` -```python -class Solution: - def profitableSchemes( - self, n: int, minProfit: int, group: List[int], profit: List[int] - ) -> int: - mod = 10**9 + 7 - m = len(group) - f = [[[0] * (minProfit + 1) for _ in range(n + 1)] for _ in range(m + 1)] - for j in range(n + 1): - f[0][j][0] = 1 - for i, (x, p) in enumerate(zip(group, profit), 1): - for j in range(n + 1): - for k in range(minProfit + 1): - f[i][j][k] = f[i - 1][j][k] - if j >= x: - f[i][j][k] = (f[i][j][k] + f[i - 1][j - x][max(0, k - p)]) % mod - return f[m][n][minProfit] -``` - -### **Java** - ```java class Solution { private Integer[][][] f; @@ -145,35 +112,6 @@ class Solution { } ``` -```java -class Solution { - public int profitableSchemes(int n, int minProfit, int[] group, int[] profit) { - final int mod = (int) 1e9 + 7; - int m = group.length; - int[][][] f = new int[m + 1][n + 1][minProfit + 1]; - for (int j = 0; j <= n; ++j) { - f[0][j][0] = 1; - } - for (int i = 1; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - for (int k = 0; k <= minProfit; ++k) { - f[i][j][k] = f[i - 1][j][k]; - if (j >= group[i - 1]) { - f[i][j][k] - = (f[i][j][k] - + f[i - 1][j - group[i - 1]][Math.max(0, k - profit[i - 1])]) - % mod; - } - } - } - } - return f[m][n][minProfit]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -201,34 +139,6 @@ public: }; ``` -```cpp -class Solution { -public: - int profitableSchemes(int n, int minProfit, vector& group, vector& profit) { - int m = group.size(); - int f[m + 1][n + 1][minProfit + 1]; - memset(f, 0, sizeof(f)); - for (int j = 0; j <= n; ++j) { - f[0][j][0] = 1; - } - const int mod = 1e9 + 7; - for (int i = 1; i <= m; ++i) { - for (int j = 0; j <= n; ++j) { - for (int k = 0; k <= minProfit; ++k) { - f[i][j][k] = f[i - 1][j][k]; - if (j >= group[i - 1]) { - f[i][j][k] = (f[i][j][k] + f[i - 1][j - group[i - 1]][max(0, k - profit[i - 1])]) % mod; - } - } - } - } - return f[m][n][minProfit]; - } -}; -``` - -### **Go** - ```go func profitableSchemes(n int, minProfit int, group []int, profit []int) int { m := len(group) @@ -266,6 +176,92 @@ func profitableSchemes(n int, minProfit int, group []int, profit []int) int { } ``` + + +### Solution 2: Dynamic Programming + +We define $f[i][j][k]$ to be the number of schemes to make a profit of at least $k$ with $i$ jobs and $j$ workers. Initially, we have $f[0][j][0] = 1$, which means that there is only one scheme to make a profit of $0$ without any jobs. + +For the $i$-th job, we can choose to work or not to work. If we do not work, then $f[i][j][k] = f[i - 1][j][k]$; if we work, then $f[i][j][k] = f[i - 1][j - group[i - 1]][max(0, k - profit[i - 1])]$. We need to enumerate $j$ and $k$, and add up all the schemes. + +The final answer is $f[m][n][minProfit]$. + +The time complexity is $O(m \times n \times minProfit)$, and the space complexity is $O(m \times n \times minProfit)$. Here $m$ and $n$ are the numbers of jobs and workers, and $minProfit$ is the minimum profit to make. + + + +```python +class Solution: + def profitableSchemes( + self, n: int, minProfit: int, group: List[int], profit: List[int] + ) -> int: + mod = 10**9 + 7 + m = len(group) + f = [[[0] * (minProfit + 1) for _ in range(n + 1)] for _ in range(m + 1)] + for j in range(n + 1): + f[0][j][0] = 1 + for i, (x, p) in enumerate(zip(group, profit), 1): + for j in range(n + 1): + for k in range(minProfit + 1): + f[i][j][k] = f[i - 1][j][k] + if j >= x: + f[i][j][k] = (f[i][j][k] + f[i - 1][j - x][max(0, k - p)]) % mod + return f[m][n][minProfit] +``` + +```java +class Solution { + public int profitableSchemes(int n, int minProfit, int[] group, int[] profit) { + final int mod = (int) 1e9 + 7; + int m = group.length; + int[][][] f = new int[m + 1][n + 1][minProfit + 1]; + for (int j = 0; j <= n; ++j) { + f[0][j][0] = 1; + } + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + for (int k = 0; k <= minProfit; ++k) { + f[i][j][k] = f[i - 1][j][k]; + if (j >= group[i - 1]) { + f[i][j][k] + = (f[i][j][k] + + f[i - 1][j - group[i - 1]][Math.max(0, k - profit[i - 1])]) + % mod; + } + } + } + } + return f[m][n][minProfit]; + } +} +``` + +```cpp +class Solution { +public: + int profitableSchemes(int n, int minProfit, vector& group, vector& profit) { + int m = group.size(); + int f[m + 1][n + 1][minProfit + 1]; + memset(f, 0, sizeof(f)); + for (int j = 0; j <= n; ++j) { + f[0][j][0] = 1; + } + const int mod = 1e9 + 7; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j <= n; ++j) { + for (int k = 0; k <= minProfit; ++k) { + f[i][j][k] = f[i - 1][j][k]; + if (j >= group[i - 1]) { + f[i][j][k] = (f[i][j][k] + f[i - 1][j - group[i - 1]][max(0, k - profit[i - 1])]) % mod; + } + } + } + } + return f[m][n][minProfit]; + } +}; +``` + ```go func profitableSchemes(n int, minProfit int, group []int, profit []int) int { m := len(group) @@ -295,10 +291,6 @@ func profitableSchemes(n int, minProfit int, group []int, profit []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0880.Decoded String at Index/README.md b/solution/0800-0899/0880.Decoded String at Index/README.md index a2840eb410389..96f2e4b15eba7 100644 --- a/solution/0800-0899/0880.Decoded String at Index/README.md +++ b/solution/0800-0899/0880.Decoded String at Index/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:逆向思维** +### 方法一:逆向思维 我们可以先计算出解码字符串的总长度 $m$,然后从后向前遍历字符串,每次更新 $k$ 为 $k \bmod m$,直到 $k$ 为 $0$ 且当前字符为字母,返回当前字符。否则,如果当前字符为数字,则将 $m$ 除以该数字。如果当前字符为字母,则将 $m$ 减 $1$。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def decodeAtIndex(self, s: str, k: int) -> str: @@ -90,10 +84,6 @@ class Solution: m -= 1 ``` -### **Java** - - - ```java class Solution { public String decodeAtIndex(String s, int k) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go func decodeAtIndex(s string, k int) string { m := 0 @@ -175,8 +161,6 @@ func decodeAtIndex(s string, k int) string { } ``` -### **TypeScript** - ```ts function decodeAtIndex(s: string, k: number): string { let m = 0n; @@ -203,10 +187,6 @@ function decodeAtIndex(s: string, k: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0880.Decoded String at Index/README_EN.md b/solution/0800-0899/0880.Decoded String at Index/README_EN.md index 62d461f36f0f9..bdccebb883790 100644 --- a/solution/0800-0899/0880.Decoded String at Index/README_EN.md +++ b/solution/0800-0899/0880.Decoded String at Index/README_EN.md @@ -55,7 +55,7 @@ The 1st letter is "a". ## Solutions -**Solution 1: Reverse Thinking** +### Solution 1: Reverse Thinking We can first calculate the total length $m$ of the decoded string, then traverse the string from back to front. Each time, we update $k$ to be $k \bmod m$, until $k$ is $0$ and the current character is a letter, then we return the current character. Otherwise, if the current character is a number, we divide $m$ by this number. If the current character is a letter, we subtract $1$ from $m$. @@ -63,8 +63,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string. The space -### **Python3** - ```python class Solution: def decodeAtIndex(self, s: str, k: int) -> str: @@ -84,8 +82,6 @@ class Solution: m -= 1 ``` -### **Java** - ```java class Solution { public String decodeAtIndex(String s, int k) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +135,6 @@ public: }; ``` -### **Go** - ```go func decodeAtIndex(s string, k int) string { m := 0 @@ -167,8 +159,6 @@ func decodeAtIndex(s string, k int) string { } ``` -### **TypeScript** - ```ts function decodeAtIndex(s: string, k: number): string { let m = 0n; @@ -195,10 +185,6 @@ function decodeAtIndex(s: string, k: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0881.Boats to Save People/README.md b/solution/0800-0899/0881.Boats to Save People/README.md index 3ad453ba9ef12..0a4ba7da430da 100644 --- a/solution/0800-0899/0881.Boats to Save People/README.md +++ b/solution/0800-0899/0881.Boats to Save People/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:贪心 + 双指针** +### 方法一:贪心 + 双指针 排序后,使用双指针分别指向数组首尾,每次取两个指针指向的元素之和与 `limit` 比较,如果小于等于 `limit`,则两个指针同时向中间移动一位,否则只移动右指针。累加答案即可。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: @@ -76,10 +70,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numRescueBoats(int[] people, int limit) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func numRescueBoats(people []int, limit int) int { sort.Ints(people) @@ -131,10 +117,6 @@ func numRescueBoats(people []int, limit int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0881.Boats to Save People/README_EN.md b/solution/0800-0899/0881.Boats to Save People/README_EN.md index 2f145dd25c90b..8f6f8ace884bf 100644 --- a/solution/0800-0899/0881.Boats to Save People/README_EN.md +++ b/solution/0800-0899/0881.Boats to Save People/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numRescueBoats(int[] people, int limit) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +94,6 @@ public: }; ``` -### **Go** - ```go func numRescueBoats(people []int, limit int) int { sort.Ints(people) @@ -114,10 +108,6 @@ func numRescueBoats(people []int, limit int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0882.Reachable Nodes In Subdivided Graph/README.md b/solution/0800-0899/0882.Reachable Nodes In Subdivided Graph/README.md index 8b5986fb6c576..87c869e3057cb 100644 --- a/solution/0800-0899/0882.Reachable Nodes In Subdivided Graph/README.md +++ b/solution/0800-0899/0882.Reachable Nodes In Subdivided Graph/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:Dijkstra 算法** +### 方法一:Dijkstra 算法 这道题本质是求从节点 $0$ 出发,最多经过 $maxMoves$ 步,可以到达多少个节点。单源最短路,且边权非负,我们可以考虑使用 Dijkstra 算法。 @@ -86,10 +84,6 @@ -### **Python3** - - - ```python class Solution: def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int: @@ -113,10 +107,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int reachableNodes(int[][] edges, int maxMoves, int n) { @@ -160,8 +150,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -201,8 +189,6 @@ public: }; ``` -### **Go** - ```go func reachableNodes(edges [][]int, maxMoves int, n int) (ans int) { g := make([][]pair, n) @@ -252,10 +238,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0882.Reachable Nodes In Subdivided Graph/README_EN.md b/solution/0800-0899/0882.Reachable Nodes In Subdivided Graph/README_EN.md index c0c7f3f6568c1..20644778654fb 100644 --- a/solution/0800-0899/0882.Reachable Nodes In Subdivided Graph/README_EN.md +++ b/solution/0800-0899/0882.Reachable Nodes In Subdivided Graph/README_EN.md @@ -54,9 +54,9 @@ The nodes that are reachable are highlighted in yellow. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -81,8 +81,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int reachableNodes(int[][] edges, int maxMoves, int n) { @@ -126,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +163,6 @@ public: }; ``` -### **Go** - ```go func reachableNodes(edges [][]int, maxMoves int, n int) (ans int) { g := make([][]pair, n) @@ -218,10 +212,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0883.Projection Area of 3D Shapes/README.md b/solution/0800-0899/0883.Projection Area of 3D Shapes/README.md index f63a009f532c4..710b7b5e10a8a 100644 --- a/solution/0800-0899/0883.Projection Area of 3D Shapes/README.md +++ b/solution/0800-0899/0883.Projection Area of 3D Shapes/README.md @@ -66,22 +66,10 @@ ## 解法 - - -根据题意: - -- xy 表示 grid 中大于 0 的元素个数 -- yz 表示 grid 每一行的最大值之和 -- zx 表示 grid 每一列的最大值之和 - -遍历 grid,更新 xy, yz, zx。遍历结束返回 `xy + yz + zx`。 +### 方法一 -### **Python3** - - - ```python class Solution: def projectionArea(self, grid: List[List[int]]) -> int: @@ -91,10 +79,6 @@ class Solution: return xy + yz + zx ``` -### **Java** - - - ```java class Solution { public int projectionArea(int[][] grid) { @@ -117,52 +101,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function projectionArea(grid: number[][]): number { - const n = grid.length; - let res = grid.reduce((r, v) => r + v.reduce((r, v) => r + (v === 0 ? 0 : 1), 0), 0); - for (let i = 0; i < n; i++) { - let xMax = 0; - let yMax = 0; - for (let j = 0; j < n; j++) { - xMax = Math.max(xMax, grid[i][j]); - yMax = Math.max(yMax, grid[j][i]); - } - res += xMax + yMax; - } - return res; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn projection_area(grid: Vec>) -> i32 { - let n = grid.len(); - let mut res = 0; - let mut x_max = vec![0; n]; - let mut y_max = vec![0; n]; - for i in 0..n { - for j in 0..n { - let val = grid[i][j]; - if val == 0 { - continue; - } - res += 1; - x_max[i] = x_max[i].max(val); - y_max[j] = y_max[j].max(val); - } - } - res + y_max.iter().sum::() + x_max.iter().sum::() - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -183,8 +121,6 @@ public: }; ``` -### **Go** - ```go func projectionArea(grid [][]int) int { xy, yz, zx := 0, 0, 0 @@ -204,10 +140,46 @@ func projectionArea(grid [][]int) int { } ``` -### **...** - +```ts +function projectionArea(grid: number[][]): number { + const n = grid.length; + let res = grid.reduce((r, v) => r + v.reduce((r, v) => r + (v === 0 ? 0 : 1), 0), 0); + for (let i = 0; i < n; i++) { + let xMax = 0; + let yMax = 0; + for (let j = 0; j < n; j++) { + xMax = Math.max(xMax, grid[i][j]); + yMax = Math.max(yMax, grid[j][i]); + } + res += xMax + yMax; + } + return res; +} ``` +```rust +impl Solution { + pub fn projection_area(grid: Vec>) -> i32 { + let n = grid.len(); + let mut res = 0; + let mut x_max = vec![0; n]; + let mut y_max = vec![0; n]; + for i in 0..n { + for j in 0..n { + let val = grid[i][j]; + if val == 0 { + continue; + } + res += 1; + x_max[i] = x_max[i].max(val); + y_max[j] = y_max[j].max(val); + } + } + res + y_max.iter().sum::() + x_max.iter().sum::() + } +} ``` + + diff --git a/solution/0800-0899/0883.Projection Area of 3D Shapes/README_EN.md b/solution/0800-0899/0883.Projection Area of 3D Shapes/README_EN.md index 4ca3af85ddcbd..4483e8958e635 100644 --- a/solution/0800-0899/0883.Projection Area of 3D Shapes/README_EN.md +++ b/solution/0800-0899/0883.Projection Area of 3D Shapes/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return xy + yz + zx ``` -### **Java** - ```java class Solution { public int projectionArea(int[][] grid) { @@ -85,52 +83,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function projectionArea(grid: number[][]): number { - const n = grid.length; - let res = grid.reduce((r, v) => r + v.reduce((r, v) => r + (v === 0 ? 0 : 1), 0), 0); - for (let i = 0; i < n; i++) { - let xMax = 0; - let yMax = 0; - for (let j = 0; j < n; j++) { - xMax = Math.max(xMax, grid[i][j]); - yMax = Math.max(yMax, grid[j][i]); - } - res += xMax + yMax; - } - return res; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn projection_area(grid: Vec>) -> i32 { - let n = grid.len(); - let mut res = 0; - let mut x_max = vec![0; n]; - let mut y_max = vec![0; n]; - for i in 0..n { - for j in 0..n { - let val = grid[i][j]; - if val == 0 { - continue; - } - res += 1; - x_max[i] = x_max[i].max(val); - y_max[j] = y_max[j].max(val); - } - } - res + y_max.iter().sum::() + x_max.iter().sum::() - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -151,8 +103,6 @@ public: }; ``` -### **Go** - ```go func projectionArea(grid [][]int) int { xy, yz, zx := 0, 0, 0 @@ -172,10 +122,46 @@ func projectionArea(grid [][]int) int { } ``` -### **...** - +```ts +function projectionArea(grid: number[][]): number { + const n = grid.length; + let res = grid.reduce((r, v) => r + v.reduce((r, v) => r + (v === 0 ? 0 : 1), 0), 0); + for (let i = 0; i < n; i++) { + let xMax = 0; + let yMax = 0; + for (let j = 0; j < n; j++) { + xMax = Math.max(xMax, grid[i][j]); + yMax = Math.max(yMax, grid[j][i]); + } + res += xMax + yMax; + } + return res; +} ``` +```rust +impl Solution { + pub fn projection_area(grid: Vec>) -> i32 { + let n = grid.len(); + let mut res = 0; + let mut x_max = vec![0; n]; + let mut y_max = vec![0; n]; + for i in 0..n { + for j in 0..n { + let val = grid[i][j]; + if val == 0 { + continue; + } + res += 1; + x_max[i] = x_max[i].max(val); + y_max[j] = y_max[j].max(val); + } + } + res + y_max.iter().sum::() + x_max.iter().sum::() + } +} ``` + + diff --git a/solution/0800-0899/0884.Uncommon Words from Two Sentences/README.md b/solution/0800-0899/0884.Uncommon Words from Two Sentences/README.md index ab0030c65b82e..5ff8e7b03fa81 100644 --- a/solution/0800-0899/0884.Uncommon Words from Two Sentences/README.md +++ b/solution/0800-0899/0884.Uncommon Words from Two Sentences/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 根据题目描述,只要单词出现一次,就符合题目要求。因此,我们用哈希表 $cnt$ 记录所有单词以及出现的次数。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def uncommonFromSentences(self, s1: str, s2: str) -> List[str]: @@ -67,10 +61,6 @@ class Solution: return [s for s, v in cnt.items() if v == 1] ``` -### **Java** - - - ```java class Solution { public String[] uncommonFromSentences(String s1, String s2) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func uncommonFromSentences(s1 string, s2 string) (ans []string) { cnt := map[string]int{} @@ -134,8 +120,6 @@ func uncommonFromSentences(s1 string, s2 string) (ans []string) { } ``` -### **TypeScript** - ```ts function uncommonFromSentences(s1: string, s2: string): string[] { const cnt: Map = new Map(); @@ -152,8 +136,6 @@ function uncommonFromSentences(s1: string, s2: string): string[] { } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -177,8 +159,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {string} s1 @@ -200,10 +180,6 @@ var uncommonFromSentences = function (s1, s2) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0884.Uncommon Words from Two Sentences/README_EN.md b/solution/0800-0899/0884.Uncommon Words from Two Sentences/README_EN.md index 740cf8e39e823..8b098a0bb6408 100644 --- a/solution/0800-0899/0884.Uncommon Words from Two Sentences/README_EN.md +++ b/solution/0800-0899/0884.Uncommon Words from Two Sentences/README_EN.md @@ -30,9 +30,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -41,8 +41,6 @@ class Solution: return [s for s, v in cnt.items() if v == 1] ``` -### **Java** - ```java class Solution { public String[] uncommonFromSentences(String s1, String s2) { @@ -64,8 +62,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -86,8 +82,6 @@ public: }; ``` -### **Go** - ```go func uncommonFromSentences(s1 string, s2 string) (ans []string) { cnt := map[string]int{} @@ -106,8 +100,6 @@ func uncommonFromSentences(s1 string, s2 string) (ans []string) { } ``` -### **TypeScript** - ```ts function uncommonFromSentences(s1: string, s2: string): string[] { const cnt: Map = new Map(); @@ -124,8 +116,6 @@ function uncommonFromSentences(s1: string, s2: string): string[] { } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -149,8 +139,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {string} s1 @@ -172,10 +160,6 @@ var uncommonFromSentences = function (s1, s2) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0885.Spiral Matrix III/README.md b/solution/0800-0899/0885.Spiral Matrix III/README.md index db71804ba60f7..5a145dafe1af8 100644 --- a/solution/0800-0899/0885.Spiral Matrix III/README.md +++ b/solution/0800-0899/0885.Spiral Matrix III/README.md @@ -42,14 +42,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def spiralMatrixIII( @@ -71,10 +67,6 @@ class Solution: k += 2 ``` -### **Java** - - - ```java class Solution { public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) { @@ -104,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +122,6 @@ public: }; ``` -### **Go** - ```go func spiralMatrixIII(rows int, cols int, rStart int, cStart int) [][]int { cnt := rows * cols @@ -161,10 +149,6 @@ func spiralMatrixIII(rows int, cols int, rStart int, cStart int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0885.Spiral Matrix III/README_EN.md b/solution/0800-0899/0885.Spiral Matrix III/README_EN.md index ef5199198a3bd..f27ee89719bdf 100644 --- a/solution/0800-0899/0885.Spiral Matrix III/README_EN.md +++ b/solution/0800-0899/0885.Spiral Matrix III/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: k += 2 ``` -### **Java** - ```java class Solution { public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +116,6 @@ public: }; ``` -### **Go** - ```go func spiralMatrixIII(rows int, cols int, rStart int, cStart int) [][]int { cnt := rows * cols @@ -149,10 +143,6 @@ func spiralMatrixIII(rows int, cols int, rStart int, cStart int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0886.Possible Bipartition/README.md b/solution/0800-0899/0886.Possible Bipartition/README.md index c629781bc4932..06aea24b070f7 100644 --- a/solution/0800-0899/0886.Possible Bipartition/README.md +++ b/solution/0800-0899/0886.Possible Bipartition/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:染色法** +### 方法一:染色法 我们用两种颜色对图进行染色,如果可以完成染色,那么就说明可以将所有人分进两组。 @@ -68,55 +66,8 @@ 时间复杂度 $O(n + m)$,其中 $n$, $m$ 分别是人数和不喜欢的关系数。 -**方法二:并查集** - -并查集是一种树形的数据结构,顾名思义,它用于处理一些不交集的**合并**及**查询**问题。 它支持两种操作: - -1. 查找(Find):确定某个元素处于哪个子集,单次操作时间复杂度 $O(\alpha(n))$ -1. 合并(Union):将两个子集合并成一个集合,单次操作时间复杂度 $O(\alpha(n))$ - -其中 $\alpha$ 为阿克曼函数的反函数,其增长极其缓慢,也就是说其单次操作的平均运行时间可以认为是一个很小的常数。 - -以下是并查集的常用模板,需要熟练掌握。其中: - -- `n` 表示节点数 -- `p` 存储每个点的父节点,初始时每个点的父节点都是自己 -- `size` 只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -- `find(x)` 函数用于查找 $x$ 所在集合的祖宗节点 -- `union(a, b)` 函数用于合并 $a$ 和 $b$ 所在的集合 - -```python -p = list(range(n)) -size = [1] * n - - -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -def union(a, b): - pa, pb = find(a), find(b) - if pa == pb: - return - p[pa] = pb - size[pb] += size[pa] -``` - -对于本题,我们遍历每一个人,他与他不喜欢的人不应该在同一个集合中,如果在同一个集合中,就产生了冲突,直接返回 `false`。如果没有冲突,那么就将他所有不喜欢的人合并到同一个集合中。 - -遍历结束,说明没有冲突,返回 `true`。 - -时间复杂度 $O(n + m\times \alpha(n))$。 - -### **Python3** - - - ```python class Solution: def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool: @@ -138,32 +89,6 @@ class Solution: return all(c or dfs(i, 1) for i, c in enumerate(color)) ``` -```python -class Solution: - def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool: - def find(x): - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - g = defaultdict(list) - for a, b in dislikes: - a, b = a - 1, b - 1 - g[a].append(b) - g[b].append(a) - p = list(range(n)) - for i in range(n): - for j in g[i]: - if find(i) == find(j): - return False - p[find(j)] = find(g[i][0]) - return True -``` - -### **Java** - - - ```java class Solution { private List[] g; @@ -203,44 +128,6 @@ class Solution { } ``` -```java -class Solution { - private int[] p; - - public boolean possibleBipartition(int n, int[][] dislikes) { - p = new int[n]; - List[] g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int i = 0; i < n; ++i) { - p[i] = i; - } - for (var e : dislikes) { - int a = e[0] - 1, b = e[1] - 1; - g[a].add(b); - g[b].add(a); - } - for (int i = 0; i < n; ++i) { - for (int j : g[i]) { - if (find(i) == find(j)) { - return false; - } - p[find(j)] = find(g[i].get(0)); - } - } - return true; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -268,35 +155,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool possibleBipartition(int n, vector>& dislikes) { - vector p(n); - iota(p.begin(), p.end(), 0); - unordered_map> g; - for (auto& e : dislikes) { - int a = e[0] - 1, b = e[1] - 1; - g[a].push_back(b); - g[b].push_back(a); - } - function find = [&](int x) -> int { - if (p[x] != x) p[x] = find(p[x]); - return p[x]; - }; - for (int i = 0; i < n; ++i) { - for (int j : g[i]) { - if (find(i) == find(j)) return false; - p[find(j)] = find(g[i][0]); - } - } - return true; - } -}; -``` - -### **Go** - ```go func possibleBipartition(n int, dislikes [][]int) bool { g := make([][]int, n) @@ -328,39 +186,6 @@ func possibleBipartition(n int, dislikes [][]int) bool { } ``` -```go -func possibleBipartition(n int, dislikes [][]int) bool { - p := make([]int, n) - g := make([][]int, n) - for i := range p { - p[i] = i - } - for _, e := range dislikes { - a, b := e[0]-1, e[1]-1 - g[a] = append(g[a], b) - g[b] = append(g[b], a) - } - var find func(int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - for i := 0; i < n; i++ { - for _, j := range g[i] { - if find(i) == find(j) { - return false - } - p[find(j)] = find(g[i][0]) - } - } - return true -} -``` - -### **TypeScript** - ```ts function possibleBipartition(n: number, dislikes: number[][]): boolean { const color = new Array(n + 1).fill(0); @@ -387,8 +212,6 @@ function possibleBipartition(n: number, dislikes: number[][]): boolean { } ``` -### **Rust** - ```rust impl Solution { fn dfs(i: usize, v: usize, color: &mut Vec, g: &Vec>) -> bool { @@ -420,10 +243,169 @@ impl Solution { } ``` -### **...** + + +### 方法二:并查集 + +并查集是一种树形的数据结构,顾名思义,它用于处理一些不交集的**合并**及**查询**问题。 它支持两种操作: + +1. 查找(Find):确定某个元素处于哪个子集,单次操作时间复杂度 $O(\alpha(n))$ +1. 合并(Union):将两个子集合并成一个集合,单次操作时间复杂度 $O(\alpha(n))$ + +其中 $\alpha$ 为阿克曼函数的反函数,其增长极其缓慢,也就是说其单次操作的平均运行时间可以认为是一个很小的常数。 + +以下是并查集的常用模板,需要熟练掌握。其中: + +- `n` 表示节点数 +- `p` 存储每个点的父节点,初始时每个点的父节点都是自己 +- `size` 只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 +- `find(x)` 函数用于查找 $x$ 所在集合的祖宗节点 +- `union(a, b)` 函数用于合并 $a$ 和 $b$ 所在的集合 + +```python +p = list(range(n)) +size = [1] * n + + +def find(x): + if p[x] != x: + # 路径压缩 + p[x] = find(p[x]) + return p[x] + + +def union(a, b): + pa, pb = find(a), find(b) + if pa == pb: + return + p[pa] = pb + size[pb] += size[pa] +``` + +对于本题,我们遍历每一个人,他与他不喜欢的人不应该在同一个集合中,如果在同一个集合中,就产生了冲突,直接返回 `false`。如果没有冲突,那么就将他所有不喜欢的人合并到同一个集合中。 + +遍历结束,说明没有冲突,返回 `true`。 + +时间复杂度 $O(n + m\times \alpha(n))$。 + + + +```python +class Solution: + def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + g = defaultdict(list) + for a, b in dislikes: + a, b = a - 1, b - 1 + g[a].append(b) + g[b].append(a) + p = list(range(n)) + for i in range(n): + for j in g[i]: + if find(i) == find(j): + return False + p[find(j)] = find(g[i][0]) + return True +``` + +```java +class Solution { + private int[] p; + + public boolean possibleBipartition(int n, int[][] dislikes) { + p = new int[n]; + List[] g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int i = 0; i < n; ++i) { + p[i] = i; + } + for (var e : dislikes) { + int a = e[0] - 1, b = e[1] - 1; + g[a].add(b); + g[b].add(a); + } + for (int i = 0; i < n; ++i) { + for (int j : g[i]) { + if (find(i) == find(j)) { + return false; + } + p[find(j)] = find(g[i].get(0)); + } + } + return true; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} +``` +```cpp +class Solution { +public: + bool possibleBipartition(int n, vector>& dislikes) { + vector p(n); + iota(p.begin(), p.end(), 0); + unordered_map> g; + for (auto& e : dislikes) { + int a = e[0] - 1, b = e[1] - 1; + g[a].push_back(b); + g[b].push_back(a); + } + function find = [&](int x) -> int { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + }; + for (int i = 0; i < n; ++i) { + for (int j : g[i]) { + if (find(i) == find(j)) return false; + p[find(j)] = find(g[i][0]); + } + } + return true; + } +}; ``` +```go +func possibleBipartition(n int, dislikes [][]int) bool { + p := make([]int, n) + g := make([][]int, n) + for i := range p { + p[i] = i + } + for _, e := range dislikes { + a, b := e[0]-1, e[1]-1 + g[a] = append(g[a], b) + g[b] = append(g[b], a) + } + var find func(int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + for i := 0; i < n; i++ { + for _, j := range g[i] { + if find(i) == find(j) { + return false + } + p[find(j)] = find(g[i][0]) + } + } + return true +} ``` + + diff --git a/solution/0800-0899/0886.Possible Bipartition/README_EN.md b/solution/0800-0899/0886.Possible Bipartition/README_EN.md index bb328e34f8277..1d4edfefeaffa 100644 --- a/solution/0800-0899/0886.Possible Bipartition/README_EN.md +++ b/solution/0800-0899/0886.Possible Bipartition/README_EN.md @@ -38,12 +38,10 @@ ## Solutions -Union find. +### Solution 1 -### **Python3** - ```python class Solution: def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool: @@ -65,30 +63,6 @@ class Solution: return all(c or dfs(i, 1) for i, c in enumerate(color)) ``` -```python -class Solution: - def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool: - def find(x): - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - g = defaultdict(list) - for a, b in dislikes: - a, b = a - 1, b - 1 - g[a].append(b) - g[b].append(a) - p = list(range(n)) - for i in range(n): - for j in g[i]: - if find(i) == find(j): - return False - p[find(j)] = find(g[i][0]) - return True -``` - -### **Java** - ```java class Solution { private List[] g; @@ -128,44 +102,6 @@ class Solution { } ``` -```java -class Solution { - private int[] p; - - public boolean possibleBipartition(int n, int[][] dislikes) { - p = new int[n]; - List[] g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int i = 0; i < n; ++i) { - p[i] = i; - } - for (var e : dislikes) { - int a = e[0] - 1, b = e[1] - 1; - g[a].add(b); - g[b].add(a); - } - for (int i = 0; i < n; ++i) { - for (int j : g[i]) { - if (find(i) == find(j)) { - return false; - } - p[find(j)] = find(g[i].get(0)); - } - } - return true; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -193,35 +129,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool possibleBipartition(int n, vector>& dislikes) { - vector p(n); - iota(p.begin(), p.end(), 0); - unordered_map> g; - for (auto& e : dislikes) { - int a = e[0] - 1, b = e[1] - 1; - g[a].push_back(b); - g[b].push_back(a); - } - function find = [&](int x) -> int { - if (p[x] != x) p[x] = find(p[x]); - return p[x]; - }; - for (int i = 0; i < n; ++i) { - for (int j : g[i]) { - if (find(i) == find(j)) return false; - p[find(j)] = find(g[i][0]); - } - } - return true; - } -}; -``` - -### **Go** - ```go func possibleBipartition(n int, dislikes [][]int) bool { g := make([][]int, n) @@ -253,39 +160,6 @@ func possibleBipartition(n int, dislikes [][]int) bool { } ``` -```go -func possibleBipartition(n int, dislikes [][]int) bool { - p := make([]int, n) - g := make([][]int, n) - for i := range p { - p[i] = i - } - for _, e := range dislikes { - a, b := e[0]-1, e[1]-1 - g[a] = append(g[a], b) - g[b] = append(g[b], a) - } - var find func(int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - for i := 0; i < n; i++ { - for _, j := range g[i] { - if find(i) == find(j) { - return false - } - p[find(j)] = find(g[i][0]) - } - } - return true -} -``` - -### **TypeScript** - ```ts function possibleBipartition(n: number, dislikes: number[][]): boolean { const color = new Array(n + 1).fill(0); @@ -312,8 +186,6 @@ function possibleBipartition(n: number, dislikes: number[][]): boolean { } ``` -### **Rust** - ```rust impl Solution { fn dfs(i: usize, v: usize, color: &mut Vec, g: &Vec>) -> bool { @@ -345,10 +217,128 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + g = defaultdict(list) + for a, b in dislikes: + a, b = a - 1, b - 1 + g[a].append(b) + g[b].append(a) + p = list(range(n)) + for i in range(n): + for j in g[i]: + if find(i) == find(j): + return False + p[find(j)] = find(g[i][0]) + return True ``` +```java +class Solution { + private int[] p; + + public boolean possibleBipartition(int n, int[][] dislikes) { + p = new int[n]; + List[] g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int i = 0; i < n; ++i) { + p[i] = i; + } + for (var e : dislikes) { + int a = e[0] - 1, b = e[1] - 1; + g[a].add(b); + g[b].add(a); + } + for (int i = 0; i < n; ++i) { + for (int j : g[i]) { + if (find(i) == find(j)) { + return false; + } + p[find(j)] = find(g[i].get(0)); + } + } + return true; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} +``` + +```cpp +class Solution { +public: + bool possibleBipartition(int n, vector>& dislikes) { + vector p(n); + iota(p.begin(), p.end(), 0); + unordered_map> g; + for (auto& e : dislikes) { + int a = e[0] - 1, b = e[1] - 1; + g[a].push_back(b); + g[b].push_back(a); + } + function find = [&](int x) -> int { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + }; + for (int i = 0; i < n; ++i) { + for (int j : g[i]) { + if (find(i) == find(j)) return false; + p[find(j)] = find(g[i][0]); + } + } + return true; + } +}; +``` + +```go +func possibleBipartition(n int, dislikes [][]int) bool { + p := make([]int, n) + g := make([][]int, n) + for i := range p { + p[i] = i + } + for _, e := range dislikes { + a, b := e[0]-1, e[1]-1 + g[a] = append(g[a], b) + g[b] = append(g[b], a) + } + var find func(int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + for i := 0; i < n; i++ { + for _, j := range g[i] { + if find(i) == find(j) { + return false + } + p[find(j)] = find(g[i][0]) + } + } + return true +} ``` + + diff --git a/solution/0800-0899/0887.Super Egg Drop/README.md b/solution/0800-0899/0887.Super Egg Drop/README.md index a7394bab0d584..fe116b66697c3 100644 --- a/solution/0800-0899/0887.Super Egg Drop/README.md +++ b/solution/0800-0899/0887.Super Egg Drop/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:记忆化搜索 + 二分查找** +### 方法一:记忆化搜索 + 二分查找 我们设计一个函数 $dfs(i, j)$,表示有 $i$ 层楼以及 $j$ 个鸡蛋时,确定 $f$ 值的最小操作次数,那么答案就是 $dfs(n, k)$。 @@ -72,24 +70,8 @@ 时间复杂度 $O(n \times k \log n)$,空间复杂度 $O(n \times k)$。其中 $n$ 和 $k$ 分别是楼层数和鸡蛋数。 -**方法二:动态规划 + 二分查找** - -我们也可以使用动态规划的方法解决这个问题。 - -我们定义 $f[i][j]$ 表示有 $i$ 层楼以及 $j$ 个鸡蛋时,确定 $f$ 值的最小操作次数,那么答案就是 $f[n][k]$。 - -状态转移方程为 $f[i][j] = \min_{1 \le x \le i} \max(f[x - 1][j - 1], f[i - x][j]) + 1$。 - -与方法一类似,我们可以使用二分查找来优化 $x$ 的枚举过程。 - -时间复杂度 $O(n \times k \log n)$,空间复杂度 $O(n \times k)$。其中 $n$ 和 $k$ 分别是楼层数和鸡蛋数。 - -### **Python3** - - - ```python class Solution: def superEggDrop(self, k: int, n: int) -> int: @@ -113,30 +95,6 @@ class Solution: return dfs(n, k) ``` -```python -class Solution: - def superEggDrop(self, k: int, n: int) -> int: - f = [[0] * (k + 1) for _ in range(n + 1)] - for i in range(1, n + 1): - f[i][1] = i - for i in range(1, n + 1): - for j in range(2, k + 1): - l, r = 1, i - while l < r: - mid = (l + r + 1) >> 1 - a, b = f[mid - 1][j - 1], f[i - mid][j] - if a <= b: - l = mid - else: - r = mid - 1 - f[i][j] = max(f[l - 1][j - 1], f[i - l][j]) + 1 - return f[n][k] -``` - -### **Java** - - - ```java class Solution { private int[][] f; @@ -172,36 +130,6 @@ class Solution { } ``` -```java -class Solution { - public int superEggDrop(int k, int n) { - int[][] f = new int[n + 1][k + 1]; - for (int i = 1; i <= n; ++i) { - f[i][1] = i; - } - for (int i = 1; i <= n; ++i) { - for (int j = 2; j <= k; ++j) { - int l = 1, r = i; - while (l < r) { - int mid = (l + r + 1) >> 1; - int a = f[mid - 1][j - 1]; - int b = f[i - mid][j]; - if (a <= b) { - l = mid; - } else { - r = mid - 1; - } - } - f[i][j] = Math.max(f[l - 1][j - 1], f[i - l][j]) + 1; - } - } - return f[n][k]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -236,38 +164,6 @@ public: }; ``` -```cpp -class Solution { -public: - int superEggDrop(int k, int n) { - int f[n + 1][k + 1]; - memset(f, 0, sizeof(f)); - for (int i = 1; i <= n; ++i) { - f[i][1] = i; - } - for (int i = 1; i <= n; ++i) { - for (int j = 2; j <= k; ++j) { - int l = 1, r = i; - while (l < r) { - int mid = (l + r + 1) >> 1; - int a = f[mid - 1][j - 1]; - int b = f[i - mid][j]; - if (a <= b) { - l = mid; - } else { - r = mid - 1; - } - } - f[i][j] = max(f[l - 1][j - 1], f[i - l][j]) + 1; - } - } - return f[n][k]; - } -}; -``` - -### **Go** - ```go func superEggDrop(k int, n int) int { f := make([][]int, n+1) @@ -302,36 +198,6 @@ func superEggDrop(k int, n int) int { } ``` -```go -func superEggDrop(k int, n int) int { - f := make([][]int, n+1) - for i := range f { - f[i] = make([]int, k+1) - } - for i := 1; i <= n; i++ { - f[i][1] = i - } - for i := 1; i <= n; i++ { - for j := 2; j <= k; j++ { - l, r := 1, i - for l < r { - mid := (l + r + 1) >> 1 - a, b := f[mid-1][j-1], f[i-mid][j] - if a <= b { - l = mid - } else { - r = mid - 1 - } - } - f[i][j] = max(f[l-1][j-1], f[i-l][j]) + 1 - } - } - return f[n][k] -} -``` - -### **TypeScript** - ```ts function superEggDrop(k: number, n: number): number { const f: number[][] = new Array(n + 1).fill(0).map(() => new Array(k + 1).fill(0)); @@ -363,6 +229,128 @@ function superEggDrop(k: number, n: number): number { } ``` + + +### 方法二:动态规划 + 二分查找 + +我们也可以使用动态规划的方法解决这个问题。 + +我们定义 $f[i][j]$ 表示有 $i$ 层楼以及 $j$ 个鸡蛋时,确定 $f$ 值的最小操作次数,那么答案就是 $f[n][k]$。 + +状态转移方程为 $f[i][j] = \min_{1 \le x \le i} \max(f[x - 1][j - 1], f[i - x][j]) + 1$。 + +与方法一类似,我们可以使用二分查找来优化 $x$ 的枚举过程。 + +时间复杂度 $O(n \times k \log n)$,空间复杂度 $O(n \times k)$。其中 $n$ 和 $k$ 分别是楼层数和鸡蛋数。 + + + +```python +class Solution: + def superEggDrop(self, k: int, n: int) -> int: + f = [[0] * (k + 1) for _ in range(n + 1)] + for i in range(1, n + 1): + f[i][1] = i + for i in range(1, n + 1): + for j in range(2, k + 1): + l, r = 1, i + while l < r: + mid = (l + r + 1) >> 1 + a, b = f[mid - 1][j - 1], f[i - mid][j] + if a <= b: + l = mid + else: + r = mid - 1 + f[i][j] = max(f[l - 1][j - 1], f[i - l][j]) + 1 + return f[n][k] +``` + +```java +class Solution { + public int superEggDrop(int k, int n) { + int[][] f = new int[n + 1][k + 1]; + for (int i = 1; i <= n; ++i) { + f[i][1] = i; + } + for (int i = 1; i <= n; ++i) { + for (int j = 2; j <= k; ++j) { + int l = 1, r = i; + while (l < r) { + int mid = (l + r + 1) >> 1; + int a = f[mid - 1][j - 1]; + int b = f[i - mid][j]; + if (a <= b) { + l = mid; + } else { + r = mid - 1; + } + } + f[i][j] = Math.max(f[l - 1][j - 1], f[i - l][j]) + 1; + } + } + return f[n][k]; + } +} +``` + +```cpp +class Solution { +public: + int superEggDrop(int k, int n) { + int f[n + 1][k + 1]; + memset(f, 0, sizeof(f)); + for (int i = 1; i <= n; ++i) { + f[i][1] = i; + } + for (int i = 1; i <= n; ++i) { + for (int j = 2; j <= k; ++j) { + int l = 1, r = i; + while (l < r) { + int mid = (l + r + 1) >> 1; + int a = f[mid - 1][j - 1]; + int b = f[i - mid][j]; + if (a <= b) { + l = mid; + } else { + r = mid - 1; + } + } + f[i][j] = max(f[l - 1][j - 1], f[i - l][j]) + 1; + } + } + return f[n][k]; + } +}; +``` + +```go +func superEggDrop(k int, n int) int { + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, k+1) + } + for i := 1; i <= n; i++ { + f[i][1] = i + } + for i := 1; i <= n; i++ { + for j := 2; j <= k; j++ { + l, r := 1, i + for l < r { + mid := (l + r + 1) >> 1 + a, b := f[mid-1][j-1], f[i-mid][j] + if a <= b { + l = mid + } else { + r = mid - 1 + } + } + f[i][j] = max(f[l-1][j-1], f[i-l][j]) + 1 + } + } + return f[n][k] +} +``` + ```ts function superEggDrop(k: number, n: number): number { const f: number[][] = new Array(n + 1).fill(0).map(() => new Array(k + 1).fill(0)); @@ -390,10 +378,6 @@ function superEggDrop(k: number, n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0887.Super Egg Drop/README_EN.md b/solution/0800-0899/0887.Super Egg Drop/README_EN.md index d15ae3eebdbba..586fcbf7433cf 100644 --- a/solution/0800-0899/0887.Super Egg Drop/README_EN.md +++ b/solution/0800-0899/0887.Super Egg Drop/README_EN.md @@ -49,9 +49,9 @@ Hence, we need at minimum 2 moves to determine with certainty what the value of ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,28 +76,6 @@ class Solution: return dfs(n, k) ``` -```python -class Solution: - def superEggDrop(self, k: int, n: int) -> int: - f = [[0] * (k + 1) for _ in range(n + 1)] - for i in range(1, n + 1): - f[i][1] = i - for i in range(1, n + 1): - for j in range(2, k + 1): - l, r = 1, i - while l < r: - mid = (l + r + 1) >> 1 - a, b = f[mid - 1][j - 1], f[i - mid][j] - if a <= b: - l = mid - else: - r = mid - 1 - f[i][j] = max(f[l - 1][j - 1], f[i - l][j]) + 1 - return f[n][k] -``` - -### **Java** - ```java class Solution { private int[][] f; @@ -133,36 +111,6 @@ class Solution { } ``` -```java -class Solution { - public int superEggDrop(int k, int n) { - int[][] f = new int[n + 1][k + 1]; - for (int i = 1; i <= n; ++i) { - f[i][1] = i; - } - for (int i = 1; i <= n; ++i) { - for (int j = 2; j <= k; ++j) { - int l = 1, r = i; - while (l < r) { - int mid = (l + r + 1) >> 1; - int a = f[mid - 1][j - 1]; - int b = f[i - mid][j]; - if (a <= b) { - l = mid; - } else { - r = mid - 1; - } - } - f[i][j] = Math.max(f[l - 1][j - 1], f[i - l][j]) + 1; - } - } - return f[n][k]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -197,38 +145,6 @@ public: }; ``` -```cpp -class Solution { -public: - int superEggDrop(int k, int n) { - int f[n + 1][k + 1]; - memset(f, 0, sizeof(f)); - for (int i = 1; i <= n; ++i) { - f[i][1] = i; - } - for (int i = 1; i <= n; ++i) { - for (int j = 2; j <= k; ++j) { - int l = 1, r = i; - while (l < r) { - int mid = (l + r + 1) >> 1; - int a = f[mid - 1][j - 1]; - int b = f[i - mid][j]; - if (a <= b) { - l = mid; - } else { - r = mid - 1; - } - } - f[i][j] = max(f[l - 1][j - 1], f[i - l][j]) + 1; - } - } - return f[n][k]; - } -}; -``` - -### **Go** - ```go func superEggDrop(k int, n int) int { f := make([][]int, n+1) @@ -263,36 +179,6 @@ func superEggDrop(k int, n int) int { } ``` -```go -func superEggDrop(k int, n int) int { - f := make([][]int, n+1) - for i := range f { - f[i] = make([]int, k+1) - } - for i := 1; i <= n; i++ { - f[i][1] = i - } - for i := 1; i <= n; i++ { - for j := 2; j <= k; j++ { - l, r := 1, i - for l < r { - mid := (l + r + 1) >> 1 - a, b := f[mid-1][j-1], f[i-mid][j] - if a <= b { - l = mid - } else { - r = mid - 1 - } - } - f[i][j] = max(f[l-1][j-1], f[i-l][j]) + 1 - } - } - return f[n][k] -} -``` - -### **TypeScript** - ```ts function superEggDrop(k: number, n: number): number { const f: number[][] = new Array(n + 1).fill(0).map(() => new Array(k + 1).fill(0)); @@ -324,6 +210,118 @@ function superEggDrop(k: number, n: number): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def superEggDrop(self, k: int, n: int) -> int: + f = [[0] * (k + 1) for _ in range(n + 1)] + for i in range(1, n + 1): + f[i][1] = i + for i in range(1, n + 1): + for j in range(2, k + 1): + l, r = 1, i + while l < r: + mid = (l + r + 1) >> 1 + a, b = f[mid - 1][j - 1], f[i - mid][j] + if a <= b: + l = mid + else: + r = mid - 1 + f[i][j] = max(f[l - 1][j - 1], f[i - l][j]) + 1 + return f[n][k] +``` + +```java +class Solution { + public int superEggDrop(int k, int n) { + int[][] f = new int[n + 1][k + 1]; + for (int i = 1; i <= n; ++i) { + f[i][1] = i; + } + for (int i = 1; i <= n; ++i) { + for (int j = 2; j <= k; ++j) { + int l = 1, r = i; + while (l < r) { + int mid = (l + r + 1) >> 1; + int a = f[mid - 1][j - 1]; + int b = f[i - mid][j]; + if (a <= b) { + l = mid; + } else { + r = mid - 1; + } + } + f[i][j] = Math.max(f[l - 1][j - 1], f[i - l][j]) + 1; + } + } + return f[n][k]; + } +} +``` + +```cpp +class Solution { +public: + int superEggDrop(int k, int n) { + int f[n + 1][k + 1]; + memset(f, 0, sizeof(f)); + for (int i = 1; i <= n; ++i) { + f[i][1] = i; + } + for (int i = 1; i <= n; ++i) { + for (int j = 2; j <= k; ++j) { + int l = 1, r = i; + while (l < r) { + int mid = (l + r + 1) >> 1; + int a = f[mid - 1][j - 1]; + int b = f[i - mid][j]; + if (a <= b) { + l = mid; + } else { + r = mid - 1; + } + } + f[i][j] = max(f[l - 1][j - 1], f[i - l][j]) + 1; + } + } + return f[n][k]; + } +}; +``` + +```go +func superEggDrop(k int, n int) int { + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, k+1) + } + for i := 1; i <= n; i++ { + f[i][1] = i + } + for i := 1; i <= n; i++ { + for j := 2; j <= k; j++ { + l, r := 1, i + for l < r { + mid := (l + r + 1) >> 1 + a, b := f[mid-1][j-1], f[i-mid][j] + if a <= b { + l = mid + } else { + r = mid - 1 + } + } + f[i][j] = max(f[l-1][j-1], f[i-l][j]) + 1 + } + } + return f[n][k] +} +``` + ```ts function superEggDrop(k: number, n: number): number { const f: number[][] = new Array(n + 1).fill(0).map(() => new Array(k + 1).fill(0)); @@ -351,10 +349,6 @@ function superEggDrop(k: number, n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0888.Fair Candy Swap/README.md b/solution/0800-0899/0888.Fair Candy Swap/README.md index c76afa93bdf61..d4d3bdf478273 100644 --- a/solution/0800-0899/0888.Fair Candy Swap/README.md +++ b/solution/0800-0899/0888.Fair Candy Swap/README.md @@ -55,16 +55,10 @@ ## 解法 - - -哈希表实现。 +### 方法一 -### **Python3** - - - ```python class Solution: def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]: @@ -76,10 +70,6 @@ class Solution: return [a, target] ``` -### **Java** - - - ```java class Solution { public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) { @@ -104,24 +94,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function fairCandySwap(aliceSizes: number[], bobSizes: number[]): number[] { - let s1 = aliceSizes.reduce((a, c) => a + c, 0); - let s2 = bobSizes.reduce((a, c) => a + c, 0); - let diff = (s1 - s2) >> 1; - for (let num of aliceSizes) { - let target = num - diff; - if (bobSizes.includes(target)) { - return [num, target]; - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -143,10 +115,20 @@ public: }; ``` -### **...** - -``` - +```ts +function fairCandySwap(aliceSizes: number[], bobSizes: number[]): number[] { + let s1 = aliceSizes.reduce((a, c) => a + c, 0); + let s2 = bobSizes.reduce((a, c) => a + c, 0); + let diff = (s1 - s2) >> 1; + for (let num of aliceSizes) { + let target = num - diff; + if (bobSizes.includes(target)) { + return [num, target]; + } + } +} ``` + + diff --git a/solution/0800-0899/0888.Fair Candy Swap/README_EN.md b/solution/0800-0899/0888.Fair Candy Swap/README_EN.md index 4198a6da33948..1b36f3355dc30 100644 --- a/solution/0800-0899/0888.Fair Candy Swap/README_EN.md +++ b/solution/0800-0899/0888.Fair Candy Swap/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return [a, target] ``` -### **Java** - ```java class Solution { public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) { @@ -85,24 +83,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function fairCandySwap(aliceSizes: number[], bobSizes: number[]): number[] { - let s1 = aliceSizes.reduce((a, c) => a + c, 0); - let s2 = bobSizes.reduce((a, c) => a + c, 0); - let diff = (s1 - s2) >> 1; - for (let num of aliceSizes) { - let target = num - diff; - if (bobSizes.includes(target)) { - return [num, target]; - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -124,10 +104,20 @@ public: }; ``` -### **...** - -``` - +```ts +function fairCandySwap(aliceSizes: number[], bobSizes: number[]): number[] { + let s1 = aliceSizes.reduce((a, c) => a + c, 0); + let s2 = bobSizes.reduce((a, c) => a + c, 0); + let diff = (s1 - s2) >> 1; + for (let num of aliceSizes) { + let target = num - diff; + if (bobSizes.includes(target)) { + return [num, target]; + } + } +} ``` + + diff --git a/solution/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/README.md b/solution/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/README.md index 6760c7ca26511..c8dd9cfb4dc44 100644 --- a/solution/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/README.md +++ b/solution/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 1. 以 preorder 的第一个元素或 postorder 的最后一个元素为根节点的值。 2. 以 preorder 的第二个元素作为左子树的根节点,在 postorder 中找到该元素的索引 i,然后基于索引 i 可以计算出左右子树的长度。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -86,45 +80,6 @@ class Solution: return root ``` -### **Go** - - - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func constructFromPrePost(preorder []int, postorder []int) *TreeNode { - postMap := make(map[int]int) - for index, v := range postorder { - postMap[v] = index - } - var dfs func(prel, prer, postl, postr int) *TreeNode - dfs = func(prel, prer, postl, postr int) *TreeNode { - if prel > prer { - return nil - } - root := &TreeNode{Val: preorder[prel]} - if prel == prer { - return root - } - leftRootIndex := postMap[preorder[prel+1]] - leftLength := leftRootIndex - postl + 1 - root.Left = dfs(prel+1, prel+leftLength, postl, leftRootIndex) - root.Right = dfs(prel+leftLength+1, prer, leftRootIndex+1, postr-1) - return root - } - return dfs(0, len(preorder)-1, 0, len(postorder)-1) -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -160,10 +115,39 @@ public: }; ``` -### **...** - -``` - +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func constructFromPrePost(preorder []int, postorder []int) *TreeNode { + postMap := make(map[int]int) + for index, v := range postorder { + postMap[v] = index + } + var dfs func(prel, prer, postl, postr int) *TreeNode + dfs = func(prel, prer, postl, postr int) *TreeNode { + if prel > prer { + return nil + } + root := &TreeNode{Val: preorder[prel]} + if prel == prer { + return root + } + leftRootIndex := postMap[preorder[prel+1]] + leftLength := leftRootIndex - postl + 1 + root.Left = dfs(prel+1, prel+leftLength, postl, leftRootIndex) + root.Right = dfs(prel+leftLength+1, prer, leftRootIndex+1, postr-1) + return root + } + return dfs(0, len(preorder)-1, 0, len(postorder)-1) +} ``` + + diff --git a/solution/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/README_EN.md b/solution/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/README_EN.md index fea450787b0f7..f98dbacf875df 100644 --- a/solution/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/README_EN.md +++ b/solution/0800-0899/0889.Construct Binary Tree from Preorder and Postorder Traversal/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -70,45 +70,6 @@ class Solution: return root ``` -### **Go** - - - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func constructFromPrePost(preorder []int, postorder []int) *TreeNode { - postMap := make(map[int]int) - for index, v := range postorder { - postMap[v] = index - } - var dfs func(prel, prer, postl, postr int) *TreeNode - dfs = func(prel, prer, postl, postr int) *TreeNode { - if prel > prer { - return nil - } - root := &TreeNode{Val: preorder[prel]} - if prel == prer { - return root - } - leftRootIndex := postMap[preorder[prel+1]] - leftLength := leftRootIndex - postl + 1 - root.Left = dfs(prel+1, prel+leftLength, postl, leftRootIndex) - root.Right = dfs(prel+leftLength+1, prer, leftRootIndex+1, postr-1) - return root - } - return dfs(0, len(preorder)-1, 0, len(postorder)-1) -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -144,10 +105,39 @@ public: }; ``` -### **...** - -``` - +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func constructFromPrePost(preorder []int, postorder []int) *TreeNode { + postMap := make(map[int]int) + for index, v := range postorder { + postMap[v] = index + } + var dfs func(prel, prer, postl, postr int) *TreeNode + dfs = func(prel, prer, postl, postr int) *TreeNode { + if prel > prer { + return nil + } + root := &TreeNode{Val: preorder[prel]} + if prel == prer { + return root + } + leftRootIndex := postMap[preorder[prel+1]] + leftLength := leftRootIndex - postl + 1 + root.Left = dfs(prel+1, prel+leftLength, postl, leftRootIndex) + root.Right = dfs(prel+leftLength+1, prer, leftRootIndex+1, postr-1) + return root + } + return dfs(0, len(preorder)-1, 0, len(postorder)-1) +} ``` + + diff --git a/solution/0800-0899/0890.Find and Replace Pattern/README.md b/solution/0800-0899/0890.Find and Replace Pattern/README.md index c2528ba244cdc..37163d5546fbd 100644 --- a/solution/0800-0899/0890.Find and Replace Pattern/README.md +++ b/solution/0800-0899/0890.Find and Replace Pattern/README.md @@ -38,16 +38,10 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 -### **Python3** - - - ```python class Solution: def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]: @@ -62,10 +56,6 @@ class Solution: return [word for word in words if match(word, pattern)] ``` -### **Java** - - - ```java class Solution { public List findAndReplacePattern(String[] words, String pattern) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func findAndReplacePattern(words []string, pattern string) []string { match := func(s, t string) bool { @@ -144,8 +130,6 @@ func findAndReplacePattern(words []string, pattern string) []string { } ``` -### **TypeScript** - ```ts function findAndReplacePattern(words: string[], pattern: string): string[] { return words.filter(word => { @@ -163,8 +147,6 @@ function findAndReplacePattern(words: string[], pattern: string): string[] { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -191,10 +173,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0890.Find and Replace Pattern/README_EN.md b/solution/0800-0899/0890.Find and Replace Pattern/README_EN.md index 4fd020f23e19b..78a11358a5c47 100644 --- a/solution/0800-0899/0890.Find and Replace Pattern/README_EN.md +++ b/solution/0800-0899/0890.Find and Replace Pattern/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return [word for word in words if match(word, pattern)] ``` -### **Java** - ```java class Solution { public List findAndReplacePattern(String[] words, String pattern) { @@ -88,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func findAndReplacePattern(words []string, pattern string) []string { match := func(s, t string) bool { @@ -137,8 +131,6 @@ func findAndReplacePattern(words []string, pattern string) []string { } ``` -### **TypeScript** - ```ts function findAndReplacePattern(words: string[], pattern: string): string[] { return words.filter(word => { @@ -156,8 +148,6 @@ function findAndReplacePattern(words: string[], pattern: string): string[] { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -184,10 +174,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0891.Sum of Subsequence Widths/README.md b/solution/0800-0899/0891.Sum of Subsequence Widths/README.md index a683b83a522fa..dbf0191402c9d 100644 --- a/solution/0800-0899/0891.Sum of Subsequence Widths/README.md +++ b/solution/0800-0899/0891.Sum of Subsequence Widths/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:排序 + 枚举元素计算贡献** +### 方法一:排序 + 枚举元素计算贡献 题目求解的是数组 `nums` 中所有子序列中最大值与最小值差值之和,注意到“子序列”,并且涉及到“最大值”与“最小值”,我们考虑先对数组 `nums` 进行排序。 @@ -96,10 +94,6 @@ $$ -### **Python3** - - - ```python class Solution: def sumSubseqWidths(self, nums: List[int]) -> int: @@ -112,10 +106,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func sumSubseqWidths(nums []int) (ans int) { const mod int = 1e9 + 7 @@ -168,10 +154,6 @@ func sumSubseqWidths(nums []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0891.Sum of Subsequence Widths/README_EN.md b/solution/0800-0899/0891.Sum of Subsequence Widths/README_EN.md index ea45c23f353ed..94dae0f48ae46 100644 --- a/solution/0800-0899/0891.Sum of Subsequence Widths/README_EN.md +++ b/solution/0800-0899/0891.Sum of Subsequence Widths/README_EN.md @@ -38,9 +38,9 @@ The sum of these widths is 6. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -73,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +89,6 @@ public: }; ``` -### **Go** - ```go func sumSubseqWidths(nums []int) (ans int) { const mod int = 1e9 + 7 @@ -108,10 +102,6 @@ func sumSubseqWidths(nums []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0892.Surface Area of 3D Shapes/README.md b/solution/0800-0899/0892.Surface Area of 3D Shapes/README.md index a99feda2d0f3c..2352174c4affb 100644 --- a/solution/0800-0899/0892.Surface Area of 3D Shapes/README.md +++ b/solution/0800-0899/0892.Surface Area of 3D Shapes/README.md @@ -53,18 +53,12 @@ ## 解法 - - -**方法一:遍历,逐个累加** +### 方法一:遍历,逐个累加 时间复杂度 $O(n^2)$,空间复杂度 $O(1)$。 -### **Python3** - - - ```python class Solution: def surfaceArea(self, grid: List[List[int]]) -> int: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int surfaceArea(int[][] grid) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func surfaceArea(grid [][]int) int { ans := 0 @@ -151,10 +137,6 @@ func surfaceArea(grid [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0892.Surface Area of 3D Shapes/README_EN.md b/solution/0800-0899/0892.Surface Area of 3D Shapes/README_EN.md index da07835aa90d9..b97e0788d5e29 100644 --- a/solution/0800-0899/0892.Surface Area of 3D Shapes/README_EN.md +++ b/solution/0800-0899/0892.Surface Area of 3D Shapes/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int surfaceArea(int[][] grid) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +107,6 @@ public: }; ``` -### **Go** - ```go func surfaceArea(grid [][]int) int { ans := 0 @@ -133,10 +127,6 @@ func surfaceArea(grid [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0893.Groups of Special-Equivalent Strings/README.md b/solution/0800-0899/0893.Groups of Special-Equivalent Strings/README.md index f7eced35e3ba4..2f843100af732 100644 --- a/solution/0800-0899/0893.Groups of Special-Equivalent Strings/README.md +++ b/solution/0800-0899/0893.Groups of Special-Equivalent Strings/README.md @@ -61,14 +61,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def numSpecialEquivGroups(self, words: List[str]) -> int: @@ -76,10 +72,6 @@ class Solution: return len(s) ``` -### **Java** - - - ```java class Solution { public int numSpecialEquivGroups(String[] words) { @@ -115,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +129,6 @@ public: }; ``` -### **Go** - ```go func numSpecialEquivGroups(words []string) int { s := map[string]bool{} @@ -165,10 +153,6 @@ func numSpecialEquivGroups(words []string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0893.Groups of Special-Equivalent Strings/README_EN.md b/solution/0800-0899/0893.Groups of Special-Equivalent Strings/README_EN.md index e96a1668839a6..6ff08ed420293 100644 --- a/solution/0800-0899/0893.Groups of Special-Equivalent Strings/README_EN.md +++ b/solution/0800-0899/0893.Groups of Special-Equivalent Strings/README_EN.md @@ -54,9 +54,9 @@ Note that in particular, "zzxy" is not special equivalent to "zzy ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return len(s) ``` -### **Java** - ```java class Solution { public int numSpecialEquivGroups(String[] words) { @@ -102,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +122,6 @@ public: }; ``` -### **Go** - ```go func numSpecialEquivGroups(words []string) int { s := map[string]bool{} @@ -152,10 +146,6 @@ func numSpecialEquivGroups(words []string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0894.All Possible Full Binary Trees/README.md b/solution/0800-0899/0894.All Possible Full Binary Trees/README.md index d56b0d1cc8b3b..eac91f8655b85 100644 --- a/solution/0800-0899/0894.All Possible Full Binary Trees/README.md +++ b/solution/0800-0899/0894.All Possible Full Binary Trees/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 如果 $n=1$,直接返回单个节点的列表。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -80,10 +74,6 @@ class Solution: return dfs(n) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -170,7 +158,80 @@ public: }; ``` -### **Rust** +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func allPossibleFBT(n int) []*TreeNode { + f := make([][]*TreeNode, n+1) + var dfs func(int) []*TreeNode + dfs = func(n int) []*TreeNode { + if len(f[n]) > 0 { + return f[n] + } + if n == 1 { + return []*TreeNode{&TreeNode{Val: 0}} + } + ans := []*TreeNode{} + for i := 0; i < n-1; i++ { + j := n - 1 - i + for _, left := range dfs(i) { + for _, right := range dfs(j) { + ans = append(ans, &TreeNode{0, left, right}) + } + } + } + f[n] = ans + return ans + } + return dfs(n) +} +``` + +```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 allPossibleFBT(n: number): Array { + const f: Array> = new Array(n + 1).fill(0).map(() => []); + const dfs = (n: number): Array => { + if (f[n].length) { + return f[n]; + } + if (n === 1) { + f[n].push(new TreeNode(0)); + return f[n]; + } + const ans: Array = []; + for (let i = 0; i < n - 1; ++i) { + const j = n - 1 - i; + for (const left of dfs(i)) { + for (const right of dfs(j)) { + ans.push(new TreeNode(0, left, right)); + } + } + } + return (f[n] = ans); + }; + return dfs(n); +} +``` ```rust // Definition for a binary tree node. @@ -254,89 +315,6 @@ impl Solution { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func allPossibleFBT(n int) []*TreeNode { - f := make([][]*TreeNode, n+1) - var dfs func(int) []*TreeNode - dfs = func(n int) []*TreeNode { - if len(f[n]) > 0 { - return f[n] - } - if n == 1 { - return []*TreeNode{&TreeNode{Val: 0}} - } - ans := []*TreeNode{} - for i := 0; i < n-1; i++ { - j := n - 1 - i - for _, left := range dfs(i) { - for _, right := range dfs(j) { - ans = append(ans, &TreeNode{0, left, right}) - } - } - } - f[n] = ans - return ans - } - return dfs(n) -} -``` - -### **TypeScript** - -```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 allPossibleFBT(n: number): Array { - const f: Array> = new Array(n + 1).fill(0).map(() => []); - const dfs = (n: number): Array => { - if (f[n].length) { - return f[n]; - } - if (n === 1) { - f[n].push(new TreeNode(0)); - return f[n]; - } - const ans: Array = []; - for (let i = 0; i < n - 1; ++i) { - const j = n - 1 - i; - for (const left of dfs(i)) { - for (const right of dfs(j)) { - ans.push(new TreeNode(0, left, right)); - } - } - } - return (f[n] = ans); - }; - return dfs(n); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0894.All Possible Full Binary Trees/README_EN.md b/solution/0800-0899/0894.All Possible Full Binary Trees/README_EN.md index ef4a244348981..cb24d208645cd 100644 --- a/solution/0800-0899/0894.All Possible Full Binary Trees/README_EN.md +++ b/solution/0800-0899/0894.All Possible Full Binary Trees/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -62,8 +62,6 @@ class Solution: return dfs(n) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -109,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -150,7 +146,80 @@ public: }; ``` -### **Rust** +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func allPossibleFBT(n int) []*TreeNode { + f := make([][]*TreeNode, n+1) + var dfs func(int) []*TreeNode + dfs = func(n int) []*TreeNode { + if len(f[n]) > 0 { + return f[n] + } + if n == 1 { + return []*TreeNode{&TreeNode{Val: 0}} + } + ans := []*TreeNode{} + for i := 0; i < n-1; i++ { + j := n - 1 - i + for _, left := range dfs(i) { + for _, right := range dfs(j) { + ans = append(ans, &TreeNode{0, left, right}) + } + } + } + f[n] = ans + return ans + } + return dfs(n) +} +``` + +```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 allPossibleFBT(n: number): Array { + const f: Array> = new Array(n + 1).fill(0).map(() => []); + const dfs = (n: number): Array => { + if (f[n].length) { + return f[n]; + } + if (n === 1) { + f[n].push(new TreeNode(0)); + return f[n]; + } + const ans: Array = []; + for (let i = 0; i < n - 1; ++i) { + const j = n - 1 - i; + for (const left of dfs(i)) { + for (const right of dfs(j)) { + ans.push(new TreeNode(0, left, right)); + } + } + } + return (f[n] = ans); + }; + return dfs(n); +} +``` ```rust // Definition for a binary tree node. @@ -234,89 +303,6 @@ impl Solution { } ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func allPossibleFBT(n int) []*TreeNode { - f := make([][]*TreeNode, n+1) - var dfs func(int) []*TreeNode - dfs = func(n int) []*TreeNode { - if len(f[n]) > 0 { - return f[n] - } - if n == 1 { - return []*TreeNode{&TreeNode{Val: 0}} - } - ans := []*TreeNode{} - for i := 0; i < n-1; i++ { - j := n - 1 - i - for _, left := range dfs(i) { - for _, right := range dfs(j) { - ans = append(ans, &TreeNode{0, left, right}) - } - } - } - f[n] = ans - return ans - } - return dfs(n) -} -``` - -### **TypeScript** - -```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 allPossibleFBT(n: number): Array { - const f: Array> = new Array(n + 1).fill(0).map(() => []); - const dfs = (n: number): Array => { - if (f[n].length) { - return f[n]; - } - if (n === 1) { - f[n].push(new TreeNode(0)); - return f[n]; - } - const ans: Array = []; - for (let i = 0; i < n - 1; ++i) { - const j = n - 1 - i; - for (const left of dfs(i)) { - for (const right of dfs(j)) { - ans.push(new TreeNode(0, left, right)); - } - } - } - return (f[n] = ans); - }; - return dfs(n); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0895.Maximum Frequency Stack/README.md b/solution/0800-0899/0895.Maximum Frequency Stack/README.md index 54582afc961e7..96ef6e893d6d8 100644 --- a/solution/0800-0899/0895.Maximum Frequency Stack/README.md +++ b/solution/0800-0899/0895.Maximum Frequency Stack/README.md @@ -54,9 +54,7 @@ freqStack.pop ();//返回 4 ,因为 4, 5 和 7 出现频率最高,但 4 是 ## 解法 - - -**方法一:哈希表 + 优先队列(大根堆)** +### 方法一:哈希表 + 优先队列(大根堆) 根据题目描述,我们需要设计一个支持弹出“出现频率最高”的元素的数据结构。如果存在多个元素出现频率相同,那么弹出最接近栈顶的元素。 @@ -66,22 +64,8 @@ freqStack.pop ();//返回 4 ,因为 4, 5 和 7 出现频率最高,但 4 是 执行弹栈操作时,我们直接从优先队列 $q$ 中弹出一个元素即可。由于优先队列 $q$ 中的元素按照频率降序排序,因此弹出的元素一定是出现频率最高的元素。如果存在多个元素出现频率相同,那么弹出最接近栈顶的元素,即弹出时间戳最大的元素。弹出后,我们将弹出元素的频率减一,即 $cnt[val] \gets cnt[val] - 1$。弹栈操作的时间复杂度为 $O(\log n)$。 -**方法二:双哈希表** - -在方法一中,为了能弹出符合要求的元素,我们维护了一个优先队列,每次都需要对优先队列进行操作,时间复杂度为 $O(\log n)$。如果我们能够在 $O(1)$ 的时间内找到符合要求的元素,那么整个数据结构每次操作的时间复杂度就可以降低到 $O(1)$。 - -实际上,我们可以用一个变量 $mx$ 记录当前出现频率的最大值,用一个哈希表 $d$ 记录每个出现频率对应的元素列表,与方法一相同,用一个哈希表 $cnt$ 记录每个元素出现的频率。 - -执行压栈操作时,我们将元素的频率加一,即 $cnt[val] \gets cnt[val] + 1$,然后将元素 $val$ 加入哈希表 $d$ 中对应的频率列表中,即 $d[cnt[val]].push(val)$。如果当前元素的频率大于 $mx$,则更新 $mx$,即 $mx \gets cnt[val]$。压栈操作的时间复杂度为 $O(1)$。 - -执行弹栈操作时,我们从哈希表 $d$ 中取出频率为 $mx$ 的元素列表,弹出列表中的最后一个元素 $val$,然后将 $val$ 从哈希表 $d$ 中移除,即 $d[mx].pop()$。最后将 $val$ 的频率减一,即 $cnt[val] \gets cnt[val] - 1$。如果 $d[mx]$ 列表为空,说明当前出现频率最大的元素已经全部弹出,我们需要将 $mx$ 减一,即 $mx \gets mx - 1$。弹栈操作的时间复杂度为 $O(1)$。 - -### **Python3** - - - ```python class FreqStack: def __init__(self): @@ -106,36 +90,6 @@ class FreqStack: # param_2 = obj.pop() ``` -```python -class FreqStack: - def __init__(self): - self.cnt = defaultdict(int) - self.d = defaultdict(list) - self.mx = 0 - - def push(self, val: int) -> None: - self.cnt[val] += 1 - self.d[self.cnt[val]].append(val) - self.mx = max(self.mx, self.cnt[val]) - - def pop(self) -> int: - val = self.d[self.mx].pop() - self.cnt[val] -= 1 - if not self.d[self.mx]: - self.mx -= 1 - return val - - -# Your FreqStack object will be instantiated and called as such: -# obj = FreqStack() -# obj.push(val) -# param_2 = obj.pop() -``` - -### **Java** - - - ```java class FreqStack { private Map cnt = new HashMap<>(); @@ -166,42 +120,6 @@ class FreqStack { */ ``` -```java -class FreqStack { - private Map cnt = new HashMap<>(); - private Map> d = new HashMap<>(); - private int mx; - - public FreqStack() { - } - - public void push(int val) { - cnt.put(val, cnt.getOrDefault(val, 0) + 1); - int t = cnt.get(val); - d.computeIfAbsent(t, k -> new ArrayDeque<>()).push(val); - mx = Math.max(mx, t); - } - - public int pop() { - int val = d.get(mx).pop(); - cnt.put(val, cnt.get(val) - 1); - if (d.get(mx).isEmpty()) { - --mx; - } - return val; - } -} - -/** - * Your FreqStack object will be instantiated and called as such: - * FreqStack obj = new FreqStack(); - * obj.push(val); - * int param_2 = obj.pop(); - */ -``` - -### **C++** - ```cpp class FreqStack { public: @@ -234,42 +152,6 @@ private: */ ``` -```cpp -class FreqStack { -public: - FreqStack() { - } - - void push(int val) { - ++cnt[val]; - d[cnt[val]].push(val); - mx = max(mx, cnt[val]); - } - - int pop() { - int val = d[mx].top(); - --cnt[val]; - d[mx].pop(); - if (d[mx].empty()) --mx; - return val; - } - -private: - unordered_map cnt; - unordered_map> d; - int mx = 0; -}; - -/** - * Your FreqStack object will be instantiated and called as such: - * FreqStack* obj = new FreqStack(); - * obj->push(val); - * int param_2 = obj->pop(); - */ -``` - -### **Go** - ```go type FreqStack struct { cnt map[int]int @@ -312,6 +194,114 @@ func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; retur */ ``` + + +### 方法二:双哈希表 + +在方法一中,为了能弹出符合要求的元素,我们维护了一个优先队列,每次都需要对优先队列进行操作,时间复杂度为 $O(\log n)$。如果我们能够在 $O(1)$ 的时间内找到符合要求的元素,那么整个数据结构每次操作的时间复杂度就可以降低到 $O(1)$。 + +实际上,我们可以用一个变量 $mx$ 记录当前出现频率的最大值,用一个哈希表 $d$ 记录每个出现频率对应的元素列表,与方法一相同,用一个哈希表 $cnt$ 记录每个元素出现的频率。 + +执行压栈操作时,我们将元素的频率加一,即 $cnt[val] \gets cnt[val] + 1$,然后将元素 $val$ 加入哈希表 $d$ 中对应的频率列表中,即 $d[cnt[val]].push(val)$。如果当前元素的频率大于 $mx$,则更新 $mx$,即 $mx \gets cnt[val]$。压栈操作的时间复杂度为 $O(1)$。 + +执行弹栈操作时,我们从哈希表 $d$ 中取出频率为 $mx$ 的元素列表,弹出列表中的最后一个元素 $val$,然后将 $val$ 从哈希表 $d$ 中移除,即 $d[mx].pop()$。最后将 $val$ 的频率减一,即 $cnt[val] \gets cnt[val] - 1$。如果 $d[mx]$ 列表为空,说明当前出现频率最大的元素已经全部弹出,我们需要将 $mx$ 减一,即 $mx \gets mx - 1$。弹栈操作的时间复杂度为 $O(1)$。 + + + +```python +class FreqStack: + def __init__(self): + self.cnt = defaultdict(int) + self.d = defaultdict(list) + self.mx = 0 + + def push(self, val: int) -> None: + self.cnt[val] += 1 + self.d[self.cnt[val]].append(val) + self.mx = max(self.mx, self.cnt[val]) + + def pop(self) -> int: + val = self.d[self.mx].pop() + self.cnt[val] -= 1 + if not self.d[self.mx]: + self.mx -= 1 + return val + + +# Your FreqStack object will be instantiated and called as such: +# obj = FreqStack() +# obj.push(val) +# param_2 = obj.pop() +``` + +```java +class FreqStack { + private Map cnt = new HashMap<>(); + private Map> d = new HashMap<>(); + private int mx; + + public FreqStack() { + } + + public void push(int val) { + cnt.put(val, cnt.getOrDefault(val, 0) + 1); + int t = cnt.get(val); + d.computeIfAbsent(t, k -> new ArrayDeque<>()).push(val); + mx = Math.max(mx, t); + } + + public int pop() { + int val = d.get(mx).pop(); + cnt.put(val, cnt.get(val) - 1); + if (d.get(mx).isEmpty()) { + --mx; + } + return val; + } +} + +/** + * Your FreqStack object will be instantiated and called as such: + * FreqStack obj = new FreqStack(); + * obj.push(val); + * int param_2 = obj.pop(); + */ +``` + +```cpp +class FreqStack { +public: + FreqStack() { + } + + void push(int val) { + ++cnt[val]; + d[cnt[val]].push(val); + mx = max(mx, cnt[val]); + } + + int pop() { + int val = d[mx].top(); + --cnt[val]; + d[mx].pop(); + if (d[mx].empty()) --mx; + return val; + } + +private: + unordered_map cnt; + unordered_map> d; + int mx = 0; +}; + +/** + * Your FreqStack object will be instantiated and called as such: + * FreqStack* obj = new FreqStack(); + * obj->push(val); + * int param_2 = obj->pop(); + */ +``` + ```go type FreqStack struct { cnt map[int]int @@ -347,10 +337,6 @@ func (this *FreqStack) Pop() int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0895.Maximum Frequency Stack/README_EN.md b/solution/0800-0899/0895.Maximum Frequency Stack/README_EN.md index 8b572aacde013..9007c4c67ee77 100644 --- a/solution/0800-0899/0895.Maximum Frequency Stack/README_EN.md +++ b/solution/0800-0899/0895.Maximum Frequency Stack/README_EN.md @@ -53,9 +53,9 @@ freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is clo ## Solutions - +### Solution 1 -### **Python3** + ```python class FreqStack: @@ -81,34 +81,6 @@ class FreqStack: # param_2 = obj.pop() ``` -```python -class FreqStack: - def __init__(self): - self.cnt = defaultdict(int) - self.d = defaultdict(list) - self.mx = 0 - - def push(self, val: int) -> None: - self.cnt[val] += 1 - self.d[self.cnt[val]].append(val) - self.mx = max(self.mx, self.cnt[val]) - - def pop(self) -> int: - val = self.d[self.mx].pop() - self.cnt[val] -= 1 - if not self.d[self.mx]: - self.mx -= 1 - return val - - -# Your FreqStack object will be instantiated and called as such: -# obj = FreqStack() -# obj.push(val) -# param_2 = obj.pop() -``` - -### **Java** - ```java class FreqStack { private Map cnt = new HashMap<>(); @@ -139,42 +111,6 @@ class FreqStack { */ ``` -```java -class FreqStack { - private Map cnt = new HashMap<>(); - private Map> d = new HashMap<>(); - private int mx; - - public FreqStack() { - } - - public void push(int val) { - cnt.put(val, cnt.getOrDefault(val, 0) + 1); - int t = cnt.get(val); - d.computeIfAbsent(t, k -> new ArrayDeque<>()).push(val); - mx = Math.max(mx, t); - } - - public int pop() { - int val = d.get(mx).pop(); - cnt.put(val, cnt.get(val) - 1); - if (d.get(mx).isEmpty()) { - --mx; - } - return val; - } -} - -/** - * Your FreqStack object will be instantiated and called as such: - * FreqStack obj = new FreqStack(); - * obj.push(val); - * int param_2 = obj.pop(); - */ -``` - -### **C++** - ```cpp class FreqStack { public: @@ -207,42 +143,6 @@ private: */ ``` -```cpp -class FreqStack { -public: - FreqStack() { - } - - void push(int val) { - ++cnt[val]; - d[cnt[val]].push(val); - mx = max(mx, cnt[val]); - } - - int pop() { - int val = d[mx].top(); - --cnt[val]; - d[mx].pop(); - if (d[mx].empty()) --mx; - return val; - } - -private: - unordered_map cnt; - unordered_map> d; - int mx = 0; -}; - -/** - * Your FreqStack object will be instantiated and called as such: - * FreqStack* obj = new FreqStack(); - * obj->push(val); - * int param_2 = obj->pop(); - */ -``` - -### **Go** - ```go type FreqStack struct { cnt map[int]int @@ -285,6 +185,106 @@ func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; retur */ ``` + + +### Solution 2 + + + +```python +class FreqStack: + def __init__(self): + self.cnt = defaultdict(int) + self.d = defaultdict(list) + self.mx = 0 + + def push(self, val: int) -> None: + self.cnt[val] += 1 + self.d[self.cnt[val]].append(val) + self.mx = max(self.mx, self.cnt[val]) + + def pop(self) -> int: + val = self.d[self.mx].pop() + self.cnt[val] -= 1 + if not self.d[self.mx]: + self.mx -= 1 + return val + + +# Your FreqStack object will be instantiated and called as such: +# obj = FreqStack() +# obj.push(val) +# param_2 = obj.pop() +``` + +```java +class FreqStack { + private Map cnt = new HashMap<>(); + private Map> d = new HashMap<>(); + private int mx; + + public FreqStack() { + } + + public void push(int val) { + cnt.put(val, cnt.getOrDefault(val, 0) + 1); + int t = cnt.get(val); + d.computeIfAbsent(t, k -> new ArrayDeque<>()).push(val); + mx = Math.max(mx, t); + } + + public int pop() { + int val = d.get(mx).pop(); + cnt.put(val, cnt.get(val) - 1); + if (d.get(mx).isEmpty()) { + --mx; + } + return val; + } +} + +/** + * Your FreqStack object will be instantiated and called as such: + * FreqStack obj = new FreqStack(); + * obj.push(val); + * int param_2 = obj.pop(); + */ +``` + +```cpp +class FreqStack { +public: + FreqStack() { + } + + void push(int val) { + ++cnt[val]; + d[cnt[val]].push(val); + mx = max(mx, cnt[val]); + } + + int pop() { + int val = d[mx].top(); + --cnt[val]; + d[mx].pop(); + if (d[mx].empty()) --mx; + return val; + } + +private: + unordered_map cnt; + unordered_map> d; + int mx = 0; +}; + +/** + * Your FreqStack object will be instantiated and called as such: + * FreqStack* obj = new FreqStack(); + * obj->push(val); + * int param_2 = obj->pop(); + */ +``` + ```go type FreqStack struct { cnt map[int]int @@ -320,10 +320,6 @@ func (this *FreqStack) Pop() int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0896.Monotonic Array/README.md b/solution/0800-0899/0896.Monotonic Array/README.md index 3fdbed747b453..e9300875a3541 100644 --- a/solution/0800-0899/0896.Monotonic Array/README.md +++ b/solution/0800-0899/0896.Monotonic Array/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 遍历数组,如果出现递增或递减的情况,记录下来。判断是否出现过递增和递减的情况,如果都出现过,说明不是单调数组,返回 `false`。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def isMonotonic(self, nums: List[int]) -> bool: @@ -73,10 +67,6 @@ class Solution: return asc or desc ``` -### **Java** - - - ```java class Solution { public boolean isMonotonic(int[] nums) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func isMonotonic(nums []int) bool { asc, desc := false, false @@ -137,31 +123,6 @@ func isMonotonic(nums []int) bool { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {boolean} - */ -var isMonotonic = function (nums) { - let [asc, desc] = [false, false]; - for (let i = 1; i < nums.length; ++i) { - if (nums[i - 1] < nums[i]) { - asc = true; - } else if (nums[i - 1] > nums[i]) { - desc = true; - } - if (asc && desc) { - return false; - } - } - return true; -}; -``` - -### **TypeScript** - ```ts function isMonotonic(nums: number[]): boolean { let [asc, desc] = [false, false]; @@ -179,8 +140,6 @@ function isMonotonic(nums: number[]): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_monotonic(nums: Vec) -> bool { @@ -201,10 +160,27 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums + * @return {boolean} + */ +var isMonotonic = function (nums) { + let [asc, desc] = [false, false]; + for (let i = 1; i < nums.length; ++i) { + if (nums[i - 1] < nums[i]) { + asc = true; + } else if (nums[i - 1] > nums[i]) { + desc = true; + } + if (asc && desc) { + return false; + } + } + return true; +}; ``` + + diff --git a/solution/0800-0899/0896.Monotonic Array/README_EN.md b/solution/0800-0899/0896.Monotonic Array/README_EN.md index b7deeb93cca1b..ddd8401144529 100644 --- a/solution/0800-0899/0896.Monotonic Array/README_EN.md +++ b/solution/0800-0899/0896.Monotonic Array/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Single Traversal** +### Solution 1: Single Traversal We traverse the array, and if an increasing or decreasing situation occurs, we record it. We then check whether both increasing and decreasing situations have occurred. If both have occurred, it means that the array is not monotonic, and we return `false`. @@ -52,8 +52,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def isMonotonic(self, nums: List[int]) -> bool: @@ -62,8 +60,6 @@ class Solution: return asc or desc ``` -### **Java** - ```java class Solution { public boolean isMonotonic(int[] nums) { @@ -83,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +99,6 @@ public: }; ``` -### **Go** - ```go func isMonotonic(nums []int) bool { asc, desc := false, false @@ -124,31 +116,6 @@ func isMonotonic(nums []int) bool { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {boolean} - */ -var isMonotonic = function (nums) { - let [asc, desc] = [false, false]; - for (let i = 1; i < nums.length; ++i) { - if (nums[i - 1] < nums[i]) { - asc = true; - } else if (nums[i - 1] > nums[i]) { - desc = true; - } - if (asc && desc) { - return false; - } - } - return true; -}; -``` - -### **TypeScript** - ```ts function isMonotonic(nums: number[]): boolean { let [asc, desc] = [false, false]; @@ -166,8 +133,6 @@ function isMonotonic(nums: number[]): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_monotonic(nums: Vec) -> bool { @@ -188,10 +153,27 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums + * @return {boolean} + */ +var isMonotonic = function (nums) { + let [asc, desc] = [false, false]; + for (let i = 1; i < nums.length; ++i) { + if (nums[i - 1] < nums[i]) { + asc = true; + } else if (nums[i - 1] > nums[i]) { + desc = true; + } + if (asc && desc) { + return false; + } + } + return true; +}; ``` + + diff --git a/solution/0800-0899/0897.Increasing Order Search Tree/README.md b/solution/0800-0899/0897.Increasing Order Search Tree/README.md index 43916c8c85560..e12e995f54b0a 100644 --- a/solution/0800-0899/0897.Increasing Order Search Tree/README.md +++ b/solution/0800-0899/0897.Increasing Order Search Tree/README.md @@ -35,9 +35,7 @@ ## 解法 - - -**方法一:DFS 中序遍历** +### 方法一:DFS 中序遍历 我们定义一个虚拟节点 $dummy$,初始时 $dummy$ 的右子节点指向根节点 $root$,定义一个指针 $prev$ 指向 $dummy$。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -77,10 +71,6 @@ class Solution: return dummy.right ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -184,8 +170,6 @@ func increasingBST(root *TreeNode) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -219,10 +203,6 @@ function increasingBST(root: TreeNode | null): TreeNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0897.Increasing Order Search Tree/README_EN.md b/solution/0800-0899/0897.Increasing Order Search Tree/README_EN.md index 8552be68c27c2..b44cd7e52717c 100644 --- a/solution/0800-0899/0897.Increasing Order Search Tree/README_EN.md +++ b/solution/0800-0899/0897.Increasing Order Search Tree/README_EN.md @@ -31,7 +31,7 @@ ## Solutions -**Solution 1: DFS In-order Traversal** +### Solution 1: DFS In-order Traversal We define a virtual node $dummy$, initially the right child of $dummy$ points to the root node $root$, and a pointer $prev$ points to $dummy$. @@ -43,8 +43,6 @@ 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: @@ -69,8 +67,6 @@ class Solution: return dummy.right ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -144,8 +138,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -174,8 +166,6 @@ func increasingBST(root *TreeNode) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -209,10 +199,6 @@ function increasingBST(root: TreeNode | null): TreeNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0898.Bitwise ORs of Subarrays/README.md b/solution/0800-0899/0898.Bitwise ORs of Subarrays/README.md index 8ab819ca5bb84..3b59667972b09 100644 --- a/solution/0800-0899/0898.Bitwise ORs of Subarrays/README.md +++ b/solution/0800-0899/0898.Bitwise ORs of Subarrays/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 题目求的是子数组按位或操作的结果的数量,如果我们枚举子数组的结束位置 $i$,那么以 $i-1$ 结尾的子数组按位或操作的结果的数量最多不超过 $32$ 个。这是因为,按位或是一个单调递增的操作。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def subarrayBitwiseORs(self, arr: List[int]) -> int: @@ -85,10 +79,6 @@ class Solution: return len(ans) ``` -### **Java** - - - ```java class Solution { public int subarrayBitwiseORs(int[] arr) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func subarrayBitwiseORs(arr []int) int { ans := map[int]bool{} @@ -150,8 +136,6 @@ func subarrayBitwiseORs(arr []int) int { } ``` -### **TypeScript** - ```ts function subarrayBitwiseORs(arr: number[]): number { const s: Set = new Set(); @@ -172,10 +156,6 @@ function subarrayBitwiseORs(arr: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0898.Bitwise ORs of Subarrays/README_EN.md b/solution/0800-0899/0898.Bitwise ORs of Subarrays/README_EN.md index 62b8166ceb66d..8aa18cea2764e 100644 --- a/solution/0800-0899/0898.Bitwise ORs of Subarrays/README_EN.md +++ b/solution/0800-0899/0898.Bitwise ORs of Subarrays/README_EN.md @@ -47,7 +47,7 @@ There are 3 unique values, so the answer is 3. ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table The problem asks for the number of unique bitwise OR operations results of subarrays. If we enumerate the end position $i$ of the subarray, the number of bitwise OR operations results of the subarray ending at $i-1$ does not exceed $32$. This is because the bitwise OR operation is a monotonically increasing operation. @@ -61,8 +61,6 @@ The time complexity is $O(n \times \log M)$, and the space complexity is $O(n \t -### **Python3** - ```python class Solution: def subarrayBitwiseORs(self, arr: List[int]) -> int: @@ -74,8 +72,6 @@ class Solution: return len(ans) ``` -### **Java** - ```java class Solution { public int subarrayBitwiseORs(int[] arr) { @@ -96,30 +92,25 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { - class Solution { - public: - int subarrayBitwiseORs(vector& arr) { - unordered_set s{{0}}; - unordered_set ans; - for (int& x : arr) { - unordered_set t{{x}}; - for (int y : s) { - t.insert(x | y); - } - s = move(t); - ans.insert(s.begin(), s.end()); +public: + int subarrayBitwiseORs(vector& arr) { + unordered_set s{{0}}; + unordered_set ans; + for (int& x : arr) { + unordered_set t{{x}}; + for (int y : s) { + t.insert(x | y); } - return ans.size(); + s = move(t); + ans.insert(s.begin(), s.end()); } - }; + return ans.size(); + } +}; ``` -### **Go** - ```go func subarrayBitwiseORs(arr []int) int { ans := map[int]bool{} @@ -138,8 +129,6 @@ func subarrayBitwiseORs(arr []int) int { } ``` -### **TypeScript** - ```ts function subarrayBitwiseORs(arr: number[]): number { const s: Set = new Set(); @@ -160,10 +149,6 @@ function subarrayBitwiseORs(arr: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0899.Orderly Queue/README.md b/solution/0800-0899/0899.Orderly Queue/README.md index 36946c4f74e38..dc8de87a1c8d8 100644 --- a/solution/0800-0899/0899.Orderly Queue/README.md +++ b/solution/0800-0899/0899.Orderly Queue/README.md @@ -43,13 +43,7 @@ ## 解法 - - -**前言** - -对于任何字符串,如果可以交换任意相邻字符,则可以对字符串中的字符做类似冒泡排序的操作,最终得到一个升序排列的字符串。 - -**方法一:分情况判断** +### 方法一:分情况判断 若 $k = 1$,我们每次只能将字符串首字符移动到字符串末尾,总共有 $|s|$ 种不同的状态,我们返回其中字典序最小的字符串即可。 @@ -61,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def orderlyQueue(self, s: str, k: int) -> str: @@ -77,10 +67,6 @@ class Solution: return "".join(sorted(s)) ``` -### **Java** - - - ```java class Solution { public String orderlyQueue(String s, int k) { @@ -102,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +106,6 @@ public: }; ``` -### **Go** - ```go func orderlyQueue(s string, k int) string { if k == 1 { @@ -142,8 +124,6 @@ func orderlyQueue(s string, k int) string { } ``` -### **TypeScript** - ```ts function orderlyQueue(s: string, k: number): string { if (k > 1) { @@ -161,10 +141,6 @@ function orderlyQueue(s: string, k: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0800-0899/0899.Orderly Queue/README_EN.md b/solution/0800-0899/0899.Orderly Queue/README_EN.md index e4b639e9a32a5..75c97aa7ce2f3 100644 --- a/solution/0800-0899/0899.Orderly Queue/README_EN.md +++ b/solution/0800-0899/0899.Orderly Queue/README_EN.md @@ -39,11 +39,7 @@ In the second move, we move the 3rd character 'c' to the end, ## Solutions -**Preface** - -For any string, if any adjacent characters can be swapped, we can perform a bubble sort-like operation on the characters in the string, eventually obtaining a string sorted in ascending order. - -**Solution 1: Case-by-case Judgment** +### Solution 1: Case-by-case Judgment If $k = 1$, we can only move the first character of the string to the end of the string each time, resulting in $|s|$ different states. We return the string with the smallest lexicographic order. @@ -55,8 +51,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ i -### **Python3** - ```python class Solution: def orderlyQueue(self, s: str, k: int) -> str: @@ -69,8 +63,6 @@ class Solution: return "".join(sorted(s)) ``` -### **Java** - ```java class Solution { public String orderlyQueue(String s, int k) { @@ -92,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +102,6 @@ public: }; ``` -### **Go** - ```go func orderlyQueue(s string, k int) string { if k == 1 { @@ -132,8 +120,6 @@ func orderlyQueue(s string, k int) string { } ``` -### **TypeScript** - ```ts function orderlyQueue(s: string, k: number): string { if (k > 1) { @@ -151,10 +137,6 @@ function orderlyQueue(s: string, k: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0900.RLE Iterator/README.md b/solution/0900-0999/0900.RLE Iterator/README.md index 491170fb222b8..426bbc0f574e0 100644 --- a/solution/0900-0999/0900.RLE Iterator/README.md +++ b/solution/0900-0999/0900.RLE Iterator/README.md @@ -54,9 +54,7 @@ rLEIterator.next(2); // 耗去序列的 2 个项,返回 -1。 这是由于第 ## 解法 - - -**方法一:维护两个指针** +### 方法一:维护两个指针 我们定义两个指针 $i$ 和 $j$,其中指针 $i$ 指向当前读取的游程编码,指针 $j$ 指向当前读取的游程编码中的第几个字符。初始时 $i = 0$, $j = 0$。 @@ -68,10 +66,6 @@ rLEIterator.next(2); // 耗去序列的 2 个项,返回 -1。 这是由于第 -### **Python3** - - - ```python class RLEIterator: def __init__(self, encoding: List[int]): @@ -96,10 +90,6 @@ class RLEIterator: # param_1 = obj.next(n) ``` -### **Java** - - - ```java class RLEIterator { private int[] encoding; @@ -132,8 +122,6 @@ class RLEIterator { */ ``` -### **C++** - ```cpp class RLEIterator { public: @@ -168,8 +156,6 @@ private: */ ``` -### **Go** - ```go type RLEIterator struct { encoding []int @@ -201,8 +187,6 @@ func (this *RLEIterator) Next(n int) int { */ ``` -### **TypeScript** - ```ts class RLEIterator { private encoding: number[]; @@ -237,10 +221,6 @@ class RLEIterator { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0900.RLE Iterator/README_EN.md b/solution/0900-0999/0900.RLE Iterator/README_EN.md index d1c2ef60728ef..5f779cc7c575c 100644 --- a/solution/0900-0999/0900.RLE Iterator/README_EN.md +++ b/solution/0900-0999/0900.RLE Iterator/README_EN.md @@ -51,7 +51,7 @@ but the second term did not exist. Since the last term exhausted does not exist, ## Solutions -**Solution 1: Maintain Two Pointers** +### Solution 1: Maintain Two Pointers We define two pointers $i$ and $j$, where pointer $i$ points to the current run-length encoding being read, and pointer $j$ points to which character in the current run-length encoding is being read. Initially, $i = 0$, $j = 0$. @@ -63,8 +63,6 @@ The time complexity is $O(n + q)$, and the space complexity is $O(n)$. Here, $n$ -### **Python3** - ```python class RLEIterator: def __init__(self, encoding: List[int]): @@ -89,8 +87,6 @@ class RLEIterator: # param_1 = obj.next(n) ``` -### **Java** - ```java class RLEIterator { private int[] encoding; @@ -123,8 +119,6 @@ class RLEIterator { */ ``` -### **C++** - ```cpp class RLEIterator { public: @@ -159,8 +153,6 @@ private: */ ``` -### **Go** - ```go type RLEIterator struct { encoding []int @@ -192,8 +184,6 @@ func (this *RLEIterator) Next(n int) int { */ ``` -### **TypeScript** - ```ts class RLEIterator { private encoding: number[]; @@ -228,10 +218,6 @@ class RLEIterator { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0901.Online Stock Span/README.md b/solution/0900-0999/0901.Online Stock Span/README.md index 93e5295f512d0..115323cd185c8 100644 --- a/solution/0900-0999/0901.Online Stock Span/README.md +++ b/solution/0900-0999/0901.Online Stock Span/README.md @@ -56,9 +56,7 @@ stockSpanner.next(85); // 返回 6 ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 根据题目描述,我们可以知道,对于当日价格 $price$,从这个价格开始往前找,找到第一个比这个价格大的价格,这两个价格的下标差 $cnt$ 就是当日价格的跨度。 @@ -74,10 +72,6 @@ stockSpanner.next(85); // 返回 6 -### **Python3** - - - ```python class StockSpanner: def __init__(self): @@ -96,10 +90,6 @@ class StockSpanner: # param_1 = obj.next(price) ``` -### **Java** - - - ```java class StockSpanner { private Deque stk = new ArrayDeque<>(); @@ -124,8 +114,6 @@ class StockSpanner { */ ``` -### **C++** - ```cpp class StockSpanner { public: @@ -153,8 +141,6 @@ private: */ ``` -### **Go** - ```go type StockSpanner struct { stk []pair @@ -183,8 +169,6 @@ type pair struct{ price, cnt int } */ ``` -### **TypeScript** - ```ts class StockSpanner { private stk: number[][]; @@ -210,8 +194,6 @@ class StockSpanner { */ ``` -### **Rust** - ```rust use std::collections::VecDeque; struct StockSpanner { @@ -244,10 +226,6 @@ impl StockSpanner { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0901.Online Stock Span/README_EN.md b/solution/0900-0999/0901.Online Stock Span/README_EN.md index 977a1ad2d099f..7336219682cde 100644 --- a/solution/0900-0999/0901.Online Stock Span/README_EN.md +++ b/solution/0900-0999/0901.Online Stock Span/README_EN.md @@ -51,7 +51,7 @@ stockSpanner.next(85); // return 6 ## Solutions -**Solution 1: Monotonic Stack** +### Solution 1: Monotonic Stack Based on the problem description, we know that for the current day's price $price$, we start from this price and look backwards to find the first price that is larger than this price. The difference in indices $cnt$ between these two prices is the span of the current day's price. @@ -67,8 +67,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class StockSpanner: def __init__(self): @@ -87,8 +85,6 @@ class StockSpanner: # param_1 = obj.next(price) ``` -### **Java** - ```java class StockSpanner { private Deque stk = new ArrayDeque<>(); @@ -113,8 +109,6 @@ class StockSpanner { */ ``` -### **C++** - ```cpp class StockSpanner { public: @@ -142,8 +136,6 @@ private: */ ``` -### **Go** - ```go type StockSpanner struct { stk []pair @@ -172,8 +164,6 @@ type pair struct{ price, cnt int } */ ``` -### **TypeScript** - ```ts class StockSpanner { private stk: number[][]; @@ -199,8 +189,6 @@ class StockSpanner { */ ``` -### **Rust** - ```rust use std::collections::VecDeque; struct StockSpanner { @@ -233,10 +221,6 @@ impl StockSpanner { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0902.Numbers At Most N Given Digit Set/README.md b/solution/0900-0999/0902.Numbers At Most N Given Digit Set/README.md index 34cac54d0ee6e..80c1696ddffca 100644 --- a/solution/0900-0999/0902.Numbers At Most N Given Digit Set/README.md +++ b/solution/0900-0999/0902.Numbers At Most N Given Digit Set/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:数位 DP** +### 方法一:数位 DP 这道题实际上是求在给定区间 $[l,..r]$ 中,由 `digits` 中的数字生成的正整数的个数。个数与数的位数以及每一位上的数字有关。我们可以用数位 DP 的思路来解决这道题。数位 DP 中,数的大小对复杂度的影响很小。 @@ -98,10 +96,6 @@ $$ -### **Python3** - - - ```python class Solution: def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: @@ -128,10 +122,6 @@ class Solution: return dfs(l, True, True) ``` -### **Java** - - - ```java class Solution { private int[] a = new int[12]; @@ -177,8 +167,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -223,8 +211,6 @@ public: }; ``` -### **Go** - ```go func atMostNGivenDigitSet(digits []string, n int) int { s := map[int]bool{} @@ -272,10 +258,6 @@ func atMostNGivenDigitSet(digits []string, n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0902.Numbers At Most N Given Digit Set/README_EN.md b/solution/0900-0999/0902.Numbers At Most N Given Digit Set/README_EN.md index 4f5cfb5f65752..8d2dff8feedcc 100644 --- a/solution/0900-0999/0902.Numbers At Most N Given Digit Set/README_EN.md +++ b/solution/0900-0999/0902.Numbers At Most N Given Digit Set/README_EN.md @@ -52,9 +52,9 @@ In total, this is 29523 integers that can be written using the digits array. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,8 +82,6 @@ class Solution: return dfs(l, True, True) ``` -### **Java** - ```java class Solution { private int[] a = new int[12]; @@ -129,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +171,6 @@ public: }; ``` -### **Go** - ```go func atMostNGivenDigitSet(digits []string, n int) int { s := map[int]bool{} @@ -224,10 +218,6 @@ func atMostNGivenDigitSet(digits []string, n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/README.md b/solution/0900-0999/0903.Valid Permutations for DI Sequence/README.md index 230d00cfda13e..67ce9d0e8a2ea 100644 --- a/solution/0900-0999/0903.Valid Permutations for DI Sequence/README.md +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示字符串的前 $i$ 个字符中,以数字 $j$ 结尾的满足题目要求的排列的数量。初始时 $f[0][0]=1$,其余 $f[0][j]=0$。答案为 $\sum_{j=0}^n f[n][j]$。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def numPermsDISequence(self, s: str) -> int: @@ -100,51 +94,6 @@ class Solution: return sum(f[n][j] for j in range(n + 1)) % mod ``` -```python -class Solution: - def numPermsDISequence(self, s: str) -> int: - mod = 10**9 + 7 - n = len(s) - f = [[0] * (n + 1) for _ in range(n + 1)] - f[0][0] = 1 - for i, c in enumerate(s, 1): - pre = 0 - if c == "D": - for j in range(i, -1, -1): - pre = (pre + f[i - 1][j]) % mod - f[i][j] = pre - else: - for j in range(i + 1): - f[i][j] = pre - pre = (pre + f[i - 1][j]) % mod - return sum(f[n][j] for j in range(n + 1)) % mod -``` - -```python -class Solution: - def numPermsDISequence(self, s: str) -> int: - mod = 10**9 + 7 - n = len(s) - f = [1] + [0] * n - for i, c in enumerate(s, 1): - pre = 0 - g = [0] * (n + 1) - if c == "D": - for j in range(i, -1, -1): - pre = (pre + f[j]) % mod - g[j] = pre - else: - for j in range(i + 1): - g[j] = pre - pre = (pre + f[j]) % mod - f = g - return sum(f) % mod -``` - -### **Java** - - - ```java class Solution { public int numPermsDISequence(String s) { @@ -176,24 +125,27 @@ class Solution { } ``` -```java +```cpp class Solution { - public int numPermsDISequence(String s) { - final int mod = (int) 1e9 + 7; - int n = s.length(); - int[][] f = new int[n + 1][n + 1]; +public: + int numPermsDISequence(string s) { + const int mod = 1e9 + 7; + int n = s.size(); + int f[n + 1][n + 1]; + memset(f, 0, sizeof(f)); f[0][0] = 1; for (int i = 1; i <= n; ++i) { - int pre = 0; - if (s.charAt(i - 1) == 'D') { - for (int j = i; j >= 0; --j) { - pre = (pre + f[i - 1][j]) % mod; - f[i][j] = pre; + if (s[i - 1] == 'D') { + for (int j = 0; j <= i; ++j) { + for (int k = j; k < i; ++k) { + f[i][j] = (f[i][j] + f[i - 1][k]) % mod; + } } } else { for (int j = 0; j <= i; ++j) { - f[i][j] = pre; - pre = (pre + f[i - 1][j]) % mod; + for (int k = 0; k < j; ++k) { + f[i][j] = (f[i][j] + f[i - 1][k]) % mod; + } } } } @@ -203,43 +155,127 @@ class Solution { } return ans; } +}; +``` + +```go +func numPermsDISequence(s string) (ans int) { + const mod = 1e9 + 7 + n := len(s) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, n+1) + } + f[0][0] = 1 + for i := 1; i <= n; i++ { + if s[i-1] == 'D' { + for j := 0; j <= i; j++ { + for k := j; k < i; k++ { + f[i][j] = (f[i][j] + f[i-1][k]) % mod + } + } + } else { + for j := 0; j <= i; j++ { + for k := 0; k < j; k++ { + f[i][j] = (f[i][j] + f[i-1][k]) % mod + } + } + } + } + for j := 0; j <= n; j++ { + ans = (ans + f[n][j]) % mod + } + return +} +``` + +```ts +function numPermsDISequence(s: string): number { + const n = s.length; + const f: number[][] = Array(n + 1) + .fill(0) + .map(() => Array(n + 1).fill(0)); + f[0][0] = 1; + const mod = 10 ** 9 + 7; + for (let i = 1; i <= n; ++i) { + if (s[i - 1] === 'D') { + for (let j = 0; j <= i; ++j) { + for (let k = j; k < i; ++k) { + f[i][j] = (f[i][j] + f[i - 1][k]) % mod; + } + } + } else { + for (let j = 0; j <= i; ++j) { + for (let k = 0; k < j; ++k) { + f[i][j] = (f[i][j] + f[i - 1][k]) % mod; + } + } + } + } + let ans = 0; + for (let j = 0; j <= n; ++j) { + ans = (ans + f[n][j]) % mod; + } + return ans; } ``` + + +### 方法二 + + + +```python +class Solution: + def numPermsDISequence(self, s: str) -> int: + mod = 10**9 + 7 + n = len(s) + f = [[0] * (n + 1) for _ in range(n + 1)] + f[0][0] = 1 + for i, c in enumerate(s, 1): + pre = 0 + if c == "D": + for j in range(i, -1, -1): + pre = (pre + f[i - 1][j]) % mod + f[i][j] = pre + else: + for j in range(i + 1): + f[i][j] = pre + pre = (pre + f[i - 1][j]) % mod + return sum(f[n][j] for j in range(n + 1)) % mod +``` + ```java class Solution { public int numPermsDISequence(String s) { final int mod = (int) 1e9 + 7; int n = s.length(); - int[] f = new int[n + 1]; - f[0] = 1; + int[][] f = new int[n + 1][n + 1]; + f[0][0] = 1; for (int i = 1; i <= n; ++i) { int pre = 0; - int[] g = new int[n + 1]; if (s.charAt(i - 1) == 'D') { for (int j = i; j >= 0; --j) { - pre = (pre + f[j]) % mod; - g[j] = pre; + pre = (pre + f[i - 1][j]) % mod; + f[i][j] = pre; } } else { for (int j = 0; j <= i; ++j) { - g[j] = pre; - pre = (pre + f[j]) % mod; + f[i][j] = pre; + pre = (pre + f[i - 1][j]) % mod; } } - f = g; } int ans = 0; for (int j = 0; j <= n; ++j) { - ans = (ans + f[j]) % mod; + ans = (ans + f[n][j]) % mod; } return ans; } } ``` -### **C++** - ```cpp class Solution { public: @@ -250,17 +286,16 @@ public: memset(f, 0, sizeof(f)); f[0][0] = 1; for (int i = 1; i <= n; ++i) { + int pre = 0; if (s[i - 1] == 'D') { - for (int j = 0; j <= i; ++j) { - for (int k = j; k < i; ++k) { - f[i][j] = (f[i][j] + f[i - 1][k]) % mod; - } + for (int j = i; j >= 0; --j) { + pre = (pre + f[i - 1][j]) % mod; + f[i][j] = pre; } } else { for (int j = 0; j <= i; ++j) { - for (int k = 0; k < j; ++k) { - f[i][j] = (f[i][j] + f[i - 1][k]) % mod; - } + f[i][j] = pre; + pre = (pre + f[i - 1][j]) % mod; } } } @@ -273,36 +308,123 @@ public: }; ``` -```cpp +```go +func numPermsDISequence(s string) (ans int) { + const mod = 1e9 + 7 + n := len(s) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, n+1) + } + f[0][0] = 1 + for i := 1; i <= n; i++ { + pre := 0 + if s[i-1] == 'D' { + for j := i; j >= 0; j-- { + pre = (pre + f[i-1][j]) % mod + f[i][j] = pre + } + } else { + for j := 0; j <= i; j++ { + f[i][j] = pre + pre = (pre + f[i-1][j]) % mod + } + } + } + for j := 0; j <= n; j++ { + ans = (ans + f[n][j]) % mod + } + return +} +``` + +```ts +function numPermsDISequence(s: string): number { + const n = s.length; + const f: number[][] = Array(n + 1) + .fill(0) + .map(() => Array(n + 1).fill(0)); + f[0][0] = 1; + const mod = 10 ** 9 + 7; + for (let i = 1; i <= n; ++i) { + let pre = 0; + if (s[i - 1] === 'D') { + for (let j = i; j >= 0; --j) { + pre = (pre + f[i - 1][j]) % mod; + f[i][j] = pre; + } + } else { + for (let j = 0; j <= i; ++j) { + f[i][j] = pre; + pre = (pre + f[i - 1][j]) % mod; + } + } + } + let ans = 0; + for (let j = 0; j <= n; ++j) { + ans = (ans + f[n][j]) % mod; + } + return ans; +} +``` + + + +### 方法三 + + + +```python +class Solution: + def numPermsDISequence(self, s: str) -> int: + mod = 10**9 + 7 + n = len(s) + f = [1] + [0] * n + for i, c in enumerate(s, 1): + pre = 0 + g = [0] * (n + 1) + if c == "D": + for j in range(i, -1, -1): + pre = (pre + f[j]) % mod + g[j] = pre + else: + for j in range(i + 1): + g[j] = pre + pre = (pre + f[j]) % mod + f = g + return sum(f) % mod +``` + +```java class Solution { -public: - int numPermsDISequence(string s) { - const int mod = 1e9 + 7; - int n = s.size(); - int f[n + 1][n + 1]; - memset(f, 0, sizeof(f)); - f[0][0] = 1; + public int numPermsDISequence(String s) { + final int mod = (int) 1e9 + 7; + int n = s.length(); + int[] f = new int[n + 1]; + f[0] = 1; for (int i = 1; i <= n; ++i) { int pre = 0; - if (s[i - 1] == 'D') { + int[] g = new int[n + 1]; + if (s.charAt(i - 1) == 'D') { for (int j = i; j >= 0; --j) { - pre = (pre + f[i - 1][j]) % mod; - f[i][j] = pre; + pre = (pre + f[j]) % mod; + g[j] = pre; } } else { for (int j = 0; j <= i; ++j) { - f[i][j] = pre; - pre = (pre + f[i - 1][j]) % mod; + g[j] = pre; + pre = (pre + f[j]) % mod; } } + f = g; } int ans = 0; for (int j = 0; j <= n; ++j) { - ans = (ans + f[n][j]) % mod; + ans = (ans + f[j]) % mod; } return ans; } -}; +} ``` ```cpp @@ -338,69 +460,6 @@ public: }; ``` -### **Go** - -```go -func numPermsDISequence(s string) (ans int) { - const mod = 1e9 + 7 - n := len(s) - f := make([][]int, n+1) - for i := range f { - f[i] = make([]int, n+1) - } - f[0][0] = 1 - for i := 1; i <= n; i++ { - if s[i-1] == 'D' { - for j := 0; j <= i; j++ { - for k := j; k < i; k++ { - f[i][j] = (f[i][j] + f[i-1][k]) % mod - } - } - } else { - for j := 0; j <= i; j++ { - for k := 0; k < j; k++ { - f[i][j] = (f[i][j] + f[i-1][k]) % mod - } - } - } - } - for j := 0; j <= n; j++ { - ans = (ans + f[n][j]) % mod - } - return -} -``` - -```go -func numPermsDISequence(s string) (ans int) { - const mod = 1e9 + 7 - n := len(s) - f := make([][]int, n+1) - for i := range f { - f[i] = make([]int, n+1) - } - f[0][0] = 1 - for i := 1; i <= n; i++ { - pre := 0 - if s[i-1] == 'D' { - for j := i; j >= 0; j-- { - pre = (pre + f[i-1][j]) % mod - f[i][j] = pre - } - } else { - for j := 0; j <= i; j++ { - f[i][j] = pre - pre = (pre + f[i-1][j]) % mod - } - } - } - for j := 0; j <= n; j++ { - ans = (ans + f[n][j]) % mod - } - return -} -``` - ```go func numPermsDISequence(s string) (ans int) { const mod = 1e9 + 7 @@ -430,69 +489,6 @@ func numPermsDISequence(s string) (ans int) { } ``` -### **TypeScript** - -```ts -function numPermsDISequence(s: string): number { - const n = s.length; - const f: number[][] = Array(n + 1) - .fill(0) - .map(() => Array(n + 1).fill(0)); - f[0][0] = 1; - const mod = 10 ** 9 + 7; - for (let i = 1; i <= n; ++i) { - if (s[i - 1] === 'D') { - for (let j = 0; j <= i; ++j) { - for (let k = j; k < i; ++k) { - f[i][j] = (f[i][j] + f[i - 1][k]) % mod; - } - } - } else { - for (let j = 0; j <= i; ++j) { - for (let k = 0; k < j; ++k) { - f[i][j] = (f[i][j] + f[i - 1][k]) % mod; - } - } - } - } - let ans = 0; - for (let j = 0; j <= n; ++j) { - ans = (ans + f[n][j]) % mod; - } - return ans; -} -``` - -```ts -function numPermsDISequence(s: string): number { - const n = s.length; - const f: number[][] = Array(n + 1) - .fill(0) - .map(() => Array(n + 1).fill(0)); - f[0][0] = 1; - const mod = 10 ** 9 + 7; - for (let i = 1; i <= n; ++i) { - let pre = 0; - if (s[i - 1] === 'D') { - for (let j = i; j >= 0; --j) { - pre = (pre + f[i - 1][j]) % mod; - f[i][j] = pre; - } - } else { - for (let j = 0; j <= i; ++j) { - f[i][j] = pre; - pre = (pre + f[i - 1][j]) % mod; - } - } - } - let ans = 0; - for (let j = 0; j <= n; ++j) { - ans = (ans + f[n][j]) % mod; - } - return ans; -} -``` - ```ts function numPermsDISequence(s: string): number { const n = s.length; @@ -523,10 +519,6 @@ function numPermsDISequence(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0903.Valid Permutations for DI Sequence/README_EN.md b/solution/0900-0999/0903.Valid Permutations for DI Sequence/README_EN.md index d036fb74360dc..3402aa4fcce89 100644 --- a/solution/0900-0999/0903.Valid Permutations for DI Sequence/README_EN.md +++ b/solution/0900-0999/0903.Valid Permutations for DI Sequence/README_EN.md @@ -52,7 +52,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ as the number of permutations that satisfy the problem's requirements with the first $i$ characters of the string ending with the number $j$. Initially, $f[0][0]=1$, and the rest $f[0][j]=0$. The answer is $\sum_{j=0}^n f[n][j]$. @@ -70,8 +70,6 @@ We can optimize the time complexity to $O(n^2)$ using prefix sums. Additionally, -### **Python3** - ```python class Solution: def numPermsDISequence(self, s: str) -> int: @@ -91,49 +89,6 @@ class Solution: return sum(f[n][j] for j in range(n + 1)) % mod ``` -```python -class Solution: - def numPermsDISequence(self, s: str) -> int: - mod = 10**9 + 7 - n = len(s) - f = [[0] * (n + 1) for _ in range(n + 1)] - f[0][0] = 1 - for i, c in enumerate(s, 1): - pre = 0 - if c == "D": - for j in range(i, -1, -1): - pre = (pre + f[i - 1][j]) % mod - f[i][j] = pre - else: - for j in range(i + 1): - f[i][j] = pre - pre = (pre + f[i - 1][j]) % mod - return sum(f[n][j] for j in range(n + 1)) % mod -``` - -```python -class Solution: - def numPermsDISequence(self, s: str) -> int: - mod = 10**9 + 7 - n = len(s) - f = [1] + [0] * n - for i, c in enumerate(s, 1): - pre = 0 - g = [0] * (n + 1) - if c == "D": - for j in range(i, -1, -1): - pre = (pre + f[j]) % mod - g[j] = pre - else: - for j in range(i + 1): - g[j] = pre - pre = (pre + f[j]) % mod - f = g - return sum(f) % mod -``` - -### **Java** - ```java class Solution { public int numPermsDISequence(String s) { @@ -165,24 +120,27 @@ class Solution { } ``` -```java +```cpp class Solution { - public int numPermsDISequence(String s) { - final int mod = (int) 1e9 + 7; - int n = s.length(); - int[][] f = new int[n + 1][n + 1]; +public: + int numPermsDISequence(string s) { + const int mod = 1e9 + 7; + int n = s.size(); + int f[n + 1][n + 1]; + memset(f, 0, sizeof(f)); f[0][0] = 1; for (int i = 1; i <= n; ++i) { - int pre = 0; - if (s.charAt(i - 1) == 'D') { - for (int j = i; j >= 0; --j) { - pre = (pre + f[i - 1][j]) % mod; - f[i][j] = pre; + if (s[i - 1] == 'D') { + for (int j = 0; j <= i; ++j) { + for (int k = j; k < i; ++k) { + f[i][j] = (f[i][j] + f[i - 1][k]) % mod; + } } } else { for (int j = 0; j <= i; ++j) { - f[i][j] = pre; - pre = (pre + f[i - 1][j]) % mod; + for (int k = 0; k < j; ++k) { + f[i][j] = (f[i][j] + f[i - 1][k]) % mod; + } } } } @@ -192,43 +150,127 @@ class Solution { } return ans; } +}; +``` + +```go +func numPermsDISequence(s string) (ans int) { + const mod = 1e9 + 7 + n := len(s) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, n+1) + } + f[0][0] = 1 + for i := 1; i <= n; i++ { + if s[i-1] == 'D' { + for j := 0; j <= i; j++ { + for k := j; k < i; k++ { + f[i][j] = (f[i][j] + f[i-1][k]) % mod + } + } + } else { + for j := 0; j <= i; j++ { + for k := 0; k < j; k++ { + f[i][j] = (f[i][j] + f[i-1][k]) % mod + } + } + } + } + for j := 0; j <= n; j++ { + ans = (ans + f[n][j]) % mod + } + return } ``` +```ts +function numPermsDISequence(s: string): number { + const n = s.length; + const f: number[][] = Array(n + 1) + .fill(0) + .map(() => Array(n + 1).fill(0)); + f[0][0] = 1; + const mod = 10 ** 9 + 7; + for (let i = 1; i <= n; ++i) { + if (s[i - 1] === 'D') { + for (let j = 0; j <= i; ++j) { + for (let k = j; k < i; ++k) { + f[i][j] = (f[i][j] + f[i - 1][k]) % mod; + } + } + } else { + for (let j = 0; j <= i; ++j) { + for (let k = 0; k < j; ++k) { + f[i][j] = (f[i][j] + f[i - 1][k]) % mod; + } + } + } + } + let ans = 0; + for (let j = 0; j <= n; ++j) { + ans = (ans + f[n][j]) % mod; + } + return ans; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def numPermsDISequence(self, s: str) -> int: + mod = 10**9 + 7 + n = len(s) + f = [[0] * (n + 1) for _ in range(n + 1)] + f[0][0] = 1 + for i, c in enumerate(s, 1): + pre = 0 + if c == "D": + for j in range(i, -1, -1): + pre = (pre + f[i - 1][j]) % mod + f[i][j] = pre + else: + for j in range(i + 1): + f[i][j] = pre + pre = (pre + f[i - 1][j]) % mod + return sum(f[n][j] for j in range(n + 1)) % mod +``` + ```java class Solution { public int numPermsDISequence(String s) { final int mod = (int) 1e9 + 7; int n = s.length(); - int[] f = new int[n + 1]; - f[0] = 1; + int[][] f = new int[n + 1][n + 1]; + f[0][0] = 1; for (int i = 1; i <= n; ++i) { int pre = 0; - int[] g = new int[n + 1]; if (s.charAt(i - 1) == 'D') { for (int j = i; j >= 0; --j) { - pre = (pre + f[j]) % mod; - g[j] = pre; + pre = (pre + f[i - 1][j]) % mod; + f[i][j] = pre; } } else { for (int j = 0; j <= i; ++j) { - g[j] = pre; - pre = (pre + f[j]) % mod; + f[i][j] = pre; + pre = (pre + f[i - 1][j]) % mod; } } - f = g; } int ans = 0; for (int j = 0; j <= n; ++j) { - ans = (ans + f[j]) % mod; + ans = (ans + f[n][j]) % mod; } return ans; } } ``` -### **C++** - ```cpp class Solution { public: @@ -239,17 +281,16 @@ public: memset(f, 0, sizeof(f)); f[0][0] = 1; for (int i = 1; i <= n; ++i) { + int pre = 0; if (s[i - 1] == 'D') { - for (int j = 0; j <= i; ++j) { - for (int k = j; k < i; ++k) { - f[i][j] = (f[i][j] + f[i - 1][k]) % mod; - } + for (int j = i; j >= 0; --j) { + pre = (pre + f[i - 1][j]) % mod; + f[i][j] = pre; } } else { for (int j = 0; j <= i; ++j) { - for (int k = 0; k < j; ++k) { - f[i][j] = (f[i][j] + f[i - 1][k]) % mod; - } + f[i][j] = pre; + pre = (pre + f[i - 1][j]) % mod; } } } @@ -262,36 +303,123 @@ public: }; ``` -```cpp +```go +func numPermsDISequence(s string) (ans int) { + const mod = 1e9 + 7 + n := len(s) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, n+1) + } + f[0][0] = 1 + for i := 1; i <= n; i++ { + pre := 0 + if s[i-1] == 'D' { + for j := i; j >= 0; j-- { + pre = (pre + f[i-1][j]) % mod + f[i][j] = pre + } + } else { + for j := 0; j <= i; j++ { + f[i][j] = pre + pre = (pre + f[i-1][j]) % mod + } + } + } + for j := 0; j <= n; j++ { + ans = (ans + f[n][j]) % mod + } + return +} +``` + +```ts +function numPermsDISequence(s: string): number { + const n = s.length; + const f: number[][] = Array(n + 1) + .fill(0) + .map(() => Array(n + 1).fill(0)); + f[0][0] = 1; + const mod = 10 ** 9 + 7; + for (let i = 1; i <= n; ++i) { + let pre = 0; + if (s[i - 1] === 'D') { + for (let j = i; j >= 0; --j) { + pre = (pre + f[i - 1][j]) % mod; + f[i][j] = pre; + } + } else { + for (let j = 0; j <= i; ++j) { + f[i][j] = pre; + pre = (pre + f[i - 1][j]) % mod; + } + } + } + let ans = 0; + for (let j = 0; j <= n; ++j) { + ans = (ans + f[n][j]) % mod; + } + return ans; +} +``` + + + +### Solution 3 + + + +```python +class Solution: + def numPermsDISequence(self, s: str) -> int: + mod = 10**9 + 7 + n = len(s) + f = [1] + [0] * n + for i, c in enumerate(s, 1): + pre = 0 + g = [0] * (n + 1) + if c == "D": + for j in range(i, -1, -1): + pre = (pre + f[j]) % mod + g[j] = pre + else: + for j in range(i + 1): + g[j] = pre + pre = (pre + f[j]) % mod + f = g + return sum(f) % mod +``` + +```java class Solution { -public: - int numPermsDISequence(string s) { - const int mod = 1e9 + 7; - int n = s.size(); - int f[n + 1][n + 1]; - memset(f, 0, sizeof(f)); - f[0][0] = 1; + public int numPermsDISequence(String s) { + final int mod = (int) 1e9 + 7; + int n = s.length(); + int[] f = new int[n + 1]; + f[0] = 1; for (int i = 1; i <= n; ++i) { int pre = 0; - if (s[i - 1] == 'D') { + int[] g = new int[n + 1]; + if (s.charAt(i - 1) == 'D') { for (int j = i; j >= 0; --j) { - pre = (pre + f[i - 1][j]) % mod; - f[i][j] = pre; + pre = (pre + f[j]) % mod; + g[j] = pre; } } else { for (int j = 0; j <= i; ++j) { - f[i][j] = pre; - pre = (pre + f[i - 1][j]) % mod; + g[j] = pre; + pre = (pre + f[j]) % mod; } } + f = g; } int ans = 0; for (int j = 0; j <= n; ++j) { - ans = (ans + f[n][j]) % mod; + ans = (ans + f[j]) % mod; } return ans; } -}; +} ``` ```cpp @@ -327,69 +455,6 @@ public: }; ``` -### **Go** - -```go -func numPermsDISequence(s string) (ans int) { - const mod = 1e9 + 7 - n := len(s) - f := make([][]int, n+1) - for i := range f { - f[i] = make([]int, n+1) - } - f[0][0] = 1 - for i := 1; i <= n; i++ { - if s[i-1] == 'D' { - for j := 0; j <= i; j++ { - for k := j; k < i; k++ { - f[i][j] = (f[i][j] + f[i-1][k]) % mod - } - } - } else { - for j := 0; j <= i; j++ { - for k := 0; k < j; k++ { - f[i][j] = (f[i][j] + f[i-1][k]) % mod - } - } - } - } - for j := 0; j <= n; j++ { - ans = (ans + f[n][j]) % mod - } - return -} -``` - -```go -func numPermsDISequence(s string) (ans int) { - const mod = 1e9 + 7 - n := len(s) - f := make([][]int, n+1) - for i := range f { - f[i] = make([]int, n+1) - } - f[0][0] = 1 - for i := 1; i <= n; i++ { - pre := 0 - if s[i-1] == 'D' { - for j := i; j >= 0; j-- { - pre = (pre + f[i-1][j]) % mod - f[i][j] = pre - } - } else { - for j := 0; j <= i; j++ { - f[i][j] = pre - pre = (pre + f[i-1][j]) % mod - } - } - } - for j := 0; j <= n; j++ { - ans = (ans + f[n][j]) % mod - } - return -} -``` - ```go func numPermsDISequence(s string) (ans int) { const mod = 1e9 + 7 @@ -419,69 +484,6 @@ func numPermsDISequence(s string) (ans int) { } ``` -### **TypeScript** - -```ts -function numPermsDISequence(s: string): number { - const n = s.length; - const f: number[][] = Array(n + 1) - .fill(0) - .map(() => Array(n + 1).fill(0)); - f[0][0] = 1; - const mod = 10 ** 9 + 7; - for (let i = 1; i <= n; ++i) { - if (s[i - 1] === 'D') { - for (let j = 0; j <= i; ++j) { - for (let k = j; k < i; ++k) { - f[i][j] = (f[i][j] + f[i - 1][k]) % mod; - } - } - } else { - for (let j = 0; j <= i; ++j) { - for (let k = 0; k < j; ++k) { - f[i][j] = (f[i][j] + f[i - 1][k]) % mod; - } - } - } - } - let ans = 0; - for (let j = 0; j <= n; ++j) { - ans = (ans + f[n][j]) % mod; - } - return ans; -} -``` - -```ts -function numPermsDISequence(s: string): number { - const n = s.length; - const f: number[][] = Array(n + 1) - .fill(0) - .map(() => Array(n + 1).fill(0)); - f[0][0] = 1; - const mod = 10 ** 9 + 7; - for (let i = 1; i <= n; ++i) { - let pre = 0; - if (s[i - 1] === 'D') { - for (let j = i; j >= 0; --j) { - pre = (pre + f[i - 1][j]) % mod; - f[i][j] = pre; - } - } else { - for (let j = 0; j <= i; ++j) { - f[i][j] = pre; - pre = (pre + f[i - 1][j]) % mod; - } - } - } - let ans = 0; - for (let j = 0; j <= n; ++j) { - ans = (ans + f[n][j]) % mod; - } - return ans; -} -``` - ```ts function numPermsDISequence(s: string): number { const n = s.length; @@ -512,10 +514,6 @@ function numPermsDISequence(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0904.Fruit Into Baskets/README.md b/solution/0900-0999/0904.Fruit Into Baskets/README.md index b9fadbfbc692d..91d4bf27356bf 100644 --- a/solution/0900-0999/0904.Fruit Into Baskets/README.md +++ b/solution/0900-0999/0904.Fruit Into Baskets/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:哈希表 + 滑动窗口** +### 方法一:哈希表 + 滑动窗口 我们用哈希表 $cnt$ 维护当前窗口内的水果种类以及对应的数量,用双指针 $j$ 和 $i$ 维护窗口的左右边界。 @@ -93,20 +91,8 @@ j i 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `fruits` 的长度。 -**方法二:滑动窗口优化** - -在方法一中,我们发现,窗口大小会时而变大,时而变小,这就需要我们每一次更新答案。 - -但本题实际上求的是水果的最大数目,也就是“最大”的窗口,我们没有必要缩小窗口,只需要让窗口单调增大。于是代码就少了每次更新答案的操作,只需要在遍历结束后将此时的窗口大小作为答案返回即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `fruits` 的长度。 - -### **Python3** - - - ```python class Solution: def totalFruit(self, fruits: List[int]) -> int: @@ -124,26 +110,6 @@ class Solution: return ans ``` -```python -class Solution: - def totalFruit(self, fruits: List[int]) -> int: - cnt = Counter() - j = 0 - for x in fruits: - cnt[x] += 1 - if len(cnt) > 2: - y = fruits[j] - cnt[y] -= 1 - if cnt[y] == 0: - cnt.pop(y) - j += 1 - return len(fruits) - j -``` - -### **Java** - - - ```java class Solution { public int totalFruit(int[] fruits) { @@ -166,28 +132,6 @@ class Solution { } ``` -```java -class Solution { - public int totalFruit(int[] fruits) { - Map cnt = new HashMap<>(); - int j = 0, n = fruits.length; - for (int x : fruits) { - cnt.put(x, cnt.getOrDefault(x, 0) + 1); - if (cnt.size() > 2) { - int y = fruits[j++]; - cnt.put(y, cnt.get(y) - 1); - if (cnt.get(y) == 0) { - cnt.remove(y); - } - } - } - return n - j; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -208,26 +152,6 @@ public: }; ``` -```cpp -class Solution { -public: - int totalFruit(vector& fruits) { - unordered_map cnt; - int j = 0, n = fruits.size(); - for (int& x : fruits) { - ++cnt[x]; - if (cnt.size() > 2) { - int y = fruits[j++]; - if (--cnt[y] == 0) cnt.erase(y); - } - } - return n - j; - } -}; -``` - -### **Go** - ```go func totalFruit(fruits []int) int { cnt := map[int]int{} @@ -247,27 +171,6 @@ func totalFruit(fruits []int) int { } ``` -```go -func totalFruit(fruits []int) int { - cnt := map[int]int{} - j := 0 - for _, x := range fruits { - cnt[x]++ - if len(cnt) > 2 { - y := fruits[j] - cnt[y]-- - if cnt[y] == 0 { - delete(cnt, y) - } - j++ - } - } - return len(fruits) - j -} -``` - -### **TypeScript** - ```ts function totalFruit(fruits: number[]): number { const n = fruits.length; @@ -291,27 +194,6 @@ function totalFruit(fruits: number[]): number { } ``` -```ts -function totalFruit(fruits: number[]): number { - const n = fruits.length; - const map = new Map(); - let i = 0; - for (const fruit of fruits) { - map.set(fruit, (map.get(fruit) ?? 0) + 1); - if (map.size > 2) { - const k = fruits[i++]; - map.set(k, map.get(k) - 1); - if (map.get(k) == 0) { - map.delete(k); - } - } - } - return n - i; -} -``` - -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -339,6 +221,110 @@ impl Solution { } ``` + + +### 方法二:滑动窗口优化 + +在方法一中,我们发现,窗口大小会时而变大,时而变小,这就需要我们每一次更新答案。 + +但本题实际上求的是水果的最大数目,也就是“最大”的窗口,我们没有必要缩小窗口,只需要让窗口单调增大。于是代码就少了每次更新答案的操作,只需要在遍历结束后将此时的窗口大小作为答案返回即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `fruits` 的长度。 + + + +```python +class Solution: + def totalFruit(self, fruits: List[int]) -> int: + cnt = Counter() + j = 0 + for x in fruits: + cnt[x] += 1 + if len(cnt) > 2: + y = fruits[j] + cnt[y] -= 1 + if cnt[y] == 0: + cnt.pop(y) + j += 1 + return len(fruits) - j +``` + +```java +class Solution { + public int totalFruit(int[] fruits) { + Map cnt = new HashMap<>(); + int j = 0, n = fruits.length; + for (int x : fruits) { + cnt.put(x, cnt.getOrDefault(x, 0) + 1); + if (cnt.size() > 2) { + int y = fruits[j++]; + cnt.put(y, cnt.get(y) - 1); + if (cnt.get(y) == 0) { + cnt.remove(y); + } + } + } + return n - j; + } +} +``` + +```cpp +class Solution { +public: + int totalFruit(vector& fruits) { + unordered_map cnt; + int j = 0, n = fruits.size(); + for (int& x : fruits) { + ++cnt[x]; + if (cnt.size() > 2) { + int y = fruits[j++]; + if (--cnt[y] == 0) cnt.erase(y); + } + } + return n - j; + } +}; +``` + +```go +func totalFruit(fruits []int) int { + cnt := map[int]int{} + j := 0 + for _, x := range fruits { + cnt[x]++ + if len(cnt) > 2 { + y := fruits[j] + cnt[y]-- + if cnt[y] == 0 { + delete(cnt, y) + } + j++ + } + } + return len(fruits) - j +} +``` + +```ts +function totalFruit(fruits: number[]): number { + const n = fruits.length; + const map = new Map(); + let i = 0; + for (const fruit of fruits) { + map.set(fruit, (map.get(fruit) ?? 0) + 1); + if (map.size > 2) { + const k = fruits[i++]; + map.set(k, map.get(k) - 1); + if (map.get(k) == 0) { + map.delete(k); + } + } + } + return n - i; +} +``` + ```rust use std::collections::HashMap; impl Solution { @@ -362,10 +348,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0904.Fruit Into Baskets/README_EN.md b/solution/0900-0999/0904.Fruit Into Baskets/README_EN.md index 7df4259b5996e..fde8214ada8de 100644 --- a/solution/0900-0999/0904.Fruit Into Baskets/README_EN.md +++ b/solution/0900-0999/0904.Fruit Into Baskets/README_EN.md @@ -53,7 +53,7 @@ If we had started at the first tree, we would only pick from trees [1,2]. ## Solutions -**Solution 1: Hash Table + Sliding Window** +### Solution 1: Hash Table + Sliding Window We use a hash table $cnt$ to maintain the types and corresponding quantities of fruits in the current window, and use two pointers $j$ and $i$ to maintain the left and right boundaries of the window. @@ -79,18 +79,8 @@ j i The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the `fruits` array. -**Solution 2: Sliding Window Optimization** - -In Solution 1, we find that the window size sometimes increases and sometimes decreases, which requires us to update the answer each time. - -But what this problem actually asks for is the maximum number of fruits, that is, the "largest" window. We don't need to shrink the window, we just need to let the window monotonically increase. So the code omits the operation of updating the answer each time, and only needs to return the size of the window as the answer after the traversal ends. - -The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the `fruits` array. - -### **Python3** - ```python class Solution: def totalFruit(self, fruits: List[int]) -> int: @@ -108,24 +98,6 @@ class Solution: return ans ``` -```python -class Solution: - def totalFruit(self, fruits: List[int]) -> int: - cnt = Counter() - j = 0 - for x in fruits: - cnt[x] += 1 - if len(cnt) > 2: - y = fruits[j] - cnt[y] -= 1 - if cnt[y] == 0: - cnt.pop(y) - j += 1 - return len(fruits) - j -``` - -### **Java** - ```java class Solution { public int totalFruit(int[] fruits) { @@ -148,28 +120,6 @@ class Solution { } ``` -```java -class Solution { - public int totalFruit(int[] fruits) { - Map cnt = new HashMap<>(); - int j = 0, n = fruits.length; - for (int x : fruits) { - cnt.put(x, cnt.getOrDefault(x, 0) + 1); - if (cnt.size() > 2) { - int y = fruits[j++]; - cnt.put(y, cnt.get(y) - 1); - if (cnt.get(y) == 0) { - cnt.remove(y); - } - } - } - return n - j; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -190,26 +140,6 @@ public: }; ``` -```cpp -class Solution { -public: - int totalFruit(vector& fruits) { - unordered_map cnt; - int j = 0, n = fruits.size(); - for (int& x : fruits) { - ++cnt[x]; - if (cnt.size() > 2) { - int y = fruits[j++]; - if (--cnt[y] == 0) cnt.erase(y); - } - } - return n - j; - } -}; -``` - -### **Go** - ```go func totalFruit(fruits []int) int { cnt := map[int]int{} @@ -229,27 +159,6 @@ func totalFruit(fruits []int) int { } ``` -```go -func totalFruit(fruits []int) int { - cnt := map[int]int{} - j := 0 - for _, x := range fruits { - cnt[x]++ - if len(cnt) > 2 { - y := fruits[j] - cnt[y]-- - if cnt[y] == 0 { - delete(cnt, y) - } - j++ - } - } - return len(fruits) - j -} -``` - -### **TypeScript** - ```ts function totalFruit(fruits: number[]): number { const n = fruits.length; @@ -273,27 +182,6 @@ function totalFruit(fruits: number[]): number { } ``` -```ts -function totalFruit(fruits: number[]): number { - const n = fruits.length; - const map = new Map(); - let i = 0; - for (const fruit of fruits) { - map.set(fruit, (map.get(fruit) ?? 0) + 1); - if (map.size > 2) { - const k = fruits[i++]; - map.set(k, map.get(k) - 1); - if (map.get(k) == 0) { - map.delete(k); - } - } - } - return n - i; -} -``` - -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -321,6 +209,110 @@ impl Solution { } ``` + + +### Solution 2: Sliding Window Optimization + +In Solution 1, we find that the window size sometimes increases and sometimes decreases, which requires us to update the answer each time. + +But what this problem actually asks for is the maximum number of fruits, that is, the "largest" window. We don't need to shrink the window, we just need to let the window monotonically increase. So the code omits the operation of updating the answer each time, and only needs to return the size of the window as the answer after the traversal ends. + +The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the `fruits` array. + + + +```python +class Solution: + def totalFruit(self, fruits: List[int]) -> int: + cnt = Counter() + j = 0 + for x in fruits: + cnt[x] += 1 + if len(cnt) > 2: + y = fruits[j] + cnt[y] -= 1 + if cnt[y] == 0: + cnt.pop(y) + j += 1 + return len(fruits) - j +``` + +```java +class Solution { + public int totalFruit(int[] fruits) { + Map cnt = new HashMap<>(); + int j = 0, n = fruits.length; + for (int x : fruits) { + cnt.put(x, cnt.getOrDefault(x, 0) + 1); + if (cnt.size() > 2) { + int y = fruits[j++]; + cnt.put(y, cnt.get(y) - 1); + if (cnt.get(y) == 0) { + cnt.remove(y); + } + } + } + return n - j; + } +} +``` + +```cpp +class Solution { +public: + int totalFruit(vector& fruits) { + unordered_map cnt; + int j = 0, n = fruits.size(); + for (int& x : fruits) { + ++cnt[x]; + if (cnt.size() > 2) { + int y = fruits[j++]; + if (--cnt[y] == 0) cnt.erase(y); + } + } + return n - j; + } +}; +``` + +```go +func totalFruit(fruits []int) int { + cnt := map[int]int{} + j := 0 + for _, x := range fruits { + cnt[x]++ + if len(cnt) > 2 { + y := fruits[j] + cnt[y]-- + if cnt[y] == 0 { + delete(cnt, y) + } + j++ + } + } + return len(fruits) - j +} +``` + +```ts +function totalFruit(fruits: number[]): number { + const n = fruits.length; + const map = new Map(); + let i = 0; + for (const fruit of fruits) { + map.set(fruit, (map.get(fruit) ?? 0) + 1); + if (map.size > 2) { + const k = fruits[i++]; + map.set(k, map.get(k) - 1); + if (map.get(k) == 0) { + map.delete(k); + } + } + } + return n - i; +} +``` + ```rust use std::collections::HashMap; impl Solution { @@ -344,10 +336,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0905.Sort Array By Parity/README.md b/solution/0900-0999/0905.Sort Array By Parity/README.md index a4cb1477e3919..96e8b2a0b7b1b 100644 --- a/solution/0900-0999/0905.Sort Array By Parity/README.md +++ b/solution/0900-0999/0905.Sort Array By Parity/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们用两个指针 $i$ 和 $j$ 分别指向数组的首尾,当 $i < j$ 时,执行以下操作。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: @@ -73,10 +67,6 @@ class Solution: return nums ``` -### **Java** - - - ```java class Solution { public int[] sortArrayByParity(int[] nums) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func sortArrayByParity(nums []int) []int { for i, j := 0, len(nums)-1; i < j; { @@ -137,7 +123,22 @@ func sortArrayByParity(nums []int) []int { } ``` -### **Rust** +```ts +function sortArrayByParity(nums: number[]): number[] { + for (let i = 0, j = nums.length - 1; i < j; ) { + if (nums[i] % 2 === 0) { + ++i; + } else if (nums[j] % 2 === 1) { + --j; + } else { + [nums[i], nums[j]] = [nums[j], nums[i]]; + ++i; + --j; + } + } + return nums; +} +``` ```rust impl Solution { @@ -159,27 +160,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function sortArrayByParity(nums: number[]): number[] { - for (let i = 0, j = nums.length - 1; i < j; ) { - if (nums[i] % 2 === 0) { - ++i; - } else if (nums[j] % 2 === 1) { - --j; - } else { - [nums[i], nums[j]] = [nums[j], nums[i]]; - ++i; - --j; - } - } - return nums; -} -``` - -### **JavaScript** - ```js /** * @param {number[]} nums @@ -201,10 +181,6 @@ var sortArrayByParity = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0905.Sort Array By Parity/README_EN.md b/solution/0900-0999/0905.Sort Array By Parity/README_EN.md index ec74765888260..f3784bc5cba01 100644 --- a/solution/0900-0999/0905.Sort Array By Parity/README_EN.md +++ b/solution/0900-0999/0905.Sort Array By Parity/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We use two pointers $i$ and $j$ to point to the beginning and end of the array respectively. When $i < j$, we perform the following operations. @@ -48,8 +48,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: @@ -65,8 +63,6 @@ class Solution: return nums ``` -### **Java** - ```java class Solution { public int[] sortArrayByParity(int[] nums) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func sortArrayByParity(nums []int) []int { for i, j := 0, len(nums)-1; i < j; { @@ -127,7 +119,22 @@ func sortArrayByParity(nums []int) []int { } ``` -### **Rust** +```ts +function sortArrayByParity(nums: number[]): number[] { + for (let i = 0, j = nums.length - 1; i < j; ) { + if (nums[i] % 2 === 0) { + ++i; + } else if (nums[j] % 2 === 1) { + --j; + } else { + [nums[i], nums[j]] = [nums[j], nums[i]]; + ++i; + --j; + } + } + return nums; +} +``` ```rust impl Solution { @@ -149,27 +156,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function sortArrayByParity(nums: number[]): number[] { - for (let i = 0, j = nums.length - 1; i < j; ) { - if (nums[i] % 2 === 0) { - ++i; - } else if (nums[j] % 2 === 1) { - --j; - } else { - [nums[i], nums[j]] = [nums[j], nums[i]]; - ++i; - --j; - } - } - return nums; -} -``` - -### **JavaScript** - ```js /** * @param {number[]} nums @@ -191,10 +177,6 @@ var sortArrayByParity = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0906.Super Palindromes/README.md b/solution/0900-0999/0906.Super Palindromes/README.md index ef3a78b8e6d06..508c4ce5f95e8 100644 --- a/solution/0900-0999/0906.Super Palindromes/README.md +++ b/solution/0900-0999/0906.Super Palindromes/README.md @@ -35,30 +35,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0900-0999/0906.Super Palindromes/README_EN.md b/solution/0900-0999/0906.Super Palindromes/README_EN.md index a65ace4a3027d..e86b5e137454a 100644 --- a/solution/0900-0999/0906.Super Palindromes/README_EN.md +++ b/solution/0900-0999/0906.Super Palindromes/README_EN.md @@ -38,24 +38,4 @@ Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrom ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0900-0999/0907.Sum of Subarray Minimums/README.md b/solution/0900-0999/0907.Sum of Subarray Minimums/README.md index 2b76c6613e867..19d2d80958c48 100644 --- a/solution/0900-0999/0907.Sum of Subarray Minimums/README.md +++ b/solution/0900-0999/0907.Sum of Subarray Minimums/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 题目要求的是每个子数组的最小值之和,实际上相当于,对于每个元素 $arr[i]$,求以 $arr[i]$ 为最小值的子数组的个数,然后乘以 $arr[i]$,最后求和。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def sumSubarrayMins(self, arr: List[int]) -> int: @@ -106,10 +100,6 @@ class Solution: return sum((i - left[i]) * (right[i] - i) * v for i, v in enumerate(arr)) % mod ``` -### **Java** - - - ```java class Solution { public int sumSubarrayMins(int[] arr) { @@ -149,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -189,8 +177,6 @@ public: }; ``` -### **Go** - ```go func sumSubarrayMins(arr []int) (ans int) { n := len(arr) @@ -229,8 +215,6 @@ func sumSubarrayMins(arr []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumSubarrayMins(arr: number[]): number { const n: number = arr.length; @@ -268,8 +252,6 @@ function sumSubarrayMins(arr: number[]): number { } ``` -### **Rust** - ```rust use std::collections::VecDeque; @@ -314,6 +296,12 @@ impl Solution { } ``` + + +### 方法二 + + + ```rust const MOD: i64 = (1e9 as i64) + 7; @@ -365,10 +353,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0907.Sum of Subarray Minimums/README_EN.md b/solution/0900-0999/0907.Sum of Subarray Minimums/README_EN.md index b085c03437199..364801546dacc 100644 --- a/solution/0900-0999/0907.Sum of Subarray Minimums/README_EN.md +++ b/solution/0900-0999/0907.Sum of Subarray Minimums/README_EN.md @@ -35,54 +35,10 @@ Sum is 17. ## Solutions -The problem asks for the sum of the minimum values of each subarray, which is actually equivalent to finding the number of subarrays for each element $arr[i]$ where $arr[i]$ is the minimum, multiplying each by $arr[i]$, and then summing these products. - -Thus, the focus of the problem is translated to finding the number of subarrays for which $arr[i]$ is the minimum. - -For each $arr[i]$, we identify the first position $left[i]$ to its left that is smaller than $arr[i]$ and the first position $right[i]$ to its right that is less than or equal to $arr[i]$. - -The number of subarrays where $arr[i]$ is the minimum can then be given by $(i - left[i]) \times (right[i] - i)$. - -It's important to note why we are looking for the first position $right[i]$ that is less than or equal to $arr[i]$ and not less than $arr[i]$. - -If we were to look for the first position less than $arr[i]$, we would end up double-counting. - -For instance, consider the following array: - -The element at index $3$ is $2$, and the first element less than $2$ to its left is at index $0$. If we find the first element less than $2$ to its right, we would end up at index $7$. That means the subarray interval is $(0, 7)$. Note that this is an open interval. - -``` -0 4 3 2 5 3 2 1 -* ^ * -``` - -If we calculate the subarray interval for the element at index $6$ using the same method, we would find that its interval is also $(0, 7)$. - -``` -0 4 3 2 5 3 2 1 -* ^ * -``` - -Therefore, the subarray intervals of the elements at index $3$ and $6$ are overlapping, leading to double-counting. - -If we were to find the first element less than or equal to $arr[i]$ to its right, we wouldn't have this problem. - -The subarray interval for the element at index $3$ would become $(0, 6)$ and for the element at index $6$ it would be $(0, 7)$, and these two are not overlapping. - -To solve this problem, we just need to traverse the array. - -For each element $arr[i]$, we use a monotonic stack to find its $left[i]$ and $right[i]$. - -Then the number of subarrays where $arr[i]$ is the minimum can be calculated by $(i - left[i]) \times (right[i] - i)$. Multiply this by $arr[i]$ and sum these values for all $i$ to get the final answer. - -Remember to take care of data overflow and modulus operation. - -The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array $arr$. +### Solution 1 -### **Python3** - ```python class Solution: def sumSubarrayMins(self, arr: List[int]) -> int: @@ -108,8 +64,6 @@ class Solution: return sum((i - left[i]) * (right[i] - i) * v for i, v in enumerate(arr)) % mod ``` -### **Java** - ```java class Solution { public int sumSubarrayMins(int[] arr) { @@ -149,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -189,8 +141,6 @@ public: }; ``` -### **Go** - ```go func sumSubarrayMins(arr []int) (ans int) { n := len(arr) @@ -229,8 +179,6 @@ func sumSubarrayMins(arr []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumSubarrayMins(arr: number[]): number { const n: number = arr.length; @@ -268,8 +216,6 @@ function sumSubarrayMins(arr: number[]): number { } ``` -### **Rust** - ```rust use std::collections::VecDeque; @@ -314,6 +260,12 @@ impl Solution { } ``` + + +### Solution 2 + + + ```rust const MOD: i64 = (1e9 as i64) + 7; @@ -365,10 +317,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0908.Smallest Range I/README.md b/solution/0900-0999/0908.Smallest Range I/README.md index dbf604ee77ce9..b1419de76c644 100644 --- a/solution/0900-0999/0908.Smallest Range I/README.md +++ b/solution/0900-0999/0908.Smallest Range I/README.md @@ -52,14 +52,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def smallestRangeI(self, nums: List[int], k: int) -> int: @@ -67,10 +63,6 @@ class Solution: return max(0, mx - mi - k * 2) ``` -### **Java** - - - ```java class Solution { public int smallestRangeI(int[] nums, int k) { @@ -85,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +87,6 @@ public: }; ``` -### **Go** - ```go func smallestRangeI(nums []int, k int) int { mi, mx := slices.Min(nums), slices.Max(nums) @@ -106,8 +94,6 @@ func smallestRangeI(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function smallestRangeI(nums: number[], k: number): number { const max = nums.reduce((r, v) => Math.max(r, v)); @@ -116,8 +102,6 @@ function smallestRangeI(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn smallest_range_i(nums: Vec, k: i32) -> i32 { @@ -128,10 +112,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0908.Smallest Range I/README_EN.md b/solution/0900-0999/0908.Smallest Range I/README_EN.md index 87953cda8851f..807448bfc0029 100644 --- a/solution/0900-0999/0908.Smallest Range I/README_EN.md +++ b/solution/0900-0999/0908.Smallest Range I/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return max(0, mx - mi - k * 2) ``` -### **Java** - ```java class Solution { public int smallestRangeI(int[] nums, int k) { @@ -75,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +83,6 @@ public: }; ``` -### **Go** - ```go func smallestRangeI(nums []int, k int) int { mi, mx := slices.Min(nums), slices.Max(nums) @@ -96,8 +90,6 @@ func smallestRangeI(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function smallestRangeI(nums: number[], k: number): number { const max = nums.reduce((r, v) => Math.max(r, v)); @@ -106,8 +98,6 @@ function smallestRangeI(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn smallest_range_i(nums: Vec, k: i32) -> i32 { @@ -118,10 +108,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0909.Snakes and Ladders/README.md b/solution/0900-0999/0909.Snakes and Ladders/README.md index 872104c858daf..8427632bd9832 100644 --- a/solution/0900-0999/0909.Snakes and Ladders/README.md +++ b/solution/0900-0999/0909.Snakes and Ladders/README.md @@ -68,16 +68,10 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS -### **Python3** - - - ```python class Solution: def snakesAndLadders(self, board: List[List[int]]) -> int: @@ -107,10 +101,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { private int n; @@ -156,8 +146,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -198,8 +186,6 @@ public: }; ``` -### **Go** - ```go func snakesAndLadders(board [][]int) int { n := len(board) @@ -240,10 +226,6 @@ func snakesAndLadders(board [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0909.Snakes and Ladders/README_EN.md b/solution/0900-0999/0909.Snakes and Ladders/README_EN.md index 538ead5197f94..eaf45f0f55a18 100644 --- a/solution/0900-0999/0909.Snakes and Ladders/README_EN.md +++ b/solution/0900-0999/0909.Snakes and Ladders/README_EN.md @@ -62,12 +62,10 @@ This is the lowest possible number of moves to reach the last square, so return ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def snakesAndLadders(self, board: List[List[int]]) -> int: @@ -97,8 +95,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { private int n; @@ -144,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -186,8 +180,6 @@ public: }; ``` -### **Go** - ```go func snakesAndLadders(board [][]int) int { n := len(board) @@ -228,10 +220,6 @@ func snakesAndLadders(board [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0910.Smallest Range II/README.md b/solution/0900-0999/0910.Smallest Range II/README.md index 3eeb21c3fd5e5..31fee43f06b71 100644 --- a/solution/0900-0999/0910.Smallest Range II/README.md +++ b/solution/0900-0999/0910.Smallest Range II/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:贪心 + 枚举** +### 方法一:贪心 + 枚举 根据题目要求,我们需要求数组中的元素最大值与最小值差值的最小值。每个元素可以加上或者减去 $k$,因此我们可以将数组中的元素分为两部分,一部分加上 $k$,一部分减去 $k$。那么,我们应该将数组中的较大值减去 $k$,较小值加上 $k$,这样才能保证最大值与最小值的差值最小。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def smallestRangeII(self, nums: List[int], k: int) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int smallestRangeII(int[] nums, int k) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func smallestRangeII(nums []int, k int) int { sort.Ints(nums) @@ -138,10 +124,6 @@ func smallestRangeII(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0910.Smallest Range II/README_EN.md b/solution/0900-0999/0910.Smallest Range II/README_EN.md index 28a1510be5eac..95771770abd47 100644 --- a/solution/0900-0999/0910.Smallest Range II/README_EN.md +++ b/solution/0900-0999/0910.Smallest Range II/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int smallestRangeII(int[] nums, int k) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +97,6 @@ public: }; ``` -### **Go** - ```go func smallestRangeII(nums []int, k int) int { sort.Ints(nums) @@ -117,10 +111,6 @@ func smallestRangeII(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0911.Online Election/README.md b/solution/0900-0999/0911.Online Election/README.md index e745b47e8e183..630f0f769c16a 100644 --- a/solution/0900-0999/0911.Online Election/README.md +++ b/solution/0900-0999/0911.Online Election/README.md @@ -55,20 +55,10 @@ topVotedCandidate.q(8); // 返回 1 ## 解法 - - -二分查找。 - -先预处理得到每个时刻的领先的候选人编号 `wins[i]`。 - -然后对于每次查询 q,二分查找得到小于等于 t 时刻的最大时刻 left,返回 `wins[left]` 即可。 +### 方法一 -### **Python3** - - - ```python class TopVotedCandidate: def __init__(self, persons: List[int], times: List[int]): @@ -98,10 +88,6 @@ class TopVotedCandidate: # param_1 = obj.q(t) ``` -### **Java** - - - ```java class TopVotedCandidate { private int[] times; @@ -143,8 +129,6 @@ class TopVotedCandidate { */ ``` -### **C++** - ```cpp class TopVotedCandidate { public: @@ -187,8 +171,6 @@ public: */ ``` -### **Go** - ```go type TopVotedCandidate struct { times []int @@ -230,10 +212,6 @@ func (this *TopVotedCandidate) Q(t int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0911.Online Election/README_EN.md b/solution/0900-0999/0911.Online Election/README_EN.md index f7cad2f4ef94e..a59e2b63513f7 100644 --- a/solution/0900-0999/0911.Online Election/README_EN.md +++ b/solution/0900-0999/0911.Online Election/README_EN.md @@ -51,12 +51,10 @@ topVotedCandidate.q(8); // return 1 ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python class TopVotedCandidate: def __init__(self, persons: List[int], times: List[int]): @@ -86,40 +84,37 @@ class TopVotedCandidate: # param_1 = obj.q(t) ``` -### **Java** - ```java class TopVotedCandidate { private int[] times; - private int[] wins; + private int[] winPersons; public TopVotedCandidate(int[] persons, int[] times) { - int n = persons.length; - int mx = 0, cur = 0; this.times = times; - wins = new int[n]; - int[] counter = new int[n]; + int mx = -1, curWin = -1; + int n = persons.length; + int[] counter = new int[n + 1]; + winPersons = new int[n]; for (int i = 0; i < n; ++i) { - int p = persons[i]; - if (++counter[p] >= mx) { - mx = counter[p]; - cur = p; + if (++counter[persons[i]] >= mx) { + mx = counter[persons[i]]; + curWin = persons[i]; } - wins[i] = cur; + winPersons[i] = curWin; } } public int q(int t) { - int left = 0, right = wins.length - 1; + int left = 0, right = winPersons.length - 1; while (left < right) { - int mid = (left + right + 1) >>> 1; + int mid = (left + right + 1) >> 1; if (times[mid] <= t) { left = mid; } else { right = mid - 1; } } - return wins[left]; + return winPersons[left]; } } @@ -130,8 +125,6 @@ class TopVotedCandidate { */ ``` -### **C++** - ```cpp class TopVotedCandidate { public: @@ -174,8 +167,6 @@ public: */ ``` -### **Go** - ```go type TopVotedCandidate struct { times []int @@ -217,10 +208,6 @@ func (this *TopVotedCandidate) Q(t int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0912.Sort an Array/README.md b/solution/0900-0999/0912.Sort an Array/README.md index 5aef194af814f..be75fb2f92732 100644 --- a/solution/0900-0999/0912.Sort an Array/README.md +++ b/solution/0900-0999/0912.Sort an Array/README.md @@ -38,28 +38,14 @@ ## 解法 - - -**方法一:快速排序** +### 方法一:快速排序 快速排序是一种高效的排序算法。它的基本思想是通过一趟排序将待排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组长度。 -**方法二:归并排序** - -归并排序是一种分治算法,其思想是将待排序的数据序列不断地折半拆分,直到每个数据块只有一个元素为止,然后再按照拆分的顺序将每个数据块两两合并,在合并的过程中进行排序,最终得到一个有序的数据序列。 - -归并排序是一种稳定的排序算法,时间复杂度为 $O(n \times \log n)$,空间复杂度为 $O(n)$。其中 $n$ 为数组长度。 - -### **Python3** - - - -快速排序: - ```python class Solution: def sortArray(self, nums: List[int]) -> List[int]: @@ -84,43 +70,6 @@ class Solution: return nums ``` -归并排序: - -```python -class Solution: - def sortArray(self, nums: List[int]) -> List[int]: - def merge_sort(l, r): - if l >= r: - return - mid = (l + r) >> 1 - merge_sort(l, mid) - merge_sort(mid + 1, r) - i, j = l, mid + 1 - tmp = [] - while i <= mid and j <= r: - if nums[i] <= nums[j]: - tmp.append(nums[i]) - i += 1 - else: - tmp.append(nums[j]) - j += 1 - if i <= mid: - tmp.extend(nums[i : mid + 1]) - if j <= r: - tmp.extend(nums[j : r + 1]) - for i in range(l, r + 1): - nums[i] = tmp[i - l] - - merge_sort(0, len(nums) - 1) - return nums -``` - -### **Java** - - - -快速排序: - ```java class Solution { private int[] nums; @@ -154,6 +103,161 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector sortArray(vector& nums) { + function quick_sort = [&](int l, int r) { + if (l >= r) { + return; + } + int i = l - 1, j = r + 1; + int x = nums[(l + r) >> 1]; + while (i < j) { + while (nums[++i] < x) { + } + while (nums[--j] > x) { + } + if (i < j) { + swap(nums[i], nums[j]); + } + } + quick_sort(l, j); + quick_sort(j + 1, r); + }; + quick_sort(0, nums.size() - 1); + return nums; + } +}; +``` + +```go +func sortArray(nums []int) []int { + quickSort(nums, 0, len(nums)-1) + return nums +} + +func quickSort(nums []int, l, r int) { + if l >= r { + return + } + i, j := l-1, r+1 + x := nums[(l+r)>>1] + for i < j { + for { + i++ + if nums[i] >= x { + break + } + } + for { + j-- + if nums[j] <= x { + break + } + } + if i < j { + nums[i], nums[j] = nums[j], nums[i] + } + } + quickSort(nums, l, j) + quickSort(nums, j+1, r) +} +``` + +```ts +function sortArray(nums: number[]): number[] { + function quickSort(l: number, r: number) { + if (l >= r) { + return; + } + let i = l - 1; + let j = r + 1; + const x = nums[(l + r) >> 1]; + while (i < j) { + while (nums[++i] < x); + while (nums[--j] > x); + if (i < j) { + [nums[i], nums[j]] = [nums[j], nums[i]]; + } + } + quickSort(l, j); + quickSort(j + 1, r); + } + const n = nums.length; + quickSort(0, n - 1); + return nums; +} +``` + +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var sortArray = function (nums) { + function quickSort(l, r) { + if (l >= r) { + return; + } + let i = l - 1; + let j = r + 1; + const x = nums[(l + r) >> 1]; + while (i < j) { + while (nums[++i] < x); + while (nums[--j] > x); + if (i < j) { + [nums[i], nums[j]] = [nums[j], nums[i]]; + } + } + quickSort(l, j); + quickSort(j + 1, r); + } + const n = nums.length; + quickSort(0, n - 1); + return nums; +}; +``` + + + +### 方法二:归并排序 + +归并排序是一种分治算法,其思想是将待排序的数据序列不断地折半拆分,直到每个数据块只有一个元素为止,然后再按照拆分的顺序将每个数据块两两合并,在合并的过程中进行排序,最终得到一个有序的数据序列。 + +归并排序是一种稳定的排序算法,时间复杂度为 $O(n \times \log n)$,空间复杂度为 $O(n)$。其中 $n$ 为数组长度。 + + + +```python +class Solution: + def sortArray(self, nums: List[int]) -> List[int]: + def merge_sort(l, r): + if l >= r: + return + mid = (l + r) >> 1 + merge_sort(l, mid) + merge_sort(mid + 1, r) + i, j = l, mid + 1 + tmp = [] + while i <= mid and j <= r: + if nums[i] <= nums[j]: + tmp.append(nums[i]) + i += 1 + else: + tmp.append(nums[j]) + j += 1 + if i <= mid: + tmp.extend(nums[i : mid + 1]) + if j <= r: + tmp.extend(nums[j : r + 1]) + for i in range(l, r + 1): + nums[i] = tmp[i - l] + + merge_sort(0, len(nums) - 1) + return nums +``` + ```java class Solution { private int[] nums; @@ -191,81 +295,6 @@ class Solution { } ``` -归并排序: - -```java -class Solution { - private int[] nums; - - public int[] sortArray(int[] nums) { - this.nums = nums; - mergeSort(0, nums.length - 1); - return nums; - } - - private void mergeSort(int l, int r) { - if (l >= r) { - return; - } - int mid = (l + r) >> 1; - mergeSort(l, mid); - mergeSort(mid + 1, r); - int i = l, j = mid + 1, k = 0; - int[] tmp = new int[r - l + 1]; - while (i <= mid && j <= r) { - if (nums[i] <= nums[j]) { - tmp[k++] = nums[i++]; - } else { - tmp[k++] = nums[j++]; - } - } - while (i <= mid) { - tmp[k++] = nums[i++]; - } - while (j <= r) { - tmp[k++] = nums[j++]; - } - for (i = l; i <= r; ++i) { - nums[i] = tmp[i - l]; - } - } -} -``` - -### **C++** - -快速排序: - -```cpp -class Solution { -public: - vector sortArray(vector& nums) { - function quick_sort = [&](int l, int r) { - if (l >= r) { - return; - } - int i = l - 1, j = r + 1; - int x = nums[(l + r) >> 1]; - while (i < j) { - while (nums[++i] < x) { - } - while (nums[--j] > x) { - } - if (i < j) { - swap(nums[i], nums[j]); - } - } - quick_sort(l, j); - quick_sort(j + 1, r); - }; - quick_sort(0, nums.size() - 1); - return nums; - } -}; -``` - -归并排序: - ```cpp class Solution { public: @@ -302,46 +331,6 @@ public: }; ``` -### **Go** - -快速排序: - -```go -func sortArray(nums []int) []int { - quickSort(nums, 0, len(nums)-1) - return nums -} - -func quickSort(nums []int, l, r int) { - if l >= r { - return - } - i, j := l-1, r+1 - x := nums[(l+r)>>1] - for i < j { - for { - i++ - if nums[i] >= x { - break - } - } - for { - j-- - if nums[j] <= x { - break - } - } - if i < j { - nums[i], nums[j] = nums[j], nums[i] - } - } - quickSort(nums, l, j) - quickSort(nums, j+1, r) -} -``` - -归并排序: - ```go func sortArray(nums []int) []int { mergeSort(nums, 0, len(nums)-1) @@ -381,37 +370,6 @@ func mergeSort(nums []int, l, r int) { } ``` -### **TypeScript** - -快速排序: - -```ts -function sortArray(nums: number[]): number[] { - function quickSort(l: number, r: number) { - if (l >= r) { - return; - } - let i = l - 1; - let j = r + 1; - const x = nums[(l + r) >> 1]; - while (i < j) { - while (nums[++i] < x); - while (nums[--j] > x); - if (i < j) { - [nums[i], nums[j]] = [nums[j], nums[i]]; - } - } - quickSort(l, j); - quickSort(j + 1, r); - } - const n = nums.length; - quickSort(0, n - 1); - return nums; -} -``` - -归并排序: - ```ts function sortArray(nums: number[]): number[] { function mergetSort(l: number, r: number) { @@ -446,41 +404,6 @@ function sortArray(nums: number[]): number[] { } ``` -### **JavaScript** - -快速排序: - -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var sortArray = function (nums) { - function quickSort(l, r) { - if (l >= r) { - return; - } - let i = l - 1; - let j = r + 1; - const x = nums[(l + r) >> 1]; - while (i < j) { - while (nums[++i] < x); - while (nums[--j] > x); - if (i < j) { - [nums[i], nums[j]] = [nums[j], nums[i]]; - } - } - quickSort(l, j); - quickSort(j + 1, r); - } - const n = nums.length; - quickSort(0, n - 1); - return nums; -}; -``` - -归并排序: - ```js /** * @param {number[]} nums @@ -519,10 +442,51 @@ var sortArray = function (nums) { }; ``` -### **...** + -``` +### 方法三 + + +```java +class Solution { + private int[] nums; + + public int[] sortArray(int[] nums) { + this.nums = nums; + mergeSort(0, nums.length - 1); + return nums; + } + + private void mergeSort(int l, int r) { + if (l >= r) { + return; + } + int mid = (l + r) >> 1; + mergeSort(l, mid); + mergeSort(mid + 1, r); + int i = l, j = mid + 1, k = 0; + int[] tmp = new int[r - l + 1]; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j]) { + tmp[k++] = nums[i++]; + } else { + tmp[k++] = nums[j++]; + } + } + while (i <= mid) { + tmp[k++] = nums[i++]; + } + while (j <= r) { + tmp[k++] = nums[j++]; + } + for (i = l; i <= r; ++i) { + nums[i] = tmp[i - l]; + } + } +} ``` + + diff --git a/solution/0900-0999/0912.Sort an Array/README_EN.md b/solution/0900-0999/0912.Sort an Array/README_EN.md index b3316bdf429cb..85ae9765f2eaa 100644 --- a/solution/0900-0999/0912.Sort an Array/README_EN.md +++ b/solution/0900-0999/0912.Sort an Array/README_EN.md @@ -35,11 +35,9 @@ ## Solutions - - -### **Python3** +### Solution 1 -Quick Sort: + ```python class Solution: @@ -65,41 +63,6 @@ class Solution: return nums ``` -Merge Sort: - -```python -class Solution: - def sortArray(self, nums: List[int]) -> List[int]: - def merge_sort(l, r): - if l >= r: - return - mid = (l + r) >> 1 - merge_sort(l, mid) - merge_sort(mid + 1, r) - i, j = l, mid + 1 - tmp = [] - while i <= mid and j <= r: - if nums[i] <= nums[j]: - tmp.append(nums[i]) - i += 1 - else: - tmp.append(nums[j]) - j += 1 - if i <= mid: - tmp.extend(nums[i : mid + 1]) - if j <= r: - tmp.extend(nums[j : r + 1]) - for i in range(l, r + 1): - nums[i] = tmp[i - l] - - merge_sort(0, len(nums) - 1) - return nums -``` - -### **Java** - -Quick Sort: - ```java class Solution { private int[] nums; @@ -133,6 +96,157 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector sortArray(vector& nums) { + function quick_sort = [&](int l, int r) { + if (l >= r) { + return; + } + int i = l - 1, j = r + 1; + int x = nums[(l + r) >> 1]; + while (i < j) { + while (nums[++i] < x) { + } + while (nums[--j] > x) { + } + if (i < j) { + swap(nums[i], nums[j]); + } + } + quick_sort(l, j); + quick_sort(j + 1, r); + }; + quick_sort(0, nums.size() - 1); + return nums; + } +}; +``` + +```go +func sortArray(nums []int) []int { + quickSort(nums, 0, len(nums)-1) + return nums +} + +func quickSort(nums []int, l, r int) { + if l >= r { + return + } + i, j := l-1, r+1 + x := nums[(l+r)>>1] + for i < j { + for { + i++ + if nums[i] >= x { + break + } + } + for { + j-- + if nums[j] <= x { + break + } + } + if i < j { + nums[i], nums[j] = nums[j], nums[i] + } + } + quickSort(nums, l, j) + quickSort(nums, j+1, r) +} +``` + +```ts +function sortArray(nums: number[]): number[] { + function quickSort(l: number, r: number) { + if (l >= r) { + return; + } + let i = l - 1; + let j = r + 1; + const x = nums[(l + r) >> 1]; + while (i < j) { + while (nums[++i] < x); + while (nums[--j] > x); + if (i < j) { + [nums[i], nums[j]] = [nums[j], nums[i]]; + } + } + quickSort(l, j); + quickSort(j + 1, r); + } + const n = nums.length; + quickSort(0, n - 1); + return nums; +} +``` + +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var sortArray = function (nums) { + function quickSort(l, r) { + if (l >= r) { + return; + } + let i = l - 1; + let j = r + 1; + const x = nums[(l + r) >> 1]; + while (i < j) { + while (nums[++i] < x); + while (nums[--j] > x); + if (i < j) { + [nums[i], nums[j]] = [nums[j], nums[i]]; + } + } + quickSort(l, j); + quickSort(j + 1, r); + } + const n = nums.length; + quickSort(0, n - 1); + return nums; +}; +``` + + + +### Solution 2 + + + +```python +class Solution: + def sortArray(self, nums: List[int]) -> List[int]: + def merge_sort(l, r): + if l >= r: + return + mid = (l + r) >> 1 + merge_sort(l, mid) + merge_sort(mid + 1, r) + i, j = l, mid + 1 + tmp = [] + while i <= mid and j <= r: + if nums[i] <= nums[j]: + tmp.append(nums[i]) + i += 1 + else: + tmp.append(nums[j]) + j += 1 + if i <= mid: + tmp.extend(nums[i : mid + 1]) + if j <= r: + tmp.extend(nums[j : r + 1]) + for i in range(l, r + 1): + nums[i] = tmp[i - l] + + merge_sort(0, len(nums) - 1) + return nums +``` + ```java class Solution { private int[] nums; @@ -170,81 +284,6 @@ class Solution { } ``` -Merge Sort: - -```java -class Solution { - private int[] nums; - - public int[] sortArray(int[] nums) { - this.nums = nums; - mergeSort(0, nums.length - 1); - return nums; - } - - private void mergeSort(int l, int r) { - if (l >= r) { - return; - } - int mid = (l + r) >> 1; - mergeSort(l, mid); - mergeSort(mid + 1, r); - int i = l, j = mid + 1, k = 0; - int[] tmp = new int[r - l + 1]; - while (i <= mid && j <= r) { - if (nums[i] <= nums[j]) { - tmp[k++] = nums[i++]; - } else { - tmp[k++] = nums[j++]; - } - } - while (i <= mid) { - tmp[k++] = nums[i++]; - } - while (j <= r) { - tmp[k++] = nums[j++]; - } - for (i = l; i <= r; ++i) { - nums[i] = tmp[i - l]; - } - } -} -``` - -### **C++** - -Quick Sort: - -```cpp -class Solution { -public: - vector sortArray(vector& nums) { - function quick_sort = [&](int l, int r) { - if (l >= r) { - return; - } - int i = l - 1, j = r + 1; - int x = nums[(l + r) >> 1]; - while (i < j) { - while (nums[++i] < x) { - } - while (nums[--j] > x) { - } - if (i < j) { - swap(nums[i], nums[j]); - } - } - quick_sort(l, j); - quick_sort(j + 1, r); - }; - quick_sort(0, nums.size() - 1); - return nums; - } -}; -``` - -Merge Sort: - ```cpp class Solution { public: @@ -281,46 +320,6 @@ public: }; ``` -### **Go** - -Quick Sort: - -```go -func sortArray(nums []int) []int { - quickSort(nums, 0, len(nums)-1) - return nums -} - -func quickSort(nums []int, l, r int) { - if l >= r { - return - } - i, j := l-1, r+1 - x := nums[(l+r)>>1] - for i < j { - for { - i++ - if nums[i] >= x { - break - } - } - for { - j-- - if nums[j] <= x { - break - } - } - if i < j { - nums[i], nums[j] = nums[j], nums[i] - } - } - quickSort(nums, l, j) - quickSort(nums, j+1, r) -} -``` - -Merge Sort: - ```go func sortArray(nums []int) []int { mergeSort(nums, 0, len(nums)-1) @@ -360,37 +359,6 @@ func mergeSort(nums []int, l, r int) { } ``` -### **TypeScript** - -Quick Sort: - -```ts -function sortArray(nums: number[]): number[] { - function quickSort(l: number, r: number) { - if (l >= r) { - return; - } - let i = l - 1; - let j = r + 1; - const x = nums[(l + r) >> 1]; - while (i < j) { - while (nums[++i] < x); - while (nums[--j] > x); - if (i < j) { - [nums[i], nums[j]] = [nums[j], nums[i]]; - } - } - quickSort(l, j); - quickSort(j + 1, r); - } - const n = nums.length; - quickSort(0, n - 1); - return nums; -} -``` - -Merge Sort: - ```ts function sortArray(nums: number[]): number[] { function mergetSort(l: number, r: number) { @@ -425,41 +393,6 @@ function sortArray(nums: number[]): number[] { } ``` -### **JavaScript** - -Quick Sort: - -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var sortArray = function (nums) { - function quickSort(l, r) { - if (l >= r) { - return; - } - let i = l - 1; - let j = r + 1; - const x = nums[(l + r) >> 1]; - while (i < j) { - while (nums[++i] < x); - while (nums[--j] > x); - if (i < j) { - [nums[i], nums[j]] = [nums[j], nums[i]]; - } - } - quickSort(l, j); - quickSort(j + 1, r); - } - const n = nums.length; - quickSort(0, n - 1); - return nums; -}; -``` - -Merge Sort: - ```js /** * @param {number[]} nums @@ -498,10 +431,51 @@ var sortArray = function (nums) { }; ``` -### **...** + -``` +### Solution 3 + + +```java +class Solution { + private int[] nums; + + public int[] sortArray(int[] nums) { + this.nums = nums; + mergeSort(0, nums.length - 1); + return nums; + } + + private void mergeSort(int l, int r) { + if (l >= r) { + return; + } + int mid = (l + r) >> 1; + mergeSort(l, mid); + mergeSort(mid + 1, r); + int i = l, j = mid + 1, k = 0; + int[] tmp = new int[r - l + 1]; + while (i <= mid && j <= r) { + if (nums[i] <= nums[j]) { + tmp[k++] = nums[i++]; + } else { + tmp[k++] = nums[j++]; + } + } + while (i <= mid) { + tmp[k++] = nums[i++]; + } + while (j <= r) { + tmp[k++] = nums[j++]; + } + for (i = l; i <= r; ++i) { + nums[i] = tmp[i - l]; + } + } +} ``` + + diff --git a/solution/0900-0999/0913.Cat and Mouse/README.md b/solution/0900-0999/0913.Cat and Mouse/README.md index dc9869e6333b2..4f08995c843ce 100644 --- a/solution/0900-0999/0913.Cat and Mouse/README.md +++ b/solution/0900-0999/0913.Cat and Mouse/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:拓扑排序** +### 方法一:拓扑排序 猫和老鼠的游戏中,状态由三个因素决定:老鼠的位置、猫的位置和移动方。根据游戏规则,可以直接确定胜负的边界状态有: @@ -91,10 +89,6 @@ -### **Python3** - - - ```python HOLE, MOUSE_START, CAT_START = 0, 1, 2 MOUSE_TURN, CAT_TURN = 0, 1 @@ -154,10 +148,6 @@ class Solution: return res[MOUSE_START][CAT_START][MOUSE_TURN] ``` -### **Java** - - - ```java class Solution { private int n; @@ -242,8 +232,6 @@ class Solution { } ``` -### **C++** - ```cpp const int HOLE = 0; const int MOUSE_START = 1; @@ -322,8 +310,6 @@ public: }; ``` -### **Go** - ```go const ( hole = 0 @@ -403,10 +389,6 @@ func catMouseGame(graph [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0913.Cat and Mouse/README_EN.md b/solution/0900-0999/0913.Cat and Mouse/README_EN.md index 7574dd7cf12f2..d77ed27c3f744 100644 --- a/solution/0900-0999/0913.Cat and Mouse/README_EN.md +++ b/solution/0900-0999/0913.Cat and Mouse/README_EN.md @@ -59,9 +59,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python HOLE, MOUSE_START, CAT_START = 0, 1, 2 @@ -122,8 +122,6 @@ class Solution: return res[MOUSE_START][CAT_START][MOUSE_TURN] ``` -### **Java** - ```java class Solution { private int n; @@ -208,8 +206,6 @@ class Solution { } ``` -### **C++** - ```cpp const int HOLE = 0; const int MOUSE_START = 1; @@ -288,8 +284,6 @@ public: }; ``` -### **Go** - ```go const ( hole = 0 @@ -369,10 +363,6 @@ func catMouseGame(graph [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0914.X of a Kind in a Deck of Cards/README.md b/solution/0900-0999/0914.X of a Kind in a Deck of Cards/README.md index 00134ea63d692..5781ccefcce82 100644 --- a/solution/0900-0999/0914.X of a Kind in a Deck of Cards/README.md +++ b/solution/0900-0999/0914.X of a Kind in a Deck of Cards/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:最大公约数** +### 方法一:最大公约数 我们先用数组或哈希表 `cnt` 统计每个数字出现的次数,只有当 $X$ 是所有数字出现次数的约数时,即 $X$ 是所有 `cnt[i]` 的最大公约数的约数时,才能满足题意。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def hasGroupsSizeX(self, deck: List[int]) -> bool: @@ -68,10 +62,6 @@ class Solution: return reduce(gcd, vals) >= 2 ``` -### **Java** - - - ```java class Solution { public boolean hasGroupsSizeX(int[] deck) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func hasGroupsSizeX(deck []int) bool { cnt := make([]int, 10000) @@ -142,10 +128,6 @@ func gcd(a, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0914.X of a Kind in a Deck of Cards/README_EN.md b/solution/0900-0999/0914.X of a Kind in a Deck of Cards/README_EN.md index a3d609c73864c..6d38a8cc781eb 100644 --- a/solution/0900-0999/0914.X of a Kind in a Deck of Cards/README_EN.md +++ b/solution/0900-0999/0914.X of a Kind in a Deck of Cards/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return reduce(gcd, vals) >= 2 ``` -### **Java** - ```java class Solution { public boolean hasGroupsSizeX(int[] deck) { @@ -77,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func hasGroupsSizeX(deck []int) bool { cnt := make([]int, 10000) @@ -125,10 +119,6 @@ func gcd(a, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0915.Partition Array into Disjoint Intervals/README.md b/solution/0900-0999/0915.Partition Array into Disjoint Intervals/README.md index 70170444b1c8c..fd8c947bab80e 100644 --- a/solution/0900-0999/0915.Partition Array into Disjoint Intervals/README.md +++ b/solution/0900-0999/0915.Partition Array into Disjoint Intervals/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:前缀最大值 + 后缀最小值** +### 方法一:前缀最大值 + 后缀最小值 划分后的两个子数组要满足题目要求,需要保证“数组前缀最大值”小于等于“数组后缀最小值”。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def partitionDisjoint(self, nums: List[int]) -> int: @@ -80,10 +74,6 @@ class Solution: return i ``` -### **Java** - - - ```java class Solution { public int partitionDisjoint(int[] nums) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func partitionDisjoint(nums []int) int { n := len(nums) @@ -148,10 +134,6 @@ func partitionDisjoint(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0915.Partition Array into Disjoint Intervals/README_EN.md b/solution/0900-0999/0915.Partition Array into Disjoint Intervals/README_EN.md index 588c5d3198f11..bae2482b4b681 100644 --- a/solution/0900-0999/0915.Partition Array into Disjoint Intervals/README_EN.md +++ b/solution/0900-0999/0915.Partition Array into Disjoint Intervals/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return i ``` -### **Java** - ```java class Solution { public int partitionDisjoint(int[] nums) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +102,6 @@ public: }; ``` -### **Go** - ```go func partitionDisjoint(nums []int) int { n := len(nums) @@ -128,10 +122,6 @@ func partitionDisjoint(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0916.Word Subsets/README.md b/solution/0900-0999/0916.Word Subsets/README.md index 7e03046bce99b..137c424f237c3 100644 --- a/solution/0900-0999/0916.Word Subsets/README.md +++ b/solution/0900-0999/0916.Word Subsets/README.md @@ -71,9 +71,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 遍历 `words2` 中的每个单词 `b`,统计每个字母出现的最大次数,记为 `cnt`。 @@ -83,10 +81,6 @@ -### **Python3** - - - ```python class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: @@ -103,10 +97,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List wordSubsets(String[] words1, String[] words2) { @@ -142,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -181,8 +169,6 @@ public: }; ``` -### **Go** - ```go func wordSubsets(words1 []string, words2 []string) (ans []string) { cnt := [26]int{} @@ -215,10 +201,6 @@ func wordSubsets(words1 []string, words2 []string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0916.Word Subsets/README_EN.md b/solution/0900-0999/0916.Word Subsets/README_EN.md index d90af354a64f2..ba3a3dfa79329 100644 --- a/solution/0900-0999/0916.Word Subsets/README_EN.md +++ b/solution/0900-0999/0916.Word Subsets/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List wordSubsets(String[] words1, String[] words2) { @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +135,6 @@ public: }; ``` -### **Go** - ```go func wordSubsets(words1 []string, words2 []string) (ans []string) { cnt := [26]int{} @@ -173,10 +167,6 @@ func wordSubsets(words1 []string, words2 []string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0917.Reverse Only Letters/README.md b/solution/0900-0999/0917.Reverse Only Letters/README.md index 947f0178b02c7..582a293d363f4 100644 --- a/solution/0900-0999/0917.Reverse Only Letters/README.md +++ b/solution/0900-0999/0917.Reverse Only Letters/README.md @@ -59,16 +59,10 @@ ## 解法 - - -双指针遍历字符串,交换两个指针指向的字母。 +### 方法一 -### **Python3** - - - ```python class Solution: def reverseOnlyLetters(self, s: str) -> str: @@ -85,10 +79,6 @@ class Solution: return ''.join(s) ``` -### **Java** - - - ```java class Solution { public String reverseOnlyLetters(String s) { @@ -114,27 +104,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function reverseOnlyLetters(s: string): string { - const n = s.length; - let i = 0, - j = n - 1; - let ans = [...s]; - while (i < j) { - while (!/[a-zA-Z]/.test(ans[i]) && i < j) i++; - while (!/[a-zA-Z]/.test(ans[j]) && i < j) j--; - [ans[i], ans[j]] = [ans[j], ans[i]]; - i++; - j--; - } - return ans.join(''); -} -``` - -### **C++** - ```cpp class Solution { public: @@ -154,8 +123,6 @@ public: }; ``` -### **Go** - ```go func reverseOnlyLetters(s string) string { ans := []rune(s) @@ -177,7 +144,22 @@ func reverseOnlyLetters(s string) string { } ``` -### **Rust** +```ts +function reverseOnlyLetters(s: string): string { + const n = s.length; + let i = 0, + j = n - 1; + let ans = [...s]; + while (i < j) { + while (!/[a-zA-Z]/.test(ans[i]) && i < j) i++; + while (!/[a-zA-Z]/.test(ans[j]) && i < j) j--; + [ans[i], ans[j]] = [ans[j], ans[i]]; + i++; + j--; + } + return ans.join(''); +} +``` ```rust impl Solution { @@ -202,10 +184,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0917.Reverse Only Letters/README_EN.md b/solution/0900-0999/0917.Reverse Only Letters/README_EN.md index d34db7ecf3fa4..ac0c6a7745674 100644 --- a/solution/0900-0999/0917.Reverse Only Letters/README_EN.md +++ b/solution/0900-0999/0917.Reverse Only Letters/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return ''.join(s) ``` -### **Java** - ```java class Solution { public String reverseOnlyLetters(String s) { @@ -82,27 +80,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function reverseOnlyLetters(s: string): string { - const n = s.length; - let i = 0, - j = n - 1; - let ans = [...s]; - while (i < j) { - while (!/[a-zA-Z]/.test(ans[i]) && i < j) i++; - while (!/[a-zA-Z]/.test(ans[j]) && i < j) j--; - [ans[i], ans[j]] = [ans[j], ans[i]]; - i++; - j--; - } - return ans.join(''); -} -``` - -### **C++** - ```cpp class Solution { public: @@ -122,8 +99,6 @@ public: }; ``` -### **Go** - ```go func reverseOnlyLetters(s string) string { ans := []rune(s) @@ -145,7 +120,22 @@ func reverseOnlyLetters(s string) string { } ``` -### **Rust** +```ts +function reverseOnlyLetters(s: string): string { + const n = s.length; + let i = 0, + j = n - 1; + let ans = [...s]; + while (i < j) { + while (!/[a-zA-Z]/.test(ans[i]) && i < j) i++; + while (!/[a-zA-Z]/.test(ans[j]) && i < j) j--; + [ans[i], ans[j]] = [ans[j], ans[i]]; + i++; + j--; + } + return ans.join(''); +} +``` ```rust impl Solution { @@ -170,10 +160,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0918.Maximum Sum Circular Subarray/README.md b/solution/0900-0999/0918.Maximum Sum Circular Subarray/README.md index 6151953c7ea55..c775bdbf60384 100644 --- a/solution/0900-0999/0918.Maximum Sum Circular Subarray/README.md +++ b/solution/0900-0999/0918.Maximum Sum Circular Subarray/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:维护前缀最值** +### 方法一:维护前缀最值 求环形子数组的最大和,可以分为两种情况: @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def maxSubarraySumCircular(self, nums: List[int]) -> int: @@ -97,24 +91,6 @@ class Solution: return s1 if s1 <= 0 else max(s1, sum(nums) - s2) ``` -```python -class Solution: - def maxSubarraySumCircular(self, nums: List[int]) -> int: - pmi, pmx = 0, -inf - ans, s, smi = -inf, 0, inf - for x in nums: - s += x - ans = max(ans, s - pmi) - smi = min(smi, s - pmx) - pmi = min(pmi, s) - pmx = max(pmx, s) - return max(ans, s - smi) -``` - -### **Java** - - - ```java class Solution { public int maxSubarraySumCircular(int[] nums) { @@ -131,26 +107,6 @@ class Solution { } ``` -```java -class Solution { - public int maxSubarraySumCircular(int[] nums) { - final int inf = 1 << 30; - int pmi = 0, pmx = -inf; - int ans = -inf, s = 0, smi = inf; - for (int x : nums) { - s += x; - ans = Math.max(ans, s - pmi); - smi = Math.min(smi, s - pmx); - pmi = Math.min(pmi, s); - pmx = Math.max(pmx, s); - } - return Math.max(ans, s - smi); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -168,27 +124,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxSubarraySumCircular(vector& nums) { - const int inf = 1 << 30; - int pmi = 0, pmx = -inf; - int ans = -inf, s = 0, smi = inf; - for (int x : nums) { - s += x; - ans = max(ans, s - pmi); - smi = min(smi, s - pmx); - pmi = min(pmi, s); - pmx = max(pmx, s); - } - return max(ans, s - smi); - } -}; -``` - -### **Go** - ```go func maxSubarraySumCircular(nums []int) int { s1, s2, f1, f2, total := nums[0], nums[0], nums[0], nums[0], nums[0] @@ -206,24 +141,6 @@ func maxSubarraySumCircular(nums []int) int { } ``` -```go -func maxSubarraySumCircular(nums []int) int { - const inf = 1 << 30 - pmi, pmx := 0, -inf - ans, s, smi := -inf, 0, inf - for _, x := range nums { - s += x - ans = max(ans, s-pmi) - smi = min(smi, s-pmx) - pmi = min(pmi, s) - pmx = max(pmx, s) - } - return max(ans, s-smi) -} -``` - -### **TypeScript** - ```ts function maxSubarraySumCircular(nums: number[]): number { let pre1 = nums[0], @@ -245,6 +162,79 @@ function maxSubarraySumCircular(nums: number[]): number { } ``` + + +### 方法二 + + + +```python +class Solution: + def maxSubarraySumCircular(self, nums: List[int]) -> int: + pmi, pmx = 0, -inf + ans, s, smi = -inf, 0, inf + for x in nums: + s += x + ans = max(ans, s - pmi) + smi = min(smi, s - pmx) + pmi = min(pmi, s) + pmx = max(pmx, s) + return max(ans, s - smi) +``` + +```java +class Solution { + public int maxSubarraySumCircular(int[] nums) { + final int inf = 1 << 30; + int pmi = 0, pmx = -inf; + int ans = -inf, s = 0, smi = inf; + for (int x : nums) { + s += x; + ans = Math.max(ans, s - pmi); + smi = Math.min(smi, s - pmx); + pmi = Math.min(pmi, s); + pmx = Math.max(pmx, s); + } + return Math.max(ans, s - smi); + } +} +``` + +```cpp +class Solution { +public: + int maxSubarraySumCircular(vector& nums) { + const int inf = 1 << 30; + int pmi = 0, pmx = -inf; + int ans = -inf, s = 0, smi = inf; + for (int x : nums) { + s += x; + ans = max(ans, s - pmi); + smi = min(smi, s - pmx); + pmi = min(pmi, s); + pmx = max(pmx, s); + } + return max(ans, s - smi); + } +}; +``` + +```go +func maxSubarraySumCircular(nums []int) int { + const inf = 1 << 30 + pmi, pmx := 0, -inf + ans, s, smi := -inf, 0, inf + for _, x := range nums { + s += x + ans = max(ans, s-pmi) + smi = min(smi, s-pmx) + pmi = min(pmi, s) + pmx = max(pmx, s) + } + return max(ans, s-smi) +} +``` + ```ts function maxSubarraySumCircular(nums: number[]): number { const inf = 1 << 30; @@ -261,10 +251,6 @@ function maxSubarraySumCircular(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0918.Maximum Sum Circular Subarray/README_EN.md b/solution/0900-0999/0918.Maximum Sum Circular Subarray/README_EN.md index 844ee82330d53..0a041a07969df 100644 --- a/solution/0900-0999/0918.Maximum Sum Circular Subarray/README_EN.md +++ b/solution/0900-0999/0918.Maximum Sum Circular Subarray/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,22 +62,6 @@ class Solution: return s1 if s1 <= 0 else max(s1, sum(nums) - s2) ``` -```python -class Solution: - def maxSubarraySumCircular(self, nums: List[int]) -> int: - pmi, pmx = 0, -inf - ans, s, smi = -inf, 0, inf - for x in nums: - s += x - ans = max(ans, s - pmi) - smi = min(smi, s - pmx) - pmi = min(pmi, s) - pmx = max(pmx, s) - return max(ans, s - smi) -``` - -### **Java** - ```java class Solution { public int maxSubarraySumCircular(int[] nums) { @@ -94,26 +78,6 @@ class Solution { } ``` -```java -class Solution { - public int maxSubarraySumCircular(int[] nums) { - final int inf = 1 << 30; - int pmi = 0, pmx = -inf; - int ans = -inf, s = 0, smi = inf; - for (int x : nums) { - s += x; - ans = Math.max(ans, s - pmi); - smi = Math.min(smi, s - pmx); - pmi = Math.min(pmi, s); - pmx = Math.max(pmx, s); - } - return Math.max(ans, s - smi); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -131,27 +95,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxSubarraySumCircular(vector& nums) { - const int inf = 1 << 30; - int pmi = 0, pmx = -inf; - int ans = -inf, s = 0, smi = inf; - for (int x : nums) { - s += x; - ans = max(ans, s - pmi); - smi = min(smi, s - pmx); - pmi = min(pmi, s); - pmx = max(pmx, s); - } - return max(ans, s - smi); - } -}; -``` - -### **Go** - ```go func maxSubarraySumCircular(nums []int) int { s1, s2, f1, f2, total := nums[0], nums[0], nums[0], nums[0], nums[0] @@ -169,24 +112,6 @@ func maxSubarraySumCircular(nums []int) int { } ``` -```go -func maxSubarraySumCircular(nums []int) int { - const inf = 1 << 30 - pmi, pmx := 0, -inf - ans, s, smi := -inf, 0, inf - for _, x := range nums { - s += x - ans = max(ans, s-pmi) - smi = min(smi, s-pmx) - pmi = min(pmi, s) - pmx = max(pmx, s) - } - return max(ans, s-smi) -} -``` - -### **TypeScript** - ```ts function maxSubarraySumCircular(nums: number[]): number { let pre1 = nums[0], @@ -208,6 +133,79 @@ function maxSubarraySumCircular(nums: number[]): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def maxSubarraySumCircular(self, nums: List[int]) -> int: + pmi, pmx = 0, -inf + ans, s, smi = -inf, 0, inf + for x in nums: + s += x + ans = max(ans, s - pmi) + smi = min(smi, s - pmx) + pmi = min(pmi, s) + pmx = max(pmx, s) + return max(ans, s - smi) +``` + +```java +class Solution { + public int maxSubarraySumCircular(int[] nums) { + final int inf = 1 << 30; + int pmi = 0, pmx = -inf; + int ans = -inf, s = 0, smi = inf; + for (int x : nums) { + s += x; + ans = Math.max(ans, s - pmi); + smi = Math.min(smi, s - pmx); + pmi = Math.min(pmi, s); + pmx = Math.max(pmx, s); + } + return Math.max(ans, s - smi); + } +} +``` + +```cpp +class Solution { +public: + int maxSubarraySumCircular(vector& nums) { + const int inf = 1 << 30; + int pmi = 0, pmx = -inf; + int ans = -inf, s = 0, smi = inf; + for (int x : nums) { + s += x; + ans = max(ans, s - pmi); + smi = min(smi, s - pmx); + pmi = min(pmi, s); + pmx = max(pmx, s); + } + return max(ans, s - smi); + } +}; +``` + +```go +func maxSubarraySumCircular(nums []int) int { + const inf = 1 << 30 + pmi, pmx := 0, -inf + ans, s, smi := -inf, 0, inf + for _, x := range nums { + s += x + ans = max(ans, s-pmi) + smi = min(smi, s-pmx) + pmi = min(pmi, s) + pmx = max(pmx, s) + } + return max(ans, s-smi) +} +``` + ```ts function maxSubarraySumCircular(nums: number[]): number { const inf = 1 << 30; @@ -224,10 +222,6 @@ function maxSubarraySumCircular(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0919.Complete Binary Tree Inserter/README.md b/solution/0900-0999/0919.Complete Binary Tree Inserter/README.md index 8f81659b0502f..31db175572378 100644 --- a/solution/0900-0999/0919.Complete Binary Tree Inserter/README.md +++ b/solution/0900-0999/0919.Complete Binary Tree Inserter/README.md @@ -54,14 +54,10 @@ cBTInserter.get_root(); // 返回 [1, 2, 3, 4] ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -103,10 +99,6 @@ class CBTInserter: # param_2 = obj.get_root() ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -168,8 +160,6 @@ class CBTInserter { */ ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -222,8 +212,6 @@ public: */ ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -279,69 +267,6 @@ func (this *CBTInserter) Get_root() *TreeNode { */ ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - */ -var CBTInserter = function (root) { - this.tree = []; - const q = [root]; - while (q.length) { - const node = q.shift(); - this.tree.push(node); - if (node.left) { - q.push(node.left); - } - if (node.right) { - q.push(node.right); - } - } -}; - -/** - * @param {number} val - * @return {number} - */ -CBTInserter.prototype.insert = function (val) { - const pid = (this.tree.length - 1) >> 1; - const node = new TreeNode(val); - this.tree.push(node); - const p = this.tree[pid]; - if (!p.left) { - p.left = node; - } else { - p.right = node; - } - return p.val; -}; - -/** - * @return {TreeNode} - */ -CBTInserter.prototype.get_root = function () { - return this.tree[0]; -}; - -/** - * Your CBTInserter object will be instantiated and called as such: - * var obj = new CBTInserter(root) - * var param_1 = obj.insert(val) - * var param_2 = obj.get_root() - */ -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -407,10 +332,65 @@ class CBTInserter { */ ``` -### **...** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + */ +var CBTInserter = function (root) { + this.tree = []; + const q = [root]; + while (q.length) { + const node = q.shift(); + this.tree.push(node); + if (node.left) { + q.push(node.left); + } + if (node.right) { + q.push(node.right); + } + } +}; + +/** + * @param {number} val + * @return {number} + */ +CBTInserter.prototype.insert = function (val) { + const pid = (this.tree.length - 1) >> 1; + const node = new TreeNode(val); + this.tree.push(node); + const p = this.tree[pid]; + if (!p.left) { + p.left = node; + } else { + p.right = node; + } + return p.val; +}; -``` +/** + * @return {TreeNode} + */ +CBTInserter.prototype.get_root = function () { + return this.tree[0]; +}; +/** + * Your CBTInserter object will be instantiated and called as such: + * var obj = new CBTInserter(root) + * var param_1 = obj.insert(val) + * var param_2 = obj.get_root() + */ ``` + + diff --git a/solution/0900-0999/0919.Complete Binary Tree Inserter/README_EN.md b/solution/0900-0999/0919.Complete Binary Tree Inserter/README_EN.md index 67022e0a8634e..8d6553004b753 100644 --- a/solution/0900-0999/0919.Complete Binary Tree Inserter/README_EN.md +++ b/solution/0900-0999/0919.Complete Binary Tree Inserter/README_EN.md @@ -47,9 +47,9 @@ cBTInserter.get_root(); // return [1, 2, 3, 4] ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -92,8 +92,6 @@ class CBTInserter: # param_2 = obj.get_root() ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -155,8 +153,6 @@ class CBTInserter { */ ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -209,8 +205,6 @@ public: */ ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -266,69 +260,6 @@ func (this *CBTInserter) Get_root() *TreeNode { */ ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - */ -var CBTInserter = function (root) { - this.tree = []; - const q = [root]; - while (q.length) { - const node = q.shift(); - this.tree.push(node); - if (node.left) { - q.push(node.left); - } - if (node.right) { - q.push(node.right); - } - } -}; - -/** - * @param {number} val - * @return {number} - */ -CBTInserter.prototype.insert = function (val) { - const pid = (this.tree.length - 1) >> 1; - const node = new TreeNode(val); - this.tree.push(node); - const p = this.tree[pid]; - if (!p.left) { - p.left = node; - } else { - p.right = node; - } - return p.val; -}; - -/** - * @return {TreeNode} - */ -CBTInserter.prototype.get_root = function () { - return this.tree[0]; -}; - -/** - * Your CBTInserter object will be instantiated and called as such: - * var obj = new CBTInserter(root) - * var param_1 = obj.insert(val) - * var param_2 = obj.get_root() - */ -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -394,10 +325,65 @@ class CBTInserter { */ ``` -### **...** +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + */ +var CBTInserter = function (root) { + this.tree = []; + const q = [root]; + while (q.length) { + const node = q.shift(); + this.tree.push(node); + if (node.left) { + q.push(node.left); + } + if (node.right) { + q.push(node.right); + } + } +}; -``` +/** + * @param {number} val + * @return {number} + */ +CBTInserter.prototype.insert = function (val) { + const pid = (this.tree.length - 1) >> 1; + const node = new TreeNode(val); + this.tree.push(node); + const p = this.tree[pid]; + if (!p.left) { + p.left = node; + } else { + p.right = node; + } + return p.val; +}; + +/** + * @return {TreeNode} + */ +CBTInserter.prototype.get_root = function () { + return this.tree[0]; +}; +/** + * Your CBTInserter object will be instantiated and called as such: + * var obj = new CBTInserter(root) + * var param_1 = obj.insert(val) + * var param_2 = obj.get_root() + */ ``` + + diff --git a/solution/0900-0999/0920.Number of Music Playlists/README.md b/solution/0900-0999/0920.Number of Music Playlists/README.md index e122d441a3dd0..c48371b11bc12 100644 --- a/solution/0900-0999/0920.Number of Music Playlists/README.md +++ b/solution/0900-0999/0920.Number of Music Playlists/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示听 $i$ 首歌,且这 $i$ 首歌中有 $j$ 首不同歌曲的播放列表的数量。初始时 $f[0][0]=1$。答案为 $f[goal][n]$。 @@ -75,10 +73,6 @@ $$ -### **Python3** - - - ```python class Solution: def numMusicPlaylists(self, n: int, goal: int, k: int) -> int: @@ -94,27 +88,6 @@ class Solution: return f[goal][n] ``` -```python -class Solution: - def numMusicPlaylists(self, n: int, goal: int, k: int) -> int: - mod = 10**9 + 7 - f = [0] * (goal + 1) - f[0] = 1 - for i in range(1, goal + 1): - g = [0] * (goal + 1) - for j in range(1, n + 1): - g[j] = f[j - 1] * (n - j + 1) - if j > k: - g[j] += f[j] * (j - k) - g[j] %= mod - f = g - return f[n] -``` - -### **Java** - - - ```java class Solution { public int numMusicPlaylists(int n, int goal, int k) { @@ -135,30 +108,6 @@ class Solution { } ``` -```java -class Solution { - public int numMusicPlaylists(int n, int goal, int k) { - final int mod = (int) 1e9 + 7; - long[] f = new long[n + 1]; - f[0] = 1; - for (int i = 1; i <= goal; ++i) { - long[] g = new long[n + 1]; - for (int j = 1; j <= n; ++j) { - g[j] = f[j - 1] * (n - j + 1); - if (j > k) { - g[j] += f[j] * (j - k); - } - g[j] %= mod; - } - f = g; - } - return (int) f[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -181,31 +130,45 @@ public: }; ``` -```cpp -class Solution { -public: - int numMusicPlaylists(int n, int goal, int k) { - const int mod = 1e9 + 7; - vector f(n + 1); - f[0] = 1; - for (int i = 1; i <= goal; ++i) { - vector g(n + 1); - for (int j = 1; j <= n; ++j) { - g[j] = f[j - 1] * (n - j + 1); - if (j > k) { - g[j] += f[j] * (j - k); - } - g[j] %= mod; +```go +func numMusicPlaylists(n int, goal int, k int) int { + const mod = 1e9 + 7 + f := make([][]int, goal+1) + for i := range f { + f[i] = make([]int, n+1) + } + f[0][0] = 1 + for i := 1; i <= goal; i++ { + for j := 1; j <= n; j++ { + f[i][j] = f[i-1][j-1] * (n - j + 1) + if j > k { + f[i][j] += f[i-1][j] * (j - k) + } + f[i][j] %= mod + } + } + return f[goal][n] +} +``` + +```ts +function numMusicPlaylists(n: number, goal: number, k: number): number { + const mod = 1e9 + 7; + const f = new Array(goal + 1).fill(0).map(() => new Array(n + 1).fill(0)); + f[0][0] = 1; + for (let i = 1; i <= goal; ++i) { + for (let j = 1; j <= n; ++j) { + f[i][j] = f[i - 1][j - 1] * (n - j + 1); + if (j > k) { + f[i][j] += f[i - 1][j] * (j - k); } - f = move(g); + f[i][j] %= mod; } - return f[n]; } -}; + return f[goal][n]; +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -238,29 +201,74 @@ impl Solution { } ``` -### **Go** + -```go -func numMusicPlaylists(n int, goal int, k int) int { - const mod = 1e9 + 7 - f := make([][]int, goal+1) - for i := range f { - f[i] = make([]int, n+1) - } - f[0][0] = 1 - for i := 1; i <= goal; i++ { - for j := 1; j <= n; j++ { - f[i][j] = f[i-1][j-1] * (n - j + 1) - if j > k { - f[i][j] += f[i-1][j] * (j - k) - } - f[i][j] %= mod - } - } - return f[goal][n] +### 方法二 + + + +```python +class Solution: + def numMusicPlaylists(self, n: int, goal: int, k: int) -> int: + mod = 10**9 + 7 + f = [0] * (goal + 1) + f[0] = 1 + for i in range(1, goal + 1): + g = [0] * (goal + 1) + for j in range(1, n + 1): + g[j] = f[j - 1] * (n - j + 1) + if j > k: + g[j] += f[j] * (j - k) + g[j] %= mod + f = g + return f[n] +``` + +```java +class Solution { + public int numMusicPlaylists(int n, int goal, int k) { + final int mod = (int) 1e9 + 7; + long[] f = new long[n + 1]; + f[0] = 1; + for (int i = 1; i <= goal; ++i) { + long[] g = new long[n + 1]; + for (int j = 1; j <= n; ++j) { + g[j] = f[j - 1] * (n - j + 1); + if (j > k) { + g[j] += f[j] * (j - k); + } + g[j] %= mod; + } + f = g; + } + return (int) f[n]; + } } ``` +```cpp +class Solution { +public: + int numMusicPlaylists(int n, int goal, int k) { + const int mod = 1e9 + 7; + vector f(n + 1); + f[0] = 1; + for (int i = 1; i <= goal; ++i) { + vector g(n + 1); + for (int j = 1; j <= n; ++j) { + g[j] = f[j - 1] * (n - j + 1); + if (j > k) { + g[j] += f[j] * (j - k); + } + g[j] %= mod; + } + f = move(g); + } + return f[n]; + } +}; +``` + ```go func numMusicPlaylists(n int, goal int, k int) int { const mod = 1e9 + 7 @@ -281,26 +289,6 @@ func numMusicPlaylists(n int, goal int, k int) int { } ``` -### **TypeScript** - -```ts -function numMusicPlaylists(n: number, goal: number, k: number): number { - const mod = 1e9 + 7; - const f = new Array(goal + 1).fill(0).map(() => new Array(n + 1).fill(0)); - f[0][0] = 1; - for (let i = 1; i <= goal; ++i) { - for (let j = 1; j <= n; ++j) { - f[i][j] = f[i - 1][j - 1] * (n - j + 1); - if (j > k) { - f[i][j] += f[i - 1][j] * (j - k); - } - f[i][j] %= mod; - } - } - return f[goal][n]; -} -``` - ```ts function numMusicPlaylists(n: number, goal: number, k: number): number { const mod = 1e9 + 7; @@ -321,10 +309,6 @@ function numMusicPlaylists(n: number, goal: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0920.Number of Music Playlists/README_EN.md b/solution/0900-0999/0920.Number of Music Playlists/README_EN.md index 09632b1443266..2c7b29c310904 100644 --- a/solution/0900-0999/0920.Number of Music Playlists/README_EN.md +++ b/solution/0900-0999/0920.Number of Music Playlists/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ to be the number of playlists that can be made from $i$ songs with exactly $j$ different songs. We have $f[0][0] = 1$ and the answer is $f[goal][n]$. @@ -69,8 +69,6 @@ Notice that $f[i][j]$ only depends on $f[i - 1][j - 1]$ and $f[i - 1][j]$, so we -### **Python3** - ```python class Solution: def numMusicPlaylists(self, n: int, goal: int, k: int) -> int: @@ -86,25 +84,6 @@ class Solution: return f[goal][n] ``` -```python -class Solution: - def numMusicPlaylists(self, n: int, goal: int, k: int) -> int: - mod = 10**9 + 7 - f = [0] * (goal + 1) - f[0] = 1 - for i in range(1, goal + 1): - g = [0] * (goal + 1) - for j in range(1, n + 1): - g[j] = f[j - 1] * (n - j + 1) - if j > k: - g[j] += f[j] * (j - k) - g[j] %= mod - f = g - return f[n] -``` - -### **Java** - ```java class Solution { public int numMusicPlaylists(int n, int goal, int k) { @@ -125,30 +104,6 @@ class Solution { } ``` -```java -class Solution { - public int numMusicPlaylists(int n, int goal, int k) { - final int mod = (int) 1e9 + 7; - long[] f = new long[n + 1]; - f[0] = 1; - for (int i = 1; i <= goal; ++i) { - long[] g = new long[n + 1]; - for (int j = 1; j <= n; ++j) { - g[j] = f[j - 1] * (n - j + 1); - if (j > k) { - g[j] += f[j] * (j - k); - } - g[j] %= mod; - } - f = g; - } - return (int) f[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -171,31 +126,45 @@ public: }; ``` -```cpp -class Solution { -public: - int numMusicPlaylists(int n, int goal, int k) { - const int mod = 1e9 + 7; - vector f(n + 1); - f[0] = 1; - for (int i = 1; i <= goal; ++i) { - vector g(n + 1); - for (int j = 1; j <= n; ++j) { - g[j] = f[j - 1] * (n - j + 1); - if (j > k) { - g[j] += f[j] * (j - k); - } - g[j] %= mod; +```go +func numMusicPlaylists(n int, goal int, k int) int { + const mod = 1e9 + 7 + f := make([][]int, goal+1) + for i := range f { + f[i] = make([]int, n+1) + } + f[0][0] = 1 + for i := 1; i <= goal; i++ { + for j := 1; j <= n; j++ { + f[i][j] = f[i-1][j-1] * (n - j + 1) + if j > k { + f[i][j] += f[i-1][j] * (j - k) + } + f[i][j] %= mod + } + } + return f[goal][n] +} +``` + +```ts +function numMusicPlaylists(n: number, goal: number, k: number): number { + const mod = 1e9 + 7; + const f = new Array(goal + 1).fill(0).map(() => new Array(n + 1).fill(0)); + f[0][0] = 1; + for (let i = 1; i <= goal; ++i) { + for (let j = 1; j <= n; ++j) { + f[i][j] = f[i - 1][j - 1] * (n - j + 1); + if (j > k) { + f[i][j] += f[i - 1][j] * (j - k); } - f = move(g); + f[i][j] %= mod; } - return f[n]; } -}; + return f[goal][n]; +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -228,29 +197,74 @@ impl Solution { } ``` -### **Go** + -```go -func numMusicPlaylists(n int, goal int, k int) int { - const mod = 1e9 + 7 - f := make([][]int, goal+1) - for i := range f { - f[i] = make([]int, n+1) - } - f[0][0] = 1 - for i := 1; i <= goal; i++ { - for j := 1; j <= n; j++ { - f[i][j] = f[i-1][j-1] * (n - j + 1) - if j > k { - f[i][j] += f[i-1][j] * (j - k) - } - f[i][j] %= mod - } - } - return f[goal][n] +### Solution 2 + + + +```python +class Solution: + def numMusicPlaylists(self, n: int, goal: int, k: int) -> int: + mod = 10**9 + 7 + f = [0] * (goal + 1) + f[0] = 1 + for i in range(1, goal + 1): + g = [0] * (goal + 1) + for j in range(1, n + 1): + g[j] = f[j - 1] * (n - j + 1) + if j > k: + g[j] += f[j] * (j - k) + g[j] %= mod + f = g + return f[n] +``` + +```java +class Solution { + public int numMusicPlaylists(int n, int goal, int k) { + final int mod = (int) 1e9 + 7; + long[] f = new long[n + 1]; + f[0] = 1; + for (int i = 1; i <= goal; ++i) { + long[] g = new long[n + 1]; + for (int j = 1; j <= n; ++j) { + g[j] = f[j - 1] * (n - j + 1); + if (j > k) { + g[j] += f[j] * (j - k); + } + g[j] %= mod; + } + f = g; + } + return (int) f[n]; + } } ``` +```cpp +class Solution { +public: + int numMusicPlaylists(int n, int goal, int k) { + const int mod = 1e9 + 7; + vector f(n + 1); + f[0] = 1; + for (int i = 1; i <= goal; ++i) { + vector g(n + 1); + for (int j = 1; j <= n; ++j) { + g[j] = f[j - 1] * (n - j + 1); + if (j > k) { + g[j] += f[j] * (j - k); + } + g[j] %= mod; + } + f = move(g); + } + return f[n]; + } +}; +``` + ```go func numMusicPlaylists(n int, goal int, k int) int { const mod = 1e9 + 7 @@ -271,26 +285,6 @@ func numMusicPlaylists(n int, goal int, k int) int { } ``` -### **TypeScript** - -```ts -function numMusicPlaylists(n: number, goal: number, k: number): number { - const mod = 1e9 + 7; - const f = new Array(goal + 1).fill(0).map(() => new Array(n + 1).fill(0)); - f[0][0] = 1; - for (let i = 1; i <= goal; ++i) { - for (let j = 1; j <= n; ++j) { - f[i][j] = f[i - 1][j - 1] * (n - j + 1); - if (j > k) { - f[i][j] += f[i - 1][j] * (j - k); - } - f[i][j] %= mod; - } - } - return f[goal][n]; -} -``` - ```ts function numMusicPlaylists(n: number, goal: number, k: number): number { const mod = 1e9 + 7; @@ -311,10 +305,6 @@ function numMusicPlaylists(n: number, goal: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/README.md b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/README.md index a77c68e611103..8b31937e1a6e2 100644 --- a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/README.md +++ b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:贪心 + 栈** +### 方法一:贪心 + 栈 这个问题属于经典的括号匹配问题,可以使用“贪心 + 栈”来解决。 @@ -64,7 +62,69 @@ 时间复杂度为 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度。 -**方法二:贪心 + 计数** + + +```python +class Solution: + def minAddToMakeValid(self, s: str) -> int: + stk = [] + for c in s: + if c == ')' and stk and stk[-1] == '(': + stk.pop() + else: + stk.append(c) + return len(stk) +``` + +```java +class Solution { + public int minAddToMakeValid(String s) { + Deque stk = new ArrayDeque<>(); + for (char c : s.toCharArray()) { + if (c == ')' && !stk.isEmpty() && stk.peek() == '(') { + stk.pop(); + } else { + stk.push(c); + } + } + return stk.size(); + } +} +``` + +```cpp +class Solution { +public: + int minAddToMakeValid(string s) { + string stk; + for (char c : s) { + if (c == ')' && stk.size() && stk.back() == '(') + stk.pop_back(); + else + stk.push_back(c); + } + return stk.size(); + } +}; +``` + +```go +func minAddToMakeValid(s string) int { + stk := []rune{} + for _, c := range s { + if c == ')' && len(stk) > 0 && stk[len(stk)-1] == '(' { + stk = stk[:len(stk)-1] + } else { + stk = append(stk, c) + } + } + return len(stk) +} +``` + + + +### 方法二:贪心 + 计数 方法一借助了栈来实现括号匹配,也可以直接通过计数来实现。 @@ -81,22 +141,6 @@ -### **Python3** - - - -```python -class Solution: - def minAddToMakeValid(self, s: str) -> int: - stk = [] - for c in s: - if c == ')' and stk and stk[-1] == '(': - stk.pop() - else: - stk.append(c) - return len(stk) -``` - ```python class Solution: def minAddToMakeValid(self, s: str) -> int: @@ -112,26 +156,6 @@ class Solution: return ans ``` -### **Java** - - - -```java -class Solution { - public int minAddToMakeValid(String s) { - Deque stk = new ArrayDeque<>(); - for (char c : s.toCharArray()) { - if (c == ')' && !stk.isEmpty() && stk.peek() == '(') { - stk.pop(); - } else { - stk.push(c); - } - } - return stk.size(); - } -} -``` - ```java class Solution { public int minAddToMakeValid(String s) { @@ -151,24 +175,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minAddToMakeValid(string s) { - string stk; - for (char c : s) { - if (c == ')' && stk.size() && stk.back() == '(') - stk.pop_back(); - else - stk.push_back(c); - } - return stk.size(); - } -}; -``` - ```cpp class Solution { public: @@ -188,22 +194,6 @@ public: }; ``` -### **Go** - -```go -func minAddToMakeValid(s string) int { - stk := []rune{} - for _, c := range s { - if c == ')' && len(stk) > 0 && stk[len(stk)-1] == '(' { - stk = stk[:len(stk)-1] - } else { - stk = append(stk, c) - } - } - return len(stk) -} -``` - ```go func minAddToMakeValid(s string) int { ans, cnt := 0, 0 @@ -221,10 +211,6 @@ func minAddToMakeValid(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/README_EN.md b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/README_EN.md index 4b951ef0bcadb..909a4ded1abfd 100644 --- a/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/README_EN.md +++ b/solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,23 +61,6 @@ class Solution: return len(stk) ``` -```python -class Solution: - def minAddToMakeValid(self, s: str) -> int: - ans = cnt = 0 - for c in s: - if c == '(': - cnt += 1 - elif cnt: - cnt -= 1 - else: - ans += 1 - ans += cnt - return ans -``` - -### **Java** - ```java class Solution { public int minAddToMakeValid(String s) { @@ -94,6 +77,57 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minAddToMakeValid(string s) { + string stk; + for (char c : s) { + if (c == ')' && stk.size() && stk.back() == '(') + stk.pop_back(); + else + stk.push_back(c); + } + return stk.size(); + } +}; +``` + +```go +func minAddToMakeValid(s string) int { + stk := []rune{} + for _, c := range s { + if c == ')' && len(stk) > 0 && stk[len(stk)-1] == '(' { + stk = stk[:len(stk)-1] + } else { + stk = append(stk, c) + } + } + return len(stk) +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minAddToMakeValid(self, s: str) -> int: + ans = cnt = 0 + for c in s: + if c == '(': + cnt += 1 + elif cnt: + cnt -= 1 + else: + ans += 1 + ans += cnt + return ans +``` + ```java class Solution { public int minAddToMakeValid(String s) { @@ -113,24 +147,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minAddToMakeValid(string s) { - string stk; - for (char c : s) { - if (c == ')' && stk.size() && stk.back() == '(') - stk.pop_back(); - else - stk.push_back(c); - } - return stk.size(); - } -}; -``` - ```cpp class Solution { public: @@ -150,22 +166,6 @@ public: }; ``` -### **Go** - -```go -func minAddToMakeValid(s string) int { - stk := []rune{} - for _, c := range s { - if c == ')' && len(stk) > 0 && stk[len(stk)-1] == '(' { - stk = stk[:len(stk)-1] - } else { - stk = append(stk, c) - } - } - return len(stk) -} -``` - ```go func minAddToMakeValid(s string) int { ans, cnt := 0, 0 @@ -183,10 +183,6 @@ func minAddToMakeValid(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0922.Sort Array By Parity II/README.md b/solution/0900-0999/0922.Sort Array By Parity II/README.md index 0781402a84617..bc9b385d19b63 100644 --- a/solution/0900-0999/0922.Sort Array By Parity II/README.md +++ b/solution/0900-0999/0922.Sort Array By Parity II/README.md @@ -46,16 +46,10 @@ ## 解法 - - -双指针原地修改数组。 +### 方法一 -### **Python3** - - - ```python class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: @@ -68,10 +62,6 @@ class Solution: return nums ``` -### **Java** - - - ```java class Solution { public int[] sortArrayByParityII(int[] nums) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +97,6 @@ public: }; ``` -### **Go** - ```go func sortArrayByParityII(nums []int) []int { for i, j := 0, 1; i < len(nums); i += 2 { @@ -125,8 +111,6 @@ func sortArrayByParityII(nums []int) []int { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -145,10 +129,6 @@ var sortArrayByParityII = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0922.Sort Array By Parity II/README_EN.md b/solution/0900-0999/0922.Sort Array By Parity II/README_EN.md index 4e2a46140d89b..1a4857a99d5dc 100644 --- a/solution/0900-0999/0922.Sort Array By Parity II/README_EN.md +++ b/solution/0900-0999/0922.Sort Array By Parity II/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return nums ``` -### **Java** - ```java class Solution { public int[] sortArrayByParityII(int[] nums) { @@ -77,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func sortArrayByParityII(nums []int) []int { for i, j := 0, 1; i < len(nums); i += 2 { @@ -112,8 +106,6 @@ func sortArrayByParityII(nums []int) []int { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -132,10 +124,6 @@ var sortArrayByParityII = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0923.3Sum With Multiplicity/README.md b/solution/0900-0999/0923.3Sum With Multiplicity/README.md index 732e47ec62cbf..8b292515c42fd 100644 --- a/solution/0900-0999/0923.3Sum With Multiplicity/README.md +++ b/solution/0900-0999/0923.3Sum With Multiplicity/README.md @@ -48,9 +48,7 @@ arr[i] = 1, arr[j] = arr[k] = 2 出现 12 次: ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们先用一个长度为 $101$ 的数组 `cnt` 记录数组 `arr` 中每个元素出现的次数。 @@ -62,10 +60,6 @@ arr[i] = 1, arr[j] = arr[k] = 2 出现 12 次: -### **Python3** - - - ```python class Solution: def threeSumMulti(self, arr: List[int], target: int) -> int: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func threeSumMulti(arr []int, target int) int { const mod int = 1e9 + 7 @@ -166,10 +152,6 @@ func threeSumMulti(arr []int, target int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0923.3Sum With Multiplicity/README_EN.md b/solution/0900-0999/0923.3Sum With Multiplicity/README_EN.md index 759f5d7589c02..2ad7d676d9e82 100644 --- a/solution/0900-0999/0923.3Sum With Multiplicity/README_EN.md +++ b/solution/0900-0999/0923.3Sum With Multiplicity/README_EN.md @@ -52,9 +52,9 @@ and two 2s from [2,2,2,2] in 6 ways. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -99,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +125,6 @@ public: }; ``` -### **Go** - ```go func threeSumMulti(arr []int, target int) int { const mod int = 1e9 + 7 @@ -154,10 +148,6 @@ func threeSumMulti(arr []int, target int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0924.Minimize Malware Spread/README.md b/solution/0900-0999/0924.Minimize Malware Spread/README.md index 32596e930c11a..7ab099c473bf0 100644 --- a/solution/0900-0999/0924.Minimize Malware Spread/README.md +++ b/solution/0900-0999/0924.Minimize Malware Spread/README.md @@ -61,79 +61,10 @@ ## 解法 - - -并查集。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` +### 方法一 -### **Python3** - - - ```python class Solution: def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int: @@ -174,10 +105,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -235,8 +162,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -284,8 +209,6 @@ public: }; ``` -### **Go** - ```go var p []int @@ -341,10 +264,6 @@ func find(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0924.Minimize Malware Spread/README_EN.md b/solution/0900-0999/0924.Minimize Malware Spread/README_EN.md index e7de7892e3a32..7aac87453b6f2 100644 --- a/solution/0900-0999/0924.Minimize Malware Spread/README_EN.md +++ b/solution/0900-0999/0924.Minimize Malware Spread/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -86,8 +86,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { private int[] p; @@ -145,8 +143,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -194,8 +190,6 @@ public: }; ``` -### **Go** - ```go var p []int @@ -251,10 +245,6 @@ func find(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0925.Long Pressed Name/README.md b/solution/0900-0999/0925.Long Pressed Name/README.md index 730bdd82a07bd..4505007e2d76a 100644 --- a/solution/0900-0999/0925.Long Pressed Name/README.md +++ b/solution/0900-0999/0925.Long Pressed Name/README.md @@ -39,16 +39,10 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 -### **Python3** - - - ```python class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: @@ -71,10 +65,6 @@ class Solution: return i == m and j == n ``` -### **Java** - - - ```java class Solution { public boolean isLongPressedName(String name, String typed) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func isLongPressedName(name string, typed string) bool { m, n := len(name), len(typed) @@ -158,10 +144,6 @@ func isLongPressedName(name string, typed string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0925.Long Pressed Name/README_EN.md b/solution/0900-0999/0925.Long Pressed Name/README_EN.md index 71b6381777b69..1e24e65958235 100644 --- a/solution/0900-0999/0925.Long Pressed Name/README_EN.md +++ b/solution/0900-0999/0925.Long Pressed Name/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return i == m and j == n ``` -### **Java** - ```java class Solution { public boolean isLongPressedName(String name, String typed) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func isLongPressedName(name string, typed string) bool { m, n := len(name), len(typed) @@ -146,10 +140,6 @@ func isLongPressedName(name string, typed string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0926.Flip String to Monotone Increasing/README.md b/solution/0900-0999/0926.Flip String to Monotone Increasing/README.md index b169620df8e8a..66c2b5fcac2cf 100644 --- a/solution/0900-0999/0926.Flip String to Monotone Increasing/README.md +++ b/solution/0900-0999/0926.Flip String to Monotone Increasing/README.md @@ -49,18 +49,12 @@ ## 解法 - - -**方法一:前缀和** +### 方法一:前缀和 我们需要找到一个分界点 `i`,使 `[:i]` 全为 0,`[i:]` 全为 1,并且翻转次数最少,问题就转换成计算 `i` 的左右两侧的翻转次数,可以用前缀和进行优化。 -### **Python3** - - - ```python class Solution: def minFlipsMonoIncr(self, s: str) -> int: @@ -76,23 +70,6 @@ class Solution: return ans ``` -```python -class Solution: - def minFlipsMonoIncr(self, s: str) -> int: - n = len(s) - presum = [0] * (n + 1) - for i, c in enumerate(s): - presum[i + 1] = presum[i] + int(c) - ans = presum[-1] - for i in range(n): - ans = min(ans, presum[i] + n - i - (presum[-1] - presum[i])) - return ans -``` - -### **Java** - - - ```java class Solution { public int minFlipsMonoIncr(String s) { @@ -114,25 +91,6 @@ class Solution { } ``` -```java -class Solution { - public int minFlipsMonoIncr(String s) { - int n = s.length(); - int[] presum = new int[n + 1]; - for (int i = 0; i < n; ++i) { - presum[i + 1] = presum[i] + (s.charAt(i) - '0'); - } - int ans = presum[n]; - for (int i = 0; i < n; ++i) { - ans = Math.min(ans, presum[i] + n - i - (presum[n] - presum[i])); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -154,22 +112,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minFlipsMonoIncr(string s) { - int n = s.size(); - vector presum(n + 1); - for (int i = 0; i < n; ++i) presum[i + 1] = presum[i] + (s[i] == '1'); - int ans = presum[n]; - for (int i = 0; i < n; ++i) ans = min(ans, presum[i] + n - i - (presum[n] - presum[i])); - return ans; - } -}; -``` - -### **Go** - ```go func minFlipsMonoIncr(s string) int { n := len(s) @@ -194,23 +136,6 @@ func minFlipsMonoIncr(s string) int { } ``` -```go -func minFlipsMonoIncr(s string) int { - n := len(s) - presum := make([]int, n+1) - for i, c := range s { - presum[i+1] = presum[i] + int(c-'0') - } - ans := presum[n] - for i := range s { - ans = min(ans, presum[i]+n-i-(presum[n]-presum[i])) - } - return ans -} -``` - -### **JavaScript** - ```js /** * @param {string} s @@ -230,10 +155,71 @@ var minFlipsMonoIncr = function (s) { }; ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def minFlipsMonoIncr(self, s: str) -> int: + n = len(s) + presum = [0] * (n + 1) + for i, c in enumerate(s): + presum[i + 1] = presum[i] + int(c) + ans = presum[-1] + for i in range(n): + ans = min(ans, presum[i] + n - i - (presum[-1] - presum[i])) + return ans ``` +```java +class Solution { + public int minFlipsMonoIncr(String s) { + int n = s.length(); + int[] presum = new int[n + 1]; + for (int i = 0; i < n; ++i) { + presum[i + 1] = presum[i] + (s.charAt(i) - '0'); + } + int ans = presum[n]; + for (int i = 0; i < n; ++i) { + ans = Math.min(ans, presum[i] + n - i - (presum[n] - presum[i])); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int minFlipsMonoIncr(string s) { + int n = s.size(); + vector presum(n + 1); + for (int i = 0; i < n; ++i) presum[i + 1] = presum[i] + (s[i] == '1'); + int ans = presum[n]; + for (int i = 0; i < n; ++i) ans = min(ans, presum[i] + n - i - (presum[n] - presum[i])); + return ans; + } +}; +``` + +```go +func minFlipsMonoIncr(s string) int { + n := len(s) + presum := make([]int, n+1) + for i, c := range s { + presum[i+1] = presum[i] + int(c-'0') + } + ans := presum[n] + for i := range s { + ans = min(ans, presum[i]+n-i-(presum[n]-presum[i])) + } + return ans +} ``` + + diff --git a/solution/0900-0999/0926.Flip String to Monotone Increasing/README_EN.md b/solution/0900-0999/0926.Flip String to Monotone Increasing/README_EN.md index 5b8dd5bfc9ab5..fb1cd19513545 100644 --- a/solution/0900-0999/0926.Flip String to Monotone Increasing/README_EN.md +++ b/solution/0900-0999/0926.Flip String to Monotone Increasing/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,21 +64,6 @@ class Solution: return ans ``` -```python -class Solution: - def minFlipsMonoIncr(self, s: str) -> int: - n = len(s) - presum = [0] * (n + 1) - for i, c in enumerate(s): - presum[i + 1] = presum[i] + int(c) - ans = presum[-1] - for i in range(n): - ans = min(ans, presum[i] + n - i - (presum[-1] - presum[i])) - return ans -``` - -### **Java** - ```java class Solution { public int minFlipsMonoIncr(String s) { @@ -100,25 +85,6 @@ class Solution { } ``` -```java -class Solution { - public int minFlipsMonoIncr(String s) { - int n = s.length(); - int[] presum = new int[n + 1]; - for (int i = 0; i < n; ++i) { - presum[i + 1] = presum[i] + (s.charAt(i) - '0'); - } - int ans = presum[n]; - for (int i = 0; i < n; ++i) { - ans = Math.min(ans, presum[i] + n - i - (presum[n] - presum[i])); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -140,22 +106,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minFlipsMonoIncr(string s) { - int n = s.size(); - vector presum(n + 1); - for (int i = 0; i < n; ++i) presum[i + 1] = presum[i] + (s[i] == '1'); - int ans = presum[n]; - for (int i = 0; i < n; ++i) ans = min(ans, presum[i] + n - i - (presum[n] - presum[i])); - return ans; - } -}; -``` - -### **Go** - ```go func minFlipsMonoIncr(s string) int { n := len(s) @@ -180,23 +130,6 @@ func minFlipsMonoIncr(s string) int { } ``` -```go -func minFlipsMonoIncr(s string) int { - n := len(s) - presum := make([]int, n+1) - for i, c := range s { - presum[i+1] = presum[i] + int(c-'0') - } - ans := presum[n] - for i := range s { - ans = min(ans, presum[i]+n-i-(presum[n]-presum[i])) - } - return ans -} -``` - -### **JavaScript** - ```js /** * @param {string} s @@ -216,10 +149,71 @@ var minFlipsMonoIncr = function (s) { }; ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def minFlipsMonoIncr(self, s: str) -> int: + n = len(s) + presum = [0] * (n + 1) + for i, c in enumerate(s): + presum[i + 1] = presum[i] + int(c) + ans = presum[-1] + for i in range(n): + ans = min(ans, presum[i] + n - i - (presum[-1] - presum[i])) + return ans +``` + +```java +class Solution { + public int minFlipsMonoIncr(String s) { + int n = s.length(); + int[] presum = new int[n + 1]; + for (int i = 0; i < n; ++i) { + presum[i + 1] = presum[i] + (s.charAt(i) - '0'); + } + int ans = presum[n]; + for (int i = 0; i < n; ++i) { + ans = Math.min(ans, presum[i] + n - i - (presum[n] - presum[i])); + } + return ans; + } +} +``` +```cpp +class Solution { +public: + int minFlipsMonoIncr(string s) { + int n = s.size(); + vector presum(n + 1); + for (int i = 0; i < n; ++i) presum[i + 1] = presum[i] + (s[i] == '1'); + int ans = presum[n]; + for (int i = 0; i < n; ++i) ans = min(ans, presum[i] + n - i - (presum[n] - presum[i])); + return ans; + } +}; ``` +```go +func minFlipsMonoIncr(s string) int { + n := len(s) + presum := make([]int, n+1) + for i, c := range s { + presum[i+1] = presum[i] + int(c-'0') + } + ans := presum[n] + for i := range s { + ans = min(ans, presum[i]+n-i-(presum[n]-presum[i])) + } + return ans +} ``` + + diff --git a/solution/0900-0999/0927.Three Equal Parts/README.md b/solution/0900-0999/0927.Three Equal Parts/README.md index 0ba1b4ff268d6..9f7c86e334346 100644 --- a/solution/0900-0999/0927.Three Equal Parts/README.md +++ b/solution/0900-0999/0927.Three Equal Parts/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:计数 + 三指针** +### 方法一:计数 + 三指针 我们记数组的长度为 $n$,数组中 $1$ 的数量为 $cnt$。 @@ -89,10 +87,6 @@ -### **Python3** - - - ```python class Solution: def threeEqualParts(self, arr: List[int]) -> List[int]: @@ -116,10 +110,6 @@ class Solution: return [i - 1, j] if k == n else [-1, -1] ``` -### **Java** - - - ```java class Solution { private int[] arr; @@ -158,8 +148,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -185,8 +173,6 @@ public: }; ``` -### **Go** - ```go func threeEqualParts(arr []int) []int { find := func(x int) int { @@ -221,8 +207,6 @@ func threeEqualParts(arr []int) []int { } ``` -### **JavaScript** - ```js /** * @param {number[]} arr @@ -257,10 +241,6 @@ var threeEqualParts = function (arr) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0927.Three Equal Parts/README_EN.md b/solution/0900-0999/0927.Three Equal Parts/README_EN.md index cd745b0059934..d678da98c4195 100644 --- a/solution/0900-0999/0927.Three Equal Parts/README_EN.md +++ b/solution/0900-0999/0927.Three Equal Parts/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return [i - 1, j] if k == n else [-1, -1] ``` -### **Java** - ```java class Solution { private int[] arr; @@ -107,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +130,6 @@ public: }; ``` -### **Go** - ```go func threeEqualParts(arr []int) []int { find := func(x int) int { @@ -170,8 +164,6 @@ func threeEqualParts(arr []int) []int { } ``` -### **JavaScript** - ```js /** * @param {number[]} arr @@ -206,10 +198,6 @@ var threeEqualParts = function (arr) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0928.Minimize Malware Spread II/README.md b/solution/0900-0999/0928.Minimize Malware Spread II/README.md index 185f9cbaeda79..e81f29ad3b35c 100644 --- a/solution/0900-0999/0928.Minimize Malware Spread II/README.md +++ b/solution/0900-0999/0928.Minimize Malware Spread II/README.md @@ -61,85 +61,10 @@ ## 解法 - - -逆向思维并查集。对于本题,先遍历所有未被感染的节点(即不在 initial 列表的节点),构造并查集,并且在集合根节点维护 size,表示当前集合的节点数。 - -然后找到只被一个 initial 节点感染的集合,求得感染节点数的最小值。 - -> 被某个 initial 节点感染的集合,节点数越多,若移除此 initial 节点,感染的节点数就越少。 - -以下是并查集的几个常用模板。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` +### 方法一 -### **Python3** - - - ```python class Solution: def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int: @@ -182,10 +107,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -264,8 +185,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -323,8 +242,6 @@ public: }; ``` -### **Go** - ```go func minMalwareSpread(graph [][]int, initial []int) int { n := len(graph) @@ -393,10 +310,6 @@ func minMalwareSpread(graph [][]int, initial []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0928.Minimize Malware Spread II/README_EN.md b/solution/0900-0999/0928.Minimize Malware Spread II/README_EN.md index c4fc57081ef35..336f26fdce377 100644 --- a/solution/0900-0999/0928.Minimize Malware Spread II/README_EN.md +++ b/solution/0900-0999/0928.Minimize Malware Spread II/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -88,8 +88,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] p; @@ -168,8 +166,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -227,8 +223,6 @@ public: }; ``` -### **Go** - ```go func minMalwareSpread(graph [][]int, initial []int) int { n := len(graph) @@ -297,10 +291,6 @@ func minMalwareSpread(graph [][]int, initial []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0929.Unique Email Addresses/README.md b/solution/0900-0999/0929.Unique Email Addresses/README.md index 8dd3246590190..ee29f3ebd5a49 100644 --- a/solution/0900-0999/0929.Unique Email Addresses/README.md +++ b/solution/0900-0999/0929.Unique Email Addresses/README.md @@ -59,18 +59,12 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 利用哈希表存放转换后的电子邮件,最后返回哈希表的 size 即可。 -### **Python3** - - - ```python class Solution: def numUniqueEmails(self, emails: List[str]) -> int: @@ -84,10 +78,6 @@ class Solution: return len(s) ``` -### **Java** - - - ```java class Solution { public int numUniqueEmails(String[] emails) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func numUniqueEmails(emails []string) int { s := map[string]bool{} @@ -145,7 +131,41 @@ func numUniqueEmails(emails []string) int { } ``` -### **JavaScript** +```ts +function numUniqueEmails(emails: string[]): number { + return new Set( + emails + .map(email => email.split('@')) + .map(([start, end]) => start.replace(/\+.*|\./g, '') + '@' + end), + ).size; +} +``` + +```rust +use std::collections::HashSet; +impl Solution { + pub fn num_unique_emails(emails: Vec) -> i32 { + let mut set = HashSet::new(); + for email in emails.iter() { + let res: Vec<&str> = email.split('@').collect(); + let mut s = String::new(); + for &c in res[0].as_bytes().iter() { + if c == b'.' { + continue; + } + if c == b'+' { + break; + } + s.push(c as char); + } + s.push('@'); + s.push_str(res[1]); + set.insert(s); + } + set.len() as i32 + } +} +``` ```js const numUniqueEmails2 = function (emails) { @@ -190,50 +210,6 @@ const numUniqueEmails = function (emails) { }; ``` -### **TypeScript** - -```ts -function numUniqueEmails(emails: string[]): number { - return new Set( - emails - .map(email => email.split('@')) - .map(([start, end]) => start.replace(/\+.*|\./g, '') + '@' + end), - ).size; -} -``` - -### **Rust** - -```rust -use std::collections::HashSet; -impl Solution { - pub fn num_unique_emails(emails: Vec) -> i32 { - let mut set = HashSet::new(); - for email in emails.iter() { - let res: Vec<&str> = email.split('@').collect(); - let mut s = String::new(); - for &c in res[0].as_bytes().iter() { - if c == b'.' { - continue; - } - if c == b'+' { - break; - } - s.push(c as char); - } - s.push('@'); - s.push_str(res[1]); - set.insert(s); - } - set.len() as i32 - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0929.Unique Email Addresses/README_EN.md b/solution/0900-0999/0929.Unique Email Addresses/README_EN.md index 7c6019d3e9635..4ec70401d94f2 100644 --- a/solution/0900-0999/0929.Unique Email Addresses/README_EN.md +++ b/solution/0900-0999/0929.Unique Email Addresses/README_EN.md @@ -57,9 +57,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return len(s) ``` -### **Java** - ```java class Solution { public int numUniqueEmails(String[] emails) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +113,6 @@ public: }; ``` -### **Go** - ```go func numUniqueEmails(emails []string) int { s := map[string]bool{} @@ -133,7 +127,41 @@ func numUniqueEmails(emails []string) int { } ``` -### **JavaScript** +```ts +function numUniqueEmails(emails: string[]): number { + return new Set( + emails + .map(email => email.split('@')) + .map(([start, end]) => start.replace(/\+.*|\./g, '') + '@' + end), + ).size; +} +``` + +```rust +use std::collections::HashSet; +impl Solution { + pub fn num_unique_emails(emails: Vec) -> i32 { + let mut set = HashSet::new(); + for email in emails.iter() { + let res: Vec<&str> = email.split('@').collect(); + let mut s = String::new(); + for &c in res[0].as_bytes().iter() { + if c == b'.' { + continue; + } + if c == b'+' { + break; + } + s.push(c as char); + } + s.push('@'); + s.push_str(res[1]); + set.insert(s); + } + set.len() as i32 + } +} +``` ```js const numUniqueEmails2 = function (emails) { @@ -178,50 +206,6 @@ const numUniqueEmails = function (emails) { }; ``` -### **TypeScript** - -```ts -function numUniqueEmails(emails: string[]): number { - return new Set( - emails - .map(email => email.split('@')) - .map(([start, end]) => start.replace(/\+.*|\./g, '') + '@' + end), - ).size; -} -``` - -### **Rust** - -```rust -use std::collections::HashSet; -impl Solution { - pub fn num_unique_emails(emails: Vec) -> i32 { - let mut set = HashSet::new(); - for email in emails.iter() { - let res: Vec<&str> = email.split('@').collect(); - let mut s = String::new(); - for &c in res[0].as_bytes().iter() { - if c == b'.' { - continue; - } - if c == b'+' { - break; - } - s.push(c as char); - } - s.push('@'); - s.push_str(res[1]); - set.insert(s); - } - set.len() as i32 - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0930.Binary Subarrays With Sum/README.md b/solution/0900-0999/0930.Binary Subarrays With Sum/README.md index fbb0839cf83db..4234c3f42b9fc 100644 --- a/solution/0900-0999/0930.Binary Subarrays With Sum/README.md +++ b/solution/0900-0999/0930.Binary Subarrays With Sum/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:数组或哈希表 + 前缀和** +### 方法一:数组或哈希表 + 前缀和 我们可以用数组或哈希表 $cnt$ 记录每个前缀和出现的次数,其中 $cnt[i]$ 表示前缀和为 $i$ 的子数组个数。初始时 $cnt[0] = 1$。 @@ -52,14 +50,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。 -**方法二:双指针** - -### **Python3** - - - ```python class Solution: def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: @@ -72,6 +64,85 @@ class Solution: return ans ``` +```java +class Solution { + public int numSubarraysWithSum(int[] nums, int goal) { + int[] cnt = new int[nums.length + 1]; + cnt[0] = 1; + int ans = 0, s = 0; + for (int v : nums) { + s += v; + if (s - goal >= 0) { + ans += cnt[s - goal]; + } + ++cnt[s]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int numSubarraysWithSum(vector& nums, int goal) { + int cnt[nums.size() + 1]; + memset(cnt, 0, sizeof cnt); + cnt[0] = 1; + int ans = 0, s = 0; + for (int& v : nums) { + s += v; + if (s - goal >= 0) { + ans += cnt[s - goal]; + } + ++cnt[s]; + } + return ans; + } +}; +``` + +```go +func numSubarraysWithSum(nums []int, goal int) (ans int) { + cnt := map[int]int{0: 1} + s := 0 + for _, v := range nums { + s += v + ans += cnt[s-goal] + cnt[s]++ + } + return +} +``` + +```js +/** + * @param {number[]} nums + * @param {number} goal + * @return {number} + */ +var numSubarraysWithSum = function (nums, goal) { + const cnt = new Array(nums.length + 1).fill(0); + cnt[0] = 1; + let ans = 0; + let s = 0; + for (const v of nums) { + s += v; + if (s >= goal) { + ans += cnt[s - goal]; + } + ++cnt[s]; + } + return ans; +}; +``` + + + +### 方法二:双指针 + + + ```python class Solution: def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: @@ -91,28 +162,6 @@ class Solution: return ans ``` -### **Java** - - - -```java -class Solution { - public int numSubarraysWithSum(int[] nums, int goal) { - int[] cnt = new int[nums.length + 1]; - cnt[0] = 1; - int ans = 0, s = 0; - for (int v : nums) { - s += v; - if (s - goal >= 0) { - ans += cnt[s - goal]; - } - ++cnt[s]; - } - return ans; - } -} -``` - ```java class Solution { public int numSubarraysWithSum(int[] nums, int goal) { @@ -135,28 +184,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numSubarraysWithSum(vector& nums, int goal) { - int cnt[nums.size() + 1]; - memset(cnt, 0, sizeof cnt); - cnt[0] = 1; - int ans = 0, s = 0; - for (int& v : nums) { - s += v; - if (s - goal >= 0) { - ans += cnt[s - goal]; - } - ++cnt[s]; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -176,21 +203,6 @@ public: }; ``` -### **Go** - -```go -func numSubarraysWithSum(nums []int, goal int) (ans int) { - cnt := map[int]int{0: 1} - s := 0 - for _, v := range nums { - s += v - ans += cnt[s-goal] - cnt[s]++ - } - return -} -``` - ```go func numSubarraysWithSum(nums []int, goal int) int { i1, i2, s1, s2, j, ans, n := 0, 0, 0, 0, 0, 0, len(nums) @@ -212,30 +224,6 @@ func numSubarraysWithSum(nums []int, goal int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} goal - * @return {number} - */ -var numSubarraysWithSum = function (nums, goal) { - const cnt = new Array(nums.length + 1).fill(0); - cnt[0] = 1; - let ans = 0; - let s = 0; - for (const v of nums) { - s += v; - if (s >= goal) { - ans += cnt[s - goal]; - } - ++cnt[s]; - } - return ans; -}; -``` - ```js /** * @param {number[]} nums @@ -262,10 +250,6 @@ var numSubarraysWithSum = function (nums, goal) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0930.Binary Subarrays With Sum/README_EN.md b/solution/0900-0999/0930.Binary Subarrays With Sum/README_EN.md index dfc9157dd9bb6..9d600a0cca0e7 100644 --- a/solution/0900-0999/0930.Binary Subarrays With Sum/README_EN.md +++ b/solution/0900-0999/0930.Binary Subarrays With Sum/README_EN.md @@ -52,9 +52,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,6 +68,85 @@ class Solution: return ans ``` +```java +class Solution { + public int numSubarraysWithSum(int[] nums, int goal) { + int[] cnt = new int[nums.length + 1]; + cnt[0] = 1; + int ans = 0, s = 0; + for (int v : nums) { + s += v; + if (s - goal >= 0) { + ans += cnt[s - goal]; + } + ++cnt[s]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int numSubarraysWithSum(vector& nums, int goal) { + int cnt[nums.size() + 1]; + memset(cnt, 0, sizeof cnt); + cnt[0] = 1; + int ans = 0, s = 0; + for (int& v : nums) { + s += v; + if (s - goal >= 0) { + ans += cnt[s - goal]; + } + ++cnt[s]; + } + return ans; + } +}; +``` + +```go +func numSubarraysWithSum(nums []int, goal int) (ans int) { + cnt := map[int]int{0: 1} + s := 0 + for _, v := range nums { + s += v + ans += cnt[s-goal] + cnt[s]++ + } + return +} +``` + +```js +/** + * @param {number[]} nums + * @param {number} goal + * @return {number} + */ +var numSubarraysWithSum = function (nums, goal) { + const cnt = new Array(nums.length + 1).fill(0); + cnt[0] = 1; + let ans = 0; + let s = 0; + for (const v of nums) { + s += v; + if (s >= goal) { + ans += cnt[s - goal]; + } + ++cnt[s]; + } + return ans; +}; +``` + + + +### Solution 2 + + + ```python class Solution: def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: @@ -87,26 +166,6 @@ class Solution: return ans ``` -### **Java** - -```java -class Solution { - public int numSubarraysWithSum(int[] nums, int goal) { - int[] cnt = new int[nums.length + 1]; - cnt[0] = 1; - int ans = 0, s = 0; - for (int v : nums) { - s += v; - if (s - goal >= 0) { - ans += cnt[s - goal]; - } - ++cnt[s]; - } - return ans; - } -} -``` - ```java class Solution { public int numSubarraysWithSum(int[] nums, int goal) { @@ -129,28 +188,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numSubarraysWithSum(vector& nums, int goal) { - int cnt[nums.size() + 1]; - memset(cnt, 0, sizeof cnt); - cnt[0] = 1; - int ans = 0, s = 0; - for (int& v : nums) { - s += v; - if (s - goal >= 0) { - ans += cnt[s - goal]; - } - ++cnt[s]; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -170,21 +207,6 @@ public: }; ``` -### **Go** - -```go -func numSubarraysWithSum(nums []int, goal int) (ans int) { - cnt := map[int]int{0: 1} - s := 0 - for _, v := range nums { - s += v - ans += cnt[s-goal] - cnt[s]++ - } - return -} -``` - ```go func numSubarraysWithSum(nums []int, goal int) int { i1, i2, s1, s2, j, ans, n := 0, 0, 0, 0, 0, 0, len(nums) @@ -206,30 +228,6 @@ func numSubarraysWithSum(nums []int, goal int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} goal - * @return {number} - */ -var numSubarraysWithSum = function (nums, goal) { - const cnt = new Array(nums.length + 1).fill(0); - cnt[0] = 1; - let ans = 0; - let s = 0; - for (const v of nums) { - s += v; - if (s >= goal) { - ans += cnt[s - goal]; - } - ++cnt[s]; - } - return ans; -}; -``` - ```js /** * @param {number[]} nums @@ -256,10 +254,6 @@ var numSubarraysWithSum = function (nums, goal) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0931.Minimum Falling Path Sum/README.md b/solution/0900-0999/0931.Minimum Falling Path Sum/README.md index 3f894a63b564f..07a95e9d430fd 100644 --- a/solution/0900-0999/0931.Minimum Falling Path Sum/README.md +++ b/solution/0900-0999/0931.Minimum Falling Path Sum/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示从第一行开始下降,到达第 $i$ 行第 $j$ 列的最小路径和。那么我们可以得到这样的动态规划转移方程: @@ -62,10 +60,6 @@ $$ -### **Python3** - - - ```python class Solution: def minFallingPathSum(self, matrix: List[List[int]]) -> int: @@ -80,10 +74,6 @@ class Solution: return min(f) ``` -### **Java** - - - ```java class Solution { public int minFallingPathSum(int[][] matrix) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func minFallingPathSum(matrix [][]int) int { n := len(matrix) @@ -162,8 +148,6 @@ func minFallingPathSum(matrix [][]int) int { } ``` -### **TypeScript** - ```ts function minFallingPathSum(matrix: number[][]): number { const n = matrix.length; @@ -185,10 +169,6 @@ function minFallingPathSum(matrix: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0931.Minimum Falling Path Sum/README_EN.md b/solution/0900-0999/0931.Minimum Falling Path Sum/README_EN.md index 72adc52be8882..c828f219947e0 100644 --- a/solution/0900-0999/0931.Minimum Falling Path Sum/README_EN.md +++ b/solution/0900-0999/0931.Minimum Falling Path Sum/README_EN.md @@ -36,12 +36,10 @@ ## Solutions -Dynamic programming. +### Solution 1 -### **Python3** - ```python class Solution: def minFallingPathSum(self, matrix: List[List[int]]) -> int: @@ -56,8 +54,6 @@ class Solution: return min(f) ``` -### **Java** - ```java class Solution { public int minFallingPathSum(int[][] matrix) { @@ -86,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +106,6 @@ public: }; ``` -### **Go** - ```go func minFallingPathSum(matrix [][]int) int { n := len(matrix) @@ -136,8 +128,6 @@ func minFallingPathSum(matrix [][]int) int { } ``` -### **TypeScript** - ```ts function minFallingPathSum(matrix: number[][]): number { const n = matrix.length; @@ -159,10 +149,6 @@ function minFallingPathSum(matrix: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0932.Beautiful Array/README.md b/solution/0900-0999/0932.Beautiful Array/README.md index 1c8db820d72ac..29f0ce7c8ec0c 100644 --- a/solution/0900-0999/0932.Beautiful Array/README.md +++ b/solution/0900-0999/0932.Beautiful Array/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:分治** +### 方法一:分治 根据题意,漂亮数组 $A$ 需要满足对于任意 $i -### **Python3** - - - ```python class Solution: def beautifulArray(self, n: int) -> List[int]: @@ -77,10 +71,6 @@ class Solution: return left + right ``` -### **Java** - - - ```java class Solution { public int[] beautifulArray(int n) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func beautifulArray(n int) []int { if n == 1 { @@ -140,10 +126,6 @@ func beautifulArray(n int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0932.Beautiful Array/README_EN.md b/solution/0900-0999/0932.Beautiful Array/README_EN.md index 330b3db71b5f2..1f8167cbc0ad3 100644 --- a/solution/0900-0999/0932.Beautiful Array/README_EN.md +++ b/solution/0900-0999/0932.Beautiful Array/README_EN.md @@ -30,9 +30,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -46,8 +46,6 @@ class Solution: return left + right ``` -### **Java** - ```java class Solution { public int[] beautifulArray(int n) { @@ -69,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +83,6 @@ public: }; ``` -### **Go** - ```go func beautifulArray(n int) []int { if n == 1 { @@ -107,10 +101,6 @@ func beautifulArray(n int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0933.Number of Recent Calls/README.md b/solution/0900-0999/0933.Number of Recent Calls/README.md index ae7fe3f7ef85b..15f17c6195835 100644 --- a/solution/0900-0999/0933.Number of Recent Calls/README.md +++ b/solution/0900-0999/0933.Number of Recent Calls/README.md @@ -48,9 +48,7 @@ recentCounter.ping(3002); // requests = [1, 100, 3001< ## 解法 - - -**方法一:队列** +### 方法一:队列 由题得知,`t` 是**严格递增**的,当一个元素不满足 `[t - 3000, t]` 条件时,在后续的请求当中,它也不可能满足。 @@ -58,16 +56,8 @@ recentCounter.ping(3002); // requests = [1, 100, 3001< 可以使用队列。每次将 `t` 进入队尾,同时从队头开始,依次移除小于 `t - 3000` 的元素。然后返回队列的大小(`q.size()`)即可。 -**方法二:二分查找** - -`t` 严格单调递增,非常适合用二分查找来定位 `[t-3000, t]` 的左右边界。 - -### **Python3** - - - ```python class RecentCounter: def __init__(self): @@ -85,25 +75,6 @@ class RecentCounter: # param_1 = obj.ping(t) ``` -```python -class RecentCounter: - def __init__(self): - self.s = [] - - def ping(self, t: int) -> int: - self.s.append(t) - return len(self.s) - bisect_left(self.s, t - 3000) - - -# Your RecentCounter object will be instantiated and called as such: -# obj = RecentCounter() -# param_1 = obj.ping(t) -``` - -### **Java** - - - ```java class RecentCounter { private int[] s = new int[10010]; @@ -138,8 +109,6 @@ class RecentCounter { */ ``` -### **C++** - ```cpp class RecentCounter { public: @@ -162,29 +131,6 @@ public: */ ``` -```cpp -class RecentCounter { -public: - vector s; - - RecentCounter() { - } - - int ping(int t) { - s.push_back(t); - return s.size() - (lower_bound(s.begin(), s.end(), t - 3000) - s.begin()); - } -}; - -/** - * Your RecentCounter object will be instantiated and called as such: - * RecentCounter* obj = new RecentCounter(); - * int param_1 = obj->ping(t); - */ -``` - -### **Go** - ```go type RecentCounter struct { q []int @@ -209,40 +155,63 @@ func (this *RecentCounter) Ping(t int) int { */ ``` -```go -type RecentCounter struct { - s []int -} +```ts +class RecentCounter { + private queue: number[]; -func Constructor() RecentCounter { - return RecentCounter{[]int{}} -} + constructor() { + this.queue = []; + } -func (this *RecentCounter) Ping(t int) int { - this.s = append(this.s, t) - search := func(x int) int { - left, right := 0, len(this.s) - for left < right { - mid := (left + right) >> 1 - if this.s[mid] >= x { - right = mid - } else { - left = mid + 1 - } - } - return left - } - return len(this.s) - search(t-3000) + ping(t: number): number { + this.queue.push(t); + while (this.queue[0] < t - 3000) { + this.queue.shift(); + } + return this.queue.length; + } } /** * Your RecentCounter object will be instantiated and called as such: - * obj := Constructor(); - * param_1 := obj.Ping(t); + * var obj = new RecentCounter() + * var param_1 = obj.ping(t) */ ``` -### **JavaScript** +```rust +use std::collections::VecDeque; +struct RecentCounter { + queue: VecDeque, +} + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl RecentCounter { + fn new() -> Self { + Self { + queue: VecDeque::new(), + } + } + + fn ping(&mut self, t: i32) -> i32 { + self.queue.push_back(t); + while let Some(&v) = self.queue.front() { + if v >= t - 3000 { + break; + } + self.queue.pop_front(); + } + self.queue.len() as i32 + } +}/** + * Your RecentCounter object will be instantiated and called as such: + * let obj = RecentCounter::new(); + * let ret_1: i32 = obj.ping(t); + */ +``` ```js var RecentCounter = function () { @@ -268,8 +237,6 @@ RecentCounter.prototype.ping = function (t) { */ ``` -### **C#** - ```cs public class RecentCounter { private Queue q = new Queue(); @@ -295,72 +262,83 @@ public class RecentCounter { */ ``` -### **TypeScript** + + +### 方法二:二分查找 -```ts +`t` 严格单调递增,非常适合用二分查找来定位 `[t-3000, t]` 的左右边界。 + + + +```python +class RecentCounter: + def __init__(self): + self.s = [] + + def ping(self, t: int) -> int: + self.s.append(t) + return len(self.s) - bisect_left(self.s, t - 3000) + + +# Your RecentCounter object will be instantiated and called as such: +# obj = RecentCounter() +# param_1 = obj.ping(t) +``` + +```cpp class RecentCounter { - private queue: number[]; +public: + vector s; - constructor() { - this.queue = []; + RecentCounter() { } - ping(t: number): number { - this.queue.push(t); - while (this.queue[0] < t - 3000) { - this.queue.shift(); - } - return this.queue.length; + int ping(int t) { + s.push_back(t); + return s.size() - (lower_bound(s.begin(), s.end(), t - 3000) - s.begin()); } -} +}; /** * Your RecentCounter object will be instantiated and called as such: - * var obj = new RecentCounter() - * var param_1 = obj.ping(t) + * RecentCounter* obj = new RecentCounter(); + * int param_1 = obj->ping(t); */ ``` -### **Rust** +```go +type RecentCounter struct { + s []int +} + +func Constructor() RecentCounter { + return RecentCounter{[]int{}} +} -```rust -use std::collections::VecDeque; -struct RecentCounter { - queue: VecDeque, +func (this *RecentCounter) Ping(t int) int { + this.s = append(this.s, t) + search := func(x int) int { + left, right := 0, len(this.s) + for left < right { + mid := (left + right) >> 1 + if this.s[mid] >= x { + right = mid + } else { + left = mid + 1 + } + } + return left + } + return len(this.s) - search(t-3000) } /** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl RecentCounter { - fn new() -> Self { - Self { - queue: VecDeque::new(), - } - } - - fn ping(&mut self, t: i32) -> i32 { - self.queue.push_back(t); - while let Some(&v) = self.queue.front() { - if v >= t - 3000 { - break; - } - self.queue.pop_front(); - } - self.queue.len() as i32 - } -}/** * Your RecentCounter object will be instantiated and called as such: - * let obj = RecentCounter::new(); - * let ret_1: i32 = obj.ping(t); + * obj := Constructor(); + * param_1 := obj.Ping(t); */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0933.Number of Recent Calls/README_EN.md b/solution/0900-0999/0933.Number of Recent Calls/README_EN.md index 2102260417400..ffcd4f9abe66a 100644 --- a/solution/0900-0999/0933.Number of Recent Calls/README_EN.md +++ b/solution/0900-0999/0933.Number of Recent Calls/README_EN.md @@ -44,9 +44,9 @@ recentCounter.ping(3002); // requests = [1, 100, 3001, 3002 +### Solution 1 -### **Python3** + ```python class RecentCounter: @@ -65,46 +65,6 @@ class RecentCounter: # param_1 = obj.ping(t) ``` -```python -class RecentCounter: - def __init__(self): - self.s = [] - - def ping(self, t: int) -> int: - self.s.append(t) - return len(self.s) - bisect_left(self.s, t - 3000) - - -# Your RecentCounter object will be instantiated and called as such: -# obj = RecentCounter() -# param_1 = obj.ping(t) -``` - -### **Java** - -```java -class RecentCounter { - private Deque q = new ArrayDeque<>(); - - public RecentCounter() { - } - - public int ping(int t) { - q.offer(t); - while (q.peekFirst() < t - 3000) { - q.pollFirst(); - } - return q.size(); - } -} - -/** - * Your RecentCounter object will be instantiated and called as such: - * RecentCounter obj = new RecentCounter(); - * int param_1 = obj.ping(t); - */ -``` - ```java class RecentCounter { private int[] s = new int[10010]; @@ -139,8 +99,6 @@ class RecentCounter { */ ``` -### **C++** - ```cpp class RecentCounter { public: @@ -163,29 +121,6 @@ public: */ ``` -```cpp -class RecentCounter { -public: - vector s; - - RecentCounter() { - } - - int ping(int t) { - s.push_back(t); - return s.size() - (lower_bound(s.begin(), s.end(), t - 3000) - s.begin()); - } -}; - -/** - * Your RecentCounter object will be instantiated and called as such: - * RecentCounter* obj = new RecentCounter(); - * int param_1 = obj->ping(t); - */ -``` - -### **Go** - ```go type RecentCounter struct { q []int @@ -210,40 +145,63 @@ func (this *RecentCounter) Ping(t int) int { */ ``` -```go -type RecentCounter struct { - s []int -} +```ts +class RecentCounter { + private queue: number[]; -func Constructor() RecentCounter { - return RecentCounter{[]int{}} -} + constructor() { + this.queue = []; + } -func (this *RecentCounter) Ping(t int) int { - this.s = append(this.s, t) - search := func(x int) int { - left, right := 0, len(this.s) - for left < right { - mid := (left + right) >> 1 - if this.s[mid] >= x { - right = mid - } else { - left = mid + 1 - } - } - return left - } - return len(this.s) - search(t-3000) + ping(t: number): number { + this.queue.push(t); + while (this.queue[0] < t - 3000) { + this.queue.shift(); + } + return this.queue.length; + } } /** * Your RecentCounter object will be instantiated and called as such: - * obj := Constructor(); - * param_1 := obj.Ping(t); + * var obj = new RecentCounter() + * var param_1 = obj.ping(t) */ ``` -### **JavaScript** +```rust +use std::collections::VecDeque; +struct RecentCounter { + queue: VecDeque, +} + +/** + * `&self` means the method takes an immutable reference. + * If you need a mutable reference, change it to `&mut self` instead. + */ +impl RecentCounter { + fn new() -> Self { + Self { + queue: VecDeque::new(), + } + } + + fn ping(&mut self, t: i32) -> i32 { + self.queue.push_back(t); + while let Some(&v) = self.queue.front() { + if v >= t - 3000 { + break; + } + self.queue.pop_front(); + } + self.queue.len() as i32 + } +}/** + * Your RecentCounter object will be instantiated and called as such: + * let obj = RecentCounter::new(); + * let ret_1: i32 = obj.ping(t); + */ +``` ```js var RecentCounter = function () { @@ -269,8 +227,6 @@ RecentCounter.prototype.ping = function (t) { */ ``` -### **C#** - ```cs public class RecentCounter { private Queue q = new Queue(); @@ -296,72 +252,81 @@ public class RecentCounter { */ ``` -### **TypeScript** + + +### Solution 2 -```ts + + +```python +class RecentCounter: + def __init__(self): + self.s = [] + + def ping(self, t: int) -> int: + self.s.append(t) + return len(self.s) - bisect_left(self.s, t - 3000) + + +# Your RecentCounter object will be instantiated and called as such: +# obj = RecentCounter() +# param_1 = obj.ping(t) +``` + +```cpp class RecentCounter { - private queue: number[]; +public: + vector s; - constructor() { - this.queue = []; + RecentCounter() { } - ping(t: number): number { - this.queue.push(t); - while (this.queue[0] < t - 3000) { - this.queue.shift(); - } - return this.queue.length; + int ping(int t) { + s.push_back(t); + return s.size() - (lower_bound(s.begin(), s.end(), t - 3000) - s.begin()); } -} +}; /** * Your RecentCounter object will be instantiated and called as such: - * var obj = new RecentCounter() - * var param_1 = obj.ping(t) + * RecentCounter* obj = new RecentCounter(); + * int param_1 = obj->ping(t); */ ``` -### **Rust** +```go +type RecentCounter struct { + s []int +} -```rust -use std::collections::VecDeque; -struct RecentCounter { - queue: VecDeque, +func Constructor() RecentCounter { + return RecentCounter{[]int{}} } -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl RecentCounter { - fn new() -> Self { - Self { - queue: VecDeque::new(), - } - } +func (this *RecentCounter) Ping(t int) int { + this.s = append(this.s, t) + search := func(x int) int { + left, right := 0, len(this.s) + for left < right { + mid := (left + right) >> 1 + if this.s[mid] >= x { + right = mid + } else { + left = mid + 1 + } + } + return left + } + return len(this.s) - search(t-3000) +} - fn ping(&mut self, t: i32) -> i32 { - self.queue.push_back(t); - while let Some(&v) = self.queue.front() { - if v >= t - 3000 { - break; - } - self.queue.pop_front(); - } - self.queue.len() as i32 - } -}/** +/** * Your RecentCounter object will be instantiated and called as such: - * let obj = RecentCounter::new(); - * let ret_1: i32 = obj.ping(t); + * obj := Constructor(); + * param_1 := obj.Ping(t); */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0934.Shortest Bridge/README.md b/solution/0900-0999/0934.Shortest Bridge/README.md index 2de4c7b2f0d87..724f5a9fa9a1e 100644 --- a/solution/0900-0999/0934.Shortest Bridge/README.md +++ b/solution/0900-0999/0934.Shortest Bridge/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:DFS + BFS** +### 方法一:DFS + BFS 题目求解的是最小翻转次数,使得两个岛屿相连,实际上等价于求解两个岛屿之间的最短距离。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def shortestBridge(self, grid: List[List[int]]) -> int: @@ -103,10 +97,6 @@ class Solution: ans += 1 ``` -### **Java** - - - ```java class Solution { private int[] dirs = {-1, 0, 1, 0, -1}; @@ -160,8 +150,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -211,8 +199,6 @@ public: }; ``` -### **Go** - ```go func shortestBridge(grid [][]int) (ans int) { n := len(grid) @@ -261,10 +247,6 @@ func shortestBridge(grid [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0934.Shortest Bridge/README_EN.md b/solution/0900-0999/0934.Shortest Bridge/README_EN.md index 7290b61e8de4f..fbf542c851051 100644 --- a/solution/0900-0999/0934.Shortest Bridge/README_EN.md +++ b/solution/0900-0999/0934.Shortest Bridge/README_EN.md @@ -46,12 +46,10 @@ ## Solutions -DFS & BFS. +### Solution 1 -### **Python3** - ```python class Solution: def shortestBridge(self, grid: List[List[int]]) -> int: @@ -83,8 +81,6 @@ class Solution: ans += 1 ``` -### **Java** - ```java class Solution { private int[] dirs = {-1, 0, 1, 0, -1}; @@ -138,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -189,8 +183,6 @@ public: }; ``` -### **Go** - ```go func shortestBridge(grid [][]int) (ans int) { n := len(grid) @@ -239,10 +231,6 @@ func shortestBridge(grid [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0935.Knight Dialer/README.md b/solution/0900-0999/0935.Knight Dialer/README.md index fe659f82668ea..2cdb1a3c55786 100644 --- a/solution/0900-0999/0935.Knight Dialer/README.md +++ b/solution/0900-0999/0935.Knight Dialer/README.md @@ -61,16 +61,10 @@ ## 解法 - - -**方法一:递推** +### 方法一:递推 -### **Python3** - - - ```python class Solution: def knightDialer(self, n: int) -> int: @@ -92,10 +86,6 @@ class Solution: return sum(t) % (10**9 + 7) ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -160,8 +148,6 @@ public: }; ``` -### **Go** - ```go func knightDialer(n int) int { if n == 1 { @@ -195,37 +181,6 @@ func knightDialer(n int) int { } ``` -### **C#** - -```cs -public class Solution { - public int KnightDialer(int n) { - if (n == 1) return 10; - int A = 4; - int B = 2; - int C = 2; - int D = 1; - int MOD = (int)1e9 + 7; - for (int i = 0; i < n - 1; i++) { - int tempA = A; - int tempB = B; - int tempC = C; - int tempD = D; - A = ((2 * tempB) % MOD + (2 * tempC) % MOD) % MOD; - B = tempA; - C = (tempA + (2 * tempD) % MOD) % MOD; - D = tempC; - } - - int ans = (A + B) % MOD; - ans = (ans + C) % MOD; - return (ans + D) % MOD; - } -} -``` - -### **TypeScript** - ```ts function knightDialer(n: number): number { const MOD: number = 1e9 + 7; @@ -263,10 +218,33 @@ function knightDialer(n: number): number { } ``` -### **...** - -``` +```cs +public class Solution { + public int KnightDialer(int n) { + if (n == 1) return 10; + int A = 4; + int B = 2; + int C = 2; + int D = 1; + int MOD = (int)1e9 + 7; + for (int i = 0; i < n - 1; i++) { + int tempA = A; + int tempB = B; + int tempC = C; + int tempD = D; + A = ((2 * tempB) % MOD + (2 * tempC) % MOD) % MOD; + B = tempA; + C = (tempA + (2 * tempD) % MOD) % MOD; + D = tempC; + } + int ans = (A + B) % MOD; + ans = (ans + C) % MOD; + return (ans + D) % MOD; + } +} ``` + + diff --git a/solution/0900-0999/0935.Knight Dialer/README_EN.md b/solution/0900-0999/0935.Knight Dialer/README_EN.md index de7b48665e3ea..5909fdd613d8a 100644 --- a/solution/0900-0999/0935.Knight Dialer/README_EN.md +++ b/solution/0900-0999/0935.Knight Dialer/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return sum(t) % (10**9 + 7) ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -141,8 +137,6 @@ public: }; ``` -### **Go** - ```go func knightDialer(n int) int { if n == 1 { @@ -176,37 +170,6 @@ func knightDialer(n int) int { } ``` -### **C#** - -```cs -public class Solution { - public int KnightDialer(int n) { - if (n == 1) return 10; - int A = 4; - int B = 2; - int C = 2; - int D = 1; - int MOD = (int)1e9 + 7; - for (int i = 0; i < n - 1; i++) { - int tempA = A; - int tempB = B; - int tempC = C; - int tempD = D; - A = ((2 * tempB) % MOD + (2 * tempC) % MOD) % MOD; - B = tempA; - C = (tempA + (2 * tempD) % MOD) % MOD; - D = tempC; - } - - int ans = (A + B) % MOD; - ans = (ans + C) % MOD; - return (ans + D) % MOD; - } -} -``` - -### **TypeScript** - ```ts function knightDialer(n: number): number { const MOD: number = 1e9 + 7; @@ -244,10 +207,33 @@ function knightDialer(n: number): number { } ``` -### **...** - -``` +```cs +public class Solution { + public int KnightDialer(int n) { + if (n == 1) return 10; + int A = 4; + int B = 2; + int C = 2; + int D = 1; + int MOD = (int)1e9 + 7; + for (int i = 0; i < n - 1; i++) { + int tempA = A; + int tempB = B; + int tempC = C; + int tempD = D; + A = ((2 * tempB) % MOD + (2 * tempC) % MOD) % MOD; + B = tempA; + C = (tempA + (2 * tempD) % MOD) % MOD; + D = tempC; + } + int ans = (A + B) % MOD; + ans = (ans + C) % MOD; + return (ans + D) % MOD; + } +} ``` + + diff --git a/solution/0900-0999/0936.Stamping The Sequence/README.md b/solution/0900-0999/0936.Stamping The Sequence/README.md index 774a72fd847e2..185ced336437c 100644 --- a/solution/0900-0999/0936.Stamping The Sequence/README.md +++ b/solution/0900-0999/0936.Stamping The Sequence/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:逆向思维 + 拓扑排序** +### 方法一:逆向思维 + 拓扑排序 如果我们正向地对序列进行操作,那么处理起来会比较麻烦,因为后续的操作会把前面的操作覆盖掉。我们不妨考虑逆向地对序列进行操作,即从目标字符串 $target$ 开始,考虑将 $target$ 变成 $?????$ 的过程。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def movesToStamp(self, stamp: str, target: str) -> List[int]: @@ -106,10 +100,6 @@ class Solution: return ans[::-1] if all(vis) else [] ``` -### **Java** - - - ```java class Solution { public int[] movesToStamp(String stamp, String target) { @@ -157,8 +147,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -206,8 +194,6 @@ public: }; ``` -### **Go** - ```go func movesToStamp(stamp string, target string) (ans []int) { m, n := len(stamp), len(target) @@ -258,8 +244,6 @@ func movesToStamp(stamp string, target string) (ans []int) { } ``` -### **TypeScript** - ```ts function movesToStamp(stamp: string, target: string): number[] { const m: number = stamp.length; @@ -303,8 +287,6 @@ function movesToStamp(stamp: string, target: string): number[] { } ``` -### **Rust** - ```rust use std::collections::VecDeque; @@ -365,10 +347,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0936.Stamping The Sequence/README_EN.md b/solution/0900-0999/0936.Stamping The Sequence/README_EN.md index 1af6bb710fbaa..e739d19170026 100644 --- a/solution/0900-0999/0936.Stamping The Sequence/README_EN.md +++ b/solution/0900-0999/0936.Stamping The Sequence/README_EN.md @@ -55,7 +55,7 @@ ## Solutions -**Solution 1: Reverse Thinking + Topological Sorting** +### Solution 1: Reverse Thinking + Topological Sorting If we operate on the sequence in a forward manner, it would be quite complicated because subsequent operations would overwrite previous ones. Therefore, we consider operating on the sequence in a reverse manner, i.e., starting from the target string $target$ and considering the process of turning $target$ into $?????$. @@ -79,8 +79,6 @@ The time complexity is $O(n \times (n - m + 1))$, and the space complexity is $O -### **Python3** - ```python class Solution: def movesToStamp(self, stamp: str, target: str) -> List[int]: @@ -111,8 +109,6 @@ class Solution: return ans[::-1] if all(vis) else [] ``` -### **Java** - ```java class Solution { public int[] movesToStamp(String stamp, String target) { @@ -160,8 +156,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -209,8 +203,6 @@ public: }; ``` -### **Go** - ```go func movesToStamp(stamp string, target string) (ans []int) { m, n := len(stamp), len(target) @@ -261,8 +253,6 @@ func movesToStamp(stamp string, target string) (ans []int) { } ``` -### **TypeScript** - ```ts function movesToStamp(stamp: string, target: string): number[] { const m: number = stamp.length; @@ -306,8 +296,6 @@ function movesToStamp(stamp: string, target: string): number[] { } ``` -### **Rust** - ```rust use std::collections::VecDeque; @@ -368,10 +356,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0937.Reorder Data in Log Files/README.md b/solution/0900-0999/0937.Reorder Data in Log Files/README.md index a7d5dd3f6c221..a2455a694ca9d 100644 --- a/solution/0900-0999/0937.Reorder Data in Log Files/README.md +++ b/solution/0900-0999/0937.Reorder Data in Log Files/README.md @@ -57,16 +57,10 @@ ## 解法 - - -**方法一:自定义排序** +### 方法一:自定义排序 -### **Python3** - - - ```python class Solution: def reorderLogFiles(self, logs: List[str]) -> List[str]: @@ -77,10 +71,6 @@ class Solution: return sorted(logs, key=cmp) ``` -### **Java** - - - ```java class Solution { public String[] reorderLogFiles(String[] logs) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function reorderLogFiles(logs: string[]): string[] { const isDigit = (c: string) => c >= '0' && c <= '9'; @@ -132,8 +120,6 @@ function reorderLogFiles(logs: string[]): string[] { } ``` -### **Rust** - ```rust impl Solution { pub fn reorder_log_files(mut logs: Vec) -> Vec { @@ -157,10 +143,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0937.Reorder Data in Log Files/README_EN.md b/solution/0900-0999/0937.Reorder Data in Log Files/README_EN.md index a9e91c44a5d00..9c821e3b28064 100644 --- a/solution/0900-0999/0937.Reorder Data in Log Files/README_EN.md +++ b/solution/0900-0999/0937.Reorder Data in Log Files/README_EN.md @@ -53,9 +53,9 @@ The digit-logs have a relative order of "dig1 8 1 5 1", "dig2 3 6 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return sorted(logs, key=cmp) ``` -### **Java** - ```java class Solution { public String[] reorderLogFiles(String[] logs) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function reorderLogFiles(logs: string[]): string[] { const isDigit = (c: string) => c >= '0' && c <= '9'; @@ -120,8 +116,6 @@ function reorderLogFiles(logs: string[]): string[] { } ``` -### **Rust** - ```rust impl Solution { pub fn reorder_log_files(mut logs: Vec) -> Vec { @@ -145,10 +139,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0938.Range Sum of BST/README.md b/solution/0900-0999/0938.Range Sum of BST/README.md index 773bb875da251..40ddf2badcd9f 100644 --- a/solution/0900-0999/0938.Range Sum of BST/README.md +++ b/solution/0900-0999/0938.Range Sum of BST/README.md @@ -37,14 +37,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -71,10 +67,6 @@ class Solution: return self.ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -108,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -137,8 +127,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -162,10 +150,6 @@ func rangeSumBST(root *TreeNode, low int, high int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0938.Range Sum of BST/README_EN.md b/solution/0900-0999/0938.Range Sum of BST/README_EN.md index eb4f680a38131..73563a4cabfda 100644 --- a/solution/0900-0999/0938.Range Sum of BST/README_EN.md +++ b/solution/0900-0999/0938.Range Sum of BST/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -65,8 +65,6 @@ class Solution: return self.ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -129,8 +125,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -154,10 +148,6 @@ func rangeSumBST(root *TreeNode, low int, high int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0939.Minimum Area Rectangle/README.md b/solution/0900-0999/0939.Minimum Area Rectangle/README.md index 861c5bc827df7..928074172d05f 100644 --- a/solution/0900-0999/0939.Minimum Area Rectangle/README.md +++ b/solution/0900-0999/0939.Minimum Area Rectangle/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:哈希表 + 排序 + 枚举** +### 方法一:哈希表 + 排序 + 枚举 对于每个点,我们将其横坐标作为键,纵坐标作为值存入哈希表 $d$ 中。对于哈希表中的每个键,我们将其对应的纵坐标按照从小到大的顺序排序。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def minAreaRect(self, points: List[List[int]]) -> int: @@ -75,10 +69,6 @@ class Solution: return 0 if ans == inf else ans ``` -### **Java** - - - ```java class Solution { public int minAreaRect(int[][] points) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func minAreaRect(points [][]int) int { d := map[int][]int{} @@ -181,10 +167,6 @@ func minAreaRect(points [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0939.Minimum Area Rectangle/README_EN.md b/solution/0900-0999/0939.Minimum Area Rectangle/README_EN.md index 12ceac185a543..a7852189dc13e 100644 --- a/solution/0900-0999/0939.Minimum Area Rectangle/README_EN.md +++ b/solution/0900-0999/0939.Minimum Area Rectangle/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return 0 if ans == inf else ans ``` -### **Java** - ```java class Solution { public int minAreaRect(int[][] points) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +122,6 @@ public: }; ``` -### **Go** - ```go func minAreaRect(points [][]int) int { d := map[int][]int{} @@ -163,10 +157,6 @@ func minAreaRect(points [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0940.Distinct Subsequences II/README.md b/solution/0900-0999/0940.Distinct Subsequences II/README.md index c158cb9d74cfd..06f05b9b17028 100644 --- a/solution/0900-0999/0940.Distinct Subsequences II/README.md +++ b/solution/0900-0999/0940.Distinct Subsequences II/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 定义 $dp[i]$ 表示以 $s[i]$ 结尾的不同子序列的个数。由于 $s$ 中只包含小写字母,因此我们可以直接创建一个长度为 $26$ 的数组。初始时 $dp$ 所有元素均为 $0$。答案为 $\sum_{i=0}^{25}dp[i]$。 @@ -65,22 +63,8 @@ 时间复杂度 $O(n\times C)$,其中 $n$ 是字符串 $s$ 的长度,而 $C$ 是字符集的大小,本题中 $C=26$。空间复杂度 $O(C)$。 -**方法二:优化的动态规划** - -在方法一的基础上,我们还可以维护当前 $dp$ 数组中所有元素的和 $ans$,这样我们每次更新 $dp[i]$ 时,只需要将 $dp[i]$ 加上 $ans-dp[i]+1$ 即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(C)$。 - -相似题目: - -- [1987. 不同的好子序列数目](/solution/1900-1999/1987.Number%20of%20Unique%20Good%20Subsequences/README.md) - -### **Python3** - - - ```python class Solution: def distinctSubseqII(self, s: str) -> int: @@ -97,35 +81,6 @@ class Solution: return sum(dp[-1]) % mod ``` -```python -class Solution: - def distinctSubseqII(self, s: str) -> int: - mod = 10**9 + 7 - dp = [0] * 26 - for c in s: - i = ord(c) - ord('a') - dp[i] = sum(dp) % mod + 1 - return sum(dp) % mod -``` - -```python -class Solution: - def distinctSubseqII(self, s: str) -> int: - mod = 10**9 + 7 - dp = [0] * 26 - ans = 0 - for c in s: - i = ord(c) - ord('a') - add = ans - dp[i] + 1 - ans = (ans + add) % mod - dp[i] += add - return ans -``` - -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -149,26 +104,6 @@ class Solution { } ``` -```java -class Solution { - private static final int MOD = (int) 1e9 + 7; - - public int distinctSubseqII(String s) { - int[] dp = new int[26]; - int ans = 0; - for (int i = 0; i < s.length(); ++i) { - int j = s.charAt(i) - 'a'; - int add = (ans - dp[j] + 1) % MOD; - ans = (ans + add) % MOD; - dp[j] = (dp[j] + add) % MOD; - } - return (ans + MOD) % MOD; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -185,27 +120,6 @@ public: }; ``` -```cpp -class Solution { -public: - const int mod = 1e9 + 7; - - int distinctSubseqII(string s) { - vector dp(26); - long ans = 0; - for (char& c : s) { - int i = c - 'a'; - long add = ans - dp[i] + 1; - ans = (ans + add + mod) % mod; - dp[i] = (dp[i] + add) % mod; - } - return ans; - } -}; -``` - -### **Go** - ```go func distinctSubseqII(s string) int { const mod int = 1e9 + 7 @@ -226,45 +140,6 @@ func distinctSubseqII(s string) int { } ``` -```go -func distinctSubseqII(s string) int { - const mod int = 1e9 + 7 - dp := make([]int, 26) - ans := 0 - for _, c := range s { - c -= 'a' - add := ans - dp[c] + 1 - ans = (ans + add) % mod - dp[c] = (dp[c] + add) % mod - } - return (ans + mod) % mod -} -``` - -### **C** - -```c -int distinctSubseqII(char* s) { - int mod = 1e9 + 7; - int n = strlen(s); - int dp[26] = {0}; - for (int i = 0; i < n; i++) { - int sum = 0; - for (int j = 0; j < 26; j++) { - sum = (sum + dp[j]) % mod; - } - dp[s[i] - 'a'] = sum + 1; - } - int res = 0; - for (int i = 0; i < 26; i++) { - res = (res + dp[i]) % mod; - } - return res; -} -``` - -### **TypeScript** - ```ts function distinctSubseqII(s: string): number { const mod = 1e9 + 7; @@ -276,8 +151,6 @@ function distinctSubseqII(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn distinct_subseq_ii(s: String) -> i32 { @@ -303,10 +176,123 @@ impl Solution { } ``` -### **...** +```c +int distinctSubseqII(char* s) { + int mod = 1e9 + 7; + int n = strlen(s); + int dp[26] = {0}; + for (int i = 0; i < n; i++) { + int sum = 0; + for (int j = 0; j < 26; j++) { + sum = (sum + dp[j]) % mod; + } + dp[s[i] - 'a'] = sum + 1; + } + int res = 0; + for (int i = 0; i < 26; i++) { + res = (res + dp[i]) % mod; + } + return res; +} +``` + + + +### 方法二:优化的动态规划 + +在方法一的基础上,我们还可以维护当前 $dp$ 数组中所有元素的和 $ans$,这样我们每次更新 $dp[i]$ 时,只需要将 $dp[i]$ 加上 $ans-dp[i]+1$ 即可。 +时间复杂度 $O(n)$,空间复杂度 $O(C)$。 + +相似题目: + +- [1987. 不同的好子序列数目](/solution/1900-1999/1987.Number%20of%20Unique%20Good%20Subsequences/README.md) + + + +```python +class Solution: + def distinctSubseqII(self, s: str) -> int: + mod = 10**9 + 7 + dp = [0] * 26 + for c in s: + i = ord(c) - ord('a') + dp[i] = sum(dp) % mod + 1 + return sum(dp) % mod ``` +```java +class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int distinctSubseqII(String s) { + int[] dp = new int[26]; + int ans = 0; + for (int i = 0; i < s.length(); ++i) { + int j = s.charAt(i) - 'a'; + int add = (ans - dp[j] + 1) % MOD; + ans = (ans + add) % MOD; + dp[j] = (dp[j] + add) % MOD; + } + return (ans + MOD) % MOD; + } +} +``` + +```cpp +class Solution { +public: + const int mod = 1e9 + 7; + + int distinctSubseqII(string s) { + vector dp(26); + long ans = 0; + for (char& c : s) { + int i = c - 'a'; + long add = ans - dp[i] + 1; + ans = (ans + add + mod) % mod; + dp[i] = (dp[i] + add) % mod; + } + return ans; + } +}; +``` + +```go +func distinctSubseqII(s string) int { + const mod int = 1e9 + 7 + dp := make([]int, 26) + ans := 0 + for _, c := range s { + c -= 'a' + add := ans - dp[c] + 1 + ans = (ans + add) % mod + dp[c] = (dp[c] + add) % mod + } + return (ans + mod) % mod +} +``` + + + +### 方法三 + + + +```python +class Solution: + def distinctSubseqII(self, s: str) -> int: + mod = 10**9 + 7 + dp = [0] * 26 + ans = 0 + for c in s: + i = ord(c) - ord('a') + add = ans - dp[i] + 1 + ans = (ans + add) % mod + dp[i] += add + return ans ``` + + diff --git a/solution/0900-0999/0940.Distinct Subsequences II/README_EN.md b/solution/0900-0999/0940.Distinct Subsequences II/README_EN.md index 4cbe59a4a9924..0a11ad5b274d6 100644 --- a/solution/0900-0999/0940.Distinct Subsequences II/README_EN.md +++ b/solution/0900-0999/0940.Distinct Subsequences II/README_EN.md @@ -41,9 +41,9 @@ A subsequence of a string is a new string that is formed from t ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,33 +61,6 @@ class Solution: return sum(dp[-1]) % mod ``` -```python -class Solution: - def distinctSubseqII(self, s: str) -> int: - mod = 10**9 + 7 - dp = [0] * 26 - for c in s: - i = ord(c) - ord('a') - dp[i] = sum(dp) % mod + 1 - return sum(dp) % mod -``` - -```python -class Solution: - def distinctSubseqII(self, s: str) -> int: - mod = 10**9 + 7 - dp = [0] * 26 - ans = 0 - for c in s: - i = ord(c) - ord('a') - add = ans - dp[i] + 1 - ans = (ans + add) % mod - dp[i] += add - return ans -``` - -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -111,26 +84,6 @@ class Solution { } ``` -```java -class Solution { - private static final int MOD = (int) 1e9 + 7; - - public int distinctSubseqII(String s) { - int[] dp = new int[26]; - int ans = 0; - for (int i = 0; i < s.length(); ++i) { - int j = s.charAt(i) - 'a'; - int add = (ans - dp[j] + 1) % MOD; - ans = (ans + add) % MOD; - dp[j] = (dp[j] + add) % MOD; - } - return (ans + MOD) % MOD; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -147,27 +100,6 @@ public: }; ``` -```cpp -class Solution { -public: - const int mod = 1e9 + 7; - - int distinctSubseqII(string s) { - vector dp(26); - long ans = 0; - for (char& c : s) { - int i = c - 'a'; - long add = ans - dp[i] + 1; - ans = (ans + add + mod) % mod; - dp[i] = (dp[i] + add) % mod; - } - return ans; - } -}; -``` - -### **Go** - ```go func distinctSubseqII(s string) int { const mod int = 1e9 + 7 @@ -188,45 +120,6 @@ func distinctSubseqII(s string) int { } ``` -```go -func distinctSubseqII(s string) int { - const mod int = 1e9 + 7 - dp := make([]int, 26) - ans := 0 - for _, c := range s { - c -= 'a' - add := ans - dp[c] + 1 - ans = (ans + add) % mod - dp[c] = (dp[c] + add) % mod - } - return (ans + mod) % mod -} -``` - -### **C** - -```c -int distinctSubseqII(char* s) { - int mod = 1e9 + 7; - int n = strlen(s); - int dp[26] = {0}; - for (int i = 0; i < n; i++) { - int sum = 0; - for (int j = 0; j < 26; j++) { - sum = (sum + dp[j]) % mod; - } - dp[s[i] - 'a'] = sum + 1; - } - int res = 0; - for (int i = 0; i < 26; i++) { - res = (res + dp[i]) % mod; - } - return res; -} -``` - -### **TypeScript** - ```ts function distinctSubseqII(s: string): number { const mod = 1e9 + 7; @@ -238,8 +131,6 @@ function distinctSubseqII(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn distinct_subseq_ii(s: String) -> i32 { @@ -265,10 +156,115 @@ impl Solution { } ``` -### **...** +```c +int distinctSubseqII(char* s) { + int mod = 1e9 + 7; + int n = strlen(s); + int dp[26] = {0}; + for (int i = 0; i < n; i++) { + int sum = 0; + for (int j = 0; j < 26; j++) { + sum = (sum + dp[j]) % mod; + } + dp[s[i] - 'a'] = sum + 1; + } + int res = 0; + for (int i = 0; i < 26; i++) { + res = (res + dp[i]) % mod; + } + return res; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def distinctSubseqII(self, s: str) -> int: + mod = 10**9 + 7 + dp = [0] * 26 + for c in s: + i = ord(c) - ord('a') + dp[i] = sum(dp) % mod + 1 + return sum(dp) % mod +``` + +```java +class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int distinctSubseqII(String s) { + int[] dp = new int[26]; + int ans = 0; + for (int i = 0; i < s.length(); ++i) { + int j = s.charAt(i) - 'a'; + int add = (ans - dp[j] + 1) % MOD; + ans = (ans + add) % MOD; + dp[j] = (dp[j] + add) % MOD; + } + return (ans + MOD) % MOD; + } +} +``` + +```cpp +class Solution { +public: + const int mod = 1e9 + 7; + + int distinctSubseqII(string s) { + vector dp(26); + long ans = 0; + for (char& c : s) { + int i = c - 'a'; + long add = ans - dp[i] + 1; + ans = (ans + add + mod) % mod; + dp[i] = (dp[i] + add) % mod; + } + return ans; + } +}; +``` +```go +func distinctSubseqII(s string) int { + const mod int = 1e9 + 7 + dp := make([]int, 26) + ans := 0 + for _, c := range s { + c -= 'a' + add := ans - dp[c] + 1 + ans = (ans + add) % mod + dp[c] = (dp[c] + add) % mod + } + return (ans + mod) % mod +} ``` + + +### Solution 3 + + + +```python +class Solution: + def distinctSubseqII(self, s: str) -> int: + mod = 10**9 + 7 + dp = [0] * 26 + ans = 0 + for c in s: + i = ord(c) - ord('a') + add = ans - dp[i] + 1 + ans = (ans + add) % mod + dp[i] += add + return ans ``` + + diff --git a/solution/0900-0999/0941.Valid Mountain Array/README.md b/solution/0900-0999/0941.Valid Mountain Array/README.md index e34917b38d845..b8923c8b16800 100644 --- a/solution/0900-0999/0941.Valid Mountain Array/README.md +++ b/solution/0900-0999/0941.Valid Mountain Array/README.md @@ -57,14 +57,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def validMountainArray(self, arr: List[int]) -> bool: @@ -79,10 +75,6 @@ class Solution: return l == r ``` -### **Java** - - - ```java class Solution { @@ -103,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +109,6 @@ public: }; ``` -### **Go** - ```go func validMountainArray(arr []int) bool { n := len(arr) @@ -138,10 +126,6 @@ func validMountainArray(arr []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0941.Valid Mountain Array/README_EN.md b/solution/0900-0999/0941.Valid Mountain Array/README_EN.md index 89fa89f3e8451..715e637c5a623 100644 --- a/solution/0900-0999/0941.Valid Mountain Array/README_EN.md +++ b/solution/0900-0999/0941.Valid Mountain Array/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return l == r ``` -### **Java** - ```java class Solution { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +91,6 @@ public: }; ``` -### **Go** - ```go func validMountainArray(arr []int) bool { n := len(arr) @@ -114,10 +108,6 @@ func validMountainArray(arr []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0942.DI String Match/README.md b/solution/0900-0999/0942.DI String Match/README.md index b7933d844bef5..2d8a9260e0d05 100644 --- a/solution/0900-0999/0942.DI String Match/README.md +++ b/solution/0900-0999/0942.DI String Match/README.md @@ -48,16 +48,10 @@ ## 解法 - - -类似贪心思想,如果当前字母是 `I`,我们只需要选择当前可选的最小数字,就能保证后面的数字无论怎么排列,当前数字和下一个数字一定是递增关系。`D` 同理,选择当前可选的最大数字即可 +### 方法一 -### **Python3** - - - ```python class Solution: def diStringMatch(self, s: str) -> List[int]: @@ -75,10 +69,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] diStringMatch(String s) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func diStringMatch(s string) []int { n := len(s) @@ -141,8 +127,6 @@ func diStringMatch(s string) []int { } ``` -### **TypeScript** - ```ts function diStringMatch(s: string): number[] { const n = s.length; @@ -161,8 +145,6 @@ function diStringMatch(s: string): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn di_string_match(s: String) -> Vec { @@ -187,10 +169,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0942.DI String Match/README_EN.md b/solution/0900-0999/0942.DI String Match/README_EN.md index 46c01611ee730..9445e59813fee 100644 --- a/solution/0900-0999/0942.DI String Match/README_EN.md +++ b/solution/0900-0999/0942.DI String Match/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] diStringMatch(String s) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +94,6 @@ public: }; ``` -### **Go** - ```go func diStringMatch(s string) []int { n := len(s) @@ -119,8 +113,6 @@ func diStringMatch(s string) []int { } ``` -### **TypeScript** - ```ts function diStringMatch(s: string): number[] { const n = s.length; @@ -139,8 +131,6 @@ function diStringMatch(s: string): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn di_string_match(s: String) -> Vec { @@ -165,10 +155,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0943.Find the Shortest Superstring/README.md b/solution/0900-0999/0943.Find the Shortest Superstring/README.md index 7d65cf371ce2c..3dc301da4b8be 100644 --- a/solution/0900-0999/0943.Find the Shortest Superstring/README.md +++ b/solution/0900-0999/0943.Find the Shortest Superstring/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:状态压缩 + 动态规划** +### 方法一:状态压缩 + 动态规划 由于题目中字符串数组 `words` 的长度不超过 12,因此可以使用状态压缩的方法来表示字符串数组中的每个字符串是否被选中。 @@ -58,10 +56,6 @@ $$ -### **Python3** - - - ```python class Solution: def shortestSuperstring(self, words: List[str]) -> str: @@ -102,10 +96,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String shortestSuperstring(String[] words) { @@ -175,8 +165,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -245,8 +233,6 @@ public: }; ``` -### **Go** - ```go func shortestSuperstring(words []string) string { n := len(words) @@ -316,10 +302,6 @@ func shortestSuperstring(words []string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0943.Find the Shortest Superstring/README_EN.md b/solution/0900-0999/0943.Find the Shortest Superstring/README_EN.md index 4e4214669f076..8858e44d520a6 100644 --- a/solution/0900-0999/0943.Find the Shortest Superstring/README_EN.md +++ b/solution/0900-0999/0943.Find the Shortest Superstring/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String shortestSuperstring(String[] words) { @@ -151,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -221,8 +217,6 @@ public: }; ``` -### **Go** - ```go func shortestSuperstring(words []string) string { n := len(words) @@ -292,10 +286,6 @@ func shortestSuperstring(words []string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0944.Delete Columns to Make Sorted/README.md b/solution/0900-0999/0944.Delete Columns to Make Sorted/README.md index 745456190ad7b..99c673801da8e 100644 --- a/solution/0900-0999/0944.Delete Columns to Make Sorted/README.md +++ b/solution/0900-0999/0944.Delete Columns to Make Sorted/README.md @@ -69,14 +69,10 @@ cae ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minDeletionSize(self, strs: List[str]) -> int: @@ -90,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minDeletionSize(String[] strs) { @@ -112,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,7 +124,21 @@ public: }; ``` -### **Rust** +```go +func minDeletionSize(strs []string) int { + m, n := len(strs[0]), len(strs) + ans := 0 + for j := 0; j < m; j++ { + for i := 1; i < n; i++ { + if strs[i][j] < strs[i-1][j] { + ans++ + break + } + } + } + return ans +} +``` ```rust impl Solution { @@ -155,28 +159,6 @@ impl Solution { } ``` -### **Go** - -```go -func minDeletionSize(strs []string) int { - m, n := len(strs[0]), len(strs) - ans := 0 - for j := 0; j < m; j++ { - for i := 1; i < n; i++ { - if strs[i][j] < strs[i-1][j] { - ans++ - break - } - } - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0944.Delete Columns to Make Sorted/README_EN.md b/solution/0900-0999/0944.Delete Columns to Make Sorted/README_EN.md index 8781cdd682509..530b13bb05515 100644 --- a/solution/0900-0999/0944.Delete Columns to Make Sorted/README_EN.md +++ b/solution/0900-0999/0944.Delete Columns to Make Sorted/README_EN.md @@ -70,9 +70,9 @@ All 3 columns are not sorted, so you will delete all 3. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -87,8 +87,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minDeletionSize(String[] strs) { @@ -107,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,7 +125,21 @@ public: }; ``` -### **Rust** +```go +func minDeletionSize(strs []string) int { + m, n := len(strs[0]), len(strs) + ans := 0 + for j := 0; j < m; j++ { + for i := 1; i < n; i++ { + if strs[i][j] < strs[i-1][j] { + ans++ + break + } + } + } + return ans +} +``` ```rust impl Solution { @@ -150,28 +160,6 @@ impl Solution { } ``` -### **Go** - -```go -func minDeletionSize(strs []string) int { - m, n := len(strs[0]), len(strs) - ans := 0 - for j := 0; j < m; j++ { - for i := 1; i < n; i++ { - if strs[i][j] < strs[i-1][j] { - ans++ - break - } - } - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0945.Minimum Increment to Make Array Unique/README.md b/solution/0900-0999/0945.Minimum Increment to Make Array Unique/README.md index 558e447875617..4d4024b6a0b79 100644 --- a/solution/0900-0999/0945.Minimum Increment to Make Array Unique/README.md +++ b/solution/0900-0999/0945.Minimum Increment to Make Array Unique/README.md @@ -42,16 +42,10 @@ ## 解法 - - -**方法一:排序 + 贪心** +### 方法一:排序 + 贪心 -### **Python3** - - - ```python class Solution: def minIncrementForUnique(self, nums: List[int]) -> int: @@ -65,10 +59,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minIncrementForUnique(int[] nums) { @@ -86,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +94,6 @@ public: }; ``` -### **Go** - ```go func minIncrementForUnique(nums []int) int { sort.Ints(nums) @@ -123,10 +109,6 @@ func minIncrementForUnique(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0945.Minimum Increment to Make Array Unique/README_EN.md b/solution/0900-0999/0945.Minimum Increment to Make Array Unique/README_EN.md index 1cd81a2316d09..577c0ffb9f3d1 100644 --- a/solution/0900-0999/0945.Minimum Increment to Make Array Unique/README_EN.md +++ b/solution/0900-0999/0945.Minimum Increment to Make Array Unique/README_EN.md @@ -38,9 +38,9 @@ It can be shown with 5 or less moves that it is impossible for the array to have ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minIncrementForUnique(int[] nums) { @@ -74,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +90,6 @@ public: }; ``` -### **Go** - ```go func minIncrementForUnique(nums []int) int { sort.Ints(nums) @@ -111,10 +105,6 @@ func minIncrementForUnique(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0946.Validate Stack Sequences/README.md b/solution/0900-0999/0946.Validate Stack Sequences/README.md index dc8f75bc91a43..2d261aacdb3fb 100644 --- a/solution/0900-0999/0946.Validate Stack Sequences/README.md +++ b/solution/0900-0999/0946.Validate Stack Sequences/README.md @@ -42,9 +42,7 @@ push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 ## 解法 - - -**方法一:栈模拟** +### 方法一:栈模拟 遍历 `pushed` 序列,将每个数 `v` 依次压入栈中,压入后检查这个数是不是 `popped` 序列中下一个要弹出的值,如果是就循环把栈顶元素弹出。 @@ -54,10 +52,6 @@ push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 -### **Python3** - - - ```python class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: @@ -70,10 +64,6 @@ class Solution: return j == len(pushed) ``` -### **Java** - - - ```java class Solution { public boolean validateStackSequences(int[] pushed, int[] popped) { @@ -91,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +99,6 @@ public: }; ``` -### **Go** - ```go func validateStackSequences(pushed []int, popped []int) bool { stk := []int{} @@ -128,8 +114,6 @@ func validateStackSequences(pushed []int, popped []int) bool { } ``` -### **TypeScript** - ```ts function validateStackSequences(pushed: number[], popped: number[]): boolean { const stk = []; @@ -145,28 +129,6 @@ function validateStackSequences(pushed: number[], popped: number[]): boolean { } ``` -### **C#** - -```cs -public class Solution { - public bool ValidateStackSequences(int[] pushed, int[] popped) { - Stack stk = new Stack(); - int j = 0; - foreach (int x in pushed) - { - stk.Push(x); - while (stk.Count != 0 && stk.Peek() == popped[j]) { - stk.Pop(); - ++j; - } - } - return stk.Count == 0; - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn validate_stack_sequences(pushed: Vec, popped: Vec) -> bool { @@ -184,8 +146,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[]} pushed @@ -206,10 +166,24 @@ var validateStackSequences = function (pushed, popped) { }; ``` -### **...** - -``` - +```cs +public class Solution { + public bool ValidateStackSequences(int[] pushed, int[] popped) { + Stack stk = new Stack(); + int j = 0; + foreach (int x in pushed) + { + stk.Push(x); + while (stk.Count != 0 && stk.Peek() == popped[j]) { + stk.Pop(); + ++j; + } + } + return stk.Count == 0; + } +} ``` + + diff --git a/solution/0900-0999/0946.Validate Stack Sequences/README_EN.md b/solution/0900-0999/0946.Validate Stack Sequences/README_EN.md index 0d2ae83e2864d..982e114f0f553 100644 --- a/solution/0900-0999/0946.Validate Stack Sequences/README_EN.md +++ b/solution/0900-0999/0946.Validate Stack Sequences/README_EN.md @@ -40,9 +40,9 @@ pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return j == len(pushed) ``` -### **Java** - ```java class Solution { public boolean validateStackSequences(int[] pushed, int[] popped) { @@ -75,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +91,6 @@ public: }; ``` -### **Go** - ```go func validateStackSequences(pushed []int, popped []int) bool { stk := []int{} @@ -112,8 +106,6 @@ func validateStackSequences(pushed []int, popped []int) bool { } ``` -### **TypeScript** - ```ts function validateStackSequences(pushed: number[], popped: number[]): boolean { const stk = []; @@ -129,28 +121,6 @@ function validateStackSequences(pushed: number[], popped: number[]): boolean { } ``` -### **C#** - -```cs -public class Solution { - public bool ValidateStackSequences(int[] pushed, int[] popped) { - Stack stk = new Stack(); - int j = 0; - foreach (int x in pushed) - { - stk.Push(x); - while (stk.Count != 0 && stk.Peek() == popped[j]) { - stk.Pop(); - ++j; - } - } - return stk.Count == 0; - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn validate_stack_sequences(pushed: Vec, popped: Vec) -> bool { @@ -168,8 +138,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[]} pushed @@ -190,10 +158,24 @@ var validateStackSequences = function (pushed, popped) { }; ``` -### **...** - -``` - +```cs +public class Solution { + public bool ValidateStackSequences(int[] pushed, int[] popped) { + Stack stk = new Stack(); + int j = 0; + foreach (int x in pushed) + { + stk.Push(x); + while (stk.Count != 0 && stk.Peek() == popped[j]) { + stk.Pop(); + ++j; + } + } + return stk.Count == 0; + } +} ``` + + diff --git a/solution/0900-0999/0947.Most Stones Removed with Same Row or Column/README.md b/solution/0900-0999/0947.Most Stones Removed with Same Row or Column/README.md index ca375533598d4..7e38756670d8a 100644 --- a/solution/0900-0999/0947.Most Stones Removed with Same Row or Column/README.md +++ b/solution/0900-0999/0947.Most Stones Removed with Same Row or Column/README.md @@ -57,81 +57,10 @@ ## 解法 - - -并查集。对于本题,`可以移除的石头数量 = 石头总数 - 连通分量个数`。遍历 `stones` 数组,将每个 `stone` 的横、纵坐标进行合并。需要注意的是,横、纵坐标数值可能相同,我们需要处理成不同的值,结合横、纵坐标的范围,我们只需要在其中一个坐标值加上 10010 即可。 - -以下是并查集的几个常用模板。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` +### 方法一 -### **Python3** - - - ```python class Solution: def removeStones(self, stones: List[List[int]]) -> int: @@ -149,10 +78,6 @@ class Solution: return len(stones) - len(s) ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -182,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -206,8 +129,6 @@ public: }; ``` -### **Go** - ```go func removeStones(stones [][]int) int { n := 10010 @@ -233,10 +154,6 @@ func removeStones(stones [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0947.Most Stones Removed with Same Row or Column/README_EN.md b/solution/0900-0999/0947.Most Stones Removed with Same Row or Column/README_EN.md index a840c9f34cdc2..d4488f6664e56 100644 --- a/solution/0900-0999/0947.Most Stones Removed with Same Row or Column/README_EN.md +++ b/solution/0900-0999/0947.Most Stones Removed with Same Row or Column/README_EN.md @@ -56,9 +56,9 @@ Stones [0,0] and [1,1] cannot be removed since they do not share a row/column wi ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return len(stones) - len(s) ``` -### **Java** - ```java class Solution { private int[] p; @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +128,6 @@ public: }; ``` -### **Go** - ```go func removeStones(stones [][]int) int { n := 10010 @@ -159,10 +153,6 @@ func removeStones(stones [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0948.Bag of Tokens/README.md b/solution/0900-0999/0948.Bag of Tokens/README.md index d20cff0256ab8..d3cdcefda0990 100644 --- a/solution/0900-0999/0948.Bag of Tokens/README.md +++ b/solution/0900-0999/0948.Bag of Tokens/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:贪心 + 排序 + 双指针** +### 方法一:贪心 + 排序 + 双指针 令牌的使用方法有两种,一种是消耗能量得到分数,一种是消耗分数得到能量。显然,我们应该消耗尽可能少的能量来得到尽可能多的分数。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def bagOfTokensScore(self, tokens: List[int], power: int) -> int: @@ -96,10 +90,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int bagOfTokensScore(int[] tokens, int power) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +136,6 @@ public: }; ``` -### **Go** - ```go func bagOfTokensScore(tokens []int, power int) int { sort.Ints(tokens) @@ -171,10 +157,6 @@ func bagOfTokensScore(tokens []int, power int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0948.Bag of Tokens/README_EN.md b/solution/0900-0999/0948.Bag of Tokens/README_EN.md index 3a6b5dcbd5183..3fc41a99f6d80 100644 --- a/solution/0900-0999/0948.Bag of Tokens/README_EN.md +++ b/solution/0900-0999/0948.Bag of Tokens/README_EN.md @@ -57,9 +57,9 @@ There is no need to play the 1st token since you cannot play it face ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int bagOfTokensScore(int[] tokens, int power) { @@ -105,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +126,6 @@ public: }; ``` -### **Go** - ```go func bagOfTokensScore(tokens []int, power int) int { sort.Ints(tokens) @@ -153,10 +147,6 @@ func bagOfTokensScore(tokens []int, power int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0949.Largest Time for Given Digits/README.md b/solution/0900-0999/0949.Largest Time for Given Digits/README.md index 6173b293096a0..7f6a8330082f5 100644 --- a/solution/0900-0999/0949.Largest Time for Given Digits/README.md +++ b/solution/0900-0999/0949.Largest Time for Given Digits/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 我们可以枚举所有的 4 个数字的排列,然后判断每个排列是否满足题目要求,如果满足则更新答案。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def largestTimeFromDigits(self, arr: List[int]) -> str: @@ -87,25 +81,6 @@ class Solution: return '' ``` -```python -class Solution: - def largestTimeFromDigits(self, arr: List[int]) -> str: - ans = -1 - for i in range(4): - for j in range(4): - for k in range(4): - if i != j and i != k and j != k: - h = arr[i] * 10 + arr[j] - m = arr[k] * 10 + arr[6 - i - j - k] - if h < 24 and m < 60: - ans = max(ans, h * 60 + m) - return '' if ans < 0 else f'{ans // 60:02}:{ans % 60:02}' -``` - -### **Java** - - - ```java class Solution { public String largestTimeFromDigits(int[] arr) { @@ -128,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +128,6 @@ public: }; ``` -### **Go** - ```go func largestTimeFromDigits(arr []int) string { ans := -1 @@ -180,10 +151,27 @@ func largestTimeFromDigits(arr []int) string { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def largestTimeFromDigits(self, arr: List[int]) -> str: + ans = -1 + for i in range(4): + for j in range(4): + for k in range(4): + if i != j and i != k and j != k: + h = arr[i] * 10 + arr[j] + m = arr[k] * 10 + arr[6 - i - j - k] + if h < 24 and m < 60: + ans = max(ans, h * 60 + m) + return '' if ans < 0 else f'{ans // 60:02}:{ans % 60:02}' ``` + + diff --git a/solution/0900-0999/0949.Largest Time for Given Digits/README_EN.md b/solution/0900-0999/0949.Largest Time for Given Digits/README_EN.md index cadea76dfaf96..e06d804a43d66 100644 --- a/solution/0900-0999/0949.Largest Time for Given Digits/README_EN.md +++ b/solution/0900-0999/0949.Largest Time for Given Digits/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,23 +59,6 @@ class Solution: return '' ``` -```python -class Solution: - def largestTimeFromDigits(self, arr: List[int]) -> str: - ans = -1 - for i in range(4): - for j in range(4): - for k in range(4): - if i != j and i != k and j != k: - h = arr[i] * 10 + arr[j] - m = arr[k] * 10 + arr[6 - i - j - k] - if h < 24 and m < 60: - ans = max(ans, h * 60 + m) - return '' if ans < 0 else f'{ans // 60:02}:{ans % 60:02}' -``` - -### **Java** - ```java class Solution { public String largestTimeFromDigits(int[] arr) { @@ -98,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +106,6 @@ public: }; ``` -### **Go** - ```go func largestTimeFromDigits(arr []int) string { ans := -1 @@ -150,10 +129,27 @@ func largestTimeFromDigits(arr []int) string { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def largestTimeFromDigits(self, arr: List[int]) -> str: + ans = -1 + for i in range(4): + for j in range(4): + for k in range(4): + if i != j and i != k and j != k: + h = arr[i] * 10 + arr[j] + m = arr[k] * 10 + arr[6 - i - j - k] + if h < 24 and m < 60: + ans = max(ans, h * 60 + m) + return '' if ans < 0 else f'{ans // 60:02}:{ans % 60:02}' ``` + + diff --git a/solution/0900-0999/0950.Reveal Cards In Increasing Order/README.md b/solution/0900-0999/0950.Reveal Cards In Increasing Order/README.md index e402c68eba102..76247679bff37 100644 --- a/solution/0900-0999/0950.Reveal Cards In Increasing Order/README.md +++ b/solution/0900-0999/0950.Reveal Cards In Increasing Order/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:队列模拟** +### 方法一:队列模拟 根据题目描述,我们知道,数组 `deck` 逆序排列后的序列就是最终的结果。我们可以从最终结果入手,逆向推导出卡片顺序。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def deckRevealedIncreasing(self, deck: List[int]) -> List[int]: @@ -82,10 +76,6 @@ class Solution: return list(q) ``` -### **Java** - - - ```java class Solution { public int[] deckRevealedIncreasing(int[] deck) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func deckRevealedIncreasing(deck []int) []int { sort.Sort(sort.Reverse(sort.IntSlice(deck))) @@ -143,10 +129,6 @@ func deckRevealedIncreasing(deck []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0950.Reveal Cards In Increasing Order/README_EN.md b/solution/0900-0999/0950.Reveal Cards In Increasing Order/README_EN.md index f00001afc0ff1..f44d80e82e890 100644 --- a/solution/0900-0999/0950.Reveal Cards In Increasing Order/README_EN.md +++ b/solution/0900-0999/0950.Reveal Cards In Increasing Order/README_EN.md @@ -57,9 +57,9 @@ Since all the cards revealed are in increasing order, the answer is correct. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return list(q) ``` -### **Java** - ```java class Solution { public int[] deckRevealedIncreasing(int[] deck) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +111,6 @@ public: }; ``` -### **Go** - ```go func deckRevealedIncreasing(deck []int) []int { sort.Sort(sort.Reverse(sort.IntSlice(deck))) @@ -131,10 +125,6 @@ func deckRevealedIncreasing(deck []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0951.Flip Equivalent Binary Trees/README.md b/solution/0900-0999/0951.Flip Equivalent Binary Trees/README.md index 8453b952f7903..464a4254ea763 100644 --- a/solution/0900-0999/0951.Flip Equivalent Binary Trees/README.md +++ b/solution/0900-0999/0951.Flip Equivalent Binary Trees/README.md @@ -49,16 +49,10 @@ ## 解法 -DFS。 - - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -80,10 +74,6 @@ class Solution: return dfs(root1, root2) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -172,10 +158,6 @@ func flipEquiv(root1 *TreeNode, root2 *TreeNode) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0951.Flip Equivalent Binary Trees/README_EN.md b/solution/0900-0999/0951.Flip Equivalent Binary Trees/README_EN.md index f5213937905fe..5d91d3c2dc0ca 100644 --- a/solution/0900-0999/0951.Flip Equivalent Binary Trees/README_EN.md +++ b/solution/0900-0999/0951.Flip Equivalent Binary Trees/README_EN.md @@ -43,12 +43,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -70,8 +68,6 @@ class Solution: return dfs(root1, root2) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -106,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -134,8 +128,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -160,10 +152,6 @@ func flipEquiv(root1 *TreeNode, root2 *TreeNode) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0952.Largest Component Size by Common Factor/README.md b/solution/0900-0999/0952.Largest Component Size by Common Factor/README.md index 15a31c1bf552b..4ccd0c54abdfd 100644 --- a/solution/0900-0999/0952.Largest Component Size by Common Factor/README.md +++ b/solution/0900-0999/0952.Largest Component Size by Common Factor/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:数学 + 并查集** +### 方法一:数学 + 并查集 利用“试除法”,对 $nums$ 中的每个数 $v$ 分解因数,然后将每个因数 $i$ 与 $v$ 合并,$v / i$ 与 $v$ 合并。此过程用并查集来维护连通分量。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class UnionFind: def __init__(self, n): @@ -102,10 +96,6 @@ class Solution: return max(Counter(uf.find(v) for v in nums).values()) ``` -### **Java** - - - ```java class UnionFind { int[] p; @@ -161,8 +151,6 @@ class Solution { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -213,8 +201,6 @@ public: }; ``` -### **Go** - ```go func largestComponentSize(nums []int) int { m := slices.Max(nums) @@ -254,10 +240,6 @@ func largestComponentSize(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0952.Largest Component Size by Common Factor/README_EN.md b/solution/0900-0999/0952.Largest Component Size by Common Factor/README_EN.md index 2d046c0271df0..3a3df906321f0 100644 --- a/solution/0900-0999/0952.Largest Component Size by Common Factor/README_EN.md +++ b/solution/0900-0999/0952.Largest Component Size by Common Factor/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class UnionFind: @@ -79,8 +79,6 @@ class Solution: return max(Counter(uf.find(v) for v in nums).values()) ``` -### **Java** - ```java class UnionFind { int[] p; @@ -136,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -188,8 +184,6 @@ public: }; ``` -### **Go** - ```go func largestComponentSize(nums []int) int { m := slices.Max(nums) @@ -229,10 +223,6 @@ func largestComponentSize(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0953.Verifying an Alien Dictionary/README.md b/solution/0900-0999/0953.Verifying an Alien Dictionary/README.md index 34394252400c9..941a80cc7dbe8 100644 --- a/solution/0900-0999/0953.Verifying an Alien Dictionary/README.md +++ b/solution/0900-0999/0953.Verifying an Alien Dictionary/README.md @@ -47,16 +47,10 @@ ## 解法 - - -用数组或哈希表存放字母顺序。依次遍历单词列表,检测相邻两单词是否满足字典序。 +### 方法一 -### **Python3** - - - ```python class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: @@ -76,10 +70,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean isAlienSorted(String[] words, String order) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +121,6 @@ public: }; ``` -### **Go** - ```go func isAlienSorted(words []string, order string) bool { m := make([]int, 26) @@ -165,8 +151,6 @@ func isAlienSorted(words []string, order string) bool { } ``` -### **TypeScript** - ```ts function isAlienSorted(words: string[], order: string): boolean { const map = new Map(); @@ -196,8 +180,6 @@ function isAlienSorted(words: string[], order: string): boolean { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -233,8 +215,6 @@ impl Solution { } ``` -### **C** - ```c #define min(a, b) (((a) < (b)) ? (a) : (b)) @@ -267,10 +247,6 @@ bool isAlienSorted(char** words, int wordsSize, char* order) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0953.Verifying an Alien Dictionary/README_EN.md b/solution/0900-0999/0953.Verifying an Alien Dictionary/README_EN.md index c23bb15360bc7..d2f448fe8abf4 100644 --- a/solution/0900-0999/0953.Verifying an Alien Dictionary/README_EN.md +++ b/solution/0900-0999/0953.Verifying an Alien Dictionary/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean isAlienSorted(String[] words, String order) { @@ -99,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func isAlienSorted(words []string, order string) bool { m := make([]int, 26) @@ -155,8 +149,6 @@ func isAlienSorted(words []string, order string) bool { } ``` -### **TypeScript** - ```ts function isAlienSorted(words: string[], order: string): boolean { const map = new Map(); @@ -186,8 +178,6 @@ function isAlienSorted(words: string[], order: string): boolean { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -223,8 +213,6 @@ impl Solution { } ``` -### **C** - ```c #define min(a, b) (((a) < (b)) ? (a) : (b)) @@ -257,10 +245,6 @@ bool isAlienSorted(char** words, int wordsSize, char* order) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0954.Array of Doubled Pairs/README.md b/solution/0900-0999/0954.Array of Doubled Pairs/README.md index 5fc42c20f0dd4..e6b77a294292e 100644 --- a/solution/0900-0999/0954.Array of Doubled Pairs/README.md +++ b/solution/0900-0999/0954.Array of Doubled Pairs/README.md @@ -44,16 +44,10 @@ ## 解法 - - -**方法一:哈希表 + 排序** +### 方法一:哈希表 + 排序 -### **Python3** - - - ```python class Solution: def canReorderDoubled(self, arr: List[int]) -> bool: @@ -67,10 +61,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean canReorderDoubled(int[] arr) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func canReorderDoubled(arr []int) bool { freq := make(map[int]int) @@ -150,10 +136,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0954.Array of Doubled Pairs/README_EN.md b/solution/0900-0999/0954.Array of Doubled Pairs/README_EN.md index bd19368194c1c..dccf36a135d51 100644 --- a/solution/0900-0999/0954.Array of Doubled Pairs/README_EN.md +++ b/solution/0900-0999/0954.Array of Doubled Pairs/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean canReorderDoubled(int[] arr) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +99,6 @@ public: }; ``` -### **Go** - ```go func canReorderDoubled(arr []int) bool { freq := make(map[int]int) @@ -138,10 +132,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0955.Delete Columns to Make Sorted II/README.md b/solution/0900-0999/0955.Delete Columns to Make Sorted II/README.md index 7db2fb2c22bc5..5769b9c8db342 100644 --- a/solution/0900-0999/0955.Delete Columns to Make Sorted II/README.md +++ b/solution/0900-0999/0955.Delete Columns to Make Sorted II/README.md @@ -63,30 +63,39 @@ strs 的列已经是按字典序排列了,所以我们不需要删除任何东 ## 解法 - +### 方法一 -### **Python3** - - - -```python - -``` - -### **Java** - - - ```java - -``` - -### **...** - -``` - +class Solution { + public int minDeletionSize(String[] A) { + if (A == null || A.length <= 1) { + return 0; + } + int len = A.length, wordLen = A[0].length(), res = 0; + boolean[] cut = new boolean[len]; + search: + for (int j = 0; j < wordLen; j++) { + // 判断第 j 列是否应当保留 + for (int i = 0; i < len - 1; i++) { + if (!cut[i] && A[i].charAt(j) > A[i + 1].charAt(j)) { + res += 1; + continue search; + } + } + // 更新 cut 的信息 + for (int i = 0; i < len - 1; i++) { + if (A[i].charAt(j) < A[i + 1].charAt(j)) { + cut[i] = true; + } + } + } + return res; + } +} ``` + + diff --git a/solution/0900-0999/0955.Delete Columns to Make Sorted II/README_EN.md b/solution/0900-0999/0955.Delete Columns to Make Sorted II/README_EN.md index bd1b8fd11e826..8bd35e892b5b1 100644 --- a/solution/0900-0999/0955.Delete Columns to Make Sorted II/README_EN.md +++ b/solution/0900-0999/0955.Delete Columns to Make Sorted II/README_EN.md @@ -55,24 +55,39 @@ i.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...) ## Solutions - - -### **Python3** +### Solution 1 -```python - -``` - -### **Java** + ```java - -``` - -### **...** - -``` - +class Solution { + public int minDeletionSize(String[] A) { + if (A == null || A.length <= 1) { + return 0; + } + int len = A.length, wordLen = A[0].length(), res = 0; + boolean[] cut = new boolean[len]; + search: + for (int j = 0; j < wordLen; j++) { + // 判断第 j 列是否应当保留 + for (int i = 0; i < len - 1; i++) { + if (!cut[i] && A[i].charAt(j) > A[i + 1].charAt(j)) { + res += 1; + continue search; + } + } + // 更新 cut 的信息 + for (int i = 0; i < len - 1; i++) { + if (A[i].charAt(j) < A[i + 1].charAt(j)) { + cut[i] = true; + } + } + } + return res; + } +} ``` + + diff --git a/solution/0900-0999/0956.Tallest Billboard/README.md b/solution/0900-0999/0956.Tallest Billboard/README.md index 1d6b158ec35b5..55b735d2b5ad7 100644 --- a/solution/0900-0999/0956.Tallest Billboard/README.md +++ b/solution/0900-0999/0956.Tallest Billboard/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j)$,表示从第 $i$ 根钢筋开始,且当前高度差为 $j$ 时,两边的最大共同高度。那么答案就是 $dfs(0, 0)$。 @@ -70,36 +68,8 @@ 时间复杂度 $O(n \times S)$,空间复杂度 $O(n \times S)$。其中 $n$ 和 $S$ 分别为 $rods$ 的长度和 $rods$ 中所有元素的和。 -**方法二:动态规划** - -我们定义 $f[i][j]$ 表示前 $i$ 根钢筋,两边高度差为 $j$ 时的最大共同高度。初始时 $f[0][0]=0$,其余 $f[i][j]=-\infty$。我们求出所有 $rods[i]$ 的和,记为 $s$,那么 $j$ 的取值范围为 $[0,..s]$。 - -对于第 $i$ 根钢筋,我们可以不选择它,此时 $f[i][j]=f[i-1][j]$;也可以选择它,此时有三种情况: - -1. 放置在原本高度较高的一边,即满足 $j \geq rods[i-1]$,此时 $f[i][j] = max(f[i][j], f[i-1][j-rods[i-1]])$; -1. 放置在原本高度较低的一遍,如果满足 $j + rods[i-1] \leq s$,此时 $f[i][j] = max(f[i][j], f[i-1][j+rods[i-1]] + rods[i-1])$;如果满足 $j \lt rods[i-1]$,此时 $f[i][j] = max(f[i][j], f[i-1][rods[i-1]-j] + rods[i-1]-j)$。 - -综上,我们可以得到状态转移方程: - -$$ -\begin{aligned} -f[i][j] &= f[i-1][j] \\ -f[i][j] &= max(f[i][j], f[i-1][j-rods[i-1]]) & \text{if } j \geq rods[i-1] \\ -f[i][j] &= max(f[i][j], f[i-1][j+rods[i-1]] + rods[i-1]) & \text{if } j + rods[i-1] \leq s \\ -f[i][j] &= max(f[i][j], f[i-1][rods[i-1]-j] + rods[i-1]-j) & \text{if } j \lt rods[i-1] -\end{aligned} -$$ - -最终答案即为 $f[n][0]$。 - -时间复杂度 $O(n \times S)$,空间复杂度 $O(n \times S)$。其中 $n$ 和 $S$ 分别为 $rods$ 的长度和 $rods$ 中所有元素的和。 - -### **Python3** - - - ```python class Solution: def tallestBillboard(self, rods: List[int]) -> int: @@ -114,31 +84,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def tallestBillboard(self, rods: List[int]) -> int: - n = len(rods) - s = sum(rods) - f = [[-inf] * (s + 1) for _ in range(n + 1)] - f[0][0] = 0 - t = 0 - for i, x in enumerate(rods, 1): - t += x - for j in range(t + 1): - f[i][j] = f[i - 1][j] - if j >= x: - f[i][j] = max(f[i][j], f[i - 1][j - x]) - if j + x <= t: - f[i][j] = max(f[i][j], f[i - 1][j + x] + x) - if j < x: - f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j) - return f[n][0] -``` - -### **Java** - - - ```java class Solution { private Integer[][] f; @@ -170,42 +115,6 @@ class Solution { } ``` -```java -class Solution { - public int tallestBillboard(int[] rods) { - int n = rods.length; - int s = 0; - for (int x : rods) { - s += x; - } - int[][] f = new int[n + 1][s + 1]; - for (var e : f) { - Arrays.fill(e, -(1 << 30)); - } - f[0][0] = 0; - for (int i = 1, t = 0; i <= n; ++i) { - int x = rods[i - 1]; - t += x; - for (int j = 0; j <= t; ++j) { - f[i][j] = f[i - 1][j]; - if (j >= x) { - f[i][j] = Math.max(f[i][j], f[i - 1][j - x]); - } - if (j + x <= t) { - f[i][j] = Math.max(f[i][j], f[i - 1][j + x] + x); - } - if (j < x) { - f[i][j] = Math.max(f[i][j], f[i - 1][x - j] + x - j); - } - } - } - return f[n][0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -230,38 +139,6 @@ public: }; ``` -```cpp -class Solution { -public: - int tallestBillboard(vector& rods) { - int n = rods.size(); - int s = accumulate(rods.begin(), rods.end(), 0); - int f[n + 1][s + 1]; - memset(f, -0x3f, sizeof(f)); - f[0][0] = 0; - for (int i = 1, t = 0; i <= n; ++i) { - int x = rods[i - 1]; - t += x; - for (int j = 0; j <= t; ++j) { - f[i][j] = f[i - 1][j]; - if (j >= x) { - f[i][j] = max(f[i][j], f[i - 1][j - x]); - } - if (j + x <= t) { - f[i][j] = max(f[i][j], f[i - 1][j + x] + x); - } - if (j < x) { - f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j); - } - } - } - return f[n][0]; - } -}; -``` - -### **Go** - ```go func tallestBillboard(rods []int) int { s := 0 @@ -303,6 +180,139 @@ func abs(x int) int { } ``` +```ts +function tallestBillboard(rods: number[]): number { + const s = rods.reduce((a, b) => a + b, 0); + const n = rods.length; + const f = new Array(n).fill(0).map(() => new Array(s + 1).fill(-1)); + const dfs = (i: number, j: number): number => { + if (i >= n) { + return j === 0 ? 0 : -(1 << 30); + } + if (f[i][j] !== -1) { + return f[i][j]; + } + let ans = Math.max(dfs(i + 1, j), dfs(i + 1, j + rods[i])); + ans = Math.max(ans, dfs(i + 1, Math.abs(j - rods[i])) + Math.min(j, rods[i])); + return (f[i][j] = ans); + }; + return dfs(0, 0); +} +``` + + + +### 方法二:动态规划 + +我们定义 $f[i][j]$ 表示前 $i$ 根钢筋,两边高度差为 $j$ 时的最大共同高度。初始时 $f[0][0]=0$,其余 $f[i][j]=-\infty$。我们求出所有 $rods[i]$ 的和,记为 $s$,那么 $j$ 的取值范围为 $[0,..s]$。 + +对于第 $i$ 根钢筋,我们可以不选择它,此时 $f[i][j]=f[i-1][j]$;也可以选择它,此时有三种情况: + +1. 放置在原本高度较高的一边,即满足 $j \geq rods[i-1]$,此时 $f[i][j] = max(f[i][j], f[i-1][j-rods[i-1]])$; +1. 放置在原本高度较低的一遍,如果满足 $j + rods[i-1] \leq s$,此时 $f[i][j] = max(f[i][j], f[i-1][j+rods[i-1]] + rods[i-1])$;如果满足 $j \lt rods[i-1]$,此时 $f[i][j] = max(f[i][j], f[i-1][rods[i-1]-j] + rods[i-1]-j)$。 + +综上,我们可以得到状态转移方程: + +$$ +\begin{aligned} +f[i][j] &= f[i-1][j] \\ +f[i][j] &= max(f[i][j], f[i-1][j-rods[i-1]]) & \text{if } j \geq rods[i-1] \\ +f[i][j] &= max(f[i][j], f[i-1][j+rods[i-1]] + rods[i-1]) & \text{if } j + rods[i-1] \leq s \\ +f[i][j] &= max(f[i][j], f[i-1][rods[i-1]-j] + rods[i-1]-j) & \text{if } j \lt rods[i-1] +\end{aligned} +$$ + +最终答案即为 $f[n][0]$。 + +时间复杂度 $O(n \times S)$,空间复杂度 $O(n \times S)$。其中 $n$ 和 $S$ 分别为 $rods$ 的长度和 $rods$ 中所有元素的和。 + + + +```python +class Solution: + def tallestBillboard(self, rods: List[int]) -> int: + n = len(rods) + s = sum(rods) + f = [[-inf] * (s + 1) for _ in range(n + 1)] + f[0][0] = 0 + t = 0 + for i, x in enumerate(rods, 1): + t += x + for j in range(t + 1): + f[i][j] = f[i - 1][j] + if j >= x: + f[i][j] = max(f[i][j], f[i - 1][j - x]) + if j + x <= t: + f[i][j] = max(f[i][j], f[i - 1][j + x] + x) + if j < x: + f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j) + return f[n][0] +``` + +```java +class Solution { + public int tallestBillboard(int[] rods) { + int n = rods.length; + int s = 0; + for (int x : rods) { + s += x; + } + int[][] f = new int[n + 1][s + 1]; + for (var e : f) { + Arrays.fill(e, -(1 << 30)); + } + f[0][0] = 0; + for (int i = 1, t = 0; i <= n; ++i) { + int x = rods[i - 1]; + t += x; + for (int j = 0; j <= t; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= x) { + f[i][j] = Math.max(f[i][j], f[i - 1][j - x]); + } + if (j + x <= t) { + f[i][j] = Math.max(f[i][j], f[i - 1][j + x] + x); + } + if (j < x) { + f[i][j] = Math.max(f[i][j], f[i - 1][x - j] + x - j); + } + } + } + return f[n][0]; + } +} +``` + +```cpp +class Solution { +public: + int tallestBillboard(vector& rods) { + int n = rods.size(); + int s = accumulate(rods.begin(), rods.end(), 0); + int f[n + 1][s + 1]; + memset(f, -0x3f, sizeof(f)); + f[0][0] = 0; + for (int i = 1, t = 0; i <= n; ++i) { + int x = rods[i - 1]; + t += x; + for (int j = 0; j <= t; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= x) { + f[i][j] = max(f[i][j], f[i - 1][j - x]); + } + if (j + x <= t) { + f[i][j] = max(f[i][j], f[i - 1][j + x] + x); + } + if (j < x) { + f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j); + } + } + } + return f[n][0]; + } +}; +``` + ```go func tallestBillboard(rods []int) int { n := len(rods) @@ -338,32 +348,6 @@ func tallestBillboard(rods []int) int { } ``` -### **TypeScript** - -```ts -function tallestBillboard(rods: number[]): number { - const s = rods.reduce((a, b) => a + b, 0); - const n = rods.length; - const f = new Array(n).fill(0).map(() => new Array(s + 1).fill(-1)); - const dfs = (i: number, j: number): number => { - if (i >= n) { - return j === 0 ? 0 : -(1 << 30); - } - if (f[i][j] !== -1) { - return f[i][j]; - } - let ans = Math.max(dfs(i + 1, j), dfs(i + 1, j + rods[i])); - ans = Math.max(ans, dfs(i + 1, Math.abs(j - rods[i])) + Math.min(j, rods[i])); - return (f[i][j] = ans); - }; - return dfs(0, 0); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0956.Tallest Billboard/README_EN.md b/solution/0900-0999/0956.Tallest Billboard/README_EN.md index 49d6f12976c7e..aaf89634cd808 100644 --- a/solution/0900-0999/0956.Tallest Billboard/README_EN.md +++ b/solution/0900-0999/0956.Tallest Billboard/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,29 +64,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def tallestBillboard(self, rods: List[int]) -> int: - n = len(rods) - s = sum(rods) - f = [[-inf] * (s + 1) for _ in range(n + 1)] - f[0][0] = 0 - t = 0 - for i, x in enumerate(rods, 1): - t += x - for j in range(t + 1): - f[i][j] = f[i - 1][j] - if j >= x: - f[i][j] = max(f[i][j], f[i - 1][j - x]) - if j + x <= t: - f[i][j] = max(f[i][j], f[i - 1][j + x] + x) - if j < x: - f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j) - return f[n][0] -``` - -### **Java** - ```java class Solution { private Integer[][] f; @@ -118,42 +95,6 @@ class Solution { } ``` -```java -class Solution { - public int tallestBillboard(int[] rods) { - int n = rods.length; - int s = 0; - for (int x : rods) { - s += x; - } - int[][] f = new int[n + 1][s + 1]; - for (var e : f) { - Arrays.fill(e, -(1 << 30)); - } - f[0][0] = 0; - for (int i = 1, t = 0; i <= n; ++i) { - int x = rods[i - 1]; - t += x; - for (int j = 0; j <= t; ++j) { - f[i][j] = f[i - 1][j]; - if (j >= x) { - f[i][j] = Math.max(f[i][j], f[i - 1][j - x]); - } - if (j + x <= t) { - f[i][j] = Math.max(f[i][j], f[i - 1][j + x] + x); - } - if (j < x) { - f[i][j] = Math.max(f[i][j], f[i - 1][x - j] + x - j); - } - } - } - return f[n][0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -178,38 +119,6 @@ public: }; ``` -```cpp -class Solution { -public: - int tallestBillboard(vector& rods) { - int n = rods.size(); - int s = accumulate(rods.begin(), rods.end(), 0); - int f[n + 1][s + 1]; - memset(f, -0x3f, sizeof(f)); - f[0][0] = 0; - for (int i = 1, t = 0; i <= n; ++i) { - int x = rods[i - 1]; - t += x; - for (int j = 0; j <= t; ++j) { - f[i][j] = f[i - 1][j]; - if (j >= x) { - f[i][j] = max(f[i][j], f[i - 1][j - x]); - } - if (j + x <= t) { - f[i][j] = max(f[i][j], f[i - 1][j + x] + x); - } - if (j < x) { - f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j); - } - } - } - return f[n][0]; - } -}; -``` - -### **Go** - ```go func tallestBillboard(rods []int) int { s := 0 @@ -251,6 +160,117 @@ func abs(x int) int { } ``` +```ts +function tallestBillboard(rods: number[]): number { + const s = rods.reduce((a, b) => a + b, 0); + const n = rods.length; + const f = new Array(n).fill(0).map(() => new Array(s + 1).fill(-1)); + const dfs = (i: number, j: number): number => { + if (i >= n) { + return j === 0 ? 0 : -(1 << 30); + } + if (f[i][j] !== -1) { + return f[i][j]; + } + let ans = Math.max(dfs(i + 1, j), dfs(i + 1, j + rods[i])); + ans = Math.max(ans, dfs(i + 1, Math.abs(j - rods[i])) + Math.min(j, rods[i])); + return (f[i][j] = ans); + }; + return dfs(0, 0); +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def tallestBillboard(self, rods: List[int]) -> int: + n = len(rods) + s = sum(rods) + f = [[-inf] * (s + 1) for _ in range(n + 1)] + f[0][0] = 0 + t = 0 + for i, x in enumerate(rods, 1): + t += x + for j in range(t + 1): + f[i][j] = f[i - 1][j] + if j >= x: + f[i][j] = max(f[i][j], f[i - 1][j - x]) + if j + x <= t: + f[i][j] = max(f[i][j], f[i - 1][j + x] + x) + if j < x: + f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j) + return f[n][0] +``` + +```java +class Solution { + public int tallestBillboard(int[] rods) { + int n = rods.length; + int s = 0; + for (int x : rods) { + s += x; + } + int[][] f = new int[n + 1][s + 1]; + for (var e : f) { + Arrays.fill(e, -(1 << 30)); + } + f[0][0] = 0; + for (int i = 1, t = 0; i <= n; ++i) { + int x = rods[i - 1]; + t += x; + for (int j = 0; j <= t; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= x) { + f[i][j] = Math.max(f[i][j], f[i - 1][j - x]); + } + if (j + x <= t) { + f[i][j] = Math.max(f[i][j], f[i - 1][j + x] + x); + } + if (j < x) { + f[i][j] = Math.max(f[i][j], f[i - 1][x - j] + x - j); + } + } + } + return f[n][0]; + } +} +``` + +```cpp +class Solution { +public: + int tallestBillboard(vector& rods) { + int n = rods.size(); + int s = accumulate(rods.begin(), rods.end(), 0); + int f[n + 1][s + 1]; + memset(f, -0x3f, sizeof(f)); + f[0][0] = 0; + for (int i = 1, t = 0; i <= n; ++i) { + int x = rods[i - 1]; + t += x; + for (int j = 0; j <= t; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= x) { + f[i][j] = max(f[i][j], f[i - 1][j - x]); + } + if (j + x <= t) { + f[i][j] = max(f[i][j], f[i - 1][j + x] + x); + } + if (j < x) { + f[i][j] = max(f[i][j], f[i - 1][x - j] + x - j); + } + } + } + return f[n][0]; + } +}; +``` + ```go func tallestBillboard(rods []int) int { n := len(rods) @@ -286,32 +306,6 @@ func tallestBillboard(rods []int) int { } ``` -### **TypeScript** - -```ts -function tallestBillboard(rods: number[]): number { - const s = rods.reduce((a, b) => a + b, 0); - const n = rods.length; - const f = new Array(n).fill(0).map(() => new Array(s + 1).fill(-1)); - const dfs = (i: number, j: number): number => { - if (i >= n) { - return j === 0 ? 0 : -(1 << 30); - } - if (f[i][j] !== -1) { - return f[i][j]; - } - let ans = Math.max(dfs(i + 1, j), dfs(i + 1, j + rods[i])); - ans = Math.max(ans, dfs(i + 1, Math.abs(j - rods[i])) + Math.min(j, rods[i])); - return (f[i][j] = ans); - }; - return dfs(0, 0); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0957.Prison Cells After N Days/README.md b/solution/0900-0999/0957.Prison Cells After N Days/README.md index e8a81a323a728..0baf1adefcfcb 100644 --- a/solution/0900-0999/0957.Prison Cells After N Days/README.md +++ b/solution/0900-0999/0957.Prison Cells After N Days/README.md @@ -58,30 +58,4 @@ Day 7: [0, 0, 1, 1, 0, 0, 0, 0] ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0900-0999/0957.Prison Cells After N Days/README_EN.md b/solution/0900-0999/0957.Prison Cells After N Days/README_EN.md index 75d6bce77c282..2863b6a65b6a0 100644 --- a/solution/0900-0999/0957.Prison Cells After N Days/README_EN.md +++ b/solution/0900-0999/0957.Prison Cells After N Days/README_EN.md @@ -54,24 +54,4 @@ Day 7: [0, 0, 1, 1, 0, 0, 0, 0] ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0900-0999/0958.Check Completeness of a Binary Tree/README.md b/solution/0900-0999/0958.Check Completeness of a Binary Tree/README.md index d20d831798b90..939f8dc7b6009 100644 --- a/solution/0900-0999/0958.Check Completeness of a Binary Tree/README.md +++ b/solution/0900-0999/0958.Check Completeness of a Binary Tree/README.md @@ -43,14 +43,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -70,10 +66,6 @@ class Solution: return all(node is None for node in q) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -107,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -137,8 +127,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -163,10 +151,6 @@ func isCompleteTree(root *TreeNode) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0958.Check Completeness of a Binary Tree/README_EN.md b/solution/0900-0999/0958.Check Completeness of a Binary Tree/README_EN.md index 2b551220c9a45..37f1fb007d6cc 100644 --- a/solution/0900-0999/0958.Check Completeness of a Binary Tree/README_EN.md +++ b/solution/0900-0999/0958.Check Completeness of a Binary Tree/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -58,8 +58,6 @@ class Solution: return all(node is None for node in q) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -149,10 +143,6 @@ func isCompleteTree(root *TreeNode) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0959.Regions Cut By Slashes/README.md b/solution/0900-0999/0959.Regions Cut By Slashes/README.md index 3f71541fb333c..6f34e16586c5f 100644 --- a/solution/0900-0999/0959.Regions Cut By Slashes/README.md +++ b/solution/0900-0999/0959.Regions Cut By Slashes/README.md @@ -56,81 +56,10 @@ ## 解法 - - -并查集。对于本题,可以把每个方块看成四个三角形,从上开始顺时针编号 0,1,2,3,`'/'`代表 0 和 3,1 和 2 连通,`'\\'` 代表 0 和 1,2 和 3 连通,`' '` 代表 0、1、2、3 都联通,然后再和方块周围的三角形联通,最后返回总的连通分量就得到结果了。 - -以下是并查集的几个常用模板。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` +### 方法一 -### **Python3** - - - ```python class Solution: def regionsBySlashes(self, grid: List[str]) -> int: @@ -169,10 +98,6 @@ class Solution: return size ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -230,8 +155,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -280,8 +203,6 @@ public: }; ``` -### **Go** - ```go func regionsBySlashes(grid []string) int { n := len(grid) @@ -331,10 +252,6 @@ func regionsBySlashes(grid []string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0959.Regions Cut By Slashes/README_EN.md b/solution/0900-0999/0959.Regions Cut By Slashes/README_EN.md index 45c541c3108c6..6df1234eee0ad 100644 --- a/solution/0900-0999/0959.Regions Cut By Slashes/README_EN.md +++ b/solution/0900-0999/0959.Regions Cut By Slashes/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -86,8 +86,6 @@ class Solution: return size ``` -### **Java** - ```java class Solution { private int[] p; @@ -145,8 +143,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -195,8 +191,6 @@ public: }; ``` -### **Go** - ```go func regionsBySlashes(grid []string) int { n := len(grid) @@ -246,10 +240,6 @@ func regionsBySlashes(grid []string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0960.Delete Columns to Make Sorted III/README.md b/solution/0900-0999/0960.Delete Columns to Make Sorted III/README.md index 629c28b530471..f11ea6d52908a 100644 --- a/solution/0900-0999/0960.Delete Columns to Make Sorted III/README.md +++ b/solution/0900-0999/0960.Delete Columns to Make Sorted III/README.md @@ -59,14 +59,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minDeletionSize(self, strs: List[str]) -> int: @@ -79,10 +75,6 @@ class Solution: return n - max(dp) ``` -### **Java** - - - ```java class Solution { public int minDeletionSize(String[] strs) { @@ -112,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +131,6 @@ public: }; ``` -### **Go** - ```go func minDeletionSize(strs []string) int { n := len(strs[0]) @@ -170,10 +158,6 @@ func minDeletionSize(strs []string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0960.Delete Columns to Make Sorted III/README_EN.md b/solution/0900-0999/0960.Delete Columns to Make Sorted III/README_EN.md index f5aff0d05cd53..bc73d669938bd 100644 --- a/solution/0900-0999/0960.Delete Columns to Make Sorted III/README_EN.md +++ b/solution/0900-0999/0960.Delete Columns to Make Sorted III/README_EN.md @@ -54,9 +54,9 @@ Note that strs[0] > strs[1] - the array strs is not necessarily in lexicograp ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return n - max(dp) ``` -### **Java** - ```java class Solution { public int minDeletionSize(String[] strs) { @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +126,6 @@ public: }; ``` -### **Go** - ```go func minDeletionSize(strs []string) int { n := len(strs[0]) @@ -159,10 +153,6 @@ func minDeletionSize(strs []string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/README.md b/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/README.md index 0dd9dcde1b65e..6b2f7056f0015 100644 --- a/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/README.md +++ b/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 由于数组 $nums$ 一共有 $2n$ 个元素,其中有 $n + 1$ 个不同的元素,且有一个元素重复了 $n$ 次,说明数组中的其余 $n$ 个元素都是不同的。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def repeatedNTimes(self, nums: List[int]) -> int: @@ -82,10 +76,6 @@ class Solution: s.add(x) ``` -### **Java** - - - ```java class Solution { public int repeatedNTimes(int[] nums) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func repeatedNTimes(nums []int) int { s := map[int]bool{} @@ -130,8 +116,6 @@ func repeatedNTimes(nums []int) int { } ``` -### **TypeScript** - ```ts function repeatedNTimes(nums: number[]): number { const s: Set = new Set(); @@ -144,8 +128,6 @@ function repeatedNTimes(nums: number[]): number { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -162,10 +144,6 @@ var repeatedNTimes = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/README_EN.md b/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/README_EN.md index 33ac0e76d7357..62b066de8b60f 100644 --- a/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/README_EN.md +++ b/solution/0900-0999/0961.N-Repeated Element in Size 2N Array/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: s.add(x) ``` -### **Java** - ```java class Solution { public int repeatedNTimes(int[] nums) { @@ -66,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -83,8 +79,6 @@ public: }; ``` -### **Go** - ```go func repeatedNTimes(nums []int) int { s := map[int]bool{} @@ -97,8 +91,6 @@ func repeatedNTimes(nums []int) int { } ``` -### **TypeScript** - ```ts function repeatedNTimes(nums: number[]): number { const s: Set = new Set(); @@ -111,8 +103,6 @@ function repeatedNTimes(nums: number[]): number { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -129,10 +119,6 @@ var repeatedNTimes = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0962.Maximum Width Ramp/README.md b/solution/0900-0999/0962.Maximum Width Ramp/README.md index ad48e074819ce..a64db2aee1680 100644 --- a/solution/0900-0999/0962.Maximum Width Ramp/README.md +++ b/solution/0900-0999/0962.Maximum Width Ramp/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 根据题意,我们可以发现,所有可能的 $nums[i]$ 所构成的子序列一定是单调递减的。为什么呢?我们不妨用反证法证明一下。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def maxWidthRamp(self, nums: List[int]) -> int: @@ -75,10 +69,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxWidthRamp(int[] nums) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func maxWidthRamp(nums []int) int { n := len(nums) @@ -152,10 +138,6 @@ func maxWidthRamp(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0962.Maximum Width Ramp/README_EN.md b/solution/0900-0999/0962.Maximum Width Ramp/README_EN.md index 9e01563e2c26c..fdd3467f22c47 100644 --- a/solution/0900-0999/0962.Maximum Width Ramp/README_EN.md +++ b/solution/0900-0999/0962.Maximum Width Ramp/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxWidthRamp(int[] nums) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +101,6 @@ public: }; ``` -### **Go** - ```go func maxWidthRamp(nums []int) int { n := len(nums) @@ -130,10 +124,6 @@ func maxWidthRamp(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0963.Minimum Area Rectangle II/README.md b/solution/0900-0999/0963.Minimum Area Rectangle II/README.md index 509237f11586e..177e09efe3e26 100644 --- a/solution/0900-0999/0963.Minimum Area Rectangle II/README.md +++ b/solution/0900-0999/0963.Minimum Area Rectangle II/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:哈希表 + 枚举** +### 方法一:哈希表 + 枚举 我们用哈希表存放所有的点,然后枚举三个点 $p_1 = (x_1, y_1)$, $p_2 = (x_2, y_2)$, $p_3 = (x_3, y_3)$,其中 $p_2$ 和 $p_3$ 是矩形的对角线的两个端点。如果 $p_1$ 和 $p_2$ 构成的直线以及 $p_1$ 和 $p_3$ 构成的直线垂直,并且第四个点 $(x_4, y_4)=(x_2 - x_1 + x_3, y_2 - y_1 + y_3)$ 存在于哈希表中,那么就找到了一个矩形。此时,我们可以计算出矩形的面积,并更新答案。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def minAreaFreeRect(self, points: List[List[int]]) -> float: @@ -103,10 +97,6 @@ class Solution: return 0 if ans == inf else ans ``` -### **Java** - - - ```java class Solution { public double minAreaFreeRect(int[][] points) { @@ -146,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -187,8 +175,6 @@ public: }; ``` -### **Go** - ```go func minAreaFreeRect(points [][]int) float64 { n := len(points) @@ -228,8 +214,6 @@ func minAreaFreeRect(points [][]int) float64 { } ``` -### **TypeScript** - ```ts function minAreaFreeRect(points: number[][]): number { const n = points.length; @@ -265,10 +249,6 @@ function minAreaFreeRect(points: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0963.Minimum Area Rectangle II/README_EN.md b/solution/0900-0999/0963.Minimum Area Rectangle II/README_EN.md index 40b984cc5fa2b..08f9998975ccc 100644 --- a/solution/0900-0999/0963.Minimum Area Rectangle II/README_EN.md +++ b/solution/0900-0999/0963.Minimum Area Rectangle II/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return 0 if ans == inf else ans ``` -### **Java** - ```java class Solution { public double minAreaFreeRect(int[][] points) { @@ -118,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +155,6 @@ public: }; ``` -### **Go** - ```go func minAreaFreeRect(points [][]int) float64 { n := len(points) @@ -200,8 +194,6 @@ func minAreaFreeRect(points [][]int) float64 { } ``` -### **TypeScript** - ```ts function minAreaFreeRect(points: number[][]): number { const n = points.length; @@ -237,10 +229,6 @@ function minAreaFreeRect(points: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0964.Least Operators to Express Number/README.md b/solution/0900-0999/0964.Least Operators to Express Number/README.md index cb4e6bc30b0b8..38b9a7fa97ba2 100644 --- a/solution/0900-0999/0964.Least Operators to Express Number/README.md +++ b/solution/0900-0999/0964.Least Operators to Express Number/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们定义一个函数 $dfs(v)$,表示用 $x$ 凑成数字 $v$ 所需要的最少运算符数量。那么答案就是 $dfs(target)$。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def leastOpsExpressTarget(self, x: int, target: int) -> int: @@ -97,10 +91,6 @@ class Solution: return dfs(target) ``` -### **Java** - - - ```java class Solution { private int x; @@ -134,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -166,8 +154,6 @@ public: }; ``` -### **Go** - ```go func leastOpsExpressTarget(x int, target int) int { f := map[int]int{} @@ -196,8 +182,6 @@ func leastOpsExpressTarget(x int, target int) int { } ``` -### **TypeScript** - ```ts function leastOpsExpressTarget(x: number, target: number): number { const f: Map = new Map(); @@ -225,10 +209,6 @@ function leastOpsExpressTarget(x: number, target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0964.Least Operators to Express Number/README_EN.md b/solution/0900-0999/0964.Least Operators to Express Number/README_EN.md index 234b0177f8560..f4fe0b1f56778 100644 --- a/solution/0900-0999/0964.Least Operators to Express Number/README_EN.md +++ b/solution/0900-0999/0964.Least Operators to Express Number/README_EN.md @@ -55,9 +55,9 @@ The expression contains 3 operations. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return dfs(target) ``` -### **Java** - ```java class Solution { private int x; @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +139,6 @@ public: }; ``` -### **Go** - ```go func leastOpsExpressTarget(x int, target int) int { f := map[int]int{} @@ -173,8 +167,6 @@ func leastOpsExpressTarget(x int, target int) int { } ``` -### **TypeScript** - ```ts function leastOpsExpressTarget(x: number, target: number): number { const f: Map = new Map(); @@ -202,10 +194,6 @@ function leastOpsExpressTarget(x: number, target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0965.Univalued Binary Tree/README.md b/solution/0900-0999/0965.Univalued Binary Tree/README.md index a5f4e631c6c24..4abb7f3a7e3fa 100644 --- a/solution/0900-0999/0965.Univalued Binary Tree/README.md +++ b/solution/0900-0999/0965.Univalued Binary Tree/README.md @@ -39,14 +39,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -64,10 +60,6 @@ class Solution: return dfs(root) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -98,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -125,8 +115,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -148,8 +136,6 @@ func isUnivalTree(root *TreeNode) bool { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -177,8 +163,6 @@ function isUnivalTree(root: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -215,10 +199,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0965.Univalued Binary Tree/README_EN.md b/solution/0900-0999/0965.Univalued Binary Tree/README_EN.md index a8b5707829d30..9985bbd30dd17 100644 --- a/solution/0900-0999/0965.Univalued Binary Tree/README_EN.md +++ b/solution/0900-0999/0965.Univalued Binary Tree/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -54,8 +54,6 @@ class Solution: return dfs(root) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -136,8 +130,6 @@ func isUnivalTree(root *TreeNode) bool { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -165,8 +157,6 @@ function isUnivalTree(root: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -203,10 +193,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0966.Vowel Spellchecker/README.md b/solution/0900-0999/0966.Vowel Spellchecker/README.md index 8b8c218f27b2e..8680688a16024 100644 --- a/solution/0900-0999/0966.Vowel Spellchecker/README.md +++ b/solution/0900-0999/0966.Vowel Spellchecker/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 遍历 `wordlist`,将单词按照大小写不敏感、元音不敏感的规则分别存入哈希表 `low` 和 `pat` 中,其中 `low` 的键为单词的小写形式,`pat` 的键为将单词的元音字母替换为 `*` 后的字符串,值为单词本身。用哈希表 `s` 存储 `wordlist` 中的单词。 @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: @@ -118,10 +112,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public String[] spellchecker(String[] wordlist, String[] queries) { @@ -170,8 +160,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -224,8 +212,6 @@ public: }; ``` -### **Go** - ```go func spellchecker(wordlist []string, queries []string) (ans []string) { s := map[string]bool{} @@ -271,10 +257,6 @@ func spellchecker(wordlist []string, queries []string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0966.Vowel Spellchecker/README_EN.md b/solution/0900-0999/0966.Vowel Spellchecker/README_EN.md index f59d2064d7cb6..add51191b607d 100644 --- a/solution/0900-0999/0966.Vowel Spellchecker/README_EN.md +++ b/solution/0900-0999/0966.Vowel Spellchecker/README_EN.md @@ -57,9 +57,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -94,8 +94,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public String[] spellchecker(String[] wordlist, String[] queries) { @@ -144,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -198,8 +194,6 @@ public: }; ``` -### **Go** - ```go func spellchecker(wordlist []string, queries []string) (ans []string) { s := map[string]bool{} @@ -245,10 +239,6 @@ func spellchecker(wordlist []string, queries []string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0967.Numbers With Same Consecutive Differences/README.md b/solution/0900-0999/0967.Numbers With Same Consecutive Differences/README.md index 7d002bdb9d2a2..a01cf0ee94088 100644 --- a/solution/0900-0999/0967.Numbers With Same Consecutive Differences/README.md +++ b/solution/0900-0999/0967.Numbers With Same Consecutive Differences/README.md @@ -53,16 +53,10 @@ ## 解法 - - -DFS。 +### 方法一 -### **Python3** - - - ```python class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] numsSameConsecDiff(int n, int k) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func numsSameConsecDiff(n int, k int) []int { var ans []int @@ -169,10 +155,6 @@ func numsSameConsecDiff(n int, k int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0967.Numbers With Same Consecutive Differences/README_EN.md b/solution/0900-0999/0967.Numbers With Same Consecutive Differences/README_EN.md index 2fd8bf8e88e1b..05665706a5fd0 100644 --- a/solution/0900-0999/0967.Numbers With Same Consecutive Differences/README_EN.md +++ b/solution/0900-0999/0967.Numbers With Same Consecutive Differences/README_EN.md @@ -34,12 +34,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python class Solution: def numsSameConsecDiff(self, n: int, k: int) -> List[int]: @@ -60,8 +58,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] numsSameConsecDiff(int n, int k) { @@ -92,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func numsSameConsecDiff(n int, k int) []int { var ans []int @@ -144,10 +136,6 @@ func numsSameConsecDiff(n int, k int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0968.Binary Tree Cameras/README.md b/solution/0900-0999/0968.Binary Tree Cameras/README.md index 3deb27f2e4dea..f5c01efdb6a3e 100644 --- a/solution/0900-0999/0968.Binary Tree Cameras/README.md +++ b/solution/0900-0999/0968.Binary Tree Cameras/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:动态规划(树形 DP)** +### 方法一:动态规划(树形 DP) 对于每个节点,我们定义三种状态: @@ -70,10 +68,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -97,10 +91,6 @@ class Solution: return min(a, b) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -176,8 +164,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -205,8 +191,6 @@ func minCameraCover(root *TreeNode) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -239,10 +223,6 @@ function minCameraCover(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0968.Binary Tree Cameras/README_EN.md b/solution/0900-0999/0968.Binary Tree Cameras/README_EN.md index e743d4c35ba5b..94f36edc2d991 100644 --- a/solution/0900-0999/0968.Binary Tree Cameras/README_EN.md +++ b/solution/0900-0999/0968.Binary Tree Cameras/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -62,8 +62,6 @@ class Solution: return min(a, b) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -139,8 +135,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -168,8 +162,6 @@ func minCameraCover(root *TreeNode) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -202,10 +194,6 @@ function minCameraCover(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0969.Pancake Sorting/README.md b/solution/0900-0999/0969.Pancake Sorting/README.md index c1603bd0d270e..e6f5ee6963bf0 100644 --- a/solution/0900-0999/0969.Pancake Sorting/README.md +++ b/solution/0900-0999/0969.Pancake Sorting/README.md @@ -57,14 +57,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def pancakeSort(self, arr: List[int]) -> List[int]: @@ -89,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List pancakeSort(int[] arr) { @@ -124,36 +116,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function pancakeSort(arr: number[]): number[] { - let ans = []; - for (let n = arr.length; n > 1; n--) { - let index = 0; - for (let i = 1; i < n; i++) { - if (arr[i] >= arr[index]) { - index = i; - } - } - if (index == n - 1) continue; - reverse(arr, index); - reverse(arr, n - 1); - ans.push(index + 1); - ans.push(n); - } - return ans; -} - -function reverse(nums: Array, end: number): void { - for (let i = 0, j = end; i < j; i++, j--) { - [nums[i], nums[j]] = [nums[j], nums[i]]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -177,8 +139,6 @@ public: }; ``` -### **Go** - ```go func pancakeSort(arr []int) []int { var ans []int @@ -205,7 +165,31 @@ func pancakeSort(arr []int) []int { } ``` -### **Rust** +```ts +function pancakeSort(arr: number[]): number[] { + let ans = []; + for (let n = arr.length; n > 1; n--) { + let index = 0; + for (let i = 1; i < n; i++) { + if (arr[i] >= arr[index]) { + index = i; + } + } + if (index == n - 1) continue; + reverse(arr, index); + reverse(arr, n - 1); + ans.push(index + 1); + ans.push(n); + } + return ans; +} + +function reverse(nums: Array, end: number): void { + for (let i = 0, j = end; i < j; i++, j--) { + [nums[i], nums[j]] = [nums[j], nums[i]]; + } +} +``` ```rust impl Solution { @@ -232,10 +216,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0969.Pancake Sorting/README_EN.md b/solution/0900-0999/0969.Pancake Sorting/README_EN.md index eb57f89f05a54..1319001417739 100644 --- a/solution/0900-0999/0969.Pancake Sorting/README_EN.md +++ b/solution/0900-0999/0969.Pancake Sorting/README_EN.md @@ -52,9 +52,9 @@ Note that other answers, such as [3, 3], would also be accepted. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List pancakeSort(int[] arr) { @@ -113,36 +111,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function pancakeSort(arr: number[]): number[] { - let ans = []; - for (let n = arr.length; n > 1; n--) { - let index = 0; - for (let i = 1; i < n; i++) { - if (arr[i] >= arr[index]) { - index = i; - } - } - if (index == n - 1) continue; - reverse(arr, index); - reverse(arr, n - 1); - ans.push(index + 1); - ans.push(n); - } - return ans; -} - -function reverse(nums: Array, end: number): void { - for (let i = 0, j = end; i < j; i++, j--) { - [nums[i], nums[j]] = [nums[j], nums[i]]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -166,8 +134,6 @@ public: }; ``` -### **Go** - ```go func pancakeSort(arr []int) []int { var ans []int @@ -194,7 +160,31 @@ func pancakeSort(arr []int) []int { } ``` -### **Rust** +```ts +function pancakeSort(arr: number[]): number[] { + let ans = []; + for (let n = arr.length; n > 1; n--) { + let index = 0; + for (let i = 1; i < n; i++) { + if (arr[i] >= arr[index]) { + index = i; + } + } + if (index == n - 1) continue; + reverse(arr, index); + reverse(arr, n - 1); + ans.push(index + 1); + ans.push(n); + } + return ans; +} + +function reverse(nums: Array, end: number): void { + for (let i = 0, j = end; i < j; i++, j--) { + [nums[i], nums[j]] = [nums[j], nums[i]]; + } +} +``` ```rust impl Solution { @@ -221,10 +211,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0970.Powerful Integers/README.md b/solution/0900-0999/0970.Powerful Integers/README.md index 730284a82e517..511bf1e7552ce 100644 --- a/solution/0900-0999/0970.Powerful Integers/README.md +++ b/solution/0900-0999/0970.Powerful Integers/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:哈希表 + 枚举** +### 方法一:哈希表 + 枚举 根据题目描述,一个强整数可以表示成 $x^i + y^j$,其中 $i \geq 0$, $j \geq 0$。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: @@ -84,10 +78,6 @@ class Solution: return list(ans) ``` -### **Java** - - - ```java class Solution { public List powerfulIntegers(int x, int y, int bound) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func powerfulIntegers(x int, y int, bound int) (ans []int) { s := map[int]struct{}{} @@ -154,8 +140,6 @@ func powerfulIntegers(x int, y int, bound int) (ans []int) { } ``` -### **TypeScript** - ```ts function powerfulIntegers(x: number, y: number, bound: number): number[] { const ans = new Set(); @@ -174,8 +158,6 @@ function powerfulIntegers(x: number, y: number, bound: number): number[] { } ``` -### **JavaScript** - ```js /** * @param {number} x @@ -200,10 +182,6 @@ var powerfulIntegers = function (x, y, bound) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0970.Powerful Integers/README_EN.md b/solution/0900-0999/0970.Powerful Integers/README_EN.md index 7b00771b6550c..fc67abc201fe5 100644 --- a/solution/0900-0999/0970.Powerful Integers/README_EN.md +++ b/solution/0900-0999/0970.Powerful Integers/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Hash Table + Enumeration** +### Solution 1: Hash Table + Enumeration According to the description of the problem, a powerful integer can be represented as $x^i + y^j$, where $i \geq 0$, $j \geq 0$. @@ -57,8 +57,6 @@ The time complexity is $O(\log^2 bound)$, and the space complexity is $O(\log^2 -### **Python3** - ```python class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: @@ -77,8 +75,6 @@ class Solution: return list(ans) ``` -### **Java** - ```java class Solution { public List powerfulIntegers(int x, int y, int bound) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func powerfulIntegers(x int, y int, bound int) (ans []int) { s := map[int]struct{}{} @@ -145,8 +137,6 @@ func powerfulIntegers(x int, y int, bound int) (ans []int) { } ``` -### **TypeScript** - ```ts function powerfulIntegers(x: number, y: number, bound: number): number[] { const ans = new Set(); @@ -165,8 +155,6 @@ function powerfulIntegers(x: number, y: number, bound: number): number[] { } ``` -### **JavaScript** - ```js /** * @param {number} x @@ -191,10 +179,6 @@ var powerfulIntegers = function (x, y, bound) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/README.md b/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/README.md index 823ec683f869a..bc5e65dfc3c1c 100644 --- a/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/README.md +++ b/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们可以通过深度优先搜索的方式遍历整棵树,用一个下标 $i$ 记录当前遍历到的节点在数组 $voyage$ 中的下标,如果当前遍历到的节点的值不等于 $voyage[i]$,那么说明翻转后无法匹配,我们标记 $ok$ 为 `false`,并直接返回。否则,我们将 $i$ 的值加 $1$,然后判断当前节点是否有左子节点,如果没有,或者左子节点的值等于 $voyage[i]$,那么我们递归遍历当前的左右子节点;否则,我们需要翻转当前节点,然后再递归遍历当前的右子节点和左子节点。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -104,10 +98,6 @@ class Solution: return ans if ok else [-1] ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -158,8 +148,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -202,8 +190,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -244,8 +230,6 @@ func flipMatchVoyage(root *TreeNode, voyage []int) []int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -287,10 +271,6 @@ function flipMatchVoyage(root: TreeNode | null, voyage: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/README_EN.md b/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/README_EN.md index b144749f59217..85964fac885be 100644 --- a/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/README_EN.md +++ b/solution/0900-0999/0971.Flip Binary Tree To Match Preorder Traversal/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -86,8 +86,6 @@ class Solution: return ans if ok else [-1] ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -138,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -182,8 +178,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -224,8 +218,6 @@ func flipMatchVoyage(root *TreeNode, voyage []int) []int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -267,10 +259,6 @@ function flipMatchVoyage(root: TreeNode | null, voyage: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0972.Equal Rational Numbers/README.md b/solution/0900-0999/0972.Equal Rational Numbers/README.md index 213ac5debbf56..f69584265d068 100644 --- a/solution/0900-0999/0972.Equal Rational Numbers/README.md +++ b/solution/0900-0999/0972.Equal Rational Numbers/README.md @@ -74,30 +74,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0900-0999/0972.Equal Rational Numbers/README_EN.md b/solution/0900-0999/0972.Equal Rational Numbers/README_EN.md index 403da27d509ef..82b6632855551 100644 --- a/solution/0900-0999/0972.Equal Rational Numbers/README_EN.md +++ b/solution/0900-0999/0972.Equal Rational Numbers/README_EN.md @@ -70,24 +70,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/0900-0999/0973.K Closest Points to Origin/README.md b/solution/0900-0999/0973.K Closest Points to Origin/README.md index ea5076d7bc1b2..a2d0a55a7d63f 100644 --- a/solution/0900-0999/0973.K Closest Points to Origin/README.md +++ b/solution/0900-0999/0973.K Closest Points to Origin/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:自定义排序** +### 方法一:自定义排序 我们将所有点按照与原点的距离从小到大排序,然后取前 $k$ 个点即可。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: @@ -68,10 +62,6 @@ class Solution: return points[:k] ``` -### **Java** - - - ```java class Solution { public int[][] kClosest(int[][] points, int k) { @@ -85,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +87,6 @@ public: }; ``` -### **Go** - ```go func kClosest(points [][]int, k int) [][]int { sort.Slice(points, func(i, j int) bool { @@ -111,16 +97,12 @@ func kClosest(points [][]int, k int) [][]int { } ``` -### **TypeScript** - ```ts function kClosest(points: number[][], k: number): number[][] { return points.sort((a, b) => a[0] ** 2 + a[1] ** 2 - (b[0] ** 2 + b[1] ** 2)).slice(0, k); } ``` -### **Rust** - ```rust impl Solution { pub fn k_closest(mut points: Vec>, k: i32) -> Vec> { @@ -132,10 +114,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0973.K Closest Points to Origin/README_EN.md b/solution/0900-0999/0973.K Closest Points to Origin/README_EN.md index d0bca7471a789..583f30471e31c 100644 --- a/solution/0900-0999/0973.K Closest Points to Origin/README_EN.md +++ b/solution/0900-0999/0973.K Closest Points to Origin/README_EN.md @@ -41,9 +41,9 @@ We only want the closest k = 1 points from the origin, so the answer is just [[- ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return points[:k] ``` -### **Java** - ```java class Solution { public int[][] kClosest(int[][] points, int k) { @@ -67,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -81,8 +77,6 @@ public: }; ``` -### **Go** - ```go func kClosest(points [][]int, k int) [][]int { sort.Slice(points, func(i, j int) bool { @@ -93,16 +87,12 @@ func kClosest(points [][]int, k int) [][]int { } ``` -### **TypeScript** - ```ts function kClosest(points: number[][], k: number): number[][] { return points.sort((a, b) => a[0] ** 2 + a[1] ** 2 - (b[0] ** 2 + b[1] ** 2)).slice(0, k); } ``` -### **Rust** - ```rust impl Solution { pub fn k_closest(mut points: Vec>, k: i32) -> Vec> { @@ -114,10 +104,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0974.Subarray Sums Divisible by K/README.md b/solution/0900-0999/0974.Subarray Sums Divisible by K/README.md index d6bf01bd7e48e..dc425f29e8d2f 100644 --- a/solution/0900-0999/0974.Subarray Sums Divisible by K/README.md +++ b/solution/0900-0999/0974.Subarray Sums Divisible by K/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:哈希表 + 前缀和** +### 方法一:哈希表 + 前缀和 假设存在 $i \leq j$,使得 $nums[i,..j]$ 的和能被 $k$ 整除,如果我们令 $s_i$ 表示 $nums[0,..i]$ 的和,令 $s_j$ 表示 $nums[0,..j]$ 的和,那么 $s_j - s_i$ 能被 $k$ 整除,即 $(s_j - s_i) \bmod k = 0$,也即 $s_j \bmod k = s_i \bmod k$。因此,我们可以用哈希表统计前缀和模 $k$ 的值的个数,从而快速判断是否存在满足条件的子数组。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def subarraysDivByK(self, nums: List[int], k: int) -> int: @@ -75,10 +69,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int subarraysDivByK(int[] nums, int k) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +100,6 @@ public: }; ``` -### **Go** - ```go func subarraysDivByK(nums []int, k int) (ans int) { cnt := map[int]int{0: 1} @@ -127,8 +113,6 @@ func subarraysDivByK(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function subarraysDivByK(nums: number[], k: number): number { const counter = new Map(); @@ -145,10 +129,6 @@ function subarraysDivByK(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0974.Subarray Sums Divisible by K/README_EN.md b/solution/0900-0999/0974.Subarray Sums Divisible by K/README_EN.md index dfdca46c979e7..214a7d65d2ead 100644 --- a/solution/0900-0999/0974.Subarray Sums Divisible by K/README_EN.md +++ b/solution/0900-0999/0974.Subarray Sums Divisible by K/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int subarraysDivByK(int[] nums, int k) { @@ -70,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +83,6 @@ public: }; ``` -### **Go** - ```go func subarraysDivByK(nums []int, k int) (ans int) { cnt := map[int]int{0: 1} @@ -102,8 +96,6 @@ func subarraysDivByK(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function subarraysDivByK(nums: number[], k: number): number { const counter = new Map(); @@ -120,10 +112,6 @@ function subarraysDivByK(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0975.Odd Even Jump/README.md b/solution/0900-0999/0975.Odd Even Jump/README.md index ad675422d63fd..eafd72536cedd 100644 --- a/solution/0900-0999/0975.Odd Even Jump/README.md +++ b/solution/0900-0999/0975.Odd Even Jump/README.md @@ -76,9 +76,7 @@ ## 解法 - - -**方法一:有序集合 + 记忆化搜索** +### 方法一:有序集合 + 记忆化搜索 我们先利用有序集合,预处理出每个位置能跳到的位置,记录在数组 $g$ 中,其中 $g[i][1]$ 和 $g[i][0]$ 分别表示当前位置是奇数次跳还是偶数次跳时能跳到的位置。如果不能跳到任何位置,那么 $g[i][1]$ 和 $g[i][0]$ 都为 $-1$。 @@ -88,10 +86,6 @@ -### **Python3** - - - ```python from sortedcontainers import SortedDict @@ -118,10 +112,6 @@ class Solution: return sum(dfs(i, 1) for i in range(n)) ``` -### **Java** - - - ```java class Solution { private int n; @@ -162,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -201,8 +189,6 @@ public: }; ``` -### **Go** - ```go func oddEvenJumps(arr []int) (ans int) { n := len(arr) @@ -245,10 +231,6 @@ func oddEvenJumps(arr []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0975.Odd Even Jump/README_EN.md b/solution/0900-0999/0975.Odd Even Jump/README_EN.md index 07df171b3544f..a05e2060d9c60 100644 --- a/solution/0900-0999/0975.Odd Even Jump/README_EN.md +++ b/solution/0900-0999/0975.Odd Even Jump/README_EN.md @@ -71,9 +71,9 @@ number of jumps. ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedDict @@ -101,8 +101,6 @@ class Solution: return sum(dfs(i, 1) for i in range(n)) ``` -### **Java** - ```java class Solution { private int n; @@ -143,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +178,6 @@ public: }; ``` -### **Go** - ```go func oddEvenJumps(arr []int) (ans int) { n := len(arr) @@ -226,10 +220,6 @@ func oddEvenJumps(arr []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0976.Largest Perimeter Triangle/README.md b/solution/0900-0999/0976.Largest Perimeter Triangle/README.md index bf67026832ef1..02e831e7c5a7a 100644 --- a/solution/0900-0999/0976.Largest Perimeter Triangle/README.md +++ b/solution/0900-0999/0976.Largest Perimeter Triangle/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:排序 + 贪心** +### 方法一:排序 + 贪心 > 三角形由三条边组成,且满足 C >= B && C >= A && C < A + B @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def largestPerimeter(self, nums: List[int]) -> int: @@ -72,10 +66,6 @@ class Solution: return 0 ``` -### **Java** - - - ```java class Solution { public int largestPerimeter(int[] nums) { @@ -91,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func largestPerimeter(nums []int) int { sort.Ints(nums) @@ -122,8 +108,6 @@ func largestPerimeter(nums []int) int { } ``` -### **TypeScript** - ```ts function largestPerimeter(nums: number[]): number { const n = nums.length; @@ -138,8 +122,6 @@ function largestPerimeter(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn largest_perimeter(mut nums: Vec) -> i32 { @@ -156,8 +138,6 @@ impl Solution { } ``` -### **C** - ```c int cmp(const void* a, const void* b) { return *(int*) b - *(int*) a; @@ -174,10 +154,6 @@ int largestPerimeter(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0976.Largest Perimeter Triangle/README_EN.md b/solution/0900-0999/0976.Largest Perimeter Triangle/README_EN.md index 5514360984761..d18ae3ec412e3 100644 --- a/solution/0900-0999/0976.Largest Perimeter Triangle/README_EN.md +++ b/solution/0900-0999/0976.Largest Perimeter Triangle/README_EN.md @@ -37,9 +37,9 @@ As we cannot use any three side lengths to form a triangle of non-zero area, we ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return 0 ``` -### **Java** - ```java class Solution { public int largestPerimeter(int[] nums) { @@ -68,8 +66,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -84,8 +80,6 @@ public: }; ``` -### **Go** - ```go func largestPerimeter(nums []int) int { sort.Ints(nums) @@ -99,8 +93,6 @@ func largestPerimeter(nums []int) int { } ``` -### **TypeScript** - ```ts function largestPerimeter(nums: number[]): number { const n = nums.length; @@ -115,8 +107,6 @@ function largestPerimeter(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn largest_perimeter(mut nums: Vec) -> i32 { @@ -133,8 +123,6 @@ impl Solution { } ``` -### **C** - ```c int cmp(const void* a, const void* b) { return *(int*) b - *(int*) a; @@ -151,10 +139,6 @@ int largestPerimeter(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0977.Squares of a Sorted Array/README.md b/solution/0900-0999/0977.Squares of a Sorted Array/README.md index 104e95f624293..d720df241eef6 100644 --- a/solution/0900-0999/0977.Squares of a Sorted Array/README.md +++ b/solution/0900-0999/0977.Squares of a Sorted Array/README.md @@ -48,49 +48,10 @@ ## 解法 - - -**暴力**: - -1. 遍历数组,并将元素修改为对应的平方值。 -2. 排序,返回。 - -_分析_: - -因为 `nums` 中存在负数,`-10` 与 `5` 转换为平方值之后,`-10` 反而要更大,因此需要额外进行一次排序。 - -**双指针**: - -该过程需要原数组保持不变动,对此声明一个等长数组存储计算结果,作为返回值。 - -声明头尾指针,并进行比较,哪方指针所指向元素的平方值更大,哪方平方值进入返回数组当中,并移动对应指针。重复比较过程,直到头指针超过尾指针。 - -由于是头尾指针,平方值获取过程是**从大到小**,对此存入数组的过程是**逆序**的。 - -```txt -SORTED-SQUARES(A) - n = A.length - i = 0 - j = n - 1 - k = n - 1 - let r[0..n]be a new array - while i < j - if A[i] * A[i] > A[j] * A[j] - r[k] = A[i] * A[i] - i += 1 - else - r[k] = A[j] * A[j] - j -= 1 - k -= 1 - return r -``` +### 方法一 -### **Python3** - - - ```python class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: @@ -108,10 +69,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int[] sortedSquares(int[] nums) { @@ -131,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +108,6 @@ public: }; ``` -### **Go** - ```go func sortedSquares(nums []int) []int { n := len(nums) @@ -173,31 +126,6 @@ func sortedSquares(nums []int) []int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var sortedSquares = function (nums) { - const n = nums.length; - const res = new Array(n); - for (let i = 0, j = n - 1, k = n - 1; i <= j; ) { - if (nums[i] * nums[i] > nums[j] * nums[j]) { - res[k--] = nums[i] * nums[i]; - ++i; - } else { - res[k--] = nums[j] * nums[j]; - --j; - } - } - return res; -}; -``` - -### **Rust** - ```rust impl Solution { pub fn sorted_squares(nums: Vec) -> Vec { @@ -221,7 +149,26 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var sortedSquares = function (nums) { + const n = nums.length; + const res = new Array(n); + for (let i = 0, j = n - 1, k = n - 1; i <= j; ) { + if (nums[i] * nums[i] > nums[j] * nums[j]) { + res[k--] = nums[i] * nums[i]; + ++i; + } else { + res[k--] = nums[j] * nums[j]; + --j; + } + } + return res; +}; +``` ```php class Solution { @@ -250,10 +197,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0977.Squares of a Sorted Array/README_EN.md b/solution/0900-0999/0977.Squares of a Sorted Array/README_EN.md index 6da87134087dc..abe2d82214950 100644 --- a/solution/0900-0999/0977.Squares of a Sorted Array/README_EN.md +++ b/solution/0900-0999/0977.Squares of a Sorted Array/README_EN.md @@ -37,9 +37,9 @@ After sorting, it becomes [0,1,9,16,100]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public int[] sortedSquares(int[] nums) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +97,6 @@ public: }; ``` -### **Go** - ```go func sortedSquares(nums []int) []int { n := len(nums) @@ -121,31 +115,6 @@ func sortedSquares(nums []int) []int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var sortedSquares = function (nums) { - const n = nums.length; - const res = new Array(n); - for (let i = 0, j = n - 1, k = n - 1; i <= j; ) { - if (nums[i] * nums[i] > nums[j] * nums[j]) { - res[k--] = nums[i] * nums[i]; - ++i; - } else { - res[k--] = nums[j] * nums[j]; - --j; - } - } - return res; -}; -``` - -### **Rust** - ```rust impl Solution { pub fn sorted_squares(nums: Vec) -> Vec { @@ -169,7 +138,26 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var sortedSquares = function (nums) { + const n = nums.length; + const res = new Array(n); + for (let i = 0, j = n - 1, k = n - 1; i <= j; ) { + if (nums[i] * nums[i] > nums[j] * nums[j]) { + res[k--] = nums[i] * nums[i]; + ++i; + } else { + res[k--] = nums[j] * nums[j]; + --j; + } + } + return res; +}; +``` ```php class Solution { @@ -198,10 +186,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0978.Longest Turbulent Subarray/README.md b/solution/0900-0999/0978.Longest Turbulent Subarray/README.md index 75fa8effb5422..ff52e832525d9 100644 --- a/solution/0900-0999/0978.Longest Turbulent Subarray/README.md +++ b/solution/0900-0999/0978.Longest Turbulent Subarray/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示以 $nums[i]$ 结尾且结尾处于上升状态的最长湍流子数组的长度,定义 $g[i]$ 表示以 $nums[i]$ 结尾且结尾处于下降状态的最长湍流子数组的长度。初始时 $f[0] = 1$, $g[0] = 1$。答案为 $max(f[i], g[i])$。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxTurbulenceSize(int[] arr) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func maxTurbulenceSize(arr []int) int { ans, f, g := 1, 1, 1 @@ -150,8 +136,6 @@ func maxTurbulenceSize(arr []int) int { } ``` -### **TypeScript** - ```ts function maxTurbulenceSize(arr: number[]): number { let f = 1; @@ -168,10 +152,6 @@ function maxTurbulenceSize(arr: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0978.Longest Turbulent Subarray/README_EN.md b/solution/0900-0999/0978.Longest Turbulent Subarray/README_EN.md index d25e4f219b56d..e650fdf9217ac 100644 --- a/solution/0900-0999/0978.Longest Turbulent Subarray/README_EN.md +++ b/solution/0900-0999/0978.Longest Turbulent Subarray/README_EN.md @@ -58,9 +58,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxTurbulenceSize(int[] arr) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +107,6 @@ public: }; ``` -### **Go** - ```go func maxTurbulenceSize(arr []int) int { ans, f, g := 1, 1, 1 @@ -131,8 +125,6 @@ func maxTurbulenceSize(arr []int) int { } ``` -### **TypeScript** - ```ts function maxTurbulenceSize(arr: number[]): number { let f = 1; @@ -149,10 +141,6 @@ function maxTurbulenceSize(arr: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0979.Distribute Coins in Binary Tree/README.md b/solution/0900-0999/0979.Distribute Coins in Binary Tree/README.md index 28e0d7af02787..9d0803f8148a4 100644 --- a/solution/0900-0999/0979.Distribute Coins in Binary Tree/README.md +++ b/solution/0900-0999/0979.Distribute Coins in Binary Tree/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们定义一个函数 $dfs(node)$,表示以 $node$ 为根节点的子树中,金币的超载量,即金币的数量减去节点数。如果 $dfs(node)$ 为正数,表示该子树中金币的数量多于节点数,需要将多余的金币移出该子树;如果 $dfs(node)$ 为负数,表示该子树中金币的数量少于节点数,需要将不足的金币移入该子树。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -189,8 +175,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -222,10 +206,6 @@ function distributeCoins(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0979.Distribute Coins in Binary Tree/README_EN.md b/solution/0900-0999/0979.Distribute Coins in Binary Tree/README_EN.md index 2cf8dc63e9ae3..b09273be60ee1 100644 --- a/solution/0900-0999/0979.Distribute Coins in Binary Tree/README_EN.md +++ b/solution/0900-0999/0979.Distribute Coins in Binary Tree/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -65,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -103,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -136,8 +132,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -169,8 +163,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -202,10 +194,6 @@ function distributeCoins(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0980.Unique Paths III/README.md b/solution/0900-0999/0980.Unique Paths III/README.md index fae967835b062..583370172c96d 100644 --- a/solution/0900-0999/0980.Unique Paths III/README.md +++ b/solution/0900-0999/0980.Unique Paths III/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:回溯** +### 方法一:回溯 我们可以先遍历整个网格,找出起点 $(x, y)$,并且统计空白格的数量 $cnt$。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def uniquePathsIII(self, grid: List[List[int]]) -> int: @@ -103,10 +97,6 @@ class Solution: return dfs(*start, 0) ``` -### **Java** - - - ```java class Solution { private int m; @@ -154,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -198,8 +186,6 @@ public: }; ``` -### **Go** - ```go func uniquePathsIII(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -241,8 +227,6 @@ func uniquePathsIII(grid [][]int) int { } ``` -### **TypeScript** - ```ts function uniquePathsIII(grid: number[][]): number { const m = grid.length; @@ -282,10 +266,6 @@ function uniquePathsIII(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0980.Unique Paths III/README_EN.md b/solution/0900-0999/0980.Unique Paths III/README_EN.md index e66ed7d927eb1..898a4f966de43 100644 --- a/solution/0900-0999/0980.Unique Paths III/README_EN.md +++ b/solution/0900-0999/0980.Unique Paths III/README_EN.md @@ -61,7 +61,7 @@ Note that the starting and ending square can be anywhere in the grid. ## Solutions -**Solution 1: Backtracking** +### Solution 1: Backtracking We can first traverse the entire grid, find the starting point $(x, y)$, and count the number of blank spaces $cnt$. @@ -77,8 +77,6 @@ The time complexity is $O(3^{m \times n})$, and the space complexity is $O(m \ti -### **Python3** - ```python class Solution: def uniquePathsIII(self, grid: List[List[int]]) -> int: @@ -102,8 +100,6 @@ class Solution: return dfs(*start, 0) ``` -### **Java** - ```java class Solution { private int m; @@ -151,8 +147,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -195,8 +189,6 @@ public: }; ``` -### **Go** - ```go func uniquePathsIII(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -238,8 +230,6 @@ func uniquePathsIII(grid [][]int) int { } ``` -### **TypeScript** - ```ts function uniquePathsIII(grid: number[][]): number { const m = grid.length; @@ -279,10 +269,6 @@ function uniquePathsIII(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0981.Time Based Key-Value Store/README.md b/solution/0900-0999/0981.Time Based Key-Value Store/README.md index 14e1da48e14c7..bee3d7cc4f8c2 100644 --- a/solution/0900-0999/0981.Time Based Key-Value Store/README.md +++ b/solution/0900-0999/0981.Time Based Key-Value Store/README.md @@ -50,9 +50,7 @@ timeMap.get("foo", 5); // 返回 "bar2" ## 解法 - - -**方法一:哈希表 + 有序集合(或二分查找)** +### 方法一:哈希表 + 有序集合(或二分查找) 我们可以用哈希表 $ktv$ 记录键值对,其中键为字符串 $key$,值为一个列表,列表中的每个元素为一个二元组 $(timestamp, value)$,表示键 $key$ 在时间戳 $timestamp$ 时对应的值为 $value$。 @@ -62,10 +60,6 @@ timeMap.get("foo", 5); // 返回 "bar2" -### **Python3** - - - ```python class TimeMap: def __init__(self): @@ -88,10 +82,6 @@ class TimeMap: # param_2 = obj.get(key,timestamp) ``` -### **Java** - - - ```java class TimeMap { private Map> ktv = new HashMap<>(); @@ -121,8 +111,6 @@ class TimeMap { */ ``` -### **C++** - ```cpp class TimeMap { public: @@ -152,8 +140,6 @@ private: */ ``` -### **Go** - ```go type TimeMap struct { ktv map[string][]pair @@ -189,10 +175,6 @@ type pair struct { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0981.Time Based Key-Value Store/README_EN.md b/solution/0900-0999/0981.Time Based Key-Value Store/README_EN.md index fa76240867c6d..832069bd76dea 100644 --- a/solution/0900-0999/0981.Time Based Key-Value Store/README_EN.md +++ b/solution/0900-0999/0981.Time Based Key-Value Store/README_EN.md @@ -47,9 +47,9 @@ timeMap.get("foo", 5); // return "bar2" ## Solutions - +### Solution 1 -### **Python3** + ```python class TimeMap: @@ -73,8 +73,6 @@ class TimeMap: # param_2 = obj.get(key,timestamp) ``` -### **Java** - ```java class TimeMap { private Map> ktv = new HashMap<>(); @@ -104,8 +102,6 @@ class TimeMap { */ ``` -### **C++** - ```cpp class TimeMap { public: @@ -135,8 +131,6 @@ private: */ ``` -### **Go** - ```go type TimeMap struct { ktv map[string][]pair @@ -172,10 +166,6 @@ type pair struct { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0982.Triples with Bitwise AND Equal To Zero/README.md b/solution/0900-0999/0982.Triples with Bitwise AND Equal To Zero/README.md index e11ebac20bf43..6efcfbb2a7c32 100644 --- a/solution/0900-0999/0982.Triples with Bitwise AND Equal To Zero/README.md +++ b/solution/0900-0999/0982.Triples with Bitwise AND Equal To Zero/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:枚举 + 计数** +### 方法一:枚举 + 计数 我们可以先枚举任意两个数 $x$ 和 $y$,用哈希表或数组 $cnt$ 统计它们的按位与结果 $x \& y$ 出现的次数。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def countTriplets(self, nums: List[int]) -> int: @@ -81,10 +75,6 @@ class Solution: return sum(v for xy, v in cnt.items() for z in nums if xy & z == 0) ``` -### **Java** - - - ```java class Solution { public int countTriplets(int[] nums) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func countTriplets(nums []int) (ans int) { mx := slices.Max(nums) @@ -160,8 +146,6 @@ func countTriplets(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function countTriplets(nums: number[]): number { const mx = Math.max(...nums); @@ -183,10 +167,6 @@ function countTriplets(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0982.Triples with Bitwise AND Equal To Zero/README_EN.md b/solution/0900-0999/0982.Triples with Bitwise AND Equal To Zero/README_EN.md index 65b7af5c1cfb3..1532ad9da8b97 100644 --- a/solution/0900-0999/0982.Triples with Bitwise AND Equal To Zero/README_EN.md +++ b/solution/0900-0999/0982.Triples with Bitwise AND Equal To Zero/README_EN.md @@ -53,9 +53,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return sum(v for xy, v in cnt.items() for z in nums if xy & z == 0) ``` -### **Java** - ```java class Solution { public int countTriplets(int[] nums) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +115,6 @@ public: }; ``` -### **Go** - ```go func countTriplets(nums []int) (ans int) { mx := slices.Max(nums) @@ -141,8 +135,6 @@ func countTriplets(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function countTriplets(nums: number[]): number { const mx = Math.max(...nums); @@ -164,10 +156,6 @@ function countTriplets(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0983.Minimum Cost For Tickets/README.md b/solution/0900-0999/0983.Minimum Cost For Tickets/README.md index 3fd2e379b12e5..207580002c7f8 100644 --- a/solution/0900-0999/0983.Minimum Cost For Tickets/README.md +++ b/solution/0900-0999/0983.Minimum Cost For Tickets/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:记忆化搜索 + 二分查找** +### 方法一:记忆化搜索 + 二分查找 定义 $dfs(i)$ 表示从第 $i$ 次出行开始的最低消费。答案为 $dfs(0)$。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def mincostTickets(self, days: List[int], costs: List[int]) -> int: @@ -93,10 +87,6 @@ class Solution: return dfs(0) ``` -### **Java** - - - ```java class Solution { private static final int[] T = new int[] {1, 7, 30}; @@ -146,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -179,8 +167,6 @@ public: }; ``` -### **Go** - ```go func mincostTickets(days []int, costs []int) int { t := []int{1, 7, 30} @@ -222,8 +208,6 @@ func lowerBound(arr []int, x int) int { } ``` -### **TypeScript** - ```ts function mincostTickets(days: number[], costs: number[]): number { const n = days.length, @@ -240,10 +224,6 @@ function mincostTickets(days: number[], costs: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0983.Minimum Cost For Tickets/README_EN.md b/solution/0900-0999/0983.Minimum Cost For Tickets/README_EN.md index 99351cb4a0d58..e08426c400393 100644 --- a/solution/0900-0999/0983.Minimum Cost For Tickets/README_EN.md +++ b/solution/0900-0999/0983.Minimum Cost For Tickets/README_EN.md @@ -59,9 +59,9 @@ In total, you spent 17 and covered all the days of your travel. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,8 +79,6 @@ class Solution: return dfs(0) ``` -### **Java** - ```java class Solution { private static final int[] T = new int[] {1, 7, 30}; @@ -130,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +159,6 @@ public: }; ``` -### **Go** - ```go func mincostTickets(days []int, costs []int) int { t := []int{1, 7, 30} @@ -206,8 +200,6 @@ func lowerBound(arr []int, x int) int { } ``` -### **TypeScript** - ```ts function mincostTickets(days: number[], costs: number[]): number { const n = days.length, @@ -224,10 +216,6 @@ function mincostTickets(days: number[], costs: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0984.String Without AAA or BBB/README.md b/solution/0900-0999/0984.String Without AAA or BBB/README.md index 5471ddaf1ed94..f60f055ff840a 100644 --- a/solution/0900-0999/0984.String Without AAA or BBB/README.md +++ b/solution/0900-0999/0984.String Without AAA or BBB/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:贪心 + 构造** +### 方法一:贪心 + 构造 循环构造字符串,当 $a$ 和 $b$ 都大于 `0` 时: @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def strWithout3a3b(self, a: int, b: int) -> str: @@ -83,10 +77,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String strWithout3a3b(int a, int b) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func strWithout3a3b(a int, b int) string { var ans strings.Builder @@ -176,10 +162,6 @@ func strWithout3a3b(a int, b int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0984.String Without AAA or BBB/README_EN.md b/solution/0900-0999/0984.String Without AAA or BBB/README_EN.md index 6d50d1d8481c4..78c8d64c33e3f 100644 --- a/solution/0900-0999/0984.String Without AAA or BBB/README_EN.md +++ b/solution/0900-0999/0984.String Without AAA or BBB/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String strWithout3a3b(int a, int b) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +120,6 @@ public: }; ``` -### **Go** - ```go func strWithout3a3b(a int, b int) string { var ans strings.Builder @@ -154,10 +148,6 @@ func strWithout3a3b(a int, b int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0985.Sum of Even Numbers After Queries/README.md b/solution/0900-0999/0985.Sum of Even Numbers After Queries/README.md index 7bc162c66329b..b173373fd3a39 100644 --- a/solution/0900-0999/0985.Sum of Even Numbers After Queries/README.md +++ b/solution/0900-0999/0985.Sum of Even Numbers After Queries/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们用一个变量 $s$ 记录数组 $nums$ 中所有偶数的和。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def sumEvenAfterQueries( @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] sumEvenAfterQueries(int[] nums, int[][] queries) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func sumEvenAfterQueries(nums []int, queries [][]int) (ans []int) { s := 0 @@ -165,22 +151,15 @@ func sumEvenAfterQueries(nums []int, queries [][]int) (ans []int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number[][]} queries - * @return {number[]} - */ -var sumEvenAfterQueries = function (nums, queries) { +```ts +function sumEvenAfterQueries(nums: number[], queries: number[][]): number[] { let s = 0; for (const x of nums) { if (x % 2 === 0) { s += x; } } - const ans = []; + const ans: number[] = []; for (const [v, i] of queries) { if (nums[i] % 2 === 0) { s -= nums[i]; @@ -192,20 +171,23 @@ var sumEvenAfterQueries = function (nums, queries) { ans.push(s); } return ans; -}; +} ``` -### **TypeScript** - -```ts -function sumEvenAfterQueries(nums: number[], queries: number[][]): number[] { +```js +/** + * @param {number[]} nums + * @param {number[][]} queries + * @return {number[]} + */ +var sumEvenAfterQueries = function (nums, queries) { let s = 0; for (const x of nums) { if (x % 2 === 0) { s += x; } } - const ans: number[] = []; + const ans = []; for (const [v, i] of queries) { if (nums[i] % 2 === 0) { s -= nums[i]; @@ -217,13 +199,9 @@ function sumEvenAfterQueries(nums: number[], queries: number[][]): number[] { ans.push(s); } return ans; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0900-0999/0985.Sum of Even Numbers After Queries/README_EN.md b/solution/0900-0999/0985.Sum of Even Numbers After Queries/README_EN.md index af572aeda288b..17ffeabc3f984 100644 --- a/solution/0900-0999/0985.Sum of Even Numbers After Queries/README_EN.md +++ b/solution/0900-0999/0985.Sum of Even Numbers After Queries/README_EN.md @@ -43,9 +43,9 @@ After adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] sumEvenAfterQueries(int[] nums, int[][] queries) { @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func sumEvenAfterQueries(nums []int, queries [][]int) (ans []int) { s := 0 @@ -148,22 +142,15 @@ func sumEvenAfterQueries(nums []int, queries [][]int) (ans []int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number[][]} queries - * @return {number[]} - */ -var sumEvenAfterQueries = function (nums, queries) { +```ts +function sumEvenAfterQueries(nums: number[], queries: number[][]): number[] { let s = 0; for (const x of nums) { if (x % 2 === 0) { s += x; } } - const ans = []; + const ans: number[] = []; for (const [v, i] of queries) { if (nums[i] % 2 === 0) { s -= nums[i]; @@ -175,20 +162,23 @@ var sumEvenAfterQueries = function (nums, queries) { ans.push(s); } return ans; -}; +} ``` -### **TypeScript** - -```ts -function sumEvenAfterQueries(nums: number[], queries: number[][]): number[] { +```js +/** + * @param {number[]} nums + * @param {number[][]} queries + * @return {number[]} + */ +var sumEvenAfterQueries = function (nums, queries) { let s = 0; for (const x of nums) { if (x % 2 === 0) { s += x; } } - const ans: number[] = []; + const ans = []; for (const [v, i] of queries) { if (nums[i] % 2 === 0) { s -= nums[i]; @@ -200,13 +190,9 @@ function sumEvenAfterQueries(nums: number[], queries: number[][]): number[] { ans.push(s); } return ans; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/0900-0999/0986.Interval List Intersections/README.md b/solution/0900-0999/0986.Interval List Intersections/README.md index c3d617d67a9fa..39b6c7efbf87c 100644 --- a/solution/0900-0999/0986.Interval List Intersections/README.md +++ b/solution/0900-0999/0986.Interval List Intersections/README.md @@ -59,16 +59,10 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 -### **Python3** - - - ```python class Solution: def intervalIntersection( @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] intervalIntersection(int[][] firstList, int[][] secondList) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func intervalIntersection(firstList [][]int, secondList [][]int) [][]int { m, n := len(firstList), len(secondList) @@ -158,8 +144,6 @@ func intervalIntersection(firstList [][]int, secondList [][]int) [][]int { } ``` -### **TypeScript** - ```ts function intervalIntersection(firstList: number[][], secondList: number[][]): number[][] { const n = firstList.length; @@ -183,8 +167,6 @@ function intervalIntersection(firstList: number[][], secondList: number[][]): nu } ``` -### **Rust** - ```rust impl Solution { pub fn interval_intersection( @@ -212,10 +194,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0986.Interval List Intersections/README_EN.md b/solution/0900-0999/0986.Interval List Intersections/README_EN.md index 2526fa3f8ea49..5a41887aee864 100644 --- a/solution/0900-0999/0986.Interval List Intersections/README_EN.md +++ b/solution/0900-0999/0986.Interval List Intersections/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] intervalIntersection(int[][] firstList, int[][] secondList) { @@ -88,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +106,6 @@ public: }; ``` -### **Go** - ```go func intervalIntersection(firstList [][]int, secondList [][]int) [][]int { m, n := len(firstList), len(secondList) @@ -132,8 +126,6 @@ func intervalIntersection(firstList [][]int, secondList [][]int) [][]int { } ``` -### **TypeScript** - ```ts function intervalIntersection(firstList: number[][], secondList: number[][]): number[][] { const n = firstList.length; @@ -157,8 +149,6 @@ function intervalIntersection(firstList: number[][], secondList: number[][]): nu } ``` -### **Rust** - ```rust impl Solution { pub fn interval_intersection( @@ -186,10 +176,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/README.md b/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/README.md index d126909724afd..33ecf0c1297d3 100644 --- a/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/README.md +++ b/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/README.md @@ -62,14 +62,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -99,10 +95,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> verticalTraversal(TreeNode root) { @@ -139,8 +131,6 @@ class Solution { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -194,10 +184,6 @@ function dfs(root: TreeNode | null, depth: number, idx: number, solution: Array< } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/README_EN.md b/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/README_EN.md index 68fe225dc6431..be045600da6c6 100644 --- a/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/README_EN.md +++ b/solution/0900-0999/0987.Vertical Order Traversal of a Binary Tree/README_EN.md @@ -59,9 +59,9 @@ Note that the solution remains the same since 5 and 6 are in the same location a ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -92,8 +92,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List> verticalTraversal(TreeNode root) { @@ -130,8 +128,6 @@ class Solution { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -150,6 +146,7 @@ class Solution { function verticalTraversal(root: TreeNode | null): number[][] { let solution = []; dfs(root, 0, 0, solution); + // 优先依据i=2排序, 然后依据i=1排序 solution.sort(compare); let ans = []; let pre = Number.MIN_SAFE_INTEGER; @@ -184,10 +181,6 @@ function dfs(root: TreeNode | null, depth: number, idx: number, solution: Array< } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0988.Smallest String Starting From Leaf/README.md b/solution/0900-0999/0988.Smallest String Starting From Leaf/README.md index 88ccc691de0c8..979af87c3fd9b 100644 --- a/solution/0900-0999/0988.Smallest String Starting From Leaf/README.md +++ b/solution/0900-0999/0988.Smallest String Starting From Leaf/README.md @@ -63,35 +63,10 @@ ## 解法 - - -本题不能用这种以下这种方式实现: - -```python -class Solution: - def smallestFromLeaf(self, root: TreeNode) -> str: - if root is None: - return '' - left = self.smallestFromLeaf(root.left) - right = self.smallestFromLeaf(root.right) - val = chr(ord('a') + root.val) - return min(left + val, right + val) -``` - -

- -我们举个例子来说明,对于上面这棵二叉树,正确答案应该是 "ababz",但是我们采用以上实现方式得到的答案是 "abz"。 - -问题就在于,当 `str(x) < str(y)`,并不能保证 `str(x) + a < str(y) + a`,例如 `"ab" < "abab"`,但是 `"abz" > "ababz"`。 - -本题可以用 DFS 解决,每次到达一个叶子节点时,翻转此路径上的字符串,并与 ans 比较大小,取二者较小值。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -117,10 +92,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -166,8 +137,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -205,8 +174,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -239,10 +206,6 @@ func smallestFromLeaf(root *TreeNode) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0988.Smallest String Starting From Leaf/README_EN.md b/solution/0900-0999/0988.Smallest String Starting From Leaf/README_EN.md index dc386d5598376..d35cf20c15c66 100644 --- a/solution/0900-0999/0988.Smallest String Starting From Leaf/README_EN.md +++ b/solution/0900-0999/0988.Smallest String Starting From Leaf/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -77,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -124,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -163,8 +159,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -197,10 +191,6 @@ func smallestFromLeaf(root *TreeNode) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0989.Add to Array-Form of Integer/README.md b/solution/0900-0999/0989.Add to Array-Form of Integer/README.md index b34a63600da93..5c0724288bd7d 100644 --- a/solution/0900-0999/0989.Add to Array-Form of Integer/README.md +++ b/solution/0900-0999/0989.Add to Array-Form of Integer/README.md @@ -56,16 +56,10 @@ ## 解法 - - -数组从尾到头遍历,分别与 `k` 中的每一位相加,进位保存在 `carry` 中,不进位和则添加到结果列表中。最后逆序结果列表即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: @@ -80,10 +74,6 @@ class Solution: return ans[::-1] ``` -### **Java** - - - ```java class Solution { public List addToArrayForm(int[] num, int k) { @@ -100,7 +90,43 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + vector addToArrayForm(vector& num, int k) { + int i = num.size() - 1, carry = 0; + vector ans; + for (; i >= 0 || k || carry; --i) { + carry += (i < 0 ? 0 : num[i]) + k % 10; + ans.push_back(carry % 10); + carry /= 10; + k /= 10; + } + reverse(ans.begin(), ans.end()); + return ans; + } +}; +``` + +```go +func addToArrayForm(num []int, k int) []int { + i, carry := len(num)-1, 0 + ans := []int{} + for ; i >= 0 || k > 0 || carry > 0; i-- { + if i >= 0 { + carry += num[i] + } + carry += k % 10 + ans = append(ans, carry%10) + carry /= 10 + k /= 10 + } + for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 { + ans[i], ans[j] = ans[j], ans[i] + } + return ans +} +``` ```ts function addToArrayForm(num: number[], k: number): number[] { @@ -118,24 +144,6 @@ function addToArrayForm(num: number[], k: number): number[] { } ``` -```ts -function addToArrayForm(num: number[], k: number): number[] { - const n = num.length; - const res = []; - let sum = 0; - for (let i = 0; i < n || sum !== 0 || k !== 0; i++) { - sum += num[n - i - 1] ?? 0; - sum += k % 10; - res.push(sum % 10); - k = Math.floor(k / 10); - sum = Math.floor(sum / 10); - } - return res.reverse(); -} -``` - -### **Rust** - ```rust impl Solution { pub fn add_to_array_form(num: Vec, mut k: i32) -> Vec { @@ -158,52 +166,28 @@ impl Solution { } ``` -### **C++** + -```cpp -class Solution { -public: - vector addToArrayForm(vector& num, int k) { - int i = num.size() - 1, carry = 0; - vector ans; - for (; i >= 0 || k || carry; --i) { - carry += (i < 0 ? 0 : num[i]) + k % 10; - ans.push_back(carry % 10); - carry /= 10; - k /= 10; - } - reverse(ans.begin(), ans.end()); - return ans; - } -}; -``` +### 方法二 -### **Go** + -```go -func addToArrayForm(num []int, k int) []int { - i, carry := len(num)-1, 0 - ans := []int{} - for ; i >= 0 || k > 0 || carry > 0; i-- { - if i >= 0 { - carry += num[i] - } - carry += k % 10 - ans = append(ans, carry%10) - carry /= 10 - k /= 10 - } - for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 { - ans[i], ans[j] = ans[j], ans[i] - } - return ans +```ts +function addToArrayForm(num: number[], k: number): number[] { + const n = num.length; + const res = []; + let sum = 0; + for (let i = 0; i < n || sum !== 0 || k !== 0; i++) { + sum += num[n - i - 1] ?? 0; + sum += k % 10; + res.push(sum % 10); + k = Math.floor(k / 10); + sum = Math.floor(sum / 10); + } + return res.reverse(); } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0989.Add to Array-Form of Integer/README_EN.md b/solution/0900-0999/0989.Add to Array-Form of Integer/README_EN.md index dd60bfa4ad0b6..d70727b5d171b 100644 --- a/solution/0900-0999/0989.Add to Array-Form of Integer/README_EN.md +++ b/solution/0900-0999/0989.Add to Array-Form of Integer/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return ans[::-1] ``` -### **Java** - ```java class Solution { public List addToArrayForm(int[] num, int k) { @@ -85,7 +83,43 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + vector addToArrayForm(vector& num, int k) { + int i = num.size() - 1, carry = 0; + vector ans; + for (; i >= 0 || k || carry; --i) { + carry += (i < 0 ? 0 : num[i]) + k % 10; + ans.push_back(carry % 10); + carry /= 10; + k /= 10; + } + reverse(ans.begin(), ans.end()); + return ans; + } +}; +``` + +```go +func addToArrayForm(num []int, k int) []int { + i, carry := len(num)-1, 0 + ans := []int{} + for ; i >= 0 || k > 0 || carry > 0; i-- { + if i >= 0 { + carry += num[i] + } + carry += k % 10 + ans = append(ans, carry%10) + carry /= 10 + k /= 10 + } + for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 { + ans[i], ans[j] = ans[j], ans[i] + } + return ans +} +``` ```ts function addToArrayForm(num: number[], k: number): number[] { @@ -103,24 +137,6 @@ function addToArrayForm(num: number[], k: number): number[] { } ``` -```ts -function addToArrayForm(num: number[], k: number): number[] { - const n = num.length; - const res = []; - let sum = 0; - for (let i = 0; i < n || sum !== 0 || k !== 0; i++) { - sum += num[n - i - 1] ?? 0; - sum += k % 10; - res.push(sum % 10); - k = Math.floor(k / 10); - sum = Math.floor(sum / 10); - } - return res.reverse(); -} -``` - -### **Rust** - ```rust impl Solution { pub fn add_to_array_form(num: Vec, mut k: i32) -> Vec { @@ -143,52 +159,28 @@ impl Solution { } ``` -### **C++** + -```cpp -class Solution { -public: - vector addToArrayForm(vector& num, int k) { - int i = num.size() - 1, carry = 0; - vector ans; - for (; i >= 0 || k || carry; --i) { - carry += (i < 0 ? 0 : num[i]) + k % 10; - ans.push_back(carry % 10); - carry /= 10; - k /= 10; - } - reverse(ans.begin(), ans.end()); - return ans; - } -}; -``` +### Solution 2 -### **Go** + -```go -func addToArrayForm(num []int, k int) []int { - i, carry := len(num)-1, 0 - ans := []int{} - for ; i >= 0 || k > 0 || carry > 0; i-- { - if i >= 0 { - carry += num[i] - } - carry += k % 10 - ans = append(ans, carry%10) - carry /= 10 - k /= 10 - } - for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 { - ans[i], ans[j] = ans[j], ans[i] - } - return ans +```ts +function addToArrayForm(num: number[], k: number): number[] { + const n = num.length; + const res = []; + let sum = 0; + for (let i = 0; i < n || sum !== 0 || k !== 0; i++) { + sum += num[n - i - 1] ?? 0; + sum += k % 10; + res.push(sum % 10); + k = Math.floor(k / 10); + sum = Math.floor(sum / 10); + } + return res.reverse(); } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0990.Satisfiability of Equality Equations/README.md b/solution/0900-0999/0990.Satisfiability of Equality Equations/README.md index bab6f3837c2d6..c376f61c3a7b5 100644 --- a/solution/0900-0999/0990.Satisfiability of Equality Equations/README.md +++ b/solution/0900-0999/0990.Satisfiability of Equality Equations/README.md @@ -61,81 +61,10 @@ ## 解法 - - -并查集。对于本题,先遍历所有的等式,构造并查集。接着遍历所有不等式,如果不等式的两个变量处于同一个集合,说明发生矛盾,返回 false。否则遍历结束返回 true。 - -以下是并查集的几个常用模板。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` +### 方法一 -### **Python3** - - - ```python class Solution: def equationsPossible(self, equations: List[str]) -> bool: @@ -156,10 +85,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -193,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -221,8 +144,6 @@ public: }; ``` -### **Go** - ```go func equationsPossible(equations []string) bool { p := make([]int, 26) @@ -252,8 +173,6 @@ func equationsPossible(equations []string) bool { } ``` -### **TypeScript** - ```ts class UnionFind { private parent: number[]; @@ -297,10 +216,6 @@ function equationsPossible(equations: string[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0990.Satisfiability of Equality Equations/README_EN.md b/solution/0900-0999/0990.Satisfiability of Equality Equations/README_EN.md index 2db2f4983a0ba..2d90ec68b8ebd 100644 --- a/solution/0900-0999/0990.Satisfiability of Equality Equations/README_EN.md +++ b/solution/0900-0999/0990.Satisfiability of Equality Equations/README_EN.md @@ -40,12 +40,10 @@ There is no way to assign the variables to satisfy both equations. ## Solutions -Union find. +### Solution 1 -### **Python3** - ```python class Solution: def equationsPossible(self, equations: List[str]) -> bool: @@ -66,8 +64,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { private int[] p; @@ -101,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +123,6 @@ public: }; ``` -### **Go** - ```go func equationsPossible(equations []string) bool { p := make([]int, 26) @@ -160,8 +152,6 @@ func equationsPossible(equations []string) bool { } ``` -### **TypeScript** - ```ts class UnionFind { private parent: number[]; @@ -205,10 +195,6 @@ function equationsPossible(equations: string[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0991.Broken Calculator/README.md b/solution/0900-0999/0991.Broken Calculator/README.md index c9f0467d4c1a2..1dd00a48f8fc4 100644 --- a/solution/0900-0999/0991.Broken Calculator/README.md +++ b/solution/0900-0999/0991.Broken Calculator/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:逆向计算** +### 方法一:逆向计算 我们可以采用逆向计算的方式,从 `target` 开始,如果 `target` 是奇数,则 `target++`,否则 `target >>= 1`,累加操作次数,直到 `target` 小于等于 `startValue`,此时的操作次数加上 `startValue - target` 即为最终结果。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def brokenCalc(self, startValue: int, target: int) -> int: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int brokenCalc(int startValue, int target) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func brokenCalc(startValue int, target int) (ans int) { for startValue < target { @@ -139,10 +125,6 @@ func brokenCalc(startValue int, target int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0991.Broken Calculator/README_EN.md b/solution/0900-0999/0991.Broken Calculator/README_EN.md index a9e82e8d2b2ac..ef13b23445088 100644 --- a/solution/0900-0999/0991.Broken Calculator/README_EN.md +++ b/solution/0900-0999/0991.Broken Calculator/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int brokenCalc(int startValue, int target) { @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +102,6 @@ public: }; ``` -### **Go** - ```go func brokenCalc(startValue int, target int) (ans int) { for startValue < target { @@ -123,10 +117,6 @@ func brokenCalc(startValue int, target int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0992.Subarrays with K Different Integers/README.md b/solution/0900-0999/0992.Subarrays with K Different Integers/README.md index c710af79f8bbb..1c5d806e93c85 100644 --- a/solution/0900-0999/0992.Subarrays with K Different Integers/README.md +++ b/solution/0900-0999/0992.Subarrays with K Different Integers/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们遍历数组 $nums$,对于每个 $i$,我们需要找到最小的 $j_1$,使得 $nums[j_1], nums[j_1 + 1], \dots, nums[i]$ 中不同的整数个数小于等于 $k$,以及最小的 $j_2$,使得 $nums[j_2], nums[j_2 + 1], \dots, nums[i]$ 中不同的整数个数小于等于 $k-1$。那么 $j_2 - j_1$ 就是以 $i$ 结尾的满足条件的子数组的个数。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def subarraysWithKDistinct(self, nums: List[int], k: int) -> int: @@ -83,10 +77,6 @@ class Solution: return sum(a - b for a, b in zip(f(k - 1), f(k))) ``` -### **Java** - - - ```java class Solution { public int subarraysWithKDistinct(int[] nums, int k) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func subarraysWithKDistinct(nums []int, k int) (ans int) { f := func(k int) []int { @@ -189,10 +175,6 @@ func subarraysWithKDistinct(nums []int, k int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0992.Subarrays with K Different Integers/README_EN.md b/solution/0900-0999/0992.Subarrays with K Different Integers/README_EN.md index e0219f41cd752..7e3803f383ad2 100644 --- a/solution/0900-0999/0992.Subarrays with K Different Integers/README_EN.md +++ b/solution/0900-0999/0992.Subarrays with K Different Integers/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return sum(a - b for a, b in zip(f(k - 1), f(k))) ``` -### **Java** - ```java class Solution { public int subarraysWithKDistinct(int[] nums, int k) { @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +133,6 @@ public: }; ``` -### **Go** - ```go func subarraysWithKDistinct(nums []int, k int) (ans int) { f := func(k int) []int { @@ -169,10 +163,6 @@ func subarraysWithKDistinct(nums []int, k int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0993.Cousins in Binary Tree/README.md b/solution/0900-0999/0993.Cousins in Binary Tree/README.md index 3f9a0c360d3aa..9ac4faa5d54d5 100644 --- a/solution/0900-0999/0993.Cousins in Binary Tree/README.md +++ b/solution/0900-0999/0993.Cousins in Binary Tree/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们定义一个队列 $q$,队列中存储的是节点和其父节点。初始时,将根节点和空节点放入队列中。 @@ -65,24 +63,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。 -**方法二:DFS** - -我们设计一个函数 $dfs(root, fa, d)$,表示从根节点 $root$ 出发,其父节点为 $fa$,深度为 $d$,进行深度优先搜索。 - -在函数中,我们首先判断当前节点是否为空,如果为空,则直接返回。如果当前节点的值为 $x$ 或 $y$,则记录该节点的父节点和深度。然后对当前节点的左右子节点分别调用函数 $dfs$,其中父节点为当前节点,深度为当前深度加 $1$。即 $dfs(root.left, root, d + 1)$ 和 $dfs(root.right, root, d + 1)$。 - -当整棵二叉树遍历完毕后,如果 $x$ 和 $y$ 的深度相同且父节点不同,则返回 $true$,否则返回 $false$。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。 - -### **Python3** - - - -BFS: - ```python # Definition for a binary tree node. # class TreeNode: @@ -111,38 +93,6 @@ class Solution: return p1 != p2 and d1 == d2 ``` -DFS: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool: - def dfs(root, fa, d): - if root is None: - return - if root.val == x: - t[0] = (fa, d) - if root.val == y: - t[1] = (fa, d) - dfs(root.left, root, d + 1) - dfs(root.right, root, d + 1) - - t = [None, None] - dfs(root, None, 0) - return t[0][0] != t[1][0] and t[0][1] == t[1][1] -``` - -### **Java** - - - -BFS: - ```java /** * Definition for a binary tree node. @@ -192,58 +142,6 @@ class Solution { } ``` -DFS: - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private int x, y; - private TreeNode p1, p2; - private int d1, d2; - - public boolean isCousins(TreeNode root, int x, int y) { - this.x = x; - this.y = y; - dfs(root, null, 0); - return p1 != p2 && d1 == d2; - } - - private void dfs(TreeNode root, TreeNode p, int d) { - if (root == null) { - return; - } - if (root.val == x) { - p1 = p; - d1 = d; - } - if (root.val == y) { - p2 = p; - d2 = d; - } - dfs(root.left, root, d + 1); - dfs(root.right, root, d + 1); - } -} -``` - -### **C++** - -BFS: - ```cpp /** * Definition for a binary tree node. @@ -291,50 +189,6 @@ public: }; ``` -DFS: - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool isCousins(TreeNode* root, int x, int y) { - TreeNode *p1, *p2; - int d1, d2; - function dfs = [&](TreeNode* root, TreeNode* fa, int d) { - if (!root) { - return; - } - if (root->val == x) { - p1 = fa; - d1 = d; - } - if (root->val == y) { - p2 = fa; - d2 = d; - } - dfs(root->left, root, d + 1); - dfs(root->right, root, d + 1); - }; - dfs(root, nullptr, 0); - return p1 != p2 && d1 == d2; - } -}; -``` - -### **Go** - -BFS: - ```go /** * Definition for a binary tree node. @@ -373,7 +227,127 @@ func isCousins(root *TreeNode, x int, y int) bool { } ``` -DFS: + + +### 方法二:DFS + +我们设计一个函数 $dfs(root, fa, d)$,表示从根节点 $root$ 出发,其父节点为 $fa$,深度为 $d$,进行深度优先搜索。 + +在函数中,我们首先判断当前节点是否为空,如果为空,则直接返回。如果当前节点的值为 $x$ 或 $y$,则记录该节点的父节点和深度。然后对当前节点的左右子节点分别调用函数 $dfs$,其中父节点为当前节点,深度为当前深度加 $1$。即 $dfs(root.left, root, d + 1)$ 和 $dfs(root.right, root, d + 1)$。 + +当整棵二叉树遍历完毕后,如果 $x$ 和 $y$ 的深度相同且父节点不同,则返回 $true$,否则返回 $false$。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool: + def dfs(root, fa, d): + if root is None: + return + if root.val == x: + t[0] = (fa, d) + if root.val == y: + t[1] = (fa, d) + dfs(root.left, root, d + 1) + dfs(root.right, root, d + 1) + + t = [None, None] + dfs(root, None, 0) + return t[0][0] != t[1][0] and t[0][1] == t[1][1] +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int x, y; + private TreeNode p1, p2; + private int d1, d2; + + public boolean isCousins(TreeNode root, int x, int y) { + this.x = x; + this.y = y; + dfs(root, null, 0); + return p1 != p2 && d1 == d2; + } + + private void dfs(TreeNode root, TreeNode p, int d) { + if (root == null) { + return; + } + if (root.val == x) { + p1 = p; + d1 = d; + } + if (root.val == y) { + p2 = p; + d2 = d; + } + dfs(root.left, root, d + 1); + dfs(root.right, root, d + 1); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isCousins(TreeNode* root, int x, int y) { + TreeNode *p1, *p2; + int d1, d2; + function dfs = [&](TreeNode* root, TreeNode* fa, int d) { + if (!root) { + return; + } + if (root->val == x) { + p1 = fa; + d1 = d; + } + if (root->val == y) { + p2 = fa; + d2 = d; + } + dfs(root->left, root, d + 1); + dfs(root->right, root, d + 1); + }; + dfs(root, nullptr, 0); + return p1 != p2 && d1 == d2; + } +}; +``` ```go /** @@ -406,10 +380,6 @@ func isCousins(root *TreeNode, x int, y int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0993.Cousins in Binary Tree/README_EN.md b/solution/0900-0999/0993.Cousins in Binary Tree/README_EN.md index dff5155a67343..fe84a0ff5e019 100644 --- a/solution/0900-0999/0993.Cousins in Binary Tree/README_EN.md +++ b/solution/0900-0999/0993.Cousins in Binary Tree/README_EN.md @@ -45,14 +45,10 @@ ## Solutions -BFS or DFS. +### Solution 1 -### **Python3** - -BFS: - ```python # Definition for a binary tree node. # class TreeNode: @@ -81,36 +77,6 @@ class Solution: return p1 != p2 and d1 == d2 ``` -DFS: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool: - def dfs(root, fa, d): - if root is None: - return - if root.val == x: - t[0] = (fa, d) - if root.val == y: - t[1] = (fa, d) - dfs(root.left, root, d + 1) - dfs(root.right, root, d + 1) - - t = [None, None] - dfs(root, None, 0) - return t[0][0] != t[1][0] and t[0][1] == t[1][1] -``` - -### **Java** - -BFS: - ```java /** * Definition for a binary tree node. @@ -160,58 +126,6 @@ class Solution { } ``` -DFS: - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private int x, y; - private TreeNode p1, p2; - private int d1, d2; - - public boolean isCousins(TreeNode root, int x, int y) { - this.x = x; - this.y = y; - dfs(root, null, 0); - return p1 != p2 && d1 == d2; - } - - private void dfs(TreeNode root, TreeNode p, int d) { - if (root == null) { - return; - } - if (root.val == x) { - p1 = p; - d1 = d; - } - if (root.val == y) { - p2 = p; - d2 = d; - } - dfs(root.left, root, d + 1); - dfs(root.right, root, d + 1); - } -} -``` - -### **C++** - -BFS: - ```cpp /** * Definition for a binary tree node. @@ -259,50 +173,6 @@ public: }; ``` -DFS: - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool isCousins(TreeNode* root, int x, int y) { - TreeNode *p1, *p2; - int d1, d2; - function dfs = [&](TreeNode* root, TreeNode* fa, int d) { - if (!root) { - return; - } - if (root->val == x) { - p1 = fa; - d1 = d; - } - if (root->val == y) { - p2 = fa; - d2 = d; - } - dfs(root->left, root, d + 1); - dfs(root->right, root, d + 1); - }; - dfs(root, nullptr, 0); - return p1 != p2 && d1 == d2; - } -}; -``` - -### **Go** - -BFS: - ```go /** * Definition for a binary tree node. @@ -341,7 +211,119 @@ func isCousins(root *TreeNode, x int, y int) bool { } ``` -DFS: + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool: + def dfs(root, fa, d): + if root is None: + return + if root.val == x: + t[0] = (fa, d) + if root.val == y: + t[1] = (fa, d) + dfs(root.left, root, d + 1) + dfs(root.right, root, d + 1) + + t = [None, None] + dfs(root, None, 0) + return t[0][0] != t[1][0] and t[0][1] == t[1][1] +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int x, y; + private TreeNode p1, p2; + private int d1, d2; + + public boolean isCousins(TreeNode root, int x, int y) { + this.x = x; + this.y = y; + dfs(root, null, 0); + return p1 != p2 && d1 == d2; + } + + private void dfs(TreeNode root, TreeNode p, int d) { + if (root == null) { + return; + } + if (root.val == x) { + p1 = p; + d1 = d; + } + if (root.val == y) { + p2 = p; + d2 = d; + } + dfs(root.left, root, d + 1); + dfs(root.right, root, d + 1); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isCousins(TreeNode* root, int x, int y) { + TreeNode *p1, *p2; + int d1, d2; + function dfs = [&](TreeNode* root, TreeNode* fa, int d) { + if (!root) { + return; + } + if (root->val == x) { + p1 = fa; + d1 = d; + } + if (root->val == y) { + p2 = fa; + d2 = d; + } + dfs(root->left, root, d + 1); + dfs(root->right, root, d + 1); + }; + dfs(root, nullptr, 0); + return p1 != p2 && d1 == d2; + } +}; +``` ```go /** @@ -374,10 +356,6 @@ func isCousins(root *TreeNode, x int, y int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0994.Rotting Oranges/README.md b/solution/0900-0999/0994.Rotting Oranges/README.md index a5462d1516333..3ef2d55ad1cfd 100644 --- a/solution/0900-0999/0994.Rotting Oranges/README.md +++ b/solution/0900-0999/0994.Rotting Oranges/README.md @@ -58,26 +58,10 @@ ## 解法 - - -首先需要确定的是,网格当中存在多少个新鲜橘子,这关系到什么时候结束。 - -其次,腐烂橘子的坐标在哪,这些坐标要作为中心点,将腐烂传播给四方的新鲜橘子。 - -步骤: - -1. 扫描网格,统计新鲜橘子的数量,记录腐烂橘子的坐标。 -2. 如果新鲜橘子的数量为 0,返回重复 2 - 5 步骤的轮数(也就是分钟)。 -3. 如果不存在**有效**的腐烂橘子,而现存的新鲜橘子不为 0,则为不可能,返回 -1。 -4. 遍历当前已记录的腐烂橘子,将四方的新鲜橘子污染。如果有新鲜橘子被污染成功,便记录该橘子的坐标,在下一轮使用(不参与本轮行动)。 -5. 回到第 2 步。 +### 方法一 -### **Python3** - - - ```python class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: @@ -104,10 +88,6 @@ class Solution: return ans if cnt == 0 else -1 ``` -### **Java** - - - ```java class Solution { public int orangesRotting(int[][] grid) { @@ -145,10 +125,6 @@ class Solution { } ``` -### **C++** - - - ```cpp class Solution { public: @@ -188,8 +164,6 @@ public: }; ``` -### **Go** - ```go func orangesRotting(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -228,8 +202,6 @@ func orangesRotting(grid [][]int) int { } ``` -### **TypeScript** - ```ts function orangesRotting(grid: number[][]): number { const m = grid.length; @@ -269,8 +241,6 @@ function orangesRotting(grid: number[][]): number { } ``` -### **Rust** - ```rust use std::collections::VecDeque; @@ -325,10 +295,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0994.Rotting Oranges/README_EN.md b/solution/0900-0999/0994.Rotting Oranges/README_EN.md index 49d841a5415d9..4575b6b123ef8 100644 --- a/solution/0900-0999/0994.Rotting Oranges/README_EN.md +++ b/solution/0900-0999/0994.Rotting Oranges/README_EN.md @@ -52,9 +52,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,8 +82,6 @@ class Solution: return ans if cnt == 0 else -1 ``` -### **Java** - ```java class Solution { public int orangesRotting(int[][] grid) { @@ -121,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +158,6 @@ public: }; ``` -### **Go** - ```go func orangesRotting(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -202,8 +196,6 @@ func orangesRotting(grid [][]int) int { } ``` -### **TypeScript** - ```ts function orangesRotting(grid: number[][]): number { const m = grid.length; @@ -243,8 +235,6 @@ function orangesRotting(grid: number[][]): number { } ``` -### **Rust** - ```rust use std::collections::VecDeque; @@ -253,6 +243,7 @@ impl Solution { let mut queue = VecDeque::new(); let m = grid.len(); let n = grid[0].len(); + // 新鲜橘子数量 let mut count = 0; for i in 0..m { for j in 0..n { @@ -298,10 +289,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/README.md b/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/README.md index e555017540348..06254f5e78b16 100644 --- a/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/README.md +++ b/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 我们注意到,对于若干个连续的元素进行反转,其结果与对这些元素进行反转的次序无关。因此我们可以贪心地考虑每个位置需要进行反转的次数。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def minKBitFlips(self, nums: List[int], k: int) -> int: @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minKBitFlips(int[] nums, int k) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func minKBitFlips(nums []int, k int) int { n := len(nums) @@ -169,8 +155,6 @@ func minKBitFlips(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function minKBitFlips(nums: number[], k: number): number { const n = nums.length; @@ -192,8 +176,6 @@ function minKBitFlips(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_k_bit_flips(nums: Vec, k: i32) -> i32 { @@ -218,10 +200,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/README_EN.md b/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/README_EN.md index becc343042136..e087106478df5 100644 --- a/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/README_EN.md +++ b/solution/0900-0999/0995.Minimum Number of K Consecutive Bit Flips/README_EN.md @@ -50,7 +50,7 @@ Flip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1] ## Solutions -**Solution 1: Difference Array** +### Solution 1: Difference Array We notice that the result of reversing several consecutive elements is independent of the order of the reversals. Therefore, we can greedily consider the number of reversals needed at each position. @@ -64,8 +64,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def minKBitFlips(self, nums: List[int], k: int) -> int: @@ -84,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minKBitFlips(int[] nums, int k) { @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +130,6 @@ public: }; ``` -### **Go** - ```go func minKBitFlips(nums []int, k int) int { n := len(nums) @@ -159,8 +151,6 @@ func minKBitFlips(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function minKBitFlips(nums: number[], k: number): number { const n = nums.length; @@ -182,8 +172,6 @@ function minKBitFlips(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_k_bit_flips(nums: Vec, k: i32) -> i32 { @@ -208,10 +196,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0996.Number of Squareful Arrays/README.md b/solution/0900-0999/0996.Number of Squareful Arrays/README.md index d34fbd63eed9f..9969a734cda89 100644 --- a/solution/0900-0999/0996.Number of Squareful Arrays/README.md +++ b/solution/0900-0999/0996.Number of Squareful Arrays/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:二进制状态压缩 + 动态规划** +### 方法一:二进制状态压缩 + 动态规划 注意到,数组 $nums$ 的长度 $n$ 不超过 $12$,因此我们可以用一个二进制数表示当前所选的数字的状态,若第 $i$ 位为 $1$,则表示当前选择了第 $i$ 个数字,否则表示当前没有选择第 $i$ 个数字。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def numSquarefulPerms(self, nums: List[int]) -> int: @@ -82,10 +76,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numSquarefulPerms(int[] nums) { @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -177,8 +165,6 @@ public: }; ``` -### **Go** - ```go func numSquarefulPerms(nums []int) (ans int) { n := len(nums) @@ -222,10 +208,6 @@ func numSquarefulPerms(nums []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0996.Number of Squareful Arrays/README_EN.md b/solution/0900-0999/0996.Number of Squareful Arrays/README_EN.md index e8703cc580b0a..c697d6052010c 100644 --- a/solution/0900-0999/0996.Number of Squareful Arrays/README_EN.md +++ b/solution/0900-0999/0996.Number of Squareful Arrays/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numSquarefulPerms(int[] nums) { @@ -109,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +152,6 @@ public: }; ``` -### **Go** - ```go func numSquarefulPerms(nums []int) (ans int) { n := len(nums) @@ -201,10 +195,6 @@ func numSquarefulPerms(nums []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0997.Find the Town Judge/README.md b/solution/0900-0999/0997.Find the Town Judge/README.md index b7e7facf53dc7..8930a089a0a39 100644 --- a/solution/0900-0999/0997.Find the Town Judge/README.md +++ b/solution/0900-0999/0997.Find the Town Judge/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们创建两个长度为 $n + 1$ 的数组 $cnt1$ 和 $cnt2$,分别表示每个人信任的人数和被信任的人数。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def findJudge(self, n: int, trust: List[List[int]]) -> int: @@ -90,10 +84,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int findJudge(int n, int[][] trust) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func findJudge(n int, trust [][]int) int { cnt1 := make([]int, n+1) @@ -157,8 +143,6 @@ func findJudge(n int, trust [][]int) int { } ``` -### **TypeScript** - ```ts function findJudge(n: number, trust: number[][]): number { const cnt1: number[] = new Array(n + 1).fill(0); @@ -176,8 +160,6 @@ function findJudge(n: number, trust: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn find_judge(n: i32, trust: Vec>) -> i32 { @@ -202,10 +184,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0997.Find the Town Judge/README_EN.md b/solution/0900-0999/0997.Find the Town Judge/README_EN.md index 3e28a9be936b5..18a80c3de35f5 100644 --- a/solution/0900-0999/0997.Find the Town Judge/README_EN.md +++ b/solution/0900-0999/0997.Find the Town Judge/README_EN.md @@ -54,7 +54,7 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We create two arrays $cnt1$ and $cnt2$ of length $n + 1$, representing the number of people each person trusts and the number of people who trust each person, respectively. @@ -66,8 +66,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def findJudge(self, n: int, trust: List[List[int]]) -> int: @@ -82,8 +80,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int findJudge(int n, int[][] trust) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +121,6 @@ public: }; ``` -### **Go** - ```go func findJudge(n int, trust [][]int) int { cnt1 := make([]int, n+1) @@ -147,8 +139,6 @@ func findJudge(n int, trust [][]int) int { } ``` -### **TypeScript** - ```ts function findJudge(n: number, trust: number[][]): number { const cnt1: number[] = new Array(n + 1).fill(0); @@ -166,8 +156,6 @@ function findJudge(n: number, trust: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn find_judge(n: i32, trust: Vec>) -> i32 { @@ -192,10 +180,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0998.Maximum Binary Tree II/README.md b/solution/0900-0999/0998.Maximum Binary Tree II/README.md index d22c09648df18..a3c90f8af45c6 100644 --- a/solution/0900-0999/0998.Maximum Binary Tree II/README.md +++ b/solution/0900-0999/0998.Maximum Binary Tree II/README.md @@ -69,9 +69,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 如果 $val$ 是最大数,那么将 $val$ 作为新的根节点,$root$ 作为新的根节点的左子树。 @@ -79,20 +77,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是树的节点数。 -**方法二:迭代** - -搜索右子树,找到 $curr.val \gt val \gt curr.right.val$ 的节点,然后创建新的节点 $node$,把 $node.left$ 指向 $curr.right$,然后 $curr.right$ 指向 $node$。 - -最后返回 $root$。 - -时间复杂度 $O(n)$,其中 $n$ 是树的节点数。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -110,32 +96,6 @@ class Solution: return root ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def insertIntoMaxTree( - self, root: Optional[TreeNode], val: int - ) -> Optional[TreeNode]: - if root.val < val: - return TreeNode(val, root) - curr = root - node = TreeNode(val) - while curr.right and curr.right.val > val: - curr = curr.right - node.left = curr.right - curr.right = node - return root -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -163,40 +123,45 @@ class Solution { } ``` -```java +```cpp /** * Definition for a binary tree node. - * public class TreeNode { + * struct TreeNode { * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; */ class Solution { - public TreeNode insertIntoMaxTree(TreeNode root, int val) { - if (root.val < val) { - return new TreeNode(val, root, null); - } - TreeNode curr = root; - TreeNode node = new TreeNode(val); - while (curr.right != null && curr.right.val > val) { - curr = curr.right; - } - node.left = curr.right; - curr.right = node; +public: + TreeNode* insertIntoMaxTree(TreeNode* root, int val) { + if (!root || root->val < val) return new TreeNode(val, root, nullptr); + root->right = insertIntoMaxTree(root->right, val); return root; } -} +}; ``` -### **TypeScript** +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func insertIntoMaxTree(root *TreeNode, val int) *TreeNode { + if root == nil || root.Val < val { + return &TreeNode{val, root, nil} + } + root.Right = insertIntoMaxTree(root.Right, val) + return root +} +``` ```ts /** @@ -222,58 +187,140 @@ function insertIntoMaxTree(root: TreeNode | null, val: number): TreeNode | null } ``` -```ts +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn insert_into_max_tree( + mut root: Option>>, + val: i32 + ) -> Option>> { + if root.is_none() || root.as_ref().unwrap().as_ref().borrow().val < val { + return Some( + Rc::new( + RefCell::new(TreeNode { + val, + left: root.take(), + right: None, + }) + ) + ); + } + { + let mut root = root.as_ref().unwrap().as_ref().borrow_mut(); + root.right = Self::insert_into_max_tree(root.right.take(), val); + } + root + } +} +``` + +```c /** * 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) - * } - * } + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; */ -function insertIntoMaxTree(root: TreeNode | null, val: number): TreeNode | null { - if (root.val < val) { - return new TreeNode(val, root); - } - const node = new TreeNode(val); - let curr = root; - while (curr.right && curr.right.val > val) { - curr = curr.right; +struct TreeNode* insertIntoMaxTree(struct TreeNode* root, int val) { + if (!root || root->val < val) { + struct TreeNode* res = (struct TreeNode*) malloc(sizeof(struct TreeNode)); + res->val = val; + res->left = root; + res->right = NULL; + return res; } - node.left = curr.right; - curr.right = node; + root->right = insertIntoMaxTree(root->right, val); return root; } ``` -### **C++** + -```cpp +### 方法二:迭代 + +搜索右子树,找到 $curr.val \gt val \gt curr.right.val$ 的节点,然后创建新的节点 $node$,把 $node.left$ 指向 $curr.right$,然后 $curr.right$ 指向 $node$。 + +最后返回 $root$。 + +时间复杂度 $O(n)$,其中 $n$ 是树的节点数。空间复杂度 $O(1)$。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def insertIntoMaxTree( + self, root: Optional[TreeNode], val: int + ) -> Optional[TreeNode]: + if root.val < val: + return TreeNode(val, root) + curr = root + node = TreeNode(val) + while curr.right and curr.right.val > val: + curr = curr.right + node.left = curr.right + curr.right = node + return root +``` + +```java /** * Definition for a binary tree node. - * struct TreeNode { + * public class TreeNode { * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } */ class Solution { -public: - TreeNode* insertIntoMaxTree(TreeNode* root, int val) { - if (!root || root->val < val) return new TreeNode(val, root, nullptr); - root->right = insertIntoMaxTree(root->right, val); + public TreeNode insertIntoMaxTree(TreeNode root, int val) { + if (root.val < val) { + return new TreeNode(val, root, null); + } + TreeNode curr = root; + TreeNode node = new TreeNode(val); + while (curr.right != null && curr.right.val > val) { + curr = curr.right; + } + node.left = curr.right; + curr.right = node; return root; } -}; +} ``` ```cpp @@ -302,26 +349,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func insertIntoMaxTree(root *TreeNode, val int) *TreeNode { - if root == nil || root.Val < val { - return &TreeNode{val, root, nil} - } - root.Right = insertIntoMaxTree(root.Right, val) - return root -} -``` - ```go /** * Definition for a binary tree node. @@ -346,83 +373,36 @@ func insertIntoMaxTree(root *TreeNode, val int) *TreeNode { } ``` -### **C** - -```c +```ts /** * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; + * 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) + * } + * } */ -struct TreeNode* insertIntoMaxTree(struct TreeNode* root, int val) { - if (!root || root->val < val) { - struct TreeNode* res = (struct TreeNode*) malloc(sizeof(struct TreeNode)); - res->val = val; - res->left = root; - res->right = NULL; - return res; +function insertIntoMaxTree(root: TreeNode | null, val: number): TreeNode | null { + if (root.val < val) { + return new TreeNode(val, root); } - root->right = insertIntoMaxTree(root->right, val); - return root; -} -``` - -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - pub fn insert_into_max_tree( - mut root: Option>>, - val: i32 - ) -> Option>> { - if root.is_none() || root.as_ref().unwrap().as_ref().borrow().val < val { - return Some( - Rc::new( - RefCell::new(TreeNode { - val, - left: root.take(), - right: None, - }) - ) - ); - } - { - let mut root = root.as_ref().unwrap().as_ref().borrow_mut(); - root.right = Self::insert_into_max_tree(root.right.take(), val); - } - root + const node = new TreeNode(val); + let curr = root; + while (curr.right && curr.right.val > val) { + curr = curr.right; } + node.left = curr.right; + curr.right = node; + return root; } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0998.Maximum Binary Tree II/README_EN.md b/solution/0900-0999/0998.Maximum Binary Tree II/README_EN.md index 6f9ffb5e5dc0a..2e7e02740d5d0 100644 --- a/solution/0900-0999/0998.Maximum Binary Tree II/README_EN.md +++ b/solution/0900-0999/0998.Maximum Binary Tree II/README_EN.md @@ -61,7 +61,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion If $val$ is the maximum number, then make $val$ the new root node, and $root$ the left subtree of the new root node. @@ -69,18 +69,8 @@ If $val$ is not the maximum number, since $val$ is the last appended number, it The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the tree. -**Solution 2: Iteration** - -Search the right subtree, find the node where $curr.val \gt val \gt curr.right.val$, then create a new node $node$, point $node.left$ to $curr.right$, and then point $curr.right$ to $node$. - -Finally, return $root$. - -The time complexity is $O(n)$, where $n$ is the number of nodes in the tree. The space complexity is $O(1)$. - -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -98,30 +88,6 @@ class Solution: return root ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def insertIntoMaxTree( - self, root: Optional[TreeNode], val: int - ) -> Optional[TreeNode]: - if root.val < val: - return TreeNode(val, root) - curr = root - node = TreeNode(val) - while curr.right and curr.right.val > val: - curr = curr.right - node.left = curr.right - curr.right = node - return root -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -149,40 +115,45 @@ class Solution { } ``` -```java +```cpp /** * Definition for a binary tree node. - * public class TreeNode { + * struct TreeNode { * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; */ class Solution { - public TreeNode insertIntoMaxTree(TreeNode root, int val) { - if (root.val < val) { - return new TreeNode(val, root, null); - } - TreeNode curr = root; - TreeNode node = new TreeNode(val); - while (curr.right != null && curr.right.val > val) { - curr = curr.right; - } - node.left = curr.right; - curr.right = node; +public: + TreeNode* insertIntoMaxTree(TreeNode* root, int val) { + if (!root || root->val < val) return new TreeNode(val, root, nullptr); + root->right = insertIntoMaxTree(root->right, val); return root; } -} +}; ``` -### **TypeScript** +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func insertIntoMaxTree(root *TreeNode, val int) *TreeNode { + if root == nil || root.Val < val { + return &TreeNode{val, root, nil} + } + root.Right = insertIntoMaxTree(root.Right, val) + return root +} +``` ```ts /** @@ -208,58 +179,140 @@ function insertIntoMaxTree(root: TreeNode | null, val: number): TreeNode | null } ``` -```ts +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + pub fn insert_into_max_tree( + mut root: Option>>, + val: i32 + ) -> Option>> { + if root.is_none() || root.as_ref().unwrap().as_ref().borrow().val < val { + return Some( + Rc::new( + RefCell::new(TreeNode { + val, + left: root.take(), + right: None, + }) + ) + ); + } + { + let mut root = root.as_ref().unwrap().as_ref().borrow_mut(); + root.right = Self::insert_into_max_tree(root.right.take(), val); + } + root + } +} +``` + +```c /** * 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) - * } - * } + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; */ -function insertIntoMaxTree(root: TreeNode | null, val: number): TreeNode | null { - if (root.val < val) { - return new TreeNode(val, root); - } - const node = new TreeNode(val); - let curr = root; - while (curr.right && curr.right.val > val) { - curr = curr.right; +struct TreeNode* insertIntoMaxTree(struct TreeNode* root, int val) { + if (!root || root->val < val) { + struct TreeNode* res = (struct TreeNode*) malloc(sizeof(struct TreeNode)); + res->val = val; + res->left = root; + res->right = NULL; + return res; } - node.left = curr.right; - curr.right = node; + root->right = insertIntoMaxTree(root->right, val); return root; } ``` -### **C++** + + +### Solution 2: Iteration -```cpp +Search the right subtree, find the node where $curr.val \gt val \gt curr.right.val$, then create a new node $node$, point $node.left$ to $curr.right$, and then point $curr.right$ to $node$. + +Finally, return $root$. + +The time complexity is $O(n)$, where $n$ is the number of nodes in the tree. The space complexity is $O(1)$. + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def insertIntoMaxTree( + self, root: Optional[TreeNode], val: int + ) -> Optional[TreeNode]: + if root.val < val: + return TreeNode(val, root) + curr = root + node = TreeNode(val) + while curr.right and curr.right.val > val: + curr = curr.right + node.left = curr.right + curr.right = node + return root +``` + +```java /** * Definition for a binary tree node. - * struct TreeNode { + * public class TreeNode { * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } */ class Solution { -public: - TreeNode* insertIntoMaxTree(TreeNode* root, int val) { - if (!root || root->val < val) return new TreeNode(val, root, nullptr); - root->right = insertIntoMaxTree(root->right, val); + public TreeNode insertIntoMaxTree(TreeNode root, int val) { + if (root.val < val) { + return new TreeNode(val, root, null); + } + TreeNode curr = root; + TreeNode node = new TreeNode(val); + while (curr.right != null && curr.right.val > val) { + curr = curr.right; + } + node.left = curr.right; + curr.right = node; return root; } -}; +} ``` ```cpp @@ -288,26 +341,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func insertIntoMaxTree(root *TreeNode, val int) *TreeNode { - if root == nil || root.Val < val { - return &TreeNode{val, root, nil} - } - root.Right = insertIntoMaxTree(root.Right, val) - return root -} -``` - ```go /** * Definition for a binary tree node. @@ -332,83 +365,36 @@ func insertIntoMaxTree(root *TreeNode, val int) *TreeNode { } ``` -### **C** - -```c +```ts /** * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; + * 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) + * } + * } */ -struct TreeNode* insertIntoMaxTree(struct TreeNode* root, int val) { - if (!root || root->val < val) { - struct TreeNode* res = (struct TreeNode*) malloc(sizeof(struct TreeNode)); - res->val = val; - res->left = root; - res->right = NULL; - return res; +function insertIntoMaxTree(root: TreeNode | null, val: number): TreeNode | null { + if (root.val < val) { + return new TreeNode(val, root); } - root->right = insertIntoMaxTree(root->right, val); - return root; -} -``` - -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - pub fn insert_into_max_tree( - mut root: Option>>, - val: i32 - ) -> Option>> { - if root.is_none() || root.as_ref().unwrap().as_ref().borrow().val < val { - return Some( - Rc::new( - RefCell::new(TreeNode { - val, - left: root.take(), - right: None, - }) - ) - ); - } - { - let mut root = root.as_ref().unwrap().as_ref().borrow_mut(); - root.right = Self::insert_into_max_tree(root.right.take(), val); - } - root + const node = new TreeNode(val); + let curr = root; + while (curr.right && curr.right.val > val) { + curr = curr.right; } + node.left = curr.right; + curr.right = node; + return root; } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0999.Available Captures for Rook/README.md b/solution/0900-0999/0999.Available Captures for Rook/README.md index 4ed9c350334fd..d0e916c370bfe 100644 --- a/solution/0900-0999/0999.Available Captures for Rook/README.md +++ b/solution/0900-0999/0999.Available Captures for Rook/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们先遍历棋盘,找到车的位置 $(x, y)$,然后从 $(x, y)$ 出发,向上下左右四个方向遍历: @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def numRookCaptures(self, board: List[List[str]]) -> int: @@ -103,10 +97,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numRookCaptures(char[][] board) { @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +155,6 @@ public: }; ``` -### **Go** - ```go func numRookCaptures(board [][]byte) (ans int) { dirs := [5]int{-1, 0, 1, 0, -1} @@ -193,10 +179,6 @@ func numRookCaptures(board [][]byte) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/0900-0999/0999.Available Captures for Rook/README_EN.md b/solution/0900-0999/0999.Available Captures for Rook/README_EN.md index e693fa492910a..4b9243ddaeaef 100644 --- a/solution/0900-0999/0999.Available Captures for Rook/README_EN.md +++ b/solution/0900-0999/0999.Available Captures for Rook/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation First, we traverse the chessboard to find the position of the rook $(x, y)$. Then, starting from $(x, y)$, we traverse in four directions: up, down, left, and right: @@ -61,8 +61,6 @@ The time complexity is $O(m \times n)$, where $m$ and $n$ are the number of rows -### **Python3** - ```python class Solution: def numRookCaptures(self, board: List[List[str]]) -> int: @@ -83,8 +81,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numRookCaptures(char[][] board) { @@ -114,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +139,6 @@ public: }; ``` -### **Go** - ```go func numRookCaptures(board [][]byte) (ans int) { dirs := [5]int{-1, 0, 1, 0, -1} @@ -171,10 +163,6 @@ func numRookCaptures(board [][]byte) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1000.Minimum Cost to Merge Stones/README.md b/solution/1000-1099/1000.Minimum Cost to Merge Stones/README.md index 2e9078e34f845..72659f6a2460d 100644 --- a/solution/1000-1099/1000.Minimum Cost to Merge Stones/README.md +++ b/solution/1000-1099/1000.Minimum Cost to Merge Stones/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:动态规划(区间 DP)+ 前缀和** +### 方法一:动态规划(区间 DP)+ 前缀和 我们不妨记题目中的 $k$ 为 $K$,石头的堆数为 $n$。 @@ -84,10 +82,6 @@ $$ -### **Python3** - - - ```python class Solution: def mergeStones(self, stones: List[int], K: int) -> int: @@ -108,10 +102,6 @@ class Solution: return f[1][n][1] ``` -### **Java** - - - ```java class Solution { public int mergeStones(int[] stones, int K) { @@ -149,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -185,8 +173,6 @@ public: }; ``` -### **Go** - ```go func mergeStones(stones []int, K int) int { n := len(stones) @@ -225,10 +211,6 @@ func mergeStones(stones []int, K int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1000.Minimum Cost to Merge Stones/README_EN.md b/solution/1000-1099/1000.Minimum Cost to Merge Stones/README_EN.md index c89b13bc12ec8..895ef70891554 100644 --- a/solution/1000-1099/1000.Minimum Cost to Merge Stones/README_EN.md +++ b/solution/1000-1099/1000.Minimum Cost to Merge Stones/README_EN.md @@ -54,9 +54,9 @@ The total cost was 25, and this is the minimum possible. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,8 +78,6 @@ class Solution: return f[1][n][1] ``` -### **Java** - ```java class Solution { public int mergeStones(int[] stones, int K) { @@ -117,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +149,6 @@ public: }; ``` -### **Go** - ```go func mergeStones(stones []int, K int) int { n := len(stones) @@ -193,10 +187,6 @@ func mergeStones(stones []int, K int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1001.Grid Illumination/README.md b/solution/1000-1099/1001.Grid Illumination/README.md index 3cee59a7acb12..31eab97e8aa93 100644 --- a/solution/1000-1099/1001.Grid Illumination/README.md +++ b/solution/1000-1099/1001.Grid Illumination/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 假设一盏灯的坐标为 $(x, y)$,那么它所在的行的数值为 $x$,列的数值为 $y$,正对角线的数值为 $x-y$,反对角线的数值为 $x+y$。确定某一直线的唯一数值标识后,我们就可以通过哈希表来记录某一直线所拥有的灯的数目。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def gridIllumination( @@ -108,10 +102,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int n; @@ -170,8 +160,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -216,8 +204,6 @@ public: }; ``` -### **Go** - ```go func gridIllumination(n int, lamps [][]int, queries [][]int) []int { row, col, diag1, diag2 := map[int]int{}, map[int]int{}, map[int]int{}, map[int]int{} @@ -258,8 +244,6 @@ func gridIllumination(n int, lamps [][]int, queries [][]int) []int { } ``` -### **TypeScript** - ```ts function gridIllumination(n: number, lamps: number[][], queries: number[][]): number[] { const row = new Map(); @@ -301,10 +285,6 @@ function gridIllumination(n: number, lamps: number[][], queries: number[][]): nu } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1001.Grid Illumination/README_EN.md b/solution/1000-1099/1001.Grid Illumination/README_EN.md index 8d59afad0f7c1..1d42b4c63d7ed 100644 --- a/solution/1000-1099/1001.Grid Illumination/README_EN.md +++ b/solution/1000-1099/1001.Grid Illumination/README_EN.md @@ -56,9 +56,9 @@ The 1st query asks if the lamp at grid[1][0] is illuminated or n ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -87,8 +87,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int n; @@ -147,8 +145,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -193,8 +189,6 @@ public: }; ``` -### **Go** - ```go func gridIllumination(n int, lamps [][]int, queries [][]int) []int { row, col, diag1, diag2 := map[int]int{}, map[int]int{}, map[int]int{}, map[int]int{} @@ -235,8 +229,6 @@ func gridIllumination(n int, lamps [][]int, queries [][]int) []int { } ``` -### **TypeScript** - ```ts function gridIllumination(n: number, lamps: number[][], queries: number[][]): number[] { const row = new Map(); @@ -278,10 +270,6 @@ function gridIllumination(n: number, lamps: number[][], queries: number[][]): nu } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1002.Find Common Characters/README.md b/solution/1000-1099/1002.Find Common Characters/README.md index 2e4f87dbcb230..fd20731917542 100644 --- a/solution/1000-1099/1002.Find Common Characters/README.md +++ b/solution/1000-1099/1002.Find Common Characters/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们用一个长度为 $26$ 的数组 $cnt$ 记录每个字符在所有字符串中出现的最小次数,最后遍历 $cnt$ 数组,将出现次数大于 $0$ 的字符加入答案即可。 @@ -46,10 +44,6 @@ -### **Python3** - - - ```python class Solution: def commonChars(self, words: List[str]) -> List[str]: @@ -64,10 +58,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List commonChars(String[] words) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func commonChars(words []string) (ans []string) { cnt := [26]int{} @@ -148,8 +134,6 @@ func commonChars(words []string) (ans []string) { } ``` -### **TypeScript** - ```ts function commonChars(words: string[]): string[] { const freq: number[] = new Array(26).fill(10000); @@ -172,10 +156,6 @@ function commonChars(words: string[]): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1002.Find Common Characters/README_EN.md b/solution/1000-1099/1002.Find Common Characters/README_EN.md index ae369cfa7b1a6..a5019594edfca 100644 --- a/solution/1000-1099/1002.Find Common Characters/README_EN.md +++ b/solution/1000-1099/1002.Find Common Characters/README_EN.md @@ -25,9 +25,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -43,8 +43,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List commonChars(String[] words) { @@ -70,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +94,6 @@ public: }; ``` -### **Go** - ```go func commonChars(words []string) (ans []string) { cnt := [26]int{} @@ -125,8 +119,6 @@ func commonChars(words []string) (ans []string) { } ``` -### **TypeScript** - ```ts function commonChars(words: string[]): string[] { const freq: number[] = new Array(26).fill(10000); @@ -149,10 +141,6 @@ function commonChars(words: string[]): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1003.Check If Word Is Valid After Substitutions/README.md b/solution/1000-1099/1003.Check If Word Is Valid After Substitutions/README.md index c24ca9e4dc69a..2e51e6838a78b 100644 --- a/solution/1000-1099/1003.Check If Word Is Valid After Substitutions/README.md +++ b/solution/1000-1099/1003.Check If Word Is Valid After Substitutions/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 我们观察题目中的操作,可以发现,每一次都会在字符串的任意位置插入字符串 `"abc"`,所以每次插入操作之后,字符串的长度都会增加 $3$。如果字符串 $s$ 有效,那么它的长度一定是 $3$ 的倍数。因此,我们先对字符串 $s$ 的长度进行判断,如果不是 $3$ 的倍数,那么 $s$ 一定无效,可以直接返回 `false`。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def isValid(self, s: str) -> bool: @@ -85,10 +79,6 @@ class Solution: return not t ``` -### **Java** - - - ```java class Solution { public boolean isValid(String s) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func isValid(s string) bool { if len(s)%3 > 0 { @@ -146,8 +132,6 @@ func isValid(s string) bool { } ``` -### **TypeScript** - ```ts function isValid(s: string): boolean { if (s.length % 3 !== 0) { @@ -164,10 +148,6 @@ function isValid(s: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1003.Check If Word Is Valid After Substitutions/README_EN.md b/solution/1000-1099/1003.Check If Word Is Valid After Substitutions/README_EN.md index 34e5b2ef3542f..f9774bda2807a 100644 --- a/solution/1000-1099/1003.Check If Word Is Valid After Substitutions/README_EN.md +++ b/solution/1000-1099/1003.Check If Word Is Valid After Substitutions/README_EN.md @@ -52,7 +52,7 @@ Thus, "abcabcababcc" is valid. ## Solutions -**Solution 1: Stack** +### Solution 1: Stack If the string is valid, it's length must be the multiple of $3$. @@ -64,8 +64,6 @@ The time complexity is $O(n)$ and the space complexity is $O(n)$. Where $n$ is t -### **Python3** - ```python class Solution: def isValid(self, s: str) -> bool: @@ -79,8 +77,6 @@ class Solution: return not t ``` -### **Java** - ```java class Solution { public boolean isValid(String s) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +114,6 @@ public: }; ``` -### **Go** - ```go func isValid(s string) bool { if len(s)%3 > 0 { @@ -138,8 +130,6 @@ func isValid(s string) bool { } ``` -### **TypeScript** - ```ts function isValid(s: string): boolean { if (s.length % 3 !== 0) { @@ -156,10 +146,6 @@ function isValid(s: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1004.Max Consecutive Ones III/README.md b/solution/1000-1099/1004.Max Consecutive Ones III/README.md index c14523ac01827..56c8ff7820565 100644 --- a/solution/1000-1099/1004.Max Consecutive Ones III/README.md +++ b/solution/1000-1099/1004.Max Consecutive Ones III/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 定义一个滑动窗口,窗口内的 $0$ 的个数不超过 $k$,窗口的右边界不断向右移动,当窗口内的 $0$ 的个数超过 $k$ 时,窗口的左边界向右移动,直到窗口内的 $0$ 的个数不超过 $k$ 为止。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def longestOnes(self, nums: List[int], k: int) -> int: @@ -82,25 +76,6 @@ class Solution: return ans ``` -```python -class Solution: - def longestOnes(self, nums: List[int], k: int) -> int: - l = r = -1 - while r < len(nums) - 1: - r += 1 - if nums[r] == 0: - k -= 1 - if k < 0: - l += 1 - if nums[l] == 0: - k += 1 - return r - l -``` - -### **Java** - - - ```java class Solution { public int longestOnes(int[] nums, int k) { @@ -122,25 +97,6 @@ class Solution { } ``` -```java -class Solution { - public int longestOnes(int[] nums, int k) { - int l = 0, r = 0; - while (r < nums.length) { - if (nums[r++] == 0) { - --k; - } - if (k < 0 && nums[l++] == 0) { - ++k; - } - } - return r - l; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -163,22 +119,6 @@ public: }; ``` -```cpp -class Solution { -public: - int longestOnes(vector& nums, int k) { - int l = 0, r = 0; - while (r < nums.size()) { - if (nums[r++] == 0) --k; - if (k < 0 && nums[l++] == 0) ++k; - } - return r - l; - } -}; -``` - -### **Go** - ```go func longestOnes(nums []int, k int) int { ans := 0 @@ -199,27 +139,6 @@ func longestOnes(nums []int, k int) int { } ``` -```go -func longestOnes(nums []int, k int) int { - l, r := -1, -1 - for r < len(nums)-1 { - r++ - if nums[r] == 0 { - k-- - } - if k < 0 { - l++ - if nums[l] == 0 { - k++ - } - } - } - return r - l -} -``` - -### **TypeScript** - ```ts function longestOnes(nums: number[], k: number): number { const n = nums.length; @@ -236,26 +155,6 @@ function longestOnes(nums: number[], k: number): number { } ``` -```ts -function longestOnes(nums: number[], k: number): number { - const n = nums.length; - let l = 0; - let res = k; - const count = [0, 0]; - for (let r = 0; r < n; r++) { - count[nums[r]]++; - res = Math.max(res, r - l); - while (count[0] > k) { - count[nums[l]]--; - l++; - } - } - return Math.max(res, n - l); -} -``` - -### **Rust** - ```rust impl Solution { pub fn longest_ones(nums: Vec, mut k: i32) -> i32 { @@ -277,10 +176,95 @@ impl Solution { } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def longestOnes(self, nums: List[int], k: int) -> int: + l = r = -1 + while r < len(nums) - 1: + r += 1 + if nums[r] == 0: + k -= 1 + if k < 0: + l += 1 + if nums[l] == 0: + k += 1 + return r - l +``` + +```java +class Solution { + public int longestOnes(int[] nums, int k) { + int l = 0, r = 0; + while (r < nums.length) { + if (nums[r++] == 0) { + --k; + } + if (k < 0 && nums[l++] == 0) { + ++k; + } + } + return r - l; + } +} +``` + +```cpp +class Solution { +public: + int longestOnes(vector& nums, int k) { + int l = 0, r = 0; + while (r < nums.size()) { + if (nums[r++] == 0) --k; + if (k < 0 && nums[l++] == 0) ++k; + } + return r - l; + } +}; +``` +```go +func longestOnes(nums []int, k int) int { + l, r := -1, -1 + for r < len(nums)-1 { + r++ + if nums[r] == 0 { + k-- + } + if k < 0 { + l++ + if nums[l] == 0 { + k++ + } + } + } + return r - l +} ``` +```ts +function longestOnes(nums: number[], k: number): number { + const n = nums.length; + let l = 0; + let res = k; + const count = [0, 0]; + for (let r = 0; r < n; r++) { + count[nums[r]]++; + res = Math.max(res, r - l); + while (count[0] > k) { + count[nums[l]]--; + l++; + } + } + return Math.max(res, n - l); +} ``` + + diff --git a/solution/1000-1099/1004.Max Consecutive Ones III/README_EN.md b/solution/1000-1099/1004.Max Consecutive Ones III/README_EN.md index c95b2c39d2c38..2723a706f702b 100644 --- a/solution/1000-1099/1004.Max Consecutive Ones III/README_EN.md +++ b/solution/1000-1099/1004.Max Consecutive Ones III/README_EN.md @@ -35,9 +35,9 @@ Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,23 +55,6 @@ class Solution: return ans ``` -```python -class Solution: - def longestOnes(self, nums: List[int], k: int) -> int: - l = r = -1 - while r < len(nums) - 1: - r += 1 - if nums[r] == 0: - k -= 1 - if k < 0: - l += 1 - if nums[l] == 0: - k += 1 - return r - l -``` - -### **Java** - ```java class Solution { public int longestOnes(int[] nums, int k) { @@ -93,25 +76,6 @@ class Solution { } ``` -```java -class Solution { - public int longestOnes(int[] nums, int k) { - int l = 0, r = 0; - while (r < nums.length) { - if (nums[r++] == 0) { - --k; - } - if (k < 0 && nums[l++] == 0) { - ++k; - } - } - return r - l; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -134,22 +98,6 @@ public: }; ``` -```cpp -class Solution { -public: - int longestOnes(vector& nums, int k) { - int l = 0, r = 0; - while (r < nums.size()) { - if (nums[r++] == 0) --k; - if (k < 0 && nums[l++] == 0) ++k; - } - return r - l; - } -}; -``` - -### **Go** - ```go func longestOnes(nums []int, k int) int { ans := 0 @@ -170,27 +118,6 @@ func longestOnes(nums []int, k int) int { } ``` -```go -func longestOnes(nums []int, k int) int { - l, r := -1, -1 - for r < len(nums)-1 { - r++ - if nums[r] == 0 { - k-- - } - if k < 0 { - l++ - if nums[l] == 0 { - k++ - } - } - } - return r - l -} -``` - -### **TypeScript** - ```ts function longestOnes(nums: number[], k: number): number { const n = nums.length; @@ -207,26 +134,6 @@ function longestOnes(nums: number[], k: number): number { } ``` -```ts -function longestOnes(nums: number[], k: number): number { - const n = nums.length; - let l = 0; - let res = k; - const count = [0, 0]; - for (let r = 0; r < n; r++) { - count[nums[r]]++; - res = Math.max(res, r - l); - while (count[0] > k) { - count[nums[l]]--; - l++; - } - } - return Math.max(res, n - l); -} -``` - -### **Rust** - ```rust impl Solution { pub fn longest_ones(nums: Vec, mut k: i32) -> i32 { @@ -248,10 +155,95 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def longestOnes(self, nums: List[int], k: int) -> int: + l = r = -1 + while r < len(nums) - 1: + r += 1 + if nums[r] == 0: + k -= 1 + if k < 0: + l += 1 + if nums[l] == 0: + k += 1 + return r - l ``` +```java +class Solution { + public int longestOnes(int[] nums, int k) { + int l = 0, r = 0; + while (r < nums.length) { + if (nums[r++] == 0) { + --k; + } + if (k < 0 && nums[l++] == 0) { + ++k; + } + } + return r - l; + } +} +``` + +```cpp +class Solution { +public: + int longestOnes(vector& nums, int k) { + int l = 0, r = 0; + while (r < nums.size()) { + if (nums[r++] == 0) --k; + if (k < 0 && nums[l++] == 0) ++k; + } + return r - l; + } +}; +``` + +```go +func longestOnes(nums []int, k int) int { + l, r := -1, -1 + for r < len(nums)-1 { + r++ + if nums[r] == 0 { + k-- + } + if k < 0 { + l++ + if nums[l] == 0 { + k++ + } + } + } + return r - l +} +``` + +```ts +function longestOnes(nums: number[], k: number): number { + const n = nums.length; + let l = 0; + let res = k; + const count = [0, 0]; + for (let r = 0; r < n; r++) { + count[nums[r]]++; + res = Math.max(res, r - l); + while (count[0] > k) { + count[nums[l]]--; + l++; + } + } + return Math.max(res, n - l); +} ``` + + diff --git a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README.md b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README.md index 6385a80582627..ad01dca84eec3 100644 --- a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README.md +++ b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:贪心 + 计数** +### 方法一:贪心 + 计数 我们观察发现,要使得数组的和尽可能大,就应该尽可能地将数组中的最小负数变成正数。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def largestSumAfterKNegations(self, nums: List[int], k: int) -> int: @@ -95,10 +89,6 @@ class Solution: return sum(x * v for x, v in cnt.items()) ``` -### **Java** - - - ```java class Solution { public int largestSumAfterKNegations(int[] nums, int k) { @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go func largestSumAfterKNegations(nums []int, k int) (ans int) { cnt := map[int]int{} @@ -200,8 +186,6 @@ func largestSumAfterKNegations(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function largestSumAfterKNegations(nums: number[], k: number): number { const cnt: Map = new Map(); @@ -233,10 +217,6 @@ function largestSumAfterKNegations(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md index 08ddc88d2eb60..6b98d59230483 100644 --- a/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md +++ b/solution/1000-1099/1005.Maximize Sum Of Array After K Negations/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return sum(x * v for x, v in cnt.items()) ``` -### **Java** - ```java class Solution { public int largestSumAfterKNegations(int[] nums, int k) { @@ -110,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +142,6 @@ public: }; ``` -### **Go** - ```go func largestSumAfterKNegations(nums []int, k int) (ans int) { cnt := map[int]int{} @@ -178,8 +172,6 @@ func largestSumAfterKNegations(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function largestSumAfterKNegations(nums: number[], k: number): number { const cnt: Map = new Map(); @@ -211,10 +203,6 @@ function largestSumAfterKNegations(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1006.Clumsy Factorial/README.md b/solution/1000-1099/1006.Clumsy Factorial/README.md index 13e92ed386f5a..102f89fa9f728 100644 --- a/solution/1000-1099/1006.Clumsy Factorial/README.md +++ b/solution/1000-1099/1006.Clumsy Factorial/README.md @@ -43,16 +43,10 @@ ## 解法 - - -遇到 `*`、`/` 时计算后入栈,遇到 `+`、`-` 时直接入栈。最后累加栈中的元素即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def clumsy(self, N: int) -> int: @@ -71,10 +65,6 @@ class Solution: return sum(s) ``` -### **Java** - - - ```java class Solution { public int clumsy(int N) { @@ -102,10 +92,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1006.Clumsy Factorial/README_EN.md b/solution/1000-1099/1006.Clumsy Factorial/README_EN.md index f1e8fc38bc5ea..9c6bde6769e1a 100644 --- a/solution/1000-1099/1006.Clumsy Factorial/README_EN.md +++ b/solution/1000-1099/1006.Clumsy Factorial/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return sum(s) ``` -### **Java** - ```java class Solution { public int clumsy(int N) { @@ -99,10 +97,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1007.Minimum Domino Rotations For Equal Row/README.md b/solution/1000-1099/1007.Minimum Domino Rotations For Equal Row/README.md index 9c0e5e9e977f4..f1de5b2743840 100644 --- a/solution/1000-1099/1007.Minimum Domino Rotations For Equal Row/README.md +++ b/solution/1000-1099/1007.Minimum Domino Rotations For Equal Row/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 根据题目描述,我们知道,要使得 $tops$ 中所有值或者 $bottoms$ 中所有值都相同,那么这个值必须是 $tops[0]$ 或者 $bottoms[0]$ 中的一个。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: @@ -82,10 +76,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - - - ```java class Solution { private int n; @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func minDominoRotations(tops []int, bottoms []int) int { n := len(tops) @@ -167,8 +153,6 @@ func minDominoRotations(tops []int, bottoms []int) int { } ``` -### **TypeScript** - ```ts function minDominoRotations(tops: number[], bottoms: number[]): number { const n = tops.length; @@ -188,10 +172,6 @@ function minDominoRotations(tops: number[], bottoms: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1007.Minimum Domino Rotations For Equal Row/README_EN.md b/solution/1000-1099/1007.Minimum Domino Rotations For Equal Row/README_EN.md index 1254be6f1b5d6..d4046f1c8ca77 100644 --- a/solution/1000-1099/1007.Minimum Domino Rotations For Equal Row/README_EN.md +++ b/solution/1000-1099/1007.Minimum Domino Rotations For Equal Row/README_EN.md @@ -43,7 +43,7 @@ In this case, it is not possible to rotate the dominoes to make one row of value ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy According to the problem description, we know that in order to make all values in $tops$ or all values in $bottoms$ the same, the value must be one of $tops[0]$ or $bottoms[0]$. @@ -57,8 +57,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int: @@ -75,8 +73,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - ```java class Solution { private int n; @@ -105,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +123,6 @@ public: }; ``` -### **Go** - ```go func minDominoRotations(tops []int, bottoms []int) int { n := len(tops) @@ -158,8 +150,6 @@ func minDominoRotations(tops []int, bottoms []int) int { } ``` -### **TypeScript** - ```ts function minDominoRotations(tops: number[], bottoms: number[]): number { const n = tops.length; @@ -179,10 +169,6 @@ function minDominoRotations(tops: number[], bottoms: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/README.md b/solution/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/README.md index 9f9c38f530290..d99ae5580a8a6 100644 --- a/solution/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/README.md +++ b/solution/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/README.md @@ -46,16 +46,10 @@ ## 解法 - - -根据二叉搜索树的性质,DFS 构建即可。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -83,10 +77,6 @@ class Solution: return dfs(preorder) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -203,8 +189,6 @@ func bstFromPreorder(preorder []int) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -242,8 +226,6 @@ function bstFromPreorder(preorder: number[]): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -304,10 +286,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/README_EN.md b/solution/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/README_EN.md index b4663e659c189..787b420dbc03e 100644 --- a/solution/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/README_EN.md +++ b/solution/1000-1099/1008.Construct Binary Search Tree from Preorder Traversal/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -69,8 +69,6 @@ class Solution: return dfs(preorder) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -152,8 +148,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -187,8 +181,6 @@ func bstFromPreorder(preorder []int) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -226,8 +218,6 @@ function bstFromPreorder(preorder: number[]): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -288,10 +278,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1009.Complement of Base 10 Integer/README.md b/solution/1000-1099/1009.Complement of Base 10 Integer/README.md index 2946656e88330..d5fb8839a6ea7 100644 --- a/solution/1000-1099/1009.Complement of Base 10 Integer/README.md +++ b/solution/1000-1099/1009.Complement of Base 10 Integer/README.md @@ -49,14 +49,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def bitwiseComplement(self, n: int) -> int: @@ -74,10 +70,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int bitwiseComplement(int n) { @@ -101,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +111,6 @@ public: }; ``` -### **Go** - ```go func bitwiseComplement(n int) int { if n == 0 { @@ -144,10 +132,6 @@ func bitwiseComplement(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1009.Complement of Base 10 Integer/README_EN.md b/solution/1000-1099/1009.Complement of Base 10 Integer/README_EN.md index 295ba6009c123..59584193691b6 100644 --- a/solution/1000-1099/1009.Complement of Base 10 Integer/README_EN.md +++ b/solution/1000-1099/1009.Complement of Base 10 Integer/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int bitwiseComplement(int n) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +111,6 @@ public: }; ``` -### **Go** - ```go func bitwiseComplement(n int) int { if n == 0 { @@ -138,10 +132,6 @@ func bitwiseComplement(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/README.md b/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/README.md index 09d764ad1e592..3364955a5c3b4 100644 --- a/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/README.md +++ b/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:数学 + 计数** +### 方法一:数学 + 计数 如果一个数对 $(a, b)$ 之和能被 $60$ 整除,即 $(a + b) \bmod 60 = 0$,那么 $(a \bmod 60 + b \bmod 60) \bmod 60 = 0$,不妨记 $x=a \bmod 60$, $y = b \bmod 60$,那么有 $(x + y) \bmod 60 = 0$,即 $y=(60 - x) \bmod 60$。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def numPairsDivisibleBy60(self, time: List[int]) -> int: @@ -70,23 +64,6 @@ class Solution: return ans ``` -```python -class Solution: - def numPairsDivisibleBy60(self, time: List[int]) -> int: - cnt = Counter() - ans = 0 - for x in time: - x %= 60 - y = (60 - x) % 60 - ans += cnt[y] - cnt[x] += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int numPairsDivisibleBy60(int[] time) { @@ -105,24 +82,6 @@ class Solution { } ``` -```java -class Solution { - public int numPairsDivisibleBy60(int[] time) { - int[] cnt = new int[60]; - int ans = 0; - for (int x : time) { - x %= 60; - int y = (60 - x) % 60; - ans += cnt[y]; - ++cnt[x]; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -142,25 +101,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numPairsDivisibleBy60(vector& time) { - int cnt[60]{}; - int ans = 0; - for (int x : time) { - x %= 60; - int y = (60 - x) % 60; - ans += cnt[y]; - ++cnt[x]; - } - return ans; - } -}; -``` - -### **Go** - ```go func numPairsDivisibleBy60(time []int) (ans int) { cnt := [60]int{} @@ -176,21 +116,6 @@ func numPairsDivisibleBy60(time []int) (ans int) { } ``` -```go -func numPairsDivisibleBy60(time []int) (ans int) { - cnt := [60]int{} - for _, x := range time { - x %= 60 - y := (60 - x) % 60 - ans += cnt[y] - cnt[x]++ - } - return -} -``` - -### **TypeScript** - ```ts function numPairsDivisibleBy60(time: number[]): number { const cnt: number[] = new Array(60).fill(0); @@ -207,6 +132,71 @@ function numPairsDivisibleBy60(time: number[]): number { } ``` + + +### 方法二 + + + +```python +class Solution: + def numPairsDivisibleBy60(self, time: List[int]) -> int: + cnt = Counter() + ans = 0 + for x in time: + x %= 60 + y = (60 - x) % 60 + ans += cnt[y] + cnt[x] += 1 + return ans +``` + +```java +class Solution { + public int numPairsDivisibleBy60(int[] time) { + int[] cnt = new int[60]; + int ans = 0; + for (int x : time) { + x %= 60; + int y = (60 - x) % 60; + ans += cnt[y]; + ++cnt[x]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int numPairsDivisibleBy60(vector& time) { + int cnt[60]{}; + int ans = 0; + for (int x : time) { + x %= 60; + int y = (60 - x) % 60; + ans += cnt[y]; + ++cnt[x]; + } + return ans; + } +}; +``` + +```go +func numPairsDivisibleBy60(time []int) (ans int) { + cnt := [60]int{} + for _, x := range time { + x %= 60 + y := (60 - x) % 60 + ans += cnt[y] + cnt[x]++ + } + return +} +``` + ```ts function numPairsDivisibleBy60(time: number[]): number { const cnt: number[] = new Array(60).fill(0); @@ -221,10 +211,6 @@ function numPairsDivisibleBy60(time: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/README_EN.md b/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/README_EN.md index 7137c63730f92..d777d0daf1d8c 100644 --- a/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/README_EN.md +++ b/solution/1000-1099/1010.Pairs of Songs With Total Durations Divisible by 60/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,21 +52,6 @@ class Solution: return ans ``` -```python -class Solution: - def numPairsDivisibleBy60(self, time: List[int]) -> int: - cnt = Counter() - ans = 0 - for x in time: - x %= 60 - y = (60 - x) % 60 - ans += cnt[y] - cnt[x] += 1 - return ans -``` - -### **Java** - ```java class Solution { public int numPairsDivisibleBy60(int[] time) { @@ -85,24 +70,6 @@ class Solution { } ``` -```java -class Solution { - public int numPairsDivisibleBy60(int[] time) { - int[] cnt = new int[60]; - int ans = 0; - for (int x : time) { - x %= 60; - int y = (60 - x) % 60; - ans += cnt[y]; - ++cnt[x]; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -122,25 +89,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numPairsDivisibleBy60(vector& time) { - int cnt[60]{}; - int ans = 0; - for (int x : time) { - x %= 60; - int y = (60 - x) % 60; - ans += cnt[y]; - ++cnt[x]; - } - return ans; - } -}; -``` - -### **Go** - ```go func numPairsDivisibleBy60(time []int) (ans int) { cnt := [60]int{} @@ -156,21 +104,6 @@ func numPairsDivisibleBy60(time []int) (ans int) { } ``` -```go -func numPairsDivisibleBy60(time []int) (ans int) { - cnt := [60]int{} - for _, x := range time { - x %= 60 - y := (60 - x) % 60 - ans += cnt[y] - cnt[x]++ - } - return -} -``` - -### **TypeScript** - ```ts function numPairsDivisibleBy60(time: number[]): number { const cnt: number[] = new Array(60).fill(0); @@ -187,6 +120,71 @@ function numPairsDivisibleBy60(time: number[]): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def numPairsDivisibleBy60(self, time: List[int]) -> int: + cnt = Counter() + ans = 0 + for x in time: + x %= 60 + y = (60 - x) % 60 + ans += cnt[y] + cnt[x] += 1 + return ans +``` + +```java +class Solution { + public int numPairsDivisibleBy60(int[] time) { + int[] cnt = new int[60]; + int ans = 0; + for (int x : time) { + x %= 60; + int y = (60 - x) % 60; + ans += cnt[y]; + ++cnt[x]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int numPairsDivisibleBy60(vector& time) { + int cnt[60]{}; + int ans = 0; + for (int x : time) { + x %= 60; + int y = (60 - x) % 60; + ans += cnt[y]; + ++cnt[x]; + } + return ans; + } +}; +``` + +```go +func numPairsDivisibleBy60(time []int) (ans int) { + cnt := [60]int{} + for _, x := range time { + x %= 60 + y := (60 - x) % 60 + ans += cnt[y] + cnt[x]++ + } + return +} +``` + ```ts function numPairsDivisibleBy60(time: number[]): number { const cnt: number[] = new Array(60).fill(0); @@ -201,10 +199,6 @@ function numPairsDivisibleBy60(time: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1011.Capacity To Ship Packages Within D Days/README.md b/solution/1000-1099/1011.Capacity To Ship Packages Within D Days/README.md index 644486702ee33..be0b5b17b375c 100644 --- a/solution/1000-1099/1011.Capacity To Ship Packages Within D Days/README.md +++ b/solution/1000-1099/1011.Capacity To Ship Packages Within D Days/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们注意到,如果运载能力 $x$ 能够在 $days$ 天内运送完所有包裹,那么运载能力 $x + 1$ 也能在 $days$ 天内运送完所有包裹。也即是说,随着运载能力的增加,运送天数只会减少,不会增加。这存在一个单调性,因此我们可以使用二分查找的方法来寻找最小的运载能力。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def shipWithinDays(self, weights: List[int], days: int) -> int: @@ -99,10 +93,6 @@ class Solution: return left + bisect_left(range(left, right), True, key=check) ``` -### **Java** - - - ```java class Solution { public int shipWithinDays(int[] weights, int days) { @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +159,6 @@ public: }; ``` -### **Go** - ```go func shipWithinDays(weights []int, days int) int { var left, right int @@ -197,8 +183,6 @@ func shipWithinDays(weights []int, days int) int { } ``` -### **TypeScript** - ```ts function shipWithinDays(weights: number[], days: number): number { let left = 0; @@ -231,10 +215,6 @@ function shipWithinDays(weights: number[], days: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1011.Capacity To Ship Packages Within D Days/README_EN.md b/solution/1000-1099/1011.Capacity To Ship Packages Within D Days/README_EN.md index fba3de27f9ece..fe0e67e46cd33 100644 --- a/solution/1000-1099/1011.Capacity To Ship Packages Within D Days/README_EN.md +++ b/solution/1000-1099/1011.Capacity To Ship Packages Within D Days/README_EN.md @@ -59,12 +59,10 @@ Note that the cargo must be shipped in the order given, so using a ship of capac ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python class Solution: def shipWithinDays(self, weights: List[int], days: int) -> int: @@ -81,8 +79,6 @@ class Solution: return left + bisect_left(range(left, right), True, key=check) ``` -### **Java** - ```java class Solution { public int shipWithinDays(int[] weights, int days) { @@ -116,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +145,6 @@ public: }; ``` -### **Go** - ```go func shipWithinDays(weights []int, days int) int { var left, right int @@ -177,8 +169,6 @@ func shipWithinDays(weights []int, days int) int { } ``` -### **TypeScript** - ```ts function shipWithinDays(weights: number[], days: number): number { let left = 0; @@ -211,10 +201,6 @@ function shipWithinDays(weights: number[], days: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1012.Numbers With Repeated Digits/README.md b/solution/1000-1099/1012.Numbers With Repeated Digits/README.md index 71009799829c2..480b487f53b8a 100644 --- a/solution/1000-1099/1012.Numbers With Repeated Digits/README.md +++ b/solution/1000-1099/1012.Numbers With Repeated Digits/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:状态压缩 + 数位 DP** +### 方法一:状态压缩 + 数位 DP 题目要求统计 $[1,..n]$ 中至少有一位重复的数字的个数,我们可以换一种思路,用一个函数 $f(n)$ 统计 $[1,..n]$ 中没有重复数字的个数,那么答案就是 $n - f(n)$。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def numDupDigitsAtMostN(self, n: int) -> int: @@ -114,38 +108,6 @@ class Solution: return ans ``` -```python -class Solution: - def numDupDigitsAtMostN(self, n: int) -> int: - return n - self.f(n) - - def f(self, n: int) -> int: - @cache - def dfs(pos: int, mask: int, lead: bool, limit: bool) -> int: - if pos < 0: - return int(lead) ^ 1 - up = nums[pos] if limit else 9 - ans = 0 - for i in range(up + 1): - if mask >> i & 1: - continue - if i == 0 and lead: - ans += dfs(pos - 1, mask, lead, limit and i == up) - else: - ans += dfs(pos - 1, mask | 1 << i, False, limit and i == up) - return ans - - nums = [] - while n: - nums.append(n % 10) - n //= 10 - return dfs(len(nums) - 1, 0, True, True) -``` - -### **Java** - - - ```java class Solution { public int numDupDigitsAtMostN(int n) { @@ -189,6 +151,170 @@ class Solution { } ``` +```cpp +class Solution { +public: + int numDupDigitsAtMostN(int n) { + return n - f(n); + } + + int f(int n) { + int ans = 0; + vector digits; + while (n) { + digits.push_back(n % 10); + n /= 10; + } + int m = digits.size(); + vector vis(10); + for (int i = 1; i < m; ++i) { + ans += 9 * A(9, i - 1); + } + for (int i = m - 1; ~i; --i) { + int v = digits[i]; + for (int j = i == m - 1 ? 1 : 0; j < v; ++j) { + if (!vis[j]) { + ans += A(10 - (m - i), i); + } + } + if (vis[v]) { + break; + } + vis[v] = true; + if (i == 0) { + ++ans; + } + } + return ans; + } + + int A(int m, int n) { + return n == 0 ? 1 : A(m, n - 1) * (m - n + 1); + } +}; +``` + +```go +func numDupDigitsAtMostN(n int) int { + return n - f(n) +} + +func f(n int) int { + digits := []int{} + for n != 0 { + digits = append(digits, n%10) + n /= 10 + } + m := len(digits) + vis := make([]bool, 10) + ans := 0 + for i := 1; i < m; i++ { + ans += 9 * A(9, i-1) + } + for i := m - 1; i >= 0; i-- { + v := digits[i] + j := 0 + if i == m-1 { + j = 1 + } + for ; j < v; j++ { + if !vis[j] { + ans += A(10-(m-i), i) + } + } + if vis[v] { + break + } + vis[v] = true + if i == 0 { + ans++ + } + } + return ans +} + +func A(m, n int) int { + if n == 0 { + return 1 + } + return A(m, n-1) * (m - n + 1) +} +``` + +```ts +function numDupDigitsAtMostN(n: number): number { + return n - f(n); +} + +function f(n: number): number { + const nums: number[] = []; + let i = -1; + for (; n; n = Math.floor(n / 10)) { + nums[++i] = n % 10; + } + const dp = Array.from({ length: 11 }, () => Array(1 << 11).fill(-1)); + const dfs = (pos: number, mask: number, lead: boolean, limit: boolean): number => { + if (pos < 0) { + return lead ? 0 : 1; + } + if (!lead && !limit && dp[pos][mask] !== -1) { + return dp[pos][mask]; + } + const up = limit ? nums[pos] : 9; + let ans = 0; + for (let i = 0; i <= up; ++i) { + if ((mask >> i) & 1) { + continue; + } + if (lead && i === 0) { + ans += dfs(pos - 1, mask, lead, limit && i === up); + } else { + ans += dfs(pos - 1, mask | (1 << i), false, limit && i === up); + } + } + if (!lead && !limit) { + dp[pos][mask] = ans; + } + return ans; + }; + return dfs(i, 0, true, true); +} +``` + + + +### 方法二 + + + +```python +class Solution: + def numDupDigitsAtMostN(self, n: int) -> int: + return n - self.f(n) + + def f(self, n: int) -> int: + @cache + def dfs(pos: int, mask: int, lead: bool, limit: bool) -> int: + if pos < 0: + return int(lead) ^ 1 + up = nums[pos] if limit else 9 + ans = 0 + for i in range(up + 1): + if mask >> i & 1: + continue + if i == 0 and lead: + ans += dfs(pos - 1, mask, lead, limit and i == up) + else: + ans += dfs(pos - 1, mask | 1 << i, False, limit and i == up) + return ans + + nums = [] + while n: + nums.append(n % 10) + n //= 10 + return dfs(len(nums) - 1, 0, True, True) +``` + ```java class Solution { private int[] nums = new int[11]; @@ -233,51 +359,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numDupDigitsAtMostN(int n) { - return n - f(n); - } - - int f(int n) { - int ans = 0; - vector digits; - while (n) { - digits.push_back(n % 10); - n /= 10; - } - int m = digits.size(); - vector vis(10); - for (int i = 1; i < m; ++i) { - ans += 9 * A(9, i - 1); - } - for (int i = m - 1; ~i; --i) { - int v = digits[i]; - for (int j = i == m - 1 ? 1 : 0; j < v; ++j) { - if (!vis[j]) { - ans += A(10 - (m - i), i); - } - } - if (vis[v]) { - break; - } - vis[v] = true; - if (i == 0) { - ++ans; - } - } - return ans; - } - - int A(int m, int n) { - return n == 0 ? 1 : A(m, n - 1) * (m - n + 1); - } -}; -``` - ```cpp class Solution { public: @@ -325,55 +406,6 @@ private: }; ``` -### **Go** - -```go -func numDupDigitsAtMostN(n int) int { - return n - f(n) -} - -func f(n int) int { - digits := []int{} - for n != 0 { - digits = append(digits, n%10) - n /= 10 - } - m := len(digits) - vis := make([]bool, 10) - ans := 0 - for i := 1; i < m; i++ { - ans += 9 * A(9, i-1) - } - for i := m - 1; i >= 0; i-- { - v := digits[i] - j := 0 - if i == m-1 { - j = 1 - } - for ; j < v; j++ { - if !vis[j] { - ans += A(10-(m-i), i) - } - } - if vis[v] { - break - } - vis[v] = true - if i == 0 { - ans++ - } - } - return ans -} - -func A(m, n int) int { - if n == 0 { - return 1 - } - return A(m, n-1) * (m - n + 1) -} -``` - ```go func numDupDigitsAtMostN(n int) int { return n - f(n) @@ -425,52 +457,6 @@ func f(n int) int { } ``` -### **TypeScript** - -```ts -function numDupDigitsAtMostN(n: number): number { - return n - f(n); -} - -function f(n: number): number { - const nums: number[] = []; - let i = -1; - for (; n; n = Math.floor(n / 10)) { - nums[++i] = n % 10; - } - const dp = Array.from({ length: 11 }, () => Array(1 << 11).fill(-1)); - const dfs = (pos: number, mask: number, lead: boolean, limit: boolean): number => { - if (pos < 0) { - return lead ? 0 : 1; - } - if (!lead && !limit && dp[pos][mask] !== -1) { - return dp[pos][mask]; - } - const up = limit ? nums[pos] : 9; - let ans = 0; - for (let i = 0; i <= up; ++i) { - if ((mask >> i) & 1) { - continue; - } - if (lead && i === 0) { - ans += dfs(pos - 1, mask, lead, limit && i === up); - } else { - ans += dfs(pos - 1, mask | (1 << i), false, limit && i === up); - } - } - if (!lead && !limit) { - dp[pos][mask] = ans; - } - return ans; - }; - return dfs(i, 0, true, true); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1012.Numbers With Repeated Digits/README_EN.md b/solution/1000-1099/1012.Numbers With Repeated Digits/README_EN.md index 2683fe7f8a63a..5676cb98f1b32 100644 --- a/solution/1000-1099/1012.Numbers With Repeated Digits/README_EN.md +++ b/solution/1000-1099/1012.Numbers With Repeated Digits/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,36 +73,6 @@ class Solution: return ans ``` -```python -class Solution: - def numDupDigitsAtMostN(self, n: int) -> int: - return n - self.f(n) - - def f(self, n: int) -> int: - @cache - def dfs(pos: int, mask: int, lead: bool, limit: bool) -> int: - if pos < 0: - return int(lead) ^ 1 - up = nums[pos] if limit else 9 - ans = 0 - for i in range(up + 1): - if mask >> i & 1: - continue - if i == 0 and lead: - ans += dfs(pos - 1, mask, lead, limit and i == up) - else: - ans += dfs(pos - 1, mask | 1 << i, False, limit and i == up) - return ans - - nums = [] - while n: - nums.append(n % 10) - n //= 10 - return dfs(len(nums) - 1, 0, True, True) -``` - -### **Java** - ```java class Solution { public int numDupDigitsAtMostN(int n) { @@ -146,6 +116,170 @@ class Solution { } ``` +```cpp +class Solution { +public: + int numDupDigitsAtMostN(int n) { + return n - f(n); + } + + int f(int n) { + int ans = 0; + vector digits; + while (n) { + digits.push_back(n % 10); + n /= 10; + } + int m = digits.size(); + vector vis(10); + for (int i = 1; i < m; ++i) { + ans += 9 * A(9, i - 1); + } + for (int i = m - 1; ~i; --i) { + int v = digits[i]; + for (int j = i == m - 1 ? 1 : 0; j < v; ++j) { + if (!vis[j]) { + ans += A(10 - (m - i), i); + } + } + if (vis[v]) { + break; + } + vis[v] = true; + if (i == 0) { + ++ans; + } + } + return ans; + } + + int A(int m, int n) { + return n == 0 ? 1 : A(m, n - 1) * (m - n + 1); + } +}; +``` + +```go +func numDupDigitsAtMostN(n int) int { + return n - f(n) +} + +func f(n int) int { + digits := []int{} + for n != 0 { + digits = append(digits, n%10) + n /= 10 + } + m := len(digits) + vis := make([]bool, 10) + ans := 0 + for i := 1; i < m; i++ { + ans += 9 * A(9, i-1) + } + for i := m - 1; i >= 0; i-- { + v := digits[i] + j := 0 + if i == m-1 { + j = 1 + } + for ; j < v; j++ { + if !vis[j] { + ans += A(10-(m-i), i) + } + } + if vis[v] { + break + } + vis[v] = true + if i == 0 { + ans++ + } + } + return ans +} + +func A(m, n int) int { + if n == 0 { + return 1 + } + return A(m, n-1) * (m - n + 1) +} +``` + +```ts +function numDupDigitsAtMostN(n: number): number { + return n - f(n); +} + +function f(n: number): number { + const nums: number[] = []; + let i = -1; + for (; n; n = Math.floor(n / 10)) { + nums[++i] = n % 10; + } + const dp = Array.from({ length: 11 }, () => Array(1 << 11).fill(-1)); + const dfs = (pos: number, mask: number, lead: boolean, limit: boolean): number => { + if (pos < 0) { + return lead ? 0 : 1; + } + if (!lead && !limit && dp[pos][mask] !== -1) { + return dp[pos][mask]; + } + const up = limit ? nums[pos] : 9; + let ans = 0; + for (let i = 0; i <= up; ++i) { + if ((mask >> i) & 1) { + continue; + } + if (lead && i === 0) { + ans += dfs(pos - 1, mask, lead, limit && i === up); + } else { + ans += dfs(pos - 1, mask | (1 << i), false, limit && i === up); + } + } + if (!lead && !limit) { + dp[pos][mask] = ans; + } + return ans; + }; + return dfs(i, 0, true, true); +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def numDupDigitsAtMostN(self, n: int) -> int: + return n - self.f(n) + + def f(self, n: int) -> int: + @cache + def dfs(pos: int, mask: int, lead: bool, limit: bool) -> int: + if pos < 0: + return int(lead) ^ 1 + up = nums[pos] if limit else 9 + ans = 0 + for i in range(up + 1): + if mask >> i & 1: + continue + if i == 0 and lead: + ans += dfs(pos - 1, mask, lead, limit and i == up) + else: + ans += dfs(pos - 1, mask | 1 << i, False, limit and i == up) + return ans + + nums = [] + while n: + nums.append(n % 10) + n //= 10 + return dfs(len(nums) - 1, 0, True, True) +``` + ```java class Solution { private int[] nums = new int[11]; @@ -190,51 +324,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numDupDigitsAtMostN(int n) { - return n - f(n); - } - - int f(int n) { - int ans = 0; - vector digits; - while (n) { - digits.push_back(n % 10); - n /= 10; - } - int m = digits.size(); - vector vis(10); - for (int i = 1; i < m; ++i) { - ans += 9 * A(9, i - 1); - } - for (int i = m - 1; ~i; --i) { - int v = digits[i]; - for (int j = i == m - 1 ? 1 : 0; j < v; ++j) { - if (!vis[j]) { - ans += A(10 - (m - i), i); - } - } - if (vis[v]) { - break; - } - vis[v] = true; - if (i == 0) { - ++ans; - } - } - return ans; - } - - int A(int m, int n) { - return n == 0 ? 1 : A(m, n - 1) * (m - n + 1); - } -}; -``` - ```cpp class Solution { public: @@ -282,55 +371,6 @@ private: }; ``` -### **Go** - -```go -func numDupDigitsAtMostN(n int) int { - return n - f(n) -} - -func f(n int) int { - digits := []int{} - for n != 0 { - digits = append(digits, n%10) - n /= 10 - } - m := len(digits) - vis := make([]bool, 10) - ans := 0 - for i := 1; i < m; i++ { - ans += 9 * A(9, i-1) - } - for i := m - 1; i >= 0; i-- { - v := digits[i] - j := 0 - if i == m-1 { - j = 1 - } - for ; j < v; j++ { - if !vis[j] { - ans += A(10-(m-i), i) - } - } - if vis[v] { - break - } - vis[v] = true - if i == 0 { - ans++ - } - } - return ans -} - -func A(m, n int) int { - if n == 0 { - return 1 - } - return A(m, n-1) * (m - n + 1) -} -``` - ```go func numDupDigitsAtMostN(n int) int { return n - f(n) @@ -382,52 +422,6 @@ func f(n int) int { } ``` -### **TypeScript** - -```ts -function numDupDigitsAtMostN(n: number): number { - return n - f(n); -} - -function f(n: number): number { - const nums: number[] = []; - let i = -1; - for (; n; n = Math.floor(n / 10)) { - nums[++i] = n % 10; - } - const dp = Array.from({ length: 11 }, () => Array(1 << 11).fill(-1)); - const dfs = (pos: number, mask: number, lead: boolean, limit: boolean): number => { - if (pos < 0) { - return lead ? 0 : 1; - } - if (!lead && !limit && dp[pos][mask] !== -1) { - return dp[pos][mask]; - } - const up = limit ? nums[pos] : 9; - let ans = 0; - for (let i = 0; i <= up; ++i) { - if ((mask >> i) & 1) { - continue; - } - if (lead && i === 0) { - ans += dfs(pos - 1, mask, lead, limit && i === up); - } else { - ans += dfs(pos - 1, mask | (1 << i), false, limit && i === up); - } - } - if (!lead && !limit) { - dp[pos][mask] = ans; - } - return ans; - }; - return dfs(i, 0, true, true); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1013.Partition Array Into Three Parts With Equal Sum/README.md b/solution/1000-1099/1013.Partition Array Into Three Parts With Equal Sum/README.md index ec342636746c4..0567682575269 100644 --- a/solution/1000-1099/1013.Partition Array Into Three Parts With Equal Sum/README.md +++ b/solution/1000-1099/1013.Partition Array Into Three Parts With Equal Sum/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 先遍历数组 `arr`,得到数组所有元素的和,记为 `s`。如果 `s` 不能被 3 整除,那么数组 `arr` 不能被分成和相等的三个部分,直接返回 `false`。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def canThreePartsEqualSum(self, arr: List[int]) -> bool: @@ -83,10 +77,6 @@ class Solution: return i < j - 1 ``` -### **Java** - - - ```java class Solution { public boolean canThreePartsEqualSum(int[] arr) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +136,6 @@ public: }; ``` -### **Go** - ```go func canThreePartsEqualSum(arr []int) bool { s := 0 @@ -179,10 +165,6 @@ func canThreePartsEqualSum(arr []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1013.Partition Array Into Three Parts With Equal Sum/README_EN.md b/solution/1000-1099/1013.Partition Array Into Three Parts With Equal Sum/README_EN.md index 480f1ef205ed8..054b5a986b6f9 100644 --- a/solution/1000-1099/1013.Partition Array Into Three Parts With Equal Sum/README_EN.md +++ b/solution/1000-1099/1013.Partition Array Into Three Parts With Equal Sum/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return i < j - 1 ``` -### **Java** - ```java class Solution { public boolean canThreePartsEqualSum(int[] arr) { @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +126,6 @@ public: }; ``` -### **Go** - ```go func canThreePartsEqualSum(arr []int) bool { s := 0 @@ -161,10 +155,6 @@ func canThreePartsEqualSum(arr []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1014.Best Sightseeing Pair/README.md b/solution/1000-1099/1014.Best Sightseeing Pair/README.md index bc80feb3d7fe7..a8cb1af338755 100644 --- a/solution/1000-1099/1014.Best Sightseeing Pair/README.md +++ b/solution/1000-1099/1014.Best Sightseeing Pair/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:枚举 + 维护前缀最大值** +### 方法一:枚举 + 维护前缀最大值 我们可以在 $[1,..n - 1]$ 的范围内枚举 $j$,那么我们要在 $[0,..j - 1]$ 的范围内找到一个 $i$,使得 $values[i] + values[j] + i - j$ 的值最大。我们可以维护一个前缀最大值,即 $values[i] + i$ 的最大值,那么我们只需要在枚举 $j$ 的过程中,不断地更新答案即可。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python class Solution: def maxScoreSightseeingPair(self, values: List[int]) -> int: @@ -64,10 +58,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxScoreSightseeingPair(int[] values) { @@ -81,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +85,6 @@ public: }; ``` -### **Go** - ```go func maxScoreSightseeingPair(values []int) (ans int) { for j, mx := 1, values[0]; j < len(values); j++ { @@ -109,8 +95,6 @@ func maxScoreSightseeingPair(values []int) (ans int) { } ``` -### **TypeScript** - ```ts function maxScoreSightseeingPair(values: number[]): number { let ans = 0; @@ -123,10 +107,6 @@ function maxScoreSightseeingPair(values: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1014.Best Sightseeing Pair/README_EN.md b/solution/1000-1099/1014.Best Sightseeing Pair/README_EN.md index 81f9c28b4b6b8..69741e05409c7 100644 --- a/solution/1000-1099/1014.Best Sightseeing Pair/README_EN.md +++ b/solution/1000-1099/1014.Best Sightseeing Pair/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -50,8 +50,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxScoreSightseeingPair(int[] values) { @@ -65,8 +63,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -81,8 +77,6 @@ public: }; ``` -### **Go** - ```go func maxScoreSightseeingPair(values []int) (ans int) { for j, mx := 1, values[0]; j < len(values); j++ { @@ -93,8 +87,6 @@ func maxScoreSightseeingPair(values []int) (ans int) { } ``` -### **TypeScript** - ```ts function maxScoreSightseeingPair(values: number[]): number { let ans = 0; @@ -107,10 +99,6 @@ function maxScoreSightseeingPair(values: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1015.Smallest Integer Divisible by K/README.md b/solution/1000-1099/1015.Smallest Integer Divisible by K/README.md index 9e0d950b76cbc..a404501cbc93c 100644 --- a/solution/1000-1099/1015.Smallest Integer Divisible by K/README.md +++ b/solution/1000-1099/1015.Smallest Integer Divisible by K/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 我们注意到,正整数 $n$ 初始值为 $1$,每次乘以 $10$ 后再加 $1$,即 $n = n \times 10 + 1$,而 $(n \times 10 + 1) \bmod k = ((n \bmod k) \times 10 + 1) \bmod k$,因此我们可以通过计算 $n \bmod k$ 来判断 $n$ 是否能被 $k$ 整除。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def smallestRepunitDivByK(self, k: int) -> int: @@ -72,10 +66,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int smallestRepunitDivByK(int k) { @@ -91,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +97,6 @@ public: }; ``` -### **Go** - ```go func smallestRepunitDivByK(k int) int { n := 1 % k @@ -124,8 +110,6 @@ func smallestRepunitDivByK(k int) int { } ``` -### **TypeScript** - ```ts function smallestRepunitDivByK(k: number): number { let n = 1 % k; @@ -139,10 +123,6 @@ function smallestRepunitDivByK(k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1015.Smallest Integer Divisible by K/README_EN.md b/solution/1000-1099/1015.Smallest Integer Divisible by K/README_EN.md index 4def10440663b..4c1b914a4ce7f 100644 --- a/solution/1000-1099/1015.Smallest Integer Divisible by K/README_EN.md +++ b/solution/1000-1099/1015.Smallest Integer Divisible by K/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int smallestRepunitDivByK(int k) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +90,6 @@ public: }; ``` -### **Go** - ```go func smallestRepunitDivByK(k int) int { n := 1 % k @@ -109,8 +103,6 @@ func smallestRepunitDivByK(k int) int { } ``` -### **TypeScript** - ```ts function smallestRepunitDivByK(k: number): number { let n = 1 % k; @@ -124,10 +116,6 @@ function smallestRepunitDivByK(k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README.md b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README.md index 37f33740cb086..8d143d2b51d95 100644 --- a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README.md +++ b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 我们注意到,字符串 $s$ 的长度不超过 $1000$,所以字符串 $s$ 能表示不超过 $1000$ 个 二进制整数,因此,如果 $n \gt 1000$,那么 $s$ 肯定不能表示 $[1,.. n]$ 范围内的所有整数的二进制表示。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python class Solution: def queryString(self, s: str, n: int) -> bool: @@ -62,10 +56,6 @@ class Solution: return all(bin(i)[2:] in s for i in range(n, n // 2, -1)) ``` -### **Java** - - - ```java class Solution { public boolean queryString(String s, int n) { @@ -82,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +91,6 @@ public: }; ``` -### **Go** - ```go func queryString(s string, n int) bool { if n > 1000 { @@ -119,8 +105,6 @@ func queryString(s string, n int) bool { } ``` -### **TypeScript** - ```ts function queryString(s: string, n: number): boolean { if (n > 1000) { @@ -135,10 +119,6 @@ function queryString(s: string, n: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README_EN.md b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README_EN.md index cc35d75bdd5b0..0746eee00ebb4 100644 --- a/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README_EN.md +++ b/solution/1000-1099/1016.Binary String With Substrings Representing 1 To N/README_EN.md @@ -27,9 +27,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -39,8 +39,6 @@ class Solution: return all(bin(i)[2:] in s for i in range(n, n // 2, -1)) ``` -### **Java** - ```java class Solution { public boolean queryString(String s, int n) { @@ -57,8 +55,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -78,8 +74,6 @@ public: }; ``` -### **Go** - ```go func queryString(s string, n int) bool { if n > 1000 { @@ -94,8 +88,6 @@ func queryString(s string, n int) bool { } ``` -### **TypeScript** - ```ts function queryString(s: string, n: number): boolean { if (n > 1000) { @@ -110,10 +102,6 @@ function queryString(s: string, n: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1017.Convert to Base -2/README.md b/solution/1000-1099/1017.Convert to Base -2/README.md index 9a33beab857ce..5d0f55f3b73fd 100644 --- a/solution/1000-1099/1017.Convert to Base -2/README.md +++ b/solution/1000-1099/1017.Convert to Base -2/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以判断 $n$ 从低位到高位的每一位,如果该位为 $1$,那么答案的该位为 $1$,否则为 $0$。如果该位为 $1$,那么我们需要将 $n$ 减去 $k$。接下来我们更新 $n = \lfloor n / 2 \rfloor$, $k = -k$。继续判断下一位。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def baseNeg2(self, n: int) -> str: @@ -82,10 +76,6 @@ class Solution: return ''.join(ans[::-1]) or '0' ``` -### **Java** - - - ```java class Solution { public String baseNeg2(int n) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func baseNeg2(n int) string { if n == 0 { @@ -162,8 +148,6 @@ func baseNeg2(n int) string { } ``` -### **TypeScript** - ```ts function baseNeg2(n: number): string { if (n === 0) { @@ -185,10 +169,6 @@ function baseNeg2(n: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1017.Convert to Base -2/README_EN.md b/solution/1000-1099/1017.Convert to Base -2/README_EN.md index 8472241f797d1..e231a37daaa68 100644 --- a/solution/1000-1099/1017.Convert to Base -2/README_EN.md +++ b/solution/1000-1099/1017.Convert to Base -2/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return ''.join(ans[::-1]) or '0' ``` -### **Java** - ```java class Solution { public String baseNeg2(int n) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +110,6 @@ public: }; ``` -### **Go** - ```go func baseNeg2(n int) string { if n == 0 { @@ -140,8 +134,6 @@ func baseNeg2(n int) string { } ``` -### **TypeScript** - ```ts function baseNeg2(n: number): string { if (n === 0) { @@ -163,10 +155,6 @@ function baseNeg2(n: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1018.Binary Prefix Divisible By 5/README.md b/solution/1000-1099/1018.Binary Prefix Divisible By 5/README.md index 3228d2c2889e0..835eef5dc782d 100644 --- a/solution/1000-1099/1018.Binary Prefix Divisible By 5/README.md +++ b/solution/1000-1099/1018.Binary Prefix Divisible By 5/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 遍历数组,每一次遍历都将当前数字加到前面的数字上,然后对 $5$ 取模,如果结果为 $0$,则当前数字可以被 $5$ 整除,答案设置为 `true`,否则为 `false`。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def prefixesDivBy5(self, nums: List[int]) -> List[bool]: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List prefixesDivBy5(int[] nums) { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +93,6 @@ public: }; ``` -### **Go** - ```go func prefixesDivBy5(nums []int) (ans []bool) { x := 0 @@ -118,8 +104,6 @@ func prefixesDivBy5(nums []int) (ans []bool) { } ``` -### **TypeScript** - ```ts function prefixesDivBy5(nums: number[]): boolean[] { const ans: boolean[] = []; @@ -132,10 +116,6 @@ function prefixesDivBy5(nums: number[]): boolean[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1018.Binary Prefix Divisible By 5/README_EN.md b/solution/1000-1099/1018.Binary Prefix Divisible By 5/README_EN.md index af2ba08ec23c8..b13b63d04d2f3 100644 --- a/solution/1000-1099/1018.Binary Prefix Divisible By 5/README_EN.md +++ b/solution/1000-1099/1018.Binary Prefix Divisible By 5/README_EN.md @@ -41,9 +41,9 @@ Only the first number is divisible by 5, so answer[0] is true. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List prefixesDivBy5(int[] nums) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,8 +85,6 @@ public: }; ``` -### **Go** - ```go func prefixesDivBy5(nums []int) (ans []bool) { x := 0 @@ -102,8 +96,6 @@ func prefixesDivBy5(nums []int) (ans []bool) { } ``` -### **TypeScript** - ```ts function prefixesDivBy5(nums: number[]): boolean[] { const ans: boolean[] = []; @@ -116,10 +108,6 @@ function prefixesDivBy5(nums: number[]): boolean[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1019.Next Greater Node In Linked List/README.md b/solution/1000-1099/1019.Next Greater Node In Linked List/README.md index 751e5fbd3e4e5..da762ff2ba3bd 100644 --- a/solution/1000-1099/1019.Next Greater Node In Linked List/README.md +++ b/solution/1000-1099/1019.Next Greater Node In Linked List/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 题目要求找到链表中每个节点的下一个更大的节点,即找到链表中每个节点的右边第一个比它大的节点。我们先遍历链表,将链表中的值存入数组 $nums$ 中。那么对于数组 $nums$ 中的每个元素,我们只需要找到它右边第一个比它大的元素即可。求下一个更大的元素的问题可以使用单调栈来解决。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -163,8 +151,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -194,42 +180,6 @@ func nextLargerNodes(head *ListNode) []int { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @return {number[]} - */ -var nextLargerNodes = function (head) { - const nums = []; - while (head) { - nums.push(head.val); - head = head.next; - } - const stk = []; - const n = nums.length; - const ans = new Array(n).fill(0); - for (let i = n - 1; i >= 0; --i) { - while (stk.length && stk[stk.length - 1] <= nums[i]) { - stk.pop(); - } - ans[i] = stk.length ? stk[stk.length - 1] : 0; - stk.push(nums[i]); - } - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -263,46 +213,6 @@ function nextLargerNodes(head: ListNode | null): number[] { } ``` -```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) - * } - * } - */ - -interface Item { - index: number; - val: number; -} - -function nextLargerNodes(head: ListNode | null): number[] { - const res: number[] = []; - const stack: Item[] = []; - let cur = head; - for (let i = 0; cur != null; i++) { - res.push(0); - const { val, next } = cur; - while (stack.length !== 0 && stack[stack.length - 1].val < val) { - res[stack.pop().index] = val; - } - stack.push({ - val, - index: i, - }); - cur = next; - } - return res; -} -``` - -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -350,10 +260,82 @@ impl Solution { } ``` -### **...** - +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {number[]} + */ +var nextLargerNodes = function (head) { + const nums = []; + while (head) { + nums.push(head.val); + head = head.next; + } + const stk = []; + const n = nums.length; + const ans = new Array(n).fill(0); + for (let i = n - 1; i >= 0; --i) { + while (stk.length && stk[stk.length - 1] <= nums[i]) { + stk.pop(); + } + ans[i] = stk.length ? stk[stk.length - 1] : 0; + stk.push(nums[i]); + } + return ans; +}; ``` + + +### 方法二 + + + +```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) + * } + * } + */ + +interface Item { + index: number; + val: number; +} + +function nextLargerNodes(head: ListNode | null): number[] { + const res: number[] = []; + const stack: Item[] = []; + let cur = head; + for (let i = 0; cur != null; i++) { + res.push(0); + const { val, next } = cur; + while (stack.length !== 0 && stack[stack.length - 1].val < val) { + res[stack.pop().index] = val; + } + stack.push({ + val, + index: i, + }); + cur = next; + } + return res; +} ``` + + diff --git a/solution/1000-1099/1019.Next Greater Node In Linked List/README_EN.md b/solution/1000-1099/1019.Next Greater Node In Linked List/README_EN.md index 75daaff8b7012..7d8f95ba62379 100644 --- a/solution/1000-1099/1019.Next Greater Node In Linked List/README_EN.md +++ b/solution/1000-1099/1019.Next Greater Node In Linked List/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -137,8 +133,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -168,42 +162,6 @@ func nextLargerNodes(head *ListNode) []int { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @return {number[]} - */ -var nextLargerNodes = function (head) { - const nums = []; - while (head) { - nums.push(head.val); - head = head.next; - } - const stk = []; - const n = nums.length; - const ans = new Array(n).fill(0); - for (let i = n - 1; i >= 0; --i) { - while (stk.length && stk[stk.length - 1] <= nums[i]) { - stk.pop(); - } - ans[i] = stk.length ? stk[stk.length - 1] : 0; - stk.push(nums[i]); - } - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -237,46 +195,6 @@ function nextLargerNodes(head: ListNode | null): number[] { } ``` -```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) - * } - * } - */ - -interface Item { - index: number; - val: number; -} - -function nextLargerNodes(head: ListNode | null): number[] { - const res: number[] = []; - const stack: Item[] = []; - let cur = head; - for (let i = 0; cur != null; i++) { - res.push(0); - const { val, next } = cur; - while (stack.length !== 0 && stack[stack.length - 1].val < val) { - res[stack.pop().index] = val; - } - stack.push({ - val, - index: i, - }); - cur = next; - } - return res; -} -``` - -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -324,10 +242,82 @@ impl Solution { } ``` -### **...** - +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {number[]} + */ +var nextLargerNodes = function (head) { + const nums = []; + while (head) { + nums.push(head.val); + head = head.next; + } + const stk = []; + const n = nums.length; + const ans = new Array(n).fill(0); + for (let i = n - 1; i >= 0; --i) { + while (stk.length && stk[stk.length - 1] <= nums[i]) { + stk.pop(); + } + ans[i] = stk.length ? stk[stk.length - 1] : 0; + stk.push(nums[i]); + } + return ans; +}; ``` + + +### 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) + * } + * } + */ + +interface Item { + index: number; + val: number; +} + +function nextLargerNodes(head: ListNode | null): number[] { + const res: number[] = []; + const stack: Item[] = []; + let cur = head; + for (let i = 0; cur != null; i++) { + res.push(0); + const { val, next } = cur; + while (stack.length !== 0 && stack[stack.length - 1].val < val) { + res[stack.pop().index] = val; + } + stack.push({ + val, + index: i, + }); + cur = next; + } + return res; +} ``` + + diff --git a/solution/1000-1099/1020.Number of Enclaves/README.md b/solution/1000-1099/1020.Number of Enclaves/README.md index 92a4bdc53018b..7edb43abec1bf 100644 --- a/solution/1000-1099/1020.Number of Enclaves/README.md +++ b/solution/1000-1099/1020.Number of Enclaves/README.md @@ -43,32 +43,14 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们可以从边界上的陆地开始进行深度优先搜索,将所有与边界相连的陆地都标记为 $0$。最后,统计剩余的 $1$ 的个数,即为答案。 时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。 -**方法二:BFS** - -我们也可以使用广度优先搜索的方法,将边界上的陆地入队,然后进行广度优先搜索,将所有与边界相连的陆地都标记为 $0$。最后,统计剩余的 $1$ 的个数,即为答案。 - -时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。 - -**方法三:并查集** - -我们还可以利用并查集的方法,将边界上的陆地与一个虚拟的节点 $(m, n)$ 进行合并,然后遍历矩阵中的所有陆地,将其与上下左右的陆地进行合并。最后,统计所有与虚拟节点 $(m, n)$ 不连通的陆地的个数,即为答案。 - -时间复杂度 $O(m \times n \alpha(m \times n))$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数,而 $\alpha$ 为 [阿克曼函数](https://zh.wikipedia.org/wiki/%E9%98%BF%E5%85%8B%E6%9B%BC%E5%87%BD%E6%95%B8) 的反函数。 - -### **Python3** - - - ```python class Solution: def numEnclaves(self, grid: List[List[int]]) -> int: @@ -88,75 +70,6 @@ class Solution: return sum(v for row in grid for v in row) ``` -```python -class Solution: - def numEnclaves(self, grid: List[List[int]]) -> int: - m, n = len(grid), len(grid[0]) - q = deque() - for i in range(m): - for j in range(n): - if grid[i][j] and (i == 0 or i == m - 1 or j == 0 or j == n - 1): - q.append((i, j)) - grid[i][j] = 0 - 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 x >= 0 and x < m and y >= 0 and y < n and grid[x][y]: - q.append((x, y)) - grid[x][y] = 0 - return sum(v for row in grid for v in row) -``` - -```python -class UnionFind: - def __init__(self, n): - self.p = list(range(n)) - self.size = [1] * n - - def find(self, x): - if self.p[x] != x: - self.p[x] = self.find(self.p[x]) - return self.p[x] - - def union(self, a, b): - pa, pb = self.find(a), self.find(b) - if pa != pb: - if self.size[pa] > self.size[pb]: - self.p[pb] = pa - self.size[pa] += self.size[pb] - else: - self.p[pa] = pb - self.size[pb] += self.size[pa] - - -class Solution: - def numEnclaves(self, grid: List[List[int]]) -> int: - m, n = len(grid), len(grid[0]) - uf = UnionFind(m * n + 1) - dirs = (-1, 0, 1, 0, -1) - for i, row in enumerate(grid): - for j, v in enumerate(row): - if v: - if i == 0 or i == m - 1 or j == 0 or j == n - 1: - uf.union(i * n + j, m * n) - else: - for a, b in pairwise(dirs): - x, y = i + a, j + b - if x >= 0 and x < m and y >= 0 and y < n and grid[x][y]: - uf.union(i * n + j, x * n + y) - return sum( - grid[i][j] == 1 and uf.find(i * n + j) != uf.find(m * n) - for i in range(m) - for j in range(n) - ) -``` - -### **Java** - - - ```java class Solution { private int m; @@ -196,6 +109,172 @@ class Solution { } ``` +```cpp +class Solution { +public: + int numEnclaves(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int dirs[5] = {-1, 0, 1, 0, -1}; + function dfs = [&](int i, int j) { + grid[i][j] = 0; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y]) { + dfs(x, y); + } + } + }; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] && (i == 0 || i == m - 1 || j == 0 || j == n - 1)) { + dfs(i, j); + } + } + } + int ans = 0; + for (auto& row : grid) { + for (auto& v : row) { + ans += v; + } + } + return ans; + } +}; +``` + +```go +func numEnclaves(grid [][]int) (ans int) { + m, n := len(grid), len(grid[0]) + dirs := [5]int{-1, 0, 1, 0, -1} + var dfs func(i, j int) + dfs = func(i, j int) { + grid[i][j] = 0 + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 { + dfs(x, y) + } + } + } + for i, row := range grid { + for j, v := range row { + if v == 1 && (i == 0 || i == m-1 || j == 0 || j == n-1) { + dfs(i, j) + } + } + } + for _, row := range grid { + for _, v := range row { + ans += v + } + } + return +} +``` + +```ts +function numEnclaves(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const dirs = [-1, 0, 1, 0, -1]; + const dfs = (i: number, j: number) => { + grid[i][j] = 0; + for (let k = 0; k < 4; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y <= n && grid[x][y] === 1) { + dfs(x, y); + } + } + }; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] === 1 && (i === 0 || i === m - 1 || j === 0 || j === n - 1)) { + dfs(i, j); + } + } + } + let ans = 0; + for (const row of grid) { + for (const v of row) { + ans += v; + } + } + return ans; +} +``` + +```rust +impl Solution { + fn dfs(grid: &mut Vec>, y: usize, x: usize) { + if y >= grid.len() || x >= grid[0].len() || grid[y][x] == 0 { + return; + } + grid[y][x] = 0; + Solution::dfs(grid, y + 1, x); + Solution::dfs(grid, y, x + 1); + if y != 0 { + Solution::dfs(grid, y - 1, x); + } + if x != 0 { + Solution::dfs(grid, y, x - 1); + } + } + pub fn num_enclaves(mut grid: Vec>) -> i32 { + let mut res = 0; + let m = grid.len(); + let n = grid[0].len(); + for i in 0..m { + Solution::dfs(&mut grid, i, 0); + Solution::dfs(&mut grid, i, n - 1); + } + for i in 0..n { + Solution::dfs(&mut grid, 0, i); + Solution::dfs(&mut grid, m - 1, i); + } + for i in 1..m - 1 { + for j in 1..n - 1 { + if grid[i][j] == 1 { + res += 1; + } + } + } + res + } +} +``` + + + +### 方法二:BFS + +我们也可以使用广度优先搜索的方法,将边界上的陆地入队,然后进行广度优先搜索,将所有与边界相连的陆地都标记为 $0$。最后,统计剩余的 $1$ 的个数,即为答案。 + +时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。 + + + +```python +class Solution: + def numEnclaves(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + q = deque() + for i in range(m): + for j in range(n): + if grid[i][j] and (i == 0 or i == m - 1 or j == 0 or j == n - 1): + q.append((i, j)) + grid[i][j] = 0 + 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 x >= 0 and x < m and y >= 0 and y < n and grid[x][y]: + q.append((x, y)) + grid[x][y] = 0 + return sum(v for row in grid for v in row) +``` + ```java class Solution { public int numEnclaves(int[][] grid) { @@ -232,6 +311,165 @@ class Solution { } ``` +```cpp +class Solution { +public: + int numEnclaves(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int dirs[5] = {-1, 0, 1, 0, -1}; + queue> q; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] && (i == 0 || i == m - 1 || j == 0 || j == n - 1)) { + q.emplace(i, j); + grid[i][j] = 0; + } + } + } + while (!q.empty()) { + auto [i, j] = q.front(); + q.pop(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y]) { + q.emplace(x, y); + grid[x][y] = 0; + } + } + } + int ans = 0; + for (auto& row : grid) { + for (auto& v : row) { + ans += v; + } + } + return ans; + } +}; +``` + +```go +func numEnclaves(grid [][]int) (ans int) { + m, n := len(grid), len(grid[0]) + dirs := [5]int{-1, 0, 1, 0, -1} + q := [][2]int{} + for i, row := range grid { + for j, v := range row { + if v == 1 && (i == 0 || i == m-1 || j == 0 || j == n-1) { + q = append(q, [2]int{i, j}) + grid[i][j] = 0 + } + } + } + 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 < m && y >= 0 && y < n && grid[x][y] == 1 { + q = append(q, [2]int{x, y}) + grid[x][y] = 0 + } + } + } + for _, row := range grid { + for _, v := range row { + ans += v + } + } + return +} +``` + +```ts +function numEnclaves(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const dirs = [-1, 0, 1, 0, -1]; + const q: number[][] = []; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] === 1 && (i === 0 || i === m - 1 || j === 0 || j === n - 1)) { + q.push([i, j]); + grid[i][j] = 0; + } + } + } + while (q.length) { + const [i, j] = q.shift()!; + for (let k = 0; k < 4; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y <= n && grid[x][y] === 1) { + q.push([x, y]); + grid[x][y] = 0; + } + } + } + let ans = 0; + for (const row of grid) { + for (const v of row) { + ans += v; + } + } + return ans; +} +``` + + + +### 方法三:并查集 + +我们还可以利用并查集的方法,将边界上的陆地与一个虚拟的节点 $(m, n)$ 进行合并,然后遍历矩阵中的所有陆地,将其与上下左右的陆地进行合并。最后,统计所有与虚拟节点 $(m, n)$ 不连通的陆地的个数,即为答案。 + +时间复杂度 $O(m \times n \alpha(m \times n))$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数,而 $\alpha$ 为 [阿克曼函数](https://zh.wikipedia.org/wiki/%E9%98%BF%E5%85%8B%E6%9B%BC%E5%87%BD%E6%95%B8) 的反函数。 + + + +```python +class UnionFind: + def __init__(self, n): + self.p = list(range(n)) + self.size = [1] * n + + def find(self, x): + if self.p[x] != x: + self.p[x] = self.find(self.p[x]) + return self.p[x] + + def union(self, a, b): + pa, pb = self.find(a), self.find(b) + if pa != pb: + if self.size[pa] > self.size[pb]: + self.p[pb] = pa + self.size[pa] += self.size[pb] + else: + self.p[pa] = pb + self.size[pb] += self.size[pa] + + +class Solution: + def numEnclaves(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + uf = UnionFind(m * n + 1) + dirs = (-1, 0, 1, 0, -1) + for i, row in enumerate(grid): + for j, v in enumerate(row): + if v: + if i == 0 or i == m - 1 or j == 0 or j == n - 1: + uf.union(i * n + j, m * n) + else: + for a, b in pairwise(dirs): + x, y = i + a, j + b + if x >= 0 and x < m and y >= 0 and y < n and grid[x][y]: + uf.union(i * n + j, x * n + y) + return sum( + grid[i][j] == 1 and uf.find(i * n + j) != uf.find(m * n) + for i in range(m) + for j in range(n) + ) +``` + ```java class UnionFind { private int[] p; @@ -302,78 +540,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numEnclaves(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - int dirs[5] = {-1, 0, 1, 0, -1}; - function dfs = [&](int i, int j) { - grid[i][j] = 0; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y]) { - dfs(x, y); - } - } - }; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] && (i == 0 || i == m - 1 || j == 0 || j == n - 1)) { - dfs(i, j); - } - } - } - int ans = 0; - for (auto& row : grid) { - for (auto& v : row) { - ans += v; - } - } - return ans; - } -}; -``` - -```cpp -class Solution { -public: - int numEnclaves(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - int dirs[5] = {-1, 0, 1, 0, -1}; - queue> q; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] && (i == 0 || i == m - 1 || j == 0 || j == n - 1)) { - q.emplace(i, j); - grid[i][j] = 0; - } - } - } - while (!q.empty()) { - auto [i, j] = q.front(); - q.pop(); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y]) { - q.emplace(x, y); - grid[x][y] = 0; - } - } - } - int ans = 0; - for (auto& row : grid) { - for (auto& v : row) { - ans += v; - } - } - return ans; - } -}; -``` - ```cpp class UnionFind { public: @@ -440,71 +606,6 @@ public: }; ``` -### **Go** - -```go -func numEnclaves(grid [][]int) (ans int) { - m, n := len(grid), len(grid[0]) - dirs := [5]int{-1, 0, 1, 0, -1} - var dfs func(i, j int) - dfs = func(i, j int) { - grid[i][j] = 0 - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 { - dfs(x, y) - } - } - } - for i, row := range grid { - for j, v := range row { - if v == 1 && (i == 0 || i == m-1 || j == 0 || j == n-1) { - dfs(i, j) - } - } - } - for _, row := range grid { - for _, v := range row { - ans += v - } - } - return -} -``` - -```go -func numEnclaves(grid [][]int) (ans int) { - m, n := len(grid), len(grid[0]) - dirs := [5]int{-1, 0, 1, 0, -1} - q := [][2]int{} - for i, row := range grid { - for j, v := range row { - if v == 1 && (i == 0 || i == m-1 || j == 0 || j == n-1) { - q = append(q, [2]int{i, j}) - grid[i][j] = 0 - } - } - } - 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 < m && y >= 0 && y < n && grid[x][y] == 1 { - q = append(q, [2]int{x, y}) - grid[x][y] = 0 - } - } - } - for _, row := range grid { - for _, v := range row { - ans += v - } - } - return -} -``` - ```go type unionFind struct { p, size []int @@ -571,121 +672,6 @@ func numEnclaves(grid [][]int) (ans int) { } ``` -### **TypeScript** - -```ts -function numEnclaves(grid: number[][]): number { - const m = grid.length; - const n = grid[0].length; - const dirs = [-1, 0, 1, 0, -1]; - const dfs = (i: number, j: number) => { - grid[i][j] = 0; - for (let k = 0; k < 4; ++k) { - const x = i + dirs[k]; - const y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y <= n && grid[x][y] === 1) { - dfs(x, y); - } - } - }; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (grid[i][j] === 1 && (i === 0 || i === m - 1 || j === 0 || j === n - 1)) { - dfs(i, j); - } - } - } - let ans = 0; - for (const row of grid) { - for (const v of row) { - ans += v; - } - } - return ans; -} -``` - -```ts -function numEnclaves(grid: number[][]): number { - const m = grid.length; - const n = grid[0].length; - const dirs = [-1, 0, 1, 0, -1]; - const q: number[][] = []; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (grid[i][j] === 1 && (i === 0 || i === m - 1 || j === 0 || j === n - 1)) { - q.push([i, j]); - grid[i][j] = 0; - } - } - } - while (q.length) { - const [i, j] = q.shift()!; - for (let k = 0; k < 4; ++k) { - const x = i + dirs[k]; - const y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y <= n && grid[x][y] === 1) { - q.push([x, y]); - grid[x][y] = 0; - } - } - } - let ans = 0; - for (const row of grid) { - for (const v of row) { - ans += v; - } - } - return ans; -} -``` - -### **Rust** - -```rust -impl Solution { - fn dfs(grid: &mut Vec>, y: usize, x: usize) { - if y >= grid.len() || x >= grid[0].len() || grid[y][x] == 0 { - return; - } - grid[y][x] = 0; - Solution::dfs(grid, y + 1, x); - Solution::dfs(grid, y, x + 1); - if y != 0 { - Solution::dfs(grid, y - 1, x); - } - if x != 0 { - Solution::dfs(grid, y, x - 1); - } - } - pub fn num_enclaves(mut grid: Vec>) -> i32 { - let mut res = 0; - let m = grid.len(); - let n = grid[0].len(); - for i in 0..m { - Solution::dfs(&mut grid, i, 0); - Solution::dfs(&mut grid, i, n - 1); - } - for i in 0..n { - Solution::dfs(&mut grid, 0, i); - Solution::dfs(&mut grid, m - 1, i); - } - for i in 1..m - 1 { - for j in 1..n - 1 { - if grid[i][j] == 1 { - res += 1; - } - } - } - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1020.Number of Enclaves/README_EN.md b/solution/1000-1099/1020.Number of Enclaves/README_EN.md index e61cc2e50f58f..3caf094a338f2 100644 --- a/solution/1000-1099/1020.Number of Enclaves/README_EN.md +++ b/solution/1000-1099/1020.Number of Enclaves/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,73 +62,6 @@ class Solution: return sum(v for row in grid for v in row) ``` -```python -class Solution: - def numEnclaves(self, grid: List[List[int]]) -> int: - m, n = len(grid), len(grid[0]) - q = deque() - for i in range(m): - for j in range(n): - if grid[i][j] and (i == 0 or i == m - 1 or j == 0 or j == n - 1): - q.append((i, j)) - grid[i][j] = 0 - 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 x >= 0 and x < m and y >= 0 and y < n and grid[x][y]: - q.append((x, y)) - grid[x][y] = 0 - return sum(v for row in grid for v in row) -``` - -```python -class UnionFind: - def __init__(self, n): - self.p = list(range(n)) - self.size = [1] * n - - def find(self, x): - if self.p[x] != x: - self.p[x] = self.find(self.p[x]) - return self.p[x] - - def union(self, a, b): - pa, pb = self.find(a), self.find(b) - if pa != pb: - if self.size[pa] > self.size[pb]: - self.p[pb] = pa - self.size[pa] += self.size[pb] - else: - self.p[pa] = pb - self.size[pb] += self.size[pa] - - -class Solution: - def numEnclaves(self, grid: List[List[int]]) -> int: - m, n = len(grid), len(grid[0]) - uf = UnionFind(m * n + 1) - dirs = (-1, 0, 1, 0, -1) - for i, row in enumerate(grid): - for j, v in enumerate(row): - if v: - if i == 0 or i == m - 1 or j == 0 or j == n - 1: - uf.union(i * n + j, m * n) - else: - for a, b in pairwise(dirs): - x, y = i + a, j + b - if x >= 0 and x < m and y >= 0 and y < n and grid[x][y]: - uf.union(i * n + j, x * n + y) - return sum( - grid[i][j] == 1 and uf.find(i * n + j) != uf.find(m * n) - for i in range(m) - for j in range(n) - ) -``` - -### **Java** - ```java class Solution { private int m; @@ -168,6 +101,168 @@ class Solution { } ``` +```cpp +class Solution { +public: + int numEnclaves(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int dirs[5] = {-1, 0, 1, 0, -1}; + function dfs = [&](int i, int j) { + grid[i][j] = 0; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y]) { + dfs(x, y); + } + } + }; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] && (i == 0 || i == m - 1 || j == 0 || j == n - 1)) { + dfs(i, j); + } + } + } + int ans = 0; + for (auto& row : grid) { + for (auto& v : row) { + ans += v; + } + } + return ans; + } +}; +``` + +```go +func numEnclaves(grid [][]int) (ans int) { + m, n := len(grid), len(grid[0]) + dirs := [5]int{-1, 0, 1, 0, -1} + var dfs func(i, j int) + dfs = func(i, j int) { + grid[i][j] = 0 + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 { + dfs(x, y) + } + } + } + for i, row := range grid { + for j, v := range row { + if v == 1 && (i == 0 || i == m-1 || j == 0 || j == n-1) { + dfs(i, j) + } + } + } + for _, row := range grid { + for _, v := range row { + ans += v + } + } + return +} +``` + +```ts +function numEnclaves(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const dirs = [-1, 0, 1, 0, -1]; + const dfs = (i: number, j: number) => { + grid[i][j] = 0; + for (let k = 0; k < 4; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y <= n && grid[x][y] === 1) { + dfs(x, y); + } + } + }; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] === 1 && (i === 0 || i === m - 1 || j === 0 || j === n - 1)) { + dfs(i, j); + } + } + } + let ans = 0; + for (const row of grid) { + for (const v of row) { + ans += v; + } + } + return ans; +} +``` + +```rust +impl Solution { + fn dfs(grid: &mut Vec>, y: usize, x: usize) { + if y >= grid.len() || x >= grid[0].len() || grid[y][x] == 0 { + return; + } + grid[y][x] = 0; + Solution::dfs(grid, y + 1, x); + Solution::dfs(grid, y, x + 1); + if y != 0 { + Solution::dfs(grid, y - 1, x); + } + if x != 0 { + Solution::dfs(grid, y, x - 1); + } + } + pub fn num_enclaves(mut grid: Vec>) -> i32 { + let mut res = 0; + let m = grid.len(); + let n = grid[0].len(); + for i in 0..m { + Solution::dfs(&mut grid, i, 0); + Solution::dfs(&mut grid, i, n - 1); + } + for i in 0..n { + Solution::dfs(&mut grid, 0, i); + Solution::dfs(&mut grid, m - 1, i); + } + for i in 1..m - 1 { + for j in 1..n - 1 { + if grid[i][j] == 1 { + res += 1; + } + } + } + res + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def numEnclaves(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + q = deque() + for i in range(m): + for j in range(n): + if grid[i][j] and (i == 0 or i == m - 1 or j == 0 or j == n - 1): + q.append((i, j)) + grid[i][j] = 0 + 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 x >= 0 and x < m and y >= 0 and y < n and grid[x][y]: + q.append((x, y)) + grid[x][y] = 0 + return sum(v for row in grid for v in row) +``` + ```java class Solution { public int numEnclaves(int[][] grid) { @@ -204,6 +299,161 @@ class Solution { } ``` +```cpp +class Solution { +public: + int numEnclaves(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int dirs[5] = {-1, 0, 1, 0, -1}; + queue> q; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] && (i == 0 || i == m - 1 || j == 0 || j == n - 1)) { + q.emplace(i, j); + grid[i][j] = 0; + } + } + } + while (!q.empty()) { + auto [i, j] = q.front(); + q.pop(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y]) { + q.emplace(x, y); + grid[x][y] = 0; + } + } + } + int ans = 0; + for (auto& row : grid) { + for (auto& v : row) { + ans += v; + } + } + return ans; + } +}; +``` + +```go +func numEnclaves(grid [][]int) (ans int) { + m, n := len(grid), len(grid[0]) + dirs := [5]int{-1, 0, 1, 0, -1} + q := [][2]int{} + for i, row := range grid { + for j, v := range row { + if v == 1 && (i == 0 || i == m-1 || j == 0 || j == n-1) { + q = append(q, [2]int{i, j}) + grid[i][j] = 0 + } + } + } + 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 < m && y >= 0 && y < n && grid[x][y] == 1 { + q = append(q, [2]int{x, y}) + grid[x][y] = 0 + } + } + } + for _, row := range grid { + for _, v := range row { + ans += v + } + } + return +} +``` + +```ts +function numEnclaves(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const dirs = [-1, 0, 1, 0, -1]; + const q: number[][] = []; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + if (grid[i][j] === 1 && (i === 0 || i === m - 1 || j === 0 || j === n - 1)) { + q.push([i, j]); + grid[i][j] = 0; + } + } + } + while (q.length) { + const [i, j] = q.shift()!; + for (let k = 0; k < 4; ++k) { + const x = i + dirs[k]; + const y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y <= n && grid[x][y] === 1) { + q.push([x, y]); + grid[x][y] = 0; + } + } + } + let ans = 0; + for (const row of grid) { + for (const v of row) { + ans += v; + } + } + return ans; +} +``` + + + +### Solution 3 + + + +```python +class UnionFind: + def __init__(self, n): + self.p = list(range(n)) + self.size = [1] * n + + def find(self, x): + if self.p[x] != x: + self.p[x] = self.find(self.p[x]) + return self.p[x] + + def union(self, a, b): + pa, pb = self.find(a), self.find(b) + if pa != pb: + if self.size[pa] > self.size[pb]: + self.p[pb] = pa + self.size[pa] += self.size[pb] + else: + self.p[pa] = pb + self.size[pb] += self.size[pa] + + +class Solution: + def numEnclaves(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + uf = UnionFind(m * n + 1) + dirs = (-1, 0, 1, 0, -1) + for i, row in enumerate(grid): + for j, v in enumerate(row): + if v: + if i == 0 or i == m - 1 or j == 0 or j == n - 1: + uf.union(i * n + j, m * n) + else: + for a, b in pairwise(dirs): + x, y = i + a, j + b + if x >= 0 and x < m and y >= 0 and y < n and grid[x][y]: + uf.union(i * n + j, x * n + y) + return sum( + grid[i][j] == 1 and uf.find(i * n + j) != uf.find(m * n) + for i in range(m) + for j in range(n) + ) +``` + ```java class UnionFind { private int[] p; @@ -274,78 +524,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numEnclaves(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - int dirs[5] = {-1, 0, 1, 0, -1}; - function dfs = [&](int i, int j) { - grid[i][j] = 0; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y]) { - dfs(x, y); - } - } - }; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] && (i == 0 || i == m - 1 || j == 0 || j == n - 1)) { - dfs(i, j); - } - } - } - int ans = 0; - for (auto& row : grid) { - for (auto& v : row) { - ans += v; - } - } - return ans; - } -}; -``` - -```cpp -class Solution { -public: - int numEnclaves(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - int dirs[5] = {-1, 0, 1, 0, -1}; - queue> q; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] && (i == 0 || i == m - 1 || j == 0 || j == n - 1)) { - q.emplace(i, j); - grid[i][j] = 0; - } - } - } - while (!q.empty()) { - auto [i, j] = q.front(); - q.pop(); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y]) { - q.emplace(x, y); - grid[x][y] = 0; - } - } - } - int ans = 0; - for (auto& row : grid) { - for (auto& v : row) { - ans += v; - } - } - return ans; - } -}; -``` - ```cpp class UnionFind { public: @@ -412,71 +590,6 @@ public: }; ``` -### **Go** - -```go -func numEnclaves(grid [][]int) (ans int) { - m, n := len(grid), len(grid[0]) - dirs := [5]int{-1, 0, 1, 0, -1} - var dfs func(i, j int) - dfs = func(i, j int) { - grid[i][j] = 0 - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 { - dfs(x, y) - } - } - } - for i, row := range grid { - for j, v := range row { - if v == 1 && (i == 0 || i == m-1 || j == 0 || j == n-1) { - dfs(i, j) - } - } - } - for _, row := range grid { - for _, v := range row { - ans += v - } - } - return -} -``` - -```go -func numEnclaves(grid [][]int) (ans int) { - m, n := len(grid), len(grid[0]) - dirs := [5]int{-1, 0, 1, 0, -1} - q := [][2]int{} - for i, row := range grid { - for j, v := range row { - if v == 1 && (i == 0 || i == m-1 || j == 0 || j == n-1) { - q = append(q, [2]int{i, j}) - grid[i][j] = 0 - } - } - } - 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 < m && y >= 0 && y < n && grid[x][y] == 1 { - q = append(q, [2]int{x, y}) - grid[x][y] = 0 - } - } - } - for _, row := range grid { - for _, v := range row { - ans += v - } - } - return -} -``` - ```go type unionFind struct { p, size []int @@ -543,121 +656,6 @@ func numEnclaves(grid [][]int) (ans int) { } ``` -### **TypeScript** - -```ts -function numEnclaves(grid: number[][]): number { - const m = grid.length; - const n = grid[0].length; - const dirs = [-1, 0, 1, 0, -1]; - const dfs = (i: number, j: number) => { - grid[i][j] = 0; - for (let k = 0; k < 4; ++k) { - const x = i + dirs[k]; - const y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y <= n && grid[x][y] === 1) { - dfs(x, y); - } - } - }; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (grid[i][j] === 1 && (i === 0 || i === m - 1 || j === 0 || j === n - 1)) { - dfs(i, j); - } - } - } - let ans = 0; - for (const row of grid) { - for (const v of row) { - ans += v; - } - } - return ans; -} -``` - -```ts -function numEnclaves(grid: number[][]): number { - const m = grid.length; - const n = grid[0].length; - const dirs = [-1, 0, 1, 0, -1]; - const q: number[][] = []; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - if (grid[i][j] === 1 && (i === 0 || i === m - 1 || j === 0 || j === n - 1)) { - q.push([i, j]); - grid[i][j] = 0; - } - } - } - while (q.length) { - const [i, j] = q.shift()!; - for (let k = 0; k < 4; ++k) { - const x = i + dirs[k]; - const y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y <= n && grid[x][y] === 1) { - q.push([x, y]); - grid[x][y] = 0; - } - } - } - let ans = 0; - for (const row of grid) { - for (const v of row) { - ans += v; - } - } - return ans; -} -``` - -### **Rust** - -```rust -impl Solution { - fn dfs(grid: &mut Vec>, y: usize, x: usize) { - if y >= grid.len() || x >= grid[0].len() || grid[y][x] == 0 { - return; - } - grid[y][x] = 0; - Solution::dfs(grid, y + 1, x); - Solution::dfs(grid, y, x + 1); - if y != 0 { - Solution::dfs(grid, y - 1, x); - } - if x != 0 { - Solution::dfs(grid, y, x - 1); - } - } - pub fn num_enclaves(mut grid: Vec>) -> i32 { - let mut res = 0; - let m = grid.len(); - let n = grid[0].len(); - for i in 0..m { - Solution::dfs(&mut grid, i, 0); - Solution::dfs(&mut grid, i, n - 1); - } - for i in 0..n { - Solution::dfs(&mut grid, 0, i); - Solution::dfs(&mut grid, m - 1, i); - } - for i in 1..m - 1 { - for j in 1..n - 1 { - if grid[i][j] == 1 { - res += 1; - } - } - } - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1021.Remove Outermost Parentheses/README.md b/solution/1000-1099/1021.Remove Outermost Parentheses/README.md index 45eb6bf34d648..1e4bed6795791 100644 --- a/solution/1000-1099/1021.Remove Outermost Parentheses/README.md +++ b/solution/1000-1099/1021.Remove Outermost Parentheses/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 遍历字符串,遇到左括号 `'('` 计数器加一,此时计数器不为 $1$ 时,说明当前括号不是最外层括号,将其加入结果字符串。遇到右括号 `')'` 计数器减一,此时计数器不为 $0$ 时,说明当前括号不是最外层括号,将其加入结果字符串。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def removeOuterParentheses(self, s: str) -> str: @@ -92,25 +86,6 @@ class Solution: return ''.join(ans) ``` -```python -class Solution: - def removeOuterParentheses(self, s: str) -> str: - ans = [] - cnt = 0 - for c in s: - if c == '(': - cnt += 1 - if cnt > 1: - ans.append(c) - if c == ')': - cnt -= 1 - return ''.join(ans) -``` - -### **Java** - - - ```java class Solution { public String removeOuterParentheses(String s) { @@ -133,30 +108,6 @@ class Solution { } ``` -```java -class Solution { - public String removeOuterParentheses(String s) { - StringBuilder ans = new StringBuilder(); - int cnt = 0; - for (int i = 0; i < s.length(); ++i) { - char c = s.charAt(i); - if (c == '(') { - ++cnt; - } - if (cnt > 1) { - ans.append(c); - } - if (c == ')') { - --cnt; - } - } - return ans.toString(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -179,30 +130,6 @@ public: }; ``` -```cpp -class Solution { -public: - string removeOuterParentheses(string s) { - string ans; - int cnt = 0; - for (char& c : s) { - if (c == '(') { - ++cnt; - } - if (cnt > 1) { - ans.push_back(c); - } - if (c == ')') { - --cnt; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func removeOuterParentheses(s string) string { ans := []rune{} @@ -224,27 +151,6 @@ func removeOuterParentheses(s string) string { } ``` -```go -func removeOuterParentheses(s string) string { - ans := []rune{} - cnt := 0 - for _, c := range s { - if c == '(' { - cnt++ - } - if cnt > 1 { - ans = append(ans, c) - } - if c == ')' { - cnt-- - } - } - return string(ans) -} -``` - -### **TypeScript** - ```ts function removeOuterParentheses(s: string): string { let res = ''; @@ -264,8 +170,6 @@ function removeOuterParentheses(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn remove_outer_parentheses(s: String) -> String { @@ -287,10 +191,90 @@ impl Solution { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def removeOuterParentheses(self, s: str) -> str: + ans = [] + cnt = 0 + for c in s: + if c == '(': + cnt += 1 + if cnt > 1: + ans.append(c) + if c == ')': + cnt -= 1 + return ''.join(ans) ``` +```java +class Solution { + public String removeOuterParentheses(String s) { + StringBuilder ans = new StringBuilder(); + int cnt = 0; + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (c == '(') { + ++cnt; + } + if (cnt > 1) { + ans.append(c); + } + if (c == ')') { + --cnt; + } + } + return ans.toString(); + } +} +``` + +```cpp +class Solution { +public: + string removeOuterParentheses(string s) { + string ans; + int cnt = 0; + for (char& c : s) { + if (c == '(') { + ++cnt; + } + if (cnt > 1) { + ans.push_back(c); + } + if (c == ')') { + --cnt; + } + } + return ans; + } +}; +``` + +```go +func removeOuterParentheses(s string) string { + ans := []rune{} + cnt := 0 + for _, c := range s { + if c == '(' { + cnt++ + } + if cnt > 1 { + ans = append(ans, c) + } + if c == ')' { + cnt-- + } + } + return string(ans) +} ``` + + diff --git a/solution/1000-1099/1021.Remove Outermost Parentheses/README_EN.md b/solution/1000-1099/1021.Remove Outermost Parentheses/README_EN.md index 8c51abd8722f1..20e0ed6b89b96 100644 --- a/solution/1000-1099/1021.Remove Outermost Parentheses/README_EN.md +++ b/solution/1000-1099/1021.Remove Outermost Parentheses/README_EN.md @@ -58,9 +58,9 @@ After removing outer parentheses of each part, this is "" + "&quo ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,23 +79,6 @@ class Solution: return ''.join(ans) ``` -```python -class Solution: - def removeOuterParentheses(self, s: str) -> str: - ans = [] - cnt = 0 - for c in s: - if c == '(': - cnt += 1 - if cnt > 1: - ans.append(c) - if c == ')': - cnt -= 1 - return ''.join(ans) -``` - -### **Java** - ```java class Solution { public String removeOuterParentheses(String s) { @@ -118,30 +101,6 @@ class Solution { } ``` -```java -class Solution { - public String removeOuterParentheses(String s) { - StringBuilder ans = new StringBuilder(); - int cnt = 0; - for (int i = 0; i < s.length(); ++i) { - char c = s.charAt(i); - if (c == '(') { - ++cnt; - } - if (cnt > 1) { - ans.append(c); - } - if (c == ')') { - --cnt; - } - } - return ans.toString(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -164,30 +123,6 @@ public: }; ``` -```cpp -class Solution { -public: - string removeOuterParentheses(string s) { - string ans; - int cnt = 0; - for (char& c : s) { - if (c == '(') { - ++cnt; - } - if (cnt > 1) { - ans.push_back(c); - } - if (c == ')') { - --cnt; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func removeOuterParentheses(s string) string { ans := []rune{} @@ -209,27 +144,6 @@ func removeOuterParentheses(s string) string { } ``` -```go -func removeOuterParentheses(s string) string { - ans := []rune{} - cnt := 0 - for _, c := range s { - if c == '(' { - cnt++ - } - if cnt > 1 { - ans = append(ans, c) - } - if c == ')' { - cnt-- - } - } - return string(ans) -} -``` - -### **TypeScript** - ```ts function removeOuterParentheses(s: string): string { let res = ''; @@ -249,8 +163,6 @@ function removeOuterParentheses(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn remove_outer_parentheses(s: String) -> String { @@ -272,10 +184,90 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def removeOuterParentheses(self, s: str) -> str: + ans = [] + cnt = 0 + for c in s: + if c == '(': + cnt += 1 + if cnt > 1: + ans.append(c) + if c == ')': + cnt -= 1 + return ''.join(ans) +``` + +```java +class Solution { + public String removeOuterParentheses(String s) { + StringBuilder ans = new StringBuilder(); + int cnt = 0; + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (c == '(') { + ++cnt; + } + if (cnt > 1) { + ans.append(c); + } + if (c == ')') { + --cnt; + } + } + return ans.toString(); + } +} +``` +```cpp +class Solution { +public: + string removeOuterParentheses(string s) { + string ans; + int cnt = 0; + for (char& c : s) { + if (c == '(') { + ++cnt; + } + if (cnt > 1) { + ans.push_back(c); + } + if (c == ')') { + --cnt; + } + } + return ans; + } +}; ``` +```go +func removeOuterParentheses(s string) string { + ans := []rune{} + cnt := 0 + for _, c := range s { + if c == '(' { + cnt++ + } + if cnt > 1 { + ans = append(ans, c) + } + if c == ')' { + cnt-- + } + } + return string(ans) +} ``` + + diff --git a/solution/1000-1099/1022.Sum of Root To Leaf Binary Numbers/README.md b/solution/1000-1099/1022.Sum of Root To Leaf Binary Numbers/README.md index 78765d12d8152..1359061346619 100644 --- a/solution/1000-1099/1022.Sum of Root To Leaf Binary Numbers/README.md +++ b/solution/1000-1099/1022.Sum of Root To Leaf Binary Numbers/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们设计递归函数 `dfs(root, t)`,它接收两个参数:当前节点 `root` 和当前节点的父节点对应的二进制数 `t`。函数的返回值是从当前节点到叶子节点的路径所表示的二进制数之和。答案即为 `dfs(root, 0)`。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -83,10 +77,6 @@ class Solution: return dfs(root, 0) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -178,8 +164,6 @@ func sumRootToLeaf(root *TreeNode) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -211,8 +195,6 @@ function sumRootToLeaf(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -253,10 +235,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1022.Sum of Root To Leaf Binary Numbers/README_EN.md b/solution/1000-1099/1022.Sum of Root To Leaf Binary Numbers/README_EN.md index 76d79d9c2bd2b..72159a6854e7d 100644 --- a/solution/1000-1099/1022.Sum of Root To Leaf Binary Numbers/README_EN.md +++ b/solution/1000-1099/1022.Sum of Root To Leaf Binary Numbers/README_EN.md @@ -40,12 +40,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -66,8 +64,6 @@ class Solution: return dfs(root, 0) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -102,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -131,8 +125,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -159,8 +151,6 @@ func sumRootToLeaf(root *TreeNode) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -192,8 +182,6 @@ function sumRootToLeaf(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -234,10 +222,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1023.Camelcase Matching/README.md b/solution/1000-1099/1023.Camelcase Matching/README.md index bebe251cccb61..39c1341351135 100644 --- a/solution/1000-1099/1023.Camelcase Matching/README.md +++ b/solution/1000-1099/1023.Camelcase Matching/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们可以遍历 `queries` 中的每个字符串,判断其是否与 `pattern` 匹配,若匹配则将 `true` 加入答案数组,否则加入 `false`。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: @@ -92,10 +86,6 @@ class Solution: return [check(q, pattern) for q in queries] ``` -### **Java** - - - ```java class Solution { public List camelMatch(String[] queries, String pattern) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func camelMatch(queries []string, pattern string) (ans []bool) { check := func(s, t string) bool { @@ -183,8 +169,6 @@ func camelMatch(queries []string, pattern string) (ans []bool) { } ``` -### **TypeScript** - ```ts function camelMatch(queries: string[], pattern: string): boolean[] { const check = (s: string, t: string) => { @@ -213,10 +197,6 @@ function camelMatch(queries: string[], pattern: string): boolean[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1023.Camelcase Matching/README_EN.md b/solution/1000-1099/1023.Camelcase Matching/README_EN.md index 0e0fa17570556..667258fd7b7bc 100644 --- a/solution/1000-1099/1023.Camelcase Matching/README_EN.md +++ b/solution/1000-1099/1023.Camelcase Matching/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We can traverse every string in `queries` and check whether it matches `pattern` or not. If it matches, we add `true` to the answer array, otherwise we add `false`. @@ -61,8 +61,6 @@ Time complexity $(n \times m)$, where $n$ and $m$ are the length of the array `q -### **Python3** - ```python class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: @@ -82,8 +80,6 @@ class Solution: return [check(q, pattern) for q in queries] ``` -### **Java** - ```java class Solution { public List camelMatch(String[] queries, String pattern) { @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +138,6 @@ public: }; ``` -### **Go** - ```go func camelMatch(queries []string, pattern string) (ans []bool) { check := func(s, t string) bool { @@ -171,8 +163,6 @@ func camelMatch(queries []string, pattern string) (ans []bool) { } ``` -### **TypeScript** - ```ts function camelMatch(queries: string[], pattern: string): boolean[] { const check = (s: string, t: string) => { @@ -201,10 +191,6 @@ function camelMatch(queries: string[], pattern: string): boolean[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1024.Video Stitching/README.md b/solution/1000-1099/1024.Video Stitching/README.md index 97f341c438970..7ad5e370c7abc 100644 --- a/solution/1000-1099/1024.Video Stitching/README.md +++ b/solution/1000-1099/1024.Video Stitching/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 注意到,如果相同起点的子区间有多个,那么选择右端点最大的那个子区间是最优的。 @@ -88,10 +86,6 @@ -### **Python3** - - - ```python class Solution: def videoStitching(self, clips: List[List[int]], time: int) -> int: @@ -110,10 +104,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int videoStitching(int[][] clips, int time) { @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +158,6 @@ public: }; ``` -### **Go** - ```go func videoStitching(clips [][]int, time int) int { last := make([]int, time) @@ -196,10 +182,6 @@ func videoStitching(clips [][]int, time int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1024.Video Stitching/README_EN.md b/solution/1000-1099/1024.Video Stitching/README_EN.md index e7dff4bbde8f7..5f8f33386b9c3 100644 --- a/solution/1000-1099/1024.Video Stitching/README_EN.md +++ b/solution/1000-1099/1024.Video Stitching/README_EN.md @@ -55,9 +55,9 @@ Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 1 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int videoStitching(int[][] clips, int time) { @@ -105,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +131,6 @@ public: }; ``` -### **Go** - ```go func videoStitching(clips [][]int, time int) int { last := make([]int, time) @@ -161,10 +155,6 @@ func videoStitching(clips [][]int, time int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1025.Divisor Game/README.md b/solution/1000-1099/1025.Divisor Game/README.md index e6a224a83859c..6d91d95530cd6 100644 --- a/solution/1000-1099/1025.Divisor Game/README.md +++ b/solution/1000-1099/1025.Divisor Game/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:数学归纳法** +### 方法一:数学归纳法 - 当 $n=1$,先手败 - 当 $n=2$,先手拿 $1$,剩下 $1$,后手败,先手胜 @@ -75,20 +73,12 @@ -### **Python3** - - - ```python class Solution: def divisorGame(self, n: int) -> bool: return n % 2 == 0 ``` -### **Java** - - - ```java class Solution { public boolean divisorGame(int n) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,18 +96,12 @@ public: }; ``` -### **Go** - ```go func divisorGame(n int) bool { return n%2 == 0 } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1025.Divisor Game/README_EN.md b/solution/1000-1099/1025.Divisor Game/README_EN.md index 6f222f9998a2e..b2a058cceecdd 100644 --- a/solution/1000-1099/1025.Divisor Game/README_EN.md +++ b/solution/1000-1099/1025.Divisor Game/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return n % 2 == 0 ``` -### **Java** - ```java class Solution { public boolean divisorGame(int n) { @@ -63,8 +61,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -74,18 +70,12 @@ public: }; ``` -### **Go** - ```go func divisorGame(n int) bool { return n%2 == 0 } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1026.Maximum Difference Between Node and Ancestor/README.md b/solution/1000-1099/1026.Maximum Difference Between Node and Ancestor/README.md index 4cd3bf0c17e83..9c3afc5118a90 100644 --- a/solution/1000-1099/1026.Maximum Difference Between Node and Ancestor/README.md +++ b/solution/1000-1099/1026.Maximum Difference Between Node and Ancestor/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 对于每个节点,求其与祖先节点的最大差值,我们只需要求出该节点与祖先节点最大值和最小值的差值,取所有差值的最大值即可。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -94,10 +88,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -170,8 +158,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -205,8 +191,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -239,8 +223,6 @@ function maxAncestorDiff(root: TreeNode | null): number { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -271,10 +253,6 @@ var maxAncestorDiff = function (root) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1026.Maximum Difference Between Node and Ancestor/README_EN.md b/solution/1000-1099/1026.Maximum Difference Between Node and Ancestor/README_EN.md index d1a5abccd98e5..8d0f39043c1c9 100644 --- a/solution/1000-1099/1026.Maximum Difference Between Node and Ancestor/README_EN.md +++ b/solution/1000-1099/1026.Maximum Difference Between Node and Ancestor/README_EN.md @@ -38,9 +38,9 @@ Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -66,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -140,8 +136,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -175,8 +169,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -209,8 +201,6 @@ function maxAncestorDiff(root: TreeNode | null): number { } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -241,10 +231,6 @@ var maxAncestorDiff = function (root) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1027.Longest Arithmetic Subsequence/README.md b/solution/1000-1099/1027.Longest Arithmetic Subsequence/README.md index beeab82142ea6..b8efe34139d87 100644 --- a/solution/1000-1099/1027.Longest Arithmetic Subsequence/README.md +++ b/solution/1000-1099/1027.Longest Arithmetic Subsequence/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示以 $nums[i]$ 结尾且公差为 $j$ 的等差数列的最大长度。初始时 $f[i][j]=1$,即每个元素自身都是一个长度为 $1$ 的等差数列。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def longestArithSeqLength(self, nums: List[int]) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestArithSeqLength(int[] nums) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func longestArithSeqLength(nums []int) int { n := len(nums) @@ -151,8 +137,6 @@ func longestArithSeqLength(nums []int) int { } ``` -### **TypeScript** - ```ts function longestArithSeqLength(nums: number[]): number { const n = nums.length; @@ -169,10 +153,6 @@ function longestArithSeqLength(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1027.Longest Arithmetic Subsequence/README_EN.md b/solution/1000-1099/1027.Longest Arithmetic Subsequence/README_EN.md index fc0fe00744501..1953e5b89b7d5 100644 --- a/solution/1000-1099/1027.Longest Arithmetic Subsequence/README_EN.md +++ b/solution/1000-1099/1027.Longest Arithmetic Subsequence/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestArithSeqLength(int[] nums) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +104,6 @@ public: }; ``` -### **Go** - ```go func longestArithSeqLength(nums []int) int { n := len(nums) @@ -129,8 +123,6 @@ func longestArithSeqLength(nums []int) int { } ``` -### **TypeScript** - ```ts function longestArithSeqLength(nums: number[]): number { const n = nums.length; @@ -147,10 +139,6 @@ function longestArithSeqLength(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1028.Recover a Tree From Preorder Traversal/README.md b/solution/1000-1099/1028.Recover a Tree From Preorder Traversal/README.md index 91840a247e85e..645696513fb00 100644 --- a/solution/1000-1099/1028.Recover a Tree From Preorder Traversal/README.md +++ b/solution/1000-1099/1028.Recover a Tree From Preorder Traversal/README.md @@ -51,30 +51,59 @@ ## 解法 - +### 方法一 -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - +```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* recoverFromPreorder(string S) { + stack st; + int depth = 0; + int num = 0; + for (int i = 0; i < S.length(); ++i) { + if (S[i] == '-') { + depth++; + } else { + num = 10 * num + S[i] - '0'; + } + if (i + 1 >= S.length() || (isdigit(S[i]) && S[i + 1] == '-')) { + TreeNode* newNode = new TreeNode(num); + while (st.size() > depth) { + st.pop(); + } + if (!st.empty()) { + if (st.top()->left == nullptr) { + st.top()->left = newNode; + } else { + st.top()->right = newNode; + } + } + st.push(newNode); + depth = 0; + num = 0; + } + } + TreeNode* res; + while (!st.empty()) { + res = st.top(); + st.pop(); + } + return res; + } +}; ``` + + diff --git a/solution/1000-1099/1028.Recover a Tree From Preorder Traversal/README_EN.md b/solution/1000-1099/1028.Recover a Tree From Preorder Traversal/README_EN.md index 3bcde814661f6..e8dc0f4fe4296 100644 --- a/solution/1000-1099/1028.Recover a Tree From Preorder Traversal/README_EN.md +++ b/solution/1000-1099/1028.Recover a Tree From Preorder Traversal/README_EN.md @@ -44,24 +44,59 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java +### Solution 1 -``` - -### **...** - -``` + +```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* recoverFromPreorder(string S) { + stack st; + int depth = 0; + int num = 0; + for (int i = 0; i < S.length(); ++i) { + if (S[i] == '-') { + depth++; + } else { + num = 10 * num + S[i] - '0'; + } + if (i + 1 >= S.length() || (isdigit(S[i]) && S[i + 1] == '-')) { + TreeNode* newNode = new TreeNode(num); + while (st.size() > depth) { + st.pop(); + } + if (!st.empty()) { + if (st.top()->left == nullptr) { + st.top()->left = newNode; + } else { + st.top()->right = newNode; + } + } + st.push(newNode); + depth = 0; + num = 0; + } + } + TreeNode* res; + while (!st.empty()) { + res = st.top(); + st.pop(); + } + return res; + } +}; ``` + + diff --git a/solution/1000-1099/1029.Two City Scheduling/README.md b/solution/1000-1099/1029.Two City Scheduling/README.md index 6a954c771d39b..e3633429f4ce4 100644 --- a/solution/1000-1099/1029.Two City Scheduling/README.md +++ b/solution/1000-1099/1029.Two City Scheduling/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:排序 + 贪心** +### 方法一:排序 + 贪心 我们不妨先假设所有人都去 $b$ 市,然后我们要从中选出 $n$ 个人去 $a$ 市,使得总费用最小。如果一个人去 $a$ 市的费用比去 $b$ 市的费用小,我们把这个人从 $b$ 市调到 $a$ 市,这样总费用就会减少。因此,我们可以将所有人按照去 $a$ 市的费用与去 $b$ 市的费用的差值从小到大排序,然后选出前 $n$ 个人去 $a$ 市,剩下的人去 $b$ 市,这样总费用就是最小的。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: @@ -79,10 +73,6 @@ class Solution: return sum(costs[i][0] + costs[i + n][1] for i in range(n)) ``` -### **Java** - - - ```java class Solution { public int twoCitySchedCost(int[][] costs) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func twoCitySchedCost(costs [][]int) (ans int) { sort.Slice(costs, func(i, j int) bool { @@ -131,8 +117,6 @@ func twoCitySchedCost(costs [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function twoCitySchedCost(costs: number[][]): number { costs.sort((a, b) => a[0] - a[1] - (b[0] - b[1])); @@ -145,10 +129,6 @@ function twoCitySchedCost(costs: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1029.Two City Scheduling/README_EN.md b/solution/1000-1099/1029.Two City Scheduling/README_EN.md index fb6721086573c..5a031292f09f7 100644 --- a/solution/1000-1099/1029.Two City Scheduling/README_EN.md +++ b/solution/1000-1099/1029.Two City Scheduling/README_EN.md @@ -49,12 +49,10 @@ The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interv ## Solutions -Greedy. +### Solution 1 -### **Python3** - ```python class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: @@ -63,8 +61,6 @@ class Solution: return sum(costs[i][0] + costs[i + n][1] for i in range(n)) ``` -### **Java** - ```java class Solution { public int twoCitySchedCost(int[][] costs) { @@ -79,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +92,6 @@ public: }; ``` -### **Go** - ```go func twoCitySchedCost(costs [][]int) (ans int) { sort.Slice(costs, func(i, j int) bool { @@ -113,8 +105,6 @@ func twoCitySchedCost(costs [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function twoCitySchedCost(costs: number[][]): number { costs.sort((a, b) => a[0] - a[1] - (b[0] - b[1])); @@ -127,10 +117,6 @@ function twoCitySchedCost(costs: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1030.Matrix Cells in Distance Order/README.md b/solution/1000-1099/1030.Matrix Cells in Distance Order/README.md index 71de61e650fff..a1989397bc557 100644 --- a/solution/1000-1099/1030.Matrix Cells in Distance Order/README.md +++ b/solution/1000-1099/1030.Matrix Cells in Distance Order/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们定义一个队列 $q$,初始时将坐标点 $(rCenter, cCenter)$ 入队,用一个二维布尔数组 $vis$ 记录已经访问过的点,初始时 $vis[rCenter][cCenter]$ 为 $true$。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def allCellsDistOrder( @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java import java.util.Deque; @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) (ans [][]int) { q := [][]int{{rCenter, cCenter}} @@ -185,10 +171,6 @@ func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) (ans [][]in } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md b/solution/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md index c5c5b04be94f1..9116d4750dff0 100644 --- a/solution/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md +++ b/solution/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md @@ -48,9 +48,9 @@ There are other answers that would also be accepted as correct, such as [[1,2],[ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java import java.util.Deque; @@ -105,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +134,6 @@ public: }; ``` -### **Go** - ```go func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) (ans [][]int) { q := [][]int{{rCenter, cCenter}} @@ -167,10 +161,6 @@ func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) (ans [][]in } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1031.Maximum Sum of Two Non-Overlapping Subarrays/README.md b/solution/1000-1099/1031.Maximum Sum of Two Non-Overlapping Subarrays/README.md index 1a97fbb669204..63e734d5e7ff9 100644 --- a/solution/1000-1099/1031.Maximum Sum of Two Non-Overlapping Subarrays/README.md +++ b/solution/1000-1099/1031.Maximum Sum of Two Non-Overlapping Subarrays/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:前缀和 + 枚举** +### 方法一:前缀和 + 枚举 我们先预处理得到数组 `nums` 的前缀和数组 $s$,其中 $s[i]$ 表示 $nums$ 中前 $i$ 个元素的和。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int: @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func maxSumTwoNoOverlap(nums []int, firstLen int, secondLen int) (ans int) { n := len(nums) @@ -165,10 +151,6 @@ func maxSumTwoNoOverlap(nums []int, firstLen int, secondLen int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1031.Maximum Sum of Two Non-Overlapping Subarrays/README_EN.md b/solution/1000-1099/1031.Maximum Sum of Two Non-Overlapping Subarrays/README_EN.md index 9e7b7f0e4b136..fc8742ec8fd1c 100644 --- a/solution/1000-1099/1031.Maximum Sum of Two Non-Overlapping Subarrays/README_EN.md +++ b/solution/1000-1099/1031.Maximum Sum of Two Non-Overlapping Subarrays/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +116,6 @@ public: }; ``` -### **Go** - ```go func maxSumTwoNoOverlap(nums []int, firstLen int, secondLen int) (ans int) { n := len(nums) @@ -141,10 +135,6 @@ func maxSumTwoNoOverlap(nums []int, firstLen int, secondLen int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1032.Stream of Characters/README.md b/solution/1000-1099/1032.Stream of Characters/README.md index a2fe7cd226b86..a3eec4598847b 100644 --- a/solution/1000-1099/1032.Stream of Characters/README.md +++ b/solution/1000-1099/1032.Stream of Characters/README.md @@ -58,9 +58,7 @@ streamChecker.query("l"); // 返回 True ,因为 'kl' 在 words 中 ## 解法 - - -**方法一:前缀树** +### 方法一:前缀树 我们可以根据初始化时的字符串数组 $words$ 构建前缀树,前缀树的每个节点包含两个属性: @@ -75,10 +73,6 @@ streamChecker.query("l"); // 返回 True ,因为 'kl' 在 words 中 -### **Python3** - - - ```python class Trie: def __init__(self): @@ -124,10 +118,6 @@ class StreamChecker: # param_1 = obj.query(letter) ``` -### **Java** - - - ```java class Trie { Trie[] children = new Trie[26]; @@ -184,8 +174,6 @@ class StreamChecker { */ ``` -### **C++** - ```cpp class Trie { public: @@ -249,8 +237,6 @@ public: */ ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -313,10 +299,6 @@ func (this *StreamChecker) Query(letter byte) bool { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1032.Stream of Characters/README_EN.md b/solution/1000-1099/1032.Stream of Characters/README_EN.md index 4437977c9bd70..f3c9134c61fe2 100644 --- a/solution/1000-1099/1032.Stream of Characters/README_EN.md +++ b/solution/1000-1099/1032.Stream of Characters/README_EN.md @@ -54,9 +54,9 @@ streamChecker.query("l"); // return True, because 'kl' is in t ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -103,8 +103,6 @@ class StreamChecker: # param_1 = obj.query(letter) ``` -### **Java** - ```java class Trie { Trie[] children = new Trie[26]; @@ -161,8 +159,6 @@ class StreamChecker { */ ``` -### **C++** - ```cpp class Trie { public: @@ -226,8 +222,6 @@ public: */ ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -290,10 +284,6 @@ func (this *StreamChecker) Query(letter byte) bool { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md b/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md index f89c42f21ebda..9ec5883072b75 100644 --- a/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md +++ b/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:分类讨论** +### 方法一:分类讨论 我们先将 $a, b, c$ 排序,记为 $x, y, z$,即 $x \lt y \lt z$。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def numMovesStones(self, a: int, b: int, c: int) -> List[int]: @@ -77,10 +71,6 @@ class Solution: return [mi, mx] ``` -### **Java** - - - ```java class Solution { public int[] numMovesStones(int a, int b, int c) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func numMovesStones(a int, b int, c int) []int { x := min(a, min(b, c)) @@ -135,8 +121,6 @@ func numMovesStones(a int, b int, c int) []int { } ``` -### **TypeScript** - ```ts function numMovesStones(a: number, b: number, c: number): number[] { const x = Math.min(a, Math.min(b, c)); @@ -152,10 +136,6 @@ function numMovesStones(a: number, b: number, c: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md b/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md index 685baf2b77ec5..b37dac2f87cb5 100644 --- a/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md +++ b/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md @@ -52,9 +52,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return [mi, mx] ``` -### **Java** - ```java class Solution { public int[] numMovesStones(int a, int b, int c) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +101,6 @@ public: }; ``` -### **Go** - ```go func numMovesStones(a int, b int, c int) []int { x := min(a, min(b, c)) @@ -124,8 +118,6 @@ func numMovesStones(a int, b int, c int) []int { } ``` -### **TypeScript** - ```ts function numMovesStones(a: number, b: number, c: number): number[] { const x = Math.min(a, Math.min(b, c)); @@ -141,10 +133,6 @@ function numMovesStones(a: number, b: number, c: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1034.Coloring A Border/README.md b/solution/1000-1099/1034.Coloring A Border/README.md index 4a2b332517e59..b143a8df27434 100644 --- a/solution/1000-1099/1034.Coloring A Border/README.md +++ b/solution/1000-1099/1034.Coloring A Border/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们从位置 $(row, col)$ 出发,利用 DFS 搜索所有颜色为 $grid[row][col]$ 的网格块,如果该网格块的某个相邻位置的颜色不为 $grid[row][col]$,或者该网格块在网格的边界上,则将该网格块的颜色改为 $color$。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def colorBorder( @@ -96,10 +90,6 @@ class Solution: return grid ``` -### **Java** - - - ```java class Solution { private int[][] grid; @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -174,8 +162,6 @@ public: }; ``` -### **Go** - ```go func colorBorder(grid [][]int, row int, col int, color int) [][]int { m, n := len(grid), len(grid[0]) @@ -207,8 +193,6 @@ func colorBorder(grid [][]int, row int, col int, color int) [][]int { } ``` -### **TypeScript** - ```ts function colorBorder(grid: number[][], row: number, col: number, color: number): number[][] { const m = grid.length; @@ -238,10 +222,6 @@ function colorBorder(grid: number[][], row: number, col: number, color: number): } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1034.Coloring A Border/README_EN.md b/solution/1000-1099/1034.Coloring A Border/README_EN.md index 5737bd6a63a0f..99f185b23f002 100644 --- a/solution/1000-1099/1034.Coloring A Border/README_EN.md +++ b/solution/1000-1099/1034.Coloring A Border/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return grid ``` -### **Java** - ```java class Solution { private int[][] grid; @@ -110,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +141,6 @@ public: }; ``` -### **Go** - ```go func colorBorder(grid [][]int, row int, col int, color int) [][]int { m, n := len(grid), len(grid[0]) @@ -178,8 +172,6 @@ func colorBorder(grid [][]int, row int, col int, color int) [][]int { } ``` -### **TypeScript** - ```ts function colorBorder(grid: number[][], row: number, col: number, color: number): number[][] { const m = grid.length; @@ -209,10 +201,6 @@ function colorBorder(grid: number[][], row: number, col: number, color: number): } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1035.Uncrossed Lines/README.md b/solution/1000-1099/1035.Uncrossed Lines/README.md index 79db55e99b4f7..d103fd4d6eb43 100644 --- a/solution/1000-1099/1035.Uncrossed Lines/README.md +++ b/solution/1000-1099/1035.Uncrossed Lines/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 最长公共子序列问题。 @@ -80,10 +78,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: @@ -98,10 +92,6 @@ class Solution: return dp[m][n] ``` -### **Java** - - - ```java class Solution { public int maxUncrossedLines(int[] nums1, int[] nums2) { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func maxUncrossedLines(nums1 []int, nums2 []int) int { m, n := len(nums1), len(nums2) @@ -166,8 +152,6 @@ func maxUncrossedLines(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - ```ts function maxUncrossedLines(nums1: number[], nums2: number[]): number { const m = nums1.length; @@ -185,10 +169,6 @@ function maxUncrossedLines(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1035.Uncrossed Lines/README_EN.md b/solution/1000-1099/1035.Uncrossed Lines/README_EN.md index 93decb5f22417..3b4320e5fce32 100644 --- a/solution/1000-1099/1035.Uncrossed Lines/README_EN.md +++ b/solution/1000-1099/1035.Uncrossed Lines/README_EN.md @@ -51,20 +51,10 @@ We cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] ## Solutions -Longest common sub-sequences - -$$ -dp[i][j]= -\begin{cases} -dp[i-1][j-1]+1, & nums1[i-1]=nums2[j-1] \\ -\max(dp[i-1][j], dp[i][j-1]), & nums1[i-1]\neq nums2[j-1] -\end{cases} -$$ +### Solution 1 -### **Python3** - ```python class Solution: def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: @@ -79,8 +69,6 @@ class Solution: return dp[m][n] ``` -### **Java** - ```java class Solution { public int maxUncrossedLines(int[] nums1, int[] nums2) { @@ -101,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +109,6 @@ public: }; ``` -### **Go** - ```go func maxUncrossedLines(nums1 []int, nums2 []int) int { m, n := len(nums1), len(nums2) @@ -145,8 +129,6 @@ func maxUncrossedLines(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - ```ts function maxUncrossedLines(nums1: number[], nums2: number[]): number { const m = nums1.length; @@ -164,10 +146,6 @@ function maxUncrossedLines(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1036.Escape a Large Maze/README.md b/solution/1000-1099/1036.Escape a Large Maze/README.md index ee24eef1fe2f2..4c0880effc18c 100644 --- a/solution/1000-1099/1036.Escape a Large Maze/README.md +++ b/solution/1000-1099/1036.Escape a Large Maze/README.md @@ -51,14 +51,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def isEscapePossible( @@ -85,10 +81,6 @@ class Solution: return dfs(source, target, set()) and dfs(target, source, set()) ``` -### **Java** - - - ```java class Solution { private int[][] dirs = new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; @@ -124,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef unsigned long long ULL; @@ -158,8 +148,6 @@ public: }; ``` -### **Go** - ```go func isEscapePossible(blocked [][]int, source []int, target []int) bool { const N = 1e6 @@ -192,8 +180,6 @@ func isEscapePossible(blocked [][]int, source []int, target []int) bool { } ``` -### **Rust** - ```rust use std::collections::{ HashSet, VecDeque }; @@ -244,10 +230,6 @@ fn bfs(block: &HashSet<(i32, i32)>, source: &Vec, target: &Vec) -> boo } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1036.Escape a Large Maze/README_EN.md b/solution/1000-1099/1036.Escape a Large Maze/README_EN.md index e7ffbd5408960..6ea6d12eefdde 100644 --- a/solution/1000-1099/1036.Escape a Large Maze/README_EN.md +++ b/solution/1000-1099/1036.Escape a Large Maze/README_EN.md @@ -46,9 +46,9 @@ We cannot move south or west because we cannot go outside of the grid. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return dfs(source, target, set()) and dfs(target, source, set()) ``` -### **Java** - ```java class Solution { private int[][] dirs = new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; @@ -113,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef unsigned long long ULL; @@ -147,8 +143,6 @@ public: }; ``` -### **Go** - ```go func isEscapePossible(blocked [][]int, source []int, target []int) bool { const N = 1e6 @@ -181,8 +175,6 @@ func isEscapePossible(blocked [][]int, source []int, target []int) bool { } ``` -### **Rust** - ```rust use std::collections::{ HashSet, VecDeque }; @@ -233,10 +225,6 @@ fn bfs(block: &HashSet<(i32, i32)>, source: &Vec, target: &Vec) -> boo } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1037.Valid Boomerang/README.md b/solution/1000-1099/1037.Valid Boomerang/README.md index cf1b2615cae9c..af1cf4320c04f 100644 --- a/solution/1000-1099/1037.Valid Boomerang/README.md +++ b/solution/1000-1099/1037.Valid Boomerang/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:斜率比较** +### 方法一:斜率比较 设三点分别为 $(x_1,y_1)$, $(x_2,y_2)$, $(x_3,y_3)$。两点之间斜率计算公式为 $\frac{y_2-y_1}{x_2-x_1}$。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def isBoomerang(self, points: List[List[int]]) -> bool: @@ -66,10 +60,6 @@ class Solution: return (y2 - y1) * (x3 - x2) != (y3 - y2) * (x2 - x1) ``` -### **Java** - - - ```java class Solution { public boolean isBoomerang(int[][] points) { @@ -81,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +83,6 @@ public: }; ``` -### **Go** - ```go func isBoomerang(points [][]int) bool { x1, y1 := points[0][0], points[0][1] @@ -106,8 +92,6 @@ func isBoomerang(points [][]int) bool { } ``` -### **TypeScript** - ```ts function isBoomerang(points: number[][]): boolean { const [x1, y1] = points[0]; @@ -117,8 +101,6 @@ function isBoomerang(points: number[][]): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_boomerang(points: Vec>) -> bool { @@ -130,10 +112,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1037.Valid Boomerang/README_EN.md b/solution/1000-1099/1037.Valid Boomerang/README_EN.md index faa1bef4e82c3..a35ecf0b1427a 100644 --- a/solution/1000-1099/1037.Valid Boomerang/README_EN.md +++ b/solution/1000-1099/1037.Valid Boomerang/README_EN.md @@ -27,9 +27,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -38,8 +38,6 @@ class Solution: return (y2 - y1) * (x3 - x2) != (y3 - y2) * (x2 - x1) ``` -### **Java** - ```java class Solution { public boolean isBoomerang(int[][] points) { @@ -51,8 +49,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -65,8 +61,6 @@ public: }; ``` -### **Go** - ```go func isBoomerang(points [][]int) bool { x1, y1 := points[0][0], points[0][1] @@ -76,8 +70,6 @@ func isBoomerang(points [][]int) bool { } ``` -### **TypeScript** - ```ts function isBoomerang(points: number[][]): boolean { const [x1, y1] = points[0]; @@ -87,8 +79,6 @@ function isBoomerang(points: number[][]): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_boomerang(points: Vec>) -> bool { @@ -100,10 +90,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README.md b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README.md index d7e36ffbb7d1e..3f3093ef0819a 100644 --- a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README.md +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README.md @@ -50,43 +50,14 @@ ## 解法 - - -**前言** - -二叉搜索树的中序遍历(左根右)结果是一个单调递增的有序序列,我们反序进行中序遍历(右根左),即可以得到一个单调递减的有序序列。通过累加单调递减的有序序列,我们可以得到大于等于 `node.val` 的新值,并重新赋值给 `node`。 - -关于反序中序遍历,有三种方法,一是递归遍历,二是栈实现非递归遍历,三是 Morris 遍历。 - -**方法一:递归** +### 方法一:递归 按照“右根左”的顺序,递归遍历二叉搜索树,累加遍历到的所有节点值到 $s$ 中,然后每次赋值给对应的 `node` 节点。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉搜索树的节点数。 -**方法二:Morris 遍历** - -Morris 遍历无需使用栈,时间复杂度 $O(n)$,空间复杂度为 $O(1)$。核心思想是: - -定义 s 表示二叉搜索树节点值累加和。遍历二叉树节点: - -1. 若当前节点 root 的右子树为空,**将当前节点值添加至 s** 中,更新当前节点值为 s,并将当前节点更新为 `root.left`。 -2. 若当前节点 root 的右子树不为空,找到右子树的最左节点 next(也即是 root 节点在中序遍历下的后继节点): - - 若后继节点 next 的左子树为空,将后继节点的左子树指向当前节点 root,并将当前节点更新为 `root.right`。 - - 若后继节点 next 的左子树不为空,**将当前节点值添加 s** 中,更新当前节点值为 s,然后将后继节点左子树指向空(即解除 next 与 root 的指向关系),并将当前节点更新为 `root.left`。 -3. 循环以上步骤,直至二叉树节点为空,遍历结束。 -4. 最后返回二叉搜索树根节点即可。 - -> Morris 反序中序遍历跟 Morris 中序遍历思路一致,只是将中序遍历的“左根右”变为“右根左”。 - -### **Python3** - - - -递归遍历: - ```python # Definition for a binary tree node. # class TreeNode: @@ -110,45 +81,6 @@ class Solution: return root ``` -Morris 遍历: - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def bstToGst(self, root: TreeNode) -> TreeNode: - s = 0 - node = root - while root: - if root.right is None: - s += root.val - root.val = s - root = root.left - else: - next = root.right - while next.left and next.left != root: - next = next.left - if next.left is None: - next.left = root - root = root.right - else: - s += root.val - root.val = s - next.left = None - root = root.left - return node -``` - -### **Java** - - - -递归遍历: - ```java /** * Definition for a binary tree node. @@ -185,7 +117,236 @@ class Solution { } ``` -Morris 遍历: +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int s = 0; + + TreeNode* bstToGst(TreeNode* root) { + dfs(root); + return root; + } + + void dfs(TreeNode* root) { + if (!root) return; + dfs(root->right); + s += root->val; + root->val = s; + dfs(root->left); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func bstToGst(root *TreeNode) *TreeNode { + s := 0 + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return + } + dfs(root.Right) + s += root.Val + root.Val = s + dfs(root.Left) + } + dfs(root) + return root +} +``` + +```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 bstToGst(root: TreeNode | null): TreeNode | null { + const dfs = (root: TreeNode | null, sum: number) => { + if (root == null) { + return sum; + } + const { val, left, right } = root; + sum = dfs(right, sum) + val; + root.val = sum; + sum = dfs(left, sum); + return sum; + }; + dfs(root, 0); + return root; +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(root: &mut Option>>, mut sum: i32) -> i32 { + if let Some(node) = root { + let mut node = node.as_ref().borrow_mut(); + sum = Self::dfs(&mut node.right, sum) + node.val; + node.val = sum; + sum = Self::dfs(&mut node.left, sum); + } + sum + } + + pub fn bst_to_gst(mut root: Option>>) -> Option>> { + Self::dfs(&mut root, 0); + root + } +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {TreeNode} + */ +var bstToGst = function (root) { + let s = 0; + function dfs(root) { + if (!root) { + return; + } + dfs(root.right); + s += root.val; + root.val = s; + dfs(root.left); + } + dfs(root); + return root; +}; +``` + +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +int dfs(struct TreeNode* root, int sum) { + if (root) { + sum = dfs(root->right, sum) + root->val; + root->val = sum; + sum = dfs(root->left, sum); + } + return sum; +} + +struct TreeNode* bstToGst(struct TreeNode* root) { + dfs(root, 0); + return root; +} +``` + + + +### 方法二:Morris 遍历 + +Morris 遍历无需使用栈,时间复杂度 $O(n)$,空间复杂度为 $O(1)$。核心思想是: + +定义 s 表示二叉搜索树节点值累加和。遍历二叉树节点: + +1. 若当前节点 root 的右子树为空,**将当前节点值添加至 s** 中,更新当前节点值为 s,并将当前节点更新为 `root.left`。 +2. 若当前节点 root 的右子树不为空,找到右子树的最左节点 next(也即是 root 节点在中序遍历下的后继节点): + - 若后继节点 next 的左子树为空,将后继节点的左子树指向当前节点 root,并将当前节点更新为 `root.right`。 + - 若后继节点 next 的左子树不为空,**将当前节点值添加 s** 中,更新当前节点值为 s,然后将后继节点左子树指向空(即解除 next 与 root 的指向关系),并将当前节点更新为 `root.left`。 +3. 循环以上步骤,直至二叉树节点为空,遍历结束。 +4. 最后返回二叉搜索树根节点即可。 + +> Morris 反序中序遍历跟 Morris 中序遍历思路一致,只是将中序遍历的“左根右”变为“右根左”。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def bstToGst(self, root: TreeNode) -> TreeNode: + s = 0 + node = root + while root: + if root.right is None: + s += root.val + root.val = s + root = root.left + else: + next = root.right + while next.left and next.left != root: + next = next.left + if next.left is None: + next.left = root + root = root.right + else: + s += root.val + root.val = s + next.left = None + root = root.left + return node +``` ```java /** @@ -233,43 +394,6 @@ class Solution { } ``` -### **C++** - -递归遍历: - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int s = 0; - - TreeNode* bstToGst(TreeNode* root) { - dfs(root); - return root; - } - - void dfs(TreeNode* root) { - if (!root) return; - dfs(root->right); - s += root->val; - root->val = s; - dfs(root->left); - } -}; -``` - -Morris 遍历: - ```cpp /** * Definition for a binary tree node. @@ -313,38 +437,6 @@ public: }; ``` -### **Go** - -递归遍历: - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func bstToGst(root *TreeNode) *TreeNode { - s := 0 - var dfs func(*TreeNode) - dfs = func(root *TreeNode) { - if root == nil { - return - } - dfs(root.Right) - s += root.Val - root.Val = s - dfs(root.Left) - } - dfs(root) - return root -} -``` - -Morris 遍历: - ```go /** * Definition for a binary tree node. @@ -382,70 +474,6 @@ func bstToGst(root *TreeNode) *TreeNode { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {TreeNode} - */ -var bstToGst = function (root) { - let s = 0; - function dfs(root) { - if (!root) { - return; - } - dfs(root.right); - s += root.val; - root.val = s; - dfs(root.left); - } - dfs(root); - return root; -}; -``` - -### **TypeScript** - -```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 bstToGst(root: TreeNode | null): TreeNode | null { - const dfs = (root: TreeNode | null, sum: number) => { - if (root == null) { - return sum; - } - const { val, left, right } = root; - sum = dfs(right, sum) + val; - root.val = sum; - sum = dfs(left, sum); - return sum; - }; - dfs(root, 0); - return root; -} -``` - ```ts /** * Definition for a binary tree node. @@ -490,74 +518,6 @@ function bstToGst(root: TreeNode | null): TreeNode | null { } ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(root: &mut Option>>, mut sum: i32) -> i32 { - if let Some(node) = root { - let mut node = node.as_ref().borrow_mut(); - sum = Self::dfs(&mut node.right, sum) + node.val; - node.val = sum; - sum = Self::dfs(&mut node.left, sum); - } - sum - } - - pub fn bst_to_gst(mut root: Option>>) -> Option>> { - Self::dfs(&mut root, 0); - root - } -} -``` - -### **C** - -```c -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -int dfs(struct TreeNode* root, int sum) { - if (root) { - sum = dfs(root->right, sum) + root->val; - root->val = sum; - sum = dfs(root->left, sum); - } - return sum; -} - -struct TreeNode* bstToGst(struct TreeNode* root) { - dfs(root, 0); - return root; -} -``` - ```c /** * Definition for a binary tree node. @@ -596,10 +556,6 @@ struct TreeNode* bstToGst(struct TreeNode* root) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README_EN.md b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README_EN.md index 6000231ad4f01..281549518d0fe 100644 --- a/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README_EN.md +++ b/solution/1000-1099/1038.Binary Search Tree to Greater Sum Tree/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -70,39 +70,6 @@ class Solution: return root ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def bstToGst(self, root: TreeNode) -> TreeNode: - s = 0 - node = root - while root: - if root.right is None: - s += root.val - root.val = s - root = root.left - else: - next = root.right - while next.left and next.left != root: - next = next.left - if next.left is None: - next.left = root - root = root.right - else: - s += root.val - root.val = s - next.left = None - root = root.left - return node -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -139,6 +106,224 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int s = 0; + + TreeNode* bstToGst(TreeNode* root) { + dfs(root); + return root; + } + + void dfs(TreeNode* root) { + if (!root) return; + dfs(root->right); + s += root->val; + root->val = s; + dfs(root->left); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func bstToGst(root *TreeNode) *TreeNode { + s := 0 + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return + } + dfs(root.Right) + s += root.Val + root.Val = s + dfs(root.Left) + } + dfs(root) + return root +} +``` + +```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 bstToGst(root: TreeNode | null): TreeNode | null { + const dfs = (root: TreeNode | null, sum: number) => { + if (root == null) { + return sum; + } + const { val, left, right } = root; + sum = dfs(right, sum) + val; + root.val = sum; + sum = dfs(left, sum); + return sum; + }; + dfs(root, 0); + return root; +} +``` + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(root: &mut Option>>, mut sum: i32) -> i32 { + if let Some(node) = root { + let mut node = node.as_ref().borrow_mut(); + sum = Self::dfs(&mut node.right, sum) + node.val; + node.val = sum; + sum = Self::dfs(&mut node.left, sum); + } + sum + } + + pub fn bst_to_gst(mut root: Option>>) -> Option>> { + Self::dfs(&mut root, 0); + root + } +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {TreeNode} + */ +var bstToGst = function (root) { + let s = 0; + function dfs(root) { + if (!root) { + return; + } + dfs(root.right); + s += root.val; + root.val = s; + dfs(root.left); + } + dfs(root); + return root; +}; +``` + +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +int dfs(struct TreeNode* root, int sum) { + if (root) { + sum = dfs(root->right, sum) + root->val; + root->val = sum; + sum = dfs(root->left, sum); + } + return sum; +} + +struct TreeNode* bstToGst(struct TreeNode* root) { + dfs(root, 0); + return root; +} +``` + + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def bstToGst(self, root: TreeNode) -> TreeNode: + s = 0 + node = root + while root: + if root.right is None: + s += root.val + root.val = s + root = root.left + else: + next = root.right + while next.left and next.left != root: + next = next.left + if next.left is None: + next.left = root + root = root.right + else: + s += root.val + root.val = s + next.left = None + root = root.left + return node +``` + ```java /** * Definition for a binary tree node. @@ -185,39 +370,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int s = 0; - - TreeNode* bstToGst(TreeNode* root) { - dfs(root); - return root; - } - - void dfs(TreeNode* root) { - if (!root) return; - dfs(root->right); - s += root->val; - root->val = s; - dfs(root->left); - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -261,34 +413,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func bstToGst(root *TreeNode) *TreeNode { - s := 0 - var dfs func(*TreeNode) - dfs = func(root *TreeNode) { - if root == nil { - return - } - dfs(root.Right) - s += root.Val - root.Val = s - dfs(root.Left) - } - dfs(root) - return root -} -``` - ```go /** * Definition for a binary tree node. @@ -326,70 +450,6 @@ func bstToGst(root *TreeNode) *TreeNode { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {TreeNode} - */ -var bstToGst = function (root) { - let s = 0; - function dfs(root) { - if (!root) { - return; - } - dfs(root.right); - s += root.val; - root.val = s; - dfs(root.left); - } - dfs(root); - return root; -}; -``` - -### **TypeScript** - -```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 bstToGst(root: TreeNode | null): TreeNode | null { - const dfs = (root: TreeNode | null, sum: number) => { - if (root == null) { - return sum; - } - const { val, left, right } = root; - sum = dfs(right, sum) + val; - root.val = sum; - sum = dfs(left, sum); - return sum; - }; - dfs(root, 0); - return root; -} -``` - ```ts /** * Definition for a binary tree node. @@ -434,74 +494,6 @@ function bstToGst(root: TreeNode | null): TreeNode | null { } ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(root: &mut Option>>, mut sum: i32) -> i32 { - if let Some(node) = root { - let mut node = node.as_ref().borrow_mut(); - sum = Self::dfs(&mut node.right, sum) + node.val; - node.val = sum; - sum = Self::dfs(&mut node.left, sum); - } - sum - } - - pub fn bst_to_gst(mut root: Option>>) -> Option>> { - Self::dfs(&mut root, 0); - root - } -} -``` - -### **C** - -```c -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -int dfs(struct TreeNode* root, int sum) { - if (root) { - sum = dfs(root->right, sum) + root->val; - root->val = sum; - sum = dfs(root->left, sum); - } - return sum; -} - -struct TreeNode* bstToGst(struct TreeNode* root) { - dfs(root, 0); - return root; -} -``` - ```c /** * Definition for a binary tree node. @@ -540,10 +532,6 @@ struct TreeNode* bstToGst(struct TreeNode* root) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README.md b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README.md index 89ce25cd2179d..4389d6240df8f 100644 --- a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README.md +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j)$,表示将多边形的顶点 $i$ 到 $j$ 进行三角剖分后的最低分数。那么答案就是 $dfs(0, n - 1)$。 @@ -76,45 +74,8 @@ 时间复杂度 $O(n^3)$,空间复杂度 $O(n^2)$。其中 $n$ 为多边形的顶点数。 -**方法二:动态规划** - -我们可以将方法一中的记忆化搜索改为动态规划。 - -定义 $f[i][j]$ 表示将多边形的顶点 $i$ 到 $j$ 进行三角剖分后的最低分数。初始时 $f[i][j]=0$,答案为 $f[0][n-1]$。 - -对于 $f[i][j]$(这里要求 $i + 1 \lt j$),我们先将 $f[i][j]$ 初始化为 $\infty$。 - -我们枚举 $i$ 和 $j$ 之间的一个顶点 $k$,即 $i \lt k \lt j$,将多边形的顶点 $i$ 到 $j$ 进行三角剖分,可以分为两个子问题:将多边形的顶点 $i$ 到 $k$ 进行三角剖分,以及将多边形的顶点 $k$ 到 $j$ 进行三角剖分。这两个子问题的最低分数分别为 $f[i][k]$ 和 $f[k][j]$,而顶点 $i$, $j$ 和 $k$ 构成的三角形的分数为 $values[i] \times values[k] \times values[j]$。那么,此次三角剖分的最低分数为 $f[i][k] + f[k][j] + values[i] \times values[k] \times values[j]$,我们取所有可能的最小值,即为 $f[i][j]$ 的值。 - -综上,我们可以得到状态转移方程: - -$$ -f[i][j]= -\begin{cases} -0, & i+1=j \\ -\min_{i -### **Python3** - - - ```python class Solution: def minScoreTriangulation(self, values: List[int]) -> int: @@ -130,39 +91,6 @@ class Solution: return dfs(0, len(values) - 1) ``` -```python -class Solution: - def minScoreTriangulation(self, values: List[int]) -> int: - n = len(values) - f = [[0] * n for _ in range(n)] - for i in range(n - 3, -1, -1): - for j in range(i + 2, n): - f[i][j] = min( - f[i][k] + f[k][j] + values[i] * values[k] * values[j] - for k in range(i + 1, j) - ) - return f[0][-1] -``` - -```python -class Solution: - def minScoreTriangulation(self, values: List[int]) -> int: - n = len(values) - f = [[0] * n for _ in range(n)] - for l in range(3, n + 1): - for i in range(n - l + 1): - j = i + l - 1 - f[i][j] = min( - f[i][k] + f[k][j] + values[i] * values[k] * values[j] - for k in range(i + 1, j) - ) - return f[0][-1] -``` - -### **Java** - - - ```java class Solution { private int n; @@ -192,47 +120,6 @@ class Solution { } ``` -```java -class Solution { - public int minScoreTriangulation(int[] values) { - int n = values.length; - int[][] f = new int[n][n]; - for (int i = n - 3; i >= 0; --i) { - for (int j = i + 2; j < n; ++j) { - f[i][j] = 1 << 30; - for (int k = i + 1; k < j; ++k) { - f[i][j] - = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); - } - } - } - return f[0][n - 1]; - } -} -``` - -```java -class Solution { - public int minScoreTriangulation(int[] values) { - int n = values.length; - int[][] f = new int[n][n]; - for (int l = 3; l <= n; ++l) { - for (int i = 0; i + l - 1 < n; ++i) { - int j = i + l - 1; - f[i][j] = 1 << 30; - for (int k = i + 1; k < j; ++k) { - f[i][j] - = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); - } - } - } - return f[0][n - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -258,24 +145,118 @@ public: }; ``` -```cpp +```go +func minScoreTriangulation(values []int) int { + n := len(values) + f := [50][50]int{} + var dfs func(int, int) int + dfs = func(i, j int) int { + if i+1 == j { + return 0 + } + if f[i][j] != 0 { + return f[i][j] + } + f[i][j] = 1 << 30 + for k := i + 1; k < j; k++ { + f[i][j] = min(f[i][j], dfs(i, k)+dfs(k, j)+values[i]*values[k]*values[j]) + } + return f[i][j] + } + return dfs(0, n-1) +} +``` + +```ts +function minScoreTriangulation(values: number[]): number { + const n = values.length; + const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); + const dfs = (i: number, j: number): number => { + if (i + 1 === j) { + return 0; + } + if (f[i][j] > 0) { + return f[i][j]; + } + let ans = 1 << 30; + for (let k = i + 1; k < j; ++k) { + ans = Math.min(ans, dfs(i, k) + dfs(k, j) + values[i] * values[k] * values[j]); + } + f[i][j] = ans; + return ans; + }; + return dfs(0, n - 1); +} +``` + + + +### 方法二:动态规划 + +我们可以将方法一中的记忆化搜索改为动态规划。 + +定义 $f[i][j]$ 表示将多边形的顶点 $i$ 到 $j$ 进行三角剖分后的最低分数。初始时 $f[i][j]=0$,答案为 $f[0][n-1]$。 + +对于 $f[i][j]$(这里要求 $i + 1 \lt j$),我们先将 $f[i][j]$ 初始化为 $\infty$。 + +我们枚举 $i$ 和 $j$ 之间的一个顶点 $k$,即 $i \lt k \lt j$,将多边形的顶点 $i$ 到 $j$ 进行三角剖分,可以分为两个子问题:将多边形的顶点 $i$ 到 $k$ 进行三角剖分,以及将多边形的顶点 $k$ 到 $j$ 进行三角剖分。这两个子问题的最低分数分别为 $f[i][k]$ 和 $f[k][j]$,而顶点 $i$, $j$ 和 $k$ 构成的三角形的分数为 $values[i] \times values[k] \times values[j]$。那么,此次三角剖分的最低分数为 $f[i][k] + f[k][j] + values[i] \times values[k] \times values[j]$,我们取所有可能的最小值,即为 $f[i][j]$ 的值。 + +综上,我们可以得到状态转移方程: + +$$ +f[i][j]= +\begin{cases} +0, & i+1=j \\ +\min_{i + +```python +class Solution: + def minScoreTriangulation(self, values: List[int]) -> int: + n = len(values) + f = [[0] * n for _ in range(n)] + for i in range(n - 3, -1, -1): + for j in range(i + 2, n): + f[i][j] = min( + f[i][k] + f[k][j] + values[i] * values[k] * values[j] + for k in range(i + 1, j) + ) + return f[0][-1] +``` + +```java class Solution { -public: - int minScoreTriangulation(vector& values) { - int n = values.size(); - int f[n][n]; - memset(f, 0, sizeof(f)); + public int minScoreTriangulation(int[] values) { + int n = values.length; + int[][] f = new int[n][n]; for (int i = n - 3; i >= 0; --i) { for (int j = i + 2; j < n; ++j) { f[i][j] = 1 << 30; for (int k = i + 1; k < j; ++k) { - f[i][j] = min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + f[i][j] + = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); } } } return f[0][n - 1]; } -}; +} ``` ```cpp @@ -285,9 +266,8 @@ public: int n = values.size(); int f[n][n]; memset(f, 0, sizeof(f)); - for (int l = 3; l <= n; ++l) { - for (int i = 0; i + l - 1 < n; ++i) { - int j = i + l - 1; + for (int i = n - 3; i >= 0; --i) { + for (int j = i + 2; j < n; ++j) { f[i][j] = 1 << 30; for (int k = i + 1; k < j; ++k) { f[i][j] = min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); @@ -299,30 +279,6 @@ public: }; ``` -### **Go** - -```go -func minScoreTriangulation(values []int) int { - n := len(values) - f := [50][50]int{} - var dfs func(int, int) int - dfs = func(i, j int) int { - if i+1 == j { - return 0 - } - if f[i][j] != 0 { - return f[i][j] - } - f[i][j] = 1 << 30 - for k := i + 1; k < j; k++ { - f[i][j] = min(f[i][j], dfs(i, k)+dfs(k, j)+values[i]*values[k]*values[j]) - } - return f[i][j] - } - return dfs(0, n-1) -} -``` - ```go func minScoreTriangulation(values []int) int { n := len(values) @@ -339,6 +295,84 @@ func minScoreTriangulation(values []int) int { } ``` +```ts +function minScoreTriangulation(values: number[]): number { + const n = values.length; + const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); + for (let i = n - 3; i >= 0; --i) { + for (let j = i + 2; j < n; ++j) { + f[i][j] = 1 << 30; + for (let k = i + 1; k < j; ++k) { + f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + } + } + } + return f[0][n - 1]; +} +``` + + + +### 方法三 + + + +```python +class Solution: + def minScoreTriangulation(self, values: List[int]) -> int: + n = len(values) + f = [[0] * n for _ in range(n)] + for l in range(3, n + 1): + for i in range(n - l + 1): + j = i + l - 1 + f[i][j] = min( + f[i][k] + f[k][j] + values[i] * values[k] * values[j] + for k in range(i + 1, j) + ) + return f[0][-1] +``` + +```java +class Solution { + public int minScoreTriangulation(int[] values) { + int n = values.length; + int[][] f = new int[n][n]; + for (int l = 3; l <= n; ++l) { + for (int i = 0; i + l - 1 < n; ++i) { + int j = i + l - 1; + f[i][j] = 1 << 30; + for (int k = i + 1; k < j; ++k) { + f[i][j] + = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + } + } + } + return f[0][n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int minScoreTriangulation(vector& values) { + int n = values.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int l = 3; l <= n; ++l) { + for (int i = 0; i + l - 1 < n; ++i) { + int j = i + l - 1; + f[i][j] = 1 << 30; + for (int k = i + 1; k < j; ++k) { + f[i][j] = min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + } + } + } + return f[0][n - 1]; + } +}; +``` + ```go func minScoreTriangulation(values []int) int { n := len(values) @@ -356,46 +390,6 @@ func minScoreTriangulation(values []int) int { } ``` -### **TypeScript** - -```ts -function minScoreTriangulation(values: number[]): number { - const n = values.length; - const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); - const dfs = (i: number, j: number): number => { - if (i + 1 === j) { - return 0; - } - if (f[i][j] > 0) { - return f[i][j]; - } - let ans = 1 << 30; - for (let k = i + 1; k < j; ++k) { - ans = Math.min(ans, dfs(i, k) + dfs(k, j) + values[i] * values[k] * values[j]); - } - f[i][j] = ans; - return ans; - }; - return dfs(0, n - 1); -} -``` - -```ts -function minScoreTriangulation(values: number[]): number { - const n = values.length; - const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); - for (let i = n - 3; i >= 0; --i) { - for (let j = i + 2; j < n; ++j) { - f[i][j] = 1 << 30; - for (let k = i + 1; k < j; ++k) { - f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); - } - } - } - return f[0][n - 1]; -} -``` - ```ts function minScoreTriangulation(values: number[]): number { const n = values.length; @@ -413,10 +407,6 @@ function minScoreTriangulation(values: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README_EN.md b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README_EN.md index 0b7852612f6e9..11e77c72edb8f 100644 --- a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README_EN.md +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README_EN.md @@ -47,9 +47,9 @@ The minimum score is 144. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,37 +66,6 @@ class Solution: return dfs(0, len(values) - 1) ``` -```python -class Solution: - def minScoreTriangulation(self, values: List[int]) -> int: - n = len(values) - f = [[0] * n for _ in range(n)] - for i in range(n - 3, -1, -1): - for j in range(i + 2, n): - f[i][j] = min( - f[i][k] + f[k][j] + values[i] * values[k] * values[j] - for k in range(i + 1, j) - ) - return f[0][-1] -``` - -```python -class Solution: - def minScoreTriangulation(self, values: List[int]) -> int: - n = len(values) - f = [[0] * n for _ in range(n)] - for l in range(3, n + 1): - for i in range(n - l + 1): - j = i + l - 1 - f[i][j] = min( - f[i][k] + f[k][j] + values[i] * values[k] * values[j] - for k in range(i + 1, j) - ) - return f[0][-1] -``` - -### **Java** - ```java class Solution { private int n; @@ -126,47 +95,6 @@ class Solution { } ``` -```java -class Solution { - public int minScoreTriangulation(int[] values) { - int n = values.length; - int[][] f = new int[n][n]; - for (int i = n - 3; i >= 0; --i) { - for (int j = i + 2; j < n; ++j) { - f[i][j] = 1 << 30; - for (int k = i + 1; k < j; ++k) { - f[i][j] - = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); - } - } - } - return f[0][n - 1]; - } -} -``` - -```java -class Solution { - public int minScoreTriangulation(int[] values) { - int n = values.length; - int[][] f = new int[n][n]; - for (int l = 3; l <= n; ++l) { - for (int i = 0; i + l - 1 < n; ++i) { - int j = i + l - 1; - f[i][j] = 1 << 30; - for (int k = i + 1; k < j; ++k) { - f[i][j] - = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); - } - } - } - return f[0][n - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -192,24 +120,87 @@ public: }; ``` -```cpp +```go +func minScoreTriangulation(values []int) int { + n := len(values) + f := [50][50]int{} + var dfs func(int, int) int + dfs = func(i, j int) int { + if i+1 == j { + return 0 + } + if f[i][j] != 0 { + return f[i][j] + } + f[i][j] = 1 << 30 + for k := i + 1; k < j; k++ { + f[i][j] = min(f[i][j], dfs(i, k)+dfs(k, j)+values[i]*values[k]*values[j]) + } + return f[i][j] + } + return dfs(0, n-1) +} +``` + +```ts +function minScoreTriangulation(values: number[]): number { + const n = values.length; + const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); + const dfs = (i: number, j: number): number => { + if (i + 1 === j) { + return 0; + } + if (f[i][j] > 0) { + return f[i][j]; + } + let ans = 1 << 30; + for (let k = i + 1; k < j; ++k) { + ans = Math.min(ans, dfs(i, k) + dfs(k, j) + values[i] * values[k] * values[j]); + } + f[i][j] = ans; + return ans; + }; + return dfs(0, n - 1); +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minScoreTriangulation(self, values: List[int]) -> int: + n = len(values) + f = [[0] * n for _ in range(n)] + for i in range(n - 3, -1, -1): + for j in range(i + 2, n): + f[i][j] = min( + f[i][k] + f[k][j] + values[i] * values[k] * values[j] + for k in range(i + 1, j) + ) + return f[0][-1] +``` + +```java class Solution { -public: - int minScoreTriangulation(vector& values) { - int n = values.size(); - int f[n][n]; - memset(f, 0, sizeof(f)); + public int minScoreTriangulation(int[] values) { + int n = values.length; + int[][] f = new int[n][n]; for (int i = n - 3; i >= 0; --i) { for (int j = i + 2; j < n; ++j) { f[i][j] = 1 << 30; for (int k = i + 1; k < j; ++k) { - f[i][j] = min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + f[i][j] + = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); } } } return f[0][n - 1]; } -}; +} ``` ```cpp @@ -219,9 +210,8 @@ public: int n = values.size(); int f[n][n]; memset(f, 0, sizeof(f)); - for (int l = 3; l <= n; ++l) { - for (int i = 0; i + l - 1 < n; ++i) { - int j = i + l - 1; + for (int i = n - 3; i >= 0; --i) { + for (int j = i + 2; j < n; ++j) { f[i][j] = 1 << 30; for (int k = i + 1; k < j; ++k) { f[i][j] = min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); @@ -233,30 +223,6 @@ public: }; ``` -### **Go** - -```go -func minScoreTriangulation(values []int) int { - n := len(values) - f := [50][50]int{} - var dfs func(int, int) int - dfs = func(i, j int) int { - if i+1 == j { - return 0 - } - if f[i][j] != 0 { - return f[i][j] - } - f[i][j] = 1 << 30 - for k := i + 1; k < j; k++ { - f[i][j] = min(f[i][j], dfs(i, k)+dfs(k, j)+values[i]*values[k]*values[j]) - } - return f[i][j] - } - return dfs(0, n-1) -} -``` - ```go func minScoreTriangulation(values []int) int { n := len(values) @@ -273,6 +239,84 @@ func minScoreTriangulation(values []int) int { } ``` +```ts +function minScoreTriangulation(values: number[]): number { + const n = values.length; + const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); + for (let i = n - 3; i >= 0; --i) { + for (let j = i + 2; j < n; ++j) { + f[i][j] = 1 << 30; + for (let k = i + 1; k < j; ++k) { + f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + } + } + } + return f[0][n - 1]; +} +``` + + + +### Solution 3 + + + +```python +class Solution: + def minScoreTriangulation(self, values: List[int]) -> int: + n = len(values) + f = [[0] * n for _ in range(n)] + for l in range(3, n + 1): + for i in range(n - l + 1): + j = i + l - 1 + f[i][j] = min( + f[i][k] + f[k][j] + values[i] * values[k] * values[j] + for k in range(i + 1, j) + ) + return f[0][-1] +``` + +```java +class Solution { + public int minScoreTriangulation(int[] values) { + int n = values.length; + int[][] f = new int[n][n]; + for (int l = 3; l <= n; ++l) { + for (int i = 0; i + l - 1 < n; ++i) { + int j = i + l - 1; + f[i][j] = 1 << 30; + for (int k = i + 1; k < j; ++k) { + f[i][j] + = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + } + } + } + return f[0][n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int minScoreTriangulation(vector& values) { + int n = values.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int l = 3; l <= n; ++l) { + for (int i = 0; i + l - 1 < n; ++i) { + int j = i + l - 1; + f[i][j] = 1 << 30; + for (int k = i + 1; k < j; ++k) { + f[i][j] = min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + } + } + } + return f[0][n - 1]; + } +}; +``` + ```go func minScoreTriangulation(values []int) int { n := len(values) @@ -290,46 +334,6 @@ func minScoreTriangulation(values []int) int { } ``` -### **TypeScript** - -```ts -function minScoreTriangulation(values: number[]): number { - const n = values.length; - const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); - const dfs = (i: number, j: number): number => { - if (i + 1 === j) { - return 0; - } - if (f[i][j] > 0) { - return f[i][j]; - } - let ans = 1 << 30; - for (let k = i + 1; k < j; ++k) { - ans = Math.min(ans, dfs(i, k) + dfs(k, j) + values[i] * values[k] * values[j]); - } - f[i][j] = ans; - return ans; - }; - return dfs(0, n - 1); -} -``` - -```ts -function minScoreTriangulation(values: number[]): number { - const n = values.length; - const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); - for (let i = n - 3; i >= 0; --i) { - for (let j = i + 2; j < n; ++j) { - f[i][j] = 1 << 30; - for (let k = i + 1; k < j; ++k) { - f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); - } - } - } - return f[0][n - 1]; -} -``` - ```ts function minScoreTriangulation(values: number[]): number { const n = values.length; @@ -347,10 +351,6 @@ function minScoreTriangulation(values: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1040.Moving Stones Until Consecutive II/README.md b/solution/1000-1099/1040.Moving Stones Until Consecutive II/README.md index 724f3c8cc5997..78cfd7c47e546 100644 --- a/solution/1000-1099/1040.Moving Stones Until Consecutive II/README.md +++ b/solution/1000-1099/1040.Moving Stones Until Consecutive II/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:排序 + 分类讨论 + 双指针** +### 方法一:排序 + 分类讨论 + 双指针 我们先对数组 `stones` 进行升序排序,接下来分别考虑最大移动次数 $mx$ 和最小移动次数 $mi$。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def numMovesStonesII(self, stones: List[int]) -> List[int]: @@ -98,10 +92,6 @@ class Solution: return [mi, mx] ``` -### **Java** - - - ```java class Solution { public int[] numMovesStonesII(int[] stones) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go func numMovesStonesII(stones []int) []int { sort.Ints(stones) @@ -172,8 +158,6 @@ func numMovesStonesII(stones []int) []int { } ``` -### **TypeScript** - ```ts function numMovesStonesII(stones: number[]): number[] { stones.sort((a, b) => a - b); @@ -194,10 +178,6 @@ function numMovesStonesII(stones: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1040.Moving Stones Until Consecutive II/README_EN.md b/solution/1000-1099/1040.Moving Stones Until Consecutive II/README_EN.md index fff62670adcc5..52271f08dd602 100644 --- a/solution/1000-1099/1040.Moving Stones Until Consecutive II/README_EN.md +++ b/solution/1000-1099/1040.Moving Stones Until Consecutive II/README_EN.md @@ -52,9 +52,9 @@ Notice we cannot move 10 -> 2 to finish the game, because that would be an il ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return [mi, mx] ``` -### **Java** - ```java class Solution { public int[] numMovesStonesII(int[] stones) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +118,6 @@ public: }; ``` -### **Go** - ```go func numMovesStonesII(stones []int) []int { sort.Ints(stones) @@ -145,8 +139,6 @@ func numMovesStonesII(stones []int) []int { } ``` -### **TypeScript** - ```ts function numMovesStonesII(stones: number[]): number[] { stones.sort((a, b) => a - b); @@ -167,10 +159,6 @@ function numMovesStonesII(stones: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1041.Robot Bounded In Circle/README.md b/solution/1000-1099/1041.Robot Bounded In Circle/README.md index 17dd7f143cafa..a15143be7cb82 100644 --- a/solution/1000-1099/1041.Robot Bounded In Circle/README.md +++ b/solution/1000-1099/1041.Robot Bounded In Circle/README.md @@ -85,9 +85,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以模拟机器人的行走过程,用一个变量 $k$ 表示机器人的方向,初始值为 $0$,表示机器人面向北方。变量 $k$ 的取值范围为 $[0, 3]$,分别表示机器人面向北、西、南、东。另外,我们用一个长度为 $4$ 的数组 $dist$ 记录机器人在四个方向上行走的距离,初始值为 $[0, 0, 0, 0]$。 @@ -108,10 +106,6 @@ -### **Python3** - - - ```python class Solution: def isRobotBounded(self, instructions: str) -> bool: @@ -127,10 +121,6 @@ class Solution: return (dist[0] == dist[2] and dist[1] == dist[3]) or k != 0 ``` -### **Java** - - - ```java class Solution { public boolean isRobotBounded(String instructions) { @@ -151,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -173,8 +161,6 @@ public: }; ``` -### **Go** - ```go func isRobotBounded(instructions string) bool { dist := [4]int{} @@ -192,8 +178,6 @@ func isRobotBounded(instructions string) bool { } ``` -### **TypeScript** - ```ts function isRobotBounded(instructions: string): boolean { const dist: number[] = new Array(4).fill(0); @@ -211,10 +195,6 @@ function isRobotBounded(instructions: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1041.Robot Bounded In Circle/README_EN.md b/solution/1000-1099/1041.Robot Bounded In Circle/README_EN.md index 2314140a29474..c866b721279bf 100644 --- a/solution/1000-1099/1041.Robot Bounded In Circle/README_EN.md +++ b/solution/1000-1099/1041.Robot Bounded In Circle/README_EN.md @@ -82,9 +82,9 @@ Based on that, we return true. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -101,8 +101,6 @@ class Solution: return (dist[0] == dist[2] and dist[1] == dist[3]) or k != 0 ``` -### **Java** - ```java class Solution { public boolean isRobotBounded(String instructions) { @@ -123,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +141,6 @@ public: }; ``` -### **Go** - ```go func isRobotBounded(instructions string) bool { dist := [4]int{} @@ -164,8 +158,6 @@ func isRobotBounded(instructions string) bool { } ``` -### **TypeScript** - ```ts function isRobotBounded(instructions: string): boolean { const dist: number[] = new Array(4).fill(0); @@ -183,10 +175,6 @@ function isRobotBounded(instructions: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1042.Flower Planting With No Adjacent/README.md b/solution/1000-1099/1042.Flower Planting With No Adjacent/README.md index 759b84571d989..9adc47001fdf6 100644 --- a/solution/1000-1099/1042.Flower Planting With No Adjacent/README.md +++ b/solution/1000-1099/1042.Flower Planting With No Adjacent/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们先根据数组 $paths$ 构建图 $g$,其中 $g[x]$ 表示与花园 $x$ 相邻的花园列表。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]: @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] gardenNoAdj(int n, int[][] paths) { @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func gardenNoAdj(n int, paths [][]int) []int { g := make([][]int, n) @@ -184,8 +170,6 @@ func gardenNoAdj(n int, paths [][]int) []int { } ``` -### **TypeScript** - ```ts function gardenNoAdj(n: number, paths: number[][]): number[] { const g: number[][] = new Array(n).fill(0).map(() => []); @@ -210,10 +194,6 @@ function gardenNoAdj(n: number, paths: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1042.Flower Planting With No Adjacent/README_EN.md b/solution/1000-1099/1042.Flower Planting With No Adjacent/README_EN.md index d6c57c95166b6..086f976e8eca1 100644 --- a/solution/1000-1099/1042.Flower Planting With No Adjacent/README_EN.md +++ b/solution/1000-1099/1042.Flower Planting With No Adjacent/README_EN.md @@ -53,9 +53,9 @@ Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] gardenNoAdj(int n, int[][] paths) { @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +133,6 @@ public: }; ``` -### **Go** - ```go func gardenNoAdj(n int, paths [][]int) []int { g := make([][]int, n) @@ -164,8 +158,6 @@ func gardenNoAdj(n int, paths [][]int) []int { } ``` -### **TypeScript** - ```ts function gardenNoAdj(n: number, paths: number[][]): number[] { const g: number[][] = new Array(n).fill(0).map(() => []); @@ -190,10 +182,6 @@ function gardenNoAdj(n: number, paths: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1043.Partition Array for Maximum Sum/README.md b/solution/1000-1099/1043.Partition Array for Maximum Sum/README.md index f5ce1dd394d50..e475de58773c7 100644 --- a/solution/1000-1099/1043.Partition Array for Maximum Sum/README.md +++ b/solution/1000-1099/1043.Partition Array for Maximum Sum/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示将数组的前 $i$ 个元素分隔成若干个子数组,最终的最大元素和。初始时 $f[i]=0$,答案为 $f[n]$。 @@ -65,10 +63,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int: @@ -82,10 +76,6 @@ class Solution: return f[n] ``` -### **Java** - - - ```java class Solution { public int maxSumAfterPartitioning(int[] arr, int k) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func maxSumAfterPartitioning(arr []int, k int) int { n := len(arr) @@ -141,8 +127,6 @@ func maxSumAfterPartitioning(arr []int, k int) int { } ``` -### **TypeScript** - ```ts function maxSumAfterPartitioning(arr: number[], k: number): number { const n: number = arr.length; @@ -158,10 +142,6 @@ function maxSumAfterPartitioning(arr: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1043.Partition Array for Maximum Sum/README_EN.md b/solution/1000-1099/1043.Partition Array for Maximum Sum/README_EN.md index 173f5aaf933e9..25f605bf9d4ef 100644 --- a/solution/1000-1099/1043.Partition Array for Maximum Sum/README_EN.md +++ b/solution/1000-1099/1043.Partition Array for Maximum Sum/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i]$ to represent the maximum element sum of the first $i$ elements of the array after separating them into several subarrays. At the beginning, $f[i]=0$, and the answer is $f[n]$. @@ -60,8 +60,6 @@ The time complexity is $O(n \times k)$, and the space complexity is $O(n)$, wher -### **Python3** - ```python class Solution: def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int: @@ -75,8 +73,6 @@ class Solution: return f[n] ``` -### **Java** - ```java class Solution { public int maxSumAfterPartitioning(int[] arr, int k) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +109,6 @@ public: }; ``` -### **Go** - ```go func maxSumAfterPartitioning(arr []int, k int) int { n := len(arr) @@ -132,8 +124,6 @@ func maxSumAfterPartitioning(arr []int, k int) int { } ``` -### **TypeScript** - ```ts function maxSumAfterPartitioning(arr: number[], k: number): number { const n: number = arr.length; @@ -149,10 +139,6 @@ function maxSumAfterPartitioning(arr: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1044.Longest Duplicate Substring/README.md b/solution/1000-1099/1044.Longest Duplicate Substring/README.md index 3fc5701af760f..8d233bd8c9d7b 100644 --- a/solution/1000-1099/1044.Longest Duplicate Substring/README.md +++ b/solution/1000-1099/1044.Longest Duplicate Substring/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:字符串哈希 + 二分查找** +### 方法一:字符串哈希 + 二分查找 **字符串哈希**是把一个任意长度的字符串映射成一个非负整数,并且其冲突的概率几乎为 0。字符串哈希用于计算字符串哈希值,快速判断两个字符串是否相等。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def longestDupSubstring(self, s: str) -> str: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private long[] p; @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef unsigned long long ULL; @@ -182,8 +170,6 @@ public: }; ``` -### **Go** - ```go func longestDupSubstring(s string) string { base, n := 131, len(s) @@ -222,10 +208,6 @@ func longestDupSubstring(s string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1044.Longest Duplicate Substring/README_EN.md b/solution/1000-1099/1044.Longest Duplicate Substring/README_EN.md index 402f70df92c18..fb10469cc291d 100644 --- a/solution/1000-1099/1044.Longest Duplicate Substring/README_EN.md +++ b/solution/1000-1099/1044.Longest Duplicate Substring/README_EN.md @@ -26,9 +26,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private long[] p; @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef unsigned long long ULL; @@ -149,8 +145,6 @@ public: }; ``` -### **Go** - ```go func longestDupSubstring(s string) string { base, n := 131, len(s) @@ -189,10 +183,6 @@ func longestDupSubstring(s string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1045.Customers Who Bought All Products/README.md b/solution/1000-1099/1045.Customers Who Bought All Products/README.md index f672bb93fdfd0..194fb4e5336be 100644 --- a/solution/1000-1099/1045.Customers Who Bought All Products/README.md +++ b/solution/1000-1099/1045.Customers Who Bought All Products/README.md @@ -75,16 +75,12 @@ Product 表: ## 解法 - - -**方法一:分组统计 + 子查询** +### 方法一:分组统计 + 子查询 我们将 `Customer` 表按照 `customer_id` 进行分组,然后使用 `HAVING` 子句筛选出购买了所有产品的客户。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT customer_id @@ -94,3 +90,5 @@ HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(1) FROM Product); ``` + + diff --git a/solution/1000-1099/1045.Customers Who Bought All Products/README_EN.md b/solution/1000-1099/1045.Customers Who Bought All Products/README_EN.md index df26697112ed6..50e2a86b4114a 100644 --- a/solution/1000-1099/1045.Customers Who Bought All Products/README_EN.md +++ b/solution/1000-1099/1045.Customers Who Bought All Products/README_EN.md @@ -74,14 +74,12 @@ The customers who bought all the products (5 and 6) are customers with IDs 1 and ## Solutions -**Solution 1: Grouping and Subquery** +### Solution 1: Grouping and Subquery We can group the `Customer` table by `customer_id`, and then use the `HAVING` clause to filter out the customers who have not purchased all products. To do this, we can use a subquery to find the total number of distinct products, and then compare it with the number of distinct products purchased by each customer. -### **SQL** - ```sql # Write your MySQL query statement below SELECT customer_id @@ -91,3 +89,5 @@ HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(1) FROM Product); ``` + + diff --git a/solution/1000-1099/1046.Last Stone Weight/README.md b/solution/1000-1099/1046.Last Stone Weight/README.md index 2ed7640557f42..06ae76cec6444 100644 --- a/solution/1000-1099/1046.Last Stone Weight/README.md +++ b/solution/1000-1099/1046.Last Stone Weight/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:优先队列(大根堆)** +### 方法一:优先队列(大根堆) 我们将数组 `stones` 所有元素放入大根堆,然后执行循环操作,每次弹出两个元素 $y$ 和 $x$,如果 $x \neq y$,将 $y - x$ 放入大根堆。当堆元素个数小于 $2$ 时,退出循环。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def lastStoneWeight(self, stones: List[int]) -> int: @@ -69,10 +63,6 @@ class Solution: return 0 if not h else -h[0] ``` -### **Java** - - - ```java class Solution { public int lastStoneWeight(int[] stones) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func lastStoneWeight(stones []int) int { q := &hp{stones} @@ -148,7 +134,22 @@ func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) } ``` -### **JavaScript** +```ts +function lastStoneWeight(stones: number[]): number { + const pq = new MaxPriorityQueue(); + for (const x of stones) { + pq.enqueue(x); + } + while (pq.size() > 1) { + const y = pq.dequeue().element; + const x = pq.dequeue().element; + if (x !== y) { + pq.enqueue(y - x); + } + } + return pq.isEmpty() ? 0 : pq.dequeue().element; +} +``` ```js /** @@ -171,29 +172,6 @@ var lastStoneWeight = function (stones) { }; ``` -### **TypeScript** - -```ts -function lastStoneWeight(stones: number[]): number { - const pq = new MaxPriorityQueue(); - for (const x of stones) { - pq.enqueue(x); - } - while (pq.size() > 1) { - const y = pq.dequeue().element; - const x = pq.dequeue().element; - if (x !== y) { - pq.enqueue(y - x); - } - } - return pq.isEmpty() ? 0 : pq.dequeue().element; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1046.Last Stone Weight/README_EN.md b/solution/1000-1099/1046.Last Stone Weight/README_EN.md index b5246edbc5624..2498aecc8c9ce 100644 --- a/solution/1000-1099/1046.Last Stone Weight/README_EN.md +++ b/solution/1000-1099/1046.Last Stone Weight/README_EN.md @@ -47,9 +47,9 @@ we combine 1 and 1 to get 0 so the array converts to [1] then that's the val ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return 0 if not h else -h[0] ``` -### **Java** - ```java class Solution { public int lastStoneWeight(int[] stones) { @@ -84,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +104,6 @@ public: }; ``` -### **Go** - ```go func lastStoneWeight(stones []int) int { q := &hp{stones} @@ -140,7 +134,22 @@ func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) } ``` -### **JavaScript** +```ts +function lastStoneWeight(stones: number[]): number { + const pq = new MaxPriorityQueue(); + for (const x of stones) { + pq.enqueue(x); + } + while (pq.size() > 1) { + const y = pq.dequeue().element; + const x = pq.dequeue().element; + if (x !== y) { + pq.enqueue(y - x); + } + } + return pq.isEmpty() ? 0 : pq.dequeue().element; +} +``` ```js /** @@ -163,29 +172,6 @@ var lastStoneWeight = function (stones) { }; ``` -### **TypeScript** - -```ts -function lastStoneWeight(stones: number[]): number { - const pq = new MaxPriorityQueue(); - for (const x of stones) { - pq.enqueue(x); - } - while (pq.size() > 1) { - const y = pq.dequeue().element; - const x = pq.dequeue().element; - if (x !== y) { - pq.enqueue(y - x); - } - } - return pq.isEmpty() ? 0 : pq.dequeue().element; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1047.Remove All Adjacent Duplicates In String/README.md b/solution/1000-1099/1047.Remove All Adjacent Duplicates In String/README.md index 85690360093d6..465ce2ffa568b 100644 --- a/solution/1000-1099/1047.Remove All Adjacent Duplicates In String/README.md +++ b/solution/1000-1099/1047.Remove All Adjacent Duplicates In String/README.md @@ -33,9 +33,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 遍历字符串 `s` 中的每个字符 `c`,若栈为空或者栈顶值不等于字符 `c`,将 `c` 入栈,否则栈顶元素出栈。 @@ -45,10 +43,6 @@ -### **Python3** - - - ```python class Solution: def removeDuplicates(self, s: str) -> str: @@ -61,10 +55,6 @@ class Solution: return ''.join(stk) ``` -### **Java** - - - ```java class Solution { public String removeDuplicates(String s) { @@ -81,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +88,6 @@ public: }; ``` -### **Go** - ```go func removeDuplicates(s string) string { stk := []rune{} @@ -116,7 +102,21 @@ func removeDuplicates(s string) string { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn remove_duplicates(s: String) -> String { + let mut stack = Vec::new(); + for c in s.chars() { + if !stack.is_empty() && *stack.last().unwrap() == c { + stack.pop(); + } else { + stack.push(c); + } + } + stack.into_iter().collect() + } +} +``` ```js /** @@ -136,26 +136,6 @@ var removeDuplicates = function (s) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn remove_duplicates(s: String) -> String { - let mut stack = Vec::new(); - for c in s.chars() { - if !stack.is_empty() && *stack.last().unwrap() == c { - stack.pop(); - } else { - stack.push(c); - } - } - stack.into_iter().collect() - } -} -``` - -### **C** - ```c char* removeDuplicates(char* s) { int n = strlen(s); @@ -174,10 +154,6 @@ char* removeDuplicates(char* s) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1047.Remove All Adjacent Duplicates In String/README_EN.md b/solution/1000-1099/1047.Remove All Adjacent Duplicates In String/README_EN.md index 20ac5f7221b42..b11606b2a3422 100644 --- a/solution/1000-1099/1047.Remove All Adjacent Duplicates In String/README_EN.md +++ b/solution/1000-1099/1047.Remove All Adjacent Duplicates In String/README_EN.md @@ -37,9 +37,9 @@ For example, in "abbaca" we could remove "bb" since the lett ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return ''.join(stk) ``` -### **Java** - ```java class Solution { public String removeDuplicates(String s) { @@ -71,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,8 +86,6 @@ public: }; ``` -### **Go** - ```go func removeDuplicates(s string) string { stk := []rune{} @@ -106,7 +100,21 @@ func removeDuplicates(s string) string { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn remove_duplicates(s: String) -> String { + let mut stack = Vec::new(); + for c in s.chars() { + if !stack.is_empty() && *stack.last().unwrap() == c { + stack.pop(); + } else { + stack.push(c); + } + } + stack.into_iter().collect() + } +} +``` ```js /** @@ -126,26 +134,6 @@ var removeDuplicates = function (s) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn remove_duplicates(s: String) -> String { - let mut stack = Vec::new(); - for c in s.chars() { - if !stack.is_empty() && *stack.last().unwrap() == c { - stack.pop(); - } else { - stack.push(c); - } - } - stack.into_iter().collect() - } -} -``` - -### **C** - ```c char* removeDuplicates(char* s) { int n = strlen(s); @@ -164,10 +152,6 @@ char* removeDuplicates(char* s) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1048.Longest String Chain/README.md b/solution/1000-1099/1048.Longest String Chain/README.md index 20eb22218fd5d..7aba99a2d3d89 100644 --- a/solution/1000-1099/1048.Longest String Chain/README.md +++ b/solution/1000-1099/1048.Longest String Chain/README.md @@ -56,18 +56,10 @@ ## 解法 - - -先按字符串长度升序排列,再利用动态规划或者哈希表求解。 +### 方法一 -### **Python3** - - - -动态规划: - ```python class Solution: def longestStrChain(self, words: List[str]) -> int: @@ -95,30 +87,6 @@ class Solution: return res ``` -哈希表: - -```python -class Solution: - def longestStrChain(self, words: List[str]) -> int: - words.sort(key=lambda x: len(x)) - res = 0 - mp = {} - for word in words: - x = 1 - for i in range(len(word)): - pre = word[:i] + word[i + 1 :] - x = max(x, mp.get(pre, 0) + 1) - mp[word] = x - res = max(res, x) - return res -``` - -### **Java** - - - -哈希表: - ```java class Solution { public int longestStrChain(String[] words) { @@ -139,30 +107,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function longestStrChain(words: string[]): number { - words.sort((a, b) => a.length - b.length); - let ans = 0; - let hashTable = new Map(); - for (let word of words) { - let c = 1; - for (let i = 0; i < word.length; i++) { - let pre = word.substring(0, i) + word.substring(i + 1); - c = Math.max(c, (hashTable.get(pre) || 0) + 1); - } - hashTable.set(word, c); - ans = Math.max(ans, c); - } - return ans; -} -``` - -### **C++** - -哈希表: - ```cpp class Solution { public: @@ -184,7 +128,41 @@ public: }; ``` -### **Rust** +```go +func longestStrChain(words []string) int { + sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) }) + res := 0 + mp := make(map[string]int) + for _, word := range words { + x := 1 + for i := 0; i < len(word); i++ { + pre := word[0:i] + word[i+1:len(word)] + x = max(x, mp[pre]+1) + } + mp[word] = x + res = max(res, x) + } + return res +} +``` + +```ts +function longestStrChain(words: string[]): number { + words.sort((a, b) => a.length - b.length); + let ans = 0; + let hashTable = new Map(); + for (let word of words) { + let c = 1; + for (let i = 0; i < word.length; i++) { + let pre = word.substring(0, i) + word.substring(i + 1); + c = Math.max(c, (hashTable.get(pre) || 0) + 1); + } + hashTable.set(word, c); + ans = Math.max(ans, c); + } + return ans; +} +``` ```rust use std::collections::HashMap; @@ -220,32 +198,28 @@ impl Solution { } ``` -### **Go** - -哈希表: - -```go -func longestStrChain(words []string) int { - sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) }) - res := 0 - mp := make(map[string]int) - for _, word := range words { - x := 1 - for i := 0; i < len(word); i++ { - pre := word[0:i] + word[i+1:len(word)] - x = max(x, mp[pre]+1) - } - mp[word] = x - res = max(res, x) - } - return res -} -``` + -### **...** +### 方法二 -``` + +```python +class Solution: + def longestStrChain(self, words: List[str]) -> int: + words.sort(key=lambda x: len(x)) + res = 0 + mp = {} + for word in words: + x = 1 + for i in range(len(word)): + pre = word[:i] + word[i + 1 :] + x = max(x, mp.get(pre, 0) + 1) + mp[word] = x + res = max(res, x) + return res ``` + + diff --git a/solution/1000-1099/1048.Longest String Chain/README_EN.md b/solution/1000-1099/1048.Longest String Chain/README_EN.md index 06d9809c6b4df..89a458dea57c6 100644 --- a/solution/1000-1099/1048.Longest String Chain/README_EN.md +++ b/solution/1000-1099/1048.Longest String Chain/README_EN.md @@ -53,9 +53,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,24 +84,6 @@ class Solution: return res ``` -```python -class Solution: - def longestStrChain(self, words: List[str]) -> int: - words.sort(key=lambda x: len(x)) - res = 0 - mp = {} - for word in words: - x = 1 - for i in range(len(word)): - pre = word[:i] + word[i + 1 :] - x = max(x, mp.get(pre, 0) + 1) - mp[word] = x - res = max(res, x) - return res -``` - -### **Java** - ```java class Solution { public int longestStrChain(String[] words) { @@ -122,28 +104,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function longestStrChain(words: string[]): number { - words.sort((a, b) => a.length - b.length); - let ans = 0; - let hashTable = new Map(); - for (let word of words) { - let c = 1; - for (let i = 0; i < word.length; i++) { - let pre = word.substring(0, i) + word.substring(i + 1); - c = Math.max(c, (hashTable.get(pre) || 0) + 1); - } - hashTable.set(word, c); - ans = Math.max(ans, c); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -165,7 +125,41 @@ public: }; ``` -### **Rust** +```go +func longestStrChain(words []string) int { + sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) }) + res := 0 + mp := make(map[string]int) + for _, word := range words { + x := 1 + for i := 0; i < len(word); i++ { + pre := word[0:i] + word[i+1:len(word)] + x = max(x, mp[pre]+1) + } + mp[word] = x + res = max(res, x) + } + return res +} +``` + +```ts +function longestStrChain(words: string[]): number { + words.sort((a, b) => a.length - b.length); + let ans = 0; + let hashTable = new Map(); + for (let word of words) { + let c = 1; + for (let i = 0; i < word.length; i++) { + let pre = word.substring(0, i) + word.substring(i + 1); + c = Math.max(c, (hashTable.get(pre) || 0) + 1); + } + hashTable.set(word, c); + ans = Math.max(ans, c); + } + return ans; +} +``` ```rust use std::collections::HashMap; @@ -201,30 +195,28 @@ impl Solution { } ``` -### **Go** - -```go -func longestStrChain(words []string) int { - sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) }) - res := 0 - mp := make(map[string]int) - for _, word := range words { - x := 1 - for i := 0; i < len(word); i++ { - pre := word[0:i] + word[i+1:len(word)] - x = max(x, mp[pre]+1) - } - mp[word] = x - res = max(res, x) - } - return res -} -``` + -### **...** +### Solution 2 -``` + +```python +class Solution: + def longestStrChain(self, words: List[str]) -> int: + words.sort(key=lambda x: len(x)) + res = 0 + mp = {} + for word in words: + x = 1 + for i in range(len(word)): + pre = word[:i] + word[i + 1 :] + x = max(x, mp.get(pre, 0) + 1) + mp[word] = x + res = max(res, x) + return res ``` + + diff --git a/solution/1000-1099/1049.Last Stone Weight II/README.md b/solution/1000-1099/1049.Last Stone Weight II/README.md index 18f62f7a4b260..7e34086dd4900 100644 --- a/solution/1000-1099/1049.Last Stone Weight II/README.md +++ b/solution/1000-1099/1049.Last Stone Weight II/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 **两个**石头的重量越接近,粉碎后的新重量就越小。同样的,**两堆**石头的重量越接近,它们粉碎后的新重量也越小。 @@ -61,12 +59,6 @@ -### **Python3** - - - -动态规划——`0-1` 背包朴素做法: - ```python class Solution: def lastStoneWeightII(self, stones: List[int]) -> int: @@ -83,24 +75,6 @@ class Solution: return s - 2 * dp[-1][-1] ``` -动态规划——`0-1` 背包空间优化: - -```python -class Solution: - def lastStoneWeightII(self, stones: List[int]) -> int: - s = sum(stones) - m, n = len(stones), s >> 1 - dp = [0] * (n + 1) - for v in stones: - for j in range(n, v - 1, -1): - dp[j] = max(dp[j], dp[j - v] + v) - return s - dp[-1] * 2 -``` - -### **Java** - - - ```java class Solution { public int lastStoneWeightII(int[] stones) { @@ -124,28 +98,6 @@ class Solution { } ``` -```java -class Solution { - public int lastStoneWeightII(int[] stones) { - int s = 0; - for (int v : stones) { - s += v; - } - int m = stones.length; - int n = s >> 1; - int[] dp = new int[n + 1]; - for (int v : stones) { - for (int j = n; j >= v; --j) { - dp[j] = Math.max(dp[j], dp[j - v] + v); - } - } - return s - dp[n] * 2; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -164,23 +116,29 @@ public: }; ``` -```cpp -class Solution { -public: - int lastStoneWeightII(vector& stones) { - int s = accumulate(stones.begin(), stones.end(), 0); - int n = s >> 1; - vector dp(n + 1); - for (int& v : stones) - for (int j = n; j >= v; --j) - dp[j] = max(dp[j], dp[j - v] + v); - return s - dp[n] * 2; - } -}; +```go +func lastStoneWeightII(stones []int) int { + s := 0 + for _, v := range stones { + s += v + } + m, n := len(stones), s>>1 + dp := make([][]int, m+1) + for i := range dp { + dp[i] = make([]int, n+1) + } + for i := 1; i <= m; i++ { + for j := 0; j <= n; j++ { + dp[i][j] = dp[i-1][j] + if stones[i-1] <= j { + dp[i][j] = max(dp[i][j], dp[i-1][j-stones[i-1]]+stones[i-1]) + } + } + } + return s - dp[m][n]*2 +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -214,50 +172,6 @@ impl Solution { } ``` -### **Go** - -```go -func lastStoneWeightII(stones []int) int { - s := 0 - for _, v := range stones { - s += v - } - m, n := len(stones), s>>1 - dp := make([][]int, m+1) - for i := range dp { - dp[i] = make([]int, n+1) - } - for i := 1; i <= m; i++ { - for j := 0; j <= n; j++ { - dp[i][j] = dp[i-1][j] - if stones[i-1] <= j { - dp[i][j] = max(dp[i][j], dp[i-1][j-stones[i-1]]+stones[i-1]) - } - } - } - return s - dp[m][n]*2 -} -``` - -```go -func lastStoneWeightII(stones []int) int { - s := 0 - for _, v := range stones { - s += v - } - n := s >> 1 - dp := make([]int, n+1) - for _, v := range stones { - for j := n; j >= v; j-- { - dp[j] = max(dp[j], dp[j-v]+v) - } - } - return s - dp[n]*2 -} -``` - -### **JavaScript** - ```js /** * @param {number[]} stones @@ -279,10 +193,76 @@ var lastStoneWeightII = function (stones) { }; ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def lastStoneWeightII(self, stones: List[int]) -> int: + s = sum(stones) + m, n = len(stones), s >> 1 + dp = [0] * (n + 1) + for v in stones: + for j in range(n, v - 1, -1): + dp[j] = max(dp[j], dp[j - v] + v) + return s - dp[-1] * 2 ``` +```java +class Solution { + public int lastStoneWeightII(int[] stones) { + int s = 0; + for (int v : stones) { + s += v; + } + int m = stones.length; + int n = s >> 1; + int[] dp = new int[n + 1]; + for (int v : stones) { + for (int j = n; j >= v; --j) { + dp[j] = Math.max(dp[j], dp[j - v] + v); + } + } + return s - dp[n] * 2; + } +} +``` + +```cpp +class Solution { +public: + int lastStoneWeightII(vector& stones) { + int s = accumulate(stones.begin(), stones.end(), 0); + int n = s >> 1; + vector dp(n + 1); + for (int& v : stones) + for (int j = n; j >= v; --j) + dp[j] = max(dp[j], dp[j - v] + v); + return s - dp[n] * 2; + } +}; +``` + +```go +func lastStoneWeightII(stones []int) int { + s := 0 + for _, v := range stones { + s += v + } + n := s >> 1 + dp := make([]int, n+1) + for _, v := range stones { + for j := n; j >= v; j-- { + dp[j] = max(dp[j], dp[j-v]+v) + } + } + return s - dp[n]*2 +} ``` + + diff --git a/solution/1000-1099/1049.Last Stone Weight II/README_EN.md b/solution/1000-1099/1049.Last Stone Weight II/README_EN.md index b5b8e7a654cad..453786add1e9e 100644 --- a/solution/1000-1099/1049.Last Stone Weight II/README_EN.md +++ b/solution/1000-1099/1049.Last Stone Weight II/README_EN.md @@ -47,14 +47,10 @@ we can combine 1 and 1 to get 0, so the array converts to [1], then that's t ## Solutions -Dynamic programming. - -This question can be converted to calculate how many stones a knapsack with a capacity of `sum / 2` can hold. +### Solution 1 -### **Python3** - ```python class Solution: def lastStoneWeightII(self, stones: List[int]) -> int: @@ -71,20 +67,6 @@ class Solution: return s - 2 * dp[-1][-1] ``` -```python -class Solution: - def lastStoneWeightII(self, stones: List[int]) -> int: - s = sum(stones) - m, n = len(stones), s >> 1 - dp = [0] * (n + 1) - for v in stones: - for j in range(n, v - 1, -1): - dp[j] = max(dp[j], dp[j - v] + v) - return s - dp[-1] * 2 -``` - -### **Java** - ```java class Solution { public int lastStoneWeightII(int[] stones) { @@ -108,28 +90,6 @@ class Solution { } ``` -```java -class Solution { - public int lastStoneWeightII(int[] stones) { - int s = 0; - for (int v : stones) { - s += v; - } - int m = stones.length; - int n = s >> 1; - int[] dp = new int[n + 1]; - for (int v : stones) { - for (int j = n; j >= v; --j) { - dp[j] = Math.max(dp[j], dp[j - v] + v); - } - } - return s - dp[n] * 2; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -148,23 +108,29 @@ public: }; ``` -```cpp -class Solution { -public: - int lastStoneWeightII(vector& stones) { - int s = accumulate(stones.begin(), stones.end(), 0); - int n = s >> 1; - vector dp(n + 1); - for (int& v : stones) - for (int j = n; j >= v; --j) - dp[j] = max(dp[j], dp[j - v] + v); - return s - dp[n] * 2; - } -}; +```go +func lastStoneWeightII(stones []int) int { + s := 0 + for _, v := range stones { + s += v + } + m, n := len(stones), s>>1 + dp := make([][]int, m+1) + for i := range dp { + dp[i] = make([]int, n+1) + } + for i := 1; i <= m; i++ { + for j := 0; j <= n; j++ { + dp[i][j] = dp[i-1][j] + if stones[i-1] <= j { + dp[i][j] = max(dp[i][j], dp[i-1][j-stones[i-1]]+stones[i-1]) + } + } + } + return s - dp[m][n]*2 +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -198,50 +164,6 @@ impl Solution { } ``` -### **Go** - -```go -func lastStoneWeightII(stones []int) int { - s := 0 - for _, v := range stones { - s += v - } - m, n := len(stones), s>>1 - dp := make([][]int, m+1) - for i := range dp { - dp[i] = make([]int, n+1) - } - for i := 1; i <= m; i++ { - for j := 0; j <= n; j++ { - dp[i][j] = dp[i-1][j] - if stones[i-1] <= j { - dp[i][j] = max(dp[i][j], dp[i-1][j-stones[i-1]]+stones[i-1]) - } - } - } - return s - dp[m][n]*2 -} -``` - -```go -func lastStoneWeightII(stones []int) int { - s := 0 - for _, v := range stones { - s += v - } - n := s >> 1 - dp := make([]int, n+1) - for _, v := range stones { - for j := n; j >= v; j-- { - dp[j] = max(dp[j], dp[j-v]+v) - } - } - return s - dp[n]*2 -} -``` - -### **JavaScript** - ```js /** * @param {number[]} stones @@ -263,10 +185,76 @@ var lastStoneWeightII = function (stones) { }; ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def lastStoneWeightII(self, stones: List[int]) -> int: + s = sum(stones) + m, n = len(stones), s >> 1 + dp = [0] * (n + 1) + for v in stones: + for j in range(n, v - 1, -1): + dp[j] = max(dp[j], dp[j - v] + v) + return s - dp[-1] * 2 ``` +```java +class Solution { + public int lastStoneWeightII(int[] stones) { + int s = 0; + for (int v : stones) { + s += v; + } + int m = stones.length; + int n = s >> 1; + int[] dp = new int[n + 1]; + for (int v : stones) { + for (int j = n; j >= v; --j) { + dp[j] = Math.max(dp[j], dp[j - v] + v); + } + } + return s - dp[n] * 2; + } +} +``` + +```cpp +class Solution { +public: + int lastStoneWeightII(vector& stones) { + int s = accumulate(stones.begin(), stones.end(), 0); + int n = s >> 1; + vector dp(n + 1); + for (int& v : stones) + for (int j = n; j >= v; --j) + dp[j] = max(dp[j], dp[j - v] + v); + return s - dp[n] * 2; + } +}; +``` + +```go +func lastStoneWeightII(stones []int) int { + s := 0 + for _, v := range stones { + s += v + } + n := s >> 1 + dp := make([]int, n+1) + for _, v := range stones { + for j := n; j >= v; j-- { + dp[j] = max(dp[j], dp[j-v]+v) + } + } + return s - dp[n]*2 +} ``` + + diff --git a/solution/1000-1099/1050.Actors and Directors Who Cooperated At Least Three Times/README.md b/solution/1000-1099/1050.Actors and Directors Who Cooperated At Least Three Times/README.md index 7dde7ff3bf88b..7b4d242e52490 100644 --- a/solution/1000-1099/1050.Actors and Directors Who Cooperated At Least Three Times/README.md +++ b/solution/1000-1099/1050.Actors and Directors Who Cooperated At Least Three Times/README.md @@ -52,16 +52,12 @@ ActorDirector 表: ## 解法 - - -**方法一:分组统计** +### 方法一:分组统计 我们可以使用 `GROUP BY` 语句,按照 `actor_id` 和 `director_id` 字段进行分组,然后使用 `HAVING` 语句,筛选出现次数大于等于 $3$ 的 `actor_id` 和 `director_id`。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT actor_id, director_id @@ -71,3 +67,5 @@ HAVING COUNT(1) >= 3; ``` + + diff --git a/solution/1000-1099/1050.Actors and Directors Who Cooperated At Least Three Times/README_EN.md b/solution/1000-1099/1050.Actors and Directors Who Cooperated At Least Three Times/README_EN.md index 0606cb8a3031d..c9b91d2b4fcc6 100644 --- a/solution/1000-1099/1050.Actors and Directors Who Cooperated At Least Three Times/README_EN.md +++ b/solution/1000-1099/1050.Actors and Directors Who Cooperated At Least Three Times/README_EN.md @@ -53,14 +53,12 @@ ActorDirector table: ## Solutions -**Solution 1: Group By + Having** +### Solution 1: Group By + Having We can use the `GROUP BY` statement to group the data by the `actor_id` and `director_id` fields, and then use the `HAVING` statement to filter out the `actor_id` and `director_id` that appear at least three times. -### **SQL** - ```sql # Write your MySQL query statement below SELECT actor_id, director_id @@ -70,3 +68,5 @@ HAVING COUNT(1) >= 3; ``` + + diff --git a/solution/1000-1099/1051.Height Checker/README.md b/solution/1000-1099/1051.Height Checker/README.md index b72facb4c7f79..5175ab5678859 100644 --- a/solution/1000-1099/1051.Height Checker/README.md +++ b/solution/1000-1099/1051.Height Checker/README.md @@ -57,26 +57,14 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 将 $heights$ 复制并排序得到 $expected$,然后同时遍历 $heights$, $expected$ ,统计对应位置元素不同的个数。 时间复杂度 $O(nlogn)$,其中 $n$ 表示 $heights$ 的长度。 -**方法二:计数排序** - -由于题目中学生高度不超过 $100$,因此可以使用计数排序。这里我们用一个长度 $101$ 的数组 $cnt$ 统计每个高度 $h_i$ 出现的次数。 - -时间复杂度 $(n)$。 - -### **Python3** - - - ```python class Solution: def heightChecker(self, heights: List[int]) -> int: @@ -84,26 +72,6 @@ class Solution: return sum(a != b for a, b in zip(heights, expected)) ``` -```python -class Solution: - def heightChecker(self, heights: List[int]) -> int: - cnt = [0] * 101 - for h in heights: - cnt[h] += 1 - ans = i = 0 - for j in range(1, 101): - while cnt[j]: - cnt[j] -= 1 - if heights[i] != j: - ans += 1 - i += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int heightChecker(int[] heights) { @@ -120,6 +88,60 @@ class Solution { } ``` +```cpp +class Solution { +public: + int heightChecker(vector& heights) { + vector expected = heights; + sort(expected.begin(), expected.end()); + int ans = 0; + for (int i = 0; i < heights.size(); ++i) ans += heights[i] != expected[i]; + return ans; + } +}; +``` + +```go +func heightChecker(heights []int) int { + expected := make([]int, len(heights)) + copy(expected, heights) + sort.Ints(expected) + ans := 0 + for i, v := range heights { + if v != expected[i] { + ans++ + } + } + return ans +} +``` + + + +### 方法二:计数排序 + +由于题目中学生高度不超过 $100$,因此可以使用计数排序。这里我们用一个长度 $101$ 的数组 $cnt$ 统计每个高度 $h_i$ 出现的次数。 + +时间复杂度 $(n)$。 + + + +```python +class Solution: + def heightChecker(self, heights: List[int]) -> int: + cnt = [0] * 101 + for h in heights: + cnt[h] += 1 + ans = i = 0 + for j in range(1, 101): + while cnt[j]: + cnt[j] -= 1 + if heights[i] != j: + ans += 1 + i += 1 + return ans +``` + ```java class Solution { public int heightChecker(int[] heights) { @@ -141,21 +163,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int heightChecker(vector& heights) { - vector expected = heights; - sort(expected.begin(), expected.end()); - int ans = 0; - for (int i = 0; i < heights.size(); ++i) ans += heights[i] != expected[i]; - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -174,23 +181,6 @@ public: }; ``` -### **Go** - -```go -func heightChecker(heights []int) int { - expected := make([]int, len(heights)) - copy(expected, heights) - sort.Ints(expected) - ans := 0 - for i, v := range heights { - if v != expected[i] { - ans++ - } - } - return ans -} -``` - ```go func heightChecker(heights []int) int { cnt := make([]int, 101) @@ -211,10 +201,6 @@ func heightChecker(heights []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1051.Height Checker/README_EN.md b/solution/1000-1099/1051.Height Checker/README_EN.md index b80f84fcdfd88..1d746f99b69bf 100644 --- a/solution/1000-1099/1051.Height Checker/README_EN.md +++ b/solution/1000-1099/1051.Height Checker/README_EN.md @@ -54,9 +54,9 @@ All indices match. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,24 +65,6 @@ class Solution: return sum(a != b for a, b in zip(heights, expected)) ``` -```python -class Solution: - def heightChecker(self, heights: List[int]) -> int: - cnt = [0] * 101 - for h in heights: - cnt[h] += 1 - ans = i = 0 - for j in range(1, 101): - while cnt[j]: - cnt[j] -= 1 - if heights[i] != j: - ans += 1 - i += 1 - return ans -``` - -### **Java** - ```java class Solution { public int heightChecker(int[] heights) { @@ -99,6 +81,56 @@ class Solution { } ``` +```cpp +class Solution { +public: + int heightChecker(vector& heights) { + vector expected = heights; + sort(expected.begin(), expected.end()); + int ans = 0; + for (int i = 0; i < heights.size(); ++i) ans += heights[i] != expected[i]; + return ans; + } +}; +``` + +```go +func heightChecker(heights []int) int { + expected := make([]int, len(heights)) + copy(expected, heights) + sort.Ints(expected) + ans := 0 + for i, v := range heights { + if v != expected[i] { + ans++ + } + } + return ans +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def heightChecker(self, heights: List[int]) -> int: + cnt = [0] * 101 + for h in heights: + cnt[h] += 1 + ans = i = 0 + for j in range(1, 101): + while cnt[j]: + cnt[j] -= 1 + if heights[i] != j: + ans += 1 + i += 1 + return ans +``` + ```java class Solution { public int heightChecker(int[] heights) { @@ -120,21 +152,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int heightChecker(vector& heights) { - vector expected = heights; - sort(expected.begin(), expected.end()); - int ans = 0; - for (int i = 0; i < heights.size(); ++i) ans += heights[i] != expected[i]; - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -153,23 +170,6 @@ public: }; ``` -### **Go** - -```go -func heightChecker(heights []int) int { - expected := make([]int, len(heights)) - copy(expected, heights) - sort.Ints(expected) - ans := 0 - for i, v := range heights { - if v != expected[i] { - ans++ - } - } - return ans -} -``` - ```go func heightChecker(heights []int) int { cnt := make([]int, 101) @@ -190,10 +190,6 @@ func heightChecker(heights []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1052.Grumpy Bookstore Owner/README.md b/solution/1000-1099/1052.Grumpy Bookstore Owner/README.md index f611795e02234..80169addc8648 100644 --- a/solution/1000-1099/1052.Grumpy Bookstore Owner/README.md +++ b/solution/1000-1099/1052.Grumpy Bookstore Owner/README.md @@ -45,18 +45,12 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 定义 $s$ 表示所有不满意的顾客总数,$cs$ 表示顾客总数。 -### **Python3** - - - ```python class Solution: def maxSatisfied( @@ -73,10 +67,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxSatisfied(int[] customers, int[] grumpy, int minutes) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func maxSatisfied(customers []int, grumpy []int, minutes int) int { s, cs := 0, 0 @@ -148,8 +134,6 @@ func maxSatisfied(customers []int, grumpy []int, minutes int) int { } ``` -### **Rust** - ```rust impl Solution { pub fn max_satisfied(customers: Vec, grumpy: Vec, minutes: i32) -> i32 { @@ -184,10 +168,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1052.Grumpy Bookstore Owner/README_EN.md b/solution/1000-1099/1052.Grumpy Bookstore Owner/README_EN.md index a4ed5e81c135d..4b928f634e970 100644 --- a/solution/1000-1099/1052.Grumpy Bookstore Owner/README_EN.md +++ b/solution/1000-1099/1052.Grumpy Bookstore Owner/README_EN.md @@ -43,9 +43,9 @@ The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxSatisfied(int[] customers, int[] grumpy, int minutes) { @@ -88,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +110,6 @@ public: }; ``` -### **Go** - ```go func maxSatisfied(customers []int, grumpy []int, minutes int) int { s, cs := 0, 0 @@ -136,8 +130,6 @@ func maxSatisfied(customers []int, grumpy []int, minutes int) int { } ``` -### **Rust** - ```rust impl Solution { pub fn max_satisfied(customers: Vec, grumpy: Vec, minutes: i32) -> i32 { @@ -172,10 +164,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1053.Previous Permutation With One Swap/README.md b/solution/1000-1099/1053.Previous Permutation With One Swap/README.md index db6f8c36af723..3f15126e8b325 100644 --- a/solution/1000-1099/1053.Previous Permutation With One Swap/README.md +++ b/solution/1000-1099/1053.Previous Permutation With One Swap/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们先从右到左遍历数组,找到第一个满足 $arr[i - 1] \gt arr[i]$ 的下标 $i$,此时 $arr[i - 1]$ 就是我们要交换的数字,我们再从右到左遍历数组,找到第一个满足 $arr[j] \lt arr[i - 1]$ 且 $arr[j] \neq arr[j - 1]$ 的下标 $j$,此时我们交换 $arr[i - 1]$ 和 $arr[j]$ 后返回即可。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def prevPermOpt1(self, arr: List[int]) -> List[int]: @@ -76,10 +70,6 @@ class Solution: return arr ``` -### **Java** - - - ```java class Solution { public int[] prevPermOpt1(int[] arr) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func prevPermOpt1(arr []int) []int { n := len(arr) @@ -142,8 +128,6 @@ func prevPermOpt1(arr []int) []int { } ``` -### **TypeScript** - ```ts function prevPermOpt1(arr: number[]): number[] { const n = arr.length; @@ -163,10 +147,6 @@ function prevPermOpt1(arr: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1053.Previous Permutation With One Swap/README_EN.md b/solution/1000-1099/1053.Previous Permutation With One Swap/README_EN.md index 2163182d57a14..8517d4df9021c 100644 --- a/solution/1000-1099/1053.Previous Permutation With One Swap/README_EN.md +++ b/solution/1000-1099/1053.Previous Permutation With One Swap/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return arr ``` -### **Java** - ```java class Solution { public int[] prevPermOpt1(int[] arr) { @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +101,6 @@ public: }; ``` -### **Go** - ```go func prevPermOpt1(arr []int) []int { n := len(arr) @@ -124,8 +118,6 @@ func prevPermOpt1(arr []int) []int { } ``` -### **TypeScript** - ```ts function prevPermOpt1(arr: number[]): number[] { const n = arr.length; @@ -145,10 +137,6 @@ function prevPermOpt1(arr: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1054.Distant Barcodes/README.md b/solution/1000-1099/1054.Distant Barcodes/README.md index d7a2bbe1e9ee1..71333bdd687f4 100644 --- a/solution/1000-1099/1054.Distant Barcodes/README.md +++ b/solution/1000-1099/1054.Distant Barcodes/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:计数 + 排序** +### 方法一:计数 + 排序 我们先用哈希表或数组 $cnt$ 统计数组 $barcodes$ 中各个数出现的次数,然后将 $barcodes$ 中的数按照它们在 $cnt$ 中出现的次数从大到小排序,如果出现次数相同,那么就按照数的大小从小到大排序(确保相同的数相邻)。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python class Solution: def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]: @@ -64,10 +58,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] rearrangeBarcodes(int[] barcodes) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func rearrangeBarcodes(barcodes []int) []int { mx := slices.Max(barcodes) @@ -148,8 +134,6 @@ func rearrangeBarcodes(barcodes []int) []int { } ``` -### **TypeScript** - ```ts function rearrangeBarcodes(barcodes: number[]): number[] { const mx = Math.max(...barcodes); @@ -169,10 +153,6 @@ function rearrangeBarcodes(barcodes: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1054.Distant Barcodes/README_EN.md b/solution/1000-1099/1054.Distant Barcodes/README_EN.md index c24d483d977ab..65a16f873701e 100644 --- a/solution/1000-1099/1054.Distant Barcodes/README_EN.md +++ b/solution/1000-1099/1054.Distant Barcodes/README_EN.md @@ -26,9 +26,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -42,8 +42,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] rearrangeBarcodes(int[] barcodes) { @@ -70,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +93,6 @@ public: }; ``` -### **Go** - ```go func rearrangeBarcodes(barcodes []int) []int { mx := slices.Max(barcodes) @@ -124,8 +118,6 @@ func rearrangeBarcodes(barcodes []int) []int { } ``` -### **TypeScript** - ```ts function rearrangeBarcodes(barcodes: number[]): number[] { const mx = Math.max(...barcodes); @@ -145,10 +137,6 @@ function rearrangeBarcodes(barcodes: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1055.Shortest Way to Form String/README.md b/solution/1000-1099/1055.Shortest Way to Form String/README.md index 17a95120e909a..3c1894765bb4b 100644 --- a/solution/1000-1099/1055.Shortest Way to Form String/README.md +++ b/solution/1000-1099/1055.Shortest Way to Form String/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们可以使用双指针的方法,用指针 $j$ 指向目标字符串 `target`,然后遍历源字符串 `source`,用指针 $i$ 指向源字符串 `source`,如果 $source[i] = target[j]$,则 $i$ 和 $j$ 同时向后移动一位,否则只移动 $i$ 指针。当指针 $i$ 和 $j$ 都到达字符串末尾时,如果没有找到相等的字符,则返回 $-1$,否则子序列数量加一,然后将指针 $i$ 置为 $0$,继续遍历。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def shortestWay(self, source: str, target: str) -> int: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int shortestWay(String source, String target) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func shortestWay(source string, target string) int { m, n := len(source), len(target) @@ -164,10 +150,6 @@ func shortestWay(source string, target string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1055.Shortest Way to Form String/README_EN.md b/solution/1000-1099/1055.Shortest Way to Form String/README_EN.md index 978761cebdefa..76a90117cc176 100644 --- a/solution/1000-1099/1055.Shortest Way to Form String/README_EN.md +++ b/solution/1000-1099/1055.Shortest Way to Form String/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int shortestWay(String source, String target) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func shortestWay(source string, target string) int { m, n := len(source), len(target) @@ -146,10 +140,6 @@ func shortestWay(source string, target string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1056.Confusing Number/README.md b/solution/1000-1099/1056.Confusing Number/README.md index 11451daa81e01..ad7b2ee69ad0b 100644 --- a/solution/1000-1099/1056.Confusing Number/README.md +++ b/solution/1000-1099/1056.Confusing Number/README.md @@ -73,22 +73,10 @@ ## 解法 - - -我们先用一个长度为 $10$ 的数组 $d$ 记录每个数字旋转 180° 后对应的数字,在这道题中,数字 $[0,1,6,8,9]$ 旋转后得到的数字是 $[0,1,9,8,6]$,其余数字旋转后得到的不是数字,我们将对应的数字置为 $-1$。 - -将 $n$ 的值赋给 $x$。然后遍历数字 $x$ 的每一位数字 $v$,如果 $d[v] \lt 0$,说明 $x$ 不是易混淆数,直接返回 `false`。否则,我们将数字 $v$ 对应的旋转数字 $d[v]$ 加入到 $y$ 中。最后,判断 $y$ 和 $n$ 是否相等,若不相等,则说明 $n$ 是易混淆数,返回 `true`。 - -时间复杂度 $O(\log n)$,空间复杂度 $O(1)$。 - -相似题目:[788. 旋转数字](/solution/0700-0799/0788.Rotated%20Digits/README.md) +### 方法一 -### **Python3** - - - ```python class Solution: def confusingNumber(self, n: int) -> bool: @@ -102,10 +90,6 @@ class Solution: return y != n ``` -### **Java** - - - ```java class Solution { public boolean confusingNumber(int n) { @@ -124,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +127,6 @@ public: }; ``` -### **Go** - ```go func confusingNumber(n int) bool { d := []int{0, 1, -1, -1, -1, -1, 9, -1, 8, 6} @@ -163,8 +143,6 @@ func confusingNumber(n int) bool { } ``` -### **PHP** - ```php class Solution { /** @@ -188,10 +166,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1056.Confusing Number/README_EN.md b/solution/1000-1099/1056.Confusing Number/README_EN.md index ee8537a8f7dc4..c808299194ce9 100644 --- a/solution/1000-1099/1056.Confusing Number/README_EN.md +++ b/solution/1000-1099/1056.Confusing Number/README_EN.md @@ -55,9 +55,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return y != n ``` -### **Java** - ```java class Solution { public boolean confusingNumber(int n) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func confusingNumber(n int) bool { d := []int{0, 1, -1, -1, -1, -1, 9, -1, 8, 6} @@ -131,8 +125,6 @@ func confusingNumber(n int) bool { } ``` -### **PHP** - ```php class Solution { /** @@ -156,10 +148,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1057.Campus Bikes/README.md b/solution/1000-1099/1057.Campus Bikes/README.md index 5456179f55243..9cfb4e9bda387 100644 --- a/solution/1000-1099/1057.Campus Bikes/README.md +++ b/solution/1000-1099/1057.Campus Bikes/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 先计算每个工人和每个自行车之间的曼哈顿距离,然后按照曼哈顿距离从小到大排序,遍历排序后的数组,如果当前工人和自行车都未被分配,则分配给当前工人和自行车。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def assignBikes( @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] assignBikes(int[][] workers, int[][] bikes) { @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go func assignBikes(workers [][]int, bikes [][]int) []int { n, m := len(workers), len(bikes) @@ -204,10 +190,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1057.Campus Bikes/README_EN.md b/solution/1000-1099/1057.Campus Bikes/README_EN.md index 1403ef5db648e..234cb6c1fe305 100644 --- a/solution/1000-1099/1057.Campus Bikes/README_EN.md +++ b/solution/1000-1099/1057.Campus Bikes/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] assignBikes(int[][] workers, int[][] bikes) { @@ -112,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +137,6 @@ public: }; ``` -### **Go** - ```go func assignBikes(workers [][]int, bikes [][]int) []int { n, m := len(workers), len(bikes) @@ -184,10 +178,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1058.Minimize Rounding Error to Meet Target/README.md b/solution/1000-1099/1058.Minimize Rounding Error to Meet Target/README.md index f8be7aebc8e8a..c9e9716a678f2 100644 --- a/solution/1000-1099/1058.Minimize Rounding Error to Meet Target/README.md +++ b/solution/1000-1099/1058.Minimize Rounding Error to Meet Target/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 遍历价格数组 `prices`,先将每个价格 $p$ 向下舍入,累加到 `mi` 中,同时将每个价格的小数点部分添加到数组 `arr` 中。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def minimizeError(self, prices: List[str], target: int) -> str: @@ -84,10 +78,6 @@ class Solution: return f'{ans:.3f}' ``` -### **Java** - - - ```java class Solution { public String minimizeError(String[] prices, int target) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func minimizeError(prices []string, target int) string { arr := []float64{} @@ -183,10 +169,6 @@ func minimizeError(prices []string, target int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1058.Minimize Rounding Error to Meet Target/README_EN.md b/solution/1000-1099/1058.Minimize Rounding Error to Meet Target/README_EN.md index 6d663e2368245..d23a1e27c3c8e 100644 --- a/solution/1000-1099/1058.Minimize Rounding Error to Meet Target/README_EN.md +++ b/solution/1000-1099/1058.Minimize Rounding Error to Meet Target/README_EN.md @@ -44,9 +44,9 @@ Use Floor, Ceil and Ceil operations to get (0.7 - 0) + (3 - 2.8) + (5 - 4.9) = 0 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return f'{ans:.3f}' ``` -### **Java** - ```java class Solution { public String minimizeError(String[] prices, int target) { @@ -99,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +129,6 @@ public: }; ``` -### **Go** - ```go func minimizeError(prices []string, target int) string { arr := []float64{} @@ -163,10 +157,6 @@ func minimizeError(prices []string, target int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1059.All Paths from Source Lead to Destination/README.md b/solution/1000-1099/1059.All Paths from Source Lead to Destination/README.md index 9d8e91bd1da0d..b5d7ba9abd7af 100644 --- a/solution/1000-1099/1059.All Paths from Source Lead to Destination/README.md +++ b/solution/1000-1099/1059.All Paths from Source Lead to Destination/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 建图,然后从 `source` 出发,进行深度优先搜索: @@ -85,10 +83,6 @@ -### **Python3** - - - ```python class Solution: def leadsToDestination( @@ -113,10 +107,6 @@ class Solution: return dfs(source) ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -159,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -196,8 +184,6 @@ public: }; ``` -### **Go** - ```go func leadsToDestination(n int, edges [][]int, source int, destination int) bool { vis := make([]bool, n) @@ -231,10 +217,6 @@ func leadsToDestination(n int, edges [][]int, source int, destination int) bool } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1059.All Paths from Source Lead to Destination/README_EN.md b/solution/1000-1099/1059.All Paths from Source Lead to Destination/README_EN.md index 50244c64a4073..9eb242c0817fe 100644 --- a/solution/1000-1099/1059.All Paths from Source Lead to Destination/README_EN.md +++ b/solution/1000-1099/1059.All Paths from Source Lead to Destination/README_EN.md @@ -53,9 +53,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -81,8 +81,6 @@ class Solution: return dfs(source) ``` -### **Java** - ```java class Solution { private List[] g; @@ -125,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +158,6 @@ public: }; ``` -### **Go** - ```go func leadsToDestination(n int, edges [][]int, source int, destination int) bool { vis := make([]bool, n) @@ -197,10 +191,6 @@ func leadsToDestination(n int, edges [][]int, source int, destination int) bool } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1060.Missing Element in Sorted Array/README.md b/solution/1000-1099/1060.Missing Element in Sorted Array/README.md index ed5df7c4c2f30..71d91017c34de 100644 --- a/solution/1000-1099/1060.Missing Element in Sorted Array/README.md +++ b/solution/1000-1099/1060.Missing Element in Sorted Array/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们设计一个函数 $missing(i)$,表示 $nums[i]$ 与 $nums[0]$ 之间缺失的元素个数。那么 $missing(i)$ 就等于 $nums[i] - nums[0] - i$。我们可以通过二分查找找到最小的 $i$,使得 $missing(i) \geq k$,那么 $nums[i - 1] + k - missing(i - 1)$ 就是第 $k$ 个缺失的元素。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def missingElement(self, nums: List[int], k: int) -> int: @@ -86,10 +80,6 @@ class Solution: return nums[l - 1] + k - missing(l - 1) ``` -### **Java** - - - ```java class Solution { public int missingElement(int[] nums, int k) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func missingElement(nums []int, k int) int { missing := func(i int) int { @@ -166,10 +152,6 @@ func missingElement(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1060.Missing Element in Sorted Array/README_EN.md b/solution/1000-1099/1060.Missing Element in Sorted Array/README_EN.md index 4baa243a21a06..aabea556ebad6 100644 --- a/solution/1000-1099/1060.Missing Element in Sorted Array/README_EN.md +++ b/solution/1000-1099/1060.Missing Element in Sorted Array/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return nums[l - 1] + k - missing(l - 1) ``` -### **Java** - ```java class Solution { public int missingElement(int[] nums, int k) { @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func missingElement(nums []int, k int) int { missing := func(i int) int { @@ -147,10 +141,6 @@ func missingElement(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1061.Lexicographically Smallest Equivalent String/README.md b/solution/1000-1099/1061.Lexicographically Smallest Equivalent String/README.md index 5c2eeefb93707..f977d82260389 100644 --- a/solution/1000-1099/1061.Lexicographically Smallest Equivalent String/README.md +++ b/solution/1000-1099/1061.Lexicographically Smallest Equivalent String/README.md @@ -64,81 +64,10 @@ ## 解法 - - -并查集。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` - -对于本题,套用并查集模板时,将数值较大的祖宗节点指向数值较小的祖宗节点,这样可以保证祖宗节点存放的是本集合的最小值。 +### 方法一 -### **Python3** - - - ```python class Solution: def smallestEquivalentString(self, s1: str, s2: str, baseStr: str) -> str: @@ -164,10 +93,6 @@ class Solution: return ''.join(res) ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -203,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -238,8 +161,6 @@ public: }; ``` -### **Go** - ```go var p []int @@ -273,10 +194,6 @@ func find(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1061.Lexicographically Smallest Equivalent String/README_EN.md b/solution/1000-1099/1061.Lexicographically Smallest Equivalent String/README_EN.md index a3ecc71abf27c..12dc9648669a6 100644 --- a/solution/1000-1099/1061.Lexicographically Smallest Equivalent String/README_EN.md +++ b/solution/1000-1099/1061.Lexicographically Smallest Equivalent String/README_EN.md @@ -63,9 +63,9 @@ So only the second letter 'o' in baseStr is changed to 'd', the ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -92,8 +92,6 @@ class Solution: return ''.join(res) ``` -### **Java** - ```java class Solution { private int[] p; @@ -129,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +160,6 @@ public: }; ``` -### **Go** - ```go var p []int @@ -199,10 +193,6 @@ func find(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1062.Longest Repeating Substring/README.md b/solution/1000-1099/1062.Longest Repeating Substring/README.md index 4b0c111d36816..c54785cd2a4c1 100644 --- a/solution/1000-1099/1062.Longest Repeating Substring/README.md +++ b/solution/1000-1099/1062.Longest Repeating Substring/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 定义 $dp[i][j]$ 表示以 $s[i]$ 和 $s[j]$ 结尾的最长重复子串的长度。状态转移方程为: @@ -71,10 +69,6 @@ $$ -### **Python3** - - - ```python class Solution: def longestRepeatingSubstring(self, s: str) -> int: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestRepeatingSubstring(String s) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func longestRepeatingSubstring(s string) int { n := len(s) @@ -160,10 +146,6 @@ func longestRepeatingSubstring(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1062.Longest Repeating Substring/README_EN.md b/solution/1000-1099/1062.Longest Repeating Substring/README_EN.md index ae4bbc8029f28..73a055a9bc1f6 100644 --- a/solution/1000-1099/1062.Longest Repeating Substring/README_EN.md +++ b/solution/1000-1099/1062.Longest Repeating Substring/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestRepeatingSubstring(String s) { @@ -80,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +98,6 @@ public: }; ``` -### **Go** - ```go func longestRepeatingSubstring(s string) int { n := len(s) @@ -128,10 +122,6 @@ func longestRepeatingSubstring(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1063.Number of Valid Subarrays/README.md b/solution/1000-1099/1063.Number of Valid Subarrays/README.md index 290320510e278..8c09b1dff040f 100644 --- a/solution/1000-1099/1063.Number of Valid Subarrays/README.md +++ b/solution/1000-1099/1063.Number of Valid Subarrays/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 题目实际上是求解每个位置 $i$ 的右边第一个小于 $nums[i]$ 的位置 $j$,那么以 $i$ 为左端点的有效子数组的个数就是 $j - i$。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def validSubarrays(self, nums: List[int]) -> int: @@ -83,24 +77,6 @@ class Solution: return sum(j - i for i, j in enumerate(right)) ``` -```python -class Solution: - def validSubarrays(self, nums: List[int]) -> int: - n = len(nums) - stk = [] - ans = 0 - for i in range(n - 1, -1, -1): - while stk and nums[stk[-1]] >= nums[i]: - stk.pop() - ans += (stk[-1] if stk else n) - i - stk.append(i) - return ans -``` - -### **Java** - - - ```java class Solution { public int validSubarrays(int[] nums) { @@ -126,27 +102,6 @@ class Solution { } ``` -```java -class Solution { - public int validSubarrays(int[] nums) { - int n = nums.length; - Deque stk = new ArrayDeque<>(); - int ans = 0; - for (int i = n - 1; i >= 0; --i) { - while (!stk.isEmpty() && nums[stk.peek()] >= nums[i]) { - stk.pop(); - } - ans += (stk.isEmpty() ? n : stk.peek()) - i; - - stk.push(i); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -172,27 +127,6 @@ public: }; ``` -```cpp -class Solution { -public: - int validSubarrays(vector& nums) { - int n = nums.size(); - stack stk; - int ans = 0; - for (int i = n - 1; ~i; --i) { - while (stk.size() && nums[stk.top()] >= nums[i]) { - stk.pop(); - } - ans += (stk.size() ? stk.top() : n) - i; - stk.push(i); - } - return ans; - } -}; -``` - -### **Go** - ```go func validSubarrays(nums []int) (ans int) { n := len(nums) @@ -217,28 +151,6 @@ func validSubarrays(nums []int) (ans int) { } ``` -```go -func validSubarrays(nums []int) (ans int) { - n := len(nums) - stk := []int{} - for i := n - 1; i >= 0; i-- { - for len(stk) > 0 && nums[stk[len(stk)-1]] >= nums[i] { - stk = stk[:len(stk)-1] - } - ans -= i - if len(stk) > 0 { - ans += stk[len(stk)-1] - } else { - ans += n - } - stk = append(stk, i) - } - return -} -``` - -### **TypeScript** - ```ts function validSubarrays(nums: number[]): number { const n = nums.length; @@ -261,6 +173,84 @@ function validSubarrays(nums: number[]): number { } ``` + + +### 方法二 + + + +```python +class Solution: + def validSubarrays(self, nums: List[int]) -> int: + n = len(nums) + stk = [] + ans = 0 + for i in range(n - 1, -1, -1): + while stk and nums[stk[-1]] >= nums[i]: + stk.pop() + ans += (stk[-1] if stk else n) - i + stk.append(i) + return ans +``` + +```java +class Solution { + public int validSubarrays(int[] nums) { + int n = nums.length; + Deque stk = new ArrayDeque<>(); + int ans = 0; + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && nums[stk.peek()] >= nums[i]) { + stk.pop(); + } + ans += (stk.isEmpty() ? n : stk.peek()) - i; + + stk.push(i); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int validSubarrays(vector& nums) { + int n = nums.size(); + stack stk; + int ans = 0; + for (int i = n - 1; ~i; --i) { + while (stk.size() && nums[stk.top()] >= nums[i]) { + stk.pop(); + } + ans += (stk.size() ? stk.top() : n) - i; + stk.push(i); + } + return ans; + } +}; +``` + +```go +func validSubarrays(nums []int) (ans int) { + n := len(nums) + stk := []int{} + for i := n - 1; i >= 0; i-- { + for len(stk) > 0 && nums[stk[len(stk)-1]] >= nums[i] { + stk = stk[:len(stk)-1] + } + ans -= i + if len(stk) > 0 { + ans += stk[len(stk)-1] + } else { + ans += n + } + stk = append(stk, i) + } + return +} +``` + ```ts function validSubarrays(nums: number[]): number { const n = nums.length; @@ -277,10 +267,6 @@ function validSubarrays(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1063.Number of Valid Subarrays/README_EN.md b/solution/1000-1099/1063.Number of Valid Subarrays/README_EN.md index bee4ffe5410c6..e58134ef33610 100644 --- a/solution/1000-1099/1063.Number of Valid Subarrays/README_EN.md +++ b/solution/1000-1099/1063.Number of Valid Subarrays/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,22 +62,6 @@ class Solution: return sum(j - i for i, j in enumerate(right)) ``` -```python -class Solution: - def validSubarrays(self, nums: List[int]) -> int: - n = len(nums) - stk = [] - ans = 0 - for i in range(n - 1, -1, -1): - while stk and nums[stk[-1]] >= nums[i]: - stk.pop() - ans += (stk[-1] if stk else n) - i - stk.append(i) - return ans -``` - -### **Java** - ```java class Solution { public int validSubarrays(int[] nums) { @@ -103,27 +87,6 @@ class Solution { } ``` -```java -class Solution { - public int validSubarrays(int[] nums) { - int n = nums.length; - Deque stk = new ArrayDeque<>(); - int ans = 0; - for (int i = n - 1; i >= 0; --i) { - while (!stk.isEmpty() && nums[stk.peek()] >= nums[i]) { - stk.pop(); - } - ans += (stk.isEmpty() ? n : stk.peek()) - i; - - stk.push(i); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -149,27 +112,6 @@ public: }; ``` -```cpp -class Solution { -public: - int validSubarrays(vector& nums) { - int n = nums.size(); - stack stk; - int ans = 0; - for (int i = n - 1; ~i; --i) { - while (stk.size() && nums[stk.top()] >= nums[i]) { - stk.pop(); - } - ans += (stk.size() ? stk.top() : n) - i; - stk.push(i); - } - return ans; - } -}; -``` - -### **Go** - ```go func validSubarrays(nums []int) (ans int) { n := len(nums) @@ -194,28 +136,6 @@ func validSubarrays(nums []int) (ans int) { } ``` -```go -func validSubarrays(nums []int) (ans int) { - n := len(nums) - stk := []int{} - for i := n - 1; i >= 0; i-- { - for len(stk) > 0 && nums[stk[len(stk)-1]] >= nums[i] { - stk = stk[:len(stk)-1] - } - ans -= i - if len(stk) > 0 { - ans += stk[len(stk)-1] - } else { - ans += n - } - stk = append(stk, i) - } - return -} -``` - -### **TypeScript** - ```ts function validSubarrays(nums: number[]): number { const n = nums.length; @@ -238,6 +158,84 @@ function validSubarrays(nums: number[]): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def validSubarrays(self, nums: List[int]) -> int: + n = len(nums) + stk = [] + ans = 0 + for i in range(n - 1, -1, -1): + while stk and nums[stk[-1]] >= nums[i]: + stk.pop() + ans += (stk[-1] if stk else n) - i + stk.append(i) + return ans +``` + +```java +class Solution { + public int validSubarrays(int[] nums) { + int n = nums.length; + Deque stk = new ArrayDeque<>(); + int ans = 0; + for (int i = n - 1; i >= 0; --i) { + while (!stk.isEmpty() && nums[stk.peek()] >= nums[i]) { + stk.pop(); + } + ans += (stk.isEmpty() ? n : stk.peek()) - i; + + stk.push(i); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int validSubarrays(vector& nums) { + int n = nums.size(); + stack stk; + int ans = 0; + for (int i = n - 1; ~i; --i) { + while (stk.size() && nums[stk.top()] >= nums[i]) { + stk.pop(); + } + ans += (stk.size() ? stk.top() : n) - i; + stk.push(i); + } + return ans; + } +}; +``` + +```go +func validSubarrays(nums []int) (ans int) { + n := len(nums) + stk := []int{} + for i := n - 1; i >= 0; i-- { + for len(stk) > 0 && nums[stk[len(stk)-1]] >= nums[i] { + stk = stk[:len(stk)-1] + } + ans -= i + if len(stk) > 0 { + ans += stk[len(stk)-1] + } else { + ans += n + } + stk = append(stk, i) + } + return +} +``` + ```ts function validSubarrays(nums: number[]): number { const n = nums.length; @@ -254,10 +252,6 @@ function validSubarrays(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1064.Fixed Point/README.md b/solution/1000-1099/1064.Fixed Point/README.md index 6530c249f2ca4..52b6444df91c4 100644 --- a/solution/1000-1099/1064.Fixed Point/README.md +++ b/solution/1000-1099/1064.Fixed Point/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 题目给定的数组是按升序排列的,因此我们可以使用二分查找的方法找出最小的满足 $arr[i]$ 等于 $i$ 的下标 $i$。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def fixedPoint(self, arr: List[int]) -> int: @@ -80,10 +74,6 @@ class Solution: return left if arr[left] == left else -1 ``` -### **Java** - - - ```java class Solution { public int fixedPoint(int[] arr) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func fixedPoint(arr []int) int { left, right := 0, len(arr)-1 @@ -141,8 +127,6 @@ func fixedPoint(arr []int) int { } ``` -### **TypeScript** - ```ts function fixedPoint(arr: number[]): number { let left = 0; @@ -159,10 +143,6 @@ function fixedPoint(arr: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1064.Fixed Point/README_EN.md b/solution/1000-1099/1064.Fixed Point/README_EN.md index 771d9ad04e5d8..3e3b787124c31 100644 --- a/solution/1000-1099/1064.Fixed Point/README_EN.md +++ b/solution/1000-1099/1064.Fixed Point/README_EN.md @@ -41,12 +41,10 @@ ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python class Solution: def fixedPoint(self, arr: List[int]) -> int: @@ -60,8 +58,6 @@ class Solution: return left if arr[left] == left else -1 ``` -### **Java** - ```java class Solution { public int fixedPoint(int[] arr) { @@ -79,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +93,6 @@ public: }; ``` -### **Go** - ```go func fixedPoint(arr []int) int { left, right := 0, len(arr)-1 @@ -119,8 +111,6 @@ func fixedPoint(arr []int) int { } ``` -### **TypeScript** - ```ts function fixedPoint(arr: number[]): number { let left = 0; @@ -137,10 +127,6 @@ function fixedPoint(arr: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1065.Index Pairs of a String/README.md b/solution/1000-1099/1065.Index Pairs of a String/README.md index ef36e990ed0be..c6683542ff9d3 100644 --- a/solution/1000-1099/1065.Index Pairs of a String/README.md +++ b/solution/1000-1099/1065.Index Pairs of a String/README.md @@ -39,23 +39,10 @@ ## 解法 - - -**方法一:暴力枚举** - -**方法二:前缀树** - -相似题目: - -- [616. 给字符串添加加粗标签](/solution/0600-0699/0616.Add%20Bold%20Tag%20in%20String/README.md) -- [758. 字符串中的加粗单词](/solution/0700-0799/0758.Bold%20Words%20in%20String/README.md) +### 方法一:暴力枚举 -### **Python3** - - - ```python class Solution: def indexPairs(self, text: str, words: List[str]) -> List[List[int]]: @@ -66,45 +53,6 @@ class Solution: ] ``` -```python -class Trie: - def __init__(self): - self.children = [None] * 26 - self.is_end = False - - def insert(self, word): - node = self - for c in word: - idx = ord(c) - ord('a') - if node.children[idx] is None: - node.children[idx] = Trie() - node = node.children[idx] - node.is_end = True - - -class Solution: - def indexPairs(self, text: str, words: List[str]) -> List[List[int]]: - trie = Trie() - for w in words: - trie.insert(w) - n = len(text) - ans = [] - for i in range(n): - node = trie - for j in range(i, n): - idx = ord(text[j]) - ord('a') - if node.children[idx] is None: - break - node = node.children[idx] - if node.is_end: - ans.append([i, j]) - return ans -``` - -### **Java** - - - ```java class Trie { Trie[] children = new Trie[26]; @@ -149,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -193,8 +139,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -241,10 +185,52 @@ func indexPairs(text string, words []string) [][]int { } ``` -### **...** + + +### 方法二:前缀树 -``` +相似题目: +- [616. 给字符串添加加粗标签](/solution/0600-0699/0616.Add%20Bold%20Tag%20in%20String/README.md) +- [758. 字符串中的加粗单词](/solution/0700-0799/0758.Bold%20Words%20in%20String/README.md) + + + +```python +class Trie: + def __init__(self): + self.children = [None] * 26 + self.is_end = False + + def insert(self, word): + node = self + for c in word: + idx = ord(c) - ord('a') + if node.children[idx] is None: + node.children[idx] = Trie() + node = node.children[idx] + node.is_end = True + + +class Solution: + def indexPairs(self, text: str, words: List[str]) -> List[List[int]]: + trie = Trie() + for w in words: + trie.insert(w) + n = len(text) + ans = [] + for i in range(n): + node = trie + for j in range(i, n): + idx = ord(text[j]) - ord('a') + if node.children[idx] is None: + break + node = node.children[idx] + if node.is_end: + ans.append([i, j]) + return ans ``` + + diff --git a/solution/1000-1099/1065.Index Pairs of a String/README_EN.md b/solution/1000-1099/1065.Index Pairs of a String/README_EN.md index 895f93e354662..877af61515aca 100644 --- a/solution/1000-1099/1065.Index Pairs of a String/README_EN.md +++ b/solution/1000-1099/1065.Index Pairs of a String/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,43 +51,6 @@ class Solution: ] ``` -```python -class Trie: - def __init__(self): - self.children = [None] * 26 - self.is_end = False - - def insert(self, word): - node = self - for c in word: - idx = ord(c) - ord('a') - if node.children[idx] is None: - node.children[idx] = Trie() - node = node.children[idx] - node.is_end = True - - -class Solution: - def indexPairs(self, text: str, words: List[str]) -> List[List[int]]: - trie = Trie() - for w in words: - trie.insert(w) - n = len(text) - ans = [] - for i in range(n): - node = trie - for j in range(i, n): - idx = ord(text[j]) - ord('a') - if node.children[idx] is None: - break - node = node.children[idx] - if node.is_end: - ans.append([i, j]) - return ans -``` - -### **Java** - ```java class Trie { Trie[] children = new Trie[26]; @@ -132,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -176,8 +137,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -224,10 +183,47 @@ func indexPairs(text string, words []string) [][]int { } ``` -### **...** + -``` +### Solution 2 + + + +```python +class Trie: + def __init__(self): + self.children = [None] * 26 + self.is_end = False + + def insert(self, word): + node = self + for c in word: + idx = ord(c) - ord('a') + if node.children[idx] is None: + node.children[idx] = Trie() + node = node.children[idx] + node.is_end = True + +class Solution: + def indexPairs(self, text: str, words: List[str]) -> List[List[int]]: + trie = Trie() + for w in words: + trie.insert(w) + n = len(text) + ans = [] + for i in range(n): + node = trie + for j in range(i, n): + idx = ord(text[j]) - ord('a') + if node.children[idx] is None: + break + node = node.children[idx] + if node.is_end: + ans.append([i, j]) + return ans ``` + + diff --git a/solution/1000-1099/1066.Campus Bikes II/README.md b/solution/1000-1099/1066.Campus Bikes II/README.md index 2d52f7a299833..d0d1e16cfffa7 100644 --- a/solution/1000-1099/1066.Campus Bikes II/README.md +++ b/solution/1000-1099/1066.Campus Bikes II/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:状态压缩动态规划** +### 方法一:状态压缩动态规划 我们定义 $f[i][j]$ 表示前 $i$ 个工人分配到自行车的状态为 $j$ 时的最小曼哈顿距离总和,其中 $j$ 是一个二进制数,表示自行车的分配情况。初始时 $f[0][0]=0$,其余 $f[0][j]=+\infty$。 @@ -79,10 +77,6 @@ $$ -### **Python3** - - - ```python class Solution: def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> int: @@ -100,10 +94,6 @@ class Solution: return min(f[n]) ``` -### **Java** - - - ```java class Solution { public int assignBikes(int[][] workers, int[][] bikes) { @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func assignBikes(workers [][]int, bikes [][]int) int { n, m := len(workers), len(bikes) @@ -190,8 +176,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function assignBikes(workers: number[][], bikes: number[][]): number { const n = workers.length; @@ -215,10 +199,6 @@ function assignBikes(workers: number[][], bikes: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1066.Campus Bikes II/README_EN.md b/solution/1000-1099/1066.Campus Bikes II/README_EN.md index d006afab83bac..ea719b6faf807 100644 --- a/solution/1000-1099/1066.Campus Bikes II/README_EN.md +++ b/solution/1000-1099/1066.Campus Bikes II/README_EN.md @@ -53,9 +53,9 @@ We first assign bike 0 to worker 0, then assign bike 1 to worker 1 or worker 2, ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return min(f[n]) ``` -### **Java** - ```java class Solution { public int assignBikes(int[][] workers, int[][] bikes) { @@ -102,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +123,6 @@ public: }; ``` -### **Go** - ```go func assignBikes(workers [][]int, bikes [][]int) int { n, m := len(workers), len(bikes) @@ -162,8 +156,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function assignBikes(workers: number[][], bikes: number[][]): number { const n = workers.length; @@ -187,10 +179,6 @@ function assignBikes(workers: number[][], bikes: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1067.Digit Count in Range/README.md b/solution/1000-1099/1067.Digit Count in Range/README.md index 189cfe5cd6835..aa8adf4e5542d 100644 --- a/solution/1000-1099/1067.Digit Count in Range/README.md +++ b/solution/1000-1099/1067.Digit Count in Range/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:数位 DP** +### 方法一:数位 DP 这道题实际上是求在给定区间 $[l,..r]$ 中,数字中出现 $d$ 的个数。个数与数的位数以及每一位上的数字有关。我们可以用数位 DP 的思路来解决这道题。数位 DP 中,数的大小对复杂度的影响很小。 @@ -71,10 +69,6 @@ $$ -### **Python3** - - - ```python class Solution: def digitsCount(self, d: int, low: int, high: int) -> int: @@ -103,10 +97,6 @@ class Solution: return dfs(l, 0, True, True) ``` -### **Java** - - - ```java class Solution { private int d; @@ -154,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -202,8 +190,6 @@ public: }; ``` -### **Go** - ```go func digitsCount(d int, low int, high int) int { f := func(n int) int { @@ -258,10 +244,6 @@ func digitsCount(d int, low int, high int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1067.Digit Count in Range/README_EN.md b/solution/1000-1099/1067.Digit Count in Range/README_EN.md index 82e5b278802da..e51b209e46fd8 100644 --- a/solution/1000-1099/1067.Digit Count in Range/README_EN.md +++ b/solution/1000-1099/1067.Digit Count in Range/README_EN.md @@ -34,9 +34,9 @@ Note that the digit d = 1 occurs twice in the number 11. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return dfs(l, 0, True, True) ``` -### **Java** - ```java class Solution { private int d; @@ -115,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +159,6 @@ public: }; ``` -### **Go** - ```go func digitsCount(d int, low int, high int) int { f := func(n int) int { @@ -219,10 +213,6 @@ func digitsCount(d int, low int, high int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1068.Product Sales Analysis I/README.md b/solution/1000-1099/1068.Product Sales Analysis I/README.md index 7552083ec63d2..14fd57f6b061e 100644 --- a/solution/1000-1099/1068.Product Sales Analysis I/README.md +++ b/solution/1000-1099/1068.Product Sales Analysis I/README.md @@ -79,16 +79,12 @@ Product 表: ## 解法 - - -**方法一:使用 `JOIN` 内连接** +### 方法一:使用 `JOIN` 内连接 我们直接使用 `JOIN` 连接 `Sales` 和 `Product` 两张表,连接字段为 `product_id`,然后选择需要的字段即可。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT product_name, year, price @@ -98,3 +94,5 @@ FROM ``` + + diff --git a/solution/1000-1099/1068.Product Sales Analysis I/README_EN.md b/solution/1000-1099/1068.Product Sales Analysis I/README_EN.md index 4e234740e0de1..3f68aee320366 100644 --- a/solution/1000-1099/1068.Product Sales Analysis I/README_EN.md +++ b/solution/1000-1099/1068.Product Sales Analysis I/README_EN.md @@ -82,9 +82,9 @@ From sale_id = 7, we can conclude that Apple was sold for 9000 in the year 2011. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -95,3 +95,5 @@ FROM ``` + + diff --git a/solution/1000-1099/1069.Product Sales Analysis II/README.md b/solution/1000-1099/1069.Product Sales Analysis II/README.md index 6614f94c0d0af..a03dcddf11078 100644 --- a/solution/1000-1099/1069.Product Sales Analysis II/README.md +++ b/solution/1000-1099/1069.Product Sales Analysis II/README.md @@ -77,16 +77,12 @@ Product 表: ## 解法 - - -**方法一:使用 `GROUP BY`** +### 方法一:使用 `GROUP BY` 我们可以使用 `GROUP BY`,按照 `product_id` 分组,然后每一组对 `quantity` 求和。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT product_id, SUM(quantity) AS total_quantity @@ -95,3 +91,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1000-1099/1069.Product Sales Analysis II/README_EN.md b/solution/1000-1099/1069.Product Sales Analysis II/README_EN.md index 06c9a926b2241..3bf2d8f9663cb 100644 --- a/solution/1000-1099/1069.Product Sales Analysis II/README_EN.md +++ b/solution/1000-1099/1069.Product Sales Analysis II/README_EN.md @@ -77,9 +77,9 @@ Product table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -89,3 +89,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1000-1099/1070.Product Sales Analysis III/README.md b/solution/1000-1099/1070.Product Sales Analysis III/README.md index d4415cfc364d0..7879cb48a7cab 100644 --- a/solution/1000-1099/1070.Product Sales Analysis III/README.md +++ b/solution/1000-1099/1070.Product Sales Analysis III/README.md @@ -78,12 +78,10 @@ Product 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -102,6 +100,12 @@ WHERE ); ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below WITH @@ -120,3 +124,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1000-1099/1070.Product Sales Analysis III/README_EN.md b/solution/1000-1099/1070.Product Sales Analysis III/README_EN.md index 00ea082ef49ea..841def4b92085 100644 --- a/solution/1000-1099/1070.Product Sales Analysis III/README_EN.md +++ b/solution/1000-1099/1070.Product Sales Analysis III/README_EN.md @@ -77,9 +77,9 @@ Product table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -99,6 +99,12 @@ WHERE ); ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below WITH @@ -117,3 +123,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1000-1099/1071.Greatest Common Divisor of Strings/README.md b/solution/1000-1099/1071.Greatest Common Divisor of Strings/README.md index caa79198820e9..1c726470875a8 100644 --- a/solution/1000-1099/1071.Greatest Common Divisor of Strings/README.md +++ b/solution/1000-1099/1071.Greatest Common Divisor of Strings/README.md @@ -44,14 +44,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str: @@ -68,19 +64,6 @@ class Solution: return '' ``` -```python -class Solution: - def gcdOfStrings(self, str1: str, str2: str) -> str: - if str1 + str2 != str2 + str1: - return '' - n = gcd(len(str1), len(str2)) - return str1[:n] -``` - -### **Java** - - - ```java class Solution { public String gcdOfStrings(String str1, String str2) { @@ -97,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +91,6 @@ public: }; ``` -### **Go** - ```go func gcdOfStrings(str1 string, str2 string) string { if str1+str2 != str2+str1 { @@ -129,8 +108,6 @@ func gcd(a, b int) int { } ``` -### **Rust** - ```rust impl Solution { pub fn gcd_of_strings(str1: String, str2: String) -> String { @@ -150,10 +127,21 @@ impl Solution { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def gcdOfStrings(self, str1: str, str2: str) -> str: + if str1 + str2 != str2 + str1: + return '' + n = gcd(len(str1), len(str2)) + return str1[:n] ``` + + diff --git a/solution/1000-1099/1071.Greatest Common Divisor of Strings/README_EN.md b/solution/1000-1099/1071.Greatest Common Divisor of Strings/README_EN.md index 7b7e4b54ce401..8a9cc3f152b14 100644 --- a/solution/1000-1099/1071.Greatest Common Divisor of Strings/README_EN.md +++ b/solution/1000-1099/1071.Greatest Common Divisor of Strings/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,17 +60,6 @@ class Solution: return '' ``` -```python -class Solution: - def gcdOfStrings(self, str1: str, str2: str) -> str: - if str1 + str2 != str2 + str1: - return '' - n = gcd(len(str1), len(str2)) - return str1[:n] -``` - -### **Java** - ```java class Solution { public String gcdOfStrings(String str1, String str2) { @@ -87,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +87,6 @@ public: }; ``` -### **Go** - ```go func gcdOfStrings(str1 string, str2 string) string { if str1+str2 != str2+str1 { @@ -119,8 +104,6 @@ func gcd(a, b int) int { } ``` -### **Rust** - ```rust impl Solution { pub fn gcd_of_strings(str1: String, str2: String) -> String { @@ -140,10 +123,21 @@ impl Solution { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def gcdOfStrings(self, str1: str, str2: str) -> str: + if str1 + str2 != str2 + str1: + return '' + n = gcd(len(str1), len(str2)) + return str1[:n] ``` + + diff --git a/solution/1000-1099/1072.Flip Columns For Maximum Number of Equal Rows/README.md b/solution/1000-1099/1072.Flip Columns For Maximum Number of Equal Rows/README.md index bf7a089281d59..d31c7802ffa4d 100644 --- a/solution/1000-1099/1072.Flip Columns For Maximum Number of Equal Rows/README.md +++ b/solution/1000-1099/1072.Flip Columns For Maximum Number of Equal Rows/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们观察发现,如果矩阵中的两行满足以下条件之一,则它们可以通过翻转某些列的方式得到相等的行: @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int: @@ -93,10 +87,6 @@ class Solution: return max(cnt.values()) ``` -### **Java** - - - ```java class Solution { public int maxEqualRowsAfterFlips(int[][] matrix) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func maxEqualRowsAfterFlips(matrix [][]int) (ans int) { cnt := map[string]int{} @@ -155,8 +141,6 @@ func maxEqualRowsAfterFlips(matrix [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function maxEqualRowsAfterFlips(matrix: number[][]): number { const cnt = new Map(); @@ -175,10 +159,6 @@ function maxEqualRowsAfterFlips(matrix: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1072.Flip Columns For Maximum Number of Equal Rows/README_EN.md b/solution/1000-1099/1072.Flip Columns For Maximum Number of Equal Rows/README_EN.md index 3ab78ff3f57b5..0cb4f40d1bf5b 100644 --- a/solution/1000-1099/1072.Flip Columns For Maximum Number of Equal Rows/README_EN.md +++ b/solution/1000-1099/1072.Flip Columns For Maximum Number of Equal Rows/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return max(cnt.values()) ``` -### **Java** - ```java class Solution { public int maxEqualRowsAfterFlips(int[][] matrix) { @@ -80,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +96,6 @@ public: }; ``` -### **Go** - ```go func maxEqualRowsAfterFlips(matrix [][]int) (ans int) { cnt := map[string]int{} @@ -121,8 +115,6 @@ func maxEqualRowsAfterFlips(matrix [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function maxEqualRowsAfterFlips(matrix: number[][]): number { const cnt = new Map(); @@ -141,10 +133,6 @@ function maxEqualRowsAfterFlips(matrix: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1073.Adding Two Negabinary Numbers/README.md b/solution/1000-1099/1073.Adding Two Negabinary Numbers/README.md index a776e4f7fa84a..4c995acab3cb1 100644 --- a/solution/1000-1099/1073.Adding Two Negabinary Numbers/README.md +++ b/solution/1000-1099/1073.Adding Two Negabinary Numbers/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们遍历两个数组,从最低位开始,记两个数组当前位的数字为 $a$ 和 $b$,进位为 $c$,三个数相加的结果为 $x$。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]: @@ -101,10 +95,6 @@ class Solution: return ans[::-1] ``` -### **Java** - - - ```java class Solution { public int[] addNegabinary(int[] arr1, int[] arr2) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +152,6 @@ public: }; ``` -### **Go** - ```go func addNegabinary(arr1 []int, arr2 []int) (ans []int) { i, j := len(arr1)-1, len(arr2)-1 @@ -197,8 +183,6 @@ func addNegabinary(arr1 []int, arr2 []int) (ans []int) { } ``` -### **TypeScript** - ```ts function addNegabinary(arr1: number[], arr2: number[]): number[] { let i = arr1.length - 1, @@ -225,8 +209,6 @@ function addNegabinary(arr1: number[], arr2: number[]): number[] { } ``` -### **C#** - ```cs public class Solution { public int[] AddNegabinary(int[] arr1, int[] arr2) { @@ -255,10 +237,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1073.Adding Two Negabinary Numbers/README_EN.md b/solution/1000-1099/1073.Adding Two Negabinary Numbers/README_EN.md index e046c058b549b..d6c48743b794c 100644 --- a/solution/1000-1099/1073.Adding Two Negabinary Numbers/README_EN.md +++ b/solution/1000-1099/1073.Adding Two Negabinary Numbers/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return ans[::-1] ``` -### **Java** - ```java class Solution { public int[] addNegabinary(int[] arr1, int[] arr2) { @@ -102,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +129,6 @@ public: }; ``` -### **Go** - ```go func addNegabinary(arr1 []int, arr2 []int) (ans []int) { i, j := len(arr1)-1, len(arr2)-1 @@ -166,8 +160,6 @@ func addNegabinary(arr1 []int, arr2 []int) (ans []int) { } ``` -### **TypeScript** - ```ts function addNegabinary(arr1: number[], arr2: number[]): number[] { let i = arr1.length - 1, @@ -194,8 +186,6 @@ function addNegabinary(arr1: number[], arr2: number[]): number[] { } ``` -### **C#** - ```cs public class Solution { public int[] AddNegabinary(int[] arr1, int[] arr2) { @@ -224,10 +214,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1074.Number of Submatrices That Sum to Target/README.md b/solution/1000-1099/1074.Number of Submatrices That Sum to Target/README.md index 1b80364781571..c2127487673c6 100644 --- a/solution/1000-1099/1074.Number of Submatrices That Sum to Target/README.md +++ b/solution/1000-1099/1074.Number of Submatrices That Sum to Target/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:枚举上下边界 + 前缀和 + 哈希表** +### 方法一:枚举上下边界 + 前缀和 + 哈希表 我们可以枚举矩阵的上下边界 $i$ 和 $j$,每次算出当前上下边界内每列的元素和,记为数组 $col$,然后问题就转换为如何在数组 $col$ 中寻找和为目标值 $target$ 的子数组个数。我们累加这些子数组的个数,就是题目要求的答案。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int: @@ -99,10 +93,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numSubmatrixSumTarget(int[][] matrix, int target) { @@ -134,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go func numSubmatrixSumTarget(matrix [][]int, target int) (ans int) { m, n := len(matrix), len(matrix[0]) @@ -200,8 +186,6 @@ func f(nums []int, target int) (cnt int) { } ``` -### **TypeScript** - ```ts function numSubmatrixSumTarget(matrix: number[][], target: number): number { const m = matrix.length; @@ -235,10 +219,6 @@ function f(nums: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1074.Number of Submatrices That Sum to Target/README_EN.md b/solution/1000-1099/1074.Number of Submatrices That Sum to Target/README_EN.md index 6bd4ae8402f94..685be665cf85d 100644 --- a/solution/1000-1099/1074.Number of Submatrices That Sum to Target/README_EN.md +++ b/solution/1000-1099/1074.Number of Submatrices That Sum to Target/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numSubmatrixSumTarget(int[][] matrix, int target) { @@ -107,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +138,6 @@ public: }; ``` -### **Go** - ```go func numSubmatrixSumTarget(matrix [][]int, target int) (ans int) { m, n := len(matrix), len(matrix[0]) @@ -173,8 +167,6 @@ func f(nums []int, target int) (cnt int) { } ``` -### **TypeScript** - ```ts function numSubmatrixSumTarget(matrix: number[][], target: number): number { const m = matrix.length; @@ -208,10 +200,6 @@ function f(nums: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1075.Project Employees I/README.md b/solution/1000-1099/1075.Project Employees I/README.md index 9c75a27f9f432..485a5680b9647 100644 --- a/solution/1000-1099/1075.Project Employees I/README.md +++ b/solution/1000-1099/1075.Project Employees I/README.md @@ -72,16 +72,12 @@ Result 表: ## 解法 - - -**方法一:内连接 + `GROUP BY` 分组** +### 方法一:内连接 + `GROUP BY` 分组 我们可以通过内连接将两张表连接起来,然后通过 `GROUP BY` 分组,最后使用 `AVG` 函数求工作年限的平均值。 -### **SQL** - ```sql # Write your MySQL query statement SELECT project_id, ROUND(AVG(experience_years), 2) AS average_years @@ -92,3 +88,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1000-1099/1075.Project Employees I/README_EN.md b/solution/1000-1099/1075.Project Employees I/README_EN.md index cd179cb4a6455..5ec3a4008b595 100644 --- a/solution/1000-1099/1075.Project Employees I/README_EN.md +++ b/solution/1000-1099/1075.Project Employees I/README_EN.md @@ -78,9 +78,9 @@ Employee table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement @@ -92,3 +92,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1000-1099/1076.Project Employees II/README.md b/solution/1000-1099/1076.Project Employees II/README.md index 33045f0bb20d5..4fd5cbb83847f 100644 --- a/solution/1000-1099/1076.Project Employees II/README.md +++ b/solution/1000-1099/1076.Project Employees II/README.md @@ -77,12 +77,10 @@ Employee table: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT project_id @@ -96,6 +94,12 @@ HAVING ); ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below WITH @@ -112,3 +116,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1000-1099/1076.Project Employees II/README_EN.md b/solution/1000-1099/1076.Project Employees II/README_EN.md index 9a94746993527..97ac41a22f99a 100644 --- a/solution/1000-1099/1076.Project Employees II/README_EN.md +++ b/solution/1000-1099/1076.Project Employees II/README_EN.md @@ -77,9 +77,9 @@ Employee table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -94,6 +94,12 @@ HAVING ); ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below WITH @@ -110,3 +116,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1000-1099/1077.Project Employees III/README.md b/solution/1000-1099/1077.Project Employees III/README.md index 1dfeae3400ca8..c068bfa1de3c0 100644 --- a/solution/1000-1099/1077.Project Employees III/README.md +++ b/solution/1000-1099/1077.Project Employees III/README.md @@ -80,16 +80,12 @@ Employee 表: ## 解法 - - -**方法一:内连接 + 窗口函数** +### 方法一:内连接 + 窗口函数 我们先将 `Project` 表和 `Employee` 表进行内连接,然后使用窗口函数 `rank()` 对 `Project` 表进行分组,按照 `experience_years` 降序排列,最后取出每个项目中经验最丰富的雇员。 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -110,3 +106,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1000-1099/1077.Project Employees III/README_EN.md b/solution/1000-1099/1077.Project Employees III/README_EN.md index c7094cff98efa..181f4762e736f 100644 --- a/solution/1000-1099/1077.Project Employees III/README_EN.md +++ b/solution/1000-1099/1077.Project Employees III/README_EN.md @@ -79,14 +79,12 @@ Employee table: ## Solutions -**Solution 1: Inner Join + Window Function** +### Solution 1: Inner Join + Window Function We can first perform an inner join between the `Project` table and the `Employee` table, and then use the window function `rank()` to group the `Project` table, sort it in descending order by `experience_years`, and finally select the most experienced employee for each project. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -107,3 +105,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1000-1099/1078.Occurrences After Bigram/README.md b/solution/1000-1099/1078.Occurrences After Bigram/README.md index 41f8e71b40103..b4e2e61f78435 100644 --- a/solution/1000-1099/1078.Occurrences After Bigram/README.md +++ b/solution/1000-1099/1078.Occurrences After Bigram/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:字符串分割** +### 方法一:字符串分割 我们可以将字符串 $text$ 按照空格分割成字符串数组 $words$,然后遍历 $words$,如果 $words[i]$ 和 $words[i+1]$ 分别等于 $first$ 和 $second$,那么就将 $words[i+2]$ 添加到答案中。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]: @@ -68,10 +62,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +100,6 @@ public: }; ``` -### **Go** - ```go func findOcurrences(text string, first string, second string) (ans []string) { words := strings.Split(text, " ") @@ -127,8 +113,6 @@ func findOcurrences(text string, first string, second string) (ans []string) { } ``` -### **TypeScript** - ```ts function findOcurrences(text: string, first: string, second: string): string[] { const words = text.split(' '); @@ -143,10 +127,6 @@ function findOcurrences(text: string, first: string, second: string): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1078.Occurrences After Bigram/README_EN.md b/solution/1000-1099/1078.Occurrences After Bigram/README_EN.md index 5cb1d15a363d4..d13a51fd5b2c0 100644 --- a/solution/1000-1099/1078.Occurrences After Bigram/README_EN.md +++ b/solution/1000-1099/1078.Occurrences After Bigram/README_EN.md @@ -29,9 +29,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -45,8 +45,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { @@ -63,8 +61,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +83,6 @@ public: }; ``` -### **Go** - ```go func findOcurrences(text string, first string, second string) (ans []string) { words := strings.Split(text, " ") @@ -102,8 +96,6 @@ func findOcurrences(text string, first string, second string) (ans []string) { } ``` -### **TypeScript** - ```ts function findOcurrences(text: string, first: string, second: string): string[] { const words = text.split(' '); @@ -118,10 +110,6 @@ function findOcurrences(text: string, first: string, second: string): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1079.Letter Tile Possibilities/README.md b/solution/1000-1099/1079.Letter Tile Possibilities/README.md index f8a774ebb5a0f..1f5f233274694 100644 --- a/solution/1000-1099/1079.Letter Tile Possibilities/README.md +++ b/solution/1000-1099/1079.Letter Tile Possibilities/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:计数 + 回溯** +### 方法一:计数 + 回溯 我们先用一个哈希表或数组 $cnt$ 统计每个字母出现的次数。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def numTilePossibilities(self, tiles: str) -> int: @@ -79,10 +73,6 @@ class Solution: return dfs(cnt) ``` -### **Java** - - - ```java class Solution { public int numTilePossibilities(String tiles) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func numTilePossibilities(tiles string) int { cnt := [26]int{} @@ -159,8 +145,6 @@ func numTilePossibilities(tiles string) int { } ``` -### **TypeScript** - ```ts function numTilePossibilities(tiles: string): number { const cnt: number[] = new Array(26).fill(0); @@ -183,10 +167,6 @@ function numTilePossibilities(tiles: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1079.Letter Tile Possibilities/README_EN.md b/solution/1000-1099/1079.Letter Tile Possibilities/README_EN.md index 7f0eb03d94a07..3d919e11ac77f 100644 --- a/solution/1000-1099/1079.Letter Tile Possibilities/README_EN.md +++ b/solution/1000-1099/1079.Letter Tile Possibilities/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return dfs(cnt) ``` -### **Java** - ```java class Solution { public int numTilePossibilities(String tiles) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +112,6 @@ public: }; ``` -### **Go** - ```go func numTilePossibilities(tiles string) int { cnt := [26]int{} @@ -140,8 +134,6 @@ func numTilePossibilities(tiles string) int { } ``` -### **TypeScript** - ```ts function numTilePossibilities(tiles: string): number { const cnt: number[] = new Array(26).fill(0); @@ -164,10 +156,6 @@ function numTilePossibilities(tiles: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/README.md b/solution/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/README.md index c037f8c8bffa5..2f918857b44b3 100644 --- a/solution/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/README.md +++ b/solution/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们递归遍历整棵树,对于当前遍历到的节点 $root$: @@ -67,10 +65,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -92,10 +86,6 @@ class Solution: return None if root.left is None and root.right is None else root ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -159,8 +147,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -193,8 +179,6 @@ func sufficientSubset(root *TreeNode, limit int) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -224,8 +208,6 @@ function sufficientSubset(root: TreeNode | null, limit: number): TreeNode | null } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -254,10 +236,6 @@ var sufficientSubset = function (root, limit) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/README_EN.md b/solution/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/README_EN.md index e384346323bd4..c330683e18564 100644 --- a/solution/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/README_EN.md +++ b/solution/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -68,8 +68,6 @@ class Solution: return None if root.left is None and root.right is None else root ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -102,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -133,8 +129,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -167,8 +161,6 @@ func sufficientSubset(root *TreeNode, limit int) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -198,8 +190,6 @@ function sufficientSubset(root: TreeNode | null, limit: number): TreeNode | null } ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -228,10 +218,6 @@ var sufficientSubset = function (root, limit) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/README.md b/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/README.md index 56f23fdb55acd..c679c942298b2 100644 --- a/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/README.md +++ b/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 我们用一个数组 $last$ 记录字符串 $s$ 每个字符最后一次出现的位置,用栈来保存结果字符串,用一个数组 $vis$ 或者一个整型变量 $mask$ 记录当前字符是否在栈中。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def smallestSubsequence(self, s: str) -> str: @@ -72,10 +66,6 @@ class Solution: return "".join(stk) ``` -### **Java** - - - ```java class Solution { public String smallestSubsequence(String text) { @@ -101,38 +91,6 @@ class Solution { } ``` -```java -class Solution { - public String smallestSubsequence(String s) { - int n = s.length(); - int[] last = new int[26]; - for (int i = 0; i < n; ++i) { - last[s.charAt(i) - 'a'] = i; - } - Deque stk = new ArrayDeque<>(); - int mask = 0; - for (int i = 0; i < n; ++i) { - char c = s.charAt(i); - if (((mask >> (c - 'a')) & 1) == 1) { - continue; - } - while (!stk.isEmpty() && stk.peek() > c && last[stk.peek() - 'a'] > i) { - mask ^= 1 << (stk.pop() - 'a'); - } - stk.push(c); - mask |= 1 << (c - 'a'); - } - StringBuilder ans = new StringBuilder(); - for (char c : stk) { - ans.append(c); - } - return ans.reverse().toString(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -161,8 +119,6 @@ public: }; ``` -### **Go** - ```go func smallestSubsequence(s string) string { last := make([]int, 26) @@ -186,8 +142,6 @@ func smallestSubsequence(s string) string { } ``` -### **TypeScript** - ```ts function smallestSubsequence(s: string): string { const f = (c: string): number => c.charCodeAt(0) - 'a'.charCodeAt(0); @@ -212,10 +166,42 @@ function smallestSubsequence(s: string): string { } ``` -### **...** + -``` +### 方法二 + + +```java +class Solution { + public String smallestSubsequence(String s) { + int n = s.length(); + int[] last = new int[26]; + for (int i = 0; i < n; ++i) { + last[s.charAt(i) - 'a'] = i; + } + Deque stk = new ArrayDeque<>(); + int mask = 0; + for (int i = 0; i < n; ++i) { + char c = s.charAt(i); + if (((mask >> (c - 'a')) & 1) == 1) { + continue; + } + while (!stk.isEmpty() && stk.peek() > c && last[stk.peek() - 'a'] > i) { + mask ^= 1 << (stk.pop() - 'a'); + } + stk.push(c); + mask |= 1 << (c - 'a'); + } + StringBuilder ans = new StringBuilder(); + for (char c : stk) { + ans.append(c); + } + return ans.reverse().toString(); + } +} ``` + + diff --git a/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/README_EN.md b/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/README_EN.md index 1ef9f88b1d0de..50daada1ebb04 100644 --- a/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/README_EN.md +++ b/solution/1000-1099/1081.Smallest Subsequence of Distinct Characters/README_EN.md @@ -34,12 +34,10 @@ ## Solutions -**Stack** +### Solution 1 -### **Python3** - ```python class Solution: def smallestSubsequence(self, s: str) -> str: @@ -56,8 +54,6 @@ class Solution: return "".join(stk) ``` -### **Java** - ```java class Solution { public String smallestSubsequence(String text) { @@ -83,38 +79,6 @@ class Solution { } ``` -```java -class Solution { - public String smallestSubsequence(String s) { - int n = s.length(); - int[] last = new int[26]; - for (int i = 0; i < n; ++i) { - last[s.charAt(i) - 'a'] = i; - } - Deque stk = new ArrayDeque<>(); - int mask = 0; - for (int i = 0; i < n; ++i) { - char c = s.charAt(i); - if (((mask >> (c - 'a')) & 1) == 1) { - continue; - } - while (!stk.isEmpty() && stk.peek() > c && last[stk.peek() - 'a'] > i) { - mask ^= 1 << (stk.pop() - 'a'); - } - stk.push(c); - mask |= 1 << (c - 'a'); - } - StringBuilder ans = new StringBuilder(); - for (char c : stk) { - ans.append(c); - } - return ans.reverse().toString(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -143,8 +107,6 @@ public: }; ``` -### **Go** - ```go func smallestSubsequence(s string) string { last := make([]int, 26) @@ -168,8 +130,6 @@ func smallestSubsequence(s string) string { } ``` -### **TypeScript** - ```ts function smallestSubsequence(s: string): string { const f = (c: string): number => c.charCodeAt(0) - 'a'.charCodeAt(0); @@ -194,10 +154,42 @@ function smallestSubsequence(s: string): string { } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + public String smallestSubsequence(String s) { + int n = s.length(); + int[] last = new int[26]; + for (int i = 0; i < n; ++i) { + last[s.charAt(i) - 'a'] = i; + } + Deque stk = new ArrayDeque<>(); + int mask = 0; + for (int i = 0; i < n; ++i) { + char c = s.charAt(i); + if (((mask >> (c - 'a')) & 1) == 1) { + continue; + } + while (!stk.isEmpty() && stk.peek() > c && last[stk.peek() - 'a'] > i) { + mask ^= 1 << (stk.pop() - 'a'); + } + stk.push(c); + mask |= 1 << (c - 'a'); + } + StringBuilder ans = new StringBuilder(); + for (char c : stk) { + ans.append(c); + } + return ans.reverse().toString(); + } +} ``` + + diff --git a/solution/1000-1099/1082.Sales Analysis I/README.md b/solution/1000-1099/1082.Sales Analysis I/README.md index 7bdb1c698fba2..551fb96dd2018 100644 --- a/solution/1000-1099/1082.Sales Analysis I/README.md +++ b/solution/1000-1099/1082.Sales Analysis I/README.md @@ -80,12 +80,10 @@ Product 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT seller_id @@ -99,6 +97,12 @@ HAVING ); ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below WITH @@ -116,3 +120,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1000-1099/1082.Sales Analysis I/README_EN.md b/solution/1000-1099/1082.Sales Analysis I/README_EN.md index 4252d408c2345..4618ba877fc03 100644 --- a/solution/1000-1099/1082.Sales Analysis I/README_EN.md +++ b/solution/1000-1099/1082.Sales Analysis I/README_EN.md @@ -78,9 +78,9 @@ Sales table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -95,6 +95,12 @@ HAVING ); ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below WITH @@ -112,3 +118,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1000-1099/1083.Sales Analysis II/README.md b/solution/1000-1099/1083.Sales Analysis II/README.md index d4cd15c379029..718d64f396554 100644 --- a/solution/1000-1099/1083.Sales Analysis II/README.md +++ b/solution/1000-1099/1083.Sales Analysis II/README.md @@ -83,16 +83,12 @@ id 为 1 的买家购买了一部 S8,但是却没有购买 iPhone,而 id 为 ## 解法 - - -**方法一:JOIN + GROUP BY + HAVING** +### 方法一:JOIN + GROUP BY + HAVING 我们先将 `Sales` 表和 `Product` 表连接起来,然后根据 `buyer_id` 分组,最后用 `HAVING` 子句筛选出购买了 S8 却没有购买 iPhone 的买家。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT buyer_id @@ -104,3 +100,5 @@ HAVING SUM(product_name = 'S8') > 0 AND SUM(product_name = 'iPhone') = 0; ``` + + diff --git a/solution/1000-1099/1083.Sales Analysis II/README_EN.md b/solution/1000-1099/1083.Sales Analysis II/README_EN.md index 619de6881529d..bd72b91c7b6ff 100644 --- a/solution/1000-1099/1083.Sales Analysis II/README_EN.md +++ b/solution/1000-1099/1083.Sales Analysis II/README_EN.md @@ -79,9 +79,9 @@ Sales table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -94,3 +94,5 @@ HAVING SUM(product_name = 'S8') > 0 AND SUM(product_name = 'iPhone') = 0; ``` + + diff --git a/solution/1000-1099/1084.Sales Analysis III/README.md b/solution/1000-1099/1084.Sales Analysis III/README.md index 60e1b4b611408..cd2ddbd442e55 100644 --- a/solution/1000-1099/1084.Sales Analysis III/README.md +++ b/solution/1000-1099/1084.Sales Analysis III/README.md @@ -83,16 +83,12 @@ id 为 3 的产品在 2019 年春季之后销售。 ## 解法 - - -**方法一:JOIN + GROUP BY + HAVING** +### 方法一:JOIN + GROUP BY + HAVING 我们可以通过 `JOIN` 将 `Sales` 表和 `Product` 表连接起来,然后通过 `GROUP BY` 和 `HAVING` 来筛选出符合条件的产品。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT product_id, product_name @@ -104,3 +100,5 @@ HAVING COUNT(1) = SUM(sale_date BETWEEN '2019-01-01' AND '2019-03-31'); ``` + + diff --git a/solution/1000-1099/1084.Sales Analysis III/README_EN.md b/solution/1000-1099/1084.Sales Analysis III/README_EN.md index 6a4e8f2173d6d..fa400f173edbd 100644 --- a/solution/1000-1099/1084.Sales Analysis III/README_EN.md +++ b/solution/1000-1099/1084.Sales Analysis III/README_EN.md @@ -81,9 +81,9 @@ We return only product 1 as it is the product that was only sold in the spring o ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -96,3 +96,5 @@ HAVING COUNT(1) = SUM(sale_date BETWEEN '2019-01-01' AND '2019-03-31'); ``` + + diff --git a/solution/1000-1099/1085.Sum of Digits in the Minimum Number/README.md b/solution/1000-1099/1085.Sum of Digits in the Minimum Number/README.md index 0aa95f6e2bd88..9aa922c585ae9 100644 --- a/solution/1000-1099/1085.Sum of Digits in the Minimum Number/README.md +++ b/solution/1000-1099/1085.Sum of Digits in the Minimum Number/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们先找到数组中的最小值,记为 $x$。然后计算 $x$ 的各个数位上的数字之和,记为 $s$。最后判断 $s$ 是否为奇数,若是则返回 $0$,否则返回 $1$。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def sumOfDigits(self, nums: List[int]) -> int: @@ -68,10 +62,6 @@ class Solution: return s & 1 ^ 1 ``` -### **Java** - - - ```java class Solution { public int sumOfDigits(int[] nums) { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +92,6 @@ public: }; ``` -### **Go** - ```go func sumOfDigits(nums []int) int { s := 0 @@ -116,10 +102,6 @@ func sumOfDigits(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1085.Sum of Digits in the Minimum Number/README_EN.md b/solution/1000-1099/1085.Sum of Digits in the Minimum Number/README_EN.md index 919aa333f3374..bfc4428cb4528 100644 --- a/solution/1000-1099/1085.Sum of Digits in the Minimum Number/README_EN.md +++ b/solution/1000-1099/1085.Sum of Digits in the Minimum Number/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -48,8 +48,6 @@ class Solution: return s & 1 ^ 1 ``` -### **Java** - ```java class Solution { public int sumOfDigits(int[] nums) { @@ -66,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -82,8 +78,6 @@ public: }; ``` -### **Go** - ```go func sumOfDigits(nums []int) int { s := 0 @@ -94,10 +88,6 @@ func sumOfDigits(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1086.High Five/README.md b/solution/1000-1099/1086.High Five/README.md index 5c38468a1c572..d32e3f5eff60b 100644 --- a/solution/1000-1099/1086.High Five/README.md +++ b/solution/1000-1099/1086.High Five/README.md @@ -45,9 +45,7 @@ ID = 2 的学生分数为 93、97、77、100 和 76 。前五科的平均分 (10 ## 解法 - - -**方法一:排序** +### 方法一:排序 我们先用一个哈希表或数组 $d$ 记录每个学生的分数列表,然后从小到大遍历学生的编号,对于每个学生,我们将他的分数列表排序,然后取最高的五个分数求平均值即可。 @@ -55,10 +53,6 @@ ID = 2 的学生分数为 93、97、77、100 和 76 。前五科的平均分 (10 -### **Python3** - - - ```python class Solution: def highFive(self, items: List[List[int]]) -> List[List[int]]: @@ -75,10 +69,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] highFive(int[][] items) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func highFive(items [][]int) (ans [][]int) { d := make([][]int, 1001) @@ -169,8 +155,6 @@ func highFive(items [][]int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function highFive(items: number[][]): number[][] { const d: number[][] = Array(1001) @@ -191,10 +175,6 @@ function highFive(items: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1086.High Five/README_EN.md b/solution/1000-1099/1086.High Five/README_EN.md index 4f9f5ffe97506..40e7af36bb6fe 100644 --- a/solution/1000-1099/1086.High Five/README_EN.md +++ b/solution/1000-1099/1086.High Five/README_EN.md @@ -41,9 +41,9 @@ The student with ID = 2 got scores 93, 97, 77, 100, and 76. Their top five avera ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,38 +61,46 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] highFive(int[][] items) { - List[] d = new List[1001]; - Arrays.setAll(d, k -> new ArrayList<>()); - for (var item : items) { - int i = item[0], x = item[1]; - d[i].add(x); - } - for (var xs : d) { - xs.sort((a, b) -> b - a); + int size = 0; + PriorityQueue[] s = new PriorityQueue[101]; + int n = 5; + for (int[] item : items) { + int i = item[0], score = item[1]; + if (s[i] == null) { + ++size; + s[i] = new PriorityQueue<>(n); + } + s[i].offer(score); + if (s[i].size() > n) { + s[i].poll(); + } } - List ans = new ArrayList<>(); - for (int i = 1; i <= 1000; ++i) { - var xs = d[i]; - if (!xs.isEmpty()) { - int s = 0; - for (int j = 0; j < 5; ++j) { - s += xs.get(j); - } - ans.add(new int[] {i, s / 5}); + int[][] res = new int[size][2]; + int j = 0; + for (int i = 0; i < 101; ++i) { + if (s[i] == null) { + continue; } + int avg = sum(s[i]) / n; + res[j][0] = i; + res[j++][1] = avg; } - return ans.toArray(new int[0][]); + return res; + } + + private int sum(PriorityQueue q) { + int s = 0; + while (!q.isEmpty()) { + s += q.poll(); + } + return s; } } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +126,6 @@ public: }; ``` -### **Go** - ```go func highFive(items [][]int) (ans [][]int) { d := make([][]int, 1001) @@ -141,8 +147,6 @@ func highFive(items [][]int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function highFive(items: number[][]): number[][] { const d: number[][] = Array(1001) @@ -163,10 +167,6 @@ function highFive(items: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1087.Brace Expansion/README.md b/solution/1000-1099/1087.Brace Expansion/README.md index e74ddca76fa83..10fba23f0442f 100644 --- a/solution/1000-1099/1087.Brace Expansion/README.md +++ b/solution/1000-1099/1087.Brace Expansion/README.md @@ -47,16 +47,10 @@ ## 解法 - - -先将字符串 s 进行 convert 转换,比如 `"{a,b}{z,x,y}"` 转换为 `[['a', 'b'], ['z', 'x', 'y']]`,然后利用 DFS 回溯获取每一个单词,放到 ans 中,最后对 ans 进行排序并返回即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def expand(self, s: str) -> List[str]: @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List ans; @@ -143,10 +133,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1087.Brace Expansion/README_EN.md b/solution/1000-1099/1087.Brace Expansion/README_EN.md index ec64282e76734..eb2a237322abc 100644 --- a/solution/1000-1099/1087.Brace Expansion/README_EN.md +++ b/solution/1000-1099/1087.Brace Expansion/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List ans; @@ -124,10 +122,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1088.Confusing Number II/README.md b/solution/1000-1099/1088.Confusing Number II/README.md index 42b9c06c6421c..792182daf9f93 100644 --- a/solution/1000-1099/1088.Confusing Number II/README.md +++ b/solution/1000-1099/1088.Confusing Number II/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:数位 DP** +### 方法一:数位 DP 我们先将数字 $n$ 转成字符串 $s$。 @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def confusingNumberII(self, n: int) -> int: @@ -110,10 +104,6 @@ class Solution: return dfs(0, True, 0) ``` -### **Java** - - - ```java class Solution { private final int[] d = {0, 1, -1, -1, -1, -1, 9, -1, 8, 6}; @@ -149,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -183,8 +171,6 @@ public: }; ``` -### **Go** - ```go func confusingNumberII(n int) int { d := [10]int{0, 1, -1, -1, -1, -1, 9, -1, 8, 6} @@ -220,8 +206,6 @@ func confusingNumberII(n int) int { } ``` -### **TypeScript** - ```ts function confusingNumberII(n: number): number { const s = n.toString(); @@ -251,10 +235,6 @@ function confusingNumberII(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1088.Confusing Number II/README_EN.md b/solution/1000-1099/1088.Confusing Number II/README_EN.md index 4b799ec5a3ae4..89b39d1eee8a7 100644 --- a/solution/1000-1099/1088.Confusing Number II/README_EN.md +++ b/solution/1000-1099/1088.Confusing Number II/README_EN.md @@ -53,9 +53,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,8 +82,6 @@ class Solution: return dfs(0, True, 0) ``` -### **Java** - ```java class Solution { private final int[] d = {0, 1, -1, -1, -1, -1, 9, -1, 8, 6}; @@ -119,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +149,6 @@ public: }; ``` -### **Go** - ```go func confusingNumberII(n int) int { d := [10]int{0, 1, -1, -1, -1, -1, 9, -1, 8, 6} @@ -190,8 +184,6 @@ func confusingNumberII(n int) int { } ``` -### **TypeScript** - ```ts function confusingNumberII(n: number): number { const s = n.toString(); @@ -221,10 +213,6 @@ function confusingNumberII(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1089.Duplicate Zeros/README.md b/solution/1000-1099/1089.Duplicate Zeros/README.md index 0b839c2f0ca08..a085bab478570 100644 --- a/solution/1000-1099/1089.Duplicate Zeros/README.md +++ b/solution/1000-1099/1089.Duplicate Zeros/README.md @@ -38,30 +38,15 @@ ## 解法 - - -由于是原地修改,所以不能直接将 0 的后一位直接修改为 0,这会丢失元素数据。 - -若选择插入,则会导致元素位置调整,时间复杂度偏高。 - -**方法一:模拟** +### 方法一:模拟 开辟一个等长数组,将 `arr` 复刻一份,再进行简单模拟即可。 - 时间复杂度:$O(n)$。 - 空间复杂度:$O(n)$。 -**方法二:双指针** - -- 时间复杂度:$O(n)$。 -- 空间复杂度:$O(1)$。 - -### **Python3** - - - ```python class Solution: def duplicateZeros(self, arr: List[int]) -> None: @@ -86,10 +71,6 @@ class Solution: i, j = i - 1, j - 1 ``` -### **Java** - - - ```java class Solution { public void duplicateZeros(int[] arr) { @@ -116,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +122,6 @@ public: }; ``` -### **Go** - ```go func duplicateZeros(arr []int) { n := len(arr) @@ -171,37 +148,6 @@ func duplicateZeros(arr []int) { } ``` -### **C** - -```c -void duplicateZeros(int* arr, int arrSize) { - int i = 0; - int j = 0; - while (j < arrSize) { - if (arr[i] == 0) { - j++; - } - i++; - j++; - } - i--; - j--; - while (i >= 0) { - if (arr[i] == 0) { - if (j < arrSize) { - arr[j] = arr[i]; - } - j--; - } - arr[j] = arr[i]; - i--; - j--; - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn duplicate_zeros(arr: &mut Vec) { @@ -230,10 +176,38 @@ impl Solution { } ``` -### **...** - -``` - +```c +void duplicateZeros(int* arr, int arrSize) { + int i = 0; + int j = 0; + while (j < arrSize) { + if (arr[i] == 0) { + j++; + } + i++; + j++; + } + i--; + j--; + while (i >= 0) { + if (arr[i] == 0) { + if (j < arrSize) { + arr[j] = arr[i]; + } + j--; + } + arr[j] = arr[i]; + i--; + j--; + } +} ``` + +### 方法二:双指针 + +- 时间复杂度:$O(n)$。 +- 空间复杂度:$O(1)$。 + + diff --git a/solution/1000-1099/1089.Duplicate Zeros/README_EN.md b/solution/1000-1099/1089.Duplicate Zeros/README_EN.md index 45546e656ee9c..a1ad4c2660907 100644 --- a/solution/1000-1099/1089.Duplicate Zeros/README_EN.md +++ b/solution/1000-1099/1089.Duplicate Zeros/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: i, j = i - 1, j - 1 ``` -### **Java** - ```java class Solution { public void duplicateZeros(int[] arr) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func duplicateZeros(arr []int) { n := len(arr) @@ -146,37 +140,6 @@ func duplicateZeros(arr []int) { } ``` -### **C** - -```c -void duplicateZeros(int* arr, int arrSize) { - int i = 0; - int j = 0; - while (j < arrSize) { - if (arr[i] == 0) { - j++; - } - i++; - j++; - } - i--; - j--; - while (i >= 0) { - if (arr[i] == 0) { - if (j < arrSize) { - arr[j] = arr[i]; - } - j--; - } - arr[j] = arr[i]; - i--; - j--; - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn duplicate_zeros(arr: &mut Vec) { @@ -205,10 +168,33 @@ impl Solution { } ``` -### **...** - -``` - +```c +void duplicateZeros(int* arr, int arrSize) { + int i = 0; + int j = 0; + while (j < arrSize) { + if (arr[i] == 0) { + j++; + } + i++; + j++; + } + i--; + j--; + while (i >= 0) { + if (arr[i] == 0) { + if (j < arrSize) { + arr[j] = arr[i]; + } + j--; + } + arr[j] = arr[i]; + i--; + j--; + } +} ``` + + diff --git a/solution/1000-1099/1090.Largest Values From Labels/README.md b/solution/1000-1099/1090.Largest Values From Labels/README.md index 9478a288443a3..44a0aac350d73 100644 --- a/solution/1000-1099/1090.Largest Values From Labels/README.md +++ b/solution/1000-1099/1090.Largest Values From Labels/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:贪心 + 排序 + 哈希表** +### 方法一:贪心 + 排序 + 哈希表 根据题目描述,我们需要从 $n$ 个元素的集合中选出一个子集,子集元素个数不超过 $numWanted$,且子集中最多有相同标签的 $useLimit$ 项,使得子集的值之和最大。因此,我们应该贪心地选择集合中值较大的元素,同时记录每个标签出现的次数,当某个标签出现的次数达到 $useLimit$ 时,我们就不能再选择该标签对应的元素了。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def largestValsFromLabels( @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int largestValsFromLabels(int[] values, int[] labels, int numWanted, int useLimit) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +136,6 @@ public: }; ``` -### **Go** - ```go func largestValsFromLabels(values []int, labels []int, numWanted int, useLimit int) (ans int) { n := len(values) @@ -171,8 +157,6 @@ func largestValsFromLabels(values []int, labels []int, numWanted int, useLimit i } ``` -### **TypeScript** - ```ts function largestValsFromLabels( values: number[], @@ -200,10 +184,6 @@ function largestValsFromLabels( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1090.Largest Values From Labels/README_EN.md b/solution/1000-1099/1090.Largest Values From Labels/README_EN.md index de247eada0daa..06a80f9498410 100644 --- a/solution/1000-1099/1090.Largest Values From Labels/README_EN.md +++ b/solution/1000-1099/1090.Largest Values From Labels/README_EN.md @@ -54,9 +54,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int largestValsFromLabels(int[] values, int[] labels, int numWanted, int useLimit) { @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +124,6 @@ public: }; ``` -### **Go** - ```go func largestValsFromLabels(values []int, labels []int, numWanted int, useLimit int) (ans int) { n := len(values) @@ -151,8 +145,6 @@ func largestValsFromLabels(values []int, labels []int, numWanted int, useLimit i } ``` -### **TypeScript** - ```ts function largestValsFromLabels( values: number[], @@ -180,10 +172,6 @@ function largestValsFromLabels( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1091.Shortest Path in Binary Matrix/README.md b/solution/1000-1099/1091.Shortest Path in Binary Matrix/README.md index f0f0c071cedda..4e0b899bfcd2b 100644 --- a/solution/1000-1099/1091.Shortest Path in Binary Matrix/README.md +++ b/solution/1000-1099/1091.Shortest Path in Binary Matrix/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 根据题目描述,一条畅通路径是从左上角单元格 $(0, 0)$ 到右下角单元格 $(n - 1, n - 1)$ 的路径,且路径上所有单元格的值都是 $0$。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: @@ -98,10 +92,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int shortestPathBinaryMatrix(int[][] grid) { @@ -134,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go func shortestPathBinaryMatrix(grid [][]int) int { if grid[0][0] == 1 { @@ -201,8 +187,6 @@ func shortestPathBinaryMatrix(grid [][]int) int { } ``` -### **TypeScript** - ```ts function shortestPathBinaryMatrix(grid: number[][]): number { if (grid[0][0]) { @@ -232,8 +216,6 @@ function shortestPathBinaryMatrix(grid: number[][]): number { } ``` -### **Rust** - ```rust use std::collections::VecDeque; impl Solution { @@ -270,10 +252,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1091.Shortest Path in Binary Matrix/README_EN.md b/solution/1000-1099/1091.Shortest Path in Binary Matrix/README_EN.md index fe134fcef982f..c64ccd721fbe1 100644 --- a/solution/1000-1099/1091.Shortest Path in Binary Matrix/README_EN.md +++ b/solution/1000-1099/1091.Shortest Path in Binary Matrix/README_EN.md @@ -49,12 +49,10 @@ ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: @@ -78,8 +76,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int shortestPathBinaryMatrix(int[][] grid) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +141,6 @@ public: }; ``` -### **Go** - ```go func shortestPathBinaryMatrix(grid [][]int) int { if grid[0][0] == 1 { @@ -179,8 +171,6 @@ func shortestPathBinaryMatrix(grid [][]int) int { } ``` -### **TypeScript** - ```ts function shortestPathBinaryMatrix(grid: number[][]): number { if (grid[0][0]) { @@ -210,8 +200,6 @@ function shortestPathBinaryMatrix(grid: number[][]): number { } ``` -### **Rust** - ```rust use std::collections::VecDeque; impl Solution { @@ -248,10 +236,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1092.Shortest Common Supersequence/README.md b/solution/1000-1099/1092.Shortest Common Supersequence/README.md index a0492f9bac1f6..eccefaa009830 100644 --- a/solution/1000-1099/1092.Shortest Common Supersequence/README.md +++ b/solution/1000-1099/1092.Shortest Common Supersequence/README.md @@ -41,9 +41,7 @@ str2 = "cab" 是 "cabac" 的一个子串,因为我们可以删去 "cabac" 末 ## 解法 - - -**方法一:动态规划 + 构造** +### 方法一:动态规划 + 构造 我们先用动态规划求出两个字符串的最长公共子序列,然后根据最长公共子序列构造出最短公共超序列。 @@ -85,10 +83,6 @@ ans: c a b a c -### **Python3** - - - ```python class Solution: def shortestCommonSupersequence(self, str1: str, str2: str) -> str: @@ -122,10 +116,6 @@ class Solution: return ''.join(ans[::-1]) ``` -### **Java** - - - ```java class Solution { public String shortestCommonSupersequence(String str1, String str2) { @@ -163,8 +153,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -201,8 +189,6 @@ public: }; ``` -### **Go** - ```go func shortestCommonSupersequence(str1 string, str2 string) string { m, n := len(str1), len(str2) @@ -248,8 +234,6 @@ func shortestCommonSupersequence(str1 string, str2 string) string { } ``` -### **TypeScript** - ```ts function shortestCommonSupersequence(str1: string, str2: string): string { const m = str1.length; @@ -287,10 +271,6 @@ function shortestCommonSupersequence(str1: string, str2: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1092.Shortest Common Supersequence/README_EN.md b/solution/1000-1099/1092.Shortest Common Supersequence/README_EN.md index 9cd21411e2328..90fcdb2c01eb7 100644 --- a/solution/1000-1099/1092.Shortest Common Supersequence/README_EN.md +++ b/solution/1000-1099/1092.Shortest Common Supersequence/README_EN.md @@ -37,9 +37,9 @@ The answer provided is the shortest such string that satisfies these properties. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return ''.join(ans[::-1]) ``` -### **Java** - ```java class Solution { public String shortestCommonSupersequence(String str1, String str2) { @@ -113,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +147,6 @@ public: }; ``` -### **Go** - ```go func shortestCommonSupersequence(str1 string, str2 string) string { m, n := len(str1), len(str2) @@ -198,8 +192,6 @@ func shortestCommonSupersequence(str1 string, str2 string) string { } ``` -### **TypeScript** - ```ts function shortestCommonSupersequence(str1: string, str2: string): string { const m = str1.length; @@ -237,10 +229,6 @@ function shortestCommonSupersequence(str1: string, str2: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1093.Statistics from a Large Sample/README.md b/solution/1000-1099/1093.Statistics from a Large Sample/README.md index ec93fa02349c5..79911c35be75d 100644 --- a/solution/1000-1099/1093.Statistics from a Large Sample/README.md +++ b/solution/1000-1099/1093.Statistics from a Large Sample/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们直接根据题目描述模拟即可,定义以下变量: @@ -93,10 +91,6 @@ -### **Python3** - - - ```python class Solution: def sampleStats(self, count: List[int]) -> List[float]: @@ -125,10 +119,6 @@ class Solution: return [mi, mx, s / cnt, median, mode] ``` -### **Java** - - - ```java class Solution { private int[] count; @@ -166,8 +156,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -200,8 +188,6 @@ public: }; ``` -### **Go** - ```go func sampleStats(count []int) []float64 { find := func(i int) int { @@ -235,8 +221,6 @@ func sampleStats(count []int) []float64 { } ``` -### **TypeScript** - ```ts function sampleStats(count: number[]): number[] { const find = (i: number): number => { @@ -267,10 +251,6 @@ function sampleStats(count: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1093.Statistics from a Large Sample/README_EN.md b/solution/1000-1099/1093.Statistics from a Large Sample/README_EN.md index ce4b62613d3bb..1829d4f3ff88f 100644 --- a/solution/1000-1099/1093.Statistics from a Large Sample/README_EN.md +++ b/solution/1000-1099/1093.Statistics from a Large Sample/README_EN.md @@ -60,9 +60,9 @@ The mode is 1 as it appears the most in the sample. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -92,8 +92,6 @@ class Solution: return [mi, mx, s / cnt, median, mode] ``` -### **Java** - ```java class Solution { private int[] count; @@ -131,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -165,8 +161,6 @@ public: }; ``` -### **Go** - ```go func sampleStats(count []int) []float64 { find := func(i int) int { @@ -200,8 +194,6 @@ func sampleStats(count []int) []float64 { } ``` -### **TypeScript** - ```ts function sampleStats(count: number[]): number[] { const find = (i: number): number => { @@ -232,10 +224,6 @@ function sampleStats(count: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1094.Car Pooling/README.md b/solution/1000-1099/1094.Car Pooling/README.md index 16eb7a31230e3..ffbef86a7b926 100644 --- a/solution/1000-1099/1094.Car Pooling/README.md +++ b/solution/1000-1099/1094.Car Pooling/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 我们可以利用差分数组的思想,将每个行程的乘客数加到起点,减去终点,最后我们只需要判断差分数组的前缀和是否都不大于车的最大载客量即可。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: @@ -67,10 +61,6 @@ class Solution: return all(s <= capacity for s in accumulate(d)) ``` -### **Java** - - - ```java class Solution { public boolean carPooling(int[][] trips, int capacity) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func carPooling(trips [][]int, capacity int) bool { d := [1001]int{} @@ -137,15 +123,8 @@ func carPooling(trips [][]int, capacity int) bool { } ``` -### **JavaScript** - -```js -/** - * @param {number[][]} trips - * @param {number} capacity - * @return {boolean} - */ -var carPooling = function (trips, capacity) { +```ts +function carPooling(trips: number[][], capacity: number): boolean { const mx = Math.max(...trips.map(([, , t]) => t)); const d = Array(mx + 1).fill(0); for (const [x, f, t] of trips) { @@ -160,13 +139,40 @@ var carPooling = function (trips, capacity) { } } return true; -}; +} ``` -### **TypeScript** +```rust +impl Solution { + pub fn car_pooling(trips: Vec>, capacity: i32) -> bool { + let mx = trips + .iter() + .map(|e| e[2]) + .max() + .unwrap_or(0) as usize; + let mut d = vec![0; mx + 1]; + for trip in &trips { + let (x, f, t) = (trip[0], trip[1] as usize, trip[2] as usize); + d[f] += x; + d[t] -= x; + } + d.iter() + .scan(0, |acc, &x| { + *acc += x; + Some(*acc) + }) + .all(|s| s <= capacity) + } +} +``` -```ts -function carPooling(trips: number[][], capacity: number): boolean { +```js +/** + * @param {number[][]} trips + * @param {number} capacity + * @return {boolean} + */ +var carPooling = function (trips, capacity) { const mx = Math.max(...trips.map(([, , t]) => t)); const d = Array(mx + 1).fill(0); for (const [x, f, t] of trips) { @@ -181,11 +187,9 @@ function carPooling(trips: number[][], capacity: number): boolean { } } return true; -} +}; ``` -### **C#** - ```cs public class Solution { public bool CarPooling(int[][] trips, int capacity) { @@ -208,36 +212,6 @@ public class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn car_pooling(trips: Vec>, capacity: i32) -> bool { - let mx = trips - .iter() - .map(|e| e[2]) - .max() - .unwrap_or(0) as usize; - let mut d = vec![0; mx + 1]; - for trip in &trips { - let (x, f, t) = (trip[0], trip[1] as usize, trip[2] as usize); - d[f] += x; - d[t] -= x; - } - d.iter() - .scan(0, |acc, &x| { - *acc += x; - Some(*acc) - }) - .all(|s| s <= capacity) - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1094.Car Pooling/README_EN.md b/solution/1000-1099/1094.Car Pooling/README_EN.md index b6ccc8d9e1604..28f09f1179b25 100644 --- a/solution/1000-1099/1094.Car Pooling/README_EN.md +++ b/solution/1000-1099/1094.Car Pooling/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Difference Array** +### Solution 1: Difference Array We can use the idea of a difference array, adding the number of passengers to the starting point of each trip and subtracting from the end point. Finally, we just need to check whether the prefix sum of the difference array does not exceed the maximum passenger capacity of the car. @@ -46,8 +46,6 @@ The time complexity is $O(n)$, and the space complexity is $O(M)$. Here, $n$ is -### **Python3** - ```python class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: @@ -59,8 +57,6 @@ class Solution: return all(s <= capacity for s in accumulate(d)) ``` -### **Java** - ```java class Solution { public boolean carPooling(int[][] trips, int capacity) { @@ -82,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +100,6 @@ public: }; ``` -### **Go** - ```go func carPooling(trips [][]int, capacity int) bool { d := [1001]int{} @@ -127,15 +119,8 @@ func carPooling(trips [][]int, capacity int) bool { } ``` -### **JavaScript** - -```js -/** - * @param {number[][]} trips - * @param {number} capacity - * @return {boolean} - */ -var carPooling = function (trips, capacity) { +```ts +function carPooling(trips: number[][], capacity: number): boolean { const mx = Math.max(...trips.map(([, , t]) => t)); const d = Array(mx + 1).fill(0); for (const [x, f, t] of trips) { @@ -150,13 +135,40 @@ var carPooling = function (trips, capacity) { } } return true; -}; +} ``` -### **TypeScript** +```rust +impl Solution { + pub fn car_pooling(trips: Vec>, capacity: i32) -> bool { + let mx = trips + .iter() + .map(|e| e[2]) + .max() + .unwrap_or(0) as usize; + let mut d = vec![0; mx + 1]; + for trip in &trips { + let (x, f, t) = (trip[0], trip[1] as usize, trip[2] as usize); + d[f] += x; + d[t] -= x; + } + d.iter() + .scan(0, |acc, &x| { + *acc += x; + Some(*acc) + }) + .all(|s| s <= capacity) + } +} +``` -```ts -function carPooling(trips: number[][], capacity: number): boolean { +```js +/** + * @param {number[][]} trips + * @param {number} capacity + * @return {boolean} + */ +var carPooling = function (trips, capacity) { const mx = Math.max(...trips.map(([, , t]) => t)); const d = Array(mx + 1).fill(0); for (const [x, f, t] of trips) { @@ -171,11 +183,9 @@ function carPooling(trips: number[][], capacity: number): boolean { } } return true; -} +}; ``` -### **C#** - ```cs public class Solution { public bool CarPooling(int[][] trips, int capacity) { @@ -198,36 +208,6 @@ public class Solution { } ``` -### **Rust** - -```rust -impl Solution { - pub fn car_pooling(trips: Vec>, capacity: i32) -> bool { - let mx = trips - .iter() - .map(|e| e[2]) - .max() - .unwrap_or(0) as usize; - let mut d = vec![0; mx + 1]; - for trip in &trips { - let (x, f, t) = (trip[0], trip[1] as usize, trip[2] as usize); - d[f] += x; - d[t] -= x; - } - d.iter() - .scan(0, |acc, &x| { - *acc += x; - Some(*acc) - }) - .all(|s| s <= capacity) - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1095.Find in Mountain Array/README.md b/solution/1000-1099/1095.Find in Mountain Array/README.md index 88a5822e42473..b15304ad705fb 100644 --- a/solution/1000-1099/1095.Find in Mountain Array/README.md +++ b/solution/1000-1099/1095.Find in Mountain Array/README.md @@ -72,9 +72,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们先通过二分查找,找到数组中的最大值所在的下标 $l$,那么数组就可以被分成两段,前半段是递增的,后半段是递减的。 @@ -84,10 +82,6 @@ -### **Python3** - - - ```python # """ # This is MountainArray's API interface. @@ -121,10 +115,6 @@ class Solution: return search(l + 1, n - 1, -1) if ans == -1 else ans ``` -### **Java** - - - ```java /** * // This is MountainArray's API interface. @@ -170,8 +160,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the MountainArray's API interface. @@ -213,60 +201,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn find_in_mountain_array(target: i32, mountain_arr: &MountainArray) -> i32 { - let n = mountain_arr.length(); - - // First find the maximum element in the array - let mut l = 0; - let mut r = n - 1; - - while l < r { - let mid = (l + r) >> 1; - if mountain_arr.get(mid) > mountain_arr.get(mid + 1) { - r = mid; - } else { - l = mid + 1; - } - } - - let left = Self::binary_search(mountain_arr, 0, l, 1, target); - - if left == -1 { - Self::binary_search(mountain_arr, l, n - 1, -1, target) - } else { - left - } - } - - #[allow(dead_code)] - fn binary_search(m: &MountainArray, mut l: i32, mut r: i32, k: i32, target: i32) -> i32 { - let n = m.length(); - - while l < r { - let mid = (l + r) >> 1; - if k * m.get(mid) >= k * target { - r = mid; - } else { - l = mid + 1; - } - } - - if m.get(l) == target { - l - } else { - -1 - } - } -} -``` - -### **Go** - ```go /** * // This is the MountainArray's API interface. @@ -311,8 +245,6 @@ func findInMountainArray(target int, mountainArr *MountainArray) int { } ``` -### **TypeScript** - ```ts /** * // This is the MountainArray's API interface. @@ -352,10 +284,56 @@ function findInMountainArray(target: number, mountainArr: MountainArray) { } ``` -### **...** +```rust +impl Solution { + #[allow(dead_code)] + pub fn find_in_mountain_array(target: i32, mountain_arr: &MountainArray) -> i32 { + let n = mountain_arr.length(); -``` + // First find the maximum element in the array + let mut l = 0; + let mut r = n - 1; + while l < r { + let mid = (l + r) >> 1; + if mountain_arr.get(mid) > mountain_arr.get(mid + 1) { + r = mid; + } else { + l = mid + 1; + } + } + + let left = Self::binary_search(mountain_arr, 0, l, 1, target); + + if left == -1 { + Self::binary_search(mountain_arr, l, n - 1, -1, target) + } else { + left + } + } + + #[allow(dead_code)] + fn binary_search(m: &MountainArray, mut l: i32, mut r: i32, k: i32, target: i32) -> i32 { + let n = m.length(); + + while l < r { + let mid = (l + r) >> 1; + if k * m.get(mid) >= k * target { + r = mid; + } else { + l = mid + 1; + } + } + + if m.get(l) == target { + l + } else { + -1 + } + } +} ``` + + diff --git a/solution/1000-1099/1095.Find in Mountain Array/README_EN.md b/solution/1000-1099/1095.Find in Mountain Array/README_EN.md index 932a5b6472b88..177d4f8e25bcc 100644 --- a/solution/1000-1099/1095.Find in Mountain Array/README_EN.md +++ b/solution/1000-1099/1095.Find in Mountain Array/README_EN.md @@ -56,9 +56,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # """ @@ -93,8 +93,6 @@ class Solution: return search(l + 1, n - 1, -1) if ans == -1 else ans ``` -### **Java** - ```java /** * // This is MountainArray's API interface. @@ -140,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the MountainArray's API interface. @@ -183,60 +179,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn find_in_mountain_array(target: i32, mountain_arr: &MountainArray) -> i32 { - let n = mountain_arr.length(); - - // First find the maximum element in the array - let mut l = 0; - let mut r = n - 1; - - while l < r { - let mid = (l + r) >> 1; - if mountain_arr.get(mid) > mountain_arr.get(mid + 1) { - r = mid; - } else { - l = mid + 1; - } - } - - let left = Self::binary_search(mountain_arr, 0, l, 1, target); - - if left == -1 { - Self::binary_search(mountain_arr, l, n - 1, -1, target) - } else { - left - } - } - - #[allow(dead_code)] - fn binary_search(m: &MountainArray, mut l: i32, mut r: i32, k: i32, target: i32) -> i32 { - let n = m.length(); - - while l < r { - let mid = (l + r) >> 1; - if k * m.get(mid) >= k * target { - r = mid; - } else { - l = mid + 1; - } - } - - if m.get(l) == target { - l - } else { - -1 - } - } -} -``` - -### **Go** - ```go /** * // This is the MountainArray's API interface. @@ -281,8 +223,6 @@ func findInMountainArray(target int, mountainArr *MountainArray) int { } ``` -### **TypeScript** - ```ts /** * // This is the MountainArray's API interface. @@ -322,10 +262,56 @@ function findInMountainArray(target: number, mountainArr: MountainArray) { } ``` -### **...** +```rust +impl Solution { + #[allow(dead_code)] + pub fn find_in_mountain_array(target: i32, mountain_arr: &MountainArray) -> i32 { + let n = mountain_arr.length(); -``` + // First find the maximum element in the array + let mut l = 0; + let mut r = n - 1; + + while l < r { + let mid = (l + r) >> 1; + if mountain_arr.get(mid) > mountain_arr.get(mid + 1) { + r = mid; + } else { + l = mid + 1; + } + } + + let left = Self::binary_search(mountain_arr, 0, l, 1, target); + + if left == -1 { + Self::binary_search(mountain_arr, l, n - 1, -1, target) + } else { + left + } + } + + #[allow(dead_code)] + fn binary_search(m: &MountainArray, mut l: i32, mut r: i32, k: i32, target: i32) -> i32 { + let n = m.length(); + + while l < r { + let mid = (l + r) >> 1; + if k * m.get(mid) >= k * target { + r = mid; + } else { + l = mid + 1; + } + } + if m.get(l) == target { + l + } else { + -1 + } + } +} ``` + + diff --git a/solution/1000-1099/1096.Brace Expansion II/README.md b/solution/1000-1099/1096.Brace Expansion II/README.md index bfcb3eaf0cd64..dd7fd132ca58e 100644 --- a/solution/1000-1099/1096.Brace Expansion II/README.md +++ b/solution/1000-1099/1096.Brace Expansion II/README.md @@ -69,9 +69,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们设计一个递归函数 $dfs(exp)$,用于处理表达式 $exp$,并将结果存入集合 $s$ 中。 @@ -85,10 +83,6 @@ -### **Python3** - - - ```python class Solution: def braceExpansionII(self, expression: str) -> List[str]: @@ -107,10 +101,6 @@ class Solution: return sorted(s) ``` -### **Java** - - - ```java class Solution { private TreeSet s = new TreeSet<>(); @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +155,6 @@ private: }; ``` -### **Go** - ```go func braceExpansionII(expression string) []string { s := map[string]struct{}{} @@ -195,8 +181,6 @@ func braceExpansionII(expression string) []string { } ``` -### **TypeScript** - ```ts function braceExpansionII(expression: string): string[] { const dfs = (exp: string) => { @@ -218,10 +202,6 @@ function braceExpansionII(expression: string): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1096.Brace Expansion II/README_EN.md b/solution/1000-1099/1096.Brace Expansion II/README_EN.md index 3aeff576a6ba4..6e689680c7bb7 100644 --- a/solution/1000-1099/1096.Brace Expansion II/README_EN.md +++ b/solution/1000-1099/1096.Brace Expansion II/README_EN.md @@ -66,9 +66,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -88,8 +88,6 @@ class Solution: return sorted(s) ``` -### **Java** - ```java class Solution { private TreeSet s = new TreeSet<>(); @@ -115,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +142,6 @@ private: }; ``` -### **Go** - ```go func braceExpansionII(expression string) []string { s := map[string]struct{}{} @@ -174,8 +168,6 @@ func braceExpansionII(expression string) []string { } ``` -### **TypeScript** - ```ts function braceExpansionII(expression: string): string[] { const dfs = (exp: string) => { @@ -197,10 +189,6 @@ function braceExpansionII(expression: string): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1097.Game Play Analysis V/README.md b/solution/1000-1099/1097.Game Play Analysis V/README.md index 3ffbf5e628de1..64b7a83f3b7b9 100644 --- a/solution/1000-1099/1097.Game Play Analysis V/README.md +++ b/solution/1000-1099/1097.Game Play Analysis V/README.md @@ -64,12 +64,10 @@ Activity 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -92,3 +90,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1000-1099/1097.Game Play Analysis V/README_EN.md b/solution/1000-1099/1097.Game Play Analysis V/README_EN.md index 00406d1ece260..2c38c97497671 100644 --- a/solution/1000-1099/1097.Game Play Analysis V/README_EN.md +++ b/solution/1000-1099/1097.Game Play Analysis V/README_EN.md @@ -61,9 +61,9 @@ Player 2 installed the game on 2017-06-25 but didn't log back in on 2017-06- ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -87,3 +87,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1000-1099/1098.Unpopular Books/README.md b/solution/1000-1099/1098.Unpopular Books/README.md index 971afbc3f4b4b..b3df04b8aeb47 100644 --- a/solution/1000-1099/1098.Unpopular Books/README.md +++ b/solution/1000-1099/1098.Unpopular Books/README.md @@ -82,12 +82,10 @@ Orders 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT book_id, name @@ -100,3 +98,5 @@ HAVING SUM(IF(dispatch_date >= '2018-06-23', quantity, 0)) < 10; ``` + + diff --git a/solution/1000-1099/1098.Unpopular Books/README_EN.md b/solution/1000-1099/1098.Unpopular Books/README_EN.md index e61f8dc371497..fecabb04e51ae 100644 --- a/solution/1000-1099/1098.Unpopular Books/README_EN.md +++ b/solution/1000-1099/1098.Unpopular Books/README_EN.md @@ -81,9 +81,9 @@ Orders table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -97,3 +97,5 @@ HAVING SUM(IF(dispatch_date >= '2018-06-23', quantity, 0)) < 10; ``` + + diff --git a/solution/1000-1099/1099.Two Sum Less Than K/README.md b/solution/1000-1099/1099.Two Sum Less Than K/README.md index 67423b32d6ce6..168fdf6de7329 100644 --- a/solution/1000-1099/1099.Two Sum Less Than K/README.md +++ b/solution/1000-1099/1099.Two Sum Less Than K/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 我们可以先对数组 $nums$ 进行排序,初始化答案为 $-1$。 @@ -51,22 +49,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组 $nums$ 的长度。 -**方法二:排序 + 双指针** - -与方法一类似,我们可以先对数组 $nums$ 进行排序,初始化答案为 $-1$。 - -接下来,我们使用双指针 $i$ 和 $j$ 分别指向数组的左右两端,每次判断 $s = nums[i] + nums[j]$ 是否小于 $k$,如果小于 $k$,那么我们就可以更新答案,即 $ans = \max(ans, s)$,并将 $i$ 右移一位,否则将 $j$ 左移一位。 - -枚举结束后,返回答案即可。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组 $nums$ 的长度。 - -### **Python3** - - - ```python class Solution: def twoSumLessThanK(self, nums: List[int], k: int) -> int: @@ -79,25 +63,6 @@ class Solution: return ans ``` -```python -class Solution: - def twoSumLessThanK(self, nums: List[int], k: int) -> int: - nums.sort() - i, j = 0, len(nums) - 1 - ans = -1 - while i < j: - if (s := nums[i] + nums[j]) < k: - ans = max(ans, s) - i += 1 - else: - j -= 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int twoSumLessThanK(int[] nums, int k) { @@ -127,6 +92,83 @@ class Solution { } ``` +```cpp +class Solution { +public: + int twoSumLessThanK(vector& nums, int k) { + sort(nums.begin(), nums.end()); + int ans = -1, n = nums.size(); + for (int i = 0; i < n; ++i) { + int j = lower_bound(nums.begin() + i + 1, nums.end(), k - nums[i]) - nums.begin() - 1; + if (i < j) { + ans = max(ans, nums[i] + nums[j]); + } + } + return ans; + } +}; +``` + +```go +func twoSumLessThanK(nums []int, k int) int { + sort.Ints(nums) + ans := -1 + for i, x := range nums { + j := sort.SearchInts(nums[i+1:], k-x) + i + if v := nums[i] + nums[j]; i < j && ans < v { + ans = v + } + } + return ans +} +``` + +```ts +function twoSumLessThanK(nums: number[], k: number): number { + nums.sort((a, b) => a - b); + let ans = -1; + for (let i = 0, j = nums.length - 1; i < j; ) { + const s = nums[i] + nums[j]; + if (s < k) { + ans = Math.max(ans, s); + ++i; + } else { + --j; + } + } + return ans; +} +``` + + + +### 方法二:排序 + 双指针 + +与方法一类似,我们可以先对数组 $nums$ 进行排序,初始化答案为 $-1$。 + +接下来,我们使用双指针 $i$ 和 $j$ 分别指向数组的左右两端,每次判断 $s = nums[i] + nums[j]$ 是否小于 $k$,如果小于 $k$,那么我们就可以更新答案,即 $ans = \max(ans, s)$,并将 $i$ 右移一位,否则将 $j$ 左移一位。 + +枚举结束后,返回答案即可。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组 $nums$ 的长度。 + + + +```python +class Solution: + def twoSumLessThanK(self, nums: List[int], k: int) -> int: + nums.sort() + i, j = 0, len(nums) - 1 + ans = -1 + while i < j: + if (s := nums[i] + nums[j]) < k: + ans = max(ans, s) + i += 1 + else: + j -= 1 + return ans +``` + ```java class Solution { public int twoSumLessThanK(int[] nums, int k) { @@ -146,25 +188,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int twoSumLessThanK(vector& nums, int k) { - sort(nums.begin(), nums.end()); - int ans = -1, n = nums.size(); - for (int i = 0; i < n; ++i) { - int j = lower_bound(nums.begin() + i + 1, nums.end(), k - nums[i]) - nums.begin() - 1; - if (i < j) { - ans = max(ans, nums[i] + nums[j]); - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -185,22 +208,6 @@ public: }; ``` -### **Go** - -```go -func twoSumLessThanK(nums []int, k int) int { - sort.Ints(nums) - ans := -1 - for i, x := range nums { - j := sort.SearchInts(nums[i+1:], k-x) + i - if v := nums[i] + nums[j]; i < j && ans < v { - ans = v - } - } - return ans -} -``` - ```go func twoSumLessThanK(nums []int, k int) int { sort.Ints(nums) @@ -217,29 +224,6 @@ func twoSumLessThanK(nums []int, k int) int { } ``` -### **TypeScript** - -```ts -function twoSumLessThanK(nums: number[], k: number): number { - nums.sort((a, b) => a - b); - let ans = -1; - for (let i = 0, j = nums.length - 1; i < j; ) { - const s = nums[i] + nums[j]; - if (s < k) { - ans = Math.max(ans, s); - ++i; - } else { - --j; - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1000-1099/1099.Two Sum Less Than K/README_EN.md b/solution/1000-1099/1099.Two Sum Less Than K/README_EN.md index e35acadba1762..bd2a6391a8390 100644 --- a/solution/1000-1099/1099.Two Sum Less Than K/README_EN.md +++ b/solution/1000-1099/1099.Two Sum Less Than K/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Sorting + Binary Search** +### Solution 1: Sorting + Binary Search We can first sort the array $nums$, and initialize the answer as $-1$. @@ -44,20 +44,8 @@ After the enumeration ends, return the answer. The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $nums$. -**Solution 2: Sorting + Two Pointers** - -Similar to Solution 1, we can first sort the array $nums$, and initialize the answer as $-1$. - -Next, we use two pointers $i$ and $j$ to point to the left and right ends of the array, respectively. Each time we judge whether $s = nums[i] + nums[j]$ is less than $k$. If it is less than $k$, then we can update the answer, i.e., $ans = \max(ans, s)$, and move $i$ one step to the right, otherwise move $j$ one step to the left. - -After the enumeration ends, return the answer. - -The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $nums$. - -### **Python3** - ```python class Solution: def twoSumLessThanK(self, nums: List[int], k: int) -> int: @@ -70,23 +58,6 @@ class Solution: return ans ``` -```python -class Solution: - def twoSumLessThanK(self, nums: List[int], k: int) -> int: - nums.sort() - i, j = 0, len(nums) - 1 - ans = -1 - while i < j: - if (s := nums[i] + nums[j]) < k: - ans = max(ans, s) - i += 1 - else: - j -= 1 - return ans -``` - -### **Java** - ```java class Solution { public int twoSumLessThanK(int[] nums, int k) { @@ -116,6 +87,83 @@ class Solution { } ``` +```cpp +class Solution { +public: + int twoSumLessThanK(vector& nums, int k) { + sort(nums.begin(), nums.end()); + int ans = -1, n = nums.size(); + for (int i = 0; i < n; ++i) { + int j = lower_bound(nums.begin() + i + 1, nums.end(), k - nums[i]) - nums.begin() - 1; + if (i < j) { + ans = max(ans, nums[i] + nums[j]); + } + } + return ans; + } +}; +``` + +```go +func twoSumLessThanK(nums []int, k int) int { + sort.Ints(nums) + ans := -1 + for i, x := range nums { + j := sort.SearchInts(nums[i+1:], k-x) + i + if v := nums[i] + nums[j]; i < j && ans < v { + ans = v + } + } + return ans +} +``` + +```ts +function twoSumLessThanK(nums: number[], k: number): number { + nums.sort((a, b) => a - b); + let ans = -1; + for (let i = 0, j = nums.length - 1; i < j; ) { + const s = nums[i] + nums[j]; + if (s < k) { + ans = Math.max(ans, s); + ++i; + } else { + --j; + } + } + return ans; +} +``` + + + +### Solution 2: Sorting + Two Pointers + +Similar to Solution 1, we can first sort the array $nums$, and initialize the answer as $-1$. + +Next, we use two pointers $i$ and $j$ to point to the left and right ends of the array, respectively. Each time we judge whether $s = nums[i] + nums[j]$ is less than $k$. If it is less than $k$, then we can update the answer, i.e., $ans = \max(ans, s)$, and move $i$ one step to the right, otherwise move $j$ one step to the left. + +After the enumeration ends, return the answer. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $nums$. + + + +```python +class Solution: + def twoSumLessThanK(self, nums: List[int], k: int) -> int: + nums.sort() + i, j = 0, len(nums) - 1 + ans = -1 + while i < j: + if (s := nums[i] + nums[j]) < k: + ans = max(ans, s) + i += 1 + else: + j -= 1 + return ans +``` + ```java class Solution { public int twoSumLessThanK(int[] nums, int k) { @@ -135,25 +183,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int twoSumLessThanK(vector& nums, int k) { - sort(nums.begin(), nums.end()); - int ans = -1, n = nums.size(); - for (int i = 0; i < n; ++i) { - int j = lower_bound(nums.begin() + i + 1, nums.end(), k - nums[i]) - nums.begin() - 1; - if (i < j) { - ans = max(ans, nums[i] + nums[j]); - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -174,22 +203,6 @@ public: }; ``` -### **Go** - -```go -func twoSumLessThanK(nums []int, k int) int { - sort.Ints(nums) - ans := -1 - for i, x := range nums { - j := sort.SearchInts(nums[i+1:], k-x) + i - if v := nums[i] + nums[j]; i < j && ans < v { - ans = v - } - } - return ans -} -``` - ```go func twoSumLessThanK(nums []int, k int) int { sort.Ints(nums) @@ -206,29 +219,6 @@ func twoSumLessThanK(nums []int, k int) int { } ``` -### **TypeScript** - -```ts -function twoSumLessThanK(nums: number[], k: number): number { - nums.sort((a, b) => a - b); - let ans = -1; - for (let i = 0, j = nums.length - 1; i < j; ) { - const s = nums[i] + nums[j]; - if (s < k) { - ans = Math.max(ans, s); - ++i; - } else { - --j; - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README.md b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README.md index 289f3108785fd..ff01f3a70bb42 100644 --- a/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README.md +++ b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:双指针 + 计数器** +### 方法一:双指针 + 计数器 我们观察发现,字符均为小写字母,也即最多有 $26$ 种不同的字符。因此,如果 $k \gt 26$ 或者 $k \gt n$,则无法找到任何长度为 $k$ 且不含重复字符的子串,直接返回 $0$ 即可。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def numKLenSubstrNoRepeats(self, s: str, k: int) -> int: @@ -74,27 +68,6 @@ class Solution: return ans ``` -```python -class Solution: - def numKLenSubstrNoRepeats(self, s: str, k: int) -> int: - n = len(s) - if k > n: - return 0 - cnt = Counter(s[:k]) - ans = int(len(cnt) == k) - for i in range(k, n): - cnt[s[i]] += 1 - cnt[s[i - k]] -= 1 - if cnt[s[i - k]] == 0: - cnt.pop(s[i - k]) - ans += len(cnt) == k - return ans -``` - -### **Java** - - - ```java class Solution { public int numKLenSubstrNoRepeats(String s, int k) { @@ -116,32 +89,6 @@ class Solution { } ``` -```java -class Solution { - public int numKLenSubstrNoRepeats(String s, int k) { - int n = s.length(); - if (k > n) { - return 0; - } - Map cnt = new HashMap<>(k); - for (int i = 0; i < k; ++i) { - cnt.merge(s.charAt(i), 1, Integer::sum); - } - int ans = cnt.size() == k ? 1 : 0; - for (int i = k; i < n; ++i) { - cnt.merge(s.charAt(i), 1, Integer::sum); - if (cnt.merge(s.charAt(i - k), -1, Integer::sum) == 0) { - cnt.remove(s.charAt(i - k)); - } - ans += cnt.size() == k ? 1 : 0; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -164,34 +111,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numKLenSubstrNoRepeats(string s, int k) { - int n = s.size(); - if (k > n) { - return 0; - } - unordered_map cnt; - for (int i = 0; i < k; ++i) { - cnt[s[i]]++; - } - int ans = cnt.size() == k ? 1 : 0; - for (int i = k; i < n; ++i) { - cnt[s[i]]++; - cnt[s[i - k]]--; - if (cnt[s[i - k]] == 0) { - cnt.erase(s[i - k]); - } - ans += cnt.size() == k ? 1 : 0; - } - return ans; - } -}; -``` - -### **Go** - ```go func numKLenSubstrNoRepeats(s string, k int) (ans int) { if k > len(s) || k > 26 { @@ -212,35 +131,6 @@ func numKLenSubstrNoRepeats(s string, k int) (ans int) { } ``` -```go -func numKLenSubstrNoRepeats(s string, k int) (ans int) { - n := len(s) - if k > n { - return 0 - } - cnt := map[byte]int{} - for i := 0; i < k; i++ { - cnt[s[i]]++ - } - if len(cnt) == k { - ans++ - } - for i := k; i < n; i++ { - cnt[s[i]]++ - cnt[s[i-k]]-- - if cnt[s[i-k]] == 0 { - delete(cnt, s[i-k]) - } - if len(cnt) == k { - ans++ - } - } - return -} -``` - -### **TypeScript** - ```ts function numKLenSubstrNoRepeats(s: string, k: number): number { const n = s.length; @@ -264,8 +154,6 @@ function numKLenSubstrNoRepeats(s: string, k: number): number { } ``` -### **PHP** - ```php class Solution { /** @@ -291,10 +179,106 @@ class Solution { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def numKLenSubstrNoRepeats(self, s: str, k: int) -> int: + n = len(s) + if k > n: + return 0 + cnt = Counter(s[:k]) + ans = int(len(cnt) == k) + for i in range(k, n): + cnt[s[i]] += 1 + cnt[s[i - k]] -= 1 + if cnt[s[i - k]] == 0: + cnt.pop(s[i - k]) + ans += len(cnt) == k + return ans ``` +```java +class Solution { + public int numKLenSubstrNoRepeats(String s, int k) { + int n = s.length(); + if (k > n) { + return 0; + } + Map cnt = new HashMap<>(k); + for (int i = 0; i < k; ++i) { + cnt.merge(s.charAt(i), 1, Integer::sum); + } + int ans = cnt.size() == k ? 1 : 0; + for (int i = k; i < n; ++i) { + cnt.merge(s.charAt(i), 1, Integer::sum); + if (cnt.merge(s.charAt(i - k), -1, Integer::sum) == 0) { + cnt.remove(s.charAt(i - k)); + } + ans += cnt.size() == k ? 1 : 0; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int numKLenSubstrNoRepeats(string s, int k) { + int n = s.size(); + if (k > n) { + return 0; + } + unordered_map cnt; + for (int i = 0; i < k; ++i) { + cnt[s[i]]++; + } + int ans = cnt.size() == k ? 1 : 0; + for (int i = k; i < n; ++i) { + cnt[s[i]]++; + cnt[s[i - k]]--; + if (cnt[s[i - k]] == 0) { + cnt.erase(s[i - k]); + } + ans += cnt.size() == k ? 1 : 0; + } + return ans; + } +}; +``` + +```go +func numKLenSubstrNoRepeats(s string, k int) (ans int) { + n := len(s) + if k > n { + return 0 + } + cnt := map[byte]int{} + for i := 0; i < k; i++ { + cnt[s[i]]++ + } + if len(cnt) == k { + ans++ + } + for i := k; i < n; i++ { + cnt[s[i]]++ + cnt[s[i-k]]-- + if cnt[s[i-k]] == 0 { + delete(cnt, s[i-k]) + } + if len(cnt) == k { + ans++ + } + } + return +} ``` + + diff --git a/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README_EN.md b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README_EN.md index 622f07e142c33..09303c5534977 100644 --- a/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README_EN.md +++ b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Two Pointers + Counter** +### Solution 1: Two Pointers + Counter We observe that all characters are lowercase letters, so there are at most $26$ different characters. Therefore, if $k > 26$ or $k > n$, it is impossible to find any substring of length $k$ without repeated characters, and we can directly return $0$. @@ -48,8 +48,6 @@ The time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is -### **Python3** - ```python class Solution: def numKLenSubstrNoRepeats(self, s: str, k: int) -> int: @@ -67,25 +65,6 @@ class Solution: return ans ``` -```python -class Solution: - def numKLenSubstrNoRepeats(self, s: str, k: int) -> int: - n = len(s) - if k > n: - return 0 - cnt = Counter(s[:k]) - ans = int(len(cnt) == k) - for i in range(k, n): - cnt[s[i]] += 1 - cnt[s[i - k]] -= 1 - if cnt[s[i - k]] == 0: - cnt.pop(s[i - k]) - ans += len(cnt) == k - return ans -``` - -### **Java** - ```java class Solution { public int numKLenSubstrNoRepeats(String s, int k) { @@ -107,32 +86,6 @@ class Solution { } ``` -```java -class Solution { - public int numKLenSubstrNoRepeats(String s, int k) { - int n = s.length(); - if (k > n) { - return 0; - } - Map cnt = new HashMap<>(k); - for (int i = 0; i < k; ++i) { - cnt.merge(s.charAt(i), 1, Integer::sum); - } - int ans = cnt.size() == k ? 1 : 0; - for (int i = k; i < n; ++i) { - cnt.merge(s.charAt(i), 1, Integer::sum); - if (cnt.merge(s.charAt(i - k), -1, Integer::sum) == 0) { - cnt.remove(s.charAt(i - k)); - } - ans += cnt.size() == k ? 1 : 0; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -155,34 +108,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numKLenSubstrNoRepeats(string s, int k) { - int n = s.size(); - if (k > n) { - return 0; - } - unordered_map cnt; - for (int i = 0; i < k; ++i) { - cnt[s[i]]++; - } - int ans = cnt.size() == k ? 1 : 0; - for (int i = k; i < n; ++i) { - cnt[s[i]]++; - cnt[s[i - k]]--; - if (cnt[s[i - k]] == 0) { - cnt.erase(s[i - k]); - } - ans += cnt.size() == k ? 1 : 0; - } - return ans; - } -}; -``` - -### **Go** - ```go func numKLenSubstrNoRepeats(s string, k int) (ans int) { if k > len(s) || k > 26 { @@ -203,35 +128,6 @@ func numKLenSubstrNoRepeats(s string, k int) (ans int) { } ``` -```go -func numKLenSubstrNoRepeats(s string, k int) (ans int) { - n := len(s) - if k > n { - return 0 - } - cnt := map[byte]int{} - for i := 0; i < k; i++ { - cnt[s[i]]++ - } - if len(cnt) == k { - ans++ - } - for i := k; i < n; i++ { - cnt[s[i]]++ - cnt[s[i-k]]-- - if cnt[s[i-k]] == 0 { - delete(cnt, s[i-k]) - } - if len(cnt) == k { - ans++ - } - } - return -} -``` - -### **TypeScript** - ```ts function numKLenSubstrNoRepeats(s: string, k: number): number { const n = s.length; @@ -255,8 +151,6 @@ function numKLenSubstrNoRepeats(s: string, k: number): number { } ``` -### **PHP** - ```php class Solution { /** @@ -282,10 +176,106 @@ class Solution { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def numKLenSubstrNoRepeats(self, s: str, k: int) -> int: + n = len(s) + if k > n: + return 0 + cnt = Counter(s[:k]) + ans = int(len(cnt) == k) + for i in range(k, n): + cnt[s[i]] += 1 + cnt[s[i - k]] -= 1 + if cnt[s[i - k]] == 0: + cnt.pop(s[i - k]) + ans += len(cnt) == k + return ans ``` +```java +class Solution { + public int numKLenSubstrNoRepeats(String s, int k) { + int n = s.length(); + if (k > n) { + return 0; + } + Map cnt = new HashMap<>(k); + for (int i = 0; i < k; ++i) { + cnt.merge(s.charAt(i), 1, Integer::sum); + } + int ans = cnt.size() == k ? 1 : 0; + for (int i = k; i < n; ++i) { + cnt.merge(s.charAt(i), 1, Integer::sum); + if (cnt.merge(s.charAt(i - k), -1, Integer::sum) == 0) { + cnt.remove(s.charAt(i - k)); + } + ans += cnt.size() == k ? 1 : 0; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int numKLenSubstrNoRepeats(string s, int k) { + int n = s.size(); + if (k > n) { + return 0; + } + unordered_map cnt; + for (int i = 0; i < k; ++i) { + cnt[s[i]]++; + } + int ans = cnt.size() == k ? 1 : 0; + for (int i = k; i < n; ++i) { + cnt[s[i]]++; + cnt[s[i - k]]--; + if (cnt[s[i - k]] == 0) { + cnt.erase(s[i - k]); + } + ans += cnt.size() == k ? 1 : 0; + } + return ans; + } +}; +``` + +```go +func numKLenSubstrNoRepeats(s string, k int) (ans int) { + n := len(s) + if k > n { + return 0 + } + cnt := map[byte]int{} + for i := 0; i < k; i++ { + cnt[s[i]]++ + } + if len(cnt) == k { + ans++ + } + for i := k; i < n; i++ { + cnt[s[i]]++ + cnt[s[i-k]]-- + if cnt[s[i-k]] == 0 { + delete(cnt, s[i-k]) + } + if len(cnt) == k { + ans++ + } + } + return +} ``` + + diff --git a/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README.md b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README.md index 6c55167068918..d8a8f04c13447 100644 --- a/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README.md +++ b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:排序 + 并查集** +### 方法一:排序 + 并查集 我们将所有的日志按照时间戳从小到大排序,然后遍历排序后的日志,利用并查集判断当前日志中的两个人是否已经是朋友,如果不是朋友,则将两个人合并成一个朋友圈,直到所有人都在一个朋友圈中,返回当前日志的时间戳。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def earliestAcq(self, logs: List[List[int]], n: int) -> int: @@ -87,6 +81,184 @@ class Solution: return -1 ``` +```java +class Solution { + private int[] p; + + public int earliestAcq(int[][] logs, int n) { + Arrays.sort(logs, (a, b) -> a[0] - b[0]); + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + for (int[] log : logs) { + int t = log[0], x = log[1], y = log[2]; + if (find(x) == find(y)) { + continue; + } + p[find(x)] = find(y); + if (--n == 1) { + return t; + } + } + return -1; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} +``` + +```cpp +class Solution { +public: + int earliestAcq(vector>& logs, int n) { + sort(logs.begin(), logs.end()); + vector p(n); + iota(p.begin(), p.end(), 0); + function find = [&](int x) { + return p[x] == x ? x : p[x] = find(p[x]); + }; + for (auto& log : logs) { + int x = find(log[1]); + int y = find(log[2]); + if (x != y) { + p[x] = y; + --n; + } + if (n == 1) { + return log[0]; + } + } + return -1; + } +}; +``` + +```go +func earliestAcq(logs [][]int, n int) int { + sort.Slice(logs, func(i, j int) bool { return logs[i][0] < logs[j][0] }) + p := make([]int, n) + for i := range p { + p[i] = i + } + var find func(int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + for _, log := range logs { + t, x, y := log[0], log[1], log[2] + if find(x) == find(y) { + continue + } + p[find(x)] = find(y) + n-- + if n == 1 { + return t + } + } + return -1 +} +``` + +```ts +function earliestAcq(logs: number[][], n: number): number { + const p: number[] = Array(n) + .fill(0) + .map((_, i) => i); + const find = (x: number): number => { + if (p[x] !== x) { + p[x] = find(p[x]); + } + return p[x]; + }; + logs.sort((a, b) => a[0] - b[0]); + for (const [t, x, y] of logs) { + const rx = find(x); + const ry = find(y); + if (rx !== ry) { + p[rx] = ry; + if (--n === 1) { + return t; + } + } + } + return -1; +} +``` + +```rust +struct UnionFind { + p: Vec, + size: Vec, +} + +impl UnionFind { + fn new(n: usize) -> Self { + let p: Vec = (0..n).collect(); + let size = vec![1; n]; + UnionFind { p, size } + } + + fn find(&mut self, x: usize) -> usize { + if self.p[x] != x { + self.p[x] = self.find(self.p[x]); + } + self.p[x] + } + + fn union(&mut self, a: usize, b: usize) -> bool { + let pa = self.find(a); + let pb = self.find(b); + if pa == pb { + false + } else if self.size[pa] > self.size[pb] { + self.p[pb] = pa; + self.size[pa] += self.size[pb]; + true + } else { + self.p[pa] = pb; + self.size[pb] += self.size[pa]; + true + } + } +} + +impl Solution { + pub fn earliest_acq(logs: Vec>, n: i32) -> i32 { + let mut logs = logs; + logs.sort_by(|a, b| a[0].cmp(&b[0])); + let mut uf = UnionFind::new(n as usize); + let mut n = n; + for log in logs { + let t = log[0]; + let x = log[1] as usize; + let y = log[2] as usize; + if uf.union(x, y) { + n -= 1; + if n == 1 { + return t; + } + } + } + -1 + } +} +``` + + + +### 方法二 + + + ```python class UnionFind: __slots__ = ('p', 'size') @@ -124,42 +296,6 @@ class Solution: return -1 ``` -### **Java** - - - -```java -class Solution { - private int[] p; - - public int earliestAcq(int[][] logs, int n) { - Arrays.sort(logs, (a, b) -> a[0] - b[0]); - p = new int[n]; - for (int i = 0; i < n; ++i) { - p[i] = i; - } - for (int[] log : logs) { - int t = log[0], x = log[1], y = log[2]; - if (find(x) == find(y)) { - continue; - } - p[find(x)] = find(y); - if (--n == 1) { - return t; - } - } - return -1; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } -} -``` - ```java class UnionFind { private int[] p; @@ -212,34 +348,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int earliestAcq(vector>& logs, int n) { - sort(logs.begin(), logs.end()); - vector p(n); - iota(p.begin(), p.end(), 0); - function find = [&](int x) { - return p[x] == x ? x : p[x] = find(p[x]); - }; - for (auto& log : logs) { - int x = find(log[1]); - int y = find(log[2]); - if (x != y) { - p[x] = y; - --n; - } - if (n == 1) { - return log[0]; - } - } - return -1; - } -}; -``` - ```cpp class UnionFind { public: @@ -291,37 +399,6 @@ public: }; ``` -### **Go** - -```go -func earliestAcq(logs [][]int, n int) int { - sort.Slice(logs, func(i, j int) bool { return logs[i][0] < logs[j][0] }) - p := make([]int, n) - for i := range p { - p[i] = i - } - var find func(int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - for _, log := range logs { - t, x, y := log[0], log[1], log[2] - if find(x) == find(y) { - continue - } - p[find(x)] = find(y) - n-- - if n == 1 { - return t - } - } - return -1 -} -``` - ```go type unionFind struct { p, size []int @@ -375,34 +452,6 @@ func earliestAcq(logs [][]int, n int) int { } ``` -### **TypeScript** - -```ts -function earliestAcq(logs: number[][], n: number): number { - const p: number[] = Array(n) - .fill(0) - .map((_, i) => i); - const find = (x: number): number => { - if (p[x] !== x) { - p[x] = find(p[x]); - } - return p[x]; - }; - logs.sort((a, b) => a[0] - b[0]); - for (const [t, x, y] of logs) { - const rx = find(x); - const ry = find(y); - if (rx !== ry) { - p[rx] = ry; - if (--n === 1) { - return t; - } - } - } - return -1; -} -``` - ```ts class UnionFind { private p: number[]; @@ -451,71 +500,6 @@ function earliestAcq(logs: number[][], n: number): number { } ``` -### **Rust** - -```rust -struct UnionFind { - p: Vec, - size: Vec, -} - -impl UnionFind { - fn new(n: usize) -> Self { - let p: Vec = (0..n).collect(); - let size = vec![1; n]; - UnionFind { p, size } - } - - fn find(&mut self, x: usize) -> usize { - if self.p[x] != x { - self.p[x] = self.find(self.p[x]); - } - self.p[x] - } - - fn union(&mut self, a: usize, b: usize) -> bool { - let pa = self.find(a); - let pb = self.find(b); - if pa == pb { - false - } else if self.size[pa] > self.size[pb] { - self.p[pb] = pa; - self.size[pa] += self.size[pb]; - true - } else { - self.p[pa] = pb; - self.size[pb] += self.size[pa]; - true - } - } -} - -impl Solution { - pub fn earliest_acq(logs: Vec>, n: i32) -> i32 { - let mut logs = logs; - logs.sort_by(|a, b| a[0].cmp(&b[0])); - let mut uf = UnionFind::new(n as usize); - let mut n = n; - for log in logs { - let t = log[0]; - let x = log[1] as usize; - let y = log[2] as usize; - if uf.union(x, y) { - n -= 1; - if n == 1 { - return t; - } - } - } - -1 - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README_EN.md b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README_EN.md index f97d0f24433cb..5d9db46f16c5d 100644 --- a/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README_EN.md +++ b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README_EN.md @@ -49,7 +49,7 @@ The sixth event occurs at timestamp = 20190301, and after 0 and 3 become friends ## Solutions -**Solution 1: Sorting + Union-Find** +### Solution 1: Sorting + Union-Find We sort all the logs in ascending order by timestamp, then traverse the sorted logs. Using a union-find set, we check whether the two people in the current log are already friends. If they are not friends, we merge them into one friend circle, until everyone is in one friend circle, then return the timestamp of the current log. @@ -59,8 +59,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def earliestAcq(self, logs: List[List[int]], n: int) -> int: @@ -80,6 +78,184 @@ class Solution: return -1 ``` +```java +class Solution { + private int[] p; + + public int earliestAcq(int[][] logs, int n) { + Arrays.sort(logs, (a, b) -> a[0] - b[0]); + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + for (int[] log : logs) { + int t = log[0], x = log[1], y = log[2]; + if (find(x) == find(y)) { + continue; + } + p[find(x)] = find(y); + if (--n == 1) { + return t; + } + } + return -1; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} +``` + +```cpp +class Solution { +public: + int earliestAcq(vector>& logs, int n) { + sort(logs.begin(), logs.end()); + vector p(n); + iota(p.begin(), p.end(), 0); + function find = [&](int x) { + return p[x] == x ? x : p[x] = find(p[x]); + }; + for (auto& log : logs) { + int x = find(log[1]); + int y = find(log[2]); + if (x != y) { + p[x] = y; + --n; + } + if (n == 1) { + return log[0]; + } + } + return -1; + } +}; +``` + +```go +func earliestAcq(logs [][]int, n int) int { + sort.Slice(logs, func(i, j int) bool { return logs[i][0] < logs[j][0] }) + p := make([]int, n) + for i := range p { + p[i] = i + } + var find func(int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + for _, log := range logs { + t, x, y := log[0], log[1], log[2] + if find(x) == find(y) { + continue + } + p[find(x)] = find(y) + n-- + if n == 1 { + return t + } + } + return -1 +} +``` + +```ts +function earliestAcq(logs: number[][], n: number): number { + const p: number[] = Array(n) + .fill(0) + .map((_, i) => i); + const find = (x: number): number => { + if (p[x] !== x) { + p[x] = find(p[x]); + } + return p[x]; + }; + logs.sort((a, b) => a[0] - b[0]); + for (const [t, x, y] of logs) { + const rx = find(x); + const ry = find(y); + if (rx !== ry) { + p[rx] = ry; + if (--n === 1) { + return t; + } + } + } + return -1; +} +``` + +```rust +struct UnionFind { + p: Vec, + size: Vec, +} + +impl UnionFind { + fn new(n: usize) -> Self { + let p: Vec = (0..n).collect(); + let size = vec![1; n]; + UnionFind { p, size } + } + + fn find(&mut self, x: usize) -> usize { + if self.p[x] != x { + self.p[x] = self.find(self.p[x]); + } + self.p[x] + } + + fn union(&mut self, a: usize, b: usize) -> bool { + let pa = self.find(a); + let pb = self.find(b); + if pa == pb { + false + } else if self.size[pa] > self.size[pb] { + self.p[pb] = pa; + self.size[pa] += self.size[pb]; + true + } else { + self.p[pa] = pb; + self.size[pb] += self.size[pa]; + true + } + } +} + +impl Solution { + pub fn earliest_acq(logs: Vec>, n: i32) -> i32 { + let mut logs = logs; + logs.sort_by(|a, b| a[0].cmp(&b[0])); + let mut uf = UnionFind::new(n as usize); + let mut n = n; + for log in logs { + let t = log[0]; + let x = log[1] as usize; + let y = log[2] as usize; + if uf.union(x, y) { + n -= 1; + if n == 1 { + return t; + } + } + } + -1 + } +} +``` + + + +### Solution 2 + + + ```python class UnionFind: __slots__ = ('p', 'size') @@ -117,40 +293,6 @@ class Solution: return -1 ``` -### **Java** - -```java -class Solution { - private int[] p; - - public int earliestAcq(int[][] logs, int n) { - Arrays.sort(logs, (a, b) -> a[0] - b[0]); - p = new int[n]; - for (int i = 0; i < n; ++i) { - p[i] = i; - } - for (int[] log : logs) { - int t = log[0], x = log[1], y = log[2]; - if (find(x) == find(y)) { - continue; - } - p[find(x)] = find(y); - if (--n == 1) { - return t; - } - } - return -1; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } -} -``` - ```java class UnionFind { private int[] p; @@ -203,34 +345,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int earliestAcq(vector>& logs, int n) { - sort(logs.begin(), logs.end()); - vector p(n); - iota(p.begin(), p.end(), 0); - function find = [&](int x) { - return p[x] == x ? x : p[x] = find(p[x]); - }; - for (auto& log : logs) { - int x = find(log[1]); - int y = find(log[2]); - if (x != y) { - p[x] = y; - --n; - } - if (n == 1) { - return log[0]; - } - } - return -1; - } -}; -``` - ```cpp class UnionFind { public: @@ -282,37 +396,6 @@ public: }; ``` -### **Go** - -```go -func earliestAcq(logs [][]int, n int) int { - sort.Slice(logs, func(i, j int) bool { return logs[i][0] < logs[j][0] }) - p := make([]int, n) - for i := range p { - p[i] = i - } - var find func(int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - for _, log := range logs { - t, x, y := log[0], log[1], log[2] - if find(x) == find(y) { - continue - } - p[find(x)] = find(y) - n-- - if n == 1 { - return t - } - } - return -1 -} -``` - ```go type unionFind struct { p, size []int @@ -366,34 +449,6 @@ func earliestAcq(logs [][]int, n int) int { } ``` -### **TypeScript** - -```ts -function earliestAcq(logs: number[][], n: number): number { - const p: number[] = Array(n) - .fill(0) - .map((_, i) => i); - const find = (x: number): number => { - if (p[x] !== x) { - p[x] = find(p[x]); - } - return p[x]; - }; - logs.sort((a, b) => a[0] - b[0]); - for (const [t, x, y] of logs) { - const rx = find(x); - const ry = find(y); - if (rx !== ry) { - p[rx] = ry; - if (--n === 1) { - return t; - } - } - } - return -1; -} -``` - ```ts class UnionFind { private p: number[]; @@ -442,71 +497,6 @@ function earliestAcq(logs: number[][], n: number): number { } ``` -### **Rust** - -```rust -struct UnionFind { - p: Vec, - size: Vec, -} - -impl UnionFind { - fn new(n: usize) -> Self { - let p: Vec = (0..n).collect(); - let size = vec![1; n]; - UnionFind { p, size } - } - - fn find(&mut self, x: usize) -> usize { - if self.p[x] != x { - self.p[x] = self.find(self.p[x]); - } - self.p[x] - } - - fn union(&mut self, a: usize, b: usize) -> bool { - let pa = self.find(a); - let pb = self.find(b); - if pa == pb { - false - } else if self.size[pa] > self.size[pb] { - self.p[pb] = pa; - self.size[pa] += self.size[pb]; - true - } else { - self.p[pa] = pb; - self.size[pb] += self.size[pa]; - true - } - } -} - -impl Solution { - pub fn earliest_acq(logs: Vec>, n: i32) -> i32 { - let mut logs = logs; - logs.sort_by(|a, b| a[0].cmp(&b[0])); - let mut uf = UnionFind::new(n as usize); - let mut n = n; - for log in logs { - let t = log[0]; - let x = log[1] as usize; - let y = log[2] as usize; - if uf.union(x, y) { - n -= 1; - if n == 1 { - return t; - } - } - } - -1 - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1102.Path With Maximum Minimum Value/README.md b/solution/1100-1199/1102.Path With Maximum Minimum Value/README.md index d19bdff44a076..f25af2e2b699f 100644 --- a/solution/1100-1199/1102.Path With Maximum Minimum Value/README.md +++ b/solution/1100-1199/1102.Path With Maximum Minimum Value/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:排序 + 并查集** +### 方法一:排序 + 并查集 我们先将矩阵的每个元素构建一个三元组 $(v, i, j)$,其中 $v$ 表示元素值,而 $i$ 和 $j$ 分别表示元素在矩阵中的行和列。然后对这些三元组按照元素值从大到小进行排序,存放在列表 $q$ 中。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def maximumMinimumPath(self, grid: List[List[int]]) -> int: @@ -99,6 +93,252 @@ class Solution: return ans ``` +```java +class Solution { + private int[] p; + + public int maximumMinimumPath(int[][] grid) { + int m = grid.length, n = grid[0].length; + p = new int[m * n]; + List q = new ArrayList<>(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + q.add(new int[] {grid[i][j], i, j}); + p[i * n + j] = i * n + j; + } + } + q.sort((a, b) -> b[0] - a[0]); + boolean[][] vis = new boolean[m][n]; + int[] dirs = {-1, 0, 1, 0, -1}; + int ans = 0; + for (int i = 0; find(0) != find(m * n - 1); ++i) { + int[] t = q.get(i); + vis[t[1]][t[2]] = true; + ans = t[0]; + for (int k = 0; k < 4; ++k) { + int x = t[1] + dirs[k], y = t[2] + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { + p[find(x * n + y)] = find(t[1] * n + t[2]); + } + } + } + return ans; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} +``` + +```cpp +class Solution { +public: + int maximumMinimumPath(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector> q; + vector p(m * n); + iota(p.begin(), p.end(), 0); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + q.emplace_back(grid[i][j], i, j); + } + } + function find = [&](int x) { + return p[x] == x ? x : p[x] = find(p[x]); + }; + sort(q.begin(), q.end(), greater>()); + int ans = 0; + int dirs[5] = {-1, 0, 1, 0, -1}; + bool vis[m][n]; + memset(vis, false, sizeof(vis)); + for (auto& [v, i, j] : q) { + vis[i][j] = true; + ans = v; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { + p[find(x * n + y)] = find(i * n + j); + } + } + if (find(0) == find(m * n - 1)) { + break; + } + } + return ans; + } +}; +``` + +```go +func maximumMinimumPath(grid [][]int) (ans int) { + m, n := len(grid), len(grid[0]) + p := make([]int, m*n) + vis := make([][]bool, m) + q := [][3]int{} + for i, row := range grid { + vis[i] = make([]bool, n) + for j, v := range row { + p[i*n+j] = i*n + j + q = append(q, [3]int{v, i, j}) + } + } + sort.Slice(q, func(i, j int) bool { return q[i][0] > q[j][0] }) + var find func(int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + dirs := [5]int{-1, 0, 1, 0, -1} + for _, t := range q { + v, i, j := t[0], t[1], t[2] + ans = v + vis[i][j] = true + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if 0 <= x && x < m && 0 <= y && y < n && vis[x][y] { + p[find(x*n+y)] = find(i*n + j) + } + } + if find(0) == find(m*n-1) { + break + } + } + return +} +``` + +```ts +function maximumMinimumPath(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const p: number[] = Array(m * n) + .fill(0) + .map((_, i) => i); + const q: number[][] = []; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + q.push([grid[i][j], i, j]); + } + } + q.sort((a, b) => b[0] - a[0]); + const find = (x: number): number => { + if (p[x] !== x) { + p[x] = find(p[x]); + } + return p[x]; + }; + const dirs: number[] = [-1, 0, 1, 0, -1]; + const vis: boolean[][] = Array(m) + .fill(0) + .map(() => Array(n).fill(false)); + let ans = 0; + for (let k = 0; find(0) !== find(m * n - 1); ++k) { + const [t, i, j] = q[k]; + ans = t; + vis[i][j] = true; + for (let d = 0; d < 4; ++d) { + const [x, y] = [i + dirs[d], j + dirs[d + 1]]; + if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { + p[find(i * n + j)] = find(x * n + y); + } + } + } + return ans; +} +``` + +```rust +struct UnionFind { + p: Vec, + size: Vec, +} + +impl UnionFind { + fn new(n: usize) -> Self { + let p: Vec = (0..n).collect(); + let size = vec![1; n]; + UnionFind { p, size } + } + + fn find(&mut self, x: usize) -> usize { + if self.p[x] != x { + self.p[x] = self.find(self.p[x]); + } + self.p[x] + } + + fn union(&mut self, a: usize, b: usize) { + let pa = self.find(a); + let pb = self.find(b); + if pa != pb { + if self.size[pa] > self.size[pb] { + self.p[pb] = pa; + self.size[pa] += self.size[pb]; + } else { + self.p[pa] = pb; + self.size[pb] += self.size[pa]; + } + } + } +} + +impl Solution { + pub fn maximum_minimum_path(grid: Vec>) -> i32 { + let m = grid.len(); + let n = grid[0].len(); + let mut uf = UnionFind::new(m * n); + let mut q: Vec> = Vec::new(); + + for i in 0..m { + for j in 0..n { + q.push(vec![grid[i][j], i as i32, j as i32]); + } + } + + q.sort_by(|a, b| b[0].cmp(&a[0])); + + let mut vis: Vec> = vec![vec![false; n]; m]; + let dirs: [i32; 5] = [-1, 0, 1, 0, -1]; + let mut ans = 0; + for k in 0..q.len() { + if uf.find(0) == uf.find(m * n - 1) { + break; + } + let t = &q[k]; + let (v, i, j) = (t[0], t[1] as usize, t[2] as usize); + ans = v; + vis[i][j] = true; + for d in 0..4 { + let x = (i as i32) + dirs[d]; + let y = (j as i32) + dirs[d + 1]; + if + x >= 0 && + x < (m as i32) && + y >= 0 && + y < (n as i32) && + vis[x as usize][y as usize] + { + uf.union((x as usize) * n + (y as usize), i * n + j); + } + } + } + ans + } +} +``` + + + +### 方法二 + + + ```python class UnionFind: __slots__ = ("p", "size") @@ -145,51 +385,6 @@ class Solution: return ans ``` -### **Java** - - - -```java -class Solution { - private int[] p; - - public int maximumMinimumPath(int[][] grid) { - int m = grid.length, n = grid[0].length; - p = new int[m * n]; - List q = new ArrayList<>(); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - q.add(new int[] {grid[i][j], i, j}); - p[i * n + j] = i * n + j; - } - } - q.sort((a, b) -> b[0] - a[0]); - boolean[][] vis = new boolean[m][n]; - int[] dirs = {-1, 0, 1, 0, -1}; - int ans = 0; - for (int i = 0; find(0) != find(m * n - 1); ++i) { - int[] t = q.get(i); - vis[t[1]][t[2]] = true; - ans = t[0]; - for (int k = 0; k < 4; ++k) { - int x = t[1] + dirs[k], y = t[2] + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { - p[find(x * n + y)] = find(t[1] * n + t[2]); - } - } - } - return ans; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } -} -``` - ```java class UnionFind { private int[] p; @@ -255,47 +450,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maximumMinimumPath(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - vector> q; - vector p(m * n); - iota(p.begin(), p.end(), 0); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - q.emplace_back(grid[i][j], i, j); - } - } - function find = [&](int x) { - return p[x] == x ? x : p[x] = find(p[x]); - }; - sort(q.begin(), q.end(), greater>()); - int ans = 0; - int dirs[5] = {-1, 0, 1, 0, -1}; - bool vis[m][n]; - memset(vis, false, sizeof(vis)); - for (auto& [v, i, j] : q) { - vis[i][j] = true; - ans = v; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { - p[find(x * n + y)] = find(i * n + j); - } - } - if (find(0) == find(m * n - 1)) { - break; - } - } - return ans; - } -}; -``` - ```cpp class UnionFind { public: @@ -363,48 +517,6 @@ public: }; ``` -### **Go** - -```go -func maximumMinimumPath(grid [][]int) (ans int) { - m, n := len(grid), len(grid[0]) - p := make([]int, m*n) - vis := make([][]bool, m) - q := [][3]int{} - for i, row := range grid { - vis[i] = make([]bool, n) - for j, v := range row { - p[i*n+j] = i*n + j - q = append(q, [3]int{v, i, j}) - } - } - sort.Slice(q, func(i, j int) bool { return q[i][0] > q[j][0] }) - var find func(int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - dirs := [5]int{-1, 0, 1, 0, -1} - for _, t := range q { - v, i, j := t[0], t[1], t[2] - ans = v - vis[i][j] = true - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if 0 <= x && x < m && 0 <= y && y < n && vis[x][y] { - p[find(x*n+y)] = find(i*n + j) - } - } - if find(0) == find(m*n-1) { - break - } - } - return -} -``` - ```go type unionFind struct { p, size []int @@ -471,48 +583,6 @@ func maximumMinimumPath(grid [][]int) (ans int) { } ``` -### **TypeScript** - -```ts -function maximumMinimumPath(grid: number[][]): number { - const m = grid.length; - const n = grid[0].length; - const p: number[] = Array(m * n) - .fill(0) - .map((_, i) => i); - const q: number[][] = []; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - q.push([grid[i][j], i, j]); - } - } - q.sort((a, b) => b[0] - a[0]); - const find = (x: number): number => { - if (p[x] !== x) { - p[x] = find(p[x]); - } - return p[x]; - }; - const dirs: number[] = [-1, 0, 1, 0, -1]; - const vis: boolean[][] = Array(m) - .fill(0) - .map(() => Array(n).fill(false)); - let ans = 0; - for (let k = 0; find(0) !== find(m * n - 1); ++k) { - const [t, i, j] = q[k]; - ans = t; - vis[i][j] = true; - for (let d = 0; d < 4; ++d) { - const [x, y] = [i + dirs[d], j + dirs[d + 1]]; - if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { - p[find(i * n + j)] = find(x * n + y); - } - } - } - return ans; -} -``` - ```ts class UnionFind { private p: number[]; @@ -580,92 +650,6 @@ function maximumMinimumPath(grid: number[][]): number { } ``` -### **Rust** - -```rust -struct UnionFind { - p: Vec, - size: Vec, -} - -impl UnionFind { - fn new(n: usize) -> Self { - let p: Vec = (0..n).collect(); - let size = vec![1; n]; - UnionFind { p, size } - } - - fn find(&mut self, x: usize) -> usize { - if self.p[x] != x { - self.p[x] = self.find(self.p[x]); - } - self.p[x] - } - - fn union(&mut self, a: usize, b: usize) { - let pa = self.find(a); - let pb = self.find(b); - if pa != pb { - if self.size[pa] > self.size[pb] { - self.p[pb] = pa; - self.size[pa] += self.size[pb]; - } else { - self.p[pa] = pb; - self.size[pb] += self.size[pa]; - } - } - } -} - -impl Solution { - pub fn maximum_minimum_path(grid: Vec>) -> i32 { - let m = grid.len(); - let n = grid[0].len(); - let mut uf = UnionFind::new(m * n); - let mut q: Vec> = Vec::new(); - - for i in 0..m { - for j in 0..n { - q.push(vec![grid[i][j], i as i32, j as i32]); - } - } - - q.sort_by(|a, b| b[0].cmp(&a[0])); - - let mut vis: Vec> = vec![vec![false; n]; m]; - let dirs: [i32; 5] = [-1, 0, 1, 0, -1]; - let mut ans = 0; - for k in 0..q.len() { - if uf.find(0) == uf.find(m * n - 1) { - break; - } - let t = &q[k]; - let (v, i, j) = (t[0], t[1] as usize, t[2] as usize); - ans = v; - vis[i][j] = true; - for d in 0..4 { - let x = (i as i32) + dirs[d]; - let y = (j as i32) + dirs[d + 1]; - if - x >= 0 && - x < (m as i32) && - y >= 0 && - y < (n as i32) && - vis[x as usize][y as usize] - { - uf.union((x as usize) * n + (y as usize), i * n + j); - } - } - } - ans - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1102.Path With Maximum Minimum Value/README_EN.md b/solution/1100-1199/1102.Path With Maximum Minimum Value/README_EN.md index 4bbed647e12ec..b5264ab50e986 100644 --- a/solution/1100-1199/1102.Path With Maximum Minimum Value/README_EN.md +++ b/solution/1100-1199/1102.Path With Maximum Minimum Value/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Sorting + Union-Find** +### Solution 1: Sorting + Union-Find First, we construct a triplet $(v, i, j)$ for each element in the matrix, where $v$ represents the element value, and $i$ and $j$ represent the row and column of the element in the matrix, respectively. Then we sort these triplets in descending order by element value and store them in a list $q$. @@ -57,8 +57,6 @@ The time complexity is $O(m \times n \times (\log (m \times n) + \alpha(m \times -### **Python3** - ```python class Solution: def maximumMinimumPath(self, grid: List[List[int]]) -> int: @@ -85,6 +83,252 @@ class Solution: return ans ``` +```java +class Solution { + private int[] p; + + public int maximumMinimumPath(int[][] grid) { + int m = grid.length, n = grid[0].length; + p = new int[m * n]; + List q = new ArrayList<>(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + q.add(new int[] {grid[i][j], i, j}); + p[i * n + j] = i * n + j; + } + } + q.sort((a, b) -> b[0] - a[0]); + boolean[][] vis = new boolean[m][n]; + int[] dirs = {-1, 0, 1, 0, -1}; + int ans = 0; + for (int i = 0; find(0) != find(m * n - 1); ++i) { + int[] t = q.get(i); + vis[t[1]][t[2]] = true; + ans = t[0]; + for (int k = 0; k < 4; ++k) { + int x = t[1] + dirs[k], y = t[2] + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { + p[find(x * n + y)] = find(t[1] * n + t[2]); + } + } + } + return ans; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} +``` + +```cpp +class Solution { +public: + int maximumMinimumPath(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + vector> q; + vector p(m * n); + iota(p.begin(), p.end(), 0); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + q.emplace_back(grid[i][j], i, j); + } + } + function find = [&](int x) { + return p[x] == x ? x : p[x] = find(p[x]); + }; + sort(q.begin(), q.end(), greater>()); + int ans = 0; + int dirs[5] = {-1, 0, 1, 0, -1}; + bool vis[m][n]; + memset(vis, false, sizeof(vis)); + for (auto& [v, i, j] : q) { + vis[i][j] = true; + ans = v; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { + p[find(x * n + y)] = find(i * n + j); + } + } + if (find(0) == find(m * n - 1)) { + break; + } + } + return ans; + } +}; +``` + +```go +func maximumMinimumPath(grid [][]int) (ans int) { + m, n := len(grid), len(grid[0]) + p := make([]int, m*n) + vis := make([][]bool, m) + q := [][3]int{} + for i, row := range grid { + vis[i] = make([]bool, n) + for j, v := range row { + p[i*n+j] = i*n + j + q = append(q, [3]int{v, i, j}) + } + } + sort.Slice(q, func(i, j int) bool { return q[i][0] > q[j][0] }) + var find func(int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + dirs := [5]int{-1, 0, 1, 0, -1} + for _, t := range q { + v, i, j := t[0], t[1], t[2] + ans = v + vis[i][j] = true + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if 0 <= x && x < m && 0 <= y && y < n && vis[x][y] { + p[find(x*n+y)] = find(i*n + j) + } + } + if find(0) == find(m*n-1) { + break + } + } + return +} +``` + +```ts +function maximumMinimumPath(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const p: number[] = Array(m * n) + .fill(0) + .map((_, i) => i); + const q: number[][] = []; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + q.push([grid[i][j], i, j]); + } + } + q.sort((a, b) => b[0] - a[0]); + const find = (x: number): number => { + if (p[x] !== x) { + p[x] = find(p[x]); + } + return p[x]; + }; + const dirs: number[] = [-1, 0, 1, 0, -1]; + const vis: boolean[][] = Array(m) + .fill(0) + .map(() => Array(n).fill(false)); + let ans = 0; + for (let k = 0; find(0) !== find(m * n - 1); ++k) { + const [t, i, j] = q[k]; + ans = t; + vis[i][j] = true; + for (let d = 0; d < 4; ++d) { + const [x, y] = [i + dirs[d], j + dirs[d + 1]]; + if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { + p[find(i * n + j)] = find(x * n + y); + } + } + } + return ans; +} +``` + +```rust +struct UnionFind { + p: Vec, + size: Vec, +} + +impl UnionFind { + fn new(n: usize) -> Self { + let p: Vec = (0..n).collect(); + let size = vec![1; n]; + UnionFind { p, size } + } + + fn find(&mut self, x: usize) -> usize { + if self.p[x] != x { + self.p[x] = self.find(self.p[x]); + } + self.p[x] + } + + fn union(&mut self, a: usize, b: usize) { + let pa = self.find(a); + let pb = self.find(b); + if pa != pb { + if self.size[pa] > self.size[pb] { + self.p[pb] = pa; + self.size[pa] += self.size[pb]; + } else { + self.p[pa] = pb; + self.size[pb] += self.size[pa]; + } + } + } +} + +impl Solution { + pub fn maximum_minimum_path(grid: Vec>) -> i32 { + let m = grid.len(); + let n = grid[0].len(); + let mut uf = UnionFind::new(m * n); + let mut q: Vec> = Vec::new(); + + for i in 0..m { + for j in 0..n { + q.push(vec![grid[i][j], i as i32, j as i32]); + } + } + + q.sort_by(|a, b| b[0].cmp(&a[0])); + + let mut vis: Vec> = vec![vec![false; n]; m]; + let dirs: [i32; 5] = [-1, 0, 1, 0, -1]; + let mut ans = 0; + for k in 0..q.len() { + if uf.find(0) == uf.find(m * n - 1) { + break; + } + let t = &q[k]; + let (v, i, j) = (t[0], t[1] as usize, t[2] as usize); + ans = v; + vis[i][j] = true; + for d in 0..4 { + let x = (i as i32) + dirs[d]; + let y = (j as i32) + dirs[d + 1]; + if + x >= 0 && + x < (m as i32) && + y >= 0 && + y < (n as i32) && + vis[x as usize][y as usize] + { + uf.union((x as usize) * n + (y as usize), i * n + j); + } + } + } + ans + } +} +``` + + + +### Solution 2 + + + ```python class UnionFind: __slots__ = ("p", "size") @@ -131,49 +375,6 @@ class Solution: return ans ``` -### **Java** - -```java -class Solution { - private int[] p; - - public int maximumMinimumPath(int[][] grid) { - int m = grid.length, n = grid[0].length; - p = new int[m * n]; - List q = new ArrayList<>(); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - q.add(new int[] {grid[i][j], i, j}); - p[i * n + j] = i * n + j; - } - } - q.sort((a, b) -> b[0] - a[0]); - boolean[][] vis = new boolean[m][n]; - int[] dirs = {-1, 0, 1, 0, -1}; - int ans = 0; - for (int i = 0; find(0) != find(m * n - 1); ++i) { - int[] t = q.get(i); - vis[t[1]][t[2]] = true; - ans = t[0]; - for (int k = 0; k < 4; ++k) { - int x = t[1] + dirs[k], y = t[2] + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { - p[find(x * n + y)] = find(t[1] * n + t[2]); - } - } - } - return ans; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } -} -``` - ```java class UnionFind { private int[] p; @@ -239,47 +440,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maximumMinimumPath(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - vector> q; - vector p(m * n); - iota(p.begin(), p.end(), 0); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - q.emplace_back(grid[i][j], i, j); - } - } - function find = [&](int x) { - return p[x] == x ? x : p[x] = find(p[x]); - }; - sort(q.begin(), q.end(), greater>()); - int ans = 0; - int dirs[5] = {-1, 0, 1, 0, -1}; - bool vis[m][n]; - memset(vis, false, sizeof(vis)); - for (auto& [v, i, j] : q) { - vis[i][j] = true; - ans = v; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { - p[find(x * n + y)] = find(i * n + j); - } - } - if (find(0) == find(m * n - 1)) { - break; - } - } - return ans; - } -}; -``` - ```cpp class UnionFind { public: @@ -347,48 +507,6 @@ public: }; ``` -### **Go** - -```go -func maximumMinimumPath(grid [][]int) (ans int) { - m, n := len(grid), len(grid[0]) - p := make([]int, m*n) - vis := make([][]bool, m) - q := [][3]int{} - for i, row := range grid { - vis[i] = make([]bool, n) - for j, v := range row { - p[i*n+j] = i*n + j - q = append(q, [3]int{v, i, j}) - } - } - sort.Slice(q, func(i, j int) bool { return q[i][0] > q[j][0] }) - var find func(int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - dirs := [5]int{-1, 0, 1, 0, -1} - for _, t := range q { - v, i, j := t[0], t[1], t[2] - ans = v - vis[i][j] = true - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if 0 <= x && x < m && 0 <= y && y < n && vis[x][y] { - p[find(x*n+y)] = find(i*n + j) - } - } - if find(0) == find(m*n-1) { - break - } - } - return -} -``` - ```go type unionFind struct { p, size []int @@ -455,48 +573,6 @@ func maximumMinimumPath(grid [][]int) (ans int) { } ``` -### **TypeScript** - -```ts -function maximumMinimumPath(grid: number[][]): number { - const m = grid.length; - const n = grid[0].length; - const p: number[] = Array(m * n) - .fill(0) - .map((_, i) => i); - const q: number[][] = []; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - q.push([grid[i][j], i, j]); - } - } - q.sort((a, b) => b[0] - a[0]); - const find = (x: number): number => { - if (p[x] !== x) { - p[x] = find(p[x]); - } - return p[x]; - }; - const dirs: number[] = [-1, 0, 1, 0, -1]; - const vis: boolean[][] = Array(m) - .fill(0) - .map(() => Array(n).fill(false)); - let ans = 0; - for (let k = 0; find(0) !== find(m * n - 1); ++k) { - const [t, i, j] = q[k]; - ans = t; - vis[i][j] = true; - for (let d = 0; d < 4; ++d) { - const [x, y] = [i + dirs[d], j + dirs[d + 1]]; - if (x >= 0 && x < m && y >= 0 && y < n && vis[x][y]) { - p[find(i * n + j)] = find(x * n + y); - } - } - } - return ans; -} -``` - ```ts class UnionFind { private p: number[]; @@ -564,92 +640,6 @@ function maximumMinimumPath(grid: number[][]): number { } ``` -### **Rust** - -```rust -struct UnionFind { - p: Vec, - size: Vec, -} - -impl UnionFind { - fn new(n: usize) -> Self { - let p: Vec = (0..n).collect(); - let size = vec![1; n]; - UnionFind { p, size } - } - - fn find(&mut self, x: usize) -> usize { - if self.p[x] != x { - self.p[x] = self.find(self.p[x]); - } - self.p[x] - } - - fn union(&mut self, a: usize, b: usize) { - let pa = self.find(a); - let pb = self.find(b); - if pa != pb { - if self.size[pa] > self.size[pb] { - self.p[pb] = pa; - self.size[pa] += self.size[pb]; - } else { - self.p[pa] = pb; - self.size[pb] += self.size[pa]; - } - } - } -} - -impl Solution { - pub fn maximum_minimum_path(grid: Vec>) -> i32 { - let m = grid.len(); - let n = grid[0].len(); - let mut uf = UnionFind::new(m * n); - let mut q: Vec> = Vec::new(); - - for i in 0..m { - for j in 0..n { - q.push(vec![grid[i][j], i as i32, j as i32]); - } - } - - q.sort_by(|a, b| b[0].cmp(&a[0])); - - let mut vis: Vec> = vec![vec![false; n]; m]; - let dirs: [i32; 5] = [-1, 0, 1, 0, -1]; - let mut ans = 0; - for k in 0..q.len() { - if uf.find(0) == uf.find(m * n - 1) { - break; - } - let t = &q[k]; - let (v, i, j) = (t[0], t[1] as usize, t[2] as usize); - ans = v; - vis[i][j] = true; - for d in 0..4 { - let x = (i as i32) + dirs[d]; - let y = (j as i32) + dirs[d + 1]; - if - x >= 0 && - x < (m as i32) && - y >= 0 && - y < (n as i32) && - vis[x as usize][y as usize] - { - uf.union((x as usize) * n + (y as usize), i * n + j); - } - } - } - ans - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1103.Distribute Candies to People/README.md b/solution/1100-1199/1103.Distribute Candies to People/README.md index c587166dc08c1..eab84dc94814b 100644 --- a/solution/1100-1199/1103.Distribute Candies to People/README.md +++ b/solution/1100-1199/1103.Distribute Candies to People/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以直接模拟每一个人分到糖果的过程,按照题目描述的规则模拟即可。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def distributeCandies(self, candies: int, num_people: int) -> List[int]: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] distributeCandies(int candies, int num_people) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +100,6 @@ public: }; ``` -### **Go** - ```go func distributeCandies(candies int, num_people int) []int { ans := make([]int, num_people) @@ -125,8 +111,6 @@ func distributeCandies(candies int, num_people int) []int { } ``` -### **TypeScript** - ```ts function distributeCandies(candies: number, num_people: number): number[] { const ans: number[] = Array(num_people).fill(0); @@ -138,10 +122,6 @@ function distributeCandies(candies: number, num_people: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1103.Distribute Candies to People/README_EN.md b/solution/1100-1199/1103.Distribute Candies to People/README_EN.md index 79f3d48c29ccd..eadf6ea677652 100644 --- a/solution/1100-1199/1103.Distribute Candies to People/README_EN.md +++ b/solution/1100-1199/1103.Distribute Candies to People/README_EN.md @@ -49,7 +49,7 @@ On the fourth turn, ans[0] += 4, and the final array is [5,2,3]. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can directly simulate the process of each person receiving candies, following the rules described in the problem. @@ -57,8 +57,6 @@ The time complexity is $O(\max(\sqrt{candies}, num\_people))$, and the space com -### **Python3** - ```python class Solution: def distributeCandies(self, candies: int, num_people: int) -> List[int]: @@ -71,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] distributeCandies(int candies, int num_people) { @@ -86,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +96,6 @@ public: }; ``` -### **Go** - ```go func distributeCandies(candies int, num_people int) []int { ans := make([]int, num_people) @@ -115,8 +107,6 @@ func distributeCandies(candies int, num_people int) []int { } ``` -### **TypeScript** - ```ts function distributeCandies(candies: number, num_people: number): number[] { const ans: number[] = Array(num_people).fill(0); @@ -128,10 +118,6 @@ function distributeCandies(candies: number, num_people: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README.md b/solution/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README.md index 828d0399629b9..4a43a728496b2 100644 --- a/solution/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README.md +++ b/solution/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 对于一棵完全二叉树,第 $i$ 行的节点个数为 $2^{i-1}$,第 $i$ 行的节点编号范围为 $[2^{i-1}, 2^i - 1]$。而题目中对于奇数行,按从左到右的顺序进行标记,对于偶数行,按从右到左的顺序进行标记。所以对于第 $i$ 行的节点 $label$,它的互补节点编号为 $2^{i-1} + 2^i - 1 - label$。所以节点 $label$ 的实际父节点编号为 $(2^{i-1} + 2^i - 1 - label) / 2$。我们可以通过不断地求互补节点编号和父节点编号,直到到达根节点,即可得到从根节点到节点 $label$ 的路径。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def pathInZigZagTree(self, label: int) -> List[int]: @@ -71,10 +65,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List pathInZigZagTree(int label) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func pathInZigZagTree(label int) (ans []int) { x, i := 1, 1 @@ -136,10 +122,6 @@ func pathInZigZagTree(label int) (ans []int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README_EN.md b/solution/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README_EN.md index 15d7d4546058c..9490345ae44a8 100644 --- a/solution/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README_EN.md +++ b/solution/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics For a complete binary tree, the number of nodes in the $i$th row is $2^{i-1}$, and the range of node labels in the $i$th row is $[2^{i-1}, 2^i - 1]$. In the problem, for odd-numbered rows, the nodes are labeled from left to right, while for even-numbered rows, the nodes are labeled from right to left. Therefore, for the node $label$ in the $i$th row, its complementary node label is $2^{i-1} + 2^i - 1 - label$. So the actual parent node label of node $label$ is $(2^{i-1} + 2^i - 1 - label) / 2$. We can find the path from the root node to node $label$ by continuously finding the complementary node label and the parent node label until we reach the root node. @@ -46,8 +46,6 @@ The time complexity is $O(\log n)$, where $n$ is the label of the node. Ignoring -### **Python3** - ```python class Solution: def pathInZigZagTree(self, label: int) -> List[int]: @@ -63,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List pathInZigZagTree(int label) { @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +100,6 @@ public: }; ``` -### **Go** - ```go func pathInZigZagTree(label int) (ans []int) { x, i := 1, 1 @@ -126,10 +118,6 @@ func pathInZigZagTree(label int) (ans []int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1105.Filling Bookcase Shelves/README.md b/solution/1100-1199/1105.Filling Bookcase Shelves/README.md index 9354f06b238ff..b54afc6edb6e7 100644 --- a/solution/1100-1199/1105.Filling Bookcase Shelves/README.md +++ b/solution/1100-1199/1105.Filling Bookcase Shelves/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示前 $i$ 本书摆放的最小高度,初始时 $f[0] = 0$,答案为 $f[n]$。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int: @@ -92,10 +86,6 @@ class Solution: return f[n] ``` -### **Java** - - - ```java class Solution { public int minHeightShelves(int[][] books, int shelfWidth) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func minHeightShelves(books [][]int, shelfWidth int) int { n := len(books) @@ -166,8 +152,6 @@ func minHeightShelves(books [][]int, shelfWidth int) int { } ``` -### **TypeScript** - ```ts function minHeightShelves(books: number[][], shelfWidth: number): number { const n = books.length; @@ -188,8 +172,6 @@ function minHeightShelves(books: number[][], shelfWidth: number): number { } ``` -### **C#** - ```cs public class Solution { public int MinHeightShelves(int[][] books, int shelfWidth) { @@ -212,10 +194,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1105.Filling Bookcase Shelves/README_EN.md b/solution/1100-1199/1105.Filling Bookcase Shelves/README_EN.md index efbcc2b711eb1..ba52b2de0e6f5 100644 --- a/solution/1100-1199/1105.Filling Bookcase Shelves/README_EN.md +++ b/solution/1100-1199/1105.Filling Bookcase Shelves/README_EN.md @@ -47,7 +47,7 @@ Notice that book number 2 does not have to be on the first shelf. ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i]$ as the minimum height for placing the first $i$ books, initially $f[0] = 0$, and the answer is $f[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 minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int: @@ -80,8 +78,6 @@ class Solution: return f[n] ``` -### **Java** - ```java class Solution { public int minHeightShelves(int[][] books, int shelfWidth) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +124,6 @@ public: }; ``` -### **Go** - ```go func minHeightShelves(books [][]int, shelfWidth int) int { n := len(books) @@ -152,8 +144,6 @@ func minHeightShelves(books [][]int, shelfWidth int) int { } ``` -### **TypeScript** - ```ts function minHeightShelves(books: number[][], shelfWidth: number): number { const n = books.length; @@ -174,8 +164,6 @@ function minHeightShelves(books: number[][], shelfWidth: number): number { } ``` -### **C#** - ```cs public class Solution { public int MinHeightShelves(int[][] books, int shelfWidth) { @@ -198,10 +186,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1106.Parsing A Boolean Expression/README.md b/solution/1100-1199/1106.Parsing A Boolean Expression/README.md index eb6d0f939bbe7..aa28c33a251b3 100644 --- a/solution/1100-1199/1106.Parsing A Boolean Expression/README.md +++ b/solution/1100-1199/1106.Parsing A Boolean Expression/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 对于这种表达式解析问题,我们可以使用栈来辅助解决。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def parseBoolExpr(self, expression: str) -> bool: @@ -107,10 +101,6 @@ class Solution: return stk[0] == 't' ``` -### **Java** - - - ```java class Solution { public boolean parseBoolExpr(String expression) { @@ -138,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go func parseBoolExpr(expression string) bool { stk := []rune{} @@ -199,8 +185,6 @@ func parseBoolExpr(expression string) bool { } ``` -### **TypeScript** - ```ts function parseBoolExpr(expression: string): boolean { const expr = expression; @@ -232,8 +216,6 @@ function parseBoolExpr(expression: string): boolean { } ``` -### **Rust** - ```rust impl Solution { fn dfs(i: &mut usize, expr: &[u8]) -> Vec { @@ -283,10 +265,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1106.Parsing A Boolean Expression/README_EN.md b/solution/1100-1199/1106.Parsing A Boolean Expression/README_EN.md index ae3074d882886..c0d84bda7b3d6 100644 --- a/solution/1100-1199/1106.Parsing A Boolean Expression/README_EN.md +++ b/solution/1100-1199/1106.Parsing A Boolean Expression/README_EN.md @@ -58,7 +58,7 @@ Then, evaluate !(f) --> NOT false --> true. We return true. ## Solutions -**Solution 1: Stack** +### Solution 1: Stack For this type of expression parsing problem, we can use a stack to assist. @@ -73,8 +73,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def parseBoolExpr(self, expression: str) -> bool: @@ -99,8 +97,6 @@ class Solution: return stk[0] == 't' ``` -### **Java** - ```java class Solution { public boolean parseBoolExpr(String expression) { @@ -128,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +152,6 @@ public: }; ``` -### **Go** - ```go func parseBoolExpr(expression string) bool { stk := []rune{} @@ -189,8 +181,6 @@ func parseBoolExpr(expression string) bool { } ``` -### **TypeScript** - ```ts function parseBoolExpr(expression: string): boolean { const expr = expression; @@ -222,8 +212,6 @@ function parseBoolExpr(expression: string): boolean { } ``` -### **Rust** - ```rust impl Solution { fn dfs(i: &mut usize, expr: &[u8]) -> Vec { @@ -273,10 +261,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1107.New Users Daily Count/README.md b/solution/1100-1199/1107.New Users Daily Count/README.md index 68dbf6c463bd1..97e7eb3f8bcfa 100644 --- a/solution/1100-1199/1107.New Users Daily Count/README.md +++ b/solution/1100-1199/1107.New Users Daily Count/README.md @@ -71,12 +71,10 @@ ID 为 5 的用户第一次登陆于 2019-03-01,因此他不算在 2019-06-21 ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -94,3 +92,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1100-1199/1107.New Users Daily Count/README_EN.md b/solution/1100-1199/1107.New Users Daily Count/README_EN.md index f9b5074a78346..0e921da916c0c 100644 --- a/solution/1100-1199/1107.New Users Daily Count/README_EN.md +++ b/solution/1100-1199/1107.New Users Daily Count/README_EN.md @@ -65,9 +65,9 @@ The user with id 5 first logged in on 2019-03-01 so he's not counted on 2019 ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -86,3 +86,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1100-1199/1108.Defanging an IP Address/README.md b/solution/1100-1199/1108.Defanging an IP Address/README.md index 835996e955eb3..3059d8da2355f 100644 --- a/solution/1100-1199/1108.Defanging an IP Address/README.md +++ b/solution/1100-1199/1108.Defanging an IP Address/README.md @@ -34,9 +34,7 @@ ## 解法 - - -**方法一:直接替换** +### 方法一:直接替换 我们直接将字符串中的 `'.'` 替换为 `'[.]'` 即可。 @@ -44,20 +42,12 @@ -### **Python3** - - - ```python class Solution: def defangIPaddr(self, address: str) -> str: return address.replace('.', '[.]') ``` -### **Java** - - - ```java class Solution { public String defangIPaddr(String address) { @@ -66,16 +56,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function defangIPaddr(address: string): string { - return address.split('.').join('[.]'); -} -``` - -### **C++** - ```cpp class Solution { public: @@ -90,18 +70,18 @@ public: }; ``` -### **Go** - ```go func defangIPaddr(address string) string { return strings.Replace(address, ".", "[.]", -1) } ``` -### **...** - -``` - +```ts +function defangIPaddr(address: string): string { + return address.split('.').join('[.]'); +} ``` + + diff --git a/solution/1100-1199/1108.Defanging an IP Address/README_EN.md b/solution/1100-1199/1108.Defanging an IP Address/README_EN.md index 49151237d4df0..e6c12f8031270 100644 --- a/solution/1100-1199/1108.Defanging an IP Address/README_EN.md +++ b/solution/1100-1199/1108.Defanging an IP Address/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Direct Replacement** +### Solution 1: Direct Replacement We can directly replace the `'.'` in the string with `'[.]'`. @@ -42,16 +42,12 @@ The time complexity is $O(n)$, where $n$ is the length of the string. Ignoring t -### **Python3** - ```python class Solution: def defangIPaddr(self, address: str) -> str: return address.replace('.', '[.]') ``` -### **Java** - ```java class Solution { public String defangIPaddr(String address) { @@ -60,16 +56,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function defangIPaddr(address: string): string { - return address.split('.').join('[.]'); -} -``` - -### **C++** - ```cpp class Solution { public: @@ -84,18 +70,18 @@ public: }; ``` -### **Go** - ```go func defangIPaddr(address string) string { return strings.Replace(address, ".", "[.]", -1) } ``` -### **...** - -``` - +```ts +function defangIPaddr(address: string): string { + return address.split('.').join('[.]'); +} ``` + + diff --git a/solution/1100-1199/1109.Corporate Flight Bookings/README.md b/solution/1100-1199/1109.Corporate Flight Bookings/README.md index ffe356ee1f517..4861cfe090c2d 100644 --- a/solution/1100-1199/1109.Corporate Flight Bookings/README.md +++ b/solution/1100-1199/1109.Corporate Flight Bookings/README.md @@ -55,15 +55,130 @@ ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 我们注意到,每一次预订都是在某个区间 `[first, last]` 内的所有航班上预订了 `seats` 个座位。因此,我们可以利用差分数组的思想,对于每一次预订,将 `first` 位置的数加上 `seats`,将 `last + 1` 位置的数减去 `seats`。最后,对差分数组求前缀和,即可得到每个航班预定的座位总数。 时间复杂度 $O(n)$,其中 $n$ 为航班数。忽略答案的空间消耗,空间复杂度 $O(1)$。 -**方法二:树状数组 + 差分思想** + + +```python +class Solution: + def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: + ans = [0] * n + for first, last, seats in bookings: + ans[first - 1] += seats + if last < n: + ans[last] -= seats + return list(accumulate(ans)) +``` + +```java +class Solution { + public int[] corpFlightBookings(int[][] bookings, int n) { + int[] ans = new int[n]; + for (var e : bookings) { + int first = e[0], last = e[1], seats = e[2]; + ans[first - 1] += seats; + if (last < n) { + ans[last] -= seats; + } + } + for (int i = 1; i < n; ++i) { + ans[i] += ans[i - 1]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector corpFlightBookings(vector>& bookings, int n) { + vector ans(n); + for (auto& e : bookings) { + int first = e[0], last = e[1], seats = e[2]; + ans[first - 1] += seats; + if (last < n) { + ans[last] -= seats; + } + } + for (int i = 1; i < n; ++i) { + ans[i] += ans[i - 1]; + } + return ans; + } +}; +``` + +```go +func corpFlightBookings(bookings [][]int, n int) []int { + ans := make([]int, n) + for _, e := range bookings { + first, last, seats := e[0], e[1], e[2] + ans[first-1] += seats + if last < n { + ans[last] -= seats + } + } + for i := 1; i < n; i++ { + ans[i] += ans[i-1] + } + return ans +} +``` + +```rust +impl Solution { + #[allow(dead_code)] + pub fn corp_flight_bookings(bookings: Vec>, n: i32) -> Vec { + let mut ans = vec![0; n as usize]; + + // Build the difference vector first + for b in &bookings { + let (l, r) = ((b[0] as usize) - 1, (b[1] as usize) - 1); + ans[l] += b[2]; + if r < (n as usize) - 1 { + ans[r + 1] -= b[2]; + } + } + + // Build the prefix sum vector based on the difference vector + for i in 1..n as usize { + ans[i] += ans[i - 1]; + } + + ans + } +} +``` + +```js +/** + * @param {number[][]} bookings + * @param {number} n + * @return {number[]} + */ +var corpFlightBookings = function (bookings, n) { + const ans = new Array(n).fill(0); + for (const [first, last, seats] of bookings) { + ans[first - 1] += seats; + if (last < n) { + ans[last] -= seats; + } + } + for (let i = 1; i < n; ++i) { + ans[i] += ans[i - 1]; + } + return ans; +}; +``` + + + +### 方法二:树状数组 + 差分思想 我们也可以利用树状数组,结合差分的思想,来实现上述操作。我们可以将每一次预订看作是在某个区间 `[first, last]` 内的所有航班上预订了 `seats` 个座位。因此,我们可以对每一次预订,对树状数组的 `first` 位置加上 `seats`,对树状数组的 `last + 1` 位置减去 `seats`。最后,对树状数组每个位置求前缀和,即可得到每个航班预定的座位总数。 @@ -80,21 +195,6 @@ -### **Python3** - - - -```python -class Solution: - def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: - ans = [0] * n - for first, last, seats in bookings: - ans[first - 1] += seats - if last < n: - ans[last] -= seats - return list(accumulate(ans)) -``` - ```python class BinaryIndexedTree: def __init__(self, n): @@ -123,29 +223,6 @@ class Solution: return [tree.query(i + 1) for i in range(n)] ``` -### **Java** - - - -```java -class Solution { - public int[] corpFlightBookings(int[][] bookings, int n) { - int[] ans = new int[n]; - for (var e : bookings) { - int first = e[0], last = e[1], seats = e[2]; - ans[first - 1] += seats; - if (last < n) { - ans[last] -= seats; - } - } - for (int i = 1; i < n; ++i) { - ans[i] += ans[i - 1]; - } - return ans; - } -} -``` - ```java class Solution { public int[] corpFlightBookings(int[][] bookings, int n) { @@ -190,28 +267,6 @@ class BinaryIndexedTree { } ``` -### **C++** - -```cpp -class Solution { -public: - vector corpFlightBookings(vector>& bookings, int n) { - vector ans(n); - for (auto& e : bookings) { - int first = e[0], last = e[1], seats = e[2]; - ans[first - 1] += seats; - if (last < n) { - ans[last] -= seats; - } - } - for (int i = 1; i < n; ++i) { - ans[i] += ans[i - 1]; - } - return ans; - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -258,52 +313,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn corp_flight_bookings(bookings: Vec>, n: i32) -> Vec { - let mut ans = vec![0; n as usize]; - - // Build the difference vector first - for b in &bookings { - let (l, r) = ((b[0] as usize) - 1, (b[1] as usize) - 1); - ans[l] += b[2]; - if r < (n as usize) - 1 { - ans[r + 1] -= b[2]; - } - } - - // Build the prefix sum vector based on the difference vector - for i in 1..n as usize { - ans[i] += ans[i - 1]; - } - - ans - } -} -``` - -### **Go** - -```go -func corpFlightBookings(bookings [][]int, n int) []int { - ans := make([]int, n) - for _, e := range bookings { - first, last, seats := e[0], e[1], e[2] - ans[first-1] += seats - if last < n { - ans[last] -= seats - } - } - for i := 1; i < n; i++ { - ans[i] += ans[i-1] - } - return ans -} -``` - ```go type BinaryIndexedTree struct { n int @@ -346,33 +355,6 @@ func corpFlightBookings(bookings [][]int, n int) []int { } ``` -### **JavaScript** - -```js -/** - * @param {number[][]} bookings - * @param {number} n - * @return {number[]} - */ -var corpFlightBookings = function (bookings, n) { - const ans = new Array(n).fill(0); - for (const [first, last, seats] of bookings) { - ans[first - 1] += seats; - if (last < n) { - ans[last] -= seats; - } - } - for (let i = 1; i < n; ++i) { - ans[i] += ans[i - 1]; - } - return ans; -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1109.Corporate Flight Bookings/README_EN.md b/solution/1100-1199/1109.Corporate Flight Bookings/README_EN.md index e47380dae28ca..f009554fcd6c2 100644 --- a/solution/1100-1199/1109.Corporate Flight Bookings/README_EN.md +++ b/solution/1100-1199/1109.Corporate Flight Bookings/README_EN.md @@ -52,13 +52,130 @@ Hence, answer = [10,25] ## Solutions -**Solution 1: Difference Array** +### Solution 1: Difference Array We notice that each booking is for `seats` seats on all flights within a certain interval `[first, last]`. Therefore, we can use the idea of a difference array. For each booking, we add `seats` to the number at the `first` position and subtract `seats` from the number at the `last + 1` position. Finally, we calculate the prefix sum of the difference array to get the total number of seats booked for each flight. The time complexity is $O(n)$, where $n$ is the number of flights. Ignoring the space consumption of the answer, the space complexity is $O(1)$. -**Solution 2: Binary Indexed Tree + Difference Idea** + + +```python +class Solution: + def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: + ans = [0] * n + for first, last, seats in bookings: + ans[first - 1] += seats + if last < n: + ans[last] -= seats + return list(accumulate(ans)) +``` + +```java +class Solution { + public int[] corpFlightBookings(int[][] bookings, int n) { + int[] ans = new int[n]; + for (var e : bookings) { + int first = e[0], last = e[1], seats = e[2]; + ans[first - 1] += seats; + if (last < n) { + ans[last] -= seats; + } + } + for (int i = 1; i < n; ++i) { + ans[i] += ans[i - 1]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector corpFlightBookings(vector>& bookings, int n) { + vector ans(n); + for (auto& e : bookings) { + int first = e[0], last = e[1], seats = e[2]; + ans[first - 1] += seats; + if (last < n) { + ans[last] -= seats; + } + } + for (int i = 1; i < n; ++i) { + ans[i] += ans[i - 1]; + } + return ans; + } +}; +``` + +```go +func corpFlightBookings(bookings [][]int, n int) []int { + ans := make([]int, n) + for _, e := range bookings { + first, last, seats := e[0], e[1], e[2] + ans[first-1] += seats + if last < n { + ans[last] -= seats + } + } + for i := 1; i < n; i++ { + ans[i] += ans[i-1] + } + return ans +} +``` + +```rust +impl Solution { + #[allow(dead_code)] + pub fn corp_flight_bookings(bookings: Vec>, n: i32) -> Vec { + let mut ans = vec![0; n as usize]; + + // Build the difference vector first + for b in &bookings { + let (l, r) = ((b[0] as usize) - 1, (b[1] as usize) - 1); + ans[l] += b[2]; + if r < (n as usize) - 1 { + ans[r + 1] -= b[2]; + } + } + + // Build the prefix sum vector based on the difference vector + for i in 1..n as usize { + ans[i] += ans[i - 1]; + } + + ans + } +} +``` + +```js +/** + * @param {number[][]} bookings + * @param {number} n + * @return {number[]} + */ +var corpFlightBookings = function (bookings, n) { + const ans = new Array(n).fill(0); + for (const [first, last, seats] of bookings) { + ans[first - 1] += seats; + if (last < n) { + ans[last] -= seats; + } + } + for (let i = 1; i < n; ++i) { + ans[i] += ans[i - 1]; + } + return ans; +}; +``` + + + +### Solution 2: Binary Indexed Tree + Difference Idea We can also use a binary indexed tree, combined with the idea of difference, to implement the above operations. We can consider each booking as booking `seats` seats on all flights within a certain interval `[first, last]`. Therefore, for each booking, we add `seats` to the `first` position of the binary indexed tree and subtract `seats` from the `last + 1` position of the binary indexed tree. Finally, we calculate the prefix sum for each position in the binary indexed tree to get the total number of seats booked for each flight. @@ -75,19 +192,6 @@ The time complexity of these two operations is $O(\log n)$. -### **Python3** - -```python -class Solution: - def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: - ans = [0] * n - for first, last, seats in bookings: - ans[first - 1] += seats - if last < n: - ans[last] -= seats - return list(accumulate(ans)) -``` - ```python class BinaryIndexedTree: def __init__(self, n): @@ -116,27 +220,6 @@ class Solution: return [tree.query(i + 1) for i in range(n)] ``` -### **Java** - -```java -class Solution { - public int[] corpFlightBookings(int[][] bookings, int n) { - int[] ans = new int[n]; - for (var e : bookings) { - int first = e[0], last = e[1], seats = e[2]; - ans[first - 1] += seats; - if (last < n) { - ans[last] -= seats; - } - } - for (int i = 1; i < n; ++i) { - ans[i] += ans[i - 1]; - } - return ans; - } -} -``` - ```java class Solution { public int[] corpFlightBookings(int[][] bookings, int n) { @@ -181,28 +264,6 @@ class BinaryIndexedTree { } ``` -### **C++** - -```cpp -class Solution { -public: - vector corpFlightBookings(vector>& bookings, int n) { - vector ans(n); - for (auto& e : bookings) { - int first = e[0], last = e[1], seats = e[2]; - ans[first - 1] += seats; - if (last < n) { - ans[last] -= seats; - } - } - for (int i = 1; i < n; ++i) { - ans[i] += ans[i - 1]; - } - return ans; - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -249,52 +310,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn corp_flight_bookings(bookings: Vec>, n: i32) -> Vec { - let mut ans = vec![0; n as usize]; - - // Build the difference vector first - for b in &bookings { - let (l, r) = ((b[0] as usize) - 1, (b[1] as usize) - 1); - ans[l] += b[2]; - if r < (n as usize) - 1 { - ans[r + 1] -= b[2]; - } - } - - // Build the prefix sum vector based on the difference vector - for i in 1..n as usize { - ans[i] += ans[i - 1]; - } - - ans - } -} -``` - -### **Go** - -```go -func corpFlightBookings(bookings [][]int, n int) []int { - ans := make([]int, n) - for _, e := range bookings { - first, last, seats := e[0], e[1], e[2] - ans[first-1] += seats - if last < n { - ans[last] -= seats - } - } - for i := 1; i < n; i++ { - ans[i] += ans[i-1] - } - return ans -} -``` - ```go type BinaryIndexedTree struct { n int @@ -337,33 +352,6 @@ func corpFlightBookings(bookings [][]int, n int) []int { } ``` -### **JavaScript** - -```js -/** - * @param {number[][]} bookings - * @param {number} n - * @return {number[]} - */ -var corpFlightBookings = function (bookings, n) { - const ans = new Array(n).fill(0); - for (const [first, last, seats] of bookings) { - ans[first - 1] += seats; - if (last < n) { - ans[last] -= seats; - } - } - for (let i = 1; i < n; ++i) { - ans[i] += ans[i - 1]; - } - return ans; -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1110.Delete Nodes And Return Forest/README.md b/solution/1100-1199/1110.Delete Nodes And Return Forest/README.md index ff913fb594cba..974350fa37036 100644 --- a/solution/1100-1199/1110.Delete Nodes And Return Forest/README.md +++ b/solution/1100-1199/1110.Delete Nodes And Return Forest/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们先用哈希表或者一个长度为 $1001$ 的数组 $s$ 记录所有需要删除的节点。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -94,10 +88,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -148,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -196,8 +184,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -237,8 +223,6 @@ func delNodes(root *TreeNode, to_delete []int) (ans []*TreeNode) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -284,10 +268,6 @@ function delNodes(root: TreeNode | null, to_delete: number[]): Array + + diff --git a/solution/1100-1199/1110.Delete Nodes And Return Forest/README_EN.md b/solution/1100-1199/1110.Delete Nodes And Return Forest/README_EN.md index 299f7e0cc6428..c8994697eeb0f 100644 --- a/solution/1100-1199/1110.Delete Nodes And Return Forest/README_EN.md +++ b/solution/1100-1199/1110.Delete Nodes And Return Forest/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS First, we use a hash table or an array of length 1001, `s`, to record all nodes that need to be deleted. @@ -52,8 +52,6 @@ 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: @@ -84,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -136,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -184,8 +178,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -225,8 +217,6 @@ func delNodes(root *TreeNode, to_delete []int) (ans []*TreeNode) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -272,10 +262,6 @@ function delNodes(root: TreeNode | null, to_delete: number[]): Array + + diff --git a/solution/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README.md b/solution/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README.md index af4cfdd07502c..2637e27cfba61 100644 --- a/solution/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README.md +++ b/solution/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README.md @@ -84,9 +84,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们用一个变量 $x$ 维护当前括号的平衡度,也就是左括号的数量减去右括号的数量。 @@ -96,10 +94,6 @@ -### **Python3** - - - ```python class Solution: def maxDepthAfterSplit(self, seq: str) -> List[int]: @@ -115,10 +109,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] maxDepthAfterSplit(String seq) { @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func maxDepthAfterSplit(seq string) []int { n := len(seq) @@ -175,8 +161,6 @@ func maxDepthAfterSplit(seq string) []int { } ``` -### **TypeScript** - ```ts function maxDepthAfterSplit(seq: string): number[] { const n = seq.length; @@ -192,10 +176,6 @@ function maxDepthAfterSplit(seq: string): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README_EN.md b/solution/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README_EN.md index c8a317e9f5fdf..5f2587395ef6e 100644 --- a/solution/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README_EN.md +++ b/solution/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README_EN.md @@ -54,7 +54,7 @@ ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy We use a variable $x$ to maintain the current balance of parentheses, which is the number of left parentheses minus the number of right parentheses. @@ -64,8 +64,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $seq$. Igno -### **Python3** - ```python class Solution: def maxDepthAfterSplit(self, seq: str) -> List[int]: @@ -81,8 +79,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] maxDepthAfterSplit(String seq) { @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +114,6 @@ public: }; ``` -### **Go** - ```go func maxDepthAfterSplit(seq string) []int { n := len(seq) @@ -139,8 +131,6 @@ func maxDepthAfterSplit(seq string) []int { } ``` -### **TypeScript** - ```ts function maxDepthAfterSplit(seq: string): number[] { const n = seq.length; @@ -156,10 +146,6 @@ function maxDepthAfterSplit(seq: string): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1112.Highest Grade For Each Student/README.md b/solution/1100-1199/1112.Highest Grade For Each Student/README.md index 429886536dd4a..e2f840a6ad1f5 100644 --- a/solution/1100-1199/1112.Highest Grade For Each Student/README.md +++ b/solution/1100-1199/1112.Highest Grade For Each Student/README.md @@ -56,20 +56,12 @@ Enrollments 表: ## 解法 - - -**方法一:RANK() OVER() 窗口函数** +### 方法一:RANK() OVER() 窗口函数 我们可以使用 `RANK() OVER()` 窗口函数,按照每个学生的成绩降序排列,如果成绩相同,按照课程号升序排列,然后取每个学生排名为 $1$ 的记录。 -**方法二:子查询** - -我们可以先查询每个学生的最高成绩,然后再查询每个学生的最高成绩对应的最小课程号。 - -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -88,6 +80,14 @@ WHERE rk = 1 ORDER BY student_id; ``` + + +### 方法二:子查询 + +我们可以先查询每个学生的最高成绩,然后再查询每个学生的最高成绩对应的最小课程号。 + + + ```sql # Write your MySQL query statement below SELECT student_id, MIN(course_id) AS course_id, grade @@ -103,3 +103,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1100-1199/1112.Highest Grade For Each Student/README_EN.md b/solution/1100-1199/1112.Highest Grade For Each Student/README_EN.md index 5d6dca731aac7..fc882657f5907 100644 --- a/solution/1100-1199/1112.Highest Grade For Each Student/README_EN.md +++ b/solution/1100-1199/1112.Highest Grade For Each Student/README_EN.md @@ -55,18 +55,12 @@ Enrollments table: ## Solutions -**Solution 1: RANK() OVER() Window Function** +### Solution 1: RANK() OVER() Window Function We can use the `RANK() OVER()` window function to sort the grades of each student in descending order. If the grades are the same, we sort them in ascending order by course number, and then select the record with a rank of $1$ for each student. -**Solution 2: Subquery** - -We can first query the highest grade of each student, and then query the minimum course number corresponding to the highest grade of each student. - -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -85,6 +79,14 @@ WHERE rk = 1 ORDER BY student_id; ``` + + +### Solution 2: Subquery + +We can first query the highest grade of each student, and then query the minimum course number corresponding to the highest grade of each student. + + + ```sql # Write your MySQL query statement below SELECT student_id, MIN(course_id) AS course_id, grade @@ -100,3 +102,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1100-1199/1113.Reported Posts/README.md b/solution/1100-1199/1113.Reported Posts/README.md index 8f9b88cb38ba5..9bf91e6b7ec8e 100644 --- a/solution/1100-1199/1113.Reported Posts/README.md +++ b/solution/1100-1199/1113.Reported Posts/README.md @@ -68,12 +68,10 @@ Actions table: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT extra AS report_reason, COUNT(DISTINCT post_id) AS report_count @@ -83,3 +81,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1100-1199/1113.Reported Posts/README_EN.md b/solution/1100-1199/1113.Reported Posts/README_EN.md index 3a704eba98253..82db11efc01b9 100644 --- a/solution/1100-1199/1113.Reported Posts/README_EN.md +++ b/solution/1100-1199/1113.Reported Posts/README_EN.md @@ -65,9 +65,9 @@ Actions table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -78,3 +78,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1100-1199/1114.Print in Order/README.md b/solution/1100-1199/1114.Print in Order/README.md index 4e87dd2939b09..a7e820c38e9b3 100644 --- a/solution/1100-1199/1114.Print in Order/README.md +++ b/solution/1100-1199/1114.Print in Order/README.md @@ -63,9 +63,7 @@ public class Foo { ## 解法 - - -**方法一:多线程 + 锁或信号量** +### 方法一:多线程 + 锁或信号量 我们可以用三个信号量 $a$, $b$, $c$ 来控制三个线程的执行顺序,初始时 $a$ 信号量的计数为 $1$,$b$ 和 $c$ 的计数为 $0$。 @@ -79,10 +77,6 @@ public class Foo { -### **Python3** - - - ```python class Foo: def __init__(self): @@ -105,39 +99,6 @@ class Foo: printThird() ``` -```python -from threading import Semaphore - - -class Foo: - def __init__(self): - self.a = Semaphore(1) - self.b = Semaphore(0) - self.c = Semaphore(0) - - def first(self, printFirst: 'Callable[[], None]') -> None: - self.a.acquire() - # printFirst() outputs "first". Do not change or remove this line. - printFirst() - self.b.release() - - def second(self, printSecond: 'Callable[[], None]') -> None: - self.b.acquire() - # printSecond() outputs "second". Do not change or remove this line. - printSecond() - self.c.release() - - def third(self, printThird: 'Callable[[], None]') -> None: - self.c.acquire() - # printThird() outputs "third". Do not change or remove this line. - printThird() - self.a.release() -``` - -### **Java** - - - ```java class Foo { private Semaphore a = new Semaphore(1); @@ -170,8 +131,6 @@ class Foo { } ``` -### **C++** - ```cpp class Foo { private: @@ -201,6 +160,41 @@ public: }; ``` + + +### 方法二 + + + +```python +from threading import Semaphore + + +class Foo: + def __init__(self): + self.a = Semaphore(1) + self.b = Semaphore(0) + self.c = Semaphore(0) + + def first(self, printFirst: 'Callable[[], None]') -> None: + self.a.acquire() + # printFirst() outputs "first". Do not change or remove this line. + printFirst() + self.b.release() + + def second(self, printSecond: 'Callable[[], None]') -> None: + self.b.acquire() + # printSecond() outputs "second". Do not change or remove this line. + printSecond() + self.c.release() + + def third(self, printThird: 'Callable[[], None]') -> None: + self.c.acquire() + # printThird() outputs "third". Do not change or remove this line. + printThird() + self.a.release() +``` + ```cpp #include @@ -238,10 +232,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1114.Print in Order/README_EN.md b/solution/1100-1199/1114.Print in Order/README_EN.md index bb228bdac50be..ee001f874418c 100644 --- a/solution/1100-1199/1114.Print in Order/README_EN.md +++ b/solution/1100-1199/1114.Print in Order/README_EN.md @@ -46,7 +46,7 @@ public class Foo { ## Solutions -**Solution 1: Multithreading + Lock or Semaphore** +### Solution 1: Multithreading + Lock or Semaphore We can use three semaphores $a$, $b$, and $c$ to control the execution order of the three threads. Initially, the count of semaphore $a$ is $1$, and the counts of $b$ and $c$ are $0$. @@ -60,8 +60,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Foo: def __init__(self): @@ -84,37 +82,6 @@ class Foo: printThird() ``` -```python -from threading import Semaphore - - -class Foo: - def __init__(self): - self.a = Semaphore(1) - self.b = Semaphore(0) - self.c = Semaphore(0) - - def first(self, printFirst: 'Callable[[], None]') -> None: - self.a.acquire() - # printFirst() outputs "first". Do not change or remove this line. - printFirst() - self.b.release() - - def second(self, printSecond: 'Callable[[], None]') -> None: - self.b.acquire() - # printSecond() outputs "second". Do not change or remove this line. - printSecond() - self.c.release() - - def third(self, printThird: 'Callable[[], None]') -> None: - self.c.acquire() - # printThird() outputs "third". Do not change or remove this line. - printThird() - self.a.release() -``` - -### **Java** - ```java class Foo { private Semaphore a = new Semaphore(1); @@ -147,8 +114,6 @@ class Foo { } ``` -### **C++** - ```cpp class Foo { private: @@ -178,6 +143,41 @@ public: }; ``` + + +### Solution 2 + + + +```python +from threading import Semaphore + + +class Foo: + def __init__(self): + self.a = Semaphore(1) + self.b = Semaphore(0) + self.c = Semaphore(0) + + def first(self, printFirst: 'Callable[[], None]') -> None: + self.a.acquire() + # printFirst() outputs "first". Do not change or remove this line. + printFirst() + self.b.release() + + def second(self, printSecond: 'Callable[[], None]') -> None: + self.b.acquire() + # printSecond() outputs "second". Do not change or remove this line. + printSecond() + self.c.release() + + def third(self, printThird: 'Callable[[], None]') -> None: + self.c.acquire() + # printThird() outputs "third". Do not change or remove this line. + printThird() + self.a.release() +``` + ```cpp #include @@ -215,10 +215,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1115.Print FooBar Alternately/README.md b/solution/1100-1199/1115.Print FooBar Alternately/README.md index a7e823454512d..8e117287b1e05 100644 --- a/solution/1100-1199/1115.Print FooBar Alternately/README.md +++ b/solution/1100-1199/1115.Print FooBar Alternately/README.md @@ -61,9 +61,7 @@ class FooBar { ## 解法 - - -**方法一:多线程 + 信号量** +### 方法一:多线程 + 信号量 我们用两个信号量 $f$ 和 $b$ 来控制两个线程的执行顺序,其中 $f$ 初始值为 $1$,而 $b$ 初始值为 $0$,表示线程 $A$ 先执行。 @@ -77,10 +75,6 @@ class FooBar { -### **Python3** - - - ```python from threading import Semaphore @@ -106,10 +100,6 @@ class FooBar: self.f.release() ``` -### **Java** - - - ```java class FooBar { private int n; @@ -140,8 +130,6 @@ class FooBar { } ``` -### **C++** - ```cpp #include @@ -177,10 +165,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1115.Print FooBar Alternately/README_EN.md b/solution/1100-1199/1115.Print FooBar Alternately/README_EN.md index 24620014b5f47..d68d95c61a378 100644 --- a/solution/1100-1199/1115.Print FooBar Alternately/README_EN.md +++ b/solution/1100-1199/1115.Print FooBar Alternately/README_EN.md @@ -58,7 +58,7 @@ class FooBar { ## Solutions -**Solution 1: Multithreading + Semaphore** +### Solution 1: Multithreading + Semaphore We use two semaphores $f$ and $b$ to control the execution order of the two threads, where $f$ is initially set to $1$ and $b$ is set to $0$, indicating that thread $A$ executes first. @@ -72,8 +72,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. -### **Python3** - ```python from threading import Semaphore @@ -99,8 +97,6 @@ class FooBar: self.f.release() ``` -### **Java** - ```java class FooBar { private int n; @@ -131,8 +127,6 @@ class FooBar { } ``` -### **C++** - ```cpp #include @@ -168,10 +162,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1116.Print Zero Even Odd/README.md b/solution/1100-1199/1116.Print Zero Even Odd/README.md index df116bdfd4323..05ec1850c5acf 100644 --- a/solution/1100-1199/1116.Print Zero Even Odd/README.md +++ b/solution/1100-1199/1116.Print Zero Even Odd/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:多线程 + 信号量** +### 方法一:多线程 + 信号量 我们用三个信号量 $z$, $e$, $o$ 来控制三个线程的执行顺序,其中 $z$ 的初始值为 $1$,$e$ 和 $o$ 的初始值为 $0$。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python from threading import Semaphore @@ -110,10 +104,6 @@ class ZeroEvenOdd: self.z.release() ``` -### **Java** - - - ```java class ZeroEvenOdd { private int n; @@ -156,8 +146,6 @@ class ZeroEvenOdd { } ``` -### **C++** - ```cpp #include @@ -205,10 +193,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1116.Print Zero Even Odd/README_EN.md b/solution/1100-1199/1116.Print Zero Even Odd/README_EN.md index e47dd4495560e..3c7647e9be79e 100644 --- a/solution/1100-1199/1116.Print Zero Even Odd/README_EN.md +++ b/solution/1100-1199/1116.Print Zero Even Odd/README_EN.md @@ -56,7 +56,7 @@ One of them calls zero(), the other calls even(), and the last one calls odd(). ## Solutions -**Solution 1: Multithreading + Semaphore** +### Solution 1: Multithreading + Semaphore We use three semaphores $z$, $e$, and $o$ to control the execution order of the three threads, where $z$ is initially set to $1$, and $e$ and $o$ are set to $0$. @@ -68,8 +68,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. -### **Python3** - ```python from threading import Semaphore @@ -104,8 +102,6 @@ class ZeroEvenOdd: self.z.release() ``` -### **Java** - ```java class ZeroEvenOdd { private int n; @@ -148,8 +144,6 @@ class ZeroEvenOdd { } ``` -### **C++** - ```cpp #include @@ -197,10 +191,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1117.Building H2O/README.md b/solution/1100-1199/1117.Building H2O/README.md index a23e7fb0b47b1..9b64c773b5cc7 100644 --- a/solution/1100-1199/1117.Building H2O/README.md +++ b/solution/1100-1199/1117.Building H2O/README.md @@ -57,14 +57,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python from threading import Semaphore @@ -88,10 +84,6 @@ class H2O: self.h.release(2) ``` -### **Java** - - - ```java class H2O { private Semaphore h = new Semaphore(2); @@ -116,8 +108,6 @@ class H2O { } ``` -### **C++** - ```cpp #include @@ -154,10 +144,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1117.Building H2O/README_EN.md b/solution/1100-1199/1117.Building H2O/README_EN.md index 24e91bd6c38a3..77766ef600826 100644 --- a/solution/1100-1199/1117.Building H2O/README_EN.md +++ b/solution/1100-1199/1117.Building H2O/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python from threading import Semaphore @@ -76,8 +76,6 @@ class H2O: self.h.release(2) ``` -### **Java** - ```java class H2O { private Semaphore h = new Semaphore(2); @@ -102,8 +100,6 @@ class H2O { } ``` -### **C++** - ```cpp #include @@ -140,10 +136,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1118.Number of Days in a Month/README.md b/solution/1100-1199/1118.Number of Days in a Month/README.md index 99bbd85e89beb..91d1d5ed94f37 100644 --- a/solution/1100-1199/1118.Number of Days in a Month/README.md +++ b/solution/1100-1199/1118.Number of Days in a Month/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:判断闰年** +### 方法一:判断闰年 我们可以先判断给定的年份是否为闰年,如果年份能被 $4$ 整除但不能被 $100$ 整除,或者能被 $400$ 整除,那么这一年就是闰年。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def numberOfDays(self, year: int, month: int) -> int: @@ -68,10 +62,6 @@ class Solution: return days[month] ``` -### **Java** - - - ```java class Solution { public int numberOfDays(int year, int month) { @@ -82,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +83,6 @@ public: }; ``` -### **Go** - ```go func numberOfDays(year int, month int) int { leap := (year%4 == 0 && year%100 != 0) || (year%400 == 0) @@ -109,8 +95,6 @@ func numberOfDays(year int, month int) int { } ``` -### **TypeScript** - ```ts function numberOfDays(year: number, month: number): number { const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; @@ -119,10 +103,6 @@ function numberOfDays(year: number, month: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1118.Number of Days in a Month/README_EN.md b/solution/1100-1199/1118.Number of Days in a Month/README_EN.md index ef7d5982ca0a4..b6e5f86670465 100644 --- a/solution/1100-1199/1118.Number of Days in a Month/README_EN.md +++ b/solution/1100-1199/1118.Number of Days in a Month/README_EN.md @@ -27,7 +27,7 @@ ## Solutions -**Solution 1: Determine Leap Year** +### Solution 1: Determine Leap Year We can first determine whether the given year is a leap year. If the year can be divided by $4$ but not by $100$, or can be divided by $400$, then this year is a leap year. @@ -39,8 +39,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def numberOfDays(self, year: int, month: int) -> int: @@ -49,8 +47,6 @@ class Solution: return days[month] ``` -### **Java** - ```java class Solution { public int numberOfDays(int year, int month) { @@ -61,8 +57,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -74,8 +68,6 @@ public: }; ``` -### **Go** - ```go func numberOfDays(year int, month int) int { leap := (year%4 == 0 && year%100 != 0) || (year%400 == 0) @@ -88,8 +80,6 @@ func numberOfDays(year int, month int) int { } ``` -### **TypeScript** - ```ts function numberOfDays(year: number, month: number): number { const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; @@ -98,10 +88,6 @@ function numberOfDays(year: number, month: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1119.Remove Vowels from a String/README.md b/solution/1100-1199/1119.Remove Vowels from a String/README.md index b7a48af684a9a..f06bd96e5df6e 100644 --- a/solution/1100-1199/1119.Remove Vowels from a String/README.md +++ b/solution/1100-1199/1119.Remove Vowels from a String/README.md @@ -35,9 +35,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们直接按照题目要求,遍历字符串,将不是元音字母的字符拼接到结果字符串中即可。 @@ -45,20 +43,12 @@ -### **Python3** - - - ```python class Solution: def removeVowels(self, s: str) -> str: return "".join(c for c in s if c not in "aeiou") ``` -### **Java** - - - ```java class Solution { public String removeVowels(String s) { @@ -74,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +79,6 @@ public: }; ``` -### **Go** - ```go func removeVowels(s string) string { ans := []rune{} @@ -105,10 +91,12 @@ func removeVowels(s string) string { } ``` -### **...** - -``` - +```ts +function removeVowels(s: string): string { + return s.replace(/[aeiou]/g, ''); +} ``` + + diff --git a/solution/1100-1199/1119.Remove Vowels from a String/README_EN.md b/solution/1100-1199/1119.Remove Vowels from a String/README_EN.md index 01cfb53f1bc79..88e5584359851 100644 --- a/solution/1100-1199/1119.Remove Vowels from a String/README_EN.md +++ b/solution/1100-1199/1119.Remove Vowels from a String/README_EN.md @@ -31,7 +31,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can directly traverse the string according to the requirements of the problem, and append characters that are not vowels to the result string. @@ -39,16 +39,12 @@ The time complexity is $O(n)$, where $n$ is the length of the string. Ignoring t -### **Python3** - ```python class Solution: def removeVowels(self, s: str) -> str: return "".join(c for c in s if c not in "aeiou") ``` -### **Java** - ```java class Solution { public String removeVowels(String s) { @@ -64,8 +60,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -81,8 +75,6 @@ public: }; ``` -### **Go** - ```go func removeVowels(s string) string { ans := []rune{} @@ -95,10 +87,12 @@ func removeVowels(s string) string { } ``` -### **...** - -``` - +```ts +function removeVowels(s: string): string { + return s.replace(/[aeiou]/g, ''); +} ``` + + diff --git a/solution/1100-1199/1120.Maximum Average Subtree/README.md b/solution/1100-1199/1120.Maximum Average Subtree/README.md index 290ea28c6e8e4..a6ea1215fbb03 100644 --- a/solution/1100-1199/1120.Maximum Average Subtree/README.md +++ b/solution/1100-1199/1120.Maximum Average Subtree/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们可以使用递归的方法,对于每个节点,计算以该节点为根的子树的节点和以及节点个数,然后计算平均值,与当前最大值比较,更新最大值。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -165,8 +153,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -193,10 +179,6 @@ func maximumAverageSubtree(root *TreeNode) (ans float64) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1120.Maximum Average Subtree/README_EN.md b/solution/1100-1199/1120.Maximum Average Subtree/README_EN.md index 34d12c67079ff..57ae6ea06ed32 100644 --- a/solution/1100-1199/1120.Maximum Average Subtree/README_EN.md +++ b/solution/1100-1199/1120.Maximum Average Subtree/README_EN.md @@ -40,7 +40,7 @@ So the answer is 6 which is the maximum. ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion We can use a recursive method. For each node, we calculate the sum and count of the nodes in the subtree rooted at that node, then calculate the average, compare it with the current maximum, and update the maximum if necessary. @@ -58,8 +58,6 @@ 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: @@ -85,8 +83,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -125,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -160,8 +154,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -188,10 +180,6 @@ func maximumAverageSubtree(root *TreeNode) (ans float64) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README.md b/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README.md index ec0323ea9efdd..f3ab09550414a 100644 --- a/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README.md +++ b/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 我们假设可以将数组分成 $m$ 个长度至少为 $k$ 的严格递增子序列,如果数组中出现次数最多的数字的个数为 $cnt$,那么这 $cnt$ 个数字必须在不同的子序列中,所以 $m \geq cnt$,又因为 $m$ 个子序列的长度至少为 $k$,因此,子序列的个数越少越好,所以 $m = cnt$。那么 $cnt \times k \leq n$,才能满足题意。因此,我们只需要统计数组中出现次数最多的数字的个数 $cnt$,然后判断 $cnt \times k \leq n$ 即可。如果是,返回 `true`,否则返回 `false`。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python class Solution: def canDivideIntoSubsequences(self, nums: List[int], k: int) -> bool: @@ -59,10 +53,6 @@ class Solution: return mx * k <= len(nums) ``` -### **Java** - - - ```java class Solution { public boolean canDivideIntoSubsequences(int[] nums, int k) { @@ -76,25 +66,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canDivideIntoSubsequences(int[] nums, int k) { - int cnt = 0; - int a = 0; - for (int b : nums) { - cnt = a == b ? cnt + 1 : 1; - if (cnt * k > nums.length) { - return false; - } - a = b; - } - return true; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -113,8 +84,6 @@ public: }; ``` -### **Go** - ```go func canDivideIntoSubsequences(nums []int, k int) bool { cnt, a := 0, 0 @@ -132,10 +101,29 @@ func canDivideIntoSubsequences(nums []int, k int) bool { } ``` -### **...** + + +### 方法二 -``` + +```java +class Solution { + public boolean canDivideIntoSubsequences(int[] nums, int k) { + int cnt = 0; + int a = 0; + for (int b : nums) { + cnt = a == b ? cnt + 1 : 1; + if (cnt * k > nums.length) { + return false; + } + a = b; + } + return true; + } +} ``` + + diff --git a/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README_EN.md b/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README_EN.md index f26f732ef5c81..b41654204c472 100644 --- a/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README_EN.md +++ b/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Quick Thinking** +### Solution 1: Quick Thinking We assume that the array can be divided into $m$ strictly increasing subsequences of length at least $k$. If the number of the most frequent number in the array is $cnt$, then these $cnt$ numbers must be in different subsequences, so $m \geq cnt$. Also, since the length of $m$ subsequences is at least $k$, the fewer the number of subsequences, the better, so $m = cnt$. Therefore, $cnt \times k \leq n$ must be satisfied. Hence, we only need to count the number of the most frequent number $cnt$ in the array, and then judge whether $cnt \times k \leq n$. If it is, return `true`, otherwise return `false`. @@ -42,8 +42,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is -### **Python3** - ```python class Solution: def canDivideIntoSubsequences(self, nums: List[int], k: int) -> bool: @@ -51,8 +49,6 @@ class Solution: return mx * k <= len(nums) ``` -### **Java** - ```java class Solution { public boolean canDivideIntoSubsequences(int[] nums, int k) { @@ -66,25 +62,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canDivideIntoSubsequences(int[] nums, int k) { - int cnt = 0; - int a = 0; - for (int b : nums) { - cnt = a == b ? cnt + 1 : 1; - if (cnt * k > nums.length) { - return false; - } - a = b; - } - return true; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -103,8 +80,6 @@ public: }; ``` -### **Go** - ```go func canDivideIntoSubsequences(nums []int, k int) bool { cnt, a := 0, 0 @@ -122,10 +97,29 @@ func canDivideIntoSubsequences(nums []int, k int) bool { } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + public boolean canDivideIntoSubsequences(int[] nums, int k) { + int cnt = 0; + int a = 0; + for (int b : nums) { + cnt = a == b ? cnt + 1 : 1; + if (cnt * k > nums.length) { + return false; + } + a = b; + } + return true; + } +} ``` + + diff --git a/solution/1100-1199/1122.Relative Sort Array/README.md b/solution/1100-1199/1122.Relative Sort Array/README.md index 4d70ed1fce603..95b6e76f49752 100644 --- a/solution/1100-1199/1122.Relative Sort Array/README.md +++ b/solution/1100-1199/1122.Relative Sort Array/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:自定义排序** +### 方法一:自定义排序 我们先用哈希表 $pos$ 记录数组 $arr2$ 中每个元素的位置。然后,我们将数组 $arr1$ 中的每个元素映射成一个二元组 $(pos.get(x, 1000 + x), x)$,并对二元组进行排序。最后我们取出所有二元组的第二个元素并返回即可。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: @@ -60,10 +54,6 @@ class Solution: return sorted(arr1, key=lambda x: pos.get(x, 1000 + x)) ``` -### **Java** - - - ```java class Solution { public int[] relativeSortArray(int[] arr1, int[] arr2) { @@ -84,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +96,6 @@ public: }; ``` -### **Go** - ```go func relativeSortArray(arr1 []int, arr2 []int) []int { pos := map[int]int{} @@ -134,8 +120,6 @@ func relativeSortArray(arr1 []int, arr2 []int) []int { } ``` -### **TypeScript** - ```ts function relativeSortArray(arr1: number[], arr2: number[]): number[] { const pos: Map = new Map(); @@ -152,10 +136,6 @@ function relativeSortArray(arr1: number[], arr2: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1122.Relative Sort Array/README_EN.md b/solution/1100-1199/1122.Relative Sort Array/README_EN.md index e025a33b6b7ff..bfa9e543a7c35 100644 --- a/solution/1100-1199/1122.Relative Sort Array/README_EN.md +++ b/solution/1100-1199/1122.Relative Sort Array/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Custom Sorting** +### Solution 1: Custom Sorting First, we use a hash table $pos$ to record the position of each element in array $arr2$. Then, we map each element in array $arr1$ to a tuple $(pos.get(x, 1000 + x), x)$, and sort these tuples. Finally, we take out the second element of all tuples and return it. @@ -43,8 +43,6 @@ The time complexity is $O(n \times \log n + m)$, and the space complexity is $O( -### **Python3** - ```python class Solution: def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: @@ -52,8 +50,6 @@ class Solution: return sorted(arr1, key=lambda x: pos.get(x, 1000 + x)) ``` -### **Java** - ```java class Solution { public int[] relativeSortArray(int[] arr1, int[] arr2) { @@ -74,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +92,6 @@ public: }; ``` -### **Go** - ```go func relativeSortArray(arr1 []int, arr2 []int) []int { pos := map[int]int{} @@ -124,8 +116,6 @@ func relativeSortArray(arr1 []int, arr2 []int) []int { } ``` -### **TypeScript** - ```ts function relativeSortArray(arr1: number[], arr2: number[]): number[] { const pos: Map = new Map(); @@ -142,10 +132,6 @@ function relativeSortArray(arr1: number[], arr2: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1123.Lowest Common Ancestor of Deepest Leaves/README.md b/solution/1100-1199/1123.Lowest Common Ancestor of Deepest Leaves/README.md index dfabbe30bb377..ce8e72493469a 100644 --- a/solution/1100-1199/1123.Lowest Common Ancestor of Deepest Leaves/README.md +++ b/solution/1100-1199/1123.Lowest Common Ancestor of Deepest Leaves/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们设计一个函数 $dfs(root)$,它将返回一个二元组 $(l, d)$,其中 $l$ 是节点 $root$ 的最深公共祖先,而 $d$ 是节点 $root$ 的深度。函数 $dfs(root)$ 的执行逻辑如下: @@ -74,10 +72,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -101,10 +95,6 @@ class Solution: return dfs(root)[0] ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -181,8 +169,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -217,8 +203,6 @@ func lcaDeepestLeaves(root *TreeNode) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -253,10 +237,6 @@ function lcaDeepestLeaves(root: TreeNode | null): TreeNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1123.Lowest Common Ancestor of Deepest Leaves/README_EN.md b/solution/1100-1199/1123.Lowest Common Ancestor of Deepest Leaves/README_EN.md index 784172802470c..29035dfb110fb 100644 --- a/solution/1100-1199/1123.Lowest Common Ancestor of Deepest Leaves/README_EN.md +++ b/solution/1100-1199/1123.Lowest Common Ancestor of Deepest Leaves/README_EN.md @@ -54,7 +54,7 @@ Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We design a function `dfs(root)` that returns a tuple `(l, d)`, where `l` is the deepest common ancestor of node `root`, and `d` is the depth of node `root`. The execution logic of the function `dfs(root)` is as follows: @@ -67,8 +67,6 @@ 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: @@ -92,8 +90,6 @@ class Solution: return dfs(root)[0] ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -133,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -170,8 +164,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -206,8 +198,6 @@ func lcaDeepestLeaves(root *TreeNode) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -242,10 +232,6 @@ function lcaDeepestLeaves(root: TreeNode | null): TreeNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1124.Longest Well-Performing Interval/README.md b/solution/1100-1199/1124.Longest Well-Performing Interval/README.md index 2d017fd47e2f0..01d2f8e913f0b 100644 --- a/solution/1100-1199/1124.Longest Well-Performing Interval/README.md +++ b/solution/1100-1199/1124.Longest Well-Performing Interval/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:前缀和 + 哈希表** +### 方法一:前缀和 + 哈希表 我们可以利用前缀和的思想,维护一个变量 $s$,表示从下标 $0$ 到当前下标的这一段,「劳累的天数」与「不劳累的天数」的差值。如果 $s$ 大于 $0$,说明从下标 $0$ 到当前下标的这一段,满足「表现良好的时间段」。另外,用哈希表 $pos$ 记录每个 $s$ 第一次出现的下标。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def longestWPI(self, hours: List[int]) -> int: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestWPI(int[] hours) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func longestWPI(hours []int) (ans int) { s := 0 @@ -151,10 +137,6 @@ func longestWPI(hours []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1124.Longest Well-Performing Interval/README_EN.md b/solution/1100-1199/1124.Longest Well-Performing Interval/README_EN.md index 6c734fee9a2a1..d9887044e59b2 100644 --- a/solution/1100-1199/1124.Longest Well-Performing Interval/README_EN.md +++ b/solution/1100-1199/1124.Longest Well-Performing Interval/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Prefix Sum + Hash Table** +### Solution 1: Prefix Sum + Hash Table We can use the idea of prefix sum, maintaining a variable $s$, which represents the difference between the number of "tiring days" and "non-tiring days" from index $0$ to the current index. If $s$ is greater than $0$, it means that the segment from index $0$ to the current index is a "well-performing time period". In addition, we use a hash table $pos$ to record the first occurrence index of each $s$. @@ -54,8 +54,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def longestWPI(self, hours: List[int]) -> int: @@ -72,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestWPI(int[] hours) { @@ -93,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func longestWPI(hours []int) (ans int) { s := 0 @@ -142,10 +134,6 @@ func longestWPI(hours []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1125.Smallest Sufficient Team/README.md b/solution/1100-1199/1125.Smallest Sufficient Team/README.md index a5f585e2883c1..ce167b9adf81f 100644 --- a/solution/1100-1199/1125.Smallest Sufficient Team/README.md +++ b/solution/1100-1199/1125.Smallest Sufficient Team/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:状态压缩动态规划** +### 方法一:状态压缩动态规划 我们注意到,技能清单 `req_skills` 的长度不超过 $16$,因此,我们可以用一个长度不超过 $16$ 的二进制数来表示每一种技能是否被掌握。不妨记数组 `req_skills` 的长度为 $m$,数组 `people` 的长度为 $n$。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def smallestSufficientTeam( @@ -111,10 +105,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] smallestSufficientTeam(String[] req_skills, List> people) { @@ -157,8 +147,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -201,8 +189,6 @@ public: }; ``` -### **Go** - ```go func smallestSufficientTeam(req_skills []string, people [][]string) (ans []int) { d := map[string]int{} @@ -243,8 +229,6 @@ func smallestSufficientTeam(req_skills []string, people [][]string) (ans []int) } ``` -### **TypeScript** - ```ts function smallestSufficientTeam(req_skills: string[], people: string[][]): number[] { const d: Map = new Map(); @@ -284,10 +268,6 @@ function smallestSufficientTeam(req_skills: string[], people: string[][]): numbe } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1125.Smallest Sufficient Team/README_EN.md b/solution/1100-1199/1125.Smallest Sufficient Team/README_EN.md index 59a1f88209a66..d301ac87b70ef 100644 --- a/solution/1100-1199/1125.Smallest Sufficient Team/README_EN.md +++ b/solution/1100-1199/1125.Smallest Sufficient Team/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: State Compression Dynamic Programming** +### Solution 1: State Compression Dynamic Programming We notice that the length of `req_skills` does not exceed $16$, so we can use a binary number of length no more than $16$ to represent whether each skill is mastered. Let's denote the length of `req_skills` as $m$ and the length of `people` as $n$. @@ -65,8 +65,6 @@ The time complexity is $O(2^m \times n)$, and the space complexity is $O(2^m)$. -### **Python3** - ```python class Solution: def smallestSufficientTeam( @@ -98,8 +96,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] smallestSufficientTeam(String[] req_skills, List> people) { @@ -142,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -186,8 +180,6 @@ public: }; ``` -### **Go** - ```go func smallestSufficientTeam(req_skills []string, people [][]string) (ans []int) { d := map[string]int{} @@ -228,8 +220,6 @@ func smallestSufficientTeam(req_skills []string, people [][]string) (ans []int) } ``` -### **TypeScript** - ```ts function smallestSufficientTeam(req_skills: string[], people: string[][]): number[] { const d: Map = new Map(); @@ -269,10 +259,6 @@ function smallestSufficientTeam(req_skills: string[], people: string[][]): numbe } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1126.Active Businesses/README.md b/solution/1100-1199/1126.Active Businesses/README.md index 5d5031104abfd..063dca65d3611 100644 --- a/solution/1100-1199/1126.Active Businesses/README.md +++ b/solution/1100-1199/1126.Active Businesses/README.md @@ -65,12 +65,10 @@ id=1 的业务有 7 个 'reviews' 事件(多于 5 个)和 11 个 'ads' 事件( ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT business_id @@ -89,6 +87,12 @@ GROUP BY business_id HAVING COUNT(1) > 1; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below WITH @@ -106,3 +110,5 @@ HAVING COUNT(1) > 1; ``` + + diff --git a/solution/1100-1199/1126.Active Businesses/README_EN.md b/solution/1100-1199/1126.Active Businesses/README_EN.md index 512a8dc299c8e..b54402f395a0d 100644 --- a/solution/1100-1199/1126.Active Businesses/README_EN.md +++ b/solution/1100-1199/1126.Active Businesses/README_EN.md @@ -63,9 +63,9 @@ The business with id=1 has 7 'reviews' events (more than 5) and 11 ' ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -85,6 +85,12 @@ GROUP BY business_id HAVING COUNT(1) > 1; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below WITH @@ -102,3 +108,5 @@ HAVING COUNT(1) > 1; ``` + + diff --git a/solution/1100-1199/1127.User Purchase Platform/README.md b/solution/1100-1199/1127.User Purchase Platform/README.md index 96dddad57215b..fc25f0f349ad4 100644 --- a/solution/1100-1199/1127.User Purchase Platform/README.md +++ b/solution/1100-1199/1127.User Purchase Platform/README.md @@ -63,12 +63,10 @@ Spending table: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -99,3 +97,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/1100-1199/1127.User Purchase Platform/README_EN.md b/solution/1100-1199/1127.User Purchase Platform/README_EN.md index 99fcf71bc5ab4..bea7954a7cfe3 100644 --- a/solution/1100-1199/1127.User Purchase Platform/README_EN.md +++ b/solution/1100-1199/1127.User Purchase Platform/README_EN.md @@ -62,9 +62,9 @@ On 2019-07-02, user 2 purchased using mobile only, user 3 purch ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -96,3 +96,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/1100-1199/1128.Number of Equivalent Domino Pairs/README.md b/solution/1100-1199/1128.Number of Equivalent Domino Pairs/README.md index 3fd3150a88919..1ea562d67764d 100644 --- a/solution/1100-1199/1128.Number of Equivalent Domino Pairs/README.md +++ b/solution/1100-1199/1128.Number of Equivalent Domino Pairs/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们可以将每个多米诺骨牌的两个数字按照大小顺序拼接成一个两位数,这样就可以将等价的多米诺骨牌拼接成相同的两位数。例如,`[1, 2]` 和 `[2, 1]` 拼接成的两位数都是 `12`,`[3, 4]` 和 `[4, 3]` 拼接成的两位数都是 `34`。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: @@ -69,22 +63,6 @@ class Solution: return ans ``` -```python -class Solution: - def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: - cnt = Counter() - ans = 0 - for a, b in dominoes: - x = a * 10 + b if a < b else b * 10 + a - ans += cnt[x] - cnt[x] += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int numEquivDominoPairs(int[][] dominoes) { @@ -99,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +92,6 @@ public: }; ``` -### **Go** - ```go func numEquivDominoPairs(dominoes [][]int) (ans int) { cnt := [100]int{} @@ -133,10 +107,24 @@ func numEquivDominoPairs(dominoes [][]int) (ans int) { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: + cnt = Counter() + ans = 0 + for a, b in dominoes: + x = a * 10 + b if a < b else b * 10 + a + ans += cnt[x] + cnt[x] += 1 + return ans ``` + + diff --git a/solution/1100-1199/1128.Number of Equivalent Domino Pairs/README_EN.md b/solution/1100-1199/1128.Number of Equivalent Domino Pairs/README_EN.md index 2615d8ec91585..d60ab74b1e54f 100644 --- a/solution/1100-1199/1128.Number of Equivalent Domino Pairs/README_EN.md +++ b/solution/1100-1199/1128.Number of Equivalent Domino Pairs/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We can concatenate the two numbers of each domino in order of size to form a two-digit number, so that equivalent dominoes can be concatenated into the same two-digit number. For example, both `[1, 2]` and `[2, 1]` are concatenated into the two-digit number `12`, and both `[3, 4]` and `[4, 3]` are concatenated into the two-digit number `34`. @@ -44,8 +44,6 @@ The time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is -### **Python3** - ```python class Solution: def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: @@ -59,20 +57,6 @@ class Solution: return ans ``` -```python -class Solution: - def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: - cnt = Counter() - ans = 0 - for a, b in dominoes: - x = a * 10 + b if a < b else b * 10 + a - ans += cnt[x] - cnt[x] += 1 - return ans -``` - -### **Java** - ```java class Solution { public int numEquivDominoPairs(int[][] dominoes) { @@ -87,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +86,6 @@ public: }; ``` -### **Go** - ```go func numEquivDominoPairs(dominoes [][]int) (ans int) { cnt := [100]int{} @@ -121,10 +101,24 @@ func numEquivDominoPairs(dominoes [][]int) (ans int) { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: + cnt = Counter() + ans = 0 + for a, b in dominoes: + x = a * 10 + b if a < b else b * 10 + a + ans += cnt[x] + cnt[x] += 1 + return ans ``` + + diff --git a/solution/1100-1199/1129.Shortest Path with Alternating Colors/README.md b/solution/1100-1199/1129.Shortest Path with Alternating Colors/README.md index b7613712263e3..aa2f3fe3141cd 100644 --- a/solution/1100-1199/1129.Shortest Path with Alternating Colors/README.md +++ b/solution/1100-1199/1129.Shortest Path with Alternating Colors/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 题目实际上是最短路问题,我们可以考虑使用 BFS 来解决。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def shortestAlternatingPaths( @@ -103,10 +97,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) { @@ -149,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -191,8 +179,6 @@ public: }; ``` -### **Go** - ```go func shortestAlternatingPaths(n int, redEdges [][]int, blueEdges [][]int) []int { g := [2][][]int{} @@ -235,10 +221,6 @@ func shortestAlternatingPaths(n int, redEdges [][]int, blueEdges [][]int) []int } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1129.Shortest Path with Alternating Colors/README_EN.md b/solution/1100-1199/1129.Shortest Path with Alternating Colors/README_EN.md index 420fed8251699..c4f2837f82869 100644 --- a/solution/1100-1199/1129.Shortest Path with Alternating Colors/README_EN.md +++ b/solution/1100-1199/1129.Shortest Path with Alternating Colors/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: BFS** +### Solution 1: BFS The problem is essentially a shortest path problem, which we can consider solving using BFS. @@ -65,8 +65,6 @@ The time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, -### **Python3** - ```python class Solution: def shortestAlternatingPaths( @@ -95,8 +93,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) { @@ -139,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -181,8 +175,6 @@ public: }; ``` -### **Go** - ```go func shortestAlternatingPaths(n int, redEdges [][]int, blueEdges [][]int) []int { g := [2][][]int{} @@ -225,10 +217,6 @@ func shortestAlternatingPaths(n int, redEdges [][]int, blueEdges [][]int) []int } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/README.md b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/README.md index 1e95b5412f04f..fef3cc599f9b5 100644 --- a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/README.md +++ b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 根据题目描述,数组 $arr$ 中的值与树的中序遍历中每个叶节点的值一一对应,我们可以将数组划分为左右两个非空子数组,分别对应树的左右子树,递归地求解每个子树的所有非叶节点的值的最小可能总和。 @@ -82,29 +80,8 @@ $$ 时间复杂度 $O(n^3)$,空间复杂度 $O(n^2)$。其中 $n$ 为数组 $arr$ 的长度。 -**方法二:动态规划** - -我们可以将方法一中的记忆化搜索改为动态规划的方式进行求解。 - -定义 $f[i][j]$ 表示数组 $arr$ 中下标范围 $[i, j]$ 内的所有非叶节点的值的最小可能总和,而 $g[i][j]$ 表示数组 $arr$ 中下标范围 $[i, j]$ 内的所有叶节点的最大值,那么状态转移方程为: - -$$ -f[i][j] = \begin{cases} -0, & \text{if } i = j \\ -\min_{i \leq k < j} \{f[i][k] + f[k + 1][j] + g[i][k] \cdot g[k + 1][j]\}, & \text{if } i < j -\end{cases} -$$ - -最后,我们返回 $f[0][n - 1]$ 即可。 - -时间复杂度 $O(n^3)$,空间复杂度 $O(n^2)$。其中 $n$ 为数组 $arr$ 的长度。 - -### **Python3** - - - ```python class Solution: def mctFromLeafValues(self, arr: List[int]) -> int: @@ -125,46 +102,6 @@ class Solution: return dfs(0, len(arr) - 1)[0] ``` -```python -class Solution: - def mctFromLeafValues(self, arr: List[int]) -> int: - @cache - def dfs(i: int, j: int) -> int: - if i == j: - return 0 - return min( - dfs(i, k) + dfs(k + 1, j) + g[i][k] * g[k + 1][j] for k in range(i, j) - ) - - n = len(arr) - g = [[0] * n for _ in range(n)] - for i in range(n - 1, -1, -1): - g[i][i] = arr[i] - for j in range(i + 1, n): - g[i][j] = max(g[i][j - 1], arr[j]) - return dfs(0, n - 1) -``` - -```python -class Solution: - def mctFromLeafValues(self, arr: List[int]) -> int: - n = len(arr) - f = [[0] * n for _ in range(n)] - g = [[0] * n for _ in range(n)] - for i in range(n - 1, -1, -1): - g[i][i] = arr[i] - for j in range(i + 1, n): - g[i][j] = max(g[i][j - 1], arr[j]) - f[i][j] = min( - f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j] for k in range(i, j) - ) - return f[0][n - 1] -``` - -### **Java** - - - ```java class Solution { private Integer[][] f; @@ -199,29 +136,6 @@ class Solution { } ``` -```java -class Solution { - public int mctFromLeafValues(int[] arr) { - int n = arr.length; - int[][] f = new int[n][n]; - int[][] g = new int[n][n]; - for (int i = n - 1; i >= 0; --i) { - g[i][i] = arr[i]; - for (int j = i + 1; j < n; ++j) { - g[i][j] = Math.max(g[i][j - 1], arr[j]); - f[i][j] = 1 << 30; - for (int k = i; k < j; ++k) { - f[i][j] = Math.min(f[i][j], f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j]); - } - } - } - return f[0][n - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -254,31 +168,6 @@ public: }; ``` -```cpp -class Solution { -public: - int mctFromLeafValues(vector& arr) { - int n = arr.size(); - int f[n][n]; - int g[n][n]; - memset(f, 0, sizeof(f)); - for (int i = n - 1; ~i; --i) { - g[i][i] = arr[i]; - for (int j = i + 1; j < n; ++j) { - g[i][j] = max(g[i][j - 1], arr[j]); - f[i][j] = 1 << 30; - for (int k = i; k < j; ++k) { - f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j]); - } - } - } - return f[0][n - 1]; - } -}; -``` - -### **Go** - ```go func mctFromLeafValues(arr []int) int { n := len(arr) @@ -310,31 +199,6 @@ func mctFromLeafValues(arr []int) int { } ``` -```go -func mctFromLeafValues(arr []int) int { - n := len(arr) - f := make([][]int, n) - g := make([][]int, n) - for i := range g { - f[i] = make([]int, n) - g[i] = make([]int, n) - } - for i := n - 1; i >= 0; i-- { - g[i][i] = arr[i] - for j := i + 1; j < n; j++ { - g[i][j] = max(g[i][j-1], arr[j]) - f[i][j] = 1 << 30 - for k := i; k < j; k++ { - f[i][j] = min(f[i][j], f[i][k]+f[k+1][j]+g[i][k]*g[k+1][j]) - } - } - } - return f[0][n-1] -} -``` - -### **TypeScript** - ```ts function mctFromLeafValues(arr: number[]): number { const n = arr.length; @@ -363,6 +227,114 @@ function mctFromLeafValues(arr: number[]): number { } ``` + + +### 方法二:动态规划 + +我们可以将方法一中的记忆化搜索改为动态规划的方式进行求解。 + +定义 $f[i][j]$ 表示数组 $arr$ 中下标范围 $[i, j]$ 内的所有非叶节点的值的最小可能总和,而 $g[i][j]$ 表示数组 $arr$ 中下标范围 $[i, j]$ 内的所有叶节点的最大值,那么状态转移方程为: + +$$ +f[i][j] = \begin{cases} +0, & \text{if } i = j \\ +\min_{i \leq k < j} \{f[i][k] + f[k + 1][j] + g[i][k] \cdot g[k + 1][j]\}, & \text{if } i < j +\end{cases} +$$ + +最后,我们返回 $f[0][n - 1]$ 即可。 + +时间复杂度 $O(n^3)$,空间复杂度 $O(n^2)$。其中 $n$ 为数组 $arr$ 的长度。 + + + +```python +class Solution: + def mctFromLeafValues(self, arr: List[int]) -> int: + @cache + def dfs(i: int, j: int) -> int: + if i == j: + return 0 + return min( + dfs(i, k) + dfs(k + 1, j) + g[i][k] * g[k + 1][j] for k in range(i, j) + ) + + n = len(arr) + g = [[0] * n for _ in range(n)] + for i in range(n - 1, -1, -1): + g[i][i] = arr[i] + for j in range(i + 1, n): + g[i][j] = max(g[i][j - 1], arr[j]) + return dfs(0, n - 1) +``` + +```java +class Solution { + public int mctFromLeafValues(int[] arr) { + int n = arr.length; + int[][] f = new int[n][n]; + int[][] g = new int[n][n]; + for (int i = n - 1; i >= 0; --i) { + g[i][i] = arr[i]; + for (int j = i + 1; j < n; ++j) { + g[i][j] = Math.max(g[i][j - 1], arr[j]); + f[i][j] = 1 << 30; + for (int k = i; k < j; ++k) { + f[i][j] = Math.min(f[i][j], f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j]); + } + } + } + return f[0][n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int mctFromLeafValues(vector& arr) { + int n = arr.size(); + int f[n][n]; + int g[n][n]; + memset(f, 0, sizeof(f)); + for (int i = n - 1; ~i; --i) { + g[i][i] = arr[i]; + for (int j = i + 1; j < n; ++j) { + g[i][j] = max(g[i][j - 1], arr[j]); + f[i][j] = 1 << 30; + for (int k = i; k < j; ++k) { + f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j]); + } + } + } + return f[0][n - 1]; + } +}; +``` + +```go +func mctFromLeafValues(arr []int) int { + n := len(arr) + f := make([][]int, n) + g := make([][]int, n) + for i := range g { + f[i] = make([]int, n) + g[i] = make([]int, n) + } + for i := n - 1; i >= 0; i-- { + g[i][i] = arr[i] + for j := i + 1; j < n; j++ { + g[i][j] = max(g[i][j-1], arr[j]) + f[i][j] = 1 << 30 + for k := i; k < j; k++ { + f[i][j] = min(f[i][j], f[i][k]+f[k+1][j]+g[i][k]*g[k+1][j]) + } + } + } + return f[0][n-1] +} +``` + ```ts function mctFromLeafValues(arr: number[]): number { const n = arr.length; @@ -382,10 +354,28 @@ function mctFromLeafValues(arr: number[]): number { } ``` -### **...** + -``` +### 方法三 + + +```python +class Solution: + def mctFromLeafValues(self, arr: List[int]) -> int: + n = len(arr) + f = [[0] * n for _ in range(n)] + g = [[0] * n for _ in range(n)] + for i in range(n - 1, -1, -1): + g[i][i] = arr[i] + for j in range(i + 1, n): + g[i][j] = max(g[i][j - 1], arr[j]) + f[i][j] = min( + f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j] for k in range(i, j) + ) + return f[0][n - 1] ``` + + diff --git a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/README_EN.md b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/README_EN.md index 15cd00f4a8c57..1060ef1918faa 100644 --- a/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/README_EN.md +++ b/solution/1100-1199/1130.Minimum Cost Tree From Leaf Values/README_EN.md @@ -44,7 +44,7 @@ The first has a non-leaf node sum 36, and the second has non-leaf node sum 32. ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search According to the problem description, the values in the array $arr$ correspond one-to-one with the values in the inorder traversal of each leaf node of the tree. We can divide the array into two non-empty sub-arrays, corresponding to the left and right subtrees of the tree, and recursively solve for the minimum possible sum of all non-leaf node values in each subtree. @@ -77,27 +77,8 @@ Finally, we return $dfs(0, n - 1)$. The time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array $arr$. -**Solution 2: Dynamic Programming** - -We can change the memoization search in Solution 1 to dynamic programming. - -Define $f[i][j]$ to represent the minimum possible sum of all non-leaf node values in the index range $[i, j]$ of the array $arr$, and $g[i][j]$ to represent the maximum value of all leaf nodes in the index range $[i, j]$ of the array $arr$. Then, the state transition equation is: - -$$ -f[i][j] = \begin{cases} -0, & \text{if } i = j \\ -\min_{i \leq k < j} \{f[i][k] + f[k + 1][j] + g[i][k] \cdot g[k + 1][j]\}, & \text{if } i < j -\end{cases} -$$ - -Finally, we return $f[0][n - 1]$. - -The time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array $arr$. - -### **Python3** - ```python class Solution: def mctFromLeafValues(self, arr: List[int]) -> int: @@ -118,44 +99,6 @@ class Solution: return dfs(0, len(arr) - 1)[0] ``` -```python -class Solution: - def mctFromLeafValues(self, arr: List[int]) -> int: - @cache - def dfs(i: int, j: int) -> int: - if i == j: - return 0 - return min( - dfs(i, k) + dfs(k + 1, j) + g[i][k] * g[k + 1][j] for k in range(i, j) - ) - - n = len(arr) - g = [[0] * n for _ in range(n)] - for i in range(n - 1, -1, -1): - g[i][i] = arr[i] - for j in range(i + 1, n): - g[i][j] = max(g[i][j - 1], arr[j]) - return dfs(0, n - 1) -``` - -```python -class Solution: - def mctFromLeafValues(self, arr: List[int]) -> int: - n = len(arr) - f = [[0] * n for _ in range(n)] - g = [[0] * n for _ in range(n)] - for i in range(n - 1, -1, -1): - g[i][i] = arr[i] - for j in range(i + 1, n): - g[i][j] = max(g[i][j - 1], arr[j]) - f[i][j] = min( - f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j] for k in range(i, j) - ) - return f[0][n - 1] -``` - -### **Java** - ```java class Solution { private Integer[][] f; @@ -190,29 +133,6 @@ class Solution { } ``` -```java -class Solution { - public int mctFromLeafValues(int[] arr) { - int n = arr.length; - int[][] f = new int[n][n]; - int[][] g = new int[n][n]; - for (int i = n - 1; i >= 0; --i) { - g[i][i] = arr[i]; - for (int j = i + 1; j < n; ++j) { - g[i][j] = Math.max(g[i][j - 1], arr[j]); - f[i][j] = 1 << 30; - for (int k = i; k < j; ++k) { - f[i][j] = Math.min(f[i][j], f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j]); - } - } - } - return f[0][n - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -245,31 +165,6 @@ public: }; ``` -```cpp -class Solution { -public: - int mctFromLeafValues(vector& arr) { - int n = arr.size(); - int f[n][n]; - int g[n][n]; - memset(f, 0, sizeof(f)); - for (int i = n - 1; ~i; --i) { - g[i][i] = arr[i]; - for (int j = i + 1; j < n; ++j) { - g[i][j] = max(g[i][j - 1], arr[j]); - f[i][j] = 1 << 30; - for (int k = i; k < j; ++k) { - f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j]); - } - } - } - return f[0][n - 1]; - } -}; -``` - -### **Go** - ```go func mctFromLeafValues(arr []int) int { n := len(arr) @@ -301,31 +196,6 @@ func mctFromLeafValues(arr []int) int { } ``` -```go -func mctFromLeafValues(arr []int) int { - n := len(arr) - f := make([][]int, n) - g := make([][]int, n) - for i := range g { - f[i] = make([]int, n) - g[i] = make([]int, n) - } - for i := n - 1; i >= 0; i-- { - g[i][i] = arr[i] - for j := i + 1; j < n; j++ { - g[i][j] = max(g[i][j-1], arr[j]) - f[i][j] = 1 << 30 - for k := i; k < j; k++ { - f[i][j] = min(f[i][j], f[i][k]+f[k+1][j]+g[i][k]*g[k+1][j]) - } - } - } - return f[0][n-1] -} -``` - -### **TypeScript** - ```ts function mctFromLeafValues(arr: number[]): number { const n = arr.length; @@ -354,6 +224,114 @@ function mctFromLeafValues(arr: number[]): number { } ``` + + +### Solution 2: Dynamic Programming + +We can change the memoization search in Solution 1 to dynamic programming. + +Define $f[i][j]$ to represent the minimum possible sum of all non-leaf node values in the index range $[i, j]$ of the array $arr$, and $g[i][j]$ to represent the maximum value of all leaf nodes in the index range $[i, j]$ of the array $arr$. Then, the state transition equation is: + +$$ +f[i][j] = \begin{cases} +0, & \text{if } i = j \\ +\min_{i \leq k < j} \{f[i][k] + f[k + 1][j] + g[i][k] \cdot g[k + 1][j]\}, & \text{if } i < j +\end{cases} +$$ + +Finally, we return $f[0][n - 1]$. + +The time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the array $arr$. + + + +```python +class Solution: + def mctFromLeafValues(self, arr: List[int]) -> int: + @cache + def dfs(i: int, j: int) -> int: + if i == j: + return 0 + return min( + dfs(i, k) + dfs(k + 1, j) + g[i][k] * g[k + 1][j] for k in range(i, j) + ) + + n = len(arr) + g = [[0] * n for _ in range(n)] + for i in range(n - 1, -1, -1): + g[i][i] = arr[i] + for j in range(i + 1, n): + g[i][j] = max(g[i][j - 1], arr[j]) + return dfs(0, n - 1) +``` + +```java +class Solution { + public int mctFromLeafValues(int[] arr) { + int n = arr.length; + int[][] f = new int[n][n]; + int[][] g = new int[n][n]; + for (int i = n - 1; i >= 0; --i) { + g[i][i] = arr[i]; + for (int j = i + 1; j < n; ++j) { + g[i][j] = Math.max(g[i][j - 1], arr[j]); + f[i][j] = 1 << 30; + for (int k = i; k < j; ++k) { + f[i][j] = Math.min(f[i][j], f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j]); + } + } + } + return f[0][n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int mctFromLeafValues(vector& arr) { + int n = arr.size(); + int f[n][n]; + int g[n][n]; + memset(f, 0, sizeof(f)); + for (int i = n - 1; ~i; --i) { + g[i][i] = arr[i]; + for (int j = i + 1; j < n; ++j) { + g[i][j] = max(g[i][j - 1], arr[j]); + f[i][j] = 1 << 30; + for (int k = i; k < j; ++k) { + f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j]); + } + } + } + return f[0][n - 1]; + } +}; +``` + +```go +func mctFromLeafValues(arr []int) int { + n := len(arr) + f := make([][]int, n) + g := make([][]int, n) + for i := range g { + f[i] = make([]int, n) + g[i] = make([]int, n) + } + for i := n - 1; i >= 0; i-- { + g[i][i] = arr[i] + for j := i + 1; j < n; j++ { + g[i][j] = max(g[i][j-1], arr[j]) + f[i][j] = 1 << 30 + for k := i; k < j; k++ { + f[i][j] = min(f[i][j], f[i][k]+f[k+1][j]+g[i][k]*g[k+1][j]) + } + } + } + return f[0][n-1] +} +``` + ```ts function mctFromLeafValues(arr: number[]): number { const n = arr.length; @@ -373,10 +351,28 @@ function mctFromLeafValues(arr: number[]): number { } ``` -### **...** + -``` +### Solution 3 + + +```python +class Solution: + def mctFromLeafValues(self, arr: List[int]) -> int: + n = len(arr) + f = [[0] * n for _ in range(n)] + g = [[0] * n for _ in range(n)] + for i in range(n - 1, -1, -1): + g[i][i] = arr[i] + for j in range(i + 1, n): + g[i][j] = max(g[i][j - 1], arr[j]) + f[i][j] = min( + f[i][k] + f[k + 1][j] + g[i][k] * g[k + 1][j] for k in range(i, j) + ) + return f[0][n - 1] ``` + + diff --git a/solution/1100-1199/1131.Maximum of Absolute Value Expression/README.md b/solution/1100-1199/1131.Maximum of Absolute Value Expression/README.md index ad4780ec95267..4e262ede80042 100644 --- a/solution/1100-1199/1131.Maximum of Absolute Value Expression/README.md +++ b/solution/1100-1199/1131.Maximum of Absolute Value Expression/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:数学 + 枚举** +### 方法一:数学 + 枚举 我们不妨令 $x_i = arr1[i]$, $y_i = arr2[i]$,由于 $i$ 和 $j$ 的大小关系不影响表达式的值,我们不妨假设 $i \ge j$,那么表达式可以变为: @@ -57,10 +55,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int: @@ -75,10 +69,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxAbsValExpr(int[] arr1, int[] arr2) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func maxAbsValExpr(arr1 []int, arr2 []int) int { dirs := [5]int{1, -1, -1, 1, 1} @@ -145,8 +131,6 @@ func maxAbsValExpr(arr1 []int, arr2 []int) int { } ``` -### **TypeScript** - ```ts function maxAbsValExpr(arr1: number[], arr2: number[]): number { const dirs = [1, -1, -1, 1, 1]; @@ -167,10 +151,6 @@ function maxAbsValExpr(arr1: number[], arr2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1131.Maximum of Absolute Value Expression/README_EN.md b/solution/1100-1199/1131.Maximum of Absolute Value Expression/README_EN.md index 8a1191e05eb7d..b2ce06484f315 100644 --- a/solution/1100-1199/1131.Maximum of Absolute Value Expression/README_EN.md +++ b/solution/1100-1199/1131.Maximum of Absolute Value Expression/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Mathematics + Enumeration** +### Solution 1: Mathematics + Enumeration Let's denote $x_i = arr1[i]$, $y_i = arr2[i]$. Since the size relationship between $i$ and $j$ does not affect the value of the expression, we can assume $i \ge j$. Then the expression can be transformed into: @@ -54,8 +54,6 @@ Similar problems: -### **Python3** - ```python class Solution: def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int: @@ -70,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxAbsValExpr(int[] arr1, int[] arr2) { @@ -93,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func maxAbsValExpr(arr1 []int, arr2 []int) int { dirs := [5]int{1, -1, -1, 1, 1} @@ -138,8 +130,6 @@ func maxAbsValExpr(arr1 []int, arr2 []int) int { } ``` -### **TypeScript** - ```ts function maxAbsValExpr(arr1: number[], arr2: number[]): number { const dirs = [1, -1, -1, 1, 1]; @@ -160,10 +150,6 @@ function maxAbsValExpr(arr1: number[], arr2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1132.Reported Posts II/README.md b/solution/1100-1199/1132.Reported Posts II/README.md index 588d22785e073..b3e0eca39c867 100644 --- a/solution/1100-1199/1132.Reported Posts II/README.md +++ b/solution/1100-1199/1132.Reported Posts II/README.md @@ -88,12 +88,10 @@ Removals table: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -111,3 +109,5 @@ FROM T; ``` + + diff --git a/solution/1100-1199/1132.Reported Posts II/README_EN.md b/solution/1100-1199/1132.Reported Posts II/README_EN.md index afbab657cdd7a..474b7db48bbcd 100644 --- a/solution/1100-1199/1132.Reported Posts II/README_EN.md +++ b/solution/1100-1199/1132.Reported Posts II/README_EN.md @@ -87,9 +87,9 @@ Note that the output is only one number and that we do not care about the remove ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -108,3 +108,5 @@ FROM T; ``` + + diff --git a/solution/1100-1199/1133.Largest Unique Number/README.md b/solution/1100-1199/1133.Largest Unique Number/README.md index 2e9825716bf7c..2d8fa9aa62c09 100644 --- a/solution/1100-1199/1133.Largest Unique Number/README.md +++ b/solution/1100-1199/1133.Largest Unique Number/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:计数 + 倒序遍历** +### 方法一:计数 + 倒序遍历 注意到题目的数据范围,我们可以使用一个长度为 $1001$ 的数组来统计每个数字出现的次数,然后倒序遍历数组,找到第一个出现次数为 $1$ 的数字即可。如果没有找到,则返回 $-1$。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def largestUniqueNumber(self, nums: List[int]) -> int: @@ -60,17 +54,6 @@ class Solution: return next((x for x in range(1000, -1, -1) if cnt[x] == 1), -1) ``` -```python -class Solution: - def largestUniqueNumber(self, nums: List[int]) -> int: - cnt = Counter(nums) - return max((x for x, v in cnt.items() if v == 1), default=-1) -``` - -### **Java** - - - ```java class Solution { public int largestUniqueNumber(int[] nums) { @@ -88,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +89,6 @@ public: }; ``` -### **Go** - ```go func largestUniqueNumber(nums []int) int { cnt := [1001]int{} @@ -125,14 +104,8 @@ func largestUniqueNumber(nums []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var largestUniqueNumber = function (nums) { +```ts +function largestUniqueNumber(nums: number[]): number { const cnt = new Array(1001).fill(0); for (const x of nums) { ++cnt[x]; @@ -143,13 +116,15 @@ var largestUniqueNumber = function (nums) { } } return -1; -}; +} ``` -### **TypeScript** - -```ts -function largestUniqueNumber(nums: number[]): number { +```js +/** + * @param {number[]} nums + * @return {number} + */ +var largestUniqueNumber = function (nums) { const cnt = new Array(1001).fill(0); for (const x of nums) { ++cnt[x]; @@ -160,13 +135,22 @@ function largestUniqueNumber(nums: number[]): number { } } return -1; -} +}; ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def largestUniqueNumber(self, nums: List[int]) -> int: + cnt = Counter(nums) + return max((x for x, v in cnt.items() if v == 1), default=-1) ``` + + diff --git a/solution/1100-1199/1133.Largest Unique Number/README_EN.md b/solution/1100-1199/1133.Largest Unique Number/README_EN.md index 55ae2bfa7d63c..c057b0adc64a2 100644 --- a/solution/1100-1199/1133.Largest Unique Number/README_EN.md +++ b/solution/1100-1199/1133.Largest Unique Number/README_EN.md @@ -32,7 +32,7 @@ ## Solutions -**Solution 1: Counting + Reverse Traversal** +### Solution 1: Counting + Reverse Traversal Given the data range in the problem, we can use an array of length $1001$ to count the occurrence of each number. Then, we traverse the array in reverse order to find the first number that appears only once. If no such number is found, we return $-1$. @@ -40,8 +40,6 @@ The time complexity is $O(n + M)$, and the space complexity is $O(M)$. Here, $n$ -### **Python3** - ```python class Solution: def largestUniqueNumber(self, nums: List[int]) -> int: @@ -49,15 +47,6 @@ class Solution: return next((x for x in range(1000, -1, -1) if cnt[x] == 1), -1) ``` -```python -class Solution: - def largestUniqueNumber(self, nums: List[int]) -> int: - cnt = Counter(nums) - return max((x for x, v in cnt.items() if v == 1), default=-1) -``` - -### **Java** - ```java class Solution { public int largestUniqueNumber(int[] nums) { @@ -75,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +82,6 @@ public: }; ``` -### **Go** - ```go func largestUniqueNumber(nums []int) int { cnt := [1001]int{} @@ -112,14 +97,8 @@ func largestUniqueNumber(nums []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var largestUniqueNumber = function (nums) { +```ts +function largestUniqueNumber(nums: number[]): number { const cnt = new Array(1001).fill(0); for (const x of nums) { ++cnt[x]; @@ -130,13 +109,15 @@ var largestUniqueNumber = function (nums) { } } return -1; -}; +} ``` -### **TypeScript** - -```ts -function largestUniqueNumber(nums: number[]): number { +```js +/** + * @param {number[]} nums + * @return {number} + */ +var largestUniqueNumber = function (nums) { const cnt = new Array(1001).fill(0); for (const x of nums) { ++cnt[x]; @@ -147,13 +128,22 @@ function largestUniqueNumber(nums: number[]): number { } } return -1; -} +}; ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def largestUniqueNumber(self, nums: List[int]) -> int: + cnt = Counter(nums) + return max((x for x, v in cnt.items() if v == 1), default=-1) ``` + + diff --git a/solution/1100-1199/1134.Armstrong Number/README.md b/solution/1100-1199/1134.Armstrong Number/README.md index c07ac5795fbf2..6efd1d8ceae9c 100644 --- a/solution/1100-1199/1134.Armstrong Number/README.md +++ b/solution/1100-1199/1134.Armstrong Number/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以先计算出数字的位数 $k$,然后计算每一位上的数字的 $k$ 次幂的总和 $s$,最后判断 $s$ 是否等于 $n$ 即可。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def isArmstrong(self, n: int) -> bool: @@ -64,10 +58,6 @@ class Solution: return s == n ``` -### **Java** - - - ```java class Solution { public boolean isArmstrong(int n) { @@ -81,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +85,6 @@ public: }; ``` -### **Go** - ```go func isArmstrong(n int) bool { k := 0 @@ -113,40 +99,32 @@ func isArmstrong(n int) bool { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {boolean} - */ -var isArmstrong = function (n) { +```ts +function isArmstrong(n: number): boolean { const k = String(n).length; let s = 0; for (let x = n; x; x = Math.floor(x / 10)) { s += Math.pow(x % 10, k); } return s == n; -}; +} ``` -### **TypeScript** - -```ts -function isArmstrong(n: number): boolean { +```js +/** + * @param {number} n + * @return {boolean} + */ +var isArmstrong = function (n) { const k = String(n).length; let s = 0; for (let x = n; x; x = Math.floor(x / 10)) { s += Math.pow(x % 10, k); } return s == n; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/1100-1199/1134.Armstrong Number/README_EN.md b/solution/1100-1199/1134.Armstrong Number/README_EN.md index 53ce8db649b14..afd4526aa5188 100644 --- a/solution/1100-1199/1134.Armstrong Number/README_EN.md +++ b/solution/1100-1199/1134.Armstrong Number/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can first calculate the number of digits $k$, then calculate the sum $s$ of the $k$th power of each digit, and finally check whether $s$ equals $n$. @@ -42,8 +42,6 @@ The time complexity is $O(\log n)$, and the space complexity is $O(\log n)$. Her -### **Python3** - ```python class Solution: def isArmstrong(self, n: int) -> bool: @@ -55,8 +53,6 @@ class Solution: return s == n ``` -### **Java** - ```java class Solution { public boolean isArmstrong(int n) { @@ -70,8 +66,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -86,8 +80,6 @@ public: }; ``` -### **Go** - ```go func isArmstrong(n int) bool { k := 0 @@ -102,40 +94,32 @@ func isArmstrong(n int) bool { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {boolean} - */ -var isArmstrong = function (n) { +```ts +function isArmstrong(n: number): boolean { const k = String(n).length; let s = 0; for (let x = n; x; x = Math.floor(x / 10)) { s += Math.pow(x % 10, k); } return s == n; -}; +} ``` -### **TypeScript** - -```ts -function isArmstrong(n: number): boolean { +```js +/** + * @param {number} n + * @return {boolean} + */ +var isArmstrong = function (n) { const k = String(n).length; let s = 0; for (let x = n; x; x = Math.floor(x / 10)) { s += Math.pow(x % 10, k); } return s == n; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/1100-1199/1135.Connecting Cities With Minimum Cost/README.md b/solution/1100-1199/1135.Connecting Cities With Minimum Cost/README.md index ff24c3be096e2..a29460f2419fc 100644 --- a/solution/1100-1199/1135.Connecting Cities With Minimum Cost/README.md +++ b/solution/1100-1199/1135.Connecting Cities With Minimum Cost/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:Kruskal 算法** +### 方法一:Kruskal 算法 Kruskal 算法是一种贪心算法,用于计算最小生成树。 @@ -65,10 +63,6 @@ Kruskal 算法的基本思想是,每次从边集中选择一条最小的边, -### **Python3** - - - ```python class Solution: def minimumCost(self, n: int, connections: List[List[int]]) -> int: @@ -92,10 +86,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go func minimumCost(n int, connections [][]int) (ans int) { p := make([]int, n) @@ -194,8 +180,6 @@ func minimumCost(n int, connections [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumCost(n: number, connections: number[][]): number { const p = new Array(n); @@ -224,10 +208,6 @@ function minimumCost(n: number, connections: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1135.Connecting Cities With Minimum Cost/README_EN.md b/solution/1100-1199/1135.Connecting Cities With Minimum Cost/README_EN.md index 4ffb5fb7400f8..e2e465695f7fd 100644 --- a/solution/1100-1199/1135.Connecting Cities With Minimum Cost/README_EN.md +++ b/solution/1100-1199/1135.Connecting Cities With Minimum Cost/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Kruskal's Algorithm** +### Solution 1: Kruskal's Algorithm Kruskal's algorithm is a greedy algorithm used to compute the minimum spanning tree. @@ -53,8 +53,6 @@ The time complexity is $O(m \times \log m)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def minimumCost(self, n: int, connections: List[List[int]]) -> int: @@ -78,8 +76,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { private int[] p; @@ -114,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +140,6 @@ public: }; ``` -### **Go** - ```go func minimumCost(n int, connections [][]int) (ans int) { p := make([]int, n) @@ -178,8 +170,6 @@ func minimumCost(n int, connections [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumCost(n: number, connections: number[][]): number { const p = new Array(n); @@ -208,10 +198,6 @@ function minimumCost(n: number, connections: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1136.Parallel Courses/README.md b/solution/1100-1199/1136.Parallel Courses/README.md index a98782010c79b..92e00a1efd727 100644 --- a/solution/1100-1199/1136.Parallel Courses/README.md +++ b/solution/1100-1199/1136.Parallel Courses/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:拓扑排序** +### 方法一:拓扑排序 我们可以先将课程之间的先修关系建立图 $g$,并统计每个课程的入度 $indeg$。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def minimumSemesters(self, n: int, relations: List[List[int]]) -> int: @@ -92,10 +86,6 @@ class Solution: return -1 if n else ans ``` -### **Java** - - - ```java class Solution { public int minimumSemesters(int n, int[][] relations) { @@ -131,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go func minimumSemesters(n int, relations [][]int) (ans int) { g := make([][]int, n) @@ -207,8 +193,6 @@ func minimumSemesters(n int, relations [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumSemesters(n: number, relations: number[][]): number { const g = Array.from({ length: n }, () => []); @@ -240,10 +224,6 @@ function minimumSemesters(n: number, relations: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1136.Parallel Courses/README_EN.md b/solution/1100-1199/1136.Parallel Courses/README_EN.md index 3ac86549b10eb..8cc4512dd4bf8 100644 --- a/solution/1100-1199/1136.Parallel Courses/README_EN.md +++ b/solution/1100-1199/1136.Parallel Courses/README_EN.md @@ -43,7 +43,7 @@ In the second semester, you can take course 3. ## Solutions -**Solution 1: Topological Sorting** +### Solution 1: Topological Sorting We can first build a graph $g$ to represent the prerequisite relationships between courses, and count the in-degree $indeg$ of each course. @@ -53,8 +53,6 @@ The time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, -### **Python3** - ```python class Solution: def minimumSemesters(self, n: int, relations: List[List[int]]) -> int: @@ -78,8 +76,6 @@ class Solution: return -1 if n else ans ``` -### **Java** - ```java class Solution { public int minimumSemesters(int n, int[][] relations) { @@ -115,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +147,6 @@ public: }; ``` -### **Go** - ```go func minimumSemesters(n int, relations [][]int) (ans int) { g := make([][]int, n) @@ -191,8 +183,6 @@ func minimumSemesters(n int, relations [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumSemesters(n: number, relations: number[][]): number { const g = Array.from({ length: n }, () => []); @@ -224,10 +214,6 @@ function minimumSemesters(n: number, relations: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1137.N-th Tribonacci Number/README.md b/solution/1100-1199/1137.N-th Tribonacci Number/README.md index a868d22110755..cfb2dbd5b2f16 100644 --- a/solution/1100-1199/1137.N-th Tribonacci Number/README.md +++ b/solution/1100-1199/1137.N-th Tribonacci Number/README.md @@ -40,9 +40,7 @@ T_4 = 1 + 1 + 2 = 4 ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 根据题目中给出的递推式,我们可以使用动态规划求解。 @@ -52,7 +50,143 @@ T_4 = 1 + 1 + 2 = 4 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为给定的整数。 -**方法二:矩阵快速幂加速递推** + + +```python +class Solution: + def tribonacci(self, n: int) -> int: + a, b, c = 0, 1, 1 + for _ in range(n): + a, b, c = b, c, a + b + c + return a +``` + +```java +class Solution { + public int tribonacci(int n) { + int a = 0, b = 1, c = 1; + while (n-- > 0) { + int d = a + b + c; + a = b; + b = c; + c = d; + } + return a; + } +} +``` + +```cpp +class Solution { +public: + int tribonacci(int n) { + long long a = 0, b = 1, c = 1; + while (n--) { + long long d = a + b + c; + a = b; + b = c; + c = d; + } + return (int) a; + } +}; +``` + +```go +func tribonacci(n int) int { + a, b, c := 0, 1, 1 + for i := 0; i < n; i++ { + a, b, c = b, c, a+b+c + } + return a +} +``` + +```ts +function tribonacci(n: number): number { + if (n === 0) { + return 0; + } + if (n < 3) { + return 1; + } + const a = [ + [1, 1, 0], + [1, 0, 1], + [1, 0, 0], + ]; + return pow(a, n - 3)[0].reduce((a, b) => a + b); +} + +function mul(a: number[][], b: number[][]): number[][] { + const [m, n] = [a.length, b[0].length]; + const c = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + for (let k = 0; k < b.length; ++k) { + c[i][j] += a[i][k] * b[k][j]; + } + } + } + return c; +} + +function pow(a: number[][], n: number): number[][] { + let res = [[1, 1, 0]]; + while (n) { + if (n & 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>= 1; + } + return res; +} +``` + +```js +/** + * @param {number} n + * @return {number} + */ +var tribonacci = function (n) { + let a = 0; + let b = 1; + let c = 1; + while (n--) { + let d = a + b + c; + a = b; + b = c; + c = d; + } + return a; +}; +``` + +```php +class Solution { + /** + * @param Integer $n + * @return Integer + */ + function tribonacci($n) { + if ($n == 0) { + return 0; + } elseif ($n == 1 || $n == 2) { + return 1; + } + $dp = [0, 1, 1]; + for ($i = 3; $i <= $n; $i++) { + $dp[$i] = $dp[$i - 1] + $dp[$i - 2] + $dp[$i - 3]; + } + return $dp[$n]; + } +} +``` + + + +### 方法二:矩阵快速幂加速递推 我们设 $Tib(n)$ 表示一个 $1 \times 3$ 的矩阵 $\begin{bmatrix} T_n & T_{n - 1} & T_{n - 2} \end{bmatrix}$,其中 $T_n$, $T_{n - 1}$ 和 $T_{n - 2}$ 分别表示第 $n$ 个、第 $n - 1$ 个和第 $n - 2$ 个泰波那契数。 @@ -80,19 +214,6 @@ $$ -### **Python3** - - - -```python -class Solution: - def tribonacci(self, n: int) -> int: - a, b, c = 0, 1, 1 - for _ in range(n): - a, b, c = b, c, a + b + c - return a -``` - ```python class Solution: def tribonacci(self, n: int) -> int: @@ -122,46 +243,6 @@ class Solution: return sum(pow(a, n - 3)[0]) ``` -```python -import numpy as np - - -class Solution: - def tribonacci(self, n: int) -> int: - if n == 0: - return 0 - if n < 3: - return 1 - factor = np.mat([(1, 1, 0), (1, 0, 1), (1, 0, 0)], np.dtype("O")) - res = np.mat([(1, 1, 0)], np.dtype("O")) - n -= 3 - while n: - if n & 1: - res *= factor - factor *= factor - n >>= 1 - return res.sum() -``` - -### **Java** - - - -```java -class Solution { - public int tribonacci(int n) { - int a = 0, b = 1, c = 1; - while (n-- > 0) { - int d = a + b + c; - a = b; - b = c; - c = d; - } - return a; - } -} -``` - ```java class Solution { public int tribonacci(int n) { @@ -207,24 +288,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int tribonacci(int n) { - long long a = 0, b = 1, c = 1; - while (n--) { - long long d = a + b + c; - a = b; - b = c; - c = d; - } - return (int) a; - } -}; -``` - ```cpp class Solution { public: @@ -269,18 +332,6 @@ private: }; ``` -### **Go** - -```go -func tribonacci(n int) int { - a, b, c := 0, 1, 1 - for i := 0; i < n; i++ { - a, b, c = b, c, a+b+c - } - return a -} -``` - ```go func tribonacci(n int) (ans int) { if n == 0 { @@ -326,27 +377,6 @@ func pow(a [][]int, n int) [][]int { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number} - */ -var tribonacci = function (n) { - let a = 0; - let b = 1; - let c = 1; - while (n--) { - let d = a + b + c; - a = b; - b = c; - c = d; - } - return a; -}; -``` - ```js /** * @param {number} n @@ -393,77 +423,33 @@ function pow(a, n) { } ``` -### **TypeScript** - -```ts -function tribonacci(n: number): number { - if (n === 0) { - return 0; - } - if (n < 3) { - return 1; - } - const a = [ - [1, 1, 0], - [1, 0, 1], - [1, 0, 0], - ]; - return pow(a, n - 3)[0].reduce((a, b) => a + b); -} - -function mul(a: number[][], b: number[][]): number[][] { - const [m, n] = [a.length, b[0].length]; - const c = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - for (let k = 0; k < b.length; ++k) { - c[i][j] += a[i][k] * b[k][j]; - } - } - } - return c; -} - -function pow(a: number[][], n: number): number[][] { - let res = [[1, 1, 0]]; - while (n) { - if (n & 1) { - res = mul(res, a); - } - a = mul(a, a); - n >>= 1; - } - return res; -} -``` + -### **PHP** +### 方法三 -```php -class Solution { - /** - * @param Integer $n - * @return Integer - */ - function tribonacci($n) { - if ($n == 0) { - return 0; - } elseif ($n == 1 || $n == 2) { - return 1; - } - $dp = [0, 1, 1]; - for ($i = 3; $i <= $n; $i++) { - $dp[$i] = $dp[$i - 1] + $dp[$i - 2] + $dp[$i - 3]; - } - return $dp[$n]; - } -} -``` + -### **...** +```python +import numpy as np -``` +class Solution: + def tribonacci(self, n: int) -> int: + if n == 0: + return 0 + if n < 3: + return 1 + factor = np.mat([(1, 1, 0), (1, 0, 1), (1, 0, 0)], np.dtype("O")) + res = np.mat([(1, 1, 0)], np.dtype("O")) + n -= 3 + while n: + if n & 1: + res *= factor + factor *= factor + n >>= 1 + return res.sum() ``` + + diff --git a/solution/1100-1199/1137.N-th Tribonacci Number/README_EN.md b/solution/1100-1199/1137.N-th Tribonacci Number/README_EN.md index a312847b4fe32..016fc765b6dfd 100644 --- a/solution/1100-1199/1137.N-th Tribonacci Number/README_EN.md +++ b/solution/1100-1199/1137.N-th Tribonacci Number/README_EN.md @@ -38,7 +38,7 @@ T_4 = 1 + 1 + 2 = 4 ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming According to the recurrence relation given in the problem, we can use dynamic programming to solve it. @@ -48,7 +48,143 @@ Then we decrease $n$ to $0$, updating the values of $a$, $b$, $c$ each time, unt The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the given integer. -**Solution 2: Matrix Exponentiation to Accelerate Recurrence** + + +```python +class Solution: + def tribonacci(self, n: int) -> int: + a, b, c = 0, 1, 1 + for _ in range(n): + a, b, c = b, c, a + b + c + return a +``` + +```java +class Solution { + public int tribonacci(int n) { + int a = 0, b = 1, c = 1; + while (n-- > 0) { + int d = a + b + c; + a = b; + b = c; + c = d; + } + return a; + } +} +``` + +```cpp +class Solution { +public: + int tribonacci(int n) { + long long a = 0, b = 1, c = 1; + while (n--) { + long long d = a + b + c; + a = b; + b = c; + c = d; + } + return (int) a; + } +}; +``` + +```go +func tribonacci(n int) int { + a, b, c := 0, 1, 1 + for i := 0; i < n; i++ { + a, b, c = b, c, a+b+c + } + return a +} +``` + +```ts +function tribonacci(n: number): number { + if (n === 0) { + return 0; + } + if (n < 3) { + return 1; + } + const a = [ + [1, 1, 0], + [1, 0, 1], + [1, 0, 0], + ]; + return pow(a, n - 3)[0].reduce((a, b) => a + b); +} + +function mul(a: number[][], b: number[][]): number[][] { + const [m, n] = [a.length, b[0].length]; + const c = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; ++j) { + for (let k = 0; k < b.length; ++k) { + c[i][j] += a[i][k] * b[k][j]; + } + } + } + return c; +} + +function pow(a: number[][], n: number): number[][] { + let res = [[1, 1, 0]]; + while (n) { + if (n & 1) { + res = mul(res, a); + } + a = mul(a, a); + n >>= 1; + } + return res; +} +``` + +```js +/** + * @param {number} n + * @return {number} + */ +var tribonacci = function (n) { + let a = 0; + let b = 1; + let c = 1; + while (n--) { + let d = a + b + c; + a = b; + b = c; + c = d; + } + return a; +}; +``` + +```php +class Solution { + /** + * @param Integer $n + * @return Integer + */ + function tribonacci($n) { + if ($n == 0) { + return 0; + } elseif ($n == 1 || $n == 2) { + return 1; + } + $dp = [0, 1, 1]; + for ($i = 3; $i <= $n; $i++) { + $dp[$i] = $dp[$i - 1] + $dp[$i - 2] + $dp[$i - 3]; + } + return $dp[$n]; + } +} +``` + + + +### Solution 2: Matrix Exponentiation to Accelerate Recurrence We define $Tib(n)$ as a $1 \times 3$ matrix $\begin{bmatrix} T_n & T_{n - 1} & T_{n - 2} \end{bmatrix}$, where $T_n$, $T_{n - 1}$ and $T_{n - 2}$ represent the $n$th, $(n - 1)$th and $(n - 2)$th Tribonacci numbers, respectively. @@ -76,17 +212,6 @@ The time complexity is $O(\log n)$, and the space complexity is $O(1)$. -### **Python3** - -```python -class Solution: - def tribonacci(self, n: int) -> int: - a, b, c = 0, 1, 1 - for _ in range(n): - a, b, c = b, c, a + b + c - return a -``` - ```python class Solution: def tribonacci(self, n: int) -> int: @@ -116,44 +241,6 @@ class Solution: return sum(pow(a, n - 3)[0]) ``` -```python -import numpy as np - - -class Solution: - def tribonacci(self, n: int) -> int: - if n == 0: - return 0 - if n < 3: - return 1 - factor = np.mat([(1, 1, 0), (1, 0, 1), (1, 0, 0)], np.dtype("O")) - res = np.mat([(1, 1, 0)], np.dtype("O")) - n -= 3 - while n: - if n & 1: - res *= factor - factor *= factor - n >>= 1 - return res.sum() -``` - -### **Java** - -```java -class Solution { - public int tribonacci(int n) { - int a = 0, b = 1, c = 1; - while (n-- > 0) { - int d = a + b + c; - a = b; - b = c; - c = d; - } - return a; - } -} -``` - ```java class Solution { public int tribonacci(int n) { @@ -199,24 +286,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int tribonacci(int n) { - long long a = 0, b = 1, c = 1; - while (n--) { - long long d = a + b + c; - a = b; - b = c; - c = d; - } - return (int) a; - } -}; -``` - ```cpp class Solution { public: @@ -261,18 +330,6 @@ private: }; ``` -### **Go** - -```go -func tribonacci(n int) int { - a, b, c := 0, 1, 1 - for i := 0; i < n; i++ { - a, b, c = b, c, a+b+c - } - return a -} -``` - ```go func tribonacci(n int) (ans int) { if n == 0 { @@ -318,27 +375,6 @@ func pow(a [][]int, n int) [][]int { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number} - */ -var tribonacci = function (n) { - let a = 0; - let b = 1; - let c = 1; - while (n--) { - let d = a + b + c; - a = b; - b = c; - c = d; - } - return a; -}; -``` - ```js /** * @param {number} n @@ -385,77 +421,33 @@ function pow(a, n) { } ``` -### **TypeScript** - -```ts -function tribonacci(n: number): number { - if (n === 0) { - return 0; - } - if (n < 3) { - return 1; - } - const a = [ - [1, 1, 0], - [1, 0, 1], - [1, 0, 0], - ]; - return pow(a, n - 3)[0].reduce((a, b) => a + b); -} - -function mul(a: number[][], b: number[][]): number[][] { - const [m, n] = [a.length, b[0].length]; - const c = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; ++j) { - for (let k = 0; k < b.length; ++k) { - c[i][j] += a[i][k] * b[k][j]; - } - } - } - return c; -} - -function pow(a: number[][], n: number): number[][] { - let res = [[1, 1, 0]]; - while (n) { - if (n & 1) { - res = mul(res, a); - } - a = mul(a, a); - n >>= 1; - } - return res; -} -``` + -### **PHP** +### Solution 3 -```php -class Solution { - /** - * @param Integer $n - * @return Integer - */ - function tribonacci($n) { - if ($n == 0) { - return 0; - } elseif ($n == 1 || $n == 2) { - return 1; - } - $dp = [0, 1, 1]; - for ($i = 3; $i <= $n; $i++) { - $dp[$i] = $dp[$i - 1] + $dp[$i - 2] + $dp[$i - 3]; - } - return $dp[$n]; - } -} -``` + -### **...** +```python +import numpy as np -``` +class Solution: + def tribonacci(self, n: int) -> int: + if n == 0: + return 0 + if n < 3: + return 1 + factor = np.mat([(1, 1, 0), (1, 0, 1), (1, 0, 0)], np.dtype("O")) + res = np.mat([(1, 1, 0)], np.dtype("O")) + n -= 3 + while n: + if n & 1: + res *= factor + factor *= factor + n >>= 1 + return res.sum() ``` + + diff --git a/solution/1100-1199/1138.Alphabet Board Path/README.md b/solution/1100-1199/1138.Alphabet Board Path/README.md index 57602ba89a737..dffa31917e6d4 100644 --- a/solution/1100-1199/1138.Alphabet Board Path/README.md +++ b/solution/1100-1199/1138.Alphabet Board Path/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 从起点 $(0, 0)$ 出发,模拟每一步的移动,将每一步的移动结果拼接到答案中。注意移动的方向遵循“左、上、右、下”的顺序。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def alphabetBoardPath(self, target: str) -> str: @@ -91,10 +85,6 @@ class Solution: return "".join(ans) ``` -### **Java** - - - ```java class Solution { public String alphabetBoardPath(String target) { @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +148,6 @@ public: }; ``` -### **Go** - ```go func alphabetBoardPath(target string) string { ans := []byte{} @@ -191,10 +177,6 @@ func alphabetBoardPath(target string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1138.Alphabet Board Path/README_EN.md b/solution/1100-1199/1138.Alphabet Board Path/README_EN.md index 85ea22e86e384..16fac3f2e939e 100644 --- a/solution/1100-1199/1138.Alphabet Board Path/README_EN.md +++ b/solution/1100-1199/1138.Alphabet Board Path/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation Starting from the origin point $(0, 0)$, simulate each step of the movement, appending the result of each step to the answer. Note that the direction of movement follows the order "left, up, right, down". @@ -50,8 +50,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string target, as -### **Python3** - ```python class Solution: def alphabetBoardPath(self, target: str) -> str: @@ -76,8 +74,6 @@ class Solution: return "".join(ans) ``` -### **Java** - ```java class Solution { public String alphabetBoardPath(String target) { @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +137,6 @@ public: }; ``` -### **Go** - ```go func alphabetBoardPath(target string) string { ans := []byte{} @@ -174,10 +166,6 @@ func alphabetBoardPath(target string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1139.Largest 1-Bordered Square/README.md b/solution/1100-1199/1139.Largest 1-Bordered Square/README.md index 82518e823ac6f..7f3e8a4166a03 100644 --- a/solution/1100-1199/1139.Largest 1-Bordered Square/README.md +++ b/solution/1100-1199/1139.Largest 1-Bordered Square/README.md @@ -34,9 +34,7 @@ ## 解法 - - -**方法一:前缀和 + 枚举** +### 方法一:前缀和 + 枚举 我们可以使用前缀和的方法预处理出每个位置向下和向右的连续 $1$ 的个数,记为 `down[i][j]` 和 `right[i][j]`。 @@ -46,10 +44,6 @@ -### **Python3** - - - ```python class Solution: def largest1BorderedSquare(self, grid: List[List[int]]) -> int: @@ -74,10 +68,6 @@ class Solution: return 0 ``` -### **Java** - - - ```java class Solution { public int largest1BorderedSquare(int[][] grid) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func largest1BorderedSquare(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -178,10 +164,6 @@ func largest1BorderedSquare(grid [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1139.Largest 1-Bordered Square/README_EN.md b/solution/1100-1199/1139.Largest 1-Bordered Square/README_EN.md index 1387cac7101be..2bf751a6b6eb3 100644 --- a/solution/1100-1199/1139.Largest 1-Bordered Square/README_EN.md +++ b/solution/1100-1199/1139.Largest 1-Bordered Square/README_EN.md @@ -32,7 +32,7 @@ ## Solutions -**Solution 1: Prefix Sum + Enumeration** +### Solution 1: Prefix Sum + Enumeration We can use the prefix sum method to preprocess the number of consecutive 1s down and to the right of each position, denoted as `down[i][j]` and `right[i][j]`. @@ -42,8 +42,6 @@ The time complexity is $O(m \times n \times \min(m, n))$, and the space complexi -### **Python3** - ```python class Solution: def largest1BorderedSquare(self, grid: List[List[int]]) -> int: @@ -68,8 +66,6 @@ class Solution: return 0 ``` -### **Java** - ```java class Solution { public int largest1BorderedSquare(int[][] grid) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +127,6 @@ public: }; ``` -### **Go** - ```go func largest1BorderedSquare(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -170,10 +162,6 @@ func largest1BorderedSquare(grid [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1140.Stone Game II/README.md b/solution/1100-1199/1140.Stone Game II/README.md index 4ff029311f7ec..ec55fb06b2e69 100644 --- a/solution/1100-1199/1140.Stone Game II/README.md +++ b/solution/1100-1199/1140.Stone Game II/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:前缀和 + 记忆化搜索** +### 方法一:前缀和 + 记忆化搜索 由于玩家每次可以拿走前 $X$ 堆的所有石子,也就是说能拿走一个区间的石子,因此,我们可以先预处理出一个长度为 $n+1$ 的前缀和数组 $s$,其中 $s[i]$ 表示数组 `piles` 的前 $i$ 个元素的和。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def stoneGameII(self, piles: List[int]) -> int: @@ -85,26 +79,6 @@ class Solution: return dfs(0, 1) ``` -```python -class Solution: - def stoneGameII(self, piles: List[int]) -> int: - @cache - def dfs(i: int, m: int = 1) -> int: - if i >= len(piles): - return 0 - t = inf - for x in range(1, m << 1 | 1): - t = min(t, dfs(i + x, max(m, x))) - return s[-1] - s[i] - t - - s = list(accumulate(piles, initial=0)) - return dfs(0) -``` - -### **Java** - - - ```java class Solution { private int[] s; @@ -137,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +141,6 @@ public: }; ``` -### **Go** - ```go func stoneGameII(piles []int) int { n := len(piles) @@ -198,8 +168,6 @@ func stoneGameII(piles []int) int { } ``` -### **TypeScript** - ```ts function stoneGameII(piles: number[]): number { const n = piles.length; @@ -225,10 +193,28 @@ function stoneGameII(piles: number[]): number { } ``` -### **...** + + +### 方法二 -``` + +```python +class Solution: + def stoneGameII(self, piles: List[int]) -> int: + @cache + def dfs(i: int, m: int = 1) -> int: + if i >= len(piles): + return 0 + t = inf + for x in range(1, m << 1 | 1): + t = min(t, dfs(i + x, max(m, x))) + return s[-1] - s[i] - t + + s = list(accumulate(piles, initial=0)) + return dfs(0) ``` + + diff --git a/solution/1100-1199/1140.Stone Game II/README_EN.md b/solution/1100-1199/1140.Stone Game II/README_EN.md index b6709e8df7904..8e291fc826486 100644 --- a/solution/1100-1199/1140.Stone Game II/README_EN.md +++ b/solution/1100-1199/1140.Stone Game II/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Prefix Sum + Memoization Search** +### Solution 1: Prefix Sum + Memoization Search Since the player can take all the stones from the first $X$ piles each time, that is, they can take the stones from an interval, we can first preprocess a prefix sum array $s$ of length $n+1$, where $s[i]$ represents the sum of the first $i$ elements of the array `piles`. @@ -59,8 +59,6 @@ The time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ -### **Python3** - ```python class Solution: def stoneGameII(self, piles: List[int]) -> int: @@ -77,24 +75,6 @@ class Solution: return dfs(0, 1) ``` -```python -class Solution: - def stoneGameII(self, piles: List[int]) -> int: - @cache - def dfs(i: int, m: int = 1) -> int: - if i >= len(piles): - return 0 - t = inf - for x in range(1, m << 1 | 1): - t = min(t, dfs(i + x, max(m, x))) - return s[-1] - s[i] - t - - s = list(accumulate(piles, initial=0)) - return dfs(0) -``` - -### **Java** - ```java class Solution { private int[] s; @@ -127,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +137,6 @@ public: }; ``` -### **Go** - ```go func stoneGameII(piles []int) int { n := len(piles) @@ -188,8 +164,6 @@ func stoneGameII(piles []int) int { } ``` -### **TypeScript** - ```ts function stoneGameII(piles: number[]): number { const n = piles.length; @@ -215,10 +189,28 @@ function stoneGameII(piles: number[]): number { } ``` -### **...** + -``` +### Solution 2 + + + +```python +class Solution: + def stoneGameII(self, piles: List[int]) -> int: + @cache + def dfs(i: int, m: int = 1) -> int: + if i >= len(piles): + return 0 + t = inf + for x in range(1, m << 1 | 1): + t = min(t, dfs(i + x, max(m, x))) + return s[-1] - s[i] - t + s = list(accumulate(piles, initial=0)) + return dfs(0) ``` + + diff --git a/solution/1100-1199/1141.User Activity for the Past 30 Days I/README.md b/solution/1100-1199/1141.User Activity for the Past 30 Days I/README.md index 7a58f193bd73c..bd3a08e28402c 100644 --- a/solution/1100-1199/1141.User Activity for the Past 30 Days I/README.md +++ b/solution/1100-1199/1141.User Activity for the Past 30 Days I/README.md @@ -64,16 +64,12 @@ Activity table: ## 解法 - - -**方法一:GROUP BY + HAVING** +### 方法一:GROUP BY + HAVING 我们查询出所有在 `2019-07-27` 且在 $30$ 天内的所有活动记录,然后按照日期分组,统计每天的去重活跃用户数。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT activity_date AS day, COUNT(DISTINCT user_id) AS active_users @@ -83,3 +79,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1100-1199/1141.User Activity for the Past 30 Days I/README_EN.md b/solution/1100-1199/1141.User Activity for the Past 30 Days I/README_EN.md index 1bc0ee33e8def..bc734b15f7deb 100644 --- a/solution/1100-1199/1141.User Activity for the Past 30 Days I/README_EN.md +++ b/solution/1100-1199/1141.User Activity for the Past 30 Days I/README_EN.md @@ -62,9 +62,9 @@ Activity table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -75,3 +75,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1100-1199/1142.User Activity for the Past 30 Days II/README.md b/solution/1100-1199/1142.User Activity for the Past 30 Days II/README.md index ac6aa2449906f..ba62fecd5c6d5 100644 --- a/solution/1100-1199/1142.User Activity for the Past 30 Days II/README.md +++ b/solution/1100-1199/1142.User Activity for the Past 30 Days II/README.md @@ -64,12 +64,10 @@ Activity 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -84,6 +82,12 @@ SELECT IFNULL(ROUND(AVG(sessions), 2), 0) AS average_sessions_per_user FROM T; ``` + + +### 方法二 + + + ```sql SELECT IFNULL( @@ -95,3 +99,5 @@ WHERE DATEDIFF('2019-07-27', activity_date) < 30; ``` + + diff --git a/solution/1100-1199/1142.User Activity for the Past 30 Days II/README_EN.md b/solution/1100-1199/1142.User Activity for the Past 30 Days II/README_EN.md index c5dcb50efa2d3..09b03bb9866a9 100644 --- a/solution/1100-1199/1142.User Activity for the Past 30 Days II/README_EN.md +++ b/solution/1100-1199/1142.User Activity for the Past 30 Days II/README_EN.md @@ -62,9 +62,9 @@ Activity table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -80,6 +80,12 @@ SELECT IFNULL(ROUND(AVG(sessions), 2), 0) AS average_sessions_per_user FROM T; ``` + + +### Solution 2 + + + ```sql SELECT IFNULL( @@ -91,3 +97,5 @@ WHERE DATEDIFF('2019-07-27', activity_date) < 30; ``` + + diff --git a/solution/1100-1199/1143.Longest Common Subsequence/README.md b/solution/1100-1199/1143.Longest Common Subsequence/README.md index c0cb498960caa..3e321edec69b7 100644 --- a/solution/1100-1199/1143.Longest Common Subsequence/README.md +++ b/solution/1100-1199/1143.Longest Common Subsequence/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示 $text1$ 的前 $i$ 个字符和 $text2$ 的前 $j$ 个字符的最长公共子序列的长度。那么答案为 $f[m][n]$,其中 $m$ 和 $n$ 分别为 $text1$ 和 $text2$ 的长度。 @@ -73,10 +71,6 @@ $$ -### **Python3** - - - ```python class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: @@ -91,10 +85,6 @@ class Solution: return f[m][n] ``` -### **Java** - - - ```java class Solution { public int longestCommonSubsequence(String text1, String text2) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func longestCommonSubsequence(text1 string, text2 string) int { m, n := len(text1), len(text2) @@ -159,33 +145,6 @@ func longestCommonSubsequence(text1 string, text2 string) int { } ``` -### **JavaScript** - -```js -/** - * @param {string} text1 - * @param {string} text2 - * @return {number} - */ -var longestCommonSubsequence = function (text1, text2) { - const m = text1.length; - const n = text2.length; - const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); - for (let i = 1; i <= m; ++i) { - for (let j = 1; j <= n; ++j) { - if (text1[i - 1] == text2[j - 1]) { - f[i][j] = f[i - 1][j - 1] + 1; - } else { - f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]); - } - } - } - return f[m][n]; -}; -``` - -### **TypeScript** - ```ts function longestCommonSubsequence(text1: string, text2: string): number { const m = text1.length; @@ -204,8 +163,6 @@ function longestCommonSubsequence(text1: string, text2: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn longest_common_subsequence(text1: String, text2: String) -> i32 { @@ -226,7 +183,28 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {string} text1 + * @param {string} text2 + * @return {number} + */ +var longestCommonSubsequence = function (text1, text2) { + const m = text1.length; + const n = text2.length; + const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); + for (let i = 1; i <= m; ++i) { + for (let j = 1; j <= n; ++j) { + if (text1[i - 1] == text2[j - 1]) { + f[i][j] = f[i - 1][j - 1] + 1; + } else { + f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]); + } + } + } + return f[m][n]; +}; +``` ```cs public class Solution { @@ -247,8 +225,6 @@ public class Solution { } ``` -### **Kotlin** - ```kotlin class Solution { fun longestCommonSubsequence(text1: String, text2: String): Int { @@ -269,10 +245,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1143.Longest Common Subsequence/README_EN.md b/solution/1100-1199/1143.Longest Common Subsequence/README_EN.md index 4a5894c9c078a..f54b8de550f0f 100644 --- a/solution/1100-1199/1143.Longest Common Subsequence/README_EN.md +++ b/solution/1100-1199/1143.Longest Common Subsequence/README_EN.md @@ -49,7 +49,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ as the length of the longest common subsequence of the first $i$ characters of $text1$ and the first $j$ characters of $text2$. Therefore, the answer is $f[m][n]$, where $m$ and $n$ are the lengths of $text1$ and $text2$, respectively. @@ -67,8 +67,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times -### **Python3** - ```python class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: @@ -83,8 +81,6 @@ class Solution: return f[m][n] ``` -### **Java** - ```java class Solution { public int longestCommonSubsequence(String text1, String text2) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +121,6 @@ public: }; ``` -### **Go** - ```go func longestCommonSubsequence(text1 string, text2 string) int { m, n := len(text1), len(text2) @@ -149,33 +141,6 @@ func longestCommonSubsequence(text1 string, text2 string) int { } ``` -### **JavaScript** - -```js -/** - * @param {string} text1 - * @param {string} text2 - * @return {number} - */ -var longestCommonSubsequence = function (text1, text2) { - const m = text1.length; - const n = text2.length; - const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); - for (let i = 1; i <= m; ++i) { - for (let j = 1; j <= n; ++j) { - if (text1[i - 1] == text2[j - 1]) { - f[i][j] = f[i - 1][j - 1] + 1; - } else { - f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]); - } - } - } - return f[m][n]; -}; -``` - -### **TypeScript** - ```ts function longestCommonSubsequence(text1: string, text2: string): number { const m = text1.length; @@ -194,8 +159,6 @@ function longestCommonSubsequence(text1: string, text2: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn longest_common_subsequence(text1: String, text2: String) -> i32 { @@ -216,7 +179,28 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {string} text1 + * @param {string} text2 + * @return {number} + */ +var longestCommonSubsequence = function (text1, text2) { + const m = text1.length; + const n = text2.length; + const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); + for (let i = 1; i <= m; ++i) { + for (let j = 1; j <= n; ++j) { + if (text1[i - 1] == text2[j - 1]) { + f[i][j] = f[i - 1][j - 1] + 1; + } else { + f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]); + } + } + } + return f[m][n]; +}; +``` ```cs public class Solution { @@ -237,8 +221,6 @@ public class Solution { } ``` -### **Kotlin** - ```kotlin class Solution { fun longestCommonSubsequence(text1: String, text2: String): Int { @@ -259,10 +241,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1144.Decrease Elements To Make Array Zigzag/README.md b/solution/1100-1199/1144.Decrease Elements To Make Array Zigzag/README.md index 292409fedc69f..629ed65d0f4de 100644 --- a/solution/1100-1199/1144.Decrease Elements To Make Array Zigzag/README.md +++ b/solution/1100-1199/1144.Decrease Elements To Make Array Zigzag/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:枚举 + 贪心** +### 方法一:枚举 + 贪心 我们可以分别枚举偶数位和奇数位作为“比相邻元素小”的元素,然后计算需要的操作次数。取两者的最小值即可。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def movesToMakeZigzag(self, nums: List[int]) -> int: @@ -73,10 +67,6 @@ class Solution: return min(ans) ``` -### **Java** - - - ```java class Solution { public int movesToMakeZigzag(int[] nums) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func movesToMakeZigzag(nums []int) int { ans := [2]int{} @@ -142,7 +128,25 @@ func movesToMakeZigzag(nums []int) int { } ``` -### **C#** +```ts +function movesToMakeZigzag(nums: number[]): number { + const ans: number[] = Array(2).fill(0); + const n = nums.length; + for (let i = 0; i < 2; ++i) { + for (let j = i; j < n; j += 2) { + let d = 0; + if (j > 0) { + d = Math.max(d, nums[j] - nums[j - 1] + 1); + } + if (j < n - 1) { + d = Math.max(d, nums[j] - nums[j + 1] + 1); + } + ans[i] += d; + } + } + return Math.min(...ans); +} +``` ```cs public class Solution { @@ -166,32 +170,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function movesToMakeZigzag(nums: number[]): number { - const ans: number[] = Array(2).fill(0); - const n = nums.length; - for (let i = 0; i < 2; ++i) { - for (let j = i; j < n; j += 2) { - let d = 0; - if (j > 0) { - d = Math.max(d, nums[j] - nums[j - 1] + 1); - } - if (j < n - 1) { - d = Math.max(d, nums[j] - nums[j + 1] + 1); - } - ans[i] += d; - } - } - return Math.min(...ans); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1144.Decrease Elements To Make Array Zigzag/README_EN.md b/solution/1100-1199/1144.Decrease Elements To Make Array Zigzag/README_EN.md index 344a4e8ec56b6..0520e37d2a105 100644 --- a/solution/1100-1199/1144.Decrease Elements To Make Array Zigzag/README_EN.md +++ b/solution/1100-1199/1144.Decrease Elements To Make Array Zigzag/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Enumeration + Greedy** +### Solution 1: Enumeration + Greedy We can separately enumerate the even and odd positions as the elements "smaller than adjacent elements", and then calculate the required number of operations. The minimum of the two is taken. @@ -49,8 +49,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def movesToMakeZigzag(self, nums: List[int]) -> int: @@ -67,8 +65,6 @@ class Solution: return min(ans) ``` -### **Java** - ```java class Solution { public int movesToMakeZigzag(int[] nums) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +106,6 @@ public: }; ``` -### **Go** - ```go func movesToMakeZigzag(nums []int) int { ans := [2]int{} @@ -134,7 +126,25 @@ func movesToMakeZigzag(nums []int) int { } ``` -### **C#** +```ts +function movesToMakeZigzag(nums: number[]): number { + const ans: number[] = Array(2).fill(0); + const n = nums.length; + for (let i = 0; i < 2; ++i) { + for (let j = i; j < n; j += 2) { + let d = 0; + if (j > 0) { + d = Math.max(d, nums[j] - nums[j - 1] + 1); + } + if (j < n - 1) { + d = Math.max(d, nums[j] - nums[j + 1] + 1); + } + ans[i] += d; + } + } + return Math.min(...ans); +} +``` ```cs public class Solution { @@ -158,32 +168,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function movesToMakeZigzag(nums: number[]): number { - const ans: number[] = Array(2).fill(0); - const n = nums.length; - for (let i = 0; i < 2; ++i) { - for (let j = i; j < n; j += 2) { - let d = 0; - if (j > 0) { - d = Math.max(d, nums[j] - nums[j - 1] + 1); - } - if (j < n - 1) { - d = Math.max(d, nums[j] - nums[j + 1] + 1); - } - ans[i] += d; - } - } - return Math.min(...ans); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1145.Binary Tree Coloring Game/README.md b/solution/1100-1199/1145.Binary Tree Coloring Game/README.md index 57ad62fdfc062..bcff72191e5fc 100644 --- a/solution/1100-1199/1145.Binary Tree Coloring Game/README.md +++ b/solution/1100-1199/1145.Binary Tree Coloring Game/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们先通过 $DFS$,找到「一号」玩家着色点 $x$ 所在的节点,记为 $node$。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -94,10 +88,6 @@ class Solution: return max(l, r, n - l - r - 1) > n // 2 ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -178,8 +166,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -216,32 +202,30 @@ func btreeGameWinningMove(root *TreeNode, n int, x int) bool { } ``` -### **JavaScript** - -```js +```ts /** * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) + * 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) + * } * } */ -/** - * @param {TreeNode} root - * @param {number} n - * @param {number} x - * @return {boolean} - */ -var btreeGameWinningMove = function (root, n, x) { - const dfs = root => { + +function btreeGameWinningMove(root: TreeNode | null, n: number, x: number): boolean { + const dfs = (root: TreeNode | null): TreeNode | null => { if (!root || root.val === x) { return root; } return dfs(root.left) || dfs(root.right); }; - const count = root => { + const count = (root: TreeNode | null): number => { if (!root) { return 0; } @@ -252,35 +236,33 @@ var btreeGameWinningMove = function (root, n, x) { const l = count(node.left); const r = count(node.right); return Math.max(l, r, n - l - r - 1) > n / 2; -}; +} ``` -### **TypeScript** - -```ts +```js /** * 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 TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) * } */ - -function btreeGameWinningMove(root: TreeNode | null, n: number, x: number): boolean { - const dfs = (root: TreeNode | null): TreeNode | null => { +/** + * @param {TreeNode} root + * @param {number} n + * @param {number} x + * @return {boolean} + */ +var btreeGameWinningMove = function (root, n, x) { + const dfs = root => { if (!root || root.val === x) { return root; } return dfs(root.left) || dfs(root.right); }; - const count = (root: TreeNode | null): number => { + const count = root => { if (!root) { return 0; } @@ -291,13 +273,9 @@ function btreeGameWinningMove(root: TreeNode | null, n: number, x: number): bool const l = count(node.left); const r = count(node.right); return Math.max(l, r, n - l - r - 1) > n / 2; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/1100-1199/1145.Binary Tree Coloring Game/README_EN.md b/solution/1100-1199/1145.Binary Tree Coloring Game/README_EN.md index 5a9ae03b9210e..98ad246286ddb 100644 --- a/solution/1100-1199/1145.Binary Tree Coloring Game/README_EN.md +++ b/solution/1100-1199/1145.Binary Tree Coloring Game/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS First, we use DFS to find the node where player 1's colored point $x$ is located, denoted as $node$. @@ -53,8 +53,6 @@ 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: @@ -79,8 +77,6 @@ class Solution: return max(l, r, n - l - r - 1) > n // 2 ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -122,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -161,8 +155,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -199,32 +191,30 @@ func btreeGameWinningMove(root *TreeNode, n int, x int) bool { } ``` -### **JavaScript** - -```js +```ts /** * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) + * 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) + * } * } */ -/** - * @param {TreeNode} root - * @param {number} n - * @param {number} x - * @return {boolean} - */ -var btreeGameWinningMove = function (root, n, x) { - const dfs = root => { + +function btreeGameWinningMove(root: TreeNode | null, n: number, x: number): boolean { + const dfs = (root: TreeNode | null): TreeNode | null => { if (!root || root.val === x) { return root; } return dfs(root.left) || dfs(root.right); }; - const count = root => { + const count = (root: TreeNode | null): number => { if (!root) { return 0; } @@ -235,35 +225,33 @@ var btreeGameWinningMove = function (root, n, x) { const l = count(node.left); const r = count(node.right); return Math.max(l, r, n - l - r - 1) > n / 2; -}; +} ``` -### **TypeScript** - -```ts +```js /** * 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 TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) * } */ - -function btreeGameWinningMove(root: TreeNode | null, n: number, x: number): boolean { - const dfs = (root: TreeNode | null): TreeNode | null => { +/** + * @param {TreeNode} root + * @param {number} n + * @param {number} x + * @return {boolean} + */ +var btreeGameWinningMove = function (root, n, x) { + const dfs = root => { if (!root || root.val === x) { return root; } return dfs(root.left) || dfs(root.right); }; - const count = (root: TreeNode | null): number => { + const count = root => { if (!root) { return 0; } @@ -274,13 +262,9 @@ function btreeGameWinningMove(root: TreeNode | null, n: number, x: number): bool const l = count(node.left); const r = count(node.right); return Math.max(l, r, n - l - r - 1) > n / 2; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/1100-1199/1146.Snapshot Array/README.md b/solution/1100-1199/1146.Snapshot Array/README.md index 63e69cd35e5d7..07899c1061222 100644 --- a/solution/1100-1199/1146.Snapshot Array/README.md +++ b/solution/1100-1199/1146.Snapshot Array/README.md @@ -43,9 +43,7 @@ snapshotArr.get(0,0); // 获取 snap_id = 0 的快照中 array[0] 的值,返 ## 解法 - - -**方法一:数组 + 二分查找** +### 方法一:数组 + 二分查找 维护一个数组,数组中的每个元素是一个列表,列表中存储的是每次设置的值以及对应的快照编号。 @@ -57,10 +55,6 @@ snapshotArr.get(0,0); // 获取 snap_id = 0 的快照中 array[0] 的值,返 -### **Python3** - - - ```python class SnapshotArray: def __init__(self, length: int): @@ -87,10 +81,6 @@ class SnapshotArray: # param_3 = obj.get(index,snap_id) ``` -### **Java** - - - ```java class SnapshotArray { private List[] arr; @@ -133,8 +123,6 @@ class SnapshotArray { */ ``` -### **C++** - ```cpp class SnapshotArray { public: @@ -179,8 +167,6 @@ private: */ ``` -### **Go** - ```go type SnapshotArray struct { idx int @@ -220,10 +206,6 @@ type pair struct{ i, v int } */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1146.Snapshot Array/README_EN.md b/solution/1100-1199/1146.Snapshot Array/README_EN.md index 2063c2806b834..f3e84e4a68c69 100644 --- a/solution/1100-1199/1146.Snapshot Array/README_EN.md +++ b/solution/1100-1199/1146.Snapshot Array/README_EN.md @@ -40,7 +40,7 @@ snapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5 -### **Python3** - ```python class SnapshotArray: def __init__(self, length: int): @@ -80,8 +78,6 @@ class SnapshotArray: # param_3 = obj.get(index,snap_id) ``` -### **Java** - ```java class SnapshotArray { private List[] arr; @@ -124,8 +120,6 @@ class SnapshotArray { */ ``` -### **C++** - ```cpp class SnapshotArray { public: @@ -170,8 +164,6 @@ private: */ ``` -### **Go** - ```go type SnapshotArray struct { idx int @@ -211,10 +203,6 @@ type pair struct{ i, v int } */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/README.md b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/README.md index db9ffca452e92..4cd53644674c5 100644 --- a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/README.md +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:贪心 + 双指针** +### 方法一:贪心 + 双指针 我们可以从字符串的两端开始,寻找长度最短的、相同且不重叠的前后缀: @@ -70,20 +68,8 @@ 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$ 或 $O(1)$。其中 $n$ 为字符串的长度。 -**方法二:字符串哈希** - -**字符串哈希**是把一个任意长度的字符串映射成一个非负整数,并且其冲突的概率几乎为 $0$。字符串哈希用于计算字符串哈希值,快速判断两个字符串是否相等。 - -因此,在方法一的基础上,我们可以使用字符串哈希的方法,在 $O(1)$ 时间内比较两个字符串是否相等。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串的长度。 - -### **Python3** - - - ```python class Solution: def longestDecomposition(self, text: str) -> int: @@ -96,51 +82,91 @@ class Solution: return 1 ``` -```python -class Solution: - def longestDecomposition(self, text: str) -> int: - ans = 0 - i, j = 0, len(text) - 1 - while i <= j: - k = 1 - ok = False - while i + k - 1 < j - k + 1: - if text[i : i + k] == text[j - k + 1 : j + 1]: - ans += 2 - i += k - j -= k - ok = True - break - k += 1 - if not ok: - ans += 1 - break - return ans +```java +class Solution { + public int longestDecomposition(String text) { + int n = text.length(); + if (n < 2) { + return n; + } + for (int i = 1; i <= n >> 1; ++i) { + if (text.substring(0, i).equals(text.substring(n - i))) { + return 2 + longestDecomposition(text.substring(i, n - i)); + } + } + return 1; + } +} +``` + +```cpp +class Solution { +public: + int longestDecomposition(string text) { + int n = text.size(); + if (n < 2) return n; + for (int i = 1; i <= n >> 1; ++i) { + if (text.substr(0, i) == text.substr(n - i)) { + return 2 + longestDecomposition(text.substr(i, n - i - i)); + } + } + return 1; + } +}; ``` +```go +func longestDecomposition(text string) int { + n := len(text) + if n < 2 { + return n + } + for i := 1; i <= n>>1; i++ { + if text[:i] == text[n-i:] { + return 2 + longestDecomposition(text[i:n-i]) + } + } + return 1 +} +``` + +```ts +function longestDecomposition(text: string): number { + const n: number = text.length; + if (n < 2) { + return n; + } + for (let i: number = 1; i <= n >> 1; i++) { + if (text.slice(0, i) === text.slice(n - i)) { + return 2 + longestDecomposition(text.slice(i, n - i)); + } + } + return 1; +} +``` + + + +### 方法二:字符串哈希 + +**字符串哈希**是把一个任意长度的字符串映射成一个非负整数,并且其冲突的概率几乎为 $0$。字符串哈希用于计算字符串哈希值,快速判断两个字符串是否相等。 + +因此,在方法一的基础上,我们可以使用字符串哈希的方法,在 $O(1)$ 时间内比较两个字符串是否相等。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串的长度。 + + + ```python class Solution: def longestDecomposition(self, text: str) -> int: - def get(l, r): - return (h[r] - h[l - 1] * p[r - l + 1]) % mod - - n = len(text) - base = 131 - mod = int(1e9) + 7 - h = [0] * (n + 10) - p = [1] * (n + 10) - for i, c in enumerate(text): - t = ord(c) - ord('a') + 1 - h[i + 1] = (h[i] * base) % mod + t - p[i + 1] = (p[i] * base) % mod - ans = 0 - i, j = 0, n - 1 + i, j = 0, len(text) - 1 while i <= j: k = 1 ok = False while i + k - 1 < j - k + 1: - if get(i + 1, i + k) == get(j - k + 2, j + 1): + if text[i : i + k] == text[j - k + 1 : j + 1]: ans += 2 i += k j -= k @@ -153,27 +179,6 @@ class Solution: return ans ``` -### **Java** - - - -```java -class Solution { - public int longestDecomposition(String text) { - int n = text.length(); - if (n < 2) { - return n; - } - for (int i = 1; i <= n >> 1; ++i) { - if (text.substring(0, i).equals(text.substring(n - i))) { - return 2 + longestDecomposition(text.substring(i, n - i)); - } - } - return 1; - } -} -``` - ```java class Solution { public int longestDecomposition(String text) { @@ -208,27 +213,23 @@ class Solution { } ``` -```java +```cpp class Solution { - private long[] h; - private long[] p; - - public int longestDecomposition(String text) { - int n = text.length(); - int base = 131; - h = new long[n + 10]; - p = new long[n + 10]; - p[0] = 1; - for (int i = 0; i < n; ++i) { - int t = text.charAt(i) - 'a' + 1; - h[i + 1] = h[i] * base + t; - p[i + 1] = p[i] * base; - } +public: + int longestDecomposition(string text) { int ans = 0; - for (int i = 0, j = n - 1; i <= j;) { - boolean ok = false; + auto check = [&](int i, int j, int k) -> bool { + while (k--) { + if (text[i++] != text[j++]) { + return false; + } + } + return true; + }; + for (int i = 0, j = text.size() - 1; i <= j;) { + bool ok = false; for (int k = 1; i + k - 1 < j - k + 1; ++k) { - if (get(i + 1, i + k) == get(j - k + 2, j + 1)) { + if (check(i, j - k + 1, k)) { ans += 2; i += k; j -= k; @@ -237,54 +238,122 @@ class Solution { } } if (!ok) { - ++ans; + ans += 1; break; } } return ans; } +}; +``` - private long get(int i, int j) { - return h[j] - h[i - 1] * p[j - i + 1]; - } +```go +func longestDecomposition(text string) (ans int) { + for i, j := 0, len(text)-1; i <= j; { + ok := false + for k := 1; i+k-1 < j-k+1; k++ { + if text[i:i+k] == text[j-k+1:j+1] { + ans += 2 + i += k + j -= k + ok = true + break + } + } + if !ok { + ans++ + break + } + } + return } ``` -### **C++** - -```cpp -class Solution { -public: - int longestDecomposition(string text) { - int n = text.size(); - if (n < 2) return n; - for (int i = 1; i <= n >> 1; ++i) { - if (text.substr(0, i) == text.substr(n - i)) { - return 2 + longestDecomposition(text.substr(i, n - i - i)); +```ts +function longestDecomposition(text: string): number { + let ans = 0; + for (let i = 0, j = text.length - 1; i <= j; ) { + let ok = false; + for (let k = 1; i + k - 1 < j - k + 1; ++k) { + if (text.slice(i, i + k) === text.slice(j - k + 1, j + 1)) { + ans += 2; + i += k; + j -= k; + ok = true; + break; } } - return 1; + if (!ok) { + ++ans; + break; + } } -}; + return ans; +} ``` -```cpp + + +### 方法三 + + + +```python +class Solution: + def longestDecomposition(self, text: str) -> int: + def get(l, r): + return (h[r] - h[l - 1] * p[r - l + 1]) % mod + + n = len(text) + base = 131 + mod = int(1e9) + 7 + h = [0] * (n + 10) + p = [1] * (n + 10) + for i, c in enumerate(text): + t = ord(c) - ord('a') + 1 + h[i + 1] = (h[i] * base) % mod + t + p[i + 1] = (p[i] * base) % mod + + ans = 0 + i, j = 0, n - 1 + while i <= j: + k = 1 + ok = False + while i + k - 1 < j - k + 1: + if get(i + 1, i + k) == get(j - k + 2, j + 1): + ans += 2 + i += k + j -= k + ok = True + break + k += 1 + if not ok: + ans += 1 + break + return ans +``` + +```java class Solution { -public: - int longestDecomposition(string text) { + private long[] h; + private long[] p; + + public int longestDecomposition(String text) { + int n = text.length(); + int base = 131; + h = new long[n + 10]; + p = new long[n + 10]; + p[0] = 1; + for (int i = 0; i < n; ++i) { + int t = text.charAt(i) - 'a' + 1; + h[i + 1] = h[i] * base + t; + p[i + 1] = p[i] * base; + } int ans = 0; - auto check = [&](int i, int j, int k) -> bool { - while (k--) { - if (text[i++] != text[j++]) { - return false; - } - } - return true; - }; - for (int i = 0, j = text.size() - 1; i <= j;) { - bool ok = false; + for (int i = 0, j = n - 1; i <= j;) { + boolean ok = false; for (int k = 1; i + k - 1 < j - k + 1; ++k) { - if (check(i, j - k + 1, k)) { + if (get(i + 1, i + k) == get(j - k + 2, j + 1)) { ans += 2; i += k; j -= k; @@ -293,13 +362,17 @@ public: } } if (!ok) { - ans += 1; + ++ans; break; } } return ans; } -}; + + private long get(int i, int j) { + return h[j] - h[i - 1] * p[j - i + 1]; + } +} ``` ```cpp @@ -344,45 +417,6 @@ public: }; ``` -### **Go** - -```go -func longestDecomposition(text string) int { - n := len(text) - if n < 2 { - return n - } - for i := 1; i <= n>>1; i++ { - if text[:i] == text[n-i:] { - return 2 + longestDecomposition(text[i:n-i]) - } - } - return 1 -} -``` - -```go -func longestDecomposition(text string) (ans int) { - for i, j := 0, len(text)-1; i <= j; { - ok := false - for k := 1; i+k-1 < j-k+1; k++ { - if text[i:i+k] == text[j-k+1:j+1] { - ans += 2 - i += k - j -= k - ok = true - break - } - } - if !ok { - ans++ - break - } - } - return -} -``` - ```go func longestDecomposition(text string) (ans int) { n := len(text) @@ -419,50 +453,6 @@ func longestDecomposition(text string) (ans int) { } ``` -### **TypeScript** - -```ts -function longestDecomposition(text: string): number { - const n: number = text.length; - if (n < 2) { - return n; - } - for (let i: number = 1; i <= n >> 1; i++) { - if (text.slice(0, i) === text.slice(n - i)) { - return 2 + longestDecomposition(text.slice(i, n - i)); - } - } - return 1; -} -``` - -```ts -function longestDecomposition(text: string): number { - let ans = 0; - for (let i = 0, j = text.length - 1; i <= j; ) { - let ok = false; - for (let k = 1; i + k - 1 < j - k + 1; ++k) { - if (text.slice(i, i + k) === text.slice(j - k + 1, j + 1)) { - ans += 2; - i += k; - j -= k; - ok = true; - break; - } - } - if (!ok) { - ++ans; - break; - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/README_EN.md b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/README_EN.md index c98cd0c44c662..043794a670f6f 100644 --- a/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/README_EN.md +++ b/solution/1100-1199/1147.Longest Chunked Palindrome Decomposition/README_EN.md @@ -49,7 +49,7 @@ ## Solutions -**Solution 1: Greedy + Two Pointers** +### Solution 1: Greedy + Two Pointers We can start from both ends of the string, looking for the shortest, identical, and non-overlapping prefixes and suffixes: @@ -64,18 +64,8 @@ Suppose there is a prefix $A_1$ and a suffix $A_2$ that meet the conditions, and The time complexity is $O(n^2)$, and the space complexity is $O(n)$ or $O(1)$. Here, $n$ is the length of the string. -**Solution 2: String Hash** - -**String hash** is to map a string of any length to a non-negative integer, and its collision probability is almost $0$. String hash is used to calculate the hash value of a string and quickly determine whether two strings are equal. - -Therefore, based on Solution 1, we can use the method of string hash to compare whether two strings are equal in $O(1)$ time. - -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 longestDecomposition(self, text: str) -> int: @@ -88,51 +78,91 @@ class Solution: return 1 ``` -```python -class Solution: - def longestDecomposition(self, text: str) -> int: - ans = 0 - i, j = 0, len(text) - 1 - while i <= j: - k = 1 - ok = False - while i + k - 1 < j - k + 1: - if text[i : i + k] == text[j - k + 1 : j + 1]: - ans += 2 - i += k - j -= k - ok = True - break - k += 1 - if not ok: - ans += 1 - break - return ans +```java +class Solution { + public int longestDecomposition(String text) { + int n = text.length(); + if (n < 2) { + return n; + } + for (int i = 1; i <= n >> 1; ++i) { + if (text.substring(0, i).equals(text.substring(n - i))) { + return 2 + longestDecomposition(text.substring(i, n - i)); + } + } + return 1; + } +} ``` +```cpp +class Solution { +public: + int longestDecomposition(string text) { + int n = text.size(); + if (n < 2) return n; + for (int i = 1; i <= n >> 1; ++i) { + if (text.substr(0, i) == text.substr(n - i)) { + return 2 + longestDecomposition(text.substr(i, n - i - i)); + } + } + return 1; + } +}; +``` + +```go +func longestDecomposition(text string) int { + n := len(text) + if n < 2 { + return n + } + for i := 1; i <= n>>1; i++ { + if text[:i] == text[n-i:] { + return 2 + longestDecomposition(text[i:n-i]) + } + } + return 1 +} +``` + +```ts +function longestDecomposition(text: string): number { + const n: number = text.length; + if (n < 2) { + return n; + } + for (let i: number = 1; i <= n >> 1; i++) { + if (text.slice(0, i) === text.slice(n - i)) { + return 2 + longestDecomposition(text.slice(i, n - i)); + } + } + return 1; +} +``` + + + +### Solution 2: String Hash + +**String hash** is to map a string of any length to a non-negative integer, and its collision probability is almost $0$. String hash is used to calculate the hash value of a string and quickly determine whether two strings are equal. + +Therefore, based on Solution 1, we can use the method of string hash to compare whether two strings are equal in $O(1)$ time. + +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 longestDecomposition(self, text: str) -> int: - def get(l, r): - return (h[r] - h[l - 1] * p[r - l + 1]) % mod - - n = len(text) - base = 131 - mod = int(1e9) + 7 - h = [0] * (n + 10) - p = [1] * (n + 10) - for i, c in enumerate(text): - t = ord(c) - ord('a') + 1 - h[i + 1] = (h[i] * base) % mod + t - p[i + 1] = (p[i] * base) % mod - ans = 0 - i, j = 0, n - 1 + i, j = 0, len(text) - 1 while i <= j: k = 1 ok = False while i + k - 1 < j - k + 1: - if get(i + 1, i + k) == get(j - k + 2, j + 1): + if text[i : i + k] == text[j - k + 1 : j + 1]: ans += 2 i += k j -= k @@ -145,25 +175,6 @@ class Solution: return ans ``` -### **Java** - -```java -class Solution { - public int longestDecomposition(String text) { - int n = text.length(); - if (n < 2) { - return n; - } - for (int i = 1; i <= n >> 1; ++i) { - if (text.substring(0, i).equals(text.substring(n - i))) { - return 2 + longestDecomposition(text.substring(i, n - i)); - } - } - return 1; - } -} -``` - ```java class Solution { public int longestDecomposition(String text) { @@ -198,27 +209,23 @@ class Solution { } ``` -```java +```cpp class Solution { - private long[] h; - private long[] p; - - public int longestDecomposition(String text) { - int n = text.length(); - int base = 131; - h = new long[n + 10]; - p = new long[n + 10]; - p[0] = 1; - for (int i = 0; i < n; ++i) { - int t = text.charAt(i) - 'a' + 1; - h[i + 1] = h[i] * base + t; - p[i + 1] = p[i] * base; - } +public: + int longestDecomposition(string text) { int ans = 0; - for (int i = 0, j = n - 1; i <= j;) { - boolean ok = false; + auto check = [&](int i, int j, int k) -> bool { + while (k--) { + if (text[i++] != text[j++]) { + return false; + } + } + return true; + }; + for (int i = 0, j = text.size() - 1; i <= j;) { + bool ok = false; for (int k = 1; i + k - 1 < j - k + 1; ++k) { - if (get(i + 1, i + k) == get(j - k + 2, j + 1)) { + if (check(i, j - k + 1, k)) { ans += 2; i += k; j -= k; @@ -227,54 +234,122 @@ class Solution { } } if (!ok) { - ++ans; + ans += 1; break; } } return ans; } +}; +``` - private long get(int i, int j) { - return h[j] - h[i - 1] * p[j - i + 1]; - } +```go +func longestDecomposition(text string) (ans int) { + for i, j := 0, len(text)-1; i <= j; { + ok := false + for k := 1; i+k-1 < j-k+1; k++ { + if text[i:i+k] == text[j-k+1:j+1] { + ans += 2 + i += k + j -= k + ok = true + break + } + } + if !ok { + ans++ + break + } + } + return } ``` -### **C++** - -```cpp -class Solution { -public: - int longestDecomposition(string text) { - int n = text.size(); - if (n < 2) return n; - for (int i = 1; i <= n >> 1; ++i) { - if (text.substr(0, i) == text.substr(n - i)) { - return 2 + longestDecomposition(text.substr(i, n - i - i)); +```ts +function longestDecomposition(text: string): number { + let ans = 0; + for (let i = 0, j = text.length - 1; i <= j; ) { + let ok = false; + for (let k = 1; i + k - 1 < j - k + 1; ++k) { + if (text.slice(i, i + k) === text.slice(j - k + 1, j + 1)) { + ans += 2; + i += k; + j -= k; + ok = true; + break; } } - return 1; + if (!ok) { + ++ans; + break; + } } -}; + return ans; +} ``` -```cpp + + +### Solution 3 + + + +```python +class Solution: + def longestDecomposition(self, text: str) -> int: + def get(l, r): + return (h[r] - h[l - 1] * p[r - l + 1]) % mod + + n = len(text) + base = 131 + mod = int(1e9) + 7 + h = [0] * (n + 10) + p = [1] * (n + 10) + for i, c in enumerate(text): + t = ord(c) - ord('a') + 1 + h[i + 1] = (h[i] * base) % mod + t + p[i + 1] = (p[i] * base) % mod + + ans = 0 + i, j = 0, n - 1 + while i <= j: + k = 1 + ok = False + while i + k - 1 < j - k + 1: + if get(i + 1, i + k) == get(j - k + 2, j + 1): + ans += 2 + i += k + j -= k + ok = True + break + k += 1 + if not ok: + ans += 1 + break + return ans +``` + +```java class Solution { -public: - int longestDecomposition(string text) { + private long[] h; + private long[] p; + + public int longestDecomposition(String text) { + int n = text.length(); + int base = 131; + h = new long[n + 10]; + p = new long[n + 10]; + p[0] = 1; + for (int i = 0; i < n; ++i) { + int t = text.charAt(i) - 'a' + 1; + h[i + 1] = h[i] * base + t; + p[i + 1] = p[i] * base; + } int ans = 0; - auto check = [&](int i, int j, int k) -> bool { - while (k--) { - if (text[i++] != text[j++]) { - return false; - } - } - return true; - }; - for (int i = 0, j = text.size() - 1; i <= j;) { - bool ok = false; + for (int i = 0, j = n - 1; i <= j;) { + boolean ok = false; for (int k = 1; i + k - 1 < j - k + 1; ++k) { - if (check(i, j - k + 1, k)) { + if (get(i + 1, i + k) == get(j - k + 2, j + 1)) { ans += 2; i += k; j -= k; @@ -283,13 +358,17 @@ public: } } if (!ok) { - ans += 1; + ++ans; break; } } return ans; } -}; + + private long get(int i, int j) { + return h[j] - h[i - 1] * p[j - i + 1]; + } +} ``` ```cpp @@ -334,45 +413,6 @@ public: }; ``` -### **Go** - -```go -func longestDecomposition(text string) int { - n := len(text) - if n < 2 { - return n - } - for i := 1; i <= n>>1; i++ { - if text[:i] == text[n-i:] { - return 2 + longestDecomposition(text[i:n-i]) - } - } - return 1 -} -``` - -```go -func longestDecomposition(text string) (ans int) { - for i, j := 0, len(text)-1; i <= j; { - ok := false - for k := 1; i+k-1 < j-k+1; k++ { - if text[i:i+k] == text[j-k+1:j+1] { - ans += 2 - i += k - j -= k - ok = true - break - } - } - if !ok { - ans++ - break - } - } - return -} -``` - ```go func longestDecomposition(text string) (ans int) { n := len(text) @@ -409,50 +449,6 @@ func longestDecomposition(text string) (ans int) { } ``` -### **TypeScript** - -```ts -function longestDecomposition(text: string): number { - const n: number = text.length; - if (n < 2) { - return n; - } - for (let i: number = 1; i <= n >> 1; i++) { - if (text.slice(0, i) === text.slice(n - i)) { - return 2 + longestDecomposition(text.slice(i, n - i)); - } - } - return 1; -} -``` - -```ts -function longestDecomposition(text: string): number { - let ans = 0; - for (let i = 0, j = text.length - 1; i <= j; ) { - let ok = false; - for (let k = 1; i + k - 1 < j - k + 1; ++k) { - if (text.slice(i, i + k) === text.slice(j - k + 1, j + 1)) { - ans += 2; - i += k; - j -= k; - ok = true; - break; - } - } - if (!ok) { - ++ans; - break; - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1148.Article Views I/README.md b/solution/1100-1199/1148.Article Views I/README.md index 61ac964a58201..4450764793f94 100644 --- a/solution/1100-1199/1148.Article Views I/README.md +++ b/solution/1100-1199/1148.Article Views I/README.md @@ -60,16 +60,12 @@ Views 表: ## 解法 - - -**方法一:DISTINCT + WHERE** +### 方法一:DISTINCT + WHERE 我们利用 `WHERE` 子句来筛选出 `author_id` 和 `viewer_id` 相等的记录,然后利用 `DISTINCT` 来去重,最后按照 `id` 排序即可。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT DISTINCT author_id AS id @@ -79,3 +75,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1100-1199/1148.Article Views I/README_EN.md b/solution/1100-1199/1148.Article Views I/README_EN.md index d82057a455819..a2e83d7e7a405 100644 --- a/solution/1100-1199/1148.Article Views I/README_EN.md +++ b/solution/1100-1199/1148.Article Views I/README_EN.md @@ -56,9 +56,9 @@ Views table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -69,3 +69,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1100-1199/1149.Article Views II/README.md b/solution/1100-1199/1149.Article Views II/README.md index 4382e051564d5..934e537c035f4 100644 --- a/solution/1100-1199/1149.Article Views II/README.md +++ b/solution/1100-1199/1149.Article Views II/README.md @@ -59,16 +59,12 @@ Views 表: ## 解法 - - -**方法一:DISTINCT + GROUP BY + HAVING** +### 方法一:DISTINCT + GROUP BY + HAVING 我们将数据按照 `viewer_id` 和 `view_date` 分组,然后利用 `HAVING` 子句来筛选出浏览文章数大于 $1$ 的记录,最后按照 `id` 去重排序即可。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT DISTINCT viewer_id AS id @@ -79,3 +75,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1100-1199/1149.Article Views II/README_EN.md b/solution/1100-1199/1149.Article Views II/README_EN.md index 3b0704dfd6665..de7c33ed5ef35 100644 --- a/solution/1100-1199/1149.Article Views II/README_EN.md +++ b/solution/1100-1199/1149.Article Views II/README_EN.md @@ -56,9 +56,9 @@ Views table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -70,3 +70,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/README.md b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/README.md index be5a58ff003b0..38e61389632d7 100644 --- a/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/README.md +++ b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/README.md @@ -44,26 +44,14 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们注意到,数组 $nums$ 中的元素是非递减的,也就是说,数组 $nums$ 中的元素单调递增。因此,我们可以使用二分查找的方法,找到数组 $nums$ 中第一个大于等于 $target$ 的元素的下标 $left$,以及第一个大于 $target$ 的元素的下标 $right$。如果 $right - left > \frac{n}{2}$,则说明数组 $nums$ 中的元素 $target$ 出现的次数超过了数组长度的一半,因此返回 $true$,否则返回 $false$。 时间复杂度 $O(\log n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。 -**方法二:二分查找(优化)** - -方法一中,我们使用了两次二分查找,分别找到数组 $nums$ 中第一个大于等于 $target$ 的元素的下标 $left$,以及第一个大于 $target$ 的元素的下标 $right$。但是,我们可以使用一次二分查找,找到数组 $nums$ 中第一个大于等于 $target$ 的元素的下标 $left$,然后判断 $nums[left + \frac{n}{2}]$ 是否等于 $target$,如果相等,说明数组 $nums$ 中的元素 $target$ 出现的次数超过了数组长度的一半,因此返回 $true$,否则返回 $false$。 - -时间复杂度 $O(\log n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。 - -### **Python3** - - - ```python class Solution: def isMajorityElement(self, nums: List[int], target: int) -> bool: @@ -72,18 +60,6 @@ class Solution: return right - left > len(nums) // 2 ``` -```python -class Solution: - def isMajorityElement(self, nums: List[int], target: int) -> bool: - left = bisect_left(nums, target) - right = left + len(nums) // 2 - return right < len(nums) and nums[right] == target -``` - -### **Java** - - - ```java class Solution { public boolean isMajorityElement(int[] nums, int target) { @@ -107,6 +83,64 @@ class Solution { } ``` +```cpp +class Solution { +public: + bool isMajorityElement(vector& nums, int target) { + auto left = lower_bound(nums.begin(), nums.end(), target); + auto right = upper_bound(nums.begin(), nums.end(), target); + return right - left > nums.size() / 2; + } +}; +``` + +```go +func isMajorityElement(nums []int, target int) bool { + left := sort.SearchInts(nums, target) + right := sort.SearchInts(nums, target+1) + return right-left > len(nums)/2 +} +``` + +```ts +function isMajorityElement(nums: number[], target: number): boolean { + const search = (x: number) => { + let left = 0; + let right = nums.length; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + }; + const left = search(target); + const right = search(target + 1); + return right - left > nums.length >> 1; +} +``` + + + +### 方法二:二分查找(优化) + +方法一中,我们使用了两次二分查找,分别找到数组 $nums$ 中第一个大于等于 $target$ 的元素的下标 $left$,以及第一个大于 $target$ 的元素的下标 $right$。但是,我们可以使用一次二分查找,找到数组 $nums$ 中第一个大于等于 $target$ 的元素的下标 $left$,然后判断 $nums[left + \frac{n}{2}]$ 是否等于 $target$,如果相等,说明数组 $nums$ 中的元素 $target$ 出现的次数超过了数组长度的一半,因此返回 $true$,否则返回 $false$。 + +时间复杂度 $O(\log n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。 + + + +```python +class Solution: + def isMajorityElement(self, nums: List[int], target: int) -> bool: + left = bisect_left(nums, target) + right = left + len(nums) // 2 + return right < len(nums) and nums[right] == target +``` + ```java class Solution { public boolean isMajorityElement(int[] nums, int target) { @@ -131,19 +165,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool isMajorityElement(vector& nums, int target) { - auto left = lower_bound(nums.begin(), nums.end(), target); - auto right = upper_bound(nums.begin(), nums.end(), target); - return right - left > nums.size() / 2; - } -}; -``` - ```cpp class Solution { public: @@ -156,16 +177,6 @@ public: }; ``` -### **Go** - -```go -func isMajorityElement(nums []int, target int) bool { - left := sort.SearchInts(nums, target) - right := sort.SearchInts(nums, target+1) - return right-left > len(nums)/2 -} -``` - ```go func isMajorityElement(nums []int, target int) bool { n := len(nums) @@ -175,29 +186,6 @@ func isMajorityElement(nums []int, target int) bool { } ``` -### **TypeScript** - -```ts -function isMajorityElement(nums: number[], target: number): boolean { - const search = (x: number) => { - let left = 0; - let right = nums.length; - while (left < right) { - const mid = (left + right) >> 1; - if (nums[mid] >= x) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - }; - const left = search(target); - const right = search(target + 1); - return right - left > nums.length >> 1; -} -``` - ```ts function isMajorityElement(nums: number[], target: number): boolean { const search = (x: number) => { @@ -220,10 +208,6 @@ function isMajorityElement(nums: number[], target: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/README_EN.md b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/README_EN.md index 70d248afc67b6..62b914134e851 100644 --- a/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/README_EN.md +++ b/solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/README_EN.md @@ -38,22 +38,14 @@ Thus, 101 is not a majority element because 2 > 4/2 is false. ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search We notice that the elements in the array $nums$ are non-decreasing, that is, the elements in the array $nums$ are monotonically increasing. Therefore, we can use the method of binary search to find the index $left$ of the first element in the array $nums$ that is greater than or equal to $target$, and the index $right$ of the first element in the array $nums$ that is greater than $target$. If $right - left > \frac{n}{2}$, it means that the number of occurrences of the element $target$ in the array $nums$ exceeds half of the length of the array, so return $true$, otherwise return $false$. The time complexity is $O(\log n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$. -**Solution 2: Binary Search (Optimized)** - -In Solution 1, we used binary search twice to find the index $left$ of the first element in the array $nums$ that is greater than or equal to $target$, and the index $right$ of the first element in the array $nums$ that is greater than $target$. However, we can use binary search once to find the index $left$ of the first element in the array $nums$ that is greater than or equal to $target$, and then judge whether $nums[left + \frac{n}{2}]$ is equal to $target$. If they are equal, it means that the number of occurrences of the element $target$ in the array $nums$ exceeds half of the length of the array, so return $true$, otherwise return $false$. - -The time complexity is $O(\log n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$. - -### **Python3** - ```python class Solution: def isMajorityElement(self, nums: List[int], target: int) -> bool: @@ -62,16 +54,6 @@ class Solution: return right - left > len(nums) // 2 ``` -```python -class Solution: - def isMajorityElement(self, nums: List[int], target: int) -> bool: - left = bisect_left(nums, target) - right = left + len(nums) // 2 - return right < len(nums) and nums[right] == target -``` - -### **Java** - ```java class Solution { public boolean isMajorityElement(int[] nums, int target) { @@ -95,6 +77,64 @@ class Solution { } ``` +```cpp +class Solution { +public: + bool isMajorityElement(vector& nums, int target) { + auto left = lower_bound(nums.begin(), nums.end(), target); + auto right = upper_bound(nums.begin(), nums.end(), target); + return right - left > nums.size() / 2; + } +}; +``` + +```go +func isMajorityElement(nums []int, target int) bool { + left := sort.SearchInts(nums, target) + right := sort.SearchInts(nums, target+1) + return right-left > len(nums)/2 +} +``` + +```ts +function isMajorityElement(nums: number[], target: number): boolean { + const search = (x: number) => { + let left = 0; + let right = nums.length; + while (left < right) { + const mid = (left + right) >> 1; + if (nums[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + }; + const left = search(target); + const right = search(target + 1); + return right - left > nums.length >> 1; +} +``` + + + +### Solution 2: Binary Search (Optimized) + +In Solution 1, we used binary search twice to find the index $left$ of the first element in the array $nums$ that is greater than or equal to $target$, and the index $right$ of the first element in the array $nums$ that is greater than $target$. However, we can use binary search once to find the index $left$ of the first element in the array $nums$ that is greater than or equal to $target$, and then judge whether $nums[left + \frac{n}{2}]$ is equal to $target$. If they are equal, it means that the number of occurrences of the element $target$ in the array $nums$ exceeds half of the length of the array, so return $true$, otherwise return $false$. + +The time complexity is $O(\log n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$. + + + +```python +class Solution: + def isMajorityElement(self, nums: List[int], target: int) -> bool: + left = bisect_left(nums, target) + right = left + len(nums) // 2 + return right < len(nums) and nums[right] == target +``` + ```java class Solution { public boolean isMajorityElement(int[] nums, int target) { @@ -119,19 +159,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool isMajorityElement(vector& nums, int target) { - auto left = lower_bound(nums.begin(), nums.end(), target); - auto right = upper_bound(nums.begin(), nums.end(), target); - return right - left > nums.size() / 2; - } -}; -``` - ```cpp class Solution { public: @@ -144,16 +171,6 @@ public: }; ``` -### **Go** - -```go -func isMajorityElement(nums []int, target int) bool { - left := sort.SearchInts(nums, target) - right := sort.SearchInts(nums, target+1) - return right-left > len(nums)/2 -} -``` - ```go func isMajorityElement(nums []int, target int) bool { n := len(nums) @@ -163,29 +180,6 @@ func isMajorityElement(nums []int, target int) bool { } ``` -### **TypeScript** - -```ts -function isMajorityElement(nums: number[], target: number): boolean { - const search = (x: number) => { - let left = 0; - let right = nums.length; - while (left < right) { - const mid = (left + right) >> 1; - if (nums[mid] >= x) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - }; - const left = search(target); - const right = search(target + 1); - return right - left > nums.length >> 1; -} -``` - ```ts function isMajorityElement(nums: number[], target: number): boolean { const search = (x: number) => { @@ -208,10 +202,6 @@ function isMajorityElement(nums: number[], target: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1151.Minimum Swaps to Group All 1's Together/README.md b/solution/1100-1199/1151.Minimum Swaps to Group All 1's Together/README.md index 8ae6359d2de9e..32df0263cd4fc 100644 --- a/solution/1100-1199/1151.Minimum Swaps to Group All 1's Together/README.md +++ b/solution/1100-1199/1151.Minimum Swaps to Group All 1's Together/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 我们先统计数组中 $1$ 的个数,记为 $k$。然后我们使用滑动窗口,窗口大小为 $k$,窗口右边界从左向右移动,统计窗口内 $1$ 的个数,记为 $t$。每次移动窗口时,都更新 $t$ 的值,最后窗口右边界移动到数组末尾时,窗口内 $1$ 的个数最多,记为 $mx$。最后答案为 $k - mx$。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def minSwaps(self, data: List[int]) -> int: @@ -85,10 +79,6 @@ class Solution: return k - mx ``` -### **Java** - - - ```java class Solution { public int minSwaps(int[] data) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func minSwaps(data []int) int { k := 0 @@ -158,8 +144,6 @@ func minSwaps(data []int) int { } ``` -### **TypeScript** - ```ts function minSwaps(data: number[]): number { const k = data.reduce((acc, cur) => acc + cur, 0); @@ -173,10 +157,6 @@ function minSwaps(data: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1151.Minimum Swaps to Group All 1's Together/README_EN.md b/solution/1100-1199/1151.Minimum Swaps to Group All 1's Together/README_EN.md index 3396838bd434e..e427172be66af 100644 --- a/solution/1100-1199/1151.Minimum Swaps to Group All 1's Together/README_EN.md +++ b/solution/1100-1199/1151.Minimum Swaps to Group All 1's Together/README_EN.md @@ -45,7 +45,7 @@ The minimum is 1. ## Solutions -**Solution 1: Sliding Window** +### Solution 1: Sliding Window First, we count the number of $1$s in the array, denoted as $k$. Then we use a sliding window of size $k$, moving the right boundary of the window from left to right, and count the number of $1$s in the window, denoted as $t$. Each time we move the window, we update the value of $t$. Finally, when the right boundary of the window moves to the end of the array, the number of $1$s in the window is the maximum, denoted as $mx$. The final answer is $k - mx$. @@ -53,8 +53,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is -### **Python3** - ```python class Solution: def minSwaps(self, data: List[int]) -> int: @@ -68,8 +66,6 @@ class Solution: return k - mx ``` -### **Java** - ```java class Solution { public int minSwaps(int[] data) { @@ -92,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func minSwaps(data []int) int { k := 0 @@ -139,8 +131,6 @@ func minSwaps(data []int) int { } ``` -### **TypeScript** - ```ts function minSwaps(data: number[]): number { const k = data.reduce((acc, cur) => acc + cur, 0); @@ -154,10 +144,6 @@ function minSwaps(data: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1152.Analyze User Website Visit Pattern/README.md b/solution/1100-1199/1152.Analyze User Website Visit Pattern/README.md index ba47c83ed909a..6486fc9bb929c 100644 --- a/solution/1100-1199/1152.Analyze User Website Visit Pattern/README.md +++ b/solution/1100-1199/1152.Analyze User Website Visit Pattern/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:哈希表 + 排序** +### 方法一:哈希表 + 排序 我们先用哈希表 $d$ 记录每个用户访问的网站,然后遍历 $d$,对于每个用户,我们枚举其访问的所有三元组,统计去重三元组的出现次数,最后遍历所有三元组,返回出现次数最多的、字典序最小的三元组。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def mostVisitedPattern( @@ -104,10 +98,6 @@ class Solution: return sorted(cnt.items(), key=lambda x: (-x[1], x[0]))[0][0] ``` -### **Java** - - - ```java class Solution { public List mostVisitedPattern(String[] username, int[] timestamp, String[] website) { @@ -163,8 +153,6 @@ class Node { } ``` -### **C++** - ```cpp class Solution { public: @@ -218,8 +206,6 @@ public: }; ``` -### **Go** - ```go func mostVisitedPattern(username []string, timestamp []int, website []string) []string { d := map[string][]pair{} @@ -262,10 +248,6 @@ type pair struct { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md b/solution/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md index 850a27848f8dc..b33cc4c0d515c 100644 --- a/solution/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md +++ b/solution/1100-1199/1152.Analyze User Website Visit Pattern/README_EN.md @@ -62,7 +62,7 @@ The pattern ("home", "home", "home") has score 0 ( ## Solutions -**Solution 1: Hash Table + Sorting** +### Solution 1: Hash Table + Sorting First, we use a hash table $d$ to record the websites each user visits. Then we traverse $d$. For each user, we enumerate all the triplets they visited, count the occurrence of distinct triplets, and finally traverse all triplets, returning the one with the highest occurrence and the smallest lexicographic order. @@ -70,8 +70,6 @@ The time complexity is $O(n^3)$, and the space complexity is $O(n^3)$. Here, $n$ -### **Python3** - ```python class Solution: def mostVisitedPattern( @@ -97,8 +95,6 @@ class Solution: return sorted(cnt.items(), key=lambda x: (-x[1], x[0]))[0][0] ``` -### **Java** - ```java class Solution { public List mostVisitedPattern(String[] username, int[] timestamp, String[] website) { @@ -154,8 +150,6 @@ class Node { } ``` -### **C++** - ```cpp class Solution { public: @@ -209,8 +203,6 @@ public: }; ``` -### **Go** - ```go func mostVisitedPattern(username []string, timestamp []int, website []string) []string { d := map[string][]pair{} @@ -253,10 +245,6 @@ type pair struct { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1153.String Transforms Into Another String/README.md b/solution/1100-1199/1153.String Transforms Into Another String/README.md index 2a4bd167bdc5e..467400311b755 100644 --- a/solution/1100-1199/1153.String Transforms Into Another String/README.md +++ b/solution/1100-1199/1153.String Transforms Into Another String/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以先判断 `str1` 和 `str2` 是否相等,若相等,直接返回 `true`。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def canConvert(self, str1: str, str2: str) -> bool: @@ -77,10 +71,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean canConvert(String str1, String str2) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +135,6 @@ public: }; ``` -### **Go** - ```go func canConvert(str1 string, str2 string) bool { if str1 == str2 { @@ -174,8 +160,6 @@ func canConvert(str1 string, str2 string) bool { } ``` -### **TypeScript** - ```ts function canConvert(str1: string, str2: string): boolean { if (str1 === str2) { @@ -196,10 +180,6 @@ function canConvert(str1: string, str2: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1153.String Transforms Into Another String/README_EN.md b/solution/1100-1199/1153.String Transforms Into Another String/README_EN.md index a8630d8441dd9..d160131b3a442 100644 --- a/solution/1100-1199/1153.String Transforms Into Another String/README_EN.md +++ b/solution/1100-1199/1153.String Transforms Into Another String/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table First, we can check if `str1` and `str2` are equal. If they are, return `true` directly. @@ -51,8 +51,6 @@ The time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is -### **Python3** - ```python class Solution: def canConvert(self, str1: str, str2: str) -> bool: @@ -69,8 +67,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean canConvert(String str1, String str2) { @@ -103,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +131,6 @@ public: }; ``` -### **Go** - ```go func canConvert(str1 string, str2 string) bool { if str1 == str2 { @@ -164,8 +156,6 @@ func canConvert(str1 string, str2 string) bool { } ``` -### **TypeScript** - ```ts function canConvert(str1: string, str2: string): boolean { if (str1 === str2) { @@ -186,10 +176,6 @@ function canConvert(str1: string, str2: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1154.Day of the Year/README.md b/solution/1100-1199/1154.Day of the Year/README.md index 64e638a496a15..eca4904ed696e 100644 --- a/solution/1100-1199/1154.Day of the Year/README.md +++ b/solution/1100-1199/1154.Day of the Year/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:直接计算** +### 方法一:直接计算 根据题意,给定的日期是公元纪年法的日期,因此可以直接计算出该日期是当年的第几天。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def dayOfYear(self, date: str) -> int: @@ -67,10 +61,6 @@ class Solution: return sum(days[: m - 1]) + d ``` -### **Java** - - - ```java class Solution { public int dayOfYear(String date) { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func dayOfYear(date string) (ans int) { var y, m, d int @@ -125,8 +111,6 @@ func dayOfYear(date string) (ans int) { } ``` -### **TypeScript** - ```ts function dayOfYear(date: string): number { const y = +date.slice(0, 4); @@ -138,8 +122,6 @@ function dayOfYear(date: string): number { } ``` -### **JavaScript** - ```js /** * @param {string} date @@ -155,10 +137,6 @@ var dayOfYear = function (date) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1154.Day of the Year/README_EN.md b/solution/1100-1199/1154.Day of the Year/README_EN.md index 73b40c74701fa..25f9959671a9d 100644 --- a/solution/1100-1199/1154.Day of the Year/README_EN.md +++ b/solution/1100-1199/1154.Day of the Year/README_EN.md @@ -33,7 +33,7 @@ ## Solutions -**Solution 1: Direct Calculation** +### Solution 1: Direct Calculation According to the problem, the given date is in the Gregorian calendar, so we can directly calculate which day of the year it is. @@ -49,8 +49,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def dayOfYear(self, date: str) -> int: @@ -60,8 +58,6 @@ class Solution: return sum(days[: m - 1]) + d ``` -### **Java** - ```java class Solution { public int dayOfYear(String date) { @@ -79,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +92,6 @@ public: }; ``` -### **Go** - ```go func dayOfYear(date string) (ans int) { var y, m, d int @@ -116,8 +108,6 @@ func dayOfYear(date string) (ans int) { } ``` -### **TypeScript** - ```ts function dayOfYear(date: string): number { const y = +date.slice(0, 4); @@ -129,8 +119,6 @@ function dayOfYear(date: string): number { } ``` -### **JavaScript** - ```js /** * @param {string} date @@ -146,10 +134,6 @@ var dayOfYear = function (date) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/README.md b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/README.md index fc38f973b5b64..c03deac9355ce 100644 --- a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/README.md +++ b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示使用 $i$ 个骰子,和为 $j$ 的方案数。那么我们可以得到状态转移方程: @@ -70,10 +68,6 @@ $$ -### **Python3** - - - ```python class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: @@ -87,24 +81,6 @@ class Solution: return f[n][target] ``` -```python -class Solution: - def numRollsToTarget(self, n: int, k: int, target: int) -> int: - f = [1] + [0] * target - mod = 10**9 + 7 - for i in range(1, n + 1): - g = [0] * (target + 1) - for j in range(1, min(i * k, target) + 1): - for h in range(1, min(j, k) + 1): - g[j] = (g[j] + f[j - h]) % mod - f = g - return f[target] -``` - -### **Java** - - - ```java class Solution { public int numRollsToTarget(int n, int k, int target) { @@ -123,28 +99,6 @@ class Solution { } ``` -```java -class Solution { - public int numRollsToTarget(int n, int k, int target) { - final int mod = (int) 1e9 + 7; - int[] f = new int[target + 1]; - f[0] = 1; - for (int i = 1; i <= n; ++i) { - int[] g = new int[target + 1]; - for (int j = 1; j <= Math.min(target, i * k); ++j) { - for (int h = 1; h <= Math.min(j, k); ++h) { - g[j] = (g[j] + f[j - h]) % mod; - } - } - f = g; - } - return f[target]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -165,29 +119,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numRollsToTarget(int n, int k, int target) { - const int mod = 1e9 + 7; - vector f(target + 1); - f[0] = 1; - for (int i = 1; i <= n; ++i) { - vector g(target + 1); - for (int j = 1; j <= min(target, i * k); ++j) { - for (int h = 1; h <= min(j, k); ++h) { - g[j] = (g[j] + f[j - h]) % mod; - } - } - f = move(g); - } - return f[target]; - } -}; -``` - -### **Go** - ```go func numRollsToTarget(n int, k int, target int) int { const mod int = 1e9 + 7 @@ -207,26 +138,6 @@ func numRollsToTarget(n int, k int, target int) int { } ``` -```go -func numRollsToTarget(n int, k int, target int) int { - const mod int = 1e9 + 7 - f := make([]int, target+1) - f[0] = 1 - for i := 1; i <= n; i++ { - g := make([]int, target+1) - for j := 1; j <= min(target, i*k); j++ { - for h := 1; h <= min(j, k); h++ { - g[j] = (g[j] + f[j-h]) % mod - } - } - f = g - } - return f[target] -} -``` - -### **TypeScript** - ```ts function numRollsToTarget(n: number, k: number, target: number): number { const f = Array.from({ length: n + 1 }, () => Array(target + 1).fill(0)); @@ -243,26 +154,6 @@ function numRollsToTarget(n: number, k: number, target: number): number { } ``` -```ts -function numRollsToTarget(n: number, k: number, target: number): number { - const f = Array(target + 1).fill(0); - f[0] = 1; - const mod = 1e9 + 7; - for (let i = 1; i <= n; ++i) { - const g = Array(target + 1).fill(0); - for (let j = 1; j <= Math.min(i * k, target); ++j) { - for (let h = 1; h <= Math.min(j, k); ++h) { - g[j] = (g[j] + f[j - h]) % mod; - } - } - f.splice(0, target + 1, ...g); - } - return f[target]; -} -``` - -### **Rust** - ```rust impl Solution { pub fn num_rolls_to_target(n: i32, k: i32, target: i32) -> i32 { @@ -286,6 +177,103 @@ impl Solution { } ``` + + +### 方法二 + + + +```python +class Solution: + def numRollsToTarget(self, n: int, k: int, target: int) -> int: + f = [1] + [0] * target + mod = 10**9 + 7 + for i in range(1, n + 1): + g = [0] * (target + 1) + for j in range(1, min(i * k, target) + 1): + for h in range(1, min(j, k) + 1): + g[j] = (g[j] + f[j - h]) % mod + f = g + return f[target] +``` + +```java +class Solution { + public int numRollsToTarget(int n, int k, int target) { + final int mod = (int) 1e9 + 7; + int[] f = new int[target + 1]; + f[0] = 1; + for (int i = 1; i <= n; ++i) { + int[] g = new int[target + 1]; + for (int j = 1; j <= Math.min(target, i * k); ++j) { + for (int h = 1; h <= Math.min(j, k); ++h) { + g[j] = (g[j] + f[j - h]) % mod; + } + } + f = g; + } + return f[target]; + } +} +``` + +```cpp +class Solution { +public: + int numRollsToTarget(int n, int k, int target) { + const int mod = 1e9 + 7; + vector f(target + 1); + f[0] = 1; + for (int i = 1; i <= n; ++i) { + vector g(target + 1); + for (int j = 1; j <= min(target, i * k); ++j) { + for (int h = 1; h <= min(j, k); ++h) { + g[j] = (g[j] + f[j - h]) % mod; + } + } + f = move(g); + } + return f[target]; + } +}; +``` + +```go +func numRollsToTarget(n int, k int, target int) int { + const mod int = 1e9 + 7 + f := make([]int, target+1) + f[0] = 1 + for i := 1; i <= n; i++ { + g := make([]int, target+1) + for j := 1; j <= min(target, i*k); j++ { + for h := 1; h <= min(j, k); h++ { + g[j] = (g[j] + f[j-h]) % mod + } + } + f = g + } + return f[target] +} +``` + +```ts +function numRollsToTarget(n: number, k: number, target: number): number { + const f = Array(target + 1).fill(0); + f[0] = 1; + const mod = 1e9 + 7; + for (let i = 1; i <= n; ++i) { + const g = Array(target + 1).fill(0); + for (let j = 1; j <= Math.min(i * k, target); ++j) { + for (let h = 1; h <= Math.min(j, k); ++h) { + g[j] = (g[j] + f[j - h]) % mod; + } + } + f.splice(0, target + 1, ...g); + } + return f[target]; +} +``` + ```rust impl Solution { pub fn num_rolls_to_target(n: i32, k: i32, target: i32) -> i32 { @@ -311,10 +299,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/README_EN.md b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/README_EN.md index 5e766dfd9d706..fee616a4f828d 100644 --- a/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/README_EN.md +++ b/solution/1100-1199/1155.Number of Dice Rolls With Target Sum/README_EN.md @@ -45,7 +45,7 @@ There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1. ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ as the number of ways to get a sum of $j$ using $i$ dice. Then, we can obtain the following state transition equation: @@ -63,8 +63,6 @@ We notice that the state $f[i][j]$ only depends on $f[i-1][]$, so we can use a r -### **Python3** - ```python class Solution: def numRollsToTarget(self, n: int, k: int, target: int) -> int: @@ -78,22 +76,6 @@ class Solution: return f[n][target] ``` -```python -class Solution: - def numRollsToTarget(self, n: int, k: int, target: int) -> int: - f = [1] + [0] * target - mod = 10**9 + 7 - for i in range(1, n + 1): - g = [0] * (target + 1) - for j in range(1, min(i * k, target) + 1): - for h in range(1, min(j, k) + 1): - g[j] = (g[j] + f[j - h]) % mod - f = g - return f[target] -``` - -### **Java** - ```java class Solution { public int numRollsToTarget(int n, int k, int target) { @@ -112,28 +94,6 @@ class Solution { } ``` -```java -class Solution { - public int numRollsToTarget(int n, int k, int target) { - final int mod = (int) 1e9 + 7; - int[] f = new int[target + 1]; - f[0] = 1; - for (int i = 1; i <= n; ++i) { - int[] g = new int[target + 1]; - for (int j = 1; j <= Math.min(target, i * k); ++j) { - for (int h = 1; h <= Math.min(j, k); ++h) { - g[j] = (g[j] + f[j - h]) % mod; - } - } - f = g; - } - return f[target]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -154,29 +114,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numRollsToTarget(int n, int k, int target) { - const int mod = 1e9 + 7; - vector f(target + 1); - f[0] = 1; - for (int i = 1; i <= n; ++i) { - vector g(target + 1); - for (int j = 1; j <= min(target, i * k); ++j) { - for (int h = 1; h <= min(j, k); ++h) { - g[j] = (g[j] + f[j - h]) % mod; - } - } - f = move(g); - } - return f[target]; - } -}; -``` - -### **Go** - ```go func numRollsToTarget(n int, k int, target int) int { const mod int = 1e9 + 7 @@ -196,26 +133,6 @@ func numRollsToTarget(n int, k int, target int) int { } ``` -```go -func numRollsToTarget(n int, k int, target int) int { - const mod int = 1e9 + 7 - f := make([]int, target+1) - f[0] = 1 - for i := 1; i <= n; i++ { - g := make([]int, target+1) - for j := 1; j <= min(target, i*k); j++ { - for h := 1; h <= min(j, k); h++ { - g[j] = (g[j] + f[j-h]) % mod - } - } - f = g - } - return f[target] -} -``` - -### **TypeScript** - ```ts function numRollsToTarget(n: number, k: number, target: number): number { const f = Array.from({ length: n + 1 }, () => Array(target + 1).fill(0)); @@ -232,26 +149,6 @@ function numRollsToTarget(n: number, k: number, target: number): number { } ``` -```ts -function numRollsToTarget(n: number, k: number, target: number): number { - const f = Array(target + 1).fill(0); - f[0] = 1; - const mod = 1e9 + 7; - for (let i = 1; i <= n; ++i) { - const g = Array(target + 1).fill(0); - for (let j = 1; j <= Math.min(i * k, target); ++j) { - for (let h = 1; h <= Math.min(j, k); ++h) { - g[j] = (g[j] + f[j - h]) % mod; - } - } - f.splice(0, target + 1, ...g); - } - return f[target]; -} -``` - -### **Rust** - ```rust impl Solution { pub fn num_rolls_to_target(n: i32, k: i32, target: i32) -> i32 { @@ -275,6 +172,103 @@ impl Solution { } ``` + + +### Solution 2 + + + +```python +class Solution: + def numRollsToTarget(self, n: int, k: int, target: int) -> int: + f = [1] + [0] * target + mod = 10**9 + 7 + for i in range(1, n + 1): + g = [0] * (target + 1) + for j in range(1, min(i * k, target) + 1): + for h in range(1, min(j, k) + 1): + g[j] = (g[j] + f[j - h]) % mod + f = g + return f[target] +``` + +```java +class Solution { + public int numRollsToTarget(int n, int k, int target) { + final int mod = (int) 1e9 + 7; + int[] f = new int[target + 1]; + f[0] = 1; + for (int i = 1; i <= n; ++i) { + int[] g = new int[target + 1]; + for (int j = 1; j <= Math.min(target, i * k); ++j) { + for (int h = 1; h <= Math.min(j, k); ++h) { + g[j] = (g[j] + f[j - h]) % mod; + } + } + f = g; + } + return f[target]; + } +} +``` + +```cpp +class Solution { +public: + int numRollsToTarget(int n, int k, int target) { + const int mod = 1e9 + 7; + vector f(target + 1); + f[0] = 1; + for (int i = 1; i <= n; ++i) { + vector g(target + 1); + for (int j = 1; j <= min(target, i * k); ++j) { + for (int h = 1; h <= min(j, k); ++h) { + g[j] = (g[j] + f[j - h]) % mod; + } + } + f = move(g); + } + return f[target]; + } +}; +``` + +```go +func numRollsToTarget(n int, k int, target int) int { + const mod int = 1e9 + 7 + f := make([]int, target+1) + f[0] = 1 + for i := 1; i <= n; i++ { + g := make([]int, target+1) + for j := 1; j <= min(target, i*k); j++ { + for h := 1; h <= min(j, k); h++ { + g[j] = (g[j] + f[j-h]) % mod + } + } + f = g + } + return f[target] +} +``` + +```ts +function numRollsToTarget(n: number, k: number, target: number): number { + const f = Array(target + 1).fill(0); + f[0] = 1; + const mod = 1e9 + 7; + for (let i = 1; i <= n; ++i) { + const g = Array(target + 1).fill(0); + for (let j = 1; j <= Math.min(i * k, target); ++j) { + for (let h = 1; h <= Math.min(j, k); ++h) { + g[j] = (g[j] + f[j - h]) % mod; + } + } + f.splice(0, target + 1, ...g); + } + return f[target]; +} +``` + ```rust impl Solution { pub fn num_rolls_to_target(n: i32, k: i32, target: i32) -> i32 { @@ -300,10 +294,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1156.Swap For Longest Repeated Character Substring/README.md b/solution/1100-1199/1156.Swap For Longest Repeated Character Substring/README.md index cf01bd3b1b0c4..577a410b220e5 100644 --- a/solution/1100-1199/1156.Swap For Longest Repeated Character Substring/README.md +++ b/solution/1100-1199/1156.Swap For Longest Repeated Character Substring/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们先用哈希表或数组 $cnt$ 统计字符串 $text$ 中每个字符出现的次数。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def maxRepOpt1(self, text: str) -> int: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxRepOpt1(String text) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func maxRepOpt1(text string) (ans int) { cnt := [26]int{} @@ -180,8 +166,6 @@ func maxRepOpt1(text string) (ans int) { } ``` -### **TypeScript** - ```ts function maxRepOpt1(text: string): number { const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); @@ -210,10 +194,6 @@ function maxRepOpt1(text: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1156.Swap For Longest Repeated Character Substring/README_EN.md b/solution/1100-1199/1156.Swap For Longest Repeated Character Substring/README_EN.md index 1801559e82c11..858e0a51f7040 100644 --- a/solution/1100-1199/1156.Swap For Longest Repeated Character Substring/README_EN.md +++ b/solution/1100-1199/1156.Swap For Longest Repeated Character Substring/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers First, we use a hash table or array $cnt$ to count the occurrence of each character in the string $text$. @@ -55,8 +55,6 @@ The time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is -### **Python3** - ```python class Solution: def maxRepOpt1(self, text: str) -> int: @@ -77,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxRepOpt1(String text) { @@ -107,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +132,6 @@ public: }; ``` -### **Go** - ```go func maxRepOpt1(text string) (ans int) { cnt := [26]int{} @@ -164,8 +156,6 @@ func maxRepOpt1(text string) (ans int) { } ``` -### **TypeScript** - ```ts function maxRepOpt1(text: string): number { const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); @@ -194,10 +184,6 @@ function maxRepOpt1(text: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1157.Online Majority Element In Subarray/README.md b/solution/1100-1199/1157.Online Majority Element In Subarray/README.md index 85fc51add8552..b3a6825526bf6 100644 --- a/solution/1100-1199/1157.Online Majority Element In Subarray/README.md +++ b/solution/1100-1199/1157.Online Majority Element In Subarray/README.md @@ -50,9 +50,7 @@ majorityChecker.query(2,3,2); // 返回 2 ## 解法 - - -**方法一:线段树 + 摩尔投票 + 二分查找** +### 方法一:线段树 + 摩尔投票 + 二分查找 我们注意到,题目需要我们找出特定区间内可能的众数,考虑使用线段树来维护每个区间内的候选众数以及其出现的次数。 @@ -77,10 +75,6 @@ majorityChecker.query(2,3,2); // 返回 2 -### **Python3** - - - ```python class Node: __slots__ = ("l", "r", "x", "cnt") @@ -156,10 +150,6 @@ class MajorityChecker: # param_1 = obj.query(left,right,threshold) ``` -### **Java** - - - ```java class Node { int l, r; @@ -271,8 +261,6 @@ class MajorityChecker { */ ``` -### **C++** - ```cpp class Node { public: @@ -378,8 +366,6 @@ private: */ ``` -### **Go** - ```go type node struct { l, r, x, cnt int @@ -483,10 +469,6 @@ func (this *MajorityChecker) Query(left int, right int, threshold int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1157.Online Majority Element In Subarray/README_EN.md b/solution/1100-1199/1157.Online Majority Element In Subarray/README_EN.md index f705d3b8002ec..8bb60ea9c0b77 100644 --- a/solution/1100-1199/1157.Online Majority Element In Subarray/README_EN.md +++ b/solution/1100-1199/1157.Online Majority Element In Subarray/README_EN.md @@ -46,7 +46,7 @@ majorityChecker.query(2, 3, 2); // return 2 ## Solutions -**Solution 1: Segment Tree + Boyer-Moore Voting Algorithm + Binary Search** +### Solution 1: Segment Tree + Boyer-Moore Voting Algorithm + Binary Search We notice that the problem requires us to find the possible majority element in a specific interval, so we consider using a segment tree to maintain the candidate majority element and its occurrence in each interval. @@ -71,8 +71,6 @@ In terms of time complexity, the time complexity of the initialization method is -### **Python3** - ```python class Node: __slots__ = ("l", "r", "x", "cnt") @@ -148,8 +146,6 @@ class MajorityChecker: # param_1 = obj.query(left,right,threshold) ``` -### **Java** - ```java class Node { int l, r; @@ -261,8 +257,6 @@ class MajorityChecker { */ ``` -### **C++** - ```cpp class Node { public: @@ -368,8 +362,6 @@ private: */ ``` -### **Go** - ```go type node struct { l, r, x, cnt int @@ -473,10 +465,6 @@ func (this *MajorityChecker) Query(left int, right int, threshold int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1158.Market Analysis I/README.md b/solution/1100-1199/1158.Market Analysis I/README.md index 8dcace792ff8e..44680a725150e 100644 --- a/solution/1100-1199/1158.Market Analysis I/README.md +++ b/solution/1100-1199/1158.Market Analysis I/README.md @@ -108,12 +108,10 @@ Items 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -126,6 +124,12 @@ FROM GROUP BY user_id; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below SELECT @@ -139,3 +143,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1100-1199/1158.Market Analysis I/README_EN.md b/solution/1100-1199/1158.Market Analysis I/README_EN.md index 2a932414bf806..9571427617d66 100644 --- a/solution/1100-1199/1158.Market Analysis I/README_EN.md +++ b/solution/1100-1199/1158.Market Analysis I/README_EN.md @@ -106,9 +106,9 @@ Items table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -122,6 +122,12 @@ FROM GROUP BY user_id; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below SELECT @@ -135,3 +141,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1100-1199/1159.Market Analysis II/README.md b/solution/1100-1199/1159.Market Analysis II/README.md index 56bf30f5a7751..32ba29c5344f1 100644 --- a/solution/1100-1199/1159.Market Analysis II/README.md +++ b/solution/1100-1199/1159.Market Analysis II/README.md @@ -109,12 +109,10 @@ id为 4 的用户的查询结果是 no,因为他卖出的第二件商品的品 ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -141,3 +139,5 @@ FROM ``` + + diff --git a/solution/1100-1199/1159.Market Analysis II/README_EN.md b/solution/1100-1199/1159.Market Analysis II/README_EN.md index e9e4242a8f58f..2e839ed1eba9a 100644 --- a/solution/1100-1199/1159.Market Analysis II/README_EN.md +++ b/solution/1100-1199/1159.Market Analysis II/README_EN.md @@ -110,9 +110,9 @@ The answer for the user with id 4 is no because the brand of their second sold i ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -140,3 +140,5 @@ FROM ``` + + diff --git a/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md b/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md index ea8e5600e2dcf..20e8a7e8c86ea 100644 --- a/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md +++ b/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们可以用一个长度为 $26$ 的数组 $cnt$ 统计字符串 $chars$ 中每个字母出现的次数。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def countCharacters(self, words: List[str], chars: str) -> int: @@ -76,10 +70,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countCharacters(String[] words, String chars) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func countCharacters(words []string, chars string) (ans int) { cnt := [26]int{} @@ -164,8 +150,6 @@ func countCharacters(words []string, chars string) (ans int) { } ``` -### **TypeScript** - ```ts function countCharacters(words: string[], chars: string): number { const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); @@ -191,8 +175,6 @@ function countCharacters(words: string[], chars: string): number { } ``` -### **PHP** - ```php class Solution { /** @@ -221,10 +203,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README_EN.md b/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README_EN.md index 0c9012c53f70e..3391a1f653355 100644 --- a/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README_EN.md +++ b/solution/1100-1199/1160.Find Words That Can Be Formed by Characters/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We can use an array $cnt$ of length $26$ to count the occurrence of each letter in the string $chars$. @@ -50,8 +50,6 @@ The time complexity is $O(L)$, and the space complexity is $O(C)$. Here, $L$ is -### **Python3** - ```python class Solution: def countCharacters(self, words: List[str], chars: str) -> int: @@ -64,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countCharacters(String[] words, String chars) { @@ -93,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +117,6 @@ public: }; ``` -### **Go** - ```go func countCharacters(words []string, chars string) (ans int) { cnt := [26]int{} @@ -150,8 +142,6 @@ func countCharacters(words []string, chars string) (ans int) { } ``` -### **TypeScript** - ```ts function countCharacters(words: string[], chars: string): number { const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); @@ -177,8 +167,6 @@ function countCharacters(words: string[], chars: string): number { } ``` -### **PHP** - ```php class Solution { /** @@ -207,10 +195,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/README.md b/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/README.md index db205fa03df3b..c5cd8b93bfe0f 100644 --- a/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/README.md +++ b/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/README.md @@ -44,26 +44,14 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS BFS 层次遍历,求每一层的节点和,找出节点和最大的层,若有多个层的节点和最大,则返回最小的层。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点数。 -**方法二:DFS** - -我们也可以使用 DFS 求解。我们用一个数组 $s$ 来存储每一层的节点和,数组的下标表示层数,数组的值表示节点和。我们使用 DFS 遍历二叉树,将每个节点的值加到对应层数的节点和上。最后,我们返回 $s$ 中的最大值对应的下标即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点数。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -92,34 +80,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def maxLevelSum(self, root: Optional[TreeNode]) -> int: - def dfs(node, i): - if node is None: - return - if i == len(s): - s.append(node.val) - else: - s[i] += node.val - dfs(node.left, i + 1) - dfs(node.right, i + 1) - - s = [] - dfs(root, 0) - return s.index(max(s)) + 1 -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -166,6 +126,152 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxLevelSum(TreeNode* root) { + queue q{{root}}; + int mx = INT_MIN; + int ans = 0; + int i = 0; + while (!q.empty()) { + ++i; + int s = 0; + for (int n = q.size(); n; --n) { + root = q.front(); + q.pop(); + s += root->val; + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + if (mx < s) mx = s, ans = i; + } + return ans; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func maxLevelSum(root *TreeNode) int { + q := []*TreeNode{root} + mx := -0x3f3f3f3f + i := 0 + ans := 0 + for len(q) > 0 { + i++ + s := 0 + for n := len(q); n > 0; n-- { + root = q[0] + q = q[1:] + s += root.Val + if root.Left != nil { + q = append(q, root.Left) + } + if root.Right != nil { + q = append(q, root.Right) + } + } + if mx < s { + mx = s + ans = i + } + } + return ans +} +``` + +```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 maxLevelSum(root: TreeNode | null): number { + const queue = [root]; + let res = 1; + let max = -Infinity; + let h = 1; + while (queue.length !== 0) { + const n = queue.length; + let sum = 0; + for (let i = 0; i < n; i++) { + const { val, left, right } = queue.shift(); + sum += val; + left && queue.push(left); + right && queue.push(right); + } + if (sum > max) { + max = sum; + res = h; + } + h++; + } + return res; +} +``` + + + +### 方法二:DFS + +我们也可以使用 DFS 求解。我们用一个数组 $s$ 来存储每一层的节点和,数组的下标表示层数,数组的值表示节点和。我们使用 DFS 遍历二叉树,将每个节点的值加到对应层数的节点和上。最后,我们返回 $s$ 中的最大值对应的下标即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点数。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxLevelSum(self, root: Optional[TreeNode]) -> int: + def dfs(node, i): + if node is None: + return + if i == len(s): + s.append(node.val) + else: + s[i] += node.val + dfs(node.left, i + 1) + dfs(node.right, i + 1) + + s = [] + dfs(root, 0) + return s.index(max(s)) + 1 +``` + ```java /** * Definition for a binary tree node. @@ -213,44 +319,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int maxLevelSum(TreeNode* root) { - queue q{{root}}; - int mx = INT_MIN; - int ans = 0; - int i = 0; - while (!q.empty()) { - ++i; - int s = 0; - for (int n = q.size(); n; --n) { - root = q.front(); - q.pop(); - s += root->val; - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } - if (mx < s) mx = s, ans = i; - } - return ans; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -287,45 +355,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func maxLevelSum(root *TreeNode) int { - q := []*TreeNode{root} - mx := -0x3f3f3f3f - i := 0 - ans := 0 - for len(q) > 0 { - i++ - s := 0 - for n := len(q); n > 0; n-- { - root = q[0] - q = q[1:] - s += root.Val - if root.Left != nil { - q = append(q, root.Left) - } - if root.Right != nil { - q = append(q, root.Right) - } - } - if mx < s { - mx = s - ans = i - } - } - return ans -} -``` - ```go /** * Definition for a binary tree node. @@ -362,51 +391,6 @@ func maxLevelSum(root *TreeNode) int { } ``` -### **TypeScript** - -```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 maxLevelSum(root: TreeNode | null): number { - const queue = [root]; - let res = 1; - let max = -Infinity; - let h = 1; - while (queue.length !== 0) { - const n = queue.length; - let sum = 0; - for (let i = 0; i < n; i++) { - const { val, left, right } = queue.shift(); - sum += val; - left && queue.push(left); - right && queue.push(right); - } - if (sum > max) { - max = sum; - res = h; - } - h++; - } - return res; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/README_EN.md b/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/README_EN.md index e643112ddc40d..5de8f68d69ef8 100644 --- a/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/README_EN.md +++ b/solution/1100-1199/1161.Maximum Level Sum of a Binary Tree/README_EN.md @@ -38,22 +38,14 @@ So we return the level with the maximum sum which is level 2. ## Solutions -**Solution 1: BFS** +### Solution 1: BFS We can use BFS to traverse the tree level by level, calculate the sum of nodes at each level, and find the level with the maximum sum. If there are multiple levels with the maximum sum, return the smallest level. The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. -**Solution 2: DFS** - -We can also use DFS to solve this problem. We use an array $s$ to store the sum of nodes at each level. The index of the array represents the level, and the value of the array represents the sum of nodes. We use DFS to traverse the binary tree, adding the value of each node to the sum of nodes at the corresponding level. Finally, we return the index corresponding to the maximum value in $s$. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. - -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -82,32 +74,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def maxLevelSum(self, root: Optional[TreeNode]) -> int: - def dfs(node, i): - if node is None: - return - if i == len(s): - s.append(node.val) - else: - s[i] += node.val - dfs(node.left, i + 1) - dfs(node.right, i + 1) - - s = [] - dfs(root, 0) - return s.index(max(s)) + 1 -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -154,6 +120,152 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxLevelSum(TreeNode* root) { + queue q{{root}}; + int mx = INT_MIN; + int ans = 0; + int i = 0; + while (!q.empty()) { + ++i; + int s = 0; + for (int n = q.size(); n; --n) { + root = q.front(); + q.pop(); + s += root->val; + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + if (mx < s) mx = s, ans = i; + } + return ans; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func maxLevelSum(root *TreeNode) int { + q := []*TreeNode{root} + mx := -0x3f3f3f3f + i := 0 + ans := 0 + for len(q) > 0 { + i++ + s := 0 + for n := len(q); n > 0; n-- { + root = q[0] + q = q[1:] + s += root.Val + if root.Left != nil { + q = append(q, root.Left) + } + if root.Right != nil { + q = append(q, root.Right) + } + } + if mx < s { + mx = s + ans = i + } + } + return ans +} +``` + +```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 maxLevelSum(root: TreeNode | null): number { + const queue = [root]; + let res = 1; + let max = -Infinity; + let h = 1; + while (queue.length !== 0) { + const n = queue.length; + let sum = 0; + for (let i = 0; i < n; i++) { + const { val, left, right } = queue.shift(); + sum += val; + left && queue.push(left); + right && queue.push(right); + } + if (sum > max) { + max = sum; + res = h; + } + h++; + } + return res; +} +``` + + + +### Solution 2: DFS + +We can also use DFS to solve this problem. We use an array $s$ to store the sum of nodes at each level. The index of the array represents the level, and the value of the array represents the sum of nodes. We use DFS to traverse the binary tree, adding the value of each node to the sum of nodes at the corresponding level. Finally, we return the index corresponding to the maximum value in $s$. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxLevelSum(self, root: Optional[TreeNode]) -> int: + def dfs(node, i): + if node is None: + return + if i == len(s): + s.append(node.val) + else: + s[i] += node.val + dfs(node.left, i + 1) + dfs(node.right, i + 1) + + s = [] + dfs(root, 0) + return s.index(max(s)) + 1 +``` + ```java /** * Definition for a binary tree node. @@ -201,44 +313,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int maxLevelSum(TreeNode* root) { - queue q{{root}}; - int mx = INT_MIN; - int ans = 0; - int i = 0; - while (!q.empty()) { - ++i; - int s = 0; - for (int n = q.size(); n; --n) { - root = q.front(); - q.pop(); - s += root->val; - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } - if (mx < s) mx = s, ans = i; - } - return ans; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -275,45 +349,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func maxLevelSum(root *TreeNode) int { - q := []*TreeNode{root} - mx := -0x3f3f3f3f - i := 0 - ans := 0 - for len(q) > 0 { - i++ - s := 0 - for n := len(q); n > 0; n-- { - root = q[0] - q = q[1:] - s += root.Val - if root.Left != nil { - q = append(q, root.Left) - } - if root.Right != nil { - q = append(q, root.Right) - } - } - if mx < s { - mx = s - ans = i - } - } - return ans -} -``` - ```go /** * Definition for a binary tree node. @@ -350,51 +385,6 @@ func maxLevelSum(root *TreeNode) int { } ``` -### **TypeScript** - -```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 maxLevelSum(root: TreeNode | null): number { - const queue = [root]; - let res = 1; - let max = -Infinity; - let h = 1; - while (queue.length !== 0) { - const n = queue.length; - let sum = 0; - for (let i = 0; i < n; i++) { - const { val, left, right } = queue.shift(); - sum += val; - left && queue.push(left); - right && queue.push(right); - } - if (sum > max) { - max = sum; - res = h; - } - h++; - } - return res; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1162.As Far from Land as Possible/README.md b/solution/1100-1199/1162.As Far from Land as Possible/README.md index b531c9f1c59e1..813d42c6a0275 100644 --- a/solution/1100-1199/1162.As Far from Land as Possible/README.md +++ b/solution/1100-1199/1162.As Far from Land as Possible/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们可以将所有陆地单元格加入队列 $q$ 中,如果队列为空,或者队列中元素个数等于网格中的单元格个数,则说明网格中只有陆地或者海洋,返回 $-1$。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def maxDistance(self, grid: List[List[int]]) -> int: @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxDistance(int[][] grid) { @@ -131,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +158,6 @@ public: }; ``` -### **Go** - ```go func maxDistance(grid [][]int) int { n := len(grid) @@ -206,8 +192,6 @@ func maxDistance(grid [][]int) int { } ``` -### **TypeScript** - ```ts function maxDistance(grid: number[][]): number { const n = grid.length; @@ -242,10 +226,6 @@ function maxDistance(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1162.As Far from Land as Possible/README_EN.md b/solution/1100-1199/1162.As Far from Land as Possible/README_EN.md index ea4ea76ce6238..46cdec63b087c 100644 --- a/solution/1100-1199/1162.As Far from Land as Possible/README_EN.md +++ b/solution/1100-1199/1162.As Far from Land as Possible/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: BFS** +### Solution 1: BFS We can add all land cells to the queue $q$. If the queue is empty, or the number of elements in the queue equals the number of cells in the grid, it means that the grid contains only land or ocean, so return $-1$. @@ -51,30 +51,27 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ -### **Python3** - ```python class Solution: def maxDistance(self, grid: List[List[int]]) -> int: n = len(grid) - q = deque([(i, j) for i in range(n) for j in range(n) if grid[i][j] == 1]) + q = deque((i, j) for i in range(n) for j in range(n) if grid[i][j]) ans = -1 - valid = False + if len(q) in (0, n * n): + return ans + dirs = (-1, 0, 1, 0, -1) while q: - ans += 1 for _ in range(len(q)): i, j = q.popleft() - for a, b in [[0, 1], [0, -1], [1, 0], [-1, 0]]: - x, y = i + a, b + j + for a, b in pairwise(dirs): + x, y = i + a, j + b if 0 <= x < n and 0 <= y < n and grid[x][y] == 0: - valid = True grid[x][y] = 1 q.append((x, y)) - return ans if valid else -1 + ans += 1 + return ans ``` -### **Java** - ```java class Solution { public int maxDistance(int[][] grid) { @@ -110,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +144,6 @@ public: }; ``` -### **Go** - ```go func maxDistance(grid [][]int) int { n := len(grid) @@ -185,8 +178,6 @@ func maxDistance(grid [][]int) int { } ``` -### **TypeScript** - ```ts function maxDistance(grid: number[][]): number { const n = grid.length; @@ -221,10 +212,6 @@ function maxDistance(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1163.Last Substring in Lexicographical Order/README.md b/solution/1100-1199/1163.Last Substring in Lexicographical Order/README.md index 3b3acb85f038e..230dd33f346c3 100644 --- a/solution/1100-1199/1163.Last Substring in Lexicographical Order/README.md +++ b/solution/1100-1199/1163.Last Substring in Lexicographical Order/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们注意到,如果一个子串从位置 $i$ 开始,那么字典序最大的子串一定是 $s[i,..n-1]$,即从位置 $i$ 开始的最长后缀。因此,我们只需要找出字典序最大的后缀子串即可。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def lastSubstring(self, s: str) -> str: @@ -80,10 +74,6 @@ class Solution: return s[i:] ``` -### **Java** - - - ```java class Solution { public String lastSubstring(String s) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func lastSubstring(s string) string { i, n := 0, len(s) @@ -159,8 +145,6 @@ func lastSubstring(s string) string { } ``` -### **TypeScript** - ```ts function lastSubstring(s: string): string { const n = s.length; @@ -183,10 +167,6 @@ function lastSubstring(s: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1163.Last Substring in Lexicographical Order/README_EN.md b/solution/1100-1199/1163.Last Substring in Lexicographical Order/README_EN.md index 2c830536946cb..912a8b028df26 100644 --- a/solution/1100-1199/1163.Last Substring in Lexicographical Order/README_EN.md +++ b/solution/1100-1199/1163.Last Substring in Lexicographical Order/README_EN.md @@ -32,7 +32,7 @@ ## Solutions -**Solution 1: Two pointers** +### Solution 1: Two pointers We notice that if a substring starts from position $i$, then the largest substring with the largest dictionary order must be $s[i,..n-1]$, which is the longest suffix starting from position $i$. Therefore, we only need to find the largest suffix substring. @@ -52,8 +52,6 @@ The time complexity is $O(n)$, where $n$ is the length of string $s$. The space -### **Python3** - ```python class Solution: def lastSubstring(self, s: str) -> str: @@ -72,8 +70,6 @@ class Solution: return s[i:] ``` -### **Java** - ```java class Solution { public String lastSubstring(String s) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +120,6 @@ public: }; ``` -### **Go** - ```go func lastSubstring(s string) string { i, n := 0, len(s) @@ -149,8 +141,6 @@ func lastSubstring(s string) string { } ``` -### **TypeScript** - ```ts function lastSubstring(s: string): string { const n = s.length; @@ -173,10 +163,6 @@ function lastSubstring(s: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1164.Product Price at a Given Date/README.md b/solution/1100-1199/1164.Product Price at a Given Date/README.md index 66bf1ea786210..9f4aa748049bc 100644 --- a/solution/1100-1199/1164.Product Price at a Given Date/README.md +++ b/solution/1100-1199/1164.Product Price at a Given Date/README.md @@ -55,16 +55,12 @@ Products 表: ## 解法 - - -**方法一:子查询 + 连接** +### 方法一:子查询 + 连接 我们可以使用子查询,找出每个产品在给定日期之前最后一次价格变更的价格,记录在 `P` 表中。然后,我们再找出所有产品的 `product_id`,记录在 `T` 表中。最后,我们将 `T` 表和 `P` 表按照 `product_id` 进行左连接,即可得到最终结果。 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -86,6 +82,12 @@ FROM LEFT JOIN P USING (product_id); ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below WITH @@ -114,3 +116,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1100-1199/1164.Product Price at a Given Date/README_EN.md b/solution/1100-1199/1164.Product Price at a Given Date/README_EN.md index c9adb68fb10ee..ebd0c48d2b9b9 100644 --- a/solution/1100-1199/1164.Product Price at a Given Date/README_EN.md +++ b/solution/1100-1199/1164.Product Price at a Given Date/README_EN.md @@ -53,14 +53,12 @@ Products table: ## Solutions -**Solution 1: Subquery + Join** +### Solution 1: Subquery + Join We can use a subquery to find the price of the last price change for each product before the given date, and record it in the `P` table. Then, we can find all `product_id`s in the `T` table. Finally, we can left join the `T` table with the `P` table on `product_id` to get the final result. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -82,6 +80,12 @@ FROM LEFT JOIN P USING (product_id); ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below WITH @@ -110,3 +114,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1100-1199/1165.Single-Row Keyboard/README.md b/solution/1100-1199/1165.Single-Row Keyboard/README.md index 659cbe31273c5..750b0d0c317e3 100644 --- a/solution/1100-1199/1165.Single-Row Keyboard/README.md +++ b/solution/1100-1199/1165.Single-Row Keyboard/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:哈希表或数组** +### 方法一:哈希表或数组 我们可以用哈希表或者一个长度为 $26$ 的数组 $pos$ 来存储每个字符在键盘上的位置,其中 $pos[c]$ 表示字符 $c$ 在键盘上的位置。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def calculateTime(self, keyboard: str, word: str) -> int: @@ -72,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int calculateTime(String keyboard, String word) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func calculateTime(keyboard string, word string) (ans int) { pos := [26]int{} @@ -140,8 +126,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function calculateTime(keyboard: string, word: string): number { const pos: number[] = Array(26).fill(0); @@ -159,10 +143,6 @@ function calculateTime(keyboard: string, word: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1165.Single-Row Keyboard/README_EN.md b/solution/1100-1199/1165.Single-Row Keyboard/README_EN.md index c916e80763a90..8ecbcc2c2623e 100644 --- a/solution/1100-1199/1165.Single-Row Keyboard/README_EN.md +++ b/solution/1100-1199/1165.Single-Row Keyboard/README_EN.md @@ -39,7 +39,7 @@ Total time = 2 + 1 + 1 = 4. ## Solutions -**Solution 1: Hash Table or Array** +### Solution 1: Hash Table or Array We can use a hash table or an array $pos$ of length $26$ to store the position of each character on the keyboard, where $pos[c]$ represents the position of character $c$ on the keyboard. @@ -51,8 +51,6 @@ The time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is -### **Python3** - ```python class Solution: def calculateTime(self, keyboard: str, word: str) -> int: @@ -64,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int calculateTime(String keyboard, String word) { @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +99,6 @@ public: }; ``` -### **Go** - ```go func calculateTime(keyboard string, word string) (ans int) { pos := [26]int{} @@ -130,8 +122,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function calculateTime(keyboard: string, word: string): number { const pos: number[] = Array(26).fill(0); @@ -149,10 +139,6 @@ function calculateTime(keyboard: string, word: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1166.Design File System/README.md b/solution/1100-1199/1166.Design File System/README.md index f4069d67dabee..9865ce86076d2 100644 --- a/solution/1100-1199/1166.Design File System/README.md +++ b/solution/1100-1199/1166.Design File System/README.md @@ -64,9 +64,7 @@ fileSystem.get("/c"); // 返回 -1 因为该路径不存在。 ## 解法 - - -**方法一:前缀树** +### 方法一:前缀树 我们可以使用前缀树来存储路径,每个节点存储一个值,表示该节点对应的路径的值。 @@ -84,10 +82,6 @@ fileSystem.get("/c"); // 返回 -1 因为该路径不存在。 -### **Python3** - - - ```python class Trie: def __init__(self, v: int = -1): @@ -132,10 +126,6 @@ class FileSystem: # param_2 = obj.get(path) ``` -### **Java** - - - ```java class Trie { Map children = new HashMap<>(); @@ -199,8 +189,6 @@ class FileSystem { */ ``` -### **C++** - ```cpp class Trie { public: @@ -279,8 +267,6 @@ private: */ ``` -### **Go** - ```go type trie struct { children map[string]*trie @@ -343,8 +329,6 @@ func (this *FileSystem) Get(path string) int { */ ``` -### **TypeScript** - ```ts class Trie { children: Map; @@ -409,10 +393,6 @@ class FileSystem { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1166.Design File System/README_EN.md b/solution/1100-1199/1166.Design File System/README_EN.md index 0adb94520a64a..99c3b1b27a09e 100644 --- a/solution/1100-1199/1166.Design File System/README_EN.md +++ b/solution/1100-1199/1166.Design File System/README_EN.md @@ -61,7 +61,7 @@ fileSystem.get("/c"); // return -1 because this path doesn't exist ## Solutions -**Solution 1: Trie** +### Solution 1: Trie We can use a trie to store the paths, where each node stores a value, representing the value of the path corresponding to the node. @@ -79,8 +79,6 @@ The total time complexity is $O(\sum_{w \in W}|w|)$, and the total space complex -### **Python3** - ```python class Trie: def __init__(self, v: int = -1): @@ -125,8 +123,6 @@ class FileSystem: # param_2 = obj.get(path) ``` -### **Java** - ```java class Trie { Map children = new HashMap<>(); @@ -190,8 +186,6 @@ class FileSystem { */ ``` -### **C++** - ```cpp class Trie { public: @@ -270,8 +264,6 @@ private: */ ``` -### **Go** - ```go type trie struct { children map[string]*trie @@ -334,8 +326,6 @@ func (this *FileSystem) Get(path string) int { */ ``` -### **TypeScript** - ```ts class Trie { children: Map; @@ -400,10 +390,6 @@ class FileSystem { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1167.Minimum Cost to Connect Sticks/README.md b/solution/1100-1199/1167.Minimum Cost to Connect Sticks/README.md index d7b5bccd7e762..60fd2b2ee967a 100644 --- a/solution/1100-1199/1167.Minimum Cost to Connect Sticks/README.md +++ b/solution/1100-1199/1167.Minimum Cost to Connect Sticks/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列(小根堆)** +### 方法一:贪心 + 优先队列(小根堆) 我们可以使用贪心的思路,每次选择最短的两根棍子进行拼接,这样可以保证拼接的代价最小。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def connectSticks(self, sticks: List[int]) -> int: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int connectSticks(int[] sticks) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func connectSticks(sticks []int) (ans int) { hp := &hp{sticks} @@ -157,8 +143,6 @@ func (h *hp) Pop() any { } ``` -### **TypeScript** - ```ts function connectSticks(sticks: number[]): number { const pq = new Heap(sticks); @@ -239,10 +223,6 @@ class Heap { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1167.Minimum Cost to Connect Sticks/README_EN.md b/solution/1100-1199/1167.Minimum Cost to Connect Sticks/README_EN.md index fb9715491800a..c20c7dafa94a4 100644 --- a/solution/1100-1199/1167.Minimum Cost to Connect Sticks/README_EN.md +++ b/solution/1100-1199/1167.Minimum Cost to Connect Sticks/README_EN.md @@ -52,7 +52,7 @@ There is only one stick left, so you are done. The total cost is 4 + 9 + 17 = 30 ## Solutions -**Solution 1: Greedy + Priority Queue (Min Heap)** +### Solution 1: Greedy + Priority Queue (Min Heap) We can use a greedy approach, each time choosing the shortest two sticks to connect, which ensures the minimum cost of connection. @@ -62,8 +62,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def connectSticks(self, sticks: List[int]) -> int: @@ -76,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int connectSticks(int[] sticks) { @@ -96,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +115,6 @@ public: }; ``` -### **Go** - ```go func connectSticks(sticks []int) (ans int) { hp := &hp{sticks} @@ -147,8 +139,6 @@ func (h *hp) Pop() any { } ``` -### **TypeScript** - ```ts function connectSticks(sticks: number[]): number { const pq = new Heap(sticks); @@ -229,10 +219,6 @@ class Heap { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1168.Optimize Water Distribution in a Village/README.md b/solution/1100-1199/1168.Optimize Water Distribution in a Village/README.md index 74c28b8954593..eb620c3f02f2f 100644 --- a/solution/1100-1199/1168.Optimize Water Distribution in a Village/README.md +++ b/solution/1100-1199/1168.Optimize Water Distribution in a Village/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:Kruskal 算法(最小生成树)** +### 方法一:Kruskal 算法(最小生成树) 我们假设有一个水井编号为 $0$,那么我们可以将每个房子与水井 $0$ 之间的连通性看作是一条边,每条边的权值为该房子建造水井的成本。同时,我们将每个房子之间的连通性也看作是一条边,每条边的权值为铺设管道的成本。这样一来,我们就可以将本题转化成求一张无向图的最小生成树的问题。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def minCostToSupplyWater( @@ -104,6 +98,214 @@ class Solution: return ans ``` +```java +class Solution { + private int[] p; + + public int minCostToSupplyWater(int n, int[] wells, int[][] pipes) { + int[][] nums = Arrays.copyOf(pipes, pipes.length + n); + for (int i = 0; i < n; i++) { + nums[pipes.length + i] = new int[] {0, i + 1, wells[i]}; + } + Arrays.sort(nums, (a, b) -> a[2] - b[2]); + p = new int[n + 1]; + for (int i = 0; i <= n; i++) { + p[i] = i; + } + int ans = 0; + for (var x : nums) { + int a = x[0], b = x[1], c = x[2]; + int pa = find(a), pb = find(b); + if (pa != pb) { + p[pa] = pb; + ans += c; + if (--n == 0) { + return ans; + } + } + } + return ans; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} +``` + +```cpp +class Solution { +public: + int minCostToSupplyWater(int n, vector& wells, vector>& pipes) { + for (int i = 0; i < n; ++i) { + pipes.push_back({0, i + 1, wells[i]}); + } + sort(pipes.begin(), pipes.end(), [](const vector& a, const vector& b) { + return a[2] < b[2]; + }); + int p[n + 1]; + iota(p, p + n + 1, 0); + function find = [&](int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + }; + int ans = 0; + for (const auto& x : pipes) { + int pa = find(x[0]), pb = find(x[1]); + if (pa == pb) { + continue; + } + p[pa] = pb; + ans += x[2]; + if (--n == 0) { + break; + } + } + return ans; + } +}; +``` + +```go +func minCostToSupplyWater(n int, wells []int, pipes [][]int) (ans int) { + for i, w := range wells { + pipes = append(pipes, []int{0, i + 1, w}) + } + sort.Slice(pipes, func(i, j int) bool { return pipes[i][2] < pipes[j][2] }) + p := make([]int, n+1) + for i := range p { + p[i] = i + } + var find func(int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + + for _, x := range pipes { + pa, pb := find(x[0]), find(x[1]) + if pa == pb { + continue + } + p[pa] = pb + ans += x[2] + n-- + if n == 0 { + break + } + } + return +} +``` + +```ts +function minCostToSupplyWater(n: number, wells: number[], pipes: number[][]): number { + for (let i = 0; i < n; ++i) { + pipes.push([0, i + 1, wells[i]]); + } + pipes.sort((a, b) => a[2] - b[2]); + const p = Array(n + 1) + .fill(0) + .map((_, i) => i); + const find = (x: number): number => { + if (p[x] !== x) { + p[x] = find(p[x]); + } + return p[x]; + }; + let ans = 0; + for (const [a, b, c] of pipes) { + const pa = find(a); + const pb = find(b); + if (pa === pb) { + continue; + } + p[pa] = pb; + ans += c; + if (--n === 0) { + break; + } + } + return ans; +} +``` + +```rust +struct UnionFind { + p: Vec, + size: Vec, +} + +impl UnionFind { + fn new(n: usize) -> Self { + let p: Vec = (0..n).collect(); + let size = vec![1; n]; + UnionFind { p, size } + } + + fn find(&mut self, x: usize) -> usize { + if self.p[x] != x { + self.p[x] = self.find(self.p[x]); + } + self.p[x] + } + + fn union(&mut self, a: usize, b: usize) -> bool { + let pa = self.find(a); + let pb = self.find(b); + if pa == pb { + false + } else if self.size[pa] > self.size[pb] { + self.p[pb] = pa; + self.size[pa] += self.size[pb]; + true + } else { + self.p[pa] = pb; + self.size[pb] += self.size[pa]; + true + } + } +} + +impl Solution { + pub fn min_cost_to_supply_water(n: i32, wells: Vec, pipes: Vec>) -> i32 { + let n = n as usize; + let mut pipes = pipes; + for i in 0..n { + pipes.push(vec![0, (i + 1) as i32, wells[i]]); + } + pipes.sort_by(|a, b| a[2].cmp(&b[2])); + let mut uf = UnionFind::new(n + 1); + let mut ans = 0; + for pipe in pipes { + let a = pipe[0] as usize; + let b = pipe[1] as usize; + let c = pipe[2]; + if uf.union(a, b) { + ans += c; + if n == 0 { + break; + } + } + } + ans + } +} +``` + + + +### 方法二 + + + ```python class UnionFind: __slots__ = ("p", "size") @@ -147,48 +349,6 @@ class Solution: return ans ``` -### **Java** - - - -```java -class Solution { - private int[] p; - - public int minCostToSupplyWater(int n, int[] wells, int[][] pipes) { - int[][] nums = Arrays.copyOf(pipes, pipes.length + n); - for (int i = 0; i < n; i++) { - nums[pipes.length + i] = new int[] {0, i + 1, wells[i]}; - } - Arrays.sort(nums, (a, b) -> a[2] - b[2]); - p = new int[n + 1]; - for (int i = 0; i <= n; i++) { - p[i] = i; - } - int ans = 0; - for (var x : nums) { - int a = x[0], b = x[1], c = x[2]; - int pa = find(a), pb = find(b); - if (pa != pb) { - p[pa] = pb; - ans += c; - if (--n == 0) { - return ans; - } - } - } - return ans; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } -} -``` - ```java class UnionFind { private int[] p; @@ -249,43 +409,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minCostToSupplyWater(int n, vector& wells, vector>& pipes) { - for (int i = 0; i < n; ++i) { - pipes.push_back({0, i + 1, wells[i]}); - } - sort(pipes.begin(), pipes.end(), [](const vector& a, const vector& b) { - return a[2] < b[2]; - }); - int p[n + 1]; - iota(p, p + n + 1, 0); - function find = [&](int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - }; - int ans = 0; - for (const auto& x : pipes) { - int pa = find(x[0]), pb = find(x[1]); - if (pa == pb) { - continue; - } - p[pa] = pb; - ans += x[2]; - if (--n == 0) { - break; - } - } - return ans; - } -}; -``` - ```cpp class UnionFind { public: @@ -345,42 +468,6 @@ public: }; ``` -### **Go** - -```go -func minCostToSupplyWater(n int, wells []int, pipes [][]int) (ans int) { - for i, w := range wells { - pipes = append(pipes, []int{0, i + 1, w}) - } - sort.Slice(pipes, func(i, j int) bool { return pipes[i][2] < pipes[j][2] }) - p := make([]int, n+1) - for i := range p { - p[i] = i - } - var find func(int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - - for _, x := range pipes { - pa, pb := find(x[0]), find(x[1]) - if pa == pb { - continue - } - p[pa] = pb - ans += x[2] - n-- - if n == 0 { - break - } - } - return -} -``` - ```go type unionFind struct { p, size []int @@ -437,40 +524,6 @@ func minCostToSupplyWater(n int, wells []int, pipes [][]int) (ans int) { } ``` -### **TypeScript** - -```ts -function minCostToSupplyWater(n: number, wells: number[], pipes: number[][]): number { - for (let i = 0; i < n; ++i) { - pipes.push([0, i + 1, wells[i]]); - } - pipes.sort((a, b) => a[2] - b[2]); - const p = Array(n + 1) - .fill(0) - .map((_, i) => i); - const find = (x: number): number => { - if (p[x] !== x) { - p[x] = find(p[x]); - } - return p[x]; - }; - let ans = 0; - for (const [a, b, c] of pipes) { - const pa = find(a); - const pb = find(b); - if (pa === pb) { - continue; - } - p[pa] = pb; - ans += c; - if (--n === 0) { - break; - } - } - return ans; -} -``` - ```ts class UnionFind { private p: number[]; @@ -526,75 +579,6 @@ function minCostToSupplyWater(n: number, wells: number[], pipes: number[][]): nu } ``` -### **Rust** - -```rust -struct UnionFind { - p: Vec, - size: Vec, -} - -impl UnionFind { - fn new(n: usize) -> Self { - let p: Vec = (0..n).collect(); - let size = vec![1; n]; - UnionFind { p, size } - } - - fn find(&mut self, x: usize) -> usize { - if self.p[x] != x { - self.p[x] = self.find(self.p[x]); - } - self.p[x] - } - - fn union(&mut self, a: usize, b: usize) -> bool { - let pa = self.find(a); - let pb = self.find(b); - if pa == pb { - false - } else if self.size[pa] > self.size[pb] { - self.p[pb] = pa; - self.size[pa] += self.size[pb]; - true - } else { - self.p[pa] = pb; - self.size[pb] += self.size[pa]; - true - } - } -} - -impl Solution { - pub fn min_cost_to_supply_water(n: i32, wells: Vec, pipes: Vec>) -> i32 { - let n = n as usize; - let mut pipes = pipes; - for i in 0..n { - pipes.push(vec![0, (i + 1) as i32, wells[i]]); - } - pipes.sort_by(|a, b| a[2].cmp(&b[2])); - let mut uf = UnionFind::new(n + 1); - let mut ans = 0; - for pipe in pipes { - let a = pipe[0] as usize; - let b = pipe[1] as usize; - let c = pipe[2]; - if uf.union(a, b) { - ans += c; - if n == 0 { - break; - } - } - } - ans - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1168.Optimize Water Distribution in a Village/README_EN.md b/solution/1100-1199/1168.Optimize Water Distribution in a Village/README_EN.md index e86f3ebb1a1c6..32ade65a6f6fd 100644 --- a/solution/1100-1199/1168.Optimize Water Distribution in a Village/README_EN.md +++ b/solution/1100-1199/1168.Optimize Water Distribution in a Village/README_EN.md @@ -57,7 +57,7 @@ Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will a ## Solutions -**Solution 1: Kruskal's Algorithm (Minimum Spanning Tree)** +### Solution 1: Kruskal's Algorithm (Minimum Spanning Tree) We assume that there is a well with the number $0$. Then we can consider the connectivity between each house and the well $0$ as an edge, and the weight of each edge is the cost of building a well for that house. At the same time, we consider the connectivity between each house as an edge, and the weight of each edge is the cost of laying a pipe. In this way, we can transform this problem into finding the minimum spanning tree of an undirected graph. @@ -67,8 +67,6 @@ The time complexity is $O((m + n) \times \log (m + n))$, and the space complexit -### **Python3** - ```python class Solution: def minCostToSupplyWater( @@ -94,6 +92,214 @@ class Solution: return ans ``` +```java +class Solution { + private int[] p; + + public int minCostToSupplyWater(int n, int[] wells, int[][] pipes) { + int[][] nums = Arrays.copyOf(pipes, pipes.length + n); + for (int i = 0; i < n; i++) { + nums[pipes.length + i] = new int[] {0, i + 1, wells[i]}; + } + Arrays.sort(nums, (a, b) -> a[2] - b[2]); + p = new int[n + 1]; + for (int i = 0; i <= n; i++) { + p[i] = i; + } + int ans = 0; + for (var x : nums) { + int a = x[0], b = x[1], c = x[2]; + int pa = find(a), pb = find(b); + if (pa != pb) { + p[pa] = pb; + ans += c; + if (--n == 0) { + return ans; + } + } + } + return ans; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} +``` + +```cpp +class Solution { +public: + int minCostToSupplyWater(int n, vector& wells, vector>& pipes) { + for (int i = 0; i < n; ++i) { + pipes.push_back({0, i + 1, wells[i]}); + } + sort(pipes.begin(), pipes.end(), [](const vector& a, const vector& b) { + return a[2] < b[2]; + }); + int p[n + 1]; + iota(p, p + n + 1, 0); + function find = [&](int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + }; + int ans = 0; + for (const auto& x : pipes) { + int pa = find(x[0]), pb = find(x[1]); + if (pa == pb) { + continue; + } + p[pa] = pb; + ans += x[2]; + if (--n == 0) { + break; + } + } + return ans; + } +}; +``` + +```go +func minCostToSupplyWater(n int, wells []int, pipes [][]int) (ans int) { + for i, w := range wells { + pipes = append(pipes, []int{0, i + 1, w}) + } + sort.Slice(pipes, func(i, j int) bool { return pipes[i][2] < pipes[j][2] }) + p := make([]int, n+1) + for i := range p { + p[i] = i + } + var find func(int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + + for _, x := range pipes { + pa, pb := find(x[0]), find(x[1]) + if pa == pb { + continue + } + p[pa] = pb + ans += x[2] + n-- + if n == 0 { + break + } + } + return +} +``` + +```ts +function minCostToSupplyWater(n: number, wells: number[], pipes: number[][]): number { + for (let i = 0; i < n; ++i) { + pipes.push([0, i + 1, wells[i]]); + } + pipes.sort((a, b) => a[2] - b[2]); + const p = Array(n + 1) + .fill(0) + .map((_, i) => i); + const find = (x: number): number => { + if (p[x] !== x) { + p[x] = find(p[x]); + } + return p[x]; + }; + let ans = 0; + for (const [a, b, c] of pipes) { + const pa = find(a); + const pb = find(b); + if (pa === pb) { + continue; + } + p[pa] = pb; + ans += c; + if (--n === 0) { + break; + } + } + return ans; +} +``` + +```rust +struct UnionFind { + p: Vec, + size: Vec, +} + +impl UnionFind { + fn new(n: usize) -> Self { + let p: Vec = (0..n).collect(); + let size = vec![1; n]; + UnionFind { p, size } + } + + fn find(&mut self, x: usize) -> usize { + if self.p[x] != x { + self.p[x] = self.find(self.p[x]); + } + self.p[x] + } + + fn union(&mut self, a: usize, b: usize) -> bool { + let pa = self.find(a); + let pb = self.find(b); + if pa == pb { + false + } else if self.size[pa] > self.size[pb] { + self.p[pb] = pa; + self.size[pa] += self.size[pb]; + true + } else { + self.p[pa] = pb; + self.size[pb] += self.size[pa]; + true + } + } +} + +impl Solution { + pub fn min_cost_to_supply_water(n: i32, wells: Vec, pipes: Vec>) -> i32 { + let n = n as usize; + let mut pipes = pipes; + for i in 0..n { + pipes.push(vec![0, (i + 1) as i32, wells[i]]); + } + pipes.sort_by(|a, b| a[2].cmp(&b[2])); + let mut uf = UnionFind::new(n + 1); + let mut ans = 0; + for pipe in pipes { + let a = pipe[0] as usize; + let b = pipe[1] as usize; + let c = pipe[2]; + if uf.union(a, b) { + ans += c; + if n == 0 { + break; + } + } + } + ans + } +} +``` + + + +### Solution 2 + + + ```python class UnionFind: __slots__ = ("p", "size") @@ -137,46 +343,6 @@ class Solution: return ans ``` -### **Java** - -```java -class Solution { - private int[] p; - - public int minCostToSupplyWater(int n, int[] wells, int[][] pipes) { - int[][] nums = Arrays.copyOf(pipes, pipes.length + n); - for (int i = 0; i < n; i++) { - nums[pipes.length + i] = new int[] {0, i + 1, wells[i]}; - } - Arrays.sort(nums, (a, b) -> a[2] - b[2]); - p = new int[n + 1]; - for (int i = 0; i <= n; i++) { - p[i] = i; - } - int ans = 0; - for (var x : nums) { - int a = x[0], b = x[1], c = x[2]; - int pa = find(a), pb = find(b); - if (pa != pb) { - p[pa] = pb; - ans += c; - if (--n == 0) { - return ans; - } - } - } - return ans; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } -} -``` - ```java class UnionFind { private int[] p; @@ -237,43 +403,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minCostToSupplyWater(int n, vector& wells, vector>& pipes) { - for (int i = 0; i < n; ++i) { - pipes.push_back({0, i + 1, wells[i]}); - } - sort(pipes.begin(), pipes.end(), [](const vector& a, const vector& b) { - return a[2] < b[2]; - }); - int p[n + 1]; - iota(p, p + n + 1, 0); - function find = [&](int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - }; - int ans = 0; - for (const auto& x : pipes) { - int pa = find(x[0]), pb = find(x[1]); - if (pa == pb) { - continue; - } - p[pa] = pb; - ans += x[2]; - if (--n == 0) { - break; - } - } - return ans; - } -}; -``` - ```cpp class UnionFind { public: @@ -333,42 +462,6 @@ public: }; ``` -### **Go** - -```go -func minCostToSupplyWater(n int, wells []int, pipes [][]int) (ans int) { - for i, w := range wells { - pipes = append(pipes, []int{0, i + 1, w}) - } - sort.Slice(pipes, func(i, j int) bool { return pipes[i][2] < pipes[j][2] }) - p := make([]int, n+1) - for i := range p { - p[i] = i - } - var find func(int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - - for _, x := range pipes { - pa, pb := find(x[0]), find(x[1]) - if pa == pb { - continue - } - p[pa] = pb - ans += x[2] - n-- - if n == 0 { - break - } - } - return -} -``` - ```go type unionFind struct { p, size []int @@ -425,40 +518,6 @@ func minCostToSupplyWater(n int, wells []int, pipes [][]int) (ans int) { } ``` -### **TypeScript** - -```ts -function minCostToSupplyWater(n: number, wells: number[], pipes: number[][]): number { - for (let i = 0; i < n; ++i) { - pipes.push([0, i + 1, wells[i]]); - } - pipes.sort((a, b) => a[2] - b[2]); - const p = Array(n + 1) - .fill(0) - .map((_, i) => i); - const find = (x: number): number => { - if (p[x] !== x) { - p[x] = find(p[x]); - } - return p[x]; - }; - let ans = 0; - for (const [a, b, c] of pipes) { - const pa = find(a); - const pb = find(b); - if (pa === pb) { - continue; - } - p[pa] = pb; - ans += c; - if (--n === 0) { - break; - } - } - return ans; -} -``` - ```ts class UnionFind { private p: number[]; @@ -514,75 +573,6 @@ function minCostToSupplyWater(n: number, wells: number[], pipes: number[][]): nu } ``` -### **Rust** - -```rust -struct UnionFind { - p: Vec, - size: Vec, -} - -impl UnionFind { - fn new(n: usize) -> Self { - let p: Vec = (0..n).collect(); - let size = vec![1; n]; - UnionFind { p, size } - } - - fn find(&mut self, x: usize) -> usize { - if self.p[x] != x { - self.p[x] = self.find(self.p[x]); - } - self.p[x] - } - - fn union(&mut self, a: usize, b: usize) -> bool { - let pa = self.find(a); - let pb = self.find(b); - if pa == pb { - false - } else if self.size[pa] > self.size[pb] { - self.p[pb] = pa; - self.size[pa] += self.size[pb]; - true - } else { - self.p[pa] = pb; - self.size[pb] += self.size[pa]; - true - } - } -} - -impl Solution { - pub fn min_cost_to_supply_water(n: i32, wells: Vec, pipes: Vec>) -> i32 { - let n = n as usize; - let mut pipes = pipes; - for i in 0..n { - pipes.push(vec![0, (i + 1) as i32, wells[i]]); - } - pipes.sort_by(|a, b| a[2].cmp(&b[2])); - let mut uf = UnionFind::new(n + 1); - let mut ans = 0; - for pipe in pipes { - let a = pipe[0] as usize; - let b = pipe[1] as usize; - let c = pipe[2]; - if uf.union(a, b) { - ans += c; - if n == 0 { - break; - } - } - } - ans - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1169.Invalid Transactions/README.md b/solution/1100-1199/1169.Invalid Transactions/README.md index c3b0d77244de5..fd71b77450c39 100644 --- a/solution/1100-1199/1169.Invalid Transactions/README.md +++ b/solution/1100-1199/1169.Invalid Transactions/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:哈希表 + 模拟** +### 方法一:哈希表 + 模拟 遍历交易列表,对于每笔交易,如果金额大于 1000,或者同名且城市不同且时间间隔不超过 60 分钟,则将其加入答案。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def invalidTransactions(self, transactions: List[str]) -> List[str]: @@ -92,10 +86,6 @@ class Solution: return [transactions[i] for i in idx] ``` -### **Java** - - - ```java class Solution { public List invalidTransactions(String[] transactions) { @@ -139,8 +129,6 @@ class Item { } ``` -### **C++** - ```cpp class Solution { public: @@ -183,8 +171,6 @@ public: }; ``` -### **Go** - ```go func invalidTransactions(transactions []string) (ans []string) { d := map[string][]tuple{} @@ -225,10 +211,6 @@ type tuple struct { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1169.Invalid Transactions/README_EN.md b/solution/1100-1199/1169.Invalid Transactions/README_EN.md index 77122a4879742..b9315284a2817 100644 --- a/solution/1100-1199/1169.Invalid Transactions/README_EN.md +++ b/solution/1100-1199/1169.Invalid Transactions/README_EN.md @@ -50,7 +50,7 @@ ## Solutions -**Solution 1: Hash Table + Simulation** +### Solution 1: Hash Table + Simulation We traverse the transaction list. For each transaction, if the amount is greater than 1000, or if the transaction has the same name but different cities and the time interval does not exceed 60 minutes, then add it to the answer. @@ -64,8 +64,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ i -### **Python3** - ```python class Solution: def invalidTransactions(self, transactions: List[str]) -> List[str]: @@ -84,8 +82,6 @@ class Solution: return [transactions[i] for i in idx] ``` -### **Java** - ```java class Solution { public List invalidTransactions(String[] transactions) { @@ -129,8 +125,6 @@ class Item { } ``` -### **C++** - ```cpp class Solution { public: @@ -173,8 +167,6 @@ public: }; ``` -### **Go** - ```go func invalidTransactions(transactions []string) (ans []string) { d := map[string][]tuple{} @@ -215,10 +207,6 @@ type tuple struct { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1170.Compare Strings by Frequency of the Smallest Character/README.md b/solution/1100-1199/1170.Compare Strings by Frequency of the Smallest Character/README.md index d6925de076ac9..19cfe44de5498 100644 --- a/solution/1100-1199/1170.Compare Strings by Frequency of the Smallest Character/README.md +++ b/solution/1100-1199/1170.Compare Strings by Frequency of the Smallest Character/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 我们先按照题目描述,实现函数 $f(s)$,函数返回字符串 $s$ 中按字典序比较最小字母的出现频次。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: @@ -75,10 +69,6 @@ class Solution: return [n - bisect_right(nums, f(q)) for q in queries] ``` -### **Java** - - - ```java class Solution { public int[] numSmallerByFrequency(String[] queries, String[] words) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func numSmallerByFrequency(queries []string, words []string) (ans []int) { f := func(s string) int { @@ -185,8 +171,6 @@ func numSmallerByFrequency(queries []string, words []string) (ans []int) { } ``` -### **TypeScript** - ```ts function numSmallerByFrequency(queries: string[], words: string[]): number[] { const f = (s: string): number => { @@ -216,10 +200,6 @@ function numSmallerByFrequency(queries: string[], words: string[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1170.Compare Strings by Frequency of the Smallest Character/README_EN.md b/solution/1100-1199/1170.Compare Strings by Frequency of the Smallest Character/README_EN.md index 6423d836c7c2c..be888a30462f3 100644 --- a/solution/1100-1199/1170.Compare Strings by Frequency of the Smallest Character/README_EN.md +++ b/solution/1100-1199/1170.Compare Strings by Frequency of the Smallest Character/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Sorting + Binary Search** +### Solution 1: Sorting + Binary Search First, according to the problem description, we implement a function $f(s)$, which returns the frequency of the smallest letter in the string $s$ in lexicographical order. @@ -51,8 +51,6 @@ The time complexity is $O((n + q) \times M)$, and the space complexity is $O(n)$ -### **Python3** - ```python class Solution: def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: @@ -65,8 +63,6 @@ class Solution: return [n - bisect_right(nums, f(q)) for q in queries] ``` -### **Java** - ```java class Solution { public int[] numSmallerByFrequency(String[] queries, String[] words) { @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +137,6 @@ public: }; ``` -### **Go** - ```go func numSmallerByFrequency(queries []string, words []string) (ans []int) { f := func(s string) int { @@ -173,8 +165,6 @@ func numSmallerByFrequency(queries []string, words []string) (ans []int) { } ``` -### **TypeScript** - ```ts function numSmallerByFrequency(queries: string[], words: string[]): number[] { const f = (s: string): number => { @@ -204,10 +194,6 @@ function numSmallerByFrequency(queries: string[], words: string[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1171.Remove Zero Sum Consecutive Nodes from Linked List/README.md b/solution/1100-1199/1171.Remove Zero Sum Consecutive Nodes from Linked List/README.md index 0371ea8924a9a..fed0f85144b0c 100644 --- a/solution/1100-1199/1171.Remove Zero Sum Consecutive Nodes from Linked List/README.md +++ b/solution/1100-1199/1171.Remove Zero Sum Consecutive Nodes from Linked List/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:前缀和 + 哈希表** +### 方法一:前缀和 + 哈希表 若链表节点的两个前缀和相等,说明两个前缀和之间的连续节点序列的和为 $0$,那么可以消去这部分连续节点。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -89,10 +83,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -127,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -164,8 +152,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -195,8 +181,6 @@ func removeZeroSumSublists(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -227,8 +211,6 @@ function removeZeroSumSublists(head: ListNode | null): ListNode | null { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -273,10 +255,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1171.Remove Zero Sum Consecutive Nodes from Linked List/README_EN.md b/solution/1100-1199/1171.Remove Zero Sum Consecutive Nodes from Linked List/README_EN.md index 3d4b852f865a2..f5ee770609934 100644 --- a/solution/1100-1199/1171.Remove Zero Sum Consecutive Nodes from Linked List/README_EN.md +++ b/solution/1100-1199/1171.Remove Zero Sum Consecutive Nodes from Linked List/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Prefix Sum + Hash Table** +### Solution 1: Prefix Sum + Hash Table If two prefix sums of the linked list are equal, it means that the sum of the continuous node sequence between the two prefix sums is $0$, so we can remove this part of the continuous nodes. @@ -57,8 +57,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -82,8 +80,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -118,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -155,8 +149,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -186,8 +178,6 @@ func removeZeroSumSublists(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -218,8 +208,6 @@ function removeZeroSumSublists(head: ListNode | null): ListNode | null { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -264,10 +252,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1172.Dinner Plate Stacks/README.md b/solution/1100-1199/1172.Dinner Plate Stacks/README.md index 18b5151e6d7a3..4329d6f09081f 100644 --- a/solution/1100-1199/1172.Dinner Plate Stacks/README.md +++ b/solution/1100-1199/1172.Dinner Plate Stacks/README.md @@ -75,9 +75,7 @@ D.pop() // 返回 -1。仍然没有栈。 ## 解法 - - -**方法一:栈数组 + 有序集合** +### 方法一:栈数组 + 有序集合 我们定义以下数据结构或变量: @@ -104,10 +102,6 @@ D.pop() // 返回 -1。仍然没有栈。 -### **Python3** - - - ```python from sortedcontainers import SortedSet @@ -152,10 +146,6 @@ class DinnerPlates: # param_3 = obj.popAtStack(index) ``` -### **Java** - - - ```java class DinnerPlates { private int capacity; @@ -212,8 +202,6 @@ class DinnerPlates { */ ``` -### **C++** - ```cpp class DinnerPlates { public: @@ -273,8 +261,6 @@ private: */ ``` -### **Go** - ```go type DinnerPlates struct { capacity int @@ -331,8 +317,6 @@ func (this *DinnerPlates) PopAtStack(index int) int { */ ``` -### **TypeScript** - ```ts class DinnerPlates { capacity: number; @@ -880,10 +864,6 @@ class TreeSet { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1172.Dinner Plate Stacks/README_EN.md b/solution/1100-1199/1172.Dinner Plate Stacks/README_EN.md index 767cbfe8008ee..bbf975b1785d4 100644 --- a/solution/1100-1199/1172.Dinner Plate Stacks/README_EN.md +++ b/solution/1100-1199/1172.Dinner Plate Stacks/README_EN.md @@ -72,7 +72,7 @@ D.pop() // Returns -1. There are still no stacks. ## Solutions -**Solution 1: Stack Array + Ordered Set** +### Solution 1: Stack Array + Ordered Set We define the following data structures or variables: @@ -99,8 +99,6 @@ The time complexity is $(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python from sortedcontainers import SortedSet @@ -145,8 +143,6 @@ class DinnerPlates: # param_3 = obj.popAtStack(index) ``` -### **Java** - ```java class DinnerPlates { private int capacity; @@ -203,8 +199,6 @@ class DinnerPlates { */ ``` -### **C++** - ```cpp class DinnerPlates { public: @@ -264,8 +258,6 @@ private: */ ``` -### **Go** - ```go type DinnerPlates struct { capacity int @@ -322,8 +314,6 @@ func (this *DinnerPlates) PopAtStack(index int) int { */ ``` -### **TypeScript** - ```ts class DinnerPlates { capacity: number; @@ -871,10 +861,6 @@ class TreeSet { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1173.Immediate Food Delivery I/README.md b/solution/1100-1199/1173.Immediate Food Delivery I/README.md index 965d725c3d891..040a99ff71d6d 100644 --- a/solution/1100-1199/1173.Immediate Food Delivery I/README.md +++ b/solution/1100-1199/1173.Immediate Food Delivery I/README.md @@ -56,16 +56,12 @@ Delivery 表: ## 解法 - - -**方法一:求和** +### 方法一:求和 我们可以用 `sum` 函数来统计即时订单的数量,然后除以总订单数即可。由于题目求的是百分比,所以需要乘以 100,最后我们用 `round` 函数保留两位小数。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -74,3 +70,5 @@ FROM Delivery; ``` + + diff --git a/solution/1100-1199/1173.Immediate Food Delivery I/README_EN.md b/solution/1100-1199/1173.Immediate Food Delivery I/README_EN.md index 1cbe2667e9bbc..e3fff5990045f 100644 --- a/solution/1100-1199/1173.Immediate Food Delivery I/README_EN.md +++ b/solution/1100-1199/1173.Immediate Food Delivery I/README_EN.md @@ -54,14 +54,12 @@ Delivery table: ## Solutions -**Solution 1: Sum** +### Solution 1: Sum We can use the `sum` function to count the number of instant orders, and then divide it by the total number of orders. Since the problem requires a percentage, we need to multiply by 100. Finally, we can use the `round` function to keep two decimal places. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -70,3 +68,5 @@ FROM Delivery; ``` + + diff --git a/solution/1100-1199/1174.Immediate Food Delivery II/README.md b/solution/1100-1199/1174.Immediate Food Delivery II/README.md index a536cb4f74b63..de6bbc65ddc47 100644 --- a/solution/1100-1199/1174.Immediate Food Delivery II/README.md +++ b/solution/1100-1199/1174.Immediate Food Delivery II/README.md @@ -65,20 +65,12 @@ Delivery 表: ## 解法 - - -**方法一:子查询** +### 方法一:子查询 我们可以使用子查询,先找到每个用户的首次订单,然后再计算即时订单的比例。 -**方法二:窗口函数** - -我们可以使用 `RANK()` 窗口函数,按照每个用户的订单日期升序排列,获取到每个用户的订单排名,然后我们筛选出排名为 $1$ 的订单,即为首次订单,再计算即时订单的比例。 - -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -92,6 +84,14 @@ WHERE ); ``` + + +### 方法二:窗口函数 + +我们可以使用 `RANK()` 窗口函数,按照每个用户的订单日期升序排列,获取到每个用户的订单排名,然后我们筛选出排名为 $1$ 的订单,即为首次订单,再计算即时订单的比例。 + + + ```sql # Write your MySQL query statement below WITH @@ -111,3 +111,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1100-1199/1174.Immediate Food Delivery II/README_EN.md b/solution/1100-1199/1174.Immediate Food Delivery II/README_EN.md index b5fb06b4425d4..0a8bbb0eb8f50 100644 --- a/solution/1100-1199/1174.Immediate Food Delivery II/README_EN.md +++ b/solution/1100-1199/1174.Immediate Food Delivery II/README_EN.md @@ -62,18 +62,12 @@ Hence, half the customers have immediate first orders. ## Solutions -**Solution 1: Subquery** +### Solution 1: Subquery We can use a subquery to first find the first order of each user, and then calculate the proportion of instant orders. -**Solution 2: Window Function** - -We can use the `RANK()` window function to rank the orders of each user in ascending order by order date, and then filter out the orders with a rank of $1$, which are the first orders of each user. After that, we can calculate the proportion of instant orders. - -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -87,6 +81,14 @@ WHERE ); ``` + + +### Solution 2: Window Function + +We can use the `RANK()` window function to rank the orders of each user in ascending order by order date, and then filter out the orders with a rank of $1$, which are the first orders of each user. After that, we can calculate the proportion of instant orders. + + + ```sql # Write your MySQL query statement below WITH @@ -106,3 +108,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1100-1199/1175.Prime Arrangements/README.md b/solution/1100-1199/1175.Prime Arrangements/README.md index e7a843124f6ea..b81588a2e4caf 100644 --- a/solution/1100-1199/1175.Prime Arrangements/README.md +++ b/solution/1100-1199/1175.Prime Arrangements/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 先统计 $[1,n]$ 范围内的质数个数,我们记为 $cnt$。然后求 $cnt$ 以及 $n-cnt$ 阶乘的乘积得到答案,注意取模操作。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def numPrimeArrangements(self, n: int) -> int: @@ -77,10 +71,6 @@ class Solution: return ans % (10**9 + 7) ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; const int MOD = 1e9 + 7; @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func numPrimeArrangements(n int) int { count := func(n int) int { @@ -186,10 +172,6 @@ func numPrimeArrangements(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1175.Prime Arrangements/README_EN.md b/solution/1100-1199/1175.Prime Arrangements/README_EN.md index e0b049d62b512..fec5416e007e0 100644 --- a/solution/1100-1199/1175.Prime Arrangements/README_EN.md +++ b/solution/1100-1199/1175.Prime Arrangements/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics First, count the number of prime numbers within the range $[1,n]$, which we denote as $cnt$. Then, calculate the product of the factorial of $cnt$ and $n-cnt$ to get the answer, remember to perform the modulo operation. @@ -51,8 +51,6 @@ The time complexity is $O(n \times \log \log n)$. -### **Python3** - ```python class Solution: def numPrimeArrangements(self, n: int) -> int: @@ -71,8 +69,6 @@ class Solution: return ans % (10**9 + 7) ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -108,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; const int MOD = 1e9 + 7; @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go func numPrimeArrangements(n int) int { count := func(n int) int { @@ -178,10 +170,6 @@ func numPrimeArrangements(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1176.Diet Plan Performance/README.md b/solution/1100-1199/1176.Diet Plan Performance/README.md index 86d26ceeda35d..865908eb213ce 100644 --- a/solution/1100-1199/1176.Diet Plan Performance/README.md +++ b/solution/1100-1199/1176.Diet Plan Performance/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:前缀和** +### 方法一:前缀和 我们先预处理出长度为 $n+1$ 的前缀和数组 $s$,其中 $s[i]$ 表示前 $i$ 天的卡路里总和。 @@ -66,18 +64,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `calories` 的长度。 -**方法二:滑动窗口** - -我们维护一个长度为 $k$ 的滑动窗口,窗口内元素之和记为 $s$。如果 $s \lt lower$,则分数减 $1$;如果 $ s \gt upper$,则分数加 $1$。 - -时间复杂度 $O(n)$,其中 $n$ 为数组 `calories` 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def dietPlanPerformance( @@ -94,30 +82,6 @@ class Solution: return ans ``` -```python -class Solution: - def dietPlanPerformance( - self, calories: List[int], k: int, lower: int, upper: int - ) -> int: - def check(s): - if s < lower: - return -1 - if s > upper: - return 1 - return 0 - - s, n = sum(calories[:k]), len(calories) - ans = check(s) - for i in range(k, n): - s += calories[i] - calories[i - k] - ans += check(s) - return ans -``` - -### **Java** - - - ```java class Solution { public int dietPlanPerformance(int[] calories, int k, int lower, int upper) { @@ -140,6 +104,99 @@ class Solution { } ``` +```cpp +class Solution { +public: + int dietPlanPerformance(vector& calories, int k, int lower, int upper) { + int n = calories.size(); + int s[n + 1]; + s[0] = 0; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + calories[i]; + } + int ans = 0; + for (int i = 0; i < n - k + 1; ++i) { + int t = s[i + k] - s[i]; + if (t < lower) { + --ans; + } else if (t > upper) { + ++ans; + } + } + return ans; + } +}; +``` + +```go +func dietPlanPerformance(calories []int, k int, lower int, upper int) (ans int) { + n := len(calories) + s := make([]int, n+1) + for i, x := range calories { + s[i+1] = s[i] + x + } + for i := 0; i < n-k+1; i++ { + t := s[i+k] - s[i] + if t < lower { + ans-- + } else if t > upper { + ans++ + } + } + return +} +``` + +```ts +function dietPlanPerformance(calories: number[], k: number, lower: number, upper: number): number { + const n = calories.length; + const s: number[] = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + calories[i]; + } + let ans = 0; + for (let i = 0; i < n - k + 1; ++i) { + const t = s[i + k] - s[i]; + if (t < lower) { + --ans; + } else if (t > upper) { + ++ans; + } + } + return ans; +} +``` + + + +### 方法二:滑动窗口 + +我们维护一个长度为 $k$ 的滑动窗口,窗口内元素之和记为 $s$。如果 $s \lt lower$,则分数减 $1$;如果 $ s \gt upper$,则分数加 $1$。 + +时间复杂度 $O(n)$,其中 $n$ 为数组 `calories` 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def dietPlanPerformance( + self, calories: List[int], k: int, lower: int, upper: int + ) -> int: + def check(s): + if s < lower: + return -1 + if s > upper: + return 1 + return 0 + + s, n = sum(calories[:k]), len(calories) + ans = check(s) + for i in range(k, n): + s += calories[i] - calories[i - k] + ans += check(s) + return ans +``` + ```java class Solution { public int dietPlanPerformance(int[] calories, int k, int lower, int upper) { @@ -166,32 +223,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int dietPlanPerformance(vector& calories, int k, int lower, int upper) { - int n = calories.size(); - int s[n + 1]; - s[0] = 0; - for (int i = 0; i < n; ++i) { - s[i + 1] = s[i] + calories[i]; - } - int ans = 0; - for (int i = 0; i < n - k + 1; ++i) { - int t = s[i + k] - s[i]; - if (t < lower) { - --ans; - } else if (t > upper) { - ++ans; - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -217,27 +248,6 @@ public: }; ``` -### **Go** - -```go -func dietPlanPerformance(calories []int, k int, lower int, upper int) (ans int) { - n := len(calories) - s := make([]int, n+1) - for i, x := range calories { - s[i+1] = s[i] + x - } - for i := 0; i < n-k+1; i++ { - t := s[i+k] - s[i] - if t < lower { - ans-- - } else if t > upper { - ans++ - } - } - return -} -``` - ```go func dietPlanPerformance(calories []int, k int, lower int, upper int) (ans int) { n := len(calories) @@ -262,28 +272,6 @@ func dietPlanPerformance(calories []int, k int, lower int, upper int) (ans int) } ``` -### **TypeScript** - -```ts -function dietPlanPerformance(calories: number[], k: number, lower: number, upper: number): number { - const n = calories.length; - const s: number[] = new Array(n + 1).fill(0); - for (let i = 0; i < n; ++i) { - s[i + 1] = s[i] + calories[i]; - } - let ans = 0; - for (let i = 0; i < n - k + 1; ++i) { - const t = s[i + k] - s[i]; - if (t < lower) { - --ans; - } else if (t > upper) { - ++ans; - } - } - return ans; -} -``` - ```ts function dietPlanPerformance(calories: number[], k: number, lower: number, upper: number): number { const n = calories.length; @@ -306,10 +294,6 @@ function dietPlanPerformance(calories: number[], k: number, lower: number, upper } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1176.Diet Plan Performance/README_EN.md b/solution/1100-1199/1176.Diet Plan Performance/README_EN.md index 2389e436b0aff..f2a884a2ec81f 100644 --- a/solution/1100-1199/1176.Diet Plan Performance/README_EN.md +++ b/solution/1100-1199/1176.Diet Plan Performance/README_EN.md @@ -60,7 +60,7 @@ calories[2] + calories[3] < lower so 1 point is lost. ## Solutions -**Solution 1: Prefix Sum** +### Solution 1: Prefix Sum First, we preprocess a prefix sum array $s$ of length $n+1$, where $s[i]$ represents the total calories of the first $i$ days. @@ -68,16 +68,8 @@ Then we traverse the prefix sum array $s$. For each position $i$, we calculate $ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the `calories` array. -**Solution 2: Sliding Window** - -We maintain a sliding window of length $k$, and the sum of the elements in the window is denoted as $s$. If $s \lt lower$, the score decreases by $1$; if $s > upper$, the score increases by $1$. - -The time complexity is $O(n)$, where $n$ is the length of the `calories` array. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def dietPlanPerformance( @@ -94,28 +86,6 @@ class Solution: return ans ``` -```python -class Solution: - def dietPlanPerformance( - self, calories: List[int], k: int, lower: int, upper: int - ) -> int: - def check(s): - if s < lower: - return -1 - if s > upper: - return 1 - return 0 - - s, n = sum(calories[:k]), len(calories) - ans = check(s) - for i in range(k, n): - s += calories[i] - calories[i - k] - ans += check(s) - return ans -``` - -### **Java** - ```java class Solution { public int dietPlanPerformance(int[] calories, int k, int lower, int upper) { @@ -138,6 +108,99 @@ class Solution { } ``` +```cpp +class Solution { +public: + int dietPlanPerformance(vector& calories, int k, int lower, int upper) { + int n = calories.size(); + int s[n + 1]; + s[0] = 0; + for (int i = 0; i < n; ++i) { + s[i + 1] = s[i] + calories[i]; + } + int ans = 0; + for (int i = 0; i < n - k + 1; ++i) { + int t = s[i + k] - s[i]; + if (t < lower) { + --ans; + } else if (t > upper) { + ++ans; + } + } + return ans; + } +}; +``` + +```go +func dietPlanPerformance(calories []int, k int, lower int, upper int) (ans int) { + n := len(calories) + s := make([]int, n+1) + for i, x := range calories { + s[i+1] = s[i] + x + } + for i := 0; i < n-k+1; i++ { + t := s[i+k] - s[i] + if t < lower { + ans-- + } else if t > upper { + ans++ + } + } + return +} +``` + +```ts +function dietPlanPerformance(calories: number[], k: number, lower: number, upper: number): number { + const n = calories.length; + const s: number[] = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + calories[i]; + } + let ans = 0; + for (let i = 0; i < n - k + 1; ++i) { + const t = s[i + k] - s[i]; + if (t < lower) { + --ans; + } else if (t > upper) { + ++ans; + } + } + return ans; +} +``` + + + +### Solution 2: Sliding Window + +We maintain a sliding window of length $k$, and the sum of the elements in the window is denoted as $s$. If $s \lt lower$, the score decreases by $1$; if $s > upper$, the score increases by $1$. + +The time complexity is $O(n)$, where $n$ is the length of the `calories` array. The space complexity is $O(1)$. + + + +```python +class Solution: + def dietPlanPerformance( + self, calories: List[int], k: int, lower: int, upper: int + ) -> int: + def check(s): + if s < lower: + return -1 + if s > upper: + return 1 + return 0 + + s, n = sum(calories[:k]), len(calories) + ans = check(s) + for i in range(k, n): + s += calories[i] - calories[i - k] + ans += check(s) + return ans +``` + ```java class Solution { public int dietPlanPerformance(int[] calories, int k, int lower, int upper) { @@ -164,32 +227,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int dietPlanPerformance(vector& calories, int k, int lower, int upper) { - int n = calories.size(); - int s[n + 1]; - s[0] = 0; - for (int i = 0; i < n; ++i) { - s[i + 1] = s[i] + calories[i]; - } - int ans = 0; - for (int i = 0; i < n - k + 1; ++i) { - int t = s[i + k] - s[i]; - if (t < lower) { - --ans; - } else if (t > upper) { - ++ans; - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -215,27 +252,6 @@ public: }; ``` -### **Go** - -```go -func dietPlanPerformance(calories []int, k int, lower int, upper int) (ans int) { - n := len(calories) - s := make([]int, n+1) - for i, x := range calories { - s[i+1] = s[i] + x - } - for i := 0; i < n-k+1; i++ { - t := s[i+k] - s[i] - if t < lower { - ans-- - } else if t > upper { - ans++ - } - } - return -} -``` - ```go func dietPlanPerformance(calories []int, k int, lower int, upper int) (ans int) { n := len(calories) @@ -260,28 +276,6 @@ func dietPlanPerformance(calories []int, k int, lower int, upper int) (ans int) } ``` -### **TypeScript** - -```ts -function dietPlanPerformance(calories: number[], k: number, lower: number, upper: number): number { - const n = calories.length; - const s: number[] = new Array(n + 1).fill(0); - for (let i = 0; i < n; ++i) { - s[i + 1] = s[i] + calories[i]; - } - let ans = 0; - for (let i = 0; i < n - k + 1; ++i) { - const t = s[i + k] - s[i]; - if (t < lower) { - --ans; - } else if (t > upper) { - ++ans; - } - } - return ans; -} -``` - ```ts function dietPlanPerformance(calories: number[], k: number, lower: number, upper: number): number { const n = calories.length; @@ -304,10 +298,6 @@ function dietPlanPerformance(calories: number[], k: number, lower: number, upper } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1177.Can Make Palindrome from Substring/README.md b/solution/1100-1199/1177.Can Make Palindrome from Substring/README.md index 8a73a16932a0d..46d7155e6d77c 100644 --- a/solution/1100-1199/1177.Can Make Palindrome from Substring/README.md +++ b/solution/1100-1199/1177.Can Make Palindrome from Substring/README.md @@ -43,9 +43,7 @@ queries[4] : 子串 = "abcda",可以变成回文的 "abcba ## 解法 - - -**方法一:前缀和** +### 方法一:前缀和 我们先考虑一个子串能否在经过最多 $k$ 次替换后变成回文串,显然,我们需要统计子串中每个字符出现的次数,这可以通过前缀和来实现。对于出现偶数次的字符,我们不需要进行替换,对于出现奇数次的字符,我们需要进行替换,替换的次数为 $\lfloor \frac{x}{2} \rfloor$,其中 $x$ 为出现奇数次的字符的个数。如果 $\lfloor \frac{x}{2} \rfloor \leq k$,那么这个子串就可以变成回文串。 @@ -55,10 +53,6 @@ queries[4] : 子串 = "abcda",可以变成回文的 "abcba -### **Python3** - - - ```python class Solution: def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]: @@ -74,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List canMakePaliQueries(String s, int[][] queries) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go func canMakePaliQueries(s string, queries [][]int) (ans []bool) { n := len(s) @@ -156,8 +142,6 @@ func canMakePaliQueries(s string, queries [][]int) (ans []bool) { } ``` -### **TypeScript** - ```ts function canMakePaliQueries(s: string, queries: number[][]): boolean[] { const n = s.length; @@ -180,10 +164,6 @@ function canMakePaliQueries(s: string, queries: number[][]): boolean[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1177.Can Make Palindrome from Substring/README_EN.md b/solution/1100-1199/1177.Can Make Palindrome from Substring/README_EN.md index e6cb2a6842f76..bbf714b10ab5f 100644 --- a/solution/1100-1199/1177.Can Make Palindrome from Substring/README_EN.md +++ b/solution/1100-1199/1177.Can Make Palindrome from Substring/README_EN.md @@ -45,7 +45,7 @@ queries[4]: substring = "abcda", could be changed to "abcba" ## Solutions -**Solution 1: Prefix Sum** +### Solution 1: Prefix Sum First, consider whether a substring can become a palindrome after at most $k$ replacements. Obviously, we need to count the number of times each character appears in the substring, which can be implemented through prefix sum. For characters that appear an even number of times, we do not need to replace them. For characters that appear an odd number of times, we need to replace them. The number of replacements is $\lfloor \frac{x}{2} \rfloor$, where $x$ is the number of characters that appear an odd number of times. If $\lfloor \frac{x}{2} \rfloor \leq k$, then this substring can become a palindrome. @@ -55,8 +55,6 @@ The time complexity is $O((n + m) \times C)$, and the space complexity is $O(n \ -### **Python3** - ```python class Solution: def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]: @@ -72,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List canMakePaliQueries(String s, int[][] queries) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +122,6 @@ public: }; ``` -### **Go** - ```go func canMakePaliQueries(s string, queries [][]int) (ans []bool) { n := len(s) @@ -152,8 +144,6 @@ func canMakePaliQueries(s string, queries [][]int) (ans []bool) { } ``` -### **TypeScript** - ```ts function canMakePaliQueries(s: string, queries: number[][]): boolean[] { const n = s.length; @@ -176,10 +166,6 @@ function canMakePaliQueries(s: string, queries: number[][]): boolean[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1178.Number of Valid Words for Each Puzzle/README.md b/solution/1100-1199/1178.Number of Valid Words for Each Puzzle/README.md index c7c52d2fa20a0..a92f43d5e9bc8 100644 --- a/solution/1100-1199/1178.Number of Valid Words for Each Puzzle/README.md +++ b/solution/1100-1199/1178.Number of Valid Words for Each Puzzle/README.md @@ -51,9 +51,7 @@ puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"] ## 解法 - - -**方法一:状态压缩 + 哈希表 + 子集枚举** +### 方法一:状态压缩 + 哈希表 + 子集枚举 根据题目描述,对于字谜数组 $puzzles$ 中的每一个字谜 $p$,我们需要统计有多少个单词 $w$ 包含了字谜 $p$ 的第一个字母,且 $w$ 的每一个字母都可以在 $p$ 中找到。 @@ -67,10 +65,6 @@ puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"] -### **Python3** - - - ```python class Solution: def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List findNumOfValidWords(String[] words, String[] puzzles) { @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +152,6 @@ public: }; ``` -### **Go** - ```go func findNumOfValidWords(words []string, puzzles []string) (ans []int) { cnt := map[int]int{} @@ -193,8 +179,6 @@ func findNumOfValidWords(words []string, puzzles []string) (ans []int) { } ``` -### **TypeScript** - ```ts function findNumOfValidWords(words: string[], puzzles: string[]): number[] { const cnt: Map = new Map(); @@ -224,10 +208,6 @@ function findNumOfValidWords(words: string[], puzzles: string[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1178.Number of Valid Words for Each Puzzle/README_EN.md b/solution/1100-1199/1178.Number of Valid Words for Each Puzzle/README_EN.md index a9924a094d8f4..b0bee94cdf6dd 100644 --- a/solution/1100-1199/1178.Number of Valid Words for Each Puzzle/README_EN.md +++ b/solution/1100-1199/1178.Number of Valid Words for Each Puzzle/README_EN.md @@ -52,7 +52,7 @@ There are no valid words for "gaswxyz" cause none of the words in the ## Solutions -**Solution 1: State Compression + Hash Table + Subset Enumeration** +### Solution 1: State Compression + Hash Table + Subset Enumeration According to the problem description, for each puzzle $p$ in the puzzle array $puzzles$, we need to count how many words $w$ contain the first letter of the puzzle $p$, and every letter in $w$ can be found in $p$. @@ -66,8 +66,6 @@ The time complexity is $O(m \times |w| + n \times 2^{|p|})$, and the space compl -### **Python3** - ```python class Solution: def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: @@ -92,8 +90,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List findNumOfValidWords(String[] words, String[] puzzles) { @@ -125,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +153,6 @@ public: }; ``` -### **Go** - ```go func findNumOfValidWords(words []string, puzzles []string) (ans []int) { cnt := map[int]int{} @@ -188,8 +180,6 @@ func findNumOfValidWords(words []string, puzzles []string) (ans []int) { } ``` -### **TypeScript** - ```ts function findNumOfValidWords(words: string[], puzzles: string[]): number[] { const cnt: Map = new Map(); @@ -219,10 +209,6 @@ function findNumOfValidWords(words: string[], puzzles: string[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1179.Reformat Department Table/README.md b/solution/1100-1199/1179.Reformat Department Table/README.md index 506928b5f0737..9010726370fcc 100644 --- a/solution/1100-1199/1179.Reformat Department Table/README.md +++ b/solution/1100-1199/1179.Reformat Department Table/README.md @@ -58,12 +58,10 @@ Department table: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -133,3 +131,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1100-1199/1179.Reformat Department Table/README_EN.md b/solution/1100-1199/1179.Reformat Department Table/README_EN.md index 821d56ed71a7f..1047a55b88f2d 100644 --- a/solution/1100-1199/1179.Reformat Department Table/README_EN.md +++ b/solution/1100-1199/1179.Reformat Department Table/README_EN.md @@ -56,9 +56,9 @@ Note that the result table has 13 columns (1 for the department id + 12 for the ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -129,3 +129,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/README.md b/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/README.md index 110ea22a3293c..38d77f8985c9e 100644 --- a/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/README.md +++ b/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们可以使用双指针,用指针 $i$ 指向当前子串的起始位置,指针 $j$ 向右移动到第一个与 $s[i]$ 不同的位置,那么 $[i,..j-1]$ 就是以 $s[i]$ 为唯一字母的子串,长度为 $j-i$,那么以 $s[i]$ 为唯一字母的子串的个数就是 $\frac{(j-i+1)(j-i)}{2}$,累加到答案中。然后令 $i=j$,继续遍历,直到 $i$ 超出字符串 $s$ 的范围。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def countLetters(self, s: str) -> int: @@ -67,26 +61,6 @@ class Solution: return ans ``` -```python -class Solution: - def countLetters(self, s: str) -> int: - ans = 0 - i, n = 0, len(s) - while i < n: - j = i - cnt = 0 - while j < n and s[j] == s[i]: - j += 1 - cnt += 1 - ans += cnt - i = j - return ans -``` - -### **Java** - - - ```java class Solution { public int countLetters(String s) { @@ -104,43 +78,95 @@ class Solution { } ``` -```java +```cpp class Solution { - public int countLetters(String s) { +public: + int countLetters(string s) { int ans = 0; - int i = 0, n = s.length(); - while (i < n) { + for (int i = 0, n = s.size(); i < n;) { int j = i; - int cnt = 0; - while (j < n && s.charAt(j) == s.charAt(i)) { + while (j < n && s[j] == s[i]) { ++j; - ans += ++cnt; } + ans += (1 + j - i) * (j - i) / 2; i = j; } return ans; } +}; +``` + +```go +func countLetters(s string) int { + ans := 0 + for i, n := 0, len(s); i < n; { + j := i + for j < n && s[j] == s[i] { + j++ + } + ans += (1 + j - i) * (j - i) / 2 + i = j + } + return ans } ``` -### **C++** +```ts +function countLetters(s: string): number { + let ans = 0; + const n = s.length; + for (let i = 0; i < n; ) { + let j = i; + let cnt = 0; + while (j < n && s[j] === s[i]) { + ++j; + ans += ++cnt; + } + i = j; + } + return ans; +} +``` -```cpp + + +### 方法二 + + + +```python +class Solution: + def countLetters(self, s: str) -> int: + ans = 0 + i, n = 0, len(s) + while i < n: + j = i + cnt = 0 + while j < n and s[j] == s[i]: + j += 1 + cnt += 1 + ans += cnt + i = j + return ans +``` + +```java class Solution { -public: - int countLetters(string s) { + public int countLetters(String s) { int ans = 0; - for (int i = 0, n = s.size(); i < n;) { + int i = 0, n = s.length(); + while (i < n) { int j = i; - while (j < n && s[j] == s[i]) { + int cnt = 0; + while (j < n && s.charAt(j) == s.charAt(i)) { ++j; + ans += ++cnt; } - ans += (1 + j - i) * (j - i) / 2; i = j; } return ans; } -}; +} ``` ```cpp @@ -163,23 +189,6 @@ public: }; ``` -### **Go** - -```go -func countLetters(s string) int { - ans := 0 - for i, n := 0, len(s); i < n; { - j := i - for j < n && s[j] == s[i] { - j++ - } - ans += (1 + j - i) * (j - i) / 2 - i = j - } - return ans -} -``` - ```go func countLetters(s string) (ans int) { i, n := 0, len(s) @@ -197,29 +206,6 @@ func countLetters(s string) (ans int) { } ``` -### **TypeScript** - -```ts -function countLetters(s: string): number { - let ans = 0; - const n = s.length; - for (let i = 0; i < n; ) { - let j = i; - let cnt = 0; - while (j < n && s[j] === s[i]) { - ++j; - ans += ++cnt; - } - i = j; - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/README_EN.md b/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/README_EN.md index 16e06a6af8cde..b3628500ae76d 100644 --- a/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/README_EN.md +++ b/solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/README_EN.md @@ -37,7 +37,7 @@ So the answer is 1 + 2 + 4 + 1 = 8. ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We can use two pointers, where pointer $i$ points to the start of the current substring, and pointer $j$ moves to the right to the first position that is different from $s[i]$. Then, $[i,..j-1]$ is a substring with $s[i]$ as the only character, and its length is $j-i$. Therefore, the number of substrings with $s[i]$ as the only character is $\frac{(j-i+1)(j-i)}{2}$, which is added to the answer. Then, we set $i=j$ and continue to traverse until $i$ exceeds the range of string $s$. @@ -45,8 +45,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. The sp -### **Python3** - ```python class Solution: def countLetters(self, s: str) -> int: @@ -61,24 +59,6 @@ class Solution: return ans ``` -```python -class Solution: - def countLetters(self, s: str) -> int: - ans = 0 - i, n = 0, len(s) - while i < n: - j = i - cnt = 0 - while j < n and s[j] == s[i]: - j += 1 - cnt += 1 - ans += cnt - i = j - return ans -``` - -### **Java** - ```java class Solution { public int countLetters(String s) { @@ -96,43 +76,95 @@ class Solution { } ``` -```java +```cpp class Solution { - public int countLetters(String s) { +public: + int countLetters(string s) { int ans = 0; - int i = 0, n = s.length(); - while (i < n) { + for (int i = 0, n = s.size(); i < n;) { int j = i; - int cnt = 0; - while (j < n && s.charAt(j) == s.charAt(i)) { + while (j < n && s[j] == s[i]) { ++j; - ans += ++cnt; } + ans += (1 + j - i) * (j - i) / 2; i = j; } return ans; } +}; +``` + +```go +func countLetters(s string) int { + ans := 0 + for i, n := 0, len(s); i < n; { + j := i + for j < n && s[j] == s[i] { + j++ + } + ans += (1 + j - i) * (j - i) / 2 + i = j + } + return ans +} +``` + +```ts +function countLetters(s: string): number { + let ans = 0; + const n = s.length; + for (let i = 0; i < n; ) { + let j = i; + let cnt = 0; + while (j < n && s[j] === s[i]) { + ++j; + ans += ++cnt; + } + i = j; + } + return ans; } ``` -### **C++** + -```cpp +### Solution 2 + + + +```python +class Solution: + def countLetters(self, s: str) -> int: + ans = 0 + i, n = 0, len(s) + while i < n: + j = i + cnt = 0 + while j < n and s[j] == s[i]: + j += 1 + cnt += 1 + ans += cnt + i = j + return ans +``` + +```java class Solution { -public: - int countLetters(string s) { + public int countLetters(String s) { int ans = 0; - for (int i = 0, n = s.size(); i < n;) { + int i = 0, n = s.length(); + while (i < n) { int j = i; - while (j < n && s[j] == s[i]) { + int cnt = 0; + while (j < n && s.charAt(j) == s.charAt(i)) { ++j; + ans += ++cnt; } - ans += (1 + j - i) * (j - i) / 2; i = j; } return ans; } -}; +} ``` ```cpp @@ -155,23 +187,6 @@ public: }; ``` -### **Go** - -```go -func countLetters(s string) int { - ans := 0 - for i, n := 0, len(s); i < n; { - j := i - for j < n && s[j] == s[i] { - j++ - } - ans += (1 + j - i) * (j - i) / 2 - i = j - } - return ans -} -``` - ```go func countLetters(s string) (ans int) { i, n := 0, len(s) @@ -189,29 +204,6 @@ func countLetters(s string) (ans int) { } ``` -### **TypeScript** - -```ts -function countLetters(s: string): number { - let ans = 0; - const n = s.length; - for (let i = 0; i < n; ) { - let j = i; - let cnt = 0; - while (j < n && s[j] === s[i]) { - ++j; - ans += ++cnt; - } - i = j; - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1181.Before and After Puzzle/README.md b/solution/1100-1199/1181.Before and After Puzzle/README.md index 790fcdaec535c..7d7e6aec3d0c7 100644 --- a/solution/1100-1199/1181.Before and After Puzzle/README.md +++ b/solution/1100-1199/1181.Before and After Puzzle/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:哈希表 + 排序** +### 方法一:哈希表 + 排序 我们先遍历列表 `phrases`,将每个短语的首尾单词存储数组 $ps$ 中,其中 $ps[i][0]$ 和 $ps[i][1]$ 分别表示第 $i$ 个短语的首尾单词。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def beforeAndAfterPuzzles(self, phrases: List[str]) -> List[str]: @@ -95,10 +89,6 @@ class Solution: return sorted(set(ans)) ``` -### **Java** - - - ```java class Solution { public List beforeAndAfterPuzzles(String[] phrases) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func beforeAndAfterPuzzles(phrases []string) []string { n := len(phrases) @@ -182,8 +168,6 @@ func beforeAndAfterPuzzles(phrases []string) []string { } ``` -### **TypeScript** - ```ts function beforeAndAfterPuzzles(phrases: string[]): string[] { const ps: string[][] = []; @@ -204,10 +188,6 @@ function beforeAndAfterPuzzles(phrases: string[]): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1181.Before and After Puzzle/README_EN.md b/solution/1100-1199/1181.Before and After Puzzle/README_EN.md index b9bb73b85bb94..d197fced2134e 100644 --- a/solution/1100-1199/1181.Before and After Puzzle/README_EN.md +++ b/solution/1100-1199/1181.Before and After Puzzle/README_EN.md @@ -58,7 +58,7 @@ ## Solutions -**Solution 1: Hash Table + Sorting** +### Solution 1: Hash Table + Sorting First, we traverse the `phrases` list, storing the first and last words of each phrase in the array $ps$, where $ps[i][0]$ and $ps[i][1]$ represent the first and last words of the $i$th phrase, respectively. @@ -70,8 +70,6 @@ The time complexity is $O(n^2 \times m \times (\log n + \log m))$, and the space -### **Python3** - ```python class Solution: def beforeAndAfterPuzzles(self, phrases: List[str]) -> List[str]: @@ -88,8 +86,6 @@ class Solution: return sorted(set(ans)) ``` -### **Java** - ```java class Solution { public List beforeAndAfterPuzzles(String[] phrases) { @@ -114,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +140,6 @@ public: }; ``` -### **Go** - ```go func beforeAndAfterPuzzles(phrases []string) []string { n := len(phrases) @@ -173,8 +165,6 @@ func beforeAndAfterPuzzles(phrases []string) []string { } ``` -### **TypeScript** - ```ts function beforeAndAfterPuzzles(phrases: string[]): string[] { const ps: string[][] = []; @@ -195,10 +185,6 @@ function beforeAndAfterPuzzles(phrases: string[]): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1182.Shortest Distance to Target Color/README.md b/solution/1100-1199/1182.Shortest Distance to Target Color/README.md index e3df9f1294b72..f6b5572ae1c5e 100644 --- a/solution/1100-1199/1182.Shortest Distance to Target Color/README.md +++ b/solution/1100-1199/1182.Shortest Distance to Target Color/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:预处理** +### 方法一:预处理 我们可以预处理出每个位置到左边最近的颜色 $1$,$2$,$3$ 的距离,以及每个位置到右边最近的颜色 $1$,$2$,$3$ 的距离,记录在数组 $left$ 和 $right$ 中。初始时 $left[0][0] = left[0][1] = left[0][2] = -\infty$,而 $right[n][0] = right[n][1] = right[n][2] = \infty$,其中 $n$ 是数组 $colors$ 的长度。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def shortestDistanceColor( @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List shortestDistanceColor(int[] colors, int[][] queries) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func shortestDistanceColor(colors []int, queries [][]int) (ans []int) { n := len(colors) @@ -192,8 +178,6 @@ func shortestDistanceColor(colors []int, queries [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function shortestDistanceColor(colors: number[], queries: number[][]): number[] { const n = colors.length; @@ -225,10 +209,6 @@ function shortestDistanceColor(colors: number[], queries: number[][]): number[] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1182.Shortest Distance to Target Color/README_EN.md b/solution/1100-1199/1182.Shortest Distance to Target Color/README_EN.md index 8239fc840a706..34d7cee8b0980 100644 --- a/solution/1100-1199/1182.Shortest Distance to Target Color/README_EN.md +++ b/solution/1100-1199/1182.Shortest Distance to Target Color/README_EN.md @@ -42,7 +42,7 @@ The nearest 1 from index 6 is at index 3 (3 steps away). ## Solutions -**Solution 1: Preprocessing** +### Solution 1: Preprocessing We can preprocess the distance from each position to the nearest color $1$, $2$, $3$ on the left, and the distance from each position to the nearest color $1$, $2$, $3$ on the right, and record them in the arrays $left$ and $right$. Initially, $left[0][0] = left[0][1] = left[0][2] = -\infty$, and $right[n][0] = right[n][1] = right[n][2] = \infty$, where $n$ is the length of the array `colors`. @@ -52,8 +52,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def shortestDistanceColor( @@ -77,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List shortestDistanceColor(int[] colors, int[][] queries) { @@ -111,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +140,6 @@ public: }; ``` -### **Go** - ```go func shortestDistanceColor(colors []int, queries [][]int) (ans []int) { n := len(colors) @@ -180,8 +172,6 @@ func shortestDistanceColor(colors []int, queries [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function shortestDistanceColor(colors: number[], queries: number[][]): number[] { const n = colors.length; @@ -213,10 +203,6 @@ function shortestDistanceColor(colors: number[], queries: number[][]): number[] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1183.Maximum Number of Ones/README.md b/solution/1100-1199/1183.Maximum Number of Ones/README.md index c52779c80b2a8..8be21c11e1522 100644 --- a/solution/1100-1199/1183.Maximum Number of Ones/README.md +++ b/solution/1100-1199/1183.Maximum Number of Ones/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:统计等效位置** +### 方法一:统计等效位置 为了方便说明,我们不妨令 $x = sideLength$。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def maximumNumberOfOnes( @@ -79,10 +73,6 @@ class Solution: return sum(cnt[:maxOnes]) ``` -### **Java** - - - ```java class Solution { public int maximumNumberOfOnes(int width, int height, int sideLength, int maxOnes) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func maximumNumberOfOnes(width int, height int, sideLength int, maxOnes int) int { x := sideLength @@ -149,8 +135,6 @@ func maximumNumberOfOnes(width int, height int, sideLength int, maxOnes int) int } ``` -### **JavaScript** - ```js /** * @param {number} width @@ -173,10 +157,6 @@ var maximumNumberOfOnes = function (width, height, sideLength, maxOnes) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1183.Maximum Number of Ones/README_EN.md b/solution/1100-1199/1183.Maximum Number of Ones/README_EN.md index 9006346076abe..728a87211c185 100644 --- a/solution/1100-1199/1183.Maximum Number of Ones/README_EN.md +++ b/solution/1100-1199/1183.Maximum Number of Ones/README_EN.md @@ -44,7 +44,7 @@ The best solution that has 4 ones is: ## Solutions -**Solution 1: Count Equivalent Positions** +### Solution 1: Count Equivalent Positions For convenience, let's denote $x = sideLength$. @@ -54,8 +54,6 @@ The time complexity is $O(m \times n)$, where $m$ and $n$ are the number of rows -### **Python3** - ```python class Solution: def maximumNumberOfOnes( @@ -71,8 +69,6 @@ class Solution: return sum(cnt[:maxOnes]) ``` -### **Java** - ```java class Solution { public int maximumNumberOfOnes(int width, int height, int sideLength, int maxOnes) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func maximumNumberOfOnes(width int, height int, sideLength int, maxOnes int) int { x := sideLength @@ -139,8 +131,6 @@ func maximumNumberOfOnes(width int, height int, sideLength int, maxOnes int) int } ``` -### **JavaScript** - ```js /** * @param {number} width @@ -163,10 +153,6 @@ var maximumNumberOfOnes = function (width, height, sideLength, maxOnes) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1184.Distance Between Bus Stops/README.md b/solution/1100-1199/1184.Distance Between Bus Stops/README.md index 8a9835409fa6c..8c8715a96e470 100644 --- a/solution/1100-1199/1184.Distance Between Bus Stops/README.md +++ b/solution/1100-1199/1184.Distance Between Bus Stops/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以先统计出公交车的总行驶距离 $s$,然后模拟公交车的行驶过程,从出发点开始,每次向右移动一站,直到到达目的地为止。在模拟的过程中,我们可以记录从出发点到目的地的距离 $a$,那么从目的地到出发点的最短距离就是 $\min(a, s - a)$。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def distanceBetweenBusStops( @@ -83,10 +77,6 @@ class Solution: return min(a, sum(distance) - a) ``` -### **Java** - - - ```java class Solution { public int distanceBetweenBusStops(int[] distance, int start, int destination) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func distanceBetweenBusStops(distance []int, start int, destination int) int { s := 0 @@ -136,16 +122,8 @@ func distanceBetweenBusStops(distance []int, start int, destination int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} distance - * @param {number} start - * @param {number} destination - * @return {number} - */ -var distanceBetweenBusStops = function (distance, start, destination) { +```ts +function distanceBetweenBusStops(distance: number[], start: number, destination: number): number { const s = distance.reduce((a, b) => a + b, 0); let a = 0; const n = distance.length; @@ -154,13 +132,17 @@ var distanceBetweenBusStops = function (distance, start, destination) { start = (start + 1) % n; } return Math.min(a, s - a); -}; +} ``` -### **TypeScript** - -```ts -function distanceBetweenBusStops(distance: number[], start: number, destination: number): number { +```js +/** + * @param {number[]} distance + * @param {number} start + * @param {number} destination + * @return {number} + */ +var distanceBetweenBusStops = function (distance, start, destination) { const s = distance.reduce((a, b) => a + b, 0); let a = 0; const n = distance.length; @@ -169,13 +151,9 @@ function distanceBetweenBusStops(distance: number[], start: number, destination: start = (start + 1) % n; } return Math.min(a, s - a); -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md b/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md index f81234bd49bc3..1384249172c1c 100644 --- a/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md +++ b/solution/1100-1199/1184.Distance Between Bus Stops/README_EN.md @@ -56,7 +56,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation First, we can calculate the total distance $s$ that the bus travels. Then, we simulate the bus's journey, starting from the departure point, moving one stop to the right each time, until we reach the destination. During the simulation, we can record the distance $a$ from the departure point to the destination. Therefore, the shortest distance from the destination to the departure point is $\min(a, s - a)$. @@ -64,8 +64,6 @@ The time complexity is $O(n)$, where $n$ is the number of bus stops. The space c -### **Python3** - ```python class Solution: def distanceBetweenBusStops( @@ -78,8 +76,6 @@ class Solution: return min(a, sum(distance) - a) ``` -### **Java** - ```java class Solution { public int distanceBetweenBusStops(int[] distance, int start, int destination) { @@ -95,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +106,6 @@ public: }; ``` -### **Go** - ```go func distanceBetweenBusStops(distance []int, start int, destination int) int { s := 0 @@ -129,16 +121,8 @@ func distanceBetweenBusStops(distance []int, start int, destination int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} distance - * @param {number} start - * @param {number} destination - * @return {number} - */ -var distanceBetweenBusStops = function (distance, start, destination) { +```ts +function distanceBetweenBusStops(distance: number[], start: number, destination: number): number { const s = distance.reduce((a, b) => a + b, 0); let a = 0; const n = distance.length; @@ -147,13 +131,17 @@ var distanceBetweenBusStops = function (distance, start, destination) { start = (start + 1) % n; } return Math.min(a, s - a); -}; +} ``` -### **TypeScript** - -```ts -function distanceBetweenBusStops(distance: number[], start: number, destination: number): number { +```js +/** + * @param {number[]} distance + * @param {number} start + * @param {number} destination + * @return {number} + */ +var distanceBetweenBusStops = function (distance, start, destination) { const s = distance.reduce((a, b) => a + b, 0); let a = 0; const n = distance.length; @@ -162,13 +150,9 @@ function distanceBetweenBusStops(distance: number[], start: number, destination: start = (start + 1) % n; } return Math.min(a, s - a); -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/1100-1199/1185.Day of the Week/README.md b/solution/1100-1199/1185.Day of the Week/README.md index ed442e29e42ac..f8f26bc3d1ab4 100644 --- a/solution/1100-1199/1185.Day of the Week/README.md +++ b/solution/1100-1199/1185.Day of the Week/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:蔡勒公式** +### 方法一:蔡勒公式 我们可以使用蔡勒公式来计算星期几,蔡勒公式如下: @@ -66,40 +64,12 @@ $$ -### **Python3** - - - ```python class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: return datetime.date(year, month, day).strftime('%A') ``` -```python -class Solution: - def dayOfTheWeek(self, d: int, m: int, y: int) -> str: - if m < 3: - m += 12 - y -= 1 - c = y // 100 - y = y % 100 - w = (c // 4 - 2 * c + y + y // 4 + 13 * (m + 1) // 5 + d - 1) % 7 - return [ - "Sunday", - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", - ][w] -``` - -### **Java** - - - ```java import java.util.Calendar; @@ -115,24 +85,6 @@ class Solution { } ``` -```java -class Solution { - public String dayOfTheWeek(int d, int m, int y) { - if (m < 3) { - m += 12; - y -= 1; - } - int c = y / 100; - y %= 100; - int w = (c / 4 - 2 * c + y + y / 4 + 13 * (m + 1) / 5 + d - 1) % 7; - return new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", - "Saturday"}[(w + 7) % 7]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -150,8 +102,6 @@ public: }; ``` -### **Go** - ```go func dayOfTheWeek(d int, m int, y int) string { if m < 3 { @@ -166,8 +116,6 @@ func dayOfTheWeek(d int, m int, y int) string { } ``` -### **TypeScript** - ```ts function dayOfTheWeek(d: number, m: number, y: number): string { if (m < 3) { @@ -190,10 +138,48 @@ function dayOfTheWeek(d: number, m: number, y: number): string { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def dayOfTheWeek(self, d: int, m: int, y: int) -> str: + if m < 3: + m += 12 + y -= 1 + c = y // 100 + y = y % 100 + w = (c // 4 - 2 * c + y + y // 4 + 13 * (m + 1) // 5 + d - 1) % 7 + return [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + ][w] ``` +```java +class Solution { + public String dayOfTheWeek(int d, int m, int y) { + if (m < 3) { + m += 12; + y -= 1; + } + int c = y / 100; + y %= 100; + int w = (c / 4 - 2 * c + y + y / 4 + 13 * (m + 1) / 5 + d - 1) % 7; + return new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", + "Saturday"}[(w + 7) % 7]; + } +} ``` + + diff --git a/solution/1100-1199/1185.Day of the Week/README_EN.md b/solution/1100-1199/1185.Day of the Week/README_EN.md index d5044521cc98e..f2c9d0f2e7c7e 100644 --- a/solution/1100-1199/1185.Day of the Week/README_EN.md +++ b/solution/1100-1199/1185.Day of the Week/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Zeller's Congruence** +### Solution 1: Zeller's Congruence We can use Zeller's Congruence to calculate the day of the week. Zeller's Congruence is as follows: @@ -63,36 +63,12 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: return datetime.date(year, month, day).strftime('%A') ``` -```python -class Solution: - def dayOfTheWeek(self, d: int, m: int, y: int) -> str: - if m < 3: - m += 12 - y -= 1 - c = y // 100 - y = y % 100 - w = (c // 4 - 2 * c + y + y // 4 + 13 * (m + 1) // 5 + d - 1) % 7 - return [ - "Sunday", - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", - ][w] -``` - -### **Java** - ```java import java.util.Calendar; @@ -108,24 +84,6 @@ class Solution { } ``` -```java -class Solution { - public String dayOfTheWeek(int d, int m, int y) { - if (m < 3) { - m += 12; - y -= 1; - } - int c = y / 100; - y %= 100; - int w = (c / 4 - 2 * c + y + y / 4 + 13 * (m + 1) / 5 + d - 1) % 7; - return new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", - "Saturday"}[(w + 7) % 7]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -143,8 +101,6 @@ public: }; ``` -### **Go** - ```go func dayOfTheWeek(d int, m int, y int) string { if m < 3 { @@ -159,8 +115,6 @@ func dayOfTheWeek(d int, m int, y int) string { } ``` -### **TypeScript** - ```ts function dayOfTheWeek(d: number, m: number, y: number): string { if (m < 3) { @@ -183,10 +137,48 @@ function dayOfTheWeek(d: number, m: number, y: number): string { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def dayOfTheWeek(self, d: int, m: int, y: int) -> str: + if m < 3: + m += 12 + y -= 1 + c = y // 100 + y = y % 100 + w = (c // 4 - 2 * c + y + y // 4 + 13 * (m + 1) // 5 + d - 1) % 7 + return [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + ][w] ``` +```java +class Solution { + public String dayOfTheWeek(int d, int m, int y) { + if (m < 3) { + m += 12; + y -= 1; + } + int c = y / 100; + y %= 100; + int w = (c / 4 - 2 * c + y + y / 4 + 13 * (m + 1) / 5 + d - 1) % 7; + return new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", + "Saturday"}[(w + 7) % 7]; + } +} ``` + + diff --git a/solution/1100-1199/1186.Maximum Subarray Sum with One Deletion/README.md b/solution/1100-1199/1186.Maximum Subarray Sum with One Deletion/README.md index b355f3dbbbdb2..204680066b0a3 100644 --- a/solution/1100-1199/1186.Maximum Subarray Sum with One Deletion/README.md +++ b/solution/1100-1199/1186.Maximum Subarray Sum with One Deletion/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:预处理 + 枚举** +### 方法一:预处理 + 枚举 我们可以先预处理出数组 $arr$ 以每个元素结尾和开头的最大子数组和,分别存入数组 $left$ 和 $right$ 中。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def maximumSum(self, arr: List[int]) -> int: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumSum(int[] arr) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func maximumSum(arr []int) int { n := len(arr) @@ -161,8 +147,6 @@ func maximumSum(arr []int) int { } ``` -### **TypeScript** - ```ts function maximumSum(arr: number[]): number { const n = arr.length; @@ -184,10 +168,6 @@ function maximumSum(arr: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1186.Maximum Subarray Sum with One Deletion/README_EN.md b/solution/1100-1199/1186.Maximum Subarray Sum with One Deletion/README_EN.md index 6670b6a19e5f5..4e2d0f5e99390 100644 --- a/solution/1100-1199/1186.Maximum Subarray Sum with One Deletion/README_EN.md +++ b/solution/1100-1199/1186.Maximum Subarray Sum with One Deletion/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Preprocessing + Enumeration** +### Solution 1: Preprocessing + Enumeration We can first preprocess the array $arr$ to find the maximum subarray sum ending at and starting from each element, and store them in the arrays $left$ and $right$ respectively. @@ -52,8 +52,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maximumSum(self, arr: List[int]) -> int: @@ -74,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumSum(int[] arr) { @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +120,6 @@ public: }; ``` -### **Go** - ```go func maximumSum(arr []int) int { n := len(arr) @@ -149,8 +141,6 @@ func maximumSum(arr []int) int { } ``` -### **TypeScript** - ```ts function maximumSum(arr: number[]): number { const n = arr.length; @@ -172,10 +162,6 @@ function maximumSum(arr: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1187.Make Array Strictly Increasing/README.md b/solution/1100-1199/1187.Make Array Strictly Increasing/README.md index 18790305f2aee..b72620268d6ed 100644 --- a/solution/1100-1199/1187.Make Array Strictly Increasing/README.md +++ b/solution/1100-1199/1187.Make Array Strictly Increasing/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示将 $arr1[0,..,i]$ 转换为严格递增数组,且 $arr1[i]$ 不替换的最小操作数。因此,我们在 $arr1$ 设置首尾两个哨兵 $-\infty$ 和 $\infty$。最后一个数一定是不替换,因此 $f[n-1]$ 即为答案。我们初始化 $f[0]=0$,其余 $f[i]=\infty$。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int: @@ -94,10 +88,6 @@ class Solution: return -1 if f[n - 1] >= inf else f[n - 1] ``` -### **Java** - - - ```java class Solution { public int makeArrayIncreasing(int[] arr1, int[] arr2) { @@ -145,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +163,6 @@ public: }; ``` -### **Go** - ```go func makeArrayIncreasing(arr1 []int, arr2 []int) int { sort.Ints(arr2) @@ -215,8 +201,6 @@ func makeArrayIncreasing(arr1 []int, arr2 []int) int { } ``` -### **TypeScript** - ```ts function makeArrayIncreasing(arr1: number[], arr2: number[]): number { arr2.sort((a, b) => a - b); @@ -260,8 +244,6 @@ function makeArrayIncreasing(arr1: number[], arr2: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int MakeArrayIncreasing(int[] arr1, int[] arr2) { @@ -311,10 +293,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1187.Make Array Strictly Increasing/README_EN.md b/solution/1100-1199/1187.Make Array Strictly Increasing/README_EN.md index 3762c5a4f29d7..60b483f0bb7e6 100644 --- a/solution/1100-1199/1187.Make Array Strictly Increasing/README_EN.md +++ b/solution/1100-1199/1187.Make Array Strictly Increasing/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i]$ as the minimum number of operations to convert $arr1[0,..,i]$ into a strictly increasing array, and $arr1[i]$ is not replaced. Therefore, we set two sentinels $-\infty$ and $\infty$ at the beginning and end of $arr1$. The last number is definitely not replaced, so $f[n-1]$ is the answer. We initialize $f[0]=0$, and the rest $f[i]=\infty$. @@ -60,8 +60,6 @@ The time complexity is $(n \times (\log m + \min(m, n)))$, and the space complex -### **Python3** - ```python class Solution: def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int: @@ -86,8 +84,6 @@ class Solution: return -1 if f[n - 1] >= inf else f[n - 1] ``` -### **Java** - ```java class Solution { public int makeArrayIncreasing(int[] arr1, int[] arr2) { @@ -135,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -165,8 +159,6 @@ public: }; ``` -### **Go** - ```go func makeArrayIncreasing(arr1 []int, arr2 []int) int { sort.Ints(arr2) @@ -205,8 +197,6 @@ func makeArrayIncreasing(arr1 []int, arr2 []int) int { } ``` -### **TypeScript** - ```ts function makeArrayIncreasing(arr1: number[], arr2: number[]): number { arr2.sort((a, b) => a - b); @@ -250,8 +240,6 @@ function makeArrayIncreasing(arr1: number[], arr2: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int MakeArrayIncreasing(int[] arr1, int[] arr2) { @@ -301,10 +289,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1188.Design Bounded Blocking Queue/README.md b/solution/1100-1199/1188.Design Bounded Blocking Queue/README.md index 02c12162dab54..7c1b2e902c826 100644 --- a/solution/1100-1199/1188.Design Bounded Blocking Queue/README.md +++ b/solution/1100-1199/1188.Design Bounded Blocking Queue/README.md @@ -96,12 +96,10 @@ queue.size(); // 队列中还有 1 个元素。 ## 解法 - +### 方法一 -### **Python3** - ```python from threading import Semaphore @@ -127,8 +125,6 @@ class BoundedBlockingQueue(object): return len(self.q) ``` -### **Java** - ```java class BoundedBlockingQueue { private Semaphore s1; @@ -159,8 +155,6 @@ class BoundedBlockingQueue { } ``` -### **C++** - ```cpp #include @@ -195,6 +189,6 @@ private: }; ``` -### \*\* - + + diff --git a/solution/1100-1199/1188.Design Bounded Blocking Queue/README_EN.md b/solution/1100-1199/1188.Design Bounded Blocking Queue/README_EN.md index 0b99eaaf683de..f6ee73389c0ec 100644 --- a/solution/1100-1199/1188.Design Bounded Blocking Queue/README_EN.md +++ b/solution/1100-1199/1188.Design Bounded Blocking Queue/README_EN.md @@ -90,9 +90,9 @@ Since the number of threads for producer/consumer is greater than 1, we do not k ## Solutions - +### Solution 1 -### **Python3** + ```python from threading import Semaphore @@ -119,8 +119,6 @@ class BoundedBlockingQueue(object): return len(self.q) ``` -### **Java** - ```java class BoundedBlockingQueue { private Semaphore s1; @@ -151,8 +149,6 @@ class BoundedBlockingQueue { } ``` -### **C++** - ```cpp #include @@ -188,3 +184,5 @@ private: ``` + + diff --git a/solution/1100-1199/1189.Maximum Number of Balloons/README.md b/solution/1100-1199/1189.Maximum Number of Balloons/README.md index 9b5fd5f79603f..4f054dd2e14ab 100644 --- a/solution/1100-1199/1189.Maximum Number of Balloons/README.md +++ b/solution/1100-1199/1189.Maximum Number of Balloons/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们统计字符串 `text` 中每个字母出现的次数,然后将其中字母 `'o'` 和 `'l'` 的出现次数分别除以 2,这是因为单词 `balloon` 中字母 `'o'` 和 `'l'` 都出现了 2 次。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def maxNumberOfBalloons(self, text: str) -> int: @@ -70,10 +64,6 @@ class Solution: return min(cnt[c] for c in 'balon') ``` -### **Java** - - - ```java class Solution { public int maxNumberOfBalloons(String text) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func maxNumberOfBalloons(text string) int { cnt := [26]int{} @@ -134,8 +120,6 @@ func maxNumberOfBalloons(text string) int { } ``` -### **TypeScript** - ```ts function maxNumberOfBalloons(text: string): number { const cnt = new Array(26).fill(0); @@ -146,8 +130,6 @@ function maxNumberOfBalloons(text: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_number_of_balloons(text: String) -> i32 { @@ -183,8 +165,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -213,10 +193,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1189.Maximum Number of Balloons/README_EN.md b/solution/1100-1199/1189.Maximum Number of Balloons/README_EN.md index e256a81ca0f59..d642bf8f8ae7b 100644 --- a/solution/1100-1199/1189.Maximum Number of Balloons/README_EN.md +++ b/solution/1100-1199/1189.Maximum Number of Balloons/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We count the frequency of each letter in the string `text`, and then divide the frequency of the letters 'o' and 'l' by 2, because the word `balloon` contains the letters 'o' and 'l' twice. @@ -54,8 +54,6 @@ The time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is -### **Python3** - ```python class Solution: def maxNumberOfBalloons(self, text: str) -> int: @@ -65,8 +63,6 @@ class Solution: return min(cnt[c] for c in 'balon') ``` -### **Java** - ```java class Solution { public int maxNumberOfBalloons(String text) { @@ -85,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +101,6 @@ public: }; ``` -### **Go** - ```go func maxNumberOfBalloons(text string) int { cnt := [26]int{} @@ -127,8 +119,6 @@ func maxNumberOfBalloons(text string) int { } ``` -### **TypeScript** - ```ts function maxNumberOfBalloons(text: string): number { const cnt = new Array(26).fill(0); @@ -139,8 +129,6 @@ function maxNumberOfBalloons(text: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_number_of_balloons(text: String) -> i32 { @@ -176,8 +164,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -206,10 +192,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/README.md b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/README.md index 35f943c90a59b..7b3cbb886aaf8 100644 --- a/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/README.md +++ b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/README.md @@ -54,30 +54,14 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 用双端队列或者栈,模拟反转的过程。 时间复杂度 $O(n^2)$,其中 $n$ 为字符串 $s$ 的长度。 -**方法二:脑筋急转弯** - -我们观察发现,遍历字符串时,每一次遇到 `(` 或者 `)`,都是跳到对应的 `)` 或者 `(`,然后反转遍历的方向,继续遍历。 - -因此,我们可以用一个数组 $d$ 来记录每个 `(` 或者 `)` 对应的另一个括号的位置,即 $d[i]$ 表示 $i$ 处的括号对应的另一个括号的位置。直接用栈就可以求出 $d$ 数组。 - -然后,我们从左到右遍历字符串,遇到 `(` 或者 `)` 时,根据 $d$ 数组跳到对应的位置,然后反转方向,继续遍历,直到遍历完整个字符串。 - -时间复杂度 $O(n)$,其中 $n$ 为字符串 $s$ 的长度。 - -### **Python3** - - - ```python class Solution: def reverseParentheses(self, s: str) -> str: @@ -94,34 +78,6 @@ class Solution: return ''.join(stk) ``` -```python -class Solution: - def reverseParentheses(self, s: str) -> str: - n = len(s) - d = [0] * n - stk = [] - for i, c in enumerate(s): - if c == '(': - stk.append(i) - elif c == ')': - j = stk.pop() - d[i], d[j] = j, i - i, x = 0, 1 - ans = [] - while i < n: - if s[i] in '()': - i = d[i] - x = -x - else: - ans.append(s[i]) - i += x - return ''.join(ans) -``` - -### **Java** - - - ```java class Solution { public String reverseParentheses(String s) { @@ -153,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -178,6 +132,99 @@ public: }; ``` +```go +func reverseParentheses(s string) string { + stk := []byte{} + for i := range s { + if s[i] == ')' { + t := []byte{} + for stk[len(stk)-1] != '(' { + t = append(t, stk[len(stk)-1]) + stk = stk[:len(stk)-1] + } + stk = stk[:len(stk)-1] + stk = append(stk, t...) + } else { + stk = append(stk, s[i]) + } + } + return string(stk) +} +``` + +```js +/** + * @param {string} s + * @return {string} + */ +var reverseParentheses = function (s) { + const n = s.length; + const d = new Array(n).fill(0); + const stk = []; + for (let i = 0; i < n; ++i) { + if (s[i] == '(') { + stk.push(i); + } else if (s[i] == ')') { + const j = stk.pop(); + d[i] = j; + d[j] = i; + } + } + let i = 0; + let x = 1; + const ans = []; + while (i < n) { + const c = s.charAt(i); + if (c == '(' || c == ')') { + i = d[i]; + x = -x; + } else { + ans.push(c); + } + i += x; + } + return ans.join(''); +}; +``` + + + +### 方法二:脑筋急转弯 + +我们观察发现,遍历字符串时,每一次遇到 `(` 或者 `)`,都是跳到对应的 `)` 或者 `(`,然后反转遍历的方向,继续遍历。 + +因此,我们可以用一个数组 $d$ 来记录每个 `(` 或者 `)` 对应的另一个括号的位置,即 $d[i]$ 表示 $i$ 处的括号对应的另一个括号的位置。直接用栈就可以求出 $d$ 数组。 + +然后,我们从左到右遍历字符串,遇到 `(` 或者 `)` 时,根据 $d$ 数组跳到对应的位置,然后反转方向,继续遍历,直到遍历完整个字符串。 + +时间复杂度 $O(n)$,其中 $n$ 为字符串 $s$ 的长度。 + + + +```python +class Solution: + def reverseParentheses(self, s: str) -> str: + n = len(s) + d = [0] * n + stk = [] + for i, c in enumerate(s): + if c == '(': + stk.append(i) + elif c == ')': + j = stk.pop() + d[i], d[j] = j, i + i, x = 0, 1 + ans = [] + while i < n: + if s[i] in '()': + i = d[i] + x = -x + else: + ans.append(s[i]) + i += x + return ''.join(ans) +``` + ```cpp class Solution { public: @@ -211,28 +258,6 @@ public: }; ``` -### **Go** - -```go -func reverseParentheses(s string) string { - stk := []byte{} - for i := range s { - if s[i] == ')' { - t := []byte{} - for stk[len(stk)-1] != '(' { - t = append(t, stk[len(stk)-1]) - stk = stk[:len(stk)-1] - } - stk = stk[:len(stk)-1] - stk = append(stk, t...) - } else { - stk = append(stk, s[i]) - } - } - return string(stk) -} -``` - ```go func reverseParentheses(s string) string { n := len(s) @@ -262,47 +287,6 @@ func reverseParentheses(s string) string { } ``` -### **JavaScript** - -```js -/** - * @param {string} s - * @return {string} - */ -var reverseParentheses = function (s) { - const n = s.length; - const d = new Array(n).fill(0); - const stk = []; - for (let i = 0; i < n; ++i) { - if (s[i] == '(') { - stk.push(i); - } else if (s[i] == ')') { - const j = stk.pop(); - d[i] = j; - d[j] = i; - } - } - let i = 0; - let x = 1; - const ans = []; - while (i < n) { - const c = s.charAt(i); - if (c == '(' || c == ')') { - i = d[i]; - x = -x; - } else { - ans.push(c); - } - i += x; - } - return ans.join(''); -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/README_EN.md b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/README_EN.md index c3d427e86a093..1a4c059ea7e14 100644 --- a/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/README_EN.md +++ b/solution/1100-1199/1190.Reverse Substrings Between Each Pair of Parentheses/README_EN.md @@ -45,26 +45,14 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can use a double-ended queue or stack to simulate the reversal process. The time complexity is $O(n^2)$, where $n$ is the length of the string $s$. -**Solution 2: Quick Thinking** - -We observe that during the traversal of the string, each time we encounter '(' or ')', we jump to the corresponding ')' or '(', then reverse the traversal direction and continue. - -Therefore, we can use an array $d$ to record the position of the other bracket corresponding to each '(' or ')', i.e., $d[i]$ represents the position of the other bracket corresponding to the bracket at position $i$. We can directly use a stack to calculate the array $d$. - -Then, we traverse the string from left to right. When we encounter '(' or ')', we jump to the corresponding position according to the array $d$, then reverse the direction and continue to traverse until the entire string is traversed. - -The time complexity is $O(n)$, where $n$ is the length of the string $s$. - -### **Python3** - ```python class Solution: def reverseParentheses(self, s: str) -> str: @@ -81,32 +69,6 @@ class Solution: return ''.join(stk) ``` -```python -class Solution: - def reverseParentheses(self, s: str) -> str: - n = len(s) - d = [0] * n - stk = [] - for i, c in enumerate(s): - if c == '(': - stk.append(i) - elif c == ')': - j = stk.pop() - d[i], d[j] = j, i - i, x = 0, 1 - ans = [] - while i < n: - if s[i] in '()': - i = d[i] - x = -x - else: - ans.append(s[i]) - i += x - return ''.join(ans) -``` - -### **Java** - ```java class Solution { public String reverseParentheses(String s) { @@ -138,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,6 +123,99 @@ public: }; ``` +```go +func reverseParentheses(s string) string { + stk := []byte{} + for i := range s { + if s[i] == ')' { + t := []byte{} + for stk[len(stk)-1] != '(' { + t = append(t, stk[len(stk)-1]) + stk = stk[:len(stk)-1] + } + stk = stk[:len(stk)-1] + stk = append(stk, t...) + } else { + stk = append(stk, s[i]) + } + } + return string(stk) +} +``` + +```js +/** + * @param {string} s + * @return {string} + */ +var reverseParentheses = function (s) { + const n = s.length; + const d = new Array(n).fill(0); + const stk = []; + for (let i = 0; i < n; ++i) { + if (s[i] == '(') { + stk.push(i); + } else if (s[i] == ')') { + const j = stk.pop(); + d[i] = j; + d[j] = i; + } + } + let i = 0; + let x = 1; + const ans = []; + while (i < n) { + const c = s.charAt(i); + if (c == '(' || c == ')') { + i = d[i]; + x = -x; + } else { + ans.push(c); + } + i += x; + } + return ans.join(''); +}; +``` + + + +### Solution 2: Quick Thinking + +We observe that during the traversal of the string, each time we encounter '(' or ')', we jump to the corresponding ')' or '(', then reverse the traversal direction and continue. + +Therefore, we can use an array $d$ to record the position of the other bracket corresponding to each '(' or ')', i.e., $d[i]$ represents the position of the other bracket corresponding to the bracket at position $i$. We can directly use a stack to calculate the array $d$. + +Then, we traverse the string from left to right. When we encounter '(' or ')', we jump to the corresponding position according to the array $d$, then reverse the direction and continue to traverse until the entire string is traversed. + +The time complexity is $O(n)$, where $n$ is the length of the string $s$. + + + +```python +class Solution: + def reverseParentheses(self, s: str) -> str: + n = len(s) + d = [0] * n + stk = [] + for i, c in enumerate(s): + if c == '(': + stk.append(i) + elif c == ')': + j = stk.pop() + d[i], d[j] = j, i + i, x = 0, 1 + ans = [] + while i < n: + if s[i] in '()': + i = d[i] + x = -x + else: + ans.append(s[i]) + i += x + return ''.join(ans) +``` + ```cpp class Solution { public: @@ -196,28 +249,6 @@ public: }; ``` -### **Go** - -```go -func reverseParentheses(s string) string { - stk := []byte{} - for i := range s { - if s[i] == ')' { - t := []byte{} - for stk[len(stk)-1] != '(' { - t = append(t, stk[len(stk)-1]) - stk = stk[:len(stk)-1] - } - stk = stk[:len(stk)-1] - stk = append(stk, t...) - } else { - stk = append(stk, s[i]) - } - } - return string(stk) -} -``` - ```go func reverseParentheses(s string) string { n := len(s) @@ -247,47 +278,6 @@ func reverseParentheses(s string) string { } ``` -### **JavaScript** - -```js -/** - * @param {string} s - * @return {string} - */ -var reverseParentheses = function (s) { - const n = s.length; - const d = new Array(n).fill(0); - const stk = []; - for (let i = 0; i < n; ++i) { - if (s[i] == '(') { - stk.push(i); - } else if (s[i] == ')') { - const j = stk.pop(); - d[i] = j; - d[j] = i; - } - } - let i = 0; - let x = 1; - const ans = []; - while (i < n) { - const c = s.charAt(i); - if (c == '(' || c == ')') { - i = d[i]; - x = -x; - } else { - ans.push(c); - } - i += x; - } - return ans.join(''); -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1191.K-Concatenation Maximum Sum/README.md b/solution/1100-1199/1191.K-Concatenation Maximum Sum/README.md index 3cd444959b916..0f00a1734ccf4 100644 --- a/solution/1100-1199/1191.K-Concatenation Maximum Sum/README.md +++ b/solution/1100-1199/1191.K-Concatenation Maximum Sum/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:前缀和 + 分类讨论** +### 方法一:前缀和 + 分类讨论 我们记数组 $arr$ 所有元素之和为 $s$,最大前缀和为 $mxPre$,最小前缀和为 $miPre$,最大子数组和为 $mxSub$。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def kConcatenationMaxSum(self, arr: List[int], k: int) -> int: @@ -94,10 +88,6 @@ class Solution: return ans % mod ``` -### **Java** - - - ```java class Solution { public int kConcatenationMaxSum(int[] arr, int k) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go func kConcatenationMaxSum(arr []int, k int) int { var s, mxPre, miPre, mxSub int @@ -176,10 +162,6 @@ func kConcatenationMaxSum(arr []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1191.K-Concatenation Maximum Sum/README_EN.md b/solution/1100-1199/1191.K-Concatenation Maximum Sum/README_EN.md index eee702ad86b22..b76483ef829c7 100644 --- a/solution/1100-1199/1191.K-Concatenation Maximum Sum/README_EN.md +++ b/solution/1100-1199/1191.K-Concatenation Maximum Sum/README_EN.md @@ -45,7 +45,7 @@ ## Solutions -**Solution 1: Prefix Sum + Case Discussion** +### Solution 1: Prefix Sum + Case Discussion We denote the sum of all elements in the array $arr$ as $s$, the maximum prefix sum as $mxPre$, the minimum prefix sum as $miPre$, and the maximum subarray sum as $mxSub$. @@ -63,8 +63,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is -### **Python3** - ```python class Solution: def kConcatenationMaxSum(self, arr: List[int], k: int) -> int: @@ -85,8 +83,6 @@ class Solution: return ans % mod ``` -### **Java** - ```java class Solution { public int kConcatenationMaxSum(int[] arr, int k) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +134,6 @@ public: }; ``` -### **Go** - ```go func kConcatenationMaxSum(arr []int, k int) int { var s, mxPre, miPre, mxSub int @@ -165,10 +157,6 @@ func kConcatenationMaxSum(arr []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1192.Critical Connections in a Network/README.md b/solution/1100-1199/1192.Critical Connections in a Network/README.md index 99f9eef4f0053..cbdb7a090ecbb 100644 --- a/solution/1100-1199/1192.Critical Connections in a Network/README.md +++ b/solution/1100-1199/1192.Critical Connections in a Network/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:Tarjan 算法** +### 方法一:Tarjan 算法 此题中的「关键连接」即为「桥」。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def criticalConnections( @@ -97,10 +91,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int now; @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +170,6 @@ public: }; ``` -### **Go** - ```go func criticalConnections(n int, connections [][]int) (ans [][]int) { now := 0 @@ -219,8 +205,6 @@ func criticalConnections(n int, connections [][]int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function criticalConnections(n: number, connections: number[][]): number[][] { let now: number = 0; @@ -256,10 +240,6 @@ function criticalConnections(n: number, connections: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1192.Critical Connections in a Network/README_EN.md b/solution/1100-1199/1192.Critical Connections in a Network/README_EN.md index 98fef92f78e64..eb1ad1e3fc6a9 100644 --- a/solution/1100-1199/1192.Critical Connections in a Network/README_EN.md +++ b/solution/1100-1199/1192.Critical Connections in a Network/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Tarjan Algorithm** +### Solution 1: Tarjan Algorithm The "critical connections" in this problem can be considered as "bridges". @@ -53,8 +53,6 @@ There is an algorithm called the Tarjan algorithm for finding "bridges" and "art -### **Python3** - ```python class Solution: def criticalConnections( @@ -88,8 +86,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int now; @@ -132,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +165,6 @@ public: }; ``` -### **Go** - ```go func criticalConnections(n int, connections [][]int) (ans [][]int) { now := 0 @@ -208,8 +200,6 @@ func criticalConnections(n int, connections [][]int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function criticalConnections(n: number, connections: number[][]): number[][] { let now: number = 0; @@ -245,10 +235,6 @@ function criticalConnections(n: number, connections: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1193.Monthly Transactions I/README.md b/solution/1100-1199/1193.Monthly Transactions I/README.md index dfd687162255c..4411da9a4014f 100644 --- a/solution/1100-1199/1193.Monthly Transactions I/README.md +++ b/solution/1100-1199/1193.Monthly Transactions I/README.md @@ -57,16 +57,12 @@ Transactions table: ## 解法 - - -**方法一:分组求和** +### 方法一:分组求和 我们可以先按照月份和国家分组,然后利用 `COUNT` 和 `SUM` 函数分别求出每个分组的事务数、已批准的事务数、总金额和已批准的总金额。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -81,3 +77,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/1100-1199/1193.Monthly Transactions I/README_EN.md b/solution/1100-1199/1193.Monthly Transactions I/README_EN.md index 841990f02be2f..76c5f592ca2cc 100644 --- a/solution/1100-1199/1193.Monthly Transactions I/README_EN.md +++ b/solution/1100-1199/1193.Monthly Transactions I/README_EN.md @@ -55,14 +55,12 @@ Transactions table: ## Solutions -**Solution 1: Grouping and Aggregation** +### Solution 1: Grouping and Aggregation We can first group by month and country, and then use the `COUNT` and `SUM` functions to respectively calculate the number of transactions, the number of approved transactions, the total amount, and the total amount of approved transactions for each group. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -77,3 +75,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/1100-1199/1194.Tournament Winners/README.md b/solution/1100-1199/1194.Tournament Winners/README.md index e8dbfbe109255..675daf4c633df 100644 --- a/solution/1100-1199/1194.Tournament Winners/README.md +++ b/solution/1100-1199/1194.Tournament Winners/README.md @@ -88,12 +88,10 @@ Players 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -129,3 +127,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1100-1199/1194.Tournament Winners/README_EN.md b/solution/1100-1199/1194.Tournament Winners/README_EN.md index 3981f34c86648..4c05667416b28 100644 --- a/solution/1100-1199/1194.Tournament Winners/README_EN.md +++ b/solution/1100-1199/1194.Tournament Winners/README_EN.md @@ -86,9 +86,9 @@ Matches table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -125,3 +125,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1100-1199/1195.Fizz Buzz Multithreaded/README.md b/solution/1100-1199/1195.Fizz Buzz Multithreaded/README.md index 1635dbef80211..a6bc83b0ff8b4 100644 --- a/solution/1100-1199/1195.Fizz Buzz Multithreaded/README.md +++ b/solution/1100-1199/1195.Fizz Buzz Multithreaded/README.md @@ -48,22 +48,10 @@ class FizzBuzz { ## 解法 - +### 方法一 -### **Python3** - - - -```python - -``` - -### **Java** - - - ```java class FizzBuzz { private int n; @@ -127,8 +115,6 @@ class FizzBuzz { } ``` -### **C++** - ```cpp class FizzBuzz { private: @@ -186,10 +172,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1195.Fizz Buzz Multithreaded/README_EN.md b/solution/1100-1199/1195.Fizz Buzz Multithreaded/README_EN.md index 49c03622058e7..618376c3946c4 100644 --- a/solution/1100-1199/1195.Fizz Buzz Multithreaded/README_EN.md +++ b/solution/1100-1199/1195.Fizz Buzz Multithreaded/README_EN.md @@ -58,15 +58,9 @@ ## Solutions - - -### **Python3** +### Solution 1 -```python - -``` - -### **Java** + ```java class FizzBuzz { @@ -131,8 +125,6 @@ class FizzBuzz { } ``` -### **C++** - ```cpp class FizzBuzz { private: @@ -140,13 +132,14 @@ private: atomic index; int n; + // 这里主要运用到了C++11中的RAII锁(lock_guard)的知识。 + // 需要强调的一点是,在进入循环后,要时刻不忘加入index <= n的逻辑 public: FizzBuzz(int n) { this->n = n; index = 1; } - // printFizz() outputs "fizz". void fizz(function printFizz) { while (index <= n) { std::lock_guard lk(mtx); @@ -157,7 +150,6 @@ public: } } - // printBuzz() outputs "buzz". void buzz(function printBuzz) { while (index <= n) { std::lock_guard lk(mtx); @@ -168,7 +160,6 @@ public: } } - // printFizzBuzz() outputs "fizzbuzz". void fizzbuzz(function printFizzBuzz) { while (index <= n) { std::lock_guard lk(mtx); @@ -179,7 +170,6 @@ public: } } - // printNumber(x) outputs "x", where x is an integer. void number(function printNumber) { while (index <= n) { std::lock_guard lk(mtx); @@ -192,10 +182,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1196.How Many Apples Can You Put into the Basket/README.md b/solution/1100-1199/1196.How Many Apples Can You Put into the Basket/README.md index f34053ce25d96..b2420d1f41584 100644 --- a/solution/1100-1199/1196.How Many Apples Can You Put into the Basket/README.md +++ b/solution/1100-1199/1196.How Many Apples Can You Put into the Basket/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 要使得苹果数量最多,那么就要使得苹果的重量尽可能的小,因此我们可以对苹果的重量进行排序,然后从小到大依次放入篮子中,直到篮子的重量超过 $5000$ 为止,返回此时放入篮子的苹果数量。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def maxNumberOfApples(self, weight: List[int]) -> int: @@ -67,10 +61,6 @@ class Solution: return len(weight) ``` -### **Java** - - - ```java class Solution { public int maxNumberOfApples(int[] weight) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +94,6 @@ public: }; ``` -### **Go** - ```go func maxNumberOfApples(weight []int) int { sort.Ints(weight) @@ -122,8 +108,6 @@ func maxNumberOfApples(weight []int) int { } ``` -### **TypeScript** - ```ts function maxNumberOfApples(weight: number[]): number { weight.sort((a, b) => a - b); @@ -138,10 +122,6 @@ function maxNumberOfApples(weight: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1196.How Many Apples Can You Put into the Basket/README_EN.md b/solution/1100-1199/1196.How Many Apples Can You Put into the Basket/README_EN.md index c0d86f0e16ff5..219bae2c78772 100644 --- a/solution/1100-1199/1196.How Many Apples Can You Put into the Basket/README_EN.md +++ b/solution/1100-1199/1196.How Many Apples Can You Put into the Basket/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Greedy Algorithm** +### Solution 1: Greedy Algorithm To maximize the number of apples, we should try to minimize the weight of the apples. Therefore, we can sort the weights of the apples, and then put them into the basket in ascending order until the weight of the basket exceeds $5000$. We then return the number of apples in the basket at this point. @@ -45,8 +45,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def maxNumberOfApples(self, weight: List[int]) -> int: @@ -59,8 +57,6 @@ class Solution: return len(weight) ``` -### **Java** - ```java class Solution { public int maxNumberOfApples(int[] weight) { @@ -77,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +90,6 @@ public: }; ``` -### **Go** - ```go func maxNumberOfApples(weight []int) int { sort.Ints(weight) @@ -112,8 +104,6 @@ func maxNumberOfApples(weight []int) int { } ``` -### **TypeScript** - ```ts function maxNumberOfApples(weight: number[]): number { weight.sort((a, b) => a - b); @@ -128,10 +118,6 @@ function maxNumberOfApples(weight: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1197.Minimum Knight Moves/README.md b/solution/1100-1199/1197.Minimum Knight Moves/README.md index a5720c05fd629..fc458ad3961a7 100644 --- a/solution/1100-1199/1197.Minimum Knight Moves/README.md +++ b/solution/1100-1199/1197.Minimum Knight Moves/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS BFS 最短路模型。本题搜索空间不大,可以直接使用朴素 BFS,以下题解中还提供了双向 BFS 的题解代码,仅供参考。 @@ -60,10 +58,6 @@ BFS 最短路模型。本题搜索空间不大,可以直接使用朴素 BFS, -### **Python3** - - - ```python class Solution: def minKnightMoves(self, x: int, y: int) -> int: @@ -85,49 +79,6 @@ class Solution: return -1 ``` -双向 BFS: - -```python -class Solution: - def minKnightMoves(self, x: int, y: int) -> int: - def extend(m1, m2, q): - for _ in range(len(q)): - i, j = q.popleft() - step = m1[(i, j)] - for a, b in ( - (-2, 1), - (-1, 2), - (1, 2), - (2, 1), - (2, -1), - (1, -2), - (-1, -2), - (-2, -1), - ): - x, y = i + a, j + b - if (x, y) in m1: - continue - if (x, y) in m2: - return step + 1 + m2[(x, y)] - q.append((x, y)) - m1[(x, y)] = step + 1 - return -1 - - if (x, y) == (0, 0): - return 0 - q1, q2 = deque([(0, 0)]), deque([(x, y)]) - m1, m2 = {(0, 0): 0}, {(x, y): 0} - while q1 and q2: - t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) - if t != -1: - return t - return -1 -``` - -### **Java** - - - ```java class Solution { public int minKnightMoves(int x, int y) { @@ -161,60 +112,6 @@ class Solution { } ``` -双向 BFS: - -```java -class Solution { - private int n = 700; - - public int minKnightMoves(int x, int y) { - if (x == 0 && y == 0) { - return 0; - } - x += 310; - y += 310; - Map m1 = new HashMap<>(); - Map m2 = new HashMap<>(); - m1.put(310 * n + 310, 0); - m2.put(x * n + y, 0); - Queue q1 = new ArrayDeque<>(); - Queue q2 = new ArrayDeque<>(); - q1.offer(new int[] {310, 310}); - q2.offer(new int[] {x, y}); - while (!q1.isEmpty() && !q2.isEmpty()) { - int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); - if (t != -1) { - return t; - } - } - return -1; - } - - private int extend(Map m1, Map m2, Queue q) { - int[][] dirs = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; - for (int k = q.size(); k > 0; --k) { - int[] p = q.poll(); - int step = m1.get(p[0] * n + p[1]); - for (int[] dir : dirs) { - int x = p[0] + dir[0]; - int y = p[1] + dir[1]; - if (m1.containsKey(x * n + y)) { - continue; - } - if (m2.containsKey(x * n + y)) { - return step + 1 + m2.get(x * n + y); - } - m1.put(x * n + y, step + 1); - q.offer(new int[] {x, y}); - } - } - return -1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -247,56 +144,37 @@ public: }; ``` -双向 BFS: - -```cpp -typedef pair PII; - -class Solution { -public: - int n = 700; - - int minKnightMoves(int x, int y) { - if (x == 0 && y == 0) return 0; - x += 310; - y += 310; - unordered_map m1; - unordered_map m2; - m1[310 * n + 310] = 0; - m2[x * n + y] = 0; - queue q1; - queue q2; - q1.push({310, 310}); - q2.push({x, y}); - while (!q1.empty() && !q2.empty()) { - int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); - if (t != -1) return t; - } - return -1; - } - - int extend(unordered_map& m1, unordered_map& m2, queue& q) { - vector> dirs = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; - for (int k = q.size(); k > 0; --k) { - auto p = q.front(); - q.pop(); - int i = p.first, j = p.second; - int step = m1[i * n + j]; - for (auto& dir : dirs) { - int x = i + dir[0], y = j + dir[1]; - if (m1.count(x * n + y)) continue; - if (m2.count(x * n + y)) return step + 1 + m2[x * n + y]; - m1[x * n + y] = step + 1; - q.push({x, y}); - } - } - return -1; - } -}; +```go +func minKnightMoves(x int, y int) int { + x, y = x+310, y+310 + ans := 0 + q := [][]int{{310, 310}} + vis := make([][]bool, 700) + for i := range vis { + vis[i] = make([]bool, 700) + } + dirs := [][]int{{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}} + for len(q) > 0 { + for k := len(q); k > 0; k-- { + p := q[0] + q = q[1:] + if p[0] == x && p[1] == y { + return ans + } + for _, dir := range dirs { + c, d := p[0]+dir[0], p[1]+dir[1] + if !vis[c][d] { + vis[c][d] = true + q = append(q, []int{c, d}) + } + } + } + ans++ + } + return -1 +} ``` -### **Rust** - ```rust use std::collections::VecDeque; @@ -369,7 +247,189 @@ impl Solution { } ``` -双向 BFS: + + +### 方法二 + + + +```python +class Solution: + def minKnightMoves(self, x: int, y: int) -> int: + def extend(m1, m2, q): + for _ in range(len(q)): + i, j = q.popleft() + step = m1[(i, j)] + for a, b in ( + (-2, 1), + (-1, 2), + (1, 2), + (2, 1), + (2, -1), + (1, -2), + (-1, -2), + (-2, -1), + ): + x, y = i + a, j + b + if (x, y) in m1: + continue + if (x, y) in m2: + return step + 1 + m2[(x, y)] + q.append((x, y)) + m1[(x, y)] = step + 1 + return -1 + + if (x, y) == (0, 0): + return 0 + q1, q2 = deque([(0, 0)]), deque([(x, y)]) + m1, m2 = {(0, 0): 0}, {(x, y): 0} + while q1 and q2: + t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) + if t != -1: + return t + return -1 +``` + +```java +class Solution { + private int n = 700; + + public int minKnightMoves(int x, int y) { + if (x == 0 && y == 0) { + return 0; + } + x += 310; + y += 310; + Map m1 = new HashMap<>(); + Map m2 = new HashMap<>(); + m1.put(310 * n + 310, 0); + m2.put(x * n + y, 0); + Queue q1 = new ArrayDeque<>(); + Queue q2 = new ArrayDeque<>(); + q1.offer(new int[] {310, 310}); + q2.offer(new int[] {x, y}); + while (!q1.isEmpty() && !q2.isEmpty()) { + int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); + if (t != -1) { + return t; + } + } + return -1; + } + + private int extend(Map m1, Map m2, Queue q) { + int[][] dirs = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; + for (int k = q.size(); k > 0; --k) { + int[] p = q.poll(); + int step = m1.get(p[0] * n + p[1]); + for (int[] dir : dirs) { + int x = p[0] + dir[0]; + int y = p[1] + dir[1]; + if (m1.containsKey(x * n + y)) { + continue; + } + if (m2.containsKey(x * n + y)) { + return step + 1 + m2.get(x * n + y); + } + m1.put(x * n + y, step + 1); + q.offer(new int[] {x, y}); + } + } + return -1; + } +} +``` + +```cpp +typedef pair PII; + +class Solution { +public: + int n = 700; + + int minKnightMoves(int x, int y) { + if (x == 0 && y == 0) return 0; + x += 310; + y += 310; + unordered_map m1; + unordered_map m2; + m1[310 * n + 310] = 0; + m2[x * n + y] = 0; + queue q1; + queue q2; + q1.push({310, 310}); + q2.push({x, y}); + while (!q1.empty() && !q2.empty()) { + int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); + if (t != -1) return t; + } + return -1; + } + + int extend(unordered_map& m1, unordered_map& m2, queue& q) { + vector> dirs = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; + for (int k = q.size(); k > 0; --k) { + auto p = q.front(); + q.pop(); + int i = p.first, j = p.second; + int step = m1[i * n + j]; + for (auto& dir : dirs) { + int x = i + dir[0], y = j + dir[1]; + if (m1.count(x * n + y)) continue; + if (m2.count(x * n + y)) return step + 1 + m2[x * n + y]; + m1[x * n + y] = step + 1; + q.push({x, y}); + } + } + return -1; + } +}; +``` + +```go +func minKnightMoves(x int, y int) int { + if x == 0 && y == 0 { + return 0 + } + n := 700 + x, y = x+310, y+310 + q1, q2 := []int{310*700 + 310}, []int{x*n + y} + m1, m2 := map[int]int{310*700 + 310: 0}, map[int]int{x*n + y: 0} + dirs := [][]int{{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}} + extend := func() int { + for k := len(q1); k > 0; k-- { + p := q1[0] + q1 = q1[1:] + i, j := p/n, p%n + step := m1[i*n+j] + for _, dir := range dirs { + x, y := i+dir[0], j+dir[1] + t := x*n + y + if _, ok := m1[t]; ok { + continue + } + if v, ok := m2[t]; ok { + return step + 1 + v + } + m1[t] = step + 1 + q1 = append(q1, t) + } + } + return -1 + } + for len(q1) > 0 && len(q2) > 0 { + if len(q1) <= len(q2) { + q1, q2 = q2, q1 + m1, m2 = m2, m1 + } + t := extend() + if t != -1 { + return t + } + } + return -1 +} +``` ```rust use std::collections::VecDeque; @@ -468,90 +528,6 @@ impl Solution { } ``` -### **Go** - -```go -func minKnightMoves(x int, y int) int { - x, y = x+310, y+310 - ans := 0 - q := [][]int{{310, 310}} - vis := make([][]bool, 700) - for i := range vis { - vis[i] = make([]bool, 700) - } - dirs := [][]int{{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}} - for len(q) > 0 { - for k := len(q); k > 0; k-- { - p := q[0] - q = q[1:] - if p[0] == x && p[1] == y { - return ans - } - for _, dir := range dirs { - c, d := p[0]+dir[0], p[1]+dir[1] - if !vis[c][d] { - vis[c][d] = true - q = append(q, []int{c, d}) - } - } - } - ans++ - } - return -1 -} -``` - -双向 BFS: - -```go -func minKnightMoves(x int, y int) int { - if x == 0 && y == 0 { - return 0 - } - n := 700 - x, y = x+310, y+310 - q1, q2 := []int{310*700 + 310}, []int{x*n + y} - m1, m2 := map[int]int{310*700 + 310: 0}, map[int]int{x*n + y: 0} - dirs := [][]int{{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}} - extend := func() int { - for k := len(q1); k > 0; k-- { - p := q1[0] - q1 = q1[1:] - i, j := p/n, p%n - step := m1[i*n+j] - for _, dir := range dirs { - x, y := i+dir[0], j+dir[1] - t := x*n + y - if _, ok := m1[t]; ok { - continue - } - if v, ok := m2[t]; ok { - return step + 1 + v - } - m1[t] = step + 1 - q1 = append(q1, t) - } - } - return -1 - } - for len(q1) > 0 && len(q2) > 0 { - if len(q1) <= len(q2) { - q1, q2 = q2, q1 - m1, m2 = m2, m1 - } - t := extend() - if t != -1 { - return t - } - } - return -1 -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1197.Minimum Knight Moves/README_EN.md b/solution/1100-1199/1197.Minimum Knight Moves/README_EN.md index 3104605e6f644..b1508e7f2103d 100644 --- a/solution/1100-1199/1197.Minimum Knight Moves/README_EN.md +++ b/solution/1100-1199/1197.Minimum Knight Moves/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: BFS** +### Solution 1: BFS This problem can be solved using the BFS shortest path model. The search space for this problem is not large, so we can directly use the naive BFS. The solution below also provides the code for bidirectional BFS for reference. @@ -50,8 +50,6 @@ Bidirectional BFS is a common optimization method for BFS. The main implementati -### **Python3** - ```python class Solution: def minKnightMoves(self, x: int, y: int) -> int: @@ -73,47 +71,6 @@ class Solution: return -1 ``` -Two-end BFS: - -```python -class Solution: - def minKnightMoves(self, x: int, y: int) -> int: - def extend(m1, m2, q): - for _ in range(len(q)): - i, j = q.popleft() - step = m1[(i, j)] - for a, b in ( - (-2, 1), - (-1, 2), - (1, 2), - (2, 1), - (2, -1), - (1, -2), - (-1, -2), - (-2, -1), - ): - x, y = i + a, j + b - if (x, y) in m1: - continue - if (x, y) in m2: - return step + 1 + m2[(x, y)] - q.append((x, y)) - m1[(x, y)] = step + 1 - return -1 - - if (x, y) == (0, 0): - return 0 - q1, q2 = deque([(0, 0)]), deque([(x, y)]) - m1, m2 = {(0, 0): 0}, {(x, y): 0} - while q1 and q2: - t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) - if t != -1: - return t - return -1 -``` - -### **Java** - ```java class Solution { public int minKnightMoves(int x, int y) { @@ -147,60 +104,6 @@ class Solution { } ``` -Two-end BFS: - -```java -class Solution { - private int n = 700; - - public int minKnightMoves(int x, int y) { - if (x == 0 && y == 0) { - return 0; - } - x += 310; - y += 310; - Map m1 = new HashMap<>(); - Map m2 = new HashMap<>(); - m1.put(310 * n + 310, 0); - m2.put(x * n + y, 0); - Queue q1 = new ArrayDeque<>(); - Queue q2 = new ArrayDeque<>(); - q1.offer(new int[] {310, 310}); - q2.offer(new int[] {x, y}); - while (!q1.isEmpty() && !q2.isEmpty()) { - int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); - if (t != -1) { - return t; - } - } - return -1; - } - - private int extend(Map m1, Map m2, Queue q) { - int[][] dirs = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; - for (int k = q.size(); k > 0; --k) { - int[] p = q.poll(); - int step = m1.get(p[0] * n + p[1]); - for (int[] dir : dirs) { - int x = p[0] + dir[0]; - int y = p[1] + dir[1]; - if (m1.containsKey(x * n + y)) { - continue; - } - if (m2.containsKey(x * n + y)) { - return step + 1 + m2.get(x * n + y); - } - m1.put(x * n + y, step + 1); - q.offer(new int[] {x, y}); - } - } - return -1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -233,56 +136,37 @@ public: }; ``` -Two-end BFS: - -```cpp -typedef pair PII; - -class Solution { -public: - int n = 700; - - int minKnightMoves(int x, int y) { - if (x == 0 && y == 0) return 0; - x += 310; - y += 310; - unordered_map m1; - unordered_map m2; - m1[310 * n + 310] = 0; - m2[x * n + y] = 0; - queue q1; - queue q2; - q1.push({310, 310}); - q2.push({x, y}); - while (!q1.empty() && !q2.empty()) { - int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); - if (t != -1) return t; - } - return -1; - } - - int extend(unordered_map& m1, unordered_map& m2, queue& q) { - vector> dirs = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; - for (int k = q.size(); k > 0; --k) { - auto p = q.front(); - q.pop(); - int i = p.first, j = p.second; - int step = m1[i * n + j]; - for (auto& dir : dirs) { - int x = i + dir[0], y = j + dir[1]; - if (m1.count(x * n + y)) continue; - if (m2.count(x * n + y)) return step + 1 + m2[x * n + y]; - m1[x * n + y] = step + 1; - q.push({x, y}); - } - } - return -1; - } -}; +```go +func minKnightMoves(x int, y int) int { + x, y = x+310, y+310 + ans := 0 + q := [][]int{{310, 310}} + vis := make([][]bool, 700) + for i := range vis { + vis[i] = make([]bool, 700) + } + dirs := [][]int{{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}} + for len(q) > 0 { + for k := len(q); k > 0; k-- { + p := q[0] + q = q[1:] + if p[0] == x && p[1] == y { + return ans + } + for _, dir := range dirs { + c, d := p[0]+dir[0], p[1]+dir[1] + if !vis[c][d] { + vis[c][d] = true + q = append(q, []int{c, d}) + } + } + } + ans++ + } + return -1 +} ``` -### **Rust** - ```rust use std::collections::VecDeque; @@ -355,7 +239,189 @@ impl Solution { } ``` -Two-end BFS: + + +### Solution 2 + + + +```python +class Solution: + def minKnightMoves(self, x: int, y: int) -> int: + def extend(m1, m2, q): + for _ in range(len(q)): + i, j = q.popleft() + step = m1[(i, j)] + for a, b in ( + (-2, 1), + (-1, 2), + (1, 2), + (2, 1), + (2, -1), + (1, -2), + (-1, -2), + (-2, -1), + ): + x, y = i + a, j + b + if (x, y) in m1: + continue + if (x, y) in m2: + return step + 1 + m2[(x, y)] + q.append((x, y)) + m1[(x, y)] = step + 1 + return -1 + + if (x, y) == (0, 0): + return 0 + q1, q2 = deque([(0, 0)]), deque([(x, y)]) + m1, m2 = {(0, 0): 0}, {(x, y): 0} + while q1 and q2: + t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) + if t != -1: + return t + return -1 +``` + +```java +class Solution { + private int n = 700; + + public int minKnightMoves(int x, int y) { + if (x == 0 && y == 0) { + return 0; + } + x += 310; + y += 310; + Map m1 = new HashMap<>(); + Map m2 = new HashMap<>(); + m1.put(310 * n + 310, 0); + m2.put(x * n + y, 0); + Queue q1 = new ArrayDeque<>(); + Queue q2 = new ArrayDeque<>(); + q1.offer(new int[] {310, 310}); + q2.offer(new int[] {x, y}); + while (!q1.isEmpty() && !q2.isEmpty()) { + int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); + if (t != -1) { + return t; + } + } + return -1; + } + + private int extend(Map m1, Map m2, Queue q) { + int[][] dirs = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; + for (int k = q.size(); k > 0; --k) { + int[] p = q.poll(); + int step = m1.get(p[0] * n + p[1]); + for (int[] dir : dirs) { + int x = p[0] + dir[0]; + int y = p[1] + dir[1]; + if (m1.containsKey(x * n + y)) { + continue; + } + if (m2.containsKey(x * n + y)) { + return step + 1 + m2.get(x * n + y); + } + m1.put(x * n + y, step + 1); + q.offer(new int[] {x, y}); + } + } + return -1; + } +} +``` + +```cpp +typedef pair PII; + +class Solution { +public: + int n = 700; + + int minKnightMoves(int x, int y) { + if (x == 0 && y == 0) return 0; + x += 310; + y += 310; + unordered_map m1; + unordered_map m2; + m1[310 * n + 310] = 0; + m2[x * n + y] = 0; + queue q1; + queue q2; + q1.push({310, 310}); + q2.push({x, y}); + while (!q1.empty() && !q2.empty()) { + int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2); + if (t != -1) return t; + } + return -1; + } + + int extend(unordered_map& m1, unordered_map& m2, queue& q) { + vector> dirs = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}}; + for (int k = q.size(); k > 0; --k) { + auto p = q.front(); + q.pop(); + int i = p.first, j = p.second; + int step = m1[i * n + j]; + for (auto& dir : dirs) { + int x = i + dir[0], y = j + dir[1]; + if (m1.count(x * n + y)) continue; + if (m2.count(x * n + y)) return step + 1 + m2[x * n + y]; + m1[x * n + y] = step + 1; + q.push({x, y}); + } + } + return -1; + } +}; +``` + +```go +func minKnightMoves(x int, y int) int { + if x == 0 && y == 0 { + return 0 + } + n := 700 + x, y = x+310, y+310 + q1, q2 := []int{310*700 + 310}, []int{x*n + y} + m1, m2 := map[int]int{310*700 + 310: 0}, map[int]int{x*n + y: 0} + dirs := [][]int{{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}} + extend := func() int { + for k := len(q1); k > 0; k-- { + p := q1[0] + q1 = q1[1:] + i, j := p/n, p%n + step := m1[i*n+j] + for _, dir := range dirs { + x, y := i+dir[0], j+dir[1] + t := x*n + y + if _, ok := m1[t]; ok { + continue + } + if v, ok := m2[t]; ok { + return step + 1 + v + } + m1[t] = step + 1 + q1 = append(q1, t) + } + } + return -1 + } + for len(q1) > 0 && len(q2) > 0 { + if len(q1) <= len(q2) { + q1, q2 = q2, q1 + m1, m2 = m2, m1 + } + t := extend() + if t != -1 { + return t + } + } + return -1 +} +``` ```rust use std::collections::VecDeque; @@ -454,90 +520,6 @@ impl Solution { } ``` -### **Go** - -Two-end BFS: - -```go -func minKnightMoves(x int, y int) int { - x, y = x+310, y+310 - ans := 0 - q := [][]int{{310, 310}} - vis := make([][]bool, 700) - for i := range vis { - vis[i] = make([]bool, 700) - } - dirs := [][]int{{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}} - for len(q) > 0 { - for k := len(q); k > 0; k-- { - p := q[0] - q = q[1:] - if p[0] == x && p[1] == y { - return ans - } - for _, dir := range dirs { - c, d := p[0]+dir[0], p[1]+dir[1] - if !vis[c][d] { - vis[c][d] = true - q = append(q, []int{c, d}) - } - } - } - ans++ - } - return -1 -} -``` - -```go -func minKnightMoves(x int, y int) int { - if x == 0 && y == 0 { - return 0 - } - n := 700 - x, y = x+310, y+310 - q1, q2 := []int{310*700 + 310}, []int{x*n + y} - m1, m2 := map[int]int{310*700 + 310: 0}, map[int]int{x*n + y: 0} - dirs := [][]int{{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}} - extend := func() int { - for k := len(q1); k > 0; k-- { - p := q1[0] - q1 = q1[1:] - i, j := p/n, p%n - step := m1[i*n+j] - for _, dir := range dirs { - x, y := i+dir[0], j+dir[1] - t := x*n + y - if _, ok := m1[t]; ok { - continue - } - if v, ok := m2[t]; ok { - return step + 1 + v - } - m1[t] = step + 1 - q1 = append(q1, t) - } - } - return -1 - } - for len(q1) > 0 && len(q2) > 0 { - if len(q1) <= len(q2) { - q1, q2 = q2, q1 - m1, m2 = m2, m1 - } - t := extend() - if t != -1 { - return t - } - } - return -1 -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1198.Find Smallest Common Element in All Rows/README.md b/solution/1100-1199/1198.Find Smallest Common Element in All Rows/README.md index 3ef9bcac5f6b9..9a167bd120abc 100644 --- a/solution/1100-1199/1198.Find Smallest Common Element in All Rows/README.md +++ b/solution/1100-1199/1198.Find Smallest Common Element in All Rows/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们用一个长度为 $10001$ 的数组 $cnt$ 统计每个数出现的次数。顺序遍历矩阵中的每个数,将其出现次数加一。当某个数的出现次数等于矩阵的行数时,说明该数在每一行都出现过,即为最小公共元素,返回该数即可。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def smallestCommonElement(self, mat: List[List[int]]) -> int: @@ -68,10 +62,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int smallestCommonElement(int[][] mat) { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func smallestCommonElement(mat [][]int) int { cnt := [10001]int{} @@ -124,8 +110,6 @@ func smallestCommonElement(mat [][]int) int { } ``` -### **TypeScript** - ```ts function smallestCommonElement(mat: number[][]): number { const cnt: number[] = new Array(10001).fill(0); @@ -140,10 +124,6 @@ function smallestCommonElement(mat: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1198.Find Smallest Common Element in All Rows/README_EN.md b/solution/1100-1199/1198.Find Smallest Common Element in All Rows/README_EN.md index 7f1927499be3c..498dd74f62c97 100644 --- a/solution/1100-1199/1198.Find Smallest Common Element in All Rows/README_EN.md +++ b/solution/1100-1199/1198.Find Smallest Common Element in All Rows/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We use an array $cnt$ of length $10001$ to count the frequency of each number. We sequentially traverse each number in the matrix and increment its frequency. When the frequency of a number equals the number of rows in the matrix, it means that this number appears in each row, and thus it is the smallest common element. We return this number. @@ -46,8 +46,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(10^4)$. H -### **Python3** - ```python class Solution: def smallestCommonElement(self, mat: List[List[int]]) -> int: @@ -60,8 +58,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int smallestCommonElement(int[][] mat) { @@ -78,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +91,6 @@ public: }; ``` -### **Go** - ```go func smallestCommonElement(mat [][]int) int { cnt := [10001]int{} @@ -114,8 +106,6 @@ func smallestCommonElement(mat [][]int) int { } ``` -### **TypeScript** - ```ts function smallestCommonElement(mat: number[][]): number { const cnt: number[] = new Array(10001).fill(0); @@ -130,10 +120,6 @@ function smallestCommonElement(mat: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1199.Minimum Time to Build Blocks/README.md b/solution/1100-1199/1199.Minimum Time to Build Blocks/README.md index d6892cb7b3be2..4a72f65f65fd2 100644 --- a/solution/1100-1199/1199.Minimum Time to Build Blocks/README.md +++ b/solution/1100-1199/1199.Minimum Time to Build Blocks/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列(小根堆)** +### 方法一:贪心 + 优先队列(小根堆) 先考虑只有一个街区的情况,此时不需要分裂工人,直接让他去建造街区,时间花费为 $block[0]$。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def minBuildTime(self, blocks: List[int], split: int) -> int: @@ -88,10 +82,6 @@ class Solution: return blocks[0] ``` -### **Java** - - - ```java class Solution { public int minBuildTime(int[] blocks, int split) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func minBuildTime(blocks []int, split int) int { q := hp{} @@ -153,8 +139,6 @@ func (h *hp) Pop() any { } ``` -### **TypeScript** - ```ts function minBuildTime(blocks: number[], split: number): number { const pq = new MinPriorityQueue(); @@ -169,8 +153,6 @@ function minBuildTime(blocks: number[], split: number): number { } ``` -### **Rust** - ```rust use std::collections::BinaryHeap; use std::cmp::Reverse; @@ -194,10 +176,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1100-1199/1199.Minimum Time to Build Blocks/README_EN.md b/solution/1100-1199/1199.Minimum Time to Build Blocks/README_EN.md index 23ae3c6f43ec3..282c9f9ee2290 100644 --- a/solution/1100-1199/1199.Minimum Time to Build Blocks/README_EN.md +++ b/solution/1100-1199/1199.Minimum Time to Build Blocks/README_EN.md @@ -52,7 +52,7 @@ The cost is 1 + max(3, 1 + max(1, 2)) = 4. ## Solutions -**Solution 1: Greedy + Priority Queue (Min Heap)** +### Solution 1: Greedy + Priority Queue (Min Heap) First, consider the case where there is only one block. In this case, there is no need to split the worker, just let him build the block directly. The time cost is $block[0]$. @@ -68,8 +68,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def minBuildTime(self, blocks: List[int], split: int) -> int: @@ -80,8 +78,6 @@ class Solution: return blocks[0] ``` -### **Java** - ```java class Solution { public int minBuildTime(int[] blocks, int split) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func minBuildTime(blocks []int, split int) int { q := hp{} @@ -143,8 +135,6 @@ func (h *hp) Pop() any { } ``` -### **TypeScript** - ```ts function minBuildTime(blocks: number[], split: number): number { const pq = new MinPriorityQueue(); @@ -159,8 +149,6 @@ function minBuildTime(blocks: number[], split: number): number { } ``` -### **Rust** - ```rust use std::collections::BinaryHeap; use std::cmp::Reverse; @@ -184,10 +172,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1200.Minimum Absolute Difference/README.md b/solution/1200-1299/1200.Minimum Absolute Difference/README.md index f307ada64370b..fdcd1c9959db7 100644 --- a/solution/1200-1299/1200.Minimum Absolute Difference/README.md +++ b/solution/1200-1299/1200.Minimum Absolute Difference/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 根据题目描述,我们需要找出数组 $arr$ 中任意两个元素的最小绝对差,因此我们可以先对数组 $arr$ 排序,随后遍历相邻元素,得到最小绝对差 $mi$。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: @@ -76,10 +70,6 @@ class Solution: return [[a, b] for a, b in pairwise(arr) if b - a == mi] ``` -### **Java** - - - ```java class Solution { public List> minimumAbsDifference(int[] arr) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func minimumAbsDifference(arr []int) (ans [][]int) { sort.Ints(arr) @@ -144,8 +130,6 @@ func minimumAbsDifference(arr []int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function minimumAbsDifference(arr: number[]): number[][] { arr.sort((a, b) => a - b); @@ -164,10 +148,6 @@ function minimumAbsDifference(arr: number[]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1200.Minimum Absolute Difference/README_EN.md b/solution/1200-1299/1200.Minimum Absolute Difference/README_EN.md index 9332b076cb1b0..1e856370f9662 100644 --- a/solution/1200-1299/1200.Minimum Absolute Difference/README_EN.md +++ b/solution/1200-1299/1200.Minimum Absolute Difference/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting According to the problem description, we need to find the minimum absolute difference between any two elements in the array $arr$. Therefore, we can first sort the array $arr$, then traverse the adjacent elements to get the minimum absolute difference $mi$. @@ -56,8 +56,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: @@ -66,8 +64,6 @@ class Solution: return [[a, b] for a, b in pairwise(arr) if b - a == mi] ``` -### **Java** - ```java class Solution { public List> minimumAbsDifference(int[] arr) { @@ -88,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +105,6 @@ public: }; ``` -### **Go** - ```go func minimumAbsDifference(arr []int) (ans [][]int) { sort.Ints(arr) @@ -132,8 +124,6 @@ func minimumAbsDifference(arr []int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function minimumAbsDifference(arr: number[]): number[][] { arr.sort((a, b) => a - b); @@ -152,10 +142,6 @@ function minimumAbsDifference(arr: number[]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1201.Ugly Number III/README.md b/solution/1200-1299/1201.Ugly Number III/README.md index bb89985e73c8b..ff5b1d86bb1c2 100644 --- a/solution/1200-1299/1201.Ugly Number III/README.md +++ b/solution/1200-1299/1201.Ugly Number III/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:二分查找 + 容斥原理** +### 方法一:二分查找 + 容斥原理 我们可以将题目转换为:找到最小的正整数 $x$,使得小于等于 $x$ 的丑数个数恰好为 $n$ 个。 @@ -74,10 +72,6 @@ $$ -### **Python3** - - - ```python class Solution: def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: @@ -104,10 +98,6 @@ class Solution: return l ``` -### **Java** - - - ```java class Solution { public int nthUglyNumber(int n, int a, int b, int c) { @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go func nthUglyNumber(n int, a int, b int, c int) int { ab, bc, ac := lcm(a, b), lcm(b, c), lcm(a, c) @@ -199,8 +185,6 @@ func lcm(a, b int) int { } ``` -### **TypeScript** - ```ts function nthUglyNumber(n: number, a: number, b: number, c: number): number { const ab = lcm(BigInt(a), BigInt(b)); @@ -237,10 +221,6 @@ function lcm(a: bigint, b: bigint): bigint { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1201.Ugly Number III/README_EN.md b/solution/1200-1299/1201.Ugly Number III/README_EN.md index 0ba91f8c1470c..ec5352dd50269 100644 --- a/solution/1200-1299/1201.Ugly Number III/README_EN.md +++ b/solution/1200-1299/1201.Ugly Number III/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Binary Search + Inclusion-Exclusion Principle** +### Solution 1: Binary Search + Inclusion-Exclusion Principle We can transform the problem into: find the smallest positive integer $x$ such that the number of ugly numbers less than or equal to $x$ is exactly $n$. @@ -62,8 +62,6 @@ The time complexity is $O(\log m)$, where $m = 2 \times 10^9$. The space complex -### **Python3** - ```python class Solution: def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: @@ -90,8 +88,6 @@ class Solution: return l ``` -### **Java** - ```java class Solution { public int nthUglyNumber(int n, int a, int b, int c) { @@ -121,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +147,6 @@ public: }; ``` -### **Go** - ```go func nthUglyNumber(n int, a int, b int, c int) int { ab, bc, ac := lcm(a, b), lcm(b, c), lcm(a, c) @@ -183,8 +175,6 @@ func lcm(a, b int) int { } ``` -### **TypeScript** - ```ts function nthUglyNumber(n: number, a: number, b: number, c: number): number { const ab = lcm(BigInt(a), BigInt(b)); @@ -221,10 +211,6 @@ function lcm(a: bigint, b: bigint): bigint { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1202.Smallest String With Swaps/README.md b/solution/1200-1299/1202.Smallest String With Swaps/README.md index 528bc90618d31..4035ecc1ff2de 100644 --- a/solution/1200-1299/1202.Smallest String With Swaps/README.md +++ b/solution/1200-1299/1202.Smallest String With Swaps/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:并查集** +### 方法一:并查集 我们注意到,索引对具有传递性,即如果 $a$ 与 $b$ 可交换,而 $b$ 与 $c$ 可交换,那么 $a$ 与 $c$ 也可交换。因此,我们可以考虑使用并查集维护这些索引对的连通性,将属于同一个连通分量的字符按照字典序排序。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: @@ -91,10 +85,6 @@ class Solution: return "".join(d[find(i)].pop() for i in range(n)) ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -134,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,69 +158,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn smallest_string_with_swaps(s: String, pairs: Vec>) -> String { - let n = s.as_bytes().len(); - let s = s.as_bytes(); - let mut disjoint_set: Vec = vec![0; n]; - let mut str_vec: Vec> = vec![Vec::new(); n]; - let mut ret_str = String::new(); - - // Initialize the disjoint set - for i in 0..n { - disjoint_set[i] = i; - } - - // Union the pairs - for pair in pairs { - Self::union(pair[0] as usize, pair[1] as usize, &mut disjoint_set); - } - - // Initialize the return vector - for (i, c) in s.iter().enumerate() { - let p_c = Self::find(i, &mut disjoint_set); - str_vec[p_c].push(*c); - } - - // Sort the return vector in reverse order - for cur_vec in &mut str_vec { - cur_vec.sort(); - cur_vec.reverse(); - } - - // Construct the return string - for i in 0..n { - let index = Self::find(i, &mut disjoint_set); - ret_str.push(str_vec[index].last().unwrap().clone() as char); - str_vec[index].pop(); - } - - ret_str - } - - #[allow(dead_code)] - fn find(x: usize, d_set: &mut Vec) -> usize { - if d_set[x] != x { - d_set[x] = Self::find(d_set[x], d_set); - } - d_set[x] - } - - #[allow(dead_code)] - fn union(x: usize, y: usize, d_set: &mut Vec) { - let p_x = Self::find(x, d_set); - let p_y = Self::find(y, d_set); - d_set[p_x] = p_y; - } -} -``` - -### **Go** - ```go func smallestStringWithSwaps(s string, pairs [][]int) string { n := len(s) @@ -269,8 +194,6 @@ func smallestStringWithSwaps(s string, pairs [][]int) string { } ``` -### **TypeScript** - ```ts function smallestStringWithSwaps(s: string, pairs: number[][]): string { const n = s.length; @@ -299,10 +222,65 @@ function smallestStringWithSwaps(s: string, pairs: number[][]): string { } ``` -### **...** +```rust +impl Solution { + #[allow(dead_code)] + pub fn smallest_string_with_swaps(s: String, pairs: Vec>) -> String { + let n = s.as_bytes().len(); + let s = s.as_bytes(); + let mut disjoint_set: Vec = vec![0; n]; + let mut str_vec: Vec> = vec![Vec::new(); n]; + let mut ret_str = String::new(); -``` + // Initialize the disjoint set + for i in 0..n { + disjoint_set[i] = i; + } + + // Union the pairs + for pair in pairs { + Self::union(pair[0] as usize, pair[1] as usize, &mut disjoint_set); + } + + // Initialize the return vector + for (i, c) in s.iter().enumerate() { + let p_c = Self::find(i, &mut disjoint_set); + str_vec[p_c].push(*c); + } + + // Sort the return vector in reverse order + for cur_vec in &mut str_vec { + cur_vec.sort(); + cur_vec.reverse(); + } + + // Construct the return string + for i in 0..n { + let index = Self::find(i, &mut disjoint_set); + ret_str.push(str_vec[index].last().unwrap().clone() as char); + str_vec[index].pop(); + } + ret_str + } + + #[allow(dead_code)] + fn find(x: usize, d_set: &mut Vec) -> usize { + if d_set[x] != x { + d_set[x] = Self::find(d_set[x], d_set); + } + d_set[x] + } + + #[allow(dead_code)] + fn union(x: usize, y: usize, d_set: &mut Vec) { + let p_x = Self::find(x, d_set); + let p_y = Self::find(y, d_set); + d_set[p_x] = p_y; + } +} ``` + + diff --git a/solution/1200-1299/1202.Smallest String With Swaps/README_EN.md b/solution/1200-1299/1202.Smallest String With Swaps/README_EN.md index c5ccb31a51259..f877b9c2e6ceb 100644 --- a/solution/1200-1299/1202.Smallest String With Swaps/README_EN.md +++ b/solution/1200-1299/1202.Smallest String With Swaps/README_EN.md @@ -54,7 +54,7 @@ Swap s[0] and s[1], s = "abc" ## Solutions -**Solution 1: Union-Find** +### Solution 1: Union-Find We notice that the index pairs have transitivity, i.e., if $a$ and $b$ can be swapped, and $b$ and $c$ can be swapped, then $a$ and $c$ can also be swapped. Therefore, we can consider using a union-find data structure to maintain the connectivity of these index pairs, and sort the characters belonging to the same connected component in lexicographical order. @@ -64,8 +64,6 @@ The time complexity is $O(n \times \log n + m \times \alpha(m))$, and the space -### **Python3** - ```python class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: @@ -86,8 +84,6 @@ class Solution: return "".join(d[find(i)].pop() for i in range(n)) ``` -### **Java** - ```java class Solution { private int[] p; @@ -127,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,69 +157,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn smallest_string_with_swaps(s: String, pairs: Vec>) -> String { - let n = s.as_bytes().len(); - let s = s.as_bytes(); - let mut disjoint_set: Vec = vec![0; n]; - let mut str_vec: Vec> = vec![Vec::new(); n]; - let mut ret_str = String::new(); - - // Initialize the disjoint set - for i in 0..n { - disjoint_set[i] = i; - } - - // Union the pairs - for pair in pairs { - Self::union(pair[0] as usize, pair[1] as usize, &mut disjoint_set); - } - - // Initialize the return vector - for (i, c) in s.iter().enumerate() { - let p_c = Self::find(i, &mut disjoint_set); - str_vec[p_c].push(*c); - } - - // Sort the return vector in reverse order - for cur_vec in &mut str_vec { - cur_vec.sort(); - cur_vec.reverse(); - } - - // Construct the return string - for i in 0..n { - let index = Self::find(i, &mut disjoint_set); - ret_str.push(str_vec[index].last().unwrap().clone() as char); - str_vec[index].pop(); - } - - ret_str - } - - #[allow(dead_code)] - fn find(x: usize, d_set: &mut Vec) -> usize { - if d_set[x] != x { - d_set[x] = Self::find(d_set[x], d_set); - } - d_set[x] - } - - #[allow(dead_code)] - fn union(x: usize, y: usize, d_set: &mut Vec) { - let p_x = Self::find(x, d_set); - let p_y = Self::find(y, d_set); - d_set[p_x] = p_y; - } -} -``` - -### **Go** - ```go func smallestStringWithSwaps(s string, pairs [][]int) string { n := len(s) @@ -262,8 +193,6 @@ func smallestStringWithSwaps(s string, pairs [][]int) string { } ``` -### **TypeScript** - ```ts function smallestStringWithSwaps(s: string, pairs: number[][]): string { const n = s.length; @@ -292,10 +221,65 @@ function smallestStringWithSwaps(s: string, pairs: number[][]): string { } ``` -### **...** +```rust +impl Solution { + #[allow(dead_code)] + pub fn smallest_string_with_swaps(s: String, pairs: Vec>) -> String { + let n = s.as_bytes().len(); + let s = s.as_bytes(); + let mut disjoint_set: Vec = vec![0; n]; + let mut str_vec: Vec> = vec![Vec::new(); n]; + let mut ret_str = String::new(); -``` + // Initialize the disjoint set + for i in 0..n { + disjoint_set[i] = i; + } + + // Union the pairs + for pair in pairs { + Self::union(pair[0] as usize, pair[1] as usize, &mut disjoint_set); + } + // Initialize the return vector + for (i, c) in s.iter().enumerate() { + let p_c = Self::find(i, &mut disjoint_set); + str_vec[p_c].push(*c); + } + + // Sort the return vector in reverse order + for cur_vec in &mut str_vec { + cur_vec.sort(); + cur_vec.reverse(); + } + + // Construct the return string + for i in 0..n { + let index = Self::find(i, &mut disjoint_set); + ret_str.push(str_vec[index].last().unwrap().clone() as char); + str_vec[index].pop(); + } + + ret_str + } + + #[allow(dead_code)] + fn find(x: usize, d_set: &mut Vec) -> usize { + if d_set[x] != x { + d_set[x] = Self::find(d_set[x], d_set); + } + d_set[x] + } + + #[allow(dead_code)] + fn union(x: usize, y: usize, d_set: &mut Vec) { + let p_x = Self::find(x, d_set); + let p_y = Self::find(y, d_set); + d_set[p_x] = p_y; + } +} ``` + + diff --git a/solution/1200-1299/1203.Sort Items by Groups Respecting Dependencies/README.md b/solution/1200-1299/1203.Sort Items by Groups Respecting Dependencies/README.md index 2c13a2dec1775..b46e957426cc2 100644 --- a/solution/1200-1299/1203.Sort Items by Groups Respecting Dependencies/README.md +++ b/solution/1200-1299/1203.Sort Items by Groups Respecting Dependencies/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:拓扑排序** +### 方法一:拓扑排序 我们先遍历数组 $group$,对于每个项目,如果其不属于任何小组,则将其新建一个小组,编号为 $m$,并将 $m$ 的值加一。这样我们就能保证所有项目都属于某个小组了。然后,我们用一个数组 $groupItems$ 记录每个小组包含的项目,数组下标为小组编号,数组值为包含的项目列表。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def sortItems( @@ -122,10 +116,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] sortItems(int n, int m, int[] group, List> beforeItems) { @@ -197,8 +187,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -266,8 +254,6 @@ public: }; ``` -### **Go** - ```go func sortItems(n int, m int, group []int, beforeItems [][]int) []int { idx := m @@ -337,8 +323,6 @@ func sortItems(n int, m int, group []int, beforeItems [][]int) []int { } ``` -### **TypeScript** - ```ts function sortItems(n: number, m: number, group: number[], beforeItems: number[][]): number[] { let idx = m; @@ -401,10 +385,6 @@ function sortItems(n: number, m: number, group: number[], beforeItems: number[][ } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1203.Sort Items by Groups Respecting Dependencies/README_EN.md b/solution/1200-1299/1203.Sort Items by Groups Respecting Dependencies/README_EN.md index 4505b68851abd..070482fd193c6 100644 --- a/solution/1200-1299/1203.Sort Items by Groups Respecting Dependencies/README_EN.md +++ b/solution/1200-1299/1203.Sort Items by Groups Respecting Dependencies/README_EN.md @@ -48,7 +48,7 @@ ## Solutions -**Solution 1: Topological Sorting** +### Solution 1: Topological Sorting First, we traverse the array $group$. For each project, if it does not belong to any group, we create a new group for it with the ID $m$, and increment $m$. This ensures that all projects belong to some group. Then, we use an array $groupItems$ to record the projects contained in each group. The array index is the group ID, and the array value is the list of projects in the group. @@ -60,8 +60,6 @@ The time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, -### **Python3** - ```python class Solution: def sortItems( @@ -114,8 +112,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] sortItems(int n, int m, int[] group, List> beforeItems) { @@ -187,8 +183,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -256,8 +250,6 @@ public: }; ``` -### **Go** - ```go func sortItems(n int, m int, group []int, beforeItems [][]int) []int { idx := m @@ -327,8 +319,6 @@ func sortItems(n int, m int, group []int, beforeItems [][]int) []int { } ``` -### **TypeScript** - ```ts function sortItems(n: number, m: number, group: number[], beforeItems: number[][]): number[] { let idx = m; @@ -391,10 +381,6 @@ function sortItems(n: number, m: number, group: number[], beforeItems: number[][ } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1204.Last Person to Fit in the Bus/README.md b/solution/1200-1299/1204.Last Person to Fit in the Bus/README.md index 6033776507fe9..cf744914418b5 100644 --- a/solution/1200-1299/1204.Last Person to Fit in the Bus/README.md +++ b/solution/1200-1299/1204.Last Person to Fit in the Bus/README.md @@ -70,14 +70,10 @@ Queue 表 ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT a.person_name @@ -91,6 +87,12 @@ ORDER BY a.turn DESC LIMIT 1; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below WITH @@ -108,3 +110,5 @@ LIMIT 1; ``` + + diff --git a/solution/1200-1299/1204.Last Person to Fit in the Bus/README_EN.md b/solution/1200-1299/1204.Last Person to Fit in the Bus/README_EN.md index fefc742fa5996..cc1233ee245f1 100644 --- a/solution/1200-1299/1204.Last Person to Fit in the Bus/README_EN.md +++ b/solution/1200-1299/1204.Last Person to Fit in the Bus/README_EN.md @@ -67,9 +67,9 @@ Queue table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -84,6 +84,12 @@ ORDER BY a.turn DESC LIMIT 1; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below WITH @@ -101,3 +107,5 @@ LIMIT 1; ``` + + diff --git a/solution/1200-1299/1205.Monthly Transactions II/README.md b/solution/1200-1299/1205.Monthly Transactions II/README.md index 748c77681b98f..2f1e7864f0ad5 100644 --- a/solution/1200-1299/1205.Monthly Transactions II/README.md +++ b/solution/1200-1299/1205.Monthly Transactions II/README.md @@ -80,12 +80,10 @@ Chargebacks 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -110,3 +108,5 @@ HAVING approved_amount OR chargeback_amount; ``` + + diff --git a/solution/1200-1299/1205.Monthly Transactions II/README_EN.md b/solution/1200-1299/1205.Monthly Transactions II/README_EN.md index ebe2ccd214236..e47ba3935468c 100644 --- a/solution/1200-1299/1205.Monthly Transactions II/README_EN.md +++ b/solution/1200-1299/1205.Monthly Transactions II/README_EN.md @@ -79,9 +79,9 @@ Chargebacks table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -107,3 +107,5 @@ HAVING approved_amount OR chargeback_amount; ``` + + diff --git a/solution/1200-1299/1206.Design Skiplist/README.md b/solution/1200-1299/1206.Design Skiplist/README.md index c9a4dcbcf0d99..bbb8f14d54a40 100644 --- a/solution/1200-1299/1206.Design Skiplist/README.md +++ b/solution/1200-1299/1206.Design Skiplist/README.md @@ -63,18 +63,12 @@ skiplist.search(1); // 返回 false,1 已被擦除 ## 解法 - - -**方法一:数据结构** +### 方法一:数据结构 因为节点 `level` 随机,所以需要多个 `next` 指针,其余操作类似单链表。 -### **Python3** - - - ```python class Node: __slots__ = ['val', 'next'] @@ -142,10 +136,6 @@ class Skiplist: # param_3 = obj.erase(num) ``` -### **Java** - - - ```java class Skiplist { private static final int MAX_LEVEL = 32; @@ -233,7 +223,84 @@ class Skiplist { */ ``` -### **Go** +```cpp +struct Node { + int val; + vector next; + Node(int v, int level) + : val(v) + , next(level, nullptr) {} +}; + +class Skiplist { +public: + const int p = RAND_MAX / 4; + const int maxLevel = 32; + Node* head; + int level; + + Skiplist() { + head = new Node(-1, maxLevel); + level = 0; + } + + bool search(int target) { + Node* curr = head; + for (int i = level - 1; ~i; --i) { + curr = findClosest(curr, i, target); + if (curr->next[i] && curr->next[i]->val == target) return true; + } + return false; + } + + void add(int num) { + Node* curr = head; + int lv = randomLevel(); + Node* node = new Node(num, lv); + level = max(level, lv); + for (int i = level - 1; ~i; --i) { + curr = findClosest(curr, i, num); + if (i < lv) { + node->next[i] = curr->next[i]; + curr->next[i] = node; + } + } + } + + bool erase(int num) { + Node* curr = head; + bool ok = false; + for (int i = level - 1; ~i; --i) { + curr = findClosest(curr, i, num); + if (curr->next[i] && curr->next[i]->val == num) { + curr->next[i] = curr->next[i]->next[i]; + ok = true; + } + } + while (level > 1 && !head->next[level - 1]) --level; + return ok; + } + + Node* findClosest(Node* curr, int level, int target) { + while (curr->next[level] && curr->next[level]->val < target) curr = curr->next[level]; + return curr; + } + + int randomLevel() { + int lv = 1; + while (lv < maxLevel && rand() < p) ++lv; + return lv; + } +}; + +/** + * Your Skiplist object will be instantiated and called as such: + * Skiplist* obj = new Skiplist(); + * bool param_1 = obj->search(target); + * obj->add(num); + * bool param_3 = obj->erase(num); + */ +``` ```go func init() { rand.Seed(time.Now().UnixNano()) } @@ -334,91 +401,6 @@ func randomLevel() int { */ ``` -### **C++** - -```cpp -struct Node { - int val; - vector next; - Node(int v, int level) - : val(v) - , next(level, nullptr) {} -}; - -class Skiplist { -public: - const int p = RAND_MAX / 4; - const int maxLevel = 32; - Node* head; - int level; - - Skiplist() { - head = new Node(-1, maxLevel); - level = 0; - } - - bool search(int target) { - Node* curr = head; - for (int i = level - 1; ~i; --i) { - curr = findClosest(curr, i, target); - if (curr->next[i] && curr->next[i]->val == target) return true; - } - return false; - } - - void add(int num) { - Node* curr = head; - int lv = randomLevel(); - Node* node = new Node(num, lv); - level = max(level, lv); - for (int i = level - 1; ~i; --i) { - curr = findClosest(curr, i, num); - if (i < lv) { - node->next[i] = curr->next[i]; - curr->next[i] = node; - } - } - } - - bool erase(int num) { - Node* curr = head; - bool ok = false; - for (int i = level - 1; ~i; --i) { - curr = findClosest(curr, i, num); - if (curr->next[i] && curr->next[i]->val == num) { - curr->next[i] = curr->next[i]->next[i]; - ok = true; - } - } - while (level > 1 && !head->next[level - 1]) --level; - return ok; - } - - Node* findClosest(Node* curr, int level, int target) { - while (curr->next[level] && curr->next[level]->val < target) curr = curr->next[level]; - return curr; - } - - int randomLevel() { - int lv = 1; - while (lv < maxLevel && rand() < p) ++lv; - return lv; - } -}; - -/** - * Your Skiplist object will be instantiated and called as such: - * Skiplist* obj = new Skiplist(); - * bool param_1 = obj->search(target); - * obj->add(num); - * bool param_3 = obj->erase(num); - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1206.Design Skiplist/README_EN.md b/solution/1200-1299/1206.Design Skiplist/README_EN.md index 18cd1d4c84d76..766845c5f40ea 100644 --- a/solution/1200-1299/1206.Design Skiplist/README_EN.md +++ b/solution/1200-1299/1206.Design Skiplist/README_EN.md @@ -60,12 +60,10 @@ skiplist.search(1); // return False, 1 has already been erased. ## Solutions -Because the `level` of the nodes is random, multiple `next` pointers are required, and the rest of the operation is like a single linked list. +### Solution 1 -### **Python3** - ```python class Node: __slots__ = ['val', 'next'] @@ -133,8 +131,6 @@ class Skiplist: # param_3 = obj.erase(num) ``` -### **Java** - ```java class Skiplist { private static final int MAX_LEVEL = 32; @@ -222,7 +218,84 @@ class Skiplist { */ ``` -### **Go** +```cpp +struct Node { + int val; + vector next; + Node(int v, int level) + : val(v) + , next(level, nullptr) {} +}; + +class Skiplist { +public: + const int p = RAND_MAX / 4; + const int maxLevel = 32; + Node* head; + int level; + + Skiplist() { + head = new Node(-1, maxLevel); + level = 0; + } + + bool search(int target) { + Node* curr = head; + for (int i = level - 1; ~i; --i) { + curr = findClosest(curr, i, target); + if (curr->next[i] && curr->next[i]->val == target) return true; + } + return false; + } + + void add(int num) { + Node* curr = head; + int lv = randomLevel(); + Node* node = new Node(num, lv); + level = max(level, lv); + for (int i = level - 1; ~i; --i) { + curr = findClosest(curr, i, num); + if (i < lv) { + node->next[i] = curr->next[i]; + curr->next[i] = node; + } + } + } + + bool erase(int num) { + Node* curr = head; + bool ok = false; + for (int i = level - 1; ~i; --i) { + curr = findClosest(curr, i, num); + if (curr->next[i] && curr->next[i]->val == num) { + curr->next[i] = curr->next[i]->next[i]; + ok = true; + } + } + while (level > 1 && !head->next[level - 1]) --level; + return ok; + } + + Node* findClosest(Node* curr, int level, int target) { + while (curr->next[level] && curr->next[level]->val < target) curr = curr->next[level]; + return curr; + } + + int randomLevel() { + int lv = 1; + while (lv < maxLevel && rand() < p) ++lv; + return lv; + } +}; + +/** + * Your Skiplist object will be instantiated and called as such: + * Skiplist* obj = new Skiplist(); + * bool param_1 = obj->search(target); + * obj->add(num); + * bool param_3 = obj->erase(num); + */ +``` ```go func init() { rand.Seed(time.Now().UnixNano()) } @@ -323,91 +396,6 @@ func randomLevel() int { */ ``` -### **C++** - -```cpp -struct Node { - int val; - vector next; - Node(int v, int level) - : val(v) - , next(level, nullptr) {} -}; - -class Skiplist { -public: - const int p = RAND_MAX / 4; - const int maxLevel = 32; - Node* head; - int level; - - Skiplist() { - head = new Node(-1, maxLevel); - level = 0; - } - - bool search(int target) { - Node* curr = head; - for (int i = level - 1; ~i; --i) { - curr = findClosest(curr, i, target); - if (curr->next[i] && curr->next[i]->val == target) return true; - } - return false; - } - - void add(int num) { - Node* curr = head; - int lv = randomLevel(); - Node* node = new Node(num, lv); - level = max(level, lv); - for (int i = level - 1; ~i; --i) { - curr = findClosest(curr, i, num); - if (i < lv) { - node->next[i] = curr->next[i]; - curr->next[i] = node; - } - } - } - - bool erase(int num) { - Node* curr = head; - bool ok = false; - for (int i = level - 1; ~i; --i) { - curr = findClosest(curr, i, num); - if (curr->next[i] && curr->next[i]->val == num) { - curr->next[i] = curr->next[i]->next[i]; - ok = true; - } - } - while (level > 1 && !head->next[level - 1]) --level; - return ok; - } - - Node* findClosest(Node* curr, int level, int target) { - while (curr->next[level] && curr->next[level]->val < target) curr = curr->next[level]; - return curr; - } - - int randomLevel() { - int lv = 1; - while (lv < maxLevel && rand() < p) ++lv; - return lv; - } -}; - -/** - * Your Skiplist object will be instantiated and called as such: - * Skiplist* obj = new Skiplist(); - * bool param_1 = obj->search(target); - * obj->add(num); - * bool param_3 = obj->erase(num); - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1207.Unique Number of Occurrences/README.md b/solution/1200-1299/1207.Unique Number of Occurrences/README.md index 5712306dac089..92c7329a52c0d 100644 --- a/solution/1200-1299/1207.Unique Number of Occurrences/README.md +++ b/solution/1200-1299/1207.Unique Number of Occurrences/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们用哈希表 $cnt$ 统计数组 $arr$ 中每个数的出现次数,然后用哈希表 $vis$ 统计出现次数的种类,最后判断 $cnt$ 和 $vis$ 的大小是否相等即可。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def uniqueOccurrences(self, arr: List[int]) -> bool: @@ -62,10 +56,6 @@ class Solution: return len(set(cnt.values())) == len(cnt) ``` -### **Java** - - - ```java class Solution { public boolean uniqueOccurrences(int[] arr) { @@ -78,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +88,6 @@ public: }; ``` -### **Go** - ```go func uniqueOccurrences(arr []int) bool { cnt := map[int]int{} @@ -119,8 +105,6 @@ func uniqueOccurrences(arr []int) bool { } ``` -### **TypeScript** - ```ts function uniqueOccurrences(arr: number[]): boolean { const cnt: Map = new Map(); @@ -131,10 +115,6 @@ function uniqueOccurrences(arr: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1207.Unique Number of Occurrences/README_EN.md b/solution/1200-1299/1207.Unique Number of Occurrences/README_EN.md index f8619c428ae42..0a8f207173f64 100644 --- a/solution/1200-1299/1207.Unique Number of Occurrences/README_EN.md +++ b/solution/1200-1299/1207.Unique Number of Occurrences/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We use a hash table $cnt$ to count the frequency of each number in the array $arr$, and then use another hash table $vis$ to count the types of frequencies. Finally, we check whether the sizes of $cnt$ and $vis$ are equal. @@ -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 uniqueOccurrences(self, arr: List[int]) -> bool: @@ -55,8 +53,6 @@ class Solution: return len(set(cnt.values())) == len(cnt) ``` -### **Java** - ```java class Solution { public boolean uniqueOccurrences(int[] arr) { @@ -69,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +85,6 @@ public: }; ``` -### **Go** - ```go func uniqueOccurrences(arr []int) bool { cnt := map[int]int{} @@ -110,8 +102,6 @@ func uniqueOccurrences(arr []int) bool { } ``` -### **TypeScript** - ```ts function uniqueOccurrences(arr: number[]): boolean { const cnt: Map = new Map(); @@ -122,10 +112,6 @@ function uniqueOccurrences(arr: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1208.Get Equal Substrings Within Budget/README.md b/solution/1200-1299/1208.Get Equal Substrings Within Budget/README.md index d5d87a91f5088..f66209e002447 100644 --- a/solution/1200-1299/1208.Get Equal Substrings Within Budget/README.md +++ b/solution/1200-1299/1208.Get Equal Substrings Within Budget/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:前缀和 + 二分查找** +### 方法一:前缀和 + 二分查找 我们可以创建一个长度为 $n + 1$ 的数组 $f$,其中 $f[i]$ 表示字符串 $s$ 的前 $i$ 个字符与字符串 $t$ 的前 $i$ 个字符的 ASCII 码值的差的绝对值之和。这样,我们就可以通过 $f[j + 1] - f[i]$ 来计算字符串 $s$ 的第 $i$ 个字符到第 $j$ 个字符的 ASCII 码值的差的绝对值之和,其中 $0 \leq i \leq j < n$。 @@ -67,20 +65,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度。 -**方法二:双指针** - -我们可以维护两个指针 $j$ 和 $i$,初始时 $i = j = 0$;维护一个变量 $sum$,表示下标区间 $[i,..j]$ 之间的 ASCII 码值的差的绝对值之和。在每一步中,我们将 $i$ 向右移动一位,然后更新 $sum = sum + |s[i] - t[i]|$。如果 $sum \gt maxCost$,那么我们就循环将指针 $j$ 向右移动,并且在移动过程中不断减少 $sum$ 的值,直到 $sum \leq maxCost$。然后我们更新答案,即 $ans = \max(ans, i - j + 1)$。 - -最后返回答案即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。 - -### **Python3** - - - ```python class Solution: def equalSubstring(self, s: str, t: str, maxCost: int) -> int: @@ -103,25 +89,6 @@ class Solution: return l ``` -```python -class Solution: - def equalSubstring(self, s: str, t: str, maxCost: int) -> int: - n = len(s) - sum = j = 0 - ans = 0 - for i in range(n): - sum += abs(ord(s[i]) - ord(t[i])) - while sum > maxCost: - sum -= abs(ord(s[j]) - ord(t[j])) - j += 1 - ans = max(ans, i - j + 1) - return ans -``` - -### **Java** - - - ```java class Solution { private int maxCost; @@ -160,27 +127,6 @@ class Solution { } ``` -```java -class Solution { - public int equalSubstring(String s, String t, int maxCost) { - int n = s.length(); - int sum = 0; - int ans = 0; - for (int i = 0, j = 0; i < n; ++i) { - sum += Math.abs(s.charAt(i) - t.charAt(i)); - while (sum > maxCost) { - sum -= Math.abs(s.charAt(j) - t.charAt(j)); - ++j; - } - ans = Math.max(ans, i - j + 1); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -214,27 +160,6 @@ public: }; ``` -```cpp -class Solution { -public: - int equalSubstring(string s, string t, int maxCost) { - int n = s.size(); - int ans = 0, sum = 0; - for (int i = 0, j = 0; i < n; ++i) { - sum += abs(s[i] - t[i]); - while (sum > maxCost) { - sum -= abs(s[j] - t[j]); - ++j; - } - ans = max(ans, i - j + 1); - } - return ans; - } -}; -``` - -### **Go** - ```go func equalSubstring(s string, t string, maxCost int) int { n := len(s) @@ -270,6 +195,71 @@ func abs(x int) int { } ``` + + +### 方法二:双指针 + +我们可以维护两个指针 $j$ 和 $i$,初始时 $i = j = 0$;维护一个变量 $sum$,表示下标区间 $[i,..j]$ 之间的 ASCII 码值的差的绝对值之和。在每一步中,我们将 $i$ 向右移动一位,然后更新 $sum = sum + |s[i] - t[i]|$。如果 $sum \gt maxCost$,那么我们就循环将指针 $j$ 向右移动,并且在移动过程中不断减少 $sum$ 的值,直到 $sum \leq maxCost$。然后我们更新答案,即 $ans = \max(ans, i - j + 1)$。 + +最后返回答案即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。 + + + +```python +class Solution: + def equalSubstring(self, s: str, t: str, maxCost: int) -> int: + n = len(s) + sum = j = 0 + ans = 0 + for i in range(n): + sum += abs(ord(s[i]) - ord(t[i])) + while sum > maxCost: + sum -= abs(ord(s[j]) - ord(t[j])) + j += 1 + ans = max(ans, i - j + 1) + return ans +``` + +```java +class Solution { + public int equalSubstring(String s, String t, int maxCost) { + int n = s.length(); + int sum = 0; + int ans = 0; + for (int i = 0, j = 0; i < n; ++i) { + sum += Math.abs(s.charAt(i) - t.charAt(i)); + while (sum > maxCost) { + sum -= Math.abs(s.charAt(j) - t.charAt(j)); + ++j; + } + ans = Math.max(ans, i - j + 1); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int equalSubstring(string s, string t, int maxCost) { + int n = s.size(); + int ans = 0, sum = 0; + for (int i = 0, j = 0; i < n; ++i) { + sum += abs(s[i] - t[i]); + while (sum > maxCost) { + sum -= abs(s[j] - t[j]); + ++j; + } + ans = max(ans, i - j + 1); + } + return ans; + } +}; +``` + ```go func equalSubstring(s string, t string, maxCost int) (ans int) { var sum, j int @@ -293,10 +283,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1208.Get Equal Substrings Within Budget/README_EN.md b/solution/1200-1299/1208.Get Equal Substrings Within Budget/README_EN.md index 5c69b70882e03..74861b507dd91 100644 --- a/solution/1200-1299/1208.Get Equal Substrings Within Budget/README_EN.md +++ b/solution/1200-1299/1208.Get Equal Substrings Within Budget/README_EN.md @@ -48,7 +48,7 @@ That costs 3, so the maximum length is 3. ## Solutions -**Solution 1: Prefix Sum + Binary Search** +### Solution 1: Prefix Sum + Binary Search We can create an array $f$ of length $n + 1$, where $f[i]$ represents the sum of the absolute differences of ASCII values between the first $i$ characters of string $s$ and the first $i$ characters of string $t$. Thus, we can calculate the sum of the absolute differences of ASCII values from the $i$-th character to the $j$-th character of string $s$ by $f[j + 1] - f[i]$, where $0 \leq i \leq j < n$. @@ -60,18 +60,8 @@ Next, we define the left boundary $l$ of binary search as $0$ and the right boun The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of string $s$. -**Solution 2: Two Pointers** - -We can maintain two pointers $j$ and $i$, initially $i = j = 0$; maintain a variable $sum$, representing the sum of the absolute differences of ASCII values in the index interval $[i,..j]$. In each step, we move $i$ to the right by one position, then update $sum = sum + |s[i] - t[i]|$. If $sum \gt maxCost$, then we move the pointer $j$ to the right in a loop, and continuously reduce the value of $sum$ during the moving process until $sum \leq maxCost$. Then we update the answer, i.e., $ans = \max(ans, i - j + 1)$. - -Finally, return the answer. - -The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of string $s$. - -### **Python3** - ```python class Solution: def equalSubstring(self, s: str, t: str, maxCost: int) -> int: @@ -94,23 +84,6 @@ class Solution: return l ``` -```python -class Solution: - def equalSubstring(self, s: str, t: str, maxCost: int) -> int: - n = len(s) - sum = j = 0 - ans = 0 - for i in range(n): - sum += abs(ord(s[i]) - ord(t[i])) - while sum > maxCost: - sum -= abs(ord(s[j]) - ord(t[j])) - j += 1 - ans = max(ans, i - j + 1) - return ans -``` - -### **Java** - ```java class Solution { private int maxCost; @@ -149,27 +122,6 @@ class Solution { } ``` -```java -class Solution { - public int equalSubstring(String s, String t, int maxCost) { - int n = s.length(); - int sum = 0; - int ans = 0; - for (int i = 0, j = 0; i < n; ++i) { - sum += Math.abs(s.charAt(i) - t.charAt(i)); - while (sum > maxCost) { - sum -= Math.abs(s.charAt(j) - t.charAt(j)); - ++j; - } - ans = Math.max(ans, i - j + 1); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -203,27 +155,6 @@ public: }; ``` -```cpp -class Solution { -public: - int equalSubstring(string s, string t, int maxCost) { - int n = s.size(); - int ans = 0, sum = 0; - for (int i = 0, j = 0; i < n; ++i) { - sum += abs(s[i] - t[i]); - while (sum > maxCost) { - sum -= abs(s[j] - t[j]); - ++j; - } - ans = max(ans, i - j + 1); - } - return ans; - } -}; -``` - -### **Go** - ```go func equalSubstring(s string, t string, maxCost int) int { n := len(s) @@ -259,6 +190,71 @@ func abs(x int) int { } ``` + + +### Solution 2: Two Pointers + +We can maintain two pointers $j$ and $i$, initially $i = j = 0$; maintain a variable $sum$, representing the sum of the absolute differences of ASCII values in the index interval $[i,..j]$. In each step, we move $i$ to the right by one position, then update $sum = sum + |s[i] - t[i]|$. If $sum \gt maxCost$, then we move the pointer $j$ to the right in a loop, and continuously reduce the value of $sum$ during the moving process until $sum \leq maxCost$. Then we update the answer, i.e., $ans = \max(ans, i - j + 1)$. + +Finally, return the answer. + +The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of string $s$. + + + +```python +class Solution: + def equalSubstring(self, s: str, t: str, maxCost: int) -> int: + n = len(s) + sum = j = 0 + ans = 0 + for i in range(n): + sum += abs(ord(s[i]) - ord(t[i])) + while sum > maxCost: + sum -= abs(ord(s[j]) - ord(t[j])) + j += 1 + ans = max(ans, i - j + 1) + return ans +``` + +```java +class Solution { + public int equalSubstring(String s, String t, int maxCost) { + int n = s.length(); + int sum = 0; + int ans = 0; + for (int i = 0, j = 0; i < n; ++i) { + sum += Math.abs(s.charAt(i) - t.charAt(i)); + while (sum > maxCost) { + sum -= Math.abs(s.charAt(j) - t.charAt(j)); + ++j; + } + ans = Math.max(ans, i - j + 1); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int equalSubstring(string s, string t, int maxCost) { + int n = s.size(); + int ans = 0, sum = 0; + for (int i = 0, j = 0; i < n; ++i) { + sum += abs(s[i] - t[i]); + while (sum > maxCost) { + sum -= abs(s[j] - t[j]); + ++j; + } + ans = max(ans, i - j + 1); + } + return ans; + } +}; +``` + ```go func equalSubstring(s string, t string, maxCost int) (ans int) { var sum, j int @@ -282,10 +278,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/README.md b/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/README.md index 84278d0a15a4e..fe1302324e097 100644 --- a/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/README.md +++ b/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 我们可以遍历字符串 $s$,维护一个栈,栈中存储的是字符和该字符出现的次数。当遍历到字符 $c$ 时,如果栈顶元素的字符和 $c$ 相同,则将栈顶元素的次数加一,否则将字符 $c$ 和次数 $1$ 入栈。当栈顶元素的次数等于 $k$ 时,将栈顶元素出栈。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def removeDuplicates(self, s: str, k: int) -> str: @@ -87,25 +81,6 @@ class Solution: return "".join(ans) ``` -```python -class Solution: - def removeDuplicates(self, s: str, k: int) -> str: - stk = [] - for c in s: - if stk and stk[-1][0] == c: - stk[-1][1] = (stk[-1][1] + 1) % k - if stk[-1][1] == 0: - stk.pop() - else: - stk.append([c, 1]) - ans = [c * v for c, v in stk] - return "".join(ans) -``` - -### **Java** - - - ```java class Solution { public String removeDuplicates(String s, int k) { @@ -134,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +133,6 @@ public: }; ``` -### **Go** - ```go func removeDuplicates(s string, k int) string { stk := []pair{} @@ -190,10 +161,27 @@ type pair struct { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def removeDuplicates(self, s: str, k: int) -> str: + stk = [] + for c in s: + if stk and stk[-1][0] == c: + stk[-1][1] = (stk[-1][1] + 1) % k + if stk[-1][1] == 0: + stk.pop() + else: + stk.append([c, 1]) + ans = [c * v for c, v in stk] + return "".join(ans) ``` + + diff --git a/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/README_EN.md b/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/README_EN.md index f982234397f81..5a342cec636c6 100644 --- a/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/README_EN.md +++ b/solution/1200-1299/1209.Remove All Adjacent Duplicates in String II/README_EN.md @@ -46,7 +46,7 @@ Finally delete "ddd", get "aa" ## Solutions -**Solution 1: Stack** +### Solution 1: Stack We can traverse the string $s$, maintaining a stack that stores the characters and their occurrence counts. When traversing to character $c$, if the character at the top of the stack is the same as $c$, we increment the count of the top element by one; otherwise, we push the character $c$ and count $1$ into the stack. When the count of the top element equals $k$, we pop the top element from the stack. @@ -56,8 +56,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def removeDuplicates(self, s: str, k: int) -> str: @@ -80,23 +78,6 @@ class Solution: return "".join(ans) ``` -```python -class Solution: - def removeDuplicates(self, s: str, k: int) -> str: - stk = [] - for c in s: - if stk and stk[-1][0] == c: - stk[-1][1] = (stk[-1][1] + 1) % k - if stk[-1][1] == 0: - stk.pop() - else: - stk.append([c, 1]) - ans = [c * v for c, v in stk] - return "".join(ans) -``` - -### **Java** - ```java class Solution { public String removeDuplicates(String s, int k) { @@ -125,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +130,6 @@ public: }; ``` -### **Go** - ```go func removeDuplicates(s string, k int) string { stk := []pair{} @@ -181,10 +158,27 @@ type pair struct { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def removeDuplicates(self, s: str, k: int) -> str: + stk = [] + for c in s: + if stk and stk[-1][0] == c: + stk[-1][1] = (stk[-1][1] + 1) % k + if stk[-1][1] == 0: + stk.pop() + else: + stk.append([c, 1]) + ans = [c * v for c, v in stk] + return "".join(ans) ``` + + diff --git a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/README.md b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/README.md index 234ceb80fc147..ae70013eecc48 100644 --- a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/README.md +++ b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 题目求的是蛇从起始位置到达目标位置的最少移动次数,我们考虑使用广度优先搜索 $BFS$ 来求解。 @@ -86,10 +84,6 @@ -### **Python3** - - - ```python class Solution: def minimumMoves(self, grid: List[List[int]]) -> int: @@ -127,10 +121,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { private int n; @@ -185,8 +175,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -241,8 +229,6 @@ public: }; ``` -### **Go** - ```go func minimumMoves(grid [][]int) int { n := len(grid) @@ -296,8 +282,6 @@ func minimumMoves(grid [][]int) int { } ``` -### **TypeScript** - ```ts function minimumMoves(grid: number[][]): number { const n = grid.length; @@ -346,8 +330,6 @@ function minimumMoves(grid: number[][]): number { } ``` -### **JavaScript** - ```js /** * @param {number[][]} grid @@ -400,10 +382,6 @@ var minimumMoves = function (grid) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/README_EN.md b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/README_EN.md index 8873dabe0dc69..132a3d3e57c73 100644 --- a/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/README_EN.md +++ b/solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/README_EN.md @@ -61,7 +61,7 @@ ## Solutions -**Solution 1: BFS** +### Solution 1: BFS The problem asks for the minimum number of moves for the snake to reach the target position from the starting position. We consider using Breadth-First Search (BFS) to solve it. @@ -80,8 +80,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ -### **Python3** - ```python class Solution: def minimumMoves(self, grid: List[List[int]]) -> int: @@ -105,18 +103,20 @@ class Solution: return ans i1, j1 = a // n, a % n i2, j2 = b // n, b % n + # 尝试向右平移(保持身体水平/垂直状态) move(i1, j1 + 1, i2, j2 + 1) + # 尝试向下平移(保持身体水平/垂直状态) move(i1 + 1, j1, i2 + 1, j2) + # 当前处于水平状态,且 grid[i1 + 1][j2] 无障碍,尝试顺时针旋转90° if i1 == i2 and i1 + 1 < n and grid[i1 + 1][j2] == 0: move(i1, j1, i1 + 1, j1) + # 当前处于垂直状态,且 grid[i2][j1 + 1] 无障碍,尝试逆时针旋转90° if j1 == j2 and j1 + 1 < n and grid[i2][j1 + 1] == 0: move(i1, j1, i1, j1 + 1) ans += 1 return -1 ``` -### **Java** - ```java class Solution { private int n; @@ -140,11 +140,15 @@ class Solution { } int i1 = p[0] / n, j1 = p[0] % n; int i2 = p[1] / n, j2 = p[1] % n; + // 尝试向右平移(保持身体水平/垂直状态) move(i1, j1 + 1, i2, j2 + 1); + // 尝试向下平移(保持身体水平/垂直状态) move(i1 + 1, j1, i2 + 1, j2); + // 当前处于水平状态,且 grid[i1 + 1][j2] 无障碍,尝试顺时针旋转90° if (i1 == i2 && i1 + 1 < n && grid[i1 + 1][j2] == 0) { move(i1, j1, i1 + 1, j1); } + // 当前处于垂直状态,且 grid[i2][j1 + 1] 无障碍,尝试逆时针旋转90° if (j1 == j2 && j1 + 1 < n && grid[i2][j1 + 1] == 0) { move(i1, j1, i1, j1 + 1); } @@ -167,8 +171,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -203,11 +205,15 @@ public: auto [a, b] = p; int i1 = a / n, j1 = a % n; int i2 = b / n, j2 = b % n; + // 尝试向右平移(保持身体水平/垂直状态) move(i1, j1 + 1, i2, j2 + 1); + // 尝试向下平移(保持身体水平/垂直状态) move(i1 + 1, j1, i2 + 1, j2); + // 当前处于水平状态,且 grid[i1 + 1][j2] 无障碍,尝试顺时针旋转90° if (i1 == i2 && i1 + 1 < n && grid[i1 + 1][j2] == 0) { move(i1, j1, i1 + 1, j1); } + // 当前处于垂直状态,且 grid[i2][j1 + 1] 无障碍,尝试逆时针旋转90° if (j1 == j2 && j1 + 1 < n && grid[i2][j1 + 1] == 0) { move(i1, j1, i1, j1 + 1); } @@ -219,8 +225,6 @@ public: }; ``` -### **Go** - ```go func minimumMoves(grid [][]int) int { n := len(grid) @@ -255,11 +259,15 @@ func minimumMoves(grid [][]int) int { a, b := p.a, p.b i1, j1 := a/n, a%n i2, j2 := b/n, b%n + // 尝试向右平移(保持身体水平/垂直状态) move(i1, j1+1, i2, j2+1) + // 尝试向下平移(保持身体水平/垂直状态) move(i1+1, j1, i2+1, j2) + // 当前处于水平状态,且 grid[i1 + 1][j2] 无障碍,尝试顺时针旋转90° if i1 == i2 && i1+1 < n && grid[i1+1][j2] == 0 { move(i1, j1, i1+1, j1) } + // 当前处于垂直状态,且 grid[i2][j1 + 1] 无障碍,尝试逆时针旋转90° if j1 == j2 && j1+1 < n && grid[i2][j1+1] == 0 { move(i1, j1, i1, j1+1) } @@ -270,8 +278,6 @@ func minimumMoves(grid [][]int) int { } ``` -### **TypeScript** - ```ts function minimumMoves(grid: number[][]): number { const n = grid.length; @@ -301,11 +307,15 @@ function minimumMoves(grid: number[][]): number { } const [i1, j1] = [~~(p[0] / n), p[0] % n]; const [i2, j2] = [~~(p[1] / n), p[1] % n]; + // 尝试向右平移(保持身体水平/垂直状态) move(i1, j1 + 1, i2, j2 + 1); + // 尝试向下平移(保持身体水平/垂直状态) move(i1 + 1, j1, i2 + 1, j2); + // 当前处于水平状态,且 grid[i1 + 1][j2] 无障碍,尝试顺时针旋转90° if (i1 == i2 && i1 + 1 < n && grid[i1 + 1][j2] == 0) { move(i1, j1, i1 + 1, j1); } + // 当前处于垂直状态,且 grid[i2][j1 + 1] 无障碍,尝试逆时针旋转90° if (j1 == j2 && j1 + 1 < n && grid[i2][j1 + 1] == 0) { move(i1, j1, i1, j1 + 1); } @@ -316,8 +326,6 @@ function minimumMoves(grid: number[][]): number { } ``` -### **JavaScript** - ```js /** * @param {number[][]} grid @@ -351,11 +359,15 @@ var minimumMoves = function (grid) { } const [i1, j1] = [~~(p[0] / n), p[0] % n]; const [i2, j2] = [~~(p[1] / n), p[1] % n]; + // 尝试向右平移(保持身体水平/垂直状态) move(i1, j1 + 1, i2, j2 + 1); + // 尝试向下平移(保持身体水平/垂直状态) move(i1 + 1, j1, i2 + 1, j2); + // 当前处于水平状态,且 grid[i1 + 1][j2] 无障碍,尝试顺时针旋转90° if (i1 == i2 && i1 + 1 < n && grid[i1 + 1][j2] == 0) { move(i1, j1, i1 + 1, j1); } + // 当前处于垂直状态,且 grid[i2][j1 + 1] 无障碍,尝试逆时针旋转90° if (j1 == j2 && j1 + 1 < n && grid[i2][j1 + 1] == 0) { move(i1, j1, i1, j1 + 1); } @@ -366,10 +378,6 @@ var minimumMoves = function (grid) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1211.Queries Quality and Percentage/README.md b/solution/1200-1299/1211.Queries Quality and Percentage/README.md index 24a48075eedf2..dd5bd29f45d8f 100644 --- a/solution/1200-1299/1211.Queries Quality and Percentage/README.md +++ b/solution/1200-1299/1211.Queries Quality and Percentage/README.md @@ -79,16 +79,12 @@ Cat 查询结果的劣质查询百分比为 (1 / 3) * 100 = 33.33 ## 解法 - - -**方法一:分组统计** +### 方法一:分组统计 我们将查询结果按照 `query_name` 进行分组,然后利用 `AVG` 和 `ROUND` 函数计算 `quality` 和 `poor_query_percentage`。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -100,3 +96,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1200-1299/1211.Queries Quality and Percentage/README_EN.md b/solution/1200-1299/1211.Queries Quality and Percentage/README_EN.md index ec22534d56084..146caa19ca1f6 100644 --- a/solution/1200-1299/1211.Queries Quality and Percentage/README_EN.md +++ b/solution/1200-1299/1211.Queries Quality and Percentage/README_EN.md @@ -76,14 +76,12 @@ Cat queries poor_ query_percentage is (1 / 3) * 100 = 33.33 ## Solutions -**Solution 1: Grouping and Aggregation** +### Solution 1: Grouping and Aggregation We can group the query results by `query_name`, and then use the `AVG` and `ROUND` functions to calculate `quality` and `poor_query_percentage`. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -95,3 +93,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1200-1299/1212.Team Scores in Football Tournament/README.md b/solution/1200-1299/1212.Team Scores in Football Tournament/README.md index 9452e3350aad3..12e50d5cd7ae9 100644 --- a/solution/1200-1299/1212.Team Scores in Football Tournament/README.md +++ b/solution/1200-1299/1212.Team Scores in Football Tournament/README.md @@ -93,9 +93,7 @@ Teams table: ## 解法 - - -**方法一:左连接 + 分组 + CASE 表达式** +### 方法一:左连接 + 分组 + CASE 表达式 我们可以通过左连接,将 `Teams` 表和 `Matches` 表连接起来,连接的条件为 `team_id = host_team OR team_id = guest_team`,这样就可以得到每个球队的所有比赛信息。 @@ -109,8 +107,6 @@ Teams table: -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -134,3 +130,5 @@ ORDER BY 3 DESC, 1; ``` + + diff --git a/solution/1200-1299/1212.Team Scores in Football Tournament/README_EN.md b/solution/1200-1299/1212.Team Scores in Football Tournament/README_EN.md index d0801f4fed39d..64ffbde3e1a36 100644 --- a/solution/1200-1299/1212.Team Scores in Football Tournament/README_EN.md +++ b/solution/1200-1299/1212.Team Scores in Football Tournament/README_EN.md @@ -90,7 +90,7 @@ Matches table: ## Solutions -**Solution 1: Left Join + Group By + Case Expression** +### Solution 1: Left Join + Group By + Case Expression We can join the `Teams` table and the `Matches` table using a left join, where the join condition is `team_id = host_team OR team_id = guest_team`, to obtain all the match information for each team. @@ -104,8 +104,6 @@ Finally, we sort the result by points in descending order, and if the points are -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -129,3 +127,5 @@ ORDER BY 3 DESC, 1; ``` + + diff --git a/solution/1200-1299/1213.Intersection of Three Sorted Arrays/README.md b/solution/1200-1299/1213.Intersection of Three Sorted Arrays/README.md index d15f77dc49648..2d16b31c3da1a 100644 --- a/solution/1200-1299/1213.Intersection of Three Sorted Arrays/README.md +++ b/solution/1200-1299/1213.Intersection of Three Sorted Arrays/README.md @@ -36,26 +36,14 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 遍历三个数组,统计每个数字出现的次数,然后遍历任意一个数组,若某个数字出现的次数为 $3$,则将其加入结果数组。 时间复杂度 $O(n)$,空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别为数组的长度和数组中数字的范围。 -**方法二:二分查找** - -遍历第一个数组,对于其中的每个数字,使用二分查找在第二个数组和第三个数组中查找该数字,若都找到,则将该数字加入结果数组。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(1)$。其中 $n$ 为数组的长度。 - -### **Python3** - - - ```python class Solution: def arraysIntersection( @@ -65,24 +53,6 @@ class Solution: return [x for x in arr1 if cnt[x] == 3] ``` -```python -class Solution: - def arraysIntersection( - self, arr1: List[int], arr2: List[int], arr3: List[int] - ) -> List[int]: - ans = [] - for x in arr1: - i = bisect_left(arr2, x) - j = bisect_left(arr3, x) - if i < len(arr2) and j < len(arr3) and arr2[i] == x and arr3[j] == x: - ans.append(x) - return ans -``` - -### **Java** - - - ```java class Solution { public List arraysIntersection(int[] arr1, int[] arr2, int[] arr3) { @@ -104,24 +74,6 @@ class Solution { } ``` -```java -class Solution { - public List arraysIntersection(int[] arr1, int[] arr2, int[] arr3) { - List ans = new ArrayList<>(); - for (int x : arr1) { - int i = Arrays.binarySearch(arr2, x); - int j = Arrays.binarySearch(arr3, x); - if (i >= 0 && j >= 0) { - ans.add(x); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -144,25 +96,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector arraysIntersection(vector& arr1, vector& arr2, vector& arr3) { - vector ans; - for (int x : arr1) { - auto i = lower_bound(arr2.begin(), arr2.end(), x); - auto j = lower_bound(arr3.begin(), arr3.end(), x); - if (*i == x && *j == x) { - ans.push_back(x); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func arraysIntersection(arr1 []int, arr2 []int, arr3 []int) (ans []int) { cnt := [2001]int{} @@ -182,21 +115,6 @@ func arraysIntersection(arr1 []int, arr2 []int, arr3 []int) (ans []int) { } ``` -```go -func arraysIntersection(arr1 []int, arr2 []int, arr3 []int) (ans []int) { - for _, x := range arr1 { - i := sort.SearchInts(arr2, x) - j := sort.SearchInts(arr3, x) - if i < len(arr2) && j < len(arr3) && arr2[i] == x && arr3[j] == x { - ans = append(ans, x) - } - } - return -} -``` - -### **PHP** - ```php class Solution { /** @@ -219,10 +137,76 @@ class Solution { } ``` -### **...** + + +### 方法二:二分查找 + +遍历第一个数组,对于其中的每个数字,使用二分查找在第二个数组和第三个数组中查找该数字,若都找到,则将该数字加入结果数组。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(1)$。其中 $n$ 为数组的长度。 + + +```python +class Solution: + def arraysIntersection( + self, arr1: List[int], arr2: List[int], arr3: List[int] + ) -> List[int]: + ans = [] + for x in arr1: + i = bisect_left(arr2, x) + j = bisect_left(arr3, x) + if i < len(arr2) and j < len(arr3) and arr2[i] == x and arr3[j] == x: + ans.append(x) + return ans ``` +```java +class Solution { + public List arraysIntersection(int[] arr1, int[] arr2, int[] arr3) { + List ans = new ArrayList<>(); + for (int x : arr1) { + int i = Arrays.binarySearch(arr2, x); + int j = Arrays.binarySearch(arr3, x); + if (i >= 0 && j >= 0) { + ans.add(x); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector arraysIntersection(vector& arr1, vector& arr2, vector& arr3) { + vector ans; + for (int x : arr1) { + auto i = lower_bound(arr2.begin(), arr2.end(), x); + auto j = lower_bound(arr3.begin(), arr3.end(), x); + if (*i == x && *j == x) { + ans.push_back(x); + } + } + return ans; + } +}; +``` + +```go +func arraysIntersection(arr1 []int, arr2 []int, arr3 []int) (ans []int) { + for _, x := range arr1 { + i := sort.SearchInts(arr2, x) + j := sort.SearchInts(arr3, x) + if i < len(arr2) && j < len(arr3) && arr2[i] == x && arr3[j] == x { + ans = append(ans, x) + } + } + return +} ``` + + diff --git a/solution/1200-1299/1213.Intersection of Three Sorted Arrays/README_EN.md b/solution/1200-1299/1213.Intersection of Three Sorted Arrays/README_EN.md index 9a25591536d27..ff709af000d86 100644 --- a/solution/1200-1299/1213.Intersection of Three Sorted Arrays/README_EN.md +++ b/solution/1200-1299/1213.Intersection of Three Sorted Arrays/README_EN.md @@ -32,22 +32,14 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting Traverse the three arrays, count the occurrence of each number, then traverse any one of the arrays. If the count of a number is $3$, add it to the result array. The time complexity is $O(n)$, and the space complexity is $O(m)$. Here, $n$ and $m$ are the length of the array and the range of numbers in the array, respectively. -**Solution 2: Binary Search** - -Traverse the first array. For each number, use binary search to find this number in the second and third arrays. If found in both, add this number to the result array. - -The time complexity is $O(n \times \log n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array. - -### **Python3** - ```python class Solution: def arraysIntersection( @@ -57,22 +49,6 @@ class Solution: return [x for x in arr1 if cnt[x] == 3] ``` -```python -class Solution: - def arraysIntersection( - self, arr1: List[int], arr2: List[int], arr3: List[int] - ) -> List[int]: - ans = [] - for x in arr1: - i = bisect_left(arr2, x) - j = bisect_left(arr3, x) - if i < len(arr2) and j < len(arr3) and arr2[i] == x and arr3[j] == x: - ans.append(x) - return ans -``` - -### **Java** - ```java class Solution { public List arraysIntersection(int[] arr1, int[] arr2, int[] arr3) { @@ -94,24 +70,6 @@ class Solution { } ``` -```java -class Solution { - public List arraysIntersection(int[] arr1, int[] arr2, int[] arr3) { - List ans = new ArrayList<>(); - for (int x : arr1) { - int i = Arrays.binarySearch(arr2, x); - int j = Arrays.binarySearch(arr3, x); - if (i >= 0 && j >= 0) { - ans.add(x); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -134,25 +92,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector arraysIntersection(vector& arr1, vector& arr2, vector& arr3) { - vector ans; - for (int x : arr1) { - auto i = lower_bound(arr2.begin(), arr2.end(), x); - auto j = lower_bound(arr3.begin(), arr3.end(), x); - if (*i == x && *j == x) { - ans.push_back(x); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func arraysIntersection(arr1 []int, arr2 []int, arr3 []int) (ans []int) { cnt := [2001]int{} @@ -172,21 +111,6 @@ func arraysIntersection(arr1 []int, arr2 []int, arr3 []int) (ans []int) { } ``` -```go -func arraysIntersection(arr1 []int, arr2 []int, arr3 []int) (ans []int) { - for _, x := range arr1 { - i := sort.SearchInts(arr2, x) - j := sort.SearchInts(arr3, x) - if i < len(arr2) && j < len(arr3) && arr2[i] == x && arr3[j] == x { - ans = append(ans, x) - } - } - return -} -``` - -### **PHP** - ```php class Solution { /** @@ -209,10 +133,76 @@ class Solution { } ``` -### **...** + +### Solution 2: Binary Search + +Traverse the first array. For each number, use binary search to find this number in the second and third arrays. If found in both, add this number to the result array. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array. + + + +```python +class Solution: + def arraysIntersection( + self, arr1: List[int], arr2: List[int], arr3: List[int] + ) -> List[int]: + ans = [] + for x in arr1: + i = bisect_left(arr2, x) + j = bisect_left(arr3, x) + if i < len(arr2) and j < len(arr3) and arr2[i] == x and arr3[j] == x: + ans.append(x) + return ans ``` +```java +class Solution { + public List arraysIntersection(int[] arr1, int[] arr2, int[] arr3) { + List ans = new ArrayList<>(); + for (int x : arr1) { + int i = Arrays.binarySearch(arr2, x); + int j = Arrays.binarySearch(arr3, x); + if (i >= 0 && j >= 0) { + ans.add(x); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector arraysIntersection(vector& arr1, vector& arr2, vector& arr3) { + vector ans; + for (int x : arr1) { + auto i = lower_bound(arr2.begin(), arr2.end(), x); + auto j = lower_bound(arr3.begin(), arr3.end(), x); + if (*i == x && *j == x) { + ans.push_back(x); + } + } + return ans; + } +}; +``` + +```go +func arraysIntersection(arr1 []int, arr2 []int, arr3 []int) (ans []int) { + for _, x := range arr1 { + i := sort.SearchInts(arr2, x) + j := sort.SearchInts(arr3, x) + if i < len(arr2) && j < len(arr3) && arr2[i] == x && arr3[j] == x { + ans = append(ans, x) + } + } + return +} ``` + + diff --git a/solution/1200-1299/1214.Two Sum BSTs/README.md b/solution/1200-1299/1214.Two Sum BSTs/README.md index d688bbbb50269..7adb4cf7e4116 100644 --- a/solution/1200-1299/1214.Two Sum BSTs/README.md +++ b/solution/1200-1299/1214.Two Sum BSTs/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:中序遍历 + 双指针** +### 方法一:中序遍历 + 双指针 我们分别对两棵树进行中序遍历,得到两个有序数组 $nums[0]$ 和 $nums[1]$,然后使用双指针的方法判断是否存在两个数的和为目标值。双指针判断方法如下: @@ -55,10 +53,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -92,10 +86,6 @@ class Solution: return False ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -145,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -190,8 +178,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -230,8 +216,6 @@ func twoSumBSTs(root1 *TreeNode, root2 *TreeNode, target int) bool { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -278,10 +262,6 @@ function twoSumBSTs(root1: TreeNode | null, root2: TreeNode | null, target: numb } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1214.Two Sum BSTs/README_EN.md b/solution/1200-1299/1214.Two Sum BSTs/README_EN.md index a2695d88cfd55..097cefae7ffd2 100644 --- a/solution/1200-1299/1214.Two Sum BSTs/README_EN.md +++ b/solution/1200-1299/1214.Two Sum BSTs/README_EN.md @@ -32,7 +32,7 @@ ## Solutions -**Solution 1: In-order Traversal + Two Pointers** +### Solution 1: In-order Traversal + Two Pointers We perform in-order traversals on the two trees separately, obtaining two sorted arrays $nums[0]$ and $nums[1]$. Then we use a two-pointer method to determine whether there exist two numbers whose sum equals the target value. The two-pointer method is as follows: @@ -44,8 +44,6 @@ The time complexity is $O(m + n)$, and the space complexity is $O(m + n)$. Here, -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -79,8 +77,6 @@ class Solution: return False ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -130,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -175,8 +169,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -215,8 +207,6 @@ func twoSumBSTs(root1 *TreeNode, root2 *TreeNode, target int) bool { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -263,10 +253,6 @@ function twoSumBSTs(root1: TreeNode | null, root2: TreeNode | null, target: numb } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1215.Stepping Numbers/README.md b/solution/1200-1299/1215.Stepping Numbers/README.md index 9285edc87edcb..63eaecce6e0fc 100644 --- a/solution/1200-1299/1215.Stepping Numbers/README.md +++ b/solution/1200-1299/1215.Stepping Numbers/README.md @@ -30,9 +30,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 首先,如果 $low$ 为 $0$,那么我们需要将 $0$ 加入答案中。 @@ -42,10 +40,6 @@ -### **Python3** - - - ```python class Solution: def countSteppingNumbers(self, low: int, high: int) -> List[int]: @@ -67,10 +61,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List countSteppingNumbers(int low, int high) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +127,6 @@ public: }; ``` -### **Go** - ```go func countSteppingNumbers(low int, high int) []int { ans := []int{} @@ -169,8 +155,6 @@ func countSteppingNumbers(low int, high int) []int { } ``` -### **TypeScript** - ```ts function countSteppingNumbers(low: number, high: number): number[] { const ans: number[] = []; @@ -201,10 +185,6 @@ function countSteppingNumbers(low: number, high: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1215.Stepping Numbers/README_EN.md b/solution/1200-1299/1215.Stepping Numbers/README_EN.md index d51716dc39329..cf9c198706670 100644 --- a/solution/1200-1299/1215.Stepping Numbers/README_EN.md +++ b/solution/1200-1299/1215.Stepping Numbers/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: BFS** +### Solution 1: BFS First, if $low$ is $0$, we need to add $0$ to the answer. @@ -46,8 +46,6 @@ The time complexity is $O(10 \times 2^{\log M})$, and the space complexity is $O -### **Python3** - ```python class Solution: def countSteppingNumbers(self, low: int, high: int) -> List[int]: @@ -69,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List countSteppingNumbers(int low, int high) { @@ -103,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +133,6 @@ public: }; ``` -### **Go** - ```go func countSteppingNumbers(low int, high int) []int { ans := []int{} @@ -169,8 +161,6 @@ func countSteppingNumbers(low int, high int) []int { } ``` -### **TypeScript** - ```ts function countSteppingNumbers(low: number, high: number): number[] { const ans: number[] = []; @@ -201,10 +191,6 @@ function countSteppingNumbers(low: number, high: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1216.Valid Palindrome III/README.md b/solution/1200-1299/1216.Valid Palindrome III/README.md index 6d84520fd58da..bd8d30739f3de 100644 --- a/solution/1200-1299/1216.Valid Palindrome III/README.md +++ b/solution/1200-1299/1216.Valid Palindrome III/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 题目要求删去最多 $k$ 个字符,使得剩余的字符串是回文串。可以转换为求最长回文子序列的问题。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def isValidPalindrome(self, s: str, k: int) -> bool: @@ -79,10 +73,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean isValidPalindrome(String s, int k) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func isValidPalindrome(s string, k int) bool { n := len(s) @@ -163,8 +149,6 @@ func isValidPalindrome(s string, k int) bool { } ``` -### **TypeScript** - ```ts function isValidPalindrome(s: string, k: number): boolean { const n = s.length; @@ -188,8 +172,6 @@ function isValidPalindrome(s: string, k: number): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_valid_palindrome(s: String, k: i32) -> bool { @@ -220,10 +202,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1216.Valid Palindrome III/README_EN.md b/solution/1200-1299/1216.Valid Palindrome III/README_EN.md index 2b47e3bf314d8..f30fd49ef8909 100644 --- a/solution/1200-1299/1216.Valid Palindrome III/README_EN.md +++ b/solution/1200-1299/1216.Valid Palindrome III/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming The problem requires us to remove at most $k$ characters to make the remaining string a palindrome. This can be transformed into finding the longest palindromic subsequence. @@ -51,8 +51,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ -### **Python3** - ```python class Solution: def isValidPalindrome(self, s: str, k: int) -> bool: @@ -71,8 +69,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean isValidPalindrome(String s, int k) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +121,6 @@ public: }; ``` -### **Go** - ```go func isValidPalindrome(s string, k int) bool { n := len(s) @@ -153,8 +145,6 @@ func isValidPalindrome(s string, k int) bool { } ``` -### **TypeScript** - ```ts function isValidPalindrome(s: string, k: number): boolean { const n = s.length; @@ -178,8 +168,6 @@ function isValidPalindrome(s: string, k: number): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_valid_palindrome(s: String, k: i32) -> bool { @@ -210,10 +198,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/README.md b/solution/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/README.md index 8e5d7ba394fa6..6a35787673087 100644 --- a/solution/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/README.md +++ b/solution/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 将所有偶数下标的芯片移动到 0 号位置,所有奇数下标的芯片移动到 1 号位置,所有的代价为 0,接下来只需要在 0/1 号位置中选择其中一个较小数量的芯片,移动到另一个位置。所需的最小代价就是那个较小的数量。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def minCostToMoveChips(self, position: List[int]) -> int: @@ -83,10 +77,6 @@ class Solution: return min(a, b) ``` -### **Java** - - - ```java class Solution { public int minCostToMoveChips(int[] position) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func minCostToMoveChips(position []int) int { a := 0 @@ -130,8 +116,6 @@ func minCostToMoveChips(position []int) int { } ``` -### **JavaScript** - ```js /** * @param {number[]} position @@ -147,10 +131,6 @@ var minCostToMoveChips = function (position) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/README_EN.md b/solution/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/README_EN.md index 5b3b29e94c94c..bec7356eacce8 100644 --- a/solution/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/README_EN.md +++ b/solution/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/README_EN.md @@ -51,7 +51,7 @@ Total cost is 1. ## Solutions -**Solution 1: Quick Thinking** +### Solution 1: Quick Thinking Move all chips at even indices to position 0, and all chips at odd indices to position 1, all at a cost of 0. Then, choose the position (either 0 or 1) with fewer chips and move these chips to the other position. The minimum cost required is the smaller quantity of chips. @@ -59,8 +59,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is -### **Python3** - ```python class Solution: def minCostToMoveChips(self, position: List[int]) -> int: @@ -69,8 +67,6 @@ class Solution: return min(a, b) ``` -### **Java** - ```java class Solution { public int minCostToMoveChips(int[] position) { @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +92,6 @@ public: }; ``` -### **Go** - ```go func minCostToMoveChips(position []int) int { a := 0 @@ -114,8 +106,6 @@ func minCostToMoveChips(position []int) int { } ``` -### **JavaScript** - ```js /** * @param {number[]} position @@ -131,10 +121,6 @@ var minCostToMoveChips = function (position) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/README.md b/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/README.md index 1fbaaaa30ceae..dae1f9a03b939 100644 --- a/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/README.md +++ b/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/README.md @@ -46,18 +46,12 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 时间复杂度 $O(n)$。 -### **Python3** - - - ```python class Solution: def longestSubsequence(self, arr: List[int], difference: int) -> int: @@ -67,10 +61,6 @@ class Solution: return max(f.values()) ``` -### **Java** - - - ```java class Solution { public int longestSubsequence(int[] arr, int difference) { @@ -85,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +90,6 @@ public: }; ``` -### **Go** - ```go func longestSubsequence(arr []int, difference int) (ans int) { f := map[int]int{} @@ -115,8 +101,6 @@ func longestSubsequence(arr []int, difference int) (ans int) { } ``` -### **TypeScript** - ```ts function longestSubsequence(arr: number[], difference: number): number { const f: Map = new Map(); @@ -127,8 +111,6 @@ function longestSubsequence(arr: number[], difference: number): number { } ``` -### **JavaScript** - ```js /** * @param {number[]} arr @@ -144,10 +126,6 @@ var longestSubsequence = function (arr, difference) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/README_EN.md b/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/README_EN.md index c81ee63a781a8..2f06e06b5c107 100644 --- a/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/README_EN.md +++ b/solution/1200-1299/1218.Longest Arithmetic Subsequence of Given Difference/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return max(f.values()) ``` -### **Java** - ```java class Solution { public int longestSubsequence(int[] arr, int difference) { @@ -71,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -88,8 +84,6 @@ public: }; ``` -### **Go** - ```go func longestSubsequence(arr []int, difference int) (ans int) { f := map[int]int{} @@ -101,8 +95,6 @@ func longestSubsequence(arr []int, difference int) (ans int) { } ``` -### **TypeScript** - ```ts function longestSubsequence(arr: number[], difference: number): number { const f: Map = new Map(); @@ -113,8 +105,6 @@ function longestSubsequence(arr: number[], difference: number): number { } ``` -### **JavaScript** - ```js /** * @param {number[]} arr @@ -130,10 +120,6 @@ var longestSubsequence = function (arr, difference) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1219.Path with Maximum Gold/README.md b/solution/1200-1299/1219.Path with Maximum Gold/README.md index d53725882f814..a5cef41ae8a1c 100644 --- a/solution/1200-1299/1219.Path with Maximum Gold/README.md +++ b/solution/1200-1299/1219.Path with Maximum Gold/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们可以枚举每个格子作为起点,然后从起点开始进行深度优先搜索。在搜索的过程中,每遇到一个非零的格子,就将其变成零,并继续搜索。当无法继续搜索时,计算当前的路径的黄金总数,然后将当前的格子变回非零的格子,从而进行回溯。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def getMaximumGold(self, grid: List[List[int]]) -> int: @@ -87,10 +81,6 @@ class Solution: return max(dfs(i, j) for i in range(m) for j in range(n)) ``` -### **Java** - - - ```java class Solution { private final int[] dirs = {-1, 0, 1, 0, -1}; @@ -127,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func getMaximumGold(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -184,8 +170,6 @@ func getMaximumGold(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function getMaximumGold(grid: number[][]): number { const m = grid.length; @@ -210,8 +194,6 @@ function getMaximumGold(grid: number[][]): number { } ``` -### **JavaScript** - ```js /** * @param {number[][]} grid @@ -240,10 +222,6 @@ var getMaximumGold = function (grid) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1219.Path with Maximum Gold/README_EN.md b/solution/1200-1299/1219.Path with Maximum Gold/README_EN.md index 5df2e8763db79..d1080771c848c 100644 --- a/solution/1200-1299/1219.Path with Maximum Gold/README_EN.md +++ b/solution/1200-1299/1219.Path with Maximum Gold/README_EN.md @@ -56,7 +56,7 @@ Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We can enumerate each cell as the starting point, and then start a depth-first search from the starting point. During the search process, whenever we encounter a non-zero cell, we turn it into zero and continue the search. When we can no longer continue the search, we calculate the total amount of gold in the current path, then turn the current cell back into a non-zero cell, thus performing backtracking. @@ -64,8 +64,6 @@ The time complexity is $O(m \times n \times 3^k)$, where $k$ is the maximum leng -### **Python3** - ```python class Solution: def getMaximumGold(self, grid: List[List[int]]) -> int: @@ -83,8 +81,6 @@ class Solution: return max(dfs(i, j) for i in range(m) for j in range(n)) ``` -### **Java** - ```java class Solution { private final int[] dirs = {-1, 0, 1, 0, -1}; @@ -121,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +143,6 @@ public: }; ``` -### **Go** - ```go func getMaximumGold(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -178,8 +170,6 @@ func getMaximumGold(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function getMaximumGold(grid: number[][]): number { const m = grid.length; @@ -204,8 +194,6 @@ function getMaximumGold(grid: number[][]): number { } ``` -### **JavaScript** - ```js /** * @param {number[][]} grid @@ -234,10 +222,6 @@ var getMaximumGold = function (grid) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1220.Count Vowels Permutation/README.md b/solution/1200-1299/1220.Count Vowels Permutation/README.md index 9ba6d31165fd9..d29d24c408344 100644 --- a/solution/1200-1299/1220.Count Vowels Permutation/README.md +++ b/solution/1200-1299/1220.Count Vowels Permutation/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 根据题目描述,我们先列出每个元音字母的后一个字母: @@ -93,16 +91,8 @@ $$ 时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 是字符串的长度,而 $C$ 是元音字母的个数。本题中 $C=5$。 -**方法二:矩阵快速幂加速递推** - -时间复杂度 $O(C^3 \times \log n)$,空间复杂度 $O(C^2)$,其中 $C$ 是元音字母的个数,本题中 $C=5$。 - -### **Python3** - - - ```python class Solution: def countVowelPermutation(self, n: int) -> int: @@ -119,6 +109,120 @@ class Solution: return sum(f) % mod ``` +```java +class Solution { + public int countVowelPermutation(int n) { + long[] f = new long[5]; + Arrays.fill(f, 1); + final int mod = (int) 1e9 + 7; + for (int i = 1; i < n; ++i) { + long[] g = new long[5]; + g[0] = (f[1] + f[2] + f[4]) % mod; + g[1] = (f[0] + f[2]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[2]; + g[4] = (f[2] + f[3]) % mod; + f = g; + } + long ans = 0; + for (long x : f) { + ans = (ans + x) % mod; + } + return (int) ans; + } +} +``` + +```cpp +class Solution { +public: + int countVowelPermutation(int n) { + using ll = long long; + vector f(5, 1); + const int mod = 1e9 + 7; + for (int i = 1; i < n; ++i) { + vector g(5); + g[0] = (f[1] + f[2] + f[4]) % mod; + g[1] = (f[0] + f[2]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[2]; + g[4] = (f[2] + f[3]) % mod; + f = move(g); + } + return accumulate(f.begin(), f.end(), 0LL) % mod; + } +}; +``` + +```go +func countVowelPermutation(n int) (ans int) { + const mod int = 1e9 + 7 + f := make([]int, 5) + for i := range f { + f[i] = 1 + } + for i := 1; i < n; i++ { + g := make([]int, 5) + g[0] = (f[1] + f[2] + f[4]) % mod + g[1] = (f[0] + f[2]) % mod + g[2] = (f[1] + f[3]) % mod + g[3] = f[2] % mod + g[4] = (f[2] + f[3]) % mod + f = g + } + for _, x := range f { + ans = (ans + x) % mod + } + return +} +``` + +```ts +function countVowelPermutation(n: number): number { + const f: number[] = Array(5).fill(1); + const mod = 1e9 + 7; + for (let i = 1; i < n; ++i) { + const g: number[] = Array(5).fill(0); + g[0] = (f[1] + f[2] + f[4]) % mod; + g[1] = (f[0] + f[2]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[2]; + g[4] = (f[2] + f[3]) % mod; + f.splice(0, 5, ...g); + } + return f.reduce((a, b) => (a + b) % mod); +} +``` + +```js +/** + * @param {number} n + * @return {number} + */ +var countVowelPermutation = function (n) { + const mod = 1e9 + 7; + const f = Array(5).fill(1); + for (let i = 1; i < n; ++i) { + const g = Array(5).fill(0); + g[0] = (f[1] + f[2] + f[4]) % mod; + g[1] = (f[0] + f[2]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[2]; + g[4] = (f[2] + f[3]) % mod; + f.splice(0, 5, ...g); + } + return f.reduce((a, b) => (a + b) % mod); +}; +``` + + + +### 方法二:矩阵快速幂加速递推 + +时间复杂度 $O(C^3 \times \log n)$,空间复杂度 $O(C^2)$,其中 $C$ 是元音字母的个数,本题中 $C=5$。 + + + ```python class Solution: def countVowelPermutation(self, n: int) -> int: @@ -153,61 +257,6 @@ class Solution: return sum(map(sum, res)) % mod ``` -```python -import numpy as np - - -class Solution: - def countVowelPermutation(self, n: int) -> int: - mod = 10**9 + 7 - factor = np.mat( - [ - (0, 1, 0, 0, 0), - (1, 0, 1, 0, 0), - (1, 1, 0, 1, 1), - (0, 0, 1, 0, 1), - (1, 0, 0, 0, 0), - ], - np.dtype("O"), - ) - res = np.mat([(1, 1, 1, 1, 1)], np.dtype("O")) - n -= 1 - 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 countVowelPermutation(int n) { - long[] f = new long[5]; - Arrays.fill(f, 1); - final int mod = (int) 1e9 + 7; - for (int i = 1; i < n; ++i) { - long[] g = new long[5]; - g[0] = (f[1] + f[2] + f[4]) % mod; - g[1] = (f[0] + f[2]) % mod; - g[2] = (f[1] + f[3]) % mod; - g[3] = f[2]; - g[4] = (f[2] + f[3]) % mod; - f = g; - } - long ans = 0; - for (long x : f) { - ans = (ans + x) % mod; - } - return (int) ans; - } -} -``` - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -251,55 +300,6 @@ class Solution { } ``` -```java -class Solution { - public int countVowelPermutation(int n) { - final int mod = 1000000007; - long countA = 1, countE = 1, countI = 1, countO = 1, countU = 1; - for (int length = 1; length < n; length++) { - // Calculate the next counts for each vowel based on the previous counts - long nextCountA = countE; - long nextCountE = (countA + countI) % mod; - long nextCountI = (countA + countE + countO + countU) % mod; - long nextCountO = (countI + countU) % mod; - long nextCountU = countA; - // Update the counts with the newly calculated values for the next length - countA = nextCountA; - countE = nextCountE; - countI = nextCountI; - countO = nextCountO; - countU = nextCountU; - } - // Calculate the total count of valid strings for length n - long totalCount = (countA + countE + countI + countO + countU) % mod; - return (int) totalCount; - } -} -``` - -### **C++** - -```cpp -class Solution { -public: - int countVowelPermutation(int n) { - using ll = long long; - vector f(5, 1); - const int mod = 1e9 + 7; - for (int i = 1; i < n; ++i) { - vector g(5); - g[0] = (f[1] + f[2] + f[4]) % mod; - g[1] = (f[0] + f[2]) % mod; - g[2] = (f[1] + f[3]) % mod; - g[3] = f[2]; - g[4] = (f[2] + f[3]) % mod; - f = move(g); - } - return accumulate(f.begin(), f.end(), 0LL) % mod; - } -}; -``` - ```cpp class Solution { public: @@ -346,31 +346,6 @@ private: }; ``` -### **Go** - -```go -func countVowelPermutation(n int) (ans int) { - const mod int = 1e9 + 7 - f := make([]int, 5) - for i := range f { - f[i] = 1 - } - for i := 1; i < n; i++ { - g := make([]int, 5) - g[0] = (f[1] + f[2] + f[4]) % mod - g[1] = (f[0] + f[2]) % mod - g[2] = (f[1] + f[3]) % mod - g[3] = f[2] % mod - g[4] = (f[2] + f[3]) % mod - f = g - } - for _, x := range f { - ans = (ans + x) % mod - } - return -} -``` - ```go const mod = 1e9 + 7 @@ -417,25 +392,6 @@ func pow(a [][]int, n int) [][]int { } ``` -### **TypeScript** - -```ts -function countVowelPermutation(n: number): number { - const f: number[] = Array(5).fill(1); - const mod = 1e9 + 7; - for (let i = 1; i < n; ++i) { - const g: number[] = Array(5).fill(0); - g[0] = (f[1] + f[2] + f[4]) % mod; - g[1] = (f[0] + f[2]) % mod; - g[2] = (f[1] + f[3]) % mod; - g[3] = f[2]; - g[4] = (f[2] + f[3]) % mod; - f.splice(0, 5, ...g); - } - return f.reduce((a, b) => (a + b) % mod); -} -``` - ```ts const mod = 1e9 + 7; @@ -478,29 +434,6 @@ function pow(a: number[][], n: number): number[][] { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number} - */ -var countVowelPermutation = function (n) { - const mod = 1e9 + 7; - const f = Array(5).fill(1); - for (let i = 1; i < n; ++i) { - const g = Array(5).fill(0); - g[0] = (f[1] + f[2] + f[4]) % mod; - g[1] = (f[0] + f[2]) % mod; - g[2] = (f[1] + f[3]) % mod; - g[3] = f[2]; - g[4] = (f[2] + f[3]) % mod; - f.splice(0, 5, ...g); - } - return f.reduce((a, b) => (a + b) % mod); -}; -``` - ```js /** * @param {number} n @@ -548,10 +481,65 @@ function pow(a, n) { } ``` -### **...** + + +### 方法三 + + +```python +import numpy as np + + +class Solution: + def countVowelPermutation(self, n: int) -> int: + mod = 10**9 + 7 + factor = np.mat( + [ + (0, 1, 0, 0, 0), + (1, 0, 1, 0, 0), + (1, 1, 0, 1, 1), + (0, 0, 1, 0, 1), + (1, 0, 0, 0, 0), + ], + np.dtype("O"), + ) + res = np.mat([(1, 1, 1, 1, 1)], np.dtype("O")) + n -= 1 + while n: + if n & 1: + res = res * factor % mod + factor = factor * factor % mod + n >>= 1 + return res.sum() % mod ``` +```java +class Solution { + public int countVowelPermutation(int n) { + final int mod = 1000000007; + long countA = 1, countE = 1, countI = 1, countO = 1, countU = 1; + for (int length = 1; length < n; length++) { + // Calculate the next counts for each vowel based on the previous counts + long nextCountA = countE; + long nextCountE = (countA + countI) % mod; + long nextCountI = (countA + countE + countO + countU) % mod; + long nextCountO = (countI + countU) % mod; + long nextCountU = countA; + // Update the counts with the newly calculated values for the next length + countA = nextCountA; + countE = nextCountE; + countI = nextCountI; + countO = nextCountO; + countU = nextCountU; + } + // Calculate the total count of valid strings for length n + long totalCount = (countA + countE + countI + countO + countU) % mod; + return (int) totalCount; + } +} ``` + + diff --git a/solution/1200-1299/1220.Count Vowels Permutation/README_EN.md b/solution/1200-1299/1220.Count Vowels Permutation/README_EN.md index 92680eaa13b37..42ee758307182 100644 --- a/solution/1200-1299/1220.Count Vowels Permutation/README_EN.md +++ b/solution/1200-1299/1220.Count Vowels Permutation/README_EN.md @@ -49,7 +49,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming Based on the problem description, we can list the possible subsequent vowels for each vowel: @@ -90,14 +90,8 @@ The final answer is $\sum_{i=0}^{4}f[i]$. Note that the answer may be very large 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 number of vowels. In this problem, $C=5$. -**Solution 2: Matrix Exponentiation to Accelerate Recursion** - -The time complexity is $O(C^3 \times \log n)$, and the space complexity is $O(C^2)$. Here, $C$ is the number of vowels. In this problem, $C=5$. - -### **Python3** - ```python class Solution: def countVowelPermutation(self, n: int) -> int: @@ -114,6 +108,120 @@ class Solution: return sum(f) % mod ``` +```java +class Solution { + public int countVowelPermutation(int n) { + long[] f = new long[5]; + Arrays.fill(f, 1); + final int mod = (int) 1e9 + 7; + for (int i = 1; i < n; ++i) { + long[] g = new long[5]; + g[0] = (f[1] + f[2] + f[4]) % mod; + g[1] = (f[0] + f[2]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[2]; + g[4] = (f[2] + f[3]) % mod; + f = g; + } + long ans = 0; + for (long x : f) { + ans = (ans + x) % mod; + } + return (int) ans; + } +} +``` + +```cpp +class Solution { +public: + int countVowelPermutation(int n) { + using ll = long long; + vector f(5, 1); + const int mod = 1e9 + 7; + for (int i = 1; i < n; ++i) { + vector g(5); + g[0] = (f[1] + f[2] + f[4]) % mod; + g[1] = (f[0] + f[2]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[2]; + g[4] = (f[2] + f[3]) % mod; + f = move(g); + } + return accumulate(f.begin(), f.end(), 0LL) % mod; + } +}; +``` + +```go +func countVowelPermutation(n int) (ans int) { + const mod int = 1e9 + 7 + f := make([]int, 5) + for i := range f { + f[i] = 1 + } + for i := 1; i < n; i++ { + g := make([]int, 5) + g[0] = (f[1] + f[2] + f[4]) % mod + g[1] = (f[0] + f[2]) % mod + g[2] = (f[1] + f[3]) % mod + g[3] = f[2] % mod + g[4] = (f[2] + f[3]) % mod + f = g + } + for _, x := range f { + ans = (ans + x) % mod + } + return +} +``` + +```ts +function countVowelPermutation(n: number): number { + const f: number[] = Array(5).fill(1); + const mod = 1e9 + 7; + for (let i = 1; i < n; ++i) { + const g: number[] = Array(5).fill(0); + g[0] = (f[1] + f[2] + f[4]) % mod; + g[1] = (f[0] + f[2]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[2]; + g[4] = (f[2] + f[3]) % mod; + f.splice(0, 5, ...g); + } + return f.reduce((a, b) => (a + b) % mod); +} +``` + +```js +/** + * @param {number} n + * @return {number} + */ +var countVowelPermutation = function (n) { + const mod = 1e9 + 7; + const f = Array(5).fill(1); + for (let i = 1; i < n; ++i) { + const g = Array(5).fill(0); + g[0] = (f[1] + f[2] + f[4]) % mod; + g[1] = (f[0] + f[2]) % mod; + g[2] = (f[1] + f[3]) % mod; + g[3] = f[2]; + g[4] = (f[2] + f[3]) % mod; + f.splice(0, 5, ...g); + } + return f.reduce((a, b) => (a + b) % mod); +}; +``` + + + +### Solution 2: Matrix Exponentiation to Accelerate Recursion + +The time complexity is $O(C^3 \times \log n)$, and the space complexity is $O(C^2)$. Here, $C$ is the number of vowels. In this problem, $C=5$. + + + ```python class Solution: def countVowelPermutation(self, n: int) -> int: @@ -148,59 +256,6 @@ class Solution: return sum(map(sum, res)) % mod ``` -```python -import numpy as np - - -class Solution: - def countVowelPermutation(self, n: int) -> int: - mod = 10**9 + 7 - factor = np.mat( - [ - (0, 1, 0, 0, 0), - (1, 0, 1, 0, 0), - (1, 1, 0, 1, 1), - (0, 0, 1, 0, 1), - (1, 0, 0, 0, 0), - ], - np.dtype("O"), - ) - res = np.mat([(1, 1, 1, 1, 1)], np.dtype("O")) - n -= 1 - 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 countVowelPermutation(int n) { - long[] f = new long[5]; - Arrays.fill(f, 1); - final int mod = (int) 1e9 + 7; - for (int i = 1; i < n; ++i) { - long[] g = new long[5]; - g[0] = (f[1] + f[2] + f[4]) % mod; - g[1] = (f[0] + f[2]) % mod; - g[2] = (f[1] + f[3]) % mod; - g[3] = f[2]; - g[4] = (f[2] + f[3]) % mod; - f = g; - } - long ans = 0; - for (long x : f) { - ans = (ans + x) % mod; - } - return (int) ans; - } -} -``` - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -244,55 +299,6 @@ class Solution { } ``` -```java -class Solution { - public int countVowelPermutation(int n) { - final int mod = 1000000007; - long countA = 1, countE = 1, countI = 1, countO = 1, countU = 1; - for (int length = 1; length < n; length++) { - // Calculate the next counts for each vowel based on the previous counts - long nextCountA = countE; - long nextCountE = (countA + countI) % mod; - long nextCountI = (countA + countE + countO + countU) % mod; - long nextCountO = (countI + countU) % mod; - long nextCountU = countA; - // Update the counts with the newly calculated values for the next length - countA = nextCountA; - countE = nextCountE; - countI = nextCountI; - countO = nextCountO; - countU = nextCountU; - } - // Calculate the total count of valid strings for length n - long totalCount = (countA + countE + countI + countO + countU) % mod; - return (int) totalCount; - } -} -``` - -### **C++** - -```cpp -class Solution { -public: - int countVowelPermutation(int n) { - using ll = long long; - vector f(5, 1); - const int mod = 1e9 + 7; - for (int i = 1; i < n; ++i) { - vector g(5); - g[0] = (f[1] + f[2] + f[4]) % mod; - g[1] = (f[0] + f[2]) % mod; - g[2] = (f[1] + f[3]) % mod; - g[3] = f[2]; - g[4] = (f[2] + f[3]) % mod; - f = move(g); - } - return accumulate(f.begin(), f.end(), 0LL) % mod; - } -}; -``` - ```cpp class Solution { public: @@ -339,31 +345,6 @@ private: }; ``` -### **Go** - -```go -func countVowelPermutation(n int) (ans int) { - const mod int = 1e9 + 7 - f := make([]int, 5) - for i := range f { - f[i] = 1 - } - for i := 1; i < n; i++ { - g := make([]int, 5) - g[0] = (f[1] + f[2] + f[4]) % mod - g[1] = (f[0] + f[2]) % mod - g[2] = (f[1] + f[3]) % mod - g[3] = f[2] % mod - g[4] = (f[2] + f[3]) % mod - f = g - } - for _, x := range f { - ans = (ans + x) % mod - } - return -} -``` - ```go const mod = 1e9 + 7 @@ -410,25 +391,6 @@ func pow(a [][]int, n int) [][]int { } ``` -### **TypeScript** - -```ts -function countVowelPermutation(n: number): number { - const f: number[] = Array(5).fill(1); - const mod = 1e9 + 7; - for (let i = 1; i < n; ++i) { - const g: number[] = Array(5).fill(0); - g[0] = (f[1] + f[2] + f[4]) % mod; - g[1] = (f[0] + f[2]) % mod; - g[2] = (f[1] + f[3]) % mod; - g[3] = f[2]; - g[4] = (f[2] + f[3]) % mod; - f.splice(0, 5, ...g); - } - return f.reduce((a, b) => (a + b) % mod); -} -``` - ```ts const mod = 1e9 + 7; @@ -471,29 +433,6 @@ function pow(a: number[][], n: number): number[][] { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {number} - */ -var countVowelPermutation = function (n) { - const mod = 1e9 + 7; - const f = Array(5).fill(1); - for (let i = 1; i < n; ++i) { - const g = Array(5).fill(0); - g[0] = (f[1] + f[2] + f[4]) % mod; - g[1] = (f[0] + f[2]) % mod; - g[2] = (f[1] + f[3]) % mod; - g[3] = f[2]; - g[4] = (f[2] + f[3]) % mod; - f.splice(0, 5, ...g); - } - return f.reduce((a, b) => (a + b) % mod); -}; -``` - ```js /** * @param {number} n @@ -541,10 +480,65 @@ function pow(a, n) { } ``` -### **...** + +### Solution 3 + + + +```python +import numpy as np + + +class Solution: + def countVowelPermutation(self, n: int) -> int: + mod = 10**9 + 7 + factor = np.mat( + [ + (0, 1, 0, 0, 0), + (1, 0, 1, 0, 0), + (1, 1, 0, 1, 1), + (0, 0, 1, 0, 1), + (1, 0, 0, 0, 0), + ], + np.dtype("O"), + ) + res = np.mat([(1, 1, 1, 1, 1)], np.dtype("O")) + n -= 1 + while n: + if n & 1: + res = res * factor % mod + factor = factor * factor % mod + n >>= 1 + return res.sum() % mod ``` +```java +class Solution { + public int countVowelPermutation(int n) { + final int mod = 1000000007; + long countA = 1, countE = 1, countI = 1, countO = 1, countU = 1; + for (int length = 1; length < n; length++) { + // Calculate the next counts for each vowel based on the previous counts + long nextCountA = countE; + long nextCountE = (countA + countI) % mod; + long nextCountI = (countA + countE + countO + countU) % mod; + long nextCountO = (countI + countU) % mod; + long nextCountU = countA; + // Update the counts with the newly calculated values for the next length + countA = nextCountA; + countE = nextCountE; + countI = nextCountI; + countO = nextCountO; + countU = nextCountU; + } + // Calculate the total count of valid strings for length n + long totalCount = (countA + countE + countI + countO + countU) % mod; + return (int) totalCount; + } +} ``` + + diff --git a/solution/1200-1299/1221.Split a String in Balanced Strings/README.md b/solution/1200-1299/1221.Split a String in Balanced Strings/README.md index 206c7673f0fda..a55898bcddbf3 100644 --- a/solution/1200-1299/1221.Split a String in Balanced Strings/README.md +++ b/solution/1200-1299/1221.Split a String in Balanced Strings/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们用变量 $l$ 维护当前字符串的平衡度,即 $l$ 的值为当前字符串中 $L$ 的数量减去 $R$ 的数量。当 $l$ 的值为 0 时,我们就找到了一个平衡字符串。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def balancedStringSplit(self, s: str) -> int: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int balancedStringSplit(String s) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func balancedStringSplit(s string) int { ans, l := 0, 0 @@ -145,8 +131,6 @@ func balancedStringSplit(s string) int { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -169,10 +153,6 @@ var balancedStringSplit = function (s) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1221.Split a String in Balanced Strings/README_EN.md b/solution/1200-1299/1221.Split a String in Balanced Strings/README_EN.md index 448e4437c0bd3..be0778c6f8040 100644 --- a/solution/1200-1299/1221.Split a String in Balanced Strings/README_EN.md +++ b/solution/1200-1299/1221.Split a String in Balanced Strings/README_EN.md @@ -50,7 +50,7 @@ Note that s cannot be split into "RL", "RR", "RL", ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy We use a variable $l$ to maintain the current balance of the string, i.e., the value of $l$ is the number of 'L's minus the number of 'R's in the current string. When the value of $l$ is 0, we have found a balanced string. @@ -60,8 +60,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is -### **Python3** - ```python class Solution: def balancedStringSplit(self, s: str) -> int: @@ -76,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int balancedStringSplit(String s) { @@ -97,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +110,6 @@ public: }; ``` -### **Go** - ```go func balancedStringSplit(s string) int { ans, l := 0, 0 @@ -135,8 +127,6 @@ func balancedStringSplit(s string) int { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -159,10 +149,6 @@ var balancedStringSplit = function (s) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1222.Queens That Can Attack the King/README.md b/solution/1200-1299/1222.Queens That Can Attack the King/README.md index f248650f19907..cad51e88031e9 100644 --- a/solution/1200-1299/1222.Queens That Can Attack the King/README.md +++ b/solution/1200-1299/1222.Queens That Can Attack the King/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:直接搜索** +### 方法一:直接搜索 我们先将所有皇后的位置存入哈希表或者二维数组 $s$ 中。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def queensAttacktheKing( @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> queensAttacktheKing(int[][] queens, int[] king) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go func queensAttacktheKing(queens [][]int, king []int) (ans [][]int) { n := 8 @@ -177,8 +163,6 @@ func queensAttacktheKing(queens [][]int, king []int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function queensAttacktheKing(queens: number[][], king: number[]): number[][] { const n = 8; @@ -204,10 +188,6 @@ function queensAttacktheKing(queens: number[][], king: number[]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1222.Queens That Can Attack the King/README_EN.md b/solution/1200-1299/1222.Queens That Can Attack the King/README_EN.md index c1d8678f55c5e..a3d800cbebec8 100644 --- a/solution/1200-1299/1222.Queens That Can Attack the King/README_EN.md +++ b/solution/1200-1299/1222.Queens That Can Attack the King/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Direct Search** +### Solution 1: Direct Search First, we store all the positions of the queens in a hash table or a two-dimensional array $s$. @@ -51,8 +51,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. In this p -### **Python3** - ```python class Solution: def queensAttacktheKing( @@ -73,8 +71,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List> queensAttacktheKing(int[][] queens, int[] king) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +130,6 @@ public: }; ``` -### **Go** - ```go func queensAttacktheKing(queens [][]int, king []int) (ans [][]int) { n := 8 @@ -164,8 +156,6 @@ func queensAttacktheKing(queens [][]int, king []int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function queensAttacktheKing(queens: number[][], king: number[]): number[][] { const n = 8; @@ -191,10 +181,6 @@ function queensAttacktheKing(queens: number[][], king: number[]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1223.Dice Roll Simulation/README.md b/solution/1200-1299/1223.Dice Roll Simulation/README.md index e0baf27e78f26..fe40b44de9d7a 100644 --- a/solution/1200-1299/1223.Dice Roll Simulation/README.md +++ b/solution/1200-1299/1223.Dice Roll Simulation/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们可以设计一个函数 $dfs(i, j, x)$ 表示从第 $i$ 次掷骰子开始,当前掷出的点数为 $j$,且连续掷出 $j$ 的次数为 $x$ 的方案数。其中 $j$ 的取值范围为 $[1, 6]$,而 $x$ 的取值范围为 $[1, rollMax[j - 1]]$。那么答案就是 $dfs(0, 0, 0)$。 @@ -62,31 +60,8 @@ 时间复杂度 $O(n \times k^2 \times M)$,空间复杂度 $O(n \times k \times M)$。其中 $k$ 为点数的取值范围,而 $M$ 为连续掷出某个点数的最大次数。 -**方法二:动态规划** - -我们可以将方法一中的记忆化搜索改为动态规划。 - -定义 $f[i][j][x]$ 表示投掷前 $i$ 次骰子,且第 $i$ 次投掷的点数为 $j$,且连续投掷点数 $j$ 的次数为 $x$ 的方案数。初始时 $f[1][j][1] = 1$,其中 $1 \leq j \leq 6$。答案即是: - -$$ -\sum_{j=1}^6 \sum_{x=1}^{rollMax[j-1]} f[n][j][x] -$$ - -我们枚举上一次投掷的点数为 $j$,且连续投掷点数 $j$ 的次数为 $x$,那么当前投掷的点数可以为 $1, 2, \cdots, 6$,如果当前投掷的点数为 $k$,那么有如下两种情况: - -- 如果 $k \neq j$,那么我们可以直接投掷出 $k$,此时连续投掷点数 $j$ 的次数 $x$ 就会被重置为 $1$,因此方案数 $f[i][k][1]$ 就会增加 $f[i-1][j][x]$。 -- 如果 $k = j$,那么我们需要判断 $x+1$ 是否小于等于 $rollMax[j-1]$,如果小于等于,那么我们可以继续投掷出 $j$,此时连续投掷点数 $j$ 的次数 $x$ 就会加 $1$,因此方案数 $f[i][j][x+1]$ 就会增加 $f[i-1][j][x]$。 - -最终的答案即为所有 $f[n][j][x]$ 的和。 - -时间复杂度 $O(n \times k^2 \times M)$,空间复杂度 $O(n \times k \times M)$。其中 $k$ 为点数的取值范围,而 $M$ 为连续掷出某个点数的最大次数。 - -### **Python3** - - - ```python class Solution: def dieSimulator(self, n: int, rollMax: List[int]) -> int: @@ -105,32 +80,6 @@ class Solution: return dfs(0, 0, 0) ``` -```python -class Solution: - def dieSimulator(self, n: int, rollMax: List[int]) -> int: - f = [[[0] * 16 for _ in range(7)] for _ in range(n + 1)] - for j in range(1, 7): - f[1][j][1] = 1 - for i in range(2, n + 1): - for j in range(1, 7): - for x in range(1, rollMax[j - 1] + 1): - for k in range(1, 7): - if k != j: - f[i][k][1] += f[i - 1][j][x] - elif x + 1 <= rollMax[j - 1]: - f[i][j][x + 1] += f[i - 1][j][x] - mod = 10**9 + 7 - ans = 0 - for j in range(1, 7): - for x in range(1, rollMax[j - 1] + 1): - ans = (ans + f[n][j][x]) % mod - return ans -``` - -### **Java** - - - ```java class Solution { private Integer[][][] f; @@ -163,6 +112,108 @@ class Solution { } ``` +```cpp +class Solution { +public: + int dieSimulator(int n, vector& rollMax) { + int f[n][7][16]; + memset(f, 0, sizeof f); + const int mod = 1e9 + 7; + function dfs = [&](int i, int j, int x) -> int { + if (i >= n) { + return 1; + } + if (f[i][j][x]) { + return f[i][j][x]; + } + long ans = 0; + for (int k = 1; k <= 6; ++k) { + if (k != j) { + ans += dfs(i + 1, k, 1); + } else if (x < rollMax[j - 1]) { + ans += dfs(i + 1, j, x + 1); + } + } + ans %= mod; + return f[i][j][x] = ans; + }; + return dfs(0, 0, 0); + } +}; +``` + +```go +func dieSimulator(n int, rollMax []int) int { + f := make([][7][16]int, n) + const mod = 1e9 + 7 + var dfs func(i, j, x int) int + dfs = func(i, j, x int) int { + if i >= n { + return 1 + } + if f[i][j][x] != 0 { + return f[i][j][x] + } + ans := 0 + for k := 1; k <= 6; k++ { + if k != j { + ans += dfs(i+1, k, 1) + } else if x < rollMax[j-1] { + ans += dfs(i+1, j, x+1) + } + } + f[i][j][x] = ans % mod + return f[i][j][x] + } + return dfs(0, 0, 0) +} +``` + + + +### 方法二:动态规划 + +我们可以将方法一中的记忆化搜索改为动态规划。 + +定义 $f[i][j][x]$ 表示投掷前 $i$ 次骰子,且第 $i$ 次投掷的点数为 $j$,且连续投掷点数 $j$ 的次数为 $x$ 的方案数。初始时 $f[1][j][1] = 1$,其中 $1 \leq j \leq 6$。答案即是: + +$$ +\sum_{j=1}^6 \sum_{x=1}^{rollMax[j-1]} f[n][j][x] +$$ + +我们枚举上一次投掷的点数为 $j$,且连续投掷点数 $j$ 的次数为 $x$,那么当前投掷的点数可以为 $1, 2, \cdots, 6$,如果当前投掷的点数为 $k$,那么有如下两种情况: + +- 如果 $k \neq j$,那么我们可以直接投掷出 $k$,此时连续投掷点数 $j$ 的次数 $x$ 就会被重置为 $1$,因此方案数 $f[i][k][1]$ 就会增加 $f[i-1][j][x]$。 +- 如果 $k = j$,那么我们需要判断 $x+1$ 是否小于等于 $rollMax[j-1]$,如果小于等于,那么我们可以继续投掷出 $j$,此时连续投掷点数 $j$ 的次数 $x$ 就会加 $1$,因此方案数 $f[i][j][x+1]$ 就会增加 $f[i-1][j][x]$。 + +最终的答案即为所有 $f[n][j][x]$ 的和。 + +时间复杂度 $O(n \times k^2 \times M)$,空间复杂度 $O(n \times k \times M)$。其中 $k$ 为点数的取值范围,而 $M$ 为连续掷出某个点数的最大次数。 + + + +```python +class Solution: + def dieSimulator(self, n: int, rollMax: List[int]) -> int: + f = [[[0] * 16 for _ in range(7)] for _ in range(n + 1)] + for j in range(1, 7): + f[1][j][1] = 1 + for i in range(2, n + 1): + for j in range(1, 7): + for x in range(1, rollMax[j - 1] + 1): + for k in range(1, 7): + if k != j: + f[i][k][1] += f[i - 1][j][x] + elif x + 1 <= rollMax[j - 1]: + f[i][j][x + 1] += f[i - 1][j][x] + mod = 10**9 + 7 + ans = 0 + for j in range(1, 7): + for x in range(1, rollMax[j - 1] + 1): + ans = (ans + f[n][j][x]) % mod + return ans +``` + ```java class Solution { public int dieSimulator(int n, int[] rollMax) { @@ -195,38 +246,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int dieSimulator(int n, vector& rollMax) { - int f[n][7][16]; - memset(f, 0, sizeof f); - const int mod = 1e9 + 7; - function dfs = [&](int i, int j, int x) -> int { - if (i >= n) { - return 1; - } - if (f[i][j][x]) { - return f[i][j][x]; - } - long ans = 0; - for (int k = 1; k <= 6; ++k) { - if (k != j) { - ans += dfs(i + 1, k, 1); - } else if (x < rollMax[j - 1]) { - ans += dfs(i + 1, j, x + 1); - } - } - ans %= mod; - return f[i][j][x] = ans; - }; - return dfs(0, 0, 0); - } -}; -``` - ```cpp class Solution { public: @@ -261,35 +280,6 @@ public: }; ``` -### **Go** - -```go -func dieSimulator(n int, rollMax []int) int { - f := make([][7][16]int, n) - const mod = 1e9 + 7 - var dfs func(i, j, x int) int - dfs = func(i, j, x int) int { - if i >= n { - return 1 - } - if f[i][j][x] != 0 { - return f[i][j][x] - } - ans := 0 - for k := 1; k <= 6; k++ { - if k != j { - ans += dfs(i+1, k, 1) - } else if x < rollMax[j-1] { - ans += dfs(i+1, j, x+1) - } - } - f[i][j][x] = ans % mod - return f[i][j][x] - } - return dfs(0, 0, 0) -} -``` - ```go func dieSimulator(n int, rollMax []int) (ans int) { f := make([][7][16]int, n+1) @@ -319,10 +309,6 @@ func dieSimulator(n int, rollMax []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1223.Dice Roll Simulation/README_EN.md b/solution/1200-1299/1223.Dice Roll Simulation/README_EN.md index 5d33d60461c34..60ff5e11384a7 100644 --- a/solution/1200-1299/1223.Dice Roll Simulation/README_EN.md +++ b/solution/1200-1299/1223.Dice Roll Simulation/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We can design a function $dfs(i, j, x)$ to represent the number of schemes starting from the $i$-th dice roll, with the current dice roll being $j$, and the number of consecutive times $j$ is rolled being $x$. The range of $j$ is $[1, 6]$, and the range of $x$ is $[1, rollMax[j - 1]]$. The answer is $dfs(0, 0, 0)$. @@ -57,29 +57,8 @@ During the process, we can use memoization search to avoid repeated calculations The time complexity is $O(n \times k^2 \times M)$, and the space complexity is $O(n \times k \times M)$. Here, $k$ is the range of dice points, and $M$ is the maximum number of times a certain point can be rolled consecutively. -**Solution 2: Dynamic Programming** - -We can change the memoization search in Solution 1 to dynamic programming. - -Define $f[i][j][x]$ as the number of schemes for the first $i$ dice rolls, with the $i$-th dice roll being $j$, and the number of consecutive times $j$ is rolled being $x$. Initially, $f[1][j][1] = 1$, where $1 \leq j \leq 6$. The answer is: - -$$ -\sum_{j=1}^6 \sum_{x=1}^{rollMax[j-1]} f[n][j][x] -$$ - -We enumerate the last dice roll as $j$, and the number of consecutive times $j$ is rolled as $x$. The current dice roll can be $1, 2, \cdots, 6$. If the current dice roll is $k$, there are two cases: - -- If $k \neq j$, we can directly roll $k$, and the number of consecutive times $j$ is rolled will be reset to $1$. Therefore, the number of schemes $f[i][k][1]$ will increase by $f[i-1][j][x]$. -- If $k = j$, we need to judge whether $x+1$ is less than or equal to $rollMax[j-1]$. If it is less than or equal to, we can continue to roll $j$, and the number of consecutive times $j$ is rolled will increase by $1$. Therefore, the number of schemes $f[i][j][x+1]$ will increase by $f[i-1][j][x]$. - -The final answer is the sum of all $f[n][j][x]$. - -The time complexity is $O(n \times k^2 \times M)$, and the space complexity is $O(n \times k \times M)$. Here, $k$ is the range of dice points, and $M$ is the maximum number of times a certain point can be rolled consecutively. - -### **Python3** - ```python class Solution: def dieSimulator(self, n: int, rollMax: List[int]) -> int: @@ -98,30 +77,6 @@ class Solution: return dfs(0, 0, 0) ``` -```python -class Solution: - def dieSimulator(self, n: int, rollMax: List[int]) -> int: - f = [[[0] * 16 for _ in range(7)] for _ in range(n + 1)] - for j in range(1, 7): - f[1][j][1] = 1 - for i in range(2, n + 1): - for j in range(1, 7): - for x in range(1, rollMax[j - 1] + 1): - for k in range(1, 7): - if k != j: - f[i][k][1] += f[i - 1][j][x] - elif x + 1 <= rollMax[j - 1]: - f[i][j][x + 1] += f[i - 1][j][x] - mod = 10**9 + 7 - ans = 0 - for j in range(1, 7): - for x in range(1, rollMax[j - 1] + 1): - ans = (ans + f[n][j][x]) % mod - return ans -``` - -### **Java** - ```java class Solution { private Integer[][][] f; @@ -154,6 +109,108 @@ class Solution { } ``` +```cpp +class Solution { +public: + int dieSimulator(int n, vector& rollMax) { + int f[n][7][16]; + memset(f, 0, sizeof f); + const int mod = 1e9 + 7; + function dfs = [&](int i, int j, int x) -> int { + if (i >= n) { + return 1; + } + if (f[i][j][x]) { + return f[i][j][x]; + } + long ans = 0; + for (int k = 1; k <= 6; ++k) { + if (k != j) { + ans += dfs(i + 1, k, 1); + } else if (x < rollMax[j - 1]) { + ans += dfs(i + 1, j, x + 1); + } + } + ans %= mod; + return f[i][j][x] = ans; + }; + return dfs(0, 0, 0); + } +}; +``` + +```go +func dieSimulator(n int, rollMax []int) int { + f := make([][7][16]int, n) + const mod = 1e9 + 7 + var dfs func(i, j, x int) int + dfs = func(i, j, x int) int { + if i >= n { + return 1 + } + if f[i][j][x] != 0 { + return f[i][j][x] + } + ans := 0 + for k := 1; k <= 6; k++ { + if k != j { + ans += dfs(i+1, k, 1) + } else if x < rollMax[j-1] { + ans += dfs(i+1, j, x+1) + } + } + f[i][j][x] = ans % mod + return f[i][j][x] + } + return dfs(0, 0, 0) +} +``` + + + +### Solution 2: Dynamic Programming + +We can change the memoization search in Solution 1 to dynamic programming. + +Define $f[i][j][x]$ as the number of schemes for the first $i$ dice rolls, with the $i$-th dice roll being $j$, and the number of consecutive times $j$ is rolled being $x$. Initially, $f[1][j][1] = 1$, where $1 \leq j \leq 6$. The answer is: + +$$ +\sum_{j=1}^6 \sum_{x=1}^{rollMax[j-1]} f[n][j][x] +$$ + +We enumerate the last dice roll as $j$, and the number of consecutive times $j$ is rolled as $x$. The current dice roll can be $1, 2, \cdots, 6$. If the current dice roll is $k$, there are two cases: + +- If $k \neq j$, we can directly roll $k$, and the number of consecutive times $j$ is rolled will be reset to $1$. Therefore, the number of schemes $f[i][k][1]$ will increase by $f[i-1][j][x]$. +- If $k = j$, we need to judge whether $x+1$ is less than or equal to $rollMax[j-1]$. If it is less than or equal to, we can continue to roll $j$, and the number of consecutive times $j$ is rolled will increase by $1$. Therefore, the number of schemes $f[i][j][x+1]$ will increase by $f[i-1][j][x]$. + +The final answer is the sum of all $f[n][j][x]$. + +The time complexity is $O(n \times k^2 \times M)$, and the space complexity is $O(n \times k \times M)$. Here, $k$ is the range of dice points, and $M$ is the maximum number of times a certain point can be rolled consecutively. + + + +```python +class Solution: + def dieSimulator(self, n: int, rollMax: List[int]) -> int: + f = [[[0] * 16 for _ in range(7)] for _ in range(n + 1)] + for j in range(1, 7): + f[1][j][1] = 1 + for i in range(2, n + 1): + for j in range(1, 7): + for x in range(1, rollMax[j - 1] + 1): + for k in range(1, 7): + if k != j: + f[i][k][1] += f[i - 1][j][x] + elif x + 1 <= rollMax[j - 1]: + f[i][j][x + 1] += f[i - 1][j][x] + mod = 10**9 + 7 + ans = 0 + for j in range(1, 7): + for x in range(1, rollMax[j - 1] + 1): + ans = (ans + f[n][j][x]) % mod + return ans +``` + ```java class Solution { public int dieSimulator(int n, int[] rollMax) { @@ -186,38 +243,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int dieSimulator(int n, vector& rollMax) { - int f[n][7][16]; - memset(f, 0, sizeof f); - const int mod = 1e9 + 7; - function dfs = [&](int i, int j, int x) -> int { - if (i >= n) { - return 1; - } - if (f[i][j][x]) { - return f[i][j][x]; - } - long ans = 0; - for (int k = 1; k <= 6; ++k) { - if (k != j) { - ans += dfs(i + 1, k, 1); - } else if (x < rollMax[j - 1]) { - ans += dfs(i + 1, j, x + 1); - } - } - ans %= mod; - return f[i][j][x] = ans; - }; - return dfs(0, 0, 0); - } -}; -``` - ```cpp class Solution { public: @@ -252,35 +277,6 @@ public: }; ``` -### **Go** - -```go -func dieSimulator(n int, rollMax []int) int { - f := make([][7][16]int, n) - const mod = 1e9 + 7 - var dfs func(i, j, x int) int - dfs = func(i, j, x int) int { - if i >= n { - return 1 - } - if f[i][j][x] != 0 { - return f[i][j][x] - } - ans := 0 - for k := 1; k <= 6; k++ { - if k != j { - ans += dfs(i+1, k, 1) - } else if x < rollMax[j-1] { - ans += dfs(i+1, j, x+1) - } - } - f[i][j][x] = ans % mod - return f[i][j][x] - } - return dfs(0, 0, 0) -} -``` - ```go func dieSimulator(n int, rollMax []int) (ans int) { f := make([][7][16]int, n+1) @@ -310,10 +306,6 @@ func dieSimulator(n int, rollMax []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1224.Maximum Equal Frequency/README.md b/solution/1200-1299/1224.Maximum Equal Frequency/README.md index 0caf4895a6320..cff050c5c4ef8 100644 --- a/solution/1200-1299/1224.Maximum Equal Frequency/README.md +++ b/solution/1200-1299/1224.Maximum Equal Frequency/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:数组或哈希表** +### 方法一:数组或哈希表 我们用 $cnt$ 记录 $nums$ 中每个元素 $v$ 出现的次数,而 $ccnt$ 记录每个次数出现的次数,元素出现的最大次数用 $mx$ 表示。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def maxEqualFreq(self, nums: List[int]) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static int[] cnt = new int[100010]; @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go func maxEqualFreq(nums []int) int { cnt := map[int]int{} @@ -172,8 +158,6 @@ func maxEqualFreq(nums []int) int { } ``` -### **TypeScript** - ```ts function maxEqualFreq(nums: number[]): number { const n = nums.length; @@ -212,10 +196,6 @@ function maxEqualFreq(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1224.Maximum Equal Frequency/README_EN.md b/solution/1200-1299/1224.Maximum Equal Frequency/README_EN.md index 314ec3017d8b1..d4bf16c3ea61c 100644 --- a/solution/1200-1299/1224.Maximum Equal Frequency/README_EN.md +++ b/solution/1200-1299/1224.Maximum Equal Frequency/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Array or Hash Table** +### Solution 1: Array or Hash Table We use $cnt$ to record the number of times each element $v$ appears in $nums$, and $ccnt$ to record the number of times each count appears. The maximum number of times an element appears is represented by $mx$. @@ -48,8 +48,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maxEqualFreq(self, nums: List[int]) -> int: @@ -71,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static int[] cnt = new int[100010]; @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +125,6 @@ public: }; ``` -### **Go** - ```go func maxEqualFreq(nums []int) int { cnt := map[int]int{} @@ -158,8 +150,6 @@ func maxEqualFreq(nums []int) int { } ``` -### **TypeScript** - ```ts function maxEqualFreq(nums: number[]): number { const n = nums.length; @@ -198,10 +188,6 @@ function maxEqualFreq(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1225.Report Contiguous Dates/README.md b/solution/1200-1299/1225.Report Contiguous Dates/README.md index 2318bac22fb18..c6f5da982fa1b 100644 --- a/solution/1200-1299/1225.Report Contiguous Dates/README.md +++ b/solution/1200-1299/1225.Report Contiguous Dates/README.md @@ -85,16 +85,12 @@ Succeeded table: ## 解法 - - -**方法一:合并 + 窗口函数 + 分组求最大最小值** +### 方法一:合并 + 窗口函数 + 分组求最大最小值 我们可以将两个表合并,用一个字段 $st$ 表示状态,其中 `failed` 表示失败,`succeeded` 表示成功。然后我们可以使用窗口函数,将相同状态的记录分到一组,求出每个日期与其所在组排名的差值 $pt$,作为同一个连续状态的标识。最后我们可以按照 $st$ 和 $pt$ 分组,求出每组的最小日期和最大日期,然后按照最小日期排序即可。 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -129,3 +125,5 @@ ORDER BY 2; ``` + + diff --git a/solution/1200-1299/1225.Report Contiguous Dates/README_EN.md b/solution/1200-1299/1225.Report Contiguous Dates/README_EN.md index 7d1c776e159c4..949e98d9030dc 100644 --- a/solution/1200-1299/1225.Report Contiguous Dates/README_EN.md +++ b/solution/1200-1299/1225.Report Contiguous Dates/README_EN.md @@ -84,14 +84,12 @@ From 2019-01-06 to 2019-01-06 all tasks succeeded and the system state was " ## Solutions -**Solution 1: Union + Window Function + Group By** +### Solution 1: Union + Window Function + Group By We can merge the two tables into one table with a field `st` representing the status, where `failed` indicates failure and `succeeded` indicates success. Then, we can use a window function to group the records with the same status into one group, and calculate the difference between each date and its rank within the group as `pt`, which serves as the identifier for the same continuous status. Finally, we can group by `st` and `pt`, and calculate the minimum and maximum dates for each group, and sort by the minimum date. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -126,3 +124,5 @@ ORDER BY 2; ``` + + diff --git a/solution/1200-1299/1226.The Dining Philosophers/README.md b/solution/1200-1299/1226.The Dining Philosophers/README.md index 3f99ced2bfde2..909575f1697b7 100644 --- a/solution/1200-1299/1226.The Dining Philosophers/README.md +++ b/solution/1200-1299/1226.The Dining Philosophers/README.md @@ -58,28 +58,10 @@ output[i] = [a, b, c] (3个整数) ## 解法 - +### 方法一 -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **C++** - ```cpp class DiningPhilosophers { public: @@ -102,10 +84,6 @@ private: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1226.The Dining Philosophers/README_EN.md b/solution/1200-1299/1226.The Dining Philosophers/README_EN.md index bbeb603a95f8a..3cf254c82703e 100644 --- a/solution/1200-1299/1226.The Dining Philosophers/README_EN.md +++ b/solution/1200-1299/1226.The Dining Philosophers/README_EN.md @@ -53,24 +53,32 @@ output[i] = [a, b, c] (three integers) ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java +### Solution 1 -``` - -### **...** - -``` + +```cpp +class DiningPhilosophers { +public: + using Act = function; + + void wantsToEat(int philosopher, Act pickLeftFork, Act pickRightFork, Act eat, Act putLeftFork, Act putRightFork) { + /* 这一题实际上是用到了C++17中的scoped_lock知识。 + 作用是传入scoped_lock(mtx1, mtx2)两个锁,然后在作用范围内,依次顺序上锁mtx1和mtx2;然后在作用范围结束时,再反续解锁mtx2和mtx1。 + 从而保证了philosopher1有动作的时候,philosopher2无法操作;但是philosopher3和philosopher4不受影响 */ + std::scoped_lock lock(mutexes_[philosopher], mutexes_[philosopher >= 4 ? 0 : philosopher + 1]); + pickLeftFork(); + pickRightFork(); + eat(); + putLeftFork(); + putRightFork(); + } + +private: + vector mutexes_ = vector(5); +}; ``` + + diff --git a/solution/1200-1299/1227.Airplane Seat Assignment Probability/README.md b/solution/1200-1299/1227.Airplane Seat Assignment Probability/README.md index 525faef2fb748..c704a5c1fa944 100644 --- a/solution/1200-1299/1227.Airplane Seat Assignment Probability/README.md +++ b/solution/1200-1299/1227.Airplane Seat Assignment Probability/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 用 $f(n)$ 表示当有 $n$ 位乘客登机时,第 $n$ 位乘客坐在自己的座位上的概率。从最简单的情况开始考虑: @@ -129,20 +127,12 @@ $$ -### **Python3** - - - ```python class Solution: def nthPersonGetsNthSeat(self, n: int) -> float: return 1 if n == 1 else 0.5 ``` -### **Java** - - - ```java class Solution { public double nthPersonGetsNthSeat(int n) { @@ -151,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go func nthPersonGetsNthSeat(n int) float64 { if n == 1 { @@ -173,10 +159,6 @@ func nthPersonGetsNthSeat(n int) float64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1227.Airplane Seat Assignment Probability/README_EN.md b/solution/1200-1299/1227.Airplane Seat Assignment Probability/README_EN.md index 63ff46c400518..7b4e167cce3db 100644 --- a/solution/1200-1299/1227.Airplane Seat Assignment Probability/README_EN.md +++ b/solution/1200-1299/1227.Airplane Seat Assignment Probability/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics Let $f(n)$ represent the probability that the $n$th passenger will sit in their own seat when there are $n$ passengers boarding. Consider from the simplest case: @@ -119,16 +119,12 @@ $$ -### **Python3** - ```python class Solution: def nthPersonGetsNthSeat(self, n: int) -> float: return 1 if n == 1 else 0.5 ``` -### **Java** - ```java class Solution { public double nthPersonGetsNthSeat(int n) { @@ -137,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +142,6 @@ public: }; ``` -### **Go** - ```go func nthPersonGetsNthSeat(n int) float64 { if n == 1 { @@ -159,10 +151,6 @@ func nthPersonGetsNthSeat(n int) float64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1228.Missing Number In Arithmetic Progression/README.md b/solution/1200-1299/1228.Missing Number In Arithmetic Progression/README.md index f9ac4daf57bf2..3e63544c8dcae 100644 --- a/solution/1200-1299/1228.Missing Number In Arithmetic Progression/README.md +++ b/solution/1200-1299/1228.Missing Number In Arithmetic Progression/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:等差数列求和公式** +### 方法一:等差数列求和公式 等差数列求和公式为 $\frac{n(a_1 + a_n)}{2}$,其中 $n$ 为等差数列的项数,$a_1$ 为等差数列的首项,$a_n$ 为等差数列的末项。 @@ -55,31 +53,12 @@ -### **Python3** - - - ```python class Solution: def missingNumber(self, arr: List[int]) -> int: return (arr[0] + arr[-1]) * (len(arr) + 1) // 2 - sum(arr) ``` -```python -class Solution: - def missingNumber(self, arr: List[int]) -> int: - n = len(arr) - d = (arr[-1] - arr[0]) // n - for i in range(1, n): - if arr[i] != arr[i - 1] + d: - return arr[i - 1] + d - return arr[0] -``` - -### **Java** - - - ```java class Solution { public int missingNumber(int[] arr) { @@ -91,23 +70,6 @@ class Solution { } ``` -```java -class Solution { - public int missingNumber(int[] arr) { - int n = arr.length; - int d = (arr[n - 1] - arr[0]) / n; - for (int i = 1; i < n; ++i) { - if (arr[i] != arr[i - 1] + d) { - return arr[i - 1] + d; - } - } - return arr[0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -120,21 +82,6 @@ public: }; ``` -```cpp -class Solution { -public: - int missingNumber(vector& arr) { - int n = arr.size(); - int d = (arr[n - 1] - arr[0]) / n; - for (int i = 1; i < n; ++i) - if (arr[i] != arr[i - 1] + d) return arr[i - 1] + d; - return arr[0]; - } -}; -``` - -### **Go** - ```go func missingNumber(arr []int) int { n := len(arr) @@ -148,10 +95,51 @@ func missingNumber(arr []int) int { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def missingNumber(self, arr: List[int]) -> int: + n = len(arr) + d = (arr[-1] - arr[0]) // n + for i in range(1, n): + if arr[i] != arr[i - 1] + d: + return arr[i - 1] + d + return arr[0] ``` +```java +class Solution { + public int missingNumber(int[] arr) { + int n = arr.length; + int d = (arr[n - 1] - arr[0]) / n; + for (int i = 1; i < n; ++i) { + if (arr[i] != arr[i - 1] + d) { + return arr[i - 1] + d; + } + } + return arr[0]; + } +} +``` + +```cpp +class Solution { +public: + int missingNumber(vector& arr) { + int n = arr.size(); + int d = (arr[n - 1] - arr[0]) / n; + for (int i = 1; i < n; ++i) + if (arr[i] != arr[i - 1] + d) return arr[i - 1] + d; + return arr[0]; + } +}; ``` + + diff --git a/solution/1200-1299/1228.Missing Number In Arithmetic Progression/README_EN.md b/solution/1200-1299/1228.Missing Number In Arithmetic Progression/README_EN.md index 2b6e7ccc0060f..5088a43470819 100644 --- a/solution/1200-1299/1228.Missing Number In Arithmetic Progression/README_EN.md +++ b/solution/1200-1299/1228.Missing Number In Arithmetic Progression/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: Arithmetic Series Sum Formula** +### Solution 1: Arithmetic Series Sum Formula The sum formula for an arithmetic series is $\frac{n(a_1 + a_n)}{2}$, where $n$ is the number of terms in the arithmetic series, $a_1$ is the first term of the arithmetic series, and $a_n$ is the last term of the arithmetic series. @@ -49,27 +49,12 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Where $n$ is -### **Python3** - ```python class Solution: def missingNumber(self, arr: List[int]) -> int: return (arr[0] + arr[-1]) * (len(arr) + 1) // 2 - sum(arr) ``` -```python -class Solution: - def missingNumber(self, arr: List[int]) -> int: - n = len(arr) - d = (arr[-1] - arr[0]) // n - for i in range(1, n): - if arr[i] != arr[i - 1] + d: - return arr[i - 1] + d - return arr[0] -``` - -### **Java** - ```java class Solution { public int missingNumber(int[] arr) { @@ -81,23 +66,6 @@ class Solution { } ``` -```java -class Solution { - public int missingNumber(int[] arr) { - int n = arr.length; - int d = (arr[n - 1] - arr[0]) / n; - for (int i = 1; i < n; ++i) { - if (arr[i] != arr[i - 1] + d) { - return arr[i - 1] + d; - } - } - return arr[0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -110,33 +78,6 @@ public: }; ``` -```cpp -class Solution { -public: - int missingNumber(vector& arr) { - int n = arr.size(); - int d = (arr[n - 1] - arr[0]) / n; - for (int i = 1; i < n; ++i) - if (arr[i] != arr[i - 1] + d) return arr[i - 1] + d; - return arr[0]; - } -}; -``` - -### **Go** - -```go -func missingNumber(arr []int) int { - n := len(arr) - x := (arr[0] + arr[n-1]) * (n + 1) / 2 - y := 0 - for _, v := range arr { - y += v - } - return x - y -} -``` - ```go func missingNumber(arr []int) int { n := len(arr) @@ -150,10 +91,51 @@ func missingNumber(arr []int) int { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def missingNumber(self, arr: List[int]) -> int: + n = len(arr) + d = (arr[-1] - arr[0]) // n + for i in range(1, n): + if arr[i] != arr[i - 1] + d: + return arr[i - 1] + d + return arr[0] ``` +```java +class Solution { + public int missingNumber(int[] arr) { + int n = arr.length; + int d = (arr[n - 1] - arr[0]) / n; + for (int i = 1; i < n; ++i) { + if (arr[i] != arr[i - 1] + d) { + return arr[i - 1] + d; + } + } + return arr[0]; + } +} +``` + +```cpp +class Solution { +public: + int missingNumber(vector& arr) { + int n = arr.size(); + int d = (arr[n - 1] - arr[0]) / n; + for (int i = 1; i < n; ++i) + if (arr[i] != arr[i - 1] + d) return arr[i - 1] + d; + return arr[0]; + } +}; ``` + + diff --git a/solution/1200-1299/1229.Meeting Scheduler/README.md b/solution/1200-1299/1229.Meeting Scheduler/README.md index 60ba1d0190e6e..31f99ef75fbb8 100644 --- a/solution/1200-1299/1229.Meeting Scheduler/README.md +++ b/solution/1200-1299/1229.Meeting Scheduler/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:排序 + 双指针** +### 方法一:排序 + 双指针 我们可以将两个人的空闲时间分别排序,然后使用双指针遍历两个数组,找到两个人的空闲时间段的交集,如果交集的长度大于等于 `duration`,则返回交集的起始时间和起始时间加上 `duration`。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def minAvailableDuration( @@ -80,10 +74,6 @@ class Solution: return [] ``` -### **Java** - - - ```java class Solution { public List minAvailableDuration(int[][] slots1, int[][] slots2, int duration) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,7 +123,26 @@ public: }; ``` -### **Rust** +```go +func minAvailableDuration(slots1 [][]int, slots2 [][]int, duration int) []int { + sort.Slice(slots1, func(i, j int) bool { return slots1[i][0] < slots1[j][0] }) + sort.Slice(slots2, func(i, j int) bool { return slots2[i][0] < slots2[j][0] }) + i, j, m, n := 0, 0, len(slots1), len(slots2) + for i < m && j < n { + start := max(slots1[i][0], slots2[j][0]) + end := min(slots1[i][1], slots2[j][1]) + if end-start >= duration { + return []int{start, start + duration} + } + if slots1[i][1] < slots2[j][1] { + i++ + } else { + j++ + } + } + return []int{} +} +``` ```rust impl Solution { @@ -185,33 +192,6 @@ impl Solution { } ``` -### **Go** - -```go -func minAvailableDuration(slots1 [][]int, slots2 [][]int, duration int) []int { - sort.Slice(slots1, func(i, j int) bool { return slots1[i][0] < slots1[j][0] }) - sort.Slice(slots2, func(i, j int) bool { return slots2[i][0] < slots2[j][0] }) - i, j, m, n := 0, 0, len(slots1), len(slots2) - for i < m && j < n { - start := max(slots1[i][0], slots2[j][0]) - end := min(slots1[i][1], slots2[j][1]) - if end-start >= duration { - return []int{start, start + duration} - } - if slots1[i][1] < slots2[j][1] { - i++ - } else { - j++ - } - } - return []int{} -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1229.Meeting Scheduler/README_EN.md b/solution/1200-1299/1229.Meeting Scheduler/README_EN.md index 57f19c2abe4bc..af775d5f2db08 100644 --- a/solution/1200-1299/1229.Meeting Scheduler/README_EN.md +++ b/solution/1200-1299/1229.Meeting Scheduler/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Sorting + Two Pointers** +### Solution 1: Sorting + Two Pointers We can sort the free time of the two people separately, then use two pointers to traverse the two arrays, find the intersection of the free time periods of the two people, and if the length of the intersection is greater than or equal to `duration`, then return the start time of the intersection and the start time plus `duration`. @@ -49,8 +49,6 @@ The time complexity is $O(m \times \log m + n \times \log n)$, and the space com -### **Python3** - ```python class Solution: def minAvailableDuration( @@ -72,8 +70,6 @@ class Solution: return [] ``` -### **Java** - ```java class Solution { public List minAvailableDuration(int[][] slots1, int[][] slots2, int duration) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,7 +119,26 @@ public: }; ``` -### **Rust** +```go +func minAvailableDuration(slots1 [][]int, slots2 [][]int, duration int) []int { + sort.Slice(slots1, func(i, j int) bool { return slots1[i][0] < slots1[j][0] }) + sort.Slice(slots2, func(i, j int) bool { return slots2[i][0] < slots2[j][0] }) + i, j, m, n := 0, 0, len(slots1), len(slots2) + for i < m && j < n { + start := max(slots1[i][0], slots2[j][0]) + end := min(slots1[i][1], slots2[j][1]) + if end-start >= duration { + return []int{start, start + duration} + } + if slots1[i][1] < slots2[j][1] { + i++ + } else { + j++ + } + } + return []int{} +} +``` ```rust impl Solution { @@ -175,33 +188,6 @@ impl Solution { } ``` -### **Go** - -```go -func minAvailableDuration(slots1 [][]int, slots2 [][]int, duration int) []int { - sort.Slice(slots1, func(i, j int) bool { return slots1[i][0] < slots1[j][0] }) - sort.Slice(slots2, func(i, j int) bool { return slots2[i][0] < slots2[j][0] }) - i, j, m, n := 0, 0, len(slots1), len(slots2) - for i < m && j < n { - start := max(slots1[i][0], slots2[j][0]) - end := min(slots1[i][1], slots2[j][1]) - if end-start >= duration { - return []int{start, start + duration} - } - if slots1[i][1] < slots2[j][1] { - i++ - } else { - j++ - } - } - return []int{} -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1230.Toss Strange Coins/README.md b/solution/1200-1299/1230.Toss Strange Coins/README.md index 9cd3fdbba0b68..7315beb78fa45 100644 --- a/solution/1200-1299/1230.Toss Strange Coins/README.md +++ b/solution/1200-1299/1230.Toss Strange Coins/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示前 $i$ 枚硬币中有 $j$ 枚正面朝上的概率,初始时 $f[0][0]=1$,答案即为 $f[n][target]$。 @@ -60,10 +58,6 @@ $$ -### **Python3** - - - ```python class Solution: def probabilityOfHeads(self, prob: List[float], target: int) -> float: @@ -78,23 +72,6 @@ class Solution: return f[n][target] ``` -```python -class Solution: - def probabilityOfHeads(self, prob: List[float], target: int) -> float: - f = [0] * (target + 1) - f[0] = 1 - for p in prob: - for j in range(target, -1, -1): - f[j] *= 1 - p - if j: - f[j] += p * f[j - 1] - return f[target] -``` - -### **Java** - - - ```java class Solution { public double probabilityOfHeads(double[] prob, int target) { @@ -114,26 +91,6 @@ class Solution { } ``` -```java -class Solution { - public double probabilityOfHeads(double[] prob, int target) { - double[] f = new double[target + 1]; - f[0] = 1; - for (double p : prob) { - for (int j = target; j >= 0; --j) { - f[j] *= (1 - p); - if (j > 0) { - f[j] += p * f[j - 1]; - } - } - } - return f[target]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -155,28 +112,6 @@ public: }; ``` -```cpp -class Solution { -public: - double probabilityOfHeads(vector& prob, int target) { - double f[target + 1]; - memset(f, 0, sizeof(f)); - f[0] = 1; - for (double p : prob) { - for (int j = target; j >= 0; --j) { - f[j] *= (1 - p); - if (j > 0) { - f[j] += p * f[j - 1]; - } - } - } - return f[target]; - } -}; -``` - -### **Go** - ```go func probabilityOfHeads(prob []float64, target int) float64 { n := len(prob) @@ -197,24 +132,6 @@ func probabilityOfHeads(prob []float64, target int) float64 { } ``` -```go -func probabilityOfHeads(prob []float64, target int) float64 { - f := make([]float64, target+1) - f[0] = 1 - for _, p := range prob { - for j := target; j >= 0; j-- { - f[j] *= (1 - p) - if j > 0 { - f[j] += p * f[j-1] - } - } - } - return f[target] -} -``` - -### **TypeScript** - ```ts function probabilityOfHeads(prob: number[], target: number): number { const n = prob.length; @@ -232,6 +149,79 @@ function probabilityOfHeads(prob: number[], target: number): number { } ``` + + +### 方法二 + + + +```python +class Solution: + def probabilityOfHeads(self, prob: List[float], target: int) -> float: + f = [0] * (target + 1) + f[0] = 1 + for p in prob: + for j in range(target, -1, -1): + f[j] *= 1 - p + if j: + f[j] += p * f[j - 1] + return f[target] +``` + +```java +class Solution { + public double probabilityOfHeads(double[] prob, int target) { + double[] f = new double[target + 1]; + f[0] = 1; + for (double p : prob) { + for (int j = target; j >= 0; --j) { + f[j] *= (1 - p); + if (j > 0) { + f[j] += p * f[j - 1]; + } + } + } + return f[target]; + } +} +``` + +```cpp +class Solution { +public: + double probabilityOfHeads(vector& prob, int target) { + double f[target + 1]; + memset(f, 0, sizeof(f)); + f[0] = 1; + for (double p : prob) { + for (int j = target; j >= 0; --j) { + f[j] *= (1 - p); + if (j > 0) { + f[j] += p * f[j - 1]; + } + } + } + return f[target]; + } +}; +``` + +```go +func probabilityOfHeads(prob []float64, target int) float64 { + f := make([]float64, target+1) + f[0] = 1 + for _, p := range prob { + for j := target; j >= 0; j-- { + f[j] *= (1 - p) + if j > 0 { + f[j] += p * f[j-1] + } + } + } + return f[target] +} +``` + ```ts function probabilityOfHeads(prob: number[], target: number): number { const f = new Array(target + 1).fill(0); @@ -248,10 +238,6 @@ function probabilityOfHeads(prob: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1230.Toss Strange Coins/README_EN.md b/solution/1200-1299/1230.Toss Strange Coins/README_EN.md index 995a25c22d072..9375be7e4c885 100644 --- a/solution/1200-1299/1230.Toss Strange Coins/README_EN.md +++ b/solution/1200-1299/1230.Toss Strange Coins/README_EN.md @@ -28,7 +28,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming Let $f[i][j]$ represent the probability of having $j$ coins facing up in the first $i$ coins, and initially $f[0][0]=1$. The answer is $f[n][target]$. @@ -49,8 +49,6 @@ The time complexity is $O(n \times target)$, and the space complexity is $O(targ -### **Python3** - ```python class Solution: def probabilityOfHeads(self, prob: List[float], target: int) -> float: @@ -65,21 +63,6 @@ class Solution: return f[n][target] ``` -```python -class Solution: - def probabilityOfHeads(self, prob: List[float], target: int) -> float: - f = [0] * (target + 1) - f[0] = 1 - for p in prob: - for j in range(target, -1, -1): - f[j] *= 1 - p - if j: - f[j] += p * f[j - 1] - return f[target] -``` - -### **Java** - ```java class Solution { public double probabilityOfHeads(double[] prob, int target) { @@ -99,26 +82,6 @@ class Solution { } ``` -```java -class Solution { - public double probabilityOfHeads(double[] prob, int target) { - double[] f = new double[target + 1]; - f[0] = 1; - for (double p : prob) { - for (int j = target; j >= 0; --j) { - f[j] *= (1 - p); - if (j > 0) { - f[j] += p * f[j - 1]; - } - } - } - return f[target]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -140,28 +103,6 @@ public: }; ``` -```cpp -class Solution { -public: - double probabilityOfHeads(vector& prob, int target) { - double f[target + 1]; - memset(f, 0, sizeof(f)); - f[0] = 1; - for (double p : prob) { - for (int j = target; j >= 0; --j) { - f[j] *= (1 - p); - if (j > 0) { - f[j] += p * f[j - 1]; - } - } - } - return f[target]; - } -}; -``` - -### **Go** - ```go func probabilityOfHeads(prob []float64, target int) float64 { n := len(prob) @@ -182,24 +123,6 @@ func probabilityOfHeads(prob []float64, target int) float64 { } ``` -```go -func probabilityOfHeads(prob []float64, target int) float64 { - f := make([]float64, target+1) - f[0] = 1 - for _, p := range prob { - for j := target; j >= 0; j-- { - f[j] *= (1 - p) - if j > 0 { - f[j] += p * f[j-1] - } - } - } - return f[target] -} -``` - -### **TypeScript** - ```ts function probabilityOfHeads(prob: number[], target: number): number { const n = prob.length; @@ -217,6 +140,79 @@ function probabilityOfHeads(prob: number[], target: number): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def probabilityOfHeads(self, prob: List[float], target: int) -> float: + f = [0] * (target + 1) + f[0] = 1 + for p in prob: + for j in range(target, -1, -1): + f[j] *= 1 - p + if j: + f[j] += p * f[j - 1] + return f[target] +``` + +```java +class Solution { + public double probabilityOfHeads(double[] prob, int target) { + double[] f = new double[target + 1]; + f[0] = 1; + for (double p : prob) { + for (int j = target; j >= 0; --j) { + f[j] *= (1 - p); + if (j > 0) { + f[j] += p * f[j - 1]; + } + } + } + return f[target]; + } +} +``` + +```cpp +class Solution { +public: + double probabilityOfHeads(vector& prob, int target) { + double f[target + 1]; + memset(f, 0, sizeof(f)); + f[0] = 1; + for (double p : prob) { + for (int j = target; j >= 0; --j) { + f[j] *= (1 - p); + if (j > 0) { + f[j] += p * f[j - 1]; + } + } + } + return f[target]; + } +}; +``` + +```go +func probabilityOfHeads(prob []float64, target int) float64 { + f := make([]float64, target+1) + f[0] = 1 + for _, p := range prob { + for j := target; j >= 0; j-- { + f[j] *= (1 - p) + if j > 0 { + f[j] += p * f[j-1] + } + } + } + return f[target] +} +``` + ```ts function probabilityOfHeads(prob: number[], target: number): number { const f = new Array(target + 1).fill(0); @@ -233,10 +229,6 @@ function probabilityOfHeads(prob: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1231.Divide Chocolate/README.md b/solution/1200-1299/1231.Divide Chocolate/README.md index c5042c3b627af..c85f5ad50e8bd 100644 --- a/solution/1200-1299/1231.Divide Chocolate/README.md +++ b/solution/1200-1299/1231.Divide Chocolate/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:二分查找 + 贪心** +### 方法一:二分查找 + 贪心 我们注意到,如果我们能吃到一块甜度为 $x$ 的巧克力,那么甜度小于等于 $x$ 的巧克力也都能吃到。这存在着单调性,因此,我们可以使用二分查找,找到最大的满足条件的 $x$。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def maximizeSweetness(self, sweetness: List[int], k: int) -> int: @@ -88,10 +82,6 @@ class Solution: return l ``` -### **Java** - - - ```java class Solution { public int maximizeSweetness(int[] sweetness, int k) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func maximizeSweetness(sweetness []int, k int) int { l, r := 0, 0 @@ -186,8 +172,6 @@ func maximizeSweetness(sweetness []int, k int) int { } ``` -### **TypeScript** - ```ts function maximizeSweetness(sweetness: number[], k: number): number { let l = 0; @@ -216,10 +200,6 @@ function maximizeSweetness(sweetness: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1231.Divide Chocolate/README_EN.md b/solution/1200-1299/1231.Divide Chocolate/README_EN.md index 6252b46f6f40d..f020e5c2f0f73 100644 --- a/solution/1200-1299/1231.Divide Chocolate/README_EN.md +++ b/solution/1200-1299/1231.Divide Chocolate/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Binary Search + Greedy** +### Solution 1: Binary Search + Greedy We notice that if we can eat a piece of chocolate with sweetness $x$, then we can also eat all chocolates with sweetness less than or equal to $x$. This shows monotonicity, therefore, we can use binary search to find the maximum $x$ that satisfies the condition. @@ -59,8 +59,6 @@ The time complexity is $O(n \times \log \sum_{i=0}^{n-1} sweetness[i])$, and the -### **Python3** - ```python class Solution: def maximizeSweetness(self, sweetness: List[int], k: int) -> int: @@ -83,8 +81,6 @@ class Solution: return l ``` -### **Java** - ```java class Solution { public int maximizeSweetness(int[] sweetness, int k) { @@ -117,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +142,6 @@ public: }; ``` -### **Go** - ```go func maximizeSweetness(sweetness []int, k int) int { l, r := 0, 0 @@ -179,8 +171,6 @@ func maximizeSweetness(sweetness []int, k int) int { } ``` -### **TypeScript** - ```ts function maximizeSweetness(sweetness: number[], k: number): number { let l = 0; @@ -209,10 +199,6 @@ function maximizeSweetness(sweetness: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1232.Check If It Is a Straight Line/README.md b/solution/1200-1299/1232.Check If It Is a Straight Line/README.md index f204998d6c1e8..35b0502f91aff 100644 --- a/solution/1200-1299/1232.Check If It Is a Straight Line/README.md +++ b/solution/1200-1299/1232.Check If It Is a Straight Line/README.md @@ -41,18 +41,12 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 时间复杂度 $O(n)$,其中 $n$ 表示 `coordinates` 数组的长度。空间复杂度 $O(1)$。 -### **Python3** - - - ```python class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: @@ -64,10 +58,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean checkStraightLine(int[][] coordinates) { @@ -84,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +91,6 @@ public: }; ``` -### **Go** - ```go func checkStraightLine(coordinates [][]int) bool { x1, y1 := coordinates[0][0], coordinates[0][1] @@ -119,10 +105,6 @@ func checkStraightLine(coordinates [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1232.Check If It Is a Straight Line/README_EN.md b/solution/1200-1299/1232.Check If It Is a Straight Line/README_EN.md index 701db7daa3b58..5fe165db5fcca 100644 --- a/solution/1200-1299/1232.Check If It Is a Straight Line/README_EN.md +++ b/solution/1200-1299/1232.Check If It Is a Straight Line/README_EN.md @@ -39,14 +39,12 @@ ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics The time complexity is $O(n)$, where $n$ is the length of the `coordinates` array. The space complexity is $O(1)$. -### **Python3** - ```python class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: @@ -58,8 +56,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean checkStraightLine(int[][] coordinates) { @@ -76,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +89,6 @@ public: }; ``` -### **Go** - ```go func checkStraightLine(coordinates [][]int) bool { x1, y1 := coordinates[0][0], coordinates[0][1] @@ -111,10 +103,6 @@ func checkStraightLine(coordinates [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/README.md b/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/README.md index 74de2121dc369..e8ba31df6ea5b 100644 --- a/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/README.md +++ b/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们先将数组 `folder` 按照字典序排序,然后遍历数组,对于当前遍历到的文件夹 $f$,如果它的长度大于等于答案数组中最后一个文件夹的长度,并且它的前缀包含答案数组的最后一个文件夹再加上一个 `/`,则说明 $f$ 是答案数组中最后一个文件夹的子文件夹,我们不需要将其加入答案数组中。否则,我们将 $f$ 加入答案数组中。 @@ -64,20 +62,8 @@ 时间复杂度 $O(n \times \log n \times m)$,空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别为数组 `folder` 的长度和数组 `folder` 中字符串的最大长度。 -**方法二:字典树** - -我们可以使用字典树存储数组 `folder` 中的所有文件夹。字典树的每个节点包含 `children` 字段,用于存储当前节点的子节点,以及 `fid` 字段,用于存储当前节点对应的文件夹在数组 `folder` 中的下标。 - -对于数组 `folder` 中的每个文件夹 $f$,我们先将 $f$ 按照 `/` 分割成若干个子串,然后从根节点开始,依次将子串加入字典树中。接下来,我们从根节点开始搜索字典树,如果当前节点的 `fid` 字段不为 `-1`,则说明当前节点对应的文件夹是答案数组中的一个文件夹,我们将其加入答案数组并且返回。否则,我们递归地搜索当前节点的所有子节点,最终返回答案数组。 - -时间复杂度 $O(n \times m)$,空间复杂度 $O(n \times m)$。其中 $n$ 和 $m$ 分别为数组 `folder` 的长度和数组 `folder` 中字符串的最大长度。 - -### **Python3** - - - ```python class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: @@ -90,6 +76,70 @@ class Solution: return ans ``` +```java +class Solution { + public List removeSubfolders(String[] folder) { + Arrays.sort(folder); + List ans = new ArrayList<>(); + ans.add(folder[0]); + for (int i = 1; i < folder.length; ++i) { + int m = ans.get(ans.size() - 1).length(); + int n = folder[i].length(); + if (m >= n + || !(ans.get(ans.size() - 1).equals(folder[i].substring(0, m)) + && folder[i].charAt(m) == '/')) { + ans.add(folder[i]); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector removeSubfolders(vector& folder) { + sort(folder.begin(), folder.end()); + vector ans = {folder[0]}; + for (int i = 1; i < folder.size(); ++i) { + int m = ans.back().size(); + int n = folder[i].size(); + if (m >= n || !(ans.back() == folder[i].substr(0, m) && folder[i][m] == '/')) { + ans.emplace_back(folder[i]); + } + } + return ans; + } +}; +``` + +```go +func removeSubfolders(folder []string) []string { + sort.Strings(folder) + ans := []string{folder[0]} + for _, f := range folder[1:] { + m, n := len(ans[len(ans)-1]), len(f) + if m >= n || !(ans[len(ans)-1] == f[:m] && f[m] == '/') { + ans = append(ans, f) + } + } + return ans +} +``` + + + +### 方法二:字典树 + +我们可以使用字典树存储数组 `folder` 中的所有文件夹。字典树的每个节点包含 `children` 字段,用于存储当前节点的子节点,以及 `fid` 字段,用于存储当前节点对应的文件夹在数组 `folder` 中的下标。 + +对于数组 `folder` 中的每个文件夹 $f$,我们先将 $f$ 按照 `/` 分割成若干个子串,然后从根节点开始,依次将子串加入字典树中。接下来,我们从根节点开始搜索字典树,如果当前节点的 `fid` 字段不为 `-1`,则说明当前节点对应的文件夹是答案数组中的一个文件夹,我们将其加入答案数组并且返回。否则,我们递归地搜索当前节点的所有子节点,最终返回答案数组。 + +时间复杂度 $O(n \times m)$,空间复杂度 $O(n \times m)$。其中 $n$ 和 $m$ 分别为数组 `folder` 的长度和数组 `folder` 中字符串的最大长度。 + + + ```python class Trie: def __init__(self): @@ -126,30 +176,6 @@ class Solution: return [folder[i] for i in trie.search()] ``` -### **Java** - - - -```java -class Solution { - public List removeSubfolders(String[] folder) { - Arrays.sort(folder); - List ans = new ArrayList<>(); - ans.add(folder[0]); - for (int i = 1; i < folder.length; ++i) { - int m = ans.get(ans.size() - 1).length(); - int n = folder[i].length(); - if (m >= n - || !(ans.get(ans.size() - 1).equals(folder[i].substring(0, m)) - && folder[i].charAt(m) == '/')) { - ans.add(folder[i]); - } - } - return ans; - } -} -``` - ```java class Trie { private Map children = new HashMap<>(); @@ -200,26 +226,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector removeSubfolders(vector& folder) { - sort(folder.begin(), folder.end()); - vector ans = {folder[0]}; - for (int i = 1; i < folder.size(); ++i) { - int m = ans.back().size(); - int n = folder[i].size(); - if (m >= n || !(ans.back() == folder[i].substr(0, m) && folder[i][m] == '/')) { - ans.emplace_back(folder[i]); - } - } - return ans; - } -}; -``` - ```cpp class Trie { public: @@ -282,22 +288,6 @@ public: }; ``` -### **Go** - -```go -func removeSubfolders(folder []string) []string { - sort.Strings(folder) - ans := []string{folder[0]} - for _, f := range folder[1:] { - m, n := len(ans[len(ans)-1]), len(f) - if m >= n || !(ans[len(ans)-1] == f[:m] && f[m] == '/') { - ans = append(ans, f) - } - } - return ans -} -``` - ```go type Trie struct { children map[string]*Trie @@ -350,6 +340,12 @@ func removeSubfolders(folder []string) []string { } ``` + + +### 方法三 + + + ```go type Trie struct { children map[string]*Trie @@ -399,10 +395,6 @@ func removeSubfolders(folder []string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/README_EN.md b/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/README_EN.md index 2f05c75d3e02e..c44593e308f4f 100644 --- a/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/README_EN.md +++ b/solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/README_EN.md @@ -51,7 +51,7 @@ ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting First, we sort the array `folder` in lexicographical order, then traverse the array. For the current folder $f$ we are traversing, if its length is greater than or equal to the length of the last folder in the answer array, and its prefix includes the last folder in the answer array plus a `/`, then $f$ is a subfolder of the last folder in the answer array, and we don't need to add it to the answer array. Otherwise, we add $f$ to the answer array. @@ -59,18 +59,8 @@ After the traversal ends, the folders in the answer array are the answer require The time complexity is $O(n \times \log n \times m)$, and the space complexity is $O(m)$. Where $n$ and $m$ are the length of the array `folder` and the maximum length of the strings in the array `folder`, respectively. -**Solution 2: Trie** - -We can use a trie to store all the folders in the array `folder`. Each node of the trie contains a `children` field, used to store the child nodes of the current node, and a `fid` field, used to store the index of the folder corresponding to the current node in the array `folder`. - -For each folder $f$ in the array `folder`, we first split $f$ into several substrings according to `/`, then start from the root node and add the substrings to the trie in turn. Next, we start from the root node to search the trie. If the `fid` field of the current node is not `-1`, it means that the folder corresponding to the current node is a folder in the answer array. We add it to the answer array and return. Otherwise, we recursively search all child nodes of the current node and finally return the answer array. - -The time complexity is $O(n \times m)$, and the space complexity is $O(n \times m)$. Where $n$ and $m$ are the length of the array `folder` and the maximum length of the strings in the array `folder`, respectively. - -### **Python3** - ```python class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: @@ -83,6 +73,70 @@ class Solution: return ans ``` +```java +class Solution { + public List removeSubfolders(String[] folder) { + Arrays.sort(folder); + List ans = new ArrayList<>(); + ans.add(folder[0]); + for (int i = 1; i < folder.length; ++i) { + int m = ans.get(ans.size() - 1).length(); + int n = folder[i].length(); + if (m >= n + || !(ans.get(ans.size() - 1).equals(folder[i].substring(0, m)) + && folder[i].charAt(m) == '/')) { + ans.add(folder[i]); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector removeSubfolders(vector& folder) { + sort(folder.begin(), folder.end()); + vector ans = {folder[0]}; + for (int i = 1; i < folder.size(); ++i) { + int m = ans.back().size(); + int n = folder[i].size(); + if (m >= n || !(ans.back() == folder[i].substr(0, m) && folder[i][m] == '/')) { + ans.emplace_back(folder[i]); + } + } + return ans; + } +}; +``` + +```go +func removeSubfolders(folder []string) []string { + sort.Strings(folder) + ans := []string{folder[0]} + for _, f := range folder[1:] { + m, n := len(ans[len(ans)-1]), len(f) + if m >= n || !(ans[len(ans)-1] == f[:m] && f[m] == '/') { + ans = append(ans, f) + } + } + return ans +} +``` + + + +### Solution 2: Trie + +We can use a trie to store all the folders in the array `folder`. Each node of the trie contains a `children` field, used to store the child nodes of the current node, and a `fid` field, used to store the index of the folder corresponding to the current node in the array `folder`. + +For each folder $f$ in the array `folder`, we first split $f$ into several substrings according to `/`, then start from the root node and add the substrings to the trie in turn. Next, we start from the root node to search the trie. If the `fid` field of the current node is not `-1`, it means that the folder corresponding to the current node is a folder in the answer array. We add it to the answer array and return. Otherwise, we recursively search all child nodes of the current node and finally return the answer array. + +The time complexity is $O(n \times m)$, and the space complexity is $O(n \times m)$. Where $n$ and $m$ are the length of the array `folder` and the maximum length of the strings in the array `folder`, respectively. + + + ```python class Trie: def __init__(self): @@ -119,28 +173,6 @@ class Solution: return [folder[i] for i in trie.search()] ``` -### **Java** - -```java -class Solution { - public List removeSubfolders(String[] folder) { - Arrays.sort(folder); - List ans = new ArrayList<>(); - ans.add(folder[0]); - for (int i = 1; i < folder.length; ++i) { - int m = ans.get(ans.size() - 1).length(); - int n = folder[i].length(); - if (m >= n - || !(ans.get(ans.size() - 1).equals(folder[i].substring(0, m)) - && folder[i].charAt(m) == '/')) { - ans.add(folder[i]); - } - } - return ans; - } -} -``` - ```java class Trie { private Map children = new HashMap<>(); @@ -191,26 +223,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector removeSubfolders(vector& folder) { - sort(folder.begin(), folder.end()); - vector ans = {folder[0]}; - for (int i = 1; i < folder.size(); ++i) { - int m = ans.back().size(); - int n = folder[i].size(); - if (m >= n || !(ans.back() == folder[i].substr(0, m) && folder[i][m] == '/')) { - ans.emplace_back(folder[i]); - } - } - return ans; - } -}; -``` - ```cpp class Trie { public: @@ -273,22 +285,64 @@ public: }; ``` -### **Go** - ```go +type Trie struct { + children map[string]*Trie + isEnd bool +} + +func newTrie() *Trie { + m := map[string]*Trie{} + return &Trie{children: m} +} + +func (this *Trie) insert(w string) { + node := this + for _, p := range strings.Split(w, "/")[1:] { + if _, ok := node.children[p]; !ok { + node.children[p] = newTrie() + } + node, _ = node.children[p] + } + node.isEnd = true +} + +func (this *Trie) search(w string) bool { + node := this + for _, p := range strings.Split(w, "/")[1:] { + if _, ok := node.children[p]; !ok { + return false + } + node, _ = node.children[p] + if node.isEnd { + return true + } + } + return false +} + func removeSubfolders(folder []string) []string { - sort.Strings(folder) - ans := []string{folder[0]} - for _, f := range folder[1:] { - m, n := len(ans[len(ans)-1]), len(f) - if m >= n || !(ans[len(ans)-1] == f[:m] && f[m] == '/') { - ans = append(ans, f) + sort.Slice(folder, func(i, j int) bool { + return len(strings.Split(folder[i], "/")) < len(strings.Split(folder[j], "/")) + }) + trie := newTrie() + var ans []string + for _, v := range folder { + if !trie.search(v) { + trie.insert(v) + ans = append(ans, v) } } return ans } ``` + + +### Solution 3 + + + ```go type Trie struct { children map[string]*Trie @@ -338,10 +392,6 @@ func removeSubfolders(folder []string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1234.Replace the Substring for Balanced String/README.md b/solution/1200-1299/1234.Replace the Substring for Balanced String/README.md index 665799c6f437b..fe3cc870db7fe 100644 --- a/solution/1200-1299/1234.Replace the Substring for Balanced String/README.md +++ b/solution/1200-1299/1234.Replace the Substring for Balanced String/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:计数 + 双指针** +### 方法一:计数 + 双指针 我们先用一个哈希表或数组 `cnt` 统计字符串 $s$ 中每个字符的数量,如果所有字符的数量都不超过 $n/4$,那么字符串 $s$ 就是平衡字符串,直接返回 $0$。 @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def balancedString(self, s: str) -> int: @@ -102,10 +96,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int balancedString(String s) { @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go func balancedString(s string) int { cnt := [4]int{} @@ -188,10 +174,6 @@ func balancedString(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1234.Replace the Substring for Balanced String/README_EN.md b/solution/1200-1299/1234.Replace the Substring for Balanced String/README_EN.md index 5a552a908bbae..013d1df827fd5 100644 --- a/solution/1200-1299/1234.Replace the Substring for Balanced String/README_EN.md +++ b/solution/1200-1299/1234.Replace the Substring for Balanced String/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Counting + Two Pointers** +### Solution 1: Counting + Two Pointers First, we use a hash table or array `cnt` to count the number of each character in string $s$. If the count of all characters does not exceed $n/4$, then the string $s$ is balanced, and we directly return $0$. @@ -61,8 +61,6 @@ The time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is -### **Python3** - ```python class Solution: def balancedString(self, s: str) -> int: @@ -80,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int balancedString(String s) { @@ -108,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +131,6 @@ public: }; ``` -### **Go** - ```go func balancedString(s string) int { cnt := [4]int{} @@ -164,10 +156,6 @@ func balancedString(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/README.md b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/README.md index 8c2de343cc417..721e4e92a7f66 100644 --- a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/README.md +++ b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:记忆化搜索 + 二分查找** +### 方法一:记忆化搜索 + 二分查找 我们先将工作按照开始时间从小到大排序,然后设计一个函数 $dfs(i)$ 表示从第 $i$ 份工作开始,可以获得的最大报酬。答案即为 $dfs(0)$。 @@ -80,33 +78,8 @@ $$ 时间复杂度 $O(n \times \log n)$,其中 $n$ 是工作的数量。 -**方法二:动态规划 + 二分查找** - -我们还可以将方法一中的记忆化搜索改为动态规划。 - -先将工作排序,这次我们按照结束时间从小到大排序,然后定义 $dp[i]$,表示前 $i$ 份工作中,可以获得的最大报酬。答案即为 $dp[n]$。初始化 $dp[0]=0$。 - -对于第 $i$ 份工作,我们可以选择做,也可以选择不做。如果不做,最大报酬就是 $dp[i]$;如果做,我们可以通过二分查找,找到在第 $i$ 份工作开始时间之前结束的最后一份工作,记为 $j$,那么最大报酬就是 $profit[i] + dp[j]$。取两者的较大值即可。即: - -$$ -dp[i+1] = \max(dp[i], profit[i] + dp[j]) -$$ - -其中 $j$ 是满足 $endTime[j] \leq startTime[i]$ 的最大的下标。 - -时间复杂度 $O(n \times \log n)$,其中 $n$ 是工作的数量。 - -相似题目: - -- [2008. 出租车的最大盈利](/solution/2000-2099/2008.Maximum%20Earnings%20From%20Taxi/README.md) -- [1751. 最多可以参加的会议数目 II](/solution/1700-1799/1751.Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended%20II/README.md) - -### **Python3** - - - ```python class Solution: def jobScheduling( @@ -125,41 +98,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def jobScheduling( - self, startTime: List[int], endTime: List[int], profit: List[int] - ) -> int: - @cache - def dfs(i: int) -> int: - if i >= n: - return 0 - j = bisect_left(idx, endTime[idx[i]], key=lambda i: startTime[i]) - return max(dfs(i + 1), profit[idx[i]] + dfs(j)) - - n = len(startTime) - idx = sorted(range(n), key=lambda i: startTime[i]) - return dfs(0) -``` - -```python -class Solution: - def jobScheduling( - self, startTime: List[int], endTime: List[int], profit: List[int] - ) -> int: - jobs = sorted(zip(endTime, startTime, profit)) - n = len(profit) - dp = [0] * (n + 1) - for i, (_, s, p) in enumerate(jobs): - j = bisect_right(jobs, s, hi=i, key=lambda x: x[0]) - dp[i + 1] = max(dp[i], dp[j] + p) - return dp[n] -``` - -### **Java** - - - ```java class Solution { private int[][] jobs; @@ -206,40 +144,6 @@ class Solution { } ``` -```java -class Solution { - public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { - int n = profit.length; - int[][] jobs = new int[n][3]; - for (int i = 0; i < n; ++i) { - jobs[i] = new int[] {startTime[i], endTime[i], profit[i]}; - } - Arrays.sort(jobs, (a, b) -> a[1] - b[1]); - int[] dp = new int[n + 1]; - for (int i = 0; i < n; ++i) { - int j = search(jobs, jobs[i][0], i); - dp[i + 1] = Math.max(dp[i], dp[j] + jobs[i][2]); - } - return dp[n]; - } - - private int search(int[][] jobs, int x, int n) { - int left = 0, right = n; - while (left < right) { - int mid = (left + right) >> 1; - if (jobs[mid][1] > x) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -264,27 +168,6 @@ public: }; ``` -```cpp -class Solution { -public: - int jobScheduling(vector& startTime, vector& endTime, vector& profit) { - int n = profit.size(); - vector> jobs(n); - for (int i = 0; i < n; ++i) jobs[i] = {endTime[i], startTime[i], profit[i]}; - sort(jobs.begin(), jobs.end()); - vector dp(n + 1); - for (int i = 0; i < n; ++i) { - auto [_, s, p] = jobs[i]; - int j = upper_bound(jobs.begin(), jobs.begin() + i, s, [&](int x, auto& job) -> bool { return x < get<0>(job); }) - jobs.begin(); - dp[i + 1] = max(dp[i], dp[j] + p); - } - return dp[n]; - } -}; -``` - -### **Go** - ```go func jobScheduling(startTime []int, endTime []int, profit []int) int { n := len(profit) @@ -312,26 +195,6 @@ func jobScheduling(startTime []int, endTime []int, profit []int) int { } ``` -```go -func jobScheduling(startTime []int, endTime []int, profit []int) int { - n := len(profit) - type tuple struct{ s, e, p int } - jobs := make([]tuple, n) - for i, p := range profit { - jobs[i] = tuple{startTime[i], endTime[i], p} - } - sort.Slice(jobs, func(i, j int) bool { return jobs[i].e < jobs[j].e }) - dp := make([]int, n+1) - for i, job := range jobs { - j := sort.Search(i, func(k int) bool { return jobs[k].e > job.s }) - dp[i+1] = max(dp[i], dp[j]+job.p) - } - return dp[n] -} -``` - -### **TypeScript** - ```ts function jobScheduling(startTime: number[], endTime: number[], profit: number[]): number { const n = startTime.length; @@ -365,10 +228,137 @@ function jobScheduling(startTime: number[], endTime: number[], profit: number[]) } ``` -### **...** + + +### 方法二:动态规划 + 二分查找 + +我们还可以将方法一中的记忆化搜索改为动态规划。 + +先将工作排序,这次我们按照结束时间从小到大排序,然后定义 $dp[i]$,表示前 $i$ 份工作中,可以获得的最大报酬。答案即为 $dp[n]$。初始化 $dp[0]=0$。 + +对于第 $i$ 份工作,我们可以选择做,也可以选择不做。如果不做,最大报酬就是 $dp[i]$;如果做,我们可以通过二分查找,找到在第 $i$ 份工作开始时间之前结束的最后一份工作,记为 $j$,那么最大报酬就是 $profit[i] + dp[j]$。取两者的较大值即可。即: + +$$ +dp[i+1] = \max(dp[i], profit[i] + dp[j]) +$$ + +其中 $j$ 是满足 $endTime[j] \leq startTime[i]$ 的最大的下标。 + +时间复杂度 $O(n \times \log n)$,其中 $n$ 是工作的数量。 + +相似题目: + +- [2008. 出租车的最大盈利](/solution/2000-2099/2008.Maximum%20Earnings%20From%20Taxi/README.md) +- [1751. 最多可以参加的会议数目 II](/solution/1700-1799/1751.Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended%20II/README.md) + + + +```python +class Solution: + def jobScheduling( + self, startTime: List[int], endTime: List[int], profit: List[int] + ) -> int: + @cache + def dfs(i: int) -> int: + if i >= n: + return 0 + j = bisect_left(idx, endTime[idx[i]], key=lambda i: startTime[i]) + return max(dfs(i + 1), profit[idx[i]] + dfs(j)) + + n = len(startTime) + idx = sorted(range(n), key=lambda i: startTime[i]) + return dfs(0) +``` + +```java +class Solution { + public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { + int n = profit.length; + int[][] jobs = new int[n][3]; + for (int i = 0; i < n; ++i) { + jobs[i] = new int[] {startTime[i], endTime[i], profit[i]}; + } + Arrays.sort(jobs, (a, b) -> a[1] - b[1]); + int[] dp = new int[n + 1]; + for (int i = 0; i < n; ++i) { + int j = search(jobs, jobs[i][0], i); + dp[i + 1] = Math.max(dp[i], dp[j] + jobs[i][2]); + } + return dp[n]; + } + + private int search(int[][] jobs, int x, int n) { + int left = 0, right = n; + while (left < right) { + int mid = (left + right) >> 1; + if (jobs[mid][1] > x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +```cpp +class Solution { +public: + int jobScheduling(vector& startTime, vector& endTime, vector& profit) { + int n = profit.size(); + vector> jobs(n); + for (int i = 0; i < n; ++i) jobs[i] = {endTime[i], startTime[i], profit[i]}; + sort(jobs.begin(), jobs.end()); + vector dp(n + 1); + for (int i = 0; i < n; ++i) { + auto [_, s, p] = jobs[i]; + int j = upper_bound(jobs.begin(), jobs.begin() + i, s, [&](int x, auto& job) -> bool { return x < get<0>(job); }) - jobs.begin(); + dp[i + 1] = max(dp[i], dp[j] + p); + } + return dp[n]; + } +}; +``` +```go +func jobScheduling(startTime []int, endTime []int, profit []int) int { + n := len(profit) + type tuple struct{ s, e, p int } + jobs := make([]tuple, n) + for i, p := range profit { + jobs[i] = tuple{startTime[i], endTime[i], p} + } + sort.Slice(jobs, func(i, j int) bool { return jobs[i].e < jobs[j].e }) + dp := make([]int, n+1) + for i, job := range jobs { + j := sort.Search(i, func(k int) bool { return jobs[k].e > job.s }) + dp[i+1] = max(dp[i], dp[j]+job.p) + } + return dp[n] +} ``` + + +### 方法三 + + + +```python +class Solution: + def jobScheduling( + self, startTime: List[int], endTime: List[int], profit: List[int] + ) -> int: + jobs = sorted(zip(endTime, startTime, profit)) + n = len(profit) + dp = [0] * (n + 1) + for i, (_, s, p) in enumerate(jobs): + j = bisect_right(jobs, s, hi=i, key=lambda x: x[0]) + dp[i + 1] = max(dp[i], dp[j] + p) + return dp[n] ``` + + diff --git a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/README_EN.md b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/README_EN.md index f857ac2073c94..32da60afcfa61 100644 --- a/solution/1200-1299/1235.Maximum Profit in Job Scheduling/README_EN.md +++ b/solution/1200-1299/1235.Maximum Profit in Job Scheduling/README_EN.md @@ -53,7 +53,7 @@ Profit obtained 150 = 20 + 70 + 60. ## Solutions -**Solution 1: Memoization Search + Binary Search** +### Solution 1: Memoization Search + Binary Search First, we sort the jobs by start time in ascending order, then design a function $dfs(i)$ to represent the maximum profit that can be obtained starting from the $i$-th job. The answer is $dfs(0)$. @@ -71,31 +71,8 @@ In this process, we can use memoization search to save the answer of each state The time complexity is $O(n \times \log n)$, where $n$ is the number of jobs. -**Solution 2: Dynamic Programming + Binary Search** - -We can also change the memoization search in Solution 1 to dynamic programming. - -First, sort the jobs, this time we sort by end time in ascending order, then define $dp[i]$, which represents the maximum profit that can be obtained from the first $i$ jobs. The answer is $dp[n]$. Initialize $dp[0]=0$. - -For the $i$-th job, we can choose to do it or not. If we don't do it, the maximum profit is $dp[i]$; if we do it, we can use binary search to find the last job that ends before the start time of the $i$-th job, denoted as $j$, then the maximum profit is $profit[i] + dp[j]$. We take the larger of the two. That is: - -$$ -dp[i+1] = \max(dp[i], profit[i] + dp[j]) -$$ - -Where $j$ is the largest index that satisfies $endTime[j] \leq startTime[i]$. - -The time complexity is $O(n \times \log n)$, where $n$ is the number of jobs. - -Similar problems: - -- [2008. Maximum Earnings From Taxi](/solution/2000-2099/2008.Maximum%20Earnings%20From%20Taxi/README.md) -- [1751. Maximum Number of Events That Can Be Attended II](/solution/1700-1799/1751.Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended%20II/README.md) - -### **Python3** - ```python class Solution: def jobScheduling( @@ -114,39 +91,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def jobScheduling( - self, startTime: List[int], endTime: List[int], profit: List[int] - ) -> int: - @cache - def dfs(i: int) -> int: - if i >= n: - return 0 - j = bisect_left(idx, endTime[idx[i]], key=lambda i: startTime[i]) - return max(dfs(i + 1), profit[idx[i]] + dfs(j)) - - n = len(startTime) - idx = sorted(range(n), key=lambda i: startTime[i]) - return dfs(0) -``` - -```python -class Solution: - def jobScheduling( - self, startTime: List[int], endTime: List[int], profit: List[int] - ) -> int: - jobs = sorted(zip(endTime, startTime, profit)) - n = len(profit) - dp = [0] * (n + 1) - for i, (_, s, p) in enumerate(jobs): - j = bisect_right(jobs, s, hi=i, key=lambda x: x[0]) - dp[i + 1] = max(dp[i], dp[j] + p) - return dp[n] -``` - -### **Java** - ```java class Solution { private int[][] jobs; @@ -193,40 +137,6 @@ class Solution { } ``` -```java -class Solution { - public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { - int n = profit.length; - int[][] jobs = new int[n][3]; - for (int i = 0; i < n; ++i) { - jobs[i] = new int[] {startTime[i], endTime[i], profit[i]}; - } - Arrays.sort(jobs, (a, b) -> a[1] - b[1]); - int[] dp = new int[n + 1]; - for (int i = 0; i < n; ++i) { - int j = search(jobs, jobs[i][0], i); - dp[i + 1] = Math.max(dp[i], dp[j] + jobs[i][2]); - } - return dp[n]; - } - - private int search(int[][] jobs, int x, int n) { - int left = 0, right = n; - while (left < right) { - int mid = (left + right) >> 1; - if (jobs[mid][1] > x) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -251,27 +161,6 @@ public: }; ``` -```cpp -class Solution { -public: - int jobScheduling(vector& startTime, vector& endTime, vector& profit) { - int n = profit.size(); - vector> jobs(n); - for (int i = 0; i < n; ++i) jobs[i] = {endTime[i], startTime[i], profit[i]}; - sort(jobs.begin(), jobs.end()); - vector dp(n + 1); - for (int i = 0; i < n; ++i) { - auto [_, s, p] = jobs[i]; - int j = upper_bound(jobs.begin(), jobs.begin() + i, s, [&](int x, auto& job) -> bool { return x < get<0>(job); }) - jobs.begin(); - dp[i + 1] = max(dp[i], dp[j] + p); - } - return dp[n]; - } -}; -``` - -### **Go** - ```go func jobScheduling(startTime []int, endTime []int, profit []int) int { n := len(profit) @@ -299,26 +188,6 @@ func jobScheduling(startTime []int, endTime []int, profit []int) int { } ``` -```go -func jobScheduling(startTime []int, endTime []int, profit []int) int { - n := len(profit) - type tuple struct{ s, e, p int } - jobs := make([]tuple, n) - for i, p := range profit { - jobs[i] = tuple{startTime[i], endTime[i], p} - } - sort.Slice(jobs, func(i, j int) bool { return jobs[i].e < jobs[j].e }) - dp := make([]int, n+1) - for i, job := range jobs { - j := sort.Search(i, func(k int) bool { return jobs[k].e > job.s }) - dp[i+1] = max(dp[i], dp[j]+job.p) - } - return dp[n] -} -``` - -### **TypeScript** - ```ts function jobScheduling(startTime: number[], endTime: number[], profit: number[]): number { const n = startTime.length; @@ -352,10 +221,137 @@ function jobScheduling(startTime: number[], endTime: number[], profit: number[]) } ``` -### **...** + + +### Solution 2: Dynamic Programming + Binary Search + +We can also change the memoization search in Solution 1 to dynamic programming. + +First, sort the jobs, this time we sort by end time in ascending order, then define $dp[i]$, which represents the maximum profit that can be obtained from the first $i$ jobs. The answer is $dp[n]$. Initialize $dp[0]=0$. + +For the $i$-th job, we can choose to do it or not. If we don't do it, the maximum profit is $dp[i]$; if we do it, we can use binary search to find the last job that ends before the start time of the $i$-th job, denoted as $j$, then the maximum profit is $profit[i] + dp[j]$. We take the larger of the two. That is: + +$$ +dp[i+1] = \max(dp[i], profit[i] + dp[j]) +$$ + +Where $j$ is the largest index that satisfies $endTime[j] \leq startTime[i]$. + +The time complexity is $O(n \times \log n)$, where $n$ is the number of jobs. +Similar problems: + +- [2008. Maximum Earnings From Taxi](/solution/2000-2099/2008.Maximum%20Earnings%20From%20Taxi/README.md) +- [1751. Maximum Number of Events That Can Be Attended II](/solution/1700-1799/1751.Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended%20II/README.md) + + + +```python +class Solution: + def jobScheduling( + self, startTime: List[int], endTime: List[int], profit: List[int] + ) -> int: + @cache + def dfs(i: int) -> int: + if i >= n: + return 0 + j = bisect_left(idx, endTime[idx[i]], key=lambda i: startTime[i]) + return max(dfs(i + 1), profit[idx[i]] + dfs(j)) + + n = len(startTime) + idx = sorted(range(n), key=lambda i: startTime[i]) + return dfs(0) ``` +```java +class Solution { + public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { + int n = profit.length; + int[][] jobs = new int[n][3]; + for (int i = 0; i < n; ++i) { + jobs[i] = new int[] {startTime[i], endTime[i], profit[i]}; + } + Arrays.sort(jobs, (a, b) -> a[1] - b[1]); + int[] dp = new int[n + 1]; + for (int i = 0; i < n; ++i) { + int j = search(jobs, jobs[i][0], i); + dp[i + 1] = Math.max(dp[i], dp[j] + jobs[i][2]); + } + return dp[n]; + } + + private int search(int[][] jobs, int x, int n) { + int left = 0, right = n; + while (left < right) { + int mid = (left + right) >> 1; + if (jobs[mid][1] > x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +```cpp +class Solution { +public: + int jobScheduling(vector& startTime, vector& endTime, vector& profit) { + int n = profit.size(); + vector> jobs(n); + for (int i = 0; i < n; ++i) jobs[i] = {endTime[i], startTime[i], profit[i]}; + sort(jobs.begin(), jobs.end()); + vector dp(n + 1); + for (int i = 0; i < n; ++i) { + auto [_, s, p] = jobs[i]; + int j = upper_bound(jobs.begin(), jobs.begin() + i, s, [&](int x, auto& job) -> bool { return x < get<0>(job); }) - jobs.begin(); + dp[i + 1] = max(dp[i], dp[j] + p); + } + return dp[n]; + } +}; +``` + +```go +func jobScheduling(startTime []int, endTime []int, profit []int) int { + n := len(profit) + type tuple struct{ s, e, p int } + jobs := make([]tuple, n) + for i, p := range profit { + jobs[i] = tuple{startTime[i], endTime[i], p} + } + sort.Slice(jobs, func(i, j int) bool { return jobs[i].e < jobs[j].e }) + dp := make([]int, n+1) + for i, job := range jobs { + j := sort.Search(i, func(k int) bool { return jobs[k].e > job.s }) + dp[i+1] = max(dp[i], dp[j]+job.p) + } + return dp[n] +} ``` + +### Solution 3 + + + +```python +class Solution: + def jobScheduling( + self, startTime: List[int], endTime: List[int], profit: List[int] + ) -> int: + jobs = sorted(zip(endTime, startTime, profit)) + n = len(profit) + dp = [0] * (n + 1) + for i, (_, s, p) in enumerate(jobs): + j = bisect_right(jobs, s, hi=i, key=lambda x: x[0]) + dp[i + 1] = max(dp[i], dp[j] + p) + return dp[n] +``` + + + + diff --git a/solution/1200-1299/1236.Web Crawler/README.md b/solution/1200-1299/1236.Web Crawler/README.md index 7565cddadc3b7..c37c95bbd2c7c 100644 --- a/solution/1200-1299/1236.Web Crawler/README.md +++ b/solution/1200-1299/1236.Web Crawler/README.md @@ -89,16 +89,10 @@ startUrl = "http://news.google.com" ## 解法 - - -DFS。 +### 方法一 -### **Python3** - - - ```python # """ # This is HtmlParser's API interface. @@ -131,10 +125,6 @@ class Solution: return list(ans) ``` -### **Java** - - - ```java /** * // This is the HtmlParser's API interface. @@ -172,8 +162,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the HtmlParser's API interface. @@ -215,8 +203,6 @@ public: }; ``` -### **Go** - ```go /** * // This is HtmlParser's API interface. @@ -250,10 +236,6 @@ func crawl(startUrl string, htmlParser HtmlParser) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1236.Web Crawler/README_EN.md b/solution/1200-1299/1236.Web Crawler/README_EN.md index cfaa16e8c6479..10998cbb2f8bb 100644 --- a/solution/1200-1299/1236.Web Crawler/README_EN.md +++ b/solution/1200-1299/1236.Web Crawler/README_EN.md @@ -89,12 +89,10 @@ startUrl = "http://news.google.com" ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python # """ # This is HtmlParser's API interface. @@ -127,8 +125,6 @@ class Solution: return list(ans) ``` -### **Java** - ```java /** * // This is the HtmlParser's API interface. @@ -166,8 +162,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the HtmlParser's API interface. @@ -209,8 +203,6 @@ public: }; ``` -### **Go** - ```go /** * // This is HtmlParser's API interface. @@ -244,10 +236,6 @@ func crawl(startUrl string, htmlParser HtmlParser) []string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/README.md b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/README.md index 1742d02315032..54281c9ec950c 100644 --- a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/README.md +++ b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/README.md @@ -71,32 +71,14 @@ x=5, y=1 -> f(5, 1) = 5 * 1 = 5 ## 解法 - - -**方法一:枚举 + 二分查找** +### 方法一:枚举 + 二分查找 根据题目我们可以知道,函数 $f(x, y)$ 是单调递增函数,因此,我们可以枚举 $x$,然后在 $[1,...z]$ 中二分查找 $y$,使得 $f(x, y) = z$。如果找到了,就将 $(x, y)$ 加入答案中。 时间复杂度 $(n \log n)$,其中 $n$ 是 $z$ 的值,空间复杂度 $O(1)$。 -**方法二:双指针** - -我们可以定义两个指针 $x$ 和 $y$,初始时 $x = 1$, $y = z$。 - -- 如果 $f(x, y) = z$,我们将 $(x, y)$ 加入答案中,然后 $x \leftarrow x + 1$, $y \leftarrow y - 1$; -- 如果 $f(x, y) \lt z$,此时对任意的 $y' \lt y$,都有 $f(x, y') \lt f(x, y) \lt z$,因此我们不能将 $y$ 减小,只能将 $x$ 增大,所以 $x \leftarrow x + 1$; -- 如果 $f(x, y) \gt z$,此时对任意的 $x' \gt x$,都有 $f(x', y) \gt f(x, y) \gt z$,因此我们不能将 $x$ 增大,只能将 $y$ 减小,所以 $y \leftarrow y - 1$。 - -循环结束后,返回答案。 - -时间复杂度 $O(n)$,其中 $n$ 是 $z$ 的值,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python """ This is the custom function interface. @@ -122,39 +104,6 @@ class Solution: return ans ``` -```python -""" - This is the custom function interface. - You should not implement it, or speculate about its implementation - class CustomFunction: - # Returns f(x, y) for any given positive integers x and y. - # Note that f(x, y) is increasing with respect to both x and y. - # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) - def f(self, x, y): - -""" - - -class Solution: - def findSolution(self, customfunction: "CustomFunction", z: int) -> List[List[int]]: - ans = [] - x, y = 1, 1000 - while x <= 1000 and y: - t = customfunction.f(x, y) - if t < z: - x += 1 - elif t > z: - y -= 1 - else: - ans.append([x, y]) - x, y = x + 1, y - 1 - return ans -``` - -### **Java** - - - ```java /* * // This is the custom function interface. @@ -189,39 +138,6 @@ class Solution { } ``` -```java -/* - * // This is the custom function interface. - * // You should not implement it, or speculate about its implementation - * class CustomFunction { - * // Returns f(x, y) for any given positive integers x and y. - * // Note that f(x, y) is increasing with respect to both x and y. - * // i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) - * public int f(int x, int y); - * }; - */ - -class Solution { - public List> findSolution(CustomFunction customfunction, int z) { - List> ans = new ArrayList<>(); - int x = 1, y = 1000; - while (x <= 1000 && y > 0) { - int t = customfunction.f(x, y); - if (t < z) { - x++; - } else if (t > z) { - y--; - } else { - ans.add(Arrays.asList(x++, y--)); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp /* * // This is the custom function interface. @@ -258,6 +174,133 @@ public: }; ``` +```go +/** + * This is the declaration of customFunction API. + * @param x int + * @param x int + * @return Returns f(x, y) for any given positive integers x and y. + * Note that f(x, y) is increasing with respect to both x and y. + * i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + */ + +func findSolution(customFunction func(int, int) int, z int) (ans [][]int) { + for x := 1; x <= 1000; x++ { + y := 1 + sort.Search(999, func(y int) bool { return customFunction(x, y+1) >= z }) + if customFunction(x, y) == z { + ans = append(ans, []int{x, y}) + } + } + return +} +``` + +```ts +/** + * // This is the CustomFunction's API interface. + * // You should not implement it, or speculate about its implementation + * class CustomFunction { + * f(x: number, y: number): number {} + * } + */ + +function findSolution(customfunction: CustomFunction, z: number): number[][] { + const ans: number[][] = []; + for (let x = 1; x <= 1000; ++x) { + let l = 1; + let r = 1000; + while (l < r) { + const mid = (l + r) >> 1; + if (customfunction.f(x, mid) >= z) { + r = mid; + } else { + l = mid + 1; + } + } + if (customfunction.f(x, l) == z) { + ans.push([x, l]); + } + } + return ans; +} +``` + + + +### 方法二:双指针 + +我们可以定义两个指针 $x$ 和 $y$,初始时 $x = 1$, $y = z$。 + +- 如果 $f(x, y) = z$,我们将 $(x, y)$ 加入答案中,然后 $x \leftarrow x + 1$, $y \leftarrow y - 1$; +- 如果 $f(x, y) \lt z$,此时对任意的 $y' \lt y$,都有 $f(x, y') \lt f(x, y) \lt z$,因此我们不能将 $y$ 减小,只能将 $x$ 增大,所以 $x \leftarrow x + 1$; +- 如果 $f(x, y) \gt z$,此时对任意的 $x' \gt x$,都有 $f(x', y) \gt f(x, y) \gt z$,因此我们不能将 $x$ 增大,只能将 $y$ 减小,所以 $y \leftarrow y - 1$。 + +循环结束后,返回答案。 + +时间复杂度 $O(n)$,其中 $n$ 是 $z$ 的值,空间复杂度 $O(1)$。 + + + +```python +""" + This is the custom function interface. + You should not implement it, or speculate about its implementation + class CustomFunction: + # Returns f(x, y) for any given positive integers x and y. + # Note that f(x, y) is increasing with respect to both x and y. + # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + def f(self, x, y): + +""" + + +class Solution: + def findSolution(self, customfunction: "CustomFunction", z: int) -> List[List[int]]: + ans = [] + x, y = 1, 1000 + while x <= 1000 and y: + t = customfunction.f(x, y) + if t < z: + x += 1 + elif t > z: + y -= 1 + else: + ans.append([x, y]) + x, y = x + 1, y - 1 + return ans +``` + +```java +/* + * // This is the custom function interface. + * // You should not implement it, or speculate about its implementation + * class CustomFunction { + * // Returns f(x, y) for any given positive integers x and y. + * // Note that f(x, y) is increasing with respect to both x and y. + * // i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + * public int f(int x, int y); + * }; + */ + +class Solution { + public List> findSolution(CustomFunction customfunction, int z) { + List> ans = new ArrayList<>(); + int x = 1, y = 1000; + while (x <= 1000 && y > 0) { + int t = customfunction.f(x, y); + if (t < z) { + x++; + } else if (t > z) { + y--; + } else { + ans.add(Arrays.asList(x++, y--)); + } + } + return ans; + } +} +``` + ```cpp /* * // This is the custom function interface. @@ -291,29 +334,6 @@ public: }; ``` -### **Go** - -```go -/** - * This is the declaration of customFunction API. - * @param x int - * @param x int - * @return Returns f(x, y) for any given positive integers x and y. - * Note that f(x, y) is increasing with respect to both x and y. - * i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) - */ - -func findSolution(customFunction func(int, int) int, z int) (ans [][]int) { - for x := 1; x <= 1000; x++ { - y := 1 + sort.Search(999, func(y int) bool { return customFunction(x, y+1) >= z }) - if customFunction(x, y) == z { - ans = append(ans, []int{x, y}) - } - } - return -} -``` - ```go /** * This is the declaration of customFunction API. @@ -341,38 +361,6 @@ func findSolution(customFunction func(int, int) int, z int) (ans [][]int) { } ``` -### **TypeScript** - -```ts -/** - * // This is the CustomFunction's API interface. - * // You should not implement it, or speculate about its implementation - * class CustomFunction { - * f(x: number, y: number): number {} - * } - */ - -function findSolution(customfunction: CustomFunction, z: number): number[][] { - const ans: number[][] = []; - for (let x = 1; x <= 1000; ++x) { - let l = 1; - let r = 1000; - while (l < r) { - const mid = (l + r) >> 1; - if (customfunction.f(x, mid) >= z) { - r = mid; - } else { - l = mid + 1; - } - } - if (customfunction.f(x, l) == z) { - ans.push([x, l]); - } - } - return ans; -} -``` - ```ts /** * // This is the CustomFunction's API interface. @@ -400,10 +388,6 @@ function findSolution(customfunction: CustomFunction, z: number): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/README_EN.md b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/README_EN.md index e25cab6fa1419..86345fc3898e1 100644 --- a/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/README_EN.md +++ b/solution/1200-1299/1237.Find Positive Integer Solution for a Given Equation/README_EN.md @@ -69,28 +69,14 @@ x=5, y=1 -> f(5, 1) = 5 * 1 = 5. ## Solutions -**Solution 1: Enumeration + Binary Search** +### Solution 1: Enumeration + Binary Search According to the problem, we know that the function $f(x, y)$ is a monotonically increasing function. Therefore, we can enumerate $x$, and then binary search $y$ in $[1,...z]$ to make $f(x, y) = z$. If found, add $(x, y)$ to the answer. The time complexity is $O(n \log n)$, where $n$ is the value of $z$, and the space complexity is $O(1)$. -**Solution 2: Two Pointers** - -We can define two pointers $x$ and $y$, initially $x = 1$, $y = z$. - -- If $f(x, y) = z$, we add $(x, y)$ to the answer, then $x \leftarrow x + 1$, $y \leftarrow y - 1$; -- If $f(x, y) \lt z$, at this time for any $y' \lt y$, we have $f(x, y') \lt f(x, y) \lt z$, so we cannot decrease $y$, we can only increase $x$, so $x \leftarrow x + 1$; -- If $f(x, y) \gt z$, at this time for any $x' \gt x$, we have $f(x', y) \gt f(x, y) \gt z$, so we cannot increase $x$, we can only decrease $y$, so $y \leftarrow y - 1$. - -After the loop ends, return the answer. - -The time complexity is $O(n)$, where $n$ is the value of $z$, and the space complexity is $O(1)$. - -### **Python3** - ```python """ This is the custom function interface. @@ -107,44 +93,15 @@ The time complexity is $O(n)$, where $n$ is the value of $z$, and the space comp class Solution: def findSolution(self, customfunction: "CustomFunction", z: int) -> List[List[int]]: ans = [] - for x in range(1, 1001): - y = 1 + bisect_left(range(1, 1001), z, key=lambda y: customfunction.f(x, y)) + for x in range(1, z + 1): + y = 1 + bisect_left( + range(1, z + 1), z, key=lambda y: customfunction.f(x, y) + ) if customfunction.f(x, y) == z: ans.append([x, y]) return ans ``` -```python -""" - This is the custom function interface. - You should not implement it, or speculate about its implementation - class CustomFunction: - # Returns f(x, y) for any given positive integers x and y. - # Note that f(x, y) is increasing with respect to both x and y. - # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) - def f(self, x, y): - -""" - - -class Solution: - def findSolution(self, customfunction: "CustomFunction", z: int) -> List[List[int]]: - ans = [] - x, y = 1, 1000 - while x <= 1000 and y: - t = customfunction.f(x, y) - if t < z: - x += 1 - elif t > z: - y -= 1 - else: - ans.append([x, y]) - x, y = x + 1, y - 1 - return ans -``` - -### **Java** - ```java /* * // This is the custom function interface. @@ -179,39 +136,6 @@ class Solution { } ``` -```java -/* - * // This is the custom function interface. - * // You should not implement it, or speculate about its implementation - * class CustomFunction { - * // Returns f(x, y) for any given positive integers x and y. - * // Note that f(x, y) is increasing with respect to both x and y. - * // i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) - * public int f(int x, int y); - * }; - */ - -class Solution { - public List> findSolution(CustomFunction customfunction, int z) { - List> ans = new ArrayList<>(); - int x = 1, y = 1000; - while (x <= 1000 && y > 0) { - int t = customfunction.f(x, y); - if (t < z) { - x++; - } else if (t > z) { - y--; - } else { - ans.add(Arrays.asList(x++, y--)); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp /* * // This is the custom function interface. @@ -248,6 +172,133 @@ public: }; ``` +```go +/** + * This is the declaration of customFunction API. + * @param x int + * @param x int + * @return Returns f(x, y) for any given positive integers x and y. + * Note that f(x, y) is increasing with respect to both x and y. + * i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + */ + +func findSolution(customFunction func(int, int) int, z int) (ans [][]int) { + for x := 1; x <= 1000; x++ { + y := 1 + sort.Search(999, func(y int) bool { return customFunction(x, y+1) >= z }) + if customFunction(x, y) == z { + ans = append(ans, []int{x, y}) + } + } + return +} +``` + +```ts +/** + * // This is the CustomFunction's API interface. + * // You should not implement it, or speculate about its implementation + * class CustomFunction { + * f(x: number, y: number): number {} + * } + */ + +function findSolution(customfunction: CustomFunction, z: number): number[][] { + const ans: number[][] = []; + for (let x = 1; x <= 1000; ++x) { + let l = 1; + let r = 1000; + while (l < r) { + const mid = (l + r) >> 1; + if (customfunction.f(x, mid) >= z) { + r = mid; + } else { + l = mid + 1; + } + } + if (customfunction.f(x, l) == z) { + ans.push([x, l]); + } + } + return ans; +} +``` + + + +### Solution 2: Two Pointers + +We can define two pointers $x$ and $y$, initially $x = 1$, $y = z$. + +- If $f(x, y) = z$, we add $(x, y)$ to the answer, then $x \leftarrow x + 1$, $y \leftarrow y - 1$; +- If $f(x, y) \lt z$, at this time for any $y' \lt y$, we have $f(x, y') \lt f(x, y) \lt z$, so we cannot decrease $y$, we can only increase $x$, so $x \leftarrow x + 1$; +- If $f(x, y) \gt z$, at this time for any $x' \gt x$, we have $f(x', y) \gt f(x, y) \gt z$, so we cannot increase $x$, we can only decrease $y$, so $y \leftarrow y - 1$. + +After the loop ends, return the answer. + +The time complexity is $O(n)$, where $n$ is the value of $z$, and the space complexity is $O(1)$. + + + +```python +""" + This is the custom function interface. + You should not implement it, or speculate about its implementation + class CustomFunction: + # Returns f(x, y) for any given positive integers x and y. + # Note that f(x, y) is increasing with respect to both x and y. + # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + def f(self, x, y): + +""" + + +class Solution: + def findSolution(self, customfunction: "CustomFunction", z: int) -> List[List[int]]: + ans = [] + x, y = 1, 1000 + while x <= 1000 and y: + t = customfunction.f(x, y) + if t < z: + x += 1 + elif t > z: + y -= 1 + else: + ans.append([x, y]) + x, y = x + 1, y - 1 + return ans +``` + +```java +/* + * // This is the custom function interface. + * // You should not implement it, or speculate about its implementation + * class CustomFunction { + * // Returns f(x, y) for any given positive integers x and y. + * // Note that f(x, y) is increasing with respect to both x and y. + * // i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) + * public int f(int x, int y); + * }; + */ + +class Solution { + public List> findSolution(CustomFunction customfunction, int z) { + List> ans = new ArrayList<>(); + int x = 1, y = 1000; + while (x <= 1000 && y > 0) { + int t = customfunction.f(x, y); + if (t < z) { + x++; + } else if (t > z) { + y--; + } else { + ans.add(Arrays.asList(x++, y--)); + } + } + return ans; + } +} +``` + ```cpp /* * // This is the custom function interface. @@ -281,29 +332,6 @@ public: }; ``` -### **Go** - -```go -/** - * This is the declaration of customFunction API. - * @param x int - * @param x int - * @return Returns f(x, y) for any given positive integers x and y. - * Note that f(x, y) is increasing with respect to both x and y. - * i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) - */ - -func findSolution(customFunction func(int, int) int, z int) (ans [][]int) { - for x := 1; x <= 1000; x++ { - y := 1 + sort.Search(999, func(y int) bool { return customFunction(x, y+1) >= z }) - if customFunction(x, y) == z { - ans = append(ans, []int{x, y}) - } - } - return -} -``` - ```go /** * This is the declaration of customFunction API. @@ -331,38 +359,6 @@ func findSolution(customFunction func(int, int) int, z int) (ans [][]int) { } ``` -### **TypeScript** - -```ts -/** - * // This is the CustomFunction's API interface. - * // You should not implement it, or speculate about its implementation - * class CustomFunction { - * f(x: number, y: number): number {} - * } - */ - -function findSolution(customfunction: CustomFunction, z: number): number[][] { - const ans: number[][] = []; - for (let x = 1; x <= 1000; ++x) { - let l = 1; - let r = 1000; - while (l < r) { - const mid = (l + r) >> 1; - if (customfunction.f(x, mid) >= z) { - r = mid; - } else { - l = mid + 1; - } - } - if (customfunction.f(x, l) == z) { - ans.push([x, l]); - } - } - return ans; -} -``` - ```ts /** * // This is the CustomFunction's API interface. @@ -390,10 +386,6 @@ function findSolution(customfunction: CustomFunction, z: number): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1238.Circular Permutation in Binary Representation/README.md b/solution/1200-1299/1238.Circular Permutation in Binary Representation/README.md index aa3ca6c615078..d1247c204cd26 100644 --- a/solution/1200-1299/1238.Circular Permutation in Binary Representation/README.md +++ b/solution/1200-1299/1238.Circular Permutation in Binary Representation/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:二进制码转格雷码** +### 方法一:二进制码转格雷码 我们观察题目中的排列,可以发现,它的二进制表示中,任意两个(包括首尾)相邻的数只有一位二进制数不同。这种编码方式就是格雷码,它是我们在工程中会遇到的一种编码方式。 @@ -66,20 +64,8 @@ int gray(x) { 时间复杂度 $O(2^n)$,空间复杂度 $O(2^n)$。其中 $n$ 为题目给定的整数。 -**方法二:转换优化** - -由于 $gray(0) = 0$,那么 $gray(0) \oplus start = start$,而 $gray(i)$ 与 $gray(i-1)$ 只有一个二进制位不同,所以 $gray(i) \oplus start$ 与 $gray(i-1) \oplus start$ 也只有一个二进制位不同。 - -因此,我们也可以直接将 $[0,..2^n - 1]$ 这些整数转换成对应的 $gray(i) \oplus start$,即可得到首项为 $start$ 的格雷码排列。 - -时间复杂度 $O(2^n)$,其中 $n$ 为题目给定的整数。忽略答案的空间消耗,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def circularPermutation(self, n: int, start: int) -> List[int]: @@ -88,16 +74,6 @@ class Solution: return g[j:] + g[:j] ``` -```python -class Solution: - def circularPermutation(self, n: int, start: int) -> List[int]: - return [i ^ (i >> 1) ^ start for i in range(1 << n)] -``` - -### **Java** - - - ```java class Solution { public List circularPermutation(int n, int start) { @@ -118,20 +94,6 @@ class Solution { } ``` -```java -class Solution { - public List circularPermutation(int n, int start) { - List ans = new ArrayList<>(); - for (int i = 0; i < 1 << n; ++i) { - ans.add(i ^ (i >> 1) ^ start); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -153,21 +115,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector circularPermutation(int n, int start) { - vector ans(1 << n); - for (int i = 0; i < 1 << n; ++i) { - ans[i] = i ^ (i >> 1) ^ start; - } - return ans; - } -}; -``` - -### **Go** - ```go func circularPermutation(n int, start int) []int { g := make([]int, 1<>1)^start) - } - return -} -``` - -### **TypeScript** - ```ts function circularPermutation(n: number, start: number): number[] { const ans: number[] = []; @@ -203,10 +139,58 @@ function circularPermutation(n: number, start: number): number[] { } ``` -### **...** + + +### 方法二:转换优化 + +由于 $gray(0) = 0$,那么 $gray(0) \oplus start = start$,而 $gray(i)$ 与 $gray(i-1)$ 只有一个二进制位不同,所以 $gray(i) \oplus start$ 与 $gray(i-1) \oplus start$ 也只有一个二进制位不同。 + +因此,我们也可以直接将 $[0,..2^n - 1]$ 这些整数转换成对应的 $gray(i) \oplus start$,即可得到首项为 $start$ 的格雷码排列。 + +时间复杂度 $O(2^n)$,其中 $n$ 为题目给定的整数。忽略答案的空间消耗,空间复杂度 $O(1)$。 + + +```python +class Solution: + def circularPermutation(self, n: int, start: int) -> List[int]: + return [i ^ (i >> 1) ^ start for i in range(1 << n)] ``` +```java +class Solution { + public List circularPermutation(int n, int start) { + List ans = new ArrayList<>(); + for (int i = 0; i < 1 << n; ++i) { + ans.add(i ^ (i >> 1) ^ start); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector circularPermutation(int n, int start) { + vector ans(1 << n); + for (int i = 0; i < 1 << n; ++i) { + ans[i] = i ^ (i >> 1) ^ start; + } + return ans; + } +}; +``` + +```go +func circularPermutation(n int, start int) (ans []int) { + for i := 0; i < 1<>1)^start) + } + return +} ``` + + diff --git a/solution/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md b/solution/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md index 33d5274e37129..43811e28e48bc 100644 --- a/solution/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md +++ b/solution/1200-1299/1238.Circular Permutation in Binary Representation/README_EN.md @@ -40,7 +40,7 @@ All the adjacent element differ by one bit. Another valid permutation is [3,1,0, ## Solutions -**Solution 1: Binary Code to Gray Code** +### Solution 1: Binary Code to Gray Code We observe the arrangement in the problem, and find that in its binary representation, only one bit is different between any two (including the first and last) adjacent numbers. This kind of coding method is Gray code, which is a coding method we will encounter in engineering. @@ -60,18 +60,8 @@ We can directly convert the integers $[0,..2^n - 1]$ into the corresponding Gray The time complexity is $O(2^n)$, and the space complexity is $O(2^n)$. Where $n$ is the integer given in the problem. -**Solution 2: Conversion Optimization** - -Since $gray(0) = 0$, then $gray(0) \oplus start = start$, and $gray(i)$ is only one binary bit different from $gray(i-1)$, so $gray(i) \oplus start$ is also only one binary bit different from $gray(i-1) \oplus start$. - -Therefore, we can also directly convert the integers $[0,..2^n - 1]$ into the corresponding $gray(i) \oplus start$ to get the Gray code arrangement with $start$ as the first term. - -The time complexity is $O(2^n)$, where $n$ is the integer given in the problem. Ignoring the space consumption of the answer, the space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def circularPermutation(self, n: int, start: int) -> List[int]: @@ -80,14 +70,6 @@ class Solution: return g[j:] + g[:j] ``` -```python -class Solution: - def circularPermutation(self, n: int, start: int) -> List[int]: - return [i ^ (i >> 1) ^ start for i in range(1 << n)] -``` - -### **Java** - ```java class Solution { public List circularPermutation(int n, int start) { @@ -108,20 +90,6 @@ class Solution { } ``` -```java -class Solution { - public List circularPermutation(int n, int start) { - List ans = new ArrayList<>(); - for (int i = 0; i < 1 << n; ++i) { - ans.add(i ^ (i >> 1) ^ start); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -143,21 +111,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector circularPermutation(int n, int start) { - vector ans(1 << n); - for (int i = 0; i < 1 << n; ++i) { - ans[i] = i ^ (i >> 1) ^ start; - } - return ans; - } -}; -``` - -### **Go** - ```go func circularPermutation(n int, start int) []int { g := make([]int, 1<>1)^start) - } - return -} -``` - -### **TypeScript** - ```ts function circularPermutation(n: number, start: number): number[] { const ans: number[] = []; @@ -193,10 +135,58 @@ function circularPermutation(n: number, start: number): number[] { } ``` -### **...** + + +### Solution 2: Conversion Optimization +Since $gray(0) = 0$, then $gray(0) \oplus start = start$, and $gray(i)$ is only one binary bit different from $gray(i-1)$, so $gray(i) \oplus start$ is also only one binary bit different from $gray(i-1) \oplus start$. + +Therefore, we can also directly convert the integers $[0,..2^n - 1]$ into the corresponding $gray(i) \oplus start$ to get the Gray code arrangement with $start$ as the first term. + +The time complexity is $O(2^n)$, where $n$ is the integer given in the problem. Ignoring the space consumption of the answer, the space complexity is $O(1)$. + + + +```python +class Solution: + def circularPermutation(self, n: int, start: int) -> List[int]: + return [i ^ (i >> 1) ^ start for i in range(1 << n)] ``` +```java +class Solution { + public List circularPermutation(int n, int start) { + List ans = new ArrayList<>(); + for (int i = 0; i < 1 << n; ++i) { + ans.add(i ^ (i >> 1) ^ start); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector circularPermutation(int n, int start) { + vector ans(1 << n); + for (int i = 0; i < 1 << n; ++i) { + ans[i] = i ^ (i >> 1) ^ start; + } + return ans; + } +}; +``` + +```go +func circularPermutation(n int, start int) (ans []int) { + for i := 0; i < 1<>1)^start) + } + return +} ``` + + diff --git a/solution/1200-1299/1239.Maximum Length of a Concatenated String with Unique Characters/README.md b/solution/1200-1299/1239.Maximum Length of a Concatenated String with Unique Characters/README.md index b0b08cb5b1dde..e8d3d7e04e206 100644 --- a/solution/1200-1299/1239.Maximum Length of a Concatenated String with Unique Characters/README.md +++ b/solution/1200-1299/1239.Maximum Length of a Concatenated String with Unique Characters/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:位运算 + 状态压缩** +### 方法一:位运算 + 状态压缩 状态压缩,用一个 $32$ 位数记录字母的出现情况,`masks` 存储之前枚举的字符串。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def maxLength(self, arr: List[str]) -> int: @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxLength(List arr) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +152,6 @@ public: }; ``` -### **Go** - ```go func maxLength(arr []string) (ans int) { masks := []int{0} @@ -194,10 +180,6 @@ func maxLength(arr []string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1239.Maximum Length of a Concatenated String with Unique Characters/README_EN.md b/solution/1200-1299/1239.Maximum Length of a Concatenated String with Unique Characters/README_EN.md index d155f413f14b1..1a639bcbd7996 100644 --- a/solution/1200-1299/1239.Maximum Length of a Concatenated String with Unique Characters/README_EN.md +++ b/solution/1200-1299/1239.Maximum Length of a Concatenated String with Unique Characters/README_EN.md @@ -53,7 +53,7 @@ Maximum length is 4. ## Solutions -**Solution 1: Bit Manipulation + State Compression** +### Solution 1: Bit Manipulation + State Compression State compression is used, with a 32-bit number recording the occurrence of letters, and `masks` storing the strings enumerated before. @@ -61,8 +61,6 @@ The time complexity is $O(2^n + L)$, and the space complexity is $O(2^n)$. Where -### **Python3** - ```python class Solution: def maxLength(self, arr: List[str]) -> int: @@ -85,8 +83,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxLength(List arr) { @@ -120,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +149,6 @@ public: }; ``` -### **Go** - ```go func maxLength(arr []string) (ans int) { masks := []int{0} @@ -185,10 +177,6 @@ func maxLength(arr []string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/README.md b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/README.md index 9b7028f278b30..c77ec991c505c 100644 --- a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/README.md +++ b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:递归回溯 + 状态压缩** +### 方法一:递归回溯 + 状态压缩 我们可以按位置进行递归回溯,过程中我们用一个变量 $t$ 记录当前使用的瓷砖数。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def tilingRectangle(self, n: int, m: int) -> int: @@ -111,50 +105,6 @@ class Solution: return ans ``` -```python -class Solution: - def tilingRectangle(self, n: int, m: int) -> int: - def dfs(i: int, j: int, t: int): - nonlocal ans - if j == m: - i += 1 - j = 0 - if i == n: - ans = t - return - if filled[i] >> j & 1: - dfs(i, j + 1, t) - elif t + 1 < ans: - r = c = 0 - for k in range(i, n): - if filled[k] >> j & 1: - break - r += 1 - for k in range(j, m): - if filled[i] >> k & 1: - break - c += 1 - mx = min(r, c) - for x in range(i, i + mx): - for y in range(j, j + mx): - filled[x] |= 1 << y - for w in range(mx, 0, -1): - dfs(i, j + w, t + 1) - for k in range(w): - filled[i + w - 1] ^= 1 << (j + k) - if k < w - 1: - filled[i + k] ^= 1 << (j + w - 1) - - ans = n * m - filled = [0] * n - dfs(0, 0, 0) - return ans -``` - -### **Java** - - - ```java class Solution { private int n; @@ -214,23 +164,24 @@ class Solution { } ``` -```java +```cpp class Solution { - private int n; - private int m; - private int[] filled; - private int ans; - - public int tilingRectangle(int n, int m) { - this.n = n; - this.m = m; +public: + int tilingRectangle(int n, int m) { + memset(filled, 0, sizeof(filled)); + this->n = n; + this->m = m; ans = n * m; - filled = new int[n]; dfs(0, 0, 0); return ans; } - private void dfs(int i, int j, int t) { +private: + int filled[13]; + int n, m; + int ans; + + void dfs(int i, int j, int t) { if (j == m) { ++i; j = 0; @@ -239,62 +190,202 @@ class Solution { ans = t; return; } - if ((filled[i] >> j & 1) == 1) { + if (filled[i] >> j & 1) { dfs(i, j + 1, t); } else if (t + 1 < ans) { int r = 0, c = 0; for (int k = i; k < n; ++k) { - if ((filled[k] >> j & 1) == 1) { + if (filled[k] >> j & 1) { break; } ++r; } for (int k = j; k < m; ++k) { - if ((filled[i] >> k & 1) == 1) { + if (filled[i] >> k & 1) { break; } ++c; } - int mx = Math.min(r, c); + int mx = min(r, c); + for (int w = 1; w <= mx; ++w) { + for (int k = 0; k < w; ++k) { + filled[i + w - 1] |= 1 << (j + k); + filled[i + k] |= 1 << (j + w - 1); + } + dfs(i, j + w, t + 1); + } for (int x = i; x < i + mx; ++x) { for (int y = j; y < j + mx; ++y) { - filled[x] |= 1 << y; + filled[x] ^= 1 << y; } } - for (int w = mx; w > 0; --w) { + } + } +}; +``` + +```go +func tilingRectangle(n int, m int) int { + ans := n * m + filled := make([]int, n) + var dfs func(i, j, t int) + dfs = func(i, j, t int) { + if j == m { + i++ + j = 0 + } + if i == n { + ans = t + return + } + if filled[i]>>j&1 == 1 { + dfs(i, j+1, t) + } else if t+1 < ans { + var r, c int + for k := i; k < n; k++ { + if filled[k]>>j&1 == 1 { + break + } + r++ + } + for k := j; k < m; k++ { + if filled[i]>>k&1 == 1 { + break + } + c++ + } + mx := min(r, c) + for w := 1; w <= mx; w++ { + for k := 0; k < w; k++ { + filled[i+w-1] |= 1 << (j + k) + filled[i+k] |= 1 << (j + w - 1) + } + dfs(i, j+w, t+1) + } + for x := i; x < i+mx; x++ { + for y := j; y < j+mx; y++ { + filled[x] ^= 1 << y + } + } + } + } + dfs(0, 0, 0) + return ans +} +``` + +```ts +function tilingRectangle(n: number, m: number): number { + let ans = n * m; + const filled: number[] = new Array(n).fill(0); + const dfs = (i: number, j: number, t: number) => { + if (j === m) { + ++i; + j = 0; + } + if (i === n) { + ans = t; + return; + } + if ((filled[i] >> j) & 1) { + dfs(i, j + 1, t); + } else if (t + 1 < ans) { + let [r, c] = [0, 0]; + for (let k = i; k < n; ++k) { + if ((filled[k] >> j) & 1) { + break; + } + ++r; + } + for (let k = j; k < m; ++k) { + if ((filled[i] >> k) & 1) { + break; + } + ++c; + } + const mx = Math.min(r, c); + for (let w = 1; w <= mx; ++w) { + for (let k = 0; k < w; ++k) { + filled[i + w - 1] |= 1 << (j + k); + filled[i + k] |= 1 << (j + w - 1); + } dfs(i, j + w, t + 1); - for (int k = 0; k < w; ++k) { - filled[i + w - 1] ^= 1 << (j + k); - if (k < w - 1) { - filled[i + k] ^= 1 << (j + w - 1); - } + } + for (let x = i; x < i + mx; ++x) { + for (let y = j; y < j + mx; ++y) { + filled[x] ^= 1 << y; } } } - } + }; + dfs(0, 0, 0); + return ans; } ``` -### **C++** + + +### 方法二 -```cpp + + +```python +class Solution: + def tilingRectangle(self, n: int, m: int) -> int: + def dfs(i: int, j: int, t: int): + nonlocal ans + if j == m: + i += 1 + j = 0 + if i == n: + ans = t + return + if filled[i] >> j & 1: + dfs(i, j + 1, t) + elif t + 1 < ans: + r = c = 0 + for k in range(i, n): + if filled[k] >> j & 1: + break + r += 1 + for k in range(j, m): + if filled[i] >> k & 1: + break + c += 1 + mx = min(r, c) + for x in range(i, i + mx): + for y in range(j, j + mx): + filled[x] |= 1 << y + for w in range(mx, 0, -1): + dfs(i, j + w, t + 1) + for k in range(w): + filled[i + w - 1] ^= 1 << (j + k) + if k < w - 1: + filled[i + k] ^= 1 << (j + w - 1) + + ans = n * m + filled = [0] * n + dfs(0, 0, 0) + return ans +``` + +```java class Solution { -public: - int tilingRectangle(int n, int m) { - memset(filled, 0, sizeof(filled)); - this->n = n; - this->m = m; + private int n; + private int m; + private int[] filled; + private int ans; + + public int tilingRectangle(int n, int m) { + this.n = n; + this.m = m; ans = n * m; + filled = new int[n]; dfs(0, 0, 0); return ans; } -private: - int filled[13]; - int n, m; - int ans; - - void dfs(int i, int j, int t) { + private void dfs(int i, int j, int t) { if (j == m) { ++i; j = 0; @@ -303,38 +394,40 @@ private: ans = t; return; } - if (filled[i] >> j & 1) { + if ((filled[i] >> j & 1) == 1) { dfs(i, j + 1, t); } else if (t + 1 < ans) { int r = 0, c = 0; for (int k = i; k < n; ++k) { - if (filled[k] >> j & 1) { + if ((filled[k] >> j & 1) == 1) { break; } ++r; } for (int k = j; k < m; ++k) { - if (filled[i] >> k & 1) { + if ((filled[i] >> k & 1) == 1) { break; } ++c; } - int mx = min(r, c); - for (int w = 1; w <= mx; ++w) { - for (int k = 0; k < w; ++k) { - filled[i + w - 1] |= 1 << (j + k); - filled[i + k] |= 1 << (j + w - 1); - } - dfs(i, j + w, t + 1); - } + int mx = Math.min(r, c); for (int x = i; x < i + mx; ++x) { for (int y = j; y < j + mx; ++y) { - filled[x] ^= 1 << y; + filled[x] |= 1 << y; + } + } + for (int w = mx; w > 0; --w) { + dfs(i, j + w, t + 1); + for (int k = 0; k < w; ++k) { + filled[i + w - 1] ^= 1 << (j + k); + if (k < w - 1) { + filled[i + k] ^= 1 << (j + w - 1); + } } } } } -}; +} ``` ```cpp @@ -399,58 +492,6 @@ private: }; ``` -### **Go** - -```go -func tilingRectangle(n int, m int) int { - ans := n * m - filled := make([]int, n) - var dfs func(i, j, t int) - dfs = func(i, j, t int) { - if j == m { - i++ - j = 0 - } - if i == n { - ans = t - return - } - if filled[i]>>j&1 == 1 { - dfs(i, j+1, t) - } else if t+1 < ans { - var r, c int - for k := i; k < n; k++ { - if filled[k]>>j&1 == 1 { - break - } - r++ - } - for k := j; k < m; k++ { - if filled[i]>>k&1 == 1 { - break - } - c++ - } - mx := min(r, c) - for w := 1; w <= mx; w++ { - for k := 0; k < w; k++ { - filled[i+w-1] |= 1 << (j + k) - filled[i+k] |= 1 << (j + w - 1) - } - dfs(i, j+w, t+1) - } - for x := i; x < i+mx; x++ { - for y := j; y < j+mx; y++ { - filled[x] ^= 1 << y - } - } - } - } - dfs(0, 0, 0) - return ans -} -``` - ```go func tilingRectangle(n int, m int) int { ans := n * m @@ -503,57 +544,6 @@ func tilingRectangle(n int, m int) int { } ``` -### **TypeScript** - -```ts -function tilingRectangle(n: number, m: number): number { - let ans = n * m; - const filled: number[] = new Array(n).fill(0); - const dfs = (i: number, j: number, t: number) => { - if (j === m) { - ++i; - j = 0; - } - if (i === n) { - ans = t; - return; - } - if ((filled[i] >> j) & 1) { - dfs(i, j + 1, t); - } else if (t + 1 < ans) { - let [r, c] = [0, 0]; - for (let k = i; k < n; ++k) { - if ((filled[k] >> j) & 1) { - break; - } - ++r; - } - for (let k = j; k < m; ++k) { - if ((filled[i] >> k) & 1) { - break; - } - ++c; - } - const mx = Math.min(r, c); - for (let w = 1; w <= mx; ++w) { - for (let k = 0; k < w; ++k) { - filled[i + w - 1] |= 1 << (j + k); - filled[i + k] |= 1 << (j + w - 1); - } - dfs(i, j + w, t + 1); - } - for (let x = i; x < i + mx; ++x) { - for (let y = j; y < j + mx; ++y) { - filled[x] ^= 1 << y; - } - } - } - }; - dfs(0, 0, 0); - return ans; -} -``` - ```ts function tilingRectangle(n: number, m: number): number { let ans = n * m; @@ -605,10 +595,6 @@ function tilingRectangle(n: number, m: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/README_EN.md b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/README_EN.md index 777ec423bf1b0..14a14fdb71c08 100644 --- a/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/README_EN.md +++ b/solution/1200-1299/1240.Tiling a Rectangle with the Fewest Squares/README_EN.md @@ -45,7 +45,7 @@ ## Solutions -**Solution 1: Recursive Backtracking + State Compression** +### Solution 1: Recursive Backtracking + State Compression We can perform recursive backtracking by position, during which we use a variable $t$ to record the current number of tiles used. @@ -58,8 +58,6 @@ Since each position only has two states: filled or not filled, we can use an int -### **Python3** - ```python class Solution: def tilingRectangle(self, n: int, m: int) -> int: @@ -99,48 +97,6 @@ class Solution: return ans ``` -```python -class Solution: - def tilingRectangle(self, n: int, m: int) -> int: - def dfs(i: int, j: int, t: int): - nonlocal ans - if j == m: - i += 1 - j = 0 - if i == n: - ans = t - return - if filled[i] >> j & 1: - dfs(i, j + 1, t) - elif t + 1 < ans: - r = c = 0 - for k in range(i, n): - if filled[k] >> j & 1: - break - r += 1 - for k in range(j, m): - if filled[i] >> k & 1: - break - c += 1 - mx = min(r, c) - for x in range(i, i + mx): - for y in range(j, j + mx): - filled[x] |= 1 << y - for w in range(mx, 0, -1): - dfs(i, j + w, t + 1) - for k in range(w): - filled[i + w - 1] ^= 1 << (j + k) - if k < w - 1: - filled[i + k] ^= 1 << (j + w - 1) - - ans = n * m - filled = [0] * n - dfs(0, 0, 0) - return ans -``` - -### **Java** - ```java class Solution { private int n; @@ -200,23 +156,24 @@ class Solution { } ``` -```java +```cpp class Solution { - private int n; - private int m; - private int[] filled; - private int ans; - - public int tilingRectangle(int n, int m) { - this.n = n; - this.m = m; +public: + int tilingRectangle(int n, int m) { + memset(filled, 0, sizeof(filled)); + this->n = n; + this->m = m; ans = n * m; - filled = new int[n]; dfs(0, 0, 0); return ans; } - private void dfs(int i, int j, int t) { +private: + int filled[13]; + int n, m; + int ans; + + void dfs(int i, int j, int t) { if (j == m) { ++i; j = 0; @@ -225,62 +182,202 @@ class Solution { ans = t; return; } - if ((filled[i] >> j & 1) == 1) { + if (filled[i] >> j & 1) { dfs(i, j + 1, t); } else if (t + 1 < ans) { int r = 0, c = 0; for (int k = i; k < n; ++k) { - if ((filled[k] >> j & 1) == 1) { + if (filled[k] >> j & 1) { break; } ++r; } for (int k = j; k < m; ++k) { - if ((filled[i] >> k & 1) == 1) { + if (filled[i] >> k & 1) { break; } ++c; } - int mx = Math.min(r, c); + int mx = min(r, c); + for (int w = 1; w <= mx; ++w) { + for (int k = 0; k < w; ++k) { + filled[i + w - 1] |= 1 << (j + k); + filled[i + k] |= 1 << (j + w - 1); + } + dfs(i, j + w, t + 1); + } for (int x = i; x < i + mx; ++x) { for (int y = j; y < j + mx; ++y) { - filled[x] |= 1 << y; + filled[x] ^= 1 << y; } } - for (int w = mx; w > 0; --w) { + } + } +}; +``` + +```go +func tilingRectangle(n int, m int) int { + ans := n * m + filled := make([]int, n) + var dfs func(i, j, t int) + dfs = func(i, j, t int) { + if j == m { + i++ + j = 0 + } + if i == n { + ans = t + return + } + if filled[i]>>j&1 == 1 { + dfs(i, j+1, t) + } else if t+1 < ans { + var r, c int + for k := i; k < n; k++ { + if filled[k]>>j&1 == 1 { + break + } + r++ + } + for k := j; k < m; k++ { + if filled[i]>>k&1 == 1 { + break + } + c++ + } + mx := min(r, c) + for w := 1; w <= mx; w++ { + for k := 0; k < w; k++ { + filled[i+w-1] |= 1 << (j + k) + filled[i+k] |= 1 << (j + w - 1) + } + dfs(i, j+w, t+1) + } + for x := i; x < i+mx; x++ { + for y := j; y < j+mx; y++ { + filled[x] ^= 1 << y + } + } + } + } + dfs(0, 0, 0) + return ans +} +``` + +```ts +function tilingRectangle(n: number, m: number): number { + let ans = n * m; + const filled: number[] = new Array(n).fill(0); + const dfs = (i: number, j: number, t: number) => { + if (j === m) { + ++i; + j = 0; + } + if (i === n) { + ans = t; + return; + } + if ((filled[i] >> j) & 1) { + dfs(i, j + 1, t); + } else if (t + 1 < ans) { + let [r, c] = [0, 0]; + for (let k = i; k < n; ++k) { + if ((filled[k] >> j) & 1) { + break; + } + ++r; + } + for (let k = j; k < m; ++k) { + if ((filled[i] >> k) & 1) { + break; + } + ++c; + } + const mx = Math.min(r, c); + for (let w = 1; w <= mx; ++w) { + for (let k = 0; k < w; ++k) { + filled[i + w - 1] |= 1 << (j + k); + filled[i + k] |= 1 << (j + w - 1); + } dfs(i, j + w, t + 1); - for (int k = 0; k < w; ++k) { - filled[i + w - 1] ^= 1 << (j + k); - if (k < w - 1) { - filled[i + k] ^= 1 << (j + w - 1); - } + } + for (let x = i; x < i + mx; ++x) { + for (let y = j; y < j + mx; ++y) { + filled[x] ^= 1 << y; } } } - } + }; + dfs(0, 0, 0); + return ans; } ``` -### **C++** + -```cpp +### Solution 2 + + + +```python +class Solution: + def tilingRectangle(self, n: int, m: int) -> int: + def dfs(i: int, j: int, t: int): + nonlocal ans + if j == m: + i += 1 + j = 0 + if i == n: + ans = t + return + if filled[i] >> j & 1: + dfs(i, j + 1, t) + elif t + 1 < ans: + r = c = 0 + for k in range(i, n): + if filled[k] >> j & 1: + break + r += 1 + for k in range(j, m): + if filled[i] >> k & 1: + break + c += 1 + mx = min(r, c) + for x in range(i, i + mx): + for y in range(j, j + mx): + filled[x] |= 1 << y + for w in range(mx, 0, -1): + dfs(i, j + w, t + 1) + for k in range(w): + filled[i + w - 1] ^= 1 << (j + k) + if k < w - 1: + filled[i + k] ^= 1 << (j + w - 1) + + ans = n * m + filled = [0] * n + dfs(0, 0, 0) + return ans +``` + +```java class Solution { -public: - int tilingRectangle(int n, int m) { - memset(filled, 0, sizeof(filled)); - this->n = n; - this->m = m; + private int n; + private int m; + private int[] filled; + private int ans; + + public int tilingRectangle(int n, int m) { + this.n = n; + this.m = m; ans = n * m; + filled = new int[n]; dfs(0, 0, 0); return ans; } -private: - int filled[13]; - int n, m; - int ans; - - void dfs(int i, int j, int t) { + private void dfs(int i, int j, int t) { if (j == m) { ++i; j = 0; @@ -289,38 +386,40 @@ private: ans = t; return; } - if (filled[i] >> j & 1) { + if ((filled[i] >> j & 1) == 1) { dfs(i, j + 1, t); } else if (t + 1 < ans) { int r = 0, c = 0; for (int k = i; k < n; ++k) { - if (filled[k] >> j & 1) { + if ((filled[k] >> j & 1) == 1) { break; } ++r; } for (int k = j; k < m; ++k) { - if (filled[i] >> k & 1) { + if ((filled[i] >> k & 1) == 1) { break; } ++c; } - int mx = min(r, c); - for (int w = 1; w <= mx; ++w) { - for (int k = 0; k < w; ++k) { - filled[i + w - 1] |= 1 << (j + k); - filled[i + k] |= 1 << (j + w - 1); - } - dfs(i, j + w, t + 1); - } + int mx = Math.min(r, c); for (int x = i; x < i + mx; ++x) { for (int y = j; y < j + mx; ++y) { - filled[x] ^= 1 << y; + filled[x] |= 1 << y; + } + } + for (int w = mx; w > 0; --w) { + dfs(i, j + w, t + 1); + for (int k = 0; k < w; ++k) { + filled[i + w - 1] ^= 1 << (j + k); + if (k < w - 1) { + filled[i + k] ^= 1 << (j + w - 1); + } } } } } -}; +} ``` ```cpp @@ -385,58 +484,6 @@ private: }; ``` -### **Go** - -```go -func tilingRectangle(n int, m int) int { - ans := n * m - filled := make([]int, n) - var dfs func(i, j, t int) - dfs = func(i, j, t int) { - if j == m { - i++ - j = 0 - } - if i == n { - ans = t - return - } - if filled[i]>>j&1 == 1 { - dfs(i, j+1, t) - } else if t+1 < ans { - var r, c int - for k := i; k < n; k++ { - if filled[k]>>j&1 == 1 { - break - } - r++ - } - for k := j; k < m; k++ { - if filled[i]>>k&1 == 1 { - break - } - c++ - } - mx := min(r, c) - for w := 1; w <= mx; w++ { - for k := 0; k < w; k++ { - filled[i+w-1] |= 1 << (j + k) - filled[i+k] |= 1 << (j + w - 1) - } - dfs(i, j+w, t+1) - } - for x := i; x < i+mx; x++ { - for y := j; y < j+mx; y++ { - filled[x] ^= 1 << y - } - } - } - } - dfs(0, 0, 0) - return ans -} -``` - ```go func tilingRectangle(n int, m int) int { ans := n * m @@ -489,57 +536,6 @@ func tilingRectangle(n int, m int) int { } ``` -### **TypeScript** - -```ts -function tilingRectangle(n: number, m: number): number { - let ans = n * m; - const filled: number[] = new Array(n).fill(0); - const dfs = (i: number, j: number, t: number) => { - if (j === m) { - ++i; - j = 0; - } - if (i === n) { - ans = t; - return; - } - if ((filled[i] >> j) & 1) { - dfs(i, j + 1, t); - } else if (t + 1 < ans) { - let [r, c] = [0, 0]; - for (let k = i; k < n; ++k) { - if ((filled[k] >> j) & 1) { - break; - } - ++r; - } - for (let k = j; k < m; ++k) { - if ((filled[i] >> k) & 1) { - break; - } - ++c; - } - const mx = Math.min(r, c); - for (let w = 1; w <= mx; ++w) { - for (let k = 0; k < w; ++k) { - filled[i + w - 1] |= 1 << (j + k); - filled[i + k] |= 1 << (j + w - 1); - } - dfs(i, j + w, t + 1); - } - for (let x = i; x < i + mx; ++x) { - for (let y = j; y < j + mx; ++y) { - filled[x] ^= 1 << y; - } - } - } - }; - dfs(0, 0, 0); - return ans; -} -``` - ```ts function tilingRectangle(n: number, m: number): number { let ans = n * m; @@ -591,10 +587,6 @@ function tilingRectangle(n: number, m: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1241.Number of Comments per Post/README.md b/solution/1200-1299/1241.Number of Comments per Post/README.md index 3b171991e7a15..1b97bab82d493 100644 --- a/solution/1200-1299/1241.Number of Comments per Post/README.md +++ b/solution/1200-1299/1241.Number of Comments per Post/README.md @@ -73,12 +73,10 @@ Submissions table: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -96,3 +94,5 @@ ORDER BY post_id; ``` + + diff --git a/solution/1200-1299/1241.Number of Comments per Post/README_EN.md b/solution/1200-1299/1241.Number of Comments per Post/README_EN.md index 71c5d24b200bf..6d37a951b5488 100644 --- a/solution/1200-1299/1241.Number of Comments per Post/README_EN.md +++ b/solution/1200-1299/1241.Number of Comments per Post/README_EN.md @@ -69,9 +69,9 @@ The comment with id 6 is a comment on a deleted post with id 7 so we ignored it. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -90,3 +90,5 @@ ORDER BY post_id; ``` + + diff --git a/solution/1200-1299/1242.Web Crawler Multithreaded/README.md b/solution/1200-1299/1242.Web Crawler Multithreaded/README.md index f277f473ff2ea..a8ddb0c4bcba0 100644 --- a/solution/1200-1299/1242.Web Crawler Multithreaded/README.md +++ b/solution/1200-1299/1242.Web Crawler Multithreaded/README.md @@ -104,30 +104,4 @@ startUrl = "http://news.google.com" ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1200-1299/1242.Web Crawler Multithreaded/README_EN.md b/solution/1200-1299/1242.Web Crawler Multithreaded/README_EN.md index 977c758fa65d2..5bab5f95994ab 100644 --- a/solution/1200-1299/1242.Web Crawler Multithreaded/README_EN.md +++ b/solution/1200-1299/1242.Web Crawler Multithreaded/README_EN.md @@ -98,24 +98,4 @@ startUrl = "http://news.google.com" ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1200-1299/1243.Array Transformation/README.md b/solution/1200-1299/1243.Array Transformation/README.md index a3b88a47051e5..1a159a3997836 100644 --- a/solution/1200-1299/1243.Array Transformation/README.md +++ b/solution/1200-1299/1243.Array Transformation/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 每次模拟一天,对于每个元素,如果它大于左右邻居,则自减 1,否则自增 1。如果数组在某一天不再发生变化,则返回该数组。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def transformArray(self, arr: List[int]) -> List[int]: @@ -81,10 +75,6 @@ class Solution: return arr ``` -### **Java** - - - ```java class Solution { public List transformArray(int[] arr) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func transformArray(arr []int) []int { f := true @@ -162,10 +148,6 @@ func transformArray(arr []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1243.Array Transformation/README_EN.md b/solution/1200-1299/1243.Array Transformation/README_EN.md index ebdf9a634ee6d..a357d6ffb1678 100644 --- a/solution/1200-1299/1243.Array Transformation/README_EN.md +++ b/solution/1200-1299/1243.Array Transformation/README_EN.md @@ -48,7 +48,7 @@ No more operations can be done to this array. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation Simulate each day. For each element, if it is greater than its left and right neighbors, it decreases by 1, otherwise, it increases by 1. If the array no longer changes on a certain day, return that array. @@ -56,8 +56,6 @@ The time complexity is $O(n \times m)$, and the space complexity is $O(n)$. Wher -### **Python3** - ```python class Solution: def transformArray(self, arr: List[int]) -> List[int]: @@ -75,8 +73,6 @@ class Solution: return arr ``` -### **Java** - ```java class Solution { public List transformArray(int[] arr) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +124,6 @@ public: }; ``` -### **Go** - ```go func transformArray(arr []int) []int { f := true @@ -154,10 +146,6 @@ func transformArray(arr []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1244.Design A Leaderboard/README.md b/solution/1200-1299/1244.Design A Leaderboard/README.md index 895039c8f2c10..8d1e57e651177 100644 --- a/solution/1200-1299/1244.Design A Leaderboard/README.md +++ b/solution/1200-1299/1244.Design A Leaderboard/README.md @@ -61,9 +61,7 @@ leaderboard.top(3); // returns 141 = 51 + 51 + 39; ## 解法 - - -**方法一:哈希表 + 有序列表** +### 方法一:哈希表 + 有序列表 我们用哈希表 $d$ 记录每个参赛者的分数,用有序列表 $rank$ 记录所有参赛者的分数。 @@ -77,10 +75,6 @@ leaderboard.top(3); // returns 141 = 51 + 51 + 39; -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -113,10 +107,6 @@ class Leaderboard: # obj.reset(playerId) ``` -### **Java** - - - ```java class Leaderboard { private Map d = new HashMap<>(); @@ -165,8 +155,6 @@ class Leaderboard { */ ``` -### **C++** - ```cpp class Leaderboard { public: @@ -213,8 +201,6 @@ private: */ ``` -### **Rust** - ```rust use std::collections::BTreeMap; @@ -273,10 +259,6 @@ impl Leaderboard { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1244.Design A Leaderboard/README_EN.md b/solution/1200-1299/1244.Design A Leaderboard/README_EN.md index ba8a518f0400f..fa59b07a25f5d 100644 --- a/solution/1200-1299/1244.Design A Leaderboard/README_EN.md +++ b/solution/1200-1299/1244.Design A Leaderboard/README_EN.md @@ -50,7 +50,7 @@ leaderboard.top(3); // returns 141 = 51 + 51 + 39; ## Solutions -**Solution 1: Hash Table + Ordered List** +### Solution 1: Hash Table + Ordered List We use a hash table $d$ to record the scores of each player, and an ordered list $rank$ to record the scores of all players. @@ -64,8 +64,6 @@ The space complexity is $O(n)$, where $n$ is the number of players. -### **Python3** - ```python from sortedcontainers import SortedList @@ -98,8 +96,6 @@ class Leaderboard: # obj.reset(playerId) ``` -### **Java** - ```java class Leaderboard { private Map d = new HashMap<>(); @@ -148,8 +144,6 @@ class Leaderboard { */ ``` -### **C++** - ```cpp class Leaderboard { public: @@ -196,8 +190,6 @@ private: */ ``` -### **Rust** - ```rust use std::collections::BTreeMap; @@ -256,10 +248,6 @@ impl Leaderboard { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1245.Tree Diameter/README.md b/solution/1200-1299/1245.Tree Diameter/README.md index 666e20fd1ed7e..3953f6d8ea74c 100644 --- a/solution/1200-1299/1245.Tree Diameter/README.md +++ b/solution/1200-1299/1245.Tree Diameter/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:两次 DFS** +### 方法一:两次 DFS 首先对任意一个结点做 DFS 求出最远的结点,然后以这个结点为根结点再做 DFS 到达另一个最远结点。第一次 DFS 到达的结点可以证明一定是这个图的直径的一端,第二次 DFS 就会达到另一端。下面来证明这个定理。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def treeDiameter(self, edges: List[List[int]]) -> int: @@ -104,10 +98,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private Map> g; @@ -147,8 +137,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -184,8 +172,6 @@ public: }; ``` -### **Go** - ```go func treeDiameter(edges [][]int) int { n := len(edges) @@ -220,10 +206,6 @@ func treeDiameter(edges [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1245.Tree Diameter/README_EN.md b/solution/1200-1299/1245.Tree Diameter/README_EN.md index e82334c1a1355..094aa77e45ca8 100644 --- a/solution/1200-1299/1245.Tree Diameter/README_EN.md +++ b/solution/1200-1299/1245.Tree Diameter/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Two DFS** +### Solution 1: Two DFS First, perform DFS on any node to find the furthest node, then perform DFS again from this node to reach another furthest node. The node reached by the first DFS can be proven to be one end of the diameter of this graph, and the second DFS will reach the other end. Let's prove this theorem. @@ -63,8 +63,6 @@ Similar problems: -### **Python3** - ```python class Solution: def treeDiameter(self, edges: List[List[int]]) -> int: @@ -92,8 +90,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private Map> g; @@ -133,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +164,6 @@ public: }; ``` -### **Go** - ```go func treeDiameter(edges [][]int) int { n := len(edges) @@ -206,10 +198,6 @@ func treeDiameter(edges [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1246.Palindrome Removal/README.md b/solution/1200-1299/1246.Palindrome Removal/README.md index 58d67be5b40ca..724d169a30099 100644 --- a/solution/1200-1299/1246.Palindrome Removal/README.md +++ b/solution/1200-1299/1246.Palindrome Removal/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:动态规划(区间 DP)** +### 方法一:动态规划(区间 DP) 我们定义 $f[i][j]$ 表示删除下标区间 $[i,..j]$ 内的所有数字所需的最少操作次数。初始时 $f[i][i] = 1$,表示只有一个数字时,需要执行一次删除操作。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def minimumMoves(self, arr: List[int]) -> int: @@ -77,10 +71,6 @@ class Solution: return f[0][n - 1] ``` -### **Java** - - - ```java class Solution { public int minimumMoves(int[] arr) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func minimumMoves(arr []int) int { n := len(arr) @@ -170,10 +156,6 @@ func minimumMoves(arr []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1246.Palindrome Removal/README_EN.md b/solution/1200-1299/1246.Palindrome Removal/README_EN.md index d4aacfd2d3f1a..bd11012f4dbed 100644 --- a/solution/1200-1299/1246.Palindrome Removal/README_EN.md +++ b/solution/1200-1299/1246.Palindrome Removal/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Dynamic Programming (Interval DP)** +### Solution 1: Dynamic Programming (Interval DP) We define $f[i][j]$ as the minimum number of operations required to delete all numbers in the index range $[i,..j]$. Initially, $f[i][i] = 1$, which means that when there is only one number, one deletion operation is needed. @@ -50,8 +50,6 @@ The time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Where $n$ -### **Python3** - ```python class Solution: def minimumMoves(self, arr: List[int]) -> int: @@ -71,8 +69,6 @@ class Solution: return f[0][n - 1] ``` -### **Java** - ```java class Solution { public int minimumMoves(int[] arr) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +123,6 @@ public: }; ``` -### **Go** - ```go func minimumMoves(arr []int) int { n := len(arr) @@ -162,10 +154,6 @@ func minimumMoves(arr []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1247.Minimum Swaps to Make Strings Equal/README.md b/solution/1200-1299/1247.Minimum Swaps to Make Strings Equal/README.md index cd711a5bc4532..3e55e40656c12 100644 --- a/solution/1200-1299/1247.Minimum Swaps to Make Strings Equal/README.md +++ b/solution/1200-1299/1247.Minimum Swaps to Make Strings Equal/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 根据题目描述,两个字符串 $s1$ 和 $s2$ 都只包含字符 $x$ 和 $y$,且长度相同,因此可以将 $s1$ 和 $s2$ 中的字符一一对应起来,即 $s1[i]$ 和 $s2[i]$。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def minimumSwap(self, s1: str, s2: str) -> int: @@ -83,8 +77,6 @@ class Solution: return xy // 2 + yx // 2 + xy % 2 + yx % 2 ``` -### **Java** - ```java class Solution { public int minimumSwap(String s1, String s2) { @@ -106,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +116,6 @@ public: }; ``` -### **Go** - ```go func minimumSwap(s1 string, s2 string) int { xy, yx := 0, 0 @@ -146,8 +134,6 @@ func minimumSwap(s1 string, s2 string) int { } ``` -### **JavaScript** - ```js var minimumSwap = function (s1, s2) { let xy = 0, @@ -169,10 +155,6 @@ var minimumSwap = function (s1, s2) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1247.Minimum Swaps to Make Strings Equal/README_EN.md b/solution/1200-1299/1247.Minimum Swaps to Make Strings Equal/README_EN.md index a6f39155b3910..6903ce3e8465a 100644 --- a/solution/1200-1299/1247.Minimum Swaps to Make Strings Equal/README_EN.md +++ b/solution/1200-1299/1247.Minimum Swaps to Make Strings Equal/README_EN.md @@ -45,7 +45,7 @@ Note that you cannot swap s1[0] and s1[1] to make s1 equal to "yx", ca ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy According to the problem description, both strings $s1$ and $s2$ only contain characters $x$ and $y$, and have the same length. Therefore, we can pair the characters in $s1$ and $s2$, i.e., $s1[i]$ and $s2[i]$. @@ -57,8 +57,6 @@ The time complexity is $O(n)$, where $n$ is the length of the strings $s1$ and $ -### **Python3** - ```python class Solution: def minimumSwap(self, s1: str, s2: str) -> int: @@ -71,8 +69,6 @@ class Solution: return xy // 2 + yx // 2 + xy % 2 + yx % 2 ``` -### **Java** - ```java class Solution { public int minimumSwap(String s1, String s2) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +108,6 @@ public: }; ``` -### **Go** - ```go func minimumSwap(s1 string, s2 string) int { xy, yx := 0, 0 @@ -134,8 +126,6 @@ func minimumSwap(s1 string, s2 string) int { } ``` -### **JavaScript** - ```js var minimumSwap = function (s1, s2) { let xy = 0, @@ -157,10 +147,6 @@ var minimumSwap = function (s1, s2) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1248.Count Number of Nice Subarrays/README.md b/solution/1200-1299/1248.Count Number of Nice Subarrays/README.md index 000bf99f11f5e..72aaa1021574c 100644 --- a/solution/1200-1299/1248.Count Number of Nice Subarrays/README.md +++ b/solution/1200-1299/1248.Count Number of Nice Subarrays/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:前缀和 + 数组或哈希表** +### 方法一:前缀和 + 数组或哈希表 题目求子数组中恰好有 $k$ 个奇数的子数组个数,我们可以求出每个前缀数组中奇数的个数 $t$,记录在数组或哈希表 $cnt$ 中。对于每个前缀数组,我们只需要求出前缀数组中奇数个数为 $t-k$ 的前缀数组个数,即为以当前前缀数组结尾的子数组个数。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def numberOfSubarrays(self, nums: List[int], k: int) -> int: @@ -73,10 +67,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numberOfSubarrays(int[] nums, int k) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func numberOfSubarrays(nums []int, k int) (ans int) { n := len(nums) @@ -137,8 +123,6 @@ func numberOfSubarrays(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfSubarrays(nums: number[], k: number): number { const n = nums.length; @@ -157,10 +141,6 @@ function numberOfSubarrays(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1248.Count Number of Nice Subarrays/README_EN.md b/solution/1200-1299/1248.Count Number of Nice Subarrays/README_EN.md index 5595a7760edfe..7165837894660 100644 --- a/solution/1200-1299/1248.Count Number of Nice Subarrays/README_EN.md +++ b/solution/1200-1299/1248.Count Number of Nice Subarrays/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Prefix Sum + Array or Hash Table** +### Solution 1: Prefix Sum + Array or Hash Table The problem asks for the number of subarrays that contain exactly $k$ odd numbers. We can calculate the number of odd numbers $t$ in each prefix array and record it in an array or hash table $cnt$. For each prefix array, we only need to find the number of prefix arrays with $t-k$ odd numbers, which is the number of subarrays ending with the current prefix array. @@ -51,8 +51,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def numberOfSubarrays(self, nums: List[int], k: int) -> int: @@ -65,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numberOfSubarrays(int[] nums, int k) { @@ -86,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +102,6 @@ public: }; ``` -### **Go** - ```go func numberOfSubarrays(nums []int, k int) (ans int) { n := len(nums) @@ -127,8 +119,6 @@ func numberOfSubarrays(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfSubarrays(nums: number[], k: number): number { const n = nums.length; @@ -147,10 +137,6 @@ function numberOfSubarrays(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1249.Minimum Remove to Make Valid Parentheses/README.md b/solution/1200-1299/1249.Minimum Remove to Make Valid Parentheses/README.md index 3f6cc168ccc25..b8a17f917d2e3 100644 --- a/solution/1200-1299/1249.Minimum Remove to Make Valid Parentheses/README.md +++ b/solution/1200-1299/1249.Minimum Remove to Make Valid Parentheses/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:两遍扫描** +### 方法一:两遍扫描 我们先从左向右扫描,将多余的右括号删除,再从右向左扫描,将多余的左括号删除。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def minRemoveToMakeValid(self, s: str) -> str: @@ -101,10 +95,6 @@ class Solution: return ''.join(ans[::-1]) ``` -### **Java** - - - ```java class Solution { public String minRemoveToMakeValid(String s) { @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +163,6 @@ public: }; ``` -### **Go** - ```go func minRemoveToMakeValid(s string) string { stk := []byte{} @@ -214,8 +200,6 @@ func minRemoveToMakeValid(s string) string { } ``` -### **TypeScript** - ```ts function minRemoveToMakeValid(s: string): string { let left = 0; @@ -252,8 +236,6 @@ function minRemoveToMakeValid(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn min_remove_to_make_valid(s: String) -> String { @@ -301,10 +283,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1249.Minimum Remove to Make Valid Parentheses/README_EN.md b/solution/1200-1299/1249.Minimum Remove to Make Valid Parentheses/README_EN.md index d491a11e11238..766d98ad06153 100644 --- a/solution/1200-1299/1249.Minimum Remove to Make Valid Parentheses/README_EN.md +++ b/solution/1200-1299/1249.Minimum Remove to Make Valid Parentheses/README_EN.md @@ -50,7 +50,7 @@ ## Solutions -**Solution 1: Two Passes** +### Solution 1: Two Passes First, we scan from left to right and remove the extra right parentheses. Then, we scan from right to left and remove the extra left parentheses. @@ -63,8 +63,6 @@ Similar problems: -### **Python3** - ```python class Solution: def minRemoveToMakeValid(self, s: str) -> str: @@ -91,8 +89,6 @@ class Solution: return ''.join(ans[::-1]) ``` -### **Java** - ```java class Solution { public String minRemoveToMakeValid(String s) { @@ -129,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +157,6 @@ public: }; ``` -### **Go** - ```go func minRemoveToMakeValid(s string) string { stk := []byte{} @@ -202,8 +194,6 @@ func minRemoveToMakeValid(s string) string { } ``` -### **TypeScript** - ```ts function minRemoveToMakeValid(s: string): string { let left = 0; @@ -240,8 +230,6 @@ function minRemoveToMakeValid(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn min_remove_to_make_valid(s: String) -> String { @@ -289,10 +277,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1250.Check If It Is a Good Array/README.md b/solution/1200-1299/1250.Check If It Is a Good Array/README.md index 90ff74d1b3a3d..c264b73f4b111 100644 --- a/solution/1200-1299/1250.Check If It Is a Good Array/README.md +++ b/solution/1200-1299/1250.Check If It Is a Good Array/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:数学(裴蜀定理)** +### 方法一:数学(裴蜀定理) 我们先可以考虑选取两个数的情况,若选取的数是 $a$ 和 $b$,那么根据题目的要求,我们需要满足 $a \times x + b \times y = 1$,其中 $x$ 和 $y$ 是任意整数。 @@ -61,20 +59,12 @@ -### **Python3** - - - ```python class Solution: def isGoodArray(self, nums: List[int]) -> bool: return reduce(gcd, nums) == 1 ``` -### **Java** - - - ```java class Solution { public boolean isGoodArray(int[] nums) { @@ -91,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +94,6 @@ public: }; ``` -### **Go** - ```go func isGoodArray(nums []int) bool { g := 0 @@ -125,10 +111,6 @@ func gcd(a, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1250.Check If It Is a Good Array/README_EN.md b/solution/1200-1299/1250.Check If It Is a Good Array/README_EN.md index 2cfe9e3382a8e..fbee4bea7cfe0 100644 --- a/solution/1200-1299/1250.Check If It Is a Good Array/README_EN.md +++ b/solution/1200-1299/1250.Check If It Is a Good Array/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Mathematics (Bézout's Identity)** +### Solution 1: Mathematics (Bézout's Identity) First, consider the situation where we select two numbers. If the selected numbers are $a$ and $b$, then according to the problem's requirements, we need to satisfy $a \times x + b \times y = 1$, where $x$ and $y$ are any integers. @@ -58,16 +58,12 @@ The time complexity is $O(n + \log m)$, and the space complexity is $O(1)$. Wher -### **Python3** - ```python class Solution: def isGoodArray(self, nums: List[int]) -> bool: return reduce(gcd, nums) == 1 ``` -### **Java** - ```java class Solution { public boolean isGoodArray(int[] nums) { @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +93,6 @@ public: }; ``` -### **Go** - ```go func isGoodArray(nums []int) bool { g := 0 @@ -118,10 +110,6 @@ func gcd(a, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1251.Average Selling Price/README.md b/solution/1200-1299/1251.Average Selling Price/README.md index 75053d6711c48..f828a9f531937 100644 --- a/solution/1200-1299/1251.Average Selling Price/README.md +++ b/solution/1200-1299/1251.Average Selling Price/README.md @@ -82,16 +82,12 @@ UnitsSold table: ## 解法 - - -**方法一:左连接 + 分组统计** +### 方法一:左连接 + 分组统计 我们可以使用左连接,将 `Prices` 表和 `UnitsSold` 表连接起来,连接条件为 `product_id` 相等,并且 `purchase_date` 在 `start_date` 和 `end_date` 之间。然后使用 `GROUP BY` 子句对 `product_id` 进行分组,使用 `AVG` 函数计算平均价格。注意,如果某个产品没有销售记录,那么 `AVG` 函数会返回 `NULL`,因此我们可以使用 `IFNULL` 函数将其转换为 $0$。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -105,3 +101,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1200-1299/1251.Average Selling Price/README_EN.md b/solution/1200-1299/1251.Average Selling Price/README_EN.md index ce682d924fa8b..755b729e89ce4 100644 --- a/solution/1200-1299/1251.Average Selling Price/README_EN.md +++ b/solution/1200-1299/1251.Average Selling Price/README_EN.md @@ -82,14 +82,12 @@ Average selling price for product 2 = ((200 * 15) + (30 * 30)) / 230 = 16.96 ## Solutions -**Solution 1: Left Join + Grouping** +### Solution 1: Left Join + Grouping We can use a left join to join the `Prices` table and the `UnitsSold` table on `product_id`, and the condition that `purchase_date` is between `start_date` and `end_date`. Then, we can use `GROUP BY` to group by `product_id` for aggregation, and use the `AVG` function to calculate the average price. Note that if a product has no sales records, the `AVG` function will return `NULL`, so we can use the `IFNULL` function to convert it to $0$. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -103,3 +101,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/README.md b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/README.md index 7b21008c84a1a..f467abbaac4e5 100644 --- a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/README.md +++ b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 创建一个矩阵 $g$ 来存放操作的结果。对于 $indices$ 中的每一对 $(r_i, c_i)$,我们将矩阵第 $r_i$ 行的所有数加 $1$,第 $c_i$ 列的所有元素加 $1$。 @@ -70,28 +68,8 @@ 时间复杂度 $O(indices.length*(m+n)+mn)$,空间复杂度 $O(mn)$。 -**方法二:空间优化** - -用行数组 $row$ 和列数组 $col$ 来记录每一行、每一列被增加的次数。对于 $indices$ 中的每一对 $(r_i, c_i)$,我们将 $row[r_i]$ 和 $col[c_i]$ 分别加 $1$。 - -操作结束后,可以算出 $(i, j)$ 位置的计数为 $row[i]+col[j]$。遍历矩阵,统计奇数的个数。 - -时间复杂度 $O(indices.length+mn)$,空间复杂度 $O(m+n)$。 - -**方法三:数学优化** - -我们注意到,只有当 $row[i]$ 和 $col[j]$ 中恰好为“一奇一偶”时,矩阵 $(i, j)$ 位置的数才会是奇数。 - -我们统计 $row$ 中的奇数个数,记为 $cnt1$;$col$ 中的奇数个数,记为 $cnt2$。那么最终得到的奇数个数为 $cnt1*(n-cnt2)+cnt2*(m-cnt1)$。 - -时间复杂度 $O(indices.length+m+n)$,空间复杂度 $O(m+n)$。 - -### **Python3** - - - ```python class Solution: def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: @@ -104,34 +82,6 @@ class Solution: return sum(v % 2 for row in g for v in row) ``` -```python -class Solution: - def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: - row = [0] * m - col = [0] * n - for r, c in indices: - row[r] += 1 - col[c] += 1 - return sum((i + j) % 2 for i in row for j in col) -``` - -```python -class Solution: - def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: - row = [0] * m - col = [0] * n - for r, c in indices: - row[r] += 1 - col[c] += 1 - cnt1 = sum(v % 2 for v in row) - cnt2 = sum(v % 2 for v in col) - return cnt1 * (n - cnt2) + cnt2 * (m - cnt1) -``` - -### **Java** - - - ```java class Solution { public int oddCells(int m, int n, int[][] indices) { @@ -156,27 +106,72 @@ class Solution { } ``` -```java +```cpp class Solution { - public int oddCells(int m, int n, int[][] indices) { - int[] row = new int[m]; - int[] col = new int[n]; - for (int[] e : indices) { +public: + int oddCells(int m, int n, vector>& indices) { + vector> g(m, vector(n)); + for (auto& e : indices) { int r = e[0], c = e[1]; - row[r]++; - col[c]++; + for (int i = 0; i < m; ++i) ++g[i][c]; + for (int j = 0; j < n; ++j) ++g[r][j]; } int ans = 0; - for (int i : row) { - for (int j : col) { - ans += (i + j) % 2; - } - } + for (auto& row : g) + for (int v : row) ans += v % 2; return ans; } +}; +``` + +```go +func oddCells(m int, n int, indices [][]int) int { + g := make([][]int, m) + for i := range g { + g[i] = make([]int, n) + } + for _, e := range indices { + r, c := e[0], e[1] + for i := 0; i < m; i++ { + g[i][c]++ + } + for j := 0; j < n; j++ { + g[r][j]++ + } + } + ans := 0 + for _, row := range g { + for _, v := range row { + ans += v % 2 + } + } + return ans } ``` + + +### 方法二:空间优化 + +用行数组 $row$ 和列数组 $col$ 来记录每一行、每一列被增加的次数。对于 $indices$ 中的每一对 $(r_i, c_i)$,我们将 $row[r_i]$ 和 $col[c_i]$ 分别加 $1$。 + +操作结束后,可以算出 $(i, j)$ 位置的计数为 $row[i]+col[j]$。遍历矩阵,统计奇数的个数。 + +时间复杂度 $O(indices.length+mn)$,空间复杂度 $O(m+n)$。 + + + +```python +class Solution: + def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: + row = [0] * m + col = [0] * n + for r, c in indices: + row[r] += 1 + col[c] += 1 + return sum((i + j) % 2 for i in row for j in col) +``` + ```java class Solution { public int oddCells(int m, int n, int[][] indices) { @@ -187,55 +182,100 @@ class Solution { row[r]++; col[c]++; } - int cnt1 = 0, cnt2 = 0; - for (int v : row) { - cnt1 += v % 2; - } - for (int v : col) { - cnt2 += v % 2; + int ans = 0; + for (int i : row) { + for (int j : col) { + ans += (i + j) % 2; + } } - return cnt1 * (n - cnt2) + cnt2 * (m - cnt1); + return ans; } } ``` -### **C++** - ```cpp class Solution { public: int oddCells(int m, int n, vector>& indices) { - vector> g(m, vector(n)); + vector row(m); + vector col(n); for (auto& e : indices) { int r = e[0], c = e[1]; - for (int i = 0; i < m; ++i) ++g[i][c]; - for (int j = 0; j < n; ++j) ++g[r][j]; + row[r]++; + col[c]++; } int ans = 0; - for (auto& row : g) - for (int v : row) ans += v % 2; + for (int i : row) + for (int j : col) ans += (i + j) % 2; return ans; } }; ``` -```cpp +```go +func oddCells(m int, n int, indices [][]int) int { + row := make([]int, m) + col := make([]int, n) + for _, e := range indices { + r, c := e[0], e[1] + row[r]++ + col[c]++ + } + ans := 0 + for _, i := range row { + for _, j := range col { + ans += (i + j) % 2 + } + } + return ans +} +``` + + + +### 方法三:数学优化 + +我们注意到,只有当 $row[i]$ 和 $col[j]$ 中恰好为“一奇一偶”时,矩阵 $(i, j)$ 位置的数才会是奇数。 + +我们统计 $row$ 中的奇数个数,记为 $cnt1$;$col$ 中的奇数个数,记为 $cnt2$。那么最终得到的奇数个数为 $cnt1*(n-cnt2)+cnt2*(m-cnt1)$。 + +时间复杂度 $O(indices.length+m+n)$,空间复杂度 $O(m+n)$。 + + + +```python +class Solution: + def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: + row = [0] * m + col = [0] * n + for r, c in indices: + row[r] += 1 + col[c] += 1 + cnt1 = sum(v % 2 for v in row) + cnt2 = sum(v % 2 for v in col) + return cnt1 * (n - cnt2) + cnt2 * (m - cnt1) +``` + +```java class Solution { -public: - int oddCells(int m, int n, vector>& indices) { - vector row(m); - vector col(n); - for (auto& e : indices) { + public int oddCells(int m, int n, int[][] indices) { + int[] row = new int[m]; + int[] col = new int[n]; + for (int[] e : indices) { int r = e[0], c = e[1]; row[r]++; col[c]++; } - int ans = 0; - for (int i : row) - for (int j : col) ans += (i + j) % 2; - return ans; + int cnt1 = 0, cnt2 = 0; + for (int v : row) { + cnt1 += v % 2; + } + for (int v : col) { + cnt2 += v % 2; + } + return cnt1 * (n - cnt2) + cnt2 * (m - cnt1); } -}; +} ``` ```cpp @@ -257,52 +297,6 @@ public: }; ``` -### **Go** - -```go -func oddCells(m int, n int, indices [][]int) int { - g := make([][]int, m) - for i := range g { - g[i] = make([]int, n) - } - for _, e := range indices { - r, c := e[0], e[1] - for i := 0; i < m; i++ { - g[i][c]++ - } - for j := 0; j < n; j++ { - g[r][j]++ - } - } - ans := 0 - for _, row := range g { - for _, v := range row { - ans += v % 2 - } - } - return ans -} -``` - -```go -func oddCells(m int, n int, indices [][]int) int { - row := make([]int, m) - col := make([]int, n) - for _, e := range indices { - r, c := e[0], e[1] - row[r]++ - col[c]++ - } - ans := 0 - for _, i := range row { - for _, j := range col { - ans += (i + j) % 2 - } - } - return ans -} -``` - ```go func oddCells(m int, n int, indices [][]int) int { row := make([]int, m) @@ -323,10 +317,6 @@ func oddCells(m int, n int, indices [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/README_EN.md b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/README_EN.md index 2b8eb905737ba..6d60aa63857eb 100644 --- a/solution/1200-1299/1252.Cells with Odd Values in a Matrix/README_EN.md +++ b/solution/1200-1299/1252.Cells with Odd Values in a Matrix/README_EN.md @@ -49,7 +49,7 @@ The final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We create a matrix $g$ to store the results of the operations. For each pair $(r_i, c_i)$ in $indices$, we add $1$ to all elements in the $r_i$th row and the $c_i$th column of the matrix. @@ -57,26 +57,8 @@ After the simulation, we traverse the matrix and count the number of odd numbers The time complexity is $O(\text{indices.length} \times (m+n) + mn)$, and the space complexity is $O(mn)$. -**Solution 2: Space Optimization** - -We use row array $row$ and column array $col$ to record the number of times each row and column are increased. For each pair $(r_i, c_i)$ in $indices$, we add $1$ to $row[r_i]$ and $col[c_i]$ respectively. - -After the operation, we can calculate that the count at position $(i, j)$ is $row[i] + col[j]$. We traverse the matrix and count the number of odd numbers. - -The time complexity is $O(\text{indices.length} + mn)$, and the space complexity is $O(m+n)$. - -**Solution 3: Mathematical Optimization** - -We notice that only when exactly one of $row[i]$ and $col[j]$ is odd, the number at position $(i, j)$ in the matrix will be odd. - -We count the number of odd numbers in $row$, denoted as $cnt1$; the number of odd numbers in $col$, denoted as $cnt2$. Then the final number of odd numbers is $cnt1 \times (n-cnt2) + cnt2 \times (m-cnt1)$. - -The time complexity is $O(\text{indices.length} + m + n)$, and the space complexity is $O(m+n)$. - -### **Python3** - ```python class Solution: def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: @@ -89,32 +71,6 @@ class Solution: return sum(v % 2 for row in g for v in row) ``` -```python -class Solution: - def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: - row = [0] * m - col = [0] * n - for r, c in indices: - row[r] += 1 - col[c] += 1 - return sum((i + j) % 2 for i in row for j in col) -``` - -```python -class Solution: - def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: - row = [0] * m - col = [0] * n - for r, c in indices: - row[r] += 1 - col[c] += 1 - cnt1 = sum(v % 2 for v in row) - cnt2 = sum(v % 2 for v in col) - return cnt1 * (n - cnt2) + cnt2 * (m - cnt1) -``` - -### **Java** - ```java class Solution { public int oddCells(int m, int n, int[][] indices) { @@ -139,27 +95,72 @@ class Solution { } ``` -```java +```cpp class Solution { - public int oddCells(int m, int n, int[][] indices) { - int[] row = new int[m]; - int[] col = new int[n]; - for (int[] e : indices) { +public: + int oddCells(int m, int n, vector>& indices) { + vector> g(m, vector(n)); + for (auto& e : indices) { int r = e[0], c = e[1]; - row[r]++; - col[c]++; + for (int i = 0; i < m; ++i) ++g[i][c]; + for (int j = 0; j < n; ++j) ++g[r][j]; } int ans = 0; - for (int i : row) { - for (int j : col) { - ans += (i + j) % 2; - } - } + for (auto& row : g) + for (int v : row) ans += v % 2; return ans; } +}; +``` + +```go +func oddCells(m int, n int, indices [][]int) int { + g := make([][]int, m) + for i := range g { + g[i] = make([]int, n) + } + for _, e := range indices { + r, c := e[0], e[1] + for i := 0; i < m; i++ { + g[i][c]++ + } + for j := 0; j < n; j++ { + g[r][j]++ + } + } + ans := 0 + for _, row := range g { + for _, v := range row { + ans += v % 2 + } + } + return ans } ``` + + +### Solution 2: Space Optimization + +We use row array $row$ and column array $col$ to record the number of times each row and column are increased. For each pair $(r_i, c_i)$ in $indices$, we add $1$ to $row[r_i]$ and $col[c_i]$ respectively. + +After the operation, we can calculate that the count at position $(i, j)$ is $row[i] + col[j]$. We traverse the matrix and count the number of odd numbers. + +The time complexity is $O(\text{indices.length} + mn)$, and the space complexity is $O(m+n)$. + + + +```python +class Solution: + def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: + row = [0] * m + col = [0] * n + for r, c in indices: + row[r] += 1 + col[c] += 1 + return sum((i + j) % 2 for i in row for j in col) +``` + ```java class Solution { public int oddCells(int m, int n, int[][] indices) { @@ -170,55 +171,100 @@ class Solution { row[r]++; col[c]++; } - int cnt1 = 0, cnt2 = 0; - for (int v : row) { - cnt1 += v % 2; - } - for (int v : col) { - cnt2 += v % 2; + int ans = 0; + for (int i : row) { + for (int j : col) { + ans += (i + j) % 2; + } } - return cnt1 * (n - cnt2) + cnt2 * (m - cnt1); + return ans; } } ``` -### **C++** - ```cpp class Solution { public: int oddCells(int m, int n, vector>& indices) { - vector> g(m, vector(n)); + vector row(m); + vector col(n); for (auto& e : indices) { int r = e[0], c = e[1]; - for (int i = 0; i < m; ++i) ++g[i][c]; - for (int j = 0; j < n; ++j) ++g[r][j]; + row[r]++; + col[c]++; } int ans = 0; - for (auto& row : g) - for (int v : row) ans += v % 2; + for (int i : row) + for (int j : col) ans += (i + j) % 2; return ans; } }; ``` -```cpp +```go +func oddCells(m int, n int, indices [][]int) int { + row := make([]int, m) + col := make([]int, n) + for _, e := range indices { + r, c := e[0], e[1] + row[r]++ + col[c]++ + } + ans := 0 + for _, i := range row { + for _, j := range col { + ans += (i + j) % 2 + } + } + return ans +} +``` + + + +### Solution 3: Mathematical Optimization + +We notice that only when exactly one of $row[i]$ and $col[j]$ is odd, the number at position $(i, j)$ in the matrix will be odd. + +We count the number of odd numbers in $row$, denoted as $cnt1$; the number of odd numbers in $col$, denoted as $cnt2$. Then the final number of odd numbers is $cnt1 \times (n-cnt2) + cnt2 \times (m-cnt1)$. + +The time complexity is $O(\text{indices.length} + m + n)$, and the space complexity is $O(m+n)$. + + + +```python +class Solution: + def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: + row = [0] * m + col = [0] * n + for r, c in indices: + row[r] += 1 + col[c] += 1 + cnt1 = sum(v % 2 for v in row) + cnt2 = sum(v % 2 for v in col) + return cnt1 * (n - cnt2) + cnt2 * (m - cnt1) +``` + +```java class Solution { -public: - int oddCells(int m, int n, vector>& indices) { - vector row(m); - vector col(n); - for (auto& e : indices) { + public int oddCells(int m, int n, int[][] indices) { + int[] row = new int[m]; + int[] col = new int[n]; + for (int[] e : indices) { int r = e[0], c = e[1]; row[r]++; col[c]++; } - int ans = 0; - for (int i : row) - for (int j : col) ans += (i + j) % 2; - return ans; + int cnt1 = 0, cnt2 = 0; + for (int v : row) { + cnt1 += v % 2; + } + for (int v : col) { + cnt2 += v % 2; + } + return cnt1 * (n - cnt2) + cnt2 * (m - cnt1); } -}; +} ``` ```cpp @@ -240,52 +286,6 @@ public: }; ``` -### **Go** - -```go -func oddCells(m int, n int, indices [][]int) int { - g := make([][]int, m) - for i := range g { - g[i] = make([]int, n) - } - for _, e := range indices { - r, c := e[0], e[1] - for i := 0; i < m; i++ { - g[i][c]++ - } - for j := 0; j < n; j++ { - g[r][j]++ - } - } - ans := 0 - for _, row := range g { - for _, v := range row { - ans += v % 2 - } - } - return ans -} -``` - -```go -func oddCells(m int, n int, indices [][]int) int { - row := make([]int, m) - col := make([]int, n) - for _, e := range indices { - r, c := e[0], e[1] - row[r]++ - col[c]++ - } - ans := 0 - for _, i := range row { - for _, j := range col { - ans += (i + j) % 2 - } - } - return ans -} -``` - ```go func oddCells(m int, n int, indices [][]int) int { row := make([]int, m) @@ -306,10 +306,6 @@ func oddCells(m int, n int, indices [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/README.md b/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/README.md index 2815f306fea1f..4b63f5b804b29 100644 --- a/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/README.md +++ b/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们先创建一个答案数组 $ans$,其中 $ans[0]$ 和 $ans[1]$ 分别表示矩阵的第一行和第二行。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def reconstructMatrix( @@ -100,10 +94,6 @@ class Solution: return ans if lower == upper == 0 else [] ``` -### **Java** - - - ```java class Solution { public List> reconstructMatrix(int upper, int lower, int[] colsum) { @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go func reconstructMatrix(upper int, lower int, colsum []int) [][]int { n := len(colsum) @@ -203,8 +189,6 @@ func reconstructMatrix(upper int, lower int, colsum []int) [][]int { } ``` -### **TypeScript** - ```ts function reconstructMatrix(upper: number, lower: number, colsum: number[]): number[][] { const n = colsum.length; @@ -233,10 +217,6 @@ function reconstructMatrix(upper: number, lower: number, colsum: number[]): numb } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/README_EN.md b/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/README_EN.md index 9bbde7b5e724e..65a6b0c9222ae 100644 --- a/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/README_EN.md +++ b/solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/README_EN.md @@ -55,7 +55,7 @@ ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy First, we create an answer array $ans$, where $ans[0]$ and $ans[1]$ represent the first and second rows of the matrix, respectively. @@ -72,8 +72,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $colsum$. Ig -### **Python3** - ```python class Solution: def reconstructMatrix( @@ -97,8 +95,6 @@ class Solution: return ans if lower == upper == 0 else [] ``` -### **Java** - ```java class Solution { public List> reconstructMatrix(int upper, int lower, int[] colsum) { @@ -131,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +157,6 @@ public: }; ``` -### **Go** - ```go func reconstructMatrix(upper int, lower int, colsum []int) [][]int { n := len(colsum) @@ -198,8 +190,6 @@ func reconstructMatrix(upper int, lower int, colsum []int) [][]int { } ``` -### **TypeScript** - ```ts function reconstructMatrix(upper: number, lower: number, colsum: number[]): number[][] { const n = colsum.length; @@ -228,10 +218,6 @@ function reconstructMatrix(upper: number, lower: number, colsum: number[]): numb } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1254.Number of Closed Islands/README.md b/solution/1200-1299/1254.Number of Closed Islands/README.md index 5e58cf6f2b418..9d67ee68903a6 100644 --- a/solution/1200-1299/1254.Number of Closed Islands/README.md +++ b/solution/1200-1299/1254.Number of Closed Islands/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 遍历矩阵,对于每个陆地,我们进行深度优先搜索,找到与其相连的所有陆地,然后判断是否存在边界上的陆地,如果存在,则不是封闭岛屿,否则是封闭岛屿,答案加一。 @@ -65,24 +63,8 @@ 时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。 -**方法二:并查集** - -我们可以用并查集维护每一块连通的陆地。 - -遍历矩阵,如果当前位置是在边界上,我们将其与虚拟节点 $m \times n$ 连接。如果当前位置是陆地,我们将其与下方和右方的陆地连接。 - -接着,我们再次遍历矩阵,对于每一块陆地,如果其根节点就是本身,那么答案加一。 - -最后返回答案即可。 - -时间复杂度 $O(m \times n \times \alpha(m \times n))$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。 - -### **Python3** - - - ```python class Solution: def closedIsland(self, grid: List[List[int]]) -> int: @@ -100,6 +82,180 @@ class Solution: return sum(grid[i][j] == 0 and dfs(i, j) for i in range(m) for j in range(n)) ``` +```java +class Solution { + private int m; + private int n; + private int[][] grid; + + public int closedIsland(int[][] grid) { + m = grid.length; + n = grid[0].length; + this.grid = grid; + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 0) { + ans += dfs(i, j); + } + } + } + return ans; + } + + private int dfs(int i, int j) { + int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0; + grid[i][j] = 1; + int[] dirs = {-1, 0, 1, 0, -1}; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) { + res &= dfs(x, y); + } + } + return res; + } +} +``` + +```cpp +class Solution { +public: + int closedIsland(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int ans = 0; + int dirs[5] = {-1, 0, 1, 0, -1}; + function dfs = [&](int i, int j) -> int { + int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0; + grid[i][j] = 1; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) { + res &= dfs(x, y); + } + } + return res; + }; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans += grid[i][j] == 0 && dfs(i, j); + } + } + return ans; + } +}; +``` + +```go +func closedIsland(grid [][]int) (ans int) { + m, n := len(grid), len(grid[0]) + dirs := [5]int{-1, 0, 1, 0, -1} + var dfs func(i, j int) int + dfs = func(i, j int) int { + res := 1 + if i == 0 || i == m-1 || j == 0 || j == n-1 { + res = 0 + } + grid[i][j] = 1 + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0 { + res &= dfs(x, y) + } + } + return res + } + for i, row := range grid { + for j, v := range row { + if v == 0 { + ans += dfs(i, j) + } + } + } + return +} +``` + +```ts +function closedIsland(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const dirs = [-1, 0, 1, 0, -1]; + const dfs = (i: number, j: number): number => { + let res = i > 0 && j > 0 && i < m - 1 && j < n - 1 ? 1 : 0; + grid[i][j] = 1; + for (let k = 0; k < 4; ++k) { + const [x, y] = [i + dirs[k], j + dirs[k + 1]]; + if (x >= 0 && y >= 0 && x < m && y < n && grid[x][y] === 0) { + res &= dfs(x, y); + } + } + return res; + }; + let ans = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 0) { + ans += dfs(i, j); + } + } + } + return ans; +} +``` + +```cs +public class Solution { + private int m; + private int n; + private int[][] grid; + + public int ClosedIsland(int[][] grid) { + m = grid.Length; + n = grid[0].Length; + this.grid = grid; + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 0) { + ans += dfs(i, j); + } + } + } + return ans; + } + + private int dfs(int i, int j) { + int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0; + grid[i][j] = 1; + int[] dirs = {-1, 0, 1, 0, -1}; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) { + res &= dfs(x, y); + } + } + return res; + } +} +``` + + + +### 方法二:并查集 + +我们可以用并查集维护每一块连通的陆地。 + +遍历矩阵,如果当前位置是在边界上,我们将其与虚拟节点 $m \times n$ 连接。如果当前位置是陆地,我们将其与下方和右方的陆地连接。 + +接着,我们再次遍历矩阵,对于每一块陆地,如果其根节点就是本身,那么答案加一。 + +最后返回答案即可。 + +时间复杂度 $O(m \times n \times \alpha(m \times n))$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是矩阵的行数和列数。 + + + ```python class UnionFind: def __init__(self, n: int): @@ -142,46 +298,6 @@ class Solution: return ans ``` -### **Java** - - - -```java -class Solution { - private int m; - private int n; - private int[][] grid; - - public int closedIsland(int[][] grid) { - m = grid.length; - n = grid[0].length; - this.grid = grid; - int ans = 0; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == 0) { - ans += dfs(i, j); - } - } - } - return ans; - } - - private int dfs(int i, int j) { - int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0; - grid[i][j] = 1; - int[] dirs = {-1, 0, 1, 0, -1}; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) { - res &= dfs(x, y); - } - } - return res; - } -} -``` - ```java class UnionFind { private int[] p; @@ -249,36 +365,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int closedIsland(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - int ans = 0; - int dirs[5] = {-1, 0, 1, 0, -1}; - function dfs = [&](int i, int j) -> int { - int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0; - grid[i][j] = 1; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) { - res &= dfs(x, y); - } - } - return res; - }; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - ans += grid[i][j] == 0 && dfs(i, j); - } - } - return ans; - } -}; -``` - ```cpp class UnionFind { public: @@ -343,38 +429,6 @@ public: }; ``` -### **Go** - -```go -func closedIsland(grid [][]int) (ans int) { - m, n := len(grid), len(grid[0]) - dirs := [5]int{-1, 0, 1, 0, -1} - var dfs func(i, j int) int - dfs = func(i, j int) int { - res := 1 - if i == 0 || i == m-1 || j == 0 || j == n-1 { - res = 0 - } - grid[i][j] = 1 - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0 { - res &= dfs(x, y) - } - } - return res - } - for i, row := range grid { - for j, v := range row { - if v == 0 { - ans += dfs(i, j) - } - } - } - return -} -``` - ```go type unionFind struct { p, size []int @@ -439,36 +493,6 @@ func closedIsland(grid [][]int) (ans int) { } ``` -### **TypeScript** - -```ts -function closedIsland(grid: number[][]): number { - const m = grid.length; - const n = grid[0].length; - const dirs = [-1, 0, 1, 0, -1]; - const dfs = (i: number, j: number): number => { - let res = i > 0 && j > 0 && i < m - 1 && j < n - 1 ? 1 : 0; - grid[i][j] = 1; - for (let k = 0; k < 4; ++k) { - const [x, y] = [i + dirs[k], j + dirs[k + 1]]; - if (x >= 0 && y >= 0 && x < m && y < n && grid[x][y] === 0) { - res &= dfs(x, y); - } - } - return res; - }; - let ans = 0; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; j++) { - if (grid[i][j] === 0) { - ans += dfs(i, j); - } - } - } - return ans; -} -``` - ```ts function closedIsland(grid: number[][]): number { const m = grid.length; @@ -534,44 +558,6 @@ class UnionFind { } ``` -### **C#** - -```cs -public class Solution { - private int m; - private int n; - private int[][] grid; - - public int ClosedIsland(int[][] grid) { - m = grid.Length; - n = grid[0].Length; - this.grid = grid; - int ans = 0; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == 0) { - ans += dfs(i, j); - } - } - } - return ans; - } - - private int dfs(int i, int j) { - int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0; - grid[i][j] = 1; - int[] dirs = {-1, 0, 1, 0, -1}; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) { - res &= dfs(x, y); - } - } - return res; - } -} -``` - ```cs class UnionFind { private int[] p; @@ -639,10 +625,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1254.Number of Closed Islands/README_EN.md b/solution/1200-1299/1254.Number of Closed Islands/README_EN.md index a0d8ac374346f..f875f6bee30d1 100644 --- a/solution/1200-1299/1254.Number of Closed Islands/README_EN.md +++ b/solution/1200-1299/1254.Number of Closed Islands/README_EN.md @@ -51,7 +51,7 @@ Islands in gray are closed because they are completely surrounded by water (grou ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We traverse the matrix, and for each piece of land, we perform a depth-first search to find all the land connected to it. Then we check if there is any land on the boundary. If there is, it is not a closed island; otherwise, it is a closed island, and we increment the answer by one. @@ -59,22 +59,8 @@ Finally, we return the answer. The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Where $m$ and $n$ are the number of rows and columns in the matrix, respectively. -**Solution 2: Union-Find** - -We can use a union-find set to maintain each piece of connected land. - -We traverse the matrix, if the current position is on the boundary, we connect it with the virtual node $m \times n$. If the current position is land, we connect it with the land below and to the right. - -Then, we traverse the matrix again, for each piece of land, if its root node is itself, we increment the answer by one. - -Finally, we return the answer. - -The time complexity is $O(m \times n \times \alpha(m \times n))$, and the space complexity is $O(m \times n)$. Where $m$ and $n$ are the number of rows and columns in the matrix, respectively. - -### **Python3** - ```python class Solution: def closedIsland(self, grid: List[List[int]]) -> int: @@ -92,6 +78,180 @@ class Solution: return sum(grid[i][j] == 0 and dfs(i, j) for i in range(m) for j in range(n)) ``` +```java +class Solution { + private int m; + private int n; + private int[][] grid; + + public int closedIsland(int[][] grid) { + m = grid.length; + n = grid[0].length; + this.grid = grid; + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 0) { + ans += dfs(i, j); + } + } + } + return ans; + } + + private int dfs(int i, int j) { + int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0; + grid[i][j] = 1; + int[] dirs = {-1, 0, 1, 0, -1}; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) { + res &= dfs(x, y); + } + } + return res; + } +} +``` + +```cpp +class Solution { +public: + int closedIsland(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int ans = 0; + int dirs[5] = {-1, 0, 1, 0, -1}; + function dfs = [&](int i, int j) -> int { + int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0; + grid[i][j] = 1; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) { + res &= dfs(x, y); + } + } + return res; + }; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans += grid[i][j] == 0 && dfs(i, j); + } + } + return ans; + } +}; +``` + +```go +func closedIsland(grid [][]int) (ans int) { + m, n := len(grid), len(grid[0]) + dirs := [5]int{-1, 0, 1, 0, -1} + var dfs func(i, j int) int + dfs = func(i, j int) int { + res := 1 + if i == 0 || i == m-1 || j == 0 || j == n-1 { + res = 0 + } + grid[i][j] = 1 + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0 { + res &= dfs(x, y) + } + } + return res + } + for i, row := range grid { + for j, v := range row { + if v == 0 { + ans += dfs(i, j) + } + } + } + return +} +``` + +```ts +function closedIsland(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const dirs = [-1, 0, 1, 0, -1]; + const dfs = (i: number, j: number): number => { + let res = i > 0 && j > 0 && i < m - 1 && j < n - 1 ? 1 : 0; + grid[i][j] = 1; + for (let k = 0; k < 4; ++k) { + const [x, y] = [i + dirs[k], j + dirs[k + 1]]; + if (x >= 0 && y >= 0 && x < m && y < n && grid[x][y] === 0) { + res &= dfs(x, y); + } + } + return res; + }; + let ans = 0; + for (let i = 0; i < m; ++i) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 0) { + ans += dfs(i, j); + } + } + } + return ans; +} +``` + +```cs +public class Solution { + private int m; + private int n; + private int[][] grid; + + public int ClosedIsland(int[][] grid) { + m = grid.Length; + n = grid[0].Length; + this.grid = grid; + int ans = 0; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 0) { + ans += dfs(i, j); + } + } + } + return ans; + } + + private int dfs(int i, int j) { + int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0; + grid[i][j] = 1; + int[] dirs = {-1, 0, 1, 0, -1}; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) { + res &= dfs(x, y); + } + } + return res; + } +} +``` + + + +### Solution 2: Union-Find + +We can use a union-find set to maintain each piece of connected land. + +We traverse the matrix, if the current position is on the boundary, we connect it with the virtual node $m \times n$. If the current position is land, we connect it with the land below and to the right. + +Then, we traverse the matrix again, for each piece of land, if its root node is itself, we increment the answer by one. + +Finally, we return the answer. + +The time complexity is $O(m \times n \times \alpha(m \times n))$, and the space complexity is $O(m \times n)$. Where $m$ and $n$ are the number of rows and columns in the matrix, respectively. + + + ```python class UnionFind: def __init__(self, n: int): @@ -134,44 +294,6 @@ class Solution: return ans ``` -### **Java** - -```java -class Solution { - private int m; - private int n; - private int[][] grid; - - public int closedIsland(int[][] grid) { - m = grid.length; - n = grid[0].length; - this.grid = grid; - int ans = 0; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == 0) { - ans += dfs(i, j); - } - } - } - return ans; - } - - private int dfs(int i, int j) { - int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0; - grid[i][j] = 1; - int[] dirs = {-1, 0, 1, 0, -1}; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) { - res &= dfs(x, y); - } - } - return res; - } -} -``` - ```java class UnionFind { private int[] p; @@ -239,36 +361,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int closedIsland(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - int ans = 0; - int dirs[5] = {-1, 0, 1, 0, -1}; - function dfs = [&](int i, int j) -> int { - int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0; - grid[i][j] = 1; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) { - res &= dfs(x, y); - } - } - return res; - }; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - ans += grid[i][j] == 0 && dfs(i, j); - } - } - return ans; - } -}; -``` - ```cpp class UnionFind { public: @@ -333,38 +425,6 @@ public: }; ``` -### **Go** - -```go -func closedIsland(grid [][]int) (ans int) { - m, n := len(grid), len(grid[0]) - dirs := [5]int{-1, 0, 1, 0, -1} - var dfs func(i, j int) int - dfs = func(i, j int) int { - res := 1 - if i == 0 || i == m-1 || j == 0 || j == n-1 { - res = 0 - } - grid[i][j] = 1 - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0 { - res &= dfs(x, y) - } - } - return res - } - for i, row := range grid { - for j, v := range row { - if v == 0 { - ans += dfs(i, j) - } - } - } - return -} -``` - ```go type unionFind struct { p, size []int @@ -429,36 +489,6 @@ func closedIsland(grid [][]int) (ans int) { } ``` -### **TypeScript** - -```ts -function closedIsland(grid: number[][]): number { - const m = grid.length; - const n = grid[0].length; - const dirs = [-1, 0, 1, 0, -1]; - const dfs = (i: number, j: number): number => { - let res = i > 0 && j > 0 && i < m - 1 && j < n - 1 ? 1 : 0; - grid[i][j] = 1; - for (let k = 0; k < 4; ++k) { - const [x, y] = [i + dirs[k], j + dirs[k + 1]]; - if (x >= 0 && y >= 0 && x < m && y < n && grid[x][y] === 0) { - res &= dfs(x, y); - } - } - return res; - }; - let ans = 0; - for (let i = 0; i < m; ++i) { - for (let j = 0; j < n; j++) { - if (grid[i][j] === 0) { - ans += dfs(i, j); - } - } - } - return ans; -} -``` - ```ts function closedIsland(grid: number[][]): number { const m = grid.length; @@ -524,44 +554,6 @@ class UnionFind { } ``` -### **C#** - -```cs -public class Solution { - private int m; - private int n; - private int[][] grid; - - public int ClosedIsland(int[][] grid) { - m = grid.Length; - n = grid[0].Length; - this.grid = grid; - int ans = 0; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (grid[i][j] == 0) { - ans += dfs(i, j); - } - } - } - return ans; - } - - private int dfs(int i, int j) { - int res = i > 0 && i < m - 1 && j > 0 && j < n - 1 ? 1 : 0; - grid[i][j] = 1; - int[] dirs = {-1, 0, 1, 0, -1}; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) { - res &= dfs(x, y); - } - } - return res; - } -} -``` - ```cs class UnionFind { private int[] p; @@ -629,10 +621,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1255.Maximum Score Words Formed by Letters/README.md b/solution/1200-1299/1255.Maximum Score Words Formed by Letters/README.md index 552608840eee0..4e1afa5e25972 100644 --- a/solution/1200-1299/1255.Maximum Score Words Formed by Letters/README.md +++ b/solution/1200-1299/1255.Maximum Score Words Formed by Letters/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:二进制枚举** +### 方法一:二进制枚举 我们注意到题目的数据范围不大,因此对于给定的单词表,我们可以使用二进制枚举的方法,枚举出所有的单词组合,然后判断每个单词组合是否满足题目要求,如果满足则计算其得分,最后取得分最大的单词组合。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def maxScoreWords( @@ -99,10 +93,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxScoreWords(String[] words, char[] letters, int[] score) { @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -178,8 +166,6 @@ public: }; ``` -### **Go** - ```go func maxScoreWords(words []string, letters []byte, score []int) (ans int) { cnt := [26]int{} @@ -213,10 +199,6 @@ func maxScoreWords(words []string, letters []byte, score []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1255.Maximum Score Words Formed by Letters/README_EN.md b/solution/1200-1299/1255.Maximum Score Words Formed by Letters/README_EN.md index c940dee910d04..fc38c2f6aa35f 100644 --- a/solution/1200-1299/1255.Maximum Score Words Formed by Letters/README_EN.md +++ b/solution/1200-1299/1255.Maximum Score Words Formed by Letters/README_EN.md @@ -54,7 +54,7 @@ Letter "e" can only be used once. ## Solutions -**Solution 1: Binary Enumeration** +### Solution 1: Binary Enumeration Given the small data range in the problem, we can use binary enumeration to enumerate all word combinations for the given word list. Then, we check whether each word combination meets the requirements of the problem. If it does, we calculate its score and finally take the word combination with the highest score. @@ -68,8 +68,6 @@ The time complexity is $(2^n \times n \times M)$, and the space complexity is $O -### **Python3** - ```python class Solution: def maxScoreWords( @@ -86,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxScoreWords(String[] words, char[] letters, int[] score) { @@ -124,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +157,6 @@ public: }; ``` -### **Go** - ```go func maxScoreWords(words []string, letters []byte, score []int) (ans int) { cnt := [26]int{} @@ -198,10 +190,6 @@ func maxScoreWords(words []string, letters []byte, score []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1256.Encode Number/README.md b/solution/1200-1299/1256.Encode Number/README.md index e04cac493f50a..a13995b50f4a0 100644 --- a/solution/1200-1299/1256.Encode Number/README.md +++ b/solution/1200-1299/1256.Encode Number/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 我们将 $num$ 加一,然后将其转换为二进制字符串,去掉最高位的 $1$ 即可。 @@ -46,20 +44,12 @@ -### **Python3** - - - ```python class Solution: def encode(self, num: int) -> str: return bin(num + 1)[3:] ``` -### **Java** - - - ```java class Solution { public String encode(int num) { @@ -68,8 +58,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -85,8 +73,6 @@ public: }; ``` -### **Go** - ```go func encode(num int) string { num++ @@ -95,8 +81,6 @@ func encode(num int) string { } ``` -### **TypeScript** - ```ts function encode(num: number): string { ++num; @@ -105,10 +89,6 @@ function encode(num: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1256.Encode Number/README_EN.md b/solution/1200-1299/1256.Encode Number/README_EN.md index 6bc98bf3e1cb5..0ef6d977faf69 100644 --- a/solution/1200-1299/1256.Encode Number/README_EN.md +++ b/solution/1200-1299/1256.Encode Number/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Bit Manipulation** +### Solution 1: Bit Manipulation We add one to $num$, then convert it to a binary string and remove the highest bit $1$. @@ -42,16 +42,12 @@ The time complexity is $O(\log n)$, and the space complexity is $O(\log n)$. Whe -### **Python3** - ```python class Solution: def encode(self, num: int) -> str: return bin(num + 1)[3:] ``` -### **Java** - ```java class Solution { public String encode(int num) { @@ -60,8 +56,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -77,8 +71,6 @@ public: }; ``` -### **Go** - ```go func encode(num int) string { num++ @@ -87,8 +79,6 @@ func encode(num int) string { } ``` -### **TypeScript** - ```ts function encode(num: number): string { ++num; @@ -97,10 +87,6 @@ function encode(num: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1257.Smallest Common Region/README.md b/solution/1200-1299/1257.Smallest Common Region/README.md index 2f37438097c95..669c85cf36221 100644 --- a/solution/1200-1299/1257.Smallest Common Region/README.md +++ b/solution/1200-1299/1257.Smallest Common Region/README.md @@ -44,16 +44,10 @@ region2 = "New York" ## 解法 - - -题目可转换为“求最近公共祖先”问题。 +### 方法一 -### **Python3** - - - ```python class Solution: def findSmallestRegion( @@ -74,10 +68,6 @@ class Solution: return region1 ``` -### **Java** - - - ```java class Solution { public String findSmallestRegion(List> regions, String region1, String region2) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func findSmallestRegion(regions [][]string, region1 string, region2 string) string { m := make(map[string]string) @@ -152,10 +138,6 @@ func findSmallestRegion(regions [][]string, region1 string, region2 string) stri } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1257.Smallest Common Region/README_EN.md b/solution/1200-1299/1257.Smallest Common Region/README_EN.md index 678d0a3c1f5fb..1903ad250bf7a 100644 --- a/solution/1200-1299/1257.Smallest Common Region/README_EN.md +++ b/solution/1200-1299/1257.Smallest Common Region/README_EN.md @@ -49,9 +49,9 @@ region2 = "New York" ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return region1 ``` -### **Java** - ```java class Solution { public String findSmallestRegion(List> regions, String region1, String region2) { @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +120,6 @@ public: }; ``` -### **Go** - ```go func findSmallestRegion(regions [][]string, region1 string, region2 string) string { m := make(map[string]string) @@ -149,10 +143,6 @@ func findSmallestRegion(regions [][]string, region1 string, region2 string) stri } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1258.Synonymous Sentences/README.md b/solution/1200-1299/1258.Synonymous Sentences/README.md index 326fd60ef8365..422f30da4c05a 100644 --- a/solution/1200-1299/1258.Synonymous Sentences/README.md +++ b/solution/1200-1299/1258.Synonymous Sentences/README.md @@ -41,9 +41,7 @@ text = "I am happy today but was sad yesterday" ## 解法 - - -**方法一:并查集 + DFS** +### 方法一:并查集 + DFS 我们可以发现,题目中的近义词是可以传递的,即如果 `a` 和 `b` 是近义词,`b` 和 `c` 是近义词,那么 `a` 和 `c` 也是近义词。因此,我们可以用并查集找出近义词的连通分量,每个连通分量中的单词都是近义词,并且按字典序从小到大排列。 @@ -59,10 +57,6 @@ text = "I am happy today but was sad yesterday" -### **Python3** - - - ```python class UnionFind: def __init__(self, n): @@ -119,10 +113,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class UnionFind { private int[] p; @@ -215,8 +205,6 @@ class Solution { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -315,8 +303,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p, size []int @@ -403,10 +389,6 @@ func generateSentences(synonyms [][]string, text string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1258.Synonymous Sentences/README_EN.md b/solution/1200-1299/1258.Synonymous Sentences/README_EN.md index e3b6b4a8e1d81..fa2fa229b414f 100644 --- a/solution/1200-1299/1258.Synonymous Sentences/README_EN.md +++ b/solution/1200-1299/1258.Synonymous Sentences/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Union-Find + DFS** +### Solution 1: Union-Find + DFS We can notice that the synonyms in the problem are transitive, i.e., if `a` and `b` are synonyms, and `b` and `c` are synonyms, then `a` and `c` are also synonyms. Therefore, we can use a union-find set to find the connected components of synonyms, where all the words in each connected component are synonyms and are sorted in lexicographical order. @@ -54,8 +54,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ i -### **Python3** - ```python class UnionFind: def __init__(self, n): @@ -112,8 +110,6 @@ class Solution: return ans ``` -### **Java** - ```java class UnionFind { private int[] p; @@ -206,8 +202,6 @@ class Solution { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -306,8 +300,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p, size []int @@ -394,10 +386,6 @@ func generateSentences(synonyms [][]string, text string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1259.Handshakes That Don't Cross/README.md b/solution/1200-1299/1259.Handshakes That Don't Cross/README.md index a1fe114a71b23..567894507b94d 100644 --- a/solution/1200-1299/1259.Handshakes That Don't Cross/README.md +++ b/solution/1200-1299/1259.Handshakes That Don't Cross/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i)$,表示 $i$ 个人的握手方案数。答案为 $dfs(n)$。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def numberOfWays(self, numPeople: int) -> int: @@ -93,10 +87,6 @@ class Solution: return dfs(numPeople) ``` -### **Java** - - - ```java class Solution { private int[] f; @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func numberOfWays(numPeople int) int { const mod int = 1e9 + 7 @@ -174,8 +160,6 @@ func numberOfWays(numPeople int) int { } ``` -### **TypeScript** - ```ts function numberOfWays(numPeople: number): number { const mod = 10 ** 9 + 7; @@ -198,10 +182,6 @@ function numberOfWays(numPeople: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1259.Handshakes That Don't Cross/README_EN.md b/solution/1200-1299/1259.Handshakes That Don't Cross/README_EN.md index 98d1298786878..e8fc173d07e52 100644 --- a/solution/1200-1299/1259.Handshakes That Don't Cross/README_EN.md +++ b/solution/1200-1299/1259.Handshakes That Don't Cross/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We design a function $dfs(i)$, which represents the number of handshake schemes for $i$ people. The answer is $dfs(n)$. @@ -51,8 +51,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ i -### **Python3** - ```python class Solution: def numberOfWays(self, numPeople: int) -> int: @@ -71,8 +69,6 @@ class Solution: return dfs(numPeople) ``` -### **Java** - ```java class Solution { private int[] f; @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +120,6 @@ public: }; ``` -### **Go** - ```go func numberOfWays(numPeople int) int { const mod int = 1e9 + 7 @@ -150,8 +142,6 @@ func numberOfWays(numPeople int) int { } ``` -### **TypeScript** - ```ts function numberOfWays(numPeople: number): number { const mod = 10 ** 9 + 7; @@ -174,10 +164,6 @@ function numberOfWays(numPeople: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1260.Shift 2D Grid/README.md b/solution/1200-1299/1260.Shift 2D Grid/README.md index e3cabc3f47879..0e2cf67137d70 100644 --- a/solution/1200-1299/1260.Shift 2D Grid/README.md +++ b/solution/1200-1299/1260.Shift 2D Grid/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:二维数组展开** +### 方法一:二维数组展开 根据题目描述,如果我们将二维数组展开成一维数组,那么每次迁移操作就是将数组中的元素向右移动一个位置,最后一个元素移动到数组的首位。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> shiftGrid(int[][] grid, int k) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func shiftGrid(grid [][]int, k int) [][]int { m, n := len(grid), len(grid[0]) @@ -156,8 +142,6 @@ func shiftGrid(grid [][]int, k int) [][]int { } ``` -### **TypeScript** - ```ts function shiftGrid(grid: number[][], k: number): number[][] { const [m, n] = [grid.length, grid[0].length]; @@ -173,10 +157,6 @@ function shiftGrid(grid: number[][], k: number): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1260.Shift 2D Grid/README_EN.md b/solution/1200-1299/1260.Shift 2D Grid/README_EN.md index 62b7542939820..13b5a4d2231e2 100644 --- a/solution/1200-1299/1260.Shift 2D Grid/README_EN.md +++ b/solution/1200-1299/1260.Shift 2D Grid/README_EN.md @@ -52,7 +52,7 @@ ## Solutions -**Solution 1: Flattening the 2D Array** +### Solution 1: Flattening the 2D Array According to the problem description, if we flatten the 2D array into a 1D array, then each shift operation is to move the elements in the array one position to the right, with the last element moving to the first position of the array. @@ -62,8 +62,6 @@ The time complexity is $O(m \times n)$, where $m$ and $n$ are the number of rows -### **Python3** - ```python class Solution: def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: @@ -76,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List> shiftGrid(int[][] grid, int k) { @@ -102,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func shiftGrid(grid [][]int, k int) [][]int { m, n := len(grid), len(grid[0]) @@ -142,8 +134,6 @@ func shiftGrid(grid [][]int, k int) [][]int { } ``` -### **TypeScript** - ```ts function shiftGrid(grid: number[][], k: number): number[][] { const [m, n] = [grid.length, grid[0].length]; @@ -159,10 +149,6 @@ function shiftGrid(grid: number[][], k: number): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1261.Find Elements in a Contaminated Binary Tree/README.md b/solution/1200-1299/1261.Find Elements in a Contaminated Binary Tree/README.md index 606c66e452dab..25ef4cb48072e 100644 --- a/solution/1200-1299/1261.Find Elements in a Contaminated Binary Tree/README.md +++ b/solution/1200-1299/1261.Find Elements in a Contaminated Binary Tree/README.md @@ -85,9 +85,7 @@ findElements.find(5); // return True ## 解法 - - -**方法一:DFS + 哈希表** +### 方法一:DFS + 哈希表 我们先通过 DFS 遍历二叉树,将节点值恢复为原来的值,然后再通过哈希表存储所有节点值,这样在查找时就可以直接判断目标值是否存在于哈希表中。 @@ -95,10 +93,6 @@ findElements.find(5); // return True -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -130,10 +124,6 @@ class FindElements: # param_1 = obj.find(target) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -182,8 +172,6 @@ class FindElements { */ ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -229,8 +217,6 @@ private: */ ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -274,10 +260,6 @@ func (this *FindElements) Find(target int) bool { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1261.Find Elements in a Contaminated Binary Tree/README_EN.md b/solution/1200-1299/1261.Find Elements in a Contaminated Binary Tree/README_EN.md index a74281996e891..6fb07a3bbf564 100644 --- a/solution/1200-1299/1261.Find Elements in a Contaminated Binary Tree/README_EN.md +++ b/solution/1200-1299/1261.Find Elements in a Contaminated Binary Tree/README_EN.md @@ -78,7 +78,7 @@ findElements.find(5); // return True ## Solutions -**Solution 1: DFS + Hash Table** +### Solution 1: DFS + Hash Table First, we traverse the binary tree using DFS to restore the node values to their original values. Then, we store all node values in a hash table, so we can directly check whether the target value exists in the hash table when searching. @@ -86,8 +86,6 @@ In terms of time complexity, we need to traverse the binary tree during initiali -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -119,8 +117,6 @@ class FindElements: # param_1 = obj.find(target) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -169,8 +165,6 @@ class FindElements { */ ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -216,8 +210,6 @@ private: */ ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -261,10 +253,6 @@ func (this *FindElements) Find(target int) bool { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1262.Greatest Sum Divisible by Three/README.md b/solution/1200-1299/1262.Greatest Sum Divisible by Three/README.md index ec81b67202b2d..73c8df2030f80 100644 --- a/solution/1200-1299/1262.Greatest Sum Divisible by Three/README.md +++ b/solution/1200-1299/1262.Greatest Sum Divisible by Three/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示前 $i$ 个数中选取若干个数,使得这若干个数的和模 $3$ 余 $j$ 的最大值。初始时 $f[0][0]=0$,其余为 $-\infty$。 @@ -69,10 +67,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxSumDivThree(self, nums: List[int]) -> int: @@ -85,22 +79,6 @@ class Solution: return f[n][0] ``` -```python -class Solution: - def maxSumDivThree(self, nums: List[int]) -> int: - f = [0, -inf, -inf] - for x in nums: - g = f[:] - for j in range(3): - g[j] = max(f[j], f[(j - x) % 3] + x) - f = g - return f[0] -``` - -### **Java** - - - ```java class Solution { public int maxSumDivThree(int[] nums) { @@ -119,25 +97,6 @@ class Solution { } ``` -```java -class Solution { - public int maxSumDivThree(int[] nums) { - final int inf = 1 << 30; - int[] f = new int[] {0, -inf, -inf}; - for (int x : nums) { - int[] g = f.clone(); - for (int j = 0; j < 3; ++j) { - g[j] = Math.max(f[j], f[(j - x % 3 + 3) % 3] + x); - } - f = g; - } - return f[0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -158,26 +117,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxSumDivThree(vector& nums) { - const int inf = 1 << 30; - vector f = {0, -inf, -inf}; - for (int& x : nums) { - vector g = f; - for (int j = 0; j < 3; ++j) { - g[j] = max(f[j], f[(j - x % 3 + 3) % 3] + x); - } - f = move(g); - } - return f[0]; - } -}; -``` - -### **Go** - ```go func maxSumDivThree(nums []int) int { n := len(nums) @@ -194,23 +133,6 @@ func maxSumDivThree(nums []int) int { } ``` -```go -func maxSumDivThree(nums []int) int { - const inf = 1 << 30 - f := [3]int{0, -inf, -inf} - for _, x := range nums { - g := [3]int{} - for j := range f { - g[j] = max(f[j], f[(j-x%3+3)%3]+x) - } - f = g - } - return f[0] -} -``` - -### **TypeScript** - ```ts function maxSumDivThree(nums: number[]): number { const n = nums.length; @@ -229,6 +151,74 @@ function maxSumDivThree(nums: number[]): number { } ``` + + +### 方法二 + + + +```python +class Solution: + def maxSumDivThree(self, nums: List[int]) -> int: + f = [0, -inf, -inf] + for x in nums: + g = f[:] + for j in range(3): + g[j] = max(f[j], f[(j - x) % 3] + x) + f = g + return f[0] +``` + +```java +class Solution { + public int maxSumDivThree(int[] nums) { + final int inf = 1 << 30; + int[] f = new int[] {0, -inf, -inf}; + for (int x : nums) { + int[] g = f.clone(); + for (int j = 0; j < 3; ++j) { + g[j] = Math.max(f[j], f[(j - x % 3 + 3) % 3] + x); + } + f = g; + } + return f[0]; + } +} +``` + +```cpp +class Solution { +public: + int maxSumDivThree(vector& nums) { + const int inf = 1 << 30; + vector f = {0, -inf, -inf}; + for (int& x : nums) { + vector g = f; + for (int j = 0; j < 3; ++j) { + g[j] = max(f[j], f[(j - x % 3 + 3) % 3] + x); + } + f = move(g); + } + return f[0]; + } +}; +``` + +```go +func maxSumDivThree(nums []int) int { + const inf = 1 << 30 + f := [3]int{0, -inf, -inf} + for _, x := range nums { + g := [3]int{} + for j := range f { + g[j] = max(f[j], f[(j-x%3+3)%3]+x) + } + f = g + } + return f[0] +} +``` + ```ts function maxSumDivThree(nums: number[]): number { const inf = 1 << 30; @@ -243,10 +233,6 @@ function maxSumDivThree(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1262.Greatest Sum Divisible by Three/README_EN.md b/solution/1200-1299/1262.Greatest Sum Divisible by Three/README_EN.md index b0298f28541bc..c99cac8832000 100644 --- a/solution/1200-1299/1262.Greatest Sum Divisible by Three/README_EN.md +++ b/solution/1200-1299/1262.Greatest Sum Divisible by Three/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ as the maximum sum of several numbers selected from the first $i$ numbers, such that the sum modulo $3$ equals $j$. Initially, $f[0][0]=0$, and the rest are $-\infty$. @@ -63,8 +63,6 @@ Note that the value of $f[i][j]$ is only related to $f[i-1][j]$ and $f[i-1][(j-x -### **Python3** - ```python class Solution: def maxSumDivThree(self, nums: List[int]) -> int: @@ -77,20 +75,6 @@ class Solution: return f[n][0] ``` -```python -class Solution: - def maxSumDivThree(self, nums: List[int]) -> int: - f = [0, -inf, -inf] - for x in nums: - g = f[:] - for j in range(3): - g[j] = max(f[j], f[(j - x) % 3] + x) - f = g - return f[0] -``` - -### **Java** - ```java class Solution { public int maxSumDivThree(int[] nums) { @@ -109,25 +93,6 @@ class Solution { } ``` -```java -class Solution { - public int maxSumDivThree(int[] nums) { - final int inf = 1 << 30; - int[] f = new int[] {0, -inf, -inf}; - for (int x : nums) { - int[] g = f.clone(); - for (int j = 0; j < 3; ++j) { - g[j] = Math.max(f[j], f[(j - x % 3 + 3) % 3] + x); - } - f = g; - } - return f[0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -148,26 +113,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxSumDivThree(vector& nums) { - const int inf = 1 << 30; - vector f = {0, -inf, -inf}; - for (int& x : nums) { - vector g = f; - for (int j = 0; j < 3; ++j) { - g[j] = max(f[j], f[(j - x % 3 + 3) % 3] + x); - } - f = move(g); - } - return f[0]; - } -}; -``` - -### **Go** - ```go func maxSumDivThree(nums []int) int { n := len(nums) @@ -184,23 +129,6 @@ func maxSumDivThree(nums []int) int { } ``` -```go -func maxSumDivThree(nums []int) int { - const inf = 1 << 30 - f := [3]int{0, -inf, -inf} - for _, x := range nums { - g := [3]int{} - for j := range f { - g[j] = max(f[j], f[(j-x%3+3)%3]+x) - } - f = g - } - return f[0] -} -``` - -### **TypeScript** - ```ts function maxSumDivThree(nums: number[]): number { const n = nums.length; @@ -219,6 +147,74 @@ function maxSumDivThree(nums: number[]): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def maxSumDivThree(self, nums: List[int]) -> int: + f = [0, -inf, -inf] + for x in nums: + g = f[:] + for j in range(3): + g[j] = max(f[j], f[(j - x) % 3] + x) + f = g + return f[0] +``` + +```java +class Solution { + public int maxSumDivThree(int[] nums) { + final int inf = 1 << 30; + int[] f = new int[] {0, -inf, -inf}; + for (int x : nums) { + int[] g = f.clone(); + for (int j = 0; j < 3; ++j) { + g[j] = Math.max(f[j], f[(j - x % 3 + 3) % 3] + x); + } + f = g; + } + return f[0]; + } +} +``` + +```cpp +class Solution { +public: + int maxSumDivThree(vector& nums) { + const int inf = 1 << 30; + vector f = {0, -inf, -inf}; + for (int& x : nums) { + vector g = f; + for (int j = 0; j < 3; ++j) { + g[j] = max(f[j], f[(j - x % 3 + 3) % 3] + x); + } + f = move(g); + } + return f[0]; + } +}; +``` + +```go +func maxSumDivThree(nums []int) int { + const inf = 1 << 30 + f := [3]int{0, -inf, -inf} + for _, x := range nums { + g := [3]int{} + for j := range f { + g[j] = max(f[j], f[(j-x%3+3)%3]+x) + } + f = g + } + return f[0] +} +``` + ```ts function maxSumDivThree(nums: number[]): number { const inf = 1 << 30; @@ -233,10 +229,6 @@ function maxSumDivThree(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1263.Minimum Moves to Move a Box to Their Target Location/README.md b/solution/1200-1299/1263.Minimum Moves to Move a Box to Their Target Location/README.md index 3c433c8a1a3a2..b8a254d31d646 100644 --- a/solution/1200-1299/1263.Minimum Moves to Move a Box to Their Target Location/README.md +++ b/solution/1200-1299/1263.Minimum Moves to Move a Box to Their Target Location/README.md @@ -78,9 +78,7 @@ ## 解法 - - -**方法一:双端队列 + BFS** +### 方法一:双端队列 + BFS 我们把玩家的位置和箱子的位置看成一个状态,即 $(s_i, s_j, b_i, b_j)$,其中 $(s_i, s_j)$ 是玩家的位置,而 $(b_i, b_j)$ 是箱子的位置。在代码实现上,我们定义一个函数 $f(i, j)$,它将二维坐标 $(i, j)$ 映射到一个一维的状态编号,即 $f(i, j) = i \times n + j$,其中 $n$ 是网格的列数。那么玩家和箱子的状态就是 $(f(s_i, s_j), f(b_i, b_j))$。 @@ -109,10 +107,6 @@ -### **Python3** - - - ```python class Solution: def minPushBox(self, grid: List[List[str]]) -> int: @@ -155,10 +149,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { private int m; @@ -227,8 +217,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -287,8 +275,6 @@ public: }; ``` -### **Go** - ```go func minPushBox(grid [][]byte) int { m, n := len(grid), len(grid[0]) @@ -345,8 +331,6 @@ func minPushBox(grid [][]byte) int { } ``` -### **TypeScript** - ```ts function minPushBox(grid: string[][]): number { const [m, n] = [grid.length, grid[0].length]; @@ -568,10 +552,6 @@ class Deque { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1263.Minimum Moves to Move a Box to Their Target Location/README_EN.md b/solution/1200-1299/1263.Minimum Moves to Move a Box to Their Target Location/README_EN.md index 2396479ad4232..cc5f4ac3ab936 100644 --- a/solution/1200-1299/1263.Minimum Moves to Move a Box to Their Target Location/README_EN.md +++ b/solution/1200-1299/1263.Minimum Moves to Move a Box to Their Target Location/README_EN.md @@ -72,7 +72,7 @@ ## Solutions -**Solution 1: Double-ended Queue + BFS** +### Solution 1: Double-ended Queue + BFS We consider the player's position and the box's position as a state, i.e., $(s_i, s_j, b_i, b_j)$, where $(s_i, s_j)$ is the player's position, and $(b_i, b_j)$ is the box's position. In the code implementation, we define a function $f(i, j)$, which maps the two-dimensional coordinates $(i, j)$ to a one-dimensional state number, i.e., $f(i, j) = i \times n + j$, where $n$ is the number of columns in the grid. So the player and the box's state is $(f(s_i, s_j), f(b_i, b_j))$. @@ -101,8 +101,6 @@ The time complexity is $O(m^2 \times n^2)$, and the space complexity is $O(m^2 \ -### **Python3** - ```python class Solution: def minPushBox(self, grid: List[List[str]]) -> int: @@ -145,8 +143,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { private int m; @@ -215,8 +211,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -275,8 +269,6 @@ public: }; ``` -### **Go** - ```go func minPushBox(grid [][]byte) int { m, n := len(grid), len(grid[0]) @@ -333,8 +325,6 @@ func minPushBox(grid [][]byte) int { } ``` -### **TypeScript** - ```ts function minPushBox(grid: string[][]): number { const [m, n] = [grid.length, grid[0].length]; @@ -556,10 +546,6 @@ class Deque { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1264.Page Recommendations/README.md b/solution/1200-1299/1264.Page Recommendations/README.md index 1b057a92db270..726d552d47246 100644 --- a/solution/1200-1299/1264.Page Recommendations/README.md +++ b/solution/1200-1299/1264.Page Recommendations/README.md @@ -94,16 +94,12 @@ Likes table: ## 解法 - - -**方法一:合并 + 等值连接 + 子查询** +### 方法一:合并 + 等值连接 + 子查询 我们先查出所有与 `user_id = 1` 的用户是朋友的用户,记录在 `T` 表中,然后再查出所有在 `T` 表中的用户喜欢的页面,最后排除掉 `user_id = 1` 喜欢的页面即可。 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -119,6 +115,12 @@ FROM WHERE page_id NOT IN (SELECT page_id FROM Likes WHERE user_id = 1); ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below SELECT DISTINCT page_id AS recommended_page @@ -133,3 +135,5 @@ WHERE ``` + + diff --git a/solution/1200-1299/1264.Page Recommendations/README_EN.md b/solution/1200-1299/1264.Page Recommendations/README_EN.md index a1482a99fd9b9..a773460f4ff09 100644 --- a/solution/1200-1299/1264.Page Recommendations/README_EN.md +++ b/solution/1200-1299/1264.Page Recommendations/README_EN.md @@ -90,14 +90,12 @@ Page 88 is not suggested because user 1 already likes it. ## Solutions -**Solution 1: Union + Equi-Join + Subquery** +### Solution 1: Union + Equi-Join + Subquery First, we query all users who are friends with `user_id = 1` and record them in the `T` table. Then, we query all pages that users in the `T` table like, and finally exclude the pages that `user_id = 1` likes. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -113,6 +111,12 @@ FROM WHERE page_id NOT IN (SELECT page_id FROM Likes WHERE user_id = 1); ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below SELECT DISTINCT page_id AS recommended_page @@ -127,3 +131,5 @@ WHERE ``` + + diff --git a/solution/1200-1299/1265.Print Immutable Linked List in Reverse/README.md b/solution/1200-1299/1265.Print Immutable Linked List in Reverse/README.md index 758f48cd6de58..f1f86e400db34 100644 --- a/solution/1200-1299/1265.Print Immutable Linked List in Reverse/README.md +++ b/solution/1200-1299/1265.Print Immutable Linked List in Reverse/README.md @@ -69,9 +69,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们可以使用递归来实现链表的逆序打印。在函数中,我们判断当前节点是否为空,如果不为空,则获取下一个节点,然后递归调用函数本身,最后打印当前节点的值。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python # """ # This is the ImmutableListNode's API interface. @@ -100,10 +94,6 @@ class Solution: head.printValue() ``` -### **Java** - - - ```java /** * // This is the ImmutableListNode's API interface. @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the ImmutableListNode's API interface. @@ -148,8 +136,6 @@ public: }; ``` -### **Go** - ```go /* Below is the interface for ImmutableListNode, which is already defined for you. * @@ -174,8 +160,6 @@ func printLinkedListInReverse(head ImmutableListNode) { } ``` -### **TypeScript** - ```ts /** * // This is the ImmutableListNode's API interface. @@ -195,8 +179,6 @@ function printLinkedListInReverse(head: ImmutableListNode) { } ``` -### **C#** - ```cs /** * // This is the ImmutableListNode's API interface. @@ -217,10 +199,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1265.Print Immutable Linked List in Reverse/README_EN.md b/solution/1200-1299/1265.Print Immutable Linked List in Reverse/README_EN.md index 62acdbb7c46ca..a60c1c33b4ccf 100644 --- a/solution/1200-1299/1265.Print Immutable Linked List in Reverse/README_EN.md +++ b/solution/1200-1299/1265.Print Immutable Linked List in Reverse/README_EN.md @@ -65,7 +65,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion We can use recursion to implement reverse printing of a linked list. In the function, we check whether the current node is null. If it is not null, we get the next node, then recursively call the function itself, and finally print the value of the current node. @@ -73,8 +73,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python # """ # This is the ImmutableListNode's API interface. @@ -92,8 +90,6 @@ class Solution: head.printValue() ``` -### **Java** - ```java /** * // This is the ImmutableListNode's API interface. @@ -114,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the ImmutableListNode's API interface. @@ -138,8 +132,6 @@ public: }; ``` -### **Go** - ```go /* Below is the interface for ImmutableListNode, which is already defined for you. * @@ -164,8 +156,6 @@ func printLinkedListInReverse(head ImmutableListNode) { } ``` -### **TypeScript** - ```ts /** * // This is the ImmutableListNode's API interface. @@ -185,8 +175,6 @@ function printLinkedListInReverse(head: ImmutableListNode) { } ``` -### **C#** - ```cs /** * // This is the ImmutableListNode's API interface. @@ -207,10 +195,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1266.Minimum Time Visiting All Points/README.md b/solution/1200-1299/1266.Minimum Time Visiting All Points/README.md index ea138989dae8e..fd71c58eecf73 100644 --- a/solution/1200-1299/1266.Minimum Time Visiting All Points/README.md +++ b/solution/1200-1299/1266.Minimum Time Visiting All Points/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 对于两个点 $p1=(x_1, y_1)$ 和 $p2=(x_2, y_2)$,横坐标和纵坐标分别移动的距离分别为 $dx = |x_1 - x_2|$ 和 $dy = |y_1 - y_2|$。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int: @@ -82,10 +76,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public int minTimeToVisitAllPoints(int[][] points) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func minTimeToVisitAllPoints(points [][]int) (ans int) { for i, p := range points[1:] { @@ -137,8 +123,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minTimeToVisitAllPoints(points: number[][]): number { let ans = 0; @@ -151,8 +135,6 @@ function minTimeToVisitAllPoints(points: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_time_to_visit_all_points(points: Vec>) -> i32 { @@ -168,8 +150,6 @@ impl Solution { } ``` -### **C** - ```c #define max(a, b) (((a) > (b)) ? (a) : (b)) @@ -184,10 +164,6 @@ int minTimeToVisitAllPoints(int** points, int pointsSize, int* pointsColSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1266.Minimum Time Visiting All Points/README_EN.md b/solution/1200-1299/1266.Minimum Time Visiting All Points/README_EN.md index d43bb299fe295..182dddf4a893f 100644 --- a/solution/1200-1299/1266.Minimum Time Visiting All Points/README_EN.md +++ b/solution/1200-1299/1266.Minimum Time Visiting All Points/README_EN.md @@ -50,7 +50,7 @@ Total time = 7 seconds ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation For two points $p1=(x_1, y_1)$ and $p2=(x_2, y_2)$, the distances moved in the x-axis and y-axis are $dx = |x_1 - x_2|$ and $dy = |y_1 - y_2|$ respectively. @@ -62,8 +62,6 @@ The time complexity is $O(n)$, where $n$ is the number of points. The space comp -### **Python3** - ```python class Solution: def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int: @@ -72,8 +70,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public int minTimeToVisitAllPoints(int[][] points) { @@ -88,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +99,6 @@ public: }; ``` -### **Go** - ```go func minTimeToVisitAllPoints(points [][]int) (ans int) { for i, p := range points[1:] { @@ -125,8 +117,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minTimeToVisitAllPoints(points: number[][]): number { let ans = 0; @@ -139,8 +129,6 @@ function minTimeToVisitAllPoints(points: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_time_to_visit_all_points(points: Vec>) -> i32 { @@ -156,8 +144,6 @@ impl Solution { } ``` -### **C** - ```c #define max(a, b) (((a) > (b)) ? (a) : (b)) @@ -172,10 +158,6 @@ int minTimeToVisitAllPoints(int** points, int pointsSize, int* pointsColSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1267.Count Servers that Communicate/README.md b/solution/1200-1299/1267.Count Servers that Communicate/README.md index fbe75925d034e..20011f90556f9 100644 --- a/solution/1200-1299/1267.Count Servers that Communicate/README.md +++ b/solution/1200-1299/1267.Count Servers that Communicate/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们可以统计每一行、每一列的服务器数量,然后遍历每个服务器,若当前服务器所在的行或者列的服务器数量超过 $1$,说明当前服务器满足条件,结果加 $1$。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def countServers(self, grid: List[List[int]]) -> int: @@ -88,10 +82,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public int countServers(int[][] grid) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func countServers(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -171,8 +157,6 @@ func countServers(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function countServers(grid: number[][]): number { const m = grid.length; @@ -199,10 +183,6 @@ function countServers(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1267.Count Servers that Communicate/README_EN.md b/solution/1200-1299/1267.Count Servers that Communicate/README_EN.md index 0d97393e789b4..c006d33dcb732 100644 --- a/solution/1200-1299/1267.Count Servers that Communicate/README_EN.md +++ b/solution/1200-1299/1267.Count Servers that Communicate/README_EN.md @@ -51,7 +51,7 @@ Return the number of servers that communicate with any other server.

## Solutions -**Solution 1: Counting** +### Solution 1: Counting We can count the number of servers in each row and each column, then traverse each server. If the number of servers in the current server's row or column exceeds $1$, it means the current server meets the condition, and we increment the result by $1$. @@ -61,8 +61,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m + n)$. -### **Python3** - ```python class Solution: def countServers(self, grid: List[List[int]]) -> int: @@ -81,8 +79,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public int countServers(int[][] grid) { @@ -110,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +131,6 @@ public: }; ``` -### **Go** - ```go func countServers(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -162,8 +154,6 @@ func countServers(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function countServers(grid: number[][]): number { const m = grid.length; @@ -190,10 +180,6 @@ function countServers(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1268.Search Suggestions System/README.md b/solution/1200-1299/1268.Search Suggestions System/README.md index e27ba4ecc18c7..c66f284628fcd 100644 --- a/solution/1200-1299/1268.Search Suggestions System/README.md +++ b/solution/1200-1299/1268.Search Suggestions System/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:排序 + 前缀树** +### 方法一:排序 + 前缀树 题目要求在输入 `searchWord` 的每一个字母后,推荐 `products` 数组中前缀与 `searchWord` 相同的最多三个产品。如果前缀相同的可推荐产品超过三个,按字典序返回最小的三个。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Trie: def __init__(self): @@ -123,10 +117,6 @@ class Solution: return [[products[i] for i in v] for v in trie.search(searchWord)] ``` -### **Java** - - - ```java class Trie { Trie[] children = new Trie[26]; @@ -183,8 +173,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -243,8 +231,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -300,10 +286,6 @@ func suggestedProducts(products []string, searchWord string) (ans [][]string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1268.Search Suggestions System/README_EN.md b/solution/1200-1299/1268.Search Suggestions System/README_EN.md index 36d5c49b16b0a..17919054a51a9 100644 --- a/solution/1200-1299/1268.Search Suggestions System/README_EN.md +++ b/solution/1200-1299/1268.Search Suggestions System/README_EN.md @@ -44,7 +44,7 @@ After typing mou, mous and mouse the system suggests ["mouse","mo ## Solutions -**Solution 1: Sorting + Trie** +### Solution 1: Sorting + Trie The problem requires that after each letter of the input `searchWord`, recommend up to three products from the `products` array that have the same prefix as `searchWord`. If there are more than three products with the same prefix that can be recommended, return the three with the smallest lexicographic order. @@ -61,8 +61,6 @@ The time complexity is $O(L \times \log n + m)$, and the space complexity is $O( -### **Python3** - ```python class Trie: def __init__(self): @@ -102,8 +100,6 @@ class Solution: return [[products[i] for i in v] for v in trie.search(searchWord)] ``` -### **Java** - ```java class Trie { Trie[] children = new Trie[26]; @@ -160,8 +156,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -220,8 +214,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -277,10 +269,6 @@ func suggestedProducts(products []string, searchWord string) (ans [][]string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1269.Number of Ways to Stay in the Same Place After Some Steps/README.md b/solution/1200-1299/1269.Number of Ways to Stay in the Same Place After Some Steps/README.md index e0fbc92982dd3..afc0b225f9dc9 100644 --- a/solution/1200-1299/1269.Number of Ways to Stay in the Same Place After Some Steps/README.md +++ b/solution/1200-1299/1269.Number of Ways to Stay in the Same Place After Some Steps/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们观察题目的数据范围,可以发现 $steps$ 最大不超过 $500$,这意味着我们最远只能往右走 $500$ 步。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def numWays(self, steps: int, arrLen: int) -> int: @@ -99,10 +93,6 @@ class Solution: return dfs(0, steps) ``` -### **Java** - - - ```java class Solution { private Integer[][] f; @@ -134,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +152,6 @@ public: }; ``` -### **Go** - ```go func numWays(steps int, arrLen int) int { const mod int = 1e9 + 7 @@ -198,8 +184,6 @@ func numWays(steps int, arrLen int) int { } ``` -### **TypeScript** - ```ts function numWays(steps: number, arrLen: number): number { const f = Array.from({ length: steps }, () => Array(steps + 1).fill(-1)); @@ -224,10 +208,6 @@ function numWays(steps: number, arrLen: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1269.Number of Ways to Stay in the Same Place After Some Steps/README_EN.md b/solution/1200-1299/1269.Number of Ways to Stay in the Same Place After Some Steps/README_EN.md index 8863d761b539f..41f274cc43bd4 100644 --- a/solution/1200-1299/1269.Number of Ways to Stay in the Same Place After Some Steps/README_EN.md +++ b/solution/1200-1299/1269.Number of Ways to Stay in the Same Place After Some Steps/README_EN.md @@ -48,7 +48,7 @@ Stay, Stay ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We observe the data range of the problem and find that $steps$ does not exceed $500$, which means that we can only go to the right for up to $500$ steps. @@ -66,8 +66,6 @@ The time complexity is $O(steps \times steps)$, and the space complexity is $O(s -### **Python3** - ```python class Solution: def numWays(self, steps: int, arrLen: int) -> int: @@ -87,8 +85,6 @@ class Solution: return dfs(0, steps) ``` -### **Java** - ```java class Solution { private Integer[][] f; @@ -120,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +144,6 @@ public: }; ``` -### **Go** - ```go func numWays(steps int, arrLen int) int { const mod int = 1e9 + 7 @@ -184,8 +176,6 @@ func numWays(steps int, arrLen int) int { } ``` -### **TypeScript** - ```ts function numWays(steps: number, arrLen: number): number { const f = Array.from({ length: steps }, () => Array(steps + 1).fill(-1)); @@ -210,10 +200,6 @@ function numWays(steps: number, arrLen: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1270.All People Report to the Given Manager/README.md b/solution/1200-1299/1270.All People Report to the Given Manager/README.md index 773b576d5ffba..4703fabbce5d6 100644 --- a/solution/1200-1299/1270.All People Report to the Given Manager/README.md +++ b/solution/1200-1299/1270.All People Report to the Given Manager/README.md @@ -69,9 +69,7 @@ employee_id 是 3, 8 ,9 的职员不会直接或间接的汇报给公司 CEO ## 解法 - - -**方法一:两次连接** +### 方法一:两次连接 我们可以通过两次连接来找到所有直接或间接向公司 CEO 汇报工作的职工的 `employee_id`。 @@ -79,8 +77,6 @@ employee_id 是 3, 8 ,9 的职员不会直接或间接的汇报给公司 CEO -### **SQL** - ```sql # Write your MySQL query statement below SELECT e1.employee_id @@ -92,3 +88,5 @@ WHERE e1.employee_id != 1 AND e3.manager_id = 1; ``` + + diff --git a/solution/1200-1299/1270.All People Report to the Given Manager/README_EN.md b/solution/1200-1299/1270.All People Report to the Given Manager/README_EN.md index f01eff0260bd0..919596871205e 100644 --- a/solution/1200-1299/1270.All People Report to the Given Manager/README_EN.md +++ b/solution/1200-1299/1270.All People Report to the Given Manager/README_EN.md @@ -66,7 +66,7 @@ The employees with employee_id 3, 8, and 9 do not report their work to the head ## Solutions -**Solution 1: Two Joins** +### Solution 1: Two Joins We can use two joins to find all employees who report directly or indirectly to the company CEO. @@ -74,8 +74,6 @@ Specifically, we first use a join to find the `manager_id` of the superior manag -### **SQL** - ```sql # Write your MySQL query statement below SELECT e1.employee_id @@ -87,3 +85,5 @@ WHERE e1.employee_id != 1 AND e3.manager_id = 1; ``` + + diff --git a/solution/1200-1299/1271.Hexspeak/README.md b/solution/1200-1299/1271.Hexspeak/README.md index 406e987167a3b..25a7e0a2e3c67 100644 --- a/solution/1200-1299/1271.Hexspeak/README.md +++ b/solution/1200-1299/1271.Hexspeak/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 将数字转换为十六进制字符串,然后遍历字符串,将数字 $0$ 转换为字母 $O$,将数字 $1$ 转换为字母 $I$,最后判断转换后的字符串是否合法。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def toHexspeak(self, num: str) -> str: @@ -61,10 +55,6 @@ class Solution: return t if all(c in s for c in t) else 'ERROR' ``` -### **Java** - - - ```java class Solution { private static final Set S = Set.of('A', 'B', 'C', 'D', 'E', 'F', 'I', 'O'); @@ -82,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +93,6 @@ public: }; ``` -### **Go** - ```go func toHexspeak(num string) string { x, _ := strconv.Atoi(num) @@ -122,10 +108,6 @@ func toHexspeak(num string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1271.Hexspeak/README_EN.md b/solution/1200-1299/1271.Hexspeak/README_EN.md index 5870ff3464660..53d13d87b4480 100644 --- a/solution/1200-1299/1271.Hexspeak/README_EN.md +++ b/solution/1200-1299/1271.Hexspeak/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation Convert the number to a hexadecimal string, then traverse the string, convert the number $0$ to the letter $O$, and the number $1$ to the letter $I$. Finally, check whether the converted string is valid. @@ -43,8 +43,6 @@ The time complexity is $O(\log n)$, where $n$ is the size of the decimal number -### **Python3** - ```python class Solution: def toHexspeak(self, num: str) -> str: @@ -53,8 +51,6 @@ class Solution: return t if all(c in s for c in t) else 'ERROR' ``` -### **Java** - ```java class Solution { private static final Set S = Set.of('A', 'B', 'C', 'D', 'E', 'F', 'I', 'O'); @@ -72,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +89,6 @@ public: }; ``` -### **Go** - ```go func toHexspeak(num string) string { x, _ := strconv.Atoi(num) @@ -112,10 +104,6 @@ func toHexspeak(num string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1272.Remove Interval/README.md b/solution/1200-1299/1272.Remove Interval/README.md index 86cc3ab72605e..e6e877583bf04 100644 --- a/solution/1200-1299/1272.Remove Interval/README.md +++ b/solution/1200-1299/1272.Remove Interval/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:分类讨论** +### 方法一:分类讨论 我们记要删除的区间为 $[x, y)$,遍历区间列表,对于每个区间 $[a, b)$,有以下三种情况: @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def removeInterval( @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> removeInterval(int[][] intervals, int[] toBeRemoved) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func removeInterval(intervals [][]int, toBeRemoved []int) (ans [][]int) { x, y := toBeRemoved[0], toBeRemoved[1] @@ -159,10 +145,6 @@ func removeInterval(intervals [][]int, toBeRemoved []int) (ans [][]int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1272.Remove Interval/README_EN.md b/solution/1200-1299/1272.Remove Interval/README_EN.md index 8edee78080dee..0f15de0e118c5 100644 --- a/solution/1200-1299/1272.Remove Interval/README_EN.md +++ b/solution/1200-1299/1272.Remove Interval/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Case Discussion** +### Solution 1: Case Discussion We denote the interval to be removed as $[x, y)$. We traverse the interval list, and for each interval $[a, b)$, there are three cases: @@ -54,8 +54,6 @@ The time complexity is $O(n)$, where $n$ is the length of the interval list. The -### **Python3** - ```python class Solution: def removeInterval( @@ -74,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List> removeInterval(int[][] intervals, int[] toBeRemoved) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +119,6 @@ public: }; ``` -### **Go** - ```go func removeInterval(intervals [][]int, toBeRemoved []int) (ans [][]int) { x, y := toBeRemoved[0], toBeRemoved[1] @@ -147,10 +139,6 @@ func removeInterval(intervals [][]int, toBeRemoved []int) (ans [][]int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1273.Delete Tree Nodes/README.md b/solution/1200-1299/1273.Delete Tree Nodes/README.md index 4730c22117893..00abb94f8a872 100644 --- a/solution/1200-1299/1273.Delete Tree Nodes/README.md +++ b/solution/1200-1299/1273.Delete Tree Nodes/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们先将树转换成图 $g$,其中 $g[i]$ 表示节点 $i$ 的所有子节点。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def deleteTreeNodes(self, nodes: int, parent: List[int], value: List[int]) -> int: @@ -99,10 +93,6 @@ class Solution: return dfs(0)[1] ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +148,6 @@ public: }; ``` -### **Go** - ```go func deleteTreeNodes(nodes int, parent []int, value []int) int { g := make([][]int, nodes) @@ -186,10 +172,6 @@ func deleteTreeNodes(nodes int, parent []int, value []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1273.Delete Tree Nodes/README_EN.md b/solution/1200-1299/1273.Delete Tree Nodes/README_EN.md index 0fa10aab68e58..e6bc71d2c9078 100644 --- a/solution/1200-1299/1273.Delete Tree Nodes/README_EN.md +++ b/solution/1200-1299/1273.Delete Tree Nodes/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS First, we convert the tree into a graph $g$, where $g[i]$ represents all the child nodes of node $i$. @@ -58,8 +58,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def deleteTreeNodes(self, nodes: int, parent: List[int], value: List[int]) -> int: @@ -79,8 +77,6 @@ class Solution: return dfs(0)[1] ``` -### **Java** - ```java class Solution { private List[] g; @@ -111,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +132,6 @@ public: }; ``` -### **Go** - ```go func deleteTreeNodes(nodes int, parent []int, value []int) int { g := make([][]int, nodes) @@ -164,10 +156,6 @@ func deleteTreeNodes(nodes int, parent []int, value []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1274.Number of Ships in a Rectangle/README.md b/solution/1200-1299/1274.Number of Ships in a Rectangle/README.md index cfabdf1e0d193..2218356997918 100644 --- a/solution/1200-1299/1274.Number of Ships in a Rectangle/README.md +++ b/solution/1200-1299/1274.Number of Ships in a Rectangle/README.md @@ -51,9 +51,7 @@ ships = [[1,1],[2,2],[3,3],[5,5]], topRight = [4,4], bottomLeft = [0,0] ## 解法 - - -**方法一:递归 + 分治** +### 方法一:递归 + 分治 由于矩形内最多只有 $10$ 艘船,所以我们可以将矩形划分为四个子矩形,分别求出每个子矩形内船只的数目,然后将四个子矩形内船只的数目相加即可。如果一个子矩形内没有船只,那么就不需要再继续划分了。 @@ -61,10 +59,6 @@ ships = [[1,1],[2,2],[3,3],[5,5]], topRight = [4,4], bottomLeft = [0,0] -### **Python3** - - - ```python # """ # This is Sea's API interface. @@ -101,10 +95,6 @@ class Solution: return dfs(topRight, bottomLeft) ``` -### **Java** - - - ```java /** * // This is Sea's API interface. @@ -138,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is Sea's API interface. @@ -175,8 +163,6 @@ public: }; ``` -### **Go** - ```go /** * // This is Sea's API interface. @@ -208,8 +194,6 @@ func countShips(sea Sea, topRight, bottomLeft []int) int { } ``` -### **TypeScript** - ```ts /** * // This is the Sea's API interface. @@ -238,10 +222,6 @@ function countShips(sea: Sea, topRight: number[], bottomLeft: number[]): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1274.Number of Ships in a Rectangle/README_EN.md b/solution/1200-1299/1274.Number of Ships in a Rectangle/README_EN.md index 2464ba0cc89fd..0ff4bdefbe69b 100644 --- a/solution/1200-1299/1274.Number of Ships in a Rectangle/README_EN.md +++ b/solution/1200-1299/1274.Number of Ships in a Rectangle/README_EN.md @@ -43,7 +43,7 @@ ships = [[1,1],[2,2],[3,3],[5,5]], topRight = [4,4], bottomLeft = [0,0] ## Solutions -**Solution 1: Recursion + Divide and Conquer** +### Solution 1: Recursion + Divide and Conquer Since there are at most $10$ ships in the rectangle, we can divide the rectangle into four sub-rectangles, calculate the number of ships in each sub-rectangle, and then add the number of ships in the four sub-rectangles. If there are no ships in a sub-rectangle, then there is no need to continue dividing. @@ -51,8 +51,6 @@ The time complexity is $O(C \times \log \max(m, n))$, and the space complexity i -### **Python3** - ```python # """ # This is Sea's API interface. @@ -89,8 +87,6 @@ class Solution: return dfs(topRight, bottomLeft) ``` -### **Java** - ```java /** * // This is Sea's API interface. @@ -124,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is Sea's API interface. @@ -161,8 +155,6 @@ public: }; ``` -### **Go** - ```go /** * // This is Sea's API interface. @@ -194,8 +186,6 @@ func countShips(sea Sea, topRight, bottomLeft []int) int { } ``` -### **TypeScript** - ```ts /** * // This is the Sea's API interface. @@ -224,10 +214,6 @@ function countShips(sea: Sea, topRight: number[], bottomLeft: number[]): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1275.Find Winner on a Tic Tac Toe Game/README.md b/solution/1200-1299/1275.Find Winner on a Tic Tac Toe Game/README.md index 6305aa0275e6e..507daeb0b2716 100644 --- a/solution/1200-1299/1275.Find Winner on a Tic Tac Toe Game/README.md +++ b/solution/1200-1299/1275.Find Winner on a Tic Tac Toe Game/README.md @@ -81,9 +81,7 @@ ## 解法 - - -**方法一:判断最后一个落棋的人能否获胜** +### 方法一:判断最后一个落棋的人能否获胜 由于 `moves` 都有效,也即是说,不存在某个人获胜后,其他人仍然落棋的情况。因此,只需判断最后一个落棋的人能否获胜即可。 @@ -95,10 +93,6 @@ -### **Python3** - - - ```python class Solution: def tictactoe(self, moves: List[List[int]]) -> str: @@ -117,10 +111,6 @@ class Solution: return "Draw" if n == 9 else "Pending" ``` -### **Java** - - - ```java class Solution { public String tictactoe(int[][] moves) { @@ -145,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -172,8 +160,6 @@ public: }; ``` -### **Go** - ```go func tictactoe(moves [][]int) string { n := len(moves) @@ -202,8 +188,6 @@ func tictactoe(moves [][]int) string { } ``` -### **TypeScript** - ```ts function tictactoe(moves: number[][]): string { const n = moves.length; @@ -226,10 +210,6 @@ function tictactoe(moves: number[][]): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1275.Find Winner on a Tic Tac Toe Game/README_EN.md b/solution/1200-1299/1275.Find Winner on a Tic Tac Toe Game/README_EN.md index 97e7bad625f7f..8479db875e0ca 100644 --- a/solution/1200-1299/1275.Find Winner on a Tic Tac Toe Game/README_EN.md +++ b/solution/1200-1299/1275.Find Winner on a Tic Tac Toe Game/README_EN.md @@ -57,7 +57,7 @@ ## Solutions -**Solution 1: Determine if the last player to move can win** +### Solution 1: Determine if the last player to move can win Since all `moves` are valid, that is, there is no situation where a person continues to play after someone has won. Therefore, we only need to determine whether the last player to move can win. @@ -69,8 +69,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def tictactoe(self, moves: List[List[int]]) -> str: @@ -89,8 +87,6 @@ class Solution: return "Draw" if n == 9 else "Pending" ``` -### **Java** - ```java class Solution { public String tictactoe(int[][] moves) { @@ -115,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go func tictactoe(moves [][]int) string { n := len(moves) @@ -172,8 +164,6 @@ func tictactoe(moves [][]int) string { } ``` -### **TypeScript** - ```ts function tictactoe(moves: number[][]): string { const n = moves.length; @@ -196,10 +186,6 @@ function tictactoe(moves: number[][]): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1276.Number of Burgers with No Waste of Ingredients/README.md b/solution/1200-1299/1276.Number of Burgers with No Waste of Ingredients/README.md index d7e8ec96f308f..b5d5a9dc0de06 100644 --- a/solution/1200-1299/1276.Number of Burgers with No Waste of Ingredients/README.md +++ b/solution/1200-1299/1276.Number of Burgers with No Waste of Ingredients/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 我们设巨无霸汉堡数量为 $x$,小皇堡数量为 $y$,则有: @@ -93,10 +91,6 @@ $$ -### **Python3** - - - ```python class Solution: def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]: @@ -106,10 +100,6 @@ class Solution: return [] if k % 2 or y < 0 or x < 0 else [x, y] ``` -### **Java** - - - ```java class Solution { public List numOfBurgers(int tomatoSlices, int cheeseSlices) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func numOfBurgers(tomatoSlices int, cheeseSlices int) []int { k := 4*cheeseSlices - tomatoSlices @@ -149,8 +135,6 @@ func numOfBurgers(tomatoSlices int, cheeseSlices int) []int { } ``` -### **TypeScript** - ```ts function numOfBurgers(tomatoSlices: number, cheeseSlices: number): number[] { const k = 4 * cheeseSlices - tomatoSlices; @@ -160,8 +144,6 @@ function numOfBurgers(tomatoSlices: number, cheeseSlices: number): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn num_of_burgers(tomato_slices: i32, cheese_slices: i32) -> Vec { @@ -177,10 +159,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1276.Number of Burgers with No Waste of Ingredients/README_EN.md b/solution/1200-1299/1276.Number of Burgers with No Waste of Ingredients/README_EN.md index 4b52f64fdfee3..2b5dfc3168025 100644 --- a/solution/1200-1299/1276.Number of Burgers with No Waste of Ingredients/README_EN.md +++ b/solution/1200-1299/1276.Number of Burgers with No Waste of Ingredients/README_EN.md @@ -48,7 +48,7 @@ There will be no remaining ingredients. ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics We set the number of Jumbo Burgers as $x$ and the number of Small Burgers as $y$, then we have: @@ -74,8 +74,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]: @@ -85,8 +83,6 @@ class Solution: return [] if k % 2 or y < 0 or x < 0 else [x, y] ``` -### **Java** - ```java class Solution { public List numOfBurgers(int tomatoSlices, int cheeseSlices) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +106,6 @@ public: }; ``` -### **Go** - ```go func numOfBurgers(tomatoSlices int, cheeseSlices int) []int { k := 4*cheeseSlices - tomatoSlices @@ -126,8 +118,6 @@ func numOfBurgers(tomatoSlices int, cheeseSlices int) []int { } ``` -### **TypeScript** - ```ts function numOfBurgers(tomatoSlices: number, cheeseSlices: number): number[] { const k = 4 * cheeseSlices - tomatoSlices; @@ -137,8 +127,6 @@ function numOfBurgers(tomatoSlices: number, cheeseSlices: number): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn num_of_burgers(tomato_slices: i32, cheese_slices: i32) -> Vec { @@ -154,10 +142,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1277.Count Square Submatrices with All Ones/README.md b/solution/1200-1299/1277.Count Square Submatrices with All Ones/README.md index 7fa5db9041834..997d58f619394 100644 --- a/solution/1200-1299/1277.Count Square Submatrices with All Ones/README.md +++ b/solution/1200-1299/1277.Count Square Submatrices with All Ones/README.md @@ -53,14 +53,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def countSquares(self, matrix: List[List[int]]) -> int: @@ -79,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countSquares(int[][] matrix) { @@ -108,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +122,6 @@ public: }; ``` -### **Go** - ```go func countSquares(matrix [][]int) int { m, n, ans := len(matrix), len(matrix[0]), 0 @@ -158,10 +146,6 @@ func countSquares(matrix [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1277.Count Square Submatrices with All Ones/README_EN.md b/solution/1200-1299/1277.Count Square Submatrices with All Ones/README_EN.md index 01eb6b8842c7e..7d848ba465cc1 100644 --- a/solution/1200-1299/1277.Count Square Submatrices with All Ones/README_EN.md +++ b/solution/1200-1299/1277.Count Square Submatrices with All Ones/README_EN.md @@ -51,9 +51,9 @@ Total number of squares = 6 + 1 = 7. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countSquares(int[][] matrix) { @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +120,6 @@ public: }; ``` -### **Go** - ```go func countSquares(matrix [][]int) int { m, n, ans := len(matrix), len(matrix[0]), 0 @@ -150,10 +144,6 @@ func countSquares(matrix [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1278.Palindrome Partitioning III/README.md b/solution/1200-1299/1278.Palindrome Partitioning III/README.md index be31bf81e1bbd..c88867e83e847 100644 --- a/solution/1200-1299/1278.Palindrome Partitioning III/README.md +++ b/solution/1200-1299/1278.Palindrome Partitioning III/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 定义 $dp[i][j]$ 表示将字符串 $s$ 的前 $i$ 个字符分割成 $j$ 个回文串所需要的最少修改次数,我们假定 $i$ 下标从 $1$ 开始,答案为 $dp[n][k]$。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def palindromePartition(self, s: str, k: int) -> int: @@ -88,10 +82,6 @@ class Solution: return f[n][k] ``` -### **Java** - - - ```java class Solution { public int palindromePartition(String s, int k) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func palindromePartition(s string, k int) int { n := len(s) @@ -194,10 +180,6 @@ func palindromePartition(s string, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1278.Palindrome Partitioning III/README_EN.md b/solution/1200-1299/1278.Palindrome Partitioning III/README_EN.md index 8ef544438fbf6..617a0f57f8add 100644 --- a/solution/1200-1299/1278.Palindrome Partitioning III/README_EN.md +++ b/solution/1200-1299/1278.Palindrome Partitioning III/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return f[n][k] ``` -### **Java** - ```java class Solution { public int palindromePartition(String s, int k) { @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +134,6 @@ public: }; ``` -### **Go** - ```go func palindromePartition(s string, k int) int { n := len(s) @@ -177,10 +171,6 @@ func palindromePartition(s string, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1279.Traffic Light Controlled Intersection/README.md b/solution/1200-1299/1279.Traffic Light Controlled Intersection/README.md index 9c1013fc41c6a..8e050111aa48d 100644 --- a/solution/1200-1299/1279.Traffic Light Controlled Intersection/README.md +++ b/solution/1200-1299/1279.Traffic Light Controlled Intersection/README.md @@ -83,12 +83,10 @@ ## 解法 - +### 方法一 -### **Python3** - ```python from threading import Lock @@ -117,8 +115,6 @@ class TrafficLight: self.lock.release() ``` -### **Java** - ```java class TrafficLight { private int road = 1; @@ -141,10 +137,6 @@ class TrafficLight { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1279.Traffic Light Controlled Intersection/README_EN.md b/solution/1200-1299/1279.Traffic Light Controlled Intersection/README_EN.md index 6d5f5a98f2304..ea8145e7aa680 100644 --- a/solution/1200-1299/1279.Traffic Light Controlled Intersection/README_EN.md +++ b/solution/1200-1299/1279.Traffic Light Controlled Intersection/README_EN.md @@ -79,9 +79,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python from threading import Lock @@ -111,8 +111,6 @@ class TrafficLight: self.lock.release() ``` -### **Java** - ```java class TrafficLight { private int road = 1; @@ -135,10 +133,6 @@ class TrafficLight { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1280.Students and Examinations/README.md b/solution/1200-1299/1280.Students and Examinations/README.md index 940ef2994ff7b..ec66e735df0ba 100644 --- a/solution/1200-1299/1280.Students and Examinations/README.md +++ b/solution/1200-1299/1280.Students and Examinations/README.md @@ -121,16 +121,12 @@ John 参加了数学、物理、编程测试各 1 次。 ## 解法 - - -**方法一:两次连接 + 分组统计** +### 方法一:两次连接 + 分组统计 我们可以先连接 `Students` 表和 `Subjects` 表,得到所有学生和所有科目的组合,然后再连接 `Examinations` 表,连接条件为 `student_id` 和 `subject_name`,这样就得到了每个学生参加每一门科目测试的次数,最后按 `student_id` 和 `subject_name` 分组统计即可。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT student_id, student_name, subject_name, COUNT(e.student_id) AS attended_exams @@ -143,3 +139,5 @@ ORDER BY 1, 3; ``` + + diff --git a/solution/1200-1299/1280.Students and Examinations/README_EN.md b/solution/1200-1299/1280.Students and Examinations/README_EN.md index b78bb6fbf0f75..c42b49f65b01b 100644 --- a/solution/1200-1299/1280.Students and Examinations/README_EN.md +++ b/solution/1200-1299/1280.Students and Examinations/README_EN.md @@ -120,14 +120,12 @@ John attended the Math exam 1 time, the Physics exam 1 time, and the Programming ## Solutions -**Solution 1: Two Joins + Grouping** +### Solution 1: Two Joins + Grouping We can first join the `Students` table and the `Subjects` table to obtain all combinations of students and subjects, and then join the `Examinations` table with the condition of `student_id` and `subject_name`. This way, we can get the number of times each student has taken each subject's test. Finally, we can group by `student_id` and `subject_name` to count the number of times each student has taken each subject's test. -### **SQL** - ```sql # Write your MySQL query statement below SELECT student_id, student_name, subject_name, COUNT(e.student_id) AS attended_exams @@ -140,3 +138,5 @@ ORDER BY 1, 3; ``` + + diff --git a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/README.md b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/README.md index f2079e463f550..2349e33de1307 100644 --- a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/README.md +++ b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们用两个变量 $x$ 和 $y$ 分别记录各位数之积、各位数之和,初始时 $x=1,y=0$。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def subtractProductAndSum(self, n: int) -> int: @@ -69,17 +63,6 @@ class Solution: return x - y ``` -```python -class Solution: - def subtractProductAndSum(self, n: int) -> int: - nums = list(map(int, str(n))) - return prod(nums) - sum(nums) -``` - -### **Java** - - - ```java class Solution { public int subtractProductAndSum(int n) { @@ -94,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +92,6 @@ public: }; ``` -### **Go** - ```go func subtractProductAndSum(n int) int { x, y := 1, 0 @@ -125,8 +104,6 @@ func subtractProductAndSum(n int) int { } ``` -### **TypeScript** - ```ts function subtractProductAndSum(n: number): number { let [x, y] = [1, 0]; @@ -139,8 +116,6 @@ function subtractProductAndSum(n: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn subtract_product_and_sum(mut n: i32) -> i32 { @@ -157,23 +132,6 @@ impl Solution { } ``` -### **C** - -```c -int subtractProductAndSum(int n) { - int x = 1; - int y = 0; - for (; n > 0; n /= 10) { - int v = n % 10; - x *= v; - y += v; - } - return x - y; -} -``` - -### **C#** - ```cs public class Solution { public int SubtractProductAndSum(int n) { @@ -189,10 +147,32 @@ public class Solution { } ``` -### **...** - +```c +int subtractProductAndSum(int n) { + int x = 1; + int y = 0; + for (; n > 0; n /= 10) { + int v = n % 10; + x *= v; + y += v; + } + return x - y; +} ``` + + +### 方法二 + + + +```python +class Solution: + def subtractProductAndSum(self, n: int) -> int: + nums = list(map(int, str(n))) + return prod(nums) - sum(nums) ``` + + diff --git a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/README_EN.md b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/README_EN.md index 9a019230baa0f..4a159169020af 100644 --- a/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/README_EN.md +++ b/solution/1200-1299/1281.Subtract the Product and Sum of Digits of an Integer/README_EN.md @@ -38,7 +38,7 @@ Result = 32 - 11 = 21 ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We use two variables $x$ and $y$ to record the product of the digits and the sum of the digits respectively. At the beginning, $x=1,y=0$. @@ -50,8 +50,6 @@ The time complexity is $O(\log n)$, where $n$ is the given integer. The space co -### **Python3** - ```python class Solution: def subtractProductAndSum(self, n: int) -> int: @@ -63,15 +61,6 @@ class Solution: return x - y ``` -```python -class Solution: - def subtractProductAndSum(self, n: int) -> int: - nums = list(map(int, str(n))) - return prod(nums) - sum(nums) -``` - -### **Java** - ```java class Solution { public int subtractProductAndSum(int n) { @@ -86,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +90,6 @@ public: }; ``` -### **Go** - ```go func subtractProductAndSum(n int) int { x, y := 1, 0 @@ -117,8 +102,6 @@ func subtractProductAndSum(n int) int { } ``` -### **TypeScript** - ```ts function subtractProductAndSum(n: number): number { let [x, y] = [1, 0]; @@ -131,8 +114,6 @@ function subtractProductAndSum(n: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn subtract_product_and_sum(mut n: i32) -> i32 { @@ -149,23 +130,6 @@ impl Solution { } ``` -### **C** - -```c -int subtractProductAndSum(int n) { - int x = 1; - int y = 0; - for (; n > 0; n /= 10) { - int v = n % 10; - x *= v; - y += v; - } - return x - y; -} -``` - -### **C#** - ```cs public class Solution { public int SubtractProductAndSum(int n) { @@ -181,10 +145,32 @@ public class Solution { } ``` -### **...** - +```c +int subtractProductAndSum(int n) { + int x = 1; + int y = 0; + for (; n > 0; n /= 10) { + int v = n % 10; + x *= v; + y += v; + } + return x - y; +} ``` + + +### Solution 2 + + + +```python +class Solution: + def subtractProductAndSum(self, n: int) -> int: + nums = list(map(int, str(n))) + return prod(nums) - sum(nums) ``` + + diff --git a/solution/1200-1299/1282.Group the People Given the Group Size They Belong To/README.md b/solution/1200-1299/1282.Group the People Given the Group Size They Belong To/README.md index a124518030a44..2c19d640c3009 100644 --- a/solution/1200-1299/1282.Group the People Given the Group Size They Belong To/README.md +++ b/solution/1200-1299/1282.Group the People Given the Group Size They Belong To/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:哈希表或数组** +### 方法一:哈希表或数组 我们用一个哈希表 $g$ 来存放每个 $groupSize$ 都有哪些人。然后对每个 $groupSize$ 中的人划分为 $k$ 等份,每一等份有 $groupSize$ 个人。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: @@ -72,27 +66,6 @@ class Solution: return [v[j : j + i] for i, v in g.items() for j in range(0, len(v), i)] ``` -```python -class Solution: - def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: - g = defaultdict(list) - for i, x in enumerate(groupSizes): - g[x].append(i) - ans = [] - for x, idx in g.items(): - t = [] - for i in idx: - t.append(i) - if len(t) == x: - ans.append(t) - t = [] - return ans -``` - -### **Java** - - - ```java class Solution { public List> groupThePeople(int[] groupSizes) { @@ -114,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +106,6 @@ public: }; ``` -### **Go** - ```go func groupThePeople(groupSizes []int) [][]int { n := len(groupSizes) @@ -154,8 +123,6 @@ func groupThePeople(groupSizes []int) [][]int { } ``` -### **TypeScript** - ```ts function groupThePeople(groupSizes: number[]): number[][] { const res = []; @@ -174,8 +141,6 @@ function groupThePeople(groupSizes: number[]): number[][] { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -196,6 +161,29 @@ impl Solution { } ``` + + +### 方法二 + + + +```python +class Solution: + def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: + g = defaultdict(list) + for i, x in enumerate(groupSizes): + g[x].append(i) + ans = [] + for x, idx in g.items(): + t = [] + for i in idx: + t.append(i) + if len(t) == x: + ans.append(t) + t = [] + return ans +``` + ```rust impl Solution { #[allow(dead_code)] @@ -217,10 +205,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1282.Group the People Given the Group Size They Belong To/README_EN.md b/solution/1200-1299/1282.Group the People Given the Group Size They Belong To/README_EN.md index 2046a8da08ff2..fd077dd5505c7 100644 --- a/solution/1200-1299/1282.Group the People Given the Group Size They Belong To/README_EN.md +++ b/solution/1200-1299/1282.Group the People Given the Group Size They Belong To/README_EN.md @@ -43,9 +43,9 @@ Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,25 +56,6 @@ class Solution: return [v[j : j + i] for i, v in g.items() for j in range(0, len(v), i)] ``` -```python -class Solution: - def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: - g = defaultdict(list) - for i, x in enumerate(groupSizes): - g[x].append(i) - ans = [] - for x, idx in g.items(): - t = [] - for i in idx: - t.append(i) - if len(t) == x: - ans.append(t) - t = [] - return ans -``` - -### **Java** - ```java class Solution { public List> groupThePeople(int[] groupSizes) { @@ -96,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +96,6 @@ public: }; ``` -### **Go** - ```go func groupThePeople(groupSizes []int) [][]int { n := len(groupSizes) @@ -136,8 +113,6 @@ func groupThePeople(groupSizes []int) [][]int { } ``` -### **TypeScript** - ```ts function groupThePeople(groupSizes: number[]): number[][] { const res = []; @@ -156,8 +131,6 @@ function groupThePeople(groupSizes: number[]): number[][] { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -178,6 +151,29 @@ impl Solution { } ``` + + +### Solution 2 + + + +```python +class Solution: + def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: + g = defaultdict(list) + for i, x in enumerate(groupSizes): + g[x].append(i) + ans = [] + for x, idx in g.items(): + t = [] + for i in idx: + t.append(i) + if len(t) == x: + ans.append(t) + t = [] + return ans +``` + ```rust impl Solution { #[allow(dead_code)] @@ -199,10 +195,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/README.md b/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/README.md index ac7706a47c2b6..8f047ac07b854 100644 --- a/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/README.md +++ b/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们注意到,对于一个数字 $v$,如果将 $nums$ 中的每个数字都除以 $v$ 的结果之和小于等于 $threshold$,那么所有大于 $v$ 的值都满足条件。这存在着单调性,因此我们可以使用二分查找的方法找到最小的满足条件的 $v$。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: @@ -82,20 +76,6 @@ class Solution: return l ``` -```python -class Solution: - def smallestDivisor(self, nums: List[int], threshold: int) -> int: - def f(v: int) -> bool: - v += 1 - return sum((x + v - 1) // v for x in nums) <= threshold - - return bisect_left(range(max(nums)), True, key=f) + 1 -``` - -### **Java** - - - ```java class Solution { public int smallestDivisor(int[] nums, int threshold) { @@ -117,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +120,6 @@ public: }; ``` -### **Go** - ```go func smallestDivisor(nums []int, threshold int) int { return sort.Search(1000000, func(v int) bool { @@ -157,15 +133,8 @@ func smallestDivisor(nums []int, threshold int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} threshold - * @return {number} - */ -var smallestDivisor = function (nums, threshold) { +```ts +function smallestDivisor(nums: number[], threshold: number): number { let l = 1; let r = Math.max(...nums); while (l < r) { @@ -181,13 +150,16 @@ var smallestDivisor = function (nums, threshold) { } } return l; -}; +} ``` -### **TypeScript** - -```ts -function smallestDivisor(nums: number[], threshold: number): number { +```js +/** + * @param {number[]} nums + * @param {number} threshold + * @return {number} + */ +var smallestDivisor = function (nums, threshold) { let l = 1; let r = Math.max(...nums); while (l < r) { @@ -203,11 +175,9 @@ function smallestDivisor(nums: number[], threshold: number): number { } } return l; -} +}; ``` -### **C#** - ```cs public class Solution { public int SmallestDivisor(int[] nums, int threshold) { @@ -230,10 +200,22 @@ public class Solution { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def smallestDivisor(self, nums: List[int], threshold: int) -> int: + def f(v: int) -> bool: + v += 1 + return sum((x + v - 1) // v for x in nums) <= threshold + + return bisect_left(range(max(nums)), True, key=f) + 1 ``` + + diff --git a/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/README_EN.md b/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/README_EN.md index 62af9ea542e9d..78f0f611c6e0c 100644 --- a/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/README_EN.md +++ b/solution/1200-1299/1283.Find the Smallest Divisor Given a Threshold/README_EN.md @@ -38,7 +38,7 @@ If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search Notice that for number $v$, if the sum of results of dividing each number in $nums$ by $v$ is less than or equal to $threshold$, then all values greater than $v$ satisfy the condition. There is a monotonicity, so we can use binary search to find the smallest $v$ that satisfies the condition. @@ -50,8 +50,6 @@ The time complexity is $O(n \times \log M)$, where $n$ is the length of the arra -### **Python3** - ```python class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: @@ -65,18 +63,6 @@ class Solution: return l ``` -```python -class Solution: - def smallestDivisor(self, nums: List[int], threshold: int) -> int: - def f(v: int) -> bool: - v += 1 - return sum((x + v - 1) // v for x in nums) <= threshold - - return bisect_left(range(max(nums)), True, key=f) + 1 -``` - -### **Java** - ```java class Solution { public int smallestDivisor(int[] nums, int threshold) { @@ -98,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +107,6 @@ public: }; ``` -### **Go** - ```go func smallestDivisor(nums []int, threshold int) int { return sort.Search(1000000, func(v int) bool { @@ -138,15 +120,8 @@ func smallestDivisor(nums []int, threshold int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} threshold - * @return {number} - */ -var smallestDivisor = function (nums, threshold) { +```ts +function smallestDivisor(nums: number[], threshold: number): number { let l = 1; let r = Math.max(...nums); while (l < r) { @@ -162,13 +137,16 @@ var smallestDivisor = function (nums, threshold) { } } return l; -}; +} ``` -### **TypeScript** - -```ts -function smallestDivisor(nums: number[], threshold: number): number { +```js +/** + * @param {number[]} nums + * @param {number} threshold + * @return {number} + */ +var smallestDivisor = function (nums, threshold) { let l = 1; let r = Math.max(...nums); while (l < r) { @@ -184,11 +162,9 @@ function smallestDivisor(nums: number[], threshold: number): number { } } return l; -} +}; ``` -### **C#** - ```cs public class Solution { public int SmallestDivisor(int[] nums, int threshold) { @@ -211,10 +187,22 @@ public class Solution { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def smallestDivisor(self, nums: List[int], threshold: int) -> int: + def f(v: int) -> bool: + v += 1 + return sum((x + v - 1) // v for x in nums) <= threshold + + return bisect_left(range(max(nums)), True, key=f) + 1 ``` + + diff --git a/solution/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/README.md b/solution/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/README.md index 5ccd5ff46f74c..42cf7d91c4e3c 100644 --- a/solution/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/README.md +++ b/solution/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/README.md @@ -56,16 +56,10 @@ ## 解法 - - -**方法一:状态压缩 + BFS** +### 方法一:状态压缩 + BFS -### **Python3** - - - ```python class Solution: def minFlips(self, mat: List[List[int]]) -> int: @@ -98,10 +92,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int minFlips(int[][] mat) { @@ -154,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -200,8 +188,6 @@ public: }; ``` -### **Go** - ```go func minFlips(mat [][]int) int { m, n := len(mat), len(mat[0]) @@ -251,10 +237,6 @@ func minFlips(mat [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/README_EN.md b/solution/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/README_EN.md index 51d1dff285fad..3c676ed09e4ee 100644 --- a/solution/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/README_EN.md +++ b/solution/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -85,8 +85,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int minFlips(int[][] mat) { @@ -139,8 +137,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -185,8 +181,6 @@ public: }; ``` -### **Go** - ```go func minFlips(mat [][]int) int { m, n := len(mat), len(mat[0]) @@ -236,10 +230,6 @@ func minFlips(mat [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/README.md b/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/README.md index c987160468c72..8f1f1ffcc3539 100644 --- a/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/README.md +++ b/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/README.md @@ -61,9 +61,7 @@ Logs 表: ## 解法 - - -**方法一:分组 + 窗口函数** +### 方法一:分组 + 窗口函数 我们需要想办法将一段连续的日志分到同一组,然后对每一组进行聚合操作,得到每一组的开始日志和结束日志。 @@ -74,8 +72,6 @@ Logs 表: -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -96,6 +92,12 @@ FROM T GROUP BY pid; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below WITH @@ -111,3 +113,5 @@ GROUP BY pid; ``` + + diff --git a/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/README_EN.md b/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/README_EN.md index a607a0207bf8f..1874781c18e59 100644 --- a/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/README_EN.md +++ b/solution/1200-1299/1285.Find the Start and End Number of Continuous Ranges/README_EN.md @@ -59,7 +59,7 @@ Number 10 is contained in the table. ## Solutions -**Solution 1: Group By + Window Function** +### Solution 1: Group By + Window Function We need to find a way to group a continuous sequence of logs into the same group, and then aggregate each group to obtain the start and end logs of each group. @@ -70,8 +70,6 @@ There are two ways to implement grouping: -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -92,6 +90,12 @@ FROM T GROUP BY pid; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below WITH @@ -107,3 +111,5 @@ GROUP BY pid; ``` + + diff --git a/solution/1200-1299/1286.Iterator for Combination/README.md b/solution/1200-1299/1286.Iterator for Combination/README.md index 7e04f64a68fa1..fd7f6ba87c9ba 100644 --- a/solution/1200-1299/1286.Iterator for Combination/README.md +++ b/solution/1200-1299/1286.Iterator for Combination/README.md @@ -47,38 +47,12 @@ iterator.hasNext(); // 返回 false ## 解法 - - -**方法一:DFS 回溯** +### 方法一:DFS 回溯 我们通过 $DFS$ 枚举,预处理生成所有长度为 $combinationLength$ 的字符串,存放到 $cs$ 数组中。 -**方法二:二进制编码** - -我们看个例子,对于 $abcd$,若 $combinationLength$ 为 2,则 $cs$ 就是 $ab, ac, ad, bc, bd, cd, ...$。 - -对应的二进制数为: - -``` -1100 -1010 -1001 -0110 -0101 -0011 -... -``` - -观察到上述规律后,我们依次按照二进制编码从大到小的规律,将所有字符串依次求出。 - -所谓的长度 $combinationLength$,只需要满足二进制编码中 $1$ 的个数满足要求即可。 - -### **Python3** - - - ```python class CombinationIterator: def __init__(self, characters: str, combinationLength: int): @@ -115,39 +89,6 @@ class CombinationIterator: # param_2 = obj.hasNext() ``` -```python -class CombinationIterator: - def __init__(self, characters: str, combinationLength: int): - self.curr = (1 << len(characters)) - 1 - self.size = combinationLength - self.cs = characters[::-1] - - def next(self) -> str: - while self.curr >= 0 and self.curr.bit_count() != self.size: - self.curr -= 1 - ans = [] - for i in range(len(self.cs)): - if (self.curr >> i) & 1: - ans.append(self.cs[i]) - self.curr -= 1 - return ''.join(ans[::-1]) - - def hasNext(self) -> bool: - while self.curr >= 0 and self.curr.bit_count() != self.size: - self.curr -= 1 - return self.curr >= 0 - - -# Your CombinationIterator object will be instantiated and called as such: -# obj = CombinationIterator(characters, combinationLength) -# param_1 = obj.next() -# param_2 = obj.hasNext() -``` - -### **Java** - - - ```java class CombinationIterator { private int n; @@ -195,54 +136,6 @@ class CombinationIterator { */ ``` -```java -class CombinationIterator { - private int curr; - private int size; - private char[] cs; - - public CombinationIterator(String characters, int combinationLength) { - int n = characters.length(); - curr = (1 << n) - 1; - size = combinationLength; - cs = new char[n]; - for (int i = 0; i < n; ++i) { - cs[i] = characters.charAt(n - i - 1); - } - } - - public String next() { - while (curr >= 0 && Integer.bitCount(curr) != size) { - --curr; - } - StringBuilder ans = new StringBuilder(); - for (int i = 0; i < cs.length; ++i) { - if (((curr >> i) & 1) == 1) { - ans.append(cs[i]); - } - } - --curr; - return ans.reverse().toString(); - } - - public boolean hasNext() { - while (curr >= 0 && Integer.bitCount(curr) != size) { - --curr; - } - return curr >= 0; - } -} - -/** - * Your CombinationIterator object will be instantiated and called as such: - * CombinationIterator obj = new CombinationIterator(characters, combinationLength); - * String param_1 = obj.next(); - * boolean param_2 = obj.hasNext(); - */ -``` - -### **C++** - ```cpp class CombinationIterator { public: @@ -290,50 +183,6 @@ public: */ ``` -```cpp -class CombinationIterator { -public: - int size; - string cs; - int curr; - - CombinationIterator(string characters, int combinationLength) { - int n = characters.size(); - curr = (1 << n) - 1; - reverse(characters.begin(), characters.end()); - cs = characters; - size = combinationLength; - } - - string next() { - while (curr >= 0 && __builtin_popcount(curr) != size) --curr; - string ans; - for (int i = 0; i < cs.size(); ++i) { - if ((curr >> i) & 1) { - ans += cs[i]; - } - } - reverse(ans.begin(), ans.end()); - --curr; - return ans; - } - - bool hasNext() { - while (curr >= 0 && __builtin_popcount(curr) != size) --curr; - return curr >= 0; - } -}; - -/** - * Your CombinationIterator object will be instantiated and called as such: - * CombinationIterator* obj = new CombinationIterator(characters, combinationLength); - * string param_1 = obj->next(); - * bool param_2 = obj->hasNext(); - */ -``` - -### **Go** - ```go type CombinationIterator struct { cs []string @@ -380,6 +229,147 @@ func (this *CombinationIterator) HasNext() bool { */ ``` + + +### 方法二:二进制编码 + +我们看个例子,对于 $abcd$,若 $combinationLength$ 为 2,则 $cs$ 就是 $ab, ac, ad, bc, bd, cd, ...$。 + +对应的二进制数为: + +``` +1100 +1010 +1001 +0110 +0101 +0011 +... +``` + +观察到上述规律后,我们依次按照二进制编码从大到小的规律,将所有字符串依次求出。 + +所谓的长度 $combinationLength$,只需要满足二进制编码中 $1$ 的个数满足要求即可。 + + + +```python +class CombinationIterator: + def __init__(self, characters: str, combinationLength: int): + self.curr = (1 << len(characters)) - 1 + self.size = combinationLength + self.cs = characters[::-1] + + def next(self) -> str: + while self.curr >= 0 and self.curr.bit_count() != self.size: + self.curr -= 1 + ans = [] + for i in range(len(self.cs)): + if (self.curr >> i) & 1: + ans.append(self.cs[i]) + self.curr -= 1 + return ''.join(ans[::-1]) + + def hasNext(self) -> bool: + while self.curr >= 0 and self.curr.bit_count() != self.size: + self.curr -= 1 + return self.curr >= 0 + + +# Your CombinationIterator object will be instantiated and called as such: +# obj = CombinationIterator(characters, combinationLength) +# param_1 = obj.next() +# param_2 = obj.hasNext() +``` + +```java +class CombinationIterator { + private int curr; + private int size; + private char[] cs; + + public CombinationIterator(String characters, int combinationLength) { + int n = characters.length(); + curr = (1 << n) - 1; + size = combinationLength; + cs = new char[n]; + for (int i = 0; i < n; ++i) { + cs[i] = characters.charAt(n - i - 1); + } + } + + public String next() { + while (curr >= 0 && Integer.bitCount(curr) != size) { + --curr; + } + StringBuilder ans = new StringBuilder(); + for (int i = 0; i < cs.length; ++i) { + if (((curr >> i) & 1) == 1) { + ans.append(cs[i]); + } + } + --curr; + return ans.reverse().toString(); + } + + public boolean hasNext() { + while (curr >= 0 && Integer.bitCount(curr) != size) { + --curr; + } + return curr >= 0; + } +} + +/** + * Your CombinationIterator object will be instantiated and called as such: + * CombinationIterator obj = new CombinationIterator(characters, combinationLength); + * String param_1 = obj.next(); + * boolean param_2 = obj.hasNext(); + */ +``` + +```cpp +class CombinationIterator { +public: + int size; + string cs; + int curr; + + CombinationIterator(string characters, int combinationLength) { + int n = characters.size(); + curr = (1 << n) - 1; + reverse(characters.begin(), characters.end()); + cs = characters; + size = combinationLength; + } + + string next() { + while (curr >= 0 && __builtin_popcount(curr) != size) --curr; + string ans; + for (int i = 0; i < cs.size(); ++i) { + if ((curr >> i) & 1) { + ans += cs[i]; + } + } + reverse(ans.begin(), ans.end()); + --curr; + return ans; + } + + bool hasNext() { + while (curr >= 0 && __builtin_popcount(curr) != size) --curr; + return curr >= 0; + } +}; + +/** + * Your CombinationIterator object will be instantiated and called as such: + * CombinationIterator* obj = new CombinationIterator(characters, combinationLength); + * string param_1 = obj->next(); + * bool param_2 = obj->hasNext(); + */ +``` + ```go type CombinationIterator struct { curr int @@ -430,10 +420,6 @@ func (this *CombinationIterator) HasNext() bool { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1286.Iterator for Combination/README_EN.md b/solution/1200-1299/1286.Iterator for Combination/README_EN.md index aee9c15bfc05e..ff847c5c68af2 100644 --- a/solution/1200-1299/1286.Iterator for Combination/README_EN.md +++ b/solution/1200-1299/1286.Iterator for Combination/README_EN.md @@ -44,9 +44,9 @@ itr.hasNext(); // return False ## Solutions - +### Solution 1 -### **Python3** + ```python class CombinationIterator: @@ -84,37 +84,6 @@ class CombinationIterator: # param_2 = obj.hasNext() ``` -```python -class CombinationIterator: - def __init__(self, characters: str, combinationLength: int): - self.curr = (1 << len(characters)) - 1 - self.size = combinationLength - self.cs = characters[::-1] - - def next(self) -> str: - while self.curr >= 0 and self.curr.bit_count() != self.size: - self.curr -= 1 - ans = [] - for i in range(len(self.cs)): - if (self.curr >> i) & 1: - ans.append(self.cs[i]) - self.curr -= 1 - return ''.join(ans[::-1]) - - def hasNext(self) -> bool: - while self.curr >= 0 and self.curr.bit_count() != self.size: - self.curr -= 1 - return self.curr >= 0 - - -# Your CombinationIterator object will be instantiated and called as such: -# obj = CombinationIterator(characters, combinationLength) -# param_1 = obj.next() -# param_2 = obj.hasNext() -``` - -### **Java** - ```java class CombinationIterator { private int n; @@ -162,54 +131,6 @@ class CombinationIterator { */ ``` -```java -class CombinationIterator { - private int curr; - private int size; - private char[] cs; - - public CombinationIterator(String characters, int combinationLength) { - int n = characters.length(); - curr = (1 << n) - 1; - size = combinationLength; - cs = new char[n]; - for (int i = 0; i < n; ++i) { - cs[i] = characters.charAt(n - i - 1); - } - } - - public String next() { - while (curr >= 0 && Integer.bitCount(curr) != size) { - --curr; - } - StringBuilder ans = new StringBuilder(); - for (int i = 0; i < cs.length; ++i) { - if (((curr >> i) & 1) == 1) { - ans.append(cs[i]); - } - } - --curr; - return ans.reverse().toString(); - } - - public boolean hasNext() { - while (curr >= 0 && Integer.bitCount(curr) != size) { - --curr; - } - return curr >= 0; - } -} - -/** - * Your CombinationIterator object will be instantiated and called as such: - * CombinationIterator obj = new CombinationIterator(characters, combinationLength); - * String param_1 = obj.next(); - * boolean param_2 = obj.hasNext(); - */ -``` - -### **C++** - ```cpp class CombinationIterator { public: @@ -257,50 +178,6 @@ public: */ ``` -```cpp -class CombinationIterator { -public: - int size; - string cs; - int curr; - - CombinationIterator(string characters, int combinationLength) { - int n = characters.size(); - curr = (1 << n) - 1; - reverse(characters.begin(), characters.end()); - cs = characters; - size = combinationLength; - } - - string next() { - while (curr >= 0 && __builtin_popcount(curr) != size) --curr; - string ans; - for (int i = 0; i < cs.size(); ++i) { - if ((curr >> i) & 1) { - ans += cs[i]; - } - } - reverse(ans.begin(), ans.end()); - --curr; - return ans; - } - - bool hasNext() { - while (curr >= 0 && __builtin_popcount(curr) != size) --curr; - return curr >= 0; - } -}; - -/** - * Your CombinationIterator object will be instantiated and called as such: - * CombinationIterator* obj = new CombinationIterator(characters, combinationLength); - * string param_1 = obj->next(); - * bool param_2 = obj->hasNext(); - */ -``` - -### **Go** - ```go type CombinationIterator struct { cs []string @@ -347,6 +224,129 @@ func (this *CombinationIterator) HasNext() bool { */ ``` + + +### Solution 2 + + + +```python +class CombinationIterator: + def __init__(self, characters: str, combinationLength: int): + self.curr = (1 << len(characters)) - 1 + self.size = combinationLength + self.cs = characters[::-1] + + def next(self) -> str: + while self.curr >= 0 and self.curr.bit_count() != self.size: + self.curr -= 1 + ans = [] + for i in range(len(self.cs)): + if (self.curr >> i) & 1: + ans.append(self.cs[i]) + self.curr -= 1 + return ''.join(ans[::-1]) + + def hasNext(self) -> bool: + while self.curr >= 0 and self.curr.bit_count() != self.size: + self.curr -= 1 + return self.curr >= 0 + + +# Your CombinationIterator object will be instantiated and called as such: +# obj = CombinationIterator(characters, combinationLength) +# param_1 = obj.next() +# param_2 = obj.hasNext() +``` + +```java +class CombinationIterator { + private int curr; + private int size; + private char[] cs; + + public CombinationIterator(String characters, int combinationLength) { + int n = characters.length(); + curr = (1 << n) - 1; + size = combinationLength; + cs = new char[n]; + for (int i = 0; i < n; ++i) { + cs[i] = characters.charAt(n - i - 1); + } + } + + public String next() { + while (curr >= 0 && Integer.bitCount(curr) != size) { + --curr; + } + StringBuilder ans = new StringBuilder(); + for (int i = 0; i < cs.length; ++i) { + if (((curr >> i) & 1) == 1) { + ans.append(cs[i]); + } + } + --curr; + return ans.reverse().toString(); + } + + public boolean hasNext() { + while (curr >= 0 && Integer.bitCount(curr) != size) { + --curr; + } + return curr >= 0; + } +} + +/** + * Your CombinationIterator object will be instantiated and called as such: + * CombinationIterator obj = new CombinationIterator(characters, combinationLength); + * String param_1 = obj.next(); + * boolean param_2 = obj.hasNext(); + */ +``` + +```cpp +class CombinationIterator { +public: + int size; + string cs; + int curr; + + CombinationIterator(string characters, int combinationLength) { + int n = characters.size(); + curr = (1 << n) - 1; + reverse(characters.begin(), characters.end()); + cs = characters; + size = combinationLength; + } + + string next() { + while (curr >= 0 && __builtin_popcount(curr) != size) --curr; + string ans; + for (int i = 0; i < cs.size(); ++i) { + if ((curr >> i) & 1) { + ans += cs[i]; + } + } + reverse(ans.begin(), ans.end()); + --curr; + return ans; + } + + bool hasNext() { + while (curr >= 0 && __builtin_popcount(curr) != size) --curr; + return curr >= 0; + } +}; + +/** + * Your CombinationIterator object will be instantiated and called as such: + * CombinationIterator* obj = new CombinationIterator(characters, combinationLength); + * string param_1 = obj->next(); + * bool param_2 = obj->hasNext(); + */ +``` + ```go type CombinationIterator struct { curr int @@ -397,10 +397,6 @@ func (this *CombinationIterator) HasNext() bool { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/README.md b/solution/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/README.md index b9b3dea6afc36..baac81e12d9e5 100644 --- a/solution/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/README.md +++ b/solution/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/README.md @@ -30,14 +30,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findSpecialInteger(self, arr: List[int]) -> int: @@ -48,10 +44,6 @@ class Solution: return 0 ``` -### **Java** - - - ```java class Solution { public int findSpecialInteger(int[] arr) { @@ -66,8 +58,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -80,8 +70,6 @@ public: }; ``` -### **Go** - ```go func findSpecialInteger(arr []int) int { n := len(arr) @@ -94,8 +82,6 @@ func findSpecialInteger(arr []int) int { } ``` -### **JavaScript** - ```js /** * @param {number[]} arr @@ -112,8 +98,6 @@ var findSpecialInteger = function (arr) { }; ``` -### **PHP** - ```php class Solution { /** @@ -132,10 +116,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/README_EN.md b/solution/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/README_EN.md index 7fcd566bf1691..5ac35a5050874 100644 --- a/solution/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/README_EN.md +++ b/solution/1200-1299/1287.Element Appearing More Than 25% In Sorted Array/README_EN.md @@ -31,9 +31,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -45,8 +45,6 @@ class Solution: return 0 ``` -### **Java** - ```java class Solution { public int findSpecialInteger(int[] arr) { @@ -61,8 +59,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -75,8 +71,6 @@ public: }; ``` -### **Go** - ```go func findSpecialInteger(arr []int) int { n := len(arr) @@ -89,8 +83,6 @@ func findSpecialInteger(arr []int) int { } ``` -### **JavaScript** - ```js /** * @param {number[]} arr @@ -107,8 +99,6 @@ var findSpecialInteger = function (arr) { }; ``` -### **PHP** - ```php class Solution { /** @@ -127,10 +117,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1288.Remove Covered Intervals/README.md b/solution/1200-1299/1288.Remove Covered Intervals/README.md index 134c4cf381e6f..4b058d069e2c0 100644 --- a/solution/1200-1299/1288.Remove Covered Intervals/README.md +++ b/solution/1200-1299/1288.Remove Covered Intervals/README.md @@ -34,22 +34,10 @@ ## 解法 - - -对起点按升序排列,若起点相同,则对终点按降序排列。 - -设 cnt 表示没有被覆盖的区间数,初始化为 1,pre 表示前一个未被覆盖的区间,初始化为 `intervals[0]`。 - -从下标 1 开始遍历区间列表,若 `pre[1] < intervals[i][1]`,说明当前区间不被前一个区间覆盖,`cnt++`,并且更新 pre 为 `intervals[i]`。否则表示当前区间被前一个区间覆盖,不做任何操作。 - -最后返回 cnt 即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: @@ -62,10 +50,6 @@ class Solution: return cnt ``` -### **Java** - - - ```java class Solution { public int removeCoveredIntervals(int[][] intervals) { @@ -83,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +85,6 @@ public: }; ``` -### **Go** - ```go func removeCoveredIntervals(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { @@ -125,10 +105,6 @@ func removeCoveredIntervals(intervals [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1288.Remove Covered Intervals/README_EN.md b/solution/1200-1299/1288.Remove Covered Intervals/README_EN.md index 5ec8c6cf3ddc4..0bf82ce41355d 100644 --- a/solution/1200-1299/1288.Remove Covered Intervals/README_EN.md +++ b/solution/1200-1299/1288.Remove Covered Intervals/README_EN.md @@ -38,18 +38,10 @@ ## Solutions -- Sort `intervals` by increasing of `startTime` and decreasing of `endTime`. -- `cnt = 1`: `cnt` is the result. -- `pre = intervals[0]`: `pre` is the last interval -- For each `interval` in `intervals` - - if `pre.endTime < interval.endTime`, means `interval` is not overlapped then we count `cnt`, and update `pre = interval` - - else we do nothing -- Return `cnt` +### Solution 1 -### **Python3** - ```python class Solution: def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: @@ -62,8 +54,6 @@ class Solution: return cnt ``` -### **Java** - ```java class Solution { public int removeCoveredIntervals(int[][] intervals) { @@ -81,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +89,6 @@ public: }; ``` -### **Go** - ```go func removeCoveredIntervals(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { @@ -123,10 +109,6 @@ func removeCoveredIntervals(intervals [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1289.Minimum Falling Path Sum II/README.md b/solution/1200-1299/1289.Minimum Falling Path Sum II/README.md index 0811b4870af04..3fbff6397e358 100644 --- a/solution/1200-1299/1289.Minimum Falling Path Sum II/README.md +++ b/solution/1200-1299/1289.Minimum Falling Path Sum II/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示前 $i$ 行,且最后一个数字在第 $j$ 列的最小数字和。那么状态转移方程为: @@ -66,10 +64,6 @@ $$ -### **Python3** - - - ```python class Solution: def minFallingPathSum(self, grid: List[List[int]]) -> int: @@ -82,30 +76,6 @@ class Solution: return min(f[n]) ``` -```python -class Solution: - def minFallingPathSum(self, grid: List[List[int]]) -> int: - f = g = 0 - fp = -1 - for row in grid: - ff = gg = inf - ffp = -1 - for j, v in enumerate(row): - s = (g if j == fp else f) + v - if s < ff: - gg = ff - ff = s - ffp = j - elif s < gg: - gg = s - f, g, fp = ff, gg, ffp - return f -``` - -### **Java** - - - ```java class Solution { public int minFallingPathSum(int[][] grid) { @@ -132,6 +102,83 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minFallingPathSum(vector>& grid) { + int n = grid.size(); + int f[n + 1][n]; + memset(f, 0, sizeof(f)); + const int inf = 1 << 30; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < n; ++j) { + int x = inf; + for (int k = 0; k < n; ++k) { + if (k != j) { + x = min(x, f[i - 1][k]); + } + } + f[i][j] = grid[i - 1][j] + (x == inf ? 0 : x); + } + } + return *min_element(f[n], f[n] + n); + } +}; +``` + +```go +func minFallingPathSum(grid [][]int) int { + n := len(grid) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, n) + } + const inf = 1 << 30 + for i, row := range grid { + i++ + for j, v := range row { + x := inf + for k := range row { + if k != j { + x = min(x, f[i-1][k]) + } + } + if x == inf { + x = 0 + } + f[i][j] = v + x + } + } + return slices.Min(f[n]) +} +``` + + + +### 方法二 + + + +```python +class Solution: + def minFallingPathSum(self, grid: List[List[int]]) -> int: + f = g = 0 + fp = -1 + for row in grid: + ff = gg = inf + ffp = -1 + for j, v in enumerate(row): + s = (g if j == fp else f) + v + if s < ff: + gg = ff + ff = s + ffp = j + elif s < gg: + gg = s + f, g, fp = ff, gg, ffp + return f +``` + ```java class Solution { public int minFallingPathSum(int[][] grid) { @@ -160,32 +207,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minFallingPathSum(vector>& grid) { - int n = grid.size(); - int f[n + 1][n]; - memset(f, 0, sizeof(f)); - const int inf = 1 << 30; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j < n; ++j) { - int x = inf; - for (int k = 0; k < n; ++k) { - if (k != j) { - x = min(x, f[i - 1][k]); - } - } - f[i][j] = grid[i - 1][j] + (x == inf ? 0 : x); - } - } - return *min_element(f[n], f[n] + n); - } -}; -``` - ```cpp class Solution { public: @@ -215,35 +236,6 @@ public: }; ``` -### **Go** - -```go -func minFallingPathSum(grid [][]int) int { - n := len(grid) - f := make([][]int, n+1) - for i := range f { - f[i] = make([]int, n) - } - const inf = 1 << 30 - for i, row := range grid { - i++ - for j, v := range row { - x := inf - for k := range row { - if k != j { - x = min(x, f[i-1][k]) - } - } - if x == inf { - x = 0 - } - f[i][j] = v + x - } - } - return slices.Min(f[n]) -} -``` - ```go func minFallingPathSum(grid [][]int) int { const inf = 1 << 30 @@ -270,10 +262,6 @@ func minFallingPathSum(grid [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1289.Minimum Falling Path Sum II/README_EN.md b/solution/1200-1299/1289.Minimum Falling Path Sum II/README_EN.md index 16733b34a055a..b03d903a97932 100644 --- a/solution/1200-1299/1289.Minimum Falling Path Sum II/README_EN.md +++ b/solution/1200-1299/1289.Minimum Falling Path Sum II/README_EN.md @@ -40,9 +40,9 @@ The falling path with the smallest sum is [1,5,7], so the answer is 13 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,28 +56,6 @@ class Solution: return min(f[n]) ``` -```python -class Solution: - def minFallingPathSum(self, grid: List[List[int]]) -> int: - f = g = 0 - fp = -1 - for row in grid: - ff = gg = inf - ffp = -1 - for j, v in enumerate(row): - s = (g if j == fp else f) + v - if s < ff: - gg = ff - ff = s - ffp = j - elif s < gg: - gg = s - f, g, fp = ff, gg, ffp - return f -``` - -### **Java** - ```java class Solution { public int minFallingPathSum(int[][] grid) { @@ -104,6 +82,83 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minFallingPathSum(vector>& grid) { + int n = grid.size(); + int f[n + 1][n]; + memset(f, 0, sizeof(f)); + const int inf = 1 << 30; + for (int i = 1; i <= n; ++i) { + for (int j = 0; j < n; ++j) { + int x = inf; + for (int k = 0; k < n; ++k) { + if (k != j) { + x = min(x, f[i - 1][k]); + } + } + f[i][j] = grid[i - 1][j] + (x == inf ? 0 : x); + } + } + return *min_element(f[n], f[n] + n); + } +}; +``` + +```go +func minFallingPathSum(grid [][]int) int { + n := len(grid) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, n) + } + const inf = 1 << 30 + for i, row := range grid { + i++ + for j, v := range row { + x := inf + for k := range row { + if k != j { + x = min(x, f[i-1][k]) + } + } + if x == inf { + x = 0 + } + f[i][j] = v + x + } + } + return slices.Min(f[n]) +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minFallingPathSum(self, grid: List[List[int]]) -> int: + f = g = 0 + fp = -1 + for row in grid: + ff = gg = inf + ffp = -1 + for j, v in enumerate(row): + s = (g if j == fp else f) + v + if s < ff: + gg = ff + ff = s + ffp = j + elif s < gg: + gg = s + f, g, fp = ff, gg, ffp + return f +``` + ```java class Solution { public int minFallingPathSum(int[][] grid) { @@ -132,32 +187,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minFallingPathSum(vector>& grid) { - int n = grid.size(); - int f[n + 1][n]; - memset(f, 0, sizeof(f)); - const int inf = 1 << 30; - for (int i = 1; i <= n; ++i) { - for (int j = 0; j < n; ++j) { - int x = inf; - for (int k = 0; k < n; ++k) { - if (k != j) { - x = min(x, f[i - 1][k]); - } - } - f[i][j] = grid[i - 1][j] + (x == inf ? 0 : x); - } - } - return *min_element(f[n], f[n] + n); - } -}; -``` - ```cpp class Solution { public: @@ -187,35 +216,6 @@ public: }; ``` -### **Go** - -```go -func minFallingPathSum(grid [][]int) int { - n := len(grid) - f := make([][]int, n+1) - for i := range f { - f[i] = make([]int, n) - } - const inf = 1 << 30 - for i, row := range grid { - i++ - for j, v := range row { - x := inf - for k := range row { - if k != j { - x = min(x, f[i-1][k]) - } - } - if x == inf { - x = 0 - } - f[i][j] = v + x - } - } - return slices.Min(f[n]) -} -``` - ```go func minFallingPathSum(grid [][]int) int { const inf = 1 << 30 @@ -242,10 +242,6 @@ func minFallingPathSum(grid [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README.md b/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README.md index fcc4fffabf905..5d6484205eea5 100644 --- a/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README.md +++ b/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:遍历链表** +### 方法一:遍历链表 我们用变量 `ans` 记录当前的十进制值,初始值为 $0$。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -139,8 +127,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -157,31 +143,6 @@ func getDecimalValue(head *ListNode) (ans int) { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @return {number} - */ -var getDecimalValue = function (head) { - let ans = 0; - for (; head; head = head.next) { - ans = (ans << 1) | head.val; - } - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -204,8 +165,6 @@ function getDecimalValue(head: ListNode | null): number { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -236,31 +195,28 @@ impl Solution { } ``` -### **C** - -```c +```js /** * Definition for singly-linked list. - * struct ListNode { - * int val; - * struct ListNode *next; - * }; + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } */ - -int getDecimalValue(struct ListNode* head) { - int ans = 0; - struct ListNode* cur = head; - while (cur) { - ans = (ans << 1) | cur->val; - cur = cur->next; +/** + * @param {ListNode} head + * @return {number} + */ +var getDecimalValue = function (head) { + let ans = 0; + for (; head; head = head.next) { + ans = (ans << 1) | head.val; } return ans; -} +}; ``` -### **PHP** - -```PHP +```php /** * Definition for a singly-linked list. * class ListNode { @@ -273,13 +229,12 @@ int getDecimalValue(struct ListNode* head) { * } */ class Solution { - /** * @param ListNode $head * @return Integer */ function getDecimalValue($head) { - $rs = array(); + $rs = []; while ($head != null) { array_push($rs, $head->val); $head = $head->next; @@ -290,10 +245,26 @@ class Solution { } ``` -### **...** - -``` +```c +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ +int getDecimalValue(struct ListNode* head) { + int ans = 0; + struct ListNode* cur = head; + while (cur) { + ans = (ans << 1) | cur->val; + cur = cur->next; + } + return ans; +} ``` + + diff --git a/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README_EN.md b/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README_EN.md index db0e3ccc1c9f7..b8513abaf3c3d 100644 --- a/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README_EN.md +++ b/solution/1200-1299/1290.Convert Binary Number in a Linked List to Integer/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -56,8 +56,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -80,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -105,8 +101,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -123,31 +117,6 @@ func getDecimalValue(head *ListNode) (ans int) { } ``` -### **JavaScript** - -```js -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @return {number} - */ -var getDecimalValue = function (head) { - let ans = 0; - for (; head; head = head.next) { - ans = (ans << 1) | head.val; - } - return ans; -}; -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -170,8 +139,6 @@ function getDecimalValue(head: ListNode | null): number { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -202,31 +169,28 @@ impl Solution { } ``` -### **C** - -```c +```js /** * Definition for singly-linked list. - * struct ListNode { - * int val; - * struct ListNode *next; - * }; + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } */ - -int getDecimalValue(struct ListNode* head) { - int ans = 0; - struct ListNode* cur = head; - while (cur) { - ans = (ans << 1) | cur->val; - cur = cur->next; +/** + * @param {ListNode} head + * @return {number} + */ +var getDecimalValue = function (head) { + let ans = 0; + for (; head; head = head.next) { + ans = (ans << 1) | head.val; } return ans; -} +}; ``` -### **PHP** - -```PHP +```php /** * Definition for a singly-linked list. * class ListNode { @@ -239,13 +203,12 @@ int getDecimalValue(struct ListNode* head) { * } */ class Solution { - /** * @param ListNode $head * @return Integer */ function getDecimalValue($head) { - $rs = array(); + $rs = []; while ($head != null) { array_push($rs, $head->val); $head = $head->next; @@ -256,10 +219,26 @@ class Solution { } ``` -### **...** - -``` +```c +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ +int getDecimalValue(struct ListNode* head) { + int ans = 0; + struct ListNode* cur = head; + while (cur) { + ans = (ans << 1) | cur->val; + cur = cur->next; + } + return ans; +} ``` + + diff --git a/solution/1200-1299/1291.Sequential Digits/README.md b/solution/1200-1299/1291.Sequential Digits/README.md index d0cdf4a543935..e216290c8add3 100644 --- a/solution/1200-1299/1291.Sequential Digits/README.md +++ b/solution/1200-1299/1291.Sequential Digits/README.md @@ -34,9 +34,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举数字的第一位 $i$,然后枚举数字的最后一位 $j$,那么这个数字就是 $i,i+1,\cdots,j$ 这 $j-i+1$ 个数字组成的。我们可以通过不断地将数字乘以 $10$ 并加上下一个数字 $j+1$ 来得到下一个数字,如果数字在 $[low, high]$ 的范围内,我们就将它加入答案中。 @@ -46,10 +44,6 @@ -### **Python3** - - - ```python class Solution: def sequentialDigits(self, low: int, high: int) -> List[int]: @@ -63,10 +57,6 @@ class Solution: return sorted(ans) ``` -### **Java** - - - ```java class Solution { public List sequentialDigits(int low, int high) { @@ -86,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +96,6 @@ public: }; ``` -### **Go** - ```go func sequentialDigits(low int, high int) (ans []int) { for i := 1; i < 9; i++ { @@ -126,8 +112,6 @@ func sequentialDigits(low int, high int) (ans []int) { } ``` -### **TypeScript** - ```ts function sequentialDigits(low: number, high: number): number[] { const ans: number[] = []; @@ -145,10 +129,6 @@ function sequentialDigits(low: number, high: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1291.Sequential Digits/README_EN.md b/solution/1200-1299/1291.Sequential Digits/README_EN.md index 4caedeadf2c33..d3664dc0d983a 100644 --- a/solution/1200-1299/1291.Sequential Digits/README_EN.md +++ b/solution/1200-1299/1291.Sequential Digits/README_EN.md @@ -25,9 +25,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -42,8 +42,6 @@ class Solution: return sorted(ans) ``` -### **Java** - ```java class Solution { public List sequentialDigits(int low, int high) { @@ -63,8 +61,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -85,8 +81,6 @@ public: }; ``` -### **Go** - ```go func sequentialDigits(low int, high int) (ans []int) { for i := 1; i < 9; i++ { @@ -103,8 +97,6 @@ func sequentialDigits(low int, high int) (ans []int) { } ``` -### **TypeScript** - ```ts function sequentialDigits(low: number, high: number): number[] { const ans: number[] = []; @@ -122,10 +114,6 @@ function sequentialDigits(low: number, high: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/README.md b/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/README.md index 2568de02d98f4..b11e6fa8a6da9 100644 --- a/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/README.md +++ b/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:二维前缀和 + 二分查找** +### 方法一:二维前缀和 + 二分查找 我们可以先预处理得到二维前缀和数组 $s$,其中 $s[i + 1][j + 1]$ 表示矩阵 $mat$ 中从 $(0, 0)$ 到 $(i, j)$ 的元素和,那么对于任意的正方形区域,我们都可以在 $O(1)$ 的时间内得到其元素和。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def maxSideLength(self, mat: List[List[int]], threshold: int) -> int: @@ -84,10 +78,6 @@ class Solution: return l ``` -### **Java** - - - ```java class Solution { private int m; @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go func maxSideLength(mat [][]int, threshold int) int { m, n := len(mat), len(mat[0]) @@ -205,8 +191,6 @@ func maxSideLength(mat [][]int, threshold int) int { } ``` -### **TypeScript** - ```ts function maxSideLength(mat: number[][], threshold: number): number { const m = mat.length; @@ -244,10 +228,6 @@ function maxSideLength(mat: number[][], threshold: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/README_EN.md b/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/README_EN.md index 482d009e54efb..12950918be590 100644 --- a/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/README_EN.md +++ b/solution/1200-1299/1292.Maximum Side Length of a Square with Sum Less than or Equal to Threshold/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return l ``` -### **Java** - ```java class Solution { private int m; @@ -109,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +143,6 @@ public: }; ``` -### **Go** - ```go func maxSideLength(mat [][]int, threshold int) int { m, n := len(mat), len(mat[0]) @@ -184,8 +178,6 @@ func maxSideLength(mat [][]int, threshold int) int { } ``` -### **TypeScript** - ```ts function maxSideLength(mat: number[][], threshold: number): number { const m = mat.length; @@ -223,10 +215,6 @@ function maxSideLength(mat: number[][], threshold: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/README.md b/solution/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/README.md index 446a667f40759..03babaa0df17a 100644 --- a/solution/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/README.md +++ b/solution/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/README.md @@ -49,18 +49,10 @@ ## 解法 - - -BFS 最短路模型。 - -对于本题,如果 `k >= m + n - 3`,那么最短路径长度一定是 `m + n - 2`,直接返回,无需 BFS 计算。 +### 方法一 -### **Python3** - - - ```python class Solution: def shortestPath(self, grid: List[List[int]], k: int) -> int: @@ -88,10 +80,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int shortestPath(int[][] grid, int k) { @@ -134,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -174,8 +160,6 @@ public: }; ``` -### **Go** - ```go func shortestPath(grid [][]int, k int) int { m, n := len(grid), len(grid[0]) @@ -220,10 +204,6 @@ func shortestPath(grid [][]int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/README_EN.md b/solution/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/README_EN.md index 8d01fc3b28f0b..a14936c6de835 100644 --- a/solution/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/README_EN.md +++ b/solution/1200-1299/1293.Shortest Path in a Grid with Obstacles Elimination/README_EN.md @@ -41,9 +41,9 @@ The shortest path with one obstacle elimination at position (3,2) is 6. Such pat ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int shortestPath(int[][] grid, int k) { @@ -116,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +152,6 @@ public: }; ``` -### **Go** - ```go func shortestPath(grid [][]int, k int) int { m, n := len(grid), len(grid[0]) @@ -202,10 +196,6 @@ func shortestPath(grid [][]int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1294.Weather Type in Each Country/README.md b/solution/1200-1299/1294.Weather Type in Each Country/README.md index d5adb7ffa8866..e34c6644e1a1c 100644 --- a/solution/1200-1299/1294.Weather Type in Each Country/README.md +++ b/solution/1200-1299/1294.Weather Type in Each Country/README.md @@ -111,12 +111,10 @@ Morocco 11 月的平均 weather_state 为 (25 + 27 + 31) / 3 = 27.667 所以天 ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -134,3 +132,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1200-1299/1294.Weather Type in Each Country/README_EN.md b/solution/1200-1299/1294.Weather Type in Each Country/README_EN.md index 33516304071a9..8990281935254 100644 --- a/solution/1200-1299/1294.Weather Type in Each Country/README_EN.md +++ b/solution/1200-1299/1294.Weather Type in Each Country/README_EN.md @@ -108,9 +108,9 @@ We know nothing about the average weather_state in Spain in November so we do no ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -129,3 +129,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README.md b/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README.md index e15f3b3db9f92..16ef0cf0f58f4 100644 --- a/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README.md +++ b/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 枚举数组 `nums` 中的每个元素,将其转换为字符串,判断字符串长度是否为偶数,是则答案加一。 @@ -52,20 +50,12 @@ -### **Python3** - - - ```python class Solution: def findNumbers(self, nums: List[int]) -> int: return sum(len(str(v)) % 2 == 0 for v in nums) ``` -### **Java** - - - ```java class Solution { public int findNumbers(int[] nums) { @@ -80,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +83,6 @@ public: }; ``` -### **Go** - ```go func findNumbers(nums []int) (ans int) { for _, v := range nums { @@ -108,8 +94,6 @@ func findNumbers(nums []int) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -124,10 +108,6 @@ var findNumbers = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README_EN.md b/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README_EN.md index 5503dbadc0c88..fe1df932292b9 100644 --- a/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README_EN.md +++ b/solution/1200-1299/1295.Find Numbers with Even Number of Digits/README_EN.md @@ -40,9 +40,9 @@ Only 1771 contains an even number of digits. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -50,8 +50,6 @@ class Solution: return sum(len(str(v)) % 2 == 0 for v in nums) ``` -### **Java** - ```java class Solution { public int findNumbers(int[] nums) { @@ -66,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -81,8 +77,6 @@ public: }; ``` -### **Go** - ```go func findNumbers(nums []int) (ans int) { for _, v := range nums { @@ -94,8 +88,6 @@ func findNumbers(nums []int) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -110,10 +102,6 @@ var findNumbers = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README.md b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README.md index 4e4811d8ae142..6d3ed91b76ad6 100644 --- a/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README.md +++ b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:哈希表 + 排序** +### 方法一:哈希表 + 排序 我们先用哈希表 `cnt` 统计数组 `nums` 中每个数字出现的次数,然后对数组 `nums` 进行排序。 @@ -67,20 +65,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `nums` 的长度。 -**方法二:有序集合** - -我们也可以使用有序集合统计数组 `nums` 中每个数字出现的次数。 - -接下来,循环取出有序集合中的最小值 $v$,然后枚举 $v$ 到 $v+k-1$ 的每个数字,如果这些数字在有序集合中出现的次数都不为 $0$,则我们将这些数字的出现次数减 $1$,如果出现次数减 $1$ 后为 $0$,则将该数字从有序集合中删除,否则说明无法将数组划分成若干个长度为 $k$ 的子数组,返回 `false`。如果可以将数组划分成若干个长度为 $k$ 的子数组,则遍历结束后返回 `true`。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `nums` 的长度。 - -### **Python3** - - - ```python class Solution: def isPossibleDivide(self, nums: List[int], k: int) -> bool: @@ -96,36 +82,6 @@ class Solution: return True ``` -```python -from sortedcontainers import SortedDict - - -class Solution: - def isPossibleDivide(self, nums: List[int], k: int) -> bool: - if len(nums) % k != 0: - return False - sd = SortedDict() - for h in nums: - if h in sd: - sd[h] += 1 - else: - sd[h] = 1 - while sd: - v = sd.peekitem(0)[0] - for i in range(v, v + k): - if i not in sd: - return False - if sd[i] == 1: - sd.pop(i) - else: - sd[i] -= 1 - return True -``` - -### **Java** - - - ```java class Solution { public boolean isPossibleDivide(int[] nums, int k) { @@ -152,6 +108,92 @@ class Solution { } ``` +```cpp +class Solution { +public: + bool isPossibleDivide(vector& nums, int k) { + unordered_map cnt; + for (int& v : nums) ++cnt[v]; + sort(nums.begin(), nums.end()); + for (int& v : nums) { + if (cnt.count(v)) { + for (int x = v; x < v + k; ++x) { + if (!cnt.count(x)) { + return false; + } + if (--cnt[x] == 0) { + cnt.erase(x); + } + } + } + } + return true; + } +}; +``` + +```go +func isPossibleDivide(nums []int, k int) bool { + cnt := map[int]int{} + for _, v := range nums { + cnt[v]++ + } + sort.Ints(nums) + for _, v := range nums { + if _, ok := cnt[v]; ok { + for x := v; x < v+k; x++ { + if _, ok := cnt[x]; !ok { + return false + } + cnt[x]-- + if cnt[x] == 0 { + delete(cnt, x) + } + } + } + } + return true +} +``` + + + +### 方法二:有序集合 + +我们也可以使用有序集合统计数组 `nums` 中每个数字出现的次数。 + +接下来,循环取出有序集合中的最小值 $v$,然后枚举 $v$ 到 $v+k-1$ 的每个数字,如果这些数字在有序集合中出现的次数都不为 $0$,则我们将这些数字的出现次数减 $1$,如果出现次数减 $1$ 后为 $0$,则将该数字从有序集合中删除,否则说明无法将数组划分成若干个长度为 $k$ 的子数组,返回 `false`。如果可以将数组划分成若干个长度为 $k$ 的子数组,则遍历结束后返回 `true`。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `nums` 的长度。 + + + +```python +from sortedcontainers import SortedDict + + +class Solution: + def isPossibleDivide(self, nums: List[int], k: int) -> bool: + if len(nums) % k != 0: + return False + sd = SortedDict() + for h in nums: + if h in sd: + sd[h] += 1 + else: + sd[h] = 1 + while sd: + v = sd.peekitem(0)[0] + for i in range(v, v + k): + if i not in sd: + return False + if sd[i] == 1: + sd.pop(i) + else: + sd[i] -= 1 + return True +``` + ```java class Solution { public boolean isPossibleDivide(int[] nums, int k) { @@ -180,32 +222,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool isPossibleDivide(vector& nums, int k) { - unordered_map cnt; - for (int& v : nums) ++cnt[v]; - sort(nums.begin(), nums.end()); - for (int& v : nums) { - if (cnt.count(v)) { - for (int x = v; x < v + k; ++x) { - if (!cnt.count(x)) { - return false; - } - if (--cnt[x] == 0) { - cnt.erase(x); - } - } - } - } - return true; - } -}; -``` - ```cpp class Solution { public: @@ -228,32 +244,6 @@ public: }; ``` -### **Go** - -```go -func isPossibleDivide(nums []int, k int) bool { - cnt := map[int]int{} - for _, v := range nums { - cnt[v]++ - } - sort.Ints(nums) - for _, v := range nums { - if _, ok := cnt[v]; ok { - for x := v; x < v+k; x++ { - if _, ok := cnt[x]; !ok { - return false - } - cnt[x]-- - if cnt[x] == 0 { - delete(cnt, x) - } - } - } - } - return true -} -``` - ```go func isPossibleDivide(nums []int, k int) bool { if len(nums)%k != 0 { @@ -284,10 +274,6 @@ func isPossibleDivide(nums []int, k int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README_EN.md b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README_EN.md index 45065bee16f23..51e074eb41eb8 100644 --- a/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README_EN.md +++ b/solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,34 +65,6 @@ class Solution: return True ``` -```python -from sortedcontainers import SortedDict - - -class Solution: - def isPossibleDivide(self, nums: List[int], k: int) -> bool: - if len(nums) % k != 0: - return False - sd = SortedDict() - for h in nums: - if h in sd: - sd[h] += 1 - else: - sd[h] = 1 - while sd: - v = sd.peekitem(0)[0] - for i in range(v, v + k): - if i not in sd: - return False - if sd[i] == 1: - sd.pop(i) - else: - sd[i] -= 1 - return True -``` - -### **Java** - ```java class Solution { public boolean isPossibleDivide(int[] nums, int k) { @@ -119,6 +91,86 @@ class Solution { } ``` +```cpp +class Solution { +public: + bool isPossibleDivide(vector& nums, int k) { + unordered_map cnt; + for (int& v : nums) ++cnt[v]; + sort(nums.begin(), nums.end()); + for (int& v : nums) { + if (cnt.count(v)) { + for (int x = v; x < v + k; ++x) { + if (!cnt.count(x)) { + return false; + } + if (--cnt[x] == 0) { + cnt.erase(x); + } + } + } + } + return true; + } +}; +``` + +```go +func isPossibleDivide(nums []int, k int) bool { + cnt := map[int]int{} + for _, v := range nums { + cnt[v]++ + } + sort.Ints(nums) + for _, v := range nums { + if _, ok := cnt[v]; ok { + for x := v; x < v+k; x++ { + if _, ok := cnt[x]; !ok { + return false + } + cnt[x]-- + if cnt[x] == 0 { + delete(cnt, x) + } + } + } + } + return true +} +``` + + + +### Solution 2 + + + +```python +from sortedcontainers import SortedDict + + +class Solution: + def isPossibleDivide(self, nums: List[int], k: int) -> bool: + if len(nums) % k != 0: + return False + sd = SortedDict() + for h in nums: + if h in sd: + sd[h] += 1 + else: + sd[h] = 1 + while sd: + v = sd.peekitem(0)[0] + for i in range(v, v + k): + if i not in sd: + return False + if sd[i] == 1: + sd.pop(i) + else: + sd[i] -= 1 + return True +``` + ```java class Solution { public boolean isPossibleDivide(int[] nums, int k) { @@ -147,32 +199,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool isPossibleDivide(vector& nums, int k) { - unordered_map cnt; - for (int& v : nums) ++cnt[v]; - sort(nums.begin(), nums.end()); - for (int& v : nums) { - if (cnt.count(v)) { - for (int x = v; x < v + k; ++x) { - if (!cnt.count(x)) { - return false; - } - if (--cnt[x] == 0) { - cnt.erase(x); - } - } - } - } - return true; - } -}; -``` - ```cpp class Solution { public: @@ -195,32 +221,6 @@ public: }; ``` -### **Go** - -```go -func isPossibleDivide(nums []int, k int) bool { - cnt := map[int]int{} - for _, v := range nums { - cnt[v]++ - } - sort.Ints(nums) - for _, v := range nums { - if _, ok := cnt[v]; ok { - for x := v; x < v+k; x++ { - if _, ok := cnt[x]; !ok { - return false - } - cnt[x]-- - if cnt[x] == 0 { - delete(cnt, x) - } - } - } - } - return true -} -``` - ```go func isPossibleDivide(nums []int, k int) bool { if len(nums)%k != 0 { @@ -251,10 +251,6 @@ func isPossibleDivide(nums []int, k int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1297.Maximum Number of Occurrences of a Substring/README.md b/solution/1200-1299/1297.Maximum Number of Occurrences of a Substring/README.md index 788e5164d516b..37559feeeed5a 100644 --- a/solution/1200-1299/1297.Maximum Number of Occurrences of a Substring/README.md +++ b/solution/1200-1299/1297.Maximum Number of Occurrences of a Substring/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:哈希表 + 枚举** +### 方法一:哈希表 + 枚举 根据题目描述,如果一个长串满足条件,那么这个长串的子串(长度至少为 `minSize`)也一定满足条件。因此,我们只需要枚举 $s$ 中所有长度为 `minSize` 的子串,然后利用哈希表记录所有子串的出现次数,找出最大的次数作为答案即可。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxFreq(String s, int maxLetters, int minSize, int maxSize) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func maxFreq(s string, maxLetters int, minSize int, maxSize int) (ans int) { cnt := map[string]int{} @@ -150,10 +136,6 @@ func maxFreq(s string, maxLetters int, minSize int, maxSize int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1297.Maximum Number of Occurrences of a Substring/README_EN.md b/solution/1200-1299/1297.Maximum Number of Occurrences of a Substring/README_EN.md index c0ec4e1a1ac24..e042dbb9bf32a 100644 --- a/solution/1200-1299/1297.Maximum Number of Occurrences of a Substring/README_EN.md +++ b/solution/1200-1299/1297.Maximum Number of Occurrences of a Substring/README_EN.md @@ -41,9 +41,9 @@ It satisfies the conditions, 2 unique letters and size 3 (between minSize and ma ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxFreq(String s, int maxLetters, int minSize, int maxSize) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +98,6 @@ public: }; ``` -### **Go** - ```go func maxFreq(s string, maxLetters int, minSize int, maxSize int) (ans int) { cnt := map[string]int{} @@ -124,10 +118,6 @@ func maxFreq(s string, maxLetters int, minSize int, maxSize int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README.md b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README.md index 256b47185b020..43d9cd2725f77 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README.md +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README.md @@ -81,16 +81,10 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS -### **Python3** - - - ```python class Solution: def maxCandies( @@ -123,10 +117,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxCandies( @@ -168,8 +158,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -212,8 +200,6 @@ public: }; ``` -### **Go** - ```go func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) int { ans := 0 @@ -253,10 +239,6 @@ func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]in } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md index f4e8381a0053e..d9acc5f40aef9 100644 --- a/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md +++ b/solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/README_EN.md @@ -59,12 +59,10 @@ The total number of candies will be 6. ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def maxCandies( @@ -97,8 +95,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxCandies( @@ -140,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -184,8 +178,6 @@ public: }; ``` -### **Go** - ```go func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) int { ans := 0 @@ -225,10 +217,6 @@ func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]in } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1299.Replace Elements with Greatest Element on Right Side/README.md b/solution/1200-1299/1299.Replace Elements with Greatest Element on Right Side/README.md index 2d36d5313d22f..a45a7c0495f77 100644 --- a/solution/1200-1299/1299.Replace Elements with Greatest Element on Right Side/README.md +++ b/solution/1200-1299/1299.Replace Elements with Greatest Element on Right Side/README.md @@ -45,14 +45,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def replaceElements(self, arr: List[int]) -> List[int]: @@ -64,10 +60,6 @@ class Solution: return arr ``` -### **Java** - - - ```java class Solution { public int[] replaceElements(int[] arr) { @@ -81,10 +73,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1200-1299/1299.Replace Elements with Greatest Element on Right Side/README_EN.md b/solution/1200-1299/1299.Replace Elements with Greatest Element on Right Side/README_EN.md index 7451b67196039..1bd60631bd6f1 100644 --- a/solution/1200-1299/1299.Replace Elements with Greatest Element on Right Side/README_EN.md +++ b/solution/1200-1299/1299.Replace Elements with Greatest Element on Right Side/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return arr ``` -### **Java** - ```java class Solution { public int[] replaceElements(int[] arr) { @@ -71,10 +69,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1300.Sum of Mutated Array Closest to Target/README.md b/solution/1300-1399/1300.Sum of Mutated Array Closest to Target/README.md index 4b645f6b32353..049e65889c97a 100644 --- a/solution/1300-1399/1300.Sum of Mutated Array Closest to Target/README.md +++ b/solution/1300-1399/1300.Sum of Mutated Array Closest to Target/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:排序 + 前缀和 + 二分查找 + 枚举** +### 方法一:排序 + 前缀和 + 二分查找 + 枚举 我们注意到,题目中要把所有大于 `value` 的值变成 `value`,并且求和,因此我们可以考虑先对数组 `arr` 进行排序,然后求出前缀和数组 $s$,其中 $s[i]$ 表示数组前 $i$ 个元素之和。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def findBestValue(self, arr: List[int], target: int) -> int: @@ -77,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int findBestValue(int[] arr, int target) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +136,6 @@ public: }; ``` -### **Go** - ```go func findBestValue(arr []int, target int) (ans int) { sort.Ints(arr) @@ -179,10 +165,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1300.Sum of Mutated Array Closest to Target/README_EN.md b/solution/1300-1399/1300.Sum of Mutated Array Closest to Target/README_EN.md index 48cec629c92f7..cd85586bc26e5 100644 --- a/solution/1300-1399/1300.Sum of Mutated Array Closest to Target/README_EN.md +++ b/solution/1300-1399/1300.Sum of Mutated Array Closest to Target/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int findBestValue(int[] arr, int target) { @@ -102,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +127,6 @@ public: }; ``` -### **Go** - ```go func findBestValue(arr []int, target int) (ans int) { sort.Ints(arr) @@ -162,10 +156,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1301.Number of Paths with Max Score/README.md b/solution/1300-1399/1301.Number of Paths with Max Score/README.md index 941fded34eddb..469a7e8e6042d 100644 --- a/solution/1300-1399/1301.Number of Paths with Max Score/README.md +++ b/solution/1300-1399/1301.Number of Paths with Max Score/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示从起点 $(n - 1, n - 1)$ 到达 $(i, j)$ 的最大得分,定义 $g[i][j]$ 表示从起点 $(n - 1, n - 1)$ 到达 $(i, j)$ 的最大得分的方案数。初始时 $f[n - 1][n - 1] = 0$,并且 $g[n - 1][n - 1] = 1$。其它位置的 $f[i][j]$ 均为 $-1$,而 $g[i][j]$ 均为 $0$。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def pathsWithMaxScore(self, board: List[str]) -> List[int]: @@ -94,10 +88,6 @@ class Solution: return [0, 0] if f[0][0] == -1 else [f[0][0], g[0][0] % mod] ``` -### **Java** - - - ```java class Solution { private List board; @@ -152,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -201,8 +189,6 @@ public: }; ``` -### **Go** - ```go func pathsWithMaxScore(board []string) []int { n := len(board) @@ -248,10 +234,6 @@ func pathsWithMaxScore(board []string) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md b/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md index 1ed93c99e0e1a..bde313dbfadbc 100644 --- a/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md +++ b/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md @@ -32,9 +32,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return [0, 0] if f[0][0] == -1 else [f[0][0], g[0][0] % mod] ``` -### **Java** - ```java class Solution { private List board; @@ -119,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +164,6 @@ public: }; ``` -### **Go** - ```go func pathsWithMaxScore(board []string) []int { n := len(board) @@ -215,10 +209,6 @@ func pathsWithMaxScore(board []string) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1302.Deepest Leaves Sum/README.md b/solution/1300-1399/1302.Deepest Leaves Sum/README.md index 8a74bc47341c8..75144fed28b4f 100644 --- a/solution/1300-1399/1302.Deepest Leaves Sum/README.md +++ b/solution/1300-1399/1302.Deepest Leaves Sum/README.md @@ -37,24 +37,14 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 可以忽略一些细节,每次都统计当前遍历层级的数值和,当 BFS 结束时,最后一次数值和便是结果。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是树中节点的数目。 -**方法二:DFS** - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是树中节点的数目。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -77,36 +67,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: - def dfs(root, i): - nonlocal ans, mx - if root is None: - return - if i == mx: - ans += root.val - elif i > mx: - ans = root.val - mx = i - dfs(root.left, i + 1) - dfs(root.right, i + 1) - - ans = mx = 0 - dfs(root, 1) - return ans -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -146,49 +106,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - int mx; - int ans; - - public int deepestLeavesSum(TreeNode root) { - dfs(root, 1); - return ans; - } - - private void dfs(TreeNode root, int i) { - if (root == null) { - return; - } - if (i > mx) { - mx = i; - ans = root.val; - } else if (i == mx) { - ans += root.val; - } - dfs(root.left, i + 1); - dfs(root.right, i + 1); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -221,44 +138,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int mx = 0; - int ans = 0; - - int deepestLeavesSum(TreeNode* root) { - dfs(root, 1); - return ans; - } - - void dfs(TreeNode* root, int i) { - if (!root) return; - if (i == mx) { - ans += root->val; - } else if (i > mx) { - mx = i; - ans = root->val; - } - dfs(root->left, i + 1); - dfs(root->right, i + 1); - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -289,37 +168,86 @@ func deepestLeavesSum(root *TreeNode) int { } ``` -```go +```ts /** * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode + * 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) + * } * } */ -func deepestLeavesSum(root *TreeNode) int { - ans, mx := 0, 0 - var dfs func(*TreeNode, int) - dfs = func(root *TreeNode, i int) { - if root == nil { - return - } - if i == mx { - ans += root.Val - } else if i > mx { - mx = i - ans = root.Val - } - dfs(root.Left, i+1) - dfs(root.Right, i+1) - } - dfs(root, 1) - return ans + +function deepestLeavesSum(root: TreeNode | null): number { + const queue = [root]; + let res = 0; + while (queue.length !== 0) { + const n = queue.length; + let sum = 0; + for (let i = 0; i < n; i++) { + const { val, left, right } = queue.shift(); + sum += val; + left && queue.push(left); + right && queue.push(right); + } + res = sum; + } + return res; } ``` -### **C** +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(root: &Option>>, depth: i32, max_depth: &mut i32, res: &mut i32) { + if let Some(node) = root { + let node = node.borrow(); + if node.left.is_none() && node.right.is_none() { + if depth == *max_depth { + *res += node.val; + } else if depth > *max_depth { + *max_depth = depth; + *res = node.val; + } + return; + } + Self::dfs(&node.left, depth + 1, max_depth, res); + Self::dfs(&node.right, depth + 1, max_depth, res); + } + } + + pub fn deepest_leaves_sum(root: Option>>) -> i32 { + let mut res = 0; + let mut max_depth = 0; + Self::dfs(&root, 0, &mut max_depth, &mut res); + res + } +} +``` ```c /** @@ -357,38 +285,144 @@ int deepestLeavesSum(struct TreeNode* root) { } ``` -### **TypeScript** + -```ts +### 方法二:DFS + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是树中节点的数目。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: + def dfs(root, i): + nonlocal ans, mx + if root is None: + return + if i == mx: + ans += root.val + elif i > mx: + ans = root.val + mx = i + dfs(root.left, i + 1) + dfs(root.right, i + 1) + + ans = mx = 0 + dfs(root, 1) + return ans +``` + +```java /** * 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) + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; * } * } */ +class Solution { + int mx; + int ans; -function deepestLeavesSum(root: TreeNode | null): number { - const queue = [root]; - let res = 0; - while (queue.length !== 0) { - const n = queue.length; - let sum = 0; - for (let i = 0; i < n; i++) { - const { val, left, right } = queue.shift(); - sum += val; - left && queue.push(left); - right && queue.push(right); + public int deepestLeavesSum(TreeNode root) { + dfs(root, 1); + return ans; + } + + private void dfs(TreeNode root, int i) { + if (root == null) { + return; } - res = sum; + if (i > mx) { + mx = i; + ans = root.val; + } else if (i == mx) { + ans += root.val; + } + dfs(root.left, i + 1); + dfs(root.right, i + 1); } - return res; +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int mx = 0; + int ans = 0; + + int deepestLeavesSum(TreeNode* root) { + dfs(root, 1); + return ans; + } + + void dfs(TreeNode* root, int i) { + if (!root) return; + if (i == mx) { + ans += root->val; + } else if (i > mx) { + mx = i; + ans = root->val; + } + dfs(root->left, i + 1); + dfs(root->right, i + 1); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func deepestLeavesSum(root *TreeNode) int { + ans, mx := 0, 0 + var dfs func(*TreeNode, int) + dfs = func(root *TreeNode, i int) { + if root == nil { + return + } + if i == mx { + ans += root.Val + } else if i > mx { + mx = i + ans = root.Val + } + dfs(root.Left, i+1) + dfs(root.Right, i+1) + } + dfs(root, 1) + return ans } ``` @@ -428,60 +462,6 @@ function deepestLeavesSum(root: TreeNode | null): number { } ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(root: &Option>>, depth: i32, max_depth: &mut i32, res: &mut i32) { - if let Some(node) = root { - let node = node.borrow(); - if node.left.is_none() && node.right.is_none() { - if depth == *max_depth { - *res += node.val; - } else if depth > *max_depth { - *max_depth = depth; - *res = node.val; - } - return; - } - Self::dfs(&node.left, depth + 1, max_depth, res); - Self::dfs(&node.right, depth + 1, max_depth, res); - } - } - - pub fn deepest_leaves_sum(root: Option>>) -> i32 { - let mut res = 0; - let mut max_depth = 0; - Self::dfs(&root, 0, &mut max_depth, &mut res); - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1302.Deepest Leaves Sum/README_EN.md b/solution/1300-1399/1302.Deepest Leaves Sum/README_EN.md index 2fc448cfe9e52..bd3d66bec1c74 100644 --- a/solution/1300-1399/1302.Deepest Leaves Sum/README_EN.md +++ b/solution/1300-1399/1302.Deepest Leaves Sum/README_EN.md @@ -31,12 +31,10 @@ Given the root of a binary tree, return the sum of values of it ## Solutions -DFS or BFS. +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -59,34 +57,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: - def dfs(root, i): - nonlocal ans, mx - if root is None: - return - if i == mx: - ans += root.val - elif i > mx: - ans = root.val - mx = i - dfs(root.left, i + 1) - dfs(root.right, i + 1) - - ans = mx = 0 - dfs(root, 1) - return ans -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -126,49 +96,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - int mx; - int ans; - - public int deepestLeavesSum(TreeNode root) { - dfs(root, 1); - return ans; - } - - private void dfs(TreeNode root, int i) { - if (root == null) { - return; - } - if (i > mx) { - mx = i; - ans = root.val; - } else if (i == mx) { - ans += root.val; - } - dfs(root.left, i + 1); - dfs(root.right, i + 1); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -201,44 +128,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - int mx = 0; - int ans = 0; - - int deepestLeavesSum(TreeNode* root) { - dfs(root, 1); - return ans; - } - - void dfs(TreeNode* root, int i) { - if (!root) return; - if (i == mx) { - ans += root->val; - } else if (i > mx) { - mx = i; - ans = root->val; - } - dfs(root->left, i + 1); - dfs(root->right, i + 1); - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -269,37 +158,86 @@ func deepestLeavesSum(root *TreeNode) int { } ``` -```go +```ts /** * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode + * 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) + * } * } */ -func deepestLeavesSum(root *TreeNode) int { - ans, mx := 0, 0 - var dfs func(*TreeNode, int) - dfs = func(root *TreeNode, i int) { - if root == nil { - return - } - if i == mx { - ans += root.Val - } else if i > mx { - mx = i - ans = root.Val - } - dfs(root.Left, i+1) - dfs(root.Right, i+1) - } - dfs(root, 1) - return ans + +function deepestLeavesSum(root: TreeNode | null): number { + const queue = [root]; + let res = 0; + while (queue.length !== 0) { + const n = queue.length; + let sum = 0; + for (let i = 0; i < n; i++) { + const { val, left, right } = queue.shift(); + sum += val; + left && queue.push(left); + right && queue.push(right); + } + res = sum; + } + return res; } ``` -### **C** +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::rc::Rc; +use std::cell::RefCell; +impl Solution { + fn dfs(root: &Option>>, depth: i32, max_depth: &mut i32, res: &mut i32) { + if let Some(node) = root { + let node = node.borrow(); + if node.left.is_none() && node.right.is_none() { + if depth == *max_depth { + *res += node.val; + } else if depth > *max_depth { + *max_depth = depth; + *res = node.val; + } + return; + } + Self::dfs(&node.left, depth + 1, max_depth, res); + Self::dfs(&node.right, depth + 1, max_depth, res); + } + } + + pub fn deepest_leaves_sum(root: Option>>) -> i32 { + let mut res = 0; + let mut max_depth = 0; + Self::dfs(&root, 0, &mut max_depth, &mut res); + res + } +} +``` ```c /** @@ -337,38 +275,142 @@ int deepestLeavesSum(struct TreeNode* root) { } ``` -### **TypeScript** + -```ts +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: + def dfs(root, i): + nonlocal ans, mx + if root is None: + return + if i == mx: + ans += root.val + elif i > mx: + ans = root.val + mx = i + dfs(root.left, i + 1) + dfs(root.right, i + 1) + + ans = mx = 0 + dfs(root, 1) + return ans +``` + +```java /** * 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) + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; * } * } */ +class Solution { + int mx; + int ans; -function deepestLeavesSum(root: TreeNode | null): number { - const queue = [root]; - let res = 0; - while (queue.length !== 0) { - const n = queue.length; - let sum = 0; - for (let i = 0; i < n; i++) { - const { val, left, right } = queue.shift(); - sum += val; - left && queue.push(left); - right && queue.push(right); + public int deepestLeavesSum(TreeNode root) { + dfs(root, 1); + return ans; + } + + private void dfs(TreeNode root, int i) { + if (root == null) { + return; } - res = sum; + if (i > mx) { + mx = i; + ans = root.val; + } else if (i == mx) { + ans += root.val; + } + dfs(root.left, i + 1); + dfs(root.right, i + 1); } - return res; +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int mx = 0; + int ans = 0; + + int deepestLeavesSum(TreeNode* root) { + dfs(root, 1); + return ans; + } + + void dfs(TreeNode* root, int i) { + if (!root) return; + if (i == mx) { + ans += root->val; + } else if (i > mx) { + mx = i; + ans = root->val; + } + dfs(root->left, i + 1); + dfs(root->right, i + 1); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func deepestLeavesSum(root *TreeNode) int { + ans, mx := 0, 0 + var dfs func(*TreeNode, int) + dfs = func(root *TreeNode, i int) { + if root == nil { + return + } + if i == mx { + ans += root.Val + } else if i > mx { + mx = i + ans = root.Val + } + dfs(root.Left, i+1) + dfs(root.Right, i+1) + } + dfs(root, 1) + return ans } ``` @@ -408,60 +450,6 @@ function deepestLeavesSum(root: TreeNode | null): number { } ``` -### **Rust** - -```rust -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::rc::Rc; -use std::cell::RefCell; -impl Solution { - fn dfs(root: &Option>>, depth: i32, max_depth: &mut i32, res: &mut i32) { - if let Some(node) = root { - let node = node.borrow(); - if node.left.is_none() && node.right.is_none() { - if depth == *max_depth { - *res += node.val; - } else if depth > *max_depth { - *max_depth = depth; - *res = node.val; - } - return; - } - Self::dfs(&node.left, depth + 1, max_depth, res); - Self::dfs(&node.right, depth + 1, max_depth, res); - } - } - - pub fn deepest_leaves_sum(root: Option>>) -> i32 { - let mut res = 0; - let mut max_depth = 0; - Self::dfs(&root, 0, &mut max_depth, &mut res); - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1303.Find the Team Size/README.md b/solution/1300-1399/1303.Find the Team Size/README.md index d13471385d6a0..23c5355c2e8fc 100644 --- a/solution/1300-1399/1303.Find the Team Size/README.md +++ b/solution/1300-1399/1303.Find the Team Size/README.md @@ -63,20 +63,12 @@ ID 为 5、6 的员工是 team_id 为 9 的团队的成员。 ## 解法 - - -**方法一:分组统计 + 等值连接** +### 方法一:分组统计 + 等值连接 我们可以先统计出每个团队的人数,记录在 `T` 表中,然后我们将 `Employee` 表与 `T` 表按照 `team_id` 进行等值连接,即可得到每个员工所在团队的总人数。 -**方法二:左连接** - -我们也可以使用左连接,将 `Employee` 表按照 `team_id` 进行自连接,然后按照 `employee_id` 进行分组,统计每个员工所在团队的总人数。 - -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -91,6 +83,14 @@ FROM JOIN T USING (team_id); ``` + + +### 方法二:左连接 + +我们也可以使用左连接,将 `Employee` 表按照 `team_id` 进行自连接,然后按照 `employee_id` 进行分组,统计每个员工所在团队的总人数。 + + + ```sql # Write your MySQL query statement below SELECT e1.employee_id, COUNT(1) AS team_size @@ -101,3 +101,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1300-1399/1303.Find the Team Size/README_EN.md b/solution/1300-1399/1303.Find the Team Size/README_EN.md index d2fe3ebd15eab..561036eff859f 100644 --- a/solution/1300-1399/1303.Find the Team Size/README_EN.md +++ b/solution/1300-1399/1303.Find the Team Size/README_EN.md @@ -60,18 +60,12 @@ Employees with Id 5,6 are part of a team with team_id = 9. ## Solutions -**Solution 1: Group By + Equi-Join** +### Solution 1: Group By + Equi-Join We can first count the number of people in each team and record it in the `T` table. Then, we can use an equi-join to join the `Employee` table and the `T` table based on `team_id`, and obtain the total number of people in each team. -**Solution 2: Left Join** - -We can also use a left join to join the `Employee` table with itself based on `team_id`, and then group by `employee_id` to count the total number of people in each team that the employee belongs to. - -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -86,6 +80,14 @@ FROM JOIN T USING (team_id); ``` + + +### Solution 2: Left Join + +We can also use a left join to join the `Employee` table with itself based on `team_id`, and then group by `employee_id` to count the total number of people in each team that the employee belongs to. + + + ```sql # Write your MySQL query statement below SELECT e1.employee_id, COUNT(1) AS team_size @@ -96,3 +98,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/README.md b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/README.md index d911793ea393e..af0d23fa6653c 100644 --- a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/README.md +++ b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/README.md @@ -39,26 +39,14 @@ ## 解法 - - -**方法一:构造** +### 方法一:构造 我们可以从 $1$ 开始,依次将正数和负数交替放入结果数组中,一共循环 $\frac{n}{2}$ 次,如果 $n$ 为奇数,则最后再将 $0$ 放入结果数组中。 时间复杂度 $O(n)$,其中 $n$ 为给定的整数。忽略答案的空间消耗,空间复杂度 $O(1)$。 -**方法二:构造 + 数学** - -我们也可以将 $1$ 到 $n-1$ 的所有整数放入结果数组中,最后再把前 $n-1$ 个整数的和 $\frac{n(n-1)}{2}$ 的相反数放入结果数组中。 - -时间复杂度 $O(n)$,其中 $n$ 为给定的整数。忽略答案的空间消耗,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def sumZero(self, n: int) -> List[int]: @@ -71,18 +59,6 @@ class Solution: return ans ``` -```python -class Solution: - def sumZero(self, n: int) -> List[int]: - ans = list(range(1, n)) - ans.append(-sum(ans)) - return ans -``` - -### **Java** - - - ```java class Solution { public int[] sumZero(int n) { @@ -96,21 +72,6 @@ class Solution { } ``` -```java -class Solution { - public int[] sumZero(int n) { - int[] ans = new int[n]; - for (int i = 1; i < n; ++i) { - ans[i] = i; - } - ans[0] = -(n * (n - 1) / 2); - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -125,20 +86,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector sumZero(int n) { - vector ans(n); - iota(ans.begin(), ans.end(), 1); - ans[n - 1] = -(n - 1) * n / 2; - return ans; - } -}; -``` - -### **Go** - ```go func sumZero(n int) []int { ans := make([]int, n) @@ -151,19 +98,6 @@ func sumZero(n int) []int { } ``` -```go -func sumZero(n int) []int { - ans := make([]int, n) - for i := 1; i < n; i++ { - ans[i] = i - } - ans[0] = -n * (n - 1) / 2 - return ans -} -``` - -### **TypeScript** - ```ts function sumZero(n: number): number[] { const ans = new Array(n).fill(0); @@ -175,6 +109,60 @@ function sumZero(n: number): number[] { } ``` + + +### 方法二:构造 + 数学 + +我们也可以将 $1$ 到 $n-1$ 的所有整数放入结果数组中,最后再把前 $n-1$ 个整数的和 $\frac{n(n-1)}{2}$ 的相反数放入结果数组中。 + +时间复杂度 $O(n)$,其中 $n$ 为给定的整数。忽略答案的空间消耗,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def sumZero(self, n: int) -> List[int]: + ans = list(range(1, n)) + ans.append(-sum(ans)) + return ans +``` + +```java +class Solution { + public int[] sumZero(int n) { + int[] ans = new int[n]; + for (int i = 1; i < n; ++i) { + ans[i] = i; + } + ans[0] = -(n * (n - 1) / 2); + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector sumZero(int n) { + vector ans(n); + iota(ans.begin(), ans.end(), 1); + ans[n - 1] = -(n - 1) * n / 2; + return ans; + } +}; +``` + +```go +func sumZero(n int) []int { + ans := make([]int, n) + for i := 1; i < n; i++ { + ans[i] = i + } + ans[0] = -n * (n - 1) / 2 + return ans +} +``` + ```ts function sumZero(n: number): number[] { const ans = new Array(n).fill(0); @@ -186,10 +174,6 @@ function sumZero(n: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/README_EN.md b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/README_EN.md index bf397b427c67a..8223c7297bd6c 100644 --- a/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/README_EN.md +++ b/solution/1300-1399/1304.Find N Unique Integers Sum up to Zero/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,16 +54,6 @@ class Solution: return ans ``` -```python -class Solution: - def sumZero(self, n: int) -> List[int]: - ans = list(range(1, n)) - ans.append(-sum(ans)) - return ans -``` - -### **Java** - ```java class Solution { public int[] sumZero(int n) { @@ -77,21 +67,6 @@ class Solution { } ``` -```java -class Solution { - public int[] sumZero(int n) { - int[] ans = new int[n]; - for (int i = 1; i < n; ++i) { - ans[i] = i; - } - ans[0] = -(n * (n - 1) / 2); - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -106,20 +81,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector sumZero(int n) { - vector ans(n); - iota(ans.begin(), ans.end(), 1); - ans[n - 1] = -(n - 1) * n / 2; - return ans; - } -}; -``` - -### **Go** - ```go func sumZero(n int) []int { ans := make([]int, n) @@ -132,19 +93,6 @@ func sumZero(n int) []int { } ``` -```go -func sumZero(n int) []int { - ans := make([]int, n) - for i := 1; i < n; i++ { - ans[i] = i - } - ans[0] = -n * (n - 1) / 2 - return ans -} -``` - -### **TypeScript** - ```ts function sumZero(n: number): number[] { const ans = new Array(n).fill(0); @@ -156,6 +104,56 @@ function sumZero(n: number): number[] { } ``` + + +### Solution 2 + + + +```python +class Solution: + def sumZero(self, n: int) -> List[int]: + ans = list(range(1, n)) + ans.append(-sum(ans)) + return ans +``` + +```java +class Solution { + public int[] sumZero(int n) { + int[] ans = new int[n]; + for (int i = 1; i < n; ++i) { + ans[i] = i; + } + ans[0] = -(n * (n - 1) / 2); + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector sumZero(int n) { + vector ans(n); + iota(ans.begin(), ans.end(), 1); + ans[n - 1] = -(n - 1) * n / 2; + return ans; + } +}; +``` + +```go +func sumZero(n int) []int { + ans := make([]int, n) + for i := 1; i < n; i++ { + ans[i] = i + } + ans[0] = -n * (n - 1) / 2 + return ans +} +``` + ```ts function sumZero(n: number): number[] { const ans = new Array(n).fill(0); @@ -167,10 +165,6 @@ function sumZero(n: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1305.All Elements in Two Binary Search Trees/README.md b/solution/1300-1399/1305.All Elements in Two Binary Search Trees/README.md index 45cbe8c2e415b..ddd5f56d7c39f 100644 --- a/solution/1300-1399/1305.All Elements in Two Binary Search Trees/README.md +++ b/solution/1300-1399/1305.All Elements in Two Binary Search Trees/README.md @@ -39,16 +39,10 @@ ## 解法 - - -二叉树中序遍历 + 有序列表归并。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -89,10 +83,6 @@ class Solution: return merge(t1, t2) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -148,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -195,8 +183,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -245,7 +231,49 @@ func getAllElements(root1 *TreeNode, root2 *TreeNode) []int { } ``` -### **Rust** +```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 getAllElements(root1: TreeNode | null, root2: TreeNode | null): number[] { + const res = []; + const stacks = [[], []]; + while (root1 != null || stacks[0].length !== 0 || root2 != null || stacks[1].length !== 0) { + if (root1 != null) { + stacks[0].push(root1); + root1 = root1.left; + } else if (root2 != null) { + stacks[1].push(root2); + root2 = root2.left; + } else { + if ( + (stacks[0][stacks[0].length - 1] ?? { val: Infinity }).val < + (stacks[1][stacks[1].length - 1] ?? { val: Infinity }).val + ) { + const { val, right } = stacks[0].pop(); + res.push(val); + root1 = right; + } else { + const { val, right } = stacks[1].pop(); + res.push(val); + root2 = right; + } + } + } + return res; +} +``` ```rust // Definition for a binary tree node. @@ -311,56 +339,6 @@ impl Solution { } ``` -### **TypeScript** - -```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 getAllElements(root1: TreeNode | null, root2: TreeNode | null): number[] { - const res = []; - const stacks = [[], []]; - while (root1 != null || stacks[0].length !== 0 || root2 != null || stacks[1].length !== 0) { - if (root1 != null) { - stacks[0].push(root1); - root1 = root1.left; - } else if (root2 != null) { - stacks[1].push(root2); - root2 = root2.left; - } else { - if ( - (stacks[0][stacks[0].length - 1] ?? { val: Infinity }).val < - (stacks[1][stacks[1].length - 1] ?? { val: Infinity }).val - ) { - const { val, right } = stacks[0].pop(); - res.push(val); - root1 = right; - } else { - const { val, right } = stacks[1].pop(); - res.push(val); - root2 = right; - } - } - } - return res; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1305.All Elements in Two Binary Search Trees/README_EN.md b/solution/1300-1399/1305.All Elements in Two Binary Search Trees/README_EN.md index 3651c180f18de..e3f7c7a6082bd 100644 --- a/solution/1300-1399/1305.All Elements in Two Binary Search Trees/README_EN.md +++ b/solution/1300-1399/1305.All Elements in Two Binary Search Trees/README_EN.md @@ -31,9 +31,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -75,8 +75,6 @@ class Solution: return merge(t1, t2) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -132,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -179,8 +175,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -229,7 +223,49 @@ func getAllElements(root1 *TreeNode, root2 *TreeNode) []int { } ``` -### **Rust** +```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 getAllElements(root1: TreeNode | null, root2: TreeNode | null): number[] { + const res = []; + const stacks = [[], []]; + while (root1 != null || stacks[0].length !== 0 || root2 != null || stacks[1].length !== 0) { + if (root1 != null) { + stacks[0].push(root1); + root1 = root1.left; + } else if (root2 != null) { + stacks[1].push(root2); + root2 = root2.left; + } else { + if ( + (stacks[0][stacks[0].length - 1] ?? { val: Infinity }).val < + (stacks[1][stacks[1].length - 1] ?? { val: Infinity }).val + ) { + const { val, right } = stacks[0].pop(); + res.push(val); + root1 = right; + } else { + const { val, right } = stacks[1].pop(); + res.push(val); + root2 = right; + } + } + } + return res; +} +``` ```rust // Definition for a binary tree node. @@ -295,56 +331,6 @@ impl Solution { } ``` -### **TypeScript** - -```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 getAllElements(root1: TreeNode | null, root2: TreeNode | null): number[] { - const res = []; - const stacks = [[], []]; - while (root1 != null || stacks[0].length !== 0 || root2 != null || stacks[1].length !== 0) { - if (root1 != null) { - stacks[0].push(root1); - root1 = root1.left; - } else if (root2 != null) { - stacks[1].push(root2); - root2 = root2.left; - } else { - if ( - (stacks[0][stacks[0].length - 1] ?? { val: Infinity }).val < - (stacks[1][stacks[1].length - 1] ?? { val: Infinity }).val - ) { - const { val, right } = stacks[0].pop(); - res.push(val); - root1 = right; - } else { - const { val, right } = stacks[1].pop(); - res.push(val); - root2 = right; - } - } - } - return res; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1306.Jump Game III/README.md b/solution/1300-1399/1306.Jump Game III/README.md index c88a2d38f8f54..f8c2caf0de241 100644 --- a/solution/1300-1399/1306.Jump Game III/README.md +++ b/solution/1300-1399/1306.Jump Game III/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们可以使用 BFS 来判断是否能够到达值为 $0$ 的下标。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def canReach(self, arr: List[int], start: int) -> bool: @@ -88,10 +82,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean canReach(int[] arr, int start) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func canReach(arr []int, start int) bool { q := []int{start} @@ -164,8 +150,6 @@ func canReach(arr []int, start int) bool { } ``` -### **TypeScript** - ```ts function canReach(arr: number[], start: number): boolean { const q: number[] = [start]; @@ -186,10 +170,6 @@ function canReach(arr: number[], start: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1306.Jump Game III/README_EN.md b/solution/1300-1399/1306.Jump Game III/README_EN.md index c56f561f952a6..414374bf13c51 100644 --- a/solution/1300-1399/1306.Jump Game III/README_EN.md +++ b/solution/1300-1399/1306.Jump Game III/README_EN.md @@ -49,12 +49,10 @@ index 0 -> index 4 -> index 1 -> index 3 ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def canReach(self, arr: List[int], start: int) -> bool: @@ -71,8 +69,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean canReach(int[] arr, int start) { @@ -96,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func canReach(arr []int, start int) bool { q := []int{start} @@ -145,8 +137,6 @@ func canReach(arr []int, start int) bool { } ``` -### **TypeScript** - ```ts function canReach(arr: number[], start: number): boolean { const q: number[] = [start]; @@ -167,10 +157,6 @@ function canReach(arr: number[], start: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1307.Verbal Arithmetic Puzzle/README.md b/solution/1300-1399/1307.Verbal Arithmetic Puzzle/README.md index 4c4659ecb9f0d..bf6d1a8fe0850 100644 --- a/solution/1300-1399/1307.Verbal Arithmetic Puzzle/README.md +++ b/solution/1300-1399/1307.Verbal Arithmetic Puzzle/README.md @@ -60,30 +60,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1300-1399/1307.Verbal Arithmetic Puzzle/README_EN.md b/solution/1300-1399/1307.Verbal Arithmetic Puzzle/README_EN.md index 6fe660b2b7903..df1b5ea7f8f94 100644 --- a/solution/1300-1399/1307.Verbal Arithmetic Puzzle/README_EN.md +++ b/solution/1300-1399/1307.Verbal Arithmetic Puzzle/README_EN.md @@ -55,24 +55,4 @@ Note that two different characters cannot map to the same digit. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1300-1399/1308.Running Total for Different Genders/README.md b/solution/1300-1399/1308.Running Total for Different Genders/README.md index c84aed84969ee..4895ab6f108fd 100644 --- a/solution/1300-1399/1308.Running Total for Different Genders/README.md +++ b/solution/1300-1399/1308.Running Total for Different Genders/README.md @@ -81,12 +81,10 @@ Scores表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -100,3 +98,5 @@ FROM Scores; ``` + + diff --git a/solution/1300-1399/1308.Running Total for Different Genders/README_EN.md b/solution/1300-1399/1308.Running Total for Different Genders/README_EN.md index b0eba97940ac1..29adbc2391ae6 100644 --- a/solution/1300-1399/1308.Running Total for Different Genders/README_EN.md +++ b/solution/1300-1399/1308.Running Total for Different Genders/README_EN.md @@ -79,9 +79,9 @@ The fifth day is 2020-01-07, Bajrang scored 7 points and the total score for the ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -96,3 +96,5 @@ FROM Scores; ``` + + diff --git a/solution/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/README.md b/solution/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/README.md index 8e1e882d26a49..2093808234c61 100644 --- a/solution/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/README.md +++ b/solution/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/README.md @@ -46,14 +46,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def freqAlphabets(self, s: str) -> str: @@ -72,10 +68,6 @@ class Solution: return ''.join(res) ``` -### **Java** - - - ```java class Solution { public String freqAlphabets(String s) { @@ -99,8 +91,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function freqAlphabets(s: string): string { const n = s.length; @@ -119,8 +109,6 @@ function freqAlphabets(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn freq_alphabets(s: String) -> String { @@ -144,8 +132,6 @@ impl Solution { } ``` -### **C** - ```c char* freqAlphabets(char* s) { int n = strlen(s); @@ -168,10 +154,6 @@ char* freqAlphabets(char* s) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/README_EN.md b/solution/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/README_EN.md index d665d0a2d9d60..23427bdd9d63e 100644 --- a/solution/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/README_EN.md +++ b/solution/1300-1399/1309.Decrypt String from Alphabet to Integer Mapping/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ''.join(res) ``` -### **Java** - ```java class Solution { public String freqAlphabets(String s) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function freqAlphabets(s: string): string { const n = s.length; @@ -109,8 +105,6 @@ function freqAlphabets(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn freq_alphabets(s: String) -> String { @@ -134,8 +128,6 @@ impl Solution { } ``` -### **C** - ```c char* freqAlphabets(char* s) { int n = strlen(s); @@ -158,10 +150,6 @@ char* freqAlphabets(char* s) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1310.XOR Queries of a Subarray/README.md b/solution/1300-1399/1310.XOR Queries of a Subarray/README.md index d833656958e63..5a6ca7c7e523b 100644 --- a/solution/1300-1399/1310.XOR Queries of a Subarray/README.md +++ b/solution/1300-1399/1310.XOR Queries of a Subarray/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:前缀异或** +### 方法一:前缀异或 我们可以用一个长度为 $n+1$ 的前缀异或数组 $s$ 来存储数组 $arr$ 的前缀异或结果,其中 $s[i] = s[i-1] \oplus arr[i-1]$,即 $s[i]$ 表示 $arr$ 中下标 $[0,i-1]$ 的元素的异或结果。 @@ -72,10 +70,6 @@ $$ -### **Python3** - - - ```python class Solution: def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: @@ -83,10 +77,6 @@ class Solution: return [s[r + 1] ^ s[l] for l, r in queries] ``` -### **Java** - - - ```java class Solution { public int[] xorQueries(int[] arr, int[][] queries) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func xorQueries(arr []int, queries [][]int) (ans []int) { n := len(arr) @@ -145,8 +131,6 @@ func xorQueries(arr []int, queries [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function xorQueries(arr: number[], queries: number[][]): number[] { const n = arr.length; @@ -162,8 +146,6 @@ function xorQueries(arr: number[], queries: number[][]): number[] { } ``` -### **JavaScript** - ```js /** * @param {number[]} arr @@ -184,10 +166,6 @@ var xorQueries = function (arr, queries) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1310.XOR Queries of a Subarray/README_EN.md b/solution/1300-1399/1310.XOR Queries of a Subarray/README_EN.md index f2cafffb6e01b..07257a40f32f4 100644 --- a/solution/1300-1399/1310.XOR Queries of a Subarray/README_EN.md +++ b/solution/1300-1399/1310.XOR Queries of a Subarray/README_EN.md @@ -48,9 +48,9 @@ The XOR values for queries are: ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return [s[r + 1] ^ s[l] for l, r in queries] ``` -### **Java** - ```java class Solution { public int[] xorQueries(int[] arr, int[][] queries) { @@ -80,30 +78,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} arr - * @param {number[][]} queries - * @return {number[]} - */ -var xorQueries = function (arr, queries) { - let n = arr.length; - let xors = new Array(n + 1).fill(0); - for (let i = 0; i < n; i++) { - xors[i + 1] = xors[i] ^ arr[i]; - } - let res = []; - for (let [l, r] of queries) { - res.push(xors[l] ^ xors[r + 1]); - } - return res; -}; -``` - -### **C++** - ```cpp class Solution { public: @@ -124,8 +98,6 @@ public: }; ``` -### **Go** - ```go func xorQueries(arr []int, queries [][]int) (ans []int) { n := len(arr) @@ -141,8 +113,6 @@ func xorQueries(arr []int, queries [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function xorQueries(arr: number[], queries: number[][]): number[] { const n = arr.length; @@ -158,8 +128,6 @@ function xorQueries(arr: number[], queries: number[][]): number[] { } ``` -### **JavaScript** - ```js /** * @param {number[]} arr @@ -180,10 +148,6 @@ var xorQueries = function (arr, queries) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1311.Get Watched Videos by Your Friends/README.md b/solution/1300-1399/1311.Get Watched Videos by Your Friends/README.md index 8b734450b739e..99d88f56b22a2 100644 --- a/solution/1300-1399/1311.Get Watched Videos by Your Friends/README.md +++ b/solution/1300-1399/1311.Get Watched Videos by Your Friends/README.md @@ -59,16 +59,10 @@ C -> 2 ## 解法 - - -BFS。 +### 方法一 -### **Python3** - - - ```python class Solution: def watchedVideosByFriends( @@ -100,10 +94,6 @@ class Solution: return [v[0] for v in videos] ``` -### **Java** - - - ```java class Solution { public List watchedVideosByFriends( @@ -149,10 +139,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1311.Get Watched Videos by Your Friends/README_EN.md b/solution/1300-1399/1311.Get Watched Videos by Your Friends/README_EN.md index 18cc2fdc08ffb..071cb7dfcf6bf 100644 --- a/solution/1300-1399/1311.Get Watched Videos by Your Friends/README_EN.md +++ b/solution/1300-1399/1311.Get Watched Videos by Your Friends/README_EN.md @@ -53,12 +53,10 @@ You have id = 0 (green color in the figure) and the only friend of your friends ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def watchedVideosByFriends( @@ -90,8 +88,6 @@ class Solution: return [v[0] for v in videos] ``` -### **Java** - ```java class Solution { public List watchedVideosByFriends( @@ -137,10 +133,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README.md b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README.md index 1474640cbb9c7..a73650be1864d 100644 --- a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README.md +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j)$,表示将字符串 $s[i..j]$ 变成回文串所需要的最少操作次数。那么答案就是 $dfs(0, n - 1)$。 @@ -67,35 +65,8 @@ 时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 为字符串 $s$ 的长度。 -**方法二:动态规划(区间 DP)** - -我们定义 $f[i][j]$ 表示将字符串 $s[i..j]$ 变成回文串所需要的最少操作次数。初始时 $f[i][j]=0$,答案即为 $f[0][n-1]$。 - -对于 $f[i][j]$,如果 $s[i]=s[j]$,那么我们只需要将 $s[i+1..j-1]$ 变成回文串,因此 $f[i][j]=f[i+1][j-1]$。否则,我们可以在 $s[i]$ 的左侧或者 $s[j]$ 的右侧插入一个与另一侧相同的字符,那么 $f[i][j]=\min(f[i+1][j],f[i][j-1])+1$。 - -综上,我们可以得到状态转移方程: - -$$ -f[i][j]=\left\{\begin{array}{ll}f[i+1][j-1], & s[i]=s[j]\\ \min(f[i+1][j],f[i][j-1])+1, & s[i]\neq s[j]\end{array}\right. -$$ - -在枚举时,我们可以有两种枚举的方式: - -1. 从大到小枚举 $i$,从小到大枚举 $j$,这样可以保证在计算状态 $f[i][j]$ 时,状态 $f[i+1][j-1]$ 和 $f[i][j-1]$ 都已经计算过了; -1. 从小到大枚举区间长度 $k$,然后枚举区间的左端点 $i$,那么可以得到右端点 $j=i+k-1$,这样也可以保证在计算较大区间 $f[i][j]$ 时,较小区间 $f[i+1][j]$ 和 $f[i][j-1]$ 都已经计算过了。 - -时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 为字符串 $s$ 的长度。 - -相似题目: - -- [1039. 多边形三角剖分的最低得分](/solution/1000-1099/1039.Minimum%20Score%20Triangulation%20of%20Polygon/README.md) - -### **Python3** - - - ```python class Solution: def minInsertions(self, s: str) -> int: @@ -110,39 +81,6 @@ class Solution: return dfs(0, len(s) - 1) ``` -```python -class Solution: - def minInsertions(self, s: str) -> int: - n = len(s) - f = [[0] * n for _ in range(n)] - for i in range(n - 2, -1, -1): - for j in range(i + 1, n): - if s[i] == s[j]: - f[i][j] = f[i + 1][j - 1] - else: - f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1 - return f[0][-1] -``` - -```python -class Solution: - def minInsertions(self, s: str) -> int: - n = len(s) - f = [[0] * n for _ in range(n)] - for k in range(2, n + 1): - for i in range(n - k + 1): - j = i + k - 1 - if s[i] == s[j]: - f[i][j] = f[i + 1][j - 1] - else: - f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1 - return f[0][n - 1] -``` - -### **Java** - - - ```java class Solution { private Integer[][] f; @@ -173,47 +111,6 @@ class Solution { } ``` -```java -class Solution { - public int minInsertions(String s) { - int n = s.length(); - int[][] f = new int[n][n]; - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - if (s.charAt(i) == s.charAt(j)) { - f[i][j] = f[i + 1][j - 1]; - } else { - f[i][j] = Math.min(f[i + 1][j], f[i][j - 1]) + 1; - } - } - } - return f[0][n - 1]; - } -} -``` - -```java -class Solution { - public int minInsertions(String s) { - int n = s.length(); - int[][] f = new int[n][n]; - for (int k = 2; k <= n; ++k) { - for (int i = 0; i + k - 1 < n; ++i) { - int j = i + k - 1; - if (s.charAt(i) == s.charAt(j)) { - f[i][j] = f[i + 1][j - 1]; - } else { - f[i][j] = Math.min(f[i + 1][j], f[i][j - 1]) + 1; - } - } - } - return f[0][n - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -241,51 +138,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minInsertions(string s) { - int n = s.size(); - int f[n][n]; - memset(f, 0, sizeof(f)); - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - if (s[i] == s[j]) { - f[i][j] = f[i + 1][j - 1]; - } else { - f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1; - } - } - } - return f[0][n - 1]; - } -}; -``` - -```cpp -class Solution { -public: - int minInsertions(string s) { - int n = s.size(); - int f[n][n]; - memset(f, 0, sizeof(f)); - for (int k = 2; k <= n; ++k) { - for (int i = 0; i + k - 1 < n; ++i) { - int j = i + k - 1; - if (s[i] == s[j]) { - f[i][j] = f[i + 1][j - 1]; - } else { - f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1; - } - } - } - return f[0][n - 1]; - } -}; -``` - -### **Go** - ```go func minInsertions(s string) int { n := len(s) @@ -317,6 +169,87 @@ func minInsertions(s string) int { } ``` + + +### 方法二:动态规划(区间 DP) + +我们定义 $f[i][j]$ 表示将字符串 $s[i..j]$ 变成回文串所需要的最少操作次数。初始时 $f[i][j]=0$,答案即为 $f[0][n-1]$。 + +对于 $f[i][j]$,如果 $s[i]=s[j]$,那么我们只需要将 $s[i+1..j-1]$ 变成回文串,因此 $f[i][j]=f[i+1][j-1]$。否则,我们可以在 $s[i]$ 的左侧或者 $s[j]$ 的右侧插入一个与另一侧相同的字符,那么 $f[i][j]=\min(f[i+1][j],f[i][j-1])+1$。 + +综上,我们可以得到状态转移方程: + +$$ +f[i][j]=\left\{\begin{array}{ll}f[i+1][j-1], & s[i]=s[j]\\ \min(f[i+1][j],f[i][j-1])+1, & s[i]\neq s[j]\end{array}\right. +$$ + +在枚举时,我们可以有两种枚举的方式: + +1. 从大到小枚举 $i$,从小到大枚举 $j$,这样可以保证在计算状态 $f[i][j]$ 时,状态 $f[i+1][j-1]$ 和 $f[i][j-1]$ 都已经计算过了; +1. 从小到大枚举区间长度 $k$,然后枚举区间的左端点 $i$,那么可以得到右端点 $j=i+k-1$,这样也可以保证在计算较大区间 $f[i][j]$ 时,较小区间 $f[i+1][j]$ 和 $f[i][j-1]$ 都已经计算过了。 + +时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 为字符串 $s$ 的长度。 + +相似题目: + +- [1039. 多边形三角剖分的最低得分](/solution/1000-1099/1039.Minimum%20Score%20Triangulation%20of%20Polygon/README.md) + + + +```python +class Solution: + def minInsertions(self, s: str) -> int: + n = len(s) + f = [[0] * n for _ in range(n)] + for i in range(n - 2, -1, -1): + for j in range(i + 1, n): + if s[i] == s[j]: + f[i][j] = f[i + 1][j - 1] + else: + f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1 + return f[0][-1] +``` + +```java +class Solution { + public int minInsertions(String s) { + int n = s.length(); + int[][] f = new int[n][n]; + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + if (s.charAt(i) == s.charAt(j)) { + f[i][j] = f[i + 1][j - 1]; + } else { + f[i][j] = Math.min(f[i + 1][j], f[i][j - 1]) + 1; + } + } + } + return f[0][n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int minInsertions(string s) { + int n = s.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + if (s[i] == s[j]) { + f[i][j] = f[i + 1][j - 1]; + } else { + f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1; + } + } + } + return f[0][n - 1]; + } +}; +``` + ```go func minInsertions(s string) int { n := len(s) @@ -337,6 +270,69 @@ func minInsertions(s string) int { } ``` + + +### 方法三 + + + +```python +class Solution: + def minInsertions(self, s: str) -> int: + n = len(s) + f = [[0] * n for _ in range(n)] + for k in range(2, n + 1): + for i in range(n - k + 1): + j = i + k - 1 + if s[i] == s[j]: + f[i][j] = f[i + 1][j - 1] + else: + f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1 + return f[0][n - 1] +``` + +```java +class Solution { + public int minInsertions(String s) { + int n = s.length(); + int[][] f = new int[n][n]; + for (int k = 2; k <= n; ++k) { + for (int i = 0; i + k - 1 < n; ++i) { + int j = i + k - 1; + if (s.charAt(i) == s.charAt(j)) { + f[i][j] = f[i + 1][j - 1]; + } else { + f[i][j] = Math.min(f[i + 1][j], f[i][j - 1]) + 1; + } + } + } + return f[0][n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int minInsertions(string s) { + int n = s.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int k = 2; k <= n; ++k) { + for (int i = 0; i + k - 1 < n; ++i) { + int j = i + k - 1; + if (s[i] == s[j]) { + f[i][j] = f[i + 1][j - 1]; + } else { + f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1; + } + } + } + return f[0][n - 1]; + } +}; +``` + ```go func minInsertions(s string) int { n := len(s) @@ -358,10 +354,6 @@ func minInsertions(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README_EN.md b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README_EN.md index b8649da36c34f..1c59d846652e8 100644 --- a/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README_EN.md +++ b/solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,37 +63,6 @@ class Solution: return dfs(0, len(s) - 1) ``` -```python -class Solution: - def minInsertions(self, s: str) -> int: - n = len(s) - f = [[0] * n for _ in range(n)] - for i in range(n - 2, -1, -1): - for j in range(i + 1, n): - if s[i] == s[j]: - f[i][j] = f[i + 1][j - 1] - else: - f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1 - return f[0][-1] -``` - -```python -class Solution: - def minInsertions(self, s: str) -> int: - n = len(s) - f = [[0] * n for _ in range(n)] - for k in range(2, n + 1): - for i in range(n - k + 1): - j = i + k - 1 - if s[i] == s[j]: - f[i][j] = f[i + 1][j - 1] - else: - f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1 - return f[0][n - 1] -``` - -### **Java** - ```java class Solution { private Integer[][] f; @@ -124,47 +93,6 @@ class Solution { } ``` -```java -class Solution { - public int minInsertions(String s) { - int n = s.length(); - int[][] f = new int[n][n]; - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - if (s.charAt(i) == s.charAt(j)) { - f[i][j] = f[i + 1][j - 1]; - } else { - f[i][j] = Math.min(f[i + 1][j], f[i][j - 1]) + 1; - } - } - } - return f[0][n - 1]; - } -} -``` - -```java -class Solution { - public int minInsertions(String s) { - int n = s.length(); - int[][] f = new int[n][n]; - for (int k = 2; k <= n; ++k) { - for (int i = 0; i + k - 1 < n; ++i) { - int j = i + k - 1; - if (s.charAt(i) == s.charAt(j)) { - f[i][j] = f[i + 1][j - 1]; - } else { - f[i][j] = Math.min(f[i + 1][j], f[i][j - 1]) + 1; - } - } - } - return f[0][n - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -192,51 +120,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minInsertions(string s) { - int n = s.size(); - int f[n][n]; - memset(f, 0, sizeof(f)); - for (int i = n - 2; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - if (s[i] == s[j]) { - f[i][j] = f[i + 1][j - 1]; - } else { - f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1; - } - } - } - return f[0][n - 1]; - } -}; -``` - -```cpp -class Solution { -public: - int minInsertions(string s) { - int n = s.size(); - int f[n][n]; - memset(f, 0, sizeof(f)); - for (int k = 2; k <= n; ++k) { - for (int i = 0; i + k - 1 < n; ++i) { - int j = i + k - 1; - if (s[i] == s[j]) { - f[i][j] = f[i + 1][j - 1]; - } else { - f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1; - } - } - } - return f[0][n - 1]; - } -}; -``` - -### **Go** - ```go func minInsertions(s string) int { n := len(s) @@ -268,6 +151,66 @@ func minInsertions(s string) int { } ``` + + +### Solution 2 + + + +```python +class Solution: + def minInsertions(self, s: str) -> int: + n = len(s) + f = [[0] * n for _ in range(n)] + for i in range(n - 2, -1, -1): + for j in range(i + 1, n): + if s[i] == s[j]: + f[i][j] = f[i + 1][j - 1] + else: + f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1 + return f[0][-1] +``` + +```java +class Solution { + public int minInsertions(String s) { + int n = s.length(); + int[][] f = new int[n][n]; + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + if (s.charAt(i) == s.charAt(j)) { + f[i][j] = f[i + 1][j - 1]; + } else { + f[i][j] = Math.min(f[i + 1][j], f[i][j - 1]) + 1; + } + } + } + return f[0][n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int minInsertions(string s) { + int n = s.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int i = n - 2; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + if (s[i] == s[j]) { + f[i][j] = f[i + 1][j - 1]; + } else { + f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1; + } + } + } + return f[0][n - 1]; + } +}; +``` + ```go func minInsertions(s string) int { n := len(s) @@ -288,6 +231,69 @@ func minInsertions(s string) int { } ``` + + +### Solution 3 + + + +```python +class Solution: + def minInsertions(self, s: str) -> int: + n = len(s) + f = [[0] * n for _ in range(n)] + for k in range(2, n + 1): + for i in range(n - k + 1): + j = i + k - 1 + if s[i] == s[j]: + f[i][j] = f[i + 1][j - 1] + else: + f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1 + return f[0][n - 1] +``` + +```java +class Solution { + public int minInsertions(String s) { + int n = s.length(); + int[][] f = new int[n][n]; + for (int k = 2; k <= n; ++k) { + for (int i = 0; i + k - 1 < n; ++i) { + int j = i + k - 1; + if (s.charAt(i) == s.charAt(j)) { + f[i][j] = f[i + 1][j - 1]; + } else { + f[i][j] = Math.min(f[i + 1][j], f[i][j - 1]) + 1; + } + } + } + return f[0][n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int minInsertions(string s) { + int n = s.size(); + int f[n][n]; + memset(f, 0, sizeof(f)); + for (int k = 2; k <= n; ++k) { + for (int i = 0; i + k - 1 < n; ++i) { + int j = i + k - 1; + if (s[i] == s[j]) { + f[i][j] = f[i + 1][j - 1]; + } else { + f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1; + } + } + } + return f[0][n - 1]; + } +}; +``` + ```go func minInsertions(s string) int { n := len(s) @@ -309,10 +315,6 @@ func minInsertions(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1313.Decompress Run-Length Encoded List/README.md b/solution/1300-1399/1313.Decompress Run-Length Encoded List/README.md index 8fbc374d92063..b1d892712f8f8 100644 --- a/solution/1300-1399/1313.Decompress Run-Length Encoded List/README.md +++ b/solution/1300-1399/1313.Decompress Run-Length Encoded List/README.md @@ -42,14 +42,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def decompressRLElist(self, nums: List[int]) -> List[int]: @@ -59,10 +55,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int[] decompressRLElist(int[] nums) { @@ -81,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +88,6 @@ public: }; ``` -### **Go** - ```go func decompressRLElist(nums []int) []int { var res []int @@ -112,8 +100,6 @@ func decompressRLElist(nums []int) []int { } ``` -### **TypeScript** - ```ts function decompressRLElist(nums: number[]): number[] { let n = nums.length >> 1; @@ -127,8 +113,6 @@ function decompressRLElist(nums: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn decompress_rl_elist(nums: Vec) -> Vec { @@ -144,8 +128,6 @@ impl Solution { } ``` -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -166,10 +148,6 @@ int* decompressRLElist(int* nums, int numsSize, int* returnSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1313.Decompress Run-Length Encoded List/README_EN.md b/solution/1300-1399/1313.Decompress Run-Length Encoded List/README_EN.md index 260b7a8a4e06b..beeac2191a0bb 100644 --- a/solution/1300-1399/1313.Decompress Run-Length Encoded List/README_EN.md +++ b/solution/1300-1399/1313.Decompress Run-Length Encoded List/README_EN.md @@ -39,9 +39,9 @@ At the end the concatenation [2] + [4,4,4] is [2,4,4,4]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public int[] decompressRLElist(int[] nums) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,8 +85,6 @@ public: }; ``` -### **Go** - ```go func decompressRLElist(nums []int) []int { var res []int @@ -103,8 +97,6 @@ func decompressRLElist(nums []int) []int { } ``` -### **TypeScript** - ```ts function decompressRLElist(nums: number[]): number[] { let n = nums.length >> 1; @@ -118,8 +110,6 @@ function decompressRLElist(nums: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn decompress_rl_elist(nums: Vec) -> Vec { @@ -135,8 +125,6 @@ impl Solution { } ``` -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -157,10 +145,6 @@ int* decompressRLElist(int* nums, int numsSize, int* returnSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1314.Matrix Block Sum/README.md b/solution/1300-1399/1314.Matrix Block Sum/README.md index 21e46e230c24e..81a29ca4dd515 100644 --- a/solution/1300-1399/1314.Matrix Block Sum/README.md +++ b/solution/1300-1399/1314.Matrix Block Sum/README.md @@ -43,16 +43,10 @@ ## 解法 - - -动态规划-二维前缀和。 +### 方法一 -### **Python3** - - - ```python class Solution: def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[][] pre; @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +140,6 @@ public: }; ``` -### **Go** - ```go func matrixBlockSum(mat [][]int, k int) [][]int { m, n := len(mat), len(mat[0]) @@ -184,10 +170,6 @@ func matrixBlockSum(mat [][]int, k int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1314.Matrix Block Sum/README_EN.md b/solution/1300-1399/1314.Matrix Block Sum/README_EN.md index d8ffa6593fb0d..0e961e2f2a8e8 100644 --- a/solution/1300-1399/1314.Matrix Block Sum/README_EN.md +++ b/solution/1300-1399/1314.Matrix Block Sum/README_EN.md @@ -39,12 +39,10 @@ ## Solutions -Dynamic programming - 2D preSum. +### Solution 1 -### **Python3** - ```python class Solution: def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]: @@ -76,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[][] pre; @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go func matrixBlockSum(mat [][]int, k int) [][]int { m, n := len(mat), len(mat[0]) @@ -174,10 +166,6 @@ func matrixBlockSum(mat [][]int, k int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1315.Sum of Nodes with Even-Valued Grandparent/README.md b/solution/1300-1399/1315.Sum of Nodes with Even-Valued Grandparent/README.md index 06fb08fdf89a9..bef0b5c75a4e4 100644 --- a/solution/1300-1399/1315.Sum of Nodes with Even-Valued Grandparent/README.md +++ b/solution/1300-1399/1315.Sum of Nodes with Even-Valued Grandparent/README.md @@ -36,16 +36,10 @@ ## 解法 - - -深度优先搜索。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -73,10 +67,6 @@ class Solution: return self.res ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -196,10 +182,6 @@ func dfs(g, p *TreeNode) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1315.Sum of Nodes with Even-Valued Grandparent/README_EN.md b/solution/1300-1399/1315.Sum of Nodes with Even-Valued Grandparent/README_EN.md index e2aded152830f..18a91e9898499 100644 --- a/solution/1300-1399/1315.Sum of Nodes with Even-Valued Grandparent/README_EN.md +++ b/solution/1300-1399/1315.Sum of Nodes with Even-Valued Grandparent/README_EN.md @@ -34,12 +34,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -67,8 +65,6 @@ class Solution: return self.res ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -150,8 +144,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -188,10 +180,6 @@ func dfs(g, p *TreeNode) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1316.Distinct Echo Substrings/README.md b/solution/1300-1399/1316.Distinct Echo Substrings/README.md index 963d15df077b7..301d2a9250180 100644 --- a/solution/1300-1399/1316.Distinct Echo Substrings/README.md +++ b/solution/1300-1399/1316.Distinct Echo Substrings/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:字符串哈希** +### 方法一:字符串哈希 **字符串哈希**是把一个任意长度的字符串映射成一个非负整数,并且其冲突的概率几乎为 0。字符串哈希用于计算字符串哈希值,快速判断两个字符串是否相等。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def distinctEchoSubstrings(self, text: str) -> int: @@ -85,10 +79,6 @@ class Solution: return len(vis) ``` -### **Java** - - - ```java class Solution { private long[] h; @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef unsigned long long ull; @@ -161,7 +149,34 @@ public: }; ``` -### **Rust** +```go +func distinctEchoSubstrings(text string) int { + n := len(text) + base := 131 + h := make([]int, n+10) + p := make([]int, n+10) + p[0] = 1 + for i, c := range text { + t := int(c-'a') + 1 + p[i+1] = p[i] * base + h[i+1] = h[i]*base + t + } + get := func(l, r int) int { + return h[r] - h[l-1]*p[r-l+1] + } + vis := map[int]bool{} + for i := 0; i < n-1; i++ { + for j := i + 1; j < n; j += 2 { + k := (i + j) >> 1 + a, b := get(i+1, k+1), get(k+2, j+1) + if a == b { + vis[a] = true + } + } + } + return len(vis) +} +``` ```rust use std::collections::HashSet; @@ -208,41 +223,6 @@ impl Solution { } ``` -### **Go** - -```go -func distinctEchoSubstrings(text string) int { - n := len(text) - base := 131 - h := make([]int, n+10) - p := make([]int, n+10) - p[0] = 1 - for i, c := range text { - t := int(c-'a') + 1 - p[i+1] = p[i] * base - h[i+1] = h[i]*base + t - } - get := func(l, r int) int { - return h[r] - h[l-1]*p[r-l+1] - } - vis := map[int]bool{} - for i := 0; i < n-1; i++ { - for j := i + 1; j < n; j += 2 { - k := (i + j) >> 1 - a, b := get(i+1, k+1), get(k+2, j+1) - if a == b { - vis[a] = true - } - } - } - return len(vis) -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1316.Distinct Echo Substrings/README_EN.md b/solution/1300-1399/1316.Distinct Echo Substrings/README_EN.md index c5a2bfb79d3c6..04867a6345ddd 100644 --- a/solution/1300-1399/1316.Distinct Echo Substrings/README_EN.md +++ b/solution/1300-1399/1316.Distinct Echo Substrings/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return len(vis) ``` -### **Java** - ```java class Solution { private long[] h; @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef unsigned long long ull; @@ -137,7 +133,34 @@ public: }; ``` -### **Rust** +```go +func distinctEchoSubstrings(text string) int { + n := len(text) + base := 131 + h := make([]int, n+10) + p := make([]int, n+10) + p[0] = 1 + for i, c := range text { + t := int(c-'a') + 1 + p[i+1] = p[i] * base + h[i+1] = h[i]*base + t + } + get := func(l, r int) int { + return h[r] - h[l-1]*p[r-l+1] + } + vis := map[int]bool{} + for i := 0; i < n-1; i++ { + for j := i + 1; j < n; j += 2 { + k := (i + j) >> 1 + a, b := get(i+1, k+1), get(k+2, j+1) + if a == b { + vis[a] = true + } + } + } + return len(vis) +} +``` ```rust use std::collections::HashSet; @@ -184,41 +207,6 @@ impl Solution { } ``` -### **Go** - -```go -func distinctEchoSubstrings(text string) int { - n := len(text) - base := 131 - h := make([]int, n+10) - p := make([]int, n+10) - p[0] = 1 - for i, c := range text { - t := int(c-'a') + 1 - p[i+1] = p[i] * base - h[i+1] = h[i]*base + t - } - get := func(l, r int) int { - return h[r] - h[l-1]*p[r-l+1] - } - vis := map[int]bool{} - for i := 0; i < n-1; i++ { - for j := i + 1; j < n; j += 2 { - k := (i + j) >> 1 - a, b := get(i+1, k+1), get(k+2, j+1) - if a == b { - vis[a] = true - } - } - } - return len(vis) -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/README.md b/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/README.md index bee69a34f8977..c282fe6277b16 100644 --- a/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/README.md +++ b/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:直接枚举** +### 方法一:直接枚举 从 $1$ 开始枚举 $a$,判断 $a$ 和 $n - a$ 是否满足条件,如果满足则返回。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def getNoZeroIntegers(self, n: int) -> List[int]: @@ -85,6 +79,50 @@ class Solution: return [a, b] ``` +```java +class Solution { + public int[] getNoZeroIntegers(int n) { + for (int a = 1;; ++a) { + int b = n - a; + if (!(a + "" + b).contains("0")) { + return new int[] {a, b}; + } + } + } +} +``` + +```cpp +class Solution { +public: + vector getNoZeroIntegers(int n) { + for (int a = 1;; ++a) { + int b = n - a; + if ((to_string(a) + to_string(b)).find('0') == -1) { + return {a, b}; + } + } + } +}; +``` + +```go +func getNoZeroIntegers(n int) []int { + for a := 1; ; a++ { + b := n - a + if !strings.Contains(strconv.Itoa(a)+strconv.Itoa(b), "0") { + return []int{a, b} + } + } +} +``` + + + +### 方法二 + + + ```python class Solution: def getNoZeroIntegers(self, n: int) -> List[int]: @@ -101,23 +139,6 @@ class Solution: return [a, b] ``` -### **Java** - - - -```java -class Solution { - public int[] getNoZeroIntegers(int n) { - for (int a = 1;; ++a) { - int b = n - a; - if (!(a + "" + b).contains("0")) { - return new int[] {a, b}; - } - } - } -} -``` - ```java class Solution { public int[] getNoZeroIntegers(int n) { @@ -140,22 +161,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector getNoZeroIntegers(int n) { - for (int a = 1;; ++a) { - int b = n - a; - if ((to_string(a) + to_string(b)).find('0') == -1) { - return {a, b}; - } - } - } -}; -``` - ```cpp class Solution { public: @@ -178,19 +183,6 @@ public: }; ``` -### **Go** - -```go -func getNoZeroIntegers(n int) []int { - for a := 1; ; a++ { - b := n - a - if !strings.Contains(strconv.Itoa(a)+strconv.Itoa(b), "0") { - return []int{a, b} - } - } -} -``` - ```go func getNoZeroIntegers(n int) []int { f := func(x int) bool { @@ -210,10 +202,6 @@ func getNoZeroIntegers(n int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/README_EN.md b/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/README_EN.md index 55660930dcdb5..16e3b0a094db2 100644 --- a/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/README_EN.md +++ b/solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/README_EN.md @@ -44,9 +44,9 @@ Note that there are other valid answers as [8, 3] that can be accepted. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,6 +57,50 @@ class Solution: return [a, b] ``` +```java +class Solution { + public int[] getNoZeroIntegers(int n) { + for (int a = 1;; ++a) { + int b = n - a; + if (!(a + "" + b).contains("0")) { + return new int[] {a, b}; + } + } + } +} +``` + +```cpp +class Solution { +public: + vector getNoZeroIntegers(int n) { + for (int a = 1;; ++a) { + int b = n - a; + if ((to_string(a) + to_string(b)).find('0') == -1) { + return {a, b}; + } + } + } +}; +``` + +```go +func getNoZeroIntegers(n int) []int { + for a := 1; ; a++ { + b := n - a + if !strings.Contains(strconv.Itoa(a)+strconv.Itoa(b), "0") { + return []int{a, b} + } + } +} +``` + + + +### Solution 2 + + + ```python class Solution: def getNoZeroIntegers(self, n: int) -> List[int]: @@ -73,21 +117,6 @@ class Solution: return [a, b] ``` -### **Java** - -```java -class Solution { - public int[] getNoZeroIntegers(int n) { - for (int a = 1;; ++a) { - int b = n - a; - if (!(a + "" + b).contains("0")) { - return new int[] {a, b}; - } - } - } -} -``` - ```java class Solution { public int[] getNoZeroIntegers(int n) { @@ -110,22 +139,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector getNoZeroIntegers(int n) { - for (int a = 1;; ++a) { - int b = n - a; - if ((to_string(a) + to_string(b)).find('0') == -1) { - return {a, b}; - } - } - } -}; -``` - ```cpp class Solution { public: @@ -148,19 +161,6 @@ public: }; ``` -### **Go** - -```go -func getNoZeroIntegers(n int) []int { - for a := 1; ; a++ { - b := n - a - if !strings.Contains(strconv.Itoa(a)+strconv.Itoa(b), "0") { - return []int{a, b} - } - } -} -``` - ```go func getNoZeroIntegers(n int) []int { f := func(x int) bool { @@ -180,10 +180,6 @@ func getNoZeroIntegers(n int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README.md b/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README.md index cbe6ea15a812d..b02b307d86c22 100644 --- a/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README.md +++ b/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 我们可以枚举 $a$, $b$, $c$ 的二进制表示的每一位,分别记为 $x$, $y$, $z$。如果 $x$ 和 $y$ 的按位或运算结果与 $z$ 不同,此时我们判断 $x$ 和 $y$ 是否都是 $1$,如果是,则需要翻转两次,否则只需要翻转一次。我们将所有需要翻转的次数累加即可。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def minFlips(self, a: int, b: int, c: int) -> int: @@ -71,10 +65,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minFlips(int a, int b, int c) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +96,6 @@ public: }; ``` -### **Go** - ```go func minFlips(a int, b int, c int) (ans int) { for i := 0; i < 30; i++ { @@ -126,10 +112,6 @@ func minFlips(a int, b int, c int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md b/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md index f5a85c727a306..9488f48ae9651 100644 --- a/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md +++ b/solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/README_EN.md @@ -42,9 +42,9 @@ Flip operation consists of change any single bit ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minFlips(int a, int b, int c) { @@ -74,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -92,8 +88,6 @@ public: }; ``` -### **Go** - ```go func minFlips(a int, b int, c int) (ans int) { for i := 0; i < 30; i++ { @@ -110,10 +104,6 @@ func minFlips(a int, b int, c int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1319.Number of Operations to Make Network Connected/README.md b/solution/1300-1399/1319.Number of Operations to Make Network Connected/README.md index c9d2f0f70c1e7..fef797bf88c57 100644 --- a/solution/1300-1399/1319.Number of Operations to Make Network Connected/README.md +++ b/solution/1300-1399/1319.Number of Operations to Make Network Connected/README.md @@ -60,86 +60,10 @@ ## 解法 - - -并查集。 - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` - -对于本题,先遍历所有的边: - -- 如果边的两个节点已经属于同个集合,说明两个节点已经相连,不必再将此边加入到集合中,累加 cnt; -- 否则将边加入集合中。 - -最后判断集合的数量 total 与 cnt 的大小关系。 +### 方法一 -### **Python3** - - - ```python class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: @@ -159,10 +83,6 @@ class Solution: return -1 if size - 1 > cnt else size - 1 ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -195,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -225,8 +143,6 @@ public: }; ``` -### **Go** - ```go func makeConnected(n int, connections [][]int) int { p := make([]int, n) @@ -257,10 +173,6 @@ func makeConnected(n int, connections [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1319.Number of Operations to Make Network Connected/README_EN.md b/solution/1300-1399/1319.Number of Operations to Make Network Connected/README_EN.md index 5abad9fd792fc..4a36b1b1dd2ef 100644 --- a/solution/1300-1399/1319.Number of Operations to Make Network Connected/README_EN.md +++ b/solution/1300-1399/1319.Number of Operations to Make Network Connected/README_EN.md @@ -49,12 +49,10 @@ ## Solutions -Union find. +### Solution 1 -### **Python3** - ```python class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: @@ -63,19 +61,17 @@ class Solution: p[x] = find(p[x]) return p[x] - cnt = 0 + cnt, size = 0, n p = list(range(n)) for a, b in connections: if find(a) == find(b): cnt += 1 else: p[find(a)] = find(b) - n -= 1 - return -1 if n - 1 > cnt else n - 1 + size -= 1 + return -1 if size - 1 > cnt else size - 1 ``` -### **Java** - ```java class Solution { private int[] p; @@ -108,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +132,6 @@ public: }; ``` -### **Go** - ```go func makeConnected(n int, connections [][]int) int { p := make([]int, n) @@ -170,10 +162,6 @@ func makeConnected(n int, connections [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/README.md b/solution/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/README.md index 874a10ee71254..12526d47f48cf 100644 --- a/solution/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/README.md +++ b/solution/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j][k]$ 表示输入完 $word[i]$,且手指 $1$ 位于位置 $j$,手指 $2$ 位于位置 $k$ 时,最小的移动距离。这里的位置 $j$ 和 $k$ 表示的是字母对应的数字,取值范围为 $[0,..25]$。初始时 $f[i][j][k]=\infty$。 @@ -87,10 +85,6 @@ -### **Python3** - - - ```python class Solution: def minimumDistance(self, word: str) -> int: @@ -120,10 +114,6 @@ class Solution: return int(min(a, b)) ``` -### **Java** - - - ```java class Solution { public int minimumDistance(String word) { @@ -171,8 +161,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -216,8 +204,6 @@ public: }; ``` -### **Go** - ```go func minimumDistance(word string) int { n := len(word) @@ -270,10 +256,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/README_EN.md b/solution/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/README_EN.md index a17b4889c3707..d8bbdbe774b50 100644 --- a/solution/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/README_EN.md +++ b/solution/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/README_EN.md @@ -55,9 +55,9 @@ Total distance = 6 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -88,8 +88,6 @@ class Solution: return int(min(a, b)) ``` -### **Java** - ```java class Solution { public int minimumDistance(String word) { @@ -137,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +178,6 @@ public: }; ``` -### **Go** - ```go func minimumDistance(word string) int { n := len(word) @@ -236,10 +230,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1321.Restaurant Growth/README.md b/solution/1300-1399/1321.Restaurant Growth/README.md index 174d70118f3b1..843ef41fb7c0d 100644 --- a/solution/1300-1399/1321.Restaurant Growth/README.md +++ b/solution/1300-1399/1321.Restaurant Growth/README.md @@ -72,12 +72,10 @@ Customer 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -104,6 +102,12 @@ FROM t WHERE rk > 6; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below SELECT @@ -119,3 +123,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1300-1399/1321.Restaurant Growth/README_EN.md b/solution/1300-1399/1321.Restaurant Growth/README_EN.md index ab91dc98bd5f9..3b04dc7558f68 100644 --- a/solution/1300-1399/1321.Restaurant Growth/README_EN.md +++ b/solution/1300-1399/1321.Restaurant Growth/README_EN.md @@ -70,9 +70,9 @@ Customer table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -100,6 +100,12 @@ FROM t WHERE rk > 6; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below SELECT @@ -115,3 +121,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1300-1399/1322.Ads Performance/README.md b/solution/1300-1399/1322.Ads Performance/README.md index f4653b28a11cd..740c6cdf8a856 100644 --- a/solution/1300-1399/1322.Ads Performance/README.md +++ b/solution/1300-1399/1322.Ads Performance/README.md @@ -75,12 +75,10 @@ Ads 表: ## 解法 - +### 方法一 -### **SQL** - ```sql SELECT ad_id, @@ -91,3 +89,5 @@ ORDER BY 2 DESC, 1; ``` + + diff --git a/solution/1300-1399/1322.Ads Performance/README_EN.md b/solution/1300-1399/1322.Ads Performance/README_EN.md index 739deba967f6b..eebddc838a22e 100644 --- a/solution/1300-1399/1322.Ads Performance/README_EN.md +++ b/solution/1300-1399/1322.Ads Performance/README_EN.md @@ -70,9 +70,9 @@ Note that we do not care about Ignored Ads. ## Solutions - +### Solution 1 -### **SQL** + ```sql SELECT @@ -84,3 +84,5 @@ ORDER BY 2 DESC, 1; ``` + + diff --git a/solution/1300-1399/1323.Maximum 69 Number/README.md b/solution/1300-1399/1323.Maximum 69 Number/README.md index 2111ad4a175ac..5bbddaa3d3351 100644 --- a/solution/1300-1399/1323.Maximum 69 Number/README.md +++ b/solution/1300-1399/1323.Maximum 69 Number/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们将数组转换为字符串,然后从左到右遍历字符串,找到第一个出现的 $6$,将其替换为 $9$,然后返回转换后的字符串对应的整数即可。 @@ -59,20 +57,12 @@ -### **Python3** - - - ```python class Solution: def maximum69Number(self, num: int) -> int: return int(str(num).replace("6", "9", 1)) ``` -### **Java** - - - ```java class Solution { public int maximum69Number(int num) { @@ -81,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +87,6 @@ public: }; ``` -### **Go** - ```go func maximum69Number(num int) int { s := strconv.Itoa(num) @@ -116,16 +102,12 @@ func maximum69Number(num int) int { } ``` -### **TypeScript** - ```ts function maximum69Number(num: number): number { return Number((num + '').replace('6', '9')); } ``` -### **Rust** - ```rust impl Solution { pub fn maximum69_number(num: i32) -> i32 { @@ -134,26 +116,6 @@ impl Solution { } ``` -### **C** - -```c -int maximum69Number(int num) { - int n = 0; - int i = 0; - int t = num; - while (t) { - n++; - if (t % 10 == 6) { - i = n; - } - t /= 10; - } - return num + 3 * pow(10, i - 1); -} -``` - -### **PHP** - ```php class Solution { /** @@ -169,10 +131,22 @@ class Solution { } ``` -### **...** - -``` - +```c +int maximum69Number(int num) { + int n = 0; + int i = 0; + int t = num; + while (t) { + n++; + if (t % 10 == 6) { + i = n; + } + t /= 10; + } + return num + 3 * pow(10, i - 1); +} ``` + + diff --git a/solution/1300-1399/1323.Maximum 69 Number/README_EN.md b/solution/1300-1399/1323.Maximum 69 Number/README_EN.md index 6b5bea265c788..468af2981ad5f 100644 --- a/solution/1300-1399/1323.Maximum 69 Number/README_EN.md +++ b/solution/1300-1399/1323.Maximum 69 Number/README_EN.md @@ -48,9 +48,9 @@ The maximum number is 9969. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return int(str(num).replace("6", "9", 1)) ``` -### **Java** - ```java class Solution { public int maximum69Number(int num) { @@ -68,8 +66,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -86,8 +82,6 @@ public: }; ``` -### **Go** - ```go func maximum69Number(num int) int { s := strconv.Itoa(num) @@ -103,16 +97,12 @@ func maximum69Number(num int) int { } ``` -### **TypeScript** - ```ts function maximum69Number(num: number): number { return Number((num + '').replace('6', '9')); } ``` -### **Rust** - ```rust impl Solution { pub fn maximum69_number(num: i32) -> i32 { @@ -121,26 +111,6 @@ impl Solution { } ``` -### **C** - -```c -int maximum69Number(int num) { - int n = 0; - int i = 0; - int t = num; - while (t) { - n++; - if (t % 10 == 6) { - i = n; - } - t /= 10; - } - return num + 3 * pow(10, i - 1); -} -``` - -### **PHP** - ```php class Solution { /** @@ -156,10 +126,22 @@ class Solution { } ``` -### **...** - -``` - +```c +int maximum69Number(int num) { + int n = 0; + int i = 0; + int t = num; + while (t) { + n++; + if (t % 10 == 6) { + i = n; + } + t /= 10; + } + return num + 3 * pow(10, i - 1); +} ``` + + diff --git a/solution/1300-1399/1324.Print Words Vertically/README.md b/solution/1300-1399/1324.Print Words Vertically/README.md index 326623c246e3f..4168fb01465e4 100644 --- a/solution/1300-1399/1324.Print Words Vertically/README.md +++ b/solution/1300-1399/1324.Print Words Vertically/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们先将字符串 $s$ 按空格分割成单词数组 $words$,然后遍历单词数组,找出最长的单词长度 $n$。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def printVertically(self, s: str) -> List[str]: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List printVertically(String s) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func printVertically(s string) (ans []string) { words := strings.Split(s, " ") @@ -165,10 +151,6 @@ func printVertically(s string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1324.Print Words Vertically/README_EN.md b/solution/1300-1399/1324.Print Words Vertically/README_EN.md index 6410ef6cf71a6..b40bbdad60dda 100644 --- a/solution/1300-1399/1324.Print Words Vertically/README_EN.md +++ b/solution/1300-1399/1324.Print Words Vertically/README_EN.md @@ -49,9 +49,9 @@ Each word would be put on only one column and that in one column there will be o ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List printVertically(String s) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func printVertically(s string) (ans []string) { words := strings.Split(s, " ") @@ -150,10 +144,6 @@ func printVertically(s string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1325.Delete Leaves With a Given Value/README.md b/solution/1300-1399/1325.Delete Leaves With a Given Value/README.md index 6a3c4d9ba5877..5b58eac79919a 100644 --- a/solution/1300-1399/1325.Delete Leaves With a Given Value/README.md +++ b/solution/1300-1399/1325.Delete Leaves With a Given Value/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们先判断 $root$ 节点是否为空,若为空,则返回空。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -103,10 +97,6 @@ class Solution: return root ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -138,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -192,8 +178,6 @@ func removeLeafNodes(root *TreeNode, target int) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -222,10 +206,6 @@ function removeLeafNodes(root: TreeNode | null, target: number): TreeNode | null } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1325.Delete Leaves With a Given Value/README_EN.md b/solution/1300-1399/1325.Delete Leaves With a Given Value/README_EN.md index 0b3cdf0f74119..b2cf06ebf1c10 100644 --- a/solution/1300-1399/1325.Delete Leaves With a Given Value/README_EN.md +++ b/solution/1300-1399/1325.Delete Leaves With a Given Value/README_EN.md @@ -49,9 +49,9 @@ After removing, new nodes become leaf nodes with value (target = 2) (Picture in ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -73,8 +73,6 @@ class Solution: return root ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -136,8 +132,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -160,8 +154,6 @@ func removeLeafNodes(root *TreeNode, target int) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -190,10 +182,6 @@ function removeLeafNodes(root: TreeNode | null, target: number): TreeNode | null } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/README.md b/solution/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/README.md index a10f0fac4e631..f3e079556c7fe 100644 --- a/solution/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/README.md +++ b/solution/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们注意到,对于所有能覆盖某个左端点的水龙头,选择能覆盖最远右端点的那个水龙头是最优的。 @@ -84,10 +82,6 @@ -### **Python3** - - - ```python class Solution: def minTaps(self, n: int, ranges: List[int]) -> int: @@ -107,10 +101,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minTaps(int n, int[] ranges) { @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,47 +150,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn min_taps(n: i32, ranges: Vec) -> i32 { - let mut last = vec![0; (n + 1) as usize]; - let mut ans = 0; - let mut mx = 0; - let mut pre = 0; - - // Initialize the last vector - for (i, &r) in ranges.iter().enumerate() { - if (i as i32) - r >= 0 { - last[((i as i32) - r) as usize] = std::cmp::max( - last[((i as i32) - r) as usize], - (i as i32) + r - ); - } else { - last[0] = std::cmp::max(last[0], (i as i32) + r); - } - } - - for i in 0..n as usize { - mx = std::cmp::max(mx, last[i]); - if mx <= (i as i32) { - return -1; - } - if pre == (i as i32) { - ans += 1; - pre = mx; - } - } - - ans - } -} -``` - -### **Go** - ```go func minTaps(n int, ranges []int) (ans int) { last := make([]int, n+1) @@ -225,8 +172,6 @@ func minTaps(n int, ranges []int) (ans int) { } ``` -### **TypeScript** - ```ts function minTaps(n: number, ranges: number[]): number { const last = new Array(n + 1).fill(0); @@ -252,10 +197,43 @@ function minTaps(n: number, ranges: number[]): number { } ``` -### **...** +```rust +impl Solution { + #[allow(dead_code)] + pub fn min_taps(n: i32, ranges: Vec) -> i32 { + let mut last = vec![0; (n + 1) as usize]; + let mut ans = 0; + let mut mx = 0; + let mut pre = 0; -``` + // Initialize the last vector + for (i, &r) in ranges.iter().enumerate() { + if (i as i32) - r >= 0 { + last[((i as i32) - r) as usize] = std::cmp::max( + last[((i as i32) - r) as usize], + (i as i32) + r + ); + } else { + last[0] = std::cmp::max(last[0], (i as i32) + r); + } + } + + for i in 0..n as usize { + mx = std::cmp::max(mx, last[i]); + if mx <= (i as i32) { + return -1; + } + if pre == (i as i32) { + ans += 1; + pre = mx; + } + } + ans + } +} ``` + + diff --git a/solution/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/README_EN.md b/solution/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/README_EN.md index 60ac56747fcb0..acb871948af24 100644 --- a/solution/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/README_EN.md +++ b/solution/1300-1399/1326.Minimum Number of Taps to Open to Water a Garden/README_EN.md @@ -46,9 +46,9 @@ Opening Only the second tap will water the whole garden [0,5] ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minTaps(int n, int[] ranges) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,47 +118,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn min_taps(n: i32, ranges: Vec) -> i32 { - let mut last = vec![0; (n + 1) as usize]; - let mut ans = 0; - let mut mx = 0; - let mut pre = 0; - - // Initialize the last vector - for (i, &r) in ranges.iter().enumerate() { - if (i as i32) - r >= 0 { - last[((i as i32) - r) as usize] = std::cmp::max( - last[((i as i32) - r) as usize], - (i as i32) + r - ); - } else { - last[0] = std::cmp::max(last[0], (i as i32) + r); - } - } - - for i in 0..n as usize { - mx = std::cmp::max(mx, last[i]); - if mx <= (i as i32) { - return -1; - } - if pre == (i as i32) { - ans += 1; - pre = mx; - } - } - - ans - } -} -``` - -### **Go** - ```go func minTaps(n int, ranges []int) (ans int) { last := make([]int, n+1) @@ -185,8 +140,6 @@ func minTaps(n int, ranges []int) (ans int) { } ``` -### **TypeScript** - ```ts function minTaps(n: number, ranges: number[]): number { const last = new Array(n + 1).fill(0); @@ -212,10 +165,43 @@ function minTaps(n: number, ranges: number[]): number { } ``` -### **...** +```rust +impl Solution { + #[allow(dead_code)] + pub fn min_taps(n: i32, ranges: Vec) -> i32 { + let mut last = vec![0; (n + 1) as usize]; + let mut ans = 0; + let mut mx = 0; + let mut pre = 0; -``` + // Initialize the last vector + for (i, &r) in ranges.iter().enumerate() { + if (i as i32) - r >= 0 { + last[((i as i32) - r) as usize] = std::cmp::max( + last[((i as i32) - r) as usize], + (i as i32) + r + ); + } else { + last[0] = std::cmp::max(last[0], (i as i32) + r); + } + } + for i in 0..n as usize { + mx = std::cmp::max(mx, last[i]); + if mx <= (i as i32) { + return -1; + } + if pre == (i as i32) { + ans += 1; + pre = mx; + } + } + + ans + } +} ``` + + diff --git a/solution/1300-1399/1327.List the Products Ordered in a Period/README.md b/solution/1300-1399/1327.List the Products Ordered in a Period/README.md index f0bb2e1b1b2af..232e97140f49f 100644 --- a/solution/1300-1399/1327.List the Products Ordered in a Period/README.md +++ b/solution/1300-1399/1327.List the Products Ordered in a Period/README.md @@ -94,12 +94,10 @@ Orders 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT product_name, SUM(unit) AS unit @@ -112,3 +110,5 @@ HAVING unit >= 100; ``` + + diff --git a/solution/1300-1399/1327.List the Products Ordered in a Period/README_EN.md b/solution/1300-1399/1327.List the Products Ordered in a Period/README_EN.md index 819f3f5ea8e7f..186adc55bb05c 100644 --- a/solution/1300-1399/1327.List the Products Ordered in a Period/README_EN.md +++ b/solution/1300-1399/1327.List the Products Ordered in a Period/README_EN.md @@ -92,9 +92,9 @@ Products with product_id = 5 is ordered in February a total of (50 + 50) = 100. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -108,3 +108,5 @@ HAVING unit >= 100; ``` + + diff --git a/solution/1300-1399/1328.Break a Palindrome/README.md b/solution/1300-1399/1328.Break a Palindrome/README.md index 64d6a9968c5a3..e4ab7674f5ce3 100644 --- a/solution/1300-1399/1328.Break a Palindrome/README.md +++ b/solution/1300-1399/1328.Break a Palindrome/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们先判断字符串的长度是否为 $1$,若是则直接返回空串。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def breakPalindrome(self, palindrome: str) -> str: @@ -72,10 +66,6 @@ class Solution: return "".join(s) ``` -### **Java** - - - ```java class Solution { public String breakPalindrome(String palindrome) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func breakPalindrome(palindrome string) string { n := len(palindrome) @@ -144,8 +130,6 @@ func breakPalindrome(palindrome string) string { } ``` -### **TypeScript** - ```ts function breakPalindrome(palindrome: string): string { const n = palindrome.length; @@ -166,10 +150,6 @@ function breakPalindrome(palindrome: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1328.Break a Palindrome/README_EN.md b/solution/1300-1399/1328.Break a Palindrome/README_EN.md index b63349f7c41ca..c483e4dbbb4a4 100644 --- a/solution/1300-1399/1328.Break a Palindrome/README_EN.md +++ b/solution/1300-1399/1328.Break a Palindrome/README_EN.md @@ -38,9 +38,9 @@ Of all the ways, "aaccba" is the lexicographically smallest. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return "".join(s) ``` -### **Java** - ```java class Solution { public String breakPalindrome(String palindrome) { @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +103,6 @@ public: }; ``` -### **Go** - ```go func breakPalindrome(palindrome string) string { n := len(palindrome) @@ -129,8 +123,6 @@ func breakPalindrome(palindrome string) string { } ``` -### **TypeScript** - ```ts function breakPalindrome(palindrome: string): string { const n = palindrome.length; @@ -151,10 +143,6 @@ function breakPalindrome(palindrome: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1329.Sort the Matrix Diagonally/README.md b/solution/1300-1399/1329.Sort the Matrix Diagonally/README.md index 4d8a833e3a2da..1865ade0ff215 100644 --- a/solution/1300-1399/1329.Sort the Matrix Diagonally/README.md +++ b/solution/1300-1399/1329.Sort the Matrix Diagonally/README.md @@ -41,14 +41,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: @@ -61,10 +57,6 @@ class Solution: return mat ``` -### **Java** - - - ```java class Solution { public int[][] diagonalSort(int[][] mat) { @@ -85,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +92,6 @@ public: }; ``` -### **Go** - ```go func diagonalSort(mat [][]int) [][]int { m, n := len(mat), len(mat[0]) @@ -120,10 +108,6 @@ func diagonalSort(mat [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1329.Sort the Matrix Diagonally/README_EN.md b/solution/1300-1399/1329.Sort the Matrix Diagonally/README_EN.md index e168e8c6f5c1a..8fcc8b15b9a02 100644 --- a/solution/1300-1399/1329.Sort the Matrix Diagonally/README_EN.md +++ b/solution/1300-1399/1329.Sort the Matrix Diagonally/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return mat ``` -### **Java** - ```java class Solution { public int[][] diagonalSort(int[][] mat) { @@ -73,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,8 +86,6 @@ public: }; ``` -### **Go** - ```go func diagonalSort(mat [][]int) [][]int { m, n := len(mat), len(mat[0]) @@ -108,10 +102,6 @@ func diagonalSort(mat [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1330.Reverse Subarray To Maximize Array Value/README.md b/solution/1300-1399/1330.Reverse Subarray To Maximize Array Value/README.md index df08e7e587b6a..9a2464394b9ea 100644 --- a/solution/1300-1399/1330.Reverse Subarray To Maximize Array Value/README.md +++ b/solution/1300-1399/1330.Reverse Subarray To Maximize Array Value/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:分类讨论 + 枚举** +### 方法一:分类讨论 + 枚举 根据题目描述,我们需要求出:在翻转一次子数组的情况下,数组值 $\sum_{i=0}^{n-2} |a_i - a_{i+1}|$ 的最大值。 @@ -89,10 +87,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxValueAfterReverse(self, nums: List[int]) -> int: @@ -111,10 +105,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxValueAfterReverse(int[] nums) { @@ -148,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +170,6 @@ public: }; ``` -### **Go** - ```go func maxValueAfterReverse(nums []int) int { s, n := 0, len(nums) @@ -222,8 +208,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function maxValueAfterReverse(nums: number[]): number { const n = nums.length; @@ -254,10 +238,6 @@ function maxValueAfterReverse(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1330.Reverse Subarray To Maximize Array Value/README_EN.md b/solution/1300-1399/1330.Reverse Subarray To Maximize Array Value/README_EN.md index d6eb690865422..4fad22f11aa4a 100644 --- a/solution/1300-1399/1330.Reverse Subarray To Maximize Array Value/README_EN.md +++ b/solution/1300-1399/1330.Reverse Subarray To Maximize Array Value/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxValueAfterReverse(int[] nums) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +123,6 @@ public: }; ``` -### **Go** - ```go func maxValueAfterReverse(nums []int) int { s, n := 0, len(nums) @@ -167,8 +161,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function maxValueAfterReverse(nums: number[]): number { const n = nums.length; @@ -199,10 +191,6 @@ function maxValueAfterReverse(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1331.Rank Transform of an Array/README.md b/solution/1300-1399/1331.Rank Transform of an Array/README.md index c1767722965e1..5cd2c45194bce 100644 --- a/solution/1300-1399/1331.Rank Transform of an Array/README.md +++ b/solution/1300-1399/1331.Rank Transform of an Array/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:离散化** +### 方法一:离散化 我们先复制一个数组 $t$,然后对其进行排序并去重,得到一个长度为 $m$ 且严格单调递增的数组。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def arrayRankTransform(self, arr: List[int]) -> List[int]: @@ -71,10 +65,6 @@ class Solution: return [bisect_right(t, x) for x in arr] ``` -### **Java** - - - ```java class Solution { public int[] arrayRankTransform(int[] arr) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func arrayRankTransform(arr []int) (ans []int) { t := make([]int, len(arr)) @@ -136,8 +122,6 @@ func arrayRankTransform(arr []int) (ans []int) { } ``` -### **TypeScript** - ```ts function arrayRankTransform(arr: number[]): number[] { const t = [...arr].sort((a, b) => a - b); @@ -167,10 +151,6 @@ function arrayRankTransform(arr: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1331.Rank Transform of an Array/README_EN.md b/solution/1300-1399/1331.Rank Transform of an Array/README_EN.md index cb375ef9c45aa..b34199c0153f5 100644 --- a/solution/1300-1399/1331.Rank Transform of an Array/README_EN.md +++ b/solution/1300-1399/1331.Rank Transform of an Array/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return [bisect_right(t, x) for x in arr] ``` -### **Java** - ```java class Solution { public int[] arrayRankTransform(int[] arr) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +95,6 @@ public: }; ``` -### **Go** - ```go func arrayRankTransform(arr []int) (ans []int) { t := make([]int, len(arr)) @@ -121,8 +115,6 @@ func arrayRankTransform(arr []int) (ans []int) { } ``` -### **TypeScript** - ```ts function arrayRankTransform(arr: number[]): number[] { const t = [...arr].sort((a, b) => a - b); @@ -152,10 +144,6 @@ function arrayRankTransform(arr: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1332.Remove Palindromic Subsequences/README.md b/solution/1300-1399/1332.Remove Palindromic Subsequences/README.md index 4f858bb31a680..8fa5ef5fc2952 100644 --- a/solution/1300-1399/1332.Remove Palindromic Subsequences/README.md +++ b/solution/1300-1399/1332.Remove Palindromic Subsequences/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 如果字符串 $s$ 本身是个回文串,那么只需要删除 $1$ 次。 @@ -65,20 +63,12 @@ -### **Python3** - - - ```python class Solution: def removePalindromeSub(self, s: str) -> int: return 1 if s[::-1] == s else 2 ``` -### **Java** - - - ```java class Solution { public int removePalindromeSub(String s) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +96,6 @@ public: }; ``` -### **Go** - ```go func removePalindromeSub(s string) int { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { @@ -121,8 +107,6 @@ func removePalindromeSub(s string) int { } ``` -### **TypeScript** - ```ts function removePalindromeSub(s: string): number { for (let i = 0, j = s.length - 1; i < j; ++i, --j) { @@ -134,8 +118,6 @@ function removePalindromeSub(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn remove_palindrome_sub(s: String) -> i32 { @@ -154,10 +136,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1332.Remove Palindromic Subsequences/README_EN.md b/solution/1300-1399/1332.Remove Palindromic Subsequences/README_EN.md index 83bf3e425ea76..eee00953dffeb 100644 --- a/solution/1300-1399/1332.Remove Palindromic Subsequences/README_EN.md +++ b/solution/1300-1399/1332.Remove Palindromic Subsequences/README_EN.md @@ -49,9 +49,9 @@ Remove palindromic subsequence "baab" then "b". ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return 1 if s[::-1] == s else 2 ``` -### **Java** - ```java class Solution { public int removePalindromeSub(String s) { @@ -74,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,8 +86,6 @@ public: }; ``` -### **Go** - ```go func removePalindromeSub(s string) int { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { @@ -103,8 +97,6 @@ func removePalindromeSub(s string) int { } ``` -### **TypeScript** - ```ts function removePalindromeSub(s: string): number { for (let i = 0, j = s.length - 1; i < j; ++i, --j) { @@ -116,8 +108,6 @@ function removePalindromeSub(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn remove_palindrome_sub(s: String) -> i32 { @@ -136,10 +126,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1333.Filter Restaurants by Vegan-Friendly, Price and Distance/README.md b/solution/1300-1399/1333.Filter Restaurants by Vegan-Friendly, Price and Distance/README.md index 502de8c44a478..780a7114e0515 100644 --- a/solution/1300-1399/1333.Filter Restaurants by Vegan-Friendly, Price and Distance/README.md +++ b/solution/1300-1399/1333.Filter Restaurants by Vegan-Friendly, Price and Distance/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们先将数组 `restaurants` 按照 `rating` 和 `id` 两个维度进行排序,然后再按照题目给定的条件进行筛选即可。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def filterRestaurants( @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List filterRestaurants( @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func filterRestaurants(restaurants [][]int, veganFriendly int, maxPrice int, maxDistance int) (ans []int) { sort.Slice(restaurants, func(i, j int) bool { @@ -150,8 +136,6 @@ func filterRestaurants(restaurants [][]int, veganFriendly int, maxPrice int, max } ``` -### **TypeScript** - ```ts function filterRestaurants( restaurants: number[][], @@ -170,10 +154,6 @@ function filterRestaurants( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1333.Filter Restaurants by Vegan-Friendly, Price and Distance/README_EN.md b/solution/1300-1399/1333.Filter Restaurants by Vegan-Friendly, Price and Distance/README_EN.md index a83565475dfcd..d62a3ae753279 100644 --- a/solution/1300-1399/1333.Filter Restaurants by Vegan-Friendly, Price and Distance/README_EN.md +++ b/solution/1300-1399/1333.Filter Restaurants by Vegan-Friendly, Price and Distance/README_EN.md @@ -55,9 +55,9 @@ After filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List filterRestaurants( @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +113,6 @@ public: }; ``` -### **Go** - ```go func filterRestaurants(restaurants [][]int, veganFriendly int, maxPrice int, maxDistance int) (ans []int) { sort.Slice(restaurants, func(i, j int) bool { @@ -137,8 +131,6 @@ func filterRestaurants(restaurants [][]int, veganFriendly int, maxPrice int, max } ``` -### **TypeScript** - ```ts function filterRestaurants( restaurants: number[][], @@ -157,10 +149,6 @@ function filterRestaurants( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README.md b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README.md index e27cac6344bc2..21cc33d09df43 100644 --- a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README.md +++ b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README.md @@ -62,30 +62,14 @@ ## 解法 - - -**方法一:Dijkstra 算法** +### 方法一:Dijkstra 算法 我们可以枚举每个城市 $i$ 作为起点,使用 Dijkstra 算法求出从 $i$ 到其他城市的最短距离,然后统计距离不超过阈值的城市个数,最后取最小的个数且编号最大的城市。 时间复杂度 $O(n^3)$,空间复杂度 $O(n^2)$。其中 $n$ 为城市个数。 -**方法二:Floyd 算法** - -我们定义 $g[i][j]$ 表示城市 $i$ 到城市 $j$ 的最短距离,初始时 $g[i][j] = \infty$, $g[i][i] = 0$,然后我们遍历所有边,对于每条边 $(f, t, w)$,我们令 $g[f][t] = g[t][f] = w$。 - -接下来,我们用 Floyd 算法求出任意两点之间的最短距离。具体地,我们先枚举中间点 $k$,再枚举起点 $i$ 和终点 $j$,如果 $g[i][k] + g[k][j] \lt g[i][j]$,那么我们就用更短的距离 $g[i][k] + g[k][j]$ 更新 $g[i][j]$。 - -最后,我们枚举每个城市 $i$ 作为起点,统计距离不超过阈值的城市个数,最后取最小的个数且编号最大的城市。 - -时间复杂度 $O(n^3)$,空间复杂度 $O(n^2)$。其中 $n$ 为城市个数。 - -### **Python3** - - - ```python class Solution: def findTheCity( @@ -117,35 +101,6 @@ class Solution: return ans ``` -```python -class Solution: - def findTheCity( - self, n: int, edges: List[List[int]], distanceThreshold: int - ) -> int: - g = [[inf] * n for _ in range(n)] - for f, t, w in edges: - g[f][t] = g[t][f] = w - - for k in range(n): - g[k][k] = 0 - for i in range(n): - for j in range(n): - # g[i][j] = min(g[i][j], g[i][k] + g[k][j]) - if g[i][k] + g[k][j] < g[i][j]: - g[i][j] = g[i][k] + g[k][j] - - ans, cnt = n, inf - for i in range(n - 1, -1, -1): - t = sum(d <= distanceThreshold for d in g[i]) - if t < cnt: - cnt, ans = t, i - return ans -``` - -### **Java** - - - ```java class Solution { private int n; @@ -207,47 +162,6 @@ class Solution { } ``` -```java -class Solution { - public int findTheCity(int n, int[][] edges, int distanceThreshold) { - final int inf = 1 << 29; - int[][] g = new int[n][n]; - for (var e : g) { - Arrays.fill(e, inf); - } - for (var e : edges) { - int f = e[0], t = e[1], w = e[2]; - g[f][t] = w; - g[t][f] = w; - } - for (int k = 0; k < n; ++k) { - g[k][k] = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); - } - } - } - int ans = n, cnt = inf; - for (int i = n - 1; i >= 0; --i) { - int t = 0; - for (int d : g[i]) { - if (d <= distanceThreshold) { - ++t; - } - } - if (t < cnt) { - cnt = t; - ans = i; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -291,39 +205,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findTheCity(int n, vector>& edges, int distanceThreshold) { - int g[n][n]; - memset(g, 0x3f, sizeof(g)); - for (auto& e : edges) { - int f = e[0], t = e[1], w = e[2]; - g[f][t] = g[t][f] = w; - } - for (int k = 0; k < n; ++k) { - g[k][k] = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - g[i][j] = min(g[i][j], g[i][k] + g[k][j]); - } - } - } - int ans = n, cnt = n + 1; - for (int i = n - 1; ~i; --i) { - int t = count_if(g[i], g[i] + n, [&](int x) { return x <= distanceThreshold; }); - if (t < cnt) { - cnt = t; - ans = i; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func findTheCity(n int, edges [][]int, distanceThreshold int) int { g := make([][]int, n) @@ -378,50 +259,6 @@ func findTheCity(n int, edges [][]int, distanceThreshold int) int { } ``` -```go -func findTheCity(n int, edges [][]int, distanceThreshold int) int { - g := make([][]int, n) - const inf int = 1e7 - for i := range g { - g[i] = make([]int, n) - for j := range g[i] { - g[i][j] = inf - } - } - - for _, e := range edges { - f, t, w := e[0], e[1], e[2] - g[f][t], g[t][f] = w, w - } - - for k := 0; k < n; k++ { - g[k][k] = 0 - for i := 0; i < n; i++ { - for j := 0; j < n; j++ { - g[i][j] = min(g[i][j], g[i][k]+g[k][j]) - } - } - } - - ans, cnt := n, n+1 - for i := n - 1; i >= 0; i-- { - t := 0 - for _, x := range g[i] { - if x <= distanceThreshold { - t++ - } - } - if t < cnt { - cnt, ans = t, i - } - } - - return ans -} -``` - -### **TypeScript** - ```ts function findTheCity(n: number, edges: number[][], distanceThreshold: number): number { const g: number[][] = Array.from({ length: n }, () => Array(n).fill(Infinity)); @@ -464,6 +301,157 @@ function findTheCity(n: number, edges: number[][], distanceThreshold: number): n } ``` + + +### 方法二:Floyd 算法 + +我们定义 $g[i][j]$ 表示城市 $i$ 到城市 $j$ 的最短距离,初始时 $g[i][j] = \infty$, $g[i][i] = 0$,然后我们遍历所有边,对于每条边 $(f, t, w)$,我们令 $g[f][t] = g[t][f] = w$。 + +接下来,我们用 Floyd 算法求出任意两点之间的最短距离。具体地,我们先枚举中间点 $k$,再枚举起点 $i$ 和终点 $j$,如果 $g[i][k] + g[k][j] \lt g[i][j]$,那么我们就用更短的距离 $g[i][k] + g[k][j]$ 更新 $g[i][j]$。 + +最后,我们枚举每个城市 $i$ 作为起点,统计距离不超过阈值的城市个数,最后取最小的个数且编号最大的城市。 + +时间复杂度 $O(n^3)$,空间复杂度 $O(n^2)$。其中 $n$ 为城市个数。 + + + +```python +class Solution: + def findTheCity( + self, n: int, edges: List[List[int]], distanceThreshold: int + ) -> int: + g = [[inf] * n for _ in range(n)] + for f, t, w in edges: + g[f][t] = g[t][f] = w + + for k in range(n): + g[k][k] = 0 + for i in range(n): + for j in range(n): + # g[i][j] = min(g[i][j], g[i][k] + g[k][j]) + if g[i][k] + g[k][j] < g[i][j]: + g[i][j] = g[i][k] + g[k][j] + + ans, cnt = n, inf + for i in range(n - 1, -1, -1): + t = sum(d <= distanceThreshold for d in g[i]) + if t < cnt: + cnt, ans = t, i + return ans +``` + +```java +class Solution { + public int findTheCity(int n, int[][] edges, int distanceThreshold) { + final int inf = 1 << 29; + int[][] g = new int[n][n]; + for (var e : g) { + Arrays.fill(e, inf); + } + for (var e : edges) { + int f = e[0], t = e[1], w = e[2]; + g[f][t] = w; + g[t][f] = w; + } + for (int k = 0; k < n; ++k) { + g[k][k] = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); + } + } + } + int ans = n, cnt = inf; + for (int i = n - 1; i >= 0; --i) { + int t = 0; + for (int d : g[i]) { + if (d <= distanceThreshold) { + ++t; + } + } + if (t < cnt) { + cnt = t; + ans = i; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int findTheCity(int n, vector>& edges, int distanceThreshold) { + int g[n][n]; + memset(g, 0x3f, sizeof(g)); + for (auto& e : edges) { + int f = e[0], t = e[1], w = e[2]; + g[f][t] = g[t][f] = w; + } + for (int k = 0; k < n; ++k) { + g[k][k] = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + g[i][j] = min(g[i][j], g[i][k] + g[k][j]); + } + } + } + int ans = n, cnt = n + 1; + for (int i = n - 1; ~i; --i) { + int t = count_if(g[i], g[i] + n, [&](int x) { return x <= distanceThreshold; }); + if (t < cnt) { + cnt = t; + ans = i; + } + } + return ans; + } +}; +``` + +```go +func findTheCity(n int, edges [][]int, distanceThreshold int) int { + g := make([][]int, n) + const inf int = 1e7 + for i := range g { + g[i] = make([]int, n) + for j := range g[i] { + g[i][j] = inf + } + } + + for _, e := range edges { + f, t, w := e[0], e[1], e[2] + g[f][t], g[t][f] = w, w + } + + for k := 0; k < n; k++ { + g[k][k] = 0 + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + g[i][j] = min(g[i][j], g[i][k]+g[k][j]) + } + } + } + + ans, cnt := n, n+1 + for i := n - 1; i >= 0; i-- { + t := 0 + for _, x := range g[i] { + if x <= distanceThreshold { + t++ + } + } + if t < cnt { + cnt, ans = t, i + } + } + + return ans +} +``` + ```ts function findTheCity(n: number, edges: number[][], distanceThreshold: number): number { const g: number[][] = Array.from({ length: n }, () => Array(n).fill(Infinity)); @@ -492,10 +480,6 @@ function findTheCity(n: number, edges: number[][], distanceThreshold: number): n } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README_EN.md b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README_EN.md index 726e7788daaad..20b850c003f83 100644 --- a/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README_EN.md +++ b/solution/1300-1399/1334.Find the City With the Smallest Number of Neighbors at a Threshold Distance/README_EN.md @@ -54,9 +54,9 @@ The city 0 has 1 neighboring city at a distanceThreshold = 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -89,33 +89,6 @@ class Solution: return ans ``` -```python -class Solution: - def findTheCity( - self, n: int, edges: List[List[int]], distanceThreshold: int - ) -> int: - g = [[inf] * n for _ in range(n)] - for f, t, w in edges: - g[f][t] = g[t][f] = w - - for k in range(n): - g[k][k] = 0 - for i in range(n): - for j in range(n): - # g[i][j] = min(g[i][j], g[i][k] + g[k][j]) - if g[i][k] + g[k][j] < g[i][j]: - g[i][j] = g[i][k] + g[k][j] - - ans, cnt = n, inf - for i in range(n - 1, -1, -1): - t = sum(d <= distanceThreshold for d in g[i]) - if t < cnt: - cnt, ans = t, i - return ans -``` - -### **Java** - ```java class Solution { private int n; @@ -177,47 +150,6 @@ class Solution { } ``` -```java -class Solution { - public int findTheCity(int n, int[][] edges, int distanceThreshold) { - final int inf = 1 << 29; - int[][] g = new int[n][n]; - for (var e : g) { - Arrays.fill(e, inf); - } - for (var e : edges) { - int f = e[0], t = e[1], w = e[2]; - g[f][t] = w; - g[t][f] = w; - } - for (int k = 0; k < n; ++k) { - g[k][k] = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); - } - } - } - int ans = n, cnt = inf; - for (int i = n - 1; i >= 0; --i) { - int t = 0; - for (int d : g[i]) { - if (d <= distanceThreshold) { - ++t; - } - } - if (t < cnt) { - cnt = t; - ans = i; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -261,39 +193,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findTheCity(int n, vector>& edges, int distanceThreshold) { - int g[n][n]; - memset(g, 0x3f, sizeof(g)); - for (auto& e : edges) { - int f = e[0], t = e[1], w = e[2]; - g[f][t] = g[t][f] = w; - } - for (int k = 0; k < n; ++k) { - g[k][k] = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - g[i][j] = min(g[i][j], g[i][k] + g[k][j]); - } - } - } - int ans = n, cnt = n + 1; - for (int i = n - 1; ~i; --i) { - int t = count_if(g[i], g[i] + n, [&](int x) { return x <= distanceThreshold; }); - if (t < cnt) { - cnt = t; - ans = i; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func findTheCity(n int, edges [][]int, distanceThreshold int) int { g := make([][]int, n) @@ -348,50 +247,6 @@ func findTheCity(n int, edges [][]int, distanceThreshold int) int { } ``` -```go -func findTheCity(n int, edges [][]int, distanceThreshold int) int { - g := make([][]int, n) - const inf int = 1e7 - for i := range g { - g[i] = make([]int, n) - for j := range g[i] { - g[i][j] = inf - } - } - - for _, e := range edges { - f, t, w := e[0], e[1], e[2] - g[f][t], g[t][f] = w, w - } - - for k := 0; k < n; k++ { - g[k][k] = 0 - for i := 0; i < n; i++ { - for j := 0; j < n; j++ { - g[i][j] = min(g[i][j], g[i][k]+g[k][j]) - } - } - } - - ans, cnt := n, n+1 - for i := n - 1; i >= 0; i-- { - t := 0 - for _, x := range g[i] { - if x <= distanceThreshold { - t++ - } - } - if t < cnt { - cnt, ans = t, i - } - } - - return ans -} -``` - -### **TypeScript** - ```ts function findTheCity(n: number, edges: number[][], distanceThreshold: number): number { const g: number[][] = Array.from({ length: n }, () => Array(n).fill(Infinity)); @@ -434,6 +289,149 @@ function findTheCity(n: number, edges: number[][], distanceThreshold: number): n } ``` + + +### Solution 2 + + + +```python +class Solution: + def findTheCity( + self, n: int, edges: List[List[int]], distanceThreshold: int + ) -> int: + g = [[inf] * n for _ in range(n)] + for f, t, w in edges: + g[f][t] = g[t][f] = w + + for k in range(n): + g[k][k] = 0 + for i in range(n): + for j in range(n): + # g[i][j] = min(g[i][j], g[i][k] + g[k][j]) + if g[i][k] + g[k][j] < g[i][j]: + g[i][j] = g[i][k] + g[k][j] + + ans, cnt = n, inf + for i in range(n - 1, -1, -1): + t = sum(d <= distanceThreshold for d in g[i]) + if t < cnt: + cnt, ans = t, i + return ans +``` + +```java +class Solution { + public int findTheCity(int n, int[][] edges, int distanceThreshold) { + final int inf = 1 << 29; + int[][] g = new int[n][n]; + for (var e : g) { + Arrays.fill(e, inf); + } + for (var e : edges) { + int f = e[0], t = e[1], w = e[2]; + g[f][t] = w; + g[t][f] = w; + } + for (int k = 0; k < n; ++k) { + g[k][k] = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]); + } + } + } + int ans = n, cnt = inf; + for (int i = n - 1; i >= 0; --i) { + int t = 0; + for (int d : g[i]) { + if (d <= distanceThreshold) { + ++t; + } + } + if (t < cnt) { + cnt = t; + ans = i; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int findTheCity(int n, vector>& edges, int distanceThreshold) { + int g[n][n]; + memset(g, 0x3f, sizeof(g)); + for (auto& e : edges) { + int f = e[0], t = e[1], w = e[2]; + g[f][t] = g[t][f] = w; + } + for (int k = 0; k < n; ++k) { + g[k][k] = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + g[i][j] = min(g[i][j], g[i][k] + g[k][j]); + } + } + } + int ans = n, cnt = n + 1; + for (int i = n - 1; ~i; --i) { + int t = count_if(g[i], g[i] + n, [&](int x) { return x <= distanceThreshold; }); + if (t < cnt) { + cnt = t; + ans = i; + } + } + return ans; + } +}; +``` + +```go +func findTheCity(n int, edges [][]int, distanceThreshold int) int { + g := make([][]int, n) + const inf int = 1e7 + for i := range g { + g[i] = make([]int, n) + for j := range g[i] { + g[i][j] = inf + } + } + + for _, e := range edges { + f, t, w := e[0], e[1], e[2] + g[f][t], g[t][f] = w, w + } + + for k := 0; k < n; k++ { + g[k][k] = 0 + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + g[i][j] = min(g[i][j], g[i][k]+g[k][j]) + } + } + } + + ans, cnt := n, n+1 + for i := n - 1; i >= 0; i-- { + t := 0 + for _, x := range g[i] { + if x <= distanceThreshold { + t++ + } + } + if t < cnt { + cnt, ans = t, i + } + } + + return ans +} +``` + ```ts function findTheCity(n: number, edges: number[][], distanceThreshold: number): number { const g: number[][] = Array.from({ length: n }, () => Array(n).fill(Infinity)); @@ -462,10 +460,6 @@ function findTheCity(n: number, edges: number[][], distanceThreshold: number): n } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1335.Minimum Difficulty of a Job Schedule/README.md b/solution/1300-1399/1335.Minimum Difficulty of a Job Schedule/README.md index 206e86f4977e9..d8d3d80f405cb 100644 --- a/solution/1300-1399/1335.Minimum Difficulty of a Job Schedule/README.md +++ b/solution/1300-1399/1335.Minimum Difficulty of a Job Schedule/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示完成前 $i$ 项工作,且一共用了 $j$ 天的最小难度。初始时 $f[0][0] = 0$,其余 $f[i][j]$ 均为 $\infty$。 @@ -83,10 +81,6 @@ $$ -### **Python3** - - - ```python class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: @@ -102,10 +96,6 @@ class Solution: return -1 if f[n][d] >= inf else f[n][d] ``` -### **Java** - - - ```java class Solution { public int minDifficulty(int[] jobDifficulty, int d) { @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func minDifficulty(jobDifficulty []int, d int) int { n := len(jobDifficulty) @@ -184,8 +170,6 @@ func minDifficulty(jobDifficulty []int, d int) int { } ``` -### **TypeScript** - ```ts function minDifficulty(jobDifficulty: number[], d: number): number { const n = jobDifficulty.length; @@ -205,10 +189,6 @@ function minDifficulty(jobDifficulty: number[], d: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1335.Minimum Difficulty of a Job Schedule/README_EN.md b/solution/1300-1399/1335.Minimum Difficulty of a Job Schedule/README_EN.md index 821087209beff..b51e98a50aa58 100644 --- a/solution/1300-1399/1335.Minimum Difficulty of a Job Schedule/README_EN.md +++ b/solution/1300-1399/1335.Minimum Difficulty of a Job Schedule/README_EN.md @@ -50,7 +50,7 @@ The difficulty of the schedule = 6 + 1 = 7 ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ as the minimum difficulty to finish the first $i$ jobs within $j$ days. Initially $f[0][0] = 0$, and all other $f[i][j]$ are $\infty$. @@ -66,8 +66,6 @@ The time complexity is $O(n^2 \times d)$, and the space complexity is $O(n \time -### **Python3** - ```python class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: @@ -83,8 +81,6 @@ class Solution: return -1 if f[n][d] >= inf else f[n][d] ``` -### **Java** - ```java class Solution { public int minDifficulty(int[] jobDifficulty, int d) { @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +127,6 @@ public: }; ``` -### **Go** - ```go func minDifficulty(jobDifficulty []int, d int) int { n := len(jobDifficulty) @@ -163,8 +155,6 @@ func minDifficulty(jobDifficulty []int, d int) int { } ``` -### **TypeScript** - ```ts function minDifficulty(jobDifficulty: number[], d: number): number { const n = jobDifficulty.length; @@ -184,10 +174,6 @@ function minDifficulty(jobDifficulty: number[], d: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1336.Number of Transactions per Visit/README.md b/solution/1300-1399/1336.Number of Transactions per Visit/README.md index bb5804db30a49..3f52b71cc98df 100644 --- a/solution/1300-1399/1336.Number of Transactions per Visit/README.md +++ b/solution/1300-1399/1336.Number of Transactions per Visit/README.md @@ -110,12 +110,10 @@ Visits 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH RECURSIVE @@ -155,3 +153,5 @@ ORDER BY n; ``` + + diff --git a/solution/1300-1399/1336.Number of Transactions per Visit/README_EN.md b/solution/1300-1399/1336.Number of Transactions per Visit/README_EN.md index 51afba48b52b6..b9aa962862766 100644 --- a/solution/1300-1399/1336.Number of Transactions per Visit/README_EN.md +++ b/solution/1300-1399/1336.Number of Transactions per Visit/README_EN.md @@ -105,9 +105,9 @@ Transactions table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -148,3 +148,5 @@ ORDER BY n; ``` + + diff --git a/solution/1300-1399/1337.The K Weakest Rows in a Matrix/README.md b/solution/1300-1399/1337.The K Weakest Rows in a Matrix/README.md index fecb17345f97a..07a828fb98281 100644 --- a/solution/1300-1399/1337.The K Weakest Rows in a Matrix/README.md +++ b/solution/1300-1399/1337.The K Weakest Rows in a Matrix/README.md @@ -70,16 +70,10 @@ k = 2 ## 解法 - - -二分查找 + 排序。 +### 方法一 -### **Python3** - - - ```python class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: @@ -90,10 +84,6 @@ class Solution: return idx[:k] ``` -### **Java** - - - ```java class Solution { public int[] kWeakestRows(int[][] mat, int k) { @@ -124,31 +114,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function kWeakestRows(mat: number[][], k: number): number[] { - let n = mat.length; - let sumMap = mat.map((d, i) => [d.reduce((a, c) => a + c, 0), i]); - let ans = []; - // 冒泡排序 - for (let i = 0; i < k; i++) { - for (let j = i; j < n; j++) { - if ( - sumMap[j][0] < sumMap[i][0] || - (sumMap[j][0] == sumMap[i][0] && sumMap[i][1] > sumMap[j][1]) - ) { - [sumMap[i], sumMap[j]] = [sumMap[j], sumMap[i]]; - } - } - ans.push(sumMap[i][1]); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -181,8 +146,6 @@ public: }; ``` -### **Go** - ```go func kWeakestRows(mat [][]int, k int) []int { m, n := len(mat), len(mat[0]) @@ -208,10 +171,27 @@ func kWeakestRows(mat [][]int, k int) []int { } ``` -### **...** - -``` - +```ts +function kWeakestRows(mat: number[][], k: number): number[] { + let n = mat.length; + let sumMap = mat.map((d, i) => [d.reduce((a, c) => a + c, 0), i]); + let ans = []; + // 冒泡排序 + for (let i = 0; i < k; i++) { + for (let j = i; j < n; j++) { + if ( + sumMap[j][0] < sumMap[i][0] || + (sumMap[j][0] == sumMap[i][0] && sumMap[i][1] > sumMap[j][1]) + ) { + [sumMap[i], sumMap[j]] = [sumMap[j], sumMap[i]]; + } + } + ans.push(sumMap[i][1]); + } + return ans; +} ``` + + diff --git a/solution/1300-1399/1337.The K Weakest Rows in a Matrix/README_EN.md b/solution/1300-1399/1337.The K Weakest Rows in a Matrix/README_EN.md index 813c70c84f874..7788f2e03c987 100644 --- a/solution/1300-1399/1337.The K Weakest Rows in a Matrix/README_EN.md +++ b/solution/1300-1399/1337.The K Weakest Rows in a Matrix/README_EN.md @@ -69,12 +69,10 @@ The rows ordered from weakest to strongest are [0,2,3,1]. ## Solutions -Binary search & sort. +### Solution 1 -### **Python3** - ```python class Solution: def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: @@ -85,8 +83,6 @@ class Solution: return idx[:k] ``` -### **Java** - ```java class Solution { public int[] kWeakestRows(int[][] mat, int k) { @@ -117,31 +113,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function kWeakestRows(mat: number[][], k: number): number[] { - let n = mat.length; - let sumMap = mat.map((d, i) => [d.reduce((a, c) => a + c, 0), i]); - let ans = []; - // 冒泡排序 - for (let i = 0; i < k; i++) { - for (let j = i; j < n; j++) { - if ( - sumMap[j][0] < sumMap[i][0] || - (sumMap[j][0] == sumMap[i][0] && sumMap[i][1] > sumMap[j][1]) - ) { - [sumMap[i], sumMap[j]] = [sumMap[j], sumMap[i]]; - } - } - ans.push(sumMap[i][1]); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -174,8 +145,6 @@ public: }; ``` -### **Go** - ```go func kWeakestRows(mat [][]int, k int) []int { m, n := len(mat), len(mat[0]) @@ -201,10 +170,27 @@ func kWeakestRows(mat [][]int, k int) []int { } ``` -### **...** - -``` - +```ts +function kWeakestRows(mat: number[][], k: number): number[] { + let n = mat.length; + let sumMap = mat.map((d, i) => [d.reduce((a, c) => a + c, 0), i]); + let ans = []; + // 冒泡排序 + for (let i = 0; i < k; i++) { + for (let j = i; j < n; j++) { + if ( + sumMap[j][0] < sumMap[i][0] || + (sumMap[j][0] == sumMap[i][0] && sumMap[i][1] > sumMap[j][1]) + ) { + [sumMap[i], sumMap[j]] = [sumMap[j], sumMap[i]]; + } + } + ans.push(sumMap[i][1]); + } + return ans; +} ``` + + diff --git a/solution/1300-1399/1338.Reduce Array Size to The Half/README.md b/solution/1300-1399/1338.Reduce Array Size to The Half/README.md index 95f59c77740b7..bf626cfa326aa 100644 --- a/solution/1300-1399/1338.Reduce Array Size to The Half/README.md +++ b/solution/1300-1399/1338.Reduce Array Size to The Half/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:计数 + 排序** +### 方法一:计数 + 排序 我们可以用哈希表或数组 $cnt$ 统计数组 $arr$ 中每个数字出现的次数,然后将 $cnt$ 中的数字从大到小排序,从大到小遍历 $cnt$,每次遍历将当前数字 $x$ 加入答案,并将 $m$ 加上 $x$,如果 $m \geq \frac{n}{2}$,则返回答案。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def minSetSize(self, arr: List[int]) -> int: @@ -69,10 +63,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minSetSize(int[] arr) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func minSetSize(arr []int) (ans int) { mx := slices.Max(arr) @@ -151,8 +137,6 @@ func minSetSize(arr []int) (ans int) { } ``` -### **TypeScript** - ```ts function minSetSize(arr: number[]): number { const counter = new Map(); @@ -174,10 +158,6 @@ function minSetSize(arr: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1338.Reduce Array Size to The Half/README_EN.md b/solution/1300-1399/1338.Reduce Array Size to The Half/README_EN.md index dc7f2bd2754b9..fb503de6a4036 100644 --- a/solution/1300-1399/1338.Reduce Array Size to The Half/README_EN.md +++ b/solution/1300-1399/1338.Reduce Array Size to The Half/README_EN.md @@ -38,9 +38,9 @@ Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minSetSize(int[] arr) { @@ -84,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func minSetSize(arr []int) (ans int) { mx := slices.Max(arr) @@ -135,8 +129,6 @@ func minSetSize(arr []int) (ans int) { } ``` -### **TypeScript** - ```ts function minSetSize(arr: number[]): number { const counter = new Map(); @@ -158,10 +150,6 @@ function minSetSize(arr: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1339.Maximum Product of Splitted Binary Tree/README.md b/solution/1300-1399/1339.Maximum Product of Splitted Binary Tree/README.md index adaf029094646..59f00990f21a6 100644 --- a/solution/1300-1399/1339.Maximum Product of Splitted Binary Tree/README.md +++ b/solution/1300-1399/1339.Maximum Product of Splitted Binary Tree/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:两次 DFS** +### 方法一:两次 DFS 我们可以用两次 DFS 来解决这个问题。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -101,10 +95,6 @@ class Solution: return ans % mod ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -152,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -199,8 +187,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -237,8 +223,6 @@ func maxProduct(root *TreeNode) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -279,10 +263,6 @@ function maxProduct(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1339.Maximum Product of Splitted Binary Tree/README_EN.md b/solution/1300-1399/1339.Maximum Product of Splitted Binary Tree/README_EN.md index 297ab46d0ed8a..9732f279b6103 100644 --- a/solution/1300-1399/1339.Maximum Product of Splitted Binary Tree/README_EN.md +++ b/solution/1300-1399/1339.Maximum Product of Splitted Binary Tree/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -71,8 +71,6 @@ class Solution: return ans % mod ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -120,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -167,8 +163,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -205,8 +199,6 @@ func maxProduct(root *TreeNode) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -247,10 +239,6 @@ function maxProduct(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1340.Jump Game V/README.md b/solution/1300-1399/1340.Jump Game V/README.md index 34a5530c17175..656d819e0d171 100644 --- a/solution/1300-1399/1340.Jump Game V/README.md +++ b/solution/1300-1399/1340.Jump Game V/README.md @@ -70,9 +70,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i)$,表示从下标 $i$ 开始跳跃能够访问的最大下标数。我们可以枚举 $i$ 的所有合法的跳跃目标 $j$,即 $i - d \leq j \leq i + d$,并且 $arr[i] \gt arr[j]$。对于每个合法的 $j$,我们可以递归地计算 $dfs(j)$,并取其中的最大值。最终的答案即为所有 $i$ 的 $dfs(i)$ 的最大值。 @@ -80,24 +78,8 @@ 时间复杂度 $O(n \times d)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $arr$ 的长度。 -**方法二:排序 + 动态规划** - -我们可以将数组 $arr$ 中的每个元素 $x$ 与其下标 $i$ 组成一个元组 $(x, i)$,并将这些元组按照 $x$ 从小到大排序。 - -接下来定义 $f[i]$ 表示从下标 $i$ 开始跳跃能够访问的最大下标数。初始时 $f[i] = 1$,即每个下标都可以单独作为一次跳跃。 - -我们可以按照元组 $(x, i)$ 的顺序枚举 $i$,并枚举 $i$ 的所有合法的跳跃目标 $j$,即 $i - d \leq j \leq i + d$,并且 $arr[i] \gt arr[j]$。对于每个合法的 $j$,我们可以更新 $f[i]$ 的值,即 $f[i] = \max(f[i], 1 + f[j])$。 - -最终的答案即为 $\max_{0 \leq i \lt n} f[i]$。 - -时间复杂度 $O(n \log n + n \times d)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $arr$ 的长度。 - -### **Python3** - - - ```python class Solution: def maxJumps(self, arr: List[int], d: int) -> int: @@ -118,27 +100,6 @@ class Solution: return max(dfs(i) for i in range(n)) ``` -```python -class Solution: - def maxJumps(self, arr: List[int], d: int) -> int: - n = len(arr) - f = [1] * n - for x, i in sorted(zip(arr, range(n))): - for j in range(i - 1, -1, -1): - if i - j > d or arr[j] >= x: - break - f[i] = max(f[i], 1 + f[j]) - for j in range(i + 1, n): - if j - i > d or arr[j] >= x: - break - f[i] = max(f[i], 1 + f[j]) - return max(f) -``` - -### **Java** - - - ```java class Solution { private int n; @@ -180,40 +141,6 @@ class Solution { } ``` -```java -class Solution { - public int maxJumps(int[] arr, int d) { - int n = arr.length; - Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } - Arrays.sort(idx, (i, j) -> arr[i] - arr[j]); - int[] f = new int[n]; - Arrays.fill(f, 1); - int ans = 0; - for (int i : idx) { - for (int j = i - 1; j >= 0; --j) { - if (i - j > d || arr[j] >= arr[i]) { - break; - } - f[i] = Math.max(f[i], 1 + f[j]); - } - for (int j = i + 1; j < n; ++j) { - if (j - i > d || arr[j] >= arr[i]) { - break; - } - f[i] = Math.max(f[i], 1 + f[j]); - } - ans = Math.max(ans, f[i]); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -249,36 +176,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxJumps(vector& arr, int d) { - int n = arr.size(); - vector idx(n); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { return arr[i] < arr[j]; }); - vector f(n, 1); - for (int i : idx) { - for (int j = i - 1; j >= 0; --j) { - if (i - j > d || arr[j] >= arr[i]) { - break; - } - f[i] = max(f[i], 1 + f[j]); - } - for (int j = i + 1; j < n; ++j) { - if (j - i > d || arr[j] >= arr[i]) { - break; - } - f[i] = max(f[i], 1 + f[j]); - } - } - return *max_element(f.begin(), f.end()); - } -}; -``` - -### **Go** - ```go func maxJumps(arr []int, d int) (ans int) { n := len(arr) @@ -311,6 +208,99 @@ func maxJumps(arr []int, d int) (ans int) { } ``` + + +### 方法二:排序 + 动态规划 + +我们可以将数组 $arr$ 中的每个元素 $x$ 与其下标 $i$ 组成一个元组 $(x, i)$,并将这些元组按照 $x$ 从小到大排序。 + +接下来定义 $f[i]$ 表示从下标 $i$ 开始跳跃能够访问的最大下标数。初始时 $f[i] = 1$,即每个下标都可以单独作为一次跳跃。 + +我们可以按照元组 $(x, i)$ 的顺序枚举 $i$,并枚举 $i$ 的所有合法的跳跃目标 $j$,即 $i - d \leq j \leq i + d$,并且 $arr[i] \gt arr[j]$。对于每个合法的 $j$,我们可以更新 $f[i]$ 的值,即 $f[i] = \max(f[i], 1 + f[j])$。 + +最终的答案即为 $\max_{0 \leq i \lt n} f[i]$。 + +时间复杂度 $O(n \log n + n \times d)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $arr$ 的长度。 + + + +```python +class Solution: + def maxJumps(self, arr: List[int], d: int) -> int: + n = len(arr) + f = [1] * n + for x, i in sorted(zip(arr, range(n))): + for j in range(i - 1, -1, -1): + if i - j > d or arr[j] >= x: + break + f[i] = max(f[i], 1 + f[j]) + for j in range(i + 1, n): + if j - i > d or arr[j] >= x: + break + f[i] = max(f[i], 1 + f[j]) + return max(f) +``` + +```java +class Solution { + public int maxJumps(int[] arr, int d) { + int n = arr.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> arr[i] - arr[j]); + int[] f = new int[n]; + Arrays.fill(f, 1); + int ans = 0; + for (int i : idx) { + for (int j = i - 1; j >= 0; --j) { + if (i - j > d || arr[j] >= arr[i]) { + break; + } + f[i] = Math.max(f[i], 1 + f[j]); + } + for (int j = i + 1; j < n; ++j) { + if (j - i > d || arr[j] >= arr[i]) { + break; + } + f[i] = Math.max(f[i], 1 + f[j]); + } + ans = Math.max(ans, f[i]); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maxJumps(vector& arr, int d) { + int n = arr.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { return arr[i] < arr[j]; }); + vector f(n, 1); + for (int i : idx) { + for (int j = i - 1; j >= 0; --j) { + if (i - j > d || arr[j] >= arr[i]) { + break; + } + f[i] = max(f[i], 1 + f[j]); + } + for (int j = i + 1; j < n; ++j) { + if (j - i > d || arr[j] >= arr[i]) { + break; + } + f[i] = max(f[i], 1 + f[j]); + } + } + return *max_element(f.begin(), f.end()); + } +}; +``` + ```go func maxJumps(arr []int, d int) int { n := len(arr) @@ -339,10 +329,6 @@ func maxJumps(arr []int, d int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1340.Jump Game V/README_EN.md b/solution/1300-1399/1340.Jump Game V/README_EN.md index 956ddc4e9950f..6c1d908d1896e 100644 --- a/solution/1300-1399/1340.Jump Game V/README_EN.md +++ b/solution/1300-1399/1340.Jump Game V/README_EN.md @@ -55,9 +55,9 @@ Similarly You cannot jump from index 3 to index 2 or index 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,25 +79,6 @@ class Solution: return max(dfs(i) for i in range(n)) ``` -```python -class Solution: - def maxJumps(self, arr: List[int], d: int) -> int: - n = len(arr) - f = [1] * n - for x, i in sorted(zip(arr, range(n))): - for j in range(i - 1, -1, -1): - if i - j > d or arr[j] >= x: - break - f[i] = max(f[i], 1 + f[j]) - for j in range(i + 1, n): - if j - i > d or arr[j] >= x: - break - f[i] = max(f[i], 1 + f[j]) - return max(f) -``` - -### **Java** - ```java class Solution { private int n; @@ -139,40 +120,6 @@ class Solution { } ``` -```java -class Solution { - public int maxJumps(int[] arr, int d) { - int n = arr.length; - Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } - Arrays.sort(idx, (i, j) -> arr[i] - arr[j]); - int[] f = new int[n]; - Arrays.fill(f, 1); - int ans = 0; - for (int i : idx) { - for (int j = i - 1; j >= 0; --j) { - if (i - j > d || arr[j] >= arr[i]) { - break; - } - f[i] = Math.max(f[i], 1 + f[j]); - } - for (int j = i + 1; j < n; ++j) { - if (j - i > d || arr[j] >= arr[i]) { - break; - } - f[i] = Math.max(f[i], 1 + f[j]); - } - ans = Math.max(ans, f[i]); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -208,36 +155,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxJumps(vector& arr, int d) { - int n = arr.size(); - vector idx(n); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { return arr[i] < arr[j]; }); - vector f(n, 1); - for (int i : idx) { - for (int j = i - 1; j >= 0; --j) { - if (i - j > d || arr[j] >= arr[i]) { - break; - } - f[i] = max(f[i], 1 + f[j]); - } - for (int j = i + 1; j < n; ++j) { - if (j - i > d || arr[j] >= arr[i]) { - break; - } - f[i] = max(f[i], 1 + f[j]); - } - } - return *max_element(f.begin(), f.end()); - } -}; -``` - -### **Go** - ```go func maxJumps(arr []int, d int) (ans int) { n := len(arr) @@ -270,6 +187,89 @@ func maxJumps(arr []int, d int) (ans int) { } ``` + + +### Solution 2 + + + +```python +class Solution: + def maxJumps(self, arr: List[int], d: int) -> int: + n = len(arr) + f = [1] * n + for x, i in sorted(zip(arr, range(n))): + for j in range(i - 1, -1, -1): + if i - j > d or arr[j] >= x: + break + f[i] = max(f[i], 1 + f[j]) + for j in range(i + 1, n): + if j - i > d or arr[j] >= x: + break + f[i] = max(f[i], 1 + f[j]) + return max(f) +``` + +```java +class Solution { + public int maxJumps(int[] arr, int d) { + int n = arr.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> arr[i] - arr[j]); + int[] f = new int[n]; + Arrays.fill(f, 1); + int ans = 0; + for (int i : idx) { + for (int j = i - 1; j >= 0; --j) { + if (i - j > d || arr[j] >= arr[i]) { + break; + } + f[i] = Math.max(f[i], 1 + f[j]); + } + for (int j = i + 1; j < n; ++j) { + if (j - i > d || arr[j] >= arr[i]) { + break; + } + f[i] = Math.max(f[i], 1 + f[j]); + } + ans = Math.max(ans, f[i]); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maxJumps(vector& arr, int d) { + int n = arr.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { return arr[i] < arr[j]; }); + vector f(n, 1); + for (int i : idx) { + for (int j = i - 1; j >= 0; --j) { + if (i - j > d || arr[j] >= arr[i]) { + break; + } + f[i] = max(f[i], 1 + f[j]); + } + for (int j = i + 1; j < n; ++j) { + if (j - i > d || arr[j] >= arr[i]) { + break; + } + f[i] = max(f[i], 1 + f[j]); + } + } + return *max_element(f.begin(), f.end()); + } +}; +``` + ```go func maxJumps(arr []int, d int) int { n := len(arr) @@ -298,10 +298,6 @@ func maxJumps(arr []int, d int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1341.Movie Rating/README.md b/solution/1300-1399/1341.Movie Rating/README.md index be45ff2b80c99..38a445e76353a 100644 --- a/solution/1300-1399/1341.Movie Rating/README.md +++ b/solution/1300-1399/1341.Movie Rating/README.md @@ -112,16 +112,12 @@ Frozen 2 和 Joker 在 2 月的评分都是 3.5,但是 Frozen 2 的字典序 ## 解法 - - -**方法一:Union all** +### 方法一:Union all 分别查询两个结果,然后使用 `union all` 合并结果集。 -### **SQL** - ```sql # Write your MySQL query statement below ( @@ -147,3 +143,5 @@ UNION ALL ``` + + diff --git a/solution/1300-1399/1341.Movie Rating/README_EN.md b/solution/1300-1399/1341.Movie Rating/README_EN.md index 81a3830fbf061..6c298247f7981 100644 --- a/solution/1300-1399/1341.Movie Rating/README_EN.md +++ b/solution/1300-1399/1341.Movie Rating/README_EN.md @@ -110,9 +110,9 @@ Frozen 2 and Joker have a rating average of 3.5 in February but Frozen 2 is smal ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -139,3 +139,5 @@ UNION ALL ``` + + diff --git a/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/README.md b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/README.md index bb2cdb04512e2..8893b1b49ba36 100644 --- a/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/README.md +++ b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/README.md @@ -50,14 +50,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def numberOfSteps(self, num: int) -> int: @@ -71,22 +67,6 @@ class Solution: return ans ``` -```python -class Solution: - def numberOfSteps(self, num: int) -> int: - if num == 0: - return 0 - return 1 + ( - self.numberOfSteps(num // 2) - if num % 2 == 0 - else self.numberOfSteps(num - 1) - ) -``` - -### **Java** - - - ```java class Solution { @@ -101,33 +81,6 @@ class Solution { } ``` -```java -class Solution { - - public int numberOfSteps(int num) { - if (num == 0) { - return 0; - } - return 1 + numberOfSteps((num & 1) == 0 ? num >> 1 : num - 1); - } -} -``` - -### **TypeScript** - -```ts -function numberOfSteps(num: number): number { - let ans = 0; - while (num) { - num = num & 1 ? num - 1 : num >>> 1; - ans++; - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -142,18 +95,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numberOfSteps(int num) { - if (num == 0) return 0; - return 1 + (num & 1 ? numberOfSteps(num - 1) : numberOfSteps(num >> 1)); - } -}; -``` - -### **Go** - ```go func numberOfSteps(num int) int { ans := 0 @@ -169,20 +110,17 @@ func numberOfSteps(num int) int { } ``` -```go -func numberOfSteps(num int) int { - if num == 0 { - return 0 - } - if (num & 1) == 0 { - return 1 + numberOfSteps(num>>1) - } - return 1 + numberOfSteps(num-1) +```ts +function numberOfSteps(num: number): number { + let ans = 0; + while (num) { + num = num & 1 ? num - 1 : num >>> 1; + ans++; + } + return ans; } ``` -### **Rust** - ```rust impl Solution { pub fn number_of_steps(mut num: i32) -> i32 { @@ -200,6 +138,58 @@ impl Solution { } ``` + + +### 方法二 + + + +```python +class Solution: + def numberOfSteps(self, num: int) -> int: + if num == 0: + return 0 + return 1 + ( + self.numberOfSteps(num // 2) + if num % 2 == 0 + else self.numberOfSteps(num - 1) + ) +``` + +```java +class Solution { + + public int numberOfSteps(int num) { + if (num == 0) { + return 0; + } + return 1 + numberOfSteps((num & 1) == 0 ? num >> 1 : num - 1); + } +} +``` + +```cpp +class Solution { +public: + int numberOfSteps(int num) { + if (num == 0) return 0; + return 1 + (num & 1 ? numberOfSteps(num - 1) : numberOfSteps(num >> 1)); + } +}; +``` + +```go +func numberOfSteps(num int) int { + if num == 0 { + return 0 + } + if (num & 1) == 0 { + return 1 + numberOfSteps(num>>1) + } + return 1 + numberOfSteps(num-1) +} +``` + ```rust impl Solution { pub fn number_of_steps(mut num: i32) -> i32 { @@ -214,10 +204,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/README_EN.md b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/README_EN.md index c27a736794f54..3f04143e8a921 100644 --- a/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/README_EN.md +++ b/solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/README_EN.md @@ -51,9 +51,9 @@ Step 4) 1 is odd; subtract 1 and obtain 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,20 +68,6 @@ class Solution: return ans ``` -```python -class Solution: - def numberOfSteps(self, num: int) -> int: - if num == 0: - return 0 - return 1 + ( - self.numberOfSteps(num // 2) - if num % 2 == 0 - else self.numberOfSteps(num - 1) - ) -``` - -### **Java** - ```java class Solution { @@ -96,33 +82,6 @@ class Solution { } ``` -```java -class Solution { - - public int numberOfSteps(int num) { - if (num == 0) { - return 0; - } - return 1 + numberOfSteps((num & 1) == 0 ? num >> 1 : num - 1); - } -} -``` - -### **TypeScript** - -```ts -function numberOfSteps(num: number): number { - let ans = 0; - while (num) { - num = num & 1 ? num - 1 : num >>> 1; - ans++; - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -137,18 +96,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numberOfSteps(int num) { - if (num == 0) return 0; - return 1 + (num & 1 ? numberOfSteps(num - 1) : numberOfSteps(num >> 1)); - } -}; -``` - -### **Go** - ```go func numberOfSteps(num int) int { ans := 0 @@ -164,20 +111,17 @@ func numberOfSteps(num int) int { } ``` -```go -func numberOfSteps(num int) int { - if num == 0 { - return 0 - } - if (num & 1) == 0 { - return 1 + numberOfSteps(num>>1) - } - return 1 + numberOfSteps(num-1) +```ts +function numberOfSteps(num: number): number { + let ans = 0; + while (num) { + num = num & 1 ? num - 1 : num >>> 1; + ans++; + } + return ans; } ``` -### **Rust** - ```rust impl Solution { pub fn number_of_steps(mut num: i32) -> i32 { @@ -195,6 +139,58 @@ impl Solution { } ``` + + +### Solution 2 + + + +```python +class Solution: + def numberOfSteps(self, num: int) -> int: + if num == 0: + return 0 + return 1 + ( + self.numberOfSteps(num // 2) + if num % 2 == 0 + else self.numberOfSteps(num - 1) + ) +``` + +```java +class Solution { + + public int numberOfSteps(int num) { + if (num == 0) { + return 0; + } + return 1 + numberOfSteps((num & 1) == 0 ? num >> 1 : num - 1); + } +} +``` + +```cpp +class Solution { +public: + int numberOfSteps(int num) { + if (num == 0) return 0; + return 1 + (num & 1 ? numberOfSteps(num - 1) : numberOfSteps(num >> 1)); + } +}; +``` + +```go +func numberOfSteps(num int) int { + if num == 0 { + return 0 + } + if (num & 1) == 0 { + return 1 + numberOfSteps(num>>1) + } + return 1 + numberOfSteps(num-1) +} +``` + ```rust impl Solution { pub fn number_of_steps(mut num: i32) -> i32 { @@ -209,10 +205,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1343.Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/README.md b/solution/1300-1399/1343.Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/README.md index 1ae97abb22a83..9becf042b2e25 100644 --- a/solution/1300-1399/1343.Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/README.md +++ b/solution/1300-1399/1343.Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 我们可以维护一个长度为 $k$ 的滑动窗口,窗口内的元素之和为 $s$,每次判断 $\frac{s}{k}$ 是否大于等于 $threshold$,如果大于等于,则满足条件的子数组个数加一。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int: @@ -69,10 +63,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numOfSubarrays(int[] arr, int k, int threshold) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func numOfSubarrays(arr []int, k int, threshold int) (ans int) { s := 0 @@ -128,8 +114,6 @@ func numOfSubarrays(arr []int, k int, threshold int) (ans int) { } ``` -### **TypeScript** - ```ts function numOfSubarrays(arr: number[], k: number, threshold: number): number { let s = arr.slice(0, k).reduce((acc, cur) => acc + cur, 0); @@ -142,10 +126,6 @@ function numOfSubarrays(arr: number[], k: number, threshold: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1343.Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/README_EN.md b/solution/1300-1399/1343.Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/README_EN.md index 172006ccbb9a3..28ab0761086f0 100644 --- a/solution/1300-1399/1343.Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/README_EN.md +++ b/solution/1300-1399/1343.Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numOfSubarrays(int[] arr, int k, int threshold) { @@ -70,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +83,6 @@ public: }; ``` -### **Go** - ```go func numOfSubarrays(arr []int, k int, threshold int) (ans int) { s := 0 @@ -108,8 +102,6 @@ func numOfSubarrays(arr []int, k int, threshold int) (ans int) { } ``` -### **TypeScript** - ```ts function numOfSubarrays(arr: number[], k: number, threshold: number): number { let s = arr.slice(0, k).reduce((acc, cur) => acc + cur, 0); @@ -122,10 +114,6 @@ function numOfSubarrays(arr: number[], k: number, threshold: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1344.Angle Between Hands of a Clock/README.md b/solution/1300-1399/1344.Angle Between Hands of a Clock/README.md index 60c2118e5ce01..f2a8966db3ab5 100644 --- a/solution/1300-1399/1344.Angle Between Hands of a Clock/README.md +++ b/solution/1300-1399/1344.Angle Between Hands of a Clock/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 时针每小时移动 30 度,每分钟移动 0.5 度。分针每分钟移动 6 度。如果指针之间的夹角大于 180 度,则取其与 360 度的差值,以确保获得最小的夹角。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def angleClock(self, hour: int, minutes: int) -> float: @@ -81,10 +75,6 @@ class Solution: return min(diff, 360 - diff) ``` -### **Java** - - - ```java class Solution { public double angleClock(int hour, int minutes) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +98,6 @@ public: }; ``` -### **Go** - ```go func angleClock(hour int, minutes int) float64 { h := 30*float64(hour) + 0.5*float64(minutes) @@ -121,8 +107,6 @@ func angleClock(hour int, minutes int) float64 { } ``` -### **TypeScript** - ```ts function angleClock(hour: number, minutes: number): number { const h = 30 * hour + 0.5 * minutes; @@ -132,10 +116,6 @@ function angleClock(hour: number, minutes: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1344.Angle Between Hands of a Clock/README_EN.md b/solution/1300-1399/1344.Angle Between Hands of a Clock/README_EN.md index 0f257374cd1e6..17387c5f6e594 100644 --- a/solution/1300-1399/1344.Angle Between Hands of a Clock/README_EN.md +++ b/solution/1300-1399/1344.Angle Between Hands of a Clock/README_EN.md @@ -40,15 +40,9 @@ ## Solutions - - -**Solution 1: Mathematics** - -The hour hand moves 30 degrees every hour and an additional 0.5 degrees for each minute. The minute hand moves 6 degrees every minute. If the angle between the hands is greater than 180 degrees, take its difference from 360 degrees to ensure the smallest angle is obtained. - -The time complexity is $O(1)$ and the space complexity is $O(1)$. +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +53,6 @@ class Solution: return min(diff, 360 - diff) ``` -### **Java** - ```java class Solution { public double angleClock(int hour, int minutes) { @@ -72,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -86,8 +76,6 @@ public: }; ``` -### **Go** - ```go func angleClock(hour int, minutes int) float64 { h := 30*float64(hour) + 0.5*float64(minutes) @@ -97,8 +85,6 @@ func angleClock(hour int, minutes int) float64 { } ``` -### **TypeScript** - ```ts function angleClock(hour: number, minutes: number): number { const h = 30 * hour + 0.5 * minutes; @@ -108,10 +94,6 @@ function angleClock(hour: number, minutes: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1345.Jump Game IV/README.md b/solution/1300-1399/1345.Jump Game IV/README.md index 1eef182c9c632..b9b3a7bf4fc79 100644 --- a/solution/1300-1399/1345.Jump Game IV/README.md +++ b/solution/1300-1399/1345.Jump Game IV/README.md @@ -58,14 +58,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minJumps(self, arr: List[int]) -> int: @@ -93,10 +89,6 @@ class Solution: q.append((i - 1, step)) ``` -### **Java** - - - ```java class Solution { public int minJumps(int[] arr) { @@ -138,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -181,8 +171,6 @@ public: }; ``` -### **Go** - ```go func minJumps(arr []int) int { idx := map[int][]int{} @@ -220,10 +208,6 @@ func minJumps(arr []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1345.Jump Game IV/README_EN.md b/solution/1300-1399/1345.Jump Game IV/README_EN.md index bed9424ff0677..beac7a8d46f3a 100644 --- a/solution/1300-1399/1345.Jump Game IV/README_EN.md +++ b/solution/1300-1399/1345.Jump Game IV/README_EN.md @@ -53,9 +53,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: q.append((i - 1, step)) ``` -### **Java** - ```java class Solution { public int minJumps(int[] arr) { @@ -127,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +166,6 @@ public: }; ``` -### **Go** - ```go func minJumps(arr []int) int { idx := map[int][]int{} @@ -209,10 +203,6 @@ func minJumps(arr []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/README.md b/solution/1300-1399/1346.Check If N and Its Double Exist/README.md index 01e7728c6eaf0..ee04854c8c5a6 100644 --- a/solution/1300-1399/1346.Check If N and Its Double Exist/README.md +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 使用哈希表 `m` 记录 `arr` 每个元素 `v` 及其对应的下标 `i`。 @@ -61,20 +59,8 @@ 时间复杂度:$O(n)$。 空间复杂度:$O(n)$。 -**方法二:排序 + 二分查找** - -首先对 `arr` 排序。 - -然后遍历 `arr` 每个元素 `v`,二分查找 `arr` 中是否存在 `v * 2` 元素,是则返回 `true`。 - -注意,元素可能为 0,这种情况下,`v*2` 的值同样为 0,二分查找可能会找到同个位置的元素,与题意不符。因此,可以预先统计 `arr` 中元素 0 的个数,若超过 1 个,可提前返回 `true`。 - -### **Python3** - - - ```python class Solution: def checkIfExist(self, arr: List[int]) -> bool: @@ -82,35 +68,6 @@ class Solution: return any(v << 1 in m and m[v << 1] != i for i, v in enumerate(arr)) ``` -```python -class Solution: - def checkIfExist(self, arr: List[int]) -> bool: - s = set() - for v in arr: - if v * 2 in s or (v % 2 == 0 and v // 2 in s): - return True - s.add(v) - return False -``` - -```python -class Solution: - def checkIfExist(self, arr: List[int]) -> bool: - if arr.count(0) > 1: - return True - arr.sort() - n = len(arr) - for v in arr: - idx = bisect_left(arr, v * 2) - if v != 0 and idx != n and arr[idx] == v * 2: - return True - return False -``` - -### **Java** - - - ```java class Solution { public boolean checkIfExist(int[] arr) { @@ -129,49 +86,6 @@ class Solution { } ``` -```java -class Solution { - public boolean checkIfExist(int[] arr) { - Set s = new HashSet<>(); - for (int v : arr) { - if (s.contains(v * 2) || (v % 2 == 0 && s.contains(v / 2))) { - return true; - } - s.add(v); - } - return false; - } -} -``` - -```java -class Solution { - public boolean checkIfExist(int[] arr) { - int cnt = 0; - for (int v : arr) { - if (v == 0) { - ++cnt; - if (cnt > 1) { - return true; - } - } - } - Arrays.sort(arr); - for (int v : arr) { - if (v != 0) { - int idx = Arrays.binarySearch(arr, v * 2); - if (idx >= 0) { - return true; - } - } - } - return false; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -187,44 +101,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool checkIfExist(vector& arr) { - unordered_set s; - for (int& v : arr) { - if (s.count(v * 2) || (v % 2 == 0 && s.count(v / 2))) { - return true; - } - s.insert(v); - } - return false; - } -}; -``` - -```cpp -class Solution { -public: - bool checkIfExist(vector& arr) { - int cnt = 0; - for (int& v : arr) - if (v == 0) ++cnt; - if (cnt > 1) return true; - sort(arr.begin(), arr.end()); - int n = arr.size(); - for (int& v : arr) { - if (v == 0) continue; - int idx = lower_bound(arr.begin(), arr.end(), v * 2) - arr.begin(); - if (idx != n && arr[idx] == v * 2) return true; - } - return false; - } -}; -``` - -### **Go** - ```go func checkIfExist(arr []int) bool { m := make(map[int]int) @@ -240,54 +116,6 @@ func checkIfExist(arr []int) bool { } ``` -```go -func checkIfExist(arr []int) bool { - s := map[int]bool{} - for _, v := range arr { - if s[v*2] || (v%2 == 0 && s[v/2]) { - return true - } - s[v] = true - } - return false -} -``` - -```go -func checkIfExist(arr []int) bool { - cnt := 0 - for _, v := range arr { - if v == 0 { - cnt++ - if cnt > 1 { - return true - } - } - } - sort.Ints(arr) - n := len(arr) - for _, v := range arr { - if v != 0 { - left, right := 0, n - for left < right { - mid := (left + right) >> 1 - if arr[mid] >= v*2 { - right = mid - } else { - left = mid + 1 - } - } - if right != n && arr[left] == v*2 { - return true - } - } - } - return false -} -``` - -### **TypeScript** - ```ts function checkIfExist(arr: number[]): boolean { const s = new Set(); @@ -301,42 +129,24 @@ function checkIfExist(arr: number[]): boolean { } ``` -```ts -function checkIfExist(arr: number[]): boolean { - let cnt = 0; - for (const v of arr) { - if (v == 0) { - ++cnt; - if (cnt > 1) { - return true; - } +```rust +use std::collections::HashMap; +impl Solution { + pub fn check_if_exist(arr: Vec) -> bool { + let mut map = HashMap::new(); + for (i, v) in arr.iter().enumerate() { + map.insert(v, i); } - } - const n = arr.length; - arr.sort((a, b) => a - b); - for (const v of arr) { - if (v != 0) { - let left = 0, - right = n; - while (left < right) { - const mid = (left + right) >> 1; - if (arr[mid] >= v * 2) { - right = mid; - } else { - left = mid + 1; - } - } - if (left != n && arr[left] == v * 2) { + for (i, v) in arr.iter().enumerate() { + if map.contains_key(&(v * 2)) && map[&(v * 2)] != i { return true; } } + false } - return false; } ``` -### **JavaScript** - ```js /** * @param {number[]} arr @@ -354,12 +164,95 @@ var checkIfExist = function (arr) { }; ``` -```js -/** - * @param {number[]} arr - * @return {boolean} - */ -var checkIfExist = function (arr) { +```php +class Solution { + /** + * @param Integer[] $arr + * @return Boolean + */ + function checkIfExist($arr) { + for ($i = 0; $i < count($arr); $i++) { + $hashtable[$arr[$i] * 2] = $i; + } + for ($i = 0; $i < count($arr); $i++) { + if (isset($hashtable[$arr[$i]]) && $hashtable[$arr[$i]] != $i) { + return true; + } + } + return false; + } +} +``` + + + +### 方法二:排序 + 二分查找 + +首先对 `arr` 排序。 + +然后遍历 `arr` 每个元素 `v`,二分查找 `arr` 中是否存在 `v * 2` 元素,是则返回 `true`。 + +注意,元素可能为 0,这种情况下,`v*2` 的值同样为 0,二分查找可能会找到同个位置的元素,与题意不符。因此,可以预先统计 `arr` 中元素 0 的个数,若超过 1 个,可提前返回 `true`。 + + + +```python +class Solution: + def checkIfExist(self, arr: List[int]) -> bool: + s = set() + for v in arr: + if v * 2 in s or (v % 2 == 0 and v // 2 in s): + return True + s.add(v) + return False +``` + +```java +class Solution { + public boolean checkIfExist(int[] arr) { + Set s = new HashSet<>(); + for (int v : arr) { + if (s.contains(v * 2) || (v % 2 == 0 && s.contains(v / 2))) { + return true; + } + s.add(v); + } + return false; + } +} +``` + +```cpp +class Solution { +public: + bool checkIfExist(vector& arr) { + unordered_set s; + for (int& v : arr) { + if (s.count(v * 2) || (v % 2 == 0 && s.count(v / 2))) { + return true; + } + s.insert(v); + } + return false; + } +}; +``` + +```go +func checkIfExist(arr []int) bool { + s := map[int]bool{} + for _, v := range arr { + if s[v*2] || (v%2 == 0 && s[v/2]) { + return true + } + s[v] = true + } + return false +} +``` + +```ts +function checkIfExist(arr: number[]): boolean { let cnt = 0; for (const v of arr) { if (v == 0) { @@ -389,26 +282,6 @@ var checkIfExist = function (arr) { } } return false; -}; -``` - -### **Rust** - -```rust -use std::collections::HashMap; -impl Solution { - pub fn check_if_exist(arr: Vec) -> bool { - let mut map = HashMap::new(); - for (i, v) in arr.iter().enumerate() { - map.insert(v, i); - } - for (i, v) in arr.iter().enumerate() { - if map.contains_key(&(v * 2)) && map[&(v * 2)] != i { - return true; - } - } - false - } } ``` @@ -445,21 +318,83 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {number[]} arr + * @return {boolean} + */ +var checkIfExist = function (arr) { + let cnt = 0; + for (const v of arr) { + if (v == 0) { + ++cnt; + if (cnt > 1) { + return true; + } + } + } + const n = arr.length; + arr.sort((a, b) => a - b); + for (const v of arr) { + if (v != 0) { + let left = 0, + right = n; + while (left < right) { + const mid = (left + right) >> 1; + if (arr[mid] >= v * 2) { + right = mid; + } else { + left = mid + 1; + } + } + if (left != n && arr[left] == v * 2) { + return true; + } + } + } + return false; +}; +``` + + + +### 方法三 -```php + + +```python +class Solution: + def checkIfExist(self, arr: List[int]) -> bool: + if arr.count(0) > 1: + return True + arr.sort() + n = len(arr) + for v in arr: + idx = bisect_left(arr, v * 2) + if v != 0 and idx != n and arr[idx] == v * 2: + return True + return False +``` + +```java class Solution { - /** - * @param Integer[] $arr - * @return Boolean - */ - function checkIfExist($arr) { - for ($i = 0; $i < count($arr); $i++) { - $hashtable[$arr[$i] * 2] = $i; + public boolean checkIfExist(int[] arr) { + int cnt = 0; + for (int v : arr) { + if (v == 0) { + ++cnt; + if (cnt > 1) { + return true; + } + } } - for ($i = 0; $i < count($arr); $i++) { - if (isset($hashtable[$arr[$i]]) && $hashtable[$arr[$i]] != $i) { - return true; + Arrays.sort(arr); + for (int v : arr) { + if (v != 0) { + int idx = Arrays.binarySearch(arr, v * 2); + if (idx >= 0) { + return true; + } } } return false; @@ -467,10 +402,59 @@ class Solution { } ``` -### **...** - +```cpp +class Solution { +public: + bool checkIfExist(vector& arr) { + int cnt = 0; + for (int& v : arr) + if (v == 0) ++cnt; + if (cnt > 1) return true; + sort(arr.begin(), arr.end()); + int n = arr.size(); + for (int& v : arr) { + if (v == 0) continue; + int idx = lower_bound(arr.begin(), arr.end(), v * 2) - arr.begin(); + if (idx != n && arr[idx] == v * 2) return true; + } + return false; + } +}; ``` +```go +func checkIfExist(arr []int) bool { + cnt := 0 + for _, v := range arr { + if v == 0 { + cnt++ + if cnt > 1 { + return true + } + } + } + sort.Ints(arr) + n := len(arr) + for _, v := range arr { + if v != 0 { + left, right := 0, n + for left < right { + mid := (left + right) >> 1 + if arr[mid] >= v*2 { + right = mid + } else { + left = mid + 1 + } + } + if right != n && arr[left] == v*2 { + return true + } + } + } + return false +} ``` + + diff --git a/solution/1300-1399/1346.Check If N and Its Double Exist/README_EN.md b/solution/1300-1399/1346.Check If N and Its Double Exist/README_EN.md index 4cc61f59b5f3d..d7832c70f35f4 100644 --- a/solution/1300-1399/1346.Check If N and Its Double Exist/README_EN.md +++ b/solution/1300-1399/1346.Check If N and Its Double Exist/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -50,33 +50,6 @@ class Solution: return any(v << 1 in m and m[v << 1] != i for i, v in enumerate(arr)) ``` -```python -class Solution: - def checkIfExist(self, arr: List[int]) -> bool: - s = set() - for v in arr: - if v * 2 in s or (v % 2 == 0 and v // 2 in s): - return True - s.add(v) - return False -``` - -```python -class Solution: - def checkIfExist(self, arr: List[int]) -> bool: - if arr.count(0) > 1: - return True - arr.sort() - n = len(arr) - for v in arr: - idx = bisect_left(arr, v * 2) - if v != 0 and idx != n and arr[idx] == v * 2: - return True - return False -``` - -### **Java** - ```java class Solution { public boolean checkIfExist(int[] arr) { @@ -95,49 +68,6 @@ class Solution { } ``` -```java -class Solution { - public boolean checkIfExist(int[] arr) { - Set s = new HashSet<>(); - for (int v : arr) { - if (s.contains(v * 2) || (v % 2 == 0 && s.contains(v / 2))) { - return true; - } - s.add(v); - } - return false; - } -} -``` - -```java -class Solution { - public boolean checkIfExist(int[] arr) { - int cnt = 0; - for (int v : arr) { - if (v == 0) { - ++cnt; - if (cnt > 1) { - return true; - } - } - } - Arrays.sort(arr); - for (int v : arr) { - if (v != 0) { - int idx = Arrays.binarySearch(arr, v * 2); - if (idx >= 0) { - return true; - } - } - } - return false; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -153,44 +83,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool checkIfExist(vector& arr) { - unordered_set s; - for (int& v : arr) { - if (s.count(v * 2) || (v % 2 == 0 && s.count(v / 2))) { - return true; - } - s.insert(v); - } - return false; - } -}; -``` - -```cpp -class Solution { -public: - bool checkIfExist(vector& arr) { - int cnt = 0; - for (int& v : arr) - if (v == 0) ++cnt; - if (cnt > 1) return true; - sort(arr.begin(), arr.end()); - int n = arr.size(); - for (int& v : arr) { - if (v == 0) continue; - int idx = lower_bound(arr.begin(), arr.end(), v * 2) - arr.begin(); - if (idx != n && arr[idx] == v * 2) return true; - } - return false; - } -}; -``` - -### **Go** - ```go func checkIfExist(arr []int) bool { m := make(map[int]int) @@ -206,54 +98,6 @@ func checkIfExist(arr []int) bool { } ``` -```go -func checkIfExist(arr []int) bool { - s := map[int]bool{} - for _, v := range arr { - if s[v*2] || (v%2 == 0 && s[v/2]) { - return true - } - s[v] = true - } - return false -} -``` - -```go -func checkIfExist(arr []int) bool { - cnt := 0 - for _, v := range arr { - if v == 0 { - cnt++ - if cnt > 1 { - return true - } - } - } - sort.Ints(arr) - n := len(arr) - for _, v := range arr { - if v != 0 { - left, right := 0, n - for left < right { - mid := (left + right) >> 1 - if arr[mid] >= v*2 { - right = mid - } else { - left = mid + 1 - } - } - if right != n && arr[left] == v*2 { - return true - } - } - } - return false -} -``` - -### **TypeScript** - ```ts function checkIfExist(arr: number[]): boolean { const s = new Set(); @@ -267,42 +111,24 @@ function checkIfExist(arr: number[]): boolean { } ``` -```ts -function checkIfExist(arr: number[]): boolean { - let cnt = 0; - for (const v of arr) { - if (v == 0) { - ++cnt; - if (cnt > 1) { - return true; - } +```rust +use std::collections::HashMap; +impl Solution { + pub fn check_if_exist(arr: Vec) -> bool { + let mut map = HashMap::new(); + for (i, v) in arr.iter().enumerate() { + map.insert(v, i); } - } - const n = arr.length; - arr.sort((a, b) => a - b); - for (const v of arr) { - if (v != 0) { - let left = 0, - right = n; - while (left < right) { - const mid = (left + right) >> 1; - if (arr[mid] >= v * 2) { - right = mid; - } else { - left = mid + 1; - } - } - if (left != n && arr[left] == v * 2) { + for (i, v) in arr.iter().enumerate() { + if map.contains_key(&(v * 2)) && map[&(v * 2)] != i { return true; } } + false } - return false; } ``` -### **JavaScript** - ```js /** * @param {number[]} arr @@ -320,12 +146,89 @@ var checkIfExist = function (arr) { }; ``` -```js -/** - * @param {number[]} arr - * @return {boolean} - */ -var checkIfExist = function (arr) { +```php +class Solution { + /** + * @param Integer[] $arr + * @return Boolean + */ + function checkIfExist($arr) { + for ($i = 0; $i < count($arr); $i++) { + $hashtable[$arr[$i] * 2] = $i; + } + for ($i = 0; $i < count($arr); $i++) { + if (isset($hashtable[$arr[$i]]) && $hashtable[$arr[$i]] != $i) { + return true; + } + } + return false; + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def checkIfExist(self, arr: List[int]) -> bool: + s = set() + for v in arr: + if v * 2 in s or (v % 2 == 0 and v // 2 in s): + return True + s.add(v) + return False +``` + +```java +class Solution { + public boolean checkIfExist(int[] arr) { + Set s = new HashSet<>(); + for (int v : arr) { + if (s.contains(v * 2) || (v % 2 == 0 && s.contains(v / 2))) { + return true; + } + s.add(v); + } + return false; + } +} +``` + +```cpp +class Solution { +public: + bool checkIfExist(vector& arr) { + unordered_set s; + for (int& v : arr) { + if (s.count(v * 2) || (v % 2 == 0 && s.count(v / 2))) { + return true; + } + s.insert(v); + } + return false; + } +}; +``` + +```go +func checkIfExist(arr []int) bool { + s := map[int]bool{} + for _, v := range arr { + if s[v*2] || (v%2 == 0 && s[v/2]) { + return true + } + s[v] = true + } + return false +} +``` + +```ts +function checkIfExist(arr: number[]): boolean { let cnt = 0; for (const v of arr) { if (v == 0) { @@ -355,26 +258,6 @@ var checkIfExist = function (arr) { } } return false; -}; -``` - -### **Rust** - -```rust -use std::collections::HashMap; -impl Solution { - pub fn check_if_exist(arr: Vec) -> bool { - let mut map = HashMap::new(); - for (i, v) in arr.iter().enumerate() { - map.insert(v, i); - } - for (i, v) in arr.iter().enumerate() { - if map.contains_key(&(v * 2)) && map[&(v * 2)] != i { - return true; - } - } - false - } } ``` @@ -411,21 +294,83 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {number[]} arr + * @return {boolean} + */ +var checkIfExist = function (arr) { + let cnt = 0; + for (const v of arr) { + if (v == 0) { + ++cnt; + if (cnt > 1) { + return true; + } + } + } + const n = arr.length; + arr.sort((a, b) => a - b); + for (const v of arr) { + if (v != 0) { + let left = 0, + right = n; + while (left < right) { + const mid = (left + right) >> 1; + if (arr[mid] >= v * 2) { + right = mid; + } else { + left = mid + 1; + } + } + if (left != n && arr[left] == v * 2) { + return true; + } + } + } + return false; +}; +``` + + -```php +### Solution 3 + + + +```python +class Solution: + def checkIfExist(self, arr: List[int]) -> bool: + if arr.count(0) > 1: + return True + arr.sort() + n = len(arr) + for v in arr: + idx = bisect_left(arr, v * 2) + if v != 0 and idx != n and arr[idx] == v * 2: + return True + return False +``` + +```java class Solution { - /** - * @param Integer[] $arr - * @return Boolean - */ - function checkIfExist($arr) { - for ($i = 0; $i < count($arr); $i++) { - $hashtable[$arr[$i] * 2] = $i; + public boolean checkIfExist(int[] arr) { + int cnt = 0; + for (int v : arr) { + if (v == 0) { + ++cnt; + if (cnt > 1) { + return true; + } + } } - for ($i = 0; $i < count($arr); $i++) { - if (isset($hashtable[$arr[$i]]) && $hashtable[$arr[$i]] != $i) { - return true; + Arrays.sort(arr); + for (int v : arr) { + if (v != 0) { + int idx = Arrays.binarySearch(arr, v * 2); + if (idx >= 0) { + return true; + } } } return false; @@ -433,10 +378,59 @@ class Solution { } ``` -### **...** - +```cpp +class Solution { +public: + bool checkIfExist(vector& arr) { + int cnt = 0; + for (int& v : arr) + if (v == 0) ++cnt; + if (cnt > 1) return true; + sort(arr.begin(), arr.end()); + int n = arr.size(); + for (int& v : arr) { + if (v == 0) continue; + int idx = lower_bound(arr.begin(), arr.end(), v * 2) - arr.begin(); + if (idx != n && arr[idx] == v * 2) return true; + } + return false; + } +}; ``` +```go +func checkIfExist(arr []int) bool { + cnt := 0 + for _, v := range arr { + if v == 0 { + cnt++ + if cnt > 1 { + return true + } + } + } + sort.Ints(arr) + n := len(arr) + for _, v := range arr { + if v != 0 { + left, right := 0, n + for left < right { + mid := (left + right) >> 1 + if arr[mid] >= v*2 { + right = mid + } else { + left = mid + 1 + } + } + if right != n && arr[left] == v*2 { + return true + } + } + } + return false +} ``` + + diff --git a/solution/1300-1399/1347.Minimum Number of Steps to Make Two Strings Anagram/README.md b/solution/1300-1399/1347.Minimum Number of Steps to Make Two Strings Anagram/README.md index ca8cc5c5a1e0d..a1164af6811c8 100644 --- a/solution/1300-1399/1347.Minimum Number of Steps to Make Two Strings Anagram/README.md +++ b/solution/1300-1399/1347.Minimum Number of Steps to Make Two Strings Anagram/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:数组或哈希表** +### 方法一:数组或哈希表 我们可以使用数组或哈希表 `cnt` 统计字符串 $s$ 中每个字符出现的次数,然后遍历字符串 $t$,对于 $t$ 中的每个字符,如果 $cnt$ 中对应的字符出现的次数大于 $0$,则将 $cnt$ 中对应的字符出现的次数减 $1$,否则将答案加 $1$。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def minSteps(self, s: str, t: str) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minSteps(String s, String t) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func minSteps(s string, t string) (ans int) { cnt := [26]int{} @@ -143,8 +129,6 @@ func minSteps(s string, t string) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -166,10 +150,6 @@ var minSteps = function (s, t) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1347.Minimum Number of Steps to Make Two Strings Anagram/README_EN.md b/solution/1300-1399/1347.Minimum Number of Steps to Make Two Strings Anagram/README_EN.md index b8be2ccde5dd7..76a5bdbb8908c 100644 --- a/solution/1300-1399/1347.Minimum Number of Steps to Make Two Strings Anagram/README_EN.md +++ b/solution/1300-1399/1347.Minimum Number of Steps to Make Two Strings Anagram/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minSteps(String s, String t) { @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +96,6 @@ public: }; ``` -### **Go** - ```go func minSteps(s string, t string) (ans int) { cnt := [26]int{} @@ -118,8 +112,6 @@ func minSteps(s string, t string) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -141,10 +133,6 @@ var minSteps = function (s, t) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1348.Tweet Counts Per Frequency/README.md b/solution/1300-1399/1348.Tweet Counts Per Frequency/README.md index 1c54a74b741ec..c8b855af05735 100644 --- a/solution/1300-1399/1348.Tweet Counts Per Frequency/README.md +++ b/solution/1300-1399/1348.Tweet Counts Per Frequency/README.md @@ -69,9 +69,7 @@ tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // 返 ## 解法 - - -**方法一:哈希表 + 有序列表** +### 方法一:哈希表 + 有序列表 我们用哈希表 `data` 记录每个用户的推文时间,用有序列表记录每个用户的所有推文时间。 @@ -83,10 +81,6 @@ tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // 返 -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -120,10 +114,6 @@ class TweetCounts: # param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime) ``` -### **Java** - - - ```java class TweetCounts { private Map> data = new HashMap<>(); @@ -167,8 +157,6 @@ class TweetCounts { */ ``` -### **C++** - ```cpp class TweetCounts { public: @@ -206,10 +194,6 @@ private: */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1348.Tweet Counts Per Frequency/README_EN.md b/solution/1300-1399/1348.Tweet Counts Per Frequency/README_EN.md index 4428cd316b157..4ed10ab19277c 100644 --- a/solution/1300-1399/1348.Tweet Counts Per Frequency/README_EN.md +++ b/solution/1300-1399/1348.Tweet Counts Per Frequency/README_EN.md @@ -63,9 +63,9 @@ tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedList @@ -100,8 +100,6 @@ class TweetCounts: # param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime) ``` -### **Java** - ```java class TweetCounts { private Map> data = new HashMap<>(); @@ -145,8 +143,6 @@ class TweetCounts { */ ``` -### **C++** - ```cpp class TweetCounts { public: @@ -184,10 +180,6 @@ private: */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1349.Maximum Students Taking Exam/README.md b/solution/1300-1399/1349.Maximum Students Taking Exam/README.md index db18853066ad0..8d0174e1b227b 100644 --- a/solution/1300-1399/1349.Maximum Students Taking Exam/README.md +++ b/solution/1300-1399/1349.Maximum Students Taking Exam/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:状态压缩 + 记忆化搜索** +### 方法一:状态压缩 + 记忆化搜索 我们注意到,每个座位有两种状态:可选和不可选。因此,我们可以使用二进制数来表示每一行的座位状态,其中 $1$ 表示可选,而 $0$ 表示不可选。例如,对于示例 $1$ 中的第一行,我们可以表示为 $010010$。因此,我们将初始座位转换为一个一维数组 $ss$,其中 $ss[i]$ 表示第 $i$ 行的座位状态。 @@ -87,10 +85,6 @@ -### **Python3** - - - ```python class Solution: def maxStudents(self, seats: List[List[str]]) -> int: @@ -122,10 +116,6 @@ class Solution: return dfs(ss[0], 0) ``` -### **Java** - - - ```java class Solution { private Integer[][] f; @@ -171,8 +161,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -214,8 +202,6 @@ public: }; ``` -### **Go** - ```go func maxStudents(seats [][]byte) int { m, n := len(seats), len(seats[0]) @@ -259,8 +245,6 @@ func maxStudents(seats [][]byte) int { } ``` -### **TypeScript** - ```ts function maxStudents(seats: string[][]): number { const m: number = seats.length; @@ -300,10 +284,6 @@ function maxStudents(seats: string[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1349.Maximum Students Taking Exam/README_EN.md b/solution/1300-1399/1349.Maximum Students Taking Exam/README_EN.md index a9acfd0c68336..c8572c61233be 100644 --- a/solution/1300-1399/1349.Maximum Students Taking Exam/README_EN.md +++ b/solution/1300-1399/1349.Maximum Students Taking Exam/README_EN.md @@ -59,7 +59,7 @@ ## Solutions -**Solution 1: State Compression + Memoization Search** +### Solution 1: State Compression + Memoization Search We notice that each seat has two states: selectable and non-selectable. Therefore, we can use a binary number to represent the seat state of each row, where $1$ represents selectable, and $0$ represents non-selectable. For example, for the first row in Example 1, we can represent it as $010010$. Therefore, we convert the initial seats into a one-dimensional array $ss$, where $ss[i]$ represents the seat state of the $i$th row. @@ -80,8 +80,6 @@ The time complexity is $O(4^n \times n \times m)$, and the space complexity is $ -### **Python3** - ```python class Solution: def maxStudents(self, seats: List[List[str]]) -> int: @@ -113,8 +111,6 @@ class Solution: return dfs(ss[0], 0) ``` -### **Java** - ```java class Solution { private Integer[][] f; @@ -160,8 +156,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -203,8 +197,6 @@ public: }; ``` -### **Go** - ```go func maxStudents(seats [][]byte) int { m, n := len(seats), len(seats[0]) @@ -248,8 +240,6 @@ func maxStudents(seats [][]byte) int { } ``` -### **TypeScript** - ```ts function maxStudents(seats: string[][]): number { const m: number = seats.length; @@ -289,10 +279,6 @@ function maxStudents(seats: string[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1350.Students With Invalid Departments/README.md b/solution/1300-1399/1350.Students With Invalid Departments/README.md index e12607ab96966..badad9f6a2440 100644 --- a/solution/1300-1399/1350.Students With Invalid Departments/README.md +++ b/solution/1300-1399/1350.Students With Invalid Departments/README.md @@ -86,20 +86,12 @@ John, Daiana, Steve 和 Jasmine 所在的院系分别是 14, 33, 74 和 77, ## 解法 - - -**方法一:子查询** +### 方法一:子查询 我们直接使用子查询的方式,找出所有不在院系表中的学生即可。 -**方法二:左连接** - -我们也可以使用左连接,将 `Students` 表和 `Departments` 连接,连接条件为 `Students.department_id = Departments.id`,然后筛选出 `Departments.id` 为空的学生即可。 - -### **SQL** - ```sql # Write your MySQL query statement below SELECT id, name @@ -107,6 +99,14 @@ FROM Students WHERE department_id NOT IN (SELECT id FROM Departments); ``` + + +### 方法二:左连接 + +我们也可以使用左连接,将 `Students` 表和 `Departments` 连接,连接条件为 `Students.department_id = Departments.id`,然后筛选出 `Departments.id` 为空的学生即可。 + + + ```sql # Write your MySQL query statement below SELECT s.id, s.name @@ -117,3 +117,5 @@ WHERE d.id IS NULL; ``` + + diff --git a/solution/1300-1399/1350.Students With Invalid Departments/README_EN.md b/solution/1300-1399/1350.Students With Invalid Departments/README_EN.md index d4abf09ef27d4..df24b0161e3d3 100644 --- a/solution/1300-1399/1350.Students With Invalid Departments/README_EN.md +++ b/solution/1300-1399/1350.Students With Invalid Departments/README_EN.md @@ -84,18 +84,12 @@ John, Daiana, Steve, and Jasmine are enrolled in departments 14, 33, 74, and 77 ## Solutions -**Solution 1: Subquery** +### Solution 1: Subquery We can directly use a subquery to find all students who are not in the `Departments` table. -**Solution 2: Left Join** - -We can also use a left join to join the `Students` table with the `Departments` table on the condition of `Students.department_id = Departments.id`, and then filter out the students whose `Departments.id` is `NULL`. - -### **SQL** - ```sql # Write your MySQL query statement below SELECT id, name @@ -103,6 +97,14 @@ FROM Students WHERE department_id NOT IN (SELECT id FROM Departments); ``` + + +### Solution 2: Left Join + +We can also use a left join to join the `Students` table with the `Departments` table on the condition of `Students.department_id = Departments.id`, and then filter out the students whose `Departments.id` is `NULL`. + + + ```sql # Write your MySQL query statement below SELECT s.id, s.name @@ -113,3 +115,5 @@ WHERE d.id IS NULL; ``` + + diff --git a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/README.md b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/README.md index e853505763d36..99e399a6a01d5 100644 --- a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/README.md +++ b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:从左下角或右上角开始遍历** +### 方法一:从左下角或右上角开始遍历 根据**其行列都以非递增顺序排列**的特点,可以从**左下角**开始**往右上方向遍历**。 @@ -54,20 +52,8 @@ 时间复杂度 $O(m + n)$,其中 $m$ 和 $n$ 分别为矩阵的行数和列数。空间复杂度 $O(1)$。 -**方法二:二分查找** - -遍历每一行,二分查找每一行第一个小于 $0$ 的位置,从该位置开始往右的所有元素均为负数,累加负数个数到答案中。 - -遍历结束,返回答案。 - -时间复杂度 $O(m \times \log n)$,其中 $m$ 和 $n$ 分别为矩阵的行数和列数。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def countNegatives(self, grid: List[List[int]]) -> int: @@ -83,16 +69,6 @@ class Solution: return ans ``` -```python -class Solution: - def countNegatives(self, grid: List[List[int]]) -> int: - return sum(bisect_left(row[::-1], 0) for row in grid) -``` - -### **Java** - - - ```java class Solution { public int countNegatives(int[][] grid) { @@ -111,30 +87,6 @@ class Solution { } ``` -```java -class Solution { - public int countNegatives(int[][] grid) { - int ans = 0; - int n = grid[0].length; - for (int[] row : grid) { - int left = 0, right = n; - while (left < right) { - int mid = (left + right) >> 1; - if (row[mid] < 0) { - right = mid; - } else { - left = mid + 1; - } - } - ans += n - left; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -153,21 +105,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countNegatives(vector>& grid) { - int ans = 0; - for (auto& row : grid) { - ans += lower_bound(row.rbegin(), row.rend(), 0) - row.rbegin(); - } - return ans; - } -}; -``` - -### **Go** - ```go func countNegatives(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -184,27 +121,6 @@ func countNegatives(grid [][]int) int { } ``` -```go -func countNegatives(grid [][]int) int { - ans, n := 0, len(grid[0]) - for _, row := range grid { - left, right := 0, n - for left < right { - mid := (left + right) >> 1 - if row[mid] < 0 { - right = mid - } else { - left = mid + 1 - } - } - ans += n - left - } - return ans -} -``` - -### **TypeScript** - ```ts function countNegatives(grid: number[][]): number { const m = grid.length, @@ -222,29 +138,29 @@ function countNegatives(grid: number[][]): number { } ``` -```ts -function countNegatives(grid: number[][]): number { - const n = grid[0].length; - let ans = 0; - for (let row of grid) { - let left = 0, - right = n; - while (left < right) { - const mid = (left + right) >> 1; - if (row[mid] < 0) { - right = mid; - } else { - left = mid + 1; - } - } - ans += n - left; +```rust +impl Solution { + pub fn count_negatives(grid: Vec>) -> i32 { + let n = grid[0].len(); + grid.into_iter() + .map(|nums| { + let mut left = 0; + let mut right = n; + while left < right { + let mid = left + (right - left) / 2; + if nums[mid] >= 0 { + left = mid + 1; + } else { + right = mid; + } + } + (n - left) as i32 + }) + .sum() } - return ans; } ``` -### **JavaScript** - ```js /** * @param {number[][]} grid @@ -266,12 +182,80 @@ var countNegatives = function (grid) { }; ``` -```js -/** - * @param {number[][]} grid - * @return {number} - */ -var countNegatives = function (grid) { + + +### 方法二:二分查找 + +遍历每一行,二分查找每一行第一个小于 $0$ 的位置,从该位置开始往右的所有元素均为负数,累加负数个数到答案中。 + +遍历结束,返回答案。 + +时间复杂度 $O(m \times \log n)$,其中 $m$ 和 $n$ 分别为矩阵的行数和列数。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def countNegatives(self, grid: List[List[int]]) -> int: + return sum(bisect_left(row[::-1], 0) for row in grid) +``` + +```java +class Solution { + public int countNegatives(int[][] grid) { + int ans = 0; + int n = grid[0].length; + for (int[] row : grid) { + int left = 0, right = n; + while (left < right) { + int mid = (left + right) >> 1; + if (row[mid] < 0) { + right = mid; + } else { + left = mid + 1; + } + } + ans += n - left; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int countNegatives(vector>& grid) { + int ans = 0; + for (auto& row : grid) { + ans += lower_bound(row.rbegin(), row.rend(), 0) - row.rbegin(); + } + return ans; + } +}; +``` + +```go +func countNegatives(grid [][]int) int { + ans, n := 0, len(grid[0]) + for _, row := range grid { + left, right := 0, n + for left < right { + mid := (left + right) >> 1 + if row[mid] < 0 { + right = mid + } else { + left = mid + 1 + } + } + ans += n - left + } + return ans +} +``` + +```ts +function countNegatives(grid: number[][]): number { const n = grid[0].length; let ans = 0; for (let row of grid) { @@ -288,31 +272,6 @@ var countNegatives = function (grid) { ans += n - left; } return ans; -}; -``` - -### **Rust** - -```rust -impl Solution { - pub fn count_negatives(grid: Vec>) -> i32 { - let n = grid[0].len(); - grid.into_iter() - .map(|nums| { - let mut left = 0; - let mut right = n; - while left < right { - let mid = left + (right - left) / 2; - if nums[mid] >= 0 { - left = mid + 1; - } else { - right = mid; - } - } - (n - left) as i32 - }) - .sum() - } } ``` @@ -337,10 +296,31 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[][]} grid + * @return {number} + */ +var countNegatives = function (grid) { + const n = grid[0].length; + let ans = 0; + for (let row of grid) { + let left = 0, + right = n; + while (left < right) { + const mid = (left + right) >> 1; + if (row[mid] < 0) { + right = mid; + } else { + left = mid + 1; + } + } + ans += n - left; + } + return ans; +}; ``` + + diff --git a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/README_EN.md b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/README_EN.md index 6f09fff42c088..fa05b34c93c34 100644 --- a/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/README_EN.md +++ b/solution/1300-1399/1351.Count Negative Numbers in a Sorted Matrix/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: Start Traversing from the Bottom Left or Top Right** +### Solution 1: Start Traversing from the Bottom Left or Top Right According to the characteristic that **both rows and columns are arranged in non-increasing order**, we can start traversing from the **bottom left corner** towards the **top right direction**. @@ -47,18 +47,8 @@ After the traversal is over, return the answer. The time complexity is $O(m + n)$, where $m$ and $n$ are the number of rows and columns of the matrix, respectively. The space complexity is $O(1)$. -**Solution 2: Binary Search** - -Traverse each row, use binary search to find the first position less than $0$ in each row. All elements to the right of this position are negative, and add the number of negative numbers to the answer. - -After the traversal is over, return the answer. - -The time complexity is $O(m \times \log 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 countNegatives(self, grid: List[List[int]]) -> int: @@ -74,14 +64,6 @@ class Solution: return ans ``` -```python -class Solution: - def countNegatives(self, grid: List[List[int]]) -> int: - return sum(bisect_left(row[::-1], 0) for row in grid) -``` - -### **Java** - ```java class Solution { public int countNegatives(int[][] grid) { @@ -100,30 +82,6 @@ class Solution { } ``` -```java -class Solution { - public int countNegatives(int[][] grid) { - int ans = 0; - int n = grid[0].length; - for (int[] row : grid) { - int left = 0, right = n; - while (left < right) { - int mid = (left + right) >> 1; - if (row[mid] < 0) { - right = mid; - } else { - left = mid + 1; - } - } - ans += n - left; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -142,21 +100,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countNegatives(vector>& grid) { - int ans = 0; - for (auto& row : grid) { - ans += lower_bound(row.rbegin(), row.rend(), 0) - row.rbegin(); - } - return ans; - } -}; -``` - -### **Go** - ```go func countNegatives(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -173,27 +116,6 @@ func countNegatives(grid [][]int) int { } ``` -```go -func countNegatives(grid [][]int) int { - ans, n := 0, len(grid[0]) - for _, row := range grid { - left, right := 0, n - for left < right { - mid := (left + right) >> 1 - if row[mid] < 0 { - right = mid - } else { - left = mid + 1 - } - } - ans += n - left - } - return ans -} -``` - -### **TypeScript** - ```ts function countNegatives(grid: number[][]): number { const m = grid.length, @@ -211,29 +133,29 @@ function countNegatives(grid: number[][]): number { } ``` -```ts -function countNegatives(grid: number[][]): number { - const n = grid[0].length; - let ans = 0; - for (let row of grid) { - let left = 0, - right = n; - while (left < right) { - const mid = (left + right) >> 1; - if (row[mid] < 0) { - right = mid; - } else { - left = mid + 1; - } - } - ans += n - left; +```rust +impl Solution { + pub fn count_negatives(grid: Vec>) -> i32 { + let n = grid[0].len(); + grid.into_iter() + .map(|nums| { + let mut left = 0; + let mut right = n; + while left < right { + let mid = left + (right - left) / 2; + if nums[mid] >= 0 { + left = mid + 1; + } else { + right = mid; + } + } + (n - left) as i32 + }) + .sum() } - return ans; } ``` -### **JavaScript** - ```js /** * @param {number[][]} grid @@ -255,12 +177,80 @@ var countNegatives = function (grid) { }; ``` -```js -/** - * @param {number[][]} grid - * @return {number} - */ -var countNegatives = function (grid) { + + +### Solution 2: Binary Search + +Traverse each row, use binary search to find the first position less than $0$ in each row. All elements to the right of this position are negative, and add the number of negative numbers to the answer. + +After the traversal is over, return the answer. + +The time complexity is $O(m \times \log 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 countNegatives(self, grid: List[List[int]]) -> int: + return sum(bisect_left(row[::-1], 0) for row in grid) +``` + +```java +class Solution { + public int countNegatives(int[][] grid) { + int ans = 0; + int n = grid[0].length; + for (int[] row : grid) { + int left = 0, right = n; + while (left < right) { + int mid = (left + right) >> 1; + if (row[mid] < 0) { + right = mid; + } else { + left = mid + 1; + } + } + ans += n - left; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int countNegatives(vector>& grid) { + int ans = 0; + for (auto& row : grid) { + ans += lower_bound(row.rbegin(), row.rend(), 0) - row.rbegin(); + } + return ans; + } +}; +``` + +```go +func countNegatives(grid [][]int) int { + ans, n := 0, len(grid[0]) + for _, row := range grid { + left, right := 0, n + for left < right { + mid := (left + right) >> 1 + if row[mid] < 0 { + right = mid + } else { + left = mid + 1 + } + } + ans += n - left + } + return ans +} +``` + +```ts +function countNegatives(grid: number[][]): number { const n = grid[0].length; let ans = 0; for (let row of grid) { @@ -277,31 +267,6 @@ var countNegatives = function (grid) { ans += n - left; } return ans; -}; -``` - -### **Rust** - -```rust -impl Solution { - pub fn count_negatives(grid: Vec>) -> i32 { - let n = grid[0].len(); - grid.into_iter() - .map(|nums| { - let mut left = 0; - let mut right = n; - while left < right { - let mid = left + (right - left) / 2; - if nums[mid] >= 0 { - left = mid + 1; - } else { - right = mid; - } - } - (n - left) as i32 - }) - .sum() - } } ``` @@ -326,10 +291,31 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[][]} grid + * @return {number} + */ +var countNegatives = function (grid) { + const n = grid[0].length; + let ans = 0; + for (let row of grid) { + let left = 0, + right = n; + while (left < right) { + const mid = (left + right) >> 1; + if (row[mid] < 0) { + right = mid; + } else { + left = mid + 1; + } + } + ans += n - left; + } + return ans; +}; ``` + + diff --git a/solution/1300-1399/1352.Product of the Last K Numbers/README.md b/solution/1300-1399/1352.Product of the Last K Numbers/README.md index c220331f67606..b3ce4e4b8cd8a 100644 --- a/solution/1300-1399/1352.Product of the Last K Numbers/README.md +++ b/solution/1300-1399/1352.Product of the Last K Numbers/README.md @@ -60,9 +60,7 @@ productOfNumbers.getProduct(2); // 返回 32 。最后 2 个数字的乘积是 4 ## 解法 - - -**方法一:前缀积** +### 方法一:前缀积 我们初始化一个数组 $s$,其中 $s[i]$ 表示前 $i$ 个数字的乘积。 @@ -74,10 +72,6 @@ productOfNumbers.getProduct(2); // 返回 32 。最后 2 个数字的乘积是 4 -### **Python3** - - - ```python class ProductOfNumbers: def __init__(self): @@ -99,10 +93,6 @@ class ProductOfNumbers: # param_2 = obj.getProduct(k) ``` -### **Java** - - - ```java class ProductOfNumbers { private List s = new ArrayList<>(); @@ -134,8 +124,6 @@ class ProductOfNumbers { */ ``` -### **C++** - ```cpp class ProductOfNumbers { public: @@ -169,8 +157,6 @@ private: */ ``` -### **Go** - ```go type ProductOfNumbers struct { s []int @@ -204,10 +190,6 @@ func (this *ProductOfNumbers) GetProduct(k int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1352.Product of the Last K Numbers/README_EN.md b/solution/1300-1399/1352.Product of the Last K Numbers/README_EN.md index 4b965fd8a45df..547e5cd8fe050 100644 --- a/solution/1300-1399/1352.Product of the Last K Numbers/README_EN.md +++ b/solution/1300-1399/1352.Product of the Last K Numbers/README_EN.md @@ -53,7 +53,7 @@ productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers ## Solutions -**Solution 1: Prefix Product** +### Solution 1: Prefix Product We initialize an array $s$, where $s[i]$ represents the product of the first $i$ numbers. @@ -65,8 +65,6 @@ The time complexity is $O(1)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class ProductOfNumbers: def __init__(self): @@ -88,8 +86,6 @@ class ProductOfNumbers: # param_2 = obj.getProduct(k) ``` -### **Java** - ```java class ProductOfNumbers { private List s = new ArrayList<>(); @@ -121,8 +117,6 @@ class ProductOfNumbers { */ ``` -### **C++** - ```cpp class ProductOfNumbers { public: @@ -156,8 +150,6 @@ private: */ ``` -### **Go** - ```go type ProductOfNumbers struct { s []int @@ -191,10 +183,6 @@ func (this *ProductOfNumbers) GetProduct(k int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README.md b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README.md index ccccf888e54ec..a4d171023b3b5 100644 --- a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README.md +++ b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:哈希表 + 贪心 + 优先队列** +### 方法一:哈希表 + 贪心 + 优先队列 定义哈希表记录每个会议的开始和结束时间,其中键为会议开始时间,值为结束时间列表。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def maxEvents(self, events: List[List[int]]) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxEvents(int[][] events) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func maxEvents(events [][]int) int { d := map[int][]int{} @@ -195,10 +181,6 @@ func (h *hp) Pop() any { func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README_EN.md b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README_EN.md index 8ba50592951c2..925955f6f058a 100644 --- a/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README_EN.md +++ b/solution/1300-1399/1353.Maximum Number of Events That Can Be Attended/README_EN.md @@ -41,7 +41,7 @@ Attend the third event on day 3. ## Solutions -**Solution 1: Hash Table + Greedy + Priority Queue** +### Solution 1: Hash Table + Greedy + Priority Queue Define a hash table to record the start and end times of each meeting, where the key is the start time of the meeting, and the value is a list of end times. @@ -53,8 +53,6 @@ The time complexity is $O(m \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def maxEvents(self, events: List[List[int]]) -> int: @@ -77,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxEvents(int[][] events) { @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go func maxEvents(events [][]int) int { d := map[int][]int{} @@ -183,10 +175,6 @@ func (h *hp) Pop() any { func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README.md b/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README.md index b1b38f2374ae7..4ccd1a2158acc 100644 --- a/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README.md +++ b/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:逆向构造 + 优先队列(大根堆)** +### 方法一:逆向构造 + 优先队列(大根堆) 我们发现,如果从数组 $arr$ 开始正向构造目标数组 $target$,每次都不好确定选择哪个下标 $i$,问题比较复杂。而如果我们从数组 $target$ 开始逆向构造,每次构造都一定是选择当前数组中最大的元素,这样就可以保证每次构造都是唯一的,问题比较简单。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def isPossible(self, target: List[int]) -> bool: @@ -87,10 +81,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean isPossible(int[] target) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go func isPossible(target []int) bool { pq := &hp{target} @@ -183,8 +169,6 @@ func (hp) Pop() (_ any) { return } func (hp) Push(any) {} ``` -### **TypeScript** - ```ts function isPossible(target: number[]): boolean { const pq = new MaxPriorityQueue(); @@ -207,10 +191,6 @@ function isPossible(target: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README_EN.md b/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README_EN.md index bc21eff07856a..2e7573632ef6a 100644 --- a/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README_EN.md +++ b/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README_EN.md @@ -53,7 +53,7 @@ ## Solutions -**Solution 1: Reverse Construction + Priority Queue (Max Heap)** +### Solution 1: Reverse Construction + Priority Queue (Max Heap) We find that if we start from the array $arr$ and construct the target array $target$ forward, it is not easy to determine which index $i$ to choose each time, and the problem is relatively complex. However, if we start from the array $target$ and construct it in reverse, each construction must choose the largest element in the current array, which can ensure that each construction is unique, and the problem is relatively simple. @@ -63,8 +63,6 @@ The time complexity is $O(n \log n)$, and the space complexity is $O(n)$. Where -### **Python3** - ```python class Solution: def isPossible(self, target: List[int]) -> bool: @@ -82,8 +80,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean isPossible(int[] target) { @@ -111,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go func isPossible(target []int) bool { pq := &hp{target} @@ -176,8 +168,6 @@ func (hp) Pop() (_ any) { return } func (hp) Push(any) {} ``` -### **TypeScript** - ```ts function isPossible(target: number[]): boolean { const pq = new MaxPriorityQueue(); @@ -200,10 +190,6 @@ function isPossible(target: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1355.Activity Participants/README.md b/solution/1300-1399/1355.Activity Participants/README.md index b12d4e1466354..93a2802815055 100644 --- a/solution/1300-1399/1355.Activity Participants/README.md +++ b/solution/1300-1399/1355.Activity Participants/README.md @@ -84,12 +84,10 @@ Singing 活动有两个人参加 (Victor J. and Jade W.) ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -104,3 +102,5 @@ WHERE cnt > (SELECT MIN(cnt) FROM t) AND cnt < (SELECT MAX(cnt) FROM t); ``` + + diff --git a/solution/1300-1399/1355.Activity Participants/README_EN.md b/solution/1300-1399/1355.Activity Participants/README_EN.md index a1528a292eb25..6ed69685734c8 100644 --- a/solution/1300-1399/1355.Activity Participants/README_EN.md +++ b/solution/1300-1399/1355.Activity Participants/README_EN.md @@ -82,9 +82,9 @@ Singing is performed by 2 friends (Victor J. and Jade W.) ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -100,3 +100,5 @@ WHERE cnt > (SELECT MIN(cnt) FROM t) AND cnt < (SELECT MAX(cnt) FROM t); ``` + + diff --git a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README.md b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README.md index 9c20ab32ecbaf..833de6bf6da9c 100644 --- a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README.md +++ b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:自定义排序** +### 方法一:自定义排序 我们将数组 $arr$ 按照题目要求排序,即按照二进制表示中数字 $1$ 的数目升序排序,如果存在多个数字二进制中 $1$ 的数目相同,则必须将它们按照数值大小升序排列。 @@ -71,20 +69,12 @@ -### **Python3** - - - ```python class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr, key=lambda x: (x.bit_count(), x)) ``` -### **Java** - - - ```java class Solution { public int[] sortByBits(int[] arr) { @@ -101,28 +91,6 @@ class Solution { } ``` -```java -class Solution { - public int[] sortByBits(int[] arr) { - int n = arr.length; - Integer[] t = new Integer[n]; - for (int i = 0; i < n; ++i) { - t[i] = arr[i]; - } - Arrays.sort(t, (a, b) -> { - int x = Integer.bitCount(a), y = Integer.bitCount(b); - return x == y ? a - b : x - y; - }); - for (int i = 0; i < n; ++i) { - arr[i] = t[i]; - } - return arr; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -139,21 +107,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector sortByBits(vector& arr) { - sort(arr.begin(), arr.end(), [&](auto& a, auto& b) -> bool { - int x = __builtin_popcount(a), y = __builtin_popcount(b); - return x < y || (x == y && a < b); - }); - return arr; - } -}; -``` - -### **Go** - ```go func sortByBits(arr []int) []int { for i, v := range arr { @@ -167,18 +120,6 @@ func sortByBits(arr []int) []int { } ``` -```go -func sortByBits(arr []int) []int { - sort.Slice(arr, func(i, j int) bool { - a, b := bits.OnesCount(uint(arr[i])), bits.OnesCount(uint(arr[j])) - return a < b || (a == b && arr[i] < arr[j]) - }) - return arr -} -``` - -### **TypeScript** - ```ts function sortByBits(arr: number[]): number[] { const countOnes = (n: number) => { @@ -193,8 +134,6 @@ function sortByBits(arr: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn sort_by_bits(mut arr: Vec) -> Vec { @@ -210,8 +149,6 @@ impl Solution { } ``` -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -242,10 +179,55 @@ int* sortByBits(int* arr, int arrSize, int* returnSize) { } ``` -### **...** + + +### 方法二 + + + +```java +class Solution { + public int[] sortByBits(int[] arr) { + int n = arr.length; + Integer[] t = new Integer[n]; + for (int i = 0; i < n; ++i) { + t[i] = arr[i]; + } + Arrays.sort(t, (a, b) -> { + int x = Integer.bitCount(a), y = Integer.bitCount(b); + return x == y ? a - b : x - y; + }); + for (int i = 0; i < n; ++i) { + arr[i] = t[i]; + } + return arr; + } +} +``` +```cpp +class Solution { +public: + vector sortByBits(vector& arr) { + sort(arr.begin(), arr.end(), [&](auto& a, auto& b) -> bool { + int x = __builtin_popcount(a), y = __builtin_popcount(b); + return x < y || (x == y && a < b); + }); + return arr; + } +}; ``` +```go +func sortByBits(arr []int) []int { + sort.Slice(arr, func(i, j int) bool { + a, b := bits.OnesCount(uint(arr[i])), bits.OnesCount(uint(arr[j])) + return a < b || (a == b && arr[i] < arr[j]) + }) + return arr +} ``` + + diff --git a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README_EN.md b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README_EN.md index 4cd32e5727fdd..1c2d1939b1618 100644 --- a/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README_EN.md +++ b/solution/1300-1399/1356.Sort Integers by The Number of 1 Bits/README_EN.md @@ -39,7 +39,7 @@ The sorted array by bits is [0,1,2,4,8,3,5,6,7] ## Solutions -**Solution 1: Custom Sorting** +### Solution 1: Custom Sorting We sort the array $arr$ according to the requirements of the problem, that is, sort in ascending order according to the number of $1$s in the binary representation. If there are multiple numbers with the same number of $1$s in the binary representation, they must be sorted in ascending order by numerical value. @@ -47,16 +47,12 @@ The time complexity is $O(n \log n)$, and the space complexity is $O(n)$. Where -### **Python3** - ```python class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr, key=lambda x: (x.bit_count(), x)) ``` -### **Java** - ```java class Solution { public int[] sortByBits(int[] arr) { @@ -73,28 +69,6 @@ class Solution { } ``` -```java -class Solution { - public int[] sortByBits(int[] arr) { - int n = arr.length; - Integer[] t = new Integer[n]; - for (int i = 0; i < n; ++i) { - t[i] = arr[i]; - } - Arrays.sort(t, (a, b) -> { - int x = Integer.bitCount(a), y = Integer.bitCount(b); - return x == y ? a - b : x - y; - }); - for (int i = 0; i < n; ++i) { - arr[i] = t[i]; - } - return arr; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -111,21 +85,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector sortByBits(vector& arr) { - sort(arr.begin(), arr.end(), [&](auto& a, auto& b) -> bool { - int x = __builtin_popcount(a), y = __builtin_popcount(b); - return x < y || (x == y && a < b); - }); - return arr; - } -}; -``` - -### **Go** - ```go func sortByBits(arr []int) []int { for i, v := range arr { @@ -139,18 +98,6 @@ func sortByBits(arr []int) []int { } ``` -```go -func sortByBits(arr []int) []int { - sort.Slice(arr, func(i, j int) bool { - a, b := bits.OnesCount(uint(arr[i])), bits.OnesCount(uint(arr[j])) - return a < b || (a == b && arr[i] < arr[j]) - }) - return arr -} -``` - -### **TypeScript** - ```ts function sortByBits(arr: number[]): number[] { const countOnes = (n: number) => { @@ -165,8 +112,6 @@ function sortByBits(arr: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn sort_by_bits(mut arr: Vec) -> Vec { @@ -182,8 +127,6 @@ impl Solution { } ``` -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -214,10 +157,55 @@ int* sortByBits(int* arr, int arrSize, int* returnSize) { } ``` -### **...** + + +### Solution 2 + + +```java +class Solution { + public int[] sortByBits(int[] arr) { + int n = arr.length; + Integer[] t = new Integer[n]; + for (int i = 0; i < n; ++i) { + t[i] = arr[i]; + } + Arrays.sort(t, (a, b) -> { + int x = Integer.bitCount(a), y = Integer.bitCount(b); + return x == y ? a - b : x - y; + }); + for (int i = 0; i < n; ++i) { + arr[i] = t[i]; + } + return arr; + } +} ``` +```cpp +class Solution { +public: + vector sortByBits(vector& arr) { + sort(arr.begin(), arr.end(), [&](auto& a, auto& b) -> bool { + int x = __builtin_popcount(a), y = __builtin_popcount(b); + return x < y || (x == y && a < b); + }); + return arr; + } +}; +``` + +```go +func sortByBits(arr []int) []int { + sort.Slice(arr, func(i, j int) bool { + a, b := bits.OnesCount(uint(arr[i])), bits.OnesCount(uint(arr[j])) + return a < b || (a == b && arr[i] < arr[j]) + }) + return arr +} ``` + + diff --git a/solution/1300-1399/1357.Apply Discount Every n Orders/README.md b/solution/1300-1399/1357.Apply Discount Every n Orders/README.md index c28ab6b356da2..3f506fab27c30 100644 --- a/solution/1300-1399/1357.Apply Discount Every n Orders/README.md +++ b/solution/1300-1399/1357.Apply Discount Every n Orders/README.md @@ -63,9 +63,7 @@ cashier.getBill([2,3,5],[5,3,2]); // 返回 2500.0 ## 解法 - - -**方法一:哈希表 + 模拟** +### 方法一:哈希表 + 模拟 用哈希表 $d$ 存储商品编号和价格,然后遍历商品编号和数量,计算总价,再根据折扣计算折扣后的价格。 @@ -73,10 +71,6 @@ cashier.getBill([2,3,5],[5,3,2]); // 返回 2500.0 -### **Python3** - - - ```python class Cashier: def __init__(self, n: int, discount: int, products: List[int], prices: List[int]): @@ -100,10 +94,6 @@ class Cashier: # param_1 = obj.getBill(product,amount) ``` -### **Java** - - - ```java class Cashier { private int i; @@ -138,8 +128,6 @@ class Cashier { */ ``` -### **C++** - ```cpp class Cashier { public: @@ -175,8 +163,6 @@ private: */ ``` -### **Go** - ```go type Cashier struct { i int @@ -213,10 +199,6 @@ func (this *Cashier) GetBill(product []int, amount []int) (ans float64) { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1357.Apply Discount Every n Orders/README_EN.md b/solution/1300-1399/1357.Apply Discount Every n Orders/README_EN.md index 30bab34f95f77..58d3816ee0d1c 100644 --- a/solution/1300-1399/1357.Apply Discount Every n Orders/README_EN.md +++ b/solution/1300-1399/1357.Apply Discount Every n Orders/README_EN.md @@ -65,7 +65,7 @@ cashier.getBill([2,3,5],[5,3,2]); // return 2500.0. 7th ## Solutions -**Solution 1: Hash Table + Simulation** +### Solution 1: Hash Table + Simulation Use a hash table $d$ to store the product ID and price, then traverse the product ID and quantity, calculate the total price, and then calculate the price after discount based on the discount. @@ -73,8 +73,6 @@ The time complexity of initialization is $O(n)$, where $n$ is the number of prod -### **Python3** - ```python class Cashier: def __init__(self, n: int, discount: int, products: List[int], prices: List[int]): @@ -98,8 +96,6 @@ class Cashier: # param_1 = obj.getBill(product,amount) ``` -### **Java** - ```java class Cashier { private int i; @@ -134,8 +130,6 @@ class Cashier { */ ``` -### **C++** - ```cpp class Cashier { public: @@ -171,8 +165,6 @@ private: */ ``` -### **Go** - ```go type Cashier struct { i int @@ -209,10 +201,6 @@ func (this *Cashier) GetBill(product []int, amount []int) (ans float64) { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1358.Number of Substrings Containing All Three Characters/README.md b/solution/1300-1399/1358.Number of Substrings Containing All Three Characters/README.md index 07b935ab1026b..063ea4084e58e 100644 --- a/solution/1300-1399/1358.Number of Substrings Containing All Three Characters/README.md +++ b/solution/1300-1399/1358.Number of Substrings Containing All Three Characters/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们用一个长度为 $3$ 的数组 $d$ 记录三种字符最近一次出现的位置,初始时均为 $-1$。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def numberOfSubstrings(self, s: str) -> int: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numberOfSubstrings(String s) { @@ -89,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +94,6 @@ public: }; ``` -### **Go** - ```go func numberOfSubstrings(s string) (ans int) { d := [3]int{-1, -1, -1} @@ -119,10 +105,6 @@ func numberOfSubstrings(s string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1358.Number of Substrings Containing All Three Characters/README_EN.md b/solution/1300-1399/1358.Number of Substrings Containing All Three Characters/README_EN.md index 9eba5ba0f7eb6..f24fb4f24e17f 100644 --- a/solution/1300-1399/1358.Number of Substrings Containing All Three Characters/README_EN.md +++ b/solution/1300-1399/1358.Number of Substrings Containing All Three Characters/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Single Pass** +### Solution 1: Single Pass We use an array $d$ of length $3$ to record the most recent occurrence of the three characters, initially all set to $-1$. @@ -52,8 +52,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. The sp -### **Python3** - ```python class Solution: def numberOfSubstrings(self, s: str) -> int: @@ -65,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numberOfSubstrings(String s) { @@ -82,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +93,6 @@ public: }; ``` -### **Go** - ```go func numberOfSubstrings(s string) (ans int) { d := [3]int{-1, -1, -1} @@ -112,10 +104,6 @@ func numberOfSubstrings(s string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1359.Count All Valid Pickup and Delivery Options/README.md b/solution/1300-1399/1359.Count All Valid Pickup and Delivery Options/README.md index 3451c80ee0614..425b599091453 100644 --- a/solution/1300-1399/1359.Count All Valid Pickup and Delivery Options/README.md +++ b/solution/1300-1399/1359.Count All Valid Pickup and Delivery Options/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示 $i$ 个订单的所有有效的收件/配送序列的数目。初始时 $f[1] = 1$。 @@ -69,10 +67,6 @@ $$ -### **Python3** - - - ```python class Solution: def countOrders(self, n: int) -> int: @@ -83,10 +77,6 @@ class Solution: return f ``` -### **Java** - - - ```java class Solution { public int countOrders(int n) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,7 +104,16 @@ public: }; ``` -### **Rust** +```go +func countOrders(n int) int { + const mod = 1e9 + 7 + f := 1 + for i := 2; i <= n; i++ { + f = f * i * (2*i - 1) % mod + } + return f +} +``` ```rust const MOD: i64 = (1e9 as i64) + 7; @@ -133,23 +130,6 @@ impl Solution { } ``` -### **Go** - -```go -func countOrders(n int) int { - const mod = 1e9 + 7 - f := 1 - for i := 2; i <= n; i++ { - f = f * i * (2*i - 1) % mod - } - return f -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1359.Count All Valid Pickup and Delivery Options/README_EN.md b/solution/1300-1399/1359.Count All Valid Pickup and Delivery Options/README_EN.md index 01e430aacf5d4..a04977e840374 100644 --- a/solution/1300-1399/1359.Count All Valid Pickup and Delivery Options/README_EN.md +++ b/solution/1300-1399/1359.Count All Valid Pickup and Delivery Options/README_EN.md @@ -45,7 +45,7 @@ This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2. ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i]$ as the number of all valid pickup/delivery sequences for $i$ orders. Initially, $f[1] = 1$. @@ -63,8 +63,6 @@ The time complexity is $O(n)$, where $n$ is the number of orders. The space comp -### **Python3** - ```python class Solution: def countOrders(self, n: int) -> int: @@ -75,8 +73,6 @@ class Solution: return f ``` -### **Java** - ```java class Solution { public int countOrders(int n) { @@ -90,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,7 +100,16 @@ public: }; ``` -### **Rust** +```go +func countOrders(n int) int { + const mod = 1e9 + 7 + f := 1 + for i := 2; i <= n; i++ { + f = f * i * (2*i - 1) % mod + } + return f +} +``` ```rust const MOD: i64 = (1e9 as i64) + 7; @@ -123,23 +126,6 @@ impl Solution { } ``` -### **Go** - -```go -func countOrders(n int) int { - const mod = 1e9 + 7 - f := 1 - for i := 2; i <= n; i++ { - f = f * i * (2*i - 1) % mod - } - return f -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1360.Number of Days Between Two Dates/README.md b/solution/1300-1399/1360.Number of Days Between Two Dates/README.md index 05aa9ddb29136..36120875fa359 100644 --- a/solution/1300-1399/1360.Number of Days Between Two Dates/README.md +++ b/solution/1300-1399/1360.Number of Days Between Two Dates/README.md @@ -34,9 +34,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 我们先定义一个函数 `isLeapYear(year)` 来判断给定的年份 `year` 是否是闰年,如果是闰年则返回 `true`,否则返回 `false`。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: @@ -90,10 +84,6 @@ class Solution: return abs(calcDays(date1) - calcDays(date2)) ``` -### **Java** - - - ```java class Solution { public int daysBetweenDates(String date1, String date2) { @@ -127,13 +117,39 @@ class Solution { } ``` -### **C++** - ```cpp +class Solution { +public: + int daysBetweenDates(string date1, string date2) { + return abs(calcDays(date1) - calcDays(date2)); + } -``` + bool isLeapYear(int year) { + return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + } -### **Go** + int daysInMonth(int year, int month) { + int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + days[1] += isLeapYear(year); + return days[month - 1]; + } + + int calcDays(string date) { + int year = stoi(date.substr(0, 4)); + int month = stoi(date.substr(5, 2)); + int day = stoi(date.substr(8, 2)); + int days = 0; + for (int y = 1971; y < year; ++y) { + days += 365 + isLeapYear(y); + } + for (int m = 1; m < month; ++m) { + days += daysInMonth(year, m); + } + days += day; + return days; + } +}; +``` ```go func daysBetweenDates(date1 string, date2 string) int { @@ -178,8 +194,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function daysBetweenDates(date1: string, date2: string): number { return Math.abs(calcDays(date1) - calcDays(date2)); @@ -208,10 +222,6 @@ function calcDays(date: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1360.Number of Days Between Two Dates/README_EN.md b/solution/1300-1399/1360.Number of Days Between Two Dates/README_EN.md index 51bba1442f0d5..68df3abec94f3 100644 --- a/solution/1300-1399/1360.Number of Days Between Two Dates/README_EN.md +++ b/solution/1300-1399/1360.Number of Days Between Two Dates/README_EN.md @@ -25,7 +25,7 @@ ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics First, we define a function `isLeapYear(year)` to determine whether the given year `year` is a leap year. If it is a leap year, return `true`, otherwise return `false`. @@ -39,8 +39,6 @@ The time complexity is $O(y + m)$, where $y$ represents the number of years from -### **Python3** - ```python class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: @@ -77,8 +75,6 @@ class Solution: return abs(calcDays(date1) - calcDays(date2)) ``` -### **Java** - ```java class Solution { public int daysBetweenDates(String date1, String date2) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +142,6 @@ public: }; ``` -### **Go** - ```go func daysBetweenDates(date1 string, date2 string) int { return abs(calcDays(date1) - calcDays(date2)) @@ -193,8 +185,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function daysBetweenDates(date1: string, date2: string): number { return Math.abs(calcDays(date1) - calcDays(date2)); @@ -223,10 +213,6 @@ function calcDays(date: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1361.Validate Binary Tree Nodes/README.md b/solution/1300-1399/1361.Validate Binary Tree Nodes/README.md index 6d4c8bf92ff65..64bd1ec113d65 100644 --- a/solution/1300-1399/1361.Validate Binary Tree Nodes/README.md +++ b/solution/1300-1399/1361.Validate Binary Tree Nodes/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:并查集** +### 方法一:并查集 我们可以遍历每个节点 $i$ 以及对应的左右孩子 $l$, $r$,用 $vis$ 数组记录节点是否有父节点: @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def validateBinaryTreeNodes( @@ -103,10 +97,6 @@ class Solution: return n == 1 ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +159,6 @@ public: }; ``` -### **Go** - ```go func validateBinaryTreeNodes(n int, leftChild []int, rightChild []int) bool { p := make([]int, n) @@ -203,10 +189,6 @@ func validateBinaryTreeNodes(n int, leftChild []int, rightChild []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1361.Validate Binary Tree Nodes/README_EN.md b/solution/1300-1399/1361.Validate Binary Tree Nodes/README_EN.md index cda45e908652b..2aecb45044e04 100644 --- a/solution/1300-1399/1361.Validate Binary Tree Nodes/README_EN.md +++ b/solution/1300-1399/1361.Validate Binary Tree Nodes/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Union-Find** +### Solution 1: Union-Find We can traverse each node $i$ and its corresponding left and right children $l$, $r$, using an array $vis$ to record whether the node has a parent: @@ -57,8 +57,6 @@ The time complexity is $O(n \times \alpha(n))$, and the space complexity is $O(n -### **Python3** - ```python class Solution: def validateBinaryTreeNodes( @@ -82,8 +80,6 @@ class Solution: return n == 1 ``` -### **Java** - ```java class Solution { private int[] p; @@ -118,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +142,6 @@ public: }; ``` -### **Go** - ```go func validateBinaryTreeNodes(n int, leftChild []int, rightChild []int) bool { p := make([]int, n) @@ -180,10 +172,6 @@ func validateBinaryTreeNodes(n int, leftChild []int, rightChild []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1362.Closest Divisors/README.md b/solution/1300-1399/1362.Closest Divisors/README.md index 7315a457a846d..ec4b4a049ecb9 100644 --- a/solution/1300-1399/1362.Closest Divisors/README.md +++ b/solution/1300-1399/1362.Closest Divisors/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们设计一个函数 $f(x)$,该函数返回乘积等于 $x$ 的两个数,且这两个数的差的绝对值最小。我们可以从 $\sqrt{x}$ 开始枚举 $i$,如果 $x$ 能被 $i$ 整除,那么 $\frac{x}{i}$ 就是另一个因数,此时我们就找到了一个乘积等于 $x$ 的两个因数,我们将其返回即可。否则我们减小 $i$ 的值,继续枚举。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def closestDivisors(self, num: int) -> List[int]: @@ -75,10 +69,6 @@ class Solution: return a if abs(a[0] - a[1]) < abs(b[0] - b[1]) else b ``` -### **Java** - - - ```java class Solution { public int[] closestDivisors(int num) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func closestDivisors(num int) []int { f := func(x int) []int { @@ -143,10 +129,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1362.Closest Divisors/README_EN.md b/solution/1300-1399/1362.Closest Divisors/README_EN.md index 88e79279c91a5..1af18b9fbcbd4 100644 --- a/solution/1300-1399/1362.Closest Divisors/README_EN.md +++ b/solution/1300-1399/1362.Closest Divisors/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We design a function $f(x)$ that returns two numbers whose product equals $x$ and the absolute difference between these two numbers is the smallest. We can start enumerating $i$ from $\sqrt{x}$. If $x$ can be divided by $i$, then $\frac{x}{i}$ is another factor. At this point, we have found two factors whose product equals $x$. We can return them directly. Otherwise, we decrease the value of $i$ and continue to enumerate. @@ -50,8 +50,6 @@ The time complexity is $O(\sqrt{num})$, and the space complexity is $O(1)$. Wher -### **Python3** - ```python class Solution: def closestDivisors(self, num: int) -> List[int]: @@ -65,8 +63,6 @@ class Solution: return a if abs(a[0] - a[1]) < abs(b[0] - b[1]) else b ``` -### **Java** - ```java class Solution { public int[] closestDivisors(int num) { @@ -85,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +99,6 @@ public: }; ``` -### **Go** - ```go func closestDivisors(num int) []int { f := func(x int) []int { @@ -131,10 +123,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1363.Largest Multiple of Three/README.md b/solution/1300-1399/1363.Largest Multiple of Three/README.md index 0de8933d4d55f..a6aee18b2c8ab 100644 --- a/solution/1300-1399/1363.Largest Multiple of Three/README.md +++ b/solution/1300-1399/1363.Largest Multiple of Three/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:贪心 + 动态规划 + 逆推** +### 方法一:贪心 + 动态规划 + 逆推 我们定义 $f[i][j]$ 表示在前 $i$ 个数中选取若干个数,使得选取的数的和模 $3$ 为 $j$ 的最大长度。为了使得选取的数最大,我们需要尽可能选取更多的数,因此我们需要使得 $f[i][j]$ 尽可能大。我们初始化 $f[0][0] = 0$,其余的 $f[0][j] = -\infty$。 @@ -71,10 +69,6 @@ $$ -### **Python3** - - - ```python class Solution: def largestMultipleOfThree(self, digits: List[int]) -> str: @@ -100,10 +94,6 @@ class Solution: return "".join(map(str, arr[i:])) ``` -### **Java** - - - ```java class Solution { public String largestMultipleOfThree(int[] digits) { @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +164,6 @@ public: }; ``` -### **Go** - ```go func largestMultipleOfThree(digits []int) string { sort.Ints(digits) @@ -215,8 +201,6 @@ func largestMultipleOfThree(digits []int) string { } ``` -### **TypeScript** - ```ts function largestMultipleOfThree(digits: number[]): string { digits.sort((a, b) => a - b); @@ -247,10 +231,6 @@ function largestMultipleOfThree(digits: number[]): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1363.Largest Multiple of Three/README_EN.md b/solution/1300-1399/1363.Largest Multiple of Three/README_EN.md index 3a1c79b49e10b..0c030935eb6fd 100644 --- a/solution/1300-1399/1363.Largest Multiple of Three/README_EN.md +++ b/solution/1300-1399/1363.Largest Multiple of Three/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Greedy + Dynamic Programming + Backtracking** +### Solution 1: Greedy + Dynamic Programming + Backtracking We define $f[i][j]$ as the maximum length of selecting several numbers from the first $i$ numbers, so that the sum of the selected numbers modulo $3$ equals $j$. To make the selected numbers as large as possible, we need to select as many numbers as possible, so we need to make $f[i][j]$ as large as possible. We initialize $f[0][0] = 0$, and the rest of $f[0][j] = -\infty$. @@ -58,8 +58,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def largestMultipleOfThree(self, digits: List[int]) -> str: @@ -85,8 +83,6 @@ class Solution: return "".join(map(str, arr[i:])) ``` -### **Java** - ```java class Solution { public String largestMultipleOfThree(int[] digits) { @@ -123,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +153,6 @@ public: }; ``` -### **Go** - ```go func largestMultipleOfThree(digits []int) string { sort.Ints(digits) @@ -198,8 +190,6 @@ func largestMultipleOfThree(digits []int) string { } ``` -### **TypeScript** - ```ts function largestMultipleOfThree(digits: number[]): string { digits.sort((a, b) => a - b); @@ -230,10 +220,6 @@ function largestMultipleOfThree(digits: number[]): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1364.Number of Trusted Contacts of a Customer/README.md b/solution/1300-1399/1364.Number of Trusted Contacts of a Customer/README.md index 794aa2907ff72..ee5725de10f89 100644 --- a/solution/1300-1399/1364.Number of Trusted Contacts of a Customer/README.md +++ b/solution/1300-1399/1364.Number of Trusted Contacts of a Customer/README.md @@ -125,12 +125,10 @@ John 没有任何联系人。 ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -149,3 +147,5 @@ ORDER BY invoice_id; ``` + + diff --git a/solution/1300-1399/1364.Number of Trusted Contacts of a Customer/README_EN.md b/solution/1300-1399/1364.Number of Trusted Contacts of a Customer/README_EN.md index d25fd21d3c078..625ce375b8d46 100644 --- a/solution/1300-1399/1364.Number of Trusted Contacts of a Customer/README_EN.md +++ b/solution/1300-1399/1364.Number of Trusted Contacts of a Customer/README_EN.md @@ -122,9 +122,9 @@ John doesn't have any contacts. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -144,3 +144,5 @@ ORDER BY invoice_id; ``` + + diff --git a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/README.md b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/README.md index 7eb2def7de429..f949612f503ed 100644 --- a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/README.md +++ b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 我们可以将数组 $nums$ 复制一份,记为 $arr$,然后对 $arr$ 进行升序排序。 @@ -59,18 +57,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。 -**方法二:计数排序 + 前缀和** - -我们注意到数组 $nums$ 中的元素的范围是 $[0, 100]$,因此我们可以使用计数排序的方法,先统计数组 $nums$ 中每个元素的个数。然后对计数数组进行前缀和计算,最后遍历数组 $nums$,对于每个元素 $x$,我们直接将计数数组中下标为 $x$ 的元素的值加入答案数组即可。 - -时间复杂度 $O(n + M)$,空间复杂度 $O(M)$,其中 $n$ 和 $M$ 分别是数组 $nums$ 的长度和最大值。 - -### **Python3** - - - ```python class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: @@ -78,20 +66,6 @@ class Solution: return [bisect_left(arr, x) for x in nums] ``` -```python -class Solution: - def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: - cnt = [0] * 102 - for x in nums: - cnt[x + 1] += 1 - s = list(accumulate(cnt)) - return [s[x] for x in nums] -``` - -### **Java** - - - ```java class Solution { public int[] smallerNumbersThanCurrent(int[] nums) { @@ -118,6 +92,75 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector smallerNumbersThanCurrent(vector& nums) { + vector arr = nums; + sort(arr.begin(), arr.end()); + for (int i = 0; i < nums.size(); ++i) { + nums[i] = lower_bound(arr.begin(), arr.end(), nums[i]) - arr.begin(); + } + return nums; + } +}; +``` + +```go +func smallerNumbersThanCurrent(nums []int) (ans []int) { + arr := make([]int, len(nums)) + copy(arr, nums) + sort.Ints(arr) + for i, x := range nums { + nums[i] = sort.SearchInts(arr, x) + } + return nums +} +``` + +```ts +function smallerNumbersThanCurrent(nums: number[]): number[] { + const search = (nums: number[], x: number) => { + let l = 0, + r = nums.length; + while (l < r) { + const mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + const arr = nums.slice().sort((a, b) => a - b); + for (let i = 0; i < nums.length; ++i) { + nums[i] = search(arr, nums[i]); + } + return nums; +} +``` + + + +### 方法二:计数排序 + 前缀和 + +我们注意到数组 $nums$ 中的元素的范围是 $[0, 100]$,因此我们可以使用计数排序的方法,先统计数组 $nums$ 中每个元素的个数。然后对计数数组进行前缀和计算,最后遍历数组 $nums$,对于每个元素 $x$,我们直接将计数数组中下标为 $x$ 的元素的值加入答案数组即可。 + +时间复杂度 $O(n + M)$,空间复杂度 $O(M)$,其中 $n$ 和 $M$ 分别是数组 $nums$ 的长度和最大值。 + + + +```python +class Solution: + def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: + cnt = [0] * 102 + for x in nums: + cnt[x + 1] += 1 + s = list(accumulate(cnt)) + return [s[x] for x in nums] +``` + ```java class Solution { public int[] smallerNumbersThanCurrent(int[] nums) { @@ -138,22 +181,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector smallerNumbersThanCurrent(vector& nums) { - vector arr = nums; - sort(arr.begin(), arr.end()); - for (int i = 0; i < nums.size(); ++i) { - nums[i] = lower_bound(arr.begin(), arr.end(), nums[i]) - arr.begin(); - } - return nums; - } -}; -``` - ```cpp class Solution { public: @@ -174,20 +201,6 @@ public: }; ``` -### **Go** - -```go -func smallerNumbersThanCurrent(nums []int) (ans []int) { - arr := make([]int, len(nums)) - copy(arr, nums) - sort.Ints(arr) - for i, x := range nums { - nums[i] = sort.SearchInts(arr, x) - } - return nums -} -``` - ```go func smallerNumbersThanCurrent(nums []int) (ans []int) { cnt := [102]int{} @@ -204,31 +217,6 @@ func smallerNumbersThanCurrent(nums []int) (ans []int) { } ``` -### **TypeScript** - -```ts -function smallerNumbersThanCurrent(nums: number[]): number[] { - const search = (nums: number[], x: number) => { - let l = 0, - r = nums.length; - while (l < r) { - const mid = (l + r) >> 1; - if (nums[mid] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - }; - const arr = nums.slice().sort((a, b) => a - b); - for (let i = 0; i < nums.length; ++i) { - nums[i] = search(arr, nums[i]); - } - return nums; -} -``` - ```ts function smallerNumbersThanCurrent(nums: number[]): number[] { const cnt: number[] = new Array(102).fill(0); @@ -247,10 +235,6 @@ function smallerNumbersThanCurrent(nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/README_EN.md b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/README_EN.md index 3a2f8b52a1aac..e5d7c18570461 100644 --- a/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/README_EN.md +++ b/solution/1300-1399/1365.How Many Numbers Are Smaller Than the Current Number/README_EN.md @@ -46,7 +46,7 @@ For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2). ## Solutions -**Solution 1: Sorting + Binary Search** +### Solution 1: Sorting + Binary Search We can make a copy of the array $nums$, denoted as $arr$, and then sort $arr$ in ascending order. @@ -54,16 +54,8 @@ Next, for each element $x$ in $nums$, we can use binary search to find the index The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$. -**Solution 2: Counting Sort + Prefix Sum** - -We notice that the range of elements in the array $nums$ is $[0, 100]$. Therefore, we can use the counting sort method to first count the number of each element in the array $nums$. Then we calculate the prefix sum of the counting array. Finally, we traverse the array $nums$. For each element $x$, we directly add the value of the element at index $x$ in the counting array to the answer array. - -The time complexity is $O(n + M)$, and the space complexity is $O(M)$. Where $n$ and $M$ are the length and the maximum value of the array $nums$, respectively. - -### **Python3** - ```python class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: @@ -71,18 +63,6 @@ class Solution: return [bisect_left(arr, x) for x in nums] ``` -```python -class Solution: - def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: - cnt = [0] * 102 - for x in nums: - cnt[x + 1] += 1 - s = list(accumulate(cnt)) - return [s[x] for x in nums] -``` - -### **Java** - ```java class Solution { public int[] smallerNumbersThanCurrent(int[] nums) { @@ -109,6 +89,75 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector smallerNumbersThanCurrent(vector& nums) { + vector arr = nums; + sort(arr.begin(), arr.end()); + for (int i = 0; i < nums.size(); ++i) { + nums[i] = lower_bound(arr.begin(), arr.end(), nums[i]) - arr.begin(); + } + return nums; + } +}; +``` + +```go +func smallerNumbersThanCurrent(nums []int) (ans []int) { + arr := make([]int, len(nums)) + copy(arr, nums) + sort.Ints(arr) + for i, x := range nums { + nums[i] = sort.SearchInts(arr, x) + } + return nums +} +``` + +```ts +function smallerNumbersThanCurrent(nums: number[]): number[] { + const search = (nums: number[], x: number) => { + let l = 0, + r = nums.length; + while (l < r) { + const mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + const arr = nums.slice().sort((a, b) => a - b); + for (let i = 0; i < nums.length; ++i) { + nums[i] = search(arr, nums[i]); + } + return nums; +} +``` + + + +### Solution 2: Counting Sort + Prefix Sum + +We notice that the range of elements in the array $nums$ is $[0, 100]$. Therefore, we can use the counting sort method to first count the number of each element in the array $nums$. Then we calculate the prefix sum of the counting array. Finally, we traverse the array $nums$. For each element $x$, we directly add the value of the element at index $x$ in the counting array to the answer array. + +The time complexity is $O(n + M)$, and the space complexity is $O(M)$. Where $n$ and $M$ are the length and the maximum value of the array $nums$, respectively. + + + +```python +class Solution: + def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: + cnt = [0] * 102 + for x in nums: + cnt[x + 1] += 1 + s = list(accumulate(cnt)) + return [s[x] for x in nums] +``` + ```java class Solution { public int[] smallerNumbersThanCurrent(int[] nums) { @@ -129,22 +178,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector smallerNumbersThanCurrent(vector& nums) { - vector arr = nums; - sort(arr.begin(), arr.end()); - for (int i = 0; i < nums.size(); ++i) { - nums[i] = lower_bound(arr.begin(), arr.end(), nums[i]) - arr.begin(); - } - return nums; - } -}; -``` - ```cpp class Solution { public: @@ -165,20 +198,6 @@ public: }; ``` -### **Go** - -```go -func smallerNumbersThanCurrent(nums []int) (ans []int) { - arr := make([]int, len(nums)) - copy(arr, nums) - sort.Ints(arr) - for i, x := range nums { - nums[i] = sort.SearchInts(arr, x) - } - return nums -} -``` - ```go func smallerNumbersThanCurrent(nums []int) (ans []int) { cnt := [102]int{} @@ -195,31 +214,6 @@ func smallerNumbersThanCurrent(nums []int) (ans []int) { } ``` -### **TypeScript** - -```ts -function smallerNumbersThanCurrent(nums: number[]): number[] { - const search = (nums: number[], x: number) => { - let l = 0, - r = nums.length; - while (l < r) { - const mid = (l + r) >> 1; - if (nums[mid] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - }; - const arr = nums.slice().sort((a, b) => a - b); - for (let i = 0; i < nums.length; ++i) { - nums[i] = search(arr, nums[i]); - } - return nums; -} -``` - ```ts function smallerNumbersThanCurrent(nums: number[]): number[] { const cnt: number[] = new Array(102).fill(0); @@ -238,10 +232,6 @@ function smallerNumbersThanCurrent(nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1366.Rank Teams by Votes/README.md b/solution/1300-1399/1366.Rank Teams by Votes/README.md index 2a299506ac046..b7ce5baa5b9bb 100644 --- a/solution/1300-1399/1366.Rank Teams by Votes/README.md +++ b/solution/1300-1399/1366.Rank Teams by Votes/README.md @@ -78,9 +78,7 @@ C 队获得两票「排位第一」,两票「排位第二」,两票「排位 ## 解法 - - -**方法一:计数 + 自定义排序** +### 方法一:计数 + 自定义排序 对于每个候选人,我们可以统计他在每个排位上的票数,然后根据不同的排位依次比较票数,票数相同则比较字母。 @@ -88,10 +86,6 @@ C 队获得两票「排位第一」,两票「排位第二」,两票「排位 -### **Python3** - - - ```python class Solution: def rankTeams(self, votes: List[str]) -> str: @@ -103,10 +97,6 @@ class Solution: return "".join(sorted(votes[0], key=lambda x: (cnt[x], -ord(x)), reverse=True)) ``` -### **Java** - - - ```java class Solution { public String rankTeams(String[] votes) { @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go func rankTeams(votes []string) string { cnt := [26][26]int{} @@ -194,10 +180,6 @@ func rankTeams(votes []string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1366.Rank Teams by Votes/README_EN.md b/solution/1300-1399/1366.Rank Teams by Votes/README_EN.md index e0f8a4abb9006..a3ef50a5f8349 100644 --- a/solution/1300-1399/1366.Rank Teams by Votes/README_EN.md +++ b/solution/1300-1399/1366.Rank Teams by Votes/README_EN.md @@ -56,7 +56,7 @@ X is the winner due to the tie-breaking rule. X has the same votes as W for the ## Solutions -**Solution 1: Counting + Custom Sorting** +### Solution 1: Counting + Custom Sorting For each candidate, we can count the number of votes they receive in each ranking, and then compare the number of votes according to different rankings. If the number of votes is the same, we compare the letters. @@ -64,8 +64,6 @@ The time complexity is $O(n^2 \times \log n)$, and the space complexity is $O(n^ -### **Python3** - ```python class Solution: def rankTeams(self, votes: List[str]) -> str: @@ -77,8 +75,6 @@ class Solution: return "".join(sorted(votes[0], key=lambda x: (cnt[x], -ord(x)), reverse=True)) ``` -### **Java** - ```java class Solution { public String rankTeams(String[] votes) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +135,6 @@ public: }; ``` -### **Go** - ```go func rankTeams(votes []string) string { cnt := [26][26]int{} @@ -166,10 +158,6 @@ func rankTeams(votes []string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1367.Linked List in Binary Tree/README.md b/solution/1300-1399/1367.Linked List in Binary Tree/README.md index 7c0501ec9e4cd..a0e5bd0a9a114 100644 --- a/solution/1300-1399/1367.Linked List in Binary Tree/README.md +++ b/solution/1300-1399/1367.Linked List in Binary Tree/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们设计一个递归函数 $dfs(head, root)$,表示链表 $head$ 是否是以 $root$ 为起点的路径上的节点值一一对应的子路径。函数 $dfs(head, root)$ 的逻辑如下: @@ -67,10 +65,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -101,10 +95,6 @@ class Solution: ) ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -151,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -196,8 +184,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -232,8 +218,6 @@ func dfs(head *ListNode, root *TreeNode) bool { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -279,8 +263,6 @@ function isSubPath(head: ListNode | null, root: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -350,10 +332,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1367.Linked List in Binary Tree/README_EN.md b/solution/1300-1399/1367.Linked List in Binary Tree/README_EN.md index 47fe4a050730d..3939afff22407 100644 --- a/solution/1300-1399/1367.Linked List in Binary Tree/README_EN.md +++ b/solution/1300-1399/1367.Linked List in Binary Tree/README_EN.md @@ -49,7 +49,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion We design a recursive function $dfs(head, root)$, which indicates whether the linked list $head$ corresponds to a subpath on the path starting with $root$ in the binary tree. The logic of the function $dfs(head, root)$ is as follows: @@ -64,8 +64,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ i -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -96,8 +94,6 @@ class Solution: ) ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -144,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -189,8 +183,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -225,8 +217,6 @@ func dfs(head *ListNode, root *TreeNode) bool { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -272,8 +262,6 @@ function isSubPath(head: ListNode | null, root: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -343,10 +331,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/README.md b/solution/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/README.md index 5ae7bf0f129b8..cfc39d8a31d4c 100644 --- a/solution/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/README.md +++ b/solution/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/README.md @@ -77,9 +77,7 @@ ## 解法 - - -**方法一:双端队列 BFS** +### 方法一:双端队列 BFS 本题实际上也是最短路模型,只不过求解的是改变方向的最小次数。 @@ -89,10 +87,6 @@ -### **Python3** - - - ```python class Solution: def minCost(self, grid: List[List[int]]) -> int: @@ -117,10 +111,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int minCost(int[][] grid) { @@ -155,43 +145,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minCost(grid: number[][]): number { - const m = grid.length, - n = grid[0].length; - let ans = Array.from({ length: m }, v => new Array(n).fill(Infinity)); - ans[0][0] = 0; - let queue = [[0, 0]]; - const dirs = [ - [0, 1], - [0, -1], - [1, 0], - [-1, 0], - ]; - while (queue.length) { - let [x, y] = queue.shift(); - for (let step = 1; step < 5; step++) { - let [dx, dy] = dirs[step - 1]; - let [i, j] = [x + dx, y + dy]; - if (i < 0 || i >= m || j < 0 || j >= n) continue; - let cost = ~~(grid[x][y] != step) + ans[x][y]; - if (cost >= ans[i][j]) continue; - ans[i][j] = cost; - if (grid[x][y] == step) { - queue.unshift([i, j]); - } else { - queue.push([i, j]); - } - } - } - return ans[m - 1][n - 1]; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -223,8 +176,6 @@ public: }; ``` -### **Go** - ```go func minCost(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -262,10 +213,39 @@ func minCost(grid [][]int) int { } ``` -### **...** - -``` - +```ts +function minCost(grid: number[][]): number { + const m = grid.length, + n = grid[0].length; + let ans = Array.from({ length: m }, v => new Array(n).fill(Infinity)); + ans[0][0] = 0; + let queue = [[0, 0]]; + const dirs = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; + while (queue.length) { + let [x, y] = queue.shift(); + for (let step = 1; step < 5; step++) { + let [dx, dy] = dirs[step - 1]; + let [i, j] = [x + dx, y + dy]; + if (i < 0 || i >= m || j < 0 || j >= n) continue; + let cost = ~~(grid[x][y] != step) + ans[x][y]; + if (cost >= ans[i][j]) continue; + ans[i][j] = cost; + if (grid[x][y] == step) { + queue.unshift([i, j]); + } else { + queue.push([i, j]); + } + } + } + return ans[m - 1][n - 1]; +} ``` + + diff --git a/solution/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/README_EN.md b/solution/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/README_EN.md index 7b24b0f70b7d7..af63bdcb3fb3d 100644 --- a/solution/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/README_EN.md +++ b/solution/1300-1399/1368.Minimum Cost to Make at Least One Valid Path in a Grid/README_EN.md @@ -59,7 +59,7 @@ The total cost = 3. ## Solutions -**Solution 1: Double-ended Queue BFS** +### Solution 1: Double-ended Queue BFS This problem is essentially a shortest path model, but what we are looking for is the minimum number of direction changes. @@ -69,8 +69,6 @@ In an undirected graph where the edge weights are only 0 and 1, we can use a dou -### **Python3** - ```python class Solution: def minCost(self, grid: List[List[int]]) -> int: @@ -95,8 +93,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int minCost(int[][] grid) { @@ -131,43 +127,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minCost(grid: number[][]): number { - const m = grid.length, - n = grid[0].length; - let ans = Array.from({ length: m }, v => new Array(n).fill(Infinity)); - ans[0][0] = 0; - let queue = [[0, 0]]; - const dirs = [ - [0, 1], - [0, -1], - [1, 0], - [-1, 0], - ]; - while (queue.length) { - let [x, y] = queue.shift(); - for (let step = 1; step < 5; step++) { - let [dx, dy] = dirs[step - 1]; - let [i, j] = [x + dx, y + dy]; - if (i < 0 || i >= m || j < 0 || j >= n) continue; - let cost = ~~(grid[x][y] != step) + ans[x][y]; - if (cost >= ans[i][j]) continue; - ans[i][j] = cost; - if (grid[x][y] == step) { - queue.unshift([i, j]); - } else { - queue.push([i, j]); - } - } - } - return ans[m - 1][n - 1]; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -199,8 +158,6 @@ public: }; ``` -### **Go** - ```go func minCost(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -238,10 +195,39 @@ func minCost(grid [][]int) int { } ``` -### **...** - -``` - +```ts +function minCost(grid: number[][]): number { + const m = grid.length, + n = grid[0].length; + let ans = Array.from({ length: m }, v => new Array(n).fill(Infinity)); + ans[0][0] = 0; + let queue = [[0, 0]]; + const dirs = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; + while (queue.length) { + let [x, y] = queue.shift(); + for (let step = 1; step < 5; step++) { + let [dx, dy] = dirs[step - 1]; + let [i, j] = [x + dx, y + dy]; + if (i < 0 || i >= m || j < 0 || j >= n) continue; + let cost = ~~(grid[x][y] != step) + ans[x][y]; + if (cost >= ans[i][j]) continue; + ans[i][j] = cost; + if (grid[x][y] == step) { + queue.unshift([i, j]); + } else { + queue.push([i, j]); + } + } + } + return ans[m - 1][n - 1]; +} ``` + + diff --git a/solution/1300-1399/1369.Get the Second Most Recent Activity/README.md b/solution/1300-1399/1369.Get the Second Most Recent Activity/README.md index c5b73a9f85bab..15bcb12fba9d8 100644 --- a/solution/1300-1399/1369.Get the Second Most Recent Activity/README.md +++ b/solution/1300-1399/1369.Get the Second Most Recent Activity/README.md @@ -60,12 +60,10 @@ Bob 只有一条记录,我们就取这条记录 ## 解法 - +### 方法一 -### **SQL** - ```sql SELECT username, @@ -87,3 +85,5 @@ WHERE a.rk = 2 OR a.cnt = 1; ``` + + diff --git a/solution/1300-1399/1369.Get the Second Most Recent Activity/README_EN.md b/solution/1300-1399/1369.Get the Second Most Recent Activity/README_EN.md index 4c3d5ffee4c27..af07557083efd 100644 --- a/solution/1300-1399/1369.Get the Second Most Recent Activity/README_EN.md +++ b/solution/1300-1399/1369.Get the Second Most Recent Activity/README_EN.md @@ -58,9 +58,9 @@ Bob only has one record, we just take that one. ## Solutions - +### Solution 1 -### **SQL** + ```sql SELECT @@ -83,3 +83,5 @@ WHERE a.rk = 2 OR a.cnt = 1; ``` + + diff --git a/solution/1300-1399/1370.Increasing Decreasing String/README.md b/solution/1300-1399/1370.Increasing Decreasing String/README.md index 537e3eb037e57..3ee12658ce36f 100644 --- a/solution/1300-1399/1370.Increasing Decreasing String/README.md +++ b/solution/1300-1399/1370.Increasing Decreasing String/README.md @@ -71,9 +71,7 @@ ## 解法 - - -**方法一:计数 + 模拟** +### 方法一:计数 + 模拟 我们先用一个哈希表或者一个长度为 $26$ 的数组 $cnt$ 统计字符串 $s$ 中每个字符出现的次数。 @@ -83,10 +81,6 @@ -### **Python3** - - - ```python class Solution: def sortString(self, s: str) -> str: @@ -101,10 +95,6 @@ class Solution: return "".join(ans) ``` -### **Java** - - - ```java class Solution { public String sortString(String s) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +151,6 @@ public: }; ``` -### **Go** - ```go func sortString(s string) string { cnt := [26]int{} @@ -191,8 +177,6 @@ func sortString(s string) string { } ``` -### **TypeScript** - ```ts function sortString(s: string): string { const cnt: number[] = Array(26).fill(0); @@ -218,8 +202,6 @@ function sortString(s: string): string { } ``` -### **Javascript** - ```js /** * @param {string} s @@ -249,10 +231,6 @@ var sortString = function (s) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1370.Increasing Decreasing String/README_EN.md b/solution/1300-1399/1370.Increasing Decreasing String/README_EN.md index f69454731d150..792434f8ef47a 100644 --- a/solution/1300-1399/1370.Increasing Decreasing String/README_EN.md +++ b/solution/1300-1399/1370.Increasing Decreasing String/README_EN.md @@ -51,7 +51,7 @@ After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba" ## Solutions -**Solution 1: Counting + Simulation** +### Solution 1: Counting + Simulation First, we use a hash table or an array $cnt$ of length $26$ to count the number of occurrences of each character in the string $s$. @@ -61,8 +61,6 @@ The time complexity is $O(n \times |\Sigma|)$, and the space complexity is $O(|\ -### **Python3** - ```python class Solution: def sortString(self, s: str) -> str: @@ -77,8 +75,6 @@ class Solution: return "".join(ans) ``` -### **Java** - ```java class Solution { public String sortString(String s) { @@ -107,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +131,6 @@ public: }; ``` -### **Go** - ```go func sortString(s string) string { cnt := [26]int{} @@ -165,8 +157,6 @@ func sortString(s string) string { } ``` -### **TypeScript** - ```ts function sortString(s: string): string { const cnt: number[] = Array(26).fill(0); @@ -192,8 +182,6 @@ function sortString(s: string): string { } ``` -### **Javascript** - ```js /** * @param {string} s @@ -223,10 +211,6 @@ var sortString = function (s) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/README.md b/solution/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/README.md index 50e4903828188..483dde470b41f 100644 --- a/solution/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/README.md +++ b/solution/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/README.md @@ -45,18 +45,10 @@ ## 解法 - - -前缀异或 + 状态压缩。 - -相似题目:[1915. 最美子字符串的数目](/solution/1900-1999/1915.Number%20of%20Wonderful%20Substrings/README.md) +### 方法一 -### **Python3** - - - ```python class Solution: def findTheLongestSubstring(self, s: str) -> int: @@ -73,10 +65,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { @@ -102,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +110,6 @@ public: }; ``` -### **Go** - ```go func findTheLongestSubstring(s string) int { pos := make([]int, 32) @@ -148,10 +132,6 @@ func findTheLongestSubstring(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/README_EN.md b/solution/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/README_EN.md index 14c37fcdb55c4..a1b195a675adf 100644 --- a/solution/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/README_EN.md +++ b/solution/1300-1399/1371.Find the Longest Substring Containing Vowels in Even Counts/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { @@ -88,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +106,6 @@ public: }; ``` -### **Go** - ```go func findTheLongestSubstring(s string) int { pos := make([]int, 32) @@ -134,10 +128,6 @@ func findTheLongestSubstring(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1372.Longest ZigZag Path in a Binary Tree/README.md b/solution/1300-1399/1372.Longest ZigZag Path in a Binary Tree/README.md index 8598a40bc073d..a96c0f20bad28 100644 --- a/solution/1300-1399/1372.Longest ZigZag Path in a Binary Tree/README.md +++ b/solution/1300-1399/1372.Longest ZigZag Path in a Binary Tree/README.md @@ -56,18 +56,12 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 时间复杂度 $O(n)$,其中 $n$ 是树中节点的个数。 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -90,10 +84,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -188,10 +174,6 @@ func longestZigZag(root *TreeNode) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1372.Longest ZigZag Path in a Binary Tree/README_EN.md b/solution/1300-1399/1372.Longest ZigZag Path in a Binary Tree/README_EN.md index e0fd1fdac6b51..7f7c93d1a5d77 100644 --- a/solution/1300-1399/1372.Longest ZigZag Path in a Binary Tree/README_EN.md +++ b/solution/1300-1399/1372.Longest ZigZag Path in a Binary Tree/README_EN.md @@ -53,9 +53,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -79,8 +79,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -116,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -148,8 +144,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -175,10 +169,6 @@ func longestZigZag(root *TreeNode) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1373.Maximum Sum BST in Binary Tree/README.md b/solution/1300-1399/1373.Maximum Sum BST in Binary Tree/README.md index e41081b4be80f..d13d48d0b401f 100644 --- a/solution/1300-1399/1373.Maximum Sum BST in Binary Tree/README.md +++ b/solution/1300-1399/1373.Maximum Sum BST in Binary Tree/README.md @@ -71,9 +71,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 判断一棵树是否是二叉搜索树,需要满足以下四个条件: @@ -105,10 +103,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -135,10 +129,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -181,8 +171,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -221,8 +209,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -252,8 +238,6 @@ func maxSumBST(root *TreeNode) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -290,10 +274,6 @@ function maxSumBST(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1373.Maximum Sum BST in Binary Tree/README_EN.md b/solution/1300-1399/1373.Maximum Sum BST in Binary Tree/README_EN.md index 550b74ced3838..36f3e327dd83e 100644 --- a/solution/1300-1399/1373.Maximum Sum BST in Binary Tree/README_EN.md +++ b/solution/1300-1399/1373.Maximum Sum BST in Binary Tree/README_EN.md @@ -53,7 +53,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS To determine whether a tree is a binary search tree, it needs to meet the following four conditions: @@ -85,8 +85,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -113,8 +111,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -157,8 +153,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -197,8 +191,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -228,8 +220,6 @@ func maxSumBST(root *TreeNode) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -266,10 +256,6 @@ function maxSumBST(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1374.Generate a String With Characters That Have Odd Counts/README.md b/solution/1300-1399/1374.Generate a String With Characters That Have Odd Counts/README.md index edd2af6e36d8d..9baba4c9a4c92 100644 --- a/solution/1300-1399/1374.Generate a String With Characters That Have Odd Counts/README.md +++ b/solution/1300-1399/1374.Generate a String With Characters That Have Odd Counts/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:构造** +### 方法一:构造 如果 $n$ 为奇数,那么直接构造 $n$ 个 `'a'` 即可。 @@ -54,20 +52,12 @@ -### **Python3** - - - ```python class Solution: def generateTheString(self, n: int) -> str: return 'a' * n if n & 1 else 'a' * (n - 1) + 'b' ``` -### **Java** - - - ```java class Solution { public String generateTheString(int n) { @@ -76,8 +66,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +79,6 @@ public: }; ``` -### **Go** - ```go func generateTheString(n int) string { ans := strings.Repeat("a", n-1) @@ -105,8 +91,6 @@ func generateTheString(n int) string { } ``` -### **TypeScript** - ```ts function generateTheString(n: number): string { const ans = Array(n).fill('a'); @@ -117,10 +101,6 @@ function generateTheString(n: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1374.Generate a String With Characters That Have Odd Counts/README_EN.md b/solution/1300-1399/1374.Generate a String With Characters That Have Odd Counts/README_EN.md index ee45a0ffc6210..df0f5e234db0d 100644 --- a/solution/1300-1399/1374.Generate a String With Characters That Have Odd Counts/README_EN.md +++ b/solution/1300-1399/1374.Generate a String With Characters That Have Odd Counts/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Construction** +### Solution 1: Construction If $n$ is odd, then we can directly construct a string with $n$ `'a'` characters. @@ -51,16 +51,12 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def generateTheString(self, n: int) -> str: return 'a' * n if n & 1 else 'a' * (n - 1) + 'b' ``` -### **Java** - ```java class Solution { public String generateTheString(int n) { @@ -69,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -84,8 +78,6 @@ public: }; ``` -### **Go** - ```go func generateTheString(n int) string { ans := strings.Repeat("a", n-1) @@ -98,8 +90,6 @@ func generateTheString(n int) string { } ``` -### **TypeScript** - ```ts function generateTheString(n: number): string { const ans = Array(n).fill('a'); @@ -110,10 +100,6 @@ function generateTheString(n: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1375.Number of Times Binary String Is Prefix-Aligned/README.md b/solution/1300-1399/1375.Number of Times Binary String Is Prefix-Aligned/README.md index 9379b86f4892f..15232bab14bc3 100644 --- a/solution/1300-1399/1375.Number of Times Binary String Is Prefix-Aligned/README.md +++ b/solution/1300-1399/1375.Number of Times Binary String Is Prefix-Aligned/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:直接遍历** +### 方法一:直接遍历 我们可以遍历数组 $flips$,记录当前遍历过的元素的最大值 $mx$,若 $mx$ 等于当前遍历到的下标 $i$,则说明前 $i$ 个元素都被翻转过了,即前缀一致,答案累加。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def numTimesAllBlue(self, flips: List[int]) -> int: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numTimesAllBlue(int[] flips) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func numTimesAllBlue(flips []int) (ans int) { mx := 0 @@ -130,8 +116,6 @@ func numTimesAllBlue(flips []int) (ans int) { } ``` -### **TypeScript** - ```ts function numTimesAllBlue(flips: number[]): number { let ans = 0; @@ -146,10 +130,6 @@ function numTimesAllBlue(flips: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1375.Number of Times Binary String Is Prefix-Aligned/README_EN.md b/solution/1300-1399/1375.Number of Times Binary String Is Prefix-Aligned/README_EN.md index b0c872bc6d755..c7c45d714d9d2 100644 --- a/solution/1300-1399/1375.Number of Times Binary String Is Prefix-Aligned/README_EN.md +++ b/solution/1300-1399/1375.Number of Times Binary String Is Prefix-Aligned/README_EN.md @@ -49,7 +49,7 @@ We can see that the string was prefix-aligned 1 time, so we return 1. ## Solutions -**Solution 1: Direct Traversal** +### Solution 1: Direct Traversal We can traverse the array $flips$, keeping track of the maximum value $mx$ of the elements we have traversed so far. If $mx$ equals the current index $i$ we are traversing, it means that the first $i$ elements have all been flipped, i.e., the prefix is consistent, and we increment the answer. @@ -59,8 +59,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $flips$. The -### **Python3** - ```python class Solution: def numTimesAllBlue(self, flips: List[int]) -> int: @@ -71,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numTimesAllBlue(int[] flips) { @@ -88,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +98,6 @@ public: }; ``` -### **Go** - ```go func numTimesAllBlue(flips []int) (ans int) { mx := 0 @@ -119,8 +111,6 @@ func numTimesAllBlue(flips []int) (ans int) { } ``` -### **TypeScript** - ```ts function numTimesAllBlue(flips: number[]): number { let ans = 0; @@ -135,10 +125,6 @@ function numTimesAllBlue(flips: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1376.Time Needed to Inform All Employees/README.md b/solution/1300-1399/1376.Time Needed to Inform All Employees/README.md index 78805d9ac84f5..524d3b2577e62 100644 --- a/solution/1300-1399/1376.Time Needed to Inform All Employees/README.md +++ b/solution/1300-1399/1376.Time Needed to Inform All Employees/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们先根据 $manager$ 数组构建邻接表 $g$,其中 $g[i]$ 表示员工 $i$ 的所有直接下属。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def numOfMinutes( @@ -90,10 +84,6 @@ class Solution: return dfs(headID) ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go func numOfMinutes(n int, headID int, manager []int, informTime []int) int { g := make([][]int, n) @@ -166,8 +152,6 @@ func numOfMinutes(n int, headID int, manager []int, informTime []int) int { } ``` -### **TypeScript** - ```ts function numOfMinutes(n: number, headID: number, manager: number[], informTime: number[]): number { const g: number[][] = new Array(n).fill(0).map(() => []); @@ -187,8 +171,6 @@ function numOfMinutes(n: number, headID: number, manager: number[], informTime: } ``` -### **C#** - ```cs public class Solution { private List[] g; @@ -218,10 +200,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1376.Time Needed to Inform All Employees/README_EN.md b/solution/1300-1399/1376.Time Needed to Inform All Employees/README_EN.md index 76e1c7b3f1c29..9d00ce24954d8 100644 --- a/solution/1300-1399/1376.Time Needed to Inform All Employees/README_EN.md +++ b/solution/1300-1399/1376.Time Needed to Inform All Employees/README_EN.md @@ -49,7 +49,7 @@ The tree structure of the employees in the company is shown. ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We first build an adjacent list $g$ according to the $manager$ array, where $g[i]$ represents all direct subordinates of employee $i$. @@ -61,8 +61,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def numOfMinutes( @@ -80,8 +78,6 @@ class Solution: return dfs(headID) ``` -### **Java** - ```java class Solution { private List[] g; @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +127,6 @@ public: }; ``` -### **Go** - ```go func numOfMinutes(n int, headID int, manager []int, informTime []int) int { g := make([][]int, n) @@ -154,8 +146,6 @@ func numOfMinutes(n int, headID int, manager []int, informTime []int) int { } ``` -### **TypeScript** - ```ts function numOfMinutes(n: number, headID: number, manager: number[], informTime: number[]): number { const g: number[][] = new Array(n).fill(0).map(() => []); @@ -175,8 +165,6 @@ function numOfMinutes(n: number, headID: number, manager: number[], informTime: } ``` -### **C#** - ```cs public class Solution { private List[] g; @@ -206,10 +194,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1377.Frog Position After T Seconds/README.md b/solution/1300-1399/1377.Frog Position After T Seconds/README.md index c61c4abd839eb..5db4a8c479aec 100644 --- a/solution/1300-1399/1377.Frog Position After T Seconds/README.md +++ b/solution/1300-1399/1377.Frog Position After T Seconds/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们先根据题目给出的无向树的边,建立一个邻接表 $g$,其中 $g[u]$ 表示顶点 $u$ 的所有相邻顶点。 @@ -84,10 +82,6 @@ -### **Python3** - - - ```python class Solution: def frogPosition( @@ -114,10 +108,6 @@ class Solution: return 0 ``` -### **Java** - - - ```java class Solution { public double frogPosition(int n, int[][] edges, int t, int target) { @@ -154,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -191,8 +179,6 @@ public: }; ``` -### **Go** - ```go func frogPosition(n int, edges [][]int, t int, target int) float64 { g := make([][]int, n+1) @@ -234,8 +220,6 @@ func frogPosition(n int, edges [][]int, t int, target int) float64 { } ``` -### **TypeScript** - ```ts function frogPosition(n: number, edges: number[][], t: number, target: number): number { const g: number[][] = Array.from({ length: n + 1 }, () => []); @@ -265,8 +249,6 @@ function frogPosition(n: number, edges: number[][], t: number, target: number): } ``` -### **C#** - ```cs public class Solution { public double FrogPosition(int n, int[][] edges, int t, int target) { @@ -303,10 +285,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1377.Frog Position After T Seconds/README_EN.md b/solution/1300-1399/1377.Frog Position After T Seconds/README_EN.md index b17a57e4e6e23..f1302ad805777 100644 --- a/solution/1300-1399/1377.Frog Position After T Seconds/README_EN.md +++ b/solution/1300-1399/1377.Frog Position After T Seconds/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: BFS** +### Solution 1: BFS First, based on the undirected tree edges given in the problem, we construct an adjacency list $g$, where $g[u]$ represents all adjacent vertices of vertex $u$. @@ -62,8 +62,6 @@ At the end of a round of search, we decrease $t$ by $1$, and then continue the n -### **Python3** - ```python class Solution: def frogPosition( @@ -90,8 +88,6 @@ class Solution: return 0 ``` -### **Java** - ```java class Solution { public double frogPosition(int n, int[][] edges, int t, int target) { @@ -128,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -165,8 +159,6 @@ public: }; ``` -### **Go** - ```go func frogPosition(n int, edges [][]int, t int, target int) float64 { g := make([][]int, n+1) @@ -208,8 +200,6 @@ func frogPosition(n int, edges [][]int, t int, target int) float64 { } ``` -### **TypeScript** - ```ts function frogPosition(n: number, edges: number[][], t: number, target: number): number { const g: number[][] = Array.from({ length: n + 1 }, () => []); @@ -239,8 +229,6 @@ function frogPosition(n: number, edges: number[][], t: number, target: number): } ``` -### **C#** - ```cs public class Solution { public double FrogPosition(int n, int[][] edges, int t, int target) { @@ -277,10 +265,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1378.Replace Employee ID With The Unique Identifier/README.md b/solution/1300-1399/1378.Replace Employee ID With The Unique Identifier/README.md index 8742605b743d4..5ee48c4ca7117 100644 --- a/solution/1300-1399/1378.Replace Employee ID With The Unique Identifier/README.md +++ b/solution/1300-1399/1378.Replace Employee ID With The Unique Identifier/README.md @@ -84,16 +84,12 @@ Jonathan 唯一标识码是 1 。 ## 解法 - - -**方法一:LEFT JOIN** +### 方法一:LEFT JOIN 我们可以使用 `LEFT JOIN` 来连接 `Employees` 和 `EmployeeUNI` 表,然后使用 `SELECT` 语句来选择 `unique_id` 和 `name` 列。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT unique_id, name @@ -103,3 +99,5 @@ FROM ``` + + diff --git a/solution/1300-1399/1378.Replace Employee ID With The Unique Identifier/README_EN.md b/solution/1300-1399/1378.Replace Employee ID With The Unique Identifier/README_EN.md index e250e29223ca9..f7def28b36a23 100644 --- a/solution/1300-1399/1378.Replace Employee ID With The Unique Identifier/README_EN.md +++ b/solution/1300-1399/1378.Replace Employee ID With The Unique Identifier/README_EN.md @@ -82,9 +82,9 @@ The unique ID of Jonathan is 1. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -95,3 +95,5 @@ FROM ``` + + diff --git a/solution/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/README.md b/solution/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/README.md index e5c7219777b7a..5011b2e62e18b 100644 --- a/solution/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/README.md +++ b/solution/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们设计一个函数 $dfs(root1, root2)$,它会在树 $root1$ 和 $root2$ 中同时进行 DFS 遍历,当遍历到某个节点时,如果这个节点恰好为 $target$,那么我们就返回 $root2$ 中对应的节点。否则,我们递归地在 $root1$ 和 $root2$ 的左右子树中寻找 $target$,并返回找到的结果中不为空的那一个。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -104,10 +98,6 @@ class Solution: return dfs(original, cloned) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -172,8 +160,6 @@ public: }; ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -207,8 +193,6 @@ function getTargetCopy( } ``` -### **C#** - ```cs /** * Definition for a binary tree node. @@ -241,10 +225,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/README_EN.md b/solution/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/README_EN.md index bec04328e54a7..0ff78bacd0034 100644 --- a/solution/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/README_EN.md +++ b/solution/1300-1399/1379.Find a Corresponding Node of a Binary Tree in a Clone of That Tree/README_EN.md @@ -49,7 +49,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We design a function $dfs(root1, root2)$, which performs DFS traversal simultaneously in trees $root1$ and $root2$. When traversing to a node, if this node happens to be $target$, then we return the corresponding node in $root2$. Otherwise, we recursively search for $target$ in the left and right subtrees of $root1$ and $root2$, and return the result that is not empty. @@ -57,8 +57,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -82,8 +80,6 @@ class Solution: return dfs(original, cloned) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -114,10 +110,9 @@ class Solution { TreeNode res = dfs(root1.left, root2.left); return res == null ? dfs(root1.right, root2.right) : res; } +} ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -147,8 +142,6 @@ public: }; ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -182,8 +175,6 @@ function getTargetCopy( } ``` -### **C#** - ```cs /** * Definition for a binary tree node. @@ -216,10 +207,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1380.Lucky Numbers in a Matrix/README.md b/solution/1300-1399/1380.Lucky Numbers in a Matrix/README.md index 54dc9c9f0d990..6f00e7f22d2b9 100644 --- a/solution/1300-1399/1380.Lucky Numbers in a Matrix/README.md +++ b/solution/1300-1399/1380.Lucky Numbers in a Matrix/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:维护行最小值和列最大值** +### 方法一:维护行最小值和列最大值 我们可以使用两个数组 $rows$ 和 $cols$ 记录矩阵中每一行的最小值和每一列的最大值,然后遍历矩阵中的每一个元素,检查该元素是否为所在行的最小值且为所在列的最大值,如果是则该元素为幸运数,我们将其加入答案数组。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def luckyNumbers(self, matrix: List[List[int]]) -> List[int]: @@ -79,10 +73,6 @@ class Solution: return list(rows & cols) ``` -### **Java** - - - ```java class Solution { public List luckyNumbers(int[][] matrix) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +127,6 @@ public: }; ``` -### **Go** - ```go func luckyNumbers(matrix [][]int) (ans []int) { m, n := len(matrix), len(matrix[0]) @@ -165,8 +151,6 @@ func luckyNumbers(matrix [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function luckyNumbers(matrix: number[][]): number[] { const m = matrix.length; @@ -191,8 +175,6 @@ function luckyNumbers(matrix: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn lucky_numbers(matrix: Vec>) -> Vec { @@ -221,10 +203,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1380.Lucky Numbers in a Matrix/README_EN.md b/solution/1300-1399/1380.Lucky Numbers in a Matrix/README_EN.md index 246995e94bfd5..02b9aefcb43c7 100644 --- a/solution/1300-1399/1380.Lucky Numbers in a Matrix/README_EN.md +++ b/solution/1300-1399/1380.Lucky Numbers in a Matrix/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Maintain Row Minimum and Column Maximum** +### Solution 1: Maintain Row Minimum and Column Maximum We can use two arrays $rows$ and $cols$ to record the minimum value of each row and the maximum value of each column in the matrix. Then, we traverse each element in the matrix, checking whether this element is the minimum value of its row and the maximum value of its column. If it is, then this element is a lucky number, and we add it to the answer array. @@ -56,8 +56,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m + n)$. -### **Python3** - ```python class Solution: def luckyNumbers(self, matrix: List[List[int]]) -> List[int]: @@ -66,8 +64,6 @@ class Solution: return list(rows & cols) ``` -### **Java** - ```java class Solution { public List luckyNumbers(int[][] matrix) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +118,6 @@ public: }; ``` -### **Go** - ```go func luckyNumbers(matrix [][]int) (ans []int) { m, n := len(matrix), len(matrix[0]) @@ -150,8 +142,6 @@ func luckyNumbers(matrix [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function luckyNumbers(matrix: number[][]): number[] { const m = matrix.length; @@ -176,8 +166,6 @@ function luckyNumbers(matrix: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn lucky_numbers(matrix: Vec>) -> Vec { @@ -206,10 +194,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1381.Design a Stack With Increment Operation/README.md b/solution/1300-1399/1381.Design a Stack With Increment Operation/README.md index cf2879d62250e..6cd09a74c592f 100644 --- a/solution/1300-1399/1381.Design a Stack With Increment Operation/README.md +++ b/solution/1300-1399/1381.Design a Stack With Increment Operation/README.md @@ -55,9 +55,7 @@ stk.pop(); // 返回 -1 --> 栈为空,返回 -1 ## 解法 - - -**方法一:数组模拟** +### 方法一:数组模拟 我们可以用一个数组 $stk$ 来模拟栈,用一个整数 $i$ 表示下一个入栈的元素位置。另外,我们还需要一个数组 $add$ 来记录每个位置上的增量累加值。 @@ -71,10 +69,6 @@ stk.pop(); // 返回 -1 --> 栈为空,返回 -1 -### **Python3** - - - ```python class CustomStack: def __init__(self, maxSize: int): @@ -110,10 +104,6 @@ class CustomStack: # obj.increment(k,val) ``` -### **Java** - - - ```java class CustomStack { private int[] stk; @@ -159,8 +149,6 @@ class CustomStack { */ ``` -### **C++** - ```cpp class CustomStack { public: @@ -209,8 +197,6 @@ private: */ ``` -### **Go** - ```go type CustomStack struct { stk []int @@ -257,8 +243,6 @@ func (this *CustomStack) Increment(k int, val int) { */ ``` -### **TypeScript** - ```ts class CustomStack { private stk: number[]; @@ -305,10 +289,6 @@ class CustomStack { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1381.Design a Stack With Increment Operation/README_EN.md b/solution/1300-1399/1381.Design a Stack With Increment Operation/README_EN.md index d78eeb46d1bd9..f410df83c0472 100644 --- a/solution/1300-1399/1381.Design a Stack With Increment Operation/README_EN.md +++ b/solution/1300-1399/1381.Design a Stack With Increment Operation/README_EN.md @@ -51,7 +51,7 @@ stk.pop(); // return -1 --> Stack is empty return ## Solutions -**Solution 1: Array Simulation** +### Solution 1: Array Simulation We can use an array $stk$ to simulate the stack, and an integer $i$ to represent the position of the next element to be pushed into the stack. In addition, we need another array $add$ to record the cumulative increment value at each position. @@ -65,8 +65,6 @@ The time complexity is $O(1)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class CustomStack: def __init__(self, maxSize: int): @@ -102,8 +100,6 @@ class CustomStack: # obj.increment(k,val) ``` -### **Java** - ```java class CustomStack { private int[] stk; @@ -149,8 +145,6 @@ class CustomStack { */ ``` -### **C++** - ```cpp class CustomStack { public: @@ -199,8 +193,6 @@ private: */ ``` -### **Go** - ```go type CustomStack struct { stk []int @@ -247,8 +239,6 @@ func (this *CustomStack) Increment(k int, val int) { */ ``` -### **TypeScript** - ```ts class CustomStack { private stk: number[]; @@ -295,10 +285,6 @@ class CustomStack { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1382.Balance a Binary Search Tree/README.md b/solution/1300-1399/1382.Balance a Binary Search Tree/README.md index f58849a6ba0e8..41ba5fb4db521 100644 --- a/solution/1300-1399/1382.Balance a Binary Search Tree/README.md +++ b/solution/1300-1399/1382.Balance a Binary Search Tree/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:中序遍历 + 构造平衡二叉树** +### 方法一:中序遍历 + 构造平衡二叉树 由于原树是一棵二叉搜索树,因此我们可以将其中序遍历的结果保存在一个数组 $nums$ 中,然后我们设计一个函数 $build(i, j)$,它用来构造 $nums$ 中下标范围 $[i, j]$ 内的平衡二叉搜索树,那么答案就是 $build(0, |nums| - 1)$。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -90,10 +84,6 @@ class Solution: return build(0, len(nums) - 1) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -184,8 +172,6 @@ private: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -221,8 +207,6 @@ func balanceBST(root *TreeNode) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -262,10 +246,6 @@ function balanceBST(root: TreeNode | null): TreeNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1382.Balance a Binary Search Tree/README_EN.md b/solution/1300-1399/1382.Balance a Binary Search Tree/README_EN.md index 737e44b2911e7..a3155d29f9226 100644 --- a/solution/1300-1399/1382.Balance a Binary Search Tree/README_EN.md +++ b/solution/1300-1399/1382.Balance a Binary Search Tree/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: In-order Traversal + Construct Balanced Binary Search Tree** +### Solution 1: In-order Traversal + Construct Balanced Binary Search Tree Since the original tree is a binary search tree, we can save the result of the in-order traversal in an array $nums$. Then we design a function $build(i, j)$, which is used to construct a balanced binary search tree within the index range $[i, j]$ in $nums$. The answer is $build(0, |nums| - 1)$. @@ -47,8 +47,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -78,8 +76,6 @@ class Solution: return build(0, len(nums) - 1) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -125,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -170,8 +164,6 @@ private: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -207,8 +199,6 @@ func balanceBST(root *TreeNode) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -248,10 +238,6 @@ function balanceBST(root: TreeNode | null): TreeNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1383.Maximum Performance of a Team/README.md b/solution/1300-1399/1383.Maximum Performance of a Team/README.md index 1e02c86718e03..fb4cc18234d96 100644 --- a/solution/1300-1399/1383.Maximum Performance of a Team/README.md +++ b/solution/1300-1399/1383.Maximum Performance of a Team/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列(小根堆)** +### 方法一:贪心 + 优先队列(小根堆) 本题是求“速度和”与“效率最小值”乘积的最大值。变量有两个,我们可以从大到小枚举 `efficiency[i]` 作为效率最小值,在所有效率大于等于 `efficiency[i]` 的工程师中选取不超过 $k-1$ 个,让他们速度和最大。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def maxPerformance( @@ -89,10 +83,6 @@ class Solution: return ans % mod ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +135,6 @@ public: }; ``` -### **Go** - ```go func maxPerformance(n int, speed []int, efficiency []int, k int) int { t := make([][]int, n) @@ -183,10 +169,6 @@ func (h *hp) Pop() any { func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1383.Maximum Performance of a Team/README_EN.md b/solution/1300-1399/1383.Maximum Performance of a Team/README_EN.md index 0fa6a68523b9e..0a394c3f50c3d 100644 --- a/solution/1300-1399/1383.Maximum Performance of a Team/README_EN.md +++ b/solution/1300-1399/1383.Maximum Performance of a Team/README_EN.md @@ -51,9 +51,9 @@ We have the maximum performance of the team by selecting engineer 2 (with speed= ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans % mod ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -102,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +125,6 @@ public: }; ``` -### **Go** - ```go func maxPerformance(n int, speed []int, efficiency []int, k int) int { t := make([][]int, n) @@ -165,10 +159,6 @@ func (h *hp) Pop() any { func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1384.Total Sales Amount by Year/README.md b/solution/1300-1399/1384.Total Sales Amount by Year/README.md index e30d0fa765add..2008ee1b6c4b9 100644 --- a/solution/1300-1399/1384.Total Sales Amount by Year/README.md +++ b/solution/1300-1399/1384.Total Sales Amount by Year/README.md @@ -86,12 +86,10 @@ LC Keychain 在 2019-12-01 至 2020-01-31 期间销售,该产品在2019 ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -134,3 +132,5 @@ ORDER BY ``` + + diff --git a/solution/1300-1399/1384.Total Sales Amount by Year/README_EN.md b/solution/1300-1399/1384.Total Sales Amount by Year/README_EN.md index 410ca2456a16c..0fb86fe434629 100644 --- a/solution/1300-1399/1384.Total Sales Amount by Year/README_EN.md +++ b/solution/1300-1399/1384.Total Sales Amount by Year/README_EN.md @@ -84,9 +84,9 @@ LC Keychain was sold for the period of 2019-12-01 to 2020-01-31, and there are 3 ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -130,3 +130,5 @@ ORDER BY ``` + + diff --git a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README.md b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README.md index 2cd56bc5f1c36..96c58d253d295 100644 --- a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README.md +++ b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 我们可以先对数组 $arr2$ 排序,然后对于数组 $arr1$ 中的每个元素 $a$,使用二分查找,找到数组 $arr2$ 中第一个大于等于 $a-d$ 的元素,如果元素存在,且小于等于 $a+d$,则说明不符合距离要求,否则说明符合距离要求。我们将符合距离要求的元素个数累加,即为答案。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int: @@ -89,10 +83,6 @@ class Solution: return sum(check(a) for a in arr1) ``` -### **Java** - - - ```java class Solution { public int findTheDistanceValue(int[] arr1, int[] arr2, int d) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func findTheDistanceValue(arr1 []int, arr2 []int, d int) (ans int) { sort.Ints(arr2) @@ -156,8 +142,6 @@ func findTheDistanceValue(arr1 []int, arr2 []int, d int) (ans int) { } ``` -### **TypeScript** - ```ts function findTheDistanceValue(arr1: number[], arr2: number[], d: number): number { const check = (a: number) => { @@ -184,8 +168,6 @@ function findTheDistanceValue(arr1: number[], arr2: number[], d: number): number } ``` -### **Rust** - ```rust impl Solution { pub fn find_the_distance_value(arr1: Vec, mut arr2: Vec, d: i32) -> i32 { @@ -216,10 +198,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README_EN.md b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README_EN.md index 18089c5d0483d..4a1cf3eba5983 100644 --- a/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README_EN.md +++ b/solution/1300-1399/1385.Find the Distance Value Between Two Arrays/README_EN.md @@ -57,7 +57,7 @@ For arr1[2]=8 we have: ## Solutions -**Solution 1: Sorting + Binary Search** +### Solution 1: Sorting + Binary Search We can first sort the array $arr2$, then for each element $a$ in array $arr1$, use binary search to find the first element in array $arr2$ that is greater than or equal to $a-d$. If such an element exists and is less than or equal to $a+d$, it means that it does not meet the distance requirement. Otherwise, it meets the distance requirement. We accumulate the number of elements that meet the distance requirement, which is the answer. @@ -65,8 +65,6 @@ The time complexity is $O((m + n) \times \log n)$, and the space complexity is $ -### **Python3** - ```python class Solution: def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int: @@ -78,8 +76,6 @@ class Solution: return sum(check(a) for a in arr1) ``` -### **Java** - ```java class Solution { public int findTheDistanceValue(int[] arr1, int[] arr2, int d) { @@ -108,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +122,6 @@ public: }; ``` -### **Go** - ```go func findTheDistanceValue(arr1 []int, arr2 []int, d int) (ans int) { sort.Ints(arr2) @@ -143,8 +135,6 @@ func findTheDistanceValue(arr1 []int, arr2 []int, d int) (ans int) { } ``` -### **TypeScript** - ```ts function findTheDistanceValue(arr1: number[], arr2: number[], d: number): number { const check = (a: number) => { @@ -171,8 +161,6 @@ function findTheDistanceValue(arr1: number[], arr2: number[], d: number): number } ``` -### **Rust** - ```rust impl Solution { pub fn find_the_distance_value(arr1: Vec, mut arr2: Vec, d: i32) -> i32 { @@ -203,10 +191,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1386.Cinema Seat Allocation/README.md b/solution/1300-1399/1386.Cinema Seat Allocation/README.md index 0bc57beb5e517..1c5b9a2ee1e57 100644 --- a/solution/1300-1399/1386.Cinema Seat Allocation/README.md +++ b/solution/1300-1399/1386.Cinema Seat Allocation/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:哈希表 + 状态压缩** +### 方法一:哈希表 + 状态压缩 我们用哈希表 $d$ 来存储所有已经被预约的座位,其中键为行号,值为该行上已经被预约的座位的状态,即一个二进制数,第 $j$ 位为 $1$ 表示第 $j$ 个座位已经被预约,为 $0$ 表示第 $j$ 个座位尚未被预约。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int: @@ -90,10 +84,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxNumberOfFamilies(int n, int[][] reservedSeats) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func maxNumberOfFamilies(n int, reservedSeats [][]int) int { d := map[int]int{} @@ -166,8 +152,6 @@ func maxNumberOfFamilies(n int, reservedSeats [][]int) int { } ``` -### **TypeScript** - ```ts function maxNumberOfFamilies(n: number, reservedSeats: number[][]): number { const d: Map = new Map(); @@ -188,10 +172,6 @@ function maxNumberOfFamilies(n: number, reservedSeats: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1386.Cinema Seat Allocation/README_EN.md b/solution/1300-1399/1386.Cinema Seat Allocation/README_EN.md index e064c86a9452a..70dc1be8f491c 100644 --- a/solution/1300-1399/1386.Cinema Seat Allocation/README_EN.md +++ b/solution/1300-1399/1386.Cinema Seat Allocation/README_EN.md @@ -51,7 +51,7 @@ ## Solutions -**Solution 1: Hash Table + Bit Manipulation** +### Solution 1: Hash Table + Bit Manipulation We use a hash table $d$ to store all the reserved seats, where the key is the row number, and the value is the state of the reserved seats in that row, i.e., a binary number. The $j$-th bit being $1$ means the $j$-th seat is reserved, and $0$ means the $j$-th seat is not reserved. @@ -67,8 +67,6 @@ The time complexity is $O(m)$, and the space complexity is $O(m)$. Where $m$ is -### **Python3** - ```python class Solution: def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int: @@ -85,8 +83,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxNumberOfFamilies(int n, int[][] reservedSeats) { @@ -110,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +130,6 @@ public: }; ``` -### **Go** - ```go func maxNumberOfFamilies(n int, reservedSeats [][]int) int { d := map[int]int{} @@ -159,8 +151,6 @@ func maxNumberOfFamilies(n int, reservedSeats [][]int) int { } ``` -### **TypeScript** - ```ts function maxNumberOfFamilies(n: number, reservedSeats: number[][]): number { const d: Map = new Map(); @@ -181,10 +171,6 @@ function maxNumberOfFamilies(n: number, reservedSeats: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1387.Sort Integers by The Power Value/README.md b/solution/1300-1399/1387.Sort Integers by The Power Value/README.md index 552bdb76c6322..2e411a68327a3 100644 --- a/solution/1300-1399/1387.Sort Integers by The Power Value/README.md +++ b/solution/1300-1399/1387.Sort Integers by The Power Value/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:自定义排序** +### 方法一:自定义排序 我们先定义一个函数 $f(x)$,表示将数字 $x$ 变成 $1$ 所需要的步数,也即是数字 $x$ 的权重。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python @cache def f(x: int) -> int: @@ -93,10 +87,6 @@ class Solution: return sorted(range(lo, hi + 1), key=f)[k - 1] ``` -### **Java** - - - ```java class Solution { public int getKth(int lo, int hi, int k) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +147,6 @@ public: }; ``` -### **Go** - ```go func getKth(lo int, hi int, k int) int { f := func(x int) (ans int) { @@ -188,8 +174,6 @@ func getKth(lo int, hi int, k int) int { } ``` -### **TypeScript** - ```ts function getKth(lo: number, hi: number, k: number): number { const f = (x: number): number => { @@ -213,10 +197,6 @@ function getKth(lo: number, hi: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1387.Sort Integers by The Power Value/README_EN.md b/solution/1300-1399/1387.Sort Integers by The Power Value/README_EN.md index 3db10e4b6892f..a34e1405d0249 100644 --- a/solution/1300-1399/1387.Sort Integers by The Power Value/README_EN.md +++ b/solution/1300-1399/1387.Sort Integers by The Power Value/README_EN.md @@ -53,7 +53,7 @@ The fourth number in the sorted array is 7. ## Solutions -**Solution 1: Custom Sorting** +### Solution 1: Custom Sorting First, we define a function $f(x)$, which represents the number of steps required to change the number $x$ to $1$, i.e., the weight of the number $x$. @@ -65,8 +65,6 @@ The time complexity is $O(n \times \log n \times M)$, and the space complexity i -### **Python3** - ```python @cache def f(x: int) -> int: @@ -85,8 +83,6 @@ class Solution: return sorted(range(lo, hi + 1), key=f)[k - 1] ``` -### **Java** - ```java class Solution { public int getKth(int lo, int hi, int k) { @@ -115,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +143,6 @@ public: }; ``` -### **Go** - ```go func getKth(lo int, hi int, k int) int { f := func(x int) (ans int) { @@ -178,8 +170,6 @@ func getKth(lo int, hi int, k int) int { } ``` -### **TypeScript** - ```ts function getKth(lo: number, hi: number, k: number): number { const f = (x: number): number => { @@ -203,10 +193,6 @@ function getKth(lo: number, hi: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1388.Pizza With 3n Slices/README.md b/solution/1300-1399/1388.Pizza With 3n Slices/README.md index c914caf347a6f..edeb1818bea55 100644 --- a/solution/1300-1399/1388.Pizza With 3n Slices/README.md +++ b/solution/1300-1399/1388.Pizza With 3n Slices/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们可以将这个问题转化为:在一个长度为 $3n$ 的环形数组中,选择其中 $n$ 个不相邻的数,使得这 $n$ 个数的和最大。 @@ -86,10 +84,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxSizeSlices(self, slices: List[int]) -> int: @@ -108,10 +102,6 @@ class Solution: return max(a, b) ``` -### **Java** - - - ```java class Solution { private int n; @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -166,8 +154,6 @@ public: }; ``` -### **Go** - ```go func maxSizeSlices(slices []int) int { n := len(slices) / 3 @@ -192,8 +178,6 @@ func maxSizeSlices(slices []int) int { } ``` -### **TypeScript** - ```ts function maxSizeSlices(slices: number[]): number { const n = Math.floor(slices.length / 3); @@ -215,10 +199,6 @@ function maxSizeSlices(slices: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1388.Pizza With 3n Slices/README_EN.md b/solution/1300-1399/1388.Pizza With 3n Slices/README_EN.md index 9d43394a8cb9d..29d0ffd9836f7 100644 --- a/solution/1300-1399/1388.Pizza With 3n Slices/README_EN.md +++ b/solution/1300-1399/1388.Pizza With 3n Slices/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We can transform this problem into: In a circular array of length $3n$, select $n$ non-adjacent numbers so that the sum of these $n$ numbers is maximized. @@ -74,8 +74,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ -### **Python3** - ```python class Solution: def maxSizeSlices(self, slices: List[int]) -> int: @@ -94,8 +92,6 @@ class Solution: return max(a, b) ``` -### **Java** - ```java class Solution { private int n; @@ -123,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +144,6 @@ public: }; ``` -### **Go** - ```go func maxSizeSlices(slices []int) int { n := len(slices) / 3 @@ -176,8 +168,6 @@ func maxSizeSlices(slices []int) int { } ``` -### **TypeScript** - ```ts function maxSizeSlices(slices: number[]): number { const n = Math.floor(slices.length / 3); @@ -199,10 +189,6 @@ function maxSizeSlices(slices: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1389.Create Target Array in the Given Order/README.md b/solution/1300-1399/1389.Create Target Array in the Given Order/README.md index 097a6189abd72..9264ef84f7ec2 100644 --- a/solution/1300-1399/1389.Create Target Array in the Given Order/README.md +++ b/solution/1300-1399/1389.Create Target Array in the Given Order/README.md @@ -65,9 +65,7 @@ nums index target ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们创建一个列表 $target$,用于存储目标数组。由于题目保证数字插入位置总是存在,因此我们可以直接按照给定的顺序插入到对应的位置。 @@ -75,10 +73,6 @@ nums index target -### **Python3** - - - ```python class Solution: def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: @@ -88,10 +82,6 @@ class Solution: return target ``` -### **Java** - - - ```java class Solution { public int[] createTargetArray(int[] nums, int[] index) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func createTargetArray(nums []int, index []int) []int { target := make([]int, len(nums)) @@ -138,8 +124,6 @@ func createTargetArray(nums []int, index []int) []int { } ``` -### **TypeScript** - ```ts function createTargetArray(nums: number[], index: number[]): number[] { const ans: number[] = []; @@ -150,10 +134,6 @@ function createTargetArray(nums: number[], index: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1389.Create Target Array in the Given Order/README_EN.md b/solution/1300-1399/1389.Create Target Array in the Given Order/README_EN.md index e8c837478d34b..8891b856a7b3c 100644 --- a/solution/1300-1399/1389.Create Target Array in the Given Order/README_EN.md +++ b/solution/1300-1399/1389.Create Target Array in the Given Order/README_EN.md @@ -64,7 +64,7 @@ nums index target ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We create a list $target$ to store the target array. Since the problem guarantees that the insertion position always exists, we can directly insert in the given order into the corresponding position. @@ -72,8 +72,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ i -### **Python3** - ```python class Solution: def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: @@ -83,8 +81,6 @@ class Solution: return target ``` -### **Java** - ```java class Solution { public int[] createTargetArray(int[] nums, int[] index) { @@ -103,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func createTargetArray(nums []int, index []int) []int { target := make([]int, len(nums)) @@ -131,8 +123,6 @@ func createTargetArray(nums []int, index []int) []int { } ``` -### **TypeScript** - ```ts function createTargetArray(nums: number[], index: number[]): number[] { const ans: number[] = []; @@ -143,10 +133,6 @@ function createTargetArray(nums: number[], index: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1390.Four Divisors/README.md b/solution/1300-1399/1390.Four Divisors/README.md index 16e692cbfb59e..832618a1645b1 100644 --- a/solution/1300-1399/1390.Four Divisors/README.md +++ b/solution/1300-1399/1390.Four Divisors/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:因数分解** +### 方法一:因数分解 我们可以对每个数进行因数分解,如果因数的个数为 $4$ 个,那么这个数就是符合题意的数,我们将其因数累加到答案中即可。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def sumFourDivisors(self, nums: List[int]) -> int: @@ -79,10 +73,6 @@ class Solution: return sum(f(x) for x in nums) ``` -### **Java** - - - ```java class Solution { public int sumFourDivisors(int[] nums) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func sumFourDivisors(nums []int) (ans int) { f := func(x int) int { @@ -168,8 +154,6 @@ func sumFourDivisors(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumFourDivisors(nums: number[]): number { const f = (x: number): number => { @@ -195,10 +179,6 @@ function sumFourDivisors(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1390.Four Divisors/README_EN.md b/solution/1300-1399/1390.Four Divisors/README_EN.md index 5211d216cb168..80f23fe6f65ae 100644 --- a/solution/1300-1399/1390.Four Divisors/README_EN.md +++ b/solution/1300-1399/1390.Four Divisors/README_EN.md @@ -43,7 +43,7 @@ The answer is the sum of divisors of 21 only. ## Solutions -**Solution 1: Factor Decomposition** +### Solution 1: Factor Decomposition We can perform factor decomposition on each number. If the number of factors is $4$, then this number meets the requirements of the problem, and we can add its factors to the answer. @@ -51,8 +51,6 @@ The time complexity is $O(n \times \sqrt{n})$, where $n$ is the length of the ar -### **Python3** - ```python class Solution: def sumFourDivisors(self, nums: List[int]) -> int: @@ -72,8 +70,6 @@ class Solution: return sum(f(x) for x in nums) ``` -### **Java** - ```java class Solution { public int sumFourDivisors(int[] nums) { @@ -101,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +125,6 @@ public: }; ``` -### **Go** - ```go func sumFourDivisors(nums []int) (ans int) { f := func(x int) int { @@ -159,8 +151,6 @@ func sumFourDivisors(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumFourDivisors(nums: number[]): number { const f = (x: number): number => { @@ -186,10 +176,6 @@ function sumFourDivisors(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1391.Check if There is a Valid Path in a Grid/README.md b/solution/1300-1399/1391.Check if There is a Valid Path in a Grid/README.md index 4213b02336fe2..33087024d0d5c 100644 --- a/solution/1300-1399/1391.Check if There is a Valid Path in a Grid/README.md +++ b/solution/1300-1399/1391.Check if There is a Valid Path in a Grid/README.md @@ -77,81 +77,10 @@ ## 解法 - - -并查集。判断每个单元格相邻节点是否连通,是则将其合并。最后判断 `grid[0][0]` 与 `grid[m - 1][n - 1]` 是否连通。 - -并查集模板: - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` +### 方法一 -### **Python3** - - - ```python class Solution: def hasValidPath(self, grid: List[List[int]]) -> bool: @@ -203,10 +132,6 @@ class Solution: return find(0) == find(m * n - 1) ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -282,8 +207,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -348,8 +271,6 @@ public: }; ``` -### **Go** - ```go func hasValidPath(grid [][]int) bool { m, n := len(grid), len(grid[0]) @@ -411,10 +332,6 @@ func hasValidPath(grid [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1391.Check if There is a Valid Path in a Grid/README_EN.md b/solution/1300-1399/1391.Check if There is a Valid Path in a Grid/README_EN.md index 2d54c4dbc1dc1..119268cdc29c4 100644 --- a/solution/1300-1399/1391.Check if There is a Valid Path in a Grid/README_EN.md +++ b/solution/1300-1399/1391.Check if There is a Valid Path in a Grid/README_EN.md @@ -58,12 +58,10 @@ ## Solutions -Union find. +### Solution 1 -### **Python3** - ```python class Solution: def hasValidPath(self, grid: List[List[int]]) -> bool: @@ -115,8 +113,6 @@ class Solution: return find(0) == find(m * n - 1) ``` -### **Java** - ```java class Solution { private int[] p; @@ -192,8 +188,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -258,8 +252,6 @@ public: }; ``` -### **Go** - ```go func hasValidPath(grid [][]int) bool { m, n := len(grid), len(grid[0]) @@ -321,10 +313,6 @@ func hasValidPath(grid [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1392.Longest Happy Prefix/README.md b/solution/1300-1399/1392.Longest Happy Prefix/README.md index fb8d83a83d37b..cc01157092cb0 100644 --- a/solution/1300-1399/1392.Longest Happy Prefix/README.md +++ b/solution/1300-1399/1392.Longest Happy Prefix/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:字符串哈希** +### 方法一:字符串哈希 **字符串哈希**是把一个任意长度的字符串映射成一个非负整数,并且其冲突的概率几乎为 0。字符串哈希用于计算字符串哈希值,快速判断两个字符串是否相等。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def longestPrefix(self, s: str) -> str: @@ -66,10 +60,6 @@ class Solution: return '' ``` -### **Java** - - - ```java class Solution { private long[] p; @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef unsigned long long ULL; @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func longestPrefix(s string) string { base := 131 @@ -150,8 +136,6 @@ func longestPrefix(s string) string { } ``` -### **TypeScript** - ```ts function longestPrefix(s: string): string { const n = s.length; @@ -164,8 +148,6 @@ function longestPrefix(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn longest_prefix(s: String) -> String { @@ -180,10 +162,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1392.Longest Happy Prefix/README_EN.md b/solution/1300-1399/1392.Longest Happy Prefix/README_EN.md index 300a1fbfcbd5b..3f8593e2baed6 100644 --- a/solution/1300-1399/1392.Longest Happy Prefix/README_EN.md +++ b/solution/1300-1399/1392.Longest Happy Prefix/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: String Hashing** +### Solution 1: String Hashing **String Hashing** is a method to map a string of any length to a non-negative integer, with the probability of collision being almost zero. String hashing is used to calculate the hash value of a string, which allows for quick determination of whether two strings are equal. @@ -47,8 +47,6 @@ Except for extremely specially constructed data, the above hash algorithm is unl -### **Python3** - ```python class Solution: def longestPrefix(self, s: str) -> str: @@ -58,8 +56,6 @@ class Solution: return '' ``` -### **Java** - ```java class Solution { private long[] p; @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef unsigned long long ULL; @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func longestPrefix(s string) string { base := 131 @@ -140,8 +132,6 @@ func longestPrefix(s string) string { } ``` -### **TypeScript** - ```ts function longestPrefix(s: string): string { const n = s.length; @@ -154,8 +144,6 @@ function longestPrefix(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn longest_prefix(s: String) -> String { @@ -170,10 +158,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1393.Capital GainLoss/README.md b/solution/1300-1399/1393.Capital GainLoss/README.md index d373e5c015940..8884579a5c606 100644 --- a/solution/1300-1399/1393.Capital GainLoss/README.md +++ b/solution/1300-1399/1393.Capital GainLoss/README.md @@ -70,16 +70,12 @@ Corona Masks 股票在第1天以10美元的价格买入,在第3天以1010美 ## 解法 - - -**方法一:GROUP BY + SUM(IF())** +### 方法一:GROUP BY + SUM(IF()) 我们使用 `GROUP BY` 将同一支股票的买卖操作分组,然后使用 `SUM(IF())` 计算每支股票的资本损益。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -90,3 +86,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1300-1399/1393.Capital GainLoss/README_EN.md b/solution/1300-1399/1393.Capital GainLoss/README_EN.md index 759ba6b37fbd7..3bf7fb528ab9a 100644 --- a/solution/1300-1399/1393.Capital GainLoss/README_EN.md +++ b/solution/1300-1399/1393.Capital GainLoss/README_EN.md @@ -67,14 +67,12 @@ Corona Masks stock was bought at day 1 for 10$ and was sold at day 3 for 1010$. ## Solutions -**Solution 1: GROUP BY + SUM(IF())** +### Solution 1: GROUP BY + SUM(IF()) We use `GROUP BY` to group the buy and sell operations of the same stock, and then use `SUM(IF())` to calculate the capital gains and losses of each stock. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -85,3 +83,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1300-1399/1394.Find Lucky Integer in an Array/README.md b/solution/1300-1399/1394.Find Lucky Integer in an Array/README.md index f9236177f2e14..0689bed6d1980 100644 --- a/solution/1300-1399/1394.Find Lucky Integer in an Array/README.md +++ b/solution/1300-1399/1394.Find Lucky Integer in an Array/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们可以用哈希表或数组 $cnt$ 统计 $arr$ 中每个数字出现的次数,然后遍历 $cnt$,找到满足 $cnt[x] = x$ 的最大的 $x$ 即可。如果没有这样的 $x$,则返回 $-1$。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def findLucky(self, arr: List[int]) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int findLucky(int[] arr) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func findLucky(arr []int) int { cnt := [510]int{} @@ -148,7 +134,21 @@ func findLucky(arr []int) int { } ``` -### **PHP** +```ts +function findLucky(arr: number[]): number { + const cnt = new Array(510).fill(0); + for (const x of arr) { + ++cnt[x]; + } + let ans = -1; + for (let x = 1; x < cnt.length; ++x) { + if (cnt[x] === x) { + ans = x; + } + } + return ans; +} +``` ```php class Solution { @@ -172,28 +172,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function findLucky(arr: number[]): number { - const cnt = new Array(510).fill(0); - for (const x of arr) { - ++cnt[x]; - } - let ans = -1; - for (let x = 1; x < cnt.length; ++x) { - if (cnt[x] === x) { - ans = x; - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1394.Find Lucky Integer in an Array/README_EN.md b/solution/1300-1399/1394.Find Lucky Integer in an Array/README_EN.md index da0541451a21e..14fa160de51a4 100644 --- a/solution/1300-1399/1394.Find Lucky Integer in an Array/README_EN.md +++ b/solution/1300-1399/1394.Find Lucky Integer in an Array/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We can use a hash table or array $cnt$ to count the occurrences of each number in $arr$, then traverse $cnt$ to find the largest $x$ that satisfies $cnt[x] = x$. If there is no such $x$, return $-1$. @@ -51,8 +51,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def findLucky(self, arr: List[int]) -> int: @@ -64,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int findLucky(int[] arr) { @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +100,6 @@ public: }; ``` -### **Go** - ```go func findLucky(arr []int) int { cnt := [510]int{} @@ -124,7 +116,21 @@ func findLucky(arr []int) int { } ``` -### **PHP** +```ts +function findLucky(arr: number[]): number { + const cnt = new Array(510).fill(0); + for (const x of arr) { + ++cnt[x]; + } + let ans = -1; + for (let x = 1; x < cnt.length; ++x) { + if (cnt[x] === x) { + ans = x; + } + } + return ans; +} +``` ```php class Solution { @@ -148,28 +154,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function findLucky(arr: number[]): number { - const cnt = new Array(510).fill(0); - for (const x of arr) { - ++cnt[x]; - } - let ans = -1; - for (let x = 1; x < cnt.length; ++x) { - if (cnt[x] === x) { - ans = x; - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1395.Count Number of Teams/README.md b/solution/1300-1399/1395.Count Number of Teams/README.md index f0c26261834da..c2a7a53086a36 100644 --- a/solution/1300-1399/1395.Count Number of Teams/README.md +++ b/solution/1300-1399/1395.Count Number of Teams/README.md @@ -55,26 +55,14 @@ ## 解法 - - -**方法一:枚举中间元素** +### 方法一:枚举中间元素 我们可以枚举数组 $rating$ 中每个元素 $rating[i]$ 作为中间元素,然后统计左边比它小的元素的个数 $l$,右边比它大的元素的个数 $r$,那么以该元素为中间元素的作战单位的个数为 $l \times r + (i - l) \times (n - i - 1 - r)$,累加到答案中即可。 时间复杂度 $O(n^2)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $rating$ 的长度。 -**方法二:树状数组** - -我们可以用两个树状数组分别维护数组 $rating$ 中每个元素的左边比它小的元素的个数 $l$,右边比它大的元素的个数 $r$,然后统计以该元素为中间元素的作战单位的个数为 $l \times r + (i - l) \times (n - i - 1 - r)$,累加到答案中即可。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $rating$ 的长度。 - -### **Python3** - - - ```python class Solution: def numTeams(self, rating: List[int]) -> int: @@ -87,6 +75,113 @@ class Solution: return ans ``` +```java +class Solution { + public int numTeams(int[] rating) { + int n = rating.length; + int ans = 0; + for (int i = 0; i < n; ++i) { + int l = 0, r = 0; + for (int j = 0; j < i; ++j) { + if (rating[j] < rating[i]) { + ++l; + } + } + for (int j = i + 1; j < n; ++j) { + if (rating[j] > rating[i]) { + ++r; + } + } + ans += l * r; + ans += (i - l) * (n - i - 1 - r); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int numTeams(vector& rating) { + int n = rating.size(); + int ans = 0; + for (int i = 0; i < n; ++i) { + int l = 0, r = 0; + for (int j = 0; j < i; ++j) { + if (rating[j] < rating[i]) { + ++l; + } + } + for (int j = i + 1; j < n; ++j) { + if (rating[j] > rating[i]) { + ++r; + } + } + ans += l * r; + ans += (i - l) * (n - i - 1 - r); + } + return ans; + } +}; +``` + +```go +func numTeams(rating []int) (ans int) { + n := len(rating) + for i, b := range rating { + l, r := 0, 0 + for _, a := range rating[:i] { + if a < b { + l++ + } + } + for _, c := range rating[i+1:] { + if c < b { + r++ + } + } + ans += l * r + ans += (i - l) * (n - i - 1 - r) + } + return +} +``` + +```ts +function numTeams(rating: number[]): number { + let ans = 0; + const n = rating.length; + for (let i = 0; i < n; ++i) { + let l = 0; + let r = 0; + for (let j = 0; j < i; ++j) { + if (rating[j] < rating[i]) { + ++l; + } + } + for (let j = i + 1; j < n; ++j) { + if (rating[j] > rating[i]) { + ++r; + } + } + ans += l * r; + ans += (i - l) * (n - i - 1 - r); + } + return ans; +} +``` + + + +### 方法二:树状数组 + +我们可以用两个树状数组分别维护数组 $rating$ 中每个元素的左边比它小的元素的个数 $l$,右边比它大的元素的个数 $r$,然后统计以该元素为中间元素的作战单位的个数为 $l \times r + (i - l) \times (n - i - 1 - r)$,累加到答案中即可。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $rating$ 的长度。 + + + ```python class BinaryIndexedTree: def __init__(self, n: int): @@ -128,35 +223,6 @@ class Solution: return ans ``` -### **Java** - - - -```java -class Solution { - public int numTeams(int[] rating) { - int n = rating.length; - int ans = 0; - for (int i = 0; i < n; ++i) { - int l = 0, r = 0; - for (int j = 0; j < i; ++j) { - if (rating[j] < rating[i]) { - ++l; - } - } - for (int j = i + 1; j < n; ++j) { - if (rating[j] > rating[i]) { - ++r; - } - } - ans += l * r; - ans += (i - l) * (n - i - 1 - r); - } - return ans; - } -} -``` - ```java class BinaryIndexedTree { private int n; @@ -230,34 +296,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numTeams(vector& rating) { - int n = rating.size(); - int ans = 0; - for (int i = 0; i < n; ++i) { - int l = 0, r = 0; - for (int j = 0; j < i; ++j) { - if (rating[j] < rating[i]) { - ++l; - } - } - for (int j = i + 1; j < n; ++j) { - if (rating[j] > rating[i]) { - ++r; - } - } - ans += l * r; - ans += (i - l) * (n - i - 1 - r); - } - return ans; - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -315,30 +353,6 @@ public: }; ``` -### **Go** - -```go -func numTeams(rating []int) (ans int) { - n := len(rating) - for i, b := range rating { - l, r := 0, 0 - for _, a := range rating[:i] { - if a < b { - l++ - } - } - for _, c := range rating[i+1:] { - if c < b { - r++ - } - } - ans += l * r - ans += (i - l) * (n - i - 1 - r) - } - return -} -``` - ```go type BinaryIndexedTree struct { n int @@ -397,32 +411,6 @@ func numTeams(rating []int) (ans int) { } ``` -### **TypeScript** - -```ts -function numTeams(rating: number[]): number { - let ans = 0; - const n = rating.length; - for (let i = 0; i < n; ++i) { - let l = 0; - let r = 0; - for (let j = 0; j < i; ++j) { - if (rating[j] < rating[i]) { - ++l; - } - } - for (let j = i + 1; j < n; ++j) { - if (rating[j] > rating[i]) { - ++r; - } - } - ans += l * r; - ans += (i - l) * (n - i - 1 - r); - } - return ans; -} -``` - ```ts class BinaryIndexedTree { private n: number; @@ -493,10 +481,6 @@ function numTeams(rating: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1395.Count Number of Teams/README_EN.md b/solution/1300-1399/1395.Count Number of Teams/README_EN.md index b9c2f9434b5ab..4bda7196eb48c 100644 --- a/solution/1300-1399/1395.Count Number of Teams/README_EN.md +++ b/solution/1300-1399/1395.Count Number of Teams/README_EN.md @@ -51,22 +51,14 @@ ## Solutions -**Solution 1: Enumerate Middle Element** +### Solution 1: Enumerate Middle Element We can enumerate each element $rating[i]$ in the array $rating$ as the middle element, then count the number of elements $l$ that are smaller than it on the left, and the number of elements $r$ that are larger than it on the right. The number of combat units with this element as the middle element is $l \times r + (i - l) \times (n - i - 1 - r)$. We can add this to the answer. The time complexity is $O(n^2)$, and the space complexity is $O(1)$. Where $n$ is the length of the array $rating$. -**Solution 2: Binary Indexed Tree** - -We can use two binary indexed trees to maintain the number of elements $l$ that are smaller than each element on the left in the array $rating$, and the number of elements $r$ that are larger than it on the right. Then count the number of combat units with this element as the middle element as $l \times r + (i - l) \times (n - i - 1 - r)$, and add this to the answer. - -The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $rating$. - -### **Python3** - ```python class Solution: def numTeams(self, rating: List[int]) -> int: @@ -79,6 +71,113 @@ class Solution: return ans ``` +```java +class Solution { + public int numTeams(int[] rating) { + int n = rating.length; + int ans = 0; + for (int i = 0; i < n; ++i) { + int l = 0, r = 0; + for (int j = 0; j < i; ++j) { + if (rating[j] < rating[i]) { + ++l; + } + } + for (int j = i + 1; j < n; ++j) { + if (rating[j] > rating[i]) { + ++r; + } + } + ans += l * r; + ans += (i - l) * (n - i - 1 - r); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int numTeams(vector& rating) { + int n = rating.size(); + int ans = 0; + for (int i = 0; i < n; ++i) { + int l = 0, r = 0; + for (int j = 0; j < i; ++j) { + if (rating[j] < rating[i]) { + ++l; + } + } + for (int j = i + 1; j < n; ++j) { + if (rating[j] > rating[i]) { + ++r; + } + } + ans += l * r; + ans += (i - l) * (n - i - 1 - r); + } + return ans; + } +}; +``` + +```go +func numTeams(rating []int) (ans int) { + n := len(rating) + for i, b := range rating { + l, r := 0, 0 + for _, a := range rating[:i] { + if a < b { + l++ + } + } + for _, c := range rating[i+1:] { + if c < b { + r++ + } + } + ans += l * r + ans += (i - l) * (n - i - 1 - r) + } + return +} +``` + +```ts +function numTeams(rating: number[]): number { + let ans = 0; + const n = rating.length; + for (let i = 0; i < n; ++i) { + let l = 0; + let r = 0; + for (let j = 0; j < i; ++j) { + if (rating[j] < rating[i]) { + ++l; + } + } + for (let j = i + 1; j < n; ++j) { + if (rating[j] > rating[i]) { + ++r; + } + } + ans += l * r; + ans += (i - l) * (n - i - 1 - r); + } + return ans; +} +``` + + + +### Solution 2: Binary Indexed Tree + +We can use two binary indexed trees to maintain the number of elements $l$ that are smaller than each element on the left in the array $rating$, and the number of elements $r$ that are larger than it on the right. Then count the number of combat units with this element as the middle element as $l \times r + (i - l) \times (n - i - 1 - r)$, and add this to the answer. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $rating$. + + + ```python class BinaryIndexedTree: def __init__(self, n: int): @@ -120,33 +219,6 @@ class Solution: return ans ``` -### **Java** - -```java -class Solution { - public int numTeams(int[] rating) { - int n = rating.length; - int ans = 0; - for (int i = 0; i < n; ++i) { - int l = 0, r = 0; - for (int j = 0; j < i; ++j) { - if (rating[j] < rating[i]) { - ++l; - } - } - for (int j = i + 1; j < n; ++j) { - if (rating[j] > rating[i]) { - ++r; - } - } - ans += l * r; - ans += (i - l) * (n - i - 1 - r); - } - return ans; - } -} -``` - ```java class BinaryIndexedTree { private int n; @@ -220,34 +292,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numTeams(vector& rating) { - int n = rating.size(); - int ans = 0; - for (int i = 0; i < n; ++i) { - int l = 0, r = 0; - for (int j = 0; j < i; ++j) { - if (rating[j] < rating[i]) { - ++l; - } - } - for (int j = i + 1; j < n; ++j) { - if (rating[j] > rating[i]) { - ++r; - } - } - ans += l * r; - ans += (i - l) * (n - i - 1 - r); - } - return ans; - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -305,30 +349,6 @@ public: }; ``` -### **Go** - -```go -func numTeams(rating []int) (ans int) { - n := len(rating) - for i, b := range rating { - l, r := 0, 0 - for _, a := range rating[:i] { - if a < b { - l++ - } - } - for _, c := range rating[i+1:] { - if c < b { - r++ - } - } - ans += l * r - ans += (i - l) * (n - i - 1 - r) - } - return -} -``` - ```go type BinaryIndexedTree struct { n int @@ -387,32 +407,6 @@ func numTeams(rating []int) (ans int) { } ``` -### **TypeScript** - -```ts -function numTeams(rating: number[]): number { - let ans = 0; - const n = rating.length; - for (let i = 0; i < n; ++i) { - let l = 0; - let r = 0; - for (let j = 0; j < i; ++j) { - if (rating[j] < rating[i]) { - ++l; - } - } - for (let j = i + 1; j < n; ++j) { - if (rating[j] > rating[i]) { - ++r; - } - } - ans += l * r; - ans += (i - l) * (n - i - 1 - r); - } - return ans; -} -``` - ```ts class BinaryIndexedTree { private n: number; @@ -483,10 +477,6 @@ function numTeams(rating: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1396.Design Underground System/README.md b/solution/1300-1399/1396.Design Underground System/README.md index f90b66bd4d724..ae45e9efe3b01 100644 --- a/solution/1300-1399/1396.Design Underground System/README.md +++ b/solution/1300-1399/1396.Design Underground System/README.md @@ -98,9 +98,7 @@ undergroundSystem.getAverageTime("Leyton", "Paradise"); // 返回 6.66667 ,(5 ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们用两个哈希表来存储数据,其中: @@ -117,10 +115,6 @@ undergroundSystem.getAverageTime("Leyton", "Paradise"); // 返回 6.66667 ,(5 -### **Python3** - - - ```python class UndergroundSystem: def __init__(self): @@ -147,10 +141,6 @@ class UndergroundSystem: # param_3 = obj.getAverageTime(startStation,endStation) ``` -### **Java** - - - ```java class UndergroundSystem { private Map ts = new HashMap<>(); @@ -189,8 +179,6 @@ class UndergroundSystem { */ ``` -### **C++** - ```cpp class UndergroundSystem { public: @@ -227,8 +215,6 @@ private: */ ``` -### **Go** - ```go type UndergroundSystem struct { ts map[int]pair @@ -281,10 +267,6 @@ type pair struct { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1396.Design Underground System/README_EN.md b/solution/1300-1399/1396.Design Underground System/README_EN.md index 100da40da87db..3d9ce2a797d1d 100644 --- a/solution/1300-1399/1396.Design Underground System/README_EN.md +++ b/solution/1300-1399/1396.Design Underground System/README_EN.md @@ -95,7 +95,7 @@ undergroundSystem.getAverageTime("Leyton", "Paradise"); // r ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We use two hash tables to store data: @@ -112,8 +112,6 @@ The time complexity is $O(1)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class UndergroundSystem: def __init__(self): @@ -140,8 +138,6 @@ class UndergroundSystem: # param_3 = obj.getAverageTime(startStation,endStation) ``` -### **Java** - ```java class UndergroundSystem { private Map ts = new HashMap<>(); @@ -180,8 +176,6 @@ class UndergroundSystem { */ ``` -### **C++** - ```cpp class UndergroundSystem { public: @@ -218,8 +212,6 @@ private: */ ``` -### **Go** - ```go type UndergroundSystem struct { ts map[int]pair @@ -272,10 +264,6 @@ type pair struct { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1397.Find All Good Strings/README.md b/solution/1300-1399/1397.Find All Good Strings/README.md index 1bb49dc2773c8..f6cd494c60a12 100644 --- a/solution/1300-1399/1397.Find All Good Strings/README.md +++ b/solution/1300-1399/1397.Find All Good Strings/README.md @@ -49,30 +49,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1300-1399/1397.Find All Good Strings/README_EN.md b/solution/1300-1399/1397.Find All Good Strings/README_EN.md index 716d6036701a1..ecfaabc6a8f48 100644 --- a/solution/1300-1399/1397.Find All Good Strings/README_EN.md +++ b/solution/1300-1399/1397.Find All Good Strings/README_EN.md @@ -46,24 +46,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1300-1399/1398.Customers Who Bought Products A and B but Not C/README.md b/solution/1300-1399/1398.Customers Who Bought Products A and B but Not C/README.md index 15245dea69032..f46a609f5fd29 100644 --- a/solution/1300-1399/1398.Customers Who Bought Products A and B but Not C/README.md +++ b/solution/1300-1399/1398.Customers Who Bought Products A and B but Not C/README.md @@ -83,16 +83,12 @@ Orders table: ## 解法 - - -**方法一:LEFT JOIN + GROUP BY + HAVING** +### 方法一:LEFT JOIN + GROUP BY + HAVING 我们可以用 `LEFT JOIN` 将 `Customers` 表和 `Orders` 表连接起来,然后按照 `customer_id` 进行分组,最后筛选出购买了产品 A 和产品 B 却没有购买产品 C 的顾客。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT customer_id, customer_name @@ -105,3 +101,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1300-1399/1398.Customers Who Bought Products A and B but Not C/README_EN.md b/solution/1300-1399/1398.Customers Who Bought Products A and B but Not C/README_EN.md index 4f2f79ffaf01b..25fd407c0cf95 100644 --- a/solution/1300-1399/1398.Customers Who Bought Products A and B but Not C/README_EN.md +++ b/solution/1300-1399/1398.Customers Who Bought Products A and B but Not C/README_EN.md @@ -79,14 +79,12 @@ Orders table: ## Solutions -**Solution 1: LEFT JOIN + GROUP BY + HAVING** +### Solution 1: LEFT JOIN + GROUP BY + HAVING We can use `LEFT JOIN` to join the `Customers` table and the `Orders` table, then group them by `customer_id`, and finally filter out the customers who have purchased products A and B but not product C. -### **SQL** - ```sql # Write your MySQL query statement below SELECT customer_id, customer_name @@ -99,3 +97,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1300-1399/1399.Count Largest Group/README.md b/solution/1300-1399/1399.Count Largest Group/README.md index 80b56e474cfeb..cfb2add0bbdbc 100644 --- a/solution/1300-1399/1399.Count Largest Group/README.md +++ b/solution/1300-1399/1399.Count Largest Group/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:哈希表或数组** +### 方法一:哈希表或数组 我们注意到数字范围不超过 $10^4$,因此数位和的范围也不超过 $9 \times 4 = 36$,因此我们可以用哈希表或者一个长度为 $40$ 的数组 $cnt$ 来统计每个数位和的个数,用一个变量 $mx$ 表示最大的数位和个数。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def countLargestGroup(self, n: int) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countLargestGroup(int n) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +127,6 @@ public: }; ``` -### **Go** - ```go func countLargestGroup(n int) (ans int) { cnt := [40]int{} @@ -162,8 +148,6 @@ func countLargestGroup(n int) (ans int) { } ``` -### **TypeScript** - ```ts function countLargestGroup(n: number): number { const cnt: number[] = new Array(40).fill(0); @@ -186,10 +170,6 @@ function countLargestGroup(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1300-1399/1399.Count Largest Group/README_EN.md b/solution/1300-1399/1399.Count Largest Group/README_EN.md index c83a726fb3239..496aefec528f0 100644 --- a/solution/1300-1399/1399.Count Largest Group/README_EN.md +++ b/solution/1300-1399/1399.Count Largest Group/README_EN.md @@ -38,7 +38,7 @@ There are 4 groups with largest size. ## Solutions -**Solution 1: Hash Table or Array** +### Solution 1: Hash Table or Array We note that the number does not exceed $10^4$, so the sum of the digits also does not exceed $9 \times 4 = 36$. Therefore, we can use a hash table or an array of length $40$, denoted as $cnt$, to count the number of each sum of digits, and use a variable $mx$ to represent the maximum count of the sum of digits. @@ -50,8 +50,6 @@ The time complexity is $O(n \times \log M)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def countLargestGroup(self, n: int) -> int: @@ -71,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countLargestGroup(int n) { @@ -96,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func countLargestGroup(n int) (ans int) { cnt := [40]int{} @@ -145,8 +137,6 @@ func countLargestGroup(n int) (ans int) { } ``` -### **TypeScript** - ```ts function countLargestGroup(n: number): number { const cnt: number[] = new Array(40).fill(0); @@ -169,10 +159,6 @@ function countLargestGroup(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1400.Construct K Palindrome Strings/README.md b/solution/1400-1499/1400.Construct K Palindrome Strings/README.md index 4aaa99380f9a8..48d90560eb540 100644 --- a/solution/1400-1499/1400.Construct K Palindrome Strings/README.md +++ b/solution/1400-1499/1400.Construct K Palindrome Strings/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们先判断字符串 $s$ 的长度是否小于 $k$,如果是,那么一定无法构造出 $k$ 个回文串,可以直接返回 `false`。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def canConstruct(self, s: str, k: int) -> bool: @@ -90,10 +84,6 @@ class Solution: return sum(v & 1 for v in cnt.values()) <= k ``` -### **Java** - - - ```java class Solution { public boolean canConstruct(String s, int k) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func canConstruct(s string, k int) bool { if len(s) < k { @@ -155,8 +141,6 @@ func canConstruct(s string, k int) bool { } ``` -### **TypeScript** - ```ts function canConstruct(s: string, k: number): boolean { if (s.length < k) { @@ -174,10 +158,6 @@ function canConstruct(s: string, k: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1400.Construct K Palindrome Strings/README_EN.md b/solution/1400-1499/1400.Construct K Palindrome Strings/README_EN.md index 3e28998b9563b..2c5c1c6683197 100644 --- a/solution/1400-1499/1400.Construct K Palindrome Strings/README_EN.md +++ b/solution/1400-1499/1400.Construct K Palindrome Strings/README_EN.md @@ -43,7 +43,7 @@ Some possible constructions "anna" + "elble", "anbna&qu ## Solutions -**Solution 1: Counting** +### Solution 1: Counting First, we check if the length of string $s$ is less than $k$. If it is, we cannot construct $k$ palindrome strings, so we can directly return `false`. @@ -53,8 +53,6 @@ The time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is -### **Python3** - ```python class Solution: def canConstruct(self, s: str, k: int) -> bool: @@ -64,8 +62,6 @@ class Solution: return sum(v & 1 for v in cnt.values()) <= k ``` -### **Java** - ```java class Solution { public boolean canConstruct(String s, int k) { @@ -86,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +102,6 @@ public: }; ``` -### **Go** - ```go func canConstruct(s string, k int) bool { if len(s) < k { @@ -127,8 +119,6 @@ func canConstruct(s string, k int) bool { } ``` -### **TypeScript** - ```ts function canConstruct(s: string, k: number): boolean { if (s.length < k) { @@ -146,10 +136,6 @@ function canConstruct(s: string, k: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1401.Circle and Rectangle Overlapping/README.md b/solution/1400-1499/1401.Circle and Rectangle Overlapping/README.md index 9c999c9643f28..0fefc2a08a7b6 100644 --- a/solution/1400-1499/1401.Circle and Rectangle Overlapping/README.md +++ b/solution/1400-1499/1401.Circle and Rectangle Overlapping/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 对于一个点 $(x, y)$,它到圆心 $(xCenter, yCenter)$ 的最短距离为 $\sqrt{(x - xCenter)^2 + (y - yCenter)^2}$,如果这个距离小于等于半径 $radius$,那么这个点就在圆内(包括边界)。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def checkOverlap( @@ -97,10 +91,6 @@ class Solution: return a * a + b * b <= radius * radius ``` -### **Java** - - - ```java class Solution { public boolean checkOverlap( @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func checkOverlap(radius int, xCenter int, yCenter int, x1 int, y1 int, x2 int, y2 int) bool { f := func(i, j, k int) int { @@ -157,8 +143,6 @@ func checkOverlap(radius int, xCenter int, yCenter int, x1 int, y1 int, x2 int, } ``` -### **TypeScript** - ```ts function checkOverlap( radius: number, @@ -181,10 +165,6 @@ function checkOverlap( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1401.Circle and Rectangle Overlapping/README_EN.md b/solution/1400-1499/1401.Circle and Rectangle Overlapping/README_EN.md index d7eb98ff9acf4..801ae10694b5d 100644 --- a/solution/1400-1499/1401.Circle and Rectangle Overlapping/README_EN.md +++ b/solution/1400-1499/1401.Circle and Rectangle Overlapping/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics For a point $(x, y)$, its shortest distance to the center of the circle $(xCenter, yCenter)$ is $\sqrt{(x - xCenter)^2 + (y - yCenter)^2}$. If this distance is less than or equal to the radius $radius$, then this point is within the circle (including the boundary). @@ -63,8 +63,6 @@ That is, $a = f(x_1, x_2, xCenter)$, $b = f(y_1, y_2, yCenter)$. If $a^2 + b^2 \ -### **Python3** - ```python class Solution: def checkOverlap( @@ -87,8 +85,6 @@ class Solution: return a * a + b * b <= radius * radius ``` -### **Java** - ```java class Solution { public boolean checkOverlap( @@ -107,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +120,6 @@ public: }; ``` -### **Go** - ```go func checkOverlap(radius int, xCenter int, yCenter int, x1 int, y1 int, x2 int, y2 int) bool { f := func(i, j, k int) int { @@ -145,8 +137,6 @@ func checkOverlap(radius int, xCenter int, yCenter int, x1 int, y1 int, x2 int, } ``` -### **TypeScript** - ```ts function checkOverlap( radius: number, @@ -169,10 +159,6 @@ function checkOverlap( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1402.Reducing Dishes/README.md b/solution/1400-1499/1402.Reducing Dishes/README.md index ad70d8251b085..ec7921340068c 100644 --- a/solution/1400-1499/1402.Reducing Dishes/README.md +++ b/solution/1400-1499/1402.Reducing Dishes/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 假如我们只选择一道菜,那么我们应该选择满意度最大的那道菜 $s_0$,并且判断 $s_0$ 是否大于 0,如果 $s_0 \leq 0$,那么我们就不做菜了,否则我们做这道菜,得到的总满意度为 $s_0$。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def maxSatisfaction(self, satisfaction: List[int]) -> int: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxSatisfaction(int[] satisfaction) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func maxSatisfaction(satisfaction []int) (ans int) { sort.Slice(satisfaction, func(i, j int) bool { return satisfaction[i] > satisfaction[j] }) @@ -142,8 +128,6 @@ func maxSatisfaction(satisfaction []int) (ans int) { } ``` -### **TypeScript** - ```ts function maxSatisfaction(satisfaction: number[]): number { satisfaction.sort((a, b) => b - a); @@ -159,10 +143,6 @@ function maxSatisfaction(satisfaction: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1402.Reducing Dishes/README_EN.md b/solution/1400-1499/1402.Reducing Dishes/README_EN.md index a1cbe86b289a9..7d0c9d2ceb9cd 100644 --- a/solution/1400-1499/1402.Reducing Dishes/README_EN.md +++ b/solution/1400-1499/1402.Reducing Dishes/README_EN.md @@ -48,7 +48,7 @@ Each dish is prepared in one unit of time. ## Solutions -**Solution 1: Greedy + Sorting** +### Solution 1: Greedy + Sorting Suppose we only choose one dish, then we should choose the dish with the highest satisfaction $s_0$, and check whether $s_0$ is greater than 0. If $s_0 \leq 0$, then we don't cook any dishes, otherwise, we cook this dish, and the total satisfaction is $s_0$. @@ -62,8 +62,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def maxSatisfaction(self, satisfaction: List[int]) -> int: @@ -77,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxSatisfaction(int[] satisfaction) { @@ -96,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +110,6 @@ public: }; ``` -### **Go** - ```go func maxSatisfaction(satisfaction []int) (ans int) { sort.Slice(satisfaction, func(i, j int) bool { return satisfaction[i] > satisfaction[j] }) @@ -133,8 +125,6 @@ func maxSatisfaction(satisfaction []int) (ans int) { } ``` -### **TypeScript** - ```ts function maxSatisfaction(satisfaction: number[]): number { satisfaction.sort((a, b) => b - a); @@ -150,10 +140,6 @@ function maxSatisfaction(satisfaction: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1403.Minimum Subsequence in Non-Increasing Order/README.md b/solution/1400-1499/1403.Minimum Subsequence in Non-Increasing Order/README.md index be22393b40e37..3c622c0b14dc8 100644 --- a/solution/1400-1499/1403.Minimum Subsequence in Non-Increasing Order/README.md +++ b/solution/1400-1499/1403.Minimum Subsequence in Non-Increasing Order/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们可以先对数组 $nums$ 按照从大到小的顺序排序,然后依次从大到小加入数组中的元素,每次加入后判断当前元素之和是否大于剩余元素之和,如果大于则返回当前数组。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def minSubsequence(self, nums: List[int]) -> List[int]: @@ -74,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List minSubsequence(int[] nums) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func minSubsequence(nums []int) (ans []int) { sort.Ints(nums) @@ -138,8 +124,6 @@ func minSubsequence(nums []int) (ans []int) { } ``` -### **TypeScript** - ```ts function minSubsequence(nums: number[]): number[] { nums.sort((a, b) => b - a); @@ -154,8 +138,6 @@ function minSubsequence(nums: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn min_subsequence(mut nums: Vec) -> Vec { @@ -175,10 +157,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1403.Minimum Subsequence in Non-Increasing Order/README_EN.md b/solution/1400-1499/1403.Minimum Subsequence in Non-Increasing Order/README_EN.md index d917ae7be2c43..6a59032b4238a 100644 --- a/solution/1400-1499/1403.Minimum Subsequence in Non-Increasing Order/README_EN.md +++ b/solution/1400-1499/1403.Minimum Subsequence in Non-Increasing Order/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting We can first sort the array $nums$ in descending order, then add the elements to the array from largest to smallest. After each addition, we check whether the sum of the current elements is greater than the sum of the remaining elements. If it is, we return the current array. @@ -45,8 +45,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def minSubsequence(self, nums: List[int]) -> List[int]: @@ -60,8 +58,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List minSubsequence(int[] nums) { @@ -81,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +97,6 @@ public: }; ``` -### **Go** - ```go func minSubsequence(nums []int) (ans []int) { sort.Ints(nums) @@ -122,8 +114,6 @@ func minSubsequence(nums []int) (ans []int) { } ``` -### **TypeScript** - ```ts function minSubsequence(nums: number[]): number[] { nums.sort((a, b) => b - a); @@ -138,8 +128,6 @@ function minSubsequence(nums: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn min_subsequence(mut nums: Vec) -> Vec { @@ -159,10 +147,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README.md b/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README.md index 32617e522fd2c..845fd8e603b17 100644 --- a/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README.md +++ b/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README.md @@ -60,9 +60,7 @@ Step 1) 2 是偶数,除 2 得到 1 ## 解法 - - -**方法一:模拟操作** +### 方法一:模拟操作 我们模拟操作 $1$ 和 $2$,同时用 carry 记录进位。 @@ -70,10 +68,6 @@ Step 1) 2 是偶数,除 2 得到 1 -### **Python3** - - - ```python class Solution: def numSteps(self, s: str) -> int: @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numSteps(String s) { @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func numSteps(s string) int { ans := 0 @@ -186,10 +172,6 @@ func numSteps(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README_EN.md b/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README_EN.md index 5013bb0a8437a..548fe8ef15fa6 100644 --- a/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README_EN.md +++ b/solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README_EN.md @@ -59,7 +59,7 @@ Step 1) 2 is even, divide by 2 and obtain 1.  ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We simulate operations $1$ and $2$, while using `carry` to record the carry-over. @@ -67,8 +67,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. The sp -### **Python3** - ```python class Solution: def numSteps(self, s: str) -> int: @@ -90,8 +88,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numSteps(String s) { @@ -121,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +144,6 @@ public: }; ``` -### **Go** - ```go func numSteps(s string) int { ans := 0 @@ -179,10 +171,6 @@ func numSteps(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1405.Longest Happy String/README.md b/solution/1400-1499/1405.Longest Happy String/README.md index 71e3948dc4bc6..82cdb005e7b87 100644 --- a/solution/1400-1499/1405.Longest Happy String/README.md +++ b/solution/1400-1499/1405.Longest Happy String/README.md @@ -50,18 +50,12 @@ ## 解法 - - -**方法一:贪心 + 优先队列** +### 方法一:贪心 + 优先队列 贪心,优先选择剩余最多的字符,通过优先队列或排序,确保每次选到的字符都是剩余最多的(为了避免出现连续 3 个一样的字符,一些情况需要选择剩余第二多的字符)。 -### **Python3** - - - ```python class Solution: def longestDiverseString(self, a: int, b: int, c: int) -> str: @@ -94,10 +88,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String longestDiverseString(int a, int b, int c) { @@ -141,42 +131,45 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + string longestDiverseString(int a, int b, int c) { + using pci = pair; + auto cmp = [](pci x, pci y) { return x.second < y.second; }; + priority_queue, decltype(cmp)> pq(cmp); -```ts -function longestDiverseString(a: number, b: number, c: number): string { - let ans = []; - let store: Array<[string, number]> = [ - ['a', a], - ['b', b], - ['c', c], - ]; - while (true) { - store.sort((a, b) => b[1] - a[1]); - let hasNext = false; - for (let [i, [ch, ctn]] of store.entries()) { - if (ctn < 1) { - break; - } - const n = ans.length; - if (n >= 2 && ans[n - 1] == ch && ans[n - 2] == ch) { - continue; + if (a > 0) pq.push({'a', a}); + if (b > 0) pq.push({'b', b}); + if (c > 0) pq.push({'c', c}); + + string ans; + while (!pq.empty()) { + pci cur = pq.top(); + pq.pop(); + int n = ans.size(); + if (n >= 2 && ans[n - 1] == cur.first && ans[n - 2] == cur.first) { + if (pq.empty()) break; + pci nxt = pq.top(); + pq.pop(); + ans.push_back(nxt.first); + if (--nxt.second > 0) { + pq.push(nxt); + } + pq.push(cur); + } else { + ans.push_back(cur.first); + if (--cur.second > 0) { + pq.push(cur); + } } - hasNext = true; - ans.push(ch); - store[i][1] -= 1; - break; - } - if (!hasNext) { - break; } + + return ans; } - return ans.join(''); -} +}; ``` -### **Go** - ```go type pair struct { c byte @@ -230,51 +223,38 @@ func longestDiverseString(a int, b int, c int) string { } ``` -### **C++** - -```cpp -class Solution { -public: - string longestDiverseString(int a, int b, int c) { - using pci = pair; - auto cmp = [](pci x, pci y) { return x.second < y.second; }; - priority_queue, decltype(cmp)> pq(cmp); - - if (a > 0) pq.push({'a', a}); - if (b > 0) pq.push({'b', b}); - if (c > 0) pq.push({'c', c}); - - string ans; - while (!pq.empty()) { - pci cur = pq.top(); - pq.pop(); - int n = ans.size(); - if (n >= 2 && ans[n - 1] == cur.first && ans[n - 2] == cur.first) { - if (pq.empty()) break; - pci nxt = pq.top(); - pq.pop(); - ans.push_back(nxt.first); - if (--nxt.second > 0) { - pq.push(nxt); - } - pq.push(cur); - } else { - ans.push_back(cur.first); - if (--cur.second > 0) { - pq.push(cur); - } +```ts +function longestDiverseString(a: number, b: number, c: number): string { + let ans = []; + let store: Array<[string, number]> = [ + ['a', a], + ['b', b], + ['c', c], + ]; + while (true) { + store.sort((a, b) => b[1] - a[1]); + let hasNext = false; + for (let [i, [ch, ctn]] of store.entries()) { + if (ctn < 1) { + break; + } + const n = ans.length; + if (n >= 2 && ans[n - 1] == ch && ans[n - 2] == ch) { + continue; } + hasNext = true; + ans.push(ch); + store[i][1] -= 1; + break; + } + if (!hasNext) { + break; } - - return ans; } -}; -``` - -### **...** - -``` - + return ans.join(''); +} ``` + + diff --git a/solution/1400-1499/1405.Longest Happy String/README_EN.md b/solution/1400-1499/1405.Longest Happy String/README_EN.md index 89512bb4afb4a..a5f44acdfbd6d 100644 --- a/solution/1400-1499/1405.Longest Happy String/README_EN.md +++ b/solution/1400-1499/1405.Longest Happy String/README_EN.md @@ -45,14 +45,12 @@ ## Solutions -**Solution 1: Greedy + Priority Queue** +### Solution 1: Greedy + Priority Queue The greedy strategy is to prioritize the selection of characters with the most remaining occurrences. By using a priority queue or sorting, we ensure that the character selected each time is the one with the most remaining occurrences (to avoid having three consecutive identical characters, in some cases, we need to select the character with the second most remaining occurrences). -### **Python3** - ```python class Solution: def longestDiverseString(self, a: int, b: int, c: int) -> str: @@ -85,8 +83,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String longestDiverseString(int a, int b, int c) { @@ -130,42 +126,45 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + string longestDiverseString(int a, int b, int c) { + using pci = pair; + auto cmp = [](pci x, pci y) { return x.second < y.second; }; + priority_queue, decltype(cmp)> pq(cmp); -```ts -function longestDiverseString(a: number, b: number, c: number): string { - let ans = []; - let store: Array<[string, number]> = [ - ['a', a], - ['b', b], - ['c', c], - ]; - while (true) { - store.sort((a, b) => b[1] - a[1]); - let hasNext = false; - for (let [i, [ch, ctn]] of store.entries()) { - if (ctn < 1) { - break; - } - const n = ans.length; - if (n >= 2 && ans[n - 1] == ch && ans[n - 2] == ch) { - continue; + if (a > 0) pq.push({'a', a}); + if (b > 0) pq.push({'b', b}); + if (c > 0) pq.push({'c', c}); + + string ans; + while (!pq.empty()) { + pci cur = pq.top(); + pq.pop(); + int n = ans.size(); + if (n >= 2 && ans[n - 1] == cur.first && ans[n - 2] == cur.first) { + if (pq.empty()) break; + pci nxt = pq.top(); + pq.pop(); + ans.push_back(nxt.first); + if (--nxt.second > 0) { + pq.push(nxt); + } + pq.push(cur); + } else { + ans.push_back(cur.first); + if (--cur.second > 0) { + pq.push(cur); + } } - hasNext = true; - ans.push(ch); - store[i][1] -= 1; - break; - } - if (!hasNext) { - break; } + + return ans; } - return ans.join(''); -} +}; ``` -### **Go** - ```go type pair struct { c byte @@ -219,51 +218,38 @@ func longestDiverseString(a int, b int, c int) string { } ``` -### **C++** - -```cpp -class Solution { -public: - string longestDiverseString(int a, int b, int c) { - using pci = pair; - auto cmp = [](pci x, pci y) { return x.second < y.second; }; - priority_queue, decltype(cmp)> pq(cmp); - - if (a > 0) pq.push({'a', a}); - if (b > 0) pq.push({'b', b}); - if (c > 0) pq.push({'c', c}); - - string ans; - while (!pq.empty()) { - pci cur = pq.top(); - pq.pop(); - int n = ans.size(); - if (n >= 2 && ans[n - 1] == cur.first && ans[n - 2] == cur.first) { - if (pq.empty()) break; - pci nxt = pq.top(); - pq.pop(); - ans.push_back(nxt.first); - if (--nxt.second > 0) { - pq.push(nxt); - } - pq.push(cur); - } else { - ans.push_back(cur.first); - if (--cur.second > 0) { - pq.push(cur); - } +```ts +function longestDiverseString(a: number, b: number, c: number): string { + let ans = []; + let store: Array<[string, number]> = [ + ['a', a], + ['b', b], + ['c', c], + ]; + while (true) { + store.sort((a, b) => b[1] - a[1]); + let hasNext = false; + for (let [i, [ch, ctn]] of store.entries()) { + if (ctn < 1) { + break; + } + const n = ans.length; + if (n >= 2 && ans[n - 1] == ch && ans[n - 2] == ch) { + continue; } + hasNext = true; + ans.push(ch); + store[i][1] -= 1; + break; + } + if (!hasNext) { + break; } - - return ans; } -}; -``` - -### **...** - -``` - + return ans.join(''); +} ``` + + diff --git a/solution/1400-1499/1406.Stone Game III/README.md b/solution/1400-1499/1406.Stone Game III/README.md index e7b46693b7e5e..602a52ae1b834 100644 --- a/solution/1400-1499/1406.Stone Game III/README.md +++ b/solution/1400-1499/1406.Stone Game III/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i)$,表示当前玩家在 $[i, n)$ 范围内进行游戏时,可以获得的最大得分差值。如果 $dfs(0) \gt 0$,则表示先手玩家 Alice 可以获胜;如果 $dfs(0) \lt 0$,则表示后手玩家 Bob 可以获胜;否则,表示两人打成平局。 @@ -78,10 +76,6 @@ $$ -### **Python3** - - - ```python class Solution: def stoneGameIII(self, stoneValue: List[int]) -> str: @@ -104,10 +98,6 @@ class Solution: return 'Alice' if ans > 0 else 'Bob' ``` -### **Java** - - - ```java class Solution { private int[] stoneValue; @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +163,6 @@ public: }; ``` -### **Go** - ```go func stoneGameIII(stoneValue []int) string { n := len(stoneValue) @@ -212,8 +198,6 @@ func stoneGameIII(stoneValue []int) string { } ``` -### **TypeScript** - ```ts function stoneGameIII(stoneValue: number[]): string { const n = stoneValue.length; @@ -242,10 +226,6 @@ function stoneGameIII(stoneValue: number[]): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1406.Stone Game III/README_EN.md b/solution/1400-1499/1406.Stone Game III/README_EN.md index 4a9a4a979680f..9146e19587d7f 100644 --- a/solution/1400-1499/1406.Stone Game III/README_EN.md +++ b/solution/1400-1499/1406.Stone Game III/README_EN.md @@ -54,7 +54,7 @@ Remember that both play optimally so here Alice will choose the scenario that ma ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We design a function $dfs(i)$, which represents the maximum score difference that the current player can obtain when playing the game in the range $[i, n)$. If $dfs(0) > 0$, it means that the first player Alice can win; if $dfs(0) < 0$, it means that the second player Bob can win; otherwise, it means that the two players tie. @@ -73,8 +73,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def stoneGameIII(self, stoneValue: List[int]) -> str: @@ -97,8 +95,6 @@ class Solution: return 'Alice' if ans > 0 else 'Bob' ``` -### **Java** - ```java class Solution { private int[] stoneValue; @@ -134,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -166,8 +160,6 @@ public: }; ``` -### **Go** - ```go func stoneGameIII(stoneValue []int) string { n := len(stoneValue) @@ -203,8 +195,6 @@ func stoneGameIII(stoneValue []int) string { } ``` -### **TypeScript** - ```ts function stoneGameIII(stoneValue: number[]): string { const n = stoneValue.length; @@ -233,10 +223,6 @@ function stoneGameIII(stoneValue: number[]): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1407.Top Travellers/README.md b/solution/1400-1499/1407.Top Travellers/README.md index 64eb05d82ef5e..e2839c0e32df7 100644 --- a/solution/1400-1499/1407.Top Travellers/README.md +++ b/solution/1400-1499/1407.Top Travellers/README.md @@ -95,16 +95,12 @@ Donald 没有任何行程, 他的旅行距离为 0。 ## 解法 - - -**方法一:左连接 + 分组统计** +### 方法一:左连接 + 分组统计 我们可以使用左连接,将 `Users` 表与 `Rides` 表按照用户 id 连接,然后按照用户 id 分组,统计每个用户的旅行距离。注意,如果用户没有旅行记录,那么旅行距离为 $0$。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT name, IFNULL(SUM(distance), 0) AS travelled_distance @@ -116,3 +112,5 @@ ORDER BY 2 DESC, 1; ``` + + diff --git a/solution/1400-1499/1407.Top Travellers/README_EN.md b/solution/1400-1499/1407.Top Travellers/README_EN.md index 0302c0af89e01..33b168e784c1b 100644 --- a/solution/1400-1499/1407.Top Travellers/README_EN.md +++ b/solution/1400-1499/1407.Top Travellers/README_EN.md @@ -92,14 +92,12 @@ Donald did not have any rides, the distance traveled by him is 0. ## Solutions -**Solution 1: LEFT JOIN + GROUP BY** +### Solution 1: LEFT JOIN + GROUP BY We can use a left join to join the `Users` table with the `Rides` table on the condition of user id, and then group by user id to calculate the travel distance for each user. Note that if a user has no travel records, the travel distance is $0$. -### **SQL** - ```sql # Write your MySQL query statement below SELECT name, IFNULL(SUM(distance), 0) AS travelled_distance @@ -111,3 +109,5 @@ ORDER BY 2 DESC, 1; ``` + + diff --git a/solution/1400-1499/1408.String Matching in an Array/README.md b/solution/1400-1499/1408.String Matching in an Array/README.md index f2f29d22a4183..e245b77e483c4 100644 --- a/solution/1400-1499/1408.String Matching in an Array/README.md +++ b/solution/1400-1499/1408.String Matching in an Array/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 我们直接枚举所有的字符串 $words[i]$,判断其是否为其他字符串的子串,如果是,将其加入答案。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def stringMatching(self, words: List[str]) -> List[str]: @@ -73,10 +67,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List stringMatching(String[] words) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func stringMatching(words []string) []string { ans := []string{} @@ -133,8 +119,6 @@ func stringMatching(words []string) []string { } ``` -### **TypeScript** - ```ts function stringMatching(words: string[]): string[] { const ans: string[] = []; @@ -151,8 +135,6 @@ function stringMatching(words: string[]): string[] { } ``` -### **Rust** - ```rust impl Solution { pub fn string_matching(words: Vec) -> Vec { @@ -171,10 +153,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1408.String Matching in an Array/README_EN.md b/solution/1400-1499/1408.String Matching in an Array/README_EN.md index 7b0fd778df18a..e398befc28b1c 100644 --- a/solution/1400-1499/1408.String Matching in an Array/README_EN.md +++ b/solution/1400-1499/1408.String Matching in an Array/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Brute Force Enumeration** +### Solution 1: Brute Force Enumeration We directly enumerate all strings $words[i]$, and check whether it is a substring of other strings. If it is, we add it to the answer. @@ -54,8 +54,6 @@ The time complexity is $O(n^3)$, and the space complexity is $O(n)$. Where $n$ i -### **Python3** - ```python class Solution: def stringMatching(self, words: List[str]) -> List[str]: @@ -66,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List stringMatching(String[] words) { @@ -86,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +101,6 @@ public: }; ``` -### **Go** - ```go func stringMatching(words []string) []string { ans := []string{} @@ -124,8 +116,6 @@ func stringMatching(words []string) []string { } ``` -### **TypeScript** - ```ts function stringMatching(words: string[]): string[] { const ans: string[] = []; @@ -142,8 +132,6 @@ function stringMatching(words: string[]): string[] { } ``` -### **Rust** - ```rust impl Solution { pub fn string_matching(words: Vec) -> Vec { @@ -162,10 +150,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1409.Queries on a Permutation With Key/README.md b/solution/1400-1499/1409.Queries on a Permutation With Key/README.md index 9a7940b657c8f..6a44190e4aca4 100644 --- a/solution/1400-1499/1409.Queries on a Permutation With Key/README.md +++ b/solution/1400-1499/1409.Queries on a Permutation With Key/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 题目数据规模不大,可以直接模拟。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def processQueries(self, queries: List[int], m: int) -> List[int]: @@ -96,6 +90,79 @@ class Solution: return ans ``` +```java +class Solution { + public int[] processQueries(int[] queries, int m) { + List p = new LinkedList<>(); + for (int i = 1; i <= m; ++i) { + p.add(i); + } + int[] ans = new int[queries.length]; + int i = 0; + for (int v : queries) { + int j = p.indexOf(v); + ans[i++] = j; + p.remove(j); + p.add(0, v); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector processQueries(vector& queries, int m) { + vector p(m); + iota(p.begin(), p.end(), 1); + vector ans; + for (int v : queries) { + int j = 0; + for (int i = 0; i < m; ++i) { + if (p[i] == v) { + j = i; + break; + } + } + ans.push_back(j); + p.erase(p.begin() + j); + p.insert(p.begin(), v); + } + return ans; + } +}; +``` + +```go +func processQueries(queries []int, m int) []int { + p := make([]int, m) + for i := range p { + p[i] = i + 1 + } + ans := []int{} + for _, v := range queries { + j := 0 + for i := range p { + if p[i] == v { + j = i + break + } + } + ans = append(ans, j) + p = append(p[:j], p[j+1:]...) + p = append([]int{v}, p...) + } + return ans +} +``` + + + +### 方法二 + + + ```python class BinaryIndexedTree: def __init__(self, n): @@ -138,30 +205,6 @@ class Solution: return ans ``` -### **Java** - - - -```java -class Solution { - public int[] processQueries(int[] queries, int m) { - List p = new LinkedList<>(); - for (int i = 1; i <= m; ++i) { - p.add(i); - } - int[] ans = new int[queries.length]; - int i = 0; - for (int v : queries) { - int j = p.indexOf(v); - ans[i++] = j; - p.remove(j); - p.add(0, v); - } - return ans; - } -} -``` - ```java class BinaryIndexedTree { private int n; @@ -217,32 +260,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector processQueries(vector& queries, int m) { - vector p(m); - iota(p.begin(), p.end(), 1); - vector ans; - for (int v : queries) { - int j = 0; - for (int i = 0; i < m; ++i) { - if (p[i] == v) { - j = i; - break; - } - } - ans.push_back(j); - p.erase(p.begin() + j); - p.insert(p.begin(), v); - } - return ans; - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -298,31 +315,6 @@ public: }; ``` -### **Go** - -```go -func processQueries(queries []int, m int) []int { - p := make([]int, m) - for i := range p { - p[i] = i + 1 - } - ans := []int{} - for _, v := range queries { - j := 0 - for i := range p { - if p[i] == v { - j = i - break - } - } - ans = append(ans, j) - p = append(p[:j], p[j+1:]...) - p = append([]int{v}, p...) - } - return ans -} -``` - ```go type BinaryIndexedTree struct { n int @@ -374,10 +366,6 @@ func processQueries(queries []int, m int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1409.Queries on a Permutation With Key/README_EN.md b/solution/1400-1499/1409.Queries on a Permutation With Key/README_EN.md index 798b7f1392200..41d8eb2ed4196 100644 --- a/solution/1400-1499/1409.Queries on a Permutation With Key/README_EN.md +++ b/solution/1400-1499/1409.Queries on a Permutation With Key/README_EN.md @@ -52,9 +52,9 @@ Therefore, the array containing the result is [2,1,2,1]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,6 +69,79 @@ class Solution: return ans ``` +```java +class Solution { + public int[] processQueries(int[] queries, int m) { + List p = new LinkedList<>(); + for (int i = 1; i <= m; ++i) { + p.add(i); + } + int[] ans = new int[queries.length]; + int i = 0; + for (int v : queries) { + int j = p.indexOf(v); + ans[i++] = j; + p.remove(j); + p.add(0, v); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector processQueries(vector& queries, int m) { + vector p(m); + iota(p.begin(), p.end(), 1); + vector ans; + for (int v : queries) { + int j = 0; + for (int i = 0; i < m; ++i) { + if (p[i] == v) { + j = i; + break; + } + } + ans.push_back(j); + p.erase(p.begin() + j); + p.insert(p.begin(), v); + } + return ans; + } +}; +``` + +```go +func processQueries(queries []int, m int) []int { + p := make([]int, m) + for i := range p { + p[i] = i + 1 + } + ans := []int{} + for _, v := range queries { + j := 0 + for i := range p { + if p[i] == v { + j = i + break + } + } + ans = append(ans, j) + p = append(p[:j], p[j+1:]...) + p = append([]int{v}, p...) + } + return ans +} +``` + + + +### Solution 2 + + + ```python class BinaryIndexedTree: def __init__(self, n): @@ -111,28 +184,6 @@ class Solution: return ans ``` -### **Java** - -```java -class Solution { - public int[] processQueries(int[] queries, int m) { - List p = new LinkedList<>(); - for (int i = 1; i <= m; ++i) { - p.add(i); - } - int[] ans = new int[queries.length]; - int i = 0; - for (int v : queries) { - int j = p.indexOf(v); - ans[i++] = j; - p.remove(j); - p.add(0, v); - } - return ans; - } -} -``` - ```java class BinaryIndexedTree { private int n; @@ -188,32 +239,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector processQueries(vector& queries, int m) { - vector p(m); - iota(p.begin(), p.end(), 1); - vector ans; - for (int v : queries) { - int j = 0; - for (int i = 0; i < m; ++i) { - if (p[i] == v) { - j = i; - break; - } - } - ans.push_back(j); - p.erase(p.begin() + j); - p.insert(p.begin(), v); - } - return ans; - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -269,31 +294,6 @@ public: }; ``` -### **Go** - -```go -func processQueries(queries []int, m int) []int { - p := make([]int, m) - for i := range p { - p[i] = i + 1 - } - ans := []int{} - for _, v := range queries { - j := 0 - for i := range p { - if p[i] == v { - j = i - break - } - } - ans = append(ans, j) - p = append(p[:j], p[j+1:]...) - p = append([]int{v}, p...) - } - return ans -} -``` - ```go type BinaryIndexedTree struct { n int @@ -345,10 +345,6 @@ func processQueries(queries []int, m int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1410.HTML Entity Parser/README.md b/solution/1400-1499/1410.HTML Entity Parser/README.md index 4ac7905a81fc0..31d70952a1b3a 100644 --- a/solution/1400-1499/1410.HTML Entity Parser/README.md +++ b/solution/1400-1499/1410.HTML Entity Parser/README.md @@ -70,9 +70,7 @@ ## 解法 - - -**方法一:哈希表 + 模拟** +### 方法一:哈希表 + 模拟 我们可以使用哈希表来存储每个字符实体对应的字符,然后遍历字符串,当遇到字符实体时,我们就将其替换为对应的字符。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def entityParser(self, text: str) -> str: @@ -110,10 +104,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String entityParser(String text) { @@ -150,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -187,8 +175,6 @@ public: }; ``` -### **Go** - ```go func entityParser(text string) string { d := map[string]string{ @@ -226,8 +212,6 @@ func entityParser(text string) string { } ``` -### **TypeScript** - ```ts function entityParser(text: string): string { const d: Record = { @@ -267,6 +251,12 @@ function entityParser(text: string): string { } ``` + + +### 方法二 + + + ```ts function entityParser(text: string): string { const d: { [key: string]: string } = { @@ -283,10 +273,6 @@ function entityParser(text: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1410.HTML Entity Parser/README_EN.md b/solution/1400-1499/1410.HTML Entity Parser/README_EN.md index 019d7d2612196..863c11b1ae742 100644 --- a/solution/1400-1499/1410.HTML Entity Parser/README_EN.md +++ b/solution/1400-1499/1410.HTML Entity Parser/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Hash Table + Simulation** +### Solution 1: Hash Table + Simulation We can use a hash table to store the corresponding character for each character entity. Then, we traverse the string, and when we encounter a character entity, we replace it with the corresponding character. @@ -55,8 +55,6 @@ The time complexity is $O(n \times l)$, and the space complexity is $O(l)$. Here -### **Python3** - ```python class Solution: def entityParser(self, text: str) -> str: @@ -83,8 +81,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String entityParser(String text) { @@ -121,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +152,6 @@ public: }; ``` -### **Go** - ```go func entityParser(text string) string { d := map[string]string{ @@ -197,8 +189,6 @@ func entityParser(text string) string { } ``` -### **TypeScript** - ```ts function entityParser(text: string): string { const d: Record = { @@ -238,6 +228,12 @@ function entityParser(text: string): string { } ``` + + +### Solution 2 + + + ```ts function entityParser(text: string): string { const d: { [key: string]: string } = { @@ -254,10 +250,6 @@ function entityParser(text: string): string { } ``` -### **...** - -``` - -``` - + + diff --git "a/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/README.md" "b/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/README.md" index 0daca7efb30c1..b031dfd4c94db 100644 --- "a/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/README.md" +++ "b/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/README.md" @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:递推** +### 方法一:递推 把每一行所有可能的状态进行分类。根据对称性原理,当一行只有 $3$ 个元素时,所有合法状态分类为 $010$ 型以及 $012$ 型。 @@ -71,7 +69,89 @@ 时间复杂度 $O(n)$,其中 $n$ 是网格的行数。空间复杂度 $O(1)$。 -**方法二:状态压缩 + 动态规划** + + +```python +class Solution: + def numOfWays(self, n: int) -> int: + mod = 10**9 + 7 + f0 = f1 = 6 + for _ in range(n - 1): + g0 = (3 * f0 + 2 * f1) % mod + g1 = (2 * f0 + 2 * f1) % mod + f0, f1 = g0, g1 + return (f0 + f1) % mod +``` + +```java +class Solution { + public int numOfWays(int n) { + int mod = (int) 1e9 + 7; + long f0 = 6, f1 = 6; + for (int i = 0; i < n - 1; ++i) { + long g0 = (3 * f0 + 2 * f1) % mod; + long g1 = (2 * f0 + 2 * f1) % mod; + f0 = g0; + f1 = g1; + } + return (int) (f0 + f1) % mod; + } +} +``` + +```cpp +using ll = long long; + +class Solution { +public: + int numOfWays(int n) { + int mod = 1e9 + 7; + ll f0 = 6, f1 = 6; + while (--n) { + ll g0 = (f0 * 3 + f1 * 2) % mod; + ll g1 = (f0 * 2 + f1 * 2) % mod; + f0 = g0; + f1 = g1; + } + return (int) (f0 + f1) % mod; + } +}; +``` + +```go +func numOfWays(n int) int { + mod := int(1e9) + 7 + f0, f1 := 6, 6 + for n > 1 { + n-- + g0 := (f0*3 + f1*2) % mod + g1 := (f0*2 + f1*2) % mod + f0, f1 = g0, g1 + } + return (f0 + f1) % mod +} +``` + +```ts +function numOfWays(n: number): number { + const mod: number = 10 ** 9 + 7; + let f0: number = 6; + let f1: number = 6; + + for (let i = 1; i < n; i++) { + const g0: number = (3 * f0 + 2 * f1) % mod; + const g1: number = (2 * f0 + 2 * f1) % mod; + f0 = g0; + f1 = g1; + } + + return (f0 + f1) % mod; +} +``` + + + +### 方法二:状态压缩 + 动态规划 我们注意到,网格只有 $3$ 列,那么一行中最多有 $3^3=27$ 种不同的涂色方案。 @@ -91,22 +171,6 @@ $$ -### **Python3** - - - -```python -class Solution: - def numOfWays(self, n: int) -> int: - mod = 10**9 + 7 - f0 = f1 = 6 - for _ in range(n - 1): - g0 = (3 * f0 + 2 * f1) % mod - g1 = (2 * f0 + 2 * f1) % mod - f0, f1 = g0, g1 - return (f0 + f1) % mod -``` - ```python class Solution: def numOfWays(self, n: int) -> int: @@ -145,26 +209,6 @@ class Solution: return sum(f) % mod ``` -### **Java** - - - -```java -class Solution { - public int numOfWays(int n) { - int mod = (int) 1e9 + 7; - long f0 = 6, f1 = 6; - for (int i = 0; i < n - 1; ++i) { - long g0 = (3 * f0 + 2 * f1) % mod; - long g1 = (2 * f0 + 2 * f1) % mod; - f0 = g0; - f1 = g1; - } - return (int) (f0 + f1) % mod; - } -} -``` - ```java class Solution { public int numOfWays(int n) { @@ -227,27 +271,6 @@ class Solution { } ``` -### **C++** - -```cpp -using ll = long long; - -class Solution { -public: - int numOfWays(int n) { - int mod = 1e9 + 7; - ll f0 = 6, f1 = 6; - while (--n) { - ll g0 = (f0 * 3 + f1 * 2) % mod; - ll g1 = (f0 * 2 + f1 * 2) % mod; - f0 = g0; - f1 = g1; - } - return (int) (f0 + f1) % mod; - } -}; -``` - ```cpp class Solution { public: @@ -311,22 +334,6 @@ public: }; ``` -### **Go** - -```go -func numOfWays(n int) int { - mod := int(1e9) + 7 - f0, f1 := 6, 6 - for n > 1 { - n-- - g0 := (f0*3 + f1*2) % mod - g1 := (f0*2 + f1*2) % mod - f0, f1 = g0, g1 - } - return (f0 + f1) % mod -} -``` - ```go func numOfWays(n int) (ans int) { f1 := func(x int) bool { @@ -384,25 +391,6 @@ func numOfWays(n int) (ans int) { } ``` -### **TypeScript** - -```ts -function numOfWays(n: number): number { - const mod: number = 10 ** 9 + 7; - let f0: number = 6; - let f1: number = 6; - - for (let i = 1; i < n; i++) { - const g0: number = (3 * f0 + 2 * f1) % mod; - const g1: number = (2 * f0 + 2 * f1) % mod; - f0 = g0; - f1 = g1; - } - - return (f0 + f1) % mod; -} -``` - ```ts function numOfWays(n: number): number { const f1 = (x: number): boolean => { @@ -461,10 +449,6 @@ function numOfWays(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git "a/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/README_EN.md" "b/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/README_EN.md" index 79b1782d4422c..ded680998ceb0 100644 --- "a/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/README_EN.md" +++ "b/solution/1400-1499/1411.Number of Ways to Paint N \303\227 3 Grid/README_EN.md" @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion We classify all possible states for each row. According to the principle of symmetry, when a row only has $3$ elements, all legal states are classified as: $010$ type, $012$ type. @@ -45,7 +45,89 @@ In summary, we can get: $newf0 = 3 \times f0 + 2 \times f1$, $newf1 = 2 \times f The time complexity is $O(n)$, where $n$ is the number of rows in the grid. The space complexity is $O(1)$. -**Solution 2: State Compression + Dynamic Programming** + + +```python +class Solution: + def numOfWays(self, n: int) -> int: + mod = 10**9 + 7 + f0 = f1 = 6 + for _ in range(n - 1): + g0 = (3 * f0 + 2 * f1) % mod + g1 = (2 * f0 + 2 * f1) % mod + f0, f1 = g0, g1 + return (f0 + f1) % mod +``` + +```java +class Solution { + public int numOfWays(int n) { + int mod = (int) 1e9 + 7; + long f0 = 6, f1 = 6; + for (int i = 0; i < n - 1; ++i) { + long g0 = (3 * f0 + 2 * f1) % mod; + long g1 = (2 * f0 + 2 * f1) % mod; + f0 = g0; + f1 = g1; + } + return (int) (f0 + f1) % mod; + } +} +``` + +```cpp +using ll = long long; + +class Solution { +public: + int numOfWays(int n) { + int mod = 1e9 + 7; + ll f0 = 6, f1 = 6; + while (--n) { + ll g0 = (f0 * 3 + f1 * 2) % mod; + ll g1 = (f0 * 2 + f1 * 2) % mod; + f0 = g0; + f1 = g1; + } + return (int) (f0 + f1) % mod; + } +}; +``` + +```go +func numOfWays(n int) int { + mod := int(1e9) + 7 + f0, f1 := 6, 6 + for n > 1 { + n-- + g0 := (f0*3 + f1*2) % mod + g1 := (f0*2 + f1*2) % mod + f0, f1 = g0, g1 + } + return (f0 + f1) % mod +} +``` + +```ts +function numOfWays(n: number): number { + const mod: number = 10 ** 9 + 7; + let f0: number = 6; + let f1: number = 6; + + for (let i = 1; i < n; i++) { + const g0: number = (3 * f0 + 2 * f1) % mod; + const g1: number = (2 * f0 + 2 * f1) % mod; + f0 = g0; + f1 = g1; + } + + return (f0 + f1) % mod; +} +``` + + + +### Solution 2: State Compression + Dynamic Programming We notice that the grid only has $3$ columns, so there are at most $3^3=27$ different coloring schemes in a row. @@ -65,20 +147,6 @@ The time complexity is $O((m + n) \times 3^{2m})$, and the space complexity is $ -### **Python3** - -```python -class Solution: - def numOfWays(self, n: int) -> int: - mod = 10**9 + 7 - f0 = f1 = 6 - for _ in range(n - 1): - g0 = (3 * f0 + 2 * f1) % mod - g1 = (2 * f0 + 2 * f1) % mod - f0, f1 = g0, g1 - return (f0 + f1) % mod -``` - ```python class Solution: def numOfWays(self, n: int) -> int: @@ -117,24 +185,6 @@ class Solution: return sum(f) % mod ``` -### **Java** - -```java -class Solution { - public int numOfWays(int n) { - int mod = (int) 1e9 + 7; - long f0 = 6, f1 = 6; - for (int i = 0; i < n - 1; ++i) { - long g0 = (3 * f0 + 2 * f1) % mod; - long g1 = (2 * f0 + 2 * f1) % mod; - f0 = g0; - f1 = g1; - } - return (int) (f0 + f1) % mod; - } -} -``` - ```java class Solution { public int numOfWays(int n) { @@ -197,27 +247,6 @@ class Solution { } ``` -### **C++** - -```cpp -using ll = long long; - -class Solution { -public: - int numOfWays(int n) { - int mod = 1e9 + 7; - ll f0 = 6, f1 = 6; - while (--n) { - ll g0 = (f0 * 3 + f1 * 2) % mod; - ll g1 = (f0 * 2 + f1 * 2) % mod; - f0 = g0; - f1 = g1; - } - return (int) (f0 + f1) % mod; - } -}; -``` - ```cpp class Solution { public: @@ -281,22 +310,6 @@ public: }; ``` -### **Go** - -```go -func numOfWays(n int) int { - mod := int(1e9) + 7 - f0, f1 := 6, 6 - for n > 1 { - n-- - g0 := (f0*3 + f1*2) % mod - g1 := (f0*2 + f1*2) % mod - f0, f1 = g0, g1 - } - return (f0 + f1) % mod -} -``` - ```go func numOfWays(n int) (ans int) { f1 := func(x int) bool { @@ -354,25 +367,6 @@ func numOfWays(n int) (ans int) { } ``` -### **TypeScript** - -```ts -function numOfWays(n: number): number { - const mod: number = 10 ** 9 + 7; - let f0: number = 6; - let f1: number = 6; - - for (let i = 1; i < n; i++) { - const g0: number = (3 * f0 + 2 * f1) % mod; - const g1: number = (2 * f0 + 2 * f1) % mod; - f0 = g0; - f1 = g1; - } - - return (f0 + f1) % mod; -} -``` - ```ts function numOfWays(n: number): number { const f1 = (x: number): boolean => { @@ -431,10 +425,6 @@ function numOfWays(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1412.Find the Quiet Students in All Exams/README.md b/solution/1400-1499/1412.Find the Quiet Students in All Exams/README.md index 0f50e42d94a93..5b134856d22ea 100644 --- a/solution/1400-1499/1412.Find the Quiet Students in All Exams/README.md +++ b/solution/1400-1499/1412.Find the Quiet Students in All Exams/README.md @@ -91,9 +91,7 @@ Exam 表: ## 解法 - - -**方法一:使用 RANK() 窗口函数 + 分组聚合** +### 方法一:使用 RANK() 窗口函数 + 分组聚合 我们可以使用 `RANK()` 窗口函数来计算每个学生在每场考试中的正序排名 $rk1$ 和倒序排序 $rk2$,得到表 $T$。 @@ -101,8 +99,6 @@ Exam 表: -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -129,3 +125,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1400-1499/1412.Find the Quiet Students in All Exams/README_EN.md b/solution/1400-1499/1412.Find the Quiet Students in All Exams/README_EN.md index a9c2ebc5372a4..3a2dcd938a3ca 100644 --- a/solution/1400-1499/1412.Find the Quiet Students in All Exams/README_EN.md +++ b/solution/1400-1499/1412.Find the Quiet Students in All Exams/README_EN.md @@ -89,7 +89,7 @@ So, we only return the information of Student 2. ## Solutions -**Solution 1: Using RANK() Window Function + Group By** +### Solution 1: Using RANK() Window Function + Group By We can use the `RANK()` window function to calculate the ascending rank $rk1$ and descending rank $rk2$ of each student in each exam, and obtain the table $T$. @@ -97,8 +97,6 @@ Next, we can perform an inner join between the table $T$ and the table $Student$ -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -125,3 +123,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/README.md b/solution/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/README.md index 1771aac37c859..bf194da48a3bc 100644 --- a/solution/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/README.md +++ b/solution/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/README.md @@ -55,14 +55,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minStartValue(self, nums: List[int]) -> int: @@ -73,17 +69,6 @@ class Solution: return max(1, 1 - t) ``` -```python -class Solution: - def minStartValue(self, nums: List[int]) -> int: - s = list(accumulate(nums)) - return 1 if min(s) >= 0 else abs(min(s)) + 1 -``` - -### **Java** - - - ```java class Solution { public int minStartValue(int[] nums) { @@ -98,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +97,6 @@ public: }; ``` -### **Go** - ```go func minStartValue(nums []int) int { s, t := 0, 10000 @@ -132,8 +113,6 @@ func minStartValue(nums []int) int { } ``` -### **TypeScript** - ```ts function minStartValue(nums: number[]): number { let sum = 0; @@ -146,8 +125,6 @@ function minStartValue(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_start_value(nums: Vec) -> i32 { @@ -162,10 +139,19 @@ impl Solution { } ``` -### **...** + + +### 方法二 -``` + +```python +class Solution: + def minStartValue(self, nums: List[int]) -> int: + s = list(accumulate(nums)) + return 1 if min(s) >= 0 else abs(min(s)) + 1 ``` + + diff --git a/solution/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/README_EN.md b/solution/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/README_EN.md index 35edd72232dbf..095ddc0bd2a11 100644 --- a/solution/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/README_EN.md +++ b/solution/1400-1499/1413.Minimum Value to Get Positive Step by Step Sum/README_EN.md @@ -51,9 +51,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,15 +65,6 @@ class Solution: return max(1, 1 - t) ``` -```python -class Solution: - def minStartValue(self, nums: List[int]) -> int: - s = list(accumulate(nums)) - return 1 if min(s) >= 0 else abs(min(s)) + 1 -``` - -### **Java** - ```java class Solution { public int minStartValue(int[] nums) { @@ -88,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +93,6 @@ public: }; ``` -### **Go** - ```go func minStartValue(nums []int) int { s, t := 0, 10000 @@ -122,8 +109,6 @@ func minStartValue(nums []int) int { } ``` -### **TypeScript** - ```ts function minStartValue(nums: number[]): number { let sum = 0; @@ -136,8 +121,6 @@ function minStartValue(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_start_value(nums: Vec) -> i32 { @@ -152,10 +135,19 @@ impl Solution { } ``` -### **...** + + +### Solution 2 -``` + +```python +class Solution: + def minStartValue(self, nums: List[int]) -> int: + s = list(accumulate(nums)) + return 1 if min(s) >= 0 else abs(min(s)) + 1 ``` + + diff --git a/solution/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/README.md b/solution/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/README.md index e98479403e566..ed1bb33e0dd92 100644 --- a/solution/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/README.md +++ b/solution/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/README.md @@ -51,29 +51,10 @@ ## 解法 - - -由于斐波那契数特点,数字重用在此题中是一个烟雾弹。举例推导:`k = 288`,数列(局部)`1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377`,可以由两个 144,或 `233 + 55` 组成;`k = 10`,可以由两个 5 或 `8 + 2` 组成。 - -由此可以使用贪心策略,逆向遍历斐波那契数列,进行暴力查找: - -```txt -FIND-MIN-FIBONACCI-NUMBERS(k) - r = 0 - for n in f - if k >= n - k -= n - r++ - if k === 0 - return res -``` +### 方法一 -### **Python3** - - - ```python class Solution: def findMinFibonacciNumbers(self, k: int) -> int: @@ -88,10 +69,6 @@ class Solution: return dfs(k) ``` -### **Java** - - - ```java class Solution { @@ -109,7 +86,33 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + int findMinFibonacciNumbers(int k) { + if (k < 2) return k; + int a = 1, b = 1; + while (b <= k) { + b = a + b; + a = b - a; + } + return 1 + findMinFibonacciNumbers(k - a); + } +}; +``` + +```go +func findMinFibonacciNumbers(k int) int { + if k < 2 { + return k + } + a, b := 1, 1 + for b <= k { + a, b = b, a+b + } + return 1 + findMinFibonacciNumbers(k-a) +} +``` ```ts const arr = [ @@ -134,8 +137,6 @@ function findMinFibonacciNumbers(k: number): number { } ``` -### **Rust** - ```rust const FIB: [i32; 45] = [ 1836311903, 1134903170, 701408733, 433494437, 267914296, 165580141, 102334155, 63245986, @@ -161,42 +162,6 @@ impl Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int findMinFibonacciNumbers(int k) { - if (k < 2) return k; - int a = 1, b = 1; - while (b <= k) { - b = a + b; - a = b - a; - } - return 1 + findMinFibonacciNumbers(k - a); - } -}; -``` - -### **Go** - -```go -func findMinFibonacciNumbers(k int) int { - if k < 2 { - return k - } - a, b := 1, 1 - for b <= k { - a, b = b, a+b - } - return 1 + findMinFibonacciNumbers(k-a) -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/README_EN.md b/solution/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/README_EN.md index 13ad463d1cdca..6d1f5996cc390 100644 --- a/solution/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/README_EN.md +++ b/solution/1400-1499/1414.Find the Minimum Number of Fibonacci Numbers Whose Sum Is K/README_EN.md @@ -48,9 +48,9 @@ For k = 7 we can use 2 + 5 = 7. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return dfs(k) ``` -### **Java** - ```java class Solution { @@ -85,7 +83,33 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + int findMinFibonacciNumbers(int k) { + if (k < 2) return k; + int a = 1, b = 1; + while (b <= k) { + b = a + b; + a = b - a; + } + return 1 + findMinFibonacciNumbers(k - a); + } +}; +``` + +```go +func findMinFibonacciNumbers(k int) int { + if k < 2 { + return k + } + a, b := 1, 1 + for b <= k { + a, b = b, a+b + } + return 1 + findMinFibonacciNumbers(k-a) +} +``` ```ts const arr = [ @@ -110,8 +134,6 @@ function findMinFibonacciNumbers(k: number): number { } ``` -### **Rust** - ```rust const FIB: [i32; 45] = [ 1836311903, 1134903170, 701408733, 433494437, 267914296, 165580141, 102334155, 63245986, @@ -137,42 +159,6 @@ impl Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int findMinFibonacciNumbers(int k) { - if (k < 2) return k; - int a = 1, b = 1; - while (b <= k) { - b = a + b; - a = b - a; - } - return 1 + findMinFibonacciNumbers(k - a); - } -}; -``` - -### **Go** - -```go -func findMinFibonacciNumbers(k int) int { - if k < 2 { - return k - } - a, b := 1, 1 - for b <= k { - a, b = b, a+b - } - return 1 + findMinFibonacciNumbers(k-a) -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1415.The k-th Lexicographical String of All Happy Strings of Length n/README.md b/solution/1400-1499/1415.The k-th Lexicographical String of All Happy Strings of Length n/README.md index 3dc43e5c93503..0f0dc05663ef7 100644 --- a/solution/1400-1499/1415.The k-th Lexicographical String of All Happy Strings of Length n/README.md +++ b/solution/1400-1499/1415.The k-th Lexicographical String of All Happy Strings of Length n/README.md @@ -67,16 +67,10 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS -### **Python3** - - - ```python class Solution: def getHappyString(self, n: int, k: int) -> str: @@ -94,10 +88,6 @@ class Solution: return '' if len(ans) < k else ans[k - 1] ``` -### **Java** - - - ```java class Solution { private List ans = new ArrayList<>(); @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,10 +136,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1415.The k-th Lexicographical String of All Happy Strings of Length n/README_EN.md b/solution/1400-1499/1415.The k-th Lexicographical String of All Happy Strings of Length n/README_EN.md index 1191da0a7bcd6..aa2a3c23cfdae 100644 --- a/solution/1400-1499/1415.The k-th Lexicographical String of All Happy Strings of Length n/README_EN.md +++ b/solution/1400-1499/1415.The k-th Lexicographical String of All Happy Strings of Length n/README_EN.md @@ -52,9 +52,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return '' if len(ans) < k else ans[k - 1] ``` -### **Java** - ```java class Solution { private List ans = new ArrayList<>(); @@ -99,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,10 +121,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1416.Restore The Array/README.md b/solution/1400-1499/1416.Restore The Array/README.md index 0127d6830d7a6..67e8d7dc85e17 100644 --- a/solution/1400-1499/1416.Restore The Array/README.md +++ b/solution/1400-1499/1416.Restore The Array/README.md @@ -62,30 +62,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1400-1499/1416.Restore The Array/README_EN.md b/solution/1400-1499/1416.Restore The Array/README_EN.md index f11340ddd518e..939fc565782b9 100644 --- a/solution/1400-1499/1416.Restore The Array/README_EN.md +++ b/solution/1400-1499/1416.Restore The Array/README_EN.md @@ -44,24 +44,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1400-1499/1417.Reformat The String/README.md b/solution/1400-1499/1417.Reformat The String/README.md index 6cfe4ce934ce0..d294fe1a55f81 100644 --- a/solution/1400-1499/1417.Reformat The String/README.md +++ b/solution/1400-1499/1417.Reformat The String/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 将字符串 $s$ 中的所有字符分成“数字”、“字母”两类,分别放入 $a$, $b$ 两个数组中。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def reformat(self, s: str) -> str: @@ -93,10 +87,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String reformat(String s) { @@ -134,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -166,8 +154,6 @@ public: }; ``` -### **Go** - ```go func reformat(s string) string { a := []byte{} @@ -197,10 +183,6 @@ func reformat(s string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1417.Reformat The String/README_EN.md b/solution/1400-1499/1417.Reformat The String/README_EN.md index f03181a77d353..21572b2a2c389 100644 --- a/solution/1400-1499/1417.Reformat The String/README_EN.md +++ b/solution/1400-1499/1417.Reformat The String/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String reformat(String s) { @@ -105,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +133,6 @@ public: }; ``` -### **Go** - ```go func reformat(s string) string { a := []byte{} @@ -168,10 +162,6 @@ func reformat(s string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README.md b/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README.md index 18245bb0b3a26..843ebcbded79d 100644 --- a/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README.md +++ b/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README.md @@ -58,14 +58,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def displayTable(self, orders: List[List[str]]) -> List[List[str]]: @@ -87,10 +83,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public List> displayTable(List> orders) { @@ -127,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +157,6 @@ public: }; ``` -### **Go** - ```go func displayTable(orders [][]string) [][]string { tables := make(map[int]bool) @@ -211,10 +199,6 @@ func displayTable(orders [][]string) [][]string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README_EN.md b/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README_EN.md index d7c625b0a0159..baa6f3f496481 100644 --- a/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README_EN.md +++ b/solution/1400-1499/1418.Display Table of Food Orders in a Restaurant/README_EN.md @@ -55,9 +55,9 @@ For the table 12: James, Ratesh and Amadeus order "Fried Chicken". ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public List> displayTable(List> orders) { @@ -118,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +154,6 @@ public: }; ``` -### **Go** - ```go func displayTable(orders [][]string) [][]string { tables := make(map[int]bool) @@ -202,10 +196,6 @@ func displayTable(orders [][]string) [][]string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1419.Minimum Number of Frogs Croaking/README.md b/solution/1400-1499/1419.Minimum Number of Frogs Croaking/README.md index 46724695f48cb..4d3cbfc5c5ff1 100644 --- a/solution/1400-1499/1419.Minimum Number of Frogs Croaking/README.md +++ b/solution/1400-1499/1419.Minimum Number of Frogs Croaking/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:计数 + 模拟** +### 方法一:计数 + 模拟 我们注意到,如果字符串 `croakOfFrogs` 是由若干有效的 `"croak"` 字符混合而成,那么它的长度一定是 $5$ 的倍数。因此,如果字符串的长度不是 $5$ 的倍数,可以直接返回 $-1$。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def minNumberOfFrogs(self, croakOfFrogs: str) -> int: @@ -96,10 +90,6 @@ class Solution: return -1 if x else ans ``` -### **Java** - - - ```java class Solution { public int minNumberOfFrogs(String croakOfFrogs) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go func minNumberOfFrogs(croakOfFrogs string) int { n := len(croakOfFrogs) @@ -206,8 +192,6 @@ func minNumberOfFrogs(croakOfFrogs string) int { } ``` -### **TypeScript** - ```ts function minNumberOfFrogs(croakOfFrogs: string): number { const n = croakOfFrogs.length; @@ -236,10 +220,6 @@ function minNumberOfFrogs(croakOfFrogs: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1419.Minimum Number of Frogs Croaking/README_EN.md b/solution/1400-1499/1419.Minimum Number of Frogs Croaking/README_EN.md index 4e43f7d17843b..e47c22f4fc9d5 100644 --- a/solution/1400-1499/1419.Minimum Number of Frogs Croaking/README_EN.md +++ b/solution/1400-1499/1419.Minimum Number of Frogs Croaking/README_EN.md @@ -47,9 +47,9 @@ The second frog could yell later "crcoakroak +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return -1 if x else ans ``` -### **Java** - ```java class Solution { public int minNumberOfFrogs(String croakOfFrogs) { @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +140,6 @@ public: }; ``` -### **Go** - ```go func minNumberOfFrogs(croakOfFrogs string) int { n := len(croakOfFrogs) @@ -181,8 +175,6 @@ func minNumberOfFrogs(croakOfFrogs string) int { } ``` -### **TypeScript** - ```ts function minNumberOfFrogs(croakOfFrogs: string): number { const n = croakOfFrogs.length; @@ -211,10 +203,6 @@ function minNumberOfFrogs(croakOfFrogs: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1420.Build Array Where You Can Find The Maximum Exactly K Comparisons/README.md b/solution/1400-1499/1420.Build Array Where You Can Find The Maximum Exactly K Comparisons/README.md index 0fe6e7fa065d6..034a07791eb8a 100644 --- a/solution/1400-1499/1420.Build Array Where You Can Find The Maximum Exactly K Comparisons/README.md +++ b/solution/1400-1499/1420.Build Array Where You Can Find The Maximum Exactly K Comparisons/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 假设 $dp[i][c][j]$ 表示长度为 $i$,搜索代价为 $c$,且最大值为 $j$ 的方案数。考虑第 $i$ 个数: @@ -92,10 +90,6 @@ $$ -### **Python3** - - - ```python class Solution: def numOfArrays(self, n: int, m: int, k: int) -> int: @@ -119,10 +113,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -154,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +170,6 @@ public: }; ``` -### **Go** - ```go func numOfArrays(n int, m int, k int) int { if k == 0 { @@ -218,10 +204,6 @@ func numOfArrays(n int, m int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1420.Build Array Where You Can Find The Maximum Exactly K Comparisons/README_EN.md b/solution/1400-1499/1420.Build Array Where You Can Find The Maximum Exactly K Comparisons/README_EN.md index 1c31b9ba20172..ca7e096fc1e19 100644 --- a/solution/1400-1499/1420.Build Array Where You Can Find The Maximum Exactly K Comparisons/README_EN.md +++ b/solution/1400-1499/1420.Build Array Where You Can Find The Maximum Exactly K Comparisons/README_EN.md @@ -52,12 +52,10 @@ ## Solutions -Dynamic Programming. +### Solution 1 -### **Python3** - ```python class Solution: def numOfArrays(self, n: int, m: int, k: int) -> int: @@ -81,8 +79,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -114,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go func numOfArrays(n int, m int, k int) int { if k == 0 { @@ -178,10 +170,6 @@ func numOfArrays(n int, m int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1421.NPV Queries/README.md b/solution/1400-1499/1421.NPV Queries/README.md index d982ae2444bbc..d8742ed9b94ab 100644 --- a/solution/1400-1499/1421.NPV Queries/README.md +++ b/solution/1400-1499/1421.NPV Queries/README.md @@ -94,12 +94,10 @@ Queries 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT q.*, IFNULL(npv, 0) AS npv @@ -109,3 +107,5 @@ FROM ``` + + diff --git a/solution/1400-1499/1421.NPV Queries/README_EN.md b/solution/1400-1499/1421.NPV Queries/README_EN.md index f451a4956686f..8787bbcc43b1a 100644 --- a/solution/1400-1499/1421.NPV Queries/README_EN.md +++ b/solution/1400-1499/1421.NPV Queries/README_EN.md @@ -90,9 +90,9 @@ The npv values of all other queries can be found in the NPV table. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -103,3 +103,5 @@ FROM ``` + + diff --git a/solution/1400-1499/1422.Maximum Score After Splitting a String/README.md b/solution/1400-1499/1422.Maximum Score After Splitting a String/README.md index 3f6863aaa4b83..8af5bd0ec92ec 100644 --- a/solution/1400-1499/1422.Maximum Score After Splitting a String/README.md +++ b/solution/1400-1499/1422.Maximum Score After Splitting a String/README.md @@ -49,34 +49,16 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxScore(self, s: str) -> int: return max(s[:i].count('0') + s[i:].count('1') for i in range(1, len(s))) ``` -```python -class Solution: - def maxScore(self, s: str) -> int: - ans = t = (s[0] == '0') + s[1:].count('1') - for i in range(1, len(s) - 1): - t += 1 if s[i] == '0' else -1 - ans = max(ans, t) - return ans -``` - -### **Java** - - - ```java class Solution { public int maxScore(String s) { @@ -100,30 +82,6 @@ class Solution { } ``` -```java -class Solution { - public int maxScore(String s) { - int t = 0; - if (s.charAt(0) == '0') { - t++; - } - for (int i = 1; i < s.length(); ++i) { - if (s.charAt(i) == '1') { - t++; - } - } - int ans = t; - for (int i = 1; i < s.length() - 1; ++i) { - t += s.charAt(i) == '0' ? 1 : -1; - ans = Math.max(ans, t); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -144,25 +102,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxScore(string s) { - int t = 0; - if (s[0] == '0') ++t; - for (int i = 1; i < s.size(); ++i) t += s[i] == '1'; - int ans = t; - for (int i = 1; i < s.size() - 1; ++i) { - t += s[i] == '0' ? 1 : -1; - ans = max(ans, t); - } - return ans; - } -}; -``` - -### **Go** - ```go func maxScore(s string) int { ans := 0 @@ -184,33 +123,6 @@ func maxScore(s string) int { } ``` -```go -func maxScore(s string) int { - t := 0 - if s[0] == '0' { - t++ - } - n := len(s) - for i := 1; i < n; i++ { - if s[i] == '1' { - t++ - } - } - ans := t - for i := 1; i < n-1; i++ { - if s[i] == '0' { - t++ - } else { - t-- - } - ans = max(ans, t) - } - return ans -} -``` - -### **TypeScript** - ```ts function maxScore(s: string): number { const n = s.length; @@ -237,8 +149,6 @@ function maxScore(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_score(s: String) -> i32 { @@ -268,10 +178,86 @@ impl Solution { } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def maxScore(self, s: str) -> int: + ans = t = (s[0] == '0') + s[1:].count('1') + for i in range(1, len(s) - 1): + t += 1 if s[i] == '0' else -1 + ans = max(ans, t) + return ans +``` + +```java +class Solution { + public int maxScore(String s) { + int t = 0; + if (s.charAt(0) == '0') { + t++; + } + for (int i = 1; i < s.length(); ++i) { + if (s.charAt(i) == '1') { + t++; + } + } + int ans = t; + for (int i = 1; i < s.length() - 1; ++i) { + t += s.charAt(i) == '0' ? 1 : -1; + ans = Math.max(ans, t); + } + return ans; + } +} +``` +```cpp +class Solution { +public: + int maxScore(string s) { + int t = 0; + if (s[0] == '0') ++t; + for (int i = 1; i < s.size(); ++i) t += s[i] == '1'; + int ans = t; + for (int i = 1; i < s.size() - 1; ++i) { + t += s[i] == '0' ? 1 : -1; + ans = max(ans, t); + } + return ans; + } +}; ``` +```go +func maxScore(s string) int { + t := 0 + if s[0] == '0' { + t++ + } + n := len(s) + for i := 1; i < n; i++ { + if s[i] == '1' { + t++ + } + } + ans := t + for i := 1; i < n-1; i++ { + if s[i] == '0' { + t++ + } else { + t-- + } + ans = max(ans, t) + } + return ans +} ``` + + diff --git a/solution/1400-1499/1422.Maximum Score After Splitting a String/README_EN.md b/solution/1400-1499/1422.Maximum Score After Splitting a String/README_EN.md index b9271d24b3632..c5dd89ddf9a5e 100644 --- a/solution/1400-1499/1422.Maximum Score After Splitting a String/README_EN.md +++ b/solution/1400-1499/1422.Maximum Score After Splitting a String/README_EN.md @@ -48,9 +48,9 @@ left = "01110" and right = "1", score = 2 + 1 = 3 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,18 +58,6 @@ class Solution: return max(s[:i].count('0') + s[i:].count('1') for i in range(1, len(s))) ``` -```python -class Solution: - def maxScore(self, s: str) -> int: - ans = t = (s[0] == '0') + s[1:].count('1') - for i in range(1, len(s) - 1): - t += 1 if s[i] == '0' else -1 - ans = max(ans, t) - return ans -``` - -### **Java** - ```java class Solution { public int maxScore(String s) { @@ -93,30 +81,6 @@ class Solution { } ``` -```java -class Solution { - public int maxScore(String s) { - int t = 0; - if (s.charAt(0) == '0') { - t++; - } - for (int i = 1; i < s.length(); ++i) { - if (s.charAt(i) == '1') { - t++; - } - } - int ans = t; - for (int i = 1; i < s.length() - 1; ++i) { - t += s.charAt(i) == '0' ? 1 : -1; - ans = Math.max(ans, t); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -137,25 +101,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxScore(string s) { - int t = 0; - if (s[0] == '0') ++t; - for (int i = 1; i < s.size(); ++i) t += s[i] == '1'; - int ans = t; - for (int i = 1; i < s.size() - 1; ++i) { - t += s[i] == '0' ? 1 : -1; - ans = max(ans, t); - } - return ans; - } -}; -``` - -### **Go** - ```go func maxScore(s string) int { ans := 0 @@ -177,33 +122,6 @@ func maxScore(s string) int { } ``` -```go -func maxScore(s string) int { - t := 0 - if s[0] == '0' { - t++ - } - n := len(s) - for i := 1; i < n; i++ { - if s[i] == '1' { - t++ - } - } - ans := t - for i := 1; i < n-1; i++ { - if s[i] == '0' { - t++ - } else { - t-- - } - ans = max(ans, t) - } - return ans -} -``` - -### **TypeScript** - ```ts function maxScore(s: string): number { const n = s.length; @@ -230,8 +148,6 @@ function maxScore(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_score(s: String) -> i32 { @@ -261,10 +177,86 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def maxScore(self, s: str) -> int: + ans = t = (s[0] == '0') + s[1:].count('1') + for i in range(1, len(s) - 1): + t += 1 if s[i] == '0' else -1 + ans = max(ans, t) + return ans +``` + +```java +class Solution { + public int maxScore(String s) { + int t = 0; + if (s.charAt(0) == '0') { + t++; + } + for (int i = 1; i < s.length(); ++i) { + if (s.charAt(i) == '1') { + t++; + } + } + int ans = t; + for (int i = 1; i < s.length() - 1; ++i) { + t += s.charAt(i) == '0' ? 1 : -1; + ans = Math.max(ans, t); + } + return ans; + } +} +``` +```cpp +class Solution { +public: + int maxScore(string s) { + int t = 0; + if (s[0] == '0') ++t; + for (int i = 1; i < s.size(); ++i) t += s[i] == '1'; + int ans = t; + for (int i = 1; i < s.size() - 1; ++i) { + t += s[i] == '0' ? 1 : -1; + ans = max(ans, t); + } + return ans; + } +}; ``` +```go +func maxScore(s string) int { + t := 0 + if s[0] == '0' { + t++ + } + n := len(s) + for i := 1; i < n; i++ { + if s[i] == '1' { + t++ + } + } + ans := t + for i := 1; i < n-1; i++ { + if s[i] == '0' { + t++ + } else { + t-- + } + ans = max(ans, t) + } + return ans +} ``` + + diff --git a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/README.md b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/README.md index 2913c3e2658ec..ab26e48b50b6d 100644 --- a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/README.md +++ b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 我们可以用一个长度为 $k$ 的滑动窗口来模拟这个过程。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def maxScore(self, cardPoints: List[int], k: int) -> int: @@ -90,10 +84,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxScore(int[] cardPoints, int k) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func maxScore(cardPoints []int, k int) int { n := len(cardPoints) @@ -147,8 +133,6 @@ func maxScore(cardPoints []int, k int) int { } ``` -### **TypeScript** - ```ts function maxScore(cardPoints: number[], k: number): number { const n = cardPoints.length; @@ -162,8 +146,6 @@ function maxScore(cardPoints: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_score(card_points: Vec, k: i32) -> i32 { @@ -180,7 +162,23 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number[]} cardPoints + * @param {number} k + * @return {number} + */ +var maxScore = function (cardPoints, k) { + const n = cardPoints.length; + let s = cardPoints.slice(-k).reduce((a, b) => a + b); + let ans = s; + for (let i = 0; i < k; ++i) { + s += cardPoints[i] - cardPoints[n - k + i]; + ans = Math.max(ans, s); + } + return ans; +}; +``` ```cs public class Solution { @@ -197,8 +195,6 @@ public class Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -219,25 +215,21 @@ class Solution { } ``` -### **Kotlin** - -```kotlin -class Solution { - fun maxScore(cardPoints: IntArray, k: Int): Int { - val n = cardPoints.size - var s = cardPoints.sliceArray(n - k until n).sum() +```scala +object Solution { + def maxScore(cardPoints: Array[Int], k: Int): Int = { + val n = cardPoints.length + var s = cardPoints.takeRight(k).sum var ans = s - for (i in 0 until k) { - s += cardPoints[i] - cardPoints[n - k + i] - ans = maxOf(ans, s) + for (i <- 0 until k) { + s += cardPoints(i) - cardPoints(n - k + i) + ans = ans.max(s) } - return ans + ans } } ``` -### **Swift** - ```swift class Solution { func maxScore(_ cardPoints: [Int], _ k: Int) -> Int { @@ -253,45 +245,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} cardPoints - * @param {number} k - * @return {number} - */ -var maxScore = function (cardPoints, k) { - const n = cardPoints.length; - let s = cardPoints.slice(-k).reduce((a, b) => a + b); - let ans = s; - for (let i = 0; i < k; ++i) { - s += cardPoints[i] - cardPoints[n - k + i]; - ans = Math.max(ans, s); - } - return ans; -}; -``` - -### **Dart** - -```dart -class Solution { - int maxScore(List cardPoints, int k) { - int n = cardPoints.length; - int s = cardPoints.sublist(n - k).reduce((a, b) => a + b); - int ans = s; - for (int i = 0; i < k; ++i) { - s += cardPoints[i] - cardPoints[n - k + i]; - ans = s > ans ? s : ans; - } - return ans; - } -} -``` - -### **Ruby** - ```rb # @param {Integer[]} card_points # @param {Integer} k @@ -308,27 +261,21 @@ def max_score(card_points, k) end ``` -### **Scala** - -```scala -object Solution { - def maxScore(cardPoints: Array[Int], k: Int): Int = { - val n = cardPoints.length - var s = cardPoints.takeRight(k).sum +```kotlin +class Solution { + fun maxScore(cardPoints: IntArray, k: Int): Int { + val n = cardPoints.size + var s = cardPoints.sliceArray(n - k until n).sum() var ans = s - for (i <- 0 until k) { - s += cardPoints(i) - cardPoints(n - k + i) - ans = ans.max(s) + for (i in 0 until k) { + s += cardPoints[i] - cardPoints[n - k + i] + ans = maxOf(ans, s) } - ans + return ans } } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/README_EN.md b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/README_EN.md index efefd07af1e12..65e4bc097632c 100644 --- a/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/README_EN.md +++ b/solution/1400-1499/1423.Maximum Points You Can Obtain from Cards/README_EN.md @@ -48,7 +48,7 @@ ## Solutions -**Solution 1: Sliding Window** +### Solution 1: Sliding Window We can use a sliding window of length $k$ to simulate this process. @@ -60,8 +60,6 @@ The time complexity is $O(k)$, where $k$ is the integer given in the problem. Th -### **Python3** - ```python class Solution: def maxScore(self, cardPoints: List[int], k: int) -> int: @@ -72,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxScore(int[] cardPoints, int k) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +103,6 @@ public: }; ``` -### **Go** - ```go func maxScore(cardPoints []int, k int) int { n := len(cardPoints) @@ -127,8 +119,6 @@ func maxScore(cardPoints []int, k int) int { } ``` -### **TypeScript** - ```ts function maxScore(cardPoints: number[], k: number): number { const n = cardPoints.length; @@ -142,8 +132,6 @@ function maxScore(cardPoints: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_score(card_points: Vec, k: i32) -> i32 { @@ -160,7 +148,23 @@ impl Solution { } ``` -### **C#** +```js +/** + * @param {number[]} cardPoints + * @param {number} k + * @return {number} + */ +var maxScore = function (cardPoints, k) { + const n = cardPoints.length; + let s = cardPoints.slice(-k).reduce((a, b) => a + b); + let ans = s; + for (let i = 0; i < k; ++i) { + s += cardPoints[i] - cardPoints[n - k + i]; + ans = Math.max(ans, s); + } + return ans; +}; +``` ```cs public class Solution { @@ -177,8 +181,6 @@ public class Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -199,25 +201,21 @@ class Solution { } ``` -### **Kotlin** - -```kotlin -class Solution { - fun maxScore(cardPoints: IntArray, k: Int): Int { - val n = cardPoints.size - var s = cardPoints.sliceArray(n - k until n).sum() +```scala +object Solution { + def maxScore(cardPoints: Array[Int], k: Int): Int = { + val n = cardPoints.length + var s = cardPoints.takeRight(k).sum var ans = s - for (i in 0 until k) { - s += cardPoints[i] - cardPoints[n - k + i] - ans = maxOf(ans, s) + for (i <- 0 until k) { + s += cardPoints(i) - cardPoints(n - k + i) + ans = ans.max(s) } - return ans + ans } } ``` -### **Swift** - ```swift class Solution { func maxScore(_ cardPoints: [Int], _ k: Int) -> Int { @@ -233,45 +231,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} cardPoints - * @param {number} k - * @return {number} - */ -var maxScore = function (cardPoints, k) { - const n = cardPoints.length; - let s = cardPoints.slice(-k).reduce((a, b) => a + b); - let ans = s; - for (let i = 0; i < k; ++i) { - s += cardPoints[i] - cardPoints[n - k + i]; - ans = Math.max(ans, s); - } - return ans; -}; -``` - -### **Dart** - -```dart -class Solution { - int maxScore(List cardPoints, int k) { - int n = cardPoints.length; - int s = cardPoints.sublist(n - k).reduce((a, b) => a + b); - int ans = s; - for (int i = 0; i < k; ++i) { - s += cardPoints[i] - cardPoints[n - k + i]; - ans = s > ans ? s : ans; - } - return ans; - } -} -``` - -### **Ruby** - ```rb # @param {Integer[]} card_points # @param {Integer} k @@ -288,27 +247,21 @@ def max_score(card_points, k) end ``` -### **Scala** - -```scala -object Solution { - def maxScore(cardPoints: Array[Int], k: Int): Int = { - val n = cardPoints.length - var s = cardPoints.takeRight(k).sum +```kotlin +class Solution { + fun maxScore(cardPoints: IntArray, k: Int): Int { + val n = cardPoints.size + var s = cardPoints.sliceArray(n - k until n).sum() var ans = s - for (i <- 0 until k) { - s += cardPoints(i) - cardPoints(n - k + i) - ans = ans.max(s) + for (i in 0 until k) { + s += cardPoints[i] - cardPoints[n - k + i] + ans = maxOf(ans, s) } - ans + return ans } } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1424.Diagonal Traverse II/README.md b/solution/1400-1499/1424.Diagonal Traverse II/README.md index 5ec5396e50603..58c06a267a1e5 100644 --- a/solution/1400-1499/1424.Diagonal Traverse II/README.md +++ b/solution/1400-1499/1424.Diagonal Traverse II/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们观察到: @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]: @@ -82,10 +76,6 @@ class Solution: return [v[2] for v in arr] ``` -### **Java** - - - ```java class Solution { public int[] findDiagonalOrder(List> nums) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func findDiagonalOrder(nums [][]int) []int { arr := [][]int{} @@ -151,8 +137,6 @@ func findDiagonalOrder(nums [][]int) []int { } ``` -### **C#** - ```cs public class Solution { public int[] FindDiagonalOrder(IList> nums) { @@ -172,10 +156,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1424.Diagonal Traverse II/README_EN.md b/solution/1400-1499/1424.Diagonal Traverse II/README_EN.md index ab7d28368a4d3..a402c5570999a 100644 --- a/solution/1400-1499/1424.Diagonal Traverse II/README_EN.md +++ b/solution/1400-1499/1424.Diagonal Traverse II/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -48,8 +48,6 @@ class Solution: return [v[2] for v in arr] ``` -### **Java** - ```java class Solution { public int[] findDiagonalOrder(List> nums) { @@ -69,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +87,6 @@ public: }; ``` -### **Go** - ```go func findDiagonalOrder(nums [][]int) []int { arr := [][]int{} @@ -115,8 +109,6 @@ func findDiagonalOrder(nums [][]int) []int { } ``` -### **C#** - ```cs public class Solution { public int[] FindDiagonalOrder(IList> nums) { @@ -136,10 +128,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1425.Constrained Subsequence Sum/README.md b/solution/1400-1499/1425.Constrained Subsequence Sum/README.md index 5aef21f314533..37611cb745dda 100644 --- a/solution/1400-1499/1425.Constrained Subsequence Sum/README.md +++ b/solution/1400-1499/1425.Constrained Subsequence Sum/README.md @@ -44,16 +44,10 @@ ## 解法 - - -**方法一:动态规划 + 单调队列** +### 方法一:动态规划 + 单调队列 -### **Python3** - - - ```python class Solution: def constrainedSubsetSum(self, nums: List[int], k: int) -> int: @@ -72,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int constrainedSubsetSum(int[] nums, int k) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func constrainedSubsetSum(nums []int, k int) int { n := len(nums) @@ -147,10 +133,6 @@ func constrainedSubsetSum(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1425.Constrained Subsequence Sum/README_EN.md b/solution/1400-1499/1425.Constrained Subsequence Sum/README_EN.md index 7af33d92a9a24..e704665f50151 100644 --- a/solution/1400-1499/1425.Constrained Subsequence Sum/README_EN.md +++ b/solution/1400-1499/1425.Constrained Subsequence Sum/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int constrainedSubsetSum(int[] nums, int k) { @@ -90,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func constrainedSubsetSum(nums []int, k int) int { n := len(nums) @@ -138,10 +132,6 @@ func constrainedSubsetSum(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1426.Counting Elements/README.md b/solution/1400-1499/1426.Counting Elements/README.md index e37aed61b98ab..c39bf59933123 100644 --- a/solution/1400-1499/1426.Counting Elements/README.md +++ b/solution/1400-1499/1426.Counting Elements/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们可以用一个哈希表或数组 $cnt$ 记录数组 $arr$ 中的每个数出现的次数,然后遍历 $cnt$ 中的每个数 $x$,如果 $x+1$ 也在 $cnt$ 中,那么就将 $cnt[x]$ 加到答案中。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python class Solution: def countElements(self, arr: List[int]) -> int: @@ -59,10 +53,6 @@ class Solution: return sum(v for x, v in cnt.items() if cnt[x + 1]) ``` -### **Java** - - - ```java class Solution { public int countElements(int[] arr) { @@ -81,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +90,6 @@ public: }; ``` -### **Go** - ```go func countElements(arr []int) (ans int) { mx := slices.Max(arr) @@ -120,8 +106,6 @@ func countElements(arr []int) (ans int) { } ``` -### **TypeScript** - ```ts function countElements(arr: number[]): number { const mx = Math.max(...arr); @@ -139,7 +123,22 @@ function countElements(arr: number[]): number { } ``` -### **JavaScript** +```rust +use std::collections::HashMap; + +impl Solution { + pub fn count_elements(arr: Vec) -> i32 { + let mut cnt = HashMap::new(); + for &num in &arr { + *cnt.entry(num).or_insert(0) += 1; + } + cnt.iter() + .filter(|(&x, _)| cnt.contains_key(&(x + 1))) + .map(|(_, &v)| v) + .sum() + } +} +``` ```js /** @@ -162,27 +161,6 @@ var countElements = function (arr) { }; ``` -### **Rust** - -```rust -use std::collections::HashMap; - -impl Solution { - pub fn count_elements(arr: Vec) -> i32 { - let mut cnt = HashMap::new(); - for &num in &arr { - *cnt.entry(num).or_insert(0) += 1; - } - cnt.iter() - .filter(|(&x, _)| cnt.contains_key(&(x + 1))) - .map(|(_, &v)| v) - .sum() - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -202,10 +180,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1426.Counting Elements/README_EN.md b/solution/1400-1499/1426.Counting Elements/README_EN.md index af1cc2f1d29d9..1cbb886cbdcff 100644 --- a/solution/1400-1499/1426.Counting Elements/README_EN.md +++ b/solution/1400-1499/1426.Counting Elements/README_EN.md @@ -33,7 +33,7 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We can use a hash table or array $cnt$ to record the frequency of each number in the array $arr$. Then, we traverse each number $x$ in $cnt$. If $x+1$ also exists in $cnt$, we add $cnt[x]$ to the answer. @@ -41,8 +41,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def countElements(self, arr: List[int]) -> int: @@ -50,8 +48,6 @@ class Solution: return sum(v for x, v in cnt.items() if cnt[x + 1]) ``` -### **Java** - ```java class Solution { public int countElements(int[] arr) { @@ -70,8 +66,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +85,6 @@ public: }; ``` -### **Go** - ```go func countElements(arr []int) (ans int) { mx := slices.Max(arr) @@ -109,8 +101,6 @@ func countElements(arr []int) (ans int) { } ``` -### **TypeScript** - ```ts function countElements(arr: number[]): number { const mx = Math.max(...arr); @@ -128,7 +118,22 @@ function countElements(arr: number[]): number { } ``` -### **JavaScript** +```rust +use std::collections::HashMap; + +impl Solution { + pub fn count_elements(arr: Vec) -> i32 { + let mut cnt = HashMap::new(); + for &num in &arr { + *cnt.entry(num).or_insert(0) += 1; + } + cnt.iter() + .filter(|(&x, _)| cnt.contains_key(&(x + 1))) + .map(|(_, &v)| v) + .sum() + } +} +``` ```js /** @@ -151,27 +156,6 @@ var countElements = function (arr) { }; ``` -### **Rust** - -```rust -use std::collections::HashMap; - -impl Solution { - pub fn count_elements(arr: Vec) -> i32 { - let mut cnt = HashMap::new(); - for &num in &arr { - *cnt.entry(num).or_insert(0) += 1; - } - cnt.iter() - .filter(|(&x, _)| cnt.contains_key(&(x + 1))) - .map(|(_, &v)| v) - .sum() - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -191,10 +175,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1427.Perform String Shifts/README.md b/solution/1400-1499/1427.Perform String Shifts/README.md index 910c04ac18a4f..2d65e8f528757 100644 --- a/solution/1400-1499/1427.Perform String Shifts/README.md +++ b/solution/1400-1499/1427.Perform String Shifts/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们不妨记字符串 $s$ 的长度为 $n$。接下来遍历数组 $shift$,累加得到最终的偏移量 $x$,然后将 $x$ 对 $n$ 取模,最终结果就是将 $s$ 的前 $n - x$ 个字符移动到末尾。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def stringShift(self, s: str, shift: List[List[int]]) -> str: @@ -76,10 +70,6 @@ class Solution: return s[-x:] + s[:-x] ``` -### **Java** - - - ```java class Solution { public String stringShift(String s, int[][] shift) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func stringShift(s string, shift [][]int) string { x := 0 @@ -134,8 +120,6 @@ func stringShift(s string, shift [][]int) string { } ``` -### **TypeScript** - ```ts function stringShift(s: string, shift: number[][]): string { let x = 0; @@ -150,10 +134,6 @@ function stringShift(s: string, shift: number[][]): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1427.Perform String Shifts/README_EN.md b/solution/1400-1499/1427.Perform String Shifts/README_EN.md index d4edfaf0dceea..e8fb5d85e0a0b 100644 --- a/solution/1400-1499/1427.Perform String Shifts/README_EN.md +++ b/solution/1400-1499/1427.Perform String Shifts/README_EN.md @@ -50,7 +50,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can denote the length of the string $s$ as $n$. Next, we traverse the array $shift$, accumulate to get the final offset $x$, then take $x$ modulo $n$, the final result is to move the first $n - x$ characters of $s$ to the end. @@ -58,8 +58,6 @@ The time complexity is $O(n + m)$, where $n$ and $m$ are the lengths of the stri -### **Python3** - ```python class Solution: def stringShift(self, s: str, shift: List[List[int]]) -> str: @@ -68,8 +66,6 @@ class Solution: return s[-x:] + s[:-x] ``` -### **Java** - ```java class Solution { public String stringShift(String s, int[][] shift) { @@ -87,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +101,6 @@ public: }; ``` -### **Go** - ```go func stringShift(s string, shift [][]int) string { x := 0 @@ -124,8 +116,6 @@ func stringShift(s string, shift [][]int) string { } ``` -### **TypeScript** - ```ts function stringShift(s: string, shift: number[][]): string { let x = 0; @@ -140,10 +130,6 @@ function stringShift(s: string, shift: number[][]): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1428.Leftmost Column with at Least a One/README.md b/solution/1400-1499/1428.Leftmost Column with at Least a One/README.md index 102a52e3eabd8..b66f7d40ea15f 100644 --- a/solution/1400-1499/1428.Leftmost Column with at Least a One/README.md +++ b/solution/1400-1499/1428.Leftmost Column with at Least a One/README.md @@ -74,9 +74,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们先调用 `BinaryMatrix.dimensions()` 得到矩阵的行数 $m$ 和列数 $n$,然后对于每一行,我们使用二分查找来找到最左边的 $1$ 所在的列数 $j$,找出所有行中最小的满足 $j$ 的值即为答案。如果不存在这样的列,则返回 $-1$。 @@ -84,10 +82,6 @@ -### **Python3** - - - ```python # """ # This is BinaryMatrix's API interface. @@ -108,10 +102,6 @@ class Solution: return -1 if ans >= n else ans ``` -### **Java** - - - ```java /** * // This is the BinaryMatrix's API interface. @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the BinaryMatrix's API interface. @@ -180,8 +168,6 @@ public: }; ``` -### **Go** - ```go /** * // This is the BinaryMatrix's API interface. @@ -215,8 +201,6 @@ func leftMostColumnWithOne(binaryMatrix BinaryMatrix) int { } ``` -### **TypeScript** - ```ts /** * // This is the BinaryMatrix's API interface. @@ -247,9 +231,8 @@ function leftMostColumnWithOne(binaryMatrix: BinaryMatrix) { } ``` -### **Rust** - ```rust + /** * // This is the BinaryMatrix's API interface. * // You should not implement it, or speculate about its implementation @@ -289,8 +272,6 @@ impl Solution { } ``` -### **C#** - ```cs /** * // This is BinaryMatrix's API interface. @@ -323,10 +304,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1428.Leftmost Column with at Least a One/README_EN.md b/solution/1400-1499/1428.Leftmost Column with at Least a One/README_EN.md index 866588ae5104f..66587a010e0a1 100644 --- a/solution/1400-1499/1428.Leftmost Column with at Least a One/README_EN.md +++ b/solution/1400-1499/1428.Leftmost Column with at Least a One/README_EN.md @@ -54,7 +54,7 @@ ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search First, we call `BinaryMatrix.dimensions()` to get the number of rows $m$ and columns $n$ of the matrix. Then for each row, we use binary search to find the column number $j$ where the leftmost $1$ is located. The smallest $j$ value that satisfies all rows is the answer. If there is no such column, return $-1$. @@ -62,8 +62,6 @@ The time complexity is $O(m \times \log n)$, where $m$ and $n$ are the number of -### **Python3** - ```python # """ # This is BinaryMatrix's API interface. @@ -84,8 +82,6 @@ class Solution: return -1 if ans >= n else ans ``` -### **Java** - ```java /** * // This is the BinaryMatrix's API interface. @@ -118,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the BinaryMatrix's API interface. @@ -154,8 +148,6 @@ public: }; ``` -### **Go** - ```go /** * // This is the BinaryMatrix's API interface. @@ -189,8 +181,6 @@ func leftMostColumnWithOne(binaryMatrix BinaryMatrix) int { } ``` -### **TypeScript** - ```ts /** * // This is the BinaryMatrix's API interface. @@ -221,9 +211,8 @@ function leftMostColumnWithOne(binaryMatrix: BinaryMatrix) { } ``` -### **Rust** - ```rust + /** * // This is the BinaryMatrix's API interface. * // You should not implement it, or speculate about its implementation @@ -263,8 +252,6 @@ impl Solution { } ``` -### **C#** - ```cs /** * // This is BinaryMatrix's API interface. @@ -297,10 +284,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1429.First Unique Number/README.md b/solution/1400-1499/1429.First Unique Number/README.md index 6ce2e8ffca560..27d14c1402e94 100644 --- a/solution/1400-1499/1429.First Unique Number/README.md +++ b/solution/1400-1499/1429.First Unique Number/README.md @@ -84,9 +84,7 @@ firstUnique.showFirstUnique(); // 返回 -1 ## 解法 - - -**方法一:哈希表 + 双端队列** +### 方法一:哈希表 + 双端队列 我们可以使用哈希表 $cnt$ 统计每个数字出现的次数,使用双端队列 $q$ 按顺序维护出现的数字。 @@ -98,10 +96,6 @@ firstUnique.showFirstUnique(); // 返回 -1 -### **Python3** - - - ```python class FirstUnique: def __init__(self, nums: List[int]): @@ -125,32 +119,6 @@ class FirstUnique: # obj.add(value) ``` -```python -class FirstUnique: - def __init__(self, nums: List[int]): - self.cnt = Counter(nums) - self.q = deque(nums) - - def showFirstUnique(self) -> int: - while self.q and self.cnt[self.q[0]] != 1: - self.q.popleft() - return -1 if not self.q else self.q[0] - - def add(self, value: int) -> None: - self.cnt[value] += 1 - self.q.append(value) - - -# Your FirstUnique object will be instantiated and called as such: -# obj = FirstUnique(nums) -# param_1 = obj.showFirstUnique() -# obj.add(value) -``` - -### **Java** - - - ```java class FirstUnique { private Map cnt = new HashMap<>(); @@ -189,41 +157,6 @@ class FirstUnique { */ ``` -```java -class FirstUnique { - private Map cnt = new HashMap<>(); - private Deque q = new ArrayDeque<>(); - - public FirstUnique(int[] nums) { - for (int v : nums) { - cnt.put(v, cnt.getOrDefault(v, 0) + 1); - q.offer(v); - } - } - - public int showFirstUnique() { - while (!q.isEmpty() && cnt.get(q.peekFirst()) != 1) { - q.poll(); - } - return q.isEmpty() ? -1 : q.peekFirst(); - } - - public void add(int value) { - cnt.put(value, cnt.getOrDefault(value, 0) + 1); - q.offer(value); - } -} - -/** - * Your FirstUnique object will be instantiated and called as such: - * FirstUnique obj = new FirstUnique(nums); - * int param_1 = obj.showFirstUnique(); - * obj.add(value); - */ -``` - -### **C++** - ```cpp class FirstUnique { public: @@ -257,8 +190,6 @@ private: */ ``` -### **Go** - ```go type FirstUnique struct { cnt map[int]int @@ -296,10 +227,67 @@ func (this *FirstUnique) Add(value int) { */ ``` -### **...** + + +### 方法二 + + + +```python +class FirstUnique: + def __init__(self, nums: List[int]): + self.cnt = Counter(nums) + self.q = deque(nums) + + def showFirstUnique(self) -> int: + while self.q and self.cnt[self.q[0]] != 1: + self.q.popleft() + return -1 if not self.q else self.q[0] + + def add(self, value: int) -> None: + self.cnt[value] += 1 + self.q.append(value) + +# Your FirstUnique object will be instantiated and called as such: +# obj = FirstUnique(nums) +# param_1 = obj.showFirstUnique() +# obj.add(value) ``` +```java +class FirstUnique { + private Map cnt = new HashMap<>(); + private Deque q = new ArrayDeque<>(); + + public FirstUnique(int[] nums) { + for (int v : nums) { + cnt.put(v, cnt.getOrDefault(v, 0) + 1); + q.offer(v); + } + } + + public int showFirstUnique() { + while (!q.isEmpty() && cnt.get(q.peekFirst()) != 1) { + q.poll(); + } + return q.isEmpty() ? -1 : q.peekFirst(); + } + + public void add(int value) { + cnt.put(value, cnt.getOrDefault(value, 0) + 1); + q.offer(value); + } +} + +/** + * Your FirstUnique object will be instantiated and called as such: + * FirstUnique obj = new FirstUnique(nums); + * int param_1 = obj.showFirstUnique(); + * obj.add(value); + */ ``` + + diff --git a/solution/1400-1499/1429.First Unique Number/README_EN.md b/solution/1400-1499/1429.First Unique Number/README_EN.md index f167f60c002e9..2d2276d07e3e9 100644 --- a/solution/1400-1499/1429.First Unique Number/README_EN.md +++ b/solution/1400-1499/1429.First Unique Number/README_EN.md @@ -80,9 +80,9 @@ firstUnique.showFirstUnique(); // return -1 ## Solutions - +### Solution 1 -### **Python3** + ```python class FirstUnique: @@ -107,30 +107,6 @@ class FirstUnique: # obj.add(value) ``` -```python -class FirstUnique: - def __init__(self, nums: List[int]): - self.cnt = Counter(nums) - self.q = deque(nums) - - def showFirstUnique(self) -> int: - while self.q and self.cnt[self.q[0]] != 1: - self.q.popleft() - return -1 if not self.q else self.q[0] - - def add(self, value: int) -> None: - self.cnt[value] += 1 - self.q.append(value) - - -# Your FirstUnique object will be instantiated and called as such: -# obj = FirstUnique(nums) -# param_1 = obj.showFirstUnique() -# obj.add(value) -``` - -### **Java** - ```java class FirstUnique { private Map cnt = new HashMap<>(); @@ -169,41 +145,6 @@ class FirstUnique { */ ``` -```java -class FirstUnique { - private Map cnt = new HashMap<>(); - private Deque q = new ArrayDeque<>(); - - public FirstUnique(int[] nums) { - for (int v : nums) { - cnt.put(v, cnt.getOrDefault(v, 0) + 1); - q.offer(v); - } - } - - public int showFirstUnique() { - while (!q.isEmpty() && cnt.get(q.peekFirst()) != 1) { - q.poll(); - } - return q.isEmpty() ? -1 : q.peekFirst(); - } - - public void add(int value) { - cnt.put(value, cnt.getOrDefault(value, 0) + 1); - q.offer(value); - } -} - -/** - * Your FirstUnique object will be instantiated and called as such: - * FirstUnique obj = new FirstUnique(nums); - * int param_1 = obj.showFirstUnique(); - * obj.add(value); - */ -``` - -### **C++** - ```cpp class FirstUnique { public: @@ -237,8 +178,6 @@ private: */ ``` -### **Go** - ```go type FirstUnique struct { cnt map[int]int @@ -276,10 +215,67 @@ func (this *FirstUnique) Add(value int) { */ ``` -### **...** + + +### Solution 2 + + +```python +class FirstUnique: + def __init__(self, nums: List[int]): + self.cnt = Counter(nums) + self.q = deque(nums) + + def showFirstUnique(self) -> int: + while self.q and self.cnt[self.q[0]] != 1: + self.q.popleft() + return -1 if not self.q else self.q[0] + + def add(self, value: int) -> None: + self.cnt[value] += 1 + self.q.append(value) + + +# Your FirstUnique object will be instantiated and called as such: +# obj = FirstUnique(nums) +# param_1 = obj.showFirstUnique() +# obj.add(value) ``` +```java +class FirstUnique { + private Map cnt = new HashMap<>(); + private Deque q = new ArrayDeque<>(); + + public FirstUnique(int[] nums) { + for (int v : nums) { + cnt.put(v, cnt.getOrDefault(v, 0) + 1); + q.offer(v); + } + } + + public int showFirstUnique() { + while (!q.isEmpty() && cnt.get(q.peekFirst()) != 1) { + q.poll(); + } + return q.isEmpty() ? -1 : q.peekFirst(); + } + + public void add(int value) { + cnt.put(value, cnt.getOrDefault(value, 0) + 1); + q.offer(value); + } +} + +/** + * Your FirstUnique object will be instantiated and called as such: + * FirstUnique obj = new FirstUnique(nums); + * int param_1 = obj.showFirstUnique(); + * obj.add(value); + */ ``` + + diff --git a/solution/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/README.md b/solution/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/README.md index c47ed44cd4301..99dda3bb548c8 100644 --- a/solution/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/README.md +++ b/solution/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 根据题目,我们设计一个递归函数 $dfs(root, u)$,表示从当前节点 $root$ 开始,且当前已经遍历到数组的第 $u$ 个元素,是否存在一条从根节点到叶子节点的路径,且路径上的元素与数组中的元素一一对应。那么答案就是 $dfs(root, 0)$。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -93,10 +87,6 @@ class Solution: return dfs(root, 0) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -160,8 +148,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -186,10 +172,6 @@ func isValidSequence(root *TreeNode, arr []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/README_EN.md b/solution/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/README_EN.md index 3936377aa350d..5f52608545c98 100644 --- a/solution/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/README_EN.md +++ b/solution/1400-1499/1430.Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree/README_EN.md @@ -54,12 +54,10 @@ Other valid sequences are: ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -79,8 +77,6 @@ class Solution: return dfs(root, 0) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -117,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -144,8 +138,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -170,10 +162,6 @@ func isValidSequence(root *TreeNode, arr []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1431.Kids With the Greatest Number of Candies/README.md b/solution/1400-1499/1431.Kids With the Greatest Number of Candies/README.md index 2a715837c6310..0c1f532ffbd18 100644 --- a/solution/1400-1499/1431.Kids With the Greatest Number of Candies/README.md +++ b/solution/1400-1499/1431.Kids With the Greatest Number of Candies/README.md @@ -49,14 +49,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: @@ -64,10 +60,6 @@ class Solution: return [candy + extraCandies >= mx for candy in candies] ``` -### **Java** - - - ```java class Solution { public List kidsWithCandies(int[] candies, int extraCandies) { @@ -84,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +90,6 @@ public: }; ``` -### **Go** - ```go func kidsWithCandies(candies []int, extraCandies int) (ans []bool) { mx := slices.Max(candies) @@ -112,8 +100,6 @@ func kidsWithCandies(candies []int, extraCandies int) (ans []bool) { } ``` -### **TypeScript** - ```ts function kidsWithCandies(candies: number[], extraCandies: number): boolean[] { const max = candies.reduce((r, v) => Math.max(r, v)); @@ -121,8 +107,6 @@ function kidsWithCandies(candies: number[], extraCandies: number): boolean[] { } ``` -### **Rust** - ```rust impl Solution { pub fn kids_with_candies(candies: Vec, extra_candies: i32) -> Vec { @@ -135,29 +119,6 @@ impl Solution { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -bool* kidsWithCandies(int* candies, int candiesSize, int extraCandies, int* returnSize) { - int mx = 0; - for (int i = 0; i < candiesSize; i++) { - mx = max(mx, candies[i]); - } - bool* ans = malloc(candiesSize * sizeof(bool)); - for (int i = 0; i < candiesSize; i++) { - ans[i] = candies[i] + extraCandies >= mx; - } - *returnSize = candiesSize; - return ans; -} -``` - -### **PHP** - ```php class Solution { /** @@ -176,10 +137,25 @@ class Solution { } ``` -### **...** - -``` - +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +bool* kidsWithCandies(int* candies, int candiesSize, int extraCandies, int* returnSize) { + int mx = 0; + for (int i = 0; i < candiesSize; i++) { + mx = max(mx, candies[i]); + } + bool* ans = malloc(candiesSize * sizeof(bool)); + for (int i = 0; i < candiesSize; i++) { + ans[i] = candies[i] + extraCandies >= mx; + } + *returnSize = candiesSize; + return ans; +} ``` + + diff --git a/solution/1400-1499/1431.Kids With the Greatest Number of Candies/README_EN.md b/solution/1400-1499/1431.Kids With the Greatest Number of Candies/README_EN.md index 0f43fb4d9dbeb..206194c8c0bd3 100644 --- a/solution/1400-1499/1431.Kids With the Greatest Number of Candies/README_EN.md +++ b/solution/1400-1499/1431.Kids With the Greatest Number of Candies/README_EN.md @@ -52,9 +52,9 @@ Kid 1 will always have the greatest number of candies, even if a different kid i ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return [candy + extraCandies >= mx for candy in candies] ``` -### **Java** - ```java class Solution { public List kidsWithCandies(int[] candies, int extraCandies) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +93,6 @@ public: }; ``` -### **Go** - ```go func kidsWithCandies(candies []int, extraCandies int) (ans []bool) { mx := slices.Max(candies) @@ -109,8 +103,6 @@ func kidsWithCandies(candies []int, extraCandies int) (ans []bool) { } ``` -### **TypeScript** - ```ts function kidsWithCandies(candies: number[], extraCandies: number): boolean[] { const max = candies.reduce((r, v) => Math.max(r, v)); @@ -118,8 +110,6 @@ function kidsWithCandies(candies: number[], extraCandies: number): boolean[] { } ``` -### **Rust** - ```rust impl Solution { pub fn kids_with_candies(candies: Vec, extra_candies: i32) -> Vec { @@ -132,29 +122,6 @@ impl Solution { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -bool* kidsWithCandies(int* candies, int candiesSize, int extraCandies, int* returnSize) { - int mx = 0; - for (int i = 0; i < candiesSize; i++) { - mx = max(mx, candies[i]); - } - bool* ans = malloc(candiesSize * sizeof(bool)); - for (int i = 0; i < candiesSize; i++) { - ans[i] = candies[i] + extraCandies >= mx; - } - *returnSize = candiesSize; - return ans; -} -``` - -### **PHP** - ```php class Solution { /** @@ -173,10 +140,25 @@ class Solution { } ``` -### **...** - -``` - +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +bool* kidsWithCandies(int* candies, int candiesSize, int extraCandies, int* returnSize) { + int mx = 0; + for (int i = 0; i < candiesSize; i++) { + mx = max(mx, candies[i]); + } + bool* ans = malloc(candiesSize * sizeof(bool)); + for (int i = 0; i < candiesSize; i++) { + ans[i] = candies[i] + extraCandies >= mx; + } + *returnSize = candiesSize; + return ans; +} ``` + + diff --git a/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README.md b/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README.md index 2c15f0af94c4f..6f2a28210f4d5 100644 --- a/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README.md +++ b/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 要想得到最大差值,那么我们应该拿到最大值与最小值,这样差值最大。 @@ -83,10 +81,6 @@ -### **Python3** - - - ```python class Solution: def maxDiff(self, num: int) -> int: @@ -105,10 +99,6 @@ class Solution: return int(a) - int(b) ``` -### **Java** - - - ```java class Solution { public int maxDiff(int num) { @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +159,6 @@ public: }; ``` -### **Go** - ```go func maxDiff(num int) int { a, b := num, num @@ -197,10 +183,6 @@ func maxDiff(num int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README_EN.md b/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README_EN.md index 7cf75d8a2b4ed..dd8526ae38674 100644 --- a/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README_EN.md +++ b/solution/1400-1499/1432.Max Difference You Can Get From Changing an Integer/README_EN.md @@ -47,9 +47,9 @@ We have now a = 9 and b = 1 and max difference = 8 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return int(a) - int(b) ``` -### **Java** - ```java class Solution { public int maxDiff(int num) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +129,6 @@ public: }; ``` -### **Go** - ```go func maxDiff(num int) int { a, b := num, num @@ -159,10 +153,6 @@ func maxDiff(num int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1433.Check If a String Can Break Another String/README.md b/solution/1400-1499/1433.Check If a String Can Break Another String/README.md index f7d5573907f0e..6b8bd0892e696 100644 --- a/solution/1400-1499/1433.Check If a String Can Break Another String/README.md +++ b/solution/1400-1499/1433.Check If a String Can Break Another String/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 将字符串 $s1$, $s2$ 分别进行升序排序。然后同时遍历两个字符串,对应字符进行大小比较。若对于任意 $i∈[0, n),都有 $s1[i] \le s2[i]$,或者都有 $s1[i] \ge s2[i]$,则存在一个排列可以打破另一个排列。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def checkIfCanBreak(self, s1: str, s2: str) -> bool: @@ -69,10 +63,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public boolean checkIfCanBreak(String s1, String s2) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func checkIfCanBreak(s1 string, s2 string) bool { cs1 := []byte(s1) @@ -136,8 +122,6 @@ func checkIfCanBreak(s1 string, s2 string) bool { } ``` -### **TypeScript** - ```ts function checkIfCanBreak(s1: string, s2: string): boolean { const cs1: string[] = Array.from(s1); @@ -156,10 +140,6 @@ function checkIfCanBreak(s1: string, s2: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1433.Check If a String Can Break Another String/README_EN.md b/solution/1400-1499/1433.Check If a String Can Break Another String/README_EN.md index b18559d26567e..98741817add1f 100644 --- a/solution/1400-1499/1433.Check If a String Can Break Another String/README_EN.md +++ b/solution/1400-1499/1433.Check If a String Can Break Another String/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public boolean checkIfCanBreak(String s1, String s2) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +99,6 @@ public: }; ``` -### **Go** - ```go func checkIfCanBreak(s1 string, s2 string) bool { cs1 := []byte(s1) @@ -123,8 +117,6 @@ func checkIfCanBreak(s1 string, s2 string) bool { } ``` -### **TypeScript** - ```ts function checkIfCanBreak(s1: string, s2: string): boolean { const cs1: string[] = Array.from(s1); @@ -143,10 +135,6 @@ function checkIfCanBreak(s1: string, s2: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1434.Number of Ways to Wear Different Hats to Each Other/README.md b/solution/1400-1499/1434.Number of Ways to Wear Different Hats to Each Other/README.md index 49aebe41727a7..883a316f182b9 100644 --- a/solution/1400-1499/1434.Number of Ways to Wear Different Hats to Each Other/README.md +++ b/solution/1400-1499/1434.Number of Ways to Wear Different Hats to Each Other/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:状态压缩动态规划** +### 方法一:状态压缩动态规划 我们注意到 $n$ 不超过 $10$,因此我们考虑使用状态压缩动态规划的方法求解。 @@ -85,10 +83,6 @@ $$ -### **Python3** - - - ```python class Solution: def numberWays(self, hats: List[List[int]]) -> int: @@ -110,10 +104,6 @@ class Solution: return f[m][-1] ``` -### **Java** - - - ```java class Solution { public int numberWays(List> hats) { @@ -149,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -185,8 +173,6 @@ public: }; ``` -### **Go** - ```go func numberWays(hats [][]int) int { n := len(hats) @@ -220,8 +206,6 @@ func numberWays(hats [][]int) int { } ``` -### **TypeScript** - ```ts function numberWays(hats: number[][]): number { const n = hats.length; @@ -251,10 +235,6 @@ function numberWays(hats: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1434.Number of Ways to Wear Different Hats to Each Other/README_EN.md b/solution/1400-1499/1434.Number of Ways to Wear Different Hats to Each Other/README_EN.md index 90a26c4763b0b..32daac60976fb 100644 --- a/solution/1400-1499/1434.Number of Ways to Wear Different Hats to Each Other/README_EN.md +++ b/solution/1400-1499/1434.Number of Ways to Wear Different Hats to Each Other/README_EN.md @@ -53,7 +53,7 @@ Number of Permutations of (1,2,3,4) = 24. ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We notice that $n$ is not greater than $10$, so we consider using DP with state compression to solve this problem. @@ -73,8 +73,6 @@ Time complexity $O(m \times 2^n \times n)$, space complexity $O(m \times 2^n)$. -### **Python3** - ```python class Solution: def numberWays(self, hats: List[List[int]]) -> int: @@ -96,8 +94,6 @@ class Solution: return f[m][-1] ``` -### **Java** - ```java class Solution { public int numberWays(List> hats) { @@ -133,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +163,6 @@ public: }; ``` -### **Go** - ```go func numberWays(hats [][]int) int { n := len(hats) @@ -204,8 +196,6 @@ func numberWays(hats [][]int) int { } ``` -### **TypeScript** - ```ts function numberWays(hats: number[][]): number { const n = hats.length; @@ -235,10 +225,6 @@ function numberWays(hats: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1435.Create a Session Bar Chart/README.md b/solution/1400-1499/1435.Create a Session Bar Chart/README.md index 465f7fb1f42bb..ff560d4e38f6d 100644 --- a/solution/1400-1499/1435.Create a Session Bar Chart/README.md +++ b/solution/1400-1499/1435.Create a Session Bar Chart/README.md @@ -63,12 +63,10 @@ Sessions 表: ## 解法 - +### 方法一 -### **SQL** - ```sql SELECT '[0-5>' AS bin, COUNT(1) AS total FROM Sessions WHERE duration < 300 UNION @@ -80,3 +78,5 @@ SELECT '15 or more' AS bin, COUNT(1) AS total FROM Sessions WHERE 900 <= duratio ``` + + diff --git a/solution/1400-1499/1435.Create a Session Bar Chart/README_EN.md b/solution/1400-1499/1435.Create a Session Bar Chart/README_EN.md index 0dd963458913f..b4cd666c32d37 100644 --- a/solution/1400-1499/1435.Create a Session Bar Chart/README_EN.md +++ b/solution/1400-1499/1435.Create a Session Bar Chart/README_EN.md @@ -60,9 +60,9 @@ For session_id 5 has a duration greater than or equal to 15 minutes. ## Solutions - +### Solution 1 -### **SQL** + ```sql SELECT '[0-5>' AS bin, COUNT(1) AS total FROM Sessions WHERE duration < 300 @@ -75,3 +75,5 @@ SELECT '15 or more' AS bin, COUNT(1) AS total FROM Sessions WHERE 900 <= duratio ``` + + diff --git a/solution/1400-1499/1436.Destination City/README.md b/solution/1400-1499/1436.Destination City/README.md index 5b2fd7ed73c86..ad6e87b3ae7c0 100644 --- a/solution/1400-1499/1436.Destination City/README.md +++ b/solution/1400-1499/1436.Destination City/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 将所有起点存入哈希表中,然后遍历所有终点,找出没出现在哈希表中的终点,即为答案。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def destCity(self, paths: List[List[str]]) -> str: @@ -75,10 +69,6 @@ class Solution: return next(b for _, b in paths if b not in s) ``` -### **Java** - - - ```java class Solution { public String destCity(List> paths) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func destCity(paths [][]string) string { s := map[string]bool{} @@ -133,29 +119,6 @@ func destCity(paths [][]string) string { } ``` -### **JavaScript** - -```js -/** - * @param {string[][]} paths - * @return {string} - */ -var destCity = function (paths) { - const s = new Set(); - for (const [a, _] of paths) { - s.add(a); - } - for (const [_, b] of paths) { - if (!s.has(b)) { - return b; - } - } - return ''; -}; -``` - -### **TypeScript** - ```ts function destCity(paths: string[][]): string { const set = new Set(paths.map(([a]) => a)); @@ -168,8 +131,6 @@ function destCity(paths: string[][]): string { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -188,7 +149,24 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {string[][]} paths + * @return {string} + */ +var destCity = function (paths) { + const s = new Set(); + for (const [a, _] of paths) { + s.add(a); + } + for (const [_, b] of paths) { + if (!s.has(b)) { + return b; + } + } + return ''; +}; +``` ```c char* destCity(char*** paths, int pathsSize, int* pathsColSize) { @@ -208,10 +186,6 @@ char* destCity(char*** paths, int pathsSize, int* pathsColSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1436.Destination City/README_EN.md b/solution/1400-1499/1436.Destination City/README_EN.md index 948fc2b3e9ae1..5052c1e9fa260 100644 --- a/solution/1400-1499/1436.Destination City/README_EN.md +++ b/solution/1400-1499/1436.Destination City/README_EN.md @@ -50,9 +50,9 @@ Clearly the destination city is "A". ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return next(b for _, b in paths if b not in s) ``` -### **Java** - ```java class Solution { public String destCity(List> paths) { @@ -80,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +96,6 @@ public: }; ``` -### **Go** - ```go func destCity(paths [][]string) string { s := map[string]bool{} @@ -117,29 +111,6 @@ func destCity(paths [][]string) string { } ``` -### **JavaScript** - -```js -/** - * @param {string[][]} paths - * @return {string} - */ -var destCity = function (paths) { - const s = new Set(); - for (const [a, _] of paths) { - s.add(a); - } - for (const [_, b] of paths) { - if (!s.has(b)) { - return b; - } - } - return ''; -}; -``` - -### **TypeScript** - ```ts function destCity(paths: string[][]): string { const set = new Set(paths.map(([a]) => a)); @@ -152,8 +123,6 @@ function destCity(paths: string[][]): string { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -172,7 +141,24 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {string[][]} paths + * @return {string} + */ +var destCity = function (paths) { + const s = new Set(); + for (const [a, _] of paths) { + s.add(a); + } + for (const [_, b] of paths) { + if (!s.has(b)) { + return b; + } + } + return ''; +}; +``` ```c char* destCity(char*** paths, int pathsSize, int* pathsColSize) { @@ -192,10 +178,6 @@ char* destCity(char*** paths, int pathsSize, int* pathsColSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/README.md b/solution/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/README.md index fe90104d7ee65..e96e5190acc23 100644 --- a/solution/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/README.md +++ b/solution/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以遍历数组 $nums$,用变量 $j$ 记录上一个 $1$ 的下标,那么当前位置 $i$ 的元素为 $1$ 时,只需要判断 $i - j - 1$ 是否小于 $k$ 即可。如果小于 $k$,则说明存在两个 $1$ 之间的 $0$ 的个数小于 $k$,返回 `false`;否则,将 $j$ 更新为 $i$,继续遍历数组。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def kLengthApart(self, nums: List[int], k: int) -> bool: @@ -78,10 +72,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean kLengthApart(int[] nums, int k) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func kLengthApart(nums []int, k int) bool { j := -(k + 1) @@ -136,8 +122,6 @@ func kLengthApart(nums []int, k int) bool { } ``` -### **TypeScript** - ```ts function kLengthApart(nums: number[], k: number): boolean { let j = -(k + 1); @@ -153,10 +137,6 @@ function kLengthApart(nums: number[], k: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/README_EN.md b/solution/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/README_EN.md index bfd81ec9263f3..1cebf35fd56d8 100644 --- a/solution/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/README_EN.md +++ b/solution/1400-1499/1437.Check If All 1's Are at Least Length K Places Away/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -50,8 +50,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean kLengthApart(int[] nums, int k) { @@ -69,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,8 +85,6 @@ public: }; ``` -### **Go** - ```go func kLengthApart(nums []int, k int) bool { j := -(k + 1) @@ -106,8 +100,6 @@ func kLengthApart(nums []int, k int) bool { } ``` -### **TypeScript** - ```ts function kLengthApart(nums: number[], k: number): boolean { let j = -(k + 1); @@ -123,10 +115,6 @@ function kLengthApart(nums: number[], k: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README.md b/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README.md index 8233faf7d68d6..e1ab08750c25a 100644 --- a/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README.md +++ b/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:有序集合 + 滑动窗口** +### 方法一:有序集合 + 滑动窗口 我们可以枚举每个位置作为子数组的右端点,找到其对应的最靠左的左端点,满足区间内中最大值与最小值的差值不超过 $limit$。过程中,我们用有序集合维护窗口内的最大值和最小值。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestSubarray(int[] nums, int limit) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func longestSubarray(nums []int, limit int) (ans int) { tm := treemap.NewWithIntComparator() @@ -163,8 +149,6 @@ func longestSubarray(nums []int, limit int) (ans int) { } ``` -### **TypeScript** - ```ts function longestSubarray(nums: number[], limit: number): number { const ts = new TreapMultiSet(); @@ -799,10 +783,6 @@ class TreapMultiSet implements ITreapMultiSet { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README_EN.md b/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README_EN.md index cccd86cf2450f..d66d13f489f7c 100644 --- a/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README_EN.md +++ b/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README_EN.md @@ -52,9 +52,9 @@ Therefore, the size of the longest subarray is 2. ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedList @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestSubarray(int[] nums, int limit) { @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +112,6 @@ public: }; ``` -### **Go** - ```go func longestSubarray(nums []int, limit int) (ans int) { tm := treemap.NewWithIntComparator() @@ -148,8 +142,6 @@ func longestSubarray(nums []int, limit int) (ans int) { } ``` -### **TypeScript** - ```ts function longestSubarray(nums: number[], limit: number): number { const ts = new TreapMultiSet(); @@ -784,10 +776,6 @@ class TreapMultiSet implements ITreapMultiSet { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1439.Find the Kth Smallest Sum of a Matrix With Sorted Rows/README.md b/solution/1400-1499/1439.Find the Kth Smallest Sum of a Matrix With Sorted Rows/README.md index 12485f6191805..39505650a6d99 100644 --- a/solution/1400-1499/1439.Find the Kth Smallest Sum of a Matrix With Sorted Rows/README.md +++ b/solution/1400-1499/1439.Find the Kth Smallest Sum of a Matrix With Sorted Rows/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:逐行遍历 + 排序** +### 方法一:逐行遍历 + 排序 根据题目描述,我们需要找出前 $m$ 行的所有可能数组中的第 $k$ 个最小数组和。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def kthSmallest(self, mat: List[List[int]], k: int) -> int: @@ -85,10 +79,6 @@ class Solution: return pre[-1] ``` -### **Java** - - - ```java class Solution { public int kthSmallest(int[][] mat, int k) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func kthSmallest(mat [][]int, k int) int { pre := []int{0} @@ -161,8 +147,6 @@ func kthSmallest(mat [][]int, k int) int { } ``` -### **TypeScript** - ```ts function kthSmallest(mat: number[][], k: number): number { let pre: number[] = [0]; @@ -179,10 +163,6 @@ function kthSmallest(mat: number[][], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1439.Find the Kth Smallest Sum of a Matrix With Sorted Rows/README_EN.md b/solution/1400-1499/1439.Find the Kth Smallest Sum of a Matrix With Sorted Rows/README_EN.md index 04e120065c3e5..7f0d167288106 100644 --- a/solution/1400-1499/1439.Find the Kth Smallest Sum of a Matrix With Sorted Rows/README_EN.md +++ b/solution/1400-1499/1439.Find the Kth Smallest Sum of a Matrix With Sorted Rows/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return pre[-1] ``` -### **Java** - ```java class Solution { public int kthSmallest(int[][] mat, int k) { @@ -90,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func kthSmallest(mat [][]int, k int) int { pre := []int{0} @@ -137,8 +131,6 @@ func kthSmallest(mat [][]int, k int) int { } ``` -### **TypeScript** - ```ts function kthSmallest(mat: number[][], k: number): number { let pre: number[] = [0]; @@ -155,10 +147,6 @@ function kthSmallest(mat: number[][], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1440.Evaluate Boolean Expression/README.md b/solution/1400-1499/1440.Evaluate Boolean Expression/README.md index 810098e7538cb..8fd25f497a447 100644 --- a/solution/1400-1499/1440.Evaluate Boolean Expression/README.md +++ b/solution/1400-1499/1440.Evaluate Boolean Expression/README.md @@ -88,16 +88,12 @@ Expressions 表: ## 解法 - - -**方法一:等值连接 + CASE 表达式** +### 方法一:等值连接 + CASE 表达式 我们可以通过等值连接,将 `Expressions` 表中的每一行与 `Variables` 表中的两行进行关联,关联的条件是 `left_operand = name` 和 `right_operand = name`,然后通过 `CASE` 表达式来判断布尔表达式的值。如果 `operator` 为 `=`,则判断两个值是否相等;如果 `operator` 为 `>`,则判断左值是否大于右值;如果 `operator` 为 `<`,则判断左值是否小于右值。若是,那么布尔表达式的值为 `true`,否则为 `false`。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -119,3 +115,5 @@ FROM ``` + + diff --git a/solution/1400-1499/1440.Evaluate Boolean Expression/README_EN.md b/solution/1400-1499/1440.Evaluate Boolean Expression/README_EN.md index 0de49de7f6b0d..be1f8e11c7ece 100644 --- a/solution/1400-1499/1440.Evaluate Boolean Expression/README_EN.md +++ b/solution/1400-1499/1440.Evaluate Boolean Expression/README_EN.md @@ -83,14 +83,12 @@ As shown, you need to find the value of each boolean expression in the table usi ## Solutions -**Solution 1: Equi-Join + CASE Expression** +### Solution 1: Equi-Join + CASE Expression We can associate each row in the `Expressions` table with two rows in the `Variables` table using an equi-join, where the conditions for the association are `left_operand = name` and `right_operand = name`. Then, we can use a `CASE` expression to determine the value of the boolean expression. If the `operator` is `=`, we check if the two values are equal. If the `operator` is `>`, we check if the left value is greater than the right value. If the `operator` is `<`, we check if the left value is less than the right value. If the condition is true, the boolean expression evaluates to `true`, otherwise it evaluates to `false`. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -112,3 +110,5 @@ FROM ``` + + diff --git a/solution/1400-1499/1441.Build an Array With Stack Operations/README.md b/solution/1400-1499/1441.Build an Array With Stack Operations/README.md index 133b1311f7411..99358b1b902f5 100644 --- a/solution/1400-1499/1441.Build an Array With Stack Operations/README.md +++ b/solution/1400-1499/1441.Build an Array With Stack Operations/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们定义 $cur$ 表示当前已经从 `list` 中读取到的数字,初始时 $cur = 0$,用一个数组 $ans$ 存储答案。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def buildArray(self, target: List[int], n: int) -> List[str]: @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List buildArray(int[] target, int n) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +121,6 @@ public: }; ``` -### **Go** - ```go func buildArray(target []int, n int) []string { cur := 0 @@ -149,33 +135,6 @@ func buildArray(target []int, n int) []string { } ``` -### **C** - -```c -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -char** buildArray(int* target, int targetSize, int n, int* returnSize) { - char** res = (char**) malloc(sizeof(char*) * n * 2); - int cur = 1; - int i = 0; - for (int j = 0; j < targetSize; j++) { - while (++cur < target[j]) { - res[i] = (char*) malloc(sizeof(char) * 8); - strcpy(res[i++], "Push"); - res[i] = (char*) malloc(sizeof(char) * 8); - strcpy(res[i++], "Pop"); - } - res[i] = (char*) malloc(sizeof(char) * 8); - strcpy(res[i++], "Push"); - } - *returnSize = i; - return res; -} -``` - -### **TypeScript** - ```ts function buildArray(target: number[], n: number): string[] { const res = []; @@ -190,8 +149,6 @@ function buildArray(target: number[], n: number): string[] { } ``` -### **Rust** - ```rust impl Solution { pub fn build_array(target: Vec, n: i32) -> Vec { @@ -211,10 +168,29 @@ impl Solution { } ``` -### **...** - -``` - +```c +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +char** buildArray(int* target, int targetSize, int n, int* returnSize) { + char** res = (char**) malloc(sizeof(char*) * n * 2); + int cur = 1; + int i = 0; + for (int j = 0; j < targetSize; j++) { + while (++cur < target[j]) { + res[i] = (char*) malloc(sizeof(char) * 8); + strcpy(res[i++], "Push"); + res[i] = (char*) malloc(sizeof(char) * 8); + strcpy(res[i++], "Pop"); + } + res[i] = (char*) malloc(sizeof(char) * 8); + strcpy(res[i++], "Push"); + } + *returnSize = i; + return res; +} ``` + + diff --git a/solution/1400-1499/1441.Build an Array With Stack Operations/README_EN.md b/solution/1400-1499/1441.Build an Array With Stack Operations/README_EN.md index 90ae080d6699b..21ccfc0e3c762 100644 --- a/solution/1400-1499/1441.Build an Array With Stack Operations/README_EN.md +++ b/solution/1400-1499/1441.Build an Array With Stack Operations/README_EN.md @@ -73,9 +73,9 @@ The answers that read integer 3 from the stream are not accepted. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -90,8 +90,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List buildArray(int[] target, int n) { @@ -109,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +125,6 @@ public: }; ``` -### **Go** - ```go func buildArray(target []int, n int) []string { cur := 0 @@ -145,33 +139,6 @@ func buildArray(target []int, n int) []string { } ``` -### **C** - -```c -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -char** buildArray(int* target, int targetSize, int n, int* returnSize) { - char** res = (char**) malloc(sizeof(char*) * n * 2); - int cur = 1; - int i = 0; - for (int j = 0; j < targetSize; j++) { - while (++cur < target[j]) { - res[i] = (char*) malloc(sizeof(char) * 8); - strcpy(res[i++], "Push"); - res[i] = (char*) malloc(sizeof(char) * 8); - strcpy(res[i++], "Pop"); - } - res[i] = (char*) malloc(sizeof(char) * 8); - strcpy(res[i++], "Push"); - } - *returnSize = i; - return res; -} -``` - -### **TypeScript** - ```ts function buildArray(target: number[], n: number): string[] { const res = []; @@ -186,8 +153,6 @@ function buildArray(target: number[], n: number): string[] { } ``` -### **Rust** - ```rust impl Solution { pub fn build_array(target: Vec, n: i32) -> Vec { @@ -207,10 +172,29 @@ impl Solution { } ``` -### **...** - -``` - +```c +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +char** buildArray(int* target, int targetSize, int n, int* returnSize) { + char** res = (char**) malloc(sizeof(char*) * n * 2); + int cur = 1; + int i = 0; + for (int j = 0; j < targetSize; j++) { + while (++cur < target[j]) { + res[i] = (char*) malloc(sizeof(char) * 8); + strcpy(res[i++], "Push"); + res[i] = (char*) malloc(sizeof(char) * 8); + strcpy(res[i++], "Pop"); + } + res[i] = (char*) malloc(sizeof(char) * 8); + strcpy(res[i++], "Push"); + } + *returnSize = i; + return res; +} ``` + + diff --git a/solution/1400-1499/1442.Count Triplets That Can Form Two Arrays of Equal XOR/README.md b/solution/1400-1499/1442.Count Triplets That Can Form Two Arrays of Equal XOR/README.md index 1ab4d4d324e82..e71cdda3b65ce 100644 --- a/solution/1400-1499/1442.Count Triplets That Can Form Two Arrays of Equal XOR/README.md +++ b/solution/1400-1499/1442.Count Triplets That Can Form Two Arrays of Equal XOR/README.md @@ -65,16 +65,10 @@ ## 解法 - - -前缀异或,然后暴力枚举即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def countTriplets(self, arr: List[int]) -> int: @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countTriplets(int[] arr) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func countTriplets(arr []int) int { n := len(arr) @@ -168,10 +154,6 @@ func countTriplets(arr []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1442.Count Triplets That Can Form Two Arrays of Equal XOR/README_EN.md b/solution/1400-1499/1442.Count Triplets That Can Form Two Arrays of Equal XOR/README_EN.md index f83f446a4e4c4..c5481d9c55b9a 100644 --- a/solution/1400-1499/1442.Count Triplets That Can Form Two Arrays of Equal XOR/README_EN.md +++ b/solution/1400-1499/1442.Count Triplets That Can Form Two Arrays of Equal XOR/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countTriplets(int[] arr) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +112,6 @@ public: }; ``` -### **Go** - ```go func countTriplets(arr []int) int { n := len(arr) @@ -140,10 +134,6 @@ func countTriplets(arr []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/README.md b/solution/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/README.md index e2300f437da4e..9332688bafadc 100644 --- a/solution/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/README.md +++ b/solution/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/README.md @@ -53,16 +53,10 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS -### **Python3** - - - ```python class Solution: def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int: @@ -85,10 +79,6 @@ class Solution: return dfs(0, 0) ``` -### **Java** - - - ```java class Solution { public int minTime(int n, int[][] edges, List hasApple) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +135,6 @@ public: }; ``` -### **Go** - ```go func minTime(n int, edges [][]int, hasApple []bool) int { vis := make([]bool, n) @@ -177,10 +163,6 @@ func minTime(n int, edges [][]int, hasApple []bool) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/README_EN.md b/solution/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/README_EN.md index 75d671cf1bc6c..1f424a908cd3d 100644 --- a/solution/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/README_EN.md +++ b/solution/1400-1499/1443.Minimum Time to Collect All Apples in a Tree/README_EN.md @@ -45,12 +45,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python class Solution: def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int: @@ -73,8 +71,6 @@ class Solution: return dfs(0, 0) ``` -### **Java** - ```java class Solution { public int minTime(int n, int[][] edges, List hasApple) { @@ -106,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +127,6 @@ public: }; ``` -### **Go** - ```go func minTime(n int, edges [][]int, hasApple []bool) int { vis := make([]bool, n) @@ -163,10 +155,6 @@ func minTime(n int, edges [][]int, hasApple []bool) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1444.Number of Ways of Cutting a Pizza/README.md b/solution/1400-1499/1444.Number of Ways of Cutting a Pizza/README.md index 084049918f274..6188b3efef420 100644 --- a/solution/1400-1499/1444.Number of Ways of Cutting a Pizza/README.md +++ b/solution/1400-1499/1444.Number of Ways of Cutting a Pizza/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:二维前缀和 + 记忆化搜索** +### 方法一:二维前缀和 + 记忆化搜索 我们可以使用二维前缀和来快速计算出每个子矩形中苹果的数量,定义 $s[i][j]$ 表示矩形前 $i$ 行,前 $j$ 列的子矩形中苹果的数量,那么 $s[i][j]$ 可以由 $s[i-1][j]$, $s[i][j-1]$, $s[i-1][j-1]$ 三个子矩形的苹果数量求得,具体的计算方法如下: @@ -76,10 +74,6 @@ $$ -### **Python3** - - - ```python class Solution: def ways(self, pizza: List[str], k: int) -> int: @@ -105,10 +99,6 @@ class Solution: return dfs(0, 0, k - 1) ``` -### **Java** - - - ```java class Solution { private int m; @@ -154,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -195,8 +183,6 @@ public: }; ``` -### **Go** - ```go func ways(pizza []string, k int) int { const mod = 1e9 + 7 @@ -252,8 +238,6 @@ func ways(pizza []string, k int) int { } ``` -### **TypeScript** - ```ts function ways(pizza: string[], k: number): number { const mod = 1e9 + 7; @@ -291,10 +275,6 @@ function ways(pizza: string[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1444.Number of Ways of Cutting a Pizza/README_EN.md b/solution/1400-1499/1444.Number of Ways of Cutting a Pizza/README_EN.md index d868cf6f10a6d..3093092ae52b6 100644 --- a/solution/1400-1499/1444.Number of Ways of Cutting a Pizza/README_EN.md +++ b/solution/1400-1499/1444.Number of Ways of Cutting a Pizza/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return dfs(0, 0, k - 1) ``` -### **Java** - ```java class Solution { private int m; @@ -124,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -165,8 +161,6 @@ public: }; ``` -### **Go** - ```go func ways(pizza []string, k int) int { const mod = 1e9 + 7 @@ -222,8 +216,6 @@ func ways(pizza []string, k int) int { } ``` -### **TypeScript** - ```ts function ways(pizza: string[], k: number): number { const mod = 1e9 + 7; @@ -261,10 +253,6 @@ function ways(pizza: string[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1445.Apples & Oranges/README.md b/solution/1400-1499/1445.Apples & Oranges/README.md index 588352c42af30..618d63d04abbd 100644 --- a/solution/1400-1499/1445.Apples & Oranges/README.md +++ b/solution/1400-1499/1445.Apples & Oranges/README.md @@ -65,16 +65,12 @@ Sales 表: ## 解法 - - -**方法一:分组求和** +### 方法一:分组求和 我们可以将数据按照日期分组,然后用 `sum` 函数求出每天苹果和桔子的销售差异。如果是苹果,我们就用正数表示,如果是桔子,我们就用负数表示。最后我们按照日期排序即可。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -86,3 +82,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1400-1499/1445.Apples & Oranges/README_EN.md b/solution/1400-1499/1445.Apples & Oranges/README_EN.md index f4a386197b035..d3cde1e040e06 100644 --- a/solution/1400-1499/1445.Apples & Oranges/README_EN.md +++ b/solution/1400-1499/1445.Apples & Oranges/README_EN.md @@ -62,14 +62,12 @@ Day 2020-05-04, 15 apples and 16 oranges were sold (Difference 15 - 16 = -1). ## Solutions -**Solution 1: Group By + Sum** +### Solution 1: Group By + Sum We can group the data by date, and then use the `sum` function to calculate the difference in sales between apples and oranges for each day. If it is an apple, we represent it with a positive number, and if it is an orange, we represent it with a negative number. Finally, we sort the data by date. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -81,3 +79,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1400-1499/1446.Consecutive Characters/README.md b/solution/1400-1499/1446.Consecutive Characters/README.md index 9163e321460a1..1ff1ccdfdfa89 100644 --- a/solution/1400-1499/1446.Consecutive Characters/README.md +++ b/solution/1400-1499/1446.Consecutive Characters/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:遍历计数** +### 方法一:遍历计数 我们定义一个变量 $t$,表示当前连续字符的长度,初始时 $t=1$。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def maxPower(self, s: str) -> int: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxPower(String s) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +97,6 @@ public: }; ``` -### **Go** - ```go func maxPower(s string) int { ans, t := 1, 1 @@ -126,8 +112,6 @@ func maxPower(s string) int { } ``` -### **TypeScript** - ```ts function maxPower(s: string): number { let ans = 1; @@ -143,10 +127,6 @@ function maxPower(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1446.Consecutive Characters/README_EN.md b/solution/1400-1499/1446.Consecutive Characters/README_EN.md index ada56c190e9fd..0a5194a36d4dc 100644 --- a/solution/1400-1499/1446.Consecutive Characters/README_EN.md +++ b/solution/1400-1499/1446.Consecutive Characters/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxPower(String s) { @@ -70,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,8 +85,6 @@ public: }; ``` -### **Go** - ```go func maxPower(s string) int { ans, t := 1, 1 @@ -106,8 +100,6 @@ func maxPower(s string) int { } ``` -### **TypeScript** - ```ts function maxPower(s: string): number { let ans = 1; @@ -123,10 +115,6 @@ function maxPower(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1447.Simplified Fractions/README.md b/solution/1400-1499/1447.Simplified Fractions/README.md index 28d6ba270e5f4..948fff076f982 100644 --- a/solution/1400-1499/1447.Simplified Fractions/README.md +++ b/solution/1400-1499/1447.Simplified Fractions/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:枚举分子分母** +### 方法一:枚举分子分母 我们可以枚举分子 $i$ 和分母 $j$,其中 $1 \leq i < j \leq n$,并判断 $i$ 和 $j$ 的最大公约数是否为 $1$,如果是则 $i/j$ 是一个最简分数。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def simplifiedFractions(self, n: int) -> List[str]: @@ -69,10 +63,6 @@ class Solution: ] ``` -### **Java** - - - ```java class Solution { public List simplifiedFractions(int n) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +100,6 @@ public: }; ``` -### **Go** - ```go func simplifiedFractions(n int) (ans []string) { for i := 1; i < n; i++ { @@ -134,8 +120,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function simplifiedFractions(n: number): string[] { const ans: string[] = []; @@ -154,8 +138,6 @@ function gcd(a: number, b: number): number { } ``` -### **Rust** - ```rust impl Solution { fn gcd(a: i32, b: i32) -> i32 { @@ -179,10 +161,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1447.Simplified Fractions/README_EN.md b/solution/1400-1499/1447.Simplified Fractions/README_EN.md index 5be8ef39ed1c4..60446f58879f2 100644 --- a/solution/1400-1499/1447.Simplified Fractions/README_EN.md +++ b/solution/1400-1499/1447.Simplified Fractions/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: ] ``` -### **Java** - ```java class Solution { public List simplifiedFractions(int n) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +91,6 @@ public: }; ``` -### **Go** - ```go func simplifiedFractions(n int) (ans []string) { for i := 1; i < n; i++ { @@ -117,8 +111,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function simplifiedFractions(n: number): string[] { const ans: string[] = []; @@ -137,8 +129,6 @@ function gcd(a: number, b: number): number { } ``` -### **Rust** - ```rust impl Solution { fn gcd(a: i32, b: i32) -> i32 { @@ -162,10 +152,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README.md b/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README.md index d891f510110f9..1be36d3449e1e 100644 --- a/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README.md +++ b/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们设计一个函数 $dfs(root, mx)$,表示从当前节点 $root$ 开始搜索好节点,其中 $mx$ 表示从根节点到当前节点的路径(不包括当前节点)上的最大值。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -97,10 +91,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -174,8 +162,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -203,8 +189,6 @@ func goodNodes(root *TreeNode) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -238,10 +222,6 @@ function goodNodes(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md b/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md index 575f9bb2845bf..33176da780f1e 100644 --- a/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md +++ b/solution/1400-1499/1448.Count Good Nodes in Binary Tree/README_EN.md @@ -48,9 +48,9 @@ Node 3 -> (3,1,3) is the maximum value in the path. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -76,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -116,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -151,8 +147,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -180,8 +174,6 @@ func goodNodes(root *TreeNode) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -215,10 +207,6 @@ function goodNodes(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/README.md b/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/README.md index 24cec9b79d38d..885be5f863266 100644 --- a/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/README.md +++ b/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/README.md @@ -73,9 +73,7 @@ ## 解法 - - -**方法一:动态规划(背包问题)** +### 方法一:动态规划(背包问题) 我们定义 $f[i][j]$ 表示使用前 $i$ 个数位,花费恰好为 $j$ 的情况下,能够得到的最大位数。初始时,$f[0][0]=0$,其余为 $-\infty$。 @@ -93,10 +91,6 @@ -### **Python3** - - - ```python class Solution: def largestNumber(self, cost: List[int], target: int) -> str: @@ -124,10 +118,6 @@ class Solution: return "".join(ans) ``` -### **Java** - - - ```java class Solution { public String largestNumber(int[] cost, int target) { @@ -167,8 +157,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -206,8 +194,6 @@ public: }; ``` -### **Go** - ```go func largestNumber(cost []int, target int) string { const inf = 1 << 30 @@ -249,8 +235,6 @@ func largestNumber(cost []int, target int) string { } ``` -### **TypeScript** - ```ts function largestNumber(cost: number[], target: number): string { const inf = 1 << 30; @@ -289,10 +273,6 @@ function largestNumber(cost: number[], target: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/README_EN.md b/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/README_EN.md index cf23fb361ddc8..c9f0fc9ddcde5 100644 --- a/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/README_EN.md +++ b/solution/1400-1499/1449.Form Largest Integer With Digits That Add up to Target/README_EN.md @@ -59,9 +59,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -90,8 +90,6 @@ class Solution: return "".join(ans) ``` -### **Java** - ```java class Solution { public String largestNumber(int[] cost, int target) { @@ -131,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +166,6 @@ public: }; ``` -### **Go** - ```go func largestNumber(cost []int, target int) string { const inf = 1 << 30 @@ -213,8 +207,6 @@ func largestNumber(cost []int, target int) string { } ``` -### **TypeScript** - ```ts function largestNumber(cost: number[], target: number): string { const inf = 1 << 30; @@ -253,10 +245,6 @@ function largestNumber(cost: number[], target: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/README.md b/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/README.md index 64ffb61995bd2..f2ebeb1e4d7cd 100644 --- a/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/README.md +++ b/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/README.md @@ -62,15 +62,104 @@ ## 解法 - - -**方法一:遍历计数** +### 方法一:遍历计数 同时遍历 $startTime$ 和 $endTime$,统计正在做作业的学生人数。 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是 $startTime$ 和 $endTime$ 的长度。 -**方法二:差分数组** + + +```python +class Solution: + def busyStudent( + self, startTime: List[int], endTime: List[int], queryTime: int + ) -> int: + return sum(a <= queryTime <= b for a, b in zip(startTime, endTime)) +``` + +```java +class Solution { + public int busyStudent(int[] startTime, int[] endTime, int queryTime) { + int ans = 0; + for (int i = 0; i < startTime.length; ++i) { + if (startTime[i] <= queryTime && queryTime <= endTime[i]) { + ++ans; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int busyStudent(vector& startTime, vector& endTime, int queryTime) { + int ans = 0; + for (int i = 0; i < startTime.size(); ++i) { + ans += startTime[i] <= queryTime && queryTime <= endTime[i]; + } + return ans; + } +}; +``` + +```go +func busyStudent(startTime []int, endTime []int, queryTime int) int { + ans := 0 + for i, a := range startTime { + b := endTime[i] + if a <= queryTime && queryTime <= b { + ans++ + } + } + return ans +} +``` + +```ts +function busyStudent(startTime: number[], endTime: number[], queryTime: number): number { + const n = startTime.length; + let res = 0; + for (let i = 0; i < n; i++) { + if (startTime[i] <= queryTime && endTime[i] >= queryTime) { + res++; + } + } + return res; +} +``` + +```rust +impl Solution { + pub fn busy_student(start_time: Vec, end_time: Vec, query_time: i32) -> i32 { + let mut res = 0; + for i in 0..start_time.len() { + if start_time[i] <= query_time && end_time[i] >= query_time { + res += 1; + } + } + res + } +} +``` + +```c +int busyStudent(int* startTime, int startTimeSize, int* endTime, int endTimeSize, int queryTime) { + int res = 0; + for (int i = 0; i < startTimeSize; i++) { + if (startTime[i] <= queryTime && endTime[i] >= queryTime) { + res++; + } + } + return res; +} +``` + + + +### 方法二:差分数组 差分数组可以 $O(1)$ 时间处理区间加减操作。例如,对区间 $[l, r]$ 中的每个数加上 $c$。 @@ -96,18 +185,6 @@ $$ -### **Python3** - - - -```python -class Solution: - def busyStudent( - self, startTime: List[int], endTime: List[int], queryTime: int - ) -> int: - return sum(a <= queryTime <= b for a, b in zip(startTime, endTime)) -``` - ```python class Solution: def busyStudent( @@ -120,24 +197,6 @@ class Solution: return sum(c[: queryTime + 1]) ``` -### **Java** - - - -```java -class Solution { - public int busyStudent(int[] startTime, int[] endTime, int queryTime) { - int ans = 0; - for (int i = 0; i < startTime.length; ++i) { - if (startTime[i] <= queryTime && queryTime <= endTime[i]) { - ++ans; - } - } - return ans; - } -} -``` - ```java class Solution { public int busyStudent(int[] startTime, int[] endTime, int queryTime) { @@ -155,21 +214,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int busyStudent(vector& startTime, vector& endTime, int queryTime) { - int ans = 0; - for (int i = 0; i < startTime.size(); ++i) { - ans += startTime[i] <= queryTime && queryTime <= endTime[i]; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -188,21 +232,6 @@ public: }; ``` -### **Go** - -```go -func busyStudent(startTime []int, endTime []int, queryTime int) int { - ans := 0 - for i, a := range startTime { - b := endTime[i] - if a <= queryTime && queryTime <= b { - ans++ - } - } - return ans -} -``` - ```go func busyStudent(startTime []int, endTime []int, queryTime int) int { c := make([]int, 1010) @@ -219,55 +248,6 @@ func busyStudent(startTime []int, endTime []int, queryTime int) int { } ``` -### **C** - -```c -int busyStudent(int* startTime, int startTimeSize, int* endTime, int endTimeSize, int queryTime) { - int res = 0; - for (int i = 0; i < startTimeSize; i++) { - if (startTime[i] <= queryTime && endTime[i] >= queryTime) { - res++; - } - } - return res; -} -``` - -### **TypeScript** - -```ts -function busyStudent(startTime: number[], endTime: number[], queryTime: number): number { - const n = startTime.length; - let res = 0; - for (let i = 0; i < n; i++) { - if (startTime[i] <= queryTime && endTime[i] >= queryTime) { - res++; - } - } - return res; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn busy_student(start_time: Vec, end_time: Vec, query_time: i32) -> i32 { - let mut res = 0; - for i in 0..start_time.len() { - if start_time[i] <= query_time && end_time[i] >= query_time { - res += 1; - } - } - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/README_EN.md b/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/README_EN.md index ee591cfb191c4..e36b97c35dba9 100644 --- a/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/README_EN.md +++ b/solution/1400-1499/1450.Number of Students Doing Homework at a Given Time/README_EN.md @@ -42,9 +42,9 @@ The third student started doing homework at time 3 and finished at time 7 and wa ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,20 +54,6 @@ class Solution: return sum(a <= queryTime <= b for a, b in zip(startTime, endTime)) ``` -```python -class Solution: - def busyStudent( - self, startTime: List[int], endTime: List[int], queryTime: int - ) -> int: - c = [0] * 1010 - for a, b in zip(startTime, endTime): - c[a] += 1 - c[b + 1] -= 1 - return sum(c[: queryTime + 1]) -``` - -### **Java** - ```java class Solution { public int busyStudent(int[] startTime, int[] endTime, int queryTime) { @@ -82,25 +68,6 @@ class Solution { } ``` -```java -class Solution { - public int busyStudent(int[] startTime, int[] endTime, int queryTime) { - int[] c = new int[1010]; - for (int i = 0; i < startTime.length; ++i) { - c[startTime[i]]++; - c[endTime[i] + 1]--; - } - int ans = 0; - for (int i = 0; i <= queryTime; ++i) { - ans += c[i]; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -114,26 +81,6 @@ public: }; ``` -```cpp -class Solution { -public: - int busyStudent(vector& startTime, vector& endTime, int queryTime) { - vector c(1010); - for (int i = 0; i < startTime.size(); ++i) { - c[startTime[i]]++; - c[endTime[i] + 1]--; - } - int ans = 0; - for (int i = 0; i <= queryTime; ++i) { - ans += c[i]; - } - return ans; - } -}; -``` - -### **Go** - ```go func busyStudent(startTime []int, endTime []int, queryTime int) int { ans := 0 @@ -147,38 +94,6 @@ func busyStudent(startTime []int, endTime []int, queryTime int) int { } ``` -```go -func busyStudent(startTime []int, endTime []int, queryTime int) int { - c := make([]int, 1010) - for i, a := range startTime { - b := endTime[i] - c[a]++ - c[b+1]-- - } - ans := 0 - for i := 0; i <= queryTime; i++ { - ans += c[i] - } - return ans -} -``` - -### **C** - -```c -int busyStudent(int* startTime, int startTimeSize, int* endTime, int endTimeSize, int queryTime) { - int res = 0; - for (int i = 0; i < startTimeSize; i++) { - if (startTime[i] <= queryTime && endTime[i] >= queryTime) { - res++; - } - } - return res; -} -``` - -### **TypeScript** - ```ts function busyStudent(startTime: number[], endTime: number[], queryTime: number): number { const n = startTime.length; @@ -192,8 +107,6 @@ function busyStudent(startTime: number[], endTime: number[], queryTime: number): } ``` -### **Rust** - ```rust impl Solution { pub fn busy_student(start_time: Vec, end_time: Vec, query_time: i32) -> i32 { @@ -208,10 +121,87 @@ impl Solution { } ``` -### **...** +```c +int busyStudent(int* startTime, int startTimeSize, int* endTime, int endTimeSize, int queryTime) { + int res = 0; + for (int i = 0; i < startTimeSize; i++) { + if (startTime[i] <= queryTime && endTime[i] >= queryTime) { + res++; + } + } + return res; +} +``` + + + +### Solution 2 + + +```python +class Solution: + def busyStudent( + self, startTime: List[int], endTime: List[int], queryTime: int + ) -> int: + c = [0] * 1010 + for a, b in zip(startTime, endTime): + c[a] += 1 + c[b + 1] -= 1 + return sum(c[: queryTime + 1]) ``` +```java +class Solution { + public int busyStudent(int[] startTime, int[] endTime, int queryTime) { + int[] c = new int[1010]; + for (int i = 0; i < startTime.length; ++i) { + c[startTime[i]]++; + c[endTime[i] + 1]--; + } + int ans = 0; + for (int i = 0; i <= queryTime; ++i) { + ans += c[i]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int busyStudent(vector& startTime, vector& endTime, int queryTime) { + vector c(1010); + for (int i = 0; i < startTime.size(); ++i) { + c[startTime[i]]++; + c[endTime[i] + 1]--; + } + int ans = 0; + for (int i = 0; i <= queryTime; ++i) { + ans += c[i]; + } + return ans; + } +}; +``` + +```go +func busyStudent(startTime []int, endTime []int, queryTime int) int { + c := make([]int, 1010) + for i, a := range startTime { + b := endTime[i] + c[a]++ + c[b+1]-- + } + ans := 0 + for i := 0; i <= queryTime; i++ { + ans += c[i] + } + return ans +} ``` + + diff --git a/solution/1400-1499/1451.Rearrange Words in a Sentence/README.md b/solution/1400-1499/1451.Rearrange Words in a Sentence/README.md index 4b6664a4c8c78..73cab0d2c1014 100644 --- a/solution/1400-1499/1451.Rearrange Words in a Sentence/README.md +++ b/solution/1400-1499/1451.Rearrange Words in a Sentence/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 将 `text` 按空格切分为字符串数组 `words`,并将 `words[0]` 转为小写。然后对 `words` 进行排序(这里需要确保长度相同的情况下,相对顺序保持不变,因此是一种稳定排序)。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def arrangeWords(self, text: str) -> str: @@ -82,10 +76,6 @@ class Solution: return " ".join(words) ``` -### **Java** - - - ```java class Solution { public String arrangeWords(String text) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func arrangeWords(text string) string { words := strings.Split(text, " ") @@ -137,33 +123,6 @@ func arrangeWords(text string) string { } ``` -### **PHP** - -```php -class Solution { - /** - * @param String $text - * @return String - */ - function arrangeWords($text) { - $text = lcfirst($text); - $arr = explode(' ', $text); - for ($i = 0; $i < count($arr); $i++) { - $hashtable[$i] = strlen($arr[$i]); - } - asort($hashtable); - $key = array_keys($hashtable); - $rs = []; - for ($j = 0; $j < count($key); $j++) { - array_push($rs, $arr[$key[$j]]); - } - return ucfirst(implode(' ', $rs)); - } -} -``` - -### **TypeScript** - ```ts function arrangeWords(text: string): string { let words: string[] = text.split(' '); @@ -174,8 +133,6 @@ function arrangeWords(text: string): string { } ``` -### **JavaScript** - ```js /** * @param {string} text @@ -190,10 +147,29 @@ var arrangeWords = function (text) { }; ``` -### **...** - -``` - +```php +class Solution { + /** + * @param String $text + * @return String + */ + function arrangeWords($text) { + $text = lcfirst($text); + $arr = explode(' ', $text); + for ($i = 0; $i < count($arr); $i++) { + $hashtable[$i] = strlen($arr[$i]); + } + asort($hashtable); + $key = array_keys($hashtable); + $rs = []; + for ($j = 0; $j < count($key); $j++) { + array_push($rs, $arr[$key[$j]]); + } + return ucfirst(implode(' ', $rs)); + } +} ``` + + diff --git a/solution/1400-1499/1451.Rearrange Words in a Sentence/README_EN.md b/solution/1400-1499/1451.Rearrange Words in a Sentence/README_EN.md index 52d15f69c6599..3dadf136588d5 100644 --- a/solution/1400-1499/1451.Rearrange Words in a Sentence/README_EN.md +++ b/solution/1400-1499/1451.Rearrange Words in a Sentence/README_EN.md @@ -55,9 +55,9 @@ Output is ordered by length and the new first word starts with capital letter. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return " ".join(words) ``` -### **Java** - ```java class Solution { public String arrangeWords(String text) { @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +106,6 @@ public: }; ``` -### **Go** - ```go func arrangeWords(text string) string { words := strings.Split(text, " ") @@ -122,33 +116,6 @@ func arrangeWords(text string) string { } ``` -### **PHP** - -```php -class Solution { - /** - * @param String $text - * @return String - */ - function arrangeWords($text) { - $text = lcfirst($text); - $arr = explode(' ', $text); - for ($i = 0; $i < count($arr); $i++) { - $hashtable[$i] = strlen($arr[$i]); - } - asort($hashtable); - $key = array_keys($hashtable); - $rs = []; - for ($j = 0; $j < count($key); $j++) { - array_push($rs, $arr[$key[$j]]); - } - return ucfirst(implode(' ', $rs)); - } -} -``` - -### **TypeScript** - ```ts function arrangeWords(text: string): string { let words: string[] = text.split(' '); @@ -159,8 +126,6 @@ function arrangeWords(text: string): string { } ``` -### **JavaScript** - ```js /** * @param {string} text @@ -175,10 +140,29 @@ var arrangeWords = function (text) { }; ``` -### **...** - -``` - +```php +class Solution { + /** + * @param String $text + * @return String + */ + function arrangeWords($text) { + $text = lcfirst($text); + $arr = explode(' ', $text); + for ($i = 0; $i < count($arr); $i++) { + $hashtable[$i] = strlen($arr[$i]); + } + asort($hashtable); + $key = array_keys($hashtable); + $rs = []; + for ($j = 0; $j < count($key); $j++) { + array_push($rs, $arr[$key[$j]]); + } + return ucfirst(implode(' ', $rs)); + } +} ``` + + diff --git a/solution/1400-1499/1452.People Whose List of Favorite Companies Is Not a Subset of Another List/README.md b/solution/1400-1499/1452.People Whose List of Favorite Companies Is Not a Subset of Another List/README.md index 6cff88de2d5ab..e92902f2523cb 100644 --- a/solution/1400-1499/1452.People Whose List of Favorite Companies Is Not a Subset of Another List/README.md +++ b/solution/1400-1499/1452.People Whose List of Favorite Companies Is Not a Subset of Another List/README.md @@ -50,9 +50,7 @@ favoriteCompanies[3]=["google"] 是 favoriteCompanies[0]=["leetco ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 将每个 `company` 字符串列表都转换为一个整数类型的集合。然后遍历每个集合,判断其是否是其他集合的子集,如果不是,则将其下标加入结果集。 @@ -60,10 +58,6 @@ favoriteCompanies[3]=["google"] 是 favoriteCompanies[0]=["leetco -### **Python3** - - - ```python class Solution: def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]: @@ -90,10 +84,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List peopleIndexes(List> favoriteCompanies) { @@ -134,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -184,8 +172,6 @@ public: }; ``` -### **Go** - ```go func peopleIndexes(favoriteCompanies [][]string) []int { d := map[string]int{} @@ -232,10 +218,6 @@ func peopleIndexes(favoriteCompanies [][]string) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1452.People Whose List of Favorite Companies Is Not a Subset of Another List/README_EN.md b/solution/1400-1499/1452.People Whose List of Favorite Companies Is Not a Subset of Another List/README_EN.md index a24f9dc6e6456..0d621dcf23ea8 100644 --- a/solution/1400-1499/1452.People Whose List of Favorite Companies Is Not a Subset of Another List/README_EN.md +++ b/solution/1400-1499/1452.People Whose List of Favorite Companies Is Not a Subset of Another List/README_EN.md @@ -49,9 +49,9 @@ Other lists of favorite companies are not a subset of another list, therefore, t ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,8 +79,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List peopleIndexes(List> favoriteCompanies) { @@ -121,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +167,6 @@ public: }; ``` -### **Go** - ```go func peopleIndexes(favoriteCompanies [][]string) []int { d := map[string]int{} @@ -219,10 +213,6 @@ func peopleIndexes(favoriteCompanies [][]string) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/README.md b/solution/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/README.md index efaec4ff72b7c..af512949b34c0 100644 --- a/solution/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/README.md +++ b/solution/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/README.md @@ -44,30 +44,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/README_EN.md b/solution/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/README_EN.md index 025cdb4f0e07b..da05ea5664910 100644 --- a/solution/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/README_EN.md +++ b/solution/1400-1499/1453.Maximum Number of Darts Inside of a Circular Dartboard/README_EN.md @@ -40,24 +40,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1400-1499/1454.Active Users/README.md b/solution/1400-1499/1454.Active Users/README.md index 07c3993c990d0..922bd74c7ce67 100644 --- a/solution/1400-1499/1454.Active Users/README.md +++ b/solution/1400-1499/1454.Active Users/README.md @@ -90,12 +90,10 @@ id = 7 的用户 Jonathon 在不同的 6 天内登录了 7 次, , 6 天中有 5 ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH t AS @@ -113,3 +111,5 @@ WHERE cnt=5; ``` + + diff --git a/solution/1400-1499/1454.Active Users/README_EN.md b/solution/1400-1499/1454.Active Users/README_EN.md index 6a758c69c7314..74578891e296f 100644 --- a/solution/1400-1499/1454.Active Users/README_EN.md +++ b/solution/1400-1499/1454.Active Users/README_EN.md @@ -84,9 +84,9 @@ User Jonathan with id = 7 logged in 7 times in 6 different days, five of them we ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -105,3 +105,5 @@ WHERE cnt=5; ``` + + diff --git a/solution/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/README.md b/solution/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/README.md index 5adeed8a31c77..3d889382c754f 100644 --- a/solution/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/README.md +++ b/solution/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:字符串分割** +### 方法一:字符串分割 将 $sentence$ 按空格分割为 $words$,然后遍历 $words$,检查 $words[i]$ 是否是 $searchWord$ 的前缀,是则返回 $i+1$。若遍历结束,所有单词都不满足,返回 $-1$。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: @@ -74,10 +68,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int isPrefixOfWord(String sentence, String searchWord) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +98,6 @@ public: }; ``` -### **Go** - ```go func isPrefixOfWord(sentence string, searchWord string) int { for i, s := range strings.Split(sentence, " ") { @@ -123,8 +109,6 @@ func isPrefixOfWord(sentence string, searchWord string) int { } ``` -### **TypeScript** - ```ts function isPrefixOfWord(sentence: string, searchWord: string): number { const ss = sentence.split(/\s/); @@ -138,8 +122,6 @@ function isPrefixOfWord(sentence: string, searchWord: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn is_prefix_of_word(sentence: String, search_word: String) -> i32 { @@ -154,8 +136,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -175,10 +155,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/README_EN.md b/solution/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/README_EN.md index d643c478aefc5..81b335e49cd7d 100644 --- a/solution/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/README_EN.md +++ b/solution/1400-1499/1455.Check If a Word Occurs As a Prefix of Any Word in a Sentence/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int isPrefixOfWord(String sentence, String searchWord) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +90,6 @@ public: }; ``` -### **Go** - ```go func isPrefixOfWord(sentence string, searchWord string) int { for i, s := range strings.Split(sentence, " ") { @@ -107,8 +101,6 @@ func isPrefixOfWord(sentence string, searchWord string) int { } ``` -### **TypeScript** - ```ts function isPrefixOfWord(sentence: string, searchWord: string): number { const ss = sentence.split(/\s/); @@ -122,8 +114,6 @@ function isPrefixOfWord(sentence: string, searchWord: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn is_prefix_of_word(sentence: String, search_word: String) -> i32 { @@ -138,8 +128,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -159,10 +147,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/README.md b/solution/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/README.md index d5e40c15b932e..95f0cb7da506e 100644 --- a/solution/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/README.md +++ b/solution/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 找出所有窗口为 $k$ 中的元音字母数目,并记录最大值。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def maxVowels(self, s: str, k: int) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxVowels(String s, int k) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func maxVowels(s string, k int) int { isVowel := func(c byte) bool { @@ -169,8 +155,6 @@ func maxVowels(s string, k int) int { } ``` -### **TypeScript** - ```ts function maxVowels(s: string, k: number): number { function isVowel(c) { @@ -196,8 +180,6 @@ function maxVowels(s: string, k: number): number { } ``` -### **PHP** - ```php class Solution { /** @@ -231,10 +213,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/README_EN.md b/solution/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/README_EN.md index 68825821c3dd8..c286fe14ce04e 100644 --- a/solution/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/README_EN.md +++ b/solution/1400-1499/1456.Maximum Number of Vowels in a Substring of Given Length/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxVowels(String s, int k) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +110,6 @@ public: }; ``` -### **Go** - ```go func maxVowels(s string, k int) int { isVowel := func(c byte) bool { @@ -141,8 +135,6 @@ func maxVowels(s string, k int) int { } ``` -### **TypeScript** - ```ts function maxVowels(s: string, k: number): number { function isVowel(c) { @@ -168,8 +160,6 @@ function maxVowels(s: string, k: number): number { } ``` -### **PHP** - ```php class Solution { /** @@ -203,10 +193,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/README.md b/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/README.md index 7af12fc988c8f..24155476524f4 100644 --- a/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/README.md +++ b/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:DFS + 位运算** +### 方法一:DFS + 位运算 一条路径是伪回文路径,当且仅当该路径经过的节点值的出现次数为奇数的数字为 $0$ 个或 $1$ 个。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -100,10 +94,6 @@ class Solution: return dfs(root, 0) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -138,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -170,8 +158,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -200,8 +186,6 @@ func pseudoPalindromicPaths(root *TreeNode) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -232,8 +216,6 @@ function pseudoPalindromicPaths(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -280,10 +262,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/README_EN.md b/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/README_EN.md index aa74b561c8baa..4ab2ea6301886 100644 --- a/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/README_EN.md +++ b/solution/1400-1499/1457.Pseudo-Palindromic Paths in a Binary Tree/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: DFS + Bit Manipulation** +### Solution 1: DFS + Bit Manipulation A path is a pseudo-palindromic path if and only if the number of nodes with odd occurrences in the path is $0$ or $1$. @@ -68,8 +68,6 @@ 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: @@ -90,8 +88,6 @@ class Solution: return dfs(root, 0) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -126,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -158,8 +152,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -188,8 +180,6 @@ func pseudoPalindromicPaths(root *TreeNode) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -220,8 +210,6 @@ function pseudoPalindromicPaths(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -268,10 +256,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1458.Max Dot Product of Two Subsequences/README.md b/solution/1400-1499/1458.Max Dot Product of Two Subsequences/README.md index e4ea3eea4ec7c..a6aeca78f743e 100644 --- a/solution/1400-1499/1458.Max Dot Product of Two Subsequences/README.md +++ b/solution/1400-1499/1458.Max Dot Product of Two Subsequences/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 定义 $dp[i][j]$ 表示 $nums1$ 前 $i$ 个元素和 $nums2$ 前 $j$ 个元素得到的最大点积。 @@ -79,10 +77,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int: @@ -95,10 +89,6 @@ class Solution: return dp[-1][-1] ``` -### **Java** - - - ```java class Solution { public int maxDotProduct(int[] nums1, int[] nums2) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,33 +127,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn max_dot_product(nums1: Vec, nums2: Vec) -> i32 { - let n = nums1.len(); - let m = nums2.len(); - let mut dp = vec![vec![i32::MIN; m + 1]; n + 1]; - - // Begin the actual dp process - for i in 1..=n { - for j in 1..=m { - dp[i][j] = std::cmp::max( - std::cmp::max(dp[i - 1][j], dp[i][j - 1]), - std::cmp::max(dp[i - 1][j - 1], 0) + nums1[i - 1] * nums2[j - 1] - ); - } - } - - dp[n][m] - } -} -``` - -### **Go** - ```go func maxDotProduct(nums1 []int, nums2 []int) int { m, n := len(nums1), len(nums2) @@ -187,10 +148,29 @@ func maxDotProduct(nums1 []int, nums2 []int) int { } ``` -### **...** +```rust +impl Solution { + #[allow(dead_code)] + pub fn max_dot_product(nums1: Vec, nums2: Vec) -> i32 { + let n = nums1.len(); + let m = nums2.len(); + let mut dp = vec![vec![i32::MIN; m + 1]; n + 1]; -``` + // Begin the actual dp process + for i in 1..=n { + for j in 1..=m { + dp[i][j] = std::cmp::max( + std::cmp::max(dp[i - 1][j], dp[i][j - 1]), + std::cmp::max(dp[i - 1][j - 1], 0) + nums1[i - 1] * nums2[j - 1] + ); + } + } + dp[n][m] + } +} ``` + + diff --git a/solution/1400-1499/1458.Max Dot Product of Two Subsequences/README_EN.md b/solution/1400-1499/1458.Max Dot Product of Two Subsequences/README_EN.md index 92b3422678131..486fea5e4da79 100644 --- a/solution/1400-1499/1458.Max Dot Product of Two Subsequences/README_EN.md +++ b/solution/1400-1499/1458.Max Dot Product of Two Subsequences/README_EN.md @@ -45,12 +45,10 @@ Their dot product is -1. ## Solutions -Dynamic Programming. +### Solution 1 -### **Python3** - ```python class Solution: def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int: @@ -63,8 +61,6 @@ class Solution: return dp[-1][-1] ``` -### **Java** - ```java class Solution { public int maxDotProduct(int[] nums1, int[] nums2) { @@ -85,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,33 +99,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn max_dot_product(nums1: Vec, nums2: Vec) -> i32 { - let n = nums1.len(); - let m = nums2.len(); - let mut dp = vec![vec![i32::MIN; m + 1]; n + 1]; - - // Begin the actual dp process - for i in 1..=n { - for j in 1..=m { - dp[i][j] = std::cmp::max( - std::cmp::max(dp[i - 1][j], dp[i][j - 1]), - std::cmp::max(dp[i - 1][j - 1], 0) + nums1[i - 1] * nums2[j - 1] - ); - } - } - - dp[n][m] - } -} -``` - -### **Go** - ```go func maxDotProduct(nums1 []int, nums2 []int) int { m, n := len(nums1), len(nums2) @@ -153,10 +120,29 @@ func maxDotProduct(nums1 []int, nums2 []int) int { } ``` -### **...** +```rust +impl Solution { + #[allow(dead_code)] + pub fn max_dot_product(nums1: Vec, nums2: Vec) -> i32 { + let n = nums1.len(); + let m = nums2.len(); + let mut dp = vec![vec![i32::MIN; m + 1]; n + 1]; -``` + // Begin the actual dp process + for i in 1..=n { + for j in 1..=m { + dp[i][j] = std::cmp::max( + std::cmp::max(dp[i - 1][j], dp[i][j - 1]), + std::cmp::max(dp[i - 1][j - 1], 0) + nums1[i - 1] * nums2[j - 1] + ); + } + } + dp[n][m] + } +} ``` + + diff --git a/solution/1400-1499/1459.Rectangles Area/README.md b/solution/1400-1499/1459.Rectangles Area/README.md index b0e738205b308..3df34cb3b1cc4 100644 --- a/solution/1400-1499/1459.Rectangles Area/README.md +++ b/solution/1400-1499/1459.Rectangles Area/README.md @@ -65,12 +65,10 @@ p1 = 1 且 p2 = 3 时, 是不可能为矩形的, 面积等于 0 ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -85,3 +83,5 @@ ORDER BY area DESC, p1, p2; ``` + + diff --git a/solution/1400-1499/1459.Rectangles Area/README_EN.md b/solution/1400-1499/1459.Rectangles Area/README_EN.md index 30a490b2e2e12..d73038d934b70 100644 --- a/solution/1400-1499/1459.Rectangles Area/README_EN.md +++ b/solution/1400-1499/1459.Rectangles Area/README_EN.md @@ -60,9 +60,9 @@ Note that the rectangle formed by p1 = 1 and p2 = 3 is invalid because the area ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -78,3 +78,5 @@ ORDER BY area DESC, p1, p2; ``` + + diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/README.md b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/README.md index 85fa950d34063..d768d5e800d55 100644 --- a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/README.md +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/README.md @@ -53,32 +53,14 @@ ## 解法 - - -**前言** - -由于我们可以对 $arr$ 任意非空子数组进行翻转,也就意味着我们可以交换任意两个相邻元素,使得数组按特定的一种顺序排列。 - -因此,题目转换为:判断一个数组是否是另一个数组的排列。 - -**方法一:排序** +### 方法一:排序 分别对数组 $arr$ 和 $target$ 排序,然后比较两数组对应位置的元素是否相等。相等则满足条件。 时间复杂度 $O(nlogn)$,空间复杂度 $O(logn)$。其中 $n$ 是数组 $arr$ 的长度,快排的平均递归深度为 $O(logn)$。 -**方法二:数组/哈希表** - -由于两数组的数据范围都是 $1 \leq x \leq 1000$,因此我们可以使用数组或哈希表来记录每个数字出现的次数。 - -时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 是数组 $arr$ 的长度,而 $C$ 是数组 $arr$ 元素的值域大小。 - -### **Python3** - - - ```python class Solution: def canBeEqual(self, target: List[int], arr: List[int]) -> bool: @@ -87,26 +69,6 @@ class Solution: return target == arr ``` -```python -class Solution: - def canBeEqual(self, target: List[int], arr: List[int]) -> bool: - return Counter(target) == Counter(arr) -``` - -```python -class Solution: - def canBeEqual(self, target: List[int], arr: List[int]) -> bool: - cnt = [0] * 1001 - for a, b in zip(target, arr): - cnt[a] += 1 - cnt[b] -= 1 - return all(v == 0 for v in cnt) -``` - -### **Java** - - - ```java class Solution { public boolean canBeEqual(int[] target, int[] arr) { @@ -117,41 +79,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canBeEqual(int[] target, int[] arr) { - int[] cnt1 = new int[1001]; - int[] cnt2 = new int[1001]; - for (int v : target) { - ++cnt1[v]; - } - for (int v : arr) { - ++cnt2[v]; - } - return Arrays.equals(cnt1, cnt2); - } -} -``` - -```java -class Solution { - public boolean canBeEqual(int[] target, int[] arr) { - int[] cnt = new int[1001]; - for (int v : target) { - ++cnt[v]; - } - for (int v : arr) { - if (--cnt[v] < 0) { - return false; - } - } - return true; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -163,34 +90,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool canBeEqual(vector& target, vector& arr) { - vector cnt1(1001); - vector cnt2(1001); - for (int& v : target) ++cnt1[v]; - for (int& v : arr) ++cnt2[v]; - return cnt1 == cnt2; - } -}; -``` - -```cpp -class Solution { -public: - bool canBeEqual(vector& target, vector& arr) { - vector cnt(1001); - for (int& v : target) ++cnt[v]; - for (int& v : arr) - if (--cnt[v] < 0) return false; - return true; - } -}; -``` - -### **Go** - ```go func canBeEqual(target []int, arr []int) bool { sort.Ints(target) @@ -204,42 +103,44 @@ func canBeEqual(target []int, arr []int) bool { } ``` -```go -func canBeEqual(target []int, arr []int) bool { - cnt1 := make([]int, 1001) - cnt2 := make([]int, 1001) - for _, v := range target { - cnt1[v]++ - } - for _, v := range arr { - cnt2[v]++ - } - for i, v := range cnt1 { - if v != cnt2[i] { - return false - } - } - return true +```ts +function canBeEqual(target: number[], arr: number[]): boolean { + target.sort((a, b) => a - b); + arr.sort((a, b) => a - b); + const n = arr.length; + for (let i = 0; i < n; i++) { + if (target[i] !== arr[i]) { + return false; + } + } + return true; } ``` -```go -func canBeEqual(target []int, arr []int) bool { - cnt := make([]int, 1001) - for _, v := range target { - cnt[v]++ - } - for _, v := range arr { - cnt[v]-- - if cnt[v] < 0 { - return false - } - } - return true +```rust +impl Solution { + pub fn can_be_equal(mut target: Vec, mut arr: Vec) -> bool { + target.sort(); + arr.sort(); + target == arr + } } ``` -### **C** +```php +class Solution { + /** + * @param Integer[] $target + * @param Integer[] $arr + * @return Boolean + */ + function canBeEqual($target, $arr) { + sort($target); + sort($arr); + return $target === $arr; + } +} +``` ```c bool canBeEqual(int* target, int targetSize, int* arr, int arrSize) { @@ -257,19 +158,67 @@ bool canBeEqual(int* target, int targetSize, int* arr, int arrSize) { } ``` -### **TypeScript** + -```ts -function canBeEqual(target: number[], arr: number[]): boolean { - target.sort((a, b) => a - b); - arr.sort((a, b) => a - b); - const n = arr.length; - for (let i = 0; i < n; i++) { - if (target[i] !== arr[i]) { - return false; +### 方法二:数组/哈希表 + +由于两数组的数据范围都是 $1 \leq x \leq 1000$,因此我们可以使用数组或哈希表来记录每个数字出现的次数。 + +时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 是数组 $arr$ 的长度,而 $C$ 是数组 $arr$ 元素的值域大小。 + + + +```python +class Solution: + def canBeEqual(self, target: List[int], arr: List[int]) -> bool: + return Counter(target) == Counter(arr) +``` + +```java +class Solution { + public boolean canBeEqual(int[] target, int[] arr) { + int[] cnt1 = new int[1001]; + int[] cnt2 = new int[1001]; + for (int v : target) { + ++cnt1[v]; + } + for (int v : arr) { + ++cnt2[v]; } + return Arrays.equals(cnt1, cnt2); } - return true; +} +``` + +```cpp +class Solution { +public: + bool canBeEqual(vector& target, vector& arr) { + vector cnt1(1001); + vector cnt2(1001); + for (int& v : target) ++cnt1[v]; + for (int& v : arr) ++cnt2[v]; + return cnt1 == cnt2; + } +}; +``` + +```go +func canBeEqual(target []int, arr []int) bool { + cnt1 := make([]int, 1001) + cnt2 := make([]int, 1001) + for _, v := range target { + cnt1[v]++ + } + for _, v := range arr { + cnt2[v]++ + } + for i, v := range cnt1 { + if v != cnt2[i] { + return false + } + } + return true } ``` @@ -285,18 +234,6 @@ function canBeEqual(target: number[], arr: number[]): boolean { } ``` -### **Rust** - -```rust -impl Solution { - pub fn can_be_equal(mut target: Vec, mut arr: Vec) -> bool { - target.sort(); - arr.sort(); - target == arr - } -} -``` - ```rust impl Solution { pub fn can_be_equal(mut target: Vec, mut arr: Vec) -> bool { @@ -311,27 +248,68 @@ impl Solution { } ``` -### **PHP** + -```php +### 方法三 + + + +```python +class Solution: + def canBeEqual(self, target: List[int], arr: List[int]) -> bool: + cnt = [0] * 1001 + for a, b in zip(target, arr): + cnt[a] += 1 + cnt[b] -= 1 + return all(v == 0 for v in cnt) +``` + +```java class Solution { - /** - * @param Integer[] $target - * @param Integer[] $arr - * @return Boolean - */ - function canBeEqual($target, $arr) { - sort($target); - sort($arr); - return $target === $arr; + public boolean canBeEqual(int[] target, int[] arr) { + int[] cnt = new int[1001]; + for (int v : target) { + ++cnt[v]; + } + for (int v : arr) { + if (--cnt[v] < 0) { + return false; + } + } + return true; } } ``` -### **...** - +```cpp +class Solution { +public: + bool canBeEqual(vector& target, vector& arr) { + vector cnt(1001); + for (int& v : target) ++cnt[v]; + for (int& v : arr) + if (--cnt[v] < 0) return false; + return true; + } +}; ``` +```go +func canBeEqual(target []int, arr []int) bool { + cnt := make([]int, 1001) + for _, v := range target { + cnt[v]++ + } + for _, v := range arr { + cnt[v]-- + if cnt[v] < 0 { + return false + } + } + return true +} ``` + + diff --git a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/README_EN.md b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/README_EN.md index 5ddced0dac5b4..e3828a51070d5 100644 --- a/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/README_EN.md +++ b/solution/1400-1499/1460.Make Two Arrays Equal by Reversing Subarrays/README_EN.md @@ -49,9 +49,9 @@ There are multiple ways to convert arr to target, this is not the only way to do ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,24 +61,6 @@ class Solution: return target == arr ``` -```python -class Solution: - def canBeEqual(self, target: List[int], arr: List[int]) -> bool: - return Counter(target) == Counter(arr) -``` - -```python -class Solution: - def canBeEqual(self, target: List[int], arr: List[int]) -> bool: - cnt = [0] * 1001 - for a, b in zip(target, arr): - cnt[a] += 1 - cnt[b] -= 1 - return all(v == 0 for v in cnt) -``` - -### **Java** - ```java class Solution { public boolean canBeEqual(int[] target, int[] arr) { @@ -89,41 +71,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canBeEqual(int[] target, int[] arr) { - int[] cnt1 = new int[1001]; - int[] cnt2 = new int[1001]; - for (int v : target) { - ++cnt1[v]; - } - for (int v : arr) { - ++cnt2[v]; - } - return Arrays.equals(cnt1, cnt2); - } -} -``` - -```java -class Solution { - public boolean canBeEqual(int[] target, int[] arr) { - int[] cnt = new int[1001]; - for (int v : target) { - ++cnt[v]; - } - for (int v : arr) { - if (--cnt[v] < 0) { - return false; - } - } - return true; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -135,34 +82,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool canBeEqual(vector& target, vector& arr) { - vector cnt1(1001); - vector cnt2(1001); - for (int& v : target) ++cnt1[v]; - for (int& v : arr) ++cnt2[v]; - return cnt1 == cnt2; - } -}; -``` - -```cpp -class Solution { -public: - bool canBeEqual(vector& target, vector& arr) { - vector cnt(1001); - for (int& v : target) ++cnt[v]; - for (int& v : arr) - if (--cnt[v] < 0) return false; - return true; - } -}; -``` - -### **Go** - ```go func canBeEqual(target []int, arr []int) bool { sort.Ints(target) @@ -176,42 +95,44 @@ func canBeEqual(target []int, arr []int) bool { } ``` -```go -func canBeEqual(target []int, arr []int) bool { - cnt1 := make([]int, 1001) - cnt2 := make([]int, 1001) - for _, v := range target { - cnt1[v]++ - } - for _, v := range arr { - cnt2[v]++ - } - for i, v := range cnt1 { - if v != cnt2[i] { - return false - } - } - return true +```ts +function canBeEqual(target: number[], arr: number[]): boolean { + target.sort((a, b) => a - b); + arr.sort((a, b) => a - b); + const n = arr.length; + for (let i = 0; i < n; i++) { + if (target[i] !== arr[i]) { + return false; + } + } + return true; } ``` -```go -func canBeEqual(target []int, arr []int) bool { - cnt := make([]int, 1001) - for _, v := range target { - cnt[v]++ - } - for _, v := range arr { - cnt[v]-- - if cnt[v] < 0 { - return false - } - } - return true +```rust +impl Solution { + pub fn can_be_equal(mut target: Vec, mut arr: Vec) -> bool { + target.sort(); + arr.sort(); + target == arr + } } ``` -### **C** +```php +class Solution { + /** + * @param Integer[] $target + * @param Integer[] $arr + * @return Boolean + */ + function canBeEqual($target, $arr) { + sort($target); + sort($arr); + return $target === $arr; + } +} +``` ```c bool canBeEqual(int* target, int targetSize, int* arr, int arrSize) { @@ -229,19 +150,63 @@ bool canBeEqual(int* target, int targetSize, int* arr, int arrSize) { } ``` -### **TypeScript** + -```ts -function canBeEqual(target: number[], arr: number[]): boolean { - target.sort((a, b) => a - b); - arr.sort((a, b) => a - b); - const n = arr.length; - for (let i = 0; i < n; i++) { - if (target[i] !== arr[i]) { - return false; +### Solution 2 + + + +```python +class Solution: + def canBeEqual(self, target: List[int], arr: List[int]) -> bool: + return Counter(target) == Counter(arr) +``` + +```java +class Solution { + public boolean canBeEqual(int[] target, int[] arr) { + int[] cnt1 = new int[1001]; + int[] cnt2 = new int[1001]; + for (int v : target) { + ++cnt1[v]; } + for (int v : arr) { + ++cnt2[v]; + } + return Arrays.equals(cnt1, cnt2); } - return true; +} +``` + +```cpp +class Solution { +public: + bool canBeEqual(vector& target, vector& arr) { + vector cnt1(1001); + vector cnt2(1001); + for (int& v : target) ++cnt1[v]; + for (int& v : arr) ++cnt2[v]; + return cnt1 == cnt2; + } +}; +``` + +```go +func canBeEqual(target []int, arr []int) bool { + cnt1 := make([]int, 1001) + cnt2 := make([]int, 1001) + for _, v := range target { + cnt1[v]++ + } + for _, v := range arr { + cnt2[v]++ + } + for i, v := range cnt1 { + if v != cnt2[i] { + return false + } + } + return true } ``` @@ -257,18 +222,6 @@ function canBeEqual(target: number[], arr: number[]): boolean { } ``` -### **Rust** - -```rust -impl Solution { - pub fn can_be_equal(mut target: Vec, mut arr: Vec) -> bool { - target.sort(); - arr.sort(); - target == arr - } -} -``` - ```rust impl Solution { pub fn can_be_equal(mut target: Vec, mut arr: Vec) -> bool { @@ -283,27 +236,68 @@ impl Solution { } ``` -### **PHP** + + +### Solution 3 -```php + + +```python +class Solution: + def canBeEqual(self, target: List[int], arr: List[int]) -> bool: + cnt = [0] * 1001 + for a, b in zip(target, arr): + cnt[a] += 1 + cnt[b] -= 1 + return all(v == 0 for v in cnt) +``` + +```java class Solution { - /** - * @param Integer[] $target - * @param Integer[] $arr - * @return Boolean - */ - function canBeEqual($target, $arr) { - sort($target); - sort($arr); - return $target === $arr; + public boolean canBeEqual(int[] target, int[] arr) { + int[] cnt = new int[1001]; + for (int v : target) { + ++cnt[v]; + } + for (int v : arr) { + if (--cnt[v] < 0) { + return false; + } + } + return true; } } ``` -### **...** - +```cpp +class Solution { +public: + bool canBeEqual(vector& target, vector& arr) { + vector cnt(1001); + for (int& v : target) ++cnt[v]; + for (int& v : arr) + if (--cnt[v] < 0) return false; + return true; + } +}; ``` +```go +func canBeEqual(target []int, arr []int) bool { + cnt := make([]int, 1001) + for _, v := range target { + cnt[v]++ + } + for _, v := range arr { + cnt[v]-- + if cnt[v] < 0 { + return false + } + } + return true +} ``` + + diff --git a/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/README.md b/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/README.md index 072d3facdc676..3a67596452269 100644 --- a/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/README.md +++ b/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/README.md @@ -46,26 +46,14 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 遍历字符串 $s$,用一个哈希表存储所有长度为 $k$ 的不同子串。只需要判断子串数能否达到 $2^k$ 即可。 时间复杂度 $O(n \times k)$,其中 $n$ 是字符串 $s$ 的长度,$k$ 是子串长度。 -**方法二:滑动窗口** - -方法一中,我们存储了所有长度为 $k$ 的不同子串,子串的处理需要 $O(k)$ 的时间,我们可以改用滑动窗口,每次添加最新字符时,删除窗口最左边的字符。此过程中用一个整型数字 $num$ 来存放子串。 - -时间复杂度 $O(n)$,其中 $n$ 是字符串 $s$ 的长度。 - -### **Python3** - - - ```python class Solution: def hasAllCodes(self, s: str, k: int) -> bool: @@ -73,6 +61,51 @@ class Solution: return len(ss) == 1 << k ``` +```java +class Solution { + public boolean hasAllCodes(String s, int k) { + Set ss = new HashSet<>(); + for (int i = 0; i < s.length() - k + 1; ++i) { + ss.add(s.substring(i, i + k)); + } + return ss.size() == 1 << k; + } +} +``` + +```cpp +class Solution { +public: + bool hasAllCodes(string s, int k) { + unordered_set ss; + for (int i = 0; i + k <= s.size(); ++i) { + ss.insert(move(s.substr(i, k))); + } + return ss.size() == 1 << k; + } +}; +``` + +```go +func hasAllCodes(s string, k int) bool { + ss := map[string]bool{} + for i := 0; i+k <= len(s); i++ { + ss[s[i:i+k]] = true + } + return len(ss) == 1< + +### 方法二:滑动窗口 + +方法一中,我们存储了所有长度为 $k$ 的不同子串,子串的处理需要 $O(k)$ 的时间,我们可以改用滑动窗口,每次添加最新字符时,删除窗口最左边的字符。此过程中用一个整型数字 $num$ 来存放子串。 + +时间复杂度 $O(n)$,其中 $n$ 是字符串 $s$ 的长度。 + + + ```python class Solution: def hasAllCodes(self, s: str, k: int) -> bool: @@ -89,22 +122,6 @@ class Solution: return all(v for v in vis) ``` -### **Java** - - - -```java -class Solution { - public boolean hasAllCodes(String s, int k) { - Set ss = new HashSet<>(); - for (int i = 0; i < s.length() - k + 1; ++i) { - ss.add(s.substring(i, i + k)); - } - return ss.size() == 1 << k; - } -} -``` - ```java class Solution { public boolean hasAllCodes(String s, int k) { @@ -131,21 +148,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool hasAllCodes(string s, int k) { - unordered_set ss; - for (int i = 0; i + k <= s.size(); ++i) { - ss.insert(move(s.substr(i, k))); - } - return ss.size() == 1 << k; - } -}; -``` - ```cpp class Solution { public: @@ -168,18 +170,6 @@ public: }; ``` -### **Go** - -```go -func hasAllCodes(s string, k int) bool { - ss := map[string]bool{} - for i := 0; i+k <= len(s); i++ { - ss[s[i:i+k]] = true - } - return len(ss) == 1< + + diff --git a/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/README_EN.md b/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/README_EN.md index 2a07ce98c64e7..6624efb4b2738 100644 --- a/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/README_EN.md +++ b/solution/1400-1499/1461.Check If a String Contains All Binary Codes of Size K/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,6 +53,47 @@ class Solution: return len(ss) == 1 << k ``` +```java +class Solution { + public boolean hasAllCodes(String s, int k) { + Set ss = new HashSet<>(); + for (int i = 0; i < s.length() - k + 1; ++i) { + ss.add(s.substring(i, i + k)); + } + return ss.size() == 1 << k; + } +} +``` + +```cpp +class Solution { +public: + bool hasAllCodes(string s, int k) { + unordered_set ss; + for (int i = 0; i + k <= s.size(); ++i) { + ss.insert(move(s.substr(i, k))); + } + return ss.size() == 1 << k; + } +}; +``` + +```go +func hasAllCodes(s string, k int) bool { + ss := map[string]bool{} + for i := 0; i+k <= len(s); i++ { + ss[s[i:i+k]] = true + } + return len(ss) == 1< + +### Solution 2 + + + ```python class Solution: def hasAllCodes(self, s: str, k: int) -> bool: @@ -69,20 +110,6 @@ class Solution: return all(v for v in vis) ``` -### **Java** - -```java -class Solution { - public boolean hasAllCodes(String s, int k) { - Set ss = new HashSet<>(); - for (int i = 0; i < s.length() - k + 1; ++i) { - ss.add(s.substring(i, i + k)); - } - return ss.size() == 1 << k; - } -} -``` - ```java class Solution { public boolean hasAllCodes(String s, int k) { @@ -109,21 +136,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool hasAllCodes(string s, int k) { - unordered_set ss; - for (int i = 0; i + k <= s.size(); ++i) { - ss.insert(move(s.substr(i, k))); - } - return ss.size() == 1 << k; - } -}; -``` - ```cpp class Solution { public: @@ -146,18 +158,6 @@ public: }; ``` -### **Go** - -```go -func hasAllCodes(s string, k int) bool { - ss := map[string]bool{} - for i := 0; i+k <= len(s); i++ { - ss[s[i:i+k]] = true - } - return len(ss) == 1< + + diff --git a/solution/1400-1499/1462.Course Schedule IV/README.md b/solution/1400-1499/1462.Course Schedule IV/README.md index f69a501a1116f..8f0851d7662a0 100644 --- a/solution/1400-1499/1462.Course Schedule IV/README.md +++ b/solution/1400-1499/1462.Course Schedule IV/README.md @@ -68,9 +68,7 @@ ## 解法 - - -**方法一:Floyd 算法** +### 方法一:Floyd 算法 我们创建一个二维数组 $f$,其中 $f[i][j]$ 表示节点 $i$ 到节点 $j$ 是否可达。 @@ -84,26 +82,8 @@ 时间复杂度 $O(n^3)$,空间复杂度 $O(n^2)$。其中 $n$ 为节点数。 -**方法二:拓扑排序** - -与方法一类似,我们创建一个二维数组 $f$,其中 $f[i][j]$ 表示节点 $i$ 到节点 $j$ 是否可达。另外,我们创建一个邻接表 $g$,其中 $g[i]$ 表示节点 $i$ 的所有后继节点;创建一个数组 $indeg$,其中 $indeg[i]$ 表示节点 $i$ 的入度。 - -接下来,我们遍历先修课程数组 $prerequisites$,对于其中的每一项 $[a, b]$,我们更新邻接表 $g$ 和入度数组 $indeg$。 - -然后,我们使用拓扑排序计算出所有节点对之间的可达性。 - -定义一个队列 $q$,初始时将所有入度为 $0$ 的节点加入队列中。随后不断进行以下操作:取出队首节点 $i$,然后遍历 $g[i]$ 中的所有节点 $j$,将 $f[i][j]$ 设为 $true$。接下来,我们枚举节点 $h$,如果 $f[h][i]$ 为 $true$,那么我们也将 $f[h][j]$ 设为 $true$。在这之后,我们将 $j$ 的入度减少 $1$。如果此时 $j$ 的入度为 $0$,那么我们就将 $j$ 加入队列中。 - -在计算完所有节点对之间的可达性之后,对于每一个查询 $[a, b]$,我们直接返回 $f[a][b]$ 即可。 - -时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 为节点数。 - -### **Python3** - - - ```python class Solution: def checkIfPrerequisite( @@ -120,6 +100,110 @@ class Solution: return [f[a][b] for a, b in queries] ``` +```java +class Solution { + public List checkIfPrerequisite(int n, int[][] prerequisites, int[][] queries) { + boolean[][] f = new boolean[n][n]; + for (var p : prerequisites) { + f[p[0]][p[1]] = true; + } + for (int k = 0; k < n; ++k) { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + f[i][j] |= f[i][k] && f[k][j]; + } + } + } + List ans = new ArrayList<>(); + for (var q : queries) { + ans.add(f[q[0]][q[1]]); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector checkIfPrerequisite(int n, vector>& prerequisites, vector>& queries) { + bool f[n][n]; + memset(f, false, sizeof(f)); + for (auto& p : prerequisites) { + f[p[0]][p[1]] = true; + } + for (int k = 0; k < n; ++k) { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + f[i][j] |= (f[i][k] && f[k][j]); + } + } + } + vector ans; + for (auto& q : queries) { + ans.push_back(f[q[0]][q[1]]); + } + return ans; + } +}; +``` + +```go +func checkIfPrerequisite(n int, prerequisites [][]int, queries [][]int) (ans []bool) { + f := make([][]bool, n) + for i := range f { + f[i] = make([]bool, n) + } + for _, p := range prerequisites { + f[p[0]][p[1]] = true + } + for k := 0; k < n; k++ { + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + f[i][j] = f[i][j] || (f[i][k] && f[k][j]) + } + } + } + for _, q := range queries { + ans = append(ans, f[q[0]][q[1]]) + } + return +} +``` + +```ts +function checkIfPrerequisite(n: number, prerequisites: number[][], queries: number[][]): boolean[] { + const f = Array.from({ length: n }, () => Array(n).fill(false)); + prerequisites.forEach(([a, b]) => (f[a][b] = true)); + for (let k = 0; k < n; ++k) { + for (let i = 0; i < n; ++i) { + for (let j = 0; j < n; ++j) { + f[i][j] ||= f[i][k] && f[k][j]; + } + } + } + return queries.map(([a, b]) => f[a][b]); +} +``` + + + +### 方法二:拓扑排序 + +与方法一类似,我们创建一个二维数组 $f$,其中 $f[i][j]$ 表示节点 $i$ 到节点 $j$ 是否可达。另外,我们创建一个邻接表 $g$,其中 $g[i]$ 表示节点 $i$ 的所有后继节点;创建一个数组 $indeg$,其中 $indeg[i]$ 表示节点 $i$ 的入度。 + +接下来,我们遍历先修课程数组 $prerequisites$,对于其中的每一项 $[a, b]$,我们更新邻接表 $g$ 和入度数组 $indeg$。 + +然后,我们使用拓扑排序计算出所有节点对之间的可达性。 + +定义一个队列 $q$,初始时将所有入度为 $0$ 的节点加入队列中。随后不断进行以下操作:取出队首节点 $i$,然后遍历 $g[i]$ 中的所有节点 $j$,将 $f[i][j]$ 设为 $true$。接下来,我们枚举节点 $h$,如果 $f[h][i]$ 为 $true$,那么我们也将 $f[h][j]$ 设为 $true$。在这之后,我们将 $j$ 的入度减少 $1$。如果此时 $j$ 的入度为 $0$,那么我们就将 $j$ 加入队列中。 + +在计算完所有节点对之间的可达性之后,对于每一个查询 $[a, b]$,我们直接返回 $f[a][b]$ 即可。 + +时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 为节点数。 + + + ```python class Solution: def checkIfPrerequisite( @@ -144,33 +228,6 @@ class Solution: return [f[a][b] for a, b in queries] ``` -### **Java** - - - -```java -class Solution { - public List checkIfPrerequisite(int n, int[][] prerequisites, int[][] queries) { - boolean[][] f = new boolean[n][n]; - for (var p : prerequisites) { - f[p[0]][p[1]] = true; - } - for (int k = 0; k < n; ++k) { - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - f[i][j] |= f[i][k] && f[k][j]; - } - } - } - List ans = new ArrayList<>(); - for (var q : queries) { - ans.add(f[q[0]][q[1]]); - } - return ans; - } -} -``` - ```java class Solution { public List checkIfPrerequisite(int n, int[][] prerequisites, int[][] queries) { @@ -209,33 +266,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector checkIfPrerequisite(int n, vector>& prerequisites, vector>& queries) { - bool f[n][n]; - memset(f, false, sizeof(f)); - for (auto& p : prerequisites) { - f[p[0]][p[1]] = true; - } - for (int k = 0; k < n; ++k) { - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - f[i][j] |= (f[i][k] && f[k][j]); - } - } - } - vector ans; - for (auto& q : queries) { - ans.push_back(f[q[0]][q[1]]); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -276,31 +306,6 @@ public: }; ``` -### **Go** - -```go -func checkIfPrerequisite(n int, prerequisites [][]int, queries [][]int) (ans []bool) { - f := make([][]bool, n) - for i := range f { - f[i] = make([]bool, n) - } - for _, p := range prerequisites { - f[p[0]][p[1]] = true - } - for k := 0; k < n; k++ { - for i := 0; i < n; i++ { - for j := 0; j < n; j++ { - f[i][j] = f[i][j] || (f[i][k] && f[k][j]) - } - } - } - for _, q := range queries { - ans = append(ans, f[q[0]][q[1]]) - } - return -} -``` - ```go func checkIfPrerequisite(n int, prerequisites [][]int, queries [][]int) (ans []bool) { f := make([][]bool, n) @@ -341,23 +346,6 @@ func checkIfPrerequisite(n int, prerequisites [][]int, queries [][]int) (ans []b } ``` -### **TypeScript** - -```ts -function checkIfPrerequisite(n: number, prerequisites: number[][], queries: number[][]): boolean[] { - const f = Array.from({ length: n }, () => Array(n).fill(false)); - prerequisites.forEach(([a, b]) => (f[a][b] = true)); - for (let k = 0; k < n; ++k) { - for (let i = 0; i < n; ++i) { - for (let j = 0; j < n; ++j) { - f[i][j] ||= f[i][k] && f[k][j]; - } - } - } - return queries.map(([a, b]) => f[a][b]); -} -``` - ```ts function checkIfPrerequisite(n: number, prerequisites: number[][], queries: number[][]): boolean[] { const f = Array.from({ length: n }, () => Array(n).fill(false)); @@ -389,10 +377,6 @@ function checkIfPrerequisite(n: number, prerequisites: number[][], queries: numb } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1462.Course Schedule IV/README_EN.md b/solution/1400-1499/1462.Course Schedule IV/README_EN.md index 216284fb9a6db..d70585ef7b2c1 100644 --- a/solution/1400-1499/1462.Course Schedule IV/README_EN.md +++ b/solution/1400-1499/1462.Course Schedule IV/README_EN.md @@ -59,9 +59,9 @@ Course 0 is not a prerequisite of course 1, but the opposite is true. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,6 +79,98 @@ class Solution: return [f[a][b] for a, b in queries] ``` +```java +class Solution { + public List checkIfPrerequisite(int n, int[][] prerequisites, int[][] queries) { + boolean[][] f = new boolean[n][n]; + for (var p : prerequisites) { + f[p[0]][p[1]] = true; + } + for (int k = 0; k < n; ++k) { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + f[i][j] |= f[i][k] && f[k][j]; + } + } + } + List ans = new ArrayList<>(); + for (var q : queries) { + ans.add(f[q[0]][q[1]]); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector checkIfPrerequisite(int n, vector>& prerequisites, vector>& queries) { + bool f[n][n]; + memset(f, false, sizeof(f)); + for (auto& p : prerequisites) { + f[p[0]][p[1]] = true; + } + for (int k = 0; k < n; ++k) { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + f[i][j] |= (f[i][k] && f[k][j]); + } + } + } + vector ans; + for (auto& q : queries) { + ans.push_back(f[q[0]][q[1]]); + } + return ans; + } +}; +``` + +```go +func checkIfPrerequisite(n int, prerequisites [][]int, queries [][]int) (ans []bool) { + f := make([][]bool, n) + for i := range f { + f[i] = make([]bool, n) + } + for _, p := range prerequisites { + f[p[0]][p[1]] = true + } + for k := 0; k < n; k++ { + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + f[i][j] = f[i][j] || (f[i][k] && f[k][j]) + } + } + } + for _, q := range queries { + ans = append(ans, f[q[0]][q[1]]) + } + return +} +``` + +```ts +function checkIfPrerequisite(n: number, prerequisites: number[][], queries: number[][]): boolean[] { + const f = Array.from({ length: n }, () => Array(n).fill(false)); + prerequisites.forEach(([a, b]) => (f[a][b] = true)); + for (let k = 0; k < n; ++k) { + for (let i = 0; i < n; ++i) { + for (let j = 0; j < n; ++j) { + f[i][j] ||= f[i][k] && f[k][j]; + } + } + } + return queries.map(([a, b]) => f[a][b]); +} +``` + + + +### Solution 2 + + + ```python class Solution: def checkIfPrerequisite( @@ -103,31 +195,6 @@ class Solution: return [f[a][b] for a, b in queries] ``` -### **Java** - -```java -class Solution { - public List checkIfPrerequisite(int n, int[][] prerequisites, int[][] queries) { - boolean[][] f = new boolean[n][n]; - for (var p : prerequisites) { - f[p[0]][p[1]] = true; - } - for (int k = 0; k < n; ++k) { - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - f[i][j] |= f[i][k] && f[k][j]; - } - } - } - List ans = new ArrayList<>(); - for (var q : queries) { - ans.add(f[q[0]][q[1]]); - } - return ans; - } -} -``` - ```java class Solution { public List checkIfPrerequisite(int n, int[][] prerequisites, int[][] queries) { @@ -166,33 +233,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector checkIfPrerequisite(int n, vector>& prerequisites, vector>& queries) { - bool f[n][n]; - memset(f, false, sizeof(f)); - for (auto& p : prerequisites) { - f[p[0]][p[1]] = true; - } - for (int k = 0; k < n; ++k) { - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - f[i][j] |= (f[i][k] && f[k][j]); - } - } - } - vector ans; - for (auto& q : queries) { - ans.push_back(f[q[0]][q[1]]); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -233,31 +273,6 @@ public: }; ``` -### **Go** - -```go -func checkIfPrerequisite(n int, prerequisites [][]int, queries [][]int) (ans []bool) { - f := make([][]bool, n) - for i := range f { - f[i] = make([]bool, n) - } - for _, p := range prerequisites { - f[p[0]][p[1]] = true - } - for k := 0; k < n; k++ { - for i := 0; i < n; i++ { - for j := 0; j < n; j++ { - f[i][j] = f[i][j] || (f[i][k] && f[k][j]) - } - } - } - for _, q := range queries { - ans = append(ans, f[q[0]][q[1]]) - } - return -} -``` - ```go func checkIfPrerequisite(n int, prerequisites [][]int, queries [][]int) (ans []bool) { f := make([][]bool, n) @@ -298,23 +313,6 @@ func checkIfPrerequisite(n int, prerequisites [][]int, queries [][]int) (ans []b } ``` -### **TypeScript** - -```ts -function checkIfPrerequisite(n: number, prerequisites: number[][], queries: number[][]): boolean[] { - const f = Array.from({ length: n }, () => Array(n).fill(false)); - prerequisites.forEach(([a, b]) => (f[a][b] = true)); - for (let k = 0; k < n; ++k) { - for (let i = 0; i < n; ++i) { - for (let j = 0; j < n; ++j) { - f[i][j] ||= f[i][k] && f[k][j]; - } - } - } - return queries.map(([a, b]) => f[a][b]); -} -``` - ```ts function checkIfPrerequisite(n: number, prerequisites: number[][], queries: number[][]): boolean[] { const f = Array.from({ length: n }, () => Array(n).fill(false)); @@ -346,10 +344,6 @@ function checkIfPrerequisite(n: number, prerequisites: number[][], queries: numb } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1463.Cherry Pickup II/README.md b/solution/1400-1499/1463.Cherry Pickup II/README.md index 4787649d1ddb7..530166bb62d37 100644 --- a/solution/1400-1499/1463.Cherry Pickup II/README.md +++ b/solution/1400-1499/1463.Cherry Pickup II/README.md @@ -71,9 +71,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j_1][j_2]$ 表示两个机器人分别在第 $i$ 行的位置 $j_1$ 和 $j_2$ 时能够摘到的最多樱桃数目。初始时 $f[0][0][n-1] = grid[0][0] + grid[0][n-1]$,其余值均为 $-1$。答案为 $\max_{0 \leq j_1, j_2 < n} f[m-1][j_1][j_2]$。 @@ -93,10 +91,6 @@ $$ -### **Python3** - - - ```python class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: @@ -114,29 +108,6 @@ class Solution: return max(f[-1][j1][j2] for j1, j2 in product(range(n), range(n))) ``` -```python -class Solution: - def cherryPickup(self, grid: List[List[int]]) -> int: - m, n = len(grid), len(grid[0]) - f = [[-1] * n for _ in range(n)] - g = [[-1] * n for _ in range(n)] - f[0][n - 1] = grid[0][0] + grid[0][n - 1] - for i in range(1, m): - for j1 in range(n): - for j2 in range(n): - x = grid[i][j1] + (0 if j1 == j2 else grid[i][j2]) - for y1 in range(j1 - 1, j1 + 2): - for y2 in range(j2 - 1, j2 + 2): - if 0 <= y1 < n and 0 <= y2 < n and f[y1][y2] != -1: - g[j1][j2] = max(g[j1][j2], f[y1][y2] + x) - f, g = g, f - return max(f[j1][j2] for j1, j2 in product(range(n), range(n))) -``` - -### **Java** - - - ```java class Solution { public int cherryPickup(int[][] grid) { @@ -173,78 +144,174 @@ class Solution { } ``` -```java +```cpp class Solution { - public int cherryPickup(int[][] grid) { - int m = grid.length, n = grid[0].length; - int[][] f = new int[n][n]; - int[][] g = new int[n][n]; - for (int i = 0; i < n; ++i) { - Arrays.fill(f[i], -1); - Arrays.fill(g[i], -1); - } - f[0][n - 1] = grid[0][0] + grid[0][n - 1]; +public: + int cherryPickup(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int f[m][n][n]; + memset(f, -1, sizeof(f)); + f[0][0][n - 1] = grid[0][0] + grid[0][n - 1]; for (int i = 1; i < m; ++i) { for (int j1 = 0; j1 < n; ++j1) { for (int j2 = 0; j2 < n; ++j2) { int x = grid[i][j1] + (j1 == j2 ? 0 : grid[i][j2]); for (int y1 = j1 - 1; y1 <= j1 + 1; ++y1) { for (int y2 = j2 - 1; y2 <= j2 + 1; ++y2) { - if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[y1][y2] != -1) { - g[j1][j2] = Math.max(g[j1][j2], f[y1][y2] + x); + if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i - 1][y1][y2] != -1) { + f[i][j1][j2] = max(f[i][j1][j2], f[i - 1][y1][y2] + x); } } } } } - int[][] t = f; - f = g; - g = t; } int ans = 0; for (int j1 = 0; j1 < n; ++j1) { for (int j2 = 0; j2 < n; ++j2) { - ans = Math.max(ans, f[j1][j2]); + ans = max(ans, f[m - 1][j1][j2]); } } return ans; } +}; +``` + +```go +func cherryPickup(grid [][]int) int { + m, n := len(grid), len(grid[0]) + f := make([][][]int, m) + for i := range f { + f[i] = make([][]int, n) + for j := range f[i] { + f[i][j] = make([]int, n) + for k := range f[i][j] { + f[i][j][k] = -1 + } + } + } + f[0][0][n-1] = grid[0][0] + grid[0][n-1] + for i := 1; i < m; i++ { + for j1 := 0; j1 < n; j1++ { + for j2 := 0; j2 < n; j2++ { + x := grid[i][j1] + if j1 != j2 { + x += grid[i][j2] + } + for y1 := j1 - 1; y1 <= j1+1; y1++ { + for y2 := j2 - 1; y2 <= j2+1; y2++ { + if y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i-1][y1][y2] != -1 { + f[i][j1][j2] = max(f[i][j1][j2], f[i-1][y1][y2]+x) + } + } + } + } + } + } + ans := 0 + for j1 := 0; j1 < n; j1++ { + for j2 := 0; j2 < n; j2++ { + ans = max(ans, f[m-1][j1][j2]) + } + } + return ans +} +``` + +```ts +function cherryPickup(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const f: number[][][] = new Array(m) + .fill(0) + .map(() => new Array(n).fill(0).map(() => new Array(n).fill(-1))); + f[0][0][n - 1] = grid[0][0] + grid[0][n - 1]; + for (let i = 1; i < m; ++i) { + for (let j1 = 0; j1 < n; ++j1) { + for (let j2 = 0; j2 < n; ++j2) { + const x = grid[i][j1] + (j1 === j2 ? 0 : grid[i][j2]); + for (let y1 = j1 - 1; y1 <= j1 + 1; ++y1) { + for (let y2 = j2 - 1; y2 <= j2 + 1; ++y2) { + if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i - 1][y1][y2] !== -1) { + f[i][j1][j2] = Math.max(f[i][j1][j2], f[i - 1][y1][y2] + x); + } + } + } + } + } + } + let ans = 0; + for (let j1 = 0; j1 < n; ++j1) { + for (let j2 = 0; j2 < n; ++j2) { + ans = Math.max(ans, f[m - 1][j1][j2]); + } + } + return ans; } ``` -### **C++** + + +### 方法二 -```cpp + + +```python +class Solution: + def cherryPickup(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + f = [[-1] * n for _ in range(n)] + g = [[-1] * n for _ in range(n)] + f[0][n - 1] = grid[0][0] + grid[0][n - 1] + for i in range(1, m): + for j1 in range(n): + for j2 in range(n): + x = grid[i][j1] + (0 if j1 == j2 else grid[i][j2]) + for y1 in range(j1 - 1, j1 + 2): + for y2 in range(j2 - 1, j2 + 2): + if 0 <= y1 < n and 0 <= y2 < n and f[y1][y2] != -1: + g[j1][j2] = max(g[j1][j2], f[y1][y2] + x) + f, g = g, f + return max(f[j1][j2] for j1, j2 in product(range(n), range(n))) +``` + +```java class Solution { -public: - int cherryPickup(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - int f[m][n][n]; - memset(f, -1, sizeof(f)); - f[0][0][n - 1] = grid[0][0] + grid[0][n - 1]; + public int cherryPickup(int[][] grid) { + int m = grid.length, n = grid[0].length; + int[][] f = new int[n][n]; + int[][] g = new int[n][n]; + for (int i = 0; i < n; ++i) { + Arrays.fill(f[i], -1); + Arrays.fill(g[i], -1); + } + f[0][n - 1] = grid[0][0] + grid[0][n - 1]; for (int i = 1; i < m; ++i) { for (int j1 = 0; j1 < n; ++j1) { for (int j2 = 0; j2 < n; ++j2) { int x = grid[i][j1] + (j1 == j2 ? 0 : grid[i][j2]); for (int y1 = j1 - 1; y1 <= j1 + 1; ++y1) { for (int y2 = j2 - 1; y2 <= j2 + 1; ++y2) { - if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i - 1][y1][y2] != -1) { - f[i][j1][j2] = max(f[i][j1][j2], f[i - 1][y1][y2] + x); + if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[y1][y2] != -1) { + g[j1][j2] = Math.max(g[j1][j2], f[y1][y2] + x); } } } } } + int[][] t = f; + f = g; + g = t; } int ans = 0; for (int j1 = 0; j1 < n; ++j1) { for (int j2 = 0; j2 < n; ++j2) { - ans = max(ans, f[m - 1][j1][j2]); + ans = Math.max(ans, f[j1][j2]); } } return ans; } -}; +} ``` ```cpp @@ -281,49 +348,6 @@ public: }; ``` -### **Go** - -```go -func cherryPickup(grid [][]int) int { - m, n := len(grid), len(grid[0]) - f := make([][][]int, m) - for i := range f { - f[i] = make([][]int, n) - for j := range f[i] { - f[i][j] = make([]int, n) - for k := range f[i][j] { - f[i][j][k] = -1 - } - } - } - f[0][0][n-1] = grid[0][0] + grid[0][n-1] - for i := 1; i < m; i++ { - for j1 := 0; j1 < n; j1++ { - for j2 := 0; j2 < n; j2++ { - x := grid[i][j1] - if j1 != j2 { - x += grid[i][j2] - } - for y1 := j1 - 1; y1 <= j1+1; y1++ { - for y2 := j2 - 1; y2 <= j2+1; y2++ { - if y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i-1][y1][y2] != -1 { - f[i][j1][j2] = max(f[i][j1][j2], f[i-1][y1][y2]+x) - } - } - } - } - } - } - ans := 0 - for j1 := 0; j1 < n; j1++ { - for j2 := 0; j2 < n; j2++ { - ans = max(ans, f[m-1][j1][j2]) - } - } - return ans -} -``` - ```go func cherryPickup(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -366,40 +390,6 @@ func cherryPickup(grid [][]int) int { } ``` -### **TypeScript** - -```ts -function cherryPickup(grid: number[][]): number { - const m = grid.length; - const n = grid[0].length; - const f: number[][][] = new Array(m) - .fill(0) - .map(() => new Array(n).fill(0).map(() => new Array(n).fill(-1))); - f[0][0][n - 1] = grid[0][0] + grid[0][n - 1]; - for (let i = 1; i < m; ++i) { - for (let j1 = 0; j1 < n; ++j1) { - for (let j2 = 0; j2 < n; ++j2) { - const x = grid[i][j1] + (j1 === j2 ? 0 : grid[i][j2]); - for (let y1 = j1 - 1; y1 <= j1 + 1; ++y1) { - for (let y2 = j2 - 1; y2 <= j2 + 1; ++y2) { - if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i - 1][y1][y2] !== -1) { - f[i][j1][j2] = Math.max(f[i][j1][j2], f[i - 1][y1][y2] + x); - } - } - } - } - } - } - let ans = 0; - for (let j1 = 0; j1 < n; ++j1) { - for (let j2 = 0; j2 < n; ++j2) { - ans = Math.max(ans, f[m - 1][j1][j2]); - } - } - return ans; -} -``` - ```ts function cherryPickup(grid: number[][]): number { const m = grid.length; @@ -432,10 +422,6 @@ function cherryPickup(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1463.Cherry Pickup II/README_EN.md b/solution/1400-1499/1463.Cherry Pickup II/README_EN.md index 7aff620e9ecc2..f1bc80ed0a6ed 100644 --- a/solution/1400-1499/1463.Cherry Pickup II/README_EN.md +++ b/solution/1400-1499/1463.Cherry Pickup II/README_EN.md @@ -58,12 +58,10 @@ Total of cherries: 17 + 11 = 28. ## Solutions -Use dynammic programming, define `dp[i][j1][j2]`: The maximum cherries that both robots can take starting on the ith row, and column j1 and j2 of Robot 1 and 2 respectively. +### Solution 1 -### **Python3** - ```python class Solution: def cherryPickup(self, grid: List[List[int]]) -> int: @@ -81,27 +79,6 @@ class Solution: return max(f[-1][j1][j2] for j1, j2 in product(range(n), range(n))) ``` -```python -class Solution: - def cherryPickup(self, grid: List[List[int]]) -> int: - m, n = len(grid), len(grid[0]) - f = [[-1] * n for _ in range(n)] - g = [[-1] * n for _ in range(n)] - f[0][n - 1] = grid[0][0] + grid[0][n - 1] - for i in range(1, m): - for j1 in range(n): - for j2 in range(n): - x = grid[i][j1] + (0 if j1 == j2 else grid[i][j2]) - for y1 in range(j1 - 1, j1 + 2): - for y2 in range(j2 - 1, j2 + 2): - if 0 <= y1 < n and 0 <= y2 < n and f[y1][y2] != -1: - g[j1][j2] = max(g[j1][j2], f[y1][y2] + x) - f, g = g, f - return max(f[j1][j2] for j1, j2 in product(range(n), range(n))) -``` - -### **Java** - ```java class Solution { public int cherryPickup(int[][] grid) { @@ -138,78 +115,174 @@ class Solution { } ``` -```java +```cpp class Solution { - public int cherryPickup(int[][] grid) { - int m = grid.length, n = grid[0].length; - int[][] f = new int[n][n]; - int[][] g = new int[n][n]; - for (int i = 0; i < n; ++i) { - Arrays.fill(f[i], -1); - Arrays.fill(g[i], -1); - } - f[0][n - 1] = grid[0][0] + grid[0][n - 1]; +public: + int cherryPickup(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + int f[m][n][n]; + memset(f, -1, sizeof(f)); + f[0][0][n - 1] = grid[0][0] + grid[0][n - 1]; for (int i = 1; i < m; ++i) { for (int j1 = 0; j1 < n; ++j1) { for (int j2 = 0; j2 < n; ++j2) { int x = grid[i][j1] + (j1 == j2 ? 0 : grid[i][j2]); for (int y1 = j1 - 1; y1 <= j1 + 1; ++y1) { for (int y2 = j2 - 1; y2 <= j2 + 1; ++y2) { - if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[y1][y2] != -1) { - g[j1][j2] = Math.max(g[j1][j2], f[y1][y2] + x); + if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i - 1][y1][y2] != -1) { + f[i][j1][j2] = max(f[i][j1][j2], f[i - 1][y1][y2] + x); } } } } } - int[][] t = f; - f = g; - g = t; } int ans = 0; for (int j1 = 0; j1 < n; ++j1) { for (int j2 = 0; j2 < n; ++j2) { - ans = Math.max(ans, f[j1][j2]); + ans = max(ans, f[m - 1][j1][j2]); } } return ans; } +}; +``` + +```go +func cherryPickup(grid [][]int) int { + m, n := len(grid), len(grid[0]) + f := make([][][]int, m) + for i := range f { + f[i] = make([][]int, n) + for j := range f[i] { + f[i][j] = make([]int, n) + for k := range f[i][j] { + f[i][j][k] = -1 + } + } + } + f[0][0][n-1] = grid[0][0] + grid[0][n-1] + for i := 1; i < m; i++ { + for j1 := 0; j1 < n; j1++ { + for j2 := 0; j2 < n; j2++ { + x := grid[i][j1] + if j1 != j2 { + x += grid[i][j2] + } + for y1 := j1 - 1; y1 <= j1+1; y1++ { + for y2 := j2 - 1; y2 <= j2+1; y2++ { + if y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i-1][y1][y2] != -1 { + f[i][j1][j2] = max(f[i][j1][j2], f[i-1][y1][y2]+x) + } + } + } + } + } + } + ans := 0 + for j1 := 0; j1 < n; j1++ { + for j2 := 0; j2 < n; j2++ { + ans = max(ans, f[m-1][j1][j2]) + } + } + return ans +} +``` + +```ts +function cherryPickup(grid: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const f: number[][][] = new Array(m) + .fill(0) + .map(() => new Array(n).fill(0).map(() => new Array(n).fill(-1))); + f[0][0][n - 1] = grid[0][0] + grid[0][n - 1]; + for (let i = 1; i < m; ++i) { + for (let j1 = 0; j1 < n; ++j1) { + for (let j2 = 0; j2 < n; ++j2) { + const x = grid[i][j1] + (j1 === j2 ? 0 : grid[i][j2]); + for (let y1 = j1 - 1; y1 <= j1 + 1; ++y1) { + for (let y2 = j2 - 1; y2 <= j2 + 1; ++y2) { + if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i - 1][y1][y2] !== -1) { + f[i][j1][j2] = Math.max(f[i][j1][j2], f[i - 1][y1][y2] + x); + } + } + } + } + } + } + let ans = 0; + for (let j1 = 0; j1 < n; ++j1) { + for (let j2 = 0; j2 < n; ++j2) { + ans = Math.max(ans, f[m - 1][j1][j2]); + } + } + return ans; } ``` -### **C++** + + +### Solution 2 -```cpp + + +```python +class Solution: + def cherryPickup(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + f = [[-1] * n for _ in range(n)] + g = [[-1] * n for _ in range(n)] + f[0][n - 1] = grid[0][0] + grid[0][n - 1] + for i in range(1, m): + for j1 in range(n): + for j2 in range(n): + x = grid[i][j1] + (0 if j1 == j2 else grid[i][j2]) + for y1 in range(j1 - 1, j1 + 2): + for y2 in range(j2 - 1, j2 + 2): + if 0 <= y1 < n and 0 <= y2 < n and f[y1][y2] != -1: + g[j1][j2] = max(g[j1][j2], f[y1][y2] + x) + f, g = g, f + return max(f[j1][j2] for j1, j2 in product(range(n), range(n))) +``` + +```java class Solution { -public: - int cherryPickup(vector>& grid) { - int m = grid.size(), n = grid[0].size(); - int f[m][n][n]; - memset(f, -1, sizeof(f)); - f[0][0][n - 1] = grid[0][0] + grid[0][n - 1]; + public int cherryPickup(int[][] grid) { + int m = grid.length, n = grid[0].length; + int[][] f = new int[n][n]; + int[][] g = new int[n][n]; + for (int i = 0; i < n; ++i) { + Arrays.fill(f[i], -1); + Arrays.fill(g[i], -1); + } + f[0][n - 1] = grid[0][0] + grid[0][n - 1]; for (int i = 1; i < m; ++i) { for (int j1 = 0; j1 < n; ++j1) { for (int j2 = 0; j2 < n; ++j2) { int x = grid[i][j1] + (j1 == j2 ? 0 : grid[i][j2]); for (int y1 = j1 - 1; y1 <= j1 + 1; ++y1) { for (int y2 = j2 - 1; y2 <= j2 + 1; ++y2) { - if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i - 1][y1][y2] != -1) { - f[i][j1][j2] = max(f[i][j1][j2], f[i - 1][y1][y2] + x); + if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[y1][y2] != -1) { + g[j1][j2] = Math.max(g[j1][j2], f[y1][y2] + x); } } } } } + int[][] t = f; + f = g; + g = t; } int ans = 0; for (int j1 = 0; j1 < n; ++j1) { for (int j2 = 0; j2 < n; ++j2) { - ans = max(ans, f[m - 1][j1][j2]); + ans = Math.max(ans, f[j1][j2]); } } return ans; } -}; +} ``` ```cpp @@ -246,49 +319,6 @@ public: }; ``` -### **Go** - -```go -func cherryPickup(grid [][]int) int { - m, n := len(grid), len(grid[0]) - f := make([][][]int, m) - for i := range f { - f[i] = make([][]int, n) - for j := range f[i] { - f[i][j] = make([]int, n) - for k := range f[i][j] { - f[i][j][k] = -1 - } - } - } - f[0][0][n-1] = grid[0][0] + grid[0][n-1] - for i := 1; i < m; i++ { - for j1 := 0; j1 < n; j1++ { - for j2 := 0; j2 < n; j2++ { - x := grid[i][j1] - if j1 != j2 { - x += grid[i][j2] - } - for y1 := j1 - 1; y1 <= j1+1; y1++ { - for y2 := j2 - 1; y2 <= j2+1; y2++ { - if y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i-1][y1][y2] != -1 { - f[i][j1][j2] = max(f[i][j1][j2], f[i-1][y1][y2]+x) - } - } - } - } - } - } - ans := 0 - for j1 := 0; j1 < n; j1++ { - for j2 := 0; j2 < n; j2++ { - ans = max(ans, f[m-1][j1][j2]) - } - } - return ans -} -``` - ```go func cherryPickup(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -331,40 +361,6 @@ func cherryPickup(grid [][]int) int { } ``` -### **TypeScript** - -```ts -function cherryPickup(grid: number[][]): number { - const m = grid.length; - const n = grid[0].length; - const f: number[][][] = new Array(m) - .fill(0) - .map(() => new Array(n).fill(0).map(() => new Array(n).fill(-1))); - f[0][0][n - 1] = grid[0][0] + grid[0][n - 1]; - for (let i = 1; i < m; ++i) { - for (let j1 = 0; j1 < n; ++j1) { - for (let j2 = 0; j2 < n; ++j2) { - const x = grid[i][j1] + (j1 === j2 ? 0 : grid[i][j2]); - for (let y1 = j1 - 1; y1 <= j1 + 1; ++y1) { - for (let y2 = j2 - 1; y2 <= j2 + 1; ++y2) { - if (y1 >= 0 && y1 < n && y2 >= 0 && y2 < n && f[i - 1][y1][y2] !== -1) { - f[i][j1][j2] = Math.max(f[i][j1][j2], f[i - 1][y1][y2] + x); - } - } - } - } - } - } - let ans = 0; - for (let j1 = 0; j1 < n; ++j1) { - for (let j2 = 0; j2 < n; ++j2) { - ans = Math.max(ans, f[m - 1][j1][j2]); - } - } - return ans; -} -``` - ```ts function cherryPickup(grid: number[][]): number { const m = grid.length; @@ -397,10 +393,6 @@ function cherryPickup(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/README.md b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/README.md index 65d8730d483de..c89fc899f9174 100644 --- a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/README.md +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/README.md @@ -43,30 +43,14 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 双重循环,枚举所有的下标对,求出 $(nums[i]-1) \times (nums[j]-1)$ 的最大值。其中 $i \neq j$。 时间复杂度 $O(n^2)$。 -**方法二:排序** - -对 $nums$ 进行排序,取最后两个元素,计算乘积 $(nums[n-1]-1) \times (nums[n-2]-1)$ 即可。 - -时间复杂度 $O(nlogn)$。 - -**方法三:一次遍历** - -遍历 $nums$,维护最大值 $a$ 和次大值 $b$。遍历结束,返回 $(a-1) \times (b-1)$。 - -### **Python3** - - - ```python class Solution: def maxProduct(self, nums: List[int]) -> int: @@ -77,29 +61,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxProduct(self, nums: List[int]) -> int: - nums.sort() - return (nums[-1] - 1) * (nums[-2] - 1) -``` - -```python -class Solution: - def maxProduct(self, nums: List[int]) -> int: - a = b = 0 - for v in nums: - if v > a: - a, b = v, a - elif v > b: - b = v - return (a - 1) * (b - 1) -``` - -### **Java** - - - ```java class Solution { public int maxProduct(int[] nums) { @@ -115,35 +76,6 @@ class Solution { } ``` -```java -class Solution { - public int maxProduct(int[] nums) { - Arrays.sort(nums); - int n = nums.length; - return (nums[n - 1] - 1) * (nums[n - 2] - 1); - } -} -``` - -```java -class Solution { - public int maxProduct(int[] nums) { - int a = 0, b = 0; - for (int v : nums) { - if (v > a) { - b = a; - a = v; - } else if (v > b) { - b = v; - } - } - return (a - 1) * (b - 1); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -160,36 +92,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxProduct(vector& nums) { - sort(nums.rbegin(), nums.rend()); - return (nums[0] - 1) * (nums[1] - 1); - } -}; -``` - -```cpp -class Solution { -public: - int maxProduct(vector& nums) { - int a = 0, b = 0; - for (int v : nums) { - if (v > a) { - b = a; - a = v; - } else if (v > b) { - b = v; - } - } - return (a - 1) * (b - 1); - } -}; -``` - -### **Go** - ```go func maxProduct(nums []int) int { ans := 0 @@ -205,49 +107,6 @@ func maxProduct(nums []int) int { } ``` -```go -func maxProduct(nums []int) int { - sort.Ints(nums) - n := len(nums) - return (nums[n-1] - 1) * (nums[n-2] - 1) -} -``` - -```go -func maxProduct(nums []int) int { - a, b := 0, 0 - for _, v := range nums { - if v > a { - b, a = a, v - } else if v > b { - b = v - } - } - return (a - 1) * (b - 1) -} -``` - -### **C** - -```c -int maxProduct(int* nums, int numsSize) { - int max = 0; - int submax = 0; - for (int i = 0; i < numsSize; i++) { - int num = nums[i]; - if (num > max) { - submax = max; - max = num; - } else if (num > submax) { - submax = num; - } - } - return (max - 1) * (submax - 1); -} -``` - -### **TypeScript** - ```ts function maxProduct(nums: number[]): number { const n = nums.length; @@ -264,24 +123,6 @@ function maxProduct(nums: number[]): number { } ``` -```ts -function maxProduct(nums: number[]): number { - let max = 0; - let submax = 0; - for (const num of nums) { - if (num > max) { - submax = max; - max = num; - } else if (num > submax) { - submax = num; - } - } - return (max - 1) * (submax - 1); -} -``` - -### **Rust** - ```rust impl Solution { pub fn max_product(nums: Vec) -> i32 { @@ -300,8 +141,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -324,10 +163,153 @@ class Solution { } ``` -### **...** +```c +int maxProduct(int* nums, int numsSize) { + int max = 0; + int submax = 0; + for (int i = 0; i < numsSize; i++) { + int num = nums[i]; + if (num > max) { + submax = max; + max = num; + } else if (num > submax) { + submax = num; + } + } + return (max - 1) * (submax - 1); +} +``` + + + +### 方法二:排序 + +对 $nums$ 进行排序,取最后两个元素,计算乘积 $(nums[n-1]-1) \times (nums[n-2]-1)$ 即可。 + +时间复杂度 $O(nlogn)$。 + + + +```python +class Solution: + def maxProduct(self, nums: List[int]) -> int: + nums.sort() + return (nums[-1] - 1) * (nums[-2] - 1) +``` + +```java +class Solution { + public int maxProduct(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + return (nums[n - 1] - 1) * (nums[n - 2] - 1); + } +} +``` + +```cpp +class Solution { +public: + int maxProduct(vector& nums) { + sort(nums.rbegin(), nums.rend()); + return (nums[0] - 1) * (nums[1] - 1); + } +}; +``` + +```go +func maxProduct(nums []int) int { + sort.Ints(nums) + n := len(nums) + return (nums[n-1] - 1) * (nums[n-2] - 1) +} +``` + +```ts +function maxProduct(nums: number[]): number { + let max = 0; + let submax = 0; + for (const num of nums) { + if (num > max) { + submax = max; + max = num; + } else if (num > submax) { + submax = num; + } + } + return (max - 1) * (submax - 1); +} +``` + + + +### 方法三:一次遍历 + +遍历 $nums$,维护最大值 $a$ 和次大值 $b$。遍历结束,返回 $(a-1) \times (b-1)$。 + + + +```python +class Solution: + def maxProduct(self, nums: List[int]) -> int: + a = b = 0 + for v in nums: + if v > a: + a, b = v, a + elif v > b: + b = v + return (a - 1) * (b - 1) +``` + +```java +class Solution { + public int maxProduct(int[] nums) { + int a = 0, b = 0; + for (int v : nums) { + if (v > a) { + b = a; + a = v; + } else if (v > b) { + b = v; + } + } + return (a - 1) * (b - 1); + } +} +``` +```cpp +class Solution { +public: + int maxProduct(vector& nums) { + int a = 0, b = 0; + for (int v : nums) { + if (v > a) { + b = a; + a = v; + } else if (v > b) { + b = v; + } + } + return (a - 1) * (b - 1); + } +}; ``` +```go +func maxProduct(nums []int) int { + a, b := 0, 0 + for _, v := range nums { + if v > a { + b, a = a, v + } else if v > b { + b = v + } + } + return (a - 1) * (b - 1) +} ``` + + diff --git a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/README_EN.md b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/README_EN.md index 1eaa0c69a1a5d..da7c9666778b5 100644 --- a/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/README_EN.md +++ b/solution/1400-1499/1464.Maximum Product of Two Elements in an Array/README_EN.md @@ -40,9 +40,9 @@ Given the array of integers nums, you will choose two different ind ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,27 +54,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxProduct(self, nums: List[int]) -> int: - nums.sort() - return (nums[-1] - 1) * (nums[-2] - 1) -``` - -```python -class Solution: - def maxProduct(self, nums: List[int]) -> int: - a = b = 0 - for v in nums: - if v > a: - a, b = v, a - elif v > b: - b = v - return (a - 1) * (b - 1) -``` - -### **Java** - ```java class Solution { public int maxProduct(int[] nums) { @@ -90,35 +69,6 @@ class Solution { } ``` -```java -class Solution { - public int maxProduct(int[] nums) { - Arrays.sort(nums); - int n = nums.length; - return (nums[n - 1] - 1) * (nums[n - 2] - 1); - } -} -``` - -```java -class Solution { - public int maxProduct(int[] nums) { - int a = 0, b = 0; - for (int v : nums) { - if (v > a) { - b = a; - a = v; - } else if (v > b) { - b = v; - } - } - return (a - 1) * (b - 1); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -135,36 +85,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxProduct(vector& nums) { - sort(nums.rbegin(), nums.rend()); - return (nums[0] - 1) * (nums[1] - 1); - } -}; -``` - -```cpp -class Solution { -public: - int maxProduct(vector& nums) { - int a = 0, b = 0; - for (int v : nums) { - if (v > a) { - b = a; - a = v; - } else if (v > b) { - b = v; - } - } - return (a - 1) * (b - 1); - } -}; -``` - -### **Go** - ```go func maxProduct(nums []int) int { ans := 0 @@ -180,49 +100,6 @@ func maxProduct(nums []int) int { } ``` -```go -func maxProduct(nums []int) int { - sort.Ints(nums) - n := len(nums) - return (nums[n-1] - 1) * (nums[n-2] - 1) -} -``` - -```go -func maxProduct(nums []int) int { - a, b := 0, 0 - for _, v := range nums { - if v > a { - b, a = a, v - } else if v > b { - b = v - } - } - return (a - 1) * (b - 1) -} -``` - -### **C** - -```c -int maxProduct(int* nums, int numsSize) { - int max = 0; - int submax = 0; - for (int i = 0; i < numsSize; i++) { - int num = nums[i]; - if (num > max) { - submax = max; - max = num; - } else if (num > submax) { - submax = num; - } - } - return (max - 1) * (submax - 1); -} -``` - -### **TypeScript** - ```ts function maxProduct(nums: number[]): number { const n = nums.length; @@ -239,24 +116,6 @@ function maxProduct(nums: number[]): number { } ``` -```ts -function maxProduct(nums: number[]): number { - let max = 0; - let submax = 0; - for (const num of nums) { - if (num > max) { - submax = max; - max = num; - } else if (num > submax) { - submax = num; - } - } - return (max - 1) * (submax - 1); -} -``` - -### **Rust** - ```rust impl Solution { pub fn max_product(nums: Vec) -> i32 { @@ -275,8 +134,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -299,10 +156,147 @@ class Solution { } ``` -### **...** +```c +int maxProduct(int* nums, int numsSize) { + int max = 0; + int submax = 0; + for (int i = 0; i < numsSize; i++) { + int num = nums[i]; + if (num > max) { + submax = max; + max = num; + } else if (num > submax) { + submax = num; + } + } + return (max - 1) * (submax - 1); +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def maxProduct(self, nums: List[int]) -> int: + nums.sort() + return (nums[-1] - 1) * (nums[-2] - 1) +``` + +```java +class Solution { + public int maxProduct(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + return (nums[n - 1] - 1) * (nums[n - 2] - 1); + } +} +``` + +```cpp +class Solution { +public: + int maxProduct(vector& nums) { + sort(nums.rbegin(), nums.rend()); + return (nums[0] - 1) * (nums[1] - 1); + } +}; +``` + +```go +func maxProduct(nums []int) int { + sort.Ints(nums) + n := len(nums) + return (nums[n-1] - 1) * (nums[n-2] - 1) +} +``` + +```ts +function maxProduct(nums: number[]): number { + let max = 0; + let submax = 0; + for (const num of nums) { + if (num > max) { + submax = max; + max = num; + } else if (num > submax) { + submax = num; + } + } + return (max - 1) * (submax - 1); +} +``` + + + +### Solution 3 + + + +```python +class Solution: + def maxProduct(self, nums: List[int]) -> int: + a = b = 0 + for v in nums: + if v > a: + a, b = v, a + elif v > b: + b = v + return (a - 1) * (b - 1) +``` + +```java +class Solution { + public int maxProduct(int[] nums) { + int a = 0, b = 0; + for (int v : nums) { + if (v > a) { + b = a; + a = v; + } else if (v > b) { + b = v; + } + } + return (a - 1) * (b - 1); + } +} +``` +```cpp +class Solution { +public: + int maxProduct(vector& nums) { + int a = 0, b = 0; + for (int v : nums) { + if (v > a) { + b = a; + a = v; + } else if (v > b) { + b = v; + } + } + return (a - 1) * (b - 1); + } +}; ``` +```go +func maxProduct(nums []int) int { + a, b := 0, 0 + for _, v := range nums { + if v > a { + b, a = a, v + } else if v > b { + b = v + } + } + return (a - 1) * (b - 1) +} ``` + + diff --git a/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/README.md b/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/README.md index e96b6a5891542..18cf6bf1ee1f9 100644 --- a/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/README.md +++ b/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们先分别对 `horizontalCuts` 和 `verticalCuts` 排序,然后分别遍历两个数组,计算相邻两个元素的最大差值,分别记为 $x$ 和 $y$,最后返回 $x \times y$ 即可。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def maxArea( @@ -89,10 +83,6 @@ class Solution: return (x * y) % (10**9 + 7) ``` -### **Java** - - - ```java class Solution { public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +127,6 @@ public: }; ``` -### **Go** - ```go func maxArea(h int, w int, horizontalCuts []int, verticalCuts []int) int { horizontalCuts = append(horizontalCuts, []int{0, h}...) @@ -159,8 +145,6 @@ func maxArea(h int, w int, horizontalCuts []int, verticalCuts []int) int { } ``` -### **TypeScript** - ```ts function maxArea(h: number, w: number, horizontalCuts: number[], verticalCuts: number[]): number { const mod = 1e9 + 7; @@ -179,8 +163,6 @@ function maxArea(h: number, w: number, horizontalCuts: number[], verticalCuts: n } ``` -### **Rust** - ```rust impl Solution { pub fn max_area( @@ -216,10 +198,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/README_EN.md b/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/README_EN.md index cf13df3ad75d2..d7a220c03bb80 100644 --- a/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/README_EN.md +++ b/solution/1400-1499/1465.Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts/README_EN.md @@ -52,7 +52,7 @@ ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting We first sort `horizontalCuts` and `verticalCuts` separately, and then traverse both arrays to calculate the maximum difference between adjacent elements. We denote these maximum differences as $x$ and $y$, respectively. Finally, we return $x \times y$. @@ -62,8 +62,6 @@ The time complexity is $O(m\log m + n\log n)$, where $m$ and $n$ are the lengths -### **Python3** - ```python class Solution: def maxArea( @@ -78,8 +76,6 @@ class Solution: return (x * y) % (10**9 + 7) ``` -### **Java** - ```java class Solution { public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) { @@ -101,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +120,6 @@ public: }; ``` -### **Go** - ```go func maxArea(h int, w int, horizontalCuts []int, verticalCuts []int) int { horizontalCuts = append(horizontalCuts, []int{0, h}...) @@ -146,8 +138,6 @@ func maxArea(h int, w int, horizontalCuts []int, verticalCuts []int) int { } ``` -### **TypeScript** - ```ts function maxArea(h: number, w: number, horizontalCuts: number[], verticalCuts: number[]): number { const mod = 1e9 + 7; @@ -166,8 +156,6 @@ function maxArea(h: number, w: number, horizontalCuts: number[], verticalCuts: n } ``` -### **Rust** - ```rust impl Solution { pub fn max_area( @@ -203,10 +191,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/README.md b/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/README.md index 565880a6a3fc4..d243b291c6839 100644 --- a/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/README.md +++ b/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 题目给定的路线图中有 $n$ 个节点和 $n-1$ 条边,如果我们忽略边的方向,那么这 $n$ 个节点构成了一棵树。而题目需要我们改变某些边的方向,使得每个节点都能到达节点 $0$。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def minReorder(self, n: int, connections: List[List[int]]) -> int: @@ -85,10 +79,6 @@ class Solution: return dfs(0, -1) ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func minReorder(n int, connections [][]int) int { g := make([][][2]int, n) @@ -166,8 +152,6 @@ func minReorder(n int, connections [][]int) int { } ``` -### **TypeScript** - ```ts function minReorder(n: number, connections: number[][]): number { const g: [number, number][][] = Array.from({ length: n }, () => []); @@ -188,8 +172,6 @@ function minReorder(n: number, connections: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_reorder(n: i32, connections: Vec>) -> i32 { @@ -214,10 +196,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/README_EN.md b/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/README_EN.md index 6209892840440..eabe4ee81b84c 100644 --- a/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/README_EN.md +++ b/solution/1400-1499/1466.Reorder Routes to Make All Paths Lead to the City Zero/README_EN.md @@ -51,7 +51,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS The route map given in the problem has $n$ nodes and $n-1$ edges. If we ignore the direction of the edges, then these $n$ nodes form a tree. The problem requires us to change the direction of some edges so that each node can reach node $0$. @@ -63,8 +63,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def minReorder(self, n: int, connections: List[List[int]]) -> int: @@ -78,8 +76,6 @@ class Solution: return dfs(0, -1) ``` -### **Java** - ```java class Solution { private List[] g; @@ -108,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +128,6 @@ public: }; ``` -### **Go** - ```go func minReorder(n int, connections [][]int) int { g := make([][][2]int, n) @@ -157,8 +149,6 @@ func minReorder(n int, connections [][]int) int { } ``` -### **TypeScript** - ```ts function minReorder(n: number, connections: number[][]): number { const g: [number, number][][] = Array.from({ length: n }, () => []); @@ -179,8 +169,6 @@ function minReorder(n: number, connections: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_reorder(n: i32, connections: Vec>) -> i32 { @@ -205,10 +193,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/README.md b/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/README.md index 315bdd2fe173c..ed4fb1dccf22d 100644 --- a/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/README.md +++ b/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:记忆化搜索 + 组合数学** +### 方法一:记忆化搜索 + 组合数学 我们知道 $2n$ 个球,平均分到两个盒子中,总共有 $C_{2n}^n$ 种分法。接下来,我们可以求出每种分法中,两个盒子中球的颜色数相同的情况数。最后,将两者相除即可。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def getProbability(self, balls: List[int]) -> float: @@ -106,10 +100,6 @@ class Solution: return dfs(0, n, 0) / comb(n << 1, n) ``` -### **Java** - - - ```java class Solution { private int n; @@ -158,8 +148,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -200,8 +188,6 @@ public: }; ``` -### **Go** - ```go func getProbability(balls []int) float64 { n, mx := 0, 0 @@ -265,8 +251,6 @@ func getProbability(balls []int) float64 { } ``` -### **TypeScript** - ```ts function getProbability(balls: number[]): number { const n = balls.reduce((a, b) => a + b, 0) >> 1; @@ -310,10 +294,6 @@ function getProbability(balls: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/README_EN.md b/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/README_EN.md index a36570e6871f4..e0e93f6765772 100644 --- a/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/README_EN.md +++ b/solution/1400-1499/1467.Probability of a Two Boxes Having The Same Number of Distinct Balls/README_EN.md @@ -57,9 +57,9 @@ Probability = 108 / 180 = 0.6 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -81,8 +81,6 @@ class Solution: return dfs(0, n, 0) / comb(n << 1, n) ``` -### **Java** - ```java class Solution { private int n; @@ -131,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -173,8 +169,6 @@ public: }; ``` -### **Go** - ```go func getProbability(balls []int) float64 { n, mx := 0, 0 @@ -238,8 +232,6 @@ func getProbability(balls []int) float64 { } ``` -### **TypeScript** - ```ts function getProbability(balls: number[]): number { const n = balls.reduce((a, b) => a + b, 0) >> 1; @@ -283,10 +275,6 @@ function getProbability(balls: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1468.Calculate Salaries/README.md b/solution/1400-1499/1468.Calculate Salaries/README.md index 901f4df2e3615..ac3a95b299f48 100644 --- a/solution/1400-1499/1468.Calculate Salaries/README.md +++ b/solution/1400-1499/1468.Calculate Salaries/README.md @@ -82,12 +82,10 @@ Salaries 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -113,3 +111,5 @@ FROM ``` + + diff --git a/solution/1400-1499/1468.Calculate Salaries/README_EN.md b/solution/1400-1499/1468.Calculate Salaries/README_EN.md index 80133acfd2471..ce38bfef77348 100644 --- a/solution/1400-1499/1468.Calculate Salaries/README_EN.md +++ b/solution/1400-1499/1468.Calculate Salaries/README_EN.md @@ -80,9 +80,9 @@ For example, Salary for Morninngcat (3, 15) after taxes = 7777 - 7777 * (24 / 10 ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -109,3 +109,5 @@ FROM ``` + + diff --git a/solution/1400-1499/1469.Find All The Lonely Nodes/README.md b/solution/1400-1499/1469.Find All The Lonely Nodes/README.md index b35b8e6fca309..d31357db5f693 100644 --- a/solution/1400-1499/1469.Find All The Lonely Nodes/README.md +++ b/solution/1400-1499/1469.Find All The Lonely Nodes/README.md @@ -70,9 +70,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 递归搜索二叉树,如果当前节点的左右子节点都不为空,则继续递归搜索左右子树;如果当前节点的左右子节点有一个为空,则将不为空的子节点的值加入结果数组中,然后继续递归搜索左右子树。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -108,10 +102,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -152,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -184,8 +172,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -216,10 +202,6 @@ func getLonelyNodes(root *TreeNode) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1469.Find All The Lonely Nodes/README_EN.md b/solution/1400-1499/1469.Find All The Lonely Nodes/README_EN.md index bda27d3e4b6e4..c21978c7eaca5 100644 --- a/solution/1400-1499/1469.Find All The Lonely Nodes/README_EN.md +++ b/solution/1400-1499/1469.Find All The Lonely Nodes/README_EN.md @@ -48,9 +48,9 @@ All other nodes are lonely. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -76,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -118,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -150,8 +146,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -182,10 +176,6 @@ func getLonelyNodes(root *TreeNode) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1470.Shuffle the Array/README.md b/solution/1400-1499/1470.Shuffle the Array/README.md index a699903429666..fe8afb06ea530 100644 --- a/solution/1400-1499/1470.Shuffle the Array/README.md +++ b/solution/1400-1499/1470.Shuffle the Array/README.md @@ -43,14 +43,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def shuffle(self, nums: List[int], n: int) -> List[int]: @@ -61,17 +57,6 @@ class Solution: return ans ``` -```python -class Solution: - def shuffle(self, nums: List[int], n: int) -> List[int]: - nums[::2], nums[1::2] = nums[:n], nums[n:] - return nums -``` - -### **Java** - - - ```java class Solution { public int[] shuffle(int[] nums, int n) { @@ -85,20 +70,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function shuffle(nums: number[], n: number): number[] { - let ans = []; - for (let i = 0; i < n; i++) { - ans.push(nums[i], nums[n + i]); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -113,8 +84,6 @@ public: }; ``` -### **Go** - ```go func shuffle(nums []int, n int) []int { var ans []int @@ -126,7 +95,29 @@ func shuffle(nums []int, n int) []int { } ``` -### **C** +```ts +function shuffle(nums: number[], n: number): number[] { + let ans = []; + for (let i = 0; i < n; i++) { + ans.push(nums[i], nums[n + i]); + } + return ans; +} +``` + +```rust +impl Solution { + pub fn shuffle(nums: Vec, n: i32) -> Vec { + let n = n as usize; + let mut res = Vec::new(); + for i in 0..n { + res.push(nums[i]); + res.push(nums[n + i]); + } + res + } +} +``` ```c /** @@ -143,20 +134,17 @@ int* shuffle(int* nums, int numsSize, int n, int* returnSize) { } ``` -### **Rust** + -```rust -impl Solution { - pub fn shuffle(nums: Vec, n: i32) -> Vec { - let n = n as usize; - let mut res = Vec::new(); - for i in 0..n { - res.push(nums[i]); - res.push(nums[n + i]); - } - res - } -} +### 方法二 + + + +```python +class Solution: + def shuffle(self, nums: List[int], n: int) -> List[int]: + nums[::2], nums[1::2] = nums[:n], nums[n:] + return nums ``` ```rust @@ -179,10 +167,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1470.Shuffle the Array/README_EN.md b/solution/1400-1499/1470.Shuffle the Array/README_EN.md index 2b80727c9cb0b..730fac8d1e8c3 100644 --- a/solution/1400-1499/1470.Shuffle the Array/README_EN.md +++ b/solution/1400-1499/1470.Shuffle the Array/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,15 +56,6 @@ class Solution: return ans ``` -```python -class Solution: - def shuffle(self, nums: List[int], n: int) -> List[int]: - nums[::2], nums[1::2] = nums[:n], nums[n:] - return nums -``` - -### **Java** - ```java class Solution { public int[] shuffle(int[] nums, int n) { @@ -78,20 +69,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function shuffle(nums: number[], n: number): number[] { - let ans = []; - for (let i = 0; i < n; i++) { - ans.push(nums[i], nums[n + i]); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -106,8 +83,6 @@ public: }; ``` -### **Go** - ```go func shuffle(nums []int, n int) []int { var ans []int @@ -119,7 +94,29 @@ func shuffle(nums []int, n int) []int { } ``` -### **C** +```ts +function shuffle(nums: number[], n: number): number[] { + let ans = []; + for (let i = 0; i < n; i++) { + ans.push(nums[i], nums[n + i]); + } + return ans; +} +``` + +```rust +impl Solution { + pub fn shuffle(nums: Vec, n: i32) -> Vec { + let n = n as usize; + let mut res = Vec::new(); + for i in 0..n { + res.push(nums[i]); + res.push(nums[n + i]); + } + res + } +} +``` ```c /** @@ -136,20 +133,17 @@ int* shuffle(int* nums, int numsSize, int n, int* returnSize) { } ``` -### **Rust** + -```rust -impl Solution { - pub fn shuffle(nums: Vec, n: i32) -> Vec { - let n = n as usize; - let mut res = Vec::new(); - for i in 0..n { - res.push(nums[i]); - res.push(nums[n + i]); - } - res - } -} +### Solution 2 + + + +```python +class Solution: + def shuffle(self, nums: List[int], n: int) -> List[int]: + nums[::2], nums[1::2] = nums[:n], nums[n:] + return nums ``` ```rust @@ -172,10 +166,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1471.The k Strongest Values in an Array/README.md b/solution/1400-1499/1471.The k Strongest Values in an Array/README.md index f5c3bbfc1a0c4..3de5379d33e7f 100644 --- a/solution/1400-1499/1471.The k Strongest Values in an Array/README.md +++ b/solution/1400-1499/1471.The k Strongest Values in an Array/README.md @@ -72,18 +72,12 @@ ## 解法 - - -**方法一:自定义排序** +### 方法一:自定义排序 时间复杂度 $O(2nlogn)$。 -### **Python3** - - - ```python class Solution: def getStrongest(self, arr: List[int], k: int) -> List[int]: @@ -93,10 +87,6 @@ class Solution: return arr[:k] ``` -### **Java** - - - ```java class Solution { public int[] getStrongest(int[] arr, int k) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func getStrongest(arr []int, k int) []int { sort.Ints(arr) @@ -162,10 +148,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1471.The k Strongest Values in an Array/README_EN.md b/solution/1400-1499/1471.The k Strongest Values in an Array/README_EN.md index 70df68c9138b5..691309ab79081 100644 --- a/solution/1400-1499/1471.The k Strongest Values in an Array/README_EN.md +++ b/solution/1400-1499/1471.The k Strongest Values in an Array/README_EN.md @@ -56,9 +56,9 @@ Any permutation of [11,8,6,6,7] is accepted. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return arr[:k] ``` -### **Java** - ```java class Solution { public int[] getStrongest(int[] arr, int k) { @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func getStrongest(arr []int, k int) []int { sort.Ints(arr) @@ -136,10 +130,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1472.Design Browser History/README.md b/solution/1400-1499/1472.Design Browser History/README.md index 215ecb6eb3d84..b96a4a8e8a620 100644 --- a/solution/1400-1499/1472.Design Browser History/README.md +++ b/solution/1400-1499/1472.Design Browser History/README.md @@ -55,18 +55,12 @@ browserHistory.back(7); // 你原本在浏览 "google.com ## 解法 - - -**方法一:栈** +### 方法一:栈 使用两个栈模拟前进与后退操作。 -### **Python3** - - - ```python class BrowserHistory: def __init__(self, homepage: str): @@ -98,10 +92,6 @@ class BrowserHistory: # param_3 = obj.forward(steps) ``` -### **Java** - - - ```java class BrowserHistory { private Deque stk1 = new ArrayDeque<>(); @@ -140,8 +130,6 @@ class BrowserHistory { */ ``` -### **C++** - ```cpp class BrowserHistory { public: @@ -183,8 +171,6 @@ public: */ ``` -### **Go** - ```go type BrowserHistory struct { stk1 []string @@ -227,10 +213,6 @@ func (this *BrowserHistory) Forward(steps int) string { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1472.Design Browser History/README_EN.md b/solution/1400-1499/1472.Design Browser History/README_EN.md index 9bc9652c11ecf..edbca0061972b 100644 --- a/solution/1400-1499/1472.Design Browser History/README_EN.md +++ b/solution/1400-1499/1472.Design Browser History/README_EN.md @@ -52,9 +52,9 @@ browserHistory.back(7); // You are in "google.com", ## Solutions - +### Solution 1 -### **Python3** + ```python class BrowserHistory: @@ -87,8 +87,6 @@ class BrowserHistory: # param_3 = obj.forward(steps) ``` -### **Java** - ```java class BrowserHistory { private Deque stk1 = new ArrayDeque<>(); @@ -127,8 +125,6 @@ class BrowserHistory { */ ``` -### **C++** - ```cpp class BrowserHistory { public: @@ -170,8 +166,6 @@ public: */ ``` -### **Go** - ```go type BrowserHistory struct { stk1 []string @@ -214,10 +208,6 @@ func (this *BrowserHistory) Forward(steps int) string { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1473.Paint House III/README.md b/solution/1400-1499/1473.Paint House III/README.md index 4298e0bf8789a..91f6f89e8bb34 100644 --- a/solution/1400-1499/1473.Paint House III/README.md +++ b/solution/1400-1499/1473.Paint House III/README.md @@ -72,9 +72,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j][k]$ 表示将下标 $[0,..i]$ 的房子涂上颜色,最后一个房子的颜色为 $j$,且恰好形成 $k$ 个街区的最小花费。那么答案就是 $f[m-1][j][target]$,其中 $j$ 的取值范围为 $[1,..n]$。初始时,我们判断下标为 $0$ 的房子是否已经涂色,如果未涂色,那么 $f[0][j][1] = cost[0][j - 1]$,其中 $j \in [1,..n]$。如果已经涂色,那么 $f[0][houses[0]][1] = 0$。其他的 $f[i][j][k]$ 的值都初始化为 $\infty$。 @@ -98,10 +96,6 @@ $$ -### **Python3** - - - ```python class Solution: def minCost( @@ -139,10 +133,6 @@ class Solution: return -1 if ans >= inf else ans ``` -### **Java** - - - ```java class Solution { public int minCost(int[] houses, int[][] cost, int m, int n, int target) { @@ -196,8 +186,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -246,8 +234,6 @@ public: }; ``` -### **Go** - ```go func minCost(houses []int, cost [][]int, m int, n int, target int) int { f := make([][][]int, m) @@ -305,8 +291,6 @@ func minCost(houses []int, cost [][]int, m int, n int, target int) int { } ``` -### **TypeScript** - ```ts function minCost(houses: number[], cost: number[][], m: number, n: number, target: number): number { const inf = 1 << 30; @@ -354,10 +338,6 @@ function minCost(houses: number[], cost: number[][], m: number, n: number, targe } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1473.Paint House III/README_EN.md b/solution/1400-1499/1473.Paint House III/README_EN.md index 396a63681f72f..218df3cb22ac5 100644 --- a/solution/1400-1499/1473.Paint House III/README_EN.md +++ b/solution/1400-1499/1473.Paint House III/README_EN.md @@ -65,9 +65,9 @@ Cost of paint the first and last house (10 + 1) = 11. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -106,8 +106,6 @@ class Solution: return -1 if ans >= inf else ans ``` -### **Java** - ```java class Solution { public int minCost(int[] houses, int[][] cost, int m, int n, int target) { @@ -161,8 +159,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -211,8 +207,6 @@ public: }; ``` -### **Go** - ```go func minCost(houses []int, cost [][]int, m int, n int, target int) int { f := make([][][]int, m) @@ -270,8 +264,6 @@ func minCost(houses []int, cost [][]int, m int, n int, target int) int { } ``` -### **TypeScript** - ```ts function minCost(houses: number[], cost: number[][], m: number, n: number, target: number): number { const inf = 1 << 30; @@ -319,10 +311,6 @@ function minCost(houses: number[], cost: number[][], m: number, n: number, targe } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README.md b/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README.md index 9eda65f02bca1..66875258108bb 100644 --- a/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README.md +++ b/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README.md @@ -70,9 +70,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 按照题意模拟,遍历链表,每次遍历 $m$ 个节点,然后删除 $n$ 个节点,直到链表尾部。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -108,10 +102,6 @@ class Solution: return head ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -145,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -181,8 +169,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -214,10 +200,6 @@ func deleteNodes(head *ListNode, m int, n int) *ListNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README_EN.md b/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README_EN.md index cfc30f67e09a3..ed2a15f6388e6 100644 --- a/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README_EN.md +++ b/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README_EN.md @@ -51,9 +51,9 @@ Head of the linked list after removing nodes is returned. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -79,8 +79,6 @@ class Solution: return head ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -150,8 +146,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -183,10 +177,6 @@ func deleteNodes(head *ListNode, m int, n int) *ListNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README.md b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README.md index c7ee779960dcb..3df7c7edcf19c 100644 --- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README.md +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README.md @@ -49,36 +49,14 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 按题意模拟,采用双重循环枚举 `i` 和 `j`。 时间复杂度为 $O(n^2)$,忽略结果数组的空间消耗,空间复杂度 $O(1)$。 -**方法二:单调栈** - -单调栈常见模型:找出每个数左/右边**离它最近的**且**比它大/小的数**。模板: - -```python -stk = [] -for i in range(n): - while stk and check(stk[-1], i): - stk.pop() - stk.append(i) -``` - -本题我们可以采用正序、逆序两种方式遍历数组 `prices`。 - -时间复杂度 $O(n)$,其中 $n$ 表示数组 `prices` 的长度。 - -### **Python3** - - - ```python class Solution: def finalPrices(self, prices: List[int]) -> List[int]: @@ -92,36 +70,6 @@ class Solution: return ans ``` -```python -class Solution: - def finalPrices(self, prices: List[int]) -> List[int]: - stk = [] - ans = prices[:] - for i, v in enumerate(prices): - while stk and prices[stk[-1]] >= v: - ans[stk.pop()] -= v - stk.append(i) - return ans -``` - -```python -class Solution: - def finalPrices(self, prices: List[int]) -> List[int]: - stk = [] - ans = prices[:] - for i in range(len(prices) - 1, -1, -1): - while stk and prices[stk[-1]] > prices[i]: - stk.pop() - if stk: - ans[i] -= prices[stk[-1]] - stk.append(i) - return ans -``` - -### **Java** - - - ```java class Solution { public int[] finalPrices(int[] prices) { @@ -141,47 +89,6 @@ class Solution { } ``` -```java -class Solution { - public int[] finalPrices(int[] prices) { - Deque stk = new ArrayDeque<>(); - int n = prices.length; - int[] ans = new int[n]; - for (int i = 0; i < n; ++i) { - ans[i] = prices[i]; - while (!stk.isEmpty() && prices[stk.peek()] >= prices[i]) { - ans[stk.pop()] -= prices[i]; - } - stk.push(i); - } - return ans; - } -} -``` - -```java -class Solution { - public int[] finalPrices(int[] prices) { - Deque stk = new ArrayDeque<>(); - int n = prices.length; - int[] ans = new int[n]; - for (int i = n - 1; i >= 0; --i) { - ans[i] = prices[i]; - while (!stk.isEmpty() && prices[stk.peek()] > prices[i]) { - stk.pop(); - } - if (!stk.isEmpty()) { - ans[i] -= prices[stk.peek()]; - } - stk.push(i); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -202,48 +109,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector finalPrices(vector& prices) { - stack stk; - vector ans = prices; - for (int i = 0; i < prices.size(); ++i) { - while (!stk.empty() && prices[stk.top()] >= prices[i]) { - ans[stk.top()] -= prices[i]; - stk.pop(); - } - stk.push(i); - } - return ans; - } -}; -``` - -```cpp -class Solution { -public: - vector finalPrices(vector& prices) { - stack stk; - int n = prices.size(); - vector ans(n); - for (int i = n - 1; i >= 0; --i) { - ans[i] = prices[i]; - while (!stk.empty() && prices[stk.top()] > prices[i]) { - stk.pop(); - } - if (!stk.empty()) { - ans[i] -= prices[stk.top()]; - } - stk.push(i); - } - return ans; - } -}; -``` - -### **Go** - ```go func finalPrices(prices []int) []int { n := len(prices) @@ -261,44 +126,6 @@ func finalPrices(prices []int) []int { } ``` -```go -func finalPrices(prices []int) []int { - var stk []int - n := len(prices) - ans := make([]int, n) - for i, v := range prices { - ans[i] = v - for len(stk) > 0 && prices[stk[len(stk)-1]] >= v { - ans[stk[len(stk)-1]] -= v - stk = stk[:len(stk)-1] - } - stk = append(stk, i) - } - return ans -} -``` - -```go -func finalPrices(prices []int) []int { - stk := []int{} - n := len(prices) - ans := make([]int, n) - for i := n - 1; i >= 0; i-- { - ans[i] = prices[i] - for len(stk) > 0 && prices[stk[len(stk)-1]] > prices[i] { - stk = stk[:len(stk)-1] - } - if len(stk) > 0 { - ans[i] -= prices[stk[len(stk)-1]] - } - stk = append(stk, i) - } - return ans -} -``` - -### **TypeScript** - ```ts function finalPrices(prices: number[]): number[] { const n = prices.length; @@ -316,41 +143,6 @@ function finalPrices(prices: number[]): number[] { } ``` -```ts -function finalPrices(prices: number[]): number[] { - const n = prices.length; - const stk = []; - const ans = new Array(n); - for (let i = 0; i < n; ++i) { - ans[i] = prices[i]; - while (stk.length && prices[stk[stk.length - 1]] >= prices[i]) { - ans[stk.pop()] -= prices[i]; - } - stk.push(i); - } - return ans; -} -``` - -```ts -function finalPrices(prices: number[]): number[] { - const n = prices.length; - const stack = []; - const res = new Array(n); - for (let i = n - 1; i >= 0; i--) { - const price = prices[i]; - while (stack.length !== 0 && stack[stack.length - 1] > price) { - stack.pop(); - } - res[i] = price - (stack[stack.length - 1] ?? 0); - stack.push(price); - } - return res; -} -``` - -### **Rust** - ```rust impl Solution { pub fn final_prices(prices: Vec) -> Vec { @@ -370,7 +162,23 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {number[]} prices + * @return {number[]} + */ +var finalPrices = function (prices) { + for (let i = 0; i < prices.length; i++) { + for (let j = i + 1; j < prices.length; j++) { + if (prices[i] >= prices[j]) { + prices[i] -= prices[j]; + break; + } + } + } + return prices; +}; +``` ```php class Solution { @@ -392,30 +200,206 @@ class Solution { } ``` -### **JavaScript** + -```js -/** - * @param {number[]} prices - * @return {number[]} - */ -var finalPrices = function (prices) { - for (let i = 0; i < prices.length; i++) { - for (let j = i + 1; j < prices.length; j++) { - if (prices[i] >= prices[j]) { - prices[i] -= prices[j]; - break; +### 方法二:单调栈 + +单调栈常见模型:找出每个数左/右边**离它最近的**且**比它大/小的数**。模板: + +```python +stk = [] +for i in range(n): + while stk and check(stk[-1], i): + stk.pop() + stk.append(i) +``` + +本题我们可以采用正序、逆序两种方式遍历数组 `prices`。 + +时间复杂度 $O(n)$,其中 $n$ 表示数组 `prices` 的长度。 + + + +```python +class Solution: + def finalPrices(self, prices: List[int]) -> List[int]: + stk = [] + ans = prices[:] + for i, v in enumerate(prices): + while stk and prices[stk[-1]] >= v: + ans[stk.pop()] -= v + stk.append(i) + return ans +``` + +```java +class Solution { + public int[] finalPrices(int[] prices) { + Deque stk = new ArrayDeque<>(); + int n = prices.length; + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + ans[i] = prices[i]; + while (!stk.isEmpty() && prices[stk.peek()] >= prices[i]) { + ans[stk.pop()] -= prices[i]; } + stk.push(i); } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector finalPrices(vector& prices) { + stack stk; + vector ans = prices; + for (int i = 0; i < prices.size(); ++i) { + while (!stk.empty() && prices[stk.top()] >= prices[i]) { + ans[stk.top()] -= prices[i]; + stk.pop(); + } + stk.push(i); + } + return ans; } - return prices; }; ``` -### **...** +```go +func finalPrices(prices []int) []int { + var stk []int + n := len(prices) + ans := make([]int, n) + for i, v := range prices { + ans[i] = v + for len(stk) > 0 && prices[stk[len(stk)-1]] >= v { + ans[stk[len(stk)-1]] -= v + stk = stk[:len(stk)-1] + } + stk = append(stk, i) + } + return ans +} +``` +```ts +function finalPrices(prices: number[]): number[] { + const n = prices.length; + const stk = []; + const ans = new Array(n); + for (let i = 0; i < n; ++i) { + ans[i] = prices[i]; + while (stk.length && prices[stk[stk.length - 1]] >= prices[i]) { + ans[stk.pop()] -= prices[i]; + } + stk.push(i); + } + return ans; +} +``` + + + +### 方法三 + + + +```python +class Solution: + def finalPrices(self, prices: List[int]) -> List[int]: + stk = [] + ans = prices[:] + for i in range(len(prices) - 1, -1, -1): + while stk and prices[stk[-1]] > prices[i]: + stk.pop() + if stk: + ans[i] -= prices[stk[-1]] + stk.append(i) + return ans ``` +```java +class Solution { + public int[] finalPrices(int[] prices) { + Deque stk = new ArrayDeque<>(); + int n = prices.length; + int[] ans = new int[n]; + for (int i = n - 1; i >= 0; --i) { + ans[i] = prices[i]; + while (!stk.isEmpty() && prices[stk.peek()] > prices[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + ans[i] -= prices[stk.peek()]; + } + stk.push(i); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector finalPrices(vector& prices) { + stack stk; + int n = prices.size(); + vector ans(n); + for (int i = n - 1; i >= 0; --i) { + ans[i] = prices[i]; + while (!stk.empty() && prices[stk.top()] > prices[i]) { + stk.pop(); + } + if (!stk.empty()) { + ans[i] -= prices[stk.top()]; + } + stk.push(i); + } + return ans; + } +}; +``` + +```go +func finalPrices(prices []int) []int { + stk := []int{} + n := len(prices) + ans := make([]int, n) + for i := n - 1; i >= 0; i-- { + ans[i] = prices[i] + for len(stk) > 0 && prices[stk[len(stk)-1]] > prices[i] { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + ans[i] -= prices[stk[len(stk)-1]] + } + stk = append(stk, i) + } + return ans +} +``` + +```ts +function finalPrices(prices: number[]): number[] { + const n = prices.length; + const stack = []; + const res = new Array(n); + for (let i = n - 1; i >= 0; i--) { + const price = prices[i]; + while (stack.length !== 0 && stack[stack.length - 1] > price) { + stack.pop(); + } + res[i] = price - (stack[stack.length - 1] ?? 0); + stack.push(price); + } + return res; +} ``` + + diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README_EN.md b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README_EN.md index 002cb1348e8b4..eb4fefbb57b2c 100644 --- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README_EN.md +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README_EN.md @@ -48,9 +48,9 @@ For items 3 and 4 you will not receive any discount at all. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,34 +65,6 @@ class Solution: return ans ``` -```python -class Solution: - def finalPrices(self, prices: List[int]) -> List[int]: - stk = [] - ans = prices[:] - for i, v in enumerate(prices): - while stk and prices[stk[-1]] >= v: - ans[stk.pop()] -= v - stk.append(i) - return ans -``` - -```python -class Solution: - def finalPrices(self, prices: List[int]) -> List[int]: - stk = [] - ans = prices[:] - for i in range(len(prices) - 1, -1, -1): - while stk and prices[stk[-1]] > prices[i]: - stk.pop() - if stk: - ans[i] -= prices[stk[-1]] - stk.append(i) - return ans -``` - -### **Java** - ```java class Solution { public int[] finalPrices(int[] prices) { @@ -112,47 +84,6 @@ class Solution { } ``` -```java -class Solution { - public int[] finalPrices(int[] prices) { - Deque stk = new ArrayDeque<>(); - int n = prices.length; - int[] ans = new int[n]; - for (int i = 0; i < n; ++i) { - ans[i] = prices[i]; - while (!stk.isEmpty() && prices[stk.peek()] >= prices[i]) { - ans[stk.pop()] -= prices[i]; - } - stk.push(i); - } - return ans; - } -} -``` - -```java -class Solution { - public int[] finalPrices(int[] prices) { - Deque stk = new ArrayDeque<>(); - int n = prices.length; - int[] ans = new int[n]; - for (int i = n - 1; i >= 0; --i) { - ans[i] = prices[i]; - while (!stk.isEmpty() && prices[stk.peek()] > prices[i]) { - stk.pop(); - } - if (!stk.isEmpty()) { - ans[i] -= prices[stk.peek()]; - } - stk.push(i); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -173,48 +104,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector finalPrices(vector& prices) { - stack stk; - vector ans = prices; - for (int i = 0; i < prices.size(); ++i) { - while (!stk.empty() && prices[stk.top()] >= prices[i]) { - ans[stk.top()] -= prices[i]; - stk.pop(); - } - stk.push(i); - } - return ans; - } -}; -``` - -```cpp -class Solution { -public: - vector finalPrices(vector& prices) { - stack stk; - int n = prices.size(); - vector ans(n); - for (int i = n - 1; i >= 0; --i) { - ans[i] = prices[i]; - while (!stk.empty() && prices[stk.top()] > prices[i]) { - stk.pop(); - } - if (!stk.empty()) { - ans[i] -= prices[stk.top()]; - } - stk.push(i); - } - return ans; - } -}; -``` - -### **Go** - ```go func finalPrices(prices []int) []int { n := len(prices) @@ -232,44 +121,6 @@ func finalPrices(prices []int) []int { } ``` -```go -func finalPrices(prices []int) []int { - var stk []int - n := len(prices) - ans := make([]int, n) - for i, v := range prices { - ans[i] = v - for len(stk) > 0 && prices[stk[len(stk)-1]] >= v { - ans[stk[len(stk)-1]] -= v - stk = stk[:len(stk)-1] - } - stk = append(stk, i) - } - return ans -} -``` - -```go -func finalPrices(prices []int) []int { - stk := []int{} - n := len(prices) - ans := make([]int, n) - for i := n - 1; i >= 0; i-- { - ans[i] = prices[i] - for len(stk) > 0 && prices[stk[len(stk)-1]] > prices[i] { - stk = stk[:len(stk)-1] - } - if len(stk) > 0 { - ans[i] -= prices[stk[len(stk)-1]] - } - stk = append(stk, i) - } - return ans -} -``` - -### **TypeScript** - ```ts function finalPrices(prices: number[]): number[] { const n = prices.length; @@ -287,41 +138,6 @@ function finalPrices(prices: number[]): number[] { } ``` -```ts -function finalPrices(prices: number[]): number[] { - const n = prices.length; - const stk = []; - const ans = new Array(n); - for (let i = 0; i < n; ++i) { - ans[i] = prices[i]; - while (stk.length && prices[stk[stk.length - 1]] >= prices[i]) { - ans[stk.pop()] -= prices[i]; - } - stk.push(i); - } - return ans; -} -``` - -```ts -function finalPrices(prices: number[]): number[] { - const n = prices.length; - const stack = []; - const res = new Array(n); - for (let i = n - 1; i >= 0; i--) { - const price = prices[i]; - while (stack.length !== 0 && stack[stack.length - 1] > price) { - stack.pop(); - } - res[i] = price - (stack[stack.length - 1] ?? 0); - stack.push(price); - } - return res; -} -``` - -### **Rust** - ```rust impl Solution { pub fn final_prices(prices: Vec) -> Vec { @@ -341,7 +157,23 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {number[]} prices + * @return {number[]} + */ +var finalPrices = function (prices) { + for (let i = 0; i < prices.length; i++) { + for (let j = i + 1; j < prices.length; j++) { + if (prices[i] >= prices[j]) { + prices[i] -= prices[j]; + break; + } + } + } + return prices; +}; +``` ```php class Solution { @@ -363,30 +195,192 @@ class Solution { } ``` -### **JavaScript** + -```js -/** - * @param {number[]} prices - * @return {number[]} - */ -var finalPrices = function (prices) { - for (let i = 0; i < prices.length; i++) { - for (let j = i + 1; j < prices.length; j++) { - if (prices[i] >= prices[j]) { - prices[i] -= prices[j]; - break; +### Solution 2 + + + +```python +class Solution: + def finalPrices(self, prices: List[int]) -> List[int]: + stk = [] + ans = prices[:] + for i, v in enumerate(prices): + while stk and prices[stk[-1]] >= v: + ans[stk.pop()] -= v + stk.append(i) + return ans +``` + +```java +class Solution { + public int[] finalPrices(int[] prices) { + Deque stk = new ArrayDeque<>(); + int n = prices.length; + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + ans[i] = prices[i]; + while (!stk.isEmpty() && prices[stk.peek()] >= prices[i]) { + ans[stk.pop()] -= prices[i]; } + stk.push(i); } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector finalPrices(vector& prices) { + stack stk; + vector ans = prices; + for (int i = 0; i < prices.size(); ++i) { + while (!stk.empty() && prices[stk.top()] >= prices[i]) { + ans[stk.top()] -= prices[i]; + stk.pop(); + } + stk.push(i); + } + return ans; } - return prices; }; ``` -### **...** +```go +func finalPrices(prices []int) []int { + var stk []int + n := len(prices) + ans := make([]int, n) + for i, v := range prices { + ans[i] = v + for len(stk) > 0 && prices[stk[len(stk)-1]] >= v { + ans[stk[len(stk)-1]] -= v + stk = stk[:len(stk)-1] + } + stk = append(stk, i) + } + return ans +} +``` +```ts +function finalPrices(prices: number[]): number[] { + const n = prices.length; + const stk = []; + const ans = new Array(n); + for (let i = 0; i < n; ++i) { + ans[i] = prices[i]; + while (stk.length && prices[stk[stk.length - 1]] >= prices[i]) { + ans[stk.pop()] -= prices[i]; + } + stk.push(i); + } + return ans; +} ``` + + +### Solution 3 + + + +```python +class Solution: + def finalPrices(self, prices: List[int]) -> List[int]: + stk = [] + ans = prices[:] + for i in range(len(prices) - 1, -1, -1): + while stk and prices[stk[-1]] > prices[i]: + stk.pop() + if stk: + ans[i] -= prices[stk[-1]] + stk.append(i) + return ans +``` + +```java +class Solution { + public int[] finalPrices(int[] prices) { + Deque stk = new ArrayDeque<>(); + int n = prices.length; + int[] ans = new int[n]; + for (int i = n - 1; i >= 0; --i) { + ans[i] = prices[i]; + while (!stk.isEmpty() && prices[stk.peek()] > prices[i]) { + stk.pop(); + } + if (!stk.isEmpty()) { + ans[i] -= prices[stk.peek()]; + } + stk.push(i); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector finalPrices(vector& prices) { + stack stk; + int n = prices.size(); + vector ans(n); + for (int i = n - 1; i >= 0; --i) { + ans[i] = prices[i]; + while (!stk.empty() && prices[stk.top()] > prices[i]) { + stk.pop(); + } + if (!stk.empty()) { + ans[i] -= prices[stk.top()]; + } + stk.push(i); + } + return ans; + } +}; +``` + +```go +func finalPrices(prices []int) []int { + stk := []int{} + n := len(prices) + ans := make([]int, n) + for i := n - 1; i >= 0; i-- { + ans[i] = prices[i] + for len(stk) > 0 && prices[stk[len(stk)-1]] > prices[i] { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + ans[i] -= prices[stk[len(stk)-1]] + } + stk = append(stk, i) + } + return ans +} +``` + +```ts +function finalPrices(prices: number[]): number[] { + const n = prices.length; + const stack = []; + const res = new Array(n); + for (let i = n - 1; i >= 0; i--) { + const price = prices[i]; + while (stack.length !== 0 && stack[stack.length - 1] > price) { + stack.pop(); + } + res[i] = price - (stack[stack.length - 1] ?? 0); + stack.push(price); + } + return res; +} ``` + + diff --git a/solution/1400-1499/1476.Subrectangle Queries/README.md b/solution/1400-1499/1476.Subrectangle Queries/README.md index 4ea54a90e1dac..5d254b9b4cc45 100644 --- a/solution/1400-1499/1476.Subrectangle Queries/README.md +++ b/solution/1400-1499/1476.Subrectangle Queries/README.md @@ -90,16 +90,10 @@ subrectangleQueries.getValue(2, 2); // 返回 20 ## 解法 - - -用历史记录列表保存修改历史。 +### 方法一 -### **Python3** - - - ```python class SubrectangleQueries: def __init__(self, rectangle: List[List[int]]): @@ -124,10 +118,6 @@ class SubrectangleQueries: # param_2 = obj.getValue(row,col) ``` -### **Java** - - - ```java class SubrectangleQueries { private int[][] g; @@ -159,8 +149,6 @@ class SubrectangleQueries { */ ``` -### **C++** - ```cpp class SubrectangleQueries { public: @@ -194,8 +182,6 @@ public: */ ``` -### **Go** - ```go type SubrectangleQueries struct { g [][]int @@ -228,8 +214,6 @@ func (this *SubrectangleQueries) GetValue(row int, col int) int { */ ``` -### **TypeScript** - ```ts class SubrectangleQueries { g: number[][]; @@ -268,10 +252,6 @@ class SubrectangleQueries { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1476.Subrectangle Queries/README_EN.md b/solution/1400-1499/1476.Subrectangle Queries/README_EN.md index b814ea5eaeb54..f88299a9daab5 100644 --- a/solution/1400-1499/1476.Subrectangle Queries/README_EN.md +++ b/solution/1400-1499/1476.Subrectangle Queries/README_EN.md @@ -88,12 +88,10 @@ subrectangleQueries.getValue(2, 2); // return 20 ## Solutions -Use history list to save the updated record. +### Solution 1 -### **Python3** - ```python class SubrectangleQueries: def __init__(self, rectangle: List[List[int]]): @@ -118,8 +116,6 @@ class SubrectangleQueries: # param_2 = obj.getValue(row,col) ``` -### **Java** - ```java class SubrectangleQueries { private int[][] g; @@ -151,8 +147,6 @@ class SubrectangleQueries { */ ``` -### **C++** - ```cpp class SubrectangleQueries { public: @@ -186,8 +180,6 @@ public: */ ``` -### **Go** - ```go type SubrectangleQueries struct { g [][]int @@ -220,8 +212,6 @@ func (this *SubrectangleQueries) GetValue(row int, col int) int { */ ``` -### **TypeScript** - ```ts class SubrectangleQueries { g: number[][]; @@ -260,10 +250,6 @@ class SubrectangleQueries { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README.md b/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README.md index 3dfe98bbe7b0c..f0ca1190b3065 100644 --- a/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README.md +++ b/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:哈希表 + 前缀和 + 动态规划** +### 方法一:哈希表 + 前缀和 + 动态规划 我们可以使用哈希表 $d$ 记录前缀和最近一次出现的位置,初始时 $d[0]=0$。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: @@ -99,10 +93,6 @@ class Solution: return -1 if ans > n else ans ``` -### **Java** - - - ```java class Solution { public int minSumOfLengths(int[] arr, int target) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func minSumOfLengths(arr []int, target int) int { d := map[int]int{0: 0} @@ -185,10 +171,6 @@ func minSumOfLengths(arr []int, target int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README_EN.md b/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README_EN.md index 989c7a60567fe..b9d2ba6a553ad 100644 --- a/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README_EN.md +++ b/solution/1400-1499/1477.Find Two Non-overlapping Sub-arrays Each With Target Sum/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return -1 if ans > n else ans ``` -### **Java** - ```java class Solution { public int minSumOfLengths(int[] arr, int target) { @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +121,6 @@ public: }; ``` -### **Go** - ```go func minSumOfLengths(arr []int, target int) int { d := map[int]int{0: 0} @@ -152,10 +146,6 @@ func minSumOfLengths(arr []int, target int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1478.Allocate Mailboxes/README.md b/solution/1400-1499/1478.Allocate Mailboxes/README.md index bf350ace5562c..fc9068a7356bc 100644 --- a/solution/1400-1499/1478.Allocate Mailboxes/README.md +++ b/solution/1400-1499/1478.Allocate Mailboxes/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示前 $i+1$ 栋房子,安排了 $j$ 个邮筒时,每栋房子与离它最近的邮筒之间的距离的最小总和。初始时 $f[i][j]=\infty$,答案即为 $f[n-1][k]$。 @@ -82,10 +80,6 @@ $$ -### **Python3** - - - ```python class Solution: def minDistance(self, houses: List[int], k: int) -> int: @@ -104,10 +98,6 @@ class Solution: return f[-1][k] ``` -### **Java** - - - ```java class Solution { public int minDistance(int[] houses, int k) { @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +155,6 @@ public: }; ``` -### **Go** - ```go func minDistance(houses []int, k int) int { sort.Ints(houses) @@ -200,10 +186,6 @@ func minDistance(houses []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1478.Allocate Mailboxes/README_EN.md b/solution/1400-1499/1478.Allocate Mailboxes/README_EN.md index e30243189a766..ed1e71a6b1850 100644 --- a/solution/1400-1499/1478.Allocate Mailboxes/README_EN.md +++ b/solution/1400-1499/1478.Allocate Mailboxes/README_EN.md @@ -40,9 +40,9 @@ Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return f[-1][k] ``` -### **Java** - ```java class Solution { public int minDistance(int[] houses, int k) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func minDistance(houses []int, k int) int { sort.Ints(houses) @@ -156,10 +150,6 @@ func minDistance(houses []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1479.Sales by Day of the Week/README.md b/solution/1400-1499/1479.Sales by Day of the Week/README.md index 9632b165f7e6d..ec7a6c488d22a 100644 --- a/solution/1400-1499/1479.Sales by Day of the Week/README.md +++ b/solution/1400-1499/1479.Sales by Day of the Week/README.md @@ -100,12 +100,10 @@ Orders 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -125,3 +123,5 @@ ORDER BY category; ``` + + diff --git a/solution/1400-1499/1479.Sales by Day of the Week/README_EN.md b/solution/1400-1499/1479.Sales by Day of the Week/README_EN.md index b1f41e4f28315..adbf90c3c3423 100644 --- a/solution/1400-1499/1479.Sales by Day of the Week/README_EN.md +++ b/solution/1400-1499/1479.Sales by Day of the Week/README_EN.md @@ -100,9 +100,9 @@ There are no sales of T-shirts. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -123,3 +123,5 @@ ORDER BY category; ``` + + diff --git a/solution/1400-1499/1480.Running Sum of 1d Array/README.md b/solution/1400-1499/1480.Running Sum of 1d Array/README.md index a04473ace84a3..15702c6fc6f53 100644 --- a/solution/1400-1499/1480.Running Sum of 1d Array/README.md +++ b/solution/1400-1499/1480.Running Sum of 1d Array/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:前缀和** +### 方法一:前缀和 我们直接遍历数组,对于当前元素 $nums[i]$,我们将其与前缀和 $nums[i-1]$ 相加,即可得到当前元素的前缀和 $nums[i]$。 @@ -51,20 +49,12 @@ -### **Python3** - - - ```python class Solution: def runningSum(self, nums: List[int]) -> List[int]: return list(accumulate(nums)) ``` -### **Java** - - - ```java class Solution { public int[] runningSum(int[] nums) { @@ -76,8 +66,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -88,8 +76,6 @@ public: }; ``` -### **Go** - ```go func runningSum(nums []int) []int { for i := 1; i < len(nums); i++ { @@ -99,8 +85,6 @@ func runningSum(nums []int) []int { } ``` -### **TypeScript** - ```ts function runningSum(nums: number[]): number[] { for (let i = 1; i < nums.length; ++i) { @@ -110,8 +94,6 @@ function runningSum(nums: number[]): number[] { } ``` -### **C#** - ```cs public class Solution { public int[] RunningSum(int[] nums) { @@ -123,8 +105,6 @@ public class Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -140,10 +120,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1480.Running Sum of 1d Array/README_EN.md b/solution/1400-1499/1480.Running Sum of 1d Array/README_EN.md index 21041fad30019..4947d9d9d300e 100644 --- a/solution/1400-1499/1480.Running Sum of 1d Array/README_EN.md +++ b/solution/1400-1499/1480.Running Sum of 1d Array/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Prefix Sum** +### Solution 1: Prefix Sum We directly traverse the array. For the current element $nums[i]$, we add it with the prefix sum $nums[i-1]$ to get the prefix sum $nums[i]$ of the current element. @@ -48,16 +48,12 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def runningSum(self, nums: List[int]) -> List[int]: return list(accumulate(nums)) ``` -### **Java** - ```java class Solution { public int[] runningSum(int[] nums) { @@ -69,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -81,8 +75,6 @@ public: }; ``` -### **Go** - ```go func runningSum(nums []int) []int { for i := 1; i < len(nums); i++ { @@ -92,8 +84,6 @@ func runningSum(nums []int) []int { } ``` -### **TypeScript** - ```ts function runningSum(nums: number[]): number[] { for (let i = 1; i < nums.length; ++i) { @@ -103,8 +93,6 @@ function runningSum(nums: number[]): number[] { } ``` -### **C#** - ```cs public class Solution { public int[] RunningSum(int[] nums) { @@ -116,8 +104,6 @@ public class Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -133,10 +119,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1481.Least Number of Unique Integers after K Removals/README.md b/solution/1400-1499/1481.Least Number of Unique Integers after K Removals/README.md index cd2bbae099807..4516f22df588f 100644 --- a/solution/1400-1499/1481.Least Number of Unique Integers after K Removals/README.md +++ b/solution/1400-1499/1481.Least Number of Unique Integers after K Removals/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:哈希表 + 排序** +### 方法一:哈希表 + 排序 我们用哈希表 $cnt$ 统计数组 $arr$ 中每个整数出现的次数,然后将 $cnt$ 中的值按照从小到大的顺序排序,记录在数组 $nums$ 中。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int: @@ -67,10 +61,6 @@ class Solution: return 0 ``` -### **Java** - - - ```java class Solution { public int findLeastNumOfUniqueInts(int[] arr, int k) { @@ -91,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func findLeastNumOfUniqueInts(arr []int, k int) int { cnt := map[int]int{} @@ -140,8 +126,6 @@ func findLeastNumOfUniqueInts(arr []int, k int) int { } ``` -### **TypeScript** - ```ts function findLeastNumOfUniqueInts(arr: number[], k: number): number { const cnt: Map = new Map(); @@ -163,10 +147,6 @@ function findLeastNumOfUniqueInts(arr: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1481.Least Number of Unique Integers after K Removals/README_EN.md b/solution/1400-1499/1481.Least Number of Unique Integers after K Removals/README_EN.md index b86ad442ca675..4636d841b6b2d 100644 --- a/solution/1400-1499/1481.Least Number of Unique Integers after K Removals/README_EN.md +++ b/solution/1400-1499/1481.Least Number of Unique Integers after K Removals/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Hash Table + Sorting** +### Solution 1: Hash Table + Sorting We use the hash table $cnt$ to count the number of times each integer in the array $arr$ appears, and then sort the values in $cnt$ in ascending order, and record them in the array $nums$. @@ -48,8 +48,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$, -### **Python3** - ```python class Solution: def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int: @@ -61,8 +59,6 @@ class Solution: return 0 ``` -### **Java** - ```java class Solution { public int findLeastNumOfUniqueInts(int[] arr, int k) { @@ -83,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +103,6 @@ public: }; ``` -### **Go** - ```go func findLeastNumOfUniqueInts(arr []int, k int) int { cnt := map[int]int{} @@ -132,8 +124,6 @@ func findLeastNumOfUniqueInts(arr []int, k int) int { } ``` -### **TypeScript** - ```ts function findLeastNumOfUniqueInts(arr: number[], k: number): number { const cnt: Map = new Map(); @@ -155,10 +145,6 @@ function findLeastNumOfUniqueInts(arr: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1482.Minimum Number of Days to Make m Bouquets/README.md b/solution/1400-1499/1482.Minimum Number of Days to Make m Bouquets/README.md index d1a5d38b29bce..1ab55cf781f37 100644 --- a/solution/1400-1499/1482.Minimum Number of Days to Make m Bouquets/README.md +++ b/solution/1400-1499/1482.Minimum Number of Days to Make m Bouquets/README.md @@ -73,16 +73,10 @@ ## 解法 - - -利用二分查找快速定位。 +### 方法一 -### **Python3** - - - ```python class Solution: def minDays(self, bloomDay: List[int], m: int, k: int) -> int: @@ -108,10 +102,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int minDays(int[] bloomDay, int m, int k) { @@ -149,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -189,8 +177,6 @@ public: }; ``` -### **Go** - ```go func minDays(bloomDay []int, m int, k int) int { if m*k > len(bloomDay) { @@ -230,10 +216,6 @@ func check(bloomDay []int, m, k, day int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1482.Minimum Number of Days to Make m Bouquets/README_EN.md b/solution/1400-1499/1482.Minimum Number of Days to Make m Bouquets/README_EN.md index 24ba63b26e88e..a316d8e11e7ec 100644 --- a/solution/1400-1499/1482.Minimum Number of Days to Make m Bouquets/README_EN.md +++ b/solution/1400-1499/1482.Minimum Number of Days to Make m Bouquets/README_EN.md @@ -59,12 +59,10 @@ It is obvious that we can make two bouquets in different ways. ## Solutions -Quickly locate using binary search. +### Solution 1 -### **Python3** - ```python class Solution: def minDays(self, bloomDay: List[int], m: int, k: int) -> int: @@ -90,8 +88,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { public int minDays(int[] bloomDay, int m, int k) { @@ -129,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +163,6 @@ public: }; ``` -### **Go** - ```go func minDays(bloomDay []int, m int, k int) int { if m*k > len(bloomDay) { @@ -210,10 +202,6 @@ func check(bloomDay []int, m, k, day int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1483.Kth Ancestor of a Tree Node/README.md b/solution/1400-1499/1483.Kth Ancestor of a Tree Node/README.md index 89fe1cf6b6c5d..d48b6fa9fd530 100644 --- a/solution/1400-1499/1483.Kth Ancestor of a Tree Node/README.md +++ b/solution/1400-1499/1483.Kth Ancestor of a Tree Node/README.md @@ -53,9 +53,7 @@ treeAncestor.getKthAncestor(6, 3); // 返回 -1 因为不存在满足要求的 ## 解法 - - -**方法一:动态规划 + 倍增** +### 方法一:动态规划 + 倍增 题目要我们寻找节点 $node$ 的第 $k$ 个祖先节点,如果暴力求解,需要从 $node$ 开始向上遍历 $k$ 次,时间复杂度为 $O(k)$,显然会超时。 @@ -79,10 +77,6 @@ $$ -### **Python3** - - - ```python class TreeAncestor: def __init__(self, n: int, parent: List[int]): @@ -109,10 +103,6 @@ class TreeAncestor: # param_1 = obj.getKthAncestor(node,k) ``` -### **Java** - - - ```java class TreeAncestor { private int[][] p; @@ -155,8 +145,6 @@ class TreeAncestor { */ ``` -### **C++** - ```cpp class TreeAncestor { public: @@ -198,8 +186,6 @@ private: */ ``` -### **Go** - ```go type TreeAncestor struct { p [][18]int @@ -243,10 +229,7 @@ func (this *TreeAncestor) GetKthAncestor(node int, k int) int { */ ``` -### **TypeScript** - ```ts -class TreeAncestor { class TreeAncestor { private p: number[][]; @@ -286,10 +269,6 @@ class TreeAncestor { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1483.Kth Ancestor of a Tree Node/README_EN.md b/solution/1400-1499/1483.Kth Ancestor of a Tree Node/README_EN.md index 288d4edd06d72..97bfdf19fa7e9 100644 --- a/solution/1400-1499/1483.Kth Ancestor of a Tree Node/README_EN.md +++ b/solution/1400-1499/1483.Kth Ancestor of a Tree Node/README_EN.md @@ -45,7 +45,7 @@ treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancest ## Solutions -**Solution 1: Dynamic Programming + Binary Lifting** +### Solution 1: Dynamic Programming + Binary Lifting The problem asks us to find the $k$-th ancestor node of a node $node$. If we solve it by brute force, we need to traverse upwards from $node$ for $k$ times, which has a time complexity of $O(k)$ and will obviously exceed the time limit. @@ -69,8 +69,6 @@ Similar problems: -### **Python3** - ```python class TreeAncestor: def __init__(self, n: int, parent: List[int]): @@ -97,8 +95,6 @@ class TreeAncestor: # param_1 = obj.getKthAncestor(node,k) ``` -### **Java** - ```java class TreeAncestor { private int[][] p; @@ -141,8 +137,6 @@ class TreeAncestor { */ ``` -### **C++** - ```cpp class TreeAncestor { public: @@ -184,8 +178,6 @@ private: */ ``` -### **Go** - ```go type TreeAncestor struct { p [][18]int @@ -229,8 +221,6 @@ func (this *TreeAncestor) GetKthAncestor(node int, k int) int { */ ``` -### **TypeScript** - ```ts class TreeAncestor { private p: number[][]; @@ -271,10 +261,6 @@ class TreeAncestor { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1483.Kth Ancestor of a Tree Node/Solution.cpp b/solution/1400-1499/1483.Kth Ancestor of a Tree Node/Solution.cpp index 1197bbe436e55..145144c07aac8 100644 --- a/solution/1400-1499/1483.Kth Ancestor of a Tree Node/Solution.cpp +++ b/solution/1400-1499/1483.Kth Ancestor of a Tree Node/Solution.cpp @@ -35,4 +35,4 @@ class TreeAncestor { * Your TreeAncestor object will be instantiated and called as such: * TreeAncestor* obj = new TreeAncestor(n, parent); * int param_1 = obj->getKthAncestor(node,k); - */ + */ \ No newline at end of file diff --git a/solution/1400-1499/1483.Kth Ancestor of a Tree Node/Solution.go b/solution/1400-1499/1483.Kth Ancestor of a Tree Node/Solution.go index 04f04ede95880..5bbd7026492bb 100644 --- a/solution/1400-1499/1483.Kth Ancestor of a Tree Node/Solution.go +++ b/solution/1400-1499/1483.Kth Ancestor of a Tree Node/Solution.go @@ -37,4 +37,4 @@ func (this *TreeAncestor) GetKthAncestor(node int, k int) int { * Your TreeAncestor object will be instantiated and called as such: * obj := Constructor(n, parent); * param_1 := obj.GetKthAncestor(node,k); - */ + */ \ No newline at end of file diff --git a/solution/1400-1499/1483.Kth Ancestor of a Tree Node/Solution.java b/solution/1400-1499/1483.Kth Ancestor of a Tree Node/Solution.java index fb9ccca670a93..9855ef2ced994 100644 --- a/solution/1400-1499/1483.Kth Ancestor of a Tree Node/Solution.java +++ b/solution/1400-1499/1483.Kth Ancestor of a Tree Node/Solution.java @@ -36,4 +36,4 @@ public int getKthAncestor(int node, int k) { * Your TreeAncestor object will be instantiated and called as such: * TreeAncestor obj = new TreeAncestor(n, parent); * int param_1 = obj.getKthAncestor(node,k); - */ + */ \ No newline at end of file diff --git a/solution/1400-1499/1484.Group Sold Products By The Date/README.md b/solution/1400-1499/1484.Group Sold Products By The Date/README.md index 884e6f4514eed..c30ef3ec945d2 100644 --- a/solution/1400-1499/1484.Group Sold Products By The Date/README.md +++ b/solution/1400-1499/1484.Group Sold Products By The Date/README.md @@ -60,12 +60,10 @@ Activities 表: ## 解法 - +### 方法一 -### **SQL** - ```sql SELECT sell_date, @@ -77,3 +75,5 @@ ORDER BY sell_date; ``` + + diff --git a/solution/1400-1499/1484.Group Sold Products By The Date/README_EN.md b/solution/1400-1499/1484.Group Sold Products By The Date/README_EN.md index 8b0789278c74e..da63b78bbbea4 100644 --- a/solution/1400-1499/1484.Group Sold Products By The Date/README_EN.md +++ b/solution/1400-1499/1484.Group Sold Products By The Date/README_EN.md @@ -60,9 +60,9 @@ For 2020-06-02, the Sold item is (Mask), we just return it. ## Solutions - +### Solution 1 -### **SQL** + ```sql SELECT @@ -75,3 +75,5 @@ ORDER BY sell_date; ``` + + diff --git a/solution/1400-1499/1485.Clone Binary Tree With Random Pointer/README.md b/solution/1400-1499/1485.Clone Binary Tree With Random Pointer/README.md index 66a0bb3a02c78..2b29d808ca1f2 100644 --- a/solution/1400-1499/1485.Clone Binary Tree With Random Pointer/README.md +++ b/solution/1400-1499/1485.Clone Binary Tree With Random Pointer/README.md @@ -64,14 +64,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for Node. # class Node: @@ -100,10 +96,6 @@ class Solution: return dfs(root) ``` -### **Java** - - - ```java /** * Definition for Node. @@ -148,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a Node. @@ -184,8 +174,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -218,10 +206,6 @@ func copyRandomBinaryTree(root *Node) *NodeCopy { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1485.Clone Binary Tree With Random Pointer/README_EN.md b/solution/1400-1499/1485.Clone Binary Tree With Random Pointer/README_EN.md index ee67fad192c3d..eba7b6437df2d 100644 --- a/solution/1400-1499/1485.Clone Binary Tree With Random Pointer/README_EN.md +++ b/solution/1400-1499/1485.Clone Binary Tree With Random Pointer/README_EN.md @@ -54,9 +54,9 @@ The random pointer of node 7 is node 1, so it is represented as [7, 0] where 0 i ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for Node. @@ -86,8 +86,6 @@ class Solution: return dfs(root) ``` -### **Java** - ```java /** * Definition for Node. @@ -132,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a Node. @@ -168,8 +164,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -202,10 +196,6 @@ func copyRandomBinaryTree(root *Node) *NodeCopy { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1486.XOR Operation in an Array/README.md b/solution/1400-1499/1486.XOR Operation in an Array/README.md index af4dc97334828..6c69402b85095 100644 --- a/solution/1400-1499/1486.XOR Operation in an Array/README.md +++ b/solution/1400-1499/1486.XOR Operation in an Array/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以直接模拟算出数组中所有元素的异或结果。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def xorOperation(self, n: int, start: int) -> int: @@ -75,16 +69,6 @@ class Solution: return ans ``` -```python -class Solution: - def xorOperation(self, n: int, start: int) -> int: - return reduce(xor, ((start + 2 * i) for i in range(n))) -``` - -### **Java** - - - ```java class Solution { public int xorOperation(int n, int start) { @@ -97,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +94,6 @@ public: }; ``` -### **Go** - ```go func xorOperation(n int, start int) (ans int) { for i := 0; i < n; i++ { @@ -123,10 +103,18 @@ func xorOperation(n int, start int) (ans int) { } ``` -### **...** + + +### 方法二 -``` + +```python +class Solution: + def xorOperation(self, n: int, start: int) -> int: + return reduce(xor, ((start + 2 * i) for i in range(n))) ``` + + diff --git a/solution/1400-1499/1486.XOR Operation in an Array/README_EN.md b/solution/1400-1499/1486.XOR Operation in an Array/README_EN.md index 67c98912f4e1a..0c5913ee13b93 100644 --- a/solution/1400-1499/1486.XOR Operation in an Array/README_EN.md +++ b/solution/1400-1499/1486.XOR Operation in an Array/README_EN.md @@ -39,9 +39,9 @@ Where "^" corresponds to bitwise XOR operator. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,14 +52,6 @@ class Solution: return ans ``` -```python -class Solution: - def xorOperation(self, n: int, start: int) -> int: - return reduce(xor, ((start + 2 * i) for i in range(n))) -``` - -### **Java** - ```java class Solution { public int xorOperation(int n, int start) { @@ -72,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +77,6 @@ public: }; ``` -### **Go** - ```go func xorOperation(n int, start int) (ans int) { for i := 0; i < n; i++ { @@ -98,10 +86,18 @@ func xorOperation(n int, start int) (ans int) { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def xorOperation(self, n: int, start: int) -> int: + return reduce(xor, ((start + 2 * i) for i in range(n))) ``` + + diff --git a/solution/1400-1499/1487.Making File Names Unique/README.md b/solution/1400-1499/1487.Making File Names Unique/README.md index a1fd910f427e8..7a68f1404c586 100644 --- a/solution/1400-1499/1487.Making File Names Unique/README.md +++ b/solution/1400-1499/1487.Making File Names Unique/README.md @@ -68,9 +68,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以用哈希表 $d$ 记录每个文件夹的最小可用编号,其中 $d[name] = k$ 表示文件夹 $name$ 的最小可用编号为 $k$。初始时,$d$ 中没有任何文件夹,因此 $d$ 为空。 @@ -88,10 +86,6 @@ -### **Python3** - - - ```python class Solution: def getFolderNames(self, names: List[str]) -> List[str]: @@ -107,10 +101,6 @@ class Solution: return names ``` -### **Java** - - - ```java class Solution { public String[] getFolderNames(String[] names) { @@ -131,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func getFolderNames(names []string) []string { d := map[string]int{} @@ -177,8 +163,6 @@ func getFolderNames(names []string) []string { } ``` -### **TypeScript** - ```ts function getFolderNames(names: string[]): string[] { let d: Map = new Map(); @@ -197,10 +181,6 @@ function getFolderNames(names: string[]): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1487.Making File Names Unique/README_EN.md b/solution/1400-1499/1487.Making File Names Unique/README_EN.md index db033f0914113..7fd98eeb74d4b 100644 --- a/solution/1400-1499/1487.Making File Names Unique/README_EN.md +++ b/solution/1400-1499/1487.Making File Names Unique/README_EN.md @@ -54,9 +54,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return names ``` -### **Java** - ```java class Solution { public String[] getFolderNames(String[] names) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func getFolderNames(names []string) []string { d := map[string]int{} @@ -141,8 +135,6 @@ func getFolderNames(names []string) []string { } ``` -### **TypeScript** - ```ts function getFolderNames(names: string[]): string[] { let d: Map = new Map(); @@ -161,10 +153,6 @@ function getFolderNames(names: string[]): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1488.Avoid Flood in The City/README.md b/solution/1400-1499/1488.Avoid Flood in The City/README.md index c686d50f0632e..c0b97ea5b7742 100644 --- a/solution/1400-1499/1488.Avoid Flood in The City/README.md +++ b/solution/1400-1499/1488.Avoid Flood in The City/README.md @@ -75,9 +75,7 @@ ## 解法 - - -**方法一:贪心 + 二分查找** +### 方法一:贪心 + 二分查找 我们将所有晴天都存入 $sunny$ 数组或者有序集合中,使用哈希表 $rainy$ 记录每个湖泊最近一次下雨的日期。初始化答案数组 $ans$ 每个元素为 $-1$。 @@ -89,10 +87,6 @@ -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -118,10 +112,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] avoidFlood(int[] rains) { @@ -152,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -184,8 +172,6 @@ public: }; ``` -### **Go** - ```go func avoidFlood(rains []int) []int { n := len(rains) @@ -215,8 +201,6 @@ func avoidFlood(rains []int) []int { } ``` -### **TypeScript** - ```ts function avoidFlood(rains: number[]): number[] { const n = rains.length; @@ -734,10 +718,6 @@ class TreeSet { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1488.Avoid Flood in The City/README_EN.md b/solution/1400-1499/1488.Avoid Flood in The City/README_EN.md index 4a92df356bcc9..169c52700f209 100644 --- a/solution/1400-1499/1488.Avoid Flood in The City/README_EN.md +++ b/solution/1400-1499/1488.Avoid Flood in The City/README_EN.md @@ -71,7 +71,7 @@ After that, it will rain over lakes [1,2]. It's easy to prove that no matter ## Solutions -**Solution 1: Greedy + Binary Search** +### Solution 1: Greedy + Binary Search We store all sunny days in the $sunny$ array or a sorted set, and use the hash table $rainy$ to record the last rainy day for each lake. We initialize the answer array $ans$ with each element set to $-1$. @@ -83,8 +83,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python from sortedcontainers import SortedList @@ -110,8 +108,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] avoidFlood(int[] rains) { @@ -142,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -174,8 +168,6 @@ public: }; ``` -### **Go** - ```go func avoidFlood(rains []int) []int { n := len(rains) @@ -205,8 +197,6 @@ func avoidFlood(rains []int) []int { } ``` -### **TypeScript** - ```ts function avoidFlood(rains: number[]): number[] { const n = rains.length; @@ -724,10 +714,6 @@ class TreeSet { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/README.md b/solution/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/README.md index be272296889c2..a82ad5a22b92a 100644 --- a/solution/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/README.md +++ b/solution/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/README.md @@ -51,23 +51,12 @@ ## 解法 - - -最小生成树问题。 - -- 关键边:若删去某条边,导致整个图不连通,或者最小生成树的权值变大,那么这条边就是关键边。 -- 伪关键边:对于非关键边,我们尝试将该边加入最小生成树集合中,若最小生成树的权值不变,那么这条边就是非关键边。 - -**方法一:Kruskal 算法** +### 方法一:Kruskal 算法 先利用 Kruskal 算法,得出最小生成树的权值 v。然后依次枚举每条边,按上面的方法,判断是否是关键边;如果不是关键边,再判断是否是伪关键边。 -### **Python3** - - - ```python class UnionFind: def __init__(self, n): @@ -112,10 +101,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) { @@ -204,8 +189,6 @@ class UnionFind { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -270,8 +253,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p []int @@ -349,10 +330,6 @@ func findCriticalAndPseudoCriticalEdges(n int, edges [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/README_EN.md b/solution/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/README_EN.md index 6d3011261e26f..9cd0f25dfa10d 100644 --- a/solution/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/README_EN.md +++ b/solution/1400-1499/1489.Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree/README_EN.md @@ -49,9 +49,9 @@ The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are consider ## Solutions - +### Solution 1 -### **Python3** + ```python class UnionFind: @@ -97,8 +97,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) { @@ -187,8 +185,6 @@ class UnionFind { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -253,8 +249,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p []int @@ -332,10 +326,6 @@ func findCriticalAndPseudoCriticalEdges(n int, edges [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1490.Clone N-ary Tree/README.md b/solution/1400-1499/1490.Clone N-ary Tree/README.md index e9809b1188d6c..d3f4dda48cbe9 100644 --- a/solution/1400-1499/1490.Clone N-ary Tree/README.md +++ b/solution/1400-1499/1490.Clone N-ary Tree/README.md @@ -54,9 +54,7 @@ class Node { ## 解法 - - -**方法一:递归** +### 方法一:递归 我们可以用递归的方法来实现 N 叉树的深拷贝。 @@ -66,10 +64,6 @@ class Node { -### **Python3** - - - ```python """ # Definition for a Node. @@ -88,10 +82,6 @@ class Solution: return Node(root.val, children) ``` -### **Java** - - - ```java /* // Definition for a Node. @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -191,10 +177,6 @@ func cloneTree(root *Node) *Node { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1490.Clone N-ary Tree/README_EN.md b/solution/1400-1499/1490.Clone N-ary Tree/README_EN.md index 98623e3ba794d..84c62085399d5 100644 --- a/solution/1400-1499/1490.Clone N-ary Tree/README_EN.md +++ b/solution/1400-1499/1490.Clone N-ary Tree/README_EN.md @@ -49,12 +49,10 @@ class Node { ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python """ # Definition for a Node. @@ -73,8 +71,6 @@ class Solution: return Node(root.val, children) ``` -### **Java** - ```java /* // Definition for a Node. @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -151,8 +145,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -174,10 +166,6 @@ func cloneTree(root *Node) *Node { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/README.md b/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/README.md index 613a69121abd3..a2bda6d3ef87d 100644 --- a/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/README.md +++ b/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 按题意模拟即可。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def average(self, salary: List[int]) -> float: @@ -76,10 +70,6 @@ class Solution: return s / (len(salary) - 2) ``` -### **Java** - - - ```java class Solution { public double average(int[] salary) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func average(salary []int) float64 { s := 0 @@ -131,8 +117,6 @@ func average(salary []int) float64 { } ``` -### **TypeScript** - ```ts function average(salary: number[]): number { let max = -Infinity; @@ -147,8 +131,6 @@ function average(salary: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn average(salary: Vec) -> f64 { @@ -166,27 +148,6 @@ impl Solution { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) -#define min(a, b) (((a) < (b)) ? (a) : (b)) - -double average(int* salary, int salarySize) { - int ma = INT_MIN; - int mi = INT_MAX; - int sum = 0; - for (int i = 0; i < salarySize; i++) { - sum += salary[i]; - ma = max(ma, salary[i]); - mi = min(mi, salary[i]); - } - return (sum - mi - ma) * 1.0 / (salarySize - 2); -} -``` - -### **PHP** - ```php class Solution { /** @@ -206,10 +167,23 @@ class Solution { } ``` -### **...** - -``` +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +#define min(a, b) (((a) < (b)) ? (a) : (b)) +double average(int* salary, int salarySize) { + int ma = INT_MIN; + int mi = INT_MAX; + int sum = 0; + for (int i = 0; i < salarySize; i++) { + sum += salary[i]; + ma = max(ma, salary[i]); + mi = min(mi, salary[i]); + } + return (sum - mi - ma) * 1.0 / (salarySize - 2); +} ``` + + diff --git a/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/README_EN.md b/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/README_EN.md index e15de0989b130..76eb88589ea61 100644 --- a/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/README_EN.md +++ b/solution/1400-1499/1491.Average Salary Excluding the Minimum and Maximum Salary/README_EN.md @@ -38,9 +38,9 @@ Average salary excluding minimum and maximum salary is (2000) / 1 = 2000 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -49,8 +49,6 @@ class Solution: return s / (len(salary) - 2) ``` -### **Java** - ```java class Solution { public double average(int[] salary) { @@ -67,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -86,8 +82,6 @@ public: }; ``` -### **Go** - ```go func average(salary []int) float64 { s := 0 @@ -102,8 +96,6 @@ func average(salary []int) float64 { } ``` -### **TypeScript** - ```ts function average(salary: number[]): number { let max = -Infinity; @@ -118,8 +110,6 @@ function average(salary: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn average(salary: Vec) -> f64 { @@ -137,27 +127,6 @@ impl Solution { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) -#define min(a, b) (((a) < (b)) ? (a) : (b)) - -double average(int* salary, int salarySize) { - int ma = INT_MIN; - int mi = INT_MAX; - int sum = 0; - for (int i = 0; i < salarySize; i++) { - sum += salary[i]; - ma = max(ma, salary[i]); - mi = min(mi, salary[i]); - } - return (sum - mi - ma) * 1.0 / (salarySize - 2); -} -``` - -### **PHP** - ```php class Solution { /** @@ -177,10 +146,23 @@ class Solution { } ``` -### **...** - -``` +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +#define min(a, b) (((a) < (b)) ? (a) : (b)) +double average(int* salary, int salarySize) { + int ma = INT_MIN; + int mi = INT_MAX; + int sum = 0; + for (int i = 0; i < salarySize; i++) { + sum += salary[i]; + ma = max(ma, salary[i]); + mi = min(mi, salary[i]); + } + return (sum - mi - ma) * 1.0 / (salarySize - 2); +} ``` + + diff --git a/solution/1400-1499/1492.The kth Factor of n/README.md b/solution/1400-1499/1492.The kth Factor of n/README.md index 540164b295d1c..cbaf0010edbbb 100644 --- a/solution/1400-1499/1492.The kth Factor of n/README.md +++ b/solution/1400-1499/1492.The kth Factor of n/README.md @@ -54,28 +54,14 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 “因子”是指能整除某个数的数。因此,我们只需要从小到大枚举 $[1,2,..n]$,找到所有能整除 $n$ 的数,然后返回第 $k$ 个即可。 时间复杂度 $O(n)$。 -**方法二:枚举优化** - -我们可以发现,如果 $n$ 有一个因子 $x$,那么 $n$ 一定也有一个因子 $n/x$。 - -因此,我们先需要枚举 $[1,2,...\left \lfloor \sqrt{n} \right \rfloor]$,找到所有能整除 $n$ 的数,如果找到第 $k$ 个因子,那么直接返回即可。如果没有找到第 $k$ 个因子,那么我们再倒序枚举 $[\left \lfloor \sqrt{n} \right \rfloor ,..1]$,找到第 $k$ 个因子即可。 - -时间复杂度 $O(\sqrt{n})$。 - -### **Python3** - - - ```python class Solution: def kthFactor(self, n: int, k: int) -> int: @@ -87,31 +73,6 @@ class Solution: return -1 ``` -```python -class Solution: - def kthFactor(self, n: int, k: int) -> int: - i = 1 - while i * i < n: - if n % i == 0: - k -= 1 - if k == 0: - return i - i += 1 - if i * i != n: - i -= 1 - while i: - if (n % (n // i)) == 0: - k -= 1 - if k == 0: - return n // i - i -= 1 - return -1 -``` - -### **Java** - - - ```java class Solution { public int kthFactor(int n, int k) { @@ -125,9 +86,10 @@ class Solution { } ``` -```java +```cpp class Solution { - public int kthFactor(int n, int k) { +public: + int kthFactor(int n, int k) { int i = 1; for (; i < n / i; ++i) { if (n % i == 0 && (--k == 0)) { @@ -144,15 +106,59 @@ class Solution { } return -1; } +}; +``` + +```go +func kthFactor(n int, k int) int { + for i := 1; i <= n; i++ { + if n%i == 0 { + k-- + if k == 0 { + return i + } + } + } + return -1 } ``` -### **C++** + -```cpp +### 方法二:枚举优化 + +我们可以发现,如果 $n$ 有一个因子 $x$,那么 $n$ 一定也有一个因子 $n/x$。 + +因此,我们先需要枚举 $[1,2,...\left \lfloor \sqrt{n} \right \rfloor]$,找到所有能整除 $n$ 的数,如果找到第 $k$ 个因子,那么直接返回即可。如果没有找到第 $k$ 个因子,那么我们再倒序枚举 $[\left \lfloor \sqrt{n} \right \rfloor ,..1]$,找到第 $k$ 个因子即可。 + +时间复杂度 $O(\sqrt{n})$。 + + + +```python +class Solution: + def kthFactor(self, n: int, k: int) -> int: + i = 1 + while i * i < n: + if n % i == 0: + k -= 1 + if k == 0: + return i + i += 1 + if i * i != n: + i -= 1 + while i: + if (n % (n // i)) == 0: + k -= 1 + if k == 0: + return n // i + i -= 1 + return -1 +``` + +```java class Solution { -public: - int kthFactor(int n, int k) { + public int kthFactor(int n, int k) { int i = 1; for (; i < n / i; ++i) { if (n % i == 0 && (--k == 0)) { @@ -169,22 +175,6 @@ public: } return -1; } -}; -``` - -### **Go** - -```go -func kthFactor(n int, k int) int { - for i := 1; i <= n; i++ { - if n%i == 0 { - k-- - if k == 0 { - return i - } - } - } - return -1 } ``` @@ -214,10 +204,6 @@ func kthFactor(n int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1492.The kth Factor of n/README_EN.md b/solution/1400-1499/1492.The kth Factor of n/README_EN.md index 51fb6b56fef33..970be18100979 100644 --- a/solution/1400-1499/1492.The kth Factor of n/README_EN.md +++ b/solution/1400-1499/1492.The kth Factor of n/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,29 +62,6 @@ class Solution: return -1 ``` -```python -class Solution: - def kthFactor(self, n: int, k: int) -> int: - i = 1 - while i * i < n: - if n % i == 0: - k -= 1 - if k == 0: - return i - i += 1 - if i * i != n: - i -= 1 - while i: - if (n % (n // i)) == 0: - k -= 1 - if k == 0: - return n // i - i -= 1 - return -1 -``` - -### **Java** - ```java class Solution { public int kthFactor(int n, int k) { @@ -98,9 +75,10 @@ class Solution { } ``` -```java +```cpp class Solution { - public int kthFactor(int n, int k) { +public: + int kthFactor(int n, int k) { int i = 1; for (; i < n / i; ++i) { if (n % i == 0 && (--k == 0)) { @@ -117,15 +95,53 @@ class Solution { } return -1; } +}; +``` + +```go +func kthFactor(n int, k int) int { + for i := 1; i <= n; i++ { + if n%i == 0 { + k-- + if k == 0 { + return i + } + } + } + return -1 } ``` -### **C++** + -```cpp +### Solution 2 + + + +```python +class Solution: + def kthFactor(self, n: int, k: int) -> int: + i = 1 + while i * i < n: + if n % i == 0: + k -= 1 + if k == 0: + return i + i += 1 + if i * i != n: + i -= 1 + while i: + if (n % (n // i)) == 0: + k -= 1 + if k == 0: + return n // i + i -= 1 + return -1 +``` + +```java class Solution { -public: - int kthFactor(int n, int k) { + public int kthFactor(int n, int k) { int i = 1; for (; i < n / i; ++i) { if (n % i == 0 && (--k == 0)) { @@ -142,22 +158,6 @@ public: } return -1; } -}; -``` - -### **Go** - -```go -func kthFactor(n int, k int) int { - for i := 1; i <= n; i++ { - if n%i == 0 { - k-- - if k == 0 { - return i - } - } - } - return -1 } ``` @@ -187,10 +187,6 @@ func kthFactor(n int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1493.Longest Subarray of 1's After Deleting One Element/README.md b/solution/1400-1499/1493.Longest Subarray of 1's After Deleting One Element/README.md index 3e115f0e77d4e..3b196479a49b8 100644 --- a/solution/1400-1499/1493.Longest Subarray of 1's After Deleting One Element/README.md +++ b/solution/1400-1499/1493.Longest Subarray of 1's After Deleting One Element/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 枚举删除的位置 $i$,那么每一个位置 $i$ 的最长子数组长度为 $i$ 左边连续的 $1$ 的个数加上 $i$ 右边连续的 $1$ 的个数。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def longestSubarray(self, nums: List[int]) -> int: @@ -77,10 +71,6 @@ class Solution: return max(a + b for a, b in zip(left, right)) ``` -### **Java** - - - ```java class Solution { public int longestSubarray(int[] nums) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func longestSubarray(nums []int) int { n := len(nums) @@ -159,10 +145,6 @@ func longestSubarray(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1493.Longest Subarray of 1's After Deleting One Element/README_EN.md b/solution/1400-1499/1493.Longest Subarray of 1's After Deleting One Element/README_EN.md index 839a233999881..54439f919aa43 100644 --- a/solution/1400-1499/1493.Longest Subarray of 1's After Deleting One Element/README_EN.md +++ b/solution/1400-1499/1493.Longest Subarray of 1's After Deleting One Element/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return max(a + b for a, b in zip(left, right)) ``` -### **Java** - ```java class Solution { public int longestSubarray(int[] nums) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +113,6 @@ public: }; ``` -### **Go** - ```go func longestSubarray(nums []int) int { n := len(nums) @@ -142,10 +136,6 @@ func longestSubarray(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1494.Parallel Courses II/README.md b/solution/1400-1499/1494.Parallel Courses II/README.md index 310bab1443d2f..b6e95a34ff98b 100644 --- a/solution/1400-1499/1494.Parallel Courses II/README.md +++ b/solution/1400-1499/1494.Parallel Courses II/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:状态压缩 + BFS + 子集枚举** +### 方法一:状态压缩 + BFS + 子集枚举 我们用数组 $d[i]$ 表示课程 $i$ 的先修课程的集合。由于数据规模 $n\lt 15$,我们可以用一个整数的二进制位(状态压缩)来表示集合,其中第 $j$ 位为 $1$ 表示课程 $j$ 是课程 $i$ 的先修课程。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int: @@ -108,10 +102,6 @@ class Solution: nxt = (nxt - 1) & x ``` -### **Java** - - - ```java class Solution { public int minNumberOfSemesters(int n, int[][] relations, int k) { @@ -155,8 +145,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -202,8 +190,6 @@ public: }; ``` -### **Go** - ```go func minNumberOfSemesters(n int, relations [][]int, k int) int { d := make([]int, n+1) @@ -247,10 +233,6 @@ func minNumberOfSemesters(n int, relations [][]int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1494.Parallel Courses II/README_EN.md b/solution/1400-1499/1494.Parallel Courses II/README_EN.md index 140068f0ce48f..394e9a4596a20 100644 --- a/solution/1400-1499/1494.Parallel Courses II/README_EN.md +++ b/solution/1400-1499/1494.Parallel Courses II/README_EN.md @@ -50,9 +50,9 @@ In the fourth semester, you can take course 5. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: nxt = (nxt - 1) & x ``` -### **Java** - ```java class Solution { public int minNumberOfSemesters(int n, int[][] relations, int k) { @@ -129,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +172,6 @@ public: }; ``` -### **Go** - ```go func minNumberOfSemesters(n int, relations [][]int, k int) int { d := make([]int, n+1) @@ -221,10 +215,6 @@ func minNumberOfSemesters(n int, relations [][]int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1495.Friendly Movies Streamed Last Month/README.md b/solution/1400-1499/1495.Friendly Movies Streamed Last Month/README.md index 68d86d16ea7aa..40e50d984149b 100644 --- a/solution/1400-1499/1495.Friendly Movies Streamed Last Month/README.md +++ b/solution/1400-1499/1495.Friendly Movies Streamed Last Month/README.md @@ -89,16 +89,12 @@ TVProgram 表: ## 解法 - - -**方法一:等值连接 + 条件筛选** +### 方法一:等值连接 + 条件筛选 我们可以先通过等值连接将两张表按照 `content_id` 字段连接起来,然后再通过条件筛选出在 $2020$ 年 $6$ 月份播放的儿童适宜电影。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT DISTINCT title @@ -112,3 +108,5 @@ WHERE ``` + + diff --git a/solution/1400-1499/1495.Friendly Movies Streamed Last Month/README_EN.md b/solution/1400-1499/1495.Friendly Movies Streamed Last Month/README_EN.md index 9b9981f1c5c20..6f97179678911 100644 --- a/solution/1400-1499/1495.Friendly Movies Streamed Last Month/README_EN.md +++ b/solution/1400-1499/1495.Friendly Movies Streamed Last Month/README_EN.md @@ -87,7 +87,7 @@ Content table: ## Solutions -**Solution 1: Equi-Join + Conditional Filtering** +### Solution 1: Equi-Join + Conditional Filtering We can first use an equi-join to join the two tables based on the `content_id` field, and then use conditional filtering to select the child-friendly movies that were played in June 2020. @@ -106,3 +106,5 @@ WHERE ``` + + diff --git a/solution/1400-1499/1496.Path Crossing/README.md b/solution/1400-1499/1496.Path Crossing/README.md index f21796b58d5b3..6edabe5d8a09f 100644 --- a/solution/1400-1499/1496.Path Crossing/README.md +++ b/solution/1400-1499/1496.Path Crossing/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以用一个哈希表 $vis$ 记录路径上的点。初始时 $vis$ 中只有原点 $(0, 0)$。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def isPathCrossing(self, path: str) -> bool: @@ -82,10 +76,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean isPathCrossing(String path) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func isPathCrossing(path string) bool { i, j := 0, 0 @@ -164,8 +150,6 @@ func isPathCrossing(path string) bool { } ``` -### **TypeScript** - ```ts function isPathCrossing(path: string): boolean { let [i, j] = [0, 0]; @@ -191,10 +175,6 @@ function isPathCrossing(path: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1496.Path Crossing/README_EN.md b/solution/1400-1499/1496.Path Crossing/README_EN.md index fc73bb342b77c..d4ef571254ff0 100644 --- a/solution/1400-1499/1496.Path Crossing/README_EN.md +++ b/solution/1400-1499/1496.Path Crossing/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean isPathCrossing(String path) { @@ -84,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func isPathCrossing(path string) bool { i, j := 0, 0 @@ -139,8 +133,6 @@ func isPathCrossing(path string) bool { } ``` -### **TypeScript** - ```ts function isPathCrossing(path: string): boolean { let [i, j] = [0, 0]; @@ -166,10 +158,6 @@ function isPathCrossing(path: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1497.Check If Array Pairs Are Divisible by k/README.md b/solution/1400-1499/1497.Check If Array Pairs Are Divisible by k/README.md index ce5148d85e9da..79ce95d8b51bf 100644 --- a/solution/1400-1499/1497.Check If Array Pairs Are Divisible by k/README.md +++ b/solution/1400-1499/1497.Check If Array Pairs Are Divisible by k/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:统计余数** +### 方法一:统计余数 两个数 $a$ 和 $b$ 的和能被 $k$ 整除,当且仅当这两个数分别对 $k$ 取模的结果之和能被 $k$ 整除。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def canArrange(self, arr: List[int], k: int) -> bool: @@ -75,10 +69,6 @@ class Solution: return cnt[0] % 2 == 0 and all(cnt[i] == cnt[k - i] for i in range(1, k)) ``` -### **Java** - - - ```java class Solution { public boolean canArrange(int[] arr, int k) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func canArrange(arr []int, k int) bool { cnt := make([]int, k) @@ -133,10 +119,6 @@ func canArrange(arr []int, k int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1497.Check If Array Pairs Are Divisible by k/README_EN.md b/solution/1400-1499/1497.Check If Array Pairs Are Divisible by k/README_EN.md index cf6430ae931b8..418e67ccf99c6 100644 --- a/solution/1400-1499/1497.Check If Array Pairs Are Divisible by k/README_EN.md +++ b/solution/1400-1499/1497.Check If Array Pairs Are Divisible by k/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return cnt[0] % 2 == 0 and all(cnt[i] == cnt[k - i] for i in range(1, k)) ``` -### **Java** - ```java class Solution { public boolean canArrange(int[] arr, int k) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +94,6 @@ public: }; ``` -### **Go** - ```go func canArrange(arr []int, k int) bool { cnt := make([]int, k) @@ -115,10 +109,6 @@ func canArrange(arr []int, k int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README.md b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README.md index aad0862237246..8faf6c51af0ec 100644 --- a/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README.md +++ b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:排序 + 枚举贡献 + 二分查找** +### 方法一:排序 + 枚举贡献 + 二分查找 由于题目中描述的是子序列,并且涉及到最小元素与最大元素的和,因此我们可以先对数组 `nums` 进行排序。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def numSubseq(self, nums: List[int], target: int) -> int: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numSubseq(int[] nums, int target) { @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func numSubseq(nums []int, target int) (ans int) { sort.Ints(nums) @@ -180,10 +166,6 @@ func numSubseq(nums []int, target int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README_EN.md b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README_EN.md index 3ac3bc214a075..52bbde7a04fde 100644 --- a/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README_EN.md +++ b/solution/1400-1499/1498.Number of Subsequences That Satisfy the Given Sum Condition/README_EN.md @@ -50,9 +50,9 @@ Number of valid subsequences (63 - 2 = 61). ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numSubseq(int[] nums, int target) { @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +134,6 @@ public: }; ``` -### **Go** - ```go func numSubseq(nums []int, target int) (ans int) { sort.Ints(nums) @@ -161,10 +155,6 @@ func numSubseq(nums []int, target int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1499.Max Value of Equation/README.md b/solution/1400-1499/1499.Max Value of Equation/README.md index dc8789be5f672..575e7926d1051 100644 --- a/solution/1400-1499/1499.Max Value of Equation/README.md +++ b/solution/1400-1499/1499.Max Value of Equation/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:优先队列(大根堆)** +### 方法一:优先队列(大根堆) 题目要求 $y_i + y_j + |x_i - x_j|$ 的最大值,其中 $i \lt j$,并且 $|x_i - x_j| \leq k$。由于 $x_i$ 是严格单调递增的,那么: @@ -65,24 +63,8 @@ $$ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $points$ 的长度。 -**方法二:单调队列** - -这道题实际上需要我们维护的是一个长度为 $k$ 的窗口中 $y-x$ 的最大值,单调队列可以很好地解决这个问题。 - -具体地,我们定义一个单调队列 $q$,队列中每个元素是一个二元组 $(x_i, y_i)$。 - -当我们遍历到点 $(x, y)$ 时,如果队列 $q$ 不为空,并且 $x - q[0][0] \gt k$,那么不断弹出队首元素,直到队列为空或者满足 $x - q[0][0] \leq k$。此时,队首元素 $(x_i, y_i)$ 即为所有满足 $x_j - x_i \leq k$ 的点中 $y_i - x_i$ 的最大值,此时更新答案 $ans = \max(ans, x + y + y_i - x_i)$。 - -接下来,在将点 $(x, y)$ 加入队尾之前,我们将队列中所有 $y_i - x_i \leq y - x$ 的元素 $(x_i, y_i)$ 弹出队列,然后将点 $(x, y)$ 加入队尾。继续遍历下一个点,直到遍历完整个数组 $points$。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $points$ 的长度。 - -### **Python3** - - - ```python class Solution: def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int: @@ -97,26 +79,6 @@ class Solution: return ans ``` -```python -class Solution: - def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int: - ans = -inf - q = deque() - for x, y in points: - while q and x - q[0][0] > k: - q.popleft() - if q: - ans = max(ans, x + y + q[0][1] - q[0][0]) - while q and y - x >= q[-1][1] - q[-1][0]: - q.pop() - q.append((x, y)) - return ans -``` - -### **Java** - - - ```java class Solution { public int findMaxValueOfEquation(int[][] points, int k) { @@ -137,31 +99,6 @@ class Solution { } ``` -```java -class Solution { - public int findMaxValueOfEquation(int[][] points, int k) { - int ans = -(1 << 30); - Deque q = new ArrayDeque<>(); - for (var p : points) { - int x = p[0], y = p[1]; - while (!q.isEmpty() && x - q.peekFirst()[0] > k) { - q.pollFirst(); - } - if (!q.isEmpty()) { - ans = Math.max(ans, x + y + q.peekFirst()[1] - q.peekFirst()[0]); - } - while (!q.isEmpty() && y - x >= q.peekLast()[1] - q.peekLast()[0]) { - q.pollLast(); - } - q.offerLast(p); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -183,32 +120,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findMaxValueOfEquation(vector>& points, int k) { - int ans = -(1 << 30); - deque> q; - for (auto& p : points) { - int x = p[0], y = p[1]; - while (!q.empty() && x - q.front().first > k) { - q.pop_front(); - } - if (!q.empty()) { - ans = max(ans, x + y + q.front().second - q.front().first); - } - while (!q.empty() && y - x >= q.back().second - q.back().first) { - q.pop_back(); - } - q.emplace_back(x, y); - } - return ans; - } -}; -``` - -### **Go** - ```go func findMaxValueOfEquation(points [][]int, k int) int { ans := -(1 << 30) @@ -240,29 +151,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -```go -func findMaxValueOfEquation(points [][]int, k int) int { - ans := -(1 << 30) - q := [][2]int{} - for _, p := range points { - x, y := p[0], p[1] - for len(q) > 0 && x-q[0][0] > k { - q = q[1:] - } - if len(q) > 0 { - ans = max(ans, x+y+q[0][1]-q[0][0]) - } - for len(q) > 0 && y-x >= q[len(q)-1][1]-q[len(q)-1][0] { - q = q[:len(q)-1] - } - q = append(q, [2]int{x, y}) - } - return ans -} -``` - -### **TypeScript** - ```ts function findMaxValueOfEquation(points: number[][], k: number): number { let ans = -(1 << 30); @@ -346,6 +234,106 @@ class Heap { } ``` + + +### 方法二:单调队列 + +这道题实际上需要我们维护的是一个长度为 $k$ 的窗口中 $y-x$ 的最大值,单调队列可以很好地解决这个问题。 + +具体地,我们定义一个单调队列 $q$,队列中每个元素是一个二元组 $(x_i, y_i)$。 + +当我们遍历到点 $(x, y)$ 时,如果队列 $q$ 不为空,并且 $x - q[0][0] \gt k$,那么不断弹出队首元素,直到队列为空或者满足 $x - q[0][0] \leq k$。此时,队首元素 $(x_i, y_i)$ 即为所有满足 $x_j - x_i \leq k$ 的点中 $y_i - x_i$ 的最大值,此时更新答案 $ans = \max(ans, x + y + y_i - x_i)$。 + +接下来,在将点 $(x, y)$ 加入队尾之前,我们将队列中所有 $y_i - x_i \leq y - x$ 的元素 $(x_i, y_i)$ 弹出队列,然后将点 $(x, y)$ 加入队尾。继续遍历下一个点,直到遍历完整个数组 $points$。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $points$ 的长度。 + + + +```python +class Solution: + def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int: + ans = -inf + q = deque() + for x, y in points: + while q and x - q[0][0] > k: + q.popleft() + if q: + ans = max(ans, x + y + q[0][1] - q[0][0]) + while q and y - x >= q[-1][1] - q[-1][0]: + q.pop() + q.append((x, y)) + return ans +``` + +```java +class Solution { + public int findMaxValueOfEquation(int[][] points, int k) { + int ans = -(1 << 30); + Deque q = new ArrayDeque<>(); + for (var p : points) { + int x = p[0], y = p[1]; + while (!q.isEmpty() && x - q.peekFirst()[0] > k) { + q.pollFirst(); + } + if (!q.isEmpty()) { + ans = Math.max(ans, x + y + q.peekFirst()[1] - q.peekFirst()[0]); + } + while (!q.isEmpty() && y - x >= q.peekLast()[1] - q.peekLast()[0]) { + q.pollLast(); + } + q.offerLast(p); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int findMaxValueOfEquation(vector>& points, int k) { + int ans = -(1 << 30); + deque> q; + for (auto& p : points) { + int x = p[0], y = p[1]; + while (!q.empty() && x - q.front().first > k) { + q.pop_front(); + } + if (!q.empty()) { + ans = max(ans, x + y + q.front().second - q.front().first); + } + while (!q.empty() && y - x >= q.back().second - q.back().first) { + q.pop_back(); + } + q.emplace_back(x, y); + } + return ans; + } +}; +``` + +```go +func findMaxValueOfEquation(points [][]int, k int) int { + ans := -(1 << 30) + q := [][2]int{} + for _, p := range points { + x, y := p[0], p[1] + for len(q) > 0 && x-q[0][0] > k { + q = q[1:] + } + if len(q) > 0 { + ans = max(ans, x+y+q[0][1]-q[0][0]) + } + for len(q) > 0 && y-x >= q[len(q)-1][1]-q[len(q)-1][0] { + q = q[:len(q)-1] + } + q = append(q, [2]int{x, y}) + } + return ans +} +``` + ```ts function findMaxValueOfEquation(points: number[][], k: number): number { let ans = -(1 << 30); @@ -366,10 +354,6 @@ function findMaxValueOfEquation(points: number[][], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1400-1499/1499.Max Value of Equation/README_EN.md b/solution/1400-1499/1499.Max Value of Equation/README_EN.md index 93d2ade260f89..9d5f4a01ff306 100644 --- a/solution/1400-1499/1499.Max Value of Equation/README_EN.md +++ b/solution/1400-1499/1499.Max Value of Equation/README_EN.md @@ -42,9 +42,9 @@ No other pairs satisfy the condition, so we return the max of 4 and 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,24 +60,6 @@ class Solution: return ans ``` -```python -class Solution: - def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int: - ans = -inf - q = deque() - for x, y in points: - while q and x - q[0][0] > k: - q.popleft() - if q: - ans = max(ans, x + y + q[0][1] - q[0][0]) - while q and y - x >= q[-1][1] - q[-1][0]: - q.pop() - q.append((x, y)) - return ans -``` - -### **Java** - ```java class Solution { public int findMaxValueOfEquation(int[][] points, int k) { @@ -98,31 +80,6 @@ class Solution { } ``` -```java -class Solution { - public int findMaxValueOfEquation(int[][] points, int k) { - int ans = -(1 << 30); - Deque q = new ArrayDeque<>(); - for (var p : points) { - int x = p[0], y = p[1]; - while (!q.isEmpty() && x - q.peekFirst()[0] > k) { - q.pollFirst(); - } - if (!q.isEmpty()) { - ans = Math.max(ans, x + y + q.peekFirst()[1] - q.peekFirst()[0]); - } - while (!q.isEmpty() && y - x >= q.peekLast()[1] - q.peekLast()[0]) { - q.pollLast(); - } - q.offerLast(p); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -144,32 +101,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findMaxValueOfEquation(vector>& points, int k) { - int ans = -(1 << 30); - deque> q; - for (auto& p : points) { - int x = p[0], y = p[1]; - while (!q.empty() && x - q.front().first > k) { - q.pop_front(); - } - if (!q.empty()) { - ans = max(ans, x + y + q.front().second - q.front().first); - } - while (!q.empty() && y - x >= q.back().second - q.back().first) { - q.pop_back(); - } - q.emplace_back(x, y); - } - return ans; - } -}; -``` - -### **Go** - ```go func findMaxValueOfEquation(points [][]int, k int) int { ans := -(1 << 30) @@ -201,29 +132,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -```go -func findMaxValueOfEquation(points [][]int, k int) int { - ans := -(1 << 30) - q := [][2]int{} - for _, p := range points { - x, y := p[0], p[1] - for len(q) > 0 && x-q[0][0] > k { - q = q[1:] - } - if len(q) > 0 { - ans = max(ans, x+y+q[0][1]-q[0][0]) - } - for len(q) > 0 && y-x >= q[len(q)-1][1]-q[len(q)-1][0] { - q = q[:len(q)-1] - } - q = append(q, [2]int{x, y}) - } - return ans -} -``` - -### **TypeScript** - ```ts function findMaxValueOfEquation(points: number[][], k: number): number { let ans = -(1 << 30); @@ -307,6 +215,96 @@ class Heap { } ``` + + +### Solution 2 + + + +```python +class Solution: + def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int: + ans = -inf + q = deque() + for x, y in points: + while q and x - q[0][0] > k: + q.popleft() + if q: + ans = max(ans, x + y + q[0][1] - q[0][0]) + while q and y - x >= q[-1][1] - q[-1][0]: + q.pop() + q.append((x, y)) + return ans +``` + +```java +class Solution { + public int findMaxValueOfEquation(int[][] points, int k) { + int ans = -(1 << 30); + Deque q = new ArrayDeque<>(); + for (var p : points) { + int x = p[0], y = p[1]; + while (!q.isEmpty() && x - q.peekFirst()[0] > k) { + q.pollFirst(); + } + if (!q.isEmpty()) { + ans = Math.max(ans, x + y + q.peekFirst()[1] - q.peekFirst()[0]); + } + while (!q.isEmpty() && y - x >= q.peekLast()[1] - q.peekLast()[0]) { + q.pollLast(); + } + q.offerLast(p); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int findMaxValueOfEquation(vector>& points, int k) { + int ans = -(1 << 30); + deque> q; + for (auto& p : points) { + int x = p[0], y = p[1]; + while (!q.empty() && x - q.front().first > k) { + q.pop_front(); + } + if (!q.empty()) { + ans = max(ans, x + y + q.front().second - q.front().first); + } + while (!q.empty() && y - x >= q.back().second - q.back().first) { + q.pop_back(); + } + q.emplace_back(x, y); + } + return ans; + } +}; +``` + +```go +func findMaxValueOfEquation(points [][]int, k int) int { + ans := -(1 << 30) + q := [][2]int{} + for _, p := range points { + x, y := p[0], p[1] + for len(q) > 0 && x-q[0][0] > k { + q = q[1:] + } + if len(q) > 0 { + ans = max(ans, x+y+q[0][1]-q[0][0]) + } + for len(q) > 0 && y-x >= q[len(q)-1][1]-q[len(q)-1][0] { + q = q[:len(q)-1] + } + q = append(q, [2]int{x, y}) + } + return ans +} +``` + ```ts function findMaxValueOfEquation(points: number[][], k: number): number { let ans = -(1 << 30); @@ -327,10 +325,6 @@ function findMaxValueOfEquation(points: number[][], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1500.Design a File Sharing System/README.md b/solution/1500-1599/1500.Design a File Sharing System/README.md index 91529f90ce19b..50c954706a6aa 100644 --- a/solution/1500-1599/1500.Design a File Sharing System/README.md +++ b/solution/1500-1599/1500.Design a File Sharing System/README.md @@ -82,14 +82,10 @@ fileSharing.join([]); // 一个不拥有任何文件块的用户加入系 ## 解法 - +### 方法一 -### **Python3** - - - ```python class FileSharing: def __init__(self, m: int): @@ -130,10 +126,6 @@ class FileSharing: # param_3 = obj.request(userID,chunkID) ``` -### **Java** - - - ```java class FileSharing { private int chunks; @@ -191,10 +183,6 @@ class FileSharing { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1500.Design a File Sharing System/README_EN.md b/solution/1500-1599/1500.Design a File Sharing System/README_EN.md index 321ad02ad5685..d7b2dd3c3d0e6 100644 --- a/solution/1500-1599/1500.Design a File Sharing System/README_EN.md +++ b/solution/1500-1599/1500.Design a File Sharing System/README_EN.md @@ -77,9 +77,9 @@ fileSharing.join([]); // A user who doesn't have any chunks joined th ## Solutions - +### Solution 1 -### **Python3** + ```python class FileSharing: @@ -121,8 +121,6 @@ class FileSharing: # param_3 = obj.request(userID,chunkID) ``` -### **Java** - ```java class FileSharing { private int chunks; @@ -180,10 +178,6 @@ class FileSharing { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1501.Countries You Can Safely Invest In/README.md b/solution/1500-1599/1501.Countries You Can Safely Invest In/README.md index adc553702b5ca..1e7551138680f 100644 --- a/solution/1500-1599/1501.Countries You Can Safely Invest In/README.md +++ b/solution/1500-1599/1501.Countries You Can Safely Invest In/README.md @@ -120,16 +120,12 @@ Calls 表: ## 解法 - - -**方法一:等值连接 + 分组 + 子查询** +### 方法一:等值连接 + 分组 + 子查询 我们可以使用等值连接,将 `Person` 表和 `Calls` 表连接起来,连接的条件是 `Person.id = Calls.caller_id` 或者 `Person.id = Calls.callee_id`,然后再将连接后的表和 `Country` 表连接起来,连接的条件是 `left(phone_number, 3) = country_code`,最后按照国家分组,计算每个国家的平均通话时长,然后再使用子查询,找出平均通话时长大于全球平均通话时长的国家。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT country @@ -145,6 +141,12 @@ FROM WHERE duration > (SELECT AVG(duration) FROM Calls); ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below WITH @@ -162,3 +164,5 @@ WHERE duration > (SELECT AVG(duration) FROM Calls); ``` + + diff --git a/solution/1500-1599/1501.Countries You Can Safely Invest In/README_EN.md b/solution/1500-1599/1501.Countries You Can Safely Invest In/README_EN.md index ee4fd8ccfefe6..af85c16e0fb31 100644 --- a/solution/1500-1599/1501.Countries You Can Safely Invest In/README_EN.md +++ b/solution/1500-1599/1501.Countries You Can Safely Invest In/README_EN.md @@ -117,14 +117,12 @@ Since Peru is the only country where the average call duration is greater than t ## Solutions -**Solution 1: Equi-Join + Group By + Subquery** +### Solution 1: Equi-Join + Group By + Subquery We can use an equi-join to join the `Person` table and the `Calls` table on the condition of `Person.id = Calls.caller_id` or `Person.id = Calls.callee_id`, and then join the result with the `Country` table on the condition of `left(phone_number, 3) = country_code`. After that, we can group by country and calculate the average call duration for each country. Finally, we can use a subquery to find the countries whose average call duration is greater than the global average call duration. -### **SQL** - ```sql # Write your MySQL query statement below SELECT country @@ -140,6 +138,12 @@ FROM WHERE duration > (SELECT AVG(duration) FROM Calls); ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below WITH @@ -157,3 +161,5 @@ WHERE duration > (SELECT AVG(duration) FROM Calls); ``` + + diff --git a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README.md b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README.md index e10decb24a56b..51b26865f1fc0 100644 --- a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README.md +++ b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README.md @@ -39,28 +39,14 @@ ## 解法 - - -**方法一:排序 + 遍历** +### 方法一:排序 + 遍历 我们可以先将数组 `arr` 排序,然后遍历数组,判断相邻两项的差是否相等即可。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 `arr` 的长度。 -**方法二:哈希表 + 数学** - -我们先找出数组 $arr$ 中的最小值 $a$ 和最大值 $b$,如果数组 $arr$ 可以重排成等差数列,那么公差 $d = \frac{b - a}{n - 1}$ 必须为整数。 - -我们可以用哈希表来记录数组 $arr$ 中的所有元素,然后遍历 $i \in [0, n)$,判断 $a + d \times i$ 是否在哈希表中,如果不在,说明数组 $arr$ 不能重排成等差数列,返回 `false`。否则遍历完数组后,返回 `true`。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `arr` 的长度。 - -### **Python3** - - - ```python class Solution: def canMakeArithmeticProgression(self, arr: List[int]) -> bool: @@ -69,23 +55,6 @@ class Solution: return all(b - a == d for a, b in pairwise(arr)) ``` -```python -class Solution: - def canMakeArithmeticProgression(self, arr: List[int]) -> bool: - a = min(arr) - b = max(arr) - n = len(arr) - if (b - a) % (n - 1): - return False - d = (b - a) // (n - 1) - s = set(arr) - return all(a + d * i in s for i in range(n)) -``` - -### **Java** - - - ```java class Solution { public boolean canMakeArithmeticProgression(int[] arr) { @@ -101,6 +70,120 @@ class Solution { } ``` +```cpp +class Solution { +public: + bool canMakeArithmeticProgression(vector& arr) { + sort(arr.begin(), arr.end()); + int d = arr[1] - arr[0]; + for (int i = 2; i < arr.size(); i++) { + if (arr[i] - arr[i - 1] != d) { + return false; + } + } + return true; + } +}; +``` + +```go +func canMakeArithmeticProgression(arr []int) bool { + sort.Ints(arr) + d := arr[1] - arr[0] + for i := 2; i < len(arr); i++ { + if arr[i]-arr[i-1] != d { + return false + } + } + return true +} +``` + +```ts +function canMakeArithmeticProgression(arr: number[]): boolean { + arr.sort((a, b) => a - b); + const n = arr.length; + for (let i = 2; i < n; i++) { + if (arr[i - 2] - arr[i - 1] !== arr[i - 1] - arr[i]) { + return false; + } + } + return true; +} +``` + +```rust +impl Solution { + pub fn can_make_arithmetic_progression(mut arr: Vec) -> bool { + arr.sort(); + let n = arr.len(); + for i in 2..n { + if arr[i - 2] - arr[i - 1] != arr[i - 1] - arr[i] { + return false; + } + } + true + } +} +``` + +```js +/** + * @param {number[]} arr + * @return {boolean} + */ +var canMakeArithmeticProgression = function (arr) { + arr.sort((a, b) => a - b); + for (let i = 1; i < arr.length - 1; i++) { + if (arr[i] << 1 != arr[i - 1] + arr[i + 1]) { + return false; + } + } + return true; +}; +``` + +```c +int cmp(const void* a, const void* b) { + return *(int*) a - *(int*) b; +} + +bool canMakeArithmeticProgression(int* arr, int arrSize) { + qsort(arr, arrSize, sizeof(int), cmp); + for (int i = 2; i < arrSize; i++) { + if (arr[i - 2] - arr[i - 1] != arr[i - 1] - arr[i]) { + return 0; + } + } + return 1; +} +``` + + + +### 方法二:哈希表 + 数学 + +我们先找出数组 $arr$ 中的最小值 $a$ 和最大值 $b$,如果数组 $arr$ 可以重排成等差数列,那么公差 $d = \frac{b - a}{n - 1}$ 必须为整数。 + +我们可以用哈希表来记录数组 $arr$ 中的所有元素,然后遍历 $i \in [0, n)$,判断 $a + d \times i$ 是否在哈希表中,如果不在,说明数组 $arr$ 不能重排成等差数列,返回 `false`。否则遍历完数组后,返回 `true`。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `arr` 的长度。 + + + +```python +class Solution: + def canMakeArithmeticProgression(self, arr: List[int]) -> bool: + a = min(arr) + b = max(arr) + n = len(arr) + if (b - a) % (n - 1): + return False + d = (b - a) // (n - 1) + s = set(arr) + return all(a + d * i in s for i in range(n)) +``` + ```java class Solution { public boolean canMakeArithmeticProgression(int[] arr) { @@ -126,24 +209,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool canMakeArithmeticProgression(vector& arr) { - sort(arr.begin(), arr.end()); - int d = arr[1] - arr[0]; - for (int i = 2; i < arr.size(); i++) { - if (arr[i] - arr[i - 1] != d) { - return false; - } - } - return true; - } -}; -``` - ```cpp class Solution { public: @@ -165,21 +230,6 @@ public: }; ``` -### **Go** - -```go -func canMakeArithmeticProgression(arr []int) bool { - sort.Ints(arr) - d := arr[1] - arr[0] - for i := 2; i < len(arr); i++ { - if arr[i]-arr[i-1] != d { - return false - } - } - return true -} -``` - ```go func canMakeArithmeticProgression(arr []int) bool { a, b := slices.Min(arr), slices.Max(arr) @@ -201,39 +251,6 @@ func canMakeArithmeticProgression(arr []int) bool { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} arr - * @return {boolean} - */ -var canMakeArithmeticProgression = function (arr) { - arr.sort((a, b) => a - b); - for (let i = 1; i < arr.length - 1; i++) { - if (arr[i] << 1 != arr[i - 1] + arr[i + 1]) { - return false; - } - } - return true; -}; -``` - -### **TypeScript** - -```ts -function canMakeArithmeticProgression(arr: number[]): boolean { - arr.sort((a, b) => a - b); - const n = arr.length; - for (let i = 2; i < n; i++) { - if (arr[i - 2] - arr[i - 1] !== arr[i - 1] - arr[i]) { - return false; - } - } - return true; -} -``` - ```ts function canMakeArithmeticProgression(arr: number[]): boolean { const n = arr.length; @@ -261,23 +278,6 @@ function canMakeArithmeticProgression(arr: number[]): boolean { } ``` -### **Rust** - -```rust -impl Solution { - pub fn can_make_arithmetic_progression(mut arr: Vec) -> bool { - arr.sort(); - let n = arr.len(); - for i in 2..n { - if arr[i - 2] - arr[i - 1] != arr[i - 1] - arr[i] { - return false; - } - } - true - } -} -``` - ```rust use std::collections::HashMap; impl Solution { @@ -310,28 +310,6 @@ impl Solution { } ``` -### **C** - -```c -int cmp(const void* a, const void* b) { - return *(int*) a - *(int*) b; -} - -bool canMakeArithmeticProgression(int* arr, int arrSize) { - qsort(arr, arrSize, sizeof(int), cmp); - for (int i = 2; i < arrSize; i++) { - if (arr[i - 2] - arr[i - 1] != arr[i - 1] - arr[i]) { - return 0; - } - } - return 1; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README_EN.md b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README_EN.md index e33adc443584a..6e74efb41c245 100644 --- a/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README_EN.md +++ b/solution/1500-1599/1502.Can Make Arithmetic Progression From Sequence/README_EN.md @@ -35,24 +35,14 @@ ## Solutions -**Solution 1: Sorting + Traversal** +### Solution 1: Sorting + Traversal We can first sort the array `arr`, then traverse the array, and check whether the difference between adjacent items is equal. The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array `arr`. -**Solution 2: Hash Table + Mathematics** - -We first find the minimum value $a$ and the maximum value $b$ in the array $arr$. If the array $arr$ can be rearranged into an arithmetic sequence, then the common difference $d = \frac{b - a}{n - 1}$ must be an integer. - -We can use a hash table to record all elements in the array $arr$, then traverse $i \in [0, n)$, and check whether $a + d \times i$ is in the hash table. If not, it means that the array $arr$ cannot be rearranged into an arithmetic sequence, and we return `false`. Otherwise, after traversing the array, we return `true`. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array `arr`. - -### **Python3** - ```python class Solution: def canMakeArithmeticProgression(self, arr: List[int]) -> bool: @@ -61,21 +51,6 @@ class Solution: return all(b - a == d for a, b in pairwise(arr)) ``` -```python -class Solution: - def canMakeArithmeticProgression(self, arr: List[int]) -> bool: - a = min(arr) - b = max(arr) - n = len(arr) - if (b - a) % (n - 1): - return False - d = (b - a) // (n - 1) - s = set(arr) - return all(a + d * i in s for i in range(n)) -``` - -### **Java** - ```java class Solution { public boolean canMakeArithmeticProgression(int[] arr) { @@ -91,6 +66,120 @@ class Solution { } ``` +```cpp +class Solution { +public: + bool canMakeArithmeticProgression(vector& arr) { + sort(arr.begin(), arr.end()); + int d = arr[1] - arr[0]; + for (int i = 2; i < arr.size(); i++) { + if (arr[i] - arr[i - 1] != d) { + return false; + } + } + return true; + } +}; +``` + +```go +func canMakeArithmeticProgression(arr []int) bool { + sort.Ints(arr) + d := arr[1] - arr[0] + for i := 2; i < len(arr); i++ { + if arr[i]-arr[i-1] != d { + return false + } + } + return true +} +``` + +```ts +function canMakeArithmeticProgression(arr: number[]): boolean { + arr.sort((a, b) => a - b); + const n = arr.length; + for (let i = 2; i < n; i++) { + if (arr[i - 2] - arr[i - 1] !== arr[i - 1] - arr[i]) { + return false; + } + } + return true; +} +``` + +```rust +impl Solution { + pub fn can_make_arithmetic_progression(mut arr: Vec) -> bool { + arr.sort(); + let n = arr.len(); + for i in 2..n { + if arr[i - 2] - arr[i - 1] != arr[i - 1] - arr[i] { + return false; + } + } + true + } +} +``` + +```js +/** + * @param {number[]} arr + * @return {boolean} + */ +var canMakeArithmeticProgression = function (arr) { + arr.sort((a, b) => a - b); + for (let i = 1; i < arr.length - 1; i++) { + if (arr[i] << 1 != arr[i - 1] + arr[i + 1]) { + return false; + } + } + return true; +}; +``` + +```c +int cmp(const void* a, const void* b) { + return *(int*) a - *(int*) b; +} + +bool canMakeArithmeticProgression(int* arr, int arrSize) { + qsort(arr, arrSize, sizeof(int), cmp); + for (int i = 2; i < arrSize; i++) { + if (arr[i - 2] - arr[i - 1] != arr[i - 1] - arr[i]) { + return 0; + } + } + return 1; +} +``` + + + +### Solution 2: Hash Table + Mathematics + +We first find the minimum value $a$ and the maximum value $b$ in the array $arr$. If the array $arr$ can be rearranged into an arithmetic sequence, then the common difference $d = \frac{b - a}{n - 1}$ must be an integer. + +We can use a hash table to record all elements in the array $arr$, then traverse $i \in [0, n)$, and check whether $a + d \times i$ is in the hash table. If not, it means that the array $arr$ cannot be rearranged into an arithmetic sequence, and we return `false`. Otherwise, after traversing the array, we return `true`. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array `arr`. + + + +```python +class Solution: + def canMakeArithmeticProgression(self, arr: List[int]) -> bool: + a = min(arr) + b = max(arr) + n = len(arr) + if (b - a) % (n - 1): + return False + d = (b - a) // (n - 1) + s = set(arr) + return all(a + d * i in s for i in range(n)) +``` + ```java class Solution { public boolean canMakeArithmeticProgression(int[] arr) { @@ -116,24 +205,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool canMakeArithmeticProgression(vector& arr) { - sort(arr.begin(), arr.end()); - int d = arr[1] - arr[0]; - for (int i = 2; i < arr.size(); i++) { - if (arr[i] - arr[i - 1] != d) { - return false; - } - } - return true; - } -}; -``` - ```cpp class Solution { public: @@ -155,21 +226,6 @@ public: }; ``` -### **Go** - -```go -func canMakeArithmeticProgression(arr []int) bool { - sort.Ints(arr) - d := arr[1] - arr[0] - for i := 2; i < len(arr); i++ { - if arr[i]-arr[i-1] != d { - return false - } - } - return true -} -``` - ```go func canMakeArithmeticProgression(arr []int) bool { a, b := slices.Min(arr), slices.Max(arr) @@ -191,39 +247,6 @@ func canMakeArithmeticProgression(arr []int) bool { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} arr - * @return {boolean} - */ -var canMakeArithmeticProgression = function (arr) { - arr.sort((a, b) => a - b); - for (let i = 1; i < arr.length - 1; i++) { - if (arr[i] << 1 != arr[i - 1] + arr[i + 1]) { - return false; - } - } - return true; -}; -``` - -### **TypeScript** - -```ts -function canMakeArithmeticProgression(arr: number[]): boolean { - arr.sort((a, b) => a - b); - const n = arr.length; - for (let i = 2; i < n; i++) { - if (arr[i - 2] - arr[i - 1] !== arr[i - 1] - arr[i]) { - return false; - } - } - return true; -} -``` - ```ts function canMakeArithmeticProgression(arr: number[]): boolean { const n = arr.length; @@ -251,23 +274,6 @@ function canMakeArithmeticProgression(arr: number[]): boolean { } ``` -### **Rust** - -```rust -impl Solution { - pub fn can_make_arithmetic_progression(mut arr: Vec) -> bool { - arr.sort(); - let n = arr.len(); - for i in 2..n { - if arr[i - 2] - arr[i - 1] != arr[i - 1] - arr[i] { - return false; - } - } - true - } -} -``` - ```rust use std::collections::HashMap; impl Solution { @@ -300,28 +306,6 @@ impl Solution { } ``` -### **C** - -```c -int cmp(const void* a, const void* b) { - return *(int*) a - *(int*) b; -} - -bool canMakeArithmeticProgression(int* arr, int arrSize) { - qsort(arr, arrSize, sizeof(int), cmp); - for (int i = 2; i < arrSize; i++) { - if (arr[i - 2] - arr[i - 1] != arr[i - 1] - arr[i]) { - return 0; - } - } - return 1; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/README.md b/solution/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/README.md index ded1ece1f9715..b4eacd642d35e 100644 --- a/solution/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/README.md +++ b/solution/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/README.md @@ -68,9 +68,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 题目关键点在于两只蚂蚁相遇,然后分别调转方向的情况,实际上相当于两只蚂蚁继续往原来的方向移动。因此,我们只需要求出所有蚂蚁中最远的那只蚂蚁的移动距离即可。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int: @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int getLastMoment(int n, int[] left, int[] right) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go func getLastMoment(n int, left []int, right []int) (ans int) { for _, x := range left { @@ -146,8 +132,6 @@ func getLastMoment(n int, left []int, right []int) (ans int) { } ``` -### **TypeScript** - ```ts function getLastMoment(n: number, left: number[], right: number[]): number { let ans = 0; @@ -161,10 +145,6 @@ function getLastMoment(n: number, left: number[], right: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/README_EN.md b/solution/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/README_EN.md index c6f44f855aeb2..ba7e2c2b309a6 100644 --- a/solution/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/README_EN.md +++ b/solution/1500-1599/1503.Last Moment Before All Ants Fall Out of a Plank/README_EN.md @@ -57,9 +57,9 @@ The last moment when an ant was on the plank is t = 4 seconds. After that, it fa ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int getLastMoment(int n, int[] left, int[] right) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +103,6 @@ public: }; ``` -### **Go** - ```go func getLastMoment(n int, left []int, right []int) (ans int) { for _, x := range left { @@ -121,8 +115,6 @@ func getLastMoment(n int, left []int, right []int) (ans int) { } ``` -### **TypeScript** - ```ts function getLastMoment(n: number, left: number[], right: number[]): number { let ans = 0; @@ -136,10 +128,6 @@ function getLastMoment(n: number, left: number[], right: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1504.Count Submatrices With All Ones/README.md b/solution/1500-1599/1504.Count Submatrices With All Ones/README.md index e4b5c38141907..048ca0e7b9d0c 100644 --- a/solution/1500-1599/1504.Count Submatrices With All Ones/README.md +++ b/solution/1500-1599/1504.Count Submatrices With All Ones/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:枚举 + 前缀和** +### 方法一:枚举 + 前缀和 我们可以枚举矩阵的右下角 $(i, j)$,然后向上枚举矩阵的第一行 $k$,那么每一行以 $(i, j)$ 为右下角的矩阵的宽度就是 $\min_{k \leq i} \textit{g}[k][j]$,其中 $\textit{g}[k][j]$ 表示第 $k$ 行以 $(k, j)$ 为右下角的矩阵的宽度。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def numSubmat(self, mat: List[List[int]]) -> int: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numSubmat(int[][] mat) { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +140,6 @@ public: }; ``` -### **Go** - ```go func numSubmat(mat [][]int) (ans int) { m, n := len(mat), len(mat[0]) @@ -183,10 +169,6 @@ func numSubmat(mat [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1504.Count Submatrices With All Ones/README_EN.md b/solution/1500-1599/1504.Count Submatrices With All Ones/README_EN.md index b2d25b30d65b0..1db78d29ba7f1 100644 --- a/solution/1500-1599/1504.Count Submatrices With All Ones/README_EN.md +++ b/solution/1500-1599/1504.Count Submatrices With All Ones/README_EN.md @@ -47,9 +47,9 @@ Total number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numSubmat(int[][] mat) { @@ -99,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +125,6 @@ public: }; ``` -### **Go** - ```go func numSubmat(mat [][]int) (ans int) { m, n := len(mat), len(mat[0]) @@ -160,10 +154,6 @@ func numSubmat(mat [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/README.md b/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/README.md index 48cc0171dfe2f..9a108c873be5d 100644 --- a/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/README.md +++ b/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:贪心算法 + 树状数组** +### 方法一:贪心算法 + 树状数组 树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作: @@ -95,10 +93,6 @@ -### **Python3** - - - ```python class BinaryIndexedTree: def __init__(self, n): @@ -145,10 +139,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String minInteger(String num, int k) { @@ -213,8 +203,6 @@ class BinaryIndexedTree { } ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -275,8 +263,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -335,10 +321,6 @@ func minInteger(num string, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/README_EN.md b/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/README_EN.md index 892eb1f1f358e..e520fb76cf072 100644 --- a/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/README_EN.md +++ b/solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/README_EN.md @@ -44,12 +44,10 @@ ## Solutions -Segment Tree. +### Solution 1 -### **Python3** - ```python class BinaryIndexedTree: def __init__(self, n): @@ -96,8 +94,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String minInteger(String num, int k) { @@ -162,8 +158,6 @@ class BinaryIndexedTree { } ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -224,8 +218,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -284,10 +276,6 @@ func minInteger(num string, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1506.Find Root of N-Ary Tree/README.md b/solution/1500-1599/1506.Find Root of N-Ary Tree/README.md index 34bd51d8fe00e..f3be31a8a972b 100644 --- a/solution/1500-1599/1506.Find Root of N-Ary Tree/README.md +++ b/solution/1500-1599/1506.Find Root of N-Ary Tree/README.md @@ -72,9 +72,7 @@ findRoot 函数应该返回根 Node(1) ,驱动程序代码将序列化它并 ## 解法 - - -**方法一:位运算** +### 方法一:位运算 对于一棵 N 叉树的节点,如果该节点是根节点,那么该节点只会出现一次在数组 `tree` 中;而如果该节点不是根节点,那么该节点会出现两次,一次在数组 `tree` 中,一次在该节点的父节点的 `children` 数组中。 @@ -86,10 +84,6 @@ findRoot 函数应该返回根 Node(1) ,驱动程序代码将序列化它并 -### **Python3** - - - ```python """ # Definition for a Node. @@ -110,10 +104,6 @@ class Solution: return next(node for node in tree if node.val == x) ``` -### **Java** - - - ```java /* // Definition for a Node. @@ -156,8 +146,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -198,8 +186,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -225,8 +211,6 @@ func findRoot(tree []*Node) *Node { } ``` -### **TypeScript** - ```ts /** * Definition for Node. @@ -252,10 +236,6 @@ function findRoot(tree: Node[]): Node | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1506.Find Root of N-Ary Tree/README_EN.md b/solution/1500-1599/1506.Find Root of N-Ary Tree/README_EN.md index 2a44ce3d40c31..ce6d12874ceac 100644 --- a/solution/1500-1599/1506.Find Root of N-Ary Tree/README_EN.md +++ b/solution/1500-1599/1506.Find Root of N-Ary Tree/README_EN.md @@ -66,9 +66,9 @@ The input data and serialized Node(1) are the same, so the test passes. ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -90,8 +90,6 @@ class Solution: return next(node for node in tree if node.val == x) ``` -### **Java** - ```java /* // Definition for a Node. @@ -134,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -176,8 +172,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a Node. @@ -203,8 +197,6 @@ func findRoot(tree []*Node) *Node { } ``` -### **TypeScript** - ```ts /** * Definition for Node. @@ -230,10 +222,6 @@ function findRoot(tree: Node[]): Node | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1507.Reformat Date/README.md b/solution/1500-1599/1507.Reformat Date/README.md index 8e220bce53b54..f490d598b97af 100644 --- a/solution/1500-1599/1507.Reformat Date/README.md +++ b/solution/1500-1599/1507.Reformat Date/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 将字符串按空格分割为三个部分,分别为 `day`、`month` 和 `year`,然后拼接为 `YYYY-MM-DD` 的格式。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def reformatDate(self, date: str) -> str: @@ -77,10 +71,6 @@ class Solution: return "-".join(s) ``` -### **Java** - - - ```java class Solution { public String reformatDate(String date) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +98,6 @@ public: }; ``` -### **Go** - ```go func reformatDate(date string) string { s := strings.Split(date, " ") @@ -123,7 +109,15 @@ func reformatDate(date string) string { } ``` -### **PHP** +```ts +function reformatDate(date: string): string { + const s = date.split(' '); + const months = ' JanFebMarAprMayJunJulAugSepOctNovDec'; + const day = parseInt(s[0].substring(0, s[0].length - 2)); + const month = Math.floor(months.indexOf(s[1]) / 3) + 1; + return `${s[2]}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`; +} +``` ```php class Solution { @@ -158,22 +152,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function reformatDate(date: string): string { - const s = date.split(' '); - const months = ' JanFebMarAprMayJunJulAugSepOctNovDec'; - const day = parseInt(s[0].substring(0, s[0].length - 2)); - const month = Math.floor(months.indexOf(s[1]) / 3) + 1; - return `${s[2]}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1507.Reformat Date/README_EN.md b/solution/1500-1599/1507.Reformat Date/README_EN.md index ed479666ef9db..28105e4b91ee7 100644 --- a/solution/1500-1599/1507.Reformat Date/README_EN.md +++ b/solution/1500-1599/1507.Reformat Date/README_EN.md @@ -51,9 +51,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return "-".join(s) ``` -### **Java** - ```java class Solution { public String reformatDate(String date) { @@ -80,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +93,6 @@ public: }; ``` -### **Go** - ```go func reformatDate(date string) string { s := strings.Split(date, " ") @@ -110,7 +104,15 @@ func reformatDate(date string) string { } ``` -### **PHP** +```ts +function reformatDate(date: string): string { + const s = date.split(' '); + const months = ' JanFebMarAprMayJunJulAugSepOctNovDec'; + const day = parseInt(s[0].substring(0, s[0].length - 2)); + const month = Math.floor(months.indexOf(s[1]) / 3) + 1; + return `${s[2]}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`; +} +``` ```php class Solution { @@ -145,22 +147,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function reformatDate(date: string): string { - const s = date.split(' '); - const months = ' JanFebMarAprMayJunJulAugSepOctNovDec'; - const day = parseInt(s[0].substring(0, s[0].length - 2)); - const month = Math.floor(months.indexOf(s[1]) / 3) + 1; - return `${s[2]}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README.md b/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README.md index 5ece9363290a8..63202308465c2 100644 --- a/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README.md +++ b/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 按照题意生成 `arr` 数组,排序后,对 $[left-1,.. right-1]$ 范围的所有元素求和,得到结果。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int: @@ -76,10 +70,6 @@ class Solution: return sum(arr[left - 1 : right]) % mod ``` -### **Java** - - - ```java class Solution { public int rangeSum(int[] nums, int n, int left, int right) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func rangeSum(nums []int, n int, left int, right int) (ans int) { var arr []int @@ -148,10 +134,6 @@ func rangeSum(nums []int, n int, left int, right int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README_EN.md b/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README_EN.md index 38d3942690a5a..bd02e2221a15a 100644 --- a/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README_EN.md +++ b/solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return sum(arr[left - 1 : right]) % mod ``` -### **Java** - ```java class Solution { public int rangeSum(int[] nums, int n, int left, int right) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +107,6 @@ public: }; ``` -### **Go** - ```go func rangeSum(nums []int, n int, left int, right int) (ans int) { var arr []int @@ -132,10 +126,6 @@ func rangeSum(nums []int, n int, left int, right int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1509.Minimum Difference Between Largest and Smallest Value in Three Moves/README.md b/solution/1500-1599/1509.Minimum Difference Between Largest and Smallest Value in Three Moves/README.md index 34d4901d5eb5d..b8ddecb0c6998 100644 --- a/solution/1500-1599/1509.Minimum Difference Between Largest and Smallest Value in Three Moves/README.md +++ b/solution/1500-1599/1509.Minimum Difference Between Largest and Smallest Value in Three Moves/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:排序 + 贪心** +### 方法一:排序 + 贪心 我们可以先判断数组长度是否小于 $5$,如果小于 $5$,那么直接返回 $0$。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def minDifference(self, nums: List[int]) -> int: @@ -94,10 +88,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minDifference(int[] nums) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func minDifference(nums []int) int { n := len(nums) @@ -155,10 +141,6 @@ func minDifference(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1509.Minimum Difference Between Largest and Smallest Value in Three Moves/README_EN.md b/solution/1500-1599/1509.Minimum Difference Between Largest and Smallest Value in Three Moves/README_EN.md index be30f982fb8fe..78a3302640b1e 100644 --- a/solution/1500-1599/1509.Minimum Difference Between Largest and Smallest Value in Three Moves/README_EN.md +++ b/solution/1500-1599/1509.Minimum Difference Between Largest and Smallest Value in Three Moves/README_EN.md @@ -57,9 +57,9 @@ After performing 3 moves, the difference between the minimum and maximum is 7 - ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minDifference(int[] nums) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +112,6 @@ public: }; ``` -### **Go** - ```go func minDifference(nums []int) int { n := len(nums) @@ -134,10 +128,6 @@ func minDifference(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1510.Stone Game IV/README.md b/solution/1500-1599/1510.Stone Game IV/README.md index cad55e960b96a..2a2d0910c3513 100644 --- a/solution/1500-1599/1510.Stone Game IV/README.md +++ b/solution/1500-1599/1510.Stone Game IV/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i)$,表示当前石子堆中有 $i$ 个石子时,当前玩家是否能赢得比赛。如果当前玩家能赢得比赛,则返回 $true$,否则返回 $false$。那么答案即为 $dfs(n)$。 @@ -80,32 +78,8 @@ 时间复杂度 $O(n \times \sqrt{n})$,空间复杂度 $O(n)$。其中 $n$ 为石子堆中石子的数量。 -**方法二:动态规划** - -我们也可以使用动态规划求解本题。 - -定义数组 $f$,其中 $f[i]$ 表示当前石子堆中有 $i$ 个石子时,当前玩家是否能赢得比赛。如果当前玩家能赢得比赛,则 $f[i]$ 为 $true$,否则为 $false$。那么答案即为 $f[n]$。 - -我们在 $[1,..n]$ 的范围内枚举 $i$,并在 $[1,..i]$ 的范围内枚举 $j$,其中 $j$ 为平方数,如果当前玩家拿走 $j$ 个石子后,另一个玩家无法赢得比赛,则当前玩家赢得比赛,即 $f[i] = true$。如果枚举完所有的 $j$,都无法满足上述条件,则当前玩家输掉比赛,即 $f[i] = false$。因此我们可以得到状态转移方程: - -$$ -f[i]= -\begin{cases} -true, & \text{if } \exists j \in [1,..i], j^2 \leq i \text{ and } f[i-j^2] = false\\ -false, & \text{otherwise} -\end{cases} -$$ - -最后,我们返回 $f[n]$ 即可。 - -时间复杂度 $O(n \times \sqrt{n})$,空间复杂度 $O(n)$。其中 $n$ 为石子堆中石子的数量。 - -### **Python3** - - - ```python class Solution: def winnerSquareGame(self, n: int) -> bool: @@ -123,24 +97,6 @@ class Solution: return dfs(n) ``` -```python -class Solution: - def winnerSquareGame(self, n: int) -> bool: - f = [False] * (n + 1) - for i in range(1, n + 1): - j = 1 - while j <= i // j: - if not f[i - j * j]: - f[i] = True - break - j += 1 - return f[n] -``` - -### **Java** - - - ```java class Solution { private Boolean[] f; @@ -167,25 +123,6 @@ class Solution { } ``` -```java -class Solution { - public boolean winnerSquareGame(int n) { - boolean[] f = new boolean[n + 1]; - for (int i = 1; i <= n; ++i) { - for (int j = 1; j <= i / j; ++j) { - if (!f[i - j * j]) { - f[i] = true; - break; - } - } - } - return f[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -213,27 +150,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool winnerSquareGame(int n) { - bool f[n + 1]; - memset(f, false, sizeof(f)); - for (int i = 1; i <= n; ++i) { - for (int j = 1; j <= i / j; ++j) { - if (!f[i - j * j]) { - f[i] = true; - break; - } - } - } - return f[n]; - } -}; -``` - -### **Go** - ```go func winnerSquareGame(n int) bool { f := make([]int, n+1) @@ -258,23 +174,6 @@ func winnerSquareGame(n int) bool { } ``` -```go -func winnerSquareGame(n int) bool { - f := make([]bool, n+1) - for i := 1; i <= n; i++ { - for j := 1; j <= i/j; j++ { - if !f[i-j*j] { - f[i] = true - break - } - } - } - return f[n] -} -``` - -### **TypeScript** - ```ts function winnerSquareGame(n: number): boolean { const f: number[] = new Array(n + 1).fill(0); @@ -298,6 +197,95 @@ function winnerSquareGame(n: number): boolean { } ``` + + +### 方法二:动态规划 + +我们也可以使用动态规划求解本题。 + +定义数组 $f$,其中 $f[i]$ 表示当前石子堆中有 $i$ 个石子时,当前玩家是否能赢得比赛。如果当前玩家能赢得比赛,则 $f[i]$ 为 $true$,否则为 $false$。那么答案即为 $f[n]$。 + +我们在 $[1,..n]$ 的范围内枚举 $i$,并在 $[1,..i]$ 的范围内枚举 $j$,其中 $j$ 为平方数,如果当前玩家拿走 $j$ 个石子后,另一个玩家无法赢得比赛,则当前玩家赢得比赛,即 $f[i] = true$。如果枚举完所有的 $j$,都无法满足上述条件,则当前玩家输掉比赛,即 $f[i] = false$。因此我们可以得到状态转移方程: + +$$ +f[i]= +\begin{cases} +true, & \text{if } \exists j \in [1,..i], j^2 \leq i \text{ and } f[i-j^2] = false\\ +false, & \text{otherwise} +\end{cases} +$$ + +最后,我们返回 $f[n]$ 即可。 + +时间复杂度 $O(n \times \sqrt{n})$,空间复杂度 $O(n)$。其中 $n$ 为石子堆中石子的数量。 + + + +```python +class Solution: + def winnerSquareGame(self, n: int) -> bool: + f = [False] * (n + 1) + for i in range(1, n + 1): + j = 1 + while j <= i // j: + if not f[i - j * j]: + f[i] = True + break + j += 1 + return f[n] +``` + +```java +class Solution { + public boolean winnerSquareGame(int n) { + boolean[] f = new boolean[n + 1]; + for (int i = 1; i <= n; ++i) { + for (int j = 1; j <= i / j; ++j) { + if (!f[i - j * j]) { + f[i] = true; + break; + } + } + } + return f[n]; + } +} +``` + +```cpp +class Solution { +public: + bool winnerSquareGame(int n) { + bool f[n + 1]; + memset(f, false, sizeof(f)); + for (int i = 1; i <= n; ++i) { + for (int j = 1; j <= i / j; ++j) { + if (!f[i - j * j]) { + f[i] = true; + break; + } + } + } + return f[n]; + } +}; +``` + +```go +func winnerSquareGame(n int) bool { + f := make([]bool, n+1) + for i := 1; i <= n; i++ { + for j := 1; j <= i/j; j++ { + if !f[i-j*j] { + f[i] = true + break + } + } + } + return f[n] +} +``` + ```ts function winnerSquareGame(n: number): boolean { const f: boolean[] = new Array(n + 1).fill(false); @@ -313,10 +301,6 @@ function winnerSquareGame(n: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1510.Stone Game IV/README_EN.md b/solution/1500-1599/1510.Stone Game IV/README_EN.md index f881d2651ce62..2d228d29f481e 100644 --- a/solution/1500-1599/1510.Stone Game IV/README_EN.md +++ b/solution/1500-1599/1510.Stone Game IV/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,22 +66,6 @@ class Solution: return dfs(n) ``` -```python -class Solution: - def winnerSquareGame(self, n: int) -> bool: - f = [False] * (n + 1) - for i in range(1, n + 1): - j = 1 - while j <= i // j: - if not f[i - j * j]: - f[i] = True - break - j += 1 - return f[n] -``` - -### **Java** - ```java class Solution { private Boolean[] f; @@ -108,25 +92,6 @@ class Solution { } ``` -```java -class Solution { - public boolean winnerSquareGame(int n) { - boolean[] f = new boolean[n + 1]; - for (int i = 1; i <= n; ++i) { - for (int j = 1; j <= i / j; ++j) { - if (!f[i - j * j]) { - f[i] = true; - break; - } - } - } - return f[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -154,27 +119,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool winnerSquareGame(int n) { - bool f[n + 1]; - memset(f, false, sizeof(f)); - for (int i = 1; i <= n; ++i) { - for (int j = 1; j <= i / j; ++j) { - if (!f[i - j * j]) { - f[i] = true; - break; - } - } - } - return f[n]; - } -}; -``` - -### **Go** - ```go func winnerSquareGame(n int) bool { f := make([]int, n+1) @@ -199,23 +143,6 @@ func winnerSquareGame(n int) bool { } ``` -```go -func winnerSquareGame(n int) bool { - f := make([]bool, n+1) - for i := 1; i <= n; i++ { - for j := 1; j <= i/j; j++ { - if !f[i-j*j] { - f[i] = true - break - } - } - } - return f[n] -} -``` - -### **TypeScript** - ```ts function winnerSquareGame(n: number): boolean { const f: number[] = new Array(n + 1).fill(0); @@ -239,6 +166,77 @@ function winnerSquareGame(n: number): boolean { } ``` + + +### Solution 2 + + + +```python +class Solution: + def winnerSquareGame(self, n: int) -> bool: + f = [False] * (n + 1) + for i in range(1, n + 1): + j = 1 + while j <= i // j: + if not f[i - j * j]: + f[i] = True + break + j += 1 + return f[n] +``` + +```java +class Solution { + public boolean winnerSquareGame(int n) { + boolean[] f = new boolean[n + 1]; + for (int i = 1; i <= n; ++i) { + for (int j = 1; j <= i / j; ++j) { + if (!f[i - j * j]) { + f[i] = true; + break; + } + } + } + return f[n]; + } +} +``` + +```cpp +class Solution { +public: + bool winnerSquareGame(int n) { + bool f[n + 1]; + memset(f, false, sizeof(f)); + for (int i = 1; i <= n; ++i) { + for (int j = 1; j <= i / j; ++j) { + if (!f[i - j * j]) { + f[i] = true; + break; + } + } + } + return f[n]; + } +}; +``` + +```go +func winnerSquareGame(n int) bool { + f := make([]bool, n+1) + for i := 1; i <= n; i++ { + for j := 1; j <= i/j; j++ { + if !f[i-j*j] { + f[i] = true + break + } + } + } + return f[n] +} +``` + ```ts function winnerSquareGame(n: number): boolean { const f: boolean[] = new Array(n + 1).fill(false); @@ -254,10 +252,6 @@ function winnerSquareGame(n: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1511.Customer Order Frequency/README.md b/solution/1500-1599/1511.Customer Order Frequency/README.md index d7720fb828436..70a47744a817a 100644 --- a/solution/1500-1599/1511.Customer Order Frequency/README.md +++ b/solution/1500-1599/1511.Customer Order Frequency/README.md @@ -115,16 +115,12 @@ Moustafa 在2020年6月花费了110 (10 * 2 + 45 * 2), 在7月花费了0. ## 解法 - - -**方法一:等值连接 + 分组求和** +### 方法一:等值连接 + 分组求和 我们可以使用 `JOIN` 语句,连接 `Orders` 和 `Product` 表,再连接 `Customers` 表,筛选出 `order_date` 在 $2020$ 年的记录,然后使用 `GROUP BY` 语句,按照 `customer_id` 分组,使用 `HAVING` 语句,筛选出 $6$ 月和 $7$ 月花费大于等于 $100$ 的客户。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT customer_id, name @@ -140,3 +136,5 @@ HAVING ``` + + diff --git a/solution/1500-1599/1511.Customer Order Frequency/README_EN.md b/solution/1500-1599/1511.Customer Order Frequency/README_EN.md index 84dee7548762b..f7e068da14f56 100644 --- a/solution/1500-1599/1511.Customer Order Frequency/README_EN.md +++ b/solution/1500-1599/1511.Customer Order Frequency/README_EN.md @@ -112,14 +112,12 @@ Moustafa spent 110 (10 * 2 + 45 * 2) in June and 0 in July 2020. ## Solutions -**Solution 1: Join + Group By + Having** +### Solution 1: Join + Group By + Having We can use the `JOIN` statement to join the `Orders` table and the `Product` table, and then join the result with the `Customers` table. We can filter out the records where the `order_date` is not in the year $2020$, and then use the `GROUP BY` statement to group the data by `customer_id`. Finally, we can use the `HAVING` statement to filter out the customers whose spending in June and July is greater than or equal to $100$. -### **SQL** - ```sql # Write your MySQL query statement below SELECT customer_id, name @@ -135,3 +133,5 @@ HAVING ``` + + diff --git a/solution/1500-1599/1512.Number of Good Pairs/README.md b/solution/1500-1599/1512.Number of Good Pairs/README.md index c099e0a28eb1e..16b81d7f6821d 100644 --- a/solution/1500-1599/1512.Number of Good Pairs/README.md +++ b/solution/1500-1599/1512.Number of Good Pairs/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 遍历数组,对于每个元素 $x$,计算 $x$ 之前有多少个元素与其相等,即为 $x$ 与之前元素组成的好数对的数目。遍历完数组后,即可得到答案。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: @@ -69,17 +63,6 @@ class Solution: return ans ``` -```python -class Solution: - def numIdenticalPairs(self, nums: List[int]) -> int: - cnt = Counter(nums) - return sum(v * (v - 1) for v in cnt.values()) >> 1 -``` - -### **Java** - - - ```java class Solution { public int numIdenticalPairs(int[] nums) { @@ -93,36 +76,114 @@ class Solution { } ``` -```java +```cpp class Solution { - public int numIdenticalPairs(int[] nums) { - int[] cnt = new int[101]; - for (int x : nums) { - ++cnt[x]; - } +public: + int numIdenticalPairs(vector& nums) { int ans = 0; - for (int v : cnt) { - ans += v * (v - 1) / 2; + int cnt[101]{}; + for (int& x : nums) { + ans += cnt[x]++; } return ans; } +}; +``` + +```go +func numIdenticalPairs(nums []int) (ans int) { + cnt := [101]int{} + for _, x := range nums { + ans += cnt[x] + cnt[x]++ + } + return } ``` -### **C++** +```ts +function numIdenticalPairs(nums: number[]): number { + const cnt = new Array(101).fill(0); + let ans = 0; + for (const x of nums) { + ans += cnt[x]++; + } + return ans; +} +``` -```cpp +```rust +impl Solution { + pub fn num_identical_pairs(nums: Vec) -> i32 { + let mut cnt = [0; 101]; + let mut ans = 0; + for &num in nums.iter() { + ans += cnt[num as usize]; + cnt[num as usize] += 1; + } + ans + } +} +``` + +```php class Solution { -public: - int numIdenticalPairs(vector& nums) { + /** + * @param Integer[] $nums + * @return Integer + */ + function numIdenticalPairs($nums) { + $arr = array_values(array_unique($nums)); + for ($i = 0; $i < count($nums); $i++) { + $v[$nums[$i]] += 1; + } + $rs = 0; + for ($j = 0; $j < count($arr); $j++) { + $rs += ($v[$arr[$j]] * ($v[$arr[$j]] - 1)) / 2; + } + return $rs; + } +} +``` + +```c +int numIdenticalPairs(int* nums, int numsSize) { + int cnt[101] = {0}; + int ans = 0; + for (int i = 0; i < numsSize; i++) { + ans += cnt[nums[i]]++; + } + return ans; +} +``` + + + +### 方法二 + + + +```python +class Solution: + def numIdenticalPairs(self, nums: List[int]) -> int: + cnt = Counter(nums) + return sum(v * (v - 1) for v in cnt.values()) >> 1 +``` + +```java +class Solution { + public int numIdenticalPairs(int[] nums) { + int[] cnt = new int[101]; + for (int x : nums) { + ++cnt[x]; + } int ans = 0; - int cnt[101]{}; - for (int& x : nums) { - ans += cnt[x]++; + for (int v : cnt) { + ans += v * (v - 1) / 2; } return ans; } -}; +} ``` ```cpp @@ -142,19 +203,6 @@ public: }; ``` -### **Go** - -```go -func numIdenticalPairs(nums []int) (ans int) { - cnt := [101]int{} - for _, x := range nums { - ans += cnt[x] - cnt[x]++ - } - return -} -``` - ```go func numIdenticalPairs(nums []int) (ans int) { cnt := [101]int{} @@ -168,19 +216,6 @@ func numIdenticalPairs(nums []int) (ans int) { } ``` -### **TypeScript** - -```ts -function numIdenticalPairs(nums: number[]): number { - const cnt = new Array(101).fill(0); - let ans = 0; - for (const x of nums) { - ans += cnt[x]++; - } - return ans; -} -``` - ```ts function numIdenticalPairs(nums: number[]): number { const cnt = new Array(101).fill(0); @@ -195,22 +230,6 @@ function numIdenticalPairs(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn num_identical_pairs(nums: Vec) -> i32 { - let mut cnt = [0; 101]; - let mut ans = 0; - for &num in nums.iter() { - ans += cnt[num as usize]; - cnt[num as usize] += 1; - } - ans - } -} -``` - ```rust impl Solution { pub fn num_identical_pairs(nums: Vec) -> i32 { @@ -227,19 +246,6 @@ impl Solution { } ``` -### **C** - -```c -int numIdenticalPairs(int* nums, int numsSize) { - int cnt[101] = {0}; - int ans = 0; - for (int i = 0; i < numsSize; i++) { - ans += cnt[nums[i]]++; - } - return ans; -} -``` - ```c int numIdenticalPairs(int* nums, int numsSize) { int cnt[101] = {0}; @@ -254,32 +260,6 @@ int numIdenticalPairs(int* nums, int numsSize) { } ``` -### **PHP** - -```php -class Solution { - /** - * @param Integer[] $nums - * @return Integer - */ - function numIdenticalPairs($nums) { - $arr = array_values(array_unique($nums)); - for ($i = 0; $i < count($nums); $i++) { - $v[$nums[$i]] += 1; - } - $rs = 0; - for ($j = 0; $j < count($arr); $j++) { - $rs += ($v[$arr[$j]] * ($v[$arr[$j]] - 1)) / 2; - } - return $rs; - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1512.Number of Good Pairs/README_EN.md b/solution/1500-1599/1512.Number of Good Pairs/README_EN.md index 35bb9f0c8e26f..186254bb88eea 100644 --- a/solution/1500-1599/1512.Number of Good Pairs/README_EN.md +++ b/solution/1500-1599/1512.Number of Good Pairs/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,15 +57,6 @@ class Solution: return ans ``` -```python -class Solution: - def numIdenticalPairs(self, nums: List[int]) -> int: - cnt = Counter(nums) - return sum(v * (v - 1) for v in cnt.values()) >> 1 -``` - -### **Java** - ```java class Solution { public int numIdenticalPairs(int[] nums) { @@ -79,36 +70,114 @@ class Solution { } ``` -```java +```cpp class Solution { - public int numIdenticalPairs(int[] nums) { - int[] cnt = new int[101]; - for (int x : nums) { - ++cnt[x]; - } +public: + int numIdenticalPairs(vector& nums) { int ans = 0; - for (int v : cnt) { - ans += v * (v - 1) / 2; + int cnt[101]{}; + for (int& x : nums) { + ans += cnt[x]++; } return ans; } +}; +``` + +```go +func numIdenticalPairs(nums []int) (ans int) { + cnt := [101]int{} + for _, x := range nums { + ans += cnt[x] + cnt[x]++ + } + return } ``` -### **C++** +```ts +function numIdenticalPairs(nums: number[]): number { + const cnt = new Array(101).fill(0); + let ans = 0; + for (const x of nums) { + ans += cnt[x]++; + } + return ans; +} +``` -```cpp +```rust +impl Solution { + pub fn num_identical_pairs(nums: Vec) -> i32 { + let mut cnt = [0; 101]; + let mut ans = 0; + for &num in nums.iter() { + ans += cnt[num as usize]; + cnt[num as usize] += 1; + } + ans + } +} +``` + +```php class Solution { -public: - int numIdenticalPairs(vector& nums) { + /** + * @param Integer[] $nums + * @return Integer + */ + function numIdenticalPairs($nums) { + $arr = array_values(array_unique($nums)); + for ($i = 0; $i < count($nums); $i++) { + $v[$nums[$i]] += 1; + } + $rs = 0; + for ($j = 0; $j < count($arr); $j++) { + $rs += ($v[$arr[$j]] * ($v[$arr[$j]] - 1)) / 2; + } + return $rs; + } +} +``` + +```c +int numIdenticalPairs(int* nums, int numsSize) { + int cnt[101] = {0}; + int ans = 0; + for (int i = 0; i < numsSize; i++) { + ans += cnt[nums[i]]++; + } + return ans; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def numIdenticalPairs(self, nums: List[int]) -> int: + cnt = Counter(nums) + return sum(v * (v - 1) for v in cnt.values()) >> 1 +``` + +```java +class Solution { + public int numIdenticalPairs(int[] nums) { + int[] cnt = new int[101]; + for (int x : nums) { + ++cnt[x]; + } int ans = 0; - int cnt[101]{}; - for (int& x : nums) { - ans += cnt[x]++; + for (int v : cnt) { + ans += v * (v - 1) / 2; } return ans; } -}; +} ``` ```cpp @@ -128,19 +197,6 @@ public: }; ``` -### **Go** - -```go -func numIdenticalPairs(nums []int) (ans int) { - cnt := [101]int{} - for _, x := range nums { - ans += cnt[x] - cnt[x]++ - } - return -} -``` - ```go func numIdenticalPairs(nums []int) (ans int) { cnt := [101]int{} @@ -154,19 +210,6 @@ func numIdenticalPairs(nums []int) (ans int) { } ``` -### **TypeScript** - -```ts -function numIdenticalPairs(nums: number[]): number { - const cnt = new Array(101).fill(0); - let ans = 0; - for (const x of nums) { - ans += cnt[x]++; - } - return ans; -} -``` - ```ts function numIdenticalPairs(nums: number[]): number { const cnt = new Array(101).fill(0); @@ -181,22 +224,6 @@ function numIdenticalPairs(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn num_identical_pairs(nums: Vec) -> i32 { - let mut cnt = [0; 101]; - let mut ans = 0; - for &num in nums.iter() { - ans += cnt[num as usize]; - cnt[num as usize] += 1; - } - ans - } -} -``` - ```rust impl Solution { pub fn num_identical_pairs(nums: Vec) -> i32 { @@ -213,19 +240,6 @@ impl Solution { } ``` -### **C** - -```c -int numIdenticalPairs(int* nums, int numsSize) { - int cnt[101] = {0}; - int ans = 0; - for (int i = 0; i < numsSize; i++) { - ans += cnt[nums[i]]++; - } - return ans; -} -``` - ```c int numIdenticalPairs(int* nums, int numsSize) { int cnt[101] = {0}; @@ -240,32 +254,6 @@ int numIdenticalPairs(int* nums, int numsSize) { } ``` -### **PHP** - -```php -class Solution { - /** - * @param Integer[] $nums - * @return Integer - */ - function numIdenticalPairs($nums) { - $arr = array_values(array_unique($nums)); - for ($i = 0; $i < count($nums); $i++) { - $v[$nums[$i]] += 1; - } - $rs = 0; - for ($j = 0; $j < count($arr); $j++) { - $rs += ($v[$arr[$j]] * ($v[$arr[$j]] - 1)) / 2; - } - return $rs; - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1513.Number of Substrings With Only 1s/README.md b/solution/1500-1599/1513.Number of Substrings With Only 1s/README.md index 232e65df9c444..de3973817b133 100644 --- a/solution/1500-1599/1513.Number of Substrings With Only 1s/README.md +++ b/solution/1500-1599/1513.Number of Substrings With Only 1s/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:遍历计数** +### 方法一:遍历计数 我们遍历字符串 $s$,用变量 $cnt$ 记录当前连续的 1 的个数,用变量 $ans$ 记录答案。当遍历到字符 $s[i]$ 时,如果 $s[i] = 1$,则 $cnt$ 自增 1,否则 $cnt$ 置 0。此时 $ans$ 自增 $cnt$。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def numSub(self, s: str) -> int: @@ -88,10 +82,6 @@ class Solution: return ans % (10**9 + 7) ``` -### **Java** - - - ```java class Solution { public int numSub(String s) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func numSub(s string) (ans int) { const mod = 1e9 + 7 @@ -141,8 +127,6 @@ func numSub(s string) (ans int) { } ``` -### **TypeScript** - ```ts function numSub(s: string): number { const mod = 10 ** 9 + 7; @@ -156,10 +140,6 @@ function numSub(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1513.Number of Substrings With Only 1s/README_EN.md b/solution/1500-1599/1513.Number of Substrings With Only 1s/README_EN.md index a6dcd2110c55f..e96a2b43ce2a0 100644 --- a/solution/1500-1599/1513.Number of Substrings With Only 1s/README_EN.md +++ b/solution/1500-1599/1513.Number of Substrings With Only 1s/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return ans % (10**9 + 7) ``` -### **Java** - ```java class Solution { public int numSub(String s) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +89,6 @@ public: }; ``` -### **Go** - ```go func numSub(s string) (ans int) { const mod = 1e9 + 7 @@ -111,8 +105,6 @@ func numSub(s string) (ans int) { } ``` -### **TypeScript** - ```ts function numSub(s: string): number { const mod = 10 ** 9 + 7; @@ -126,10 +118,6 @@ function numSub(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1514.Path with Maximum Probability/README.md b/solution/1500-1599/1514.Path with Maximum Probability/README.md index 0cb493798d3d0..ddeb2e2fb5fd5 100644 --- a/solution/1500-1599/1514.Path with Maximum Probability/README.md +++ b/solution/1500-1599/1514.Path with Maximum Probability/README.md @@ -57,22 +57,12 @@ ## 解法 - - -**方法一:堆优化 Dijkstra 算法** +### 方法一:堆优化 Dijkstra 算法 时间复杂度 O(mlogn)。 -**方法二:SPFA 算法** - -时间复杂度,平均情况下 O(m),最坏情况下 O(nm),n 表示点数,m 表示边数。 - -### **Python3** - - - ```python class Solution: def maxProbability( @@ -102,41 +92,6 @@ class Solution: return d[end] ``` -```python -class Solution: - def maxProbability( - self, - n: int, - edges: List[List[int]], - succProb: List[float], - start: int, - end: int, - ) -> float: - g = defaultdict(list) - for (a, b), s in zip(edges, succProb): - g[a].append((b, s)) - g[b].append((a, s)) - d = [0] * n - vis = [False] * n - d[start] = 1 - q = deque([start]) - vis[start] = True - while q: - i = q.popleft() - vis[i] = False - for j, s in g[i]: - if d[j] < d[i] * s: - d[j] = d[i] * s - if not vis[j]: - q.append(j) - vis[j] = True - return d[end] -``` - -### **Java** - - - ```java class Solution { public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) { @@ -172,45 +127,6 @@ class Solution { } ``` -```java -class Solution { - public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) { - List>[] g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int i = 0; i < edges.length; ++i) { - int a = edges[i][0], b = edges[i][1]; - double s = succProb[i]; - g[a].add(new Pair<>(b, s)); - g[b].add(new Pair<>(a, s)); - } - double[] d = new double[n]; - d[start] = 1.0; - boolean[] vis = new boolean[n]; - Deque q = new ArrayDeque<>(); - q.offer(start); - vis[start] = true; - while (!q.isEmpty()) { - int i = q.poll(); - vis[i] = false; - for (Pair ne : g[i]) { - int j = ne.getKey(); - double s = ne.getValue(); - if (d[j] < d[i] * s) { - d[j] = d[i] * s; - if (!vis[j]) { - q.offer(j); - vis[j] = true; - } - } - } - } - return d[end]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -246,45 +162,6 @@ public: }; ``` -```cpp -class Solution { -public: - double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) { - vector>> g(n); - for (int i = 0; i < edges.size(); ++i) { - int a = edges[i][0], b = edges[i][1]; - double s = succProb[i]; - g[a].push_back({b, s}); - g[b].push_back({a, s}); - } - vector d(n); - vector vis(n); - d[start] = 1.0; - queue q{{start}}; - vis[start] = true; - while (!q.empty()) { - int i = q.front(); - q.pop(); - vis[i] = false; - for (auto& ne : g[i]) { - int j = ne.first; - double s = ne.second; - if (d[j] < d[i] * s) { - d[j] = d[i] * s; - if (!vis[j]) { - q.push(j); - vis[j] = true; - } - } - } - } - return d[end]; - } -}; -``` - -### **Go** - ```go func maxProbability(n int, edges [][]int, succProb []float64, start int, end int) float64 { g := make([][]pair, n) @@ -322,10 +199,119 @@ type pair struct { } ``` -### **...** + + +### 方法二:SPFA 算法 + +时间复杂度,平均情况下 O(m),最坏情况下 O(nm),n 表示点数,m 表示边数。 + + +```python +class Solution: + def maxProbability( + self, + n: int, + edges: List[List[int]], + succProb: List[float], + start: int, + end: int, + ) -> float: + g = defaultdict(list) + for (a, b), s in zip(edges, succProb): + g[a].append((b, s)) + g[b].append((a, s)) + d = [0] * n + vis = [False] * n + d[start] = 1 + q = deque([start]) + vis[start] = True + while q: + i = q.popleft() + vis[i] = False + for j, s in g[i]: + if d[j] < d[i] * s: + d[j] = d[i] * s + if not vis[j]: + q.append(j) + vis[j] = True + return d[end] ``` +```java +class Solution { + public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) { + List>[] g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int i = 0; i < edges.length; ++i) { + int a = edges[i][0], b = edges[i][1]; + double s = succProb[i]; + g[a].add(new Pair<>(b, s)); + g[b].add(new Pair<>(a, s)); + } + double[] d = new double[n]; + d[start] = 1.0; + boolean[] vis = new boolean[n]; + Deque q = new ArrayDeque<>(); + q.offer(start); + vis[start] = true; + while (!q.isEmpty()) { + int i = q.poll(); + vis[i] = false; + for (Pair ne : g[i]) { + int j = ne.getKey(); + double s = ne.getValue(); + if (d[j] < d[i] * s) { + d[j] = d[i] * s; + if (!vis[j]) { + q.offer(j); + vis[j] = true; + } + } + } + } + return d[end]; + } +} +``` + +```cpp +class Solution { +public: + double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) { + vector>> g(n); + for (int i = 0; i < edges.size(); ++i) { + int a = edges[i][0], b = edges[i][1]; + double s = succProb[i]; + g[a].push_back({b, s}); + g[b].push_back({a, s}); + } + vector d(n); + vector vis(n); + d[start] = 1.0; + queue q{{start}}; + vis[start] = true; + while (!q.empty()) { + int i = q.front(); + q.pop(); + vis[i] = false; + for (auto& ne : g[i]) { + int j = ne.first; + double s = ne.second; + if (d[j] < d[i] * s) { + d[j] = d[i] * s; + if (!vis[j]) { + q.push(j); + vis[j] = true; + } + } + } + } + return d[end]; + } +}; ``` + + diff --git a/solution/1500-1599/1514.Path with Maximum Probability/README_EN.md b/solution/1500-1599/1514.Path with Maximum Probability/README_EN.md index 2ba60ab1d8d07..88b65e9ca6eb1 100644 --- a/solution/1500-1599/1514.Path with Maximum Probability/README_EN.md +++ b/solution/1500-1599/1514.Path with Maximum Probability/README_EN.md @@ -56,9 +56,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -89,39 +89,6 @@ class Solution: return d[end] ``` -```python -class Solution: - def maxProbability( - self, - n: int, - edges: List[List[int]], - succProb: List[float], - start: int, - end: int, - ) -> float: - g = defaultdict(list) - for (a, b), s in zip(edges, succProb): - g[a].append((b, s)) - g[b].append((a, s)) - d = [0] * n - vis = [False] * n - d[start] = 1 - q = deque([start]) - vis[start] = True - while q: - i = q.popleft() - vis[i] = False - for j, s in g[i]: - if d[j] < d[i] * s: - d[j] = d[i] * s - if not vis[j]: - q.append(j) - vis[j] = True - return d[end] -``` - -### **Java** - ```java class Solution { public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) { @@ -157,45 +124,6 @@ class Solution { } ``` -```java -class Solution { - public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) { - List>[] g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int i = 0; i < edges.length; ++i) { - int a = edges[i][0], b = edges[i][1]; - double s = succProb[i]; - g[a].add(new Pair<>(b, s)); - g[b].add(new Pair<>(a, s)); - } - double[] d = new double[n]; - d[start] = 1.0; - boolean[] vis = new boolean[n]; - Deque q = new ArrayDeque<>(); - q.offer(start); - vis[start] = true; - while (!q.isEmpty()) { - int i = q.poll(); - vis[i] = false; - for (Pair ne : g[i]) { - int j = ne.getKey(); - double s = ne.getValue(); - if (d[j] < d[i] * s) { - d[j] = d[i] * s; - if (!vis[j]) { - q.offer(j); - vis[j] = true; - } - } - } - } - return d[end]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -231,45 +159,6 @@ public: }; ``` -```cpp -class Solution { -public: - double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) { - vector>> g(n); - for (int i = 0; i < edges.size(); ++i) { - int a = edges[i][0], b = edges[i][1]; - double s = succProb[i]; - g[a].push_back({b, s}); - g[b].push_back({a, s}); - } - vector d(n); - vector vis(n); - d[start] = 1.0; - queue q{{start}}; - vis[start] = true; - while (!q.empty()) { - int i = q.front(); - q.pop(); - vis[i] = false; - for (auto& ne : g[i]) { - int j = ne.first; - double s = ne.second; - if (d[j] < d[i] * s) { - d[j] = d[i] * s; - if (!vis[j]) { - q.push(j); - vis[j] = true; - } - } - } - } - return d[end]; - } -}; -``` - -### **Go** - ```go func maxProbability(n int, edges [][]int, succProb []float64, start int, end int) float64 { g := make([][]pair, n) @@ -307,10 +196,117 @@ type pair struct { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def maxProbability( + self, + n: int, + edges: List[List[int]], + succProb: List[float], + start: int, + end: int, + ) -> float: + g = defaultdict(list) + for (a, b), s in zip(edges, succProb): + g[a].append((b, s)) + g[b].append((a, s)) + d = [0] * n + vis = [False] * n + d[start] = 1 + q = deque([start]) + vis[start] = True + while q: + i = q.popleft() + vis[i] = False + for j, s in g[i]: + if d[j] < d[i] * s: + d[j] = d[i] * s + if not vis[j]: + q.append(j) + vis[j] = True + return d[end] +``` +```java +class Solution { + public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) { + List>[] g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int i = 0; i < edges.length; ++i) { + int a = edges[i][0], b = edges[i][1]; + double s = succProb[i]; + g[a].add(new Pair<>(b, s)); + g[b].add(new Pair<>(a, s)); + } + double[] d = new double[n]; + d[start] = 1.0; + boolean[] vis = new boolean[n]; + Deque q = new ArrayDeque<>(); + q.offer(start); + vis[start] = true; + while (!q.isEmpty()) { + int i = q.poll(); + vis[i] = false; + for (Pair ne : g[i]) { + int j = ne.getKey(); + double s = ne.getValue(); + if (d[j] < d[i] * s) { + d[j] = d[i] * s; + if (!vis[j]) { + q.offer(j); + vis[j] = true; + } + } + } + } + return d[end]; + } +} ``` +```cpp +class Solution { +public: + double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) { + vector>> g(n); + for (int i = 0; i < edges.size(); ++i) { + int a = edges[i][0], b = edges[i][1]; + double s = succProb[i]; + g[a].push_back({b, s}); + g[b].push_back({a, s}); + } + vector d(n); + vector vis(n); + d[start] = 1.0; + queue q{{start}}; + vis[start] = true; + while (!q.empty()) { + int i = q.front(); + q.pop(); + vis[i] = false; + for (auto& ne : g[i]) { + int j = ne.first; + double s = ne.second; + if (d[j] < d[i] * s) { + d[j] = d[i] * s; + if (!vis[j]) { + q.push(j); + vis[j] = true; + } + } + } + } + return d[end]; + } +}; ``` + + diff --git a/solution/1500-1599/1515.Best Position for a Service Centre/README.md b/solution/1500-1599/1515.Best Position for a Service Centre/README.md index 610aae578b1b4..020e57e36aa45 100644 --- a/solution/1500-1599/1515.Best Position for a Service Centre/README.md +++ b/solution/1500-1599/1515.Best Position for a Service Centre/README.md @@ -50,18 +50,12 @@ ## 解法 - - -**方法一:梯度下降法** +### 方法一:梯度下降法 我们可以先设定一个初始的服务中心位置为所有客户坐标的几何中心 $(x, y)$。接下来,使用梯度下降法不断迭代,设定一个学习率 $\alpha=0.5$,衰减率 $decay=0.999$。每次一次迭代,计算当前位置到所有客户的距离之和,然后计算当前位置的梯度,最后更新当前位置。当梯度的绝对值都小于 $10^{-6}$ 时,停止迭代,返回当前位置到所有客户的距离之和。 -### **Python3** - - - ```python class Solution: def getMinDistSum(self, positions: List[List[int]]) -> float: @@ -93,10 +87,6 @@ class Solution: return dist ``` -### **Java** - - - ```java class Solution { public double getMinDistSum(int[][] positions) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -172,8 +160,6 @@ public: }; ``` -### **Go** - ```go func getMinDistSum(positions [][]int) float64 { n := len(positions) @@ -210,8 +196,6 @@ func getMinDistSum(positions [][]int) float64 { } ``` -### **TypeScript** - ```ts function getMinDistSum(positions: number[][]): number { const n = positions.length; @@ -248,10 +232,6 @@ function getMinDistSum(positions: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1515.Best Position for a Service Centre/README_EN.md b/solution/1500-1599/1515.Best Position for a Service Centre/README_EN.md index 3b7a1e75d6a08..5c604e253487e 100644 --- a/solution/1500-1599/1515.Best Position for a Service Centre/README_EN.md +++ b/solution/1500-1599/1515.Best Position for a Service Centre/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return dist ``` -### **Java** - ```java class Solution { public double getMinDistSum(int[][] positions) { @@ -113,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +148,6 @@ public: }; ``` -### **Go** - ```go func getMinDistSum(positions [][]int) float64 { n := len(positions) @@ -190,8 +184,6 @@ func getMinDistSum(positions [][]int) float64 { } ``` -### **TypeScript** - ```ts function getMinDistSum(positions: number[][]): number { const n = positions.length; @@ -228,10 +220,6 @@ function getMinDistSum(positions: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1516.Move Sub-Tree of N-Ary Tree/README.md b/solution/1500-1599/1516.Move Sub-Tree of N-Ary Tree/README.md index 598a22c1dc799..b5e3661e767d4 100644 --- a/solution/1500-1599/1516.Move Sub-Tree of N-Ary Tree/README.md +++ b/solution/1500-1599/1516.Move Sub-Tree of N-Ary Tree/README.md @@ -80,30 +80,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1500-1599/1516.Move Sub-Tree of N-Ary Tree/README_EN.md b/solution/1500-1599/1516.Move Sub-Tree of N-Ary Tree/README_EN.md index 1ac1d4664fbc3..bf754bde41eae 100644 --- a/solution/1500-1599/1516.Move Sub-Tree of N-Ary Tree/README_EN.md +++ b/solution/1500-1599/1516.Move Sub-Tree of N-Ary Tree/README_EN.md @@ -68,24 +68,4 @@ Notice that node 4 is the last child of node 1. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1500-1599/1517.Find Users With Valid E-Mails/README.md b/solution/1500-1599/1517.Find Users With Valid E-Mails/README.md index 83031367c637e..89cb35023eb45 100644 --- a/solution/1500-1599/1517.Find Users With Valid E-Mails/README.md +++ b/solution/1500-1599/1517.Find Users With Valid E-Mails/README.md @@ -70,14 +70,10 @@ Users 表: ## 解法 - - -**方法一:REGEXP 正则匹配** +### 方法一:REGEXP 正则匹配 -### **SQL** - ```sql # Write your MySQL query statement below SELECT * @@ -86,3 +82,5 @@ WHERE mail REGEXP '^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode[.]com$'; ``` + + diff --git a/solution/1500-1599/1517.Find Users With Valid E-Mails/README_EN.md b/solution/1500-1599/1517.Find Users With Valid E-Mails/README_EN.md index b159c811e429f..b7258e86d7c1f 100644 --- a/solution/1500-1599/1517.Find Users With Valid E-Mails/README_EN.md +++ b/solution/1500-1599/1517.Find Users With Valid E-Mails/README_EN.md @@ -67,9 +67,9 @@ The mail of user 7 starts with a period. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -79,3 +79,5 @@ WHERE mail REGEXP '^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode[.]com$'; ``` + + diff --git a/solution/1500-1599/1518.Water Bottles/README.md b/solution/1500-1599/1518.Water Bottles/README.md index 70ffb7413f044..026feeb41991e 100644 --- a/solution/1500-1599/1518.Water Bottles/README.md +++ b/solution/1500-1599/1518.Water Bottles/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以直接模拟整个过程。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def numWaterBottles(self, numBottles: int, numExchange: int) -> int: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numWaterBottles(int numBottles, int numExchange) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +98,6 @@ public: }; ``` -### **Go** - ```go func numWaterBottles(numBottles int, numExchange int) int { ans := numBottles @@ -122,8 +108,6 @@ func numWaterBottles(numBottles int, numExchange int) int { } ``` -### **TypeScript** - ```ts function numWaterBottles(numBottles: number, numExchange: number): number { let ans = numBottles; @@ -134,7 +118,20 @@ function numWaterBottles(numBottles: number, numExchange: number): number { } ``` -### **PHP** +```js +/** + * @param {number} numBottles + * @param {number} numExchange + * @return {number} + */ +var numWaterBottles = function (numBottles, numExchange) { + let ans = numBottles; + for (; numBottles >= numExchange; ++ans) { + numBottles -= numExchange - 1; + } + return ans; +}; +``` ```php class Solution { @@ -154,27 +151,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number} numBottles - * @param {number} numExchange - * @return {number} - */ -var numWaterBottles = function (numBottles, numExchange) { - let ans = numBottles; - for (; numBottles >= numExchange; ++ans) { - numBottles -= numExchange - 1; - } - return ans; -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1518.Water Bottles/README_EN.md b/solution/1500-1599/1518.Water Bottles/README_EN.md index 8712e5e225ee5..cad2d506ee006 100644 --- a/solution/1500-1599/1518.Water Bottles/README_EN.md +++ b/solution/1500-1599/1518.Water Bottles/README_EN.md @@ -39,9 +39,9 @@ Number of water bottles you can drink: 15 + 3 + 1 = 19. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numWaterBottles(int numBottles, int numExchange) { @@ -67,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -82,8 +78,6 @@ public: }; ``` -### **Go** - ```go func numWaterBottles(numBottles int, numExchange int) int { ans := numBottles @@ -94,8 +88,6 @@ func numWaterBottles(numBottles int, numExchange int) int { } ``` -### **TypeScript** - ```ts function numWaterBottles(numBottles: number, numExchange: number): number { let ans = numBottles; @@ -106,7 +98,20 @@ function numWaterBottles(numBottles: number, numExchange: number): number { } ``` -### **PHP** +```js +/** + * @param {number} numBottles + * @param {number} numExchange + * @return {number} + */ +var numWaterBottles = function (numBottles, numExchange) { + let ans = numBottles; + for (; numBottles >= numExchange; ++ans) { + numBottles -= numExchange - 1; + } + return ans; +}; +``` ```php class Solution { @@ -126,27 +131,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number} numBottles - * @param {number} numExchange - * @return {number} - */ -var numWaterBottles = function (numBottles, numExchange) { - let ans = numBottles; - for (; numBottles >= numExchange; ++ans) { - numBottles -= numExchange - 1; - } - return ans; -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/README.md b/solution/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/README.md index 6291b35435e48..34068ea448e0a 100644 --- a/solution/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/README.md +++ b/solution/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们先将边数组转换为邻接表 $g$。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]: @@ -104,10 +98,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +163,6 @@ public: }; ``` -### **Go** - ```go func countSubTrees(n int, edges [][]int, labels string) []int { g := make([][]int, n) @@ -204,8 +190,6 @@ func countSubTrees(n int, edges [][]int, labels string) []int { } ``` -### **TypeScript** - ```ts function countSubTrees(n: number, edges: number[][], labels: string): number[] { const dfs = (i: number, fa: number) => { @@ -231,10 +215,6 @@ function countSubTrees(n: number, edges: number[][], labels: string): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/README_EN.md b/solution/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/README_EN.md index 6efdf2205ab73..cd215878e623c 100644 --- a/solution/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/README_EN.md +++ b/solution/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/README_EN.md @@ -55,9 +55,9 @@ The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -118,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +145,6 @@ public: }; ``` -### **Go** - ```go func countSubTrees(n int, edges [][]int, labels string) []int { g := make([][]int, n) @@ -178,8 +172,6 @@ func countSubTrees(n int, edges [][]int, labels string) []int { } ``` -### **TypeScript** - ```ts function countSubTrees(n: number, edges: number[][], labels: string): number[] { const dfs = (i: number, fa: number) => { @@ -205,10 +197,6 @@ function countSubTrees(n: number, edges: number[][], labels: string): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1520.Maximum Number of Non-Overlapping Substrings/README.md b/solution/1500-1599/1520.Maximum Number of Non-Overlapping Substrings/README.md index 614a055ceeeac..3364429362caa 100644 --- a/solution/1500-1599/1520.Maximum Number of Non-Overlapping Substrings/README.md +++ b/solution/1500-1599/1520.Maximum Number of Non-Overlapping Substrings/README.md @@ -55,30 +55,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1500-1599/1520.Maximum Number of Non-Overlapping Substrings/README_EN.md b/solution/1500-1599/1520.Maximum Number of Non-Overlapping Substrings/README_EN.md index 4bde6107ca559..7018da61d669e 100644 --- a/solution/1500-1599/1520.Maximum Number of Non-Overlapping Substrings/README_EN.md +++ b/solution/1500-1599/1520.Maximum Number of Non-Overlapping Substrings/README_EN.md @@ -51,24 +51,4 @@ If we choose the first string, we cannot choose anything else and we'd get o ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/README.md b/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/README.md index 9d04cf6200278..1b07dab3d435c 100644 --- a/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/README.md +++ b/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:哈希表 + 枚举** +### 方法一:哈希表 + 枚举 根据题目描述,我们知道,函数 $func(arr, l, r)$ 实际上就是数组 $arr$ 下标 $l$ 到 $r$ 的元素的按位与运算的结果,即 $arr[l] \& arr[l + 1] \& \cdots \& arr[r]$。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def closestToTarget(self, arr: List[int], target: int) -> int: @@ -75,10 +69,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int closestToTarget(int[] arr, int target) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func closestToTarget(arr []int, target int) int { ans := abs(arr[0] - target) @@ -153,8 +139,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function closestToTarget(arr: number[], target: number): number { let ans = Math.abs(arr[0] - target); @@ -175,10 +159,6 @@ function closestToTarget(arr: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/README_EN.md b/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/README_EN.md index 00c356ad17aba..0b904e7370c26 100644 --- a/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/README_EN.md +++ b/solution/1500-1599/1521.Find a Value of a Mysterious Function Closest to Target/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Hash Table + Enumeration** +### Solution 1: Hash Table + Enumeration According to the problem description, we know that the function $func(arr, l, r)$ is actually the bitwise AND result of the elements in the array $arr$ from index $l$ to $r$, i.e., $arr[l] \& arr[l + 1] \& \cdots \& arr[r]$. @@ -57,8 +57,6 @@ The time complexity is $O(n \times \log M)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def closestToTarget(self, arr: List[int], target: int) -> int: @@ -70,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int closestToTarget(int[] arr, int target) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +113,6 @@ public: }; ``` -### **Go** - ```go func closestToTarget(arr []int, target int) int { ans := abs(arr[0] - target) @@ -146,8 +138,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function closestToTarget(arr: number[], target: number): number { let ans = Math.abs(arr[0] - target); @@ -168,10 +158,6 @@ function closestToTarget(arr: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1522.Diameter of N-Ary Tree/README.md b/solution/1500-1599/1522.Diameter of N-Ary Tree/README.md index 05088054ef6c8..dfe56f5fa49cb 100644 --- a/solution/1500-1599/1522.Diameter of N-Ary Tree/README.md +++ b/solution/1500-1599/1522.Diameter of N-Ary Tree/README.md @@ -52,38 +52,10 @@ ## 解法 - - -**方法一**:后序遍历求每个结点的深度,此过程中获取每个结点子树的最长两个伸展(深度),迭代获取最长路径。 - -相似题目:[543. 二叉树的直径](/solution/0500-0599/0543.Diameter%20of%20Binary%20Tree/README.md) - -**方法二**:两次 DFS。 - -首先对任意一个结点做 DFS 求出最远的结点,然后以这个结点为根结点再做 DFS 到达另一个最远结点。第一次 DFS 到达的结点可以证明一定是这个图的直径的一端,第二次 DFS 就会达到另一端。下面来证明这个定理。 - -定理:在一个连通无向无环图中,以任意结点出发所能到达的最远结点,一定是该图直径的端点之一。 - -证明:假设这条直径是 δ(s, t)。分两种情况: - -1. 当出发结点 y 在 δ(s, t) 时,假设到达的最远结点 z 不是 s, t 中的任一个。这时将 δ(y, z) 与不与之重合的 δ(y, s) 拼接(也可以假设不与之重合的是直径的另一个方向),可以得到一条更长的直径,与前提矛盾。 -1. 当出发结点 y 不在 δ(s, t) 上时,分两种情况: - - - 当 y 到达的最远结点 z 横穿 δ(s, t) 时,记与之相交的结点为 x。此时有 δ(y, z) = δ(y, x) + δ(x, z)。而此时 δ(y, z) > δ(y, t),故可得 δ(x, z) > δ(x, t)。由 1 的结论可知该假设不成立。 - - 当 y 到达的最远结点 z 与 δ(s, t) 不相交时,定义从 y 开始到 t 结束的简单路径上,第一个同时也存在于简单路径 δ(s, t) 上的结点为 x,最后一个存在于简单路径 δ(y, z) 上的结点为 x’。如下图。那么根据假设,有 δ(y, z) ≥ δ(y, t) => δ(x', z) ≥ δ(x', x) + δ(x, t)。既然这样,那么 δ(x, z) ≥ δ(x, t),和 δ(s, t) 对应着直径这一前提不符,故 y 的最远结点 z 不可能在 s 到 t 这个直径对应的路外面。 - - - -因此定理成立。 - -相似题目:[1245. 树的直径](/solution/1200-1299/1245.Tree%20Diameter/README.md) +### 方法一 -### **Python3** - - - ```python """ # Definition for a Node. @@ -120,58 +92,6 @@ class Solution: return ans ``` -```python -""" -# Definition for a Node. -class Node: - def __init__(self, val=None, children=None): - self.val = val - self.children = children if children is not None else [] -""" - - -class Solution: - def diameter(self, root: 'Node') -> int: - """ - :type root: 'Node' - :rtype: int - """ - - def build(root): - nonlocal d - if root is None: - return - for child in root.children: - d[root].add(child) - d[child].add(root) - build(child) - - def dfs(u, t): - nonlocal ans, vis, d, next - if u in vis: - return - vis.add(u) - for v in d[u]: - dfs(v, t + 1) - if ans < t: - ans = t - next = u - - d = defaultdict(set) - vis = set() - build(root) - ans = 0 - next = None - dfs(root, 0) - vis.clear() - dfs(next, 0) - return ans -``` - -### **Java** - - - ```java /* // Definition for a Node. @@ -225,6 +145,141 @@ class Solution { } ``` +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { +public: + int ans; + + int diameter(Node* root) { + ans = 0; + dfs(root); + return ans; + } + + int dfs(Node* root) { + if (!root) return 0; + int m1 = 0, m2 = 0; + for (Node* child : root->children) { + int t = dfs(child); + if (t > m1) { + m2 = m1; + m1 = t; + } else if (t > m2) + m2 = t; + } + ans = max(ans, m1 + m2); + return 1 + m1; + } +}; +``` + +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Children []*Node + * } + */ + +func diameter(root *Node) int { + ans := 0 + var dfs func(root *Node) int + dfs = func(root *Node) int { + if root == nil { + return 0 + } + m1, m2 := 0, 0 + for _, child := range root.Children { + t := dfs(child) + if t > m1 { + m2, m1 = m1, t + } else if t > m2 { + m2 = t + } + } + ans = max(ans, m1+m2) + return 1 + m1 + } + dfs(root) + return ans +} +``` + + + +### 方法二 + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children if children is not None else [] +""" + + +class Solution: + def diameter(self, root: 'Node') -> int: + """ + :type root: 'Node' + :rtype: int + """ + + def build(root): + nonlocal d + if root is None: + return + for child in root.children: + d[root].add(child) + d[child].add(root) + build(child) + + def dfs(u, t): + nonlocal ans, vis, d, next + if u in vis: + return + vis.add(u) + for v in d[u]: + dfs(v, t + 1) + if ans < t: + ans = t + next = u + + d = defaultdict(set) + vis = set() + build(root) + ans = 0 + next = None + dfs(root, 0) + vis.clear() + dfs(next, 0) + return ans +``` + ```java /* // Definition for a Node. @@ -296,56 +351,6 @@ class Solution { } ``` -### **C++** - -```cpp -/* -// Definition for a Node. -class Node { -public: - int val; - vector children; - - Node() {} - - Node(int _val) { - val = _val; - } - - Node(int _val, vector _children) { - val = _val; - children = _children; - } -}; -*/ - -class Solution { -public: - int ans; - - int diameter(Node* root) { - ans = 0; - dfs(root); - return ans; - } - - int dfs(Node* root) { - if (!root) return 0; - int m1 = 0, m2 = 0; - for (Node* child : root->children) { - int t = dfs(child); - if (t > m1) { - m2 = m1; - m1 = t; - } else if (t > m2) - m2 = t; - } - ans = max(ans, m1 + m2); - return 1 + m1; - } -}; -``` - ```cpp /* // Definition for a Node. @@ -407,41 +412,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a Node. - * type Node struct { - * Val int - * Children []*Node - * } - */ - -func diameter(root *Node) int { - ans := 0 - var dfs func(root *Node) int - dfs = func(root *Node) int { - if root == nil { - return 0 - } - m1, m2 := 0, 0 - for _, child := range root.Children { - t := dfs(child) - if t > m1 { - m2, m1 = m1, t - } else if t > m2 { - m2 = t - } - } - ans = max(ans, m1+m2) - return 1 + m1 - } - dfs(root) - return ans -} -``` - ```go /** * Definition for a Node. @@ -491,10 +461,6 @@ func diameter(root *Node) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1522.Diameter of N-Ary Tree/README_EN.md b/solution/1500-1599/1522.Diameter of N-Ary Tree/README_EN.md index bb3a3891de2bb..a525a281b1345 100644 --- a/solution/1500-1599/1522.Diameter of N-Ary Tree/README_EN.md +++ b/solution/1500-1599/1522.Diameter of N-Ary Tree/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -88,56 +88,6 @@ class Solution: return ans ``` -```python -""" -# Definition for a Node. -class Node: - def __init__(self, val=None, children=None): - self.val = val - self.children = children if children is not None else [] -""" - - -class Solution: - def diameter(self, root: 'Node') -> int: - """ - :type root: 'Node' - :rtype: int - """ - - def build(root): - nonlocal d - if root is None: - return - for child in root.children: - d[root].add(child) - d[child].add(root) - build(child) - - def dfs(u, t): - nonlocal ans, vis, d, next - if u in vis: - return - vis.add(u) - for v in d[u]: - dfs(v, t + 1) - if ans < t: - ans = t - next = u - - d = defaultdict(set) - vis = set() - build(root) - ans = 0 - next = None - dfs(root, 0) - vis.clear() - dfs(next, 0) - return ans -``` - -### **Java** - ```java /* // Definition for a Node. @@ -191,6 +141,141 @@ class Solution { } ``` +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { +public: + int ans; + + int diameter(Node* root) { + ans = 0; + dfs(root); + return ans; + } + + int dfs(Node* root) { + if (!root) return 0; + int m1 = 0, m2 = 0; + for (Node* child : root->children) { + int t = dfs(child); + if (t > m1) { + m2 = m1; + m1 = t; + } else if (t > m2) + m2 = t; + } + ans = max(ans, m1 + m2); + return 1 + m1; + } +}; +``` + +```go +/** + * Definition for a Node. + * type Node struct { + * Val int + * Children []*Node + * } + */ + +func diameter(root *Node) int { + ans := 0 + var dfs func(root *Node) int + dfs = func(root *Node) int { + if root == nil { + return 0 + } + m1, m2 := 0, 0 + for _, child := range root.Children { + t := dfs(child) + if t > m1 { + m2, m1 = m1, t + } else if t > m2 { + m2 = t + } + } + ans = max(ans, m1+m2) + return 1 + m1 + } + dfs(root) + return ans +} +``` + + + +### Solution 2 + + + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children if children is not None else [] +""" + + +class Solution: + def diameter(self, root: 'Node') -> int: + """ + :type root: 'Node' + :rtype: int + """ + + def build(root): + nonlocal d + if root is None: + return + for child in root.children: + d[root].add(child) + d[child].add(root) + build(child) + + def dfs(u, t): + nonlocal ans, vis, d, next + if u in vis: + return + vis.add(u) + for v in d[u]: + dfs(v, t + 1) + if ans < t: + ans = t + next = u + + d = defaultdict(set) + vis = set() + build(root) + ans = 0 + next = None + dfs(root, 0) + vis.clear() + dfs(next, 0) + return ans +``` + ```java /* // Definition for a Node. @@ -262,56 +347,6 @@ class Solution { } ``` -### **C++** - -```cpp -/* -// Definition for a Node. -class Node { -public: - int val; - vector children; - - Node() {} - - Node(int _val) { - val = _val; - } - - Node(int _val, vector _children) { - val = _val; - children = _children; - } -}; -*/ - -class Solution { -public: - int ans; - - int diameter(Node* root) { - ans = 0; - dfs(root); - return ans; - } - - int dfs(Node* root) { - if (!root) return 0; - int m1 = 0, m2 = 0; - for (Node* child : root->children) { - int t = dfs(child); - if (t > m1) { - m2 = m1; - m1 = t; - } else if (t > m2) - m2 = t; - } - ans = max(ans, m1 + m2); - return 1 + m1; - } -}; -``` - ```cpp /* // Definition for a Node. @@ -373,41 +408,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a Node. - * type Node struct { - * Val int - * Children []*Node - * } - */ - -func diameter(root *Node) int { - ans := 0 - var dfs func(root *Node) int - dfs = func(root *Node) int { - if root == nil { - return 0 - } - m1, m2 := 0, 0 - for _, child := range root.Children { - t := dfs(child) - if t > m1 { - m2, m1 = m1, t - } else if t > m2 { - m2 = t - } - } - ans = max(ans, m1+m2) - return 1 + m1 - } - dfs(root) - return ans -} -``` - ```go /** * Definition for a Node. @@ -457,10 +457,6 @@ func diameter(root *Node) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/README.md b/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/README.md index 991e1e375b74a..89c7cc8d88c71 100644 --- a/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/README.md +++ b/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/README.md @@ -32,28 +32,18 @@ ## 解法 - - -**方法一:前缀和思想** +### 方法一:前缀和思想 `[0, x]` 之间的奇数个数为 `(x + 1) >> 1`,那么 `[low, high]` 之间的奇数个数为 `((high + 1) >> 1) - (low >> 1)`。 -### **Python3** - - - ```python class Solution: def countOdds(self, low: int, high: int) -> int: return ((high + 1) >> 1) - (low >> 1) ``` -### **Java** - - - ```java class Solution { public int countOdds(int low, int high) { @@ -62,8 +52,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -73,24 +61,18 @@ public: }; ``` -### **Go** - ```go func countOdds(low int, high int) int { return ((high + 1) >> 1) - (low >> 1) } ``` -### **TypeScript** - ```ts function countOdds(low: number, high: number): number { return ((high + 1) >> 1) - (low >> 1); } ``` -### **Rust** - ```rust impl Solution { pub fn count_odds(low: i32, high: i32) -> i32 { @@ -99,16 +81,6 @@ impl Solution { } ``` -### **C** - -```c -int countOdds(int low, int high) { - return ((high + 1) >> 1) - (low >> 1); -} -``` - -### **PHP** - ```php class Solution { /** @@ -122,10 +94,12 @@ class Solution { } ``` -### **...** - -``` - +```c +int countOdds(int low, int high) { + return ((high + 1) >> 1) - (low >> 1); +} ``` + + diff --git a/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/README_EN.md b/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/README_EN.md index 2af4d51d5f015..4a0359b9069e7 100644 --- a/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/README_EN.md +++ b/solution/1500-1599/1523.Count Odd Numbers in an Interval Range/README_EN.md @@ -30,9 +30,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -40,8 +40,6 @@ class Solution: return ((high + 1) >> 1) - (low >> 1) ``` -### **Java** - ```java class Solution { public int countOdds(int low, int high) { @@ -50,8 +48,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -61,24 +57,18 @@ public: }; ``` -### **Go** - ```go func countOdds(low int, high int) int { return ((high + 1) >> 1) - (low >> 1) } ``` -### **TypeScript** - ```ts function countOdds(low: number, high: number): number { return ((high + 1) >> 1) - (low >> 1); } ``` -### **Rust** - ```rust impl Solution { pub fn count_odds(low: i32, high: i32) -> i32 { @@ -87,16 +77,6 @@ impl Solution { } ``` -### **C** - -```c -int countOdds(int low, int high) { - return ((high + 1) >> 1) - (low >> 1); -} -``` - -### **PHP** - ```php class Solution { /** @@ -110,10 +90,12 @@ class Solution { } ``` -### **...** - -``` - +```c +int countOdds(int low, int high) { + return ((high + 1) >> 1) - (low >> 1); +} ``` + + diff --git a/solution/1500-1599/1524.Number of Sub-arrays With Odd Sum/README.md b/solution/1500-1599/1524.Number of Sub-arrays With Odd Sum/README.md index 7f96bd76c1ce4..5dff87c8b1ee0 100644 --- a/solution/1500-1599/1524.Number of Sub-arrays With Odd Sum/README.md +++ b/solution/1500-1599/1524.Number of Sub-arrays With Odd Sum/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:前缀和 + 计数器** +### 方法一:前缀和 + 计数器 我们定义一个长度为 $2$ 的数组 $cnt$ 作为计数器,其中 $cnt[0]$ 和 $cnt[1]$ 分别表示前缀和为偶数和奇数的子数组的个数。初始时 $cnt[0] = 1$,而 $cnt[1] = 0$。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def numOfSubarrays(self, arr: List[int]) -> int: @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numOfSubarrays(int[] arr) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func numOfSubarrays(arr []int) (ans int) { const mod int = 1e9 + 7 @@ -147,8 +133,6 @@ func numOfSubarrays(arr []int) (ans int) { } ``` -### **TypeScript** - ```ts function numOfSubarrays(arr: number[]): number { let ans = 0; @@ -164,10 +148,6 @@ function numOfSubarrays(arr: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1524.Number of Sub-arrays With Odd Sum/README_EN.md b/solution/1500-1599/1524.Number of Sub-arrays With Odd Sum/README_EN.md index 7db3ff0014065..ab4b9ae9625d9 100644 --- a/solution/1500-1599/1524.Number of Sub-arrays With Odd Sum/README_EN.md +++ b/solution/1500-1599/1524.Number of Sub-arrays With Odd Sum/README_EN.md @@ -46,9 +46,9 @@ All sub-arrays have even sum and the answer is 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numOfSubarrays(int[] arr) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +96,6 @@ public: }; ``` -### **Go** - ```go func numOfSubarrays(arr []int) (ans int) { const mod int = 1e9 + 7 @@ -116,8 +110,6 @@ func numOfSubarrays(arr []int) (ans int) { } ``` -### **TypeScript** - ```ts function numOfSubarrays(arr: number[]): number { let ans = 0; @@ -133,10 +125,6 @@ function numOfSubarrays(arr: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1525.Number of Good Ways to Split a String/README.md b/solution/1500-1599/1525.Number of Good Ways to Split a String/README.md index 883b04144363a..f9aeb1afeec16 100644 --- a/solution/1500-1599/1525.Number of Good Ways to Split a String/README.md +++ b/solution/1500-1599/1525.Number of Good Ways to Split a String/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们维护两个哈希表,分别记录左侧出现的字符、右侧的字符以及出现的次数。初始时,左侧的哈希表为空,右侧的哈希表为字符串 $s$ 中所有字符出现的次数。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def numSplits(self, s: str) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numSplits(String s) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func numSplits(s string) (ans int) { cnt := map[rune]int{} @@ -161,10 +147,6 @@ func numSplits(s string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1525.Number of Good Ways to Split a String/README_EN.md b/solution/1500-1599/1525.Number of Good Ways to Split a String/README_EN.md index 3cd1ed1d95886..7e478584538b9 100644 --- a/solution/1500-1599/1525.Number of Good Ways to Split a String/README_EN.md +++ b/solution/1500-1599/1525.Number of Good Ways to Split a String/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numSplits(String s) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +106,6 @@ public: }; ``` -### **Go** - ```go func numSplits(s string) (ans int) { cnt := map[rune]int{} @@ -133,10 +127,6 @@ func numSplits(s string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1526.Minimum Number of Increments on Subarrays to Form a Target Array/README.md b/solution/1500-1599/1526.Minimum Number of Increments on Subarrays to Form a Target Array/README.md index 330d4a3d4b3f5..46aa242f0da24 100644 --- a/solution/1500-1599/1526.Minimum Number of Increments on Subarrays to Form a Target Array/README.md +++ b/solution/1500-1599/1526.Minimum Number of Increments on Subarrays to Form a Target Array/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示得到 $target[0,..i]$ 的最少操作次数,初始时 $f[0] = target[0]$。 @@ -77,20 +75,12 @@ -### **Python3** - - - ```python class Solution: def minNumberOperations(self, target: List[int]) -> int: return target[0] + sum(max(0, b - a) for a, b in pairwise(target)) ``` -### **Java** - - - ```java class Solution { public int minNumberOperations(int[] target) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func minNumberOperations(target []int) int { f := target[0] @@ -136,8 +122,6 @@ func minNumberOperations(target []int) int { } ``` -### **TypeScript** - ```ts function minNumberOperations(target: number[]): number { let f = target[0]; @@ -150,10 +134,6 @@ function minNumberOperations(target: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1526.Minimum Number of Increments on Subarrays to Form a Target Array/README_EN.md b/solution/1500-1599/1526.Minimum Number of Increments on Subarrays to Form a Target Array/README_EN.md index 8daf70819364a..0a42fb1f49ed9 100644 --- a/solution/1500-1599/1526.Minimum Number of Increments on Subarrays to Form a Target Array/README_EN.md +++ b/solution/1500-1599/1526.Minimum Number of Increments on Subarrays to Form a Target Array/README_EN.md @@ -51,9 +51,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return target[0] + sum(max(0, b - a) for a, b in pairwise(target)) ``` -### **Java** - ```java class Solution { public int minNumberOperations(int[] target) { @@ -77,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +90,6 @@ public: }; ``` -### **Go** - ```go func minNumberOperations(target []int) int { f := target[0] @@ -108,8 +102,6 @@ func minNumberOperations(target []int) int { } ``` -### **TypeScript** - ```ts function minNumberOperations(target: number[]): number { let f = target[0]; @@ -122,10 +114,6 @@ function minNumberOperations(target: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1527.Patients With a Condition/README.md b/solution/1500-1599/1527.Patients With a Condition/README.md index 0047f46eb6c83..8c62c3ddbcccc 100644 --- a/solution/1500-1599/1527.Patients With a Condition/README.md +++ b/solution/1500-1599/1527.Patients With a Condition/README.md @@ -55,12 +55,10 @@ ## 解法 - +### 方法一 -### **SQL** - ```sql SELECT patient_id, @@ -71,3 +69,5 @@ WHERE conditions LIKE 'DIAB1%' OR conditions LIKE '% DIAB1%'; ``` + + diff --git a/solution/1500-1599/1527.Patients With a Condition/README_EN.md b/solution/1500-1599/1527.Patients With a Condition/README_EN.md index 676b383308a73..fab8874410698 100644 --- a/solution/1500-1599/1527.Patients With a Condition/README_EN.md +++ b/solution/1500-1599/1527.Patients With a Condition/README_EN.md @@ -54,9 +54,9 @@ Patients table: ## Solutions - +### Solution 1 -### **SQL** + ```sql SELECT @@ -68,3 +68,5 @@ WHERE conditions LIKE 'DIAB1%' OR conditions LIKE '% DIAB1%'; ``` + + diff --git a/solution/1500-1599/1528.Shuffle String/README.md b/solution/1500-1599/1528.Shuffle String/README.md index e75950a10e9d4..fa8c138d584b2 100644 --- a/solution/1500-1599/1528.Shuffle String/README.md +++ b/solution/1500-1599/1528.Shuffle String/README.md @@ -46,14 +46,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def restoreString(self, s: str, indices: List[int]) -> str: @@ -63,10 +59,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String restoreString(String s, int[] indices) { @@ -80,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +86,6 @@ public: }; ``` -### **Go** - ```go func restoreString(s string, indices []int) string { ans := make([]rune, len(s)) @@ -108,8 +96,6 @@ func restoreString(s string, indices []int) string { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -125,10 +111,6 @@ var restoreString = function (s, indices) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1528.Shuffle String/README_EN.md b/solution/1500-1599/1528.Shuffle String/README_EN.md index 488ffbbf8dd93..d0e091462830b 100644 --- a/solution/1500-1599/1528.Shuffle String/README_EN.md +++ b/solution/1500-1599/1528.Shuffle String/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String restoreString(String s, int[] indices) { @@ -66,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -82,8 +78,6 @@ public: }; ``` -### **Go** - ```go func restoreString(s string, indices []int) string { ans := make([]rune, len(s)) @@ -94,8 +88,6 @@ func restoreString(s string, indices []int) string { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -111,10 +103,6 @@ var restoreString = function (s, indices) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1529.Minimum Suffix Flips/README.md b/solution/1500-1599/1529.Minimum Suffix Flips/README.md index 5008ad6897a88..7ce11e6d91bce 100644 --- a/solution/1500-1599/1529.Minimum Suffix Flips/README.md +++ b/solution/1500-1599/1529.Minimum Suffix Flips/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 从前往后遍历 $target$,判断每个位置是否需要翻转,如果需要翻转,则翻转,并记录翻转次数。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def minFlips(self, target: str) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minFlips(String target) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func minFlips(target string) int { ans := 0 @@ -138,18 +124,6 @@ func minFlips(target string) int { } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1529.Minimum Suffix Flips/README_EN.md b/solution/1500-1599/1529.Minimum Suffix Flips/README_EN.md index 27eeb6758428a..880acecc49f26 100644 --- a/solution/1500-1599/1529.Minimum Suffix Flips/README_EN.md +++ b/solution/1500-1599/1529.Minimum Suffix Flips/README_EN.md @@ -54,9 +54,9 @@ We need at least 3 flip operations to form target. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minFlips(String target) { @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +99,6 @@ public: }; ``` -### **Go** - ```go func minFlips(target string) int { ans := 0 @@ -118,16 +112,6 @@ func minFlips(target string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1530.Number of Good Leaf Nodes Pairs/README.md b/solution/1500-1599/1530.Number of Good Leaf Nodes Pairs/README.md index 07ab3a380352d..c1afc2ea084c2 100644 --- a/solution/1500-1599/1530.Number of Good Leaf Nodes Pairs/README.md +++ b/solution/1500-1599/1530.Number of Good Leaf Nodes Pairs/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 题目求一个二叉树好叶子节点的对数,答案可以拆分为三部分之和:左子树好叶子节点的对数、右子树好叶子节点的对数,以及左子树叶子节点与右子树叶子节点组成的好叶子节点的对数。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -116,10 +110,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -170,8 +160,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -215,8 +203,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -258,10 +244,6 @@ func dfs(root *TreeNode, cnt []int, i int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1530.Number of Good Leaf Nodes Pairs/README_EN.md b/solution/1500-1599/1530.Number of Good Leaf Nodes Pairs/README_EN.md index 70b01c2e26a85..e4e6f27a29a88 100644 --- a/solution/1500-1599/1530.Number of Good Leaf Nodes Pairs/README_EN.md +++ b/solution/1500-1599/1530.Number of Good Leaf Nodes Pairs/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -83,8 +83,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -135,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -180,8 +176,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -223,10 +217,6 @@ func dfs(root *TreeNode, cnt []int, i int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1531.String Compression II/README.md b/solution/1500-1599/1531.String Compression II/README.md index 36c6d744dd493..c75bddc02237b 100644 --- a/solution/1500-1599/1531.String Compression II/README.md +++ b/solution/1500-1599/1531.String Compression II/README.md @@ -48,22 +48,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - -```python - -``` - -### **Java** - - - ```java class Solution { public int getLengthOfOptimalCompression(String s, int k) { @@ -116,10 +104,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1531.String Compression II/README_EN.md b/solution/1500-1599/1531.String Compression II/README_EN.md index ea953dfe3807a..fcddf800ca6bc 100644 --- a/solution/1500-1599/1531.String Compression II/README_EN.md +++ b/solution/1500-1599/1531.String Compression II/README_EN.md @@ -47,15 +47,9 @@ ## Solutions - - -### **Python3** - -```python +### Solution 1 -``` - -### **Java** + ```java class Solution { @@ -109,10 +103,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1532.The Most Recent Three Orders/README.md b/solution/1500-1599/1532.The Most Recent Three Orders/README.md index b717299e360c2..b652456e2e36e 100644 --- a/solution/1500-1599/1532.The Most Recent Three Orders/README.md +++ b/solution/1500-1599/1532.The Most Recent Three Orders/README.md @@ -109,16 +109,12 @@ Marwan 只有 1 笔订单。 ## 解法 - - -**方法一:等值连接 + 窗口函数** +### 方法一:等值连接 + 窗口函数 我们可以使用等值连接,将 `Customers` 表和 `Orders` 表按照 `customer_id` 进行连接,然后使用 `row_number()` 窗口函数来为每个消费者的订单按照 `order_date` 降序排列,并为每个消费者的订单添加一个序号,最后筛选出序号小于等于 $3$ 的订单即可。 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -140,3 +136,5 @@ ORDER BY 1, 2, 4 DESC; ``` + + diff --git a/solution/1500-1599/1532.The Most Recent Three Orders/README_EN.md b/solution/1500-1599/1532.The Most Recent Three Orders/README_EN.md index 79b53383dc6c0..f29cb3bd9a1dc 100644 --- a/solution/1500-1599/1532.The Most Recent Three Orders/README_EN.md +++ b/solution/1500-1599/1532.The Most Recent Three Orders/README_EN.md @@ -100,14 +100,12 @@ We sort the result table by customer_name in ascending order, by customer_id in ## Solutions -**Solution 1: Equi-Join + Window Function** +### Solution 1: Equi-Join + Window Function We can use an equi-join to join the `Customers` table and the `Orders` table based on `customer_id`, and then use the window function `row_number()` to sort the orders for each customer by `order_date` in descending order and assign a row number to each order. Finally, we can filter out the orders with a row number less than or equal to $3$. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -129,3 +127,5 @@ ORDER BY 1, 2, 4 DESC; ``` + + diff --git a/solution/1500-1599/1533.Find the Index of the Large Integer/README.md b/solution/1500-1599/1533.Find the Index of the Large Integer/README.md index 2bd4c9230291e..3cca747e9fdf5 100644 --- a/solution/1500-1599/1533.Find the Index of the Large Integer/README.md +++ b/solution/1500-1599/1533.Find the Index of the Large Integer/README.md @@ -71,18 +71,10 @@ reader.compareSub(4, 4, 5, 5) // 返回 1。因此,可以确定 arr[4] 是数 ## 解法 - - -三分查找。 - -前两部分数量相等,进行 `compareSub` 比较。 +### 方法一 -### **Python3** - - - ```python # """ # This is ArrayReader's API interface. @@ -119,10 +111,6 @@ class Solution: return left ``` -### **Java** - - - ```java /** * // This is ArrayReader's API interface. @@ -159,8 +147,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the ArrayReader's API interface. @@ -199,8 +185,6 @@ public: }; ``` -### **Go** - ```go /** * // This is the ArrayReader's API interface. @@ -234,10 +218,6 @@ func getIndex(reader *ArrayReader) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1533.Find the Index of the Large Integer/README_EN.md b/solution/1500-1599/1533.Find the Index of the Large Integer/README_EN.md index 4efb96ff0c4cd..cb9621b01355f 100644 --- a/solution/1500-1599/1533.Find the Index of the Large Integer/README_EN.md +++ b/solution/1500-1599/1533.Find the Index of the Large Integer/README_EN.md @@ -63,9 +63,9 @@ Notice that we made only 3 calls, so the answer is valid. ## Solutions - +### Solution 1 -### **Python3** + ```python # """ @@ -103,8 +103,6 @@ class Solution: return left ``` -### **Java** - ```java /** * // This is ArrayReader's API interface. @@ -141,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the ArrayReader's API interface. @@ -181,8 +177,6 @@ public: }; ``` -### **Go** - ```go /** * // This is the ArrayReader's API interface. @@ -216,10 +210,6 @@ func getIndex(reader *ArrayReader) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1534.Count Good Triplets/README.md b/solution/1500-1599/1534.Count Good Triplets/README.md index 13e6c5505d9cf..132037d8ed4e2 100644 --- a/solution/1500-1599/1534.Count Good Triplets/README.md +++ b/solution/1500-1599/1534.Count Good Triplets/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举所有的 $i$, $j$ 和 $k$,其中 $i \lt j \lt k$,判断是否同时满足 $|arr[i] - arr[j]| \le a$,$|arr[j] - arr[k]| \le b$ 和 $|arr[i] - arr[k]| \le c$,如果满足则将答案加一。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countGoodTriplets(int[] arr, int a, int b, int c) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func countGoodTriplets(arr []int, a int, b int, c int) (ans int) { n := len(arr) @@ -149,10 +135,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1534.Count Good Triplets/README_EN.md b/solution/1500-1599/1534.Count Good Triplets/README_EN.md index e2b06e3076c2a..1f0e414c4e897 100644 --- a/solution/1500-1599/1534.Count Good Triplets/README_EN.md +++ b/solution/1500-1599/1534.Count Good Triplets/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countGoodTriplets(int[] arr, int a, int b, int c) { @@ -88,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +104,6 @@ public: }; ``` -### **Go** - ```go func countGoodTriplets(arr []int, a int, b int, c int) (ans int) { n := len(arr) @@ -133,10 +127,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1535.Find the Winner of an Array Game/README.md b/solution/1500-1599/1535.Find the Winner of an Array Game/README.md index d00eef2d4d1ed..ab8a8c83d6b97 100644 --- a/solution/1500-1599/1535.Find the Winner of an Array Game/README.md +++ b/solution/1500-1599/1535.Find the Winner of an Array Game/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 我们注意到,每次会比较数组的前两个元素,不管结果怎么样,下一次的比较,一定是轮到了数组中的下一个元素和当前的胜者进行比较。因此,如果循环了 $n-1$ 次,那么最后的胜者一定是数组中的最大元素。否则,如果某个元素连续胜出了 $k$ 次,那么这个元素就是最后的胜者。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def getWinner(self, arr: List[int], k: int) -> int: @@ -87,10 +81,6 @@ class Solution: return mx ``` -### **Java** - - - ```java class Solution { public int getWinner(int[] arr, int k) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func getWinner(arr []int, k int) int { mx, cnt := arr[0], 0 @@ -154,8 +140,6 @@ func getWinner(arr []int, k int) int { } ``` -### **TypeScript** - ```ts function getWinner(arr: number[], k: number): number { let mx = arr[0]; @@ -175,8 +159,6 @@ function getWinner(arr: number[], k: number): number { } ``` -### **C#** - ```cs public class Solution { public int GetWinner(int[] arr, int k) { @@ -197,10 +179,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1535.Find the Winner of an Array Game/README_EN.md b/solution/1500-1599/1535.Find the Winner of an Array Game/README_EN.md index c693ac6433995..95a45466aa63d 100644 --- a/solution/1500-1599/1535.Find the Winner of an Array Game/README_EN.md +++ b/solution/1500-1599/1535.Find the Winner of an Array Game/README_EN.md @@ -47,9 +47,9 @@ So we can see that 4 rounds will be played and 5 is the winner because it wins 2 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return mx ``` -### **Java** - ```java class Solution { public int getWinner(int[] arr, int k) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func getWinner(arr []int, k int) int { mx, cnt := arr[0], 0 @@ -132,8 +126,6 @@ func getWinner(arr []int, k int) int { } ``` -### **TypeScript** - ```ts function getWinner(arr: number[], k: number): number { let mx = arr[0]; @@ -153,8 +145,6 @@ function getWinner(arr: number[], k: number): number { } ``` -### **C#** - ```cs public class Solution { public int GetWinner(int[] arr, int k) { @@ -175,10 +165,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/README.md b/solution/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/README.md index 29f52cdb45ad1..a685508d4a808 100644 --- a/solution/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/README.md +++ b/solution/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们逐行处理,对于第 $i$ 行,最后一个 $1$ 所在的位置必须小于等于 $i$,我们在 $[i, n)$ 中找到第一个满足条件的行,记为 $k$。然后从第 $k$ 行开始,依次向上交换相邻的两行,直到第 $i$ 行。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def minSwaps(self, grid: List[List[int]]) -> int: @@ -94,10 +88,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minSwaps(int[][] grid) { @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -174,8 +162,6 @@ public: }; ``` -### **Go** - ```go func minSwaps(grid [][]int) (ans int) { n := len(grid) @@ -211,8 +197,6 @@ func minSwaps(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function minSwaps(grid: number[][]): number { const n = grid.length; @@ -246,10 +230,6 @@ function minSwaps(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/README_EN.md b/solution/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/README_EN.md index b185c1f9be2e1..c6fb8c9333d6c 100644 --- a/solution/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/README_EN.md +++ b/solution/1500-1599/1536.Minimum Swaps to Arrange a Binary Grid/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy We process row by row. For the $i$-th row, the position of the last '1' must be less than or equal to $i$. We find the first row that meets the condition in $[i, n)$, denoted as $k$. Then, starting from the $k$-th row, we swap the adjacent two rows upwards until the $i$-th row. @@ -54,8 +54,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ i -### **Python3** - ```python class Solution: def minSwaps(self, grid: List[List[int]]) -> int: @@ -82,8 +80,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minSwaps(int[][] grid) { @@ -122,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +154,6 @@ public: }; ``` -### **Go** - ```go func minSwaps(grid [][]int) (ans int) { n := len(grid) @@ -197,8 +189,6 @@ func minSwaps(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function minSwaps(grid: number[][]): number { const n = grid.length; @@ -232,10 +222,6 @@ function minSwaps(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1537.Get the Maximum Score/README.md b/solution/1500-1599/1537.Get the Maximum Score/README.md index 0a492aa4680b8..1c52eb929d47c 100644 --- a/solution/1500-1599/1537.Get the Maximum Score/README.md +++ b/solution/1500-1599/1537.Get the Maximum Score/README.md @@ -64,14 +64,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxSum(self, nums1: List[int], nums2: List[int]) -> int: @@ -99,10 +95,6 @@ class Solution: return max(f, g) % mod ``` -### **Java** - - - ```java class Solution { public int maxSum(int[] nums1, int[] nums2) { @@ -130,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +150,6 @@ public: }; ``` -### **Go** - ```go func maxSum(nums1 []int, nums2 []int) int { const mod int = 1e9 + 7 @@ -192,8 +180,6 @@ func maxSum(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - ```ts function maxSum(nums1: number[], nums2: number[]): number { const mod = 1e9 + 7; @@ -220,10 +206,6 @@ function maxSum(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1537.Get the Maximum Score/README_EN.md b/solution/1500-1599/1537.Get the Maximum Score/README_EN.md index 625a42dae6470..a95be86694d49 100644 --- a/solution/1500-1599/1537.Get the Maximum Score/README_EN.md +++ b/solution/1500-1599/1537.Get the Maximum Score/README_EN.md @@ -58,9 +58,9 @@ Maximum sum is obtained with the path [6,7,8,9,10]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -89,8 +89,6 @@ class Solution: return max(f, g) % mod ``` -### **Java** - ```java class Solution { public int maxSum(int[] nums1, int[] nums2) { @@ -118,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +144,6 @@ public: }; ``` -### **Go** - ```go func maxSum(nums1 []int, nums2 []int) int { const mod int = 1e9 + 7 @@ -180,8 +174,6 @@ func maxSum(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - ```ts function maxSum(nums1: number[], nums2: number[]): number { const mod = 1e9 + 7; @@ -208,10 +200,6 @@ function maxSum(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1538.Guess the Majority in a Hidden Array/README.md b/solution/1500-1599/1538.Guess the Majority in a Hidden Array/README.md index 63d067e88716c..4dd616af1ff0e 100644 --- a/solution/1500-1599/1538.Guess the Majority in a Hidden Array/README.md +++ b/solution/1500-1599/1538.Guess the Majority in a Hidden Array/README.md @@ -68,9 +68,7 @@ reader.query(4,5,6,7) // 返回 4,因为 nums[4], nums[5], nums[6], nums[7] ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 我们先调用 `reader.query(0, 1, 2, 3)`,将得到的结果记为 $x$。 @@ -84,10 +82,6 @@ reader.query(4,5,6,7) // 返回 4,因为 nums[4], nums[5], nums[6], nums[7] -### **Python3** - - - ```python # """ # This is the ArrayReader's API interface. @@ -140,10 +134,6 @@ class Solution: return 3 if a > b else k ``` -### **Java** - - - ```java /** * // This is the ArrayReader's API interface. @@ -204,8 +194,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the ArrayReader's API interface. @@ -266,8 +254,6 @@ public: }; ``` -### **Go** - ```go /** * // This is the ArrayReader's API interface. @@ -327,8 +313,6 @@ func guessMajority(reader *ArrayReader) int { } ``` -### **TypeScript** - ```ts /** * // This is the ArrayReader's API interface. @@ -385,10 +369,6 @@ function guessMajority(reader: ArrayReader): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1538.Guess the Majority in a Hidden Array/README_EN.md b/solution/1500-1599/1538.Guess the Majority in a Hidden Array/README_EN.md index 1ed29e47bbd7f..8f249021ab890 100644 --- a/solution/1500-1599/1538.Guess the Majority in a Hidden Array/README_EN.md +++ b/solution/1500-1599/1538.Guess the Majority in a Hidden Array/README_EN.md @@ -63,9 +63,9 @@ Index 2, 4, 6, 7 is also a correct answer. ## Solutions - +### Solution 1 -### **Python3** + ```python # """ @@ -119,8 +119,6 @@ class Solution: return 3 if a > b else k ``` -### **Java** - ```java /** * // This is the ArrayReader's API interface. @@ -181,8 +179,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the ArrayReader's API interface. @@ -243,8 +239,6 @@ public: }; ``` -### **Go** - ```go /** * // This is the ArrayReader's API interface. @@ -304,8 +298,6 @@ func guessMajority(reader *ArrayReader) int { } ``` -### **TypeScript** - ```ts /** * // This is the ArrayReader's API interface. @@ -362,10 +354,6 @@ function guessMajority(reader: ArrayReader): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1539.Kth Missing Positive Number/README.md b/solution/1500-1599/1539.Kth Missing Positive Number/README.md index 794a9f1ab7c47..b172b36fcece8 100644 --- a/solution/1500-1599/1539.Kth Missing Positive Number/README.md +++ b/solution/1500-1599/1539.Kth Missing Positive Number/README.md @@ -47,16 +47,10 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 -### **Python3** - - - ```python class Solution: def findKthPositive(self, arr: List[int], k: int) -> int: @@ -72,10 +66,6 @@ class Solution: return arr[left - 1] + k - (arr[left - 1] - (left - 1) - 1) ``` -### **Java** - - - ```java class Solution { public int findKthPositive(int[] arr, int k) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func findKthPositive(arr []int, k int) int { if arr[0] > k { @@ -136,10 +122,6 @@ func findKthPositive(arr []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1539.Kth Missing Positive Number/README_EN.md b/solution/1500-1599/1539.Kth Missing Positive Number/README_EN.md index 5c4871cb82dcc..885ab45c09237 100644 --- a/solution/1500-1599/1539.Kth Missing Positive Number/README_EN.md +++ b/solution/1500-1599/1539.Kth Missing Positive Number/README_EN.md @@ -42,12 +42,10 @@ ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python class Solution: def findKthPositive(self, arr: List[int], k: int) -> int: @@ -63,8 +61,6 @@ class Solution: return arr[left - 1] + k - (arr[left - 1] - (left - 1) - 1) ``` -### **Java** - ```java class Solution { public int findKthPositive(int[] arr, int k) { @@ -85,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +99,6 @@ public: }; ``` -### **Go** - ```go func findKthPositive(arr []int, k int) int { if arr[0] > k { @@ -125,10 +117,6 @@ func findKthPositive(arr []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1540.Can Convert String in K Moves/README.md b/solution/1500-1599/1540.Can Convert String in K Moves/README.md index f10355d6ec9f5..3bdd0dba443d3 100644 --- a/solution/1500-1599/1540.Can Convert String in K Moves/README.md +++ b/solution/1500-1599/1540.Can Convert String in K Moves/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们首先判断字符串 $s$ 和字符串 $t$ 的长度是否相等,如果不相等,直接返回 `false`。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def canConvertString(self, s: str, t: str, k: int) -> bool: @@ -94,10 +88,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean canConvertString(String s, String t, int k) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func canConvertString(s string, t string, k int) bool { if len(s) != len(t) { @@ -164,10 +150,6 @@ func canConvertString(s string, t string, k int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1540.Can Convert String in K Moves/README_EN.md b/solution/1500-1599/1540.Can Convert String in K Moves/README_EN.md index cc5a42a609ab4..45c659725128e 100644 --- a/solution/1500-1599/1540.Can Convert String in K Moves/README_EN.md +++ b/solution/1500-1599/1540.Can Convert String in K Moves/README_EN.md @@ -55,9 +55,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean canConvertString(String s, String t, int k) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +117,6 @@ public: }; ``` -### **Go** - ```go func canConvertString(s string, t string, k int) bool { if len(s) != len(t) { @@ -142,10 +136,6 @@ func canConvertString(s string, t string, k int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/README.md b/solution/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/README.md index 0e5593d24c400..5b2176d30a09b 100644 --- a/solution/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/README.md +++ b/solution/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们用 $x$ 表示字符串中待匹配的左括号的数量,初始时为 $0$。遍历字符串 $s$: @@ -86,10 +84,6 @@ -### **Python3** - - - ```python class Solution: def minInsertions(self, s: str) -> int: @@ -118,10 +112,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minInsertions(String s) { @@ -149,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -179,8 +167,6 @@ public: }; ``` -### **Go** - ```go func minInsertions(s string) int { ans, x, n := 0, 0, len(s) @@ -205,10 +191,6 @@ func minInsertions(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/README_EN.md b/solution/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/README_EN.md index 9266432fa797a..e2ecd2a014c4d 100644 --- a/solution/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/README_EN.md +++ b/solution/1500-1599/1541.Minimum Insertions to Balance a Parentheses String/README_EN.md @@ -56,9 +56,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,23 +67,27 @@ class Solution: i, n = 0, len(s) while i < n: if s[i] == '(': + # 待匹配的左括号加 1 x += 1 else: if i < n - 1 and s[i + 1] == ')': + # 有连续两个右括号,i 往后移动 i += 1 else: + # 只有一个右括号,插入一个 ans += 1 if x == 0: + # 无待匹配的左括号,插入一个 ans += 1 else: + # 待匹配的左括号减 1 x -= 1 i += 1 + # 遍历结束,仍有待匹配的左括号,说明右括号不足,插入 x << 1 个 ans += x << 1 return ans ``` -### **Java** - ```java class Solution { public int minInsertions(String s) { @@ -111,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +143,6 @@ public: }; ``` -### **Go** - ```go func minInsertions(s string) int { ans, x, n := 0, 0, len(s) @@ -167,10 +167,6 @@ func minInsertions(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1542.Find Longest Awesome Substring/README.md b/solution/1500-1599/1542.Find Longest Awesome Substring/README.md index f72490b2c7bd7..f175fa7901710 100644 --- a/solution/1500-1599/1542.Find Longest Awesome Substring/README.md +++ b/solution/1500-1599/1542.Find Longest Awesome Substring/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:状态压缩 + 前缀和思想** +### 方法一:状态压缩 + 前缀和思想 根据题目描述,“超赞子字符串”中的字符可以通过交换得到回文字符串,因此,“超赞子字符串”中最多有一个数字字符出现奇数次,其余数字字符出现偶数次。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def longestAwesome(self, s: str) -> int: @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestAwesome(String s) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func longestAwesome(s string) int { d := [1024]int{} @@ -178,10 +164,6 @@ func longestAwesome(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1542.Find Longest Awesome Substring/README_EN.md b/solution/1500-1599/1542.Find Longest Awesome Substring/README_EN.md index 16a715ae9bf6b..9322401c4ec1e 100644 --- a/solution/1500-1599/1542.Find Longest Awesome Substring/README_EN.md +++ b/solution/1500-1599/1542.Find Longest Awesome Substring/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestAwesome(String s) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +117,6 @@ public: }; ``` -### **Go** - ```go func longestAwesome(s string) int { d := [1024]int{} @@ -146,10 +140,6 @@ func longestAwesome(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1543.Fix Product Name Format/README.md b/solution/1500-1599/1543.Fix Product Name Format/README.md index fb1964cf5941e..423bff33d4725 100644 --- a/solution/1500-1599/1543.Fix Product Name Format/README.md +++ b/solution/1500-1599/1543.Fix Product Name Format/README.md @@ -69,12 +69,10 @@ Sales 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -91,3 +89,5 @@ ORDER BY 1, 2; ``` + + diff --git a/solution/1500-1599/1543.Fix Product Name Format/README_EN.md b/solution/1500-1599/1543.Fix Product Name Format/README_EN.md index 1f086a35dbdf9..9bf298e75d0aa 100644 --- a/solution/1500-1599/1543.Fix Product Name Format/README_EN.md +++ b/solution/1500-1599/1543.Fix Product Name Format/README_EN.md @@ -67,9 +67,9 @@ In March, one matryoshka was sold. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -87,3 +87,5 @@ ORDER BY 1, 2; ``` + + diff --git a/solution/1500-1599/1544.Make The String Great/README.md b/solution/1500-1599/1544.Make The String Great/README.md index ca9d08150361d..e4a592625730c 100644 --- a/solution/1500-1599/1544.Make The String Great/README.md +++ b/solution/1500-1599/1544.Make The String Great/README.md @@ -59,18 +59,12 @@ ## 解法 - - -**方法一:栈模拟** +### 方法一:栈模拟 时间复杂度 $O(n)$,空间复杂度 $O(n)$,其中 $n$ 是字符串 `s` 的长度。 -### **Python3** - - - ```python class Solution: def makeGood(self, s: str) -> str: @@ -83,10 +77,6 @@ class Solution: return "".join(stk) ``` -### **Java** - - - ```java class Solution { public String makeGood(String s) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func makeGood(s string) string { stk := []rune{} @@ -145,10 +131,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1544.Make The String Great/README_EN.md b/solution/1500-1599/1544.Make The String Great/README_EN.md index 0761acc428007..5128b80bf2f8f 100644 --- a/solution/1500-1599/1544.Make The String Great/README_EN.md +++ b/solution/1500-1599/1544.Make The String Great/README_EN.md @@ -55,9 +55,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return "".join(stk) ``` -### **Java** - ```java class Solution { public String makeGood(String s) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +104,6 @@ public: }; ``` -### **Go** - ```go func makeGood(s string) string { stk := []rune{} @@ -131,10 +125,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/README.md b/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/README.md index 0b5ffeb52f948..f1e9d6b533ae2 100644 --- a/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/README.md +++ b/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/README.md @@ -69,9 +69,7 @@ ## 解法 - - -**方法一:分类讨论 + 递归** +### 方法一:分类讨论 + 递归 我们可以发现,对于 $S_n$,其前半部分和 $S_{n-1}$ 是一样的,而后半部分是 $S_{n-1}$ 的反转取反。因此我们可以设计一个函数 $dfs(n, k)$,表示第 $n$ 个字符串的第 $k$ 位字符。答案即为 $dfs(n, k)$。 @@ -86,10 +84,6 @@ -### **Python3** - - - ```python class Solution: def findKthBit(self, n: int, k: int) -> str: @@ -106,10 +100,6 @@ class Solution: return str(dfs(n, k)) ``` -### **Java** - - - ```java class Solution { public char findKthBit(int n, int k) { @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func findKthBit(n int, k int) byte { var dfs func(n, k int) int @@ -178,8 +164,6 @@ func findKthBit(n int, k int) byte { } ``` -### **TypeScript** - ```ts function findKthBit(n: number, k: number): string { const dfs = (n: number, k: number): number => { @@ -199,10 +183,6 @@ function findKthBit(n: number, k: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/README_EN.md b/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/README_EN.md index 6456248f0b814..4949b76bd1987 100644 --- a/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/README_EN.md +++ b/solution/1500-1599/1545.Find Kth Bit in Nth Binary String/README_EN.md @@ -53,7 +53,7 @@ The 11th bit is "1". ## Solutions -**Solution 1: Case Analysis + Recursion** +### Solution 1: Case Analysis + Recursion We can observe that for $S_n$, the first half is the same as $S_{n-1}$, and the second half is the reverse and negation of $S_{n-1}$. Therefore, we can design a function $dfs(n, k)$, which represents the $k$-th character of the $n$-th string. The answer is $dfs(n, k)$. @@ -68,8 +68,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def findKthBit(self, n: int, k: int) -> str: @@ -86,8 +84,6 @@ class Solution: return str(dfs(n, k)) ``` -### **Java** - ```java class Solution { public char findKthBit(int n, int k) { @@ -110,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +128,6 @@ public: }; ``` -### **Go** - ```go func findKthBit(n int, k int) byte { var dfs func(n, k int) int @@ -156,8 +148,6 @@ func findKthBit(n int, k int) byte { } ``` -### **TypeScript** - ```ts function findKthBit(n: number, k: number): string { const dfs = (n: number, k: number): number => { @@ -177,10 +167,6 @@ function findKthBit(n: number, k: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/README.md b/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/README.md index 1793d4125d072..3052d448d00e5 100644 --- a/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/README.md +++ b/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:贪心 + 前缀和 + 哈希表** +### 方法一:贪心 + 前缀和 + 哈希表 我们遍历数组 $nums$,利用前缀和 + 哈希表的方法,寻找和为 $target$ 的子数组,若找到,则答案加一,然后我们将前缀和置为 $0$,继续遍历数组 $nums$,直到遍历完整个数组。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def maxNonOverlapping(self, nums: List[int], target: int) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxNonOverlapping(int[] nums, int target) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func maxNonOverlapping(nums []int, target int) (ans int) { n := len(nums) @@ -156,8 +142,6 @@ func maxNonOverlapping(nums []int, target int) (ans int) { } ``` -### **TypeScript** - ```ts function maxNonOverlapping(nums: number[], target: number): number { const n = nums.length; @@ -179,10 +163,6 @@ function maxNonOverlapping(nums: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/README_EN.md b/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/README_EN.md index d437b392235a2..e58c56b30e544 100644 --- a/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/README_EN.md +++ b/solution/1500-1599/1546.Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Greedy + Prefix Sum + Hash Table** +### Solution 1: Greedy + Prefix Sum + Hash Table We traverse the array $nums$, using the method of prefix sum + hash table, to find subarrays with a sum of $target$. If found, we increment the answer by one, then we set the prefix sum to $0$ and continue to traverse the array $nums$ until the entire array is traversed. @@ -43,8 +43,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maxNonOverlapping(self, nums: List[int], target: int) -> int: @@ -64,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxNonOverlapping(int[] nums, int target) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +108,6 @@ public: }; ``` -### **Go** - ```go func maxNonOverlapping(nums []int, target int) (ans int) { n := len(nums) @@ -135,8 +127,6 @@ func maxNonOverlapping(nums []int, target int) (ans int) { } ``` -### **TypeScript** - ```ts function maxNonOverlapping(nums: number[], target: number): number { const n = nums.length; @@ -158,10 +148,6 @@ function maxNonOverlapping(nums: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1547.Minimum Cost to Cut a Stick/README.md b/solution/1500-1599/1547.Minimum Cost to Cut a Stick/README.md index 7197139bf6af1..f08325c667445 100644 --- a/solution/1500-1599/1547.Minimum Cost to Cut a Stick/README.md +++ b/solution/1500-1599/1547.Minimum Cost to Cut a Stick/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:动态规划(区间 DP)** +### 方法一:动态规划(区间 DP) 我们可以往切割点数组 $cuts$ 中添加两个元素,分别是 $0$ 和 $n$,表示棍子的两端。然后我们对 $cuts$ 数组进行排序,这样我们就可以将整个棍子切割为若干个区间,每个区间都有两个切割点。不妨设此时 $cuts$ 数组的长度为 $m$。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def minCost(self, n: int, cuts: List[int]) -> int: @@ -91,25 +85,6 @@ class Solution: return f[0][-1] ``` -```python -class Solution: - def minCost(self, n: int, cuts: List[int]) -> int: - cuts.extend([0, n]) - cuts.sort() - m = len(cuts) - f = [[0] * m for _ in range(m)] - for i in range(m - 1, -1, -1): - for j in range(i + 2, m): - f[i][j] = inf - for k in range(i + 1, j): - f[i][j] = min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]) - return f[0][-1] -``` - -### **Java** - - - ```java class Solution { public int minCost(int n, int[] cuts) { @@ -136,33 +111,6 @@ class Solution { } ``` -```java -class Solution { - public int minCost(int n, int[] cuts) { - List nums = new ArrayList<>(); - for (int x : cuts) { - nums.add(x); - } - nums.add(0); - nums.add(n); - Collections.sort(nums); - int m = nums.size(); - int[][] f = new int[m][m]; - for (int i = m - 1; i >= 0; --i) { - for (int j = i + 2; j < m; ++j) { - f[i][j] = 1 << 30; - for (int k = i + 1; k < j; ++k) { - f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + nums.get(j) - nums.get(i)); - } - } - } - return f[0][m - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -186,30 +134,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minCost(int n, vector& cuts) { - cuts.push_back(0); - cuts.push_back(n); - sort(cuts.begin(), cuts.end()); - int m = cuts.size(); - int f[110][110]{}; - for (int i = m - 1; ~i; --i) { - for (int j = i + 2; j < m; ++j) { - f[i][j] = 1 << 30; - for (int k = i + 1; k < j; ++k) { - f[i][j] = min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]); - } - } - } - return f[0][m - 1]; - } -}; -``` - -### **Go** - ```go func minCost(n int, cuts []int) int { cuts = append(cuts, []int{0, n}...) @@ -232,29 +156,6 @@ func minCost(n int, cuts []int) int { } ``` -```go -func minCost(n int, cuts []int) int { - cuts = append(cuts, []int{0, n}...) - sort.Ints(cuts) - m := len(cuts) - f := make([][]int, m) - for i := range f { - f[i] = make([]int, m) - } - for i := m - 1; i >= 0; i-- { - for j := i + 2; j < m; j++ { - f[i][j] = 1 << 30 - for k := i + 1; k < j; k++ { - f[i][j] = min(f[i][j], f[i][k]+f[k][j]+cuts[j]-cuts[i]) - } - } - } - return f[0][m-1] -} -``` - -### **TypeScript** - ```ts function minCost(n: number, cuts: number[]): number { cuts.push(0); @@ -274,10 +175,95 @@ function minCost(n: number, cuts: number[]): number { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def minCost(self, n: int, cuts: List[int]) -> int: + cuts.extend([0, n]) + cuts.sort() + m = len(cuts) + f = [[0] * m for _ in range(m)] + for i in range(m - 1, -1, -1): + for j in range(i + 2, m): + f[i][j] = inf + for k in range(i + 1, j): + f[i][j] = min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]) + return f[0][-1] ``` +```java +class Solution { + public int minCost(int n, int[] cuts) { + List nums = new ArrayList<>(); + for (int x : cuts) { + nums.add(x); + } + nums.add(0); + nums.add(n); + Collections.sort(nums); + int m = nums.size(); + int[][] f = new int[m][m]; + for (int i = m - 1; i >= 0; --i) { + for (int j = i + 2; j < m; ++j) { + f[i][j] = 1 << 30; + for (int k = i + 1; k < j; ++k) { + f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + nums.get(j) - nums.get(i)); + } + } + } + return f[0][m - 1]; + } +} +``` + +```cpp +class Solution { +public: + int minCost(int n, vector& cuts) { + cuts.push_back(0); + cuts.push_back(n); + sort(cuts.begin(), cuts.end()); + int m = cuts.size(); + int f[110][110]{}; + for (int i = m - 1; ~i; --i) { + for (int j = i + 2; j < m; ++j) { + f[i][j] = 1 << 30; + for (int k = i + 1; k < j; ++k) { + f[i][j] = min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]); + } + } + } + return f[0][m - 1]; + } +}; +``` + +```go +func minCost(n int, cuts []int) int { + cuts = append(cuts, []int{0, n}...) + sort.Ints(cuts) + m := len(cuts) + f := make([][]int, m) + for i := range f { + f[i] = make([]int, m) + } + for i := m - 1; i >= 0; i-- { + for j := i + 2; j < m; j++ { + f[i][j] = 1 << 30 + for k := i + 1; k < j; k++ { + f[i][j] = min(f[i][j], f[i][k]+f[k][j]+cuts[j]-cuts[i]) + } + } + } + return f[0][m-1] +} ``` + + diff --git a/solution/1500-1599/1547.Minimum Cost to Cut a Stick/README_EN.md b/solution/1500-1599/1547.Minimum Cost to Cut a Stick/README_EN.md index 004d9a56bb0a7..caab0eca430e4 100644 --- a/solution/1500-1599/1547.Minimum Cost to Cut a Stick/README_EN.md +++ b/solution/1500-1599/1547.Minimum Cost to Cut a Stick/README_EN.md @@ -46,7 +46,7 @@ There are much ordering with total cost <= 25, for example, the order [4, 6, ## Solutions -**Solution 1: Dynamic Programming (Interval DP)** +### Solution 1: Dynamic Programming (Interval DP) We can add two elements to the cut array $cuts$, which are $0$ and $n$, representing the two ends of the stick. Then we sort the $cuts$ array, so that we can cut the entire stick into several intervals, each interval has two cut points. Suppose the length of the $cuts$ array at this time is $m$. @@ -62,8 +62,6 @@ The time complexity is $O(m^3)$, and the space complexity is $O(m^2)$. Here, $m$ -### **Python3** - ```python class Solution: def minCost(self, n: int, cuts: List[int]) -> int: @@ -80,23 +78,6 @@ class Solution: return f[0][-1] ``` -```python -class Solution: - def minCost(self, n: int, cuts: List[int]) -> int: - cuts.extend([0, n]) - cuts.sort() - m = len(cuts) - f = [[0] * m for _ in range(m)] - for i in range(m - 1, -1, -1): - for j in range(i + 2, m): - f[i][j] = inf - for k in range(i + 1, j): - f[i][j] = min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]) - return f[0][-1] -``` - -### **Java** - ```java class Solution { public int minCost(int n, int[] cuts) { @@ -123,33 +104,6 @@ class Solution { } ``` -```java -class Solution { - public int minCost(int n, int[] cuts) { - List nums = new ArrayList<>(); - for (int x : cuts) { - nums.add(x); - } - nums.add(0); - nums.add(n); - Collections.sort(nums); - int m = nums.size(); - int[][] f = new int[m][m]; - for (int i = m - 1; i >= 0; --i) { - for (int j = i + 2; j < m; ++j) { - f[i][j] = 1 << 30; - for (int k = i + 1; k < j; ++k) { - f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + nums.get(j) - nums.get(i)); - } - } - } - return f[0][m - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -173,30 +127,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minCost(int n, vector& cuts) { - cuts.push_back(0); - cuts.push_back(n); - sort(cuts.begin(), cuts.end()); - int m = cuts.size(); - int f[110][110]{}; - for (int i = m - 1; ~i; --i) { - for (int j = i + 2; j < m; ++j) { - f[i][j] = 1 << 30; - for (int k = i + 1; k < j; ++k) { - f[i][j] = min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]); - } - } - } - return f[0][m - 1]; - } -}; -``` - -### **Go** - ```go func minCost(n int, cuts []int) int { cuts = append(cuts, []int{0, n}...) @@ -219,29 +149,6 @@ func minCost(n int, cuts []int) int { } ``` -```go -func minCost(n int, cuts []int) int { - cuts = append(cuts, []int{0, n}...) - sort.Ints(cuts) - m := len(cuts) - f := make([][]int, m) - for i := range f { - f[i] = make([]int, m) - } - for i := m - 1; i >= 0; i-- { - for j := i + 2; j < m; j++ { - f[i][j] = 1 << 30 - for k := i + 1; k < j; k++ { - f[i][j] = min(f[i][j], f[i][k]+f[k][j]+cuts[j]-cuts[i]) - } - } - } - return f[0][m-1] -} -``` - -### **TypeScript** - ```ts function minCost(n: number, cuts: number[]): number { cuts.push(0); @@ -249,9 +156,8 @@ function minCost(n: number, cuts: number[]): number { cuts.sort((a, b) => a - b); const m = cuts.length; const f: number[][] = new Array(m).fill(0).map(() => new Array(m).fill(0)); - for (let l = 2; l < m; ++l) { - for (let i = 0; i + l < m; ++i) { - const j = i + l; + for (let i = m - 2; i >= 0; --i) { + for (let j = i + 2; j < m; ++j) { f[i][j] = 1 << 30; for (let k = i + 1; k < j; ++k) { f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]); @@ -262,49 +168,95 @@ function minCost(n: number, cuts: number[]): number { } ``` -```ts -function minCost(n: number, cuts: number[]): number { - cuts.push(0); - cuts.push(n); - cuts.sort((a, b) => a - b); - const m = cuts.length; - const f: number[][] = new Array(m).fill(0).map(() => new Array(m).fill(0)); - for (let l = 2; l < m; ++l) { - for (let i = 0; i + l < m; ++i) { - const j = i + l; - f[i][j] = 1 << 30; - for (let k = i + 1; k < j; ++k) { - f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]); + + +### Solution 2 + + + +```python +class Solution: + def minCost(self, n: int, cuts: List[int]) -> int: + cuts.extend([0, n]) + cuts.sort() + m = len(cuts) + f = [[0] * m for _ in range(m)] + for i in range(m - 1, -1, -1): + for j in range(i + 2, m): + f[i][j] = inf + for k in range(i + 1, j): + f[i][j] = min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]) + return f[0][-1] +``` + +```java +class Solution { + public int minCost(int n, int[] cuts) { + List nums = new ArrayList<>(); + for (int x : cuts) { + nums.add(x); + } + nums.add(0); + nums.add(n); + Collections.sort(nums); + int m = nums.size(); + int[][] f = new int[m][m]; + for (int i = m - 1; i >= 0; --i) { + for (int j = i + 2; j < m; ++j) { + f[i][j] = 1 << 30; + for (int k = i + 1; k < j; ++k) { + f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + nums.get(j) - nums.get(i)); + } } } + return f[0][m - 1]; } - return f[0][m - 1]; } ``` -```ts -function minCost(n: number, cuts: number[]): number { - cuts.push(0); - cuts.push(n); - cuts.sort((a, b) => a - b); - const m = cuts.length; - const f: number[][] = new Array(m).fill(0).map(() => new Array(m).fill(0)); - for (let i = m - 2; i >= 0; --i) { - for (let j = i + 2; j < m; ++j) { - f[i][j] = 1 << 30; - for (let k = i + 1; k < j; ++k) { - f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]); +```cpp +class Solution { +public: + int minCost(int n, vector& cuts) { + cuts.push_back(0); + cuts.push_back(n); + sort(cuts.begin(), cuts.end()); + int m = cuts.size(); + int f[110][110]{}; + for (int i = m - 1; ~i; --i) { + for (int j = i + 2; j < m; ++j) { + f[i][j] = 1 << 30; + for (int k = i + 1; k < j; ++k) { + f[i][j] = min(f[i][j], f[i][k] + f[k][j] + cuts[j] - cuts[i]); + } } } + return f[0][m - 1]; } - return f[0][m - 1]; -} -``` - -### **...** - +}; ``` +```go +func minCost(n int, cuts []int) int { + cuts = append(cuts, []int{0, n}...) + sort.Ints(cuts) + m := len(cuts) + f := make([][]int, m) + for i := range f { + f[i] = make([]int, m) + } + for i := m - 1; i >= 0; i-- { + for j := i + 2; j < m; j++ { + f[i][j] = 1 << 30 + for k := i + 1; k < j; k++ { + f[i][j] = min(f[i][j], f[i][k]+f[k][j]+cuts[j]-cuts[i]) + } + } + } + return f[0][m-1] +} ``` + + diff --git a/solution/1500-1599/1548.The Most Similar Path in a Graph/README.md b/solution/1500-1599/1548.The Most Similar Path in a Graph/README.md index 39f17e0fa01e6..50665d032660e 100644 --- a/solution/1500-1599/1548.The Most Similar Path in a Graph/README.md +++ b/solution/1500-1599/1548.The Most Similar Path in a Graph/README.md @@ -78,9 +78,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们先根据给定的道路构建一个邻接表 $g$,其中 $g[i]$ 表示与城市 $i$ 直接相连的城市列表。 @@ -98,10 +96,6 @@ $$ -### **Python3** - - - ```python class Solution: def mostSimilar( @@ -135,10 +129,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List mostSimilar(int n, int[][] roads, String[] names, String[] targetPath) { @@ -189,8 +179,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -238,8 +226,6 @@ public: }; ``` -### **Go** - ```go func mostSimilar(n int, roads [][]int, names []string, targetPath []string) []int { g := make([][]int, n) @@ -297,8 +283,6 @@ func mostSimilar(n int, roads [][]int, names []string, targetPath []string) []in } ``` -### **TypeScript** - ```ts function mostSimilar( n: number, @@ -345,10 +329,6 @@ function mostSimilar( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1548.The Most Similar Path in a Graph/README_EN.md b/solution/1500-1599/1548.The Most Similar Path in a Graph/README_EN.md index cf341567b9070..fe8d7fcea74fd 100644 --- a/solution/1500-1599/1548.The Most Similar Path in a Graph/README_EN.md +++ b/solution/1500-1599/1548.The Most Similar Path in a Graph/README_EN.md @@ -67,7 +67,7 @@ It's equivalent to ["ATL","DXB","HND","DX ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We first build an adjacency list $g$ based on the given roads, where $g[i]$ represents the list of cities directly connected to city $i$. @@ -85,8 +85,6 @@ The time complexity is $O(m \times n^2)$, and the space complexity is $O(m \time -### **Python3** - ```python class Solution: def mostSimilar( @@ -120,8 +118,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List mostSimilar(int n, int[][] roads, String[] names, String[] targetPath) { @@ -172,8 +168,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -221,8 +215,6 @@ public: }; ``` -### **Go** - ```go func mostSimilar(n int, roads [][]int, names []string, targetPath []string) []int { g := make([][]int, n) @@ -280,8 +272,6 @@ func mostSimilar(n int, roads [][]int, names []string, targetPath []string) []in } ``` -### **TypeScript** - ```ts function mostSimilar( n: number, @@ -328,10 +318,6 @@ function mostSimilar( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1549.The Most Recent Orders for Each Product/README.md b/solution/1500-1599/1549.The Most Recent Orders for Each Product/README.md index 61f70c63c2e42..886179acc8de6 100644 --- a/solution/1500-1599/1549.The Most Recent Orders for Each Product/README.md +++ b/solution/1500-1599/1549.The Most Recent Orders for Each Product/README.md @@ -117,16 +117,12 @@ hard disk 没有被下单, 我们不把它包含在结果表中. ## 解法 - - -**方法一:等值连接 + 窗口函数** +### 方法一:等值连接 + 窗口函数 我们可以使用等值连接,将 `Orders` 表和 `Products` 表按照 `product_id` 连接起来,然后使用窗口函数 `rank()`,对 `Orders` 表中的每个 `product_id` 进行分组,按照 `order_date` 降序排列,然后取出每个分组中排名第一的记录。 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -148,3 +144,5 @@ ORDER BY 1, 2, 3; ``` + + diff --git a/solution/1500-1599/1549.The Most Recent Orders for Each Product/README_EN.md b/solution/1500-1599/1549.The Most Recent Orders for Each Product/README_EN.md index bf954d7731eff..02ecc9fbc0ade 100644 --- a/solution/1500-1599/1549.The Most Recent Orders for Each Product/README_EN.md +++ b/solution/1500-1599/1549.The Most Recent Orders for Each Product/README_EN.md @@ -115,14 +115,12 @@ The hard disk was never ordered and we do not include it in the result table. ## Solutions -**Solution 1: Equi-Join + Window Function** +### Solution 1: Equi-Join + Window Function We can use an equi-join to join the `Orders` table and the `Products` table based on `product_id`, and then use the window function `rank()`, which assigns a rank to each `product_id` in the `Orders` table based on its `order_date` in descending order. Finally, we can select the rows with a rank of $1$ for each `product_id`. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -144,3 +142,5 @@ ORDER BY 1, 2, 3; ``` + + diff --git a/solution/1500-1599/1550.Three Consecutive Odds/README.md b/solution/1500-1599/1550.Three Consecutive Odds/README.md index 1f8dd61337fe6..b4bfbda28a6d0 100644 --- a/solution/1500-1599/1550.Three Consecutive Odds/README.md +++ b/solution/1500-1599/1550.Three Consecutive Odds/README.md @@ -35,9 +35,7 @@ ## 解法 - - -**方法一:遍历数组** +### 方法一:遍历数组 直接遍历数组,统计连续奇数的个数,如果个数达到 3,则返回 `true`,否则遍历结束,返回 `false`。 @@ -45,10 +43,6 @@ -### **Python3** - - - ```python class Solution: def threeConsecutiveOdds(self, arr: List[int]) -> bool: @@ -63,19 +57,6 @@ class Solution: return False ``` -```python -class Solution: - def threeConsecutiveOdds(self, arr: List[int]) -> bool: - for i in range(len(arr) - 2): - if arr[i] % 2 + arr[i + 1] % 2 + arr[i + 2] % 2 == 3: - return True - return False -``` - -### **Java** - - - ```java class Solution { public boolean threeConsecutiveOdds(int[] arr) { @@ -95,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +93,6 @@ public: }; ``` -### **Go** - ```go func threeConsecutiveOdds(arr []int) bool { cnt := 0 @@ -133,8 +110,6 @@ func threeConsecutiveOdds(arr []int) bool { } ``` -### **TypeScript** - ```ts function threeConsecutiveOdds(arr: number[]): boolean { let cnt = 0; @@ -152,10 +127,21 @@ function threeConsecutiveOdds(arr: number[]): boolean { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def threeConsecutiveOdds(self, arr: List[int]) -> bool: + for i in range(len(arr) - 2): + if arr[i] % 2 + arr[i + 1] % 2 + arr[i + 2] % 2 == 3: + return True + return False ``` + + diff --git a/solution/1500-1599/1550.Three Consecutive Odds/README_EN.md b/solution/1500-1599/1550.Three Consecutive Odds/README_EN.md index 45a2f151bac22..58a244419856d 100644 --- a/solution/1500-1599/1550.Three Consecutive Odds/README_EN.md +++ b/solution/1500-1599/1550.Three Consecutive Odds/README_EN.md @@ -33,9 +33,9 @@ Given an integer array arr, return true if there ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,17 +51,6 @@ class Solution: return False ``` -```python -class Solution: - def threeConsecutiveOdds(self, arr: List[int]) -> bool: - for i in range(len(arr) - 2): - if arr[i] % 2 + arr[i + 1] % 2 + arr[i + 2] % 2 == 3: - return True - return False -``` - -### **Java** - ```java class Solution { public boolean threeConsecutiveOdds(int[] arr) { @@ -81,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +87,6 @@ public: }; ``` -### **Go** - ```go func threeConsecutiveOdds(arr []int) bool { cnt := 0 @@ -119,8 +104,6 @@ func threeConsecutiveOdds(arr []int) bool { } ``` -### **TypeScript** - ```ts function threeConsecutiveOdds(arr: number[]): boolean { let cnt = 0; @@ -138,10 +121,21 @@ function threeConsecutiveOdds(arr: number[]): boolean { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def threeConsecutiveOdds(self, arr: List[int]) -> bool: + for i in range(len(arr) - 2): + if arr[i] % 2 + arr[i + 1] % 2 + arr[i + 2] % 2 == 3: + return True + return False ``` + + diff --git a/solution/1500-1599/1551.Minimum Operations to Make Array Equal/README.md b/solution/1500-1599/1551.Minimum Operations to Make Array Equal/README.md index 582585644d75f..8d5457686fed2 100644 --- a/solution/1500-1599/1551.Minimum Operations to Make Array Equal/README.md +++ b/solution/1500-1599/1551.Minimum Operations to Make Array Equal/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 根据题目描述,数组 $arr$ 是一个首项为 $1$,公差为 $2$ 的等差数列。那么数组前 $n$ 项的和为: @@ -63,20 +61,12 @@ $$ -### **Python3** - - - ```python class Solution: def minOperations(self, n: int) -> int: return sum(n - (i << 1 | 1) for i in range(n >> 1)) ``` -### **Java** - - - ```java class Solution { public int minOperations(int n) { @@ -89,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +92,6 @@ public: }; ``` -### **Go** - ```go func minOperations(n int) (ans int) { for i := 0; i < n>>1; i++ { @@ -115,8 +101,6 @@ func minOperations(n int) (ans int) { } ``` -### **TypeScript** - ```ts function minOperations(n: number): number { let ans = 0; @@ -127,10 +111,6 @@ function minOperations(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1551.Minimum Operations to Make Array Equal/README_EN.md b/solution/1500-1599/1551.Minimum Operations to Make Array Equal/README_EN.md index 748f5e7d54b7c..cef14af5eb9ae 100644 --- a/solution/1500-1599/1551.Minimum Operations to Make Array Equal/README_EN.md +++ b/solution/1500-1599/1551.Minimum Operations to Make Array Equal/README_EN.md @@ -37,7 +37,7 @@ In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3]. ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics According to the problem description, the array $arr$ is an arithmetic sequence with the first term as $1$ and the common difference as $2$. Therefore, the sum of the first $n$ terms of the array is: @@ -59,16 +59,12 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def minOperations(self, n: int) -> int: return sum(n - (i << 1 | 1) for i in range(n >> 1)) ``` -### **Java** - ```java class Solution { public int minOperations(int n) { @@ -81,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +90,6 @@ public: }; ``` -### **Go** - ```go func minOperations(n int) (ans int) { for i := 0; i < n>>1; i++ { @@ -107,8 +99,6 @@ func minOperations(n int) (ans int) { } ``` -### **TypeScript** - ```ts function minOperations(n: number): number { let ans = 0; @@ -119,10 +109,6 @@ function minOperations(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1552.Magnetic Force Between Two Balls/README.md b/solution/1500-1599/1552.Magnetic Force Between Two Balls/README.md index 2234ca46e6e60..5ec273b03d0bd 100644 --- a/solution/1500-1599/1552.Magnetic Force Between Two Balls/README.md +++ b/solution/1500-1599/1552.Magnetic Force Between Two Balls/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 先对 position 进行排序。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def maxDistance(self, position: List[int], m: int) -> int: @@ -82,10 +76,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int maxDistance(int[] position, int m) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func maxDistance(position []int, m int) int { sort.Ints(position) @@ -178,8 +164,6 @@ func maxDistance(position []int, m int) int { } ``` -### **JavaScript** - ```js /** * @param {number[]} position @@ -216,10 +200,6 @@ var maxDistance = function (position, m) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1552.Magnetic Force Between Two Balls/README_EN.md b/solution/1500-1599/1552.Magnetic Force Between Two Balls/README_EN.md index 9e607b308b889..e9cfe9e2c75ae 100644 --- a/solution/1500-1599/1552.Magnetic Force Between Two Balls/README_EN.md +++ b/solution/1500-1599/1552.Magnetic Force Between Two Balls/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { public int maxDistance(int[] position, int m) { @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +130,6 @@ public: }; ``` -### **Go** - ```go func maxDistance(position []int, m int) int { sort.Ints(position) @@ -162,8 +156,6 @@ func maxDistance(position []int, m int) int { } ``` -### **JavaScript** - ```js /** * @param {number[]} position @@ -200,10 +192,6 @@ var maxDistance = function (position, m) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1553.Minimum Number of Days to Eat N Oranges/README.md b/solution/1500-1599/1553.Minimum Number of Days to Eat N Oranges/README.md index efeec4d9c9896..3be0ab5667000 100644 --- a/solution/1500-1599/1553.Minimum Number of Days to Eat N Oranges/README.md +++ b/solution/1500-1599/1553.Minimum Number of Days to Eat N Oranges/README.md @@ -65,16 +65,10 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 -### **Python3** - - - ```python class Solution: def minDays(self, n: int) -> int: @@ -87,10 +81,6 @@ class Solution: return dfs(n) ``` -### **Java** - - - ```java class Solution { private Map f = new HashMap<>(); @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func minDays(n int) int { f := map[int]int{0: 0, 1: 1} @@ -152,10 +138,6 @@ func minDays(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1553.Minimum Number of Days to Eat N Oranges/README_EN.md b/solution/1500-1599/1553.Minimum Number of Days to Eat N Oranges/README_EN.md index 5771f62fb968e..81f5f66a9dc6a 100644 --- a/solution/1500-1599/1553.Minimum Number of Days to Eat N Oranges/README_EN.md +++ b/solution/1500-1599/1553.Minimum Number of Days to Eat N Oranges/README_EN.md @@ -51,9 +51,9 @@ You need at least 3 days to eat the 6 oranges. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return dfs(n) ``` -### **Java** - ```java class Solution { private Map f = new HashMap<>(); @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func minDays(n int) int { f := map[int]int{0: 0, 1: 1} @@ -130,10 +124,6 @@ func minDays(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1554.Strings Differ by One Character/README.md b/solution/1500-1599/1554.Strings Differ by One Character/README.md index 36baa485c439d..62d8fc206290d 100644 --- a/solution/1500-1599/1554.Strings Differ by One Character/README.md +++ b/solution/1500-1599/1554.Strings Differ by One Character/README.md @@ -51,18 +51,10 @@ ## 解法 - - -哈希表。 - -将字符串列表中每个字符串进行处理,比如 `"abcd"` 处理成 `"*bcd"`、`"a*cd"`、`"ab*d"`、`"abc*"` 模式串,依次存入哈希表中。存入之前先判断哈希表中是否已存在该模式串,若是,说明存在两个字符串在相同索引处只有一个字符不同,直接返回 true。否则遍历结束返回 false。 +### 方法一 -### **Python3** - - - ```python class Solution: def differByOne(self, dict: List[str]) -> bool: @@ -76,10 +68,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean differByOne(String[] dict) { @@ -98,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +104,6 @@ public: }; ``` -### **Go** - ```go func differByOne(dict []string) bool { s := make(map[string]bool) @@ -136,10 +120,6 @@ func differByOne(dict []string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1554.Strings Differ by One Character/README_EN.md b/solution/1500-1599/1554.Strings Differ by One Character/README_EN.md index dd6f2b5bbbce8..840d654b0b1b6 100644 --- a/solution/1500-1599/1554.Strings Differ by One Character/README_EN.md +++ b/solution/1500-1599/1554.Strings Differ by One Character/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean differByOne(String[] dict) { @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +99,6 @@ public: }; ``` -### **Go** - ```go func differByOne(dict []string) bool { s := make(map[string]bool) @@ -121,10 +115,6 @@ func differByOne(dict []string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1555.Bank Account Summary/README.md b/solution/1500-1599/1555.Bank Account Summary/README.md index b525c75d3dc9e..12fe659688650 100644 --- a/solution/1500-1599/1555.Bank Account Summary/README.md +++ b/solution/1500-1599/1555.Bank Account Summary/README.md @@ -96,12 +96,10 @@ Luis 未收到任何转账信息,额度 = 800 ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -122,3 +120,5 @@ GROUP BY t.user_id; ``` + + diff --git a/solution/1500-1599/1555.Bank Account Summary/README_EN.md b/solution/1500-1599/1555.Bank Account Summary/README_EN.md index bf83ab6862b14..c5297e31a49b1 100644 --- a/solution/1500-1599/1555.Bank Account Summary/README_EN.md +++ b/solution/1500-1599/1555.Bank Account Summary/README_EN.md @@ -94,9 +94,9 @@ Luis did not received any transfer, credit = 800 ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -118,3 +118,5 @@ GROUP BY t.user_id; ``` + + diff --git a/solution/1500-1599/1556.Thousand Separator/README.md b/solution/1500-1599/1556.Thousand Separator/README.md index c752ea37c1f40..3c1532d34273f 100644 --- a/solution/1500-1599/1556.Thousand Separator/README.md +++ b/solution/1500-1599/1556.Thousand Separator/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 直接按照题目要求模拟即可。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def thousandSeparator(self, n: int) -> str: @@ -75,10 +69,6 @@ class Solution: return ''.join(ans[::-1]) ``` -### **Java** - - - ```java class Solution { public String thousandSeparator(int n) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func thousandSeparator(n int) string { cnt := 0 @@ -152,10 +138,6 @@ func thousandSeparator(n int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1556.Thousand Separator/README_EN.md b/solution/1500-1599/1556.Thousand Separator/README_EN.md index 7f054617d8bc9..409dd38ed35b7 100644 --- a/solution/1500-1599/1556.Thousand Separator/README_EN.md +++ b/solution/1500-1599/1556.Thousand Separator/README_EN.md @@ -30,9 +30,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return ''.join(ans[::-1]) ``` -### **Java** - ```java class Solution { public String thousandSeparator(int n) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +96,6 @@ public: }; ``` -### **Go** - ```go func thousandSeparator(n int) string { cnt := 0 @@ -126,10 +120,6 @@ func thousandSeparator(n int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/README.md b/solution/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/README.md index 4754ce84d9638..8c60bb297ff13 100644 --- a/solution/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/README.md +++ b/solution/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:统计入度为 0 的点** +### 方法一:统计入度为 0 的点 我们注意到,所有入度为 $0$ 的点都一定属于最小点集,因为它们没有任何入边。而由于题目给定的是一张有向无环图,因此所有入度不为 $0$ 的点一定存在一条入边,也即一定能从某个入度为 $0$ 的点出发到达。因此我们只需要找到所有入度为 $0$ 的点即可。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: @@ -66,10 +60,6 @@ class Solution: return [i for i in range(n) if cnt[i] == 0] ``` -### **Java** - - - ```java class Solution { public List findSmallestSetOfVertices(int n, List> edges) { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +97,6 @@ public: }; ``` -### **Go** - ```go func findSmallestSetOfVertices(n int, edges [][]int) (ans []int) { cnt := make([]int, n) @@ -126,8 +112,6 @@ func findSmallestSetOfVertices(n int, edges [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function findSmallestSetOfVertices(n: number, edges: number[][]): number[] { const cnt: number[] = new Array(n).fill(0); @@ -144,8 +128,6 @@ function findSmallestSetOfVertices(n: number, edges: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn find_smallest_set_of_vertices(n: i32, edges: Vec>) -> Vec { @@ -161,10 +143,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/README_EN.md b/solution/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/README_EN.md index e6355f9effa02..3747ea4f8e5f7 100644 --- a/solution/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/README_EN.md +++ b/solution/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return [i for i in range(n) if cnt[i] == 0] ``` -### **Java** - ```java class Solution { public List findSmallestSetOfVertices(int n, List> edges) { @@ -74,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +91,6 @@ public: }; ``` -### **Go** - ```go func findSmallestSetOfVertices(n int, edges [][]int) (ans []int) { cnt := make([]int, n) @@ -112,8 +106,6 @@ func findSmallestSetOfVertices(n int, edges [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function findSmallestSetOfVertices(n: number, edges: number[][]): number[] { const cnt: number[] = new Array(n).fill(0); @@ -130,8 +122,6 @@ function findSmallestSetOfVertices(n: number, edges: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn find_smallest_set_of_vertices(n: i32, edges: Vec>) -> Vec { @@ -147,10 +137,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/README.md b/solution/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/README.md index 17b97c110060f..e194d03a2cb64 100644 --- a/solution/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/README.md +++ b/solution/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/README.md @@ -70,24 +70,16 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minOperations(self, nums: List[int]) -> int: return sum(v.bit_count() for v in nums) + max(0, max(nums).bit_length() - 1) ``` -### **Java** - - - ```java class Solution { public int minOperations(int[] nums) { @@ -103,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +111,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int) int { ans, mx := 0, 0 @@ -144,10 +132,6 @@ func minOperations(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/README_EN.md b/solution/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/README_EN.md index af63ef90d5e31..f65b2b07d94d3 100644 --- a/solution/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/README_EN.md +++ b/solution/1500-1599/1558.Minimum Numbers of Function Calls to Make Target Array/README_EN.md @@ -52,9 +52,9 @@ Total of operations: 2 + 1 = 3. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return sum(v.bit_count() for v in nums) + max(0, max(nums).bit_length() - 1) ``` -### **Java** - ```java class Solution { public int minOperations(int[] nums) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +93,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int) int { ans, mx := 0, 0 @@ -120,10 +114,6 @@ func minOperations(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1559.Detect Cycles in 2D Grid/README.md b/solution/1500-1599/1559.Detect Cycles in 2D Grid/README.md index e41ce2f601ae8..91619d37a113d 100644 --- a/solution/1500-1599/1559.Detect Cycles in 2D Grid/README.md +++ b/solution/1500-1599/1559.Detect Cycles in 2D Grid/README.md @@ -58,81 +58,10 @@ ## 解法 - - -构造并查集,遍历每个坐标 `(i, j)`,如果下方或者右侧的元素 `(x, y)` 与当前元素 `(i, j)` 相同,进行合并操作。若是,若此前两个坐标已经处于连通状态,再进行合并时会形成环,直接返回 true。否则遍历结束返回 false。 - -并查集模板: - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` +### 方法一 -### **Python3** - - - ```python class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: @@ -154,10 +83,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -196,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -229,7 +152,37 @@ public: }; ``` -### **Rust** +```go +func containsCycle(grid [][]byte) bool { + m, n := len(grid), len(grid[0]) + p := make([]int, m*n) + for i := range p { + p[i] = i + } + var find func(x int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + dirs := []int{1, 0, 1} + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + for k := 0; k < 2; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x < m && y < n && grid[x][y] == grid[i][j] { + if find(x*n+y) == find(i*n+j) { + return true + } + p[find(x*n+y)] = find(i*n + j) + } + } + } + } + return false +} +``` ```rust impl Solution { @@ -290,42 +243,6 @@ impl Solution { } ``` -### **Go** - -```go -func containsCycle(grid [][]byte) bool { - m, n := len(grid), len(grid[0]) - p := make([]int, m*n) - for i := range p { - p[i] = i - } - var find func(x int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - dirs := []int{1, 0, 1} - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - for k := 0; k < 2; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x < m && y < n && grid[x][y] == grid[i][j] { - if find(x*n+y) == find(i*n+j) { - return true - } - p[find(x*n+y)] = find(i*n + j) - } - } - } - } - return false -} -``` - -### **JavaScript** - ```js /** * @param {character[][]} grid @@ -360,10 +277,6 @@ var containsCycle = function (grid) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1559.Detect Cycles in 2D Grid/README_EN.md b/solution/1500-1599/1559.Detect Cycles in 2D Grid/README_EN.md index b0e88b6569fe0..7e1270fa1f111 100644 --- a/solution/1500-1599/1559.Detect Cycles in 2D Grid/README_EN.md +++ b/solution/1500-1599/1559.Detect Cycles in 2D Grid/README_EN.md @@ -56,12 +56,10 @@ ## Solutions -Union find. +### Solution 1 -### **Python3** - ```python class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: @@ -83,8 +81,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { private int[] p; @@ -123,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,7 +150,37 @@ public: }; ``` -### **Rust** +```go +func containsCycle(grid [][]byte) bool { + m, n := len(grid), len(grid[0]) + p := make([]int, m*n) + for i := range p { + p[i] = i + } + var find func(x int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + dirs := []int{1, 0, 1} + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + for k := 0; k < 2; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x < m && y < n && grid[x][y] == grid[i][j] { + if find(x*n+y) == find(i*n+j) { + return true + } + p[find(x*n+y)] = find(i*n + j) + } + } + } + } + return false +} +``` ```rust impl Solution { @@ -217,42 +241,6 @@ impl Solution { } ``` -### **Go** - -```go -func containsCycle(grid [][]byte) bool { - m, n := len(grid), len(grid[0]) - p := make([]int, m*n) - for i := range p { - p[i] = i - } - var find func(x int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - dirs := []int{1, 0, 1} - for i := 0; i < m; i++ { - for j := 0; j < n; j++ { - for k := 0; k < 2; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x < m && y < n && grid[x][y] == grid[i][j] { - if find(x*n+y) == find(i*n+j) { - return true - } - p[find(x*n+y)] = find(i*n + j) - } - } - } - } - return false -} -``` - -### **JavaScript** - ```js /** * @param {character[][]} grid @@ -287,10 +275,6 @@ var containsCycle = function (grid) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1560.Most Visited Sector in a Circular Track/README.md b/solution/1500-1599/1560.Most Visited Sector in a Circular Track/README.md index 751cf3848f2fb..93063dcc1052a 100644 --- a/solution/1500-1599/1560.Most Visited Sector in a Circular Track/README.md +++ b/solution/1500-1599/1560.Most Visited Sector in a Circular Track/README.md @@ -50,16 +50,10 @@ ## 解法 - - -**方法一:考虑开始、结束的位置关系** +### 方法一:考虑开始、结束的位置关系 -### **Python3** - - - ```python class Solution: def mostVisited(self, n: int, rounds: List[int]) -> List[int]: @@ -68,10 +62,6 @@ class Solution: return list(range(1, rounds[-1] + 1)) + list(range(rounds[0], n + 1)) ``` -### **Java** - - - ```java class Solution { public List mostVisited(int n, int[] rounds) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func mostVisited(n int, rounds []int) []int { m := len(rounds) - 1 @@ -135,10 +121,6 @@ func mostVisited(n int, rounds []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1560.Most Visited Sector in a Circular Track/README_EN.md b/solution/1500-1599/1560.Most Visited Sector in a Circular Track/README_EN.md index 07a5ff87c3aa6..f48c5c7857bb4 100644 --- a/solution/1500-1599/1560.Most Visited Sector in a Circular Track/README_EN.md +++ b/solution/1500-1599/1560.Most Visited Sector in a Circular Track/README_EN.md @@ -47,9 +47,9 @@ We can see that both sectors 1 and 2 are visited twice and they are the most vis ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return list(range(1, rounds[-1] + 1)) + list(range(rounds[0], n + 1)) ``` -### **Java** - ```java class Solution { public List mostVisited(int n, int[] rounds) { @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +98,6 @@ public: }; ``` -### **Go** - ```go func mostVisited(n int, rounds []int) []int { m := len(rounds) - 1 @@ -124,10 +118,6 @@ func mostVisited(n int, rounds []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1561.Maximum Number of Coins You Can Get/README.md b/solution/1500-1599/1561.Maximum Number of Coins You Can Get/README.md index f8ae5b555709e..5c0f7dc707cff 100644 --- a/solution/1500-1599/1561.Maximum Number of Coins You Can Get/README.md +++ b/solution/1500-1599/1561.Maximum Number of Coins You Can Get/README.md @@ -56,18 +56,12 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 Bob 取走最小的 1/3,剩余的硬币堆由 Alice 和我按硬币数从高到低依次取走每一堆。 -### **Python3** - - - ```python class Solution: def maxCoins(self, piles: List[int]) -> int: @@ -75,10 +69,6 @@ class Solution: return sum(piles[-2 : len(piles) // 3 - 1 : -2]) ``` -### **Java** - - - ```java class Solution { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func maxCoins(piles []int) int { sort.Ints(piles) @@ -120,8 +106,6 @@ func maxCoins(piles []int) int { } ``` -### **TypeScript** - ```ts function maxCoins(piles: number[]): number { piles.sort((a, b) => a - b); @@ -134,8 +118,6 @@ function maxCoins(piles: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_coins(mut piles: Vec) -> i32 { @@ -150,8 +132,6 @@ impl Solution { } ``` -### **C** - ```c int cmp(const void* a, const void* b) { return *(int*) a - *(int*) b; @@ -167,10 +147,6 @@ int maxCoins(int* piles, int pilesSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1561.Maximum Number of Coins You Can Get/README_EN.md b/solution/1500-1599/1561.Maximum Number of Coins You Can Get/README_EN.md index 9bae47cd41a22..48fc5674ae2eb 100644 --- a/solution/1500-1599/1561.Maximum Number of Coins You Can Get/README_EN.md +++ b/solution/1500-1599/1561.Maximum Number of Coins You Can Get/README_EN.md @@ -55,12 +55,10 @@ On the other hand if we choose this arrangement (1, 2, 8), (2, ## Solutions -Greedy. +### Solution 1 -### **Python3** - ```python class Solution: def maxCoins(self, piles: List[int]) -> int: @@ -68,10 +66,9 @@ class Solution: return sum(piles[-2 : len(piles) // 3 - 1 : -2]) ``` -### **Java** - ```java class Solution { + public int maxCoins(int[] piles) { Arrays.sort(piles); int ans = 0; @@ -83,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +92,6 @@ public: }; ``` -### **Go** - ```go func maxCoins(piles []int) int { sort.Ints(piles) @@ -110,8 +103,6 @@ func maxCoins(piles []int) int { } ``` -### **TypeScript** - ```ts function maxCoins(piles: number[]): number { piles.sort((a, b) => a - b); @@ -124,8 +115,6 @@ function maxCoins(piles: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_coins(mut piles: Vec) -> i32 { @@ -140,8 +129,6 @@ impl Solution { } ``` -### **C** - ```c int cmp(const void* a, const void* b) { return *(int*) a - *(int*) b; @@ -157,10 +144,6 @@ int maxCoins(int* piles, int pilesSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1562.Find Latest Group of Size M/README.md b/solution/1500-1599/1562.Find Latest Group of Size M/README.md index f96898d5bf29e..96bc3a86f7077 100644 --- a/solution/1500-1599/1562.Find Latest Group of Size M/README.md +++ b/solution/1500-1599/1562.Find Latest Group of Size M/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:并查集** +### 方法一:并查集 正向遍历 $arr$,利用并查集动态维护每组 $1$ 的长度。 @@ -77,18 +75,8 @@ 相似题目:[2334. 元素值大于变化阈值的子数组](/solution/2300-2399/2334.Subarray%20With%20Elements%20Greater%20Than%20Varying%20Threshold/README.md) -**方法二:动态维护区间端点的长度** - -我们其实并不需要去通过查找并查集来获取每个区间长度,我们只需要在每个区间端点处记录每个区间长度,由于合并的时候**只会访问区间端点**,所以合并区间的时候修改端点区间长度即可。 - -时间复杂度 $O(n)$。 - -### **Python3** - - - ```python class Solution: def findLatestStep(self, arr: List[int], m: int) -> int: @@ -125,27 +113,6 @@ class Solution: return ans ``` -```python -class Solution: - def findLatestStep(self, arr: List[int], m: int) -> int: - n = len(arr) - if m == n: - return n - cnt = [0] * (n + 2) - ans = -1 - for i, v in enumerate(arr): - v -= 1 - l, r = cnt[v - 1], cnt[v + 1] - if l == m or r == m: - ans = i - cnt[v - l] = cnt[v + r] = l + r + 1 - return ans -``` - -### **Java** - - - ```java class Solution { private int[] p; @@ -201,31 +168,6 @@ class Solution { } ``` -```java -class Solution { - public int findLatestStep(int[] arr, int m) { - int n = arr.length; - if (m == n) { - return n; - } - int[] cnt = new int[n + 2]; - int ans = -1; - for (int i = 0; i < n; ++i) { - int v = arr[i]; - int l = cnt[v - 1], r = cnt[v + 1]; - if (l == m || r == m) { - ans = i; - } - cnt[v - l] = l + r + 1; - cnt[v + r] = l + r + 1; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -269,27 +211,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findLatestStep(vector& arr, int m) { - int n = arr.size(); - if (m == n) return n; - vector cnt(n + 2); - int ans = -1; - for (int i = 0; i < n; ++i) { - int v = arr[i]; - int l = cnt[v - 1], r = cnt[v + 1]; - if (l == m || r == m) ans = i; - cnt[v - l] = cnt[v + r] = l + r + 1; - } - return ans; - } -}; -``` - -### **Go** - ```go func findLatestStep(arr []int, m int) int { n := len(arr) @@ -340,6 +261,75 @@ func findLatestStep(arr []int, m int) int { } ``` + + +### 方法二:动态维护区间端点的长度 + +我们其实并不需要去通过查找并查集来获取每个区间长度,我们只需要在每个区间端点处记录每个区间长度,由于合并的时候**只会访问区间端点**,所以合并区间的时候修改端点区间长度即可。 + +时间复杂度 $O(n)$。 + + + +```python +class Solution: + def findLatestStep(self, arr: List[int], m: int) -> int: + n = len(arr) + if m == n: + return n + cnt = [0] * (n + 2) + ans = -1 + for i, v in enumerate(arr): + v -= 1 + l, r = cnt[v - 1], cnt[v + 1] + if l == m or r == m: + ans = i + cnt[v - l] = cnt[v + r] = l + r + 1 + return ans +``` + +```java +class Solution { + public int findLatestStep(int[] arr, int m) { + int n = arr.length; + if (m == n) { + return n; + } + int[] cnt = new int[n + 2]; + int ans = -1; + for (int i = 0; i < n; ++i) { + int v = arr[i]; + int l = cnt[v - 1], r = cnt[v + 1]; + if (l == m || r == m) { + ans = i; + } + cnt[v - l] = l + r + 1; + cnt[v + r] = l + r + 1; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int findLatestStep(vector& arr, int m) { + int n = arr.size(); + if (m == n) return n; + vector cnt(n + 2); + int ans = -1; + for (int i = 0; i < n; ++i) { + int v = arr[i]; + int l = cnt[v - 1], r = cnt[v + 1]; + if (l == m || r == m) ans = i; + cnt[v - l] = cnt[v + r] = l + r + 1; + } + return ans; + } +}; +``` + ```go func findLatestStep(arr []int, m int) int { n := len(arr) @@ -359,10 +349,6 @@ func findLatestStep(arr []int, m int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1562.Find Latest Group of Size M/README_EN.md b/solution/1500-1599/1562.Find Latest Group of Size M/README_EN.md index 51ae4052c9f44..6f05c247b78b2 100644 --- a/solution/1500-1599/1562.Find Latest Group of Size M/README_EN.md +++ b/solution/1500-1599/1562.Find Latest Group of Size M/README_EN.md @@ -53,9 +53,9 @@ No group of size 2 exists during any step. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -93,25 +93,6 @@ class Solution: return ans ``` -```python -class Solution: - def findLatestStep(self, arr: List[int], m: int) -> int: - n = len(arr) - if m == n: - return n - cnt = [0] * (n + 2) - ans = -1 - for i, v in enumerate(arr): - v -= 1 - l, r = cnt[v - 1], cnt[v + 1] - if l == m or r == m: - ans = i - cnt[v - l] = cnt[v + r] = l + r + 1 - return ans -``` - -### **Java** - ```java class Solution { private int[] p; @@ -167,31 +148,6 @@ class Solution { } ``` -```java -class Solution { - public int findLatestStep(int[] arr, int m) { - int n = arr.length; - if (m == n) { - return n; - } - int[] cnt = new int[n + 2]; - int ans = -1; - for (int i = 0; i < n; ++i) { - int v = arr[i]; - int l = cnt[v - 1], r = cnt[v + 1]; - if (l == m || r == m) { - ans = i; - } - cnt[v - l] = l + r + 1; - cnt[v + r] = l + r + 1; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -235,27 +191,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findLatestStep(vector& arr, int m) { - int n = arr.size(); - if (m == n) return n; - vector cnt(n + 2); - int ans = -1; - for (int i = 0; i < n; ++i) { - int v = arr[i]; - int l = cnt[v - 1], r = cnt[v + 1]; - if (l == m || r == m) ans = i; - cnt[v - l] = cnt[v + r] = l + r + 1; - } - return ans; - } -}; -``` - -### **Go** - ```go func findLatestStep(arr []int, m int) int { n := len(arr) @@ -306,6 +241,71 @@ func findLatestStep(arr []int, m int) int { } ``` + + +### Solution 2 + + + +```python +class Solution: + def findLatestStep(self, arr: List[int], m: int) -> int: + n = len(arr) + if m == n: + return n + cnt = [0] * (n + 2) + ans = -1 + for i, v in enumerate(arr): + v -= 1 + l, r = cnt[v - 1], cnt[v + 1] + if l == m or r == m: + ans = i + cnt[v - l] = cnt[v + r] = l + r + 1 + return ans +``` + +```java +class Solution { + public int findLatestStep(int[] arr, int m) { + int n = arr.length; + if (m == n) { + return n; + } + int[] cnt = new int[n + 2]; + int ans = -1; + for (int i = 0; i < n; ++i) { + int v = arr[i]; + int l = cnt[v - 1], r = cnt[v + 1]; + if (l == m || r == m) { + ans = i; + } + cnt[v - l] = l + r + 1; + cnt[v + r] = l + r + 1; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int findLatestStep(vector& arr, int m) { + int n = arr.size(); + if (m == n) return n; + vector cnt(n + 2); + int ans = -1; + for (int i = 0; i < n; ++i) { + int v = arr[i]; + int l = cnt[v - 1], r = cnt[v + 1]; + if (l == m || r == m) ans = i; + cnt[v - l] = cnt[v + r] = l + r + 1; + } + return ans; + } +}; +``` + ```go func findLatestStep(arr []int, m int) int { n := len(arr) @@ -325,10 +325,6 @@ func findLatestStep(arr []int, m int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1563.Stone Game V/README.md b/solution/1500-1599/1563.Stone Game V/README.md index d74f9a9981311..da4803839b72d 100644 --- a/solution/1500-1599/1563.Stone Game V/README.md +++ b/solution/1500-1599/1563.Stone Game V/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:记忆化搜索 + 剪枝** +### 方法一:记忆化搜索 + 剪枝 我们先预处理出前缀和数组 $s$,其中 $s[i]$ 表示数组 $stoneValue$ 前 $i$ 个元素的和。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def stoneGameV(self, stoneValue: List[int]) -> int: @@ -102,10 +96,6 @@ class Solution: return dfs(0, len(stoneValue) - 1) ``` -### **Java** - - - ```java class Solution { private int n; @@ -155,8 +145,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -202,8 +190,6 @@ public: }; ``` -### **Go** - ```go func stoneGameV(stoneValue []int) int { n := len(stoneValue) @@ -248,10 +234,6 @@ func stoneGameV(stoneValue []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1563.Stone Game V/README_EN.md b/solution/1500-1599/1563.Stone Game V/README_EN.md index b09c07c5fada1..0d43fe2174fe9 100644 --- a/solution/1500-1599/1563.Stone Game V/README_EN.md +++ b/solution/1500-1599/1563.Stone Game V/README_EN.md @@ -47,9 +47,9 @@ The last round Alice has only one choice to divide the row which is [2], [3]. Bo ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,8 +78,6 @@ class Solution: return dfs(0, len(stoneValue) - 1) ``` -### **Java** - ```java class Solution { private int n; @@ -129,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +172,6 @@ public: }; ``` -### **Go** - ```go func stoneGameV(stoneValue []int) int { n := len(stoneValue) @@ -222,10 +216,6 @@ func stoneGameV(stoneValue []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1564.Put Boxes Into the Warehouse I/README.md b/solution/1500-1599/1564.Put Boxes Into the Warehouse I/README.md index 8c010e32dda3a..25aac8768107a 100644 --- a/solution/1500-1599/1564.Put Boxes Into the Warehouse I/README.md +++ b/solution/1500-1599/1564.Put Boxes Into the Warehouse I/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:预处理 + 排序 + 双指针** +### 方法一:预处理 + 排序 + 双指针 我们可以先对仓库的房间进行预处理,得到一个数组 $left$,其中 $left[i]$ 表示下标 $i$ 可以放入的最大箱子高度。 @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def maxBoxesInWarehouse(self, boxes: List[int], warehouse: List[int]) -> int: @@ -103,10 +97,6 @@ class Solution: return i ``` -### **Java** - - - ```java class Solution { public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go func maxBoxesInWarehouse(boxes []int, warehouse []int) int { n := len(warehouse) @@ -187,8 +173,6 @@ func maxBoxesInWarehouse(boxes []int, warehouse []int) int { } ``` -### **TypeScript** - ```ts function maxBoxesInWarehouse(boxes: number[], warehouse: number[]): number { const n = warehouse.length; @@ -214,10 +198,6 @@ function maxBoxesInWarehouse(boxes: number[], warehouse: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1564.Put Boxes Into the Warehouse I/README_EN.md b/solution/1500-1599/1564.Put Boxes Into the Warehouse I/README_EN.md index a71da9adecb67..b97ca915ea821 100644 --- a/solution/1500-1599/1564.Put Boxes Into the Warehouse I/README_EN.md +++ b/solution/1500-1599/1564.Put Boxes Into the Warehouse I/README_EN.md @@ -61,9 +61,9 @@ Swapping the orange and green boxes is also valid, or swapping one of them with ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,8 +83,6 @@ class Solution: return i ``` -### **Java** - ```java class Solution { public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) { @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +136,6 @@ public: }; ``` -### **Go** - ```go func maxBoxesInWarehouse(boxes []int, warehouse []int) int { n := len(warehouse) @@ -165,8 +159,6 @@ func maxBoxesInWarehouse(boxes []int, warehouse []int) int { } ``` -### **TypeScript** - ```ts function maxBoxesInWarehouse(boxes: number[], warehouse: number[]): number { const n = warehouse.length; @@ -192,10 +184,6 @@ function maxBoxesInWarehouse(boxes: number[], warehouse: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1565.Unique Orders and Customers Per Month/README.md b/solution/1500-1599/1565.Unique Orders and Customers Per Month/README.md index 4ed179e799b42..e8434604da076 100644 --- a/solution/1500-1599/1565.Unique Orders and Customers Per Month/README.md +++ b/solution/1500-1599/1565.Unique Orders and Customers Per Month/README.md @@ -68,12 +68,10 @@ Orders ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -86,3 +84,5 @@ GROUP BY month; ``` + + diff --git a/solution/1500-1599/1565.Unique Orders and Customers Per Month/README_EN.md b/solution/1500-1599/1565.Unique Orders and Customers Per Month/README_EN.md index c2eac8e472a04..1b8af0d8251a6 100644 --- a/solution/1500-1599/1565.Unique Orders and Customers Per Month/README_EN.md +++ b/solution/1500-1599/1565.Unique Orders and Customers Per Month/README_EN.md @@ -66,9 +66,9 @@ In January 2021 we have two orders from 2 different customers, but only one of t ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -82,3 +82,5 @@ GROUP BY month; ``` + + diff --git a/solution/1500-1599/1566.Detect Pattern of Length M Repeated K or More Times/README.md b/solution/1500-1599/1566.Detect Pattern of Length M Repeated K or More Times/README.md index 7f1e38e06cdf8..6a21cb8dd5c74 100644 --- a/solution/1500-1599/1566.Detect Pattern of Length M Repeated K or More Times/README.md +++ b/solution/1500-1599/1566.Detect Pattern of Length M Repeated K or More Times/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 枚举数组的左端点 `i`,判断是否存在一个 `i`,满足对于任意 `j∈[0, m * k)`,`arr[i + j] == arr[i + (j % m)]`。存在则返回 `true`,否则返回 `false`。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def containsPattern(self, arr: List[int], m: int, k: int) -> bool: @@ -91,10 +85,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean containsPattern(int[] arr, int m, int k) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func containsPattern(arr []int, m int, k int) bool { n := len(arr) @@ -158,8 +144,6 @@ func containsPattern(arr []int, m int, k int) bool { } ``` -### **TypeScript** - ```ts function containsPattern(arr: number[], m: number, k: number): boolean { const n = arr.length; @@ -178,10 +162,6 @@ function containsPattern(arr: number[], m: number, k: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1566.Detect Pattern of Length M Repeated K or More Times/README_EN.md b/solution/1500-1599/1566.Detect Pattern of Length M Repeated K or More Times/README_EN.md index 4834b77d83800..3695ca9d4f533 100644 --- a/solution/1500-1599/1566.Detect Pattern of Length M Repeated K or More Times/README_EN.md +++ b/solution/1500-1599/1566.Detect Pattern of Length M Repeated K or More Times/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean containsPattern(int[] arr, int m, int k) { @@ -88,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +107,6 @@ public: }; ``` -### **Go** - ```go func containsPattern(arr []int, m int, k int) bool { n := len(arr) @@ -131,8 +125,6 @@ func containsPattern(arr []int, m int, k int) bool { } ``` -### **TypeScript** - ```ts function containsPattern(arr: number[], m: number, k: number): boolean { const n = arr.length; @@ -151,10 +143,6 @@ function containsPattern(arr: number[], m: number, k: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1567.Maximum Length of Subarray With Positive Product/README.md b/solution/1500-1599/1567.Maximum Length of Subarray With Positive Product/README.md index c1be22b101d72..7022b981df5e5 100644 --- a/solution/1500-1599/1567.Maximum Length of Subarray With Positive Product/README.md +++ b/solution/1500-1599/1567.Maximum Length of Subarray With Positive Product/README.md @@ -51,14 +51,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def getMaxLen(self, nums: List[int]) -> int: @@ -87,10 +83,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int getMaxLen(int[] nums) { @@ -116,35 +108,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function getMaxLen(nums: number[]): number { - // 连续正数计数n1, 连续负数计数n2 - let n1 = nums[0] > 0 ? 1 : 0, - n2 = nums[0] < 0 ? 1 : 0; - let ans = n1; - for (let i = 1; i < nums.length; ++i) { - let cur = nums[i]; - if (cur == 0) { - (n1 = 0), (n2 = 0); - } else if (cur > 0) { - ++n1; - n2 = n2 > 0 ? n2 + 1 : 0; - } else { - let t1 = n1, - t2 = n2; - n1 = t2 > 0 ? t2 + 1 : 0; - n2 = t1 + 1; - } - ans = Math.max(ans, n1); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -171,8 +134,6 @@ public: }; ``` -### **Go** - ```go func getMaxLen(nums []int) int { f1, f2 := 0, 0 @@ -208,10 +169,31 @@ func getMaxLen(nums []int) int { } ``` -### **...** - -``` - +```ts +function getMaxLen(nums: number[]): number { + // 连续正数计数n1, 连续负数计数n2 + let n1 = nums[0] > 0 ? 1 : 0, + n2 = nums[0] < 0 ? 1 : 0; + let ans = n1; + for (let i = 1; i < nums.length; ++i) { + let cur = nums[i]; + if (cur == 0) { + (n1 = 0), (n2 = 0); + } else if (cur > 0) { + ++n1; + n2 = n2 > 0 ? n2 + 1 : 0; + } else { + let t1 = n1, + t2 = n2; + n1 = t2 > 0 ? t2 + 1 : 0; + n2 = t1 + 1; + } + ans = Math.max(ans, n1); + } + return ans; +} ``` + + diff --git a/solution/1500-1599/1567.Maximum Length of Subarray With Positive Product/README_EN.md b/solution/1500-1599/1567.Maximum Length of Subarray With Positive Product/README_EN.md index 9128cdb7cc191..044b8df3c77d9 100644 --- a/solution/1500-1599/1567.Maximum Length of Subarray With Positive Product/README_EN.md +++ b/solution/1500-1599/1567.Maximum Length of Subarray With Positive Product/README_EN.md @@ -45,9 +45,9 @@ Notice that we cannot include 0 in the subarray since that'll make the produ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public int getMaxLen(int[] nums) { @@ -104,35 +102,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function getMaxLen(nums: number[]): number { - // 连续正数计数n1, 连续负数计数n2 - let n1 = nums[0] > 0 ? 1 : 0, - n2 = nums[0] < 0 ? 1 : 0; - let ans = n1; - for (let i = 1; i < nums.length; ++i) { - let cur = nums[i]; - if (cur == 0) { - (n1 = 0), (n2 = 0); - } else if (cur > 0) { - ++n1; - n2 = n2 > 0 ? n2 + 1 : 0; - } else { - let t1 = n1, - t2 = n2; - n1 = t2 > 0 ? t2 + 1 : 0; - n2 = t1 + 1; - } - ans = Math.max(ans, n1); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -159,8 +128,6 @@ public: }; ``` -### **Go** - ```go func getMaxLen(nums []int) int { f1, f2 := 0, 0 @@ -196,10 +163,31 @@ func getMaxLen(nums []int) int { } ``` -### **...** - -``` - +```ts +function getMaxLen(nums: number[]): number { + // 连续正数计数n1, 连续负数计数n2 + let n1 = nums[0] > 0 ? 1 : 0, + n2 = nums[0] < 0 ? 1 : 0; + let ans = n1; + for (let i = 1; i < nums.length; ++i) { + let cur = nums[i]; + if (cur == 0) { + (n1 = 0), (n2 = 0); + } else if (cur > 0) { + ++n1; + n2 = n2 > 0 ? n2 + 1 : 0; + } else { + let t1 = n1, + t2 = n2; + n1 = t2 > 0 ? t2 + 1 : 0; + n2 = t1 + 1; + } + ans = Math.max(ans, n1); + } + return ans; +} ``` + + diff --git a/solution/1500-1599/1568.Minimum Number of Days to Disconnect Island/README.md b/solution/1500-1599/1568.Minimum Number of Days to Disconnect Island/README.md index cad505599dcbd..38bbb6f2e15d5 100644 --- a/solution/1500-1599/1568.Minimum Number of Days to Disconnect Island/README.md +++ b/solution/1500-1599/1568.Minimum Number of Days to Disconnect Island/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 观察发现,我们总是可以通过把角落相邻的两个陆地变成水,使得岛屿分离。因此,答案只可能是 0,1 或 2。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def minDays(self, grid: List[List[int]]) -> int: @@ -102,10 +96,6 @@ class Solution: return cnt ``` -### **Java** - - - ```java class Solution { private static final int[] DIRS = new int[] {-1, 0, 1, 0, -1}; @@ -166,8 +156,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -225,8 +213,6 @@ public: }; ``` -### **Go** - ```go func minDays(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -281,10 +267,6 @@ func minDays(grid [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1568.Minimum Number of Days to Disconnect Island/README_EN.md b/solution/1500-1599/1568.Minimum Number of Days to Disconnect Island/README_EN.md index bcae62cf60736..5c3413c2e5573 100644 --- a/solution/1500-1599/1568.Minimum Number of Days to Disconnect Island/README_EN.md +++ b/solution/1500-1599/1568.Minimum Number of Days to Disconnect Island/README_EN.md @@ -44,9 +44,9 @@ Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -85,8 +85,6 @@ class Solution: return cnt ``` -### **Java** - ```java class Solution { private static final int[] DIRS = new int[] {-1, 0, 1, 0, -1}; @@ -147,8 +145,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -206,8 +202,6 @@ public: }; ``` -### **Go** - ```go func minDays(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -262,10 +256,6 @@ func minDays(grid [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/README.md b/solution/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/README.md index ae6d2b25309b6..5ee7c80fe6a6d 100644 --- a/solution/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/README.md +++ b/solution/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:组合计数 + 递归** +### 方法一:组合计数 + 递归 我们设计一个函数 $dfs(nums)$,它的功能是计算以 $nums$ 为节点构成的二叉搜索树的方案数。那么答案就是 $dfs(nums)-1$,因为 $dfs(nums)$ 计算的是以 $nums$ 为节点构成的二叉搜索树的方案数,而题目要求的是重排后与原数组 $nums$ 得到相同二叉搜索树的方案数,因此答案需要减去一。 @@ -85,10 +83,6 @@ $$ -### **Python3** - - - ```python class Solution: def numOfWays(self, nums: List[int]) -> int: @@ -112,10 +106,6 @@ class Solution: return (dfs(nums) - 1 + mod) % mod ``` -### **Java** - - - ```java class Solution { private int[][] c; @@ -158,8 +148,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -196,8 +184,6 @@ public: }; ``` -### **Go** - ```go func numOfWays(nums []int) int { n := len(nums) @@ -234,8 +220,6 @@ func numOfWays(nums []int) int { } ``` -### **TypeScript** - ```ts function numOfWays(nums: number[]): number { const n = nums.length; @@ -271,10 +255,6 @@ function numOfWays(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/README_EN.md b/solution/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/README_EN.md index d4e1eda1e3eef..906d61e81642e 100644 --- a/solution/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/README_EN.md +++ b/solution/1500-1599/1569.Number of Ways to Reorder Array to Get Same BST/README_EN.md @@ -55,7 +55,7 @@ ## Solutions -**Solution 1: Combination Counting + Recursion** +### Solution 1: Combination Counting + Recursion We design a function $dfs(nums)$, which is used to calculate the number of solutions of the binary search tree with $nums$ as nodes. Then the answer is $dfs(nums)-1$, because $dfs(nums)$ calculates the number of solutions of the binary search tree with $nums$ as nodes, while the problem requires the number of solutions of the binary search tree with $nums$ as nodes after reordering, so the answer needs to be subtracted by one. @@ -75,8 +75,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ -### **Python3** - ```python class Solution: def numOfWays(self, nums: List[int]) -> int: @@ -100,8 +98,6 @@ class Solution: return (dfs(nums) - 1 + mod) % mod ``` -### **Java** - ```java class Solution { private int[][] c; @@ -144,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +176,6 @@ public: }; ``` -### **Go** - ```go func numOfWays(nums []int) int { n := len(nums) @@ -220,8 +212,6 @@ func numOfWays(nums []int) int { } ``` -### **TypeScript** - ```ts function numOfWays(nums: number[]): number { const n = nums.length; @@ -257,10 +247,6 @@ function numOfWays(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/README.md b/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/README.md index b3811e33ec015..4fc1625358c5e 100644 --- a/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/README.md +++ b/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/README.md @@ -58,9 +58,7 @@ v1.dotProduct(v2) = 0*0 + 1*0 + 0*0 + 0*0 + 0*2 = 0 ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们用哈希表 $d$ 来存储非零元素,其中键为下标,值为对应的值。我们遍历 $nums$,如果 $nums[i]$ 不为 $0$,我们就将 $(i, nums[i])$ 加入到哈希表 $d$ 中。 @@ -70,10 +68,6 @@ v1.dotProduct(v2) = 0*0 + 1*0 + 0*0 + 0*0 + 0*2 = 0 -### **Python3** - - - ```python class SparseVector: def __init__(self, nums: List[int]): @@ -93,10 +87,6 @@ class SparseVector: # ans = v1.dotProduct(v2) ``` -### **Java** - - - ```java class SparseVector { public Map d = new HashMap<>(128); @@ -133,8 +123,6 @@ class SparseVector { // int ans = v1.dotProduct(v2); ``` -### **C++** - ```cpp class SparseVector { public: @@ -171,8 +159,6 @@ public: // int ans = v1.dotProduct(v2); ``` -### **Go** - ```go type SparseVector struct { d map[int]int @@ -210,8 +196,6 @@ func (this *SparseVector) dotProduct(vec SparseVector) (ans int) { */ ``` -### **TypeScript** - ```ts class SparseVector { d: Map; @@ -250,10 +234,6 @@ class SparseVector { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/README_EN.md b/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/README_EN.md index 02588a2a055d3..7bbd9109b9108 100644 --- a/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/README_EN.md +++ b/solution/1500-1599/1570.Dot Product of Two Sparse Vectors/README_EN.md @@ -54,9 +54,9 @@ v1.dotProduct(v2) = 0*0 + 1*0 + 0*0 + 0*0 + 0*2 = 0 ## Solutions - +### Solution 1 -### **Python3** + ```python class SparseVector: @@ -77,8 +77,6 @@ class SparseVector: # ans = v1.dotProduct(v2) ``` -### **Java** - ```java class SparseVector { public Map d = new HashMap<>(128); @@ -115,8 +113,6 @@ class SparseVector { // int ans = v1.dotProduct(v2); ``` -### **C++** - ```cpp class SparseVector { public: @@ -153,8 +149,6 @@ public: // int ans = v1.dotProduct(v2); ``` -### **Go** - ```go type SparseVector struct { d map[int]int @@ -192,8 +186,6 @@ func (this *SparseVector) dotProduct(vec SparseVector) (ans int) { */ ``` -### **TypeScript** - ```ts class SparseVector { d: Map; @@ -232,10 +224,6 @@ class SparseVector { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1571.Warehouse Manager/README.md b/solution/1500-1599/1571.Warehouse Manager/README.md index a575384b4b57c..7575aecc63a27 100644 --- a/solution/1500-1599/1571.Warehouse Manager/README.md +++ b/solution/1500-1599/1571.Warehouse Manager/README.md @@ -94,16 +94,12 @@ Id为4的商品(LC-T-Shirt)的存货量为 4x10x20 = 800 ## 解法 - - -**方法一:等值连接 + 分组求和** +### 方法一:等值连接 + 分组求和 我们可以使用等值连接将 `Warehouse` 表和 `Products` 表按照 `product_id` 进行连接,并按照仓库名称进行分组,然后使用 `SUM` 函数计算每个仓库的存货量。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -116,3 +112,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1500-1599/1571.Warehouse Manager/README_EN.md b/solution/1500-1599/1571.Warehouse Manager/README_EN.md index 79b265bc69d90..72275b2ef64b5 100644 --- a/solution/1500-1599/1571.Warehouse Manager/README_EN.md +++ b/solution/1500-1599/1571.Warehouse Manager/README_EN.md @@ -92,14 +92,12 @@ LCHouse3: 1 unit of LC-T-Shirt. ## Solutions -**Solution 1: Inner Join + Group By + Sum Function** +### Solution 1: Inner Join + Group By + Sum Function We can use an inner join to join the `Warehouse` table and the `Products` table on the condition of `product_id`, and then group by warehouse name to calculate the inventory of each warehouse using the `SUM` function. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -112,3 +110,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1500-1599/1572.Matrix Diagonal Sum/README.md b/solution/1500-1599/1572.Matrix Diagonal Sum/README.md index 536fd8cf0fbcf..805a3361fffd5 100644 --- a/solution/1500-1599/1572.Matrix Diagonal Sum/README.md +++ b/solution/1500-1599/1572.Matrix Diagonal Sum/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:逐行遍历** +### 方法一:逐行遍历 我们可以遍历矩阵的每一行 $row[i]$,对于每一行,我们可以计算出两个对角线上的元素,即 $row[i][i]$ 和 $row[i][n - i - 1]$,其中 $n$ 是矩阵的行数。如果 $i = n - i - 1$,则说明当前行的对角线上只有一个元素,否则有两个元素。我们将其加到答案中即可。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def diagonalSum(self, mat: List[List[int]]) -> int: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int diagonalSum(int[][] mat) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func diagonalSum(mat [][]int) (ans int) { n := len(mat) @@ -131,8 +117,6 @@ func diagonalSum(mat [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function diagonalSum(mat: number[][]): number { let ans = 0; @@ -145,22 +129,6 @@ function diagonalSum(mat: number[][]): number { } ``` -```ts -function diagonalSum(mat: number[][]): number { - const n = mat.length; - let ans = 0; - for (let i = 0; i < n; i++) { - ans += mat[i][i] + mat[i][n - 1 - i]; - } - if (n & 1) { - ans -= mat[n >> 1][n >> 1]; - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn diagonal_sum(mat: Vec>) -> i32 { @@ -177,8 +145,6 @@ impl Solution { } ``` -### **C** - ```c int diagonalSum(int** mat, int matSize, int* matColSize) { int ans = 0; @@ -192,10 +158,26 @@ int diagonalSum(int** mat, int matSize, int* matColSize) { } ``` -### **...** + -``` +### 方法二 + + +```ts +function diagonalSum(mat: number[][]): number { + const n = mat.length; + let ans = 0; + for (let i = 0; i < n; i++) { + ans += mat[i][i] + mat[i][n - 1 - i]; + } + if (n & 1) { + ans -= mat[n >> 1][n >> 1]; + } + return ans; +} ``` + + diff --git a/solution/1500-1599/1572.Matrix Diagonal Sum/README_EN.md b/solution/1500-1599/1572.Matrix Diagonal Sum/README_EN.md index c087ba33fff53..ed984202eefed 100644 --- a/solution/1500-1599/1572.Matrix Diagonal Sum/README_EN.md +++ b/solution/1500-1599/1572.Matrix Diagonal Sum/README_EN.md @@ -48,9 +48,9 @@ Notice that element mat[1][1] = 5 is counted only once. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int diagonalSum(int[][] mat) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func diagonalSum(mat [][]int) (ans int) { n := len(mat) @@ -111,8 +105,6 @@ func diagonalSum(mat [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function diagonalSum(mat: number[][]): number { let ans = 0; @@ -125,22 +117,6 @@ function diagonalSum(mat: number[][]): number { } ``` -```ts -function diagonalSum(mat: number[][]): number { - const n = mat.length; - let ans = 0; - for (let i = 0; i < n; i++) { - ans += mat[i][i] + mat[i][n - 1 - i]; - } - if (n & 1) { - ans -= mat[n >> 1][n >> 1]; - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn diagonal_sum(mat: Vec>) -> i32 { @@ -157,8 +133,6 @@ impl Solution { } ``` -### **C** - ```c int diagonalSum(int** mat, int matSize, int* matColSize) { int ans = 0; @@ -172,10 +146,26 @@ int diagonalSum(int** mat, int matSize, int* matColSize) { } ``` -### **...** + -``` +### Solution 2 + + +```ts +function diagonalSum(mat: number[][]): number { + const n = mat.length; + let ans = 0; + for (let i = 0; i < n; i++) { + ans += mat[i][i] + mat[i][n - 1 - i]; + } + if (n & 1) { + ans -= mat[n >> 1][n >> 1]; + } + return ans; +} ``` + + diff --git a/solution/1500-1599/1573.Number of Ways to Split a String/README.md b/solution/1500-1599/1573.Number of Ways to Split a String/README.md index 886e8646e4dd6..afecdf1f846e2 100644 --- a/solution/1500-1599/1573.Number of Ways to Split a String/README.md +++ b/solution/1500-1599/1573.Number of Ways to Split a String/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们先遍历字符串 $s$,统计其中字符 $1$ 的个数 $cnt$,如果 $cnt$ 不能被 $3$ 整除,那么无法分割,直接返回 $0$。如果 $cnt$ 为 $0$,说明字符串中没有字符 $1$,我们可以在 $n-1$ 个位置中任意选择两个位置,将字符串分割成三个子串,那么方案数就是 $C_{n-1}^2$。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def numWays(self, s: str) -> int: @@ -104,10 +98,6 @@ class Solution: return (i2 - i1) * (j2 - j1) % (10**9 + 7) ``` -### **Java** - - - ```java class Solution { private String s; @@ -147,8 +137,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -183,8 +171,6 @@ public: }; ``` -### **Go** - ```go func numWays(s string) int { cnt := 0 @@ -220,10 +206,6 @@ func numWays(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1573.Number of Ways to Split a String/README_EN.md b/solution/1500-1599/1573.Number of Ways to Split a String/README_EN.md index e665c9d47c697..c9de012e1e229 100644 --- a/solution/1500-1599/1573.Number of Ways to Split a String/README_EN.md +++ b/solution/1500-1599/1573.Number of Ways to Split a String/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return (i2 - i1) * (j2 - j1) % (10**9 + 7) ``` -### **Java** - ```java class Solution { private String s; @@ -116,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +148,6 @@ public: }; ``` -### **Go** - ```go func numWays(s string) int { cnt := 0 @@ -189,10 +183,6 @@ func numWays(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/README.md b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/README.md index 7693700c89553..f1f0dd41e1426 100644 --- a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/README.md +++ b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:双指针 + 二分查找** +### 方法一:双指针 + 二分查找 我们先找出数组的最长非递减前缀和最长非递减后缀,分别记为 $nums[0..i]$ 和 $nums[j..n-1]$。 @@ -70,24 +68,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(1)$。其中 $n$ 为数组长度。 -**方法二:双指针** - -与方法一类似,我们先找出数组的最长非递减前缀和最长非递减后缀,分别记为 $nums[0..i]$ 和 $nums[j..n-1]$。 - -如果 $i \geq j$,说明数组本身就是非递减的,返回 $0$。 - -否则,我们可以选择删除右侧后缀,也可以选择删除左侧前缀,因此初始时答案为 $min(n - i - 1, j)$。 - -接下来,我们枚举左侧前缀的最右端点 $l$,对于每个 $l$,我们直接利用双指针找到第一个大于等于 $nums[l]$ 的位置,记为 $r$,此时我们可以删除 $nums[l+1..r-1]$,并且更新答案 $ans = min(ans, r - l - 1)$。继续枚举 $l$,最终得到答案。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组长度。 - -### **Python3** - - - ```python class Solution: def findLengthOfShortestSubarray(self, arr: List[int]) -> int: @@ -106,30 +88,6 @@ class Solution: return ans ``` -```python -class Solution: - def findLengthOfShortestSubarray(self, arr: List[int]) -> int: - n = len(arr) - i, j = 0, n - 1 - while i + 1 < n and arr[i] <= arr[i + 1]: - i += 1 - while j - 1 >= 0 and arr[j - 1] <= arr[j]: - j -= 1 - if i >= j: - return 0 - ans = min(n - i - 1, j) - r = j - for l in range(i + 1): - while r < n and arr[r] < arr[l]: - r += 1 - ans = min(ans, r - l - 1) - return ans -``` - -### **Java** - - - ```java class Solution { public int findLengthOfShortestSubarray(int[] arr) { @@ -167,10 +125,11 @@ class Solution { } ``` -```java +```cpp class Solution { - public int findLengthOfShortestSubarray(int[] arr) { - int n = arr.length; +public: + int findLengthOfShortestSubarray(vector& arr) { + int n = arr.size(); int i = 0, j = n - 1; while (i + 1 < n && arr[i] <= arr[i + 1]) { ++i; @@ -181,25 +140,78 @@ class Solution { if (i >= j) { return 0; } - int ans = Math.min(n - i - 1, j); - for (int l = 0, r = j; l <= i; ++l) { - while (r < n && arr[r] < arr[l]) { - ++r; - } - ans = Math.min(ans, r - l - 1); + int ans = min(n - 1 - i, j); + for (int l = 0; l <= i; ++l) { + int r = lower_bound(arr.begin() + j, arr.end(), arr[l]) - arr.begin(); + ans = min(ans, r - l - 1); } return ans; } +}; +``` + +```go +func findLengthOfShortestSubarray(arr []int) int { + n := len(arr) + i, j := 0, n-1 + for i+1 < n && arr[i] <= arr[i+1] { + i++ + } + for j-1 >= 0 && arr[j-1] <= arr[j] { + j-- + } + if i >= j { + return 0 + } + ans := min(n-i-1, j) + for l := 0; l <= i; l++ { + r := j + sort.SearchInts(arr[j:], arr[l]) + ans = min(ans, r-l-1) + } + return ans } ``` -### **C++** + -```cpp +### 方法二:双指针 + +与方法一类似,我们先找出数组的最长非递减前缀和最长非递减后缀,分别记为 $nums[0..i]$ 和 $nums[j..n-1]$。 + +如果 $i \geq j$,说明数组本身就是非递减的,返回 $0$。 + +否则,我们可以选择删除右侧后缀,也可以选择删除左侧前缀,因此初始时答案为 $min(n - i - 1, j)$。 + +接下来,我们枚举左侧前缀的最右端点 $l$,对于每个 $l$,我们直接利用双指针找到第一个大于等于 $nums[l]$ 的位置,记为 $r$,此时我们可以删除 $nums[l+1..r-1]$,并且更新答案 $ans = min(ans, r - l - 1)$。继续枚举 $l$,最终得到答案。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组长度。 + + + +```python +class Solution: + def findLengthOfShortestSubarray(self, arr: List[int]) -> int: + n = len(arr) + i, j = 0, n - 1 + while i + 1 < n and arr[i] <= arr[i + 1]: + i += 1 + while j - 1 >= 0 and arr[j - 1] <= arr[j]: + j -= 1 + if i >= j: + return 0 + ans = min(n - i - 1, j) + r = j + for l in range(i + 1): + while r < n and arr[r] < arr[l]: + r += 1 + ans = min(ans, r - l - 1) + return ans +``` + +```java class Solution { -public: - int findLengthOfShortestSubarray(vector& arr) { - int n = arr.size(); + public int findLengthOfShortestSubarray(int[] arr) { + int n = arr.length; int i = 0, j = n - 1; while (i + 1 < n && arr[i] <= arr[i + 1]) { ++i; @@ -210,14 +222,16 @@ public: if (i >= j) { return 0; } - int ans = min(n - 1 - i, j); - for (int l = 0; l <= i; ++l) { - int r = lower_bound(arr.begin() + j, arr.end(), arr[l]) - arr.begin(); - ans = min(ans, r - l - 1); + int ans = Math.min(n - i - 1, j); + for (int l = 0, r = j; l <= i; ++l) { + while (r < n && arr[r] < arr[l]) { + ++r; + } + ans = Math.min(ans, r - l - 1); } return ans; } -}; +} ``` ```cpp @@ -247,30 +261,6 @@ public: }; ``` -### **Go** - -```go -func findLengthOfShortestSubarray(arr []int) int { - n := len(arr) - i, j := 0, n-1 - for i+1 < n && arr[i] <= arr[i+1] { - i++ - } - for j-1 >= 0 && arr[j-1] <= arr[j] { - j-- - } - if i >= j { - return 0 - } - ans := min(n-i-1, j) - for l := 0; l <= i; l++ { - r := j + sort.SearchInts(arr[j:], arr[l]) - ans = min(ans, r-l-1) - } - return ans -} -``` - ```go func findLengthOfShortestSubarray(arr []int) int { n := len(arr) @@ -296,10 +286,6 @@ func findLengthOfShortestSubarray(arr []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/README_EN.md b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/README_EN.md index d41c85128fe3f..5c90b1f50034c 100644 --- a/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/README_EN.md +++ b/solution/1500-1599/1574.Shortest Subarray to be Removed to Make Array Sorted/README_EN.md @@ -46,9 +46,9 @@ Another correct solution is to remove the subarray [3,10,4]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,28 +68,6 @@ class Solution: return ans ``` -```python -class Solution: - def findLengthOfShortestSubarray(self, arr: List[int]) -> int: - n = len(arr) - i, j = 0, n - 1 - while i + 1 < n and arr[i] <= arr[i + 1]: - i += 1 - while j - 1 >= 0 and arr[j - 1] <= arr[j]: - j -= 1 - if i >= j: - return 0 - ans = min(n - i - 1, j) - r = j - for l in range(i + 1): - while r < n and arr[r] < arr[l]: - r += 1 - ans = min(ans, r - l - 1) - return ans -``` - -### **Java** - ```java class Solution { public int findLengthOfShortestSubarray(int[] arr) { @@ -127,10 +105,11 @@ class Solution { } ``` -```java +```cpp class Solution { - public int findLengthOfShortestSubarray(int[] arr) { - int n = arr.length; +public: + int findLengthOfShortestSubarray(vector& arr) { + int n = arr.size(); int i = 0, j = n - 1; while (i + 1 < n && arr[i] <= arr[i + 1]) { ++i; @@ -141,25 +120,68 @@ class Solution { if (i >= j) { return 0; } - int ans = Math.min(n - i - 1, j); - for (int l = 0, r = j; l <= i; ++l) { - while (r < n && arr[r] < arr[l]) { - ++r; - } - ans = Math.min(ans, r - l - 1); + int ans = min(n - 1 - i, j); + for (int l = 0; l <= i; ++l) { + int r = lower_bound(arr.begin() + j, arr.end(), arr[l]) - arr.begin(); + ans = min(ans, r - l - 1); } return ans; } +}; +``` + +```go +func findLengthOfShortestSubarray(arr []int) int { + n := len(arr) + i, j := 0, n-1 + for i+1 < n && arr[i] <= arr[i+1] { + i++ + } + for j-1 >= 0 && arr[j-1] <= arr[j] { + j-- + } + if i >= j { + return 0 + } + ans := min(n-i-1, j) + for l := 0; l <= i; l++ { + r := j + sort.SearchInts(arr[j:], arr[l]) + ans = min(ans, r-l-1) + } + return ans } ``` -### **C++** + + +### Solution 2 -```cpp + + +```python +class Solution: + def findLengthOfShortestSubarray(self, arr: List[int]) -> int: + n = len(arr) + i, j = 0, n - 1 + while i + 1 < n and arr[i] <= arr[i + 1]: + i += 1 + while j - 1 >= 0 and arr[j - 1] <= arr[j]: + j -= 1 + if i >= j: + return 0 + ans = min(n - i - 1, j) + r = j + for l in range(i + 1): + while r < n and arr[r] < arr[l]: + r += 1 + ans = min(ans, r - l - 1) + return ans +``` + +```java class Solution { -public: - int findLengthOfShortestSubarray(vector& arr) { - int n = arr.size(); + public int findLengthOfShortestSubarray(int[] arr) { + int n = arr.length; int i = 0, j = n - 1; while (i + 1 < n && arr[i] <= arr[i + 1]) { ++i; @@ -170,14 +192,16 @@ public: if (i >= j) { return 0; } - int ans = min(n - 1 - i, j); - for (int l = 0; l <= i; ++l) { - int r = lower_bound(arr.begin() + j, arr.end(), arr[l]) - arr.begin(); - ans = min(ans, r - l - 1); + int ans = Math.min(n - i - 1, j); + for (int l = 0, r = j; l <= i; ++l) { + while (r < n && arr[r] < arr[l]) { + ++r; + } + ans = Math.min(ans, r - l - 1); } return ans; } -}; +} ``` ```cpp @@ -207,30 +231,6 @@ public: }; ``` -### **Go** - -```go -func findLengthOfShortestSubarray(arr []int) int { - n := len(arr) - i, j := 0, n-1 - for i+1 < n && arr[i] <= arr[i+1] { - i++ - } - for j-1 >= 0 && arr[j-1] <= arr[j] { - j-- - } - if i >= j { - return 0 - } - ans := min(n-i-1, j) - for l := 0; l <= i; l++ { - r := j + sort.SearchInts(arr[j:], arr[l]) - ans = min(ans, r-l-1) - } - return ans -} -``` - ```go func findLengthOfShortestSubarray(arr []int) int { n := len(arr) @@ -256,10 +256,6 @@ func findLengthOfShortestSubarray(arr []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1575.Count All Possible Routes/README.md b/solution/1500-1599/1575.Count All Possible Routes/README.md index 14cc52e3cc617..3e3a015b811ba 100644 --- a/solution/1500-1599/1575.Count All Possible Routes/README.md +++ b/solution/1500-1599/1575.Count All Possible Routes/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, k)$,表示从城市 $i$ 出发,剩余汽油量为 $k$ 时,到达目的地 $finish$ 的路径数。那么答案就是 $dfs(start, fuel)$。 @@ -81,24 +79,8 @@ 时间复杂度 $O(n^2 \times m)$,空间复杂度 $O(n \times m)$。其中 $n$ 和 $m$ 分别是数组 $locations$ 和 $fuel$ 的大小。 -**方法二:动态规划** - -我们也可以将方法一的记忆化搜索转换为动态规划。 - -我们定义 $f[i][k]$ 表示从城市 $i$ 出发,剩余汽油量为 $k$ 时,到达目的地 $finish$ 的路径数。那么答案就是 $f[start][fuel]$。初始时 $f[finish][k]=1$,其余均为 $0$。 - -接下来,我们从小到大枚举剩余汽油量 $k$,然后枚举所有的城市 $i$,对于每个城市 $i$,我们枚举所有的城市 $j$,如果 $j \ne i$,并且 $|locations[i] - locations[j]| \le k$,那么我们可以从城市 $i$ 移动到城市 $j$,此时剩余汽油量为 $k - |locations[i] - locations[j]|$,那么我们可以将答案路径数加上 $f[j][k - |locations[i] - locations[j]|]$。 - -最后,我们返回答案路径数 $f[start][fuel]$ 即可。 - -时间复杂度 $O(n^2 \times m)$,空间复杂度 $O(n \times m)$。其中 $n$ 和 $m$ 分别是数组 $locations$ 和 $fuel$ 的大小。 - -### **Python3** - - - ```python class Solution: def countRoutes( @@ -118,30 +100,6 @@ class Solution: return dfs(start, fuel) ``` -```python -class Solution: - def countRoutes( - self, locations: List[int], start: int, finish: int, fuel: int - ) -> int: - mod = 10**9 + 7 - n = len(locations) - f = [[0] * (fuel + 1) for _ in range(n)] - for k in range(fuel + 1): - f[finish][k] = 1 - for k in range(fuel + 1): - for i in range(n): - for j in range(n): - if j != i and abs(locations[i] - locations[j]) <= k: - f[i][k] = ( - f[i][k] + f[j][k - abs(locations[i] - locations[j])] - ) % mod - return f[start][fuel] -``` - -### **Java** - - - ```java class Solution { private int[] locations; @@ -176,31 +134,6 @@ class Solution { } ``` -```java -class Solution { - public int countRoutes(int[] locations, int start, int finish, int fuel) { - final int mod = (int) 1e9 + 7; - int n = locations.length; - int[][] f = new int[n][fuel + 1]; - for (int k = 0; k <= fuel; ++k) { - f[finish][k] = 1; - } - for (int k = 0; k <= fuel; ++k) { - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (j != i && Math.abs(locations[i] - locations[j]) <= k) { - f[i][k] = (f[i][k] + f[j][k - Math.abs(locations[i] - locations[j])]) % mod; - } - } - } - } - return f[start][fuel]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -229,33 +162,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countRoutes(vector& locations, int start, int finish, int fuel) { - const int mod = 1e9 + 7; - int n = locations.size(); - int f[n][fuel + 1]; - memset(f, 0, sizeof(f)); - for (int k = 0; k <= fuel; ++k) { - f[finish][k] = 1; - } - for (int k = 0; k <= fuel; ++k) { - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (j != i && abs(locations[i] - locations[j]) <= k) { - f[i][k] = (f[i][k] + f[j][k - abs(locations[i] - locations[j])]) % mod; - } - } - } - } - return f[start][fuel]; - } -}; -``` - -### **Go** - ```go func countRoutes(locations []int, start int, finish int, fuel int) int { n := len(locations) @@ -297,6 +203,115 @@ func abs(x int) int { } ``` +```ts +function countRoutes(locations: number[], start: number, finish: number, fuel: number): number { + const n = locations.length; + const f = Array.from({ length: n }, () => Array(fuel + 1).fill(-1)); + const mod = 1e9 + 7; + const dfs = (i: number, k: number): number => { + if (k < Math.abs(locations[i] - locations[finish])) { + return 0; + } + if (f[i][k] !== -1) { + return f[i][k]; + } + let ans = i === finish ? 1 : 0; + for (let j = 0; j < n; ++j) { + if (j !== i) { + const x = Math.abs(locations[i] - locations[j]); + ans = (ans + dfs(j, k - x)) % mod; + } + } + return (f[i][k] = ans); + }; + return dfs(start, fuel); +} +``` + + + +### 方法二:动态规划 + +我们也可以将方法一的记忆化搜索转换为动态规划。 + +我们定义 $f[i][k]$ 表示从城市 $i$ 出发,剩余汽油量为 $k$ 时,到达目的地 $finish$ 的路径数。那么答案就是 $f[start][fuel]$。初始时 $f[finish][k]=1$,其余均为 $0$。 + +接下来,我们从小到大枚举剩余汽油量 $k$,然后枚举所有的城市 $i$,对于每个城市 $i$,我们枚举所有的城市 $j$,如果 $j \ne i$,并且 $|locations[i] - locations[j]| \le k$,那么我们可以从城市 $i$ 移动到城市 $j$,此时剩余汽油量为 $k - |locations[i] - locations[j]|$,那么我们可以将答案路径数加上 $f[j][k - |locations[i] - locations[j]|]$。 + +最后,我们返回答案路径数 $f[start][fuel]$ 即可。 + +时间复杂度 $O(n^2 \times m)$,空间复杂度 $O(n \times m)$。其中 $n$ 和 $m$ 分别是数组 $locations$ 和 $fuel$ 的大小。 + + + +```python +class Solution: + def countRoutes( + self, locations: List[int], start: int, finish: int, fuel: int + ) -> int: + mod = 10**9 + 7 + n = len(locations) + f = [[0] * (fuel + 1) for _ in range(n)] + for k in range(fuel + 1): + f[finish][k] = 1 + for k in range(fuel + 1): + for i in range(n): + for j in range(n): + if j != i and abs(locations[i] - locations[j]) <= k: + f[i][k] = ( + f[i][k] + f[j][k - abs(locations[i] - locations[j])] + ) % mod + return f[start][fuel] +``` + +```java +class Solution { + public int countRoutes(int[] locations, int start, int finish, int fuel) { + final int mod = (int) 1e9 + 7; + int n = locations.length; + int[][] f = new int[n][fuel + 1]; + for (int k = 0; k <= fuel; ++k) { + f[finish][k] = 1; + } + for (int k = 0; k <= fuel; ++k) { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (j != i && Math.abs(locations[i] - locations[j]) <= k) { + f[i][k] = (f[i][k] + f[j][k - Math.abs(locations[i] - locations[j])]) % mod; + } + } + } + } + return f[start][fuel]; + } +} +``` + +```cpp +class Solution { +public: + int countRoutes(vector& locations, int start, int finish, int fuel) { + const int mod = 1e9 + 7; + int n = locations.size(); + int f[n][fuel + 1]; + memset(f, 0, sizeof(f)); + for (int k = 0; k <= fuel; ++k) { + f[finish][k] = 1; + } + for (int k = 0; k <= fuel; ++k) { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (j != i && abs(locations[i] - locations[j]) <= k) { + f[i][k] = (f[i][k] + f[j][k - abs(locations[i] - locations[j])]) % mod; + } + } + } + } + return f[start][fuel]; + } +}; +``` + ```go func countRoutes(locations []int, start int, finish int, fuel int) int { n := len(locations) @@ -328,33 +343,6 @@ func abs(x int) int { } ``` -### **TypeScript** - -```ts -function countRoutes(locations: number[], start: number, finish: number, fuel: number): number { - const n = locations.length; - const f = Array.from({ length: n }, () => Array(fuel + 1).fill(-1)); - const mod = 1e9 + 7; - const dfs = (i: number, k: number): number => { - if (k < Math.abs(locations[i] - locations[finish])) { - return 0; - } - if (f[i][k] !== -1) { - return f[i][k]; - } - let ans = i === finish ? 1 : 0; - for (let j = 0; j < n; ++j) { - if (j !== i) { - const x = Math.abs(locations[i] - locations[j]); - ans = (ans + dfs(j, k - x)) % mod; - } - } - return (f[i][k] = ans); - }; - return dfs(start, fuel); -} -``` - ```ts function countRoutes(locations: number[], start: number, finish: number, fuel: number): number { const n = locations.length; @@ -376,10 +364,6 @@ function countRoutes(locations: number[], start: number, finish: number, fuel: n } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1575.Count All Possible Routes/README_EN.md b/solution/1500-1599/1575.Count All Possible Routes/README_EN.md index 57c4c34d73218..d4cd14a553dac 100644 --- a/solution/1500-1599/1575.Count All Possible Routes/README_EN.md +++ b/solution/1500-1599/1575.Count All Possible Routes/README_EN.md @@ -59,7 +59,7 @@ ## Solutions -**Solution 1: Memoization** +### Solution 1: Memoization We design a function $dfs(i, k)$, which represents the number of paths from city $i$ with $k$ remaining fuel to the destination $finish$. So the answer is $dfs(start, fuel)$. @@ -74,22 +74,8 @@ To avoid repeated calculations, we can use memoization. The time complexity is $O(n^2 \times m)$, and the space complexity is $O(n \times m)$. Where $n$ and $m$ are the size of the array $locations$ and $fuel$ respectively. -**Solution 2: Dynamic Programming** - -We can also convert the memoization of solution 1 into dynamic programming. - -We define $f[i][k]$ represents the number of paths from city $i$ with $k$ remaining fuel to the destination $finish$. So the answer is $f[start][fuel]$. Initially $f[finish][k]=1$, others are $0$. - -Next, we enumerate the remaining fuel $k$ from small to large, and then enumerate all cities $i$. For each city $i$, we enumerate all cities $j$. If $j \ne i$, and $|locations[i] - locations[j]| \le k$, then we can move from city $i$ to city $j$, and the remaining fuel is $k - |locations[i] - locations[j]|$. Then we can add the number of paths to the answer $f[j][k - |locations[i] - locations[j]|]$. - -Finally, we return the number of paths to the answer $f[start][fuel]$. - -The time complexity is $O(n^2 \times m)$, and the space complexity is $O(n \times m)$. Where $n$ and $m$ are the size of the array $locations$ and $fuel$ respectively. - -### **Python3** - ```python class Solution: def countRoutes( @@ -109,28 +95,6 @@ class Solution: return dfs(start, fuel) ``` -```python -class Solution: - def countRoutes( - self, locations: List[int], start: int, finish: int, fuel: int - ) -> int: - mod = 10**9 + 7 - n = len(locations) - f = [[0] * (fuel + 1) for _ in range(n)] - for k in range(fuel + 1): - f[finish][k] = 1 - for k in range(fuel + 1): - for i in range(n): - for j in range(n): - if j != i and abs(locations[i] - locations[j]) <= k: - f[i][k] = ( - f[i][k] + f[j][k - abs(locations[i] - locations[j])] - ) % mod - return f[start][fuel] -``` - -### **Java** - ```java class Solution { private int[] locations; @@ -165,31 +129,6 @@ class Solution { } ``` -```java -class Solution { - public int countRoutes(int[] locations, int start, int finish, int fuel) { - final int mod = (int) 1e9 + 7; - int n = locations.length; - int[][] f = new int[n][fuel + 1]; - for (int k = 0; k <= fuel; ++k) { - f[finish][k] = 1; - } - for (int k = 0; k <= fuel; ++k) { - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (j != i && Math.abs(locations[i] - locations[j]) <= k) { - f[i][k] = (f[i][k] + f[j][k - Math.abs(locations[i] - locations[j])]) % mod; - } - } - } - } - return f[start][fuel]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -218,33 +157,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countRoutes(vector& locations, int start, int finish, int fuel) { - const int mod = 1e9 + 7; - int n = locations.size(); - int f[n][fuel + 1]; - memset(f, 0, sizeof(f)); - for (int k = 0; k <= fuel; ++k) { - f[finish][k] = 1; - } - for (int k = 0; k <= fuel; ++k) { - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (j != i && abs(locations[i] - locations[j]) <= k) { - f[i][k] = (f[i][k] + f[j][k - abs(locations[i] - locations[j])]) % mod; - } - } - } - } - return f[start][fuel]; - } -}; -``` - -### **Go** - ```go func countRoutes(locations []int, start int, finish int, fuel int) int { n := len(locations) @@ -286,6 +198,115 @@ func abs(x int) int { } ``` +```ts +function countRoutes(locations: number[], start: number, finish: number, fuel: number): number { + const n = locations.length; + const f = Array.from({ length: n }, () => Array(fuel + 1).fill(-1)); + const mod = 1e9 + 7; + const dfs = (i: number, k: number): number => { + if (k < Math.abs(locations[i] - locations[finish])) { + return 0; + } + if (f[i][k] !== -1) { + return f[i][k]; + } + let ans = i === finish ? 1 : 0; + for (let j = 0; j < n; ++j) { + if (j !== i) { + const x = Math.abs(locations[i] - locations[j]); + ans = (ans + dfs(j, k - x)) % mod; + } + } + return (f[i][k] = ans); + }; + return dfs(start, fuel); +} +``` + + + +### Solution 2: Dynamic Programming + +We can also convert the memoization of solution 1 into dynamic programming. + +We define $f[i][k]$ represents the number of paths from city $i$ with $k$ remaining fuel to the destination $finish$. So the answer is $f[start][fuel]$. Initially $f[finish][k]=1$, others are $0$. + +Next, we enumerate the remaining fuel $k$ from small to large, and then enumerate all cities $i$. For each city $i$, we enumerate all cities $j$. If $j \ne i$, and $|locations[i] - locations[j]| \le k$, then we can move from city $i$ to city $j$, and the remaining fuel is $k - |locations[i] - locations[j]|$. Then we can add the number of paths to the answer $f[j][k - |locations[i] - locations[j]|]$. + +Finally, we return the number of paths to the answer $f[start][fuel]$. + +The time complexity is $O(n^2 \times m)$, and the space complexity is $O(n \times m)$. Where $n$ and $m$ are the size of the array $locations$ and $fuel$ respectively. + + + +```python +class Solution: + def countRoutes( + self, locations: List[int], start: int, finish: int, fuel: int + ) -> int: + mod = 10**9 + 7 + n = len(locations) + f = [[0] * (fuel + 1) for _ in range(n)] + for k in range(fuel + 1): + f[finish][k] = 1 + for k in range(fuel + 1): + for i in range(n): + for j in range(n): + if j != i and abs(locations[i] - locations[j]) <= k: + f[i][k] = ( + f[i][k] + f[j][k - abs(locations[i] - locations[j])] + ) % mod + return f[start][fuel] +``` + +```java +class Solution { + public int countRoutes(int[] locations, int start, int finish, int fuel) { + final int mod = (int) 1e9 + 7; + int n = locations.length; + int[][] f = new int[n][fuel + 1]; + for (int k = 0; k <= fuel; ++k) { + f[finish][k] = 1; + } + for (int k = 0; k <= fuel; ++k) { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (j != i && Math.abs(locations[i] - locations[j]) <= k) { + f[i][k] = (f[i][k] + f[j][k - Math.abs(locations[i] - locations[j])]) % mod; + } + } + } + } + return f[start][fuel]; + } +} +``` + +```cpp +class Solution { +public: + int countRoutes(vector& locations, int start, int finish, int fuel) { + const int mod = 1e9 + 7; + int n = locations.size(); + int f[n][fuel + 1]; + memset(f, 0, sizeof(f)); + for (int k = 0; k <= fuel; ++k) { + f[finish][k] = 1; + } + for (int k = 0; k <= fuel; ++k) { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (j != i && abs(locations[i] - locations[j]) <= k) { + f[i][k] = (f[i][k] + f[j][k - abs(locations[i] - locations[j])]) % mod; + } + } + } + } + return f[start][fuel]; + } +}; +``` + ```go func countRoutes(locations []int, start int, finish int, fuel int) int { n := len(locations) @@ -317,33 +338,6 @@ func abs(x int) int { } ``` -### **TypeScript** - -```ts -function countRoutes(locations: number[], start: number, finish: number, fuel: number): number { - const n = locations.length; - const f = Array.from({ length: n }, () => Array(fuel + 1).fill(-1)); - const mod = 1e9 + 7; - const dfs = (i: number, k: number): number => { - if (k < Math.abs(locations[i] - locations[finish])) { - return 0; - } - if (f[i][k] !== -1) { - return f[i][k]; - } - let ans = i === finish ? 1 : 0; - for (let j = 0; j < n; ++j) { - if (j !== i) { - const x = Math.abs(locations[i] - locations[j]); - ans = (ans + dfs(j, k - x)) % mod; - } - } - return (f[i][k] = ans); - }; - return dfs(start, fuel); -} -``` - ```ts function countRoutes(locations: number[], start: number, finish: number, fuel: number): number { const n = locations.length; @@ -365,10 +359,6 @@ function countRoutes(locations: number[], start: number, finish: number, fuel: n } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1576.Replace All 's to Avoid Consecutive Repeating Characters/README.md b/solution/1500-1599/1576.Replace All 's to Avoid Consecutive Repeating Characters/README.md index e993b9da7fd92..d1d1484b33f75 100644 --- a/solution/1500-1599/1576.Replace All 's to Avoid Consecutive Repeating Characters/README.md +++ b/solution/1500-1599/1576.Replace All 's to Avoid Consecutive Repeating Characters/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们遍历字符串,对于每个位置,如果该位置是 `?`,则枚举字符 `'a'`、`'b'`、`'c'`,如果该字符 $c$ 与前后字符都不相同,则将该位置替换为该字符,否则继续枚举下一个字符。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def modifyString(self, s: str) -> str: @@ -77,10 +71,6 @@ class Solution: return "".join(s) ``` -### **Java** - - - ```java class Solution { public String modifyString(String s) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func modifyString(s string) string { n := len(s) @@ -146,8 +132,6 @@ func modifyString(s string) string { } ``` -### **TypeScript** - ```ts function modifyString(s: string): string { const cs = s.split(''); @@ -167,10 +151,6 @@ function modifyString(s: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1576.Replace All 's to Avoid Consecutive Repeating Characters/README_EN.md b/solution/1500-1599/1576.Replace All 's to Avoid Consecutive Repeating Characters/README_EN.md index d4c4806cc2b85..9554f66470f6e 100644 --- a/solution/1500-1599/1576.Replace All 's to Avoid Consecutive Repeating Characters/README_EN.md +++ b/solution/1500-1599/1576.Replace All 's to Avoid Consecutive Repeating Characters/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return "".join(s) ``` -### **Java** - ```java class Solution { public String modifyString(String s) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +98,6 @@ public: }; ``` -### **Go** - ```go func modifyString(s string) string { n := len(s) @@ -123,8 +117,6 @@ func modifyString(s string) string { } ``` -### **TypeScript** - ```ts function modifyString(s: string): string { const cs = s.split(''); @@ -144,10 +136,6 @@ function modifyString(s: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1577.Number of Ways Where Square of Number Is Equal to Product of Two Numbers/README.md b/solution/1500-1599/1577.Number of Ways Where Square of Number Is Equal to Product of Two Numbers/README.md index 3c28196329d18..a64e37e1f07a8 100644 --- a/solution/1500-1599/1577.Number of Ways Where Square of Number Is Equal to Product of Two Numbers/README.md +++ b/solution/1500-1599/1577.Number of Ways Where Square of Number Is Equal to Product of Two Numbers/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们用哈希表 `cnt1` 统计 `nums1` 中每个数出现的次数,用哈希表 `cnt2` 统计 `nums2` 中每个数出现的次数。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def numTriplets(self, nums1: List[int], nums2: List[int]) -> int: @@ -101,10 +95,6 @@ class Solution: return ans >> 1 ``` -### **Java** - - - ```java class Solution { public int numTriplets(int[] nums1, int[] nums2) { @@ -144,8 +134,6 @@ class Solution { } ``` -### **Go** - ```go func numTriplets(nums1 []int, nums2 []int) (ans int) { cnt1 := map[int]int{} @@ -181,10 +169,6 @@ func numTriplets(nums1 []int, nums2 []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1577.Number of Ways Where Square of Number Is Equal to Product of Two Numbers/README_EN.md b/solution/1500-1599/1577.Number of Ways Where Square of Number Is Equal to Product of Two Numbers/README_EN.md index b58f044614948..7a1bafc7dc661 100644 --- a/solution/1500-1599/1577.Number of Ways Where Square of Number Is Equal to Product of Two Numbers/README_EN.md +++ b/solution/1500-1599/1577.Number of Ways Where Square of Number Is Equal to Product of Two Numbers/README_EN.md @@ -50,9 +50,9 @@ Type 2: (3,0,1). nums2[3]2 = nums1[0] * nums1[1]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return ans >> 1 ``` -### **Java** - ```java class Solution { public int numTriplets(int[] nums1, int[] nums2) { @@ -118,8 +116,6 @@ class Solution { } ``` -### **Go** - ```go func numTriplets(nums1 []int, nums2 []int) (ans int) { cnt1 := map[int]int{} @@ -155,10 +151,6 @@ func numTriplets(nums1 []int, nums2 []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1578.Minimum Time to Make Rope Colorful/README.md b/solution/1500-1599/1578.Minimum Time to Make Rope Colorful/README.md index 179c3f12f8b2c..8dd8bf7e35cf7 100644 --- a/solution/1500-1599/1578.Minimum Time to Make Rope Colorful/README.md +++ b/solution/1500-1599/1578.Minimum Time to Make Rope Colorful/README.md @@ -53,9 +53,7 @@ Bob 可以移除下标 2 的蓝色气球。这将花费 3 秒。 ## 解法 - - -**方法一:双指针 + 贪心** +### 方法一:双指针 + 贪心 我们可以用双指针指向当前连续相同颜色的气球的首尾,然后计算出当前连续相同颜色的气球的总时间 $s$,以及最大的时间 $mx$。如果当前连续相同颜色的气球个数大于 $1$,那么我们可以贪心地选择保留时间最大的气球,然后移除其它相同颜色的气球,耗时 $s - mx$,累加到答案中。接下来继续遍历,直到遍历完所有气球。 @@ -63,10 +61,6 @@ Bob 可以移除下标 2 的蓝色气球。这将花费 3 秒。 -### **Python3** - - - ```python class Solution: def minCost(self, colors: str, neededTime: List[int]) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minCost(String colors, int[] neededTime) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func minCost(colors string, neededTime []int) (ans int) { n := len(colors) @@ -160,16 +146,6 @@ func minCost(colors string, neededTime []int) (ans int) { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1578.Minimum Time to Make Rope Colorful/README_EN.md b/solution/1500-1599/1578.Minimum Time to Make Rope Colorful/README_EN.md index ec67d48fc5756..dd0ff7bdd7b58 100644 --- a/solution/1500-1599/1578.Minimum Time to Make Rope Colorful/README_EN.md +++ b/solution/1500-1599/1578.Minimum Time to Make Rope Colorful/README_EN.md @@ -49,9 +49,9 @@ There are no longer two consecutive balloons of the same color. Total time = 1 + ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minCost(String colors, int[] neededTime) { @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +117,6 @@ public: }; ``` -### **Go** - ```go func minCost(colors string, neededTime []int) (ans int) { n := len(colors) @@ -144,16 +138,6 @@ func minCost(colors string, neededTime []int) (ans int) { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/README.md b/solution/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/README.md index e6da576012e07..6048f1d887d5d 100644 --- a/solution/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/README.md +++ b/solution/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:贪心 + 并查集** +### 方法一:贪心 + 并查集 题目要求我们删除最多数目的边,使得 Alice 和 Bob 都可以遍历整个图。也即是说,我们需要保留尽可能少的边,并且要求这些边能够使得 Alice 和 Bob 都可以遍历整个图。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class UnionFind: def __init__(self, n): @@ -128,10 +122,6 @@ class Solution: return ans if ufa.cnt == 1 and ufb.cnt == 1 else -1 ``` -### **Java** - - - ```java class UnionFind { private int[] p; @@ -201,8 +191,6 @@ class Solution { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -268,8 +256,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p, size []int @@ -338,10 +324,6 @@ func maxNumEdgesToRemove(n int, edges [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/README_EN.md b/solution/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/README_EN.md index f4be75eb5c4bb..f56678fdd3a1a 100644 --- a/solution/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/README_EN.md +++ b/solution/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/README_EN.md @@ -62,12 +62,10 @@ ## Solutions -Union find. +### Solution 1 -### **Python3** - ```python class UnionFind: def __init__(self, n): @@ -113,8 +111,6 @@ class Solution: return ans if ufa.cnt == 1 and ufb.cnt == 1 else -1 ``` -### **Java** - ```java class UnionFind { private int[] p; @@ -184,8 +180,6 @@ class Solution { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -251,8 +245,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p, size []int @@ -321,10 +313,6 @@ func maxNumEdgesToRemove(n int, edges [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1580.Put Boxes Into the Warehouse II/README.md b/solution/1500-1599/1580.Put Boxes Into the Warehouse II/README.md index 35069c552041d..558bbaad86596 100644 --- a/solution/1500-1599/1580.Put Boxes Into the Warehouse II/README.md +++ b/solution/1500-1599/1580.Put Boxes Into the Warehouse II/README.md @@ -73,9 +73,7 @@ ## 解法 - - -**方法一:预处理 + 排序 + 贪心** +### 方法一:预处理 + 排序 + 贪心 我们先对仓库进行预处理,得到每个房间的最大高度,然后对箱子和仓库进行排序,从最小的箱子开始,从最小的房间开始,如果当前房间的高度大于等于当前箱子的高度,则可以将当前箱子放入当前房间,否则继续寻找下一个房间。 @@ -85,10 +83,6 @@ -### **Python3** - - - ```python class Solution: def maxBoxesInWarehouse(self, boxes: List[int], warehouse: List[int]) -> int: @@ -114,10 +108,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) { @@ -154,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -192,8 +180,6 @@ public: }; ``` -### **Go** - ```go func maxBoxesInWarehouse(boxes []int, warehouse []int) (ans int) { n := len(warehouse) @@ -228,10 +214,6 @@ func maxBoxesInWarehouse(boxes []int, warehouse []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1580.Put Boxes Into the Warehouse II/README_EN.md b/solution/1500-1599/1580.Put Boxes Into the Warehouse II/README_EN.md index 9d630ef60215b..703e473e21a4c 100644 --- a/solution/1500-1599/1580.Put Boxes Into the Warehouse II/README_EN.md +++ b/solution/1500-1599/1580.Put Boxes Into the Warehouse II/README_EN.md @@ -55,9 +55,9 @@ Other valid solutions are to put the green box in room 2 or to put the orange bo ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) { @@ -122,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +156,6 @@ public: }; ``` -### **Go** - ```go func maxBoxesInWarehouse(boxes []int, warehouse []int) (ans int) { n := len(warehouse) @@ -196,10 +190,6 @@ func maxBoxesInWarehouse(boxes []int, warehouse []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/README.md b/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/README.md index b84503bcd99c5..97d06adf5253e 100644 --- a/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/README.md +++ b/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/README.md @@ -89,22 +89,12 @@ ID = 96 的顾客曾经去过购物中心,并且没有进行任何交易。 ## 解法 - - -**方法一:子查询 + 分组统计** +### 方法一:子查询 + 分组统计 我们可以使用子查询,先找出所有没有进行交易的 `visit_id`,然后按照 `customer_id` 进行分组,统计每个顾客的没有进行交易的次数。 -**方法二:左连接 + 分组统计** - -我们也可以使用左连接,将 `Visits` 表和 `Transactions` 表按照 `visit_id` 进行连接,然后筛选出 `amount` 为 `NULL` 的记录,按照 `customer_id` 进行分组,统计每个顾客的没有进行交易的次数。 - -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT customer_id, COUNT(1) AS count_no_trans @@ -113,6 +103,14 @@ WHERE visit_id NOT IN (SELECT visit_id FROM Transactions) GROUP BY 1; ``` + + +### 方法二:左连接 + 分组统计 + +我们也可以使用左连接,将 `Visits` 表和 `Transactions` 表按照 `visit_id` 进行连接,然后筛选出 `amount` 为 `NULL` 的记录,按照 `customer_id` 进行分组,统计每个顾客的没有进行交易的次数。 + + + ```sql # Write your MySQL query statement below SELECT customer_id, COUNT(1) AS count_no_trans @@ -124,3 +122,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/README_EN.md b/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/README_EN.md index 80afc20e9870d..d9dec22f63637 100644 --- a/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/README_EN.md +++ b/solution/1500-1599/1581.Customer Who Visited but Did Not Make Any Transactions/README_EN.md @@ -87,20 +87,12 @@ As we can see, users with IDs 30 and 96 visited the mall one time without making ## Solutions -**Solution 1: Subquery + Grouping** +### Solution 1: Subquery + Grouping We can use a subquery to first find all `visit_id`s that have not made any transactions, and then group by `customer_id` to count the number of times each customer has not made any transactions. -**Solution 2: Left Join + Grouping** - -We can also use a left join to join the `Visits` table and the `Transactions` table on `visit_id`, and then filter out the records where `amount` is `NULL`. After that, we can group by `customer_id` to count the number of times each customer has not made any transactions. - -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT customer_id, COUNT(1) AS count_no_trans @@ -109,6 +101,14 @@ WHERE visit_id NOT IN (SELECT visit_id FROM Transactions) GROUP BY 1; ``` + + +### Solution 2: Left Join + Grouping + +We can also use a left join to join the `Visits` table and the `Transactions` table on `visit_id`, and then filter out the records where `amount` is `NULL`. After that, we can group by `customer_id` to count the number of times each customer has not made any transactions. + + + ```sql # Write your MySQL query statement below SELECT customer_id, COUNT(1) AS count_no_trans @@ -120,3 +120,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1500-1599/1582.Special Positions in a Binary Matrix/README.md b/solution/1500-1599/1582.Special Positions in a Binary Matrix/README.md index e2dca4701539b..c62b5955b2735 100644 --- a/solution/1500-1599/1582.Special Positions in a Binary Matrix/README.md +++ b/solution/1500-1599/1582.Special Positions in a Binary Matrix/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 遍历矩阵 `mat`,先统计每一行,每一列中 `1` 的个数,分别记录在 `r` 和 `c` 数组中。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def numSpecial(self, mat: List[List[int]]) -> int: @@ -75,10 +69,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numSpecial(int[][] mat) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func numSpecial(mat [][]int) int { m, n := len(mat), len(mat[0]) @@ -155,40 +141,6 @@ func numSpecial(mat [][]int) int { } ``` -### **C** - -```c -int numSpecial(int** mat, int matSize, int* matColSize) { - int m = matSize; - int n = *matColSize; - int* rows = (int*) malloc(sizeof(int) * m); - int* cols = (int*) malloc(sizeof(int) * n); - memset(rows, 0, sizeof(int) * m); - memset(cols, 0, sizeof(int) * n); - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (mat[i][j] == 1) { - rows[i]++; - cols[j]++; - } - } - } - int res = 0; - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (mat[i][j] == 1 && rows[i] == 1 && cols[j] == 1) { - res++; - } - } - } - free(rows); - free(cols); - return res; -} -``` - -### **TypeScript** - ```ts function numSpecial(mat: number[][]): number { const m = mat.length; @@ -217,8 +169,6 @@ function numSpecial(mat: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn num_special(mat: Vec>) -> i32 { @@ -246,10 +196,36 @@ impl Solution { } ``` -### **...** - -``` - +```c +int numSpecial(int** mat, int matSize, int* matColSize) { + int m = matSize; + int n = *matColSize; + int* rows = (int*) malloc(sizeof(int) * m); + int* cols = (int*) malloc(sizeof(int) * n); + memset(rows, 0, sizeof(int) * m); + memset(cols, 0, sizeof(int) * n); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (mat[i][j] == 1) { + rows[i]++; + cols[j]++; + } + } + } + int res = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (mat[i][j] == 1 && rows[i] == 1 && cols[j] == 1) { + res++; + } + } + } + free(rows); + free(cols); + return res; +} ``` + + diff --git a/solution/1500-1599/1582.Special Positions in a Binary Matrix/README_EN.md b/solution/1500-1599/1582.Special Positions in a Binary Matrix/README_EN.md index 9a85f017e5d39..80ea1574ffe75 100644 --- a/solution/1500-1599/1582.Special Positions in a Binary Matrix/README_EN.md +++ b/solution/1500-1599/1582.Special Positions in a Binary Matrix/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numSpecial(int[][] mat) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func numSpecial(mat [][]int) int { m, n := len(mat), len(mat[0]) @@ -137,40 +131,6 @@ func numSpecial(mat [][]int) int { } ``` -### **C** - -```c -int numSpecial(int** mat, int matSize, int* matColSize) { - int m = matSize; - int n = *matColSize; - int* rows = (int*) malloc(sizeof(int) * m); - int* cols = (int*) malloc(sizeof(int) * n); - memset(rows, 0, sizeof(int) * m); - memset(cols, 0, sizeof(int) * n); - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (mat[i][j] == 1) { - rows[i]++; - cols[j]++; - } - } - } - int res = 0; - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (mat[i][j] == 1 && rows[i] == 1 && cols[j] == 1) { - res++; - } - } - } - free(rows); - free(cols); - return res; -} -``` - -### **TypeScript** - ```ts function numSpecial(mat: number[][]): number { const m = mat.length; @@ -199,8 +159,6 @@ function numSpecial(mat: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn num_special(mat: Vec>) -> i32 { @@ -228,10 +186,36 @@ impl Solution { } ``` -### **...** - -``` - +```c +int numSpecial(int** mat, int matSize, int* matColSize) { + int m = matSize; + int n = *matColSize; + int* rows = (int*) malloc(sizeof(int) * m); + int* cols = (int*) malloc(sizeof(int) * n); + memset(rows, 0, sizeof(int) * m); + memset(cols, 0, sizeof(int) * n); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (mat[i][j] == 1) { + rows[i]++; + cols[j]++; + } + } + } + int res = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (mat[i][j] == 1 && rows[i] == 1 && cols[j] == 1) { + res++; + } + } + } + free(rows); + free(cols); + return res; +} ``` + + diff --git a/solution/1500-1599/1583.Count Unhappy Friends/README.md b/solution/1500-1599/1583.Count Unhappy Friends/README.md index 40ab02367c45c..d6b7771037737 100644 --- a/solution/1500-1599/1583.Count Unhappy Friends/README.md +++ b/solution/1500-1599/1583.Count Unhappy Friends/README.md @@ -74,9 +74,7 @@ ## 解法 - - -**方法一:数组 + 枚举** +### 方法一:数组 + 枚举 我们用数组 $d$ 记录每个朋友与其它朋友的亲近程度,其中 $d[i][j]$ 表示朋友 $i$ 对 $j$ 的亲近程度(值越小,越亲近),另外,用数组 $p$ 记录每个朋友的配对朋友。 @@ -88,10 +86,6 @@ -### **Python3** - - - ```python class Solution: def unhappyFriends( @@ -109,10 +103,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int unhappyFriends(int n, int[][] preferences, int[][] pairs) { @@ -146,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +170,6 @@ public: }; ``` -### **Go** - ```go func unhappyFriends(n int, preferences [][]int, pairs [][]int) (ans int) { d := make([][]int, n) @@ -215,10 +201,6 @@ func unhappyFriends(n int, preferences [][]int, pairs [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1583.Count Unhappy Friends/README_EN.md b/solution/1500-1599/1583.Count Unhappy Friends/README_EN.md index d22602e0a3fee..816424d2b4171 100644 --- a/solution/1500-1599/1583.Count Unhappy Friends/README_EN.md +++ b/solution/1500-1599/1583.Count Unhappy Friends/README_EN.md @@ -70,9 +70,9 @@ Friends 0 and 2 are happy. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -91,8 +91,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int unhappyFriends(int n, int[][] preferences, int[][] pairs) { @@ -126,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +158,6 @@ public: }; ``` -### **Go** - ```go func unhappyFriends(n int, preferences [][]int, pairs [][]int) (ans int) { d := make([][]int, n) @@ -195,10 +189,6 @@ func unhappyFriends(n int, preferences [][]int, pairs [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1584.Min Cost to Connect All Points/README.md b/solution/1500-1599/1584.Min Cost to Connect All Points/README.md index 7a955b47ff1d4..5fc71aaad04cb 100644 --- a/solution/1500-1599/1584.Min Cost to Connect All Points/README.md +++ b/solution/1500-1599/1584.Min Cost to Connect All Points/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:朴素 Prim 算法** +### 方法一:朴素 Prim 算法 我们定义一个数组 $dist$,其中 $dist[i]$ 表示点 $i$ 到当前生成树的距离,初始时 $dist[0] = 0$,其余均为 $+\infty$,定义一个数组 $vis$,其中 $vis[i]$ 表示点 $i$ 是否在生成树中,初始时所有点均不在生成树中,定义一个二维数组 $g$,其中 $g[i][j]$ 表示点 $i$ 到点 $j$ 的距离,那么我们的目标是将所有点都加入到生成树中,且总费用最小。 @@ -77,18 +75,8 @@ 该算法适用于稠密图,时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 为点的数量。 -**方法二:Kruskal 算法** - -我们先将所有边按照长度由小到大进行排序,循环遍历每条边,逐个加入到图中,当所有点达到一个连通状态时,退出循环,返回此时的总费用即可。 - -时间复杂度 $O(m \times \log m)$,空间复杂度 $O(m)$。其中 $m$ 为边的数量,本题中 $m = n^2$。 - -### **Python3** - - - ```python class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: @@ -116,39 +104,6 @@ class Solution: return ans ``` -```python -class Solution: - def minCostConnectPoints(self, points: List[List[int]]) -> int: - def find(x: int) -> int: - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - n = len(points) - g = [] - for i, (x1, y1) in enumerate(points): - for j in range(i + 1, n): - x2, y2 = points[j] - t = abs(x1 - x2) + abs(y1 - y2) - g.append((t, i, j)) - p = list(range(n)) - ans = 0 - for cost, i, j in sorted(g): - pa, pb = find(i), find(j) - if pa == pb: - continue - p[pa] = pb - ans += cost - n -= 1 - if n == 1: - break - return ans -``` - -### **Java** - - - ```java class Solution { public int minCostConnectPoints(int[][] points) { @@ -189,51 +144,6 @@ class Solution { } ``` -```java -class Solution { - private int[] p; - - public int minCostConnectPoints(int[][] points) { - int n = points.length; - List g = new ArrayList<>(); - 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]; - g.add(new int[] {Math.abs(x1 - x2) + Math.abs(y1 - y2), i, j}); - } - } - g.sort(Comparator.comparingInt(a -> a[0])); - p = new int[n]; - for (int i = 0; i < n; ++i) { - p[i] = i; - } - int ans = 0; - for (int[] e : g) { - int cost = e[0], i = e[1], j = e[2]; - if (find(i) == find(j)) { - continue; - } - p[find(i)] = find(j); - ans += cost; - if (--n == 1) { - return ans; - } - } - return 0; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -275,44 +185,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector p; - - int minCostConnectPoints(vector>& points) { - int n = points.size(); - vector> g; - 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]; - g.push_back({abs(x1 - x2) + abs(y1 - y2), i, j}); - } - } - sort(g.begin(), g.end()); - p.resize(n); - for (int i = 0; i < n; ++i) p[i] = i; - int ans = 0; - for (auto& e : g) { - int cost = e[0], i = e[1], j = e[2]; - if (find(i) == find(j)) continue; - p[find(i)] = find(j); - ans += cost; - if (--n == 1) return ans; - } - return 0; - } - - int find(int x) { - if (p[x] != x) p[x] = find(p[x]); - return p[x]; - } -}; -``` - -### **Go** - ```go func minCostConnectPoints(points [][]int) (ans int) { n := len(points) @@ -359,6 +231,162 @@ func abs(x int) int { } ``` +```ts +function minCostConnectPoints(points: number[][]): number { + const n = points.length; + const g: number[][] = Array(n) + .fill(0) + .map(() => Array(n).fill(0)); + const dist: number[] = Array(n).fill(1 << 30); + const vis: boolean[] = Array(n).fill(false); + for (let i = 0; i < n; ++i) { + const [x1, y1] = points[i]; + for (let j = i + 1; j < n; ++j) { + const [x2, y2] = points[j]; + const t = Math.abs(x1 - x2) + Math.abs(y1 - y2); + g[i][j] = t; + g[j][i] = t; + } + } + let ans = 0; + dist[0] = 0; + for (let i = 0; i < n; ++i) { + let j = -1; + for (let k = 0; k < n; ++k) { + if (!vis[k] && (j === -1 || dist[k] < dist[j])) { + j = k; + } + } + vis[j] = true; + ans += dist[j]; + for (let k = 0; k < n; ++k) { + if (!vis[k]) { + dist[k] = Math.min(dist[k], g[j][k]); + } + } + } + return ans; +} +``` + + + +### 方法二:Kruskal 算法 + +我们先将所有边按照长度由小到大进行排序,循环遍历每条边,逐个加入到图中,当所有点达到一个连通状态时,退出循环,返回此时的总费用即可。 + +时间复杂度 $O(m \times \log m)$,空间复杂度 $O(m)$。其中 $m$ 为边的数量,本题中 $m = n^2$。 + + + +```python +class Solution: + def minCostConnectPoints(self, points: List[List[int]]) -> int: + def find(x: int) -> int: + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + n = len(points) + g = [] + for i, (x1, y1) in enumerate(points): + for j in range(i + 1, n): + x2, y2 = points[j] + t = abs(x1 - x2) + abs(y1 - y2) + g.append((t, i, j)) + p = list(range(n)) + ans = 0 + for cost, i, j in sorted(g): + pa, pb = find(i), find(j) + if pa == pb: + continue + p[pa] = pb + ans += cost + n -= 1 + if n == 1: + break + return ans +``` + +```java +class Solution { + private int[] p; + + public int minCostConnectPoints(int[][] points) { + int n = points.length; + List g = new ArrayList<>(); + 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]; + g.add(new int[] {Math.abs(x1 - x2) + Math.abs(y1 - y2), i, j}); + } + } + g.sort(Comparator.comparingInt(a -> a[0])); + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + int ans = 0; + for (int[] e : g) { + int cost = e[0], i = e[1], j = e[2]; + if (find(i) == find(j)) { + continue; + } + p[find(i)] = find(j); + ans += cost; + if (--n == 1) { + return ans; + } + } + return 0; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} +``` + +```cpp +class Solution { +public: + vector p; + + int minCostConnectPoints(vector>& points) { + int n = points.size(); + vector> g; + 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]; + g.push_back({abs(x1 - x2) + abs(y1 - y2), i, j}); + } + } + sort(g.begin(), g.end()); + p.resize(n); + for (int i = 0; i < n; ++i) p[i] = i; + int ans = 0; + for (auto& e : g) { + int cost = e[0], i = e[1], j = e[2]; + if (find(i) == find(j)) continue; + p[find(i)] = find(j); + ans += cost; + if (--n == 1) return ans; + } + return 0; + } + + int find(int x) { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + } +}; +``` + ```go func minCostConnectPoints(points [][]int) int { n := len(points) @@ -408,50 +436,6 @@ func abs(x int) int { } ``` -### **TypeScript** - -```ts -function minCostConnectPoints(points: number[][]): number { - const n = points.length; - const g: number[][] = Array(n) - .fill(0) - .map(() => Array(n).fill(0)); - const dist: number[] = Array(n).fill(1 << 30); - const vis: boolean[] = Array(n).fill(false); - for (let i = 0; i < n; ++i) { - const [x1, y1] = points[i]; - for (let j = i + 1; j < n; ++j) { - const [x2, y2] = points[j]; - const t = Math.abs(x1 - x2) + Math.abs(y1 - y2); - g[i][j] = t; - g[j][i] = t; - } - } - let ans = 0; - dist[0] = 0; - for (let i = 0; i < n; ++i) { - let j = -1; - for (let k = 0; k < n; ++k) { - if (!vis[k] && (j === -1 || dist[k] < dist[j])) { - j = k; - } - } - vis[j] = true; - ans += dist[j]; - for (let k = 0; k < n; ++k) { - if (!vis[k]) { - dist[k] = Math.min(dist[k], g[j][k]); - } - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1584.Min Cost to Connect All Points/README_EN.md b/solution/1500-1599/1584.Min Cost to Connect All Points/README_EN.md index ffa6b14bfc958..f56aa27a06ad7 100644 --- a/solution/1500-1599/1584.Min Cost to Connect All Points/README_EN.md +++ b/solution/1500-1599/1584.Min Cost to Connect All Points/README_EN.md @@ -40,9 +40,9 @@ Notice that there is a unique path between every pair of points. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,37 +71,6 @@ class Solution: return ans ``` -```python -class Solution: - def minCostConnectPoints(self, points: List[List[int]]) -> int: - def find(x: int) -> int: - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - n = len(points) - g = [] - for i, (x1, y1) in enumerate(points): - for j in range(i + 1, n): - x2, y2 = points[j] - t = abs(x1 - x2) + abs(y1 - y2) - g.append((t, i, j)) - p = list(range(n)) - ans = 0 - for cost, i, j in sorted(g): - pa, pb = find(i), find(j) - if pa == pb: - continue - p[pa] = pb - ans += cost - n -= 1 - if n == 1: - break - return ans -``` - -### **Java** - ```java class Solution { public int minCostConnectPoints(int[][] points) { @@ -142,51 +111,6 @@ class Solution { } ``` -```java -class Solution { - private int[] p; - - public int minCostConnectPoints(int[][] points) { - int n = points.length; - List g = new ArrayList<>(); - 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]; - g.add(new int[] {Math.abs(x1 - x2) + Math.abs(y1 - y2), i, j}); - } - } - g.sort(Comparator.comparingInt(a -> a[0])); - p = new int[n]; - for (int i = 0; i < n; ++i) { - p[i] = i; - } - int ans = 0; - for (int[] e : g) { - int cost = e[0], i = e[1], j = e[2]; - if (find(i) == find(j)) { - continue; - } - p[find(i)] = find(j); - ans += cost; - if (--n == 1) { - return ans; - } - } - return 0; - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -228,44 +152,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector p; - - int minCostConnectPoints(vector>& points) { - int n = points.size(); - vector> g; - 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]; - g.push_back({abs(x1 - x2) + abs(y1 - y2), i, j}); - } - } - sort(g.begin(), g.end()); - p.resize(n); - for (int i = 0; i < n; ++i) p[i] = i; - int ans = 0; - for (auto& e : g) { - int cost = e[0], i = e[1], j = e[2]; - if (find(i) == find(j)) continue; - p[find(i)] = find(j); - ans += cost; - if (--n == 1) return ans; - } - return 0; - } - - int find(int x) { - if (p[x] != x) p[x] = find(p[x]); - return p[x]; - } -}; -``` - -### **Go** - ```go func minCostConnectPoints(points [][]int) (ans int) { n := len(points) @@ -312,6 +198,158 @@ func abs(x int) int { } ``` +```ts +function minCostConnectPoints(points: number[][]): number { + const n = points.length; + const g: number[][] = Array(n) + .fill(0) + .map(() => Array(n).fill(0)); + const dist: number[] = Array(n).fill(1 << 30); + const vis: boolean[] = Array(n).fill(false); + for (let i = 0; i < n; ++i) { + const [x1, y1] = points[i]; + for (let j = i + 1; j < n; ++j) { + const [x2, y2] = points[j]; + const t = Math.abs(x1 - x2) + Math.abs(y1 - y2); + g[i][j] = t; + g[j][i] = t; + } + } + let ans = 0; + dist[0] = 0; + for (let i = 0; i < n; ++i) { + let j = -1; + for (let k = 0; k < n; ++k) { + if (!vis[k] && (j === -1 || dist[k] < dist[j])) { + j = k; + } + } + vis[j] = true; + ans += dist[j]; + for (let k = 0; k < n; ++k) { + if (!vis[k]) { + dist[k] = Math.min(dist[k], g[j][k]); + } + } + } + return ans; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minCostConnectPoints(self, points: List[List[int]]) -> int: + def find(x: int) -> int: + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + n = len(points) + g = [] + for i, (x1, y1) in enumerate(points): + for j in range(i + 1, n): + x2, y2 = points[j] + t = abs(x1 - x2) + abs(y1 - y2) + g.append((t, i, j)) + p = list(range(n)) + ans = 0 + for cost, i, j in sorted(g): + pa, pb = find(i), find(j) + if pa == pb: + continue + p[pa] = pb + ans += cost + n -= 1 + if n == 1: + break + return ans +``` + +```java +class Solution { + private int[] p; + + public int minCostConnectPoints(int[][] points) { + int n = points.length; + List g = new ArrayList<>(); + 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]; + g.add(new int[] {Math.abs(x1 - x2) + Math.abs(y1 - y2), i, j}); + } + } + g.sort(Comparator.comparingInt(a -> a[0])); + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + int ans = 0; + for (int[] e : g) { + int cost = e[0], i = e[1], j = e[2]; + if (find(i) == find(j)) { + continue; + } + p[find(i)] = find(j); + ans += cost; + if (--n == 1) { + return ans; + } + } + return 0; + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } +} +``` + +```cpp +class Solution { +public: + vector p; + + int minCostConnectPoints(vector>& points) { + int n = points.size(); + vector> g; + 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]; + g.push_back({abs(x1 - x2) + abs(y1 - y2), i, j}); + } + } + sort(g.begin(), g.end()); + p.resize(n); + for (int i = 0; i < n; ++i) p[i] = i; + int ans = 0; + for (auto& e : g) { + int cost = e[0], i = e[1], j = e[2]; + if (find(i) == find(j)) continue; + p[find(i)] = find(j); + ans += cost; + if (--n == 1) return ans; + } + return 0; + } + + int find(int x) { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + } +}; +``` + ```go func minCostConnectPoints(points [][]int) int { n := len(points) @@ -361,50 +399,6 @@ func abs(x int) int { } ``` -### **TypeScript** - -```ts -function minCostConnectPoints(points: number[][]): number { - const n = points.length; - const g: number[][] = Array(n) - .fill(0) - .map(() => Array(n).fill(0)); - const dist: number[] = Array(n).fill(1 << 30); - const vis: boolean[] = Array(n).fill(false); - for (let i = 0; i < n; ++i) { - const [x1, y1] = points[i]; - for (let j = i + 1; j < n; ++j) { - const [x2, y2] = points[j]; - const t = Math.abs(x1 - x2) + Math.abs(y1 - y2); - g[i][j] = t; - g[j][i] = t; - } - } - let ans = 0; - dist[0] = 0; - for (let i = 0; i < n; ++i) { - let j = -1; - for (let k = 0; k < n; ++k) { - if (!vis[k] && (j === -1 || dist[k] < dist[j])) { - j = k; - } - } - vis[j] = true; - ans += dist[j]; - for (let k = 0; k < n; ++k) { - if (!vis[k]) { - dist[k] = Math.min(dist[k], g[j][k]); - } - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1585.Check If String Is Transformable With Substring Sort Operations/README.md b/solution/1500-1599/1585.Check If String Is Transformable With Substring Sort Operations/README.md index ee5282fc95757..7a4547e0b144e 100644 --- a/solution/1500-1599/1585.Check If String Is Transformable With Substring Sort Operations/README.md +++ b/solution/1500-1599/1585.Check If String Is Transformable With Substring Sort Operations/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:冒泡排序** +### 方法一:冒泡排序 题目实际上等价于判断:将字符串 $s$ 中任意长度为 $2$ 的子字符串采用冒泡排序交换,是否能得到 $t$。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def isTransformable(self, s: str, t: str) -> bool: @@ -100,10 +94,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean isTransformable(String s, String t) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func isTransformable(s string, t string) bool { pos := [10][]int{} @@ -180,10 +166,6 @@ func isTransformable(s string, t string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1585.Check If String Is Transformable With Substring Sort Operations/README_EN.md b/solution/1500-1599/1585.Check If String Is Transformable With Substring Sort Operations/README_EN.md index 540363c9fc806..ae8c17f091930 100644 --- a/solution/1500-1599/1585.Check If String Is Transformable With Substring Sort Operations/README_EN.md +++ b/solution/1500-1599/1585.Check If String Is Transformable With Substring Sort Operations/README_EN.md @@ -59,9 +59,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean isTransformable(String s, String t) { @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +127,6 @@ public: }; ``` -### **Go** - ```go func isTransformable(s string, t string) bool { pos := [10][]int{} @@ -155,10 +149,6 @@ func isTransformable(s string, t string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1586.Binary Search Tree Iterator II/README.md b/solution/1500-1599/1586.Binary Search Tree Iterator II/README.md index cdaf89ded6d26..100a6f122bf51 100644 --- a/solution/1500-1599/1586.Binary Search Tree Iterator II/README.md +++ b/solution/1500-1599/1586.Binary Search Tree Iterator II/README.md @@ -63,9 +63,7 @@ bSTIterator.prev(); // 状态变为 [3, 7, <u>9</u>, 15, 20], 返回 ## 解法 - - -**方法一:中序遍历 + 数组** +### 方法一:中序遍历 + 数组 我们可以使用中序遍历将二叉搜索树的所有节点的值存储到数组 $nums$ 中,然后使用数组实现迭代器。我们定义一个指针 $i$,初始时 $i = -1$,表示指向数组 $nums$ 中的一个元素。每次调用 $next()$ 时,我们将 $i$ 的值加 $1$,并返回 $nums[i]$;每次调用 $prev()$ 时,我们将 $i$ 的值减 $1$,并返回 $nums[i]$。 @@ -73,10 +71,6 @@ bSTIterator.prev(); // 状态变为 [3, 7, <u>9</u>, 15, 20], 返回 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -121,10 +115,6 @@ class BSTIterator: # param_4 = obj.prev() ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -185,8 +175,6 @@ class BSTIterator { */ ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -247,8 +235,6 @@ private: */ ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -306,8 +292,6 @@ func (this *BSTIterator) Prev() int { */ ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -370,10 +354,6 @@ class BSTIterator { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1586.Binary Search Tree Iterator II/README_EN.md b/solution/1500-1599/1586.Binary Search Tree Iterator II/README_EN.md index 2d121ecb559d5..8eb7ee67d8e08 100644 --- a/solution/1500-1599/1586.Binary Search Tree Iterator II/README_EN.md +++ b/solution/1500-1599/1586.Binary Search Tree Iterator II/README_EN.md @@ -61,7 +61,7 @@ bSTIterator.prev(); // state becomes [3, 7, 9, 15, 20], return 9 ## Solutions -**Solution 1: In-order Traversal + Array** +### Solution 1: In-order Traversal + Array We can use in-order traversal to store the values of all nodes in the binary search tree into an array $nums$, and then use the array to implement the iterator. We define a pointer $i$, initially $i = -1$, which points to an element in the array $nums$. Each time we call $next()$, we add $1$ to the value of $i$ and return $nums[i]$; each time we call $prev()$, we subtract $1$ from the value of $i$ and return $nums[i]$. @@ -69,8 +69,6 @@ In terms of time complexity, initializing the iterator requires $O(n)$ time, whe -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -115,8 +113,6 @@ class BSTIterator: # param_4 = obj.prev() ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -177,8 +173,6 @@ class BSTIterator { */ ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -239,8 +233,6 @@ private: */ ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -298,8 +290,6 @@ func (this *BSTIterator) Prev() int { */ ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -362,10 +352,6 @@ class BSTIterator { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1587.Bank Account Summary II/README.md b/solution/1500-1599/1587.Bank Account Summary II/README.md index ac5c036c96baf..309d9ada3661a 100644 --- a/solution/1500-1599/1587.Bank Account Summary II/README.md +++ b/solution/1500-1599/1587.Bank Account Summary II/README.md @@ -88,18 +88,12 @@ Charlie 的余额为(6000 + 6000 - 4000) = 8000. ## 解法 - - -**方法一:等值连接 + 分组求和** +### 方法一:等值连接 + 分组求和 我们可以使用等值连接,将 `Users` 和 `Transactions` 表按照 `account` 列连接起来,然后按照 `account` 列分组求和,最后筛选出余额大于 $10000$ 的用户。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -113,3 +107,5 @@ HAVING balance > 10000; ``` + + diff --git a/solution/1500-1599/1587.Bank Account Summary II/README_EN.md b/solution/1500-1599/1587.Bank Account Summary II/README_EN.md index e02eb57b2d2d1..d62fe0bfdf449 100644 --- a/solution/1500-1599/1587.Bank Account Summary II/README_EN.md +++ b/solution/1500-1599/1587.Bank Account Summary II/README_EN.md @@ -84,14 +84,12 @@ Charlie's balance is (6000 + 6000 - 4000) = 8000. ## Solutions -**Solution 1: Equi-Join + Group By + Sum** +### Solution 1: Equi-Join + Group By + Sum We can use an equi-join to join the `Users` table and the `Transactions` table on the condition of `account`, and then group by `account` to calculate the balance for each account using the `SUM` function. Finally, we can filter out the users whose balance is less than or equal to $10000$. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -105,3 +103,5 @@ HAVING balance > 10000; ``` + + diff --git a/solution/1500-1599/1588.Sum of All Odd Length Subarrays/README.md b/solution/1500-1599/1588.Sum of All Odd Length Subarrays/README.md index de6edfb40d810..fa029d17d73d1 100644 --- a/solution/1500-1599/1588.Sum of All Odd Length Subarrays/README.md +++ b/solution/1500-1599/1588.Sum of All Odd Length Subarrays/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:枚举 + 前缀和** +### 方法一:枚举 + 前缀和 我们可以枚举子数组的起点 $i$ 和终点 $j$,其中 $i \leq j$,维护每个子数组的和,然后判断子数组的长度是否为奇数,如果是,则将子数组的和加入答案。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int sumOddLengthSubarrays(int[] arr) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func sumOddLengthSubarrays(arr []int) (ans int) { n := len(arr) @@ -152,8 +138,6 @@ func sumOddLengthSubarrays(arr []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumOddLengthSubarrays(arr: number[]): number { const n = arr.length; @@ -171,8 +155,6 @@ function sumOddLengthSubarrays(arr: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn sum_odd_length_subarrays(arr: Vec) -> i32 { @@ -192,8 +174,6 @@ impl Solution { } ``` -### **C** - ```c int sumOddLengthSubarrays(int* arr, int arrSize) { int ans = 0; @@ -210,10 +190,6 @@ int sumOddLengthSubarrays(int* arr, int arrSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1588.Sum of All Odd Length Subarrays/README_EN.md b/solution/1500-1599/1588.Sum of All Odd Length Subarrays/README_EN.md index 63166c349b882..22641bb2bafa2 100644 --- a/solution/1500-1599/1588.Sum of All Odd Length Subarrays/README_EN.md +++ b/solution/1500-1599/1588.Sum of All Odd Length Subarrays/README_EN.md @@ -55,9 +55,9 @@ If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58

+### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int sumOddLengthSubarrays(int[] arr) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +111,6 @@ public: }; ``` -### **Go** - ```go func sumOddLengthSubarrays(arr []int) (ans int) { n := len(arr) @@ -133,8 +127,6 @@ func sumOddLengthSubarrays(arr []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumOddLengthSubarrays(arr: number[]): number { const n = arr.length; @@ -152,8 +144,6 @@ function sumOddLengthSubarrays(arr: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn sum_odd_length_subarrays(arr: Vec) -> i32 { @@ -173,8 +163,6 @@ impl Solution { } ``` -### **C** - ```c int sumOddLengthSubarrays(int* arr, int arrSize) { int ans = 0; @@ -191,10 +179,6 @@ int sumOddLengthSubarrays(int* arr, int arrSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README.md b/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README.md index b83ca3423ac30..04f5e2504a9b6 100644 --- a/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README.md +++ b/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README.md @@ -55,9 +55,7 @@ requests[1] -> nums[0] + nums[1] = 3 + 5 = 8 ## 解法 - - -**方法一:差分数组 + 排序 + 贪心** +### 方法一:差分数组 + 排序 + 贪心 我们观察发现,对于一次查询操作,会返回该查询区间 $[l, r]$ 中的所有元素之和。而题目要求的是所有查询操作的结果之和的最大值,也即是说,我们要累计所有查询操作的结果,使得这些结果之和最大。因此,如果一个下标 $i$ 在查询操作中出现的次数越多,那么我们就应该赋给下标 $i$ 一个较大的值,这样才能使得所有查询操作的结果之和最大。 @@ -67,10 +65,6 @@ requests[1] -> nums[0] + nums[1] = 3 + 5 = 8 -### **Python3** - - - ```python class Solution: def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int: @@ -88,10 +82,6 @@ class Solution: return sum(a * b for a, b in zip(nums, d)) % mod ``` -### **Java** - - - ```java class Solution { public int maxSumRangeQuery(int[] nums, int[][] requests) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func maxSumRangeQuery(nums []int, requests [][]int) (ans int) { n := len(nums) @@ -176,8 +162,6 @@ func maxSumRangeQuery(nums []int, requests [][]int) (ans int) { return ``` -### **TypeScript** - ```ts function maxSumRangeQuery(nums: number[], requests: number[][]): number { const n = nums.length; @@ -202,10 +186,6 @@ function maxSumRangeQuery(nums: number[], requests: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README_EN.md b/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README_EN.md index 46eaaedbd4ec2..94f129069d75d 100644 --- a/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README_EN.md +++ b/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README_EN.md @@ -54,9 +54,9 @@ Total sum: 11 + 8 = 19, which is the best that you can do. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return sum(a * b for a, b in zip(nums, d)) % mod ``` -### **Java** - ```java class Solution { public int maxSumRangeQuery(int[] nums, int[][] requests) { @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +131,6 @@ public: }; ``` -### **Go** - ```go func maxSumRangeQuery(nums []int, requests [][]int) (ans int) { n := len(nums) @@ -159,11 +153,8 @@ func maxSumRangeQuery(nums []int, requests [][]int) (ans int) { ans = (ans + a*b) % mod } return -} ``` -### **TypeScript** - ```ts function maxSumRangeQuery(nums: number[], requests: number[][]): number { const n = nums.length; @@ -188,10 +179,6 @@ function maxSumRangeQuery(nums: number[], requests: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1590.Make Sum Divisible by P/README.md b/solution/1500-1599/1590.Make Sum Divisible by P/README.md index 6e8d883aadd68..222fb73f041ac 100644 --- a/solution/1500-1599/1590.Make Sum Divisible by P/README.md +++ b/solution/1500-1599/1590.Make Sum Divisible by P/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:前缀和 + 哈希表** +### 方法一:前缀和 + 哈希表 我们可以先求出数组 $nums$ 所有元素之和模 $p$ 的值,记为 $k$。如果 $k$ 为 $0$,说明数组 $nums$ 所有元素之和就是 $p$ 的倍数,直接返回 $0$ 即可。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def minSubarray(self, nums: List[int], p: int) -> int: @@ -100,10 +94,6 @@ class Solution: return -1 if ans == len(nums) else ans ``` -### **Java** - - - ```java class Solution { public int minSubarray(int[] nums, int p) { @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +151,6 @@ public: }; ``` -### **Go** - ```go func minSubarray(nums []int, p int) int { k := 0 @@ -193,8 +179,6 @@ func minSubarray(nums []int, p int) int { } ``` -### **TypeScript** - ```ts function minSubarray(nums: number[], p: number): number { let k = 0; @@ -222,10 +206,6 @@ function minSubarray(nums: number[], p: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1590.Make Sum Divisible by P/README_EN.md b/solution/1500-1599/1590.Make Sum Divisible by P/README_EN.md index 4d65d3e3b5353..9149cc3ca498a 100644 --- a/solution/1500-1599/1590.Make Sum Divisible by P/README_EN.md +++ b/solution/1500-1599/1590.Make Sum Divisible by P/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return -1 if ans == len(nums) else ans ``` -### **Java** - ```java class Solution { public int minSubarray(int[] nums, int p) { @@ -98,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +125,6 @@ public: }; ``` -### **Go** - ```go func minSubarray(nums []int, p int) int { k := 0 @@ -159,8 +153,6 @@ func minSubarray(nums []int, p int) int { } ``` -### **TypeScript** - ```ts function minSubarray(nums: number[], p: number): number { let k = 0; @@ -188,10 +180,6 @@ function minSubarray(nums: number[], p: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1591.Strange Printer II/README.md b/solution/1500-1599/1591.Strange Printer II/README.md index e6989ed62a3d3..a86785a70522e 100644 --- a/solution/1500-1599/1591.Strange Printer II/README.md +++ b/solution/1500-1599/1591.Strange Printer II/README.md @@ -60,30 +60,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1500-1599/1591.Strange Printer II/README_EN.md b/solution/1500-1599/1591.Strange Printer II/README_EN.md index 12efda467c2a5..fb640562feab0 100644 --- a/solution/1500-1599/1591.Strange Printer II/README_EN.md +++ b/solution/1500-1599/1591.Strange Printer II/README_EN.md @@ -50,24 +50,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1500-1599/1592.Rearrange Spaces Between Words/README.md b/solution/1500-1599/1592.Rearrange Spaces Between Words/README.md index f7d4eb19ea4c0..fc04ce80352fa 100644 --- a/solution/1500-1599/1592.Rearrange Spaces Between Words/README.md +++ b/solution/1500-1599/1592.Rearrange Spaces Between Words/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:字符串模拟** +### 方法一:字符串模拟 统计字符串 `text` 中的空格数,记为 `cnt`。将 `text` 按空格分割成字符串数组 `words`。然后计算相邻字符串之间需要拼接的空格数,进行拼接。最后将剩余的空格拼接在末尾。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def reorderSpaces(self, text: str) -> str: @@ -83,10 +77,6 @@ class Solution: return (' ' * (cnt // m)).join(words) + ' ' * (cnt % m) ``` -### **Java** - - - ```java class Solution { public String reorderSpaces(String text) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **Go** - ```go func reorderSpaces(text string) string { cnt := strings.Count(text, " ") @@ -128,8 +116,6 @@ func reorderSpaces(text string) string { } ``` -### **TypeScript** - ```ts function reorderSpaces(text: string): string { let count = 0; @@ -151,8 +137,6 @@ function reorderSpaces(text: string): string { } ``` -### **Rust** - ```rust impl Solution { fn create_spaces(n: usize) -> String { @@ -184,10 +168,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1592.Rearrange Spaces Between Words/README_EN.md b/solution/1500-1599/1592.Rearrange Spaces Between Words/README_EN.md index 4a24ce2e2c795..bf5f940de2152 100644 --- a/solution/1500-1599/1592.Rearrange Spaces Between Words/README_EN.md +++ b/solution/1500-1599/1592.Rearrange Spaces Between Words/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return (' ' * (cnt // m)).join(words) + ' ' * (cnt % m) ``` -### **Java** - ```java class Solution { public String reorderSpaces(String text) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **Go** - ```go func reorderSpaces(text string) string { cnt := strings.Count(text, " ") @@ -96,8 +92,6 @@ func reorderSpaces(text string) string { } ``` -### **TypeScript** - ```ts function reorderSpaces(text: string): string { let count = 0; @@ -119,8 +113,6 @@ function reorderSpaces(text: string): string { } ``` -### **Rust** - ```rust impl Solution { fn create_spaces(n: usize) -> String { @@ -152,10 +144,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1593.Split a String Into the Max Number of Unique Substrings/README.md b/solution/1500-1599/1593.Split a String Into the Max Number of Unique Substrings/README.md index f528d164fea71..ea6573c810376 100644 --- a/solution/1500-1599/1593.Split a String Into the Max Number of Unique Substrings/README.md +++ b/solution/1500-1599/1593.Split a String Into the Max Number of Unique Substrings/README.md @@ -50,18 +50,12 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 经典 DFS 回溯问题。 -### **Python3** - - - ```python class Solution: def maxUniqueSplit(self, s: str) -> int: @@ -82,10 +76,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private Set vis = new HashSet<>(); @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func maxUniqueSplit(s string) int { ans := 1 @@ -173,10 +159,6 @@ func maxUniqueSplit(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1593.Split a String Into the Max Number of Unique Substrings/README_EN.md b/solution/1500-1599/1593.Split a String Into the Max Number of Unique Substrings/README_EN.md index cbf428e27eca9..279fc5022ddc2 100644 --- a/solution/1500-1599/1593.Split a String Into the Max Number of Unique Substrings/README_EN.md +++ b/solution/1500-1599/1593.Split a String Into the Max Number of Unique Substrings/README_EN.md @@ -49,12 +49,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python class Solution: def maxUniqueSplit(self, s: str) -> int: @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private Set vis = new HashSet<>(); @@ -105,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +131,6 @@ public: }; ``` -### **Go** - ```go func maxUniqueSplit(s string) int { ans := 1 @@ -164,10 +156,6 @@ func maxUniqueSplit(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1594.Maximum Non Negative Product in a Matrix/README.md b/solution/1500-1599/1594.Maximum Non Negative Product in a Matrix/README.md index 45282b25e336f..30e856922114b 100644 --- a/solution/1500-1599/1594.Maximum Non Negative Product in a Matrix/README.md +++ b/solution/1500-1599/1594.Maximum Non Negative Product in a Matrix/README.md @@ -52,18 +52,12 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 时间复杂度 $O(m\times n)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数。 -### **Python3** - - - ```python class Solution: def maxProductPath(self, grid: List[List[int]]) -> int: @@ -87,10 +81,6 @@ class Solution: return -1 if ans < 0 else ans % mod ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -127,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; const int mod = 1e9 + 7; @@ -165,8 +153,6 @@ public: }; ``` -### **Go** - ```go func maxProductPath(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -207,10 +193,6 @@ func maxProductPath(grid [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1594.Maximum Non Negative Product in a Matrix/README_EN.md b/solution/1500-1599/1594.Maximum Non Negative Product in a Matrix/README_EN.md index a87b28669d0b8..2fa6a78d00dde 100644 --- a/solution/1500-1599/1594.Maximum Non Negative Product in a Matrix/README_EN.md +++ b/solution/1500-1599/1594.Maximum Non Negative Product in a Matrix/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return -1 if ans < 0 else ans % mod ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; const int mod = 1e9 + 7; @@ -152,8 +148,6 @@ public: }; ``` -### **Go** - ```go func maxProductPath(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -194,10 +188,6 @@ func maxProductPath(grid [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/README.md b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/README.md index c5588b8c0292d..6da1025b4a97b 100644 --- a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/README.md +++ b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:状态压缩 + 动态规划** +### 方法一:状态压缩 + 动态规划 我们记第一组的点数为 $m$,第二组的点数为 $n$。 @@ -89,10 +87,6 @@ $$ -### **Python3** - - - ```python class Solution: def connectTwoGroups(self, cost: List[List[int]]) -> int: @@ -110,30 +104,6 @@ class Solution: return f[m][-1] ``` -```python -class Solution: - def connectTwoGroups(self, cost: List[List[int]]) -> int: - m, n = len(cost), len(cost[0]) - f = [inf] * (1 << n) - f[0] = 0 - g = f[:] - for i in range(1, m + 1): - for j in range(1 << n): - g[j] = inf - for k in range(n): - if (j >> k & 1) == 0: - continue - c = cost[i - 1][k] - x = min(g[j ^ (1 << k)], f[j], f[j ^ (1 << k)]) + c - g[j] = min(g[j], x) - f = g[:] - return f[-1] -``` - -### **Java** - - - ```java class Solution { public int connectTwoGroups(List> cost) { @@ -161,6 +131,109 @@ class Solution { } ``` +```cpp +class Solution { +public: + int connectTwoGroups(vector>& cost) { + int m = cost.size(), n = cost[0].size(); + int f[m + 1][1 << n]; + memset(f, 0x3f, sizeof(f)); + f[0][0] = 0; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j < 1 << n; ++j) { + for (int k = 0; k < n; ++k) { + if (j >> k & 1) { + int c = cost[i - 1][k]; + int x = min({f[i][j ^ (1 << k)], f[i - 1][j], f[i - 1][j ^ (1 << k)]}) + c; + f[i][j] = min(f[i][j], x); + } + } + } + } + return f[m][(1 << n) - 1]; + } +}; +``` + +```go +func connectTwoGroups(cost [][]int) int { + m, n := len(cost), len(cost[0]) + const inf = 1 << 30 + f := make([][]int, m+1) + for i := range f { + f[i] = make([]int, 1<>k&1 == 1 { + f[i][j] = min(f[i][j], f[i][j^(1< Array(1 << n).fill(inf)); + f[0][0] = 0; + for (let i = 1; i <= m; ++i) { + for (let j = 0; j < 1 << n; ++j) { + for (let k = 0; k < n; ++k) { + if (((j >> k) & 1) === 1) { + const c = cost[i - 1][k]; + f[i][j] = Math.min(f[i][j], f[i][j ^ (1 << k)] + c); + f[i][j] = Math.min(f[i][j], f[i - 1][j] + c); + f[i][j] = Math.min(f[i][j], f[i - 1][j ^ (1 << k)] + c); + } + } + } + } + return f[m][(1 << n) - 1]; +} +``` + + + +### 方法二 + + + +```python +class Solution: + def connectTwoGroups(self, cost: List[List[int]]) -> int: + m, n = len(cost), len(cost[0]) + f = [inf] * (1 << n) + f[0] = 0 + g = f[:] + for i in range(1, m + 1): + for j in range(1 << n): + g[j] = inf + for k in range(n): + if (j >> k & 1) == 0: + continue + c = cost[i - 1][k] + x = min(g[j ^ (1 << k)], f[j], f[j ^ (1 << k)]) + c + g[j] = min(g[j], x) + f = g[:] + return f[-1] +``` + ```java class Solution { public int connectTwoGroups(List> cost) { @@ -189,32 +262,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int connectTwoGroups(vector>& cost) { - int m = cost.size(), n = cost[0].size(); - int f[m + 1][1 << n]; - memset(f, 0x3f, sizeof(f)); - f[0][0] = 0; - for (int i = 1; i <= m; ++i) { - for (int j = 0; j < 1 << n; ++j) { - for (int k = 0; k < n; ++k) { - if (j >> k & 1) { - int c = cost[i - 1][k]; - int x = min({f[i][j ^ (1 << k)], f[i - 1][j], f[i - 1][j ^ (1 << k)]}) + c; - f[i][j] = min(f[i][j], x); - } - } - } - } - return f[m][(1 << n) - 1]; - } -}; -``` - ```cpp class Solution { public: @@ -242,36 +289,6 @@ public: }; ``` -### **Go** - -```go -func connectTwoGroups(cost [][]int) int { - m, n := len(cost), len(cost[0]) - const inf = 1 << 30 - f := make([][]int, m+1) - for i := range f { - f[i] = make([]int, 1<>k&1 == 1 { - f[i][j] = min(f[i][j], f[i][j^(1< Array(1 << n).fill(inf)); - f[0][0] = 0; - for (let i = 1; i <= m; ++i) { - for (let j = 0; j < 1 << n; ++j) { - for (let k = 0; k < n; ++k) { - if (((j >> k) & 1) === 1) { - const c = cost[i - 1][k]; - f[i][j] = Math.min(f[i][j], f[i][j ^ (1 << k)] + c); - f[i][j] = Math.min(f[i][j], f[i - 1][j] + c); - f[i][j] = Math.min(f[i][j], f[i - 1][j ^ (1 << k)] + c); - } - } - } - } - return f[m][(1 << n) - 1]; -} -``` - ```ts function connectTwoGroups(cost: number[][]): number { const m = cost.length; @@ -353,10 +343,6 @@ function connectTwoGroups(cost: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/README_EN.md b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/README_EN.md index 07022a7ec01af..c06fad823f8d6 100644 --- a/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/README_EN.md +++ b/solution/1500-1599/1595.Minimum Cost to Connect Two Groups of Points/README_EN.md @@ -56,9 +56,9 @@ Note that there are multiple points connected to point 2 in the first group and ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,28 +77,6 @@ class Solution: return f[m][-1] ``` -```python -class Solution: - def connectTwoGroups(self, cost: List[List[int]]) -> int: - m, n = len(cost), len(cost[0]) - f = [inf] * (1 << n) - f[0] = 0 - g = f[:] - for i in range(1, m + 1): - for j in range(1 << n): - g[j] = inf - for k in range(n): - if (j >> k & 1) == 0: - continue - c = cost[i - 1][k] - x = min(g[j ^ (1 << k)], f[j], f[j ^ (1 << k)]) + c - g[j] = min(g[j], x) - f = g[:] - return f[-1] -``` - -### **Java** - ```java class Solution { public int connectTwoGroups(List> cost) { @@ -126,6 +104,109 @@ class Solution { } ``` +```cpp +class Solution { +public: + int connectTwoGroups(vector>& cost) { + int m = cost.size(), n = cost[0].size(); + int f[m + 1][1 << n]; + memset(f, 0x3f, sizeof(f)); + f[0][0] = 0; + for (int i = 1; i <= m; ++i) { + for (int j = 0; j < 1 << n; ++j) { + for (int k = 0; k < n; ++k) { + if (j >> k & 1) { + int c = cost[i - 1][k]; + int x = min({f[i][j ^ (1 << k)], f[i - 1][j], f[i - 1][j ^ (1 << k)]}) + c; + f[i][j] = min(f[i][j], x); + } + } + } + } + return f[m][(1 << n) - 1]; + } +}; +``` + +```go +func connectTwoGroups(cost [][]int) int { + m, n := len(cost), len(cost[0]) + const inf = 1 << 30 + f := make([][]int, m+1) + for i := range f { + f[i] = make([]int, 1<>k&1 == 1 { + f[i][j] = min(f[i][j], f[i][j^(1< Array(1 << n).fill(inf)); + f[0][0] = 0; + for (let i = 1; i <= m; ++i) { + for (let j = 0; j < 1 << n; ++j) { + for (let k = 0; k < n; ++k) { + if (((j >> k) & 1) === 1) { + const c = cost[i - 1][k]; + f[i][j] = Math.min(f[i][j], f[i][j ^ (1 << k)] + c); + f[i][j] = Math.min(f[i][j], f[i - 1][j] + c); + f[i][j] = Math.min(f[i][j], f[i - 1][j ^ (1 << k)] + c); + } + } + } + } + return f[m][(1 << n) - 1]; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def connectTwoGroups(self, cost: List[List[int]]) -> int: + m, n = len(cost), len(cost[0]) + f = [inf] * (1 << n) + f[0] = 0 + g = f[:] + for i in range(1, m + 1): + for j in range(1 << n): + g[j] = inf + for k in range(n): + if (j >> k & 1) == 0: + continue + c = cost[i - 1][k] + x = min(g[j ^ (1 << k)], f[j], f[j ^ (1 << k)]) + c + g[j] = min(g[j], x) + f = g[:] + return f[-1] +``` + ```java class Solution { public int connectTwoGroups(List> cost) { @@ -154,32 +235,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int connectTwoGroups(vector>& cost) { - int m = cost.size(), n = cost[0].size(); - int f[m + 1][1 << n]; - memset(f, 0x3f, sizeof(f)); - f[0][0] = 0; - for (int i = 1; i <= m; ++i) { - for (int j = 0; j < 1 << n; ++j) { - for (int k = 0; k < n; ++k) { - if (j >> k & 1) { - int c = cost[i - 1][k]; - int x = min({f[i][j ^ (1 << k)], f[i - 1][j], f[i - 1][j ^ (1 << k)]}) + c; - f[i][j] = min(f[i][j], x); - } - } - } - } - return f[m][(1 << n) - 1]; - } -}; -``` - ```cpp class Solution { public: @@ -207,36 +262,6 @@ public: }; ``` -### **Go** - -```go -func connectTwoGroups(cost [][]int) int { - m, n := len(cost), len(cost[0]) - const inf = 1 << 30 - f := make([][]int, m+1) - for i := range f { - f[i] = make([]int, 1<>k&1 == 1 { - f[i][j] = min(f[i][j], f[i][j^(1< Array(1 << n).fill(inf)); - f[0][0] = 0; - for (let i = 1; i <= m; ++i) { - for (let j = 0; j < 1 << n; ++j) { - for (let k = 0; k < n; ++k) { - if (((j >> k) & 1) === 1) { - const c = cost[i - 1][k]; - f[i][j] = Math.min(f[i][j], f[i][j ^ (1 << k)] + c); - f[i][j] = Math.min(f[i][j], f[i - 1][j] + c); - f[i][j] = Math.min(f[i][j], f[i - 1][j ^ (1 << k)] + c); - } - } - } - } - return f[m][(1 << n) - 1]; -} -``` - ```ts function connectTwoGroups(cost: number[][]): number { const m = cost.length; @@ -318,10 +316,6 @@ function connectTwoGroups(cost: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1596.The Most Frequently Ordered Products for Each Customer/README.md b/solution/1500-1599/1596.The Most Frequently Ordered Products for Each Customer/README.md index 5ab822bc945b1..93a280e425046 100644 --- a/solution/1500-1599/1596.The Most Frequently Ordered Products for Each Customer/README.md +++ b/solution/1500-1599/1596.The Most Frequently Ordered Products for Each Customer/README.md @@ -122,18 +122,12 @@ John (customer 5) 没有订购过商品, 所以我们并没有把 John 包含在 ## 解法 - - -**方法一:分组 + 窗口函数** +### 方法一:分组 + 窗口函数 我们将 `Orders` 表按照 `customer_id` 和 `product_id` 进行分组,然后利用窗口函数 `rank()`,按照 `customer_id` 分区,并且按照 `count(1)` 降序排列,得到每个 `customer_id` 下对应的 `product_id` 的排名,排名为 $1$ 的就是该 `customer_id` 下最经常订购的商品。 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -156,3 +150,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1500-1599/1596.The Most Frequently Ordered Products for Each Customer/README_EN.md b/solution/1500-1599/1596.The Most Frequently Ordered Products for Each Customer/README_EN.md index 888b1e1efcb60..e92f75b1cd0b3 100644 --- a/solution/1500-1599/1596.The Most Frequently Ordered Products for Each Customer/README_EN.md +++ b/solution/1500-1599/1596.The Most Frequently Ordered Products for Each Customer/README_EN.md @@ -120,14 +120,12 @@ John (customer 5) did not order anything, so we do not include them in the resul ## Solutions -**Solution 1: Group By + Window Function** +### Solution 1: Group By + Window Function We group the `Orders` table by `customer_id` and `product_id`, and then use the window function `rank()`, which assigns a rank to each `product_id` in each `customer_id` group based on its frequency in descending order. Finally, we select the `product_id` with a rank of $1$ for each `customer_id`, which is the most frequently ordered product for that `customer_id`. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -150,3 +148,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1500-1599/1597.Build Binary Expression Tree From Infix Expression/README.md b/solution/1500-1599/1597.Build Binary Expression Tree From Infix Expression/README.md index ad336b24b1335..4a151f3269ed0 100644 --- a/solution/1500-1599/1597.Build Binary Expression Tree From Infix Expression/README.md +++ b/solution/1500-1599/1597.Build Binary Expression Tree From Infix Expression/README.md @@ -60,30 +60,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1500-1599/1597.Build Binary Expression Tree From Infix Expression/README_EN.md b/solution/1500-1599/1597.Build Binary Expression Tree From Infix Expression/README_EN.md index 1755352914619..299b9207c4d6a 100644 --- a/solution/1500-1599/1597.Build Binary Expression Tree From Infix Expression/README_EN.md +++ b/solution/1500-1599/1597.Build Binary Expression Tree From Infix Expression/README_EN.md @@ -57,24 +57,4 @@ The third tree below is also not valid. Although it produces the same result and ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1500-1599/1598.Crawler Log Folder/README.md b/solution/1500-1599/1598.Crawler Log Folder/README.md index fd08c4970a8ce..458d9164d93b5 100644 --- a/solution/1500-1599/1598.Crawler Log Folder/README.md +++ b/solution/1500-1599/1598.Crawler Log Folder/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 直接模拟,记录深度的变化即可。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, logs: List[str]) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minOperations(String[] logs) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func minOperations(logs []string) int { ans := 0 @@ -144,27 +130,6 @@ func minOperations(logs []string) int { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int minOperations(char** logs, int logsSize) { - int depth = 0; - for (int i = 0; i < logsSize; i++) { - char* log = logs[i]; - if (!strcmp(log, "../")) { - depth = max(0, depth - 1); - } else if (strcmp(log, "./")) { - depth++; - } - } - return depth; -} -``` - -### **TypeScript** - ```ts function minOperations(logs: string[]): number { let depth = 0; @@ -179,8 +144,6 @@ function minOperations(logs: string[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_operations(logs: Vec) -> i32 { @@ -197,10 +160,23 @@ impl Solution { } ``` -### **...** - -``` +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +int minOperations(char** logs, int logsSize) { + int depth = 0; + for (int i = 0; i < logsSize; i++) { + char* log = logs[i]; + if (!strcmp(log, "../")) { + depth = max(0, depth - 1); + } else if (strcmp(log, "./")) { + depth++; + } + } + return depth; +} ``` + + diff --git a/solution/1500-1599/1598.Crawler Log Folder/README_EN.md b/solution/1500-1599/1598.Crawler Log Folder/README_EN.md index 061724372da2d..5531372bb113b 100644 --- a/solution/1500-1599/1598.Crawler Log Folder/README_EN.md +++ b/solution/1500-1599/1598.Crawler Log Folder/README_EN.md @@ -60,9 +60,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minOperations(String[] logs) { @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func minOperations(logs []string) int { ans := 0 @@ -131,27 +125,6 @@ func minOperations(logs []string) int { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int minOperations(char** logs, int logsSize) { - int depth = 0; - for (int i = 0; i < logsSize; i++) { - char* log = logs[i]; - if (!strcmp(log, "../")) { - depth = max(0, depth - 1); - } else if (strcmp(log, "./")) { - depth++; - } - } - return depth; -} -``` - -### **TypeScript** - ```ts function minOperations(logs: string[]): number { let depth = 0; @@ -166,8 +139,6 @@ function minOperations(logs: string[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_operations(logs: Vec) -> i32 { @@ -184,10 +155,23 @@ impl Solution { } ``` -### **...** - -``` +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +int minOperations(char** logs, int logsSize) { + int depth = 0; + for (int i = 0; i < logsSize; i++) { + char* log = logs[i]; + if (!strcmp(log, "../")) { + depth = max(0, depth - 1); + } else if (strcmp(log, "./")) { + depth++; + } + } + return depth; +} ``` + + diff --git a/solution/1500-1599/1599.Maximum Profit of Operating a Centennial Wheel/README.md b/solution/1500-1599/1599.Maximum Profit of Operating a Centennial Wheel/README.md index aaf8bae2442e3..e2a68a58af6a7 100644 --- a/solution/1500-1599/1599.Maximum Profit of Operating a Centennial Wheel/README.md +++ b/solution/1500-1599/1599.Maximum Profit of Operating a Centennial Wheel/README.md @@ -72,9 +72,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们直接模拟摩天轮的轮转过程,每次轮转时,累加等待的游客以及新到达的游客,然后最多 $4$ 个人上船,更新等待的游客数和利润,记录最大利润与其对应的轮转次数。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def minOperationsMaxProfit( @@ -107,10 +101,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minOperationsMaxProfit(int[] customers, int boardingCost, int runningCost) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func minOperationsMaxProfit(customers []int, boardingCost int, runningCost int) int { ans := -1 @@ -182,8 +168,6 @@ func minOperationsMaxProfit(customers []int, boardingCost int, runningCost int) } ``` -### **TypeScript** - ```ts function minOperationsMaxProfit( customers: number[], @@ -209,8 +193,6 @@ function minOperationsMaxProfit( } ``` -### **Rust** - ```rust impl Solution { pub fn min_operations_max_profit( @@ -242,10 +224,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1500-1599/1599.Maximum Profit of Operating a Centennial Wheel/README_EN.md b/solution/1500-1599/1599.Maximum Profit of Operating a Centennial Wheel/README_EN.md index a2e52e1701e86..e05fd99543aa5 100644 --- a/solution/1500-1599/1599.Maximum Profit of Operating a Centennial Wheel/README_EN.md +++ b/solution/1500-1599/1599.Maximum Profit of Operating a Centennial Wheel/README_EN.md @@ -67,7 +67,7 @@ The profit was never positive, so return -1. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We directly simulate the rotation process of the Ferris wheel. Each time it rotates, we add up the waiting customers and the newly arrived customers, then at most $4$ people get on the ride, update the number of waiting customers and profit, and record the maximum profit and its corresponding number of rotations. @@ -75,8 +75,6 @@ The time complexity is $O(n)$, where $n$ is the length of the `customers` array. -### **Python3** - ```python class Solution: def minOperationsMaxProfit( @@ -98,8 +96,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minOperationsMaxProfit(int[] customers, int boardingCost, int runningCost) { @@ -122,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +141,6 @@ public: }; ``` -### **Go** - ```go func minOperationsMaxProfit(customers []int, boardingCost int, runningCost int) int { ans := -1 @@ -171,8 +163,6 @@ func minOperationsMaxProfit(customers []int, boardingCost int, runningCost int) } ``` -### **TypeScript** - ```ts function minOperationsMaxProfit( customers: number[], @@ -198,8 +188,6 @@ function minOperationsMaxProfit( } ``` -### **Rust** - ```rust impl Solution { pub fn min_operations_max_profit( @@ -231,10 +219,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1600.Throne Inheritance/README.md b/solution/1600-1699/1600.Throne Inheritance/README.md index 00f4ddedb765c..1b4098cf93204 100644 --- a/solution/1600-1699/1600.Throne Inheritance/README.md +++ b/solution/1600-1699/1600.Throne Inheritance/README.md @@ -79,9 +79,7 @@ t.getInheritanceOrder(); // 返回 ["king", "andy", "matthew", "alex", "asha", " ## 解法 - - -**方法一:多叉树的前序遍历** +### 方法一:多叉树的前序遍历 可以发现,题目中王位的继承顺序,实际上是多叉树的前序遍历。 @@ -91,10 +89,6 @@ t.getInheritanceOrder(); // 返回 ["king", "andy", "matthew", "alex", "asha", " -### **Python3** - - - ```python class ThroneInheritance: def __init__(self, kingName: str): @@ -127,10 +121,6 @@ class ThroneInheritance: # param_3 = obj.getInheritanceOrder() ``` -### **Java** - - - ```java class ThroneInheritance { private Map> g = new HashMap<>(); @@ -175,8 +165,6 @@ class ThroneInheritance { */ ``` -### **C++** - ```cpp class ThroneInheritance { public: @@ -222,8 +210,6 @@ public: */ ``` -### **Go** - ```go type ThroneInheritance struct { g map[string][]string @@ -270,10 +256,6 @@ func (this *ThroneInheritance) GetInheritanceOrder() []string { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1600.Throne Inheritance/README_EN.md b/solution/1600-1699/1600.Throne Inheritance/README_EN.md index effde21ad576d..770a8830b50cd 100644 --- a/solution/1600-1699/1600.Throne Inheritance/README_EN.md +++ b/solution/1600-1699/1600.Throne Inheritance/README_EN.md @@ -75,9 +75,9 @@ t.getInheritanceOrder(); // return ["king", "andy", "ma ## Solutions - +### Solution 1 -### **Python3** + ```python class ThroneInheritance: @@ -111,8 +111,6 @@ class ThroneInheritance: # param_3 = obj.getInheritanceOrder() ``` -### **Java** - ```java class ThroneInheritance { private Map> g = new HashMap<>(); @@ -157,8 +155,6 @@ class ThroneInheritance { */ ``` -### **C++** - ```cpp class ThroneInheritance { public: @@ -204,8 +200,6 @@ public: */ ``` -### **Go** - ```go type ThroneInheritance struct { g map[string][]string @@ -252,10 +246,6 @@ func (this *ThroneInheritance) GetInheritanceOrder() []string { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1601.Maximum Number of Achievable Transfer Requests/README.md b/solution/1600-1699/1601.Maximum Number of Achievable Transfer Requests/README.md index 02ad3365c4c50..25de3715b5fc4 100644 --- a/solution/1600-1699/1601.Maximum Number of Achievable Transfer Requests/README.md +++ b/solution/1600-1699/1601.Maximum Number of Achievable Transfer Requests/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:二进制枚举** +### 方法一:二进制枚举 我们注意到,换楼请求列表长度不超过 $16$,因此我们可以使用二进制枚举的方法枚举所有的换楼请求列表。具体地,我们可以使用一个长度为 $16$ 的二进制数来表示一种换楼请求列表,其中第 $i$ 位为 $1$ 表示第 $i$ 个换楼请求被选中,为 $0$ 表示第 $i$ 个换楼请求不被选中。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def maximumRequests(self, n: int, requests: List[List[int]]) -> int: @@ -98,10 +92,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int m; @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -177,8 +165,6 @@ public: }; ``` -### **Go** - ```go func maximumRequests(n int, requests [][]int) (ans int) { m := len(requests) @@ -208,8 +194,6 @@ func maximumRequests(n int, requests [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function maximumRequests(n: number, requests: number[][]): number { const m = requests.length; @@ -244,8 +228,6 @@ function bitCount(i: number): number { } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -285,10 +267,6 @@ function bitCount(i) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1601.Maximum Number of Achievable Transfer Requests/README_EN.md b/solution/1600-1699/1601.Maximum Number of Achievable Transfer Requests/README_EN.md index 03c202689759d..5fb4196dd0cc4 100644 --- a/solution/1600-1699/1601.Maximum Number of Achievable Transfer Requests/README_EN.md +++ b/solution/1600-1699/1601.Maximum Number of Achievable Transfer Requests/README_EN.md @@ -58,9 +58,9 @@ We can achieve all the requests. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -81,8 +81,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int m; @@ -122,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +154,6 @@ public: }; ``` -### **Go** - ```go func maximumRequests(n int, requests [][]int) (ans int) { m := len(requests) @@ -189,8 +183,6 @@ func maximumRequests(n int, requests [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function maximumRequests(n: number, requests: number[][]): number { const m = requests.length; @@ -225,8 +217,6 @@ function bitCount(i: number): number { } ``` -### **JavaScript** - ```js /** * @param {number} n @@ -266,10 +256,6 @@ function bitCount(i) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/README.md b/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/README.md index b9b755778d935..3215307ad5b25 100644 --- a/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/README.md +++ b/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/README.md @@ -57,26 +57,14 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS BFS 层序遍历,找到 $u$ 所在层的右侧相邻节点。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。 -**方法二:DFS** - -DFS 先序遍历二叉树,首次搜索到 $u$ 时,标记目前层数 $d$,下次遇到同一层的节点时,即为目标节点。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -98,38 +86,6 @@ class Solution: q.append(root.right) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]: - def dfs(root, i): - nonlocal d, ans - if root is None or ans: - return - if d == i: - ans = root - return - if root == u: - d = i - return - dfs(root.left, i + 1) - dfs(root.right, i + 1) - - d = 0 - ans = None - dfs(root, 1) - return ans -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -169,6 +125,141 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* findNearestRightNode(TreeNode* root, TreeNode* u) { + queue q{{root}}; + while (q.size()) { + for (int i = q.size(); i; --i) { + root = q.front(); + q.pop(); + if (root == u) return i > 1 ? q.front() : nullptr; + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + } + return nullptr; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func findNearestRightNode(root *TreeNode, u *TreeNode) *TreeNode { + q := []*TreeNode{root} + for len(q) > 0 { + for i := len(q); i > 0; i-- { + root = q[0] + q = q[1:] + if root == u { + if i > 1 { + return q[0] + } + return nil + } + if root.Left != nil { + q = append(q, root.Left) + } + if root.Right != nil { + q = append(q, root.Right) + } + } + } + return nil +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} u + * @return {TreeNode} + */ +var findNearestRightNode = function (root, u) { + const q = [root]; + while (q.length) { + for (let i = q.length; i; --i) { + root = q.shift(); + if (root == u) { + return i > 1 ? q[0] : null; + } + if (root.left) { + q.push(root.left); + } + if (root.right) { + q.push(root.right); + } + } + } + return null; +}; +``` + + + +### 方法二:DFS + +DFS 先序遍历二叉树,首次搜索到 $u$ 时,标记目前层数 $d$,下次遇到同一层的节点时,即为目标节点。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]: + def dfs(root, i): + nonlocal d, ans + if root is None or ans: + return + if d == i: + ans = root + return + if root == u: + d = i + return + dfs(root.left, i + 1) + dfs(root.right, i + 1) + + d = 0 + ans = None + dfs(root, 1) + return ans +``` + ```java /** * Definition for a binary tree node. @@ -214,38 +305,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* findNearestRightNode(TreeNode* root, TreeNode* u) { - queue q{{root}}; - while (q.size()) { - for (int i = q.size(); i; --i) { - root = q.front(); - q.pop(); - if (root == u) return i > 1 ? q.front() : nullptr; - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } - } - return nullptr; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -286,41 +345,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func findNearestRightNode(root *TreeNode, u *TreeNode) *TreeNode { - q := []*TreeNode{root} - for len(q) > 0 { - for i := len(q); i > 0; i-- { - root = q[0] - q = q[1:] - if root == u { - if i > 1 { - return q[0] - } - return nil - } - if root.Left != nil { - q = append(q, root.Left) - } - if root.Right != nil { - q = append(q, root.Right) - } - } - } - return nil -} -``` - ```go /** * Definition for a binary tree node. @@ -354,42 +378,6 @@ func findNearestRightNode(root *TreeNode, u *TreeNode) *TreeNode { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @param {TreeNode} u - * @return {TreeNode} - */ -var findNearestRightNode = function (root, u) { - const q = [root]; - while (q.length) { - for (let i = q.length; i; --i) { - root = q.shift(); - if (root == u) { - return i > 1 ? q[0] : null; - } - if (root.left) { - q.push(root.left); - } - if (root.right) { - q.push(root.right); - } - } - } - return null; -}; -``` - ```js /** * Definition for a binary tree node. @@ -427,10 +415,6 @@ var findNearestRightNode = function (root, u) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/README_EN.md b/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/README_EN.md index 7619d21b5e044..1764c0422d617 100644 --- a/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/README_EN.md +++ b/solution/1600-1699/1602.Find Nearest Right Node in Binary Tree/README_EN.md @@ -35,12 +35,10 @@ ## Solutions -BFS or DFS. +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -62,36 +60,6 @@ class Solution: q.append(root.right) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]: - def dfs(root, i): - nonlocal d, ans - if root is None or ans: - return - if d == i: - ans = root - return - if root == u: - d = i - return - dfs(root.left, i + 1) - dfs(root.right, i + 1) - - d = 0 - ans = None - dfs(root, 1) - return ans -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -131,6 +99,137 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* findNearestRightNode(TreeNode* root, TreeNode* u) { + queue q{{root}}; + while (q.size()) { + for (int i = q.size(); i; --i) { + root = q.front(); + q.pop(); + if (root == u) return i > 1 ? q.front() : nullptr; + if (root->left) q.push(root->left); + if (root->right) q.push(root->right); + } + } + return nullptr; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func findNearestRightNode(root *TreeNode, u *TreeNode) *TreeNode { + q := []*TreeNode{root} + for len(q) > 0 { + for i := len(q); i > 0; i-- { + root = q[0] + q = q[1:] + if root == u { + if i > 1 { + return q[0] + } + return nil + } + if root.Left != nil { + q = append(q, root.Left) + } + if root.Right != nil { + q = append(q, root.Right) + } + } + } + return nil +} +``` + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} u + * @return {TreeNode} + */ +var findNearestRightNode = function (root, u) { + const q = [root]; + while (q.length) { + for (let i = q.length; i; --i) { + root = q.shift(); + if (root == u) { + return i > 1 ? q[0] : null; + } + if (root.left) { + q.push(root.left); + } + if (root.right) { + q.push(root.right); + } + } + } + return null; +}; +``` + + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]: + def dfs(root, i): + nonlocal d, ans + if root is None or ans: + return + if d == i: + ans = root + return + if root == u: + d = i + return + dfs(root.left, i + 1) + dfs(root.right, i + 1) + + d = 0 + ans = None + dfs(root, 1) + return ans +``` + ```java /** * Definition for a binary tree node. @@ -176,38 +275,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* findNearestRightNode(TreeNode* root, TreeNode* u) { - queue q{{root}}; - while (q.size()) { - for (int i = q.size(); i; --i) { - root = q.front(); - q.pop(); - if (root == u) return i > 1 ? q.front() : nullptr; - if (root->left) q.push(root->left); - if (root->right) q.push(root->right); - } - } - return nullptr; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -248,41 +315,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func findNearestRightNode(root *TreeNode, u *TreeNode) *TreeNode { - q := []*TreeNode{root} - for len(q) > 0 { - for i := len(q); i > 0; i-- { - root = q[0] - q = q[1:] - if root == u { - if i > 1 { - return q[0] - } - return nil - } - if root.Left != nil { - q = append(q, root.Left) - } - if root.Right != nil { - q = append(q, root.Right) - } - } - } - return nil -} -``` - ```go /** * Definition for a binary tree node. @@ -316,42 +348,6 @@ func findNearestRightNode(root *TreeNode, u *TreeNode) *TreeNode { } ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @param {TreeNode} u - * @return {TreeNode} - */ -var findNearestRightNode = function (root, u) { - const q = [root]; - while (q.length) { - for (let i = q.length; i; --i) { - root = q.shift(); - if (root == u) { - return i > 1 ? q[0] : null; - } - if (root.left) { - q.push(root.left); - } - if (root.right) { - q.push(root.right); - } - } - } - return null; -}; -``` - ```js /** * Definition for a binary tree node. @@ -389,10 +385,6 @@ var findNearestRightNode = function (root, u) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1603.Design Parking System/README.md b/solution/1600-1699/1603.Design Parking System/README.md index 8588e875bb5f4..d42809c6b9654 100644 --- a/solution/1600-1699/1603.Design Parking System/README.md +++ b/solution/1600-1699/1603.Design Parking System/README.md @@ -46,9 +46,7 @@ parkingSystem.addCar(1); // 返回 false ,因为没有空的大车位,唯一 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 为每种车维护一个计数器,初始值为车位的数目。此后,每来一辆车,就将对应类型的计数器减 `1`。当计数器为 `0` 时,说明车位已满。 @@ -56,10 +54,6 @@ parkingSystem.addCar(1); // 返回 false ,因为没有空的大车位,唯一 -### **Python3** - - - ```python class ParkingSystem: def __init__(self, big: int, medium: int, small: int): @@ -77,10 +71,6 @@ class ParkingSystem: # param_1 = obj.addCar(carType) ``` -### **Java** - - - ```java class ParkingSystem { private int[] cnt; @@ -105,8 +95,6 @@ class ParkingSystem { */ ``` -### **C++** - ```cpp class ParkingSystem { public: @@ -130,8 +118,6 @@ public: */ ``` -### **Go** - ```go type ParkingSystem struct { cnt []int @@ -156,8 +142,6 @@ func (this *ParkingSystem) AddCar(carType int) bool { */ ``` -### **TypeScript** - ```ts class ParkingSystem { private count: [number, number, number]; @@ -182,8 +166,6 @@ class ParkingSystem { */ ``` -### **Rust** - ```rust struct ParkingSystem { count: [i32; 3], @@ -215,7 +197,30 @@ impl ParkingSystem { */ ``` -### **C** +```cs +public class ParkingSystem { + + private List cnt; + + public ParkingSystem(int big, int medium, int small) { + cnt = new List() {0 , big, medium, small}; + } + + public bool AddCar(int carType) { + if (cnt[carType] == 0) { + return false; + } + --cnt[carType]; + return true; + } +} + +/** + * Your ParkingSystem object will be instantiated and called as such: + * ParkingSystem obj = new ParkingSystem(big, medium, small); + * bool param_1 = obj.AddCar(carType); + */ +``` ```c typedef struct { @@ -253,37 +258,6 @@ void parkingSystemFree(ParkingSystem* obj) { */ ``` -### **C#** - -```cs -public class ParkingSystem { - - private List cnt; - - public ParkingSystem(int big, int medium, int small) { - cnt = new List() {0 , big, medium, small}; - } - - public bool AddCar(int carType) { - if (cnt[carType] == 0) { - return false; - } - --cnt[carType]; - return true; - } -} - -/** - * Your ParkingSystem object will be instantiated and called as such: - * ParkingSystem obj = new ParkingSystem(big, medium, small); - * bool param_1 = obj.AddCar(carType); - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1603.Design Parking System/README_EN.md b/solution/1600-1699/1603.Design Parking System/README_EN.md index 030969cd3b52d..5ecba7a6979ce 100644 --- a/solution/1600-1699/1603.Design Parking System/README_EN.md +++ b/solution/1600-1699/1603.Design Parking System/README_EN.md @@ -42,9 +42,9 @@ parkingSystem.addCar(1); // return false because there is no available slot for ## Solutions - +### Solution 1 -### **Python3** + ```python class ParkingSystem: @@ -63,8 +63,6 @@ class ParkingSystem: # param_1 = obj.addCar(carType) ``` -### **Java** - ```java class ParkingSystem { private int[] cnt; @@ -89,8 +87,6 @@ class ParkingSystem { */ ``` -### **C++** - ```cpp class ParkingSystem { public: @@ -114,8 +110,6 @@ public: */ ``` -### **Go** - ```go type ParkingSystem struct { cnt []int @@ -140,8 +134,6 @@ func (this *ParkingSystem) AddCar(carType int) bool { */ ``` -### **TypeScript** - ```ts class ParkingSystem { private count: [number, number, number]; @@ -166,8 +158,6 @@ class ParkingSystem { */ ``` -### **Rust** - ```rust struct ParkingSystem { count: [i32; 3], @@ -199,7 +189,30 @@ impl ParkingSystem { */ ``` -### **C** +```cs +public class ParkingSystem { + + private List cnt; + + public ParkingSystem(int big, int medium, int small) { + cnt = new List() {0 , big, medium, small}; + } + + public bool AddCar(int carType) { + if (cnt[carType] == 0) { + return false; + } + --cnt[carType]; + return true; + } +} + +/** + * Your ParkingSystem object will be instantiated and called as such: + * ParkingSystem obj = new ParkingSystem(big, medium, small); + * bool param_1 = obj.AddCar(carType); + */ +``` ```c typedef struct { @@ -237,37 +250,6 @@ void parkingSystemFree(ParkingSystem* obj) { */ ``` -### **C#** - -```cs -public class ParkingSystem { - - private List cnt; - - public ParkingSystem(int big, int medium, int small) { - cnt = new List() {0 , big, medium, small}; - } - - public bool AddCar(int carType) { - if (cnt[carType] == 0) { - return false; - } - --cnt[carType]; - return true; - } -} - -/** - * Your ParkingSystem object will be instantiated and called as such: - * ParkingSystem obj = new ParkingSystem(big, medium, small); - * bool param_1 = obj.AddCar(carType); - */ -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1604.Alert Using Same Key-Card Three or More Times in a One Hour Period/README.md b/solution/1600-1699/1604.Alert Using Same Key-Card Three or More Times in a One Hour Period/README.md index b179a6cb4f242..893c5ef2f6033 100644 --- a/solution/1600-1699/1604.Alert Using Same Key-Card Three or More Times in a One Hour Period/README.md +++ b/solution/1600-1699/1604.Alert Using Same Key-Card Three or More Times in a One Hour Period/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:哈希表 + 排序** +### 方法一:哈希表 + 排序 我们先用哈希表 $d$ 记录每个员工的所有打卡时间。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List alertNames(String[] keyName, String[] keyTime) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func alertNames(keyName []string, keyTime []string) (ans []string) { d := map[string][]int{} @@ -183,10 +169,6 @@ func alertNames(keyName []string, keyTime []string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1604.Alert Using Same Key-Card Three or More Times in a One Hour Period/README_EN.md b/solution/1600-1699/1604.Alert Using Same Key-Card Three or More Times in a One Hour Period/README_EN.md index ee72c0143e0ef..49e8ee377bf89 100644 --- a/solution/1600-1699/1604.Alert Using Same Key-Card Three or More Times in a One Hour Period/README_EN.md +++ b/solution/1600-1699/1604.Alert Using Same Key-Card Three or More Times in a One Hour Period/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List alertNames(String[] keyName, String[] keyTime) { @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +131,6 @@ public: }; ``` -### **Go** - ```go func alertNames(keyName []string, keyTime []string) (ans []string) { d := map[string][]int{} @@ -163,10 +157,6 @@ func alertNames(keyName []string, keyTime []string) (ans []string) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/README.md b/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/README.md index 0bdb37be29d4e..0f68b5e17f569 100644 --- a/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/README.md +++ b/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/README.md @@ -74,9 +74,7 @@ ## 解法 - - -**方法一:贪心 + 构造** +### 方法一:贪心 + 构造 我们可以先初始化一个 $m$ 行 $n$ 列的答案矩阵 $ans$。 @@ -92,10 +90,6 @@ -### **Python3** - - - ```python class Solution: def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: @@ -110,10 +104,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] restoreMatrix(int[] rowSum, int[] colSum) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func restoreMatrix(rowSum []int, colSum []int) [][]int { m, n := len(rowSum), len(colSum) @@ -175,15 +161,8 @@ func restoreMatrix(rowSum []int, colSum []int) [][]int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} rowSum - * @param {number[]} colSum - * @return {number[][]} - */ -var restoreMatrix = function (rowSum, colSum) { +```ts +function restoreMatrix(rowSum: number[], colSum: number[]): number[][] { const m = rowSum.length; const n = colSum.length; const ans = Array.from(new Array(m), () => new Array(n).fill(0)); @@ -196,13 +175,16 @@ var restoreMatrix = function (rowSum, colSum) { } } return ans; -}; +} ``` -### **TypeScript** - -```ts -function restoreMatrix(rowSum: number[], colSum: number[]): number[][] { +```js +/** + * @param {number[]} rowSum + * @param {number[]} colSum + * @return {number[][]} + */ +var restoreMatrix = function (rowSum, colSum) { const m = rowSum.length; const n = colSum.length; const ans = Array.from(new Array(m), () => new Array(n).fill(0)); @@ -215,13 +197,9 @@ function restoreMatrix(rowSum: number[], colSum: number[]): number[][] { } } return ans; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/README_EN.md b/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/README_EN.md index 22ad3fba51702..da9992549690b 100644 --- a/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/README_EN.md +++ b/solution/1600-1699/1605.Find Valid Matrix Given Row and Column Sums/README_EN.md @@ -47,9 +47,9 @@ Another possible matrix is: [[1,2], ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] restoreMatrix(int[] rowSum, int[] colSum) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +103,6 @@ public: }; ``` -### **Go** - ```go func restoreMatrix(rowSum []int, colSum []int) [][]int { m, n := len(rowSum), len(colSum) @@ -128,15 +122,8 @@ func restoreMatrix(rowSum []int, colSum []int) [][]int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} rowSum - * @param {number[]} colSum - * @return {number[][]} - */ -var restoreMatrix = function (rowSum, colSum) { +```ts +function restoreMatrix(rowSum: number[], colSum: number[]): number[][] { const m = rowSum.length; const n = colSum.length; const ans = Array.from(new Array(m), () => new Array(n).fill(0)); @@ -149,13 +136,16 @@ var restoreMatrix = function (rowSum, colSum) { } } return ans; -}; +} ``` -### **TypeScript** - -```ts -function restoreMatrix(rowSum: number[], colSum: number[]): number[][] { +```js +/** + * @param {number[]} rowSum + * @param {number[]} colSum + * @return {number[][]} + */ +var restoreMatrix = function (rowSum, colSum) { const m = rowSum.length; const n = colSum.length; const ans = Array.from(new Array(m), () => new Array(n).fill(0)); @@ -168,13 +158,9 @@ function restoreMatrix(rowSum: number[], colSum: number[]): number[][] { } } return ans; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/README.md b/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/README.md index 07b42258091d8..a9cc345e8d8ab 100644 --- a/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/README.md +++ b/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/README.md @@ -83,9 +83,7 @@ ## 解法 - - -**方法一:有序集合 + 优先队列** +### 方法一:有序集合 + 优先队列 题目求的是最繁忙的服务器列表,因此可以想到用**哈希表**记录每个服务器处理的任务数,然后获取所有处理了最大任务数 mx 的服务器列表即可。关键的问题就在于,求出每个任务分配给了哪台服务器处理。 @@ -99,10 +97,6 @@ -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -130,10 +124,6 @@ class Solution: return [i for i, v in enumerate(cnt) if v == mx] ``` -### **Java** - - - ```java class Solution { public List busiestServers(int k, int[] arrival, int[] load) { @@ -175,7 +165,37 @@ class Solution { } ``` -### **Go** +```cpp +class Solution { +public: + vector busiestServers(int k, vector& arrival, vector& load) { + set free; + for (int i = 0; i < k; ++i) free.insert(i); + priority_queue, vector>, greater<>> busy; + vector cnt(k); + for (int i = 0; i < arrival.size(); ++i) { + int start = arrival[i], end = start + load[i]; + while (!busy.empty() && busy.top().first <= start) { + free.insert(busy.top().second); + busy.pop(); + } + if (free.empty()) continue; + auto p = free.lower_bound(i % k); + if (p == free.end()) p = free.begin(); + int server = *p; + ++cnt[server]; + busy.emplace(end, server); + free.erase(server); + } + int mx = *max_element(cnt.begin(), cnt.end()); + vector ans; + for (int i = 0; i < k; ++i) + if (cnt[i] == mx) + ans.push_back(i); + return ans; + } +}; +``` ```go func busiestServers(k int, arrival, load []int) (ans []int) { @@ -221,10 +241,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/README_EN.md b/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/README_EN.md index bba08c2a31c62..16d77520039eb 100644 --- a/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/README_EN.md +++ b/solution/1600-1699/1606.Find Servers That Handled Most Number of Requests/README_EN.md @@ -63,9 +63,9 @@ Server 0 handled two requests, while servers 1 and 2 handled one request each. H ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedList @@ -94,8 +94,6 @@ class Solution: return [i for i, v in enumerate(cnt) if v == mx] ``` -### **Java** - ```java class Solution { public List busiestServers(int k, int[] arrival, int[] load) { @@ -137,7 +135,37 @@ class Solution { } ``` -### **Go** +```cpp +class Solution { +public: + vector busiestServers(int k, vector& arrival, vector& load) { + set free; + for (int i = 0; i < k; ++i) free.insert(i); + priority_queue, vector>, greater<>> busy; + vector cnt(k); + for (int i = 0; i < arrival.size(); ++i) { + int start = arrival[i], end = start + load[i]; + while (!busy.empty() && busy.top().first <= start) { + free.insert(busy.top().second); + busy.pop(); + } + if (free.empty()) continue; + auto p = free.lower_bound(i % k); + if (p == free.end()) p = free.begin(); + int server = *p; + ++cnt[server]; + busy.emplace(end, server); + free.erase(server); + } + int mx = *max_element(cnt.begin(), cnt.end()); + vector ans; + for (int i = 0; i < k; ++i) + if (cnt[i] == mx) + ans.push_back(i); + return ans; + } +}; +``` ```go func busiestServers(k int, arrival, load []int) (ans []int) { @@ -183,10 +211,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1607.Sellers With No Sales/README.md b/solution/1600-1699/1607.Sellers With No Sales/README.md index a5bf63bca1d14..c55374b71519a 100644 --- a/solution/1600-1699/1607.Sellers With No Sales/README.md +++ b/solution/1600-1699/1607.Sellers With No Sales/README.md @@ -106,16 +106,12 @@ Frank 在 2019 年卖出 1 次, 在 2020 年没有卖出。 ## 解法 - - -**方法一:左连接 + 分组 + 筛选** +### 方法一:左连接 + 分组 + 筛选 我们可以使用左连接,将 `Seller` 表与 `Orders` 表按照字段 `seller_id` 连接,然后按照 `seller_id` 分组,统计每个卖家在 $2020$ 年的卖出次数,最后筛选出卖出次数为 $0$ 的卖家。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT seller_name @@ -128,3 +124,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1600-1699/1607.Sellers With No Sales/README_EN.md b/solution/1600-1699/1607.Sellers With No Sales/README_EN.md index f8074bd3d3101..782d6927f6512 100644 --- a/solution/1600-1699/1607.Sellers With No Sales/README_EN.md +++ b/solution/1600-1699/1607.Sellers With No Sales/README_EN.md @@ -104,14 +104,12 @@ Frank made 1 sale in 2019 but no sales in 2020. ## Solutions -**Solution 1: LEFT JOIN + GROUP BY + FILTER** +### Solution 1: LEFT JOIN + GROUP BY + FILTER We can use a left join to join the `Seller` table with the `Orders` table on the condition `seller_id`, and then group by `seller_id` to count the number of sales for each seller in the year $2020$. Finally, we can filter out the sellers with zero sales. -### **SQL** - ```sql # Write your MySQL query statement below SELECT seller_name @@ -124,3 +122,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/README.md b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/README.md index 6878eac3fcb7c..f9be0cefa38e4 100644 --- a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/README.md +++ b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/README.md @@ -55,28 +55,14 @@ x 不能取更大的值,因为 nums 中只有两个元素。 ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 在 $[1..n]$ 范围内枚举 $x$,然后统计数组中大于等于 $x$ 的元素个数,记为 $cnt$。若存在 $cnt$ 与 $x$ 相等,直接返回 $x$。 时间复杂度 $O(n^2)$。 -**方法二:排序 + 二分查找** - -我们也可以先对 `nums` 进行排序。 - -接下来同样枚举 $x$,利用二分查找,找到 `nums` 中第一个大于等于 $x$ 的元素,快速统计出 `nums` 中大于等于 $x$ 的元素个数。 - -时间复杂度 $O(n\log n)$。 - -### **Python3** - - - ```python class Solution: def specialArray(self, nums: List[int]) -> int: @@ -87,22 +73,6 @@ class Solution: return -1 ``` -```python -class Solution: - def specialArray(self, nums: List[int]) -> int: - nums.sort() - n = len(nums) - for x in range(1, n + 1): - cnt = n - bisect_left(nums, x) - if cnt == x: - return x - return -1 -``` - -### **Java** - - - ```java class Solution { public int specialArray(int[] nums) { @@ -122,6 +92,93 @@ class Solution { } ``` +```cpp +class Solution { +public: + int specialArray(vector& nums) { + for (int x = 1; x <= nums.size(); ++x) { + int cnt = 0; + for (int v : nums) cnt += v >= x; + if (cnt == x) return x; + } + return -1; + } +}; +``` + +```go +func specialArray(nums []int) int { + for x := 1; x <= len(nums); x++ { + cnt := 0 + for _, v := range nums { + if v >= x { + cnt++ + } + } + if cnt == x { + return x + } + } + return -1 +} +``` + +```ts +function specialArray(nums: number[]): number { + const n = nums.length; + for (let i = 0; i <= n; i++) { + if (i === nums.reduce((r, v) => r + (v >= i ? 1 : 0), 0)) { + return i; + } + } + return -1; +} +``` + +```rust +impl Solution { + pub fn special_array(nums: Vec) -> i32 { + let n = nums.len() as i32; + for i in 0..=n { + let mut count = 0; + for &num in nums.iter() { + if num >= i { + count += 1; + } + } + if count == i { + return i; + } + } + -1 + } +} +``` + + + +### 方法二:排序 + 二分查找 + +我们也可以先对 `nums` 进行排序。 + +接下来同样枚举 $x$,利用二分查找,找到 `nums` 中第一个大于等于 $x$ 的元素,快速统计出 `nums` 中大于等于 $x$ 的元素个数。 + +时间复杂度 $O(n\log n)$。 + + + +```python +class Solution: + def specialArray(self, nums: List[int]) -> int: + nums.sort() + n = len(nums) + for x in range(1, n + 1): + cnt = n - bisect_left(nums, x) + if cnt == x: + return x + return -1 +``` + ```java class Solution { public int specialArray(int[] nums) { @@ -147,22 +204,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int specialArray(vector& nums) { - for (int x = 1; x <= nums.size(); ++x) { - int cnt = 0; - for (int v : nums) cnt += v >= x; - if (cnt == x) return x; - } - return -1; - } -}; -``` - ```cpp class Solution { public: @@ -178,25 +219,6 @@ public: }; ``` -### **Go** - -```go -func specialArray(nums []int) int { - for x := 1; x <= len(nums); x++ { - cnt := 0 - for _, v := range nums { - if v >= x { - cnt++ - } - } - if cnt == x { - return x - } - } - return -1 -} -``` - ```go func specialArray(nums []int) int { sort.Ints(nums) @@ -220,20 +242,6 @@ func specialArray(nums []int) int { } ``` -### **TypeScript** - -```ts -function specialArray(nums: number[]): number { - const n = nums.length; - for (let i = 0; i <= n; i++) { - if (i === nums.reduce((r, v) => r + (v >= i ? 1 : 0), 0)) { - return i; - } - } - return -1; -} -``` - ```ts function specialArray(nums: number[]): number { const n = nums.length; @@ -257,28 +265,6 @@ function specialArray(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn special_array(nums: Vec) -> i32 { - let n = nums.len() as i32; - for i in 0..=n { - let mut count = 0; - for &num in nums.iter() { - if num >= i { - count += 1; - } - } - if count == i { - return i; - } - } - -1 - } -} -``` - ```rust use std::cmp::Ordering; impl Solution { @@ -311,10 +297,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/README_EN.md b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/README_EN.md index a6656f8cfb5ec..b27e6afb7d96d 100644 --- a/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/README_EN.md +++ b/solution/1600-1699/1608.Special Array With X Elements Greater Than or Equal X/README_EN.md @@ -49,9 +49,9 @@ x cannot be greater since there are only 2 numbers in nums. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,20 +63,6 @@ class Solution: return -1 ``` -```python -class Solution: - def specialArray(self, nums: List[int]) -> int: - nums.sort() - n = len(nums) - for x in range(1, n + 1): - cnt = n - bisect_left(nums, x) - if cnt == x: - return x - return -1 -``` - -### **Java** - ```java class Solution { public int specialArray(int[] nums) { @@ -96,6 +82,87 @@ class Solution { } ``` +```cpp +class Solution { +public: + int specialArray(vector& nums) { + for (int x = 1; x <= nums.size(); ++x) { + int cnt = 0; + for (int v : nums) cnt += v >= x; + if (cnt == x) return x; + } + return -1; + } +}; +``` + +```go +func specialArray(nums []int) int { + for x := 1; x <= len(nums); x++ { + cnt := 0 + for _, v := range nums { + if v >= x { + cnt++ + } + } + if cnt == x { + return x + } + } + return -1 +} +``` + +```ts +function specialArray(nums: number[]): number { + const n = nums.length; + for (let i = 0; i <= n; i++) { + if (i === nums.reduce((r, v) => r + (v >= i ? 1 : 0), 0)) { + return i; + } + } + return -1; +} +``` + +```rust +impl Solution { + pub fn special_array(nums: Vec) -> i32 { + let n = nums.len() as i32; + for i in 0..=n { + let mut count = 0; + for &num in nums.iter() { + if num >= i { + count += 1; + } + } + if count == i { + return i; + } + } + -1 + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def specialArray(self, nums: List[int]) -> int: + nums.sort() + n = len(nums) + for x in range(1, n + 1): + cnt = n - bisect_left(nums, x) + if cnt == x: + return x + return -1 +``` + ```java class Solution { public int specialArray(int[] nums) { @@ -121,22 +188,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int specialArray(vector& nums) { - for (int x = 1; x <= nums.size(); ++x) { - int cnt = 0; - for (int v : nums) cnt += v >= x; - if (cnt == x) return x; - } - return -1; - } -}; -``` - ```cpp class Solution { public: @@ -152,25 +203,6 @@ public: }; ``` -### **Go** - -```go -func specialArray(nums []int) int { - for x := 1; x <= len(nums); x++ { - cnt := 0 - for _, v := range nums { - if v >= x { - cnt++ - } - } - if cnt == x { - return x - } - } - return -1 -} -``` - ```go func specialArray(nums []int) int { sort.Ints(nums) @@ -194,20 +226,6 @@ func specialArray(nums []int) int { } ``` -### **TypeScript** - -```ts -function specialArray(nums: number[]): number { - const n = nums.length; - for (let i = 0; i <= n; i++) { - if (i === nums.reduce((r, v) => r + (v >= i ? 1 : 0), 0)) { - return i; - } - } - return -1; -} -``` - ```ts function specialArray(nums: number[]): number { const n = nums.length; @@ -231,28 +249,6 @@ function specialArray(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn special_array(nums: Vec) -> i32 { - let n = nums.len() as i32; - for i in 0..=n { - let mut count = 0; - for &num in nums.iter() { - if num >= i { - count += 1; - } - } - if count == i { - return i; - } - } - -1 - } -} -``` - ```rust use std::cmp::Ordering; impl Solution { @@ -285,10 +281,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1609.Even Odd Tree/README.md b/solution/1600-1699/1609.Even Odd Tree/README.md index bdd1d3fec74d0..a4b48a1266b04 100644 --- a/solution/1600-1699/1609.Even Odd Tree/README.md +++ b/solution/1600-1699/1609.Even Odd Tree/README.md @@ -82,26 +82,14 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS BFS 逐层遍历,每层按照奇偶性判断,每层的节点值都是偶数或奇数,且严格递增或递减。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。 -**方法二:DFS** - -DFS 先序遍历二叉树,同样根据节点所在层的奇偶性判断是否满足条件,遍历过程中用哈希表记录每一层最近访问到的节点值。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -130,35 +118,6 @@ class Solution: return True ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: - def dfs(root, i): - if root is None: - return True - even = i % 2 == 0 - prev = d.get(i, 0 if even else inf) - if even and (root.val % 2 == 0 or prev >= root.val): - return False - if not even and (root.val % 2 == 1 or prev <= root.val): - return False - d[i] = root.val - return dfs(root.left, i + 1) and dfs(root.right, i + 1) - - d = {} - return dfs(root, 0) -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -205,49 +164,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private Map d = new HashMap<>(); - - public boolean isEvenOddTree(TreeNode root) { - return dfs(root, 0); - } - - private boolean dfs(TreeNode root, int i) { - if (root == null) { - return true; - } - boolean even = i % 2 == 0; - int prev = d.getOrDefault(i, even ? 0 : 1000000); - if (even && (root.val % 2 == 0 || prev >= root.val)) { - return false; - } - if (!even && (root.val % 2 == 1 || prev <= root.val)) { - return false; - } - d.put(i, root.val); - return dfs(root.left, i + 1) && dfs(root.right, i + 1); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -283,40 +199,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - unordered_map d; - - bool isEvenOddTree(TreeNode* root) { - return dfs(root, 0); - } - - bool dfs(TreeNode* root, int i) { - if (!root) return true; - int even = i % 2 == 0; - int prev = d.count(i) ? d[i] : (even ? 0 : 1e6); - if (even && (root->val % 2 == 0 || prev >= root->val)) return false; - if (!even && (root->val % 2 == 1 || prev <= root->val)) return false; - d[i] = root->val; - return dfs(root->left, i + 1) && dfs(root->right, i + 1); - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -357,6 +239,114 @@ func isEvenOddTree(root *TreeNode) bool { } ``` + + +### 方法二:DFS + +DFS 先序遍历二叉树,同样根据节点所在层的奇偶性判断是否满足条件,遍历过程中用哈希表记录每一层最近访问到的节点值。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: + def dfs(root, i): + if root is None: + return True + even = i % 2 == 0 + prev = d.get(i, 0 if even else inf) + if even and (root.val % 2 == 0 or prev >= root.val): + return False + if not even and (root.val % 2 == 1 or prev <= root.val): + return False + d[i] = root.val + return dfs(root.left, i + 1) and dfs(root.right, i + 1) + + d = {} + return dfs(root, 0) +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private Map d = new HashMap<>(); + + public boolean isEvenOddTree(TreeNode root) { + return dfs(root, 0); + } + + private boolean dfs(TreeNode root, int i) { + if (root == null) { + return true; + } + boolean even = i % 2 == 0; + int prev = d.getOrDefault(i, even ? 0 : 1000000); + if (even && (root.val % 2 == 0 || prev >= root.val)) { + return false; + } + if (!even && (root.val % 2 == 1 || prev <= root.val)) { + return false; + } + d.put(i, root.val); + return dfs(root.left, i + 1) && dfs(root.right, i + 1); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + unordered_map d; + + bool isEvenOddTree(TreeNode* root) { + return dfs(root, 0); + } + + bool dfs(TreeNode* root, int i) { + if (!root) return true; + int even = i % 2 == 0; + int prev = d.count(i) ? d[i] : (even ? 0 : 1e6); + if (even && (root->val % 2 == 0 || prev >= root->val)) return false; + if (!even && (root->val % 2 == 1 || prev <= root->val)) return false; + d[i] = root->val; + return dfs(root->left, i + 1) && dfs(root->right, i + 1); + } +}; +``` + ```go /** * Definition for a binary tree node. @@ -395,10 +385,6 @@ func isEvenOddTree(root *TreeNode) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1609.Even Odd Tree/README_EN.md b/solution/1600-1699/1609.Even Odd Tree/README_EN.md index e4043a7c9bd43..a7f717bb0b809 100644 --- a/solution/1600-1699/1609.Even Odd Tree/README_EN.md +++ b/solution/1600-1699/1609.Even Odd Tree/README_EN.md @@ -58,12 +58,10 @@ Node values in level 2 must be in strictly increasing order, so the tree is not ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -92,33 +90,6 @@ class Solution: return True ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: - def dfs(root, i): - if root is None: - return True - even = i % 2 == 0 - prev = d.get(i, 0 if even else inf) - if even and (root.val % 2 == 0 or prev >= root.val): - return False - if not even and (root.val % 2 == 1 or prev <= root.val): - return False - d[i] = root.val - return dfs(root.left, i + 1) and dfs(root.right, i + 1) - - d = {} - return dfs(root, 0) -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -165,49 +136,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private Map d = new HashMap<>(); - - public boolean isEvenOddTree(TreeNode root) { - return dfs(root, 0); - } - - private boolean dfs(TreeNode root, int i) { - if (root == null) { - return true; - } - boolean even = i % 2 == 0; - int prev = d.getOrDefault(i, even ? 0 : 1000000); - if (even && (root.val % 2 == 0 || prev >= root.val)) { - return false; - } - if (!even && (root.val % 2 == 1 || prev <= root.val)) { - return false; - } - d.put(i, root.val); - return dfs(root.left, i + 1) && dfs(root.right, i + 1); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -243,40 +171,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - unordered_map d; - - bool isEvenOddTree(TreeNode* root) { - return dfs(root, 0); - } - - bool dfs(TreeNode* root, int i) { - if (!root) return true; - int even = i % 2 == 0; - int prev = d.count(i) ? d[i] : (even ? 0 : 1e6); - if (even && (root->val % 2 == 0 || prev >= root->val)) return false; - if (!even && (root->val % 2 == 1 || prev <= root->val)) return false; - d[i] = root->val; - return dfs(root->left, i + 1) && dfs(root->right, i + 1); - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -317,6 +211,110 @@ func isEvenOddTree(root *TreeNode) bool { } ``` + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: + def dfs(root, i): + if root is None: + return True + even = i % 2 == 0 + prev = d.get(i, 0 if even else inf) + if even and (root.val % 2 == 0 or prev >= root.val): + return False + if not even and (root.val % 2 == 1 or prev <= root.val): + return False + d[i] = root.val + return dfs(root.left, i + 1) and dfs(root.right, i + 1) + + d = {} + return dfs(root, 0) +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private Map d = new HashMap<>(); + + public boolean isEvenOddTree(TreeNode root) { + return dfs(root, 0); + } + + private boolean dfs(TreeNode root, int i) { + if (root == null) { + return true; + } + boolean even = i % 2 == 0; + int prev = d.getOrDefault(i, even ? 0 : 1000000); + if (even && (root.val % 2 == 0 || prev >= root.val)) { + return false; + } + if (!even && (root.val % 2 == 1 || prev <= root.val)) { + return false; + } + d.put(i, root.val); + return dfs(root.left, i + 1) && dfs(root.right, i + 1); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + unordered_map d; + + bool isEvenOddTree(TreeNode* root) { + return dfs(root, 0); + } + + bool dfs(TreeNode* root, int i) { + if (!root) return true; + int even = i % 2 == 0; + int prev = d.count(i) ? d[i] : (even ? 0 : 1e6); + if (even && (root->val % 2 == 0 || prev >= root->val)) return false; + if (!even && (root->val % 2 == 1 || prev <= root->val)) return false; + d[i] = root->val; + return dfs(root->left, i + 1) && dfs(root->right, i + 1); + } +}; +``` + ```go /** * Definition for a binary tree node. @@ -355,10 +353,6 @@ func isEvenOddTree(root *TreeNode) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1610.Maximum Number of Visible Points/README.md b/solution/1600-1699/1610.Maximum Number of Visible Points/README.md index 88818b966d613..1fcd0948f343c 100644 --- a/solution/1600-1699/1610.Maximum Number of Visible Points/README.md +++ b/solution/1600-1699/1610.Maximum Number of Visible Points/README.md @@ -59,22 +59,10 @@ ## 解法 - - -根据题目我们得知,需要求出在视角范围 `[d - angle/2, d + angle / 2]` 范围内覆盖的最多点的数量。视角可以转换为相对于 location `(x, y)` 的极角。 - -可以排除与 location 重合的点,将剩下的所有点 p 的坐标 `(xi, yi)` 转换为相对于 `(x, y)` 的极角。可以利用 `atan2` 函数,`atan2` 返回值范围是 `[−π,π]`,覆盖范围是 2π。 - -求出极角后,按照大小进行排序。因为可以循环,所以把整个数组所有元素加上 2π 接在数组后面。 - -接下来利用双指针找出覆盖最多点的区间即可。最后返回时,要把重合的点加上。 +### 方法一 -### **Python3** - - - ```python class Solution: def visiblePoints( @@ -96,10 +84,6 @@ class Solution: return mx + same ``` -### **Java** - - - ```java class Solution { public int visiblePoints(List> points, int angle, List location) { @@ -132,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +145,6 @@ public: }; ``` -### **Go** - ```go func visiblePoints(points [][]int, angle int, location []int) int { same := 0 @@ -193,10 +173,6 @@ func visiblePoints(points [][]int, angle int, location []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1610.Maximum Number of Visible Points/README_EN.md b/solution/1600-1699/1610.Maximum Number of Visible Points/README_EN.md index 6944e9811208d..16e7b5d5f26a2 100644 --- a/solution/1600-1699/1610.Maximum Number of Visible Points/README_EN.md +++ b/solution/1600-1699/1610.Maximum Number of Visible Points/README_EN.md @@ -56,9 +56,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -81,8 +81,6 @@ class Solution: return mx + same ``` -### **Java** - ```java class Solution { public int visiblePoints(List> points, int angle, List location) { @@ -115,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +142,6 @@ public: }; ``` -### **Go** - ```go func visiblePoints(points [][]int, angle int, location []int) int { same := 0 @@ -176,10 +170,6 @@ func visiblePoints(points [][]int, angle int, location []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/README.md b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/README.md index f239083ea8625..ef08bb0f8daed 100644 --- a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/README.md +++ b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:格雷码逆变换(格雷码转二进制码)** +### 方法一:格雷码逆变换(格雷码转二进制码) 本题实际上求的是格雷码为 $n$ 的逆变换,即通过格雷码构造原数。 @@ -77,10 +75,6 @@ int rev(int x) { -### **Python3** - - - ```python class Solution: def minimumOneBitOperations(self, n: int) -> int: @@ -91,18 +85,6 @@ class Solution: return ans ``` -```python -class Solution: - def minimumOneBitOperations(self, n: int) -> int: - if n == 0: - return 0 - return n ^ self.minimumOneBitOperations(n >> 1) -``` - -### **Java** - - - ```java class Solution { public int minimumOneBitOperations(int n) { @@ -115,19 +97,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumOneBitOperations(int n) { - if (n == 0) { - return 0; - } - return n ^ minimumOneBitOperations(n >> 1); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -141,6 +110,50 @@ public: }; ``` +```go +func minimumOneBitOperations(n int) (ans int) { + for ; n > 0; n >>= 1 { + ans ^= n + } + return +} +``` + +```ts +function minimumOneBitOperations(n: number): number { + let ans = 0; + for (; n > 0; n >>= 1) { + ans ^= n; + } + return ans; +} +``` + + + +### 方法二 + + + +```python +class Solution: + def minimumOneBitOperations(self, n: int) -> int: + if n == 0: + return 0 + return n ^ self.minimumOneBitOperations(n >> 1) +``` + +```java +class Solution { + public int minimumOneBitOperations(int n) { + if (n == 0) { + return 0; + } + return n ^ minimumOneBitOperations(n >> 1); + } +} +``` + ```cpp class Solution { public: @@ -153,17 +166,6 @@ public: }; ``` -### **Go** - -```go -func minimumOneBitOperations(n int) (ans int) { - for ; n > 0; n >>= 1 { - ans ^= n - } - return -} -``` - ```go func minimumOneBitOperations(n int) int { if n == 0 { @@ -173,18 +175,6 @@ func minimumOneBitOperations(n int) int { } ``` -### **TypeScript** - -```ts -function minimumOneBitOperations(n: number): number { - let ans = 0; - for (; n > 0; n >>= 1) { - ans ^= n; - } - return ans; -} -``` - ```ts function minimumOneBitOperations(n: number): number { if (n === 0) { @@ -194,10 +184,6 @@ function minimumOneBitOperations(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/README_EN.md b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/README_EN.md index 92212f9ee7614..ae4edb6d65211 100644 --- a/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/README_EN.md +++ b/solution/1600-1699/1611.Minimum One Bit Operations to Make Integers Zero/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,16 +59,6 @@ class Solution: return ans ``` -```python -class Solution: - def minimumOneBitOperations(self, n: int) -> int: - if n == 0: - return 0 - return n ^ self.minimumOneBitOperations(n >> 1) -``` - -### **Java** - ```java class Solution { public int minimumOneBitOperations(int n) { @@ -81,19 +71,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumOneBitOperations(int n) { - if (n == 0) { - return 0; - } - return n ^ minimumOneBitOperations(n >> 1); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -107,6 +84,50 @@ public: }; ``` +```go +func minimumOneBitOperations(n int) (ans int) { + for ; n > 0; n >>= 1 { + ans ^= n + } + return +} +``` + +```ts +function minimumOneBitOperations(n: number): number { + let ans = 0; + for (; n > 0; n >>= 1) { + ans ^= n; + } + return ans; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minimumOneBitOperations(self, n: int) -> int: + if n == 0: + return 0 + return n ^ self.minimumOneBitOperations(n >> 1) +``` + +```java +class Solution { + public int minimumOneBitOperations(int n) { + if (n == 0) { + return 0; + } + return n ^ minimumOneBitOperations(n >> 1); + } +} +``` + ```cpp class Solution { public: @@ -119,17 +140,6 @@ public: }; ``` -### **Go** - -```go -func minimumOneBitOperations(n int) (ans int) { - for ; n > 0; n >>= 1 { - ans ^= n - } - return -} -``` - ```go func minimumOneBitOperations(n int) int { if n == 0 { @@ -139,18 +149,6 @@ func minimumOneBitOperations(n int) int { } ``` -### **TypeScript** - -```ts -function minimumOneBitOperations(n: number): number { - let ans = 0; - for (; n > 0; n >>= 1) { - ans ^= n; - } - return ans; -} -``` - ```ts function minimumOneBitOperations(n: number): number { if (n === 0) { @@ -160,10 +158,6 @@ function minimumOneBitOperations(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/README.md b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/README.md index 567dd3a3c1794..c3ebc8b5ab502 100644 --- a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/README.md +++ b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们定义一个计数器 $cnt$,用于统计每个字母出现的次数。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class Node(object): @@ -97,35 +91,6 @@ class Solution: return all(x == 0 for x in cnt.values()) ``` -```python -# Definition for a binary tree node. -# class Node(object): -# def __init__(self, val=" ", left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool: - def dfs(root): - cnt = [0] * 26 - if root is None: - return cnt - if root.val in '+-': - l, r = dfs(root.left), dfs(root.right) - k = 1 if root.val == '+' else -1 - for i in range(26): - cnt[i] += l[i] + r[i] * k - else: - cnt[ord(root.val) - ord('a')] += 1 - return cnt - - return dfs(root1) == dfs(root2) -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -169,6 +134,112 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct Node { + * char val; + * Node *left; + * Node *right; + * Node() : val(' '), left(nullptr), right(nullptr) {} + * Node(char x) : val(x), left(nullptr), right(nullptr) {} + * Node(char x, Node *left, Node *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool checkEquivalence(Node* root1, Node* root2) { + int cnt[26]{}; + function dfs = [&](Node* root, int v) { + if (!root) { + return; + } + if (root->val != '+') { + cnt[root->val - 'a'] += v; + } + dfs(root->left, v); + dfs(root->right, v); + }; + dfs(root1, 1); + dfs(root2, -1); + for (int& x : cnt) { + if (x) { + return false; + } + } + return true; + } +}; +``` + +```js +/** + * Definition for a binary tree node. + * function Node(val, left, right) { + * this.val = (val===undefined ? " " : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {Node} root1 + * @param {Node} root2 + * @return {boolean} + */ +var checkEquivalence = function (root1, root2) { + const cnt = new Array(26).fill(0); + const dfs = (root, v) => { + if (!root) { + return; + } + if (root.val !== '+') { + cnt[root.val.charCodeAt(0) - 'a'.charCodeAt(0)] += v; + } + dfs(root.left, v); + dfs(root.right, v); + }; + dfs(root1, 1); + dfs(root2, -1); + for (const x of cnt) { + if (x) { + return false; + } + } + return true; +}; +``` + + + +### 方法二 + + + +```python +# Definition for a binary tree node. +# class Node(object): +# def __init__(self, val=" ", left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool: + def dfs(root): + cnt = [0] * 26 + if root is None: + return cnt + if root.val in '+-': + l, r = dfs(root.left), dfs(root.right) + k = 1 if root.val == '+' else -1 + for i in range(26): + cnt[i] += l[i] + r[i] * k + else: + cnt[ord(root.val) - ord('a')] += 1 + return cnt + + return dfs(root1) == dfs(root2) +``` + ```java /** * Definition for a binary tree node. @@ -217,46 +288,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct Node { - * char val; - * Node *left; - * Node *right; - * Node() : val(' '), left(nullptr), right(nullptr) {} - * Node(char x) : val(x), left(nullptr), right(nullptr) {} - * Node(char x, Node *left, Node *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool checkEquivalence(Node* root1, Node* root2) { - int cnt[26]{}; - function dfs = [&](Node* root, int v) { - if (!root) { - return; - } - if (root->val != '+') { - cnt[root->val - 'a'] += v; - } - dfs(root->left, v); - dfs(root->right, v); - }; - dfs(root1, 1); - dfs(root2, -1); - for (int& x : cnt) { - if (x) { - return false; - } - } - return true; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -294,45 +325,6 @@ public: }; ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function Node(val, left, right) { - * this.val = (val===undefined ? " " : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {Node} root1 - * @param {Node} root2 - * @return {boolean} - */ -var checkEquivalence = function (root1, root2) { - const cnt = new Array(26).fill(0); - const dfs = (root, v) => { - if (!root) { - return; - } - if (root.val !== '+') { - cnt[root.val.charCodeAt(0) - 'a'.charCodeAt(0)] += v; - } - dfs(root.left, v); - dfs(root.right, v); - }; - dfs(root1, 1); - dfs(root2, -1); - for (const x of cnt) { - if (x) { - return false; - } - } - return true; -}; -``` - ```js /** * Definition for a binary tree node. @@ -376,10 +368,6 @@ var checkEquivalence = function (root1, root2) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/README_EN.md b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/README_EN.md index 17fc2405519e0..01ebf333db845 100644 --- a/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/README_EN.md +++ b/solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/README_EN.md @@ -51,9 +51,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -78,33 +78,6 @@ class Solution: return all(x == 0 for x in cnt.values()) ``` -```python -# Definition for a binary tree node. -# class Node(object): -# def __init__(self, val=" ", left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool: - def dfs(root): - cnt = [0] * 26 - if root is None: - return cnt - if root.val in '+-': - l, r = dfs(root.left), dfs(root.right) - k = 1 if root.val == '+' else -1 - for i in range(26): - cnt[i] += l[i] + r[i] * k - else: - cnt[ord(root.val) - ord('a')] += 1 - return cnt - - return dfs(root1) == dfs(root2) -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -148,6 +121,112 @@ class Solution { } ``` +```cpp +/** + * Definition for a binary tree node. + * struct Node { + * char val; + * Node *left; + * Node *right; + * Node() : val(' '), left(nullptr), right(nullptr) {} + * Node(char x) : val(x), left(nullptr), right(nullptr) {} + * Node(char x, Node *left, Node *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool checkEquivalence(Node* root1, Node* root2) { + int cnt[26]{}; + function dfs = [&](Node* root, int v) { + if (!root) { + return; + } + if (root->val != '+') { + cnt[root->val - 'a'] += v; + } + dfs(root->left, v); + dfs(root->right, v); + }; + dfs(root1, 1); + dfs(root2, -1); + for (int& x : cnt) { + if (x) { + return false; + } + } + return true; + } +}; +``` + +```js +/** + * Definition for a binary tree node. + * function Node(val, left, right) { + * this.val = (val===undefined ? " " : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {Node} root1 + * @param {Node} root2 + * @return {boolean} + */ +var checkEquivalence = function (root1, root2) { + const cnt = new Array(26).fill(0); + const dfs = (root, v) => { + if (!root) { + return; + } + if (root.val !== '+') { + cnt[root.val.charCodeAt(0) - 'a'.charCodeAt(0)] += v; + } + dfs(root.left, v); + dfs(root.right, v); + }; + dfs(root1, 1); + dfs(root2, -1); + for (const x of cnt) { + if (x) { + return false; + } + } + return true; +}; +``` + + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class Node(object): +# def __init__(self, val=" ", left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool: + def dfs(root): + cnt = [0] * 26 + if root is None: + return cnt + if root.val in '+-': + l, r = dfs(root.left), dfs(root.right) + k = 1 if root.val == '+' else -1 + for i in range(26): + cnt[i] += l[i] + r[i] * k + else: + cnt[ord(root.val) - ord('a')] += 1 + return cnt + + return dfs(root1) == dfs(root2) +``` + ```java /** * Definition for a binary tree node. @@ -196,46 +275,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct Node { - * char val; - * Node *left; - * Node *right; - * Node() : val(' '), left(nullptr), right(nullptr) {} - * Node(char x) : val(x), left(nullptr), right(nullptr) {} - * Node(char x, Node *left, Node *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool checkEquivalence(Node* root1, Node* root2) { - int cnt[26]{}; - function dfs = [&](Node* root, int v) { - if (!root) { - return; - } - if (root->val != '+') { - cnt[root->val - 'a'] += v; - } - dfs(root->left, v); - dfs(root->right, v); - }; - dfs(root1, 1); - dfs(root2, -1); - for (int& x : cnt) { - if (x) { - return false; - } - } - return true; - } -}; -``` - ```cpp /** * Definition for a binary tree node. @@ -273,45 +312,6 @@ public: }; ``` -### **JavaScript** - -```js -/** - * Definition for a binary tree node. - * function Node(val, left, right) { - * this.val = (val===undefined ? " " : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {Node} root1 - * @param {Node} root2 - * @return {boolean} - */ -var checkEquivalence = function (root1, root2) { - const cnt = new Array(26).fill(0); - const dfs = (root, v) => { - if (!root) { - return; - } - if (root.val !== '+') { - cnt[root.val.charCodeAt(0) - 'a'.charCodeAt(0)] += v; - } - dfs(root.left, v); - dfs(root.right, v); - }; - dfs(root1, 1); - dfs(root2, -1); - for (const x of cnt) { - if (x) { - return false; - } - } - return true; -}; -``` - ```js /** * Definition for a binary tree node. @@ -355,10 +355,6 @@ var checkEquivalence = function (root1, root2) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1613.Find the Missing IDs/README.md b/solution/1600-1699/1613.Find the Missing IDs/README.md index 43a49d81c4fe5..d74424ecdc933 100644 --- a/solution/1600-1699/1613.Find the Missing IDs/README.md +++ b/solution/1600-1699/1613.Find the Missing IDs/README.md @@ -55,16 +55,12 @@ Customers 表: ## 解法 - - -**方法一:递归** +### 方法一:递归 利用 `recursive` 关键字,递归生成 `[1, 100]` 的序列,然后排除已有的 `customer_id`,即可得到结果。 -### **SQL** - ```sql # Write your MySQL query statement below WITH RECURSIVE @@ -94,3 +90,5 @@ WHERE ``` + + diff --git a/solution/1600-1699/1613.Find the Missing IDs/README_EN.md b/solution/1600-1699/1613.Find the Missing IDs/README_EN.md index d87ac8170a8b7..cb3be882855f7 100644 --- a/solution/1600-1699/1613.Find the Missing IDs/README_EN.md +++ b/solution/1600-1699/1613.Find the Missing IDs/README_EN.md @@ -53,9 +53,9 @@ The maximum customer_id present in the table is 5, so in the range [1,5], IDs 2 ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -86,3 +86,5 @@ WHERE ``` + + diff --git a/solution/1600-1699/1614.Maximum Nesting Depth of the Parentheses/README.md b/solution/1600-1699/1614.Maximum Nesting Depth of the Parentheses/README.md index b5a502822962b..7323cae574d0f 100644 --- a/solution/1600-1699/1614.Maximum Nesting Depth of the Parentheses/README.md +++ b/solution/1600-1699/1614.Maximum Nesting Depth of the Parentheses/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:遍历** +### 方法一:遍历 我们可以遍历字符串,维护当前的嵌套深度,遇到左括号时深度加一,并且更新组最大深大;遇到右括号时深度减一。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def maxDepth(self, s: str) -> int: @@ -85,10 +79,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxDepth(String s) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func maxDepth(s string) (ans int) { d := 0 @@ -142,7 +128,20 @@ func maxDepth(s string) (ans int) { } ``` -### **JavaScript** +```ts +function maxDepth(s: string): number { + let ans = 0; + let d = 0; + for (const c of s) { + if (c === '(') { + ans = Math.max(ans, ++d); + } else if (c === ')') { + --d; + } + } + return ans; +} +``` ```js /** @@ -163,8 +162,6 @@ var maxDepth = function (s) { }; ``` -### **C#** - ```cs public class Solution { public int MaxDepth(string s) { @@ -181,27 +178,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function maxDepth(s: string): number { - let ans = 0; - let d = 0; - for (const c of s) { - if (c === '(') { - ans = Math.max(ans, ++d); - } else if (c === ')') { - --d; - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1614.Maximum Nesting Depth of the Parentheses/README_EN.md b/solution/1600-1699/1614.Maximum Nesting Depth of the Parentheses/README_EN.md index af71fe3eb889b..ba35ce9fa1e88 100644 --- a/solution/1600-1699/1614.Maximum Nesting Depth of the Parentheses/README_EN.md +++ b/solution/1600-1699/1614.Maximum Nesting Depth of the Parentheses/README_EN.md @@ -52,9 +52,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxDepth(String s) { @@ -88,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +103,6 @@ public: }; ``` -### **Go** - ```go func maxDepth(s string) (ans int) { d := 0 @@ -124,7 +118,20 @@ func maxDepth(s string) (ans int) { } ``` -### **JavaScript** +```ts +function maxDepth(s: string): number { + let ans = 0; + let d = 0; + for (const c of s) { + if (c === '(') { + ans = Math.max(ans, ++d); + } else if (c === ')') { + --d; + } + } + return ans; +} +``` ```js /** @@ -145,8 +152,6 @@ var maxDepth = function (s) { }; ``` -### **C#** - ```cs public class Solution { public int MaxDepth(string s) { @@ -163,27 +168,6 @@ public class Solution { } ``` -### **TypeScript** - -```ts -function maxDepth(s: string): number { - let ans = 0; - let d = 0; - for (const c of s) { - if (c === '(') { - ans = Math.max(ans, ++d); - } else if (c === ')') { - --d; - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1615.Maximal Network Rank/README.md b/solution/1600-1699/1615.Maximal Network Rank/README.md index a34c9841052b6..1f8ad528bb2b4 100644 --- a/solution/1600-1699/1615.Maximal Network Rank/README.md +++ b/solution/1600-1699/1615.Maximal Network Rank/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们可以用一维数组 $cnt$ 记录每个城市的度,用二维数组 $g$ 记录每对城市之间是否有道路相连,如果城市 $a$ 和城市 $b$ 之间有道路相连,则 $g[a][b] = g[b][a] = 1$,否则 $g[a][b] = g[b][a] = 0$。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: @@ -90,22 +84,6 @@ class Solution: return ans ``` -```python -class Solution: - def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: - g = [[0] * n for _ in range(n)] - cnt = [0] * n - for a, b in roads: - g[a][b] = g[b][a] = 1 - cnt[a] += 1 - cnt[b] += 1 - return max(cnt[a] + cnt[b] - g[a][b] for a in range(n) for b in range(a + 1, n)) -``` - -### **Java** - - - ```java class Solution { public int maximalNetworkRank(int n, int[][] roads) { @@ -129,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +132,6 @@ public: }; ``` -### **Go** - ```go func maximalNetworkRank(n int, roads [][]int) (ans int) { g := make([][]int, n) @@ -180,8 +154,6 @@ func maximalNetworkRank(n int, roads [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function maximalNetworkRank(n: number, roads: number[][]): number { const g: number[][] = Array.from(new Array(n), () => new Array(n).fill(0)); @@ -202,10 +174,24 @@ function maximalNetworkRank(n: number, roads: number[][]): number { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: + g = [[0] * n for _ in range(n)] + cnt = [0] * n + for a, b in roads: + g[a][b] = g[b][a] = 1 + cnt[a] += 1 + cnt[b] += 1 + return max(cnt[a] + cnt[b] - g[a][b] for a in range(n) for b in range(a + 1, n)) ``` + + diff --git a/solution/1600-1699/1615.Maximal Network Rank/README_EN.md b/solution/1600-1699/1615.Maximal Network Rank/README_EN.md index 1a5db5a0006fd..e717420a4c10f 100644 --- a/solution/1600-1699/1615.Maximal Network Rank/README_EN.md +++ b/solution/1600-1699/1615.Maximal Network Rank/README_EN.md @@ -55,9 +55,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,20 +74,6 @@ class Solution: return ans ``` -```python -class Solution: - def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: - g = [[0] * n for _ in range(n)] - cnt = [0] * n - for a, b in roads: - g[a][b] = g[b][a] = 1 - cnt[a] += 1 - cnt[b] += 1 - return max(cnt[a] + cnt[b] - g[a][b] for a in range(n) for b in range(a + 1, n)) -``` - -### **Java** - ```java class Solution { public int maximalNetworkRank(int n, int[][] roads) { @@ -111,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +122,6 @@ public: }; ``` -### **Go** - ```go func maximalNetworkRank(n int, roads [][]int) (ans int) { g := make([][]int, n) @@ -162,8 +144,6 @@ func maximalNetworkRank(n int, roads [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function maximalNetworkRank(n: number, roads: number[][]): number { const g: number[][] = Array.from(new Array(n), () => new Array(n).fill(0)); @@ -184,10 +164,24 @@ function maximalNetworkRank(n: number, roads: number[][]): number { } ``` -### **...** + + +### Solution 2 -``` + +```python +class Solution: + def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: + g = [[0] * n for _ in range(n)] + cnt = [0] * n + for a, b in roads: + g[a][b] = g[b][a] = 1 + cnt[a] += 1 + cnt[b] += 1 + return max(cnt[a] + cnt[b] - g[a][b] for a in range(n) for b in range(a + 1, n)) ``` + + diff --git a/solution/1600-1699/1616.Split Two Strings to Make Palindrome/README.md b/solution/1600-1699/1616.Split Two Strings to Make Palindrome/README.md index b2975bc41c634..604d940030237 100644 --- a/solution/1600-1699/1616.Split Two Strings to Make Palindrome/README.md +++ b/solution/1600-1699/1616.Split Two Strings to Make Palindrome/README.md @@ -56,9 +56,7 @@ bprefix = "jiz", bsuffix = "alu" ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们可以使用双指针,其中一个指针 $i$ 从字符串 $a$ 的头部开始,另一个指针 $j$ 从字符串 $b$ 的尾部开始,如果两个指针指向的字符相等,那么两个指针同时往中间移动,直到遇到不同的字符或两指针交叉。 @@ -70,10 +68,6 @@ bprefix = "jiz", bsuffix = "alu" -### **Python3** - - - ```python class Solution: def checkPalindromeFormation(self, a: str, b: str) -> bool: @@ -89,10 +83,6 @@ class Solution: return check1(a, b) or check1(b, a) ``` -### **Java** - - - ```java class Solution { public boolean checkPalindromeFormation(String a, String b) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +136,6 @@ private: }; ``` -### **Go** - ```go func checkPalindromeFormation(a string, b string) bool { return check1(a, b) || check1(b, a) @@ -173,7 +159,28 @@ func check2(a string, i, j int) bool { } ``` -### **Rust** +```ts +function checkPalindromeFormation(a: string, b: string): boolean { + const check1 = (a: string, b: string) => { + let i = 0; + let j = b.length - 1; + while (i < j && a.charAt(i) === b.charAt(j)) { + i++; + j--; + } + return i >= j || check2(a, i, j) || check2(b, i, j); + }; + + const check2 = (a: string, i: number, j: number) => { + while (i < j && a.charAt(i) === a.charAt(j)) { + i++; + j--; + } + return i >= j; + }; + return check1(a, b) || check1(b, a); +} +``` ```rust impl Solution { @@ -205,35 +212,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function checkPalindromeFormation(a: string, b: string): boolean { - const check1 = (a: string, b: string) => { - let i = 0; - let j = b.length - 1; - while (i < j && a.charAt(i) === b.charAt(j)) { - i++; - j--; - } - return i >= j || check2(a, i, j) || check2(b, i, j); - }; - - const check2 = (a: string, i: number, j: number) => { - while (i < j && a.charAt(i) === a.charAt(j)) { - i++; - j--; - } - return i >= j; - }; - return check1(a, b) || check1(b, a); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1616.Split Two Strings to Make Palindrome/README_EN.md b/solution/1600-1699/1616.Split Two Strings to Make Palindrome/README_EN.md index 1ee30ed5bb6bf..1582e567ac629 100644 --- a/solution/1600-1699/1616.Split Two Strings to Make Palindrome/README_EN.md +++ b/solution/1600-1699/1616.Split Two Strings to Make Palindrome/README_EN.md @@ -53,9 +53,9 @@ Then, aprefix + bsuffix = "ula" + "alu" ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return check1(a, b) or check1(b, a) ``` -### **Java** - ```java class Solution { public boolean checkPalindromeFormation(String a, String b) { @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +125,6 @@ private: }; ``` -### **Go** - ```go func checkPalindromeFormation(a string, b string) bool { return check1(a, b) || check1(b, a) @@ -154,7 +148,28 @@ func check2(a string, i, j int) bool { } ``` -### **Rust** +```ts +function checkPalindromeFormation(a: string, b: string): boolean { + const check1 = (a: string, b: string) => { + let i = 0; + let j = b.length - 1; + while (i < j && a.charAt(i) === b.charAt(j)) { + i++; + j--; + } + return i >= j || check2(a, i, j) || check2(b, i, j); + }; + + const check2 = (a: string, i: number, j: number) => { + while (i < j && a.charAt(i) === a.charAt(j)) { + i++; + j--; + } + return i >= j; + }; + return check1(a, b) || check1(b, a); +} +``` ```rust impl Solution { @@ -186,35 +201,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function checkPalindromeFormation(a: string, b: string): boolean { - const check1 = (a: string, b: string) => { - let i = 0; - let j = b.length - 1; - while (i < j && a.charAt(i) === b.charAt(j)) { - i++; - j--; - } - return i >= j || check2(a, i, j) || check2(b, i, j); - }; - - const check2 = (a: string, i: number, j: number) => { - while (i < j && a.charAt(i) === a.charAt(j)) { - i++; - j--; - } - return i >= j; - }; - return check1(a, b) || check1(b, a); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README.md b/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README.md index 20fea677c6f73..adf92926cc11a 100644 --- a/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README.md +++ b/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:二进制枚举 + BFS 或 DFS** +### 方法一:二进制枚举 + BFS 或 DFS 我们注意到 $n \leq 15$,因此可以考虑使用二进制枚举的方法枚举所有的子树。而子树中节点的最大距离,其实就是子树中两个节点之间的最长路径,也即是树的直径,求解树的直径一般可以使用 DFS 或 BFS,先找到树直径的一个端点,然后再从该端点出发,找到树的另一个端点,这两个端点之间的路径长度就是树的直径。 @@ -85,10 +83,6 @@ -### **Python3** - - - ```python class Solution: def countSubgraphsForEachDiameter( @@ -123,50 +117,6 @@ class Solution: return ans ``` -```python -class Solution: - def countSubgraphsForEachDiameter( - self, n: int, edges: List[List[int]] - ) -> List[int]: - def bfs(u: int) -> int: - d = -1 - q = deque([u]) - nonlocal msk, nxt - msk ^= 1 << u - while q: - d += 1 - for _ in range(len(q)): - nxt = u = q.popleft() - for v in g[u]: - if msk >> v & 1: - msk ^= 1 << v - q.append(v) - return d - - g = defaultdict(list) - for u, v in edges: - u, v = u - 1, v - 1 - g[u].append(v) - g[v].append(u) - ans = [0] * (n - 1) - nxt = 0 - for mask in range(1, 1 << n): - if mask & (mask - 1) == 0: - continue - msk = mask - cur = msk.bit_length() - 1 - bfs(cur) - if msk == 0: - msk = mask - mx = bfs(nxt) - ans[mx - 1] += 1 - return ans -``` - -### **Java** - - - ```java class Solution { private List[] g; @@ -216,6 +166,198 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector countSubgraphsForEachDiameter(int n, vector>& edges) { + vector> g(n); + for (auto& e : edges) { + int u = e[0] - 1, v = e[1] - 1; + g[u].emplace_back(v); + g[v].emplace_back(u); + } + vector ans(n - 1); + int nxt = 0, msk = 0, mx = 0; + function dfs = [&](int u, int d) { + msk ^= 1 << u; + if (mx < d) { + mx = d; + nxt = u; + } + for (int& v : g[u]) { + if (msk >> v & 1) { + dfs(v, d + 1); + } + } + }; + for (int mask = 1; mask < 1 << n; ++mask) { + if ((mask & (mask - 1)) == 0) { + continue; + } + msk = mask; + mx = 0; + int cur = 31 - __builtin_clz(msk); + dfs(cur, 0); + if (msk == 0) { + msk = mask; + mx = 0; + dfs(nxt, 0); + ++ans[mx - 1]; + } + } + return ans; + } +}; +``` + +```go +func countSubgraphsForEachDiameter(n int, edges [][]int) []int { + g := make([][]int, n) + for _, e := range edges { + u, v := e[0]-1, e[1]-1 + g[u] = append(g[u], v) + g[v] = append(g[v], u) + } + ans := make([]int, n-1) + var msk, nxt, mx int + var dfs func(int, int) + dfs = func(u, d int) { + msk ^= 1 << u + if mx < d { + mx, nxt = d, u + } + for _, v := range g[u] { + if msk>>v&1 == 1 { + dfs(v, d+1) + } + } + } + for mask := 1; mask < 1< []); + for (const [u, v] of edges) { + g[u - 1].push(v - 1); + g[v - 1].push(u - 1); + } + const ans: number[] = new Array(n - 1).fill(0); + let [mx, msk, nxt] = [0, 0, 0]; + const dfs = (u: number, d: number) => { + if (mx < d) { + mx = d; + nxt = u; + } + msk ^= 1 << u; + for (const v of g[u]) { + if ((msk >> v) & 1) { + dfs(v, d + 1); + } + } + }; + for (let mask = 1; mask < 1 << n; ++mask) { + if ((mask & (mask - 1)) === 0) { + continue; + } + msk = mask; + mx = 0; + const cur = 31 - numberOfLeadingZeros(msk); + dfs(cur, 0); + if (msk === 0) { + msk = mask; + mx = 0; + dfs(nxt, 0); + ++ans[mx - 1]; + } + } + return ans; +} + +function numberOfLeadingZeros(i: number): number { + if (i == 0) return 32; + let n = 1; + if (i >>> 16 == 0) { + n += 16; + i <<= 16; + } + if (i >>> 24 == 0) { + n += 8; + i <<= 8; + } + if (i >>> 28 == 0) { + n += 4; + i <<= 4; + } + if (i >>> 30 == 0) { + n += 2; + i <<= 2; + } + n -= i >>> 31; + return n; +} +``` + + + +### 方法二 + + + +```python +class Solution: + def countSubgraphsForEachDiameter( + self, n: int, edges: List[List[int]] + ) -> List[int]: + def bfs(u: int) -> int: + d = -1 + q = deque([u]) + nonlocal msk, nxt + msk ^= 1 << u + while q: + d += 1 + for _ in range(len(q)): + nxt = u = q.popleft() + for v in g[u]: + if msk >> v & 1: + msk ^= 1 << v + q.append(v) + return d + + g = defaultdict(list) + for u, v in edges: + u, v = u - 1, v - 1 + g[u].append(v) + g[v].append(u) + ans = [0] * (n - 1) + nxt = 0 + for mask in range(1, 1 << n): + if mask & (mask - 1) == 0: + continue + msk = mask + cur = msk.bit_length() - 1 + bfs(cur) + if msk == 0: + msk = mask + mx = bfs(nxt) + ans[mx - 1] += 1 + return ans +``` + ```java class Solution { private List[] g; @@ -270,52 +412,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector countSubgraphsForEachDiameter(int n, vector>& edges) { - vector> g(n); - for (auto& e : edges) { - int u = e[0] - 1, v = e[1] - 1; - g[u].emplace_back(v); - g[v].emplace_back(u); - } - vector ans(n - 1); - int nxt = 0, msk = 0, mx = 0; - function dfs = [&](int u, int d) { - msk ^= 1 << u; - if (mx < d) { - mx = d; - nxt = u; - } - for (int& v : g[u]) { - if (msk >> v & 1) { - dfs(v, d + 1); - } - } - }; - for (int mask = 1; mask < 1 << n; ++mask) { - if ((mask & (mask - 1)) == 0) { - continue; - } - msk = mask; - mx = 0; - int cur = 31 - __builtin_clz(msk); - dfs(cur, 0); - if (msk == 0) { - msk = mask; - mx = 0; - dfs(nxt, 0); - ++ans[mx - 1]; - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -366,47 +462,6 @@ public: }; ``` -### **Go** - -```go -func countSubgraphsForEachDiameter(n int, edges [][]int) []int { - g := make([][]int, n) - for _, e := range edges { - u, v := e[0]-1, e[1]-1 - g[u] = append(g[u], v) - g[v] = append(g[v], u) - } - ans := make([]int, n-1) - var msk, nxt, mx int - var dfs func(int, int) - dfs = func(u, d int) { - msk ^= 1 << u - if mx < d { - mx, nxt = d, u - } - for _, v := range g[u] { - if msk>>v&1 == 1 { - dfs(v, d+1) - } - } - } - for mask := 1; mask < 1< []); - for (const [u, v] of edges) { - g[u - 1].push(v - 1); - g[v - 1].push(u - 1); - } - const ans: number[] = new Array(n - 1).fill(0); - let [mx, msk, nxt] = [0, 0, 0]; - const dfs = (u: number, d: number) => { - if (mx < d) { - mx = d; - nxt = u; - } - msk ^= 1 << u; - for (const v of g[u]) { - if ((msk >> v) & 1) { - dfs(v, d + 1); - } - } - }; - for (let mask = 1; mask < 1 << n; ++mask) { - if ((mask & (mask - 1)) === 0) { - continue; - } - msk = mask; - mx = 0; - const cur = 31 - numberOfLeadingZeros(msk); - dfs(cur, 0); - if (msk === 0) { - msk = mask; - mx = 0; - dfs(nxt, 0); - ++ans[mx - 1]; - } - } - return ans; -} - -function numberOfLeadingZeros(i: number): number { - if (i == 0) return 32; - let n = 1; - if (i >>> 16 == 0) { - n += 16; - i <<= 16; - } - if (i >>> 24 == 0) { - n += 8; - i <<= 8; - } - if (i >>> 28 == 0) { - n += 4; - i <<= 4; - } - if (i >>> 30 == 0) { - n += 2; - i <<= 2; - } - n -= i >>> 31; - return n; -} -``` - ```ts function countSubgraphsForEachDiameter(n: number, edges: number[][]): number[] { const g = Array.from({ length: n }, () => []); @@ -587,10 +577,6 @@ function numberOfLeadingZeros(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README_EN.md b/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README_EN.md index e8e5e56fdbbc2..33554acfed23e 100644 --- a/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README_EN.md +++ b/solution/1600-1699/1617.Count Subtrees With Max Distance Between Cities/README_EN.md @@ -55,9 +55,9 @@ No subtree has two nodes where the max distance between them is 3. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -93,48 +93,6 @@ class Solution: return ans ``` -```python -class Solution: - def countSubgraphsForEachDiameter( - self, n: int, edges: List[List[int]] - ) -> List[int]: - def bfs(u: int) -> int: - d = -1 - q = deque([u]) - nonlocal msk, nxt - msk ^= 1 << u - while q: - d += 1 - for _ in range(len(q)): - nxt = u = q.popleft() - for v in g[u]: - if msk >> v & 1: - msk ^= 1 << v - q.append(v) - return d - - g = defaultdict(list) - for u, v in edges: - u, v = u - 1, v - 1 - g[u].append(v) - g[v].append(u) - ans = [0] * (n - 1) - nxt = 0 - for mask in range(1, 1 << n): - if mask & (mask - 1) == 0: - continue - msk = mask - cur = msk.bit_length() - 1 - bfs(cur) - if msk == 0: - msk = mask - mx = bfs(nxt) - ans[mx - 1] += 1 - return ans -``` - -### **Java** - ```java class Solution { private List[] g; @@ -184,6 +142,198 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector countSubgraphsForEachDiameter(int n, vector>& edges) { + vector> g(n); + for (auto& e : edges) { + int u = e[0] - 1, v = e[1] - 1; + g[u].emplace_back(v); + g[v].emplace_back(u); + } + vector ans(n - 1); + int nxt = 0, msk = 0, mx = 0; + function dfs = [&](int u, int d) { + msk ^= 1 << u; + if (mx < d) { + mx = d; + nxt = u; + } + for (int& v : g[u]) { + if (msk >> v & 1) { + dfs(v, d + 1); + } + } + }; + for (int mask = 1; mask < 1 << n; ++mask) { + if ((mask & (mask - 1)) == 0) { + continue; + } + msk = mask; + mx = 0; + int cur = 31 - __builtin_clz(msk); + dfs(cur, 0); + if (msk == 0) { + msk = mask; + mx = 0; + dfs(nxt, 0); + ++ans[mx - 1]; + } + } + return ans; + } +}; +``` + +```go +func countSubgraphsForEachDiameter(n int, edges [][]int) []int { + g := make([][]int, n) + for _, e := range edges { + u, v := e[0]-1, e[1]-1 + g[u] = append(g[u], v) + g[v] = append(g[v], u) + } + ans := make([]int, n-1) + var msk, nxt, mx int + var dfs func(int, int) + dfs = func(u, d int) { + msk ^= 1 << u + if mx < d { + mx, nxt = d, u + } + for _, v := range g[u] { + if msk>>v&1 == 1 { + dfs(v, d+1) + } + } + } + for mask := 1; mask < 1< []); + for (const [u, v] of edges) { + g[u - 1].push(v - 1); + g[v - 1].push(u - 1); + } + const ans: number[] = new Array(n - 1).fill(0); + let [mx, msk, nxt] = [0, 0, 0]; + const dfs = (u: number, d: number) => { + if (mx < d) { + mx = d; + nxt = u; + } + msk ^= 1 << u; + for (const v of g[u]) { + if ((msk >> v) & 1) { + dfs(v, d + 1); + } + } + }; + for (let mask = 1; mask < 1 << n; ++mask) { + if ((mask & (mask - 1)) === 0) { + continue; + } + msk = mask; + mx = 0; + const cur = 31 - numberOfLeadingZeros(msk); + dfs(cur, 0); + if (msk === 0) { + msk = mask; + mx = 0; + dfs(nxt, 0); + ++ans[mx - 1]; + } + } + return ans; +} + +function numberOfLeadingZeros(i: number): number { + if (i == 0) return 32; + let n = 1; + if (i >>> 16 == 0) { + n += 16; + i <<= 16; + } + if (i >>> 24 == 0) { + n += 8; + i <<= 8; + } + if (i >>> 28 == 0) { + n += 4; + i <<= 4; + } + if (i >>> 30 == 0) { + n += 2; + i <<= 2; + } + n -= i >>> 31; + return n; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def countSubgraphsForEachDiameter( + self, n: int, edges: List[List[int]] + ) -> List[int]: + def bfs(u: int) -> int: + d = -1 + q = deque([u]) + nonlocal msk, nxt + msk ^= 1 << u + while q: + d += 1 + for _ in range(len(q)): + nxt = u = q.popleft() + for v in g[u]: + if msk >> v & 1: + msk ^= 1 << v + q.append(v) + return d + + g = defaultdict(list) + for u, v in edges: + u, v = u - 1, v - 1 + g[u].append(v) + g[v].append(u) + ans = [0] * (n - 1) + nxt = 0 + for mask in range(1, 1 << n): + if mask & (mask - 1) == 0: + continue + msk = mask + cur = msk.bit_length() - 1 + bfs(cur) + if msk == 0: + msk = mask + mx = bfs(nxt) + ans[mx - 1] += 1 + return ans +``` + ```java class Solution { private List[] g; @@ -238,52 +388,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector countSubgraphsForEachDiameter(int n, vector>& edges) { - vector> g(n); - for (auto& e : edges) { - int u = e[0] - 1, v = e[1] - 1; - g[u].emplace_back(v); - g[v].emplace_back(u); - } - vector ans(n - 1); - int nxt = 0, msk = 0, mx = 0; - function dfs = [&](int u, int d) { - msk ^= 1 << u; - if (mx < d) { - mx = d; - nxt = u; - } - for (int& v : g[u]) { - if (msk >> v & 1) { - dfs(v, d + 1); - } - } - }; - for (int mask = 1; mask < 1 << n; ++mask) { - if ((mask & (mask - 1)) == 0) { - continue; - } - msk = mask; - mx = 0; - int cur = 31 - __builtin_clz(msk); - dfs(cur, 0); - if (msk == 0) { - msk = mask; - mx = 0; - dfs(nxt, 0); - ++ans[mx - 1]; - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -334,47 +438,6 @@ public: }; ``` -### **Go** - -```go -func countSubgraphsForEachDiameter(n int, edges [][]int) []int { - g := make([][]int, n) - for _, e := range edges { - u, v := e[0]-1, e[1]-1 - g[u] = append(g[u], v) - g[v] = append(g[v], u) - } - ans := make([]int, n-1) - var msk, nxt, mx int - var dfs func(int, int) - dfs = func(u, d int) { - msk ^= 1 << u - if mx < d { - mx, nxt = d, u - } - for _, v := range g[u] { - if msk>>v&1 == 1 { - dfs(v, d+1) - } - } - } - for mask := 1; mask < 1< []); - for (const [u, v] of edges) { - g[u - 1].push(v - 1); - g[v - 1].push(u - 1); - } - const ans: number[] = new Array(n - 1).fill(0); - let [mx, msk, nxt] = [0, 0, 0]; - const dfs = (u: number, d: number) => { - if (mx < d) { - mx = d; - nxt = u; - } - msk ^= 1 << u; - for (const v of g[u]) { - if ((msk >> v) & 1) { - dfs(v, d + 1); - } - } - }; - for (let mask = 1; mask < 1 << n; ++mask) { - if ((mask & (mask - 1)) === 0) { - continue; - } - msk = mask; - mx = 0; - const cur = 31 - numberOfLeadingZeros(msk); - dfs(cur, 0); - if (msk === 0) { - msk = mask; - mx = 0; - dfs(nxt, 0); - ++ans[mx - 1]; - } - } - return ans; -} - -function numberOfLeadingZeros(i: number): number { - if (i == 0) return 32; - let n = 1; - if (i >>> 16 == 0) { - n += 16; - i <<= 16; - } - if (i >>> 24 == 0) { - n += 8; - i <<= 8; - } - if (i >>> 28 == 0) { - n += 4; - i <<= 4; - } - if (i >>> 30 == 0) { - n += 2; - i <<= 2; - } - n -= i >>> 31; - return n; -} -``` - ```ts function countSubgraphsForEachDiameter(n: number, edges: number[][]): number[] { const g = Array.from({ length: n }, () => []); @@ -555,10 +553,6 @@ function numberOfLeadingZeros(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README.md b/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README.md index 78e5b09b3f34b..7876925d06b5b 100644 --- a/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README.md +++ b/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README.md @@ -77,9 +77,7 @@ interface FontInfo { ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 根据题目描述,字体数组按升序排列。因此,我们可以二分枚举字体大小 `fontSize`,找到最大的并且能够在屏幕上显示文本字体大小即可。 @@ -89,10 +87,6 @@ interface FontInfo { -### **Python3** - - - ```python # """ # This is FontInfo's API interface. @@ -132,10 +126,6 @@ class Solution: return fonts[left] if check(fonts[left]) else -1 ``` -### **Java** - - - ```java /** * // This is the FontInfo's API interface. @@ -174,8 +164,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the FontInfo's API interface. @@ -214,8 +202,6 @@ public: }; ``` -### **JavaScript** - ```js /** * // This is the FontInfo's API interface. @@ -269,10 +255,6 @@ var maxFont = function (text, w, h, fonts, fontInfo) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README_EN.md b/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README_EN.md index 55b2ce045174d..f5c8be9148496 100644 --- a/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README_EN.md +++ b/solution/1600-1699/1618.Maximum Font to Fit a Sentence in a Screen/README_EN.md @@ -71,9 +71,9 @@ interface FontInfo { ## Solutions - +### Solution 1 -### **Python3** + ```python # """ @@ -114,8 +114,6 @@ class Solution: return fonts[left] if check(fonts[left]) else -1 ``` -### **Java** - ```java /** * // This is the FontInfo's API interface. @@ -154,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the FontInfo's API interface. @@ -194,8 +190,6 @@ public: }; ``` -### **JavaScript** - ```js /** * // This is the FontInfo's API interface. @@ -249,10 +243,6 @@ var maxFont = function (text, w, h, fonts, fontInfo) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1619.Mean of Array After Removing Some Elements/README.md b/solution/1600-1699/1619.Mean of Array After Removing Some Elements/README.md index 0799d0d6ecec4..a4df7380eb973 100644 --- a/solution/1600-1699/1619.Mean of Array After Removing Some Elements/README.md +++ b/solution/1600-1699/1619.Mean of Array After Removing Some Elements/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 直接模拟。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def trimMean(self, arr: List[int]) -> float: @@ -86,10 +80,6 @@ class Solution: return round(sum(t) / len(t), 5) ``` -### **Java** - - - ```java class Solution { public double trimMean(int[] arr) { @@ -104,23 +94,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function trimMean(arr: number[]): number { - arr.sort((a, b) => a - b); - let n = arr.length, - rmLen = n * 0.05; - let sum = 0; - for (let i = rmLen; i < n - rmLen; i++) { - sum += arr[i]; - } - return sum / (n * 0.9); -} -``` - -### **C++** - ```cpp class Solution { public: @@ -135,8 +108,6 @@ public: }; ``` -### **Go** - ```go func trimMean(arr []int) float64 { sort.Ints(arr) @@ -149,7 +120,18 @@ func trimMean(arr []int) float64 { } ``` -### **Rust** +```ts +function trimMean(arr: number[]): number { + arr.sort((a, b) => a - b); + let n = arr.length, + rmLen = n * 0.05; + let sum = 0; + for (let i = rmLen; i < n - rmLen; i++) { + sum += arr[i]; + } + return sum / (n * 0.9); +} +``` ```rust impl Solution { @@ -166,10 +148,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1619.Mean of Array After Removing Some Elements/README_EN.md b/solution/1600-1699/1619.Mean of Array After Removing Some Elements/README_EN.md index b0d464aaa4b5e..3bddd16676229 100644 --- a/solution/1600-1699/1619.Mean of Array After Removing Some Elements/README_EN.md +++ b/solution/1600-1699/1619.Mean of Array After Removing Some Elements/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return round(sum(t) / len(t), 5) ``` -### **Java** - ```java class Solution { public double trimMean(int[] arr) { @@ -72,23 +70,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function trimMean(arr: number[]): number { - arr.sort((a, b) => a - b); - let n = arr.length, - rmLen = n * 0.05; - let sum = 0; - for (let i = rmLen; i < n - rmLen; i++) { - sum += arr[i]; - } - return sum / (n * 0.9); -} -``` - -### **C++** - ```cpp class Solution { public: @@ -103,8 +84,6 @@ public: }; ``` -### **Go** - ```go func trimMean(arr []int) float64 { sort.Ints(arr) @@ -117,7 +96,18 @@ func trimMean(arr []int) float64 { } ``` -### **Rust** +```ts +function trimMean(arr: number[]): number { + arr.sort((a, b) => a - b); + let n = arr.length, + rmLen = n * 0.05; + let sum = 0; + for (let i = rmLen; i < n - rmLen; i++) { + sum += arr[i]; + } + return sum / (n * 0.9); +} +``` ```rust impl Solution { @@ -134,10 +124,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1620.Coordinate With Maximum Network Quality/README.md b/solution/1600-1699/1620.Coordinate With Maximum Network Quality/README.md index 71cbe544eb2fc..48016ddb29f2e 100644 --- a/solution/1600-1699/1620.Coordinate With Maximum Network Quality/README.md +++ b/solution/1600-1699/1620.Coordinate With Maximum Network Quality/README.md @@ -69,9 +69,7 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 由于坐标点的范围是 $[0,.. 50]$,因此我们可以直接暴力枚举所有的坐标点 $(i, j)$,计算每个坐标点的信号强度,然后找出信号强度最大的坐标点。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]: @@ -101,10 +95,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] bestCoordinate(int[][] towers, int radius) { @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func bestCoordinate(towers [][]int, radius int) []int { ans := []int{0, 0} @@ -183,10 +169,6 @@ func bestCoordinate(towers [][]int, radius int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1620.Coordinate With Maximum Network Quality/README_EN.md b/solution/1600-1699/1620.Coordinate With Maximum Network Quality/README_EN.md index bd7209af2dd6d..e151afa198345 100644 --- a/solution/1600-1699/1620.Coordinate With Maximum Network Quality/README_EN.md +++ b/solution/1600-1699/1620.Coordinate With Maximum Network Quality/README_EN.md @@ -66,9 +66,9 @@ No other coordinate has a higher network quality. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -88,8 +88,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] bestCoordinate(int[][] towers, int radius) { @@ -115,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +139,6 @@ public: }; ``` -### **Go** - ```go func bestCoordinate(towers [][]int, radius int) []int { ans := []int{0, 0} @@ -168,10 +162,6 @@ func bestCoordinate(towers [][]int, radius int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1621.Number of Sets of K Non-Overlapping Line Segments/README.md b/solution/1600-1699/1621.Number of Sets of K Non-Overlapping Line Segments/README.md index 14a3f6eabbdb0..d0e4cd2dfb9cc 100644 --- a/solution/1600-1699/1621.Number of Sets of K Non-Overlapping Line Segments/README.md +++ b/solution/1600-1699/1621.Number of Sets of K Non-Overlapping Line Segments/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 记 $f[i][j]$ 表示使用前 $i$ 个点构造了 $j$ 条线段,且最后一条线段的右端点不为 $i$ 的方案数;记 $g[i][j]$ 表示使用了前 $i$ 个点构造了 $j$ 条线段,且最后一条线段的右端点为 $i$ 的方案数。初始时 $f[1][0]=1$。 @@ -91,10 +89,6 @@ $$ -### **Python3** - - - ```python class Solution: def numberOfSets(self, n: int, k: int) -> int: @@ -114,10 +108,6 @@ class Solution: return (f[-1][-1] + g[-1][-1]) % mod ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -173,8 +161,6 @@ public: }; ``` -### **Go** - ```go func numberOfSets(n int, k int) int { f := make([][]int, n+1) @@ -201,8 +187,6 @@ func numberOfSets(n int, k int) int { } ``` -### **TypeScript** - ```ts function numberOfSets(n: number, k: number): number { const f = Array.from({ length: n + 1 }, _ => new Array(k + 1).fill(0)); @@ -225,10 +209,6 @@ function numberOfSets(n: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1621.Number of Sets of K Non-Overlapping Line Segments/README_EN.md b/solution/1600-1699/1621.Number of Sets of K Non-Overlapping Line Segments/README_EN.md index e8d12f8bff256..fc1a9e44b32c9 100644 --- a/solution/1600-1699/1621.Number of Sets of K Non-Overlapping Line Segments/README_EN.md +++ b/solution/1600-1699/1621.Number of Sets of K Non-Overlapping Line Segments/README_EN.md @@ -44,9 +44,9 @@ The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1), ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return (f[-1][-1] + g[-1][-1]) % mod ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +120,6 @@ public: }; ``` -### **Go** - ```go func numberOfSets(n int, k int) int { f := make([][]int, n+1) @@ -152,8 +146,6 @@ func numberOfSets(n int, k int) int { } ``` -### **TypeScript** - ```ts function numberOfSets(n: number, k: number): number { const f = Array.from({ length: n + 1 }, _ => new Array(k + 1).fill(0)); @@ -176,10 +168,6 @@ function numberOfSets(n: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1622.Fancy Sequence/README.md b/solution/1600-1699/1622.Fancy Sequence/README.md index 961a1ab46e558..2a35b09550545 100644 --- a/solution/1600-1699/1622.Fancy Sequence/README.md +++ b/solution/1600-1699/1622.Fancy Sequence/README.md @@ -56,9 +56,7 @@ fancy.getIndex(2); // 返回 20 ## 解法 - - -**方法一:线段树** +### 方法一:线段树 线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。区间修改时,需要使用**懒标记**保证效率。 @@ -69,10 +67,6 @@ fancy.getIndex(2); // 返回 20 -### **Python3** - - - ```python MOD = int(1e9 + 7) @@ -188,10 +182,6 @@ class Fancy: # param_4 = obj.getIndex(idx) ``` -### **Java** - - - ```java class Node { Node left; @@ -346,8 +336,6 @@ class Fancy { */ ``` -### **C++** - ```cpp const int MOD = 1e9 + 7; @@ -491,10 +479,6 @@ public: */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1622.Fancy Sequence/README_EN.md b/solution/1600-1699/1622.Fancy Sequence/README_EN.md index 3d5dde9d47730..c1847a0b8dc2a 100644 --- a/solution/1600-1699/1622.Fancy Sequence/README_EN.md +++ b/solution/1600-1699/1622.Fancy Sequence/README_EN.md @@ -52,11 +52,9 @@ fancy.getIndex(2); // return 20 ## Solutions - - -Segment Tree. +### Solution 1 -### **Python3** + ```python MOD = int(1e9 + 7) @@ -173,8 +171,6 @@ class Fancy: # param_4 = obj.getIndex(idx) ``` -### **Java** - ```java class Node { Node left; @@ -329,8 +325,6 @@ class Fancy { */ ``` -### **C++** - ```cpp const int MOD = 1e9 + 7; @@ -474,10 +468,6 @@ public: */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1623.All Valid Triplets That Can Represent a Country/README.md b/solution/1600-1699/1623.All Valid Triplets That Can Represent a Country/README.md index 0b53f20b54c2b..e576561fa2b94 100644 --- a/solution/1600-1699/1623.All Valid Triplets That Can Represent a Country/README.md +++ b/solution/1600-1699/1623.All Valid Triplets That Can Represent a Country/README.md @@ -116,12 +116,10 @@ student_id 是该表具有唯一值的列 ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -142,3 +140,5 @@ WHERE ``` + + diff --git a/solution/1600-1699/1623.All Valid Triplets That Can Represent a Country/README_EN.md b/solution/1600-1699/1623.All Valid Triplets That Can Represent a Country/README_EN.md index 73ebb59635ff0..aee8827d4d879 100644 --- a/solution/1600-1699/1623.All Valid Triplets That Can Represent a Country/README_EN.md +++ b/solution/1600-1699/1623.All Valid Triplets That Can Represent a Country/README_EN.md @@ -112,9 +112,9 @@ Let us see all the possible triplets. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -136,3 +136,5 @@ WHERE ``` + + diff --git a/solution/1600-1699/1624.Largest Substring Between Two Equal Characters/README.md b/solution/1600-1699/1624.Largest Substring Between Two Equal Characters/README.md index f156e790975ce..f911eb05c9a26 100644 --- a/solution/1600-1699/1624.Largest Substring Between Two Equal Characters/README.md +++ b/solution/1600-1699/1624.Largest Substring Between Two Equal Characters/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:数组或哈希表** +### 方法一:数组或哈希表 用数组或哈希表记录字符串 $s$ 每个字符第一次出现的位置。由于本题中字符串 $s$ 只含小写英文字母,因此可以用一个长度为 $26$ 的数组 $d$ 来记录,初始时数组元素值均为 $-1$。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def maxLengthBetweenEqualCharacters(self, s: str) -> int: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxLengthBetweenEqualCharacters(String s) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func maxLengthBetweenEqualCharacters(s string) int { d := make([]int, 26) @@ -144,31 +130,6 @@ func maxLengthBetweenEqualCharacters(s string) int { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int maxLengthBetweenEqualCharacters(char* s) { - int pos[26]; - memset(pos, -1, sizeof(pos)); - int n = strlen(s); - int res = -1; - for (int i = 0; i < n; i++) { - char c = s[i]; - int j = c - 'a'; - if (pos[j] == -1) { - pos[j] = i; - } else { - res = max(res, i - pos[j] - 1); - } - } - return res; -} -``` - -### **TypeScript** - ```ts function maxLengthBetweenEqualCharacters(s: string): number { const n = s.length; @@ -186,8 +147,6 @@ function maxLengthBetweenEqualCharacters(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_length_between_equal_characters(s: String) -> i32 { @@ -209,10 +168,27 @@ impl Solution { } ``` -### **...** - -``` +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +int maxLengthBetweenEqualCharacters(char* s) { + int pos[26]; + memset(pos, -1, sizeof(pos)); + int n = strlen(s); + int res = -1; + for (int i = 0; i < n; i++) { + char c = s[i]; + int j = c - 'a'; + if (pos[j] == -1) { + pos[j] = i; + } else { + res = max(res, i - pos[j] - 1); + } + } + return res; +} ``` + + diff --git a/solution/1600-1699/1624.Largest Substring Between Two Equal Characters/README_EN.md b/solution/1600-1699/1624.Largest Substring Between Two Equal Characters/README_EN.md index bfc8059f40173..1745aa4ac06b4 100644 --- a/solution/1600-1699/1624.Largest Substring Between Two Equal Characters/README_EN.md +++ b/solution/1600-1699/1624.Largest Substring Between Two Equal Characters/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxLengthBetweenEqualCharacters(String s) { @@ -80,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +97,6 @@ public: }; ``` -### **Go** - ```go func maxLengthBetweenEqualCharacters(s string) int { d := make([]int, 26) @@ -122,31 +116,6 @@ func maxLengthBetweenEqualCharacters(s string) int { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int maxLengthBetweenEqualCharacters(char* s) { - int pos[26]; - memset(pos, -1, sizeof(pos)); - int n = strlen(s); - int res = -1; - for (int i = 0; i < n; i++) { - char c = s[i]; - int j = c - 'a'; - if (pos[j] == -1) { - pos[j] = i; - } else { - res = max(res, i - pos[j] - 1); - } - } - return res; -} -``` - -### **TypeScript** - ```ts function maxLengthBetweenEqualCharacters(s: string): number { const n = s.length; @@ -164,8 +133,6 @@ function maxLengthBetweenEqualCharacters(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_length_between_equal_characters(s: String) -> i32 { @@ -187,10 +154,27 @@ impl Solution { } ``` -### **...** - -``` +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +int maxLengthBetweenEqualCharacters(char* s) { + int pos[26]; + memset(pos, -1, sizeof(pos)); + int n = strlen(s); + int res = -1; + for (int i = 0; i < n; i++) { + char c = s[i]; + int j = c - 'a'; + if (pos[j] == -1) { + pos[j] = i; + } else { + res = max(res, i - pos[j] - 1); + } + } + return res; +} ``` + + diff --git a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README.md b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README.md index f1b1ca45b09d3..02a63a21c3922 100644 --- a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README.md +++ b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README.md @@ -74,28 +74,12 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 本题数据规模较小,我们可以使用 BFS 暴力搜索所有可能的状态,然后取字典序最小的状态即可。 -**方法二:枚举** - -我们观察发现,对于累加操作,数字最多累加 $10$ 次,就会回到原来的状态;对于轮转操作,字符串最多轮转 $n$ 次,也会回到原来的状态。 - -因此,轮转操作最多产生 $n$ 种状态,如果轮转位数 $b$ 为偶数,累加操作只会对奇数位数字产生影响,因此总共产生 $n \times 10$ 种状态;如果轮转位数 $b$ 为奇数,累加操作既会对奇数位数字产生影响,也会对偶数位数字产生影响,因此总共产生 $n \times 10 \times 10$ 种状态。 - -所以,我们直接枚举所有的字符串状态,取字典序最小的状态即可。 - -时间复杂度 $O(n^2 \times 10^2)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度。 - -### **Python3** - - - ```python class Solution: def findLexSmallestString(self, s: str, a: int, b: int) -> str: @@ -117,35 +101,6 @@ class Solution: return ans ``` -```python -class Solution: - def findLexSmallestString(self, s: str, a: int, b: int) -> str: - ans = s - n = len(s) - s = list(s) - for _ in range(n): - s = s[-b:] + s[:-b] - for j in range(10): - for k in range(1, n, 2): - s[k] = str((int(s[k]) + a) % 10) - if b & 1: - for p in range(10): - for k in range(0, n, 2): - s[k] = str((int(s[k]) + a) % 10) - t = ''.join(s) - if ans > t: - ans = t - else: - t = ''.join(s) - if ans > t: - ans = t - return ans -``` - -### **Java** - - - ```java class Solution { public String findLexSmallestString(String s, int a, int b) { @@ -177,6 +132,102 @@ class Solution { } ``` +```cpp +class Solution { +public: + string findLexSmallestString(string s, int a, int b) { + queue q{{s}}; + unordered_set vis{{s}}; + string ans = s; + int n = s.size(); + while (!q.empty()) { + s = q.front(); + q.pop(); + ans = min(ans, s); + string t1 = s; + for (int i = 1; i < n; i += 2) { + t1[i] = (t1[i] - '0' + a) % 10 + '0'; + } + string t2 = s.substr(n - b) + s.substr(0, n - b); + for (auto& t : {t1, t2}) { + if (!vis.count(t)) { + vis.insert(t); + q.emplace(t); + } + } + } + return ans; + } +}; +``` + +```go +func findLexSmallestString(s string, a int, b int) string { + q := []string{s} + vis := map[string]bool{s: true} + ans := s + n := len(s) + for len(q) > 0 { + s = q[0] + q = q[1:] + if ans > s { + ans = s + } + t1 := []byte(s) + for i := 1; i < n; i += 2 { + t1[i] = byte((int(t1[i]-'0')+a)%10 + '0') + } + t2 := s[n-b:] + s[:n-b] + for _, t := range []string{string(t1), t2} { + if !vis[t] { + vis[t] = true + q = append(q, t) + } + } + } + return ans +} +``` + + + +### 方法二:枚举 + +我们观察发现,对于累加操作,数字最多累加 $10$ 次,就会回到原来的状态;对于轮转操作,字符串最多轮转 $n$ 次,也会回到原来的状态。 + +因此,轮转操作最多产生 $n$ 种状态,如果轮转位数 $b$ 为偶数,累加操作只会对奇数位数字产生影响,因此总共产生 $n \times 10$ 种状态;如果轮转位数 $b$ 为奇数,累加操作既会对奇数位数字产生影响,也会对偶数位数字产生影响,因此总共产生 $n \times 10 \times 10$ 种状态。 + +所以,我们直接枚举所有的字符串状态,取字典序最小的状态即可。 + +时间复杂度 $O(n^2 \times 10^2)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度。 + + + +```python +class Solution: + def findLexSmallestString(self, s: str, a: int, b: int) -> str: + ans = s + n = len(s) + s = list(s) + for _ in range(n): + s = s[-b:] + s[:-b] + for j in range(10): + for k in range(1, n, 2): + s[k] = str((int(s[k]) + a) % 10) + if b & 1: + for p in range(10): + for k in range(0, n, 2): + s[k] = str((int(s[k]) + a) % 10) + t = ''.join(s) + if ans > t: + ans = t + else: + t = ''.join(s) + if ans > t: + ans = t + return ans +``` + ```java class Solution { public String findLexSmallestString(String s, int a, int b) { @@ -212,37 +263,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string findLexSmallestString(string s, int a, int b) { - queue q{{s}}; - unordered_set vis{{s}}; - string ans = s; - int n = s.size(); - while (!q.empty()) { - s = q.front(); - q.pop(); - ans = min(ans, s); - string t1 = s; - for (int i = 1; i < n; i += 2) { - t1[i] = (t1[i] - '0' + a) % 10 + '0'; - } - string t2 = s.substr(n - b) + s.substr(0, n - b); - for (auto& t : {t1, t2}) { - if (!vis.count(t)) { - vis.insert(t); - q.emplace(t); - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -272,36 +292,6 @@ public: }; ``` -### **Go** - -```go -func findLexSmallestString(s string, a int, b int) string { - q := []string{s} - vis := map[string]bool{s: true} - ans := s - n := len(s) - for len(q) > 0 { - s = q[0] - q = q[1:] - if ans > s { - ans = s - } - t1 := []byte(s) - for i := 1; i < n; i += 2 { - t1[i] = byte((int(t1[i]-'0')+a)%10 + '0') - } - t2 := s[n-b:] + s[:n-b] - for _, t := range []string{string(t1), t2} { - if !vis[t] { - vis[t] = true - q = append(q, t) - } - } - } - return ans -} -``` - ```go func findLexSmallestString(s string, a int, b int) string { n := len(s) @@ -335,10 +325,6 @@ func findLexSmallestString(s string, a int, b int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README_EN.md b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README_EN.md index 61ce1ba5d96eb..309aea104ff46 100644 --- a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README_EN.md +++ b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README_EN.md @@ -70,12 +70,10 @@ There is no way to obtain a string that is lexicographically smaller than " ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def findLexSmallestString(self, s: str, a: int, b: int) -> str: @@ -97,33 +95,6 @@ class Solution: return ans ``` -```python -class Solution: - def findLexSmallestString(self, s: str, a: int, b: int) -> str: - ans = s - n = len(s) - s = list(s) - for _ in range(n): - s = s[-b:] + s[:-b] - for j in range(10): - for k in range(1, n, 2): - s[k] = str((int(s[k]) + a) % 10) - if b & 1: - for p in range(10): - for k in range(0, n, 2): - s[k] = str((int(s[k]) + a) % 10) - t = ''.join(s) - if ans > t: - ans = t - else: - t = ''.join(s) - if ans > t: - ans = t - return ans -``` - -### **Java** - ```java class Solution { public String findLexSmallestString(String s, int a, int b) { @@ -155,6 +126,94 @@ class Solution { } ``` +```cpp +class Solution { +public: + string findLexSmallestString(string s, int a, int b) { + queue q{{s}}; + unordered_set vis{{s}}; + string ans = s; + int n = s.size(); + while (!q.empty()) { + s = q.front(); + q.pop(); + ans = min(ans, s); + string t1 = s; + for (int i = 1; i < n; i += 2) { + t1[i] = (t1[i] - '0' + a) % 10 + '0'; + } + string t2 = s.substr(n - b) + s.substr(0, n - b); + for (auto& t : {t1, t2}) { + if (!vis.count(t)) { + vis.insert(t); + q.emplace(t); + } + } + } + return ans; + } +}; +``` + +```go +func findLexSmallestString(s string, a int, b int) string { + q := []string{s} + vis := map[string]bool{s: true} + ans := s + n := len(s) + for len(q) > 0 { + s = q[0] + q = q[1:] + if ans > s { + ans = s + } + t1 := []byte(s) + for i := 1; i < n; i += 2 { + t1[i] = byte((int(t1[i]-'0')+a)%10 + '0') + } + t2 := s[n-b:] + s[:n-b] + for _, t := range []string{string(t1), t2} { + if !vis[t] { + vis[t] = true + q = append(q, t) + } + } + } + return ans +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def findLexSmallestString(self, s: str, a: int, b: int) -> str: + ans = s + n = len(s) + s = list(s) + for _ in range(n): + s = s[-b:] + s[:-b] + for j in range(10): + for k in range(1, n, 2): + s[k] = str((int(s[k]) + a) % 10) + if b & 1: + for p in range(10): + for k in range(0, n, 2): + s[k] = str((int(s[k]) + a) % 10) + t = ''.join(s) + if ans > t: + ans = t + else: + t = ''.join(s) + if ans > t: + ans = t + return ans +``` + ```java class Solution { public String findLexSmallestString(String s, int a, int b) { @@ -190,37 +249,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string findLexSmallestString(string s, int a, int b) { - queue q{{s}}; - unordered_set vis{{s}}; - string ans = s; - int n = s.size(); - while (!q.empty()) { - s = q.front(); - q.pop(); - ans = min(ans, s); - string t1 = s; - for (int i = 1; i < n; i += 2) { - t1[i] = (t1[i] - '0' + a) % 10 + '0'; - } - string t2 = s.substr(n - b) + s.substr(0, n - b); - for (auto& t : {t1, t2}) { - if (!vis.count(t)) { - vis.insert(t); - q.emplace(t); - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -250,36 +278,6 @@ public: }; ``` -### **Go** - -```go -func findLexSmallestString(s string, a int, b int) string { - q := []string{s} - vis := map[string]bool{s: true} - ans := s - n := len(s) - for len(q) > 0 { - s = q[0] - q = q[1:] - if ans > s { - ans = s - } - t1 := []byte(s) - for i := 1; i < n; i += 2 { - t1[i] = byte((int(t1[i]-'0')+a)%10 + '0') - } - t2 := s[n-b:] + s[:n-b] - for _, t := range []string{string(t1), t2} { - if !vis[t] { - vis[t] = true - q = append(q, t) - } - } - } - return ans -} -``` - ```go func findLexSmallestString(s string, a int, b int) string { n := len(s) @@ -313,10 +311,6 @@ func findLexSmallestString(s string, a int, b int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1626.Best Team With No Conflicts/README.md b/solution/1600-1699/1626.Best Team With No Conflicts/README.md index c9bf5816cee37..1f0227d7ca72b 100644 --- a/solution/1600-1699/1626.Best Team With No Conflicts/README.md +++ b/solution/1600-1699/1626.Best Team With No Conflicts/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:排序 + 动态规划** +### 方法一:排序 + 动态规划 我们可以将球员按照分数从小到大排序,如果分数相同,则按照年龄从小到大排序。 @@ -63,22 +61,8 @@ 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为球员的数量。 -**方法二:排序 + 树状数组** - -与方法一类似,我们可以将球员按照分数从小到大排序,如果分数相同,则按照年龄从小到大排序。 - -接下来,我们使用树状数组维护不超过当前球员年龄的球员的最大得分。每一次,我们只需要在 $O(\log m)$ 的时间内找出不超过当前球员年龄的球员的最大得分,然后将当前球员的分数加到该得分上,即可更新当前球员年龄的最大得分。 - -最后,我们返回得分的最大值即可。 - -时间复杂度 $O(n \times (\log n + \log m))$,空间复杂度 $O(n + m)$。其中 $n$ 和 $m$ 分别为球员的数量和球员的年龄的最大值。 - -### **Python3** - - - ```python class Solution: def bestTeamScore(self, scores: List[int], ages: List[int]) -> int: @@ -93,6 +77,134 @@ class Solution: return max(f) ``` +```java +class Solution { + public int bestTeamScore(int[] scores, int[] ages) { + int n = ages.length; + int[][] arr = new int[n][2]; + for (int i = 0; i < n; ++i) { + arr[i] = new int[] {scores[i], ages[i]}; + } + Arrays.sort(arr, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + int[] f = new int[n]; + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (arr[i][1] >= arr[j][1]) { + f[i] = Math.max(f[i], f[j]); + } + } + f[i] += arr[i][0]; + ans = Math.max(ans, f[i]); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int bestTeamScore(vector& scores, vector& ages) { + int n = ages.size(); + vector> arr(n); + for (int i = 0; i < n; ++i) { + arr[i] = {scores[i], ages[i]}; + } + sort(arr.begin(), arr.end()); + vector f(n); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (arr[i].second >= arr[j].second) { + f[i] = max(f[i], f[j]); + } + } + f[i] += arr[i].first; + } + return *max_element(f.begin(), f.end()); + } +}; +``` + +```go +func bestTeamScore(scores []int, ages []int) int { + n := len(ages) + arr := make([][2]int, n) + for i := range ages { + arr[i] = [2]int{scores[i], ages[i]} + } + sort.Slice(arr, func(i, j int) bool { + a, b := arr[i], arr[j] + return a[0] < b[0] || a[0] == b[0] && a[1] < b[1] + }) + f := make([]int, n) + for i := range arr { + for j := 0; j < i; j++ { + if arr[i][1] >= arr[j][1] { + f[i] = max(f[i], f[j]) + } + } + f[i] += arr[i][0] + } + return slices.Max(f) +} +``` + +```ts +function bestTeamScore(scores: number[], ages: number[]): number { + const arr = ages.map((age, i) => [age, scores[i]]); + arr.sort((a, b) => (a[0] == b[0] ? a[1] - b[1] : a[0] - b[0])); + const n = arr.length; + const f = new Array(n).fill(0); + for (let i = 0; i < n; ++i) { + for (let j = 0; j < i; ++j) { + if (arr[i][1] >= arr[j][1]) { + f[i] = Math.max(f[i], f[j]); + } + } + f[i] += arr[i][1]; + } + return Math.max(...f); +} +``` + +```js +/** + * @param {number[]} scores + * @param {number[]} ages + * @return {number} + */ +var bestTeamScore = function (scores, ages) { + const arr = ages.map((age, i) => [age, scores[i]]); + arr.sort((a, b) => (a[0] == b[0] ? a[1] - b[1] : a[0] - b[0])); + const n = arr.length; + const f = new Array(n).fill(0); + for (let i = 0; i < n; ++i) { + for (let j = 0; j < i; ++j) { + if (arr[i][1] >= arr[j][1]) { + f[i] = Math.max(f[i], f[j]); + } + } + f[i] += arr[i][1]; + } + return Math.max(...f); +}; +``` + + + +### 方法二:排序 + 树状数组 + +与方法一类似,我们可以将球员按照分数从小到大排序,如果分数相同,则按照年龄从小到大排序。 + +接下来,我们使用树状数组维护不超过当前球员年龄的球员的最大得分。每一次,我们只需要在 $O(\log m)$ 的时间内找出不超过当前球员年龄的球员的最大得分,然后将当前球员的分数加到该得分上,即可更新当前球员年龄的最大得分。 + +最后,我们返回得分的最大值即可。 + +时间复杂度 $O(n \times (\log n + \log m))$,空间复杂度 $O(n + m)$。其中 $n$ 和 $m$ 分别为球员的数量和球员的年龄的最大值。 + + + ```python class BinaryIndexedTree: def __init__(self, n): @@ -121,35 +233,6 @@ class Solution: return tree.query(m) ``` -### **Java** - - - -```java -class Solution { - public int bestTeamScore(int[] scores, int[] ages) { - int n = ages.length; - int[][] arr = new int[n][2]; - for (int i = 0; i < n; ++i) { - arr[i] = new int[] {scores[i], ages[i]}; - } - Arrays.sort(arr, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); - int[] f = new int[n]; - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (arr[i][1] >= arr[j][1]) { - f[i] = Math.max(f[i], f[j]); - } - } - f[i] += arr[i][0]; - ans = Math.max(ans, f[i]); - } - return ans; - } -} -``` - ```java class BinaryIndexedTree { private int n; @@ -198,32 +281,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int bestTeamScore(vector& scores, vector& ages) { - int n = ages.size(); - vector> arr(n); - for (int i = 0; i < n; ++i) { - arr[i] = {scores[i], ages[i]}; - } - sort(arr.begin(), arr.end()); - vector f(n); - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (arr[i].second >= arr[j].second) { - f[i] = max(f[i], f[j]); - } - } - f[i] += arr[i].first; - } - return *max_element(f.begin(), f.end()); - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -271,32 +328,6 @@ public: }; ``` -### **Go** - -```go -func bestTeamScore(scores []int, ages []int) int { - n := len(ages) - arr := make([][2]int, n) - for i := range ages { - arr[i] = [2]int{scores[i], ages[i]} - } - sort.Slice(arr, func(i, j int) bool { - a, b := arr[i], arr[j] - return a[0] < b[0] || a[0] == b[0] && a[1] < b[1] - }) - f := make([]int, n) - for i := range arr { - for j := 0; j < i; j++ { - if arr[i][1] >= arr[j][1] { - f[i] = max(f[i], f[j]) - } - } - f[i] += arr[i][0] - } - return slices.Max(f) -} -``` - ```go type BinaryIndexedTree struct { n int @@ -344,55 +375,6 @@ func bestTeamScore(scores []int, ages []int) int { } ``` -### **TypeScript** - -```ts -function bestTeamScore(scores: number[], ages: number[]): number { - const arr = ages.map((age, i) => [age, scores[i]]); - arr.sort((a, b) => (a[0] == b[0] ? a[1] - b[1] : a[0] - b[0])); - const n = arr.length; - const f = new Array(n).fill(0); - for (let i = 0; i < n; ++i) { - for (let j = 0; j < i; ++j) { - if (arr[i][1] >= arr[j][1]) { - f[i] = Math.max(f[i], f[j]); - } - } - f[i] += arr[i][1]; - } - return Math.max(...f); -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} scores - * @param {number[]} ages - * @return {number} - */ -var bestTeamScore = function (scores, ages) { - const arr = ages.map((age, i) => [age, scores[i]]); - arr.sort((a, b) => (a[0] == b[0] ? a[1] - b[1] : a[0] - b[0])); - const n = arr.length; - const f = new Array(n).fill(0); - for (let i = 0; i < n; ++i) { - for (let j = 0; j < i; ++j) { - if (arr[i][1] >= arr[j][1]) { - f[i] = Math.max(f[i], f[j]); - } - } - f[i] += arr[i][1]; - } - return Math.max(...f); -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1626.Best Team With No Conflicts/README_EN.md b/solution/1600-1699/1626.Best Team With No Conflicts/README_EN.md index de78d4da00a25..a104f2b07d268 100644 --- a/solution/1600-1699/1626.Best Team With No Conflicts/README_EN.md +++ b/solution/1600-1699/1626.Best Team With No Conflicts/README_EN.md @@ -47,12 +47,10 @@ ## Solutions -LIS. +### Solution 1 -### **Python3** - ```python class Solution: def bestTeamScore(self, scores: List[int], ages: List[int]) -> int: @@ -67,6 +65,126 @@ class Solution: return max(f) ``` +```java +class Solution { + public int bestTeamScore(int[] scores, int[] ages) { + int n = ages.length; + int[][] arr = new int[n][2]; + for (int i = 0; i < n; ++i) { + arr[i] = new int[] {scores[i], ages[i]}; + } + Arrays.sort(arr, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + int[] f = new int[n]; + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (arr[i][1] >= arr[j][1]) { + f[i] = Math.max(f[i], f[j]); + } + } + f[i] += arr[i][0]; + ans = Math.max(ans, f[i]); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int bestTeamScore(vector& scores, vector& ages) { + int n = ages.size(); + vector> arr(n); + for (int i = 0; i < n; ++i) { + arr[i] = {scores[i], ages[i]}; + } + sort(arr.begin(), arr.end()); + vector f(n); + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { + if (arr[i].second >= arr[j].second) { + f[i] = max(f[i], f[j]); + } + } + f[i] += arr[i].first; + } + return *max_element(f.begin(), f.end()); + } +}; +``` + +```go +func bestTeamScore(scores []int, ages []int) int { + n := len(ages) + arr := make([][2]int, n) + for i := range ages { + arr[i] = [2]int{scores[i], ages[i]} + } + sort.Slice(arr, func(i, j int) bool { + a, b := arr[i], arr[j] + return a[0] < b[0] || a[0] == b[0] && a[1] < b[1] + }) + f := make([]int, n) + for i := range arr { + for j := 0; j < i; j++ { + if arr[i][1] >= arr[j][1] { + f[i] = max(f[i], f[j]) + } + } + f[i] += arr[i][0] + } + return slices.Max(f) +} +``` + +```ts +function bestTeamScore(scores: number[], ages: number[]): number { + const arr = ages.map((age, i) => [age, scores[i]]); + arr.sort((a, b) => (a[0] == b[0] ? a[1] - b[1] : a[0] - b[0])); + const n = arr.length; + const f = new Array(n).fill(0); + for (let i = 0; i < n; ++i) { + for (let j = 0; j < i; ++j) { + if (arr[i][1] >= arr[j][1]) { + f[i] = Math.max(f[i], f[j]); + } + } + f[i] += arr[i][1]; + } + return Math.max(...f); +} +``` + +```js +/** + * @param {number[]} scores + * @param {number[]} ages + * @return {number} + */ +var bestTeamScore = function (scores, ages) { + const arr = ages.map((age, i) => [age, scores[i]]); + arr.sort((a, b) => (a[0] == b[0] ? a[1] - b[1] : a[0] - b[0])); + const n = arr.length; + const f = new Array(n).fill(0); + for (let i = 0; i < n; ++i) { + for (let j = 0; j < i; ++j) { + if (arr[i][1] >= arr[j][1]) { + f[i] = Math.max(f[i], f[j]); + } + } + f[i] += arr[i][1]; + } + return Math.max(...f); +}; +``` + + + +### Solution 2 + + + ```python class BinaryIndexedTree: def __init__(self, n): @@ -95,33 +213,6 @@ class Solution: return tree.query(m) ``` -### **Java** - -```java -class Solution { - public int bestTeamScore(int[] scores, int[] ages) { - int n = ages.length; - int[][] arr = new int[n][2]; - for (int i = 0; i < n; ++i) { - arr[i] = new int[] {scores[i], ages[i]}; - } - Arrays.sort(arr, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); - int[] f = new int[n]; - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (arr[i][1] >= arr[j][1]) { - f[i] = Math.max(f[i], f[j]); - } - } - f[i] += arr[i][0]; - ans = Math.max(ans, f[i]); - } - return ans; - } -} -``` - ```java class BinaryIndexedTree { private int n; @@ -170,32 +261,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int bestTeamScore(vector& scores, vector& ages) { - int n = ages.size(); - vector> arr(n); - for (int i = 0; i < n; ++i) { - arr[i] = {scores[i], ages[i]}; - } - sort(arr.begin(), arr.end()); - vector f(n); - for (int i = 0; i < n; ++i) { - for (int j = 0; j < i; ++j) { - if (arr[i].second >= arr[j].second) { - f[i] = max(f[i], f[j]); - } - } - f[i] += arr[i].first; - } - return *max_element(f.begin(), f.end()); - } -}; -``` - ```cpp class BinaryIndexedTree { public: @@ -243,32 +308,6 @@ public: }; ``` -### **Go** - -```go -func bestTeamScore(scores []int, ages []int) int { - n := len(ages) - arr := make([][2]int, n) - for i := range ages { - arr[i] = [2]int{scores[i], ages[i]} - } - sort.Slice(arr, func(i, j int) bool { - a, b := arr[i], arr[j] - return a[0] < b[0] || a[0] == b[0] && a[1] < b[1] - }) - f := make([]int, n) - for i := range arr { - for j := 0; j < i; j++ { - if arr[i][1] >= arr[j][1] { - f[i] = max(f[i], f[j]) - } - } - f[i] += arr[i][0] - } - return slices.Max(f) -} -``` - ```go type BinaryIndexedTree struct { n int @@ -316,55 +355,6 @@ func bestTeamScore(scores []int, ages []int) int { } ``` -### **TypeScript** - -```ts -function bestTeamScore(scores: number[], ages: number[]): number { - const arr = ages.map((age, i) => [age, scores[i]]); - arr.sort((a, b) => (a[0] == b[0] ? a[1] - b[1] : a[0] - b[0])); - const n = arr.length; - const f = new Array(n).fill(0); - for (let i = 0; i < n; ++i) { - for (let j = 0; j < i; ++j) { - if (arr[i][1] >= arr[j][1]) { - f[i] = Math.max(f[i], f[j]); - } - } - f[i] += arr[i][1]; - } - return Math.max(...f); -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} scores - * @param {number[]} ages - * @return {number} - */ -var bestTeamScore = function (scores, ages) { - const arr = ages.map((age, i) => [age, scores[i]]); - arr.sort((a, b) => (a[0] == b[0] ? a[1] - b[1] : a[0] - b[0])); - const n = arr.length; - const f = new Array(n).fill(0); - for (let i = 0; i < n; ++i) { - for (let j = 0; j < i; ++j) { - if (arr[i][1] >= arr[j][1]) { - f[i] = Math.max(f[i], f[j]); - } - } - f[i] += arr[i][1]; - } - return Math.max(...f); -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1627.Graph Connectivity With Threshold/README.md b/solution/1600-1699/1627.Graph Connectivity With Threshold/README.md index 42a8a1272fd94..ae98349b4d9f3 100644 --- a/solution/1600-1699/1627.Graph Connectivity With Threshold/README.md +++ b/solution/1600-1699/1627.Graph Connectivity With Threshold/README.md @@ -82,9 +82,7 @@ ## 解法 - - -**方法一:并查集** +### 方法一:并查集 我们可以枚举 $z$ 以及 $z$ 的倍数,用并查集将它们连通起来。这样,对于每个查询 $[a, b]$,我们只需要判断 $a$ 和 $b$ 是否在同一个连通块中即可。 @@ -92,10 +90,6 @@ -### **Python3** - - - ```python class UnionFind: def __init__(self, n): @@ -131,10 +125,6 @@ class Solution: return [uf.find(a) == uf.find(b) for a, b in queries] ``` -### **Java** - - - ```java class UnionFind { private int[] p; @@ -189,8 +179,6 @@ class Solution { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -244,8 +232,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p, size []int @@ -298,8 +284,6 @@ func areConnected(n int, threshold int, queries [][]int) []bool { } ``` -### **TypeScript** - ```ts class UnionFind { p: number[]; @@ -345,10 +329,6 @@ function areConnected(n: number, threshold: number, queries: number[][]): boolea } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1627.Graph Connectivity With Threshold/README_EN.md b/solution/1600-1699/1627.Graph Connectivity With Threshold/README_EN.md index 9e3beb9666636..58c23c44815b0 100644 --- a/solution/1600-1699/1627.Graph Connectivity With Threshold/README_EN.md +++ b/solution/1600-1699/1627.Graph Connectivity With Threshold/README_EN.md @@ -68,7 +68,7 @@ Please notice that there can be multiple queries for the same pair of nodes [x, ## Solutions -**Solution 1: Union-Find** +### Solution 1: Union-Find We can enumerate $z$ and its multiples, and use union-find to connect them. In this way, for each query $[a, b]$, we only need to determine whether $a$ and $b$ are in the same connected component. @@ -76,8 +76,6 @@ The time complexity is $O(n \times \log n \times (\alpha(n) + q))$, and the spac -### **Python3** - ```python class UnionFind: def __init__(self, n): @@ -113,8 +111,6 @@ class Solution: return [uf.find(a) == uf.find(b) for a, b in queries] ``` -### **Java** - ```java class UnionFind { private int[] p; @@ -169,8 +165,6 @@ class Solution { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -224,8 +218,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p, size []int @@ -278,8 +270,6 @@ func areConnected(n int, threshold int, queries [][]int) []bool { } ``` -### **TypeScript** - ```ts class UnionFind { p: number[]; @@ -325,10 +315,6 @@ function areConnected(n: number, threshold: number, queries: number[][]): boolea } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1628.Design an Expression Tree With Evaluate Function/README.md b/solution/1600-1699/1628.Design an Expression Tree With Evaluate Function/README.md index f98ee48f66ca9..7ca1f356d4920 100644 --- a/solution/1600-1699/1628.Design an Expression Tree With Evaluate Function/README.md +++ b/solution/1600-1699/1628.Design an Expression Tree With Evaluate Function/README.md @@ -56,14 +56,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python import abc from abc import ABC, abstractmethod @@ -130,10 +126,6 @@ ans = expTree.evaluate(); """ ``` -### **Java** - - - ```java /** * This is the interface for the expression tree Node. @@ -213,8 +205,6 @@ class TreeBuilder { */ ``` -### **C++** - ```cpp /** * This is the interface for the expression tree Node. @@ -291,10 +281,6 @@ public: */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1628.Design an Expression Tree With Evaluate Function/README_EN.md b/solution/1600-1699/1628.Design an Expression Tree With Evaluate Function/README_EN.md index bd56d26ea583c..3652ba78e0624 100644 --- a/solution/1600-1699/1628.Design an Expression Tree With Evaluate Function/README_EN.md +++ b/solution/1600-1699/1628.Design an Expression Tree With Evaluate Function/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python import abc @@ -118,8 +118,6 @@ ans = expTree.evaluate(); """ ``` -### **Java** - ```java /** * This is the interface for the expression tree Node. @@ -199,8 +197,6 @@ class TreeBuilder { */ ``` -### **C++** - ```cpp /** * This is the interface for the expression tree Node. @@ -277,10 +273,6 @@ public: */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1629.Slowest Key/README.md b/solution/1600-1699/1629.Slowest Key/README.md index 4230b561746d0..f93e8acbb2fac 100644 --- a/solution/1600-1699/1629.Slowest Key/README.md +++ b/solution/1600-1699/1629.Slowest Key/README.md @@ -60,14 +60,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: @@ -81,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public char slowestKey(int[] releaseTimes, String keysPressed) { @@ -102,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +112,6 @@ public: }; ``` -### **Go** - ```go func slowestKey(releaseTimes []int, keysPressed string) byte { ans := keysPressed[0] @@ -139,10 +127,6 @@ func slowestKey(releaseTimes []int, keysPressed string) byte { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1629.Slowest Key/README_EN.md b/solution/1600-1699/1629.Slowest Key/README_EN.md index 2dda93264ced9..08cf1e216e13b 100644 --- a/solution/1600-1699/1629.Slowest Key/README_EN.md +++ b/solution/1600-1699/1629.Slowest Key/README_EN.md @@ -56,9 +56,9 @@ The longest of these was the keypress for 'a' with duration 16. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public char slowestKey(int[] releaseTimes, String keysPressed) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func slowestKey(releaseTimes []int, keysPressed string) byte { ans := keysPressed[0] @@ -129,10 +123,6 @@ func slowestKey(releaseTimes []int, keysPressed string) byte { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1630.Arithmetic Subarrays/README.md b/solution/1600-1699/1630.Arithmetic Subarrays/README.md index a9d24fd93a762..7f4853bd8a8dd 100644 --- a/solution/1600-1699/1630.Arithmetic Subarrays/README.md +++ b/solution/1600-1699/1630.Arithmetic Subarrays/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:数学 + 模拟** +### 方法一:数学 + 模拟 我们设计一个函数 $check(nums, l, r)$,用于判断子数组 $nums[l], nums[l+1], \dots, nums[r]$ 是否可以重新排列形成等差数列。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def checkArithmeticSubarrays( @@ -92,10 +86,6 @@ class Solution: return [check(nums, left, right) for left, right in zip(l, r)] ``` -### **Java** - - - ```java class Solution { public List checkArithmeticSubarrays(int[] nums, int[] l, int[] r) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +152,6 @@ public: }; ``` -### **Go** - ```go func checkArithmeticSubarrays(nums []int, l []int, r []int) (ans []bool) { check := func(nums []int, l, r int) bool { @@ -199,8 +185,6 @@ func checkArithmeticSubarrays(nums []int, l []int, r []int) (ans []bool) { } ``` -### **TypeScript** - ```ts function checkArithmeticSubarrays(nums: number[], l: number[], r: number[]): boolean[] { const check = (nums: number[], l: number, r: number): boolean => { @@ -232,8 +216,6 @@ function checkArithmeticSubarrays(nums: number[], l: number[], r: number[]): boo } ``` -### **Rust** - ```rust impl Solution { pub fn check_arithmetic_subarrays(nums: Vec, l: Vec, r: Vec) -> Vec { @@ -254,8 +236,6 @@ impl Solution { } ``` -### **C#** - ```cs class Solution { public bool Check(int[] arr) { @@ -281,13 +261,8 @@ class Solution { return ans; } } - -``` - -### **...** - -``` - ``` + + diff --git a/solution/1600-1699/1630.Arithmetic Subarrays/README_EN.md b/solution/1600-1699/1630.Arithmetic Subarrays/README_EN.md index de58fb13e664a..d24676eb9654a 100644 --- a/solution/1600-1699/1630.Arithmetic Subarrays/README_EN.md +++ b/solution/1600-1699/1630.Arithmetic Subarrays/README_EN.md @@ -55,9 +55,9 @@ In the 2nd query, the subarray is [5,9,3,7]. This can be ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return [check(nums, left, right) for left, right in zip(l, r)] ``` -### **Java** - ```java class Solution { public List checkArithmeticSubarrays(int[] nums, int[] l, int[] r) { @@ -109,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +140,6 @@ public: }; ``` -### **Go** - ```go func checkArithmeticSubarrays(nums []int, l []int, r []int) (ans []bool) { check := func(nums []int, l, r int) bool { @@ -179,8 +173,6 @@ func checkArithmeticSubarrays(nums []int, l []int, r []int) (ans []bool) { } ``` -### **TypeScript** - ```ts function checkArithmeticSubarrays(nums: number[], l: number[], r: number[]): boolean[] { const check = (nums: number[], l: number, r: number): boolean => { @@ -212,8 +204,6 @@ function checkArithmeticSubarrays(nums: number[], l: number[], r: number[]): boo } ``` -### **Rust** - ```rust impl Solution { pub fn check_arithmetic_subarrays(nums: Vec, l: Vec, r: Vec) -> Vec { @@ -234,8 +224,6 @@ impl Solution { } ``` -### **C#** - ```cs class Solution { public bool Check(int[] arr) { @@ -261,13 +249,8 @@ class Solution { return ans; } } - -``` - -### **...** - -``` - ``` + + diff --git a/solution/1600-1699/1631.Path With Minimum Effort/README.md b/solution/1600-1699/1631.Path With Minimum Effort/README.md index 941c1f824379a..8cc8779bd6a52 100644 --- a/solution/1600-1699/1631.Path With Minimum Effort/README.md +++ b/solution/1600-1699/1631.Path With Minimum Effort/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:并查集** +### 方法一:并查集 对于本题,我们可以把每个格子当做图的一个节点,把相邻两个格子的高度差绝对值当做边的权重,因此本题是求解从最左上角的节点到最右下角的节点的连通性问题。 @@ -66,30 +64,8 @@ 时间复杂度 $O(m \times n \times \log(m \times n))$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是二维数组的行数和列数。 -**方法二:二分查找 + BFS** - -我们注意到,如果一个路径的最大体力消耗值为 $x$,那么对于任意 $y > x$,该路径也是满足条件的,这存在着单调性,因此我们可以使用二分查找的方法,找到最小的满足条件的体力消耗值。 - -我们定义二分查找的左边界 $l=0$,右边界 $r=10^6$,每次取 $mid=(l+r)/2$,然后使用 BFS 判断是否存在一条从左上角到右下角的路径,使得路径上相邻节点的高度差绝对值都不大于 $mid$,如果存在,那么说明 $mid$ 还有可能是最小的满足条件的体力消耗值,因此令 $r=mid$,否则令 $l=mid+1$。 - -时间复杂度 $O(m \times n \times \log M)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是二维数组的行数和列数,而 $M$ 是二维数组中的最大值,本题中 $M=10^6$。 - -**方法三:堆优化的 Dijkstra 算法** - -我们可以把每个格子当做图的一个节点,把相邻两个格子的高度差绝对值当做边的权重,因此本题是求解从最左上角的节点到最右下角的节点的最短路径问题。 - -我们可以使用 Dijkstra 算法求解最短路径,使用优先队列(堆)来优化时间复杂度。具体地,我们维护一个大小为 $m \times n$ 的二维数组 $dist$,其中 $dist[i][j]$ 表示从左上角到节点 $(i,j)$ 的最短路径的最大权重,初始时 $dist[0][0]=0$,其余元素均为正无穷大。 - -我们用优先队列(堆)来存储节点,每次从优先队列(堆)中取出权重最小的节点,然后更新其相邻节点的权重,如果相邻节点的权重发生了改变,那么就把该节点加入优先队列(堆)中。当优先队列(堆)为空时,说明我们已经找到了最短路径。 - -时间复杂度 $O(m \times n \times \log(m \times n))$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是二维数组的行数和列数。 - -### **Python3** - - - ```python class UnionFind: def __init__(self, n): @@ -139,60 +115,6 @@ class Solution: return 0 ``` -```python -class Solution: - def minimumEffortPath(self, heights: List[List[int]]) -> int: - def check(h: int) -> bool: - q = deque([(0, 0)]) - vis = {(0, 0)} - dirs = (-1, 0, 1, 0, -1) - while q: - for _ in range(len(q)): - i, j = q.popleft() - if i == m - 1 and j == n - 1: - return True - for a, b in pairwise(dirs): - x, y = i + a, j + b - if ( - 0 <= x < m - and 0 <= y < n - and (x, y) not in vis - and abs(heights[i][j] - heights[x][y]) <= h - ): - q.append((x, y)) - vis.add((x, y)) - return False - - m, n = len(heights), len(heights[0]) - return bisect_left(range(10**6), True, key=check) -``` - -```python -class Solution: - def minimumEffortPath(self, heights: List[List[int]]) -> int: - m, n = len(heights), len(heights[0]) - dist = [[inf] * n for _ in range(m)] - dist[0][0] = 0 - dirs = (-1, 0, 1, 0, -1) - q = [(0, 0, 0)] - while q: - t, i, j = heappop(q) - for a, b in pairwise(dirs): - x, y = i + a, j + b - if ( - 0 <= x < m - and 0 <= y < n - and (d := max(t, abs(heights[i][j] - heights[x][y]))) < dist[x][y] - ): - dist[x][y] = d - heappush(q, (d, x, y)) - return int(dist[-1][-1]) -``` - -### **Java** - - - ```java class UnionFind { private final int[] p; @@ -263,81 +185,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumEffortPath(int[][] heights) { - int l = 0, r = 1000000; - while (l < r) { - int mid = (l + r) >> 1; - if (check(heights, mid)) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } - - private boolean check(int[][] heights, int h) { - int m = heights.length, n = heights[0].length; - boolean[][] vis = new boolean[m][n]; - Deque q = new ArrayDeque<>(); - q.add(new int[] {0, 0}); - vis[0][0] = true; - int[] dirs = {-1, 0, 1, 0, -1}; - while (!q.isEmpty()) { - var p = q.poll(); - int i = p[0], j = p[1]; - if (i == m - 1 && j == n - 1) { - return true; - } - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] - && Math.abs(heights[x][y] - heights[i][j]) <= h) { - q.add(new int[] {x, y}); - vis[x][y] = true; - } - } - } - return false; - } -} -``` - -```java -class Solution { - public int minimumEffortPath(int[][] heights) { - int m = heights.length, n = heights[0].length; - int[][] dist = new int[m][n]; - for (var row : dist) { - Arrays.fill(row, 1 << 30); - } - dist[0][0] = 0; - int[] dirs = {-1, 0, 1, 0, -1}; - PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); - pq.offer(new int[] {0, 0, 0}); - while (!pq.isEmpty()) { - var p = pq.poll(); - int t = p[0], i = p[1], j = p[2]; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n) { - int d = Math.max(t, Math.abs(heights[x][y] - heights[i][j])); - if (d < dist[x][y]) { - dist[x][y] = d; - pq.offer(new int[] {d, x, y}); - } - } - } - } - return dist[m - 1][n - 1]; - } -} -``` - -### **C++** - ```cpp class UnionFind { public: @@ -406,81 +253,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minimumEffortPath(vector>& heights) { - auto check = [&](int h) { - int m = heights.size(), n = heights[0].size(); - bool vis[m][n]; - memset(vis, false, sizeof(vis)); - queue> q{{{0, 0}}}; - vis[0][0] = true; - int dirs[5] = {-1, 0, 1, 0, -1}; - while (!q.empty()) { - auto [i, j] = q.front(); - q.pop(); - if (i == m - 1 && j == n - 1) { - return true; - } - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && abs(heights[x][y] - heights[i][j]) <= h) { - q.push({x, y}); - vis[x][y] = true; - } - } - } - return false; - }; - int l = 0, r = 1e6; - while (l < r) { - int mid = (l + r) >> 1; - if (check(mid)) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } -}; -``` - -```cpp -class Solution { -public: - int minimumEffortPath(vector>& heights) { - int m = heights.size(), n = heights[0].size(); - int dist[m][n]; - memset(dist, 0x3f, sizeof(dist)); - dist[0][0] = 0; - int dirs[5] = {0, 1, 0, -1, 0}; - using T = tuple; - priority_queue, greater> pq; - pq.emplace(0, 0, 0); - while (!pq.empty()) { - auto [t, i, j] = pq.top(); - pq.pop(); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x < 0 || x >= m || y < 0 || y >= n) { - continue; - } - int d = max(t, abs(heights[x][y] - heights[i][j])); - if (d < dist[x][y]) { - dist[x][y] = d; - pq.emplace(d, x, y); - } - } - } - return dist[m - 1][n - 1]; - } -}; -``` - -### **Go** - ```go type unionFind struct { p, size []int @@ -555,98 +327,10 @@ func abs(x int) int { } ``` -```go -func minimumEffortPath(heights [][]int) int { - return sort.Search(1e6, func(h int) bool { - m, n := len(heights), len(heights[0]) - vis := make([][]bool, m) - for i := range vis { - vis[i] = make([]bool, n) - } - vis[0][0] = true - q := [][2]int{} - q = append(q, [2]int{0, 0}) - dirs := [5]int{-1, 0, 1, 0, -1} - for len(q) > 0 { - p := q[0] - q = q[1:] - i, j := p[0], p[1] - if i == m-1 && j == n-1 { - return true - } - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && abs(heights[x][y]-heights[i][j]) <= h { - vis[x][y] = true - q = append(q, [2]int{x, y}) - } - } - } - return false - }) -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x -} -``` - -```go -func minimumEffortPath(heights [][]int) int { - m, n := len(heights), len(heights[0]) - dist := make([][]int, m) - for i := range dist { - dist[i] = make([]int, n) - for j := range dist[i] { - dist[i][j] = 1 << 30 - } - } - dirs := [5]int{-1, 0, 1, 0, -1} - dist[0][0] = 0 - pq := hp{} - heap.Push(&pq, tuple{0, 0, 0}) - for pq.Len() > 0 { - p := heap.Pop(&pq).(tuple) - t, i, j := p.t, p.i, p.j - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n { - if d := max(t, abs(heights[x][y]-heights[i][j])); d < dist[x][y] { - dist[x][y] = d - heap.Push(&pq, tuple{d, x, y}) - } - } - } - } - return dist[m-1][n-1] -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x -} - -type tuple struct{ t, i, j int } -type hp []tuple - -func (h hp) Len() int { return len(h) } -func (h hp) Less(i, j int) bool { return h[i].t < h[j].t } -func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } -func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } -``` - -### **TypeScript** - -```ts -class UnionFind { - private p: number[]; - private size: number[]; +```ts +class UnionFind { + private p: number[]; + private size: number[]; constructor(n: number) { this.p = Array.from({ length: n }, (_, i) => i); @@ -714,6 +398,168 @@ function minimumEffortPath(heights: number[][]): number { } ``` + + +### 方法二:二分查找 + BFS + +我们注意到,如果一个路径的最大体力消耗值为 $x$,那么对于任意 $y > x$,该路径也是满足条件的,这存在着单调性,因此我们可以使用二分查找的方法,找到最小的满足条件的体力消耗值。 + +我们定义二分查找的左边界 $l=0$,右边界 $r=10^6$,每次取 $mid=(l+r)/2$,然后使用 BFS 判断是否存在一条从左上角到右下角的路径,使得路径上相邻节点的高度差绝对值都不大于 $mid$,如果存在,那么说明 $mid$ 还有可能是最小的满足条件的体力消耗值,因此令 $r=mid$,否则令 $l=mid+1$。 + +时间复杂度 $O(m \times n \times \log M)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是二维数组的行数和列数,而 $M$ 是二维数组中的最大值,本题中 $M=10^6$。 + + + +```python +class Solution: + def minimumEffortPath(self, heights: List[List[int]]) -> int: + def check(h: int) -> bool: + q = deque([(0, 0)]) + vis = {(0, 0)} + dirs = (-1, 0, 1, 0, -1) + while q: + for _ in range(len(q)): + i, j = q.popleft() + if i == m - 1 and j == n - 1: + return True + for a, b in pairwise(dirs): + x, y = i + a, j + b + if ( + 0 <= x < m + and 0 <= y < n + and (x, y) not in vis + and abs(heights[i][j] - heights[x][y]) <= h + ): + q.append((x, y)) + vis.add((x, y)) + return False + + m, n = len(heights), len(heights[0]) + return bisect_left(range(10**6), True, key=check) +``` + +```java +class Solution { + public int minimumEffortPath(int[][] heights) { + int l = 0, r = 1000000; + while (l < r) { + int mid = (l + r) >> 1; + if (check(heights, mid)) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } + + private boolean check(int[][] heights, int h) { + int m = heights.length, n = heights[0].length; + boolean[][] vis = new boolean[m][n]; + Deque q = new ArrayDeque<>(); + q.add(new int[] {0, 0}); + vis[0][0] = true; + int[] dirs = {-1, 0, 1, 0, -1}; + while (!q.isEmpty()) { + var p = q.poll(); + int i = p[0], j = p[1]; + if (i == m - 1 && j == n - 1) { + return true; + } + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] + && Math.abs(heights[x][y] - heights[i][j]) <= h) { + q.add(new int[] {x, y}); + vis[x][y] = true; + } + } + } + return false; + } +} +``` + +```cpp +class Solution { +public: + int minimumEffortPath(vector>& heights) { + auto check = [&](int h) { + int m = heights.size(), n = heights[0].size(); + bool vis[m][n]; + memset(vis, false, sizeof(vis)); + queue> q{{{0, 0}}}; + vis[0][0] = true; + int dirs[5] = {-1, 0, 1, 0, -1}; + while (!q.empty()) { + auto [i, j] = q.front(); + q.pop(); + if (i == m - 1 && j == n - 1) { + return true; + } + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && abs(heights[x][y] - heights[i][j]) <= h) { + q.push({x, y}); + vis[x][y] = true; + } + } + } + return false; + }; + int l = 0, r = 1e6; + while (l < r) { + int mid = (l + r) >> 1; + if (check(mid)) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } +}; +``` + +```go +func minimumEffortPath(heights [][]int) int { + return sort.Search(1e6, func(h int) bool { + m, n := len(heights), len(heights[0]) + vis := make([][]bool, m) + for i := range vis { + vis[i] = make([]bool, n) + } + vis[0][0] = true + q := [][2]int{} + q = append(q, [2]int{0, 0}) + dirs := [5]int{-1, 0, 1, 0, -1} + for len(q) > 0 { + p := q[0] + q = q[1:] + i, j := p[0], p[1] + if i == m-1 && j == n-1 { + return true + } + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && abs(heights[x][y]-heights[i][j]) <= h { + vis[x][y] = true + q = append(q, [2]int{x, y}) + } + } + } + return false + }) +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} +``` + ```ts function minimumEffortPath(heights: number[][]): number { const check = (h: number): boolean => { @@ -762,6 +608,152 @@ function minimumEffortPath(heights: number[][]): number { } ``` + + +### 方法三:堆优化的 Dijkstra 算法 + +我们可以把每个格子当做图的一个节点,把相邻两个格子的高度差绝对值当做边的权重,因此本题是求解从最左上角的节点到最右下角的节点的最短路径问题。 + +我们可以使用 Dijkstra 算法求解最短路径,使用优先队列(堆)来优化时间复杂度。具体地,我们维护一个大小为 $m \times n$ 的二维数组 $dist$,其中 $dist[i][j]$ 表示从左上角到节点 $(i,j)$ 的最短路径的最大权重,初始时 $dist[0][0]=0$,其余元素均为正无穷大。 + +我们用优先队列(堆)来存储节点,每次从优先队列(堆)中取出权重最小的节点,然后更新其相邻节点的权重,如果相邻节点的权重发生了改变,那么就把该节点加入优先队列(堆)中。当优先队列(堆)为空时,说明我们已经找到了最短路径。 + +时间复杂度 $O(m \times n \times \log(m \times n))$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是二维数组的行数和列数。 + + + +```python +class Solution: + def minimumEffortPath(self, heights: List[List[int]]) -> int: + m, n = len(heights), len(heights[0]) + dist = [[inf] * n for _ in range(m)] + dist[0][0] = 0 + dirs = (-1, 0, 1, 0, -1) + q = [(0, 0, 0)] + while q: + t, i, j = heappop(q) + for a, b in pairwise(dirs): + x, y = i + a, j + b + if ( + 0 <= x < m + and 0 <= y < n + and (d := max(t, abs(heights[i][j] - heights[x][y]))) < dist[x][y] + ): + dist[x][y] = d + heappush(q, (d, x, y)) + return int(dist[-1][-1]) +``` + +```java +class Solution { + public int minimumEffortPath(int[][] heights) { + int m = heights.length, n = heights[0].length; + int[][] dist = new int[m][n]; + for (var row : dist) { + Arrays.fill(row, 1 << 30); + } + dist[0][0] = 0; + int[] dirs = {-1, 0, 1, 0, -1}; + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); + pq.offer(new int[] {0, 0, 0}); + while (!pq.isEmpty()) { + var p = pq.poll(); + int t = p[0], i = p[1], j = p[2]; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + int d = Math.max(t, Math.abs(heights[x][y] - heights[i][j])); + if (d < dist[x][y]) { + dist[x][y] = d; + pq.offer(new int[] {d, x, y}); + } + } + } + } + return dist[m - 1][n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int minimumEffortPath(vector>& heights) { + int m = heights.size(), n = heights[0].size(); + int dist[m][n]; + memset(dist, 0x3f, sizeof(dist)); + dist[0][0] = 0; + int dirs[5] = {0, 1, 0, -1, 0}; + using T = tuple; + priority_queue, greater> pq; + pq.emplace(0, 0, 0); + while (!pq.empty()) { + auto [t, i, j] = pq.top(); + pq.pop(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n) { + continue; + } + int d = max(t, abs(heights[x][y] - heights[i][j])); + if (d < dist[x][y]) { + dist[x][y] = d; + pq.emplace(d, x, y); + } + } + } + return dist[m - 1][n - 1]; + } +}; +``` + +```go +func minimumEffortPath(heights [][]int) int { + m, n := len(heights), len(heights[0]) + dist := make([][]int, m) + for i := range dist { + dist[i] = make([]int, n) + for j := range dist[i] { + dist[i][j] = 1 << 30 + } + } + dirs := [5]int{-1, 0, 1, 0, -1} + dist[0][0] = 0 + pq := hp{} + heap.Push(&pq, tuple{0, 0, 0}) + for pq.Len() > 0 { + p := heap.Pop(&pq).(tuple) + t, i, j := p.t, p.i, p.j + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n { + if d := max(t, abs(heights[x][y]-heights[i][j])); d < dist[x][y] { + dist[x][y] = d + heap.Push(&pq, tuple{d, x, y}) + } + } + } + } + return dist[m-1][n-1] +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} + +type tuple struct{ t, i, j int } +type hp []tuple + +func (h hp) Len() int { return len(h) } +func (h hp) Less(i, j int) bool { return h[i].t < h[j].t } +func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } +func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } +``` + ```ts function minimumEffortPath(heights: number[][]): number { const m = heights.length; @@ -788,10 +780,6 @@ function minimumEffortPath(heights: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1631.Path With Minimum Effort/README_EN.md b/solution/1600-1699/1631.Path With Minimum Effort/README_EN.md index f23a28223908d..30e08311e6bd5 100644 --- a/solution/1600-1699/1631.Path With Minimum Effort/README_EN.md +++ b/solution/1600-1699/1631.Path With Minimum Effort/README_EN.md @@ -52,7 +52,7 @@ This is better than the route of [1,2,2,2,5], where the maximum absolute differe ## Solutions -**Solution 1: Union-Find** +### Solution 1: Union-Find For this problem, we can treat each cell as a node in a graph, and the absolute difference in height between two adjacent cells as the weight of the edge. Therefore, this problem is to solve the connectivity problem from the top-left node to the bottom-right node. @@ -60,28 +60,8 @@ We first construct a set of edges, then sort them in ascending order of edge wei The time complexity is $O(m \times n \times \log(m \times n))$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the number of rows and columns in the two-dimensional array, respectively. -**Solution 2: Binary Search + BFS** - -We notice that if the maximum physical consumption value of a path is $x$, then for any $y > x$, this path also meets the conditions. This shows monotonicity, so we can use the binary search method to find the minimum physical consumption value that meets the conditions. - -We define the left boundary of the binary search as $l=0$, and the right boundary as $r=10^6$. Each time we take $mid=(l+r)/2$, then use BFS to determine whether there is a path from the top-left corner to the bottom-right corner, so that the absolute difference in height between adjacent nodes on the path is not greater than $mid$. If it exists, it means that $mid$ may still be the minimum physical consumption value that meets the conditions, so we set $r=mid$, otherwise we set $l=mid+1$. - -The time complexity is $O(m \times n \times \log M)$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the number of rows and columns in the two-dimensional array, respectively, and $M$ is the maximum value in the two-dimensional array. In this problem, $M=10^6$. - -**Solution 3: Heap-optimized Dijkstra Algorithm** - -We can treat each cell as a node in a graph, and the absolute difference in height between two adjacent cells as the weight of the edge. Therefore, this problem is to solve the shortest path problem from the top-left node to the bottom-right node. - -We can use the Dijkstra algorithm to solve the shortest path problem, and use a priority queue (heap) to optimize the time complexity. Specifically, we maintain a two-dimensional array $dist$ of size $m \times n$, where $dist[i][j]$ represents the maximum weight of the shortest path from the top-left corner to the node $(i,j)$. Initially, $dist[0][0]=0$, and all other elements are positive infinity. - -We use a priority queue (heap) to store nodes, and each time we take out the node with the smallest weight from the priority queue (heap), then update the weights of its adjacent nodes. If the weight of an adjacent node changes, then we add this node to the priority queue (heap). When the priority queue (heap) is empty, it means that we have found the shortest path. - -The time complexity is $O(m \times n \times \log(m \times n))$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the number of rows and columns in the two-dimensional array, respectively. - -### **Python3** - ```python class UnionFind: def __init__(self, n): @@ -131,58 +111,6 @@ class Solution: return 0 ``` -```python -class Solution: - def minimumEffortPath(self, heights: List[List[int]]) -> int: - def check(h: int) -> bool: - q = deque([(0, 0)]) - vis = {(0, 0)} - dirs = (-1, 0, 1, 0, -1) - while q: - for _ in range(len(q)): - i, j = q.popleft() - if i == m - 1 and j == n - 1: - return True - for a, b in pairwise(dirs): - x, y = i + a, j + b - if ( - 0 <= x < m - and 0 <= y < n - and (x, y) not in vis - and abs(heights[i][j] - heights[x][y]) <= h - ): - q.append((x, y)) - vis.add((x, y)) - return False - - m, n = len(heights), len(heights[0]) - return bisect_left(range(10**6), True, key=check) -``` - -```python -class Solution: - def minimumEffortPath(self, heights: List[List[int]]) -> int: - m, n = len(heights), len(heights[0]) - dist = [[inf] * n for _ in range(m)] - dist[0][0] = 0 - dirs = (-1, 0, 1, 0, -1) - q = [(0, 0, 0)] - while q: - t, i, j = heappop(q) - for a, b in pairwise(dirs): - x, y = i + a, j + b - if ( - 0 <= x < m - and 0 <= y < n - and (d := max(t, abs(heights[i][j] - heights[x][y]))) < dist[x][y] - ): - dist[x][y] = d - heappush(q, (d, x, y)) - return int(dist[-1][-1]) -``` - -### **Java** - ```java class UnionFind { private final int[] p; @@ -253,81 +181,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumEffortPath(int[][] heights) { - int l = 0, r = 1000000; - while (l < r) { - int mid = (l + r) >> 1; - if (check(heights, mid)) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } - - private boolean check(int[][] heights, int h) { - int m = heights.length, n = heights[0].length; - boolean[][] vis = new boolean[m][n]; - Deque q = new ArrayDeque<>(); - q.add(new int[] {0, 0}); - vis[0][0] = true; - int[] dirs = {-1, 0, 1, 0, -1}; - while (!q.isEmpty()) { - var p = q.poll(); - int i = p[0], j = p[1]; - if (i == m - 1 && j == n - 1) { - return true; - } - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] - && Math.abs(heights[x][y] - heights[i][j]) <= h) { - q.add(new int[] {x, y}); - vis[x][y] = true; - } - } - } - return false; - } -} -``` - -```java -class Solution { - public int minimumEffortPath(int[][] heights) { - int m = heights.length, n = heights[0].length; - int[][] dist = new int[m][n]; - for (var row : dist) { - Arrays.fill(row, 1 << 30); - } - dist[0][0] = 0; - int[] dirs = {-1, 0, 1, 0, -1}; - PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); - pq.offer(new int[] {0, 0, 0}); - while (!pq.isEmpty()) { - var p = pq.poll(); - int t = p[0], i = p[1], j = p[2]; - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n) { - int d = Math.max(t, Math.abs(heights[x][y] - heights[i][j])); - if (d < dist[x][y]) { - dist[x][y] = d; - pq.offer(new int[] {d, x, y}); - } - } - } - } - return dist[m - 1][n - 1]; - } -} -``` - -### **C++** - ```cpp class UnionFind { public: @@ -396,81 +249,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minimumEffortPath(vector>& heights) { - auto check = [&](int h) { - int m = heights.size(), n = heights[0].size(); - bool vis[m][n]; - memset(vis, false, sizeof(vis)); - queue> q{{{0, 0}}}; - vis[0][0] = true; - int dirs[5] = {-1, 0, 1, 0, -1}; - while (!q.empty()) { - auto [i, j] = q.front(); - q.pop(); - if (i == m - 1 && j == n - 1) { - return true; - } - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && abs(heights[x][y] - heights[i][j]) <= h) { - q.push({x, y}); - vis[x][y] = true; - } - } - } - return false; - }; - int l = 0, r = 1e6; - while (l < r) { - int mid = (l + r) >> 1; - if (check(mid)) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } -}; -``` - -```cpp -class Solution { -public: - int minimumEffortPath(vector>& heights) { - int m = heights.size(), n = heights[0].size(); - int dist[m][n]; - memset(dist, 0x3f, sizeof(dist)); - dist[0][0] = 0; - int dirs[5] = {0, 1, 0, -1, 0}; - using T = tuple; - priority_queue, greater> pq; - pq.emplace(0, 0, 0); - while (!pq.empty()) { - auto [t, i, j] = pq.top(); - pq.pop(); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x < 0 || x >= m || y < 0 || y >= n) { - continue; - } - int d = max(t, abs(heights[x][y] - heights[i][j])); - if (d < dist[x][y]) { - dist[x][y] = d; - pq.emplace(d, x, y); - } - } - } - return dist[m - 1][n - 1]; - } -}; -``` - -### **Go** - ```go type unionFind struct { p, size []int @@ -545,98 +323,10 @@ func abs(x int) int { } ``` -```go -func minimumEffortPath(heights [][]int) int { - return sort.Search(1e6, func(h int) bool { - m, n := len(heights), len(heights[0]) - vis := make([][]bool, m) - for i := range vis { - vis[i] = make([]bool, n) - } - vis[0][0] = true - q := [][2]int{} - q = append(q, [2]int{0, 0}) - dirs := [5]int{-1, 0, 1, 0, -1} - for len(q) > 0 { - p := q[0] - q = q[1:] - i, j := p[0], p[1] - if i == m-1 && j == n-1 { - return true - } - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && abs(heights[x][y]-heights[i][j]) <= h { - vis[x][y] = true - q = append(q, [2]int{x, y}) - } - } - } - return false - }) -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x -} -``` - -```go -func minimumEffortPath(heights [][]int) int { - m, n := len(heights), len(heights[0]) - dist := make([][]int, m) - for i := range dist { - dist[i] = make([]int, n) - for j := range dist[i] { - dist[i][j] = 1 << 30 - } - } - dirs := [5]int{-1, 0, 1, 0, -1} - dist[0][0] = 0 - pq := hp{} - heap.Push(&pq, tuple{0, 0, 0}) - for pq.Len() > 0 { - p := heap.Pop(&pq).(tuple) - t, i, j := p.t, p.i, p.j - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n { - if d := max(t, abs(heights[x][y]-heights[i][j])); d < dist[x][y] { - dist[x][y] = d - heap.Push(&pq, tuple{d, x, y}) - } - } - } - } - return dist[m-1][n-1] -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x -} - -type tuple struct{ t, i, j int } -type hp []tuple - -func (h hp) Len() int { return len(h) } -func (h hp) Less(i, j int) bool { return h[i].t < h[j].t } -func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } -func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } -``` - -### **TypeScript** - -```ts -class UnionFind { - private p: number[]; - private size: number[]; +```ts +class UnionFind { + private p: number[]; + private size: number[]; constructor(n: number) { this.p = Array.from({ length: n }, (_, i) => i); @@ -704,6 +394,168 @@ function minimumEffortPath(heights: number[][]): number { } ``` + + +### Solution 2: Binary Search + BFS + +We notice that if the maximum physical consumption value of a path is $x$, then for any $y > x$, this path also meets the conditions. This shows monotonicity, so we can use the binary search method to find the minimum physical consumption value that meets the conditions. + +We define the left boundary of the binary search as $l=0$, and the right boundary as $r=10^6$. Each time we take $mid=(l+r)/2$, then use BFS to determine whether there is a path from the top-left corner to the bottom-right corner, so that the absolute difference in height between adjacent nodes on the path is not greater than $mid$. If it exists, it means that $mid$ may still be the minimum physical consumption value that meets the conditions, so we set $r=mid$, otherwise we set $l=mid+1$. + +The time complexity is $O(m \times n \times \log M)$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the number of rows and columns in the two-dimensional array, respectively, and $M$ is the maximum value in the two-dimensional array. In this problem, $M=10^6$. + + + +```python +class Solution: + def minimumEffortPath(self, heights: List[List[int]]) -> int: + def check(h: int) -> bool: + q = deque([(0, 0)]) + vis = {(0, 0)} + dirs = (-1, 0, 1, 0, -1) + while q: + for _ in range(len(q)): + i, j = q.popleft() + if i == m - 1 and j == n - 1: + return True + for a, b in pairwise(dirs): + x, y = i + a, j + b + if ( + 0 <= x < m + and 0 <= y < n + and (x, y) not in vis + and abs(heights[i][j] - heights[x][y]) <= h + ): + q.append((x, y)) + vis.add((x, y)) + return False + + m, n = len(heights), len(heights[0]) + return bisect_left(range(10**6), True, key=check) +``` + +```java +class Solution { + public int minimumEffortPath(int[][] heights) { + int l = 0, r = 1000000; + while (l < r) { + int mid = (l + r) >> 1; + if (check(heights, mid)) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } + + private boolean check(int[][] heights, int h) { + int m = heights.length, n = heights[0].length; + boolean[][] vis = new boolean[m][n]; + Deque q = new ArrayDeque<>(); + q.add(new int[] {0, 0}); + vis[0][0] = true; + int[] dirs = {-1, 0, 1, 0, -1}; + while (!q.isEmpty()) { + var p = q.poll(); + int i = p[0], j = p[1]; + if (i == m - 1 && j == n - 1) { + return true; + } + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] + && Math.abs(heights[x][y] - heights[i][j]) <= h) { + q.add(new int[] {x, y}); + vis[x][y] = true; + } + } + } + return false; + } +} +``` + +```cpp +class Solution { +public: + int minimumEffortPath(vector>& heights) { + auto check = [&](int h) { + int m = heights.size(), n = heights[0].size(); + bool vis[m][n]; + memset(vis, false, sizeof(vis)); + queue> q{{{0, 0}}}; + vis[0][0] = true; + int dirs[5] = {-1, 0, 1, 0, -1}; + while (!q.empty()) { + auto [i, j] = q.front(); + q.pop(); + if (i == m - 1 && j == n - 1) { + return true; + } + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && abs(heights[x][y] - heights[i][j]) <= h) { + q.push({x, y}); + vis[x][y] = true; + } + } + } + return false; + }; + int l = 0, r = 1e6; + while (l < r) { + int mid = (l + r) >> 1; + if (check(mid)) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } +}; +``` + +```go +func minimumEffortPath(heights [][]int) int { + return sort.Search(1e6, func(h int) bool { + m, n := len(heights), len(heights[0]) + vis := make([][]bool, m) + for i := range vis { + vis[i] = make([]bool, n) + } + vis[0][0] = true + q := [][2]int{} + q = append(q, [2]int{0, 0}) + dirs := [5]int{-1, 0, 1, 0, -1} + for len(q) > 0 { + p := q[0] + q = q[1:] + i, j := p[0], p[1] + if i == m-1 && j == n-1 { + return true + } + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && abs(heights[x][y]-heights[i][j]) <= h { + vis[x][y] = true + q = append(q, [2]int{x, y}) + } + } + } + return false + }) +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} +``` + ```ts function minimumEffortPath(heights: number[][]): number { const check = (h: number): boolean => { @@ -752,6 +604,152 @@ function minimumEffortPath(heights: number[][]): number { } ``` + + +### Solution 3: Heap-optimized Dijkstra Algorithm + +We can treat each cell as a node in a graph, and the absolute difference in height between two adjacent cells as the weight of the edge. Therefore, this problem is to solve the shortest path problem from the top-left node to the bottom-right node. + +We can use the Dijkstra algorithm to solve the shortest path problem, and use a priority queue (heap) to optimize the time complexity. Specifically, we maintain a two-dimensional array $dist$ of size $m \times n$, where $dist[i][j]$ represents the maximum weight of the shortest path from the top-left corner to the node $(i,j)$. Initially, $dist[0][0]=0$, and all other elements are positive infinity. + +We use a priority queue (heap) to store nodes, and each time we take out the node with the smallest weight from the priority queue (heap), then update the weights of its adjacent nodes. If the weight of an adjacent node changes, then we add this node to the priority queue (heap). When the priority queue (heap) is empty, it means that we have found the shortest path. + +The time complexity is $O(m \times n \times \log(m \times n))$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the number of rows and columns in the two-dimensional array, respectively. + + + +```python +class Solution: + def minimumEffortPath(self, heights: List[List[int]]) -> int: + m, n = len(heights), len(heights[0]) + dist = [[inf] * n for _ in range(m)] + dist[0][0] = 0 + dirs = (-1, 0, 1, 0, -1) + q = [(0, 0, 0)] + while q: + t, i, j = heappop(q) + for a, b in pairwise(dirs): + x, y = i + a, j + b + if ( + 0 <= x < m + and 0 <= y < n + and (d := max(t, abs(heights[i][j] - heights[x][y]))) < dist[x][y] + ): + dist[x][y] = d + heappush(q, (d, x, y)) + return int(dist[-1][-1]) +``` + +```java +class Solution { + public int minimumEffortPath(int[][] heights) { + int m = heights.length, n = heights[0].length; + int[][] dist = new int[m][n]; + for (var row : dist) { + Arrays.fill(row, 1 << 30); + } + dist[0][0] = 0; + int[] dirs = {-1, 0, 1, 0, -1}; + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); + pq.offer(new int[] {0, 0, 0}); + while (!pq.isEmpty()) { + var p = pq.poll(); + int t = p[0], i = p[1], j = p[2]; + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n) { + int d = Math.max(t, Math.abs(heights[x][y] - heights[i][j])); + if (d < dist[x][y]) { + dist[x][y] = d; + pq.offer(new int[] {d, x, y}); + } + } + } + } + return dist[m - 1][n - 1]; + } +} +``` + +```cpp +class Solution { +public: + int minimumEffortPath(vector>& heights) { + int m = heights.size(), n = heights[0].size(); + int dist[m][n]; + memset(dist, 0x3f, sizeof(dist)); + dist[0][0] = 0; + int dirs[5] = {0, 1, 0, -1, 0}; + using T = tuple; + priority_queue, greater> pq; + pq.emplace(0, 0, 0); + while (!pq.empty()) { + auto [t, i, j] = pq.top(); + pq.pop(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x < 0 || x >= m || y < 0 || y >= n) { + continue; + } + int d = max(t, abs(heights[x][y] - heights[i][j])); + if (d < dist[x][y]) { + dist[x][y] = d; + pq.emplace(d, x, y); + } + } + } + return dist[m - 1][n - 1]; + } +}; +``` + +```go +func minimumEffortPath(heights [][]int) int { + m, n := len(heights), len(heights[0]) + dist := make([][]int, m) + for i := range dist { + dist[i] = make([]int, n) + for j := range dist[i] { + dist[i][j] = 1 << 30 + } + } + dirs := [5]int{-1, 0, 1, 0, -1} + dist[0][0] = 0 + pq := hp{} + heap.Push(&pq, tuple{0, 0, 0}) + for pq.Len() > 0 { + p := heap.Pop(&pq).(tuple) + t, i, j := p.t, p.i, p.j + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n { + if d := max(t, abs(heights[x][y]-heights[i][j])); d < dist[x][y] { + dist[x][y] = d + heap.Push(&pq, tuple{d, x, y}) + } + } + } + } + return dist[m-1][n-1] +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} + +type tuple struct{ t, i, j int } +type hp []tuple + +func (h hp) Len() int { return len(h) } +func (h hp) Less(i, j int) bool { return h[i].t < h[j].t } +func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } +func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } +``` + ```ts function minimumEffortPath(heights: number[][]): number { const m = heights.length; @@ -778,10 +776,6 @@ function minimumEffortPath(heights: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1632.Rank Transform of a Matrix/README.md b/solution/1600-1699/1632.Rank Transform of a Matrix/README.md index f6ac0b9a4c684..053d7ab717b3f 100644 --- a/solution/1600-1699/1632.Rank Transform of a Matrix/README.md +++ b/solution/1600-1699/1632.Rank Transform of a Matrix/README.md @@ -72,9 +72,7 @@ matrix[1][1] 的秩为 3 ,因为 matrix[1][1] > matrix[0][1], matrix[1][1] > ## 解法 - - -**方法一:排序 + 并查集** +### 方法一:排序 + 并查集 我们先考虑简化情形:没有相同的元素。那么显然最小的元素的秩为 $1$,第二小的元素则要考虑是否和最小元素同行或同列。于是得到贪心解法:从小到大遍历元素,并维护每行、每列的最大秩,该元素的秩即为同行、同列的最大秩加 $1$。见题目:[2371. 最小化网格中的最大值](/solution/2300-2399/2371.Minimize%20Maximum%20Value%20in%20a%20Grid/README.md)。 @@ -86,10 +84,6 @@ matrix[1][1] 的秩为 3 ,因为 matrix[1][1] > matrix[0][1], matrix[1][1] > -### **Python3** - - - ```python class UnionFind: def __init__(self, n): @@ -141,10 +135,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class UnionFind { private int[] p; @@ -223,8 +213,6 @@ class Solution { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -298,8 +286,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p, size []int @@ -385,10 +371,6 @@ func matrixRankTransform(matrix [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1632.Rank Transform of a Matrix/README_EN.md b/solution/1600-1699/1632.Rank Transform of a Matrix/README_EN.md index fbe730b32fc96..1f569c0bda78a 100644 --- a/solution/1600-1699/1632.Rank Transform of a Matrix/README_EN.md +++ b/solution/1600-1699/1632.Rank Transform of a Matrix/README_EN.md @@ -61,9 +61,9 @@ The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][ ## Solutions - +### Solution 1 -### **Python3** + ```python class UnionFind: @@ -116,8 +116,6 @@ class Solution: return ans ``` -### **Java** - ```java class UnionFind { private int[] p; @@ -196,8 +194,6 @@ class Solution { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -271,8 +267,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p, size []int @@ -358,10 +352,6 @@ func matrixRankTransform(matrix [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1633.Percentage of Users Attended a Contest/README.md b/solution/1600-1699/1633.Percentage of Users Attended a Contest/README.md index 711ebb94a675f..ce7aeee2e3567 100644 --- a/solution/1600-1699/1633.Percentage of Users Attended a Contest/README.md +++ b/solution/1600-1699/1633.Percentage of Users Attended a Contest/README.md @@ -89,16 +89,12 @@ Bob 注册了 207 赛事,注册率为 ((1/3) * 100) = 33.33% ## 解法 - - -**方法一:分组统计 + 子查询** +### 方法一:分组统计 + 子查询 我们可以将 `Register` 表按照 `contest_id` 分组,统计每个赛事的注册人数,每个赛事的注册人数除以总注册人数即为该赛事的注册率。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -110,3 +106,5 @@ ORDER BY 2 DESC, 1; ``` + + diff --git a/solution/1600-1699/1633.Percentage of Users Attended a Contest/README_EN.md b/solution/1600-1699/1633.Percentage of Users Attended a Contest/README_EN.md index 2f10fcf3836be..ef78c1bd1e38c 100644 --- a/solution/1600-1699/1633.Percentage of Users Attended a Contest/README_EN.md +++ b/solution/1600-1699/1633.Percentage of Users Attended a Contest/README_EN.md @@ -88,14 +88,12 @@ Bob registered in contest 207 and the percentage is ((1/3) * 100) = 33.33% ## Solutions -**Solution 1: Grouping and Subquery** +### Solution 1: Grouping and Subquery We can group the `Register` table by `contest_id` and count the number of registrations for each contest. The registration rate of each contest is the number of registrations divided by the total number of registrations. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -107,3 +105,5 @@ ORDER BY 2 DESC, 1; ``` + + diff --git a/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README.md b/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README.md index a56fe708a591b..0bd6e92d9036a 100644 --- a/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README.md +++ b/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README.md @@ -70,9 +70,7 @@ ## 解法 - - -**方法一:遍历链表** +### 方法一:遍历链表 我们可以同时遍历两个链表,根据指数大小关系,将节点添加到结果链表中。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python # Definition for polynomial singly-linked list. # class PolyNode: @@ -117,10 +111,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for polynomial singly-linked list. @@ -169,8 +159,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for polynomial singly-linked list-> @@ -218,7 +206,47 @@ public: }; ``` -### **C#** +```js +/** + * Definition for polynomial singly-linked list. + * function PolyNode(x=0, y=0, next=null) { + * this.coefficient = x; + * this.power = y; + * this.next = next; + * } + */ + +/** + * @param {PolyNode} poly1 + * @param {PolyNode} poly2 + * @return {PolyNode} + */ +var addPoly = function (poly1, poly2) { + const dummy = new PolyNode(); + let curr = dummy; + while (poly1 && poly2) { + if (poly1.power > poly2.power) { + curr.next = poly1; + poly1 = poly1.next; + curr = curr.next; + } else if (poly1.power < poly2.power) { + curr.next = poly2; + poly2 = poly2.next; + curr = curr.next; + } else { + const c = poly1.coefficient + poly2.coefficient; + if (c != 0) { + curr.next = new PolyNode(c, poly1.power); + curr = curr.next; + } + poly1 = poly1.next; + poly2 = poly2.next; + } + } + curr.next = poly1 || poly2; + return dummy.next; +}; +``` ```cs /** @@ -269,54 +297,6 @@ public class Solution { } ``` -### **JavaScript** - -```js -/** - * Definition for polynomial singly-linked list. - * function PolyNode(x=0, y=0, next=null) { - * this.coefficient = x; - * this.power = y; - * this.next = next; - * } - */ - -/** - * @param {PolyNode} poly1 - * @param {PolyNode} poly2 - * @return {PolyNode} - */ -var addPoly = function (poly1, poly2) { - const dummy = new PolyNode(); - let curr = dummy; - while (poly1 && poly2) { - if (poly1.power > poly2.power) { - curr.next = poly1; - poly1 = poly1.next; - curr = curr.next; - } else if (poly1.power < poly2.power) { - curr.next = poly2; - poly2 = poly2.next; - curr = curr.next; - } else { - const c = poly1.coefficient + poly2.coefficient; - if (c != 0) { - curr.next = new PolyNode(c, poly1.power); - curr = curr.next; - } - poly1 = poly1.next; - poly2 = poly2.next; - } - } - curr.next = poly1 || poly2; - return dummy.next; -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README_EN.md b/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README_EN.md index 9ef71e7a02ffc..13084432841cd 100644 --- a/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README_EN.md +++ b/solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/README_EN.md @@ -66,9 +66,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for polynomial singly-linked list. @@ -101,8 +101,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for polynomial singly-linked list. @@ -151,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for polynomial singly-linked list-> @@ -200,7 +196,47 @@ public: }; ``` -### **C#** +```js +/** + * Definition for polynomial singly-linked list. + * function PolyNode(x=0, y=0, next=null) { + * this.coefficient = x; + * this.power = y; + * this.next = next; + * } + */ + +/** + * @param {PolyNode} poly1 + * @param {PolyNode} poly2 + * @return {PolyNode} + */ +var addPoly = function (poly1, poly2) { + const dummy = new PolyNode(); + let curr = dummy; + while (poly1 && poly2) { + if (poly1.power > poly2.power) { + curr.next = poly1; + poly1 = poly1.next; + curr = curr.next; + } else if (poly1.power < poly2.power) { + curr.next = poly2; + poly2 = poly2.next; + curr = curr.next; + } else { + const c = poly1.coefficient + poly2.coefficient; + if (c != 0) { + curr.next = new PolyNode(c, poly1.power); + curr = curr.next; + } + poly1 = poly1.next; + poly2 = poly2.next; + } + } + curr.next = poly1 || poly2; + return dummy.next; +}; +``` ```cs /** @@ -251,54 +287,6 @@ public class Solution { } ``` -### **JavaScript** - -```js -/** - * Definition for polynomial singly-linked list. - * function PolyNode(x=0, y=0, next=null) { - * this.coefficient = x; - * this.power = y; - * this.next = next; - * } - */ - -/** - * @param {PolyNode} poly1 - * @param {PolyNode} poly2 - * @return {PolyNode} - */ -var addPoly = function (poly1, poly2) { - const dummy = new PolyNode(); - let curr = dummy; - while (poly1 && poly2) { - if (poly1.power > poly2.power) { - curr.next = poly1; - poly1 = poly1.next; - curr = curr.next; - } else if (poly1.power < poly2.power) { - curr.next = poly2; - poly2 = poly2.next; - curr = curr.next; - } else { - const c = poly1.coefficient + poly2.coefficient; - if (c != 0) { - curr.next = new PolyNode(c, poly1.power); - curr = curr.next; - } - poly1 = poly1.next; - poly2 = poly2.next; - } - } - curr.next = poly1 || poly2; - return dummy.next; -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1635.Hopper Company Queries I/README.md b/solution/1600-1699/1635.Hopper Company Queries I/README.md index 503ba71fbad94..4b321c2465ec7 100644 --- a/solution/1600-1699/1635.Hopper Company Queries I/README.md +++ b/solution/1600-1699/1635.Hopper Company Queries I/README.md @@ -154,12 +154,10 @@ ride_id 是该表的主键(具有唯一值的列)。 ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -194,3 +192,5 @@ GROUP BY month; ``` + + diff --git a/solution/1600-1699/1635.Hopper Company Queries I/README_EN.md b/solution/1600-1699/1635.Hopper Company Queries I/README_EN.md index a0e460093ecaa..34d17980da700 100644 --- a/solution/1600-1699/1635.Hopper Company Queries I/README_EN.md +++ b/solution/1600-1699/1635.Hopper Company Queries I/README_EN.md @@ -152,9 +152,9 @@ By the end of December --> six active drivers (10, 8, 5, 7, 4, 1) and one acc ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -190,3 +190,5 @@ GROUP BY month; ``` + + diff --git a/solution/1600-1699/1636.Sort Array by Increasing Frequency/README.md b/solution/1600-1699/1636.Sort Array by Increasing Frequency/README.md index da218fd1cd623..8141ae5a2c1df 100644 --- a/solution/1600-1699/1636.Sort Array by Increasing Frequency/README.md +++ b/solution/1600-1699/1636.Sort Array by Increasing Frequency/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:数组或哈希表计数** +### 方法一:数组或哈希表计数 用数组或者哈希表统计 `nums` 中每个数字出现的次数,由于题目中数字的范围是 $[-100, 100]$,我们可以直接创建一个大小为 $201$ 的数组来统计。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def frequencySort(self, nums: List[int]) -> List[int]: @@ -65,10 +59,6 @@ class Solution: return sorted(nums, key=lambda x: (cnt[x], -x)) ``` -### **Java** - - - ```java class Solution { public int[] frequencySort(int[] nums) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +97,6 @@ public: }; ``` -### **Go** - ```go func frequencySort(nums []int) []int { cnt := make([]int, 201) @@ -125,8 +111,6 @@ func frequencySort(nums []int) []int { } ``` -### **TypeScript** - ```ts function frequencySort(nums: number[]): number[] { const map = new Map(); @@ -137,8 +121,6 @@ function frequencySort(nums: number[]): number[] { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -159,8 +141,6 @@ impl Solution { } ``` -### **Javascript** - ```js /** * @param {number[]} nums @@ -176,10 +156,6 @@ var frequencySort = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1636.Sort Array by Increasing Frequency/README_EN.md b/solution/1600-1699/1636.Sort Array by Increasing Frequency/README_EN.md index c01b4a1057c2f..7d544c0eafb57 100644 --- a/solution/1600-1699/1636.Sort Array by Increasing Frequency/README_EN.md +++ b/solution/1600-1699/1636.Sort Array by Increasing Frequency/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return sorted(nums, key=lambda x: (cnt[x], -x)) ``` -### **Java** - ```java class Solution { public int[] frequencySort(int[] nums) { @@ -75,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +90,6 @@ public: }; ``` -### **Go** - ```go func frequencySort(nums []int) []int { cnt := make([]int, 201) @@ -110,8 +104,6 @@ func frequencySort(nums []int) []int { } ``` -### **TypeScript** - ```ts function frequencySort(nums: number[]): number[] { const map = new Map(); @@ -122,8 +114,6 @@ function frequencySort(nums: number[]): number[] { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -144,8 +134,6 @@ impl Solution { } ``` -### **Javascript** - ```js /** * @param {number[]} nums @@ -161,10 +149,6 @@ var frequencySort = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README.md b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README.md index 99eda8a916949..87dec18fa3136 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README.md +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README.md @@ -42,15 +42,89 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们可以对数组 $points$ 按照 $x$ 升序排列,获取相邻点之间 $x$ 的差值的最大值。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 $points$ 的长度。 -**方法二:桶排序** + + +```python +class Solution: + def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: + points.sort() + return max(b[0] - a[0] for a, b in pairwise(points)) +``` + +```java +class Solution { + public int maxWidthOfVerticalArea(int[][] points) { + Arrays.sort(points, (a, b) -> a[0] - b[0]); + int ans = 0; + for (int i = 0; i < points.length - 1; ++i) { + ans = Math.max(ans, points[i + 1][0] - points[i][0]); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maxWidthOfVerticalArea(vector>& points) { + sort(points.begin(), points.end()); + int ans = 0; + for (int i = 0; i < points.size() - 1; ++i) { + ans = max(ans, points[i + 1][0] - points[i][0]); + } + return ans; + } +}; +``` + +```go +func maxWidthOfVerticalArea(points [][]int) (ans int) { + sort.Slice(points, func(i, j int) bool { return points[i][0] < points[j][0] }) + for i, p := range points[1:] { + ans = max(ans, p[0]-points[i][0]) + } + return +} +``` + +```ts +function maxWidthOfVerticalArea(points: number[][]): number { + points.sort((a, b) => a[0] - b[0]); + let ans = 0; + for (let i = 1; i < points.length; ++i) { + ans = Math.max(ans, points[i][0] - points[i - 1][0]); + } + return ans; +} +``` + +```js +/** + * @param {number[][]} points + * @return {number} + */ +var maxWidthOfVerticalArea = function (points) { + points.sort((a, b) => a[0] - b[0]); + let ans = 0; + let px = points[0][0]; + for (const [x, _] of points) { + ans = Math.max(ans, x - px); + px = x; + } + return ans; +}; +``` + + + +### 方法二:桶排序 方法一中排序的时间复杂度为 $O(n \times \log n)$,其实我们可以利用桶排序的思想,将时间复杂度降低到 $O(n)$。 @@ -74,17 +148,6 @@ $$ -### **Python3** - - - -```python -class Solution: - def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: - points.sort() - return max(b[0] - a[0] for a, b in pairwise(points)) -``` - ```python class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: @@ -108,23 +171,6 @@ class Solution: return ans ``` -### **Java** - - - -```java -class Solution { - public int maxWidthOfVerticalArea(int[][] points) { - Arrays.sort(points, (a, b) -> a[0] - b[0]); - int ans = 0; - for (int i = 0; i < points.length - 1; ++i) { - ans = Math.max(ans, points[i + 1][0] - points[i][0]); - } - return ans; - } -} -``` - ```java class Solution { public int maxWidthOfVerticalArea(int[][] points) { @@ -165,22 +211,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maxWidthOfVerticalArea(vector>& points) { - sort(points.begin(), points.end()); - int ans = 0; - for (int i = 0; i < points.size() - 1; ++i) { - ans = max(ans, points[i + 1][0] - points[i][0]); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -216,18 +246,6 @@ public: }; ``` -### **Go** - -```go -func maxWidthOfVerticalArea(points [][]int) (ans int) { - sort.Slice(points, func(i, j int) bool { return points[i][0] < points[j][0] }) - for i, p := range points[1:] { - ans = max(ans, p[0]-points[i][0]) - } - return -} -``` - ```go func maxWidthOfVerticalArea(points [][]int) (ans int) { n := len(points) @@ -264,19 +282,6 @@ func maxWidthOfVerticalArea(points [][]int) (ans int) { } ``` -### **TypeScript** - -```ts -function maxWidthOfVerticalArea(points: number[][]): number { - points.sort((a, b) => a[0] - b[0]); - let ans = 0; - for (let i = 1; i < points.length; ++i) { - ans = Math.max(ans, points[i][0] - points[i - 1][0]); - } - return ans; -} -``` - ```ts function maxWidthOfVerticalArea(points: number[][]): number { const nums: number[] = points.map(point => point[0]); @@ -309,25 +314,6 @@ function maxWidthOfVerticalArea(points: number[][]): number { } ``` -### **JavaScript** - -```js -/** - * @param {number[][]} points - * @return {number} - */ -var maxWidthOfVerticalArea = function (points) { - points.sort((a, b) => a[0] - b[0]); - let ans = 0; - let px = points[0][0]; - for (const [x, _] of points) { - ans = Math.max(ans, x - px); - px = x; - } - return ans; -}; -``` - ```js /** * @param {number[][]} points @@ -364,10 +350,6 @@ var maxWidthOfVerticalArea = function (points) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README_EN.md b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README_EN.md index 7890b22eccc8a..bb5d1a76b0181 100644 --- a/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README_EN.md +++ b/solution/1600-1699/1637.Widest Vertical Area Between Two Points Containing No Points/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -49,6 +49,77 @@ class Solution: return max(b[0] - a[0] for a, b in pairwise(points)) ``` +```java +class Solution { + public int maxWidthOfVerticalArea(int[][] points) { + Arrays.sort(points, (a, b) -> a[0] - b[0]); + int ans = 0; + for (int i = 0; i < points.length - 1; ++i) { + ans = Math.max(ans, points[i + 1][0] - points[i][0]); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maxWidthOfVerticalArea(vector>& points) { + sort(points.begin(), points.end()); + int ans = 0; + for (int i = 0; i < points.size() - 1; ++i) { + ans = max(ans, points[i + 1][0] - points[i][0]); + } + return ans; + } +}; +``` + +```go +func maxWidthOfVerticalArea(points [][]int) (ans int) { + sort.Slice(points, func(i, j int) bool { return points[i][0] < points[j][0] }) + for i, p := range points[1:] { + ans = max(ans, p[0]-points[i][0]) + } + return +} +``` + +```ts +function maxWidthOfVerticalArea(points: number[][]): number { + points.sort((a, b) => a[0] - b[0]); + let ans = 0; + for (let i = 1; i < points.length; ++i) { + ans = Math.max(ans, points[i][0] - points[i - 1][0]); + } + return ans; +} +``` + +```js +/** + * @param {number[][]} points + * @return {number} + */ +var maxWidthOfVerticalArea = function (points) { + points.sort((a, b) => a[0] - b[0]); + let ans = 0; + let px = points[0][0]; + for (const [x, _] of points) { + ans = Math.max(ans, x - px); + px = x; + } + return ans; +}; +``` + + + +### Solution 2 + + + ```python class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: @@ -72,21 +143,6 @@ class Solution: return ans ``` -### **Java** - -```java -class Solution { - public int maxWidthOfVerticalArea(int[][] points) { - Arrays.sort(points, (a, b) -> a[0] - b[0]); - int ans = 0; - for (int i = 0; i < points.length - 1; ++i) { - ans = Math.max(ans, points[i + 1][0] - points[i][0]); - } - return ans; - } -} -``` - ```java class Solution { public int maxWidthOfVerticalArea(int[][] points) { @@ -127,22 +183,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maxWidthOfVerticalArea(vector>& points) { - sort(points.begin(), points.end()); - int ans = 0; - for (int i = 0; i < points.size() - 1; ++i) { - ans = max(ans, points[i + 1][0] - points[i][0]); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -178,18 +218,6 @@ public: }; ``` -### **Go** - -```go -func maxWidthOfVerticalArea(points [][]int) (ans int) { - sort.Slice(points, func(i, j int) bool { return points[i][0] < points[j][0] }) - for i, p := range points[1:] { - ans = max(ans, p[0]-points[i][0]) - } - return -} -``` - ```go func maxWidthOfVerticalArea(points [][]int) (ans int) { n := len(points) @@ -226,19 +254,6 @@ func maxWidthOfVerticalArea(points [][]int) (ans int) { } ``` -### **TypeScript** - -```ts -function maxWidthOfVerticalArea(points: number[][]): number { - points.sort((a, b) => a[0] - b[0]); - let ans = 0; - for (let i = 1; i < points.length; ++i) { - ans = Math.max(ans, points[i][0] - points[i - 1][0]); - } - return ans; -} -``` - ```ts function maxWidthOfVerticalArea(points: number[][]): number { const nums: number[] = points.map(point => point[0]); @@ -271,25 +286,6 @@ function maxWidthOfVerticalArea(points: number[][]): number { } ``` -### **JavaScript** - -```js -/** - * @param {number[][]} points - * @return {number} - */ -var maxWidthOfVerticalArea = function (points) { - points.sort((a, b) => a[0] - b[0]); - let ans = 0; - let px = points[0][0]; - for (const [x, _] of points) { - ans = Math.max(ans, x - px); - px = x; - } - return ans; -}; -``` - ```js /** * @param {number[][]} points @@ -326,10 +322,6 @@ var maxWidthOfVerticalArea = function (points) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1638.Count Substrings That Differ by One Character/README.md b/solution/1600-1699/1638.Count Substrings That Differ by One Character/README.md index 34566b0dec1c9..a96509ec3013d 100644 --- a/solution/1600-1699/1638.Count Substrings That Differ by One Character/README.md +++ b/solution/1600-1699/1638.Count Substrings That Differ by One Character/README.md @@ -68,9 +68,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举字符串 $s$ 和 $t$ 中不同的那个字符位置,然后分别向两边扩展,直到遇到不同的字符为止,这样就可以得到以该位置为中心的满足条件的子串对数目。我们记左边扩展的相同字符个数为 $l$,右边扩展的相同字符个数为 $r$,那么以该位置为中心的满足条件的子串对数目为 $(l + 1) \times (r + 1)$,累加到答案中即可。 @@ -78,20 +76,8 @@ 时间复杂度 $O(m \times n \times \min(m, n))$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别为字符串 $s$ 和 $t$ 的长度。 -**方法二:预处理 + 枚举** - -方法一中,我们每次需要分别往左右两边扩展,得出 $l$ 和 $r$ 的值。实际上,我们可以预处理出以每个位置 $(i, j)$ 结尾的最长相同后缀的长度,以及以每个位置 $(i, j)$ 开头的最长相同前缀的长度,分别记录在数组 $f$ 和 $g$ 中。 - -接下来,与方法一类似,我们枚举字符串 $s$ 和 $t$ 中不同的那个字符位置 $(i, j)$,那么以该位置为中心的满足条件的子串对数目为 $(f[i][j] + 1) \times (g[i + 1][j + 1] + 1)$,累加到答案中即可。 - -时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别为字符串 $s$ 和 $t$ 的长度。 - -### **Python3** - - - ```python class Solution: def countSubstrings(self, s: str, t: str) -> int: @@ -111,30 +97,6 @@ class Solution: return ans ``` -```python -class Solution: - def countSubstrings(self, s: str, t: str) -> int: - ans = 0 - m, n = len(s), len(t) - f = [[0] * (n + 1) for _ in range(m + 1)] - g = [[0] * (n + 1) for _ in range(m + 1)] - for i, a in enumerate(s, 1): - for j, b in enumerate(t, 1): - if a == b: - f[i][j] = f[i - 1][j - 1] + 1 - for i in range(m - 1, -1, -1): - for j in range(n - 1, -1, -1): - if s[i] == t[j]: - g[i][j] = g[i + 1][j + 1] + 1 - else: - ans += (f[i][j] + 1) * (g[i + 1][j + 1] + 1) - return ans -``` - -### **Java** - - - ```java class Solution { public int countSubstrings(String s, String t) { @@ -160,6 +122,84 @@ class Solution { } ``` +```cpp +class Solution { +public: + int countSubstrings(string s, string t) { + int ans = 0; + int m = s.size(), n = t.size(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (s[i] != t[j]) { + int l = 0, r = 0; + while (i - l > 0 && j - l > 0 && s[i - l - 1] == t[j - l - 1]) { + ++l; + } + while (i + r + 1 < m && j + r + 1 < n && s[i + r + 1] == t[j + r + 1]) { + ++r; + } + ans += (l + 1) * (r + 1); + } + } + } + return ans; + } +}; +``` + +```go +func countSubstrings(s string, t string) (ans int) { + m, n := len(s), len(t) + for i, a := range s { + for j, b := range t { + if a != b { + l, r := 0, 0 + for i > l && j > l && s[i-l-1] == t[j-l-1] { + l++ + } + for i+r+1 < m && j+r+1 < n && s[i+r+1] == t[j+r+1] { + r++ + } + ans += (l + 1) * (r + 1) + } + } + } + return +} +``` + + + +### 方法二:预处理 + 枚举 + +方法一中,我们每次需要分别往左右两边扩展,得出 $l$ 和 $r$ 的值。实际上,我们可以预处理出以每个位置 $(i, j)$ 结尾的最长相同后缀的长度,以及以每个位置 $(i, j)$ 开头的最长相同前缀的长度,分别记录在数组 $f$ 和 $g$ 中。 + +接下来,与方法一类似,我们枚举字符串 $s$ 和 $t$ 中不同的那个字符位置 $(i, j)$,那么以该位置为中心的满足条件的子串对数目为 $(f[i][j] + 1) \times (g[i + 1][j + 1] + 1)$,累加到答案中即可。 + +时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别为字符串 $s$ 和 $t$ 的长度。 + + + +```python +class Solution: + def countSubstrings(self, s: str, t: str) -> int: + ans = 0 + m, n = len(s), len(t) + f = [[0] * (n + 1) for _ in range(m + 1)] + g = [[0] * (n + 1) for _ in range(m + 1)] + for i, a in enumerate(s, 1): + for j, b in enumerate(t, 1): + if a == b: + f[i][j] = f[i - 1][j - 1] + 1 + for i in range(m - 1, -1, -1): + for j in range(n - 1, -1, -1): + if s[i] == t[j]: + g[i][j] = g[i + 1][j + 1] + 1 + else: + ans += (f[i][j] + 1) * (g[i + 1][j + 1] + 1) + return ans +``` + ```java class Solution { public int countSubstrings(String s, String t) { @@ -188,33 +228,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int countSubstrings(string s, string t) { - int ans = 0; - int m = s.size(), n = t.size(); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (s[i] != t[j]) { - int l = 0, r = 0; - while (i - l > 0 && j - l > 0 && s[i - l - 1] == t[j - l - 1]) { - ++l; - } - while (i + r + 1 < m && j + r + 1 < n && s[i + r + 1] == t[j + r + 1]) { - ++r; - } - ans += (l + 1) * (r + 1); - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -246,29 +259,6 @@ public: }; ``` -### **Go** - -```go -func countSubstrings(s string, t string) (ans int) { - m, n := len(s), len(t) - for i, a := range s { - for j, b := range t { - if a != b { - l, r := 0, 0 - for i > l && j > l && s[i-l-1] == t[j-l-1] { - l++ - } - for i+r+1 < m && j+r+1 < n && s[i+r+1] == t[j+r+1] { - r++ - } - ans += (l + 1) * (r + 1) - } - } - } - return -} -``` - ```go func countSubstrings(s string, t string) (ans int) { m, n := len(s), len(t) @@ -298,10 +288,6 @@ func countSubstrings(s string, t string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1638.Count Substrings That Differ by One Character/README_EN.md b/solution/1600-1699/1638.Count Substrings That Differ by One Character/README_EN.md index e93c7ca230ed2..786f725962e92 100644 --- a/solution/1600-1699/1638.Count Substrings That Differ by One Character/README_EN.md +++ b/solution/1600-1699/1638.Count Substrings That Differ by One Character/README_EN.md @@ -50,9 +50,9 @@ The underlined portions are the substrings that are chosen from s and t. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,28 +73,6 @@ class Solution: return ans ``` -```python -class Solution: - def countSubstrings(self, s: str, t: str) -> int: - ans = 0 - m, n = len(s), len(t) - f = [[0] * (n + 1) for _ in range(m + 1)] - g = [[0] * (n + 1) for _ in range(m + 1)] - for i, a in enumerate(s, 1): - for j, b in enumerate(t, 1): - if a == b: - f[i][j] = f[i - 1][j - 1] + 1 - for i in range(m - 1, -1, -1): - for j in range(n - 1, -1, -1): - if s[i] == t[j]: - g[i][j] = g[i + 1][j + 1] + 1 - else: - ans += (f[i][j] + 1) * (g[i + 1][j + 1] + 1) - return ans -``` - -### **Java** - ```java class Solution { public int countSubstrings(String s, String t) { @@ -120,6 +98,78 @@ class Solution { } ``` +```cpp +class Solution { +public: + int countSubstrings(string s, string t) { + int ans = 0; + int m = s.size(), n = t.size(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (s[i] != t[j]) { + int l = 0, r = 0; + while (i - l > 0 && j - l > 0 && s[i - l - 1] == t[j - l - 1]) { + ++l; + } + while (i + r + 1 < m && j + r + 1 < n && s[i + r + 1] == t[j + r + 1]) { + ++r; + } + ans += (l + 1) * (r + 1); + } + } + } + return ans; + } +}; +``` + +```go +func countSubstrings(s string, t string) (ans int) { + m, n := len(s), len(t) + for i, a := range s { + for j, b := range t { + if a != b { + l, r := 0, 0 + for i > l && j > l && s[i-l-1] == t[j-l-1] { + l++ + } + for i+r+1 < m && j+r+1 < n && s[i+r+1] == t[j+r+1] { + r++ + } + ans += (l + 1) * (r + 1) + } + } + } + return +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def countSubstrings(self, s: str, t: str) -> int: + ans = 0 + m, n = len(s), len(t) + f = [[0] * (n + 1) for _ in range(m + 1)] + g = [[0] * (n + 1) for _ in range(m + 1)] + for i, a in enumerate(s, 1): + for j, b in enumerate(t, 1): + if a == b: + f[i][j] = f[i - 1][j - 1] + 1 + for i in range(m - 1, -1, -1): + for j in range(n - 1, -1, -1): + if s[i] == t[j]: + g[i][j] = g[i + 1][j + 1] + 1 + else: + ans += (f[i][j] + 1) * (g[i + 1][j + 1] + 1) + return ans +``` + ```java class Solution { public int countSubstrings(String s, String t) { @@ -148,33 +198,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int countSubstrings(string s, string t) { - int ans = 0; - int m = s.size(), n = t.size(); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - if (s[i] != t[j]) { - int l = 0, r = 0; - while (i - l > 0 && j - l > 0 && s[i - l - 1] == t[j - l - 1]) { - ++l; - } - while (i + r + 1 < m && j + r + 1 < n && s[i + r + 1] == t[j + r + 1]) { - ++r; - } - ans += (l + 1) * (r + 1); - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -206,29 +229,6 @@ public: }; ``` -### **Go** - -```go -func countSubstrings(s string, t string) (ans int) { - m, n := len(s), len(t) - for i, a := range s { - for j, b := range t { - if a != b { - l, r := 0, 0 - for i > l && j > l && s[i-l-1] == t[j-l-1] { - l++ - } - for i+r+1 < m && j+r+1 < n && s[i+r+1] == t[j+r+1] { - r++ - } - ans += (l + 1) * (r + 1) - } - } - } - return -} -``` - ```go func countSubstrings(s string, t string) (ans int) { m, n := len(s), len(t) @@ -258,10 +258,6 @@ func countSubstrings(s string, t string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/README.md b/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/README.md index ad07c6f933a7f..4f367f0ac03f4 100644 --- a/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/README.md +++ b/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/README.md @@ -79,9 +79,7 @@ ## 解法 - - -**方法一:预处理 + 记忆化搜索** +### 方法一:预处理 + 记忆化搜索 我们注意到,字符串数组 $words$ 中的每一个字符串长度都相同,不妨记为 $n$,那么我们可以预处理出一个二维数组 $cnt$,其中 $cnt[j][c]$ 表示字符串数组 $words$ 中第 $j$ 个位置的字符 $c$ 的数量。 @@ -97,24 +95,8 @@ 时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 为字符串 $target$ 的长度,而 $n$ 为字符串数组 $words$ 中每个字符串的长度。 -**方法二:预处理 + 动态规划** - -与方法一类似,我们可以先预处理出一个二维数组 $cnt$,其中 $cnt[j][c]$ 表示字符串数组 $words$ 中第 $j$ 个位置的字符 $c$ 的数量。 - -接下来,我们定义 $f[i][j]$ 表示构造 $target$ 的前 $i$ 个字符,且当前是从 $words$ 中每个单词的前 $j$ 个字符中选取字符的方案数。那么答案就是 $f[m][n]$。初始时 $f[0][j] = 1$,其中 $0 \leq j \leq n$。 - -考虑 $f[i][j]$,其中 $i \gt 0$, $j \gt 0$。我们可以不选取 $words$ 中的第 $j$ 个位置的字符,那么方案数为 $f[i][j - 1]$;或者我们选择 $words$ 中的第 $j$ 个位置的字符,那么方案数为 $f[i - 1][j - 1] \times cnt[j - 1][target[i - 1] - 'a']$。最后,我们将这两种情况的方案数相加,即为 $f[i][j]$ 的值。 - -最后,我们返回 $f[m][n]$ 即可。注意答案的取模操作。 - -时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 为字符串 $target$ 的长度,而 $n$ 为字符串数组 $words$ 中每个字符串的长度。 - -### **Python3** - - - ```python class Solution: def numWays(self, words: List[str], target: str) -> int: @@ -137,31 +119,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def numWays(self, words: List[str], target: str) -> int: - m, n = len(target), len(words[0]) - cnt = [[0] * 26 for _ in range(n)] - for w in words: - for j, c in enumerate(w): - cnt[j][ord(c) - ord('a')] += 1 - mod = 10**9 + 7 - f = [[0] * (n + 1) for _ in range(m + 1)] - f[0] = [1] * (n + 1) - for i in range(1, m + 1): - for j in range(1, n + 1): - f[i][j] = ( - f[i][j - 1] - + f[i - 1][j - 1] * cnt[j - 1][ord(target[i - 1]) - ord('a')] - ) - f[i][j] %= mod - return f[m][n] -``` - -### **Java** - - - ```java class Solution { private int m; @@ -203,33 +160,6 @@ class Solution { } ``` -```java -class Solution { - public int numWays(String[] words, String target) { - int m = target.length(); - int n = words[0].length(); - final int mod = (int) 1e9 + 7; - long[][] f = new long[m + 1][n + 1]; - Arrays.fill(f[0], 1); - int[][] cnt = new int[n][26]; - for (var w : words) { - for (int j = 0; j < n; ++j) { - cnt[j][w.charAt(j) - 'a']++; - } - } - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - f[i][j] = f[i][j - 1] + f[i - 1][j - 1] * cnt[j - 1][target.charAt(i - 1) - 'a']; - f[i][j] %= mod; - } - } - return (int) f[m][n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -263,34 +193,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numWays(vector& words, string target) { - int m = target.size(), n = words[0].size(); - const int mod = 1e9 + 7; - long long f[m + 1][n + 1]; - memset(f, 0, sizeof(f)); - fill(f[0], f[0] + n + 1, 1); - vector> cnt(n, vector(26)); - for (auto& w : words) { - for (int j = 0; j < n; ++j) { - ++cnt[j][w[j] - 'a']; - } - } - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - f[i][j] = f[i][j - 1] + f[i - 1][j - 1] * cnt[j - 1][target[i - 1] - 'a']; - f[i][j] %= mod; - } - } - return f[m][n]; - } -}; -``` - -### **Go** - ```go func numWays(words []string, target string) int { m, n := len(target), len(words[0]) @@ -328,35 +230,6 @@ func numWays(words []string, target string) int { } ``` -```go -func numWays(words []string, target string) int { - const mod = 1e9 + 7 - m, n := len(target), len(words[0]) - f := make([][]int, m+1) - for i := range f { - f[i] = make([]int, n+1) - } - for j := range f[0] { - f[0][j] = 1 - } - cnt := make([][26]int, n) - for _, w := range words { - for j, c := range w { - cnt[j][c-'a']++ - } - } - for i := 1; i <= m; i++ { - for j := 1; j <= n; j++ { - f[i][j] = f[i][j-1] + f[i-1][j-1]*cnt[j-1][target[i-1]-'a'] - f[i][j] %= mod - } - } - return f[m][n] -} -``` - -### **TypeScript** - ```ts function numWays(words: string[], target: string): number { const m = target.length; @@ -382,10 +255,121 @@ function numWays(words: string[], target: string): number { } ``` -### **...** + + +### 方法二:预处理 + 动态规划 + +与方法一类似,我们可以先预处理出一个二维数组 $cnt$,其中 $cnt[j][c]$ 表示字符串数组 $words$ 中第 $j$ 个位置的字符 $c$ 的数量。 + +接下来,我们定义 $f[i][j]$ 表示构造 $target$ 的前 $i$ 个字符,且当前是从 $words$ 中每个单词的前 $j$ 个字符中选取字符的方案数。那么答案就是 $f[m][n]$。初始时 $f[0][j] = 1$,其中 $0 \leq j \leq n$。 + +考虑 $f[i][j]$,其中 $i \gt 0$, $j \gt 0$。我们可以不选取 $words$ 中的第 $j$ 个位置的字符,那么方案数为 $f[i][j - 1]$;或者我们选择 $words$ 中的第 $j$ 个位置的字符,那么方案数为 $f[i - 1][j - 1] \times cnt[j - 1][target[i - 1] - 'a']$。最后,我们将这两种情况的方案数相加,即为 $f[i][j]$ 的值。 + +最后,我们返回 $f[m][n]$ 即可。注意答案的取模操作。 + +时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 为字符串 $target$ 的长度,而 $n$ 为字符串数组 $words$ 中每个字符串的长度。 + + + +```python +class Solution: + def numWays(self, words: List[str], target: str) -> int: + m, n = len(target), len(words[0]) + cnt = [[0] * 26 for _ in range(n)] + for w in words: + for j, c in enumerate(w): + cnt[j][ord(c) - ord('a')] += 1 + mod = 10**9 + 7 + f = [[0] * (n + 1) for _ in range(m + 1)] + f[0] = [1] * (n + 1) + for i in range(1, m + 1): + for j in range(1, n + 1): + f[i][j] = ( + f[i][j - 1] + + f[i - 1][j - 1] * cnt[j - 1][ord(target[i - 1]) - ord('a')] + ) + f[i][j] %= mod + return f[m][n] +``` + +```java +class Solution { + public int numWays(String[] words, String target) { + int m = target.length(); + int n = words[0].length(); + final int mod = (int) 1e9 + 7; + long[][] f = new long[m + 1][n + 1]; + Arrays.fill(f[0], 1); + int[][] cnt = new int[n][26]; + for (var w : words) { + for (int j = 0; j < n; ++j) { + cnt[j][w.charAt(j) - 'a']++; + } + } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + f[i][j] = f[i][j - 1] + f[i - 1][j - 1] * cnt[j - 1][target.charAt(i - 1) - 'a']; + f[i][j] %= mod; + } + } + return (int) f[m][n]; + } +} +``` +```cpp +class Solution { +public: + int numWays(vector& words, string target) { + int m = target.size(), n = words[0].size(); + const int mod = 1e9 + 7; + long long f[m + 1][n + 1]; + memset(f, 0, sizeof(f)); + fill(f[0], f[0] + n + 1, 1); + vector> cnt(n, vector(26)); + for (auto& w : words) { + for (int j = 0; j < n; ++j) { + ++cnt[j][w[j] - 'a']; + } + } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + f[i][j] = f[i][j - 1] + f[i - 1][j - 1] * cnt[j - 1][target[i - 1] - 'a']; + f[i][j] %= mod; + } + } + return f[m][n]; + } +}; ``` +```go +func numWays(words []string, target string) int { + const mod = 1e9 + 7 + m, n := len(target), len(words[0]) + f := make([][]int, m+1) + for i := range f { + f[i] = make([]int, n+1) + } + for j := range f[0] { + f[0][j] = 1 + } + cnt := make([][26]int, n) + for _, w := range words { + for j, c := range w { + cnt[j][c-'a']++ + } + } + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + f[i][j] = f[i][j-1] + f[i-1][j-1]*cnt[j-1][target[i-1]-'a'] + f[i][j] %= mod + } + } + return f[m][n] +} ``` + + diff --git a/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/README_EN.md b/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/README_EN.md index 4201cdd917094..68957f04e369d 100644 --- a/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/README_EN.md +++ b/solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/README_EN.md @@ -59,7 +59,7 @@ ## Solutions -**Solution 1: Preprocessing + Memory Search** +### Solution 1: Preprocessing + Memory Search We noticed that the length of each string in the string array $words$ is the same, so let's remember $n$, then we can preprocess a two-dimensional array $cnt$, where $cnt[j][c]$ represents the string array $words$ The number of characters $c$ in the $j$-th position of. @@ -75,22 +75,8 @@ Finally, we return $dfs(0, 0)$. Note that the answer is taken in modulo operatio The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Where $m$ is the length of the string $target$, and $n$ is the length of each string in the string array $words$. -**Solution 2: Preprocessing + Dynamic Programming** - -Similar to Solution 1, we can first preprocess a two-dimensional array $cnt$, where $cnt[j][c]$ represents the number of characters $c$ in the $j$-th position of the string array $words$. - -Next, we define $f[i][j]$ which represents the number of ways to construct the first $i$ characters of $target$, and currently select characters from the first $j$ characters of each word in $words$. Then the answer is $f[m][n]$. Initially $f[0][j] = 1$, where $0 \leq j \leq n$. - -Consider $f[i][j]$, where $i \gt 0$, $j \gt 0$. We can choose not to select the character in the $j$-th position of $words$, in which case the number of ways is $f[i][j - 1]$; or we choose the character in the $j$-th position of $words$, in which case the number of ways is $f[i - 1][j - 1] \times cnt[j - 1][target[i - 1] - 'a']$. Finally, we add the number of ways in these two cases, which is the value of $f[i][j]$. - -Finally, we return $f[m][n]$. Note the mod operation of the answer. - -The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Where $m$ is the length of the string $target$, and $n$ is the length of each string in the string array $words$. - -### **Python3** - ```python class Solution: def numWays(self, words: List[str], target: str) -> int: @@ -113,29 +99,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def numWays(self, words: List[str], target: str) -> int: - m, n = len(target), len(words[0]) - cnt = [[0] * 26 for _ in range(n)] - for w in words: - for j, c in enumerate(w): - cnt[j][ord(c) - ord('a')] += 1 - mod = 10**9 + 7 - f = [[0] * (n + 1) for _ in range(m + 1)] - f[0] = [1] * (n + 1) - for i in range(1, m + 1): - for j in range(1, n + 1): - f[i][j] = ( - f[i][j - 1] - + f[i - 1][j - 1] * cnt[j - 1][ord(target[i - 1]) - ord('a')] - ) - f[i][j] %= mod - return f[m][n] -``` - -### **Java** - ```java class Solution { private int m; @@ -177,33 +140,6 @@ class Solution { } ``` -```java -class Solution { - public int numWays(String[] words, String target) { - int m = target.length(); - int n = words[0].length(); - final int mod = (int) 1e9 + 7; - long[][] f = new long[m + 1][n + 1]; - Arrays.fill(f[0], 1); - int[][] cnt = new int[n][26]; - for (var w : words) { - for (int j = 0; j < n; ++j) { - cnt[j][w.charAt(j) - 'a']++; - } - } - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - f[i][j] = f[i][j - 1] + f[i - 1][j - 1] * cnt[j - 1][target.charAt(i - 1) - 'a']; - f[i][j] %= mod; - } - } - return (int) f[m][n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -237,34 +173,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numWays(vector& words, string target) { - int m = target.size(), n = words[0].size(); - const int mod = 1e9 + 7; - long long f[m + 1][n + 1]; - memset(f, 0, sizeof(f)); - fill(f[0], f[0] + n + 1, 1); - vector> cnt(n, vector(26)); - for (auto& w : words) { - for (int j = 0; j < n; ++j) { - ++cnt[j][w[j] - 'a']; - } - } - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - f[i][j] = f[i][j - 1] + f[i - 1][j - 1] * cnt[j - 1][target[i - 1] - 'a']; - f[i][j] %= mod; - } - } - return f[m][n]; - } -}; -``` - -### **Go** - ```go func numWays(words []string, target string) int { m, n := len(target), len(words[0]) @@ -302,35 +210,6 @@ func numWays(words []string, target string) int { } ``` -```go -func numWays(words []string, target string) int { - const mod = 1e9 + 7 - m, n := len(target), len(words[0]) - f := make([][]int, m+1) - for i := range f { - f[i] = make([]int, n+1) - } - for j := range f[0] { - f[0][j] = 1 - } - cnt := make([][26]int, n) - for _, w := range words { - for j, c := range w { - cnt[j][c-'a']++ - } - } - for i := 1; i <= m; i++ { - for j := 1; j <= n; j++ { - f[i][j] = f[i][j-1] + f[i-1][j-1]*cnt[j-1][target[i-1]-'a'] - f[i][j] %= mod - } - } - return f[m][n] -} -``` - -### **TypeScript** - ```ts function numWays(words: string[], target: string): number { const m = target.length; @@ -356,10 +235,121 @@ function numWays(words: string[], target: string): number { } ``` -### **...** + + +### Solution 2: Preprocessing + Dynamic Programming + +Similar to Solution 1, we can first preprocess a two-dimensional array $cnt$, where $cnt[j][c]$ represents the number of characters $c$ in the $j$-th position of the string array $words$. + +Next, we define $f[i][j]$ which represents the number of ways to construct the first $i$ characters of $target$, and currently select characters from the first $j$ characters of each word in $words$. Then the answer is $f[m][n]$. Initially $f[0][j] = 1$, where $0 \leq j \leq n$. + +Consider $f[i][j]$, where $i \gt 0$, $j \gt 0$. We can choose not to select the character in the $j$-th position of $words$, in which case the number of ways is $f[i][j - 1]$; or we choose the character in the $j$-th position of $words$, in which case the number of ways is $f[i - 1][j - 1] \times cnt[j - 1][target[i - 1] - 'a']$. Finally, we add the number of ways in these two cases, which is the value of $f[i][j]$. + +Finally, we return $f[m][n]$. Note the mod operation of the answer. + +The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Where $m$ is the length of the string $target$, and $n$ is the length of each string in the string array $words$. + + + +```python +class Solution: + def numWays(self, words: List[str], target: str) -> int: + m, n = len(target), len(words[0]) + cnt = [[0] * 26 for _ in range(n)] + for w in words: + for j, c in enumerate(w): + cnt[j][ord(c) - ord('a')] += 1 + mod = 10**9 + 7 + f = [[0] * (n + 1) for _ in range(m + 1)] + f[0] = [1] * (n + 1) + for i in range(1, m + 1): + for j in range(1, n + 1): + f[i][j] = ( + f[i][j - 1] + + f[i - 1][j - 1] * cnt[j - 1][ord(target[i - 1]) - ord('a')] + ) + f[i][j] %= mod + return f[m][n] +``` + +```java +class Solution { + public int numWays(String[] words, String target) { + int m = target.length(); + int n = words[0].length(); + final int mod = (int) 1e9 + 7; + long[][] f = new long[m + 1][n + 1]; + Arrays.fill(f[0], 1); + int[][] cnt = new int[n][26]; + for (var w : words) { + for (int j = 0; j < n; ++j) { + cnt[j][w.charAt(j) - 'a']++; + } + } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + f[i][j] = f[i][j - 1] + f[i - 1][j - 1] * cnt[j - 1][target.charAt(i - 1) - 'a']; + f[i][j] %= mod; + } + } + return (int) f[m][n]; + } +} +``` +```cpp +class Solution { +public: + int numWays(vector& words, string target) { + int m = target.size(), n = words[0].size(); + const int mod = 1e9 + 7; + long long f[m + 1][n + 1]; + memset(f, 0, sizeof(f)); + fill(f[0], f[0] + n + 1, 1); + vector> cnt(n, vector(26)); + for (auto& w : words) { + for (int j = 0; j < n; ++j) { + ++cnt[j][w[j] - 'a']; + } + } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + f[i][j] = f[i][j - 1] + f[i - 1][j - 1] * cnt[j - 1][target[i - 1] - 'a']; + f[i][j] %= mod; + } + } + return f[m][n]; + } +}; ``` +```go +func numWays(words []string, target string) int { + const mod = 1e9 + 7 + m, n := len(target), len(words[0]) + f := make([][]int, m+1) + for i := range f { + f[i] = make([]int, n+1) + } + for j := range f[0] { + f[0][j] = 1 + } + cnt := make([][26]int, n) + for _, w := range words { + for j, c := range w { + cnt[j][c-'a']++ + } + } + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + f[i][j] = f[i][j-1] + f[i-1][j-1]*cnt[j-1][target[i-1]-'a'] + f[i][j] %= mod + } + } + return f[m][n] +} ``` + + diff --git a/solution/1600-1699/1640.Check Array Formation Through Concatenation/README.md b/solution/1600-1699/1640.Check Array Formation Through Concatenation/README.md index 0c85113073527..9a512521e9ab9 100644 --- a/solution/1600-1699/1640.Check Array Formation Through Concatenation/README.md +++ b/solution/1600-1699/1640.Check Array Formation Through Concatenation/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 遍历 `arr`,在 `pieces` 中找到首元素等于当前 `arr[i]` 的数组项,如果找不到,直接返回 `false`。 @@ -60,22 +58,8 @@ 遍历结束,返回 `true`。 -**方法二:哈希表** - -创建一个哈希表,键为 `pieces` 中每个数组项的首元素,值为数组项。 - -遍历 `arr`,如果当前元素在哈希表中不存在,直接返回 `false`;否则,取出哈希表中对应的数组项,判断其与 `arr` 中的元素是否相等,如果不相等,直接返回 `false`。 - -否则,遍历结束,返回 `true`。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 `arr` 的长度。 - -### **Python3** - - - ```python class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: @@ -92,25 +76,6 @@ class Solution: return True ``` -```python -class Solution: - def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: - d = {p[0]: p for p in pieces} - i, n = 0, len(arr) - while i < n: - if arr[i] not in d: - return False - p = d[arr[i]] - if arr[i : i + len(p)] != p: - return False - i += len(p) - return True -``` - -### **Java** - - - ```java class Solution { public boolean canFormArray(int[] arr, int[][] pieces) { @@ -133,32 +98,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canFormArray(int[] arr, int[][] pieces) { - Map d = new HashMap<>(); - for (var p : pieces) { - d.put(p[0], p); - } - for (int i = 0; i < arr.length;) { - if (!d.containsKey(arr[i])) { - return false; - } - for (int v : d.get(arr[i])) { - if (arr[i++] != v) { - return false; - } - } - } - return true; - } -} -``` - -### **C++** - -### **C++** - ```cpp class Solution { public: @@ -182,31 +121,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool canFormArray(vector& arr, vector>& pieces) { - unordered_map> d; - for (auto& p : pieces) { - d[p[0]] = p; - } - for (int i = 0; i < arr.size();) { - if (!d.count(arr[i])) { - return false; - } - for (int& v : d[arr[i]]) { - if (arr[i++] != v) { - return false; - } - } - } - return true; - } -}; -``` - -### **Go** - ```go func canFormArray(arr []int, pieces [][]int) bool { for i := 0; i < len(arr); { @@ -226,58 +140,6 @@ func canFormArray(arr []int, pieces [][]int) bool { } ``` -```go -func canFormArray(arr []int, pieces [][]int) bool { - d := map[int][]int{} - for _, p := range pieces { - d[p[0]] = p - } - for i := 0; i < len(arr); { - p, ok := d[arr[i]] - if !ok { - return false - } - for _, v := range p { - if arr[i] != v { - return false - } - i++ - } - } - return true -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} arr - * @param {number[][]} pieces - * @return {boolean} - */ -var canFormArray = function (arr, pieces) { - const d = new Map(); - for (const p of pieces) { - d.set(p[0], p); - } - for (let i = 0; i < arr.length; ) { - if (!d.has(arr[i])) { - return false; - } - const p = d.get(arr[i]); - for (const v of p) { - if (arr[i++] != v) { - return false; - } - } - } - return true; -}; -``` - -### **TypeScript** - ```ts function canFormArray(arr: number[], pieces: number[][]): boolean { const n = arr.length; @@ -299,8 +161,6 @@ function canFormArray(arr: number[], pieces: number[][]): boolean { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -331,10 +191,128 @@ impl Solution { } ``` -### **...** +```js +/** + * @param {number[]} arr + * @param {number[][]} pieces + * @return {boolean} + */ +var canFormArray = function (arr, pieces) { + const d = new Map(); + for (const p of pieces) { + d.set(p[0], p); + } + for (let i = 0; i < arr.length; ) { + if (!d.has(arr[i])) { + return false; + } + const p = d.get(arr[i]); + for (const v of p) { + if (arr[i++] != v) { + return false; + } + } + } + return true; +}; +``` + + + +### 方法二:哈希表 + +创建一个哈希表,键为 `pieces` 中每个数组项的首元素,值为数组项。 + +遍历 `arr`,如果当前元素在哈希表中不存在,直接返回 `false`;否则,取出哈希表中对应的数组项,判断其与 `arr` 中的元素是否相等,如果不相等,直接返回 `false`。 + +否则,遍历结束,返回 `true`。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 `arr` 的长度。 + + + +```python +class Solution: + def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: + d = {p[0]: p for p in pieces} + i, n = 0, len(arr) + while i < n: + if arr[i] not in d: + return False + p = d[arr[i]] + if arr[i : i + len(p)] != p: + return False + i += len(p) + return True +``` + +```java +class Solution { + public boolean canFormArray(int[] arr, int[][] pieces) { + Map d = new HashMap<>(); + for (var p : pieces) { + d.put(p[0], p); + } + for (int i = 0; i < arr.length;) { + if (!d.containsKey(arr[i])) { + return false; + } + for (int v : d.get(arr[i])) { + if (arr[i++] != v) { + return false; + } + } + } + return true; + } +} +``` +```cpp +class Solution { +public: + bool canFormArray(vector& arr, vector>& pieces) { + unordered_map> d; + for (auto& p : pieces) { + d[p[0]] = p; + } + for (int i = 0; i < arr.size();) { + if (!d.count(arr[i])) { + return false; + } + for (int& v : d[arr[i]]) { + if (arr[i++] != v) { + return false; + } + } + } + return true; + } +}; ``` +```go +func canFormArray(arr []int, pieces [][]int) bool { + d := map[int][]int{} + for _, p := range pieces { + d[p[0]] = p + } + for i := 0; i < len(arr); { + p, ok := d[arr[i]] + if !ok { + return false + } + for _, v := range p { + if arr[i] != v { + return false + } + i++ + } + } + return true +} ``` + + diff --git a/solution/1600-1699/1640.Check Array Formation Through Concatenation/README_EN.md b/solution/1600-1699/1640.Check Array Formation Through Concatenation/README_EN.md index 1a66c81368f33..f1c2b508b8be8 100644 --- a/solution/1600-1699/1640.Check Array Formation Through Concatenation/README_EN.md +++ b/solution/1600-1699/1640.Check Array Formation Through Concatenation/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,23 +67,6 @@ class Solution: return True ``` -```python -class Solution: - def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: - d = {p[0]: p for p in pieces} - i, n = 0, len(arr) - while i < n: - if arr[i] not in d: - return False - p = d[arr[i]] - if arr[i : i + len(p)] != p: - return False - i += len(p) - return True -``` - -### **Java** - ```java class Solution { public boolean canFormArray(int[] arr, int[][] pieces) { @@ -106,30 +89,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canFormArray(int[] arr, int[][] pieces) { - Map d = new HashMap<>(); - for (var p : pieces) { - d.put(p[0], p); - } - for (int i = 0; i < arr.length;) { - if (!d.containsKey(arr[i])) { - return false; - } - for (int v : d.get(arr[i])) { - if (arr[i++] != v) { - return false; - } - } - } - return true; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -153,31 +112,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool canFormArray(vector& arr, vector>& pieces) { - unordered_map> d; - for (auto& p : pieces) { - d[p[0]] = p; - } - for (int i = 0; i < arr.size();) { - if (!d.count(arr[i])) { - return false; - } - for (int& v : d[arr[i]]) { - if (arr[i++] != v) { - return false; - } - } - } - return true; - } -}; -``` - -### **Go** - ```go func canFormArray(arr []int, pieces [][]int) bool { for i := 0; i < len(arr); { @@ -197,58 +131,6 @@ func canFormArray(arr []int, pieces [][]int) bool { } ``` -```go -func canFormArray(arr []int, pieces [][]int) bool { - d := map[int][]int{} - for _, p := range pieces { - d[p[0]] = p - } - for i := 0; i < len(arr); { - p, ok := d[arr[i]] - if !ok { - return false - } - for _, v := range p { - if arr[i] != v { - return false - } - i++ - } - } - return true -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} arr - * @param {number[][]} pieces - * @return {boolean} - */ -var canFormArray = function (arr, pieces) { - const d = new Map(); - for (const p of pieces) { - d.set(p[0], p); - } - for (let i = 0; i < arr.length; ) { - if (!d.has(arr[i])) { - return false; - } - const p = d.get(arr[i]); - for (const v of p) { - if (arr[i++] != v) { - return false; - } - } - } - return true; -}; -``` - -### **TypeScript** - ```ts function canFormArray(arr: number[], pieces: number[][]): boolean { const n = arr.length; @@ -270,8 +152,6 @@ function canFormArray(arr: number[], pieces: number[][]): boolean { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -302,10 +182,120 @@ impl Solution { } ``` -### **...** +```js +/** + * @param {number[]} arr + * @param {number[][]} pieces + * @return {boolean} + */ +var canFormArray = function (arr, pieces) { + const d = new Map(); + for (const p of pieces) { + d.set(p[0], p); + } + for (let i = 0; i < arr.length; ) { + if (!d.has(arr[i])) { + return false; + } + const p = d.get(arr[i]); + for (const v of p) { + if (arr[i++] != v) { + return false; + } + } + } + return true; +}; +``` + + + +### Solution 2 + + + +```python +class Solution: + def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: + d = {p[0]: p for p in pieces} + i, n = 0, len(arr) + while i < n: + if arr[i] not in d: + return False + p = d[arr[i]] + if arr[i : i + len(p)] != p: + return False + i += len(p) + return True +``` + +```java +class Solution { + public boolean canFormArray(int[] arr, int[][] pieces) { + Map d = new HashMap<>(); + for (var p : pieces) { + d.put(p[0], p); + } + for (int i = 0; i < arr.length;) { + if (!d.containsKey(arr[i])) { + return false; + } + for (int v : d.get(arr[i])) { + if (arr[i++] != v) { + return false; + } + } + } + return true; + } +} +``` +```cpp +class Solution { +public: + bool canFormArray(vector& arr, vector>& pieces) { + unordered_map> d; + for (auto& p : pieces) { + d[p[0]] = p; + } + for (int i = 0; i < arr.size();) { + if (!d.count(arr[i])) { + return false; + } + for (int& v : d[arr[i]]) { + if (arr[i++] != v) { + return false; + } + } + } + return true; + } +}; ``` +```go +func canFormArray(arr []int, pieces [][]int) bool { + d := map[int][]int{} + for _, p := range pieces { + d[p[0]] = p + } + for i := 0; i < len(arr); { + p, ok := d[arr[i]] + if !ok { + return false + } + for _, v := range p { + if arr[i] != v { + return false + } + i++ + } + } + return true +} ``` + + diff --git a/solution/1600-1699/1641.Count Sorted Vowel Strings/README.md b/solution/1600-1699/1641.Count Sorted Vowel Strings/README.md index e6fe83dc37be8..ccd253e7d75cb 100644 --- a/solution/1600-1699/1641.Count Sorted Vowel Strings/README.md +++ b/solution/1600-1699/1641.Count Sorted Vowel Strings/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j)$,表示当前已经选了 $i$ 个元音字母,且最后一个元音字母是 $j$ 的方案数。那么答案就是 $dfs(0, 0)$。 @@ -62,20 +60,8 @@ 时间复杂度 $O(n \times C^2)$,空间复杂度 $O(n \times C)$。其中 $n$ 为题目给定的整数,而 $C$ 是元音字母的数量,本题中 $C = 5$。 -**方法二:动态规划 + 前缀和** - -定义 $f[i][j]$ 表示当前已经选了 $i$ 个元音字母,且最后一个元音字母是 $j$ 的方案数。初始时 $f[1][j]=1$。答案是 $\sum_{j = 0}^4 f[n][j]$。 - -我们可以发现 $f[i][j]$ 只与 $f[i - 1][j]$ 有关,因此可以将二维数组压缩为一维数组,从而优化空间复杂度。 - -时间复杂度 $O(n \times C)$,空间复杂度 $O(C)$。其中 $n$ 为题目给定的整数,而 $C$ 是元音字母的数量,本题中 $C = 5$。 - -### **Python3** - - - ```python class Solution: def countVowelStrings(self, n: int) -> int: @@ -86,22 +72,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def countVowelStrings(self, n: int) -> int: - f = [1] * 5 - for _ in range(n - 1): - s = 0 - for j in range(5): - s += f[j] - f[j] = s - return sum(f) -``` - -### **Java** - - - ```java class Solution { private Integer[][] f; @@ -129,24 +99,6 @@ class Solution { } ``` -```java -class Solution { - public int countVowelStrings(int n) { - int[] f = {1, 1, 1, 1, 1}; - for (int i = 0; i < n - 1; ++i) { - int s = 0; - for (int j = 0; j < 5; ++j) { - s += f[j]; - f[j] = s; - } - } - return Arrays.stream(f).sum(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -171,25 +123,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countVowelStrings(int n) { - int f[5] = {1, 1, 1, 1, 1}; - for (int i = 0; i < n - 1; ++i) { - int s = 0; - for (int j = 0; j < 5; ++j) { - s += f[j]; - f[j] = s; - } - } - return accumulate(f, f + 5, 0); - } -}; -``` - -### **Go** - ```go func countVowelStrings(n int) int { f := make([][5]int, n) @@ -212,6 +145,63 @@ func countVowelStrings(n int) int { } ``` + + +### 方法二:动态规划 + 前缀和 + +定义 $f[i][j]$ 表示当前已经选了 $i$ 个元音字母,且最后一个元音字母是 $j$ 的方案数。初始时 $f[1][j]=1$。答案是 $\sum_{j = 0}^4 f[n][j]$。 + +我们可以发现 $f[i][j]$ 只与 $f[i - 1][j]$ 有关,因此可以将二维数组压缩为一维数组,从而优化空间复杂度。 + +时间复杂度 $O(n \times C)$,空间复杂度 $O(C)$。其中 $n$ 为题目给定的整数,而 $C$ 是元音字母的数量,本题中 $C = 5$。 + + + +```python +class Solution: + def countVowelStrings(self, n: int) -> int: + f = [1] * 5 + for _ in range(n - 1): + s = 0 + for j in range(5): + s += f[j] + f[j] = s + return sum(f) +``` + +```java +class Solution { + public int countVowelStrings(int n) { + int[] f = {1, 1, 1, 1, 1}; + for (int i = 0; i < n - 1; ++i) { + int s = 0; + for (int j = 0; j < 5; ++j) { + s += f[j]; + f[j] = s; + } + } + return Arrays.stream(f).sum(); + } +} +``` + +```cpp +class Solution { +public: + int countVowelStrings(int n) { + int f[5] = {1, 1, 1, 1, 1}; + for (int i = 0; i < n - 1; ++i) { + int s = 0; + for (int j = 0; j < 5; ++j) { + s += f[j]; + f[j] = s; + } + } + return accumulate(f, f + 5, 0); + } +}; +``` + ```go func countVowelStrings(n int) (ans int) { f := [5]int{1, 1, 1, 1, 1} @@ -229,10 +219,6 @@ func countVowelStrings(n int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1641.Count Sorted Vowel Strings/README_EN.md b/solution/1600-1699/1641.Count Sorted Vowel Strings/README_EN.md index de37903df4f25..ec9a628569ad8 100644 --- a/solution/1600-1699/1641.Count Sorted Vowel Strings/README_EN.md +++ b/solution/1600-1699/1641.Count Sorted Vowel Strings/README_EN.md @@ -43,9 +43,9 @@ Note that "ea" is not a valid string since 'e' comes after  ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,20 +57,6 @@ class Solution: return dfs(0, 0) ``` -```python -class Solution: - def countVowelStrings(self, n: int) -> int: - f = [1] * 5 - for _ in range(n - 1): - s = 0 - for j in range(5): - s += f[j] - f[j] = s - return sum(f) -``` - -### **Java** - ```java class Solution { private Integer[][] f; @@ -98,24 +84,6 @@ class Solution { } ``` -```java -class Solution { - public int countVowelStrings(int n) { - int[] f = {1, 1, 1, 1, 1}; - for (int i = 0; i < n - 1; ++i) { - int s = 0; - for (int j = 0; j < 5; ++j) { - s += f[j]; - f[j] = s; - } - } - return Arrays.stream(f).sum(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -140,25 +108,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countVowelStrings(int n) { - int f[5] = {1, 1, 1, 1, 1}; - for (int i = 0; i < n - 1; ++i) { - int s = 0; - for (int j = 0; j < 5; ++j) { - s += f[j]; - f[j] = s; - } - } - return accumulate(f, f + 5, 0); - } -}; -``` - -### **Go** - ```go func countVowelStrings(n int) int { f := make([][5]int, n) @@ -181,6 +130,57 @@ func countVowelStrings(n int) int { } ``` + + +### Solution 2 + + + +```python +class Solution: + def countVowelStrings(self, n: int) -> int: + f = [1] * 5 + for _ in range(n - 1): + s = 0 + for j in range(5): + s += f[j] + f[j] = s + return sum(f) +``` + +```java +class Solution { + public int countVowelStrings(int n) { + int[] f = {1, 1, 1, 1, 1}; + for (int i = 0; i < n - 1; ++i) { + int s = 0; + for (int j = 0; j < 5; ++j) { + s += f[j]; + f[j] = s; + } + } + return Arrays.stream(f).sum(); + } +} +``` + +```cpp +class Solution { +public: + int countVowelStrings(int n) { + int f[5] = {1, 1, 1, 1, 1}; + for (int i = 0; i < n - 1; ++i) { + int s = 0; + for (int j = 0; j < 5; ++j) { + s += f[j]; + f[j] = s; + } + } + return accumulate(f, f + 5, 0); + } +}; +``` + ```go func countVowelStrings(n int) (ans int) { f := [5]int{1, 1, 1, 1, 1} @@ -198,10 +198,6 @@ func countVowelStrings(n int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1642.Furthest Building You Can Reach/README.md b/solution/1600-1699/1642.Furthest Building You Can Reach/README.md index ca03251ec2349..b517dd8e72a1d 100644 --- a/solution/1600-1699/1642.Furthest Building You Can Reach/README.md +++ b/solution/1600-1699/1642.Furthest Building You Can Reach/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列(小根堆)** +### 方法一:贪心 + 优先队列(小根堆) 梯子最好用在高度差较大的地方,因此我们可以将所有的高度差存入优先队列中,每次取出最小的高度差,如果梯子不够用,则用砖块填补,如果砖块不够用,则返回当前位置。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int: @@ -90,10 +84,6 @@ class Solution: return len(heights) - 1 ``` -### **Java** - - - ```java class Solution { public int furthestBuilding(int[] heights, int bricks, int ladders) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func furthestBuilding(heights []int, bricks int, ladders int) int { q := hp{} @@ -177,10 +163,6 @@ func (h *hp) Pop() any { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1642.Furthest Building You Can Reach/README_EN.md b/solution/1600-1699/1642.Furthest Building You Can Reach/README_EN.md index d07f61bbf6d78..26b05dfab76c9 100644 --- a/solution/1600-1699/1642.Furthest Building You Can Reach/README_EN.md +++ b/solution/1600-1699/1642.Furthest Building You Can Reach/README_EN.md @@ -57,9 +57,9 @@ It is impossible to go beyond building 4 because you do not have any more bricks ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return len(heights) - 1 ``` -### **Java** - ```java class Solution { public int furthestBuilding(int[] heights, int bricks, int ladders) { @@ -102,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +125,6 @@ public: }; ``` -### **Go** - ```go func furthestBuilding(heights []int, bricks int, ladders int) int { q := hp{} @@ -162,10 +156,6 @@ func (h *hp) Pop() any { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1643.Kth Smallest Instructions/README.md b/solution/1600-1699/1643.Kth Smallest Instructions/README.md index e7f8a737df724..15a59ae44080b 100644 --- a/solution/1600-1699/1643.Kth Smallest Instructions/README.md +++ b/solution/1600-1699/1643.Kth Smallest Instructions/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:组合计数** +### 方法一:组合计数 根据题目描述我们可以知道,最终的路径是由 $destination[0]$ 个 `'V'` 和 $destination[1]$ 个 `'H'` 组成的,且按字典序排列后的第 $k$ 条最小指令。 @@ -85,10 +83,6 @@ -### **Python3** - - - ```python class Solution: def kthSmallestPath(self, destination: List[int], k: int) -> str: @@ -109,10 +103,6 @@ class Solution: return "".join(ans) ``` -### **Java** - - - ```java class Solution { public String kthSmallestPath(int[] destination, int k) { @@ -147,8 +137,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -185,8 +173,6 @@ public: }; ``` -### **Go** - ```go func kthSmallestPath(destination []int, k int) string { v, h := destination[0], destination[1] @@ -221,10 +207,6 @@ func kthSmallestPath(destination []int, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1643.Kth Smallest Instructions/README_EN.md b/solution/1600-1699/1643.Kth Smallest Instructions/README_EN.md index 9dabb2a2861d8..d5b484752cbaf 100644 --- a/solution/1600-1699/1643.Kth Smallest Instructions/README_EN.md +++ b/solution/1600-1699/1643.Kth Smallest Instructions/README_EN.md @@ -60,9 +60,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: return "".join(ans) ``` -### **Java** - ```java class Solution { public String kthSmallestPath(int[] destination, int k) { @@ -120,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +154,6 @@ public: }; ``` -### **Go** - ```go func kthSmallestPath(destination []int, k int) string { v, h := destination[0], destination[1] @@ -194,10 +188,6 @@ func kthSmallestPath(destination []int, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/README.md b/solution/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/README.md index 0ee486703eadb..8d19e06f5f6e2 100644 --- a/solution/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/README.md +++ b/solution/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:递归(后序遍历)** +### 方法一:递归(后序遍历) 我们设计一个函数 $dfs(root, p, q)$,该函数返回以 $root$ 为根节点的二叉树中是否包含节点 $p$ 或节点 $q$,如果包含,则返回 `true`,否则返回 `false`。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -111,10 +105,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -150,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -189,10 +177,41 @@ private: }; ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} p + * @param {TreeNode} q + * @return {TreeNode} + */ +var lowestCommonAncestor = function (root, p, q) { + const dfs = root => { + if (!root) { + return false; + } + const l = dfs(root.left); + const r = dfs(root.right); + if (l && r) { + ans = root; + } + if ((l || r) && (root.val === p.val || root.val === q.val)) { + ans = root; + } + return l || r || root.val === p.val || root.val === q.val; + }; + let ans = null; + dfs(root); + return ans; +}; ``` + + diff --git a/solution/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/README_EN.md b/solution/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/README_EN.md index 9e28eb7c3c727..be9f8dd53c77a 100644 --- a/solution/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/README_EN.md +++ b/solution/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/README_EN.md @@ -50,9 +50,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. @@ -121,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -160,10 +156,41 @@ private: }; ``` -### **...** - -``` - +```js +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {TreeNode} p + * @param {TreeNode} q + * @return {TreeNode} + */ +var lowestCommonAncestor = function (root, p, q) { + const dfs = root => { + if (!root) { + return false; + } + const l = dfs(root.left); + const r = dfs(root.right); + if (l && r) { + ans = root; + } + if ((l || r) && (root.val === p.val || root.val === q.val)) { + ans = root; + } + return l || r || root.val === p.val || root.val === q.val; + }; + let ans = null; + dfs(root); + return ans; +}; ``` + + diff --git a/solution/1600-1699/1645.Hopper Company Queries II/README.md b/solution/1600-1699/1645.Hopper Company Queries II/README.md index 7a40e4d58925c..5cc6b7172f5e1 100644 --- a/solution/1600-1699/1645.Hopper Company Queries II/README.md +++ b/solution/1600-1699/1645.Hopper Company Queries II/README.md @@ -155,9 +155,7 @@ ride_id 是该表具有唯一值的列。 ## 解法 - - -**方法一:递归 + 左连接 + 分组** +### 方法一:递归 + 左连接 + 分组 我们可以使用递归的方法生成 $1 \sim 12$ 月的数据,记录在 `Month` 表中。 @@ -169,10 +167,6 @@ ride_id 是该表具有唯一值的列。 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH RECURSIVE @@ -214,3 +208,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1600-1699/1645.Hopper Company Queries II/README_EN.md b/solution/1600-1699/1645.Hopper Company Queries II/README_EN.md index bf968645804ee..9cc331ca6ff3a 100644 --- a/solution/1600-1699/1645.Hopper Company Queries II/README_EN.md +++ b/solution/1600-1699/1645.Hopper Company Queries II/README_EN.md @@ -149,9 +149,9 @@ By the end of December --> six active drivers (10, 8, 5, 7, 4, 1) and one acc ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -194,3 +194,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1600-1699/1646.Get Maximum in Generated Array/README.md b/solution/1600-1699/1646.Get Maximum in Generated Array/README.md index be01a31771632..e19f25581fbfe 100644 --- a/solution/1600-1699/1646.Get Maximum in Generated Array/README.md +++ b/solution/1600-1699/1646.Get Maximum in Generated Array/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们先判断 $n$ 的值,如果 $n < 2$,则直接返回 $n$。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def getMaximumGenerated(self, n: int) -> int: @@ -94,10 +88,6 @@ class Solution: return max(nums) ``` -### **Java** - - - ```java class Solution { public int getMaximumGenerated(int n) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func getMaximumGenerated(n int) int { if n < 2 { @@ -154,8 +140,6 @@ func getMaximumGenerated(n int) int { } ``` -### **TypeScript** - ```ts function getMaximumGenerated(n: number): number { if (n === 0) { @@ -170,10 +154,6 @@ function getMaximumGenerated(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1646.Get Maximum in Generated Array/README_EN.md b/solution/1600-1699/1646.Get Maximum in Generated Array/README_EN.md index 3ffcac5b6cf29..006b98b207462 100644 --- a/solution/1600-1699/1646.Get Maximum in Generated Array/README_EN.md +++ b/solution/1600-1699/1646.Get Maximum in Generated Array/README_EN.md @@ -58,9 +58,9 @@ Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return max(nums) ``` -### **Java** - ```java class Solution { public int getMaximumGenerated(int n) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func getMaximumGenerated(n int) int { if n < 2 { @@ -132,8 +126,6 @@ func getMaximumGenerated(n int) int { } ``` -### **TypeScript** - ```ts function getMaximumGenerated(n: number): number { if (n === 0) { @@ -148,10 +140,6 @@ function getMaximumGenerated(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/README.md b/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/README.md index 4557251c0cf51..6f1702a242693 100644 --- a/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/README.md +++ b/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:数组 + 排序** +### 方法一:数组 + 排序 我们先用一个长度为 $26$ 的数组 `cnt` 统计字符串 $s$ 中每个字母出现的次数。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def minDeletions(self, s: str) -> int: @@ -86,23 +80,6 @@ class Solution: return ans ``` -```python -class Solution: - def minDeletions(self, s: str) -> int: - cnt = Counter(s) - vals = sorted(cnt.values(), reverse=True) - ans = 0 - for i in range(1, len(vals)): - while vals[i] >= vals[i - 1] and vals[i] > 0: - vals[i] -= 1 - ans += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int minDeletions(String s) { @@ -123,33 +100,6 @@ class Solution { } ``` -```java -class Solution { - public int minDeletions(String s) { - int[] cnt = new int[26]; - for (int i = 0; i < s.length(); ++i) { - ++cnt[s.charAt(i) - 'a']; - } - Arrays.sort(cnt); - int ans = 0, pre = 1 << 30; - for (int i = 25; i >= 0; --i) { - int v = cnt[i]; - if (pre == 0) { - ans += v; - } else if (v >= pre) { - ans += v - pre + 1; - --pre; - } else { - pre = v; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -169,31 +119,42 @@ public: }; ``` -```cpp -class Solution { -public: - int minDeletions(string s) { - vector cnt(26); - for (char& c : s) ++cnt[c - 'a']; - sort(cnt.rbegin(), cnt.rend()); - int ans = 0, pre = 1 << 30; - for (int& v : cnt) { - if (pre == 0) { - ans += v; - } else if (v >= pre) { - ans += v - pre + 1; - --pre; - } else { - pre = v; - } +```go +func minDeletions(s string) (ans int) { + cnt := make([]int, 26) + for _, c := range s { + cnt[c-'a']++ + } + sort.Sort(sort.Reverse(sort.IntSlice(cnt))) + for i := 1; i < 26; i++ { + for cnt[i] >= cnt[i-1] && cnt[i] > 0 { + cnt[i]-- + ans++ + } + } + return +} +``` + +```ts +function minDeletions(s: string): number { + let map = {}; + for (let c of s) { + map[c] = (map[c] || 0) + 1; + } + let ans = 0; + let vals: number[] = Object.values(map); + vals.sort((a, b) => a - b); + for (let i = 1; i < vals.length; ++i) { + while (vals[i] > 0 && i != vals.indexOf(vals[i])) { + --vals[i]; + ++ans; } - return ans; } -}; + return ans; +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -219,25 +180,73 @@ impl Solution { } ``` -### **Go** + -```go -func minDeletions(s string) (ans int) { - cnt := make([]int, 26) - for _, c := range s { - cnt[c-'a']++ - } - sort.Sort(sort.Reverse(sort.IntSlice(cnt))) - for i := 1; i < 26; i++ { - for cnt[i] >= cnt[i-1] && cnt[i] > 0 { - cnt[i]-- - ans++ - } - } - return +### 方法二 + + + +```python +class Solution: + def minDeletions(self, s: str) -> int: + cnt = Counter(s) + vals = sorted(cnt.values(), reverse=True) + ans = 0 + for i in range(1, len(vals)): + while vals[i] >= vals[i - 1] and vals[i] > 0: + vals[i] -= 1 + ans += 1 + return ans +``` + +```java +class Solution { + public int minDeletions(String s) { + int[] cnt = new int[26]; + for (int i = 0; i < s.length(); ++i) { + ++cnt[s.charAt(i) - 'a']; + } + Arrays.sort(cnt); + int ans = 0, pre = 1 << 30; + for (int i = 25; i >= 0; --i) { + int v = cnt[i]; + if (pre == 0) { + ans += v; + } else if (v >= pre) { + ans += v - pre + 1; + --pre; + } else { + pre = v; + } + } + return ans; + } } ``` +```cpp +class Solution { +public: + int minDeletions(string s) { + vector cnt(26); + for (char& c : s) ++cnt[c - 'a']; + sort(cnt.rbegin(), cnt.rend()); + int ans = 0, pre = 1 << 30; + for (int& v : cnt) { + if (pre == 0) { + ans += v; + } else if (v >= pre) { + ans += v - pre + 1; + --pre; + } else { + pre = v; + } + } + return ans; + } +}; +``` + ```go func minDeletions(s string) (ans int) { cnt := make([]int, 26) @@ -260,31 +269,6 @@ func minDeletions(s string) (ans int) { } ``` -### **TypeScript** - -```ts -function minDeletions(s: string): number { - let map = {}; - for (let c of s) { - map[c] = (map[c] || 0) + 1; - } - let ans = 0; - let vals: number[] = Object.values(map); - vals.sort((a, b) => a - b); - for (let i = 1; i < vals.length; ++i) { - while (vals[i] > 0 && i != vals.indexOf(vals[i])) { - --vals[i]; - ++ans; - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/README_EN.md b/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/README_EN.md index ea5d77bd99288..cfbbe67348998 100644 --- a/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/README_EN.md +++ b/solution/1600-1699/1647.Minimum Deletions to Make Character Frequencies Unique/README_EN.md @@ -46,9 +46,9 @@ Note that we only care about characters that are still in the string at the end ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,21 +66,6 @@ class Solution: return ans ``` -```python -class Solution: - def minDeletions(self, s: str) -> int: - cnt = Counter(s) - vals = sorted(cnt.values(), reverse=True) - ans = 0 - for i in range(1, len(vals)): - while vals[i] >= vals[i - 1] and vals[i] > 0: - vals[i] -= 1 - ans += 1 - return ans -``` - -### **Java** - ```java class Solution { public int minDeletions(String s) { @@ -101,33 +86,6 @@ class Solution { } ``` -```java -class Solution { - public int minDeletions(String s) { - int[] cnt = new int[26]; - for (int i = 0; i < s.length(); ++i) { - ++cnt[s.charAt(i) - 'a']; - } - Arrays.sort(cnt); - int ans = 0, pre = 1 << 30; - for (int i = 25; i >= 0; --i) { - int v = cnt[i]; - if (pre == 0) { - ans += v; - } else if (v >= pre) { - ans += v - pre + 1; - --pre; - } else { - pre = v; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -147,31 +105,42 @@ public: }; ``` -```cpp -class Solution { -public: - int minDeletions(string s) { - vector cnt(26); - for (char& c : s) ++cnt[c - 'a']; - sort(cnt.rbegin(), cnt.rend()); - int ans = 0, pre = 1 << 30; - for (int& v : cnt) { - if (pre == 0) { - ans += v; - } else if (v >= pre) { - ans += v - pre + 1; - --pre; - } else { - pre = v; - } +```go +func minDeletions(s string) (ans int) { + cnt := make([]int, 26) + for _, c := range s { + cnt[c-'a']++ + } + sort.Sort(sort.Reverse(sort.IntSlice(cnt))) + for i := 1; i < 26; i++ { + for cnt[i] >= cnt[i-1] && cnt[i] > 0 { + cnt[i]-- + ans++ + } + } + return +} +``` + +```ts +function minDeletions(s: string): number { + let map = {}; + for (let c of s) { + map[c] = (map[c] || 0) + 1; + } + let ans = 0; + let vals: number[] = Object.values(map); + vals.sort((a, b) => a - b); + for (let i = 1; i < vals.length; ++i) { + while (vals[i] > 0 && i != vals.indexOf(vals[i])) { + --vals[i]; + ++ans; } - return ans; } -}; + return ans; +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -197,25 +166,73 @@ impl Solution { } ``` -### **Go** + -```go -func minDeletions(s string) (ans int) { - cnt := make([]int, 26) - for _, c := range s { - cnt[c-'a']++ - } - sort.Sort(sort.Reverse(sort.IntSlice(cnt))) - for i := 1; i < 26; i++ { - for cnt[i] >= cnt[i-1] && cnt[i] > 0 { - cnt[i]-- - ans++ - } - } - return +### Solution 2 + + + +```python +class Solution: + def minDeletions(self, s: str) -> int: + cnt = Counter(s) + vals = sorted(cnt.values(), reverse=True) + ans = 0 + for i in range(1, len(vals)): + while vals[i] >= vals[i - 1] and vals[i] > 0: + vals[i] -= 1 + ans += 1 + return ans +``` + +```java +class Solution { + public int minDeletions(String s) { + int[] cnt = new int[26]; + for (int i = 0; i < s.length(); ++i) { + ++cnt[s.charAt(i) - 'a']; + } + Arrays.sort(cnt); + int ans = 0, pre = 1 << 30; + for (int i = 25; i >= 0; --i) { + int v = cnt[i]; + if (pre == 0) { + ans += v; + } else if (v >= pre) { + ans += v - pre + 1; + --pre; + } else { + pre = v; + } + } + return ans; + } } ``` +```cpp +class Solution { +public: + int minDeletions(string s) { + vector cnt(26); + for (char& c : s) ++cnt[c - 'a']; + sort(cnt.rbegin(), cnt.rend()); + int ans = 0, pre = 1 << 30; + for (int& v : cnt) { + if (pre == 0) { + ans += v; + } else if (v >= pre) { + ans += v - pre + 1; + --pre; + } else { + pre = v; + } + } + return ans; + } +}; +``` + ```go func minDeletions(s string) (ans int) { cnt := make([]int, 26) @@ -238,31 +255,6 @@ func minDeletions(s string) (ans int) { } ``` -### **TypeScript** - -```ts -function minDeletions(s: string): number { - let map = {}; - for (let c of s) { - map[c] = (map[c] || 0) + 1; - } - let ans = 0; - let vals: number[] = Object.values(map); - vals.sort((a, b) => a - b); - for (let i = 1; i < vals.length; ++i) { - while (vals[i] > 0 && i != vals.indexOf(vals[i])) { - --vals[i]; - ++ans; - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1648.Sell Diminishing-Valued Colored Balls/README.md b/solution/1600-1699/1648.Sell Diminishing-Valued Colored Balls/README.md index c5de7a8988610..0082448c6d132 100644 --- a/solution/1600-1699/1648.Sell Diminishing-Valued Colored Balls/README.md +++ b/solution/1600-1699/1648.Sell Diminishing-Valued Colored Balls/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:贪心 + 优化模拟** +### 方法一:贪心 + 优化模拟 要使得总价值最大,我们可以贪心地每次卖出数量最多的一种颜色的球。由于 `orders` 值域较大,如果直接简单地模拟,会超时。因此,我们需要优化模拟的过程。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def maxProfit(self, inventory: List[int], orders: int) -> int: @@ -107,10 +101,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -151,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -186,8 +174,6 @@ public: }; ``` -### **Go** - ```go func maxProfit(inventory []int, orders int) int { var mod int = 1e9 + 7 @@ -224,10 +210,6 @@ func maxProfit(inventory []int, orders int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1648.Sell Diminishing-Valued Colored Balls/README_EN.md b/solution/1600-1699/1648.Sell Diminishing-Valued Colored Balls/README_EN.md index 081bd1225d769..25ccc54772efd 100644 --- a/solution/1600-1699/1648.Sell Diminishing-Valued Colored Balls/README_EN.md +++ b/solution/1600-1699/1648.Sell Diminishing-Valued Colored Balls/README_EN.md @@ -42,9 +42,9 @@ The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -118,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +149,6 @@ public: }; ``` -### **Go** - ```go func maxProfit(inventory []int, orders int) int { var mod int = 1e9 + 7 @@ -191,10 +185,6 @@ func maxProfit(inventory []int, orders int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1649.Create Sorted Array through Instructions/README.md b/solution/1600-1699/1649.Create Sorted Array through Instructions/README.md index d1790d3814b38..0b02f8a05123c 100644 --- a/solution/1600-1699/1649.Create Sorted Array through Instructions/README.md +++ b/solution/1600-1699/1649.Create Sorted Array through Instructions/README.md @@ -72,9 +72,7 @@ ## 解法 - - -**方法一:树状数组** +### 方法一:树状数组 树状数组,也称作“二叉索引树”(Binary Indexed Tree)或 Fenwick 树。 它可以高效地实现如下两个操作: @@ -89,25 +87,8 @@ 解决方案是直接遍历数组,每个位置先求出 `query(a[i])`,然后再修改树状数组 `update(a[i], 1)` 即可。当数的范围比较大时,需要进行离散化,即先进行去重并排序,然后对每个数字进行编号。 -**方法二:线段树** - -线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。 - -- 线段树的每个节点代表一个区间; -- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 `[1, N]`; -- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`; -- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。 - -> 本题线段树 Python3 代码 TLE,Java、C++ 代码 AC。 - -### **Python3** - - - -树状数组: - ```python class BinaryIndexedTree: def __init__(self, n): @@ -140,7 +121,195 @@ class Solution: return ans % mod ``` -线段树: +```java +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + this.c = new int[n + 1]; + } + + public void update(int x, int v) { + while (x <= n) { + c[x] += v; + x += x & -x; + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +} + +class Solution { + public int createSortedArray(int[] instructions) { + int m = 0; + for (int x : instructions) { + m = Math.max(m, x); + } + BinaryIndexedTree tree = new BinaryIndexedTree(m); + int ans = 0; + final int mod = (int) 1e9 + 7; + for (int i = 0; i < instructions.length; ++i) { + int x = instructions[i]; + int cost = Math.min(tree.query(x - 1), i - tree.query(x)); + ans = (ans + cost) % mod; + tree.update(x, 1); + } + return ans; + } +} +``` + +```cpp +class BinaryIndexedTree { +public: + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + int query(int x) { + int s = 0; + while (x) { + s += c[x]; + x -= x & -x; + } + return s; + } + +private: + int n; + vector c; +}; + +class Solution { +public: + int createSortedArray(vector& instructions) { + int m = *max_element(instructions.begin(), instructions.end()); + BinaryIndexedTree tree(m); + const int mod = 1e9 + 7; + int ans = 0; + for (int i = 0; i < instructions.size(); ++i) { + int x = instructions[i]; + int cost = min(tree.query(x - 1), i - tree.query(x)); + ans = (ans + cost) % mod; + tree.update(x, 1); + } + return ans; + } +}; +``` + +```go +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += x & -x + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= x & -x + } + return s +} + +func createSortedArray(instructions []int) (ans int) { + m := slices.Max(instructions) + tree := newBinaryIndexedTree(m) + const mod = 1e9 + 7 + for i, x := range instructions { + cost := min(tree.query(x-1), i-tree.query(x)) + ans = (ans + cost) % mod + tree.update(x, 1) + } + return +} +``` + +```ts +class BinaryIndexedTree { + private n: number; + private c: number[]; + + constructor(n: number) { + this.n = n; + this.c = new Array(n + 1).fill(0); + } + + public update(x: number, v: number): void { + while (x <= this.n) { + this.c[x] += v; + x += x & -x; + } + } + + public query(x: number): number { + let s = 0; + while (x > 0) { + s += this.c[x]; + x -= x & -x; + } + return s; + } +} + +function createSortedArray(instructions: number[]): number { + const m = Math.max(...instructions); + const tree = new BinaryIndexedTree(m); + let ans = 0; + const mod = 10 ** 9 + 7; + for (let i = 0; i < instructions.length; ++i) { + const x = instructions[i]; + const cost = Math.min(tree.query(x - 1), i - tree.query(x)); + ans = (ans + cost) % mod; + tree.update(x, 1); + } + return ans; +} +``` + + + +### 方法二:线段树 + +线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。 + +- 线段树的每个节点代表一个区间; +- 线段树具有唯一的根节点,代表的区间是整个统计范围,如 `[1, N]`; +- 线段树的每个叶子节点代表一个长度为 1 的元区间 `[x, x]`; +- 对于每个内部节点 `[l, r]`,它的左儿子是 `[l, mid]`,右儿子是 `[mid + 1, r]`, 其中 `mid = ⌊(l + r) / 2⌋` (即向下取整)。 + +> 本题线段树 Python3 代码 TLE,Java、C++ 代码 AC。 + + ```python class Node: @@ -203,61 +372,6 @@ class Solution: return ans % int((1e9 + 7)) ``` -### **Java** - - - -树状数组: - -```java -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - this.c = new int[n + 1]; - } - - public void update(int x, int v) { - while (x <= n) { - c[x] += v; - x += x & -x; - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= x & -x; - } - return s; - } -} - -class Solution { - public int createSortedArray(int[] instructions) { - int m = 0; - for (int x : instructions) { - m = Math.max(m, x); - } - BinaryIndexedTree tree = new BinaryIndexedTree(m); - int ans = 0; - final int mod = (int) 1e9 + 7; - for (int i = 0; i < instructions.length; ++i) { - int x = instructions[i]; - int cost = Math.min(tree.query(x - 1), i - tree.query(x)); - ans = (ans + cost) % mod; - tree.update(x, 1); - } - return ans; - } -} -``` - -线段树: - ```java class Solution { public int createSortedArray(int[] instructions) { @@ -339,58 +453,6 @@ class SegmentTree { } ``` -### **C++** - -树状数组: - -```cpp -class BinaryIndexedTree { -public: - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += x & -x; - } - } - - int query(int x) { - int s = 0; - while (x) { - s += c[x]; - x -= x & -x; - } - return s; - } - -private: - int n; - vector c; -}; - -class Solution { -public: - int createSortedArray(vector& instructions) { - int m = *max_element(instructions.begin(), instructions.end()); - BinaryIndexedTree tree(m); - const int mod = 1e9 + 7; - int ans = 0; - for (int i = 0; i < instructions.size(); ++i) { - int x = instructions[i]; - int cost = min(tree.query(x - 1), i - tree.query(x)); - ans = (ans + cost) % mod; - tree.update(x, 1); - } - return ans; - } -}; -``` - -线段树: - ```cpp class Node { public: @@ -464,98 +526,6 @@ public: }; ``` -### **Go** - -树状数组: - -```go -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (this *BinaryIndexedTree) update(x, delta int) { - for x <= this.n { - this.c[x] += delta - x += x & -x - } -} - -func (this *BinaryIndexedTree) query(x int) int { - s := 0 - for x > 0 { - s += this.c[x] - x -= x & -x - } - return s -} - -func createSortedArray(instructions []int) (ans int) { - m := slices.Max(instructions) - tree := newBinaryIndexedTree(m) - const mod = 1e9 + 7 - for i, x := range instructions { - cost := min(tree.query(x-1), i-tree.query(x)) - ans = (ans + cost) % mod - tree.update(x, 1) - } - return -} -``` - -### **TypeScript** - -```ts -class BinaryIndexedTree { - private n: number; - private c: number[]; - - constructor(n: number) { - this.n = n; - this.c = new Array(n + 1).fill(0); - } - - public update(x: number, v: number): void { - while (x <= this.n) { - this.c[x] += v; - x += x & -x; - } - } - - public query(x: number): number { - let s = 0; - while (x > 0) { - s += this.c[x]; - x -= x & -x; - } - return s; - } -} - -function createSortedArray(instructions: number[]): number { - const m = Math.max(...instructions); - const tree = new BinaryIndexedTree(m); - let ans = 0; - const mod = 10 ** 9 + 7; - for (let i = 0; i < instructions.length; ++i) { - const x = instructions[i]; - const cost = Math.min(tree.query(x - 1), i - tree.query(x)); - ans = (ans + cost) % mod; - tree.update(x, 1); - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1649.Create Sorted Array through Instructions/README_EN.md b/solution/1600-1699/1649.Create Sorted Array through Instructions/README_EN.md index 78f4fe3daf054..8aa72c14077b9 100644 --- a/solution/1600-1699/1649.Create Sorted Array through Instructions/README_EN.md +++ b/solution/1600-1699/1649.Create Sorted Array through Instructions/README_EN.md @@ -71,14 +71,10 @@ The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4. ## Solutions -Binary Indexed Tree or Segment Tree. +### Solution 1 -### **Python3** - -Binary Indexed Tree: - ```python class BinaryIndexedTree: def __init__(self, n): @@ -111,7 +107,186 @@ class Solution: return ans % mod ``` -Segment Tree: +```java +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + this.c = new int[n + 1]; + } + + public void update(int x, int v) { + while (x <= n) { + c[x] += v; + x += x & -x; + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= x & -x; + } + return s; + } +} + +class Solution { + public int createSortedArray(int[] instructions) { + int m = 0; + for (int x : instructions) { + m = Math.max(m, x); + } + BinaryIndexedTree tree = new BinaryIndexedTree(m); + int ans = 0; + final int mod = (int) 1e9 + 7; + for (int i = 0; i < instructions.length; ++i) { + int x = instructions[i]; + int cost = Math.min(tree.query(x - 1), i - tree.query(x)); + ans = (ans + cost) % mod; + tree.update(x, 1); + } + return ans; + } +} +``` + +```cpp +class BinaryIndexedTree { +public: + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += x & -x; + } + } + + int query(int x) { + int s = 0; + while (x) { + s += c[x]; + x -= x & -x; + } + return s; + } + +private: + int n; + vector c; +}; + +class Solution { +public: + int createSortedArray(vector& instructions) { + int m = *max_element(instructions.begin(), instructions.end()); + BinaryIndexedTree tree(m); + const int mod = 1e9 + 7; + int ans = 0; + for (int i = 0; i < instructions.size(); ++i) { + int x = instructions[i]; + int cost = min(tree.query(x - 1), i - tree.query(x)); + ans = (ans + cost) % mod; + tree.update(x, 1); + } + return ans; + } +}; +``` + +```go +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += x & -x + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= x & -x + } + return s +} + +func createSortedArray(instructions []int) (ans int) { + m := slices.Max(instructions) + tree := newBinaryIndexedTree(m) + const mod = 1e9 + 7 + for i, x := range instructions { + cost := min(tree.query(x-1), i-tree.query(x)) + ans = (ans + cost) % mod + tree.update(x, 1) + } + return +} +``` + +```ts +class BinaryIndexedTree { + private n: number; + private c: number[]; + + constructor(n: number) { + this.n = n; + this.c = new Array(n + 1).fill(0); + } + + public update(x: number, v: number): void { + while (x <= this.n) { + this.c[x] += v; + x += x & -x; + } + } + + public query(x: number): number { + let s = 0; + while (x > 0) { + s += this.c[x]; + x -= x & -x; + } + return s; + } +} + +function createSortedArray(instructions: number[]): number { + const m = Math.max(...instructions); + const tree = new BinaryIndexedTree(m); + let ans = 0; + const mod = 10 ** 9 + 7; + for (let i = 0; i < instructions.length; ++i) { + const x = instructions[i]; + const cost = Math.min(tree.query(x - 1), i - tree.query(x)); + ans = (ans + cost) % mod; + tree.update(x, 1); + } + return ans; +} +``` + + + +### Solution 2 + + ```python class Node: @@ -174,59 +349,6 @@ class Solution: return ans % int((1e9 + 7)) ``` -### **Java** - -Binary Indexed Tree: - -```java -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - this.c = new int[n + 1]; - } - - public void update(int x, int v) { - while (x <= n) { - c[x] += v; - x += x & -x; - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= x & -x; - } - return s; - } -} - -class Solution { - public int createSortedArray(int[] instructions) { - int m = 0; - for (int x : instructions) { - m = Math.max(m, x); - } - BinaryIndexedTree tree = new BinaryIndexedTree(m); - int ans = 0; - final int mod = (int) 1e9 + 7; - for (int i = 0; i < instructions.length; ++i) { - int x = instructions[i]; - int cost = Math.min(tree.query(x - 1), i - tree.query(x)); - ans = (ans + cost) % mod; - tree.update(x, 1); - } - return ans; - } -} -``` - -Segment Tree: - ```java class Solution { public int createSortedArray(int[] instructions) { @@ -308,58 +430,6 @@ class SegmentTree { } ``` -### **C++** - -Binary Indexed Tree: - -```cpp -class BinaryIndexedTree { -public: - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += x & -x; - } - } - - int query(int x) { - int s = 0; - while (x) { - s += c[x]; - x -= x & -x; - } - return s; - } - -private: - int n; - vector c; -}; - -class Solution { -public: - int createSortedArray(vector& instructions) { - int m = *max_element(instructions.begin(), instructions.end()); - BinaryIndexedTree tree(m); - const int mod = 1e9 + 7; - int ans = 0; - for (int i = 0; i < instructions.size(); ++i) { - int x = instructions[i]; - int cost = min(tree.query(x - 1), i - tree.query(x)); - ans = (ans + cost) % mod; - tree.update(x, 1); - } - return ans; - } -}; -``` - -Segment Tree: - ```cpp class Node { public: @@ -433,98 +503,6 @@ public: }; ``` -### **Go** - -Binary Indexed Tree: - -```go -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (this *BinaryIndexedTree) update(x, delta int) { - for x <= this.n { - this.c[x] += delta - x += x & -x - } -} - -func (this *BinaryIndexedTree) query(x int) int { - s := 0 - for x > 0 { - s += this.c[x] - x -= x & -x - } - return s -} - -func createSortedArray(instructions []int) (ans int) { - m := slices.Max(instructions) - tree := newBinaryIndexedTree(m) - const mod = 1e9 + 7 - for i, x := range instructions { - cost := min(tree.query(x-1), i-tree.query(x)) - ans = (ans + cost) % mod - tree.update(x, 1) - } - return -} -``` - -### **TypeScript** - -```ts -class BinaryIndexedTree { - private n: number; - private c: number[]; - - constructor(n: number) { - this.n = n; - this.c = new Array(n + 1).fill(0); - } - - public update(x: number, v: number): void { - while (x <= this.n) { - this.c[x] += v; - x += x & -x; - } - } - - public query(x: number): number { - let s = 0; - while (x > 0) { - s += this.c[x]; - x -= x & -x; - } - return s; - } -} - -function createSortedArray(instructions: number[]): number { - const m = Math.max(...instructions); - const tree = new BinaryIndexedTree(m); - let ans = 0; - const mod = 10 ** 9 + 7; - for (let i = 0; i < instructions.length; ++i) { - const x = instructions[i]; - const cost = Math.min(tree.query(x - 1), i - tree.query(x)); - ans = (ans + cost) % mod; - tree.update(x, 1); - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/README.md b/solution/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/README.md index 2af725a49bc4b..65b67bf8481a2 100644 --- a/solution/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/README.md +++ b/solution/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/README.md @@ -56,14 +56,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python """ # Definition for a Node. @@ -85,10 +81,6 @@ class Solution: return a ``` -### **Java** - - - ```java /* // Definition for a Node. @@ -112,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -140,8 +130,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for Node. @@ -171,10 +159,6 @@ func lowestCommonAncestor(p *Node, q *Node) *Node { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/README_EN.md b/solution/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/README_EN.md index 6978f4d9166c2..7a48c2ecfbcb4 100644 --- a/solution/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/README_EN.md +++ b/solution/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/README_EN.md @@ -56,9 +56,9 @@ class Node { ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -81,8 +81,6 @@ class Solution: return a ``` -### **Java** - ```java /* // Definition for a Node. @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node. @@ -134,8 +130,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for Node. @@ -165,10 +159,6 @@ func lowestCommonAncestor(p *Node, q *Node) *Node { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1651.Hopper Company Queries III/README.md b/solution/1600-1699/1651.Hopper Company Queries III/README.md index c45f393eb34de..bfaee9351f22f 100644 --- a/solution/1600-1699/1651.Hopper Company Queries III/README.md +++ b/solution/1600-1699/1651.Hopper Company Queries III/README.md @@ -143,14 +143,10 @@ AcceptedRides table: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH RECURSIVE @@ -188,3 +184,5 @@ LIMIT 10; ``` + + diff --git a/solution/1600-1699/1651.Hopper Company Queries III/README_EN.md b/solution/1600-1699/1651.Hopper Company Queries III/README_EN.md index 2c8e341f657d3..2110ffec8932b 100644 --- a/solution/1600-1699/1651.Hopper Company Queries III/README_EN.md +++ b/solution/1600-1699/1651.Hopper Company Queries III/README_EN.md @@ -145,9 +145,9 @@ By the end of October --> average_ride_distance = (0+163+6)/3=56.33, average_ ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -186,3 +186,5 @@ LIMIT 10; ``` + + diff --git a/solution/1600-1699/1652.Defuse the Bomb/README.md b/solution/1600-1699/1652.Defuse the Bomb/README.md index 7da2bdd47e9f0..f80221bbc6a6c 100644 --- a/solution/1600-1699/1652.Defuse the Bomb/README.md +++ b/solution/1600-1699/1652.Defuse the Bomb/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 定义答案数组 `ans`,长度为 $n$,初始时所有元素都为 $0$。根据题意,若 $k$ 为 $0$,直接返回 `ans`。 @@ -81,24 +79,8 @@ $$ 时间复杂度 $O(n\times|k|)$,忽略答案的空间消耗,空间复杂度 $O(1)$。 -**方法二:前缀和** - -在方法一中,对于每个位置 $i$,都需要遍历 $k$ 个位置,有很多重复计算的操作。我们可以利用前缀和来优化。 - -我们将 `code` 数组复制一份(可以不用执行复制操作,直接通过循环遍历取模实现),得到两倍长度的数组,对其求前缀和,得到长度为 $2\times n + 1$ 的前缀和数组 $s$。 - -若 $k$ 为正数,那么 $i$ 位置的值为 $i$ 位置后 $k$ 个位置的值之和,即 $ans[i] = s[i + k + 1] - s[i + 1]$。 - -若 $k$ 为负数,那么 $i$ 位置的值为 $i$ 位置前 $|k|$ 个位置的值之和,即 $ans[i] = s[i + n] - s[i + k + n]$。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 `code` 数组的长度。 - -### **Python3** - - - ```python class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: @@ -116,26 +98,6 @@ class Solution: return ans ``` -```python -class Solution: - def decrypt(self, code: List[int], k: int) -> List[int]: - n = len(code) - ans = [0] * n - if k == 0: - return ans - s = list(accumulate(code + code, initial=0)) - for i in range(n): - if k > 0: - ans[i] = s[i + k + 1] - s[i + 1] - else: - ans[i] = s[i + n] - s[i + k + n] - return ans -``` - -### **Java** - - - ```java class Solution { public int[] decrypt(int[] code, int k) { @@ -160,32 +122,6 @@ class Solution { } ``` -```java -class Solution { - public int[] decrypt(int[] code, int k) { - int n = code.length; - int[] ans = new int[n]; - if (k == 0) { - return ans; - } - int[] s = new int[n << 1 | 1]; - for (int i = 0; i < n << 1; ++i) { - s[i + 1] = s[i] + code[i % n]; - } - for (int i = 0; i < n; ++i) { - if (k > 0) { - ans[i] = s[i + k + 1] - s[i + 1]; - } else { - ans[i] = s[i + n] - s[i + k + n]; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -211,33 +147,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector decrypt(vector& code, int k) { - int n = code.size(); - vector ans(n); - if (k == 0) { - return ans; - } - vector s(n << 1 | 1); - for (int i = 0; i < n << 1; ++i) { - s[i + 1] = s[i] + code[i % n]; - } - for (int i = 0; i < n; ++i) { - if (k > 0) { - ans[i] = s[i + k + 1] - s[i + 1]; - } else { - ans[i] = s[i + n] - s[i + k + n]; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func decrypt(code []int, k int) []int { n := len(code) @@ -260,30 +169,6 @@ func decrypt(code []int, k int) []int { } ``` -```go -func decrypt(code []int, k int) []int { - n := len(code) - ans := make([]int, n) - if k == 0 { - return ans - } - s := make([]int, n<<1|1) - for i := 0; i < n<<1; i++ { - s[i+1] = s[i] + code[i%n] - } - for i := range code { - if k > 0 { - ans[i] = s[i+k+1] - s[i+1] - } else { - ans[i] = s[i+n] - s[i+k+n] - } - } - return ans -} -``` - -### **TypeScript** - ```ts function decrypt(code: number[], k: number): number[] { const n = code.length; @@ -318,10 +203,109 @@ function decrypt(code: number[], k: number): number[] { } ``` -### **...** + + +### 方法二:前缀和 + +在方法一中,对于每个位置 $i$,都需要遍历 $k$ 个位置,有很多重复计算的操作。我们可以利用前缀和来优化。 + +我们将 `code` 数组复制一份(可以不用执行复制操作,直接通过循环遍历取模实现),得到两倍长度的数组,对其求前缀和,得到长度为 $2\times n + 1$ 的前缀和数组 $s$。 + +若 $k$ 为正数,那么 $i$ 位置的值为 $i$ 位置后 $k$ 个位置的值之和,即 $ans[i] = s[i + k + 1] - s[i + 1]$。 + +若 $k$ 为负数,那么 $i$ 位置的值为 $i$ 位置前 $|k|$ 个位置的值之和,即 $ans[i] = s[i + n] - s[i + k + n]$。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 `code` 数组的长度。 + + + +```python +class Solution: + def decrypt(self, code: List[int], k: int) -> List[int]: + n = len(code) + ans = [0] * n + if k == 0: + return ans + s = list(accumulate(code + code, initial=0)) + for i in range(n): + if k > 0: + ans[i] = s[i + k + 1] - s[i + 1] + else: + ans[i] = s[i + n] - s[i + k + n] + return ans +``` + +```java +class Solution { + public int[] decrypt(int[] code, int k) { + int n = code.length; + int[] ans = new int[n]; + if (k == 0) { + return ans; + } + int[] s = new int[n << 1 | 1]; + for (int i = 0; i < n << 1; ++i) { + s[i + 1] = s[i] + code[i % n]; + } + for (int i = 0; i < n; ++i) { + if (k > 0) { + ans[i] = s[i + k + 1] - s[i + 1]; + } else { + ans[i] = s[i + n] - s[i + k + n]; + } + } + return ans; + } +} +``` +```cpp +class Solution { +public: + vector decrypt(vector& code, int k) { + int n = code.size(); + vector ans(n); + if (k == 0) { + return ans; + } + vector s(n << 1 | 1); + for (int i = 0; i < n << 1; ++i) { + s[i + 1] = s[i] + code[i % n]; + } + for (int i = 0; i < n; ++i) { + if (k > 0) { + ans[i] = s[i + k + 1] - s[i + 1]; + } else { + ans[i] = s[i + n] - s[i + k + n]; + } + } + return ans; + } +}; ``` +```go +func decrypt(code []int, k int) []int { + n := len(code) + ans := make([]int, n) + if k == 0 { + return ans + } + s := make([]int, n<<1|1) + for i := 0; i < n<<1; i++ { + s[i+1] = s[i] + code[i%n] + } + for i := range code { + if k > 0 { + ans[i] = s[i+k+1] - s[i+1] + } else { + ans[i] = s[i+n] - s[i+k+n] + } + } + return ans +} ``` + + diff --git a/solution/1600-1699/1652.Defuse the Bomb/README_EN.md b/solution/1600-1699/1652.Defuse the Bomb/README_EN.md index 4126487f66c09..dd8b92bce30b2 100644 --- a/solution/1600-1699/1652.Defuse the Bomb/README_EN.md +++ b/solution/1600-1699/1652.Defuse the Bomb/README_EN.md @@ -55,9 +55,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,24 +76,6 @@ class Solution: return ans ``` -```python -class Solution: - def decrypt(self, code: List[int], k: int) -> List[int]: - n = len(code) - ans = [0] * n - if k == 0: - return ans - s = list(accumulate(code + code, initial=0)) - for i in range(n): - if k > 0: - ans[i] = s[i + k + 1] - s[i + 1] - else: - ans[i] = s[i + n] - s[i + k + n] - return ans -``` - -### **Java** - ```java class Solution { public int[] decrypt(int[] code, int k) { @@ -118,32 +100,6 @@ class Solution { } ``` -```java -class Solution { - public int[] decrypt(int[] code, int k) { - int n = code.length; - int[] ans = new int[n]; - if (k == 0) { - return ans; - } - int[] s = new int[n << 1 | 1]; - for (int i = 0; i < n << 1; ++i) { - s[i + 1] = s[i] + code[i % n]; - } - for (int i = 0; i < n; ++i) { - if (k > 0) { - ans[i] = s[i + k + 1] - s[i + 1]; - } else { - ans[i] = s[i + n] - s[i + k + n]; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -169,33 +125,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector decrypt(vector& code, int k) { - int n = code.size(); - vector ans(n); - if (k == 0) { - return ans; - } - vector s(n << 1 | 1); - for (int i = 0; i < n << 1; ++i) { - s[i + 1] = s[i] + code[i % n]; - } - for (int i = 0; i < n; ++i) { - if (k > 0) { - ans[i] = s[i + k + 1] - s[i + 1]; - } else { - ans[i] = s[i + n] - s[i + k + n]; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func decrypt(code []int, k int) []int { n := len(code) @@ -218,30 +147,6 @@ func decrypt(code []int, k int) []int { } ``` -```go -func decrypt(code []int, k int) []int { - n := len(code) - ans := make([]int, n) - if k == 0 { - return ans - } - s := make([]int, n<<1|1) - for i := 0; i < n<<1; i++ { - s[i+1] = s[i] + code[i%n] - } - for i := range code { - if k > 0 { - ans[i] = s[i+k+1] - s[i+1] - } else { - ans[i] = s[i+n] - s[i+k+n] - } - } - return ans -} -``` - -### **TypeScript** - ```ts function decrypt(code: number[], k: number): number[] { const n = code.length; @@ -276,10 +181,99 @@ function decrypt(code: number[], k: number): number[] { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def decrypt(self, code: List[int], k: int) -> List[int]: + n = len(code) + ans = [0] * n + if k == 0: + return ans + s = list(accumulate(code + code, initial=0)) + for i in range(n): + if k > 0: + ans[i] = s[i + k + 1] - s[i + 1] + else: + ans[i] = s[i + n] - s[i + k + n] + return ans +``` + +```java +class Solution { + public int[] decrypt(int[] code, int k) { + int n = code.length; + int[] ans = new int[n]; + if (k == 0) { + return ans; + } + int[] s = new int[n << 1 | 1]; + for (int i = 0; i < n << 1; ++i) { + s[i + 1] = s[i] + code[i % n]; + } + for (int i = 0; i < n; ++i) { + if (k > 0) { + ans[i] = s[i + k + 1] - s[i + 1]; + } else { + ans[i] = s[i + n] - s[i + k + n]; + } + } + return ans; + } +} +``` +```cpp +class Solution { +public: + vector decrypt(vector& code, int k) { + int n = code.size(); + vector ans(n); + if (k == 0) { + return ans; + } + vector s(n << 1 | 1); + for (int i = 0; i < n << 1; ++i) { + s[i + 1] = s[i] + code[i % n]; + } + for (int i = 0; i < n; ++i) { + if (k > 0) { + ans[i] = s[i + k + 1] - s[i + 1]; + } else { + ans[i] = s[i + n] - s[i + k + n]; + } + } + return ans; + } +}; ``` +```go +func decrypt(code []int, k int) []int { + n := len(code) + ans := make([]int, n) + if k == 0 { + return ans + } + s := make([]int, n<<1|1) + for i := 0; i < n<<1; i++ { + s[i+1] = s[i] + code[i%n] + } + for i := range code { + if k > 0 { + ans[i] = s[i+k+1] - s[i+1] + } else { + ans[i] = s[i+n] - s[i+k+n] + } + } + return ans +} ``` + + diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/README.md b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/README.md index 31ee7cbd7bfd4..ba08aa550fd23 100644 --- a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/README.md +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示前 $i$ 个字符中,删除最少的字符数,使得字符串平衡。初始时 $f[0]=0$。答案为 $f[n]$。 @@ -69,20 +67,8 @@ $$ 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。 -**方法二:枚举 + 前缀和** - -我们可以枚举字符串 $s$ 中的每一个位置 $i$,将字符串 $s$ 分成两部分,分别为 $s[0,..,i-1]$ 和 $s[i+1,..n-1]$,要使得字符串平衡,我们在当前位置 $i$ 需要删除的字符数为 $s[0,..,i-1]$ 中字符 $b$ 的个数加上 $s[i+1,..n-1]$ 中字符 $a$ 的个数。 - -因此,我们维护两个变量 $lb$ 和 $ra$ 分别表示 $s[0,..,i-1]$ 中字符 $b$ 的个数以及 $s[i+1,..n-1]$ 中字符 $a$ 的个数,那么我们需要删除的字符数为 $lb+ra$。枚举过程中,更新变量 $lb$ 和 $ra$。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。 - -### **Python3** - - - ```python class Solution: def minimumDeletions(self, s: str) -> int: @@ -98,34 +84,6 @@ class Solution: return f[n] ``` -```python -class Solution: - def minimumDeletions(self, s: str) -> int: - ans = b = 0 - for c in s: - if c == 'b': - b += 1 - else: - ans = min(ans + 1, b) - return ans -``` - -```python -class Solution: - def minimumDeletions(self, s: str) -> int: - lb, ra = 0, s.count('a') - ans = len(s) - for c in s: - ra -= c == 'a' - ans = min(ans, lb + ra) - lb += c == 'b' - return ans -``` - -### **Java** - - - ```java class Solution { public int minimumDeletions(String s) { @@ -145,46 +103,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumDeletions(String s) { - int n = s.length(); - int ans = 0, b = 0; - for (int i = 0; i < n; ++i) { - if (s.charAt(i) == 'b') { - ++b; - } else { - ans = Math.min(ans + 1, b); - } - } - return ans; - } -} -``` - -```java -class Solution { - public int minimumDeletions(String s) { - int lb = 0, ra = 0; - int n = s.length(); - for (int i = 0; i < n; ++i) { - if (s.charAt(i) == 'a') { - ++ra; - } - } - int ans = n; - for (int i = 0; i < n; ++i) { - ra -= (s.charAt(i) == 'a' ? 1 : 0); - ans = Math.min(ans, lb + ra); - lb += (s.charAt(i) == 'b' ? 1 : 0); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -206,59 +124,99 @@ public: }; ``` -```cpp +```go +func minimumDeletions(s string) int { + n := len(s) + f := make([]int, n+1) + b := 0 + for i, c := range s { + i++ + if c == 'b' { + f[i] = f[i-1] + b++ + } else { + f[i] = min(f[i-1]+1, b) + } + } + return f[n] +} +``` + +```ts +function minimumDeletions(s: string): number { + const n = s.length; + const f = new Array(n + 1).fill(0); + let b = 0; + for (let i = 1; i <= n; ++i) { + if (s.charAt(i - 1) === 'b') { + f[i] = f[i - 1]; + ++b; + } else { + f[i] = Math.min(f[i - 1] + 1, b); + } + } + return f[n]; +} +``` + + + +### 方法二:枚举 + 前缀和 + +我们可以枚举字符串 $s$ 中的每一个位置 $i$,将字符串 $s$ 分成两部分,分别为 $s[0,..,i-1]$ 和 $s[i+1,..n-1]$,要使得字符串平衡,我们在当前位置 $i$ 需要删除的字符数为 $s[0,..,i-1]$ 中字符 $b$ 的个数加上 $s[i+1,..n-1]$ 中字符 $a$ 的个数。 + +因此,我们维护两个变量 $lb$ 和 $ra$ 分别表示 $s[0,..,i-1]$ 中字符 $b$ 的个数以及 $s[i+1,..n-1]$ 中字符 $a$ 的个数,那么我们需要删除的字符数为 $lb+ra$。枚举过程中,更新变量 $lb$ 和 $ra$。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。 + + + +```python +class Solution: + def minimumDeletions(self, s: str) -> int: + ans = b = 0 + for c in s: + if c == 'b': + b += 1 + else: + ans = min(ans + 1, b) + return ans +``` + +```java class Solution { -public: - int minimumDeletions(string s) { + public int minimumDeletions(String s) { + int n = s.length(); int ans = 0, b = 0; - for (char& c : s) { - if (c == 'b') { + for (int i = 0; i < n; ++i) { + if (s.charAt(i) == 'b') { ++b; } else { - ans = min(ans + 1, b); + ans = Math.min(ans + 1, b); } } return ans; } -}; +} ``` ```cpp class Solution { public: int minimumDeletions(string s) { - int lb = 0, ra = count(s.begin(), s.end(), 'a'); - int ans = ra; + int ans = 0, b = 0; for (char& c : s) { - ra -= c == 'a'; - ans = min(ans, lb + ra); - lb += c == 'b'; + if (c == 'b') { + ++b; + } else { + ans = min(ans + 1, b); + } } return ans; } }; ``` -### **Go** - -```go -func minimumDeletions(s string) int { - n := len(s) - f := make([]int, n+1) - b := 0 - for i, c := range s { - i++ - if c == 'b' { - f[i] = f[i-1] - b++ - } else { - f[i] = min(f[i-1]+1, b) - } - } - return f[n] -} -``` - ```go func minimumDeletions(s string) int { ans, b := 0, 0 @@ -273,6 +231,77 @@ func minimumDeletions(s string) int { } ``` +```ts +function minimumDeletions(s: string): number { + const n = s.length; + let ans = 0, + b = 0; + for (let i = 0; i < n; ++i) { + if (s.charAt(i) === 'b') { + ++b; + } else { + ans = Math.min(ans + 1, b); + } + } + return ans; +} +``` + + + +### 方法三 + + + +```python +class Solution: + def minimumDeletions(self, s: str) -> int: + lb, ra = 0, s.count('a') + ans = len(s) + for c in s: + ra -= c == 'a' + ans = min(ans, lb + ra) + lb += c == 'b' + return ans +``` + +```java +class Solution { + public int minimumDeletions(String s) { + int lb = 0, ra = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + if (s.charAt(i) == 'a') { + ++ra; + } + } + int ans = n; + for (int i = 0; i < n; ++i) { + ra -= (s.charAt(i) == 'a' ? 1 : 0); + ans = Math.min(ans, lb + ra); + lb += (s.charAt(i) == 'b' ? 1 : 0); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int minimumDeletions(string s) { + int lb = 0, ra = count(s.begin(), s.end(), 'a'); + int ans = ra; + for (char& c : s) { + ra -= c == 'a'; + ans = min(ans, lb + ra); + lb += c == 'b'; + } + return ans; + } +}; +``` + ```go func minimumDeletions(s string) int { lb, ra := 0, strings.Count(s, "a") @@ -292,41 +321,6 @@ func minimumDeletions(s string) int { } ``` -### **TypeScript** - -```ts -function minimumDeletions(s: string): number { - const n = s.length; - const f = new Array(n + 1).fill(0); - let b = 0; - for (let i = 1; i <= n; ++i) { - if (s.charAt(i - 1) === 'b') { - f[i] = f[i - 1]; - ++b; - } else { - f[i] = Math.min(f[i - 1] + 1, b); - } - } - return f[n]; -} -``` - -```ts -function minimumDeletions(s: string): number { - const n = s.length; - let ans = 0, - b = 0; - for (let i = 0; i < n; ++i) { - if (s.charAt(i) === 'b') { - ++b; - } else { - ans = Math.min(ans + 1, b); - } - } - return ans; -} -``` - ```ts function minimumDeletions(s: string): number { let lb = 0, @@ -347,10 +341,6 @@ function minimumDeletions(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/README_EN.md b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/README_EN.md index f4344acaf9c4d..1d56a721f14c8 100644 --- a/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/README_EN.md +++ b/solution/1600-1699/1653.Minimum Deletions to Make String Balanced/README_EN.md @@ -39,12 +39,10 @@ Delete the characters at 0-indexed positions 3 and 6 ("aababba -### **Python3** - ```python class Solution: def minimumDeletions(self, s: str) -> int: @@ -60,32 +58,6 @@ class Solution: return f[n] ``` -```python -class Solution: - def minimumDeletions(self, s: str) -> int: - ans = b = 0 - for c in s: - if c == 'b': - b += 1 - else: - ans = min(ans + 1, b) - return ans -``` - -```python -class Solution: - def minimumDeletions(self, s: str) -> int: - lb, ra = 0, s.count('a') - ans = len(s) - for c in s: - ra -= c == 'a' - ans = min(ans, lb + ra) - lb += c == 'b' - return ans -``` - -### **Java** - ```java class Solution { public int minimumDeletions(String s) { @@ -105,46 +77,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumDeletions(String s) { - int n = s.length(); - int ans = 0, b = 0; - for (int i = 0; i < n; ++i) { - if (s.charAt(i) == 'b') { - ++b; - } else { - ans = Math.min(ans + 1, b); - } - } - return ans; - } -} -``` - -```java -class Solution { - public int minimumDeletions(String s) { - int lb = 0, ra = 0; - int n = s.length(); - for (int i = 0; i < n; ++i) { - if (s.charAt(i) == 'a') { - ++ra; - } - } - int ans = n; - for (int i = 0; i < n; ++i) { - ra -= (s.charAt(i) == 'a' ? 1 : 0); - ans = Math.min(ans, lb + ra); - lb += (s.charAt(i) == 'b' ? 1 : 0); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -166,59 +98,93 @@ public: }; ``` -```cpp +```go +func minimumDeletions(s string) int { + n := len(s) + f := make([]int, n+1) + b := 0 + for i, c := range s { + i++ + if c == 'b' { + f[i] = f[i-1] + b++ + } else { + f[i] = min(f[i-1]+1, b) + } + } + return f[n] +} +``` + +```ts +function minimumDeletions(s: string): number { + const n = s.length; + const f = new Array(n + 1).fill(0); + let b = 0; + for (let i = 1; i <= n; ++i) { + if (s.charAt(i - 1) === 'b') { + f[i] = f[i - 1]; + ++b; + } else { + f[i] = Math.min(f[i - 1] + 1, b); + } + } + return f[n]; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minimumDeletions(self, s: str) -> int: + ans = b = 0 + for c in s: + if c == 'b': + b += 1 + else: + ans = min(ans + 1, b) + return ans +``` + +```java class Solution { -public: - int minimumDeletions(string s) { + public int minimumDeletions(String s) { + int n = s.length(); int ans = 0, b = 0; - for (char& c : s) { - if (c == 'b') { + for (int i = 0; i < n; ++i) { + if (s.charAt(i) == 'b') { ++b; } else { - ans = min(ans + 1, b); + ans = Math.min(ans + 1, b); } } return ans; } -}; +} ``` ```cpp class Solution { public: int minimumDeletions(string s) { - int lb = 0, ra = count(s.begin(), s.end(), 'a'); - int ans = ra; + int ans = 0, b = 0; for (char& c : s) { - ra -= c == 'a'; - ans = min(ans, lb + ra); - lb += c == 'b'; + if (c == 'b') { + ++b; + } else { + ans = min(ans + 1, b); + } } return ans; } }; ``` -### **Go** - -```go -func minimumDeletions(s string) int { - n := len(s) - f := make([]int, n+1) - b := 0 - for i, c := range s { - i++ - if c == 'b' { - f[i] = f[i-1] - b++ - } else { - f[i] = min(f[i-1]+1, b) - } - } - return f[n] -} -``` - ```go func minimumDeletions(s string) int { ans, b := 0, 0 @@ -233,6 +199,77 @@ func minimumDeletions(s string) int { } ``` +```ts +function minimumDeletions(s: string): number { + const n = s.length; + let ans = 0, + b = 0; + for (let i = 0; i < n; ++i) { + if (s.charAt(i) === 'b') { + ++b; + } else { + ans = Math.min(ans + 1, b); + } + } + return ans; +} +``` + + + +### Solution 3 + + + +```python +class Solution: + def minimumDeletions(self, s: str) -> int: + lb, ra = 0, s.count('a') + ans = len(s) + for c in s: + ra -= c == 'a' + ans = min(ans, lb + ra) + lb += c == 'b' + return ans +``` + +```java +class Solution { + public int minimumDeletions(String s) { + int lb = 0, ra = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + if (s.charAt(i) == 'a') { + ++ra; + } + } + int ans = n; + for (int i = 0; i < n; ++i) { + ra -= (s.charAt(i) == 'a' ? 1 : 0); + ans = Math.min(ans, lb + ra); + lb += (s.charAt(i) == 'b' ? 1 : 0); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int minimumDeletions(string s) { + int lb = 0, ra = count(s.begin(), s.end(), 'a'); + int ans = ra; + for (char& c : s) { + ra -= c == 'a'; + ans = min(ans, lb + ra); + lb += c == 'b'; + } + return ans; + } +}; +``` + ```go func minimumDeletions(s string) int { lb, ra := 0, strings.Count(s, "a") @@ -252,41 +289,6 @@ func minimumDeletions(s string) int { } ``` -### **TypeScript** - -```ts -function minimumDeletions(s: string): number { - const n = s.length; - const f = new Array(n + 1).fill(0); - let b = 0; - for (let i = 1; i <= n; ++i) { - if (s.charAt(i - 1) === 'b') { - f[i] = f[i - 1]; - ++b; - } else { - f[i] = Math.min(f[i - 1] + 1, b); - } - } - return f[n]; -} -``` - -```ts -function minimumDeletions(s: string): number { - const n = s.length; - let ans = 0, - b = 0; - for (let i = 0; i < n; ++i) { - if (s.charAt(i) === 'b') { - ++b; - } else { - ans = Math.min(ans + 1, b); - } - } - return ans; -} -``` - ```ts function minimumDeletions(s: string): number { let lb = 0, @@ -307,10 +309,6 @@ function minimumDeletions(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1654.Minimum Jumps to Reach Home/README.md b/solution/1600-1699/1654.Minimum Jumps to Reach Home/README.md index dd2328f9227ea..5ae7c2c343c51 100644 --- a/solution/1600-1699/1654.Minimum Jumps to Reach Home/README.md +++ b/solution/1600-1699/1654.Minimum Jumps to Reach Home/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们可以将跳蚤的位置和跳跃方向作为状态,使用 BFS 搜索最短路径。本题比较关键的地方在于确定右边界,即跳蚤最远能跳到哪里。 @@ -85,10 +83,6 @@ -### **Python3** - - - ```python class Solution: def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int: @@ -112,10 +106,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int minimumJumps(int[] forbidden, int a, int b, int x) { @@ -155,8 +145,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -192,8 +180,6 @@ public: }; ``` -### **Go** - ```go func minimumJumps(forbidden []int, a int, b int, x int) (ans int) { s := map[int]bool{} @@ -229,8 +215,6 @@ func minimumJumps(forbidden []int, a int, b int, x int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumJumps(forbidden: number[], a: number, b: number, x: number): number { const s: Set = new Set(forbidden); @@ -260,10 +244,6 @@ function minimumJumps(forbidden: number[], a: number, b: number, x: number): num } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1654.Minimum Jumps to Reach Home/README_EN.md b/solution/1600-1699/1654.Minimum Jumps to Reach Home/README_EN.md index 3006b3fcbba14..23b73fefb8f9b 100644 --- a/solution/1600-1699/1654.Minimum Jumps to Reach Home/README_EN.md +++ b/solution/1600-1699/1654.Minimum Jumps to Reach Home/README_EN.md @@ -56,12 +56,10 @@ ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int: @@ -85,8 +83,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int minimumJumps(int[] forbidden, int a, int b, int x) { @@ -126,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +157,6 @@ public: }; ``` -### **Go** - ```go func minimumJumps(forbidden []int, a int, b int, x int) (ans int) { s := map[int]bool{} @@ -200,8 +192,6 @@ func minimumJumps(forbidden []int, a int, b int, x int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumJumps(forbidden: number[], a: number, b: number, x: number): number { const s: Set = new Set(forbidden); @@ -231,10 +221,6 @@ function minimumJumps(forbidden: number[], a: number, b: number, x: number): num } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1655.Distribute Repeating Integers/README.md b/solution/1600-1699/1655.Distribute Repeating Integers/README.md index 011ea1c7e71a3..fa02794dc81c3 100644 --- a/solution/1600-1699/1655.Distribute Repeating Integers/README.md +++ b/solution/1600-1699/1655.Distribute Repeating Integers/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:状态压缩动态规划 + 子集枚举** +### 方法一:状态压缩动态规划 + 子集枚举 我们先统计数组 $nums$ 中每个数字出现的次数,记录在哈希表 $cnt$ 中,然后将哈希表中的值存入数组 $arr$ 中,我们记数组 $arr$ 的长度为 $n$。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def canDistribute(self, nums: List[int], quantity: List[int]) -> bool: @@ -114,10 +108,6 @@ class Solution: return f[-1][-1] ``` -### **Java** - - - ```java class Solution { public boolean canDistribute(int[] nums, int[] quantity) { @@ -166,8 +156,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -218,8 +206,6 @@ public: }; ``` -### **Go** - ```go func canDistribute(nums []int, quantity []int) bool { m := len(quantity) @@ -266,8 +252,6 @@ func canDistribute(nums []int, quantity []int) bool { } ``` -### **TypeScript** - ```ts function canDistribute(nums: number[], quantity: number[]): boolean { const m = quantity.length; @@ -313,10 +297,6 @@ function canDistribute(nums: number[], quantity: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1655.Distribute Repeating Integers/README_EN.md b/solution/1600-1699/1655.Distribute Repeating Integers/README_EN.md index 54bfcc88df326..ef878cbe445d2 100644 --- a/solution/1600-1699/1655.Distribute Repeating Integers/README_EN.md +++ b/solution/1600-1699/1655.Distribute Repeating Integers/README_EN.md @@ -54,9 +54,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -90,8 +90,6 @@ class Solution: return f[-1][-1] ``` -### **Java** - ```java class Solution { public boolean canDistribute(int[] nums, int[] quantity) { @@ -140,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -192,8 +188,6 @@ public: }; ``` -### **Go** - ```go func canDistribute(nums []int, quantity []int) bool { m := len(quantity) @@ -240,8 +234,6 @@ func canDistribute(nums []int, quantity []int) bool { } ``` -### **TypeScript** - ```ts function canDistribute(nums: number[], quantity: number[]): boolean { const m = quantity.length; @@ -287,10 +279,6 @@ function canDistribute(nums: number[], quantity: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1656.Design an Ordered Stream/README.md b/solution/1600-1699/1656.Design an Ordered Stream/README.md index dd5905d3a13d5..8df8a7144e4fa 100644 --- a/solution/1600-1699/1656.Design an Ordered Stream/README.md +++ b/solution/1600-1699/1656.Design an Ordered Stream/README.md @@ -61,14 +61,10 @@ os.insert(4, "ddddd"); // 插入 (4, "ddddd"),返回 ["ddddd", "eeeee"] ## 解法 - +### 方法一 -### **Python3** - - - ```python class OrderedStream: def __init__(self, n: int): @@ -89,10 +85,6 @@ class OrderedStream: # param_1 = obj.insert(idKey,value) ``` -### **Java** - - - ```java class OrderedStream { private String[] data; @@ -120,8 +112,6 @@ class OrderedStream { */ ``` -### **C++** - ```cpp class OrderedStream { public: @@ -147,8 +137,6 @@ public: */ ``` -### **Go** - ```go type OrderedStream struct { data []string @@ -177,8 +165,6 @@ func (this *OrderedStream) Insert(idKey int, value string) []string { */ ``` -### **TypeScript** - ```ts class OrderedStream { private ptr: number; @@ -207,8 +193,6 @@ class OrderedStream { */ ``` -### **Rust** - ```rust struct OrderedStream { ptr: usize, @@ -244,10 +228,6 @@ impl OrderedStream { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1656.Design an Ordered Stream/README_EN.md b/solution/1600-1699/1656.Design an Ordered Stream/README_EN.md index 4877cb7394b07..e1e36536b50fd 100644 --- a/solution/1600-1699/1656.Design an Ordered Stream/README_EN.md +++ b/solution/1600-1699/1656.Design an Ordered Stream/README_EN.md @@ -54,9 +54,9 @@ os.insert(4, "ddddd"); // Inserts (4, "ddddd"), returns [&qu ## Solutions - +### Solution 1 -### **Python3** + ```python class OrderedStream: @@ -78,8 +78,6 @@ class OrderedStream: # param_1 = obj.insert(idKey,value) ``` -### **Java** - ```java class OrderedStream { private String[] data; @@ -107,8 +105,6 @@ class OrderedStream { */ ``` -### **C++** - ```cpp class OrderedStream { public: @@ -134,8 +130,6 @@ public: */ ``` -### **Go** - ```go type OrderedStream struct { data []string @@ -164,8 +158,6 @@ func (this *OrderedStream) Insert(idKey int, value string) []string { */ ``` -### **TypeScript** - ```ts class OrderedStream { private ptr: number; @@ -194,8 +186,6 @@ class OrderedStream { */ ``` -### **Rust** - ```rust struct OrderedStream { ptr: usize, @@ -231,10 +221,6 @@ impl OrderedStream { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1657.Determine if Two Strings Are Close/README.md b/solution/1600-1699/1657.Determine if Two Strings Are Close/README.md index 54324f6c9db6a..2b231cf251f69 100644 --- a/solution/1600-1699/1657.Determine if Two Strings Are Close/README.md +++ b/solution/1600-1699/1657.Determine if Two Strings Are Close/README.md @@ -73,9 +73,7 @@ ## 解法 - - -**方法一:计数 + 排序** +### 方法一:计数 + 排序 根据题目描述,两个字符串接近,需要同时满足以下两个条件: @@ -92,10 +90,6 @@ -### **Python3** - - - ```python class Solution: def closeStrings(self, word1: str, word2: str) -> bool: @@ -105,10 +99,6 @@ class Solution: ) == set(cnt2.keys()) ``` -### **Java** - - - ```java class Solution { public boolean closeStrings(String word1, String word2) { @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func closeStrings(word1 string, word2 string) bool { cnt1 := make([]int, 26) @@ -179,8 +165,6 @@ func closeStrings(word1 string, word2 string) bool { } ``` -### **TypeScript** - ```ts function closeStrings(word1: string, word2: string): boolean { const cnt1 = Array(26).fill(0); @@ -202,8 +186,6 @@ function closeStrings(word1: string, word2: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn close_strings(word1: String, word2: String) -> bool { @@ -227,10 +209,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1657.Determine if Two Strings Are Close/README_EN.md b/solution/1600-1699/1657.Determine if Two Strings Are Close/README_EN.md index 5f7a69e3d82d8..22ee484a983e0 100644 --- a/solution/1600-1699/1657.Determine if Two Strings Are Close/README_EN.md +++ b/solution/1600-1699/1657.Determine if Two Strings Are Close/README_EN.md @@ -63,7 +63,7 @@ Apply Operation 2: "baaccc" -> "abbccc" ## Solutions -**Solution 1: Counting + Sorting** +### Solution 1: Counting + Sorting According to the problem description, two strings are close if they meet the following two conditions simultaneously: @@ -80,8 +80,6 @@ The time complexity is $O(m + n + C \times \log C)$, and the space complexity is -### **Python3** - ```python class Solution: def closeStrings(self, word1: str, word2: str) -> bool: @@ -91,8 +89,6 @@ class Solution: ) == set(cnt2.keys()) ``` -### **Java** - ```java class Solution { public boolean closeStrings(String word1, String word2) { @@ -116,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go func closeStrings(word1 string, word2 string) bool { cnt1 := make([]int, 26) @@ -163,8 +155,6 @@ func closeStrings(word1 string, word2 string) bool { } ``` -### **TypeScript** - ```ts function closeStrings(word1: string, word2: string): boolean { const cnt1 = Array(26).fill(0); @@ -186,8 +176,6 @@ function closeStrings(word1: string, word2: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn close_strings(word1: String, word2: String) -> bool { @@ -211,10 +199,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/README.md b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/README.md index 65fec550eaf36..fcd676fca6289 100644 --- a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/README.md +++ b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:哈希表 + 前缀和** +### 方法一:哈希表 + 前缀和 我们可以将问题转换为求中间连续子数组的最大长度,使得子数组的和为 $x = sum(nums) - x$。 @@ -61,22 +59,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。 -**方法二:双指针** - -与方法一类似,我们要找到一个子数组,使得子数组的和为 $x = sum(nums) - x$。 - -定义两个指针 $j$ 和 $i$,初始时 $i = j = 0$,然后我们向右移动指针 $i$,将 $nums[i]$ 加到前缀和 $s$ 上。如果 $s \gt x$,那么我们循环向右移动指针 $j$,并且将 $nums[j]$ 从前缀和 $s$ 上减去,直到 $s \le x$。如果 $s = x$,我们可以更新答案的最小值,即 $ans = min(ans, n - (i - j + 1))$。继续向右移动指针 $i$,重复上述过程。 - -最后,如果找不到满足条件的子数组,返回 $-1$,否则返回 $ans$。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。 - -### **Python3** - - - ```python class Solution: def minOperations(self, nums: List[int], x: int) -> int: @@ -94,27 +78,6 @@ class Solution: return -1 if ans == inf else ans ``` -```python -class Solution: - def minOperations(self, nums: List[int], x: int) -> int: - x = sum(nums) - x - ans = inf - n = len(nums) - s = j = 0 - for i, v in enumerate(nums): - s += v - while j <= i and s > x: - s -= nums[j] - j += 1 - if s == x: - ans = min(ans, n - (i - j + 1)) - return -1 if ans == inf else ans -``` - -### **Java** - - - ```java class Solution { public int minOperations(int[] nums, int x) { @@ -139,31 +102,6 @@ class Solution { } ``` -```java -class Solution { - public int minOperations(int[] nums, int x) { - x = -x; - for (int v : nums) { - x += v; - } - int n = nums.length; - int ans = 1 << 30; - for (int i = 0, j = 0, s = 0; i < n; ++i) { - s += nums[i]; - while (j <= i && s > x) { - s -= nums[j++]; - } - if (s == x) { - ans = Math.min(ans, n - (i - j + 1)); - } - } - return ans == 1 << 30 ? -1 : ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -187,29 +125,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minOperations(vector& nums, int x) { - x = accumulate(nums.begin(), nums.end(), 0) - x; - int n = nums.size(); - int ans = 1 << 30; - for (int i = 0, j = 0, s = 0; i < n; ++i) { - s += nums[i]; - while (j <= i && s > x) { - s -= nums[j++]; - } - if (s == x) { - ans = min(ans, n - (i - j + 1)); - } - } - return ans == 1 << 30 ? -1 : ans; - } -}; -``` - -### **Go** - ```go func minOperations(nums []int, x int) int { x = -x @@ -235,34 +150,6 @@ func minOperations(nums []int, x int) int { } ``` -```go -func minOperations(nums []int, x int) int { - x = -x - for _, v := range nums { - x += v - } - ans := 1 << 30 - s, n := 0, len(nums) - j := 0 - for i, v := range nums { - s += v - for j <= i && s > x { - s -= nums[j] - j++ - } - if s == x { - ans = min(ans, n-(i-j+1)) - } - } - if ans == 1<<30 { - return -1 - } - return ans -} -``` - -### **TypeScript** - ```ts function minOperations(nums: number[], x: number): number { x = nums.reduce((a, b) => a + b, 0) - x; @@ -284,26 +171,6 @@ function minOperations(nums: number[], x: number): number { } ``` -```ts -function minOperations(nums: number[], x: number): number { - x = nums.reduce((a, b) => a + b, 0) - x; - const n = nums.length; - let ans = 1 << 30; - for (let i = 0, j = 0, s = 0; i < n; ++i) { - s += nums[i]; - while (j <= i && s > x) { - s -= nums[j++]; - } - if (s == x) { - ans = Math.min(ans, n - (i - j + 1)); - } - } - return ans == 1 << 30 ? -1 : ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn min_operations(nums: Vec, x: i32) -> i32 { @@ -333,8 +200,6 @@ impl Solution { } ``` -### **C** - ```c #define min(a, b) (((a) < (b)) ? (a) : (b)) @@ -365,10 +230,125 @@ int minOperations(int* nums, int numsSize, int x) { } ``` -### **...** + + +### 方法二:双指针 + +与方法一类似,我们要找到一个子数组,使得子数组的和为 $x = sum(nums) - x$。 + +定义两个指针 $j$ 和 $i$,初始时 $i = j = 0$,然后我们向右移动指针 $i$,将 $nums[i]$ 加到前缀和 $s$ 上。如果 $s \gt x$,那么我们循环向右移动指针 $j$,并且将 $nums[j]$ 从前缀和 $s$ 上减去,直到 $s \le x$。如果 $s = x$,我们可以更新答案的最小值,即 $ans = min(ans, n - (i - j + 1))$。继续向右移动指针 $i$,重复上述过程。 + +最后,如果找不到满足条件的子数组,返回 $-1$,否则返回 $ans$。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。 + + +```python +class Solution: + def minOperations(self, nums: List[int], x: int) -> int: + x = sum(nums) - x + ans = inf + n = len(nums) + s = j = 0 + for i, v in enumerate(nums): + s += v + while j <= i and s > x: + s -= nums[j] + j += 1 + if s == x: + ans = min(ans, n - (i - j + 1)) + return -1 if ans == inf else ans ``` +```java +class Solution { + public int minOperations(int[] nums, int x) { + x = -x; + for (int v : nums) { + x += v; + } + int n = nums.length; + int ans = 1 << 30; + for (int i = 0, j = 0, s = 0; i < n; ++i) { + s += nums[i]; + while (j <= i && s > x) { + s -= nums[j++]; + } + if (s == x) { + ans = Math.min(ans, n - (i - j + 1)); + } + } + return ans == 1 << 30 ? -1 : ans; + } +} +``` + +```cpp +class Solution { +public: + int minOperations(vector& nums, int x) { + x = accumulate(nums.begin(), nums.end(), 0) - x; + int n = nums.size(); + int ans = 1 << 30; + for (int i = 0, j = 0, s = 0; i < n; ++i) { + s += nums[i]; + while (j <= i && s > x) { + s -= nums[j++]; + } + if (s == x) { + ans = min(ans, n - (i - j + 1)); + } + } + return ans == 1 << 30 ? -1 : ans; + } +}; +``` + +```go +func minOperations(nums []int, x int) int { + x = -x + for _, v := range nums { + x += v + } + ans := 1 << 30 + s, n := 0, len(nums) + j := 0 + for i, v := range nums { + s += v + for j <= i && s > x { + s -= nums[j] + j++ + } + if s == x { + ans = min(ans, n-(i-j+1)) + } + } + if ans == 1<<30 { + return -1 + } + return ans +} +``` + +```ts +function minOperations(nums: number[], x: number): number { + x = nums.reduce((a, b) => a + b, 0) - x; + const n = nums.length; + let ans = 1 << 30; + for (let i = 0, j = 0, s = 0; i < n; ++i) { + s += nums[i]; + while (j <= i && s > x) { + s -= nums[j++]; + } + if (s == x) { + ans = Math.min(ans, n - (i - j + 1)); + } + } + return ans == 1 << 30 ? -1 : ans; +} ``` + + diff --git a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/README_EN.md b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/README_EN.md index 466a2afac6c18..a536af757bbd6 100644 --- a/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/README_EN.md +++ b/solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,25 +64,6 @@ class Solution: return -1 if ans == inf else ans ``` -```python -class Solution: - def minOperations(self, nums: List[int], x: int) -> int: - x = sum(nums) - x - ans = inf - n = len(nums) - s = j = 0 - for i, v in enumerate(nums): - s += v - while j <= i and s > x: - s -= nums[j] - j += 1 - if s == x: - ans = min(ans, n - (i - j + 1)) - return -1 if ans == inf else ans -``` - -### **Java** - ```java class Solution { public int minOperations(int[] nums, int x) { @@ -107,31 +88,6 @@ class Solution { } ``` -```java -class Solution { - public int minOperations(int[] nums, int x) { - x = -x; - for (int v : nums) { - x += v; - } - int n = nums.length; - int ans = 1 << 30; - for (int i = 0, j = 0, s = 0; i < n; ++i) { - s += nums[i]; - while (j <= i && s > x) { - s -= nums[j++]; - } - if (s == x) { - ans = Math.min(ans, n - (i - j + 1)); - } - } - return ans == 1 << 30 ? -1 : ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -155,29 +111,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minOperations(vector& nums, int x) { - x = accumulate(nums.begin(), nums.end(), 0) - x; - int n = nums.size(); - int ans = 1 << 30; - for (int i = 0, j = 0, s = 0; i < n; ++i) { - s += nums[i]; - while (j <= i && s > x) { - s -= nums[j++]; - } - if (s == x) { - ans = min(ans, n - (i - j + 1)); - } - } - return ans == 1 << 30 ? -1 : ans; - } -}; -``` - -### **Go** - ```go func minOperations(nums []int, x int) int { x = -x @@ -203,34 +136,6 @@ func minOperations(nums []int, x int) int { } ``` -```go -func minOperations(nums []int, x int) int { - x = -x - for _, v := range nums { - x += v - } - ans := 1 << 30 - s, n := 0, len(nums) - j := 0 - for i, v := range nums { - s += v - for j <= i && s > x { - s -= nums[j] - j++ - } - if s == x { - ans = min(ans, n-(i-j+1)) - } - } - if ans == 1<<30 { - return -1 - } - return ans -} -``` - -### **TypeScript** - ```ts function minOperations(nums: number[], x: number): number { x = nums.reduce((a, b) => a + b, 0) - x; @@ -252,26 +157,6 @@ function minOperations(nums: number[], x: number): number { } ``` -```ts -function minOperations(nums: number[], x: number): number { - x = nums.reduce((a, b) => a + b, 0) - x; - const n = nums.length; - let ans = 1 << 30; - for (let i = 0, j = 0, s = 0; i < n; ++i) { - s += nums[i]; - while (j <= i && s > x) { - s -= nums[j++]; - } - if (s == x) { - ans = Math.min(ans, n - (i - j + 1)); - } - } - return ans == 1 << 30 ? -1 : ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn min_operations(nums: Vec, x: i32) -> i32 { @@ -301,8 +186,6 @@ impl Solution { } ``` -### **C** - ```c #define min(a, b) (((a) < (b)) ? (a) : (b)) @@ -333,10 +216,117 @@ int minOperations(int* nums, int numsSize, int x) { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def minOperations(self, nums: List[int], x: int) -> int: + x = sum(nums) - x + ans = inf + n = len(nums) + s = j = 0 + for i, v in enumerate(nums): + s += v + while j <= i and s > x: + s -= nums[j] + j += 1 + if s == x: + ans = min(ans, n - (i - j + 1)) + return -1 if ans == inf else ans ``` +```java +class Solution { + public int minOperations(int[] nums, int x) { + x = -x; + for (int v : nums) { + x += v; + } + int n = nums.length; + int ans = 1 << 30; + for (int i = 0, j = 0, s = 0; i < n; ++i) { + s += nums[i]; + while (j <= i && s > x) { + s -= nums[j++]; + } + if (s == x) { + ans = Math.min(ans, n - (i - j + 1)); + } + } + return ans == 1 << 30 ? -1 : ans; + } +} +``` + +```cpp +class Solution { +public: + int minOperations(vector& nums, int x) { + x = accumulate(nums.begin(), nums.end(), 0) - x; + int n = nums.size(); + int ans = 1 << 30; + for (int i = 0, j = 0, s = 0; i < n; ++i) { + s += nums[i]; + while (j <= i && s > x) { + s -= nums[j++]; + } + if (s == x) { + ans = min(ans, n - (i - j + 1)); + } + } + return ans == 1 << 30 ? -1 : ans; + } +}; +``` + +```go +func minOperations(nums []int, x int) int { + x = -x + for _, v := range nums { + x += v + } + ans := 1 << 30 + s, n := 0, len(nums) + j := 0 + for i, v := range nums { + s += v + for j <= i && s > x { + s -= nums[j] + j++ + } + if s == x { + ans = min(ans, n-(i-j+1)) + } + } + if ans == 1<<30 { + return -1 + } + return ans +} +``` + +```ts +function minOperations(nums: number[], x: number): number { + x = nums.reduce((a, b) => a + b, 0) - x; + const n = nums.length; + let ans = 1 << 30; + for (let i = 0, j = 0, s = 0; i < n; ++i) { + s += nums[i]; + while (j <= i && s > x) { + s -= nums[j++]; + } + if (s == x) { + ans = Math.min(ans, n - (i - j + 1)); + } + } + return ans == 1 << 30 ? -1 : ans; +} ``` + + diff --git a/solution/1600-1699/1659.Maximize Grid Happiness/README.md b/solution/1600-1699/1659.Maximize Grid Happiness/README.md index 6cd41cf1ee277..6d0aadb566474 100644 --- a/solution/1600-1699/1659.Maximize Grid Happiness/README.md +++ b/solution/1600-1699/1659.Maximize Grid Happiness/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:三进制状态压缩 + 记忆化搜索** +### 方法一:三进制状态压缩 + 记忆化搜索 我们注意到,题目中 $1 \leq m, n \leq 5$,并且每个网格单元只有三种状态,即:不分配人员、分配内向的人、分配外向的人。因此,我们可以用 $0$, $1$, $2$ 表示这三种状态,网格中的每一行可以用一个长度为 $n$ 的三进制数表示。 @@ -98,32 +96,8 @@ $$ 时间复杂度 $O(3^{2n} \times (m \times ic \times ec + n))$,空间复杂度 $O(3^{2n} + 3^n \times m \times ic \times ec)$。其中 $ic$ 和 $ec$ 分别表示内向的人和外向的人的个数。 -**方法二:轮廓线记忆化搜索** - -我们可以考虑搜索每个网格单元,每次搜索一个位置 $(i, j)$,我们记 $pos = i \times n + j$。那么它左边以及上边的相邻网格会影响到它们之间的幸福感贡献。 - -我们定义一个函数 $dfs(pos, pre, ic, ec)$,表示当前搜索到位置 $pos$,且此前的 $n$ 个网格单元的状态为 $pre$,内向的人还剩 $ic$ 个,外向的人还剩 $ec$ 个时,网格的最大幸福感。那么答案就是 $dfs(0, 0, introvertsCount, extrovertsCount)$。 - -函数 $dfs(pos, pre, ic, ec)$ 的计算过程如下: - -如果 $pos = m \times n$,表示已经处理完了所有的网格单元,那么返回 $0$; - -如果 $ic = 0$ 且 $ec = 0$,表示所有的人都已经分配完了,那么返回 $0$; - -否则,我们根据 $pre$ 算出当前网格单元的上边相邻网格单元的状态 $up = \frac{pre}{3^{n-1}}$,以及左边相邻网格单元的状态 $left = pre \bmod 3$(注意,如果 $pos$ 在第 $0$ 列,那么 $left = 0$)。 - -接下来,我们枚举当前网格单元的状态 $i$,其中 $i \in [0, 3)$。那么当前的 $n$ 个网格单元的状态为 $cur = pre \bmod 3^{n-1} \times 3 + i$,当前网格单元以及左边和上边的相邻网格单元的幸福感贡献为 $h[up][i]+h[left][i]$;而当前网格单元本身的幸福感取决于该位置是否分配人员,以及分配的人员是内向的还是外向的,如果是内向的,那么幸福感为 $120$,如果是外向的,那么幸福感为 $40$,否则幸福感为 $0$;然后,如果当前网格单元分配了人员,那么我们递归调用时需要更新 $ic$ 或 $ec$。累计这些幸福感,取最大值作为函数的返回值。 - -与方法一类似,我们也可以使用记忆化搜索的方法,避免重复计算。 - -时间复杂度 $O(3^{n+1} \times m \times n \times ic \times ec)$,空间复杂度 $O(3^n \times m \times n \times ic \times ec)$。其中 $ic$ 和 $ec$ 分别表示内向的人和外向的人的个数。 - -### **Python3** - - - ```python class Solution: def getMaxGridHappiness( @@ -168,41 +142,6 @@ class Solution: return dfs(0, 0, introvertsCount, extrovertsCount) ``` -```python -class Solution: - def getMaxGridHappiness( - self, m: int, n: int, introvertsCount: int, extrovertsCount: int - ) -> int: - @cache - def dfs(pos: int, pre: int, ic: int, ec: int) -> int: - if pos == m * n or (ic == 0 and ec == 0): - return 0 - ans = 0 - up = pre // p - left = 0 if pos % n == 0 else pre % 3 - for i in range(3): - if (i == 1 and ic == 0) or (i == 2 and ec == 0): - continue - cur = pre % p * 3 + i - a = h[up][i] + h[left][i] - b = dfs(pos + 1, cur, ic - (i == 1), ec - (i == 2)) - c = 0 - if i == 1: - c = 120 - elif i == 2: - c = 40 - ans = max(ans, a + b + c) - return ans - - p = pow(3, n - 1) - h = [[0, 0, 0], [0, -60, -10], [0, -10, 40]] - return dfs(0, 0, introvertsCount, extrovertsCount) -``` - -### **Java** - - - ```java class Solution { private int m; @@ -271,49 +210,6 @@ class Solution { } ``` -```java -class Solution { - private int m; - private int n; - private int p; - private final int[][] h = {{0, 0, 0}, {0, -60, -10}, {0, -10, 40}}; - private Integer[][][][] memo; - - public int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { - this.m = m; - this.n = n; - p = (int) Math.pow(3, n - 1); - memo = new Integer[m * n][p * 3][introvertsCount + 1][extrovertsCount + 1]; - return dfs(0, 0, introvertsCount, extrovertsCount); - } - - private int dfs(int pos, int pre, int ic, int ec) { - if (pos == m * n || (ic == 0 && ec == 0)) { - return 0; - } - if (memo[pos][pre][ic][ec] != null) { - return memo[pos][pre][ic][ec]; - } - int ans = 0; - int up = pre / p; - int left = pos % n == 0 ? 0 : pre % 3; - for (int i = 0; i < 3; ++i) { - if (i == 1 && (ic == 0) || (i == 2 && ec == 0)) { - continue; - } - int cur = pre % p * 3 + i; - int a = h[up][i] + h[left][i]; - int b = dfs(pos + 1, cur, ic - (i == 1 ? 1 : 0), ec - (i == 2 ? 1 : 0)); - int c = i == 1 ? 120 : (i == 2 ? 40 : 0); - ans = Math.max(ans, a + b + c); - } - return memo[pos][pre][ic][ec] = ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -377,43 +273,6 @@ public: }; ``` -```cpp -class Solution { -public: - int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { - int h[3][3] = {{0, 0, 0}, {0, -60, -10}, {0, -10, 40}}; - int p = pow(3, n - 1); - int memo[m * n][p * 3][introvertsCount + 1][extrovertsCount + 1]; - memset(memo, -1, sizeof(memo)); - function dfs = [&](int pos, int pre, int ic, int ec) { - if (pos == m * n || (ic == 0 && ec == 0)) { - return 0; - } - if (memo[pos][pre][ic][ec] != -1) { - return memo[pos][pre][ic][ec]; - } - int ans = 0; - int up = pre / p; - int left = pos % n == 0 ? 0 : pre % 3; - for (int i = 0; i < 3; ++i) { - if ((i == 1 && ic == 0) || (i == 2 && ec == 0)) { - continue; - } - int cur = pre % p * 3 + i; - int a = h[up][i] + h[left][i]; - int b = dfs(pos + 1, cur, ic - (i == 1), ec - (i == 2)); - int c = i == 1 ? 120 : (i == 2 ? 40 : 0); - ans = max(ans, a + b + c); - } - return memo[pos][pre][ic][ec] = ans; - }; - return dfs(0, 0, introvertsCount, extrovertsCount); - } -}; -``` - -### **Go** - ```go func getMaxGridHappiness(m int, n int, introvertsCount int, extrovertsCount int) int { mx := int(math.Pow(3, float64(n))) @@ -486,64 +345,6 @@ func getMaxGridHappiness(m int, n int, introvertsCount int, extrovertsCount int) } ``` -```go -func getMaxGridHappiness(m int, n int, introvertsCount int, extrovertsCount int) int { - p := int(math.Pow(3, float64(n-1))) - h := [3][3]int{{0, 0, 0}, {0, -60, -10}, {0, -10, 40}} - memo := make([][][][]int, m*n) - for i := range memo { - memo[i] = make([][][]int, p*3) - for j := range memo[i] { - memo[i][j] = make([][]int, introvertsCount+1) - for k := range memo[i][j] { - memo[i][j][k] = make([]int, extrovertsCount+1) - for l := range memo[i][j][k] { - memo[i][j][k][l] = -1 - } - } - } - } - var dfs func(int, int, int, int) int - dfs = func(pos, pre, ic, ec int) int { - if pos == m*n || (ic == 0 && ec == 0) { - return 0 - } - if memo[pos][pre][ic][ec] != -1 { - return memo[pos][pre][ic][ec] - } - ans := 0 - up := pre / p - left := pre % 3 - if pos%n == 0 { - left = 0 - } - for i := 0; i < 3; i++ { - if (i == 1 && ic == 0) || (i == 2 && ec == 0) { - continue - } - cur := pre%p*3 + i - nic, nec := ic, ec - c := 0 - if i == 1 { - nic-- - c = 120 - } else if i == 2 { - nec-- - c = 40 - } - a := h[up][i] + h[left][i] - b := dfs(pos+1, cur, nic, nec) - ans = max(ans, a+b+c) - } - memo[pos][pre][ic][ec] = ans - return ans - } - return dfs(0, 0, introvertsCount, extrovertsCount) -} -``` - -### **TypeScript** - ```ts function getMaxGridHappiness( m: number, @@ -623,6 +424,193 @@ function getMaxGridHappiness( } ``` + + +### 方法二:轮廓线记忆化搜索 + +我们可以考虑搜索每个网格单元,每次搜索一个位置 $(i, j)$,我们记 $pos = i \times n + j$。那么它左边以及上边的相邻网格会影响到它们之间的幸福感贡献。 + +我们定义一个函数 $dfs(pos, pre, ic, ec)$,表示当前搜索到位置 $pos$,且此前的 $n$ 个网格单元的状态为 $pre$,内向的人还剩 $ic$ 个,外向的人还剩 $ec$ 个时,网格的最大幸福感。那么答案就是 $dfs(0, 0, introvertsCount, extrovertsCount)$。 + +函数 $dfs(pos, pre, ic, ec)$ 的计算过程如下: + +如果 $pos = m \times n$,表示已经处理完了所有的网格单元,那么返回 $0$; + +如果 $ic = 0$ 且 $ec = 0$,表示所有的人都已经分配完了,那么返回 $0$; + +否则,我们根据 $pre$ 算出当前网格单元的上边相邻网格单元的状态 $up = \frac{pre}{3^{n-1}}$,以及左边相邻网格单元的状态 $left = pre \bmod 3$(注意,如果 $pos$ 在第 $0$ 列,那么 $left = 0$)。 + +接下来,我们枚举当前网格单元的状态 $i$,其中 $i \in [0, 3)$。那么当前的 $n$ 个网格单元的状态为 $cur = pre \bmod 3^{n-1} \times 3 + i$,当前网格单元以及左边和上边的相邻网格单元的幸福感贡献为 $h[up][i]+h[left][i]$;而当前网格单元本身的幸福感取决于该位置是否分配人员,以及分配的人员是内向的还是外向的,如果是内向的,那么幸福感为 $120$,如果是外向的,那么幸福感为 $40$,否则幸福感为 $0$;然后,如果当前网格单元分配了人员,那么我们递归调用时需要更新 $ic$ 或 $ec$。累计这些幸福感,取最大值作为函数的返回值。 + +与方法一类似,我们也可以使用记忆化搜索的方法,避免重复计算。 + +时间复杂度 $O(3^{n+1} \times m \times n \times ic \times ec)$,空间复杂度 $O(3^n \times m \times n \times ic \times ec)$。其中 $ic$ 和 $ec$ 分别表示内向的人和外向的人的个数。 + + + +```python +class Solution: + def getMaxGridHappiness( + self, m: int, n: int, introvertsCount: int, extrovertsCount: int + ) -> int: + @cache + def dfs(pos: int, pre: int, ic: int, ec: int) -> int: + if pos == m * n or (ic == 0 and ec == 0): + return 0 + ans = 0 + up = pre // p + left = 0 if pos % n == 0 else pre % 3 + for i in range(3): + if (i == 1 and ic == 0) or (i == 2 and ec == 0): + continue + cur = pre % p * 3 + i + a = h[up][i] + h[left][i] + b = dfs(pos + 1, cur, ic - (i == 1), ec - (i == 2)) + c = 0 + if i == 1: + c = 120 + elif i == 2: + c = 40 + ans = max(ans, a + b + c) + return ans + + p = pow(3, n - 1) + h = [[0, 0, 0], [0, -60, -10], [0, -10, 40]] + return dfs(0, 0, introvertsCount, extrovertsCount) +``` + +```java +class Solution { + private int m; + private int n; + private int p; + private final int[][] h = {{0, 0, 0}, {0, -60, -10}, {0, -10, 40}}; + private Integer[][][][] memo; + + public int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { + this.m = m; + this.n = n; + p = (int) Math.pow(3, n - 1); + memo = new Integer[m * n][p * 3][introvertsCount + 1][extrovertsCount + 1]; + return dfs(0, 0, introvertsCount, extrovertsCount); + } + + private int dfs(int pos, int pre, int ic, int ec) { + if (pos == m * n || (ic == 0 && ec == 0)) { + return 0; + } + if (memo[pos][pre][ic][ec] != null) { + return memo[pos][pre][ic][ec]; + } + int ans = 0; + int up = pre / p; + int left = pos % n == 0 ? 0 : pre % 3; + for (int i = 0; i < 3; ++i) { + if (i == 1 && (ic == 0) || (i == 2 && ec == 0)) { + continue; + } + int cur = pre % p * 3 + i; + int a = h[up][i] + h[left][i]; + int b = dfs(pos + 1, cur, ic - (i == 1 ? 1 : 0), ec - (i == 2 ? 1 : 0)); + int c = i == 1 ? 120 : (i == 2 ? 40 : 0); + ans = Math.max(ans, a + b + c); + } + return memo[pos][pre][ic][ec] = ans; + } +} +``` + +```cpp +class Solution { +public: + int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { + int h[3][3] = {{0, 0, 0}, {0, -60, -10}, {0, -10, 40}}; + int p = pow(3, n - 1); + int memo[m * n][p * 3][introvertsCount + 1][extrovertsCount + 1]; + memset(memo, -1, sizeof(memo)); + function dfs = [&](int pos, int pre, int ic, int ec) { + if (pos == m * n || (ic == 0 && ec == 0)) { + return 0; + } + if (memo[pos][pre][ic][ec] != -1) { + return memo[pos][pre][ic][ec]; + } + int ans = 0; + int up = pre / p; + int left = pos % n == 0 ? 0 : pre % 3; + for (int i = 0; i < 3; ++i) { + if ((i == 1 && ic == 0) || (i == 2 && ec == 0)) { + continue; + } + int cur = pre % p * 3 + i; + int a = h[up][i] + h[left][i]; + int b = dfs(pos + 1, cur, ic - (i == 1), ec - (i == 2)); + int c = i == 1 ? 120 : (i == 2 ? 40 : 0); + ans = max(ans, a + b + c); + } + return memo[pos][pre][ic][ec] = ans; + }; + return dfs(0, 0, introvertsCount, extrovertsCount); + } +}; +``` + +```go +func getMaxGridHappiness(m int, n int, introvertsCount int, extrovertsCount int) int { + p := int(math.Pow(3, float64(n-1))) + h := [3][3]int{{0, 0, 0}, {0, -60, -10}, {0, -10, 40}} + memo := make([][][][]int, m*n) + for i := range memo { + memo[i] = make([][][]int, p*3) + for j := range memo[i] { + memo[i][j] = make([][]int, introvertsCount+1) + for k := range memo[i][j] { + memo[i][j][k] = make([]int, extrovertsCount+1) + for l := range memo[i][j][k] { + memo[i][j][k][l] = -1 + } + } + } + } + var dfs func(int, int, int, int) int + dfs = func(pos, pre, ic, ec int) int { + if pos == m*n || (ic == 0 && ec == 0) { + return 0 + } + if memo[pos][pre][ic][ec] != -1 { + return memo[pos][pre][ic][ec] + } + ans := 0 + up := pre / p + left := pre % 3 + if pos%n == 0 { + left = 0 + } + for i := 0; i < 3; i++ { + if (i == 1 && ic == 0) || (i == 2 && ec == 0) { + continue + } + cur := pre%p*3 + i + nic, nec := ic, ec + c := 0 + if i == 1 { + nic-- + c = 120 + } else if i == 2 { + nec-- + c = 40 + } + a := h[up][i] + h[left][i] + b := dfs(pos+1, cur, nic, nec) + ans = max(ans, a+b+c) + } + memo[pos][pre][ic][ec] = ans + return ans + } + return dfs(0, 0, introvertsCount, extrovertsCount) +} +``` + ```ts function getMaxGridHappiness( m: number, @@ -675,10 +663,6 @@ function getMaxGridHappiness( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1659.Maximize Grid Happiness/README_EN.md b/solution/1600-1699/1659.Maximize Grid Happiness/README_EN.md index b12fad6510172..515995694be43 100644 --- a/solution/1600-1699/1659.Maximize Grid Happiness/README_EN.md +++ b/solution/1600-1699/1659.Maximize Grid Happiness/README_EN.md @@ -63,9 +63,9 @@ The grid happiness is 90 + 80 + 90 = 260. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -111,39 +111,6 @@ class Solution: return dfs(0, 0, introvertsCount, extrovertsCount) ``` -```python -class Solution: - def getMaxGridHappiness( - self, m: int, n: int, introvertsCount: int, extrovertsCount: int - ) -> int: - @cache - def dfs(pos: int, pre: int, ic: int, ec: int) -> int: - if pos == m * n or (ic == 0 and ec == 0): - return 0 - ans = 0 - up = pre // p - left = 0 if pos % n == 0 else pre % 3 - for i in range(3): - if (i == 1 and ic == 0) or (i == 2 and ec == 0): - continue - cur = pre % p * 3 + i - a = h[up][i] + h[left][i] - b = dfs(pos + 1, cur, ic - (i == 1), ec - (i == 2)) - c = 0 - if i == 1: - c = 120 - elif i == 2: - c = 40 - ans = max(ans, a + b + c) - return ans - - p = pow(3, n - 1) - h = [[0, 0, 0], [0, -60, -10], [0, -10, 40]] - return dfs(0, 0, introvertsCount, extrovertsCount) -``` - -### **Java** - ```java class Solution { private int m; @@ -212,49 +179,6 @@ class Solution { } ``` -```java -class Solution { - private int m; - private int n; - private int p; - private final int[][] h = {{0, 0, 0}, {0, -60, -10}, {0, -10, 40}}; - private Integer[][][][] memo; - - public int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { - this.m = m; - this.n = n; - p = (int) Math.pow(3, n - 1); - memo = new Integer[m * n][p * 3][introvertsCount + 1][extrovertsCount + 1]; - return dfs(0, 0, introvertsCount, extrovertsCount); - } - - private int dfs(int pos, int pre, int ic, int ec) { - if (pos == m * n || (ic == 0 && ec == 0)) { - return 0; - } - if (memo[pos][pre][ic][ec] != null) { - return memo[pos][pre][ic][ec]; - } - int ans = 0; - int up = pre / p; - int left = pos % n == 0 ? 0 : pre % 3; - for (int i = 0; i < 3; ++i) { - if (i == 1 && (ic == 0) || (i == 2 && ec == 0)) { - continue; - } - int cur = pre % p * 3 + i; - int a = h[up][i] + h[left][i]; - int b = dfs(pos + 1, cur, ic - (i == 1 ? 1 : 0), ec - (i == 2 ? 1 : 0)); - int c = i == 1 ? 120 : (i == 2 ? 40 : 0); - ans = Math.max(ans, a + b + c); - } - return memo[pos][pre][ic][ec] = ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -318,43 +242,6 @@ public: }; ``` -```cpp -class Solution { -public: - int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { - int h[3][3] = {{0, 0, 0}, {0, -60, -10}, {0, -10, 40}}; - int p = pow(3, n - 1); - int memo[m * n][p * 3][introvertsCount + 1][extrovertsCount + 1]; - memset(memo, -1, sizeof(memo)); - function dfs = [&](int pos, int pre, int ic, int ec) { - if (pos == m * n || (ic == 0 && ec == 0)) { - return 0; - } - if (memo[pos][pre][ic][ec] != -1) { - return memo[pos][pre][ic][ec]; - } - int ans = 0; - int up = pre / p; - int left = pos % n == 0 ? 0 : pre % 3; - for (int i = 0; i < 3; ++i) { - if ((i == 1 && ic == 0) || (i == 2 && ec == 0)) { - continue; - } - int cur = pre % p * 3 + i; - int a = h[up][i] + h[left][i]; - int b = dfs(pos + 1, cur, ic - (i == 1), ec - (i == 2)); - int c = i == 1 ? 120 : (i == 2 ? 40 : 0); - ans = max(ans, a + b + c); - } - return memo[pos][pre][ic][ec] = ans; - }; - return dfs(0, 0, introvertsCount, extrovertsCount); - } -}; -``` - -### **Go** - ```go func getMaxGridHappiness(m int, n int, introvertsCount int, extrovertsCount int) int { mx := int(math.Pow(3, float64(n))) @@ -427,64 +314,6 @@ func getMaxGridHappiness(m int, n int, introvertsCount int, extrovertsCount int) } ``` -```go -func getMaxGridHappiness(m int, n int, introvertsCount int, extrovertsCount int) int { - p := int(math.Pow(3, float64(n-1))) - h := [3][3]int{{0, 0, 0}, {0, -60, -10}, {0, -10, 40}} - memo := make([][][][]int, m*n) - for i := range memo { - memo[i] = make([][][]int, p*3) - for j := range memo[i] { - memo[i][j] = make([][]int, introvertsCount+1) - for k := range memo[i][j] { - memo[i][j][k] = make([]int, extrovertsCount+1) - for l := range memo[i][j][k] { - memo[i][j][k][l] = -1 - } - } - } - } - var dfs func(int, int, int, int) int - dfs = func(pos, pre, ic, ec int) int { - if pos == m*n || (ic == 0 && ec == 0) { - return 0 - } - if memo[pos][pre][ic][ec] != -1 { - return memo[pos][pre][ic][ec] - } - ans := 0 - up := pre / p - left := pre % 3 - if pos%n == 0 { - left = 0 - } - for i := 0; i < 3; i++ { - if (i == 1 && ic == 0) || (i == 2 && ec == 0) { - continue - } - cur := pre%p*3 + i - nic, nec := ic, ec - c := 0 - if i == 1 { - nic-- - c = 120 - } else if i == 2 { - nec-- - c = 40 - } - a := h[up][i] + h[left][i] - b := dfs(pos+1, cur, nic, nec) - ans = max(ans, a+b+c) - } - memo[pos][pre][ic][ec] = ans - return ans - } - return dfs(0, 0, introvertsCount, extrovertsCount) -} -``` - -### **TypeScript** - ```ts function getMaxGridHappiness( m: number, @@ -564,6 +393,175 @@ function getMaxGridHappiness( } ``` + + +### Solution 2 + + + +```python +class Solution: + def getMaxGridHappiness( + self, m: int, n: int, introvertsCount: int, extrovertsCount: int + ) -> int: + @cache + def dfs(pos: int, pre: int, ic: int, ec: int) -> int: + if pos == m * n or (ic == 0 and ec == 0): + return 0 + ans = 0 + up = pre // p + left = 0 if pos % n == 0 else pre % 3 + for i in range(3): + if (i == 1 and ic == 0) or (i == 2 and ec == 0): + continue + cur = pre % p * 3 + i + a = h[up][i] + h[left][i] + b = dfs(pos + 1, cur, ic - (i == 1), ec - (i == 2)) + c = 0 + if i == 1: + c = 120 + elif i == 2: + c = 40 + ans = max(ans, a + b + c) + return ans + + p = pow(3, n - 1) + h = [[0, 0, 0], [0, -60, -10], [0, -10, 40]] + return dfs(0, 0, introvertsCount, extrovertsCount) +``` + +```java +class Solution { + private int m; + private int n; + private int p; + private final int[][] h = {{0, 0, 0}, {0, -60, -10}, {0, -10, 40}}; + private Integer[][][][] memo; + + public int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { + this.m = m; + this.n = n; + p = (int) Math.pow(3, n - 1); + memo = new Integer[m * n][p * 3][introvertsCount + 1][extrovertsCount + 1]; + return dfs(0, 0, introvertsCount, extrovertsCount); + } + + private int dfs(int pos, int pre, int ic, int ec) { + if (pos == m * n || (ic == 0 && ec == 0)) { + return 0; + } + if (memo[pos][pre][ic][ec] != null) { + return memo[pos][pre][ic][ec]; + } + int ans = 0; + int up = pre / p; + int left = pos % n == 0 ? 0 : pre % 3; + for (int i = 0; i < 3; ++i) { + if (i == 1 && (ic == 0) || (i == 2 && ec == 0)) { + continue; + } + int cur = pre % p * 3 + i; + int a = h[up][i] + h[left][i]; + int b = dfs(pos + 1, cur, ic - (i == 1 ? 1 : 0), ec - (i == 2 ? 1 : 0)); + int c = i == 1 ? 120 : (i == 2 ? 40 : 0); + ans = Math.max(ans, a + b + c); + } + return memo[pos][pre][ic][ec] = ans; + } +} +``` + +```cpp +class Solution { +public: + int getMaxGridHappiness(int m, int n, int introvertsCount, int extrovertsCount) { + int h[3][3] = {{0, 0, 0}, {0, -60, -10}, {0, -10, 40}}; + int p = pow(3, n - 1); + int memo[m * n][p * 3][introvertsCount + 1][extrovertsCount + 1]; + memset(memo, -1, sizeof(memo)); + function dfs = [&](int pos, int pre, int ic, int ec) { + if (pos == m * n || (ic == 0 && ec == 0)) { + return 0; + } + if (memo[pos][pre][ic][ec] != -1) { + return memo[pos][pre][ic][ec]; + } + int ans = 0; + int up = pre / p; + int left = pos % n == 0 ? 0 : pre % 3; + for (int i = 0; i < 3; ++i) { + if ((i == 1 && ic == 0) || (i == 2 && ec == 0)) { + continue; + } + int cur = pre % p * 3 + i; + int a = h[up][i] + h[left][i]; + int b = dfs(pos + 1, cur, ic - (i == 1), ec - (i == 2)); + int c = i == 1 ? 120 : (i == 2 ? 40 : 0); + ans = max(ans, a + b + c); + } + return memo[pos][pre][ic][ec] = ans; + }; + return dfs(0, 0, introvertsCount, extrovertsCount); + } +}; +``` + +```go +func getMaxGridHappiness(m int, n int, introvertsCount int, extrovertsCount int) int { + p := int(math.Pow(3, float64(n-1))) + h := [3][3]int{{0, 0, 0}, {0, -60, -10}, {0, -10, 40}} + memo := make([][][][]int, m*n) + for i := range memo { + memo[i] = make([][][]int, p*3) + for j := range memo[i] { + memo[i][j] = make([][]int, introvertsCount+1) + for k := range memo[i][j] { + memo[i][j][k] = make([]int, extrovertsCount+1) + for l := range memo[i][j][k] { + memo[i][j][k][l] = -1 + } + } + } + } + var dfs func(int, int, int, int) int + dfs = func(pos, pre, ic, ec int) int { + if pos == m*n || (ic == 0 && ec == 0) { + return 0 + } + if memo[pos][pre][ic][ec] != -1 { + return memo[pos][pre][ic][ec] + } + ans := 0 + up := pre / p + left := pre % 3 + if pos%n == 0 { + left = 0 + } + for i := 0; i < 3; i++ { + if (i == 1 && ic == 0) || (i == 2 && ec == 0) { + continue + } + cur := pre%p*3 + i + nic, nec := ic, ec + c := 0 + if i == 1 { + nic-- + c = 120 + } else if i == 2 { + nec-- + c = 40 + } + a := h[up][i] + h[left][i] + b := dfs(pos+1, cur, nic, nec) + ans = max(ans, a+b+c) + } + memo[pos][pre][ic][ec] = ans + return ans + } + return dfs(0, 0, introvertsCount, extrovertsCount) +} +``` + ```ts function getMaxGridHappiness( m: number, @@ -616,10 +614,6 @@ function getMaxGridHappiness( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1660.Correct a Binary Tree/README.md b/solution/1600-1699/1660.Correct a Binary Tree/README.md index 690602d68ae7c..2c38be97cd2db 100644 --- a/solution/1600-1699/1660.Correct a Binary Tree/README.md +++ b/solution/1600-1699/1660.Correct a Binary Tree/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们设计一个函数 $dfs(root)$,用于处理以 $root$ 为根的子树。如果 $root$ 为 $null$ 或者 $root.right$ 已经被访问过,说明 $root$ 为无效节点,返回 $null$。否则,递归处理 $root.right$ 和 $root.left$,并返回 $root$。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -97,10 +91,6 @@ class Solution: return dfs(root) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -168,8 +156,6 @@ public: }; ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -200,10 +186,6 @@ var correctBinaryTree = function (root) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1660.Correct a Binary Tree/README_EN.md b/solution/1600-1699/1660.Correct a Binary Tree/README_EN.md index 6a15153885077..bed4d93a46577 100644 --- a/solution/1600-1699/1660.Correct a Binary Tree/README_EN.md +++ b/solution/1600-1699/1660.Correct a Binary Tree/README_EN.md @@ -56,9 +56,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -81,8 +81,6 @@ class Solution: return dfs(root) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -118,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -150,8 +146,6 @@ public: }; ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -182,10 +176,6 @@ var correctBinaryTree = function (root) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1661.Average Time of Process per Machine/README.md b/solution/1600-1699/1661.Average Time of Process per Machine/README.md index e03cb256116b5..858a45a877928 100644 --- a/solution/1600-1699/1661.Average Time of Process per Machine/README.md +++ b/solution/1600-1699/1661.Average Time of Process per Machine/README.md @@ -77,9 +77,7 @@ Activity table: ## 解法 - - -**方法一:分组统计** +### 方法一:分组统计 我们可以根据 `machine_id` 分组,然后利用 `AVG` 函数计算每台机器上所有进程任务的平均耗时。由于机器上的每个进程任务都有一对开始时间戳和结束时间戳,完成一个进程任务的时间指进程的 `end` 时间戳 减去 `start` 时间戳,因此我们可以利用 `CASE WHEN` 或者 `IF` 函数来计算每个进程任务的耗时,最后再利用 `AVG` 函数计算每台机器上所有进程任务的平均耗时。 @@ -87,8 +85,6 @@ Activity table: -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -106,6 +102,12 @@ FROM Activity GROUP BY 1; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below SELECT @@ -116,3 +118,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1600-1699/1661.Average Time of Process per Machine/README_EN.md b/solution/1600-1699/1661.Average Time of Process per Machine/README_EN.md index e8d8931c169ff..b21d124b822b3 100644 --- a/solution/1600-1699/1661.Average Time of Process per Machine/README_EN.md +++ b/solution/1600-1699/1661.Average Time of Process per Machine/README_EN.md @@ -75,7 +75,7 @@ Machine 2's average time is ((4.512 - 4.100) + (5.000 - 2.500)) / 2 = 1.456 ## Solutions -**Solution 1: Grouping and Aggregation** +### Solution 1: Grouping and Aggregation We can group by `machine_id` and use the `AVG` function to calculate the average time consumption of all process tasks on each machine. Since each process task on the machine has a pair of start and end timestamps, the time consumption of each process task can be calculated by subtracting the `start` timestamp from the `end` timestamp. Therefore, we can use the `CASE WHEN` or `IF` function to calculate the time consumption of each process task, and then use the `AVG` function to calculate the average time consumption of all process tasks on each machine. @@ -83,8 +83,6 @@ Note that each machine has $2$ process tasks, so we need to multiply the calcula -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -102,6 +100,12 @@ FROM Activity GROUP BY 1; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below SELECT @@ -112,3 +116,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/README.md b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/README.md index 0653f81c8d79c..607809f3e3f46 100644 --- a/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/README.md +++ b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/README.md @@ -49,15 +49,84 @@ word2 表示的字符串为 "a" + "bc" -> "abc" ## 解法 - - -**方法一:字符串拼接** +### 方法一:字符串拼接 将两个数组中的字符串拼接成两个字符串,然后比较两个字符串是否相等。 时间复杂度 $O(m)$,空间复杂度 $O(m)$。其中 $m$ 为数组中字符串的总长度。 -**方法二:直接遍历** + + +```python +class Solution: + def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: + return ''.join(word1) == ''.join(word2) +``` + +```java +class Solution { + public boolean arrayStringsAreEqual(String[] word1, String[] word2) { + return String.join("", word1).equals(String.join("", word2)); + } +} +``` + +```cpp +class Solution { +public: + bool arrayStringsAreEqual(vector& word1, vector& word2) { + return reduce(word1.cbegin(), word1.cend()) == reduce(word2.cbegin(), word2.cend()); + } +}; +``` + +```go +func arrayStringsAreEqual(word1 []string, word2 []string) bool { + return strings.Join(word1, "") == strings.Join(word2, "") +} +``` + +```ts +function arrayStringsAreEqual(word1: string[], word2: string[]): boolean { + return word1.join('') === word2.join(''); +} +``` + +```rust +impl Solution { + pub fn array_strings_are_equal(word1: Vec, word2: Vec) -> bool { + word1.join("") == word2.join("") + } +} +``` + +```c +bool arrayStringsAreEqual(char** word1, int word1Size, char** word2, int word2Size) { + int i = 0; + int j = 0; + int x = 0; + int y = 0; + while (i < word1Size && j < word2Size) { + if (word1[i][x++] != word2[j][y++]) { + return 0; + } + + if (word1[i][x] == '\0') { + x = 0; + i++; + } + if (word2[j][y] == '\0') { + y = 0; + j++; + } + } + return i == word1Size && j == word2Size; +} +``` + + + +### 方法二:直接遍历 方法一中,我们是将两个数组中的字符串拼接成两个新的字符串,有额外的空间开销。我们也可以直接遍历两个数组,逐个字符比较。 @@ -71,16 +140,6 @@ word2 表示的字符串为 "a" + "bc" -> "abc" -### **Python3** - - - -```python -class Solution: - def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: - return ''.join(word1) == ''.join(word2) -``` - ```python class Solution: def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: @@ -96,18 +155,6 @@ class Solution: return i == len(word1) and j == len(word2) ``` -### **Java** - - - -```java -class Solution { - public boolean arrayStringsAreEqual(String[] word1, String[] word2) { - return String.join("", word1).equals(String.join("", word2)); - } -} -``` - ```java class Solution { public boolean arrayStringsAreEqual(String[] word1, String[] word2) { @@ -131,17 +178,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool arrayStringsAreEqual(vector& word1, vector& word2) { - return reduce(word1.cbegin(), word1.cend()) == reduce(word2.cbegin(), word2.cend()); - } -}; -``` - ```cpp class Solution { public: @@ -157,14 +193,6 @@ public: }; ``` -### **Go** - -```go -func arrayStringsAreEqual(word1 []string, word2 []string) bool { - return strings.Join(word1, "") == strings.Join(word2, "") -} -``` - ```go func arrayStringsAreEqual(word1 []string, word2 []string) bool { var i, j, x, y int @@ -184,40 +212,6 @@ func arrayStringsAreEqual(word1 []string, word2 []string) bool { } ``` -### **C** - -```c -bool arrayStringsAreEqual(char** word1, int word1Size, char** word2, int word2Size) { - int i = 0; - int j = 0; - int x = 0; - int y = 0; - while (i < word1Size && j < word2Size) { - if (word1[i][x++] != word2[j][y++]) { - return 0; - } - - if (word1[i][x] == '\0') { - x = 0; - i++; - } - if (word2[j][y] == '\0') { - y = 0; - j++; - } - } - return i == word1Size && j == word2Size; -} -``` - -### **TypeScript** - -```ts -function arrayStringsAreEqual(word1: string[], word2: string[]): boolean { - return word1.join('') === word2.join(''); -} -``` - ```ts function arrayStringsAreEqual(word1: string[], word2: string[]): boolean { let [i, j, x, y] = [0, 0, 0, 0]; @@ -238,16 +232,6 @@ function arrayStringsAreEqual(word1: string[], word2: string[]): boolean { } ``` -### **Rust** - -```rust -impl Solution { - pub fn array_strings_are_equal(word1: Vec, word2: Vec) -> bool { - word1.join("") == word2.join("") - } -} -``` - ```rust impl Solution { pub fn array_strings_are_equal(word1: Vec, word2: Vec) -> bool { @@ -273,10 +257,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/README_EN.md b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/README_EN.md index 15b2815d42062..db5222a0652dd 100644 --- a/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/README_EN.md +++ b/solution/1600-1699/1662.Check If Two String Arrays are Equivalent/README_EN.md @@ -45,9 +45,9 @@ The strings are the same, so return true. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,6 +55,73 @@ class Solution: return ''.join(word1) == ''.join(word2) ``` +```java +class Solution { + public boolean arrayStringsAreEqual(String[] word1, String[] word2) { + return String.join("", word1).equals(String.join("", word2)); + } +} +``` + +```cpp +class Solution { +public: + bool arrayStringsAreEqual(vector& word1, vector& word2) { + return reduce(word1.cbegin(), word1.cend()) == reduce(word2.cbegin(), word2.cend()); + } +}; +``` + +```go +func arrayStringsAreEqual(word1 []string, word2 []string) bool { + return strings.Join(word1, "") == strings.Join(word2, "") +} +``` + +```ts +function arrayStringsAreEqual(word1: string[], word2: string[]): boolean { + return word1.join('') === word2.join(''); +} +``` + +```rust +impl Solution { + pub fn array_strings_are_equal(word1: Vec, word2: Vec) -> bool { + word1.join("") == word2.join("") + } +} +``` + +```c +bool arrayStringsAreEqual(char** word1, int word1Size, char** word2, int word2Size) { + int i = 0; + int j = 0; + int x = 0; + int y = 0; + while (i < word1Size && j < word2Size) { + if (word1[i][x++] != word2[j][y++]) { + return 0; + } + + if (word1[i][x] == '\0') { + x = 0; + i++; + } + if (word2[j][y] == '\0') { + y = 0; + j++; + } + } + return i == word1Size && j == word2Size; +} +``` + + + +### Solution 2 + + + ```python class Solution: def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: @@ -70,16 +137,6 @@ class Solution: return i == len(word1) and j == len(word2) ``` -### **Java** - -```java -class Solution { - public boolean arrayStringsAreEqual(String[] word1, String[] word2) { - return String.join("", word1).equals(String.join("", word2)); - } -} -``` - ```java class Solution { public boolean arrayStringsAreEqual(String[] word1, String[] word2) { @@ -103,17 +160,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool arrayStringsAreEqual(vector& word1, vector& word2) { - return reduce(word1.cbegin(), word1.cend()) == reduce(word2.cbegin(), word2.cend()); - } -}; -``` - ```cpp class Solution { public: @@ -129,14 +175,6 @@ public: }; ``` -### **Go** - -```go -func arrayStringsAreEqual(word1 []string, word2 []string) bool { - return strings.Join(word1, "") == strings.Join(word2, "") -} -``` - ```go func arrayStringsAreEqual(word1 []string, word2 []string) bool { var i, j, x, y int @@ -156,40 +194,6 @@ func arrayStringsAreEqual(word1 []string, word2 []string) bool { } ``` -### **C** - -```c -bool arrayStringsAreEqual(char** word1, int word1Size, char** word2, int word2Size) { - int i = 0; - int j = 0; - int x = 0; - int y = 0; - while (i < word1Size && j < word2Size) { - if (word1[i][x++] != word2[j][y++]) { - return 0; - } - - if (word1[i][x] == '\0') { - x = 0; - i++; - } - if (word2[j][y] == '\0') { - y = 0; - j++; - } - } - return i == word1Size && j == word2Size; -} -``` - -### **TypeScript** - -```ts -function arrayStringsAreEqual(word1: string[], word2: string[]): boolean { - return word1.join('') === word2.join(''); -} -``` - ```ts function arrayStringsAreEqual(word1: string[], word2: string[]): boolean { let [i, j, x, y] = [0, 0, 0, 0]; @@ -210,16 +214,6 @@ function arrayStringsAreEqual(word1: string[], word2: string[]): boolean { } ``` -### **Rust** - -```rust -impl Solution { - pub fn array_strings_are_equal(word1: Vec, word2: Vec) -> bool { - word1.join("") == word2.join("") - } -} -``` - ```rust impl Solution { pub fn array_strings_are_equal(word1: Vec, word2: Vec) -> bool { @@ -245,10 +239,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1663.Smallest String With A Given Numeric Value/README.md b/solution/1600-1699/1663.Smallest String With A Given Numeric Value/README.md index 3e9c99f04021f..978a40b2d1443 100644 --- a/solution/1600-1699/1663.Smallest String With A Given Numeric Value/README.md +++ b/solution/1600-1699/1663.Smallest String With A Given Numeric Value/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们先将字符串的每个字符都初始化为 `'a'`,此时剩余的数值为 $d=k-n$。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def getSmallestString(self, n: int, k: int) -> str: @@ -75,10 +69,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String getSmallestString(int n, int k) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +99,6 @@ public: }; ``` -### **Go** - ```go func getSmallestString(n int, k int) string { ans := make([]byte, n) @@ -128,10 +114,6 @@ func getSmallestString(n int, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1663.Smallest String With A Given Numeric Value/README_EN.md b/solution/1600-1699/1663.Smallest String With A Given Numeric Value/README_EN.md index 8c7f7f5321601..22023fa633e0b 100644 --- a/solution/1600-1699/1663.Smallest String With A Given Numeric Value/README_EN.md +++ b/solution/1600-1699/1663.Smallest String With A Given Numeric Value/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String getSmallestString(int n, int k) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,8 +85,6 @@ public: }; ``` -### **Go** - ```go func getSmallestString(n int, k int) string { ans := make([]byte, n) @@ -106,10 +100,6 @@ func getSmallestString(n int, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1664.Ways to Make a Fair Array/README.md b/solution/1600-1699/1664.Ways to Make a Fair Array/README.md index 6a8bd7fd1d5d1..86f9acace0fa3 100644 --- a/solution/1600-1699/1664.Ways to Make a Fair Array/README.md +++ b/solution/1600-1699/1664.Ways to Make a Fair Array/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:枚举 + 前缀和** +### 方法一:枚举 + 前缀和 我们先预处理得到数组 `nums` 的偶数下标元素之和 $s_1$ 以及奇数下标元素之和 $s_2$。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def waysToMakeFair(self, nums: List[int]) -> int: @@ -99,10 +93,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int waysToMakeFair(int[] nums) { @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +140,6 @@ public: }; ``` -### **Go** - ```go func waysToMakeFair(nums []int) (ans int) { var s1, s2, t1, t2 int @@ -181,8 +167,6 @@ func waysToMakeFair(nums []int) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -210,10 +194,6 @@ var waysToMakeFair = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1664.Ways to Make a Fair Array/README_EN.md b/solution/1600-1699/1664.Ways to Make a Fair Array/README_EN.md index 2f2563a75cfd7..60811a451fc15 100644 --- a/solution/1600-1699/1664.Ways to Make a Fair Array/README_EN.md +++ b/solution/1600-1699/1664.Ways to Make a Fair Array/README_EN.md @@ -58,9 +58,9 @@ There is 1 index that you can remove to make nums fair. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int waysToMakeFair(int[] nums) { @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +122,6 @@ public: }; ``` -### **Go** - ```go func waysToMakeFair(nums []int) (ans int) { var s1, s2, t1, t2 int @@ -155,8 +149,6 @@ func waysToMakeFair(nums []int) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -184,10 +176,6 @@ var waysToMakeFair = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1665.Minimum Initial Energy to Finish Tasks/README.md b/solution/1600-1699/1665.Minimum Initial Energy to Finish Tasks/README.md index d36e4e8be8c5a..dc4d63aa4274c 100644 --- a/solution/1600-1699/1665.Minimum Initial Energy to Finish Tasks/README.md +++ b/solution/1600-1699/1665.Minimum Initial Energy to Finish Tasks/README.md @@ -69,9 +69,7 @@ ## 解法 - - -**方法一:贪心 + 自定义排序** +### 方法一:贪心 + 自定义排序 我们假设任务数为 $n$,初始能量值为 $E$,考虑完成最后一个任务,这需要我们完成前 $n-1$ 个任务后,剩余的能量值不小于完成最后一个任务需要达到的能量值 $m_n$,即: @@ -99,10 +97,6 @@ $$ -### **Python3** - - - ```python class Solution: def minimumEffort(self, tasks: List[List[int]]) -> int: @@ -115,10 +109,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumEffort(int[][] tasks) { @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func minimumEffort(tasks [][]int) (ans int) { sort.Slice(tasks, func(i, j int) bool { return tasks[i][0]-tasks[i][1] < tasks[j][0]-tasks[j][1] }) @@ -176,8 +162,6 @@ func minimumEffort(tasks [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumEffort(tasks: number[][]): number { tasks.sort((a, b) => a[0] - a[1] - (b[0] - b[1])); @@ -194,10 +178,6 @@ function minimumEffort(tasks: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1665.Minimum Initial Energy to Finish Tasks/README_EN.md b/solution/1600-1699/1665.Minimum Initial Energy to Finish Tasks/README_EN.md index 611d5c7121d41..c01cac8cef66a 100644 --- a/solution/1600-1699/1665.Minimum Initial Energy to Finish Tasks/README_EN.md +++ b/solution/1600-1699/1665.Minimum Initial Energy to Finish Tasks/README_EN.md @@ -68,9 +68,9 @@ Starting with 27 energy, we finish the tasks in the following order: ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumEffort(int[][] tasks) { @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +121,6 @@ public: }; ``` -### **Go** - ```go func minimumEffort(tasks [][]int) (ans int) { sort.Slice(tasks, func(i, j int) bool { return tasks[i][0]-tasks[i][1] < tasks[j][0]-tasks[j][1] }) @@ -143,8 +137,6 @@ func minimumEffort(tasks [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumEffort(tasks: number[][]): number { tasks.sort((a, b) => a[0] - a[1] - (b[0] - b[1])); @@ -161,10 +153,6 @@ function minimumEffort(tasks: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1666.Change the Root of a Binary Tree/README.md b/solution/1600-1699/1666.Change the Root of a Binary Tree/README.md index f2c258d7134fd..09eb2df8be9cd 100644 --- a/solution/1600-1699/1666.Change the Root of a Binary Tree/README.md +++ b/solution/1600-1699/1666.Change the Root of a Binary Tree/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:自底向上模拟** +### 方法一:自底向上模拟 从叶节点 `leaf` 开始,向上模拟翻转操作。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python """ # Definition for a Node. @@ -92,10 +86,6 @@ class Solution: return leaf ``` -### **Java** - - - ```java /* // Definition for a Node. @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node-> @@ -172,46 +160,6 @@ public: }; ``` -### **C#** - -```cs -/* -// Definition for a Node. -public class Node { - public int val; - public Node left; - public Node right; - public Node parent; -} -*/ - -public class Solution { - public Node FlipBinaryTree(Node root, Node leaf) { - Node cur = leaf; - Node p = cur.parent; - while (cur != root) { - Node gp = p.parent; - if (cur.left != null) { - cur.right = cur.left; - } - cur.left = p; - p.parent = cur; - if (p.left == cur) { - p.left = null; - } else if (p.right == cur) { - p.right = null; - } - cur = p; - p = gp; - } - leaf.parent = null; - return leaf; - } -} -``` - -### **JavaScript** - ```js /** * // Definition for a Node. @@ -250,10 +198,42 @@ var flipBinaryTree = function (root, leaf) { }; ``` -### **...** - -``` +```cs +/* +// Definition for a Node. +public class Node { + public int val; + public Node left; + public Node right; + public Node parent; +} +*/ +public class Solution { + public Node FlipBinaryTree(Node root, Node leaf) { + Node cur = leaf; + Node p = cur.parent; + while (cur != root) { + Node gp = p.parent; + if (cur.left != null) { + cur.right = cur.left; + } + cur.left = p; + p.parent = cur; + if (p.left == cur) { + p.left = null; + } else if (p.right == cur) { + p.right = null; + } + cur = p; + p = gp; + } + leaf.parent = null; + return leaf; + } +} ``` + + diff --git a/solution/1600-1699/1666.Change the Root of a Binary Tree/README_EN.md b/solution/1600-1699/1666.Change the Root of a Binary Tree/README_EN.md index bf3d586188601..89b0c2d0a6d52 100644 --- a/solution/1600-1699/1666.Change the Root of a Binary Tree/README_EN.md +++ b/solution/1600-1699/1666.Change the Root of a Binary Tree/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python """ @@ -80,8 +80,6 @@ class Solution: return leaf ``` -### **Java** - ```java /* // Definition for a Node. @@ -118,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp /* // Definition for a Node-> @@ -158,46 +154,6 @@ public: }; ``` -### **C#** - -```cs -/* -// Definition for a Node. -public class Node { - public int val; - public Node left; - public Node right; - public Node parent; -} -*/ - -public class Solution { - public Node FlipBinaryTree(Node root, Node leaf) { - Node cur = leaf; - Node p = cur.parent; - while (cur != root) { - Node gp = p.parent; - if (cur.left != null) { - cur.right = cur.left; - } - cur.left = p; - p.parent = cur; - if (p.left == cur) { - p.left = null; - } else if (p.right == cur) { - p.right = null; - } - cur = p; - p = gp; - } - leaf.parent = null; - return leaf; - } -} -``` - -### **JavaScript** - ```js /** * // Definition for a Node. @@ -236,10 +192,42 @@ var flipBinaryTree = function (root, leaf) { }; ``` -### **...** - -``` +```cs +/* +// Definition for a Node. +public class Node { + public int val; + public Node left; + public Node right; + public Node parent; +} +*/ +public class Solution { + public Node FlipBinaryTree(Node root, Node leaf) { + Node cur = leaf; + Node p = cur.parent; + while (cur != root) { + Node gp = p.parent; + if (cur.left != null) { + cur.right = cur.left; + } + cur.left = p; + p.parent = cur; + if (p.left == cur) { + p.left = null; + } else if (p.right == cur) { + p.right = null; + } + cur = p; + p = gp; + } + leaf.parent = null; + return leaf; + } +} ``` + + diff --git a/solution/1600-1699/1667.Fix Names in a Table/README.md b/solution/1600-1699/1667.Fix Names in a Table/README.md index abe01174d8fa8..0ce150d151c88 100644 --- a/solution/1600-1699/1667.Fix Names in a Table/README.md +++ b/solution/1600-1699/1667.Fix Names in a Table/README.md @@ -50,14 +50,10 @@ Users table: ## 解法 - +### 方法一 -### **SQL** - -MySQL - ```sql SELECT user_id, @@ -68,7 +64,11 @@ ORDER BY user_id; ``` -SQL Server + + +### 方法二 + + ```sql SELECT @@ -84,3 +84,5 @@ ORDER BY ``` + + diff --git a/solution/1600-1699/1667.Fix Names in a Table/README_EN.md b/solution/1600-1699/1667.Fix Names in a Table/README_EN.md index 0952eaf205ec2..cc9fdb7e079bd 100644 --- a/solution/1600-1699/1667.Fix Names in a Table/README_EN.md +++ b/solution/1600-1699/1667.Fix Names in a Table/README_EN.md @@ -48,11 +48,9 @@ Users table: ## Solutions - - -### **SQL** +### Solution 1 -MySQL + ```sql SELECT @@ -64,7 +62,11 @@ ORDER BY user_id; ``` -SQL Server + + +### Solution 2 + + ```sql SELECT @@ -80,3 +82,5 @@ ORDER BY ``` + + diff --git a/solution/1600-1699/1668.Maximum Repeating Substring/README.md b/solution/1600-1699/1668.Maximum Repeating Substring/README.md index dc6e9d8a17864..5c600f27bccf9 100644 --- a/solution/1600-1699/1668.Maximum Repeating Substring/README.md +++ b/solution/1600-1699/1668.Maximum Repeating Substring/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:直接枚举** +### 方法一:直接枚举 注意到字符串长度不超过 $100$,我们直接从大到小枚举 `word` 的重复次数 $k$,判断 `word` 重复该次数后是否是 `sequence` 的子串,是则直接返回当前的重复次数 $k$。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def maxRepeating(self, sequence: str, word: str) -> int: @@ -70,10 +64,6 @@ class Solution: return k ``` -### **Java** - - - ```java class Solution { public int maxRepeating(String sequence, String word) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +96,6 @@ public: }; ``` -### **Go** - ```go func maxRepeating(sequence string, word string) int { for k := len(sequence) / len(word); k > 0; k-- { @@ -121,34 +107,6 @@ func maxRepeating(sequence string, word string) int { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int findWord(int i, char* sequence, char* word) { - int n = strlen(word); - for (int j = 0; j < n; j++) { - if (sequence[j + i] != word[j]) { - return 0; - } - } - return 1 + findWord(i + n, sequence, word); -} - -int maxRepeating(char* sequence, char* word) { - int n = strlen(sequence); - int m = strlen(word); - int ans = 0; - for (int i = 0; i <= n - m; i++) { - ans = max(ans, findWord(i, sequence, word)); - } - return ans; -} -``` - -### **TypeScript** - ```ts function maxRepeating(sequence: string, word: string): number { let n = sequence.length; @@ -162,8 +120,6 @@ function maxRepeating(sequence: string, word: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_repeating(sequence: String, word: String) -> i32 { @@ -184,10 +140,30 @@ impl Solution { } ``` -### **...** +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) -``` +int findWord(int i, char* sequence, char* word) { + int n = strlen(word); + for (int j = 0; j < n; j++) { + if (sequence[j + i] != word[j]) { + return 0; + } + } + return 1 + findWord(i + n, sequence, word); +} +int maxRepeating(char* sequence, char* word) { + int n = strlen(sequence); + int m = strlen(word); + int ans = 0; + for (int i = 0; i <= n - m; i++) { + ans = max(ans, findWord(i, sequence, word)); + } + return ans; +} ``` + + diff --git a/solution/1600-1699/1668.Maximum Repeating Substring/README_EN.md b/solution/1600-1699/1668.Maximum Repeating Substring/README_EN.md index fc42103235dca..ffab869333f89 100644 --- a/solution/1600-1699/1668.Maximum Repeating Substring/README_EN.md +++ b/solution/1600-1699/1668.Maximum Repeating Substring/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return k ``` -### **Java** - ```java class Solution { public int maxRepeating(String sequence, String word) { @@ -71,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -81,6 +77,7 @@ public: string t = word; int x = sequence.size() / word.size(); for (int k = 1; k <= x; ++k) { + // C++ 这里从小到大枚举重复值 if (sequence.find(t) != string::npos) { ans = k; } @@ -91,8 +88,6 @@ public: }; ``` -### **Go** - ```go func maxRepeating(sequence string, word string) int { for k := len(sequence) / len(word); k > 0; k-- { @@ -104,34 +99,6 @@ func maxRepeating(sequence string, word string) int { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int findWord(int i, char* sequence, char* word) { - int n = strlen(word); - for (int j = 0; j < n; j++) { - if (sequence[j + i] != word[j]) { - return 0; - } - } - return 1 + findWord(i + n, sequence, word); -} - -int maxRepeating(char* sequence, char* word) { - int n = strlen(sequence); - int m = strlen(word); - int ans = 0; - for (int i = 0; i <= n - m; i++) { - ans = max(ans, findWord(i, sequence, word)); - } - return ans; -} -``` - -### **TypeScript** - ```ts function maxRepeating(sequence: string, word: string): number { let n = sequence.length; @@ -145,8 +112,6 @@ function maxRepeating(sequence: string, word: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_repeating(sequence: String, word: String) -> i32 { @@ -167,10 +132,30 @@ impl Solution { } ``` -### **...** +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) -``` +int findWord(int i, char* sequence, char* word) { + int n = strlen(word); + for (int j = 0; j < n; j++) { + if (sequence[j + i] != word[j]) { + return 0; + } + } + return 1 + findWord(i + n, sequence, word); +} +int maxRepeating(char* sequence, char* word) { + int n = strlen(sequence); + int m = strlen(word); + int ans = 0; + for (int i = 0; i <= n - m; i++) { + ans = max(ans, findWord(i, sequence, word)); + } + return ans; +} ``` + + diff --git a/solution/1600-1699/1669.Merge In Between Linked Lists/README.md b/solution/1600-1699/1669.Merge In Between Linked Lists/README.md index b82e8556d1b06..b59ac0b104f9c 100644 --- a/solution/1600-1699/1669.Merge In Between Linked Lists/README.md +++ b/solution/1600-1699/1669.Merge In Between Linked Lists/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 直接模拟题目中的操作即可。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -87,10 +81,6 @@ class Solution: return list1 ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -184,8 +170,6 @@ func mergeInBetween(list1 *ListNode, a int, b int, list2 *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -223,8 +207,6 @@ function mergeInBetween( } ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -257,10 +239,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1669.Merge In Between Linked Lists/README_EN.md b/solution/1600-1699/1669.Merge In Between Linked Lists/README_EN.md index 7aca79e22048d..a0c26cf3702b7 100644 --- a/solution/1600-1699/1669.Merge In Between Linked Lists/README_EN.md +++ b/solution/1600-1699/1669.Merge In Between Linked Lists/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -67,8 +67,6 @@ class Solution: return list1 ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -134,8 +130,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -162,8 +156,6 @@ func mergeInBetween(list1 *ListNode, a int, b int, list2 *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -201,8 +193,6 @@ function mergeInBetween( } ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -235,10 +225,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1670.Design Front Middle Back Queue/README.md b/solution/1600-1699/1670.Design Front Middle Back Queue/README.md index 5e9a9da09aac5..733fd7add9640 100644 --- a/solution/1600-1699/1670.Design Front Middle Back Queue/README.md +++ b/solution/1600-1699/1670.Design Front Middle Back Queue/README.md @@ -62,9 +62,7 @@ q.popFront(); // 返回 -1 -> [] (队列为空) ## 解法 - - -**方法一:两个双端队列** +### 方法一:两个双端队列 我们用两个双端队列,其中 $q_1$ 存储前半部分,而 $q_2$ 存储后半部分。每次由 `rebalance` 函数来维护两个队列的平衡性,即保持 $q_2$ 的长度大于等于 $q_1$ 的长度,且长度之差不超过 $1$。 @@ -80,10 +78,6 @@ q.popFront(); // 返回 -1 -> [] (队列为空) -### **Python3** - - - ```python class FrontMiddleBackQueue: def __init__(self): @@ -146,10 +140,6 @@ class FrontMiddleBackQueue: # param_6 = obj.popBack() ``` -### **Java** - - - ```java class FrontMiddleBackQueue { private Deque q1 = new ArrayDeque<>(); @@ -222,8 +212,6 @@ class FrontMiddleBackQueue { */ ``` -### **C++** - ```cpp class FrontMiddleBackQueue { public: @@ -309,8 +297,6 @@ private: */ ``` -### **Go** - ```go type FrontMiddleBackQueue struct { q1, q2 Deque @@ -451,8 +437,6 @@ func (q Deque) Get(i int) int { */ ``` -### **TypeScript** - ```ts class FrontMiddleBackQueue { private q1: Deque; @@ -624,8 +608,6 @@ class Deque { */ ``` -### **JavaScript** - ```js class FrontMiddleBackQueue { constructor() { @@ -786,10 +768,6 @@ class Deque { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1670.Design Front Middle Back Queue/README_EN.md b/solution/1600-1699/1670.Design Front Middle Back Queue/README_EN.md index 29233c1f9a2bc..cd766c7ba682c 100644 --- a/solution/1600-1699/1670.Design Front Middle Back Queue/README_EN.md +++ b/solution/1600-1699/1670.Design Front Middle Back Queue/README_EN.md @@ -58,7 +58,7 @@ q.popFront(); // return -1 -> [] (The queue is empty) ## Solutions -**Solution 1: Two Deques** +### Solution 1: Two Deques We use two deques, where $q_1$ stores the first half, and $q_2$ stores the second half. The `rebalance` function is used to maintain the balance between the two queues, i.e., keeping the length of $q_2$ greater than or equal to the length of $q_1$, and the difference in length does not exceed $1$. @@ -74,8 +74,6 @@ The time complexity of the above operations is $O(1)$, and the space complexity -### **Python3** - ```python class FrontMiddleBackQueue: def __init__(self): @@ -138,8 +136,6 @@ class FrontMiddleBackQueue: # param_6 = obj.popBack() ``` -### **Java** - ```java class FrontMiddleBackQueue { private Deque q1 = new ArrayDeque<>(); @@ -212,8 +208,6 @@ class FrontMiddleBackQueue { */ ``` -### **C++** - ```cpp class FrontMiddleBackQueue { public: @@ -299,8 +293,6 @@ private: */ ``` -### **Go** - ```go type FrontMiddleBackQueue struct { q1, q2 Deque @@ -441,8 +433,6 @@ func (q Deque) Get(i int) int { */ ``` -### **TypeScript** - ```ts class FrontMiddleBackQueue { private q1: Deque; @@ -614,8 +604,6 @@ class Deque { */ ``` -### **JavaScript** - ```js class FrontMiddleBackQueue { constructor() { @@ -776,10 +764,6 @@ class Deque { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1671.Minimum Number of Removals to Make Mountain Array/README.md b/solution/1600-1699/1671.Minimum Number of Removals to Make Mountain Array/README.md index efe07d5b8af3e..1b7fb91640cd1 100644 --- a/solution/1600-1699/1671.Minimum Number of Removals to Make Mountain Array/README.md +++ b/solution/1600-1699/1671.Minimum Number of Removals to Make Mountain Array/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 本题可以转化为求最长上升子序列和最长下降子序列。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def minimumMountainRemovals(self, nums: List[int]) -> int: @@ -85,10 +79,6 @@ class Solution: return n - max(a + b - 1 for a, b in zip(left, right) if a > 1 and b > 1) ``` -### **Java** - - - ```java class Solution { public int minimumMountainRemovals(int[] nums) { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func minimumMountainRemovals(nums []int) int { n := len(nums) @@ -188,8 +174,6 @@ func minimumMountainRemovals(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumMountainRemovals(nums: number[]): number { const n = nums.length; @@ -219,8 +203,6 @@ function minimumMountainRemovals(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn minimum_mountain_removals(nums: Vec) -> i32 { @@ -254,10 +236,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1671.Minimum Number of Removals to Make Mountain Array/README_EN.md b/solution/1600-1699/1671.Minimum Number of Removals to Make Mountain Array/README_EN.md index cac1ba743c46a..e94277c6830c8 100644 --- a/solution/1600-1699/1671.Minimum Number of Removals to Make Mountain Array/README_EN.md +++ b/solution/1600-1699/1671.Minimum Number of Removals to Make Mountain Array/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming This problem can be transformed into finding the longest increasing subsequence and the longest decreasing subsequence. @@ -58,8 +58,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ i -### **Python3** - ```python class Solution: def minimumMountainRemovals(self, nums: List[int]) -> int: @@ -77,8 +75,6 @@ class Solution: return n - max(a + b - 1 for a, b in zip(left, right) if a > 1 and b > 1) ``` -### **Java** - ```java class Solution { public int minimumMountainRemovals(int[] nums) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +139,6 @@ public: }; ``` -### **Go** - ```go func minimumMountainRemovals(nums []int) int { n := len(nums) @@ -178,8 +170,6 @@ func minimumMountainRemovals(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumMountainRemovals(nums: number[]): number { const n = nums.length; @@ -209,8 +199,6 @@ function minimumMountainRemovals(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn minimum_mountain_removals(nums: Vec) -> i32 { @@ -244,10 +232,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1672.Richest Customer Wealth/README.md b/solution/1600-1699/1672.Richest Customer Wealth/README.md index f8bfac40e4606..326c639cc9336 100644 --- a/solution/1600-1699/1672.Richest Customer Wealth/README.md +++ b/solution/1600-1699/1672.Richest Customer Wealth/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:求和** +### 方法一:求和 遍历 `accounts`,求出每一行的和,然后求出最大值。 @@ -61,20 +59,12 @@ -### **Python3** - - - ```python class Solution: def maximumWealth(self, accounts: List[List[int]]) -> int: return max(sum(v) for v in accounts) ``` -### **Java** - - - ```java class Solution { public int maximumWealth(int[][] accounts) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func maximumWealth(accounts [][]int) int { ans := 0 @@ -125,8 +111,6 @@ func maximumWealth(accounts [][]int) int { } ``` -### **TypeScript** - ```ts function maximumWealth(accounts: number[][]): number { return accounts.reduce( @@ -140,8 +124,6 @@ function maximumWealth(accounts: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn maximum_wealth(accounts: Vec>) -> i32 { @@ -154,7 +136,27 @@ impl Solution { } ``` -### **C** +```php +class Solution { + /** + * @param Integer[][] $accounts + * @return Integer + */ + function maximumWealth($accounts) { + $rs = 0; + for ($i = 0; $i < count($accounts); $i++) { + $sum = 0; + for ($j = 0; $j < count($accounts[$i]); $j++) { + $sum += $accounts[$i][$j]; + } + if ($sum > $rs) { + $rs = $sum; + } + } + return $rs; + } +} +``` ```c #define max(a, b) (((a) > (b)) ? (a) : (b)) @@ -172,8 +174,6 @@ int maximumWealth(int** accounts, int accountsSize, int* accountsColSize) { } ``` -### **Kotlin** - ```kotlin class Solution { fun maximumWealth(accounts: Array): Int { @@ -189,34 +189,6 @@ class Solution { } ``` -### **PHP** - -```php -class Solution { - /** - * @param Integer[][] $accounts - * @return Integer - */ - function maximumWealth($accounts) { - $rs = 0; - for ($i = 0; $i < count($accounts); $i++) { - $sum = 0; - for ($j = 0; $j < count($accounts[$i]); $j++) { - $sum += $accounts[$i][$j]; - } - if ($sum > $rs) { - $rs = $sum; - } - } - return $rs; - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1672.Richest Customer Wealth/README_EN.md b/solution/1600-1699/1672.Richest Customer Wealth/README_EN.md index 82b328587e1fb..958520fb8a274 100644 --- a/solution/1600-1699/1672.Richest Customer Wealth/README_EN.md +++ b/solution/1600-1699/1672.Richest Customer Wealth/README_EN.md @@ -50,9 +50,9 @@ The 2nd customer is the richest with a wealth of 10. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return max(sum(v) for v in accounts) ``` -### **Java** - ```java class Solution { public int maximumWealth(int[][] accounts) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +90,6 @@ public: }; ``` -### **Go** - ```go func maximumWealth(accounts [][]int) int { ans := 0 @@ -112,8 +106,6 @@ func maximumWealth(accounts [][]int) int { } ``` -### **TypeScript** - ```ts function maximumWealth(accounts: number[][]): number { return accounts.reduce( @@ -127,8 +119,6 @@ function maximumWealth(accounts: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn maximum_wealth(accounts: Vec>) -> i32 { @@ -141,7 +131,27 @@ impl Solution { } ``` -### **C** +```php +class Solution { + /** + * @param Integer[][] $accounts + * @return Integer + */ + function maximumWealth($accounts) { + $rs = 0; + for ($i = 0; $i < count($accounts); $i++) { + $sum = 0; + for ($j = 0; $j < count($accounts[$i]); $j++) { + $sum += $accounts[$i][$j]; + } + if ($sum > $rs) { + $rs = $sum; + } + } + return $rs; + } +} +``` ```c #define max(a, b) (((a) > (b)) ? (a) : (b)) @@ -159,8 +169,6 @@ int maximumWealth(int** accounts, int accountsSize, int* accountsColSize) { } ``` -### **Kotlin** - ```kotlin class Solution { fun maximumWealth(accounts: Array): Int { @@ -176,34 +184,6 @@ class Solution { } ``` -### **PHP** - -```php -class Solution { - /** - * @param Integer[][] $accounts - * @return Integer - */ - function maximumWealth($accounts) { - $rs = 0; - for ($i = 0; $i < count($accounts); $i++) { - $sum = 0; - for ($j = 0; $j < count($accounts[$i]); $j++) { - $sum += $accounts[$i][$j]; - } - if ($sum > $rs) { - $rs = $sum; - } - } - return $rs; - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1673.Find the Most Competitive Subsequence/README.md b/solution/1600-1699/1673.Find the Most Competitive Subsequence/README.md index 56a88dbc1a471..b5730e6291d47 100644 --- a/solution/1600-1699/1673.Find the Most Competitive Subsequence/README.md +++ b/solution/1600-1699/1673.Find the Most Competitive Subsequence/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 我们从左到右遍历数组 `nums`,维护一个栈 `stk`,遍历过程中,如果当前元素 `nums[i]` 小于栈顶元素,且栈中元素个数加上 $n-i$ 大于 $k$,则将栈顶元素出栈,直到不满足上述条件为止。此时如果栈中元素个数小于 $k$,则将当前元素入栈。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def mostCompetitive(self, nums: List[int], k: int) -> List[int]: @@ -70,10 +64,6 @@ class Solution: return stk ``` -### **Java** - - - ```java class Solution { public int[] mostCompetitive(int[] nums, int k) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func mostCompetitive(nums []int, k int) []int { stk := []int{} @@ -135,10 +121,6 @@ func mostCompetitive(nums []int, k int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1673.Find the Most Competitive Subsequence/README_EN.md b/solution/1600-1699/1673.Find the Most Competitive Subsequence/README_EN.md index 1ebc8c0bdf60a..ddca514c7f2a7 100644 --- a/solution/1600-1699/1673.Find the Most Competitive Subsequence/README_EN.md +++ b/solution/1600-1699/1673.Find the Most Competitive Subsequence/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return stk ``` -### **Java** - ```java class Solution { public int[] mostCompetitive(int[] nums, int k) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +95,6 @@ public: }; ``` -### **Go** - ```go func mostCompetitive(nums []int, k int) []int { stk := []int{} @@ -117,10 +111,6 @@ func mostCompetitive(nums []int, k int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README.md b/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README.md index d54248ce22f05..b85d0f6b88719 100644 --- a/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README.md +++ b/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README.md @@ -56,9 +56,7 @@ nums[3] + nums[0] = 3 + 1 = 4. ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 我们不妨设 $a$ 为 $nums[i]$ 和 $nums[n-i-1]$ 的较小值,设 $b$ 为 $nums[i]$ 和 $nums[n-i-1]$ 的较大值。 @@ -84,10 +82,6 @@ nums[3] + nums[0] = 3 + 1 = 4. -### **Python3** - - - ```python class Solution: def minMoves(self, nums: List[int], limit: int) -> int: @@ -114,10 +108,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minMoves(int[] nums, int limit) { @@ -148,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -181,8 +169,6 @@ public: }; ``` -### **Go** - ```go func minMoves(nums []int, limit int) int { d := make([]int, limit*2+2) @@ -209,10 +195,6 @@ func minMoves(nums []int, limit int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README_EN.md b/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README_EN.md index b1429576b6fdc..b665cc0e1f848 100644 --- a/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README_EN.md +++ b/solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README_EN.md @@ -52,7 +52,7 @@ Therefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary. ## Solutions -**Solution 1: Difference Array** +### Solution 1: Difference Array Let's denote $a$ as the smaller value between $nums[i]$ and $nums[n-i-1]$, and $b$ as the larger value between $nums[i]$ and $nums[n-i-1]$. @@ -78,8 +78,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def minMoves(self, nums: List[int], limit: int) -> int: @@ -106,8 +104,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minMoves(int[] nums, int limit) { @@ -138,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +165,6 @@ public: }; ``` -### **Go** - ```go func minMoves(nums []int, limit int) int { d := make([]int, limit*2+2) @@ -199,10 +191,6 @@ func minMoves(nums []int, limit int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1675.Minimize Deviation in Array/README.md b/solution/1600-1699/1675.Minimize Deviation in Array/README.md index 6d7d78489ab08..5c03da2b12026 100644 --- a/solution/1600-1699/1675.Minimize Deviation in Array/README.md +++ b/solution/1600-1699/1675.Minimize Deviation in Array/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列** +### 方法一:贪心 + 优先队列 直观上,为了得到数组的最小偏移量,我们需要将减小数组的最大值,增大数组的最小值。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def minimumDeviation(self, nums: List[int]) -> int: @@ -104,10 +98,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumDeviation(int[] nums) { @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func minimumDeviation(nums []int) int { q := hp{} @@ -193,10 +179,6 @@ func (h *hp) Pop() any { func (h *hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1675.Minimize Deviation in Array/README_EN.md b/solution/1600-1699/1675.Minimize Deviation in Array/README_EN.md index 65a7366b82fa0..473558e3830e1 100644 --- a/solution/1600-1699/1675.Minimize Deviation in Array/README_EN.md +++ b/solution/1600-1699/1675.Minimize Deviation in Array/README_EN.md @@ -60,7 +60,7 @@ ## Solutions -**Solution 1: Greedy + Priority Queue** +### Solution 1: Greedy + Priority Queue Intuitively, to get the minimum offset of the array, we need to decrease the maximum value of the array and increase the minimum value of the array. @@ -74,8 +74,6 @@ The time complexity is $O(n\log n \times \log m)$. Where $n$ and $m$ are the len -### **Python3** - ```python class Solution: def minimumDeviation(self, nums: List[int]) -> int: @@ -96,8 +94,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumDeviation(int[] nums) { @@ -122,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +142,6 @@ public: }; ``` -### **Go** - ```go func minimumDeviation(nums []int) int { q := hp{} @@ -183,10 +175,6 @@ func (h *hp) Pop() any { func (h *hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/README.md b/solution/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/README.md index 091e269f3854c..da6eee0caae2c 100644 --- a/solution/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/README.md +++ b/solution/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/README.md @@ -55,16 +55,10 @@ ## 解法 - - -**方法一:哈希表 + DFS** +### 方法一:哈希表 + DFS -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -90,10 +84,6 @@ class Solution: return dfs(root) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -131,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -163,8 +151,6 @@ public: }; ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -197,10 +183,6 @@ var lowestCommonAncestor = function (root, nodes) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/README_EN.md b/solution/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/README_EN.md index c7f4140915559..3c4fa799c686d 100644 --- a/solution/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/README_EN.md +++ b/solution/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -76,8 +76,6 @@ class Solution: return dfs(root) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -115,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -147,8 +143,6 @@ public: }; ``` -### **JavaScript** - ```js /** * Definition for a binary tree node. @@ -181,10 +175,6 @@ var lowestCommonAncestor = function (root, nodes) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1677.Product's Worth Over Invoices/README.md b/solution/1600-1699/1677.Product's Worth Over Invoices/README.md index b9e12c55ba299..05c3fe8fbc5de 100644 --- a/solution/1600-1699/1677.Product's Worth Over Invoices/README.md +++ b/solution/1600-1699/1677.Product's Worth Over Invoices/README.md @@ -86,12 +86,10 @@ Result 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -108,3 +106,5 @@ ORDER BY name; ``` + + diff --git a/solution/1600-1699/1677.Product's Worth Over Invoices/README_EN.md b/solution/1600-1699/1677.Product's Worth Over Invoices/README_EN.md index 093203afa43bb..2e9d95db34d9a 100644 --- a/solution/1600-1699/1677.Product's Worth Over Invoices/README_EN.md +++ b/solution/1600-1699/1677.Product's Worth Over Invoices/README_EN.md @@ -91,9 +91,9 @@ Invoice table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -111,3 +111,5 @@ ORDER BY name; ``` + + diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/README.md b/solution/1600-1699/1678.Goal Parser Interpretation/README.md index 2112cc1fee9cf..219d14eb88d22 100644 --- a/solution/1600-1699/1678.Goal Parser Interpretation/README.md +++ b/solution/1600-1699/1678.Goal Parser Interpretation/README.md @@ -46,13 +46,85 @@ G -> G ## 解法 - - -**方法一:字符串替换** +### 方法一:字符串替换 根据题意,只需要将字符串 `command` 中的 `"()"` 替换为 `'o'`,`"(al)"` 替换为 `"al"` 即可。 -**方法二:字符串遍历** + + +```python +class Solution: + def interpret(self, command: str) -> str: + return command.replace('()', 'o').replace('(al)', 'al') +``` + +```java +class Solution { + public String interpret(String command) { + return command.replace("()", "o").replace("(al)", "al"); + } +} +``` + +```cpp +class Solution { +public: + string interpret(string command) { + while (command.find("()") != -1) command.replace(command.find("()"), 2, "o"); + while (command.find("(al)") != -1) command.replace(command.find("(al)"), 4, "al"); + return command; + } +}; +``` + +```go +func interpret(command string) string { + command = strings.ReplaceAll(command, "()", "o") + command = strings.ReplaceAll(command, "(al)", "al") + return command +} +``` + +```ts +function interpret(command: string): string { + return command.replace(/\(\)/g, 'o').replace(/\(al\)/g, 'al'); +} +``` + +```rust +impl Solution { + pub fn interpret(command: String) -> String { + command.replace("()", "o").replace("(al)", "al") + } +} +``` + +```c +char* interpret(char* command) { + int n = strlen(command); + char* ans = malloc(sizeof(char) * n + 1); + int i = 0; + for (int j = 0; j < n; j++) { + char c = command[j]; + if (c == 'G') { + ans[i++] = 'G'; + } else if (c == '(') { + if (command[j + 1] == ')') { + ans[i++] = 'o'; + } else { + ans[i++] = 'a'; + ans[i++] = 'l'; + } + } + } + ans[i] = '\0'; + return ans; +} +``` + + + +### 方法二:字符串遍历 我们也可以遍历字符串 `command`,对于每个字符 $c$: @@ -65,16 +137,6 @@ G -> G -### **Python3** - - - -```python -class Solution: - def interpret(self, command: str) -> str: - return command.replace('()', 'o').replace('(al)', 'al') -``` - ```python class Solution: def interpret(self, command: str) -> str: @@ -87,18 +149,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - -```java -class Solution { - public String interpret(String command) { - return command.replace("()", "o").replace("(al)", "al"); - } -} -``` - ```java class Solution { public String interpret(String command) { @@ -116,19 +166,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string interpret(string command) { - while (command.find("()") != -1) command.replace(command.find("()"), 2, "o"); - while (command.find("(al)") != -1) command.replace(command.find("(al)"), 4, "al"); - return command; - } -}; -``` - ```cpp class Solution { public: @@ -146,16 +183,6 @@ public: }; ``` -### **Go** - -```go -func interpret(command string) string { - command = strings.ReplaceAll(command, "()", "o") - command = strings.ReplaceAll(command, "(al)", "al") - return command -} -``` - ```go func interpret(command string) string { ans := &strings.Builder{} @@ -174,14 +201,6 @@ func interpret(command string) string { } ``` -### **TypeScript** - -```ts -function interpret(command: string): string { - return command.replace(/\(\)/g, 'o').replace(/\(al\)/g, 'al'); -} -``` - ```ts function interpret(command: string): string { const n = command.length; @@ -198,16 +217,6 @@ function interpret(command: string): string { } ``` -### **Rust** - -```rust -impl Solution { - pub fn interpret(command: String) -> String { - command.replace("()", "o").replace("(al)", "al") - } -} -``` - ```rust impl Solution { pub fn interpret(command: String) -> String { @@ -228,35 +237,6 @@ impl Solution { } ``` -### **C** - -```c -char* interpret(char* command) { - int n = strlen(command); - char* ans = malloc(sizeof(char) * n + 1); - int i = 0; - for (int j = 0; j < n; j++) { - char c = command[j]; - if (c == 'G') { - ans[i++] = 'G'; - } else if (c == '(') { - if (command[j + 1] == ')') { - ans[i++] = 'o'; - } else { - ans[i++] = 'a'; - ans[i++] = 'l'; - } - } - } - ans[i] = '\0'; - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1678.Goal Parser Interpretation/README_EN.md b/solution/1600-1699/1678.Goal Parser Interpretation/README_EN.md index cf6aec728af88..13bce82b7bdc1 100644 --- a/solution/1600-1699/1678.Goal Parser Interpretation/README_EN.md +++ b/solution/1600-1699/1678.Goal Parser Interpretation/README_EN.md @@ -45,11 +45,85 @@ The final concatenated result is "Goal". ## Solutions -**Solution 1: String Replacement** +### Solution 1: String Replacement According to the problem, we only need to replace `"()"` with `'o'` and `"(al)"` with `"al"` in the string `command`. -**Solution 2: String Iteration** + + +```python +class Solution: + def interpret(self, command: str) -> str: + return command.replace('()', 'o').replace('(al)', 'al') +``` + +```java +class Solution { + public String interpret(String command) { + return command.replace("()", "o").replace("(al)", "al"); + } +} +``` + +```cpp +class Solution { +public: + string interpret(string command) { + while (command.find("()") != -1) command.replace(command.find("()"), 2, "o"); + while (command.find("(al)") != -1) command.replace(command.find("(al)"), 4, "al"); + return command; + } +}; +``` + +```go +func interpret(command string) string { + command = strings.ReplaceAll(command, "()", "o") + command = strings.ReplaceAll(command, "(al)", "al") + return command +} +``` + +```ts +function interpret(command: string): string { + return command.replace(/\(\)/g, 'o').replace(/\(al\)/g, 'al'); +} +``` + +```rust +impl Solution { + pub fn interpret(command: String) -> String { + command.replace("()", "o").replace("(al)", "al") + } +} +``` + +```c +char* interpret(char* command) { + int n = strlen(command); + char* ans = malloc(sizeof(char) * n + 1); + int i = 0; + for (int j = 0; j < n; j++) { + char c = command[j]; + if (c == 'G') { + ans[i++] = 'G'; + } else if (c == '(') { + if (command[j + 1] == ')') { + ans[i++] = 'o'; + } else { + ans[i++] = 'a'; + ans[i++] = 'l'; + } + } + } + ans[i] = '\0'; + return ans; +} +``` + + + +### Solution 2: String Iteration We can also iterate over the string `command`. For each character $c$: @@ -62,14 +136,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. -### **Python3** - -```python -class Solution: - def interpret(self, command: str) -> str: - return command.replace('()', 'o').replace('(al)', 'al') -``` - ```python class Solution: def interpret(self, command: str) -> str: @@ -82,16 +148,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - -```java -class Solution { - public String interpret(String command) { - return command.replace("()", "o").replace("(al)", "al"); - } -} -``` - ```java class Solution { public String interpret(String command) { @@ -109,19 +165,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string interpret(string command) { - while (command.find("()") != -1) command.replace(command.find("()"), 2, "o"); - while (command.find("(al)") != -1) command.replace(command.find("(al)"), 4, "al"); - return command; - } -}; -``` - ```cpp class Solution { public: @@ -139,16 +182,6 @@ public: }; ``` -### **Go** - -```go -func interpret(command string) string { - command = strings.ReplaceAll(command, "()", "o") - command = strings.ReplaceAll(command, "(al)", "al") - return command -} -``` - ```go func interpret(command string) string { ans := &strings.Builder{} @@ -167,14 +200,6 @@ func interpret(command string) string { } ``` -### **TypeScript** - -```ts -function interpret(command: string): string { - return command.replace(/\(\)/g, 'o').replace(/\(al\)/g, 'al'); -} -``` - ```ts function interpret(command: string): string { const n = command.length; @@ -191,16 +216,6 @@ function interpret(command: string): string { } ``` -### **Rust** - -```rust -impl Solution { - pub fn interpret(command: String) -> String { - command.replace("()", "o").replace("(al)", "al") - } -} -``` - ```rust impl Solution { pub fn interpret(command: String) -> String { @@ -221,35 +236,6 @@ impl Solution { } ``` -### **C** - -```c -char* interpret(char* command) { - int n = strlen(command); - char* ans = malloc(sizeof(char) * n + 1); - int i = 0; - for (int j = 0; j < n; j++) { - char c = command[j]; - if (c == 'G') { - ans[i++] = 'G'; - } else if (c == '(') { - if (command[j + 1] == ')') { - ans[i++] = 'o'; - } else { - ans[i++] = 'a'; - ans[i++] = 'l'; - } - } - } - ans[i] = '\0'; - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1679.Max Number of K-Sum Pairs/README.md b/solution/1600-1699/1679.Max Number of K-Sum Pairs/README.md index 5d0eeb81c6323..8769d22fda230 100644 --- a/solution/1600-1699/1679.Max Number of K-Sum Pairs/README.md +++ b/solution/1600-1699/1679.Max Number of K-Sum Pairs/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们对 $nums$ 进行排序。然后 $l$, $r$ 分别指向 $nums$ 首尾元素,判断两整数之和 $s$ 与 $k$ 的大小关系。 @@ -60,22 +58,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为 $nums$ 的长度。 -**方法二:哈希表** - -我们使用哈希表 $cnt$ 记录当前剩余整数及其出现的次数。 - -遍历 $nums$,对于当前整数 $x$,判断 $k - x$ 是否在 $cnt$ 中,若存在,则说明找到了两个整数,满足和为 $k$,答案加一,然后将 $k - x$ 的出现次数减一;否则,将 $x$ 的出现次数加一。 - -遍历结束,返回答案。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 $nums$ 的长度。 - -### **Python3** - - - ```python class Solution: def maxOperations(self, nums: List[int], k: int) -> int: @@ -93,24 +77,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxOperations(self, nums: List[int], k: int) -> int: - cnt = Counter() - ans = 0 - for x in nums: - if cnt[k - x]: - ans += 1 - cnt[k - x] -= 1 - else: - cnt[x] += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int maxOperations(int[] nums, int k) { @@ -134,28 +100,6 @@ class Solution { } ``` -```java -class Solution { - public int maxOperations(int[] nums, int k) { - Map cnt = new HashMap<>(); - int ans = 0; - for (int x : nums) { - if (cnt.containsKey(k - x)) { - ++ans; - if (cnt.merge(k - x, -1, Integer::sum) == 0) { - cnt.remove(k - x); - } - } else { - cnt.merge(x, 1, Integer::sum); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -179,27 +123,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxOperations(vector& nums, int k) { - unordered_map cnt; - int ans = 0; - for (int& x : nums) { - if (cnt[k - x]) { - --cnt[k - x]; - ++ans; - } else { - ++cnt[x]; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func maxOperations(nums []int, k int) int { sort.Ints(nums) @@ -220,23 +143,6 @@ func maxOperations(nums []int, k int) int { } ``` -```go -func maxOperations(nums []int, k int) (ans int) { - cnt := map[int]int{} - for _, x := range nums { - if cnt[k-x] > 0 { - cnt[k-x]-- - ans++ - } else { - cnt[x]++ - } - } - return -} -``` - -### **TypeScript** - ```ts function maxOperations(nums: number[], k: number): number { const cnt = new Map(); @@ -253,8 +159,6 @@ function maxOperations(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_operations(nums: Vec, k: i32) -> i32 { @@ -281,6 +185,88 @@ impl Solution { } ``` + + +### 方法二:哈希表 + +我们使用哈希表 $cnt$ 记录当前剩余整数及其出现的次数。 + +遍历 $nums$,对于当前整数 $x$,判断 $k - x$ 是否在 $cnt$ 中,若存在,则说明找到了两个整数,满足和为 $k$,答案加一,然后将 $k - x$ 的出现次数减一;否则,将 $x$ 的出现次数加一。 + +遍历结束,返回答案。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为 $nums$ 的长度。 + + + +```python +class Solution: + def maxOperations(self, nums: List[int], k: int) -> int: + cnt = Counter() + ans = 0 + for x in nums: + if cnt[k - x]: + ans += 1 + cnt[k - x] -= 1 + else: + cnt[x] += 1 + return ans +``` + +```java +class Solution { + public int maxOperations(int[] nums, int k) { + Map cnt = new HashMap<>(); + int ans = 0; + for (int x : nums) { + if (cnt.containsKey(k - x)) { + ++ans; + if (cnt.merge(k - x, -1, Integer::sum) == 0) { + cnt.remove(k - x); + } + } else { + cnt.merge(x, 1, Integer::sum); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maxOperations(vector& nums, int k) { + unordered_map cnt; + int ans = 0; + for (int& x : nums) { + if (cnt[k - x]) { + --cnt[k - x]; + ++ans; + } else { + ++cnt[x]; + } + } + return ans; + } +}; +``` + +```go +func maxOperations(nums []int, k int) (ans int) { + cnt := map[int]int{} + for _, x := range nums { + if cnt[k-x] > 0 { + cnt[k-x]-- + ans++ + } else { + cnt[x]++ + } + } + return +} +``` + ```rust impl Solution { pub fn max_operations(nums: Vec, k: i32) -> i32 { @@ -305,10 +291,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1679.Max Number of K-Sum Pairs/README_EN.md b/solution/1600-1699/1679.Max Number of K-Sum Pairs/README_EN.md index a0eb5cd7669ea..b2aeb53ab0c25 100644 --- a/solution/1600-1699/1679.Max Number of K-Sum Pairs/README_EN.md +++ b/solution/1600-1699/1679.Max Number of K-Sum Pairs/README_EN.md @@ -41,7 +41,7 @@ There are no more pairs that sum up to 6, hence a total of 1 operation. ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting We sort $nums$. Then $l$ and $r$ point to the first and last elements of $nums$ respectively, and we compare the sum $s$ of the two integers with $k$. @@ -54,20 +54,8 @@ After the loop ends, we return the answer. The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of $nums$. -**Solution 2: Hash Table** - -We use a hash table $cnt$ to record the current remaining integers and their occurrence counts. - -We iterate over $nums$. For the current integer $x$, we check if $k - x$ is in $cnt$. If it exists, it means that we have found two integers whose sum is $k$. We increment the answer and then decrement the occurrence count of $k - x$; otherwise, we increment the occurrence count of $x$. - -After the iteration ends, we return the answer. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of $nums$. - -### **Python3** - ```python class Solution: def maxOperations(self, nums: List[int], k: int) -> int: @@ -85,22 +73,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxOperations(self, nums: List[int], k: int) -> int: - cnt = Counter() - ans = 0 - for x in nums: - if cnt[k - x]: - ans += 1 - cnt[k - x] -= 1 - else: - cnt[x] += 1 - return ans -``` - -### **Java** - ```java class Solution { public int maxOperations(int[] nums, int k) { @@ -124,28 +96,6 @@ class Solution { } ``` -```java -class Solution { - public int maxOperations(int[] nums, int k) { - Map cnt = new HashMap<>(); - int ans = 0; - for (int x : nums) { - if (cnt.containsKey(k - x)) { - ++ans; - if (cnt.merge(k - x, -1, Integer::sum) == 0) { - cnt.remove(k - x); - } - } else { - cnt.merge(x, 1, Integer::sum); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -169,27 +119,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxOperations(vector& nums, int k) { - unordered_map cnt; - int ans = 0; - for (int& x : nums) { - if (cnt[k - x]) { - --cnt[k - x]; - ++ans; - } else { - ++cnt[x]; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func maxOperations(nums []int, k int) int { sort.Ints(nums) @@ -210,23 +139,6 @@ func maxOperations(nums []int, k int) int { } ``` -```go -func maxOperations(nums []int, k int) (ans int) { - cnt := map[int]int{} - for _, x := range nums { - if cnt[k-x] > 0 { - cnt[k-x]-- - ans++ - } else { - cnt[x]++ - } - } - return -} -``` - -### **TypeScript** - ```ts function maxOperations(nums: number[], k: number): number { const cnt = new Map(); @@ -243,8 +155,6 @@ function maxOperations(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_operations(nums: Vec, k: i32) -> i32 { @@ -271,6 +181,88 @@ impl Solution { } ``` + + +### Solution 2: Hash Table + +We use a hash table $cnt$ to record the current remaining integers and their occurrence counts. + +We iterate over $nums$. For the current integer $x$, we check if $k - x$ is in $cnt$. If it exists, it means that we have found two integers whose sum is $k$. We increment the answer and then decrement the occurrence count of $k - x$; otherwise, we increment the occurrence count of $x$. + +After the iteration ends, we return the answer. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of $nums$. + + + +```python +class Solution: + def maxOperations(self, nums: List[int], k: int) -> int: + cnt = Counter() + ans = 0 + for x in nums: + if cnt[k - x]: + ans += 1 + cnt[k - x] -= 1 + else: + cnt[x] += 1 + return ans +``` + +```java +class Solution { + public int maxOperations(int[] nums, int k) { + Map cnt = new HashMap<>(); + int ans = 0; + for (int x : nums) { + if (cnt.containsKey(k - x)) { + ++ans; + if (cnt.merge(k - x, -1, Integer::sum) == 0) { + cnt.remove(k - x); + } + } else { + cnt.merge(x, 1, Integer::sum); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maxOperations(vector& nums, int k) { + unordered_map cnt; + int ans = 0; + for (int& x : nums) { + if (cnt[k - x]) { + --cnt[k - x]; + ++ans; + } else { + ++cnt[x]; + } + } + return ans; + } +}; +``` + +```go +func maxOperations(nums []int, k int) (ans int) { + cnt := map[int]int{} + for _, x := range nums { + if cnt[k-x] > 0 { + cnt[k-x]-- + ans++ + } else { + cnt[x]++ + } + } + return +} +``` + ```rust impl Solution { pub fn max_operations(nums: Vec, k: i32) -> i32 { @@ -295,10 +287,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README.md b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README.md index a611a068b7b51..93bade1d701e8 100644 --- a/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README.md +++ b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 观察数字的连接规律,我们可以发现,当连接到第 $i$ 个数时,实际上是将前 $i-1$ 个数连接而成的结果 $ans$ 往左移动一定的位数,然后再加上 $i$ 这个数,移动的位数 $shift$ 是 $i$ 中二进制的位数。由于 $i$ 在不断加 $1$,移动的位数要么与上一次移动的位数保持不变,要么加一。当 $i$ 为 $2$ 的幂次方的时候,也即是说 $i$ 的二进制数中只有一位是 $1$ 时,移动的位数相比于上次加 $1$。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def concatenatedBinary(self, n: int) -> int: @@ -68,22 +62,6 @@ class Solution: return ans ``` -```python -class Solution: - def concatenatedBinary(self, n: int) -> int: - mod = 10**9 + 7 - ans = shift = 0 - for i in range(1, n + 1): - if (i & (i - 1)) == 0: - shift += 1 - ans = (ans << shift | i) % mod - return ans -``` - -### **Java** - - - ```java class Solution { public int concatenatedBinary(int n) { @@ -97,6 +75,63 @@ class Solution { } ``` +```cpp +class Solution { +public: + int concatenatedBinary(int n) { + const int mod = 1e9 + 7; + long ans = 0; + for (int i = 1; i <= n; ++i) { + ans = (ans << (32 - __builtin_clz(i)) | i) % mod; + } + return ans; + } +}; +``` + +```go +func concatenatedBinary(n int) (ans int) { + const mod = 1e9 + 7 + for i := 1; i <= n; i++ { + ans = (ans< + +### 方法二 + + + +```python +class Solution: + def concatenatedBinary(self, n: int) -> int: + mod = 10**9 + 7 + ans = shift = 0 + for i in range(1, n + 1): + if (i & (i - 1)) == 0: + shift += 1 + ans = (ans << shift | i) % mod + return ans +``` + ```java class Solution { public int concatenatedBinary(int n) { @@ -114,22 +149,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int concatenatedBinary(int n) { - const int mod = 1e9 + 7; - long ans = 0; - for (int i = 1; i <= n; ++i) { - ans = (ans << (32 - __builtin_clz(i)) | i) % mod; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -148,18 +167,6 @@ public: }; ``` -### **Go** - -```go -func concatenatedBinary(n int) (ans int) { - const mod = 1e9 + 7 - for i := 1; i <= n; i++ { - ans = (ans< + + diff --git a/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README_EN.md b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README_EN.md index 327a29556a8ab..c50ae5ebc4d90 100644 --- a/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README_EN.md +++ b/solution/1600-1699/1680.Concatenation of Consecutive Binary Numbers/README_EN.md @@ -43,7 +43,7 @@ After modulo 109 + 7, the result is 505379714. ## Solutions -**Solution 1: Bit Manipulation** +### Solution 1: Bit Manipulation By observing the pattern of number concatenation, we can find that when concatenating to the $i$-th number, the result $ans$ formed by concatenating the previous $i-1$ numbers is actually shifted to the left by a certain number of bits, and then $i$ is added. The number of bits shifted, $shift$, is the number of binary digits in $i$. Since $i$ is continuously incremented by $1$, the number of bits shifted either remains the same as the last shift or increases by one. When $i$ is a power of $2$, that is, when there is only one bit in the binary number of $i$ that is $1$, the number of bits shifted increases by $1$ compared to the last time. @@ -51,8 +51,6 @@ The time complexity is $O(n)$, where $n$ is the given integer. The space complex -### **Python3** - ```python class Solution: def concatenatedBinary(self, n: int) -> int: @@ -63,20 +61,6 @@ class Solution: return ans ``` -```python -class Solution: - def concatenatedBinary(self, n: int) -> int: - mod = 10**9 + 7 - ans = shift = 0 - for i in range(1, n + 1): - if (i & (i - 1)) == 0: - shift += 1 - ans = (ans << shift | i) % mod - return ans -``` - -### **Java** - ```java class Solution { public int concatenatedBinary(int n) { @@ -90,6 +74,63 @@ class Solution { } ``` +```cpp +class Solution { +public: + int concatenatedBinary(int n) { + const int mod = 1e9 + 7; + long ans = 0; + for (int i = 1; i <= n; ++i) { + ans = (ans << (32 - __builtin_clz(i)) | i) % mod; + } + return ans; + } +}; +``` + +```go +func concatenatedBinary(n int) (ans int) { + const mod = 1e9 + 7 + for i := 1; i <= n; i++ { + ans = (ans< + +### Solution 2 + + + +```python +class Solution: + def concatenatedBinary(self, n: int) -> int: + mod = 10**9 + 7 + ans = shift = 0 + for i in range(1, n + 1): + if (i & (i - 1)) == 0: + shift += 1 + ans = (ans << shift | i) % mod + return ans +``` + ```java class Solution { public int concatenatedBinary(int n) { @@ -107,22 +148,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int concatenatedBinary(int n) { - const int mod = 1e9 + 7; - long ans = 0; - for (int i = 1; i <= n; ++i) { - ans = (ans << (32 - __builtin_clz(i)) | i) % mod; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -141,18 +166,6 @@ public: }; ``` -### **Go** - -```go -func concatenatedBinary(n int) (ans int) { - const mod = 1e9 + 7 - for i := 1; i <= n; i++ { - ans = (ans< + + diff --git a/solution/1600-1699/1681.Minimum Incompatibility/README.md b/solution/1600-1699/1681.Minimum Incompatibility/README.md index 51dccd6c5f4d1..5dd3e9f3fe03a 100644 --- a/solution/1600-1699/1681.Minimum Incompatibility/README.md +++ b/solution/1600-1699/1681.Minimum Incompatibility/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:预处理 + 状态压缩 + 动态规划** +### 方法一:预处理 + 状态压缩 + 动态规划 不妨设划分后每个子集的大小为 $m$,那么 $m=\frac{n}{k}$,其中 $n$ 是数组的长度。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def minimumIncompatibility(self, nums: List[int], k: int) -> int: @@ -119,35 +113,6 @@ class Solution: return f[-1] if f[-1] != inf else -1 ``` -```python -class Solution: - def minimumIncompatibility(self, nums: List[int], k: int) -> int: - @cache - def dfs(mask): - if mask == (1 << n) - 1: - return 0 - d = {v: i for i, v in enumerate(nums) if (mask >> i & 1) == 0} - ans = inf - if len(d) < m: - return ans - for vs in combinations(d.keys(), m): - nxt = mask - for v in vs: - nxt |= 1 << d[v] - ans = min(ans, max(vs) - min(vs) + dfs(nxt)) - return ans - - n = len(nums) - m = n // k - ans = dfs(0) - dfs.cache_clear() - return ans if ans < inf else -1 -``` - -### **Java** - - - ```java class Solution { public int minimumIncompatibility(int[] nums, int k) { @@ -204,8 +169,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -263,8 +226,6 @@ public: }; ``` -### **Go** - ```go func minimumIncompatibility(nums []int, k int) int { n := len(nums) @@ -325,8 +286,6 @@ func minimumIncompatibility(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function minimumIncompatibility(nums: number[], k: number): number { const n = nums.length; @@ -389,8 +348,6 @@ function bitCount(i: number): number { } ``` -### **C#** - ```cs public class Solution { public int MinimumIncompatibility(int[] nums, int k) { @@ -457,10 +414,37 @@ public class Solution { } ``` -### **...** + + +### 方法二 -``` + +```python +class Solution: + def minimumIncompatibility(self, nums: List[int], k: int) -> int: + @cache + def dfs(mask): + if mask == (1 << n) - 1: + return 0 + d = {v: i for i, v in enumerate(nums) if (mask >> i & 1) == 0} + ans = inf + if len(d) < m: + return ans + for vs in combinations(d.keys(), m): + nxt = mask + for v in vs: + nxt |= 1 << d[v] + ans = min(ans, max(vs) - min(vs) + dfs(nxt)) + return ans + + n = len(nums) + m = n // k + ans = dfs(0) + dfs.cache_clear() + return ans if ans < inf else -1 ``` + + diff --git a/solution/1600-1699/1681.Minimum Incompatibility/README_EN.md b/solution/1600-1699/1681.Minimum Incompatibility/README_EN.md index 6b9e0636b051f..655469a690db5 100644 --- a/solution/1600-1699/1681.Minimum Incompatibility/README_EN.md +++ b/solution/1600-1699/1681.Minimum Incompatibility/README_EN.md @@ -50,7 +50,7 @@ The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6. ## Solutions -**Solution 1: Preprocessing + State Compression + Dynamic Programming** +### Solution 1: Preprocessing + State Compression + Dynamic Programming Let's assume that the size of each subset after partitioning is $m$, so $m=\frac{n}{k}$, where $n$ is the length of the array. @@ -68,8 +68,6 @@ The time complexity is $O(3^n)$, and the space complexity is $O(2^n)$. Here, $n$ -### **Python3** - ```python class Solution: def minimumIncompatibility(self, nums: List[int], k: int) -> int: @@ -111,33 +109,6 @@ class Solution: return f[-1] if f[-1] != inf else -1 ``` -```python -class Solution: - def minimumIncompatibility(self, nums: List[int], k: int) -> int: - @cache - def dfs(mask): - if mask == (1 << n) - 1: - return 0 - d = {v: i for i, v in enumerate(nums) if (mask >> i & 1) == 0} - ans = inf - if len(d) < m: - return ans - for vs in combinations(d.keys(), m): - nxt = mask - for v in vs: - nxt |= 1 << d[v] - ans = min(ans, max(vs) - min(vs) + dfs(nxt)) - return ans - - n = len(nums) - m = n // k - ans = dfs(0) - dfs.cache_clear() - return ans if ans < inf else -1 -``` - -### **Java** - ```java class Solution { public int minimumIncompatibility(int[] nums, int k) { @@ -194,8 +165,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -253,8 +222,6 @@ public: }; ``` -### **Go** - ```go func minimumIncompatibility(nums []int, k int) int { n := len(nums) @@ -315,8 +282,6 @@ func minimumIncompatibility(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function minimumIncompatibility(nums: number[], k: number): number { const n = nums.length; @@ -379,8 +344,6 @@ function bitCount(i: number): number { } ``` -### **C#** - ```cs public class Solution { public int MinimumIncompatibility(int[] nums, int k) { @@ -447,10 +410,37 @@ public class Solution { } ``` -### **...** + + +### Solution 2 -``` + +```python +class Solution: + def minimumIncompatibility(self, nums: List[int], k: int) -> int: + @cache + def dfs(mask): + if mask == (1 << n) - 1: + return 0 + d = {v: i for i, v in enumerate(nums) if (mask >> i & 1) == 0} + ans = inf + if len(d) < m: + return ans + for vs in combinations(d.keys(), m): + nxt = mask + for v in vs: + nxt |= 1 << d[v] + ans = min(ans, max(vs) - min(vs) + dfs(nxt)) + return ans + + n = len(nums) + m = n // k + ans = dfs(0) + dfs.cache_clear() + return ans if ans < inf else -1 ``` + + diff --git a/solution/1600-1699/1682.Longest Palindromic Subsequence II/README.md b/solution/1600-1699/1682.Longest Palindromic Subsequence II/README.md index ffe7f02872176..8d7c6b3c33f48 100644 --- a/solution/1600-1699/1682.Longest Palindromic Subsequence II/README.md +++ b/solution/1600-1699/1682.Longest Palindromic Subsequence II/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j, x)$ 表示字符串 $s$ 中下标范围 $[i, j]$ 内,且以字符 $x$ 结尾的最长“好的回文子序列”的长度。答案为 $dfs(0, n - 1, 26)$。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def longestPalindromeSubseq(self, s: str) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[][][] f; @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +140,6 @@ public: }; ``` -### **Go** - ```go func longestPalindromeSubseq(s string) int { n := len(s) @@ -188,10 +174,6 @@ func longestPalindromeSubseq(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1682.Longest Palindromic Subsequence II/README_EN.md b/solution/1600-1699/1682.Longest Palindromic Subsequence II/README_EN.md index 74d69ad05cf4f..eb82d7e67ab0b 100644 --- a/solution/1600-1699/1682.Longest Palindromic Subsequence II/README_EN.md +++ b/solution/1600-1699/1682.Longest Palindromic Subsequence II/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Memorization Search** +### Solution 1: Memorization Search We design a function $dfs(i, j, x)$ to represent the length of the longest "good" palindrome subsequence ending with character $x$ in the index range $[i, j]$ of string $s$. The answer is $dfs(0, n - 1, 26)$. @@ -60,8 +60,6 @@ The time complexity is $O(n^2 \times C)$. Where $n$ is the length of the string -### **Python3** - ```python class Solution: def longestPalindromeSubseq(self, s: str) -> int: @@ -78,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[][][] f; @@ -116,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go func longestPalindromeSubseq(s string) int { n := len(s) @@ -178,10 +170,6 @@ func longestPalindromeSubseq(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1683.Invalid Tweets/README.md b/solution/1600-1699/1683.Invalid Tweets/README.md index bb058649aabd9..5a6c68d4a94cf 100644 --- a/solution/1600-1699/1683.Invalid Tweets/README.md +++ b/solution/1600-1699/1683.Invalid Tweets/README.md @@ -53,9 +53,7 @@ Tweets 表: ## 解法 - - -**方法一:使用 `CHAR_LENGTH` 函数** +### 方法一:使用 `CHAR_LENGTH` 函数 `CHAR_LENGTH()` 函数返回字符串的长度,其中中文、数字、字母都是 $1$ 字节。 @@ -65,8 +63,6 @@ Tweets 表: -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -76,3 +72,5 @@ WHERE CHAR_LENGTH(content) > 15; ``` + + diff --git a/solution/1600-1699/1683.Invalid Tweets/README_EN.md b/solution/1600-1699/1683.Invalid Tweets/README_EN.md index c5fc81aaeab97..9435c8e34e04f 100644 --- a/solution/1600-1699/1683.Invalid Tweets/README_EN.md +++ b/solution/1600-1699/1683.Invalid Tweets/README_EN.md @@ -50,7 +50,7 @@ Tweet 2 has length = 32. It is an invalid tweet. ## Solutions -**Solution 1: Using `CHAR_LENGTH` Function** +### Solution 1: Using `CHAR_LENGTH` Function The `CHAR_LENGTH()` function returns the length of a string, where Chinese characters, numbers, and letters are all counted as $1$ byte. @@ -60,8 +60,6 @@ For this problem, we can directly use the `CHAR_LENGTH` function to get the leng -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -71,3 +69,5 @@ WHERE CHAR_LENGTH(content) > 15; ``` + + diff --git a/solution/1600-1699/1684.Count the Number of Consistent Strings/README.md b/solution/1600-1699/1684.Count the Number of Consistent Strings/README.md index 34e665744e857..c635fcb506961 100644 --- a/solution/1600-1699/1684.Count the Number of Consistent Strings/README.md +++ b/solution/1600-1699/1684.Count the Number of Consistent Strings/README.md @@ -50,30 +50,14 @@ ## 解法 - - -**方法一:哈希表或数组** +### 方法一:哈希表或数组 一种比较直接的思路是,用哈希表或数组 $s$ 记录 `allowed` 中的字符。然后遍历 `words` 数组,对于每个字符串 $w$,判断其是否由 `allowed` 中的字符组成。若是,答案加一。 时间复杂度 $O(m)$,空间复杂度 $O(C)$。其中 $m$ 为所有字符串的总长度,而 $C$ 为 `allowed` 字符集的大小。本题中 $C \leq 26$。 -**方法二:位运算** - -我们也可以仅用一个整数来表示每个字符串中字符的出现情况。其中,整数的二进制表示中的每一位表示一个字符是否出现。 - -我们简单地定义一个函数 $f(w)$,这个函数可以将一个字符串 $w$ 转换为一个整数。整数的二进制表示中的每一位表示一个字符是否出现。例如,字符串 `ab` 可以转换为整数 $3$,即二进制表示为 $11$。字符串 `abd` 可以转换为整数 $11$,即二进制表示为 $1011$。 - -回到题目上,判断一个字符串 $w$ 是否由 `allowed` 中的字符组成,就可以转换为:判断 $f(allowed)$ 和 $f(w)$ 进行按位或运算后的结果是否等于 $f(allowed)$。若是,答案加一。 - -时间复杂度 $O(m)$,其中 $m$ 为所有字符串的总长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def countConsistentStrings(self, allowed: str, words: List[str]) -> int: @@ -81,20 +65,6 @@ class Solution: return sum(all(c in s for c in w) for w in words) ``` -```python -class Solution: - def countConsistentStrings(self, allowed: str, words: List[str]) -> int: - def f(w): - return reduce(or_, (1 << (ord(c) - ord('a')) for c in w)) - - mask = f(allowed) - return sum((mask | f(w)) == mask for w in words) -``` - -### **Java** - - - ```java class Solution { public int countConsistentStrings(String allowed, String[] words) { @@ -122,31 +92,6 @@ class Solution { } ``` -```java -class Solution { - public int countConsistentStrings(String allowed, String[] words) { - int mask = f(allowed); - int ans = 0; - for (String w : words) { - if ((mask | f(w)) == mask) { - ++ans; - } - } - return ans; - } - - private int f(String w) { - int mask = 0; - for (int i = 0; i < w.length(); ++i) { - mask |= 1 << (w.charAt(i) - 'a'); - } - return mask; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -165,25 +110,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countConsistentStrings(string allowed, vector& words) { - auto f = [](string& w) { - int mask = 0; - for (auto& c : w) mask |= 1 << (c - 'a'); - return mask; - }; - int mask = f(allowed); - int ans = 0; - for (auto& w : words) ans += (mask | f(w)) == mask; - return ans; - } -}; -``` - -### **Go** - ```go func countConsistentStrings(allowed string, words []string) (ans int) { s := [26]bool{} @@ -207,26 +133,44 @@ func countConsistentStrings(allowed string, words []string) (ans int) { } ``` -```go -func countConsistentStrings(allowed string, words []string) (ans int) { - f := func(w string) (mask int) { - for _, c := range w { - mask |= 1 << (c - 'a') - } - return - } - - mask := f(allowed) - for _, w := range words { - if (mask | f(w)) == mask { - ans++ - } - } - return +```ts +function countConsistentStrings(allowed: string, words: string[]): number { + const set = new Set([...allowed]); + const n = words.length; + let ans = n; + for (const word of words) { + for (const c of word) { + if (!set.has(c)) { + ans--; + break; + } + } + } + return ans; } ``` -### **C** +```rust +impl Solution { + pub fn count_consistent_strings(allowed: String, words: Vec) -> i32 { + let n = words.len(); + let mut make = [false; 26]; + for c in allowed.as_bytes() { + make[(c - b'a') as usize] = true; + } + let mut ans = n as i32; + for word in words.iter() { + for c in word.as_bytes().iter() { + if !make[(c - b'a') as usize] { + ans -= 1; + break; + } + } + } + ans + } +} +``` ```c int countConsistentStrings(char* allowed, char** words, int wordsSize) { @@ -249,44 +193,86 @@ int countConsistentStrings(char* allowed, char** words, int wordsSize) { } ``` -```c -int helper(char* s) { - int res = 0; - int n = strlen(s); - for (int i = 0; i < n; i++) { - res |= 1 << (s[i] - 'a'); + + +### 方法二:位运算 + +我们也可以仅用一个整数来表示每个字符串中字符的出现情况。其中,整数的二进制表示中的每一位表示一个字符是否出现。 + +我们简单地定义一个函数 $f(w)$,这个函数可以将一个字符串 $w$ 转换为一个整数。整数的二进制表示中的每一位表示一个字符是否出现。例如,字符串 `ab` 可以转换为整数 $3$,即二进制表示为 $11$。字符串 `abd` 可以转换为整数 $11$,即二进制表示为 $1011$。 + +回到题目上,判断一个字符串 $w$ 是否由 `allowed` 中的字符组成,就可以转换为:判断 $f(allowed)$ 和 $f(w)$ 进行按位或运算后的结果是否等于 $f(allowed)$。若是,答案加一。 + +时间复杂度 $O(m)$,其中 $m$ 为所有字符串的总长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def countConsistentStrings(self, allowed: str, words: List[str]) -> int: + def f(w): + return reduce(or_, (1 << (ord(c) - ord('a')) for c in w)) + + mask = f(allowed) + return sum((mask | f(w)) == mask for w in words) +``` + +```java +class Solution { + public int countConsistentStrings(String allowed, String[] words) { + int mask = f(allowed); + int ans = 0; + for (String w : words) { + if ((mask | f(w)) == mask) { + ++ans; + } + } + return ans; } - return res; -} -int countConsistentStrings(char* allowed, char** words, int wordsSize) { - int mask = helper(allowed); - int ans = 0; - for (int i = 0; i < wordsSize; i++) { - if ((mask | helper(words[i])) == mask) { - ans++; + private int f(String w) { + int mask = 0; + for (int i = 0; i < w.length(); ++i) { + mask |= 1 << (w.charAt(i) - 'a'); } + return mask; } - return ans; } ``` -### **TypeScript** - -```ts -function countConsistentStrings(allowed: string, words: string[]): number { - const set = new Set([...allowed]); - const n = words.length; - let ans = n; - for (const word of words) { - for (const c of word) { - if (!set.has(c)) { - ans--; - break; - } - } +```cpp +class Solution { +public: + int countConsistentStrings(string allowed, vector& words) { + auto f = [](string& w) { + int mask = 0; + for (auto& c : w) mask |= 1 << (c - 'a'); + return mask; + }; + int mask = f(allowed); + int ans = 0; + for (auto& w : words) ans += (mask | f(w)) == mask; + return ans; } - return ans; +}; +``` + +```go +func countConsistentStrings(allowed string, words []string) (ans int) { + f := func(w string) (mask int) { + for _, c := range w { + mask |= 1 << (c - 'a') + } + return + } + + mask := f(allowed) + for _, w := range words { + if (mask | f(w)) == mask { + ans++ + } + } + return } ``` @@ -310,30 +296,6 @@ function countConsistentStrings(allowed: string, words: string[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn count_consistent_strings(allowed: String, words: Vec) -> i32 { - let n = words.len(); - let mut make = [false; 26]; - for c in allowed.as_bytes() { - make[(c - b'a') as usize] = true; - } - let mut ans = n as i32; - for word in words.iter() { - for c in word.as_bytes().iter() { - if !make[(c - b'a') as usize] { - ans -= 1; - break; - } - } - } - ans - } -} -``` - ```rust impl Solution { fn helper(s: &String) -> i32 { @@ -357,10 +319,28 @@ impl Solution { } ``` -### **...** - -``` +```c +int helper(char* s) { + int res = 0; + int n = strlen(s); + for (int i = 0; i < n; i++) { + res |= 1 << (s[i] - 'a'); + } + return res; +} +int countConsistentStrings(char* allowed, char** words, int wordsSize) { + int mask = helper(allowed); + int ans = 0; + for (int i = 0; i < wordsSize; i++) { + if ((mask | helper(words[i])) == mask) { + ans++; + } + } + return ans; +} ``` + + diff --git a/solution/1600-1699/1684.Count the Number of Consistent Strings/README_EN.md b/solution/1600-1699/1684.Count the Number of Consistent Strings/README_EN.md index 8955025943bf1..21a7a68506a99 100644 --- a/solution/1600-1699/1684.Count the Number of Consistent Strings/README_EN.md +++ b/solution/1600-1699/1684.Count the Number of Consistent Strings/README_EN.md @@ -46,26 +46,14 @@ ## Solutions -**Solution 1: Hash Table or Array** +### Solution 1: Hash Table or Array A straightforward approach is to use a hash table or array $s$ to record the characters in `allowed`. Then iterate over the `words` array, for each string $w$, determine whether it is composed of characters in `allowed`. If so, increment the answer. The time complexity is $O(m)$, and the space complexity is $O(C)$. Here, $m$ is the total length of all strings, and $C$ is the size of the character set `allowed`. In this problem, $C \leq 26$. -**Solution 2: Bit Manipulation** - -We can also use a single integer to represent the occurrence of characters in each string. In this integer, each bit in the binary representation indicates whether a character appears. - -We simply define a function $f(w)$ that can convert a string $w$ into an integer. Each bit in the binary representation of the integer indicates whether a character appears. For example, the string `ab` can be converted into the integer $3$, which is represented in binary as $11$. The string `abd` can be converted into the integer $11$, which is represented in binary as $1011$. - -Back to the problem, to determine whether a string $w$ is composed of characters in `allowed`, we can check whether the result of the bitwise OR operation between $f(allowed)$ and $f(w)$ is equal to $f(allowed)$. If so, increment the answer. - -The time complexity is $O(m)$, where $m$ is the total length of all strings. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def countConsistentStrings(self, allowed: str, words: List[str]) -> int: @@ -73,18 +61,6 @@ class Solution: return sum(all(c in s for c in w) for w in words) ``` -```python -class Solution: - def countConsistentStrings(self, allowed: str, words: List[str]) -> int: - def f(w): - return reduce(or_, (1 << (ord(c) - ord('a')) for c in w)) - - mask = f(allowed) - return sum((mask | f(w)) == mask for w in words) -``` - -### **Java** - ```java class Solution { public int countConsistentStrings(String allowed, String[] words) { @@ -112,31 +88,6 @@ class Solution { } ``` -```java -class Solution { - public int countConsistentStrings(String allowed, String[] words) { - int mask = f(allowed); - int ans = 0; - for (String w : words) { - if ((mask | f(w)) == mask) { - ++ans; - } - } - return ans; - } - - private int f(String w) { - int mask = 0; - for (int i = 0; i < w.length(); ++i) { - mask |= 1 << (w.charAt(i) - 'a'); - } - return mask; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -155,25 +106,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countConsistentStrings(string allowed, vector& words) { - auto f = [](string& w) { - int mask = 0; - for (auto& c : w) mask |= 1 << (c - 'a'); - return mask; - }; - int mask = f(allowed); - int ans = 0; - for (auto& w : words) ans += (mask | f(w)) == mask; - return ans; - } -}; -``` - -### **Go** - ```go func countConsistentStrings(allowed string, words []string) (ans int) { s := [26]bool{} @@ -197,26 +129,44 @@ func countConsistentStrings(allowed string, words []string) (ans int) { } ``` -```go -func countConsistentStrings(allowed string, words []string) (ans int) { - f := func(w string) (mask int) { - for _, c := range w { - mask |= 1 << (c - 'a') - } - return - } - - mask := f(allowed) - for _, w := range words { - if (mask | f(w)) == mask { - ans++ - } - } - return +```ts +function countConsistentStrings(allowed: string, words: string[]): number { + const set = new Set([...allowed]); + const n = words.length; + let ans = n; + for (const word of words) { + for (const c of word) { + if (!set.has(c)) { + ans--; + break; + } + } + } + return ans; } ``` -### **C** +```rust +impl Solution { + pub fn count_consistent_strings(allowed: String, words: Vec) -> i32 { + let n = words.len(); + let mut make = [false; 26]; + for c in allowed.as_bytes() { + make[(c - b'a') as usize] = true; + } + let mut ans = n as i32; + for word in words.iter() { + for c in word.as_bytes().iter() { + if !make[(c - b'a') as usize] { + ans -= 1; + break; + } + } + } + ans + } +} +``` ```c int countConsistentStrings(char* allowed, char** words, int wordsSize) { @@ -239,44 +189,86 @@ int countConsistentStrings(char* allowed, char** words, int wordsSize) { } ``` -```c -int helper(char* s) { - int res = 0; - int n = strlen(s); - for (int i = 0; i < n; i++) { - res |= 1 << (s[i] - 'a'); + + +### Solution 2: Bit Manipulation + +We can also use a single integer to represent the occurrence of characters in each string. In this integer, each bit in the binary representation indicates whether a character appears. + +We simply define a function $f(w)$ that can convert a string $w$ into an integer. Each bit in the binary representation of the integer indicates whether a character appears. For example, the string `ab` can be converted into the integer $3$, which is represented in binary as $11$. The string `abd` can be converted into the integer $11$, which is represented in binary as $1011$. + +Back to the problem, to determine whether a string $w$ is composed of characters in `allowed`, we can check whether the result of the bitwise OR operation between $f(allowed)$ and $f(w)$ is equal to $f(allowed)$. If so, increment the answer. + +The time complexity is $O(m)$, where $m$ is the total length of all strings. The space complexity is $O(1)$. + + + +```python +class Solution: + def countConsistentStrings(self, allowed: str, words: List[str]) -> int: + def f(w): + return reduce(or_, (1 << (ord(c) - ord('a')) for c in w)) + + mask = f(allowed) + return sum((mask | f(w)) == mask for w in words) +``` + +```java +class Solution { + public int countConsistentStrings(String allowed, String[] words) { + int mask = f(allowed); + int ans = 0; + for (String w : words) { + if ((mask | f(w)) == mask) { + ++ans; + } + } + return ans; } - return res; -} -int countConsistentStrings(char* allowed, char** words, int wordsSize) { - int mask = helper(allowed); - int ans = 0; - for (int i = 0; i < wordsSize; i++) { - if ((mask | helper(words[i])) == mask) { - ans++; + private int f(String w) { + int mask = 0; + for (int i = 0; i < w.length(); ++i) { + mask |= 1 << (w.charAt(i) - 'a'); } + return mask; } - return ans; } ``` -### **TypeScript** - -```ts -function countConsistentStrings(allowed: string, words: string[]): number { - const set = new Set([...allowed]); - const n = words.length; - let ans = n; - for (const word of words) { - for (const c of word) { - if (!set.has(c)) { - ans--; - break; - } - } +```cpp +class Solution { +public: + int countConsistentStrings(string allowed, vector& words) { + auto f = [](string& w) { + int mask = 0; + for (auto& c : w) mask |= 1 << (c - 'a'); + return mask; + }; + int mask = f(allowed); + int ans = 0; + for (auto& w : words) ans += (mask | f(w)) == mask; + return ans; } - return ans; +}; +``` + +```go +func countConsistentStrings(allowed string, words []string) (ans int) { + f := func(w string) (mask int) { + for _, c := range w { + mask |= 1 << (c - 'a') + } + return + } + + mask := f(allowed) + for _, w := range words { + if (mask | f(w)) == mask { + ans++ + } + } + return } ``` @@ -300,30 +292,6 @@ function countConsistentStrings(allowed: string, words: string[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn count_consistent_strings(allowed: String, words: Vec) -> i32 { - let n = words.len(); - let mut make = [false; 26]; - for c in allowed.as_bytes() { - make[(c - b'a') as usize] = true; - } - let mut ans = n as i32; - for word in words.iter() { - for c in word.as_bytes().iter() { - if !make[(c - b'a') as usize] { - ans -= 1; - break; - } - } - } - ans - } -} -``` - ```rust impl Solution { fn helper(s: &String) -> i32 { @@ -347,10 +315,28 @@ impl Solution { } ``` -### **...** - -``` +```c +int helper(char* s) { + int res = 0; + int n = strlen(s); + for (int i = 0; i < n; i++) { + res |= 1 << (s[i] - 'a'); + } + return res; +} +int countConsistentStrings(char* allowed, char** words, int wordsSize) { + int mask = helper(allowed); + int ans = 0; + for (int i = 0; i < wordsSize; i++) { + if ((mask | helper(words[i])) == mask) { + ans++; + } + } + return ans; +} ``` + + diff --git a/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README.md b/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README.md index 408539f1915c3..2e3c967e71ff3 100644 --- a/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README.md +++ b/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README.md @@ -43,9 +43,7 @@ result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5。 ## 解法 - - -**方法一:求和 + 枚举** +### 方法一:求和 + 枚举 我们先求出数组 $nums$ 所有元素的和,记为 $s$,用变量 $t$ 记录当前已经枚举过的元素之和。 @@ -55,10 +53,6 @@ result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5。 -### **Python3** - - - ```python class Solution: def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]: @@ -71,10 +65,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] getSumAbsoluteDifferences(int[] nums) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func getSumAbsoluteDifferences(nums []int) (ans []int) { var s, t int @@ -131,8 +117,6 @@ func getSumAbsoluteDifferences(nums []int) (ans []int) { } ``` -### **TypeScript** - ```ts function getSumAbsoluteDifferences(nums: number[]): number[] { const s = nums.reduce((a, b) => a + b); @@ -148,29 +132,6 @@ function getSumAbsoluteDifferences(nums: number[]): number[] { } ``` -### **C#** - -```cs -public class Solution { - public int[] GetSumAbsoluteDifferences(int[] nums) { - int s = 0, t = 0; - foreach (int x in nums) { - s += x; - } - int n = nums.Length; - int[] ans = new int[n]; - for (int i = 0; i < n; ++i) { - int v = nums[i] * i - t + s - t - nums[i] * (n - i); - ans[i] = v; - t += nums[i]; - } - return ans; - } -} -``` - -### **JavaScript** - ```js /** * @param {number[]} nums @@ -190,10 +151,25 @@ var getSumAbsoluteDifferences = function (nums) { }; ``` -### **...** - -``` - +```cs +public class Solution { + public int[] GetSumAbsoluteDifferences(int[] nums) { + int s = 0, t = 0; + foreach (int x in nums) { + s += x; + } + int n = nums.Length; + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + int v = nums[i] * i - t + s - t - nums[i] * (n - i); + ans[i] = v; + t += nums[i]; + } + return ans; + } +} ``` + + diff --git a/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README_EN.md b/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README_EN.md index 8ddeb18d733fa..77efdb4ebb259 100644 --- a/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README_EN.md +++ b/solution/1600-1699/1685.Sum of Absolute Differences in a Sorted Array/README_EN.md @@ -39,7 +39,7 @@ result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5. ## Solutions -**Solution 1: Summation + Enumeration** +### Solution 1: Summation + Enumeration First, we calculate the sum of all elements in the array $nums$, denoted as $s$. We use a variable $t$ to record the sum of the elements that have been enumerated so far. @@ -49,8 +49,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]: @@ -63,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] getSumAbsoluteDifferences(int[] nums) { @@ -85,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +98,6 @@ public: }; ``` -### **Go** - ```go func getSumAbsoluteDifferences(nums []int) (ans []int) { var s, t int @@ -121,8 +113,6 @@ func getSumAbsoluteDifferences(nums []int) (ans []int) { } ``` -### **TypeScript** - ```ts function getSumAbsoluteDifferences(nums: number[]): number[] { const s = nums.reduce((a, b) => a + b); @@ -138,29 +128,6 @@ function getSumAbsoluteDifferences(nums: number[]): number[] { } ``` -### **C#** - -```cs -public class Solution { - public int[] GetSumAbsoluteDifferences(int[] nums) { - int s = 0, t = 0; - foreach (int x in nums) { - s += x; - } - int n = nums.Length; - int[] ans = new int[n]; - for (int i = 0; i < n; ++i) { - int v = nums[i] * i - t + s - t - nums[i] * (n - i); - ans[i] = v; - t += nums[i]; - } - return ans; - } -} -``` - -### **JavaScript** - ```js /** * @param {number[]} nums @@ -180,10 +147,25 @@ var getSumAbsoluteDifferences = function (nums) { }; ``` -### **...** - -``` - +```cs +public class Solution { + public int[] GetSumAbsoluteDifferences(int[] nums) { + int s = 0, t = 0; + foreach (int x in nums) { + s += x; + } + int n = nums.Length; + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + int v = nums[i] * i - t + s - t - nums[i] * (n - i); + ans[i] = v; + t += nums[i]; + } + return ans; + } +} ``` + + diff --git a/solution/1600-1699/1686.Stone Game VI/README.md b/solution/1600-1699/1686.Stone Game VI/README.md index 259cd2f0203ae..85be57c3c2957 100644 --- a/solution/1600-1699/1686.Stone Game VI/README.md +++ b/solution/1600-1699/1686.Stone Game VI/README.md @@ -68,9 +68,7 @@ Bob 会获胜。 ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 选取石头的最优化的策略是,让自己得分最高,同时让对手失分最多。因此,我们创建一个数组 `arr`,其中 `arr[i] = aliceValues[i] + bobValues[i]`,然后对 `arr` 进行降序排序。然后,我们从 `arr` 中取出石头,每次取出两个石头,分别给 Alice 和 Bob,直到 `arr` 中没有石头为止。最后,我们比较 Alice 和 Bob 的得分,得分高的人获胜。 @@ -78,10 +76,6 @@ Bob 会获胜。 -### **Python3** - - - ```python class Solution: def stoneGameVI(self, aliceValues: List[int], bobValues: List[int]) -> int: @@ -96,10 +90,6 @@ class Solution: return 0 ``` -### **Java** - - - ```java class Solution { public int stoneGameVI(int[] aliceValues, int[] bobValues) { @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func stoneGameVI(aliceValues []int, bobValues []int) int { arr := make([][]int, len(aliceValues)) @@ -181,10 +167,6 @@ func stoneGameVI(aliceValues []int, bobValues []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1686.Stone Game VI/README_EN.md b/solution/1600-1699/1686.Stone Game VI/README_EN.md index 2144944556eb1..1b674dade792f 100644 --- a/solution/1600-1699/1686.Stone Game VI/README_EN.md +++ b/solution/1600-1699/1686.Stone Game VI/README_EN.md @@ -64,7 +64,7 @@ Bob wins. ## Solutions -**Solution 1: Greedy + Sorting** +### Solution 1: Greedy + Sorting The optimal strategy for picking stones is to maximize one's own score while making the opponent lose as much as possible. Therefore, we create an array `arr`, where `arr[i] = aliceValues[i] + bobValues[i]`, and then sort `arr` in descending order. Then, we take stones from `arr`, taking two stones each time, one for Alice and one for Bob, until there are no stones left in `arr`. Finally, we compare the scores of Alice and Bob, and the person with the higher score wins. @@ -72,8 +72,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def stoneGameVI(self, aliceValues: List[int], bobValues: List[int]) -> int: @@ -88,8 +86,6 @@ class Solution: return 0 ``` -### **Java** - ```java class Solution { public int stoneGameVI(int[] aliceValues, int[] bobValues) { @@ -116,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +137,6 @@ public: }; ``` -### **Go** - ```go func stoneGameVI(aliceValues []int, bobValues []int) int { arr := make([][]int, len(aliceValues)) @@ -171,10 +163,6 @@ func stoneGameVI(aliceValues []int, bobValues []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README.md b/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README.md index d8731e450f4ca..01ebdbf1b965f 100644 --- a/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README.md +++ b/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README.md @@ -93,9 +93,7 @@ ## 解法 - - -**方法一:动态规划 + 单调队列优化** +### 方法一:动态规划 + 单调队列优化 我们定义 $f[i]$ 表示把前 $i$ 个箱子从仓库运送到相应码头的最少行程数,那么答案就是 $f[n]$。 @@ -237,10 +235,6 @@ $$ -### **Python3** - - - ```python class Solution: def boxDelivering( @@ -264,10 +258,6 @@ class Solution: return f[n] ``` -### **Java** - - - ```java class Solution { public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) { @@ -304,8 +294,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -334,8 +322,6 @@ public: }; ``` -### **Go** - ```go func boxDelivering(boxes [][]int, portsCount int, maxBoxes int, maxWeight int) int { n := len(boxes) @@ -372,10 +358,6 @@ func boxDelivering(boxes [][]int, portsCount int, maxBoxes int, maxWeight int) i } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README_EN.md b/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README_EN.md index 514b169e5a0f6..2296ed1aa1d1d 100644 --- a/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README_EN.md +++ b/solution/1600-1699/1687.Delivering Boxes from Storage to Ports/README_EN.md @@ -74,7 +74,7 @@ So the total number of trips is 2 + 2 + 2 = 6. ## Solutions -**Solution 1: Dynamic Programming + Monotonic Queue Optimization** +### Solution 1: Dynamic Programming + Monotonic Queue Optimization We define $f[i]$ as the minimum number of trips required to transport the first $i$ boxes from the warehouse to the corresponding docks, so the answer is $f[n]$. @@ -216,8 +216,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def boxDelivering( @@ -241,8 +239,6 @@ class Solution: return f[n] ``` -### **Java** - ```java class Solution { public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) { @@ -279,8 +275,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -309,8 +303,6 @@ public: }; ``` -### **Go** - ```go func boxDelivering(boxes [][]int, portsCount int, maxBoxes int, maxWeight int) int { n := len(boxes) @@ -347,10 +339,6 @@ func boxDelivering(boxes [][]int, portsCount int, maxBoxes int, maxWeight int) i } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1688.Count of Matches in Tournament/README.md b/solution/1600-1699/1688.Count of Matches in Tournament/README.md index c3b58ed8b0109..51fd0786c7a6c 100644 --- a/solution/1600-1699/1688.Count of Matches in Tournament/README.md +++ b/solution/1600-1699/1688.Count of Matches in Tournament/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 根据题目描述我们知道,一共有 $n$ 支队伍,每一次的配对,都会淘汰一支队伍,所以配对次数就是淘汰的队伍数,即 $n - 1$。 @@ -60,20 +58,12 @@ -### **Python3** - - - ```python class Solution: def numberOfMatches(self, n: int) -> int: return n - 1 ``` -### **Java** - - - ```java class Solution { public int numberOfMatches(int n) { @@ -82,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,15 +81,17 @@ public: }; ``` -### **Go** - ```go func numberOfMatches(n int) int { return n - 1 } ``` -### **JavaScript** +```ts +function numberOfMatches(n: number): number { + return n - 1; +} +``` ```js /** @@ -113,18 +103,6 @@ var numberOfMatches = function (n) { }; ``` -### **TypeScript** - -```ts -function numberOfMatches(n: number): number { - return n - 1; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1688.Count of Matches in Tournament/README_EN.md b/solution/1600-1699/1688.Count of Matches in Tournament/README_EN.md index e010bbf8300f6..4c3fdd6c6b222 100644 --- a/solution/1600-1699/1688.Count of Matches in Tournament/README_EN.md +++ b/solution/1600-1699/1688.Count of Matches in Tournament/README_EN.md @@ -48,7 +48,7 @@ Total number of matches = 7 + 3 + 2 + 1 = 13. ## Solutions -**Solution 1: Quick Thinking** +### Solution 1: Quick Thinking From the problem description, we know that there are $n$ teams in total. Each pairing will eliminate one team. Therefore, the number of pairings is equal to the number of teams eliminated, which is $n - 1$. @@ -56,16 +56,12 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def numberOfMatches(self, n: int) -> int: return n - 1 ``` -### **Java** - ```java class Solution { public int numberOfMatches(int n) { @@ -74,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -85,15 +79,17 @@ public: }; ``` -### **Go** - ```go func numberOfMatches(n int) int { return n - 1 } ``` -### **JavaScript** +```ts +function numberOfMatches(n: number): number { + return n - 1; +} +``` ```js /** @@ -105,18 +101,6 @@ var numberOfMatches = function (n) { }; ``` -### **TypeScript** - -```ts -function numberOfMatches(n: number): number { - return n - 1; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README.md b/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README.md index 096c65ba84b65..7c21db37a3478 100644 --- a/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README.md +++ b/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 题目等价于找字符串中的最大数。 @@ -53,20 +51,12 @@ -### **Python3** - - - ```python class Solution: def minPartitions(self, n: str) -> int: return int(max(n)) ``` -### **Java** - - - ```java class Solution { public int minPartitions(String n) { @@ -79,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -92,8 +80,6 @@ public: }; ``` -### **Go** - ```go func minPartitions(n string) (ans int) { for _, c := range n { @@ -105,8 +91,6 @@ func minPartitions(n string) (ans int) { } ``` -### **TypeScript** - ```ts function minPartitions(n: string): number { let nums = n.split('').map(d => parseInt(d)); @@ -115,8 +99,6 @@ function minPartitions(n: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_partitions(n: String) -> i32 { @@ -129,8 +111,6 @@ impl Solution { } ``` -### **C** - ```c int minPartitions(char* n) { int ans = 0; @@ -144,10 +124,6 @@ int minPartitions(char* n) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README_EN.md b/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README_EN.md index 83b2b13c1e64b..67369c2f32c5f 100644 --- a/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README_EN.md +++ b/solution/1600-1699/1689.Partitioning Into Minimum Number Of Deci-Binary Numbers/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Quick Thinking** +### Solution 1: Quick Thinking The problem is equivalent to finding the maximum number in the string. @@ -50,16 +50,12 @@ The time complexity is $O(n)$, where $n$ is the length of the string. The space -### **Python3** - ```python class Solution: def minPartitions(self, n: str) -> int: return int(max(n)) ``` -### **Java** - ```java class Solution { public int minPartitions(String n) { @@ -72,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -85,8 +79,6 @@ public: }; ``` -### **Go** - ```go func minPartitions(n string) (ans int) { for _, c := range n { @@ -98,8 +90,6 @@ func minPartitions(n string) (ans int) { } ``` -### **TypeScript** - ```ts function minPartitions(n: string): number { let nums = n.split('').map(d => parseInt(d)); @@ -108,8 +98,6 @@ function minPartitions(n: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_partitions(n: String) -> i32 { @@ -122,8 +110,6 @@ impl Solution { } ``` -### **C** - ```c int minPartitions(char* n) { int ans = 0; @@ -137,10 +123,6 @@ int minPartitions(char* n) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1690.Stone Game VII/README.md b/solution/1600-1699/1690.Stone Game VII/README.md index df90d3af94431..eba3f157f428c 100644 --- a/solution/1600-1699/1690.Stone Game VII/README.md +++ b/solution/1600-1699/1690.Stone Game VII/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们先预处理出前缀和数组 $s$,其中 $s[i]$ 表示前 $i$ 个石头的总和。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def stoneGameVII(self, stones: List[int]) -> int: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] s; @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go func stoneGameVII(stones []int) int { n := len(stones) @@ -179,10 +165,6 @@ func stoneGameVII(stones []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1690.Stone Game VII/README_EN.md b/solution/1600-1699/1690.Stone Game VII/README_EN.md index 42abd46bff4b7..0f211167ab0c4 100644 --- a/solution/1600-1699/1690.Stone Game VII/README_EN.md +++ b/solution/1600-1699/1690.Stone Game VII/README_EN.md @@ -44,7 +44,7 @@ The score difference is 18 - 12 = 6. ## Solutions -**Solution 1: Memorization Search** +### Solution 1: Memorization Search First, we preprocess to get the prefix sum array $s$, where $s[i]$ represents the total sum of the first $i$ stones. @@ -61,8 +61,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ -### **Python3** - ```python class Solution: def stoneGameVII(self, stones: List[int]) -> int: @@ -80,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] s; @@ -111,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +135,6 @@ public: }; ``` -### **Go** - ```go func stoneGameVII(stones []int) int { n := len(stones) @@ -169,10 +161,6 @@ func stoneGameVII(stones []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/README.md b/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/README.md index d41f920eb4a1c..0bfd0dd5f6c13 100644 --- a/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/README.md +++ b/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:排序 + 动态规划** +### 方法一:排序 + 动态规划 根据题目描述,长方体 $j$ 能够放在长方体 $i$ 上,当且仅当长方体 $j$ 的“长、宽、高”分别小于等于长方体 $i$ 的“长、宽、高”。 @@ -87,10 +85,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxHeight(self, cuboids: List[List[int]]) -> int: @@ -107,10 +101,6 @@ class Solution: return max(f) ``` -### **Java** - - - ```java class Solution { public int maxHeight(int[][] cuboids) { @@ -134,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func maxHeight(cuboids [][]int) int { for _, c := range cuboids { @@ -182,8 +168,6 @@ func maxHeight(cuboids [][]int) int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} cuboids @@ -211,10 +195,6 @@ var maxHeight = function (cuboids) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/README_EN.md b/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/README_EN.md index 82a9e018fb25d..625cc2c2edc66 100644 --- a/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/README_EN.md +++ b/solution/1600-1699/1691.Maximum Height by Stacking Cuboids/README_EN.md @@ -57,7 +57,7 @@ The maximum height of stacked cuboids is 6 * 17 = 102. ## Solutions -**Solution 1: Sorting + Dynamic Programming** +### Solution 1: Sorting + Dynamic Programming According to the problem description, box $j$ can be placed on box $i$ if and only if the "length, width, and height" of box $j$ are less than or equal to the "length, width, and height" of box $i$. @@ -81,8 +81,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ i -### **Python3** - ```python class Solution: def maxHeight(self, cuboids: List[List[int]]) -> int: @@ -99,8 +97,6 @@ class Solution: return max(f) ``` -### **Java** - ```java class Solution { public int maxHeight(int[][] cuboids) { @@ -124,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +141,6 @@ public: }; ``` -### **Go** - ```go func maxHeight(cuboids [][]int) int { for _, c := range cuboids { @@ -172,8 +164,6 @@ func maxHeight(cuboids [][]int) int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} cuboids @@ -201,10 +191,6 @@ var maxHeight = function (cuboids) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1692.Count Ways to Distribute Candies/README.md b/solution/1600-1699/1692.Count Ways to Distribute Candies/README.md index 6fcb52db1116d..3995bf4945ec5 100644 --- a/solution/1600-1699/1692.Count Ways to Distribute Candies/README.md +++ b/solution/1600-1699/1692.Count Ways to Distribute Candies/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示将 $i$ 个糖果分配给 $j$ 个手袋的不同分配方式的数量。初始时 $f[0][0]=1$,答案为 $f[n][k]$。 @@ -80,10 +78,6 @@ $$ -### **Python3** - - - ```python class Solution: def waysToDistribute(self, n: int, k: int) -> int: @@ -96,10 +90,6 @@ class Solution: return f[n][k] ``` -### **Java** - - - ```java class Solution { public int waysToDistribute(int n, int k) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func waysToDistribute(n int, k int) int { f := make([][]int, n+1) @@ -155,8 +141,6 @@ func waysToDistribute(n int, k int) int { } ``` -### **TypeScript** - ```ts function waysToDistribute(n: number, k: number): number { const mod = 10 ** 9 + 7; @@ -173,10 +157,6 @@ function waysToDistribute(n: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1692.Count Ways to Distribute Candies/README_EN.md b/solution/1600-1699/1692.Count Ways to Distribute Candies/README_EN.md index ce13975d87e49..6786dd7425b80 100644 --- a/solution/1600-1699/1692.Count Ways to Distribute Candies/README_EN.md +++ b/solution/1600-1699/1692.Count Ways to Distribute Candies/README_EN.md @@ -58,7 +58,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ as the number of different ways to distribute $i$ candies to $j$ bags. Initially, $f[0][0]=1$, and the answer is $f[n][k]$. @@ -74,8 +74,6 @@ The time complexity is $O(n \times k)$, and the space complexity is $O(n \times -### **Python3** - ```python class Solution: def waysToDistribute(self, n: int, k: int) -> int: @@ -88,8 +86,6 @@ class Solution: return f[n][k] ``` -### **Java** - ```java class Solution { public int waysToDistribute(int n, int k) { @@ -106,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +120,6 @@ public: }; ``` -### **Go** - ```go func waysToDistribute(n int, k int) int { f := make([][]int, n+1) @@ -145,8 +137,6 @@ func waysToDistribute(n int, k int) int { } ``` -### **TypeScript** - ```ts function waysToDistribute(n: number, k: number): number { const mod = 10 ** 9 + 7; @@ -163,10 +153,6 @@ function waysToDistribute(n: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1693.Daily Leads and Partners/README.md b/solution/1600-1699/1693.Daily Leads and Partners/README.md index 6c6f8fa0bc8d6..58deef52464da 100644 --- a/solution/1600-1699/1693.Daily Leads and Partners/README.md +++ b/solution/1600-1699/1693.Daily Leads and Partners/README.md @@ -65,16 +65,12 @@ DailySales 表: ## 解法 - - -**方法一:分组统计** +### 方法一:分组统计 我们可以使用 `GROUP BY` 语句,按照 `date_id` 和 `make_name` 字段进行分组,然后使用 `COUNT(DISTINCT)` 函数,统计 `lead_id` 和 `partner_id` 的不同值的数量。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -87,3 +83,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/1600-1699/1693.Daily Leads and Partners/README_EN.md b/solution/1600-1699/1693.Daily Leads and Partners/README_EN.md index 3c12283ae9a53..21e5ad8c7359d 100644 --- a/solution/1600-1699/1693.Daily Leads and Partners/README_EN.md +++ b/solution/1600-1699/1693.Daily Leads and Partners/README_EN.md @@ -64,14 +64,12 @@ For 2020-12-7, toyota gets leads = [0] and partners = [1, 2] while honda gets le ## Solutions -**Solution 1: Group By + Count Distinct** +### Solution 1: Group By + Count Distinct We can use the `GROUP BY` statement to group the data by the `date_id` and `make_name` fields, and then use the `COUNT(DISTINCT)` function to count the number of distinct values for `lead_id` and `partner_id`. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -84,3 +82,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/1600-1699/1694.Reformat Phone Number/README.md b/solution/1600-1699/1694.Reformat Phone Number/README.md index 16d2e32fa98ed..84a102ff88458 100644 --- a/solution/1600-1699/1694.Reformat Phone Number/README.md +++ b/solution/1600-1699/1694.Reformat Phone Number/README.md @@ -85,9 +85,7 @@ ## 解法 - - -**方法一:简单模拟** +### 方法一:简单模拟 我们先按照题意,去除字符串中的所有空格和破折号。 @@ -101,10 +99,6 @@ -### **Python3** - - - ```python class Solution: def reformatNumber(self, number: str) -> str: @@ -119,10 +113,6 @@ class Solution: return "-".join(ans) ``` -### **Java** - - - ```java class Solution { public String reformatNumber(String number) { @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -177,8 +165,6 @@ public: }; ``` -### **Go** - ```go func reformatNumber(number string) string { number = strings.ReplaceAll(number, " ", "") @@ -198,8 +184,6 @@ func reformatNumber(number string) string { } ``` -### **TypeScript** - ```ts function reformatNumber(number: string): string { const cs = [...number].filter(c => c !== ' ' && c !== '-'); @@ -215,8 +199,6 @@ function reformatNumber(number: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn reformat_number(number: String) -> String { @@ -238,10 +220,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1694.Reformat Phone Number/README_EN.md b/solution/1600-1699/1694.Reformat Phone Number/README_EN.md index 47b0fcf8a4f5e..1c3c56178e5af 100644 --- a/solution/1600-1699/1694.Reformat Phone Number/README_EN.md +++ b/solution/1600-1699/1694.Reformat Phone Number/README_EN.md @@ -64,7 +64,7 @@ Joining the blocks gives "123-456-78". ## Solutions -**Solution 1: Simple Simulation** +### Solution 1: Simple Simulation First, according to the problem description, we remove all spaces and hyphens from the string. @@ -78,8 +78,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def reformatNumber(self, number: str) -> str: @@ -94,8 +92,6 @@ class Solution: return "-".join(ans) ``` -### **Java** - ```java class Solution { public String reformatNumber(String number) { @@ -116,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +144,6 @@ public: }; ``` -### **Go** - ```go func reformatNumber(number string) string { number = strings.ReplaceAll(number, " ", "") @@ -171,8 +163,6 @@ func reformatNumber(number string) string { } ``` -### **TypeScript** - ```ts function reformatNumber(number: string): string { const cs = [...number].filter(c => c !== ' ' && c !== '-'); @@ -188,8 +178,6 @@ function reformatNumber(number: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn reformat_number(number: String) -> String { @@ -211,10 +199,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1695.Maximum Erasure Value/README.md b/solution/1600-1699/1695.Maximum Erasure Value/README.md index 12dd265db16cc..656e154e0ef56 100644 --- a/solution/1600-1699/1695.Maximum Erasure Value/README.md +++ b/solution/1600-1699/1695.Maximum Erasure Value/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:数组或哈希表 + 前缀和** +### 方法一:数组或哈希表 + 前缀和 我们用数组或哈希表 $d$ 记录每个数字最后一次出现的位置,用 $s$ 记录前缀和,用 $j$ 记录当前不重复子数组的左端点。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumUniqueSubarray(int[] nums) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func maximumUniqueSubarray(nums []int) (ans int) { d := [10001]int{} @@ -140,8 +126,6 @@ func maximumUniqueSubarray(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function maximumUniqueSubarray(nums: number[]): number { const m = Math.max(...nums); @@ -161,10 +145,6 @@ function maximumUniqueSubarray(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1695.Maximum Erasure Value/README_EN.md b/solution/1600-1699/1695.Maximum Erasure Value/README_EN.md index a9adb5e203913..dbe4651b19167 100644 --- a/solution/1600-1699/1695.Maximum Erasure Value/README_EN.md +++ b/solution/1600-1699/1695.Maximum Erasure Value/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: Array or Hash Table + Prefix Sum** +### Solution 1: Array or Hash Table + Prefix Sum We use an array or hash table $d$ to record the last occurrence of each number, use $s$ to record the prefix sum, and use $j$ to record the left endpoint of the current non-repeating subarray. @@ -47,8 +47,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: @@ -62,8 +60,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumUniqueSubarray(int[] nums) { @@ -85,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func maximumUniqueSubarray(nums []int) (ans int) { d := [10001]int{} @@ -130,8 +122,6 @@ func maximumUniqueSubarray(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function maximumUniqueSubarray(nums: number[]): number { const m = Math.max(...nums); @@ -151,10 +141,6 @@ function maximumUniqueSubarray(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1696.Jump Game VI/README.md b/solution/1600-1699/1696.Jump Game VI/README.md index a4125f1d0a91b..413fc8d92448a 100644 --- a/solution/1600-1699/1696.Jump Game VI/README.md +++ b/solution/1600-1699/1696.Jump Game VI/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:动态规划 + 单调队列优化** +### 方法一:动态规划 + 单调队列优化 我们定义 $f[i]$ 表示到达下标 $i$ 的最大得分,那么 $f[i]$ 的值可以从 $f[j]$ 转移而来,其中 $j$ 满足 $i - k \leq j \leq i - 1$。因此我们可以使用动态规划求解。 @@ -68,10 +66,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxResult(self, nums: List[int], k: int) -> int: @@ -88,10 +82,6 @@ class Solution: return f[-1] ``` -### **Java** - - - ```java class Solution { public int maxResult(int[] nums, int k) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func maxResult(nums []int, k int) int { n := len(nums) @@ -156,10 +142,6 @@ func maxResult(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1696.Jump Game VI/README_EN.md b/solution/1600-1699/1696.Jump Game VI/README_EN.md index bc2b29d3aff27..55ed130153870 100644 --- a/solution/1600-1699/1696.Jump Game VI/README_EN.md +++ b/solution/1600-1699/1696.Jump Game VI/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Dynamic Programming + Monotonic Queue Optimization** +### Solution 1: Dynamic Programming + Monotonic Queue Optimization We define $f[i]$ as the maximum score when reaching index $i$. The value of $f[i]$ can be transferred from $f[j]$, where $j$ satisfies $i - k \leq j \leq i - 1$. Therefore, we can use dynamic programming to solve this problem. @@ -62,8 +62,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maxResult(self, nums: List[int], k: int) -> int: @@ -80,8 +78,6 @@ class Solution: return f[-1] ``` -### **Java** - ```java class Solution { public int maxResult(int[] nums, int k) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +119,6 @@ public: }; ``` -### **Go** - ```go func maxResult(nums []int, k int) int { n := len(nums) @@ -146,10 +138,6 @@ func maxResult(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1697.Checking Existence of Edge Length Limited Paths/README.md b/solution/1600-1699/1697.Checking Existence of Edge Length Limited Paths/README.md index 7a6cfa441e5f2..e0b51d0efacfb 100644 --- a/solution/1600-1699/1697.Checking Existence of Edge Length Limited Paths/README.md +++ b/solution/1600-1699/1697.Checking Existence of Edge Length Limited Paths/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:离线查询 + 并查集** +### 方法一:离线查询 + 并查集 根据题目要求,我们需要对每个查询 $queries[i]$ 进行判断,即判断当前查询的两个点 $a$ 和 $b$ 之间是否存在一条边权小于等于 $limit$ 的路径。 @@ -173,10 +171,6 @@ func union(a, b int) { -### **Python3** - - - ```python class Solution: def distanceLimitedPathsExist( @@ -200,10 +194,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -243,8 +233,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -276,7 +264,40 @@ public: }; ``` -### **Rust** +```go +func distanceLimitedPathsExist(n int, edgeList [][]int, queries [][]int) []bool { + p := make([]int, n) + for i := range p { + p[i] = i + } + sort.Slice(edgeList, func(i, j int) bool { return edgeList[i][2] < edgeList[j][2] }) + var find func(int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + m := len(queries) + qid := make([]int, m) + ans := make([]bool, m) + for i := range qid { + qid[i] = i + } + sort.Slice(qid, func(i, j int) bool { return queries[qid[i]][2] < queries[qid[j]][2] }) + j := 0 + for _, i := range qid { + a, b, limit := queries[i][0], queries[i][1], queries[i][2] + for j < len(edgeList) && edgeList[j][2] < limit { + u, v := edgeList[j][0], edgeList[j][1] + p[find(u)] = find(v) + j++ + } + ans[i] = find(a) == find(b) + } + return ans +} +``` ```rust impl Solution { @@ -353,47 +374,6 @@ impl Solution { } ``` -### **Go** - -```go -func distanceLimitedPathsExist(n int, edgeList [][]int, queries [][]int) []bool { - p := make([]int, n) - for i := range p { - p[i] = i - } - sort.Slice(edgeList, func(i, j int) bool { return edgeList[i][2] < edgeList[j][2] }) - var find func(int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - m := len(queries) - qid := make([]int, m) - ans := make([]bool, m) - for i := range qid { - qid[i] = i - } - sort.Slice(qid, func(i, j int) bool { return queries[qid[i]][2] < queries[qid[j]][2] }) - j := 0 - for _, i := range qid { - a, b, limit := queries[i][0], queries[i][1], queries[i][2] - for j < len(edgeList) && edgeList[j][2] < limit { - u, v := edgeList[j][0], edgeList[j][1] - p[find(u)] = find(v) - j++ - } - ans[i] = find(a) == find(b) - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1697.Checking Existence of Edge Length Limited Paths/README_EN.md b/solution/1600-1699/1697.Checking Existence of Edge Length Limited Paths/README_EN.md index f27d93437a441..1297221b79953 100644 --- a/solution/1600-1699/1697.Checking Existence of Edge Length Limited Paths/README_EN.md +++ b/solution/1600-1699/1697.Checking Existence of Edge Length Limited Paths/README_EN.md @@ -46,12 +46,10 @@ For the second query, there is a path (0 -> 1 -> 2) of two edges with dist ## Solutions -Union find. +### Solution 1 -### **Python3** - ```python class Solution: def distanceLimitedPathsExist( @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] p; @@ -116,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,7 +143,40 @@ public: }; ``` -### **Rust** +```go +func distanceLimitedPathsExist(n int, edgeList [][]int, queries [][]int) []bool { + p := make([]int, n) + for i := range p { + p[i] = i + } + sort.Slice(edgeList, func(i, j int) bool { return edgeList[i][2] < edgeList[j][2] }) + var find func(int) int + find = func(x int) int { + if p[x] != x { + p[x] = find(p[x]) + } + return p[x] + } + m := len(queries) + qid := make([]int, m) + ans := make([]bool, m) + for i := range qid { + qid[i] = i + } + sort.Slice(qid, func(i, j int) bool { return queries[qid[i]][2] < queries[qid[j]][2] }) + j := 0 + for _, i := range qid { + a, b, limit := queries[i][0], queries[i][1], queries[i][2] + for j < len(edgeList) && edgeList[j][2] < limit { + u, v := edgeList[j][0], edgeList[j][1] + p[find(u)] = find(v) + j++ + } + ans[i] = find(a) == find(b) + } + return ans +} +``` ```rust impl Solution { @@ -226,47 +253,6 @@ impl Solution { } ``` -### **Go** - -```go -func distanceLimitedPathsExist(n int, edgeList [][]int, queries [][]int) []bool { - p := make([]int, n) - for i := range p { - p[i] = i - } - sort.Slice(edgeList, func(i, j int) bool { return edgeList[i][2] < edgeList[j][2] }) - var find func(int) int - find = func(x int) int { - if p[x] != x { - p[x] = find(p[x]) - } - return p[x] - } - m := len(queries) - qid := make([]int, m) - ans := make([]bool, m) - for i := range qid { - qid[i] = i - } - sort.Slice(qid, func(i, j int) bool { return queries[qid[i]][2] < queries[qid[j]][2] }) - j := 0 - for _, i := range qid { - a, b, limit := queries[i][0], queries[i][1], queries[i][2] - for j < len(edgeList) && edgeList[j][2] < limit { - u, v := edgeList[j][0], edgeList[j][1] - p[find(u)] = find(v) - j++ - } - ans[i] = find(a) == find(b) - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1698.Number of Distinct Substrings in a String/README.md b/solution/1600-1699/1698.Number of Distinct Substrings in a String/README.md index d58bfc4cbde58..984b179d3e8b1 100644 --- a/solution/1600-1699/1698.Number of Distinct Substrings in a String/README.md +++ b/solution/1600-1699/1698.Number of Distinct Substrings in a String/README.md @@ -40,15 +40,69 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 枚举所有子串,使用哈希表记录不同子串的个数。 时间复杂度 $O(n^3)$,空间复杂度 $O(n^2)$。其中 $n$ 为字符串长度。 -**方法二:字符串哈希** + + +```python +class Solution: + def countDistinct(self, s: str) -> int: + n = len(s) + return len({s[i:j] for i in range(n) for j in range(i + 1, n + 1)}) +``` + +```java +class Solution { + public int countDistinct(String s) { + Set ss = new HashSet<>(); + int n = s.length(); + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j <= n; ++j) { + ss.add(s.substring(i, j)); + } + } + return ss.size(); + } +} +``` + +```cpp +class Solution { +public: + int countDistinct(string s) { + unordered_set ss; + int n = s.size(); + string_view t, v = s; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j <= n; ++j) { + t = v.substr(i, j - i); + ss.insert(t); + } + } + return ss.size(); + } +}; +``` + +```go +func countDistinct(s string) int { + ss := map[string]struct{}{} + for i := range s { + for j := i + 1; j <= len(s); j++ { + ss[s[i:j]] = struct{}{} + } + } + return len(ss) +} +``` + + + +### 方法二:字符串哈希 **字符串哈希**是把一个任意长度的字符串映射成一个非负整数,并且其冲突的概率几乎为 0。字符串哈希用于计算字符串哈希值,快速判断两个字符串是否相等。 @@ -62,17 +116,6 @@ -### **Python3** - - - -```python -class Solution: - def countDistinct(self, s: str) -> int: - n = len(s) - return len({s[i:j] for i in range(n) for j in range(i + 1, n + 1)}) -``` - ```python class Solution: def countDistinct(self, s: str) -> int: @@ -92,25 +135,6 @@ class Solution: return len(ss) ``` -### **Java** - - - -```java -class Solution { - public int countDistinct(String s) { - Set ss = new HashSet<>(); - int n = s.length(); - for (int i = 0; i < n; ++i) { - for (int j = i + 1; j <= n; ++j) { - ss.add(s.substring(i, j)); - } - } - return ss.size(); - } -} -``` - ```java class Solution { public int countDistinct(String s) { @@ -135,26 +159,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int countDistinct(string s) { - unordered_set ss; - int n = s.size(); - string_view t, v = s; - for (int i = 0; i < n; ++i) { - for (int j = i + 1; j <= n; ++j) { - t = v.substr(i, j - i); - ss.insert(t); - } - } - return ss.size(); - } -}; -``` - ```cpp class Solution { public: @@ -180,20 +184,6 @@ public: }; ``` -### **Go** - -```go -func countDistinct(s string) int { - ss := map[string]struct{}{} - for i := range s { - for j := i + 1; j <= len(s); j++ { - ss[s[i:j]] = struct{}{} - } - } - return len(ss) -} -``` - ```go func countDistinct(s string) int { n := len(s) @@ -215,10 +205,6 @@ func countDistinct(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1698.Number of Distinct Substrings in a String/README_EN.md b/solution/1600-1699/1698.Number of Distinct Substrings in a String/README_EN.md index 7ed32b5830f4b..f433fa7f43c65 100644 --- a/solution/1600-1699/1698.Number of Distinct Substrings in a String/README_EN.md +++ b/solution/1600-1699/1698.Number of Distinct Substrings in a String/README_EN.md @@ -37,13 +37,69 @@ ## Solutions -**Solution 1: Brute Force Enumeration** +### Solution 1: Brute Force Enumeration Enumerate all substrings and use a hash table to record the count of different substrings. The time complexity is $O(n^3)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string. -**Solution 2: String Hashing** + + +```python +class Solution: + def countDistinct(self, s: str) -> int: + n = len(s) + return len({s[i:j] for i in range(n) for j in range(i + 1, n + 1)}) +``` + +```java +class Solution { + public int countDistinct(String s) { + Set ss = new HashSet<>(); + int n = s.length(); + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j <= n; ++j) { + ss.add(s.substring(i, j)); + } + } + return ss.size(); + } +} +``` + +```cpp +class Solution { +public: + int countDistinct(string s) { + unordered_set ss; + int n = s.size(); + string_view t, v = s; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j <= n; ++j) { + t = v.substr(i, j - i); + ss.insert(t); + } + } + return ss.size(); + } +}; +``` + +```go +func countDistinct(s string) int { + ss := map[string]struct{}{} + for i := range s { + for j := i + 1; j <= len(s); j++ { + ss[s[i:j]] = struct{}{} + } + } + return len(ss) +} +``` + + + +### Solution 2: String Hashing **String hashing** is a method to map a string of any length to a non-negative integer, and the probability of collision is almost zero. String hashing is used to calculate the hash value of a string, which can quickly determine whether two strings are equal. @@ -57,15 +113,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ -### **Python3** - -```python -class Solution: - def countDistinct(self, s: str) -> int: - n = len(s) - return len({s[i:j] for i in range(n) for j in range(i + 1, n + 1)}) -``` - ```python class Solution: def countDistinct(self, s: str) -> int: @@ -85,23 +132,6 @@ class Solution: return len(ss) ``` -### **Java** - -```java -class Solution { - public int countDistinct(String s) { - Set ss = new HashSet<>(); - int n = s.length(); - for (int i = 0; i < n; ++i) { - for (int j = i + 1; j <= n; ++j) { - ss.add(s.substring(i, j)); - } - } - return ss.size(); - } -} -``` - ```java class Solution { public int countDistinct(String s) { @@ -126,26 +156,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int countDistinct(string s) { - unordered_set ss; - int n = s.size(); - string_view t, v = s; - for (int i = 0; i < n; ++i) { - for (int j = i + 1; j <= n; ++j) { - t = v.substr(i, j - i); - ss.insert(t); - } - } - return ss.size(); - } -}; -``` - ```cpp class Solution { public: @@ -171,20 +181,6 @@ public: }; ``` -### **Go** - -```go -func countDistinct(s string) int { - ss := map[string]struct{}{} - for i := range s { - for j := i + 1; j <= len(s); j++ { - ss[s[i:j]] = struct{}{} - } - } - return len(ss) -} -``` - ```go func countDistinct(s string) int { n := len(s) @@ -206,10 +202,6 @@ func countDistinct(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1600-1699/1699.Number of Calls Between Two Persons/README.md b/solution/1600-1699/1699.Number of Calls Between Two Persons/README.md index eee1f6c3e29bd..e2fb0bcb58e67 100644 --- a/solution/1600-1699/1699.Number of Calls Between Two Persons/README.md +++ b/solution/1600-1699/1699.Number of Calls Between Two Persons/README.md @@ -62,16 +62,12 @@ Calls 表: ## 解法 - - -**方法一:分组求和统计** +### 方法一:分组求和统计 我们可以用 `if` 函数或者 `least` 和 `greatest` 函数来将 `from_id` 和 `to_id` 转换成 `person1` 和 `person2`,然后按照 `person1` 和 `person2` 分组求和统计即可。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -83,6 +79,12 @@ FROM Calls GROUP BY 1, 2; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below SELECT @@ -95,3 +97,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/1600-1699/1699.Number of Calls Between Two Persons/README_EN.md b/solution/1600-1699/1699.Number of Calls Between Two Persons/README_EN.md index 83437f0a5ecd1..38e8d73163f5d 100644 --- a/solution/1600-1699/1699.Number of Calls Between Two Persons/README_EN.md +++ b/solution/1600-1699/1699.Number of Calls Between Two Persons/README_EN.md @@ -60,14 +60,12 @@ Users 3 and 4 had 4 calls and the total duration is 999 (100 + 200 + 200 + 499). ## Solutions -**Solution 1: Grouping and Summing** +### Solution 1: Grouping and Summing We can use the `if` function or the `least` and `greatest` functions to convert `from_id` and `to_id` into `person1` and `person2`, and then group by `person1` and `person2` and sum the values. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -79,6 +77,12 @@ FROM Calls GROUP BY 1, 2; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below SELECT @@ -91,3 +95,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README.md b/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README.md index f9db8488fcd89..c9c2092e82760 100644 --- a/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README.md +++ b/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们观察发现,学生位置可调整,而三明治位置不可调整。也就是说,若前面的三明治没被拿走,则往后的所有三明治也无法被拿走。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: @@ -86,10 +80,6 @@ class Solution: return 0 ``` -### **Java** - - - ```java class Solution { public int countStudents(int[] students, int[] sandwiches) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func countStudents(students []int, sandwiches []int) int { cnt := [2]int{} @@ -143,27 +129,6 @@ func countStudents(students []int, sandwiches []int) int { } ``` -### **C** - -```c -int countStudents(int* students, int studentsSize, int* sandwiches, int sandwichesSize) { - int count[2] = {0}; - for (int i = 0; i < studentsSize; i++) { - count[students[i]]++; - } - for (int i = 0; i < sandwichesSize; i++) { - int j = sandwiches[i]; - if (count[j] == 0) { - return count[j ^ 1]; - } - count[j]--; - } - return 0; -} -``` - -### **TypeScript** - ```ts function countStudents(students: number[], sandwiches: number[]): number { const count = [0, 0]; @@ -180,8 +145,6 @@ function countStudents(students: number[], sandwiches: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_students(students: Vec, sandwiches: Vec) -> i32 { @@ -201,10 +164,23 @@ impl Solution { } ``` -### **...** - -``` - +```c +int countStudents(int* students, int studentsSize, int* sandwiches, int sandwichesSize) { + int count[2] = {0}; + for (int i = 0; i < studentsSize; i++) { + count[students[i]]++; + } + for (int i = 0; i < sandwichesSize; i++) { + int j = sandwiches[i]; + if (count[j] == 0) { + return count[j ^ 1]; + } + count[j]--; + } + return 0; +} ``` + + diff --git a/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README_EN.md b/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README_EN.md index 187d84453332f..917550e02aa81 100644 --- a/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README_EN.md +++ b/solution/1700-1799/1700.Number of Students Unable to Eat Lunch/README_EN.md @@ -54,7 +54,7 @@ Hence all students are able to eat. ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We observe that the positions of the students can be adjusted, but the positions of the sandwiches cannot be adjusted. That is to say, if the sandwich in front is not taken, then all the sandwiches behind cannot be taken. @@ -68,8 +68,6 @@ The time complexity is $O(n)$, where $n$ is the number of sandwiches. The space -### **Python3** - ```python class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: @@ -81,8 +79,6 @@ class Solution: return 0 ``` -### **Java** - ```java class Solution { public int countStudents(int[] students, int[] sandwiches) { @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func countStudents(students []int, sandwiches []int) int { cnt := [2]int{} @@ -136,27 +128,6 @@ func countStudents(students []int, sandwiches []int) int { } ``` -### **C** - -```c -int countStudents(int* students, int studentsSize, int* sandwiches, int sandwichesSize) { - int count[2] = {0}; - for (int i = 0; i < studentsSize; i++) { - count[students[i]]++; - } - for (int i = 0; i < sandwichesSize; i++) { - int j = sandwiches[i]; - if (count[j] == 0) { - return count[j ^ 1]; - } - count[j]--; - } - return 0; -} -``` - -### **TypeScript** - ```ts function countStudents(students: number[], sandwiches: number[]): number { const count = [0, 0]; @@ -173,8 +144,6 @@ function countStudents(students: number[], sandwiches: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_students(students: Vec, sandwiches: Vec) -> i32 { @@ -194,10 +163,23 @@ impl Solution { } ``` -### **...** - -``` - +```c +int countStudents(int* students, int studentsSize, int* sandwiches, int sandwichesSize) { + int count[2] = {0}; + for (int i = 0; i < studentsSize; i++) { + count[students[i]]++; + } + for (int i = 0; i < sandwichesSize; i++) { + int j = sandwiches[i]; + if (count[j] == 0) { + return count[j ^ 1]; + } + count[j]--; + } + return 0; +} ``` + + diff --git a/solution/1700-1799/1701.Average Waiting Time/README.md b/solution/1700-1799/1701.Average Waiting Time/README.md index c7c6d27c2c5c9..b204313e821c8 100644 --- a/solution/1700-1799/1701.Average Waiting Time/README.md +++ b/solution/1700-1799/1701.Average Waiting Time/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们用变量 `tot` 记录顾客的总等待时间,用变量 `t` 记录做完每个顾客的订单的时间,初始值均为 $0$。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def averageWaitingTime(self, customers: List[List[int]]) -> float: @@ -86,10 +80,6 @@ class Solution: return tot / len(customers) ``` -### **Java** - - - ```java class Solution { public double averageWaitingTime(int[][] customers) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func averageWaitingTime(customers [][]int) float64 { tot, t := 0, 0 @@ -137,10 +123,6 @@ func averageWaitingTime(customers [][]int) float64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1701.Average Waiting Time/README_EN.md b/solution/1700-1799/1701.Average Waiting Time/README_EN.md index 42fc8327724e6..3a629dc8554cf 100644 --- a/solution/1700-1799/1701.Average Waiting Time/README_EN.md +++ b/solution/1700-1799/1701.Average Waiting Time/README_EN.md @@ -52,7 +52,7 @@ So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We use a variable `tot` to record the total waiting time of the customers, and a variable `t` to record the time when each customer's order is completed. The initial values of both are $0$. @@ -66,8 +66,6 @@ The time complexity is $O(n)$, where $n$ is the length of the customer array `cu -### **Python3** - ```python class Solution: def averageWaitingTime(self, customers: List[List[int]]) -> float: @@ -78,8 +76,6 @@ class Solution: return tot / len(customers) ``` -### **Java** - ```java class Solution { public double averageWaitingTime(int[][] customers) { @@ -95,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +107,6 @@ public: }; ``` -### **Go** - ```go func averageWaitingTime(customers [][]int) float64 { tot, t := 0, 0 @@ -127,10 +119,6 @@ func averageWaitingTime(customers [][]int) float64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1702.Maximum Binary String After Change/README.md b/solution/1700-1799/1702.Maximum Binary String After Change/README.md index bcbf3be939470..4045482998ca4 100644 --- a/solution/1700-1799/1702.Maximum Binary String After Change/README.md +++ b/solution/1700-1799/1702.Maximum Binary String After Change/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 我们观察发现,操作 2 可以把所有的 $1$ 都移动到字符串的末尾,而操作 1 可以把所有的 `0000..000` 串变为 `111..110`。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def maximumBinaryString(self, binary: str) -> str: @@ -83,10 +77,6 @@ class Solution: return '1' * k + '0' + '1' * (len(binary) - k - 1) ``` -### **Java** - - - ```java class Solution { public String maximumBinaryString(String binary) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func maximumBinaryString(binary string) string { k := strings.IndexByte(binary, '0') @@ -149,10 +135,6 @@ func maximumBinaryString(binary string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1702.Maximum Binary String After Change/README_EN.md b/solution/1700-1799/1702.Maximum Binary String After Change/README_EN.md index 6420fbabbf7a6..b92c91c101352 100644 --- a/solution/1700-1799/1702.Maximum Binary String After Change/README_EN.md +++ b/solution/1700-1799/1702.Maximum Binary String After Change/README_EN.md @@ -53,7 +53,7 @@ ## Solutions -**Solution 1: Quick Thinking** +### Solution 1: Quick Thinking We observe that operation 2 can move all $1$s to the end of the string, and operation 1 can change all `0000..000` strings to `111..110`. @@ -63,8 +63,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string `binary`. I -### **Python3** - ```python class Solution: def maximumBinaryString(self, binary: str) -> str: @@ -75,8 +73,6 @@ class Solution: return '1' * k + '0' + '1' * (len(binary) - k - 1) ``` -### **Java** - ```java class Solution { public String maximumBinaryString(String binary) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func maximumBinaryString(binary string) string { k := strings.IndexByte(binary, '0') @@ -139,10 +131,6 @@ func maximumBinaryString(binary string) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README.md b/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README.md index e7ff6870f5b6b..ed40a79fcc18a 100644 --- a/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README.md +++ b/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:前缀和 + 中位数枚举** +### 方法一:前缀和 + 中位数枚举 我们可以将数组 $nums$ 中的 $1$ 的下标存入数组 $arr$ 中。接下来,我们预处理数组 $arr$ 的前缀和数组 $s$,其中 $s[i]$ 表示数组 $arr$ 中前 $i$ 个元素的和。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def minMoves(self, nums: List[int], k: int) -> int: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minMoves(int[] nums, int k) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func minMoves(nums []int, k int) int { arr := []int{} @@ -179,10 +165,6 @@ func minMoves(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README_EN.md b/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README_EN.md index 1f4d8e981281c..d684c163d2a9e 100644 --- a/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README_EN.md +++ b/solution/1700-1799/1703.Minimum Adjacent Swaps for K Consecutive Ones/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Prefix Sum + Median Enumeration** +### Solution 1: Prefix Sum + Median Enumeration We can store the indices of $1$s in the array $nums$ into an array $arr$. Next, we preprocess the prefix sum array $s$ of the array $arr$, where $s[i]$ represents the sum of the first $i$ elements in the array $arr$. @@ -56,8 +56,6 @@ The time complexity is $O(n)$, and the space complexity is $O(m)$. Here, $n$ and -### **Python3** - ```python class Solution: def minMoves(self, nums: List[int], k: int) -> int: @@ -76,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minMoves(int[] nums, int k) { @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +137,6 @@ public: }; ``` -### **Go** - ```go func minMoves(nums []int, k int) int { arr := []int{} @@ -172,10 +164,6 @@ func minMoves(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1704.Determine if String Halves Are Alike/README.md b/solution/1700-1799/1704.Determine if String Halves Are Alike/README.md index 47d29a1e1fa28..4b99e17789185 100644 --- a/solution/1700-1799/1704.Determine if String Halves Are Alike/README.md +++ b/solution/1700-1799/1704.Determine if String Halves Are Alike/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 遍历字符串,若字符串前半段的元音个数等于后半段的元音个数,则返回 `true`,否则返回 `false`。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def halvesAreAlike(self, s: str) -> bool: @@ -68,18 +62,6 @@ class Solution: return cnt == 0 ``` -```python -class Solution: - def halvesAreAlike(self, s: str) -> bool: - vowels = set('aeiouAEIOU') - a, b = s[: len(s) >> 1], s[len(s) >> 1 :] - return sum(c in vowels for c in a) == sum(c in vowels for c in b) -``` - -### **Java** - - - ```java class Solution { private static final Set VOWELS @@ -96,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +93,6 @@ public: }; ``` -### **Go** - ```go func halvesAreAlike(s string) bool { vowels := map[byte]bool{} @@ -134,8 +112,6 @@ func halvesAreAlike(s string) bool { } ``` -### **TypeScript** - ```ts function halvesAreAlike(s: string): boolean { const set = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']); @@ -149,8 +125,6 @@ function halvesAreAlike(s: string): boolean { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -174,7 +148,21 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {string} s + * @return {boolean} + */ +var halvesAreAlike = function (s) { + const str = 'aeiouAEIOU'; + let cnt = 0; + for (let i = 0; i < s.length / 2; i++) { + if (str.indexOf(s[i]) > -1) cnt++; + if (str.indexOf(s[s.length - 1 - i]) > -1) cnt--; + } + return cnt === 0; +}; +``` ```php class Solution { @@ -197,28 +185,20 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {string} s - * @return {boolean} - */ -var halvesAreAlike = function (s) { - const str = 'aeiouAEIOU'; - let cnt = 0; - for (let i = 0; i < s.length / 2; i++) { - if (str.indexOf(s[i]) > -1) cnt++; - if (str.indexOf(s[s.length - 1 - i]) > -1) cnt--; - } - return cnt === 0; -}; -``` + -### **...** +### 方法二 -``` + +```python +class Solution: + def halvesAreAlike(self, s: str) -> bool: + vowels = set('aeiouAEIOU') + a, b = s[: len(s) >> 1], s[len(s) >> 1 :] + return sum(c in vowels for c in a) == sum(c in vowels for c in b) ``` + + diff --git a/solution/1700-1799/1704.Determine if String Halves Are Alike/README_EN.md b/solution/1700-1799/1704.Determine if String Halves Are Alike/README_EN.md index 9af178b3e83a4..f3593e2e0fd53 100644 --- a/solution/1700-1799/1704.Determine if String Halves Are Alike/README_EN.md +++ b/solution/1700-1799/1704.Determine if String Halves Are Alike/README_EN.md @@ -39,7 +39,7 @@ Notice that the vowel o is counted twice. ## Solutions -**Solution 1: Counting** +### Solution 1: Counting Traverse the string. If the number of vowels in the first half of the string is equal to the number of vowels in the second half, return `true`. Otherwise, return `false`. @@ -47,8 +47,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string. The space -### **Python3** - ```python class Solution: def halvesAreAlike(self, s: str) -> bool: @@ -60,16 +58,6 @@ class Solution: return cnt == 0 ``` -```python -class Solution: - def halvesAreAlike(self, s: str) -> bool: - vowels = set('aeiouAEIOU') - a, b = s[: len(s) >> 1], s[len(s) >> 1 :] - return sum(c in vowels for c in a) == sum(c in vowels for c in b) -``` - -### **Java** - ```java class Solution { private static final Set VOWELS @@ -86,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +89,6 @@ public: }; ``` -### **Go** - ```go func halvesAreAlike(s string) bool { vowels := map[byte]bool{} @@ -124,8 +108,6 @@ func halvesAreAlike(s string) bool { } ``` -### **TypeScript** - ```ts function halvesAreAlike(s: string): boolean { const set = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']); @@ -139,8 +121,6 @@ function halvesAreAlike(s: string): boolean { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -164,7 +144,21 @@ impl Solution { } ``` -### **PHP** +```js +/** + * @param {string} s + * @return {boolean} + */ +var halvesAreAlike = function (s) { + const str = 'aeiouAEIOU'; + let cnt = 0; + for (let i = 0; i < s.length / 2; i++) { + if (str.indexOf(s[i]) > -1) cnt++; + if (str.indexOf(s[s.length - 1 - i]) > -1) cnt--; + } + return cnt === 0; +}; +``` ```php class Solution { @@ -187,28 +181,20 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {string} s - * @return {boolean} - */ -var halvesAreAlike = function (s) { - const str = 'aeiouAEIOU'; - let cnt = 0; - for (let i = 0; i < s.length / 2; i++) { - if (str.indexOf(s[i]) > -1) cnt++; - if (str.indexOf(s[s.length - 1 - i]) > -1) cnt--; - } - return cnt === 0; -}; -``` + -### **...** +### Solution 2 -``` + +```python +class Solution: + def halvesAreAlike(self, s: str) -> bool: + vowels = set('aeiouAEIOU') + a, b = s[: len(s) >> 1], s[len(s) >> 1 :] + return sum(c in vowels for c in a) == sum(c in vowels for c in b) ``` + + diff --git a/solution/1700-1799/1705.Maximum Number of Eaten Apples/README.md b/solution/1700-1799/1705.Maximum Number of Eaten Apples/README.md index ab678a114a627..57431588668bc 100644 --- a/solution/1700-1799/1705.Maximum Number of Eaten Apples/README.md +++ b/solution/1700-1799/1705.Maximum Number of Eaten Apples/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列** +### 方法一:贪心 + 优先队列 我们可以贪心地在未腐烂的苹果中优先选择最容易腐烂的苹果,这样可以使得吃到的苹果尽可能多。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def eatenApples(self, apples: List[int], days: List[int]) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int eatenApples(int[] apples, int[] days) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp using pii = pair; @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go func eatenApples(apples []int, days []int) int { var h hp @@ -183,10 +169,6 @@ func (a *hp) Push(x any) { *a = append(*a, x.(pair)) } func (a *hp) Pop() any { l := len(*a); t := (*a)[l-1]; *a = (*a)[:l-1]; return t } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1705.Maximum Number of Eaten Apples/README_EN.md b/solution/1700-1799/1705.Maximum Number of Eaten Apples/README_EN.md index c9564d53c0b3d..9243baf70fb4c 100644 --- a/solution/1700-1799/1705.Maximum Number of Eaten Apples/README_EN.md +++ b/solution/1700-1799/1705.Maximum Number of Eaten Apples/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Greedy + Priority Queue** +### Solution 1: Greedy + Priority Queue We can greedily choose the apple that is most likely to rot among the unrotten apples, so that we can eat as many apples as possible. @@ -56,8 +56,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def eatenApples(self, apples: List[int], days: List[int]) -> int: @@ -79,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int eatenApples(int[] apples, int[] days) { @@ -108,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp using pii = pair; @@ -136,8 +130,6 @@ public: }; ``` -### **Go** - ```go func eatenApples(apples []int, days []int) int { var h hp @@ -174,10 +166,6 @@ func (a *hp) Push(x any) { *a = append(*a, x.(pair)) } func (a *hp) Pop() any { l := len(*a); t := (*a)[l-1]; *a = (*a)[:l-1]; return t } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1706.Where Will the Ball Fall/README.md b/solution/1700-1799/1706.Where Will the Ball Fall/README.md index ed8bb7bf9d0e6..ab6e2c55d2972 100644 --- a/solution/1700-1799/1706.Where Will the Ball Fall/README.md +++ b/solution/1700-1799/1706.Where Will the Ball Fall/README.md @@ -64,9 +64,7 @@ b4 球开始放在第 4 列上,会卡在第 2、3 列和第 1 行之间的 "V" ## 解法 - - -**方法一:分情况讨论 + DFS** +### 方法一:分情况讨论 + DFS 我们可以使用 DFS 来模拟球的运动过程,设计一个函数 $dfs(i, j)$,表示球从第 $i$ 行第 $j$ 列出发,最终会落在第几列。对于以下情况,球会卡住: @@ -81,10 +79,6 @@ b4 球开始放在第 4 列上,会卡在第 2、3 列和第 1 行之间的 "V" -### **Python3** - - - ```python class Solution: def findBall(self, grid: List[List[int]]) -> List[int]: @@ -105,10 +99,6 @@ class Solution: return [dfs(0, j) for j in range(n)] ``` -### **Java** - - - ```java class Solution { private int m; @@ -147,8 +137,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -181,8 +169,6 @@ public: }; ``` -### **Go** - ```go func findBall(grid [][]int) (ans []int) { m, n := len(grid), len(grid[0]) @@ -215,8 +201,6 @@ func findBall(grid [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function findBall(grid: number[][]): number[] { const m = grid.length; @@ -245,8 +229,6 @@ function findBall(grid: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { fn dfs(grid: &Vec>, i: usize, j: usize) -> i32 { @@ -278,10 +260,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1706.Where Will the Ball Fall/README_EN.md b/solution/1700-1799/1706.Where Will the Ball Fall/README_EN.md index 86589eaac2fa7..586226f9fe5a1 100644 --- a/solution/1700-1799/1706.Where Will the Ball Fall/README_EN.md +++ b/solution/1700-1799/1706.Where Will the Ball Fall/README_EN.md @@ -60,7 +60,7 @@ Ball b4 is dropped at column 4 and will get stuck on the box between column 2 an ## Solutions -**Solution 1: Case Discussion + DFS** +### Solution 1: Case Discussion + DFS We can use DFS to simulate the movement of the ball. We design a function $dfs(i, j)$, which represents that the ball starts from the $i$th row and the $j$th column, and finally falls in which column. The ball will get stuck in the following situations: @@ -75,8 +75,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m)$. Wher -### **Python3** - ```python class Solution: def findBall(self, grid: List[List[int]]) -> List[int]: @@ -97,8 +95,6 @@ class Solution: return [dfs(0, j) for j in range(n)] ``` -### **Java** - ```java class Solution { private int m; @@ -137,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +165,6 @@ public: }; ``` -### **Go** - ```go func findBall(grid [][]int) (ans []int) { m, n := len(grid), len(grid[0]) @@ -205,8 +197,6 @@ func findBall(grid [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function findBall(grid: number[][]): number[] { const m = grid.length; @@ -235,8 +225,6 @@ function findBall(grid: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { fn dfs(grid: &Vec>, i: usize, j: usize) -> i32 { @@ -268,10 +256,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1707.Maximum XOR With an Element From Array/README.md b/solution/1700-1799/1707.Maximum XOR With an Element From Array/README.md index 48ffaddd71e47..53b2794e0a16b 100644 --- a/solution/1700-1799/1707.Maximum XOR With an Element From Array/README.md +++ b/solution/1700-1799/1707.Maximum XOR With an Element From Array/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:离线查询 + 0-1 字典树** +### 方法一:离线查询 + 0-1 字典树 根据题目描述我们知道,每个查询相互独立,并且查询的结果与 $nums$ 中的元素顺序无关,因此,我们考虑将所有的查询按照 $m_i$ 从小到大排序,并且将 $nums$ 从小到大排序。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Trie: __slots__ = ["children"] @@ -102,10 +96,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Trie { private Trie[] children = new Trie[2]; @@ -163,8 +153,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { private: @@ -226,8 +214,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [2]*Trie @@ -290,8 +276,6 @@ func maximizeXor(nums []int, queries [][]int) []int { } ``` -### **TypeScript** - ```ts class Trie { children: (Trie | null)[]; @@ -349,10 +333,6 @@ function maximizeXor(nums: number[], queries: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1707.Maximum XOR With an Element From Array/README_EN.md b/solution/1700-1799/1707.Maximum XOR With an Element From Array/README_EN.md index f16a6fabd45a1..a7befdb52117e 100644 --- a/solution/1700-1799/1707.Maximum XOR With an Element From Array/README_EN.md +++ b/solution/1700-1799/1707.Maximum XOR With an Element From Array/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Offline Query + Binary Trie** +### Solution 1: Offline Query + Binary Trie From the problem description, we know that each query is independent and the result of the query is irrelevant to the order of elements in $nums$. Therefore, we consider sorting all queries in ascending order of $m_i$, and also sorting $nums$ in ascending order. @@ -50,8 +50,6 @@ The time complexity is $O(m \times \log m + n \times (\log n + \log M))$, and th -### **Python3** - ```python class Trie: __slots__ = ["children"] @@ -96,8 +94,6 @@ class Solution: return ans ``` -### **Java** - ```java class Trie { private Trie[] children = new Trie[2]; @@ -155,8 +151,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { private: @@ -218,8 +212,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [2]*Trie @@ -282,8 +274,6 @@ func maximizeXor(nums []int, queries [][]int) []int { } ``` -### **TypeScript** - ```ts class Trie { children: (Trie | null)[]; @@ -341,10 +331,6 @@ function maximizeXor(nums: number[], queries: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1708.Largest Subarray Length K/README.md b/solution/1700-1799/1708.Largest Subarray Length K/README.md index 64a96d4848363..7db7795c2c11e 100644 --- a/solution/1700-1799/1708.Largest Subarray Length K/README.md +++ b/solution/1700-1799/1708.Largest Subarray Length K/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 数组中所有整数都不同,我们可以先在 $[0,..n-k]$ 范围内找到最大的元素的下标,然后从该下标开始取 $k$ 个元素即可。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def largestSubarray(self, nums: List[int], k: int) -> List[int]: @@ -80,10 +74,6 @@ class Solution: return nums[i : i + k] ``` -### **Java** - - - ```java class Solution { public int[] largestSubarray(int[] nums, int k) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +98,6 @@ public: }; ``` -### **Go** - ```go func largestSubarray(nums []int, k int) []int { j := 0 @@ -124,8 +110,6 @@ func largestSubarray(nums []int, k int) []int { } ``` -### **TypeScript** - ```ts function largestSubarray(nums: number[], k: number): number[] { let j = 0; @@ -138,8 +122,6 @@ function largestSubarray(nums: number[], k: number): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn largest_subarray(nums: Vec, k: i32) -> Vec { @@ -154,10 +136,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1708.Largest Subarray Length K/README_EN.md b/solution/1700-1799/1708.Largest Subarray Length K/README_EN.md index 64c866b199478..ac357712bef25 100644 --- a/solution/1700-1799/1708.Largest Subarray Length K/README_EN.md +++ b/solution/1700-1799/1708.Largest Subarray Length K/README_EN.md @@ -55,7 +55,7 @@ Of these, [4,5,2,3] is the largest. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation All integers in the array are distinct, so we can first find the index of the maximum element in the range $[0,..n-k]$, and then take $k$ elements starting from this index. @@ -63,8 +63,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. Ignoring th -### **Python3** - ```python class Solution: def largestSubarray(self, nums: List[int], k: int) -> List[int]: @@ -72,8 +70,6 @@ class Solution: return nums[i : i + k] ``` -### **Java** - ```java class Solution { public int[] largestSubarray(int[] nums, int k) { @@ -88,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +94,6 @@ public: }; ``` -### **Go** - ```go func largestSubarray(nums []int, k int) []int { j := 0 @@ -114,8 +106,6 @@ func largestSubarray(nums []int, k int) []int { } ``` -### **TypeScript** - ```ts function largestSubarray(nums: number[], k: number): number[] { let j = 0; @@ -128,8 +118,6 @@ function largestSubarray(nums: number[], k: number): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn largest_subarray(nums: Vec, k: i32) -> Vec { @@ -144,10 +132,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1709.Biggest Window Between Visits/README.md b/solution/1700-1799/1709.Biggest Window Between Visits/README.md index c3e0215e84653..c26f3aa85089c 100644 --- a/solution/1700-1799/1709.Biggest Window Between Visits/README.md +++ b/solution/1700-1799/1709.Biggest Window Between Visits/README.md @@ -67,16 +67,12 @@ UserVisits 表: ## 解法 - - -**方法一:窗口函数** +### 方法一:窗口函数 我们可以使用窗口函数 `LEAD` 来获取每个用户每次访问的下一次访问的日期(如果下一次访问的日期不存在,则视为 `2021-1-1`),然后利用 `DATEDIFF` 函数来计算两次访问之间的天数差值,最后对每个用户的天数差值求最大值即可。 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -99,3 +95,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1700-1799/1709.Biggest Window Between Visits/README_EN.md b/solution/1700-1799/1709.Biggest Window Between Visits/README_EN.md index a07213b53c35d..5a64a5e1d9f3f 100644 --- a/solution/1700-1799/1709.Biggest Window Between Visits/README_EN.md +++ b/solution/1700-1799/1709.Biggest Window Between Visits/README_EN.md @@ -66,14 +66,12 @@ For the third user, the only window in question is between dates 2020-11-11 and ## Solutions -**Solution 1: Window Function** +### Solution 1: Window Function We can use the window function `LEAD` to obtain the date of the next visit for each user (if the date of the next visit does not exist, it is considered as `2021-1-1`), and then use the `DATEDIFF` function to calculate the number of days between two visits. Finally, we can take the maximum value of the number of days between visits for each user. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -96,3 +94,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1700-1799/1710.Maximum Units on a Truck/README.md b/solution/1700-1799/1710.Maximum Units on a Truck/README.md index 882ffb005a6e2..eeb79ab9b83e5 100644 --- a/solution/1700-1799/1710.Maximum Units on a Truck/README.md +++ b/solution/1700-1799/1710.Maximum Units on a Truck/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 根据题意,我们应该选择尽可能多的单元数,因此,我们先对 `boxTypes` 按照单元数从大到小的顺序排列。 @@ -60,20 +58,8 @@ 时间复杂度 $O(n \times \log n)$,其中 $n$ 表示二维数组 `boxTypes` 的长度。 -**方法二:计数排序** - -我们还可以利用计数排序的思想,开一个长度为 $1001$ 的数组 $cnt$,其中 $cnt[b]$ 表示单元数为 $b$ 的箱子的数量。 - -然后从单元数最大的箱子开始,选择最多 `truckSize` 个箱子,累加单元数。 - -时间复杂度 $O(M)$,其中 $M$ 是单元数的最大值。本题中 $M=1000$。 - -### **Python3** - - - ```python class Solution: def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: @@ -86,27 +72,6 @@ class Solution: return ans ``` -```python -class Solution: - def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: - cnt = [0] * 1001 - for a, b in boxTypes: - cnt[b] += a - ans = 0 - for b in range(1000, 0, -1): - a = cnt[b] - if a: - ans += b * min(truckSize, a) - truckSize -= a - if truckSize <= 0: - break - return ans -``` - -### **Java** - - - ```java class Solution { public int maximumUnits(int[][] boxTypes, int truckSize) { @@ -125,6 +90,105 @@ class Solution { } ``` +```cpp +class Solution { +public: + int maximumUnits(vector>& boxTypes, int truckSize) { + sort(boxTypes.begin(), boxTypes.end(), [](auto& a, auto& b) { return a[1] > b[1]; }); + int ans = 0; + for (auto& e : boxTypes) { + int a = e[0], b = e[1]; + ans += b * min(truckSize, a); + truckSize -= a; + if (truckSize <= 0) break; + } + return ans; + } +}; +``` + +```go +func maximumUnits(boxTypes [][]int, truckSize int) (ans int) { + sort.Slice(boxTypes, func(i, j int) bool { return boxTypes[i][1] > boxTypes[j][1] }) + for _, e := range boxTypes { + a, b := e[0], e[1] + ans += b * min(truckSize, a) + truckSize -= a + if truckSize <= 0 { + break + } + } + return +} +``` + +```ts +function maximumUnits(boxTypes: number[][], truckSize: number): number { + boxTypes.sort((a, b) => b[1] - a[1]); + let sum = 0; + let ans = 0; + for (const [count, size] of boxTypes) { + if (sum + count < truckSize) { + ans += size * count; + sum += count; + } else { + ans += (truckSize - sum) * size; + break; + } + } + return ans; +} +``` + +```rust +impl Solution { + pub fn maximum_units(mut box_types: Vec>, truck_size: i32) -> i32 { + box_types.sort_by(|a, b| b[1].cmp(&a[1])); + let mut sum = 0; + let mut ans = 0; + for box_type in box_types.iter() { + if sum + box_type[0] < truck_size { + sum += box_type[0]; + ans += box_type[0] * box_type[1]; + } else { + ans += (truck_size - sum) * box_type[1]; + break; + } + } + ans + } +} +``` + + + +### 方法二:计数排序 + +我们还可以利用计数排序的思想,开一个长度为 $1001$ 的数组 $cnt$,其中 $cnt[b]$ 表示单元数为 $b$ 的箱子的数量。 + +然后从单元数最大的箱子开始,选择最多 `truckSize` 个箱子,累加单元数。 + +时间复杂度 $O(M)$,其中 $M$ 是单元数的最大值。本题中 $M=1000$。 + + + +```python +class Solution: + def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: + cnt = [0] * 1001 + for a, b in boxTypes: + cnt[b] += a + ans = 0 + for b in range(1000, 0, -1): + a = cnt[b] + if a: + ans += b * min(truckSize, a) + truckSize -= a + if truckSize <= 0: + break + return ans +``` + ```java class Solution { public int maximumUnits(int[][] boxTypes, int truckSize) { @@ -146,25 +210,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maximumUnits(vector>& boxTypes, int truckSize) { - sort(boxTypes.begin(), boxTypes.end(), [](auto& a, auto& b) { return a[1] > b[1]; }); - int ans = 0; - for (auto& e : boxTypes) { - int a = e[0], b = e[1]; - ans += b * min(truckSize, a); - truckSize -= a; - if (truckSize <= 0) break; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -187,23 +232,6 @@ public: }; ``` -### **Go** - -```go -func maximumUnits(boxTypes [][]int, truckSize int) (ans int) { - sort.Slice(boxTypes, func(i, j int) bool { return boxTypes[i][1] > boxTypes[j][1] }) - for _, e := range boxTypes { - a, b := e[0], e[1] - ans += b * min(truckSize, a) - truckSize -= a - if truckSize <= 0 { - break - } - } - return -} -``` - ```go func maximumUnits(boxTypes [][]int, truckSize int) (ans int) { cnt := [1001]int{} @@ -222,26 +250,6 @@ func maximumUnits(boxTypes [][]int, truckSize int) (ans int) { } ``` -### **TypeScript** - -```ts -function maximumUnits(boxTypes: number[][], truckSize: number): number { - boxTypes.sort((a, b) => b[1] - a[1]); - let sum = 0; - let ans = 0; - for (const [count, size] of boxTypes) { - if (sum + count < truckSize) { - ans += size * count; - sum += count; - } else { - ans += (truckSize - sum) * size; - break; - } - } - return ans; -} -``` - ```ts function maximumUnits(boxTypes: number[][], truckSize: number): number { const cnt = new Array(1001).fill(0); @@ -260,32 +268,6 @@ function maximumUnits(boxTypes: number[][], truckSize: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn maximum_units(mut box_types: Vec>, truck_size: i32) -> i32 { - box_types.sort_by(|a, b| b[1].cmp(&a[1])); - let mut sum = 0; - let mut ans = 0; - for box_type in box_types.iter() { - if sum + box_type[0] < truck_size { - sum += box_type[0]; - ans += box_type[0] * box_type[1]; - } else { - ans += (truck_size - sum) * box_type[1]; - break; - } - } - ans - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1710.Maximum Units on a Truck/README_EN.md b/solution/1700-1799/1710.Maximum Units on a Truck/README_EN.md index 3673d77c44f09..a393610ff46b6 100644 --- a/solution/1700-1799/1710.Maximum Units on a Truck/README_EN.md +++ b/solution/1700-1799/1710.Maximum Units on a Truck/README_EN.md @@ -47,7 +47,7 @@ The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8. ## Solutions -**Solution 1: Greedy + Sorting** +### Solution 1: Greedy + Sorting According to the problem, we should choose as many units as possible. Therefore, we first sort `boxTypes` in descending order of the number of units. @@ -55,18 +55,8 @@ Then we traverse `boxTypes` from front to back, choose up to `truckSize` boxes, The time complexity is $O(n \times \log n)$, where $n$ is the length of the two-dimensional array `boxTypes`. -**Solution 2: Counting Sort** - -We can also use the idea of counting sort, create an array $cnt$ of length $1001$, where $cnt[b]$ represents the number of boxes with $b$ units. - -Then starting from the box with the maximum number of units, choose up to `truckSize` boxes, and accumulate the number of units. - -The time complexity is $O(M)$, where $M$ is the maximum number of units. In this problem, $M=1000$. - -### **Python3** - ```python class Solution: def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: @@ -79,25 +69,6 @@ class Solution: return ans ``` -```python -class Solution: - def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: - cnt = [0] * 1001 - for a, b in boxTypes: - cnt[b] += a - ans = 0 - for b in range(1000, 0, -1): - a = cnt[b] - if a: - ans += b * min(truckSize, a) - truckSize -= a - if truckSize <= 0: - break - return ans -``` - -### **Java** - ```java class Solution { public int maximumUnits(int[][] boxTypes, int truckSize) { @@ -116,6 +87,105 @@ class Solution { } ``` +```cpp +class Solution { +public: + int maximumUnits(vector>& boxTypes, int truckSize) { + sort(boxTypes.begin(), boxTypes.end(), [](auto& a, auto& b) { return a[1] > b[1]; }); + int ans = 0; + for (auto& e : boxTypes) { + int a = e[0], b = e[1]; + ans += b * min(truckSize, a); + truckSize -= a; + if (truckSize <= 0) break; + } + return ans; + } +}; +``` + +```go +func maximumUnits(boxTypes [][]int, truckSize int) (ans int) { + sort.Slice(boxTypes, func(i, j int) bool { return boxTypes[i][1] > boxTypes[j][1] }) + for _, e := range boxTypes { + a, b := e[0], e[1] + ans += b * min(truckSize, a) + truckSize -= a + if truckSize <= 0 { + break + } + } + return +} +``` + +```ts +function maximumUnits(boxTypes: number[][], truckSize: number): number { + boxTypes.sort((a, b) => b[1] - a[1]); + let sum = 0; + let ans = 0; + for (const [count, size] of boxTypes) { + if (sum + count < truckSize) { + ans += size * count; + sum += count; + } else { + ans += (truckSize - sum) * size; + break; + } + } + return ans; +} +``` + +```rust +impl Solution { + pub fn maximum_units(mut box_types: Vec>, truck_size: i32) -> i32 { + box_types.sort_by(|a, b| b[1].cmp(&a[1])); + let mut sum = 0; + let mut ans = 0; + for box_type in box_types.iter() { + if sum + box_type[0] < truck_size { + sum += box_type[0]; + ans += box_type[0] * box_type[1]; + } else { + ans += (truck_size - sum) * box_type[1]; + break; + } + } + ans + } +} +``` + + + +### Solution 2: Counting Sort + +We can also use the idea of counting sort, create an array $cnt$ of length $1001$, where $cnt[b]$ represents the number of boxes with $b$ units. + +Then starting from the box with the maximum number of units, choose up to `truckSize` boxes, and accumulate the number of units. + +The time complexity is $O(M)$, where $M$ is the maximum number of units. In this problem, $M=1000$. + + + +```python +class Solution: + def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: + cnt = [0] * 1001 + for a, b in boxTypes: + cnt[b] += a + ans = 0 + for b in range(1000, 0, -1): + a = cnt[b] + if a: + ans += b * min(truckSize, a) + truckSize -= a + if truckSize <= 0: + break + return ans +``` + ```java class Solution { public int maximumUnits(int[][] boxTypes, int truckSize) { @@ -137,25 +207,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maximumUnits(vector>& boxTypes, int truckSize) { - sort(boxTypes.begin(), boxTypes.end(), [](auto& a, auto& b) { return a[1] > b[1]; }); - int ans = 0; - for (auto& e : boxTypes) { - int a = e[0], b = e[1]; - ans += b * min(truckSize, a); - truckSize -= a; - if (truckSize <= 0) break; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -178,23 +229,6 @@ public: }; ``` -### **Go** - -```go -func maximumUnits(boxTypes [][]int, truckSize int) (ans int) { - sort.Slice(boxTypes, func(i, j int) bool { return boxTypes[i][1] > boxTypes[j][1] }) - for _, e := range boxTypes { - a, b := e[0], e[1] - ans += b * min(truckSize, a) - truckSize -= a - if truckSize <= 0 { - break - } - } - return -} -``` - ```go func maximumUnits(boxTypes [][]int, truckSize int) (ans int) { cnt := [1001]int{} @@ -213,26 +247,6 @@ func maximumUnits(boxTypes [][]int, truckSize int) (ans int) { } ``` -### **TypeScript** - -```ts -function maximumUnits(boxTypes: number[][], truckSize: number): number { - boxTypes.sort((a, b) => b[1] - a[1]); - let sum = 0; - let ans = 0; - for (const [count, size] of boxTypes) { - if (sum + count < truckSize) { - ans += size * count; - sum += count; - } else { - ans += (truckSize - sum) * size; - break; - } - } - return ans; -} -``` - ```ts function maximumUnits(boxTypes: number[][], truckSize: number): number { const cnt = new Array(1001).fill(0); @@ -251,32 +265,6 @@ function maximumUnits(boxTypes: number[][], truckSize: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn maximum_units(mut box_types: Vec>, truck_size: i32) -> i32 { - box_types.sort_by(|a, b| b[1].cmp(&a[1])); - let mut sum = 0; - let mut ans = 0; - for box_type in box_types.iter() { - if sum + box_type[0] < truck_size { - sum += box_type[0]; - ans += box_type[0] * box_type[1]; - } else { - ans += (truck_size - sum) * box_type[1]; - break; - } - } - ans - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1711.Count Good Meals/README.md b/solution/1700-1799/1711.Count Good Meals/README.md index 5bc43a6453b2b..04448dd56ee1e 100644 --- a/solution/1700-1799/1711.Count Good Meals/README.md +++ b/solution/1700-1799/1711.Count Good Meals/README.md @@ -43,7 +43,7 @@ ## 解法 -**方法一:哈希表 + 枚举二的幂** +### 方法一:哈希表 + 枚举二的幂 根据题意,我们需要统计数组中两个数的和为 $2$ 的幂的组合数。直接暴力枚举所有的组合数,时间复杂度为 $O(n^2)$ ,肯定会超时。 @@ -67,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def countPairs(self, deliciousness: List[int]) -> int: @@ -87,24 +83,6 @@ class Solution: return ans ``` -```python -class Solution: - def countPairs(self, deliciousness: List[int]) -> int: - mod = 10**9 + 7 - cnt = Counter(deliciousness) - ans = 0 - for i in range(22): - s = 1 << i - for a, m in cnt.items(): - if (b := s - a) in cnt: - ans += m * (m - 1) if a == b else m * cnt[b] - return (ans >> 1) % mod -``` - -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -124,6 +102,61 @@ class Solution { } ``` +```cpp +class Solution { +public: + const int mod = 1e9 + 7; + + int countPairs(vector& deliciousness) { + int mx = *max_element(deliciousness.begin(), deliciousness.end()) << 1; + unordered_map cnt; + int ans = 0; + for (auto& d : deliciousness) { + for (int s = 1; s <= mx; s <<= 1) { + ans = (ans + cnt[s - d]) % mod; + } + ++cnt[d]; + } + return ans; + } +}; +``` + +```go +func countPairs(deliciousness []int) (ans int) { + mx := slices.Max(deliciousness) << 1 + const mod int = 1e9 + 7 + cnt := map[int]int{} + for _, d := range deliciousness { + for s := 1; s <= mx; s <<= 1 { + ans = (ans + cnt[s-d]) % mod + } + cnt[d]++ + } + return +} +``` + + + +### 方法二 + + + +```python +class Solution: + def countPairs(self, deliciousness: List[int]) -> int: + mod = 10**9 + 7 + cnt = Counter(deliciousness) + ans = 0 + for i in range(22): + s = 1 << i + for a, m in cnt.items(): + if (b := s - a) in cnt: + ans += m * (m - 1) if a == b else m * cnt[b] + return (ans >> 1) % mod +``` + ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -151,28 +184,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - const int mod = 1e9 + 7; - - int countPairs(vector& deliciousness) { - int mx = *max_element(deliciousness.begin(), deliciousness.end()) << 1; - unordered_map cnt; - int ans = 0; - for (auto& d : deliciousness) { - for (int s = 1; s <= mx; s <<= 1) { - ans = (ans + cnt[s - d]) % mod; - } - ++cnt[d]; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -196,23 +207,6 @@ public: }; ``` -### **Go** - -```go -func countPairs(deliciousness []int) (ans int) { - mx := slices.Max(deliciousness) << 1 - const mod int = 1e9 + 7 - cnt := map[int]int{} - for _, d := range deliciousness { - for s := 1; s <= mx; s <<= 1 { - ans = (ans + cnt[s-d]) % mod - } - cnt[d]++ - } - return -} -``` - ```go func countPairs(deliciousness []int) (ans int) { cnt := map[int]int{} @@ -238,10 +232,6 @@ func countPairs(deliciousness []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1711.Count Good Meals/README_EN.md b/solution/1700-1799/1711.Count Good Meals/README_EN.md index 453412002730c..b91f932cd0136 100644 --- a/solution/1700-1799/1711.Count Good Meals/README_EN.md +++ b/solution/1700-1799/1711.Count Good Meals/README_EN.md @@ -39,7 +39,7 @@ Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. ## Solutions -**Solution 1: Hash Table + Enumeration of Powers of Two** +### Solution 1: Hash Table + Enumeration of Powers of Two According to the problem, we need to count the number of combinations in the array where the sum of two numbers is a power of $2$. Directly enumerating all combinations has a time complexity of $O(n^2)$, which will definitely time out. @@ -61,8 +61,6 @@ The time complexity is the same as the method above. -### **Python3** - ```python class Solution: def countPairs(self, deliciousness: List[int]) -> int: @@ -79,22 +77,6 @@ class Solution: return ans ``` -```python -class Solution: - def countPairs(self, deliciousness: List[int]) -> int: - mod = 10**9 + 7 - cnt = Counter(deliciousness) - ans = 0 - for i in range(22): - s = 1 << i - for a, m in cnt.items(): - if (b := s - a) in cnt: - ans += m * (m - 1) if a == b else m * cnt[b] - return (ans >> 1) % mod -``` - -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -114,6 +96,61 @@ class Solution { } ``` +```cpp +class Solution { +public: + const int mod = 1e9 + 7; + + int countPairs(vector& deliciousness) { + int mx = *max_element(deliciousness.begin(), deliciousness.end()) << 1; + unordered_map cnt; + int ans = 0; + for (auto& d : deliciousness) { + for (int s = 1; s <= mx; s <<= 1) { + ans = (ans + cnt[s - d]) % mod; + } + ++cnt[d]; + } + return ans; + } +}; +``` + +```go +func countPairs(deliciousness []int) (ans int) { + mx := slices.Max(deliciousness) << 1 + const mod int = 1e9 + 7 + cnt := map[int]int{} + for _, d := range deliciousness { + for s := 1; s <= mx; s <<= 1 { + ans = (ans + cnt[s-d]) % mod + } + cnt[d]++ + } + return +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def countPairs(self, deliciousness: List[int]) -> int: + mod = 10**9 + 7 + cnt = Counter(deliciousness) + ans = 0 + for i in range(22): + s = 1 << i + for a, m in cnt.items(): + if (b := s - a) in cnt: + ans += m * (m - 1) if a == b else m * cnt[b] + return (ans >> 1) % mod +``` + ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -141,28 +178,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - const int mod = 1e9 + 7; - - int countPairs(vector& deliciousness) { - int mx = *max_element(deliciousness.begin(), deliciousness.end()) << 1; - unordered_map cnt; - int ans = 0; - for (auto& d : deliciousness) { - for (int s = 1; s <= mx; s <<= 1) { - ans = (ans + cnt[s - d]) % mod; - } - ++cnt[d]; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -186,23 +201,6 @@ public: }; ``` -### **Go** - -```go -func countPairs(deliciousness []int) (ans int) { - mx := slices.Max(deliciousness) << 1 - const mod int = 1e9 + 7 - cnt := map[int]int{} - for _, d := range deliciousness { - for s := 1; s <= mx; s <<= 1 { - ans = (ans + cnt[s-d]) % mod - } - cnt[d]++ - } - return -} -``` - ```go func countPairs(deliciousness []int) (ans int) { cnt := map[int]int{} @@ -228,10 +226,6 @@ func countPairs(deliciousness []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1712.Ways to Split Array Into Three Subarrays/README.md b/solution/1700-1799/1712.Ways to Split Array Into Three Subarrays/README.md index 469a380f2b00b..5f9380d128e86 100644 --- a/solution/1700-1799/1712.Ways to Split Array Into Three Subarrays/README.md +++ b/solution/1700-1799/1712.Ways to Split Array Into Three Subarrays/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:前缀和 + 二分查找** +### 方法一:前缀和 + 二分查找 我们先预处理出数组 $nums$ 的前缀和数组 $s$,其中 $s[i]$ 表述数组 $nums$ 前 $i+1$ 个元素之和。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def waysToSplit(self, nums: List[int]) -> int: @@ -88,10 +82,6 @@ class Solution: return ans % mod ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +136,6 @@ public: }; ``` -### **Go** - ```go func waysToSplit(nums []int) (ans int) { const mod int = 1e9 + 7 @@ -168,8 +154,6 @@ func waysToSplit(nums []int) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -203,10 +187,6 @@ var waysToSplit = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1712.Ways to Split Array Into Three Subarrays/README_EN.md b/solution/1700-1799/1712.Ways to Split Array Into Three Subarrays/README_EN.md index 7ce95c4fb4d33..2ac055f8987e9 100644 --- a/solution/1700-1799/1712.Ways to Split Array Into Three Subarrays/README_EN.md +++ b/solution/1700-1799/1712.Ways to Split Array Into Three Subarrays/README_EN.md @@ -49,7 +49,7 @@ ## Solutions -**Solution 1: Prefix Sum + Binary Search** +### Solution 1: Prefix Sum + Binary Search First, we preprocess the prefix sum array $s$ of the array $nums$, where $s[i]$ represents the sum of the first $i+1$ elements of the array $nums$. @@ -65,8 +65,6 @@ The time complexity is $O(n \times \log n)$, where $n$ is the length of the arra -### **Python3** - ```python class Solution: def waysToSplit(self, nums: List[int]) -> int: @@ -80,8 +78,6 @@ class Solution: return ans % mod ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -116,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +132,6 @@ public: }; ``` -### **Go** - ```go func waysToSplit(nums []int) (ans int) { const mod int = 1e9 + 7 @@ -158,8 +150,6 @@ func waysToSplit(nums []int) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -193,10 +183,6 @@ var waysToSplit = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1713.Minimum Operations to Make a Subsequence/README.md b/solution/1700-1799/1713.Minimum Operations to Make a Subsequence/README.md index 81fb30aa476a3..7462bf69ace7f 100644 --- a/solution/1700-1799/1713.Minimum Operations to Make a Subsequence/README.md +++ b/solution/1700-1799/1713.Minimum Operations to Make a Subsequence/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:最长递增子序列** +### 方法一:最长递增子序列 根据题意,`target` 和 `arr` 这两个数组的公共子序列越长,需要添加的元素就越少。因此,最少添加的元素个数等于 `target` 的长度减去 `target` 和 `arr` 的最长公共子序列的长度。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class BinaryIndexedTree: def __init__(self, n): @@ -103,10 +97,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class BinaryIndexedTree { private int n; @@ -176,8 +166,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -241,8 +229,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -318,10 +304,6 @@ func lengthOfLIS(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1713.Minimum Operations to Make a Subsequence/README_EN.md b/solution/1700-1799/1713.Minimum Operations to Make a Subsequence/README_EN.md index fb31f24f7f1af..085d582c7dcfd 100644 --- a/solution/1700-1799/1713.Minimum Operations to Make a Subsequence/README_EN.md +++ b/solution/1700-1799/1713.Minimum Operations to Make a Subsequence/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class BinaryIndexedTree: @@ -85,8 +85,6 @@ class Solution: return ans ``` -### **Java** - ```java class BinaryIndexedTree { private int n; @@ -156,8 +154,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -221,8 +217,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -298,10 +292,6 @@ func lengthOfLIS(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1714.Sum Of Special Evenly-Spaced Elements In Array/README.md b/solution/1700-1799/1714.Sum Of Special Evenly-Spaced Elements In Array/README.md index a50a6af98cb5b..65b77d63fc946 100644 --- a/solution/1700-1799/1714.Sum Of Special Evenly-Spaced Elements In Array/README.md +++ b/solution/1700-1799/1714.Sum Of Special Evenly-Spaced Elements In Array/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:分块** +### 方法一:分块 这道题是一道比较典型的分块题目,对于步长较大的查询,我们可以直接暴力求解;对于步长较小的查询,我们可以预处理出每个位置的后缀和,然后直接查询。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def solve(self, nums: List[int], queries: List[List[int]]) -> List[int]: @@ -85,10 +79,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] solve(int[] nums, int[][] queries) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func solve(nums []int, queries [][]int) (ans []int) { n := len(nums) @@ -185,8 +171,6 @@ func solve(nums []int, queries [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function solve(nums: number[], queries: number[][]): number[] { const n = nums.length; @@ -216,10 +200,6 @@ function solve(nums: number[], queries: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1714.Sum Of Special Evenly-Spaced Elements In Array/README_EN.md b/solution/1700-1799/1714.Sum Of Special Evenly-Spaced Elements In Array/README_EN.md index e1433d1b349c3..bbb5f75573385 100644 --- a/solution/1700-1799/1714.Sum Of Special Evenly-Spaced Elements In Array/README_EN.md +++ b/solution/1700-1799/1714.Sum Of Special Evenly-Spaced Elements In Array/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Block Decomposition** +### Solution 1: Block Decomposition This problem is a typical block decomposition problem. For queries with a large step size, we can directly brute force the solution; for queries with a small step size, we can preprocess the suffix sum of each position and then directly query. @@ -58,8 +58,6 @@ The time complexity is $O((n + m) \times \sqrt{n})$, and the space complexity i -### **Python3** - ```python class Solution: def solve(self, nums: List[int], queries: List[List[int]]) -> List[int]: @@ -79,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] solve(int[] nums, int[][] queries) { @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +141,6 @@ public: }; ``` -### **Go** - ```go func solve(nums []int, queries [][]int) (ans []int) { n := len(nums) @@ -177,8 +169,6 @@ func solve(nums []int, queries [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function solve(nums: number[], queries: number[][]): number[] { const n = nums.length; @@ -208,10 +198,6 @@ function solve(nums: number[], queries: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1715.Count Apples and Oranges/README.md b/solution/1700-1799/1715.Count Apples and Oranges/README.md index 8f2794ea0c584..21c59b3f99a78 100644 --- a/solution/1700-1799/1715.Count Apples and Oranges/README.md +++ b/solution/1700-1799/1715.Count Apples and Oranges/README.md @@ -91,14 +91,10 @@ Chests 表: ## 解法 - - -“`LEFT JOIN` + `IFNULL`”实现。 +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -110,3 +106,5 @@ FROM ``` + + diff --git a/solution/1700-1799/1715.Count Apples and Oranges/README_EN.md b/solution/1700-1799/1715.Count Apples and Oranges/README_EN.md index 431fa53b8cacf..ffc6822746d2e 100644 --- a/solution/1700-1799/1715.Count Apples and Oranges/README_EN.md +++ b/solution/1700-1799/1715.Count Apples and Oranges/README_EN.md @@ -89,11 +89,9 @@ Total number of oranges = 15 + 25 + 8 + 28 + 15 + 15 + 17 = 123 ## Solutions - - -`LEFT JOIN` and `IFNULL`. +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -106,3 +104,5 @@ FROM ``` + + diff --git a/solution/1700-1799/1716.Calculate Money in Leetcode Bank/README.md b/solution/1700-1799/1716.Calculate Money in Leetcode Bank/README.md index 95d94082fed53..0c1f16efd97a6 100644 --- a/solution/1700-1799/1716.Calculate Money in Leetcode Bank/README.md +++ b/solution/1700-1799/1716.Calculate Money in Leetcode Bank/README.md @@ -45,16 +45,10 @@ ## 解法 - - -等差数列。 +### 方法一 -### **Python3** - - - ```python class Solution: def totalMoney(self, n: int) -> int: @@ -62,10 +56,6 @@ class Solution: return (28 + 28 + 7 * (a - 1)) * a // 2 + (a * 2 + b + 1) * b // 2 ``` -### **Java** - - - ```java class Solution { public int totalMoney(int n) { @@ -75,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +75,6 @@ public: }; ``` -### **Go** - ```go func totalMoney(n int) int { a, b := n/7, n%7 @@ -96,10 +82,6 @@ func totalMoney(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1716.Calculate Money in Leetcode Bank/README_EN.md b/solution/1700-1799/1716.Calculate Money in Leetcode Bank/README_EN.md index d2e8024e9dfe5..84ed34c172bb4 100644 --- a/solution/1700-1799/1716.Calculate Money in Leetcode Bank/README_EN.md +++ b/solution/1700-1799/1716.Calculate Money in Leetcode Bank/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return (28 + 28 + 7 * (a - 1)) * a // 2 + (a * 2 + b + 1) * b // 2 ``` -### **Java** - ```java class Solution { public int totalMoney(int n) { @@ -66,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -78,8 +74,6 @@ public: }; ``` -### **Go** - ```go func totalMoney(n int) int { a, b := n/7, n%7 @@ -87,10 +81,6 @@ func totalMoney(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1717.Maximum Score From Removing Substrings/README.md b/solution/1700-1799/1717.Maximum Score From Removing Substrings/README.md index 194395e4fb832..185294c7bca79 100644 --- a/solution/1700-1799/1717.Maximum Score From Removing Substrings/README.md +++ b/solution/1700-1799/1717.Maximum Score From Removing Substrings/README.md @@ -54,16 +54,10 @@ ## 解法 - - -不失一般性,可以设 `x >= y`。因此,可以先删除所有 "ab",再删除所有 "ba",获取最终得分 ans。 +### 方法一 -### **Python3** - - - ```python class Solution: def maximumGain(self, s: str, x: int, y: int) -> int: @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumGain(String s, int x, int y) { @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -178,8 +166,6 @@ public: }; ``` -### **Go** - ```go func maximumGain(s string, x int, y int) int { if x < y { @@ -220,10 +206,6 @@ func maximumGain(s string, x int, y int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1717.Maximum Score From Removing Substrings/README_EN.md b/solution/1700-1799/1717.Maximum Score From Removing Substrings/README_EN.md index 4d0f4c5569976..64d6fbb56bdad 100644 --- a/solution/1700-1799/1717.Maximum Score From Removing Substrings/README_EN.md +++ b/solution/1700-1799/1717.Maximum Score From Removing Substrings/README_EN.md @@ -52,9 +52,9 @@ Total score = 5 + 4 + 5 + 5 = 19. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -85,8 +85,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumGain(String s, int x, int y) { @@ -126,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +164,6 @@ public: }; ``` -### **Go** - ```go func maximumGain(s string, x int, y int) int { if x < y { @@ -210,10 +204,6 @@ func maximumGain(s string, x int, y int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1718.Construct the Lexicographically Largest Valid Sequence/README.md b/solution/1700-1799/1718.Construct the Lexicographically Largest Valid Sequence/README.md index d9dcef41ad30b..f008c87d4d431 100644 --- a/solution/1700-1799/1718.Construct the Lexicographically Largest Valid Sequence/README.md +++ b/solution/1700-1799/1718.Construct the Lexicographically Largest Valid Sequence/README.md @@ -45,16 +45,10 @@ ## 解法 - - -DFS 回溯。 +### 方法一 -### **Python3** - - - ```python class Solution: def constructDistancedSequence(self, n: int) -> List[int]: @@ -85,10 +79,6 @@ class Solution: return path[1:] ``` -### **Java** - - - ```java class Solution { private int[] path; @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -186,8 +174,6 @@ public: }; ``` -### **Go** - ```go func constructDistancedSequence(n int) []int { path := make([]int, n*2) @@ -231,10 +217,6 @@ func constructDistancedSequence(n int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1718.Construct the Lexicographically Largest Valid Sequence/README_EN.md b/solution/1700-1799/1718.Construct the Lexicographically Largest Valid Sequence/README_EN.md index cd3af20cdc173..2b79eb7e166ba 100644 --- a/solution/1700-1799/1718.Construct the Lexicographically Largest Valid Sequence/README_EN.md +++ b/solution/1700-1799/1718.Construct the Lexicographically Largest Valid Sequence/README_EN.md @@ -43,12 +43,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python class Solution: def constructDistancedSequence(self, n: int) -> List[int]: @@ -79,8 +77,6 @@ class Solution: return path[1:] ``` -### **Java** - ```java class Solution { private int[] path; @@ -135,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -178,8 +172,6 @@ public: }; ``` -### **Go** - ```go func constructDistancedSequence(n int) []int { path := make([]int, n*2) @@ -223,10 +215,6 @@ func constructDistancedSequence(n int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1719.Number Of Ways To Reconstruct A Tree/README.md b/solution/1700-1799/1719.Number Of Ways To Reconstruct A Tree/README.md index e15bf3fad528c..df914e58cc84c 100644 --- a/solution/1700-1799/1719.Number Of Ways To Reconstruct A Tree/README.md +++ b/solution/1700-1799/1719.Number Of Ways To Reconstruct A Tree/README.md @@ -72,24 +72,10 @@ ## 解法 - - -题目性质:假设祖先节点为 x ,后代节点为 y ,则 x 在 pairs 中的出现次数一定大于等于 y 在 pairs 中的出现次数,且当等号成立时 x、y 可互换位置。 - -思路: - -1. 用邻接矩阵、邻接表存放 pairs。 -1. 将树中所有节点 nodes 按照出现的次数升序排列。设置 equal 标志,用来记录是否出现“次数相同”的祖孙节点,root 用来记录没有父节点的节点数。 -1. 遍历每个节点 `nodes[i]`(记为 x),找出出现次数大于 x 的节点 y。如果 x 跟 y 构成祖孙关系,那么 y 的邻居 z 也需要构成祖孙关系。否则直接返回 0。 - -遍历结束,判断 root 的个数,若大于 1,说明不满足只有一个根节点,返回 0。若 equal 为真,说明存在可互换祖孙关系的节点对,返回 2;否则返回 1。 +### 方法一 -### **Python3** - - - ```python class Solution: def checkWays(self, pairs: List[List[int]]) -> int: @@ -125,10 +111,6 @@ class Solution: return 2 if equal else 1 ``` -### **Java** - - - ```java class Solution { public int checkWays(int[][] pairs) { @@ -179,8 +161,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -224,8 +204,6 @@ public: }; ``` -### **Go** - ```go func checkWays(pairs [][]int) int { g := make([][]bool, 510) @@ -280,10 +258,6 @@ func checkWays(pairs [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1719.Number Of Ways To Reconstruct A Tree/README_EN.md b/solution/1700-1799/1719.Number Of Ways To Reconstruct A Tree/README_EN.md index 1df6402a1b9e1..f03962d4024e9 100644 --- a/solution/1700-1799/1719.Number Of Ways To Reconstruct A Tree/README_EN.md +++ b/solution/1700-1799/1719.Number Of Ways To Reconstruct A Tree/README_EN.md @@ -68,9 +68,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -107,8 +107,6 @@ class Solution: return 2 if equal else 1 ``` -### **Java** - ```java class Solution { public int checkWays(int[][] pairs) { @@ -159,8 +157,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -204,8 +200,6 @@ public: }; ``` -### **Go** - ```go func checkWays(pairs [][]int) int { g := make([][]bool, 510) @@ -260,10 +254,6 @@ func checkWays(pairs [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1720.Decode XORed Array/README.md b/solution/1700-1799/1720.Decode XORed Array/README.md index 89caf95431eca..946aa01459c20 100644 --- a/solution/1700-1799/1720.Decode XORed Array/README.md +++ b/solution/1700-1799/1720.Decode XORed Array/README.md @@ -44,18 +44,10 @@ ## 解法 - - -异或运算。 - -`a = b ^ c` => `a ^ b = b ^ c ^ b` => `c = a ^ b`。 +### 方法一 -### **Python3** - - - ```python class Solution: def decode(self, encoded: List[int], first: int) -> List[int]: @@ -65,10 +57,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] decode(int[] encoded, int first) { @@ -83,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +83,6 @@ public: }; ``` -### **Go** - ```go func decode(encoded []int, first int) []int { ans := []int{first} @@ -109,10 +93,6 @@ func decode(encoded []int, first int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1720.Decode XORed Array/README_EN.md b/solution/1700-1799/1720.Decode XORed Array/README_EN.md index 3cedc2856c401..46d1dd53bcfa0 100644 --- a/solution/1700-1799/1720.Decode XORed Array/README_EN.md +++ b/solution/1700-1799/1720.Decode XORed Array/README_EN.md @@ -40,14 +40,10 @@ ## Solutions -XOR. - -`a = b ^ c` => `a ^ b = b ^ c ^ b` => `c = a ^ b`. +### Solution 1 -### **Python3** - ```python class Solution: def decode(self, encoded: List[int], first: int) -> List[int]: @@ -57,8 +53,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] decode(int[] encoded, int first) { @@ -73,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +79,6 @@ public: }; ``` -### **Go** - ```go func decode(encoded []int, first int) []int { ans := []int{first} @@ -99,10 +89,6 @@ func decode(encoded []int, first int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1721.Swapping Nodes in a Linked List/README.md b/solution/1700-1799/1721.Swapping Nodes in a Linked List/README.md index a60530f50177c..7ad2e4b536efc 100644 --- a/solution/1700-1799/1721.Swapping Nodes in a Linked List/README.md +++ b/solution/1700-1799/1721.Swapping Nodes in a Linked List/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:快慢指针** +### 方法一:快慢指针 我们可以先用快指针 $fast$ 找到链表的第 $k$ 个节点,用指针 $p$ 指向它。然后我们再用慢指针 $slow$ 从链表的头节点出发,快慢指针同时向后移动,当快指针到达链表的最后一个节点时,慢指针 $slow$ 恰好指向倒数第 $k$ 个节点,用指针 $q$ 指向它。此时,我们只需要交换 $p$ 和 $q$ 的值即可。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -92,10 +86,6 @@ class Solution: return head ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -187,8 +173,6 @@ func swapNodes(head *ListNode, k int) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -218,8 +202,6 @@ function swapNodes(head: ListNode | null, k: number): ListNode | null { } ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -253,10 +235,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1721.Swapping Nodes in a Linked List/README_EN.md b/solution/1700-1799/1721.Swapping Nodes in a Linked List/README_EN.md index 163a8a65a8f3e..9fe97bb445056 100644 --- a/solution/1700-1799/1721.Swapping Nodes in a Linked List/README_EN.md +++ b/solution/1700-1799/1721.Swapping Nodes in a Linked List/README_EN.md @@ -34,7 +34,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We can first use a fast pointer `fast` to find the $k$th node of the linked list, and use a pointer `p` to point to it. Then, we use a slow pointer `slow` to start from the head node of the linked list, and move both pointers forward at the same time. When the fast pointer reaches the last node of the linked list, the slow pointer `slow` points to the $k$th node from the end of the linked list, and we use a pointer `q` to point to it. At this point, we only need to swap the values of `p` and `q`. @@ -42,8 +42,6 @@ The time complexity is $O(n)$, where $n$ is the length of the linked list. The s -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -63,8 +61,6 @@ class Solution: return head ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -97,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -130,8 +124,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -156,8 +148,6 @@ func swapNodes(head *ListNode, k int) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -187,8 +177,6 @@ function swapNodes(head: ListNode | null, k: number): ListNode | null { } ``` -### **C#** - ```cs /** * Definition for singly-linked list. @@ -222,10 +210,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/README.md b/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/README.md index d687e51498635..8cfbdf13a740e 100644 --- a/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/README.md +++ b/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/README.md @@ -53,9 +53,7 @@ source 和 target 间的汉明距离是 2 ,二者有 2 处元素不同,在 ## 解法 - - -**方法一:并查集 + 哈希表** +### 方法一:并查集 + 哈希表 我们可以将每个下标看作一个节点,每个下标对应的元素看作节点的值,那么给定的 `allowedSwaps` 中的每个元素 `[a_i, b_i]` 就表示下标 `a_i` 和 `b_i` 之间存在一条边。因此,我们可以使用并查集来维护这些连通分量。 @@ -65,10 +63,6 @@ source 和 target 间的汉明距离是 2 ,二者有 2 处元素不同,在 -### **Python3** - - - ```python class Solution: def minimumHammingDistance( @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +155,6 @@ public: }; ``` -### **Go** - ```go func minimumHammingDistance(source []int, target []int, allowedSwaps [][]int) (ans int) { n := len(source) @@ -205,8 +191,6 @@ func minimumHammingDistance(source []int, target []int, allowedSwaps [][]int) (a } ``` -### **TypeScript** - ```ts function minimumHammingDistance( source: number[], @@ -246,10 +230,6 @@ function minimumHammingDistance( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/README_EN.md b/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/README_EN.md index 6be207e77fa02..b39f23cae6cb3 100644 --- a/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/README_EN.md +++ b/solution/1700-1799/1722.Minimize Hamming Distance After Swap Operations/README_EN.md @@ -53,7 +53,7 @@ The Hamming distance of source and target is 2 as they differ in 2 positions: in ## Solutions -**Solution 1: Union-Find + Hash Table** +### Solution 1: Union-Find + Hash Table We can consider each index as a node, and the element corresponding to each index as the value of the node. Then each element `[a_i, b_i]` in the given `allowedSwaps` represents an edge between index `a_i` and `b_i`. Therefore, we can use a union-find set to maintain these connected components. @@ -63,8 +63,6 @@ The time complexity is $O(n \times \log n)$ or $O(n \times \alpha(n))$, and the -### **Python3** - ```python class Solution: def minimumHammingDistance( @@ -91,8 +89,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] p; @@ -131,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +155,6 @@ public: }; ``` -### **Go** - ```go func minimumHammingDistance(source []int, target []int, allowedSwaps [][]int) (ans int) { n := len(source) @@ -199,8 +191,6 @@ func minimumHammingDistance(source []int, target []int, allowedSwaps [][]int) (a } ``` -### **TypeScript** - ```ts function minimumHammingDistance( source: number[], @@ -240,10 +230,6 @@ function minimumHammingDistance( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1723.Find Minimum Time to Finish All Jobs/README.md b/solution/1700-1799/1723.Find Minimum Time to Finish All Jobs/README.md index 8b91b4104c9f1..8ef9281948622 100644 --- a/solution/1700-1799/1723.Find Minimum Time to Finish All Jobs/README.md +++ b/solution/1700-1799/1723.Find Minimum Time to Finish All Jobs/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:DFS + 剪枝** +### 方法一:DFS + 剪枝 本题与 [2305. 公平分发饼干](/solution/2300-2399/2305.Fair%20Distribution%20of%20Cookies/README.md) 基本一致,不同的地方仅在于 $k$ 值的大小。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def minimumTimeRequired(self, jobs: List[int], k: int) -> int: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] cnt; @@ -131,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go func minimumTimeRequired(jobs []int, k int) int { cnt := make([]int, k) @@ -195,10 +181,6 @@ func minimumTimeRequired(jobs []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1723.Find Minimum Time to Finish All Jobs/README_EN.md b/solution/1700-1799/1723.Find Minimum Time to Finish All Jobs/README_EN.md index b6576e820f9a2..45dee7cb1e679 100644 --- a/solution/1700-1799/1723.Find Minimum Time to Finish All Jobs/README_EN.md +++ b/solution/1700-1799/1723.Find Minimum Time to Finish All Jobs/README_EN.md @@ -39,9 +39,9 @@ The maximum working time is 11. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] cnt; @@ -115,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +142,6 @@ public: }; ``` -### **Go** - ```go func minimumTimeRequired(jobs []int, k int) int { cnt := make([]int, k) @@ -179,10 +173,6 @@ func minimumTimeRequired(jobs []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/README.md b/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/README.md index db8c358982c8c..7349ad3006ccb 100644 --- a/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/README.md +++ b/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/README.md @@ -56,16 +56,10 @@ distanceLimitedPathsExist.query(0, 5, 6); // 返回 false。从 0 到 5 之间 ## 解法 - - -**方法一:可持久化并查集** +### 方法一:可持久化并查集 -### **Python3** - - - ```python class PersistentUnionFind: def __init__(self, n): @@ -104,10 +98,6 @@ class DistanceLimitedPathsExist: return self.puf.find(p, limit) == self.puf.find(q, limit) ``` -### **Java** - - - ```java class PersistentUnionFind { private final int inf = 1 << 30; @@ -175,8 +165,6 @@ public class DistanceLimitedPathsExist { */ ``` -### **C++** - ```cpp class PersistentUnionFind { private: @@ -250,8 +238,6 @@ public: */ ``` -### **Go** - ```go type PersistentUnionFind struct { rank []int @@ -335,8 +321,6 @@ func (dle *DistanceLimitedPathsExist) Query(p, q, limit int) bool { */ ``` -### **TypeScript** - ```ts class PersistentUnionFind { private rank: number[]; @@ -402,10 +386,6 @@ class DistanceLimitedPathsExist { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/README_EN.md b/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/README_EN.md index 0a28ab49f72b5..97aa422cde542 100644 --- a/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/README_EN.md +++ b/solution/1700-1799/1724.Checking Existence of Edge Length Limited Paths II/README_EN.md @@ -49,9 +49,9 @@ distanceLimitedPathsExist.query(0, 5, 6); // return false. There are no paths fr ## Solutions - +### Solution 1 -### **Python3** + ```python class PersistentUnionFind: @@ -91,8 +91,6 @@ class DistanceLimitedPathsExist: return self.puf.find(p, limit) == self.puf.find(q, limit) ``` -### **Java** - ```java class PersistentUnionFind { private final int inf = 1 << 30; @@ -160,8 +158,6 @@ public class DistanceLimitedPathsExist { */ ``` -### **C++** - ```cpp class PersistentUnionFind { private: @@ -235,8 +231,6 @@ public: */ ``` -### **Go** - ```go type PersistentUnionFind struct { rank []int @@ -320,8 +314,6 @@ func (dle *DistanceLimitedPathsExist) Query(p, q, limit int) bool { */ ``` -### **TypeScript** - ```ts class PersistentUnionFind { private rank: number[]; @@ -387,10 +379,6 @@ class DistanceLimitedPathsExist { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README.md b/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README.md index 6f428b5f85ef8..a0f636e6e4e58 100644 --- a/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README.md +++ b/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们定义一个变量 $ans$ 来记录当前最大边长的正方形的个数,定义另一个变量 $mx$ 来记录当前最大的边长。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def countGoodRectangles(self, rectangles: List[List[int]]) -> int: @@ -77,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countGoodRectangles(int[][] rectangles) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func countGoodRectangles(rectangles [][]int) (ans int) { mx := 0 @@ -138,8 +124,6 @@ func countGoodRectangles(rectangles [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function countGoodRectangles(rectangles: number[][]): number { let [ans, mx] = [0, 0]; @@ -156,10 +140,6 @@ function countGoodRectangles(rectangles: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README_EN.md b/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README_EN.md index 076da9d7f7269..bd195f8232e2e 100644 --- a/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README_EN.md +++ b/solution/1700-1799/1725.Number Of Rectangles That Can Form The Largest Square/README_EN.md @@ -41,7 +41,7 @@ The largest possible square is of length 5, and you can get it out of 3 rectangl ## Solutions -**Solution 1: Single Pass** +### Solution 1: Single Pass We define a variable $ans$ to record the count of squares with the current maximum side length, and another variable $mx$ to record the current maximum side length. @@ -53,8 +53,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $rectangles$ -### **Python3** - ```python class Solution: def countGoodRectangles(self, rectangles: List[List[int]]) -> int: @@ -69,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countGoodRectangles(int[][] rectangles) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func countGoodRectangles(rectangles [][]int) (ans int) { mx := 0 @@ -128,8 +120,6 @@ func countGoodRectangles(rectangles [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function countGoodRectangles(rectangles: number[][]): number { let [ans, mx] = [0, 0]; @@ -146,10 +136,6 @@ function countGoodRectangles(rectangles: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1726.Tuple with Same Product/README.md b/solution/1700-1799/1726.Tuple with Same Product/README.md index f5f0557fabcd6..220597a607b57 100644 --- a/solution/1700-1799/1726.Tuple with Same Product/README.md +++ b/solution/1700-1799/1726.Tuple with Same Product/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:组合数 + 哈希表** +### 方法一:组合数 + 哈希表 假设存在 $n$ 组数,对于其中任意两组数 $a, b$ 和 $c, d$,均满足 $a \times b = c \times d$ 的条件,则这样的组合一共有 $\mathrm{C}_n^2 = \frac{n \times (n-1)}{2}$ 个。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def tupleSameProduct(self, nums: List[int]) -> int: @@ -71,10 +65,6 @@ class Solution: return sum(v * (v - 1) // 2 for v in cnt.values()) << 3 ``` -### **Java** - - - ```java class Solution { public int tupleSameProduct(int[] nums) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func tupleSameProduct(nums []int) int { cnt := map[int]int{} @@ -135,7 +121,22 @@ func tupleSameProduct(nums []int) int { } ``` -### **Rust** +```ts +function tupleSameProduct(nums: number[]): number { + const cnt: Map = new Map(); + for (let i = 1; i < nums.length; ++i) { + for (let j = 0; j < i; ++j) { + const x = nums[i] * nums[j]; + cnt.set(x, (cnt.get(x) ?? 0) + 1); + } + } + let ans = 0; + for (const [_, v] of cnt) { + ans += (v * (v - 1)) / 2; + } + return ans << 3; +} +``` ```rust use std::collections::HashMap; @@ -161,29 +162,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function tupleSameProduct(nums: number[]): number { - const cnt: Map = new Map(); - for (let i = 1; i < nums.length; ++i) { - for (let j = 0; j < i; ++j) { - const x = nums[i] * nums[j]; - cnt.set(x, (cnt.get(x) ?? 0) + 1); - } - } - let ans = 0; - for (const [_, v] of cnt) { - ans += (v * (v - 1)) / 2; - } - return ans << 3; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1726.Tuple with Same Product/README_EN.md b/solution/1700-1799/1726.Tuple with Same Product/README_EN.md index 471f0d5cedbbb..a090da8cd7ec2 100644 --- a/solution/1700-1799/1726.Tuple with Same Product/README_EN.md +++ b/solution/1700-1799/1726.Tuple with Same Product/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Combination + Hash Table** +### Solution 1: Combination + Hash Table Assuming there are $n$ pairs of numbers, for any two pairs of numbers $a, b$ and $c, d$ that satisfy the condition $a \times b = c \times d$, there are a total of $\mathrm{C}_n^2 = \frac{n \times (n-1)}{2}$ such combinations. @@ -50,8 +50,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ -### **Python3** - ```python class Solution: def tupleSameProduct(self, nums: List[int]) -> int: @@ -63,8 +61,6 @@ class Solution: return sum(v * (v - 1) // 2 for v in cnt.values()) << 3 ``` -### **Java** - ```java class Solution { public int tupleSameProduct(int[] nums) { @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +100,6 @@ public: }; ``` -### **Go** - ```go func tupleSameProduct(nums []int) int { cnt := map[int]int{} @@ -125,7 +117,22 @@ func tupleSameProduct(nums []int) int { } ``` -### **Rust** +```ts +function tupleSameProduct(nums: number[]): number { + const cnt: Map = new Map(); + for (let i = 1; i < nums.length; ++i) { + for (let j = 0; j < i; ++j) { + const x = nums[i] * nums[j]; + cnt.set(x, (cnt.get(x) ?? 0) + 1); + } + } + let ans = 0; + for (const [_, v] of cnt) { + ans += (v * (v - 1)) / 2; + } + return ans << 3; +} +``` ```rust use std::collections::HashMap; @@ -151,29 +158,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function tupleSameProduct(nums: number[]): number { - const cnt: Map = new Map(); - for (let i = 1; i < nums.length; ++i) { - for (let j = 0; j < i; ++j) { - const x = nums[i] * nums[j]; - cnt.set(x, (cnt.get(x) ?? 0) + 1); - } - } - let ans = 0; - for (const [_, v] of cnt) { - ans += (v * (v - 1)) / 2; - } - return ans << 3; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1727.Largest Submatrix With Rearrangements/README.md b/solution/1700-1799/1727.Largest Submatrix With Rearrangements/README.md index ce3d614685df2..75f3d03c20ce5 100644 --- a/solution/1700-1799/1727.Largest Submatrix With Rearrangements/README.md +++ b/solution/1700-1799/1727.Largest Submatrix With Rearrangements/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:预处理 + 排序** +### 方法一:预处理 + 排序 由于题目中矩阵是按列进行重排,因此,我们可以先对矩阵的每一列进行预处理。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def largestSubmatrix(self, matrix: List[List[int]]) -> int: @@ -96,10 +90,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int largestSubmatrix(int[][] matrix) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func largestSubmatrix(matrix [][]int) int { m, n := len(matrix), len(matrix[0]) @@ -173,8 +159,6 @@ func largestSubmatrix(matrix [][]int) int { } ``` -### **TypeScript** - ```ts function largestSubmatrix(matrix: number[][]): number { for (let column = 0; column < matrix[0].length; column++) { @@ -214,10 +198,6 @@ function largestSubmatrix(matrix: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1727.Largest Submatrix With Rearrangements/README_EN.md b/solution/1700-1799/1727.Largest Submatrix With Rearrangements/README_EN.md index 0f6883e97199a..82e3b83b2a8ce 100644 --- a/solution/1700-1799/1727.Largest Submatrix With Rearrangements/README_EN.md +++ b/solution/1700-1799/1727.Largest Submatrix With Rearrangements/README_EN.md @@ -47,9 +47,9 @@ The largest submatrix of 1s, in bold, has an area of 3. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int largestSubmatrix(int[][] matrix) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func largestSubmatrix(matrix [][]int) int { m, n := len(matrix), len(matrix[0]) @@ -141,8 +135,6 @@ func largestSubmatrix(matrix [][]int) int { } ``` -### **TypeScript** - ```ts function largestSubmatrix(matrix: number[][]): number { for (let column = 0; column < matrix[0].length; column++) { @@ -182,10 +174,6 @@ function largestSubmatrix(matrix: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1728.Cat and Mouse II/README.md b/solution/1700-1799/1728.Cat and Mouse II/README.md index caf1c7bbf5f59..e6158b22f9ebb 100644 --- a/solution/1700-1799/1728.Cat and Mouse II/README.md +++ b/solution/1700-1799/1728.Cat and Mouse II/README.md @@ -96,14 +96,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool: @@ -177,18 +173,6 @@ class Solution: return dp(cat, mouse, 0) ``` -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1728.Cat and Mouse II/README_EN.md b/solution/1700-1799/1728.Cat and Mouse II/README_EN.md index 7a587affbb430..fb2bfc593c40b 100644 --- a/solution/1700-1799/1728.Cat and Mouse II/README_EN.md +++ b/solution/1700-1799/1728.Cat and Mouse II/README_EN.md @@ -74,9 +74,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -151,16 +151,6 @@ class Solution: return dp(cat, mouse, 0) ``` -### **Java** - -```java - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1729.Find Followers Count/README.md b/solution/1700-1799/1729.Find Followers Count/README.md index 504e57f659af5..6b4d2ed917c06 100644 --- a/solution/1700-1799/1729.Find Followers Count/README.md +++ b/solution/1700-1799/1729.Find Followers Count/README.md @@ -56,16 +56,12 @@ Followers 表: ## 解法 - - -**方法一:分组统计** +### 方法一:分组统计 我们可以直接对 `Followers` 表按照 `user_id` 进行分组,然后使用 `COUNT` 函数统计每个用户的关注者数量即可。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT user_id, COUNT(1) AS followers_count @@ -75,3 +71,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1700-1799/1729.Find Followers Count/README_EN.md b/solution/1700-1799/1729.Find Followers Count/README_EN.md index ae3186b2a42d3..974bfb67693e4 100644 --- a/solution/1700-1799/1729.Find Followers Count/README_EN.md +++ b/solution/1700-1799/1729.Find Followers Count/README_EN.md @@ -54,14 +54,12 @@ The followers of 2 are {0,1} ## Solutions -**Solution 1: Grouping and Aggregation** +### Solution 1: Grouping and Aggregation We can directly group the `Followers` table by `user_id`, and use the `COUNT` function to count the number of followers for each user. -### **SQL** - ```sql # Write your MySQL query statement below SELECT user_id, COUNT(1) AS followers_count @@ -71,3 +69,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1700-1799/1730.Shortest Path to Get Food/README.md b/solution/1700-1799/1730.Shortest Path to Get Food/README.md index c69858a6ccb9d..1554cb17c963f 100644 --- a/solution/1700-1799/1730.Shortest Path to Get Food/README.md +++ b/solution/1700-1799/1730.Shortest Path to Get Food/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 根据题意,我们需要从 `*` 出发,找到最近的 `#`,返回最短路径长度。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def getFood(self, grid: List[List[str]]) -> int: @@ -98,10 +92,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { private int[] dirs = {-1, 0, 1, 0, -1}; @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -185,8 +173,6 @@ public: }; ``` -### **Go** - ```go func getFood(grid [][]byte) (ans int) { m, n := len(grid), len(grid[0]) @@ -225,8 +211,6 @@ func getFood(grid [][]byte) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {character[][]} grid @@ -270,10 +254,6 @@ var getFood = function (grid) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1730.Shortest Path to Get Food/README_EN.md b/solution/1700-1799/1730.Shortest Path to Get Food/README_EN.md index efbdaf4f9242b..14b4bd541a516 100644 --- a/solution/1700-1799/1730.Shortest Path to Get Food/README_EN.md +++ b/solution/1700-1799/1730.Shortest Path to Get Food/README_EN.md @@ -56,12 +56,10 @@ ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def getFood(self, grid: List[List[str]]) -> int: @@ -85,8 +83,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { private int[] dirs = {-1, 0, 1, 0, -1}; @@ -128,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +164,6 @@ public: }; ``` -### **Go** - ```go func getFood(grid [][]byte) (ans int) { m, n := len(grid), len(grid[0]) @@ -210,8 +202,6 @@ func getFood(grid [][]byte) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {character[][]} grid @@ -255,10 +245,6 @@ var getFood = function (grid) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1731.The Number of Employees Which Report to Each Employee/README.md b/solution/1700-1799/1731.The Number of Employees Which Report to Each Employee/README.md index c75353099715c..645cc9895025f 100644 --- a/solution/1700-1799/1731.The Number of Employees Which Report to Each Employee/README.md +++ b/solution/1700-1799/1731.The Number of Employees Which Report to Each Employee/README.md @@ -53,16 +53,12 @@ Hercy 有两个需要向他汇报的员工, 他们是 Alice and Bob. 他们的 ## 解法 - - -**方法一:自连接 + 分组统计** +### 方法一:自连接 + 分组统计 我们可以通过自连接的方式,将每个员工的上级经理信息连接到每个员工的信息上,然后再通过分组统计的方式,统计每个经理的下属员工数量和平均年龄。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -78,3 +74,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1700-1799/1731.The Number of Employees Which Report to Each Employee/README_EN.md b/solution/1700-1799/1731.The Number of Employees Which Report to Each Employee/README_EN.md index daef18999f982..2a6e284e13c35 100644 --- a/solution/1700-1799/1731.The Number of Employees Which Report to Each Employee/README_EN.md +++ b/solution/1700-1799/1731.The Number of Employees Which Report to Each Employee/README_EN.md @@ -54,14 +54,12 @@ Employees table: ## Solutions -**Solution 1: Self-Join + Grouping** +### Solution 1: Self-Join + Grouping We can use self-join to connect the information of each employee's superior manager to the information of each employee, and then use grouping and aggregation to count the number of subordinates and the average age of each manager. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -77,3 +75,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1700-1799/1732.Find the Highest Altitude/README.md b/solution/1700-1799/1732.Find the Highest Altitude/README.md index 717d947a9834d..6352f1dee88dc 100644 --- a/solution/1700-1799/1732.Find the Highest Altitude/README.md +++ b/solution/1700-1799/1732.Find the Highest Altitude/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:前缀和(差分数组)** +### 方法一:前缀和(差分数组) 我们假设每个点的海拔为 $h_i$,由于 $gain[i]$ 表示第 $i$ 个点和第 $i + 1$ 个点的海拔差,因此 $gain[i] = h_{i + 1} - h_i$。那么: @@ -64,30 +62,12 @@ $$ -### **Python3** - - - ```python class Solution: def largestAltitude(self, gain: List[int]) -> int: return max(accumulate(gain, initial=0)) ``` -```python -class Solution: - def largestAltitude(self, gain: List[int]) -> int: - ans = h = 0 - for v in gain: - h += v - ans = max(ans, h) - return ans -``` - -### **Java** - - - ```java class Solution { public int largestAltitude(int[] gain) { @@ -101,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +92,6 @@ public: }; ``` -### **Go** - ```go func largestAltitude(gain []int) (ans int) { h := 0 @@ -129,26 +105,6 @@ func largestAltitude(gain []int) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} gain - * @return {number} - */ -var largestAltitude = function (gain) { - let ans = 0; - let h = 0; - for (const v of gain) { - h += v; - ans = Math.max(ans, h); - } - return ans; -}; -``` - -### **Rust** - ```rust impl Solution { pub fn largest_altitude(gain: Vec) -> i32 { @@ -163,24 +119,22 @@ impl Solution { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int largestAltitude(int* gain, int gainSize) { - int ans = 0; - int h = 0; - for (int i = 0; i < gainSize; i++) { - h += gain[i]; - ans = max(ans, h); +```js +/** + * @param {number[]} gain + * @return {number} + */ +var largestAltitude = function (gain) { + let ans = 0; + let h = 0; + for (const v of gain) { + h += v; + ans = Math.max(ans, h); } return ans; -} +}; ``` -### **PHP** - ```php class Solution { /** @@ -200,10 +154,36 @@ class Solution { } ``` -### **...** +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +int largestAltitude(int* gain, int gainSize) { + int ans = 0; + int h = 0; + for (int i = 0; i < gainSize; i++) { + h += gain[i]; + ans = max(ans, h); + } + return ans; +} ``` + + +### 方法二 + + + +```python +class Solution: + def largestAltitude(self, gain: List[int]) -> int: + ans = h = 0 + for v in gain: + h += v + ans = max(ans, h) + return ans ``` + + diff --git a/solution/1700-1799/1732.Find the Highest Altitude/README_EN.md b/solution/1700-1799/1732.Find the Highest Altitude/README_EN.md index a6176f7dee71b..570c8a4f84a6a 100644 --- a/solution/1700-1799/1732.Find the Highest Altitude/README_EN.md +++ b/solution/1700-1799/1732.Find the Highest Altitude/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Prefix Sum (Difference Array)** +### Solution 1: Prefix Sum (Difference Array) We assume the altitude of each point is $h_i$. Since $gain[i]$ represents the altitude difference between the $i$th point and the $(i + 1)$th point, we have $gain[i] = h_{i + 1} - h_i$. Therefore: @@ -58,26 +58,12 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is -### **Python3** - ```python class Solution: def largestAltitude(self, gain: List[int]) -> int: return max(accumulate(gain, initial=0)) ``` -```python -class Solution: - def largestAltitude(self, gain: List[int]) -> int: - ans = h = 0 - for v in gain: - h += v - ans = max(ans, h) - return ans -``` - -### **Java** - ```java class Solution { public int largestAltitude(int[] gain) { @@ -91,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +88,6 @@ public: }; ``` -### **Go** - ```go func largestAltitude(gain []int) (ans int) { h := 0 @@ -119,26 +101,6 @@ func largestAltitude(gain []int) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} gain - * @return {number} - */ -var largestAltitude = function (gain) { - let ans = 0; - let h = 0; - for (const v of gain) { - h += v; - ans = Math.max(ans, h); - } - return ans; -}; -``` - -### **Rust** - ```rust impl Solution { pub fn largest_altitude(gain: Vec) -> i32 { @@ -153,24 +115,22 @@ impl Solution { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int largestAltitude(int* gain, int gainSize) { - int ans = 0; - int h = 0; - for (int i = 0; i < gainSize; i++) { - h += gain[i]; - ans = max(ans, h); +```js +/** + * @param {number[]} gain + * @return {number} + */ +var largestAltitude = function (gain) { + let ans = 0; + let h = 0; + for (const v of gain) { + h += v; + ans = Math.max(ans, h); } return ans; -} +}; ``` -### **PHP** - ```php class Solution { /** @@ -190,10 +150,36 @@ class Solution { } ``` -### **...** +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +int largestAltitude(int* gain, int gainSize) { + int ans = 0; + int h = 0; + for (int i = 0; i < gainSize; i++) { + h += gain[i]; + ans = max(ans, h); + } + return ans; +} ``` + + +### Solution 2 + + + +```python +class Solution: + def largestAltitude(self, gain: List[int]) -> int: + ans = h = 0 + for v in gain: + h += v + ans = max(ans, h) + return ans ``` + + diff --git a/solution/1700-1799/1733.Minimum Number of People to Teach/README.md b/solution/1700-1799/1733.Minimum Number of People to Teach/README.md index ae1149354541e..e3e79f1da6d6c 100644 --- a/solution/1700-1799/1733.Minimum Number of People to Teach/README.md +++ b/solution/1700-1799/1733.Minimum Number of People to Teach/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:模拟 + 统计** +### 方法一:模拟 + 统计 对于每个好友关系,如果两个人掌握的语言集合不相交,则需要教一门语言,使得两个人可以相互沟通,我们将这些人放入一个哈希集合 $s$ 中。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def minimumTeachings( @@ -95,10 +89,6 @@ class Solution: return len(s) - max(cnt.values(), default=0) ``` -### **Java** - - - ```java class Solution { public int minimumTeachings(int n, int[][] languages, int[][] friendships) { @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -178,8 +166,6 @@ public: }; ``` -### **Go** - ```go func minimumTeachings(n int, languages [][]int, friendships [][]int) int { check := func(u, v int) bool { @@ -212,10 +198,6 @@ func minimumTeachings(n int, languages [][]int, friendships [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1733.Minimum Number of People to Teach/README_EN.md b/solution/1700-1799/1733.Minimum Number of People to Teach/README_EN.md index 6d4dfa6af8baf..b61b2b6755e91 100644 --- a/solution/1700-1799/1733.Minimum Number of People to Teach/README_EN.md +++ b/solution/1700-1799/1733.Minimum Number of People to Teach/README_EN.md @@ -50,9 +50,9 @@ Note that friendships are not transitive, meaning if x is a friend ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,8 +78,6 @@ class Solution: return len(s) - max(cnt.values(), default=0) ``` -### **Java** - ```java class Solution { public int minimumTeachings(int n, int[][] languages, int[][] friendships) { @@ -120,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +155,6 @@ public: }; ``` -### **Go** - ```go func minimumTeachings(n int, languages [][]int, friendships [][]int) int { check := func(u, v int) bool { @@ -193,10 +187,6 @@ func minimumTeachings(n int, languages [][]int, friendships [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1734.Decode XORed Permutation/README.md b/solution/1700-1799/1734.Decode XORed Permutation/README.md index 0d734544e00a4..b43896f612c16 100644 --- a/solution/1700-1799/1734.Decode XORed Permutation/README.md +++ b/solution/1700-1799/1734.Decode XORed Permutation/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 我们注意到,数组 $perm$ 是前 $n$ 个正整数的排列,因此 $perm$ 的所有元素的异或和为 $1 \oplus 2 \oplus \cdots \oplus n$,记为 $a$。而 $encode[i]=perm[i] \oplus perm[i+1]$,如果我们将 $encode[0],encode[2],\cdots,encode[n-3]$ 的所有元素的异或和记为 $b$,则 $perm[n-1]=a \oplus b$。知道了 $perm$ 的最后一个元素,我们就可以通过逆序遍历数组 $encode$ 求出 $perm$ 的所有元素。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def decode(self, encoded: List[int]) -> List[int]: @@ -69,10 +63,6 @@ class Solution: return perm ``` -### **Java** - - - ```java class Solution { public int[] decode(int[] encoded) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func decode(encoded []int) []int { n := len(encoded) + 1 @@ -139,10 +125,6 @@ func decode(encoded []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1734.Decode XORed Permutation/README_EN.md b/solution/1700-1799/1734.Decode XORed Permutation/README_EN.md index ffd79009ff24a..73e6af8990b93 100644 --- a/solution/1700-1799/1734.Decode XORed Permutation/README_EN.md +++ b/solution/1700-1799/1734.Decode XORed Permutation/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: Bitwise Operation** +### Solution 1: Bitwise Operation We notice that the array $perm$ is a permutation of the first $n$ positive integers, so the XOR of all elements in $perm$ is $1 \oplus 2 \oplus \cdots \oplus n$, denoted as $a$. And $encode[i]=perm[i] \oplus perm[i+1]$, if we denote the XOR of all elements $encode[0],encode[2],\cdots,encode[n-3]$ as $b$, then $perm[n-1]=a \oplus b$. Knowing the last element of $perm$, we can find all elements of $perm$ by traversing the array $encode$ in reverse order. @@ -45,8 +45,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $perm$. Igno -### **Python3** - ```python class Solution: def decode(self, encoded: List[int]) -> List[int]: @@ -63,8 +61,6 @@ class Solution: return perm ``` -### **Java** - ```java class Solution { public int[] decode(int[] encoded) { @@ -86,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func decode(encoded []int) []int { n := len(encoded) + 1 @@ -131,10 +123,6 @@ func decode(encoded []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1735.Count Ways to Make Array With Product/README.md b/solution/1700-1799/1735.Count Ways to Make Array With Product/README.md index e96659874822e..5353c84fbf563 100644 --- a/solution/1700-1799/1735.Count Ways to Make Array With Product/README.md +++ b/solution/1700-1799/1735.Count Ways to Make Array With Product/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:质因数分解 + 组合数学** +### 方法一:质因数分解 + 组合数学 我们可以对 $k$ 进行质因数分解,即 $k = p_1^{x_1} \times p_2^{x_2} \times \cdots \times p_m^{x_m}$,其中 $p_i$ 为质数,而 $x_i$ 为 $p_i$ 的指数。那么题目实际上等价于:把 $x_1$ 个 $p_1$, $x_2$ 个 $p_2$, $\cdots$, $x_m$ 个 $p_m$ 分别放到 $n$ 个位置上,单个位置可以为空,问有多少种方案。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python N = 10020 MOD = 10**9 + 7 @@ -103,10 +97,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int N = 10020; @@ -171,8 +161,6 @@ class Solution { } ``` -### **C++** - ```cpp int N = 10020; int MOD = 1e9 + 7; @@ -237,8 +225,6 @@ public: }; ``` -### **Go** - ```go const n = 1e4 + 20 const mod = 1e9 + 7 @@ -298,10 +284,6 @@ func waysToFillArray(queries [][]int) (ans []int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1735.Count Ways to Make Array With Product/README_EN.md b/solution/1700-1799/1735.Count Ways to Make Array With Product/README_EN.md index 692d66ed09b34..8cacb46fcdb42 100644 --- a/solution/1700-1799/1735.Count Ways to Make Array With Product/README_EN.md +++ b/solution/1700-1799/1735.Count Ways to Make Array With Product/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: Prime Factorization + Combinatorial Mathematics** +### Solution 1: Prime Factorization + Combinatorial Mathematics We can perform prime factorization on $k$, i.e., $k = p_1^{x_1} \times p_2^{x_2} \times \cdots \times p_m^{x_m}$, where $p_i$ is a prime number, and $x_i$ is the exponent of $p_i$. The problem is equivalent to: placing $x_1$ $p_1$s, $x_2$ $p_2$s, $\cdots$, $x_m$ $p_m$s into $n$ positions respectively, where a single position can be empty. The question is how many schemes are there. @@ -55,8 +55,6 @@ The time complexity is $O(K \times \log \log K + N + m \times \log K)$, and the -### **Python3** - ```python N = 10020 MOD = 10**9 + 7 @@ -95,8 +93,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int N = 10020; @@ -161,8 +157,6 @@ class Solution { } ``` -### **C++** - ```cpp int N = 10020; int MOD = 1e9 + 7; @@ -227,8 +221,6 @@ public: }; ``` -### **Go** - ```go const n = 1e4 + 20 const mod = 1e9 + 7 @@ -288,10 +280,6 @@ func waysToFillArray(queries [][]int) (ans []int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1736.Latest Time by Replacing Hidden Digits/README.md b/solution/1700-1799/1736.Latest Time by Replacing Hidden Digits/README.md index 7e718c2fd7798..d5498c5b54a66 100644 --- a/solution/1700-1799/1736.Latest Time by Replacing Hidden Digits/README.md +++ b/solution/1700-1799/1736.Latest Time by Replacing Hidden Digits/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们依次处理字符串的每一位,处理的规则如下: @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def maximumTime(self, time: str) -> str: @@ -81,10 +75,6 @@ class Solution: return ''.join(t) ``` -### **Java** - - - ```java class Solution { public String maximumTime(String time) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func maximumTime(time string) string { t := []byte(time) @@ -158,8 +144,6 @@ func maximumTime(time string) string { } ``` -### **JavaScript** - ```js /** * @param {string} time @@ -183,10 +167,6 @@ var maximumTime = function (time) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1736.Latest Time by Replacing Hidden Digits/README_EN.md b/solution/1700-1799/1736.Latest Time by Replacing Hidden Digits/README_EN.md index 10b46b009f4c1..e1813ec9466ab 100644 --- a/solution/1700-1799/1736.Latest Time by Replacing Hidden Digits/README_EN.md +++ b/solution/1700-1799/1736.Latest Time by Replacing Hidden Digits/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy We process each digit of the string in order, following these rules: @@ -56,8 +56,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def maximumTime(self, time: str) -> str: @@ -73,8 +71,6 @@ class Solution: return ''.join(t) ``` -### **Java** - ```java class Solution { public String maximumTime(String time) { @@ -96,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +113,6 @@ public: }; ``` -### **Go** - ```go func maximumTime(time string) string { t := []byte(time) @@ -148,8 +140,6 @@ func maximumTime(time string) string { } ``` -### **JavaScript** - ```js /** * @param {string} time @@ -173,10 +163,6 @@ var maximumTime = function (time) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1737.Change Minimum Characters to Satisfy One of Three Conditions/README.md b/solution/1700-1799/1737.Change Minimum Characters to Satisfy One of Three Conditions/README.md index 424b8b325461e..36932a055cf38 100644 --- a/solution/1700-1799/1737.Change Minimum Characters to Satisfy One of Three Conditions/README.md +++ b/solution/1700-1799/1737.Change Minimum Characters to Satisfy One of Three Conditions/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:计数 + 枚举** +### 方法一:计数 + 枚举 我们先统计字符串 $a$ 和 $b$ 中每个字母出现的次数,记为 $cnt_1$ 和 $cnt_2$。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def minCharacters(self, a: str, b: str) -> int: @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int ans; @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +151,6 @@ public: }; ``` -### **Go** - ```go func minCharacters(a string, b string) int { cnt1 := [26]int{} @@ -198,8 +184,6 @@ func minCharacters(a string, b string) int { } ``` -### **TypeScript** - ```ts function minCharacters(a: string, b: string): number { const m = a.length, @@ -230,10 +214,6 @@ function minCharacters(a: string, b: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1737.Change Minimum Characters to Satisfy One of Three Conditions/README_EN.md b/solution/1700-1799/1737.Change Minimum Characters to Satisfy One of Three Conditions/README_EN.md index db9f938f78ccb..e25762febb9c6 100644 --- a/solution/1700-1799/1737.Change Minimum Characters to Satisfy One of Three Conditions/README_EN.md +++ b/solution/1700-1799/1737.Change Minimum Characters to Satisfy One of Three Conditions/README_EN.md @@ -47,7 +47,7 @@ The best way was done in 2 operations (either condition 1 or condition 3). ## Solutions -**Solution 1: Counting + Enumeration** +### Solution 1: Counting + Enumeration First, we count the number of occurrences of each letter in strings $a$ and $b$, denoted as $cnt_1$ and $cnt_2$. @@ -61,8 +61,6 @@ The time complexity is $O(m + n + C^2)$, where $m$ and $n$ are the lengths of st -### **Python3** - ```python class Solution: def minCharacters(self, a: str, b: str) -> int: @@ -87,8 +85,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int ans; @@ -127,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +149,6 @@ public: }; ``` -### **Go** - ```go func minCharacters(a string, b string) int { cnt1 := [26]int{} @@ -190,8 +182,6 @@ func minCharacters(a string, b string) int { } ``` -### **TypeScript** - ```ts function minCharacters(a: string, b: string): number { const m = a.length, @@ -222,10 +212,6 @@ function minCharacters(a: string, b: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1738.Find Kth Largest XOR Coordinate Value/README.md b/solution/1700-1799/1738.Find Kth Largest XOR Coordinate Value/README.md index 0ccfd0aa5b3c3..84f4c06f9481a 100644 --- a/solution/1700-1799/1738.Find Kth Largest XOR Coordinate Value/README.md +++ b/solution/1700-1799/1738.Find Kth Largest XOR Coordinate Value/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:二维前缀异或 + 排序或快速选择** +### 方法一:二维前缀异或 + 排序或快速选择 我们定义一个二维前缀异或数组 $s$,其中 $s[i][j]$ 表示矩阵前 $i$ 行和前 $j$ 列的元素异或运算的结果,即: @@ -74,10 +72,6 @@ $$ -### **Python3** - - - ```python class Solution: def kthLargestValue(self, matrix: List[List[int]], k: int) -> int: @@ -91,10 +85,6 @@ class Solution: return nlargest(k, ans)[-1] ``` -### **Java** - - - ```java class Solution { public int kthLargestValue(int[][] matrix, int k) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func kthLargestValue(matrix [][]int, k int) int { m, n := len(matrix), len(matrix[0]) @@ -155,8 +141,6 @@ func kthLargestValue(matrix [][]int, k int) int { } ``` -### **TypeScript** - ```ts function kthLargestValue(matrix: number[][], k: number): number { const m: number = matrix.length; @@ -174,10 +158,6 @@ function kthLargestValue(matrix: number[][], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1738.Find Kth Largest XOR Coordinate Value/README_EN.md b/solution/1700-1799/1738.Find Kth Largest XOR Coordinate Value/README_EN.md index 079d29c94d819..992481d0387eb 100644 --- a/solution/1700-1799/1738.Find Kth Largest XOR Coordinate Value/README_EN.md +++ b/solution/1700-1799/1738.Find Kth Largest XOR Coordinate Value/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Two-dimensional Prefix XOR + Sorting or Quick Selection** +### Solution 1: Two-dimensional Prefix XOR + Sorting or Quick Selection We define a two-dimensional prefix XOR array $s$, where $s[i][j]$ represents the XOR result of the elements in the first $i$ rows and the first $j$ columns of the matrix, i.e., @@ -67,8 +67,6 @@ The time complexity is $O(m \times n \times \log (m \times n))$ or $O(m \times n -### **Python3** - ```python class Solution: def kthLargestValue(self, matrix: List[List[int]], k: int) -> int: @@ -82,8 +80,6 @@ class Solution: return nlargest(k, ans)[-1] ``` -### **Java** - ```java class Solution { public int kthLargestValue(int[][] matrix, int k) { @@ -102,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +117,6 @@ public: }; ``` -### **Go** - ```go func kthLargestValue(matrix [][]int, k int) int { m, n := len(matrix), len(matrix[0]) @@ -144,8 +136,6 @@ func kthLargestValue(matrix [][]int, k int) int { } ``` -### **TypeScript** - ```ts function kthLargestValue(matrix: number[][], k: number): number { const m: number = matrix.length; @@ -163,10 +153,6 @@ function kthLargestValue(matrix: number[][], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1739.Building Boxes/README.md b/solution/1700-1799/1739.Building Boxes/README.md index c8147d435fd47..775f4ba091b3c 100644 --- a/solution/1700-1799/1739.Building Boxes/README.md +++ b/solution/1700-1799/1739.Building Boxes/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:数学规律** +### 方法一:数学规律 根据题目描述,层数最高的盒子需要放在墙角,并且盒子的摆放呈阶梯状,这样可以使得接触地面的盒子数量最少。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def minimumBoxes(self, n: int) -> int: @@ -94,10 +88,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumBoxes(int n) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func minimumBoxes(n int) int { s, k := 0, 1 @@ -164,10 +150,6 @@ func minimumBoxes(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1739.Building Boxes/README_EN.md b/solution/1700-1799/1739.Building Boxes/README_EN.md index 346766ad96fc3..b64e075cab24c 100644 --- a/solution/1700-1799/1739.Building Boxes/README_EN.md +++ b/solution/1700-1799/1739.Building Boxes/README_EN.md @@ -55,7 +55,7 @@ These boxes are placed in the corner of the room, where the corner is on the bac ## Solutions -**Solution 1: Mathematical Rule** +### Solution 1: Mathematical Rule According to the problem description, the box with the highest number of layers needs to be placed in the corner of the wall, and the arrangement of the boxes is in a step-like shape, which can minimize the number of boxes touching the ground. @@ -67,8 +67,6 @@ The time complexity is $O(\sqrt{n})$, where $n$ is the number of boxes given in -### **Python3** - ```python class Solution: def minimumBoxes(self, n: int) -> int: @@ -86,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumBoxes(int n) { @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +127,6 @@ public: }; ``` -### **Go** - ```go func minimumBoxes(n int) int { s, k := 0, 1 @@ -154,10 +146,6 @@ func minimumBoxes(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1740.Find Distance in a Binary Tree/README.md b/solution/1700-1799/1740.Find Distance in a Binary Tree/README.md index d2e080cb7bd0b..68c9f10e5c553 100644 --- a/solution/1700-1799/1740.Find Distance in a Binary Tree/README.md +++ b/solution/1700-1799/1740.Find Distance in a Binary Tree/README.md @@ -46,16 +46,10 @@ ## 解法 - - -先找到两个整数节点的最近公共祖先 g。然后累加节点 g 到节点 p 和节点 q 的距离即可。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -90,10 +84,6 @@ class Solution: return dfs(g, p) + dfs(g, q) ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -148,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -189,8 +177,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -234,10 +220,6 @@ func findDistance(root *TreeNode, p int, q int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1740.Find Distance in a Binary Tree/README_EN.md b/solution/1700-1799/1740.Find Distance in a Binary Tree/README_EN.md index 56d9e28c21fec..9d866a76888f3 100644 --- a/solution/1700-1799/1740.Find Distance in a Binary Tree/README_EN.md +++ b/solution/1700-1799/1740.Find Distance in a Binary Tree/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -80,8 +80,6 @@ class Solution: return dfs(g, p) + dfs(g, q) ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -136,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -177,8 +173,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -222,10 +216,6 @@ func findDistance(root *TreeNode, p int, q int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1741.Find Total Time Spent by Each Employee/README.md b/solution/1700-1799/1741.Find Total Time Spent by Each Employee/README.md index 8534cc5a1cb47..ca9bdbbd8af4c 100644 --- a/solution/1700-1799/1741.Find Total Time Spent by Each Employee/README.md +++ b/solution/1700-1799/1741.Find Total Time Spent by Each Employee/README.md @@ -63,16 +63,12 @@ Employees table: ## 解法 - - -**方法一:分组求和** +### 方法一:分组求和 我们可以先按照 `emp_id` 和 `event_day` 进行分组,然后计算每个分组的总时间。总时间等于每个分组的 `out_time` 减去 `in_time` 的和。 -### **SQL** - ```sql # Write your MySQL query statement below SELECT event_day AS day, emp_id, SUM(out_time - in_time) AS total_time @@ -81,3 +77,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/1700-1799/1741.Find Total Time Spent by Each Employee/README_EN.md b/solution/1700-1799/1741.Find Total Time Spent by Each Employee/README_EN.md index 19060e3ad57b4..4c7c65ef9412c 100644 --- a/solution/1700-1799/1741.Find Total Time Spent by Each Employee/README_EN.md +++ b/solution/1700-1799/1741.Find Total Time Spent by Each Employee/README_EN.md @@ -61,14 +61,12 @@ Employee 2 has two events: one on day 2020-11-28 with a total of (33 - 3) = 30, ## Solutions -**Solution 1: Group By + Sum Function** +### Solution 1: Group By + Sum Function We can first group by `emp_id` and `event_day`, and then calculate the total time for each group. The total time is equal to the sum of the differences between `out_time` and `in_time` for each record in the group. -### **SQL** - ```sql # Write your MySQL query statement below SELECT event_day AS day, emp_id, SUM(out_time - in_time) AS total_time @@ -77,3 +75,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/1700-1799/1742.Maximum Number of Balls in a Box/README.md b/solution/1700-1799/1742.Maximum Number of Balls in a Box/README.md index 8be6270a46148..1c657b6aa0ec4 100644 --- a/solution/1700-1799/1742.Maximum Number of Balls in a Box/README.md +++ b/solution/1700-1799/1742.Maximum Number of Balls in a Box/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:数组 + 模拟** +### 方法一:数组 + 模拟 观察题目的数据范围,小球的编号最大不超过 $10^5$,那么每个编号的各个位数之和的最大值小于 $50$。因此,我们可以直接开一个长度为 $50$ 的数组 $cnt$ 来统计每个编号的各个位数之和的数量。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: @@ -85,10 +79,6 @@ class Solution: return max(cnt) ``` -### **Java** - - - ```java class Solution { public int countBalls(int lowLimit, int highLimit) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func countBalls(lowLimit int, highLimit int) (ans int) { cnt := [50]int{} @@ -144,8 +130,6 @@ func countBalls(lowLimit int, highLimit int) (ans int) { } ``` -### **TypeScript** - ```ts function countBalls(lowLimit: number, highLimit: number): number { const cnt: number[] = Array(50).fill(0); @@ -160,10 +144,6 @@ function countBalls(lowLimit: number, highLimit: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1742.Maximum Number of Balls in a Box/README_EN.md b/solution/1700-1799/1742.Maximum Number of Balls in a Box/README_EN.md index 10bec9c0f03cf..38d11c785ef11 100644 --- a/solution/1700-1799/1742.Maximum Number of Balls in a Box/README_EN.md +++ b/solution/1700-1799/1742.Maximum Number of Balls in a Box/README_EN.md @@ -52,7 +52,7 @@ Box 10 has the most number of balls with 2 balls. ## Solutions -**Solution 1: Array + Simulation** +### Solution 1: Array + Simulation Observing the data range of the problem, the maximum number of the ball does not exceed $10^5$, so the maximum value of the sum of each digit of the number is less than $50$. Therefore, we can directly create an array $cnt$ with a length of $50$ to count the number of each digit sum of each number. @@ -62,8 +62,6 @@ The time complexity is $O(n \times \log_{10}m)$. Here, $n = highLimit - lowLimit -### **Python3** - ```python class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: @@ -77,8 +75,6 @@ class Solution: return max(cnt) ``` -### **Java** - ```java class Solution { public int countBalls(int lowLimit, int highLimit) { @@ -95,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +109,6 @@ public: }; ``` -### **Go** - ```go func countBalls(lowLimit int, highLimit int) (ans int) { cnt := [50]int{} @@ -134,8 +126,6 @@ func countBalls(lowLimit int, highLimit int) (ans int) { } ``` -### **TypeScript** - ```ts function countBalls(lowLimit: number, highLimit: number): number { const cnt: number[] = Array(50).fill(0); @@ -150,10 +140,6 @@ function countBalls(lowLimit: number, highLimit: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/README.md b/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/README.md index 6d02f3131644c..9b50fc7a17ae9 100644 --- a/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/README.md +++ b/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 从度为一的点开始遍历图,可以用 DFS,也可以直接遍历。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: @@ -90,29 +84,6 @@ class Solution: return ans ``` -```python -class Solution: - def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: - def dfs(i, fa): - ans.append(i) - for j in g[i]: - if j != fa: - dfs(j, i) - - g = defaultdict(list) - for a, b in adjacentPairs: - g[a].append(b) - g[b].append(a) - i = next(i for i, v in g.items() if len(v) == 1) - ans = [] - dfs(i, 1e6) - return ans -``` - -### **Java** - - - ```java class Solution { public int[] restoreArray(int[][] adjacentPairs) { @@ -140,41 +111,6 @@ class Solution { } ``` -```java -class Solution { - private Map> g = new HashMap<>(); - private int[] ans; - - public int[] restoreArray(int[][] adjacentPairs) { - for (var e : adjacentPairs) { - int a = e[0], b = e[1]; - g.computeIfAbsent(a, k -> new ArrayList<>()).add(b); - g.computeIfAbsent(b, k -> new ArrayList<>()).add(a); - } - int n = adjacentPairs.length + 1; - ans = new int[n]; - for (var e : g.entrySet()) { - if (e.getValue().size() == 1) { - dfs(e.getKey(), 1000000, 0); - break; - } - } - return ans; - } - - private void dfs(int i, int fa, int k) { - ans[k++] = i; - for (int j : g.get(i)) { - if (j != fa) { - dfs(j, i, k); - } - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -203,39 +139,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector restoreArray(vector>& adjacentPairs) { - unordered_map> g; - for (auto& e : adjacentPairs) { - int a = e[0], b = e[1]; - g[a].emplace_back(b); - g[b].emplace_back(a); - } - int n = adjacentPairs.size() + 1; - vector ans; - function dfs = [&](int i, int fa) { - ans.emplace_back(i); - for (int& j : g[i]) { - if (j != fa) { - dfs(j, i); - } - } - }; - for (auto& [i, v] : g) { - if (v.size() == 1) { - dfs(i, 1e6); - break; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func restoreArray(adjacentPairs [][]int) []int { n := len(adjacentPairs) + 1 @@ -264,36 +167,6 @@ func restoreArray(adjacentPairs [][]int) []int { } ``` -```go -func restoreArray(adjacentPairs [][]int) []int { - g := map[int][]int{} - for _, e := range adjacentPairs { - a, b := e[0], e[1] - g[a] = append(g[a], b) - g[b] = append(g[b], a) - } - ans := []int{} - var dfs func(i, fa int) - dfs = func(i, fa int) { - ans = append(ans, i) - for _, j := range g[i] { - if j != fa { - dfs(j, i) - } - } - } - for i, v := range g { - if len(v) == 1 { - dfs(i, 1000000) - break - } - } - return ans -} -``` - -### **C#** - ```cs public class Solution { public int[] RestoreArray(int[][] adjacentPairs) { @@ -332,10 +205,123 @@ public class Solution { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: + def dfs(i, fa): + ans.append(i) + for j in g[i]: + if j != fa: + dfs(j, i) + + g = defaultdict(list) + for a, b in adjacentPairs: + g[a].append(b) + g[b].append(a) + i = next(i for i, v in g.items() if len(v) == 1) + ans = [] + dfs(i, 1e6) + return ans ``` +```java +class Solution { + private Map> g = new HashMap<>(); + private int[] ans; + + public int[] restoreArray(int[][] adjacentPairs) { + for (var e : adjacentPairs) { + int a = e[0], b = e[1]; + g.computeIfAbsent(a, k -> new ArrayList<>()).add(b); + g.computeIfAbsent(b, k -> new ArrayList<>()).add(a); + } + int n = adjacentPairs.length + 1; + ans = new int[n]; + for (var e : g.entrySet()) { + if (e.getValue().size() == 1) { + dfs(e.getKey(), 1000000, 0); + break; + } + } + return ans; + } + + private void dfs(int i, int fa, int k) { + ans[k++] = i; + for (int j : g.get(i)) { + if (j != fa) { + dfs(j, i, k); + } + } + } +} +``` + +```cpp +class Solution { +public: + vector restoreArray(vector>& adjacentPairs) { + unordered_map> g; + for (auto& e : adjacentPairs) { + int a = e[0], b = e[1]; + g[a].emplace_back(b); + g[b].emplace_back(a); + } + int n = adjacentPairs.size() + 1; + vector ans; + function dfs = [&](int i, int fa) { + ans.emplace_back(i); + for (int& j : g[i]) { + if (j != fa) { + dfs(j, i); + } + } + }; + for (auto& [i, v] : g) { + if (v.size() == 1) { + dfs(i, 1e6); + break; + } + } + return ans; + } +}; +``` + +```go +func restoreArray(adjacentPairs [][]int) []int { + g := map[int][]int{} + for _, e := range adjacentPairs { + a, b := e[0], e[1] + g[a] = append(g[a], b) + g[b] = append(g[b], a) + } + ans := []int{} + var dfs func(i, fa int) + dfs = func(i, fa int) { + ans = append(ans, i) + for _, j := range g[i] { + if j != fa { + dfs(j, i) + } + } + } + for i, v := range g { + if len(v) == 1 { + dfs(i, 1000000) + break + } + } + return ans +} ``` + + diff --git a/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/README_EN.md b/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/README_EN.md index b679c3e65bf46..349e4f3fa1568 100644 --- a/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/README_EN.md +++ b/solution/1700-1799/1743.Restore the Array From Adjacent Pairs/README_EN.md @@ -52,12 +52,10 @@ Another solution is [-3,1,4,-2], which would also be accepted. ## Solutions -Traverse the graph from the point where the degree is one. +### Solution 1 -### **Python3** - ```python class Solution: def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: @@ -78,27 +76,6 @@ class Solution: return ans ``` -```python -class Solution: - def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: - def dfs(i, fa): - ans.append(i) - for j in g[i]: - if j != fa: - dfs(j, i) - - g = defaultdict(list) - for a, b in adjacentPairs: - g[a].append(b) - g[b].append(a) - i = next(i for i, v in g.items() if len(v) == 1) - ans = [] - dfs(i, 1e6) - return ans -``` - -### **Java** - ```java class Solution { public int[] restoreArray(int[][] adjacentPairs) { @@ -126,41 +103,6 @@ class Solution { } ``` -```java -class Solution { - private Map> g = new HashMap<>(); - private int[] ans; - - public int[] restoreArray(int[][] adjacentPairs) { - for (var e : adjacentPairs) { - int a = e[0], b = e[1]; - g.computeIfAbsent(a, k -> new ArrayList<>()).add(b); - g.computeIfAbsent(b, k -> new ArrayList<>()).add(a); - } - int n = adjacentPairs.length + 1; - ans = new int[n]; - for (var e : g.entrySet()) { - if (e.getValue().size() == 1) { - dfs(e.getKey(), 1000000, 0); - break; - } - } - return ans; - } - - private void dfs(int i, int fa, int k) { - ans[k++] = i; - for (int j : g.get(i)) { - if (j != fa) { - dfs(j, i, k); - } - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -189,39 +131,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector restoreArray(vector>& adjacentPairs) { - unordered_map> g; - for (auto& e : adjacentPairs) { - int a = e[0], b = e[1]; - g[a].emplace_back(b); - g[b].emplace_back(a); - } - int n = adjacentPairs.size() + 1; - vector ans; - function dfs = [&](int i, int fa) { - ans.emplace_back(i); - for (int& j : g[i]) { - if (j != fa) { - dfs(j, i); - } - } - }; - for (auto& [i, v] : g) { - if (v.size() == 1) { - dfs(i, 1e6); - break; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func restoreArray(adjacentPairs [][]int) []int { n := len(adjacentPairs) + 1 @@ -250,36 +159,6 @@ func restoreArray(adjacentPairs [][]int) []int { } ``` -```go -func restoreArray(adjacentPairs [][]int) []int { - g := map[int][]int{} - for _, e := range adjacentPairs { - a, b := e[0], e[1] - g[a] = append(g[a], b) - g[b] = append(g[b], a) - } - ans := []int{} - var dfs func(i, fa int) - dfs = func(i, fa int) { - ans = append(ans, i) - for _, j := range g[i] { - if j != fa { - dfs(j, i) - } - } - } - for i, v := range g { - if len(v) == 1 { - dfs(i, 1000000) - break - } - } - return ans -} -``` - -### **C#** - ```cs public class Solution { public int[] RestoreArray(int[][] adjacentPairs) { @@ -318,10 +197,123 @@ public class Solution { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: + def dfs(i, fa): + ans.append(i) + for j in g[i]: + if j != fa: + dfs(j, i) + + g = defaultdict(list) + for a, b in adjacentPairs: + g[a].append(b) + g[b].append(a) + i = next(i for i, v in g.items() if len(v) == 1) + ans = [] + dfs(i, 1e6) + return ans +``` + +```java +class Solution { + private Map> g = new HashMap<>(); + private int[] ans; + + public int[] restoreArray(int[][] adjacentPairs) { + for (var e : adjacentPairs) { + int a = e[0], b = e[1]; + g.computeIfAbsent(a, k -> new ArrayList<>()).add(b); + g.computeIfAbsent(b, k -> new ArrayList<>()).add(a); + } + int n = adjacentPairs.length + 1; + ans = new int[n]; + for (var e : g.entrySet()) { + if (e.getValue().size() == 1) { + dfs(e.getKey(), 1000000, 0); + break; + } + } + return ans; + } + + private void dfs(int i, int fa, int k) { + ans[k++] = i; + for (int j : g.get(i)) { + if (j != fa) { + dfs(j, i, k); + } + } + } +} +``` +```cpp +class Solution { +public: + vector restoreArray(vector>& adjacentPairs) { + unordered_map> g; + for (auto& e : adjacentPairs) { + int a = e[0], b = e[1]; + g[a].emplace_back(b); + g[b].emplace_back(a); + } + int n = adjacentPairs.size() + 1; + vector ans; + function dfs = [&](int i, int fa) { + ans.emplace_back(i); + for (int& j : g[i]) { + if (j != fa) { + dfs(j, i); + } + } + }; + for (auto& [i, v] : g) { + if (v.size() == 1) { + dfs(i, 1e6); + break; + } + } + return ans; + } +}; ``` +```go +func restoreArray(adjacentPairs [][]int) []int { + g := map[int][]int{} + for _, e := range adjacentPairs { + a, b := e[0], e[1] + g[a] = append(g[a], b) + g[b] = append(g[b], a) + } + ans := []int{} + var dfs func(i, fa int) + dfs = func(i, fa int) { + ans = append(ans, i) + for _, j := range g[i] { + if j != fa { + dfs(j, i) + } + } + } + for i, v := range g { + if len(v) == 1 { + dfs(i, 1000000) + break + } + } + return ans +} ``` + + diff --git a/solution/1700-1799/1744.Can You Eat Your Favorite Candy on Your Favorite Day/README.md b/solution/1700-1799/1744.Can You Eat Your Favorite Candy on Your Favorite Day/README.md index 6d4acfe778463..e133cb3321661 100644 --- a/solution/1700-1799/1744.Can You Eat Your Favorite Candy on Your Favorite Day/README.md +++ b/solution/1700-1799/1744.Can You Eat Your Favorite Candy on Your Favorite Day/README.md @@ -63,18 +63,12 @@ ## 解法 - - -**方法一:前缀和** +### 方法一:前缀和 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `candiesCount` 的长度。 -### **Python3** - - - ```python class Solution: def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public boolean[] canEat(int[] candiesCount, int[][] queries) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go func canEat(candiesCount []int, queries [][]int) (ans []bool) { n := len(candiesCount) @@ -150,10 +136,6 @@ func canEat(candiesCount []int, queries [][]int) (ans []bool) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1744.Can You Eat Your Favorite Candy on Your Favorite Day/README_EN.md b/solution/1700-1799/1744.Can You Eat Your Favorite Candy on Your Favorite Day/README_EN.md index 280de685c4a8d..d06073810d31f 100644 --- a/solution/1700-1799/1744.Can You Eat Your Favorite Candy on Your Favorite Day/README_EN.md +++ b/solution/1700-1799/1744.Can You Eat Your Favorite Candy on Your Favorite Day/README_EN.md @@ -54,9 +54,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public boolean[] canEat(int[] candiesCount, int[][] queries) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func canEat(candiesCount []int, queries [][]int) (ans []bool) { n := len(candiesCount) @@ -131,10 +125,6 @@ func canEat(candiesCount []int, queries [][]int) (ans []bool) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1745.Palindrome Partitioning IV/README.md b/solution/1700-1799/1745.Palindrome Partitioning IV/README.md index 36d8aaf665349..67d0692bcf2e8 100644 --- a/solution/1700-1799/1745.Palindrome Partitioning IV/README.md +++ b/solution/1700-1799/1745.Palindrome Partitioning IV/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:预处理 + 枚举** +### 方法一:预处理 + 枚举 预处理出字符串 `s` 的所有子串是否为回文串,然后枚举 `s` 的所有分割点,判断是否满足条件。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def checkPartitioning(self, s: str) -> bool: @@ -68,10 +62,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean checkPartitioning(String s) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func checkPartitioning(s string) bool { n := len(s) @@ -150,10 +136,6 @@ func checkPartitioning(s string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1745.Palindrome Partitioning IV/README_EN.md b/solution/1700-1799/1745.Palindrome Partitioning IV/README_EN.md index e3e29b434689c..e0f0ae6ac03cc 100644 --- a/solution/1700-1799/1745.Palindrome Partitioning IV/README_EN.md +++ b/solution/1700-1799/1745.Palindrome Partitioning IV/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean checkPartitioning(String s) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +102,6 @@ public: }; ``` -### **Go** - ```go func checkPartitioning(s string) bool { n := len(s) @@ -134,10 +128,6 @@ func checkPartitioning(s string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1746.Maximum Subarray Sum After One Operation/README.md b/solution/1700-1799/1746.Maximum Subarray Sum After One Operation/README.md index e3a01111c3696..efb6ede4ad0fe 100644 --- a/solution/1700-1799/1746.Maximum Subarray Sum After One Operation/README.md +++ b/solution/1700-1799/1746.Maximum Subarray Sum After One Operation/README.md @@ -37,9 +37,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示以 $nums[i]$ 结尾,且没有进行替换的最大子数组和,另外定义 $g[i]$ 表示以 $nums[i]$ 结尾,且进行了替换的最大子数组和。那么有如下状态转移方程: @@ -58,10 +56,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxSumAfterOperation(self, nums: List[int]) -> int: @@ -75,10 +69,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxSumAfterOperation(int[] nums) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,7 +104,19 @@ public: }; ``` -### **Rust** +```go +func maxSumAfterOperation(nums []int) int { + var f, g int + ans := -(1 << 30) + for _, x := range nums { + ff := max(f, 0) + x + gg := max(max(f, 0)+x*x, g+x) + f, g = ff, gg + ans = max(ans, max(f, g)) + } + return ans +} +``` ```rust impl Solution { @@ -146,26 +146,6 @@ impl Solution { } ``` -### **Go** - -```go -func maxSumAfterOperation(nums []int) int { - var f, g int - ans := -(1 << 30) - for _, x := range nums { - ff := max(f, 0) + x - gg := max(max(f, 0)+x*x, g+x) - f, g = ff, gg - ans = max(ans, max(f, g)) - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1746.Maximum Subarray Sum After One Operation/README_EN.md b/solution/1700-1799/1746.Maximum Subarray Sum After One Operation/README_EN.md index 46a1c597d8b88..fce43fe245929 100644 --- a/solution/1700-1799/1746.Maximum Subarray Sum After One Operation/README_EN.md +++ b/solution/1700-1799/1746.Maximum Subarray Sum After One Operation/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -50,8 +50,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxSumAfterOperation(int[] nums) { @@ -69,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,7 +85,19 @@ public: }; ``` -### **Rust** +```go +func maxSumAfterOperation(nums []int) int { + var f, g int + ans := -(1 << 30) + for _, x := range nums { + ff := max(f, 0) + x + gg := max(max(f, 0)+x*x, g+x) + f, g = ff, gg + ans = max(ans, max(f, g)) + } + return ans +} +``` ```rust impl Solution { @@ -119,26 +127,6 @@ impl Solution { } ``` -### **Go** - -```go -func maxSumAfterOperation(nums []int) int { - var f, g int - ans := -(1 << 30) - for _, x := range nums { - ff := max(f, 0) + x - gg := max(max(f, 0)+x*x, g+x) - f, g = ff, gg - ans = max(ans, max(f, g)) - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1747.Leetflex Banned Accounts/README.md b/solution/1700-1799/1747.Leetflex Banned Accounts/README.md index 7a2821fbb2048..83829909d2cc1 100644 --- a/solution/1700-1799/1747.Leetflex Banned Accounts/README.md +++ b/solution/1700-1799/1747.Leetflex Banned Accounts/README.md @@ -64,9 +64,7 @@ Account ID 4 --> 该账户从 "2021-02-01 17:00:00" 到 "2021-02-01 17:00:00" ## 解法 - - -**方法一:自连接** +### 方法一:自连接 我们可以通过自连接的方式,找出每个账户在同一天内,从不同的网络地址登录的情况。连接的条件是: @@ -76,8 +74,6 @@ Account ID 4 --> 该账户从 "2021-02-01 17:00:00" 到 "2021-02-01 17:00:00" -### **SQL** - ```sql # Write your MySQL query statement below SELECT DISTINCT @@ -91,3 +87,5 @@ FROM ``` + + diff --git a/solution/1700-1799/1747.Leetflex Banned Accounts/README_EN.md b/solution/1700-1799/1747.Leetflex Banned Accounts/README_EN.md index 4e314b9953f57..6feff32e6483f 100644 --- a/solution/1700-1799/1747.Leetflex Banned Accounts/README_EN.md +++ b/solution/1700-1799/1747.Leetflex Banned Accounts/README_EN.md @@ -62,7 +62,7 @@ Account ID 4 --> The account was active from "2021-02-01 17:00:00" ## Solutions -**Solution 1: Self-Join** +### Solution 1: Self-Join We can use a self-join to find out the cases where each account logs in from different IP addresses on the same day. The conditions for joining are: @@ -72,8 +72,6 @@ We can use a self-join to find out the cases where each account logs in from dif -### **SQL** - ```sql # Write your MySQL query statement below SELECT DISTINCT @@ -87,3 +85,5 @@ FROM ``` + + diff --git a/solution/1700-1799/1748.Sum of Unique Elements/README.md b/solution/1700-1799/1748.Sum of Unique Elements/README.md index 79c3b892c27d0..b41fd6d0dc0b8 100644 --- a/solution/1700-1799/1748.Sum of Unique Elements/README.md +++ b/solution/1700-1799/1748.Sum of Unique Elements/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们可以用数组或哈希表 `cnt` 统计数组 `nums` 中每个数字出现的次数,然后遍历 `cnt`,对于出现次数为 1 的数字,将其加入答案。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def sumOfUnique(self, nums: List[int]) -> int: @@ -67,10 +61,6 @@ class Solution: return sum(x for x, v in cnt.items() if v == 1) ``` -### **Java** - - - ```java class Solution { public int sumOfUnique(int[] nums) { @@ -89,25 +79,6 @@ class Solution { } ``` -```java -class Solution { - public int sumOfUnique(int[] nums) { - int ans = 0; - int[] cnt = new int[101]; - for (int x : nums) { - if (++cnt[x] == 1) { - ans += x; - } else if (cnt[x] == 2) { - ans -= x; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -127,26 +98,6 @@ public: }; ``` -```cpp -class Solution { -public: - int sumOfUnique(vector& nums) { - int ans = 0; - int cnt[101]{}; - for (int& x : nums) { - if (++cnt[x] == 1) { - ans += x; - } else if (cnt[x] == 2) { - ans -= x; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func sumOfUnique(nums []int) (ans int) { cnt := [101]int{} @@ -162,23 +113,6 @@ func sumOfUnique(nums []int) (ans int) { } ``` -```go -func sumOfUnique(nums []int) (ans int) { - cnt := [101]int{} - for _, x := range nums { - cnt[x]++ - if cnt[x] == 1 { - ans += x - } else if cnt[x] == 2 { - ans -= x - } - } - return -} -``` - -### **TypeScript** - ```ts function sumOfUnique(nums: number[]): number { const cnt = new Array(101).fill(0); @@ -195,23 +129,6 @@ function sumOfUnique(nums: number[]): number { } ``` -```ts -function sumOfUnique(nums: number[]): number { - let ans = 0; - const cnt = new Array(101).fill(0); - for (const x of nums) { - if (++cnt[x] === 1) { - ans += x; - } else if (cnt[x] === 2) { - ans -= x; - } - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn sum_of_unique(nums: Vec) -> i32 { @@ -230,31 +147,6 @@ impl Solution { } ``` -```rust -use std::collections::HashMap; - -impl Solution { - pub fn sum_of_unique(nums: Vec) -> i32 { - let mut res = 0; - let mut map = HashMap::new(); - for num in nums { - if map.contains_key(&num) { - if *map.get(&num).unwrap() { - map.insert(num, false); - res -= num; - } - } else { - map.insert(num, true); - res += num; - } - } - res - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -277,10 +169,100 @@ class Solution { } ``` -### **...** + + +### 方法二 + + +```java +class Solution { + public int sumOfUnique(int[] nums) { + int ans = 0; + int[] cnt = new int[101]; + for (int x : nums) { + if (++cnt[x] == 1) { + ans += x; + } else if (cnt[x] == 2) { + ans -= x; + } + } + return ans; + } +} ``` +```cpp +class Solution { +public: + int sumOfUnique(vector& nums) { + int ans = 0; + int cnt[101]{}; + for (int& x : nums) { + if (++cnt[x] == 1) { + ans += x; + } else if (cnt[x] == 2) { + ans -= x; + } + } + return ans; + } +}; +``` + +```go +func sumOfUnique(nums []int) (ans int) { + cnt := [101]int{} + for _, x := range nums { + cnt[x]++ + if cnt[x] == 1 { + ans += x + } else if cnt[x] == 2 { + ans -= x + } + } + return +} +``` + +```ts +function sumOfUnique(nums: number[]): number { + let ans = 0; + const cnt = new Array(101).fill(0); + for (const x of nums) { + if (++cnt[x] === 1) { + ans += x; + } else if (cnt[x] === 2) { + ans -= x; + } + } + return ans; +} +``` + +```rust +use std::collections::HashMap; + +impl Solution { + pub fn sum_of_unique(nums: Vec) -> i32 { + let mut res = 0; + let mut map = HashMap::new(); + for num in nums { + if map.contains_key(&num) { + if *map.get(&num).unwrap() { + map.insert(num, false); + res -= num; + } + } else { + map.insert(num, true); + res += num; + } + } + res + } +} ``` + + diff --git a/solution/1700-1799/1748.Sum of Unique Elements/README_EN.md b/solution/1700-1799/1748.Sum of Unique Elements/README_EN.md index ecdff647f593e..ae42da026b965 100644 --- a/solution/1700-1799/1748.Sum of Unique Elements/README_EN.md +++ b/solution/1700-1799/1748.Sum of Unique Elements/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return sum(x for x, v in cnt.items() if v == 1) ``` -### **Java** - ```java class Solution { public int sumOfUnique(int[] nums) { @@ -74,25 +72,6 @@ class Solution { } ``` -```java -class Solution { - public int sumOfUnique(int[] nums) { - int ans = 0; - int[] cnt = new int[101]; - for (int x : nums) { - if (++cnt[x] == 1) { - ans += x; - } else if (cnt[x] == 2) { - ans -= x; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -112,26 +91,6 @@ public: }; ``` -```cpp -class Solution { -public: - int sumOfUnique(vector& nums) { - int ans = 0; - int cnt[101]{}; - for (int& x : nums) { - if (++cnt[x] == 1) { - ans += x; - } else if (cnt[x] == 2) { - ans -= x; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func sumOfUnique(nums []int) (ans int) { cnt := [101]int{} @@ -147,23 +106,6 @@ func sumOfUnique(nums []int) (ans int) { } ``` -```go -func sumOfUnique(nums []int) (ans int) { - cnt := [101]int{} - for _, x := range nums { - cnt[x]++ - if cnt[x] == 1 { - ans += x - } else if cnt[x] == 2 { - ans -= x - } - } - return -} -``` - -### **TypeScript** - ```ts function sumOfUnique(nums: number[]): number { const cnt = new Array(101).fill(0); @@ -180,23 +122,6 @@ function sumOfUnique(nums: number[]): number { } ``` -```ts -function sumOfUnique(nums: number[]): number { - let ans = 0; - const cnt = new Array(101).fill(0); - for (const x of nums) { - if (++cnt[x] === 1) { - ans += x; - } else if (cnt[x] === 2) { - ans -= x; - } - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn sum_of_unique(nums: Vec) -> i32 { @@ -215,31 +140,6 @@ impl Solution { } ``` -```rust -use std::collections::HashMap; - -impl Solution { - pub fn sum_of_unique(nums: Vec) -> i32 { - let mut res = 0; - let mut map = HashMap::new(); - for num in nums { - if map.contains_key(&num) { - if *map.get(&num).unwrap() { - map.insert(num, false); - res -= num; - } - } else { - map.insert(num, true); - res += num; - } - } - res - } -} -``` - -### **PHP** - ```php class Solution { /** @@ -262,10 +162,100 @@ class Solution { } ``` -### **...** + + +### Solution 2 + + + +```java +class Solution { + public int sumOfUnique(int[] nums) { + int ans = 0; + int[] cnt = new int[101]; + for (int x : nums) { + if (++cnt[x] == 1) { + ans += x; + } else if (cnt[x] == 2) { + ans -= x; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int sumOfUnique(vector& nums) { + int ans = 0; + int cnt[101]{}; + for (int& x : nums) { + if (++cnt[x] == 1) { + ans += x; + } else if (cnt[x] == 2) { + ans -= x; + } + } + return ans; + } +}; +``` + +```go +func sumOfUnique(nums []int) (ans int) { + cnt := [101]int{} + for _, x := range nums { + cnt[x]++ + if cnt[x] == 1 { + ans += x + } else if cnt[x] == 2 { + ans -= x + } + } + return +} +``` +```ts +function sumOfUnique(nums: number[]): number { + let ans = 0; + const cnt = new Array(101).fill(0); + for (const x of nums) { + if (++cnt[x] === 1) { + ans += x; + } else if (cnt[x] === 2) { + ans -= x; + } + } + return ans; +} ``` +```rust +use std::collections::HashMap; + +impl Solution { + pub fn sum_of_unique(nums: Vec) -> i32 { + let mut res = 0; + let mut map = HashMap::new(); + for num in nums { + if map.contains_key(&num) { + if *map.get(&num).unwrap() { + map.insert(num, false); + res -= num; + } + } else { + map.insert(num, true); + res += num; + } + } + res + } +} ``` + + diff --git a/solution/1700-1799/1749.Maximum Absolute Sum of Any Subarray/README.md b/solution/1700-1799/1749.Maximum Absolute Sum of Any Subarray/README.md index 7d62dd70549b0..d0f46df026dfc 100644 --- a/solution/1700-1799/1749.Maximum Absolute Sum of Any Subarray/README.md +++ b/solution/1700-1799/1749.Maximum Absolute Sum of Any Subarray/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示以 $nums[i]$ 结尾的子数组的和的最大值,定义 $g[i]$ 表示以 $nums[i]$ 结尾的子数组的和的最小值。那么 $f[i]$ 和 $g[i]$ 的状态转移方程如下: @@ -67,10 +65,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxAbsoluteSum(self, nums: List[int]) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxAbsoluteSum(int[] nums) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func maxAbsoluteSum(nums []int) (ans int) { var f, g int @@ -141,8 +127,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function maxAbsoluteSum(nums: number[]): number { let f = 0; @@ -157,8 +141,6 @@ function maxAbsoluteSum(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_absolute_sum(nums: Vec) -> i32 { @@ -175,10 +157,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1749.Maximum Absolute Sum of Any Subarray/README_EN.md b/solution/1700-1799/1749.Maximum Absolute Sum of Any Subarray/README_EN.md index 6e3c6015dd56d..ed59f18c7b07c 100644 --- a/solution/1700-1799/1749.Maximum Absolute Sum of Any Subarray/README_EN.md +++ b/solution/1700-1799/1749.Maximum Absolute Sum of Any Subarray/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i]$ to represent the maximum value of the subarray ending with $nums[i]$, and define $g[i]$ to represent the minimum value of the subarray ending with $nums[i]$. Then the state transition equation of $f[i]$ and $g[i]$ is as follows: @@ -61,8 +61,6 @@ Time complexity $O(n)$, space complexity $O(1)$, where $n$ is the length of the -### **Python3** - ```python class Solution: def maxAbsoluteSum(self, nums: List[int]) -> int: @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxAbsoluteSum(int[] nums) { @@ -92,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func maxAbsoluteSum(nums []int) (ans int) { var f, g int @@ -131,8 +123,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function maxAbsoluteSum(nums: number[]): number { let f = 0; @@ -147,8 +137,6 @@ function maxAbsoluteSum(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_absolute_sum(nums: Vec) -> i32 { @@ -165,10 +153,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/README.md b/solution/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/README.md index 56ffb54d14f6d..3594ea157d2e3 100644 --- a/solution/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/README.md +++ b/solution/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们定义两个指针 $i$ 和 $j$ 分别指向字符串 $s$ 的头部和尾部,然后向中间移动,直到 $i$ 和 $j$ 指向的字符不相等,此时 $\max(0, j - i + 1)$ 即为答案。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def minimumLength(self, s: str) -> int: @@ -87,10 +81,6 @@ class Solution: return max(0, j - i + 1) ``` -### **Java** - - - ```java class Solution { public int minimumLength(String s) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go func minimumLength(s string) int { i, j := 0, len(s)-1 @@ -150,8 +136,6 @@ func minimumLength(s string) int { } ``` -### **TypeScript** - ```ts function minimumLength(s: string): number { let i = 0; @@ -170,8 +154,6 @@ function minimumLength(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn minimum_length(s: String) -> i32 { @@ -194,8 +176,6 @@ impl Solution { } ``` -### **C** - ```c int minimumLength(char* s) { int n = strlen(s); @@ -218,10 +198,6 @@ int minimumLength(char* s) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/README_EN.md b/solution/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/README_EN.md index 503fa79ccae1d..9b8c012462393 100644 --- a/solution/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/README_EN.md +++ b/solution/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/README_EN.md @@ -56,7 +56,7 @@ ## Solutions -**Solution 1: Two pointers** +### Solution 1: Two pointers We define two pointers $i$ and $j$ to point to the head and tail of the string $s$ respectively, then move them to the middle until the characters pointed to by $i$ and $j$ are not equal, then $\max(0, j - i + 1)$ is the answer. @@ -64,8 +64,6 @@ The time complexity is $O(n)$ and the space complexity is $O(1)$. Where $n$ is t -### **Python3** - ```python class Solution: def minimumLength(self, s: str) -> int: @@ -79,8 +77,6 @@ class Solution: return max(0, j - i + 1) ``` -### **Java** - ```java class Solution { public int minimumLength(String s) { @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func minimumLength(s string) int { i, j := 0, len(s)-1 @@ -140,8 +132,6 @@ func minimumLength(s string) int { } ``` -### **TypeScript** - ```ts function minimumLength(s: string): number { let i = 0; @@ -160,8 +150,6 @@ function minimumLength(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn minimum_length(s: String) -> i32 { @@ -184,8 +172,6 @@ impl Solution { } ``` -### **C** - ```c int minimumLength(char* s) { int n = strlen(s); @@ -208,10 +194,6 @@ int minimumLength(char* s) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README.md b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README.md index 706f708e19756..20b471f1416c5 100644 --- a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README.md +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:记忆化搜索 + 二分查找** +### 方法一:记忆化搜索 + 二分查找 我们先将会议按照开始时间从小到大排序,然后设计一个函数 $dfs(i, k)$ 表示从第 $i$ 个会议开始,最多参加 $k$ 个会议的最大价值和。答案即为 $dfs(0, k)$。 @@ -75,33 +73,8 @@ $$ 时间复杂度 $O(n\times \log n + n\times k)$,其中 $n$ 为会议数量。 -**方法二:动态规划 + 二分查找** - -我们可以将方法一中的记忆化搜索改为动态规划。 - -先将会议排序,这次我们按照结束时间从小到大排序。然后定义 $f[i][j]$ 表示前 $i$ 个会议中,最多参加 $j$ 个会议的最大价值和。答案即为 $f[n][k]$。 - -对于第 $i$ 个会议,我们可以选择参加或者不参加。如果不参加,那么最大价值和就是 $f[i][j]$,如果参加,我们可以通过二分查找,找到最后一个结束时间小于第 $i$ 个会议开始时间的会议,记为 $h$,那么最大价值和就是 $f[h+1][j - 1] + value[i]$。取二者的较大值即可。即: - -$$ -f[i+1][j] = \max(f[i][j], f[h+1][j - 1] + value[i]) -$$ - -其中 $h$ 为最后一个结束时间小于第 $i$ 个会议开始时间的会议,可以通过二分查找得到。 - -时间复杂度 $O(n\times \log n + n\times k)$,其中 $n$ 为会议数量。 - -相似题目: - -- [1235. 规划兼职工作](/solution/1200-1299/1235.Maximum%20Profit%20in%20Job%20Scheduling/README.md) -- [2008. 出租车的最大盈利](/solution/2000-2099/2008.Maximum%20Earnings%20From%20Taxi/README.md) - -### **Python3** - - - ```python class Solution: def maxValue(self, events: List[List[int]], k: int) -> int: @@ -120,23 +93,6 @@ class Solution: return dfs(0, k) ``` -```python -class Solution: - def maxValue(self, events: List[List[int]], k: int) -> int: - events.sort(key=lambda x: x[1]) - n = len(events) - f = [[0] * (k + 1) for _ in range(n + 1)] - for i, (st, _, val) in enumerate(events, 1): - p = bisect_left(events, st, hi=i - 1, key=lambda x: x[1]) - for j in range(1, k + 1): - f[i][j] = max(f[i - 1][j], f[p][j - 1] + val) - return f[n][k] -``` - -### **Java** - - - ```java class Solution { private int[][] events; @@ -178,39 +134,6 @@ class Solution { } ``` -```java -class Solution { - public int maxValue(int[][] events, int k) { - Arrays.sort(events, (a, b) -> a[1] - b[1]); - int n = events.length; - int[][] f = new int[n + 1][k + 1]; - for (int i = 1; i <= n; ++i) { - int st = events[i - 1][0], val = events[i - 1][2]; - int p = search(events, st, i - 1); - for (int j = 1; j <= k; ++j) { - f[i][j] = Math.max(f[i - 1][j], f[p][j - 1] + val); - } - } - return f[n][k]; - } - - private int search(int[][] events, int x, int hi) { - int l = 0, r = hi; - while (l < r) { - int mid = (l + r) >> 1; - if (events[mid][1] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -237,29 +160,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxValue(vector>& events, int k) { - sort(events.begin(), events.end(), [](const auto& a, const auto& b) { return a[1] < b[1]; }); - int n = events.size(); - int f[n + 1][k + 1]; - memset(f, 0, sizeof(f)); - for (int i = 1; i <= n; ++i) { - int st = events[i - 1][0], val = events[i - 1][2]; - vector t = {st}; - int p = lower_bound(events.begin(), events.begin() + i - 1, t, [](const auto& a, const auto& b) { return a[1] < b[0]; }) - events.begin(); - for (int j = 1; j <= k; ++j) { - f[i][j] = max(f[i - 1][j], f[p][j - 1] + val); - } - } - return f[n][k]; - } -}; -``` - -### **Go** - ```go func maxValue(events [][]int, k int) int { sort.Slice(events, func(i, j int) bool { return events[i][0] < events[j][0] }) @@ -285,27 +185,6 @@ func maxValue(events [][]int, k int) int { } ``` -```go -func maxValue(events [][]int, k int) int { - sort.Slice(events, func(i, j int) bool { return events[i][1] < events[j][1] }) - n := len(events) - f := make([][]int, n+1) - for i := range f { - f[i] = make([]int, k+1) - } - for i := 1; i <= n; i++ { - st, val := events[i-1][0], events[i-1][2] - p := sort.Search(i, func(j int) bool { return events[j][1] >= st }) - for j := 1; j <= k; j++ { - f[i][j] = max(f[i-1][j], f[p][j-1]+val) - } - } - return f[n][k] -} -``` - -### **TypeScript** - ```ts function maxValue(events: number[][], k: number): number { events.sort((a, b) => a[1] - b[1]); @@ -335,10 +214,115 @@ function maxValue(events: number[][], k: number): number { } ``` -### **...** + + +### 方法二:动态规划 + 二分查找 + +我们可以将方法一中的记忆化搜索改为动态规划。 + +先将会议排序,这次我们按照结束时间从小到大排序。然后定义 $f[i][j]$ 表示前 $i$ 个会议中,最多参加 $j$ 个会议的最大价值和。答案即为 $f[n][k]$。 + +对于第 $i$ 个会议,我们可以选择参加或者不参加。如果不参加,那么最大价值和就是 $f[i][j]$,如果参加,我们可以通过二分查找,找到最后一个结束时间小于第 $i$ 个会议开始时间的会议,记为 $h$,那么最大价值和就是 $f[h+1][j - 1] + value[i]$。取二者的较大值即可。即: + +$$ +f[i+1][j] = \max(f[i][j], f[h+1][j - 1] + value[i]) +$$ + +其中 $h$ 为最后一个结束时间小于第 $i$ 个会议开始时间的会议,可以通过二分查找得到。 + +时间复杂度 $O(n\times \log n + n\times k)$,其中 $n$ 为会议数量。 + +相似题目: + +- [1235. 规划兼职工作](/solution/1200-1299/1235.Maximum%20Profit%20in%20Job%20Scheduling/README.md) +- [2008. 出租车的最大盈利](/solution/2000-2099/2008.Maximum%20Earnings%20From%20Taxi/README.md) + + + +```python +class Solution: + def maxValue(self, events: List[List[int]], k: int) -> int: + events.sort(key=lambda x: x[1]) + n = len(events) + f = [[0] * (k + 1) for _ in range(n + 1)] + for i, (st, _, val) in enumerate(events, 1): + p = bisect_left(events, st, hi=i - 1, key=lambda x: x[1]) + for j in range(1, k + 1): + f[i][j] = max(f[i - 1][j], f[p][j - 1] + val) + return f[n][k] +``` + +```java +class Solution { + public int maxValue(int[][] events, int k) { + Arrays.sort(events, (a, b) -> a[1] - b[1]); + int n = events.length; + int[][] f = new int[n + 1][k + 1]; + for (int i = 1; i <= n; ++i) { + int st = events[i - 1][0], val = events[i - 1][2]; + int p = search(events, st, i - 1); + for (int j = 1; j <= k; ++j) { + f[i][j] = Math.max(f[i - 1][j], f[p][j - 1] + val); + } + } + return f[n][k]; + } + + private int search(int[][] events, int x, int hi) { + int l = 0, r = hi; + while (l < r) { + int mid = (l + r) >> 1; + if (events[mid][1] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } +} +``` +```cpp +class Solution { +public: + int maxValue(vector>& events, int k) { + sort(events.begin(), events.end(), [](const auto& a, const auto& b) { return a[1] < b[1]; }); + int n = events.size(); + int f[n + 1][k + 1]; + memset(f, 0, sizeof(f)); + for (int i = 1; i <= n; ++i) { + int st = events[i - 1][0], val = events[i - 1][2]; + vector t = {st}; + int p = lower_bound(events.begin(), events.begin() + i - 1, t, [](const auto& a, const auto& b) { return a[1] < b[0]; }) - events.begin(); + for (int j = 1; j <= k; ++j) { + f[i][j] = max(f[i - 1][j], f[p][j - 1] + val); + } + } + return f[n][k]; + } +}; ``` +```go +func maxValue(events [][]int, k int) int { + sort.Slice(events, func(i, j int) bool { return events[i][1] < events[j][1] }) + n := len(events) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, k+1) + } + for i := 1; i <= n; i++ { + st, val := events[i-1][0], events[i-1][2] + p := sort.Search(i, func(j int) bool { return events[j][1] >= st }) + for j := 1; j <= k; j++ { + f[i][j] = max(f[i-1][j], f[p][j-1]+val) + } + } + return f[n][k] +} ``` + + diff --git a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README_EN.md b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README_EN.md index 689e17321143e..b20bc1018e7cd 100644 --- a/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README_EN.md +++ b/solution/1700-1799/1751.Maximum Number of Events That Can Be Attended II/README_EN.md @@ -51,9 +51,9 @@ Notice that you cannot attend any other event as they overlap, and that you do < ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,21 +73,6 @@ class Solution: return dfs(0, k) ``` -```python -class Solution: - def maxValue(self, events: List[List[int]], k: int) -> int: - events.sort(key=lambda x: x[1]) - n = len(events) - f = [[0] * (k + 1) for _ in range(n + 1)] - for i, (st, _, val) in enumerate(events, 1): - p = bisect_left(events, st, hi=i - 1, key=lambda x: x[1]) - for j in range(1, k + 1): - f[i][j] = max(f[i - 1][j], f[p][j - 1] + val) - return f[n][k] -``` - -### **Java** - ```java class Solution { private int[][] events; @@ -129,39 +114,6 @@ class Solution { } ``` -```java -class Solution { - public int maxValue(int[][] events, int k) { - Arrays.sort(events, (a, b) -> a[1] - b[1]); - int n = events.length; - int[][] f = new int[n + 1][k + 1]; - for (int i = 1; i <= n; ++i) { - int st = events[i - 1][0], val = events[i - 1][2]; - int p = search(events, st, i - 1); - for (int j = 1; j <= k; ++j) { - f[i][j] = Math.max(f[i - 1][j], f[p][j - 1] + val); - } - } - return f[n][k]; - } - - private int search(int[][] events, int x, int hi) { - int l = 0, r = hi; - while (l < r) { - int mid = (l + r) >> 1; - if (events[mid][1] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -188,29 +140,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxValue(vector>& events, int k) { - sort(events.begin(), events.end(), [](const auto& a, const auto& b) { return a[1] < b[1]; }); - int n = events.size(); - int f[n + 1][k + 1]; - memset(f, 0, sizeof(f)); - for (int i = 1; i <= n; ++i) { - int st = events[i - 1][0], val = events[i - 1][2]; - vector t = {st}; - int p = lower_bound(events.begin(), events.begin() + i - 1, t, [](const auto& a, const auto& b) { return a[1] < b[0]; }) - events.begin(); - for (int j = 1; j <= k; ++j) { - f[i][j] = max(f[i - 1][j], f[p][j - 1] + val); - } - } - return f[n][k]; - } -}; -``` - -### **Go** - ```go func maxValue(events [][]int, k int) int { sort.Slice(events, func(i, j int) bool { return events[i][0] < events[j][0] }) @@ -236,27 +165,6 @@ func maxValue(events [][]int, k int) int { } ``` -```go -func maxValue(events [][]int, k int) int { - sort.Slice(events, func(i, j int) bool { return events[i][1] < events[j][1] }) - n := len(events) - f := make([][]int, n+1) - for i := range f { - f[i] = make([]int, k+1) - } - for i := 1; i <= n; i++ { - st, val := events[i-1][0], events[i-1][2] - p := sort.Search(i, func(j int) bool { return events[j][1] >= st }) - for j := 1; j <= k; j++ { - f[i][j] = max(f[i-1][j], f[p][j-1]+val) - } - } - return f[n][k] -} -``` - -### **TypeScript** - ```ts function maxValue(events: number[][], k: number): number { events.sort((a, b) => a[1] - b[1]); @@ -286,10 +194,96 @@ function maxValue(events: number[][], k: number): number { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def maxValue(self, events: List[List[int]], k: int) -> int: + events.sort(key=lambda x: x[1]) + n = len(events) + f = [[0] * (k + 1) for _ in range(n + 1)] + for i, (st, _, val) in enumerate(events, 1): + p = bisect_left(events, st, hi=i - 1, key=lambda x: x[1]) + for j in range(1, k + 1): + f[i][j] = max(f[i - 1][j], f[p][j - 1] + val) + return f[n][k] ``` +```java +class Solution { + public int maxValue(int[][] events, int k) { + Arrays.sort(events, (a, b) -> a[1] - b[1]); + int n = events.length; + int[][] f = new int[n + 1][k + 1]; + for (int i = 1; i <= n; ++i) { + int st = events[i - 1][0], val = events[i - 1][2]; + int p = search(events, st, i - 1); + for (int j = 1; j <= k; ++j) { + f[i][j] = Math.max(f[i - 1][j], f[p][j - 1] + val); + } + } + return f[n][k]; + } + + private int search(int[][] events, int x, int hi) { + int l = 0, r = hi; + while (l < r) { + int mid = (l + r) >> 1; + if (events[mid][1] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } +} +``` + +```cpp +class Solution { +public: + int maxValue(vector>& events, int k) { + sort(events.begin(), events.end(), [](const auto& a, const auto& b) { return a[1] < b[1]; }); + int n = events.size(); + int f[n + 1][k + 1]; + memset(f, 0, sizeof(f)); + for (int i = 1; i <= n; ++i) { + int st = events[i - 1][0], val = events[i - 1][2]; + vector t = {st}; + int p = lower_bound(events.begin(), events.begin() + i - 1, t, [](const auto& a, const auto& b) { return a[1] < b[0]; }) - events.begin(); + for (int j = 1; j <= k; ++j) { + f[i][j] = max(f[i - 1][j], f[p][j - 1] + val); + } + } + return f[n][k]; + } +}; +``` + +```go +func maxValue(events [][]int, k int) int { + sort.Slice(events, func(i, j int) bool { return events[i][1] < events[j][1] }) + n := len(events) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, k+1) + } + for i := 1; i <= n; i++ { + st, val := events[i-1][0], events[i-1][2] + p := sort.Search(i, func(j int) bool { return events[j][1] >= st }) + for j := 1; j <= k; j++ { + f[i][j] = max(f[i-1][j], f[p][j-1]+val) + } + } + return f[n][k] +} ``` + + diff --git a/solution/1700-1799/1752.Check if Array Is Sorted and Rotated/README.md b/solution/1700-1799/1752.Check if Array Is Sorted and Rotated/README.md index 52721f5eb7a88..e76f12d0a4b21 100644 --- a/solution/1700-1799/1752.Check if Array Is Sorted and Rotated/README.md +++ b/solution/1700-1799/1752.Check if Array Is Sorted and Rotated/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 要满足题目要求,那么数组 `nums` 中最多只能存在一个元素,其值大于下一个元素,即 $nums[i] \gt nums[i + 1]$。如果存在多个这样的元素,那么数组 `nums` 无法通过轮转得到。 @@ -65,20 +63,12 @@ -### **Python3** - - - ```python class Solution: def check(self, nums: List[int]) -> bool: return sum(nums[i - 1] > v for i, v in enumerate(nums)) <= 1 ``` -### **Java** - - - ```java class Solution { public boolean check(int[] nums) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +96,6 @@ public: }; ``` -### **Go** - ```go func check(nums []int) bool { cnt := 0 @@ -122,8 +108,6 @@ func check(nums []int) bool { } ``` -### **TypeScript** - ```ts function check(nums: number[]): boolean { const n = nums.length; @@ -131,8 +115,6 @@ function check(nums: number[]): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn check(nums: Vec) -> bool { @@ -148,8 +130,6 @@ impl Solution { } ``` -### **C** - ```c bool check(int* nums, int numsSize) { int count = 0; @@ -162,10 +142,6 @@ bool check(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1752.Check if Array Is Sorted and Rotated/README_EN.md b/solution/1700-1799/1752.Check if Array Is Sorted and Rotated/README_EN.md index 2c1524ad8839d..ad8be8d516e33 100644 --- a/solution/1700-1799/1752.Check if Array Is Sorted and Rotated/README_EN.md +++ b/solution/1700-1799/1752.Check if Array Is Sorted and Rotated/README_EN.md @@ -47,9 +47,9 @@ You can rotate the array by x = 0 positions (i.e. no rotation) to make nums. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,8 +57,6 @@ class Solution: return sum(nums[i - 1] > v for i, v in enumerate(nums)) <= 1 ``` -### **Java** - ```java class Solution { public boolean check(int[] nums) { @@ -73,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -88,8 +84,6 @@ public: }; ``` -### **Go** - ```go func check(nums []int) bool { cnt := 0 @@ -102,8 +96,6 @@ func check(nums []int) bool { } ``` -### **TypeScript** - ```ts function check(nums: number[]): boolean { const n = nums.length; @@ -111,8 +103,6 @@ function check(nums: number[]): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn check(nums: Vec) -> bool { @@ -128,8 +118,6 @@ impl Solution { } ``` -### **C** - ```c bool check(int* nums, int numsSize) { int count = 0; @@ -142,10 +130,6 @@ bool check(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1753.Maximum Score From Removing Stones/README.md b/solution/1700-1799/1753.Maximum Score From Removing Stones/README.md index 1131bfebad281..fa34fc44d2f8c 100644 --- a/solution/1700-1799/1753.Maximum Score From Removing Stones/README.md +++ b/solution/1700-1799/1753.Maximum Score From Removing Stones/README.md @@ -63,29 +63,14 @@ ## 解法 - - -**方法一:贪心 + 模拟** +### 方法一:贪心 + 模拟 每次贪心地从最大的两堆石子中取石头,直到至少有两堆石子为空。 时间复杂度 $O(n)$,其中 $n$ 为石子总数。 -**方法二:贪心 + 数学** - -我们不妨设 $a \le b \le c$,那么: - -- 当 $a + b \le c$ 时,我们可以先从 $a$, $c$ 两堆中取石头,得到分数 $a$;再从 $b$, $c$ 两堆中取石头,得到分数 $b$,总分数为 $a + b$; -- 当 $a + b \gt c$ 时,这时我们每次会从 $c$ 以及 $a$ 和 $b$ 中较大的那一堆中取石头,最终将 $c$ 取空。此时 $a$ 和 $b$ 的大小差最多为 $1$。我们再从 $a$, $b$ 两堆中取石头,直到不能取为止,总分数为 $\left \lfloor \frac{a + b + c}{2} \right \rfloor$。 - -时间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def maximumScore(self, a: int, b: int, c: int) -> int: @@ -99,19 +84,6 @@ class Solution: return ans ``` -```python -class Solution: - def maximumScore(self, a: int, b: int, c: int) -> int: - a, b, c = sorted([a, b, c]) - if a + b < c: - return a + b - return (a + b + c) >> 1 -``` - -### **Java** - - - ```java class Solution { public int maximumScore(int a, int b, int c) { @@ -129,21 +101,6 @@ class Solution { } ``` -```java -class Solution { - public int maximumScore(int a, int b, int c) { - int[] s = new int[] {a, b, c}; - Arrays.sort(s); - if (s[0] + s[1] < s[2]) { - return s[0] + s[1]; - } - return (a + b + c) >> 1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -162,20 +119,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maximumScore(int a, int b, int c) { - vector s = {a, b, c}; - sort(s.begin(), s.end()); - if (s[0] + s[1] < s[2]) return s[0] + s[1]; - return (a + b + c) >> 1; - } -}; -``` - -### **Go** - ```go func maximumScore(a int, b int, c int) (ans int) { s := []int{a, b, c} @@ -190,6 +133,53 @@ func maximumScore(a int, b int, c int) (ans int) { } ``` + + +### 方法二:贪心 + 数学 + +我们不妨设 $a \le b \le c$,那么: + +- 当 $a + b \le c$ 时,我们可以先从 $a$, $c$ 两堆中取石头,得到分数 $a$;再从 $b$, $c$ 两堆中取石头,得到分数 $b$,总分数为 $a + b$; +- 当 $a + b \gt c$ 时,这时我们每次会从 $c$ 以及 $a$ 和 $b$ 中较大的那一堆中取石头,最终将 $c$ 取空。此时 $a$ 和 $b$ 的大小差最多为 $1$。我们再从 $a$, $b$ 两堆中取石头,直到不能取为止,总分数为 $\left \lfloor \frac{a + b + c}{2} \right \rfloor$。 + +时间复杂度 $O(1)$。 + + + +```python +class Solution: + def maximumScore(self, a: int, b: int, c: int) -> int: + a, b, c = sorted([a, b, c]) + if a + b < c: + return a + b + return (a + b + c) >> 1 +``` + +```java +class Solution { + public int maximumScore(int a, int b, int c) { + int[] s = new int[] {a, b, c}; + Arrays.sort(s); + if (s[0] + s[1] < s[2]) { + return s[0] + s[1]; + } + return (a + b + c) >> 1; + } +} +``` + +```cpp +class Solution { +public: + int maximumScore(int a, int b, int c) { + vector s = {a, b, c}; + sort(s.begin(), s.end()); + if (s[0] + s[1] < s[2]) return s[0] + s[1]; + return (a + b + c) >> 1; + } +}; +``` + ```go func maximumScore(a int, b int, c int) int { s := []int{a, b, c} @@ -201,10 +191,6 @@ func maximumScore(a int, b int, c int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1753.Maximum Score From Removing Stones/README_EN.md b/solution/1700-1799/1753.Maximum Score From Removing Stones/README_EN.md index 805569ccca088..c0f09349353d2 100644 --- a/solution/1700-1799/1753.Maximum Score From Removing Stones/README_EN.md +++ b/solution/1700-1799/1753.Maximum Score From Removing Stones/README_EN.md @@ -58,9 +58,9 @@ After that, there are fewer than two non-empty piles, so the game ends. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,17 +75,6 @@ class Solution: return ans ``` -```python -class Solution: - def maximumScore(self, a: int, b: int, c: int) -> int: - a, b, c = sorted([a, b, c]) - if a + b < c: - return a + b - return (a + b + c) >> 1 -``` - -### **Java** - ```java class Solution { public int maximumScore(int a, int b, int c) { @@ -103,21 +92,6 @@ class Solution { } ``` -```java -class Solution { - public int maximumScore(int a, int b, int c) { - int[] s = new int[] {a, b, c}; - Arrays.sort(s); - if (s[0] + s[1] < s[2]) { - return s[0] + s[1]; - } - return (a + b + c) >> 1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -136,20 +110,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maximumScore(int a, int b, int c) { - vector s = {a, b, c}; - sort(s.begin(), s.end()); - if (s[0] + s[1] < s[2]) return s[0] + s[1]; - return (a + b + c) >> 1; - } -}; -``` - -### **Go** - ```go func maximumScore(a int, b int, c int) (ans int) { s := []int{a, b, c} @@ -164,6 +124,46 @@ func maximumScore(a int, b int, c int) (ans int) { } ``` + + +### Solution 2 + + + +```python +class Solution: + def maximumScore(self, a: int, b: int, c: int) -> int: + a, b, c = sorted([a, b, c]) + if a + b < c: + return a + b + return (a + b + c) >> 1 +``` + +```java +class Solution { + public int maximumScore(int a, int b, int c) { + int[] s = new int[] {a, b, c}; + Arrays.sort(s); + if (s[0] + s[1] < s[2]) { + return s[0] + s[1]; + } + return (a + b + c) >> 1; + } +} +``` + +```cpp +class Solution { +public: + int maximumScore(int a, int b, int c) { + vector s = {a, b, c}; + sort(s.begin(), s.end()); + if (s[0] + s[1] < s[2]) return s[0] + s[1]; + return (a + b + c) >> 1; + } +}; +``` + ```go func maximumScore(a int, b int, c int) int { s := []int{a, b, c} @@ -175,10 +175,6 @@ func maximumScore(a int, b int, c int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1754.Largest Merge Of Two Strings/README.md b/solution/1700-1799/1754.Largest Merge Of Two Strings/README.md index 3ea79694acac0..8e601e00728bd 100644 --- a/solution/1700-1799/1754.Largest Merge Of Two Strings/README.md +++ b/solution/1700-1799/1754.Largest Merge Of Two Strings/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:贪心 + 双指针** +### 方法一:贪心 + 双指针 我们用指针 $i$ 和 $j$ 分别指向字符串 `word1` 和 `word2` 的第一个字符。然后循环,每次比较 $word1[i:]$ 和 $word2[j:]$ 的大小,如果 $word1[i:]$ 比 $word2[j:]$ 大,那么我们就将 $word1[i]$ 加入答案,否则我们就将 $word2[j]$ 加入答案。循环,直至 $i$ 到达字符串 `word1` 的末尾,或者 $j$ 到达字符串 `word2` 的末尾。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def largestMerge(self, word1: str, word2: str) -> str: @@ -92,10 +86,6 @@ class Solution: return "".join(ans) ``` -### **Java** - - - ```java class Solution { public String largestMerge(String word1, String word2) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +121,6 @@ public: }; ``` -### **Go** - ```go func largestMerge(word1 string, word2 string) string { m, n := len(word1), len(word2) @@ -155,8 +141,6 @@ func largestMerge(word1 string, word2 string) string { } ``` -### **TypeScript** - ```ts function largestMerge(word1: string, word2: string): string { const m = word1.length; @@ -173,8 +157,6 @@ function largestMerge(word1: string, word2: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn largest_merge(word1: String, word2: String) -> String { @@ -201,8 +183,6 @@ impl Solution { } ``` -### **C** - ```c char* largestMerge(char* word1, char* word2) { int m = strlen(word1); @@ -236,10 +216,6 @@ char* largestMerge(char* word1, char* word2) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1754.Largest Merge Of Two Strings/README_EN.md b/solution/1700-1799/1754.Largest Merge Of Two Strings/README_EN.md index bb7e8df587a42..a24db9944a4cd 100644 --- a/solution/1700-1799/1754.Largest Merge Of Two Strings/README_EN.md +++ b/solution/1700-1799/1754.Largest Merge Of Two Strings/README_EN.md @@ -55,9 +55,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return "".join(ans) ``` -### **Java** - ```java class Solution { public String largestMerge(String word1, String word2) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +111,6 @@ public: }; ``` -### **Go** - ```go func largestMerge(word1 string, word2 string) string { m, n := len(word1), len(word2) @@ -137,8 +131,6 @@ func largestMerge(word1 string, word2 string) string { } ``` -### **TypeScript** - ```ts function largestMerge(word1: string, word2: string): string { const m = word1.length; @@ -155,8 +147,6 @@ function largestMerge(word1: string, word2: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn largest_merge(word1: String, word2: String) -> String { @@ -183,8 +173,6 @@ impl Solution { } ``` -### **C** - ```c char* largestMerge(char* word1, char* word2) { int m = strlen(word1); @@ -218,10 +206,6 @@ char* largestMerge(char* word1, char* word2) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1755.Closest Subsequence Sum/README.md b/solution/1700-1799/1755.Closest Subsequence Sum/README.md index 3feaef1d1e393..3dfae480ea2fe 100644 --- a/solution/1700-1799/1755.Closest Subsequence Sum/README.md +++ b/solution/1700-1799/1755.Closest Subsequence Sum/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:DFS + 二分查找** +### 方法一:DFS + 二分查找 每个数选或不选两种可能,所以 $n$ 个数就有 $2^n$ 种组合,由于 $n$ 最大为 $40$,枚举 $2^{40}$ 种组合显然会超时。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def minAbsDifference(self, nums: List[int], goal: int) -> int: @@ -103,36 +97,6 @@ class Solution: self.getSubSeqSum(i + 1, curr + arr[i], arr, result) ``` -```python -class Solution: - def minAbsDifference(self, nums: List[int], goal: int) -> int: - def dfs(arr, res, i, s): - if i == len(arr): - res.add(s) - return - dfs(arr, res, i + 1, s) - dfs(arr, res, i + 1, s + arr[i]) - - n = len(nums) - left, right = set(), set() - dfs(nums[: n >> 1], left, 0, 0) - dfs(nums[n >> 1 :], right, 0, 0) - right = sorted(right) - ans = inf - for l in left: - x = goal - l - i = bisect_left(right, x) - if i < len(right): - ans = min(ans, abs(x - right[i])) - if i: - ans = min(ans, abs(x - right[i - 1])) - return ans -``` - -### **Java** - - - ```java class Solution { public int minAbsDifference(int[] nums, int goal) { @@ -179,51 +143,54 @@ class Solution { } ``` -```java +```cpp class Solution { - public int minAbsDifference(int[] nums, int goal) { - int n = nums.length; - Set left = new HashSet<>(); - Set right = new HashSet<>(); - dfs(nums, 0, n >> 1, 0, left); - dfs(nums, n >> 1, n, 0, right); - List rs = new ArrayList<>(right); - Collections.sort(rs); - int ans = Integer.MAX_VALUE; - for (int x : left) { - int y = goal - x; - int l = 0, r = rs.size(); - while (l < r) { - int mid = (l + r) >> 1; - if (rs.get(mid) >= y) { - r = mid; +public: + int minAbsDifference(vector& nums, int goal) { + int n = nums.size(); + vector lsum; + vector rsum; + dfs(nums, lsum, 0, n / 2, 0); + dfs(nums, rsum, n / 2, n, 0); + + sort(rsum.begin(), rsum.end()); + int res = INT_MAX; + + for (int x : lsum) { + int target = goal - x; + int left = 0, right = rsum.size(); + while (left < right) { + int mid = (left + right) >> 1; + if (rsum[mid] < target) { + left = mid + 1; } else { - l = mid + 1; + right = mid; } } - if (l < rs.size()) { - ans = Math.min(ans, Math.abs(y - rs.get(l))); + if (left < rsum.size()) { + res = min(res, abs(target - rsum[left])); } - if (l > 0) { - ans = Math.min(ans, Math.abs(y - rs.get(l - 1))); + if (left > 0) { + res = min(res, abs(target - rsum[left - 1])); } } - return ans; + + return res; } - private void dfs(int[] arr, int i, int n, int s, Set res) { +private: + void dfs(vector& nums, vector& sum, int i, int n, int cur) { if (i == n) { - res.add(s); + sum.emplace_back(cur); return; } - dfs(arr, i + 1, n, s, res); - dfs(arr, i + 1, n, s + arr[i], res); + + dfs(nums, sum, i + 1, n, cur); + dfs(nums, sum, i + 1, n, cur + nums[i]); } -} +}; ``` -### **Go** - ```go func minAbsDifference(nums []int, goal int) int { n := len(nums) @@ -276,101 +243,79 @@ func abs(x int) int { } ``` -```go -func minAbsDifference(nums []int, goal int) int { - n := len(nums) - left := []int{} - right := []int{} - dfs(nums[:n>>1], &left, 0, 0) - dfs(nums[n>>1:], &right, 0, 0) - sort.Ints(right) - ans := math.MaxInt32 - for _, x := range left { - y := goal - x - l, r := 0, len(right) - for l < r { - mid := (l + r) >> 1 - if right[mid] >= y { - r = mid - } else { - l = mid + 1 - } - } - if l < len(right) { - ans = min(ans, abs(y-right[l])) - } - if l > 0 { - ans = min(ans, abs(y-right[l-1])) - } - } - return ans -} - -func dfs(arr []int, res *[]int, i, s int) { - if i == len(arr) { - *res = append(*res, s) - return - } - dfs(arr, res, i+1, s) - dfs(arr, res, i+1, s+arr[i]) -} + -func abs(x int) int { - if x < 0 { - return -x - } - return x -} -``` +### 方法二 -### **C++** + -```cpp -class Solution { -public: - int minAbsDifference(vector& nums, int goal) { - int n = nums.size(); - vector lsum; - vector rsum; - dfs(nums, lsum, 0, n / 2, 0); - dfs(nums, rsum, n / 2, n, 0); +```python +class Solution: + def minAbsDifference(self, nums: List[int], goal: int) -> int: + def dfs(arr, res, i, s): + if i == len(arr): + res.add(s) + return + dfs(arr, res, i + 1, s) + dfs(arr, res, i + 1, s + arr[i]) - sort(rsum.begin(), rsum.end()); - int res = INT_MAX; + n = len(nums) + left, right = set(), set() + dfs(nums[: n >> 1], left, 0, 0) + dfs(nums[n >> 1 :], right, 0, 0) + right = sorted(right) + ans = inf + for l in left: + x = goal - l + i = bisect_left(right, x) + if i < len(right): + ans = min(ans, abs(x - right[i])) + if i: + ans = min(ans, abs(x - right[i - 1])) + return ans +``` - for (int x : lsum) { - int target = goal - x; - int left = 0, right = rsum.size(); - while (left < right) { - int mid = (left + right) >> 1; - if (rsum[mid] < target) { - left = mid + 1; +```java +class Solution { + public int minAbsDifference(int[] nums, int goal) { + int n = nums.length; + Set left = new HashSet<>(); + Set right = new HashSet<>(); + dfs(nums, 0, n >> 1, 0, left); + dfs(nums, n >> 1, n, 0, right); + List rs = new ArrayList<>(right); + Collections.sort(rs); + int ans = Integer.MAX_VALUE; + for (int x : left) { + int y = goal - x; + int l = 0, r = rs.size(); + while (l < r) { + int mid = (l + r) >> 1; + if (rs.get(mid) >= y) { + r = mid; } else { - right = mid; + l = mid + 1; } } - if (left < rsum.size()) { - res = min(res, abs(target - rsum[left])); + if (l < rs.size()) { + ans = Math.min(ans, Math.abs(y - rs.get(l))); } - if (left > 0) { - res = min(res, abs(target - rsum[left - 1])); + if (l > 0) { + ans = Math.min(ans, Math.abs(y - rs.get(l - 1))); } } - - return res; + return ans; } -private: - void dfs(vector& nums, vector& sum, int i, int n, int cur) { + private void dfs(int[] arr, int i, int n, int s, Set res) { if (i == n) { - sum.emplace_back(cur); + res.add(s); return; } - - dfs(nums, sum, i + 1, n, cur); - dfs(nums, sum, i + 1, n, cur + nums[i]); + dfs(arr, i + 1, n, s, res); + dfs(arr, i + 1, n, s + arr[i], res); } -}; +} ``` ```cpp @@ -405,10 +350,53 @@ private: }; ``` -### **...** +```go +func minAbsDifference(nums []int, goal int) int { + n := len(nums) + left := []int{} + right := []int{} + dfs(nums[:n>>1], &left, 0, 0) + dfs(nums[n>>1:], &right, 0, 0) + sort.Ints(right) + ans := math.MaxInt32 + for _, x := range left { + y := goal - x + l, r := 0, len(right) + for l < r { + mid := (l + r) >> 1 + if right[mid] >= y { + r = mid + } else { + l = mid + 1 + } + } + if l < len(right) { + ans = min(ans, abs(y-right[l])) + } + if l > 0 { + ans = min(ans, abs(y-right[l-1])) + } + } + return ans +} -``` +func dfs(arr []int, res *[]int, i, s int) { + if i == len(arr) { + *res = append(*res, s) + return + } + dfs(arr, res, i+1, s) + dfs(arr, res, i+1, s+arr[i]) +} +func abs(x int) int { + if x < 0 { + return -x + } + return x +} ``` + + diff --git a/solution/1700-1799/1755.Closest Subsequence Sum/README_EN.md b/solution/1700-1799/1755.Closest Subsequence Sum/README_EN.md index be01463e0d4a0..f9e993c2160d9 100644 --- a/solution/1700-1799/1755.Closest Subsequence Sum/README_EN.md +++ b/solution/1700-1799/1755.Closest Subsequence Sum/README_EN.md @@ -49,9 +49,9 @@ The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -88,34 +88,6 @@ class Solution: self.getSubSeqSum(i + 1, curr + arr[i], arr, result) ``` -```python -class Solution: - def minAbsDifference(self, nums: List[int], goal: int) -> int: - def dfs(arr, res, i, s): - if i == len(arr): - res.add(s) - return - dfs(arr, res, i + 1, s) - dfs(arr, res, i + 1, s + arr[i]) - - n = len(nums) - left, right = set(), set() - dfs(nums[: n >> 1], left, 0, 0) - dfs(nums[n >> 1 :], right, 0, 0) - right = sorted(right) - ans = inf - for l in left: - x = goal - l - i = bisect_left(right, x) - if i < len(right): - ans = min(ans, abs(x - right[i])) - if i: - ans = min(ans, abs(x - right[i - 1])) - return ans -``` - -### **Java** - ```java class Solution { public int minAbsDifference(int[] nums, int goal) { @@ -162,51 +134,54 @@ class Solution { } ``` -```java +```cpp class Solution { - public int minAbsDifference(int[] nums, int goal) { - int n = nums.length; - Set left = new HashSet<>(); - Set right = new HashSet<>(); - dfs(nums, 0, n >> 1, 0, left); - dfs(nums, n >> 1, n, 0, right); - List rs = new ArrayList<>(right); - Collections.sort(rs); - int ans = Integer.MAX_VALUE; - for (int x : left) { - int y = goal - x; - int l = 0, r = rs.size(); - while (l < r) { - int mid = (l + r) >> 1; - if (rs.get(mid) >= y) { - r = mid; +public: + int minAbsDifference(vector& nums, int goal) { + int n = nums.size(); + vector lsum; + vector rsum; + dfs(nums, lsum, 0, n / 2, 0); + dfs(nums, rsum, n / 2, n, 0); + + sort(rsum.begin(), rsum.end()); + int res = INT_MAX; + + for (int x : lsum) { + int target = goal - x; + int left = 0, right = rsum.size(); + while (left < right) { + int mid = (left + right) >> 1; + if (rsum[mid] < target) { + left = mid + 1; } else { - l = mid + 1; + right = mid; } } - if (l < rs.size()) { - ans = Math.min(ans, Math.abs(y - rs.get(l))); + if (left < rsum.size()) { + res = min(res, abs(target - rsum[left])); } - if (l > 0) { - ans = Math.min(ans, Math.abs(y - rs.get(l - 1))); + if (left > 0) { + res = min(res, abs(target - rsum[left - 1])); } } - return ans; + + return res; } - private void dfs(int[] arr, int i, int n, int s, Set res) { +private: + void dfs(vector& nums, vector& sum, int i, int n, int cur) { if (i == n) { - res.add(s); + sum.emplace_back(cur); return; } - dfs(arr, i + 1, n, s, res); - dfs(arr, i + 1, n, s + arr[i], res); + + dfs(nums, sum, i + 1, n, cur); + dfs(nums, sum, i + 1, n, cur + nums[i]); } -} +}; ``` -### **Go** - ```go func minAbsDifference(nums []int, goal int) int { n := len(nums) @@ -259,101 +234,79 @@ func abs(x int) int { } ``` -```go -func minAbsDifference(nums []int, goal int) int { - n := len(nums) - left := []int{} - right := []int{} - dfs(nums[:n>>1], &left, 0, 0) - dfs(nums[n>>1:], &right, 0, 0) - sort.Ints(right) - ans := math.MaxInt32 - for _, x := range left { - y := goal - x - l, r := 0, len(right) - for l < r { - mid := (l + r) >> 1 - if right[mid] >= y { - r = mid - } else { - l = mid + 1 - } - } - if l < len(right) { - ans = min(ans, abs(y-right[l])) - } - if l > 0 { - ans = min(ans, abs(y-right[l-1])) - } - } - return ans -} - -func dfs(arr []int, res *[]int, i, s int) { - if i == len(arr) { - *res = append(*res, s) - return - } - dfs(arr, res, i+1, s) - dfs(arr, res, i+1, s+arr[i]) -} + -func abs(x int) int { - if x < 0 { - return -x - } - return x -} -``` +### Solution 2 -### **C++** + -```cpp -class Solution { -public: - int minAbsDifference(vector& nums, int goal) { - int n = nums.size(); - vector lsum; - vector rsum; - dfs(nums, lsum, 0, n / 2, 0); - dfs(nums, rsum, n / 2, n, 0); +```python +class Solution: + def minAbsDifference(self, nums: List[int], goal: int) -> int: + def dfs(arr, res, i, s): + if i == len(arr): + res.add(s) + return + dfs(arr, res, i + 1, s) + dfs(arr, res, i + 1, s + arr[i]) - sort(rsum.begin(), rsum.end()); - int res = INT_MAX; + n = len(nums) + left, right = set(), set() + dfs(nums[: n >> 1], left, 0, 0) + dfs(nums[n >> 1 :], right, 0, 0) + right = sorted(right) + ans = inf + for l in left: + x = goal - l + i = bisect_left(right, x) + if i < len(right): + ans = min(ans, abs(x - right[i])) + if i: + ans = min(ans, abs(x - right[i - 1])) + return ans +``` - for (int x : lsum) { - int target = goal - x; - int left = 0, right = rsum.size(); - while (left < right) { - int mid = (left + right) >> 1; - if (rsum[mid] < target) { - left = mid + 1; +```java +class Solution { + public int minAbsDifference(int[] nums, int goal) { + int n = nums.length; + Set left = new HashSet<>(); + Set right = new HashSet<>(); + dfs(nums, 0, n >> 1, 0, left); + dfs(nums, n >> 1, n, 0, right); + List rs = new ArrayList<>(right); + Collections.sort(rs); + int ans = Integer.MAX_VALUE; + for (int x : left) { + int y = goal - x; + int l = 0, r = rs.size(); + while (l < r) { + int mid = (l + r) >> 1; + if (rs.get(mid) >= y) { + r = mid; } else { - right = mid; + l = mid + 1; } } - if (left < rsum.size()) { - res = min(res, abs(target - rsum[left])); + if (l < rs.size()) { + ans = Math.min(ans, Math.abs(y - rs.get(l))); } - if (left > 0) { - res = min(res, abs(target - rsum[left - 1])); + if (l > 0) { + ans = Math.min(ans, Math.abs(y - rs.get(l - 1))); } } - - return res; + return ans; } -private: - void dfs(vector& nums, vector& sum, int i, int n, int cur) { + private void dfs(int[] arr, int i, int n, int s, Set res) { if (i == n) { - sum.emplace_back(cur); + res.add(s); return; } - - dfs(nums, sum, i + 1, n, cur); - dfs(nums, sum, i + 1, n, cur + nums[i]); + dfs(arr, i + 1, n, s, res); + dfs(arr, i + 1, n, s + arr[i], res); } -}; +} ``` ```cpp @@ -388,10 +341,53 @@ private: }; ``` -### **...** +```go +func minAbsDifference(nums []int, goal int) int { + n := len(nums) + left := []int{} + right := []int{} + dfs(nums[:n>>1], &left, 0, 0) + dfs(nums[n>>1:], &right, 0, 0) + sort.Ints(right) + ans := math.MaxInt32 + for _, x := range left { + y := goal - x + l, r := 0, len(right) + for l < r { + mid := (l + r) >> 1 + if right[mid] >= y { + r = mid + } else { + l = mid + 1 + } + } + if l < len(right) { + ans = min(ans, abs(y-right[l])) + } + if l > 0 { + ans = min(ans, abs(y-right[l-1])) + } + } + return ans +} -``` +func dfs(arr []int, res *[]int, i, s int) { + if i == len(arr) { + *res = append(*res, s) + return + } + dfs(arr, res, i+1, s) + dfs(arr, res, i+1, s+arr[i]) +} +func abs(x int) int { + if x < 0 { + return -x + } + return x +} ``` + + diff --git a/solution/1700-1799/1756.Design Most Recently Used Queue/README.md b/solution/1700-1799/1756.Design Most Recently Used Queue/README.md index 0c9314d4d9b06..2d8c41efbcaa1 100644 --- a/solution/1700-1799/1756.Design Most Recently Used Queue/README.md +++ b/solution/1700-1799/1756.Design Most Recently Used Queue/README.md @@ -49,9 +49,7 @@ mRUQueue.fetch(8); // 第 8 个元素 (2) 已经在队列尾部了,所以直 ## 解法 - - -**方法一:树状数组 + 二分查找** +### 方法一:树状数组 + 二分查找 我们用一个数组 $q$ 维护当前队列中的元素,移动第 $k$ 个元素时,我们考虑不删除该元素,而是直接将其追加到数组末尾。如果不删除,我们如何知道第 $k$ 个元素在数组 $q$ 中的位置呢? @@ -61,10 +59,6 @@ mRUQueue.fetch(8); // 第 8 个元素 (2) 已经在队列尾部了,所以直 -### **Python3** - - - ```python class MRUQueue: def __init__(self, n: int): @@ -82,53 +76,6 @@ class MRUQueue: # param_1 = obj.fetch(k) ``` -```python -class BinaryIndexedTree: - def __init__(self, n: int): - self.n = n - self.c = [0] * (n + 1) - - def update(self, x: int, v: int): - while x <= self.n: - self.c[x] += v - x += x & -x - - def query(self, x: int) -> int: - s = 0 - while x: - s += self.c[x] - x -= x & -x - return s - - -class MRUQueue: - def __init__(self, n: int): - self.q = list(range(n + 1)) - self.tree = BinaryIndexedTree(n + 2010) - - def fetch(self, k: int) -> int: - l, r = 1, len(self.q) - while l < r: - mid = (l + r) >> 1 - if mid - self.tree.query(mid) >= k: - r = mid - else: - l = mid + 1 - x = self.q[l] - self.q.append(x) - self.tree.update(l, 1) - return x - - -# Your MRUQueue object will be instantiated and called as such: -# obj = MRUQueue(n) -# param_1 = obj.fetch(k) -``` - -### **Java** - - - ```java class BinaryIndexedTree { private int n; @@ -194,8 +141,6 @@ class MRUQueue { */ ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -260,8 +205,6 @@ private: */ ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -325,8 +268,6 @@ func (this *MRUQueue) Fetch(k int) int { */ ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -391,10 +332,55 @@ class MRUQueue { */ ``` -### **...** + + +### 方法二 -``` + + +```python +class BinaryIndexedTree: + def __init__(self, n: int): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x: int, v: int): + while x <= self.n: + self.c[x] += v + x += x & -x + + def query(self, x: int) -> int: + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s + +class MRUQueue: + def __init__(self, n: int): + self.q = list(range(n + 1)) + self.tree = BinaryIndexedTree(n + 2010) + + def fetch(self, k: int) -> int: + l, r = 1, len(self.q) + while l < r: + mid = (l + r) >> 1 + if mid - self.tree.query(mid) >= k: + r = mid + else: + l = mid + 1 + x = self.q[l] + self.q.append(x) + self.tree.update(l, 1) + return x + + +# Your MRUQueue object will be instantiated and called as such: +# obj = MRUQueue(n) +# param_1 = obj.fetch(k) ``` + + diff --git a/solution/1700-1799/1756.Design Most Recently Used Queue/README_EN.md b/solution/1700-1799/1756.Design Most Recently Used Queue/README_EN.md index e3fbd8fc4ee73..1d16cbb060000 100644 --- a/solution/1700-1799/1756.Design Most Recently Used Queue/README_EN.md +++ b/solution/1700-1799/1756.Design Most Recently Used Queue/README_EN.md @@ -45,9 +45,9 @@ mRUQueue.fetch(8); // The 8th element (2) is already at the end of th ## Solutions - +### Solution 1 -### **Python3** + ```python class MRUQueue: @@ -66,51 +66,6 @@ class MRUQueue: # param_1 = obj.fetch(k) ``` -```python -class BinaryIndexedTree: - def __init__(self, n: int): - self.n = n - self.c = [0] * (n + 1) - - def update(self, x: int, v: int): - while x <= self.n: - self.c[x] += v - x += x & -x - - def query(self, x: int) -> int: - s = 0 - while x: - s += self.c[x] - x -= x & -x - return s - - -class MRUQueue: - def __init__(self, n: int): - self.q = list(range(n + 1)) - self.tree = BinaryIndexedTree(n + 2010) - - def fetch(self, k: int) -> int: - l, r = 1, len(self.q) - while l < r: - mid = (l + r) >> 1 - if mid - self.tree.query(mid) >= k: - r = mid - else: - l = mid + 1 - x = self.q[l] - self.q.append(x) - self.tree.update(l, 1) - return x - - -# Your MRUQueue object will be instantiated and called as such: -# obj = MRUQueue(n) -# param_1 = obj.fetch(k) -``` - -### **Java** - ```java class BinaryIndexedTree { private int n; @@ -176,8 +131,6 @@ class MRUQueue { */ ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -242,8 +195,6 @@ private: */ ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -307,8 +258,6 @@ func (this *MRUQueue) Fetch(k int) int { */ ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -373,10 +322,55 @@ class MRUQueue { */ ``` -### **...** + + +### Solution 2 + + + +```python +class BinaryIndexedTree: + def __init__(self, n: int): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x: int, v: int): + while x <= self.n: + self.c[x] += v + x += x & -x + + def query(self, x: int) -> int: + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s -``` +class MRUQueue: + def __init__(self, n: int): + self.q = list(range(n + 1)) + self.tree = BinaryIndexedTree(n + 2010) + + def fetch(self, k: int) -> int: + l, r = 1, len(self.q) + while l < r: + mid = (l + r) >> 1 + if mid - self.tree.query(mid) >= k: + r = mid + else: + l = mid + 1 + x = self.q[l] + self.q.append(x) + self.tree.update(l, 1) + return x + + +# Your MRUQueue object will be instantiated and called as such: +# obj = MRUQueue(n) +# param_1 = obj.fetch(k) ``` + + diff --git a/solution/1700-1799/1757.Recyclable and Low Fat Products/README.md b/solution/1700-1799/1757.Recyclable and Low Fat Products/README.md index 8666096fbc255..a5640cf97ee87 100644 --- a/solution/1700-1799/1757.Recyclable and Low Fat Products/README.md +++ b/solution/1700-1799/1757.Recyclable and Low Fat Products/README.md @@ -57,25 +57,12 @@ Products 表: ## 解法 - - -**方法一:条件筛选** +### 方法一:条件筛选 我们直接筛选出 `low_fats` 为 `Y` 且 `recyclable` 为 `Y` 的产品编号即可。 -### **SQL** - -```sql -SELECT - product_id -FROM Products -WHERE low_fats = 'Y' AND recyclable = 'Y'; -``` - -### **PANDAS** - ```python import pandas as pd @@ -86,4 +73,13 @@ def find_products(products: pd.DataFrame) -> pd.DataFrame: return rs ``` +```sql +SELECT + product_id +FROM Products +WHERE low_fats = 'Y' AND recyclable = 'Y'; +``` + + + diff --git a/solution/1700-1799/1757.Recyclable and Low Fat Products/README_EN.md b/solution/1700-1799/1757.Recyclable and Low Fat Products/README_EN.md index 8b5f02cc81aa9..bec25e1273e33 100644 --- a/solution/1700-1799/1757.Recyclable and Low Fat Products/README_EN.md +++ b/solution/1700-1799/1757.Recyclable and Low Fat Products/README_EN.md @@ -53,23 +53,12 @@ Products table: ## Solutions -**Solution 1: Conditional Filtering** +### Solution 1: Conditional Filtering We can directly filter the product IDs where `low_fats` is `Y` and `recyclable` is `Y`. -### **SQL** - -```sql -SELECT - product_id -FROM Products -WHERE low_fats = 'Y' AND recyclable = 'Y'; -``` - -### **PANDAS** - ```python import pandas as pd @@ -80,4 +69,13 @@ def find_products(products: pd.DataFrame) -> pd.DataFrame: return rs ``` +```sql +SELECT + product_id +FROM Products +WHERE low_fats = 'Y' AND recyclable = 'Y'; +``` + + + diff --git a/solution/1700-1799/1758.Minimum Changes To Make Alternating Binary String/README.md b/solution/1700-1799/1758.Minimum Changes To Make Alternating Binary String/README.md index 117ca2151449c..cac644a894c94 100644 --- a/solution/1700-1799/1758.Minimum Changes To Make Alternating Binary String/README.md +++ b/solution/1700-1799/1758.Minimum Changes To Make Alternating Binary String/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 根据题意,如果得到交替字符串 `01010101...` 所需要的操作数为 $cnt$,那么得到交替字符串 `10101010...` 所需要的操作数为 $n - cnt$。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, s: str) -> int: @@ -69,10 +63,6 @@ class Solution: return min(cnt, len(s) - cnt) ``` -### **Java** - - - ```java class Solution { public int minOperations(String s) { @@ -85,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +86,6 @@ public: }; ``` -### **Go** - ```go func minOperations(s string) int { cnt := 0 @@ -112,8 +98,6 @@ func minOperations(s string) int { } ``` -### **TypeScript** - ```ts function minOperations(s: string): number { const n = s.length; @@ -125,8 +109,6 @@ function minOperations(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_operations(s: String) -> i32 { @@ -142,8 +124,6 @@ impl Solution { } ``` -### **C** - ```c #define min(a, b) (((a) < (b)) ? (a) : (b)) @@ -157,10 +137,6 @@ int minOperations(char* s) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1758.Minimum Changes To Make Alternating Binary String/README_EN.md b/solution/1700-1799/1758.Minimum Changes To Make Alternating Binary String/README_EN.md index 0c8ccd00a95db..acc3f00b83b64 100644 --- a/solution/1700-1799/1758.Minimum Changes To Make Alternating Binary String/README_EN.md +++ b/solution/1700-1799/1758.Minimum Changes To Make Alternating Binary String/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return min(cnt, len(s) - cnt) ``` -### **Java** - ```java class Solution { public int minOperations(String s) { @@ -70,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -83,8 +79,6 @@ public: }; ``` -### **Go** - ```go func minOperations(s string) int { cnt := 0 @@ -97,8 +91,6 @@ func minOperations(s string) int { } ``` -### **TypeScript** - ```ts function minOperations(s: string): number { const n = s.length; @@ -110,8 +102,6 @@ function minOperations(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_operations(s: String) -> i32 { @@ -127,8 +117,6 @@ impl Solution { } ``` -### **C** - ```c #define min(a, b) (((a) < (b)) ? (a) : (b)) @@ -142,10 +130,6 @@ int minOperations(char* s) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1759.Count Number of Homogenous Substrings/README.md b/solution/1700-1799/1759.Count Number of Homogenous Substrings/README.md index 2ff1acd90832b..5c2071219997c 100644 --- a/solution/1700-1799/1759.Count Number of Homogenous Substrings/README.md +++ b/solution/1700-1799/1759.Count Number of Homogenous Substrings/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 遍历字符串 $s$,用指针 $i$ 指向当前字符,指针 $j$ 指向下一个不同的字符,那么 $[i,..j-1]$ 区间内的字符都是相同的,假设 $cnt=j-i$,那么该区间内的同构子字符串个数为 $\frac{(1 + cnt) \times cnt}{2}$,将其累加到答案中即可。继续遍历,直到指针 $i$ 到达字符串末尾。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def countHomogenous(self, s: str) -> int: @@ -87,21 +81,6 @@ class Solution: return ans ``` -```python -class Solution: - def countHomogenous(self, s: str) -> int: - mod = 10**9 + 7 - ans = cnt = 1 - for a, b in pairwise(s): - cnt = cnt + 1 if a == b else 1 - ans = (ans + cnt) % mod - return ans -``` - -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -123,24 +102,6 @@ class Solution { } ``` -```java -class Solution { - private static final int MOD = (int) 1e9 + 7; - - public int countHomogenous(String s) { - int n = s.length(); - int ans = 1, cnt = 1; - for (int i = 1; i < n; ++i) { - cnt = s.charAt(i) == s.charAt(i - 1) ? cnt + 1 : 1; - ans = (ans + cnt) % MOD; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -161,25 +122,6 @@ public: }; ``` -```cpp -class Solution { -public: - const int mod = 1e9 + 7; - - int countHomogenous(string s) { - int n = s.size(); - int ans = 1, cnt = 1; - for (int i = 1; i < n; ++i) { - cnt = s[i] == s[i - 1] ? cnt + 1 : 1; - ans = (ans + cnt) % mod; - } - return ans; - } -}; -``` - -### **Go** - ```go func countHomogenous(s string) (ans int) { n := len(s) @@ -197,25 +139,6 @@ func countHomogenous(s string) (ans int) { } ``` -```go -func countHomogenous(s string) int { - n := len(s) - const mod int = 1e9 + 7 - ans, cnt := 1, 1 - for i := 1; i < n; i++ { - if s[i] == s[i-1] { - cnt++ - } else { - cnt = 1 - } - ans = (ans + cnt) % mod - } - return ans -} -``` - -### **TypeScript** - ```ts function countHomogenous(s: string): number { const mod = 1e9 + 7; @@ -231,8 +154,6 @@ function countHomogenous(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_homogenous(s: String) -> i32 { @@ -252,7 +173,24 @@ impl Solution { } ``` -### **C** +```cs +public class Solution { + public int CountHomogenous(string s) { + long MOD = 1000000007; + long ans = 0; + for (int i = 0, j = 0; i < s.Length; i = j) { + j = i; + while (j < s.Length && s[j] == s[i]) { + ++j; + } + int cnt = j - i; + ans += (long) (1 + cnt) * cnt / 2; + ans %= MOD; + } + return (int) ans; + } +} +``` ```c int countHomogenous(char* s) { @@ -268,31 +206,73 @@ int countHomogenous(char* s) { } ``` -### **C#** + -```cs -public class Solution { - public int CountHomogenous(string s) { - long MOD = 1000000007; - long ans = 0; - for (int i = 0, j = 0; i < s.Length; i = j) { - j = i; - while (j < s.Length && s[j] == s[i]) { - ++j; - } - int cnt = j - i; - ans += (long) (1 + cnt) * cnt / 2; - ans %= MOD; +### 方法二 + + + +```python +class Solution: + def countHomogenous(self, s: str) -> int: + mod = 10**9 + 7 + ans = cnt = 1 + for a, b in pairwise(s): + cnt = cnt + 1 if a == b else 1 + ans = (ans + cnt) % mod + return ans +``` + +```java +class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int countHomogenous(String s) { + int n = s.length(); + int ans = 1, cnt = 1; + for (int i = 1; i < n; ++i) { + cnt = s.charAt(i) == s.charAt(i - 1) ? cnt + 1 : 1; + ans = (ans + cnt) % MOD; } - return (int) ans; + return ans; } } ``` -### **...** +```cpp +class Solution { +public: + const int mod = 1e9 + 7; + int countHomogenous(string s) { + int n = s.size(); + int ans = 1, cnt = 1; + for (int i = 1; i < n; ++i) { + cnt = s[i] == s[i - 1] ? cnt + 1 : 1; + ans = (ans + cnt) % mod; + } + return ans; + } +}; ``` +```go +func countHomogenous(s string) int { + n := len(s) + const mod int = 1e9 + 7 + ans, cnt := 1, 1 + for i := 1; i < n; i++ { + if s[i] == s[i-1] { + cnt++ + } else { + cnt = 1 + } + ans = (ans + cnt) % mod + } + return ans +} ``` + + diff --git a/solution/1700-1799/1759.Count Number of Homogenous Substrings/README_EN.md b/solution/1700-1799/1759.Count Number of Homogenous Substrings/README_EN.md index 45be485926bd7..41c89eec83f32 100644 --- a/solution/1700-1799/1759.Count Number of Homogenous Substrings/README_EN.md +++ b/solution/1700-1799/1759.Count Number of Homogenous Substrings/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,19 +71,6 @@ class Solution: return ans ``` -```python -class Solution: - def countHomogenous(self, s: str) -> int: - mod = 10**9 + 7 - ans = cnt = 1 - for a, b in pairwise(s): - cnt = cnt + 1 if a == b else 1 - ans = (ans + cnt) % mod - return ans -``` - -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -105,24 +92,6 @@ class Solution { } ``` -```java -class Solution { - private static final int MOD = (int) 1e9 + 7; - - public int countHomogenous(String s) { - int n = s.length(); - int ans = 1, cnt = 1; - for (int i = 1; i < n; ++i) { - cnt = s.charAt(i) == s.charAt(i - 1) ? cnt + 1 : 1; - ans = (ans + cnt) % MOD; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -143,25 +112,6 @@ public: }; ``` -```cpp -class Solution { -public: - const int mod = 1e9 + 7; - - int countHomogenous(string s) { - int n = s.size(); - int ans = 1, cnt = 1; - for (int i = 1; i < n; ++i) { - cnt = s[i] == s[i - 1] ? cnt + 1 : 1; - ans = (ans + cnt) % mod; - } - return ans; - } -}; -``` - -### **Go** - ```go func countHomogenous(s string) (ans int) { n := len(s) @@ -179,25 +129,6 @@ func countHomogenous(s string) (ans int) { } ``` -```go -func countHomogenous(s string) int { - n := len(s) - const mod int = 1e9 + 7 - ans, cnt := 1, 1 - for i := 1; i < n; i++ { - if s[i] == s[i-1] { - cnt++ - } else { - cnt = 1 - } - ans = (ans + cnt) % mod - } - return ans -} -``` - -### **TypeScript** - ```ts function countHomogenous(s: string): number { const mod = 1e9 + 7; @@ -213,8 +144,6 @@ function countHomogenous(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_homogenous(s: String) -> i32 { @@ -234,7 +163,24 @@ impl Solution { } ``` -### **C** +```cs +public class Solution { + public int CountHomogenous(string s) { + long MOD = 1000000007; + long ans = 0; + for (int i = 0, j = 0; i < s.Length; i = j) { + j = i; + while (j < s.Length && s[j] == s[i]) { + ++j; + } + int cnt = j - i; + ans += (long) (1 + cnt) * cnt / 2; + ans %= MOD; + } + return (int) ans; + } +} +``` ```c int countHomogenous(char* s) { @@ -250,31 +196,73 @@ int countHomogenous(char* s) { } ``` -### **C#** + -```cs -public class Solution { - public int CountHomogenous(string s) { - long MOD = 1000000007; - long ans = 0; - for (int i = 0, j = 0; i < s.Length; i = j) { - j = i; - while (j < s.Length && s[j] == s[i]) { - ++j; - } - int cnt = j - i; - ans += (long) (1 + cnt) * cnt / 2; - ans %= MOD; +### Solution 2 + + + +```python +class Solution: + def countHomogenous(self, s: str) -> int: + mod = 10**9 + 7 + ans = cnt = 1 + for a, b in pairwise(s): + cnt = cnt + 1 if a == b else 1 + ans = (ans + cnt) % mod + return ans +``` + +```java +class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int countHomogenous(String s) { + int n = s.length(); + int ans = 1, cnt = 1; + for (int i = 1; i < n; ++i) { + cnt = s.charAt(i) == s.charAt(i - 1) ? cnt + 1 : 1; + ans = (ans + cnt) % MOD; } - return (int) ans; + return ans; } } ``` -### **...** +```cpp +class Solution { +public: + const int mod = 1e9 + 7; + int countHomogenous(string s) { + int n = s.size(); + int ans = 1, cnt = 1; + for (int i = 1; i < n; ++i) { + cnt = s[i] == s[i - 1] ? cnt + 1 : 1; + ans = (ans + cnt) % mod; + } + return ans; + } +}; ``` +```go +func countHomogenous(s string) int { + n := len(s) + const mod int = 1e9 + 7 + ans, cnt := 1, 1 + for i := 1; i < n; i++ { + if s[i] == s[i-1] { + cnt++ + } else { + cnt = 1 + } + ans = (ans + cnt) % mod + } + return ans +} ``` + + diff --git a/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/README.md b/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/README.md index 1ecc470ec7849..6ca14897bfd59 100644 --- a/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/README.md +++ b/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们可以将题目可以转换为:对某个开销值,看它能不能在 maxOperations 次操作内得到。因此,二分枚举开销值,找到最小的且满足条件的开销值即可。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def minimumSize(self, nums: List[int], maxOperations: int) -> int: @@ -89,10 +83,6 @@ class Solution: return bisect_left(range(1, max(nums)), True, key=check) + 1 ``` -### **Java** - - - ```java class Solution { public int minimumSize(int[] nums, int maxOperations) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func minimumSize(nums []int, maxOperations int) int { r := slices.Max(nums) @@ -157,15 +143,8 @@ func minimumSize(nums []int, maxOperations int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} maxOperations - * @return {number} - */ -var minimumSize = function (nums, maxOperations) { +```ts +function minimumSize(nums: number[], maxOperations: number): number { let left = 1; let right = Math.max(...nums); while (left < right) { @@ -181,13 +160,16 @@ var minimumSize = function (nums, maxOperations) { } } return left; -}; +} ``` -### **TypeScript** - -```ts -function minimumSize(nums: number[], maxOperations: number): number { +```js +/** + * @param {number[]} nums + * @param {number} maxOperations + * @return {number} + */ +var minimumSize = function (nums, maxOperations) { let left = 1; let right = Math.max(...nums); while (left < right) { @@ -203,13 +185,9 @@ function minimumSize(nums: number[], maxOperations: number): number { } } return left; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/README_EN.md b/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/README_EN.md index c338b55bfc8e5..18e851029113c 100644 --- a/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/README_EN.md +++ b/solution/1700-1799/1760.Minimum Limit of Balls in a Bag/README_EN.md @@ -55,12 +55,10 @@ The bag with the most number of balls has 2 balls, so your penalty is 2, and you ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python class Solution: def minimumSize(self, nums: List[int], maxOperations: int) -> int: @@ -70,8 +68,6 @@ class Solution: return bisect_left(range(1, max(nums)), True, key=check) + 1 ``` -### **Java** - ```java class Solution { public int minimumSize(int[] nums, int maxOperations) { @@ -96,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +114,6 @@ public: }; ``` -### **Go** - ```go func minimumSize(nums []int, maxOperations int) int { r := slices.Max(nums) @@ -136,15 +128,8 @@ func minimumSize(nums []int, maxOperations int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} maxOperations - * @return {number} - */ -var minimumSize = function (nums, maxOperations) { +```ts +function minimumSize(nums: number[], maxOperations: number): number { let left = 1; let right = Math.max(...nums); while (left < right) { @@ -160,13 +145,16 @@ var minimumSize = function (nums, maxOperations) { } } return left; -}; +} ``` -### **TypeScript** - -```ts -function minimumSize(nums: number[], maxOperations: number): number { +```js +/** + * @param {number[]} nums + * @param {number} maxOperations + * @return {number} + */ +var minimumSize = function (nums, maxOperations) { let left = 1; let right = Math.max(...nums); while (left < right) { @@ -182,13 +170,9 @@ function minimumSize(nums: number[], maxOperations: number): number { } } return left; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/README.md b/solution/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/README.md index c435bea2aeade..1b03bffb84546 100644 --- a/solution/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/README.md +++ b/solution/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 我们先将所有边存入邻接矩阵 $g$ 中,再将每个节点的度数存入数组 $deg$ 中。初始化答案 $ans=+\infty$。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def minTrioDegree(self, n: int, edges: List[List[int]]) -> int: @@ -88,10 +82,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - - - ```java class Solution { public int minTrioDegree(int n, int[][] edges) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func minTrioDegree(n int, edges [][]int) int { g := make([][]bool, n) @@ -187,8 +173,6 @@ func minTrioDegree(n int, edges [][]int) int { } ``` -### **TypeScript** - ```ts function minTrioDegree(n: number, edges: number[][]): number { const g = Array.from({ length: n }, () => Array(n).fill(false)); @@ -216,10 +200,6 @@ function minTrioDegree(n: number, edges: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/README_EN.md b/solution/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/README_EN.md index 0b909a42d11a7..b7ebf40748d39 100644 --- a/solution/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/README_EN.md +++ b/solution/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - ```java class Solution { public int minTrioDegree(int n, int[][] edges) { @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +129,6 @@ public: }; ``` -### **Go** - ```go func minTrioDegree(n int, edges [][]int) int { g := make([][]bool, n) @@ -167,8 +161,6 @@ func minTrioDegree(n int, edges [][]int) int { } ``` -### **TypeScript** - ```ts function minTrioDegree(n: number, edges: number[][]): number { const g = Array.from({ length: n }, () => Array(n).fill(false)); @@ -196,10 +188,6 @@ function minTrioDegree(n: number, edges: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1762.Buildings With an Ocean View/README.md b/solution/1700-1799/1762.Buildings With an Ocean View/README.md index 8a37c823dfdba..a6c3c2e407997 100644 --- a/solution/1700-1799/1762.Buildings With an Ocean View/README.md +++ b/solution/1700-1799/1762.Buildings With an Ocean View/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:逆序遍历求右侧最大值** +### 方法一:逆序遍历求右侧最大值 我们逆序遍历数组 $height$ 每个元素 $v$,判断 $v$ 与右侧最大元素 $mx$ 的大小关系,若 $mx \lt v$,说明右侧所有元素都比当前元素小,当前位置能看到海景,加入结果数组 $ans$。然后我们更新 $mx$ 为 $v$。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def findBuildings(self, heights: List[int]) -> List[int]: @@ -82,10 +76,6 @@ class Solution: return ans[::-1] ``` -### **Java** - - - ```java class Solution { public int[] findBuildings(int[] heights) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func findBuildings(heights []int) (ans []int) { mx := 0 @@ -142,8 +128,6 @@ func findBuildings(heights []int) (ans []int) { } ``` -### **TypeScript** - ```ts function findBuildings(heights: number[]): number[] { const ans: number[] = []; @@ -158,8 +142,6 @@ function findBuildings(heights: number[]): number[] { } ``` -### **JavaScript** - ```js /** * @param {number[]} heights @@ -178,10 +160,6 @@ var findBuildings = function (heights) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1762.Buildings With an Ocean View/README_EN.md b/solution/1700-1799/1762.Buildings With an Ocean View/README_EN.md index e9f6f93bd0233..201fc97a49a44 100644 --- a/solution/1700-1799/1762.Buildings With an Ocean View/README_EN.md +++ b/solution/1700-1799/1762.Buildings With an Ocean View/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ans[::-1] ``` -### **Java** - ```java class Solution { public int[] findBuildings(int[] heights) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +97,6 @@ public: }; ``` -### **Go** - ```go func findBuildings(heights []int) (ans []int) { mx := 0 @@ -119,8 +113,6 @@ func findBuildings(heights []int) (ans []int) { } ``` -### **TypeScript** - ```ts function findBuildings(heights: number[]): number[] { const ans: number[] = []; @@ -135,8 +127,6 @@ function findBuildings(heights: number[]): number[] { } ``` -### **JavaScript** - ```js /** * @param {number[]} heights @@ -155,10 +145,6 @@ var findBuildings = function (heights) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1763.Longest Nice Substring/README.md b/solution/1700-1799/1763.Longest Nice Substring/README.md index ecee41f83b684..8defbd01d4c13 100644 --- a/solution/1700-1799/1763.Longest Nice Substring/README.md +++ b/solution/1700-1799/1763.Longest Nice Substring/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:枚举 + 哈希表** +### 方法一:枚举 + 哈希表 我们可以直接枚举所有子串的起点位置 $i$,找到以该位置所在的字符为首字符的所有子串,用哈希表 $s$ 记录子串的所有字符。 @@ -64,20 +62,8 @@ 时间复杂度 $O(n^2 \times C)$,空间复杂度 $O(C)$。其中 $n$ 为字符串 $s$ 的长度,而 $C$ 为字符集的大小。 -**方法二:枚举 + 位运算** - -与方法一类似,我们可以直接枚举所有子串的起点位置 $i$,找到以该位置所在的字符为首字符的所有子串,用两个整数 $lower$ 和 $upper$ 分别记录子串中小写字母和大写字母的出现情况。 - -判断子串是否满足条件,只需要判断 $lower$ 和 $upper$ 中对应的位是否都为 $1$ 即可。 - -时间复杂度 $O(n^2)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。 - -### **Python3** - - - ```python class Solution: def longestNiceSubstring(self, s: str) -> str: @@ -95,27 +81,6 @@ class Solution: return ans ``` -```python -class Solution: - def longestNiceSubstring(self, s: str) -> str: - n = len(s) - ans = '' - for i in range(n): - lower = upper = 0 - for j in range(i, n): - if s[j].islower(): - lower |= 1 << (ord(s[j]) - ord('a')) - else: - upper |= 1 << (ord(s[j]) - ord('A')) - if lower == upper and len(ans) < j - i + 1: - ans = s[i : j + 1] - return ans -``` - -### **Java** - - - ```java class Solution { public String longestNiceSubstring(String s) { @@ -145,34 +110,6 @@ class Solution { } ``` -```java -class Solution { - public String longestNiceSubstring(String s) { - int n = s.length(); - int k = -1; - int mx = 0; - for (int i = 0; i < n; ++i) { - int lower = 0, upper = 0; - for (int j = i; j < n; ++j) { - char c = s.charAt(j); - if (Character.isLowerCase(c)) { - lower |= 1 << (c - 'a'); - } else { - upper |= 1 << (c - 'A'); - } - if (lower == upper && mx < j - i + 1) { - mx = j - i + 1; - k = i; - } - } - } - return k == -1 ? "" : s.substring(k, k + mx); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -202,33 +139,6 @@ public: }; ``` -```cpp -class Solution { -public: - string longestNiceSubstring(string s) { - int n = s.size(); - int k = -1, mx = 0; - for (int i = 0; i < n; ++i) { - int lower = 0, upper = 0; - for (int j = i; j < n; ++j) { - char c = s[j]; - if (islower(c)) - lower |= 1 << (c - 'a'); - else - upper |= 1 << (c - 'A'); - if (lower == upper && mx < j - i + 1) { - mx = j - i + 1; - k = i; - } - } - } - return k == -1 ? "" : s.substr(k, mx); - } -}; -``` - -### **Go** - ```go func longestNiceSubstring(s string) string { n := len(s) @@ -258,33 +168,6 @@ func longestNiceSubstring(s string) string { } ``` -```go -func longestNiceSubstring(s string) string { - n := len(s) - k, mx := -1, 0 - for i := 0; i < n; i++ { - var lower, upper int - for j := i; j < n; j++ { - if unicode.IsLower(rune(s[j])) { - lower |= 1 << (s[j] - 'a') - } else { - upper |= 1 << (s[j] - 'A') - } - if lower == upper && mx < j-i+1 { - mx = j - i + 1 - k = i - } - } - } - if k < 0 { - return "" - } - return s[k : k+mx] -} -``` - -### **TypeScript** - ```ts function longestNiceSubstring(s: string): string { const n = s.length; @@ -308,10 +191,111 @@ function longestNiceSubstring(s: string): string { } ``` -### **...** + + +### 方法二:枚举 + 位运算 + +与方法一类似,我们可以直接枚举所有子串的起点位置 $i$,找到以该位置所在的字符为首字符的所有子串,用两个整数 $lower$ 和 $upper$ 分别记录子串中小写字母和大写字母的出现情况。 + +判断子串是否满足条件,只需要判断 $lower$ 和 $upper$ 中对应的位是否都为 $1$ 即可。 + +时间复杂度 $O(n^2)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。 + + + +```python +class Solution: + def longestNiceSubstring(self, s: str) -> str: + n = len(s) + ans = '' + for i in range(n): + lower = upper = 0 + for j in range(i, n): + if s[j].islower(): + lower |= 1 << (ord(s[j]) - ord('a')) + else: + upper |= 1 << (ord(s[j]) - ord('A')) + if lower == upper and len(ans) < j - i + 1: + ans = s[i : j + 1] + return ans +``` + +```java +class Solution { + public String longestNiceSubstring(String s) { + int n = s.length(); + int k = -1; + int mx = 0; + for (int i = 0; i < n; ++i) { + int lower = 0, upper = 0; + for (int j = i; j < n; ++j) { + char c = s.charAt(j); + if (Character.isLowerCase(c)) { + lower |= 1 << (c - 'a'); + } else { + upper |= 1 << (c - 'A'); + } + if (lower == upper && mx < j - i + 1) { + mx = j - i + 1; + k = i; + } + } + } + return k == -1 ? "" : s.substring(k, k + mx); + } +} +``` +```cpp +class Solution { +public: + string longestNiceSubstring(string s) { + int n = s.size(); + int k = -1, mx = 0; + for (int i = 0; i < n; ++i) { + int lower = 0, upper = 0; + for (int j = i; j < n; ++j) { + char c = s[j]; + if (islower(c)) + lower |= 1 << (c - 'a'); + else + upper |= 1 << (c - 'A'); + if (lower == upper && mx < j - i + 1) { + mx = j - i + 1; + k = i; + } + } + } + return k == -1 ? "" : s.substr(k, mx); + } +}; ``` +```go +func longestNiceSubstring(s string) string { + n := len(s) + k, mx := -1, 0 + for i := 0; i < n; i++ { + var lower, upper int + for j := i; j < n; j++ { + if unicode.IsLower(rune(s[j])) { + lower |= 1 << (s[j] - 'a') + } else { + upper |= 1 << (s[j] - 'A') + } + if lower == upper && mx < j-i+1 { + mx = j - i + 1 + k = i + } + } + } + if k < 0 { + return "" + } + return s[k : k+mx] +} ``` + + diff --git a/solution/1700-1799/1763.Longest Nice Substring/README_EN.md b/solution/1700-1799/1763.Longest Nice Substring/README_EN.md index f6a2585cfffc8..f716d6e5af912 100644 --- a/solution/1700-1799/1763.Longest Nice Substring/README_EN.md +++ b/solution/1700-1799/1763.Longest Nice Substring/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,25 +65,6 @@ class Solution: return ans ``` -```python -class Solution: - def longestNiceSubstring(self, s: str) -> str: - n = len(s) - ans = '' - for i in range(n): - lower = upper = 0 - for j in range(i, n): - if s[j].islower(): - lower |= 1 << (ord(s[j]) - ord('a')) - else: - upper |= 1 << (ord(s[j]) - ord('A')) - if lower == upper and len(ans) < j - i + 1: - ans = s[i : j + 1] - return ans -``` - -### **Java** - ```java class Solution { public String longestNiceSubstring(String s) { @@ -113,34 +94,6 @@ class Solution { } ``` -```java -class Solution { - public String longestNiceSubstring(String s) { - int n = s.length(); - int k = -1; - int mx = 0; - for (int i = 0; i < n; ++i) { - int lower = 0, upper = 0; - for (int j = i; j < n; ++j) { - char c = s.charAt(j); - if (Character.isLowerCase(c)) { - lower |= 1 << (c - 'a'); - } else { - upper |= 1 << (c - 'A'); - } - if (lower == upper && mx < j - i + 1) { - mx = j - i + 1; - k = i; - } - } - } - return k == -1 ? "" : s.substring(k, k + mx); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -170,33 +123,6 @@ public: }; ``` -```cpp -class Solution { -public: - string longestNiceSubstring(string s) { - int n = s.size(); - int k = -1, mx = 0; - for (int i = 0; i < n; ++i) { - int lower = 0, upper = 0; - for (int j = i; j < n; ++j) { - char c = s[j]; - if (islower(c)) - lower |= 1 << (c - 'a'); - else - upper |= 1 << (c - 'A'); - if (lower == upper && mx < j - i + 1) { - mx = j - i + 1; - k = i; - } - } - } - return k == -1 ? "" : s.substr(k, mx); - } -}; -``` - -### **Go** - ```go func longestNiceSubstring(s string) string { n := len(s) @@ -226,33 +152,6 @@ func longestNiceSubstring(s string) string { } ``` -```go -func longestNiceSubstring(s string) string { - n := len(s) - k, mx := -1, 0 - for i := 0; i < n; i++ { - var lower, upper int - for j := i; j < n; j++ { - if unicode.IsLower(rune(s[j])) { - lower |= 1 << (s[j] - 'a') - } else { - upper |= 1 << (s[j] - 'A') - } - if lower == upper && mx < j-i+1 { - mx = j - i + 1 - k = i - } - } - } - if k < 0 { - return "" - } - return s[k : k+mx] -} -``` - -### **TypeScript** - ```ts function longestNiceSubstring(s: string): string { const n = s.length; @@ -276,10 +175,105 @@ function longestNiceSubstring(s: string): string { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def longestNiceSubstring(self, s: str) -> str: + n = len(s) + ans = '' + for i in range(n): + lower = upper = 0 + for j in range(i, n): + if s[j].islower(): + lower |= 1 << (ord(s[j]) - ord('a')) + else: + upper |= 1 << (ord(s[j]) - ord('A')) + if lower == upper and len(ans) < j - i + 1: + ans = s[i : j + 1] + return ans +``` + +```java +class Solution { + public String longestNiceSubstring(String s) { + int n = s.length(); + int k = -1; + int mx = 0; + for (int i = 0; i < n; ++i) { + int lower = 0, upper = 0; + for (int j = i; j < n; ++j) { + char c = s.charAt(j); + if (Character.isLowerCase(c)) { + lower |= 1 << (c - 'a'); + } else { + upper |= 1 << (c - 'A'); + } + if (lower == upper && mx < j - i + 1) { + mx = j - i + 1; + k = i; + } + } + } + return k == -1 ? "" : s.substring(k, k + mx); + } +} +``` +```cpp +class Solution { +public: + string longestNiceSubstring(string s) { + int n = s.size(); + int k = -1, mx = 0; + for (int i = 0; i < n; ++i) { + int lower = 0, upper = 0; + for (int j = i; j < n; ++j) { + char c = s[j]; + if (islower(c)) + lower |= 1 << (c - 'a'); + else + upper |= 1 << (c - 'A'); + if (lower == upper && mx < j - i + 1) { + mx = j - i + 1; + k = i; + } + } + } + return k == -1 ? "" : s.substr(k, mx); + } +}; ``` +```go +func longestNiceSubstring(s string) string { + n := len(s) + k, mx := -1, 0 + for i := 0; i < n; i++ { + var lower, upper int + for j := i; j < n; j++ { + if unicode.IsLower(rune(s[j])) { + lower |= 1 << (s[j] - 'a') + } else { + upper |= 1 << (s[j] - 'A') + } + if lower == upper && mx < j-i+1 { + mx = j - i + 1 + k = i + } + } + } + if k < 0 { + return "" + } + return s[k : k+mx] +} ``` + + diff --git a/solution/1700-1799/1764.Form Array by Concatenating Subarrays of Another Array/README.md b/solution/1700-1799/1764.Form Array by Concatenating Subarrays of Another Array/README.md index 1736a1080dc26..964a73030755f 100644 --- a/solution/1700-1799/1764.Form Array by Concatenating Subarrays of Another Array/README.md +++ b/solution/1700-1799/1764.Form Array by Concatenating Subarrays of Another Array/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:贪心枚举** +### 方法一:贪心枚举 我们贪心地枚举 `nums` 中每一个数 $nums[j]$ 作为子数组的开始,判断其是否与当前 $groups[i]$ 匹配,是则将指针 $i$ 往后移一位,将指针 $j$ 往后移动 $groups[i].length$ 位,否则将指针 $j$ 往后移动一位。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool: @@ -88,10 +82,6 @@ class Solution: return i == n ``` -### **Java** - - - ```java class Solution { public boolean canChoose(int[][] groups, int[] nums) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +140,6 @@ public: }; ``` -### **Go** - ```go func canChoose(groups [][]int, nums []int) bool { check := func(a, b []int, j int) bool { @@ -180,10 +166,6 @@ func canChoose(groups [][]int, nums []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1764.Form Array by Concatenating Subarrays of Another Array/README_EN.md b/solution/1700-1799/1764.Form Array by Concatenating Subarrays of Another Array/README_EN.md index cc41ed48761c2..9da167d9f1d57 100644 --- a/solution/1700-1799/1764.Form Array by Concatenating Subarrays of Another Array/README_EN.md +++ b/solution/1700-1799/1764.Form Array by Concatenating Subarrays of Another Array/README_EN.md @@ -53,9 +53,9 @@ They share a common elements nums[4] (0-indexed). ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return i == n ``` -### **Java** - ```java class Solution { public boolean canChoose(int[][] groups, int[] nums) { @@ -103,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +130,6 @@ public: }; ``` -### **Go** - ```go func canChoose(groups [][]int, nums []int) bool { check := func(a, b []int, j int) bool { @@ -162,10 +156,6 @@ func canChoose(groups [][]int, nums []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1765.Map of Highest Peak/README.md b/solution/1700-1799/1765.Map of Highest Peak/README.md index a3094eb792fe5..086eaf19abb33 100644 --- a/solution/1700-1799/1765.Map of Highest Peak/README.md +++ b/solution/1700-1799/1765.Map of Highest Peak/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 根据题目描述,水域的高度必须是 $0$,而任意相邻格子的高度差至多为 $1$。因此,我们可以从所有水域格子出发,用 BFS 搜索相邻且未访问过的格子,将其高度置为当前格子的高度再加一。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: @@ -100,32 +94,6 @@ class Solution: return ans ``` -```python -class Solution: - def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: - m, n = len(isWater), len(isWater[0]) - ans = [[-1] * n for _ in range(m)] - q = deque() - for i, row in enumerate(isWater): - for j, v in enumerate(row): - if v: - q.append((i, j)) - ans[i][j] = 0 - while q: - for _ in range(len(q)): - i, j = q.popleft() - for a, b in pairwise((-1, 0, 1, 0, -1)): - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n and ans[x][y] == -1: - ans[x][y] = ans[i][j] + 1 - q.append((x, y)) - return ans -``` - -### **Java** - - - ```java class Solution { public int[][] highestPeak(int[][] isWater) { @@ -157,41 +125,6 @@ class Solution { } ``` -```java -class Solution { - public int[][] highestPeak(int[][] isWater) { - int m = isWater.length, n = isWater[0].length; - int[][] ans = new int[m][n]; - Deque q = new ArrayDeque<>(); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - ans[i][j] = isWater[i][j] - 1; - if (ans[i][j] == 0) { - q.offer(new int[] {i, j}); - } - } - } - int[] dirs = {-1, 0, 1, 0, -1}; - while (!q.isEmpty()) { - for (int t = q.size(); t > 0; --t) { - var 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 < m && y >= 0 && y < n && ans[x][y] == -1) { - ans[x][y] = ans[i][j] + 1; - q.offer(new int[] {x, y}); - } - } - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -225,43 +158,71 @@ public: }; ``` -```cpp -class Solution { -public: - const int dirs[5] = {-1, 0, 1, 0, -1}; +```go +func highestPeak(isWater [][]int) [][]int { + m, n := len(isWater), len(isWater[0]) + ans := make([][]int, m) + type pair struct{ i, j int } + q := []pair{} + for i, row := range isWater { + ans[i] = make([]int, n) + for j, v := range row { + ans[i][j] = v - 1 + if v == 1 { + q = append(q, pair{i, j}) + } + } + } + dirs := []int{-1, 0, 1, 0, -1} + for len(q) > 0 { + p := q[0] + q = q[1:] + i, j := p.i, p.j + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1 { + ans[x][y] = ans[i][j] + 1 + q = append(q, pair{x, y}) + } + } + } + return ans +} +``` - vector> highestPeak(vector>& isWater) { - int m = isWater.size(), n = isWater[0].size(); - vector> ans(m, vector(n)); - queue> q; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - ans[i][j] = isWater[i][j] - 1; - if (ans[i][j] == 0) { - q.emplace(i, j); - } +```ts +function highestPeak(isWater: number[][]): number[][] { + const m = isWater.length; + const n = isWater[0].length; + let ans: number[][] = []; + let q: number[][] = []; + for (let i = 0; i < m; ++i) { + ans.push(new Array(n).fill(-1)); + for (let j = 0; j < n; ++j) { + if (isWater[i][j]) { + q.push([i, j]); + ans[i][j] = 0; } } - while (!q.empty()) { - for (int t = q.size(); t; --t) { - auto [i, j] = q.front(); - q.pop(); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1) { - ans[x][y] = ans[i][j] + 1; - q.emplace(x, y); - } + } + const dirs = [-1, 0, 1, 0, -1]; + while (q.length) { + let tq: number[][] = []; + for (const [i, j] of q) { + for (let k = 0; k < 4; k++) { + const [x, y] = [i + dirs[k], j + dirs[k + 1]]; + if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1) { + tq.push([x, y]); + ans[x][y] = ans[i][j] + 1; } } } - return ans; + q = tq; } -}; + return ans; +} ``` -### **Rust** - ```rust use std::collections::VecDeque; @@ -314,40 +275,102 @@ impl Solution { } ``` -### **Go** + -```go -func highestPeak(isWater [][]int) [][]int { - m, n := len(isWater), len(isWater[0]) - ans := make([][]int, m) - type pair struct{ i, j int } - q := []pair{} - for i, row := range isWater { - ans[i] = make([]int, n) - for j, v := range row { - ans[i][j] = v - 1 - if v == 1 { - q = append(q, pair{i, j}) - } - } - } - dirs := []int{-1, 0, 1, 0, -1} - for len(q) > 0 { - p := q[0] - q = q[1:] - i, j := p.i, p.j - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1 { - ans[x][y] = ans[i][j] + 1 - q = append(q, pair{x, y}) - } - } - } - return ans +### 方法二 + + + +```python +class Solution: + def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: + m, n = len(isWater), len(isWater[0]) + ans = [[-1] * n for _ in range(m)] + q = deque() + for i, row in enumerate(isWater): + for j, v in enumerate(row): + if v: + q.append((i, j)) + ans[i][j] = 0 + while q: + for _ in range(len(q)): + i, j = q.popleft() + for a, b in pairwise((-1, 0, 1, 0, -1)): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and ans[x][y] == -1: + ans[x][y] = ans[i][j] + 1 + q.append((x, y)) + return ans +``` + +```java +class Solution { + public int[][] highestPeak(int[][] isWater) { + int m = isWater.length, n = isWater[0].length; + int[][] ans = new int[m][n]; + Deque q = new ArrayDeque<>(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans[i][j] = isWater[i][j] - 1; + if (ans[i][j] == 0) { + q.offer(new int[] {i, j}); + } + } + } + int[] dirs = {-1, 0, 1, 0, -1}; + while (!q.isEmpty()) { + for (int t = q.size(); t > 0; --t) { + var 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 < m && y >= 0 && y < n && ans[x][y] == -1) { + ans[x][y] = ans[i][j] + 1; + q.offer(new int[] {x, y}); + } + } + } + } + return ans; + } } ``` +```cpp +class Solution { +public: + const int dirs[5] = {-1, 0, 1, 0, -1}; + + vector> highestPeak(vector>& isWater) { + int m = isWater.size(), n = isWater[0].size(); + vector> ans(m, vector(n)); + queue> q; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans[i][j] = isWater[i][j] - 1; + if (ans[i][j] == 0) { + q.emplace(i, j); + } + } + } + while (!q.empty()) { + for (int t = q.size(); t; --t) { + auto [i, j] = q.front(); + q.pop(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1) { + ans[x][y] = ans[i][j] + 1; + q.emplace(x, y); + } + } + } + } + return ans; + } +}; +``` + ```go func highestPeak(isWater [][]int) [][]int { m, n := len(isWater), len(isWater[0]) @@ -382,45 +405,6 @@ func highestPeak(isWater [][]int) [][]int { } ``` -### **TypeScript** - -```ts -function highestPeak(isWater: number[][]): number[][] { - const m = isWater.length; - const n = isWater[0].length; - let ans: number[][] = []; - let q: number[][] = []; - for (let i = 0; i < m; ++i) { - ans.push(new Array(n).fill(-1)); - for (let j = 0; j < n; ++j) { - if (isWater[i][j]) { - q.push([i, j]); - ans[i][j] = 0; - } - } - } - const dirs = [-1, 0, 1, 0, -1]; - while (q.length) { - let tq: number[][] = []; - for (const [i, j] of q) { - for (let k = 0; k < 4; k++) { - const [x, y] = [i + dirs[k], j + dirs[k + 1]]; - if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1) { - tq.push([x, y]); - ans[x][y] = ans[i][j] + 1; - } - } - } - q = tq; - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1765.Map of Highest Peak/README_EN.md b/solution/1700-1799/1765.Map of Highest Peak/README_EN.md index b6ccacf1cb27d..300c7ba461015 100644 --- a/solution/1700-1799/1765.Map of Highest Peak/README_EN.md +++ b/solution/1700-1799/1765.Map of Highest Peak/README_EN.md @@ -59,20 +59,10 @@ Any height assignment that has a maximum height of 2 while still meeting the rul ## Solutions -**Method One: Multi-Source BFS** - -Based on the problem description, the height of the water area must be $0$, and the height difference between any adjacent cells can be at most $1$. - -Therefore, we can start from all water cells, perform BFS to search for adjacent and unvisited cells, and set their heights to the height of the current cell plus one. - -Finally, return the resulting matrix. - -The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$, where $m$ and $n$ are the number of rows and columns in the integer matrix isWater, respectively. +### Solution 1 -### **Python3** - ```python class Solution: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: @@ -94,30 +84,6 @@ class Solution: return ans ``` -```python -class Solution: - def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: - m, n = len(isWater), len(isWater[0]) - ans = [[-1] * n for _ in range(m)] - q = deque() - for i, row in enumerate(isWater): - for j, v in enumerate(row): - if v: - q.append((i, j)) - ans[i][j] = 0 - while q: - for _ in range(len(q)): - i, j = q.popleft() - for a, b in pairwise((-1, 0, 1, 0, -1)): - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n and ans[x][y] == -1: - ans[x][y] = ans[i][j] + 1 - q.append((x, y)) - return ans -``` - -### **Java** - ```java class Solution { public int[][] highestPeak(int[][] isWater) { @@ -149,41 +115,6 @@ class Solution { } ``` -```java -class Solution { - public int[][] highestPeak(int[][] isWater) { - int m = isWater.length, n = isWater[0].length; - int[][] ans = new int[m][n]; - Deque q = new ArrayDeque<>(); - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - ans[i][j] = isWater[i][j] - 1; - if (ans[i][j] == 0) { - q.offer(new int[] {i, j}); - } - } - } - int[] dirs = {-1, 0, 1, 0, -1}; - while (!q.isEmpty()) { - for (int t = q.size(); t > 0; --t) { - var 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 < m && y >= 0 && y < n && ans[x][y] == -1) { - ans[x][y] = ans[i][j] + 1; - q.offer(new int[] {x, y}); - } - } - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -217,43 +148,71 @@ public: }; ``` -```cpp -class Solution { -public: - const int dirs[5] = {-1, 0, 1, 0, -1}; +```go +func highestPeak(isWater [][]int) [][]int { + m, n := len(isWater), len(isWater[0]) + ans := make([][]int, m) + type pair struct{ i, j int } + q := []pair{} + for i, row := range isWater { + ans[i] = make([]int, n) + for j, v := range row { + ans[i][j] = v - 1 + if v == 1 { + q = append(q, pair{i, j}) + } + } + } + dirs := []int{-1, 0, 1, 0, -1} + for len(q) > 0 { + p := q[0] + q = q[1:] + i, j := p.i, p.j + for k := 0; k < 4; k++ { + x, y := i+dirs[k], j+dirs[k+1] + if x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1 { + ans[x][y] = ans[i][j] + 1 + q = append(q, pair{x, y}) + } + } + } + return ans +} +``` - vector> highestPeak(vector>& isWater) { - int m = isWater.size(), n = isWater[0].size(); - vector> ans(m, vector(n)); - queue> q; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - ans[i][j] = isWater[i][j] - 1; - if (ans[i][j] == 0) { - q.emplace(i, j); - } +```ts +function highestPeak(isWater: number[][]): number[][] { + const m = isWater.length; + const n = isWater[0].length; + let ans: number[][] = []; + let q: number[][] = []; + for (let i = 0; i < m; ++i) { + ans.push(new Array(n).fill(-1)); + for (let j = 0; j < n; ++j) { + if (isWater[i][j]) { + q.push([i, j]); + ans[i][j] = 0; } } - while (!q.empty()) { - for (int t = q.size(); t; --t) { - auto [i, j] = q.front(); - q.pop(); - for (int k = 0; k < 4; ++k) { - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1) { - ans[x][y] = ans[i][j] + 1; - q.emplace(x, y); - } + } + const dirs = [-1, 0, 1, 0, -1]; + while (q.length) { + let tq: number[][] = []; + for (const [i, j] of q) { + for (let k = 0; k < 4; k++) { + const [x, y] = [i + dirs[k], j + dirs[k + 1]]; + if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1) { + tq.push([x, y]); + ans[x][y] = ans[i][j] + 1; } } } - return ans; + q = tq; } -}; + return ans; +} ``` -### **Rust** - ```rust use std::collections::VecDeque; @@ -306,40 +265,102 @@ impl Solution { } ``` -### **Go** + -```go -func highestPeak(isWater [][]int) [][]int { - m, n := len(isWater), len(isWater[0]) - ans := make([][]int, m) - type pair struct{ i, j int } - q := []pair{} - for i, row := range isWater { - ans[i] = make([]int, n) - for j, v := range row { - ans[i][j] = v - 1 - if v == 1 { - q = append(q, pair{i, j}) - } - } - } - dirs := []int{-1, 0, 1, 0, -1} - for len(q) > 0 { - p := q[0] - q = q[1:] - i, j := p.i, p.j - for k := 0; k < 4; k++ { - x, y := i+dirs[k], j+dirs[k+1] - if x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1 { - ans[x][y] = ans[i][j] + 1 - q = append(q, pair{x, y}) - } - } - } - return ans +### Solution 2 + + + +```python +class Solution: + def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: + m, n = len(isWater), len(isWater[0]) + ans = [[-1] * n for _ in range(m)] + q = deque() + for i, row in enumerate(isWater): + for j, v in enumerate(row): + if v: + q.append((i, j)) + ans[i][j] = 0 + while q: + for _ in range(len(q)): + i, j = q.popleft() + for a, b in pairwise((-1, 0, 1, 0, -1)): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and ans[x][y] == -1: + ans[x][y] = ans[i][j] + 1 + q.append((x, y)) + return ans +``` + +```java +class Solution { + public int[][] highestPeak(int[][] isWater) { + int m = isWater.length, n = isWater[0].length; + int[][] ans = new int[m][n]; + Deque q = new ArrayDeque<>(); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans[i][j] = isWater[i][j] - 1; + if (ans[i][j] == 0) { + q.offer(new int[] {i, j}); + } + } + } + int[] dirs = {-1, 0, 1, 0, -1}; + while (!q.isEmpty()) { + for (int t = q.size(); t > 0; --t) { + var 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 < m && y >= 0 && y < n && ans[x][y] == -1) { + ans[x][y] = ans[i][j] + 1; + q.offer(new int[] {x, y}); + } + } + } + } + return ans; + } } ``` +```cpp +class Solution { +public: + const int dirs[5] = {-1, 0, 1, 0, -1}; + + vector> highestPeak(vector>& isWater) { + int m = isWater.size(), n = isWater[0].size(); + vector> ans(m, vector(n)); + queue> q; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + ans[i][j] = isWater[i][j] - 1; + if (ans[i][j] == 0) { + q.emplace(i, j); + } + } + } + while (!q.empty()) { + for (int t = q.size(); t; --t) { + auto [i, j] = q.front(); + q.pop(); + for (int k = 0; k < 4; ++k) { + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1) { + ans[x][y] = ans[i][j] + 1; + q.emplace(x, y); + } + } + } + } + return ans; + } +}; +``` + ```go func highestPeak(isWater [][]int) [][]int { m, n := len(isWater), len(isWater[0]) @@ -374,45 +395,6 @@ func highestPeak(isWater [][]int) [][]int { } ``` -### **TypeScript** - -```ts -function highestPeak(isWater: number[][]): number[][] { - const m = isWater.length; - const n = isWater[0].length; - let ans: number[][] = []; - let q: number[][] = []; - for (let i = 0; i < m; ++i) { - ans.push(new Array(n).fill(-1)); - for (let j = 0; j < n; ++j) { - if (isWater[i][j]) { - q.push([i, j]); - ans[i][j] = 0; - } - } - } - const dirs = [-1, 0, 1, 0, -1]; - while (q.length) { - let tq: number[][] = []; - for (const [i, j] of q) { - for (let k = 0; k < 4; k++) { - const [x, y] = [i + dirs[k], j + dirs[k + 1]]; - if (x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1) { - tq.push([x, y]); - ans[x][y] = ans[i][j] + 1; - } - } - } - q = tq; - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1766.Tree of Coprimes/README.md b/solution/1700-1799/1766.Tree of Coprimes/README.md index b689eaebb822c..bf301637ce4ed 100644 --- a/solution/1700-1799/1766.Tree of Coprimes/README.md +++ b/solution/1700-1799/1766.Tree of Coprimes/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:预处理 + 枚举 + 栈 + 回溯** +### 方法一:预处理 + 枚举 + 栈 + 回溯 由于题目中 $nums[i]$ 的取值范围为 $[1, 50]$,因此我们可以预处理出每个数的所有互质数,记录在数组 $f$ 中,其中 $f[i]$ 表示 $i$ 的所有互质数。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]: @@ -104,10 +98,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -167,8 +157,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -214,8 +202,6 @@ public: }; ``` -### **Go** - ```go func getCoprimes(nums []int, edges [][]int) []int { n := len(nums) @@ -266,10 +252,6 @@ func gcd(a, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1766.Tree of Coprimes/README_EN.md b/solution/1700-1799/1766.Tree of Coprimes/README_EN.md index 69e080538b521..80f56858c3f20 100644 --- a/solution/1700-1799/1766.Tree of Coprimes/README_EN.md +++ b/solution/1700-1799/1766.Tree of Coprimes/README_EN.md @@ -55,9 +55,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -90,8 +90,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -151,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -198,8 +194,6 @@ public: }; ``` -### **Go** - ```go func getCoprimes(nums []int, edges [][]int) []int { n := len(nums) @@ -250,10 +244,6 @@ func gcd(a, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1767.Find the Subtasks That Did Not Execute/README.md b/solution/1700-1799/1767.Find the Subtasks That Did Not Execute/README.md index e8a93e429ea85..f00ce1f9ca20f 100644 --- a/solution/1700-1799/1767.Find the Subtasks That Did Not Execute/README.md +++ b/solution/1700-1799/1767.Find the Subtasks That Did Not Execute/README.md @@ -84,18 +84,12 @@ Task 3 被分成了 4 subtasks (1, 2, 3, 4)。所有的subtask都被成功执行 ## 解法 - - -**方法一:递归生成数据表 + 左连接** +### 方法一:递归生成数据表 + 左连接 我们可以通过递归生成一个数据表,该数据表包含了所有的(主任务,子任务)对,然后我们通过左连接找到没有被执行的(主任务,子任务)对。 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH RECURSIVE @@ -120,3 +114,5 @@ WHERE Executed.subtask_id IS NULL; ``` + + diff --git a/solution/1700-1799/1767.Find the Subtasks That Did Not Execute/README_EN.md b/solution/1700-1799/1767.Find the Subtasks That Did Not Execute/README_EN.md index 7228366af90ff..69d5a2359eb43 100644 --- a/solution/1700-1799/1767.Find the Subtasks That Did Not Execute/README_EN.md +++ b/solution/1700-1799/1767.Find the Subtasks That Did Not Execute/README_EN.md @@ -81,14 +81,12 @@ Task 3 was divided into 4 subtasks (1, 2, 3, 4). All of the subtasks were execut ## Solutions -**Solution 1: Recursive Table Generation + Left Join** +### Solution 1: Recursive Table Generation + Left Join We can generate a table recursively that contains all pairs of (parent task, child task), and then use a left join to find the pairs that have not been executed. -### **SQL** - ```sql # Write your MySQL query statement below WITH RECURSIVE @@ -113,3 +111,5 @@ WHERE Executed.subtask_id IS NULL; ``` + + diff --git a/solution/1700-1799/1768.Merge Strings Alternately/README.md b/solution/1700-1799/1768.Merge Strings Alternately/README.md index 410dce908a5e6..0ac735a00f6d8 100644 --- a/solution/1700-1799/1768.Merge Strings Alternately/README.md +++ b/solution/1700-1799/1768.Merge Strings Alternately/README.md @@ -56,9 +56,7 @@ word2: p q ## 解法 - - -**方法一:直接模拟** +### 方法一:直接模拟 我们遍历 `word1`, `word2` 两个字符串,依次取出字符,拼接到结果字符串中。Python 代码可以简化为一行。 @@ -66,20 +64,12 @@ word2: p q -### **Python3** - - - ```python class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: return ''.join(a + b for a, b in zip_longest(word1, word2, fillvalue='')) ``` -### **Java** - - - ```java class Solution { public String mergeAlternately(String word1, String word2) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func mergeAlternately(word1 string, word2 string) string { m, n := len(word1), len(word2) @@ -133,8 +119,6 @@ func mergeAlternately(word1 string, word2 string) string { } ``` -### **TypeScript** - ```ts function mergeAlternately(word1: string, word2: string): string { const ans: string[] = []; @@ -151,8 +135,6 @@ function mergeAlternately(word1: string, word2: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn merge_alternately(word1: String, word2: String) -> String { @@ -173,8 +155,6 @@ impl Solution { } ``` -### **C** - ```c char* mergeAlternately(char* word1, char* word2) { int m = strlen(word1); @@ -197,10 +177,6 @@ char* mergeAlternately(char* word1, char* word2) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1768.Merge Strings Alternately/README_EN.md b/solution/1700-1799/1768.Merge Strings Alternately/README_EN.md index 0dad35455e056..b0431d952eae9 100644 --- a/solution/1700-1799/1768.Merge Strings Alternately/README_EN.md +++ b/solution/1700-1799/1768.Merge Strings Alternately/README_EN.md @@ -52,7 +52,7 @@ merged: a p b q c d ## Solutions -**Solution 1: Direct Simulation** +### Solution 1: Direct Simulation We traverse the two strings `word1` and `word2`, take out the characters one by one, and append them to the result string. The Python code can be simplified into one line. @@ -60,16 +60,12 @@ The time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the two -### **Python3** - ```python class Solution: def mergeAlternately(self, word1: str, word2: str) -> str: return ''.join(a + b for a, b in zip_longest(word1, word2, fillvalue='')) ``` -### **Java** - ```java class Solution { public String mergeAlternately(String word1, String word2) { @@ -88,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +99,6 @@ public: }; ``` -### **Go** - ```go func mergeAlternately(word1 string, word2 string) string { m, n := len(word1), len(word2) @@ -123,8 +115,6 @@ func mergeAlternately(word1 string, word2 string) string { } ``` -### **TypeScript** - ```ts function mergeAlternately(word1: string, word2: string): string { const ans: string[] = []; @@ -141,8 +131,6 @@ function mergeAlternately(word1: string, word2: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn merge_alternately(word1: String, word2: String) -> String { @@ -163,8 +151,6 @@ impl Solution { } ``` -### **C** - ```c char* mergeAlternately(char* word1, char* word2) { int m = strlen(word1); @@ -187,10 +173,6 @@ char* mergeAlternately(char* word1, char* word2) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/README.md b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/README.md index 5f5f941f3963b..405b77c2223f6 100644 --- a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/README.md +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:预处理 + 枚举** +### 方法一:预处理 + 枚举 我们可以预处理出每个位置 $i$ 左边的小球移动到 $i$ 的操作数,记为 $left[i]$;每个位置 $i$ 右边的小球移动到 $i$ 的操作数,记为 $right[i]$。那么答案数组的第 $i$ 个元素就是 $left[i] + right[i]$。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, boxes: str) -> List[int]: @@ -80,29 +74,6 @@ class Solution: return [a + b for a, b in zip(left, right)] ``` -```python -class Solution: - def minOperations(self, boxes: str) -> List[int]: - n = len(boxes) - ans = [0] * n - cnt = 0 - for i in range(1, n): - if boxes[i - 1] == '1': - cnt += 1 - ans[i] = ans[i - 1] + cnt - cnt = s = 0 - for i in range(n - 2, -1, -1): - if boxes[i + 1] == '1': - cnt += 1 - s += cnt - ans[i] += s - return ans -``` - -### **Java** - - - ```java class Solution { public int[] minOperations(String boxes) { @@ -130,31 +101,6 @@ class Solution { } ``` -```java -class Solution { - public int[] minOperations(String boxes) { - int n = boxes.length(); - int[] ans = new int[n]; - for (int i = 1, cnt = 0; i < n; ++i) { - if (boxes.charAt(i - 1) == '1') { - ++cnt; - } - ans[i] = ans[i - 1] + cnt; - } - for (int i = n - 2, cnt = 0, s = 0; i >= 0; --i) { - if (boxes.charAt(i + 1) == '1') { - ++cnt; - } - s += cnt; - ans[i] += s; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -179,28 +125,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector minOperations(string boxes) { - int n = boxes.size(); - vector ans(n); - for (int i = 1, cnt = 0; i < n; ++i) { - cnt += boxes[i - 1] == '1'; - ans[i] = ans[i - 1] + cnt; - } - for (int i = n - 2, cnt = 0, s = 0; ~i; --i) { - cnt += boxes[i + 1] == '1'; - s += cnt; - ans[i] += s; - } - return ans; - } -}; -``` - -### **Go** - ```go func minOperations(boxes string) []int { n := len(boxes) @@ -226,29 +150,6 @@ func minOperations(boxes string) []int { } ``` -```go -func minOperations(boxes string) []int { - n := len(boxes) - ans := make([]int, n) - for i, cnt := 1, 0; i < n; i++ { - if boxes[i-1] == '1' { - cnt++ - } - ans[i] = ans[i-1] + cnt - } - for i, cnt, s := n-2, 0, 0; i >= 0; i-- { - if boxes[i+1] == '1' { - cnt++ - } - s += cnt - ans[i] += s - } - return ans -} -``` - -### **TypeScript** - ```ts function minOperations(boxes: string): number[] { const n = boxes.length; @@ -270,29 +171,6 @@ function minOperations(boxes: string): number[] { } ``` -```ts -function minOperations(boxes: string): number[] { - const n = boxes.length; - const ans = new Array(n).fill(0); - for (let i = 1, count = 0; i < n; i++) { - if (boxes[i - 1] === '1') { - count++; - } - ans[i] = ans[i - 1] + count; - } - for (let i = n - 2, count = 0, sum = 0; i >= 0; i--) { - if (boxes[i + 1] === '1') { - count++; - } - sum += count; - ans[i] += sum; - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn min_operations(boxes: String) -> Vec { @@ -322,35 +200,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn min_operations(boxes: String) -> Vec { - let s = boxes.as_bytes(); - let n = s.len(); - let mut ans = vec![0; n]; - let mut count = 0; - for i in 1..n { - if s[i - 1] == b'1' { - count += 1; - } - ans[i] = ans[i - 1] + count; - } - let mut sum = 0; - count = 0; - for i in (0..n - 1).rev() { - if s[i + 1] == b'1' { - count += 1; - } - sum += count; - ans[i] += sum; - } - ans - } -} -``` - -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -384,6 +233,143 @@ int* minOperations(char* boxes, int* returnSize) { } ``` + + +### 方法二 + + + +```python +class Solution: + def minOperations(self, boxes: str) -> List[int]: + n = len(boxes) + ans = [0] * n + cnt = 0 + for i in range(1, n): + if boxes[i - 1] == '1': + cnt += 1 + ans[i] = ans[i - 1] + cnt + cnt = s = 0 + for i in range(n - 2, -1, -1): + if boxes[i + 1] == '1': + cnt += 1 + s += cnt + ans[i] += s + return ans +``` + +```java +class Solution { + public int[] minOperations(String boxes) { + int n = boxes.length(); + int[] ans = new int[n]; + for (int i = 1, cnt = 0; i < n; ++i) { + if (boxes.charAt(i - 1) == '1') { + ++cnt; + } + ans[i] = ans[i - 1] + cnt; + } + for (int i = n - 2, cnt = 0, s = 0; i >= 0; --i) { + if (boxes.charAt(i + 1) == '1') { + ++cnt; + } + s += cnt; + ans[i] += s; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector minOperations(string boxes) { + int n = boxes.size(); + vector ans(n); + for (int i = 1, cnt = 0; i < n; ++i) { + cnt += boxes[i - 1] == '1'; + ans[i] = ans[i - 1] + cnt; + } + for (int i = n - 2, cnt = 0, s = 0; ~i; --i) { + cnt += boxes[i + 1] == '1'; + s += cnt; + ans[i] += s; + } + return ans; + } +}; +``` + +```go +func minOperations(boxes string) []int { + n := len(boxes) + ans := make([]int, n) + for i, cnt := 1, 0; i < n; i++ { + if boxes[i-1] == '1' { + cnt++ + } + ans[i] = ans[i-1] + cnt + } + for i, cnt, s := n-2, 0, 0; i >= 0; i-- { + if boxes[i+1] == '1' { + cnt++ + } + s += cnt + ans[i] += s + } + return ans +} +``` + +```ts +function minOperations(boxes: string): number[] { + const n = boxes.length; + const ans = new Array(n).fill(0); + for (let i = 1, count = 0; i < n; i++) { + if (boxes[i - 1] === '1') { + count++; + } + ans[i] = ans[i - 1] + count; + } + for (let i = n - 2, count = 0, sum = 0; i >= 0; i--) { + if (boxes[i + 1] === '1') { + count++; + } + sum += count; + ans[i] += sum; + } + return ans; +} +``` + +```rust +impl Solution { + pub fn min_operations(boxes: String) -> Vec { + let s = boxes.as_bytes(); + let n = s.len(); + let mut ans = vec![0; n]; + let mut count = 0; + for i in 1..n { + if s[i - 1] == b'1' { + count += 1; + } + ans[i] = ans[i - 1] + count; + } + let mut sum = 0; + count = 0; + for i in (0..n - 1).rev() { + if s[i + 1] == b'1' { + count += 1; + } + sum += count; + ans[i] += sum; + } + ans + } +} +``` + ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -410,10 +396,6 @@ int* minOperations(char* boxes, int* returnSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/README_EN.md b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/README_EN.md index 14511624f2ec9..30dc7174d23f3 100644 --- a/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/README_EN.md +++ b/solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,27 +64,6 @@ class Solution: return [a + b for a, b in zip(left, right)] ``` -```python -class Solution: - def minOperations(self, boxes: str) -> List[int]: - n = len(boxes) - ans = [0] * n - cnt = 0 - for i in range(1, n): - if boxes[i - 1] == '1': - cnt += 1 - ans[i] = ans[i - 1] + cnt - cnt = s = 0 - for i in range(n - 2, -1, -1): - if boxes[i + 1] == '1': - cnt += 1 - s += cnt - ans[i] += s - return ans -``` - -### **Java** - ```java class Solution { public int[] minOperations(String boxes) { @@ -112,31 +91,6 @@ class Solution { } ``` -```java -class Solution { - public int[] minOperations(String boxes) { - int n = boxes.length(); - int[] ans = new int[n]; - for (int i = 1, cnt = 0; i < n; ++i) { - if (boxes.charAt(i - 1) == '1') { - ++cnt; - } - ans[i] = ans[i - 1] + cnt; - } - for (int i = n - 2, cnt = 0, s = 0; i >= 0; --i) { - if (boxes.charAt(i + 1) == '1') { - ++cnt; - } - s += cnt; - ans[i] += s; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -161,28 +115,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector minOperations(string boxes) { - int n = boxes.size(); - vector ans(n); - for (int i = 1, cnt = 0; i < n; ++i) { - cnt += boxes[i - 1] == '1'; - ans[i] = ans[i - 1] + cnt; - } - for (int i = n - 2, cnt = 0, s = 0; ~i; --i) { - cnt += boxes[i + 1] == '1'; - s += cnt; - ans[i] += s; - } - return ans; - } -}; -``` - -### **Go** - ```go func minOperations(boxes string) []int { n := len(boxes) @@ -208,29 +140,6 @@ func minOperations(boxes string) []int { } ``` -```go -func minOperations(boxes string) []int { - n := len(boxes) - ans := make([]int, n) - for i, cnt := 1, 0; i < n; i++ { - if boxes[i-1] == '1' { - cnt++ - } - ans[i] = ans[i-1] + cnt - } - for i, cnt, s := n-2, 0, 0; i >= 0; i-- { - if boxes[i+1] == '1' { - cnt++ - } - s += cnt - ans[i] += s - } - return ans -} -``` - -### **TypeScript** - ```ts function minOperations(boxes: string): number[] { const n = boxes.length; @@ -252,29 +161,6 @@ function minOperations(boxes: string): number[] { } ``` -```ts -function minOperations(boxes: string): number[] { - const n = boxes.length; - const ans = new Array(n).fill(0); - for (let i = 1, count = 0; i < n; i++) { - if (boxes[i - 1] === '1') { - count++; - } - ans[i] = ans[i - 1] + count; - } - for (let i = n - 2, count = 0, sum = 0; i >= 0; i--) { - if (boxes[i + 1] === '1') { - count++; - } - sum += count; - ans[i] += sum; - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn min_operations(boxes: String) -> Vec { @@ -304,35 +190,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn min_operations(boxes: String) -> Vec { - let s = boxes.as_bytes(); - let n = s.len(); - let mut ans = vec![0; n]; - let mut count = 0; - for i in 1..n { - if s[i - 1] == b'1' { - count += 1; - } - ans[i] = ans[i - 1] + count; - } - let mut sum = 0; - count = 0; - for i in (0..n - 1).rev() { - if s[i + 1] == b'1' { - count += 1; - } - sum += count; - ans[i] += sum; - } - ans - } -} -``` - -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -366,6 +223,143 @@ int* minOperations(char* boxes, int* returnSize) { } ``` + + +### Solution 2 + + + +```python +class Solution: + def minOperations(self, boxes: str) -> List[int]: + n = len(boxes) + ans = [0] * n + cnt = 0 + for i in range(1, n): + if boxes[i - 1] == '1': + cnt += 1 + ans[i] = ans[i - 1] + cnt + cnt = s = 0 + for i in range(n - 2, -1, -1): + if boxes[i + 1] == '1': + cnt += 1 + s += cnt + ans[i] += s + return ans +``` + +```java +class Solution { + public int[] minOperations(String boxes) { + int n = boxes.length(); + int[] ans = new int[n]; + for (int i = 1, cnt = 0; i < n; ++i) { + if (boxes.charAt(i - 1) == '1') { + ++cnt; + } + ans[i] = ans[i - 1] + cnt; + } + for (int i = n - 2, cnt = 0, s = 0; i >= 0; --i) { + if (boxes.charAt(i + 1) == '1') { + ++cnt; + } + s += cnt; + ans[i] += s; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector minOperations(string boxes) { + int n = boxes.size(); + vector ans(n); + for (int i = 1, cnt = 0; i < n; ++i) { + cnt += boxes[i - 1] == '1'; + ans[i] = ans[i - 1] + cnt; + } + for (int i = n - 2, cnt = 0, s = 0; ~i; --i) { + cnt += boxes[i + 1] == '1'; + s += cnt; + ans[i] += s; + } + return ans; + } +}; +``` + +```go +func minOperations(boxes string) []int { + n := len(boxes) + ans := make([]int, n) + for i, cnt := 1, 0; i < n; i++ { + if boxes[i-1] == '1' { + cnt++ + } + ans[i] = ans[i-1] + cnt + } + for i, cnt, s := n-2, 0, 0; i >= 0; i-- { + if boxes[i+1] == '1' { + cnt++ + } + s += cnt + ans[i] += s + } + return ans +} +``` + +```ts +function minOperations(boxes: string): number[] { + const n = boxes.length; + const ans = new Array(n).fill(0); + for (let i = 1, count = 0; i < n; i++) { + if (boxes[i - 1] === '1') { + count++; + } + ans[i] = ans[i - 1] + count; + } + for (let i = n - 2, count = 0, sum = 0; i >= 0; i--) { + if (boxes[i + 1] === '1') { + count++; + } + sum += count; + ans[i] += sum; + } + return ans; +} +``` + +```rust +impl Solution { + pub fn min_operations(boxes: String) -> Vec { + let s = boxes.as_bytes(); + let n = s.len(); + let mut ans = vec![0; n]; + let mut count = 0; + for i in 1..n { + if s[i - 1] == b'1' { + count += 1; + } + ans[i] = ans[i - 1] + count; + } + let mut sum = 0; + count = 0; + for i in (0..n - 1).rev() { + if s[i + 1] == b'1' { + count += 1; + } + sum += count; + ans[i] += sum; + } + ans + } +} +``` + ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -392,10 +386,6 @@ int* minOperations(char* boxes, int* returnSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/README.md b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/README.md index 894fae9a20381..7285882b77d81 100644 --- a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/README.md +++ b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j)$,表示从 `nums` 数组头部第 $i$ 个元素开始,从 `nums` 数组尾部第 $j$ 个元素开始,能够获得的最大分数。那么答案就是 $dfs(0, 0)$。 @@ -72,24 +70,8 @@ 时间复杂度 $O(m^2)$,空间复杂度 $O(m^2)$。其中 $m$ 为 `multipliers` 数组的长度。 -**方法二:动态规划** - -我们可以将方法一中的记忆化搜索改写为动态规划的形式。 - -我们用 $f[i][j]$ 表示取数组 $nums$ 的前 $i$ 个元素,以及取数组 $nums$ 的后 $j$ 个元素,能够获得的最大分数。初始时 $f[0][0] = 0$,其余元素均为 $-\infty$。答案为 $\max_{0 \leq i \leq m} f[i][m-i]$。 - -考虑 $f[i][j]$,那么当前我们可以选择 `nums` 数组头部的第 $i$ 个元素,或者选择 `nums` 数组尾部的第 $j$ 个元素。如果选择了 `nums` 数组头部的第 $i$ 个元素,那么能够获得的最大分数为 $f[i-1][j] + nums[i-1] \times multipliers[i+j-1]$;如果选择了 `nums` 数组尾部的第 $j$ 个元素,那么能够获得的最大分数为 $f[i][j-1] + nums[n-j] \times multipliers[i+j-1]$。我们取两者的最大值作为 $f[i][j]$ 的值。如果 $i + j = m$,我们我们更新答案 $ans = \max(ans, f[i][j])$。 - -最后返回答案 $ans$ 即可。 - -时间复杂度 $O(m^2)$,空间复杂度 $O(m^2)$。其中 $m$ 为 `multipliers` 数组的长度。 - -### **Python3** - - - ```python class Solution: def maximumScore(self, nums: List[int], multipliers: List[int]) -> int: @@ -106,29 +88,6 @@ class Solution: return f(0, n - 1, 0) ``` -```python -class Solution: - def maximumScore(self, nums: List[int], multipliers: List[int]) -> int: - n, m = len(nums), len(multipliers) - f = [[-inf] * (m + 1) for _ in range(m + 1)] - f[0][0] = 0 - ans = -inf - for i in range(m + 1): - for j in range(m - i + 1): - k = i + j - 1 - if i > 0: - f[i][j] = max(f[i][j], f[i - 1][j] + multipliers[k] * nums[i - 1]) - if j > 0: - f[i][j] = max(f[i][j], f[i][j - 1] + multipliers[k] * nums[n - j]) - if i + j == m: - ans = max(ans, f[i][j]) - return ans -``` - -### **Java** - - - ```java class Solution { private Integer[][] f; @@ -162,6 +121,115 @@ class Solution { } ``` +```cpp +class Solution { +public: + int maximumScore(vector& nums, vector& multipliers) { + int n = nums.size(), m = multipliers.size(); + int f[m][m]; + memset(f, 0x3f, sizeof f); + function dfs = [&](int i, int j) -> int { + if (i >= m || j >= m || (i + j) >= m) return 0; + if (f[i][j] != 0x3f3f3f3f) return f[i][j]; + int k = i + j; + int a = dfs(i + 1, j) + nums[i] * multipliers[k]; + int b = dfs(i, j + 1) + nums[n - j - 1] * multipliers[k]; + return f[i][j] = max(a, b); + }; + return dfs(0, 0); + } +}; +``` + +```go +func maximumScore(nums []int, multipliers []int) int { + n, m := len(nums), len(multipliers) + f := make([][]int, m) + for i := range f { + f[i] = make([]int, m) + for j := range f[i] { + f[i][j] = 1 << 30 + } + } + var dfs func(i, j int) int + dfs = func(i, j int) int { + if i >= m || j >= m || i+j >= m { + return 0 + } + if f[i][j] != 1<<30 { + return f[i][j] + } + k := i + j + a := dfs(i+1, j) + nums[i]*multipliers[k] + b := dfs(i, j+1) + nums[n-j-1]*multipliers[k] + f[i][j] = max(a, b) + return f[i][j] + } + return dfs(0, 0) +} +``` + +```ts +function maximumScore(nums: number[], multipliers: number[]): number { + const inf = 1 << 30; + const n = nums.length; + const m = multipliers.length; + const f = new Array(m + 1).fill(0).map(() => new Array(m + 1).fill(-inf)); + f[0][0] = 0; + let ans = -inf; + for (let i = 0; i <= m; ++i) { + for (let j = 0; j <= m - i; ++j) { + const k = i + j - 1; + if (i > 0) { + f[i][j] = Math.max(f[i][j], f[i - 1][j] + nums[i - 1] * multipliers[k]); + } + if (j > 0) { + f[i][j] = Math.max(f[i][j], f[i][j - 1] + nums[n - j] * multipliers[k]); + } + if (i + j === m) { + ans = Math.max(ans, f[i][j]); + } + } + } + return ans; +} +``` + + + +### 方法二:动态规划 + +我们可以将方法一中的记忆化搜索改写为动态规划的形式。 + +我们用 $f[i][j]$ 表示取数组 $nums$ 的前 $i$ 个元素,以及取数组 $nums$ 的后 $j$ 个元素,能够获得的最大分数。初始时 $f[0][0] = 0$,其余元素均为 $-\infty$。答案为 $\max_{0 \leq i \leq m} f[i][m-i]$。 + +考虑 $f[i][j]$,那么当前我们可以选择 `nums` 数组头部的第 $i$ 个元素,或者选择 `nums` 数组尾部的第 $j$ 个元素。如果选择了 `nums` 数组头部的第 $i$ 个元素,那么能够获得的最大分数为 $f[i-1][j] + nums[i-1] \times multipliers[i+j-1]$;如果选择了 `nums` 数组尾部的第 $j$ 个元素,那么能够获得的最大分数为 $f[i][j-1] + nums[n-j] \times multipliers[i+j-1]$。我们取两者的最大值作为 $f[i][j]$ 的值。如果 $i + j = m$,我们我们更新答案 $ans = \max(ans, f[i][j])$。 + +最后返回答案 $ans$ 即可。 + +时间复杂度 $O(m^2)$,空间复杂度 $O(m^2)$。其中 $m$ 为 `multipliers` 数组的长度。 + + + +```python +class Solution: + def maximumScore(self, nums: List[int], multipliers: List[int]) -> int: + n, m = len(nums), len(multipliers) + f = [[-inf] * (m + 1) for _ in range(m + 1)] + f[0][0] = 0 + ans = -inf + for i in range(m + 1): + for j in range(m - i + 1): + k = i + j - 1 + if i > 0: + f[i][j] = max(f[i][j], f[i - 1][j] + multipliers[k] * nums[i - 1]) + if j > 0: + f[i][j] = max(f[i][j], f[i][j - 1] + multipliers[k] * nums[n - j]) + if i + j == m: + ans = max(ans, f[i][j]) + return ans +``` + ```java class Solution { public int maximumScore(int[] nums, int[] multipliers) { @@ -192,28 +260,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maximumScore(vector& nums, vector& multipliers) { - int n = nums.size(), m = multipliers.size(); - int f[m][m]; - memset(f, 0x3f, sizeof f); - function dfs = [&](int i, int j) -> int { - if (i >= m || j >= m || (i + j) >= m) return 0; - if (f[i][j] != 0x3f3f3f3f) return f[i][j]; - int k = i + j; - int a = dfs(i + 1, j) + nums[i] * multipliers[k]; - int b = dfs(i, j + 1) + nums[n - j - 1] * multipliers[k]; - return f[i][j] = max(a, b); - }; - return dfs(0, 0); - } -}; -``` - ```cpp class Solution { public: @@ -242,36 +288,6 @@ public: }; ``` -### **Go** - -```go -func maximumScore(nums []int, multipliers []int) int { - n, m := len(nums), len(multipliers) - f := make([][]int, m) - for i := range f { - f[i] = make([]int, m) - for j := range f[i] { - f[i][j] = 1 << 30 - } - } - var dfs func(i, j int) int - dfs = func(i, j int) int { - if i >= m || j >= m || i+j >= m { - return 0 - } - if f[i][j] != 1<<30 { - return f[i][j] - } - k := i + j - a := dfs(i+1, j) + nums[i]*multipliers[k] - b := dfs(i, j+1) + nums[n-j-1]*multipliers[k] - f[i][j] = max(a, b) - return f[i][j] - } - return dfs(0, 0) -} -``` - ```go func maximumScore(nums []int, multipliers []int) int { const inf int = 1 << 30 @@ -303,38 +319,6 @@ func maximumScore(nums []int, multipliers []int) int { } ``` -### **TypeScript** - -```ts -function maximumScore(nums: number[], multipliers: number[]): number { - const inf = 1 << 30; - const n = nums.length; - const m = multipliers.length; - const f = new Array(m + 1).fill(0).map(() => new Array(m + 1).fill(-inf)); - f[0][0] = 0; - let ans = -inf; - for (let i = 0; i <= m; ++i) { - for (let j = 0; j <= m - i; ++j) { - const k = i + j - 1; - if (i > 0) { - f[i][j] = Math.max(f[i][j], f[i - 1][j] + nums[i - 1] * multipliers[k]); - } - if (j > 0) { - f[i][j] = Math.max(f[i][j], f[i][j - 1] + nums[n - j] * multipliers[k]); - } - if (i + j === m) { - ans = Math.max(ans, f[i][j]); - } - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/README_EN.md b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/README_EN.md index 6eb62cbd78072..8e14b8ad66478 100644 --- a/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/README_EN.md +++ b/solution/1700-1799/1770.Maximum Score from Performing Multiplication Operations/README_EN.md @@ -59,9 +59,9 @@ The total score is 50 + 15 - 9 + 4 + 42 = 102. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,27 +79,6 @@ class Solution: return f(0, n - 1, 0) ``` -```python -class Solution: - def maximumScore(self, nums: List[int], multipliers: List[int]) -> int: - n, m = len(nums), len(multipliers) - f = [[-inf] * (m + 1) for _ in range(m + 1)] - f[0][0] = 0 - ans = -inf - for i in range(m + 1): - for j in range(m - i + 1): - k = i + j - 1 - if i > 0: - f[i][j] = max(f[i][j], f[i - 1][j] + multipliers[k] * nums[i - 1]) - if j > 0: - f[i][j] = max(f[i][j], f[i][j - 1] + multipliers[k] * nums[n - j]) - if i + j == m: - ans = max(ans, f[i][j]) - return ans -``` - -### **Java** - ```java class Solution { private Integer[][] f; @@ -133,6 +112,105 @@ class Solution { } ``` +```cpp +class Solution { +public: + int maximumScore(vector& nums, vector& multipliers) { + int n = nums.size(), m = multipliers.size(); + int f[m][m]; + memset(f, 0x3f, sizeof f); + function dfs = [&](int i, int j) -> int { + if (i >= m || j >= m || (i + j) >= m) return 0; + if (f[i][j] != 0x3f3f3f3f) return f[i][j]; + int k = i + j; + int a = dfs(i + 1, j) + nums[i] * multipliers[k]; + int b = dfs(i, j + 1) + nums[n - j - 1] * multipliers[k]; + return f[i][j] = max(a, b); + }; + return dfs(0, 0); + } +}; +``` + +```go +func maximumScore(nums []int, multipliers []int) int { + n, m := len(nums), len(multipliers) + f := make([][]int, m) + for i := range f { + f[i] = make([]int, m) + for j := range f[i] { + f[i][j] = 1 << 30 + } + } + var dfs func(i, j int) int + dfs = func(i, j int) int { + if i >= m || j >= m || i+j >= m { + return 0 + } + if f[i][j] != 1<<30 { + return f[i][j] + } + k := i + j + a := dfs(i+1, j) + nums[i]*multipliers[k] + b := dfs(i, j+1) + nums[n-j-1]*multipliers[k] + f[i][j] = max(a, b) + return f[i][j] + } + return dfs(0, 0) +} +``` + +```ts +function maximumScore(nums: number[], multipliers: number[]): number { + const inf = 1 << 30; + const n = nums.length; + const m = multipliers.length; + const f = new Array(m + 1).fill(0).map(() => new Array(m + 1).fill(-inf)); + f[0][0] = 0; + let ans = -inf; + for (let i = 0; i <= m; ++i) { + for (let j = 0; j <= m - i; ++j) { + const k = i + j - 1; + if (i > 0) { + f[i][j] = Math.max(f[i][j], f[i - 1][j] + nums[i - 1] * multipliers[k]); + } + if (j > 0) { + f[i][j] = Math.max(f[i][j], f[i][j - 1] + nums[n - j] * multipliers[k]); + } + if (i + j === m) { + ans = Math.max(ans, f[i][j]); + } + } + } + return ans; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def maximumScore(self, nums: List[int], multipliers: List[int]) -> int: + n, m = len(nums), len(multipliers) + f = [[-inf] * (m + 1) for _ in range(m + 1)] + f[0][0] = 0 + ans = -inf + for i in range(m + 1): + for j in range(m - i + 1): + k = i + j - 1 + if i > 0: + f[i][j] = max(f[i][j], f[i - 1][j] + multipliers[k] * nums[i - 1]) + if j > 0: + f[i][j] = max(f[i][j], f[i][j - 1] + multipliers[k] * nums[n - j]) + if i + j == m: + ans = max(ans, f[i][j]) + return ans +``` + ```java class Solution { public int maximumScore(int[] nums, int[] multipliers) { @@ -163,28 +241,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maximumScore(vector& nums, vector& multipliers) { - int n = nums.size(), m = multipliers.size(); - int f[m][m]; - memset(f, 0x3f, sizeof f); - function dfs = [&](int i, int j) -> int { - if (i >= m || j >= m || (i + j) >= m) return 0; - if (f[i][j] != 0x3f3f3f3f) return f[i][j]; - int k = i + j; - int a = dfs(i + 1, j) + nums[i] * multipliers[k]; - int b = dfs(i, j + 1) + nums[n - j - 1] * multipliers[k]; - return f[i][j] = max(a, b); - }; - return dfs(0, 0); - } -}; -``` - ```cpp class Solution { public: @@ -213,36 +269,6 @@ public: }; ``` -### **Go** - -```go -func maximumScore(nums []int, multipliers []int) int { - n, m := len(nums), len(multipliers) - f := make([][]int, m) - for i := range f { - f[i] = make([]int, m) - for j := range f[i] { - f[i][j] = 1 << 30 - } - } - var dfs func(i, j int) int - dfs = func(i, j int) int { - if i >= m || j >= m || i+j >= m { - return 0 - } - if f[i][j] != 1<<30 { - return f[i][j] - } - k := i + j - a := dfs(i+1, j) + nums[i]*multipliers[k] - b := dfs(i, j+1) + nums[n-j-1]*multipliers[k] - f[i][j] = max(a, b) - return f[i][j] - } - return dfs(0, 0) -} -``` - ```go func maximumScore(nums []int, multipliers []int) int { const inf int = 1 << 30 @@ -274,38 +300,6 @@ func maximumScore(nums []int, multipliers []int) int { } ``` -### **TypeScript** - -```ts -function maximumScore(nums: number[], multipliers: number[]): number { - const inf = 1 << 30; - const n = nums.length; - const m = multipliers.length; - const f = new Array(m + 1).fill(0).map(() => new Array(m + 1).fill(-inf)); - f[0][0] = 0; - let ans = -inf; - for (let i = 0; i <= m; ++i) { - for (let j = 0; j <= m - i; ++j) { - const k = i + j - 1; - if (i > 0) { - f[i][j] = Math.max(f[i][j], f[i - 1][j] + nums[i - 1] * multipliers[k]); - } - if (j > 0) { - f[i][j] = Math.max(f[i][j], f[i][j - 1] + nums[n - j] * multipliers[k]); - } - if (i + j === m) { - ans = Math.max(ans, f[i][j]); - } - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README.md b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README.md index 6ea9e375205e8..0878a6dd40221 100644 --- a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README.md +++ b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们首先将字符串 `word1` 和 `word2` 连接起来,得到字符串 $s$,然后我们可以将问题转化为求字符串 $s$ 的最长回文子序列的长度。只不过这里在算最后的答案时,需要保证回文字符串中,至少有一个字符来自 `word1`,另一个字符来自 `word2`。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def longestPalindrome(self, word1: str, word2: str) -> int: @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestPalindrome(String word1, String word2) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func longestPalindrome(word1 string, word2 string) (ans int) { s := word1 + word2 @@ -180,8 +166,6 @@ func longestPalindrome(word1 string, word2 string) (ans int) { } ``` -### **TypeScript** - ```ts function longestPalindrome(word1: string, word2: string): number { const s = word1 + word2; @@ -207,8 +191,6 @@ function longestPalindrome(word1: string, word2: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn longest_palindrome(word1: String, word2: String) -> i32 { @@ -236,10 +218,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md index 729f1e7db4d42..5810b494ec9ad 100644 --- a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md +++ b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md @@ -50,7 +50,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming First, we concatenate strings `word1` and `word2` to get string $s$. Then we can transform the problem into finding the length of the longest palindromic subsequence in string $s$. However, when calculating the final answer, we need to ensure that at least one character in the palindrome string comes from `word1` and another character comes from `word2`. @@ -66,8 +66,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ -### **Python3** - ```python class Solution: def longestPalindrome(self, word1: str, word2: str) -> int: @@ -88,8 +86,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestPalindrome(String word1, String word2) { @@ -117,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +140,6 @@ public: }; ``` -### **Go** - ```go func longestPalindrome(word1 string, word2 string) (ans int) { s := word1 + word2 @@ -173,8 +165,6 @@ func longestPalindrome(word1 string, word2 string) (ans int) { } ``` -### **TypeScript** - ```ts function longestPalindrome(word1: string, word2: string): number { const s = word1 + word2; @@ -200,8 +190,6 @@ function longestPalindrome(word1: string, word2: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn longest_palindrome(word1: String, word2: String) -> i32 { @@ -229,10 +217,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1772.Sort Features by Popularity/README.md b/solution/1700-1799/1772.Sort Features by Popularity/README.md index 762b662cc1fd7..ff8e63fab3e84 100644 --- a/solution/1700-1799/1772.Sort Features by Popularity/README.md +++ b/solution/1700-1799/1772.Sort Features by Popularity/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:哈希表 + 自定义排序** +### 方法一:哈希表 + 自定义排序 我们遍历 `responses`,对于 `responses[i]` 中的每个单词,我们用一个哈希表 `vis` 暂存。接下来将 `vis` 中的单词记录到哈希表 `cnt` 中,记录每个单词出现的次数。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]: @@ -73,10 +67,6 @@ class Solution: return sorted(features, key=lambda w: -cnt[w]) ``` -### **Java** - - - ```java class Solution { public String[] sortFeatures(String[] features, String[] responses) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func sortFeatures(features []string, responses []string) []string { cnt := map[string]int{} @@ -161,8 +147,6 @@ func sortFeatures(features []string, responses []string) []string { } ``` -### **TypeScript** - ```ts function sortFeatures(features: string[], responses: string[]): string[] { const cnt: Map = new Map(); @@ -187,10 +171,6 @@ function sortFeatures(features: string[], responses: string[]): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1772.Sort Features by Popularity/README_EN.md b/solution/1700-1799/1772.Sort Features by Popularity/README_EN.md index d8849be99f6b0..f4727b201b530 100644 --- a/solution/1700-1799/1772.Sort Features by Popularity/README_EN.md +++ b/solution/1700-1799/1772.Sort Features by Popularity/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Hash Table + Custom Sorting** +### Solution 1: Hash Table + Custom Sorting We traverse `responses`, and for each word in `responses[i]`, we temporarily store it in a hash table `vis`. Next, we record the words in `vis` into the hash table `cnt`, recording the number of times each word appears. @@ -53,8 +53,6 @@ The time complexity is $O(n \times \log n)$, where $n$ is the length of `feature -### **Python3** - ```python class Solution: def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]: @@ -65,8 +63,6 @@ class Solution: return sorted(features, key=lambda w: -cnt[w]) ``` -### **Java** - ```java class Solution { public String[] sortFeatures(String[] features, String[] responses) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +126,6 @@ public: }; ``` -### **Go** - ```go func sortFeatures(features []string, responses []string) []string { cnt := map[string]int{} @@ -151,8 +143,6 @@ func sortFeatures(features []string, responses []string) []string { } ``` -### **TypeScript** - ```ts function sortFeatures(features: string[], responses: string[]): string[] { const cnt: Map = new Map(); @@ -177,10 +167,6 @@ function sortFeatures(features: string[], responses: string[]): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1773.Count Items Matching a Rule/README.md b/solution/1700-1799/1773.Count Items Matching a Rule/README.md index 4b2f781d620ed..a1e53c8892047 100644 --- a/solution/1700-1799/1773.Count Items Matching a Rule/README.md +++ b/solution/1700-1799/1773.Count Items Matching a Rule/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:计数模拟** +### 方法一:计数模拟 由于 `ruleKey` 只可能是 `"type"`、`"color"` 或 `"name"`,我们可以直接取 `ruleKey` 的第一个字符来确定 `item` 的下标 $i$。然后遍历 `items` 数组,统计 `item[i] == ruleValue` 的个数即可。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int: @@ -71,10 +65,6 @@ class Solution: return sum(v[i] == ruleValue for v in items) ``` -### **Java** - - - ```java class Solution { public int countMatches(List> items, String ruleKey, String ruleValue) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +90,6 @@ public: }; ``` -### **Go** - ```go func countMatches(items [][]string, ruleKey string, ruleValue string) (ans int) { i := map[byte]int{'t': 0, 'c': 1, 'n': 2}[ruleKey[0]] @@ -116,24 +102,6 @@ func countMatches(items [][]string, ruleKey string, ruleValue string) (ans int) } ``` -### **C** - -```c -int countMatches(char*** items, int itemsSize, int* itemsColSize, char* ruleKey, char* ruleValue) { - int k = strcmp(ruleKey, "type") == 0 ? 0 : strcmp(ruleKey, "color") == 0 ? 1 - : 2; - int res = 0; - for (int i = 0; i < itemsSize; i++) { - if (strcmp(items[i][k], ruleValue) == 0) { - res++; - } - } - return res; -} -``` - -### **TypeScript** - ```ts function countMatches(items: string[][], ruleKey: string, ruleValue: string): number { const key = ruleKey === 'type' ? 0 : ruleKey === 'color' ? 1 : 2; @@ -141,8 +109,6 @@ function countMatches(items: string[][], ruleKey: string, ruleValue: string): nu } ``` -### **Rust** - ```rust impl Solution { pub fn count_matches(items: Vec>, rule_key: String, rule_value: String) -> i32 { @@ -155,10 +121,20 @@ impl Solution { } ``` -### **...** - -``` - +```c +int countMatches(char*** items, int itemsSize, int* itemsColSize, char* ruleKey, char* ruleValue) { + int k = strcmp(ruleKey, "type") == 0 ? 0 : strcmp(ruleKey, "color") == 0 ? 1 + : 2; + int res = 0; + for (int i = 0; i < itemsSize; i++) { + if (strcmp(items[i][k], ruleValue) == 0) { + res++; + } + } + return res; +} ``` + + diff --git a/solution/1700-1799/1773.Count Items Matching a Rule/README_EN.md b/solution/1700-1799/1773.Count Items Matching a Rule/README_EN.md index 6857c0eb8c49d..45efe308c1a3d 100644 --- a/solution/1700-1799/1773.Count Items Matching a Rule/README_EN.md +++ b/solution/1700-1799/1773.Count Items Matching a Rule/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return sum(v[i] == ruleValue for v in items) ``` -### **Java** - ```java class Solution { public int countMatches(List> items, String ruleKey, String ruleValue) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -84,8 +80,6 @@ public: }; ``` -### **Go** - ```go func countMatches(items [][]string, ruleKey string, ruleValue string) (ans int) { i := map[byte]int{'t': 0, 'c': 1, 'n': 2}[ruleKey[0]] @@ -98,24 +92,6 @@ func countMatches(items [][]string, ruleKey string, ruleValue string) (ans int) } ``` -### **C** - -```c -int countMatches(char*** items, int itemsSize, int* itemsColSize, char* ruleKey, char* ruleValue) { - int k = strcmp(ruleKey, "type") == 0 ? 0 : strcmp(ruleKey, "color") == 0 ? 1 - : 2; - int res = 0; - for (int i = 0; i < itemsSize; i++) { - if (strcmp(items[i][k], ruleValue) == 0) { - res++; - } - } - return res; -} -``` - -### **TypeScript** - ```ts function countMatches(items: string[][], ruleKey: string, ruleValue: string): number { const key = ruleKey === 'type' ? 0 : ruleKey === 'color' ? 1 : 2; @@ -123,8 +99,6 @@ function countMatches(items: string[][], ruleKey: string, ruleValue: string): nu } ``` -### **Rust** - ```rust impl Solution { pub fn count_matches(items: Vec>, rule_key: String, rule_value: String) -> i32 { @@ -137,10 +111,20 @@ impl Solution { } ``` -### **...** - -``` - +```c +int countMatches(char*** items, int itemsSize, int* itemsColSize, char* ruleKey, char* ruleValue) { + int k = strcmp(ruleKey, "type") == 0 ? 0 : strcmp(ruleKey, "color") == 0 ? 1 + : 2; + int res = 0; + for (int i = 0; i < itemsSize; i++) { + if (strcmp(items[i][k], ruleValue) == 0) { + res++; + } + } + return res; +} ``` + + diff --git a/solution/1700-1799/1774.Closest Dessert Cost/README.md b/solution/1700-1799/1774.Closest Dessert Cost/README.md index f364493c8ec56..880855fd29193 100644 --- a/solution/1700-1799/1774.Closest Dessert Cost/README.md +++ b/solution/1700-1799/1774.Closest Dessert Cost/README.md @@ -82,9 +82,7 @@ ## 解法 - - -**方法一:枚举子集和 + 排序 + 二分查找** +### 方法一:枚举子集和 + 排序 + 二分查找 每种类型的配料最多可以选两份,因此,我们可以复制一份配料,然后利用 `DFS` 枚举子集之和。在实现上,我们可以只枚举一半的配料的所有子集和,然后在另一半配料子集和中,利用二分查找找到最接近的配料。 @@ -94,10 +92,6 @@ -### **Python3** - - - ```python class Solution: def closestCost( @@ -130,10 +124,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List arr = new ArrayList<>(); @@ -190,8 +180,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -231,8 +219,6 @@ public: }; ``` -### **Go** - ```go func closestCost(baseCosts []int, toppingCosts []int, target int) int { arr := []int{} @@ -277,8 +263,6 @@ func abs(x int) int { } ``` -### **JavaScript** - ```js const closestCost = function (baseCosts, toppingCosts, target) { let closestDessertCost = -Infinity; @@ -303,10 +287,6 @@ const closestCost = function (baseCosts, toppingCosts, target) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1774.Closest Dessert Cost/README_EN.md b/solution/1700-1799/1774.Closest Dessert Cost/README_EN.md index 0851b86ca71be..c69821e8dc2cc 100644 --- a/solution/1700-1799/1774.Closest Dessert Cost/README_EN.md +++ b/solution/1700-1799/1774.Closest Dessert Cost/README_EN.md @@ -71,9 +71,9 @@ Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -91,8 +91,12 @@ class Solution: dfs(0, 0) arr.sort() d = ans = inf + + # 选择一种冰激淋基料 for x in baseCosts: + # 枚举子集和 for y in arr: + # 二分查找 i = bisect_left(arr, target - x - y) for j in (i, i - 1): if 0 <= j < len(arr): @@ -103,8 +107,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List arr = new ArrayList<>(); @@ -116,8 +118,12 @@ class Solution { dfs(0, 0); Collections.sort(arr); int d = inf, ans = inf; + + // 选择一种冰激淋基料 for (int x : baseCosts) { + // 枚举子集和 for (int y : arr) { + // 二分查找 int i = search(target - x - y); for (int j : new int[] {i, i - 1}) { if (j >= 0 && j < arr.size()) { @@ -157,8 +163,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +180,11 @@ public: dfs(0, 0); sort(arr.begin(), arr.end()); int d = inf, ans = inf; + // 选择一种冰激淋基料 for (int x : baseCosts) { + // 枚举子集和 for (int y : arr) { + // 二分查找 int i = lower_bound(arr.begin(), arr.end(), target - x - y) - arr.begin(); for (int j = i - 1; j < i + 1; ++j) { if (j >= 0 && j < arr.size()) { @@ -195,8 +202,6 @@ public: }; ``` -### **Go** - ```go func closestCost(baseCosts []int, toppingCosts []int, target int) int { arr := []int{} @@ -213,8 +218,11 @@ func closestCost(baseCosts []int, toppingCosts []int, target int) int { sort.Ints(arr) const inf = 1 << 30 ans, d := inf, inf + // 选择一种冰激淋基料 for _, x := range baseCosts { + // 枚举子集和 for _, y := range arr { + // 二分查找 i := sort.SearchInts(arr, target-x-y) for j := i - 1; j < i+1; j++ { if j >= 0 && j < len(arr) { @@ -238,8 +246,6 @@ func abs(x int) int { } ``` -### **JavaScript** - ```js const closestCost = function (baseCosts, toppingCosts, target) { let closestDessertCost = -Infinity; @@ -264,10 +270,6 @@ const closestCost = function (baseCosts, toppingCosts, target) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1774.Closest Dessert Cost/Solution.js b/solution/1700-1799/1774.Closest Dessert Cost/Solution.js new file mode 100644 index 0000000000000..9751d45676c5e --- /dev/null +++ b/solution/1700-1799/1774.Closest Dessert Cost/Solution.js @@ -0,0 +1,21 @@ +const closestCost = function (baseCosts, toppingCosts, target) { + let closestDessertCost = -Infinity; + function dfs(dessertCost, j) { + const tarCurrDiff = Math.abs(target - dessertCost); + const tarCloseDiff = Math.abs(target - closestDessertCost); + if (tarCurrDiff < tarCloseDiff) { + closestDessertCost = dessertCost; + } else if (tarCurrDiff === tarCloseDiff && dessertCost < closestDessertCost) { + closestDessertCost = dessertCost; + } + if (dessertCost > target) return; + if (j === toppingCosts.length) return; + for (let count = 0; count <= 2; count++) { + dfs(dessertCost + count * toppingCosts[j], j + 1); + } + } + for (let i = 0; i < baseCosts.length; i++) { + dfs(baseCosts[i], 0); + } + return closestDessertCost; +}; diff --git a/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/README.md b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/README.md index 4459be40f0b2d..9e393d27e75cf 100644 --- a/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/README.md +++ b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 我们用 $s_1$ 和 $s_2$ 分别表示数组 `nums1` 和 `nums2` 的和。 @@ -72,20 +70,8 @@ 时间复杂度 $O((m+n) \times \log (m + n))$,空间复杂度 $O(m+n)$。其中 $m$ 和 $n$ 分别为数组 `nums1` 和 `nums2` 的长度。 -**方法二:贪心 + 计数排序** - -方法一中,我们需要创建数组 `arr` 并进行排序,时空复杂度较高。由于数组 `arr` 中元素的范围为 $[0,..5]$,因此我们创建一个长度为 $6$ 的数组 `cnt`,用于统计数组 `arr` 中每个元素的数量,也即每个最大变化量的元素的数量。 - -接下来,我们从最大变化量 $i=5$ 开始,贪心地将 $d$ 减去最大变化量,直到 $d \leq 0$,返回此时的操作次数即可。 - -时间复杂度 $O(m+n)$,空间复杂度 $O(C)$。其中 $m$ 和 $n$ 分别为数组 `nums1` 和 `nums2` 的长度。本题中 $C=6$。 - -### **Python3** - - - ```python class Solution: def minOperations(self, nums1: List[int], nums2: List[int]) -> int: @@ -103,29 +89,6 @@ class Solution: return -1 ``` -```python -class Solution: - def minOperations(self, nums1: List[int], nums2: List[int]) -> int: - s1, s2 = sum(nums1), sum(nums2) - if s1 == s2: - return 0 - if s1 > s2: - return self.minOperations(nums2, nums1) - cnt = Counter([6 - v for v in nums1] + [v - 1 for v in nums2]) - d = s2 - s1 - ans = 0 - for i in range(5, 0, -1): - while cnt[i] and d > 0: - d -= i - cnt[i] -= 1 - ans += 1 - return ans if d <= 0 else -1 -``` - -### **Java** - - - ```java class Solution { public int minOperations(int[] nums1, int[] nums2) { @@ -158,40 +121,6 @@ class Solution { } ``` -```java -class Solution { - public int minOperations(int[] nums1, int[] nums2) { - int s1 = Arrays.stream(nums1).sum(); - int s2 = Arrays.stream(nums2).sum(); - if (s1 == s2) { - return 0; - } - if (s1 > s2) { - return minOperations(nums2, nums1); - } - int d = s2 - s1; - int[] cnt = new int[6]; - for (int v : nums1) { - ++cnt[6 - v]; - } - for (int v : nums2) { - ++cnt[v - 1]; - } - int ans = 0; - for (int i = 5; i > 0; --i) { - while (cnt[i] > 0 && d > 0) { - d -= i; - --cnt[i]; - ++ans; - } - } - return d <= 0 ? ans : -1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -215,33 +144,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minOperations(vector& nums1, vector& nums2) { - int s1 = accumulate(nums1.begin(), nums1.end(), 0); - int s2 = accumulate(nums2.begin(), nums2.end(), 0); - if (s1 == s2) return 0; - if (s1 > s2) return minOperations(nums2, nums1); - int d = s2 - s1; - int cnt[6] = {0}; - for (int& v : nums1) ++cnt[6 - v]; - for (int& v : nums2) ++cnt[v - 1]; - int ans = 0; - for (int i = 5; i; --i) { - while (cnt[i] && d > 0) { - d -= i; - --cnt[i]; - ++ans; - } - } - return d <= 0 ? ans : -1; - } -}; -``` - -### **Go** - ```go func minOperations(nums1 []int, nums2 []int) int { s1, s2 := sum(nums1), sum(nums2) @@ -277,6 +179,94 @@ func sum(nums []int) (s int) { } ``` + + +### 方法二:贪心 + 计数排序 + +方法一中,我们需要创建数组 `arr` 并进行排序,时空复杂度较高。由于数组 `arr` 中元素的范围为 $[0,..5]$,因此我们创建一个长度为 $6$ 的数组 `cnt`,用于统计数组 `arr` 中每个元素的数量,也即每个最大变化量的元素的数量。 + +接下来,我们从最大变化量 $i=5$ 开始,贪心地将 $d$ 减去最大变化量,直到 $d \leq 0$,返回此时的操作次数即可。 + +时间复杂度 $O(m+n)$,空间复杂度 $O(C)$。其中 $m$ 和 $n$ 分别为数组 `nums1` 和 `nums2` 的长度。本题中 $C=6$。 + + + +```python +class Solution: + def minOperations(self, nums1: List[int], nums2: List[int]) -> int: + s1, s2 = sum(nums1), sum(nums2) + if s1 == s2: + return 0 + if s1 > s2: + return self.minOperations(nums2, nums1) + cnt = Counter([6 - v for v in nums1] + [v - 1 for v in nums2]) + d = s2 - s1 + ans = 0 + for i in range(5, 0, -1): + while cnt[i] and d > 0: + d -= i + cnt[i] -= 1 + ans += 1 + return ans if d <= 0 else -1 +``` + +```java +class Solution { + public int minOperations(int[] nums1, int[] nums2) { + int s1 = Arrays.stream(nums1).sum(); + int s2 = Arrays.stream(nums2).sum(); + if (s1 == s2) { + return 0; + } + if (s1 > s2) { + return minOperations(nums2, nums1); + } + int d = s2 - s1; + int[] cnt = new int[6]; + for (int v : nums1) { + ++cnt[6 - v]; + } + for (int v : nums2) { + ++cnt[v - 1]; + } + int ans = 0; + for (int i = 5; i > 0; --i) { + while (cnt[i] > 0 && d > 0) { + d -= i; + --cnt[i]; + ++ans; + } + } + return d <= 0 ? ans : -1; + } +} +``` + +```cpp +class Solution { +public: + int minOperations(vector& nums1, vector& nums2) { + int s1 = accumulate(nums1.begin(), nums1.end(), 0); + int s2 = accumulate(nums2.begin(), nums2.end(), 0); + if (s1 == s2) return 0; + if (s1 > s2) return minOperations(nums2, nums1); + int d = s2 - s1; + int cnt[6] = {0}; + for (int& v : nums1) ++cnt[6 - v]; + for (int& v : nums2) ++cnt[v - 1]; + int ans = 0; + for (int i = 5; i; --i) { + while (cnt[i] && d > 0) { + d -= i; + --cnt[i]; + ++ans; + } + } + return d <= 0 ? ans : -1; + } +}; +``` + ```go func minOperations(nums1 []int, nums2 []int) (ans int) { s1, s2 := sum(nums1), sum(nums2) @@ -315,10 +305,6 @@ func sum(nums []int) (s int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/README_EN.md b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/README_EN.md index a4affea5c5bfa..6a28393bf0b48 100644 --- a/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/README_EN.md +++ b/solution/1700-1799/1775.Equal Sum Arrays With Minimum Number of Operations/README_EN.md @@ -51,9 +51,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,27 +72,6 @@ class Solution: return -1 ``` -```python -class Solution: - def minOperations(self, nums1: List[int], nums2: List[int]) -> int: - s1, s2 = sum(nums1), sum(nums2) - if s1 == s2: - return 0 - if s1 > s2: - return self.minOperations(nums2, nums1) - cnt = Counter([6 - v for v in nums1] + [v - 1 for v in nums2]) - d = s2 - s1 - ans = 0 - for i in range(5, 0, -1): - while cnt[i] and d > 0: - d -= i - cnt[i] -= 1 - ans += 1 - return ans if d <= 0 else -1 -``` - -### **Java** - ```java class Solution { public int minOperations(int[] nums1, int[] nums2) { @@ -125,40 +104,6 @@ class Solution { } ``` -```java -class Solution { - public int minOperations(int[] nums1, int[] nums2) { - int s1 = Arrays.stream(nums1).sum(); - int s2 = Arrays.stream(nums2).sum(); - if (s1 == s2) { - return 0; - } - if (s1 > s2) { - return minOperations(nums2, nums1); - } - int d = s2 - s1; - int[] cnt = new int[6]; - for (int v : nums1) { - ++cnt[6 - v]; - } - for (int v : nums2) { - ++cnt[v - 1]; - } - int ans = 0; - for (int i = 5; i > 0; --i) { - while (cnt[i] > 0 && d > 0) { - d -= i; - --cnt[i]; - ++ans; - } - } - return d <= 0 ? ans : -1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -182,33 +127,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minOperations(vector& nums1, vector& nums2) { - int s1 = accumulate(nums1.begin(), nums1.end(), 0); - int s2 = accumulate(nums2.begin(), nums2.end(), 0); - if (s1 == s2) return 0; - if (s1 > s2) return minOperations(nums2, nums1); - int d = s2 - s1; - int cnt[6] = {0}; - for (int& v : nums1) ++cnt[6 - v]; - for (int& v : nums2) ++cnt[v - 1]; - int ans = 0; - for (int i = 5; i; --i) { - while (cnt[i] && d > 0) { - d -= i; - --cnt[i]; - ++ans; - } - } - return d <= 0 ? ans : -1; - } -}; -``` - -### **Go** - ```go func minOperations(nums1 []int, nums2 []int) int { s1, s2 := sum(nums1), sum(nums2) @@ -244,6 +162,88 @@ func sum(nums []int) (s int) { } ``` + + +### Solution 2 + + + +```python +class Solution: + def minOperations(self, nums1: List[int], nums2: List[int]) -> int: + s1, s2 = sum(nums1), sum(nums2) + if s1 == s2: + return 0 + if s1 > s2: + return self.minOperations(nums2, nums1) + cnt = Counter([6 - v for v in nums1] + [v - 1 for v in nums2]) + d = s2 - s1 + ans = 0 + for i in range(5, 0, -1): + while cnt[i] and d > 0: + d -= i + cnt[i] -= 1 + ans += 1 + return ans if d <= 0 else -1 +``` + +```java +class Solution { + public int minOperations(int[] nums1, int[] nums2) { + int s1 = Arrays.stream(nums1).sum(); + int s2 = Arrays.stream(nums2).sum(); + if (s1 == s2) { + return 0; + } + if (s1 > s2) { + return minOperations(nums2, nums1); + } + int d = s2 - s1; + int[] cnt = new int[6]; + for (int v : nums1) { + ++cnt[6 - v]; + } + for (int v : nums2) { + ++cnt[v - 1]; + } + int ans = 0; + for (int i = 5; i > 0; --i) { + while (cnt[i] > 0 && d > 0) { + d -= i; + --cnt[i]; + ++ans; + } + } + return d <= 0 ? ans : -1; + } +} +``` + +```cpp +class Solution { +public: + int minOperations(vector& nums1, vector& nums2) { + int s1 = accumulate(nums1.begin(), nums1.end(), 0); + int s2 = accumulate(nums2.begin(), nums2.end(), 0); + if (s1 == s2) return 0; + if (s1 > s2) return minOperations(nums2, nums1); + int d = s2 - s1; + int cnt[6] = {0}; + for (int& v : nums1) ++cnt[6 - v]; + for (int& v : nums2) ++cnt[v - 1]; + int ans = 0; + for (int i = 5; i; --i) { + while (cnt[i] && d > 0) { + d -= i; + --cnt[i]; + ++ans; + } + } + return d <= 0 ? ans : -1; + } +}; +``` + ```go func minOperations(nums1 []int, nums2 []int) (ans int) { s1, s2 := sum(nums1), sum(nums2) @@ -282,10 +282,6 @@ func sum(nums []int) (s int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1776.Car Fleet II/README.md b/solution/1700-1799/1776.Car Fleet II/README.md index 025274e4d95d2..3dbcf4c177006 100644 --- a/solution/1700-1799/1776.Car Fleet II/README.md +++ b/solution/1700-1799/1776.Car Fleet II/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 由于每一辆车最终追上其右边第一辆车的时间与其左边的车没有关系,因此,我们可以从右往左遍历,计算每辆车与其右边第一辆车相遇的时间。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def getCollisionTimes(self, cars: List[List[int]]) -> List[float]: @@ -85,10 +79,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public double[] getCollisionTimes(int[][] cars) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func getCollisionTimes(cars [][]int) []float64 { n := len(cars) @@ -171,10 +157,6 @@ func getCollisionTimes(cars [][]int) []float64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1776.Car Fleet II/README_EN.md b/solution/1700-1799/1776.Car Fleet II/README_EN.md index 063bf82f80d8e..ddabf0ba3c310 100644 --- a/solution/1700-1799/1776.Car Fleet II/README_EN.md +++ b/solution/1700-1799/1776.Car Fleet II/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public double[] getCollisionTimes(int[][] cars) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +117,6 @@ public: }; ``` -### **Go** - ```go func getCollisionTimes(cars [][]int) []float64 { n := len(cars) @@ -149,10 +143,6 @@ func getCollisionTimes(cars [][]int) []float64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1777.Product's Price for Each Store/README.md b/solution/1700-1799/1777.Product's Price for Each Store/README.md index 8c7760293afd9..b9e48aff25412 100644 --- a/solution/1700-1799/1777.Product's Price for Each Store/README.md +++ b/solution/1700-1799/1777.Product's Price for Each Store/README.md @@ -58,12 +58,10 @@ Products 表: ## 解法 - +### 方法一 -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -76,3 +74,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1700-1799/1777.Product's Price for Each Store/README_EN.md b/solution/1700-1799/1777.Product's Price for Each Store/README_EN.md index 4c38925df5131..dc153b94dd042 100644 --- a/solution/1700-1799/1777.Product's Price for Each Store/README_EN.md +++ b/solution/1700-1799/1777.Product's Price for Each Store/README_EN.md @@ -56,9 +56,9 @@ Product 1 price's are 70 for store1, 80 for store3 and, it's not sold in ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -72,3 +72,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README.md b/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README.md index 9bc5ec30c9ab8..733b2aefbad55 100644 --- a/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README.md +++ b/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README.md @@ -88,9 +88,7 @@ The robot is initially standing on cell (1, 0), denoted by the -1. ## 解法 - - -**方法一:DFS 建图 + BFS 求最短路** +### 方法一:DFS 建图 + BFS 求最短路 我们不妨假设机器人从坐标 $(0, 0)$ 出发,那么我们可以通过 DFS,找到所有可达的坐标,记录在哈希表 $vis$ 中。另外,我们还需要记录终点的坐标 $target$。 @@ -104,10 +102,6 @@ The robot is initially standing on cell (1, 0), denoted by the -1. -### **Python3** - - - ```python # """ # This is GridMaster's API interface. @@ -164,10 +158,6 @@ class Solution(object): return -1 ``` -### **Java** - - - ```java /** * // This is the GridMaster's API interface. @@ -230,8 +220,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the GridMaster's API interface. @@ -299,10 +287,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README_EN.md b/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README_EN.md index 4bac1d9e7321f..2261565c57087 100644 --- a/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README_EN.md +++ b/solution/1700-1799/1778.Shortest Path in a Hidden Grid/README_EN.md @@ -86,7 +86,7 @@ We now know that the target is the cell (0, 1), and the shortest path to the tar ## Solutions -**Solution 1: DFS for Graph Construction + BFS for Shortest Path** +### Solution 1: DFS for Graph Construction + BFS for Shortest Path We can assume that the robot starts from the coordinate $(0, 0)$. Then, we can use DFS to find all reachable coordinates and record them in the hash table $vis$. In addition, we also need to record the coordinates of the endpoint $target$. @@ -100,8 +100,6 @@ Similar problems: -### **Python3** - ```python # """ # This is GridMaster's API interface. @@ -158,8 +156,6 @@ class Solution(object): return -1 ``` -### **Java** - ```java /** * // This is the GridMaster's API interface. @@ -222,8 +218,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * // This is the GridMaster's API interface. @@ -291,10 +285,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/README.md b/solution/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/README.md index 785baa7c3a063..5de71dfee2d2a 100644 --- a/solution/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/README.md +++ b/solution/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:直接遍历** +### 方法一:直接遍历 直接遍历 `points` 数组,对于 $points[i]$,如果 $points[i][0] = x$ 或者 $points[i][1] = y$,则说明 $points[i]$ 是有效点,计算曼哈顿距离,更新最小距离和最小距离的下标。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int: @@ -73,10 +67,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int nearestValidPoint(int x, int y, int[][] points) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func nearestValidPoint(x int, y int, points [][]int) int { ans, mi := -1, 1000000 @@ -143,8 +129,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function nearestValidPoint(x: number, y: number, points: number[][]): number { let res = -1; @@ -163,8 +147,6 @@ function nearestValidPoint(x: number, y: number, points: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn nearest_valid_point(x: i32, y: i32, points: Vec>) -> i32 { @@ -187,8 +169,6 @@ impl Solution { } ``` -### **C** - ```c int nearestValidPoint(int x, int y, int** points, int pointsSize, int* pointsColSize) { int ans = -1; @@ -208,10 +188,6 @@ int nearestValidPoint(int x, int y, int** points, int pointsSize, int* pointsCol } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/README_EN.md b/solution/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/README_EN.md index fe630779a23d4..97bf49996e19c 100644 --- a/solution/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/README_EN.md +++ b/solution/1700-1799/1779.Find Nearest Point That Has the Same X or Y Coordinate/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int nearestValidPoint(int x, int y, int[][] points) { @@ -80,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +98,6 @@ public: }; ``` -### **Go** - ```go func nearestValidPoint(x int, y int, points [][]int) int { ans, mi := -1, 1000000 @@ -127,8 +121,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function nearestValidPoint(x: number, y: number, points: number[][]): number { let res = -1; @@ -147,8 +139,6 @@ function nearestValidPoint(x: number, y: number, points: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn nearest_valid_point(x: i32, y: i32, points: Vec>) -> i32 { @@ -171,8 +161,6 @@ impl Solution { } ``` -### **C** - ```c int nearestValidPoint(int x, int y, int** points, int pointsSize, int* pointsColSize) { int ans = -1; @@ -192,10 +180,6 @@ int nearestValidPoint(int x, int y, int** points, int pointsSize, int* pointsCol } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1780.Check if Number is a Sum of Powers of Three/README.md b/solution/1700-1799/1780.Check if Number is a Sum of Powers of Three/README.md index 0b0b9e844b557..44ee939ee28a2 100644 --- a/solution/1700-1799/1780.Check if Number is a Sum of Powers of Three/README.md +++ b/solution/1700-1799/1780.Check if Number is a Sum of Powers of Three/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:数学分析** +### 方法一:数学分析 我们发现,如果一个数 $n$ 可以表示成若干个“不同的”三的幂之和,那么 $n$ 的三进制表示中,每一位上的数字只能是 $0$ 或者 $1$。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def checkPowersOfThree(self, n: int) -> bool: @@ -68,10 +62,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean checkPowersOfThree(int n) { @@ -86,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +89,6 @@ public: }; ``` -### **Go** - ```go func checkPowersOfThree(n int) bool { for n > 0 { @@ -115,8 +101,6 @@ func checkPowersOfThree(n int) bool { } ``` -### **TypeScript** - ```ts function checkPowersOfThree(n: number): boolean { while (n) { @@ -127,10 +111,6 @@ function checkPowersOfThree(n: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1780.Check if Number is a Sum of Powers of Three/README_EN.md b/solution/1700-1799/1780.Check if Number is a Sum of Powers of Three/README_EN.md index a05658d952279..52e1b4ef6c44d 100644 --- a/solution/1700-1799/1780.Check if Number is a Sum of Powers of Three/README_EN.md +++ b/solution/1700-1799/1780.Check if Number is a Sum of Powers of Three/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean checkPowersOfThree(int n) { @@ -71,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -86,8 +82,6 @@ public: }; ``` -### **Go** - ```go func checkPowersOfThree(n int) bool { for n > 0 { @@ -100,8 +94,6 @@ func checkPowersOfThree(n int) bool { } ``` -### **TypeScript** - ```ts function checkPowersOfThree(n: number): boolean { while (n) { @@ -112,10 +104,6 @@ function checkPowersOfThree(n: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1781.Sum of Beauty of All Substrings/README.md b/solution/1700-1799/1781.Sum of Beauty of All Substrings/README.md index c0257d3ab4de6..9a97a232c117d 100644 --- a/solution/1700-1799/1781.Sum of Beauty of All Substrings/README.md +++ b/solution/1700-1799/1781.Sum of Beauty of All Substrings/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:枚举 + 计数** +### 方法一:枚举 + 计数 枚举每个子串的起点位置 $i$,找到以该起点位置的字符为左端点的所有子串,然后计算每个子串的美丽值,累加到答案中。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def beautySum(self, s: str) -> int: @@ -67,34 +61,6 @@ class Solution: return ans ``` -```python -class Solution: - def beautySum(self, s: str) -> int: - ans, n = 0, len(s) - for i in range(n): - cnt = Counter() - freq = Counter() - mi = mx = 1 - for j in range(i, n): - freq[cnt[s[j]]] -= 1 - cnt[s[j]] += 1 - freq[cnt[s[j]]] += 1 - - if cnt[s[j]] == 1: - mi = 1 - if freq[mi] == 0: - mi += 1 - if cnt[s[j]] > mx: - mx = cnt[s[j]] - - ans += mx - mi - return ans -``` - -### **Java** - - - ```java class Solution { public int beautySum(String s) { @@ -119,6 +85,105 @@ class Solution { } ``` +```cpp +class Solution { +public: + int beautySum(string s) { + int ans = 0; + int n = s.size(); + int cnt[26]; + for (int i = 0; i < n; ++i) { + memset(cnt, 0, sizeof cnt); + for (int j = i; j < n; ++j) { + ++cnt[s[j] - 'a']; + int mi = 1000, mx = 0; + for (int& v : cnt) { + if (v > 0) { + mi = min(mi, v); + mx = max(mx, v); + } + } + ans += mx - mi; + } + } + return ans; + } +}; +``` + +```go +func beautySum(s string) (ans int) { + for i := range s { + cnt := [26]int{} + for j := i; j < len(s); j++ { + cnt[s[j]-'a']++ + mi, mx := 1000, 0 + for _, v := range cnt { + if v > 0 { + if mi > v { + mi = v + } + if mx < v { + mx = v + } + } + } + ans += mx - mi + } + } + return +} +``` + +```js +/** + * @param {string} s + * @return {number} + */ +var beautySum = function (s) { + let ans = 0; + for (let i = 0; i < s.length; ++i) { + const cnt = new Map(); + for (let j = i; j < s.length; ++j) { + cnt.set(s[j], (cnt.get(s[j]) || 0) + 1); + const t = Array.from(cnt.values()); + ans += Math.max(...t) - Math.min(...t); + } + } + return ans; +}; +``` + + + +### 方法二 + + + +```python +class Solution: + def beautySum(self, s: str) -> int: + ans, n = 0, len(s) + for i in range(n): + cnt = Counter() + freq = Counter() + mi = mx = 1 + for j in range(i, n): + freq[cnt[s[j]]] -= 1 + cnt[s[j]] += 1 + freq[cnt[s[j]]] += 1 + + if cnt[s[j]] == 1: + mi = 1 + if freq[mi] == 0: + mi += 1 + if cnt[s[j]] > mx: + mx = cnt[s[j]] + + ans += mx - mi + return ans +``` + ```java class Solution { public int beautySum(String s) { @@ -151,34 +216,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int beautySum(string s) { - int ans = 0; - int n = s.size(); - int cnt[26]; - for (int i = 0; i < n; ++i) { - memset(cnt, 0, sizeof cnt); - for (int j = i; j < n; ++j) { - ++cnt[s[j] - 'a']; - int mi = 1000, mx = 0; - for (int& v : cnt) { - if (v > 0) { - mi = min(mi, v); - mx = max(mx, v); - } - } - ans += mx - mi; - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -212,32 +249,6 @@ public: }; ``` -### **Go** - -```go -func beautySum(s string) (ans int) { - for i := range s { - cnt := [26]int{} - for j := i; j < len(s); j++ { - cnt[s[j]-'a']++ - mi, mx := 1000, 0 - for _, v := range cnt { - if v > 0 { - if mi > v { - mi = v - } - if mx < v { - mx = v - } - } - } - ans += mx - mi - } - } - return -} -``` - ```go func beautySum(s string) (ans int) { n := len(s) @@ -267,27 +278,6 @@ func beautySum(s string) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {string} s - * @return {number} - */ -var beautySum = function (s) { - let ans = 0; - for (let i = 0; i < s.length; ++i) { - const cnt = new Map(); - for (let j = i; j < s.length; ++j) { - cnt.set(s[j], (cnt.get(s[j]) || 0) + 1); - const t = Array.from(cnt.values()); - ans += Math.max(...t) - Math.min(...t); - } - } - return ans; -}; -``` - ```js /** * @param {string} s @@ -321,10 +311,6 @@ var beautySum = function (s) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1781.Sum of Beauty of All Substrings/README_EN.md b/solution/1700-1799/1781.Sum of Beauty of All Substrings/README_EN.md index 307f99dcf51c4..312faf1eb57f4 100644 --- a/solution/1700-1799/1781.Sum of Beauty of All Substrings/README_EN.md +++ b/solution/1700-1799/1781.Sum of Beauty of All Substrings/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: Enumeration + Counting** +### Solution 1: Enumeration + Counting Enumerate the starting position $i$ of each substring, find all substrings with the character at this starting position as the left endpoint, then calculate the beauty value of each substring, and accumulate it to the answer. @@ -45,8 +45,6 @@ The time complexity is $O(n^2 \times C)$, and the space complexity is $O(C)$. He -### **Python3** - ```python class Solution: def beautySum(self, s: str) -> int: @@ -59,32 +57,6 @@ class Solution: return ans ``` -```python -class Solution: - def beautySum(self, s: str) -> int: - ans, n = 0, len(s) - for i in range(n): - cnt = Counter() - freq = Counter() - mi = mx = 1 - for j in range(i, n): - freq[cnt[s[j]]] -= 1 - cnt[s[j]] += 1 - freq[cnt[s[j]]] += 1 - - if cnt[s[j]] == 1: - mi = 1 - if freq[mi] == 0: - mi += 1 - if cnt[s[j]] > mx: - mx = cnt[s[j]] - - ans += mx - mi - return ans -``` - -### **Java** - ```java class Solution { public int beautySum(String s) { @@ -109,6 +81,105 @@ class Solution { } ``` +```cpp +class Solution { +public: + int beautySum(string s) { + int ans = 0; + int n = s.size(); + int cnt[26]; + for (int i = 0; i < n; ++i) { + memset(cnt, 0, sizeof cnt); + for (int j = i; j < n; ++j) { + ++cnt[s[j] - 'a']; + int mi = 1000, mx = 0; + for (int& v : cnt) { + if (v > 0) { + mi = min(mi, v); + mx = max(mx, v); + } + } + ans += mx - mi; + } + } + return ans; + } +}; +``` + +```go +func beautySum(s string) (ans int) { + for i := range s { + cnt := [26]int{} + for j := i; j < len(s); j++ { + cnt[s[j]-'a']++ + mi, mx := 1000, 0 + for _, v := range cnt { + if v > 0 { + if mi > v { + mi = v + } + if mx < v { + mx = v + } + } + } + ans += mx - mi + } + } + return +} +``` + +```js +/** + * @param {string} s + * @return {number} + */ +var beautySum = function (s) { + let ans = 0; + for (let i = 0; i < s.length; ++i) { + const cnt = new Map(); + for (let j = i; j < s.length; ++j) { + cnt.set(s[j], (cnt.get(s[j]) || 0) + 1); + const t = Array.from(cnt.values()); + ans += Math.max(...t) - Math.min(...t); + } + } + return ans; +}; +``` + + + +### Solution 2 + + + +```python +class Solution: + def beautySum(self, s: str) -> int: + ans, n = 0, len(s) + for i in range(n): + cnt = Counter() + freq = Counter() + mi = mx = 1 + for j in range(i, n): + freq[cnt[s[j]]] -= 1 + cnt[s[j]] += 1 + freq[cnt[s[j]]] += 1 + + if cnt[s[j]] == 1: + mi = 1 + if freq[mi] == 0: + mi += 1 + if cnt[s[j]] > mx: + mx = cnt[s[j]] + + ans += mx - mi + return ans +``` + ```java class Solution { public int beautySum(String s) { @@ -141,34 +212,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int beautySum(string s) { - int ans = 0; - int n = s.size(); - int cnt[26]; - for (int i = 0; i < n; ++i) { - memset(cnt, 0, sizeof cnt); - for (int j = i; j < n; ++j) { - ++cnt[s[j] - 'a']; - int mi = 1000, mx = 0; - for (int& v : cnt) { - if (v > 0) { - mi = min(mi, v); - mx = max(mx, v); - } - } - ans += mx - mi; - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -202,32 +245,6 @@ public: }; ``` -### **Go** - -```go -func beautySum(s string) (ans int) { - for i := range s { - cnt := [26]int{} - for j := i; j < len(s); j++ { - cnt[s[j]-'a']++ - mi, mx := 1000, 0 - for _, v := range cnt { - if v > 0 { - if mi > v { - mi = v - } - if mx < v { - mx = v - } - } - } - ans += mx - mi - } - } - return -} -``` - ```go func beautySum(s string) (ans int) { n := len(s) @@ -257,27 +274,6 @@ func beautySum(s string) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {string} s - * @return {number} - */ -var beautySum = function (s) { - let ans = 0; - for (let i = 0; i < s.length; ++i) { - const cnt = new Map(); - for (let j = i; j < s.length; ++j) { - cnt.set(s[j], (cnt.get(s[j]) || 0) + 1); - const t = Array.from(cnt.values()); - ans += Math.max(...t) - Math.min(...t); - } - } - return ans; -}; -``` - ```js /** * @param {string} s @@ -311,10 +307,6 @@ var beautySum = function (s) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1782.Count Pairs Of Nodes/README.md b/solution/1700-1799/1782.Count Pairs Of Nodes/README.md index 6d04bbbe204eb..cffaf7a45c3c0 100644 --- a/solution/1700-1799/1782.Count Pairs Of Nodes/README.md +++ b/solution/1700-1799/1782.Count Pairs Of Nodes/README.md @@ -55,9 +55,7 @@ answers[1] = 5。所有的点对(a, b)中除了(3,4)边数等于3,其它点对 ## 解法 - - -**方法一:哈希表 + 排序 + 二分查找** +### 方法一:哈希表 + 排序 + 二分查找 根据题目,我们可以知道,与点对 $(a, b)$ 相连的边数等于“与 $a$ 相连的边数”加上“与 $b$ 相连的边数”,再减去同时与 $a$ 和 $b$ 相连的边数。 @@ -69,10 +67,6 @@ answers[1] = 5。所有的点对(a, b)中除了(3,4)边数等于3,其它点对 -### **Python3** - - - ```python class Solution: def countPairs( @@ -99,10 +93,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] countPairs(int n, int[][] edges, int[] queries) { @@ -151,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -188,8 +176,6 @@ public: }; ``` -### **Go** - ```go func countPairs(n int, edges [][]int, queries []int) []int { cnt := make([]int, n) @@ -223,8 +209,6 @@ func countPairs(n int, edges [][]int, queries []int) []int { } ``` -### **TypeScript** - ```ts function countPairs(n: number, edges: number[][], queries: number[]): number[] { const cnt: number[] = new Array(n).fill(0); @@ -268,10 +252,6 @@ function countPairs(n: number, edges: number[][], queries: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1782.Count Pairs Of Nodes/README_EN.md b/solution/1700-1799/1782.Count Pairs Of Nodes/README_EN.md index abca69726ca59..b261e49398dc6 100644 --- a/solution/1700-1799/1782.Count Pairs Of Nodes/README_EN.md +++ b/solution/1700-1799/1782.Count Pairs Of Nodes/README_EN.md @@ -52,9 +52,9 @@ The answers for each of the queries are as follows: ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] countPairs(int n, int[][] edges, int[] queries) { @@ -132,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +165,6 @@ public: }; ``` -### **Go** - ```go func countPairs(n int, edges [][]int, queries []int) []int { cnt := make([]int, n) @@ -204,8 +198,6 @@ func countPairs(n int, edges [][]int, queries []int) []int { } ``` -### **TypeScript** - ```ts function countPairs(n: number, edges: number[][], queries: number[]): number[] { const cnt: number[] = new Array(n).fill(0); @@ -249,10 +241,6 @@ function countPairs(n: number, edges: number[][], queries: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1783.Grand Slam Titles/README.md b/solution/1700-1799/1783.Grand Slam Titles/README.md index 575d048178bc6..823a19517e0f2 100644 --- a/solution/1700-1799/1783.Grand Slam Titles/README.md +++ b/solution/1700-1799/1783.Grand Slam Titles/README.md @@ -81,16 +81,12 @@ Player 3 (Novak) 没有赢得,因此不包含在结果集中。 ## 解法 - - -**方法一:合并 + 等值连接 + 分组** +### 方法一:合并 + 等值连接 + 分组 我们可以使用 `UNION ALL`,将所有赢得大满贯比赛的球员 ID 合并到一张表 `T` 中,然后使用等值连接 `JOIN`,将 `T` 表与 `Players` 表按照 `player_id` 进行连接,最后使用 `GROUP BY` 和 `COUNT` 统计每个球员赢得大满贯比赛的次数。 -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -114,6 +110,12 @@ FROM GROUP BY 1; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below SELECT @@ -150,3 +152,5 @@ HAVING grand_slams_count > 0; ``` + + diff --git a/solution/1700-1799/1783.Grand Slam Titles/README_EN.md b/solution/1700-1799/1783.Grand Slam Titles/README_EN.md index 51df23db8cef9..3cf6f44be93da 100644 --- a/solution/1700-1799/1783.Grand Slam Titles/README_EN.md +++ b/solution/1700-1799/1783.Grand Slam Titles/README_EN.md @@ -79,14 +79,12 @@ Player 3 (Novak) did not win anything, we did not include them in the result tab ## Solutions -**Solution 1: Union All + Equi-Join + Group By** +### Solution 1: Union All + Equi-Join + Group By We can use `UNION ALL` to merge all player IDs who won Grand Slam titles into a table `T`, then use an equi-join `JOIN` to join `T` table with `Players` table on `player_id`, and finally use `GROUP BY` and `COUNT` to count the number of Grand Slam titles won by each player. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -110,6 +108,12 @@ FROM GROUP BY 1; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below SELECT @@ -146,3 +150,5 @@ HAVING grand_slams_count > 0; ``` + + diff --git a/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README.md b/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README.md index 59d740d71cee6..92d02b38a5e24 100644 --- a/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README.md +++ b/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:0 后面不能有 1** +### 方法一:0 后面不能有 1 注意到字符串 $s$ 不含前导零,说明 $s$ 以 '1' 开头。 @@ -54,20 +52,12 @@ -### **Python3** - - - ```python class Solution: def checkOnesSegment(self, s: str) -> bool: return '01' not in s ``` -### **Java** - - - ```java class Solution { public boolean checkOnesSegment(String s) { @@ -76,8 +66,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,16 +75,12 @@ public: }; ``` -### **Go** - ```go func checkOnesSegment(s string) bool { return !strings.Contains(s, "01") } ``` -### **TypeScript** - ```ts function checkOnesSegment(s: string): boolean { let pre = s[0]; @@ -110,14 +94,6 @@ function checkOnesSegment(s: string): boolean { } ``` -```ts -function checkOnesSegment(s: string): boolean { - return !s.includes('01'); -} -``` - -### **Rust** - ```rust impl Solution { pub fn check_ones_segment(s: String) -> bool { @@ -126,10 +102,18 @@ impl Solution { } ``` -### **...** + -``` +### 方法二 + + +```ts +function checkOnesSegment(s: string): boolean { + return !s.includes('01'); +} ``` + + diff --git a/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README_EN.md b/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README_EN.md index a57363a24050c..ab6304f3ba2a5 100644 --- a/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README_EN.md +++ b/solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/README_EN.md @@ -32,7 +32,7 @@ ## Solutions -**Solution 1: No '1' After '0'** +### Solution 1: No '1' After '0' Notice that the string $s$ does not contain leading zeros, which means $s$ starts with '1'. @@ -46,16 +46,12 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. The sp -### **Python3** - ```python class Solution: def checkOnesSegment(self, s: str) -> bool: return '01' not in s ``` -### **Java** - ```java class Solution { public boolean checkOnesSegment(String s) { @@ -64,8 +60,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -75,16 +69,12 @@ public: }; ``` -### **Go** - ```go func checkOnesSegment(s string) bool { return !strings.Contains(s, "01") } ``` -### **TypeScript** - ```ts function checkOnesSegment(s: string): boolean { let pre = s[0]; @@ -98,14 +88,6 @@ function checkOnesSegment(s: string): boolean { } ``` -```ts -function checkOnesSegment(s: string): boolean { - return !s.includes('01'); -} -``` - -### **Rust** - ```rust impl Solution { pub fn check_ones_segment(s: String) -> bool { @@ -114,10 +96,18 @@ impl Solution { } ``` -### **...** + -``` +### Solution 2 + + +```ts +function checkOnesSegment(s: string): boolean { + return !s.includes('01'); +} ``` + + diff --git a/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README.md b/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README.md index ef10269b14063..89fdef4c52796 100644 --- a/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README.md +++ b/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们先计算数组元素总和 $s$,然后计算 $s$ 与 $goal$ 的差值 $d$。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def minElements(self, nums: List[int], limit: int, goal: int) -> int: @@ -67,10 +61,6 @@ class Solution: return (d + limit - 1) // limit ``` -### **Java** - - - ```java class Solution { public int minElements(int[] nums, int limit, int goal) { @@ -85,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +86,6 @@ public: }; ``` -### **Go** - ```go func minElements(nums []int, limit int, goal int) int { s := 0 @@ -118,8 +104,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minElements(nums: number[], limit: number, goal: number): number { const sum = nums.reduce((r, v) => r + v, 0); @@ -128,8 +112,6 @@ function minElements(nums: number[], limit: number, goal: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_elements(nums: Vec, limit: i32, goal: i32) -> i32 { @@ -145,8 +127,6 @@ impl Solution { } ``` -### **C** - ```c int minElements(int* nums, int numsSize, int limit, int goal) { long long sum = 0; @@ -158,10 +138,6 @@ int minElements(int* nums, int numsSize, int limit, int goal) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README_EN.md b/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README_EN.md index b396d4e1d7667..e230e51347219 100644 --- a/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README_EN.md +++ b/solution/1700-1799/1785.Minimum Elements to Add to Form a Given Sum/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy First, we calculate the sum of the array elements $s$, and then calculate the difference $d$ between $s$ and $goal$. @@ -50,8 +50,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is -### **Python3** - ```python class Solution: def minElements(self, nums: List[int], limit: int, goal: int) -> int: @@ -59,8 +57,6 @@ class Solution: return (d + limit - 1) // limit ``` -### **Java** - ```java class Solution { public int minElements(int[] nums, int limit, int goal) { @@ -75,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -88,8 +82,6 @@ public: }; ``` -### **Go** - ```go func minElements(nums []int, limit int, goal int) int { s := 0 @@ -108,8 +100,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minElements(nums: number[], limit: number, goal: number): number { const sum = nums.reduce((r, v) => r + v, 0); @@ -118,8 +108,6 @@ function minElements(nums: number[], limit: number, goal: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_elements(nums: Vec, limit: i32, goal: i32) -> i32 { @@ -135,8 +123,6 @@ impl Solution { } ``` -### **C** - ```c int minElements(int* nums, int numsSize, int limit, int goal) { long long sum = 0; @@ -148,10 +134,6 @@ int minElements(int* nums, int numsSize, int limit, int goal) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/README.md b/solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/README.md index 03f8389b47144..615bfe13b2dae 100644 --- a/solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/README.md +++ b/solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/README.md @@ -51,16 +51,10 @@ ## 解法 - - -**方法一:堆优化 Dijkstra + 记忆化搜索** +### 方法一:堆优化 Dijkstra + 记忆化搜索 -### **Python3** - - - ```python class Solution: def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int: @@ -91,38 +85,6 @@ class Solution: return dfs(1) ``` -```python -class Solution: - def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int: - g = defaultdict(list) - for u, v, w in edges: - g[u].append((v, w)) - g[v].append((u, w)) - dist = [inf] * (n + 1) - dist[n] = 0 - q = [(0, n)] - mod = 10**9 + 7 - while q: - _, u = heappop(q) - for v, w in g[u]: - if dist[v] > dist[u] + w: - dist[v] = dist[u] + w - heappush(q, (dist[v], v)) - arr = list(range(1, n + 1)) - arr.sort(key=lambda i: dist[i]) - f = [0] * (n + 1) - f[n] = 1 - for i in arr: - for j, _ in g[i]: - if dist[i] > dist[j]: - f[i] = (f[i] + f[j]) % mod - return f[1] -``` - -### **Java** - - - ```java class Solution { private static final int INF = Integer.MAX_VALUE; @@ -184,57 +146,6 @@ class Solution { } ``` -```java -class Solution { - private static final int INF = Integer.MAX_VALUE; - private static final int MOD = (int) 1e9 + 7; - - public int countRestrictedPaths(int n, int[][] edges) { - List[] g = new List[n + 1]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int[] e : edges) { - int u = e[0], v = e[1], w = e[2]; - g[u].add(new int[] {v, w}); - g[v].add(new int[] {u, w}); - } - PriorityQueue q = new PriorityQueue<>((a, b) -> a[0] - b[0]); - q.offer(new int[] {0, n}); - int[] dist = new int[n + 1]; - Arrays.fill(dist, INF); - dist[n] = 0; - while (!q.isEmpty()) { - int[] p = q.poll(); - int u = p[1]; - for (int[] ne : g[u]) { - int v = ne[0], w = ne[1]; - if (dist[v] > dist[u] + w) { - dist[v] = dist[u] + w; - q.offer(new int[] {dist[v], v}); - } - } - } - int[] f = new int[n + 1]; - f[n] = 1; - Integer[] arr = new Integer[n]; - for (int i = 0; i < n; ++i) { - arr[i] = i + 1; - } - Arrays.sort(arr, (i, j) -> dist[i] - dist[j]); - for (int i : arr) { - for (int[] ne : g[i]) { - int j = ne[0]; - if (dist[i] > dist[j]) { - f[i] = (f[i] + f[j]) % MOD; - } - } - } - return f[1]; - } -} -``` - -### **C++** - ```cpp using pii = pair; @@ -288,8 +199,6 @@ public: }; ``` -### **Go** - ```go const inf = math.MaxInt32 const mod = 1e9 + 7 @@ -359,10 +268,89 @@ func countRestrictedPaths(n int, edges [][]int) int { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int: + g = defaultdict(list) + for u, v, w in edges: + g[u].append((v, w)) + g[v].append((u, w)) + dist = [inf] * (n + 1) + dist[n] = 0 + q = [(0, n)] + mod = 10**9 + 7 + while q: + _, u = heappop(q) + for v, w in g[u]: + if dist[v] > dist[u] + w: + dist[v] = dist[u] + w + heappush(q, (dist[v], v)) + arr = list(range(1, n + 1)) + arr.sort(key=lambda i: dist[i]) + f = [0] * (n + 1) + f[n] = 1 + for i in arr: + for j, _ in g[i]: + if dist[i] > dist[j]: + f[i] = (f[i] + f[j]) % mod + return f[1] ``` +```java +class Solution { + private static final int INF = Integer.MAX_VALUE; + private static final int MOD = (int) 1e9 + 7; + + public int countRestrictedPaths(int n, int[][] edges) { + List[] g = new List[n + 1]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int[] e : edges) { + int u = e[0], v = e[1], w = e[2]; + g[u].add(new int[] {v, w}); + g[v].add(new int[] {u, w}); + } + PriorityQueue q = new PriorityQueue<>((a, b) -> a[0] - b[0]); + q.offer(new int[] {0, n}); + int[] dist = new int[n + 1]; + Arrays.fill(dist, INF); + dist[n] = 0; + while (!q.isEmpty()) { + int[] p = q.poll(); + int u = p[1]; + for (int[] ne : g[u]) { + int v = ne[0], w = ne[1]; + if (dist[v] > dist[u] + w) { + dist[v] = dist[u] + w; + q.offer(new int[] {dist[v], v}); + } + } + } + int[] f = new int[n + 1]; + f[n] = 1; + Integer[] arr = new Integer[n]; + for (int i = 0; i < n; ++i) { + arr[i] = i + 1; + } + Arrays.sort(arr, (i, j) -> dist[i] - dist[j]); + for (int i : arr) { + for (int[] ne : g[i]) { + int j = ne[0]; + if (dist[i] > dist[j]) { + f[i] = (f[i] + f[j]) % MOD; + } + } + } + return f[1]; + } +} ``` + + diff --git a/solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/README_EN.md b/solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/README_EN.md index 764e7192ec100..4f7ad747058f7 100644 --- a/solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/README_EN.md +++ b/solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,36 +82,6 @@ class Solution: return dfs(1) ``` -```python -class Solution: - def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int: - g = defaultdict(list) - for u, v, w in edges: - g[u].append((v, w)) - g[v].append((u, w)) - dist = [inf] * (n + 1) - dist[n] = 0 - q = [(0, n)] - mod = 10**9 + 7 - while q: - _, u = heappop(q) - for v, w in g[u]: - if dist[v] > dist[u] + w: - dist[v] = dist[u] + w - heappush(q, (dist[v], v)) - arr = list(range(1, n + 1)) - arr.sort(key=lambda i: dist[i]) - f = [0] * (n + 1) - f[n] = 1 - for i in arr: - for j, _ in g[i]: - if dist[i] > dist[j]: - f[i] = (f[i] + f[j]) % mod - return f[1] -``` - -### **Java** - ```java class Solution { private static final int INF = Integer.MAX_VALUE; @@ -173,57 +143,6 @@ class Solution { } ``` -```java -class Solution { - private static final int INF = Integer.MAX_VALUE; - private static final int MOD = (int) 1e9 + 7; - - public int countRestrictedPaths(int n, int[][] edges) { - List[] g = new List[n + 1]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int[] e : edges) { - int u = e[0], v = e[1], w = e[2]; - g[u].add(new int[] {v, w}); - g[v].add(new int[] {u, w}); - } - PriorityQueue q = new PriorityQueue<>((a, b) -> a[0] - b[0]); - q.offer(new int[] {0, n}); - int[] dist = new int[n + 1]; - Arrays.fill(dist, INF); - dist[n] = 0; - while (!q.isEmpty()) { - int[] p = q.poll(); - int u = p[1]; - for (int[] ne : g[u]) { - int v = ne[0], w = ne[1]; - if (dist[v] > dist[u] + w) { - dist[v] = dist[u] + w; - q.offer(new int[] {dist[v], v}); - } - } - } - int[] f = new int[n + 1]; - f[n] = 1; - Integer[] arr = new Integer[n]; - for (int i = 0; i < n; ++i) { - arr[i] = i + 1; - } - Arrays.sort(arr, (i, j) -> dist[i] - dist[j]); - for (int i : arr) { - for (int[] ne : g[i]) { - int j = ne[0]; - if (dist[i] > dist[j]) { - f[i] = (f[i] + f[j]) % MOD; - } - } - } - return f[1]; - } -} -``` - -### **C++** - ```cpp using pii = pair; @@ -277,8 +196,6 @@ public: }; ``` -### **Go** - ```go const inf = math.MaxInt32 const mod = 1e9 + 7 @@ -348,10 +265,89 @@ func countRestrictedPaths(n int, edges [][]int) int { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int: + g = defaultdict(list) + for u, v, w in edges: + g[u].append((v, w)) + g[v].append((u, w)) + dist = [inf] * (n + 1) + dist[n] = 0 + q = [(0, n)] + mod = 10**9 + 7 + while q: + _, u = heappop(q) + for v, w in g[u]: + if dist[v] > dist[u] + w: + dist[v] = dist[u] + w + heappush(q, (dist[v], v)) + arr = list(range(1, n + 1)) + arr.sort(key=lambda i: dist[i]) + f = [0] * (n + 1) + f[n] = 1 + for i in arr: + for j, _ in g[i]: + if dist[i] > dist[j]: + f[i] = (f[i] + f[j]) % mod + return f[1] ``` +```java +class Solution { + private static final int INF = Integer.MAX_VALUE; + private static final int MOD = (int) 1e9 + 7; + + public int countRestrictedPaths(int n, int[][] edges) { + List[] g = new List[n + 1]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int[] e : edges) { + int u = e[0], v = e[1], w = e[2]; + g[u].add(new int[] {v, w}); + g[v].add(new int[] {u, w}); + } + PriorityQueue q = new PriorityQueue<>((a, b) -> a[0] - b[0]); + q.offer(new int[] {0, n}); + int[] dist = new int[n + 1]; + Arrays.fill(dist, INF); + dist[n] = 0; + while (!q.isEmpty()) { + int[] p = q.poll(); + int u = p[1]; + for (int[] ne : g[u]) { + int v = ne[0], w = ne[1]; + if (dist[v] > dist[u] + w) { + dist[v] = dist[u] + w; + q.offer(new int[] {dist[v], v}); + } + } + } + int[] f = new int[n + 1]; + f[n] = 1; + Integer[] arr = new Integer[n]; + for (int i = 0; i < n; ++i) { + arr[i] = i + 1; + } + Arrays.sort(arr, (i, j) -> dist[i] - dist[j]); + for (int i : arr) { + for (int[] ne : g[i]) { + int j = ne[0]; + if (dist[i] > dist[j]) { + f[i] = (f[i] + f[j]) % MOD; + } + } + } + return f[1]; + } +} ``` + + diff --git a/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/README.md b/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/README.md index 55f172c8371f6..ea4acb3800247 100644 --- a/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/README.md +++ b/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 注意到数组 `nums` 在修改之后,任意长度为 $k$ 的区间异或结果都等于 $0$,那么对于任意的 $i$,都有: @@ -78,10 +76,6 @@ $$ -### **Python3** - - - ```python class Solution: def minChanges(self, nums: List[int], k: int) -> int: @@ -102,10 +96,6 @@ class Solution: return f[0] ``` -### **Java** - - - ```java class Solution { public int minChanges(int[] nums, int k) { @@ -146,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +164,6 @@ public: }; ``` -### **Go** - ```go func minChanges(nums []int, k int) int { n := 1 << 10 @@ -211,10 +197,6 @@ func minChanges(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/README_EN.md b/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/README_EN.md index 6f9bcb142765d..50aebf5cce01f 100644 --- a/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/README_EN.md +++ b/solution/1700-1799/1787.Make the XOR of All Segments Equal to Zero/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return f[0] ``` -### **Java** - ```java class Solution { public int minChanges(int[] nums, int k) { @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +134,6 @@ public: }; ``` -### **Go** - ```go func minChanges(nums []int, k int) int { n := 1 << 10 @@ -173,10 +167,6 @@ func minChanges(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1788.Maximize the Beauty of the Garden/README.md b/solution/1700-1799/1788.Maximize the Beauty of the Garden/README.md index a3b2b8db17f1d..f713fe3253415 100644 --- a/solution/1700-1799/1788.Maximize the Beauty of the Garden/README.md +++ b/solution/1700-1799/1788.Maximize the Beauty of the Garden/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:哈希表 + 前缀和** +### 方法一:哈希表 + 前缀和 我们用哈希表 $d$ 记录每个美观度第一次出现的位置,用前缀和数组 $s$ 记录当前位置之前的美观度之和。如果一个美观度 $v$ 在位置 $i$ 和 $j$ 出现过(其中 $i \lt j$),那么我们可以得到一个有效的花园 $[i+1,j]$,其美观度为 $s[i] - s[j + 1] + v \times 2$,我们用这个值更新答案。否则,我们将当前美观度所在的位置 $i$ 记录到哈希表 $d$ 中。接下来,我们更新前缀和,如果美观度 $v$ 为负数,我们将其视为 $0$。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def maximumBeauty(self, flowers: List[int]) -> int: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumBeauty(int[] flowers) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +121,6 @@ public: }; ``` -### **Go** - ```go func maximumBeauty(flowers []int) int { n := len(flowers) @@ -153,7 +139,24 @@ func maximumBeauty(flowers []int) int { } ``` -### **Rust** +```ts +function maximumBeauty(flowers: number[]): number { + const n = flowers.length; + const s: number[] = Array(n + 1).fill(0); + const d: Map = new Map(); + let ans = -Infinity; + for (let i = 0; i < n; ++i) { + const v = flowers[i]; + if (d.has(v)) { + ans = Math.max(ans, s[i] - s[d.get(v)! + 1] + v * 2); + } else { + d.set(v, i); + } + s[i + 1] = s[i] + Math.max(v, 0); + } + return ans; +} +``` ```rust use std::collections::HashMap; @@ -178,31 +181,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function maximumBeauty(flowers: number[]): number { - const n = flowers.length; - const s: number[] = Array(n + 1).fill(0); - const d: Map = new Map(); - let ans = -Infinity; - for (let i = 0; i < n; ++i) { - const v = flowers[i]; - if (d.has(v)) { - ans = Math.max(ans, s[i] - s[d.get(v)! + 1] + v * 2); - } else { - d.set(v, i); - } - s[i + 1] = s[i] + Math.max(v, 0); - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1788.Maximize the Beauty of the Garden/README_EN.md b/solution/1700-1799/1788.Maximize the Beauty of the Garden/README_EN.md index 54607e447715e..f4180cd25ddef 100644 --- a/solution/1700-1799/1788.Maximize the Beauty of the Garden/README_EN.md +++ b/solution/1700-1799/1788.Maximize the Beauty of the Garden/README_EN.md @@ -52,7 +52,7 @@ ## Solutions -**Solution 1: Hash Table + Prefix Sum** +### Solution 1: Hash Table + Prefix Sum We use a hash table $d$ to record the first occurrence of each aesthetic value, and a prefix sum array $s$ to record the sum of the aesthetic values before the current position. If an aesthetic value $v$ appears at positions $i$ and $j$ (where $i \lt j$), then we can get a valid garden $[i+1,j]$, whose aesthetic value is $s[i] - s[j + 1] + v \times 2$. We use this value to update the answer. Otherwise, we record the current position $i$ of the aesthetic value in the hash table $d$. Next, we update the prefix sum. If the aesthetic value $v$ is negative, we treat it as $0$. @@ -62,8 +62,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maximumBeauty(self, flowers: List[int]) -> int: @@ -79,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumBeauty(int[] flowers) { @@ -102,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +120,6 @@ public: }; ``` -### **Go** - ```go func maximumBeauty(flowers []int) int { n := len(flowers) @@ -146,7 +138,24 @@ func maximumBeauty(flowers []int) int { } ``` -### **Rust** +```ts +function maximumBeauty(flowers: number[]): number { + const n = flowers.length; + const s: number[] = Array(n + 1).fill(0); + const d: Map = new Map(); + let ans = -Infinity; + for (let i = 0; i < n; ++i) { + const v = flowers[i]; + if (d.has(v)) { + ans = Math.max(ans, s[i] - s[d.get(v)! + 1] + v * 2); + } else { + d.set(v, i); + } + s[i + 1] = s[i] + Math.max(v, 0); + } + return ans; +} +``` ```rust use std::collections::HashMap; @@ -171,31 +180,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function maximumBeauty(flowers: number[]): number { - const n = flowers.length; - const s: number[] = Array(n + 1).fill(0); - const d: Map = new Map(); - let ans = -Infinity; - for (let i = 0; i < n; ++i) { - const v = flowers[i]; - if (d.has(v)) { - ans = Math.max(ans, s[i] - s[d.get(v)! + 1] + v * 2); - } else { - d.set(v, i); - } - s[i + 1] = s[i] + Math.max(v, 0); - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1789.Primary Department for Each Employee/README.md b/solution/1700-1799/1789.Primary Department for Each Employee/README.md index 2401b77261dd0..dd6fff614d12f 100644 --- a/solution/1700-1799/1789.Primary Department for Each Employee/README.md +++ b/solution/1700-1799/1789.Primary Department for Each Employee/README.md @@ -69,18 +69,12 @@ Employee table: ## 解法 - - -**方法一:合并** +### 方法一:合并 我们可以查出所有已经有直属部门的员工,然后再查出所有只属于一个部门的员工,最后我们可以使用 `UNION` 合并两个结果集。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT employee_id, department_id @@ -94,3 +88,5 @@ HAVING COUNT(1) = 1; ``` + + diff --git a/solution/1700-1799/1789.Primary Department for Each Employee/README_EN.md b/solution/1700-1799/1789.Primary Department for Each Employee/README_EN.md index b7df78b27f4af..5efebcea48f38 100644 --- a/solution/1700-1799/1789.Primary Department for Each Employee/README_EN.md +++ b/solution/1700-1799/1789.Primary Department for Each Employee/README_EN.md @@ -65,14 +65,12 @@ Employee table: ## Solutions -**Solution 1: Merging** +### Solution 1: Merging We can first query all employees who already have a direct department, and then query all employees who belong to only one department. Finally, we can merge the two results using `UNION`. -### **SQL** - ```sql # Write your MySQL query statement below SELECT employee_id, department_id @@ -86,3 +84,5 @@ HAVING COUNT(1) = 1; ``` + + diff --git a/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README.md b/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README.md index c3978224e0804..e37309a37a113 100644 --- a/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README.md +++ b/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们用变量 $cnt$ 记录两个字符串中相同位置字符不同的个数,两个字符串若满足题目要求,那么 $cnt$ 一定为 $0$ 或 $2$。另外用两个字符变量 $c1$ 和 $c2$ 记录两个字符串中相同位置字符不同的字符。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def areAlmostEqual(self, s1: str, s2: str) -> bool: @@ -83,10 +77,6 @@ class Solution: return cnt != 1 ``` -### **Java** - - - ```java class Solution { public boolean areAlmostEqual(String s1, String s2) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func areAlmostEqual(s1 string, s2 string) bool { cnt := 0 @@ -149,36 +135,6 @@ func areAlmostEqual(s1 string, s2 string) bool { } ``` -### **C** - -```c -bool areAlmostEqual(char* s1, char* s2) { - int n = strlen(s1); - int i1 = -1; - int i2 = -1; - for (int i = 0; i < n; i++) { - if (s1[i] != s2[i]) { - if (i1 == -1) { - i1 = i; - } else if (i2 == -1) { - i2 = i; - } else { - return 0; - } - } - } - if (i1 == -1 && i2 == -1) { - return 1; - } - if (i1 == -1 || i2 == -1) { - return 0; - } - return s1[i1] == s2[i2] && s1[i2] == s2[i1]; -} -``` - -### **TypeScript** - ```ts function areAlmostEqual(s1: string, s2: string): boolean { let c1, c2; @@ -198,8 +154,6 @@ function areAlmostEqual(s1: string, s2: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn are_almost_equal(s1: String, s2: String) -> bool { @@ -221,10 +175,32 @@ impl Solution { } ``` -### **...** - -``` - +```c +bool areAlmostEqual(char* s1, char* s2) { + int n = strlen(s1); + int i1 = -1; + int i2 = -1; + for (int i = 0; i < n; i++) { + if (s1[i] != s2[i]) { + if (i1 == -1) { + i1 = i; + } else if (i2 == -1) { + i2 = i; + } else { + return 0; + } + } + } + if (i1 == -1 && i2 == -1) { + return 1; + } + if (i1 == -1 || i2 == -1) { + return 0; + } + return s1[i1] == s2[i2] && s1[i2] == s2[i1]; +} ``` + + diff --git a/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README_EN.md b/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README_EN.md index 8600e6aa2752d..e7df4ed99e8df 100644 --- a/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README_EN.md +++ b/solution/1700-1799/1790.Check if One String Swap Can Make Strings Equal/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We use a variable $cnt$ to record the number of characters at the same position in the two strings that are different. If the two strings meet the requirements of the problem, then $cnt$ must be $0$ or $2$. We also use two character variables $c1$ and $c2$ to record the characters that are different at the same position in the two strings. @@ -56,8 +56,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string. The space -### **Python3** - ```python class Solution: def areAlmostEqual(self, s1: str, s2: str) -> bool: @@ -72,8 +70,6 @@ class Solution: return cnt != 1 ``` -### **Java** - ```java class Solution { public boolean areAlmostEqual(String s1, String s2) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +110,6 @@ public: }; ``` -### **Go** - ```go func areAlmostEqual(s1 string, s2 string) bool { cnt := 0 @@ -136,36 +128,6 @@ func areAlmostEqual(s1 string, s2 string) bool { } ``` -### **C** - -```c -bool areAlmostEqual(char* s1, char* s2) { - int n = strlen(s1); - int i1 = -1; - int i2 = -1; - for (int i = 0; i < n; i++) { - if (s1[i] != s2[i]) { - if (i1 == -1) { - i1 = i; - } else if (i2 == -1) { - i2 = i; - } else { - return 0; - } - } - } - if (i1 == -1 && i2 == -1) { - return 1; - } - if (i1 == -1 || i2 == -1) { - return 0; - } - return s1[i1] == s2[i2] && s1[i2] == s2[i1]; -} -``` - -### **TypeScript** - ```ts function areAlmostEqual(s1: string, s2: string): boolean { let c1, c2; @@ -185,8 +147,6 @@ function areAlmostEqual(s1: string, s2: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn are_almost_equal(s1: String, s2: String) -> bool { @@ -208,10 +168,32 @@ impl Solution { } ``` -### **...** - -``` - +```c +bool areAlmostEqual(char* s1, char* s2) { + int n = strlen(s1); + int i1 = -1; + int i2 = -1; + for (int i = 0; i < n; i++) { + if (s1[i] != s2[i]) { + if (i1 == -1) { + i1 = i; + } else if (i2 == -1) { + i2 = i; + } else { + return 0; + } + } + } + if (i1 == -1 && i2 == -1) { + return 1; + } + if (i1 == -1 || i2 == -1) { + return 0; + } + return s1[i1] == s2[i2] && s1[i2] == s2[i1]; +} ``` + + diff --git a/solution/1700-1799/1791.Find Center of Star Graph/README.md b/solution/1700-1799/1791.Find Center of Star Graph/README.md index bf094088b5934..300e9d251c502 100644 --- a/solution/1700-1799/1791.Find Center of Star Graph/README.md +++ b/solution/1700-1799/1791.Find Center of Star Graph/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:直接比较前两条边的点** +### 方法一:直接比较前两条边的点 中心点的特点是,它与其他所有点都相连,因此只要比较前两条边的点,如果有相同的点,那么这个点就是中心点。 @@ -52,20 +50,12 @@ -### **Python3** - - - ```python class Solution: def findCenter(self, edges: List[List[int]]) -> int: return edges[0][0] if edges[0][0] in edges[1] else edges[0][1] ``` -### **Java** - - - ```java class Solution { public int findCenter(int[][] edges) { @@ -76,20 +66,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function findCenter(edges: number[][]): number { - for (let num of edges[0]) { - if (edges[1].includes(num)) { - return num; - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -101,8 +77,6 @@ public: }; ``` -### **Go** - ```go func findCenter(edges [][]int) int { a, b := edges[0][0], edges[0][1] @@ -114,7 +88,15 @@ func findCenter(edges [][]int) int { } ``` -### **Rust** +```ts +function findCenter(edges: number[][]): number { + for (let num of edges[0]) { + if (edges[1].includes(num)) { + return num; + } + } +} +``` ```rust impl Solution { @@ -127,8 +109,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[][]} edges @@ -141,10 +121,6 @@ var findCenter = function (edges) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1791.Find Center of Star Graph/README_EN.md b/solution/1700-1799/1791.Find Center of Star Graph/README_EN.md index ef0388de2310d..8f11acebfe683 100644 --- a/solution/1700-1799/1791.Find Center of Star Graph/README_EN.md +++ b/solution/1700-1799/1791.Find Center of Star Graph/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Directly Compare the Points of the First Two Edges** +### Solution 1: Directly Compare the Points of the First Two Edges The characteristic of the center point is that it is connected to all other points. Therefore, as long as we compare the points of the first two edges, if there are the same points, then this point is the center point. @@ -46,16 +46,12 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def findCenter(self, edges: List[List[int]]) -> int: return edges[0][0] if edges[0][0] in edges[1] else edges[0][1] ``` -### **Java** - ```java class Solution { public int findCenter(int[][] edges) { @@ -66,20 +62,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function findCenter(edges: number[][]): number { - for (let num of edges[0]) { - if (edges[1].includes(num)) { - return num; - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -91,8 +73,6 @@ public: }; ``` -### **Go** - ```go func findCenter(edges [][]int) int { a, b := edges[0][0], edges[0][1] @@ -104,7 +84,15 @@ func findCenter(edges [][]int) int { } ``` -### **Rust** +```ts +function findCenter(edges: number[][]): number { + for (let num of edges[0]) { + if (edges[1].includes(num)) { + return num; + } + } +} +``` ```rust impl Solution { @@ -117,8 +105,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[][]} edges @@ -131,10 +117,6 @@ var findCenter = function (edges) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1792.Maximum Average Pass Ratio/README.md b/solution/1700-1799/1792.Maximum Average Pass Ratio/README.md index 7d4cc11a23ff6..83af7ea36740b 100644 --- a/solution/1700-1799/1792.Maximum Average Pass Ratio/README.md +++ b/solution/1700-1799/1792.Maximum Average Pass Ratio/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:优先队列(增量大根堆)** +### 方法一:优先队列(增量大根堆) 假设一个班级当前的通过率为 $\frac{a}{b}$,那么如果我们将一个聪明的学生安排到此班级,那么班级的通过率就会变为 $\frac{a+1}{b+1}$。我们可以发现,通过率的增量为 $\frac{a+1}{b+1} - \frac{a}{b}$。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: @@ -76,10 +70,6 @@ class Solution: return sum(v[1] / v[2] for v in h) / len(classes) ``` -### **Java** - - - ```java class Solution { public double maxAverageRatio(int[][] classes, int extraStudents) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func maxAverageRatio(classes [][]int, extraStudents int) float64 { pq := hp{} @@ -179,10 +165,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1792.Maximum Average Pass Ratio/README_EN.md b/solution/1700-1799/1792.Maximum Average Pass Ratio/README_EN.md index 7df629cd0146d..be165f719fe54 100644 --- a/solution/1700-1799/1792.Maximum Average Pass Ratio/README_EN.md +++ b/solution/1700-1799/1792.Maximum Average Pass Ratio/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Priority Queue (Max-Heap of Increment)** +### Solution 1: Priority Queue (Max-Heap of Increment) Suppose a class currently has a pass rate of $\frac{a}{b}$. If we arrange a smart student into this class, then the pass rate of the class will become $\frac{a+1}{b+1}$. We can find that the increment of the pass rate is $\frac{a+1}{b+1} - \frac{a}{b}$. @@ -54,8 +54,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: @@ -68,8 +66,6 @@ class Solution: return sum(v[1] / v[2] for v in h) / len(classes) ``` -### **Java** - ```java class Solution { public double maxAverageRatio(int[][] classes, int extraStudents) { @@ -96,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +121,6 @@ public: }; ``` -### **Go** - ```go func maxAverageRatio(classes [][]int, extraStudents int) float64 { pq := hp{} @@ -169,10 +161,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1793.Maximum Score of a Good Subarray/README.md b/solution/1700-1799/1793.Maximum Score of a Good Subarray/README.md index fd9fcd81ff635..7d49d88c8b7dc 100644 --- a/solution/1700-1799/1793.Maximum Score of a Good Subarray/README.md +++ b/solution/1700-1799/1793.Maximum Score of a Good Subarray/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 我们可以枚举 $nums$ 中的每个元素 $nums[i]$ 作为子数组的最小值,利用单调栈找出其左边第一个小于 $nums[i]$ 的位置 $left[i]$ 和右边第一个小于等于 $nums[i]$ 的位置 $right[i]$,则以 $nums[i]$ 为最小值的子数组的分数为 $nums[i] \times (right[i] - left[i] - 1)$。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def maximumScore(self, nums: List[int], k: int) -> int: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumScore(int[] nums, int k) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +159,6 @@ public: }; ``` -### **Go** - ```go func maximumScore(nums []int, k int) (ans int) { n := len(nums) @@ -212,8 +198,6 @@ func maximumScore(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function maximumScore(nums: number[], k: number): number { const n = nums.length; @@ -249,10 +233,6 @@ function maximumScore(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1793.Maximum Score of a Good Subarray/README_EN.md b/solution/1700-1799/1793.Maximum Score of a Good Subarray/README_EN.md index 2576f08105491..81df87cc31ea4 100644 --- a/solution/1700-1799/1793.Maximum Score of a Good Subarray/README_EN.md +++ b/solution/1700-1799/1793.Maximum Score of a Good Subarray/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Monotonic Stack** +### Solution 1: Monotonic Stack We can enumerate each element $nums[i]$ in $nums$ as the minimum value of the subarray, and use a monotonic stack to find the first position $left[i]$ on the left that is less than $nums[i]$ and the first position $right[i]$ on the right that is less than or equal to $nums[i]$. Then, the score of the subarray with $nums[i]$ as the minimum value is $nums[i] \times (right[i] - left[i] - 1)$. @@ -48,8 +48,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maximumScore(self, nums: List[int], k: int) -> int: @@ -78,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumScore(int[] nums, int k) { @@ -121,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +157,6 @@ public: }; ``` -### **Go** - ```go func maximumScore(nums []int, k int) (ans int) { n := len(nums) @@ -204,8 +196,6 @@ func maximumScore(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function maximumScore(nums: number[], k: number): number { const n = nums.length; @@ -241,10 +231,6 @@ function maximumScore(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README.md b/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README.md index 6ea0d604d612d..b36a09b7f274f 100644 --- a/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README.md +++ b/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:贪心 + 哈希表** +### 方法一:贪心 + 哈希表 题目实际上要我们找到一个最小的下标 $i$ 和一个最大的下标 $j$,使得 $firstString[i]$ 与 $secondString[j]$ 相等,且 $i - j$ 的值是所有满足条件的下标对中最小的。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def countQuadruples(self, firstString: str, secondString: str) -> int: @@ -78,10 +72,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countQuadruples(String firstString, String secondString) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func countQuadruples(firstString string, secondString string) (ans int) { last := [26]int{} @@ -160,8 +146,6 @@ func countQuadruples(firstString string, secondString string) (ans int) { } ``` -### **TypeScript** - ```ts function countQuadruples(firstString: string, secondString: string): number { const last: number[] = new Array(26).fill(0); @@ -185,10 +169,6 @@ function countQuadruples(firstString: string, secondString: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README_EN.md b/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README_EN.md index 992312b4063df..a4c2ca0deee94 100644 --- a/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README_EN.md +++ b/solution/1700-1799/1794.Count Pairs of Equal Substrings With Minimum Difference/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Greedy + Hash Table** +### Solution 1: Greedy + Hash Table The problem actually asks us to find a smallest index $i$ and a largest index $j$ such that $firstString[i]$ equals $secondString[j]$, and the value of $i - j$ is the smallest among all index pairs that meet the conditions. @@ -52,8 +52,6 @@ The time complexity is $O(m + n)$, and the space complexity is $O(C)$. Here, $m$ -### **Python3** - ```python class Solution: def countQuadruples(self, firstString: str, secondString: str) -> int: @@ -70,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countQuadruples(String firstString, String secondString) { @@ -97,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +119,6 @@ public: }; ``` -### **Go** - ```go func countQuadruples(firstString string, secondString string) (ans int) { last := [26]int{} @@ -150,8 +142,6 @@ func countQuadruples(firstString string, secondString string) (ans int) { } ``` -### **TypeScript** - ```ts function countQuadruples(firstString: string, secondString: string): number { const last: number[] = new Array(26).fill(0); @@ -175,10 +165,6 @@ function countQuadruples(firstString: string, secondString: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1795.Rearrange Products Table/README.md b/solution/1700-1799/1795.Rearrange Products Table/README.md index 9420bc01c2a9e..252af057033e9 100644 --- a/solution/1700-1799/1795.Rearrange Products Table/README.md +++ b/solution/1700-1799/1795.Rearrange Products Table/README.md @@ -59,18 +59,12 @@ Products table: ## 解法 - - -**方法一:合并** +### 方法一:合并 我们可以筛选出每个商店的产品和价格,然后使用 `UNION` 合并即可。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT product_id, 'store1' AS store, store1 AS price FROM Products WHERE store1 IS NOT NULL @@ -81,3 +75,5 @@ SELECT product_id, 'store3' AS store, store3 AS price FROM Products WHERE store3 ``` + + diff --git a/solution/1700-1799/1795.Rearrange Products Table/README_EN.md b/solution/1700-1799/1795.Rearrange Products Table/README_EN.md index 0fec08c72c588..a978c5eda8354 100644 --- a/solution/1700-1799/1795.Rearrange Products Table/README_EN.md +++ b/solution/1700-1799/1795.Rearrange Products Table/README_EN.md @@ -57,14 +57,12 @@ Product 1 is available in store1 with price 70 and store3 with price 80. The pro ## Solutions -**Solution 1: Union** +### Solution 1: Union We can select the products and prices for each store, and then use the `UNION` operator to combine the results. -### **SQL** - ```sql # Write your MySQL query statement below SELECT product_id, 'store1' AS store, store1 AS price FROM Products WHERE store1 IS NOT NULL @@ -75,3 +73,5 @@ SELECT product_id, 'store3' AS store, store3 AS price FROM Products WHERE store3 ``` + + diff --git a/solution/1700-1799/1796.Second Largest Digit in a String/README.md b/solution/1700-1799/1796.Second Largest Digit in a String/README.md index f687064bfa79d..0b9c6e7b54cbb 100644 --- a/solution/1700-1799/1796.Second Largest Digit in a String/README.md +++ b/solution/1700-1799/1796.Second Largest Digit in a String/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们定义 $a$ 和 $b$ 分别表示字符串中出现的最大数字和第二大数字,初始时 $a = b = -1$。 @@ -51,22 +49,8 @@ 时间复杂度 $O(n)$,其中 $n$ 为字符串 $s$ 的长度。空间复杂度 $O(1)$。 -**方法二:位运算** - -我们可以用一个整数 $mask$ 来标识字符串中出现的数字,其中 $mask$ 的第 $i$ 位表示数字 $i$ 是否出现过。 - -遍历字符串 $s$,如果当前字符是数字,我们将其转换为数字 $v$,将 $mask$ 的第 $v$ 个二进制位的值置为 $1$。 - -最后,我们从高位向低位遍历 $mask$,找到第二个为 $1$ 的二进制位,其对应的数字即为第二大数字。如果不存在第二大数字,返回 $-1$。 - -时间复杂度 $O(n)$,其中 $n$ 为字符串 $s$ 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def secondHighest(self, s: str) -> int: @@ -81,23 +65,6 @@ class Solution: return b ``` -```python -class Solution: - def secondHighest(self, s: str) -> int: - mask = reduce(or_, (1 << int(c) for c in s if c.isdigit()), 0) - cnt = 0 - for i in range(9, -1, -1): - if (mask >> i) & 1: - cnt += 1 - if cnt == 2: - return i - return -1 -``` - -### **Java** - - - ```java class Solution { public int secondHighest(String s) { @@ -119,28 +86,6 @@ class Solution { } ``` -```java -class Solution { - public int secondHighest(String s) { - int mask = 0; - for (int i = 0; i < s.length(); ++i) { - char c = s.charAt(i); - if (Character.isDigit(c)) { - mask |= 1 << (c - '0'); - } - } - for (int i = 9, cnt = 0; i >= 0; --i) { - if (((mask >> i) & 1) == 1 && ++cnt == 2) { - return i; - } - } - return -1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -161,22 +106,6 @@ public: }; ``` -```cpp -class Solution { -public: - int secondHighest(string s) { - int mask = 0; - for (char& c : s) - if (isdigit(c)) mask |= 1 << c - '0'; - for (int i = 9, cnt = 0; ~i; --i) - if (mask >> i & 1 && ++cnt == 2) return i; - return -1; - } -}; -``` - -### **Go** - ```go func secondHighest(s string) int { a, b := -1, -1 @@ -194,28 +123,6 @@ func secondHighest(s string) int { } ``` -```go -func secondHighest(s string) int { - mask := 0 - for _, c := range s { - if c >= '0' && c <= '9' { - mask |= 1 << int(c-'0') - } - } - for i, cnt := 9, 0; i >= 0; i-- { - if mask>>i&1 == 1 { - cnt++ - if cnt == 2 { - return i - } - } - } - return -1 -} -``` - -### **TypeScript** - ```ts function secondHighest(s: string): number { let first = -1; @@ -234,8 +141,6 @@ function secondHighest(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn second_highest(s: String) -> i32 { @@ -257,8 +162,6 @@ impl Solution { } ``` -### **C** - ```c int secondHighest(char* s) { int first = -1; @@ -278,10 +181,87 @@ int secondHighest(char* s) { } ``` -### **...** + + +### 方法二:位运算 + +我们可以用一个整数 $mask$ 来标识字符串中出现的数字,其中 $mask$ 的第 $i$ 位表示数字 $i$ 是否出现过。 + +遍历字符串 $s$,如果当前字符是数字,我们将其转换为数字 $v$,将 $mask$ 的第 $v$ 个二进制位的值置为 $1$。 +最后,我们从高位向低位遍历 $mask$,找到第二个为 $1$ 的二进制位,其对应的数字即为第二大数字。如果不存在第二大数字,返回 $-1$。 + +时间复杂度 $O(n)$,其中 $n$ 为字符串 $s$ 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def secondHighest(self, s: str) -> int: + mask = reduce(or_, (1 << int(c) for c in s if c.isdigit()), 0) + cnt = 0 + for i in range(9, -1, -1): + if (mask >> i) & 1: + cnt += 1 + if cnt == 2: + return i + return -1 ``` +```java +class Solution { + public int secondHighest(String s) { + int mask = 0; + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (Character.isDigit(c)) { + mask |= 1 << (c - '0'); + } + } + for (int i = 9, cnt = 0; i >= 0; --i) { + if (((mask >> i) & 1) == 1 && ++cnt == 2) { + return i; + } + } + return -1; + } +} +``` + +```cpp +class Solution { +public: + int secondHighest(string s) { + int mask = 0; + for (char& c : s) + if (isdigit(c)) mask |= 1 << c - '0'; + for (int i = 9, cnt = 0; ~i; --i) + if (mask >> i & 1 && ++cnt == 2) return i; + return -1; + } +}; +``` + +```go +func secondHighest(s string) int { + mask := 0 + for _, c := range s { + if c >= '0' && c <= '9' { + mask |= 1 << int(c-'0') + } + } + for i, cnt := 9, 0; i >= 0; i-- { + if mask>>i&1 == 1 { + cnt++ + if cnt == 2 { + return i + } + } + } + return -1 +} ``` + + diff --git a/solution/1700-1799/1796.Second Largest Digit in a String/README_EN.md b/solution/1700-1799/1796.Second Largest Digit in a String/README_EN.md index 901df4778eb42..1ec9cc41f3a57 100644 --- a/solution/1700-1799/1796.Second Largest Digit in a String/README_EN.md +++ b/solution/1700-1799/1796.Second Largest Digit in a String/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: One Pass** +### Solution 1: One Pass We define $a$ and $b$ to represent the largest and second largest numbers in the string, initially $a = b = -1$. @@ -45,20 +45,8 @@ After the traversal, we return $b$. The time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$. -**Solution 2: Bit Manipulation** - -We can use an integer $mask$ to mark the numbers that appear in the string, where the $i$-th bit of $mask$ indicates whether the number $i$ has appeared. - -We traverse the string $s$. If the current character is a digit, we convert it to a number $v$, and set the $v$-th bit of $mask$ to $1$. - -Finally, we traverse $mask$ from high to low, find the second bit that is $1$, and the corresponding number is the second largest number. If there is no second largest number, return $-1$. - -The time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def secondHighest(self, s: str) -> int: @@ -73,21 +61,6 @@ class Solution: return b ``` -```python -class Solution: - def secondHighest(self, s: str) -> int: - mask = reduce(or_, (1 << int(c) for c in s if c.isdigit()), 0) - cnt = 0 - for i in range(9, -1, -1): - if (mask >> i) & 1: - cnt += 1 - if cnt == 2: - return i - return -1 -``` - -### **Java** - ```java class Solution { public int secondHighest(String s) { @@ -109,28 +82,6 @@ class Solution { } ``` -```java -class Solution { - public int secondHighest(String s) { - int mask = 0; - for (int i = 0; i < s.length(); ++i) { - char c = s.charAt(i); - if (Character.isDigit(c)) { - mask |= 1 << (c - '0'); - } - } - for (int i = 9, cnt = 0; i >= 0; --i) { - if (((mask >> i) & 1) == 1 && ++cnt == 2) { - return i; - } - } - return -1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -151,8 +102,6 @@ public: }; ``` -### **Go** - ```go func secondHighest(s string) int { a, b := -1, -1 @@ -170,28 +119,6 @@ func secondHighest(s string) int { } ``` -```go -func secondHighest(s string) int { - mask := 0 - for _, c := range s { - if c >= '0' && c <= '9' { - mask |= 1 << int(c-'0') - } - } - for i, cnt := 9, 0; i >= 0; i-- { - if mask>>i&1 == 1 { - cnt++ - if cnt == 2 { - return i - } - } - } - return -1 -} -``` - -### **TypeScript** - ```ts function secondHighest(s: string): number { let first = -1; @@ -210,8 +137,6 @@ function secondHighest(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn second_highest(s: String) -> i32 { @@ -233,8 +158,6 @@ impl Solution { } ``` -### **C** - ```c int secondHighest(char* s) { int first = -1; @@ -254,10 +177,87 @@ int secondHighest(char* s) { } ``` -### **...** + + +### Solution 2: Bit Manipulation +We can use an integer $mask$ to mark the numbers that appear in the string, where the $i$-th bit of $mask$ indicates whether the number $i$ has appeared. + +We traverse the string $s$. If the current character is a digit, we convert it to a number $v$, and set the $v$-th bit of $mask$ to $1$. + +Finally, we traverse $mask$ from high to low, find the second bit that is $1$, and the corresponding number is the second largest number. If there is no second largest number, return $-1$. + +The time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$. + + + +```python +class Solution: + def secondHighest(self, s: str) -> int: + mask = reduce(or_, (1 << int(c) for c in s if c.isdigit()), 0) + cnt = 0 + for i in range(9, -1, -1): + if (mask >> i) & 1: + cnt += 1 + if cnt == 2: + return i + return -1 +``` + +```java +class Solution { + public int secondHighest(String s) { + int mask = 0; + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (Character.isDigit(c)) { + mask |= 1 << (c - '0'); + } + } + for (int i = 9, cnt = 0; i >= 0; --i) { + if (((mask >> i) & 1) == 1 && ++cnt == 2) { + return i; + } + } + return -1; + } +} ``` +```cpp +class Solution { +public: + int secondHighest(string s) { + int mask = 0; + for (char& c : s) + if (isdigit(c)) mask |= 1 << c - '0'; + for (int i = 9, cnt = 0; ~i; --i) + if (mask >> i & 1 && ++cnt == 2) return i; + return -1; + } +}; +``` + +```go +func secondHighest(s string) int { + mask := 0 + for _, c := range s { + if c >= '0' && c <= '9' { + mask |= 1 << int(c-'0') + } + } + for i, cnt := 9, 0; i >= 0; i-- { + if mask>>i&1 == 1 { + cnt++ + if cnt == 2 { + return i + } + } + } + return -1 +} ``` + + diff --git a/solution/1700-1799/1797.Design Authentication Manager/README.md b/solution/1700-1799/1797.Design Authentication Manager/README.md index 5b83ae891e3a6..4026a20a303ba 100644 --- a/solution/1700-1799/1797.Design Authentication Manager/README.md +++ b/solution/1700-1799/1797.Design Authentication Manager/README.md @@ -58,9 +58,7 @@ authenticationManager.countUnexpiredTokens(15); // tokenId 为 "bbb ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以简单维护一个哈希表 $d$,键为 `tokenId`,值为过期时间。 @@ -74,10 +72,6 @@ authenticationManager.countUnexpiredTokens(15); // tokenId 为 "bbb -### **Python3** - - - ```python class AuthenticationManager: def __init__(self, timeToLive: int): @@ -103,10 +97,6 @@ class AuthenticationManager: # param_3 = obj.countUnexpiredTokens(currentTime) ``` -### **Java** - - - ```java class AuthenticationManager { private int t; @@ -147,8 +137,6 @@ class AuthenticationManager { */ ``` -### **C++** - ```cpp class AuthenticationManager { public: @@ -185,8 +173,6 @@ private: */ ``` -### **Go** - ```go type AuthenticationManager struct { t int @@ -227,8 +213,6 @@ func (this *AuthenticationManager) CountUnexpiredTokens(currentTime int) int { */ ``` -### **TypeScript** - ```ts class AuthenticationManager { private timeToLive: number; @@ -270,8 +254,6 @@ class AuthenticationManager { */ ``` -### **Rust** - ```rust use std::collections::HashMap; struct AuthenticationManager { @@ -317,10 +299,6 @@ impl AuthenticationManager { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1797.Design Authentication Manager/README_EN.md b/solution/1700-1799/1797.Design Authentication Manager/README_EN.md index 0f11ff8f01cd6..8874ccf8582dd 100644 --- a/solution/1700-1799/1797.Design Authentication Manager/README_EN.md +++ b/solution/1700-1799/1797.Design Authentication Manager/README_EN.md @@ -54,7 +54,7 @@ authenticationManager.countUnexpiredTokens(15); // The token with t ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We can simply maintain a hash table $d$, where the key is `tokenId` and the value is the expiration time. @@ -68,8 +68,6 @@ The space complexity is $O(n)$, where $n$ is the number of key-value pairs in th -### **Python3** - ```python class AuthenticationManager: def __init__(self, timeToLive: int): @@ -95,8 +93,6 @@ class AuthenticationManager: # param_3 = obj.countUnexpiredTokens(currentTime) ``` -### **Java** - ```java class AuthenticationManager { private int t; @@ -137,8 +133,6 @@ class AuthenticationManager { */ ``` -### **C++** - ```cpp class AuthenticationManager { public: @@ -175,8 +169,6 @@ private: */ ``` -### **Go** - ```go type AuthenticationManager struct { t int @@ -217,8 +209,6 @@ func (this *AuthenticationManager) CountUnexpiredTokens(currentTime int) int { */ ``` -### **TypeScript** - ```ts class AuthenticationManager { private timeToLive: number; @@ -260,8 +250,6 @@ class AuthenticationManager { */ ``` -### **Rust** - ```rust use std::collections::HashMap; struct AuthenticationManager { @@ -307,10 +295,6 @@ impl AuthenticationManager { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README.md b/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README.md index d6fffa4261e52..09a2615355376 100644 --- a/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README.md +++ b/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:排序 + 贪心** +### 方法一:排序 + 贪心 我们先对数组进行排序。然后定义 $ans$ 表示当前能够构造的连续整数的个数,初始化为 $1$。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def getMaximumConsecutive(self, coins: List[int]) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int getMaximumConsecutive(int[] coins) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func getMaximumConsecutive(coins []int) int { sort.Ints(coins) @@ -140,8 +126,6 @@ func getMaximumConsecutive(coins []int) int { } ``` -### **TypeScript** - ```ts function getMaximumConsecutive(coins: number[]): number { coins.sort((a, b) => a - b); @@ -156,10 +140,6 @@ function getMaximumConsecutive(coins: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README_EN.md b/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README_EN.md index 9c716ae53f87a..cd6326c959c13 100644 --- a/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README_EN.md +++ b/solution/1700-1799/1798.Maximum Number of Consecutive Values You Can Make/README_EN.md @@ -54,7 +54,7 @@ You can make 8 consecutive integer values starting from 0. ## Solutions -**Solution 1: Sorting + Greedy** +### Solution 1: Sorting + Greedy First, we sort the array. Then we define $ans$ as the current number of consecutive integers that can be constructed, initialized to $1$. @@ -66,8 +66,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def getMaximumConsecutive(self, coins: List[int]) -> int: @@ -79,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int getMaximumConsecutive(int[] coins) { @@ -97,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +108,6 @@ public: }; ``` -### **Go** - ```go func getMaximumConsecutive(coins []int) int { sort.Ints(coins) @@ -130,8 +122,6 @@ func getMaximumConsecutive(coins []int) int { } ``` -### **TypeScript** - ```ts function getMaximumConsecutive(coins: number[]): number { coins.sort((a, b) => a - b); @@ -146,10 +136,6 @@ function getMaximumConsecutive(coins: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1799.Maximize Score After N Operations/README.md b/solution/1700-1799/1799.Maximize Score After N Operations/README.md index 283ba495938b2..2ab9966420bef 100644 --- a/solution/1700-1799/1799.Maximize Score After N Operations/README.md +++ b/solution/1700-1799/1799.Maximize Score After N Operations/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:状态压缩 + 动态规划** +### 方法一:状态压缩 + 动态规划 我们可以先预处理得到数组 `nums` 中任意两个数的最大公约数,存储在二维数组 $g$ 中,其中 $g[i][j]$ 表示 $nums[i]$ 和 $nums[j]$ 的最大公约数。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def maxScore(self, nums: List[int]) -> int: @@ -102,10 +96,6 @@ class Solution: return f[-1] ``` -### **Java** - - - ```java class Solution { public int maxScore(int[] nums) { @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +163,6 @@ public: }; ``` -### **Go** - ```go func maxScore(nums []int) int { m := len(nums) @@ -212,8 +198,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function maxScore(nums: number[]): number { const m = nums.length; @@ -256,10 +240,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1700-1799/1799.Maximize Score After N Operations/README_EN.md b/solution/1700-1799/1799.Maximize Score After N Operations/README_EN.md index ba05525821a69..82d8256084d71 100644 --- a/solution/1700-1799/1799.Maximize Score After N Operations/README_EN.md +++ b/solution/1700-1799/1799.Maximize Score After N Operations/README_EN.md @@ -57,7 +57,7 @@ ## Solutions -**Solution 1: State Compression + Dynamic Programming** +### Solution 1: State Compression + Dynamic Programming We can preprocess to get the greatest common divisor of any two numbers in the array `nums`, stored in the two-dimensional array $g$, where $g[i][j]$ represents the greatest common divisor of $nums[i]$ and $nums[j]$. @@ -73,8 +73,6 @@ The time complexity is $O(2^m \times m^2)$, and the space complexity is $O(2^m)$ -### **Python3** - ```python class Solution: def maxScore(self, nums: List[int]) -> int: @@ -97,8 +95,6 @@ class Solution: return f[-1] ``` -### **Java** - ```java class Solution { public int maxScore(int[] nums) { @@ -134,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +162,6 @@ public: }; ``` -### **Go** - ```go func maxScore(nums []int) int { m := len(nums) @@ -205,8 +197,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function maxScore(nums: number[]): number { const m = nums.length; @@ -249,10 +239,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README.md b/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README.md index 9db6c877f825e..c11adb6f1e434 100644 --- a/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README.md +++ b/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:直接模拟** +### 方法一:直接模拟 我们用变量 $t$ 记录当前升序子数组的和,用变量 $ans$ 记录最大的升序子数组和。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def maxAscendingSum(self, nums: List[int]) -> int: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxAscendingSum(int[] nums) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func maxAscendingSum(nums []int) int { ans, t := 0, 0 @@ -149,27 +135,6 @@ func maxAscendingSum(nums []int) int { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int maxAscendingSum(int* nums, int numsSize) { - int res = nums[0]; - int sum = nums[0]; - for (int i = 1; i < numsSize; i++) { - if (nums[i - 1] >= nums[i]) { - res = max(res, sum); - sum = 0; - } - sum += nums[i]; - } - return max(res, sum); -} -``` - -### **TypeScript** - ```ts function maxAscendingSum(nums: number[]): number { const n = nums.length; @@ -186,8 +151,6 @@ function maxAscendingSum(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_ascending_sum(nums: Vec) -> i32 { @@ -206,10 +169,23 @@ impl Solution { } ``` -### **...** - -``` +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +int maxAscendingSum(int* nums, int numsSize) { + int res = nums[0]; + int sum = nums[0]; + for (int i = 1; i < numsSize; i++) { + if (nums[i - 1] >= nums[i]) { + res = max(res, sum); + sum = 0; + } + sum += nums[i]; + } + return max(res, sum); +} ``` + + diff --git a/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README_EN.md b/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README_EN.md index b49337e100f2d..8bf2f40b89139 100644 --- a/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README_EN.md +++ b/solution/1800-1899/1800.Maximum Ascending Subarray Sum/README_EN.md @@ -45,7 +45,7 @@ ## Solutions -**Solution 1: Direct Simulation** +### Solution 1: Direct Simulation We use a variable $t$ to record the current sum of the ascending subarray, and a variable $ans$ to record the maximum sum of the ascending subarray. @@ -59,8 +59,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def maxAscendingSum(self, nums: List[int]) -> int: @@ -74,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxAscendingSum(int[] nums) { @@ -93,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +107,6 @@ public: }; ``` -### **Go** - ```go func maxAscendingSum(nums []int) int { ans, t := 0, 0 @@ -132,27 +124,6 @@ func maxAscendingSum(nums []int) int { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int maxAscendingSum(int* nums, int numsSize) { - int res = nums[0]; - int sum = nums[0]; - for (int i = 1; i < numsSize; i++) { - if (nums[i - 1] >= nums[i]) { - res = max(res, sum); - sum = 0; - } - sum += nums[i]; - } - return max(res, sum); -} -``` - -### **TypeScript** - ```ts function maxAscendingSum(nums: number[]): number { const n = nums.length; @@ -169,8 +140,6 @@ function maxAscendingSum(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_ascending_sum(nums: Vec) -> i32 { @@ -189,10 +158,23 @@ impl Solution { } ``` -### **...** - -``` +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +int maxAscendingSum(int* nums, int numsSize) { + int res = nums[0]; + int sum = nums[0]; + for (int i = 1; i < numsSize; i++) { + if (nums[i - 1] >= nums[i]) { + res = max(res, sum); + sum = 0; + } + sum += nums[i]; + } + return max(res, sum); +} ``` + + diff --git a/solution/1800-1899/1801.Number of Orders in the Backlog/README.md b/solution/1800-1899/1801.Number of Orders in the Backlog/README.md index c6a8697f3e0d9..fe8548598ed32 100644 --- a/solution/1800-1899/1801.Number of Orders in the Backlog/README.md +++ b/solution/1800-1899/1801.Number of Orders in the Backlog/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:优先队列(大小根堆) + 模拟** +### 方法一:优先队列(大小根堆) + 模拟 我们可以使用优先队列(大小根堆)维护当前的积压订单,其中大根堆 `buy` 维护积压的采购订单,小根堆 `sell` 维护积压的销售订单。堆中每个元素是一个二元组 $(price, amount)$,表示价格为 `price` 的订单数量为 `amount`。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int: @@ -113,10 +107,6 @@ class Solution: return sum(v[1] for v in buy + sell) % mod ``` -### **Java** - - - ```java class Solution { public int getNumberOfBacklogOrders(int[][] orders) { @@ -167,8 +157,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -223,8 +211,6 @@ public: }; ``` -### **Go** - ```go func getNumberOfBacklogOrders(orders [][]int) (ans int) { sell := hp{} @@ -281,10 +267,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1801.Number of Orders in the Backlog/README_EN.md b/solution/1800-1899/1801.Number of Orders in the Backlog/README_EN.md index 9fc03f54a15e1..40b908a2baff3 100644 --- a/solution/1800-1899/1801.Number of Orders in the Backlog/README_EN.md +++ b/solution/1800-1899/1801.Number of Orders in the Backlog/README_EN.md @@ -61,7 +61,7 @@ Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995 ## Solutions -**Solution 1: Priority Queue (Max-Min Heap) + Simulation** +### Solution 1: Priority Queue (Max-Min Heap) + Simulation We can use a priority queue (max-min heap) to maintain the current backlog of orders, where the max heap `buy` maintains the backlog of purchase orders, and the min heap `sell` maintains the backlog of sales orders. Each element in the heap is a tuple $(price, amount)$, indicating that the number of orders at price `price` is `amount`. @@ -73,8 +73,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int: @@ -100,16 +98,10 @@ class Solution: a = 0 if a: heappush(sell, (p, a)) - ans, mod = 0, 10**9 + 7 - for _, v in buy: - ans = (ans + v) % mod - for _, v in sell: - ans = (ans + v) % mod - return ans + mod = 10**9 + 7 + return sum(v[1] for v in buy + sell) % mod ``` -### **Java** - ```java class Solution { public int getNumberOfBacklogOrders(int[][] orders) { @@ -160,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -216,8 +206,6 @@ public: }; ``` -### **Go** - ```go func getNumberOfBacklogOrders(orders [][]int) (ans int) { sell := hp{} @@ -274,10 +262,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README.md b/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README.md index bbe53f1fe2603..0b673897b026b 100644 --- a/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README.md +++ b/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 根据题目描述,如果我们确定了 $nums[index]$ 的值为 $x$,此时我们可以找到一个最小的数组总和。也就是说,在 $index$ 左侧的数组元素从 $x-1$ 一直递减到 $1$,如果还有剩余的元素,那么剩余的元素都为 $1$;同理,在 $index$ 及右侧的数组元素从 $x$ 一直递减到 $1$,如果还有剩余的元素,那么剩余的元素都为 $1$。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def maxValue(self, n: int, index: int, maxSum: int) -> int: @@ -89,10 +83,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int maxValue(int n, int index, int maxSum) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func maxValue(n int, index int, maxSum int) int { sum := func(x, cnt int) int { @@ -154,10 +140,6 @@ func maxValue(n int, index int, maxSum int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md b/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md index 1fbde3299aa1b..f0144c37385e4 100644 --- a/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md +++ b/solution/1800-1899/1802.Maximum Value at a Given Index in a Bounded Array/README_EN.md @@ -45,7 +45,7 @@ There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search According to the problem description, if we determine the value of $nums[index]$ as $x$, we can find a minimum array sum. That is, the elements on the left side of $index$ in the array decrease from $x-1$ to $1$, and if there are remaining elements, the remaining elements are all $1$; similarly, the elements at $index$ and on the right side of the array decrease from $x$ to $1$, and if there are remaining elements, the remaining elements are all $1$. @@ -64,8 +64,6 @@ The time complexity is $O(\log M)$, where $M=maxSum$. The space complexity is $O -### **Python3** - ```python class Solution: def maxValue(self, n: int, index: int, maxSum: int) -> int: @@ -84,8 +82,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { public int maxValue(int n, int index, int maxSum) { @@ -107,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +124,6 @@ public: }; ``` -### **Go** - ```go func maxValue(n int, index int, maxSum int) int { sum := func(x, cnt int) int { @@ -147,10 +139,6 @@ func maxValue(n int, index int, maxSum int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1803.Count Pairs With XOR in a Range/README.md b/solution/1800-1899/1803.Count Pairs With XOR in a Range/README.md index b9c0413fb8f16..b2c3732ae67cf 100644 --- a/solution/1800-1899/1803.Count Pairs With XOR in a Range/README.md +++ b/solution/1800-1899/1803.Count Pairs With XOR in a Range/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:0-1 字典树** +### 方法一:0-1 字典树 对于这种区间 $[low, high]$ 统计的问题,我们可以考虑将其转换为统计 $[0, high]$ 和 $[0, low - 1]$ 的问题,然后相减即可得到答案。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Trie: def __init__(self): @@ -125,10 +119,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Trie { private Trie[] children = new Trie[2]; @@ -177,8 +167,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -234,8 +222,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [2]*Trie @@ -284,10 +270,6 @@ func countPairs(nums []int, low int, high int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md b/solution/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md index ec418767ff1d6..23a3ce2943b05 100644 --- a/solution/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md +++ b/solution/1800-1899/1803.Count Pairs With XOR in a Range/README_EN.md @@ -49,7 +49,7 @@ ## Solutions -**Solution 1: 0-1 Trie** +### Solution 1: 0-1 Trie For this kind of problem that counts the interval $[low, high]$, we can consider converting it into counting $[0, high]$ and $[0, low - 1]$, and then subtracting the latter from the former to get the answer. @@ -76,8 +76,6 @@ The time complexity is $O(n \times \log M)$, and the space complexity is $O(n \t -### **Python3** - ```python class Trie: def __init__(self): @@ -119,8 +117,6 @@ class Solution: return ans ``` -### **Java** - ```java class Trie { private Trie[] children = new Trie[2]; @@ -169,8 +165,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -226,8 +220,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [2]*Trie @@ -276,10 +268,6 @@ func countPairs(nums []int, low int, high int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1804.Implement Trie II (Prefix Tree)/README.md b/solution/1800-1899/1804.Implement Trie II (Prefix Tree)/README.md index 9d51f49a09c8e..e98113fa39981 100644 --- a/solution/1800-1899/1804.Implement Trie II (Prefix Tree)/README.md +++ b/solution/1800-1899/1804.Implement Trie II (Prefix Tree)/README.md @@ -54,9 +54,7 @@ trie.countWordsStartingWith("app"); // 返回 0 ## 解法 - - -**方法一:数组实现前缀树** +### 方法一:数组实现前缀树 前缀树每个节点包括三部分: @@ -94,10 +92,6 @@ trie.countWordsStartingWith("app"); // 返回 0 -### **Python3** - - - ```python class Trie: def __init__(self): @@ -148,10 +142,6 @@ class Trie: # obj.erase(word) ``` -### **Java** - - - ```java class Trie { private Trie[] children = new Trie[26]; @@ -217,8 +207,6 @@ class Trie { */ ``` -### **C++** - ```cpp class Trie { public: @@ -288,8 +276,6 @@ private: */ ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -360,10 +346,6 @@ func (this *Trie) search(word string) *Trie { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1804.Implement Trie II (Prefix Tree)/README_EN.md b/solution/1800-1899/1804.Implement Trie II (Prefix Tree)/README_EN.md index eb3a06340bfa5..5524137ed7560 100644 --- a/solution/1800-1899/1804.Implement Trie II (Prefix Tree)/README_EN.md +++ b/solution/1800-1899/1804.Implement Trie II (Prefix Tree)/README_EN.md @@ -51,7 +51,7 @@ trie.countWordsStartingWith("app"); // return 0 ## Solutions -**Solution 1: Implement Trie with Array** +### Solution 1: Implement Trie with Array Each node in the Trie includes three parts: @@ -89,8 +89,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string. -### **Python3** - ```python class Trie: def __init__(self): @@ -141,8 +139,6 @@ class Trie: # obj.erase(word) ``` -### **Java** - ```java class Trie { private Trie[] children = new Trie[26]; @@ -208,8 +204,6 @@ class Trie { */ ``` -### **C++** - ```cpp class Trie { public: @@ -279,8 +273,6 @@ private: */ ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -351,10 +343,6 @@ func (this *Trie) search(word string) *Trie { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1805.Number of Different Integers in a String/README.md b/solution/1800-1899/1805.Number of Different Integers in a String/README.md index fa81aea39f54a..d49407504cd8e 100644 --- a/solution/1800-1899/1805.Number of Different Integers in a String/README.md +++ b/solution/1800-1899/1805.Number of Different Integers in a String/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:双指针 + 模拟** +### 方法一:双指针 + 模拟 遍历字符串 `word`,找到每个整数的起始位置和结束位置,截取出这一个子串,将其存入哈希表 $s$ 中。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def numDifferentIntegers(self, word: str) -> int: @@ -86,10 +80,6 @@ class Solution: return len(s) ``` -### **Java** - - - ```java class Solution { public int numDifferentIntegers(String word) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func numDifferentIntegers(word string) int { s := map[string]struct{}{} @@ -158,8 +144,6 @@ func numDifferentIntegers(word string) int { } ``` -### **TypeScript** - ```ts function numDifferentIntegers(word: string): number { return new Set( @@ -173,8 +157,6 @@ function numDifferentIntegers(word: string): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -203,10 +185,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1805.Number of Different Integers in a String/README_EN.md b/solution/1800-1899/1805.Number of Different Integers in a String/README_EN.md index cb7d8d4a3ad19..0ea45be87ff49 100644 --- a/solution/1800-1899/1805.Number of Different Integers in a String/README_EN.md +++ b/solution/1800-1899/1805.Number of Different Integers in a String/README_EN.md @@ -47,7 +47,7 @@ the leading zeros are ignored when comparing their decimal values. ## Solutions -**Solution 1: Double Pointers + Simulation** +### Solution 1: Double Pointers + Simulation Traverse the string `word`, find the start and end positions of each integer, cut out this substring, and store it in the hash set $s$. @@ -59,8 +59,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def numDifferentIntegers(self, word: str) -> int: @@ -79,8 +77,6 @@ class Solution: return len(s) ``` -### **Java** - ```java class Solution { public int numDifferentIntegers(String word) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +120,6 @@ public: }; ``` -### **Go** - ```go func numDifferentIntegers(word string) int { s := map[string]struct{}{} @@ -149,8 +141,6 @@ func numDifferentIntegers(word string) int { } ``` -### **TypeScript** - ```ts function numDifferentIntegers(word: string): number { return new Set( @@ -164,8 +154,6 @@ function numDifferentIntegers(word: string): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -194,10 +182,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README.md b/solution/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README.md index 991ff602a4cbd..2fd99179f3474 100644 --- a/solution/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README.md +++ b/solution/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:找规律 + 模拟** +### 方法一:找规律 + 模拟 我们观察数字的变化规律,发现: @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def reinitializePermutation(self, n: int) -> int: @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int reinitializePermutation(int n) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func reinitializePermutation(n int) (ans int) { for i := 1; ; { @@ -158,10 +144,6 @@ func reinitializePermutation(n int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README_EN.md b/solution/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README_EN.md index a6445ba262d44..c32c4d64df45c 100644 --- a/solution/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README_EN.md +++ b/solution/1800-1899/1806.Minimum Number of Operations to Reinitialize a Permutation/README_EN.md @@ -56,7 +56,7 @@ So it takes only 2 operations. ## Solutions -**Solution 1: Find Pattern + Simulation** +### Solution 1: Find Pattern + Simulation We observe the change pattern of the numbers and find that: @@ -73,8 +73,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def reinitializePermutation(self, n: int) -> int: @@ -89,8 +87,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int reinitializePermutation(int n) { @@ -110,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +126,6 @@ public: }; ``` -### **Go** - ```go func reinitializePermutation(n int) (ans int) { for i := 1; ; { @@ -150,10 +142,6 @@ func reinitializePermutation(n int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1807.Evaluate the Bracket Pairs of a String/README.md b/solution/1800-1899/1807.Evaluate the Bracket Pairs of a String/README.md index 5bf3d3f6e9c4c..b537550c30a14 100644 --- a/solution/1800-1899/1807.Evaluate the Bracket Pairs of a String/README.md +++ b/solution/1800-1899/1807.Evaluate the Bracket Pairs of a String/README.md @@ -74,9 +74,7 @@ ## 解法 - - -**方法一:哈希表 + 模拟** +### 方法一:哈希表 + 模拟 我们先用哈希表 $d$ 记录 `knowledge` 中的键值对。 @@ -86,10 +84,6 @@ -### **Python3** - - - ```python class Solution: def evaluate(self, s: str, knowledge: List[List[str]]) -> str: @@ -107,10 +101,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String evaluate(String s, List> knowledge) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +147,6 @@ public: }; ``` -### **Go** - ```go func evaluate(s string, knowledge [][]string) string { d := map[string]string{} @@ -188,8 +174,6 @@ func evaluate(s string, knowledge [][]string) string { } ``` -### **TypeScript** - ```ts function evaluate(s: string, knowledge: string[][]): string { const n = s.length; @@ -213,8 +197,6 @@ function evaluate(s: string, knowledge: string[][]): string { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -248,10 +230,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1807.Evaluate the Bracket Pairs of a String/README_EN.md b/solution/1800-1899/1807.Evaluate the Bracket Pairs of a String/README_EN.md index 20ce8b2df0a7b..79c298bdcc3aa 100644 --- a/solution/1800-1899/1807.Evaluate the Bracket Pairs of a String/README_EN.md +++ b/solution/1800-1899/1807.Evaluate the Bracket Pairs of a String/README_EN.md @@ -70,7 +70,7 @@ Notice that the "a"s not in a bracket pair are not evaluated. ## Solutions -**Solution 1: Hash Table + Simulation** +### Solution 1: Hash Table + Simulation First, we use a hash table $d$ to record the key-value pairs in `knowledge`. @@ -80,8 +80,6 @@ The time complexity is $O(n + m)$, and the space complexity is $O(L)$. Here, $n$ -### **Python3** - ```python class Solution: def evaluate(self, s: str, knowledge: List[List[str]]) -> str: @@ -99,8 +97,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String evaluate(String s, List> knowledge) { @@ -123,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +143,6 @@ public: }; ``` -### **Go** - ```go func evaluate(s string, knowledge [][]string) string { d := map[string]string{} @@ -178,8 +170,6 @@ func evaluate(s string, knowledge [][]string) string { } ``` -### **TypeScript** - ```ts function evaluate(s: string, knowledge: string[][]): string { const n = s.length; @@ -203,8 +193,6 @@ function evaluate(s: string, knowledge: string[][]): string { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -238,10 +226,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1808.Maximize Number of Nice Divisors/README.md b/solution/1800-1899/1808.Maximize Number of Nice Divisors/README.md index 45c7e0f4ca0ba..8e10259a1f93c 100644 --- a/solution/1800-1899/1808.Maximize Number of Nice Divisors/README.md +++ b/solution/1800-1899/1808.Maximize Number of Nice Divisors/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:问题转换 + 快速幂** +### 方法一:问题转换 + 快速幂 我们可以将 $n$ 进行质因数分解,即 $n = a_1^{k_1} \times a_2^{k_2} \times\cdots \times a_m^{k_m}$,其中 $a_i$ 为质因子,而 $k_i$ 为质因子 $a_i$ 的指数。由于 $n$ 的质因子个数不超过 $primeFactors$ 个,因此 $k_1 + k_2 + \cdots + k_m \leq primeFactors$。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def maxNiceDivisors(self, primeFactors: int) -> int: @@ -84,10 +78,6 @@ class Solution: return 2 * pow(3, primeFactors // 3, mod) % mod ``` -### **Java** - - - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go func maxNiceDivisors(primeFactors int) int { if primeFactors < 4 { @@ -177,8 +163,6 @@ func maxNiceDivisors(primeFactors int) int { } ``` -### **JavaScript** - ```js /** * @param {number} primeFactors @@ -210,10 +194,6 @@ var maxNiceDivisors = function (primeFactors) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md b/solution/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md index e011744cdf904..84ab04877bd16 100644 --- a/solution/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md +++ b/solution/1800-1899/1808.Maximize Number of Nice Divisors/README_EN.md @@ -42,7 +42,7 @@ There is not other value of n that has at most 5 prime factors and more nice div ## Solutions -**Solution 1: Problem Transformation + Fast Power** +### Solution 1: Problem Transformation + Fast Power We can factorize $n$ into prime factors, i.e., $n = a_1^{k_1} \times a_2^{k_2} \times\cdots \times a_m^{k_m}$, where $a_i$ is a prime factor and $k_i$ is the exponent of the prime factor $a_i$. Since the number of prime factors of $n$ does not exceed `primeFactors`, we have $k_1 + k_2 + \cdots + k_m \leq primeFactors$. @@ -61,8 +61,6 @@ The time complexity is $O(\log n)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def maxNiceDivisors(self, primeFactors: int) -> int: @@ -76,8 +74,6 @@ class Solution: return 2 * pow(3, primeFactors // 3, mod) % mod ``` -### **Java** - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -108,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +133,6 @@ public: }; ``` -### **Go** - ```go func maxNiceDivisors(primeFactors int) int { if primeFactors < 4 { @@ -167,8 +159,6 @@ func maxNiceDivisors(primeFactors int) int { } ``` -### **JavaScript** - ```js /** * @param {number} primeFactors @@ -200,10 +190,6 @@ var maxNiceDivisors = function (primeFactors) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1809.Ad-Free Sessions/README.md b/solution/1800-1899/1809.Ad-Free Sessions/README.md index 1af1273b0d829..8602a4303f955 100644 --- a/solution/1800-1899/1809.Ad-Free Sessions/README.md +++ b/solution/1800-1899/1809.Ad-Free Sessions/README.md @@ -87,14 +87,10 @@ Ads table: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT session_id @@ -110,3 +106,5 @@ WHERE ``` + + diff --git a/solution/1800-1899/1809.Ad-Free Sessions/README_EN.md b/solution/1800-1899/1809.Ad-Free Sessions/README_EN.md index 107a83945540c..29a15f2edf625 100644 --- a/solution/1800-1899/1809.Ad-Free Sessions/README_EN.md +++ b/solution/1800-1899/1809.Ad-Free Sessions/README_EN.md @@ -85,9 +85,9 @@ We can see that sessions 1 and 4 had at least one ad. Sessions 2, 3, and 5 did n ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -104,3 +104,5 @@ WHERE ``` + + diff --git a/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README.md b/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README.md index 621eb985b7f6a..9860a2a89d123 100644 --- a/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README.md +++ b/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README.md @@ -93,16 +93,10 @@ ## 解法 - - -**方法一:DFS 建图 + 堆优化版 Dijkstra 算法** +### 方法一:DFS 建图 + 堆优化版 Dijkstra 算法 -### **Python3** - - - ```python # """ # This is GridMaster's API interface. @@ -166,10 +160,6 @@ class Solution(object): return 0 ``` -### **Java** - - - ```java /** * // This is the GridMaster's API interface. @@ -239,10 +229,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README_EN.md b/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README_EN.md index dfeb8e5db9316..1027a9f1a41a7 100644 --- a/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README_EN.md +++ b/solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/README_EN.md @@ -89,9 +89,9 @@ We now know that the target is the cell (1, 0), and the minimum total cost to re ## Solutions - +### Solution 1 -### **Python3** + ```python # """ @@ -156,8 +156,6 @@ class Solution(object): return 0 ``` -### **Java** - ```java /** * // This is the GridMaster's API interface. @@ -227,10 +225,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1811.Find Interview Candidates/README.md b/solution/1800-1899/1811.Find Interview Candidates/README.md index 7b0b0e663b50d..0b2a72cf18857 100644 --- a/solution/1800-1899/1811.Find Interview Candidates/README.md +++ b/solution/1800-1899/1811.Find Interview Candidates/README.md @@ -105,14 +105,10 @@ Quarz在连续5场竞赛中赢得了奖牌(190, 191, 192, 193, and 194), 所以 ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -156,3 +152,5 @@ FROM ``` + + diff --git a/solution/1800-1899/1811.Find Interview Candidates/README_EN.md b/solution/1800-1899/1811.Find Interview Candidates/README_EN.md index 801dac38d8f8d..4fdb2be6a4f33 100644 --- a/solution/1800-1899/1811.Find Interview Candidates/README_EN.md +++ b/solution/1800-1899/1811.Find Interview Candidates/README_EN.md @@ -102,9 +102,9 @@ Quarz won a medal in 5 consecutive contests (190, 191, 192, 193, and 194), so we ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -149,3 +149,5 @@ FROM ``` + + diff --git a/solution/1800-1899/1812.Determine Color of a Chessboard Square/README.md b/solution/1800-1899/1812.Determine Color of a Chessboard Square/README.md index d041ac9c64815..8715f6361724b 100644 --- a/solution/1800-1899/1812.Determine Color of a Chessboard Square/README.md +++ b/solution/1800-1899/1812.Determine Color of a Chessboard Square/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:找规律** +### 方法一:找规律 观察棋盘我们发现,颜色相同的两个格子 $(x_1, y_1)$ 和 $(x_2, y_2)$ 满足 $x_1 + y_1$ 和 $x_2 + y_2$ 均为奇数或偶数。 @@ -63,20 +61,12 @@ -### **Python3** - - - ```python class Solution: def squareIsWhite(self, coordinates: str) -> bool: return (ord(coordinates[0]) + ord(coordinates[1])) % 2 == 1 ``` -### **Java** - - - ```java class Solution { public boolean squareIsWhite(String coordinates) { @@ -85,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,38 +84,18 @@ public: }; ``` -### **Go** - ```go func squareIsWhite(coordinates string) bool { return (coordinates[0]+coordinates[1])%2 == 1 } ``` -### **JavaScript** - -```js -/** - * @param {string} coordinates - * @return {boolean} - */ -var squareIsWhite = function (coordinates) { - const x = coordinates.charAt(0).charCodeAt(); - const y = coordinates.charAt(1).charCodeAt(); - return (x + y) % 2 == 1; -}; -``` - -### **TypeScript** - ```ts function squareIsWhite(coordinates: string): boolean { return ((coordinates.charCodeAt(0) + coordinates.charCodeAt(1)) & 1) === 1; } ``` -### **Rust** - ```rust impl Solution { pub fn square_is_white(coordinates: String) -> bool { @@ -137,7 +105,17 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {string} coordinates + * @return {boolean} + */ +var squareIsWhite = function (coordinates) { + const x = coordinates.charAt(0).charCodeAt(); + const y = coordinates.charAt(1).charCodeAt(); + return (x + y) % 2 == 1; +}; +``` ```c bool squareIsWhite(char* coordinates) { @@ -145,10 +123,6 @@ bool squareIsWhite(char* coordinates) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1812.Determine Color of a Chessboard Square/README_EN.md b/solution/1800-1899/1812.Determine Color of a Chessboard Square/README_EN.md index 8504ef7ccf717..fedc17c99f17c 100644 --- a/solution/1800-1899/1812.Determine Color of a Chessboard Square/README_EN.md +++ b/solution/1800-1899/1812.Determine Color of a Chessboard Square/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Find the Pattern** +### Solution 1: Find the Pattern By observing the chessboard, we find that two squares $(x_1, y_1)$ and $(x_2, y_2)$ with the same color satisfy that both $x_1 + y_1$ and $x_2 + y_2$ are either odd or even. @@ -57,16 +57,12 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def squareIsWhite(self, coordinates: str) -> bool: return (ord(coordinates[0]) + ord(coordinates[1])) % 2 == 1 ``` -### **Java** - ```java class Solution { public boolean squareIsWhite(String coordinates) { @@ -75,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -86,38 +80,18 @@ public: }; ``` -### **Go** - ```go func squareIsWhite(coordinates string) bool { return (coordinates[0]+coordinates[1])%2 == 1 } ``` -### **JavaScript** - -```js -/** - * @param {string} coordinates - * @return {boolean} - */ -var squareIsWhite = function (coordinates) { - const x = coordinates.charAt(0).charCodeAt(); - const y = coordinates.charAt(1).charCodeAt(); - return (x + y) % 2 == 1; -}; -``` - -### **TypeScript** - ```ts function squareIsWhite(coordinates: string): boolean { return ((coordinates.charCodeAt(0) + coordinates.charCodeAt(1)) & 1) === 1; } ``` -### **Rust** - ```rust impl Solution { pub fn square_is_white(coordinates: String) -> bool { @@ -127,7 +101,17 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {string} coordinates + * @return {boolean} + */ +var squareIsWhite = function (coordinates) { + const x = coordinates.charAt(0).charCodeAt(); + const y = coordinates.charAt(1).charCodeAt(); + return (x + y) % 2 == 1; +}; +``` ```c bool squareIsWhite(char* coordinates) { @@ -135,10 +119,6 @@ bool squareIsWhite(char* coordinates) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1813.Sentence Similarity III/README.md b/solution/1800-1899/1813.Sentence Similarity III/README.md index 2e6f17b98871c..c47cac6500d0d 100644 --- a/solution/1800-1899/1813.Sentence Similarity III/README.md +++ b/solution/1800-1899/1813.Sentence Similarity III/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们将两个句子按照空格分割成两个单词数组 `words1` 和 `words2`,假设 `words1` 和 `words2` 的长度分别为 $m$ 和 $n$,不妨设 $m \geq n$。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool: @@ -87,10 +81,6 @@ class Solution: return i + j >= n ``` -### **Java** - - - ```java class Solution { public boolean areSentencesSimilar(String sentence1, String sentence2) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +136,6 @@ public: }; ``` -### **Go** - ```go func areSentencesSimilar(sentence1 string, sentence2 string) bool { words1, words2 := strings.Fields(sentence1), strings.Fields(sentence2) @@ -168,8 +154,6 @@ func areSentencesSimilar(sentence1 string, sentence2 string) bool { } ``` -### **TypeScript** - ```ts function areSentencesSimilar(sentence1: string, sentence2: string): boolean { const words1 = sentence1.split(' '); @@ -189,10 +173,6 @@ function areSentencesSimilar(sentence1: string, sentence2: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1813.Sentence Similarity III/README_EN.md b/solution/1800-1899/1813.Sentence Similarity III/README_EN.md index fc79dcd1d8981..97c2f635b3401 100644 --- a/solution/1800-1899/1813.Sentence Similarity III/README_EN.md +++ b/solution/1800-1899/1813.Sentence Similarity III/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We split the two sentences into two word arrays `words1` and `words2` by spaces. Let the lengths of `words1` and `words2` be $m$ and $n$, respectively, and assume that $m \ge nn. @@ -58,8 +58,6 @@ The time complexity is $O(L)$, and the space complexity is $O(L)$, where $L$ is -### **Python3** - ```python class Solution: def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool: @@ -76,8 +74,6 @@ class Solution: return i + j >= n ``` -### **Java** - ```java class Solution { public boolean areSentencesSimilar(String sentence1, String sentence2) { @@ -101,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +129,6 @@ public: }; ``` -### **Go** - ```go func areSentencesSimilar(sentence1 string, sentence2 string) bool { words1, words2 := strings.Fields(sentence1), strings.Fields(sentence2) @@ -155,8 +147,6 @@ func areSentencesSimilar(sentence1 string, sentence2 string) bool { } ``` -### **TypeScript** - ```ts function areSentencesSimilar(sentence1: string, sentence2: string): boolean { const words1 = sentence1.split(' '); @@ -176,10 +166,6 @@ function areSentencesSimilar(sentence1: string, sentence2: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1814.Count Nice Pairs in an Array/README.md b/solution/1800-1899/1814.Count Nice Pairs in an Array/README.md index cbca81f3085cf..6e4f9c31b990b 100644 --- a/solution/1800-1899/1814.Count Nice Pairs in an Array/README.md +++ b/solution/1800-1899/1814.Count Nice Pairs in an Array/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:式子变换 + 哈希表** +### 方法一:式子变换 + 哈希表 对于下标对 $(i, j)$,如果满足条件,那么有 $nums[i] + rev(nums[j]) = nums[j] + rev(nums[i])$,即 $nums[i] - nums[j] = rev(nums[j]) - rev(nums[i])$。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def countNicePairs(self, nums: List[int]) -> int: @@ -76,30 +70,6 @@ class Solution: return sum(v * (v - 1) // 2 for v in cnt.values()) % mod ``` -```python -class Solution: - def countNicePairs(self, nums: List[int]) -> int: - def rev(x): - y = 0 - while x: - y = y * 10 + x % 10 - x //= 10 - return y - - ans = 0 - mod = 10**9 + 7 - cnt = Counter() - for x in nums: - y = x - rev(x) - ans += cnt[y] - cnt[y] += 1 - return ans % mod -``` - -### **Java** - - - ```java class Solution { public int countNicePairs(int[] nums) { @@ -126,32 +96,6 @@ class Solution { } ``` -```java -class Solution { - public int countNicePairs(int[] nums) { - Map cnt = new HashMap<>(); - final int mod = (int) 1e9 + 7; - int ans = 0; - for (int x : nums) { - int y = x - rev(x); - ans = (ans + cnt.getOrDefault(y, 0)) % mod; - cnt.merge(y, 1, Integer::sum); - } - return ans; - } - - private int rev(int x) { - int y = 0; - for (; x > 0; x /= 10) { - y = y * 10 + x % 10; - } - return y; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -178,31 +122,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countNicePairs(vector& nums) { - auto rev = [](int x) { - int y = 0; - for (; x > 0; x /= 10) { - y = y * 10 + x % 10; - } - return y; - }; - unordered_map cnt; - int ans = 0; - const int mod = 1e9 + 7; - for (int& x : nums) { - int y = x - rev(x); - ans = (ans + cnt[y]++) % mod; - } - return ans; - } -}; -``` - -### **Go** - ```go func countNicePairs(nums []int) (ans int) { rev := func(x int) (y int) { @@ -224,52 +143,26 @@ func countNicePairs(nums []int) (ans int) { } ``` -```go -func countNicePairs(nums []int) (ans int) { - rev := func(x int) (y int) { - for ; x > 0; x /= 10 { - y = y*10 + x%10 - } - return - } - cnt := map[int]int{} - const mod int = 1e9 + 7 - for _, x := range nums { - y := x - rev(x) - ans = (ans + cnt[y]) % mod - cnt[y]++ - } - return -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var countNicePairs = function (nums) { - const rev = x => { +```ts +function countNicePairs(nums: number[]): number { + const rev = (x: number): number => { let y = 0; - for (; x > 0; x = Math.floor(x / 10)) { + while (x) { y = y * 10 + (x % 10); + x = Math.floor(x / 10); } return y; }; - const cnt = new Map(); + const mod = 10 ** 9 + 7; + const cnt = new Map(); + let ans = 0; for (const x of nums) { const y = x - rev(x); - cnt.set(y, (cnt.get(y) | 0) + 1); - } - let ans = 0; - const mod = 1e9 + 7; - for (const [_, v] of cnt) { - ans = (ans + Math.floor((v * (v - 1)) / 2)) % mod; + ans = (ans + (cnt.get(y) ?? 0)) % mod; + cnt.set(y, (cnt.get(y) ?? 0) + 1); } return ans; -}; +} ``` ```js @@ -285,45 +178,20 @@ var countNicePairs = function (nums) { } return y; }; - let ans = 0; - const mod = 1e9 + 7; const cnt = new Map(); for (const x of nums) { const y = x - rev(x); - const v = cnt.get(y) | 0; - ans = (ans + v) % mod; - cnt.set(y, v + 1); + cnt.set(y, (cnt.get(y) | 0) + 1); } - return ans; -}; -``` - -### **TypeScript** - -```ts -function countNicePairs(nums: number[]): number { - const rev = (x: number): number => { - let y = 0; - while (x) { - y = y * 10 + (x % 10); - x = Math.floor(x / 10); - } - return y; - }; - const mod = 10 ** 9 + 7; - const cnt = new Map(); let ans = 0; - for (const x of nums) { - const y = x - rev(x); - ans = (ans + (cnt.get(y) ?? 0)) % mod; - cnt.set(y, (cnt.get(y) ?? 0) + 1); + const mod = 1e9 + 7; + for (const [_, v] of cnt) { + ans = (ans + Math.floor((v * (v - 1)) / 2)) % mod; } return ans; -} +}; ``` -### **C#** - ```cs public class Solution { public int CountNicePairs(int[] nums) { @@ -351,10 +219,124 @@ public class Solution { } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def countNicePairs(self, nums: List[int]) -> int: + def rev(x): + y = 0 + while x: + y = y * 10 + x % 10 + x //= 10 + return y + ans = 0 + mod = 10**9 + 7 + cnt = Counter() + for x in nums: + y = x - rev(x) + ans += cnt[y] + cnt[y] += 1 + return ans % mod ``` +```java +class Solution { + public int countNicePairs(int[] nums) { + Map cnt = new HashMap<>(); + final int mod = (int) 1e9 + 7; + int ans = 0; + for (int x : nums) { + int y = x - rev(x); + ans = (ans + cnt.getOrDefault(y, 0)) % mod; + cnt.merge(y, 1, Integer::sum); + } + return ans; + } + + private int rev(int x) { + int y = 0; + for (; x > 0; x /= 10) { + y = y * 10 + x % 10; + } + return y; + } +} +``` + +```cpp +class Solution { +public: + int countNicePairs(vector& nums) { + auto rev = [](int x) { + int y = 0; + for (; x > 0; x /= 10) { + y = y * 10 + x % 10; + } + return y; + }; + unordered_map cnt; + int ans = 0; + const int mod = 1e9 + 7; + for (int& x : nums) { + int y = x - rev(x); + ans = (ans + cnt[y]++) % mod; + } + return ans; + } +}; +``` + +```go +func countNicePairs(nums []int) (ans int) { + rev := func(x int) (y int) { + for ; x > 0; x /= 10 { + y = y*10 + x%10 + } + return + } + cnt := map[int]int{} + const mod int = 1e9 + 7 + for _, x := range nums { + y := x - rev(x) + ans = (ans + cnt[y]) % mod + cnt[y]++ + } + return +} +``` + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var countNicePairs = function (nums) { + const rev = x => { + let y = 0; + for (; x > 0; x = Math.floor(x / 10)) { + y = y * 10 + (x % 10); + } + return y; + }; + let ans = 0; + const mod = 1e9 + 7; + const cnt = new Map(); + for (const x of nums) { + const y = x - rev(x); + const v = cnt.get(y) | 0; + ans = (ans + v) % mod; + cnt.set(y, v + 1); + } + return ans; +}; ``` + + diff --git a/solution/1800-1899/1814.Count Nice Pairs in an Array/README_EN.md b/solution/1800-1899/1814.Count Nice Pairs in an Array/README_EN.md index 515aecbbcf281..4d73a664b7cc4 100644 --- a/solution/1800-1899/1814.Count Nice Pairs in an Array/README_EN.md +++ b/solution/1800-1899/1814.Count Nice Pairs in an Array/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Equation Transformation + Hash Table** +### Solution 1: Equation Transformation + Hash Table For the index pair $(i, j)$, if it satisfies the condition, then we have $nums[i] + rev(nums[j]) = nums[j] + rev(nums[i])$, which means $nums[i] - nums[j] = rev(nums[j]) - rev(nums[i])$. @@ -53,8 +53,6 @@ The time complexity is $O(n \times \log M)$, where $n$ and $M$ are the length of -### **Python3** - ```python class Solution: def countNicePairs(self, nums: List[int]) -> int: @@ -70,28 +68,6 @@ class Solution: return sum(v * (v - 1) // 2 for v in cnt.values()) % mod ``` -```python -class Solution: - def countNicePairs(self, nums: List[int]) -> int: - def rev(x): - y = 0 - while x: - y = y * 10 + x % 10 - x //= 10 - return y - - ans = 0 - mod = 10**9 + 7 - cnt = Counter() - for x in nums: - y = x - rev(x) - ans += cnt[y] - cnt[y] += 1 - return ans % mod -``` - -### **Java** - ```java class Solution { public int countNicePairs(int[] nums) { @@ -118,32 +94,6 @@ class Solution { } ``` -```java -class Solution { - public int countNicePairs(int[] nums) { - Map cnt = new HashMap<>(); - final int mod = (int) 1e9 + 7; - int ans = 0; - for (int x : nums) { - int y = x - rev(x); - ans = (ans + cnt.getOrDefault(y, 0)) % mod; - cnt.merge(y, 1, Integer::sum); - } - return ans; - } - - private int rev(int x) { - int y = 0; - for (; x > 0; x /= 10) { - y = y * 10 + x % 10; - } - return y; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -170,31 +120,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countNicePairs(vector& nums) { - auto rev = [](int x) { - int y = 0; - for (; x > 0; x /= 10) { - y = y * 10 + x % 10; - } - return y; - }; - unordered_map cnt; - int ans = 0; - const int mod = 1e9 + 7; - for (int& x : nums) { - int y = x - rev(x); - ans = (ans + cnt[y]++) % mod; - } - return ans; - } -}; -``` - -### **Go** - ```go func countNicePairs(nums []int) (ans int) { rev := func(x int) (y int) { @@ -216,52 +141,26 @@ func countNicePairs(nums []int) (ans int) { } ``` -```go -func countNicePairs(nums []int) (ans int) { - rev := func(x int) (y int) { - for ; x > 0; x /= 10 { - y = y*10 + x%10 - } - return - } - cnt := map[int]int{} - const mod int = 1e9 + 7 - for _, x := range nums { - y := x - rev(x) - ans = (ans + cnt[y]) % mod - cnt[y]++ - } - return -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var countNicePairs = function (nums) { - const rev = x => { +```ts +function countNicePairs(nums: number[]): number { + const rev = (x: number): number => { let y = 0; - for (; x > 0; x = Math.floor(x / 10)) { + while (x) { y = y * 10 + (x % 10); + x = Math.floor(x / 10); } return y; }; - const cnt = new Map(); + const mod = 10 ** 9 + 7; + const cnt = new Map(); + let ans = 0; for (const x of nums) { const y = x - rev(x); - cnt.set(y, (cnt.get(y) | 0) + 1); - } - let ans = 0; - const mod = 1e9 + 7; - for (const [_, v] of cnt) { - ans = (ans + Math.floor((v * (v - 1)) / 2)) % mod; + ans = (ans + (cnt.get(y) ?? 0)) % mod; + cnt.set(y, (cnt.get(y) ?? 0) + 1); } return ans; -}; +} ``` ```js @@ -277,45 +176,20 @@ var countNicePairs = function (nums) { } return y; }; - let ans = 0; - const mod = 1e9 + 7; const cnt = new Map(); for (const x of nums) { const y = x - rev(x); - const v = cnt.get(y) | 0; - ans = (ans + v) % mod; - cnt.set(y, v + 1); + cnt.set(y, (cnt.get(y) | 0) + 1); } - return ans; -}; -``` - -### **TypeScript** - -```ts -function countNicePairs(nums: number[]): number { - const rev = (x: number): number => { - let y = 0; - while (x) { - y = y * 10 + (x % 10); - x = Math.floor(x / 10); - } - return y; - }; - const mod = 10 ** 9 + 7; - const cnt = new Map(); let ans = 0; - for (const x of nums) { - const y = x - rev(x); - ans = (ans + (cnt.get(y) ?? 0)) % mod; - cnt.set(y, (cnt.get(y) ?? 0) + 1); + const mod = 1e9 + 7; + for (const [_, v] of cnt) { + ans = (ans + Math.floor((v * (v - 1)) / 2)) % mod; } return ans; -} +}; ``` -### **C#** - ```cs public class Solution { public int CountNicePairs(int[] nums) { @@ -343,10 +217,124 @@ public class Solution { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def countNicePairs(self, nums: List[int]) -> int: + def rev(x): + y = 0 + while x: + y = y * 10 + x % 10 + x //= 10 + return y + + ans = 0 + mod = 10**9 + 7 + cnt = Counter() + for x in nums: + y = x - rev(x) + ans += cnt[y] + cnt[y] += 1 + return ans % mod +``` + +```java +class Solution { + public int countNicePairs(int[] nums) { + Map cnt = new HashMap<>(); + final int mod = (int) 1e9 + 7; + int ans = 0; + for (int x : nums) { + int y = x - rev(x); + ans = (ans + cnt.getOrDefault(y, 0)) % mod; + cnt.merge(y, 1, Integer::sum); + } + return ans; + } + + private int rev(int x) { + int y = 0; + for (; x > 0; x /= 10) { + y = y * 10 + x % 10; + } + return y; + } +} +``` + +```cpp +class Solution { +public: + int countNicePairs(vector& nums) { + auto rev = [](int x) { + int y = 0; + for (; x > 0; x /= 10) { + y = y * 10 + x % 10; + } + return y; + }; + unordered_map cnt; + int ans = 0; + const int mod = 1e9 + 7; + for (int& x : nums) { + int y = x - rev(x); + ans = (ans + cnt[y]++) % mod; + } + return ans; + } +}; +``` +```go +func countNicePairs(nums []int) (ans int) { + rev := func(x int) (y int) { + for ; x > 0; x /= 10 { + y = y*10 + x%10 + } + return + } + cnt := map[int]int{} + const mod int = 1e9 + 7 + for _, x := range nums { + y := x - rev(x) + ans = (ans + cnt[y]) % mod + cnt[y]++ + } + return +} ``` +```js +/** + * @param {number[]} nums + * @return {number} + */ +var countNicePairs = function (nums) { + const rev = x => { + let y = 0; + for (; x > 0; x = Math.floor(x / 10)) { + y = y * 10 + (x % 10); + } + return y; + }; + let ans = 0; + const mod = 1e9 + 7; + const cnt = new Map(); + for (const x of nums) { + const y = x - rev(x); + const v = cnt.get(y) | 0; + ans = (ans + v) % mod; + cnt.set(y, v + 1); + } + return ans; +}; ``` + + diff --git a/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README.md b/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README.md index e5a2c362234f6..e45a1ba13c539 100644 --- a/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README.md +++ b/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:贪心 + 状态压缩 + 记忆化搜索** +### 方法一:贪心 + 状态压缩 + 记忆化搜索 题目实际上要我们找到一种安排顺序,使得前缀和(这里指的是“人数”)与 $batchSize$ 取模后为 $0$ 的组数最多。因此,我们可以将所有顾客按组分成两类: @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int: @@ -89,31 +83,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int: - @cache - def dfs(state, x): - if state == mask: - return 0 - vis = [False] * batchSize - res = 0 - for i, v in enumerate(g): - if state >> i & 1 == 0 and not vis[v]: - vis[v] = True - y = (x + v) % batchSize - res = max(res, dfs(state | 1 << i, y)) - return res + (x == 0) - - g = [v % batchSize for v in groups if v % batchSize] - mask = (1 << len(g)) - 1 - return len(groups) - len(g) + dfs(0, 0) -``` - -### **Java** - - - ```java class Solution { private Map f = new HashMap<>(); @@ -152,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -189,8 +156,6 @@ public: }; ``` -### **Go** - ```go func maxHappyGroups(batchSize int, groups []int) (ans int) { state := 0 @@ -227,10 +192,33 @@ func maxHappyGroups(batchSize int, groups []int) (ans int) { } ``` -### **...** + -``` +### 方法二 + + + +```python +class Solution: + def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int: + @cache + def dfs(state, x): + if state == mask: + return 0 + vis = [False] * batchSize + res = 0 + for i, v in enumerate(g): + if state >> i & 1 == 0 and not vis[v]: + vis[v] = True + y = (x + v) % batchSize + res = max(res, dfs(state | 1 << i, y)) + return res + (x == 0) + g = [v % batchSize for v in groups if v % batchSize] + mask = (1 << len(g)) - 1 + return len(groups) - len(g) + dfs(0, 0) ``` + + diff --git a/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README_EN.md b/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README_EN.md index 66664be34c575..97acbbfe3991e 100644 --- a/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README_EN.md +++ b/solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: Greedy + State Compression + Memorized Search** +### Solution 1: Greedy + State Compression + Memorized Search The problem actually asks us to find an arrangement order that maximizes the number of groups whose prefix sum (referring to "number of people" here) modulo $batchSize$ equals $0$. Therefore, we can divide all customers into two categories: @@ -56,8 +56,6 @@ The time complexity does not exceed $O(10^7)$, and the space complexity does not -### **Python3** - ```python class Solution: def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int: @@ -81,29 +79,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int: - @cache - def dfs(state, x): - if state == mask: - return 0 - vis = [False] * batchSize - res = 0 - for i, v in enumerate(g): - if state >> i & 1 == 0 and not vis[v]: - vis[v] = True - y = (x + v) % batchSize - res = max(res, dfs(state | 1 << i, y)) - return res + (x == 0) - - g = [v % batchSize for v in groups if v % batchSize] - mask = (1 << len(g)) - 1 - return len(groups) - len(g) + dfs(0, 0) -``` - -### **Java** - ```java class Solution { private Map f = new HashMap<>(); @@ -142,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -179,8 +152,6 @@ public: }; ``` -### **Go** - ```go func maxHappyGroups(batchSize int, groups []int) (ans int) { state := 0 @@ -217,10 +188,33 @@ func maxHappyGroups(batchSize int, groups []int) (ans int) { } ``` -### **...** + -``` +### Solution 2 + + + +```python +class Solution: + def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int: + @cache + def dfs(state, x): + if state == mask: + return 0 + vis = [False] * batchSize + res = 0 + for i, v in enumerate(g): + if state >> i & 1 == 0 and not vis[v]: + vis[v] = True + y = (x + v) % batchSize + res = max(res, dfs(state | 1 << i, y)) + return res + (x == 0) + g = [v % batchSize for v in groups if v % batchSize] + mask = (1 << len(g)) - 1 + return len(groups) - len(g) + dfs(0, 0) ``` + + diff --git a/solution/1800-1899/1816.Truncate Sentence/README.md b/solution/1800-1899/1816.Truncate Sentence/README.md index 3ca8c4e594a1e..39530c2b18364 100644 --- a/solution/1800-1899/1816.Truncate Sentence/README.md +++ b/solution/1800-1899/1816.Truncate Sentence/README.md @@ -55,9 +55,7 @@ s 中的单词为 ["What", "is" "the", "solution", "to", "this", "problem"] ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们从前往后遍历字符串 $s$,对于当前遍历到的字符 $s[i]$,如果 $s[i]$ 是空格,那么 $k$ 自减 $1$,当 $k$ 为 $0$ 时,说明已经截取了 $k$ 个单词,截取字符串 $s[0..i)$ 返回即可。 @@ -67,30 +65,12 @@ s 中的单词为 ["What", "is" "the", "solution", "to", "this", "problem"] -### **Python3** - - - ```python class Solution: def truncateSentence(self, s: str, k: int) -> str: return ' '.join(s.split()[:k]) ``` -```python -class Solution: - def truncateSentence(self, s: str, k: int) -> str: - for i, c in enumerate(s): - k -= c == ' ' - if k == 0: - return s[:i] - return s -``` - -### **Java** - - - ```java class Solution { public String truncateSentence(String s, int k) { @@ -104,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +98,6 @@ public: }; ``` -### **Go** - ```go func truncateSentence(s string, k int) string { for i, c := range s { @@ -136,8 +112,6 @@ func truncateSentence(s string, k int) string { } ``` -### **TypeScript** - ```ts function truncateSentence(s: string, k: number): string { for (let i = 0; i < s.length; ++i) { @@ -149,8 +123,6 @@ function truncateSentence(s: string, k: number): string { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -167,10 +139,22 @@ var truncateSentence = function (s, k) { }; ``` -### **...** + + +### 方法二 -``` + +```python +class Solution: + def truncateSentence(self, s: str, k: int) -> str: + for i, c in enumerate(s): + k -= c == ' ' + if k == 0: + return s[:i] + return s ``` + + diff --git a/solution/1800-1899/1816.Truncate Sentence/README_EN.md b/solution/1800-1899/1816.Truncate Sentence/README_EN.md index 3544e9fd6d57a..886cb98f6ffcc 100644 --- a/solution/1800-1899/1816.Truncate Sentence/README_EN.md +++ b/solution/1800-1899/1816.Truncate Sentence/README_EN.md @@ -54,7 +54,7 @@ Hence, you should return "What is the solution". ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We traverse the string $s$ from the beginning. For the current character $s[i]$, if it is a space, we decrement $k$. When $k$ becomes $0$, it means that we have extracted $k$ words, so we return the substring $s[0..i)$. @@ -64,26 +64,12 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. Ignori -### **Python3** - ```python class Solution: def truncateSentence(self, s: str, k: int) -> str: return ' '.join(s.split()[:k]) ``` -```python -class Solution: - def truncateSentence(self, s: str, k: int) -> str: - for i, c in enumerate(s): - k -= c == ' ' - if k == 0: - return s[:i] - return s -``` - -### **Java** - ```java class Solution { public String truncateSentence(String s, int k) { @@ -97,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +97,6 @@ public: }; ``` -### **Go** - ```go func truncateSentence(s string, k int) string { for i, c := range s { @@ -129,8 +111,6 @@ func truncateSentence(s string, k int) string { } ``` -### **TypeScript** - ```ts function truncateSentence(s: string, k: number): string { for (let i = 0; i < s.length; ++i) { @@ -142,8 +122,6 @@ function truncateSentence(s: string, k: number): string { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -160,10 +138,22 @@ var truncateSentence = function (s, k) { }; ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def truncateSentence(self, s: str, k: int) -> str: + for i, c in enumerate(s): + k -= c == ' ' + if k == 0: + return s[:i] + return s ``` + + diff --git a/solution/1800-1899/1817.Finding the Users Active Minutes/README.md b/solution/1800-1899/1817.Finding the Users Active Minutes/README.md index 6306710e13a07..98c3fac94e92b 100644 --- a/solution/1800-1899/1817.Finding the Users Active Minutes/README.md +++ b/solution/1800-1899/1817.Finding the Users Active Minutes/README.md @@ -54,9 +54,7 @@ ID=2 的用户执行操作的分钟分别是:2 和 3 。因此,该用户的 ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们用哈希表 $d$ 记录每个用户的所有去重操作时间,然后遍历哈希表,统计每个用户的用户活跃分钟数,最后统计每个用户活跃分钟数的分布情况。 @@ -64,10 +62,6 @@ ID=2 的用户执行操作的分钟分别是:2 和 3 。因此,该用户的 -### **Python3** - - - ```python class Solution: def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] findingUsersActiveMinutes(int[][] logs, int k) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func findingUsersActiveMinutes(logs [][]int, k int) []int { d := map[int]map[int]bool{} @@ -141,8 +127,6 @@ func findingUsersActiveMinutes(logs [][]int, k int) []int { } ``` -### **TypeScript** - ```ts function findingUsersActiveMinutes(logs: number[][], k: number): number[] { const d: Map> = new Map(); @@ -160,10 +144,6 @@ function findingUsersActiveMinutes(logs: number[][], k: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1817.Finding the Users Active Minutes/README_EN.md b/solution/1800-1899/1817.Finding the Users Active Minutes/README_EN.md index f62aa002751a1..eeaf7fc1d48d2 100644 --- a/solution/1800-1899/1817.Finding the Users Active Minutes/README_EN.md +++ b/solution/1800-1899/1817.Finding the Users Active Minutes/README_EN.md @@ -50,7 +50,7 @@ Hence, answer[1] = 1, answer[2] = 1, and the remaining values are 0. ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We use a hash table $d$ to record all the unique operation times of each user, and then traverse the hash table to count the number of active minutes for each user. Finally, we count the distribution of the number of active minutes for each user. @@ -58,8 +58,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is -### **Python3** - ```python class Solution: def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]: @@ -72,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] findingUsersActiveMinutes(int[][] logs, int k) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +105,6 @@ public: }; ``` -### **Go** - ```go func findingUsersActiveMinutes(logs [][]int, k int) []int { d := map[int]map[int]bool{} @@ -131,8 +123,6 @@ func findingUsersActiveMinutes(logs [][]int, k int) []int { } ``` -### **TypeScript** - ```ts function findingUsersActiveMinutes(logs: number[][], k: number): number[] { const d: Map> = new Map(); @@ -150,10 +140,6 @@ function findingUsersActiveMinutes(logs: number[][], k: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1818.Minimum Absolute Sum Difference/README.md b/solution/1800-1899/1818.Minimum Absolute Sum Difference/README.md index 09ef4dc75f57c..29b580a524114 100644 --- a/solution/1800-1899/1818.Minimum Absolute Sum Difference/README.md +++ b/solution/1800-1899/1818.Minimum Absolute Sum Difference/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 根据题意,我们可以先计算出在不进行替换的情况下,`nums1` 和 `nums2` 的绝对差值和,记为 $s$。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int: @@ -100,10 +94,6 @@ class Solution: return (s - mx + mod) % mod ``` -### **Java** - - - ```java class Solution { public int minAbsoluteSumDiff(int[] nums1, int[] nums2) { @@ -145,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +164,6 @@ public: }; ``` -### **Go** - ```go func minAbsoluteSumDiff(nums1 []int, nums2 []int) int { n := len(nums1) @@ -213,15 +199,8 @@ func abs(x int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var minAbsoluteSumDiff = function (nums1, nums2) { +```ts +function minAbsoluteSumDiff(nums1: number[], nums2: number[]): number { const mod = 10 ** 9 + 7; const nums = [...nums1]; nums.sort((a, b) => a - b); @@ -244,9 +223,9 @@ var minAbsoluteSumDiff = function (nums1, nums2) { mx = Math.max(mx, d1 - d2); } return (s - mx + mod) % mod; -}; +} -function search(nums, x) { +function search(nums: number[], x: number): number { let left = 0; let right = nums.length; while (left < right) { @@ -261,10 +240,13 @@ function search(nums, x) { } ``` -### **TypeScript** - -```ts -function minAbsoluteSumDiff(nums1: number[], nums2: number[]): number { +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var minAbsoluteSumDiff = function (nums1, nums2) { const mod = 10 ** 9 + 7; const nums = [...nums1]; nums.sort((a, b) => a - b); @@ -287,9 +269,9 @@ function minAbsoluteSumDiff(nums1: number[], nums2: number[]): number { mx = Math.max(mx, d1 - d2); } return (s - mx + mod) % mod; -} +}; -function search(nums: number[], x: number): number { +function search(nums, x) { let left = 0; let right = nums.length; while (left < right) { @@ -304,10 +286,6 @@ function search(nums: number[], x: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1818.Minimum Absolute Sum Difference/README_EN.md b/solution/1800-1899/1818.Minimum Absolute Sum Difference/README_EN.md index 04bb97ce0811e..bee3730fff534 100644 --- a/solution/1800-1899/1818.Minimum Absolute Sum Difference/README_EN.md +++ b/solution/1800-1899/1818.Minimum Absolute Sum Difference/README_EN.md @@ -61,7 +61,7 @@ This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| ## Solutions -**Solution 1: Sorting + Binary Search** +### Solution 1: Sorting + Binary Search According to the problem, we can first calculate the absolute difference sum of `nums1` and `nums2` without any replacements, denoted as $s$. @@ -73,8 +73,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int: @@ -93,8 +91,6 @@ class Solution: return (s - mx + mod) % mod ``` -### **Java** - ```java class Solution { public int minAbsoluteSumDiff(int[] nums1, int[] nums2) { @@ -136,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +161,6 @@ public: }; ``` -### **Go** - ```go func minAbsoluteSumDiff(nums1 []int, nums2 []int) int { n := len(nums1) @@ -204,15 +196,8 @@ func abs(x int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var minAbsoluteSumDiff = function (nums1, nums2) { +```ts +function minAbsoluteSumDiff(nums1: number[], nums2: number[]): number { const mod = 10 ** 9 + 7; const nums = [...nums1]; nums.sort((a, b) => a - b); @@ -235,9 +220,9 @@ var minAbsoluteSumDiff = function (nums1, nums2) { mx = Math.max(mx, d1 - d2); } return (s - mx + mod) % mod; -}; +} -function search(nums, x) { +function search(nums: number[], x: number): number { let left = 0; let right = nums.length; while (left < right) { @@ -252,10 +237,13 @@ function search(nums, x) { } ``` -### **TypeScript** - -```ts -function minAbsoluteSumDiff(nums1: number[], nums2: number[]): number { +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var minAbsoluteSumDiff = function (nums1, nums2) { const mod = 10 ** 9 + 7; const nums = [...nums1]; nums.sort((a, b) => a - b); @@ -278,9 +266,9 @@ function minAbsoluteSumDiff(nums1: number[], nums2: number[]): number { mx = Math.max(mx, d1 - d2); } return (s - mx + mod) % mod; -} +}; -function search(nums: number[], x: number): number { +function search(nums, x) { let left = 0; let right = nums.length; while (left < right) { @@ -295,10 +283,6 @@ function search(nums: number[], x: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1819.Number of Different Subsequences GCDs/README.md b/solution/1800-1899/1819.Number of Different Subsequences GCDs/README.md index 38d95416e4663..303ad1039e137 100644 --- a/solution/1800-1899/1819.Number of Different Subsequences GCDs/README.md +++ b/solution/1800-1899/1819.Number of Different Subsequences GCDs/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:枚举 + 数学** +### 方法一:枚举 + 数学 对于数组 $nums$ 的所有子序列,其最大公约数一定不超过数组中的最大值 $mx$。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countDifferentSubsequenceGCDs(int[] nums) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go func countDifferentSubsequenceGCDs(nums []int) (ans int) { mx := slices.Max(nums) @@ -181,10 +167,6 @@ func gcd(a, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1819.Number of Different Subsequences GCDs/README_EN.md b/solution/1800-1899/1819.Number of Different Subsequences GCDs/README_EN.md index 40be4c785fe91..1cf5e61710a97 100644 --- a/solution/1800-1899/1819.Number of Different Subsequences GCDs/README_EN.md +++ b/solution/1800-1899/1819.Number of Different Subsequences GCDs/README_EN.md @@ -47,7 +47,7 @@ The different GCDs are 6, 10, 3, 2, and 1. ## Solutions -**Solution 1: Enumeration + Mathematics** +### Solution 1: Enumeration + Mathematics For all sub-sequences of the array $nums$, their greatest common divisor (GCD) will not exceed the maximum value $mx$ in the array. @@ -59,8 +59,6 @@ The time complexity is $O(n + M \times \log M)$, and the space complexity is $O( -### **Python3** - ```python class Solution: def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int: @@ -78,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countDifferentSubsequenceGCDs(int[] nums) { @@ -110,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +133,6 @@ public: }; ``` -### **Go** - ```go func countDifferentSubsequenceGCDs(nums []int) (ans int) { mx := slices.Max(nums) @@ -171,10 +163,6 @@ func gcd(a, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README.md b/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README.md index dc9d2c9fe701c..b1a486fa2908d 100644 --- a/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README.md +++ b/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:匈牙利算法** +### 方法一:匈牙利算法 本题属于二分图最大匹配问题,适合用匈牙利算法来求解。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def maximumInvitations(self, grid: List[List[int]]) -> int: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[][] grid; @@ -131,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +151,6 @@ public: }; ``` -### **Go** - ```go func maximumInvitations(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -197,10 +183,6 @@ func maximumInvitations(grid [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README_EN.md b/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README_EN.md index 2d6ad590aed01..0252e656d0e8c 100644 --- a/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README_EN.md +++ b/solution/1800-1899/1820.Maximum Number of Accepted Invitations/README_EN.md @@ -49,7 +49,7 @@ Explanation:
The invitations are sent as follows: ## Solutions -**Solution 1: Hungarian Algorithm** +### Solution 1: Hungarian Algorithm This problem belongs to the maximum matching problem of bipartite graphs, which is suitable for solving with the Hungarian algorithm. @@ -59,8 +59,6 @@ The time complexity is $O(m \times n)$. -### **Python3** - ```python class Solution: def maximumInvitations(self, grid: List[List[int]]) -> int: @@ -82,8 +80,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[][] grid; @@ -123,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +149,6 @@ public: }; ``` -### **Go** - ```go func maximumInvitations(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -189,10 +181,6 @@ func maximumInvitations(grid [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1821.Find Customers With Positive Revenue this Year/README.md b/solution/1800-1899/1821.Find Customers With Positive Revenue this Year/README.md index c70907487c719..f9dc43e502b08 100644 --- a/solution/1800-1899/1821.Find Customers With Positive Revenue this Year/README.md +++ b/solution/1800-1899/1821.Find Customers With Positive Revenue this Year/README.md @@ -63,18 +63,12 @@ Customers ## 解法 - - -**方法一:WHERE 子句** +### 方法一:WHERE 子句 我们可以直接使用 `WHERE` 子句来筛选出 `year` 为 `2021` 且 `revenue` 大于 $0$ 的客户。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -84,3 +78,5 @@ WHERE year = '2021' AND revenue > 0; ``` + + diff --git a/solution/1800-1899/1821.Find Customers With Positive Revenue this Year/README_EN.md b/solution/1800-1899/1821.Find Customers With Positive Revenue this Year/README_EN.md index 4827aa76b7b9a..54b80afe4c55e 100644 --- a/solution/1800-1899/1821.Find Customers With Positive Revenue this Year/README_EN.md +++ b/solution/1800-1899/1821.Find Customers With Positive Revenue this Year/README_EN.md @@ -61,14 +61,12 @@ Thus only customers 1 and 4 have positive revenue in the year 2021. ## Solutions -**Solution 1: WHERE Clause** +### Solution 1: WHERE Clause We can directly use the `WHERE` clause to filter out the customers whose `year` is `2021` and `revenue` is greater than $0$. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -78,3 +76,5 @@ WHERE year = '2021' AND revenue > 0; ``` + + diff --git a/solution/1800-1899/1822.Sign of the Product of an Array/README.md b/solution/1800-1899/1822.Sign of the Product of an Array/README.md index fed6be914fd8a..74581dfec65e3 100644 --- a/solution/1800-1899/1822.Sign of the Product of an Array/README.md +++ b/solution/1800-1899/1822.Sign of the Product of an Array/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:直接遍历** +### 方法一:直接遍历 题目要求返回数组元素乘积的符号,即正数返回 $1$,负数返回 $-1$, 等于 $0$ 则返回 $0$。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def arraySign(self, nums: List[int]) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int arraySign(int[] nums) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func arraySign(nums []int) int { ans := 1 @@ -141,7 +127,22 @@ func arraySign(nums []int) int { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn array_sign(nums: Vec) -> i32 { + let mut ans = 1; + for &num in nums.iter() { + if num == 0 { + return 0; + } + if num < 0 { + ans *= -1; + } + } + ans + } +} +``` ```js /** @@ -162,27 +163,6 @@ var arraySign = function (nums) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn array_sign(nums: Vec) -> i32 { - let mut ans = 1; - for &num in nums.iter() { - if num == 0 { - return 0; - } - if num < 0 { - ans *= -1; - } - } - ans - } -} -``` - -### **C** - ```c int arraySign(int* nums, int numsSize) { int ans = 1; @@ -198,10 +178,6 @@ int arraySign(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1822.Sign of the Product of an Array/README_EN.md b/solution/1800-1899/1822.Sign of the Product of an Array/README_EN.md index fe1a5a0513497..05ced30febe02 100644 --- a/solution/1800-1899/1822.Sign of the Product of an Array/README_EN.md +++ b/solution/1800-1899/1822.Sign of the Product of an Array/README_EN.md @@ -51,7 +51,7 @@ ## Solutions -**Solution 1: Direct Traversal** +### Solution 1: Direct Traversal The problem requires us to return the sign of the product of the array elements, i.e., return $1$ for positive numbers, $-1$ for negative numbers, and $0$ if it equals $0$. @@ -65,8 +65,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def arraySign(self, nums: List[int]) -> int: @@ -79,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int arraySign(int[] nums) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +108,6 @@ public: }; ``` -### **Go** - ```go func arraySign(nums []int) int { ans := 1 @@ -131,7 +123,22 @@ func arraySign(nums []int) int { } ``` -### **JavaScript** +```rust +impl Solution { + pub fn array_sign(nums: Vec) -> i32 { + let mut ans = 1; + for &num in nums.iter() { + if num == 0 { + return 0; + } + if num < 0 { + ans *= -1; + } + } + ans + } +} +``` ```js /** @@ -152,27 +159,6 @@ var arraySign = function (nums) { }; ``` -### **Rust** - -```rust -impl Solution { - pub fn array_sign(nums: Vec) -> i32 { - let mut ans = 1; - for &num in nums.iter() { - if num == 0 { - return 0; - } - if num < 0 { - ans *= -1; - } - } - ans - } -} -``` - -### **C** - ```c int arraySign(int* nums, int numsSize) { int ans = 1; @@ -188,10 +174,6 @@ int arraySign(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1823.Find the Winner of the Circular Game/README.md b/solution/1800-1899/1823.Find the Winner of the Circular Game/README.md index 1bdedb1eae196..bd81cf1b91901 100644 --- a/solution/1800-1899/1823.Find the Winner of the Circular Game/README.md +++ b/solution/1800-1899/1823.Find the Winner of the Circular Game/README.md @@ -60,16 +60,10 @@ ## 解法 - - -约瑟夫环。 +### 方法一 -### **Python3** - - - ```python class Solution: def findTheWinner(self, n: int, k: int) -> int: @@ -79,10 +73,6 @@ class Solution: return n if ans == 0 else ans ``` -### **Java** - - - ```java class Solution { public int findTheWinner(int n, int k) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +96,6 @@ public: }; ``` -### **Go** - ```go func findTheWinner(n int, k int) int { if n == 1 { @@ -123,8 +109,6 @@ func findTheWinner(n int, k int) int { } ``` -### **TypeScript** - ```ts class LinkNode { public val: number; @@ -163,10 +147,6 @@ function findTheWinner(n: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1823.Find the Winner of the Circular Game/README_EN.md b/solution/1800-1899/1823.Find the Winner of the Circular Game/README_EN.md index 8bd121dcd4062..e6c6672a380cf 100644 --- a/solution/1800-1899/1823.Find the Winner of the Circular Game/README_EN.md +++ b/solution/1800-1899/1823.Find the Winner of the Circular Game/README_EN.md @@ -57,9 +57,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return n if ans == 0 else ans ``` -### **Java** - ```java class Solution { public int findTheWinner(int n, int k) { @@ -84,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +93,6 @@ public: }; ``` -### **Go** - ```go func findTheWinner(n int, k int) int { if n == 1 { @@ -112,8 +106,6 @@ func findTheWinner(n int, k int) int { } ``` -### **TypeScript** - ```ts class LinkNode { public val: number; @@ -152,10 +144,6 @@ function findTheWinner(n: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1824.Minimum Sideway Jumps/README.md b/solution/1800-1899/1824.Minimum Sideway Jumps/README.md index 7da74ee8bc0a9..d1f8a99d42b4b 100644 --- a/solution/1800-1899/1824.Minimum Sideway Jumps/README.md +++ b/solution/1800-1899/1824.Minimum Sideway Jumps/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示青蛙到达第 $i$ 个点,且处于第 $j$ 条跑道(下标从 $0$ 开始)的最小侧跳次数。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def minSideJumps(self, obstacles: List[int]) -> int: @@ -100,10 +94,6 @@ class Solution: return min(f) ``` -### **Java** - - - ```java class Solution { public int minSideJumps(int[] obstacles) { @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func minSideJumps(obstacles []int) int { f := [3]int{1, 0, 1} @@ -179,8 +165,6 @@ func minSideJumps(obstacles []int) int { } ``` -### **TypeScript** - ```ts function minSideJumps(obstacles: number[]): number { const inf = 1 << 30; @@ -203,10 +187,6 @@ function minSideJumps(obstacles: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1824.Minimum Sideway Jumps/README_EN.md b/solution/1800-1899/1824.Minimum Sideway Jumps/README_EN.md index dcb9055bfb502..4e0ebb2d3b33d 100644 --- a/solution/1800-1899/1824.Minimum Sideway Jumps/README_EN.md +++ b/solution/1800-1899/1824.Minimum Sideway Jumps/README_EN.md @@ -60,7 +60,7 @@ Note that the frog can jump over obstacles only when making side jumps (as shown ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ as the minimum number of sidesteps for the frog to reach the $i$-th point and be on the $j$-th lane (index starts from $0$). @@ -74,8 +74,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $obstacles$. -### **Python3** - ```python class Solution: def minSideJumps(self, obstacles: List[int]) -> int: @@ -92,8 +90,6 @@ class Solution: return min(f) ``` -### **Java** - ```java class Solution { public int minSideJumps(int[] obstacles) { @@ -118,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +139,6 @@ public: }; ``` -### **Go** - ```go func minSideJumps(obstacles []int) int { f := [3]int{1, 0, 1} @@ -169,8 +161,6 @@ func minSideJumps(obstacles []int) int { } ``` -### **TypeScript** - ```ts function minSideJumps(obstacles: number[]): number { const inf = 1 << 30; @@ -193,10 +183,6 @@ function minSideJumps(obstacles: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1825.Finding MK Average/README.md b/solution/1800-1899/1825.Finding MK Average/README.md index 1d3c0072362af..570212768c56c 100644 --- a/solution/1800-1899/1825.Finding MK Average/README.md +++ b/solution/1800-1899/1825.Finding MK Average/README.md @@ -65,9 +65,7 @@ obj.calculateMKAverage(); // 最后 3 个元素为 [5,5,5] ## 解法 - - -**方法一:有序集合 + 队列** +### 方法一:有序集合 + 队列 我们可以维护以下数据结构或变量: @@ -91,10 +89,6 @@ obj.calculateMKAverage(); // 最后 3 个元素为 [5,5,5] -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -154,57 +148,6 @@ class MKAverage: # param_2 = obj.calculateMKAverage() ``` -```python -from sortedcontainers import SortedList - - -class MKAverage: - def __init__(self, m: int, k: int): - self.m = m - self.k = k - self.sl = SortedList() - self.q = deque() - self.s = 0 - - def addElement(self, num: int) -> None: - self.q.append(num) - if len(self.q) == self.m: - self.sl = SortedList(self.q) - self.s = sum(self.sl[self.k : -self.k]) - elif len(self.q) > self.m: - i = self.sl.bisect_left(num) - if i < self.k: - self.s += self.sl[self.k - 1] - elif self.k <= i <= self.m - self.k: - self.s += num - else: - self.s += self.sl[self.m - self.k] - self.sl.add(num) - - x = self.q.popleft() - i = self.sl.bisect_left(x) - if i < self.k: - self.s -= self.sl[self.k] - elif self.k <= i <= self.m - self.k: - self.s -= x - else: - self.s -= self.sl[self.m - self.k] - self.sl.remove(x) - - def calculateMKAverage(self) -> int: - return -1 if len(self.sl) < self.m else self.s // (self.m - self.k * 2) - - -# Your MKAverage object will be instantiated and called as such: -# obj = MKAverage(m, k) -# obj.addElement(num) -# param_2 = obj.calculateMKAverage() -``` - -### **Java** - - - ```java class MKAverage { @@ -299,8 +242,6 @@ class MKAverage { */ ``` -### **C++** - ```cpp class MKAverage { public: @@ -377,8 +318,6 @@ private: */ ``` -### **Go** - ```go type MKAverage struct { lo, mid, hi *redblacktree.Tree @@ -474,10 +413,59 @@ func (this *MKAverage) CalculateMKAverage() int { */ ``` -### **...** + -``` +### 方法二 + + + +```python +from sortedcontainers import SortedList + + +class MKAverage: + def __init__(self, m: int, k: int): + self.m = m + self.k = k + self.sl = SortedList() + self.q = deque() + self.s = 0 + + def addElement(self, num: int) -> None: + self.q.append(num) + if len(self.q) == self.m: + self.sl = SortedList(self.q) + self.s = sum(self.sl[self.k : -self.k]) + elif len(self.q) > self.m: + i = self.sl.bisect_left(num) + if i < self.k: + self.s += self.sl[self.k - 1] + elif self.k <= i <= self.m - self.k: + self.s += num + else: + self.s += self.sl[self.m - self.k] + self.sl.add(num) + + x = self.q.popleft() + i = self.sl.bisect_left(x) + if i < self.k: + self.s -= self.sl[self.k] + elif self.k <= i <= self.m - self.k: + self.s -= x + else: + self.s -= self.sl[self.m - self.k] + self.sl.remove(x) + + def calculateMKAverage(self) -> int: + return -1 if len(self.sl) < self.m else self.s // (self.m - self.k * 2) + +# Your MKAverage object will be instantiated and called as such: +# obj = MKAverage(m, k) +# obj.addElement(num) +# param_2 = obj.calculateMKAverage() ``` + + diff --git a/solution/1800-1899/1825.Finding MK Average/README_EN.md b/solution/1800-1899/1825.Finding MK Average/README_EN.md index 9443d06f8f471..e7966216c1660 100644 --- a/solution/1800-1899/1825.Finding MK Average/README_EN.md +++ b/solution/1800-1899/1825.Finding MK Average/README_EN.md @@ -61,7 +61,7 @@ obj.calculateMKAverage(); // The last 3 elements are [5,5,5]. ## Solutions -**Solution 1: Ordered Set + Queue** +### Solution 1: Ordered Set + Queue We can maintain the following data structures or variables: @@ -85,8 +85,6 @@ In terms of time complexity, each call to the $addElement(num)$ function has a t -### **Python3** - ```python from sortedcontainers import SortedList @@ -146,55 +144,6 @@ class MKAverage: # param_2 = obj.calculateMKAverage() ``` -```python -from sortedcontainers import SortedList - - -class MKAverage: - def __init__(self, m: int, k: int): - self.m = m - self.k = k - self.sl = SortedList() - self.q = deque() - self.s = 0 - - def addElement(self, num: int) -> None: - self.q.append(num) - if len(self.q) == self.m: - self.sl = SortedList(self.q) - self.s = sum(self.sl[self.k : -self.k]) - elif len(self.q) > self.m: - i = self.sl.bisect_left(num) - if i < self.k: - self.s += self.sl[self.k - 1] - elif self.k <= i <= self.m - self.k: - self.s += num - else: - self.s += self.sl[self.m - self.k] - self.sl.add(num) - - x = self.q.popleft() - i = self.sl.bisect_left(x) - if i < self.k: - self.s -= self.sl[self.k] - elif self.k <= i <= self.m - self.k: - self.s -= x - else: - self.s -= self.sl[self.m - self.k] - self.sl.remove(x) - - def calculateMKAverage(self) -> int: - return -1 if len(self.sl) < self.m else self.s // (self.m - self.k * 2) - - -# Your MKAverage object will be instantiated and called as such: -# obj = MKAverage(m, k) -# obj.addElement(num) -# param_2 = obj.calculateMKAverage() -``` - -### **Java** - ```java class MKAverage { @@ -289,8 +238,6 @@ class MKAverage { */ ``` -### **C++** - ```cpp class MKAverage { public: @@ -367,8 +314,6 @@ private: */ ``` -### **Go** - ```go type MKAverage struct { lo, mid, hi *redblacktree.Tree @@ -464,10 +409,59 @@ func (this *MKAverage) CalculateMKAverage() int { */ ``` -### **...** + -``` +### Solution 2 + + + +```python +from sortedcontainers import SortedList + + +class MKAverage: + def __init__(self, m: int, k: int): + self.m = m + self.k = k + self.sl = SortedList() + self.q = deque() + self.s = 0 + + def addElement(self, num: int) -> None: + self.q.append(num) + if len(self.q) == self.m: + self.sl = SortedList(self.q) + self.s = sum(self.sl[self.k : -self.k]) + elif len(self.q) > self.m: + i = self.sl.bisect_left(num) + if i < self.k: + self.s += self.sl[self.k - 1] + elif self.k <= i <= self.m - self.k: + self.s += num + else: + self.s += self.sl[self.m - self.k] + self.sl.add(num) + x = self.q.popleft() + i = self.sl.bisect_left(x) + if i < self.k: + self.s -= self.sl[self.k] + elif self.k <= i <= self.m - self.k: + self.s -= x + else: + self.s -= self.sl[self.m - self.k] + self.sl.remove(x) + + def calculateMKAverage(self) -> int: + return -1 if len(self.sl) < self.m else self.s // (self.m - self.k * 2) + + +# Your MKAverage object will be instantiated and called as such: +# obj = MKAverage(m, k) +# obj.addElement(num) +# param_2 = obj.calculateMKAverage() ``` + + diff --git a/solution/1800-1899/1826.Faulty Sensor/README.md b/solution/1800-1899/1826.Faulty Sensor/README.md index 0ae247a90eb46..49c090e15e304 100644 --- a/solution/1800-1899/1826.Faulty Sensor/README.md +++ b/solution/1800-1899/1826.Faulty Sensor/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:遍历** +### 方法一:遍历 遍历两个数组,找到第一个不相等的位置 $i$。如果 $i \lt n - 1$,循环比较 $sensor1[i + 1]$ 和 $sensor2[i]$,如果不相等,说明传感器 $1$ 有缺陷,返回 $1$;否则比较 $sensor1[i]$ 和 $sensor2[i + 1]$,如果不相等,说明传感器 $2$ 有缺陷,返回 $2$。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def badSensor(self, sensor1: List[int], sensor2: List[int]) -> int: @@ -91,10 +85,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int badSensor(int[] sensor1, int[] sensor2) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +121,6 @@ public: }; ``` -### **Go** - ```go func badSensor(sensor1 []int, sensor2 []int) int { i, n := 0, len(sensor1) @@ -152,8 +138,6 @@ func badSensor(sensor1 []int, sensor2 []int) int { } ``` -### **TypeScript** - ```ts function badSensor(sensor1: number[], sensor2: number[]): number { let i = 0; @@ -177,10 +161,6 @@ function badSensor(sensor1: number[], sensor2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1826.Faulty Sensor/README_EN.md b/solution/1800-1899/1826.Faulty Sensor/README_EN.md index 1b4924842c72e..47dce1a6c358d 100644 --- a/solution/1800-1899/1826.Faulty Sensor/README_EN.md +++ b/solution/1800-1899/1826.Faulty Sensor/README_EN.md @@ -53,7 +53,7 @@ The fourth data point from sensor 1 is dropped, and the last value of sensor 1 i ## Solutions -**Solution 1: Traversal** +### Solution 1: Traversal Traverse both arrays, find the first unequal position $i$. If $i \lt n - 1$, loop to compare $sensor1[i + 1]$ and $sensor2[i]$, if they are not equal, it indicates that sensor $1$ is defective, return $1$; otherwise compare $sensor1[i]$ and $sensor2[i + 1]$, if they are not equal, it indicates that sensor $2$ is defective, return $2$. @@ -63,8 +63,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def badSensor(self, sensor1: List[int], sensor2: List[int]) -> int: @@ -82,8 +80,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int badSensor(int[] sensor1, int[] sensor2) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func badSensor(sensor1 []int, sensor2 []int) int { i, n := 0, len(sensor1) @@ -141,8 +133,6 @@ func badSensor(sensor1 []int, sensor2 []int) int { } ``` -### **TypeScript** - ```ts function badSensor(sensor1: number[], sensor2: number[]): number { let i = 0; @@ -166,10 +156,6 @@ function badSensor(sensor1: number[], sensor2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README.md b/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README.md index 899537c064c96..d9675f91c4df3 100644 --- a/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README.md +++ b/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们用变量 $mx$ 记录当前严格递增数组的最大值,初始时 $mx = 0$。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, nums: List[int]) -> int: @@ -77,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minOperations(int[] nums) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +98,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int) (ans int) { mx := 0 @@ -123,23 +109,6 @@ func minOperations(nums []int) (ans int) { } ``` -### **C#** - -```cs -public class Solution { - public int MinOperations(int[] nums) { - int ans = 0, mx = 0; - foreach (int v in nums) { - ans += Math.Max(0, mx + 1 - v); - mx = Math.Max(mx + 1, v); - } - return ans; - } -} -``` - -### **TypeScript** - ```ts function minOperations(nums: number[]): number { let ans = 0; @@ -152,8 +121,6 @@ function minOperations(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_operations(nums: Vec) -> i32 { @@ -168,7 +135,18 @@ impl Solution { } ``` -### **C** +```cs +public class Solution { + public int MinOperations(int[] nums) { + int ans = 0, mx = 0; + foreach (int v in nums) { + ans += Math.Max(0, mx + 1 - v); + mx = Math.Max(mx + 1, v); + } + return ans; + } +} +``` ```c #define max(a, b) (((a) > (b)) ? (a) : (b)) @@ -184,10 +162,6 @@ int minOperations(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md b/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md index e091d69993010..4c8a8100fed66 100644 --- a/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md +++ b/solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/README_EN.md @@ -50,7 +50,7 @@ ## Solutions -**Solution 1: Single Pass** +### Solution 1: Single Pass We use a variable $mx$ to record the maximum value of the current strictly increasing array, initially $mx = 0$. @@ -60,8 +60,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array `nums`. The -### **Python3** - ```python class Solution: def minOperations(self, nums: List[int]) -> int: @@ -72,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minOperations(int[] nums) { @@ -87,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +97,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int) (ans int) { mx := 0 @@ -116,23 +108,6 @@ func minOperations(nums []int) (ans int) { } ``` -### **C#** - -```cs -public class Solution { - public int MinOperations(int[] nums) { - int ans = 0, mx = 0; - foreach (int v in nums) { - ans += Math.Max(0, mx + 1 - v); - mx = Math.Max(mx + 1, v); - } - return ans; - } -} -``` - -### **TypeScript** - ```ts function minOperations(nums: number[]): number { let ans = 0; @@ -145,8 +120,6 @@ function minOperations(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_operations(nums: Vec) -> i32 { @@ -161,7 +134,18 @@ impl Solution { } ``` -### **C** +```cs +public class Solution { + public int MinOperations(int[] nums) { + int ans = 0, mx = 0; + foreach (int v in nums) { + ans += Math.Max(0, mx + 1 - v); + mx = Math.Max(mx + 1, v); + } + return ans; + } +} +``` ```c #define max(a, b) (((a) > (b)) ? (a) : (b)) @@ -177,10 +161,6 @@ int minOperations(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/README.md b/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/README.md index cd6b16bc3cfa5..60d9d51209a64 100644 --- a/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/README.md +++ b/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/README.md @@ -49,9 +49,7 @@ queries[0] 是绿色的圆,queries[1] 是红色的圆,queries[2] 是蓝色 ## 解法 - - -**方法一:枚举** +### 方法一:枚举 枚举所有的圆点 $(x, y, r)$,对于每个圆点,计算在圆内的点的个数,即可得到答案。 @@ -59,10 +57,6 @@ queries[0] 是绿色的圆,queries[1] 是红色的圆,queries[2] 是蓝色 -### **Python3** - - - ```python class Solution: def countPoints( @@ -78,10 +72,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] countPoints(int[][] points, int[][] queries) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func countPoints(points [][]int, queries [][]int) (ans []int) { for _, q := range queries { @@ -144,8 +130,6 @@ func countPoints(points [][]int, queries [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function countPoints(points: number[][], queries: number[][]): number[] { return queries.map(([cx, cy, r]) => { @@ -160,8 +144,6 @@ function countPoints(points: number[][], queries: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn count_points(points: Vec>, queries: Vec>) -> Vec { @@ -184,8 +166,6 @@ impl Solution { } ``` -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -210,10 +190,6 @@ int* countPoints(int** points, int pointsSize, int* pointsColSize, int** queries } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/README_EN.md b/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/README_EN.md index 01406f8334dec..fb91db7eef09a 100644 --- a/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/README_EN.md +++ b/solution/1800-1899/1828.Queries on Number of Points Inside a Circle/README_EN.md @@ -50,7 +50,7 @@ queries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is pu ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration Enumerate all the circles $(x, y, r)$. For each circle, calculate the number of points within the circle to get the answer. @@ -58,8 +58,6 @@ The time complexity is $O(m \times n)$, where $m$ and $n$ are the lengths of the -### **Python3** - ```python class Solution: def countPoints( @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] countPoints(int[][] points, int[][] queries) { @@ -97,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +113,6 @@ public: }; ``` -### **Go** - ```go func countPoints(points [][]int, queries [][]int) (ans []int) { for _, q := range queries { @@ -139,8 +131,6 @@ func countPoints(points [][]int, queries [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function countPoints(points: number[][], queries: number[][]): number[] { return queries.map(([cx, cy, r]) => { @@ -155,8 +145,6 @@ function countPoints(points: number[][], queries: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn count_points(points: Vec>, queries: Vec>) -> Vec { @@ -179,8 +167,6 @@ impl Solution { } ``` -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -205,10 +191,6 @@ int* countPoints(int** points, int pointsSize, int* pointsColSize, int** queries } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/README.md b/solution/1800-1899/1829.Maximum XOR for Each Query/README.md index 1d724a572e335..7a40c4708e87f 100644 --- a/solution/1800-1899/1829.Maximum XOR for Each Query/README.md +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:位运算 + 枚举** +### 方法一:位运算 + 枚举 我们先预处理出数组 `nums` 的异或和 $xs$,即 $xs=nums[0] \oplus nums[1] \oplus \cdots \oplus nums[n-1]$。 @@ -74,20 +72,8 @@ 时间复杂度 $O(n \times m)$,其中 $n$ 和 $m$ 分别是数组 `nums` 和 `maximumBit` 的值。忽略答案数组的空间消耗,空间复杂度 $O(1)$。 -**方法二:枚举优化** - -与方法一类似,我们先预处理出数组 `nums` 的异或和 $xs$,即 $xs=nums[0] \oplus nums[1] \oplus \cdots \oplus nums[n-1]$。 - -接下来,我们算出 $2^{maximumBit} - 1$,即 $2^{maximumBit}$ 减去 $1$,记为 $mask$。然后,我们从后往前枚举数组 `nums` 中的每个元素 $x$,当前的异或和为 $xs$,那么 $k=xs \oplus mask$ 就是每一次查询的答案。然后,我们将 $xs$ 更新为 $xs \oplus x$,继续枚举下一个元素。 - -时间复杂度 $O(n)$,其中 $n$ 是数组 `nums` 的长度。忽略答案数组的空间消耗,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]: @@ -103,23 +89,6 @@ class Solution: return ans ``` -```python -class Solution: - def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]: - ans = [] - xs = reduce(xor, nums) - mask = (1 << maximumBit) - 1 - for x in nums[::-1]: - k = xs ^ mask - ans.append(k) - xs ^= x - return ans -``` - -### **Java** - - - ```java class Solution { public int[] getMaximumXor(int[] nums, int maximumBit) { @@ -145,29 +114,6 @@ class Solution { } ``` -```java -class Solution { - public int[] getMaximumXor(int[] nums, int maximumBit) { - int xs = 0; - for (int x : nums) { - xs ^= x; - } - int mask = (1 << maximumBit) - 1; - int n = nums.length; - int[] ans = new int[n]; - for (int i = 0; i < n; ++i) { - int x = nums[n - i - 1]; - int k = xs ^ mask; - ans[i] = k; - xs ^= x; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -194,30 +140,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector getMaximumXor(vector& nums, int maximumBit) { - int xs = 0; - for (int& x : nums) { - xs ^= x; - } - int mask = (1 << maximumBit) - 1; - int n = nums.size(); - vector ans(n); - for (int i = 0; i < n; ++i) { - int x = nums[n - i - 1]; - int k = xs ^ mask; - ans[i] = k; - xs ^= x; - } - return ans; - } -}; -``` - -### **Go** - ```go func getMaximumXor(nums []int, maximumBit int) (ans []int) { xs := 0 @@ -239,25 +161,6 @@ func getMaximumXor(nums []int, maximumBit int) (ans []int) { } ``` -```go -func getMaximumXor(nums []int, maximumBit int) (ans []int) { - xs := 0 - for _, x := range nums { - xs ^= x - } - mask := (1 << maximumBit) - 1 - for i := range nums { - x := nums[len(nums)-i-1] - k := xs ^ mask - ans = append(ans, k) - xs ^= x - } - return -} -``` - -### **TypeScript** - ```ts function getMaximumXor(nums: number[], maximumBit: number): number[] { let xs = 0; @@ -281,27 +184,34 @@ function getMaximumXor(nums: number[], maximumBit: number): number[] { } ``` -```ts -function getMaximumXor(nums: number[], maximumBit: number): number[] { +```js +/** + * @param {number[]} nums + * @param {number} maximumBit + * @return {number[]} + */ +var getMaximumXor = function (nums, maximumBit) { let xs = 0; for (const x of nums) { xs ^= x; } - const mask = (1 << maximumBit) - 1; const n = nums.length; const ans = new Array(n); for (let i = 0; i < n; ++i) { const x = nums[n - i - 1]; - let k = xs ^ mask; + let k = 0; + for (let j = maximumBit - 1; j >= 0; --j) { + if (((xs >> j) & 1) == 0) { + k |= 1 << j; + } + } ans[i] = k; xs ^= x; } return ans; -} +}; ``` -### **C#** - ```cs public class Solution { public int[] GetMaximumXor(int[] nums, int maximumBit) { @@ -327,15 +237,40 @@ public class Solution { } ``` -```cs -public class Solution { - public int[] GetMaximumXor(int[] nums, int maximumBit) { + + +### 方法二:枚举优化 + +与方法一类似,我们先预处理出数组 `nums` 的异或和 $xs$,即 $xs=nums[0] \oplus nums[1] \oplus \cdots \oplus nums[n-1]$。 + +接下来,我们算出 $2^{maximumBit} - 1$,即 $2^{maximumBit}$ 减去 $1$,记为 $mask$。然后,我们从后往前枚举数组 `nums` 中的每个元素 $x$,当前的异或和为 $xs$,那么 $k=xs \oplus mask$ 就是每一次查询的答案。然后,我们将 $xs$ 更新为 $xs \oplus x$,继续枚举下一个元素。 + +时间复杂度 $O(n)$,其中 $n$ 是数组 `nums` 的长度。忽略答案数组的空间消耗,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]: + ans = [] + xs = reduce(xor, nums) + mask = (1 << maximumBit) - 1 + for x in nums[::-1]: + k = xs ^ mask + ans.append(k) + xs ^= x + return ans +``` + +```java +class Solution { + public int[] getMaximumXor(int[] nums, int maximumBit) { int xs = 0; - foreach (int x in nums) { + for (int x : nums) { xs ^= x; } int mask = (1 << maximumBit) - 1; - int n = nums.Length; + int n = nums.length; int[] ans = new int[n]; for (int i = 0; i < n; ++i) { int x = nums[n - i - 1]; @@ -348,34 +283,62 @@ public class Solution { } ``` -### **JavaScript** +```cpp +class Solution { +public: + vector getMaximumXor(vector& nums, int maximumBit) { + int xs = 0; + for (int& x : nums) { + xs ^= x; + } + int mask = (1 << maximumBit) - 1; + int n = nums.size(); + vector ans(n); + for (int i = 0; i < n; ++i) { + int x = nums[n - i - 1]; + int k = xs ^ mask; + ans[i] = k; + xs ^= x; + } + return ans; + } +}; +``` -```js -/** - * @param {number[]} nums - * @param {number} maximumBit - * @return {number[]} - */ -var getMaximumXor = function (nums, maximumBit) { +```go +func getMaximumXor(nums []int, maximumBit int) (ans []int) { + xs := 0 + for _, x := range nums { + xs ^= x + } + mask := (1 << maximumBit) - 1 + for i := range nums { + x := nums[len(nums)-i-1] + k := xs ^ mask + ans = append(ans, k) + xs ^= x + } + return +} +``` + +```ts +function getMaximumXor(nums: number[], maximumBit: number): number[] { let xs = 0; for (const x of nums) { xs ^= x; } + const mask = (1 << maximumBit) - 1; const n = nums.length; const ans = new Array(n); for (let i = 0; i < n; ++i) { const x = nums[n - i - 1]; - let k = 0; - for (let j = maximumBit - 1; j >= 0; --j) { - if (((xs >> j) & 1) == 0) { - k |= 1 << j; - } - } + let k = xs ^ mask; ans[i] = k; xs ^= x; } return ans; -}; +} ``` ```js @@ -402,10 +365,27 @@ var getMaximumXor = function (nums, maximumBit) { }; ``` -### **...** - -``` - +```cs +public class Solution { + public int[] GetMaximumXor(int[] nums, int maximumBit) { + int xs = 0; + foreach (int x in nums) { + xs ^= x; + } + int mask = (1 << maximumBit) - 1; + int n = nums.Length; + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + int x = nums[n - i - 1]; + int k = xs ^ mask; + ans[i] = k; + xs ^= x; + } + return ans; + } +} ``` + + diff --git a/solution/1800-1899/1829.Maximum XOR for Each Query/README_EN.md b/solution/1800-1899/1829.Maximum XOR for Each Query/README_EN.md index 364660b5f4766..0daef25b86070 100644 --- a/solution/1800-1899/1829.Maximum XOR for Each Query/README_EN.md +++ b/solution/1800-1899/1829.Maximum XOR for Each Query/README_EN.md @@ -58,7 +58,7 @@ ## Solutions -**Solution 1: Bitwise Operation + Enumeration** +### Solution 1: Bitwise Operation + Enumeration First, we preprocess the XOR sum $xs$ of the array `nums`, i.e., $xs=nums[0] \oplus nums[1] \oplus \cdots \oplus nums[n-1]$. @@ -68,18 +68,8 @@ That is to say, we start from the $maximumBit - 1$ bit of $xs$ and enumerate to The time complexity is $O(n \times m)$, where $n$ and $m$ are the values of the array `nums` and `maximumBit` respectively. Ignoring the space consumption of the answer, the space complexity is $O(1)$. -**Solution 2: Enumeration Optimization** - -Similar to Solution 1, we first preprocess the XOR sum $xs$ of the array `nums`, i.e., $xs=nums[0] \oplus nums[1] \oplus \cdots \oplus nums[n-1]$. - -Next, we calculate $2^{maximumBit} - 1$, which is $2^{maximumBit}$ minus $1$, denoted as $mask$. Then, we enumerate each element $x$ in the array `nums` from back to front. The current XOR sum is $xs$, then $k=xs \oplus mask$ is the answer to each query. Then, we update $xs$ to $xs \oplus x$ and continue to enumerate the next element. - -The time complexity is $O(n)$, where $n$ is the length of the array `nums`. Ignoring the space consumption of the answer, the space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]: @@ -95,21 +85,6 @@ class Solution: return ans ``` -```python -class Solution: - def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]: - ans = [] - xs = reduce(xor, nums) - mask = (1 << maximumBit) - 1 - for x in nums[::-1]: - k = xs ^ mask - ans.append(k) - xs ^= x - return ans -``` - -### **Java** - ```java class Solution { public int[] getMaximumXor(int[] nums, int maximumBit) { @@ -135,29 +110,6 @@ class Solution { } ``` -```java -class Solution { - public int[] getMaximumXor(int[] nums, int maximumBit) { - int xs = 0; - for (int x : nums) { - xs ^= x; - } - int mask = (1 << maximumBit) - 1; - int n = nums.length; - int[] ans = new int[n]; - for (int i = 0; i < n; ++i) { - int x = nums[n - i - 1]; - int k = xs ^ mask; - ans[i] = k; - xs ^= x; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -184,30 +136,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector getMaximumXor(vector& nums, int maximumBit) { - int xs = 0; - for (int& x : nums) { - xs ^= x; - } - int mask = (1 << maximumBit) - 1; - int n = nums.size(); - vector ans(n); - for (int i = 0; i < n; ++i) { - int x = nums[n - i - 1]; - int k = xs ^ mask; - ans[i] = k; - xs ^= x; - } - return ans; - } -}; -``` - -### **Go** - ```go func getMaximumXor(nums []int, maximumBit int) (ans []int) { xs := 0 @@ -229,25 +157,6 @@ func getMaximumXor(nums []int, maximumBit int) (ans []int) { } ``` -```go -func getMaximumXor(nums []int, maximumBit int) (ans []int) { - xs := 0 - for _, x := range nums { - xs ^= x - } - mask := (1 << maximumBit) - 1 - for i := range nums { - x := nums[len(nums)-i-1] - k := xs ^ mask - ans = append(ans, k) - xs ^= x - } - return -} -``` - -### **TypeScript** - ```ts function getMaximumXor(nums: number[], maximumBit: number): number[] { let xs = 0; @@ -271,27 +180,34 @@ function getMaximumXor(nums: number[], maximumBit: number): number[] { } ``` -```ts -function getMaximumXor(nums: number[], maximumBit: number): number[] { +```js +/** + * @param {number[]} nums + * @param {number} maximumBit + * @return {number[]} + */ +var getMaximumXor = function (nums, maximumBit) { let xs = 0; for (const x of nums) { xs ^= x; } - const mask = (1 << maximumBit) - 1; const n = nums.length; const ans = new Array(n); for (let i = 0; i < n; ++i) { const x = nums[n - i - 1]; - let k = xs ^ mask; + let k = 0; + for (let j = maximumBit - 1; j >= 0; --j) { + if (((xs >> j) & 1) == 0) { + k |= 1 << j; + } + } ans[i] = k; xs ^= x; } return ans; -} +}; ``` -### **C#** - ```cs public class Solution { public int[] GetMaximumXor(int[] nums, int maximumBit) { @@ -317,15 +233,40 @@ public class Solution { } ``` -```cs -public class Solution { - public int[] GetMaximumXor(int[] nums, int maximumBit) { + + +### Solution 2: Enumeration Optimization + +Similar to Solution 1, we first preprocess the XOR sum $xs$ of the array `nums`, i.e., $xs=nums[0] \oplus nums[1] \oplus \cdots \oplus nums[n-1]$. + +Next, we calculate $2^{maximumBit} - 1$, which is $2^{maximumBit}$ minus $1$, denoted as $mask$. Then, we enumerate each element $x$ in the array `nums` from back to front. The current XOR sum is $xs$, then $k=xs \oplus mask$ is the answer to each query. Then, we update $xs$ to $xs \oplus x$ and continue to enumerate the next element. + +The time complexity is $O(n)$, where $n$ is the length of the array `nums`. Ignoring the space consumption of the answer, the space complexity is $O(1)$. + + + +```python +class Solution: + def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]: + ans = [] + xs = reduce(xor, nums) + mask = (1 << maximumBit) - 1 + for x in nums[::-1]: + k = xs ^ mask + ans.append(k) + xs ^= x + return ans +``` + +```java +class Solution { + public int[] getMaximumXor(int[] nums, int maximumBit) { int xs = 0; - foreach (int x in nums) { + for (int x : nums) { xs ^= x; } int mask = (1 << maximumBit) - 1; - int n = nums.Length; + int n = nums.length; int[] ans = new int[n]; for (int i = 0; i < n; ++i) { int x = nums[n - i - 1]; @@ -338,34 +279,62 @@ public class Solution { } ``` -### **JavaScript** +```cpp +class Solution { +public: + vector getMaximumXor(vector& nums, int maximumBit) { + int xs = 0; + for (int& x : nums) { + xs ^= x; + } + int mask = (1 << maximumBit) - 1; + int n = nums.size(); + vector ans(n); + for (int i = 0; i < n; ++i) { + int x = nums[n - i - 1]; + int k = xs ^ mask; + ans[i] = k; + xs ^= x; + } + return ans; + } +}; +``` -```js -/** - * @param {number[]} nums - * @param {number} maximumBit - * @return {number[]} - */ -var getMaximumXor = function (nums, maximumBit) { +```go +func getMaximumXor(nums []int, maximumBit int) (ans []int) { + xs := 0 + for _, x := range nums { + xs ^= x + } + mask := (1 << maximumBit) - 1 + for i := range nums { + x := nums[len(nums)-i-1] + k := xs ^ mask + ans = append(ans, k) + xs ^= x + } + return +} +``` + +```ts +function getMaximumXor(nums: number[], maximumBit: number): number[] { let xs = 0; for (const x of nums) { xs ^= x; } + const mask = (1 << maximumBit) - 1; const n = nums.length; const ans = new Array(n); for (let i = 0; i < n; ++i) { const x = nums[n - i - 1]; - let k = 0; - for (let j = maximumBit - 1; j >= 0; --j) { - if (((xs >> j) & 1) == 0) { - k |= 1 << j; - } - } + let k = xs ^ mask; ans[i] = k; xs ^= x; } return ans; -}; +} ``` ```js @@ -392,10 +361,27 @@ var getMaximumXor = function (nums, maximumBit) { }; ``` -### **...** - -``` - +```cs +public class Solution { + public int[] GetMaximumXor(int[] nums, int maximumBit) { + int xs = 0; + foreach (int x in nums) { + xs ^= x; + } + int mask = (1 << maximumBit) - 1; + int n = nums.Length; + int[] ans = new int[n]; + for (int i = 0; i < n; ++i) { + int x = nums[n - i - 1]; + int k = xs ^ mask; + ans[i] = k; + xs ^= x; + } + return ans; + } +} ``` + + diff --git a/solution/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README.md b/solution/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README.md index f1abb4d422645..e451cfe0fc9d3 100644 --- a/solution/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README.md +++ b/solution/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:计数 + 排列组合 + 预处理** +### 方法一:计数 + 排列组合 + 预处理 题目中的操作实际上是求当前排列的上一个字典序排列,因此,我们只需要求出比当前排列小的排列的数量,就是答案。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python n = 3010 mod = 10**9 + 7 @@ -113,10 +107,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int N = 3010; @@ -169,8 +159,6 @@ class Solution { } ``` -### **C++** - ```cpp const int N = 3010; const int MOD = 1e9 + 7; @@ -224,8 +212,6 @@ public: }; ``` -### **Go** - ```go const n = 3010 const mod = 1e9 + 7 @@ -274,10 +260,6 @@ func makeStringSorted(s string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README_EN.md b/solution/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README_EN.md index 5ff0b7a4690bb..fa55e051b1f4b 100644 --- a/solution/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README_EN.md +++ b/solution/1800-1899/1830.Minimum Number of Operations to Make String Sorted/README_EN.md @@ -49,7 +49,7 @@ Operation 2: i=4, j=4. Swap s[3] and s[4] to get s="aaaab", then rever ## Solutions -**Solution 1: Counting + Permutation and Combination + Preprocessing** +### Solution 1: Counting + Permutation and Combination + Preprocessing The operation in the problem is actually to find the previous permutation in lexicographical order of the current permutation. Therefore, we only need to find the number of permutations smaller than the current permutation, which is the answer. @@ -67,8 +67,6 @@ The time complexity is $O(n \times k)$, and the space complexity is $O(n)$. Wher -### **Python3** - ```python n = 3010 mod = 10**9 + 7 @@ -96,8 +94,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int N = 3010; @@ -150,8 +146,6 @@ class Solution { } ``` -### **C++** - ```cpp const int N = 3010; const int MOD = 1e9 + 7; @@ -205,8 +199,6 @@ public: }; ``` -### **Go** - ```go const n = 3010 const mod = 1e9 + 7 @@ -255,10 +247,6 @@ func makeStringSorted(s string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1831.Maximum Transaction Each Day/README.md b/solution/1800-1899/1831.Maximum Transaction Each Day/README.md index 881c154ba556b..8f764ff3494c5 100644 --- a/solution/1800-1899/1831.Maximum Transaction Each Day/README.md +++ b/solution/1800-1899/1831.Maximum Transaction Each Day/README.md @@ -65,18 +65,12 @@ Transactions table: ## 解法 - - -**方法一:窗口函数** +### 方法一:窗口函数 我们可以使用窗口函数 `RANK`,按照每天的交易金额 `amount` 降序排列,然后选择排名为 $1$ 的交易。 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -96,3 +90,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1800-1899/1831.Maximum Transaction Each Day/README_EN.md b/solution/1800-1899/1831.Maximum Transaction Each Day/README_EN.md index a58e8d3f4468f..5308f6f17a01d 100644 --- a/solution/1800-1899/1831.Maximum Transaction Each Day/README_EN.md +++ b/solution/1800-1899/1831.Maximum Transaction Each Day/README_EN.md @@ -62,14 +62,12 @@ We order the result table by transaction_id after collecting these IDs. ## Solutions -**Solution 1: Window Function** +### Solution 1: Window Function We can use the window function `RANK()`, which assigns a rank to each transaction based on its amount in descending order, and then select the transactions with a rank of $1$. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -89,3 +87,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/README.md b/solution/1800-1899/1832.Check if the Sentence Is Pangram/README.md index b6e525b41b318..11b0744f27166 100644 --- a/solution/1800-1899/1832.Check if the Sentence Is Pangram/README.md +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/README.md @@ -40,47 +40,20 @@ ## 解法 - - -**方法一:数组或哈希表** +### 方法一:数组或哈希表 遍历字符串 `sentence`,用数组或哈希表记录出现过的字母,最后判断数组或哈希表中是否有 $26$ 个字母即可。 时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 为字符串 `sentence` 的长度,而 $C$ 为字符集大小。本题中 $C = 26$。 -**方法二:位运算** - -我们也可以用一个整数 $mask$ 记录出现过的字母,其中 $mask$ 的第 $i$ 位表示第 $i$ 个字母是否出现过。 - -最后判断 $mask$ 的二进制表示中是否有 $26$ 个 $1$,也即判断 $mask$ 是否等于 $2^{26} - 1$。若是,返回 `true`,否则返回 `false`。 - -时间复杂度 $O(n)$,其中 $n$ 为字符串 `sentence` 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def checkIfPangram(self, sentence: str) -> bool: return len(set(sentence)) == 26 ``` -```python -class Solution: - def checkIfPangram(self, sentence: str) -> bool: - mask = 0 - for c in sentence: - mask |= 1 << (ord(c) - ord('a')) - return mask == (1 << 26) - 1 -``` - -### **Java** - - - ```java class Solution { public boolean checkIfPangram(String sentence) { @@ -98,20 +71,6 @@ class Solution { } ``` -```java -class Solution { - public boolean checkIfPangram(String sentence) { - int mask = 0; - for (int i = 0; i < sentence.length(); ++i) { - mask |= 1 << (sentence.charAt(i) - 'a'); - } - return mask == (1 << 26) - 1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -125,19 +84,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool checkIfPangram(string sentence) { - int mask = 0; - for (char& c : sentence) mask |= 1 << (c - 'a'); - return mask == (1 << 26) - 1; - } -}; -``` - -### **Go** - ```go func checkIfPangram(sentence string) bool { vis := [26]bool{} @@ -153,18 +99,6 @@ func checkIfPangram(sentence string) bool { } ``` -```go -func checkIfPangram(sentence string) bool { - mask := 0 - for _, c := range sentence { - mask |= 1 << int(c-'a') - } - return mask == 1<<26-1 -} -``` - -### **TypeScript** - ```ts function checkIfPangram(sentence: string): boolean { const vis = new Array(26).fill(false); @@ -175,18 +109,6 @@ function checkIfPangram(sentence: string): boolean { } ``` -```ts -function checkIfPangram(sentence: string): boolean { - let mark = 0; - for (const c of sentence) { - mark |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); - } - return mark === (1 << 26) - 1; -} -``` - -### **Rust** - ```rust impl Solution { pub fn check_if_pangram(sentence: String) -> bool { @@ -199,20 +121,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn check_if_pangram(sentence: String) -> bool { - let mut mark = 0; - for c in sentence.as_bytes() { - mark |= 1 << (*c - b'a'); - } - mark == (1 << 26) - 1 - } -} -``` - -### **C** - ```c bool checkIfPangram(char* sentence) { int vis[26] = {0}; @@ -228,6 +136,82 @@ bool checkIfPangram(char* sentence) { } ``` + + +### 方法二:位运算 + +我们也可以用一个整数 $mask$ 记录出现过的字母,其中 $mask$ 的第 $i$ 位表示第 $i$ 个字母是否出现过。 + +最后判断 $mask$ 的二进制表示中是否有 $26$ 个 $1$,也即判断 $mask$ 是否等于 $2^{26} - 1$。若是,返回 `true`,否则返回 `false`。 + +时间复杂度 $O(n)$,其中 $n$ 为字符串 `sentence` 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def checkIfPangram(self, sentence: str) -> bool: + mask = 0 + for c in sentence: + mask |= 1 << (ord(c) - ord('a')) + return mask == (1 << 26) - 1 +``` + +```java +class Solution { + public boolean checkIfPangram(String sentence) { + int mask = 0; + for (int i = 0; i < sentence.length(); ++i) { + mask |= 1 << (sentence.charAt(i) - 'a'); + } + return mask == (1 << 26) - 1; + } +} +``` + +```cpp +class Solution { +public: + bool checkIfPangram(string sentence) { + int mask = 0; + for (char& c : sentence) mask |= 1 << (c - 'a'); + return mask == (1 << 26) - 1; + } +}; +``` + +```go +func checkIfPangram(sentence string) bool { + mask := 0 + for _, c := range sentence { + mask |= 1 << int(c-'a') + } + return mask == 1<<26-1 +} +``` + +```ts +function checkIfPangram(sentence: string): boolean { + let mark = 0; + for (const c of sentence) { + mark |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); + } + return mark === (1 << 26) - 1; +} +``` + +```rust +impl Solution { + pub fn check_if_pangram(sentence: String) -> bool { + let mut mark = 0; + for c in sentence.as_bytes() { + mark |= 1 << (*c - b'a'); + } + mark == (1 << 26) - 1 + } +} +``` + ```c bool checkIfPangram(char* sentence) { int mark = 0; @@ -238,10 +222,6 @@ bool checkIfPangram(char* sentence) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1832.Check if the Sentence Is Pangram/README_EN.md b/solution/1800-1899/1832.Check if the Sentence Is Pangram/README_EN.md index f81fa8095fde3..7606d684232c3 100644 --- a/solution/1800-1899/1832.Check if the Sentence Is Pangram/README_EN.md +++ b/solution/1800-1899/1832.Check if the Sentence Is Pangram/README_EN.md @@ -34,41 +34,20 @@ ## Solutions -**Solution 1: Array or Hash Table** +### Solution 1: Array or Hash Table Traverse the string `sentence`, use an array or hash table to record the letters that have appeared, and finally check whether there are $26$ letters in the array or hash table. The time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of the string `sentence`, and $C$ is the size of the character set. In this problem, $C = 26$. -**Solution 2: Bit Manipulation** - -We can also use an integer $mask$ to record the letters that have appeared, where the $i$-th bit of $mask$ indicates whether the $i$-th letter has appeared. - -Finally, check whether there are $26$ $1$s in the binary representation of $mask$, that is, check whether $mask$ is equal to $2^{26} - 1$. If so, return `true`, otherwise return `false`. - -The time complexity is $O(n)$, where $n$ is the length of the string `sentence`. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def checkIfPangram(self, sentence: str) -> bool: return len(set(sentence)) == 26 ``` -```python -class Solution: - def checkIfPangram(self, sentence: str) -> bool: - mask = 0 - for c in sentence: - mask |= 1 << (ord(c) - ord('a')) - return mask == (1 << 26) - 1 -``` - -### **Java** - ```java class Solution { public boolean checkIfPangram(String sentence) { @@ -86,20 +65,6 @@ class Solution { } ``` -```java -class Solution { - public boolean checkIfPangram(String sentence) { - int mask = 0; - for (int i = 0; i < sentence.length(); ++i) { - mask |= 1 << (sentence.charAt(i) - 'a'); - } - return mask == (1 << 26) - 1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -113,19 +78,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool checkIfPangram(string sentence) { - int mask = 0; - for (char& c : sentence) mask |= 1 << (c - 'a'); - return mask == (1 << 26) - 1; - } -}; -``` - -### **Go** - ```go func checkIfPangram(sentence string) bool { vis := [26]bool{} @@ -141,18 +93,6 @@ func checkIfPangram(sentence string) bool { } ``` -```go -func checkIfPangram(sentence string) bool { - mask := 0 - for _, c := range sentence { - mask |= 1 << int(c-'a') - } - return mask == 1<<26-1 -} -``` - -### **TypeScript** - ```ts function checkIfPangram(sentence: string): boolean { const vis = new Array(26).fill(false); @@ -163,18 +103,6 @@ function checkIfPangram(sentence: string): boolean { } ``` -```ts -function checkIfPangram(sentence: string): boolean { - let mark = 0; - for (const c of sentence) { - mark |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); - } - return mark === (1 << 26) - 1; -} -``` - -### **Rust** - ```rust impl Solution { pub fn check_if_pangram(sentence: String) -> bool { @@ -187,20 +115,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn check_if_pangram(sentence: String) -> bool { - let mut mark = 0; - for c in sentence.as_bytes() { - mark |= 1 << (*c - b'a'); - } - mark == (1 << 26) - 1 - } -} -``` - -### **C** - ```c bool checkIfPangram(char* sentence) { int vis[26] = {0}; @@ -216,6 +130,82 @@ bool checkIfPangram(char* sentence) { } ``` + + +### Solution 2: Bit Manipulation + +We can also use an integer $mask$ to record the letters that have appeared, where the $i$-th bit of $mask$ indicates whether the $i$-th letter has appeared. + +Finally, check whether there are $26$ $1$s in the binary representation of $mask$, that is, check whether $mask$ is equal to $2^{26} - 1$. If so, return `true`, otherwise return `false`. + +The time complexity is $O(n)$, where $n$ is the length of the string `sentence`. The space complexity is $O(1)$. + + + +```python +class Solution: + def checkIfPangram(self, sentence: str) -> bool: + mask = 0 + for c in sentence: + mask |= 1 << (ord(c) - ord('a')) + return mask == (1 << 26) - 1 +``` + +```java +class Solution { + public boolean checkIfPangram(String sentence) { + int mask = 0; + for (int i = 0; i < sentence.length(); ++i) { + mask |= 1 << (sentence.charAt(i) - 'a'); + } + return mask == (1 << 26) - 1; + } +} +``` + +```cpp +class Solution { +public: + bool checkIfPangram(string sentence) { + int mask = 0; + for (char& c : sentence) mask |= 1 << (c - 'a'); + return mask == (1 << 26) - 1; + } +}; +``` + +```go +func checkIfPangram(sentence string) bool { + mask := 0 + for _, c := range sentence { + mask |= 1 << int(c-'a') + } + return mask == 1<<26-1 +} +``` + +```ts +function checkIfPangram(sentence: string): boolean { + let mark = 0; + for (const c of sentence) { + mark |= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0)); + } + return mark === (1 << 26) - 1; +} +``` + +```rust +impl Solution { + pub fn check_if_pangram(sentence: String) -> bool { + let mut mark = 0; + for c in sentence.as_bytes() { + mark |= 1 << (*c - b'a'); + } + mark == (1 << 26) - 1 + } +} +``` + ```c bool checkIfPangram(char* sentence) { int mark = 0; @@ -226,10 +216,6 @@ bool checkIfPangram(char* sentence) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1833.Maximum Ice Cream Bars/README.md b/solution/1800-1899/1833.Maximum Ice Cream Bars/README.md index 57caa1e517e5a..4914a69be988e 100644 --- a/solution/1800-1899/1833.Maximum Ice Cream Bars/README.md +++ b/solution/1800-1899/1833.Maximum Ice Cream Bars/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 要买尽可能多的雪糕,且可以按任意顺序购买,因此,我们应该优先选择定价小的雪糕。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def maxIceCream(self, costs: List[int], coins: int) -> int: @@ -82,10 +76,6 @@ class Solution: return len(costs) ``` -### **Java** - - - ```java class Solution { public int maxIceCream(int[] costs, int coins) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func maxIceCream(costs []int, coins int) int { sort.Ints(costs) @@ -134,8 +120,6 @@ func maxIceCream(costs []int, coins int) int { } ``` -### **TypeScript** - ```ts function maxIceCream(costs: number[], coins: number): number { costs.sort((a, b) => a - b); @@ -150,8 +134,6 @@ function maxIceCream(costs: number[], coins: number): number { } ``` -### **JavaScript** - ```js /** * @param {number[]} costs @@ -171,10 +153,6 @@ var maxIceCream = function (costs, coins) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1833.Maximum Ice Cream Bars/README_EN.md b/solution/1800-1899/1833.Maximum Ice Cream Bars/README_EN.md index 897d8822d3d83..b979f7726130f 100644 --- a/solution/1800-1899/1833.Maximum Ice Cream Bars/README_EN.md +++ b/solution/1800-1899/1833.Maximum Ice Cream Bars/README_EN.md @@ -51,7 +51,7 @@ ## Solutions -**Solution 1: Greedy + Sorting** +### Solution 1: Greedy + Sorting To buy as many ice creams as possible, and they can be purchased in any order, we should prioritize choosing ice creams with lower prices. @@ -61,8 +61,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def maxIceCream(self, costs: List[int], coins: int) -> int: @@ -74,8 +72,6 @@ class Solution: return len(costs) ``` -### **Java** - ```java class Solution { public int maxIceCream(int[] costs, int coins) { @@ -92,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +103,6 @@ public: }; ``` -### **Go** - ```go func maxIceCream(costs []int, coins int) int { sort.Ints(costs) @@ -124,8 +116,6 @@ func maxIceCream(costs []int, coins int) int { } ``` -### **TypeScript** - ```ts function maxIceCream(costs: number[], coins: number): number { costs.sort((a, b) => a - b); @@ -140,8 +130,6 @@ function maxIceCream(costs: number[], coins: number): number { } ``` -### **JavaScript** - ```js /** * @param {number[]} costs @@ -161,10 +149,6 @@ var maxIceCream = function (costs, coins) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1834.Single-Threaded CPU/README.md b/solution/1800-1899/1834.Single-Threaded CPU/README.md index 0c09cd7c41a13..4611d64080628 100644 --- a/solution/1800-1899/1834.Single-Threaded CPU/README.md +++ b/solution/1800-1899/1834.Single-Threaded CPU/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:排序 + 优先队列(小根堆)** +### 方法一:排序 + 优先队列(小根堆) 我们先将任务按照 `enqueueTime` 从小到大排序,接下来用一个优先队列(小根堆)维护当前可执行的任务,队列中的元素为 `(processingTime, index)`,即任务的执行时间和任务的编号。另外用一个变量 $t$ 表示当前时间,初始值为 $0$。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def getOrder(self, tasks: List[List[int]]) -> List[int]: @@ -106,10 +100,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] getOrder(int[][] tasks) { @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +158,6 @@ public: }; ``` -### **Go** - ```go func getOrder(tasks [][]int) (ans []int) { for i := range tasks { @@ -205,10 +191,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1834.Single-Threaded CPU/README_EN.md b/solution/1800-1899/1834.Single-Threaded CPU/README_EN.md index aa0951d96024c..6649334603752 100644 --- a/solution/1800-1899/1834.Single-Threaded CPU/README_EN.md +++ b/solution/1800-1899/1834.Single-Threaded CPU/README_EN.md @@ -61,7 +61,7 @@ ## Solutions -**Solution 1: Sorting + Priority Queue (Min Heap)** +### Solution 1: Sorting + Priority Queue (Min Heap) First, we sort the tasks by `enqueueTime` in ascending order. Next, we use a priority queue (min heap) to maintain the currently executable tasks. The elements in the queue are `(processingTime, index)`, which represent the execution time and the index of the task. We also use a variable $t$ to represent the current time, initially set to $0$. @@ -77,8 +77,6 @@ The time complexity is $O(n \times \log n)$, where $n$ is the number of tasks. -### **Python3** - ```python class Solution: def getOrder(self, tasks: List[List[int]]) -> List[int]: @@ -101,8 +99,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] getOrder(int[][] tasks) { @@ -133,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +157,6 @@ public: }; ``` -### **Go** - ```go func getOrder(tasks [][]int) (ans []int) { for i := range tasks { @@ -198,10 +190,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1835.Find XOR Sum of All Pairs Bitwise AND/README.md b/solution/1800-1899/1835.Find XOR Sum of All Pairs Bitwise AND/README.md index 26d7e82fbb08d..e38f82699c8bc 100644 --- a/solution/1800-1899/1835.Find XOR Sum of All Pairs Bitwise AND/README.md +++ b/solution/1800-1899/1835.Find XOR Sum of All Pairs Bitwise AND/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 假设数组 $arr1$ 的元素分别为 $a_1, a_2, \cdots, a_n$,数组 $arr2$ 的元素分别为 $b_1, b_2, \cdots, b_m$,那么题目答案为: @@ -72,10 +70,6 @@ $$ -### **Python3** - - - ```python class Solution: def getXORSum(self, arr1: List[int], arr2: List[int]) -> int: @@ -84,10 +78,6 @@ class Solution: return a & b ``` -### **Java** - - - ```java class Solution { public int getXORSum(int[] arr1, int[] arr2) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func getXORSum(arr1 []int, arr2 []int) int { var a, b int @@ -131,8 +117,6 @@ func getXORSum(arr1 []int, arr2 []int) int { } ``` -### **TypeScript** - ```ts function getXORSum(arr1: number[], arr2: number[]): number { const a = arr1.reduce((acc, x) => acc ^ x); @@ -141,10 +125,6 @@ function getXORSum(arr1: number[], arr2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1835.Find XOR Sum of All Pairs Bitwise AND/README_EN.md b/solution/1800-1899/1835.Find XOR Sum of All Pairs Bitwise AND/README_EN.md index aca506c9ef0d0..a63f3030b5cfa 100644 --- a/solution/1800-1899/1835.Find XOR Sum of All Pairs Bitwise AND/README_EN.md +++ b/solution/1800-1899/1835.Find XOR Sum of All Pairs Bitwise AND/README_EN.md @@ -44,7 +44,7 @@ The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0. ## Solutions -**Solution 1: Bitwise Operation** +### Solution 1: Bitwise Operation Assume that the elements of array $arr1$ are $a_1, a_2, ..., a_n$, and the elements of array $arr2$ are $b_1, b_2, ..., b_m$. Then, the answer to the problem is: @@ -69,8 +69,6 @@ The time complexity is $O(n + m)$, where $n$ and $m$ are the lengths of arrays $ -### **Python3** - ```python class Solution: def getXORSum(self, arr1: List[int], arr2: List[int]) -> int: @@ -79,8 +77,6 @@ class Solution: return a & b ``` -### **Java** - ```java class Solution { public int getXORSum(int[] arr1, int[] arr2) { @@ -96,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +103,6 @@ public: }; ``` -### **Go** - ```go func getXORSum(arr1 []int, arr2 []int) int { var a, b int @@ -124,8 +116,6 @@ func getXORSum(arr1 []int, arr2 []int) int { } ``` -### **TypeScript** - ```ts function getXORSum(arr1: number[], arr2: number[]): number { const a = arr1.reduce((acc, x) => acc ^ x); @@ -134,10 +124,6 @@ function getXORSum(arr1: number[], arr2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README.md b/solution/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README.md index 6ed3f9354b896..8568d7523a292 100644 --- a/solution/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README.md +++ b/solution/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以用哈希表 $cnt$ 统计链表中每个元素出现的次数,然后遍历链表,删除出现次数大于 1 的元素。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -82,10 +76,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -176,8 +162,6 @@ func deleteDuplicatesUnsorted(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -209,10 +193,6 @@ function deleteDuplicatesUnsorted(head: ListNode | null): ListNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README_EN.md b/solution/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README_EN.md index 3702a2ddc0948..ec1105dc95440 100644 --- a/solution/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README_EN.md +++ b/solution/1800-1899/1836.Remove Duplicates From an Unsorted Linked List/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We can use a hash table $cnt$ to count the number of occurrences of each element in the linked list, and then traverse the linked list to delete elements that appear more than once. @@ -51,8 +51,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -77,8 +75,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -169,8 +161,6 @@ func deleteDuplicatesUnsorted(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -202,10 +192,6 @@ function deleteDuplicatesUnsorted(head: ListNode | null): ListNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1837.Sum of Digits in Base K/README.md b/solution/1800-1899/1837.Sum of Digits in Base K/README.md index d5cc54f23b6d1..d0b8d78ac6618 100644 --- a/solution/1800-1899/1837.Sum of Digits in Base K/README.md +++ b/solution/1800-1899/1837.Sum of Digits in Base K/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 我们将 $n$ 除 $k$ 取余,直至为 $0$,余数相加即可得到结果。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def sumBase(self, n: int, k: int) -> int: @@ -63,10 +57,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int sumBase(int n, int k) { @@ -80,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +84,6 @@ public: }; ``` -### **Go** - ```go func sumBase(n int, k int) (ans int) { for n > 0 { @@ -108,26 +94,6 @@ func sumBase(n int, k int) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @param {number} k - * @return {number} - */ -var sumBase = function (n, k) { - let ans = 0; - while (n) { - ans += n % k; - n = Math.floor(n / k); - } - return ans; -}; -``` - -### **TypeScript** - ```ts function sumBase(n: number, k: number): number { let ans = 0; @@ -139,8 +105,6 @@ function sumBase(n: number, k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn sum_base(mut n: i32, k: i32) -> i32 { @@ -154,7 +118,21 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {number} n + * @param {number} k + * @return {number} + */ +var sumBase = function (n, k) { + let ans = 0; + while (n) { + ans += n % k; + n = Math.floor(n / k); + } + return ans; +}; +``` ```c int sumBase(int n, int k) { @@ -167,10 +145,6 @@ int sumBase(int n, int k) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1837.Sum of Digits in Base K/README_EN.md b/solution/1800-1899/1837.Sum of Digits in Base K/README_EN.md index dc8e8ed1072fb..cad8685e316b9 100644 --- a/solution/1800-1899/1837.Sum of Digits in Base K/README_EN.md +++ b/solution/1800-1899/1837.Sum of Digits in Base K/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics We divide $n$ by $k$ and take the remainder until it is $0$. The sum of the remainders gives the result. @@ -43,8 +43,6 @@ The time complexity is $O(\log_{k}n)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def sumBase(self, n: int, k: int) -> int: @@ -55,8 +53,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int sumBase(int n, int k) { @@ -70,8 +66,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -86,8 +80,6 @@ public: }; ``` -### **Go** - ```go func sumBase(n int, k int) (ans int) { for n > 0 { @@ -98,26 +90,6 @@ func sumBase(n int, k int) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @param {number} k - * @return {number} - */ -var sumBase = function (n, k) { - let ans = 0; - while (n) { - ans += n % k; - n = Math.floor(n / k); - } - return ans; -}; -``` - -### **TypeScript** - ```ts function sumBase(n: number, k: number): number { let ans = 0; @@ -129,8 +101,6 @@ function sumBase(n: number, k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn sum_base(mut n: i32, k: i32) -> i32 { @@ -144,7 +114,21 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {number} n + * @param {number} k + * @return {number} + */ +var sumBase = function (n, k) { + let ans = 0; + while (n) { + ans += n % k; + n = Math.floor(n / k); + } + return ans; +}; +``` ```c int sumBase(int n, int k) { @@ -157,10 +141,6 @@ int sumBase(int n, int k) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1838.Frequency of the Most Frequent Element/README.md b/solution/1800-1899/1838.Frequency of the Most Frequent Element/README.md index 03066ca80c195..d28e42d263a85 100644 --- a/solution/1800-1899/1838.Frequency of the Most Frequent Element/README.md +++ b/solution/1800-1899/1838.Frequency of the Most Frequent Element/README.md @@ -52,32 +52,14 @@ ## 解法 - - -**方法一:排序 + 滑动窗口** +### 方法一:排序 + 滑动窗口 我们可以先对数组 $nums$ 进行排序,然后枚举每个数作为最高频元素,用滑动窗口维护下标 $l$ 到 $r$ 的数都增加到 $nums[r]$ 的操作次数。如果操作次数大于 $k$,则窗口左端右移,直到操作次数小于等于 $k$。这样,我们就可以求出以每个数为最高频元素的最大频数。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 $nums$ 的长度。 -**方法二:排序 + 前缀和 + 二分查找** - -我们观察发现,如果一个区间长度 $cnt$ 满足条件,那么区间长度小于 $cnt$ 的也一定满足条件。因此,我们可以使用二分查找的方法,找到最大的且满足条件的区间长度。 - -在二分查找之前,我们需要对数组 $nums[r]$ 进行排序,然后计算出数组 $nums[r]$ 的前缀和数组 $s$,其中 $s[i]$ 表示数组 $nums[r]$ 前 $i$ 个数的和。这样,我们就可以在 $O(1)$ 的时间内求出区间 $[i, j]$ 的和为 $s[j + 1] - s[i]$。 - -接下来,我们定义二分的左边界 $left=1$, $right=n$。然后二分枚举区间长度 $mid$,如果当前区间长度 $mid$ 满足条件,那么我们就更新二分的左边界为 $mid$,否则更新二分的右边界为 $mid-1$。最后,我们返回二分的左边界即可。 - -问题转换为如何判断区间长度为 $cnt$ 的区间是否满足条件。我们在 $[0,..n-cnt]$ 范围内枚举左端点 $i$,那么此时区间的右端点 $j = i + cnt - 1$。要把区间内的所有数都增加到 $nums[j]$,需要的操作次数为 $nums[j] \times cnt - (s[j + 1] - s[i])$。如果这个操作次数小于等于 $k$,那么说明区间长度为 $cnt$ 的区间满足条件,返回 `true`。否则枚举结束,返回 `false`。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 - -### **Python3** - - - ```python class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: @@ -94,6 +76,115 @@ class Solution: return ans ``` +```java +class Solution { + public int maxFrequency(int[] nums, int k) { + Arrays.sort(nums); + int n = nums.length; + int ans = 1, window = 0; + for (int l = 0, r = 1; r < n; ++r) { + window += (nums[r] - nums[r - 1]) * (r - l); + while (window > k) { + window -= (nums[r] - nums[l++]); + } + ans = Math.max(ans, r - l + 1); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maxFrequency(vector& nums, int k) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + int ans = 1; + long long window = 0; + for (int l = 0, r = 1; r < n; ++r) { + window += 1LL * (nums[r] - nums[r - 1]) * (r - l); + while (window > k) { + window -= (nums[r] - nums[l++]); + } + ans = max(ans, r - l + 1); + } + return ans; + } +}; +``` + +```go +func maxFrequency(nums []int, k int) int { + sort.Ints(nums) + ans, window := 1, 0 + for l, r := 0, 1; r < len(nums); r++ { + window += (nums[r] - nums[r-1]) * (r - l) + for window > k { + window -= nums[r] - nums[l] + l++ + } + ans = max(ans, r-l+1) + } + return ans +} +``` + +```ts +function maxFrequency(nums: number[], k: number): number { + nums.sort((a, b) => a - b); + let ans = 1; + let window = 0; + const n = nums.length; + for (let l = 0, r = 1; r < n; ++r) { + window += (nums[r] - nums[r - 1]) * (r - l); + while (window > k) { + window -= nums[r] - nums[l++]; + } + ans = Math.max(ans, r - l + 1); + } + return ans; +} +``` + +```js +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var maxFrequency = function (nums, k) { + nums.sort((a, b) => a - b); + let ans = 1; + let window = 0; + const n = nums.length; + for (let l = 0, r = 1; r < n; ++r) { + window += (nums[r] - nums[r - 1]) * (r - l); + while (window > k) { + window -= nums[r] - nums[l++]; + } + ans = Math.max(ans, r - l + 1); + } + return ans; +}; +``` + + + +### 方法二:排序 + 前缀和 + 二分查找 + +我们观察发现,如果一个区间长度 $cnt$ 满足条件,那么区间长度小于 $cnt$ 的也一定满足条件。因此,我们可以使用二分查找的方法,找到最大的且满足条件的区间长度。 + +在二分查找之前,我们需要对数组 $nums[r]$ 进行排序,然后计算出数组 $nums[r]$ 的前缀和数组 $s$,其中 $s[i]$ 表示数组 $nums[r]$ 前 $i$ 个数的和。这样,我们就可以在 $O(1)$ 的时间内求出区间 $[i, j]$ 的和为 $s[j + 1] - s[i]$。 + +接下来,我们定义二分的左边界 $left=1$, $right=n$。然后二分枚举区间长度 $mid$,如果当前区间长度 $mid$ 满足条件,那么我们就更新二分的左边界为 $mid$,否则更新二分的右边界为 $mid-1$。最后,我们返回二分的左边界即可。 + +问题转换为如何判断区间长度为 $cnt$ 的区间是否满足条件。我们在 $[0,..n-cnt]$ 范围内枚举左端点 $i$,那么此时区间的右端点 $j = i + cnt - 1$。要把区间内的所有数都增加到 $nums[j]$,需要的操作次数为 $nums[j] \times cnt - (s[j + 1] - s[i])$。如果这个操作次数小于等于 $k$,那么说明区间长度为 $cnt$ 的区间满足条件,返回 `true`。否则枚举结束,返回 `false`。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 + + + ```python class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: @@ -117,28 +208,6 @@ class Solution: return left ``` -### **Java** - - - -```java -class Solution { - public int maxFrequency(int[] nums, int k) { - Arrays.sort(nums); - int n = nums.length; - int ans = 1, window = 0; - for (int l = 0, r = 1; r < n; ++r) { - window += (nums[r] - nums[r - 1]) * (r - l); - while (window > k) { - window -= (nums[r] - nums[l++]); - } - ans = Math.max(ans, r - l + 1); - } - return ans; - } -} -``` - ```java class Solution { private long[] s; @@ -179,28 +248,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maxFrequency(vector& nums, int k) { - sort(nums.begin(), nums.end()); - int n = nums.size(); - int ans = 1; - long long window = 0; - for (int l = 0, r = 1; r < n; ++r) { - window += 1LL * (nums[r] - nums[r - 1]) * (r - l); - while (window > k) { - window -= (nums[r] - nums[l++]); - } - ans = max(ans, r - l + 1); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -235,24 +282,6 @@ public: }; ``` -### **Go** - -```go -func maxFrequency(nums []int, k int) int { - sort.Ints(nums) - ans, window := 1, 0 - for l, r := 0, 1; r < len(nums); r++ { - window += (nums[r] - nums[r-1]) * (r - l) - for window > k { - window -= nums[r] - nums[l] - l++ - } - ans = max(ans, r-l+1) - } - return ans -} -``` - ```go func maxFrequency(nums []int, k int) int { sort.Ints(nums) @@ -283,44 +312,15 @@ func maxFrequency(nums []int, k int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var maxFrequency = function (nums, k) { - nums.sort((a, b) => a - b); - let ans = 1; - let window = 0; - const n = nums.length; - for (let l = 0, r = 1; r < n; ++r) { - window += (nums[r] - nums[r - 1]) * (r - l); - while (window > k) { - window -= nums[r] - nums[l++]; - } - ans = Math.max(ans, r - l + 1); - } - return ans; -}; -``` - -```js -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var maxFrequency = function (nums, k) { +```ts +function maxFrequency(nums: number[], k: number): number { nums.sort((a, b) => a - b); const n = nums.length; const s = new Array(n + 1).fill(0); for (let i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } - const check = cnt => { + const check = (cnt: number) => { for (let i = 0; i < n + 1 - cnt; ++i) { const j = i + cnt - 1; if (nums[j] * cnt - (s[j + 1] - s[i]) <= k) { @@ -340,37 +340,23 @@ var maxFrequency = function (nums, k) { } } return left; -}; -``` - -### **TypeScript** - -```ts -function maxFrequency(nums: number[], k: number): number { - nums.sort((a, b) => a - b); - let ans = 1; - let window = 0; - const n = nums.length; - for (let l = 0, r = 1; r < n; ++r) { - window += (nums[r] - nums[r - 1]) * (r - l); - while (window > k) { - window -= nums[r] - nums[l++]; - } - ans = Math.max(ans, r - l + 1); - } - return ans; } ``` -```ts -function maxFrequency(nums: number[], k: number): number { +```js +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var maxFrequency = function (nums, k) { nums.sort((a, b) => a - b); const n = nums.length; const s = new Array(n + 1).fill(0); for (let i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } - const check = (cnt: number) => { + const check = cnt => { for (let i = 0; i < n + 1 - cnt; ++i) { const j = i + cnt - 1; if (nums[j] * cnt - (s[j + 1] - s[i]) <= k) { @@ -390,13 +376,9 @@ function maxFrequency(nums: number[], k: number): number { } } return left; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/1800-1899/1838.Frequency of the Most Frequent Element/README_EN.md b/solution/1800-1899/1838.Frequency of the Most Frequent Element/README_EN.md index 7f379cea68b3c..1ecee4b24cee4 100644 --- a/solution/1800-1899/1838.Frequency of the Most Frequent Element/README_EN.md +++ b/solution/1800-1899/1838.Frequency of the Most Frequent Element/README_EN.md @@ -48,28 +48,10 @@ Explanation:
Increment the first element three times and the second ele ## Solutions -**Method 1: Sorting + Sliding Window** - -We can first sort the array $nums$, then enumerate each number as the most frequent element, and use a sliding window to maintain the number of operations to increase all numbers from index $l$ to $r$ to $nums[r]$. If the number of operations is greater than $k$, the left end of the window moves to the right until the number of operations is less than or equal to $k$. In this way, we can find out the maximum frequency for each number as the most frequent element. - -The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Where $n$ is the length of the array $nums$. - -**Method 2: Sorting + Prefix Sum + Binary Search** - -We observe that if a range length $cnt$ meets the condition, then the range length less than $cnt$ must also meet the condition. Therefore, we can use the method of binary search to find the maximum range length that meets the condition. - -Before binary search, we need to sort the array $nums[r]$, then calculate the prefix sum array $s$ of the array $nums[r]$, where $s[i]$ represents the sum of the first $i$ numbers in the array $nums[r]$. In this way, we can find the sum of the range $[i, j]$ is $s[j + 1] - s[i]$ in $O(1)$ time. - -Next, we define the left boundary of the binary search as $left=1$, $right=n$. Then we binary search the range length $mid$, if the current range length $mid$ meets the condition, then we update the left boundary of the binary search to $mid$, otherwise update the right boundary of the binary search to $mid-1$. Finally, we return the left boundary of the binary search. - -The problem is transformed into how to judge whether the range with length $cnt$ meets the condition. We enumerate the left endpoint $i$ in the range $[0,..n-cnt]$, then the right endpoint of the range at this time is $j = i + cnt - 1$. The number of operations required to increase all numbers in the range to $nums[j]$ is $nums[j] \times cnt - (s[j + 1] - s[i])$. If this number of operations is less than or equal to $k$, it means that the range with length $cnt$ meets the condition, return `true`. Otherwise, the enumeration ends, return `false`. - -The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$. +### Solution 1 -### **Python3** - ```python class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: @@ -86,6 +68,105 @@ class Solution: return ans ``` +```java +class Solution { + public int maxFrequency(int[] nums, int k) { + Arrays.sort(nums); + int n = nums.length; + int ans = 1, window = 0; + for (int l = 0, r = 1; r < n; ++r) { + window += (nums[r] - nums[r - 1]) * (r - l); + while (window > k) { + window -= (nums[r] - nums[l++]); + } + ans = Math.max(ans, r - l + 1); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maxFrequency(vector& nums, int k) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + int ans = 1; + long long window = 0; + for (int l = 0, r = 1; r < n; ++r) { + window += 1LL * (nums[r] - nums[r - 1]) * (r - l); + while (window > k) { + window -= (nums[r] - nums[l++]); + } + ans = max(ans, r - l + 1); + } + return ans; + } +}; +``` + +```go +func maxFrequency(nums []int, k int) int { + sort.Ints(nums) + ans, window := 1, 0 + for l, r := 0, 1; r < len(nums); r++ { + window += (nums[r] - nums[r-1]) * (r - l) + for window > k { + window -= nums[r] - nums[l] + l++ + } + ans = max(ans, r-l+1) + } + return ans +} +``` + +```ts +function maxFrequency(nums: number[], k: number): number { + nums.sort((a, b) => a - b); + let ans = 1; + let window = 0; + const n = nums.length; + for (let l = 0, r = 1; r < n; ++r) { + window += (nums[r] - nums[r - 1]) * (r - l); + while (window > k) { + window -= nums[r] - nums[l++]; + } + ans = Math.max(ans, r - l + 1); + } + return ans; +} +``` + +```js +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var maxFrequency = function (nums, k) { + nums.sort((a, b) => a - b); + let ans = 1; + let window = 0; + const n = nums.length; + for (let l = 0, r = 1; r < n; ++r) { + window += (nums[r] - nums[r - 1]) * (r - l); + while (window > k) { + window -= nums[r] - nums[l++]; + } + ans = Math.max(ans, r - l + 1); + } + return ans; +}; +``` + + + +### Solution 2 + + + ```python class Solution: def maxFrequency(self, nums: List[int], k: int) -> int: @@ -109,26 +190,6 @@ class Solution: return left ``` -### **Java** - -```java -class Solution { - public int maxFrequency(int[] nums, int k) { - Arrays.sort(nums); - int n = nums.length; - int ans = 1, window = 0; - for (int l = 0, r = 1; r < n; ++r) { - window += (nums[r] - nums[r - 1]) * (r - l); - while (window > k) { - window -= (nums[r] - nums[l++]); - } - ans = Math.max(ans, r - l + 1); - } - return ans; - } -} -``` - ```java class Solution { private long[] s; @@ -169,28 +230,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maxFrequency(vector& nums, int k) { - sort(nums.begin(), nums.end()); - int n = nums.size(); - int ans = 1; - long long window = 0; - for (int l = 0, r = 1; r < n; ++r) { - window += 1LL * (nums[r] - nums[r - 1]) * (r - l); - while (window > k) { - window -= (nums[r] - nums[l++]); - } - ans = max(ans, r - l + 1); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -225,24 +264,6 @@ public: }; ``` -### **Go** - -```go -func maxFrequency(nums []int, k int) int { - sort.Ints(nums) - ans, window := 1, 0 - for l, r := 0, 1; r < len(nums); r++ { - window += (nums[r] - nums[r-1]) * (r - l) - for window > k { - window -= nums[r] - nums[l] - l++ - } - ans = max(ans, r-l+1) - } - return ans -} -``` - ```go func maxFrequency(nums []int, k int) int { sort.Ints(nums) @@ -273,44 +294,15 @@ func maxFrequency(nums []int, k int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var maxFrequency = function (nums, k) { - nums.sort((a, b) => a - b); - let ans = 1; - let window = 0; - const n = nums.length; - for (let l = 0, r = 1; r < n; ++r) { - window += (nums[r] - nums[r - 1]) * (r - l); - while (window > k) { - window -= nums[r] - nums[l++]; - } - ans = Math.max(ans, r - l + 1); - } - return ans; -}; -``` - -```js -/** - * @param {number[]} nums - * @param {number} k - * @return {number} - */ -var maxFrequency = function (nums, k) { +```ts +function maxFrequency(nums: number[], k: number): number { nums.sort((a, b) => a - b); const n = nums.length; const s = new Array(n + 1).fill(0); for (let i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } - const check = cnt => { + const check = (cnt: number) => { for (let i = 0; i < n + 1 - cnt; ++i) { const j = i + cnt - 1; if (nums[j] * cnt - (s[j + 1] - s[i]) <= k) { @@ -330,37 +322,23 @@ var maxFrequency = function (nums, k) { } } return left; -}; -``` - -### **TypeScript** - -```ts -function maxFrequency(nums: number[], k: number): number { - nums.sort((a, b) => a - b); - let ans = 1; - let window = 0; - const n = nums.length; - for (let l = 0, r = 1; r < n; ++r) { - window += (nums[r] - nums[r - 1]) * (r - l); - while (window > k) { - window -= nums[r] - nums[l++]; - } - ans = Math.max(ans, r - l + 1); - } - return ans; } ``` -```ts -function maxFrequency(nums: number[], k: number): number { +```js +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var maxFrequency = function (nums, k) { nums.sort((a, b) => a - b); const n = nums.length; const s = new Array(n + 1).fill(0); for (let i = 0; i < n; ++i) { s[i + 1] = s[i] + nums[i]; } - const check = (cnt: number) => { + const check = cnt => { for (let i = 0; i < n + 1 - cnt; ++i) { const j = i + cnt - 1; if (nums[j] * cnt - (s[j + 1] - s[i]) <= k) { @@ -380,13 +358,9 @@ function maxFrequency(nums: number[], k: number): number { } } return left; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/1800-1899/1839.Longest Substring Of All Vowels in Order/README.md b/solution/1800-1899/1839.Longest Substring Of All Vowels in Order/README.md index 095a00b6ccb17..9ff9367a1453d 100644 --- a/solution/1800-1899/1839.Longest Substring Of All Vowels in Order/README.md +++ b/solution/1800-1899/1839.Longest Substring Of All Vowels in Order/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:双指针 + 模拟** +### 方法一:双指针 + 模拟 我们可以先将字符串 `word` 做个转化,比如对于 `word="aaaeiouu"`,我们可以将其转化为数据项 `('a', 3)`, `('e', 1)`, `('i', 1)`, `('o', 1)`, `('u', 2)`,存放在数组 `arr` 中。其中每个数据项的第一个元素表示元音字母,第二个元素表示该元音字母连续出现的次数。这部分转化可以通过双指针来实现。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def longestBeautifulSubstring(self, word: str) -> int: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestBeautifulSubstring(String word) { @@ -131,8 +121,6 @@ class Node { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go func longestBeautifulSubstring(word string) (ans int) { arr := []pair{} @@ -190,10 +176,6 @@ type pair struct { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1839.Longest Substring Of All Vowels in Order/README_EN.md b/solution/1800-1899/1839.Longest Substring Of All Vowels in Order/README_EN.md index 2f257483cfee0..2b112a3a40b73 100644 --- a/solution/1800-1899/1839.Longest Substring Of All Vowels in Order/README_EN.md +++ b/solution/1800-1899/1839.Longest Substring Of All Vowels in Order/README_EN.md @@ -51,7 +51,7 @@ ## Solutions -**Solution 1: Two Pointers + Simulation** +### Solution 1: Two Pointers + Simulation We can first transform the string `word`. For example, for `word="aaaeiouu"`, we can transform it into data items `('a', 3)`, `('e', 1)`, `('i', 1)`, `('o', 1)`, `('u', 2)` and store them in an array `arr`. Each data item's first element represents a vowel, and the second element represents the number of times the vowel appears consecutively. This transformation can be implemented using two pointers. @@ -61,8 +61,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def longestBeautifulSubstring(self, word: str) -> int: @@ -83,8 +81,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestBeautifulSubstring(String word) { @@ -121,8 +117,6 @@ class Node { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +145,6 @@ public: }; ``` -### **Go** - ```go func longestBeautifulSubstring(word string) (ans int) { arr := []pair{} @@ -180,10 +172,6 @@ type pair struct { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1840.Maximum Building Height/README.md b/solution/1800-1899/1840.Maximum Building Height/README.md index a690b5b0746cd..09244b25e7a03 100644 --- a/solution/1800-1899/1840.Maximum Building Height/README.md +++ b/solution/1800-1899/1840.Maximum Building Height/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:排序 + 数学** +### 方法一:排序 + 数学 首先,我们将所有的限制条件按照建筑物的编号从小到大排序。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int: @@ -106,10 +100,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxBuilding(int n, int[][] restrictions) { @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +155,6 @@ public: }; ``` -### **Go** - ```go func maxBuilding(n int, restrictions [][]int) (ans int) { r := restrictions @@ -192,10 +178,6 @@ func maxBuilding(n int, restrictions [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1840.Maximum Building Height/README_EN.md b/solution/1800-1899/1840.Maximum Building Height/README_EN.md index f9c4795d88bb5..f7e7b3d9aa2e5 100644 --- a/solution/1800-1899/1840.Maximum Building Height/README_EN.md +++ b/solution/1800-1899/1840.Maximum Building Height/README_EN.md @@ -60,24 +60,10 @@ We can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest b ## Solutions -**Soution 1: Sorting + Mathematics** - -First, we sort all the restrictions by the building number in ascending order. - -Then we traverse all the restrictions from left to right. For each restriction, we can get an upper bound of the maximum height, that is, $r_i[1] = \min(r_i[1], r_{i-1}[1] + r_i[0] - r_{i-1}[0])$, where $r_i$ represents the $i$-th restriction, and $r_i[0]$ and $r_i[1]$ represent the building number and the upper bound of the maximum height of the building, respectively. - -Then we traverse all the restrictions from right to left. For each restriction, we can get an upper bound of the maximum height, that is, $r_i[1] = \min(r_i[1], r_{i+1}[1] + r_{i+1}[0] - r_i[0])$. - -In this way, we get the upper bound of the maximum height for each restricted building. - -The problem asks for the height of the tallest building. We can enumerate the buildings $i$ and $i+1$ between two adjacent restrictions. To maximize the height, the height should first increase and then decrease. Suppose the maximum height is $t$, then $t - r_i[1] + t - r_{i+1}[1] \leq r_{i+1}[0] - r_i[0]$, that is, $t \leq \frac{r_i[1] + r_{i+1}[1] + r_{i+1}[0] - r_{i}[0]}{2}$. We can take the maximum value among all $t$. - -The time complexity is $O(m \times \log m)$, and the space complexity is $O(m)$. Where $m$ is the number of restrictions. +### Solution 1 -### **Python3** - ```python class Solution: def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int: @@ -98,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxBuilding(int n, int[][] restrictions) { @@ -130,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +139,6 @@ public: }; ``` -### **Go** - ```go func maxBuilding(n int, restrictions [][]int) (ans int) { r := restrictions @@ -182,10 +162,6 @@ func maxBuilding(n int, restrictions [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1841.League Statistics/README.md b/solution/1800-1899/1841.League Statistics/README.md index d5028d59875e6..468e199a28eb4 100644 --- a/solution/1800-1899/1841.League Statistics/README.md +++ b/solution/1800-1899/1841.League Statistics/README.md @@ -97,14 +97,10 @@ Dortmund 是积分榜上的第一支球队. Ajax和Arsenal 有同样的分数, ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -146,3 +142,5 @@ ORDER BY points DESC, goal_diff DESC, team_name; ``` + + diff --git a/solution/1800-1899/1841.League Statistics/README_EN.md b/solution/1800-1899/1841.League Statistics/README_EN.md index 1a8d201f8ddea..886fac8f7708d 100644 --- a/solution/1800-1899/1841.League Statistics/README_EN.md +++ b/solution/1800-1899/1841.League Statistics/README_EN.md @@ -95,9 +95,9 @@ Dortmund is the first team in the table. Ajax and Arsenal have the same points, ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -140,3 +140,5 @@ ORDER BY points DESC, goal_diff DESC, team_name; ``` + + diff --git a/solution/1800-1899/1842.Next Palindrome Using Same Digits/README.md b/solution/1800-1899/1842.Next Palindrome Using Same Digits/README.md index 202179c5c907b..71ffbe41d5926 100644 --- a/solution/1800-1899/1842.Next Palindrome Using Same Digits/README.md +++ b/solution/1800-1899/1842.Next Palindrome Using Same Digits/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:求前一半的下一个排列** +### 方法一:求前一半的下一个排列 根据题目描述,我们只需要求出前一半的下一个排列,然后遍历前一半,对称赋值后半部分即可。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def nextPalindrome(self, num: str) -> str: @@ -89,10 +83,6 @@ class Solution: return "".join(nums) ``` -### **Java** - - - ```java class Solution { public String nextPalindrome(String num) { @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func nextPalindrome(num string) string { nums := []byte(num) @@ -191,8 +177,6 @@ func nextPermutation(nums []byte) bool { } ``` -### **TypeScript** - ```ts function nextPalindrome(num: string): string { const nums = num.split(''); @@ -227,10 +211,6 @@ function nextPermutation(nums: string[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1842.Next Palindrome Using Same Digits/README_EN.md b/solution/1800-1899/1842.Next Palindrome Using Same Digits/README_EN.md index 8c44f4dd9e8a6..5aab6a1fcaae3 100644 --- a/solution/1800-1899/1842.Next Palindrome Using Same Digits/README_EN.md +++ b/solution/1800-1899/1842.Next Palindrome Using Same Digits/README_EN.md @@ -45,7 +45,7 @@ ## Solutions -**Solution 1: Find the Next Permutation of the First Half** +### Solution 1: Find the Next Permutation of the First Half According to the problem description, we only need to find the next permutation of the first half of the string, then traverse the first half and symmetrically assign values to the second half. @@ -53,8 +53,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def nextPalindrome(self, num: str) -> str: @@ -81,8 +79,6 @@ class Solution: return "".join(nums) ``` -### **Java** - ```java class Solution { public String nextPalindrome(String num) { @@ -125,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +139,6 @@ public: }; ``` -### **Go** - ```go func nextPalindrome(num string) string { nums := []byte(num) @@ -181,8 +173,6 @@ func nextPermutation(nums []byte) bool { } ``` -### **TypeScript** - ```ts function nextPalindrome(num: string): string { const nums = num.split(''); @@ -217,10 +207,6 @@ function nextPermutation(nums: string[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1843.Suspicious Bank Accounts/README.md b/solution/1800-1899/1843.Suspicious Bank Accounts/README.md index 286f59ec88142..440deb2b39b86 100644 --- a/solution/1800-1899/1843.Suspicious Bank Accounts/README.md +++ b/solution/1800-1899/1843.Suspicious Bank Accounts/README.md @@ -97,14 +97,10 @@ Transactions 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -129,6 +125,12 @@ WHERE s1.marked = 1 AND s2.marked = 1 ORDER BY s1.tx; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below WITH @@ -151,3 +153,5 @@ ORDER BY tx; ``` + + diff --git a/solution/1800-1899/1843.Suspicious Bank Accounts/README_EN.md b/solution/1800-1899/1843.Suspicious Bank Accounts/README_EN.md index 7eed07ed210ac..86de6deb52163 100644 --- a/solution/1800-1899/1843.Suspicious Bank Accounts/README_EN.md +++ b/solution/1800-1899/1843.Suspicious Bank Accounts/README_EN.md @@ -95,9 +95,9 @@ We can see that the income exceeded the max income in May and July, but not in J ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -123,6 +123,12 @@ WHERE s1.marked = 1 AND s2.marked = 1 ORDER BY s1.tx; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below WITH @@ -145,3 +151,5 @@ ORDER BY tx; ``` + + diff --git a/solution/1800-1899/1844.Replace All Digits with Characters/README.md b/solution/1800-1899/1844.Replace All Digits with Characters/README.md index 5a61e159666d1..1066670be5b3d 100644 --- a/solution/1800-1899/1844.Replace All Digits with Characters/README.md +++ b/solution/1800-1899/1844.Replace All Digits with Characters/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 遍历字符串,对于奇数下标的字符,将其替换为前一个字符后移对应位数的字符。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def replaceDigits(self, s: str) -> str: @@ -76,10 +70,6 @@ class Solution: return ''.join(s) ``` -### **Java** - - - ```java class Solution { public String replaceDigits(String s) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func replaceDigits(s string) string { cs := []byte(s) @@ -119,8 +105,6 @@ func replaceDigits(s string) string { } ``` -### **TypeScript** - ```ts function replaceDigits(s: string): string { const n = s.length; @@ -132,8 +116,6 @@ function replaceDigits(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn replace_digits(s: String) -> String { @@ -149,8 +131,6 @@ impl Solution { } ``` -### **C** - ```c char* replaceDigits(char* s) { int n = strlen(s); @@ -161,10 +141,6 @@ char* replaceDigits(char* s) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1844.Replace All Digits with Characters/README_EN.md b/solution/1800-1899/1844.Replace All Digits with Characters/README_EN.md index 7b7aa83ce56dd..65b7ef0f01d64 100644 --- a/solution/1800-1899/1844.Replace All Digits with Characters/README_EN.md +++ b/solution/1800-1899/1844.Replace All Digits with Characters/README_EN.md @@ -49,7 +49,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation Traverse the string, for characters at odd indices, replace them with the character that is a certain number of positions after the previous character. @@ -59,8 +59,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. Ignori -### **Python3** - ```python class Solution: def replaceDigits(self, s: str) -> str: @@ -70,8 +68,6 @@ class Solution: return ''.join(s) ``` -### **Java** - ```java class Solution { public String replaceDigits(String s) { @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +93,6 @@ public: }; ``` -### **Go** - ```go func replaceDigits(s string) string { cs := []byte(s) @@ -111,8 +103,6 @@ func replaceDigits(s string) string { } ``` -### **TypeScript** - ```ts function replaceDigits(s: string): string { const n = s.length; @@ -124,8 +114,6 @@ function replaceDigits(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn replace_digits(s: String) -> String { @@ -141,8 +129,6 @@ impl Solution { } ``` -### **C** - ```c char* replaceDigits(char* s) { int n = strlen(s); @@ -153,10 +139,6 @@ char* replaceDigits(char* s) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1845.Seat Reservation Manager/README.md b/solution/1800-1899/1845.Seat Reservation Manager/README.md index 727644656d8a8..e5c023bc0adb8 100644 --- a/solution/1800-1899/1845.Seat Reservation Manager/README.md +++ b/solution/1800-1899/1845.Seat Reservation Manager/README.md @@ -52,9 +52,7 @@ seatManager.unreserve(5); // 将座位 5 变为可以预约,现在可预约的 ## 解法 - - -**方法一:优先队列(小根堆)** +### 方法一:优先队列(小根堆) 我们可以使用优先队列(小根堆)来维护可预约座位的最小编号。 @@ -68,10 +66,6 @@ seatManager.unreserve(5); // 将座位 5 变为可以预约,现在可预约的 -### **Python3** - - - ```python class SeatManager: def __init__(self, n: int): @@ -91,10 +85,6 @@ class SeatManager: # obj.unreserve(seatNumber) ``` -### **Java** - - - ```java class SeatManager { private PriorityQueue q = new PriorityQueue<>(); @@ -122,8 +112,6 @@ class SeatManager { */ ``` -### **C++** - ```cpp class SeatManager { public: @@ -155,8 +143,6 @@ private: */ ``` -### **Go** - ```go type SeatManager struct { q hp @@ -197,8 +183,6 @@ func (h *hp) Pop() any { */ ``` -### **C#** - ```cs public class SeatManager { private SortedSet availableSeats; @@ -229,10 +213,6 @@ public class SeatManager { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1845.Seat Reservation Manager/README_EN.md b/solution/1800-1899/1845.Seat Reservation Manager/README_EN.md index f83ba80bf6162..80adefd659b61 100644 --- a/solution/1800-1899/1845.Seat Reservation Manager/README_EN.md +++ b/solution/1800-1899/1845.Seat Reservation Manager/README_EN.md @@ -49,7 +49,7 @@ seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5 ## Solutions -**Solution 1: Priority Queue (Min Heap)** +### Solution 1: Priority Queue (Min Heap) We can use a priority queue (min heap) to maintain the smallest number of reservable seats. @@ -63,8 +63,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class SeatManager: def __init__(self, n: int): @@ -84,8 +82,6 @@ class SeatManager: # obj.unreserve(seatNumber) ``` -### **Java** - ```java class SeatManager { private PriorityQueue q = new PriorityQueue<>(); @@ -113,8 +109,6 @@ class SeatManager { */ ``` -### **C++** - ```cpp class SeatManager { public: @@ -146,8 +140,6 @@ private: */ ``` -### **Go** - ```go type SeatManager struct { q hp @@ -188,8 +180,6 @@ func (h *hp) Pop() any { */ ``` -### **C#** - ```cs public class SeatManager { private SortedSet availableSeats; @@ -220,10 +210,6 @@ public class SeatManager { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README.md b/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README.md index 58248789592c8..8e4132b3db35c 100644 --- a/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README.md +++ b/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README.md @@ -67,9 +67,7 @@ arr 中最大元素为 3 。 ## 解法 - - -**方法一:排序 + 贪心** +### 方法一:排序 + 贪心 我们先对数组进行排序,然后将数组的第一个元素设置为 $1$。 @@ -81,10 +79,6 @@ arr 中最大元素为 3 。 -### **Python3** - - - ```python class Solution: def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int: @@ -96,10 +90,6 @@ class Solution: return max(arr) ``` -### **Java** - - - ```java class Solution { public int maximumElementAfterDecrementingAndRearranging(int[] arr) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func maximumElementAfterDecrementingAndRearranging(arr []int) int { sort.Ints(arr) @@ -151,8 +137,6 @@ func maximumElementAfterDecrementingAndRearranging(arr []int) int { } ``` -### **TypeScript** - ```ts function maximumElementAfterDecrementingAndRearranging(arr: number[]): number { arr.sort((a, b) => a - b); @@ -167,8 +151,6 @@ function maximumElementAfterDecrementingAndRearranging(arr: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int MaximumElementAfterDecrementingAndRearranging(int[] arr) { @@ -183,10 +165,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README_EN.md b/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README_EN.md index 729f297ebf90e..ff3c68f8bd68c 100644 --- a/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README_EN.md +++ b/solution/1800-1899/1846.Maximum Element After Decreasing and Rearranging/README_EN.md @@ -63,7 +63,7 @@ The largest element in arr is 3. ## Solutions -**Solution 1: Sorting + Greedy Algorithm** +### Solution 1: Sorting + Greedy Algorithm First, we sort the array and then set the first element of the array to $1$. @@ -75,8 +75,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int: @@ -88,8 +86,6 @@ class Solution: return max(arr) ``` -### **Java** - ```java class Solution { public int maximumElementAfterDecrementingAndRearranging(int[] arr) { @@ -106,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +119,6 @@ public: }; ``` -### **Go** - ```go func maximumElementAfterDecrementingAndRearranging(arr []int) int { sort.Ints(arr) @@ -141,8 +133,6 @@ func maximumElementAfterDecrementingAndRearranging(arr []int) int { } ``` -### **TypeScript** - ```ts function maximumElementAfterDecrementingAndRearranging(arr: number[]): number { arr.sort((a, b) => a - b); @@ -157,8 +147,6 @@ function maximumElementAfterDecrementingAndRearranging(arr: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int MaximumElementAfterDecrementingAndRearranging(int[] arr) { @@ -173,10 +161,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1847.Closest Room/README.md b/solution/1800-1899/1847.Closest Room/README.md index 686244faf10c9..b6ef4ef692f51 100644 --- a/solution/1800-1899/1847.Closest Room/README.md +++ b/solution/1800-1899/1847.Closest Room/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:离线查询 + 有序集合 + 二分查找** +### 方法一:离线查询 + 有序集合 + 二分查找 我们注意到,查询的顺序并不影响答案,而且题目中涉及到房间面积的大小关系,因此,我们可以将查询按照最小面积从小到大排序,这样我们就可以从小到大依次处理每个查询。另外,我们也将房间按照面积从小到大排序。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -103,10 +97,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] closestRoom(int[][] rooms, int[][] queries) { @@ -150,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -197,8 +185,6 @@ public: }; ``` -### **Go** - ```go func closestRoom(rooms [][]int, queries [][]int) []int { n, k := len(rooms), len(queries) @@ -250,10 +236,6 @@ func closestRoom(rooms [][]int, queries [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1847.Closest Room/README_EN.md b/solution/1800-1899/1847.Closest Room/README_EN.md index 63671490189ee..fcc70a459faa6 100644 --- a/solution/1800-1899/1847.Closest Room/README_EN.md +++ b/solution/1800-1899/1847.Closest Room/README_EN.md @@ -52,7 +52,7 @@ Query = [2,5]: Room number 3 is the only room with a size of at least 5. The ans ## Solutions -**Solution 1: Offline Query + Ordered Set + Binary Search** +### Solution 1: Offline Query + Ordered Set + Binary Search We notice that the order of queries does not affect the answer, and the problem involves the size relationship of room areas. Therefore, we can sort the queries in ascending order of minimum area, so that we can process each query from small to large. Also, we sort the rooms in ascending order of area. @@ -64,8 +64,6 @@ The time complexity is $O(n \times \log n + k \times \log k)$, and the space com -### **Python3** - ```python from sortedcontainers import SortedList @@ -95,8 +93,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] closestRoom(int[][] rooms, int[][] queries) { @@ -140,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -187,8 +181,6 @@ public: }; ``` -### **Go** - ```go func closestRoom(rooms [][]int, queries [][]int) []int { n, k := len(rooms), len(queries) @@ -240,10 +232,6 @@ func closestRoom(rooms [][]int, queries [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1848.Minimum Distance to the Target Element/README.md b/solution/1800-1899/1848.Minimum Distance to the Target Element/README.md index c7df61c61e413..f8612e6f97064 100644 --- a/solution/1800-1899/1848.Minimum Distance to the Target Element/README.md +++ b/solution/1800-1899/1848.Minimum Distance to the Target Element/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 遍历数组,找到所有等于 $target$ 的下标,然后计算 $|i - start|$,取最小值即可。 @@ -61,20 +59,12 @@ -### **Python3** - - - ```python class Solution: def getMinDistance(self, nums: List[int], target: int, start: int) -> int: return min(abs(i - start) for i, x in enumerate(nums) if x == target) ``` -### **Java** - - - ```java class Solution { public int getMinDistance(int[] nums, int target, int start) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +96,6 @@ public: }; ``` -### **Go** - ```go func getMinDistance(nums []int, target int, start int) int { ans := 1 << 30 @@ -129,8 +115,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function getMinDistance(nums: number[], target: number, start: number): number { let ans = Infinity; @@ -143,8 +127,6 @@ function getMinDistance(nums: number[], target: number, start: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn get_min_distance(nums: Vec, target: i32, start: i32) -> i32 { @@ -158,10 +140,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1848.Minimum Distance to the Target Element/README_EN.md b/solution/1800-1899/1848.Minimum Distance to the Target Element/README_EN.md index a36485733b223..c75727956708f 100644 --- a/solution/1800-1899/1848.Minimum Distance to the Target Element/README_EN.md +++ b/solution/1800-1899/1848.Minimum Distance to the Target Element/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Single Pass** +### Solution 1: Single Pass Traverse the array, find all indices equal to $target$, then calculate $|i - start|$, and take the minimum value. @@ -55,16 +55,12 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def getMinDistance(self, nums: List[int], target: int, start: int) -> int: return min(abs(i - start) for i, x in enumerate(nums) if x == target) ``` -### **Java** - ```java class Solution { public int getMinDistance(int[] nums, int target, int start) { @@ -80,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +92,6 @@ public: }; ``` -### **Go** - ```go func getMinDistance(nums []int, target int, start int) int { ans := 1 << 30 @@ -119,8 +111,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function getMinDistance(nums: number[], target: number, start: number): number { let ans = Infinity; @@ -133,8 +123,6 @@ function getMinDistance(nums: number[], target: number, start: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn get_min_distance(nums: Vec, target: i32, start: i32) -> i32 { @@ -148,10 +136,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README.md b/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README.md index 4f96ba4ecfe9e..f4e02cd80188f 100644 --- a/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README.md +++ b/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 从字符串的第一个字符开始,枚举所有可能的拆分位置,判断拆分出来的子串是否满足题目要求,如果满足则继续递归判断剩余的子串是否满足题目要求,直到遍历完整个字符串。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def splitString(self, s: str) -> bool: @@ -95,10 +89,6 @@ class Solution: return dfs(0, -1, 0) ``` -### **Java** - - - ```java class Solution { private String s; @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go func splitString(s string) bool { var dfs func(i, x, k int) bool @@ -176,10 +162,6 @@ func splitString(s string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md b/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md index cbfee9331af28..54096be76949c 100644 --- a/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md +++ b/solution/1800-1899/1849.Splitting a String Into Descending Consecutive Values/README_EN.md @@ -53,7 +53,7 @@ The values are in descending order with adjacent values differing by 1. ## Solutions -**Solution 1: DFS (Depth-First Search)** +### Solution 1: DFS (Depth-First Search) Starting from the first character of the string, enumerate all possible split positions. Check if the split substring meets the requirements of the problem. If it does, continue to recursively check whether the remaining substring meets the requirements, until the entire string is traversed. @@ -61,8 +61,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ i -### **Python3** - ```python class Solution: def splitString(self, s: str) -> bool: @@ -79,8 +77,6 @@ class Solution: return dfs(0, -1, 0) ``` -### **Java** - ```java class Solution { private String s; @@ -106,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +127,6 @@ public: }; ``` -### **Go** - ```go func splitString(s string) bool { var dfs func(i, x, k int) bool @@ -158,10 +150,6 @@ func splitString(s string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README.md b/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README.md index 9ca361dfbcbb6..1e76b65b779e6 100644 --- a/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README.md +++ b/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:求下一个排列 + 逆序对** +### 方法一:求下一个排列 + 逆序对 我们可以调用 $k$ 次 `next_permutation` 函数,得到第 $k$ 个最小妙数 $s$。 @@ -97,10 +95,6 @@ $$ -### **Python3** - - - ```python class Solution: def getMinSwaps(self, num: str, k: int) -> int: @@ -135,10 +129,6 @@ class Solution: return sum(arr[j] > arr[i] for i in range(n) for j in range(i)) ``` -### **Java** - - - ```java class Solution { public int getMinSwaps(String num, int k) { @@ -196,8 +186,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -229,8 +217,6 @@ public: }; ``` -### **Go** - ```go func getMinSwaps(num string, k int) (ans int) { s := []byte(num) @@ -281,8 +267,6 @@ func nextPermutation(nums []byte) bool { } ``` -### **TypeScript** - ```ts function getMinSwaps(num: string, k: number): number { const n = num.length; @@ -331,10 +315,6 @@ function nextPermutation(nums: string[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README_EN.md b/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README_EN.md index 712c42d049db9..47dc743e24caf 100644 --- a/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README_EN.md +++ b/solution/1800-1899/1850.Minimum Adjacent Swaps to Reach the Kth Smallest Number/README_EN.md @@ -66,7 +66,7 @@ ## Solutions -**Solution 1: Find Next Permutation + Inversion Pairs** +### Solution 1: Find Next Permutation + Inversion Pairs We can call the `next_permutation` function $k$ times to get the $k$th smallest permutation $s$. @@ -94,8 +94,6 @@ The time complexity is $O(n \times (k + n))$, and the space complexity is $O(n)$ -### **Python3** - ```python class Solution: def getMinSwaps(self, num: str, k: int) -> int: @@ -130,8 +128,6 @@ class Solution: return sum(arr[j] > arr[i] for i in range(n) for j in range(i)) ``` -### **Java** - ```java class Solution { public int getMinSwaps(String num, int k) { @@ -189,8 +185,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -222,8 +216,6 @@ public: }; ``` -### **Go** - ```go func getMinSwaps(num string, k int) (ans int) { s := []byte(num) @@ -274,8 +266,6 @@ func nextPermutation(nums []byte) bool { } ``` -### **TypeScript** - ```ts function getMinSwaps(num: string, k: number): number { const n = num.length; @@ -324,10 +314,6 @@ function nextPermutation(nums: string[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1851.Minimum Interval to Include Each Query/README.md b/solution/1800-1899/1851.Minimum Interval to Include Each Query/README.md index b9c347f00d802..a76712356dcd9 100644 --- a/solution/1800-1899/1851.Minimum Interval to Include Each Query/README.md +++ b/solution/1800-1899/1851.Minimum Interval to Include Each Query/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:排序 + 离线查询 + 优先队列(小根堆)** +### 方法一:排序 + 离线查询 + 优先队列(小根堆) 我们注意到,题目中查询的顺序并不会影响答案,并且涉及到的区间也不会发生变化,因此,我们考虑将所有的查询按照从小到大的顺序进行排序,同时将所有的区间按照左端点从小到大的顺序进行排序。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]: @@ -97,10 +91,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] minInterval(int[][] intervals, int[] queries) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go func minInterval(intervals [][]int, queries []int) []int { n, m := len(intervals), len(queries) @@ -210,10 +196,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1851.Minimum Interval to Include Each Query/README_EN.md b/solution/1800-1899/1851.Minimum Interval to Include Each Query/README_EN.md index 2fa6984e19e21..a25effbba514e 100644 --- a/solution/1800-1899/1851.Minimum Interval to Include Each Query/README_EN.md +++ b/solution/1800-1899/1851.Minimum Interval to Include Each Query/README_EN.md @@ -48,7 +48,7 @@ ## Solutions -**Solution 1: Sorting + Offline Query + Priority Queue (Min Heap)** +### Solution 1: Sorting + Offline Query + Priority Queue (Min Heap) We notice that the order of queries does not affect the answer, and the intervals involved do not change. Therefore, we consider sorting all queries in ascending order, and sorting all intervals in ascending order of the left endpoint. @@ -66,8 +66,6 @@ The time complexity is $O(n \times \log n + m \times \log m)$, and the space com -### **Python3** - ```python class Solution: def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]: @@ -89,8 +87,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] minInterval(int[][] intervals, int[] queries) { @@ -123,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +152,6 @@ public: }; ``` -### **Go** - ```go func minInterval(intervals [][]int, queries []int) []int { n, m := len(intervals), len(queries) @@ -200,10 +192,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/README.md b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/README.md index ebc35cd961d2b..e474f708773cc 100644 --- a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/README.md +++ b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:滑动窗口 + 哈希表或数组** +### 方法一:滑动窗口 + 哈希表或数组 我们用一个哈希表或数组 $cnt$ 用户记录每个长度为 $k$ 的子数组中数字的出现次数。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def distinctNumbers(self, nums: List[int], k: int) -> List[int]: @@ -82,10 +76,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] distinctNumbers(int[] nums, int k) { @@ -108,6 +98,73 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector distinctNumbers(vector& nums, int k) { + unordered_map cnt; + for (int i = 0; i < k; ++i) { + ++cnt[nums[i]]; + } + int n = nums.size(); + vector ans; + ans.push_back(cnt.size()); + for (int i = k; i < n; ++i) { + ++cnt[nums[i]]; + if (--cnt[nums[i - k]] == 0) { + cnt.erase(nums[i - k]); + } + ans.push_back(cnt.size()); + } + return ans; + } +}; +``` + +```go +func distinctNumbers(nums []int, k int) []int { + cnt := map[int]int{} + for _, x := range nums[:k] { + cnt[x]++ + } + ans := []int{len(cnt)} + for i := k; i < len(nums); i++ { + cnt[nums[i]]++ + cnt[nums[i-k]]-- + if cnt[nums[i-k]] == 0 { + delete(cnt, nums[i-k]) + } + ans = append(ans, len(cnt)) + } + return ans +} +``` + +```ts +function distinctNumbers(nums: number[], k: number): number[] { + const cnt: Map = new Map(); + for (let i = 0; i < k; ++i) { + cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1); + } + const ans: number[] = [cnt.size]; + for (let i = k; i < nums.length; ++i) { + cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1); + cnt.set(nums[i - k], cnt.get(nums[i - k])! - 1); + if (cnt.get(nums[i - k]) === 0) { + cnt.delete(nums[i - k]); + } + ans.push(cnt.size); + } + return ans; +} +``` + + + +### 方法二 + + + ```java class Solution { public int[] distinctNumbers(int[] nums, int k) { @@ -139,31 +196,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector distinctNumbers(vector& nums, int k) { - unordered_map cnt; - for (int i = 0; i < k; ++i) { - ++cnt[nums[i]]; - } - int n = nums.size(); - vector ans; - ans.push_back(cnt.size()); - for (int i = k; i < n; ++i) { - ++cnt[nums[i]]; - if (--cnt[nums[i - k]] == 0) { - cnt.erase(nums[i - k]); - } - ans.push_back(cnt.size()); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -194,27 +226,6 @@ public: }; ``` -### **Go** - -```go -func distinctNumbers(nums []int, k int) []int { - cnt := map[int]int{} - for _, x := range nums[:k] { - cnt[x]++ - } - ans := []int{len(cnt)} - for i := k; i < len(nums); i++ { - cnt[nums[i]]++ - cnt[nums[i-k]]-- - if cnt[nums[i-k]] == 0 { - delete(cnt, nums[i-k]) - } - ans = append(ans, len(cnt)) - } - return ans -} -``` - ```go func distinctNumbers(nums []int, k int) (ans []int) { m := slices.Max(nums) @@ -242,27 +253,6 @@ func distinctNumbers(nums []int, k int) (ans []int) { } ``` -### **TypeScript** - -```ts -function distinctNumbers(nums: number[], k: number): number[] { - const cnt: Map = new Map(); - for (let i = 0; i < k; ++i) { - cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1); - } - const ans: number[] = [cnt.size]; - for (let i = k; i < nums.length; ++i) { - cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1); - cnt.set(nums[i - k], cnt.get(nums[i - k])! - 1); - if (cnt.get(nums[i - k]) === 0) { - cnt.delete(nums[i - k]); - } - ans.push(cnt.size); - } - return ans; -} -``` - ```ts function distinctNumbers(nums: number[], k: number): number[] { const m = Math.max(...nums); @@ -287,10 +277,6 @@ function distinctNumbers(nums: number[], k: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/README_EN.md b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/README_EN.md index 0c3f0c371db4d..079dc53307174 100644 --- a/solution/1800-1899/1852.Distinct Numbers in Each Subarray/README_EN.md +++ b/solution/1800-1899/1852.Distinct Numbers in Each Subarray/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Sliding Window + Hash Table or Array** +### Solution 1: Sliding Window + Hash Table or Array We use a hash table or array $cnt$ to record the occurrence of each number in each subarray of length $k$. @@ -58,8 +58,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$ or $O(M)$. Whe -### **Python3** - ```python class Solution: def distinctNumbers(self, nums: List[int], k: int) -> List[int]: @@ -74,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] distinctNumbers(int[] nums, int k) { @@ -98,6 +94,73 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector distinctNumbers(vector& nums, int k) { + unordered_map cnt; + for (int i = 0; i < k; ++i) { + ++cnt[nums[i]]; + } + int n = nums.size(); + vector ans; + ans.push_back(cnt.size()); + for (int i = k; i < n; ++i) { + ++cnt[nums[i]]; + if (--cnt[nums[i - k]] == 0) { + cnt.erase(nums[i - k]); + } + ans.push_back(cnt.size()); + } + return ans; + } +}; +``` + +```go +func distinctNumbers(nums []int, k int) []int { + cnt := map[int]int{} + for _, x := range nums[:k] { + cnt[x]++ + } + ans := []int{len(cnt)} + for i := k; i < len(nums); i++ { + cnt[nums[i]]++ + cnt[nums[i-k]]-- + if cnt[nums[i-k]] == 0 { + delete(cnt, nums[i-k]) + } + ans = append(ans, len(cnt)) + } + return ans +} +``` + +```ts +function distinctNumbers(nums: number[], k: number): number[] { + const cnt: Map = new Map(); + for (let i = 0; i < k; ++i) { + cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1); + } + const ans: number[] = [cnt.size]; + for (let i = k; i < nums.length; ++i) { + cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1); + cnt.set(nums[i - k], cnt.get(nums[i - k])! - 1); + if (cnt.get(nums[i - k]) === 0) { + cnt.delete(nums[i - k]); + } + ans.push(cnt.size); + } + return ans; +} +``` + + + +### Solution 2 + + + ```java class Solution { public int[] distinctNumbers(int[] nums, int k) { @@ -129,31 +192,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector distinctNumbers(vector& nums, int k) { - unordered_map cnt; - for (int i = 0; i < k; ++i) { - ++cnt[nums[i]]; - } - int n = nums.size(); - vector ans; - ans.push_back(cnt.size()); - for (int i = k; i < n; ++i) { - ++cnt[nums[i]]; - if (--cnt[nums[i - k]] == 0) { - cnt.erase(nums[i - k]); - } - ans.push_back(cnt.size()); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -184,27 +222,6 @@ public: }; ``` -### **Go** - -```go -func distinctNumbers(nums []int, k int) []int { - cnt := map[int]int{} - for _, x := range nums[:k] { - cnt[x]++ - } - ans := []int{len(cnt)} - for i := k; i < len(nums); i++ { - cnt[nums[i]]++ - cnt[nums[i-k]]-- - if cnt[nums[i-k]] == 0 { - delete(cnt, nums[i-k]) - } - ans = append(ans, len(cnt)) - } - return ans -} -``` - ```go func distinctNumbers(nums []int, k int) (ans []int) { m := slices.Max(nums) @@ -232,27 +249,6 @@ func distinctNumbers(nums []int, k int) (ans []int) { } ``` -### **TypeScript** - -```ts -function distinctNumbers(nums: number[], k: number): number[] { - const cnt: Map = new Map(); - for (let i = 0; i < k; ++i) { - cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1); - } - const ans: number[] = [cnt.size]; - for (let i = k; i < nums.length; ++i) { - cnt.set(nums[i], (cnt.get(nums[i]) ?? 0) + 1); - cnt.set(nums[i - k], cnt.get(nums[i - k])! - 1); - if (cnt.get(nums[i - k]) === 0) { - cnt.delete(nums[i - k]); - } - ans.push(cnt.size); - } - return ans; -} -``` - ```ts function distinctNumbers(nums: number[], k: number): number[] { const m = Math.max(...nums); @@ -277,10 +273,6 @@ function distinctNumbers(nums: number[], k: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1853.Convert Date Format/README.md b/solution/1800-1899/1853.Convert Date Format/README.md index 8cf26902f571b..71e0bc8bf7728 100644 --- a/solution/1800-1899/1853.Convert Date Format/README.md +++ b/solution/1800-1899/1853.Convert Date Format/README.md @@ -51,17 +51,15 @@ Days table: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT DATE_FORMAT(day, '%W, %M %e, %Y') AS day FROM Days; ``` + + diff --git a/solution/1800-1899/1853.Convert Date Format/README_EN.md b/solution/1800-1899/1853.Convert Date Format/README_EN.md index 837a78d384dfd..f44bbc2297f63 100644 --- a/solution/1800-1899/1853.Convert Date Format/README_EN.md +++ b/solution/1800-1899/1853.Convert Date Format/README_EN.md @@ -49,9 +49,9 @@ Days table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -59,3 +59,5 @@ SELECT DATE_FORMAT(day, '%W, %M %e, %Y') AS day FROM Days; ``` + + diff --git a/solution/1800-1899/1854.Maximum Population Year/README.md b/solution/1800-1899/1854.Maximum Population Year/README.md index c488007b50a17..938a6d0a6e0a7 100644 --- a/solution/1800-1899/1854.Maximum Population Year/README.md +++ b/solution/1800-1899/1854.Maximum Population Year/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 我们注意到,年份的范围是 $[1950,..2050]$,因此我们可以将这些年份映射到一个长度为 $101$ 的数组 $d$ 中,数组的下标表示年份减去 $1950$ 的值。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def maximumPopulation(self, logs: List[List[int]]) -> int: @@ -73,10 +67,6 @@ class Solution: return j + offset ``` -### **Java** - - - ```java class Solution { public int maximumPopulation(int[][] logs) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func maximumPopulation(logs [][]int) int { d := [101]int{} @@ -153,7 +139,25 @@ func maximumPopulation(logs [][]int) int { } ``` -### **JavaScript** +```ts +function maximumPopulation(logs: number[][]): number { + const d: number[] = new Array(101).fill(0); + const offset = 1950; + for (const [birth, death] of logs) { + d[birth - offset]++; + d[death - offset]--; + } + let j = 0; + for (let i = 0, s = 0, mx = 0; i < d.length; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + j = i; + } + } + return j + offset; +} +``` ```js /** @@ -181,32 +185,6 @@ var maximumPopulation = function (logs) { }; ``` -### **TypeScript** - -```ts -function maximumPopulation(logs: number[][]): number { - const d: number[] = new Array(101).fill(0); - const offset = 1950; - for (const [birth, death] of logs) { - d[birth - offset]++; - d[death - offset]--; - } - let j = 0; - for (let i = 0, s = 0, mx = 0; i < d.length; ++i) { - s += d[i]; - if (mx < s) { - mx = s; - j = i; - } - } - return j + offset; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1854.Maximum Population Year/README_EN.md b/solution/1800-1899/1854.Maximum Population Year/README_EN.md index eaead5e298fb6..9cc54bfd3c54d 100644 --- a/solution/1800-1899/1854.Maximum Population Year/README_EN.md +++ b/solution/1800-1899/1854.Maximum Population Year/README_EN.md @@ -38,7 +38,7 @@ The earlier year between them is 1960. ## Solutions -**Solution 1: Difference Array** +### Solution 1: Difference Array We notice that the range of years is $[1950,..2050]$. Therefore, we can map these years to an array $d$ of length $101$, where the index of the array represents the value of the year minus $1950$. @@ -48,8 +48,6 @@ The time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is -### **Python3** - ```python class Solution: def maximumPopulation(self, logs: List[List[int]]) -> int: @@ -67,8 +65,6 @@ class Solution: return j + offset ``` -### **Java** - ```java class Solution { public int maximumPopulation(int[][] logs) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func maximumPopulation(logs [][]int) int { d := [101]int{} @@ -145,7 +137,25 @@ func maximumPopulation(logs [][]int) int { } ``` -### **JavaScript** +```ts +function maximumPopulation(logs: number[][]): number { + const d: number[] = new Array(101).fill(0); + const offset = 1950; + for (const [birth, death] of logs) { + d[birth - offset]++; + d[death - offset]--; + } + let j = 0; + for (let i = 0, s = 0, mx = 0; i < d.length; ++i) { + s += d[i]; + if (mx < s) { + mx = s; + j = i; + } + } + return j + offset; +} +``` ```js /** @@ -173,32 +183,6 @@ var maximumPopulation = function (logs) { }; ``` -### **TypeScript** - -```ts -function maximumPopulation(logs: number[][]): number { - const d: number[] = new Array(101).fill(0); - const offset = 1950; - for (const [birth, death] of logs) { - d[birth - offset]++; - d[death - offset]--; - } - let j = 0; - for (let i = 0, s = 0, mx = 0; i < d.length; ++i) { - s += d[i]; - if (mx < s) { - mx = s; - j = i; - } - } - return j + offset; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README.md b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README.md index ebb5f2c30ba77..0ca9f32056f31 100644 --- a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README.md +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 假设 $nums1$, $nums2$ 的长度分别为 $m$ 和 $n$。 @@ -65,18 +63,8 @@ 时间复杂度 $O(m \times \log n)$,其中 $m$ 和 $n$ 分别为 $nums1$ 和 $nums2$ 的长度。空间复杂度 $O(1)$。 -**方法二:双指针** - -在方法一中,我们只利用到 $nums2$ 是非递增数组这一条件,实际上,$nums1$ 也是非递增数组,我们可以用双指针 $i$ 和 $j$ 来遍历 $nums1$ 和 $nums2$。 - -时间复杂度 $O(m+n)$,其中 $m$ 和 $n$ 分别为 $nums1$ 和 $nums2$ 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: @@ -88,23 +76,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: - m, n = len(nums1), len(nums2) - ans = i = j = 0 - while i < m: - while j < n and nums1[i] <= nums2[j]: - j += 1 - ans = max(ans, j - i - 1) - i += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int maxDistance(int[] nums1, int[] nums2) { @@ -127,24 +98,6 @@ class Solution { } ``` -```java -class Solution { - public int maxDistance(int[] nums1, int[] nums2) { - int m = nums1.length, n = nums2.length; - int ans = 0; - for (int i = 0, j = 0; i < m; ++i) { - while (j < n && nums1[i] <= nums2[j]) { - ++j; - } - ans = Math.max(ans, j - i - 1); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -160,25 +113,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxDistance(vector& nums1, vector& nums2) { - int m = nums1.size(), n = nums2.size(); - int ans = 0; - for (int i = 0, j = 0; i < m; ++i) { - while (j < n && nums1[i] <= nums2[j]) { - ++j; - } - ans = max(ans, j - i - 1); - } - return ans; - } -}; -``` - -### **Go** - ```go func maxDistance(nums1 []int, nums2 []int) int { ans, n := 0, len(nums2) @@ -200,31 +134,8 @@ func maxDistance(nums1 []int, nums2 []int) int { } ``` -```go -func maxDistance(nums1 []int, nums2 []int) int { - m, n := len(nums1), len(nums2) - ans := 0 - for i, j := 0, 0; i < m; i++ { - for j < n && nums1[i] <= nums2[j] { - j++ - } - if ans < j-i-1 { - ans = j - i - 1 - } - } - return ans -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var maxDistance = function (nums1, nums2) { +```ts +function maxDistance(nums1: number[], nums2: number[]): number { let ans = 0; let m = nums1.length; let n = nums2.length; @@ -242,7 +153,31 @@ var maxDistance = function (nums1, nums2) { ans = Math.max(ans, left - i); } return ans; -}; +} +``` + +```rust +impl Solution { + pub fn max_distance(nums1: Vec, nums2: Vec) -> i32 { + let m = nums1.len(); + let n = nums2.len(); + let mut res = 0; + for i in 0..m { + let mut left = i; + let mut right = n; + while left < right { + let mid = left + (right - left) / 2; + if nums2[mid] >= nums1[i] { + left = mid + 1; + } else { + right = mid; + } + } + res = res.max((left - i - 1) as i32); + } + res + } +} ``` ```js @@ -252,23 +187,6 @@ var maxDistance = function (nums1, nums2) { * @return {number} */ var maxDistance = function (nums1, nums2) { - let ans = 0; - const m = nums1.length; - const n = nums2.length; - for (let i = 0, j = 0; i < m; ++i) { - while (j < n && nums1[i] <= nums2[j]) { - j++; - } - ans = Math.max(ans, j - i - 1); - } - return ans; -}; -``` - -### **TypeScript** - -```ts -function maxDistance(nums1: number[], nums2: number[]): number { let ans = 0; let m = nums1.length; let n = nums2.length; @@ -286,6 +204,78 @@ function maxDistance(nums1: number[], nums2: number[]): number { ans = Math.max(ans, left - i); } return ans; +}; +``` + + + +### 方法二:双指针 + +在方法一中,我们只利用到 $nums2$ 是非递增数组这一条件,实际上,$nums1$ 也是非递增数组,我们可以用双指针 $i$ 和 $j$ 来遍历 $nums1$ 和 $nums2$。 + +时间复杂度 $O(m+n)$,其中 $m$ 和 $n$ 分别为 $nums1$ 和 $nums2$ 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: + m, n = len(nums1), len(nums2) + ans = i = j = 0 + while i < m: + while j < n and nums1[i] <= nums2[j]: + j += 1 + ans = max(ans, j - i - 1) + i += 1 + return ans +``` + +```java +class Solution { + public int maxDistance(int[] nums1, int[] nums2) { + int m = nums1.length, n = nums2.length; + int ans = 0; + for (int i = 0, j = 0; i < m; ++i) { + while (j < n && nums1[i] <= nums2[j]) { + ++j; + } + ans = Math.max(ans, j - i - 1); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maxDistance(vector& nums1, vector& nums2) { + int m = nums1.size(), n = nums2.size(); + int ans = 0; + for (int i = 0, j = 0; i < m; ++i) { + while (j < n && nums1[i] <= nums2[j]) { + ++j; + } + ans = max(ans, j - i - 1); + } + return ans; + } +}; +``` + +```go +func maxDistance(nums1 []int, nums2 []int) int { + m, n := len(nums1), len(nums2) + ans := 0 + for i, j := 0, 0; i < m; i++ { + for j < n && nums1[i] <= nums2[j] { + j++ + } + if ans < j-i-1 { + ans = j - i - 1 + } + } + return ans } ``` @@ -304,32 +294,6 @@ function maxDistance(nums1: number[], nums2: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn max_distance(nums1: Vec, nums2: Vec) -> i32 { - let m = nums1.len(); - let n = nums2.len(); - let mut res = 0; - for i in 0..m { - let mut left = i; - let mut right = n; - while left < right { - let mid = left + (right - left) / 2; - if nums2[mid] >= nums1[i] { - left = mid + 1; - } else { - right = mid; - } - } - res = res.max((left - i - 1) as i32); - } - res - } -} -``` - ```rust impl Solution { pub fn max_distance(nums1: Vec, nums2: Vec) -> i32 { @@ -348,10 +312,26 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var maxDistance = function (nums1, nums2) { + let ans = 0; + const m = nums1.length; + const n = nums2.length; + for (let i = 0, j = 0; i < m; ++i) { + while (j < n && nums1[i] <= nums2[j]) { + j++; + } + ans = Math.max(ans, j - i - 1); + } + return ans; +}; ``` + + diff --git a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README_EN.md b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README_EN.md index 2a15ee4b03de0..51be3bee7a804 100644 --- a/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README_EN.md +++ b/solution/1800-1899/1855.Maximum Distance Between a Pair of Values/README_EN.md @@ -51,7 +51,7 @@ The maximum distance is 2 with pair (2,4). ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search Assume the lengths of $nums1$ and $nums2$ are $m$ and $n$ respectively. @@ -61,8 +61,6 @@ The time complexity is $O(m \times \log n)$, where $m$ and $n$ are the lengths o -### **Python3** - ```python class Solution: def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: @@ -74,21 +72,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: - m, n = len(nums1), len(nums2) - ans = i = j = 0 - while i < m: - while j < n and nums1[i] <= nums2[j]: - j += 1 - ans = max(ans, j - i - 1) - i += 1 - return ans -``` - -### **Java** - ```java class Solution { public int maxDistance(int[] nums1, int[] nums2) { @@ -111,24 +94,6 @@ class Solution { } ``` -```java -class Solution { - public int maxDistance(int[] nums1, int[] nums2) { - int m = nums1.length, n = nums2.length; - int ans = 0; - for (int i = 0, j = 0; i < m; ++i) { - while (j < n && nums1[i] <= nums2[j]) { - ++j; - } - ans = Math.max(ans, j - i - 1); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -144,25 +109,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxDistance(vector& nums1, vector& nums2) { - int m = nums1.size(), n = nums2.size(); - int ans = 0; - for (int i = 0, j = 0; i < m; ++i) { - while (j < n && nums1[i] <= nums2[j]) { - ++j; - } - ans = max(ans, j - i - 1); - } - return ans; - } -}; -``` - -### **Go** - ```go func maxDistance(nums1 []int, nums2 []int) int { ans, n := 0, len(nums2) @@ -184,31 +130,8 @@ func maxDistance(nums1 []int, nums2 []int) int { } ``` -```go -func maxDistance(nums1 []int, nums2 []int) int { - m, n := len(nums1), len(nums2) - ans := 0 - for i, j := 0, 0; i < m; i++ { - for j < n && nums1[i] <= nums2[j] { - j++ - } - if ans < j-i-1 { - ans = j - i - 1 - } - } - return ans -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number} - */ -var maxDistance = function (nums1, nums2) { +```ts +function maxDistance(nums1: number[], nums2: number[]): number { let ans = 0; let m = nums1.length; let n = nums2.length; @@ -226,7 +149,31 @@ var maxDistance = function (nums1, nums2) { ans = Math.max(ans, left - i); } return ans; -}; +} +``` + +```rust +impl Solution { + pub fn max_distance(nums1: Vec, nums2: Vec) -> i32 { + let m = nums1.len(); + let n = nums2.len(); + let mut res = 0; + for i in 0..m { + let mut left = i; + let mut right = n; + while left < right { + let mid = left + (right - left) / 2; + if nums2[mid] >= nums1[i] { + left = mid + 1; + } else { + right = mid; + } + } + res = res.max((left - i - 1) as i32); + } + res + } +} ``` ```js @@ -236,23 +183,6 @@ var maxDistance = function (nums1, nums2) { * @return {number} */ var maxDistance = function (nums1, nums2) { - let ans = 0; - const m = nums1.length; - const n = nums2.length; - for (let i = 0, j = 0; i < m; ++i) { - while (j < n && nums1[i] <= nums2[j]) { - j++; - } - ans = Math.max(ans, j - i - 1); - } - return ans; -}; -``` - -### **TypeScript** - -```ts -function maxDistance(nums1: number[], nums2: number[]): number { let ans = 0; let m = nums1.length; let n = nums2.length; @@ -270,6 +200,74 @@ function maxDistance(nums1: number[], nums2: number[]): number { ans = Math.max(ans, left - i); } return ans; +}; +``` + + + +### Solution 2 + + + +```python +class Solution: + def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: + m, n = len(nums1), len(nums2) + ans = i = j = 0 + while i < m: + while j < n and nums1[i] <= nums2[j]: + j += 1 + ans = max(ans, j - i - 1) + i += 1 + return ans +``` + +```java +class Solution { + public int maxDistance(int[] nums1, int[] nums2) { + int m = nums1.length, n = nums2.length; + int ans = 0; + for (int i = 0, j = 0; i < m; ++i) { + while (j < n && nums1[i] <= nums2[j]) { + ++j; + } + ans = Math.max(ans, j - i - 1); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maxDistance(vector& nums1, vector& nums2) { + int m = nums1.size(), n = nums2.size(); + int ans = 0; + for (int i = 0, j = 0; i < m; ++i) { + while (j < n && nums1[i] <= nums2[j]) { + ++j; + } + ans = max(ans, j - i - 1); + } + return ans; + } +}; +``` + +```go +func maxDistance(nums1 []int, nums2 []int) int { + m, n := len(nums1), len(nums2) + ans := 0 + for i, j := 0, 0; i < m; i++ { + for j < n && nums1[i] <= nums2[j] { + j++ + } + if ans < j-i-1 { + ans = j - i - 1 + } + } + return ans } ``` @@ -288,32 +286,6 @@ function maxDistance(nums1: number[], nums2: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn max_distance(nums1: Vec, nums2: Vec) -> i32 { - let m = nums1.len(); - let n = nums2.len(); - let mut res = 0; - for i in 0..m { - let mut left = i; - let mut right = n; - while left < right { - let mid = left + (right - left) / 2; - if nums2[mid] >= nums1[i] { - left = mid + 1; - } else { - right = mid; - } - } - res = res.max((left - i - 1) as i32); - } - res - } -} -``` - ```rust impl Solution { pub fn max_distance(nums1: Vec, nums2: Vec) -> i32 { @@ -332,10 +304,26 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number} + */ +var maxDistance = function (nums1, nums2) { + let ans = 0; + const m = nums1.length; + const n = nums2.length; + for (let i = 0, j = 0; i < m; ++i) { + while (j < n && nums1[i] <= nums2[j]) { + j++; + } + ans = Math.max(ans, j - i - 1); + } + return ans; +}; ``` + + diff --git a/solution/1800-1899/1856.Maximum Subarray Min-Product/README.md b/solution/1800-1899/1856.Maximum Subarray Min-Product/README.md index c54ebe9d190a9..64ff543e6b4cc 100644 --- a/solution/1800-1899/1856.Maximum Subarray Min-Product/README.md +++ b/solution/1800-1899/1856.Maximum Subarray Min-Product/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:单调栈 + 前缀和** +### 方法一:单调栈 + 前缀和 我们可以枚举每个元素 $nums[i]$ 作为子数组的最小值,找出子数组的左右边界 $left[i]$ 和 $right[i]$。其中 $left[i]$ 表示 $i$ 左侧第一个严格小于 $nums[i]$ 的位置,而 $right[i]$ 表示 $i$ 右侧第一个小于等于 $nums[i]$ 的位置。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def maxSumMinProduct(self, nums: List[int]) -> int: @@ -101,10 +95,6 @@ class Solution: return max((s[right[i]] - s[left[i] + 1]) * x for i, x in enumerate(nums)) % mod ``` -### **Java** - - - ```java class Solution { public int maxSumMinProduct(int[] nums) { @@ -147,8 +137,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -191,8 +179,6 @@ public: }; ``` -### **Go** - ```go func maxSumMinProduct(nums []int) int { n := len(nums) @@ -237,8 +223,6 @@ func maxSumMinProduct(nums []int) int { } ``` -### **TypeSript** - ```ts function maxSumMinProduct(nums: number[]): number { const n = nums.length; @@ -280,10 +264,6 @@ function maxSumMinProduct(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md b/solution/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md index ebb444cc0da7e..9c59110930bae 100644 --- a/solution/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md +++ b/solution/1800-1899/1856.Maximum Subarray Min-Product/README_EN.md @@ -54,7 +54,7 @@ ## Solutions -**Solution 1: Monotonic Stack + Prefix Sum** +### Solution 1: Monotonic Stack + Prefix Sum We can enumerate each element $nums[i]$ as the minimum value of the subarray, and find the left and right boundaries $left[i]$ and $right[i]$ of the subarray. Where $left[i]$ represents the first position strictly less than $nums[i]$ on the left side of $i$, and $right[i]$ represents the first position less than or equal to $nums[i]$ on the right side of $i$. @@ -66,8 +66,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def maxSumMinProduct(self, nums: List[int]) -> int: @@ -93,8 +91,6 @@ class Solution: return max((s[right[i]] - s[left[i] + 1]) * x for i, x in enumerate(nums)) % mod ``` -### **Java** - ```java class Solution { public int maxSumMinProduct(int[] nums) { @@ -137,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -181,8 +175,6 @@ public: }; ``` -### **Go** - ```go func maxSumMinProduct(nums []int) int { n := len(nums) @@ -227,8 +219,6 @@ func maxSumMinProduct(nums []int) int { } ``` -### **TypeSript** - ```ts function maxSumMinProduct(nums: number[]): number { const n = nums.length; @@ -270,10 +260,6 @@ function maxSumMinProduct(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README.md b/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README.md index 3034a17bc360b..929560507c7da 100644 --- a/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README.md +++ b/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:拓扑排序 + 动态规划** +### 方法一:拓扑排序 + 动态规划 求出每个点的入度,进行拓扑排序。每个点维护一个长度为 $26$ 的数组,记录每个字母从任意起点到当前点的出现次数。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def largestPathValue(self, colors: str, edges: List[List[int]]) -> int: @@ -95,10 +89,6 @@ class Solution: return -1 if cnt < n else ans ``` -### **Java** - - - ```java class Solution { public int largestPathValue(String colors, int[][] edges) { @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -184,8 +172,6 @@ public: }; ``` -### **Go** - ```go func largestPathValue(colors string, edges [][]int) int { n := len(colors) @@ -237,10 +223,6 @@ func largestPathValue(colors string, edges [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README_EN.md b/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README_EN.md index af1bcacc1c19c..3b7d6119f7ad7 100644 --- a/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README_EN.md +++ b/solution/1800-1899/1857.Largest Color Value in a Directed Graph/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,8 +83,6 @@ class Solution: return -1 if cnt < n else ans ``` -### **Java** - ```java class Solution { public int largestPathValue(String colors, int[][] edges) { @@ -127,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +166,6 @@ public: }; ``` -### **Go** - ```go func largestPathValue(colors string, edges [][]int) int { n := len(colors) @@ -223,10 +217,6 @@ func largestPathValue(colors string, edges [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1858.Longest Word With All Prefixes/README.md b/solution/1800-1899/1858.Longest Word With All Prefixes/README.md index 285c4d782fe53..65f522efeaa5e 100644 --- a/solution/1800-1899/1858.Longest Word With All Prefixes/README.md +++ b/solution/1800-1899/1858.Longest Word With All Prefixes/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:前缀树** +### 方法一:前缀树 我们定义一棵前缀树,前缀树每个节点有两个属性,一个是长度为 $26$ 的子节点数组 `children`,另一个是是否为单词结尾的标记 `isEnd`。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Trie: __slots__ = ["children", "is_end"] @@ -106,10 +100,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Trie { private Trie[] children = new Trie[26]; @@ -161,8 +151,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { private: @@ -217,8 +205,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -268,8 +254,6 @@ func longestWord(words []string) string { } ``` -### **TypeScript** - ```ts class Trie { private children: (Trie | null)[] = Array(26).fill(null); @@ -315,8 +299,6 @@ function longestWord(words: string[]): string { } ``` -### **Rust** - ```rust struct Trie { children: [Option>; 26], @@ -372,8 +354,6 @@ impl Solution { } ``` -### **C#** - ```cs public class Trie { private Trie[] children = new Trie[26]; @@ -424,10 +404,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1858.Longest Word With All Prefixes/README_EN.md b/solution/1800-1899/1858.Longest Word With All Prefixes/README_EN.md index 9e1a15022f8cf..8432c08702ced 100644 --- a/solution/1800-1899/1858.Longest Word With All Prefixes/README_EN.md +++ b/solution/1800-1899/1858.Longest Word With All Prefixes/README_EN.md @@ -48,7 +48,7 @@ However, "apple" is lexicographically smaller, so we return that. ## Solutions -**Solution 1: Trie** +### Solution 1: Trie We define a trie, each node of the trie has two attributes, one is a `children` array of length $26$, and the other is a `isEnd` flag indicating whether it is the end of a word. @@ -60,8 +60,6 @@ The time complexity is $O(\sum_{w \in words} |w|)$, and the space complexity is -### **Python3** - ```python class Trie: __slots__ = ["children", "is_end"] @@ -101,8 +99,6 @@ class Solution: return ans ``` -### **Java** - ```java class Trie { private Trie[] children = new Trie[26]; @@ -154,8 +150,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { private: @@ -210,8 +204,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -261,8 +253,6 @@ func longestWord(words []string) string { } ``` -### **TypeScript** - ```ts class Trie { private children: (Trie | null)[] = Array(26).fill(null); @@ -308,8 +298,6 @@ function longestWord(words: string[]): string { } ``` -### **Rust** - ```rust struct Trie { children: [Option>; 26], @@ -365,8 +353,6 @@ impl Solution { } ``` -### **C#** - ```cs public class Trie { private Trie[] children = new Trie[26]; @@ -417,10 +403,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1859.Sorting the Sentence/README.md b/solution/1800-1899/1859.Sorting the Sentence/README.md index 7958fa6aa2971..8077bba6fde45 100644 --- a/solution/1800-1899/1859.Sorting the Sentence/README.md +++ b/solution/1800-1899/1859.Sorting the Sentence/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:字符串分割** +### 方法一:字符串分割 我们先将字符串 $s$ 按照空格分割,得到字符串数组 $words$。然后,我们创建一个长度为 $|words|$ 的字符串数组 $ans$,用于存放答案。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def sortSentence(self, s: str) -> str: @@ -73,20 +67,6 @@ class Solution: return ' '.join(w for w, _ in ws) ``` -```python -class Solution: - def sortSentence(self, s: str) -> str: - ws = s.split() - ans = [None] * len(ws) - for w in ws: - ans[int(w[-1]) - 1] = w[:-1] - return ' '.join(ans) -``` - -### **Java** - - - ```java class Solution { public String sortSentence(String s) { @@ -102,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +106,6 @@ public: }; ``` -### **Go** - ```go func sortSentence(s string) string { ws := strings.Split(s, " ") @@ -141,7 +117,16 @@ func sortSentence(s string) string { } ``` -### **JavaScript** +```ts +function sortSentence(s: string): string { + const ws = s.split(' '); + const ans = Array(ws.length); + for (const w of ws) { + ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1); + } + return ans.join(' '); +} +``` ```js /** @@ -158,23 +143,22 @@ var sortSentence = function (s) { }; ``` -### **TypeScript** - -```ts -function sortSentence(s: string): string { - const ws = s.split(' '); - const ans = Array(ws.length); - for (const w of ws) { - ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1); - } - return ans.join(' '); -} -``` + -### **...** +### 方法二 -``` + +```python +class Solution: + def sortSentence(self, s: str) -> str: + ws = s.split() + ans = [None] * len(ws) + for w in ws: + ans[int(w[-1]) - 1] = w[:-1] + return ' '.join(ans) ``` + + diff --git a/solution/1800-1899/1859.Sorting the Sentence/README_EN.md b/solution/1800-1899/1859.Sorting the Sentence/README_EN.md index 0b57e23b45781..c1bf6ebe8d507 100644 --- a/solution/1800-1899/1859.Sorting the Sentence/README_EN.md +++ b/solution/1800-1899/1859.Sorting the Sentence/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: String Splitting** +### Solution 1: String Splitting First, we split the string $s$ by spaces to get the string array $words$. Then, we create a string array $ans$ of length $|words|$ to store the answer. @@ -56,8 +56,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def sortSentence(self, s: str) -> str: @@ -66,18 +64,6 @@ class Solution: return ' '.join(w for w, _ in ws) ``` -```python -class Solution: - def sortSentence(self, s: str) -> str: - ws = s.split() - ans = [None] * len(ws) - for w in ws: - ans[int(w[-1]) - 1] = w[:-1] - return ' '.join(ans) -``` - -### **Java** - ```java class Solution { public String sortSentence(String s) { @@ -93,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +103,6 @@ public: }; ``` -### **Go** - ```go func sortSentence(s string) string { ws := strings.Split(s, " ") @@ -132,7 +114,16 @@ func sortSentence(s string) string { } ``` -### **JavaScript** +```ts +function sortSentence(s: string): string { + const ws = s.split(' '); + const ans = Array(ws.length); + for (const w of ws) { + ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1); + } + return ans.join(' '); +} +``` ```js /** @@ -149,23 +140,22 @@ var sortSentence = function (s) { }; ``` -### **TypeScript** - -```ts -function sortSentence(s: string): string { - const ws = s.split(' '); - const ans = Array(ws.length); - for (const w of ws) { - ans[w.charCodeAt(w.length - 1) - '1'.charCodeAt(0)] = w.slice(0, -1); - } - return ans.join(' '); -} -``` + -### **...** +### Solution 2 -``` + +```python +class Solution: + def sortSentence(self, s: str) -> str: + ws = s.split() + ans = [None] * len(ws) + for w in ws: + ans[int(w[-1]) - 1] = w[:-1] + return ' '.join(ans) ``` + + diff --git a/solution/1800-1899/1860.Incremental Memory Leak/README.md b/solution/1800-1899/1860.Incremental Memory Leak/README.md index 1fd6ff6c99677..650a0ecdb3121 100644 --- a/solution/1800-1899/1860.Incremental Memory Leak/README.md +++ b/solution/1800-1899/1860.Incremental Memory Leak/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们直接模拟内存的分配。 @@ -63,10 +61,6 @@ $$ -### **Python3** - - - ```python class Solution: def memLeak(self, memory1: int, memory2: int) -> List[int]: @@ -80,10 +74,6 @@ class Solution: return [i, memory1, memory2] ``` -### **Java** - - - ```java class Solution { public int[] memLeak(int memory1, int memory2) { @@ -100,29 +90,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number} memory1 - * @param {number} memory2 - * @return {number[]} - */ -var memLeak = function (memory1, memory2) { - let i = 1; - for (; i <= Math.max(memory1, memory2); ++i) { - if (memory1 >= memory2) { - memory1 -= i; - } else { - memory2 -= i; - } - } - return [i, memory1, memory2]; -}; -``` - -### **C++** - ```cpp class Solution { public: @@ -140,8 +107,6 @@ public: }; ``` -### **Go** - ```go func memLeak(memory1 int, memory2 int) []int { i := 1 @@ -156,8 +121,6 @@ func memLeak(memory1 int, memory2 int) []int { } ``` -### **TypeScript** - ```ts function memLeak(memory1: number, memory2: number): number[] { let i = 1; @@ -172,10 +135,25 @@ function memLeak(memory1: number, memory2: number): number[] { } ``` -### **...** - -``` - +```js +/** + * @param {number} memory1 + * @param {number} memory2 + * @return {number[]} + */ +var memLeak = function (memory1, memory2) { + let i = 1; + for (; i <= Math.max(memory1, memory2); ++i) { + if (memory1 >= memory2) { + memory1 -= i; + } else { + memory2 -= i; + } + } + return [i, memory1, memory2]; +}; ``` + + diff --git a/solution/1800-1899/1860.Incremental Memory Leak/README_EN.md b/solution/1800-1899/1860.Incremental Memory Leak/README_EN.md index 169841f2bb8ad..888435edbbcd7 100644 --- a/solution/1800-1899/1860.Incremental Memory Leak/README_EN.md +++ b/solution/1800-1899/1860.Incremental Memory Leak/README_EN.md @@ -45,7 +45,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We directly simulate the allocation of memory. @@ -59,8 +59,6 @@ The time complexity is $O(\sqrt{m_1+m_2})$, where $m_1$ and $m_2$ are the sizes -### **Python3** - ```python class Solution: def memLeak(self, memory1: int, memory2: int) -> List[int]: @@ -74,8 +72,6 @@ class Solution: return [i, memory1, memory2] ``` -### **Java** - ```java class Solution { public int[] memLeak(int memory1, int memory2) { @@ -92,29 +88,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number} memory1 - * @param {number} memory2 - * @return {number[]} - */ -var memLeak = function (memory1, memory2) { - let i = 1; - for (; i <= Math.max(memory1, memory2); ++i) { - if (memory1 >= memory2) { - memory1 -= i; - } else { - memory2 -= i; - } - } - return [i, memory1, memory2]; -}; -``` - -### **C++** - ```cpp class Solution { public: @@ -132,8 +105,6 @@ public: }; ``` -### **Go** - ```go func memLeak(memory1 int, memory2 int) []int { i := 1 @@ -148,8 +119,6 @@ func memLeak(memory1 int, memory2 int) []int { } ``` -### **TypeScript** - ```ts function memLeak(memory1: number, memory2: number): number[] { let i = 1; @@ -164,10 +133,25 @@ function memLeak(memory1: number, memory2: number): number[] { } ``` -### **...** - -``` - +```js +/** + * @param {number} memory1 + * @param {number} memory2 + * @return {number[]} + */ +var memLeak = function (memory1, memory2) { + let i = 1; + for (; i <= Math.max(memory1, memory2); ++i) { + if (memory1 >= memory2) { + memory1 -= i; + } else { + memory2 -= i; + } + } + return [i, memory1, memory2]; +}; ``` + + diff --git a/solution/1800-1899/1861.Rotating the Box/README.md b/solution/1800-1899/1861.Rotating the Box/README.md index 29bf09f736a63..808728e670a86 100644 --- a/solution/1800-1899/1861.Rotating the Box/README.md +++ b/solution/1800-1899/1861.Rotating the Box/README.md @@ -72,9 +72,7 @@ ## 解法 - - -**方法一:队列模拟** +### 方法一:队列模拟 我们先将矩阵顺时针旋转 90 度,然后模拟每一列石头的下落过程。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: @@ -108,10 +102,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public char[][] rotateTheBox(char[][] box) { @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +163,6 @@ public: }; ``` -### **Go** - ```go func rotateTheBox(box [][]byte) [][]byte { m, n := len(box), len(box[0]) @@ -208,10 +194,6 @@ func rotateTheBox(box [][]byte) [][]byte { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1861.Rotating the Box/README_EN.md b/solution/1800-1899/1861.Rotating the Box/README_EN.md index beb5e46d8c82a..facf2bb1745af 100644 --- a/solution/1800-1899/1861.Rotating the Box/README_EN.md +++ b/solution/1800-1899/1861.Rotating the Box/README_EN.md @@ -71,7 +71,7 @@ ## Solutions -**Solution 1: Queue Simulation** +### Solution 1: Queue Simulation First, we rotate the matrix 90 degrees clockwise, then simulate the falling process of the stones in each column. @@ -79,8 +79,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times -### **Python3** - ```python class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: @@ -103,8 +101,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public char[][] rotateTheBox(char[][] box) { @@ -134,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +162,6 @@ public: }; ``` -### **Go** - ```go func rotateTheBox(box [][]byte) [][]byte { m, n := len(box), len(box[0]) @@ -201,10 +193,6 @@ func rotateTheBox(box [][]byte) [][]byte { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1862.Sum of Floored Pairs/README.md b/solution/1800-1899/1862.Sum of Floored Pairs/README.md index 5b39b0d02a45a..042fe91ab2371 100644 --- a/solution/1800-1899/1862.Sum of Floored Pairs/README.md +++ b/solution/1800-1899/1862.Sum of Floored Pairs/README.md @@ -42,9 +42,7 @@ floor(9 / 5) = 1 ## 解法 - - -**方法一:值域前缀和 + 优化枚举** +### 方法一:值域前缀和 + 优化枚举 我们先统计数组 $nums$ 中每个元素出现的次数,记录在数组 $cnt$ 中,然后计算数组 $cnt$ 的前缀和,记录在数组 $s$ 中,即 $s[i]$ 表示小于等于 $i$ 的元素的个数。 @@ -54,10 +52,6 @@ floor(9 / 5) = 1 -### **Python3** - - - ```python class Solution: def sumOfFlooredPairs(self, nums: List[int]) -> int: @@ -78,10 +72,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int sumOfFlooredPairs(int[] nums) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func sumOfFlooredPairs(nums []int) (ans int) { mx := slices.Max(nums) @@ -168,8 +154,6 @@ func sumOfFlooredPairs(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumOfFlooredPairs(nums: number[]): number { const mx = Math.max(...nums); @@ -195,8 +179,6 @@ function sumOfFlooredPairs(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn sum_of_floored_pairs(nums: Vec) -> i32 { @@ -238,10 +220,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1862.Sum of Floored Pairs/README_EN.md b/solution/1800-1899/1862.Sum of Floored Pairs/README_EN.md index e2a2e74fc21d8..e4ab4f8fc7179 100644 --- a/solution/1800-1899/1862.Sum of Floored Pairs/README_EN.md +++ b/solution/1800-1899/1862.Sum of Floored Pairs/README_EN.md @@ -40,7 +40,7 @@ We calculate the floor of the division for every pair of indices in the array th ## Solutions -**Solution 1: Prefix Sum of Value Range + Optimized Enumeration** +### Solution 1: Prefix Sum of Value Range + Optimized Enumeration First, we count the occurrences of each element in the array $nums$ and record them in the array $cnt$. Then, we calculate the prefix sum of the array $cnt$ and record it in the array $s$, i.e., $s[i]$ represents the count of elements less than or equal to $i$. @@ -50,8 +50,6 @@ The time complexity is $O(M \times \log M)$, and the space complexity is $O(M)$. -### **Python3** - ```python class Solution: def sumOfFlooredPairs(self, nums: List[int]) -> int: @@ -72,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int sumOfFlooredPairs(int[] nums) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +128,6 @@ public: }; ``` -### **Go** - ```go func sumOfFlooredPairs(nums []int) (ans int) { mx := slices.Max(nums) @@ -160,8 +152,6 @@ func sumOfFlooredPairs(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumOfFlooredPairs(nums: number[]): number { const mx = Math.max(...nums); @@ -187,8 +177,6 @@ function sumOfFlooredPairs(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn sum_of_floored_pairs(nums: Vec) -> i32 { @@ -230,10 +218,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/README.md b/solution/1800-1899/1863.Sum of All Subset XOR Totals/README.md index 705002837f323..8485ba95cd53b 100644 --- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/README.md +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:二进制枚举** +### 方法一:二进制枚举 我们可以用二进制枚举的方法,枚举出所有的子集,然后计算每个子集的异或总和。 @@ -76,25 +74,8 @@ 时间复杂度 $O(n \times 2^n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 -**方法二:DFS** - -我们也可以使用深度优先搜索的方法,枚举出所有的子集,然后计算每个子集的异或总和。 - -我们设计一个函数 $dfs(i, s)$,其中 $i$ 表示当前搜索到数组 $nums$ 的第 $i$ 个元素,$s$ 表示当前子集的异或总和。初始时,$i=0$, $s=0$。在搜索的过程中,每次我们都有两种选择: - -- 将 $nums$ 的第 $i$ 个元素加入当前子集,即 $dfs(i+1, s \oplus nums[i])$; -- 将 $nums$ 的第 $i$ 个元素不加入当前子集,即 $dfs(i+1, s)$。 - -当我们搜索完数组 $nums$ 的所有元素时,即 $i=n$ 时,当前子集的异或总和为 $s$,将其加到答案中即可。 - -时间复杂度 $O(2^n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。 - -### **Python3** - - - ```python class Solution: def subsetXORSum(self, nums: List[int]) -> int: @@ -108,26 +89,6 @@ class Solution: return ans ``` -```python -class Solution: - def subsetXORSum(self, nums: List[int]) -> int: - def dfs(i: int, s: int): - nonlocal ans - if i >= len(nums): - ans += s - return - dfs(i + 1, s) - dfs(i + 1, s ^ nums[i]) - - ans = 0 - dfs(0, 0) - return ans -``` - -### **Java** - - - ```java class Solution { public int subsetXORSum(int[] nums) { @@ -147,6 +108,113 @@ class Solution { } ``` +```cpp +class Solution { +public: + int subsetXORSum(vector& nums) { + int n = nums.size(); + int ans = 0; + for (int i = 0; i < 1 << n; ++i) { + int s = 0; + for (int j = 0; j < n; ++j) { + if (i >> j & 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; + } +}; +``` + +```go +func subsetXORSum(nums []int) (ans int) { + n := len(nums) + for i := 0; i < 1<>j&1 == 1 { + s ^= x + } + } + ans += s + } + return +} +``` + +```ts +function subsetXORSum(nums: number[]): number { + let ans = 0; + const n = nums.length; + for (let i = 0; i < 1 << n; ++i) { + let s = 0; + for (let j = 0; j < n; ++j) { + if ((i >> j) & 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; +} +``` + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var subsetXORSum = function (nums) { + let ans = 0; + const n = nums.length; + for (let i = 0; i < 1 << n; ++i) { + let s = 0; + for (let j = 0; j < n; ++j) { + if ((i >> j) & 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; +}; +``` + + + +### 方法二:DFS + +我们也可以使用深度优先搜索的方法,枚举出所有的子集,然后计算每个子集的异或总和。 + +我们设计一个函数 $dfs(i, s)$,其中 $i$ 表示当前搜索到数组 $nums$ 的第 $i$ 个元素,$s$ 表示当前子集的异或总和。初始时,$i=0$, $s=0$。在搜索的过程中,每次我们都有两种选择: + +- 将 $nums$ 的第 $i$ 个元素加入当前子集,即 $dfs(i+1, s \oplus nums[i])$; +- 将 $nums$ 的第 $i$ 个元素不加入当前子集,即 $dfs(i+1, s)$。 + +当我们搜索完数组 $nums$ 的所有元素时,即 $i=n$ 时,当前子集的异或总和为 $s$,将其加到答案中即可。 + +时间复杂度 $O(2^n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。 + + + +```python +class Solution: + def subsetXORSum(self, nums: List[int]) -> int: + def dfs(i: int, s: int): + nonlocal ans + if i >= len(nums): + ans += s + return + dfs(i + 1, s) + dfs(i + 1, s ^ nums[i]) + + ans = 0 + dfs(0, 0) + return ans +``` + ```java class Solution { private int ans; @@ -169,28 +237,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int subsetXORSum(vector& nums) { - int n = nums.size(); - int ans = 0; - for (int i = 0; i < 1 << n; ++i) { - int s = 0; - for (int j = 0; j < n; ++j) { - if (i >> j & 1) { - s ^= nums[j]; - } - } - ans += s; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -211,24 +257,6 @@ public: }; ``` -### **Go** - -```go -func subsetXORSum(nums []int) (ans int) { - n := len(nums) - for i := 0; i < 1<>j&1 == 1 { - s ^= x - } - } - ans += s - } - return -} -``` - ```go func subsetXORSum(nums []int) (ans int) { n := len(nums) @@ -246,25 +274,6 @@ func subsetXORSum(nums []int) (ans int) { } ``` -### **TypeScript** - -```ts -function subsetXORSum(nums: number[]): number { - let ans = 0; - const n = nums.length; - for (let i = 0; i < 1 << n; ++i) { - let s = 0; - for (let j = 0; j < n; ++j) { - if ((i >> j) & 1) { - s ^= nums[j]; - } - } - ans += s; - } - return ans; -} -``` - ```ts function subsetXORSum(nums: number[]): number { let ans = 0; @@ -282,29 +291,6 @@ function subsetXORSum(nums: number[]): number { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var subsetXORSum = function (nums) { - let ans = 0; - const n = nums.length; - for (let i = 0; i < 1 << n; ++i) { - let s = 0; - for (let j = 0; j < n; ++j) { - if ((i >> j) & 1) { - s ^= nums[j]; - } - } - ans += s; - } - return ans; -}; -``` - ```js /** * @param {number[]} nums @@ -326,10 +312,6 @@ var subsetXORSum = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md b/solution/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md index 7c9c5b68cea25..efb01c75dc440 100644 --- a/solution/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md +++ b/solution/1800-1899/1863.Sum of All Subset XOR Totals/README_EN.md @@ -65,7 +65,7 @@ ## Solutions -**Solution 1: Binary Enumeration** +### Solution 1: Binary Enumeration We can use binary enumeration to enumerate all subsets, and then calculate the XOR sum of each subset. @@ -73,23 +73,8 @@ Specifically, we enumerate $i$ in the range $[0, 2^n)$, where $n$ is the length The time complexity is $O(n \times 2^n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. -**Solution 2: DFS (Depth-First Search)** - -We can also use depth-first search to enumerate all subsets, and then calculate the XOR sum of each subset. - -We design a function $dfs(i, s)$, where $i$ represents the current search to the $i$th element of the array $nums$, and $s$ represents the XOR sum of the current subset. Initially, $i=0$, $s=0$. During the search, we have two choices each time: - -- Add the $i$th element of $nums$ to the current subset, i.e., $dfs(i+1, s \oplus nums[i])$; -- Do not add the $i$th element of $nums$ to the current subset, i.e., $dfs(i+1, s)$. - -When we have searched all elements of the array $nums$, i.e., $i=n$, the XOR sum of the current subset is $s$, and we can add it to the answer. - -The time complexity is $O(2^n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$. - -### **Python3** - ```python class Solution: def subsetXORSum(self, nums: List[int]) -> int: @@ -103,24 +88,6 @@ class Solution: return ans ``` -```python -class Solution: - def subsetXORSum(self, nums: List[int]) -> int: - def dfs(i: int, s: int): - nonlocal ans - if i >= len(nums): - ans += s - return - dfs(i + 1, s) - dfs(i + 1, s ^ nums[i]) - - ans = 0 - dfs(0, 0) - return ans -``` - -### **Java** - ```java class Solution { public int subsetXORSum(int[] nums) { @@ -140,6 +107,113 @@ class Solution { } ``` +```cpp +class Solution { +public: + int subsetXORSum(vector& nums) { + int n = nums.size(); + int ans = 0; + for (int i = 0; i < 1 << n; ++i) { + int s = 0; + for (int j = 0; j < n; ++j) { + if (i >> j & 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; + } +}; +``` + +```go +func subsetXORSum(nums []int) (ans int) { + n := len(nums) + for i := 0; i < 1<>j&1 == 1 { + s ^= x + } + } + ans += s + } + return +} +``` + +```ts +function subsetXORSum(nums: number[]): number { + let ans = 0; + const n = nums.length; + for (let i = 0; i < 1 << n; ++i) { + let s = 0; + for (let j = 0; j < n; ++j) { + if ((i >> j) & 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; +} +``` + +```js +/** + * @param {number[]} nums + * @return {number} + */ +var subsetXORSum = function (nums) { + let ans = 0; + const n = nums.length; + for (let i = 0; i < 1 << n; ++i) { + let s = 0; + for (let j = 0; j < n; ++j) { + if ((i >> j) & 1) { + s ^= nums[j]; + } + } + ans += s; + } + return ans; +}; +``` + + + +### Solution 2: DFS (Depth-First Search) + +We can also use depth-first search to enumerate all subsets, and then calculate the XOR sum of each subset. + +We design a function $dfs(i, s)$, where $i$ represents the current search to the $i$th element of the array $nums$, and $s$ represents the XOR sum of the current subset. Initially, $i=0$, $s=0$. During the search, we have two choices each time: + +- Add the $i$th element of $nums$ to the current subset, i.e., $dfs(i+1, s \oplus nums[i])$; +- Do not add the $i$th element of $nums$ to the current subset, i.e., $dfs(i+1, s)$. + +When we have searched all elements of the array $nums$, i.e., $i=n$, the XOR sum of the current subset is $s$, and we can add it to the answer. + +The time complexity is $O(2^n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $nums$. + + + +```python +class Solution: + def subsetXORSum(self, nums: List[int]) -> int: + def dfs(i: int, s: int): + nonlocal ans + if i >= len(nums): + ans += s + return + dfs(i + 1, s) + dfs(i + 1, s ^ nums[i]) + + ans = 0 + dfs(0, 0) + return ans +``` + ```java class Solution { private int ans; @@ -162,28 +236,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int subsetXORSum(vector& nums) { - int n = nums.size(); - int ans = 0; - for (int i = 0; i < 1 << n; ++i) { - int s = 0; - for (int j = 0; j < n; ++j) { - if (i >> j & 1) { - s ^= nums[j]; - } - } - ans += s; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -204,24 +256,6 @@ public: }; ``` -### **Go** - -```go -func subsetXORSum(nums []int) (ans int) { - n := len(nums) - for i := 0; i < 1<>j&1 == 1 { - s ^= x - } - } - ans += s - } - return -} -``` - ```go func subsetXORSum(nums []int) (ans int) { n := len(nums) @@ -239,25 +273,6 @@ func subsetXORSum(nums []int) (ans int) { } ``` -### **TypeScript** - -```ts -function subsetXORSum(nums: number[]): number { - let ans = 0; - const n = nums.length; - for (let i = 0; i < 1 << n; ++i) { - let s = 0; - for (let j = 0; j < n; ++j) { - if ((i >> j) & 1) { - s ^= nums[j]; - } - } - ans += s; - } - return ans; -} -``` - ```ts function subsetXORSum(nums: number[]): number { let ans = 0; @@ -275,29 +290,6 @@ function subsetXORSum(nums: number[]): number { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var subsetXORSum = function (nums) { - let ans = 0; - const n = nums.length; - for (let i = 0; i < 1 << n; ++i) { - let s = 0; - for (let j = 0; j < n; ++j) { - if ((i >> j) & 1) { - s ^= nums[j]; - } - } - ans += s; - } - return ans; -}; -``` - ```js /** * @param {number[]} nums @@ -319,10 +311,6 @@ var subsetXORSum = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1864.Minimum Number of Swaps to Make the Binary String Alternating/README.md b/solution/1800-1899/1864.Minimum Number of Swaps to Make the Binary String Alternating/README.md index d908186f7723c..1a7d9d86c2fe8 100644 --- a/solution/1800-1899/1864.Minimum Number of Swaps to Make the Binary String Alternating/README.md +++ b/solution/1800-1899/1864.Minimum Number of Swaps to Make the Binary String Alternating/README.md @@ -48,14 +48,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minSwaps(self, s: str) -> int: @@ -80,10 +76,6 @@ class Solution: return min(s0n0, s1n0) ``` -### **Java** - - - ```java class Solution { public int minSwaps(String s) { @@ -118,8 +110,6 @@ class Solution { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -151,10 +141,6 @@ var minSwaps = function (s) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1864.Minimum Number of Swaps to Make the Binary String Alternating/README_EN.md b/solution/1800-1899/1864.Minimum Number of Swaps to Make the Binary String Alternating/README_EN.md index 2a649e0350989..7284b09526d54 100644 --- a/solution/1800-1899/1864.Minimum Number of Swaps to Make the Binary String Alternating/README_EN.md +++ b/solution/1800-1899/1864.Minimum Number of Swaps to Make the Binary String Alternating/README_EN.md @@ -45,9 +45,9 @@ The string is now alternating. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return min(s0n0, s1n0) ``` -### **Java** - ```java class Solution { public int minSwaps(String s) { @@ -109,8 +107,6 @@ class Solution { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -142,10 +138,6 @@ var minSwaps = function (s) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README.md b/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README.md index b90594ad0a817..17ce4e6faa961 100644 --- a/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README.md +++ b/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README.md @@ -60,9 +60,7 @@ findSumPairs.count(7); // 返回 11 ;下标对 (2,1), (2,2), (2,4), (3,1), (3 ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以用哈希表 `cnt` 统计数组 `nums2` 中每个数字出现的次数。 @@ -74,10 +72,6 @@ findSumPairs.count(7); // 返回 11 ;下标对 (2,1), (2,2), (2,4), (3,1), (3 -### **Python3** - - - ```python class FindSumPairs: def __init__(self, nums1: List[int], nums2: List[int]): @@ -101,10 +95,6 @@ class FindSumPairs: # param_2 = obj.count(tot) ``` -### **Java** - - - ```java class FindSumPairs { private int[] nums1; @@ -143,8 +133,6 @@ class FindSumPairs { */ ``` -### **C++** - ```cpp class FindSumPairs { public: @@ -185,8 +173,6 @@ private: */ ``` -### **Go** - ```go type FindSumPairs struct { nums1 []int @@ -224,10 +210,6 @@ func (this *FindSumPairs) Count(tot int) (ans int) { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README_EN.md b/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README_EN.md index 8ec03a1e40169..958dd0249355d 100644 --- a/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README_EN.md +++ b/solution/1800-1899/1865.Finding Pairs With a Certain Sum/README_EN.md @@ -56,9 +56,9 @@ findSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), ( ## Solutions - +### Solution 1 -### **Python3** + ```python class FindSumPairs: @@ -83,8 +83,6 @@ class FindSumPairs: # param_2 = obj.count(tot) ``` -### **Java** - ```java class FindSumPairs { private int[] nums1; @@ -123,8 +121,6 @@ class FindSumPairs { */ ``` -### **C++** - ```cpp class FindSumPairs { public: @@ -165,8 +161,6 @@ private: */ ``` -### **Go** - ```go type FindSumPairs struct { nums1 []int @@ -204,10 +198,6 @@ func (this *FindSumPairs) Count(tot int) (ans int) { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/README.md b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/README.md index cebe76dae4ea7..a38b27b415c15 100644 --- a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/README.md +++ b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示长度为 $i$ 的排列中,恰有 $j$ 根木棍可以看到的排列数目。初始时 $f[0][0]=1$,其余 $f[i][j]=0$。答案为 $f[n][k]$。 @@ -72,10 +70,6 @@ $$ -### **Python3** - - - ```python class Solution: def rearrangeSticks(self, n: int, k: int) -> int: @@ -88,22 +82,6 @@ class Solution: return f[n][k] ``` -```python -class Solution: - def rearrangeSticks(self, n: int, k: int) -> int: - mod = 10**9 + 7 - f = [1] + [0] * k - for i in range(1, n + 1): - for j in range(k, 0, -1): - f[j] = (f[j] * (i - 1) + f[j - 1]) % mod - f[0] = 0 - return f[k] -``` - -### **Java** - - - ```java class Solution { public int rearrangeSticks(int n, int k) { @@ -120,25 +98,6 @@ class Solution { } ``` -```java -class Solution { - public int rearrangeSticks(int n, int k) { - final int mod = (int) 1e9 + 7; - int[] f = new int[k + 1]; - f[0] = 1; - for (int i = 1; i <= n; ++i) { - for (int j = k; j > 0; --j) { - f[j] = (int) ((f[j] * (i - 1L) + f[j - 1]) % mod); - } - f[0] = 0; - } - return f[k]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -157,6 +116,74 @@ public: }; ``` +```go +func rearrangeSticks(n int, k int) int { + const mod = 1e9 + 7 + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, k+1) + } + f[0][0] = 1 + for i := 1; i <= n; i++ { + for j := 1; j <= k; j++ { + f[i][j] = (f[i-1][j-1] + (i-1)*f[i-1][j]) % mod + } + } + return f[n][k] +} +``` + +```ts +function rearrangeSticks(n: number, k: number): number { + const mod = 10 ** 9 + 7; + const f: number[][] = Array.from({ length: n + 1 }, () => + Array.from({ length: k + 1 }, () => 0), + ); + f[0][0] = 1; + for (let i = 1; i <= n; ++i) { + for (let j = 1; j <= k; ++j) { + f[i][j] = (f[i - 1][j - 1] + (i - 1) * f[i - 1][j]) % mod; + } + } + return f[n][k]; +} +``` + + + +### 方法二 + + + +```python +class Solution: + def rearrangeSticks(self, n: int, k: int) -> int: + mod = 10**9 + 7 + f = [1] + [0] * k + for i in range(1, n + 1): + for j in range(k, 0, -1): + f[j] = (f[j] * (i - 1) + f[j - 1]) % mod + f[0] = 0 + return f[k] +``` + +```java +class Solution { + public int rearrangeSticks(int n, int k) { + final int mod = (int) 1e9 + 7; + int[] f = new int[k + 1]; + f[0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = k; j > 0; --j) { + f[j] = (int) ((f[j] * (i - 1L) + f[j - 1]) % mod); + } + f[0] = 0; + } + return f[k]; + } +} +``` + ```cpp class Solution { public: @@ -176,25 +203,6 @@ public: }; ``` -### **Go** - -```go -func rearrangeSticks(n int, k int) int { - const mod = 1e9 + 7 - f := make([][]int, n+1) - for i := range f { - f[i] = make([]int, k+1) - } - f[0][0] = 1 - for i := 1; i <= n; i++ { - for j := 1; j <= k; j++ { - f[i][j] = (f[i-1][j-1] + (i-1)*f[i-1][j]) % mod - } - } - return f[n][k] -} -``` - ```go func rearrangeSticks(n int, k int) int { const mod = 1e9 + 7 @@ -210,24 +218,6 @@ func rearrangeSticks(n int, k int) int { } ``` -### **TypeScript** - -```ts -function rearrangeSticks(n: number, k: number): number { - const mod = 10 ** 9 + 7; - const f: number[][] = Array.from({ length: n + 1 }, () => - Array.from({ length: k + 1 }, () => 0), - ); - f[0][0] = 1; - for (let i = 1; i <= n; ++i) { - for (let j = 1; j <= k; ++j) { - f[i][j] = (f[i - 1][j - 1] + (i - 1) * f[i - 1][j]) % mod; - } - } - return f[n][k]; -} -``` - ```ts function rearrangeSticks(n: number, k: number): number { const mod = 10 ** 9 + 7; @@ -243,10 +233,6 @@ function rearrangeSticks(n: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/README_EN.md b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/README_EN.md index 85e6e846bf618..ae8bfb4c6b62c 100644 --- a/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/README_EN.md +++ b/solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/README_EN.md @@ -49,7 +49,7 @@ The visible sticks are underlined. ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ to represent the number of permutations of length $i$ in which exactly $j$ sticks can be seen. Initially, $f[0][0]=1$ and the rest $f[i][j]=0$. The answer is $f[n][k]$. @@ -69,34 +69,18 @@ The time complexity is $O(n \times k)$, and the space complexity is $O(k)$. Here -### **Python3** - ```python class Solution: def rearrangeSticks(self, n: int, k: int) -> int: mod = 10**9 + 7 - f = [1] + [0] * k + f = [[0] * (k + 1) for _ in range(n + 1)] + f[0][0] = 1 for i in range(1, n + 1): - for j in range(k, 0, -1): - f[j] = (f[j] * (i - 1) + f[j - 1]) % mod - f[0] = 0 - return f[k] + for j in range(1, k + 1): + f[i][j] = (f[i - 1][j - 1] + f[i - 1][j] * (i - 1)) % mod + return f[n][k] ``` -```python -class Solution: - def rearrangeSticks(self, n: int, k: int) -> int: - mod = 10**9 + 7 - f = [1] + [0] * k - for i in range(1, n + 1): - for j in range(k, 0, -1): - f[j] = (f[j] * (i - 1) + f[j - 1]) % mod - f[0] = 0 - return f[k] -``` - -### **Java** - ```java class Solution { public int rearrangeSticks(int n, int k) { @@ -113,25 +97,6 @@ class Solution { } ``` -```java -class Solution { - public int rearrangeSticks(int n, int k) { - final int mod = (int) 1e9 + 7; - int[] f = new int[k + 1]; - f[0] = 1; - for (int i = 1; i <= n; ++i) { - for (int j = k; j > 0; --j) { - f[j] = (int) ((f[j] * (i - 1L) + f[j - 1]) % mod); - } - f[0] = 0; - } - return f[k]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -150,6 +115,74 @@ public: }; ``` +```go +func rearrangeSticks(n int, k int) int { + const mod = 1e9 + 7 + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, k+1) + } + f[0][0] = 1 + for i := 1; i <= n; i++ { + for j := 1; j <= k; j++ { + f[i][j] = (f[i-1][j-1] + (i-1)*f[i-1][j]) % mod + } + } + return f[n][k] +} +``` + +```ts +function rearrangeSticks(n: number, k: number): number { + const mod = 10 ** 9 + 7; + const f: number[][] = Array.from({ length: n + 1 }, () => + Array.from({ length: k + 1 }, () => 0), + ); + f[0][0] = 1; + for (let i = 1; i <= n; ++i) { + for (let j = 1; j <= k; ++j) { + f[i][j] = (f[i - 1][j - 1] + (i - 1) * f[i - 1][j]) % mod; + } + } + return f[n][k]; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def rearrangeSticks(self, n: int, k: int) -> int: + mod = 10**9 + 7 + f = [1] + [0] * k + for i in range(1, n + 1): + for j in range(k, 0, -1): + f[j] = (f[j] * (i - 1) + f[j - 1]) % mod + f[0] = 0 + return f[k] +``` + +```java +class Solution { + public int rearrangeSticks(int n, int k) { + final int mod = (int) 1e9 + 7; + int[] f = new int[k + 1]; + f[0] = 1; + for (int i = 1; i <= n; ++i) { + for (int j = k; j > 0; --j) { + f[j] = (int) ((f[j] * (i - 1L) + f[j - 1]) % mod); + } + f[0] = 0; + } + return f[k]; + } +} +``` + ```cpp class Solution { public: @@ -169,25 +202,6 @@ public: }; ``` -### **Go** - -```go -func rearrangeSticks(n int, k int) int { - const mod = 1e9 + 7 - f := make([][]int, n+1) - for i := range f { - f[i] = make([]int, k+1) - } - f[0][0] = 1 - for i := 1; i <= n; i++ { - for j := 1; j <= k; j++ { - f[i][j] = (f[i-1][j-1] + (i-1)*f[i-1][j]) % mod - } - } - return f[n][k] -} -``` - ```go func rearrangeSticks(n int, k int) int { const mod = 1e9 + 7 @@ -203,24 +217,6 @@ func rearrangeSticks(n int, k int) int { } ``` -### **TypeScript** - -```ts -function rearrangeSticks(n: number, k: number): number { - const mod = 10 ** 9 + 7; - const f: number[][] = Array.from({ length: n + 1 }, () => - Array.from({ length: k + 1 }, () => 0), - ); - f[0][0] = 1; - for (let i = 1; i <= n; ++i) { - for (let j = 1; j <= k; ++j) { - f[i][j] = (f[i - 1][j - 1] + (i - 1) * f[i - 1][j]) % mod; - } - } - return f[n][k]; -} -``` - ```ts function rearrangeSticks(n: number, k: number): number { const mod = 10 ** 9 + 7; @@ -236,10 +232,6 @@ function rearrangeSticks(n: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1867.Orders With Maximum Quantity Above Average/README.md b/solution/1800-1899/1867.Orders With Maximum Quantity Above Average/README.md index 93f5d1f6f8db0..1eb82e39c2cf0 100644 --- a/solution/1800-1899/1867.Orders With Maximum Quantity Above Average/README.md +++ b/solution/1800-1899/1867.Orders With Maximum Quantity Above Average/README.md @@ -85,14 +85,10 @@ OrdersDetails 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -110,3 +106,5 @@ WHERE max_quantity > (SELECT MAX(avg_quantity) FROM t); ``` + + diff --git a/solution/1800-1899/1867.Orders With Maximum Quantity Above Average/README_EN.md b/solution/1800-1899/1867.Orders With Maximum Quantity Above Average/README_EN.md index 9f70ec7d41d4a..477a15f273764 100644 --- a/solution/1800-1899/1867.Orders With Maximum Quantity Above Average/README_EN.md +++ b/solution/1800-1899/1867.Orders With Maximum Quantity Above Average/README_EN.md @@ -82,9 +82,9 @@ Orders 1 and 3 are imbalanced because they have a maximum quantity that exceeds ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -103,3 +103,5 @@ WHERE max_quantity > (SELECT MAX(avg_quantity) FROM t); ``` + + diff --git a/solution/1800-1899/1868.Product of Two Run-Length Encoded Arrays/README.md b/solution/1800-1899/1868.Product of Two Run-Length Encoded Arrays/README.md index 53ec185c8043a..c721aabdb1a4b 100644 --- a/solution/1800-1899/1868.Product of Two Run-Length Encoded Arrays/README.md +++ b/solution/1800-1899/1868.Product of Two Run-Length Encoded Arrays/README.md @@ -59,9 +59,7 @@ prodNums = [2,2,2,6,9,9],压缩成行程编码数组 [[2,3],[6,1],[9,2]]。 ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们用两个指针 $i$ 和 $j$ 分别指向两个数组的当前位置,然后开始模拟乘法的过程。 @@ -73,10 +71,6 @@ prodNums = [2,2,2,6,9,9],压缩成行程编码数组 [[2,3],[6,1],[9,2]]。 -### **Python3** - - - ```python class Solution: def findRLEArray( @@ -99,10 +93,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> findRLEArray(int[][] encoded1, int[][] encoded2) { @@ -131,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go func findRLEArray(encoded1 [][]int, encoded2 [][]int) (ans [][]int) { j := 0 @@ -187,10 +173,6 @@ func findRLEArray(encoded1 [][]int, encoded2 [][]int) (ans [][]int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1868.Product of Two Run-Length Encoded Arrays/README_EN.md b/solution/1800-1899/1868.Product of Two Run-Length Encoded Arrays/README_EN.md index cdbecebfca055..1c87efbbd4769 100644 --- a/solution/1800-1899/1868.Product of Two Run-Length Encoded Arrays/README_EN.md +++ b/solution/1800-1899/1868.Product of Two Run-Length Encoded Arrays/README_EN.md @@ -57,9 +57,9 @@ prodNums = [2,2,2,6,9,9], which is compressed into the run-length encoded array ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,8 +83,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List> findRLEArray(int[][] encoded1, int[][] encoded2) { @@ -113,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +139,6 @@ public: }; ``` -### **Go** - ```go func findRLEArray(encoded1 [][]int, encoded2 [][]int) (ans [][]int) { j := 0 @@ -169,10 +163,6 @@ func findRLEArray(encoded1 [][]int, encoded2 [][]int) (ans [][]int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/README.md b/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/README.md index 3e98b0c54ec30..0b78c321b52ce 100644 --- a/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/README.md +++ b/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:两次遍历** +### 方法一:两次遍历 我们设计一个函数 $f(x)$,表示字符串 $s$ 中由 $x$ 组成的最长连续子字符串的长度。如果 $f(1) \gt f(0)$,那么返回 `true`,否则返回 `false`。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def checkZeroOnes(self, s: str) -> bool: @@ -90,10 +84,6 @@ class Solution: return f("1") > f("0") ``` -### **Java** - - - ```java class Solution { public boolean checkZeroOnes(String s) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func checkZeroOnes(s string) bool { f := func(x rune) int { @@ -156,8 +142,6 @@ func checkZeroOnes(s string) bool { } ``` -### **TypeScript** - ```ts function checkZeroOnes(s: string): boolean { const f = (x: string): number => { @@ -175,8 +159,6 @@ function checkZeroOnes(s: string): boolean { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -198,10 +180,6 @@ var checkZeroOnes = function (s) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/README_EN.md b/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/README_EN.md index 8aa5e04be0c16..cc0fa7229bd88 100644 --- a/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/README_EN.md +++ b/solution/1800-1899/1869.Longer Contiguous Segments of Ones than Zeros/README_EN.md @@ -56,7 +56,7 @@ The segment of 1s is not longer, so return false. ## Solutions -**Solution 1: Two Passes** +### Solution 1: Two Passes We design a function $f(x)$, which represents the length of the longest consecutive substring in string $s$ composed of $x$. If $f(1) > f(0)$, then return `true`, otherwise return `false`. @@ -64,8 +64,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. The sp -### **Python3** - ```python class Solution: def checkZeroOnes(self, s: str) -> bool: @@ -82,8 +80,6 @@ class Solution: return f("1") > f("0") ``` -### **Java** - ```java class Solution { public boolean checkZeroOnes(String s) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +120,6 @@ public: }; ``` -### **Go** - ```go func checkZeroOnes(s string) bool { f := func(x rune) int { @@ -146,8 +138,6 @@ func checkZeroOnes(s string) bool { } ``` -### **TypeScript** - ```ts function checkZeroOnes(s: string): boolean { const f = (x: string): number => { @@ -165,8 +155,6 @@ function checkZeroOnes(s: string): boolean { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -188,10 +176,6 @@ var checkZeroOnes = function (s) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1870.Minimum Speed to Arrive on Time/README.md b/solution/1800-1899/1870.Minimum Speed to Arrive on Time/README.md index 2d921928eb591..af057e09f5c86 100644 --- a/solution/1800-1899/1870.Minimum Speed to Arrive on Time/README.md +++ b/solution/1800-1899/1870.Minimum Speed to Arrive on Time/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 二分枚举速度值,找到满足条件的最小速度。 @@ -125,10 +123,6 @@ int search(int left, int right) { -### **Python3** - - - ```python class Solution: def minSpeedOnTime(self, dist: List[int], hour: float) -> int: @@ -143,10 +137,6 @@ class Solution: return -1 if ans == r else ans ``` -### **Java** - - - ```java class Solution { public int minSpeedOnTime(int[] dist, double hour) { @@ -173,8 +163,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -202,8 +190,6 @@ public: }; ``` -### **Go** - ```go func minSpeedOnTime(dist []int, hour float64) int { n := len(dist) @@ -224,45 +210,6 @@ func minSpeedOnTime(dist []int, hour float64) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} dist - * @param {number} hour - * @return {number} - */ -var minSpeedOnTime = function (dist, hour) { - if (dist.length > Math.ceil(hour)) return -1; - let left = 1, - right = 10 ** 7; - while (left < right) { - let mid = (left + right) >> 1; - if (arriveOnTime(dist, mid, hour)) { - right = mid; - } else { - left = mid + 1; - } - } - return left; -}; - -function arriveOnTime(dist, speed, hour) { - let res = 0.0; - let n = dist.length; - for (let i = 0; i < n; i++) { - let cost = parseFloat(dist[i]) / speed; - if (i != n - 1) { - cost = Math.ceil(cost); - } - res += cost; - } - return res <= hour; -} -``` - -### **Rust** - ```rust impl Solution { pub fn min_speed_on_time(dist: Vec, hour: f64) -> i32 { @@ -299,10 +246,41 @@ impl Solution { } ``` -### **...** - -``` +```js +/** + * @param {number[]} dist + * @param {number} hour + * @return {number} + */ +var minSpeedOnTime = function (dist, hour) { + if (dist.length > Math.ceil(hour)) return -1; + let left = 1, + right = 10 ** 7; + while (left < right) { + let mid = (left + right) >> 1; + if (arriveOnTime(dist, mid, hour)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +}; +function arriveOnTime(dist, speed, hour) { + let res = 0.0; + let n = dist.length; + for (let i = 0; i < n; i++) { + let cost = parseFloat(dist[i]) / speed; + if (i != n - 1) { + cost = Math.ceil(cost); + } + res += cost; + } + return res <= hour; +} ``` + + diff --git a/solution/1800-1899/1870.Minimum Speed to Arrive on Time/README_EN.md b/solution/1800-1899/1870.Minimum Speed to Arrive on Time/README_EN.md index bd845221efa41..93c921d3c5207 100644 --- a/solution/1800-1899/1870.Minimum Speed to Arrive on Time/README_EN.md +++ b/solution/1800-1899/1870.Minimum Speed to Arrive on Time/README_EN.md @@ -62,61 +62,10 @@ ## Solutions -Binary search. - -Template 1: - -```java -boolean check(int x) { -} - -int search(int left, int right) { - while (left < right) { - int mid = (left + right) >> 1; - if (check(mid)) { - right = mid; - } else { - left = mid + 1; - } - } - return left; -} -``` - -Template 2: - -```java -boolean check(int x) { -} - -int search(int left, int right) { - while (left < right) { - int mid = (left + right + 1) >> 1; - if (check(mid)) { - left = mid; - } else { - right = mid - 1; - } - } - return left; -} -``` - -When doing binary search problems, you can follow the following routine: - -1. Write out the loop condition $left < right$; -2. Inside the loop, you might as well write $mid = \lfloor \frac{left + right}{2} \rfloor$ first; -3. According to the specific problem, implement the $check()$ function (sometimes the logic is very simple, you can not define $check$), think about whether to use $right = mid$ (Template $1$) or $left = mid$ (Template $2$); - - If $right = mid$, then write the else statement $left = mid + 1$, and there is no need to change the calculation of $mid$, that is, keep $mid = \lfloor \frac{left + right}{2} \rfloor$; - - If $left = mid$, then write the else statement $right = mid - 1$, and add +1 when calculating $mid$, that is, $mid = \lfloor \frac{left + right + 1}{2} \rfloor$; -4. When the loop ends, $left$ equals $right$. - -Note that the advantage of these two templates is that they always keep the answer within the binary search interval, and the value corresponding to the end condition of the binary search is exactly at the position of the answer. For the case that may have no solution, just check whether the $left$ or $right$ after the binary search ends satisfies the problem. +### Solution 1 -### **Python3** - ```python class Solution: def minSpeedOnTime(self, dist: List[int], hour: float) -> int: @@ -131,8 +80,6 @@ class Solution: return -1 if ans == r else ans ``` -### **Java** - ```java class Solution { public int minSpeedOnTime(int[] dist, double hour) { @@ -159,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -188,8 +133,6 @@ public: }; ``` -### **Go** - ```go func minSpeedOnTime(dist []int, hour float64) int { n := len(dist) @@ -210,45 +153,6 @@ func minSpeedOnTime(dist []int, hour float64) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} dist - * @param {number} hour - * @return {number} - */ -var minSpeedOnTime = function (dist, hour) { - if (dist.length > Math.ceil(hour)) return -1; - let left = 1, - right = 10 ** 7; - while (left < right) { - let mid = (left + right) >> 1; - if (arriveOnTime(dist, mid, hour)) { - right = mid; - } else { - left = mid + 1; - } - } - return left; -}; - -function arriveOnTime(dist, speed, hour) { - let res = 0.0; - let n = dist.length; - for (let i = 0; i < n; i++) { - let cost = parseFloat(dist[i]) / speed; - if (i != n - 1) { - cost = Math.ceil(cost); - } - res += cost; - } - return res <= hour; -} -``` - -### **Rust** - ```rust impl Solution { pub fn min_speed_on_time(dist: Vec, hour: f64) -> i32 { @@ -285,10 +189,41 @@ impl Solution { } ``` -### **...** - -``` +```js +/** + * @param {number[]} dist + * @param {number} hour + * @return {number} + */ +var minSpeedOnTime = function (dist, hour) { + if (dist.length > Math.ceil(hour)) return -1; + let left = 1, + right = 10 ** 7; + while (left < right) { + let mid = (left + right) >> 1; + if (arriveOnTime(dist, mid, hour)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; +}; +function arriveOnTime(dist, speed, hour) { + let res = 0.0; + let n = dist.length; + for (let i = 0; i < n; i++) { + let cost = parseFloat(dist[i]) / speed; + if (i != n - 1) { + cost = Math.ceil(cost); + } + res += cost; + } + return res <= hour; +} ``` + + diff --git a/solution/1800-1899/1871.Jump Game VII/README.md b/solution/1800-1899/1871.Jump Game VII/README.md index 0427d704dc190..d9261ca9cda1c 100644 --- a/solution/1800-1899/1871.Jump Game VII/README.md +++ b/solution/1800-1899/1871.Jump Game VII/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:前缀和 + 动态规划** +### 方法一:前缀和 + 动态规划 我们定义一个长度为 $n+1$ 的前缀和数组 $pre$,其中 $pre[i]$ 表示 $s$ 的前 $i$ 个位置中能够到达的个数。定义一个长度为 $n$ 的布尔数组 $f$,其中 $f[i]$ 表示 $s[i]$ 是否能够到达。初始时 $pre[1] = 1$,而 $f[0] = true$。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def canReach(self, s: str, minJump: int, maxJump: int) -> bool: @@ -80,10 +74,6 @@ class Solution: return f[-1] ``` -### **Java** - - - ```java class Solution { public boolean canReach(String s, int minJump, int maxJump) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func canReach(s string, minJump int, maxJump int) bool { n := len(s) @@ -154,8 +140,6 @@ func canReach(s string, minJump int, maxJump int) bool { } ``` -### **TypeScript** - ```ts function canReach(s: string, minJump: number, maxJump: number): boolean { const n = s.length; @@ -174,8 +158,6 @@ function canReach(s: string, minJump: number, maxJump: number): boolean { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -200,10 +182,6 @@ var canReach = function (s, minJump, maxJump) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1871.Jump Game VII/README_EN.md b/solution/1800-1899/1871.Jump Game VII/README_EN.md index d111bf47c417e..98cdf64625c43 100644 --- a/solution/1800-1899/1871.Jump Game VII/README_EN.md +++ b/solution/1800-1899/1871.Jump Game VII/README_EN.md @@ -43,7 +43,7 @@ In the second step, move from index 3 to index 5. ## Solutions -**Solution 1: Prefix Sum + Dynamic Programming** +### Solution 1: Prefix Sum + Dynamic Programming We define a prefix sum array $pre$ of length $n+1$, where $pre[i]$ represents the number of reachable positions in the first $i$ positions of $s$. We define a boolean array $f$ of length $n$, where $f[i]$ indicates whether $s[i]$ is reachable. Initially, $pre[1] = 1$ and $f[0] = true$. @@ -55,8 +55,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def canReach(self, s: str, minJump: int, maxJump: int) -> bool: @@ -72,8 +70,6 @@ class Solution: return f[-1] ``` -### **Java** - ```java class Solution { public boolean canReach(String s, int minJump, int maxJump) { @@ -95,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +115,6 @@ public: }; ``` -### **Go** - ```go func canReach(s string, minJump int, maxJump int) bool { n := len(s) @@ -144,8 +136,6 @@ func canReach(s string, minJump int, maxJump int) bool { } ``` -### **TypeScript** - ```ts function canReach(s: string, minJump: number, maxJump: number): boolean { const n = s.length; @@ -164,8 +154,6 @@ function canReach(s: string, minJump: number, maxJump: number): boolean { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -190,10 +178,6 @@ var canReach = function (s, minJump, maxJump) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1872.Stone Game VIII/README.md b/solution/1800-1899/1872.Stone Game VIII/README.md index 78826f6e5caf5..03238aa7a2ea9 100644 --- a/solution/1800-1899/1872.Stone Game VIII/README.md +++ b/solution/1800-1899/1872.Stone Game VIII/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:前缀和 + 记忆化搜索** +### 方法一:前缀和 + 记忆化搜索 根据题目描述,每次取走最左边的 $x$ 个石子,把它们的和加到自己的分数中,然后把一个价值为这个和的石子放在最左边,相当于把这 $x$ 个石子合并成了一个价值为这个和的石子,前缀和不变。 @@ -85,36 +83,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $stones$ 的长度。 -**方法二:前缀和 + 动态规划** - -我们也可以使用动态规划的方法来解决这个问题。 - -与方法一类似,我们先用一个长度为 $n$ 的前缀和数组 $s$ 来表示数组 $stones$ 的前缀和,其中 $s[i]$ 表示 $stones[0..i]$ 的元素和。 - -我们定义 $f[i]$ 表示当前从 $stones[i:]$ 中取石子,返回当前玩家能得到的最大分数差。 - -若玩家选择取走 $stones[:i]$ 的石子,那么获得的分数为 $s[i]$,此时另一个玩家会在 $stones[i+1:]$ 中取石子,那么另一个玩家能得到的最大分数差为 $f[i+1]$,因此当前玩家能得到的最大分数差为 $s[i] - f[i+1]$。 - -若玩家选择从 $stones[i+1:]$ 中取石子,那么获得的最大分数差为 $f[i+1]$。 - -因此我们可以得到状态转移方程: - -$$ -f[i] = \max\{s[i] - f[i+1], f[i+1]\} -$$ - -最终,我们可以得到 Alice 和 Bob 的分数之差为 $f[1]$,即 $Alice$ 必须从 $stones[1:]$ 中取石子开始游戏。 - -我们注意到 $f[i]$ 只与 $f[i+1]$ 有关,因此我们只需要使用一个变量 $f$ 来表示 $f[i]$ 即可。 - -时间复杂度 $O(n)$,其中 $n$ 为数组 $stones$ 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def stoneGameVIII(self, stones: List[int]) -> int: @@ -128,20 +98,6 @@ class Solution: return dfs(1) ``` -```python -class Solution: - def stoneGameVIII(self, stones: List[int]) -> int: - s = list(accumulate(stones)) - f = s[-1] - for i in range(len(s) - 2, 0, -1): - f = max(f, s[i] - f) - return f -``` - -### **Java** - - - ```java class Solution { private Integer[] f; @@ -170,24 +126,6 @@ class Solution { } ``` -```java -class Solution { - public int stoneGameVIII(int[] stones) { - int n = stones.length; - for (int i = 1; i < n; ++i) { - stones[i] += stones[i - 1]; - } - int f = stones[n - 1]; - for (int i = n - 2; i > 0; --i) { - f = Math.max(f, stones[i] - f); - } - return f; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -212,25 +150,6 @@ public: }; ``` -```cpp -class Solution { -public: - int stoneGameVIII(vector& stones) { - int n = stones.size(); - for (int i = 1; i < n; ++i) { - stones[i] += stones[i - 1]; - } - int f = stones.back(); - for (int i = n - 2; i; --i) { - f = max(f, stones[i] - f); - } - return f; - } -}; -``` - -### **Go** - ```go func stoneGameVIII(stones []int) int { n := len(stones) @@ -255,8 +174,6 @@ func stoneGameVIII(stones []int) int { } ``` -### **TypeScript** - ```ts function stoneGameVIII(stones: number[]): number { const n = stones.length; @@ -277,6 +194,77 @@ function stoneGameVIII(stones: number[]): number { } ``` + + +### 方法二:前缀和 + 动态规划 + +我们也可以使用动态规划的方法来解决这个问题。 + +与方法一类似,我们先用一个长度为 $n$ 的前缀和数组 $s$ 来表示数组 $stones$ 的前缀和,其中 $s[i]$ 表示 $stones[0..i]$ 的元素和。 + +我们定义 $f[i]$ 表示当前从 $stones[i:]$ 中取石子,返回当前玩家能得到的最大分数差。 + +若玩家选择取走 $stones[:i]$ 的石子,那么获得的分数为 $s[i]$,此时另一个玩家会在 $stones[i+1:]$ 中取石子,那么另一个玩家能得到的最大分数差为 $f[i+1]$,因此当前玩家能得到的最大分数差为 $s[i] - f[i+1]$。 + +若玩家选择从 $stones[i+1:]$ 中取石子,那么获得的最大分数差为 $f[i+1]$。 + +因此我们可以得到状态转移方程: + +$$ +f[i] = \max\{s[i] - f[i+1], f[i+1]\} +$$ + +最终,我们可以得到 Alice 和 Bob 的分数之差为 $f[1]$,即 $Alice$ 必须从 $stones[1:]$ 中取石子开始游戏。 + +我们注意到 $f[i]$ 只与 $f[i+1]$ 有关,因此我们只需要使用一个变量 $f$ 来表示 $f[i]$ 即可。 + +时间复杂度 $O(n)$,其中 $n$ 为数组 $stones$ 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def stoneGameVIII(self, stones: List[int]) -> int: + s = list(accumulate(stones)) + f = s[-1] + for i in range(len(s) - 2, 0, -1): + f = max(f, s[i] - f) + return f +``` + +```java +class Solution { + public int stoneGameVIII(int[] stones) { + int n = stones.length; + for (int i = 1; i < n; ++i) { + stones[i] += stones[i - 1]; + } + int f = stones[n - 1]; + for (int i = n - 2; i > 0; --i) { + f = Math.max(f, stones[i] - f); + } + return f; + } +} +``` + +```cpp +class Solution { +public: + int stoneGameVIII(vector& stones) { + int n = stones.size(); + for (int i = 1; i < n; ++i) { + stones[i] += stones[i - 1]; + } + int f = stones.back(); + for (int i = n - 2; i; --i) { + f = max(f, stones[i] - f); + } + return f; + } +}; +``` + ```ts function stoneGameVIII(stones: number[]): number { const n = stones.length; @@ -291,10 +279,6 @@ function stoneGameVIII(stones: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1872.Stone Game VIII/README_EN.md b/solution/1800-1899/1872.Stone Game VIII/README_EN.md index 9e2e8a379997f..dd5129814224b 100644 --- a/solution/1800-1899/1872.Stone Game VIII/README_EN.md +++ b/solution/1800-1899/1872.Stone Game VIII/README_EN.md @@ -67,7 +67,7 @@ The difference between their scores is (-22) - 0 = -22. ## Solutions -**Solution 1: Prefix Sum + Memoization Search** +### Solution 1: Prefix Sum + Memoization Search According to the problem description, each time we take the leftmost $x$ stones, add their sum to our score, and then put a stone with this sum value on the leftmost side, it is equivalent to merging these $x$ stones into a stone with this sum value, and the prefix sum remains unchanged. @@ -86,34 +86,8 @@ To avoid repeated calculations, we can use memoization search. The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $stones$. -**Solution 2: Prefix Sum + Dynamic Programming** - -We can also use dynamic programming to solve this problem. - -Similar to Solution 1, we first use a prefix sum array $s$ of length $n$ to represent the prefix sum of the array $stones$, where $s[i]$ represents the sum of the elements $stones[0..i]$. - -We define $f[i]$ to represent the maximum score difference that the current player can get when taking stones from $stones[i:]$. - -If the player chooses to take the stones $stones[:i]$, then the score obtained is $s[i]$. At this time, the other player will take stones from $stones[i+1:]$, and the maximum score difference that the other player can get is $f[i+1]$. Therefore, the maximum score difference that the current player can get is $s[i] - f[i+1]$. - -If the player chooses to take stones from $stones[i+1:]$, then the maximum score difference obtained is $f[i+1]$. - -Therefore, we can get the state transition equation: - -$$ -f[i] = \max\{s[i] - f[i+1], f[i+1]\} -$$ - -Finally, we can get the score difference between Alice and Bob as $f[1]$, that is, Alice must start the game by taking stones from $stones[1:]$. - -We notice that $f[i]$ is only related to $f[i+1]$, so we only need to use a variable $f$ to represent $f[i]$. - -The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $stones$. - -### **Python3** - ```python class Solution: def stoneGameVIII(self, stones: List[int]) -> int: @@ -127,18 +101,6 @@ class Solution: return dfs(1) ``` -```python -class Solution: - def stoneGameVIII(self, stones: List[int]) -> int: - s = list(accumulate(stones)) - f = s[-1] - for i in range(len(s) - 2, 0, -1): - f = max(f, s[i] - f) - return f -``` - -### **Java** - ```java class Solution { private Integer[] f; @@ -167,24 +129,6 @@ class Solution { } ``` -```java -class Solution { - public int stoneGameVIII(int[] stones) { - int n = stones.length; - for (int i = 1; i < n; ++i) { - stones[i] += stones[i - 1]; - } - int f = stones[n - 1]; - for (int i = n - 2; i > 0; --i) { - f = Math.max(f, stones[i] - f); - } - return f; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -209,25 +153,6 @@ public: }; ``` -```cpp -class Solution { -public: - int stoneGameVIII(vector& stones) { - int n = stones.size(); - for (int i = 1; i < n; ++i) { - stones[i] += stones[i - 1]; - } - int f = stones.back(); - for (int i = n - 2; i; --i) { - f = max(f, stones[i] - f); - } - return f; - } -}; -``` - -### **Go** - ```go func stoneGameVIII(stones []int) int { n := len(stones) @@ -252,22 +177,6 @@ func stoneGameVIII(stones []int) int { } ``` -```go -func stoneGameVIII(stones []int) int { - n := len(stones) - for i := 1; i < n; i++ { - stones[i] += stones[i-1] - } - f := stones[n-1] - for i := n - 2; i > 0; i-- { - f = max(f, stones[i]-f) - } - return f -} -``` - -### **TypeScript** - ```ts function stoneGameVIII(stones: number[]): number { const n = stones.length; @@ -288,6 +197,77 @@ function stoneGameVIII(stones: number[]): number { } ``` + + +### Solution 2: Prefix Sum + Dynamic Programming + +We can also use dynamic programming to solve this problem. + +Similar to Solution 1, we first use a prefix sum array $s$ of length $n$ to represent the prefix sum of the array $stones$, where $s[i]$ represents the sum of the elements $stones[0..i]$. + +We define $f[i]$ to represent the maximum score difference that the current player can get when taking stones from $stones[i:]$. + +If the player chooses to take the stones $stones[:i]$, then the score obtained is $s[i]$. At this time, the other player will take stones from $stones[i+1:]$, and the maximum score difference that the other player can get is $f[i+1]$. Therefore, the maximum score difference that the current player can get is $s[i] - f[i+1]$. + +If the player chooses to take stones from $stones[i+1:]$, then the maximum score difference obtained is $f[i+1]$. + +Therefore, we can get the state transition equation: + +$$ +f[i] = \max\{s[i] - f[i+1], f[i+1]\} +$$ + +Finally, we can get the score difference between Alice and Bob as $f[1]$, that is, Alice must start the game by taking stones from $stones[1:]$. + +We notice that $f[i]$ is only related to $f[i+1]$, so we only need to use a variable $f$ to represent $f[i]$. + +The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $stones$. + + + +```python +class Solution: + def stoneGameVIII(self, stones: List[int]) -> int: + s = list(accumulate(stones)) + f = s[-1] + for i in range(len(s) - 2, 0, -1): + f = max(f, s[i] - f) + return f +``` + +```java +class Solution { + public int stoneGameVIII(int[] stones) { + int n = stones.length; + for (int i = 1; i < n; ++i) { + stones[i] += stones[i - 1]; + } + int f = stones[n - 1]; + for (int i = n - 2; i > 0; --i) { + f = Math.max(f, stones[i] - f); + } + return f; + } +} +``` + +```cpp +class Solution { +public: + int stoneGameVIII(vector& stones) { + int n = stones.size(); + for (int i = 1; i < n; ++i) { + stones[i] += stones[i - 1]; + } + int f = stones.back(); + for (int i = n - 2; i; --i) { + f = max(f, stones[i] - f); + } + return f; + } +}; +``` + ```ts function stoneGameVIII(stones: number[]): number { const n = stones.length; @@ -302,10 +282,6 @@ function stoneGameVIII(stones: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1873.Calculate Special Bonus/README.md b/solution/1800-1899/1873.Calculate Special Bonus/README.md index f8f1dd2a5e8db..cbd8551af7515 100644 --- a/solution/1800-1899/1873.Calculate Special Bonus/README.md +++ b/solution/1800-1899/1873.Calculate Special Bonus/README.md @@ -61,18 +61,12 @@ Employees 表: ## 解法 - - -**方法一:IF 语句 + ORDER BY 子句** +### 方法一:IF 语句 + ORDER BY 子句 我们可以使用 `IF` 语句来判断奖金的计算方式,然后使用 `ORDER BY` 将结果按照 `employee_id` 排序。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -89,3 +83,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1800-1899/1873.Calculate Special Bonus/README_EN.md b/solution/1800-1899/1873.Calculate Special Bonus/README_EN.md index 6c37b8363d137..3f087ce86ba07 100644 --- a/solution/1800-1899/1873.Calculate Special Bonus/README_EN.md +++ b/solution/1800-1899/1873.Calculate Special Bonus/README_EN.md @@ -59,14 +59,12 @@ The rest of the employees get a 100% bonus. ## Solutions -**Solution 1: IF Statement + ORDER BY Clause** +### Solution 1: IF Statement + ORDER BY Clause We can use the `IF` statement to determine the calculation method of the bonus, and then use `ORDER BY` to sort the results by `employee_id`. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -83,3 +81,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1800-1899/1874.Minimize Product Sum of Two Arrays/README.md b/solution/1800-1899/1874.Minimize Product Sum of Two Arrays/README.md index 0984560fdc0bf..82ce7c0bbdec6 100644 --- a/solution/1800-1899/1874.Minimize Product Sum of Two Arrays/README.md +++ b/solution/1800-1899/1874.Minimize Product Sum of Two Arrays/README.md @@ -40,16 +40,10 @@ ## 解法 - - -对两数组排序,然后首尾相乘求和。 +### 方法一 -### **Python3** - - - ```python class Solution: def minProductSum(self, nums1: List[int], nums2: List[int]) -> int: @@ -61,10 +55,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int minProductSum(int[] nums1, int[] nums2) { @@ -79,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +84,6 @@ public: }; ``` -### **Go** - ```go func minProductSum(nums1 []int, nums2 []int) int { sort.Ints(nums1) @@ -110,10 +96,6 @@ func minProductSum(nums1 []int, nums2 []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1874.Minimize Product Sum of Two Arrays/README_EN.md b/solution/1800-1899/1874.Minimize Product Sum of Two Arrays/README_EN.md index c4f5e60c623e9..8acc3110a1a8f 100644 --- a/solution/1800-1899/1874.Minimize Product Sum of Two Arrays/README_EN.md +++ b/solution/1800-1899/1874.Minimize Product Sum of Two Arrays/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public int minProductSum(int[] nums1, int[] nums2) { @@ -71,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -88,8 +84,6 @@ public: }; ``` -### **Go** - ```go func minProductSum(nums1 []int, nums2 []int) int { sort.Ints(nums1) @@ -102,10 +96,6 @@ func minProductSum(nums1 []int, nums2 []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1875.Group Employees of the Same Salary/README.md b/solution/1800-1899/1875.Group Employees of the Same Salary/README.md index 607b9014b1daf..bcc32c4312836 100644 --- a/solution/1800-1899/1875.Group Employees of the Same Salary/README.md +++ b/solution/1800-1899/1875.Group Employees of the Same Salary/README.md @@ -74,14 +74,10 @@ Juan的工资(6100)没有被计算在排名中,因为他不属于任何一个 ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -103,3 +99,5 @@ ORDER BY 4, 1; ``` + + diff --git a/solution/1800-1899/1875.Group Employees of the Same Salary/README_EN.md b/solution/1800-1899/1875.Group Employees of the Same Salary/README_EN.md index 4ed290f23d2eb..7710fdeceda10 100644 --- a/solution/1800-1899/1875.Group Employees of the Same Salary/README_EN.md +++ b/solution/1800-1899/1875.Group Employees of the Same Salary/README_EN.md @@ -72,9 +72,9 @@ Juan's salary of 6100 is not included in the ranking because they are not on ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -97,3 +97,5 @@ ORDER BY 4, 1; ``` + + diff --git a/solution/1800-1899/1876.Substrings of Size Three with Distinct Characters/README.md b/solution/1800-1899/1876.Substrings of Size Three with Distinct Characters/README.md index 191d046044c39..9580961d756db 100644 --- a/solution/1800-1899/1876.Substrings of Size Three with Distinct Characters/README.md +++ b/solution/1800-1899/1876.Substrings of Size Three with Distinct Characters/README.md @@ -45,14 +45,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def countGoodSubstrings(self, s: str) -> int: @@ -62,10 +58,6 @@ class Solution: return count ``` -### **Java** - - - ```java class Solution { public int countGoodSubstrings(String s) { @@ -81,8 +73,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function countGoodSubstrings(s: string): number { const n: number = s.length; @@ -99,8 +89,6 @@ function countGoodSubstrings(s: string): number { } ``` -### **PHP** - ```php class Solution { /** @@ -119,10 +107,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1876.Substrings of Size Three with Distinct Characters/README_EN.md b/solution/1800-1899/1876.Substrings of Size Three with Distinct Characters/README_EN.md index 6d8722739da17..2b03fa9ccce98 100644 --- a/solution/1800-1899/1876.Substrings of Size Three with Distinct Characters/README_EN.md +++ b/solution/1800-1899/1876.Substrings of Size Three with Distinct Characters/README_EN.md @@ -41,9 +41,9 @@ The good substrings are "abc", "bca", "cab", and & ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return count ``` -### **Java** - ```java class Solution { public int countGoodSubstrings(String s) { @@ -71,8 +69,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function countGoodSubstrings(s: string): number { const n: number = s.length; @@ -89,8 +85,6 @@ function countGoodSubstrings(s: string): number { } ``` -### **PHP** - ```php class Solution { /** @@ -109,10 +103,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1877.Minimize Maximum Pair Sum in Array/README.md b/solution/1800-1899/1877.Minimize Maximum Pair Sum in Array/README.md index 731e7a74364ca..3c36a6147d734 100644 --- a/solution/1800-1899/1877.Minimize Maximum Pair Sum in Array/README.md +++ b/solution/1800-1899/1877.Minimize Maximum Pair Sum in Array/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 要使得数组中最大数对和的值最小,那么我们可以将数组中最小的数和最大的数配对,次小的数和次大的数配对,依此类推。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def minPairSum(self, nums: List[int]) -> int: @@ -76,10 +70,6 @@ class Solution: return max(x + nums[n - i - 1] for i, x in enumerate(nums[: n >> 1])) ``` -### **Java** - - - ```java class Solution { public int minPairSum(int[] nums) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +97,6 @@ public: }; ``` -### **Go** - ```go func minPairSum(nums []int) (ans int) { sort.Ints(nums) @@ -122,8 +108,6 @@ func minPairSum(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function minPairSum(nums: number[]): number { nums.sort((a, b) => a - b); @@ -136,8 +120,6 @@ function minPairSum(nums: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int MinPairSum(int[] nums) { @@ -151,10 +133,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1877.Minimize Maximum Pair Sum in Array/README_EN.md b/solution/1800-1899/1877.Minimize Maximum Pair Sum in Array/README_EN.md index 9b78d50ee6865..8395e1ff6f545 100644 --- a/solution/1800-1899/1877.Minimize Maximum Pair Sum in Array/README_EN.md +++ b/solution/1800-1899/1877.Minimize Maximum Pair Sum in Array/README_EN.md @@ -50,12 +50,10 @@ The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. ## Solutions -Sort & Greedy. +### Solution 1 -### **Python3** - ```python class Solution: def minPairSum(self, nums: List[int]) -> int: @@ -64,8 +62,6 @@ class Solution: return max(x + nums[n - i - 1] for i, x in enumerate(nums[: n >> 1])) ``` -### **Java** - ```java class Solution { public int minPairSum(int[] nums) { @@ -79,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +89,6 @@ public: }; ``` -### **Go** - ```go func minPairSum(nums []int) (ans int) { sort.Ints(nums) @@ -108,8 +100,6 @@ func minPairSum(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function minPairSum(nums: number[]): number { nums.sort((a, b) => a - b); @@ -122,8 +112,6 @@ function minPairSum(nums: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int MinPairSum(int[] nums) { @@ -137,10 +125,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/README.md b/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/README.md index 59aeaa8b43f2d..a7f9cea218fd5 100644 --- a/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/README.md +++ b/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:枚举菱形中心点 + 前缀和 + 有序集合** +### 方法一:枚举菱形中心点 + 前缀和 + 有序集合 我们可以预处理得到两个前缀和数组 $s_1$ 和 $s_2$,其中 $s_1[i][j]$ 表示以 $(i, j)$ 为末尾的左上对角线上的元素之和,而 $s_2[i][j]$ 表示以 $(i, j)$ 为末尾的右上对角线上的元素之和。 @@ -83,10 +81,6 @@ $$ -### **Python3** - - - ```python from sortedcontainers import SortedSet @@ -118,10 +112,6 @@ class Solution: return list(ss)[::-1] ``` -### **Java** - - - ```java class Solution { public int[] getBiggestThree(int[][] grid) { @@ -160,8 +150,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -197,8 +185,6 @@ public: }; ``` -### **Go** - ```go func getBiggestThree(grid [][]int) []int { m, n := len(grid), len(grid[0]) @@ -241,8 +227,6 @@ func getBiggestThree(grid [][]int) []int { } ``` -### **TypeScript** - ```ts function getBiggestThree(grid: number[][]): number[] { const m = grid.length; @@ -916,10 +900,6 @@ class TreeMultiSet { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/README_EN.md b/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/README_EN.md index c305d3eb78410..5eb90ddbbde2a 100644 --- a/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/README_EN.md +++ b/solution/1800-1899/1878.Get Biggest Three Rhombus Sums in a Grid/README_EN.md @@ -55,7 +55,7 @@ ## Solutions -**Solution 1: Enumerate Diamond Center + Prefix Sum + Ordered Set** +### Solution 1: Enumerate Diamond Center + Prefix Sum + Ordered Set We can preprocess to get two prefix sum arrays $s_1$ and $s_2$, where $s_1[i][j]$ represents the sum of the elements on the upper left diagonal ending at $(i, j)$, and $s_2[i][j]$ represents the sum of the elements on the upper right diagonal ending at $(i, j)$. @@ -75,8 +75,6 @@ The time complexity is $O(m \times n \times \min(m, n))$, and the space complexi -### **Python3** - ```python from sortedcontainers import SortedSet @@ -108,8 +106,6 @@ class Solution: return list(ss)[::-1] ``` -### **Java** - ```java class Solution { public int[] getBiggestThree(int[][] grid) { @@ -148,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -185,8 +179,6 @@ public: }; ``` -### **Go** - ```go func getBiggestThree(grid [][]int) []int { m, n := len(grid), len(grid[0]) @@ -229,8 +221,6 @@ func getBiggestThree(grid [][]int) []int { } ``` -### **TypeScript** - ```ts function getBiggestThree(grid: number[][]): number[] { const m = grid.length; @@ -904,10 +894,6 @@ class TreeMultiSet { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/README.md b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/README.md index 1903ef9e1556a..56083333802f7 100644 --- a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/README.md +++ b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:状态压缩动态规划** +### 方法一:状态压缩动态规划 我们注意到 $n \leq 14$,因此,我们可以考虑使用状态压缩动态规划的方法求解本题。 @@ -66,18 +64,8 @@ 我们注意到,状态 $f[i][j]$ 只与 $f[i-1][j\oplus 2^k]$ 有关,因此我们去掉第一维,将空间复杂度优化到 $O(2^n)$。 -**方法二:状态压缩动态规划(枚举优化)** - -我们也可以直接在 $[0, 2^n)$ 范围内枚举状态 $i$,假设 $i$ 的二进制表示中有 $k$ 个 $1$,那么当前枚举的就是 $nums1$ 的第 $k$ 个数,下标为 $k-1$。状态转移方程为 $f[i]=\min(f[i],f[i\oplus 2^j]+(nums1[k-1]\oplus nums2[j]))$,其中 $j$ 是 $i$ 的二进制表示中的某个 $1$ 所在的位置。 - -时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(2^n)$。其中 $n$ 是数组的长度。 - -### **Python3** - - - ```python class Solution: def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: @@ -92,38 +80,6 @@ class Solution: return f[-1][-1] ``` -```python -class Solution: - def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: - n = len(nums2) - f = [inf] * (1 << n) - f[0] = 0 - for x in nums1: - for j in range((1 << n) - 1, -1, -1): - for k in range(n): - if j >> k & 1: - f[j] = min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])) - return f[-1] -``` - -```python -class Solution: - def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: - n = len(nums2) - f = [inf] * (1 << n) - f[0] = 0 - for i in range(1, 1 << n): - k = i.bit_count() - 1 - for j in range(n): - if i >> j & 1: - f[i] = min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])) - return f[-1] -``` - -### **Java** - - - ```java class Solution { public int minimumXORSum(int[] nums1, int[] nums2) { @@ -148,49 +104,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumXORSum(int[] nums1, int[] nums2) { - int n = nums1.length; - int[] f = new int[1 << n]; - Arrays.fill(f, 1 << 30); - f[0] = 0; - for (int x : nums1) { - for (int j = (1 << n) - 1; j >= 0; --j) { - for (int k = 0; k < n; ++k) { - if ((j >> k & 1) == 1) { - f[j] = Math.min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); - } - } - } - } - return f[(1 << n) - 1]; - } -} -``` - -```java -class Solution { - public int minimumXORSum(int[] nums1, int[] nums2) { - int n = nums1.length; - int[] f = new int[1 << n]; - Arrays.fill(f, 1 << 30); - f[0] = 0; - for (int i = 0; i < 1 << n; ++i) { - int k = Integer.bitCount(i) - 1; - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 1) { - f[i] = Math.min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])); - } - } - } - return f[(1 << n) - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -213,26 +126,93 @@ public: }; ``` -```cpp +```go +func minimumXORSum(nums1 []int, nums2 []int) int { + n := len(nums1) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, 1<>k&1 == 1 { + f[i][j] = min(f[i][j], f[i-1][j^(1< Array(1 << n).fill(1 << 30)); + f[0][0] = 0; + for (let i = 1; i <= n; ++i) { + for (let j = 0; j < 1 << n; ++j) { + for (let k = 0; k < n; ++k) { + if (((j >> k) & 1) === 1) { + f[i][j] = Math.min(f[i][j], f[i - 1][j ^ (1 << k)] + (nums1[i - 1] ^ nums2[k])); + } + } + } + } + return f[n][(1 << n) - 1]; +} +``` + + + +### 方法二:状态压缩动态规划(枚举优化) + +我们也可以直接在 $[0, 2^n)$ 范围内枚举状态 $i$,假设 $i$ 的二进制表示中有 $k$ 个 $1$,那么当前枚举的就是 $nums1$ 的第 $k$ 个数,下标为 $k-1$。状态转移方程为 $f[i]=\min(f[i],f[i\oplus 2^j]+(nums1[k-1]\oplus nums2[j]))$,其中 $j$ 是 $i$ 的二进制表示中的某个 $1$ 所在的位置。 + +时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(2^n)$。其中 $n$ 是数组的长度。 + + + +```python +class Solution: + def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: + n = len(nums2) + f = [inf] * (1 << n) + f[0] = 0 + for x in nums1: + for j in range((1 << n) - 1, -1, -1): + for k in range(n): + if j >> k & 1: + f[j] = min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])) + return f[-1] +``` + +```java class Solution { -public: - int minimumXORSum(vector& nums1, vector& nums2) { - int n = nums1.size(); - int f[1 << n]; - memset(f, 0x3f, sizeof(f)); + public int minimumXORSum(int[] nums1, int[] nums2) { + int n = nums1.length; + int[] f = new int[1 << n]; + Arrays.fill(f, 1 << 30); f[0] = 0; for (int x : nums1) { - for (int j = (1 << n) - 1; ~j; --j) { + for (int j = (1 << n) - 1; j >= 0; --j) { for (int k = 0; k < n; ++k) { - if (j >> k & 1) { - f[j] = min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); + if ((j >> k & 1) == 1) { + f[j] = Math.min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); } } } } return f[(1 << n) - 1]; } -}; +} ``` ```cpp @@ -243,11 +223,12 @@ public: int f[1 << n]; memset(f, 0x3f, sizeof(f)); f[0] = 0; - for (int i = 0; i < 1 << n; ++i) { - int k = __builtin_popcount(i) - 1; - for (int j = 0; j < n; ++j) { - if (i >> j & 1) { - f[i] = min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])); + for (int x : nums1) { + for (int j = (1 << n) - 1; ~j; --j) { + for (int k = 0; k < n; ++k) { + if (j >> k & 1) { + f[j] = min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); + } } } } @@ -256,32 +237,6 @@ public: }; ``` -### **Go** - -```go -func minimumXORSum(nums1 []int, nums2 []int) int { - n := len(nums1) - f := make([][]int, n+1) - for i := range f { - f[i] = make([]int, 1<>k&1 == 1 { - f[i][j] = min(f[i][j], f[i-1][j^(1<> k) & 1) === 1) { + f[j] = Math.min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); + } + } + } + } + return f[(1 << n) - 1]; +} +``` + + + +### 方法三 + + + +```python +class Solution: + def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: + n = len(nums2) + f = [inf] * (1 << n) + f[0] = 0 + for i in range(1, 1 << n): + k = i.bit_count() - 1 + for j in range(n): + if i >> j & 1: + f[i] = min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])) + return f[-1] +``` + +```java +class Solution { + public int minimumXORSum(int[] nums1, int[] nums2) { + int n = nums1.length; + int[] f = new int[1 << n]; + Arrays.fill(f, 1 << 30); + f[0] = 0; + for (int i = 0; i < 1 << n; ++i) { + int k = Integer.bitCount(i) - 1; + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + f[i] = Math.min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])); + } + } + } + return f[(1 << n) - 1]; + } +} +``` + +```cpp +class Solution { +public: + int minimumXORSum(vector& nums1, vector& nums2) { + int n = nums1.size(); + int f[1 << n]; + memset(f, 0x3f, sizeof(f)); + f[0] = 0; + for (int i = 0; i < 1 << n; ++i) { + int k = __builtin_popcount(i) - 1; + for (int j = 0; j < n; ++j) { + if (i >> j & 1) { + f[i] = min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])); + } + } + } + return f[(1 << n) - 1]; + } +}; +``` + ```go func minimumXORSum(nums1 []int, nums2 []int) int { n := len(nums1) @@ -323,46 +357,6 @@ func minimumXORSum(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - -```ts -function minimumXORSum(nums1: number[], nums2: number[]): number { - const n = nums1.length; - const f: number[][] = Array(n + 1) - .fill(0) - .map(() => Array(1 << n).fill(1 << 30)); - f[0][0] = 0; - for (let i = 1; i <= n; ++i) { - for (let j = 0; j < 1 << n; ++j) { - for (let k = 0; k < n; ++k) { - if (((j >> k) & 1) === 1) { - f[i][j] = Math.min(f[i][j], f[i - 1][j ^ (1 << k)] + (nums1[i - 1] ^ nums2[k])); - } - } - } - } - return f[n][(1 << n) - 1]; -} -``` - -```ts -function minimumXORSum(nums1: number[], nums2: number[]): number { - const n = nums1.length; - const f: number[] = Array(1 << n).fill(1 << 30); - f[0] = 0; - for (const x of nums1) { - for (let j = (1 << n) - 1; ~j; --j) { - for (let k = 0; k < n; ++k) { - if (((j >> k) & 1) === 1) { - f[j] = Math.min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); - } - } - } - } - return f[(1 << n) - 1]; -} -``` - ```ts function minimumXORSum(nums1: number[], nums2: number[]): number { const n = nums1.length; @@ -389,10 +383,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/README_EN.md b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/README_EN.md index 1b3bb473c8659..65d650949b1f4 100644 --- a/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/README_EN.md +++ b/solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/README_EN.md @@ -46,9 +46,9 @@ The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,36 +64,6 @@ class Solution: return f[-1][-1] ``` -```python -class Solution: - def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: - n = len(nums2) - f = [inf] * (1 << n) - f[0] = 0 - for x in nums1: - for j in range((1 << n) - 1, -1, -1): - for k in range(n): - if j >> k & 1: - f[j] = min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])) - return f[-1] -``` - -```python -class Solution: - def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: - n = len(nums2) - f = [inf] * (1 << n) - f[0] = 0 - for i in range(1, 1 << n): - k = i.bit_count() - 1 - for j in range(n): - if i >> j & 1: - f[i] = min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])) - return f[-1] -``` - -### **Java** - ```java class Solution { public int minimumXORSum(int[] nums1, int[] nums2) { @@ -118,49 +88,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumXORSum(int[] nums1, int[] nums2) { - int n = nums1.length; - int[] f = new int[1 << n]; - Arrays.fill(f, 1 << 30); - f[0] = 0; - for (int x : nums1) { - for (int j = (1 << n) - 1; j >= 0; --j) { - for (int k = 0; k < n; ++k) { - if ((j >> k & 1) == 1) { - f[j] = Math.min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); - } - } - } - } - return f[(1 << n) - 1]; - } -} -``` - -```java -class Solution { - public int minimumXORSum(int[] nums1, int[] nums2) { - int n = nums1.length; - int[] f = new int[1 << n]; - Arrays.fill(f, 1 << 30); - f[0] = 0; - for (int i = 0; i < 1 << n; ++i) { - int k = Integer.bitCount(i) - 1; - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 1) { - f[i] = Math.min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])); - } - } - } - return f[(1 << n) - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -183,26 +110,89 @@ public: }; ``` -```cpp +```go +func minimumXORSum(nums1 []int, nums2 []int) int { + n := len(nums1) + f := make([][]int, n+1) + for i := range f { + f[i] = make([]int, 1<>k&1 == 1 { + f[i][j] = min(f[i][j], f[i-1][j^(1< Array(1 << n).fill(1 << 30)); + f[0][0] = 0; + for (let i = 1; i <= n; ++i) { + for (let j = 0; j < 1 << n; ++j) { + for (let k = 0; k < n; ++k) { + if (((j >> k) & 1) === 1) { + f[i][j] = Math.min(f[i][j], f[i - 1][j ^ (1 << k)] + (nums1[i - 1] ^ nums2[k])); + } + } + } + } + return f[n][(1 << n) - 1]; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: + n = len(nums2) + f = [inf] * (1 << n) + f[0] = 0 + for x in nums1: + for j in range((1 << n) - 1, -1, -1): + for k in range(n): + if j >> k & 1: + f[j] = min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])) + return f[-1] +``` + +```java class Solution { -public: - int minimumXORSum(vector& nums1, vector& nums2) { - int n = nums1.size(); - int f[1 << n]; - memset(f, 0x3f, sizeof(f)); + public int minimumXORSum(int[] nums1, int[] nums2) { + int n = nums1.length; + int[] f = new int[1 << n]; + Arrays.fill(f, 1 << 30); f[0] = 0; for (int x : nums1) { - for (int j = (1 << n) - 1; ~j; --j) { + for (int j = (1 << n) - 1; j >= 0; --j) { for (int k = 0; k < n; ++k) { - if (j >> k & 1) { - f[j] = min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); + if ((j >> k & 1) == 1) { + f[j] = Math.min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); } } } } return f[(1 << n) - 1]; } -}; +} ``` ```cpp @@ -213,11 +203,12 @@ public: int f[1 << n]; memset(f, 0x3f, sizeof(f)); f[0] = 0; - for (int i = 0; i < 1 << n; ++i) { - int k = __builtin_popcount(i) - 1; - for (int j = 0; j < n; ++j) { - if (i >> j & 1) { - f[i] = min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])); + for (int x : nums1) { + for (int j = (1 << n) - 1; ~j; --j) { + for (int k = 0; k < n; ++k) { + if (j >> k & 1) { + f[j] = min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); + } } } } @@ -226,32 +217,6 @@ public: }; ``` -### **Go** - -```go -func minimumXORSum(nums1 []int, nums2 []int) int { - n := len(nums1) - f := make([][]int, n+1) - for i := range f { - f[i] = make([]int, 1<>k&1 == 1 { - f[i][j] = min(f[i][j], f[i-1][j^(1<> k) & 1) === 1) { + f[j] = Math.min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); + } + } + } + } + return f[(1 << n) - 1]; +} +``` + + + +### Solution 3 + + + +```python +class Solution: + def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int: + n = len(nums2) + f = [inf] * (1 << n) + f[0] = 0 + for i in range(1, 1 << n): + k = i.bit_count() - 1 + for j in range(n): + if i >> j & 1: + f[i] = min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])) + return f[-1] +``` + +```java +class Solution { + public int minimumXORSum(int[] nums1, int[] nums2) { + int n = nums1.length; + int[] f = new int[1 << n]; + Arrays.fill(f, 1 << 30); + f[0] = 0; + for (int i = 0; i < 1 << n; ++i) { + int k = Integer.bitCount(i) - 1; + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + f[i] = Math.min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])); + } + } + } + return f[(1 << n) - 1]; + } +} +``` + +```cpp +class Solution { +public: + int minimumXORSum(vector& nums1, vector& nums2) { + int n = nums1.size(); + int f[1 << n]; + memset(f, 0x3f, sizeof(f)); + f[0] = 0; + for (int i = 0; i < 1 << n; ++i) { + int k = __builtin_popcount(i) - 1; + for (int j = 0; j < n; ++j) { + if (i >> j & 1) { + f[i] = min(f[i], f[i ^ (1 << j)] + (nums1[k] ^ nums2[j])); + } + } + } + return f[(1 << n) - 1]; + } +}; +``` + ```go func minimumXORSum(nums1 []int, nums2 []int) int { n := len(nums1) @@ -293,46 +337,6 @@ func minimumXORSum(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - -```ts -function minimumXORSum(nums1: number[], nums2: number[]): number { - const n = nums1.length; - const f: number[][] = Array(n + 1) - .fill(0) - .map(() => Array(1 << n).fill(1 << 30)); - f[0][0] = 0; - for (let i = 1; i <= n; ++i) { - for (let j = 0; j < 1 << n; ++j) { - for (let k = 0; k < n; ++k) { - if (((j >> k) & 1) === 1) { - f[i][j] = Math.min(f[i][j], f[i - 1][j ^ (1 << k)] + (nums1[i - 1] ^ nums2[k])); - } - } - } - } - return f[n][(1 << n) - 1]; -} -``` - -```ts -function minimumXORSum(nums1: number[], nums2: number[]): number { - const n = nums1.length; - const f: number[] = Array(1 << n).fill(1 << 30); - f[0] = 0; - for (const x of nums1) { - for (let j = (1 << n) - 1; ~j; --j) { - for (let k = 0; k < n; ++k) { - if (((j >> k) & 1) === 1) { - f[j] = Math.min(f[j], f[j ^ (1 << k)] + (x ^ nums2[k])); - } - } - } - } - return f[(1 << n) - 1]; -} -``` - ```ts function minimumXORSum(nums1: number[], nums2: number[]): number { const n = nums1.length; @@ -359,10 +363,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1880.Check if Word Equals Summation of Two Words/README.md b/solution/1800-1899/1880.Check if Word Equals Summation of Two Words/README.md index 65675ec21e361..7218597b42347 100644 --- a/solution/1800-1899/1880.Check if Word Equals Summation of Two Words/README.md +++ b/solution/1800-1899/1880.Check if Word Equals Summation of Two Words/README.md @@ -63,14 +63,10 @@ targetWord 的数值为 "aaaa" -> "0000" -> 0 ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool: @@ -83,10 +79,6 @@ class Solution: return f(firstWord) + f(secondWord) == f(targetWord) ``` -### **Java** - - - ```java class Solution { public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { @@ -103,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +110,6 @@ public: }; ``` -### **Go** - ```go func isSumEqual(firstWord string, secondWord string, targetWord string) bool { f := func(s string) int { @@ -135,29 +123,6 @@ func isSumEqual(firstWord string, secondWord string, targetWord string) bool { } ``` -### **JavaScript** - -```js -/** - * @param {string} firstWord - * @param {string} secondWord - * @param {string} targetWord - * @return {boolean} - */ -var isSumEqual = function (firstWord, secondWord, targetWord) { - function f(s) { - let res = 0; - for (let c of s) { - res = res * 10 + (c.charCodeAt() - 'a'.charCodeAt()); - } - return res; - } - return f(firstWord) + f(secondWord) == f(targetWord); -}; -``` - -### **TypeScript** - ```ts function isSumEqual(firstWord: string, secondWord: string, targetWord: string): boolean { const calc = (s: string) => { @@ -171,8 +136,6 @@ function isSumEqual(firstWord: string, secondWord: string, targetWord: string): } ``` -### **Rust** - ```rust impl Solution { fn calc(s: &String) -> i32 { @@ -189,7 +152,24 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {string} firstWord + * @param {string} secondWord + * @param {string} targetWord + * @return {boolean} + */ +var isSumEqual = function (firstWord, secondWord, targetWord) { + function f(s) { + let res = 0; + for (let c of s) { + res = res * 10 + (c.charCodeAt() - 'a'.charCodeAt()); + } + return res; + } + return f(firstWord) + f(secondWord) == f(targetWord); +}; +``` ```c int calc(char* s) { @@ -205,10 +185,6 @@ bool isSumEqual(char* firstWord, char* secondWord, char* targetWord) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1880.Check if Word Equals Summation of Two Words/README_EN.md b/solution/1800-1899/1880.Check if Word Equals Summation of Two Words/README_EN.md index f62ef2176aaf9..4f8efe07d144b 100644 --- a/solution/1800-1899/1880.Check if Word Equals Summation of Two Words/README_EN.md +++ b/solution/1800-1899/1880.Check if Word Equals Summation of Two Words/README_EN.md @@ -63,9 +63,9 @@ We return true because 0 + 0 == 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,8 +79,6 @@ class Solution: return f(firstWord) + f(secondWord) == f(targetWord) ``` -### **Java** - ```java class Solution { public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +110,6 @@ public: }; ``` -### **Go** - ```go func isSumEqual(firstWord string, secondWord string, targetWord string) bool { f := func(s string) int { @@ -129,29 +123,6 @@ func isSumEqual(firstWord string, secondWord string, targetWord string) bool { } ``` -### **JavaScript** - -```js -/** - * @param {string} firstWord - * @param {string} secondWord - * @param {string} targetWord - * @return {boolean} - */ -var isSumEqual = function (firstWord, secondWord, targetWord) { - function f(s) { - let res = 0; - for (let c of s) { - res = res * 10 + (c.charCodeAt() - 'a'.charCodeAt()); - } - return res; - } - return f(firstWord) + f(secondWord) == f(targetWord); -}; -``` - -### **TypeScript** - ```ts function isSumEqual(firstWord: string, secondWord: string, targetWord: string): boolean { const calc = (s: string) => { @@ -165,8 +136,6 @@ function isSumEqual(firstWord: string, secondWord: string, targetWord: string): } ``` -### **Rust** - ```rust impl Solution { fn calc(s: &String) -> i32 { @@ -183,7 +152,24 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {string} firstWord + * @param {string} secondWord + * @param {string} targetWord + * @return {boolean} + */ +var isSumEqual = function (firstWord, secondWord, targetWord) { + function f(s) { + let res = 0; + for (let c of s) { + res = res * 10 + (c.charCodeAt() - 'a'.charCodeAt()); + } + return res; + } + return f(firstWord) + f(secondWord) == f(targetWord); +}; +``` ```c int calc(char* s) { @@ -199,10 +185,6 @@ bool isSumEqual(char* firstWord, char* secondWord, char* targetWord) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1881.Maximum Value after Insertion/README.md b/solution/1800-1899/1881.Maximum Value after Insertion/README.md index 5e92353206b73..a442086e5f9df 100644 --- a/solution/1800-1899/1881.Maximum Value after Insertion/README.md +++ b/solution/1800-1899/1881.Maximum Value after Insertion/README.md @@ -49,14 +49,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxValue(self, n: str, x: int) -> str: @@ -72,10 +68,6 @@ class Solution: return n + str(x) ``` -### **Java** - - - ```java class Solution { public String maxValue(String n, int x) { @@ -92,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +100,6 @@ public: }; ``` -### **Go** - ```go func maxValue(n string, x int) string { i := 0 @@ -127,8 +115,6 @@ func maxValue(n string, x int) string { } ``` -### **JavaScript** - ```js /** * @param {string} n @@ -151,10 +137,6 @@ var maxValue = function (n, x) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1881.Maximum Value after Insertion/README_EN.md b/solution/1800-1899/1881.Maximum Value after Insertion/README_EN.md index a770f7d377aef..cb86172861bbf 100644 --- a/solution/1800-1899/1881.Maximum Value after Insertion/README_EN.md +++ b/solution/1800-1899/1881.Maximum Value after Insertion/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return n + str(x) ``` -### **Java** - ```java class Solution { public String maxValue(String n, int x) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +96,6 @@ public: }; ``` -### **Go** - ```go func maxValue(n string, x int) string { i := 0 @@ -117,8 +111,6 @@ func maxValue(n string, x int) string { } ``` -### **JavaScript** - ```js /** * @param {string} n @@ -141,10 +133,6 @@ var maxValue = function (n, x) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1882.Process Tasks Using Servers/README.md b/solution/1800-1899/1882.Process Tasks Using Servers/README.md index cb3328a49847a..85348959232d3 100644 --- a/solution/1800-1899/1882.Process Tasks Using Servers/README.md +++ b/solution/1800-1899/1882.Process Tasks Using Servers/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:优先队列(小根堆)** +### 方法一:优先队列(小根堆) 定义两个优先级队列,分别表示空闲服务器、使用中的服务器。其中:空闲服务器 `idle` 依据**权重、下标**排序;而使用中的服务器 `busy` 依据**结束时间、权重、下标**排序。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]: @@ -101,10 +95,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int[] assignTasks(int[] servers, int[] tasks) { @@ -143,10 +133,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1882.Process Tasks Using Servers/README_EN.md b/solution/1800-1899/1882.Process Tasks Using Servers/README_EN.md index 147986dc4608e..f87f738a396a6 100644 --- a/solution/1800-1899/1882.Process Tasks Using Servers/README_EN.md +++ b/solution/1800-1899/1882.Process Tasks Using Servers/README_EN.md @@ -59,9 +59,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public int[] assignTasks(int[] servers, int[] tasks) { @@ -124,10 +122,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/README.md b/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/README.md index 4e7413bde302a..eed2cd4dfbdff 100644 --- a/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/README.md +++ b/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示考虑前 $i$ 条道路,恰好跳过 $j$ 次休息时间的最短用时。初始时 $f[0][0]=0$,其余 $f[i][j]=\infty$。 @@ -87,10 +85,6 @@ $$ -### **Python3** - - - ```python class Solution: def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int: @@ -110,28 +104,6 @@ class Solution: return -1 ``` -```python -class Solution: - def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int: - n = len(dist) - f = [[inf] * (n + 1) for _ in range(n + 1)] - f[0][0] = 0 - for i, x in enumerate(dist, 1): - for j in range(i + 1): - if j < i: - f[i][j] = min(f[i][j], ((f[i - 1][j] + x - 1) // speed + 1) * speed) - if j: - f[i][j] = min(f[i][j], f[i - 1][j - 1] + x) - for j in range(n + 1): - if f[n][j] <= hoursBefore * speed: - return j - return -1 -``` - -### **Java** - - - ```java class Solution { public int minSkips(int[] dist, int speed, int hoursBefore) { @@ -163,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -193,8 +163,6 @@ public: }; ``` -### **Go** - ```go func minSkips(dist []int, speed int, hoursBefore int) int { n := len(dist) @@ -226,8 +194,6 @@ func minSkips(dist []int, speed int, hoursBefore int) int { } ``` -### **TypeScript** - ```ts function minSkips(dist: number[], speed: number, hoursBefore: number): number { const n = dist.length; @@ -253,10 +219,30 @@ function minSkips(dist: number[], speed: number, hoursBefore: number): number { } ``` -### **...** + + +### 方法二 -``` + +```python +class Solution: + def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int: + n = len(dist) + f = [[inf] * (n + 1) for _ in range(n + 1)] + f[0][0] = 0 + for i, x in enumerate(dist, 1): + for j in range(i + 1): + if j < i: + f[i][j] = min(f[i][j], ((f[i - 1][j] + x - 1) // speed + 1) * speed) + if j: + f[i][j] = min(f[i][j], f[i - 1][j - 1] + x) + for j in range(n + 1): + if f[n][j] <= hoursBefore * speed: + return j + return -1 ``` + + diff --git a/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/README_EN.md b/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/README_EN.md index 7fa4c8303800a..50fc038083308 100644 --- a/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/README_EN.md +++ b/solution/1800-1899/1883.Minimum Skips to Arrive at Meeting On Time/README_EN.md @@ -63,9 +63,9 @@ You can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0) ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -86,26 +86,6 @@ class Solution: return -1 ``` -```python -class Solution: - def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int: - n = len(dist) - f = [[inf] * (n + 1) for _ in range(n + 1)] - f[0][0] = 0 - for i, x in enumerate(dist, 1): - for j in range(i + 1): - if j < i: - f[i][j] = min(f[i][j], ((f[i - 1][j] + x - 1) // speed + 1) * speed) - if j: - f[i][j] = min(f[i][j], f[i - 1][j - 1] + x) - for j in range(n + 1): - if f[n][j] <= hoursBefore * speed: - return j - return -1 -``` - -### **Java** - ```java class Solution { public int minSkips(int[] dist, int speed, int hoursBefore) { @@ -137,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +145,6 @@ public: }; ``` -### **Go** - ```go func minSkips(dist []int, speed int, hoursBefore int) int { n := len(dist) @@ -200,8 +176,6 @@ func minSkips(dist []int, speed int, hoursBefore int) int { } ``` -### **TypeScript** - ```ts function minSkips(dist: number[], speed: number, hoursBefore: number): number { const n = dist.length; @@ -227,10 +201,30 @@ function minSkips(dist: number[], speed: number, hoursBefore: number): number { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int: + n = len(dist) + f = [[inf] * (n + 1) for _ in range(n + 1)] + f[0][0] = 0 + for i, x in enumerate(dist, 1): + for j in range(i + 1): + if j < i: + f[i][j] = min(f[i][j], ((f[i - 1][j] + x - 1) // speed + 1) * speed) + if j: + f[i][j] = min(f[i][j], f[i - 1][j - 1] + x) + for j in range(n + 1): + if f[n][j] <= hoursBefore * speed: + return j + return -1 ``` + + diff --git a/solution/1800-1899/1884.Egg Drop With 2 Eggs and N Floors/README.md b/solution/1800-1899/1884.Egg Drop With 2 Eggs and N Floors/README.md index fd1dfebdee5f2..a74eb2cbb4128 100644 --- a/solution/1800-1899/1884.Egg Drop With 2 Eggs and N Floors/README.md +++ b/solution/1800-1899/1884.Egg Drop With 2 Eggs and N Floors/README.md @@ -50,30 +50,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1800-1899/1884.Egg Drop With 2 Eggs and N Floors/README_EN.md b/solution/1800-1899/1884.Egg Drop With 2 Eggs and N Floors/README_EN.md index c29d3e4dcd105..6574525828356 100644 --- a/solution/1800-1899/1884.Egg Drop With 2 Eggs and N Floors/README_EN.md +++ b/solution/1800-1899/1884.Egg Drop With 2 Eggs and N Floors/README_EN.md @@ -45,24 +45,4 @@ Regardless of the outcome, it takes at most 14 drops to determine f. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1800-1899/1885.Count Pairs in Two Arrays/README.md b/solution/1800-1899/1885.Count Pairs in Two Arrays/README.md index 95128de4f69ff..edc6ba222df5c 100644 --- a/solution/1800-1899/1885.Count Pairs in Two Arrays/README.md +++ b/solution/1800-1899/1885.Count Pairs in Two Arrays/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 `nums1[i] + nums1[j] > nums2[i] + nums2[j]` 可以转换为 `nums1[i] - nums2[i] > -(nums1[j] - nums2[j])`。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def countPairs(self, nums1: List[int], nums2: List[int]) -> int: @@ -67,10 +61,6 @@ class Solution: return sum(n - bisect_right(d, -v, lo=i + 1) for i, v in enumerate(d)) ``` -### **Java** - - - ```java class Solution { public long countPairs(int[] nums1, int[] nums2) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func countPairs(nums1 []int, nums2 []int) int64 { n := len(nums1) @@ -145,10 +131,6 @@ func countPairs(nums1 []int, nums2 []int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1885.Count Pairs in Two Arrays/README_EN.md b/solution/1800-1899/1885.Count Pairs in Two Arrays/README_EN.md index 47968f63e9883..91bcef21abff3 100644 --- a/solution/1800-1899/1885.Count Pairs in Two Arrays/README_EN.md +++ b/solution/1800-1899/1885.Count Pairs in Two Arrays/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return sum(n - bisect_right(d, -v, lo=i + 1) for i, v in enumerate(d)) ``` -### **Java** - ```java class Solution { public long countPairs(int[] nums1, int[] nums2) { @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +99,6 @@ public: }; ``` -### **Go** - ```go func countPairs(nums1 []int, nums2 []int) int64 { n := len(nums1) @@ -130,10 +124,6 @@ func countPairs(nums1 []int, nums2 []int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/README.md b/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/README.md index 52dff0147945f..deb4ef67c1de2 100644 --- a/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/README.md +++ b/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/README.md @@ -47,31 +47,12 @@ ## 解法 - - -**方法一:模拟旋转** +### 方法一:模拟旋转 旋转矩阵,判断矩阵是否一致,旋转方式同 [48. 旋转图像](https://leetcode.cn/problems/rotate-image/)。 -**方法二:原地比较** - -此题不同于 [48. 旋转图像](https://leetcode.cn/problems/rotate-image/),并不要求改动原数组,因此,只要比较对应的位置即可。 - -| 旋转度数 | A | B | -| -------- | ------ | -------------- | -| 0 | `i, j` | `i, j` | -| 90 | `i, j` | `j, n - i` | -| 180 | `i, j` | `n - i, n - j` | -| 270 | `i, j` | `n - j, i` | - -> `n = A.length - 1 = B.length - 1` - -### **Python3** - - - ```python class Solution: def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: @@ -92,20 +73,6 @@ class Solution: return False ``` -```python -class Solution: - def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: - for _ in range(4): - mat = [list(col) for col in zip(*mat[::-1])] - if mat == target: - return True - return False -``` - -### **Java** - - - ```java class Solution { public boolean findRotation(int[][] mat, int[][] target) { @@ -146,41 +113,6 @@ class Solution { } ``` -```java -class Solution { - public boolean findRotation(int[][] mat, int[][] target) { - int n = mat.length; - for (int k = 0; k < 4; ++k) { - int[][] g = new int[n][n]; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - g[i][j] = mat[j][n - i - 1]; - } - } - if (equals(g, target)) { - return true; - } - mat = g; - } - return false; - } - - private boolean equals(int[][] a, int[][] b) { - int n = a.length; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (a[i][j] != b[i][j]) { - return false; - } - } - } - return true; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -199,8 +131,6 @@ public: }; ``` -### **Go** - ```go func findRotation(mat [][]int, target [][]int) bool { n := len(mat) @@ -234,8 +164,6 @@ func equals(a, b [][]int) bool { } ``` -### **TypeScript** - ```ts function findRotation(mat: number[][], target: number[][]): boolean { for (let k = 0; k < 4; k++) { @@ -279,8 +207,6 @@ function rotate(matrix: number[][]): void { } ``` -### **Rust** - ```rust impl Solution { pub fn find_rotation(mat: Vec>, target: Vec>) -> bool { @@ -307,10 +233,66 @@ impl Solution { } ``` -### **...** + + +### 方法二:原地比较 + +此题不同于 [48. 旋转图像](https://leetcode.cn/problems/rotate-image/),并不要求改动原数组,因此,只要比较对应的位置即可。 + +| 旋转度数 | A | B | +| -------- | ------ | -------------- | +| 0 | `i, j` | `i, j` | +| 90 | `i, j` | `j, n - i` | +| 180 | `i, j` | `n - i, n - j` | +| 270 | `i, j` | `n - j, i` | + +> `n = A.length - 1 = B.length - 1` + + +```python +class Solution: + def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: + for _ in range(4): + mat = [list(col) for col in zip(*mat[::-1])] + if mat == target: + return True + return False ``` +```java +class Solution { + public boolean findRotation(int[][] mat, int[][] target) { + int n = mat.length; + for (int k = 0; k < 4; ++k) { + int[][] g = new int[n][n]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + g[i][j] = mat[j][n - i - 1]; + } + } + if (equals(g, target)) { + return true; + } + mat = g; + } + return false; + } + + private boolean equals(int[][] a, int[][] b) { + int n = a.length; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (a[i][j] != b[i][j]) { + return false; + } + } + } + return true; + } +} ``` + + diff --git a/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/README_EN.md b/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/README_EN.md index 7f658ffe22c5e..6f4effd6ba1b3 100644 --- a/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/README_EN.md +++ b/solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,18 +67,6 @@ class Solution: return False ``` -```python -class Solution: - def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: - for _ in range(4): - mat = [list(col) for col in zip(*mat[::-1])] - if mat == target: - return True - return False -``` - -### **Java** - ```java class Solution { public boolean findRotation(int[][] mat, int[][] target) { @@ -119,41 +107,6 @@ class Solution { } ``` -```java -class Solution { - public boolean findRotation(int[][] mat, int[][] target) { - int n = mat.length; - for (int k = 0; k < 4; ++k) { - int[][] g = new int[n][n]; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - g[i][j] = mat[j][n - i - 1]; - } - } - if (equals(g, target)) { - return true; - } - mat = g; - } - return false; - } - - private boolean equals(int[][] a, int[][] b) { - int n = a.length; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (a[i][j] != b[i][j]) { - return false; - } - } - } - return true; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -172,8 +125,6 @@ public: }; ``` -### **Go** - ```go func findRotation(mat [][]int, target [][]int) bool { n := len(mat) @@ -207,8 +158,6 @@ func equals(a, b [][]int) bool { } ``` -### **TypeScript** - ```ts function findRotation(mat: number[][], target: number[][]): boolean { for (let k = 0; k < 4; k++) { @@ -252,8 +201,6 @@ function rotate(matrix: number[][]): void { } ``` -### **Rust** - ```rust impl Solution { pub fn find_rotation(mat: Vec>, target: Vec>) -> bool { @@ -280,10 +227,55 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool: + for _ in range(4): + mat = [list(col) for col in zip(*mat[::-1])] + if mat == target: + return True + return False ``` +```java +class Solution { + public boolean findRotation(int[][] mat, int[][] target) { + int n = mat.length; + for (int k = 0; k < 4; ++k) { + int[][] g = new int[n][n]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + g[i][j] = mat[j][n - i - 1]; + } + } + if (equals(g, target)) { + return true; + } + mat = g; + } + return false; + } + + private boolean equals(int[][] a, int[][] b) { + int n = a.length; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (a[i][j] != b[i][j]) { + return false; + } + } + } + return true; + } +} ``` + + diff --git a/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/README.md b/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/README.md index d951f83323901..5bd91b69c6d18 100644 --- a/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/README.md +++ b/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 对 $nums$ 进行排序,用 $cnt$ 表示元素所需的操作次数,初始时 $cnt=0$。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def reductionOperations(self, nums: List[int]) -> int: @@ -88,20 +82,6 @@ class Solution: return ans ``` -```python -class Solution: - def reductionOperations(self, nums: List[int]) -> int: - ans = cnt = 0 - for _, v in sorted(Counter(nums).items()): - ans += cnt * v - cnt += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int reductionOperations(int[] nums) { @@ -118,42 +98,6 @@ class Solution { } ``` -```java -class Solution { - public int reductionOperations(int[] nums) { - Map tm = new TreeMap<>(); - for (int v : nums) { - tm.put(v, tm.getOrDefault(v, 0) + 1); - } - int ans = 0, cnt = 0; - for (int v : tm.values()) { - ans += cnt * v; - ++cnt; - } - return ans; - } -} -``` - -### **TypeScript** - -```ts -function reductionOperations(nums: number[]): number { - nums.sort((a, b) => a - b); - let ans = 0; - let cnt = 0; - for (let i = 1; i < nums.length; ++i) { - if (nums[i] != nums[i - 1]) { - ++cnt; - } - ans += cnt; - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -169,24 +113,6 @@ public: }; ``` -```cpp -class Solution { -public: - int reductionOperations(vector& nums) { - map m; - for (int v : nums) ++m[v]; - int ans = 0, cnt = 0; - for (auto [_, v] : m) { - ans += cnt * v; - ++cnt; - } - return ans; - } -}; -``` - -### **Go** - ```go func reductionOperations(nums []int) int { sort.Ints(nums) @@ -201,7 +127,20 @@ func reductionOperations(nums []int) int { } ``` -### **C#** +```ts +function reductionOperations(nums: number[]): number { + nums.sort((a, b) => a - b); + let ans = 0; + let cnt = 0; + for (let i = 1; i < nums.length; ++i) { + if (nums[i] != nums[i - 1]) { + ++cnt; + } + ans += cnt; + } + return ans; +} +``` ```cs public class Solution { @@ -219,10 +158,55 @@ public class Solution { } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def reductionOperations(self, nums: List[int]) -> int: + ans = cnt = 0 + for _, v in sorted(Counter(nums).items()): + ans += cnt * v + cnt += 1 + return ans +``` +```java +class Solution { + public int reductionOperations(int[] nums) { + Map tm = new TreeMap<>(); + for (int v : nums) { + tm.put(v, tm.getOrDefault(v, 0) + 1); + } + int ans = 0, cnt = 0; + for (int v : tm.values()) { + ans += cnt * v; + ++cnt; + } + return ans; + } +} ``` +```cpp +class Solution { +public: + int reductionOperations(vector& nums) { + map m; + for (int v : nums) ++m[v]; + int ans = 0, cnt = 0; + for (auto [_, v] : m) { + ans += cnt * v; + ++cnt; + } + return ans; + } +}; ``` + + diff --git a/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/README_EN.md b/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/README_EN.md index f050c24969e09..3fc6bb61c1b27 100644 --- a/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/README_EN.md +++ b/solution/1800-1899/1887.Reduction Operations to Make the Array Elements Equal/README_EN.md @@ -56,9 +56,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,18 +72,6 @@ class Solution: return ans ``` -```python -class Solution: - def reductionOperations(self, nums: List[int]) -> int: - ans = cnt = 0 - for _, v in sorted(Counter(nums).items()): - ans += cnt * v - cnt += 1 - return ans -``` - -### **Java** - ```java class Solution { public int reductionOperations(int[] nums) { @@ -100,42 +88,6 @@ class Solution { } ``` -```java -class Solution { - public int reductionOperations(int[] nums) { - Map tm = new TreeMap<>(); - for (int v : nums) { - tm.put(v, tm.getOrDefault(v, 0) + 1); - } - int ans = 0, cnt = 0; - for (int v : tm.values()) { - ans += cnt * v; - ++cnt; - } - return ans; - } -} -``` - -### **TypeScript** - -```ts -function reductionOperations(nums: number[]): number { - nums.sort((a, b) => a - b); - let ans = 0; - let cnt = 0; - for (let i = 1; i < nums.length; ++i) { - if (nums[i] != nums[i - 1]) { - ++cnt; - } - ans += cnt; - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -151,24 +103,6 @@ public: }; ``` -```cpp -class Solution { -public: - int reductionOperations(vector& nums) { - map m; - for (int v : nums) ++m[v]; - int ans = 0, cnt = 0; - for (auto [_, v] : m) { - ans += cnt * v; - ++cnt; - } - return ans; - } -}; -``` - -### **Go** - ```go func reductionOperations(nums []int) int { sort.Ints(nums) @@ -183,7 +117,20 @@ func reductionOperations(nums []int) int { } ``` -### **C#** +```ts +function reductionOperations(nums: number[]): number { + nums.sort((a, b) => a - b); + let ans = 0; + let cnt = 0; + for (let i = 1; i < nums.length; ++i) { + if (nums[i] != nums[i - 1]) { + ++cnt; + } + ans += cnt; + } + return ans; +} +``` ```cs public class Solution { @@ -201,10 +148,55 @@ public class Solution { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def reductionOperations(self, nums: List[int]) -> int: + ans = cnt = 0 + for _, v in sorted(Counter(nums).items()): + ans += cnt * v + cnt += 1 + return ans ``` +```java +class Solution { + public int reductionOperations(int[] nums) { + Map tm = new TreeMap<>(); + for (int v : nums) { + tm.put(v, tm.getOrDefault(v, 0) + 1); + } + int ans = 0, cnt = 0; + for (int v : tm.values()) { + ans += cnt * v; + ++cnt; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int reductionOperations(vector& nums) { + map m; + for (int v : nums) ++m[v]; + int ans = 0, cnt = 0; + for (auto [_, v] : m) { + ans += cnt * v; + ++cnt; + } + return ans; + } +}; ``` + + diff --git a/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README.md b/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README.md index 0ebec51f0e17b..46023fb8a347a 100644 --- a/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README.md +++ b/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 我们注意到,操作 $1$ 的作用实际上是让字符串成为一个环,而操作 $2$ 是使得环中的一段长度为 $n$ 的子串变成交替二进制串。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def minFlips(self, s: str) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minFlips(String s) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go func minFlips(s string) int { n := len(s) @@ -171,8 +157,6 @@ func minFlips(s string) int { } ``` -### **TypeScript** - ```ts function minFlips(s: string): number { const n = s.length; @@ -197,10 +181,6 @@ function minFlips(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README_EN.md b/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README_EN.md index 96fad4533a5c2..f890dc47cb44e 100644 --- a/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README_EN.md +++ b/solution/1800-1899/1888.Minimum Number of Flips to Make the Binary String Alternating/README_EN.md @@ -55,9 +55,9 @@ Then, use the second operation on the third and sixth elements to make s = " ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minFlips(String s) { @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +126,6 @@ public: }; ``` -### **Go** - ```go func minFlips(s string) int { n := len(s) @@ -156,8 +150,6 @@ func minFlips(s string) int { } ``` -### **TypeScript** - ```ts function minFlips(s: string): number { const n = s.length; @@ -182,10 +174,6 @@ function minFlips(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1889.Minimum Space Wasted From Packaging/README.md b/solution/1800-1899/1889.Minimum Space Wasted From Packaging/README.md index c90009d9e3e1b..dc4e3e5ba1613 100644 --- a/solution/1800-1899/1889.Minimum Space Wasted From Packaging/README.md +++ b/solution/1800-1899/1889.Minimum Space Wasted From Packaging/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 我们首先对包裹的尺寸数组 $packages$ 进行排序。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int: @@ -107,10 +101,6 @@ class Solution: return (ans - sum(packages)) % mod ``` -### **Java** - - - ```java class Solution { public int minWastedSpace(int[] packages, int[][] boxes) { @@ -158,8 +148,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -188,8 +176,6 @@ public: }; ``` -### **Go** - ```go func minWastedSpace(packages []int, boxes [][]int) int { n := len(packages) @@ -221,8 +207,6 @@ func minWastedSpace(packages []int, boxes [][]int) int { } ``` -### **TypeScript** - ```ts function minWastedSpace(packages: number[], boxes: number[][]): number { const n = packages.length; @@ -264,10 +248,6 @@ function search(nums: number[], x: number, l: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1889.Minimum Space Wasted From Packaging/README_EN.md b/solution/1800-1899/1889.Minimum Space Wasted From Packaging/README_EN.md index fd0298fc7c576..fe024a80ada06 100644 --- a/solution/1800-1899/1889.Minimum Space Wasted From Packaging/README_EN.md +++ b/solution/1800-1899/1889.Minimum Space Wasted From Packaging/README_EN.md @@ -60,9 +60,9 @@ The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -85,8 +85,6 @@ class Solution: return (ans - sum(packages)) % mod ``` -### **Java** - ```java class Solution { public int minWastedSpace(int[] packages, int[][] boxes) { @@ -134,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +160,6 @@ public: }; ``` -### **Go** - ```go func minWastedSpace(packages []int, boxes [][]int) int { n := len(packages) @@ -197,8 +191,6 @@ func minWastedSpace(packages []int, boxes [][]int) int { } ``` -### **TypeScript** - ```ts function minWastedSpace(packages: number[], boxes: number[][]): number { const n = packages.length; @@ -240,10 +232,6 @@ function search(nums: number[], x: number, l: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1890.The Latest Login in 2020/README.md b/solution/1800-1899/1890.The Latest Login in 2020/README.md index dcf457fa31b8e..5028ef6a60100 100644 --- a/solution/1800-1899/1890.The Latest Login in 2020/README.md +++ b/solution/1800-1899/1890.The Latest Login in 2020/README.md @@ -63,18 +63,12 @@ Logins 表: ## 解法 - - -**方法一:分组求最大值** +### 方法一:分组求最大值 我们可以先筛选出 2020 年的登录记录,并且按照 `user_id` 分组,然后利用 `max` 函数求出每个用户的最大登录时间。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT user_id, MAX(time_stamp) AS last_stamp @@ -84,3 +78,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1800-1899/1890.The Latest Login in 2020/README_EN.md b/solution/1800-1899/1890.The Latest Login in 2020/README_EN.md index 8cefd0dc07e71..55055a689a8e3 100644 --- a/solution/1800-1899/1890.The Latest Login in 2020/README_EN.md +++ b/solution/1800-1899/1890.The Latest Login in 2020/README_EN.md @@ -61,14 +61,12 @@ User 14 did not login in 2020, so we do not include them in the result table. ## Solutions -**Solution 1: Group By + Max Function** +### Solution 1: Group By + Max Function We can first filter out the login records in 2020, and then group by `user_id`, and use the `max` function to calculate the maximum login time for each user. -### **SQL** - ```sql # Write your MySQL query statement below SELECT user_id, MAX(time_stamp) AS last_stamp @@ -78,3 +76,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1800-1899/1891.Cutting Ribbons/README.md b/solution/1800-1899/1891.Cutting Ribbons/README.md index fc5e7005156c8..051bf7aac0f57 100644 --- a/solution/1800-1899/1891.Cutting Ribbons/README.md +++ b/solution/1800-1899/1891.Cutting Ribbons/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们发现,如果我们能够得到长度为 $x$ 的 $k$ 根绳子,那么我们一定能够得到长度为 $x - 1$ 的 $k$ 根绳子,这存在着单调性。因此,我们可以使用二分查找的方法,找到最大的长度 $x$,使得我们能够得到长度为 $x$ 的 $k$ 根绳子。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def maxLength(self, ribbons: List[int], k: int) -> int: @@ -96,10 +90,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int maxLength(int[] ribbons, int k) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +136,6 @@ public: }; ``` -### **Go** - ```go func maxLength(ribbons []int, k int) int { left, right := 0, slices.Max(ribbons) @@ -169,35 +155,6 @@ func maxLength(ribbons []int, k int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} ribbons - * @param {number} k - * @return {number} - */ -var maxLength = function (ribbons, k) { - let left = 0; - let right = Math.max(...ribbons); - while (left < right) { - const mid = (left + right + 1) >> 1; - let cnt = 0; - for (const x of ribbons) { - cnt += Math.floor(x / mid); - } - if (cnt >= k) { - left = mid; - } else { - right = mid - 1; - } - } - return left; -}; -``` - -### **TypeScript** - ```ts function maxLength(ribbons: number[], k: number): number { let left = 0; @@ -218,8 +175,6 @@ function maxLength(ribbons: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_length(ribbons: Vec, k: i32) -> i32 { @@ -245,10 +200,31 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} ribbons + * @param {number} k + * @return {number} + */ +var maxLength = function (ribbons, k) { + let left = 0; + let right = Math.max(...ribbons); + while (left < right) { + const mid = (left + right + 1) >> 1; + let cnt = 0; + for (const x of ribbons) { + cnt += Math.floor(x / mid); + } + if (cnt >= k) { + left = mid; + } else { + right = mid - 1; + } + } + return left; +}; ``` + + diff --git a/solution/1800-1899/1891.Cutting Ribbons/README_EN.md b/solution/1800-1899/1891.Cutting Ribbons/README_EN.md index 213d8fca15fda..8a80091a5c7bb 100644 --- a/solution/1800-1899/1891.Cutting Ribbons/README_EN.md +++ b/solution/1800-1899/1891.Cutting Ribbons/README_EN.md @@ -65,7 +65,7 @@ Now you have 4 ribbons of length 4. ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search We observe that if we can obtain $k$ ropes of length $x$, then we can also obtain $k$ ropes of length $x-1$. This implies that there is a monotonicity property, and we can use binary search to find the maximum length $x$ such that we can obtain $k$ ropes of length $x$. @@ -77,8 +77,6 @@ The time complexity is $O(n \times \log M)$, where $n$ and $M$ are the number of -### **Python3** - ```python class Solution: def maxLength(self, ribbons: List[int], k: int) -> int: @@ -93,8 +91,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { public int maxLength(int[] ribbons, int k) { @@ -119,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +137,6 @@ public: }; ``` -### **Go** - ```go func maxLength(ribbons []int, k int) int { left, right := 0, slices.Max(ribbons) @@ -164,35 +156,6 @@ func maxLength(ribbons []int, k int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} ribbons - * @param {number} k - * @return {number} - */ -var maxLength = function (ribbons, k) { - let left = 0; - let right = Math.max(...ribbons); - while (left < right) { - const mid = (left + right + 1) >> 1; - let cnt = 0; - for (const x of ribbons) { - cnt += Math.floor(x / mid); - } - if (cnt >= k) { - left = mid; - } else { - right = mid - 1; - } - } - return left; -}; -``` - -### **TypeScript** - ```ts function maxLength(ribbons: number[], k: number): number { let left = 0; @@ -213,8 +176,6 @@ function maxLength(ribbons: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_length(ribbons: Vec, k: i32) -> i32 { @@ -240,10 +201,31 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} ribbons + * @param {number} k + * @return {number} + */ +var maxLength = function (ribbons, k) { + let left = 0; + let right = Math.max(...ribbons); + while (left < right) { + const mid = (left + right + 1) >> 1; + let cnt = 0; + for (const x of ribbons) { + cnt += Math.floor(x / mid); + } + if (cnt >= k) { + left = mid; + } else { + right = mid - 1; + } + } + return left; +}; ``` + + diff --git a/solution/1800-1899/1892.Page Recommendations II/README.md b/solution/1800-1899/1892.Page Recommendations II/README.md index 1fde96530f1a4..5e1095d3c6eb4 100644 --- a/solution/1800-1899/1892.Page Recommendations II/README.md +++ b/solution/1800-1899/1892.Page Recommendations II/README.md @@ -117,14 +117,10 @@ Likes 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -147,3 +143,5 @@ GROUP BY user1_id, page_id; ``` + + diff --git a/solution/1800-1899/1892.Page Recommendations II/README_EN.md b/solution/1800-1899/1892.Page Recommendations II/README_EN.md index 588dcaf819792..be2c5b8ec1230 100644 --- a/solution/1800-1899/1892.Page Recommendations II/README_EN.md +++ b/solution/1800-1899/1892.Page Recommendations II/README_EN.md @@ -115,9 +115,9 @@ You can recommend pages for users 2, 3, 4, and 5 using a similar process. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -141,3 +141,5 @@ GROUP BY user1_id, page_id; ``` + + diff --git a/solution/1800-1899/1893.Check if All the Integers in a Range Are Covered/README.md b/solution/1800-1899/1893.Check if All the Integers in a Range Are Covered/README.md index 5cf4e6bb54b2f..af04d143652fb 100644 --- a/solution/1800-1899/1893.Check if All the Integers in a Range Are Covered/README.md +++ b/solution/1800-1899/1893.Check if All the Integers in a Range Are Covered/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 我们可以使用差分数组的思想,对于每个区间 $[l, r]$,我们将 $diff[l]$ 加 $1$,将 $diff[r + 1]$ 减 $1$。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool: @@ -78,10 +72,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean isCovered(int[][] ranges, int left, int right) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func isCovered(ranges [][]int, left int, right int) bool { diff := [52]int{} @@ -148,8 +134,6 @@ func isCovered(ranges [][]int, left int, right int) bool { } ``` -### **TypeScript** - ```ts function isCovered(ranges: number[][], left: number, right: number): boolean { const diff = new Array(52).fill(0); @@ -168,8 +152,6 @@ function isCovered(ranges: number[][], left: number, right: number): boolean { } ``` -### **JavaScript** - ```js /** * @param {number[][]} ranges @@ -194,10 +176,6 @@ var isCovered = function (ranges, left, right) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1893.Check if All the Integers in a Range Are Covered/README_EN.md b/solution/1800-1899/1893.Check if All the Integers in a Range Are Covered/README_EN.md index 3b7c7075e278a..56327afacdf4f 100644 --- a/solution/1800-1899/1893.Check if All the Integers in a Range Are Covered/README_EN.md +++ b/solution/1800-1899/1893.Check if All the Integers in a Range Are Covered/README_EN.md @@ -41,12 +41,10 @@ ## Solutions -Interval update using difference array. +### Solution 1 -### **Python3** - ```python class Solution: def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool: @@ -62,8 +60,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean isCovered(int[][] ranges, int left, int right) { @@ -85,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +103,6 @@ public: }; ``` -### **Go** - ```go func isCovered(ranges [][]int, left int, right int) bool { diff := [52]int{} @@ -130,8 +122,6 @@ func isCovered(ranges [][]int, left int, right int) bool { } ``` -### **TypeScript** - ```ts function isCovered(ranges: number[][], left: number, right: number): boolean { const diff = new Array(52).fill(0); @@ -150,8 +140,6 @@ function isCovered(ranges: number[][], left: number, right: number): boolean { } ``` -### **JavaScript** - ```js /** * @param {number[][]} ranges @@ -176,10 +164,6 @@ var isCovered = function (ranges, left, right) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/README.md b/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/README.md index fc9519935e519..2ae67acb509a0 100644 --- a/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/README.md +++ b/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:求和取余 + 模拟** +### 方法一:求和取余 + 模拟 由于学生的回答是一轮一轮循环进行的,因此我们可以将所有学生需要消耗的粉笔数加起来,得到一个总数 $s$。然后我们对 $k$ 取 $s$ 的余数,即可知道最后一轮结束后剩余的粉笔数。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def chalkReplacer(self, chalk: List[int], k: int) -> int: @@ -86,10 +80,6 @@ class Solution: k -= x ``` -### **Java** - - - ```java class Solution { public int chalkReplacer(int[] chalk, int k) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func chalkReplacer(chalk []int, k int) int { s := 0 @@ -144,7 +130,21 @@ func chalkReplacer(chalk []int, k int) int { } ``` -### **Rust** +```ts +function chalkReplacer(chalk: number[], k: number): number { + let s = 0; + for (const x of chalk) { + s += x; + } + k %= s; + for (let i = 0; ; ++i) { + if (k < chalk[i]) { + return i; + } + k -= chalk[i]; + } +} +``` ```rust impl Solution { @@ -165,28 +165,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function chalkReplacer(chalk: number[], k: number): number { - let s = 0; - for (const x of chalk) { - s += x; - } - k %= s; - for (let i = 0; ; ++i) { - if (k < chalk[i]) { - return i; - } - k -= chalk[i]; - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/README_EN.md b/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/README_EN.md index 63d62b17f6ffa..ca82f00267277 100644 --- a/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/README_EN.md +++ b/solution/1800-1899/1894.Find the Student that Will Replace the Chalk/README_EN.md @@ -55,7 +55,7 @@ Student number 1 does not have enough chalk, so they will have to replace it. ## Solutions -**Solution 1: Sum and Modulo + Simulation** +### Solution 1: Sum and Modulo + Simulation Since the students' answers are conducted in rounds, we can add up the chalk needed by all students to get a total $s$. Then we take the remainder of $k$ by $s$, which can tell us the remaining number of chalks after the last round. @@ -65,8 +65,6 @@ The time complexity is $O(n)$, where $n$ is the number of students. The space co -### **Python3** - ```python class Solution: def chalkReplacer(self, chalk: List[int], k: int) -> int: @@ -78,8 +76,6 @@ class Solution: k -= x ``` -### **Java** - ```java class Solution { public int chalkReplacer(int[] chalk, int k) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +110,6 @@ public: }; ``` -### **Go** - ```go func chalkReplacer(chalk []int, k int) int { s := 0 @@ -134,7 +126,21 @@ func chalkReplacer(chalk []int, k int) int { } ``` -### **Rust** +```ts +function chalkReplacer(chalk: number[], k: number): number { + let s = 0; + for (const x of chalk) { + s += x; + } + k %= s; + for (let i = 0; ; ++i) { + if (k < chalk[i]) { + return i; + } + k -= chalk[i]; + } +} +``` ```rust impl Solution { @@ -155,28 +161,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function chalkReplacer(chalk: number[], k: number): number { - let s = 0; - for (const x of chalk) { - s += x; - } - k %= s; - for (let i = 0; ; ++i) { - if (k < chalk[i]) { - return i; - } - k -= chalk[i]; - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1895.Largest Magic Square/README.md b/solution/1800-1899/1895.Largest Magic Square/README.md index 9fcfeb20f9e58..f04ab60702b9e 100644 --- a/solution/1800-1899/1895.Largest Magic Square/README.md +++ b/solution/1800-1899/1895.Largest Magic Square/README.md @@ -42,16 +42,10 @@ ## 解法 - - -先求每行、每列的前缀和。然后从大到小枚举尺寸 k,找到第一个符合条件的 k,然后返回即可。否则最后返回 1。 +### 方法一 -### **Python3** - - - ```python class Solution: def largestMagicSquare(self, grid: List[List[int]]) -> int: @@ -100,10 +94,6 @@ class Solution: return 1 ``` -### **Java** - - - ```java class Solution { private int[][] rowsum; @@ -163,84 +153,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function largestMagicSquare(grid: number[][]): number { - let m = grid.length, - n = grid[0].length; - // 前缀和 - let rowSum = Array.from({ length: m + 1 }, (v, i) => new Array(n + 1).fill(0)), - colSum = Array.from({ length: m + 1 }, v => new Array(n + 1).fill(0)); - for (let i = 0; i < m; i++) { - rowSum[i + 1][1] = grid[i][0]; - for (let j = 1; j < n; j++) { - rowSum[i + 1][j + 1] = rowSum[i + 1][j] + grid[i][j]; - } - } - - for (let j = 0; j < n; j++) { - colSum[1][j + 1] = grid[0][j]; - for (let i = 1; i < m; i++) { - colSum[i + 1][j + 1] = colSum[i][j + 1] + grid[i][j]; - } - } - // console.log(rowSum, colSum) - // 寻找最大k - for (let k = Math.min(m, n); k > 1; k--) { - for (let i = 0; i + k - 1 < m; i++) { - for (let j = 0; j + k - 1 < n; j++) { - let x2 = i + k - 1, - y2 = j + k - 1; - if (valid(grid, rowSum, colSum, i, j, x2, y2)) { - return k; - } - } - } - } - return 1; -} - -function valid( - grid: number[][], - rowSum: number[][], - colSum: number[][], - x1: number, - y1: number, - x2: number, - y2: number, -): boolean { - let diff = rowSum[x1 + 1][y2 + 1] - rowSum[x1 + 1][y1]; - // 行 - for (let i = x1 + 1; i <= x2; i++) { - if (diff != rowSum[i + 1][y2 + 1] - rowSum[i + 1][y1]) { - return false; - } - } - // 列 - for (let j = y1; j <= y2; j++) { - if (diff != colSum[x2 + 1][j + 1] - colSum[x1][j + 1]) { - return false; - } - } - // 主队对角线 - let mainSum = diff; - for (let i = x1, j = y1; i <= x2; i++, j++) { - mainSum -= grid[i][j]; - } - if (mainSum != 0) return false; - // 副对角线 - let subSum = diff; - for (let i = x1, j = y2; i <= x2; i++, j--) { - subSum -= grid[i][j]; - } - if (subSum != 0) return false; - return true; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -289,8 +201,6 @@ public: }; ``` -### **Go** - ```go func largestMagicSquare(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -349,10 +259,80 @@ func check(grid, rowsum, colsum [][]int, x1, y1, x2, y2 int) bool { } ``` -### **...** +```ts +function largestMagicSquare(grid: number[][]): number { + let m = grid.length, + n = grid[0].length; + // 前缀和 + let rowSum = Array.from({ length: m + 1 }, (v, i) => new Array(n + 1).fill(0)), + colSum = Array.from({ length: m + 1 }, v => new Array(n + 1).fill(0)); + for (let i = 0; i < m; i++) { + rowSum[i + 1][1] = grid[i][0]; + for (let j = 1; j < n; j++) { + rowSum[i + 1][j + 1] = rowSum[i + 1][j] + grid[i][j]; + } + } -``` + for (let j = 0; j < n; j++) { + colSum[1][j + 1] = grid[0][j]; + for (let i = 1; i < m; i++) { + colSum[i + 1][j + 1] = colSum[i][j + 1] + grid[i][j]; + } + } + // console.log(rowSum, colSum) + // 寻找最大k + for (let k = Math.min(m, n); k > 1; k--) { + for (let i = 0; i + k - 1 < m; i++) { + for (let j = 0; j + k - 1 < n; j++) { + let x2 = i + k - 1, + y2 = j + k - 1; + if (valid(grid, rowSum, colSum, i, j, x2, y2)) { + return k; + } + } + } + } + return 1; +} +function valid( + grid: number[][], + rowSum: number[][], + colSum: number[][], + x1: number, + y1: number, + x2: number, + y2: number, +): boolean { + let diff = rowSum[x1 + 1][y2 + 1] - rowSum[x1 + 1][y1]; + // 行 + for (let i = x1 + 1; i <= x2; i++) { + if (diff != rowSum[i + 1][y2 + 1] - rowSum[i + 1][y1]) { + return false; + } + } + // 列 + for (let j = y1; j <= y2; j++) { + if (diff != colSum[x2 + 1][j + 1] - colSum[x1][j + 1]) { + return false; + } + } + // 主队对角线 + let mainSum = diff; + for (let i = x1, j = y1; i <= x2; i++, j++) { + mainSum -= grid[i][j]; + } + if (mainSum != 0) return false; + // 副对角线 + let subSum = diff; + for (let i = x1, j = y2; i <= x2; i++, j--) { + subSum -= grid[i][j]; + } + if (subSum != 0) return false; + return true; +} ``` + + diff --git a/solution/1800-1899/1895.Largest Magic Square/README_EN.md b/solution/1800-1899/1895.Largest Magic Square/README_EN.md index 6fe6c32c9dcf9..565e27dfba705 100644 --- a/solution/1800-1899/1895.Largest Magic Square/README_EN.md +++ b/solution/1800-1899/1895.Largest Magic Square/README_EN.md @@ -40,9 +40,9 @@ Every row sum, column sum, and diagonal sum of this magic square is equal to 12. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -92,8 +92,6 @@ class Solution: return 1 ``` -### **Java** - ```java class Solution { private int[][] rowsum; @@ -153,84 +151,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function largestMagicSquare(grid: number[][]): number { - let m = grid.length, - n = grid[0].length; - // 前缀和 - let rowSum = Array.from({ length: m + 1 }, (v, i) => new Array(n + 1).fill(0)), - colSum = Array.from({ length: m + 1 }, v => new Array(n + 1).fill(0)); - for (let i = 0; i < m; i++) { - rowSum[i + 1][1] = grid[i][0]; - for (let j = 1; j < n; j++) { - rowSum[i + 1][j + 1] = rowSum[i + 1][j] + grid[i][j]; - } - } - - for (let j = 0; j < n; j++) { - colSum[1][j + 1] = grid[0][j]; - for (let i = 1; i < m; i++) { - colSum[i + 1][j + 1] = colSum[i][j + 1] + grid[i][j]; - } - } - // console.log(rowSum, colSum) - // 寻找最大k - for (let k = Math.min(m, n); k > 1; k--) { - for (let i = 0; i + k - 1 < m; i++) { - for (let j = 0; j + k - 1 < n; j++) { - let x2 = i + k - 1, - y2 = j + k - 1; - if (valid(grid, rowSum, colSum, i, j, x2, y2)) { - return k; - } - } - } - } - return 1; -} - -function valid( - grid: number[][], - rowSum: number[][], - colSum: number[][], - x1: number, - y1: number, - x2: number, - y2: number, -): boolean { - let diff = rowSum[x1 + 1][y2 + 1] - rowSum[x1 + 1][y1]; - // 行 - for (let i = x1 + 1; i <= x2; i++) { - if (diff != rowSum[i + 1][y2 + 1] - rowSum[i + 1][y1]) { - return false; - } - } - // 列 - for (let j = y1; j <= y2; j++) { - if (diff != colSum[x2 + 1][j + 1] - colSum[x1][j + 1]) { - return false; - } - } - // 主队对角线 - let mainSum = diff; - for (let i = x1, j = y1; i <= x2; i++, j++) { - mainSum -= grid[i][j]; - } - if (mainSum != 0) return false; - // 副对角线 - let subSum = diff; - for (let i = x1, j = y2; i <= x2; i++, j--) { - subSum -= grid[i][j]; - } - if (subSum != 0) return false; - return true; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -279,8 +199,6 @@ public: }; ``` -### **Go** - ```go func largestMagicSquare(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -339,10 +257,80 @@ func check(grid, rowsum, colsum [][]int, x1, y1, x2, y2 int) bool { } ``` -### **...** +```ts +function largestMagicSquare(grid: number[][]): number { + let m = grid.length, + n = grid[0].length; + // 前缀和 + let rowSum = Array.from({ length: m + 1 }, (v, i) => new Array(n + 1).fill(0)), + colSum = Array.from({ length: m + 1 }, v => new Array(n + 1).fill(0)); + for (let i = 0; i < m; i++) { + rowSum[i + 1][1] = grid[i][0]; + for (let j = 1; j < n; j++) { + rowSum[i + 1][j + 1] = rowSum[i + 1][j] + grid[i][j]; + } + } -``` + for (let j = 0; j < n; j++) { + colSum[1][j + 1] = grid[0][j]; + for (let i = 1; i < m; i++) { + colSum[i + 1][j + 1] = colSum[i][j + 1] + grid[i][j]; + } + } + // console.log(rowSum, colSum) + // 寻找最大k + for (let k = Math.min(m, n); k > 1; k--) { + for (let i = 0; i + k - 1 < m; i++) { + for (let j = 0; j + k - 1 < n; j++) { + let x2 = i + k - 1, + y2 = j + k - 1; + if (valid(grid, rowSum, colSum, i, j, x2, y2)) { + return k; + } + } + } + } + return 1; +} +function valid( + grid: number[][], + rowSum: number[][], + colSum: number[][], + x1: number, + y1: number, + x2: number, + y2: number, +): boolean { + let diff = rowSum[x1 + 1][y2 + 1] - rowSum[x1 + 1][y1]; + // 行 + for (let i = x1 + 1; i <= x2; i++) { + if (diff != rowSum[i + 1][y2 + 1] - rowSum[i + 1][y1]) { + return false; + } + } + // 列 + for (let j = y1; j <= y2; j++) { + if (diff != colSum[x2 + 1][j + 1] - colSum[x1][j + 1]) { + return false; + } + } + // 主队对角线 + let mainSum = diff; + for (let i = x1, j = y1; i <= x2; i++, j++) { + mainSum -= grid[i][j]; + } + if (mainSum != 0) return false; + // 副对角线 + let subSum = diff; + for (let i = x1, j = y2; i <= x2; i++, j--) { + subSum -= grid[i][j]; + } + if (subSum != 0) return false; + return true; +} ``` + + diff --git a/solution/1800-1899/1896.Minimum Cost to Change the Final Value of Expression/README.md b/solution/1800-1899/1896.Minimum Cost to Change the Final Value of Expression/README.md index 109ccfa24a015..f1b6bcb06cd72 100644 --- a/solution/1800-1899/1896.Minimum Cost to Change the Final Value of Expression/README.md +++ b/solution/1800-1899/1896.Minimum Cost to Change the Final Value of Expression/README.md @@ -67,30 +67,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1800-1899/1896.Minimum Cost to Change the Final Value of Expression/README_EN.md b/solution/1800-1899/1896.Minimum Cost to Change the Final Value of Expression/README_EN.md index 02759da7fea1b..fc834e1da3659 100644 --- a/solution/1800-1899/1896.Minimum Cost to Change the Final Value of Expression/README_EN.md +++ b/solution/1800-1899/1896.Minimum Cost to Change the Final Value of Expression/README_EN.md @@ -66,24 +66,4 @@ The new expression evaluates to 0. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1800-1899/1897.Redistribute Characters to Make All Strings Equal/README.md b/solution/1800-1899/1897.Redistribute Characters to Make All Strings Equal/README.md index 77d2288b9099e..a8475b9b477be 100644 --- a/solution/1800-1899/1897.Redistribute Characters to Make All Strings Equal/README.md +++ b/solution/1800-1899/1897.Redistribute Characters to Make All Strings Equal/README.md @@ -42,14 +42,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def makeEqual(self, words: List[str]) -> bool: @@ -61,10 +57,6 @@ class Solution: return all(count % n == 0 for count in counter.values()) ``` -### **Java** - - - ```java class Solution { public boolean makeEqual(String[] words) { @@ -85,29 +77,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function makeEqual(words: string[]): boolean { - let n = words.length; - let letters = new Array(26).fill(0); - for (let word of words) { - for (let i = 0; i < word.length; ++i) { - ++letters[word.charCodeAt(i) - 97]; - } - } - - for (let i = 0; i < letters.length; ++i) { - if (letters[i] % n != 0) { - return false; - } - } - return true; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -127,8 +96,6 @@ public: }; ``` -### **Go** - ```go func makeEqual(words []string) bool { counter := [26]int{} @@ -147,10 +114,25 @@ func makeEqual(words []string) bool { } ``` -### **...** - -``` +```ts +function makeEqual(words: string[]): boolean { + let n = words.length; + let letters = new Array(26).fill(0); + for (let word of words) { + for (let i = 0; i < word.length; ++i) { + ++letters[word.charCodeAt(i) - 97]; + } + } + for (let i = 0; i < letters.length; ++i) { + if (letters[i] % n != 0) { + return false; + } + } + return true; +} ``` + + diff --git a/solution/1800-1899/1897.Redistribute Characters to Make All Strings Equal/README_EN.md b/solution/1800-1899/1897.Redistribute Characters to Make All Strings Equal/README_EN.md index fdfd0e61ee11d..2a60b361595c8 100644 --- a/solution/1800-1899/1897.Redistribute Characters to Make All Strings Equal/README_EN.md +++ b/solution/1800-1899/1897.Redistribute Characters to Make All Strings Equal/README_EN.md @@ -40,9 +40,9 @@ All the strings are now equal to "abc", so return true. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return all(count % n == 0 for count in counter.values()) ``` -### **Java** - ```java class Solution { public boolean makeEqual(String[] words) { @@ -77,29 +75,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function makeEqual(words: string[]): boolean { - let n = words.length; - let letters = new Array(26).fill(0); - for (let word of words) { - for (let i = 0; i < word.length; ++i) { - ++letters[word.charCodeAt(i) - 97]; - } - } - - for (let i = 0; i < letters.length; ++i) { - if (letters[i] % n != 0) { - return false; - } - } - return true; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -119,8 +94,6 @@ public: }; ``` -### **Go** - ```go func makeEqual(words []string) bool { counter := [26]int{} @@ -139,10 +112,25 @@ func makeEqual(words []string) bool { } ``` -### **...** - -``` +```ts +function makeEqual(words: string[]): boolean { + let n = words.length; + let letters = new Array(26).fill(0); + for (let word of words) { + for (let i = 0; i < word.length; ++i) { + ++letters[word.charCodeAt(i) - 97]; + } + } + for (let i = 0; i < letters.length; ++i) { + if (letters[i] % n != 0) { + return false; + } + } + return true; +} ``` + + diff --git a/solution/1800-1899/1898.Maximum Number of Removable Characters/README.md b/solution/1800-1899/1898.Maximum Number of Removable Characters/README.md index bf054f19c81b9..a686c66d65425 100644 --- a/solution/1800-1899/1898.Maximum Number of Removable Characters/README.md +++ b/solution/1800-1899/1898.Maximum Number of Removable Characters/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:二分查找 + 判断子序列** +### 方法一:二分查找 + 判断子序列 二分枚举整数 k,找到满足要求的最大 k 即可。 @@ -118,10 +116,6 @@ int search(int left, int right) { -### **Python3** - - - ```python class Solution: def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int: @@ -145,10 +139,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int maximumRemovals(String s, String p, int[] removable) { @@ -181,40 +171,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function maximumRemovals(s: string, p: string, removable: number[]): number { - let left = 0, - right = removable.length; - while (left < right) { - let mid = (left + right + 1) >> 1; - if (isSub(s, p, new Set(removable.slice(0, mid)))) { - left = mid; - } else { - right = mid - 1; - } - } - return left; -} - -function isSub(str: string, sub: string, idxes: Set): boolean { - let m = str.length, - n = sub.length; - let i = 0, - j = 0; - while (i < m && j < n) { - if (!idxes.has(i) && str.charAt(i) == sub.charAt(j)) { - ++j; - } - ++i; - } - return j == n; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -248,8 +204,6 @@ public: }; ``` -### **Go** - ```go func maximumRemovals(s string, p string, removable []int) int { check := func(k int) bool { @@ -280,7 +234,35 @@ func maximumRemovals(s string, p string, removable []int) int { } ``` -### **Rust** +```ts +function maximumRemovals(s: string, p: string, removable: number[]): number { + let left = 0, + right = removable.length; + while (left < right) { + let mid = (left + right + 1) >> 1; + if (isSub(s, p, new Set(removable.slice(0, mid)))) { + left = mid; + } else { + right = mid - 1; + } + } + return left; +} + +function isSub(str: string, sub: string, idxes: Set): boolean { + let m = str.length, + n = sub.length; + let i = 0, + j = 0; + while (i < m && j < n) { + if (!idxes.has(i) && str.charAt(i) == sub.charAt(j)) { + ++j; + } + ++i; + } + return j == n; +} +``` ```rust use std::collections::HashSet; @@ -324,10 +306,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1898.Maximum Number of Removable Characters/README_EN.md b/solution/1800-1899/1898.Maximum Number of Removable Characters/README_EN.md index f231aedd4bc35..b29d1f38000ea 100644 --- a/solution/1800-1899/1898.Maximum Number of Removable Characters/README_EN.md +++ b/solution/1800-1899/1898.Maximum Number of Removable Characters/README_EN.md @@ -55,50 +55,10 @@ Hence, the maximum k is 2. ## Solutions -Binary search. - -Template 1: - -```java -boolean check(int x) { -} - -int search(int left, int right) { - while (left < right) { - int mid = (left + right) >> 1; - if (check(mid)) { - right = mid; - } else { - left = mid + 1; - } - } - return left; -} -``` - -Template 2: - -```java -boolean check(int x) { -} - -int search(int left, int right) { - while (left < right) { - int mid = (left + right + 1) >> 1; - if (check(mid)) { - left = mid; - } else { - right = mid - 1; - } - } - return left; -} -``` +### Solution 1 -### **Python3** - ```python class Solution: def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int: @@ -122,8 +82,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { public int maximumRemovals(String s, String p, int[] removable) { @@ -156,40 +114,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function maximumRemovals(s: string, p: string, removable: number[]): number { - let left = 0, - right = removable.length; - while (left < right) { - let mid = (left + right + 1) >> 1; - if (isSub(s, p, new Set(removable.slice(0, mid)))) { - left = mid; - } else { - right = mid - 1; - } - } - return left; -} - -function isSub(str: string, sub: string, idxes: Set): boolean { - let m = str.length, - n = sub.length; - let i = 0, - j = 0; - while (i < m && j < n) { - if (!idxes.has(i) && str.charAt(i) == sub.charAt(j)) { - ++j; - } - ++i; - } - return j == n; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -223,8 +147,6 @@ public: }; ``` -### **Go** - ```go func maximumRemovals(s string, p string, removable []int) int { check := func(k int) bool { @@ -255,7 +177,35 @@ func maximumRemovals(s string, p string, removable []int) int { } ``` -### **Rust** +```ts +function maximumRemovals(s: string, p: string, removable: number[]): number { + let left = 0, + right = removable.length; + while (left < right) { + let mid = (left + right + 1) >> 1; + if (isSub(s, p, new Set(removable.slice(0, mid)))) { + left = mid; + } else { + right = mid - 1; + } + } + return left; +} + +function isSub(str: string, sub: string, idxes: Set): boolean { + let m = str.length, + n = sub.length; + let i = 0, + j = 0; + while (i < m && j < n) { + if (!idxes.has(i) && str.charAt(i) == sub.charAt(j)) { + ++j; + } + ++i; + } + return j == n; +} +``` ```rust use std::collections::HashSet; @@ -299,10 +249,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1899.Merge Triplets to Form Target Triplet/README.md b/solution/1800-1899/1899.Merge Triplets to Form Target Triplet/README.md index 6027c1a6468b1..a648265a928e3 100644 --- a/solution/1800-1899/1899.Merge Triplets to Form Target Triplet/README.md +++ b/solution/1800-1899/1899.Merge Triplets to Form Target Triplet/README.md @@ -71,9 +71,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们记 $target = [x, y, z]$,初始时 $d = e = f = 0$,表示当前的 $a, b, c$ 的最大值。 @@ -85,10 +83,6 @@ -### **Python3** - - - ```python class Solution: def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool: @@ -102,10 +96,6 @@ class Solution: return [d, e, f] == target ``` -### **Java** - - - ```java class Solution { public boolean mergeTriplets(int[][] triplets, int[] target) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go func mergeTriplets(triplets [][]int, target []int) bool { x, y, z := target[0], target[1], target[2] @@ -163,8 +149,6 @@ func mergeTriplets(triplets [][]int, target []int) bool { } ``` -### **TypeScript** - ```ts function mergeTriplets(triplets: number[][], target: number[]): boolean { const [x, y, z] = target; @@ -180,10 +164,6 @@ function mergeTriplets(triplets: number[][], target: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1800-1899/1899.Merge Triplets to Form Target Triplet/README_EN.md b/solution/1800-1899/1899.Merge Triplets to Form Target Triplet/README_EN.md index fb1349b708102..0a5762a79762d 100644 --- a/solution/1800-1899/1899.Merge Triplets to Form Target Triplet/README_EN.md +++ b/solution/1800-1899/1899.Merge Triplets to Form Target Triplet/README_EN.md @@ -59,9 +59,9 @@ The target triplet [5,5,5] is now an element of triplets. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return [d, e, f] == target ``` -### **Java** - ```java class Solution { public boolean mergeTriplets(int[][] triplets, int[] target) { @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +113,6 @@ public: }; ``` -### **Go** - ```go func mergeTriplets(triplets [][]int, target []int) bool { x, y, z := target[0], target[1], target[2] @@ -135,8 +129,6 @@ func mergeTriplets(triplets [][]int, target []int) bool { } ``` -### **TypeScript** - ```ts function mergeTriplets(triplets: number[][], target: number[]): boolean { const [x, y, z] = target; @@ -152,10 +144,6 @@ function mergeTriplets(triplets: number[][], target: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1900.The Earliest and Latest Rounds Where Players Compete/README.md b/solution/1900-1999/1900.The Earliest and Latest Rounds Where Players Compete/README.md index 8da82efa53981..6324ca1b5e71e 100644 --- a/solution/1900-1999/1900.The Earliest and Latest Rounds Where Players Compete/README.md +++ b/solution/1900-1999/1900.The Earliest and Latest Rounds Where Players Compete/README.md @@ -65,14 +65,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def earliestAndLatest( @@ -104,18 +100,6 @@ class Solution: return dp(firstPlayer, n - secondPlayer + 1, n) ``` -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1900.The Earliest and Latest Rounds Where Players Compete/README_EN.md b/solution/1900-1999/1900.The Earliest and Latest Rounds Where Players Compete/README_EN.md index f4dc39e4cc1ef..2edb3a622302b 100644 --- a/solution/1900-1999/1900.The Earliest and Latest Rounds Where Players Compete/README_EN.md +++ b/solution/1900-1999/1900.The Earliest and Latest Rounds Where Players Compete/README_EN.md @@ -63,9 +63,9 @@ There is no way to make them compete in any other round. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -98,16 +98,6 @@ class Solution: return dp(firstPlayer, n - secondPlayer + 1, n) ``` -### **Java** - -```java - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1901.Find a Peak Element II/README.md b/solution/1900-1999/1901.Find a Peak Element II/README.md index 18fcae226ba99..6d21a8c3f8c89 100644 --- a/solution/1900-1999/1901.Find a Peak Element II/README.md +++ b/solution/1900-1999/1901.Find a Peak Element II/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 记 $m$ 和 $n$ 分别为矩阵的行数和列数。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def findPeakGrid(self, mat: List[List[int]]) -> List[int]: @@ -96,10 +90,6 @@ class Solution: return [l, mat[l].index(max(mat[l]))] ``` -### **Java** - - - ```java class Solution { public int[] findPeakGrid(int[][] mat) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go func findPeakGrid(mat [][]int) []int { maxPos := func(arr []int) int { @@ -178,8 +164,6 @@ func findPeakGrid(mat [][]int) []int { } ``` -### **TypeScript** - ```ts function findPeakGrid(mat: number[][]): number[] { let [l, r] = [0, mat.length - 1]; @@ -196,8 +180,6 @@ function findPeakGrid(mat: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn find_peak_grid(mat: Vec>) -> Vec { @@ -224,10 +206,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1901.Find a Peak Element II/README_EN.md b/solution/1900-1999/1901.Find a Peak Element II/README_EN.md index b68f7bb90ed3e..f6e9423756547 100644 --- a/solution/1900-1999/1901.Find a Peak Element II/README_EN.md +++ b/solution/1900-1999/1901.Find a Peak Element II/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search Let $m$ and $n$ be the number of rows and columns of the matrix, respectively. @@ -70,8 +70,6 @@ The time complexity is $O(n \times \log m)$, where $m$ and $n$ are the number of -### **Python3** - ```python class Solution: def findPeakGrid(self, mat: List[List[int]]) -> List[int]: @@ -86,8 +84,6 @@ class Solution: return [l, mat[l].index(max(mat[l]))] ``` -### **Java** - ```java class Solution { public int[] findPeakGrid(int[][] mat) { @@ -117,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +133,6 @@ public: }; ``` -### **Go** - ```go func findPeakGrid(mat [][]int) []int { maxPos := func(arr []int) int { @@ -166,8 +158,6 @@ func findPeakGrid(mat [][]int) []int { } ``` -### **TypeScript** - ```ts function findPeakGrid(mat: number[][]): number[] { let [l, r] = [0, mat.length - 1]; @@ -184,8 +174,6 @@ function findPeakGrid(mat: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn find_peak_grid(mat: Vec>) -> Vec { @@ -212,10 +200,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1902.Depth of BST Given Insertion Order/README.md b/solution/1900-1999/1902.Depth of BST Given Insertion Order/README.md index 7b41a2574df40..a20c10a1aaf6a 100644 --- a/solution/1900-1999/1902.Depth of BST Given Insertion Order/README.md +++ b/solution/1900-1999/1902.Depth of BST Given Insertion Order/README.md @@ -65,33 +65,10 @@ ## 解法 - - -从二叉搜索树的原理出发,任意一个新节点加入到二叉搜索树,都是从 root 节点开始,如果比当前节点小,就往左子树遍历,如果比当前节点大,就往右子树遍历。所以,新节点的最终父节点,一定是在原树中,并且是**绝对值之差最接近的两个元素之一**。 - -这样我们就可以通过二分查找,从原二叉搜索树中,来确定 lower,higher 边界节点。 - -确定左右节点边界之后怎么办呢?很简单,只要找 lower 和 higher 中 深度较大的那个节点即可。 - -为什么呢?因为在原树中,有 root 的存在,lower 和 higher,只会在 root 的同一侧子树中,不会跨过 root 节点。 - -可以用反证法证明,如果 lower 和 higher 分别在 root 的左子树和右子树中,那么一定存在 lower < root < higher 的情况,对于 newNode 也位于 (lower,higher) 的开区间中,又 newNode.val ≠ root.val ,则区间情况会变为 (lower,root) 或者 (root,higher),与之前产生了矛盾。所以,lower 和 higher 只会在 root 的同一侧子树中。 - -那么,对于 lower 和 higher 来说,只存在两种情况: - -1. lower 在 higher 的左子树中 -2. higher 在 lower 的右子树中 - -对于情况 1,则表示 higher 存在一个左孩子节点(至少左子树中存在一个 lower 节点),所以,新节点不能成为到 higher 的左孩子,那么新节点只能成为 lower 的右孩子,而 lower 在 higher 的左子树中,则 lower.depth > higher.depth。 - -情况 2 同理可证。 +### 方法一 -### **Python3** - - - ```python from sortedcontainers import SortedDict @@ -109,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxDepthBST(int[] order) { @@ -134,10 +107,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1902.Depth of BST Given Insertion Order/README_EN.md b/solution/1900-1999/1902.Depth of BST Given Insertion Order/README_EN.md index 0952cffb636b8..b4ebd1889bb1c 100644 --- a/solution/1900-1999/1902.Depth of BST Given Insertion Order/README_EN.md +++ b/solution/1900-1999/1902.Depth of BST Given Insertion Order/README_EN.md @@ -61,9 +61,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedDict @@ -82,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxDepthBST(int[] order) { @@ -105,10 +103,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1903.Largest Odd Number in String/README.md b/solution/1900-1999/1903.Largest Odd Number in String/README.md index ddc7567d2cb0b..27956d6a5fee0 100644 --- a/solution/1900-1999/1903.Largest Odd Number in String/README.md +++ b/solution/1900-1999/1903.Largest Odd Number in String/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:逆序遍历** +### 方法一:逆序遍历 我们可以从后往前遍历字符串,找到第一个奇数,然后返回从开头到该奇数的子字符串即可。如果不存在奇数,则返回空字符串。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def largestOddNumber(self, num: str) -> str: @@ -70,10 +64,6 @@ class Solution: return '' ``` -### **Java** - - - ```java class Solution { public String largestOddNumber(String num) { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +93,6 @@ public: }; ``` -### **Go** - ```go func largestOddNumber(num string) string { for i := len(num) - 1; i >= 0; i-- { @@ -119,8 +105,6 @@ func largestOddNumber(num string) string { } ``` -### **TypeScript** - ```ts function largestOddNumber(num: string): string { for (let i = num.length - 1; ~i; --i) { @@ -132,8 +116,6 @@ function largestOddNumber(num: string): string { } ``` -### **JavaScript** - ```js /** * @param {string} num @@ -149,10 +131,6 @@ var largestOddNumber = function (num) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1903.Largest Odd Number in String/README_EN.md b/solution/1900-1999/1903.Largest Odd Number in String/README_EN.md index 37f0e4c9123ec..e2dd59f5658c5 100644 --- a/solution/1900-1999/1903.Largest Odd Number in String/README_EN.md +++ b/solution/1900-1999/1903.Largest Odd Number in String/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Reverse Traversal** +### Solution 1: Reverse Traversal We can traverse the string from the end to the beginning, find the first odd number, and then return the substring from the beginning to this odd number. If there is no odd number, return an empty string. @@ -51,8 +51,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $num$. Igno -### **Python3** - ```python class Solution: def largestOddNumber(self, num: str) -> str: @@ -62,8 +60,6 @@ class Solution: return '' ``` -### **Java** - ```java class Solution { public String largestOddNumber(String num) { @@ -78,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +89,6 @@ public: }; ``` -### **Go** - ```go func largestOddNumber(num string) string { for i := len(num) - 1; i >= 0; i-- { @@ -109,8 +101,6 @@ func largestOddNumber(num string) string { } ``` -### **TypeScript** - ```ts function largestOddNumber(num: string): string { for (let i = num.length - 1; ~i; --i) { @@ -122,8 +112,6 @@ function largestOddNumber(num: string): string { } ``` -### **JavaScript** - ```js /** * @param {string} num @@ -139,10 +127,6 @@ var largestOddNumber = function (num) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1904.The Number of Full Rounds You Have Played/README.md b/solution/1900-1999/1904.The Number of Full Rounds You Have Played/README.md index 7623a31b09997..8c2ab5ef66e37 100644 --- a/solution/1900-1999/1904.The Number of Full Rounds You Have Played/README.md +++ b/solution/1900-1999/1904.The Number of Full Rounds You Have Played/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:转换为分钟数** +### 方法一:转换为分钟数 我们可以将输入的字符串转换为分钟数 $a$ 和 $b$,如果 $a > b$,则说明跨越了午夜,需要将 $b$ 加上一天的分钟数 $1440$。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def numberOfRounds(self, loginTime: str, logoutTime: str) -> int: @@ -89,10 +83,6 @@ class Solution: return max(0, b - a) ``` -### **Java** - - - ```java class Solution { public int numberOfRounds(String loginTime, String logoutTime) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func numberOfRounds(loginTime string, logoutTime string) int { f := func(s string) int { @@ -148,8 +134,6 @@ func numberOfRounds(loginTime string, logoutTime string) int { } ``` -### **TypeScript** - ```ts function numberOfRounds(startTime: string, finishTime: string): number { const f = (s: string): number => { @@ -164,10 +148,6 @@ function numberOfRounds(startTime: string, finishTime: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1904.The Number of Full Rounds You Have Played/README_EN.md b/solution/1900-1999/1904.The Number of Full Rounds You Have Played/README_EN.md index 84e24f5c9aaf5..de181dee99770 100644 --- a/solution/1900-1999/1904.The Number of Full Rounds You Have Played/README_EN.md +++ b/solution/1900-1999/1904.The Number of Full Rounds You Have Played/README_EN.md @@ -55,7 +55,7 @@ You did not play the full round from 10:00 to 10:15 because you logged out at 10 ## Solutions -**Solution 1: Convert to Minutes** +### Solution 1: Convert to Minutes We can convert the input strings to minutes $a$ and $b$. If $a > b$, it means that it crosses midnight, so we need to add one day's minutes $1440$ to $b$. @@ -65,8 +65,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def numberOfRounds(self, loginTime: str, logoutTime: str) -> int: @@ -80,8 +78,6 @@ class Solution: return max(0, b - a) ``` -### **Java** - ```java class Solution { public int numberOfRounds(String loginTime, String logoutTime) { @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +114,6 @@ public: }; ``` -### **Go** - ```go func numberOfRounds(loginTime string, logoutTime string) int { f := func(s string) int { @@ -137,8 +129,6 @@ func numberOfRounds(loginTime string, logoutTime string) int { } ``` -### **TypeScript** - ```ts function numberOfRounds(startTime: string, finishTime: string): number { const f = (s: string): number => { @@ -153,10 +143,6 @@ function numberOfRounds(startTime: string, finishTime: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1905.Count Sub Islands/README.md b/solution/1900-1999/1905.Count Sub Islands/README.md index 17c3d49b63237..d38f8e4365b44 100644 --- a/solution/1900-1999/1905.Count Sub Islands/README.md +++ b/solution/1900-1999/1905.Count Sub Islands/README.md @@ -43,9 +43,7 @@ grid2 中标红的 1 区域是子岛屿,总共有 2 个子岛屿。 ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们可以遍历矩阵 `grid2` 中的每一个格子 $(i, j)$,如果该格子为 $1$,则从该格子开始进行深度优先搜索,将与该格子相连的所有格子的值都置为 $0$,并记录与该格子相连的所有格子中,`grid1` 中对应格子的值是否为 $1$,如果为 $1$,则说明该格子在 `grid1` 中也是一个岛屿,否则不是。最后统计 `grid2` 中子岛屿的数量即可。 @@ -53,10 +51,6 @@ grid2 中标红的 1 区域是子岛屿,总共有 2 个子岛屿。 -### **Python3** - - - ```python class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: @@ -74,32 +68,6 @@ class Solution: return sum(dfs(i, j) for i in range(m) for j in range(n) if grid2[i][j]) ``` -```python -class Solution: - def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: - def bfs(i: int, j: int) -> int: - ok = grid1[i][j] - q = deque([(i, j)]) - grid2[i][j] = 0 - while q: - i, j = q.popleft() - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n and grid2[x][y]: - q.append((x, y)) - ok = ok & grid1[x][y] - grid2[x][y] = 0 - return ok - - m, n = len(grid1), len(grid1[0]) - dirs = (-1, 0, 1, 0, -1) - return sum(bfs(i, j) for i in range(m) for j in range(n) if grid2[i][j]) -``` - -### **Java** - - - ```java class Solution { private final int[] dirs = {-1, 0, 1, 0, -1}; @@ -138,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +136,6 @@ public: }; ``` -### **Go** - ```go func countSubIslands(grid1 [][]int, grid2 [][]int) (ans int) { m, n := len(grid1), len(grid1[0]) @@ -199,8 +163,6 @@ func countSubIslands(grid1 [][]int, grid2 [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function countSubIslands(grid1: number[][], grid2: number[][]): number { const [m, n] = [grid1.length, grid1[0].length]; @@ -228,10 +190,34 @@ function countSubIslands(grid1: number[][], grid2: number[][]): number { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: + def bfs(i: int, j: int) -> int: + ok = grid1[i][j] + q = deque([(i, j)]) + grid2[i][j] = 0 + while q: + i, j = q.popleft() + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and grid2[x][y]: + q.append((x, y)) + ok = ok & grid1[x][y] + grid2[x][y] = 0 + return ok + + m, n = len(grid1), len(grid1[0]) + dirs = (-1, 0, 1, 0, -1) + return sum(bfs(i, j) for i in range(m) for j in range(n) if grid2[i][j]) ``` + + diff --git a/solution/1900-1999/1905.Count Sub Islands/README_EN.md b/solution/1900-1999/1905.Count Sub Islands/README_EN.md index 8a9213ae3eec5..930ce6f15df14 100644 --- a/solution/1900-1999/1905.Count Sub Islands/README_EN.md +++ b/solution/1900-1999/1905.Count Sub Islands/README_EN.md @@ -41,7 +41,7 @@ The 1s colored red in grid2 are those considered to be part of a sub-island. The ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We can traverse each cell $(i, j)$ in the matrix `grid2`. If the value of the cell is $1$, we start a depth-first search from this cell, set the value of all cells connected to this cell to $0$, and record whether the corresponding cell in `grid1` is also $1$ for all cells connected to this cell. If it is $1$, it means that this cell is also an island in `grid1`, otherwise it is not. Finally, we count the number of sub-islands in `grid2`. @@ -49,8 +49,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times -### **Python3** - ```python class Solution: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: @@ -68,30 +66,6 @@ class Solution: return sum(dfs(i, j) for i in range(m) for j in range(n) if grid2[i][j]) ``` -```python -class Solution: - def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: - def bfs(i: int, j: int) -> int: - ok = grid1[i][j] - q = deque([(i, j)]) - grid2[i][j] = 0 - while q: - i, j = q.popleft() - for a, b in pairwise(dirs): - x, y = i + a, j + b - if 0 <= x < m and 0 <= y < n and grid2[x][y]: - q.append((x, y)) - ok = ok & grid1[x][y] - grid2[x][y] = 0 - return ok - - m, n = len(grid1), len(grid1[0]) - dirs = (-1, 0, 1, 0, -1) - return sum(bfs(i, j) for i in range(m) for j in range(n) if grid2[i][j]) -``` - -### **Java** - ```java class Solution { private final int[] dirs = {-1, 0, 1, 0, -1}; @@ -130,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +134,6 @@ public: }; ``` -### **Go** - ```go func countSubIslands(grid1 [][]int, grid2 [][]int) (ans int) { m, n := len(grid1), len(grid1[0]) @@ -191,8 +161,6 @@ func countSubIslands(grid1 [][]int, grid2 [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function countSubIslands(grid1: number[][], grid2: number[][]): number { const [m, n] = [grid1.length, grid1[0].length]; @@ -220,10 +188,34 @@ function countSubIslands(grid1: number[][], grid2: number[][]): number { } ``` -### **...** + + +### Solution 2 -``` + + +```python +class Solution: + def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: + def bfs(i: int, j: int) -> int: + ok = grid1[i][j] + q = deque([(i, j)]) + grid2[i][j] = 0 + while q: + i, j = q.popleft() + for a, b in pairwise(dirs): + x, y = i + a, j + b + if 0 <= x < m and 0 <= y < n and grid2[x][y]: + q.append((x, y)) + ok = ok & grid1[x][y] + grid2[x][y] = 0 + return ok + m, n = len(grid1), len(grid1[0]) + dirs = (-1, 0, 1, 0, -1) + return sum(bfs(i, j) for i in range(m) for j in range(n) if grid2[i][j]) ``` + + diff --git a/solution/1900-1999/1906.Minimum Absolute Difference Queries/README.md b/solution/1900-1999/1906.Minimum Absolute Difference Queries/README.md index 4449c7ad109ee..f2863c8582c0a 100644 --- a/solution/1900-1999/1906.Minimum Absolute Difference Queries/README.md +++ b/solution/1900-1999/1906.Minimum Absolute Difference Queries/README.md @@ -64,18 +64,10 @@ ## 解法 - - -数组元素范围在 `[1,100]` 之间,对于每个区间 `[left, right]`,可以遍历整数 `1~100`,判断每个整数是否出现,求得差绝对值的最小值。 - -用前缀和 `preSum[i][j]` 表示数组前 i 个元素中包含整数 j 的个数,那么对于区间 `[left, right]`,如果 `preSum[right + 1][j] - preSum[left][j] > 0`,那么表示此区间存在整数 j。j 从 `1~100` 进行遍历,可以判断每个递增整数是否在区间中存在。 +### 方法一 -### **Python3** - - - ```python class Solution: def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]: @@ -102,10 +94,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] minDifference(int[] nums, int[][] queries) { @@ -141,42 +129,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minDifference(nums: number[], queries: number[][]): number[] { - let m = nums.length, - n = queries.length; - let max = 100; - // let max = Math.max(...nums); - let pre: number[][] = []; - pre.push(new Array(max + 1).fill(0)); - for (let i = 0; i < m; ++i) { - let num = nums[i]; - pre.push(pre[i].slice()); - pre[i + 1][num] += 1; - } - - let ans = []; - for (let [left, right] of queries) { - let last = -1; - let min = Infinity; - for (let j = 1; j < max + 1; ++j) { - if (pre[left][j] < pre[right + 1][j]) { - if (last != -1) { - min = Math.min(min, j - last); - } - last = j; - } - } - ans.push(min == Infinity ? -1 : min); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -213,8 +165,6 @@ public: }; ``` -### **Go** - ```go func minDifference(nums []int, queries [][]int) []int { m, n := len(nums), len(queries) @@ -252,10 +202,38 @@ func minDifference(nums []int, queries [][]int) []int { } ``` -### **...** - -``` +```ts +function minDifference(nums: number[], queries: number[][]): number[] { + let m = nums.length, + n = queries.length; + let max = 100; + // let max = Math.max(...nums); + let pre: number[][] = []; + pre.push(new Array(max + 1).fill(0)); + for (let i = 0; i < m; ++i) { + let num = nums[i]; + pre.push(pre[i].slice()); + pre[i + 1][num] += 1; + } + let ans = []; + for (let [left, right] of queries) { + let last = -1; + let min = Infinity; + for (let j = 1; j < max + 1; ++j) { + if (pre[left][j] < pre[right + 1][j]) { + if (last != -1) { + min = Math.min(min, j - last); + } + last = j; + } + } + ans.push(min == Infinity ? -1 : min); + } + return ans; +} ``` + + diff --git a/solution/1900-1999/1906.Minimum Absolute Difference Queries/README_EN.md b/solution/1900-1999/1906.Minimum Absolute Difference Queries/README_EN.md index c9e8f1936d3d5..a2dc92877c0ba 100644 --- a/solution/1900-1999/1906.Minimum Absolute Difference Queries/README_EN.md +++ b/solution/1900-1999/1906.Minimum Absolute Difference Queries/README_EN.md @@ -61,9 +61,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -91,8 +91,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] minDifference(int[] nums, int[][] queries) { @@ -128,42 +126,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minDifference(nums: number[], queries: number[][]): number[] { - let m = nums.length, - n = queries.length; - let max = 100; - // let max = Math.max(...nums); - let pre: number[][] = []; - pre.push(new Array(max + 1).fill(0)); - for (let i = 0; i < m; ++i) { - let num = nums[i]; - pre.push(pre[i].slice()); - pre[i + 1][num] += 1; - } - - let ans = []; - for (let [left, right] of queries) { - let last = -1; - let min = Infinity; - for (let j = 1; j < max + 1; ++j) { - if (pre[left][j] < pre[right + 1][j]) { - if (last != -1) { - min = Math.min(min, j - last); - } - last = j; - } - } - ans.push(min == Infinity ? -1 : min); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -200,8 +162,6 @@ public: }; ``` -### **Go** - ```go func minDifference(nums []int, queries [][]int) []int { m, n := len(nums), len(queries) @@ -239,10 +199,38 @@ func minDifference(nums []int, queries [][]int) []int { } ``` -### **...** - -``` +```ts +function minDifference(nums: number[], queries: number[][]): number[] { + let m = nums.length, + n = queries.length; + let max = 100; + // let max = Math.max(...nums); + let pre: number[][] = []; + pre.push(new Array(max + 1).fill(0)); + for (let i = 0; i < m; ++i) { + let num = nums[i]; + pre.push(pre[i].slice()); + pre[i + 1][num] += 1; + } + let ans = []; + for (let [left, right] of queries) { + let last = -1; + let min = Infinity; + for (let j = 1; j < max + 1; ++j) { + if (pre[left][j] < pre[right + 1][j]) { + if (last != -1) { + min = Math.min(min, j - last); + } + last = j; + } + } + ans.push(min == Infinity ? -1 : min); + } + return ans; +} ``` + + diff --git a/solution/1900-1999/1907.Count Salary Categories/README.md b/solution/1900-1999/1907.Count Salary Categories/README.md index 0635edcc6aea6..9a2f6c51e9d4d 100644 --- a/solution/1900-1999/1907.Count Salary Categories/README.md +++ b/solution/1900-1999/1907.Count Salary Categories/README.md @@ -67,22 +67,12 @@ Accounts 表: ## 解法 - - -**方法一:构建临时表 + 分组统计 + 左连接** +### 方法一:构建临时表 + 分组统计 + 左连接 我们可以先构建一个临时表,包含所有工资类别,然后再统计每个工资类别的银行账户数量。最后我们使用左连接,将临时表和统计结果表连接起来,这样就可以保证结果表中包含所有工资类别。 -**方法二:筛选 + 合并** - -我们可以分别筛选出每个工资类别的银行账户数量,然后再将结果合并起来。这里我们使用 `UNION` 来合并结果。 - -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -110,6 +100,14 @@ FROM LEFT JOIN T USING (category); ``` + + +### 方法二:筛选 + 合并 + +我们可以分别筛选出每个工资类别的银行账户数量,然后再将结果合并起来。这里我们使用 `UNION` 来合并结果。 + + + ```sql # Write your MySQL query statement below SELECT 'Low Salary' AS category, IFNULL(SUM(income < 20000), 0) AS accounts_count FROM Accounts @@ -123,3 +121,5 @@ SELECT 'High Salary' AS category, IFNULL(SUM(income > 50000), 0) AS accounts_cou ``` + + diff --git a/solution/1900-1999/1907.Count Salary Categories/README_EN.md b/solution/1900-1999/1907.Count Salary Categories/README_EN.md index c7fd32769dacc..5ea7940b99376 100644 --- a/solution/1900-1999/1907.Count Salary Categories/README_EN.md +++ b/solution/1900-1999/1907.Count Salary Categories/README_EN.md @@ -63,18 +63,12 @@ High Salary: Accounts 3, 6, and 8. ## Solutions -**Solution 1: Temporary Table + Grouping + Left Join** +### Solution 1: Temporary Table + Grouping + Left Join We can first create a temporary table containing all salary categories, and then count the number of bank accounts for each salary category. Finally, we use a left join to connect the temporary table with the result table to ensure that the result table contains all salary categories. -**Solution 2: Filtering + Merging** - -We can filter out the number of bank accounts for each salary category separately, and then merge the results. Here, we use `UNION` to merge the results. - -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -102,6 +96,14 @@ FROM LEFT JOIN T USING (category); ``` + + +### Solution 2: Filtering + Merging + +We can filter out the number of bank accounts for each salary category separately, and then merge the results. Here, we use `UNION` to merge the results. + + + ```sql # Write your MySQL query statement below SELECT 'Low Salary' AS category, IFNULL(SUM(income < 20000), 0) AS accounts_count FROM Accounts @@ -115,3 +117,5 @@ SELECT 'High Salary' AS category, IFNULL(SUM(income > 50000), 0) AS accounts_cou ``` + + diff --git a/solution/1900-1999/1908.Game of Nim/README.md b/solution/1900-1999/1908.Game of Nim/README.md index ba0837c4e325a..4240153a94554 100644 --- a/solution/1900-1999/1908.Game of Nim/README.md +++ b/solution/1900-1999/1908.Game of Nim/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们发现,一共最多有 $7$ 堆石头,每堆石头最多有 $7$ 个,那么一共有 $7^7$ 种状态,因此我们可以用一个八进制数来表示当前的状态。 @@ -83,10 +81,6 @@ -### **Python3** - - - ```python class Solution: def nimGame(self, piles: List[int]) -> bool: @@ -104,10 +98,6 @@ class Solution: return dfs(tuple(piles)) ``` -### **Java** - - - ```java class Solution { private Map memo = new HashMap<>(); @@ -154,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -194,8 +182,6 @@ public: }; ``` -### **Go** - ```go func nimGame(piles []int) bool { memo := map[int]bool{} @@ -235,8 +221,6 @@ func nimGame(piles []int) bool { } ``` -### **TypeScript** - ```ts function nimGame(piles: number[]): boolean { const p: number[] = Array(8).fill(1); @@ -274,10 +258,6 @@ function nimGame(piles: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1908.Game of Nim/README_EN.md b/solution/1900-1999/1908.Game of Nim/README_EN.md index f45a745decf9c..94dc70fae7c52 100644 --- a/solution/1900-1999/1908.Game of Nim/README_EN.md +++ b/solution/1900-1999/1908.Game of Nim/README_EN.md @@ -60,9 +60,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -81,8 +81,6 @@ class Solution: return dfs(tuple(piles)) ``` -### **Java** - ```java class Solution { private Map memo = new HashMap<>(); @@ -129,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +165,6 @@ public: }; ``` -### **Go** - ```go func nimGame(piles []int) bool { memo := map[int]bool{} @@ -210,8 +204,6 @@ func nimGame(piles []int) bool { } ``` -### **TypeScript** - ```ts function nimGame(piles: number[]): boolean { const p: number[] = Array(8).fill(1); @@ -249,10 +241,6 @@ function nimGame(piles: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1909.Remove One Element to Make the Array Strictly Increasing/README.md b/solution/1900-1999/1909.Remove One Element to Make the Array Strictly Increasing/README.md index ad201c3bd4e72..f5c4cc1d113f1 100644 --- a/solution/1900-1999/1909.Remove One Element to Make the Array Strictly Increasing/README.md +++ b/solution/1900-1999/1909.Remove One Element to Make the Array Strictly Increasing/README.md @@ -57,14 +57,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: @@ -84,10 +80,6 @@ class Solution: return check(nums, i - 1) or check(nums, i) ``` -### **Java** - - - ```java class Solution { public boolean canBeIncreasing(int[] nums) { @@ -113,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +127,6 @@ public: }; ``` -### **Go** - ```go func canBeIncreasing(nums []int) bool { i, n := 1, len(nums) @@ -163,7 +151,28 @@ func check(nums []int, i int) bool { } ``` -### **Rust** +```ts +function canBeIncreasing(nums: number[]): boolean { + const check = (p: number) => { + let prev = undefined; + for (let j = 0; j < nums.length; j++) { + if (p != j) { + if (prev !== undefined && prev >= nums[j]) { + return false; + } + prev = nums[j]; + } + } + return true; + }; + for (let i = 0; i < nums.length; i++) { + if (nums[i - 1] >= nums[i]) { + return check(i - 1) || check(i); + } + } + return true; +} +``` ```rust impl Solution { @@ -192,35 +201,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function canBeIncreasing(nums: number[]): boolean { - const check = (p: number) => { - let prev = undefined; - for (let j = 0; j < nums.length; j++) { - if (p != j) { - if (prev !== undefined && prev >= nums[j]) { - return false; - } - prev = nums[j]; - } - } - return true; - }; - for (let i = 0; i < nums.length; i++) { - if (nums[i - 1] >= nums[i]) { - return check(i - 1) || check(i); - } - } - return true; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1909.Remove One Element to Make the Array Strictly Increasing/README_EN.md b/solution/1900-1999/1909.Remove One Element to Make the Array Strictly Increasing/README_EN.md index fbd6c370b064e..59d36509bd15a 100644 --- a/solution/1900-1999/1909.Remove One Element to Make the Array Strictly Increasing/README_EN.md +++ b/solution/1900-1999/1909.Remove One Element to Make the Array Strictly Increasing/README_EN.md @@ -49,9 +49,9 @@ No resulting array is strictly increasing, so return false. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return check(nums, i - 1) or check(nums, i) ``` -### **Java** - ```java class Solution { public boolean canBeIncreasing(int[] nums) { @@ -99,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func canBeIncreasing(nums []int) bool { i, n := 1, len(nums) @@ -149,7 +143,28 @@ func check(nums []int, i int) bool { } ``` -### **Rust** +```ts +function canBeIncreasing(nums: number[]): boolean { + const check = (p: number) => { + let prev = undefined; + for (let j = 0; j < nums.length; j++) { + if (p != j) { + if (prev !== undefined && prev >= nums[j]) { + return false; + } + prev = nums[j]; + } + } + return true; + }; + for (let i = 0; i < nums.length; i++) { + if (nums[i - 1] >= nums[i]) { + return check(i - 1) || check(i); + } + } + return true; +} +``` ```rust impl Solution { @@ -178,35 +193,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function canBeIncreasing(nums: number[]): boolean { - const check = (p: number) => { - let prev = undefined; - for (let j = 0; j < nums.length; j++) { - if (p != j) { - if (prev !== undefined && prev >= nums[j]) { - return false; - } - prev = nums[j]; - } - } - return true; - }; - for (let i = 0; i < nums.length; i++) { - if (nums[i - 1] >= nums[i]) { - return check(i - 1) || check(i); - } - } - return true; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1910.Remove All Occurrences of a Substring/README.md b/solution/1900-1999/1910.Remove All Occurrences of a Substring/README.md index be2091ab06ea1..2f55b920608cf 100644 --- a/solution/1900-1999/1910.Remove All Occurrences of a Substring/README.md +++ b/solution/1900-1999/1910.Remove All Occurrences of a Substring/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:暴力替换** +### 方法一:暴力替换 我们循环判断 $s$ 中是否存在字符串 $part$,是则进行一次替换,继续循环此操作,直至 $s$ 中不存在字符串 $part$,返回此时的 $s$ 作为答案字符串。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def removeOccurrences(self, s: str, part: str) -> str: @@ -75,10 +69,6 @@ class Solution: return s ``` -### **Java** - - - ```java class Solution { public String removeOccurrences(String s, String part) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +93,6 @@ public: }; ``` -### **Go** - ```go func removeOccurrences(s string, part string) string { for strings.Contains(s, part) { @@ -116,8 +102,6 @@ func removeOccurrences(s string, part string) string { } ``` -### **TypeScript** - ```ts function removeOccurrences(s: string, part: string): string { while (s.includes(part)) { @@ -127,10 +111,6 @@ function removeOccurrences(s: string, part: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1910.Remove All Occurrences of a Substring/README_EN.md b/solution/1900-1999/1910.Remove All Occurrences of a Substring/README_EN.md index 8eacac0d147ba..82c68dd109467 100644 --- a/solution/1900-1999/1910.Remove All Occurrences of a Substring/README_EN.md +++ b/solution/1900-1999/1910.Remove All Occurrences of a Substring/README_EN.md @@ -51,9 +51,9 @@ Now s has no occurrences of "xy". ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return s ``` -### **Java** - ```java class Solution { public String removeOccurrences(String s, String part) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +87,6 @@ public: }; ``` -### **Go** - ```go func removeOccurrences(s string, part string) string { for strings.Contains(s, part) { @@ -102,8 +96,6 @@ func removeOccurrences(s string, part string) string { } ``` -### **TypeScript** - ```ts function removeOccurrences(s: string, part: string): string { while (s.includes(part)) { @@ -113,10 +105,6 @@ function removeOccurrences(s: string, part: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/README.md b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/README.md index 73a7e1f1a4d62..3ab390c95efc2 100644 --- a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/README.md +++ b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示从前 $i$ 个元素中选出的子序列,且最后一个元素为奇数下标时的最大交替和,定义 $g[i]$ 表示从前 $i$ 个元素中选出的子序列,且最后一个元素为偶数下标时的最大交替和。初始时 $f[0] = g[0] = 0$。答案为 $max(f[n], g[n])$。 @@ -82,10 +80,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxAlternatingSum(self, nums: List[int]) -> int: @@ -98,19 +92,6 @@ class Solution: return max(f[n], g[n]) ``` -```python -class Solution: - def maxAlternatingSum(self, nums: List[int]) -> int: - f = g = 0 - for x in nums: - f, g = max(g - x, f), max(f + x, g) - return max(f, g) -``` - -### **Java** - - - ```java class Solution { public long maxAlternatingSum(int[] nums) { @@ -126,23 +107,6 @@ class Solution { } ``` -```java -class Solution { - public long maxAlternatingSum(int[] nums) { - long f = 0, g = 0; - for (int x : nums) { - long ff = Math.max(g - x, f); - long gg = Math.max(f + x, g); - f = ff; - g = gg; - } - return Math.max(f, g); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -158,22 +122,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long maxAlternatingSum(vector& nums) { - long long f = 0, g = 0; - for (int& x : nums) { - long ff = max(g - x, f), gg = max(f + x, g); - f = ff, g = gg; - } - return max(f, g); - } -}; -``` - -### **Go** - ```go func maxAlternatingSum(nums []int) int64 { n := len(nums) @@ -188,18 +136,6 @@ func maxAlternatingSum(nums []int) int64 { } ``` -```go -func maxAlternatingSum(nums []int) int64 { - var f, g int - for _, x := range nums { - f, g = max(g-x, f), max(f+x, g) - } - return int64(max(f, g)) -} -``` - -### **TypeScript** - ```ts function maxAlternatingSum(nums: number[]): number { const n = nums.length; @@ -213,6 +149,60 @@ function maxAlternatingSum(nums: number[]): number { } ``` + + +### 方法二 + + + +```python +class Solution: + def maxAlternatingSum(self, nums: List[int]) -> int: + f = g = 0 + for x in nums: + f, g = max(g - x, f), max(f + x, g) + return max(f, g) +``` + +```java +class Solution { + public long maxAlternatingSum(int[] nums) { + long f = 0, g = 0; + for (int x : nums) { + long ff = Math.max(g - x, f); + long gg = Math.max(f + x, g); + f = ff; + g = gg; + } + return Math.max(f, g); + } +} +``` + +```cpp +class Solution { +public: + long long maxAlternatingSum(vector& nums) { + long long f = 0, g = 0; + for (int& x : nums) { + long ff = max(g - x, f), gg = max(f + x, g); + f = ff, g = gg; + } + return max(f, g); + } +}; +``` + +```go +func maxAlternatingSum(nums []int) int64 { + var f, g int + for _, x := range nums { + f, g = max(g-x, f), max(f+x, g) + } + return int64(max(f, g)) +} +``` + ```ts function maxAlternatingSum(nums: number[]): number { let [f, g] = [0, 0]; @@ -223,10 +213,6 @@ function maxAlternatingSum(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/README_EN.md b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/README_EN.md index 7cb837f26843e..8403a6fcb74e6 100644 --- a/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/README_EN.md +++ b/solution/1900-1999/1911.Maximum Alternating Subsequence Sum/README_EN.md @@ -52,9 +52,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,17 +68,6 @@ class Solution: return max(f[n], g[n]) ``` -```python -class Solution: - def maxAlternatingSum(self, nums: List[int]) -> int: - f = g = 0 - for x in nums: - f, g = max(g - x, f), max(f + x, g) - return max(f, g) -``` - -### **Java** - ```java class Solution { public long maxAlternatingSum(int[] nums) { @@ -94,23 +83,6 @@ class Solution { } ``` -```java -class Solution { - public long maxAlternatingSum(int[] nums) { - long f = 0, g = 0; - for (int x : nums) { - long ff = Math.max(g - x, f); - long gg = Math.max(f + x, g); - f = ff; - g = gg; - } - return Math.max(f, g); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -126,22 +98,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long maxAlternatingSum(vector& nums) { - long long f = 0, g = 0; - for (int& x : nums) { - long ff = max(g - x, f), gg = max(f + x, g); - f = ff, g = gg; - } - return max(f, g); - } -}; -``` - -### **Go** - ```go func maxAlternatingSum(nums []int) int64 { n := len(nums) @@ -156,18 +112,6 @@ func maxAlternatingSum(nums []int) int64 { } ``` -```go -func maxAlternatingSum(nums []int) int64 { - var f, g int - for _, x := range nums { - f, g = max(g-x, f), max(f+x, g) - } - return int64(max(f, g)) -} -``` - -### **TypeScript** - ```ts function maxAlternatingSum(nums: number[]): number { const n = nums.length; @@ -181,6 +125,60 @@ function maxAlternatingSum(nums: number[]): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def maxAlternatingSum(self, nums: List[int]) -> int: + f = g = 0 + for x in nums: + f, g = max(g - x, f), max(f + x, g) + return max(f, g) +``` + +```java +class Solution { + public long maxAlternatingSum(int[] nums) { + long f = 0, g = 0; + for (int x : nums) { + long ff = Math.max(g - x, f); + long gg = Math.max(f + x, g); + f = ff; + g = gg; + } + return Math.max(f, g); + } +} +``` + +```cpp +class Solution { +public: + long long maxAlternatingSum(vector& nums) { + long long f = 0, g = 0; + for (int& x : nums) { + long ff = max(g - x, f), gg = max(f + x, g); + f = ff, g = gg; + } + return max(f, g); + } +}; +``` + +```go +func maxAlternatingSum(nums []int) int64 { + var f, g int + for _, x := range nums { + f, g = max(g-x, f), max(f+x, g) + } + return int64(max(f, g)) +} +``` + ```ts function maxAlternatingSum(nums: number[]): number { let [f, g] = [0, 0]; @@ -191,10 +189,6 @@ function maxAlternatingSum(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1912.Design Movie Rental System/README.md b/solution/1900-1999/1912.Design Movie Rental System/README.md index 569ffe773e617..7052e5e5aec08 100644 --- a/solution/1900-1999/1912.Design Movie Rental System/README.md +++ b/solution/1900-1999/1912.Design Movie Rental System/README.md @@ -67,14 +67,10 @@ movieRentingSystem.search(2); // 返回 [0, 1] 。商店 0 和 1 有未借出 ## 解法 - +### 方法一 -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -113,18 +109,6 @@ class MovieRentingSystem: # param_4 = obj.report() ``` -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1912.Design Movie Rental System/README_EN.md b/solution/1900-1999/1912.Design Movie Rental System/README_EN.md index 8276a456cdb36..de59d90cae6c4 100644 --- a/solution/1900-1999/1912.Design Movie Rental System/README_EN.md +++ b/solution/1900-1999/1912.Design Movie Rental System/README_EN.md @@ -63,9 +63,9 @@ movieRentingSystem.search(2); // return [0, 1]. Movies of ID 2 are unrented at ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedList @@ -105,16 +105,6 @@ class MovieRentingSystem: # param_4 = obj.report() ``` -### **Java** - -```java - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1913.Maximum Product Difference Between Two Pairs/README.md b/solution/1900-1999/1913.Maximum Product Difference Between Two Pairs/README.md index c09a88cd52e3b..f39b4263ab64d 100644 --- a/solution/1900-1999/1913.Maximum Product Difference Between Two Pairs/README.md +++ b/solution/1900-1999/1913.Maximum Product Difference Between Two Pairs/README.md @@ -45,14 +45,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxProductDifference(self, nums: List[int]) -> int: @@ -60,10 +56,6 @@ class Solution: return nums[-1] * nums[-2] - nums[0] * nums[1] ``` -### **Java** - - - ```java class Solution { public int maxProductDifference(int[] nums) { @@ -74,23 +66,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var maxProductDifference = function (nums) { - nums.sort((a, b) => a - b); - let n = nums.length; - let ans = nums[n - 1] * nums[n - 2] - nums[0] * nums[1]; - return ans; -}; -``` - -### **C++** - ```cpp class Solution { public: @@ -102,8 +77,6 @@ public: }; ``` -### **Go** - ```go func maxProductDifference(nums []int) int { sort.Ints(nums) @@ -112,10 +85,19 @@ func maxProductDifference(nums []int) int { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums + * @return {number} + */ +var maxProductDifference = function (nums) { + nums.sort((a, b) => a - b); + let n = nums.length; + let ans = nums[n - 1] * nums[n - 2] - nums[0] * nums[1]; + return ans; +}; ``` + + diff --git a/solution/1900-1999/1913.Maximum Product Difference Between Two Pairs/README_EN.md b/solution/1900-1999/1913.Maximum Product Difference Between Two Pairs/README_EN.md index d7a9b5c4c2bd5..f14a01df8a51b 100644 --- a/solution/1900-1999/1913.Maximum Product Difference Between Two Pairs/README_EN.md +++ b/solution/1900-1999/1913.Maximum Product Difference Between Two Pairs/README_EN.md @@ -43,9 +43,9 @@ The product difference is (9 * 8) - (2 * 4) = 64. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return nums[-1] * nums[-2] - nums[0] * nums[1] ``` -### **Java** - ```java class Solution { public int maxProductDifference(int[] nums) { @@ -66,23 +64,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var maxProductDifference = function (nums) { - nums.sort((a, b) => a - b); - let n = nums.length; - let ans = nums[n - 1] * nums[n - 2] - nums[0] * nums[1]; - return ans; -}; -``` - -### **C++** - ```cpp class Solution { public: @@ -94,8 +75,6 @@ public: }; ``` -### **Go** - ```go func maxProductDifference(nums []int) int { sort.Ints(nums) @@ -104,10 +83,19 @@ func maxProductDifference(nums []int) int { } ``` -### **...** - -``` - +```js +/** + * @param {number[]} nums + * @return {number} + */ +var maxProductDifference = function (nums) { + nums.sort((a, b) => a - b); + let n = nums.length; + let ans = nums[n - 1] * nums[n - 2] - nums[0] * nums[1]; + return ans; +}; ``` + + diff --git a/solution/1900-1999/1914.Cyclically Rotating a Grid/README.md b/solution/1900-1999/1914.Cyclically Rotating a Grid/README.md index 17f9a90e04c6d..78a07993d9fad 100644 --- a/solution/1900-1999/1914.Cyclically Rotating a Grid/README.md +++ b/solution/1900-1999/1914.Cyclically Rotating a Grid/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:逐层模拟** +### 方法一:逐层模拟 我们先计算得到矩阵的层数 $p$,然后从外到内逐层模拟循环轮转的过程。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: @@ -100,10 +94,6 @@ class Solution: return grid ``` -### **Java** - - - ```java class Solution { private int m; @@ -155,8 +145,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -202,8 +190,6 @@ public: }; ``` -### **Go** - ```go func rotateGrid(grid [][]int, k int) [][]int { m, n := len(grid), len(grid[0]) @@ -252,8 +238,6 @@ func rotateGrid(grid [][]int, k int) [][]int { } ``` -### **TypeScript** - ```ts function rotateGrid(grid: number[][], k: number): number[][] { const m = grid.length; @@ -297,10 +281,6 @@ function rotateGrid(grid: number[][], k: number): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1914.Cyclically Rotating a Grid/README_EN.md b/solution/1900-1999/1914.Cyclically Rotating a Grid/README_EN.md index 61052abcd7af1..8213aa175916f 100644 --- a/solution/1900-1999/1914.Cyclically Rotating a Grid/README_EN.md +++ b/solution/1900-1999/1914.Cyclically Rotating a Grid/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -87,8 +87,6 @@ class Solution: return grid ``` -### **Java** - ```java class Solution { private int m; @@ -140,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -187,8 +183,6 @@ public: }; ``` -### **Go** - ```go func rotateGrid(grid [][]int, k int) [][]int { m, n := len(grid), len(grid[0]) @@ -237,8 +231,6 @@ func rotateGrid(grid [][]int, k int) [][]int { } ``` -### **TypeScript** - ```ts function rotateGrid(grid: number[][], k: number): number[][] { const m = grid.length; @@ -282,10 +274,6 @@ function rotateGrid(grid: number[][], k: number): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1915.Number of Wonderful Substrings/README.md b/solution/1900-1999/1915.Number of Wonderful Substrings/README.md index 9554af13a42b0..288595636700f 100644 --- a/solution/1900-1999/1915.Number of Wonderful Substrings/README.md +++ b/solution/1900-1999/1915.Number of Wonderful Substrings/README.md @@ -68,9 +68,7 @@ ## 解法 - - -**方法一:前缀异或 + 计数** +### 方法一:前缀异或 + 计数 由于字符串中只包含 $10$ 个小写字母,因此可以用一个长度为 $10$ 的二进制数表示字符串中每个字母的奇偶性,其中第 $i$ 位为 $1$ 表示第 $i$ 个字母出现了奇数次,为 $0$ 表示第 $i$ 个字母出现了偶数次。 @@ -86,10 +84,6 @@ -### **Python3** - - - ```python class Solution: def wonderfulSubstrings(self, word: str) -> int: @@ -104,10 +98,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long wonderfulSubstrings(String word) { @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func wonderfulSubstrings(word string) (ans int64) { cnt := [1024]int{1} @@ -168,8 +154,6 @@ func wonderfulSubstrings(word string) (ans int64) { } ``` -### **TypeScript** - ```ts function wonderfulSubstrings(word: string): number { const cnt: number[] = new Array(1 << 10).fill(0); @@ -188,8 +172,6 @@ function wonderfulSubstrings(word: string): number { } ``` -### **JavaScript** - ```js /** * @param {string} word @@ -212,10 +194,6 @@ var wonderfulSubstrings = function (word) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1915.Number of Wonderful Substrings/README_EN.md b/solution/1900-1999/1915.Number of Wonderful Substrings/README_EN.md index a8ff2ba63c46e..2999d1ba69d87 100644 --- a/solution/1900-1999/1915.Number of Wonderful Substrings/README_EN.md +++ b/solution/1900-1999/1915.Number of Wonderful Substrings/README_EN.md @@ -64,9 +64,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long wonderfulSubstrings(String word) { @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +122,6 @@ public: }; ``` -### **Go** - ```go func wonderfulSubstrings(word string) (ans int64) { cnt := [1024]int{1} @@ -144,8 +138,6 @@ func wonderfulSubstrings(word string) (ans int64) { } ``` -### **TypeScript** - ```ts function wonderfulSubstrings(word: string): number { const cnt: number[] = new Array(1 << 10).fill(0); @@ -164,8 +156,6 @@ function wonderfulSubstrings(word: string): number { } ``` -### **JavaScript** - ```js /** * @param {string} word @@ -188,10 +178,6 @@ var wonderfulSubstrings = function (word) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README.md b/solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README.md index ef36c1a254651..996a8c7cbcd1f 100644 --- a/solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README.md +++ b/solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README.md @@ -52,30 +52,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README_EN.md b/solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README_EN.md index 5aaa6a15544fa..41f30ae95b127 100644 --- a/solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README_EN.md +++ b/solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README_EN.md @@ -48,24 +48,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1917.Leetcodify Friends Recommendations/README.md b/solution/1900-1999/1917.Leetcodify Friends Recommendations/README.md index 0527606ed07a6..75ecf9d8495a0 100644 --- a/solution/1900-1999/1917.Leetcodify Friends Recommendations/README.md +++ b/solution/1900-1999/1917.Leetcodify Friends Recommendations/README.md @@ -103,14 +103,10 @@ Friendship 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -137,3 +133,5 @@ HAVING COUNT(DISTINCT l1.song_id) >= 3; ``` + + diff --git a/solution/1900-1999/1917.Leetcodify Friends Recommendations/README_EN.md b/solution/1900-1999/1917.Leetcodify Friends Recommendations/README_EN.md index d081afc71cce1..c589bc516743f 100644 --- a/solution/1900-1999/1917.Leetcodify Friends Recommendations/README_EN.md +++ b/solution/1900-1999/1917.Leetcodify Friends Recommendations/README_EN.md @@ -100,9 +100,9 @@ Similarly, we can see that users 2 and 3 listened to songs 10, 11, and 12 on the ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -130,3 +130,5 @@ HAVING COUNT(DISTINCT l1.song_id) >= 3; ``` + + diff --git a/solution/1900-1999/1918.Kth Smallest Subarray Sum/README.md b/solution/1900-1999/1918.Kth Smallest Subarray Sum/README.md index 9cbe6c81ce007..ae89e569bd70b 100644 --- a/solution/1900-1999/1918.Kth Smallest Subarray Sum/README.md +++ b/solution/1900-1999/1918.Kth Smallest Subarray Sum/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:二分查找 + 双指针** +### 方法一:二分查找 + 双指针 我们注意到,题目中数组元素均为正整数,子数组的和 $s$ 越大,那么数组中子数组和小于等于 $s$ 的个数就越多。这存在一个单调性,因此我们可以考虑使用使用二分查找的方法来求解。 @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def kthSmallestSubarraySum(self, nums: List[int], k: int) -> int: @@ -103,10 +97,6 @@ class Solution: return l + bisect_left(range(l, r + 1), True, key=f) ``` -### **Java** - - - ```java class Solution { public int kthSmallestSubarraySum(int[] nums, int k) { @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +164,6 @@ public: }; ``` -### **Go** - ```go func kthSmallestSubarraySum(nums []int, k int) int { l, r := 1<<30, 0 @@ -209,10 +195,6 @@ func kthSmallestSubarraySum(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1918.Kth Smallest Subarray Sum/README_EN.md b/solution/1900-1999/1918.Kth Smallest Subarray Sum/README_EN.md index 2a54424a6ea18..037d9b0fe2bd4 100644 --- a/solution/1900-1999/1918.Kth Smallest Subarray Sum/README_EN.md +++ b/solution/1900-1999/1918.Kth Smallest Subarray Sum/README_EN.md @@ -55,9 +55,9 @@ Ordering the sums from smallest to largest gives 3, 3, 5, 5, 6, 8, 10, 11 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return l + bisect_left(range(l, r + 1), True, key=f) ``` -### **Java** - ```java class Solution { public int kthSmallestSubarraySum(int[] nums, int k) { @@ -113,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +144,6 @@ public: }; ``` -### **Go** - ```go func kthSmallestSubarraySum(nums []int, k int) int { l, r := 1<<30, 0 @@ -181,10 +175,6 @@ func kthSmallestSubarraySum(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1919.Leetcodify Similar Friends/README.md b/solution/1900-1999/1919.Leetcodify Similar Friends/README.md index 31e08744d7cac..413adf03a8675 100644 --- a/solution/1900-1999/1919.Leetcodify Similar Friends/README.md +++ b/solution/1900-1999/1919.Leetcodify Similar Friends/README.md @@ -97,14 +97,10 @@ Friendship table: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT DISTINCT user1_id, user2_id @@ -118,3 +114,5 @@ HAVING COUNT(DISTINCT l1.song_id) >= 3; ``` + + diff --git a/solution/1900-1999/1919.Leetcodify Similar Friends/README_EN.md b/solution/1900-1999/1919.Leetcodify Similar Friends/README_EN.md index ba443c828cd97..b044295aa5967 100644 --- a/solution/1900-1999/1919.Leetcodify Similar Friends/README_EN.md +++ b/solution/1900-1999/1919.Leetcodify Similar Friends/README_EN.md @@ -95,9 +95,9 @@ Users 2 and 5 are friends and listened to songs 10, 11, and 12, but they did not ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -112,3 +112,5 @@ HAVING COUNT(DISTINCT l1.song_id) >= 3; ``` + + diff --git a/solution/1900-1999/1920.Build Array from Permutation/README.md b/solution/1900-1999/1920.Build Array from Permutation/README.md index 55f85bae913eb..a09b21c7dff8a 100644 --- a/solution/1900-1999/1920.Build Array from Permutation/README.md +++ b/solution/1900-1999/1920.Build Array from Permutation/README.md @@ -42,24 +42,16 @@ ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]] ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def buildArray(self, nums: List[int]) -> List[int]: return [nums[num] for num in nums] ``` -### **Java** - - - ```java class Solution { public int[] buildArray(int[] nums) { @@ -72,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +77,6 @@ public: }; ``` -### **Go** - ```go func buildArray(nums []int) []int { ans := make([]int, len(nums)) @@ -99,32 +87,12 @@ func buildArray(nums []int) []int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var buildArray = function (nums) { - let ans = []; - for (let i = 0; i < nums.length; ++i) { - ans[i] = nums[nums[i]]; - } - return ans; -}; -``` - -### **TypeScript** - ```ts function buildArray(nums: number[]): number[] { return nums.map(v => nums[v]); } ``` -### **Rust** - ```rust impl Solution { pub fn build_array(nums: Vec) -> Vec { @@ -135,7 +103,19 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var buildArray = function (nums) { + let ans = []; + for (let i = 0; i < nums.length; ++i) { + ans[i] = nums[nums[i]]; + } + return ans; +}; +``` ```c /** @@ -151,10 +131,6 @@ int* buildArray(int* nums, int numsSize, int* returnSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1920.Build Array from Permutation/README_EN.md b/solution/1900-1999/1920.Build Array from Permutation/README_EN.md index 367932c7fddec..1a554c707eee9 100644 --- a/solution/1900-1999/1920.Build Array from Permutation/README_EN.md +++ b/solution/1900-1999/1920.Build Array from Permutation/README_EN.md @@ -43,9 +43,9 @@ ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]] ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return [nums[num] for num in nums] ``` -### **Java** - ```java class Solution { public int[] buildArray(int[] nums) { @@ -67,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -82,8 +78,6 @@ public: }; ``` -### **Go** - ```go func buildArray(nums []int) []int { ans := make([]int, len(nums)) @@ -94,32 +88,12 @@ func buildArray(nums []int) []int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var buildArray = function (nums) { - let ans = []; - for (let i = 0; i < nums.length; ++i) { - ans[i] = nums[nums[i]]; - } - return ans; -}; -``` - -### **TypeScript** - ```ts function buildArray(nums: number[]): number[] { return nums.map(v => nums[v]); } ``` -### **Rust** - ```rust impl Solution { pub fn build_array(nums: Vec) -> Vec { @@ -130,7 +104,19 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var buildArray = function (nums) { + let ans = []; + for (let i = 0; i < nums.length; ++i) { + ans[i] = nums[nums[i]]; + } + return ans; +}; +``` ```c /** @@ -146,10 +132,6 @@ int* buildArray(int* nums, int numsSize, int* returnSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1921.Eliminate Maximum Number of Monsters/README.md b/solution/1900-1999/1921.Eliminate Maximum Number of Monsters/README.md index 1d3e664ebfaf1..c5941e77e4aff 100644 --- a/solution/1900-1999/1921.Eliminate Maximum Number of Monsters/README.md +++ b/solution/1900-1999/1921.Eliminate Maximum Number of Monsters/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:排序 + 贪心** +### 方法一:排序 + 贪心 我们用 $times$ 数组记录每个怪物最晚可被消灭的时间。对于第 $i$ 个怪物,最晚可被消灭的时间满足: @@ -81,10 +79,6 @@ $$times[i] = \lfloor \frac{dist[i]-1}{speed[i]} \rfloor$$ -### **Python3** - - - ```python class Solution: def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: @@ -95,10 +89,6 @@ class Solution: return len(times) ``` -### **Java** - - - ```java class Solution { public int eliminateMaximum(int[] dist, int[] speed) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func eliminateMaximum(dist []int, speed []int) int { n := len(dist) @@ -159,8 +145,6 @@ func eliminateMaximum(dist []int, speed []int) int { } ``` -### **TypeScript** - ```ts function eliminateMaximum(dist: number[], speed: number[]): number { const n = dist.length; @@ -178,8 +162,6 @@ function eliminateMaximum(dist: number[], speed: number[]): number { } ``` -### **JavaScript** - ```js /** * @param {number[]} dist @@ -201,8 +183,6 @@ var eliminateMaximum = function (dist, speed) { }; ``` -### **C#** - ```cs public class Solution { public int EliminateMaximum(int[] dist, int[] speed) { @@ -222,10 +202,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1921.Eliminate Maximum Number of Monsters/README_EN.md b/solution/1900-1999/1921.Eliminate Maximum Number of Monsters/README_EN.md index 6a1f55a2a142f..4c51a83c3ca08 100644 --- a/solution/1900-1999/1921.Eliminate Maximum Number of Monsters/README_EN.md +++ b/solution/1900-1999/1921.Eliminate Maximum Number of Monsters/README_EN.md @@ -59,9 +59,9 @@ You can only eliminate 1 monster. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return len(times) ``` -### **Java** - ```java class Solution { public int eliminateMaximum(int[] dist, int[] speed) { @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +112,6 @@ public: }; ``` -### **Go** - ```go func eliminateMaximum(dist []int, speed []int) int { n := len(dist) @@ -135,8 +129,6 @@ func eliminateMaximum(dist []int, speed []int) int { } ``` -### **TypeScript** - ```ts function eliminateMaximum(dist: number[], speed: number[]): number { const n = dist.length; @@ -154,8 +146,6 @@ function eliminateMaximum(dist: number[], speed: number[]): number { } ``` -### **JavaScript** - ```js /** * @param {number[]} dist @@ -177,8 +167,6 @@ var eliminateMaximum = function (dist, speed) { }; ``` -### **C#** - ```cs public class Solution { public int EliminateMaximum(int[] dist, int[] speed) { @@ -198,10 +186,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1922.Count Good Numbers/README.md b/solution/1900-1999/1922.Count Good Numbers/README.md index c45bcb68936c2..d33b771d6508c 100644 --- a/solution/1900-1999/1922.Count Good Numbers/README.md +++ b/solution/1900-1999/1922.Count Good Numbers/README.md @@ -50,14 +50,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def countGoodNumbers(self, n: int) -> int: @@ -75,10 +71,6 @@ class Solution: return myPow(5, (n + 1) >> 1) * myPow(4, n >> 1) % mod ``` -### **Java** - - - ```java class Solution { private int mod = 1000000007; @@ -101,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp int MOD = 1000000007; @@ -127,8 +117,6 @@ private: }; ``` -### **Go** - ```go const mod int64 = 1e9 + 7 @@ -149,10 +137,6 @@ func myPow(x, n int64) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1922.Count Good Numbers/README_EN.md b/solution/1900-1999/1922.Count Good Numbers/README_EN.md index 0abf8631fda1c..2fe24475ee4cb 100644 --- a/solution/1900-1999/1922.Count Good Numbers/README_EN.md +++ b/solution/1900-1999/1922.Count Good Numbers/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return myPow(5, (n + 1) >> 1) * myPow(4, n >> 1) % mod ``` -### **Java** - ```java class Solution { private int mod = 1000000007; @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp int MOD = 1000000007; @@ -117,8 +113,6 @@ private: }; ``` -### **Go** - ```go const mod int64 = 1e9 + 7 @@ -139,10 +133,6 @@ func myPow(x, n int64) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1923.Longest Common Subpath/README.md b/solution/1900-1999/1923.Longest Common Subpath/README.md index 69c581dd07d10..b875a071b710e 100644 --- a/solution/1900-1999/1923.Longest Common Subpath/README.md +++ b/solution/1900-1999/1923.Longest Common Subpath/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:字符串哈希** +### 方法一:字符串哈希 **字符串哈希**是把一个任意长度的字符串映射成一个非负整数,并且其冲突的概率几乎为 0。字符串哈希用于计算字符串哈希值,快速判断两个字符串是否相等。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def longestCommonSubpath(self, n: int, paths: List[List[int]]) -> int: @@ -115,10 +109,6 @@ class Solution: return l ``` -### **Java** - - - ```java class Solution { int N = 100010; @@ -176,10 +166,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1923.Longest Common Subpath/README_EN.md b/solution/1900-1999/1923.Longest Common Subpath/README_EN.md index f0bedc180015c..187122354cdb5 100644 --- a/solution/1900-1999/1923.Longest Common Subpath/README_EN.md +++ b/solution/1900-1999/1923.Longest Common Subpath/README_EN.md @@ -53,9 +53,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -97,8 +97,6 @@ class Solution: return l ``` -### **Java** - ```java class Solution { int N = 100010; @@ -156,10 +154,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1924.Erect the Fence II/README.md b/solution/1900-1999/1924.Erect the Fence II/README.md index 97eaf22cd56e4..308477d1f4a8c 100644 --- a/solution/1900-1999/1924.Erect the Fence II/README.md +++ b/solution/1900-1999/1924.Erect the Fence II/README.md @@ -46,30 +46,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1924.Erect the Fence II/README_EN.md b/solution/1900-1999/1924.Erect the Fence II/README_EN.md index c3046ff44f1dd..db3d5b1ba3778 100644 --- a/solution/1900-1999/1924.Erect the Fence II/README_EN.md +++ b/solution/1900-1999/1924.Erect the Fence II/README_EN.md @@ -44,24 +44,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1925.Count Square Sum Triples/README.md b/solution/1900-1999/1925.Count Square Sum Triples/README.md index 7287232d203c6..e4c07e1f3290c 100644 --- a/solution/1900-1999/1925.Count Square Sum Triples/README.md +++ b/solution/1900-1999/1925.Count Square Sum Triples/README.md @@ -36,14 +36,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def countTriples(self, n: int) -> int: @@ -57,10 +53,6 @@ class Solution: return res ``` -### **Java** - - - ```java class Solution { public int countTriples(int n) { @@ -79,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +90,6 @@ public: }; ``` -### **Go** - ```go func countTriples(n int) int { res := 0 @@ -118,10 +106,6 @@ func countTriples(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1925.Count Square Sum Triples/README_EN.md b/solution/1900-1999/1925.Count Square Sum Triples/README_EN.md index 6444ac2e566ab..4d34018e08bce 100644 --- a/solution/1900-1999/1925.Count Square Sum Triples/README_EN.md +++ b/solution/1900-1999/1925.Count Square Sum Triples/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return res ``` -### **Java** - ```java class Solution { public int countTriples(int n) { @@ -71,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -92,8 +88,6 @@ public: }; ``` -### **Go** - ```go func countTriples(n int) int { res := 0 @@ -110,10 +104,6 @@ func countTriples(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1926.Nearest Exit from Entrance in Maze/README.md b/solution/1900-1999/1926.Nearest Exit from Entrance in Maze/README.md index 01c8002a2cf49..efb13de73e12d 100644 --- a/solution/1900-1999/1926.Nearest Exit from Entrance in Maze/README.md +++ b/solution/1900-1999/1926.Nearest Exit from Entrance in Maze/README.md @@ -61,16 +61,10 @@ ## 解法 - - -BFS 最短路模型。 +### 方法一 -### **Python3** - - - ```python class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: @@ -93,10 +87,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int nearestExit(char[][] maze, int[] entrance) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +148,6 @@ public: }; ``` -### **Go** - ```go func nearestExit(maze [][]byte, entrance []int) int { m, n := len(maze), len(maze[0]) @@ -190,10 +176,6 @@ func nearestExit(maze [][]byte, entrance []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1926.Nearest Exit from Entrance in Maze/README_EN.md b/solution/1900-1999/1926.Nearest Exit from Entrance in Maze/README_EN.md index acf259ada3261..73c58bed048d7 100644 --- a/solution/1900-1999/1926.Nearest Exit from Entrance in Maze/README_EN.md +++ b/solution/1900-1999/1926.Nearest Exit from Entrance in Maze/README_EN.md @@ -60,12 +60,10 @@ Thus, the nearest exit is [1,2], which is 2 steps away. ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: @@ -88,8 +86,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int nearestExit(char[][] maze, int[] entrance) { @@ -122,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +147,6 @@ public: }; ``` -### **Go** - ```go func nearestExit(maze [][]byte, entrance []int) int { m, n := len(maze), len(maze[0]) @@ -183,10 +175,6 @@ func nearestExit(maze [][]byte, entrance []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1927.Sum Game/README.md b/solution/1900-1999/1927.Sum Game/README.md index b5e4f82974c76..6a400e71060a5 100644 --- a/solution/1900-1999/1927.Sum Game/README.md +++ b/solution/1900-1999/1927.Sum Game/README.md @@ -69,9 +69,7 @@ Bob 获胜,因为 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7 。 ## 解法 - - -**方法一:分类讨论** +### 方法一:分类讨论 如果 `'?'` 的个数为奇数,那么 Alice 一定会获胜,因为她可以选择将最后一个 `'?'` 替换为任何一个数字,使得前一半的和与后一半的和不相等。 @@ -91,10 +89,6 @@ Bob 获胜,因为 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7 。 -### **Python3** - - - ```python class Solution: def sumGame(self, num: str) -> bool: @@ -106,10 +100,6 @@ class Solution: return (cnt1 + cnt2) % 2 == 1 or s1 - s2 != 9 * (cnt2 - cnt1) // 2 ``` -### **Java** - - - ```java class Solution { public boolean sumGame(String num) { @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +151,6 @@ public: }; ``` -### **Go** - ```go func sumGame(num string) bool { n := len(num) @@ -187,8 +173,6 @@ func sumGame(num string) bool { } ``` -### **TypeScript** - ```ts function sumGame(num: string): boolean { const n = num.length; @@ -211,10 +195,6 @@ function sumGame(num: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1927.Sum Game/README_EN.md b/solution/1900-1999/1927.Sum Game/README_EN.md index 4e4a5b8d267ba..48891ae63a100 100644 --- a/solution/1900-1999/1927.Sum Game/README_EN.md +++ b/solution/1900-1999/1927.Sum Game/README_EN.md @@ -65,9 +65,9 @@ Bob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return (cnt1 + cnt2) % 2 == 1 or s1 - s2 != 9 * (cnt2 - cnt1) // 2 ``` -### **Java** - ```java class Solution { public boolean sumGame(String num) { @@ -107,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +131,6 @@ public: }; ``` -### **Go** - ```go func sumGame(num string) bool { n := len(num) @@ -159,8 +153,6 @@ func sumGame(num string) bool { } ``` -### **TypeScript** - ```ts function sumGame(num: string): boolean { const n = num.length; @@ -183,10 +175,6 @@ function sumGame(num: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1928.Minimum Cost to Reach Destination in Time/README.md b/solution/1900-1999/1928.Minimum Cost to Reach Destination in Time/README.md index bfe67a4494fb4..c2398fa31fdd1 100644 --- a/solution/1900-1999/1928.Minimum Cost to Reach Destination in Time/README.md +++ b/solution/1900-1999/1928.Minimum Cost to Reach Destination in Time/README.md @@ -63,30 +63,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1928.Minimum Cost to Reach Destination in Time/README_EN.md b/solution/1900-1999/1928.Minimum Cost to Reach Destination in Time/README_EN.md index ab515318f82b6..9df5e3b1a0cb3 100644 --- a/solution/1900-1999/1928.Minimum Cost to Reach Destination in Time/README_EN.md +++ b/solution/1900-1999/1928.Minimum Cost to Reach Destination in Time/README_EN.md @@ -59,24 +59,4 @@ You cannot take path 0 -> 1 -> 2 -> 5 since it would take too long. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1929.Concatenation of Array/README.md b/solution/1900-1999/1929.Concatenation of Array/README.md index 617da1f8dbdaa..b2d671dddc8d3 100644 --- a/solution/1900-1999/1929.Concatenation of Array/README.md +++ b/solution/1900-1999/1929.Concatenation of Array/README.md @@ -50,24 +50,16 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def getConcatenation(self, nums: List[int]) -> List[int]: return nums + nums ``` -### **Java** - - - ```java class Solution { public int[] getConcatenation(int[] nums) { @@ -81,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,38 +85,18 @@ public: }; ``` -### **Go** - ```go func getConcatenation(nums []int) []int { return append(nums, nums...) } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var getConcatenation = function (nums) { - let ans = nums.slice(); - ans.splice(nums.length, 0, ...nums); - return ans; -}; -``` - -### **TypeScript** - ```ts function getConcatenation(nums: number[]): number[] { return [...nums, ...nums]; } ``` -### **Rust** - ```rust impl Solution { pub fn get_concatenation(nums: Vec) -> Vec { @@ -135,7 +105,17 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var getConcatenation = function (nums) { + let ans = nums.slice(); + ans.splice(nums.length, 0, ...nums); + return ans; +}; +``` ```c /** @@ -151,10 +131,6 @@ int* getConcatenation(int* nums, int numsSize, int* returnSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1929.Concatenation of Array/README_EN.md b/solution/1900-1999/1929.Concatenation of Array/README_EN.md index a27fbe221f433..1920ba03d3c43 100644 --- a/solution/1900-1999/1929.Concatenation of Array/README_EN.md +++ b/solution/1900-1999/1929.Concatenation of Array/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return nums + nums ``` -### **Java** - ```java class Solution { public int[] getConcatenation(int[] nums) { @@ -66,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -80,38 +76,18 @@ public: }; ``` -### **Go** - ```go func getConcatenation(nums []int) []int { return append(nums, nums...) } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number[]} - */ -var getConcatenation = function (nums) { - let ans = nums.slice(); - ans.splice(nums.length, 0, ...nums); - return ans; -}; -``` - -### **TypeScript** - ```ts function getConcatenation(nums: number[]): number[] { return [...nums, ...nums]; } ``` -### **Rust** - ```rust impl Solution { pub fn get_concatenation(nums: Vec) -> Vec { @@ -120,7 +96,17 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {number[]} nums + * @return {number[]} + */ +var getConcatenation = function (nums) { + let ans = nums.slice(); + ans.splice(nums.length, 0, ...nums); + return ans; +}; +``` ```c /** @@ -136,10 +122,6 @@ int* getConcatenation(int* nums, int numsSize, int* returnSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1930.Unique Length-3 Palindromic Subsequences/README.md b/solution/1900-1999/1930.Unique Length-3 Palindromic Subsequences/README.md index bb62d6cae4def..0af28e93f5878 100644 --- a/solution/1900-1999/1930.Unique Length-3 Palindromic Subsequences/README.md +++ b/solution/1900-1999/1930.Unique Length-3 Palindromic Subsequences/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:枚举两端字符 + 哈希表** +### 方法一:枚举两端字符 + 哈希表 由于字符串中只包含小写字母,因此我们可以直接枚举所有的两端字符。对于每一对两端字符 $c$,我们找出它们在字符串中第一次和最后一次出现的位置 $l$ 和 $r$,如果 $r - l > 1$,说明找到了满足条件的回文序列,我们将 $[l+1,..r-1]$ 之间的字符去重后统计个数,即为以 $c$ 为两端字符的回文序列个数,加入答案中。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def countPalindromicSubsequence(self, s: str) -> int: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countPalindromicSubsequence(String s) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func countPalindromicSubsequence(s string) (ans int) { for c := 'a'; c <= 'z'; c++ { @@ -144,8 +130,6 @@ func countPalindromicSubsequence(s string) (ans int) { } ``` -### **C#** - ```cs public class Solution { public int CountPalindromicSubsequence(string s) { @@ -163,10 +147,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1930.Unique Length-3 Palindromic Subsequences/README_EN.md b/solution/1900-1999/1930.Unique Length-3 Palindromic Subsequences/README_EN.md index d43f3dcac4012..e1d28387030e0 100644 --- a/solution/1900-1999/1930.Unique Length-3 Palindromic Subsequences/README_EN.md +++ b/solution/1900-1999/1930.Unique Length-3 Palindromic Subsequences/README_EN.md @@ -58,9 +58,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countPalindromicSubsequence(String s) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +106,6 @@ public: }; ``` -### **Go** - ```go func countPalindromicSubsequence(s string) (ans int) { for c := 'a'; c <= 'z'; c++ { @@ -126,8 +120,6 @@ func countPalindromicSubsequence(s string) (ans int) { } ``` -### **C#** - ```cs public class Solution { public int CountPalindromicSubsequence(string s) { @@ -145,10 +137,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1931.Painting a Grid With Three Different Colors/README.md b/solution/1900-1999/1931.Painting a Grid With Three Different Colors/README.md index e06cb05277232..8f449c1ad6ad4 100644 --- a/solution/1900-1999/1931.Painting a Grid With Three Different Colors/README.md +++ b/solution/1900-1999/1931.Painting a Grid With Three Different Colors/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:状态压缩 + 动态规划** +### 方法一:状态压缩 + 动态规划 我们注意到,网格的行数不超过 $5$,那么一列中最多有 $3^5=243$ 种不同的颜色方案。 @@ -68,10 +66,6 @@ $$ -### **Python3** - - - ```python class Solution: def colorTheGrid(self, m: int, n: int) -> int: @@ -109,10 +103,6 @@ class Solution: return sum(f) % mod ``` -### **Java** - - - ```java class Solution { private int m; @@ -178,8 +168,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -242,8 +230,6 @@ public: }; ``` -### **Go** - ```go func colorTheGrid(m int, n int) (ans int) { f1 := func(x int) bool { @@ -301,8 +287,6 @@ func colorTheGrid(m int, n int) (ans int) { } ``` -### **TypeScript** - ```ts function colorTheGrid(m: number, n: number): number { const f1 = (x: number): boolean => { @@ -361,10 +345,6 @@ function colorTheGrid(m: number, n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1931.Painting a Grid With Three Different Colors/README_EN.md b/solution/1900-1999/1931.Painting a Grid With Three Different Colors/README_EN.md index a4758bc614cfb..0ab538274e662 100644 --- a/solution/1900-1999/1931.Painting a Grid With Three Different Colors/README_EN.md +++ b/solution/1900-1999/1931.Painting a Grid With Three Different Colors/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: State Compression + Dynamic Programming** +### Solution 1: State Compression + Dynamic Programming We notice that the number of rows in the grid does not exceed $5$, so there are at most $3^5=243$ different color schemes in a column. @@ -62,8 +62,6 @@ The time complexity is $O((m + n) \times 3^{2m})$, and the space complexity is $ -### **Python3** - ```python class Solution: def colorTheGrid(self, m: int, n: int) -> int: @@ -101,8 +99,6 @@ class Solution: return sum(f) % mod ``` -### **Java** - ```java class Solution { private int m; @@ -168,8 +164,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -232,8 +226,6 @@ public: }; ``` -### **Go** - ```go func colorTheGrid(m int, n int) (ans int) { f1 := func(x int) bool { @@ -291,8 +283,6 @@ func colorTheGrid(m int, n int) (ans int) { } ``` -### **TypeScript** - ```ts function colorTheGrid(m: number, n: number): number { const f1 = (x: number): boolean => { @@ -351,10 +341,6 @@ function colorTheGrid(m: number, n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1932.Merge BSTs to Create Single BST/README.md b/solution/1900-1999/1932.Merge BSTs to Create Single BST/README.md index 18cba219ee571..68f7344765794 100644 --- a/solution/1900-1999/1932.Merge BSTs to Create Single BST/README.md +++ b/solution/1900-1999/1932.Merge BSTs to Create Single BST/README.md @@ -77,30 +77,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1932.Merge BSTs to Create Single BST/README_EN.md b/solution/1900-1999/1932.Merge BSTs to Create Single BST/README_EN.md index ad47b9ad180e3..8599c05321926 100644 --- a/solution/1900-1999/1932.Merge BSTs to Create Single BST/README_EN.md +++ b/solution/1900-1999/1932.Merge BSTs to Create Single BST/README_EN.md @@ -73,24 +73,4 @@ The resulting tree is shown above. This is the only valid operation that can be ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/README.md b/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/README.md index 1f9d17d12be2f..4796f1537e909 100644 --- a/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/README.md +++ b/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 遍历字符串 $s$,用双指针 $i$ 和 $j$ 统计每个等值子字符串的长度。若长度模 $3$ 余 $1$,说明该子字符串长度不符合要求,返回 `false`;若长度模 $3$ 余 $2$,说明出现了长度为 $2$ 的子字符串,若此前已经出现过长度为 $2$ 的子字符串,返回 `false`,否则将 $j$ 的值赋给 $i$,继续遍历。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def isDecomposable(self, s: str) -> bool: @@ -87,24 +81,6 @@ class Solution: return cnt2 == 1 ``` -```python -class Solution: - def isDecomposable(self, s: str) -> bool: - cnt2 = 0 - for _, g in groupby(s): - m = len(list(g)) - if m % 3 == 1: - return False - cnt2 += m % 3 == 2 - if cnt2 > 1: - return False - return cnt2 == 1 -``` - -### **Java** - - - ```java class Solution { public boolean isDecomposable(String s) { @@ -128,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +128,6 @@ public: }; ``` -### **Go** - ```go func isDecomposable(s string) bool { i, n := 0, len(s) @@ -180,8 +152,6 @@ func isDecomposable(s string) bool { } ``` -### **TypeScript** - ```ts function isDecomposable(s: string): boolean { const n = s.length; @@ -203,10 +173,26 @@ function isDecomposable(s: string): boolean { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def isDecomposable(self, s: str) -> bool: + cnt2 = 0 + for _, g in groupby(s): + m = len(list(g)) + if m % 3 == 1: + return False + cnt2 += m % 3 == 2 + if cnt2 > 1: + return False + return cnt2 == 1 ``` + + diff --git a/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/README_EN.md b/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/README_EN.md index 463da18783da9..ab23e1a3d46e7 100644 --- a/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/README_EN.md +++ b/solution/1900-1999/1933.Check if String Is Decomposable Into Value-Equal Substrings/README_EN.md @@ -52,7 +52,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We traverse the string $s$, using two pointers $i$ and $j$ to count the length of each equal substring. If the length modulo $3$ is $1$, it means that the length of this substring does not meet the requirements, so we return `false`. If the length modulo $3$ is $2$, it means that a substring of length $2$ has appeared. If a substring of length $2$ has appeared before, return `false`, otherwise assign the value of $j$ to $i$ and continue to traverse. @@ -62,8 +62,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. The sp -### **Python3** - ```python class Solution: def isDecomposable(self, s: str) -> bool: @@ -82,22 +80,6 @@ class Solution: return cnt2 == 1 ``` -```python -class Solution: - def isDecomposable(self, s: str) -> bool: - cnt2 = 0 - for _, g in groupby(s): - m = len(list(g)) - if m % 3 == 1: - return False - cnt2 += m % 3 == 2 - if cnt2 > 1: - return False - return cnt2 == 1 -``` - -### **Java** - ```java class Solution { public boolean isDecomposable(String s) { @@ -121,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +127,6 @@ public: }; ``` -### **Go** - ```go func isDecomposable(s string) bool { i, n := 0, len(s) @@ -173,8 +151,6 @@ func isDecomposable(s string) bool { } ``` -### **TypeScript** - ```ts function isDecomposable(s: string): boolean { const n = s.length; @@ -196,10 +172,26 @@ function isDecomposable(s: string): boolean { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def isDecomposable(self, s: str) -> bool: + cnt2 = 0 + for _, g in groupby(s): + m = len(list(g)) + if m % 3 == 1: + return False + cnt2 += m % 3 == 2 + if cnt2 > 1: + return False + return cnt2 == 1 ``` + + diff --git a/solution/1900-1999/1934.Confirmation Rate/README.md b/solution/1900-1999/1934.Confirmation Rate/README.md index 8d5509201d969..dcdbaf2a31379 100644 --- a/solution/1900-1999/1934.Confirmation Rate/README.md +++ b/solution/1900-1999/1934.Confirmation Rate/README.md @@ -89,18 +89,12 @@ Confirmations 表: ## 解法 - - -**方法一:左连接 + 分组统计** +### 方法一:左连接 + 分组统计 我们可以使用左连接,将 `Signups` 表和 `Confirmations` 表按照 `user_id` 进行连接,然后使用 `GROUP BY` 对 `user_id` 进行分组统计。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -113,3 +107,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1900-1999/1934.Confirmation Rate/README_EN.md b/solution/1900-1999/1934.Confirmation Rate/README_EN.md index 0dc545e608eda..ef27ea13177f3 100644 --- a/solution/1900-1999/1934.Confirmation Rate/README_EN.md +++ b/solution/1900-1999/1934.Confirmation Rate/README_EN.md @@ -89,14 +89,12 @@ User 2 made 2 requests where one was confirmed and the other timed out. The conf ## Solutions -**Solution 1: Left Join + Grouping** +### Solution 1: Left Join + Grouping We can use a left join to join the `Signups` table and the `Confirmations` table on `user_id`, and then use `GROUP BY` to group by `user_id` for aggregation. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -109,3 +107,5 @@ GROUP BY 1; ``` + + diff --git a/solution/1900-1999/1935.Maximum Number of Words You Can Type/README.md b/solution/1900-1999/1935.Maximum Number of Words You Can Type/README.md index 93aac2a878718..9e9e45982dcfe 100644 --- a/solution/1900-1999/1935.Maximum Number of Words You Can Type/README.md +++ b/solution/1900-1999/1935.Maximum Number of Words You Can Type/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:数组或哈希表** +### 方法一:数组或哈希表 我们可以用哈希表或者一个长度为 $26$ 的数组 $s$ 来记录所有损坏的字母键。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def canBeTypedWords(self, text: str, brokenLetters: str) -> int: @@ -72,10 +66,6 @@ class Solution: return sum(all(c not in s for c in w) for w in text.split()) ``` -### **Java** - - - ```java class Solution { public int canBeTypedWords(String text, String brokenLetters) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func canBeTypedWords(text string, brokenLetters string) (ans int) { s := [26]bool{} @@ -159,8 +145,6 @@ func canBeTypedWords(text string, brokenLetters string) (ans int) { } ``` -### **TypeScript** - ```ts function canBeTypedWords(text: string, brokenLetters: string): number { const s: boolean[] = Array(26).fill(false); @@ -181,8 +165,6 @@ function canBeTypedWords(text: string, brokenLetters: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn can_be_typed_words(text: String, broken_letters: String) -> i32 { @@ -206,10 +188,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1935.Maximum Number of Words You Can Type/README_EN.md b/solution/1900-1999/1935.Maximum Number of Words You Can Type/README_EN.md index adcf42879e8a5..268e453f4d91b 100644 --- a/solution/1900-1999/1935.Maximum Number of Words You Can Type/README_EN.md +++ b/solution/1900-1999/1935.Maximum Number of Words You Can Type/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Array or Hash Table** +### Solution 1: Array or Hash Table We can use a hash table or an array $s$ of length $26$ to record all the broken letter keys. @@ -58,8 +58,6 @@ The time complexity is $O(n)$, and the space complexity is $O(|\Sigma|)$, where -### **Python3** - ```python class Solution: def canBeTypedWords(self, text: str, brokenLetters: str) -> int: @@ -67,8 +65,6 @@ class Solution: return sum(all(c not in s for c in w) for w in text.split()) ``` -### **Java** - ```java class Solution { public int canBeTypedWords(String text, String brokenLetters) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +125,6 @@ public: }; ``` -### **Go** - ```go func canBeTypedWords(text string, brokenLetters string) (ans int) { s := [26]bool{} @@ -152,8 +144,6 @@ func canBeTypedWords(text string, brokenLetters string) (ans int) { } ``` -### **TypeScript** - ```ts function canBeTypedWords(text: string, brokenLetters: string): number { const s: boolean[] = Array(26).fill(false); @@ -174,8 +164,6 @@ function canBeTypedWords(text: string, brokenLetters: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn can_be_typed_words(text: String, broken_letters: String) -> i32 { @@ -199,10 +187,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1936.Add Minimum Number of Rungs/README.md b/solution/1900-1999/1936.Add Minimum Number of Rungs/README.md index b5f7763c2c126..dca32fd221fae 100644 --- a/solution/1900-1999/1936.Add Minimum Number of Rungs/README.md +++ b/solution/1900-1999/1936.Add Minimum Number of Rungs/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:贪心 + 模拟** +### 方法一:贪心 + 模拟 根据题目描述,我们知道,每一次计划爬上一个新的台阶,都需要满足新的台阶的高度与当前所在位置的高度之差不超过 `dist`,否则,我们需要贪心地在距离当前位置 $dist$ 的地方插入一个新的台阶,爬上一个新的台阶,一共需要插入的台阶数为 $\lfloor \frac{b - a - 1}{dist} \rfloor$,其中 $a$ 和 $b$ 分别为当前位置和新台阶的高度。那么答案即为所有插入的台阶数之和。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def addRungs(self, rungs: List[int], dist: int) -> int: @@ -87,10 +81,6 @@ class Solution: return sum((b - a - 1) // dist for a, b in pairwise(rungs)) ``` -### **Java** - - - ```java class Solution { public int addRungs(int[] rungs, int dist) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func addRungs(rungs []int, dist int) (ans int) { prev := 0 @@ -133,8 +119,6 @@ func addRungs(rungs []int, dist int) (ans int) { } ``` -### **TypeScript** - ```ts function addRungs(rungs: number[], dist: number): number { let ans = 0; @@ -147,8 +131,6 @@ function addRungs(rungs: number[], dist: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn add_rungs(rungs: Vec, dist: i32) -> i32 { @@ -165,10 +147,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1936.Add Minimum Number of Rungs/README_EN.md b/solution/1900-1999/1936.Add Minimum Number of Rungs/README_EN.md index 2b899949d9f6c..a5294bf68bdaa 100644 --- a/solution/1900-1999/1936.Add Minimum Number of Rungs/README_EN.md +++ b/solution/1900-1999/1936.Add Minimum Number of Rungs/README_EN.md @@ -54,7 +54,7 @@ The ladder will now have rungs at [1,3,4,6,7]. ## Solutions -**Solution 1: Greedy + Simulation** +### Solution 1: Greedy + Simulation According to the problem description, we know that every time we plan to climb a new rung, we need to ensure that the height difference between the new rung and the current position does not exceed `dist`. Otherwise, we need to greedily insert a new rung at a distance of $dist$ from the current position, climb a new rung, and the total number of rungs to be inserted is $\lfloor \frac{b - a - 1}{dist} \rfloor$, where $a$ and $b$ are the current position and the height of the new rung, respectively. The answer is the sum of all inserted rungs. @@ -62,8 +62,6 @@ The time complexity is $O(n)$, where $n$ is the length of `rungs`. The space com -### **Python3** - ```python class Solution: def addRungs(self, rungs: List[int], dist: int) -> int: @@ -71,8 +69,6 @@ class Solution: return sum((b - a - 1) // dist for a, b in pairwise(rungs)) ``` -### **Java** - ```java class Solution { public int addRungs(int[] rungs, int dist) { @@ -86,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +96,6 @@ public: }; ``` -### **Go** - ```go func addRungs(rungs []int, dist int) (ans int) { prev := 0 @@ -115,8 +107,6 @@ func addRungs(rungs []int, dist int) (ans int) { } ``` -### **TypeScript** - ```ts function addRungs(rungs: number[], dist: number): number { let ans = 0; @@ -129,8 +119,6 @@ function addRungs(rungs: number[], dist: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn add_rungs(rungs: Vec, dist: i32) -> i32 { @@ -147,10 +135,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1937.Maximum Number of Points with Cost/README.md b/solution/1900-1999/1937.Maximum Number of Points with Cost/README.md index 869b28534a6d4..1cd6f3ff72fb2 100644 --- a/solution/1900-1999/1937.Maximum Number of Points with Cost/README.md +++ b/solution/1900-1999/1937.Maximum Number of Points with Cost/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示选取前 $i-1$ 行,并且第 $i-1$ 行选择第 $j$ 列的格子时的最大得分。初始时 $f[0][j] = points[0][j]$。 @@ -85,10 +83,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxPoints(self, points: List[List[int]]) -> int: @@ -108,10 +102,6 @@ class Solution: return max(f) ``` -### **Java** - - - ```java class Solution { public long maxPoints(int[][] points) { @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go func maxPoints(points [][]int) int64 { n := len(points[0]) @@ -192,8 +178,6 @@ func maxPoints(points [][]int) int64 { } ``` -### **TypeScript** - ```ts function maxPoints(points: number[][]): number { const n = points[0].length; @@ -216,10 +200,6 @@ function maxPoints(points: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1937.Maximum Number of Points with Cost/README_EN.md b/solution/1900-1999/1937.Maximum Number of Points with Cost/README_EN.md index 90ef8c2f1c419..5b74b29cbc99e 100644 --- a/solution/1900-1999/1937.Maximum Number of Points with Cost/README_EN.md +++ b/solution/1900-1999/1937.Maximum Number of Points with Cost/README_EN.md @@ -57,9 +57,9 @@ Your final score is 12 - 1 = 11. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return max(f) ``` -### **Java** - ```java class Solution { public long maxPoints(int[][] points) { @@ -110,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +134,6 @@ public: }; ``` -### **Go** - ```go func maxPoints(points [][]int) int64 { n := len(points[0]) @@ -162,8 +156,6 @@ func maxPoints(points [][]int) int64 { } ``` -### **TypeScript** - ```ts function maxPoints(points: number[][]): number { const n = points[0].length; @@ -186,10 +178,6 @@ function maxPoints(points: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1938.Maximum Genetic Difference Query/README.md b/solution/1900-1999/1938.Maximum Genetic Difference Query/README.md index 0b9ffa353fe05..66cb95d4e39e7 100644 --- a/solution/1900-1999/1938.Maximum Genetic Difference Query/README.md +++ b/solution/1900-1999/1938.Maximum Genetic Difference Query/README.md @@ -49,30 +49,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1938.Maximum Genetic Difference Query/README_EN.md b/solution/1900-1999/1938.Maximum Genetic Difference Query/README_EN.md index f8fb10acd95fe..ab68973743b2d 100644 --- a/solution/1900-1999/1938.Maximum Genetic Difference Query/README_EN.md +++ b/solution/1900-1999/1938.Maximum Genetic Difference Query/README_EN.md @@ -47,24 +47,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1939.Users That Actively Request Confirmation Messages/README.md b/solution/1900-1999/1939.Users That Actively Request Confirmation Messages/README.md index 05add2f41cba8..acb1842217e9c 100644 --- a/solution/1900-1999/1939.Users That Actively Request Confirmation Messages/README.md +++ b/solution/1900-1999/1939.Users That Actively Request Confirmation Messages/README.md @@ -79,14 +79,10 @@ Result table ## 解法 - +### 方法一 -### **SQL** - - - ```sql SELECT DISTINCT user_id FROM @@ -98,3 +94,5 @@ WHERE ``` + + diff --git a/solution/1900-1999/1939.Users That Actively Request Confirmation Messages/README_EN.md b/solution/1900-1999/1939.Users That Actively Request Confirmation Messages/README_EN.md index 04d2cbcc48b86..eb5fe412a09f5 100644 --- a/solution/1900-1999/1939.Users That Actively Request Confirmation Messages/README_EN.md +++ b/solution/1900-1999/1939.Users That Actively Request Confirmation Messages/README_EN.md @@ -86,9 +86,9 @@ User 7 requested two messages within 24 hours and 1 second of each other, so we ## Solutions - +### Solution 1 -### **SQL** + ```sql SELECT DISTINCT user_id @@ -101,3 +101,5 @@ WHERE ``` + + diff --git a/solution/1900-1999/1940.Longest Common Subsequence Between Sorted Arrays/README.md b/solution/1900-1999/1940.Longest Common Subsequence Between Sorted Arrays/README.md index e60c555505922..d63a494d8a8ff 100644 --- a/solution/1900-1999/1940.Longest Common Subsequence Between Sorted Arrays/README.md +++ b/solution/1900-1999/1940.Longest Common Subsequence Between Sorted Arrays/README.md @@ -51,16 +51,10 @@ ## 解法 - - -计数器或者双指针实现。 +### 方法一 -### **Python3** - - - ```python class Solution: def longestCommomSubsequence(self, arrays: List[List[int]]) -> List[int]: @@ -72,33 +66,6 @@ class Solution: return [e for e, count in counter.items() if count == n] ``` -```python -class Solution: - def longestCommomSubsequence(self, arrays: List[List[int]]) -> List[int]: - def common(l1, l2): - i, j, n1, n2 = 0, 0, len(l1), len(l2) - res = [] - while i < n1 and j < n2: - if l1[i] == l2[j]: - res.append(l1[i]) - i += 1 - j += 1 - elif l1[i] > l2[j]: - j += 1 - else: - i += 1 - return res - - n = len(arrays) - for i in range(1, n): - arrays[i] = common(arrays[i - 1], arrays[i]) - return arrays[n - 1] -``` - -### **Java** - - - ```java class Solution { public List longestCommomSubsequence(int[][] arrays) { @@ -120,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +107,6 @@ public: }; ``` -### **Go** - ```go func longestCommomSubsequence(arrays [][]int) []int { counter := make(map[int]int) @@ -161,8 +124,6 @@ func longestCommomSubsequence(arrays [][]int) []int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} arrays @@ -182,10 +143,35 @@ var longestCommonSubsequence = function (arrays) { }; ``` -### **...** + -``` +### 方法二 + + + +```python +class Solution: + def longestCommomSubsequence(self, arrays: List[List[int]]) -> List[int]: + def common(l1, l2): + i, j, n1, n2 = 0, 0, len(l1), len(l2) + res = [] + while i < n1 and j < n2: + if l1[i] == l2[j]: + res.append(l1[i]) + i += 1 + j += 1 + elif l1[i] > l2[j]: + j += 1 + else: + i += 1 + return res + n = len(arrays) + for i in range(1, n): + arrays[i] = common(arrays[i - 1], arrays[i]) + return arrays[n - 1] ``` + + diff --git a/solution/1900-1999/1940.Longest Common Subsequence Between Sorted Arrays/README_EN.md b/solution/1900-1999/1940.Longest Common Subsequence Between Sorted Arrays/README_EN.md index 0bbedb3fc417d..ad7cfbbbc5132 100644 --- a/solution/1900-1999/1940.Longest Common Subsequence Between Sorted Arrays/README_EN.md +++ b/solution/1900-1999/1940.Longest Common Subsequence Between Sorted Arrays/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,31 +64,6 @@ class Solution: return [e for e, count in counter.items() if count == n] ``` -```python -class Solution: - def longestCommomSubsequence(self, arrays: List[List[int]]) -> List[int]: - def common(l1, l2): - i, j, n1, n2 = 0, 0, len(l1), len(l2) - res = [] - while i < n1 and j < n2: - if l1[i] == l2[j]: - res.append(l1[i]) - i += 1 - j += 1 - elif l1[i] > l2[j]: - j += 1 - else: - i += 1 - return res - - n = len(arrays) - for i in range(1, n): - arrays[i] = common(arrays[i - 1], arrays[i]) - return arrays[n - 1] -``` - -### **Java** - ```java class Solution { public List longestCommomSubsequence(int[][] arrays) { @@ -110,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +105,6 @@ public: }; ``` -### **Go** - ```go func longestCommomSubsequence(arrays [][]int) []int { counter := make(map[int]int) @@ -151,8 +122,6 @@ func longestCommomSubsequence(arrays [][]int) []int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} arrays @@ -172,10 +141,35 @@ var longestCommonSubsequence = function (arrays) { }; ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def longestCommomSubsequence(self, arrays: List[List[int]]) -> List[int]: + def common(l1, l2): + i, j, n1, n2 = 0, 0, len(l1), len(l2) + res = [] + while i < n1 and j < n2: + if l1[i] == l2[j]: + res.append(l1[i]) + i += 1 + j += 1 + elif l1[i] > l2[j]: + j += 1 + else: + i += 1 + return res + + n = len(arrays) + for i in range(1, n): + arrays[i] = common(arrays[i - 1], arrays[i]) + return arrays[n - 1] ``` + + diff --git a/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/README.md b/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/README.md index d9625a70ca43b..e6e3e9feab9ce 100644 --- a/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/README.md +++ b/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们用一个哈希表或一个长度为 $26$ 的数组 $cnt$ 记录字符串 $s$ 中每个字符出现的次数。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python class Solution: def areOccurrencesEqual(self, s: str) -> bool: @@ -61,10 +55,6 @@ class Solution: return len(set(cnt.values())) == 1 ``` -### **Java** - - - ```java class Solution { public boolean areOccurrencesEqual(String s) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +100,6 @@ public: }; ``` -### **Go** - ```go func areOccurrencesEqual(s string) bool { cnt := [26]int{} @@ -134,8 +120,6 @@ func areOccurrencesEqual(s string) bool { } ``` -### **TypeScript** - ```ts function areOccurrencesEqual(s: string): boolean { const cnt: number[] = new Array(26).fill(0); @@ -156,19 +140,6 @@ function areOccurrencesEqual(s: string): boolean { } ``` -```ts -function areOccurrencesEqual(s: string): boolean { - const cnt: number[] = new Array(26).fill(0); - for (const c of s) { - ++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; - } - const x = cnt.find(v => v); - return cnt.every(v => !v || v === x); -} -``` - -### **PHP** - ```php class Solution { /** @@ -185,10 +156,23 @@ class Solution { } ``` -### **...** + -``` +### 方法二 + + +```ts +function areOccurrencesEqual(s: string): boolean { + const cnt: number[] = new Array(26).fill(0); + for (const c of s) { + ++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; + } + const x = cnt.find(v => v); + return cnt.every(v => !v || v === x); +} ``` + + diff --git a/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/README_EN.md b/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/README_EN.md index 5cd2486642ead..0e966678ba851 100644 --- a/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/README_EN.md +++ b/solution/1900-1999/1941.Check if All Characters Have Equal Number of Occurrences/README_EN.md @@ -36,9 +36,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -47,8 +47,6 @@ class Solution: return len(set(cnt.values())) == 1 ``` -### **Java** - ```java class Solution { public boolean areOccurrencesEqual(String s) { @@ -71,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func areOccurrencesEqual(s string) bool { cnt := [26]int{} @@ -118,8 +112,6 @@ func areOccurrencesEqual(s string) bool { } ``` -### **TypeScript** - ```ts function areOccurrencesEqual(s: string): boolean { const cnt: number[] = new Array(26).fill(0); @@ -140,19 +132,6 @@ function areOccurrencesEqual(s: string): boolean { } ``` -```ts -function areOccurrencesEqual(s: string): boolean { - const cnt: number[] = new Array(26).fill(0); - for (const c of s) { - ++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; - } - const x = cnt.find(v => v); - return cnt.every(v => !v || v === x); -} -``` - -### **PHP** - ```php class Solution { /** @@ -169,10 +148,23 @@ class Solution { } ``` -### **...** + -``` +### Solution 2 + + +```ts +function areOccurrencesEqual(s: string): boolean { + const cnt: number[] = new Array(26).fill(0); + for (const c of s) { + ++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; + } + const x = cnt.find(v => v); + return cnt.every(v => !v || v === x); +} ``` + + diff --git a/solution/1900-1999/1942.The Number of the Smallest Unoccupied Chair/README.md b/solution/1900-1999/1942.The Number of the Smallest Unoccupied Chair/README.md index 64b4d8f403a82..69718aa717e74 100644 --- a/solution/1900-1999/1942.The Number of the Smallest Unoccupied Chair/README.md +++ b/solution/1900-1999/1942.The Number of the Smallest Unoccupied Chair/README.md @@ -62,16 +62,10 @@ ## 解法 - - -**方法一:优先队列(最小堆)** +### 方法一:优先队列(最小堆) -### **Python3** - - - ```python class Solution: def smallestChair(self, times: List[List[int]], targetFriend: int) -> int: @@ -92,10 +86,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int smallestChair(int[][] times, int targetFriend) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp using pii = pair; @@ -156,10 +144,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1942.The Number of the Smallest Unoccupied Chair/README_EN.md b/solution/1900-1999/1942.The Number of the Smallest Unoccupied Chair/README_EN.md index 65cfd76dc9c0d..92b467106bdc5 100644 --- a/solution/1900-1999/1942.The Number of the Smallest Unoccupied Chair/README_EN.md +++ b/solution/1900-1999/1942.The Number of the Smallest Unoccupied Chair/README_EN.md @@ -60,9 +60,9 @@ Since friend 0 sat on chair 2, we return 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int smallestChair(int[][] times, int targetFriend) { @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp using pii = pair; @@ -146,10 +142,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1943.Describe the Painting/README.md b/solution/1900-1999/1943.Describe the Painting/README.md index 25ae959d87698..0cae1f712b427 100644 --- a/solution/1900-1999/1943.Describe the Painting/README.md +++ b/solution/1900-1999/1943.Describe the Painting/README.md @@ -82,16 +82,10 @@ ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 -### **Python3** - - - ```python class Solution: def splitPainting(self, segments: List[List[int]]) -> List[List[int]]: @@ -106,10 +100,6 @@ class Solution: return [[s[i][0], s[i + 1][0], s[i][1]] for i in range(n - 1) if s[i][1]] ``` -### **Java** - - - ```java class Solution { public List> splitPainting(int[][] segments) { @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,10 +156,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1943.Describe the Painting/README_EN.md b/solution/1900-1999/1943.Describe the Painting/README_EN.md index 43a5c44bede91..2e6bdf8353f90 100644 --- a/solution/1900-1999/1943.Describe the Painting/README_EN.md +++ b/solution/1900-1999/1943.Describe the Painting/README_EN.md @@ -78,9 +78,9 @@ Note that returning a single segment [1,7) is incorrect because the mixed color ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -96,8 +96,6 @@ class Solution: return [[s[i][0], s[i + 1][0], s[i][1]] for i in range(n - 1) if s[i][1]] ``` -### **Java** - ```java class Solution { public List> splitPainting(int[][] segments) { @@ -127,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,10 +152,6 @@ public: }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1944.Number of Visible People in a Queue/README.md b/solution/1900-1999/1944.Number of Visible People in a Queue/README.md index 7f3fd277f98db..32a3d0c1afeca 100644 --- a/solution/1900-1999/1944.Number of Visible People in a Queue/README.md +++ b/solution/1900-1999/1944.Number of Visible People in a Queue/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 我们观察发现,对于第 $i$ 个人来说,他能看到的人一定是按从左到右高度严格单调递增的。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def canSeePersonsCount(self, heights: List[int]) -> List[int]: @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] canSeePersonsCount(int[] heights) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func canSeePersonsCount(heights []int) []int { n := len(heights) @@ -162,8 +148,6 @@ func canSeePersonsCount(heights []int) []int { } ``` -### **TypeScript** - ```ts function canSeePersonsCount(heights: number[]): number[] { const n = heights.length; @@ -183,8 +167,6 @@ function canSeePersonsCount(heights: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn can_see_persons_count(heights: Vec) -> Vec { @@ -206,8 +188,6 @@ impl Solution { } ``` -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -232,10 +212,6 @@ int* canSeePersonsCount(int* heights, int heightsSize, int* returnSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1944.Number of Visible People in a Queue/README_EN.md b/solution/1900-1999/1944.Number of Visible People in a Queue/README_EN.md index 2bec70c9fa51e..bcd20168b956d 100644 --- a/solution/1900-1999/1944.Number of Visible People in a Queue/README_EN.md +++ b/solution/1900-1999/1944.Number of Visible People in a Queue/README_EN.md @@ -46,12 +46,10 @@ Person 5 can see no one since nobody is to the right of them. ## Solutions -Monotonic stack. +### Solution 1 -### **Python3** - ```python class Solution: def canSeePersonsCount(self, heights: List[int]) -> List[int]: @@ -68,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] canSeePersonsCount(int[] heights) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +109,6 @@ public: }; ``` -### **Go** - ```go func canSeePersonsCount(heights []int) []int { n := len(heights) @@ -136,8 +128,6 @@ func canSeePersonsCount(heights []int) []int { } ``` -### **TypeScript** - ```ts function canSeePersonsCount(heights: number[]): number[] { const n = heights.length; @@ -157,8 +147,6 @@ function canSeePersonsCount(heights: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn can_see_persons_count(heights: Vec) -> Vec { @@ -180,8 +168,6 @@ impl Solution { } ``` -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -206,10 +192,6 @@ int* canSeePersonsCount(int* heights, int heightsSize, int* returnSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1945.Sum of Digits of String After Convert/README.md b/solution/1900-1999/1945.Sum of Digits of String After Convert/README.md index d6a76d4282ded..ab9eb977c3f93 100644 --- a/solution/1900-1999/1945.Sum of Digits of String After Convert/README.md +++ b/solution/1900-1999/1945.Sum of Digits of String After Convert/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 根据题目描述进行模拟即可。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def getLucky(self, s: str, k: int) -> int: @@ -81,10 +75,6 @@ class Solution: return int(s) ``` -### **Java** - - - ```java class Solution { public int getLucky(String s, int k) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func getLucky(s string, k int) int { var t strings.Builder @@ -146,8 +132,6 @@ func getLucky(s string, k int) int { } ``` -### **TypeScript** - ```ts function getLucky(s: string, k: number): number { let ans = ''; @@ -165,8 +149,6 @@ function getLucky(s: string, k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn get_lucky(s: String, k: i32) -> i32 { @@ -186,8 +168,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -214,10 +194,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1945.Sum of Digits of String After Convert/README_EN.md b/solution/1900-1999/1945.Sum of Digits of String After Convert/README_EN.md index 4fbc4be42ff88..f9a9612862f28 100644 --- a/solution/1900-1999/1945.Sum of Digits of String After Convert/README_EN.md +++ b/solution/1900-1999/1945.Sum of Digits of String After Convert/README_EN.md @@ -60,9 +60,9 @@ Thus the resulting integer is 6. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return int(s) ``` -### **Java** - ```java class Solution { public int getLucky(String s, int k) { @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +111,6 @@ public: }; ``` -### **Go** - ```go func getLucky(s string, k int) int { var t strings.Builder @@ -137,8 +131,6 @@ func getLucky(s string, k int) int { } ``` -### **TypeScript** - ```ts function getLucky(s: string, k: number): number { let ans = ''; @@ -156,8 +148,6 @@ function getLucky(s: string, k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn get_lucky(s: String, k: i32) -> i32 { @@ -177,8 +167,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -205,10 +193,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1946.Largest Number After Mutating Substring/README.md b/solution/1900-1999/1946.Largest Number After Mutating Substring/README.md index 0b49619b1970c..3ab7b5cdf5a8c 100644 --- a/solution/1900-1999/1946.Largest Number After Mutating Substring/README.md +++ b/solution/1900-1999/1946.Largest Number After Mutating Substring/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 从左到右遍历字符串 `num`,找到第一个比 `change` 中对应数字小的数字,然后将其替换为 `change` 中对应的数字,直到遇到比 `change` 中对应数字大的数字,停止替换。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def maximumNumber(self, num: str, change: List[int]) -> str: @@ -85,10 +79,6 @@ class Solution: return ''.join(s) ``` -### **Java** - - - ```java class Solution { public String maximumNumber(String num, int[] change) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func maximumNumber(num string, change []int) string { s := []byte(num) @@ -143,10 +129,6 @@ func maximumNumber(num string, change []int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1946.Largest Number After Mutating Substring/README_EN.md b/solution/1900-1999/1946.Largest Number After Mutating Substring/README_EN.md index 7902b71c514c5..8c453020b3e08 100644 --- a/solution/1900-1999/1946.Largest Number After Mutating Substring/README_EN.md +++ b/solution/1900-1999/1946.Largest Number After Mutating Substring/README_EN.md @@ -57,9 +57,9 @@ Thus, "021" becomes "934". ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return ''.join(s) ``` -### **Java** - ```java class Solution { public String maximumNumber(String num, int[] change) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func maximumNumber(num string, change []int) string { s := []byte(num) @@ -130,10 +124,6 @@ func maximumNumber(num string, change []int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1947.Maximum Compatibility Score Sum/README.md b/solution/1900-1999/1947.Maximum Compatibility Score Sum/README.md index e154dc6b1fde7..a4179b6938b86 100644 --- a/solution/1900-1999/1947.Maximum Compatibility Score Sum/README.md +++ b/solution/1900-1999/1947.Maximum Compatibility Score Sum/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:预处理 + 回溯** +### 方法一:预处理 + 回溯 预处理出每个学生与每个导师的兼容性评分,然后使用回溯的方法枚举所有的配对方案,求出最大的兼容性评分和。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def maxCompatibilitySum( @@ -94,10 +88,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[][] g; @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +163,6 @@ public: }; ``` -### **Go** - ```go func maxCompatibilitySum(students [][]int, mentors [][]int) (ans int) { m, n := len(students), len(students[0]) @@ -211,10 +197,6 @@ func maxCompatibilitySum(students [][]int, mentors [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1947.Maximum Compatibility Score Sum/README_EN.md b/solution/1900-1999/1947.Maximum Compatibility Score Sum/README_EN.md index 51eb5654c416a..e94908818c0c9 100644 --- a/solution/1900-1999/1947.Maximum Compatibility Score Sum/README_EN.md +++ b/solution/1900-1999/1947.Maximum Compatibility Score Sum/README_EN.md @@ -52,9 +52,9 @@ The compatibility score sum is 3 + 2 + 3 = 8. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,8 +83,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[][] g; @@ -123,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +158,6 @@ public: }; ``` -### **Go** - ```go func maxCompatibilitySum(students [][]int, mentors [][]int) (ans int) { m, n := len(students), len(students[0]) @@ -198,10 +192,6 @@ func maxCompatibilitySum(students [][]int, mentors [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1948.Delete Duplicate Folders in System/README.md b/solution/1900-1999/1948.Delete Duplicate Folders in System/README.md index da3a700b5addb..9969612e07124 100644 --- a/solution/1900-1999/1948.Delete Duplicate Folders in System/README.md +++ b/solution/1900-1999/1948.Delete Duplicate Folders in System/README.md @@ -102,30 +102,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1948.Delete Duplicate Folders in System/README_EN.md b/solution/1900-1999/1948.Delete Duplicate Folders in System/README_EN.md index c63dc42e7f7c4..5f051d31d7bed 100644 --- a/solution/1900-1999/1948.Delete Duplicate Folders in System/README_EN.md +++ b/solution/1900-1999/1948.Delete Duplicate Folders in System/README_EN.md @@ -79,24 +79,4 @@ Note that the returned array can be in a different order as the order does not m ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1949.Strong Friendship/README.md b/solution/1900-1999/1949.Strong Friendship/README.md index 43aeeaf7aa9db..9c1c828bc3c13 100644 --- a/solution/1900-1999/1949.Strong Friendship/README.md +++ b/solution/1900-1999/1949.Strong Friendship/README.md @@ -70,14 +70,10 @@ Friendship table: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -105,3 +101,5 @@ HAVING COUNT(1) >= 3; ``` + + diff --git a/solution/1900-1999/1949.Strong Friendship/README_EN.md b/solution/1900-1999/1949.Strong Friendship/README_EN.md index a7f23e85aa5bb..d95faf0b7385d 100644 --- a/solution/1900-1999/1949.Strong Friendship/README_EN.md +++ b/solution/1900-1999/1949.Strong Friendship/README_EN.md @@ -67,9 +67,9 @@ We did not include the friendship of users 2 and 3 because they only have two co ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -98,3 +98,5 @@ HAVING COUNT(1) >= 3; ``` + + diff --git a/solution/1900-1999/1950.Maximum of Minimum Values in All Subarrays/README.md b/solution/1900-1999/1950.Maximum of Minimum Values in All Subarrays/README.md index 0c2d8532f1450..7515549b236d1 100644 --- a/solution/1900-1999/1950.Maximum of Minimum Values in All Subarrays/README.md +++ b/solution/1900-1999/1950.Maximum of Minimum Values in All Subarrays/README.md @@ -69,9 +69,7 @@ i = 3: ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 我们可以先利用单调栈,求出每个位置的左边第一个比它小的位置 $left[i]$ 和右边第一个比它小的位置 $right[i]$,那么以 $nums[i]$ 为最小值的子数组的长度为 $m = right[i] - left[i] - 1$。 @@ -85,10 +83,6 @@ i = 3: -### **Python3** - - - ```python class Solution: def findMaximums(self, nums: List[int]) -> List[int]: @@ -118,10 +112,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] findMaximums(int[] nums) { @@ -163,8 +153,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -205,8 +193,6 @@ public: }; ``` -### **Go** - ```go func findMaximums(nums []int) []int { n := len(nums) @@ -248,10 +234,6 @@ func findMaximums(nums []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1950.Maximum of Minimum Values in All Subarrays/README_EN.md b/solution/1900-1999/1950.Maximum of Minimum Values in All Subarrays/README_EN.md index dc2c2944f05ee..3c6898d4b6cb1 100644 --- a/solution/1900-1999/1950.Maximum of Minimum Values in All Subarrays/README_EN.md +++ b/solution/1900-1999/1950.Maximum of Minimum Values in All Subarrays/README_EN.md @@ -69,9 +69,9 @@ i=3: ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -102,8 +102,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] findMaximums(int[] nums) { @@ -145,8 +143,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -187,8 +183,6 @@ public: }; ``` -### **Go** - ```go func findMaximums(nums []int) []int { n := len(nums) @@ -230,10 +224,6 @@ func findMaximums(nums []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1951.All the Pairs With the Maximum Number of Common Followers/README.md b/solution/1900-1999/1951.All the Pairs With the Maximum Number of Common Followers/README.md index 9360ea6a2fb26..e8930c8235dca 100644 --- a/solution/1900-1999/1951.All the Pairs With the Maximum Number of Common Followers/README.md +++ b/solution/1900-1999/1951.All the Pairs With the Maximum Number of Common Followers/README.md @@ -64,14 +64,10 @@ Result 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -93,3 +89,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1900-1999/1951.All the Pairs With the Maximum Number of Common Followers/README_EN.md b/solution/1900-1999/1951.All the Pairs With the Maximum Number of Common Followers/README_EN.md index ab8376e704dd7..2589b55cec0bc 100644 --- a/solution/1900-1999/1951.All the Pairs With the Maximum Number of Common Followers/README_EN.md +++ b/solution/1900-1999/1951.All the Pairs With the Maximum Number of Common Followers/README_EN.md @@ -62,9 +62,9 @@ Note that we do not have any information about the users that follow users 3, 4, ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -87,3 +87,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/1900-1999/1952.Three Divisors/README.md b/solution/1900-1999/1952.Three Divisors/README.md index 933ed1c03f33f..900cad852c9d1 100644 --- a/solution/1900-1999/1952.Three Divisors/README.md +++ b/solution/1900-1999/1952.Three Divisors/README.md @@ -35,48 +35,20 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 一个数 $n$ 一定有 $1$ 和 $n$ 两个正除数,因此只需要枚举 $2$ 到 $n-1$ 之间的数,看它们是否是 $n$ 的正除数即可,是则累加计数器,最后判断计数器是否为 $1$ 即可。 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为给定的整数。 -**方法二:枚举优化** - -我们可以枚举 $1$ 到 $\sqrt{n}$ 之间的数 $i$,如果 $n$ 能被 $i$ 整除,并且 $\frac{n}{i}$ 不等于 $i$,那么计数器累加 $2$,否则计数器累加 $1$。最后判断计数器是否为 $3$ 即可。 - -时间复杂度 $O(\sqrt{n})$,空间复杂度 $O(1)$。其中 $n$ 为给定的整数。 - -### **Python3** - - - ```python class Solution: def isThree(self, n: int) -> bool: return sum(n % i == 0 for i in range(2, n)) == 1 ``` -```python -class Solution: - def isThree(self, n: int) -> bool: - cnt = 0 - i = 1 - while i <= n // i: - if n % i == 0: - cnt += 1 if i == n // i else 2 - i += 1 - return cnt == 3 -``` - -### **Java** - - - ```java class Solution { public boolean isThree(int n) { @@ -91,33 +63,81 @@ class Solution { } ``` -```java +```cpp class Solution { - public boolean isThree(int n) { +public: + bool isThree(int n) { int cnt = 0; - for (int i = 1; i <= n / i; ++i) { - if (n % i == 0) { - cnt += n / i == i ? 1 : 2; - } + for (int i = 2; i < n; ++i) { + cnt += n % i == 0; } - return cnt == 3; + return cnt == 1; } +}; +``` + +```go +func isThree(n int) bool { + cnt := 0 + for i := 2; i < n; i++ { + if n%i == 0 { + cnt++ + } + } + return cnt == 1 } ``` -### **C++** +```js +/** + * @param {number} n + * @return {boolean} + */ +var isThree = function (n) { + let cnt = 0; + for (let i = 2; i < n; ++i) { + if (n % i == 0) { + ++cnt; + } + } + return cnt == 1; +}; +``` -```cpp + + +### 方法二:枚举优化 + +我们可以枚举 $1$ 到 $\sqrt{n}$ 之间的数 $i$,如果 $n$ 能被 $i$ 整除,并且 $\frac{n}{i}$ 不等于 $i$,那么计数器累加 $2$,否则计数器累加 $1$。最后判断计数器是否为 $3$ 即可。 + +时间复杂度 $O(\sqrt{n})$,空间复杂度 $O(1)$。其中 $n$ 为给定的整数。 + + + +```python +class Solution: + def isThree(self, n: int) -> bool: + cnt = 0 + i = 1 + while i <= n // i: + if n % i == 0: + cnt += 1 if i == n // i else 2 + i += 1 + return cnt == 3 +``` + +```java class Solution { -public: - bool isThree(int n) { + public boolean isThree(int n) { int cnt = 0; - for (int i = 2; i < n; ++i) { - cnt += n % i == 0; + for (int i = 1; i <= n / i; ++i) { + if (n % i == 0) { + cnt += n / i == i ? 1 : 2; + } } - return cnt == 1; + return cnt == 3; } -}; +} ``` ```cpp @@ -135,20 +155,6 @@ public: }; ``` -### **Go** - -```go -func isThree(n int) bool { - cnt := 0 - for i := 2; i < n; i++ { - if n%i == 0 { - cnt++ - } - } - return cnt == 1 -} -``` - ```go func isThree(n int) bool { cnt := 0 @@ -165,24 +171,6 @@ func isThree(n int) bool { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {boolean} - */ -var isThree = function (n) { - let cnt = 0; - for (let i = 2; i < n; ++i) { - if (n % i == 0) { - ++cnt; - } - } - return cnt == 1; -}; -``` - ```js /** * @param {number} n @@ -199,10 +187,6 @@ var isThree = function (n) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1952.Three Divisors/README_EN.md b/solution/1900-1999/1952.Three Divisors/README_EN.md index abf967009474a..b549aad2433c7 100644 --- a/solution/1900-1999/1952.Three Divisors/README_EN.md +++ b/solution/1900-1999/1952.Three Divisors/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -44,20 +44,6 @@ class Solution: return sum(n % i == 0 for i in range(2, n)) == 1 ``` -```python -class Solution: - def isThree(self, n: int) -> bool: - cnt = 0 - i = 1 - while i <= n // i: - if n % i == 0: - cnt += 1 if i == n // i else 2 - i += 1 - return cnt == 3 -``` - -### **Java** - ```java class Solution { public boolean isThree(int n) { @@ -72,33 +58,77 @@ class Solution { } ``` -```java +```cpp class Solution { - public boolean isThree(int n) { +public: + bool isThree(int n) { int cnt = 0; - for (int i = 1; i <= n / i; ++i) { - if (n % i == 0) { - cnt += n / i == i ? 1 : 2; - } + for (int i = 2; i < n; ++i) { + cnt += n % i == 0; } - return cnt == 3; + return cnt == 1; } +}; +``` + +```go +func isThree(n int) bool { + cnt := 0 + for i := 2; i < n; i++ { + if n%i == 0 { + cnt++ + } + } + return cnt == 1 } ``` -### **C++** +```js +/** + * @param {number} n + * @return {boolean} + */ +var isThree = function (n) { + let cnt = 0; + for (let i = 2; i < n; ++i) { + if (n % i == 0) { + ++cnt; + } + } + return cnt == 1; +}; +``` -```cpp + + +### Solution 2 + + + +```python +class Solution: + def isThree(self, n: int) -> bool: + cnt = 0 + i = 1 + while i <= n // i: + if n % i == 0: + cnt += 1 if i == n // i else 2 + i += 1 + return cnt == 3 +``` + +```java class Solution { -public: - bool isThree(int n) { + public boolean isThree(int n) { int cnt = 0; - for (int i = 2; i < n; ++i) { - cnt += n % i == 0; + for (int i = 1; i <= n / i; ++i) { + if (n % i == 0) { + cnt += n / i == i ? 1 : 2; + } } - return cnt == 1; + return cnt == 3; } -}; +} ``` ```cpp @@ -116,20 +146,6 @@ public: }; ``` -### **Go** - -```go -func isThree(n int) bool { - cnt := 0 - for i := 2; i < n; i++ { - if n%i == 0 { - cnt++ - } - } - return cnt == 1 -} -``` - ```go func isThree(n int) bool { cnt := 0 @@ -146,24 +162,6 @@ func isThree(n int) bool { } ``` -### **JavaScript** - -```js -/** - * @param {number} n - * @return {boolean} - */ -var isThree = function (n) { - let cnt = 0; - for (let i = 2; i < n; ++i) { - if (n % i == 0) { - ++cnt; - } - } - return cnt == 1; -}; -``` - ```js /** * @param {number} n @@ -180,10 +178,6 @@ var isThree = function (n) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1953.Maximum Number of Weeks for Which You Can Work/README.md b/solution/1900-1999/1953.Maximum Number of Weeks for Which You Can Work/README.md index 5b82324cd7417..3a4f8c419a789 100644 --- a/solution/1900-1999/1953.Maximum Number of Weeks for Which You Can Work/README.md +++ b/solution/1900-1999/1953.Maximum Number of Weeks for Which You Can Work/README.md @@ -65,14 +65,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def numberOfWeeks(self, milestones: List[int]) -> int: @@ -81,10 +77,6 @@ class Solution: return rest * 2 + 1 if mx > rest + 1 else s ``` -### **Java** - - - ```java class Solution { public long numberOfWeeks(int[] milestones) { @@ -100,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +104,6 @@ public: }; ``` -### **Go** - ```go func numberOfWeeks(milestones []int) int64 { mx := slices.Max(milestones) @@ -131,10 +119,6 @@ func numberOfWeeks(milestones []int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1953.Maximum Number of Weeks for Which You Can Work/README_EN.md b/solution/1900-1999/1953.Maximum Number of Weeks for Which You Can Work/README_EN.md index 3014d4bad86fc..68bbadbc7000c 100644 --- a/solution/1900-1999/1953.Maximum Number of Weeks for Which You Can Work/README_EN.md +++ b/solution/1900-1999/1953.Maximum Number of Weeks for Which You Can Work/README_EN.md @@ -62,9 +62,9 @@ Thus, one milestone in project 0 will remain unfinished. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return rest * 2 + 1 if mx > rest + 1 else s ``` -### **Java** - ```java class Solution { public long numberOfWeeks(int[] milestones) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +101,6 @@ public: }; ``` -### **Go** - ```go func numberOfWeeks(milestones []int) int64 { mx := slices.Max(milestones) @@ -122,10 +116,6 @@ func numberOfWeeks(milestones []int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/README.md b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/README.md index ac6ecf843d0b5..c0337e8355b42 100644 --- a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/README.md +++ b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:数学 + 枚举** +### 方法一:数学 + 枚举 假设正方形右上角坐标为 $(n, n)$,那么它的边长为 $2n$,周长为 $8n$,里面的苹果总数为: @@ -83,16 +81,8 @@ $$ 时间复杂度 $O(m^{\frac{1}{3}})$,其中 $m$ 为 $neededApples$ 的值。空间复杂度 $O(1)$。 -**方法二:二分查找** - -我们也可以二分枚举 $n$,时间复杂度 $O(\log m)$。 - -### **Python3** - - - ```python class Solution: def minimumPerimeter(self, neededApples: int) -> int: @@ -102,6 +92,59 @@ class Solution: return x * 8 ``` +```java +class Solution { + public long minimumPerimeter(long neededApples) { + long x = 1; + while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { + ++x; + } + return 8 * x; + } +} +``` + +```cpp +class Solution { +public: + long long minimumPerimeter(long long neededApples) { + long long x = 1; + while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { + ++x; + } + return 8 * x; + } +}; +``` + +```go +func minimumPerimeter(neededApples int64) int64 { + var x int64 = 1 + for 2*x*(x+1)*(2*x+1) < neededApples { + x++ + } + return 8 * x +} +``` + +```ts +function minimumPerimeter(neededApples: number): number { + let x = 1; + while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { + ++x; + } + return 8 * x; +} +``` + + + +### 方法二:二分查找 + +我们也可以二分枚举 $n$,时间复杂度 $O(\log m)$。 + + + ```python class Solution: def minimumPerimeter(self, neededApples: int) -> int: @@ -115,22 +158,6 @@ class Solution: return l * 8 ``` -### **Java** - - - -```java -class Solution { - public long minimumPerimeter(long neededApples) { - long x = 1; - while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { - ++x; - } - return 8 * x; - } -} -``` - ```java class Solution { public long minimumPerimeter(long neededApples) { @@ -148,21 +175,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - long long minimumPerimeter(long long neededApples) { - long long x = 1; - while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { - ++x; - } - return 8 * x; - } -}; -``` - ```cpp class Solution { public: @@ -181,18 +193,6 @@ public: }; ``` -### **Go** - -```go -func minimumPerimeter(neededApples int64) int64 { - var x int64 = 1 - for 2*x*(x+1)*(2*x+1) < neededApples { - x++ - } - return 8 * x -} -``` - ```go func minimumPerimeter(neededApples int64) int64 { var l, r int64 = 1, 100000 @@ -208,18 +208,6 @@ func minimumPerimeter(neededApples int64) int64 { } ``` -### **TypeScript** - -```ts -function minimumPerimeter(neededApples: number): number { - let x = 1; - while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { - ++x; - } - return 8 * x; -} -``` - ```ts function minimumPerimeter(neededApples: number): number { let l = 1; @@ -236,10 +224,6 @@ function minimumPerimeter(neededApples: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/README_EN.md b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/README_EN.md index 90769733bbb90..f2c8a6b6003a8 100644 --- a/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/README_EN.md +++ b/solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/README_EN.md @@ -51,9 +51,9 @@ The perimeter is 2 * 4 = 8. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,6 +64,57 @@ class Solution: return x * 8 ``` +```java +class Solution { + public long minimumPerimeter(long neededApples) { + long x = 1; + while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { + ++x; + } + return 8 * x; + } +} +``` + +```cpp +class Solution { +public: + long long minimumPerimeter(long long neededApples) { + long long x = 1; + while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { + ++x; + } + return 8 * x; + } +}; +``` + +```go +func minimumPerimeter(neededApples int64) int64 { + var x int64 = 1 + for 2*x*(x+1)*(2*x+1) < neededApples { + x++ + } + return 8 * x +} +``` + +```ts +function minimumPerimeter(neededApples: number): number { + let x = 1; + while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { + ++x; + } + return 8 * x; +} +``` + + + +### Solution 2 + + + ```python class Solution: def minimumPerimeter(self, neededApples: int) -> int: @@ -77,20 +128,6 @@ class Solution: return l * 8 ``` -### **Java** - -```java -class Solution { - public long minimumPerimeter(long neededApples) { - long x = 1; - while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { - ++x; - } - return 8 * x; - } -} -``` - ```java class Solution { public long minimumPerimeter(long neededApples) { @@ -108,21 +145,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - long long minimumPerimeter(long long neededApples) { - long long x = 1; - while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { - ++x; - } - return 8 * x; - } -}; -``` - ```cpp class Solution { public: @@ -141,18 +163,6 @@ public: }; ``` -### **Go** - -```go -func minimumPerimeter(neededApples int64) int64 { - var x int64 = 1 - for 2*x*(x+1)*(2*x+1) < neededApples { - x++ - } - return 8 * x -} -``` - ```go func minimumPerimeter(neededApples int64) int64 { var l, r int64 = 1, 100000 @@ -168,18 +178,6 @@ func minimumPerimeter(neededApples int64) int64 { } ``` -### **TypeScript** - -```ts -function minimumPerimeter(neededApples: number): number { - let x = 1; - while (2 * x * (x + 1) * (2 * x + 1) < neededApples) { - ++x; - } - return 8 * x; -} -``` - ```ts function minimumPerimeter(neededApples: number): number { let l = 1; @@ -196,10 +194,6 @@ function minimumPerimeter(neededApples: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1955.Count Number of Special Subsequences/README.md b/solution/1900-1999/1955.Count Number of Special Subsequences/README.md index b8ec2d604a2bc..75a3592ff7401 100644 --- a/solution/1900-1999/1955.Count Number of Special Subsequences/README.md +++ b/solution/1900-1999/1955.Count Number of Special Subsequences/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示前 $i+1$ 个元素中,以 $j$ 结尾的特殊子序列的个数。初始时 $f[i][j]=0$,如果 $nums[0]=0$,则 $f[0][0]=1$。 @@ -94,10 +92,6 @@ $$ -### **Python3** - - - ```python class Solution: def countSpecialSubsequences(self, nums: List[int]) -> int: @@ -121,27 +115,6 @@ class Solution: return f[n - 1][2] ``` -```python -class Solution: - def countSpecialSubsequences(self, nums: List[int]) -> int: - mod = 10**9 + 7 - n = len(nums) - f = [0] * 3 - f[0] = nums[0] == 0 - for i in range(1, n): - if nums[i] == 0: - f[0] = (2 * f[0] + 1) % mod - elif nums[i] == 1: - f[1] = (f[0] + 2 * f[1]) % mod - else: - f[2] = (f[1] + 2 * f[2]) % mod - return f[2] -``` - -### **Java** - - - ```java class Solution { public int countSpecialSubsequences(int[] nums) { @@ -169,29 +142,6 @@ class Solution { } ``` -```java -class Solution { - public int countSpecialSubsequences(int[] nums) { - final int mod = (int) 1e9 + 7; - int n = nums.length; - int[] f = new int[3]; - f[0] = nums[0] == 0 ? 1 : 0; - for (int i = 1; i < n; ++i) { - if (nums[i] == 0) { - f[0] = (2 * f[0] % mod + 1) % mod; - } else if (nums[i] == 1) { - f[1] = (f[0] + 2 * f[1] % mod) % mod; - } else { - f[2] = (f[1] + 2 * f[2] % mod) % mod; - } - } - return f[2]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -221,30 +171,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countSpecialSubsequences(vector& nums) { - const int mod = 1e9 + 7; - int n = nums.size(); - int f[3]{0}; - f[0] = nums[0] == 0; - for (int i = 1; i < n; ++i) { - if (nums[i] == 0) { - f[0] = (2 * f[0] % mod + 1) % mod; - } else if (nums[i] == 1) { - f[1] = (f[0] + 2 * f[1] % mod) % mod; - } else { - f[2] = (f[1] + 2 * f[2] % mod) % mod; - } - } - return f[2]; - } -}; -``` - -### **Go** - ```go func countSpecialSubsequences(nums []int) int { const mod = 1e9 + 7 @@ -272,29 +198,6 @@ func countSpecialSubsequences(nums []int) int { } ``` -```go -func countSpecialSubsequences(nums []int) int { - const mod = 1e9 + 7 - n := len(nums) - f := [3]int{} - if nums[0] == 0 { - f[0] = 1 - } - for i := 1; i < n; i++ { - if nums[i] == 0 { - f[0] = (2*f[0] + 1) % mod - } else if nums[i] == 1 { - f[1] = (f[0] + 2*f[1]) % mod - } else { - f[2] = (f[1] + 2*f[2]) % mod - } - } - return f[2] -} -``` - -### **TypeScript** - ```ts function countSpecialSubsequences(nums: number[]): number { const mod = 1e9 + 7; @@ -322,6 +225,93 @@ function countSpecialSubsequences(nums: number[]): number { } ``` + + +### 方法二 + + + +```python +class Solution: + def countSpecialSubsequences(self, nums: List[int]) -> int: + mod = 10**9 + 7 + n = len(nums) + f = [0] * 3 + f[0] = nums[0] == 0 + for i in range(1, n): + if nums[i] == 0: + f[0] = (2 * f[0] + 1) % mod + elif nums[i] == 1: + f[1] = (f[0] + 2 * f[1]) % mod + else: + f[2] = (f[1] + 2 * f[2]) % mod + return f[2] +``` + +```java +class Solution { + public int countSpecialSubsequences(int[] nums) { + final int mod = (int) 1e9 + 7; + int n = nums.length; + int[] f = new int[3]; + f[0] = nums[0] == 0 ? 1 : 0; + for (int i = 1; i < n; ++i) { + if (nums[i] == 0) { + f[0] = (2 * f[0] % mod + 1) % mod; + } else if (nums[i] == 1) { + f[1] = (f[0] + 2 * f[1] % mod) % mod; + } else { + f[2] = (f[1] + 2 * f[2] % mod) % mod; + } + } + return f[2]; + } +} +``` + +```cpp +class Solution { +public: + int countSpecialSubsequences(vector& nums) { + const int mod = 1e9 + 7; + int n = nums.size(); + int f[3]{0}; + f[0] = nums[0] == 0; + for (int i = 1; i < n; ++i) { + if (nums[i] == 0) { + f[0] = (2 * f[0] % mod + 1) % mod; + } else if (nums[i] == 1) { + f[1] = (f[0] + 2 * f[1] % mod) % mod; + } else { + f[2] = (f[1] + 2 * f[2] % mod) % mod; + } + } + return f[2]; + } +}; +``` + +```go +func countSpecialSubsequences(nums []int) int { + const mod = 1e9 + 7 + n := len(nums) + f := [3]int{} + if nums[0] == 0 { + f[0] = 1 + } + for i := 1; i < n; i++ { + if nums[i] == 0 { + f[0] = (2*f[0] + 1) % mod + } else if nums[i] == 1 { + f[1] = (f[0] + 2*f[1]) % mod + } else { + f[2] = (f[1] + 2*f[2]) % mod + } + } + return f[2] +} +``` + ```ts function countSpecialSubsequences(nums: number[]): number { const mod = 1e9 + 7; @@ -347,10 +337,6 @@ function countSpecialSubsequences(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1955.Count Number of Special Subsequences/README_EN.md b/solution/1900-1999/1955.Count Number of Special Subsequences/README_EN.md index 2278c0ef728a2..037652124f95c 100644 --- a/solution/1900-1999/1955.Count Number of Special Subsequences/README_EN.md +++ b/solution/1900-1999/1955.Count Number of Special Subsequences/README_EN.md @@ -57,9 +57,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,25 +84,6 @@ class Solution: return f[n - 1][2] ``` -```python -class Solution: - def countSpecialSubsequences(self, nums: List[int]) -> int: - mod = 10**9 + 7 - n = len(nums) - f = [0] * 3 - f[0] = nums[0] == 0 - for i in range(1, n): - if nums[i] == 0: - f[0] = (2 * f[0] + 1) % mod - elif nums[i] == 1: - f[1] = (f[0] + 2 * f[1]) % mod - else: - f[2] = (f[1] + 2 * f[2]) % mod - return f[2] -``` - -### **Java** - ```java class Solution { public int countSpecialSubsequences(int[] nums) { @@ -130,29 +111,6 @@ class Solution { } ``` -```java -class Solution { - public int countSpecialSubsequences(int[] nums) { - final int mod = (int) 1e9 + 7; - int n = nums.length; - int[] f = new int[3]; - f[0] = nums[0] == 0 ? 1 : 0; - for (int i = 1; i < n; ++i) { - if (nums[i] == 0) { - f[0] = (2 * f[0] % mod + 1) % mod; - } else if (nums[i] == 1) { - f[1] = (f[0] + 2 * f[1] % mod) % mod; - } else { - f[2] = (f[1] + 2 * f[2] % mod) % mod; - } - } - return f[2]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -182,30 +140,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countSpecialSubsequences(vector& nums) { - const int mod = 1e9 + 7; - int n = nums.size(); - int f[3]{0}; - f[0] = nums[0] == 0; - for (int i = 1; i < n; ++i) { - if (nums[i] == 0) { - f[0] = (2 * f[0] % mod + 1) % mod; - } else if (nums[i] == 1) { - f[1] = (f[0] + 2 * f[1] % mod) % mod; - } else { - f[2] = (f[1] + 2 * f[2] % mod) % mod; - } - } - return f[2]; - } -}; -``` - -### **Go** - ```go func countSpecialSubsequences(nums []int) int { const mod = 1e9 + 7 @@ -233,29 +167,6 @@ func countSpecialSubsequences(nums []int) int { } ``` -```go -func countSpecialSubsequences(nums []int) int { - const mod = 1e9 + 7 - n := len(nums) - f := [3]int{} - if nums[0] == 0 { - f[0] = 1 - } - for i := 1; i < n; i++ { - if nums[i] == 0 { - f[0] = (2*f[0] + 1) % mod - } else if nums[i] == 1 { - f[1] = (f[0] + 2*f[1]) % mod - } else { - f[2] = (f[1] + 2*f[2]) % mod - } - } - return f[2] -} -``` - -### **TypeScript** - ```ts function countSpecialSubsequences(nums: number[]): number { const mod = 1e9 + 7; @@ -283,6 +194,93 @@ function countSpecialSubsequences(nums: number[]): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def countSpecialSubsequences(self, nums: List[int]) -> int: + mod = 10**9 + 7 + n = len(nums) + f = [0] * 3 + f[0] = nums[0] == 0 + for i in range(1, n): + if nums[i] == 0: + f[0] = (2 * f[0] + 1) % mod + elif nums[i] == 1: + f[1] = (f[0] + 2 * f[1]) % mod + else: + f[2] = (f[1] + 2 * f[2]) % mod + return f[2] +``` + +```java +class Solution { + public int countSpecialSubsequences(int[] nums) { + final int mod = (int) 1e9 + 7; + int n = nums.length; + int[] f = new int[3]; + f[0] = nums[0] == 0 ? 1 : 0; + for (int i = 1; i < n; ++i) { + if (nums[i] == 0) { + f[0] = (2 * f[0] % mod + 1) % mod; + } else if (nums[i] == 1) { + f[1] = (f[0] + 2 * f[1] % mod) % mod; + } else { + f[2] = (f[1] + 2 * f[2] % mod) % mod; + } + } + return f[2]; + } +} +``` + +```cpp +class Solution { +public: + int countSpecialSubsequences(vector& nums) { + const int mod = 1e9 + 7; + int n = nums.size(); + int f[3]{0}; + f[0] = nums[0] == 0; + for (int i = 1; i < n; ++i) { + if (nums[i] == 0) { + f[0] = (2 * f[0] % mod + 1) % mod; + } else if (nums[i] == 1) { + f[1] = (f[0] + 2 * f[1] % mod) % mod; + } else { + f[2] = (f[1] + 2 * f[2] % mod) % mod; + } + } + return f[2]; + } +}; +``` + +```go +func countSpecialSubsequences(nums []int) int { + const mod = 1e9 + 7 + n := len(nums) + f := [3]int{} + if nums[0] == 0 { + f[0] = 1 + } + for i := 1; i < n; i++ { + if nums[i] == 0 { + f[0] = (2*f[0] + 1) % mod + } else if nums[i] == 1 { + f[1] = (f[0] + 2*f[1]) % mod + } else { + f[2] = (f[1] + 2*f[2]) % mod + } + } + return f[2] +} +``` + ```ts function countSpecialSubsequences(nums: number[]): number { const mod = 1e9 + 7; @@ -308,10 +306,6 @@ function countSpecialSubsequences(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1956.Minimum Time For K Virus Variants to Spread/README.md b/solution/1900-1999/1956.Minimum Time For K Virus Variants to Spread/README.md index 111d0cf7b11d1..a5e388fbe6f7e 100644 --- a/solution/1900-1999/1956.Minimum Time For K Virus Variants to Spread/README.md +++ b/solution/1900-1999/1956.Minimum Time For K Virus Variants to Spread/README.md @@ -58,30 +58,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1956.Minimum Time For K Virus Variants to Spread/README_EN.md b/solution/1900-1999/1956.Minimum Time For K Virus Variants to Spread/README_EN.md index 0fb88ade06eef..a97ca7d205156 100644 --- a/solution/1900-1999/1956.Minimum Time For K Virus Variants to Spread/README_EN.md +++ b/solution/1900-1999/1956.Minimum Time For K Virus Variants to Spread/README_EN.md @@ -48,24 +48,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1957.Delete Characters to Make Fancy String/README.md b/solution/1900-1999/1957.Delete Characters to Make Fancy String/README.md index debbb18968f43..1e1a153deaac7 100644 --- a/solution/1900-1999/1957.Delete Characters to Make Fancy String/README.md +++ b/solution/1900-1999/1957.Delete Characters to Make Fancy String/README.md @@ -54,14 +54,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def makeFancyString(self, s: str) -> str: @@ -73,10 +69,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String makeFancyString(String s) { @@ -93,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +100,6 @@ public: }; ``` -### **Go** - ```go func makeFancyString(s string) string { ans := []rune{} @@ -126,8 +114,6 @@ func makeFancyString(s string) string { } ``` -### **PHP** - ```php class Solution { /** @@ -148,10 +134,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1957.Delete Characters to Make Fancy String/README_EN.md b/solution/1900-1999/1957.Delete Characters to Make Fancy String/README_EN.md index 2042735d31cf0..61cd6c68ba9b4 100644 --- a/solution/1900-1999/1957.Delete Characters to Make Fancy String/README_EN.md +++ b/solution/1900-1999/1957.Delete Characters to Make Fancy String/README_EN.md @@ -50,9 +50,9 @@ No three consecutive characters are equal, so return "aabaa". ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String makeFancyString(String s) { @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +96,6 @@ public: }; ``` -### **Go** - ```go func makeFancyString(s string) string { ans := []rune{} @@ -116,8 +110,6 @@ func makeFancyString(s string) string { } ``` -### **PHP** - ```php class Solution { /** @@ -138,10 +130,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1958.Check if Move is Legal/README.md b/solution/1900-1999/1958.Check if Move is Legal/README.md index 6e50d4c9dc2c1..23d20e59727ea 100644 --- a/solution/1900-1999/1958.Check if Move is Legal/README.md +++ b/solution/1900-1999/1958.Check if Move is Legal/README.md @@ -50,14 +50,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def checkMove( @@ -78,10 +74,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { private static final int[][] DIRS @@ -110,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +126,6 @@ public: }; ``` -### **Go** - ```go func checkMove(board [][]byte, rMove int, cMove int, color byte) bool { dirs := [8][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}} @@ -162,10 +150,6 @@ func checkMove(board [][]byte, rMove int, cMove int, color byte) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1958.Check if Move is Legal/README_EN.md b/solution/1900-1999/1958.Check if Move is Legal/README_EN.md index 80a4056f24c0d..a9b69e016e0a3 100644 --- a/solution/1900-1999/1958.Check if Move is Legal/README_EN.md +++ b/solution/1900-1999/1958.Check if Move is Legal/README_EN.md @@ -42,9 +42,9 @@ The two good lines with the chosen cell as an endpoint are annotated above with ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { private static final int[][] DIRS @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +118,6 @@ public: }; ``` -### **Go** - ```go func checkMove(board [][]byte, rMove int, cMove int, color byte) bool { dirs := [8][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}} @@ -148,10 +142,6 @@ func checkMove(board [][]byte, rMove int, cMove int, color byte) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1959.Minimum Total Space Wasted With K Resizing Operations/README.md b/solution/1900-1999/1959.Minimum Total Space Wasted With K Resizing Operations/README.md index d49d2b78d6139..63036eb433d0e 100644 --- a/solution/1900-1999/1959.Minimum Total Space Wasted With K Resizing Operations/README.md +++ b/solution/1900-1999/1959.Minimum Total Space Wasted With K Resizing Operations/README.md @@ -55,16 +55,10 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 -### **Python3** - - - ```python class Solution: def minSpaceWastedKResizing(self, nums: List[int], k: int) -> int: @@ -86,10 +80,6 @@ class Solution: return f[-1][-1] ``` -### **Java** - - - ```java class Solution { public int minSpaceWastedKResizing(int[] nums, int k) { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func minSpaceWastedKResizing(nums []int, k int) int { k++ @@ -192,10 +178,6 @@ func minSpaceWastedKResizing(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1959.Minimum Total Space Wasted With K Resizing Operations/README_EN.md b/solution/1900-1999/1959.Minimum Total Space Wasted With K Resizing Operations/README_EN.md index 12c707103475a..ba3b8149b390e 100644 --- a/solution/1900-1999/1959.Minimum Total Space Wasted With K Resizing Operations/README_EN.md +++ b/solution/1900-1999/1959.Minimum Total Space Wasted With K Resizing Operations/README_EN.md @@ -54,9 +54,9 @@ The total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,8 +79,6 @@ class Solution: return f[-1][-1] ``` -### **Java** - ```java class Solution { public int minSpaceWastedKResizing(int[] nums, int k) { @@ -113,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +141,6 @@ public: }; ``` -### **Go** - ```go func minSpaceWastedKResizing(nums []int, k int) int { k++ @@ -183,10 +177,6 @@ func minSpaceWastedKResizing(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1960.Maximum Product of the Length of Two Palindromic Substrings/README.md b/solution/1900-1999/1960.Maximum Product of the Length of Two Palindromic Substrings/README.md index b53f5432eba97..7a3d4e8f4d1ad 100644 --- a/solution/1900-1999/1960.Maximum Product of the Length of Two Palindromic Substrings/README.md +++ b/solution/1900-1999/1960.Maximum Product of the Length of Two Palindromic Substrings/README.md @@ -43,30 +43,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1960.Maximum Product of the Length of Two Palindromic Substrings/README_EN.md b/solution/1900-1999/1960.Maximum Product of the Length of Two Palindromic Substrings/README_EN.md index b6ef0ebc06329..3d1966239ed5d 100644 --- a/solution/1900-1999/1960.Maximum Product of the Length of Two Palindromic Substrings/README_EN.md +++ b/solution/1900-1999/1960.Maximum Product of the Length of Two Palindromic Substrings/README_EN.md @@ -39,24 +39,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/1900-1999/1961.Check If String Is a Prefix of Array/README.md b/solution/1900-1999/1961.Check If String Is a Prefix of Array/README.md index c64a6e4eaca52..52e4a9c1a1727 100644 --- a/solution/1900-1999/1961.Check If String Is a Prefix of Array/README.md +++ b/solution/1900-1999/1961.Check If String Is a Prefix of Array/README.md @@ -44,9 +44,7 @@ s 可以由 "i"、"love" 和 "leetcode" 相连得到。 ## 解法 - - -**方法一:遍历** +### 方法一:遍历 我们遍历数组 $words$,用一个变量 $t$ 记录当前已经拼接的字符串,如果 $t$ 的长度大于 $s$ 的长度,说明 $s$ 不是 $words$ 的前缀字符串,返回 $false$;如果 $t$ 的长度等于 $s$ 的长度,返回 $t$ 是否等于 $s$。 @@ -56,10 +54,6 @@ s 可以由 "i"、"love" 和 "leetcode" 相连得到。 -### **Python3** - - - ```python class Solution: def isPrefixString(self, s: str, words: List[str]) -> bool: @@ -71,10 +65,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean isPrefixString(String s, String[] words) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func isPrefixString(s string, words []string) bool { t := strings.Builder{} @@ -132,8 +118,6 @@ func isPrefixString(s string, words []string) bool { } ``` -### **TypeScript** - ```ts function isPrefixString(s: string, words: string[]): boolean { const t: string[] = []; @@ -153,10 +137,6 @@ function isPrefixString(s: string, words: string[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1961.Check If String Is a Prefix of Array/README_EN.md b/solution/1900-1999/1961.Check If String Is a Prefix of Array/README_EN.md index e0aef0a3c8277..34beb5cd63c03 100644 --- a/solution/1900-1999/1961.Check If String Is a Prefix of Array/README_EN.md +++ b/solution/1900-1999/1961.Check If String Is a Prefix of Array/README_EN.md @@ -40,7 +40,7 @@ It is impossible to make s using a prefix of arr. ## Solutions -**Solution 1: Traversal** +### Solution 1: Traversal We traverse the array $words$, using a variable $t$ to record the currently concatenated string. If the length of $t$ is greater than the length of $s$, it means that $s$ is not a prefix string of $words$, so we return $false$; if the length of $t$ is equal to the length of $s$, we return whether $t$ is equal to $s$. @@ -50,8 +50,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def isPrefixString(self, s: str, words: List[str]) -> bool: @@ -63,8 +61,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean isPrefixString(String s, String[] words) { @@ -83,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +98,6 @@ public: }; ``` -### **Go** - ```go func isPrefixString(s string, words []string) bool { t := strings.Builder{} @@ -122,8 +114,6 @@ func isPrefixString(s string, words []string) bool { } ``` -### **TypeScript** - ```ts function isPrefixString(s: string, words: string[]): boolean { const t: string[] = []; @@ -143,10 +133,6 @@ function isPrefixString(s: string, words: string[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1962.Remove Stones to Minimize the Total/README.md b/solution/1900-1999/1962.Remove Stones to Minimize the Total/README.md index 4af062eb390c5..4d5b8e343ff15 100644 --- a/solution/1900-1999/1962.Remove Stones to Minimize the Total/README.md +++ b/solution/1900-1999/1962.Remove Stones to Minimize the Total/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列(大根堆)** +### 方法一:贪心 + 优先队列(大根堆) 根据题目描述,为了使得剩下的石子总数最小,我们需要尽可能多地移除石子堆中的石子。因此,每次应该选择数量最多的石子堆进行移除。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def minStoneSum(self, piles: List[int], k: int) -> int: @@ -85,10 +79,6 @@ class Solution: return -sum(pq) ``` -### **Java** - - - ```java class Solution { public int minStoneSum(int[] piles, int k) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func minStoneSum(piles []int, k int) (ans int) { pq := &hp{piles} @@ -164,8 +150,6 @@ func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) } ``` -### **TypeScript** - ```ts function minStoneSum(piles: number[], k: number): number { const pq = new MaxPriorityQueue(); @@ -184,10 +168,6 @@ function minStoneSum(piles: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1962.Remove Stones to Minimize the Total/README_EN.md b/solution/1900-1999/1962.Remove Stones to Minimize the Total/README_EN.md index be8a372b5f73a..9998be1aa3b5a 100644 --- a/solution/1900-1999/1962.Remove Stones to Minimize the Total/README_EN.md +++ b/solution/1900-1999/1962.Remove Stones to Minimize the Total/README_EN.md @@ -51,7 +51,7 @@ The total number of stones in [2,3,3,4] is 12. ## Solutions -**Solution 1: Greedy + Priority Queue (Max Heap)** +### Solution 1: Greedy + Priority Queue (Max Heap) According to the problem description, in order to minimize the total number of remaining stones, we need to remove as many stones as possible from the stone piles. Therefore, we should always choose the pile with the most stones for removal. @@ -65,8 +65,6 @@ The time complexity is $O(n + k \times \log n)$, and the space complexity is $O( -### **Python3** - ```python class Solution: def minStoneSum(self, piles: List[int], k: int) -> int: @@ -77,8 +75,6 @@ class Solution: return -sum(pq) ``` -### **Java** - ```java class Solution { public int minStoneSum(int[] piles, int k) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +118,6 @@ public: }; ``` -### **Go** - ```go func minStoneSum(piles []int, k int) (ans int) { pq := &hp{piles} @@ -154,8 +146,6 @@ func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) } ``` -### **TypeScript** - ```ts function minStoneSum(piles: number[], k: number): number { const pq = new MaxPriorityQueue(); @@ -174,10 +164,6 @@ function minStoneSum(piles: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/README.md b/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/README.md index 225b53785b43a..c68f8cab76354 100644 --- a/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/README.md +++ b/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们用一个变量 $x$ 记录当前未匹配的左括号的数量,遍历字符串 $s$,对于每个字符 $c$: @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def minSwaps(self, s: str) -> int: @@ -95,10 +89,6 @@ class Solution: return (x + 1) >> 1 ``` -### **Java** - - - ```java class Solution { public int minSwaps(String s) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func minSwaps(s string) int { x := 0 @@ -151,8 +137,6 @@ func minSwaps(s string) int { } ``` -### **TypeScript** - ```ts function minSwaps(s: string): number { let x = 0; @@ -167,10 +151,6 @@ function minSwaps(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/README_EN.md b/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/README_EN.md index 7214ceba134d7..32c1605342369 100644 --- a/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/README_EN.md +++ b/solution/1900-1999/1963.Minimum Number of Swaps to Make the String Balanced/README_EN.md @@ -60,7 +60,7 @@ The resulting string is "[[][]]". ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy We use a variable $x$ to record the current number of unmatched left brackets. We traverse the string $s$, for each character $c$: @@ -73,8 +73,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. The sp -### **Python3** - ```python class Solution: def minSwaps(self, s: str) -> int: @@ -87,8 +85,6 @@ class Solution: return (x + 1) >> 1 ``` -### **Java** - ```java class Solution { public int minSwaps(String s) { @@ -106,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +119,6 @@ public: }; ``` -### **Go** - ```go func minSwaps(s string) int { x := 0 @@ -141,8 +133,6 @@ func minSwaps(s string) int { } ``` -### **TypeScript** - ```ts function minSwaps(s: string): number { let x = 0; @@ -157,10 +147,6 @@ function minSwaps(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/README.md b/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/README.md index 997ba82649317..f58e62e8c9c44 100644 --- a/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/README.md +++ b/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/README.md @@ -70,9 +70,7 @@ ## 解法 - - -**方法一:树状数组** +### 方法一:树状数组 我们可以用树状数组维护一个最长递增子序列的长度数组。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class BinaryIndexedTree: __slots__ = ["n", "c"] @@ -120,10 +114,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class BinaryIndexedTree { private int n; @@ -169,8 +159,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { private: @@ -220,8 +208,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -261,8 +247,6 @@ func longestObstacleCourseAtEachPosition(obstacles []int) (ans []int) { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -317,10 +301,6 @@ function longestObstacleCourseAtEachPosition(obstacles: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/README_EN.md b/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/README_EN.md index 6c5b3512f928e..a246128b88894 100644 --- a/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/README_EN.md +++ b/solution/1900-1999/1964.Find the Longest Valid Obstacle Course at Each Position/README_EN.md @@ -66,7 +66,7 @@ ## Solutions -**Solution 1: Binary Indexed Tree (Fenwick Tree)** +### Solution 1: Binary Indexed Tree (Fenwick Tree) We can use a Binary Indexed Tree to maintain an array of the lengths of the longest increasing subsequences. @@ -76,8 +76,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class BinaryIndexedTree: __slots__ = ["n", "c"] @@ -112,8 +110,6 @@ class Solution: return ans ``` -### **Java** - ```java class BinaryIndexedTree { private int n; @@ -159,8 +155,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { private: @@ -210,8 +204,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -251,8 +243,6 @@ func longestObstacleCourseAtEachPosition(obstacles []int) (ans []int) { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -307,10 +297,6 @@ function longestObstacleCourseAtEachPosition(obstacles: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1965.Employees With Missing Information/README.md b/solution/1900-1999/1965.Employees With Missing Information/README.md index 32b09d9782d97..61a428642bd6e 100644 --- a/solution/1900-1999/1965.Employees With Missing Information/README.md +++ b/solution/1900-1999/1965.Employees With Missing Information/README.md @@ -81,18 +81,12 @@ Salaries table: ## 解法 - - -**方法一:子查询 + 合并** +### 方法一:子查询 + 合并 我们可以先从 `Employees` 表中找出所有不在 `Salaries` 表中的 `employee_id`,再从 `Salaries` 表中找出所有不在 `Employees` 表中的 `employee_id`,最后将两个结果合并,然后按照 `employee_id` 排序即可。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT employee_id @@ -106,3 +100,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1900-1999/1965.Employees With Missing Information/README_EN.md b/solution/1900-1999/1965.Employees With Missing Information/README_EN.md index d44c57e0074b2..e7c253bced536 100644 --- a/solution/1900-1999/1965.Employees With Missing Information/README_EN.md +++ b/solution/1900-1999/1965.Employees With Missing Information/README_EN.md @@ -81,14 +81,12 @@ The salary of employee 2 is missing. ## Solutions -**Solution 1: Subquery + Union** +### Solution 1: Subquery + Union We can first find all `employee_id` that are not in the `Salaries` table from the `Employees` table, and then find all `employee_id` that are not in the `Employees` table from the `Salaries` table. Finally, we can combine the two results using the `UNION` operator, and sort the result by `employee_id`. -### **SQL** - ```sql # Write your MySQL query statement below SELECT employee_id @@ -102,3 +100,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1900-1999/1966.Binary Searchable Numbers in an Unsorted Array/README.md b/solution/1900-1999/1966.Binary Searchable Numbers in an Unsorted Array/README.md index bb83f9433fae7..450d129b03bbd 100644 --- a/solution/1900-1999/1966.Binary Searchable Numbers in an Unsorted Array/README.md +++ b/solution/1900-1999/1966.Binary Searchable Numbers in an Unsorted Array/README.md @@ -72,9 +72,7 @@ func(sequence, target) ## 解法 - - -**方法一:维护前缀最大值和后缀最小值** +### 方法一:维护前缀最大值和后缀最小值 我们注意到,对于数组中的每个元素,如果它是可被二分搜索的,那么需要满足两个条件: @@ -93,10 +91,6 @@ func(sequence, target) -### **Python3** - - - ```python class Solution: def binarySearchableNumbers(self, nums: List[int]) -> int: @@ -116,10 +110,6 @@ class Solution: return sum(ok) ``` -### **Java** - - - ```java class Solution { public int binarySearchableNumbers(int[] nums) { @@ -146,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -174,8 +162,6 @@ public: }; ``` -### **Go** - ```go func binarySearchableNumbers(nums []int) (ans int) { n := len(nums) @@ -203,10 +189,6 @@ func binarySearchableNumbers(nums []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1966.Binary Searchable Numbers in an Unsorted Array/README_EN.md b/solution/1900-1999/1966.Binary Searchable Numbers in an Unsorted Array/README_EN.md index 63ce52c76efe6..2f86a059cecab 100644 --- a/solution/1900-1999/1966.Binary Searchable Numbers in an Unsorted Array/README_EN.md +++ b/solution/1900-1999/1966.Binary Searchable Numbers in an Unsorted Array/README_EN.md @@ -68,9 +68,9 @@ Because only -1 is guaranteed to be found, you should return 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -91,8 +91,6 @@ class Solution: return sum(ok) ``` -### **Java** - ```java class Solution { public int binarySearchableNumbers(int[] nums) { @@ -119,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +143,6 @@ public: }; ``` -### **Go** - ```go func binarySearchableNumbers(nums []int) (ans int) { n := len(nums) @@ -176,10 +170,6 @@ func binarySearchableNumbers(nums []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1967.Number of Strings That Appear as Substrings in Word/README.md b/solution/1900-1999/1967.Number of Strings That Appear as Substrings in Word/README.md index 6bd5c52b60d9f..941d7e5a6cb25 100644 --- a/solution/1900-1999/1967.Number of Strings That Appear as Substrings in Word/README.md +++ b/solution/1900-1999/1967.Number of Strings That Appear as Substrings in Word/README.md @@ -58,9 +58,7 @@ patterns 中有 2 个字符串作为子字符串出现在 word 中。 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 遍历字符串数组 $patterns$ 中的每个字符串 $p$,判断其是否为 $word$ 的子字符串,如果是,答案加一。 @@ -70,20 +68,12 @@ patterns 中有 2 个字符串作为子字符串出现在 word 中。 -### **Python3** - - - ```python class Solution: def numOfStrings(self, patterns: List[str], word: str) -> int: return sum(p in word for p in patterns) ``` -### **Java** - - - ```java class Solution { public int numOfStrings(String[] patterns, String word) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func numOfStrings(patterns []string, word string) (ans int) { for _, p := range patterns { @@ -126,8 +112,6 @@ func numOfStrings(patterns []string, word string) (ans int) { } ``` -### **TypeScript** - ```ts function numOfStrings(patterns: string[], word: string): number { let ans = 0; @@ -140,10 +124,6 @@ function numOfStrings(patterns: string[], word: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1967.Number of Strings That Appear as Substrings in Word/README_EN.md b/solution/1900-1999/1967.Number of Strings That Appear as Substrings in Word/README_EN.md index 33409da15d47a..09f10e54b2be2 100644 --- a/solution/1900-1999/1967.Number of Strings That Appear as Substrings in Word/README_EN.md +++ b/solution/1900-1999/1967.Number of Strings That Appear as Substrings in Word/README_EN.md @@ -54,9 +54,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return sum(p in word for p in patterns) ``` -### **Java** - ```java class Solution { public int numOfStrings(String[] patterns, String word) { @@ -80,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +91,6 @@ public: }; ``` -### **Go** - ```go func numOfStrings(patterns []string, word string) (ans int) { for _, p := range patterns { @@ -108,8 +102,6 @@ func numOfStrings(patterns []string, word string) (ans int) { } ``` -### **TypeScript** - ```ts function numOfStrings(patterns: string[], word: string): number { let ans = 0; @@ -122,10 +114,6 @@ function numOfStrings(patterns: string[], word: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1968.Array With Elements Not Equal to Average of Neighbors/README.md b/solution/1900-1999/1968.Array With Elements Not Equal to Average of Neighbors/README.md index 21190708acf44..27fce2f3d9d57 100644 --- a/solution/1900-1999/1968.Array With Elements Not Equal to Average of Neighbors/README.md +++ b/solution/1900-1999/1968.Array With Elements Not Equal to Average of Neighbors/README.md @@ -45,18 +45,10 @@ i=3, nums[i] = 2, 两相邻元素平均值为 (6+0) / 2 = 3 ## 解法 - - -**方法一:排序** - -**方法二:随机打乱** +### 方法一:排序 -### **Python3** - - - ```python class Solution: def rearrangeArray(self, nums: List[int]) -> List[int]: @@ -71,10 +63,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] rearrangeArray(int[] nums) { @@ -93,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +98,6 @@ public: }; ``` -### **Go** - ```go func rearrangeArray(nums []int) []int { sort.Ints(nums) @@ -130,6 +114,12 @@ func rearrangeArray(nums []int) []int { } ``` + + +### 方法二:随机打乱 + + + ```go func rearrangeArray(nums []int) []int { rand.Seed(time.Now().UnixNano()) @@ -146,10 +136,6 @@ outer: } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1968.Array With Elements Not Equal to Average of Neighbors/README_EN.md b/solution/1900-1999/1968.Array With Elements Not Equal to Average of Neighbors/README_EN.md index 3c2c69f0ddd25..8fed95c756f0c 100644 --- a/solution/1900-1999/1968.Array With Elements Not Equal to Average of Neighbors/README_EN.md +++ b/solution/1900-1999/1968.Array With Elements Not Equal to Average of Neighbors/README_EN.md @@ -43,9 +43,9 @@ When i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] rearrangeArray(int[] nums) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +96,6 @@ public: }; ``` -### **Go** - ```go func rearrangeArray(nums []int) []int { sort.Ints(nums) @@ -118,6 +112,12 @@ func rearrangeArray(nums []int) []int { } ``` + + +### Solution 2 + + + ```go func rearrangeArray(nums []int) []int { rand.Seed(time.Now().UnixNano()) @@ -134,10 +134,6 @@ outer: } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/README.md b/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/README.md index d66ff947fdd5c..91c75cb8dff70 100644 --- a/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/README.md +++ b/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:贪心 + 快速幂** +### 方法一:贪心 + 快速幂 我们注意到,每一次操作,并不会改变元素的和,而在元素和不变的情况下,要想使得乘积最小,应该尽可能最大化元素的差值。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def minNonZeroProduct(self, p: int) -> int: @@ -88,10 +82,6 @@ class Solution: return (2**p - 1) * pow(2**p - 2, 2 ** (p - 1) - 1, mod) % mod ``` -### **Java** - - - ```java class Solution { public int minNonZeroProduct(int p) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +127,6 @@ public: }; ``` -### **Go** - ```go func minNonZeroProduct(p int) int { const mod int = 1e9 + 7 @@ -160,8 +146,6 @@ func minNonZeroProduct(p int) int { } ``` -### **TypeScript** - ```ts function minNonZeroProduct(p: number): number { const mod = BigInt(1e9 + 7); @@ -182,10 +166,6 @@ function minNonZeroProduct(p: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/README_EN.md b/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/README_EN.md index 769a4190727ad..b418273189a7a 100644 --- a/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/README_EN.md +++ b/solution/1900-1999/1969.Minimum Non-Zero Product of the Array Elements/README_EN.md @@ -59,9 +59,9 @@ The array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum poss ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return (2**p - 1) * pow(2**p - 2, 2 ** (p - 1) - 1, mod) % mod ``` -### **Java** - ```java class Solution { public int minNonZeroProduct(int p) { @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +115,6 @@ public: }; ``` -### **Go** - ```go func minNonZeroProduct(p int) int { const mod int = 1e9 + 7 @@ -140,8 +134,6 @@ func minNonZeroProduct(p int) int { } ``` -### **TypeScript** - ```ts function minNonZeroProduct(p: number): number { const mod = BigInt(1e9 + 7); @@ -162,10 +154,6 @@ function minNonZeroProduct(p: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1970.Last Day Where You Can Still Cross/README.md b/solution/1900-1999/1970.Last Day Where You Can Still Cross/README.md index 4a3e4ce562dd6..55ff7f7df8dd2 100644 --- a/solution/1900-1999/1970.Last Day Where You Can Still Cross/README.md +++ b/solution/1900-1999/1970.Last Day Where You Can Still Cross/README.md @@ -55,81 +55,10 @@ ## 解法 - - -逆序并查集。 - -并查集模板: - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` +### 方法一 -### **Python3** - - - ```python class Solution: def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int: @@ -161,10 +90,6 @@ class Solution: return 0 ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -217,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -260,8 +183,6 @@ public: }; ``` -### **Go** - ```go var p []int @@ -310,10 +231,6 @@ func find(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1970.Last Day Where You Can Still Cross/README_EN.md b/solution/1900-1999/1970.Last Day Where You Can Still Cross/README_EN.md index 2e4f33d28254b..3152748442d76 100644 --- a/solution/1900-1999/1970.Last Day Where You Can Still Cross/README_EN.md +++ b/solution/1900-1999/1970.Last Day Where You Can Still Cross/README_EN.md @@ -54,9 +54,9 @@ The last day where it is possible to cross from top to bottom is on day 3. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -89,10 +89,6 @@ class Solution: return 0 ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -145,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -188,8 +182,6 @@ public: }; ``` -### **Go** - ```go var p []int @@ -238,10 +230,6 @@ func find(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1971.Find if Path Exists in Graph/README.md b/solution/1900-1999/1971.Find if Path Exists in Graph/README.md index 3b69685d40323..ef806aa1167eb 100644 --- a/solution/1900-1999/1971.Find if Path Exists in Graph/README.md +++ b/solution/1900-1999/1971.Find if Path Exists in Graph/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们先将 `edges` 转换成邻接表 $g$,然后使用 DFS,判断是否存在从 `source` 到 `destination` 的路径。 @@ -59,7 +57,148 @@ 时间复杂度 $O(n + m)$,其中 $n$ 和 $m$ 分别是节点数和边数。 -**方法二:并查集** + + +```python +class Solution: + def validPath( + self, n: int, edges: List[List[int]], source: int, destination: int + ) -> bool: + def dfs(i): + if i == destination: + return True + vis.add(i) + for j in g[i]: + if j not in vis and dfs(j): + return True + return False + + g = defaultdict(list) + for a, b in edges: + g[a].append(b) + g[b].append(a) + vis = set() + return dfs(source) +``` + +```java +class Solution { + private boolean[] vis; + private List[] g; + + public boolean validPath(int n, int[][] edges, int source, int destination) { + vis = new boolean[n]; + g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (var e : edges) { + int a = e[0], b = e[1]; + g[a].add(b); + g[b].add(a); + } + return dfs(source, destination); + } + + private boolean dfs(int source, int destination) { + if (source == destination) { + return true; + } + vis[source] = true; + for (int nxt : g[source]) { + if (!vis[nxt] && dfs(nxt, destination)) { + return true; + } + } + return false; + } +} +``` + +```cpp +class Solution { +public: + bool validPath(int n, vector>& edges, int source, int destination) { + vector vis(n); + vector> g(n); + for (auto& e : edges) { + int a = e[0], b = e[1]; + g[a].emplace_back(b); + g[b].emplace_back(a); + } + function dfs = [&](int i) -> bool { + if (i == destination) return true; + vis[i] = true; + for (int& j : g[i]) { + if (!vis[j] && dfs(j)) { + return true; + } + } + return false; + }; + return dfs(source); + } +}; +``` + +```go +func validPath(n int, edges [][]int, source int, destination int) bool { + vis := make([]bool, n) + g := make([][]int, n) + for _, e := range edges { + a, b := e[0], e[1] + g[a] = append(g[a], b) + g[b] = append(g[b], a) + } + var dfs func(int) bool + dfs = func(i int) bool { + if i == destination { + return true + } + vis[i] = true + for _, j := range g[i] { + if !vis[j] && dfs(j) { + return true + } + } + return false + } + return dfs(source) +} +``` + +```rust +impl Solution { + pub fn valid_path(n: i32, edges: Vec>, source: i32, destination: i32) -> bool { + let mut disjoint_set: Vec = vec![0; n as usize]; + // Initialize the set + for i in 0..n { + disjoint_set[i as usize] = i; + } + + // Traverse the edges + for p_vec in &edges { + let parent_one = Solution::find(p_vec[0], &mut disjoint_set); + let parent_two = Solution::find(p_vec[1], &mut disjoint_set); + disjoint_set[parent_one as usize] = parent_two; + } + + let p_s = Solution::find(source, &mut disjoint_set); + let p_d = Solution::find(destination, &mut disjoint_set); + + p_s == p_d + } + + pub fn find(x: i32, d_set: &mut Vec) -> i32 { + if d_set[x as usize] != x { + d_set[x as usize] = Solution::find(d_set[x as usize], d_set); + } + d_set[x as usize] + } +} +``` + + + +### 方法二:并查集 判断图中两个节点是否连通,一种比较简单直接的方法是使用并查集。 @@ -180,32 +319,6 @@ func union(a, b int) { -### **Python3** - - - -```python -class Solution: - def validPath( - self, n: int, edges: List[List[int]], source: int, destination: int - ) -> bool: - def dfs(i): - if i == destination: - return True - vis.add(i) - for j in g[i]: - if j not in vis and dfs(j): - return True - return False - - g = defaultdict(list) - for a, b in edges: - g[a].append(b) - g[b].append(a) - vis = set() - return dfs(source) -``` - ```python class Solution: def validPath( @@ -222,42 +335,6 @@ class Solution: return find(source) == find(destination) ``` -### **Java** - - - -```java -class Solution { - private boolean[] vis; - private List[] g; - - public boolean validPath(int n, int[][] edges, int source, int destination) { - vis = new boolean[n]; - g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (var e : edges) { - int a = e[0], b = e[1]; - g[a].add(b); - g[b].add(a); - } - return dfs(source, destination); - } - - private boolean dfs(int source, int destination) { - if (source == destination) { - return true; - } - vis[source] = true; - for (int nxt : g[source]) { - if (!vis[nxt] && dfs(nxt, destination)) { - return true; - } - } - return false; - } -} -``` - ```java class Solution { private int[] p; @@ -282,34 +359,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool validPath(int n, vector>& edges, int source, int destination) { - vector vis(n); - vector> g(n); - for (auto& e : edges) { - int a = e[0], b = e[1]; - g[a].emplace_back(b); - g[b].emplace_back(a); - } - function dfs = [&](int i) -> bool { - if (i == destination) return true; - vis[i] = true; - for (int& j : g[i]) { - if (!vis[j] && dfs(j)) { - return true; - } - } - return false; - }; - return dfs(source); - } -}; -``` - ```cpp class Solution { public: @@ -326,67 +375,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - pub fn valid_path(n: i32, edges: Vec>, source: i32, destination: i32) -> bool { - let mut disjoint_set: Vec = vec![0; n as usize]; - // Initialize the set - for i in 0..n { - disjoint_set[i as usize] = i; - } - - // Traverse the edges - for p_vec in &edges { - let parent_one = Solution::find(p_vec[0], &mut disjoint_set); - let parent_two = Solution::find(p_vec[1], &mut disjoint_set); - disjoint_set[parent_one as usize] = parent_two; - } - - let p_s = Solution::find(source, &mut disjoint_set); - let p_d = Solution::find(destination, &mut disjoint_set); - - p_s == p_d - } - - pub fn find(x: i32, d_set: &mut Vec) -> i32 { - if d_set[x as usize] != x { - d_set[x as usize] = Solution::find(d_set[x as usize], d_set); - } - d_set[x as usize] - } -} -``` - -### **Go** - -```go -func validPath(n int, edges [][]int, source int, destination int) bool { - vis := make([]bool, n) - g := make([][]int, n) - for _, e := range edges { - a, b := e[0], e[1] - g[a] = append(g[a], b) - g[b] = append(g[b], a) - } - var dfs func(int) bool - dfs = func(i int) bool { - if i == destination { - return true - } - vis[i] = true - for _, j := range g[i] { - if !vis[j] && dfs(j) { - return true - } - } - return false - } - return dfs(source) -} -``` - ```go func validPath(n int, edges [][]int, source int, destination int) bool { p := make([]int, n) @@ -407,10 +395,6 @@ func validPath(n int, edges [][]int, source int, destination int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1971.Find if Path Exists in Graph/README_EN.md b/solution/1900-1999/1971.Find if Path Exists in Graph/README_EN.md index deae972d73c75..97fce3782ac66 100644 --- a/solution/1900-1999/1971.Find if Path Exists in Graph/README_EN.md +++ b/solution/1900-1999/1971.Find if Path Exists in Graph/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,24 +71,6 @@ class Solution: return dfs(source) ``` -```python -class Solution: - def validPath( - self, n: int, edges: List[List[int]], source: int, destination: int - ) -> bool: - def find(x): - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - p = list(range(n)) - for u, v in edges: - p[find(u)] = find(v) - return find(source) == find(destination) -``` - -### **Java** - ```java class Solution { private boolean[] vis; @@ -121,32 +103,6 @@ class Solution { } ``` -```java -class Solution { - private int[] p; - - public boolean validPath(int n, int[][] edges, int source, int destination) { - p = new int[n]; - for (int i = 0; i < n; ++i) { - p[i] = i; - } - for (int[] e : edges) { - p[find(e[0])] = find(e[1]); - } - return find(source) == find(destination); - } - - private int find(int x) { - if (p[x] != x) { - p[x] = find(p[x]); - } - return p[x]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -173,24 +129,32 @@ public: }; ``` -```cpp -class Solution { -public: - bool validPath(int n, vector>& edges, int source, int destination) { - vector p(n); - iota(p.begin(), p.end(), 0); - function find = [&](int x) -> int { - if (p[x] != x) p[x] = find(p[x]); - return p[x]; - }; - for (auto& e : edges) p[find(e[0])] = find(e[1]); - return find(source) == find(destination); - } -}; +```go +func validPath(n int, edges [][]int, source int, destination int) bool { + vis := make([]bool, n) + g := make([][]int, n) + for _, e := range edges { + a, b := e[0], e[1] + g[a] = append(g[a], b) + g[b] = append(g[b], a) + } + var dfs func(int) bool + dfs = func(i int) bool { + if i == destination { + return true + } + vis[i] = true + for _, j := range g[i] { + if !vis[j] && dfs(j) { + return true + } + } + return false + } + return dfs(source) +} ``` -### **Rust** - ```rust impl Solution { pub fn valid_path(n: i32, edges: Vec>, source: i32, destination: i32) -> bool { @@ -222,34 +186,68 @@ impl Solution { } ``` -### **Go** + -```go -func validPath(n int, edges [][]int, source int, destination int) bool { - vis := make([]bool, n) - g := make([][]int, n) - for _, e := range edges { - a, b := e[0], e[1] - g[a] = append(g[a], b) - g[b] = append(g[b], a) - } - var dfs func(int) bool - dfs = func(i int) bool { - if i == destination { - return true - } - vis[i] = true - for _, j := range g[i] { - if !vis[j] && dfs(j) { - return true - } - } - return false - } - return dfs(source) +### Solution 2 + + + +```python +class Solution: + def validPath( + self, n: int, edges: List[List[int]], source: int, destination: int + ) -> bool: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + p = list(range(n)) + for u, v in edges: + p[find(u)] = find(v) + return find(source) == find(destination) +``` + +```java +class Solution { + private int[] p; + + public boolean validPath(int n, int[][] edges, int source, int destination) { + p = new int[n]; + for (int i = 0; i < n; ++i) { + p[i] = i; + } + for (int[] e : edges) { + p[find(e[0])] = find(e[1]); + } + return find(source) == find(destination); + } + + private int find(int x) { + if (p[x] != x) { + p[x] = find(p[x]); + } + return p[x]; + } } ``` +```cpp +class Solution { +public: + bool validPath(int n, vector>& edges, int source, int destination) { + vector p(n); + iota(p.begin(), p.end(), 0); + function find = [&](int x) -> int { + if (p[x] != x) p[x] = find(p[x]); + return p[x]; + }; + for (auto& e : edges) p[find(e[0])] = find(e[1]); + return find(source) == find(destination); + } +}; +``` + ```go func validPath(n int, edges [][]int, source int, destination int) bool { p := make([]int, n) @@ -270,10 +268,6 @@ func validPath(n int, edges [][]int, source int, destination int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1972.First and Last Call On the Same Day/README.md b/solution/1900-1999/1972.First and Last Call On the Same Day/README.md index c1f98a1868509..4144ec1cae62d 100644 --- a/solution/1900-1999/1972.First and Last Call On the Same Day/README.md +++ b/solution/1900-1999/1972.First and Last Call On the Same Day/README.md @@ -58,14 +58,10 @@ Calls table: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below with s as ( @@ -109,3 +105,5 @@ where ``` + + diff --git a/solution/1900-1999/1972.First and Last Call On the Same Day/README_EN.md b/solution/1900-1999/1972.First and Last Call On the Same Day/README_EN.md index 996345f2e5673..b097af01d25d4 100644 --- a/solution/1900-1999/1972.First and Last Call On the Same Day/README_EN.md +++ b/solution/1900-1999/1972.First and Last Call On the Same Day/README_EN.md @@ -59,9 +59,9 @@ On 2021-08-11, user 1 and 5 had a call. This call was the only call for both of ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -106,3 +106,5 @@ where ``` + + diff --git a/solution/1900-1999/1973.Count Nodes Equal to Sum of Descendants/README.md b/solution/1900-1999/1973.Count Nodes Equal to Sum of Descendants/README.md index abdf83eb567c1..0de609a1690be 100644 --- a/solution/1900-1999/1973.Count Nodes Equal to Sum of Descendants/README.md +++ b/solution/1900-1999/1973.Count Nodes Equal to Sum of Descendants/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们设计一个函数 $dfs(root)$,该函数返回以 $root$ 为根节点的子树的所有节点值之和。函数 $dfs(root)$ 的执行过程如下: @@ -66,10 +64,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -196,10 +182,6 @@ func equalToDescendants(root *TreeNode) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1973.Count Nodes Equal to Sum of Descendants/README_EN.md b/solution/1900-1999/1973.Count Nodes Equal to Sum of Descendants/README_EN.md index f8201a38319fe..3c4083cb80a6d 100644 --- a/solution/1900-1999/1973.Count Nodes Equal to Sum of Descendants/README_EN.md +++ b/solution/1900-1999/1973.Count Nodes Equal to Sum of Descendants/README_EN.md @@ -46,9 +46,9 @@ For the node with value 0: The sum of its descendants is 0 since it has no desce ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -113,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -146,8 +142,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -174,10 +168,6 @@ func equalToDescendants(root *TreeNode) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1974.Minimum Time to Type Word Using Special Typewriter/README.md b/solution/1900-1999/1974.Minimum Time to Type Word Using Special Typewriter/README.md index b30fd069d1e5c..4159867fa6eb8 100644 --- a/solution/1900-1999/1974.Minimum Time to Type Word Using Special Typewriter/README.md +++ b/solution/1900-1999/1974.Minimum Time to Type Word Using Special Typewriter/README.md @@ -76,14 +76,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minTimeToType(self, word: str) -> int: @@ -97,10 +93,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minTimeToType(String word) { @@ -118,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +128,6 @@ public: }; ``` -### **Go** - ```go func minTimeToType(word string) int { ans, prev := 0, 0 @@ -161,10 +149,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1974.Minimum Time to Type Word Using Special Typewriter/README_EN.md b/solution/1900-1999/1974.Minimum Time to Type Word Using Special Typewriter/README_EN.md index c9d80e5286406..71abefec2ecce 100644 --- a/solution/1900-1999/1974.Minimum Time to Type Word Using Special Typewriter/README_EN.md +++ b/solution/1900-1999/1974.Minimum Time to Type Word Using Special Typewriter/README_EN.md @@ -72,9 +72,9 @@ The characters are printed as follows: ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -89,8 +89,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minTimeToType(String word) { @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +124,6 @@ public: }; ``` -### **Go** - ```go func minTimeToType(word string) int { ans, prev := 0, 0 @@ -151,10 +145,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1975.Maximum Matrix Sum/README.md b/solution/1900-1999/1975.Maximum Matrix Sum/README.md index 7ddc47141231c..024f9240ee837 100644 --- a/solution/1900-1999/1975.Maximum Matrix Sum/README.md +++ b/solution/1900-1999/1975.Maximum Matrix Sum/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 如果矩阵中存在零,或者矩阵中负数的个数为偶数,那么最大和就是矩阵中所有元素的绝对值之和。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def maxMatrixSum(self, matrix: List[List[int]]) -> int: @@ -79,10 +73,6 @@ class Solution: return s - mi * 2 ``` -### **Java** - - - ```java class Solution { public long maxMatrixSum(int[][] matrix) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func maxMatrixSum(matrix [][]int) int64 { s := 0 @@ -156,8 +142,6 @@ func abs(x int) int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} matrix @@ -181,10 +165,6 @@ var maxMatrixSum = function (matrix) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1975.Maximum Matrix Sum/README_EN.md b/solution/1900-1999/1975.Maximum Matrix Sum/README_EN.md index 59ae99cb71bfd..57f1d48f2f8ef 100644 --- a/solution/1900-1999/1975.Maximum Matrix Sum/README_EN.md +++ b/solution/1900-1999/1975.Maximum Matrix Sum/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return s - mi * 2 ``` -### **Java** - ```java class Solution { public long maxMatrixSum(int[][] matrix) { @@ -90,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +107,6 @@ public: }; ``` -### **Go** - ```go func maxMatrixSum(matrix [][]int) int64 { s := 0 @@ -140,8 +134,6 @@ func abs(x int) int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} matrix @@ -165,10 +157,6 @@ var maxMatrixSum = function (matrix) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1976.Number of Ways to Arrive at Destination/README.md b/solution/1900-1999/1976.Number of Ways to Arrive at Destination/README.md index 5bff567777703..4f98766a41ae9 100644 --- a/solution/1900-1999/1976.Number of Ways to Arrive at Destination/README.md +++ b/solution/1900-1999/1976.Number of Ways to Arrive at Destination/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:朴素 Dijkstra 算法** +### 方法一:朴素 Dijkstra 算法 在求最短路的过程中顺便记录到达某个点最短路径的方案数。松弛优化时,如果发现有更优的路径,则方案数也赋值最优路径的前驱的方案数。如果发现与最优的路径长度相同,则累加当前前驱的方案数。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def countPaths(self, n: int, roads: List[List[int]]) -> int: @@ -101,10 +95,6 @@ class Solution: return w[-1] % MOD ``` -### **Java** - - - ```java class Solution { private static final long INF = Long.MAX_VALUE / 2; @@ -153,8 +143,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef long long ll; @@ -197,8 +185,6 @@ public: }; ``` -### **Go** - ```go func countPaths(n int, roads [][]int) int { const inf = math.MaxInt64 / 2 @@ -246,10 +232,6 @@ func countPaths(n int, roads [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1976.Number of Ways to Arrive at Destination/README_EN.md b/solution/1900-1999/1976.Number of Ways to Arrive at Destination/README_EN.md index 3b20e19a5a112..e30e7ad385a6e 100644 --- a/solution/1900-1999/1976.Number of Ways to Arrive at Destination/README_EN.md +++ b/solution/1900-1999/1976.Number of Ways to Arrive at Destination/README_EN.md @@ -48,9 +48,9 @@ The four ways to get there in 7 minutes are: ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -85,8 +85,6 @@ class Solution: return w[-1] % MOD ``` -### **Java** - ```java class Solution { private static final long INF = Long.MAX_VALUE / 2; @@ -135,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp typedef long long ll; @@ -179,8 +175,6 @@ public: }; ``` -### **Go** - ```go func countPaths(n int, roads [][]int) int { const inf = math.MaxInt64 / 2 @@ -228,10 +222,6 @@ func countPaths(n int, roads [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1977.Number of Ways to Separate Numbers/README.md b/solution/1900-1999/1977.Number of Ways to Separate Numbers/README.md index bd41672b8231e..0a3302fd0c010 100644 --- a/solution/1900-1999/1977.Number of Ways to Separate Numbers/README.md +++ b/solution/1900-1999/1977.Number of Ways to Separate Numbers/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:动态规划 + 前缀和** +### 方法一:动态规划 + 前缀和 定义 $dp[i][j]$ 表示字符串 `num` 的前 $i$ 个字符,且最后一个数字的长度为 $j$ 时的方案数。显然答案为 $\sum_{j=0}^{n} dp[n][j]$。初始值 $dp[0][0] = 1$。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def numberOfCombinations(self, num: str) -> int: @@ -99,10 +93,6 @@ class Solution: return dp[n][n] ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +170,6 @@ public: }; ``` -### **Go** - ```go func numberOfCombinations(num string) int { n := len(num) @@ -223,10 +209,6 @@ func numberOfCombinations(num string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1977.Number of Ways to Separate Numbers/README_EN.md b/solution/1900-1999/1977.Number of Ways to Separate Numbers/README_EN.md index 831b5d1df78b1..cf6e97c64153c 100644 --- a/solution/1900-1999/1977.Number of Ways to Separate Numbers/README_EN.md +++ b/solution/1900-1999/1977.Number of Ways to Separate Numbers/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,8 +78,6 @@ class Solution: return dp[n][n] ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -118,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +155,6 @@ public: }; ``` -### **Go** - ```go func numberOfCombinations(num string) int { n := len(num) @@ -200,10 +194,6 @@ func numberOfCombinations(num string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1978.Employees Whose Manager Left the Company/README.md b/solution/1900-1999/1978.Employees Whose Manager Left the Company/README.md index 84fd4dfb30e1c..b40d419d5c0ce 100644 --- a/solution/1900-1999/1978.Employees Whose Manager Left the Company/README.md +++ b/solution/1900-1999/1978.Employees Whose Manager Left the Company/README.md @@ -62,22 +62,12 @@ Joziah 的上级经理是 6 号员工,他已经离职,因为员工表里面 ## 解法 - - -**方法一:左连接** +### 方法一:左连接 我们可以使用左连接,将员工表自身连接一次,然后筛选出薪水小于 30000 的员工,且有上级经理,但是上级经理已经离职的员工。 -**方法二:子查询** - -我们也可以使用子查询,先找出所有已经离职的经理,然后再找出薪水小于 30000 的员工,且他们的上级经理不在已经离职的经理列表中。 - -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT e1.employee_id @@ -88,6 +78,14 @@ WHERE e1.salary < 30000 AND e1.manager_id IS NOT NULL AND e2.employee_id IS NULL ORDER BY 1; ``` + + +### 方法二:子查询 + +我们也可以使用子查询,先找出所有已经离职的经理,然后再找出薪水小于 30000 的员工,且他们的上级经理不在已经离职的经理列表中。 + + + ```sql # Write your MySQL query statement below SELECT employee_id @@ -97,3 +95,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1900-1999/1978.Employees Whose Manager Left the Company/README_EN.md b/solution/1900-1999/1978.Employees Whose Manager Left the Company/README_EN.md index 4aaf8dd1e6ccb..fff39e625e1ef 100644 --- a/solution/1900-1999/1978.Employees Whose Manager Left the Company/README_EN.md +++ b/solution/1900-1999/1978.Employees Whose Manager Left the Company/README_EN.md @@ -58,18 +58,12 @@ Joziah's manager is employee 6, who left the company because there is no row ## Solutions -**Solution 1: Left Join** +### Solution 1: Left Join We can use a left join to connect the employee table with itself, and then filter out the employees whose salary is less than $30000$ and have a superior manager who has left the company. -**Solution 2: Subquery** - -We can also use a subquery to first find all the managers who have left the company, and then find the employees whose salary is less than $30000$ and whose superior manager is not in the list of managers who have left the company. - -### **SQL** - ```sql # Write your MySQL query statement below SELECT e1.employee_id @@ -80,6 +74,14 @@ WHERE e1.salary < 30000 AND e1.manager_id IS NOT NULL AND e2.employee_id IS NULL ORDER BY 1; ``` + + +### Solution 2: Subquery + +We can also use a subquery to first find all the managers who have left the company, and then find the employees whose salary is less than $30000$ and whose superior manager is not in the list of managers who have left the company. + + + ```sql # Write your MySQL query statement below SELECT employee_id @@ -89,3 +91,5 @@ ORDER BY 1; ``` + + diff --git a/solution/1900-1999/1979.Find Greatest Common Divisor of Array/README.md b/solution/1900-1999/1979.Find Greatest Common Divisor of Array/README.md index 64d9d270b0008..dae7530ab4f7e 100644 --- a/solution/1900-1999/1979.Find Greatest Common Divisor of Array/README.md +++ b/solution/1900-1999/1979.Find Greatest Common Divisor of Array/README.md @@ -53,9 +53,7 @@ nums 中最大的数是 3 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 根据题意模拟即可,即先找出数组 `nums` 中的最大值和最小值,然后求最大值和最小值的最大公约数。 @@ -63,20 +61,12 @@ nums 中最大的数是 3 -### **Python3** - - - ```python class Solution: def findGCD(self, nums: List[int]) -> int: return gcd(max(nums), min(nums)) ``` -### **Java** - - - ```java class Solution { public int findGCD(int[] nums) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func findGCD(nums []int) int { a, b := slices.Max(nums), slices.Min(nums) @@ -123,8 +109,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function findGCD(nums: number[]): number { let a = 1; @@ -144,10 +128,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1979.Find Greatest Common Divisor of Array/README_EN.md b/solution/1900-1999/1979.Find Greatest Common Divisor of Array/README_EN.md index daffe0aabb0f7..3aa294e3c9643 100644 --- a/solution/1900-1999/1979.Find Greatest Common Divisor of Array/README_EN.md +++ b/solution/1900-1999/1979.Find Greatest Common Divisor of Array/README_EN.md @@ -52,9 +52,9 @@ The greatest common divisor of 3 and 3 is 3. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return gcd(max(nums), min(nums)) ``` -### **Java** - ```java class Solution { public int findGCD(int[] nums) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +90,6 @@ public: }; ``` -### **Go** - ```go func findGCD(nums []int) int { a, b := slices.Max(nums), slices.Min(nums) @@ -110,8 +104,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function findGCD(nums: number[]): number { let a = 1; @@ -131,10 +123,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1980.Find Unique Binary String/README.md b/solution/1900-1999/1980.Find Unique Binary String/README.md index 6f66f4eb85e81..77c762bfc4f51 100644 --- a/solution/1900-1999/1980.Find Unique Binary String/README.md +++ b/solution/1900-1999/1980.Find Unique Binary String/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:计数 + 枚举** +### 方法一:计数 + 枚举 由于 `'1'` 在长度为 $n$ 的二进制字符串中出现的次数可以为 $0, 1, 2, \cdots, n$(共有 $n + 1$ 种可能),因此我们一定可以找出一个新的二进制字符串,满足 `'1'` 在字符串中出现次数与 `nums` 中每个字符串不同。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def findDifferentBinaryString(self, nums: List[str]) -> str: @@ -77,10 +71,6 @@ class Solution: return "1" * i + "0" * (n - i) ``` -### **Java** - - - ```java class Solution { public String findDifferentBinaryString(String[] nums) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func findDifferentBinaryString(nums []string) string { mask := 0 @@ -139,8 +125,6 @@ func findDifferentBinaryString(nums []string) string { } ``` -### **C#** - ```cs public class Solution { public string FindDifferentBinaryString(string[] nums) { @@ -158,10 +142,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1980.Find Unique Binary String/README_EN.md b/solution/1900-1999/1980.Find Unique Binary String/README_EN.md index c181d5fc5ef8e..aa6d8fa1c8e16 100644 --- a/solution/1900-1999/1980.Find Unique Binary String/README_EN.md +++ b/solution/1900-1999/1980.Find Unique Binary String/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return "1" * i + "0" * (n - i) ``` -### **Java** - ```java class Solution { public String findDifferentBinaryString(String[] nums) { @@ -84,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +100,6 @@ public: }; ``` -### **Go** - ```go func findDifferentBinaryString(nums []string) string { mask := 0 @@ -120,8 +114,6 @@ func findDifferentBinaryString(nums []string) string { } ``` -### **C#** - ```cs public class Solution { public string FindDifferentBinaryString(string[] nums) { @@ -139,10 +131,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README.md b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README.md index 670060f15be09..6049cf4871975 100644 --- a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README.md +++ b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README.md @@ -69,9 +69,7 @@ ## 解法 - - -**方法一:动态规划(分组背包)** +### 方法一:动态规划(分组背包) 设 $f[i][j]$ 表示前 $i$ 行是否能选出元素和为 $j$,则有状态转移方程: @@ -89,10 +87,6 @@ $$ -### **Python3** - - - ```python class Solution: def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int: @@ -102,10 +96,6 @@ class Solution: return min(abs(v - target) for v in f) ``` -### **Java** - - - ```java class Solution { public int minimizeTheDifference(int[][] mat, int target) { @@ -129,36 +119,6 @@ class Solution { } ``` -```java -class Solution { - public int minimizeTheDifference(int[][] mat, int target) { - boolean[] f = {true}; - for (var row : mat) { - int mx = 0; - for (int x : row) { - mx = Math.max(mx, x); - } - boolean[] g = new boolean[f.length + mx]; - for (int x : row) { - for (int j = x; j < f.length + x; ++j) { - g[j] |= f[j - x]; - } - } - f = g; - } - int ans = 1 << 30; - for (int j = 0; j < f.length; ++j) { - if (f[j]) { - ans = Math.min(ans, Math.abs(j - target)); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -185,8 +145,6 @@ public: }; ``` -### **Go** - ```go func minimizeTheDifference(mat [][]int, target int) int { f := []int{1} @@ -217,10 +175,40 @@ func abs(x int) int { } ``` -### **...** + -``` +### 方法二 + + +```java +class Solution { + public int minimizeTheDifference(int[][] mat, int target) { + boolean[] f = {true}; + for (var row : mat) { + int mx = 0; + for (int x : row) { + mx = Math.max(mx, x); + } + boolean[] g = new boolean[f.length + mx]; + for (int x : row) { + for (int j = x; j < f.length + x; ++j) { + g[j] |= f[j - x]; + } + } + f = g; + } + int ans = 1 << 30; + for (int j = 0; j < f.length; ++j) { + if (f[j]) { + ans = Math.min(ans, Math.abs(j - target)); + } + } + return ans; + } +} ``` + + diff --git a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README_EN.md b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README_EN.md index 787cbd3242c1b..9960f214bda8f 100644 --- a/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README_EN.md +++ b/solution/1900-1999/1981.Minimize the Difference Between Target and Chosen Elements/README_EN.md @@ -59,9 +59,9 @@ The absolute difference is 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return min(abs(v - target) for v in f) ``` -### **Java** - ```java class Solution { public int minimizeTheDifference(int[][] mat, int target) { @@ -97,36 +95,6 @@ class Solution { } ``` -```java -class Solution { - public int minimizeTheDifference(int[][] mat, int target) { - boolean[] f = {true}; - for (var row : mat) { - int mx = 0; - for (int x : row) { - mx = Math.max(mx, x); - } - boolean[] g = new boolean[f.length + mx]; - for (int x : row) { - for (int j = x; j < f.length + x; ++j) { - g[j] |= f[j - x]; - } - } - f = g; - } - int ans = 1 << 30; - for (int j = 0; j < f.length; ++j) { - if (f[j]) { - ans = Math.min(ans, Math.abs(j - target)); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -153,8 +121,6 @@ public: }; ``` -### **Go** - ```go func minimizeTheDifference(mat [][]int, target int) int { f := []int{1} @@ -185,10 +151,40 @@ func abs(x int) int { } ``` -### **...** + + +### Solution 2 -``` + +```java +class Solution { + public int minimizeTheDifference(int[][] mat, int target) { + boolean[] f = {true}; + for (var row : mat) { + int mx = 0; + for (int x : row) { + mx = Math.max(mx, x); + } + boolean[] g = new boolean[f.length + mx]; + for (int x : row) { + for (int j = x; j < f.length + x; ++j) { + g[j] |= f[j - x]; + } + } + f = g; + } + int ans = 1 << 30; + for (int j = 0; j < f.length; ++j) { + if (f[j]) { + ans = Math.min(ans, Math.abs(j - target)); + } + } + return ans; + } +} ``` + + diff --git a/solution/1900-1999/1982.Find Array Given Subset Sums/README.md b/solution/1900-1999/1982.Find Array Given Subset Sums/README.md index 0830b8a1da0f3..8424a99a8087c 100644 --- a/solution/1900-1999/1982.Find Array Given Subset Sums/README.md +++ b/solution/1900-1999/1982.Find Array Given Subset Sums/README.md @@ -61,14 +61,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -95,35 +91,6 @@ class Solution: return ans ``` -```python -class Solution: - def recoverArray(self, n: int, sums: List[int]) -> List[int]: - sums.sort() - ans = [] - for i in range(n, 0, -1): - k = 1 << i - d = sums[k - 1] - sums[k - 2] - cnt = Counter(sums[:k]) - sums1, sums2 = [], [] - sign = 1 - for s in sums[:k]: - if not cnt[s]: - continue - cnt[s] -= 1 - cnt[s + d] -= 1 - sums1.append(s) - sums2.append(s + d) - if s + d == 0: - sign = -1 - ans.append(sign * d) - sums = sums1 if sign == 1 else sums2 - return ans -``` - -### **Java** - - - ```java class Solution { public int[] recoverArray(int n, int[] sums) { @@ -178,44 +145,6 @@ class Solution { } ``` -```java -class Solution { - public int[] recoverArray(int n, int[] sums) { - Arrays.sort(sums); - int[] sums1 = new int[1 << n]; - int[] sums2 = new int[1 << n]; - Map cnt = new HashMap<>(); - int[] ans = new int[n]; - for (int i = n; i > 0; --i) { - int k = 1 << i; - int d = sums[k - 1] - sums[k - 2]; - cnt.clear(); - for (int j = 0; j < k; ++j) { - cnt.merge(sums[j], 1, Integer::sum); - } - int sign = 1; - for (int j = 0, p = 0; j < k; ++j) { - if (cnt.getOrDefault(sums[j], 0) == 0) { - continue; - } - cnt.merge(sums[j], -1, Integer::sum); - cnt.merge(sums[j] + d, -1, Integer::sum); - sums1[p] = sums[j]; - sums2[p++] = sums[j] + d; - if (sums[j] + d == 0) { - sign = -1; - } - } - ans[i - 1] = sign * d; - System.arraycopy(sign == 1 ? sums1 : sums2, 0, sums, 0, k / 2); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -264,46 +193,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector recoverArray(int n, vector& sums) { - sort(sums.begin(), sums.end()); - vector ans(n); - unordered_map cnt; - for (int i = n; i; --i) { - cnt.clear(); - int k = 1 << i; - int d = sums[k - 1] - sums[k - 2]; - for (int j = 0; j < k; ++j) { - cnt[sums[j]]++; - } - vector sums1, sums2; - int sign = 1; - for (int j = 0; j < k; ++j) { - if (cnt[sums[j]] == 0) { - continue; - } - --cnt[sums[j]]; - --cnt[sums[j] + d]; - sums1.push_back(sums[j]); - sums2.push_back(sums[j] + d); - if (sums2.back() == 0) { - sign = -1; - } - } - ans[i - 1] = sign * d; - for (int j = 0; j < k / 2; ++j) { - sums[j] = sign == 1 ? sums1[j] : sums2[j]; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func recoverArray(n int, sums []int) []int { m := -slices.Min(sums) @@ -361,6 +250,111 @@ func recoverArray(n int, sums []int) []int { } ``` + + +### 方法二 + + + +```python +class Solution: + def recoverArray(self, n: int, sums: List[int]) -> List[int]: + sums.sort() + ans = [] + for i in range(n, 0, -1): + k = 1 << i + d = sums[k - 1] - sums[k - 2] + cnt = Counter(sums[:k]) + sums1, sums2 = [], [] + sign = 1 + for s in sums[:k]: + if not cnt[s]: + continue + cnt[s] -= 1 + cnt[s + d] -= 1 + sums1.append(s) + sums2.append(s + d) + if s + d == 0: + sign = -1 + ans.append(sign * d) + sums = sums1 if sign == 1 else sums2 + return ans +``` + +```java +class Solution { + public int[] recoverArray(int n, int[] sums) { + Arrays.sort(sums); + int[] sums1 = new int[1 << n]; + int[] sums2 = new int[1 << n]; + Map cnt = new HashMap<>(); + int[] ans = new int[n]; + for (int i = n; i > 0; --i) { + int k = 1 << i; + int d = sums[k - 1] - sums[k - 2]; + cnt.clear(); + for (int j = 0; j < k; ++j) { + cnt.merge(sums[j], 1, Integer::sum); + } + int sign = 1; + for (int j = 0, p = 0; j < k; ++j) { + if (cnt.getOrDefault(sums[j], 0) == 0) { + continue; + } + cnt.merge(sums[j], -1, Integer::sum); + cnt.merge(sums[j] + d, -1, Integer::sum); + sums1[p] = sums[j]; + sums2[p++] = sums[j] + d; + if (sums[j] + d == 0) { + sign = -1; + } + } + ans[i - 1] = sign * d; + System.arraycopy(sign == 1 ? sums1 : sums2, 0, sums, 0, k / 2); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector recoverArray(int n, vector& sums) { + sort(sums.begin(), sums.end()); + vector ans(n); + unordered_map cnt; + for (int i = n; i; --i) { + cnt.clear(); + int k = 1 << i; + int d = sums[k - 1] - sums[k - 2]; + for (int j = 0; j < k; ++j) { + cnt[sums[j]]++; + } + vector sums1, sums2; + int sign = 1; + for (int j = 0; j < k; ++j) { + if (cnt[sums[j]] == 0) { + continue; + } + --cnt[sums[j]]; + --cnt[sums[j] + d]; + sums1.push_back(sums[j]); + sums2.push_back(sums[j] + d); + if (sums2.back() == 0) { + sign = -1; + } + } + ans[i - 1] = sign * d; + for (int j = 0; j < k / 2; ++j) { + sums[j] = sign == 1 ? sums1[j] : sums2[j]; + } + } + return ans; + } +}; +``` + ```go func recoverArray(n int, sums []int) (ans []int) { sort.Ints(sums) @@ -395,10 +389,6 @@ func recoverArray(n int, sums []int) (ans []int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1982.Find Array Given Subset Sums/README_EN.md b/solution/1900-1999/1982.Find Array Given Subset Sums/README_EN.md index b5918ad081102..6c875d608a635 100644 --- a/solution/1900-1999/1982.Find Array Given Subset Sums/README_EN.md +++ b/solution/1900-1999/1982.Find Array Given Subset Sums/README_EN.md @@ -57,9 +57,9 @@ Note that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedList @@ -87,33 +87,6 @@ class Solution: return ans ``` -```python -class Solution: - def recoverArray(self, n: int, sums: List[int]) -> List[int]: - sums.sort() - ans = [] - for i in range(n, 0, -1): - k = 1 << i - d = sums[k - 1] - sums[k - 2] - cnt = Counter(sums[:k]) - sums1, sums2 = [], [] - sign = 1 - for s in sums[:k]: - if not cnt[s]: - continue - cnt[s] -= 1 - cnt[s + d] -= 1 - sums1.append(s) - sums2.append(s + d) - if s + d == 0: - sign = -1 - ans.append(sign * d) - sums = sums1 if sign == 1 else sums2 - return ans -``` - -### **Java** - ```java class Solution { public int[] recoverArray(int n, int[] sums) { @@ -168,44 +141,6 @@ class Solution { } ``` -```java -class Solution { - public int[] recoverArray(int n, int[] sums) { - Arrays.sort(sums); - int[] sums1 = new int[1 << n]; - int[] sums2 = new int[1 << n]; - Map cnt = new HashMap<>(); - int[] ans = new int[n]; - for (int i = n; i > 0; --i) { - int k = 1 << i; - int d = sums[k - 1] - sums[k - 2]; - cnt.clear(); - for (int j = 0; j < k; ++j) { - cnt.merge(sums[j], 1, Integer::sum); - } - int sign = 1; - for (int j = 0, p = 0; j < k; ++j) { - if (cnt.getOrDefault(sums[j], 0) == 0) { - continue; - } - cnt.merge(sums[j], -1, Integer::sum); - cnt.merge(sums[j] + d, -1, Integer::sum); - sums1[p] = sums[j]; - sums2[p++] = sums[j] + d; - if (sums[j] + d == 0) { - sign = -1; - } - } - ans[i - 1] = sign * d; - System.arraycopy(sign == 1 ? sums1 : sums2, 0, sums, 0, k / 2); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -254,46 +189,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector recoverArray(int n, vector& sums) { - sort(sums.begin(), sums.end()); - vector ans(n); - unordered_map cnt; - for (int i = n; i; --i) { - cnt.clear(); - int k = 1 << i; - int d = sums[k - 1] - sums[k - 2]; - for (int j = 0; j < k; ++j) { - cnt[sums[j]]++; - } - vector sums1, sums2; - int sign = 1; - for (int j = 0; j < k; ++j) { - if (cnt[sums[j]] == 0) { - continue; - } - --cnt[sums[j]]; - --cnt[sums[j] + d]; - sums1.push_back(sums[j]); - sums2.push_back(sums[j] + d); - if (sums2.back() == 0) { - sign = -1; - } - } - ans[i - 1] = sign * d; - for (int j = 0; j < k / 2; ++j) { - sums[j] = sign == 1 ? sums1[j] : sums2[j]; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func recoverArray(n int, sums []int) []int { m := -slices.Min(sums) @@ -351,6 +246,111 @@ func recoverArray(n int, sums []int) []int { } ``` + + +### Solution 2 + + + +```python +class Solution: + def recoverArray(self, n: int, sums: List[int]) -> List[int]: + sums.sort() + ans = [] + for i in range(n, 0, -1): + k = 1 << i + d = sums[k - 1] - sums[k - 2] + cnt = Counter(sums[:k]) + sums1, sums2 = [], [] + sign = 1 + for s in sums[:k]: + if not cnt[s]: + continue + cnt[s] -= 1 + cnt[s + d] -= 1 + sums1.append(s) + sums2.append(s + d) + if s + d == 0: + sign = -1 + ans.append(sign * d) + sums = sums1 if sign == 1 else sums2 + return ans +``` + +```java +class Solution { + public int[] recoverArray(int n, int[] sums) { + Arrays.sort(sums); + int[] sums1 = new int[1 << n]; + int[] sums2 = new int[1 << n]; + Map cnt = new HashMap<>(); + int[] ans = new int[n]; + for (int i = n; i > 0; --i) { + int k = 1 << i; + int d = sums[k - 1] - sums[k - 2]; + cnt.clear(); + for (int j = 0; j < k; ++j) { + cnt.merge(sums[j], 1, Integer::sum); + } + int sign = 1; + for (int j = 0, p = 0; j < k; ++j) { + if (cnt.getOrDefault(sums[j], 0) == 0) { + continue; + } + cnt.merge(sums[j], -1, Integer::sum); + cnt.merge(sums[j] + d, -1, Integer::sum); + sums1[p] = sums[j]; + sums2[p++] = sums[j] + d; + if (sums[j] + d == 0) { + sign = -1; + } + } + ans[i - 1] = sign * d; + System.arraycopy(sign == 1 ? sums1 : sums2, 0, sums, 0, k / 2); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector recoverArray(int n, vector& sums) { + sort(sums.begin(), sums.end()); + vector ans(n); + unordered_map cnt; + for (int i = n; i; --i) { + cnt.clear(); + int k = 1 << i; + int d = sums[k - 1] - sums[k - 2]; + for (int j = 0; j < k; ++j) { + cnt[sums[j]]++; + } + vector sums1, sums2; + int sign = 1; + for (int j = 0; j < k; ++j) { + if (cnt[sums[j]] == 0) { + continue; + } + --cnt[sums[j]]; + --cnt[sums[j] + d]; + sums1.push_back(sums[j]); + sums2.push_back(sums[j] + d); + if (sums2.back() == 0) { + sign = -1; + } + } + ans[i - 1] = sign * d; + for (int j = 0; j < k / 2; ++j) { + sums[j] = sign == 1 ? sums1[j] : sums2[j]; + } + } + return ans; + } +}; +``` + ```go func recoverArray(n int, sums []int) (ans []int) { sort.Ints(sums) @@ -385,10 +385,6 @@ func recoverArray(n int, sums []int) (ans []int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1983.Widest Pair of Indices With Equal Range Sum/README.md b/solution/1900-1999/1983.Widest Pair of Indices With Equal Range Sum/README.md index fe6cad90ab37e..dcbcac3b1f4fd 100644 --- a/solution/1900-1999/1983.Widest Pair of Indices With Equal Range Sum/README.md +++ b/solution/1900-1999/1983.Widest Pair of Indices With Equal Range Sum/README.md @@ -60,9 +60,7 @@ i和j之间的距离是j - i + 1 = 1 - 1 + 1 = 1。 ## 解法 - - -**方法一:前缀和 + 哈希表** +### 方法一:前缀和 + 哈希表 我们观察到,对于任意的索引对 $(i, j)$,如果 $nums1[i] + nums1[i+1] + ... + nums1[j] = nums2[i] + nums2[i+1] + ... + nums2[j]$,那么 $nums1[i] - nums2[i] + nums1[i+1] - nums2[i+1] + ... + nums1[j] - nums2[j] = 0$。如果我们将数组 $nums1$ 与数组 $nums2$ 对应位置的元素相减,得到一个新的数组 $nums$,那么问题转换为在数组 $nums$ 中找到一个最长的子数组,使得子数组的和为 $0$。这可以通过前缀和 + 哈希表的方法求解。 @@ -76,10 +74,6 @@ i和j之间的距离是j - i + 1 = 1 - 1 + 1 = 1。 -### **Python3** - - - ```python class Solution: def widestPairOfIndices(self, nums1: List[int], nums2: List[int]) -> int: @@ -94,10 +88,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int widestPairOfIndices(int[] nums1, int[] nums2) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func widestPairOfIndices(nums1 []int, nums2 []int) (ans int) { d := map[int]int{0: -1} @@ -160,10 +146,6 @@ func widestPairOfIndices(nums1 []int, nums2 []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1983.Widest Pair of Indices With Equal Range Sum/README_EN.md b/solution/1900-1999/1983.Widest Pair of Indices With Equal Range Sum/README_EN.md index a245060b10784..12fb155185064 100644 --- a/solution/1900-1999/1983.Widest Pair of Indices With Equal Range Sum/README_EN.md +++ b/solution/1900-1999/1983.Widest Pair of Indices With Equal Range Sum/README_EN.md @@ -56,9 +56,9 @@ There are no pairs of indices that meet the requirements. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int widestPairOfIndices(int[] nums1, int[] nums2) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +116,6 @@ public: }; ``` -### **Go** - ```go func widestPairOfIndices(nums1 []int, nums2 []int) (ans int) { d := map[int]int{0: -1} @@ -138,10 +132,6 @@ func widestPairOfIndices(nums1 []int, nums2 []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1984.Minimum Difference Between Highest and Lowest of K Scores/README.md b/solution/1900-1999/1984.Minimum Difference Between Highest and Lowest of K Scores/README.md index 227ddc504782c..025ca7dfc00e0 100644 --- a/solution/1900-1999/1984.Minimum Difference Between Highest and Lowest of K Scores/README.md +++ b/solution/1900-1999/1984.Minimum Difference Between Highest and Lowest of K Scores/README.md @@ -47,16 +47,10 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 -### **Python3** - - - ```python class Solution: def minimumDifference(self, nums: List[int], k: int) -> int: @@ -64,10 +58,6 @@ class Solution: return min(nums[i + k - 1] - nums[i] for i in range(len(nums) - k + 1)) ``` -### **Java** - - - ```java class Solution { public int minimumDifference(int[] nums, int k) { @@ -81,22 +71,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minimumDifference(nums: number[], k: number): number { - nums.sort((a, b) => a - b); - const n = nums.length; - let ans = nums[n - 1] - nums[0]; - for (let i = 0; i + k - 1 < n; i++) { - ans = Math.min(nums[i + k - 1] - nums[i], ans); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -110,8 +84,6 @@ public: }; ``` -### **Go** - ```go func minimumDifference(nums []int, k int) int { sort.Ints(nums) @@ -123,7 +95,17 @@ func minimumDifference(nums []int, k int) int { } ``` -### **Rust** +```ts +function minimumDifference(nums: number[], k: number): number { + nums.sort((a, b) => a - b); + const n = nums.length; + let ans = nums[n - 1] - nums[0]; + for (let i = 0; i + k - 1 < n; i++) { + ans = Math.min(nums[i + k - 1] - nums[i], ans); + } + return ans; +} +``` ```rust impl Solution { @@ -139,8 +121,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -159,10 +139,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1984.Minimum Difference Between Highest and Lowest of K Scores/README_EN.md b/solution/1900-1999/1984.Minimum Difference Between Highest and Lowest of K Scores/README_EN.md index ff59ab3366a54..d6f1635a4a0e2 100644 --- a/solution/1900-1999/1984.Minimum Difference Between Highest and Lowest of K Scores/README_EN.md +++ b/solution/1900-1999/1984.Minimum Difference Between Highest and Lowest of K Scores/README_EN.md @@ -45,9 +45,9 @@ The minimum possible difference is 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return min(nums[i + k - 1] - nums[i] for i in range(len(nums) - k + 1)) ``` -### **Java** - ```java class Solution { public int minimumDifference(int[] nums, int k) { @@ -71,22 +69,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minimumDifference(nums: number[], k: number): number { - nums.sort((a, b) => a - b); - const n = nums.length; - let ans = nums[n - 1] - nums[0]; - for (let i = 0; i + k - 1 < n; i++) { - ans = Math.min(nums[i + k - 1] - nums[i], ans); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -100,8 +82,6 @@ public: }; ``` -### **Go** - ```go func minimumDifference(nums []int, k int) int { sort.Ints(nums) @@ -113,7 +93,17 @@ func minimumDifference(nums []int, k int) int { } ``` -### **Rust** +```ts +function minimumDifference(nums: number[], k: number): number { + nums.sort((a, b) => a - b); + const n = nums.length; + let ans = nums[n - 1] - nums[0]; + for (let i = 0; i + k - 1 < n; i++) { + ans = Math.min(nums[i + k - 1] - nums[i], ans); + } + return ans; +} +``` ```rust impl Solution { @@ -129,8 +119,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -149,10 +137,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README.md b/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README.md index 01fc65f19bdcd..3d2b33df4cfe3 100644 --- a/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README.md +++ b/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README.md @@ -57,16 +57,10 @@ nums 中的数字按非递减顺序排列为 ["0","0"] ## 解法 - - -**方法一:自定义排序** +### 方法一:自定义排序 -### **Python3** - - - ```python class Solution: def kthLargestNumber(self, nums: List[str], k: int) -> str: @@ -79,10 +73,6 @@ class Solution: return nums[k - 1] ``` -### **Java** - - - ```java class Solution { public String kthLargestNumber(String[] nums, int k) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +94,6 @@ public: }; ``` -### **Go** - ```go func kthLargestNumber(nums []string, k int) string { sort.Slice(nums, func(i, j int) bool { @@ -121,10 +107,6 @@ func kthLargestNumber(nums []string, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README_EN.md b/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README_EN.md index 3a79c83916351..f0e01d1659ddc 100644 --- a/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README_EN.md +++ b/solution/1900-1999/1985.Find the Kth Largest Integer in the Array/README_EN.md @@ -53,9 +53,9 @@ The 2nd largest integer in nums is "0". ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return nums[k - 1] ``` -### **Java** - ```java class Solution { public String kthLargestNumber(String[] nums, int k) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +90,6 @@ public: }; ``` -### **Go** - ```go func kthLargestNumber(nums []string, k int) string { sort.Slice(nums, func(i, j int) bool { @@ -109,10 +103,6 @@ func kthLargestNumber(nums []string, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/README.md b/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/README.md index 84704c7e39030..74030a355314f 100644 --- a/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/README.md +++ b/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:状态压缩动态规划 + 枚举子集** +### 方法一:状态压缩动态规划 + 枚举子集 我们注意到 $n$ 不超过 $14$,因此,我们可以考虑使用状态压缩动态规划的方法求解本题。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def minSessions(self, tasks: List[int], sessionTime: int) -> int: @@ -99,10 +93,6 @@ class Solution: return f[-1] ``` -### **Java** - - - ```java class Solution { public int minSessions(int[] tasks, int sessionTime) { @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -165,8 +153,6 @@ public: }; ``` -### **Go** - ```go func minSessions(tasks []int, sessionTime int) int { n := len(tasks) @@ -193,8 +179,6 @@ func minSessions(tasks []int, sessionTime int) int { } ``` -### **TypeScript** - ```ts function minSessions(tasks: number[], sessionTime: number): number { const n = tasks.length; @@ -222,10 +206,6 @@ function minSessions(tasks: number[], sessionTime: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/README_EN.md b/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/README_EN.md index c71cff0b3e40d..0490baad467da 100644 --- a/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/README_EN.md +++ b/solution/1900-1999/1986.Minimum Number of Work Sessions to Finish the Tasks/README_EN.md @@ -59,9 +59,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,8 +82,6 @@ class Solution: return f[-1] ``` -### **Java** - ```java class Solution { public int minSessions(int[] tasks, int sessionTime) { @@ -113,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +142,6 @@ public: }; ``` -### **Go** - ```go func minSessions(tasks []int, sessionTime int) int { n := len(tasks) @@ -174,8 +168,6 @@ func minSessions(tasks []int, sessionTime int) int { } ``` -### **TypeScript** - ```ts function minSessions(tasks: number[], sessionTime: number): number { const n = tasks.length; @@ -203,10 +195,6 @@ function minSessions(tasks: number[], sessionTime: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1987.Number of Unique Good Subsequences/README.md b/solution/1900-1999/1987.Number of Unique Good Subsequences/README.md index cec12bc676a28..1c10594c43453 100644 --- a/solution/1900-1999/1987.Number of Unique Good Subsequences/README.md +++ b/solution/1900-1999/1987.Number of Unique Good Subsequences/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f$ 表示以 $1$ 结尾的不同好子序列的数目,定义 $g$ 表示以 $0$ 结尾的且以 $1$ 开头的不同好子序列的数目。初始时 $f = g = 0$。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def numberOfUniqueGoodSubsequences(self, binary: str) -> int: @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numberOfUniqueGoodSubsequences(String binary) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func numberOfUniqueGoodSubsequences(binary string) (ans int) { const mod int = 1e9 + 7 @@ -161,8 +147,6 @@ func numberOfUniqueGoodSubsequences(binary string) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfUniqueGoodSubsequences(binary: string): number { let [f, g] = [0, 0]; @@ -181,10 +165,6 @@ function numberOfUniqueGoodSubsequences(binary: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1987.Number of Unique Good Subsequences/README_EN.md b/solution/1900-1999/1987.Number of Unique Good Subsequences/README_EN.md index 86fb09554a750..eae2c398dd656 100644 --- a/solution/1900-1999/1987.Number of Unique Good Subsequences/README_EN.md +++ b/solution/1900-1999/1987.Number of Unique Good Subsequences/README_EN.md @@ -53,9 +53,9 @@ The unique good subsequences are "0", "1", "10", & ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numberOfUniqueGoodSubsequences(String binary) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func numberOfUniqueGoodSubsequences(binary string) (ans int) { const mod int = 1e9 + 7 @@ -137,8 +131,6 @@ func numberOfUniqueGoodSubsequences(binary string) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfUniqueGoodSubsequences(binary: string): number { let [f, g] = [0, 0]; @@ -157,10 +149,6 @@ function numberOfUniqueGoodSubsequences(binary: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1988.Find Cutoff Score for Each School/README.md b/solution/1900-1999/1988.Find Cutoff Score for Each School/README.md index 8d1ecddd6c044..7ce0e617e53d4 100644 --- a/solution/1900-1999/1988.Find Cutoff Score for Each School/README.md +++ b/solution/1900-1999/1988.Find Cutoff Score for Each School/README.md @@ -92,14 +92,10 @@ Exam 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT school_id, MIN(IFNULL(score, -1)) AS score @@ -110,3 +106,5 @@ GROUP BY school_id; ``` + + diff --git a/solution/1900-1999/1988.Find Cutoff Score for Each School/README_EN.md b/solution/1900-1999/1988.Find Cutoff Score for Each School/README_EN.md index d435630aebcfb..0db828bf64c9d 100644 --- a/solution/1900-1999/1988.Find Cutoff Score for Each School/README_EN.md +++ b/solution/1900-1999/1988.Find Cutoff Score for Each School/README_EN.md @@ -91,9 +91,9 @@ Exam table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -105,3 +105,5 @@ GROUP BY school_id; ``` + + diff --git a/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README.md b/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README.md index 775ade28d0daf..f4a32051b1d59 100644 --- a/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README.md +++ b/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们可以用两个指针 $i$ 和 $j$ 指向鬼和非鬼的人,初始时 $i=0$, $j=0$。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def catchMaximumAmountofPeople(self, team: List[int], dist: int) -> int: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int catchMaximumAmountofPeople(int[] team, int dist) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func catchMaximumAmountofPeople(team []int, dist int) (ans int) { n := len(team) @@ -165,10 +151,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README_EN.md b/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README_EN.md index d816c5d035d84..613822a71e293 100644 --- a/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README_EN.md +++ b/solution/1900-1999/1989.Maximum Number of People That Can Be Caught in Tag/README_EN.md @@ -52,9 +52,9 @@ There are no people who are not "it" to catch. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int catchMaximumAmountofPeople(int[] team, int dist) { @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func catchMaximumAmountofPeople(team []int, dist int) (ans int) { n := len(team) @@ -145,10 +139,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1990.Count the Number of Experiments/README.md b/solution/1900-1999/1990.Count the Number of Experiments/README.md index 5efaaab927289..67ec8823bc5a2 100644 --- a/solution/1900-1999/1990.Count the Number of Experiments/README.md +++ b/solution/1900-1999/1990.Count the Number of Experiments/README.md @@ -70,14 +70,10 @@ Experiments table: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -109,3 +105,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/1900-1999/1990.Count the Number of Experiments/README_EN.md b/solution/1900-1999/1990.Count the Number of Experiments/README_EN.md index 6567e453d9059..bd006c085b2bc 100644 --- a/solution/1900-1999/1990.Count the Number of Experiments/README_EN.md +++ b/solution/1900-1999/1990.Count the Number of Experiments/README_EN.md @@ -66,9 +66,9 @@ On the platform "Web", we had two "Reading" experiments and ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -101,3 +101,5 @@ GROUP BY 1, 2; ``` + + diff --git a/solution/1900-1999/1991.Find the Middle Index in Array/README.md b/solution/1900-1999/1991.Find the Middle Index in Array/README.md index 819cc07d7e132..b0011be588581 100644 --- a/solution/1900-1999/1991.Find the Middle Index in Array/README.md +++ b/solution/1900-1999/1991.Find the Middle Index in Array/README.md @@ -70,9 +70,7 @@ ## 解法 - - -**方法一:前缀和** +### 方法一:前缀和 我们定义变量 $left$ 表示数组 `nums` 中下标 $i$ 左侧元素之和,变量 $right$ 表示数组 `nums` 中下标 $i$ 右侧元素之和。初始时 $left = 0$, $right = \sum_{i = 0}^{n - 1} nums[i]$。 @@ -89,10 +87,6 @@ -### **Python3** - - - ```python class Solution: def findMiddleIndex(self, nums: List[int]) -> int: @@ -105,10 +99,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int findMiddleIndex(int[] nums) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func findMiddleIndex(nums []int) int { s := 0 @@ -163,14 +149,8 @@ func findMiddleIndex(nums []int) int { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var findMiddleIndex = function (nums) { +```ts +function findMiddleIndex(nums: number[]): number { let left = 0, right = nums.reduce((a, b) => a + b); for (let i = 0; i < nums.length; ++i) { @@ -181,13 +161,15 @@ var findMiddleIndex = function (nums) { left += nums[i]; } return -1; -}; +} ``` -### **TypeScript** - -```ts -function findMiddleIndex(nums: number[]): number { +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findMiddleIndex = function (nums) { let left = 0, right = nums.reduce((a, b) => a + b); for (let i = 0; i < nums.length; ++i) { @@ -198,13 +180,9 @@ function findMiddleIndex(nums: number[]): number { left += nums[i]; } return -1; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/1900-1999/1991.Find the Middle Index in Array/README_EN.md b/solution/1900-1999/1991.Find the Middle Index in Array/README_EN.md index ff384a9fb2067..62e3191fe7e13 100644 --- a/solution/1900-1999/1991.Find the Middle Index in Array/README_EN.md +++ b/solution/1900-1999/1991.Find the Middle Index in Array/README_EN.md @@ -52,9 +52,9 @@ The sum of the numbers after index 2 is: 0 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int findMiddleIndex(int[] nums) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,33 +101,25 @@ public: }; ``` -### **Go** - ```go func findMiddleIndex(nums []int) int { - var left, right int - for _, x := range nums { - right += x + s := 0 + for _, num := range nums { + s += num } - for i, x := range nums { - right -= x - if left == right { + total := 0 + for i, num := range nums { + total += num + if total-num == s-total { return i } - left += x } return -1 } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var findMiddleIndex = function (nums) { +```ts +function findMiddleIndex(nums: number[]): number { let left = 0, right = nums.reduce((a, b) => a + b); for (let i = 0; i < nums.length; ++i) { @@ -142,13 +130,15 @@ var findMiddleIndex = function (nums) { left += nums[i]; } return -1; -}; +} ``` -### **TypeScript** - -```ts -function findMiddleIndex(nums: number[]): number { +```js +/** + * @param {number[]} nums + * @return {number} + */ +var findMiddleIndex = function (nums) { let left = 0, right = nums.reduce((a, b) => a + b); for (let i = 0; i < nums.length; ++i) { @@ -159,13 +149,9 @@ function findMiddleIndex(nums: number[]): number { left += nums[i]; } return -1; -} -``` - -### **...** - -``` - +}; ``` + + diff --git a/solution/1900-1999/1992.Find All Groups of Farmland/README.md b/solution/1900-1999/1992.Find All Groups of Farmland/README.md index 9edfd70a83cd1..7e56e25ce6df1 100644 --- a/solution/1900-1999/1992.Find All Groups of Farmland/README.md +++ b/solution/1900-1999/1992.Find All Groups of Farmland/README.md @@ -59,22 +59,10 @@ ## 解法 - - -判断是否为矩形左上角,需要满足三个条件: - -- 元素值为 1; -- 左边是边界或者是 0; -- 上边是边界或者是 0。 - -然后遍历找到矩形的右边界和下边界。 +### 方法一 -### **Python3** - - - ```python class Solution: def findFarmland(self, land: List[List[int]]) -> List[List[int]]: @@ -97,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] findFarmland(int[][] land) { @@ -127,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +135,6 @@ public: }; ``` -### **Go** - ```go func findFarmland(land [][]int) [][]int { m, n := len(land), len(land[0]) @@ -176,10 +156,6 @@ func findFarmland(land [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1992.Find All Groups of Farmland/README_EN.md b/solution/1900-1999/1992.Find All Groups of Farmland/README_EN.md index 7ebb1e9f5b823..80354e394a277 100644 --- a/solution/1900-1999/1992.Find All Groups of Farmland/README_EN.md +++ b/solution/1900-1999/1992.Find All Groups of Farmland/README_EN.md @@ -54,9 +54,9 @@ There are no groups of farmland. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] findFarmland(int[][] land) { @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +130,6 @@ public: }; ``` -### **Go** - ```go func findFarmland(land [][]int) [][]int { m, n := len(land), len(land[0]) @@ -157,10 +151,6 @@ func findFarmland(land [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1993.Operations on Tree/README.md b/solution/1900-1999/1993.Operations on Tree/README.md index 151fd2262497f..e0726dea8e6df 100644 --- a/solution/1900-1999/1993.Operations on Tree/README.md +++ b/solution/1900-1999/1993.Operations on Tree/README.md @@ -74,9 +74,7 @@ lockingTree.lock(0, 1); // 返回 false ,因为节点 0 已经被上锁了 ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们定义以下几个变量: @@ -94,10 +92,6 @@ lockingTree.lock(0, 1); // 返回 false ,因为节点 0 已经被上锁了 -### **Python3** - - - ```python class LockingTree: def __init__(self, parent: List[int]): @@ -150,10 +144,6 @@ class LockingTree: # param_3 = obj.upgrade(num,user) ``` -### **Java** - - - ```java class LockingTree { private int[] locked; @@ -225,8 +215,6 @@ class LockingTree { */ ``` -### **C++** - ```cpp class LockingTree { public: @@ -297,8 +285,6 @@ private: */ ``` -### **Go** - ```go type LockingTree struct { locked []int @@ -370,8 +356,6 @@ func (this *LockingTree) Upgrade(num int, user int) bool { */ ``` -### **TypeScript** - ```ts class LockingTree { private locked: number[]; @@ -441,10 +425,6 @@ class LockingTree { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1993.Operations on Tree/README_EN.md b/solution/1900-1999/1993.Operations on Tree/README_EN.md index 1d6cd09924699..8d72a41a73f1b 100644 --- a/solution/1900-1999/1993.Operations on Tree/README_EN.md +++ b/solution/1900-1999/1993.Operations on Tree/README_EN.md @@ -70,12 +70,10 @@ lockingTree.lock(0, 1); // return false because node 0 is already locked. ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python class LockingTree: def __init__(self, parent: List[int]): @@ -128,8 +126,6 @@ class LockingTree: # param_3 = obj.upgrade(num,user) ``` -### **Java** - ```java class LockingTree { private int[] locked; @@ -201,8 +197,6 @@ class LockingTree { */ ``` -### **C++** - ```cpp class LockingTree { public: @@ -273,8 +267,6 @@ private: */ ``` -### **Go** - ```go type LockingTree struct { locked []int @@ -346,8 +338,6 @@ func (this *LockingTree) Upgrade(num int, user int) bool { */ ``` -### **TypeScript** - ```ts class LockingTree { private locked: number[]; @@ -417,10 +407,6 @@ class LockingTree { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1994.The Number of Good Subsets/README.md b/solution/1900-1999/1994.The Number of Good Subsets/README.md index 0e4ca0a4934bd..e57a40e2fe36d 100644 --- a/solution/1900-1999/1994.The Number of Good Subsets/README.md +++ b/solution/1900-1999/1994.The Number of Good Subsets/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:状态压缩动态规划** +### 方法一:状态压缩动态规划 注意到题目中 $nums[i]$ 的范围为 $[1, 30]$,因此我们可以预处理出所有小于等于 $30$ 的质数,即 $[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]$。 @@ -83,10 +81,6 @@ -### **Python3** - - - ```python class Solution: def numberOfGoodSubsets(self, nums: List[int]) -> int: @@ -109,10 +103,6 @@ class Solution: return sum(f[i] for i in range(1, 1 << n)) % mod ``` -### **Java** - - - ```java class Solution { public int numberOfGoodSubsets(int[] nums) { @@ -153,8 +143,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -196,8 +184,6 @@ public: }; ``` -### **Go** - ```go func numberOfGoodSubsets(nums []int) (ans int) { primes := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} @@ -235,10 +221,6 @@ func numberOfGoodSubsets(nums []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1994.The Number of Good Subsets/README_EN.md b/solution/1900-1999/1994.The Number of Good Subsets/README_EN.md index 431163d17f76f..5fbfb6d8cbcba 100644 --- a/solution/1900-1999/1994.The Number of Good Subsets/README_EN.md +++ b/solution/1900-1999/1994.The Number of Good Subsets/README_EN.md @@ -57,9 +57,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,8 +83,6 @@ class Solution: return sum(f[i] for i in range(1, 1 << n)) % mod ``` -### **Java** - ```java class Solution { public int numberOfGoodSubsets(int[] nums) { @@ -125,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +164,6 @@ public: }; ``` -### **Go** - ```go func numberOfGoodSubsets(nums []int) (ans int) { primes := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} @@ -207,10 +201,6 @@ func numberOfGoodSubsets(nums []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1995.Count Special Quadruplets/README.md b/solution/1900-1999/1995.Count Special Quadruplets/README.md index 0e5b1bbbe07f6..ab7237caf8da9 100644 --- a/solution/1900-1999/1995.Count Special Quadruplets/README.md +++ b/solution/1900-1999/1995.Count Special Quadruplets/README.md @@ -51,16 +51,10 @@ ## 解法 - - -直接暴力枚举,或者用哈希表实现。 +### 方法一 -### **Python3** - - - ```python class Solution: def countQuadruplets(self, nums: List[int]) -> int: @@ -74,6 +68,65 @@ class Solution: return ans ``` +```java +class Solution { + public int countQuadruplets(int[] nums) { + int ans = 0, n = nums.length; + for (int a = 0; a < n - 3; ++a) { + for (int b = a + 1; b < n - 2; ++b) { + for (int c = b + 1; c < n - 1; ++c) { + for (int d = c + 1; d < n; ++d) { + if (nums[a] + nums[b] + nums[c] == nums[d]) { + ++ans; + } + } + } + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int countQuadruplets(vector& nums) { + int ans = 0, n = nums.size(); + for (int a = 0; a < n - 3; ++a) + for (int b = a + 1; b < n - 2; ++b) + for (int c = b + 1; c < n - 1; ++c) + for (int d = c + 1; d < n; ++d) + if (nums[a] + nums[b] + nums[c] == nums[d]) ++ans; + return ans; + } +}; +``` + +```go +func countQuadruplets(nums []int) int { + ans, n := 0, len(nums) + for a := 0; a < n-3; a++ { + for b := a + 1; b < n-2; b++ { + for c := b + 1; c < n-1; c++ { + for d := c + 1; d < n; d++ { + if nums[a]+nums[b]+nums[c] == nums[d] { + ans++ + } + } + } + } + } + return ans +} +``` + + + +### 方法二 + + + ```python class Solution: def countQuadruplets(self, nums: List[int]) -> int: @@ -87,36 +140,16 @@ class Solution: return ans ``` -```python -class Solution: - def countQuadruplets(self, nums: List[int]) -> int: - ans, n = 0, len(nums) - counter = Counter() - for b in range(n - 3, 0, -1): - c = b + 1 - for d in range(c + 1, n): - counter[nums[d] - nums[c]] += 1 - for a in range(b): - ans += counter[nums[a] + nums[b]] - return ans -``` - -### **Java** - - - ```java class Solution { public int countQuadruplets(int[] nums) { int ans = 0, n = nums.length; - for (int a = 0; a < n - 3; ++a) { - for (int b = a + 1; b < n - 2; ++b) { - for (int c = b + 1; c < n - 1; ++c) { - for (int d = c + 1; d < n; ++d) { - if (nums[a] + nums[b] + nums[c] == nums[d]) { - ++ans; - } - } + int[] counter = new int[310]; + for (int c = n - 2; c > 1; --c) { + ++counter[nums[c + 1]]; + for (int a = 0; a < c - 1; ++a) { + for (int b = a + 1; b < c; ++b) { + ans += counter[nums[a] + nums[b] + nums[c]]; } } } @@ -125,11 +158,12 @@ class Solution { } ``` -```java +```cpp class Solution { - public int countQuadruplets(int[] nums) { - int ans = 0, n = nums.length; - int[] counter = new int[310]; +public: + int countQuadruplets(vector& nums) { + int ans = 0, n = nums.size(); + vector counter(310); for (int c = n - 2; c > 1; --c) { ++counter[nums[c + 1]]; for (int a = 0; a < c - 1; ++a) { @@ -140,9 +174,45 @@ class Solution { } return ans; } +}; +``` + +```go +func countQuadruplets(nums []int) int { + ans, n := 0, len(nums) + counter := make([]int, 310) + for c := n - 2; c > 1; c-- { + counter[nums[c+1]]++ + for a := 0; a < c-1; a++ { + for b := a + 1; b < c; b++ { + ans += counter[nums[a]+nums[b]+nums[c]] + } + } + } + return ans } ``` + + +### 方法三 + + + +```python +class Solution: + def countQuadruplets(self, nums: List[int]) -> int: + ans, n = 0, len(nums) + counter = Counter() + for b in range(n - 3, 0, -1): + c = b + 1 + for d in range(c + 1, n): + counter[nums[d] - nums[c]] += 1 + for a in range(b): + ans += counter[nums[a] + nums[b]] + return ans +``` + ```java class Solution { public int countQuadruplets(int[] nums) { @@ -164,42 +234,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int countQuadruplets(vector& nums) { - int ans = 0, n = nums.size(); - for (int a = 0; a < n - 3; ++a) - for (int b = a + 1; b < n - 2; ++b) - for (int c = b + 1; c < n - 1; ++c) - for (int d = c + 1; d < n; ++d) - if (nums[a] + nums[b] + nums[c] == nums[d]) ++ans; - return ans; - } -}; -``` - -```cpp -class Solution { -public: - int countQuadruplets(vector& nums) { - int ans = 0, n = nums.size(); - vector counter(310); - for (int c = n - 2; c > 1; --c) { - ++counter[nums[c + 1]]; - for (int a = 0; a < c - 1; ++a) { - for (int b = a + 1; b < c; ++b) { - ans += counter[nums[a] + nums[b] + nums[c]]; - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -222,42 +256,6 @@ public: }; ``` -### **Go** - -```go -func countQuadruplets(nums []int) int { - ans, n := 0, len(nums) - for a := 0; a < n-3; a++ { - for b := a + 1; b < n-2; b++ { - for c := b + 1; c < n-1; c++ { - for d := c + 1; d < n; d++ { - if nums[a]+nums[b]+nums[c] == nums[d] { - ans++ - } - } - } - } - } - return ans -} -``` - -```go -func countQuadruplets(nums []int) int { - ans, n := 0, len(nums) - counter := make([]int, 310) - for c := n - 2; c > 1; c-- { - counter[nums[c+1]]++ - for a := 0; a < c-1; a++ { - for b := a + 1; b < c; b++ { - ans += counter[nums[a]+nums[b]+nums[c]] - } - } - } - return ans -} -``` - ```go func countQuadruplets(nums []int) int { ans, n := 0, len(nums) @@ -277,10 +275,6 @@ func countQuadruplets(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1995.Count Special Quadruplets/README_EN.md b/solution/1900-1999/1995.Count Special Quadruplets/README_EN.md index 02509eaba2b1a..8ac6a6f59d7b5 100644 --- a/solution/1900-1999/1995.Count Special Quadruplets/README_EN.md +++ b/solution/1900-1999/1995.Count Special Quadruplets/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,6 +67,65 @@ class Solution: return ans ``` +```java +class Solution { + public int countQuadruplets(int[] nums) { + int ans = 0, n = nums.length; + for (int a = 0; a < n - 3; ++a) { + for (int b = a + 1; b < n - 2; ++b) { + for (int c = b + 1; c < n - 1; ++c) { + for (int d = c + 1; d < n; ++d) { + if (nums[a] + nums[b] + nums[c] == nums[d]) { + ++ans; + } + } + } + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int countQuadruplets(vector& nums) { + int ans = 0, n = nums.size(); + for (int a = 0; a < n - 3; ++a) + for (int b = a + 1; b < n - 2; ++b) + for (int c = b + 1; c < n - 1; ++c) + for (int d = c + 1; d < n; ++d) + if (nums[a] + nums[b] + nums[c] == nums[d]) ++ans; + return ans; + } +}; +``` + +```go +func countQuadruplets(nums []int) int { + ans, n := 0, len(nums) + for a := 0; a < n-3; a++ { + for b := a + 1; b < n-2; b++ { + for c := b + 1; c < n-1; c++ { + for d := c + 1; d < n; d++ { + if nums[a]+nums[b]+nums[c] == nums[d] { + ans++ + } + } + } + } + } + return ans +} +``` + + + +### Solution 2 + + + ```python class Solution: def countQuadruplets(self, nums: List[int]) -> int: @@ -80,34 +139,16 @@ class Solution: return ans ``` -```python -class Solution: - def countQuadruplets(self, nums: List[int]) -> int: - ans, n = 0, len(nums) - counter = Counter() - for b in range(n - 3, 0, -1): - c = b + 1 - for d in range(c + 1, n): - counter[nums[d] - nums[c]] += 1 - for a in range(b): - ans += counter[nums[a] + nums[b]] - return ans -``` - -### **Java** - ```java class Solution { public int countQuadruplets(int[] nums) { int ans = 0, n = nums.length; - for (int a = 0; a < n - 3; ++a) { - for (int b = a + 1; b < n - 2; ++b) { - for (int c = b + 1; c < n - 1; ++c) { - for (int d = c + 1; d < n; ++d) { - if (nums[a] + nums[b] + nums[c] == nums[d]) { - ++ans; - } - } + int[] counter = new int[310]; + for (int c = n - 2; c > 1; --c) { + ++counter[nums[c + 1]]; + for (int a = 0; a < c - 1; ++a) { + for (int b = a + 1; b < c; ++b) { + ans += counter[nums[a] + nums[b] + nums[c]]; } } } @@ -116,11 +157,12 @@ class Solution { } ``` -```java +```cpp class Solution { - public int countQuadruplets(int[] nums) { - int ans = 0, n = nums.length; - int[] counter = new int[310]; +public: + int countQuadruplets(vector& nums) { + int ans = 0, n = nums.size(); + vector counter(310); for (int c = n - 2; c > 1; --c) { ++counter[nums[c + 1]]; for (int a = 0; a < c - 1; ++a) { @@ -131,9 +173,45 @@ class Solution { } return ans; } +}; +``` + +```go +func countQuadruplets(nums []int) int { + ans, n := 0, len(nums) + counter := make([]int, 310) + for c := n - 2; c > 1; c-- { + counter[nums[c+1]]++ + for a := 0; a < c-1; a++ { + for b := a + 1; b < c; b++ { + ans += counter[nums[a]+nums[b]+nums[c]] + } + } + } + return ans } ``` + + +### Solution 3 + + + +```python +class Solution: + def countQuadruplets(self, nums: List[int]) -> int: + ans, n = 0, len(nums) + counter = Counter() + for b in range(n - 3, 0, -1): + c = b + 1 + for d in range(c + 1, n): + counter[nums[d] - nums[c]] += 1 + for a in range(b): + ans += counter[nums[a] + nums[b]] + return ans +``` + ```java class Solution { public int countQuadruplets(int[] nums) { @@ -155,42 +233,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int countQuadruplets(vector& nums) { - int ans = 0, n = nums.size(); - for (int a = 0; a < n - 3; ++a) - for (int b = a + 1; b < n - 2; ++b) - for (int c = b + 1; c < n - 1; ++c) - for (int d = c + 1; d < n; ++d) - if (nums[a] + nums[b] + nums[c] == nums[d]) ++ans; - return ans; - } -}; -``` - -```cpp -class Solution { -public: - int countQuadruplets(vector& nums) { - int ans = 0, n = nums.size(); - vector counter(310); - for (int c = n - 2; c > 1; --c) { - ++counter[nums[c + 1]]; - for (int a = 0; a < c - 1; ++a) { - for (int b = a + 1; b < c; ++b) { - ans += counter[nums[a] + nums[b] + nums[c]]; - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -213,42 +255,6 @@ public: }; ``` -### **Go** - -```go -func countQuadruplets(nums []int) int { - ans, n := 0, len(nums) - for a := 0; a < n-3; a++ { - for b := a + 1; b < n-2; b++ { - for c := b + 1; c < n-1; c++ { - for d := c + 1; d < n; d++ { - if nums[a]+nums[b]+nums[c] == nums[d] { - ans++ - } - } - } - } - } - return ans -} -``` - -```go -func countQuadruplets(nums []int) int { - ans, n := 0, len(nums) - counter := make([]int, 310) - for c := n - 2; c > 1; c-- { - counter[nums[c+1]]++ - for a := 0; a < c-1; a++ { - for b := a + 1; b < c; b++ { - ans += counter[nums[a]+nums[b]+nums[c]] - } - } - } - return ans -} -``` - ```go func countQuadruplets(nums []int) int { ans, n := 0, len(nums) @@ -268,10 +274,6 @@ func countQuadruplets(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1996.The Number of Weak Characters in the Game/README.md b/solution/1900-1999/1996.The Number of Weak Characters in the Game/README.md index 9baf93ee1698e..6c2068f7171b0 100644 --- a/solution/1900-1999/1996.The Number of Weak Characters in the Game/README.md +++ b/solution/1900-1999/1996.The Number of Weak Characters in the Game/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:排序 + 遍历** +### 方法一:排序 + 遍历 我们可以将所有角色按照攻击力降序排序,防御力升序排序。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def numberOfWeakCharacters(self, properties: List[List[int]]) -> int: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numberOfWeakCharacters(int[][] properties) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func numberOfWeakCharacters(properties [][]int) (ans int) { sort.Slice(properties, func(i, j int) bool { @@ -139,8 +125,6 @@ func numberOfWeakCharacters(properties [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfWeakCharacters(properties: number[][]): number { properties.sort((a, b) => (a[0] == b[0] ? a[1] - b[1] : b[0] - a[0])); @@ -157,8 +141,6 @@ function numberOfWeakCharacters(properties: number[][]): number { } ``` -### **JavaScript** - ```js /** * @param {number[][]} properties @@ -179,10 +161,6 @@ var numberOfWeakCharacters = function (properties) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1996.The Number of Weak Characters in the Game/README_EN.md b/solution/1900-1999/1996.The Number of Weak Characters in the Game/README_EN.md index e13f171bc11c2..85192ccc177c7 100644 --- a/solution/1900-1999/1996.The Number of Weak Characters in the Game/README_EN.md +++ b/solution/1900-1999/1996.The Number of Weak Characters in the Game/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numberOfWeakCharacters(int[][] properties) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func numberOfWeakCharacters(properties [][]int) (ans int) { sort.Slice(properties, func(i, j int) bool { @@ -119,8 +113,6 @@ func numberOfWeakCharacters(properties [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfWeakCharacters(properties: number[][]): number { properties.sort((a, b) => (a[0] == b[0] ? a[1] - b[1] : b[0] - a[0])); @@ -137,8 +129,6 @@ function numberOfWeakCharacters(properties: number[][]): number { } ``` -### **JavaScript** - ```js /** * @param {number[][]} properties @@ -159,10 +149,6 @@ var numberOfWeakCharacters = function (properties) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1997.First Day Where You Have Been in All the Rooms/README.md b/solution/1900-1999/1997.First Day Where You Have Been in All the Rooms/README.md index 1543ea8c6847c..25a89e155fac8 100644 --- a/solution/1900-1999/1997.First Day Where You Have Been in All the Rooms/README.md +++ b/solution/1900-1999/1997.First Day Where You Have Been in All the Rooms/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示第一次访问第 $i$ 号房间的日期编号,那么答案就是 $f[n - 1]$。 @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int: @@ -96,10 +90,6 @@ class Solution: return f[-1] ``` -### **Java** - - - ```java class Solution { public int firstDayBeenInAllRooms(int[] nextVisit) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func firstDayBeenInAllRooms(nextVisit []int) int { n := len(nextVisit) @@ -145,10 +131,6 @@ func firstDayBeenInAllRooms(nextVisit []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1997.First Day Where You Have Been in All the Rooms/README_EN.md b/solution/1900-1999/1997.First Day Where You Have Been in All the Rooms/README_EN.md index 7f3ef3b8dbf87..86bc3915beb26 100644 --- a/solution/1900-1999/1997.First Day Where You Have Been in All the Rooms/README_EN.md +++ b/solution/1900-1999/1997.First Day Where You Have Been in All the Rooms/README_EN.md @@ -61,9 +61,9 @@ Day 6 is the first day where you have been in all the rooms. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return f[-1] ``` -### **Java** - ```java class Solution { public int firstDayBeenInAllRooms(int[] nextVisit) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +105,6 @@ public: }; ``` -### **Go** - ```go func firstDayBeenInAllRooms(nextVisit []int) int { n := len(nextVisit) @@ -123,10 +117,6 @@ func firstDayBeenInAllRooms(nextVisit []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1998.GCD Sort of an Array/README.md b/solution/1900-1999/1998.GCD Sort of an Array/README.md index 2e6d25b94ea35..536498482c98f 100644 --- a/solution/1900-1999/1998.GCD Sort of an Array/README.md +++ b/solution/1900-1999/1998.GCD Sort of an Array/README.md @@ -54,87 +54,10 @@ ## 解法 - - -并查集。 - -并查集模板: - -模板 1——朴素并查集: - -```python -# 初始化,p存储每个点的父节点 -p = list(range(n)) - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -``` - -模板 2——维护 size 的并查集: - -```python -# 初始化,p存储每个点的父节点,size只有当节点是祖宗节点时才有意义,表示祖宗节点所在集合中,点的数量 -p = list(range(n)) -size = [1] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - # 路径压缩 - p[x] = find(p[x]) - return p[x] - - -# 合并a和b所在的两个集合 -if find(a) != find(b): - size[find(b)] += size[find(a)] - p[find(a)] = find(b) -``` - -模板 3——维护到祖宗节点距离的并查集: - -```python -# 初始化,p存储每个点的父节点,d[x]存储x到p[x]的距离 -p = list(range(n)) -d = [0] * n - - -# 返回x的祖宗节点 -def find(x): - if p[x] != x: - t = find(p[x]) - d[x] += d[p[x]] - p[x] = t - return p[x] - - -# 合并a和b所在的两个集合 -p[find(a)] = find(b) -d[find(a)] = distance -``` - -对于本题,最大公因数大于 1 的两个数,可以进行交换,因此,只要一个集合中所有数都存在相同公因数,那么这个集合中任意数都能进行两两交换,因此可以用并查集,把同个集合中的所有数字进行合并。 - -> 在这道题中,可以先预处理每个数的质因数,数字与质因数归属同一个集合。 - -合并之后,将原数组复制一份,并进行升序排列,得到新数组 s。然后遍历原数组,若原数组对应元素与新数组对应元素不相同,并且两个元素也不在同一个集合中,说明不满足条件,直接返回 false,否则遍历结束返回 true。 +### 方法一 -### **Python3** - - - ```python class Solution: def gcdSort(self, nums: List[int]) -> bool: @@ -164,10 +87,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -216,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -252,8 +169,6 @@ public: }; ``` -### **Go** - ```go var p []int @@ -302,10 +217,6 @@ func find(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1998.GCD Sort of an Array/README_EN.md b/solution/1900-1999/1998.GCD Sort of an Array/README_EN.md index a590b4d776549..2f24bb216ad3a 100644 --- a/solution/1900-1999/1998.GCD Sort of an Array/README_EN.md +++ b/solution/1900-1999/1998.GCD Sort of an Array/README_EN.md @@ -52,12 +52,10 @@ We can sort [10,5,9,3,15] by performing the following operations: ## Solutions -Union find. +### Solution 1 -### **Python3** - ```python class Solution: def gcdSort(self, nums: List[int]) -> bool: @@ -87,8 +85,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { private int[] p; @@ -137,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -173,8 +167,6 @@ public: }; ``` -### **Go** - ```go var p []int @@ -223,10 +215,6 @@ func find(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1999.Smallest Greater Multiple Made of Two Digits/README.md b/solution/1900-1999/1999.Smallest Greater Multiple Made of Two Digits/README.md index 508bc2f23bf00..e9370bbcd99f8 100644 --- a/solution/1900-1999/1999.Smallest Greater Multiple Made of Two Digits/README.md +++ b/solution/1900-1999/1999.Smallest Greater Multiple Made of Two Digits/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们观察 $k$ 的范围,发现 $1 \leq k \leq 1000$,因此,如果 $digit1$ 和 $digit2$ 都为 $0$,那么一定不存在满足条件的整数,直接返回 $-1$ 即可。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def findInteger(self, k: int, digit1: int, digit2: int) -> int: @@ -90,10 +84,6 @@ class Solution: q.append(x * 10 + digit2) ``` -### **Java** - - - ```java class Solution { public int findInteger(int k, int digit1, int digit2) { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func findInteger(k int, digit1 int, digit2 int) int { if digit1 == 0 && digit2 == 0 { @@ -181,10 +167,6 @@ func findInteger(k int, digit1 int, digit2 int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/1900-1999/1999.Smallest Greater Multiple Made of Two Digits/README_EN.md b/solution/1900-1999/1999.Smallest Greater Multiple Made of Two Digits/README_EN.md index 471faa6af0cb5..90859547a80ad 100644 --- a/solution/1900-1999/1999.Smallest Greater Multiple Made of Two Digits/README_EN.md +++ b/solution/1900-1999/1999.Smallest Greater Multiple Made of Two Digits/README_EN.md @@ -53,9 +53,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: q.append(x * 10 + digit2) ``` -### **Java** - ```java class Solution { public int findInteger(int k, int digit1, int digit2) { @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +133,6 @@ public: }; ``` -### **Go** - ```go func findInteger(k int, digit1 int, digit2 int) int { if digit1 == 0 && digit2 == 0 { @@ -165,10 +159,6 @@ func findInteger(k int, digit1 int, digit2 int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2000.Reverse Prefix of Word/README.md b/solution/2000-2099/2000.Reverse Prefix of Word/README.md index beccff6c07122..a507910343b62 100644 --- a/solution/2000-2099/2000.Reverse Prefix of Word/README.md +++ b/solution/2000-2099/2000.Reverse Prefix of Word/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们先找到字符 $ch$ 第一次出现的下标 $i$,然后反转从下标 $0$ 开始、直到下标 $i$ 结束(含下标 $i$)的那段字符,最后将反转后的字符串与下标 $i + 1$ 开始的字符串拼接即可。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def reversePrefix(self, word: str, ch: str) -> str: @@ -73,10 +67,6 @@ class Solution: return word if i == -1 else word[i::-1] + word[i + 1 :] ``` -### **Java** - - - ```java class Solution { public String reversePrefix(String word, char ch) { @@ -95,23 +85,6 @@ class Solution { } ``` -```java -class Solution { - public String reversePrefix(String word, char ch) { - int j = word.indexOf(ch); - if (j == -1) { - return word; - } - return new StringBuilder(word.substring(0, j + 1)) - .reverse() - .append(word.substring(j + 1)) - .toString(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -125,8 +98,6 @@ public: }; ``` -### **Go** - ```go func reversePrefix(word string, ch byte) string { j := strings.IndexByte(word, ch) @@ -142,8 +113,6 @@ func reversePrefix(word string, ch byte) string { } ``` -### **TypeScript** - ```ts function reversePrefix(word: string, ch: string): string { const i = word.indexOf(ch) + 1; @@ -154,8 +123,6 @@ function reversePrefix(word: string, ch: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn reverse_prefix(word: String, ch: char) -> String { @@ -167,8 +134,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -195,10 +160,27 @@ class Solution { } ``` -### **...** + -``` +### 方法二 + + +```java +class Solution { + public String reversePrefix(String word, char ch) { + int j = word.indexOf(ch); + if (j == -1) { + return word; + } + return new StringBuilder(word.substring(0, j + 1)) + .reverse() + .append(word.substring(j + 1)) + .toString(); + } +} ``` + + diff --git a/solution/2000-2099/2000.Reverse Prefix of Word/README_EN.md b/solution/2000-2099/2000.Reverse Prefix of Word/README_EN.md index c13eab2cb0ac4..c6d9366a95a84 100644 --- a/solution/2000-2099/2000.Reverse Prefix of Word/README_EN.md +++ b/solution/2000-2099/2000.Reverse Prefix of Word/README_EN.md @@ -51,7 +51,7 @@ You should not do any reverse operation, the resulting string is "abcd" ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation First, we find the index $i$ where the character $ch$ first appears. Then, we reverse the characters from index $0$ to index $i$ (including index $i$). Finally, we concatenate the reversed string with the string starting from index $i + 1$. @@ -59,8 +59,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def reversePrefix(self, word: str, ch: str) -> str: @@ -68,8 +66,6 @@ class Solution: return word if i == -1 else word[i::-1] + word[i + 1 :] ``` -### **Java** - ```java class Solution { public String reversePrefix(String word, char ch) { @@ -88,23 +84,6 @@ class Solution { } ``` -```java -class Solution { - public String reversePrefix(String word, char ch) { - int j = word.indexOf(ch); - if (j == -1) { - return word; - } - return new StringBuilder(word.substring(0, j + 1)) - .reverse() - .append(word.substring(j + 1)) - .toString(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -118,8 +97,6 @@ public: }; ``` -### **Go** - ```go func reversePrefix(word string, ch byte) string { j := strings.IndexByte(word, ch) @@ -135,8 +112,6 @@ func reversePrefix(word string, ch byte) string { } ``` -### **TypeScript** - ```ts function reversePrefix(word: string, ch: string): string { const i = word.indexOf(ch) + 1; @@ -147,8 +122,6 @@ function reversePrefix(word: string, ch: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn reverse_prefix(word: String, ch: char) -> String { @@ -160,8 +133,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -188,10 +159,27 @@ class Solution { } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + public String reversePrefix(String word, char ch) { + int j = word.indexOf(ch); + if (j == -1) { + return word; + } + return new StringBuilder(word.substring(0, j + 1)) + .reverse() + .append(word.substring(j + 1)) + .toString(); + } +} ``` + + diff --git a/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README.md b/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README.md index 667dec5bda68b..be63bfd5c3bc7 100644 --- a/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README.md +++ b/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:数学 + 哈希表** +### 方法一:数学 + 哈希表 为了能够唯一表示矩形,我们需要将矩形的宽高比化简为最简分数。因此,我们可以求出每个矩形的宽高比的最大公约数,然后将宽高比化简为最简分数。接下来,我们使用哈希表统计每个最简分数的矩形数量,然后计算每个最简分数的矩形数量的组合数,即可得到答案。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def interchangeableRectangles(self, rectangles: List[List[int]]) -> int: @@ -76,10 +70,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long interchangeableRectangles(int[][] rectangles) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func interchangeableRectangles(rectangles [][]int) int64 { ans := 0 @@ -153,8 +139,6 @@ func gcd(a, b int) int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} rectangles @@ -182,10 +166,6 @@ function gcd(a, b) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README_EN.md b/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README_EN.md index 972c1a1f4ed96..cbe5000746977 100644 --- a/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README_EN.md +++ b/solution/2000-2099/2001.Number of Pairs of Interchangeable Rectangles/README_EN.md @@ -45,7 +45,7 @@ ## Solutions -**Solution 1: Mathematics + Hash Table** +### Solution 1: Mathematics + Hash Table In order to uniquely represent a rectangle, we need to simplify the width-to-height ratio of the rectangle to a simplest fraction. Therefore, we can find the greatest common divisor of the width-to-height ratio of each rectangle, and then simplify the width-to-height ratio to the simplest fraction. Next, we use a hash table to count the number of rectangles for each simplest fraction, and then calculate the combination of the number of rectangles for each simplest fraction to get the answer. @@ -53,8 +53,6 @@ The time complexity is $O(n \times \log M)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def interchangeableRectangles(self, rectangles: List[List[int]]) -> int: @@ -68,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long interchangeableRectangles(int[][] rectangles) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func interchangeableRectangles(rectangles [][]int) int64 { ans := 0 @@ -143,8 +135,6 @@ func gcd(a, b int) int { } ``` -### **JavaScript** - ```js /** * @param {number[][]} rectangles @@ -172,10 +162,6 @@ function gcd(a, b) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2002.Maximum Product of the Length of Two Palindromic Subsequences/README.md b/solution/2000-2099/2002.Maximum Product of the Length of Two Palindromic Subsequences/README.md index 7432b4fc2930b..139e96288f9f8 100644 --- a/solution/2000-2099/2002.Maximum Product of the Length of Two Palindromic Subsequences/README.md +++ b/solution/2000-2099/2002.Maximum Product of the Length of Two Palindromic Subsequences/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:二进制枚举** +### 方法一:二进制枚举 我们注意到,字符串 $s$ 的长度不超过 $12$,因此我们可以使用二进制枚举的方法来枚举 $s$ 的所有子序列。不妨设 $s$ 的长度为 $n$,我们可以使用 $2^n$ 个长度为 $n$ 的二进制数来表示 $s$ 的所有子序列。对于每个二进制数,第 $i$ 位为 $1$ 表示 $s$ 的第 $i$ 个字符在子序列中,为 $0$ 表示不在子序列中。我们对于每个二进制数,判断其是否为回文子序列,并且记录在数组 $p$ 中。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def maxProduct(self, s: str) -> int: @@ -97,10 +91,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxProduct(String s) { @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -179,8 +167,6 @@ public: }; ``` -### **Go** - ```go func maxProduct(s string) (ans int) { n := len(s) @@ -219,10 +205,6 @@ func maxProduct(s string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2002.Maximum Product of the Length of Two Palindromic Subsequences/README_EN.md b/solution/2000-2099/2002.Maximum Product of the Length of Two Palindromic Subsequences/README_EN.md index c2383c0890906..7e3316ebb5f84 100644 --- a/solution/2000-2099/2002.Maximum Product of the Length of Two Palindromic Subsequences/README_EN.md +++ b/solution/2000-2099/2002.Maximum Product of the Length of Two Palindromic Subsequences/README_EN.md @@ -48,7 +48,7 @@ The product of their lengths is: 5 * 5 = 25. ## Solutions -**Solution 1: Binary Enumeration** +### Solution 1: Binary Enumeration We notice that the length of the string $s$ does not exceed $12$, so we can use the method of binary enumeration to enumerate all subsequences of $s$. Suppose the length of $s$ is $n$, we can use $2^n$ binary numbers of length $n$ to represent all subsequences of $s$. For each binary number, the $i$-th bit being $1$ means the $i$-th character of $s$ is in the subsequence, and $0$ means it is not in the subsequence. For each binary number, we judge whether it is a palindrome subsequence and record it in the array $p$. @@ -58,8 +58,6 @@ The time complexity is $(2^n \times n + 3^n)$, and the space complexity is $O(2^ -### **Python3** - ```python class Solution: def maxProduct(self, s: str) -> int: @@ -90,8 +88,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxProduct(String s) { @@ -130,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +164,6 @@ public: }; ``` -### **Go** - ```go func maxProduct(s string) (ans int) { n := len(s) @@ -210,10 +202,6 @@ func maxProduct(s string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/README.md b/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/README.md index 0d284d5cce617..b85e6677e5650 100644 --- a/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/README.md +++ b/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们注意到,每个节点的基因值互不相同,因此,我们只需要找到基因值为 $1$ 的节点 $idx$,那么除了从节点 $idx$ 到根节点 $0$ 的每个节点,其它节点的答案都是 $1$。 @@ -87,10 +85,6 @@ -### **Python3** - - - ```python class Solution: def smallestMissingValueSubtree( @@ -128,10 +122,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -185,8 +175,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -234,8 +222,6 @@ public: }; ``` -### **Go** - ```go func smallestMissingValueSubtree(parents []int, nums []int) []int { n := len(nums) @@ -280,7 +266,47 @@ func smallestMissingValueSubtree(parents []int, nums []int) []int { } ``` -### **Rust** +```ts +function smallestMissingValueSubtree(parents: number[], nums: number[]): number[] { + const n = nums.length; + const g: number[][] = Array.from({ length: n }, () => []); + const vis: boolean[] = Array(n).fill(false); + const has: boolean[] = Array(n + 2).fill(false); + const ans: number[] = Array(n).fill(1); + let idx = -1; + for (let i = 0; i < n; ++i) { + if (i) { + g[parents[i]].push(i); + } + if (nums[i] === 1) { + idx = i; + } + } + if (idx === -1) { + return ans; + } + const dfs = (i: number): void => { + if (vis[i]) { + return; + } + vis[i] = true; + if (nums[i] < has.length) { + has[nums[i]] = true; + } + for (const j of g[i]) { + dfs(j); + } + }; + for (let i = 2; ~idx; idx = parents[idx]) { + dfs(idx); + while (has[i]) { + ++i; + } + ans[idx] = i; + } + return ans; +} +``` ```rust impl Solution { @@ -336,54 +362,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function smallestMissingValueSubtree(parents: number[], nums: number[]): number[] { - const n = nums.length; - const g: number[][] = Array.from({ length: n }, () => []); - const vis: boolean[] = Array(n).fill(false); - const has: boolean[] = Array(n + 2).fill(false); - const ans: number[] = Array(n).fill(1); - let idx = -1; - for (let i = 0; i < n; ++i) { - if (i) { - g[parents[i]].push(i); - } - if (nums[i] === 1) { - idx = i; - } - } - if (idx === -1) { - return ans; - } - const dfs = (i: number): void => { - if (vis[i]) { - return; - } - vis[i] = true; - if (nums[i] < has.length) { - has[nums[i]] = true; - } - for (const j of g[i]) { - dfs(j); - } - }; - for (let i = 2; ~idx; idx = parents[idx]) { - dfs(idx); - while (has[i]) { - ++i; - } - ans[idx] = i; - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/README_EN.md b/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/README_EN.md index 5fc3e00da5e39..45864948974c8 100644 --- a/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/README_EN.md +++ b/solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/README_EN.md @@ -62,7 +62,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We notice that each node has a unique gene value, so we only need to find the node $idx$ with gene value $1$, and all nodes except for those on the path from node $idx$ to the root node $0$ have an answer of $1$. @@ -80,8 +80,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def smallestMissingValueSubtree( @@ -119,8 +117,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -174,8 +170,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -223,8 +217,6 @@ public: }; ``` -### **Go** - ```go func smallestMissingValueSubtree(parents []int, nums []int) []int { n := len(nums) @@ -269,7 +261,47 @@ func smallestMissingValueSubtree(parents []int, nums []int) []int { } ``` -### **Rust** +```ts +function smallestMissingValueSubtree(parents: number[], nums: number[]): number[] { + const n = nums.length; + const g: number[][] = Array.from({ length: n }, () => []); + const vis: boolean[] = Array(n).fill(false); + const has: boolean[] = Array(n + 2).fill(false); + const ans: number[] = Array(n).fill(1); + let idx = -1; + for (let i = 0; i < n; ++i) { + if (i) { + g[parents[i]].push(i); + } + if (nums[i] === 1) { + idx = i; + } + } + if (idx === -1) { + return ans; + } + const dfs = (i: number): void => { + if (vis[i]) { + return; + } + vis[i] = true; + if (nums[i] < has.length) { + has[nums[i]] = true; + } + for (const j of g[i]) { + dfs(j); + } + }; + for (let i = 2; ~idx; idx = parents[idx]) { + dfs(idx); + while (has[i]) { + ++i; + } + ans[idx] = i; + } + return ans; +} +``` ```rust impl Solution { @@ -325,54 +357,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function smallestMissingValueSubtree(parents: number[], nums: number[]): number[] { - const n = nums.length; - const g: number[][] = Array.from({ length: n }, () => []); - const vis: boolean[] = Array(n).fill(false); - const has: boolean[] = Array(n + 2).fill(false); - const ans: number[] = Array(n).fill(1); - let idx = -1; - for (let i = 0; i < n; ++i) { - if (i) { - g[parents[i]].push(i); - } - if (nums[i] === 1) { - idx = i; - } - } - if (idx === -1) { - return ans; - } - const dfs = (i: number): void => { - if (vis[i]) { - return; - } - vis[i] = true; - if (nums[i] < has.length) { - has[nums[i]] = true; - } - for (const j of g[i]) { - dfs(j); - } - }; - for (let i = 2; ~idx; idx = parents[idx]) { - dfs(idx); - while (has[i]) { - ++i; - } - ans[idx] = i; - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2004.The Number of Seniors and Juniors to Join the Company/README.md b/solution/2000-2099/2004.The Number of Seniors and Juniors to Join the Company/README.md index b3dcc52dcb8c5..342219924ad00 100644 --- a/solution/2000-2099/2004.The Number of Seniors and Juniors to Join the Company/README.md +++ b/solution/2000-2099/2004.The Number of Seniors and Juniors to Join the Company/README.md @@ -90,9 +90,7 @@ Candidates table: ## 解法 - - -**方法一:窗口函数** +### 方法一:窗口函数 相似题目: @@ -100,10 +98,6 @@ Candidates table: -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -141,3 +135,5 @@ WHERE cur <= 70000; ``` + + diff --git a/solution/2000-2099/2004.The Number of Seniors and Juniors to Join the Company/README_EN.md b/solution/2000-2099/2004.The Number of Seniors and Juniors to Join the Company/README_EN.md index 5e2ec440383c6..eee2d8b9a0ddf 100644 --- a/solution/2000-2099/2004.The Number of Seniors and Juniors to Join the Company/README_EN.md +++ b/solution/2000-2099/2004.The Number of Seniors and Juniors to Join the Company/README_EN.md @@ -91,9 +91,9 @@ We can hire all three juniors with the remaining budget. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -132,3 +132,5 @@ WHERE cur <= 70000; ``` + + diff --git a/solution/2000-2099/2005.Subtree Removal Game with Fibonacci Tree/README.md b/solution/2000-2099/2005.Subtree Removal Game with Fibonacci Tree/README.md index 7e1e2ff8e1654..a741264eb1af3 100644 --- a/solution/2000-2099/2005.Subtree Removal Game with Fibonacci Tree/README.md +++ b/solution/2000-2099/2005.Subtree Removal Game with Fibonacci Tree/README.md @@ -69,30 +69,4 @@ Bob 只能删除根节点 2,所以 Bob 输了。 ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2000-2099/2005.Subtree Removal Game with Fibonacci Tree/README_EN.md b/solution/2000-2099/2005.Subtree Removal Game with Fibonacci Tree/README_EN.md index 9a41c4eb4f29d..023b90b021969 100644 --- a/solution/2000-2099/2005.Subtree Removal Game with Fibonacci Tree/README_EN.md +++ b/solution/2000-2099/2005.Subtree Removal Game with Fibonacci Tree/README_EN.md @@ -65,24 +65,4 @@ Return true because Alice wins. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README.md b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README.md index 69a90157d713d..129243272324e 100644 --- a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README.md +++ b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 我们注意到,数组 $nums$ 的长度不超过 $200$,因此我们可以枚举所有的数对 $(i, j)$,其中 $i < j$,并判断 $|nums[i] - nums[j]|$ 是否等于 $k$,是则答案加一。 @@ -67,20 +65,8 @@ 时间复杂度 $O(n^2)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。 -**方法二:哈希表或数组** - -我们可以使用哈希表或数组记录数组 $nums$ 中每个数出现的次数,然后枚举数组 $nums$ 中的每个数 $x$,判断 $x + k$ 和 $x - k$ 是否在数组 $nums$ 中,是则答案加上 $x+k$ 和 $x-k$ 出现的次数之和。 - -最后返回答案即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 - -### **Python3** - - - ```python class Solution: def countKDifference(self, nums: List[int], k: int) -> int: @@ -90,21 +76,6 @@ class Solution: ) ``` -```python -class Solution: - def countKDifference(self, nums: List[int], k: int) -> int: - ans = 0 - cnt = Counter() - for num in nums: - ans += cnt[num - k] + cnt[num + k] - cnt[num] += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int countKDifference(int[] nums, int k) { @@ -121,27 +92,6 @@ class Solution { } ``` -```java -class Solution { - public int countKDifference(int[] nums, int k) { - int ans = 0; - int[] cnt = new int[110]; - for (int num : nums) { - if (num >= k) { - ans += cnt[num - k]; - } - if (num + k <= 100) { - ans += cnt[num + k]; - } - ++cnt[num]; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -158,28 +108,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countKDifference(vector& nums, int k) { - int ans = 0; - int cnt[110]{}; - for (int num : nums) { - if (num >= k) { - ans += cnt[num - k]; - } - if (num + k <= 100) { - ans += cnt[num + k]; - } - ++cnt[num]; - } - return ans; - } -}; -``` - -### **Go** - ```go func countKDifference(nums []int, k int) int { n := len(nums) @@ -202,24 +130,6 @@ func abs(x int) int { } ``` -```go -func countKDifference(nums []int, k int) (ans int) { - cnt := [110]int{} - for _, num := range nums { - if num >= k { - ans += cnt[num-k] - } - if num+k <= 100 { - ans += cnt[num+k] - } - cnt[num]++ - } - return -} -``` - -### **TypeScript** - ```ts function countKDifference(nums: number[], k: number): number { let ans = 0; @@ -232,8 +142,6 @@ function countKDifference(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_k_difference(nums: Vec, k: i32) -> i32 { @@ -251,6 +159,84 @@ impl Solution { } ``` + + +### 方法二:哈希表或数组 + +我们可以使用哈希表或数组记录数组 $nums$ 中每个数出现的次数,然后枚举数组 $nums$ 中的每个数 $x$,判断 $x + k$ 和 $x - k$ 是否在数组 $nums$ 中,是则答案加上 $x+k$ 和 $x-k$ 出现的次数之和。 + +最后返回答案即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 + + + +```python +class Solution: + def countKDifference(self, nums: List[int], k: int) -> int: + ans = 0 + cnt = Counter() + for num in nums: + ans += cnt[num - k] + cnt[num + k] + cnt[num] += 1 + return ans +``` + +```java +class Solution { + public int countKDifference(int[] nums, int k) { + int ans = 0; + int[] cnt = new int[110]; + for (int num : nums) { + if (num >= k) { + ans += cnt[num - k]; + } + if (num + k <= 100) { + ans += cnt[num + k]; + } + ++cnt[num]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int countKDifference(vector& nums, int k) { + int ans = 0; + int cnt[110]{}; + for (int num : nums) { + if (num >= k) { + ans += cnt[num - k]; + } + if (num + k <= 100) { + ans += cnt[num + k]; + } + ++cnt[num]; + } + return ans; + } +}; +``` + +```go +func countKDifference(nums []int, k int) (ans int) { + cnt := [110]int{} + for _, num := range nums { + if num >= k { + ans += cnt[num-k] + } + if num+k <= 100 { + ans += cnt[num+k] + } + cnt[num]++ + } + return +} +``` + ```rust impl Solution { pub fn count_k_difference(nums: Vec, k: i32) -> i32 { @@ -270,10 +256,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README_EN.md b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README_EN.md index e8c6442012b0e..15eba02e244fe 100644 --- a/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README_EN.md +++ b/solution/2000-2099/2006.Count Number of Pairs With Absolute Difference K/README_EN.md @@ -56,7 +56,7 @@ ## Solutions -**Solution 1: Brute Force Enumeration** +### Solution 1: Brute Force Enumeration We notice that the length of the array $nums$ does not exceed $200$, so we can enumerate all pairs $(i, j)$, where $i < j$, and check if $|nums[i] - nums[j]|$ equals $k$. If it does, we increment the answer by one. @@ -64,18 +64,8 @@ Finally, we return the answer. The time complexity is $O(n^2)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$. -**Solution 2: Hash Table or Array** - -We can use a hash table or array to record the occurrence count of each number in the array $nums$. Then, we enumerate each number $x$ in the array $nums$, and check if $x + k$ and $x - k$ are in the array $nums$. If they are, we increment the answer by the sum of the occurrence counts of $x + k$ and $x - k$. - -Finally, we return the answer. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. - -### **Python3** - ```python class Solution: def countKDifference(self, nums: List[int], k: int) -> int: @@ -85,19 +75,6 @@ class Solution: ) ``` -```python -class Solution: - def countKDifference(self, nums: List[int], k: int) -> int: - ans = 0 - cnt = Counter() - for num in nums: - ans += cnt[num - k] + cnt[num + k] - cnt[num] += 1 - return ans -``` - -### **Java** - ```java class Solution { public int countKDifference(int[] nums, int k) { @@ -114,27 +91,6 @@ class Solution { } ``` -```java -class Solution { - public int countKDifference(int[] nums, int k) { - int ans = 0; - int[] cnt = new int[110]; - for (int num : nums) { - if (num >= k) { - ans += cnt[num - k]; - } - if (num + k <= 100) { - ans += cnt[num + k]; - } - ++cnt[num]; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -151,28 +107,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countKDifference(vector& nums, int k) { - int ans = 0; - int cnt[110]{}; - for (int num : nums) { - if (num >= k) { - ans += cnt[num - k]; - } - if (num + k <= 100) { - ans += cnt[num + k]; - } - ++cnt[num]; - } - return ans; - } -}; -``` - -### **Go** - ```go func countKDifference(nums []int, k int) int { n := len(nums) @@ -195,24 +129,6 @@ func abs(x int) int { } ``` -```go -func countKDifference(nums []int, k int) (ans int) { - cnt := [110]int{} - for _, num := range nums { - if num >= k { - ans += cnt[num-k] - } - if num+k <= 100 { - ans += cnt[num+k] - } - cnt[num]++ - } - return -} -``` - -### **TypeScript** - ```ts function countKDifference(nums: number[], k: number): number { let ans = 0; @@ -225,8 +141,6 @@ function countKDifference(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_k_difference(nums: Vec, k: i32) -> i32 { @@ -244,6 +158,84 @@ impl Solution { } ``` + + +### Solution 2: Hash Table or Array + +We can use a hash table or array to record the occurrence count of each number in the array $nums$. Then, we enumerate each number $x$ in the array $nums$, and check if $x + k$ and $x - k$ are in the array $nums$. If they are, we increment the answer by the sum of the occurrence counts of $x + k$ and $x - k$. + +Finally, we return the answer. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. + + + +```python +class Solution: + def countKDifference(self, nums: List[int], k: int) -> int: + ans = 0 + cnt = Counter() + for num in nums: + ans += cnt[num - k] + cnt[num + k] + cnt[num] += 1 + return ans +``` + +```java +class Solution { + public int countKDifference(int[] nums, int k) { + int ans = 0; + int[] cnt = new int[110]; + for (int num : nums) { + if (num >= k) { + ans += cnt[num - k]; + } + if (num + k <= 100) { + ans += cnt[num + k]; + } + ++cnt[num]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int countKDifference(vector& nums, int k) { + int ans = 0; + int cnt[110]{}; + for (int num : nums) { + if (num >= k) { + ans += cnt[num - k]; + } + if (num + k <= 100) { + ans += cnt[num + k]; + } + ++cnt[num]; + } + return ans; + } +}; +``` + +```go +func countKDifference(nums []int, k int) (ans int) { + cnt := [110]int{} + for _, num := range nums { + if num >= k { + ans += cnt[num-k] + } + if num+k <= 100 { + ans += cnt[num+k] + } + cnt[num]++ + } + return +} +``` + ```rust impl Solution { pub fn count_k_difference(nums: Vec, k: i32) -> i32 { @@ -263,10 +255,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2007.Find Original Array From Doubled Array/README.md b/solution/2000-2099/2007.Find Original Array From Doubled Array/README.md index 87e784a3b3386..98dd10e389e2b 100644 --- a/solution/2000-2099/2007.Find Original Array From Doubled Array/README.md +++ b/solution/2000-2099/2007.Find Original Array From Doubled Array/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:排序 + 计数 + 遍历** +### 方法一:排序 + 计数 + 遍历 我们先判断数组 `changed` 的长度 $n$ 是否为奇数,若是,则直接返回空数组。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def findOriginalArray(self, changed: List[int]) -> List[int]: @@ -88,10 +82,6 @@ class Solution: return ans if len(ans) == n // 2 else [] ``` -### **Java** - - - ```java class Solution { public int[] findOriginalArray(int[] changed) { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func findOriginalArray(changed []int) []int { n := len(changed) @@ -186,8 +172,6 @@ func findOriginalArray(changed []int) []int { } ``` -### **TypeScript** - ```ts function findOriginalArray(changed: number[]): number[] { const n = changed.length; @@ -215,10 +199,6 @@ function findOriginalArray(changed: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2007.Find Original Array From Doubled Array/README_EN.md b/solution/2000-2099/2007.Find Original Array From Doubled Array/README_EN.md index 0df1b54ba8d62..c4b16f18dc169 100644 --- a/solution/2000-2099/2007.Find Original Array From Doubled Array/README_EN.md +++ b/solution/2000-2099/2007.Find Original Array From Doubled Array/README_EN.md @@ -47,7 +47,7 @@ Other original arrays could be [4,3,1] or [3,1,4]. ## Solutions -**Solution 1: Sorting + Counting + Traversal** +### Solution 1: Sorting + Counting + Traversal First, we check if the length $n$ of the array `changed` is odd. If it is, we directly return an empty array. @@ -61,8 +61,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def findOriginalArray(self, changed: List[int]) -> List[int]: @@ -83,8 +81,6 @@ class Solution: return ans if len(ans) == n // 2 else [] ``` -### **Java** - ```java class Solution { public int[] findOriginalArray(int[] changed) { @@ -115,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +141,6 @@ public: }; ``` -### **Go** - ```go func findOriginalArray(changed []int) []int { n := len(changed) @@ -179,8 +171,6 @@ func findOriginalArray(changed []int) []int { } ``` -### **TypeScript** - ```ts function findOriginalArray(changed: number[]): number[] { const n = changed.length; @@ -208,10 +198,6 @@ function findOriginalArray(changed: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2008.Maximum Earnings From Taxi/README.md b/solution/2000-2099/2008.Maximum Earnings From Taxi/README.md index 741ce76fba85d..1dbec4161aa2a 100644 --- a/solution/2000-2099/2008.Maximum Earnings From Taxi/README.md +++ b/solution/2000-2099/2008.Maximum Earnings From Taxi/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:记忆化搜索 + 二分查找** +### 方法一:记忆化搜索 + 二分查找 我们先将 $rides$ 按照$start$ 从小到大排序,然后设计一个函数 $dfs(i)$,表示从第 $i$ 个乘客开始接单,最多能获得的小费。答案即为 $dfs(0)$。 @@ -69,33 +67,8 @@ $$ 时间复杂度 $O(m \times \log m)$,空间复杂度 $O(m)$。其中 $m$ 为$rides$ 的长度。 -**方法二:动态规划 + 二分查找** - -我们可以将方法一中的记忆化搜索改为动态规划。 - -先将 $rides$ 排序,这次我们按照 $end$ 从小到大排序。然后定义 $f[i]$,表示前 $i$ 个乘客中,最多能获得的小费。初始时 $f[0] = 0$,答案为 $f[m]$。 - -对于第 $i$ 个乘客,我们可以选择接单,也可以选择不接单。如果不接单,那么最多能获得的小费为 $f[i-1]$;如果接单,我们可以通过二分查找,找到在第 $i$ 个乘客上车地点之前,最后一个下车地点不大于 $start_i$ 的乘客,记为 $j$,那么最多能获得的小费为 $f[j] + end_i - start_i + tip_i$。取两者的较大值即可。即: - -$$ -f[i] = \max(f[i - 1], f[j] + end_i - start_i + tip_i) -$$ - -其中 $j$ 是满足 $end_j \le start_i$ 的最大的下标,可以通过二分查找得到。 - -时间复杂度 $O(m \times \log m)$,空间复杂度 $O(m)$。其中 $m$ 为$rides$ 的长度。 - -相似题目: - -- [1235. 规划兼职工作](/solution/1200-1299/1235.Maximum%20Profit%20in%20Job%20Scheduling/README.md) -- [1751. 最多可以参加的会议数目 II](/solution/1700-1799/1751.Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended%20II/README.md) - -### **Python3** - - - ```python class Solution: def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: @@ -111,21 +84,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: - rides.sort(key=lambda x: x[1]) - f = [0] * (len(rides) + 1) - for i, (st, ed, tip) in enumerate(rides, 1): - j = bisect_left(rides, st + 1, hi=i, key=lambda x: x[1]) - f[i] = max(f[i - 1], f[j] + ed - st + tip) - return f[-1] -``` - -### **Java** - - - ```java class Solution { private int m; @@ -168,38 +126,6 @@ class Solution { } ``` -```java -class Solution { - public long maxTaxiEarnings(int n, int[][] rides) { - Arrays.sort(rides, (a, b) -> a[1] - b[1]); - int m = rides.length; - long[] f = new long[m + 1]; - for (int i = 1; i <= m; ++i) { - int[] r = rides[i - 1]; - int st = r[0], ed = r[1], tip = r[2]; - int j = search(rides, st + 1, i); - f[i] = Math.max(f[i - 1], f[j] + ed - st + tip); - } - return f[m]; - } - - private int search(int[][] nums, int x, int r) { - int l = 0; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid][1] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -225,27 +151,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long maxTaxiEarnings(int n, vector>& rides) { - sort(rides.begin(), rides.end(), [](const vector& a, const vector& b) { return a[1] < b[1]; }); - int m = rides.size(); - vector f(m + 1); - for (int i = 1; i <= m; ++i) { - auto& r = rides[i - 1]; - int st = r[0], ed = r[1], tip = r[2]; - auto it = lower_bound(rides.begin(), rides.begin() + i, st + 1, [](auto& a, int val) { return a[1] < val; }); - int j = distance(rides.begin(), it); - f[i] = max(f[i - 1], f[j] + ed - st + tip); - } - return f.back(); - } -}; -``` - -### **Go** - ```go func maxTaxiEarnings(n int, rides [][]int) int64 { sort.Slice(rides, func(i, j int) bool { return rides[i][0] < rides[j][0] }) @@ -267,23 +172,6 @@ func maxTaxiEarnings(n int, rides [][]int) int64 { } ``` -```go -func maxTaxiEarnings(n int, rides [][]int) int64 { - sort.Slice(rides, func(i, j int) bool { return rides[i][1] < rides[j][1] }) - m := len(rides) - f := make([]int64, m+1) - for i := 1; i <= m; i++ { - r := rides[i-1] - st, ed, tip := r[0], r[1], r[2] - j := sort.Search(m, func(j int) bool { return rides[j][1] >= st+1 }) - f[i] = max(f[i-1], f[j]+int64(ed-st+tip)) - } - return f[m] -} -``` - -### **TypeScript** - ```ts function maxTaxiEarnings(n: number, rides: number[][]): number { rides.sort((a, b) => a[0] - b[0]); @@ -316,6 +204,106 @@ function maxTaxiEarnings(n: number, rides: number[][]): number { } ``` + + +### 方法二:动态规划 + 二分查找 + +我们可以将方法一中的记忆化搜索改为动态规划。 + +先将 $rides$ 排序,这次我们按照 $end$ 从小到大排序。然后定义 $f[i]$,表示前 $i$ 个乘客中,最多能获得的小费。初始时 $f[0] = 0$,答案为 $f[m]$。 + +对于第 $i$ 个乘客,我们可以选择接单,也可以选择不接单。如果不接单,那么最多能获得的小费为 $f[i-1]$;如果接单,我们可以通过二分查找,找到在第 $i$ 个乘客上车地点之前,最后一个下车地点不大于 $start_i$ 的乘客,记为 $j$,那么最多能获得的小费为 $f[j] + end_i - start_i + tip_i$。取两者的较大值即可。即: + +$$ +f[i] = \max(f[i - 1], f[j] + end_i - start_i + tip_i) +$$ + +其中 $j$ 是满足 $end_j \le start_i$ 的最大的下标,可以通过二分查找得到。 + +时间复杂度 $O(m \times \log m)$,空间复杂度 $O(m)$。其中 $m$ 为$rides$ 的长度。 + +相似题目: + +- [1235. 规划兼职工作](/solution/1200-1299/1235.Maximum%20Profit%20in%20Job%20Scheduling/README.md) +- [1751. 最多可以参加的会议数目 II](/solution/1700-1799/1751.Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended%20II/README.md) + + + +```python +class Solution: + def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: + rides.sort(key=lambda x: x[1]) + f = [0] * (len(rides) + 1) + for i, (st, ed, tip) in enumerate(rides, 1): + j = bisect_left(rides, st + 1, hi=i, key=lambda x: x[1]) + f[i] = max(f[i - 1], f[j] + ed - st + tip) + return f[-1] +``` + +```java +class Solution { + public long maxTaxiEarnings(int n, int[][] rides) { + Arrays.sort(rides, (a, b) -> a[1] - b[1]); + int m = rides.length; + long[] f = new long[m + 1]; + for (int i = 1; i <= m; ++i) { + int[] r = rides[i - 1]; + int st = r[0], ed = r[1], tip = r[2]; + int j = search(rides, st + 1, i); + f[i] = Math.max(f[i - 1], f[j] + ed - st + tip); + } + return f[m]; + } + + private int search(int[][] nums, int x, int r) { + int l = 0; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid][1] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } +} +``` + +```cpp +class Solution { +public: + long long maxTaxiEarnings(int n, vector>& rides) { + sort(rides.begin(), rides.end(), [](const vector& a, const vector& b) { return a[1] < b[1]; }); + int m = rides.size(); + vector f(m + 1); + for (int i = 1; i <= m; ++i) { + auto& r = rides[i - 1]; + int st = r[0], ed = r[1], tip = r[2]; + auto it = lower_bound(rides.begin(), rides.begin() + i, st + 1, [](auto& a, int val) { return a[1] < val; }); + int j = distance(rides.begin(), it); + f[i] = max(f[i - 1], f[j] + ed - st + tip); + } + return f.back(); + } +}; +``` + +```go +func maxTaxiEarnings(n int, rides [][]int) int64 { + sort.Slice(rides, func(i, j int) bool { return rides[i][1] < rides[j][1] }) + m := len(rides) + f := make([]int64, m+1) + for i := 1; i <= m; i++ { + r := rides[i-1] + st, ed, tip := r[0], r[1], r[2] + j := sort.Search(m, func(j int) bool { return rides[j][1] >= st+1 }) + f[i] = max(f[i-1], f[j]+int64(ed-st+tip)) + } + return f[m] +} +``` + ```ts function maxTaxiEarnings(n: number, rides: number[][]): number { rides.sort((a, b) => a[1] - b[1]); @@ -342,10 +330,6 @@ function maxTaxiEarnings(n: number, rides: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2008.Maximum Earnings From Taxi/README_EN.md b/solution/2000-2099/2008.Maximum Earnings From Taxi/README_EN.md index c5efc0bae5f68..50e07ac1e6247 100644 --- a/solution/2000-2099/2008.Maximum Earnings From Taxi/README_EN.md +++ b/solution/2000-2099/2008.Maximum Earnings From Taxi/README_EN.md @@ -47,7 +47,7 @@ We earn 9 + 5 + 6 = 20 dollars in total. ## Solutions -**Solution 1: Memoization Search + Binary Search** +### Solution 1: Memoization Search + Binary Search First, we sort $rides$ in ascending order by $start$. Then we design a function $dfs(i)$, which represents the maximum tip that can be obtained from accepting orders starting from the $i$-th passenger. The answer is $dfs(0)$. @@ -65,31 +65,8 @@ In this process, we can use memoization search to save the answer of each state The time complexity is $O(m \times \log m)$, and the space complexity is $O(m)$. Here, $m$ is the length of $rides$. -**Solution 2: Dynamic Programming + Binary Search** - -We can change the memoization search in Solution 1 to dynamic programming. - -First, sort $rides$, this time we sort by $end$ in ascending order. Then define $f[i]$, which represents the maximum tip that can be obtained from the first $i$ passengers. Initially, $f[0] = 0$, and the answer is $f[m]$. - -For the $i$-th passenger, we can choose to accept or not to accept the order. If we don't accept the order, the maximum tip that can be obtained is $f[i-1]$. If we accept the order, we can use binary search to find the last passenger whose drop-off point is not greater than $start_i$ before the $i$-th passenger gets on the car, denoted as $j$. The maximum tip that can be obtained is $f[j] + end_i - start_i + tip_i$. Take the larger of the two. That is: - -$$ -f[i] = \max(f[i - 1], f[j] + end_i - start_i + tip_i) -$$ - -Where $j$ is the largest index that satisfies $end_j \le start_i$, which can be obtained by binary search. - -The time complexity is $O(m \times \log m)$, and the space complexity is $O(m)$. Here, $m$ is the length of $rides$. - -Similar problems: - -- [1235. Maximum Profit in Job Scheduling](/solution/1200-1299/1235.Maximum%20Profit%20in%20Job%20Scheduling/README_EN.md) -- [1751. Maximum Number of Events That Can Be Attended II](/solution/1700-1799/1751.Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended%20II/README_EN.md) - -### **Python3** - ```python class Solution: def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: @@ -105,19 +82,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: - rides.sort(key=lambda x: x[1]) - f = [0] * (len(rides) + 1) - for i, (st, ed, tip) in enumerate(rides, 1): - j = bisect_left(rides, st + 1, hi=i, key=lambda x: x[1]) - f[i] = max(f[i - 1], f[j] + ed - st + tip) - return f[-1] -``` - -### **Java** - ```java class Solution { private int m; @@ -160,38 +124,6 @@ class Solution { } ``` -```java -class Solution { - public long maxTaxiEarnings(int n, int[][] rides) { - Arrays.sort(rides, (a, b) -> a[1] - b[1]); - int m = rides.length; - long[] f = new long[m + 1]; - for (int i = 1; i <= m; ++i) { - int[] r = rides[i - 1]; - int st = r[0], ed = r[1], tip = r[2]; - int j = search(rides, st + 1, i); - f[i] = Math.max(f[i - 1], f[j] + ed - st + tip); - } - return f[m]; - } - - private int search(int[][] nums, int x, int r) { - int l = 0; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid][1] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -217,27 +149,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long maxTaxiEarnings(int n, vector>& rides) { - sort(rides.begin(), rides.end(), [](const vector& a, const vector& b) { return a[1] < b[1]; }); - int m = rides.size(); - vector f(m + 1); - for (int i = 1; i <= m; ++i) { - auto& r = rides[i - 1]; - int st = r[0], ed = r[1], tip = r[2]; - auto it = lower_bound(rides.begin(), rides.begin() + i, st + 1, [](auto& a, int val) { return a[1] < val; }); - int j = distance(rides.begin(), it); - f[i] = max(f[i - 1], f[j] + ed - st + tip); - } - return f.back(); - } -}; -``` - -### **Go** - ```go func maxTaxiEarnings(n int, rides [][]int) int64 { sort.Slice(rides, func(i, j int) bool { return rides[i][0] < rides[j][0] }) @@ -259,23 +170,6 @@ func maxTaxiEarnings(n int, rides [][]int) int64 { } ``` -```go -func maxTaxiEarnings(n int, rides [][]int) int64 { - sort.Slice(rides, func(i, j int) bool { return rides[i][1] < rides[j][1] }) - m := len(rides) - f := make([]int64, m+1) - for i := 1; i <= m; i++ { - r := rides[i-1] - st, ed, tip := r[0], r[1], r[2] - j := sort.Search(m, func(j int) bool { return rides[j][1] >= st+1 }) - f[i] = max(f[i-1], f[j]+int64(ed-st+tip)) - } - return f[m] -} -``` - -### **TypeScript** - ```ts function maxTaxiEarnings(n: number, rides: number[][]): number { rides.sort((a, b) => a[0] - b[0]); @@ -308,6 +202,106 @@ function maxTaxiEarnings(n: number, rides: number[][]): number { } ``` + + +### Solution 2: Dynamic Programming + Binary Search + +We can change the memoization search in Solution 1 to dynamic programming. + +First, sort $rides$, this time we sort by $end$ in ascending order. Then define $f[i]$, which represents the maximum tip that can be obtained from the first $i$ passengers. Initially, $f[0] = 0$, and the answer is $f[m]$. + +For the $i$-th passenger, we can choose to accept or not to accept the order. If we don't accept the order, the maximum tip that can be obtained is $f[i-1]$. If we accept the order, we can use binary search to find the last passenger whose drop-off point is not greater than $start_i$ before the $i$-th passenger gets on the car, denoted as $j$. The maximum tip that can be obtained is $f[j] + end_i - start_i + tip_i$. Take the larger of the two. That is: + +$$ +f[i] = \max(f[i - 1], f[j] + end_i - start_i + tip_i) +$$ + +Where $j$ is the largest index that satisfies $end_j \le start_i$, which can be obtained by binary search. + +The time complexity is $O(m \times \log m)$, and the space complexity is $O(m)$. Here, $m$ is the length of $rides$. + +Similar problems: + +- [1235. Maximum Profit in Job Scheduling](/solution/1200-1299/1235.Maximum%20Profit%20in%20Job%20Scheduling/README_EN.md) +- [1751. Maximum Number of Events That Can Be Attended II](/solution/1700-1799/1751.Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended%20II/README_EN.md) + + + +```python +class Solution: + def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: + rides.sort(key=lambda x: x[1]) + f = [0] * (len(rides) + 1) + for i, (st, ed, tip) in enumerate(rides, 1): + j = bisect_left(rides, st + 1, hi=i, key=lambda x: x[1]) + f[i] = max(f[i - 1], f[j] + ed - st + tip) + return f[-1] +``` + +```java +class Solution { + public long maxTaxiEarnings(int n, int[][] rides) { + Arrays.sort(rides, (a, b) -> a[1] - b[1]); + int m = rides.length; + long[] f = new long[m + 1]; + for (int i = 1; i <= m; ++i) { + int[] r = rides[i - 1]; + int st = r[0], ed = r[1], tip = r[2]; + int j = search(rides, st + 1, i); + f[i] = Math.max(f[i - 1], f[j] + ed - st + tip); + } + return f[m]; + } + + private int search(int[][] nums, int x, int r) { + int l = 0; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid][1] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + } +} +``` + +```cpp +class Solution { +public: + long long maxTaxiEarnings(int n, vector>& rides) { + sort(rides.begin(), rides.end(), [](const vector& a, const vector& b) { return a[1] < b[1]; }); + int m = rides.size(); + vector f(m + 1); + for (int i = 1; i <= m; ++i) { + auto& r = rides[i - 1]; + int st = r[0], ed = r[1], tip = r[2]; + auto it = lower_bound(rides.begin(), rides.begin() + i, st + 1, [](auto& a, int val) { return a[1] < val; }); + int j = distance(rides.begin(), it); + f[i] = max(f[i - 1], f[j] + ed - st + tip); + } + return f.back(); + } +}; +``` + +```go +func maxTaxiEarnings(n int, rides [][]int) int64 { + sort.Slice(rides, func(i, j int) bool { return rides[i][1] < rides[j][1] }) + m := len(rides) + f := make([]int64, m+1) + for i := 1; i <= m; i++ { + r := rides[i-1] + st, ed, tip := r[0], r[1], r[2] + j := sort.Search(m, func(j int) bool { return rides[j][1] >= st+1 }) + f[i] = max(f[i-1], f[j]+int64(ed-st+tip)) + } + return f[m] +} +``` + ```ts function maxTaxiEarnings(n: number, rides: number[][]): number { rides.sort((a, b) => a[1] - b[1]); @@ -334,10 +328,6 @@ function maxTaxiEarnings(n: number, rides: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README.md b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README.md index 15a9add2c4227..02610fc9854b1 100644 --- a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README.md +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:排序 + 去重 + 二分查找** +### 方法一:排序 + 去重 + 二分查找 我们先将数组排序,去重。 @@ -70,22 +68,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组长度。 -**方法二:排序 + 去重 + 双指针** - -与方法一类似,我们先将数组排序,去重。 - -然后遍历数组,枚举以当前元素 $nums[i]$ 作为连续数组的最小值,通过双指针找到第一个大于 $nums[i] + n - 1$ 的位置 $j$,那么 $j-i$ 就是当前元素作为最小值时,连续数组的长度,更新答案,即 $ans = \min(ans, n - (j - i))$。 - -最后返回 $ans$ 即可。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组长度。 - -### **Python3** - - - ```python class Solution: def minOperations(self, nums: List[int]) -> int: @@ -97,23 +81,6 @@ class Solution: return ans ``` -```python -class Solution: - def minOperations(self, nums: List[int]) -> int: - n = len(nums) - nums = sorted(set(nums)) - ans, j = n, 0 - for i, v in enumerate(nums): - while j < len(nums) and nums[j] - v <= n - 1: - j += 1 - ans = min(ans, n - (j - i)) - return ans -``` - -### **Java** - - - ```java class Solution { public int minOperations(int[] nums) { @@ -147,31 +114,6 @@ class Solution { } ``` -```java -class Solution { - public int minOperations(int[] nums) { - int n = nums.length; - Arrays.sort(nums); - int m = 1; - for (int i = 1; i < n; ++i) { - if (nums[i] != nums[i - 1]) { - nums[m++] = nums[i]; - } - } - int ans = n; - for (int i = 0, j = 0; i < m; ++i) { - while (j < m && nums[j] - nums[i] <= n - 1) { - ++j; - } - ans = Math.min(ans, n - (j - i)); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -189,27 +131,26 @@ public: }; ``` -```cpp -class Solution { -public: - int minOperations(vector& nums) { - sort(nums.begin(), nums.end()); - int m = unique(nums.begin(), nums.end()) - nums.begin(); - int n = nums.size(); - int ans = n; - for (int i = 0, j = 0; i < m; ++i) { - while (j < m && nums[j] - nums[i] <= n - 1) { - ++j; - } - ans = min(ans, n - (j - i)); - } - return ans; - } -}; +```go +func minOperations(nums []int) int { + sort.Ints(nums) + n := len(nums) + m := 1 + for i := 1; i < n; i++ { + if nums[i] != nums[i-1] { + nums[m] = nums[i] + m++ + } + } + ans := n + for i := 0; i < m; i++ { + j := sort.Search(m, func(k int) bool { return nums[k] > nums[i]+n-1 }) + ans = min(ans, n-(j-i)) + } + return ans +} ``` -### **Rust** - ```rust use std::collections::BTreeSet; @@ -237,28 +178,75 @@ impl Solution { } ``` -### **Go** + -```go -func minOperations(nums []int) int { - sort.Ints(nums) - n := len(nums) - m := 1 - for i := 1; i < n; i++ { - if nums[i] != nums[i-1] { - nums[m] = nums[i] - m++ - } - } - ans := n - for i := 0; i < m; i++ { - j := sort.Search(m, func(k int) bool { return nums[k] > nums[i]+n-1 }) - ans = min(ans, n-(j-i)) - } - return ans +### 方法二:排序 + 去重 + 双指针 + +与方法一类似,我们先将数组排序,去重。 + +然后遍历数组,枚举以当前元素 $nums[i]$ 作为连续数组的最小值,通过双指针找到第一个大于 $nums[i] + n - 1$ 的位置 $j$,那么 $j-i$ 就是当前元素作为最小值时,连续数组的长度,更新答案,即 $ans = \min(ans, n - (j - i))$。 + +最后返回 $ans$ 即可。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组长度。 + + + +```python +class Solution: + def minOperations(self, nums: List[int]) -> int: + n = len(nums) + nums = sorted(set(nums)) + ans, j = n, 0 + for i, v in enumerate(nums): + while j < len(nums) and nums[j] - v <= n - 1: + j += 1 + ans = min(ans, n - (j - i)) + return ans +``` + +```java +class Solution { + public int minOperations(int[] nums) { + int n = nums.length; + Arrays.sort(nums); + int m = 1; + for (int i = 1; i < n; ++i) { + if (nums[i] != nums[i - 1]) { + nums[m++] = nums[i]; + } + } + int ans = n; + for (int i = 0, j = 0; i < m; ++i) { + while (j < m && nums[j] - nums[i] <= n - 1) { + ++j; + } + ans = Math.min(ans, n - (j - i)); + } + return ans; + } } ``` +```cpp +class Solution { +public: + int minOperations(vector& nums) { + sort(nums.begin(), nums.end()); + int m = unique(nums.begin(), nums.end()) - nums.begin(); + int n = nums.size(); + int ans = n; + for (int i = 0, j = 0; i < m; ++i) { + while (j < m && nums[j] - nums[i] <= n - 1) { + ++j; + } + ans = min(ans, n - (j - i)); + } + return ans; + } +}; +``` + ```go func minOperations(nums []int) int { sort.Ints(nums) @@ -281,10 +269,6 @@ func minOperations(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README_EN.md b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README_EN.md index f8bb443093238..207e8beac7fd8 100644 --- a/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README_EN.md +++ b/solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/README_EN.md @@ -57,7 +57,7 @@ The resulting array is [1,2,3,4], which is continuous. ## Solutions -**Solution 1: Sorting + Deduplication + Binary Search** +### Solution 1: Sorting + Deduplication + Binary Search First, we sort the array and remove duplicates. @@ -67,20 +67,8 @@ Finally, we return $ans$. The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array. -**Solution 2: Sorting + Deduplication + Two Pointers** - -Similar to Solution 1, we first sort the array and remove duplicates. - -Then, we traverse the array, enumerating the current element $nums[i]$ as the minimum value of the consecutive array. We use two pointers to find the first position $j$ that is greater than $nums[i] + n - 1$. Then, $j-i$ is the length of the consecutive array when the current element is the minimum value. We update the answer, i.e., $ans = \min(ans, n - (j - i))$. - -Finally, we return $ans$. - -The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array. - -### **Python3** - ```python class Solution: def minOperations(self, nums: List[int]) -> int: @@ -92,21 +80,6 @@ class Solution: return ans ``` -```python -class Solution: - def minOperations(self, nums: List[int]) -> int: - n = len(nums) - nums = sorted(set(nums)) - ans, j = n, 0 - for i, v in enumerate(nums): - while j < len(nums) and nums[j] - v <= n - 1: - j += 1 - ans = min(ans, n - (j - i)) - return ans -``` - -### **Java** - ```java class Solution { public int minOperations(int[] nums) { @@ -140,31 +113,6 @@ class Solution { } ``` -```java -class Solution { - public int minOperations(int[] nums) { - int n = nums.length; - Arrays.sort(nums); - int m = 1; - for (int i = 1; i < n; ++i) { - if (nums[i] != nums[i - 1]) { - nums[m++] = nums[i]; - } - } - int ans = n; - for (int i = 0, j = 0; i < m; ++i) { - while (j < m && nums[j] - nums[i] <= n - 1) { - ++j; - } - ans = Math.min(ans, n - (j - i)); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -182,27 +130,26 @@ public: }; ``` -```cpp -class Solution { -public: - int minOperations(vector& nums) { - sort(nums.begin(), nums.end()); - int m = unique(nums.begin(), nums.end()) - nums.begin(); - int n = nums.size(); - int ans = n; - for (int i = 0, j = 0; i < m; ++i) { - while (j < m && nums[j] - nums[i] <= n - 1) { - ++j; - } - ans = min(ans, n - (j - i)); - } - return ans; - } -}; +```go +func minOperations(nums []int) int { + sort.Ints(nums) + n := len(nums) + m := 1 + for i := 1; i < n; i++ { + if nums[i] != nums[i-1] { + nums[m] = nums[i] + m++ + } + } + ans := n + for i := 0; i < m; i++ { + j := sort.Search(m, func(k int) bool { return nums[k] > nums[i]+n-1 }) + ans = min(ans, n-(j-i)) + } + return ans +} ``` -### **Rust** - ```rust use std::collections::BTreeSet; @@ -230,28 +177,75 @@ impl Solution { } ``` -### **Go** + -```go -func minOperations(nums []int) int { - sort.Ints(nums) - n := len(nums) - m := 1 - for i := 1; i < n; i++ { - if nums[i] != nums[i-1] { - nums[m] = nums[i] - m++ - } - } - ans := n - for i := 0; i < m; i++ { - j := sort.Search(m, func(k int) bool { return nums[k] > nums[i]+n-1 }) - ans = min(ans, n-(j-i)) - } - return ans +### Solution 2: Sorting + Deduplication + Two Pointers + +Similar to Solution 1, we first sort the array and remove duplicates. + +Then, we traverse the array, enumerating the current element $nums[i]$ as the minimum value of the consecutive array. We use two pointers to find the first position $j$ that is greater than $nums[i] + n - 1$. Then, $j-i$ is the length of the consecutive array when the current element is the minimum value. We update the answer, i.e., $ans = \min(ans, n - (j - i))$. + +Finally, we return $ans$. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array. + + + +```python +class Solution: + def minOperations(self, nums: List[int]) -> int: + n = len(nums) + nums = sorted(set(nums)) + ans, j = n, 0 + for i, v in enumerate(nums): + while j < len(nums) and nums[j] - v <= n - 1: + j += 1 + ans = min(ans, n - (j - i)) + return ans +``` + +```java +class Solution { + public int minOperations(int[] nums) { + int n = nums.length; + Arrays.sort(nums); + int m = 1; + for (int i = 1; i < n; ++i) { + if (nums[i] != nums[i - 1]) { + nums[m++] = nums[i]; + } + } + int ans = n; + for (int i = 0, j = 0; i < m; ++i) { + while (j < m && nums[j] - nums[i] <= n - 1) { + ++j; + } + ans = Math.min(ans, n - (j - i)); + } + return ans; + } } ``` +```cpp +class Solution { +public: + int minOperations(vector& nums) { + sort(nums.begin(), nums.end()); + int m = unique(nums.begin(), nums.end()) - nums.begin(); + int n = nums.size(); + int ans = n; + for (int i = 0, j = 0; i < m; ++i) { + while (j < m && nums[j] - nums[i] <= n - 1) { + ++j; + } + ans = min(ans, n - (j - i)); + } + return ans; + } +}; +``` + ```go func minOperations(nums []int) int { sort.Ints(nums) @@ -274,10 +268,6 @@ func minOperations(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2010.The Number of Seniors and Juniors to Join the Company II/README.md b/solution/2000-2099/2010.The Number of Seniors and Juniors to Join the Company II/README.md index fdb5a83e31a63..3fa27e830a398 100644 --- a/solution/2000-2099/2010.The Number of Seniors and Juniors to Join the Company II/README.md +++ b/solution/2000-2099/2010.The Number of Seniors and Juniors to Join the Company II/README.md @@ -95,9 +95,7 @@ Candidates table: ## 解法 - - -**方法一:窗口函数** +### 方法一:窗口函数 相似题目: @@ -105,10 +103,6 @@ Candidates table: -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -144,3 +138,5 @@ WHERE cur <= 70000; ``` + + diff --git a/solution/2000-2099/2010.The Number of Seniors and Juniors to Join the Company II/README_EN.md b/solution/2000-2099/2010.The Number of Seniors and Juniors to Join the Company II/README_EN.md index 1ac6b0da7cc83..805240ceca2b4 100644 --- a/solution/2000-2099/2010.The Number of Seniors and Juniors to Join the Company II/README_EN.md +++ b/solution/2000-2099/2010.The Number of Seniors and Juniors to Join the Company II/README_EN.md @@ -95,9 +95,9 @@ We can hire all three juniors with the remaining budget. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -134,3 +134,5 @@ WHERE cur <= 70000; ``` + + diff --git a/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README.md b/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README.md index 7597cafb11fa8..437715b0533c3 100644 --- a/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README.md +++ b/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README.md @@ -67,9 +67,7 @@ X--:X 减 1 ,X = 1 - 1 = 0 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 遍历数组 `operations`,对于每个操作 $operations[i]$,如果包含 `'+'`,那么答案加 $1$,否则答案减 $1$。 @@ -77,20 +75,12 @@ X--:X 减 1 ,X = 1 - 1 = 0 -### **Python3** - - - ```python class Solution: def finalValueAfterOperations(self, operations: List[str]) -> int: return sum(1 if s[1] == '+' else -1 for s in operations) ``` -### **Java** - - - ```java class Solution { public int finalValueAfterOperations(String[] operations) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func finalValueAfterOperations(operations []string) (ans int) { for _, s := range operations { @@ -131,24 +117,6 @@ func finalValueAfterOperations(operations []string) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {string[]} operations - * @return {number} - */ -var finalValueAfterOperations = function (operations) { - let ans = 0; - for (const s of operations) { - ans += s[1] === '+' ? 1 : -1; - } - return ans; -}; -``` - -### **TypeScript** - ```ts function finalValueAfterOperations(operations: string[]): number { let ans = 0; @@ -159,14 +127,6 @@ function finalValueAfterOperations(operations: string[]): number { } ``` -```ts -function finalValueAfterOperations(operations: string[]): number { - return operations.reduce((r, v) => r + (v[1] === '+' ? 1 : -1), 0); -} -``` - -### **Rust** - ```rust impl Solution { pub fn final_value_after_operations(operations: Vec) -> i32 { @@ -179,7 +139,19 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {string[]} operations + * @return {number} + */ +var finalValueAfterOperations = function (operations) { + let ans = 0; + for (const s of operations) { + ans += s[1] === '+' ? 1 : -1; + } + return ans; +}; +``` ```c int finalValueAfterOperations(char** operations, int operationsSize) { @@ -191,10 +163,18 @@ int finalValueAfterOperations(char** operations, int operationsSize) { } ``` -### **...** + -``` +### 方法二 + + +```ts +function finalValueAfterOperations(operations: string[]): number { + return operations.reduce((r, v) => r + (v[1] === '+' ? 1 : -1), 0); +} ``` + + diff --git a/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README_EN.md b/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README_EN.md index 24db735dcb32e..534633eb30750 100644 --- a/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README_EN.md +++ b/solution/2000-2099/2011.Final Value of Variable After Performing Operations/README_EN.md @@ -63,7 +63,7 @@ X--: X is decremented by 1, X = 1 - 1 = 0. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation Traverse the array `operations`. For each operation $operations[i]$, if it contains `'+'`, then the answer increases by $1$, otherwise the answer decreases by $1$. @@ -71,16 +71,12 @@ The time complexity is $O(n)$, where $n$ is the length of the array `operations` -### **Python3** - ```python class Solution: def finalValueAfterOperations(self, operations: List[str]) -> int: return sum(1 if s[1] == '+' else -1 for s in operations) ``` -### **Java** - ```java class Solution { public int finalValueAfterOperations(String[] operations) { @@ -93,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +100,6 @@ public: }; ``` -### **Go** - ```go func finalValueAfterOperations(operations []string) (ans int) { for _, s := range operations { @@ -121,24 +113,6 @@ func finalValueAfterOperations(operations []string) (ans int) { } ``` -### **JavaScript** - -```js -/** - * @param {string[]} operations - * @return {number} - */ -var finalValueAfterOperations = function (operations) { - let ans = 0; - for (const s of operations) { - ans += s[1] === '+' ? 1 : -1; - } - return ans; -}; -``` - -### **TypeScript** - ```ts function finalValueAfterOperations(operations: string[]): number { let ans = 0; @@ -149,14 +123,6 @@ function finalValueAfterOperations(operations: string[]): number { } ``` -```ts -function finalValueAfterOperations(operations: string[]): number { - return operations.reduce((r, v) => r + (v[1] === '+' ? 1 : -1), 0); -} -``` - -### **Rust** - ```rust impl Solution { pub fn final_value_after_operations(operations: Vec) -> i32 { @@ -169,7 +135,19 @@ impl Solution { } ``` -### **C** +```js +/** + * @param {string[]} operations + * @return {number} + */ +var finalValueAfterOperations = function (operations) { + let ans = 0; + for (const s of operations) { + ans += s[1] === '+' ? 1 : -1; + } + return ans; +}; +``` ```c int finalValueAfterOperations(char** operations, int operationsSize) { @@ -181,10 +159,18 @@ int finalValueAfterOperations(char** operations, int operationsSize) { } ``` -### **...** + -``` +### Solution 2 + + +```ts +function finalValueAfterOperations(operations: string[]): number { + return operations.reduce((r, v) => r + (v[1] === '+' ? 1 : -1), 0); +} ``` + + diff --git a/solution/2000-2099/2012.Sum of Beauty in the Array/README.md b/solution/2000-2099/2012.Sum of Beauty in the Array/README.md index dca2030754e2f..ead91af5e3b1a 100644 --- a/solution/2000-2099/2012.Sum of Beauty in the Array/README.md +++ b/solution/2000-2099/2012.Sum of Beauty in the Array/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:预处理右侧最小值 + 遍历维护左侧最大值** +### 方法一:预处理右侧最小值 + 遍历维护左侧最大值 我们可以预处理出右侧最小值数组 $right$,其中 $right[i]$ 表示 $nums[i..n-1]$ 中的最小值。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def sumOfBeauties(self, nums: List[int]) -> int: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int sumOfBeauties(int[] nums) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func sumOfBeauties(nums []int) (ans int) { n := len(nums) @@ -169,8 +155,6 @@ func sumOfBeauties(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumOfBeauties(nums: number[]): number { const n = nums.length; @@ -192,10 +176,6 @@ function sumOfBeauties(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2012.Sum of Beauty in the Array/README_EN.md b/solution/2000-2099/2012.Sum of Beauty in the Array/README_EN.md index 53d91ccb0eb9a..fb2436f821aa9 100644 --- a/solution/2000-2099/2012.Sum of Beauty in the Array/README_EN.md +++ b/solution/2000-2099/2012.Sum of Beauty in the Array/README_EN.md @@ -53,7 +53,7 @@ ## Solutions -**Solution 1: Preprocessing Right Minimum + Traversing to Maintain Left Maximum** +### Solution 1: Preprocessing Right Minimum + Traversing to Maintain Left Maximum We can preprocess the right minimum array $right$, where $right[i]$ represents the minimum value in $nums[i..n-1]$. @@ -65,8 +65,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def sumOfBeauties(self, nums: List[int]) -> int: @@ -86,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int sumOfBeauties(int[] nums) { @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +133,6 @@ public: }; ``` -### **Go** - ```go func sumOfBeauties(nums []int) (ans int) { n := len(nums) @@ -162,8 +154,6 @@ func sumOfBeauties(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumOfBeauties(nums: number[]): number { const n = nums.length; @@ -185,10 +175,6 @@ function sumOfBeauties(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2013.Detect Squares/README.md b/solution/2000-2099/2013.Detect Squares/README.md index 86256f871542d..0aec416dd881d 100644 --- a/solution/2000-2099/2013.Detect Squares/README.md +++ b/solution/2000-2099/2013.Detect Squares/README.md @@ -61,9 +61,7 @@ detectSquares.count([11, 10]); // 返回 2 。你可以选择: ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以用一个哈希表 $cnt$ 维护所有点的信息,其中 $cnt[x][y]$ 表示点 $(x, y)$ 的个数。 @@ -75,10 +73,6 @@ detectSquares.count([11, 10]); // 返回 2 。你可以选择: -### **Python3** - - - ```python class DetectSquares: def __init__(self): @@ -107,10 +101,6 @@ class DetectSquares: # param_2 = obj.count(point) ``` -### **Java** - - - ```java class DetectSquares { private Map> cnt = new HashMap<>(); @@ -153,8 +143,6 @@ class DetectSquares { */ ``` -### **C++** - ```cpp class DetectSquares { public: @@ -195,8 +183,6 @@ private: */ ``` -### **Go** - ```go type DetectSquares struct { cnt map[int]map[int]int @@ -236,10 +222,6 @@ func (this *DetectSquares) Count(point []int) (ans int) { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2013.Detect Squares/README_EN.md b/solution/2000-2099/2013.Detect Squares/README_EN.md index 6b5f329bbfeed..e574b7f19392b 100644 --- a/solution/2000-2099/2013.Detect Squares/README_EN.md +++ b/solution/2000-2099/2013.Detect Squares/README_EN.md @@ -57,7 +57,7 @@ detectSquares.count([11, 10]); // return 2. You can choose: ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We can use a hash table $cnt$ to maintain all the information of the points, where $cnt[x][y]$ represents the count of point $(x, y)$. @@ -69,8 +69,6 @@ In terms of time complexity, the time complexity of calling the $add(x, y)$ meth -### **Python3** - ```python class DetectSquares: def __init__(self): @@ -99,8 +97,6 @@ class DetectSquares: # param_2 = obj.count(point) ``` -### **Java** - ```java class DetectSquares { private Map> cnt = new HashMap<>(); @@ -143,8 +139,6 @@ class DetectSquares { */ ``` -### **C++** - ```cpp class DetectSquares { public: @@ -185,8 +179,6 @@ private: */ ``` -### **Go** - ```go type DetectSquares struct { cnt map[int]map[int]int @@ -226,10 +218,6 @@ func (this *DetectSquares) Count(point []int) (ans int) { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README.md b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README.md index 84abe5b60a67d..44973d4652dea 100644 --- a/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README.md +++ b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README.md @@ -60,30 +60,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README_EN.md b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README_EN.md index 0a386ab9692b2..d392f30cd862c 100644 --- a/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README_EN.md +++ b/solution/2000-2099/2014.Longest Subsequence Repeated k Times/README_EN.md @@ -54,24 +54,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README.md b/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README.md index 7c0888a757553..1f207a0196f21 100644 --- a/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README.md +++ b/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README.md @@ -75,9 +75,7 @@ ## 解法 - - -**方法一:差分有序哈希表** +### 方法一:差分有序哈希表 我们利用差分思想,使用有序哈希表 `height` 记录每个位置的高度变化,`cnt` 记录建筑物的数量变化。对有序哈希表求前缀和,即可得到每个位置的高度和建筑物数量。 @@ -87,10 +85,6 @@ -### **Python3** - - - ```python class Solution: def averageHeightOfBuildings(self, buildings: List[List[int]]) -> List[List[int]]: @@ -116,10 +110,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] averageHeightOfBuildings(int[][] buildings) { @@ -157,8 +147,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -189,8 +177,6 @@ public: }; ``` -### **Go** - ```go func averageHeightOfBuildings(buildings [][]int) [][]int { height := make(map[int]int) @@ -226,10 +212,6 @@ func averageHeightOfBuildings(buildings [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README_EN.md b/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README_EN.md index 04440f70dbfc1..98f2494642974 100644 --- a/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README_EN.md +++ b/solution/2000-2099/2015.Average Height of Buildings in Each Segment/README_EN.md @@ -74,7 +74,7 @@ We cannot group the segments together because an empty space with no buildings s ## Solutions -**Solution 1: Differential Ordered Hash Table** +### Solution 1: Differential Ordered Hash Table We use the differential idea and an ordered hash table `height` to record the height change at each position, and `cnt` to record the change in the number of buildings. By calculating the prefix sum of the ordered hash table, we can get the height and the number of buildings at each position. @@ -84,8 +84,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def averageHeightOfBuildings(self, buildings: List[List[int]]) -> List[List[int]]: @@ -111,8 +109,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] averageHeightOfBuildings(int[][] buildings) { @@ -150,8 +146,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +176,6 @@ public: }; ``` -### **Go** - ```go func averageHeightOfBuildings(buildings [][]int) [][]int { height := make(map[int]int) @@ -219,10 +211,6 @@ func averageHeightOfBuildings(buildings [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README.md b/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README.md index f24db30adee2a..23bb430b994d5 100644 --- a/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README.md +++ b/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:维护前缀最小值** +### 方法一:维护前缀最小值 我们用变量 $mi$ 表示当前遍历到的元素中的最小值,用变量 $ans$ 表示最大差值,初始时 $mi$ 为 $+\infty$,而 $ans$ 为 $-1$。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def maximumDifference(self, nums: List[int]) -> int: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumDifference(int[] nums) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func maximumDifference(nums []int) int { mi := 1 << 30 @@ -138,8 +124,6 @@ func maximumDifference(nums []int) int { } ``` -### **TypeScript** - ```ts function maximumDifference(nums: number[]): number { const n = nums.length; @@ -153,8 +137,6 @@ function maximumDifference(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn maximum_difference(nums: Vec) -> i32 { @@ -172,8 +154,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -193,10 +173,6 @@ var maximumDifference = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README_EN.md b/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README_EN.md index 6218fd05f2301..93551c731c2cf 100644 --- a/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README_EN.md +++ b/solution/2000-2099/2016.Maximum Difference Between Increasing Elements/README_EN.md @@ -48,7 +48,7 @@ The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = ## Solutions -**Solution 1: Maintaining Prefix Minimum** +### Solution 1: Maintaining Prefix Minimum We use the variable $mi$ to represent the minimum value of the elements we have traversed so far, and the variable $ans$ to represent the maximum difference. Initially, $mi$ is set to $+\infty$, and $ans$ is set to $-1$. @@ -60,8 +60,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def maximumDifference(self, nums: List[int]) -> int: @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumDifference(int[] nums) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +108,6 @@ public: }; ``` -### **Go** - ```go func maximumDifference(nums []int) int { mi := 1 << 30 @@ -131,8 +123,6 @@ func maximumDifference(nums []int) int { } ``` -### **TypeScript** - ```ts function maximumDifference(nums: number[]): number { const n = nums.length; @@ -146,8 +136,6 @@ function maximumDifference(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn maximum_difference(nums: Vec) -> i32 { @@ -165,8 +153,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -186,10 +172,6 @@ var maximumDifference = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2017.Grid Game/README.md b/solution/2000-2099/2017.Grid Game/README.md index 91cba95d0d74f..a96714c1d341d 100644 --- a/solution/2000-2099/2017.Grid Game/README.md +++ b/solution/2000-2099/2017.Grid Game/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:前缀和** +### 方法一:前缀和 我们注意到,如果确定了第一个机器人拐头向下的位置 $j$,那么第二个机器人的最优路径也就确定了,第二个机器人的最优路径就是第一行从 $j+1$ 到 $n-1$ 的前缀和,或者第二行从 $0$ 到 $j-1$ 的前缀和,取两者的最大值。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def gridGame(self, grid: List[List[int]]) -> int: @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long gridGame(int[][] grid) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func gridGame(grid [][]int) int64 { ans := math.MaxInt64 @@ -156,8 +142,6 @@ func gridGame(grid [][]int) int64 { } ``` -### **TypeScript** - ```ts function gridGame(grid: number[][]): number { let ans = Number.MAX_SAFE_INTEGER; @@ -172,10 +156,6 @@ function gridGame(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2017.Grid Game/README_EN.md b/solution/2000-2099/2017.Grid Game/README_EN.md index 691e58097240d..493bd694e63a1 100644 --- a/solution/2000-2099/2017.Grid Game/README_EN.md +++ b/solution/2000-2099/2017.Grid Game/README_EN.md @@ -55,7 +55,7 @@ The second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points. ## Solutions -**Solution 1: Prefix Sum** +### Solution 1: Prefix Sum We notice that if we determine the position $j$ where the first robot turns down, then the optimal path of the second robot is also determined. The optimal path of the second robot is the prefix sum of the first row from $j+1$ to $n-1$, or the prefix sum of the second row from $0$ to $j-1$, taking the maximum of the two. @@ -69,8 +69,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is -### **Python3** - ```python class Solution: def gridGame(self, grid: List[List[int]]) -> int: @@ -83,8 +81,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long gridGame(int[][] grid) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -126,8 +120,6 @@ public: }; ``` -### **Go** - ```go func gridGame(grid [][]int) int64 { ans := math.MaxInt64 @@ -144,8 +136,6 @@ func gridGame(grid [][]int) int64 { } ``` -### **TypeScript** - ```ts function gridGame(grid: number[][]): number { let ans = Number.MAX_SAFE_INTEGER; @@ -160,10 +150,6 @@ function gridGame(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2018.Check if Word Can Be Placed In Crossword/README.md b/solution/2000-2099/2018.Check if Word Can Be Placed In Crossword/README.md index bb65d2d0f72da..a62bc4fa0d561 100644 --- a/solution/2000-2099/2018.Check if Word Can Be Placed In Crossword/README.md +++ b/solution/2000-2099/2018.Check if Word Can Be Placed In Crossword/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举矩阵的每个位置 $(i, j)$,判断是否能以该位置为起点,从左到右或从右到左放置单词 `word`,或者从上到下或从下到上放置单词 `word`。 @@ -90,10 +88,6 @@ -### **Python3** - - - ```python class Solution: def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool: @@ -130,10 +124,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { private int m; @@ -180,8 +170,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -218,8 +206,6 @@ public: }; ``` -### **Go** - ```go func placeWordInCrossword(board [][]byte, word string) bool { m, n := len(board), len(board[0]) @@ -252,10 +238,6 @@ func placeWordInCrossword(board [][]byte, word string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2018.Check if Word Can Be Placed In Crossword/README_EN.md b/solution/2000-2099/2018.Check if Word Can Be Placed In Crossword/README_EN.md index 5f3894a07b4c4..e33cf90a4887f 100644 --- a/solution/2000-2099/2018.Check if Word Can Be Placed In Crossword/README_EN.md +++ b/solution/2000-2099/2018.Check if Word Can Be Placed In Crossword/README_EN.md @@ -55,7 +55,7 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We can enumerate each position $(i, j)$ in the matrix, and judge whether we can place the word `word` from left to right or from right to left, or from top to bottom or from bottom to top, starting from this position. @@ -78,8 +78,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(1)$. Here -### **Python3** - ```python class Solution: def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool: @@ -116,8 +114,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { private int m; @@ -164,8 +160,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -202,8 +196,6 @@ public: }; ``` -### **Go** - ```go func placeWordInCrossword(board [][]byte, word string) bool { m, n := len(board), len(board[0]) @@ -236,10 +228,6 @@ func placeWordInCrossword(board [][]byte, word string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2019.The Score of Students Solving Math Expression/README.md b/solution/2000-2099/2019.The Score of Students Solving Math Expression/README.md index 6b80d34a5a86c..7255ded0087cf 100644 --- a/solution/2000-2099/2019.The Score of Students Solving Math Expression/README.md +++ b/solution/2000-2099/2019.The Score of Students Solving Math Expression/README.md @@ -72,9 +72,7 @@ ## 解法 - - -**方法一:动态规划(区间 DP)** +### 方法一:动态规划(区间 DP) 我们先设计一个函数 $cal(s)$,用于计算一个合法的只含有个位数数字的数学表达式的结果。那么正确答案就是 $x = cal(s)$。 @@ -101,10 +99,6 @@ $$ -### **Python3** - - - ```python class Solution: def scoreOfStudents(self, s: str, answers: List[int]) -> int: @@ -142,10 +136,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int scoreOfStudents(String s, int[] answers) { @@ -206,8 +196,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -266,8 +254,6 @@ public: }; ``` -### **Go** - ```go func scoreOfStudents(s string, answers []int) int { n := len(s) @@ -326,8 +312,6 @@ func cal(s string) int { } ``` -### **TypeScript** - ```ts function scoreOfStudents(s: string, answers: number[]): number { const n = s.length; @@ -388,10 +372,6 @@ function scoreOfStudents(s: string, answers: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2019.The Score of Students Solving Math Expression/README_EN.md b/solution/2000-2099/2019.The Score of Students Solving Math Expression/README_EN.md index 00f118e8c02d8..b750c5469883e 100644 --- a/solution/2000-2099/2019.The Score of Students Solving Math Expression/README_EN.md +++ b/solution/2000-2099/2019.The Score of Students Solving Math Expression/README_EN.md @@ -69,7 +69,7 @@ The points for the students are: [0,0,5,0,0,5]. The sum of the points is 10. ## Solutions -**Solution 1: Dynamic Programming (Interval DP)** +### Solution 1: Dynamic Programming (Interval DP) First, we design a function $cal(s)$ to calculate the result of a valid mathematical expression that only contains single-digit numbers. The correct answer is $x = cal(s)$. @@ -96,8 +96,6 @@ The time complexity is $O(n^3 \times M^2)$, and the space complexity is $O(n^2 \ -### **Python3** - ```python class Solution: def scoreOfStudents(self, s: str, answers: List[int]) -> int: @@ -135,8 +133,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int scoreOfStudents(String s, int[] answers) { @@ -197,8 +193,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -257,8 +251,6 @@ public: }; ``` -### **Go** - ```go func scoreOfStudents(s string, answers []int) int { n := len(s) @@ -317,8 +309,6 @@ func cal(s string) int { } ``` -### **TypeScript** - ```ts function scoreOfStudents(s: string, answers: number[]): number { const n = s.length; @@ -379,10 +369,6 @@ function scoreOfStudents(s: string, answers: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2020.Number of Accounts That Did Not Stream/README.md b/solution/2000-2099/2020.Number of Accounts That Did Not Stream/README.md index 22a968d5fefe2..2c60fbd0f1769 100644 --- a/solution/2000-2099/2020.Number of Accounts That Did Not Stream/README.md +++ b/solution/2000-2099/2020.Number of Accounts That Did Not Stream/README.md @@ -80,14 +80,10 @@ Streams table: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT COUNT(sub.account_id) AS accounts_count @@ -101,3 +97,5 @@ WHERE ``` + + diff --git a/solution/2000-2099/2020.Number of Accounts That Did Not Stream/README_EN.md b/solution/2000-2099/2020.Number of Accounts That Did Not Stream/README_EN.md index b10b11491611e..73c722df77932 100644 --- a/solution/2000-2099/2020.Number of Accounts That Did Not Stream/README_EN.md +++ b/solution/2000-2099/2020.Number of Accounts That Did Not Stream/README_EN.md @@ -81,9 +81,9 @@ User 11 did not subscribe in 2021. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -98,3 +98,5 @@ WHERE ``` + + diff --git a/solution/2000-2099/2021.Brightest Position on Street/README.md b/solution/2000-2099/2021.Brightest Position on Street/README.md index 3eab4a53078f2..5be29dad11d58 100644 --- a/solution/2000-2099/2021.Brightest Position on Street/README.md +++ b/solution/2000-2099/2021.Brightest Position on Street/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:差分数组 + 哈希表 + 排序** +### 方法一:差分数组 + 哈希表 + 排序 我们可以将每个路灯照亮的范围看作是一个区间,区间左端点 $l = position_i - range_i$,区间右端点 $r = position_i + range_i$。我们可以利用差分数组的思想,对于每个区间 $[l, r]$,将位置 $l$ 的值加 $1$,将位置 $r + 1$ 的值减 $1$,用哈希表维护每个位置的变化值。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def brightestPosition(self, lights: List[List[int]]) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int brightestPosition(int[][] lights) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +127,6 @@ public: }; ``` -### **Go** - ```go func brightestPosition(lights [][]int) (ans int) { d := map[int]int{} @@ -166,8 +152,6 @@ func brightestPosition(lights [][]int) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {number[][]} lights @@ -200,10 +184,6 @@ var brightestPosition = function (lights) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2021.Brightest Position on Street/README_EN.md b/solution/2000-2099/2021.Brightest Position on Street/README_EN.md index d9f8294388bc9..0fbd6612f1db5 100644 --- a/solution/2000-2099/2021.Brightest Position on Street/README_EN.md +++ b/solution/2000-2099/2021.Brightest Position on Street/README_EN.md @@ -64,7 +64,7 @@ Out of all these positions, -1 is the smallest, so return it. ## Solutions -**Solution 1: Difference Array + Hash Table + Sorting** +### Solution 1: Difference Array + Hash Table + Sorting We can consider the range illuminated by each street light as an interval, with the left endpoint $l = position_i - range_i$ and the right endpoint $r = position_i + range_i$. We can use the idea of a difference array. For each interval $[l, r]$, we add $1$ to the value at position $l$ and subtract $1$ from the value at position $r + 1$. We use a hash table to maintain the change value at each position. @@ -76,8 +76,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def brightestPosition(self, lights: List[List[int]]) -> int: @@ -95,8 +93,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int brightestPosition(int[][] lights) { @@ -120,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +139,6 @@ public: }; ``` -### **Go** - ```go func brightestPosition(lights [][]int) (ans int) { d := map[int]int{} @@ -172,8 +164,6 @@ func brightestPosition(lights [][]int) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {number[][]} lights @@ -206,10 +196,6 @@ var brightestPosition = function (lights) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2022.Convert 1D Array Into 2D Array/README.md b/solution/2000-2099/2022.Convert 1D Array Into 2D Array/README.md index df0eb72eb7261..532c6c285bb31 100644 --- a/solution/2000-2099/2022.Convert 1D Array Into 2D Array/README.md +++ b/solution/2000-2099/2022.Convert 1D Array Into 2D Array/README.md @@ -63,9 +63,7 @@ original 中只有 1 个元素。 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 根据题目描述,我们知道,要想构造出一个 $m$ 行 $n$ 列的二维数组,需要满足 $m \times n$ 等于原数组的长度。如果不满足,直接返回空数组即可。 @@ -75,10 +73,6 @@ original 中只有 1 个元素。 -### **Python3** - - - ```python class Solution: def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]: @@ -87,10 +81,6 @@ class Solution: return [original[i : i + n] for i in range(0, m * n, n)] ``` -### **Java** - - - ```java class Solution { public int[][] construct2DArray(int[] original, int m, int n) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func construct2DArray(original []int, m int, n int) (ans [][]int) { if m*n != len(original) { @@ -142,7 +128,18 @@ func construct2DArray(original []int, m int, n int) (ans [][]int) { } ``` -### **JavaScript** +```ts +function construct2DArray(original: number[], m: number, n: number): number[][] { + if (m * n != original.length) { + return []; + } + const ans: number[][] = []; + for (let i = 0; i < m * n; i += n) { + ans.push(original.slice(i, i + n)); + } + return ans; +} +``` ```js /** @@ -163,25 +160,6 @@ var construct2DArray = function (original, m, n) { }; ``` -### **TypeScript** - -```ts -function construct2DArray(original: number[], m: number, n: number): number[][] { - if (m * n != original.length) { - return []; - } - const ans: number[][] = []; - for (let i = 0; i < m * n; i += n) { - ans.push(original.slice(i, i + n)); - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2022.Convert 1D Array Into 2D Array/README_EN.md b/solution/2000-2099/2022.Convert 1D Array Into 2D Array/README_EN.md index 8a7099bf4ec23..66edb154665d0 100644 --- a/solution/2000-2099/2022.Convert 1D Array Into 2D Array/README_EN.md +++ b/solution/2000-2099/2022.Convert 1D Array Into 2D Array/README_EN.md @@ -50,7 +50,7 @@ It is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D arra ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation According to the problem description, we know that to construct an $m$-row and $n$-column two-dimensional array, it needs to satisfy that $m \times n$ equals the length of the original array. If it does not satisfy, return an empty array directly. @@ -60,8 +60,6 @@ The time complexity is $O(m \times n)$, where $m$ and $n$ are the number of rows -### **Python3** - ```python class Solution: def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]: @@ -70,8 +68,6 @@ class Solution: return [original[i : i + n] for i in range(0, m * n, n)] ``` -### **Java** - ```java class Solution { public int[][] construct2DArray(int[] original, int m, int n) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +103,6 @@ public: }; ``` -### **Go** - ```go func construct2DArray(original []int, m int, n int) (ans [][]int) { if m*n != len(original) { @@ -123,7 +115,18 @@ func construct2DArray(original []int, m int, n int) (ans [][]int) { } ``` -### **JavaScript** +```ts +function construct2DArray(original: number[], m: number, n: number): number[][] { + if (m * n != original.length) { + return []; + } + const ans: number[][] = []; + for (let i = 0; i < m * n; i += n) { + ans.push(original.slice(i, i + n)); + } + return ans; +} +``` ```js /** @@ -144,25 +147,6 @@ var construct2DArray = function (original, m, n) { }; ``` -### **TypeScript** - -```ts -function construct2DArray(original: number[], m: number, n: number): number[][] { - if (m * n != original.length) { - return []; - } - const ans: number[][] = []; - for (let i = 0; i < m * n; i += n) { - ans.push(original.slice(i, i + n)); - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README.md b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README.md index df0da51095ff8..c516d445eece8 100644 --- a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README.md +++ b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README.md @@ -57,26 +57,14 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 遍历数组 `nums`,对于每个 $i$,枚举所有 $j$,如果 $i \neq j$ 且 $nums[i] + nums[j] = target$,则答案加一。 时间复杂度 $O(n^2 \times m)$,其中 $n$ 和 $m$ 分别为数组 `nums` 和字符串 `target` 的长度。空间复杂度 $O(1)$。 -**方法二:哈希表** - -我们可以用哈希表统计数组 `nums` 中每个字符串出现的次数,然后遍历字符串 `target` 的所有前缀和后缀,如果前缀和后缀都在哈希表中,则答案加上它们出现的次数的乘积。 - -时间复杂度 $O(n + m^2)$,空间复杂度 $O(n)$。其中 $n$ 和 $m$ 分别为数组 `nums` 和字符串 `target` 的长度。 - -### **Python3** - - - ```python class Solution: def numOfPairs(self, nums: List[str], target: str) -> int: @@ -86,24 +74,6 @@ class Solution: ) ``` -```python -class Solution: - def numOfPairs(self, nums: List[str], target: str) -> int: - cnt = Counter(nums) - ans = 0 - for i in range(1, len(target)): - a, b = target[:i], target[i:] - if a != b: - ans += cnt[a] * cnt[b] - else: - ans += cnt[a] * (cnt[a] - 1) - return ans -``` - -### **Java** - - - ```java class Solution { public int numOfPairs(String[] nums, String target) { @@ -121,6 +91,59 @@ class Solution { } ``` +```cpp +class Solution { +public: + int numOfPairs(vector& nums, string target) { + int n = nums.size(); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (i != j && nums[i] + nums[j] == target) ++ans; + } + } + return ans; + } +}; +``` + +```go +func numOfPairs(nums []string, target string) (ans int) { + for i, a := range nums { + for j, b := range nums { + if i != j && a+b == target { + ans++ + } + } + } + return ans +} +``` + + + +### 方法二:哈希表 + +我们可以用哈希表统计数组 `nums` 中每个字符串出现的次数,然后遍历字符串 `target` 的所有前缀和后缀,如果前缀和后缀都在哈希表中,则答案加上它们出现的次数的乘积。 + +时间复杂度 $O(n + m^2)$,空间复杂度 $O(n)$。其中 $n$ 和 $m$ 分别为数组 `nums` 和字符串 `target` 的长度。 + + + +```python +class Solution: + def numOfPairs(self, nums: List[str], target: str) -> int: + cnt = Counter(nums) + ans = 0 + for i in range(1, len(target)): + a, b = target[:i], target[i:] + if a != b: + ans += cnt[a] * cnt[b] + else: + ans += cnt[a] * (cnt[a] - 1) + return ans +``` + ```java class Solution { public int numOfPairs(String[] nums, String target) { @@ -145,24 +168,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numOfPairs(vector& nums, string target) { - int n = nums.size(); - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (i != j && nums[i] + nums[j] == target) ++ans; - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -185,21 +190,6 @@ public: }; ``` -### **Go** - -```go -func numOfPairs(nums []string, target string) (ans int) { - for i, a := range nums { - for j, b := range nums { - if i != j && a+b == target { - ans++ - } - } - } - return ans -} -``` - ```go func numOfPairs(nums []string, target string) (ans int) { cnt := map[string]int{} @@ -218,10 +208,6 @@ func numOfPairs(nums []string, target string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README_EN.md b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README_EN.md index 624be1a4f7a47..5492796b2fbd3 100644 --- a/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README_EN.md +++ b/solution/2000-2099/2023.Number of Pairs of Strings With Concatenation Equal to Target/README_EN.md @@ -56,22 +56,14 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration Traverse the array `nums`, for each $i$, enumerate all $j$, if $i \neq j$ and $nums[i] + nums[j] = target$, then increment the answer by one. The time complexity is $O(n^2 \times m)$, where $n$ and $m$ are the lengths of the array `nums` and the string `target`, respectively. The space complexity is $O(1)$. -**Solution 2: Hash Table** - -We can use a hash table to count the occurrence of each string in the array `nums`, then traverse all prefixes and suffixes of the string `target`. If both the prefix and suffix are in the hash table, then increment the answer by the product of their occurrences. - -The time complexity is $O(n + m^2)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the lengths of the array `nums` and the string `target`, respectively. - -### **Python3** - ```python class Solution: def numOfPairs(self, nums: List[str], target: str) -> int: @@ -81,22 +73,6 @@ class Solution: ) ``` -```python -class Solution: - def numOfPairs(self, nums: List[str], target: str) -> int: - cnt = Counter(nums) - ans = 0 - for i in range(1, len(target)): - a, b = target[:i], target[i:] - if a != b: - ans += cnt[a] * cnt[b] - else: - ans += cnt[a] * (cnt[a] - 1) - return ans -``` - -### **Java** - ```java class Solution { public int numOfPairs(String[] nums, String target) { @@ -114,6 +90,59 @@ class Solution { } ``` +```cpp +class Solution { +public: + int numOfPairs(vector& nums, string target) { + int n = nums.size(); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (i != j && nums[i] + nums[j] == target) ++ans; + } + } + return ans; + } +}; +``` + +```go +func numOfPairs(nums []string, target string) (ans int) { + for i, a := range nums { + for j, b := range nums { + if i != j && a+b == target { + ans++ + } + } + } + return ans +} +``` + + + +### Solution 2: Hash Table + +We can use a hash table to count the occurrence of each string in the array `nums`, then traverse all prefixes and suffixes of the string `target`. If both the prefix and suffix are in the hash table, then increment the answer by the product of their occurrences. + +The time complexity is $O(n + m^2)$, and the space complexity is $O(n)$. Here, $n$ and $m$ are the lengths of the array `nums` and the string `target`, respectively. + + + +```python +class Solution: + def numOfPairs(self, nums: List[str], target: str) -> int: + cnt = Counter(nums) + ans = 0 + for i in range(1, len(target)): + a, b = target[:i], target[i:] + if a != b: + ans += cnt[a] * cnt[b] + else: + ans += cnt[a] * (cnt[a] - 1) + return ans +``` + ```java class Solution { public int numOfPairs(String[] nums, String target) { @@ -138,24 +167,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int numOfPairs(vector& nums, string target) { - int n = nums.size(); - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (i != j && nums[i] + nums[j] == target) ++ans; - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -178,21 +189,6 @@ public: }; ``` -### **Go** - -```go -func numOfPairs(nums []string, target string) (ans int) { - for i, a := range nums { - for j, b := range nums { - if i != j && a+b == target { - ans++ - } - } - } - return ans -} -``` - ```go func numOfPairs(nums []string, target string) (ans int) { cnt := map[string]int{} @@ -211,10 +207,6 @@ func numOfPairs(nums []string, target string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2024.Maximize the Confusion of an Exam/README.md b/solution/2000-2099/2024.Maximize the Confusion of an Exam/README.md index 4cc7bec63f90e..1cfad54ed0aec 100644 --- a/solution/2000-2099/2024.Maximize the Confusion of an Exam/README.md +++ b/solution/2000-2099/2024.Maximize the Confusion of an Exam/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 思路同 [1004. 最大连续 1 的个数 III](/solution/1000-1099/1004.Max%20Consecutive%20Ones%20III/README.md) @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int: @@ -98,10 +92,6 @@ class Solution: return max(get('T', k), get('F', k)) ``` -### **Java** - - - ```java class Solution { public int maxConsecutiveAnswers(String answerKey, int k) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func maxConsecutiveAnswers(answerKey string, k int) int { get := func(c byte, k int) int { @@ -167,8 +153,6 @@ func maxConsecutiveAnswers(answerKey string, k int) int { } ``` -### **TypeScript** - ```ts function maxConsecutiveAnswers(answerKey: string, k: number): number { const n = answerKey.length; @@ -189,8 +173,6 @@ function maxConsecutiveAnswers(answerKey: string, k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_consecutive_answers(answer_key: String, k: i32) -> i32 { @@ -217,10 +199,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2024.Maximize the Confusion of an Exam/README_EN.md b/solution/2000-2099/2024.Maximize the Confusion of an Exam/README_EN.md index d6e749d36bdca..b14a3bb1fd20b 100644 --- a/solution/2000-2099/2024.Maximize the Confusion of an Exam/README_EN.md +++ b/solution/2000-2099/2024.Maximize the Confusion of an Exam/README_EN.md @@ -56,9 +56,9 @@ In both cases, there are five consecutive 'T's. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,8 +78,6 @@ class Solution: return max(get('T', k), get('F', k)) ``` -### **Java** - ```java class Solution { public int maxConsecutiveAnswers(String answerKey, int k) { @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +117,6 @@ public: }; ``` -### **Go** - ```go func maxConsecutiveAnswers(answerKey string, k int) int { get := func(c byte, k int) int { @@ -145,8 +139,6 @@ func maxConsecutiveAnswers(answerKey string, k int) int { } ``` -### **TypeScript** - ```ts function maxConsecutiveAnswers(answerKey: string, k: number): number { const n = answerKey.length; @@ -167,8 +159,6 @@ function maxConsecutiveAnswers(answerKey: string, k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_consecutive_answers(answer_key: String, k: i32) -> i32 { @@ -195,10 +185,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2025.Maximum Number of Ways to Partition an Array/README.md b/solution/2000-2099/2025.Maximum Number of Ways to Partition an Array/README.md index 00a469699c993..cc1403386019e 100644 --- a/solution/2000-2099/2025.Maximum Number of Ways to Partition an Array/README.md +++ b/solution/2000-2099/2025.Maximum Number of Ways to Partition an Array/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:前缀和 + 哈希表** +### 方法一:前缀和 + 哈希表 我们可以先预处理得到数组 $nums$ 对应的前缀和数组 $s$,其中 $s[i]$ 表示数组 $nums[0,...i-1]$ 的和。那么数组所有元素之和为 $s[n - 1]$。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def waysToPartition(self, nums: List[int], k: int) -> int: @@ -104,10 +98,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int waysToPartition(int[] nums, int k) { @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -172,8 +160,6 @@ public: }; ``` -### **Go** - ```go func waysToPartition(nums []int, k int) (ans int) { n := len(nums) @@ -203,10 +189,6 @@ func waysToPartition(nums []int, k int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2025.Maximum Number of Ways to Partition an Array/README_EN.md b/solution/2000-2099/2025.Maximum Number of Ways to Partition an Array/README_EN.md index f45dd5b8737de..da6286b464616 100644 --- a/solution/2000-2099/2025.Maximum Number of Ways to Partition an Array/README_EN.md +++ b/solution/2000-2099/2025.Maximum Number of Ways to Partition an Array/README_EN.md @@ -57,7 +57,7 @@ There are four ways to partition the array. ## Solutions -**Solution 1: Prefix Sum + Hash Table** +### Solution 1: Prefix Sum + Hash Table We can preprocess to get the prefix sum array $s$ corresponding to the array $nums$, where $s[i]$ represents the sum of the array $nums[0,...i-1]$. Therefore, the sum of all elements in the array is $s[n - 1]$. @@ -71,8 +71,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def waysToPartition(self, nums: List[int], k: int) -> int: @@ -99,8 +97,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int waysToPartition(int[] nums, int k) { @@ -132,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -165,8 +159,6 @@ public: }; ``` -### **Go** - ```go func waysToPartition(nums []int, k int) (ans int) { n := len(nums) @@ -196,10 +188,6 @@ func waysToPartition(nums []int, k int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2026.Low-Quality Problems/README.md b/solution/2000-2099/2026.Low-Quality Problems/README.md index b8460c73154f9..4260e8e561315 100644 --- a/solution/2000-2099/2026.Low-Quality Problems/README.md +++ b/solution/2000-2099/2026.Low-Quality Problems/README.md @@ -65,14 +65,10 @@ Problems 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT problem_id @@ -82,3 +78,5 @@ ORDER BY problem_id; ``` + + diff --git a/solution/2000-2099/2026.Low-Quality Problems/README_EN.md b/solution/2000-2099/2026.Low-Quality Problems/README_EN.md index 2e59b469281ca..d8477be597ad8 100644 --- a/solution/2000-2099/2026.Low-Quality Problems/README_EN.md +++ b/solution/2000-2099/2026.Low-Quality Problems/README_EN.md @@ -62,9 +62,9 @@ Problems 7, 10, 11, and 13 are low-quality problems because their like percentag ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -75,3 +75,5 @@ ORDER BY problem_id; ``` + + diff --git a/solution/2000-2099/2027.Minimum Moves to Convert String/README.md b/solution/2000-2099/2027.Minimum Moves to Convert String/README.md index 1badca2e4ba4f..5ef352179c8a2 100644 --- a/solution/2000-2099/2027.Minimum Moves to Convert String/README.md +++ b/solution/2000-2099/2027.Minimum Moves to Convert String/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 遍历字符串 $s$,只要遇到 `'X'`,指针 $i$ 就直接往后移动三格,并且答案加 $1$;否则指针 $i$ 往后移动一格。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def minimumMoves(self, s: str) -> int: @@ -78,10 +72,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumMoves(String s) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func minimumMoves(s string) (ans int) { for i := 0; i < len(s); i++ { @@ -129,8 +115,6 @@ func minimumMoves(s string) (ans int) { } ``` -### **TypeScript** - ```ts function minimumMoves(s: string): number { const n = s.length; @@ -148,8 +132,6 @@ function minimumMoves(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn minimum_moves(s: String) -> i32 { @@ -170,8 +152,6 @@ impl Solution { } ``` -### **C** - ```c int minimumMoves(char* s) { int n = strlen(s); @@ -189,10 +169,6 @@ int minimumMoves(char* s) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2027.Minimum Moves to Convert String/README_EN.md b/solution/2000-2099/2027.Minimum Moves to Convert String/README_EN.md index 77f218c7be286..d310c5fc8fdf6 100644 --- a/solution/2000-2099/2027.Minimum Moves to Convert String/README_EN.md +++ b/solution/2000-2099/2027.Minimum Moves to Convert String/README_EN.md @@ -47,7 +47,7 @@ Then we select the last 3 characters and convert them so that the final string c ## Solutions -**Solution 1: Greedy Algorithm** +### Solution 1: Greedy Algorithm Traverse the string $s$. Whenever you encounter `'X'`, move the pointer $i$ three steps forward and add $1$ to the answer; otherwise, move the pointer $i$ one step forward. @@ -55,8 +55,6 @@ The time complexity is $O(n)$, where $n$ represents the length of the string $s$ -### **Python3** - ```python class Solution: def minimumMoves(self, s: str) -> int: @@ -70,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumMoves(String s) { @@ -87,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +99,6 @@ public: }; ``` -### **Go** - ```go func minimumMoves(s string) (ans int) { for i := 0; i < len(s); i++ { @@ -119,8 +111,6 @@ func minimumMoves(s string) (ans int) { } ``` -### **TypeScript** - ```ts function minimumMoves(s: string): number { const n = s.length; @@ -138,8 +128,6 @@ function minimumMoves(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn minimum_moves(s: String) -> i32 { @@ -160,8 +148,6 @@ impl Solution { } ``` -### **C** - ```c int minimumMoves(char* s) { int n = strlen(s); @@ -179,10 +165,6 @@ int minimumMoves(char* s) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2028.Find Missing Observations/README.md b/solution/2000-2099/2028.Find Missing Observations/README.md index 088c494eaf743..b28da7abcc66b 100644 --- a/solution/2000-2099/2028.Find Missing Observations/README.md +++ b/solution/2000-2099/2028.Find Missing Observations/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:构造** +### 方法一:构造 根据题目描述,所有数字之和为 $(n + m) \times mean$,已知的数字之和为 `sum(rolls)`,那么缺失的数字之和为 $s = (n + m) \times mean - sum(rolls)$。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]: @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] missingRolls(int[] rolls, int mean, int n) { @@ -118,7 +108,41 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + vector missingRolls(vector& rolls, int mean, int n) { + int m = rolls.size(); + int s = (n + m) * mean; + for (int& v : rolls) s -= v; + if (s > n * 6 || s < n) return {}; + vector ans(n, s / n); + for (int i = 0; i < s % n; ++i) ++ans[i]; + return ans; + } +}; +``` + +```go +func missingRolls(rolls []int, mean int, n int) []int { + m := len(rolls) + s := (n + m) * mean + for _, v := range rolls { + s -= v + } + if s > n*6 || s < n { + return []int{} + } + ans := make([]int, n) + for i, j := 0, 0; i < n; i, j = i+1, j+1 { + ans[i] = s / n + if j < s%n { + ans[i]++ + } + } + return ans +} +``` ```ts function missingRolls(rolls: number[], mean: number, n: number): number[] { @@ -152,8 +176,6 @@ function missingRolls(rolls: number[], mean: number, n: number): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn missing_rolls(rolls: Vec, mean: i32, n: i32) -> Vec { @@ -191,50 +213,6 @@ impl Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector missingRolls(vector& rolls, int mean, int n) { - int m = rolls.size(); - int s = (n + m) * mean; - for (int& v : rolls) s -= v; - if (s > n * 6 || s < n) return {}; - vector ans(n, s / n); - for (int i = 0; i < s % n; ++i) ++ans[i]; - return ans; - } -}; -``` - -### **Go** - -```go -func missingRolls(rolls []int, mean int, n int) []int { - m := len(rolls) - s := (n + m) * mean - for _, v := range rolls { - s -= v - } - if s > n*6 || s < n { - return []int{} - } - ans := make([]int, n) - for i, j := 0, 0; i < n; i, j = i+1, j+1 { - ans[i] = s / n - if j < s%n { - ans[i]++ - } - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2028.Find Missing Observations/README_EN.md b/solution/2000-2099/2028.Find Missing Observations/README_EN.md index e4adf847cc447..59d6e014cc97b 100644 --- a/solution/2000-2099/2028.Find Missing Observations/README_EN.md +++ b/solution/2000-2099/2028.Find Missing Observations/README_EN.md @@ -50,7 +50,7 @@ ## Solutions -**Solution 1: Construction** +### Solution 1: Construction According to the problem description, the sum of all numbers is $(n + m) \times mean$, and the sum of known numbers is `sum(rolls)`. Therefore, the sum of the missing numbers is $s = (n + m) \times mean - sum(rolls)$. @@ -62,8 +62,6 @@ The time complexity is $O(n + m)$, and the space complexity is $O(1)$. Here, $n$ -### **Python3** - ```python class Solution: def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]: @@ -77,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] missingRolls(int[] rolls, int mean, int n) { @@ -100,7 +96,41 @@ class Solution { } ``` -### **TypeScript** +```cpp +class Solution { +public: + vector missingRolls(vector& rolls, int mean, int n) { + int m = rolls.size(); + int s = (n + m) * mean; + for (int& v : rolls) s -= v; + if (s > n * 6 || s < n) return {}; + vector ans(n, s / n); + for (int i = 0; i < s % n; ++i) ++ans[i]; + return ans; + } +}; +``` + +```go +func missingRolls(rolls []int, mean int, n int) []int { + m := len(rolls) + s := (n + m) * mean + for _, v := range rolls { + s -= v + } + if s > n*6 || s < n { + return []int{} + } + ans := make([]int, n) + for i, j := 0, 0; i < n; i, j = i+1, j+1 { + ans[i] = s / n + if j < s%n { + ans[i]++ + } + } + return ans +} +``` ```ts function missingRolls(rolls: number[], mean: number, n: number): number[] { @@ -134,8 +164,6 @@ function missingRolls(rolls: number[], mean: number, n: number): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn missing_rolls(rolls: Vec, mean: i32, n: i32) -> Vec { @@ -173,50 +201,6 @@ impl Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector missingRolls(vector& rolls, int mean, int n) { - int m = rolls.size(); - int s = (n + m) * mean; - for (int& v : rolls) s -= v; - if (s > n * 6 || s < n) return {}; - vector ans(n, s / n); - for (int i = 0; i < s % n; ++i) ++ans[i]; - return ans; - } -}; -``` - -### **Go** - -```go -func missingRolls(rolls []int, mean int, n int) []int { - m := len(rolls) - s := (n + m) * mean - for _, v := range rolls { - s -= v - } - if s > n*6 || s < n { - return []int{} - } - ans := make([]int, n) - for i, j := 0, 0; i < n; i, j = i+1, j+1 { - ans[i] = s / n - if j < s%n { - ans[i]++ - } - } - return ans -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2029.Stone Game IX/README.md b/solution/2000-2099/2029.Stone Game IX/README.md index dfffc13bd6884..4e4c968691626 100644 --- a/solution/2000-2099/2029.Stone Game IX/README.md +++ b/solution/2000-2099/2029.Stone Game IX/README.md @@ -64,28 +64,10 @@ Alice 输掉游戏,因为已移除石子值总和(15)可以被 3 整除, ## 解法 - - -由于我们只关心总和能否被 3 整除,我们可以将 stones 按照模 3 的结果进行分组计数。 - -根据题意,第一回合不能移除 0,否则直接输掉游戏,因此第一回合只能移除 1 或者 2。我们可以枚举这两种情况,如果其中一种可以让 Alice 获胜就返回 true,否则返回 false。 - -下面以第一回合移除 1 来说明。在不考虑移除 0 的前提下,后面的移除由于要满足总和不能被 3 整除,因此移除的石子是固定的,整体构成一个 112121212… 循环的序列。 - -对于 0,由于移除之后不会改变总和模 3 的结果,因此不会改变后续 1 和 2 的移除顺序,所以我们可以在序列的任意非开头位置插入 0。 - -两人为了不让自己输掉,必然会按照上述序列进行,直到没有石子,或某一方只能移除导致总和被 3 整除的石子时分出胜负。因此我们需要求出让总和不能被 3 整除的最大的回合数,这相当于 112121212... 序列的最长长度,加上 0 的个数。 - -若该回合数为奇数,且还有剩余石子,那么下一回合要轮到 Bob 移除石子,且他只能移除一枚让总和被 3 整除的石子,于是 Alice 获胜;否则 Bob 获胜。 - -对于第一回合移除 2 的情况,同样会构成一个 221212121... 循环的序列,做法同上。 +### 方法一 -### **Python3** - - - ```python class Solution: def stoneGameIX(self, stones: List[int]) -> bool: @@ -106,10 +88,6 @@ class Solution: return check(c) or check(c1) ``` -### **Java** - - - ```java class Solution { public boolean stoneGameIX(int[] stones) { @@ -136,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +137,6 @@ public: }; ``` -### **Go** - ```go func stoneGameIX(stones []int) bool { check := func(c [3]int) bool { @@ -185,10 +159,6 @@ func stoneGameIX(stones []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2029.Stone Game IX/README_EN.md b/solution/2000-2099/2029.Stone Game IX/README_EN.md index 921edbd7480b7..764d2dd9cec02 100644 --- a/solution/2000-2099/2029.Stone Game IX/README_EN.md +++ b/solution/2000-2099/2029.Stone Game IX/README_EN.md @@ -55,9 +55,9 @@ Alice loses the game because the sum of the removed stones (15) is divisible by ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,8 +79,6 @@ class Solution: return check(c) or check(c1) ``` -### **Java** - ```java class Solution { public boolean stoneGameIX(int[] stones) { @@ -107,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +128,6 @@ public: }; ``` -### **Go** - ```go func stoneGameIX(stones []int) bool { check := func(c [3]int) bool { @@ -156,10 +150,6 @@ func stoneGameIX(stones []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2030.Smallest K-Length Subsequence With Occurrences of a Letter/README.md b/solution/2000-2099/2030.Smallest K-Length Subsequence With Occurrences of a Letter/README.md index 5eef4385b46a1..552d1e16d9ca3 100644 --- a/solution/2000-2099/2030.Smallest K-Length Subsequence With Occurrences of a Letter/README.md +++ b/solution/2000-2099/2030.Smallest K-Length Subsequence With Occurrences of a Letter/README.md @@ -59,30 +59,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2000-2099/2030.Smallest K-Length Subsequence With Occurrences of a Letter/README_EN.md b/solution/2000-2099/2030.Smallest K-Length Subsequence With Occurrences of a Letter/README_EN.md index 692bc6d62cc0d..fcdca6a1478e8 100644 --- a/solution/2000-2099/2030.Smallest K-Length Subsequence With Occurrences of a Letter/README_EN.md +++ b/solution/2000-2099/2030.Smallest K-Length Subsequence With Occurrences of a Letter/README_EN.md @@ -53,24 +53,4 @@ The lexicographically smallest subsequence among them is "eet". ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/README.md b/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/README.md index 733a76e96a2fb..d61599bde0dea 100644 --- a/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/README.md +++ b/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:前缀和 + 树状数组** +### 方法一:前缀和 + 树状数组 题目需要我们统计所有子数组中 $1$ 的数量大于 $0$ 的数量的子数组的个数,如果我们将数组中的元素 $0$ 看作 $-1$,那么题目就变成了统计所有子数组中元素和大于 $0$ 的子数组的个数。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class BinaryIndexedTree: __slots__ = ["n", "c"] @@ -108,27 +102,6 @@ class Solution: return ans ``` -```python -from sortedcontainers import SortedList - - -class Solution: - def subarraysWithMoreZerosThanOnes(self, nums: List[int]) -> int: - sl = SortedList([0]) - mod = 10**9 + 7 - ans = s = 0 - for x in nums: - s += x or -1 - ans += sl.bisect_left(s) - ans %= mod - sl.add(s) - return ans -``` - -### **Java** - - - ```java class BinaryIndexedTree { private int n; @@ -173,8 +146,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { private: @@ -221,8 +192,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -267,8 +236,6 @@ func subarraysWithMoreZerosThanOnes(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -312,10 +279,29 @@ function subarraysWithMoreZerosThanOnes(nums: number[]): number { } ``` -### **...** + + +### 方法二 -``` + +```python +from sortedcontainers import SortedList + + +class Solution: + def subarraysWithMoreZerosThanOnes(self, nums: List[int]) -> int: + sl = SortedList([0]) + mod = 10**9 + 7 + ans = s = 0 + for x in nums: + s += x or -1 + ans += sl.bisect_left(s) + ans %= mod + sl.add(s) + return ans ``` + + diff --git a/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/README_EN.md b/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/README_EN.md index 751ae94f8117d..ae93e4e3ba537 100644 --- a/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/README_EN.md +++ b/solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/README_EN.md @@ -50,7 +50,7 @@ The subarrays of size 1 that have more ones than zeros are: [1] ## Solutions -**Solution 1: Prefix Sum + Binary Indexed Tree** +### Solution 1: Prefix Sum + Binary Indexed Tree The problem requires us to count the number of subarrays where the count of $1$ is greater than the count of $0$. If we treat $0$ in the array as $-1$, then the problem becomes counting the number of subarrays where the sum of elements is greater than $0$. @@ -64,8 +64,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class BinaryIndexedTree: __slots__ = ["n", "c"] @@ -103,25 +101,6 @@ class Solution: return ans ``` -```python -from sortedcontainers import SortedList - - -class Solution: - def subarraysWithMoreZerosThanOnes(self, nums: List[int]) -> int: - sl = SortedList([0]) - mod = 10**9 + 7 - ans = s = 0 - for x in nums: - s += x or -1 - ans += sl.bisect_left(s) - ans %= mod - sl.add(s) - return ans -``` - -### **Java** - ```java class BinaryIndexedTree { private int n; @@ -166,8 +145,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { private: @@ -214,8 +191,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -260,8 +235,6 @@ func subarraysWithMoreZerosThanOnes(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -305,10 +278,29 @@ function subarraysWithMoreZerosThanOnes(nums: number[]): number { } ``` -### **...** + -``` +### Solution 2 + + +```python +from sortedcontainers import SortedList + + +class Solution: + def subarraysWithMoreZerosThanOnes(self, nums: List[int]) -> int: + sl = SortedList([0]) + mod = 10**9 + 7 + ans = s = 0 + for x in nums: + s += x or -1 + ans += sl.bisect_left(s) + ans %= mod + sl.add(s) + return ans ``` + + diff --git a/solution/2000-2099/2032.Two Out of Three/README.md b/solution/2000-2099/2032.Two Out of Three/README.md index c79925e7d4296..8078c68919c5d 100644 --- a/solution/2000-2099/2032.Two Out of Three/README.md +++ b/solution/2000-2099/2032.Two Out of Three/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:数组 + 枚举** +### 方法一:数组 + 枚举 我们可以先将每个数组中的元素放入数组中,然后枚举 $1$ 到 $100$ 中的每个数 $i$,判断 $i$ 是否在至少两个数组中出现过。若是,则将 $i$ 加入答案数组中。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def twoOutOfThree( @@ -73,10 +67,6 @@ class Solution: return [i for i in range(1, 101) if (i in s1) + (i in s2) + (i in s3) > 1] ``` -### **Java** - - - ```java class Solution { public List twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func twoOutOfThree(nums1 []int, nums2 []int, nums3 []int) (ans []int) { get := func(nums []int) (s [101]int) { @@ -143,8 +129,6 @@ func twoOutOfThree(nums1 []int, nums2 []int, nums3 []int) (ans []int) { } ``` -### **TypeScript** - ```ts function twoOutOfThree(nums1: number[], nums2: number[], nums3: number[]): number[] { const count = new Array(101).fill(0); @@ -161,8 +145,6 @@ function twoOutOfThree(nums1: number[], nums2: number[], nums3: number[]): numbe } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -203,10 +185,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2032.Two Out of Three/README_EN.md b/solution/2000-2099/2032.Two Out of Three/README_EN.md index 07de98b48dbc7..7455ddf2d107d 100644 --- a/solution/2000-2099/2032.Two Out of Three/README_EN.md +++ b/solution/2000-2099/2032.Two Out of Three/README_EN.md @@ -46,7 +46,7 @@ Given three integer arrays nums1, nums2, and num ## Solutions -**Solution 1: Array + Enumeration** +### Solution 1: Array + Enumeration We can first put each element of the arrays into an array, then enumerate each number $i$ from $1$ to $100$, and check whether $i$ appears in at least two arrays. If so, add $i$ to the answer array. @@ -54,8 +54,6 @@ The time complexity is $O(n_1 + n_2 + n_3)$, and the space complexity is $O(n_1 -### **Python3** - ```python class Solution: def twoOutOfThree( @@ -65,8 +63,6 @@ class Solution: return [i for i in range(1, 101) if (i in s1) + (i in s2) + (i in s3) > 1] ``` -### **Java** - ```java class Solution { public List twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) { @@ -90,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +107,6 @@ public: }; ``` -### **Go** - ```go func twoOutOfThree(nums1 []int, nums2 []int, nums3 []int) (ans []int) { get := func(nums []int) (s [101]int) { @@ -133,8 +125,6 @@ func twoOutOfThree(nums1 []int, nums2 []int, nums3 []int) (ans []int) { } ``` -### **TypeScript** - ```ts function twoOutOfThree(nums1: number[], nums2: number[], nums3: number[]): number[] { const count = new Array(101).fill(0); @@ -151,8 +141,6 @@ function twoOutOfThree(nums1: number[], nums2: number[], nums3: number[]): numbe } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -193,10 +181,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2033.Minimum Operations to Make a Uni-Value Grid/README.md b/solution/2000-2099/2033.Minimum Operations to Make a Uni-Value Grid/README.md index ad1e1b83919d1..0b747e125235f 100644 --- a/solution/2000-2099/2033.Minimum Operations to Make a Uni-Value Grid/README.md +++ b/solution/2000-2099/2033.Minimum Operations to Make a Uni-Value Grid/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 首先,要使得网格化为单值网格,那么网格的所有元素与 $x$ 的余数必须相同。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, grid: List[List[int]], x: int) -> int: @@ -93,10 +87,6 @@ class Solution: return sum(abs(v - mid) // x for v in nums) ``` -### **Java** - - - ```java class Solution { public int minOperations(int[][] grid, int x) { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func minOperations(grid [][]int, x int) int { mod := grid[0][0] % x @@ -181,10 +167,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2033.Minimum Operations to Make a Uni-Value Grid/README_EN.md b/solution/2000-2099/2033.Minimum Operations to Make a Uni-Value Grid/README_EN.md index 5849d97181fcb..08b4c32740d9d 100644 --- a/solution/2000-2099/2033.Minimum Operations to Make a Uni-Value Grid/README_EN.md +++ b/solution/2000-2099/2033.Minimum Operations to Make a Uni-Value Grid/README_EN.md @@ -52,7 +52,7 @@ A total of 4 operations were used. ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy Firstly, to make the grid a single-value grid, the remainder of all elements of the grid with $x$ must be the same. @@ -62,8 +62,6 @@ The time complexity is $O((m \times n) \times \log (m \times n))$, and the space -### **Python3** - ```python class Solution: def minOperations(self, grid: List[List[int]], x: int) -> int: @@ -79,8 +77,6 @@ class Solution: return sum(abs(v - mid) // x for v in nums) ``` -### **Java** - ```java class Solution { public int minOperations(int[][] grid, int x) { @@ -106,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +128,6 @@ public: }; ``` -### **Go** - ```go func minOperations(grid [][]int, x int) int { mod := grid[0][0] % x @@ -165,10 +157,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2034.Stock Price Fluctuation/README.md b/solution/2000-2099/2034.Stock Price Fluctuation/README.md index d24cf00cfe82c..e20e3c88bc697 100644 --- a/solution/2000-2099/2034.Stock Price Fluctuation/README.md +++ b/solution/2000-2099/2034.Stock Price Fluctuation/README.md @@ -64,9 +64,7 @@ stockPrice.minimum(); // 返回 2 ,最低价格时间戳为 4 ,价格为 ## 解法 - - -**方法一:哈希表 + 有序集合** +### 方法一:哈希表 + 有序集合 我们定义以下几个数据结构或变量,其中: @@ -85,10 +83,6 @@ stockPrice.minimum(); // 返回 2 ,最低价格时间戳为 4 ,价格为 -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -124,10 +118,6 @@ class StockPrice: # param_4 = obj.minimum() ``` -### **Java** - - - ```java class StockPrice { private Map d = new HashMap<>(); @@ -172,8 +162,6 @@ class StockPrice { */ ``` -### **C++** - ```cpp class StockPrice { public: @@ -217,8 +205,6 @@ private: */ ``` -### **Go** - ```go type StockPrice struct { d map[int]int @@ -277,10 +263,6 @@ func (this *StockPrice) Minimum() int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2034.Stock Price Fluctuation/README_EN.md b/solution/2000-2099/2034.Stock Price Fluctuation/README_EN.md index 1e3ea44e59486..00b7ada87ade5 100644 --- a/solution/2000-2099/2034.Stock Price Fluctuation/README_EN.md +++ b/solution/2000-2099/2034.Stock Price Fluctuation/README_EN.md @@ -61,7 +61,7 @@ stockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4. ## Solutions -**Solution 1: Hash Table + Ordered Set** +### Solution 1: Hash Table + Ordered Set We define the following data structures or variables: @@ -80,8 +80,6 @@ The space complexity is $O(n)$, where $n$ is the number of `update` operations. -### **Python3** - ```python from sortedcontainers import SortedList @@ -117,8 +115,6 @@ class StockPrice: # param_4 = obj.minimum() ``` -### **Java** - ```java class StockPrice { private Map d = new HashMap<>(); @@ -163,8 +159,6 @@ class StockPrice { */ ``` -### **C++** - ```cpp class StockPrice { public: @@ -208,8 +202,6 @@ private: */ ``` -### **Go** - ```go type StockPrice struct { d map[int]int @@ -268,10 +260,6 @@ func (this *StockPrice) Minimum() int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2035.Partition Array Into Two Arrays to Minimize Sum Difference/README.md b/solution/2000-2099/2035.Partition Array Into Two Arrays to Minimize Sum Difference/README.md index b048ca078e3d3..4b555951d124c 100644 --- a/solution/2000-2099/2035.Partition Array Into Two Arrays to Minimize Sum Difference/README.md +++ b/solution/2000-2099/2035.Partition Array Into Two Arrays to Minimize Sum Difference/README.md @@ -52,14 +52,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minimumDifference(self, nums: List[int]) -> int: @@ -100,10 +96,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumDifference(int[] nums) { @@ -155,8 +147,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -205,8 +195,6 @@ public: }; ``` -### **Go** - ```go func minimumDifference(nums []int) int { n := len(nums) >> 1 @@ -264,10 +252,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2035.Partition Array Into Two Arrays to Minimize Sum Difference/README_EN.md b/solution/2000-2099/2035.Partition Array Into Two Arrays to Minimize Sum Difference/README_EN.md index dcdf777c777a4..364e89dc4a9c7 100644 --- a/solution/2000-2099/2035.Partition Array Into Two Arrays to Minimize Sum Difference/README_EN.md +++ b/solution/2000-2099/2035.Partition Array Into Two Arrays to Minimize Sum Difference/README_EN.md @@ -47,9 +47,9 @@ The absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -91,8 +91,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumDifference(int[] nums) { @@ -144,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -194,8 +190,6 @@ public: }; ``` -### **Go** - ```go func minimumDifference(nums []int) int { n := len(nums) >> 1 @@ -253,10 +247,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2036.Maximum Alternating Subarray Sum/README.md b/solution/2000-2099/2036.Maximum Alternating Subarray Sum/README.md index 043a88c7a2c5c..2efaa50886eb7 100644 --- a/solution/2000-2099/2036.Maximum Alternating Subarray Sum/README.md +++ b/solution/2000-2099/2036.Maximum Alternating Subarray Sum/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f$ 表示以 $nums[i]$ 结尾的交替子数组的最大和,定义 $g$ 表示以 $-nums[i]$ 结尾的交替子数组的最大和,初始时 $f$ 和 $g$ 均为 $-\infty$。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def maximumAlternatingSubarraySum(self, nums: List[int]) -> int: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long maximumAlternatingSubarraySum(int[] nums) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func maximumAlternatingSubarraySum(nums []int) int64 { const inf = 1 << 60 @@ -133,8 +119,6 @@ func maximumAlternatingSubarraySum(nums []int) int64 { } ``` -### **TypeScript** - ```ts function maximumAlternatingSubarraySum(nums: number[]): number { let [ans, f, g] = [-Infinity, -Infinity, -Infinity]; @@ -146,10 +130,6 @@ function maximumAlternatingSubarraySum(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2036.Maximum Alternating Subarray Sum/README_EN.md b/solution/2000-2099/2036.Maximum Alternating Subarray Sum/README_EN.md index 3190e4ad6ea52..7f19cbc3e572b 100644 --- a/solution/2000-2099/2036.Maximum Alternating Subarray Sum/README_EN.md +++ b/solution/2000-2099/2036.Maximum Alternating Subarray Sum/README_EN.md @@ -53,7 +53,7 @@ The alternating subarray sum is 1. ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f$ as the maximum sum of the alternating subarray ending with $nums[i]$, and define $g$ as the maximum sum of the alternating subarray ending with $-nums[i]$. Initially, both $f$ and $g$ are $-\infty$. @@ -63,8 +63,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def maximumAlternatingSubarraySum(self, nums: List[int]) -> int: @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long maximumAlternatingSubarraySum(int[] nums) { @@ -93,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +107,6 @@ public: }; ``` -### **Go** - ```go func maximumAlternatingSubarraySum(nums []int) int64 { const inf = 1 << 60 @@ -127,8 +119,6 @@ func maximumAlternatingSubarraySum(nums []int) int64 { } ``` -### **TypeScript** - ```ts function maximumAlternatingSubarraySum(nums: number[]): number { let [ans, f, g] = [-Infinity, -Infinity, -Infinity]; @@ -140,10 +130,6 @@ function maximumAlternatingSubarraySum(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/README.md b/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/README.md index 0ceb38cd19a1b..3f3891dc0796d 100644 --- a/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/README.md +++ b/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 将两个数组分别排序,然后遍历两个数组,计算每个学生的座位与其实际座位的距离,将所有距离相加即为答案。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def minMovesToSeat(self, seats: List[int], students: List[int]) -> int: @@ -89,10 +83,6 @@ class Solution: return sum(abs(a - b) for a, b in zip(seats, students)) ``` -### **Java** - - - ```java class Solution { public int minMovesToSeat(int[] seats, int[] students) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func minMovesToSeat(seats []int, students []int) (ans int) { sort.Ints(seats) @@ -145,8 +131,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minMovesToSeat(seats: number[], students: number[]): number { seats.sort((a, b) => a - b); @@ -160,8 +144,6 @@ function minMovesToSeat(seats: number[], students: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_moves_to_seat(mut seats: Vec, mut students: Vec) -> i32 { @@ -177,8 +159,6 @@ impl Solution { } ``` -### **C** - ```c int cmp(const void* a, const void* b) { return *(int*) a - *(int*) b; @@ -195,10 +175,6 @@ int minMovesToSeat(int* seats, int seatsSize, int* students, int studentsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/README_EN.md b/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/README_EN.md index 2646bbc35a64a..cdf123f5461fc 100644 --- a/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/README_EN.md +++ b/solution/2000-2099/2037.Minimum Number of Moves to Seat Everyone/README_EN.md @@ -67,7 +67,7 @@ In total, 1 + 3 + 0 + 0 = 4 moves were used. ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting Sort both arrays, then traverse the two arrays, calculate the distance between each student's seat and their actual seat, and add all the distances to get the answer. @@ -75,8 +75,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def minMovesToSeat(self, seats: List[int], students: List[int]) -> int: @@ -85,8 +83,6 @@ class Solution: return sum(abs(a - b) for a, b in zip(seats, students)) ``` -### **Java** - ```java class Solution { public int minMovesToSeat(int[] seats, int[] students) { @@ -101,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func minMovesToSeat(seats []int, students []int) (ans int) { sort.Ints(seats) @@ -139,8 +131,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minMovesToSeat(seats: number[], students: number[]): number { seats.sort((a, b) => a - b); @@ -154,8 +144,6 @@ function minMovesToSeat(seats: number[], students: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_moves_to_seat(mut seats: Vec, mut students: Vec) -> i32 { @@ -171,8 +159,6 @@ impl Solution { } ``` -### **C** - ```c int cmp(const void* a, const void* b) { return *(int*) a - *(int*) b; @@ -189,10 +175,6 @@ int minMovesToSeat(int* seats, int seatsSize, int* students, int studentsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/README.md b/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/README.md index 812d234dc4ea5..0f34b72f0584b 100644 --- a/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/README.md +++ b/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/README.md @@ -73,9 +73,7 @@ ABBBBBBBAA -> ABBBBBBAA ## 解法 - - -**方法一:计数** +### 方法一:计数 我们统计字符串 `colors` 中连续出现 $3$ 个 `'A'` 或 $3$ 个 `'B'` 的个数,分别记为 $a$ 和 $b$。 @@ -85,10 +83,6 @@ ABBBBBBBAA -> ABBBBBBAA -### **Python3** - - - ```python class Solution: def winnerOfGame(self, colors: str) -> bool: @@ -102,10 +96,6 @@ class Solution: return a > b ``` -### **Java** - - - ```java class Solution { public boolean winnerOfGame(String colors) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func winnerOfGame(colors string) bool { n := len(colors) @@ -178,8 +164,6 @@ func winnerOfGame(colors string) bool { } ``` -### **TypeScript** - ```ts function winnerOfGame(colors: string): boolean { const n = colors.length; @@ -201,10 +185,6 @@ function winnerOfGame(colors: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/README_EN.md b/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/README_EN.md index 57e0a28703afd..ff3903479d535 100644 --- a/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/README_EN.md +++ b/solution/2000-2099/2038.Remove Colored Pieces if Both Neighbors are the Same Color/README_EN.md @@ -72,7 +72,7 @@ Thus, Bob wins, so return false. ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We count the number of times that the string `colors` contains three consecutive `'A'`s or three consecutive `'B'`s, denoted as $a$ and $b$, respectively. @@ -82,8 +82,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string `colors`. T -### **Python3** - ```python class Solution: def winnerOfGame(self, colors: str) -> bool: @@ -97,8 +95,6 @@ class Solution: return a > b ``` -### **Java** - ```java class Solution { public boolean winnerOfGame(String colors) { @@ -122,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +142,6 @@ public: }; ``` -### **Go** - ```go func winnerOfGame(colors string) bool { n := len(colors) @@ -171,8 +163,6 @@ func winnerOfGame(colors string) bool { } ``` -### **TypeScript** - ```ts function winnerOfGame(colors: string): boolean { const n = colors.length; @@ -194,10 +184,6 @@ function winnerOfGame(colors: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2039.The Time When the Network Becomes Idle/README.md b/solution/2000-2099/2039.The Time When the Network Becomes Idle/README.md index 6f543c14573c1..1ad25421b2f84 100644 --- a/solution/2000-2099/2039.The Time When the Network Becomes Idle/README.md +++ b/solution/2000-2099/2039.The Time When the Network Becomes Idle/README.md @@ -84,9 +84,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们先根据二维数组 $edges$ 构建无向图 $g$,其中 $g[u]$ 表示节点 $u$ 的所有邻居节点。 @@ -96,10 +94,6 @@ -### **Python3** - - - ```python class Solution: def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int: @@ -123,10 +117,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int networkBecomesIdle(int[][] edges, int[] patience) { @@ -162,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -200,8 +188,6 @@ public: }; ``` -### **Go** - ```go func networkBecomesIdle(edges [][]int, patience []int) (ans int) { n := len(patience) @@ -232,8 +218,6 @@ func networkBecomesIdle(edges [][]int, patience []int) (ans int) { } ``` -### **TypeScript** - ```ts function networkBecomesIdle(edges: number[][], patience: number[]): number { const n = patience.length; @@ -264,10 +248,6 @@ function networkBecomesIdle(edges: number[][], patience: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2039.The Time When the Network Becomes Idle/README_EN.md b/solution/2000-2099/2039.The Time When the Network Becomes Idle/README_EN.md index a4d97f8830375..92e038c920475 100644 --- a/solution/2000-2099/2039.The Time When the Network Becomes Idle/README_EN.md +++ b/solution/2000-2099/2039.The Time When the Network Becomes Idle/README_EN.md @@ -81,7 +81,7 @@ From the beginning of the second 3, the network becomes idle. ## Solutions -**Solution 1: BFS** +### Solution 1: BFS First, we construct an undirected graph $g$ based on the 2D array $edges$, where $g[u]$ represents all neighboring nodes of node $u$. @@ -91,8 +91,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int: @@ -116,8 +114,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int networkBecomesIdle(int[][] edges, int[] patience) { @@ -153,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -191,8 +185,6 @@ public: }; ``` -### **Go** - ```go func networkBecomesIdle(edges [][]int, patience []int) (ans int) { n := len(patience) @@ -223,8 +215,6 @@ func networkBecomesIdle(edges [][]int, patience []int) (ans int) { } ``` -### **TypeScript** - ```ts function networkBecomesIdle(edges: number[][], patience: number[]): number { const n = patience.length; @@ -255,10 +245,6 @@ function networkBecomesIdle(edges: number[][], patience: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README.md b/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README.md index c6d81e5a52d70..48a39701cd1e9 100644 --- a/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README.md +++ b/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README.md @@ -58,30 +58,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README_EN.md b/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README_EN.md index ae0828368ab70..5ef7085a4aac1 100644 --- a/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README_EN.md +++ b/solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/README_EN.md @@ -57,24 +57,4 @@ The 3rd smallest product is -6. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2000-2099/2041.Accepted Candidates From the Interviews/README.md b/solution/2000-2099/2041.Accepted Candidates From the Interviews/README.md index 7a7ab86cd4b2d..d59b0b37b32dc 100644 --- a/solution/2000-2099/2041.Accepted Candidates From the Interviews/README.md +++ b/solution/2000-2099/2041.Accepted Candidates From the Interviews/README.md @@ -92,14 +92,10 @@ Rounds table: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT candidate_id @@ -112,3 +108,5 @@ HAVING SUM(score) > 15; ``` + + diff --git a/solution/2000-2099/2041.Accepted Candidates From the Interviews/README_EN.md b/solution/2000-2099/2041.Accepted Candidates From the Interviews/README_EN.md index 8874a8a3f66c5..ea78dac757d24 100644 --- a/solution/2000-2099/2041.Accepted Candidates From the Interviews/README_EN.md +++ b/solution/2000-2099/2041.Accepted Candidates From the Interviews/README_EN.md @@ -89,9 +89,9 @@ Rounds table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -105,3 +105,5 @@ HAVING SUM(score) > 15; ``` + + diff --git a/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/README.md b/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/README.md index 48db940eea109..36a097ccb02da 100644 --- a/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/README.md +++ b/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/README.md @@ -72,9 +72,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以将字符串 $s$ 按空格分割成若干个单词。然后遍历每个单词,判断其是否为数字,若是数字,则将其转换为整数,与前一个数字比较,若不严格递增,返回 `false`,否则,将当前数字赋值给前一个数字,继续遍历。 @@ -84,10 +82,6 @@ -### **Python3** - - - ```python class Solution: def areNumbersAscending(self, s: str) -> bool: @@ -100,29 +94,6 @@ class Solution: return True ``` -```python -class Solution: - def areNumbersAscending(self, s: str) -> bool: - pre = i = 0 - n = len(s) - while i < n: - if s[i].isdigit(): - cur = 0 - while i < n and s[i].isdigit(): - cur = cur * 10 + int(s[i]) - i += 1 - if pre >= cur: - return False - pre = cur - else: - i += 1 - return True -``` - -### **Java** - - - ```java class Solution { public boolean areNumbersAscending(String s) { @@ -141,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +133,6 @@ public: }; ``` -### **Go** - ```go func areNumbersAscending(s string) bool { pre := 0 @@ -182,8 +149,6 @@ func areNumbersAscending(s string) bool { } ``` -### **TypeScript** - ```ts function areNumbersAscending(s: string): boolean { let pre = -1; @@ -200,8 +165,6 @@ function areNumbersAscending(s: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn are_numbers_ascending(s: String) -> bool { @@ -220,8 +183,6 @@ impl Solution { } ``` -### **C** - ```c bool areNumbersAscending(char* s) { int pre = -1; @@ -246,10 +207,31 @@ bool areNumbersAscending(char* s) { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def areNumbersAscending(self, s: str) -> bool: + pre = i = 0 + n = len(s) + while i < n: + if s[i].isdigit(): + cur = 0 + while i < n and s[i].isdigit(): + cur = cur * 10 + int(s[i]) + i += 1 + if pre >= cur: + return False + pre = cur + else: + i += 1 + return True ``` + + diff --git a/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/README_EN.md b/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/README_EN.md index 3b8f07e15d017..1cbad0d1e334d 100644 --- a/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/README_EN.md +++ b/solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/README_EN.md @@ -55,7 +55,7 @@ They are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can split the string $s$ into several words by spaces. Then, for each word, check if it is a number. If it is a number, convert it to an integer, compare it with the previous number. If it is not strictly increasing, return `false`. Otherwise, assign the current number to the previous number and continue the traversal. @@ -65,8 +65,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def areNumbersAscending(self, s: str) -> bool: @@ -79,27 +77,6 @@ class Solution: return True ``` -```python -class Solution: - def areNumbersAscending(self, s: str) -> bool: - pre = i = 0 - n = len(s) - while i < n: - if s[i].isdigit(): - cur = 0 - while i < n and s[i].isdigit(): - cur = cur * 10 + int(s[i]) - i += 1 - if pre >= cur: - return False - pre = cur - else: - i += 1 - return True -``` - -### **Java** - ```java class Solution { public boolean areNumbersAscending(String s) { @@ -118,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +116,6 @@ public: }; ``` -### **Go** - ```go func areNumbersAscending(s string) bool { pre := 0 @@ -159,8 +132,6 @@ func areNumbersAscending(s string) bool { } ``` -### **TypeScript** - ```ts function areNumbersAscending(s: string): boolean { let pre = -1; @@ -177,8 +148,6 @@ function areNumbersAscending(s: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn are_numbers_ascending(s: String) -> bool { @@ -197,8 +166,6 @@ impl Solution { } ``` -### **C** - ```c bool areNumbersAscending(char* s) { int pre = -1; @@ -223,10 +190,31 @@ bool areNumbersAscending(char* s) { } ``` -### **...** + + +### Solution 2 -``` + +```python +class Solution: + def areNumbersAscending(self, s: str) -> bool: + pre = i = 0 + n = len(s) + while i < n: + if s[i].isdigit(): + cur = 0 + while i < n and s[i].isdigit(): + cur = cur * 10 + int(s[i]) + i += 1 + if pre >= cur: + return False + pre = cur + else: + i += 1 + return True ``` + + diff --git a/solution/2000-2099/2043.Simple Bank System/README.md b/solution/2000-2099/2043.Simple Bank System/README.md index 8ec504b2ad7d3..0038e8032a91d 100644 --- a/solution/2000-2099/2043.Simple Bank System/README.md +++ b/solution/2000-2099/2043.Simple Bank System/README.md @@ -61,9 +61,7 @@ bank.withdraw(10, 50); // 返回 false ,交易无效,因为账户 10 并 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 根据题意,我们可以使用一个数组 `balance` 来模拟银行账户的余额,数组下标从 0 开始,数组的值表示账户的余额。 @@ -76,10 +74,6 @@ bank.withdraw(10, 50); // 返回 false ,交易无效,因为账户 10 并 -### **Python3** - - - ```python class Bank: def __init__(self, balance: List[int]): @@ -113,10 +107,6 @@ class Bank: # param_3 = obj.withdraw(account,money) ``` -### **Java** - - - ```java class Bank { private long[] balance; @@ -162,53 +152,6 @@ class Bank { */ ``` -### **TypeScript** - -```ts -class Bank { - balance: number[]; - constructor(balance: number[]) { - this.balance = balance; - } - - transfer(account1: number, account2: number, money: number): boolean { - if ( - account1 > this.balance.length || - account2 > this.balance.length || - money > this.balance[account1 - 1] - ) - return false; - this.balance[account1 - 1] -= money; - this.balance[account2 - 1] += money; - return true; - } - - deposit(account: number, money: number): boolean { - if (account > this.balance.length) return false; - this.balance[account - 1] += money; - return true; - } - - withdraw(account: number, money: number): boolean { - if (account > this.balance.length || money > this.balance[account - 1]) { - return false; - } - this.balance[account - 1] -= money; - return true; - } -} - -/** - * Your Bank object will be instantiated and called as such: - * var obj = new Bank(balance) - * var param_1 = obj.transfer(account1,account2,money) - * var param_2 = obj.deposit(account,money) - * var param_3 = obj.withdraw(account,money) - */ -``` - -### **C++** - ```cpp class Bank { public: @@ -249,8 +192,6 @@ public: */ ``` -### **Go** - ```go type Bank struct { balance []int64 @@ -295,7 +236,48 @@ func (this *Bank) Withdraw(account int, money int64) bool { */ ``` -### **Rust** +```ts +class Bank { + balance: number[]; + constructor(balance: number[]) { + this.balance = balance; + } + + transfer(account1: number, account2: number, money: number): boolean { + if ( + account1 > this.balance.length || + account2 > this.balance.length || + money > this.balance[account1 - 1] + ) + return false; + this.balance[account1 - 1] -= money; + this.balance[account2 - 1] += money; + return true; + } + + deposit(account: number, money: number): boolean { + if (account > this.balance.length) return false; + this.balance[account - 1] += money; + return true; + } + + withdraw(account: number, money: number): boolean { + if (account > this.balance.length || money > this.balance[account - 1]) { + return false; + } + this.balance[account - 1] -= money; + return true; + } +} + +/** + * Your Bank object will be instantiated and called as such: + * var obj = new Bank(balance) + * var param_1 = obj.transfer(account1,account2,money) + * var param_2 = obj.deposit(account,money) + * var param_3 = obj.withdraw(account,money) + */ +``` ```rust struct Bank { @@ -353,10 +335,6 @@ impl Bank { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2043.Simple Bank System/README_EN.md b/solution/2000-2099/2043.Simple Bank System/README_EN.md index ff6afeae2609a..8110d051abe74 100644 --- a/solution/2000-2099/2043.Simple Bank System/README_EN.md +++ b/solution/2000-2099/2043.Simple Bank System/README_EN.md @@ -57,7 +57,7 @@ bank.withdraw(10, 50); // return false, it is invalid because account 10 does ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation According to the problem description, we can use an array `balance` to simulate the balance of bank accounts. The array index starts from 0, and the value of the array represents the balance of the account. @@ -70,8 +70,6 @@ The time complexity of the above operations is $O(1)$, and the space complexity -### **Python3** - ```python class Bank: def __init__(self, balance: List[int]): @@ -105,8 +103,6 @@ class Bank: # param_3 = obj.withdraw(account,money) ``` -### **Java** - ```java class Bank { private long[] balance; @@ -152,53 +148,6 @@ class Bank { */ ``` -### **TypeScript** - -```ts -class Bank { - balance: number[]; - constructor(balance: number[]) { - this.balance = balance; - } - - transfer(account1: number, account2: number, money: number): boolean { - if ( - account1 > this.balance.length || - account2 > this.balance.length || - money > this.balance[account1 - 1] - ) - return false; - this.balance[account1 - 1] -= money; - this.balance[account2 - 1] += money; - return true; - } - - deposit(account: number, money: number): boolean { - if (account > this.balance.length) return false; - this.balance[account - 1] += money; - return true; - } - - withdraw(account: number, money: number): boolean { - if (account > this.balance.length || money > this.balance[account - 1]) { - return false; - } - this.balance[account - 1] -= money; - return true; - } -} - -/** - * Your Bank object will be instantiated and called as such: - * var obj = new Bank(balance) - * var param_1 = obj.transfer(account1,account2,money) - * var param_2 = obj.deposit(account,money) - * var param_3 = obj.withdraw(account,money) - */ -``` - -### **C++** - ```cpp class Bank { public: @@ -239,8 +188,6 @@ public: */ ``` -### **Go** - ```go type Bank struct { balance []int64 @@ -285,7 +232,48 @@ func (this *Bank) Withdraw(account int, money int64) bool { */ ``` -### **Rust** +```ts +class Bank { + balance: number[]; + constructor(balance: number[]) { + this.balance = balance; + } + + transfer(account1: number, account2: number, money: number): boolean { + if ( + account1 > this.balance.length || + account2 > this.balance.length || + money > this.balance[account1 - 1] + ) + return false; + this.balance[account1 - 1] -= money; + this.balance[account2 - 1] += money; + return true; + } + + deposit(account: number, money: number): boolean { + if (account > this.balance.length) return false; + this.balance[account - 1] += money; + return true; + } + + withdraw(account: number, money: number): boolean { + if (account > this.balance.length || money > this.balance[account - 1]) { + return false; + } + this.balance[account - 1] -= money; + return true; + } +} + +/** + * Your Bank object will be instantiated and called as such: + * var obj = new Bank(balance) + * var param_1 = obj.transfer(account1,account2,money) + * var param_2 = obj.deposit(account,money) + * var param_3 = obj.withdraw(account,money) + */ +``` ```rust struct Bank { @@ -343,10 +331,6 @@ impl Bank { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/README.md b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/README.md index 6e5ac7d398f21..aeddc38c6eba0 100644 --- a/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/README.md +++ b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/README.md @@ -56,24 +56,14 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 简单 DFS。可以预先算出按位或的最大值 mx,然后 DFS 搜索按位或结果等于 mx 的所有子集数。也可以在 DFS 搜索中逐渐更新 mx 与对应的子集数。 时间复杂度 $O(2^n)$。 -**方法二:二进制枚举** - -时间复杂度 $O(n*2^n)$。 - -### **Python3** - - - ```python class Solution: def countMaxOrSubsets(self, nums: List[int]) -> int: @@ -94,48 +84,6 @@ class Solution: return ans ``` -```python -class Solution: - def countMaxOrSubsets(self, nums: List[int]) -> int: - def dfs(u, t): - nonlocal ans, mx - if u == len(nums): - if t > mx: - mx, ans = t, 1 - elif t == mx: - ans += 1 - return - dfs(u + 1, t | nums[u]) - dfs(u + 1, t) - - ans = mx = 0 - dfs(0, 0) - return ans -``` - -```python -class Solution: - def countMaxOrSubsets(self, nums: List[int]) -> int: - n = len(nums) - ans = 0 - mx = 0 - for mask in range(1 << n): - t = 0 - for i, v in enumerate(nums): - if (mask >> i) & 1: - t |= v - if mx < t: - mx = t - ans = 1 - elif mx == t: - ans += 1 - return ans -``` - -### **Java** - - - ```java class Solution { private int mx; @@ -165,61 +113,57 @@ class Solution { } ``` -```java +```cpp class Solution { - private int mx; - private int ans; - private int[] nums; +public: + int mx; + int ans; + vector nums; - public int countMaxOrSubsets(int[] nums) { - this.nums = nums; + int countMaxOrSubsets(vector& nums) { + this->nums = nums; + mx = 0; + ans = 0; + for (int x : nums) mx |= x; dfs(0, 0); return ans; } - private void dfs(int u, int t) { - if (u == nums.length) { - if (t > mx) { - mx = t; - ans = 1; - } else if (t == mx) { - ++ans; - } + void dfs(int i, int t) { + if (i == nums.size()) { + if (t == mx) ++ans; return; } - dfs(u + 1, t); - dfs(u + 1, t | nums[u]); + dfs(i + 1, t); + dfs(i + 1, t | nums[i]); } -} +}; ``` -```java -class Solution { - public int countMaxOrSubsets(int[] nums) { - int n = nums.length; - int ans = 0; - int mx = 0; - for (int mask = 1; mask < 1 << n; ++mask) { - int t = 0; - for (int i = 0; i < n; ++i) { - if (((mask >> i) & 1) == 1) { - t |= nums[i]; - } - } - if (mx < t) { - mx = t; - ans = 1; - } else if (mx == t) { - ++ans; - } - } - return ans; - } +```go +func countMaxOrSubsets(nums []int) int { + mx, ans := 0, 0 + for _, x := range nums { + mx |= x + } + + var dfs func(i, t int) + dfs = func(i, t int) { + if i == len(nums) { + if t == mx { + ans++ + } + return + } + dfs(i+1, t) + dfs(i+1, t|nums[i]) + } + + dfs(0, 0) + return ans } ``` -### **TypeScript** - ```ts function countMaxOrSubsets(nums: number[]): number { let n = nums.length; @@ -241,57 +185,92 @@ function countMaxOrSubsets(nums: number[]): number { } ``` -```ts -function countMaxOrSubsets(nums: number[]): number { - const n = nums.length; - let res = 0; - let max = -Infinity; - const dfs = (i: number, sum: number) => { - for (let j = i; j < n; j++) { - const num = sum | nums[j]; - if (num >= max) { - if (num > max) { +```rust +impl Solution { + fn dfs(nums: &Vec, i: usize, sum: i32) -> (i32, i32) { + let n = nums.len(); + let mut max = i32::MIN; + let mut res = 0; + for j in i..n { + let num = sum | nums[j]; + if num >= max { + if num > max { max = num; res = 0; } - res++; + res += 1; + } + let (r_max, r_res) = Self::dfs(nums, j + 1, num); + if r_max >= max { + if r_max > max { + max = r_max; + res = 0; + } + res += r_res; } - dfs(j + 1, num); } - }; - dfs(0, 0); + (max, res) + } - return res; + pub fn count_max_or_subsets(nums: Vec) -> i32 { + Self::dfs(&nums, 0, 0).1 + } } ``` -### **C++** + -```cpp +### 方法二:二进制枚举 + +时间复杂度 $O(n*2^n)$。 + + + +```python +class Solution: + def countMaxOrSubsets(self, nums: List[int]) -> int: + def dfs(u, t): + nonlocal ans, mx + if u == len(nums): + if t > mx: + mx, ans = t, 1 + elif t == mx: + ans += 1 + return + dfs(u + 1, t | nums[u]) + dfs(u + 1, t) + + ans = mx = 0 + dfs(0, 0) + return ans +``` + +```java class Solution { -public: - int mx; - int ans; - vector nums; + private int mx; + private int ans; + private int[] nums; - int countMaxOrSubsets(vector& nums) { - this->nums = nums; - mx = 0; - ans = 0; - for (int x : nums) mx |= x; + public int countMaxOrSubsets(int[] nums) { + this.nums = nums; dfs(0, 0); return ans; } - void dfs(int i, int t) { - if (i == nums.size()) { - if (t == mx) ++ans; + private void dfs(int u, int t) { + if (u == nums.length) { + if (t > mx) { + mx = t; + ans = 1; + } else if (t == mx) { + ++ans; + } return; } - dfs(i + 1, t); - dfs(i + 1, t | nums[i]); + dfs(u + 1, t); + dfs(u + 1, t | nums[u]); } -}; +} ``` ```cpp @@ -320,6 +299,103 @@ public: }; ``` +```go +func countMaxOrSubsets(nums []int) int { + n := len(nums) + ans := 0 + mx := 0 + for mask := 1; mask < 1<> i) & 1) == 1 { + t |= v + } + } + if mx < t { + mx = t + ans = 1 + } else if mx == t { + ans++ + } + } + return ans +} +``` + +```ts +function countMaxOrSubsets(nums: number[]): number { + const n = nums.length; + let res = 0; + let max = -Infinity; + const dfs = (i: number, sum: number) => { + for (let j = i; j < n; j++) { + const num = sum | nums[j]; + if (num >= max) { + if (num > max) { + max = num; + res = 0; + } + res++; + } + dfs(j + 1, num); + } + }; + dfs(0, 0); + + return res; +} +``` + + + +### 方法三 + + + +```python +class Solution: + def countMaxOrSubsets(self, nums: List[int]) -> int: + n = len(nums) + ans = 0 + mx = 0 + for mask in range(1 << n): + t = 0 + for i, v in enumerate(nums): + if (mask >> i) & 1: + t |= v + if mx < t: + mx = t + ans = 1 + elif mx == t: + ans += 1 + return ans +``` + +```java +class Solution { + public int countMaxOrSubsets(int[] nums) { + int n = nums.length; + int ans = 0; + int mx = 0; + for (int mask = 1; mask < 1 << n; ++mask) { + int t = 0; + for (int i = 0; i < n; ++i) { + if (((mask >> i) & 1) == 1) { + t |= nums[i]; + } + } + if (mx < t) { + mx = t; + ans = 1; + } else if (mx == t) { + ++ans; + } + } + return ans; + } +} +``` + ```cpp class Solution { public: @@ -345,55 +421,6 @@ public: }; ``` -### **Go** - -```go -func countMaxOrSubsets(nums []int) int { - mx, ans := 0, 0 - for _, x := range nums { - mx |= x - } - - var dfs func(i, t int) - dfs = func(i, t int) { - if i == len(nums) { - if t == mx { - ans++ - } - return - } - dfs(i+1, t) - dfs(i+1, t|nums[i]) - } - - dfs(0, 0) - return ans -} -``` - -```go -func countMaxOrSubsets(nums []int) int { - n := len(nums) - ans := 0 - mx := 0 - for mask := 1; mask < 1<> i) & 1) == 1 { - t |= v - } - } - if mx < t { - mx = t - ans = 1 - } else if mx == t { - ans++ - } - } - return ans -} -``` - ```go func countMaxOrSubsets(nums []int) int { mx, ans := 0, 0 @@ -415,45 +442,6 @@ func countMaxOrSubsets(nums []int) int { } ``` -### **Rust** - -```rust -impl Solution { - fn dfs(nums: &Vec, i: usize, sum: i32) -> (i32, i32) { - let n = nums.len(); - let mut max = i32::MIN; - let mut res = 0; - for j in i..n { - let num = sum | nums[j]; - if num >= max { - if num > max { - max = num; - res = 0; - } - res += 1; - } - let (r_max, r_res) = Self::dfs(nums, j + 1, num); - if r_max >= max { - if r_max > max { - max = r_max; - res = 0; - } - res += r_res; - } - } - (max, res) - } - - pub fn count_max_or_subsets(nums: Vec) -> i32 { - Self::dfs(&nums, 0, 0).1 - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/README_EN.md b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/README_EN.md index f616ef0639be9..37dc17acabb14 100644 --- a/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/README_EN.md +++ b/solution/2000-2099/2044.Count Number of Maximum Bitwise-OR Subsets/README_EN.md @@ -52,12 +52,10 @@ ## Solutions -DFS. +### Solution 1 -### **Python3** - ```python class Solution: def countMaxOrSubsets(self, nums: List[int]) -> int: @@ -78,46 +76,6 @@ class Solution: return ans ``` -```python -class Solution: - def countMaxOrSubsets(self, nums: List[int]) -> int: - def dfs(u, t): - nonlocal ans, mx - if u == len(nums): - if t > mx: - mx, ans = t, 1 - elif t == mx: - ans += 1 - return - dfs(u + 1, t | nums[u]) - dfs(u + 1, t) - - ans = mx = 0 - dfs(0, 0) - return ans -``` - -```python -class Solution: - def countMaxOrSubsets(self, nums: List[int]) -> int: - n = len(nums) - ans = 0 - mx = 0 - for mask in range(1 << n): - t = 0 - for i, v in enumerate(nums): - if (mask >> i) & 1: - t |= v - if mx < t: - mx = t - ans = 1 - elif mx == t: - ans += 1 - return ans -``` - -### **Java** - ```java class Solution { private int mx; @@ -147,61 +105,57 @@ class Solution { } ``` -```java +```cpp class Solution { - private int mx; - private int ans; - private int[] nums; +public: + int mx; + int ans; + vector nums; - public int countMaxOrSubsets(int[] nums) { - this.nums = nums; + int countMaxOrSubsets(vector& nums) { + this->nums = nums; + mx = 0; + ans = 0; + for (int x : nums) mx |= x; dfs(0, 0); return ans; } - private void dfs(int u, int t) { - if (u == nums.length) { - if (t > mx) { - mx = t; - ans = 1; - } else if (t == mx) { - ++ans; - } + void dfs(int i, int t) { + if (i == nums.size()) { + if (t == mx) ++ans; return; } - dfs(u + 1, t); - dfs(u + 1, t | nums[u]); + dfs(i + 1, t); + dfs(i + 1, t | nums[i]); } -} +}; ``` -```java -class Solution { - public int countMaxOrSubsets(int[] nums) { - int n = nums.length; - int ans = 0; - int mx = 0; - for (int mask = 1; mask < 1 << n; ++mask) { - int t = 0; - for (int i = 0; i < n; ++i) { - if (((mask >> i) & 1) == 1) { - t |= nums[i]; - } - } - if (mx < t) { - mx = t; - ans = 1; - } else if (mx == t) { - ++ans; - } - } - return ans; - } +```go +func countMaxOrSubsets(nums []int) int { + mx, ans := 0, 0 + for _, x := range nums { + mx |= x + } + + var dfs func(i, t int) + dfs = func(i, t int) { + if i == len(nums) { + if t == mx { + ans++ + } + return + } + dfs(i+1, t) + dfs(i+1, t|nums[i]) + } + + dfs(0, 0) + return ans } ``` -### **TypeScript** - ```ts function countMaxOrSubsets(nums: number[]): number { let n = nums.length; @@ -223,57 +177,90 @@ function countMaxOrSubsets(nums: number[]): number { } ``` -```ts -function countMaxOrSubsets(nums: number[]): number { - const n = nums.length; - let res = 0; - let max = -Infinity; - const dfs = (i: number, sum: number) => { - for (let j = i; j < n; j++) { - const num = sum | nums[j]; - if (num >= max) { - if (num > max) { +```rust +impl Solution { + fn dfs(nums: &Vec, i: usize, sum: i32) -> (i32, i32) { + let n = nums.len(); + let mut max = i32::MIN; + let mut res = 0; + for j in i..n { + let num = sum | nums[j]; + if num >= max { + if num > max { max = num; res = 0; } - res++; + res += 1; + } + let (r_max, r_res) = Self::dfs(nums, j + 1, num); + if r_max >= max { + if r_max > max { + max = r_max; + res = 0; + } + res += r_res; } - dfs(j + 1, num); } - }; - dfs(0, 0); + (max, res) + } - return res; + pub fn count_max_or_subsets(nums: Vec) -> i32 { + Self::dfs(&nums, 0, 0).1 + } } ``` -### **C++** + -```cpp +### Solution 2 + + + +```python +class Solution: + def countMaxOrSubsets(self, nums: List[int]) -> int: + def dfs(u, t): + nonlocal ans, mx + if u == len(nums): + if t > mx: + mx, ans = t, 1 + elif t == mx: + ans += 1 + return + dfs(u + 1, t | nums[u]) + dfs(u + 1, t) + + ans = mx = 0 + dfs(0, 0) + return ans +``` + +```java class Solution { -public: - int mx; - int ans; - vector nums; + private int mx; + private int ans; + private int[] nums; - int countMaxOrSubsets(vector& nums) { - this->nums = nums; - mx = 0; - ans = 0; - for (int x : nums) mx |= x; + public int countMaxOrSubsets(int[] nums) { + this.nums = nums; dfs(0, 0); return ans; } - void dfs(int i, int t) { - if (i == nums.size()) { - if (t == mx) ++ans; + private void dfs(int u, int t) { + if (u == nums.length) { + if (t > mx) { + mx = t; + ans = 1; + } else if (t == mx) { + ++ans; + } return; } - dfs(i + 1, t); - dfs(i + 1, t | nums[i]); + dfs(u + 1, t); + dfs(u + 1, t | nums[u]); } -}; +} ``` ```cpp @@ -302,6 +289,103 @@ public: }; ``` +```go +func countMaxOrSubsets(nums []int) int { + n := len(nums) + ans := 0 + mx := 0 + for mask := 1; mask < 1<> i) & 1) == 1 { + t |= v + } + } + if mx < t { + mx = t + ans = 1 + } else if mx == t { + ans++ + } + } + return ans +} +``` + +```ts +function countMaxOrSubsets(nums: number[]): number { + const n = nums.length; + let res = 0; + let max = -Infinity; + const dfs = (i: number, sum: number) => { + for (let j = i; j < n; j++) { + const num = sum | nums[j]; + if (num >= max) { + if (num > max) { + max = num; + res = 0; + } + res++; + } + dfs(j + 1, num); + } + }; + dfs(0, 0); + + return res; +} +``` + + + +### Solution 3 + + + +```python +class Solution: + def countMaxOrSubsets(self, nums: List[int]) -> int: + n = len(nums) + ans = 0 + mx = 0 + for mask in range(1 << n): + t = 0 + for i, v in enumerate(nums): + if (mask >> i) & 1: + t |= v + if mx < t: + mx = t + ans = 1 + elif mx == t: + ans += 1 + return ans +``` + +```java +class Solution { + public int countMaxOrSubsets(int[] nums) { + int n = nums.length; + int ans = 0; + int mx = 0; + for (int mask = 1; mask < 1 << n; ++mask) { + int t = 0; + for (int i = 0; i < n; ++i) { + if (((mask >> i) & 1) == 1) { + t |= nums[i]; + } + } + if (mx < t) { + mx = t; + ans = 1; + } else if (mx == t) { + ++ans; + } + } + return ans; + } +} +``` + ```cpp class Solution { public: @@ -327,32 +411,6 @@ public: }; ``` -### **Go** - -```go -func countMaxOrSubsets(nums []int) int { - mx, ans := 0, 0 - for _, x := range nums { - mx |= x - } - - var dfs func(i, t int) - dfs = func(i, t int) { - if i == len(nums) { - if t == mx { - ans++ - } - return - } - dfs(i+1, t) - dfs(i+1, t|nums[i]) - } - - dfs(0, 0) - return ans -} -``` - ```go func countMaxOrSubsets(nums []int) int { mx, ans := 0, 0 @@ -374,68 +432,6 @@ func countMaxOrSubsets(nums []int) int { } ``` -```go -func countMaxOrSubsets(nums []int) int { - n := len(nums) - ans := 0 - mx := 0 - for mask := 1; mask < 1<> i) & 1) == 1 { - t |= v - } - } - if mx < t { - mx = t - ans = 1 - } else if mx == t { - ans++ - } - } - return ans -} -``` - -### **Rust** - -```rust -impl Solution { - fn dfs(nums: &Vec, i: usize, sum: i32) -> (i32, i32) { - let n = nums.len(); - let mut max = i32::MIN; - let mut res = 0; - for j in i..n { - let num = sum | nums[j]; - if num >= max { - if num > max { - max = num; - res = 0; - } - res += 1; - } - let (r_max, r_res) = Self::dfs(nums, j + 1, num); - if r_max >= max { - if r_max > max { - max = r_max; - res = 0; - } - res += r_res; - } - } - (max, res) - } - - pub fn count_max_or_subsets(nums: Vec) -> i32 { - Self::dfs(&nums, 0, 0).1 - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2045.Second Minimum Time to Reach Destination/README.md b/solution/2000-2099/2045.Second Minimum Time to Reach Destination/README.md index b3565acf52b00..f07f15cb3978d 100644 --- a/solution/2000-2099/2045.Second Minimum Time to Reach Destination/README.md +++ b/solution/2000-2099/2045.Second Minimum Time to Reach Destination/README.md @@ -80,14 +80,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def secondMinimum( @@ -119,10 +115,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int secondMinimum(int n, int[][] edges, int time, int change) { @@ -168,10 +160,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2045.Second Minimum Time to Reach Destination/README_EN.md b/solution/2000-2099/2045.Second Minimum Time to Reach Destination/README_EN.md index 26b77d6d43c42..a94d6fce8111f 100644 --- a/solution/2000-2099/2045.Second Minimum Time to Reach Destination/README_EN.md +++ b/solution/2000-2099/2045.Second Minimum Time to Reach Destination/README_EN.md @@ -73,9 +73,9 @@ The second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -108,8 +108,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int secondMinimum(int n, int[][] edges, int time, int change) { @@ -155,10 +153,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2046.Sort Linked List Already Sorted Using Absolute Values/README.md b/solution/2000-2099/2046.Sort Linked List Already Sorted Using Absolute Values/README.md index 6c932e8a16ebf..ca11b2cea6876 100644 --- a/solution/2000-2099/2046.Sort Linked List Already Sorted Using Absolute Values/README.md +++ b/solution/2000-2099/2046.Sort Linked List Already Sorted Using Absolute Values/README.md @@ -54,18 +54,12 @@ ## 解法 - - -**方法一:头插法** +### 方法一:头插法 先默认第一个点已经排序完毕。然后从第二个点开始,遇到值为负数的节点,采用头插法;非负数,则继续往下遍历即可。 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -87,10 +81,6 @@ class Solution: return head ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -184,10 +170,6 @@ func sortLinkedList(head *ListNode) *ListNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2046.Sort Linked List Already Sorted Using Absolute Values/README_EN.md b/solution/2000-2099/2046.Sort Linked List Already Sorted Using Absolute Values/README_EN.md index 6add5130e9143..f15b29d641961 100644 --- a/solution/2000-2099/2046.Sort Linked List Already Sorted Using Absolute Values/README_EN.md +++ b/solution/2000-2099/2046.Sort Linked List Already Sorted Using Absolute Values/README_EN.md @@ -52,9 +52,9 @@ The linked list is already sorted in non-decreasing order. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -77,8 +77,6 @@ class Solution: return head ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -110,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -145,8 +141,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -172,10 +166,6 @@ func sortLinkedList(head *ListNode) *ListNode { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2047.Number of Valid Words in a Sentence/README.md b/solution/2000-2099/2047.Number of Valid Words in a Sentence/README.md index 96ec18b60bf72..8eb0a2e7ea252 100644 --- a/solution/2000-2099/2047.Number of Valid Words in a Sentence/README.md +++ b/solution/2000-2099/2047.Number of Valid Words in a Sentence/README.md @@ -61,14 +61,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def countValidWords(self, sentence: str) -> int: @@ -92,10 +88,6 @@ class Solution: return sum(check(token) for token in sentence.split()) ``` -### **Java** - - - ```java class Solution { public int countValidWords(String sentence) { @@ -132,8 +124,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function countValidWords(sentence: string): number { let words = sentence.trim().split(/\s+/); @@ -173,10 +163,6 @@ function isValied(str: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2047.Number of Valid Words in a Sentence/README_EN.md b/solution/2000-2099/2047.Number of Valid Words in a Sentence/README_EN.md index 4fae6dd0fe900..71f98db0b1a62 100644 --- a/solution/2000-2099/2047.Number of Valid Words in a Sentence/README_EN.md +++ b/solution/2000-2099/2047.Number of Valid Words in a Sentence/README_EN.md @@ -57,9 +57,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: return sum(check(token) for token in sentence.split()) ``` -### **Java** - ```java class Solution { public int countValidWords(String sentence) { @@ -122,8 +120,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function countValidWords(sentence: string): number { let words = sentence.trim().split(/\s+/); @@ -163,10 +159,6 @@ function isValied(str: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2048.Next Greater Numerically Balanced Number/README.md b/solution/2000-2099/2048.Next Greater Numerically Balanced Number/README.md index ffa24fe6c17d2..062c5f3bc1365 100644 --- a/solution/2000-2099/2048.Next Greater Numerically Balanced Number/README.md +++ b/solution/2000-2099/2048.Next Greater Numerically Balanced Number/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们注意到,题目中 $n$ 的范围是 $[0, 10^6]$,而大于 $10^6$ 的其中一个数值平衡数是 $1224444$,因此我们直接枚举 $x \in [n + 1, ..]$,然后判断 $x$ 是否是数值平衡数即可。枚举的 $x$ 一定不会超过 $1224444$。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def nextBeautifulNumber(self, n: int) -> int: @@ -84,10 +78,6 @@ class Solution: return x ``` -### **Java** - - - ```java class Solution { public int nextBeautifulNumber(int n) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func nextBeautifulNumber(n int) int { for x := n + 1; ; x++ { @@ -160,8 +146,6 @@ func nextBeautifulNumber(n int) int { } ``` -### **TypeScript** - ```ts function nextBeautifulNumber(n: number): number { for (let x = n + 1; ; ++x) { @@ -183,10 +167,6 @@ function nextBeautifulNumber(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2048.Next Greater Numerically Balanced Number/README_EN.md b/solution/2000-2099/2048.Next Greater Numerically Balanced Number/README_EN.md index 1527880977ce2..5be9e18e66c7d 100644 --- a/solution/2000-2099/2048.Next Greater Numerically Balanced Number/README_EN.md +++ b/solution/2000-2099/2048.Next Greater Numerically Balanced Number/README_EN.md @@ -54,7 +54,7 @@ It is also the smallest numerically balanced number strictly greater than 3000. ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We note that the range of $n$ in the problem is $[0, 10^6]$, and one of the balanced numbers greater than $10^6$ is $1224444$. Therefore, we directly enumerate $x \in [n + 1, ..]$ and then judge whether $x$ is a balanced number. The enumerated $x$ will definitely not exceed $1224444$. @@ -62,8 +62,6 @@ The time complexity is $O(M - n)$, where $M = 1224444$. The space complexity is -### **Python3** - ```python class Solution: def nextBeautifulNumber(self, n: int) -> int: @@ -77,8 +75,6 @@ class Solution: return x ``` -### **Java** - ```java class Solution { public int nextBeautifulNumber(int n) { @@ -102,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +122,6 @@ public: }; ``` -### **Go** - ```go func nextBeautifulNumber(n int) int { for x := n + 1; ; x++ { @@ -151,8 +143,6 @@ func nextBeautifulNumber(n int) int { } ``` -### **TypeScript** - ```ts function nextBeautifulNumber(n: number): number { for (let x = n + 1; ; ++x) { @@ -174,10 +164,6 @@ function nextBeautifulNumber(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2049.Count Nodes With the Highest Score/README.md b/solution/2000-2099/2049.Count Nodes With the Highest Score/README.md index 6eb0fed56726d..dd72f33df8a68 100644 --- a/solution/2000-2099/2049.Count Nodes With the Highest Score/README.md +++ b/solution/2000-2099/2049.Count Nodes With the Highest Score/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们先根据给定的父节点数组 `parents` 构建图 $g$,其中 $g[i]$ 表示节点 $i$ 的所有子节点。定义变量 $ans$ 表示最高得分的节点数目,变量 $mx$ 表示最高得分。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def countHighestScoreNodes(self, parents: List[int]) -> int: @@ -115,10 +109,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -161,8 +151,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -201,8 +189,6 @@ public: }; ``` -### **Go** - ```go func countHighestScoreNodes(parents []int) (ans int) { n := len(parents) @@ -237,8 +223,6 @@ func countHighestScoreNodes(parents []int) (ans int) { } ``` -### **TypeScript** - ```ts function countHighestScoreNodes(parents: number[]): number { const n = parents.length; @@ -272,8 +256,6 @@ function countHighestScoreNodes(parents: number[]): number { } ``` -### **C#** - ```cs public class Solution { private List[] g; @@ -323,10 +305,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2049.Count Nodes With the Highest Score/README_EN.md b/solution/2000-2099/2049.Count Nodes With the Highest Score/README_EN.md index 0bf9ac5b228d9..9f7e669409805 100644 --- a/solution/2000-2099/2049.Count Nodes With the Highest Score/README_EN.md +++ b/solution/2000-2099/2049.Count Nodes With the Highest Score/README_EN.md @@ -50,7 +50,7 @@ The highest score is 2, and two nodes (node 0 and node 1) have the highest score ## Solutions -**Solution 1: DFS** +### Solution 1: DFS First, we construct a graph $g$ based on the given parent array `parents`, where $g[i]$ represents all child nodes of node $i$. We define a variable $ans$ to represent the number of nodes with the highest score, and a variable $mx$ to represent the highest score. @@ -74,8 +74,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def countHighestScoreNodes(self, parents: List[int]) -> int: @@ -105,8 +103,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -149,8 +145,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -189,8 +183,6 @@ public: }; ``` -### **Go** - ```go func countHighestScoreNodes(parents []int) (ans int) { n := len(parents) @@ -225,8 +217,6 @@ func countHighestScoreNodes(parents []int) (ans int) { } ``` -### **TypeScript** - ```ts function countHighestScoreNodes(parents: number[]): number { const n = parents.length; @@ -260,8 +250,6 @@ function countHighestScoreNodes(parents: number[]): number { } ``` -### **C#** - ```cs public class Solution { private List[] g; @@ -311,10 +299,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2050.Parallel Courses III/README.md b/solution/2000-2099/2050.Parallel Courses III/README.md index e85377bcb7519..c5aac836b7d17 100644 --- a/solution/2000-2099/2050.Parallel Courses III/README.md +++ b/solution/2000-2099/2050.Parallel Courses III/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:拓扑排序 + 动态规划** +### 方法一:拓扑排序 + 动态规划 我们首先根据给定的先修课程关系,构建出一个有向无环图,对该图进行拓扑排序,然后根据拓扑排序的结果,使用动态规划求出完成所有课程所需要的最少时间。 @@ -86,10 +84,6 @@ -### **Python3** - - - ```python class Solution: def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int: @@ -117,10 +111,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumTime(int n, int[][] relations, int[] time) { @@ -158,8 +148,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -198,8 +186,6 @@ public: }; ``` -### **Go** - ```go func minimumTime(n int, relations [][]int, time []int) int { g := make([][]int, n) @@ -235,8 +221,6 @@ func minimumTime(n int, relations [][]int, time []int) int { } ``` -### **TypeScript** - ```ts function minimumTime(n: number, relations: number[][], time: number[]): number { const g: number[][] = Array(n) @@ -271,10 +255,6 @@ function minimumTime(n: number, relations: number[][], time: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2050.Parallel Courses III/README_EN.md b/solution/2000-2099/2050.Parallel Courses III/README_EN.md index a1de7a8d6961d..85497c2a23848 100644 --- a/solution/2000-2099/2050.Parallel Courses III/README_EN.md +++ b/solution/2000-2099/2050.Parallel Courses III/README_EN.md @@ -61,9 +61,9 @@ Thus, the minimum time needed to complete all the courses is 7 + 5 = 12 months. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -92,8 +92,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumTime(int n, int[][] relations, int[] time) { @@ -131,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +167,6 @@ public: }; ``` -### **Go** - ```go func minimumTime(n int, relations [][]int, time []int) int { g := make([][]int, n) @@ -208,8 +202,6 @@ func minimumTime(n int, relations [][]int, time []int) int { } ``` -### **TypeScript** - ```ts function minimumTime(n: number, relations: number[][], time: number[]): number { const g: number[][] = Array(n) @@ -244,10 +236,6 @@ function minimumTime(n: number, relations: number[][], time: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2051.The Category of Each Member in the Store/README.md b/solution/2000-2099/2051.The Category of Each Member in the Store/README.md index 6462963b72a1c..f421efb74cb84 100644 --- a/solution/2000-2099/2051.The Category of Each Member in the Store/README.md +++ b/solution/2000-2099/2051.The Category of Each Member in the Store/README.md @@ -126,14 +126,10 @@ Purchases 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -153,3 +149,5 @@ GROUP BY member_id; ``` + + diff --git a/solution/2000-2099/2051.The Category of Each Member in the Store/README_EN.md b/solution/2000-2099/2051.The Category of Each Member in the Store/README_EN.md index a05b197afe90c..28089e827c3b2 100644 --- a/solution/2000-2099/2051.The Category of Each Member in the Store/README_EN.md +++ b/solution/2000-2099/2051.The Category of Each Member in the Store/README_EN.md @@ -124,9 +124,9 @@ Purchases table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -147,3 +147,5 @@ GROUP BY member_id; ``` + + diff --git a/solution/2000-2099/2052.Minimum Cost to Separate Sentence Into Rows/README.md b/solution/2000-2099/2052.Minimum Cost to Separate Sentence Into Rows/README.md index 6273541249dff..9dd1bb2d513c3 100644 --- a/solution/2000-2099/2052.Minimum Cost to Separate Sentence Into Rows/README.md +++ b/solution/2000-2099/2052.Minimum Cost to Separate Sentence Into Rows/README.md @@ -73,16 +73,10 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 -### **Python3** - - - ```python class Solution: def minimumCost(self, sentence: str, k: int) -> int: @@ -102,10 +96,6 @@ class Solution: return dfs(0) ``` -### **Java** - - - ```java class Solution { private static final int INF = Integer.MAX_VALUE; @@ -146,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -183,8 +171,6 @@ public: }; ``` -### **Go** - ```go func minimumCost(sentence string, k int) int { words := strings.Split(sentence, " ") @@ -221,10 +207,6 @@ func minimumCost(sentence string, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2052.Minimum Cost to Separate Sentence Into Rows/README_EN.md b/solution/2000-2099/2052.Minimum Cost to Separate Sentence Into Rows/README_EN.md index 01327a10c4cdf..3b3f250acff74 100644 --- a/solution/2000-2099/2052.Minimum Cost to Separate Sentence Into Rows/README_EN.md +++ b/solution/2000-2099/2052.Minimum Cost to Separate Sentence Into Rows/README_EN.md @@ -70,9 +70,9 @@ The cost of the last row is not included in the total cost, and since there is o ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -93,8 +93,6 @@ class Solution: return dfs(0) ``` -### **Java** - ```java class Solution { private static final int INF = Integer.MAX_VALUE; @@ -135,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -172,8 +168,6 @@ public: }; ``` -### **Go** - ```go func minimumCost(sentence string, k int) int { words := strings.Split(sentence, " ") @@ -210,10 +204,6 @@ func minimumCost(sentence string, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2053.Kth Distinct String in an Array/README.md b/solution/2000-2099/2053.Kth Distinct String in an Array/README.md index 51fe14473d03b..82515e0fceebf 100644 --- a/solution/2000-2099/2053.Kth Distinct String in an Array/README.md +++ b/solution/2000-2099/2053.Kth Distinct String in an Array/README.md @@ -53,16 +53,10 @@ arr 中所有字符串都是独一无二的,所以返回第 1 个字符串 "aa ## 解法 - - -哈希表计数。 +### 方法一 -### **Python3** - - - ```python class Solution: def kthDistinct(self, arr: List[str], k: int) -> str: @@ -75,10 +69,6 @@ class Solution: return '' ``` -### **Java** - - - ```java class Solution { public String kthDistinct(String[] arr, int k) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func kthDistinct(arr []string, k int) string { counter := make(map[string]int) @@ -138,10 +124,6 @@ func kthDistinct(arr []string, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2053.Kth Distinct String in an Array/README_EN.md b/solution/2000-2099/2053.Kth Distinct String in an Array/README_EN.md index 8526551ba9731..02083b70dbb2a 100644 --- a/solution/2000-2099/2053.Kth Distinct String in an Array/README_EN.md +++ b/solution/2000-2099/2053.Kth Distinct String in an Array/README_EN.md @@ -52,9 +52,9 @@ The only distinct string is "b". Since there are fewer than 3 distinct ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return '' ``` -### **Java** - ```java class Solution { public String kthDistinct(String[] arr, int k) { @@ -90,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +105,6 @@ public: }; ``` -### **Go** - ```go func kthDistinct(arr []string, k int) string { counter := make(map[string]int) @@ -129,10 +123,6 @@ func kthDistinct(arr []string, k int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2054.Two Best Non-Overlapping Events/README.md b/solution/2000-2099/2054.Two Best Non-Overlapping Events/README.md index 599949e4fcbf8..47c6a94f69619 100644 --- a/solution/2000-2099/2054.Two Best Non-Overlapping Events/README.md +++ b/solution/2000-2099/2054.Two Best Non-Overlapping Events/README.md @@ -53,18 +53,12 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 时间复杂度 $O(nlogn)$,其中 $n$ 表示 $events$ 的长度。 -### **Python3** - - - ```python class Solution: def maxTwoEvents(self, events: List[List[int]]) -> int: @@ -82,10 +76,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxTwoEvents(int[][] events) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func maxTwoEvents(events [][]int) int { sort.Slice(events, func(i, j int) bool { @@ -179,10 +165,6 @@ func maxTwoEvents(events [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2054.Two Best Non-Overlapping Events/README_EN.md b/solution/2000-2099/2054.Two Best Non-Overlapping Events/README_EN.md index 688199127ad2a..c5eed3481ec15 100644 --- a/solution/2000-2099/2054.Two Best Non-Overlapping Events/README_EN.md +++ b/solution/2000-2099/2054.Two Best Non-Overlapping Events/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxTwoEvents(int[][] events) { @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +125,6 @@ public: }; ``` -### **Go** - ```go func maxTwoEvents(events [][]int) int { sort.Slice(events, func(i, j int) bool { @@ -162,10 +156,6 @@ func maxTwoEvents(events [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2055.Plates Between Candles/README.md b/solution/2000-2099/2055.Plates Between Candles/README.md index 76197b2d2cbb4..122b83ce0cf9e 100644 --- a/solution/2000-2099/2055.Plates Between Candles/README.md +++ b/solution/2000-2099/2055.Plates Between Candles/README.md @@ -54,18 +54,10 @@ ## 解法 - - -预处理得到每个位置最左边、最右边的蜡烛位置 `left`, `right`。 - -对于每个查询 `(i, j)`,可以获取到区间左端、右端蜡烛位置 `right[i]`, `left[j]`,然后前缀和求解两个蜡烛之间的盘子数量即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]: @@ -93,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] platesBetweenCandles(String s, int[][] queries) { @@ -132,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +148,6 @@ public: }; ``` -### **Go** - ```go func platesBetweenCandles(s string, queries [][]int) []int { n := len(s) @@ -198,10 +182,6 @@ func platesBetweenCandles(s string, queries [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2055.Plates Between Candles/README_EN.md b/solution/2000-2099/2055.Plates Between Candles/README_EN.md index 7e010e89f89b2..b8cc56de7a21d 100644 --- a/solution/2000-2099/2055.Plates Between Candles/README_EN.md +++ b/solution/2000-2099/2055.Plates Between Candles/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,8 +79,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] platesBetweenCandles(String s, int[][] queries) { @@ -116,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +142,6 @@ public: }; ``` -### **Go** - ```go func platesBetweenCandles(s string, queries [][]int) []int { n := len(s) @@ -182,10 +176,6 @@ func platesBetweenCandles(s string, queries [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2056.Number of Valid Move Combinations On Chessboard/README.md b/solution/2000-2099/2056.Number of Valid Move Combinations On Chessboard/README.md index f86678dc85257..644e7cf5b3eb3 100644 --- a/solution/2000-2099/2056.Number of Valid Move Combinations On Chessboard/README.md +++ b/solution/2000-2099/2056.Number of Valid Move Combinations On Chessboard/README.md @@ -107,30 +107,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2000-2099/2056.Number of Valid Move Combinations On Chessboard/README_EN.md b/solution/2000-2099/2056.Number of Valid Move Combinations On Chessboard/README_EN.md index 6d83f6a14978f..565c050aaec9b 100644 --- a/solution/2000-2099/2056.Number of Valid Move Combinations On Chessboard/README_EN.md +++ b/solution/2000-2099/2056.Number of Valid Move Combinations On Chessboard/README_EN.md @@ -66,24 +66,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2000-2099/2057.Smallest Index With Equal Value/README.md b/solution/2000-2099/2057.Smallest Index With Equal Value/README.md index 8934a6598a63c..1cf5a760ac57a 100644 --- a/solution/2000-2099/2057.Smallest Index With Equal Value/README.md +++ b/solution/2000-2099/2057.Smallest Index With Equal Value/README.md @@ -60,14 +60,10 @@ i=3: 3 mod 10 = 3 != nums[3]. ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def smallestEqual(self, nums: List[int]) -> int: @@ -77,10 +73,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int smallestEqual(int[] nums) { @@ -94,19 +86,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function smallestEqual(nums: number[]): number { - for (let i = 0; i < nums.length; i++) { - if (i % 10 == nums[i]) return i; - } - return -1; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -119,8 +98,6 @@ public: }; ``` -### **Go** - ```go func smallestEqual(nums []int) int { for i, v := range nums { @@ -132,10 +109,15 @@ func smallestEqual(nums []int) int { } ``` -### **...** - -``` - +```ts +function smallestEqual(nums: number[]): number { + for (let i = 0; i < nums.length; i++) { + if (i % 10 == nums[i]) return i; + } + return -1; +} ``` + + diff --git a/solution/2000-2099/2057.Smallest Index With Equal Value/README_EN.md b/solution/2000-2099/2057.Smallest Index With Equal Value/README_EN.md index aa9411d4d25ed..f92b312699aab 100644 --- a/solution/2000-2099/2057.Smallest Index With Equal Value/README_EN.md +++ b/solution/2000-2099/2057.Smallest Index With Equal Value/README_EN.md @@ -52,9 +52,9 @@ i=3: 3 mod 10 = 3 != nums[3]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int smallestEqual(int[] nums) { @@ -80,19 +78,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function smallestEqual(nums: number[]): number { - for (let i = 0; i < nums.length; i++) { - if (i % 10 == nums[i]) return i; - } - return -1; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -105,8 +90,6 @@ public: }; ``` -### **Go** - ```go func smallestEqual(nums []int) int { for i, v := range nums { @@ -118,10 +101,15 @@ func smallestEqual(nums []int) int { } ``` -### **...** - -``` - +```ts +function smallestEqual(nums: number[]): number { + for (let i = 0; i < nums.length; i++) { + if (i % 10 == nums[i]) return i; + } + return -1; +} ``` + + diff --git a/solution/2000-2099/2058.Find the Minimum and Maximum Number of Nodes Between Critical Points/README.md b/solution/2000-2099/2058.Find the Minimum and Maximum Number of Nodes Between Critical Points/README.md index ce3bf91b92ede..01b8f073b9a2c 100644 --- a/solution/2000-2099/2058.Find the Minimum and Maximum Number of Nodes Between Critical Points/README.md +++ b/solution/2000-2099/2058.Find the Minimum and Maximum Number of Nodes Between Critical Points/README.md @@ -79,16 +79,10 @@ ## 解法 - - -遍历链表,维护第一个临界点 first、最后一个临界点 last,以及相邻临界点的最小距离。 +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -116,10 +110,6 @@ class Solution: return ans if first != last else [-1, -1] ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -160,51 +150,6 @@ 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 nodesBetweenCriticalPoints(head: ListNode | null): number[] { - let idx = 1; - let pre = head.val; - head = head.next; - let nums = []; - while (head.next != null) { - let val = head.val, - post = head.next.val; - if (pre < val && val > post) { - nums.push(idx); - } - if (pre > val && val < post) { - nums.push(idx); - } - pre = val; - idx++; - head = head.next; - } - let n = nums.length; - if (n < 2) return [-1, -1]; - let min = Infinity; - for (let i = 1; i < n; i++) { - min = Math.min(nums[i] - nums[i - 1], min); - } - return [min, nums[n - 1] - nums[0]]; -} -``` - -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -244,8 +189,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -279,10 +222,47 @@ func nodesBetweenCriticalPoints(head *ListNode) []int { } ``` -### **...** - -``` +```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 nodesBetweenCriticalPoints(head: ListNode | null): number[] { + let idx = 1; + let pre = head.val; + head = head.next; + let nums = []; + while (head.next != null) { + let val = head.val, + post = head.next.val; + if (pre < val && val > post) { + nums.push(idx); + } + if (pre > val && val < post) { + nums.push(idx); + } + pre = val; + idx++; + head = head.next; + } + let n = nums.length; + if (n < 2) return [-1, -1]; + let min = Infinity; + for (let i = 1; i < n; i++) { + min = Math.min(nums[i] - nums[i - 1], min); + } + return [min, nums[n - 1] - nums[0]]; +} ``` + + diff --git a/solution/2000-2099/2058.Find the Minimum and Maximum Number of Nodes Between Critical Points/README_EN.md b/solution/2000-2099/2058.Find the Minimum and Maximum Number of Nodes Between Critical Points/README_EN.md index 155e710680ab2..6263db20129dc 100644 --- a/solution/2000-2099/2058.Find the Minimum and Maximum Number of Nodes Between Critical Points/README_EN.md +++ b/solution/2000-2099/2058.Find the Minimum and Maximum Number of Nodes Between Critical Points/README_EN.md @@ -59,9 +59,9 @@ Note that the last node is not considered a local maxima because it does not hav ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -90,8 +90,6 @@ class Solution: return ans if first != last else [-1, -1] ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -132,51 +130,6 @@ 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 nodesBetweenCriticalPoints(head: ListNode | null): number[] { - let idx = 1; - let pre = head.val; - head = head.next; - let nums = []; - while (head.next != null) { - let val = head.val, - post = head.next.val; - if (pre < val && val > post) { - nums.push(idx); - } - if (pre > val && val < post) { - nums.push(idx); - } - pre = val; - idx++; - head = head.next; - } - let n = nums.length; - if (n < 2) return [-1, -1]; - let min = Infinity; - for (let i = 1; i < n; i++) { - min = Math.min(nums[i] - nums[i - 1], min); - } - return [min, nums[n - 1] - nums[0]]; -} -``` - -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -216,8 +169,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -251,10 +202,47 @@ func nodesBetweenCriticalPoints(head *ListNode) []int { } ``` -### **...** - -``` +```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 nodesBetweenCriticalPoints(head: ListNode | null): number[] { + let idx = 1; + let pre = head.val; + head = head.next; + let nums = []; + while (head.next != null) { + let val = head.val, + post = head.next.val; + if (pre < val && val > post) { + nums.push(idx); + } + if (pre > val && val < post) { + nums.push(idx); + } + pre = val; + idx++; + head = head.next; + } + let n = nums.length; + if (n < 2) return [-1, -1]; + let min = Infinity; + for (let i = 1; i < n; i++) { + min = Math.min(nums[i] - nums[i - 1], min); + } + return [min, nums[n - 1] - nums[0]]; +} ``` + + diff --git a/solution/2000-2099/2059.Minimum Operations to Convert Number/README.md b/solution/2000-2099/2059.Minimum Operations to Convert Number/README.md index 43dcb51189e50..18516954f7b70 100644 --- a/solution/2000-2099/2059.Minimum Operations to Convert Number/README.md +++ b/solution/2000-2099/2059.Minimum Operations to Convert Number/README.md @@ -69,48 +69,10 @@ ## 解法 - - -BFS 最小步数模型。本题搜索空间不大,可以直接使用朴素 BFS,以下题解中还提供了双向 BFS 的题解代码,仅供参考。 - -双向 BFS 是 BFS 常见的一个优化方法,主要实现思路如下: - -1. 创建两个队列 q1, q2 分别用于“起点 -> 终点”、“终点 -> 起点”两个方向的搜索; -2. 创建两个哈希表 m1, m2 分别记录访问过的节点以及对应的扩展次数(步数); -3. 每次搜索时,优先选择元素数量较少的队列进行搜索扩展,如果在扩展过程中,搜索到另一个方向已经访问过的节点,说明找到了最短路径; -4. 只要其中一个队列为空,说明当前方向的搜索已经进行不下去了,说明起点到终点不连通,无需继续搜索。 - -```python -while q1 and q2: - if len(q1) <= len(q2): - # 优先选择较少元素的队列进行扩展 - extend(m1, m2, q1) - else: - extend(m2, m1, q2) - - -def extend(m1, m2, q): - # 新一轮扩展 - for _ in range(len(q)): - p = q.popleft() - step = m1[p] - for t in next(p): - if t in m1: - # 此前已经访问过 - continue - if t in m2: - # 另一个方向已经搜索过,说明找到了一条最短的连通路径 - return step + 1 + m2[t] - q.append(t) - m1[t] = step + 1 -``` +### 方法一 -### **Python3** - - - ```python class Solution: def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: @@ -133,73 +95,6 @@ class Solution: return -1 ``` -```python -class Solution: - def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: - def next(x): - res = [] - for num in nums: - res.append(x + num) - res.append(x - num) - res.append(x ^ num) - return res - - q = deque([start]) - vis = {start} - ans = 0 - while q: - ans += 1 - for _ in range(len(q)): - x = q.popleft() - for y in next(x): - if y == goal: - return ans - if 0 <= y <= 1000 and y not in vis: - vis.add(y) - q.append(y) - return -1 -``` - -双向 BFS: - -```python -class Solution: - def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: - def next(x): - res = [] - for num in nums: - res.append(x + num) - res.append(x - num) - res.append(x ^ num) - return res - - def extend(m1, m2, q): - for _ in range(len(q)): - x = q.popleft() - step = m1[x] - for y in next(x): - if y in m1: - continue - if y in m2: - return step + 1 + m2[y] - if 0 <= y <= 1000: - m1[y] = step + 1 - q.append(y) - return -1 - - m1, m2 = {start: 0}, {goal: 0} - q1, q2 = deque([start]), deque([goal]) - while q1 and q2: - t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) - if t != -1: - return t - return -1 -``` - -### **Java** - - - ```java class Solution { public int minimumOperations(int[] nums, int start, int goal) { @@ -231,6 +126,143 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minimumOperations(vector& nums, int start, int goal) { + using pii = pair; + vector> ops{ + [](int x, int y) { return x + y; }, + [](int x, int y) { return x - y; }, + [](int x, int y) { return x ^ y; }, + }; + vector vis(1001, false); + queue q; + q.push({start, 0}); + while (!q.empty()) { + auto [x, step] = q.front(); + q.pop(); + for (int num : nums) { + for (auto op : ops) { + int nx = op(x, num); + if (nx == goal) { + return step + 1; + } + if (nx >= 0 && nx <= 1000 && !vis[nx]) { + q.push({nx, step + 1}); + vis[nx] = true; + } + } + } + } + return -1; + } +}; +``` + +```go +func minimumOperations(nums []int, start int, goal int) int { + type pair struct { + x int + step int + } + + ops := []func(int, int) int{ + func(x, y int) int { return x + y }, + func(x, y int) int { return x - y }, + func(x, y int) int { return x ^ y }, + } + vis := make([]bool, 1001) + q := []pair{{start, 0}} + + for len(q) > 0 { + x, step := q[0].x, q[0].step + q = q[1:] + for _, num := range nums { + for _, op := range ops { + nx := op(x, num) + if nx == goal { + return step + 1 + } + if nx >= 0 && nx <= 1000 && !vis[nx] { + q = append(q, pair{nx, step + 1}) + vis[nx] = true + } + } + } + } + return -1 +} +``` + +```ts +function minimumOperations(nums: number[], start: number, goal: number): number { + const n = nums.length; + const op1 = function (x: number, y: number): number { + return x + y; + }; + const op2 = function (x: number, y: number): number { + return x - y; + }; + const op3 = function (x: number, y: number): number { + return x ^ y; + }; + const ops = [op1, op2, op3]; + let vis = new Array(1001).fill(false); + let quenue: Array> = [[start, 0]]; + vis[start] = true; + while (quenue.length) { + let [x, step] = quenue.shift(); + for (let i = 0; i < n; i++) { + for (let j = 0; j < ops.length; j++) { + const nx = ops[j](x, nums[i]); + if (nx == goal) { + return step + 1; + } + if (nx >= 0 && nx <= 1000 && !vis[nx]) { + vis[nx] = true; + quenue.push([nx, step + 1]); + } + } + } + } + return -1; +} +``` + + + +### 方法二 + + + +```python +class Solution: + def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: + def next(x): + res = [] + for num in nums: + res.append(x + num) + res.append(x - num) + res.append(x ^ num) + return res + + q = deque([start]) + vis = {start} + ans = 0 + while q: + ans += 1 + for _ in range(len(q)): + x = q.popleft() + for y in next(x): + if y == goal: + return ans + if 0 <= y <= 1000 and y not in vis: + vis.add(y) + q.append(y) + return -1 +``` + ```java class Solution { public int minimumOperations(int[] nums, int start, int goal) { @@ -268,7 +300,113 @@ class Solution { } ``` -双向 BFS: +```cpp +class Solution { +public: + int minimumOperations(vector& nums, int start, int goal) { + queue q{{start}}; + vector vis(1001); + int ans = 0; + while (!q.empty()) { + ++ans; + for (int n = q.size(); n > 0; --n) { + int x = q.front(); + q.pop(); + for (int y : next(nums, x)) { + if (y == goal) return ans; + if (y >= 0 && y <= 1000 && !vis[y]) { + vis[y] = true; + q.push(y); + } + } + } + } + return -1; + } + + vector next(vector& nums, int x) { + vector res; + for (int num : nums) { + res.push_back(x + num); + res.push_back(x - num); + res.push_back(x ^ num); + } + return res; + } +}; +``` + +```go +func minimumOperations(nums []int, start int, goal int) int { + next := func(x int) []int { + var res []int + for _, num := range nums { + res = append(res, []int{x + num, x - num, x ^ num}...) + } + return res + } + q := []int{start} + vis := make([]bool, 1001) + ans := 0 + for len(q) > 0 { + ans++ + for n := len(q); n > 0; n-- { + x := q[0] + q = q[1:] + for _, y := range next(x) { + if y == goal { + return ans + } + if y >= 0 && y <= 1000 && !vis[y] { + vis[y] = true + q = append(q, y) + } + } + } + } + return -1 +} +``` + + + +### 方法三 + + + +```python +class Solution: + def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: + def next(x): + res = [] + for num in nums: + res.append(x + num) + res.append(x - num) + res.append(x ^ num) + return res + + def extend(m1, m2, q): + for _ in range(len(q)): + x = q.popleft() + step = m1[x] + for y in next(x): + if y in m1: + continue + if y in m2: + return step + 1 + m2[y] + if 0 <= y <= 1000: + m1[y] = step + 1 + q.append(y) + return -1 + + m1, m2 = {start: 0}, {goal: 0} + q1, q2 = deque([start]), deque([goal]) + while q1 and q2: + t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) + if t != -1: + return t + return -1 +``` ```java class Solution { @@ -325,80 +463,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minimumOperations(vector& nums, int start, int goal) { - using pii = pair; - vector> ops{ - [](int x, int y) { return x + y; }, - [](int x, int y) { return x - y; }, - [](int x, int y) { return x ^ y; }, - }; - vector vis(1001, false); - queue q; - q.push({start, 0}); - while (!q.empty()) { - auto [x, step] = q.front(); - q.pop(); - for (int num : nums) { - for (auto op : ops) { - int nx = op(x, num); - if (nx == goal) { - return step + 1; - } - if (nx >= 0 && nx <= 1000 && !vis[nx]) { - q.push({nx, step + 1}); - vis[nx] = true; - } - } - } - } - return -1; - } -}; -``` - -```cpp -class Solution { -public: - int minimumOperations(vector& nums, int start, int goal) { - queue q{{start}}; - vector vis(1001); - int ans = 0; - while (!q.empty()) { - ++ans; - for (int n = q.size(); n > 0; --n) { - int x = q.front(); - q.pop(); - for (int y : next(nums, x)) { - if (y == goal) return ans; - if (y >= 0 && y <= 1000 && !vis[y]) { - vis[y] = true; - q.push(y); - } - } - } - } - return -1; - } - - vector next(vector& nums, int x) { - vector res; - for (int num : nums) { - res.push_back(x + num); - res.push_back(x - num); - res.push_back(x ^ num); - } - return res; - } -}; -``` - -双向 BFS: - ```cpp class Solution { public: @@ -445,77 +509,6 @@ public: }; ``` -### **Go** - -```go -func minimumOperations(nums []int, start int, goal int) int { - type pair struct { - x int - step int - } - - ops := []func(int, int) int{ - func(x, y int) int { return x + y }, - func(x, y int) int { return x - y }, - func(x, y int) int { return x ^ y }, - } - vis := make([]bool, 1001) - q := []pair{{start, 0}} - - for len(q) > 0 { - x, step := q[0].x, q[0].step - q = q[1:] - for _, num := range nums { - for _, op := range ops { - nx := op(x, num) - if nx == goal { - return step + 1 - } - if nx >= 0 && nx <= 1000 && !vis[nx] { - q = append(q, pair{nx, step + 1}) - vis[nx] = true - } - } - } - } - return -1 -} -``` - -```go -func minimumOperations(nums []int, start int, goal int) int { - next := func(x int) []int { - var res []int - for _, num := range nums { - res = append(res, []int{x + num, x - num, x ^ num}...) - } - return res - } - q := []int{start} - vis := make([]bool, 1001) - ans := 0 - for len(q) > 0 { - ans++ - for n := len(q); n > 0; n-- { - x := q[0] - q = q[1:] - for _, y := range next(x) { - if y == goal { - return ans - } - if y >= 0 && y <= 1000 && !vis[y] { - vis[y] = true - q = append(q, y) - } - } - } - } - return -1 -} -``` - -双向 BFS: - ```go func minimumOperations(nums []int, start int, goal int) int { next := func(x int) []int { @@ -561,47 +554,6 @@ func minimumOperations(nums []int, start int, goal int) int { } ``` -### **TypeScript** - -```ts -function minimumOperations(nums: number[], start: number, goal: number): number { - const n = nums.length; - const op1 = function (x: number, y: number): number { - return x + y; - }; - const op2 = function (x: number, y: number): number { - return x - y; - }; - const op3 = function (x: number, y: number): number { - return x ^ y; - }; - const ops = [op1, op2, op3]; - let vis = new Array(1001).fill(false); - let quenue: Array> = [[start, 0]]; - vis[start] = true; - while (quenue.length) { - let [x, step] = quenue.shift(); - for (let i = 0; i < n; i++) { - for (let j = 0; j < ops.length; j++) { - const nx = ops[j](x, nums[i]); - if (nx == goal) { - return step + 1; - } - if (nx >= 0 && nx <= 1000 && !vis[nx]) { - vis[nx] = true; - quenue.push([nx, step + 1]); - } - } - } - } - return -1; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2059.Minimum Operations to Convert Number/README_EN.md b/solution/2000-2099/2059.Minimum Operations to Convert Number/README_EN.md index ed7422fa2380e..4160edb4fd880 100644 --- a/solution/2000-2099/2059.Minimum Operations to Convert Number/README_EN.md +++ b/solution/2000-2099/2059.Minimum Operations to Convert Number/README_EN.md @@ -61,12 +61,10 @@ Note that the last operation sets x out of the range 0 <= x <= 1000, which ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: @@ -89,71 +87,6 @@ class Solution: return -1 ``` -```python -class Solution: - def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: - def next(x): - res = [] - for num in nums: - res.append(x + num) - res.append(x - num) - res.append(x ^ num) - return res - - q = deque([start]) - vis = {start} - ans = 0 - while q: - ans += 1 - for _ in range(len(q)): - x = q.popleft() - for y in next(x): - if y == goal: - return ans - if 0 <= y <= 1000 and y not in vis: - vis.add(y) - q.append(y) - return -1 -``` - -Two-end BFS: - -```python -class Solution: - def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: - def next(x): - res = [] - for num in nums: - res.append(x + num) - res.append(x - num) - res.append(x ^ num) - return res - - def extend(m1, m2, q): - for _ in range(len(q)): - x = q.popleft() - step = m1[x] - for y in next(x): - if y in m1: - continue - if y in m2: - return step + 1 + m2[y] - if 0 <= y <= 1000: - m1[y] = step + 1 - q.append(y) - return -1 - - m1, m2 = {start: 0}, {goal: 0} - q1, q2 = deque([start]), deque([goal]) - while q1 and q2: - t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) - if t != -1: - return t - return -1 -``` - -### **Java** - ```java class Solution { public int minimumOperations(int[] nums, int start, int goal) { @@ -185,6 +118,143 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minimumOperations(vector& nums, int start, int goal) { + using pii = pair; + vector> ops{ + [](int x, int y) { return x + y; }, + [](int x, int y) { return x - y; }, + [](int x, int y) { return x ^ y; }, + }; + vector vis(1001, false); + queue q; + q.push({start, 0}); + while (!q.empty()) { + auto [x, step] = q.front(); + q.pop(); + for (int num : nums) { + for (auto op : ops) { + int nx = op(x, num); + if (nx == goal) { + return step + 1; + } + if (nx >= 0 && nx <= 1000 && !vis[nx]) { + q.push({nx, step + 1}); + vis[nx] = true; + } + } + } + } + return -1; + } +}; +``` + +```go +func minimumOperations(nums []int, start int, goal int) int { + type pair struct { + x int + step int + } + + ops := []func(int, int) int{ + func(x, y int) int { return x + y }, + func(x, y int) int { return x - y }, + func(x, y int) int { return x ^ y }, + } + vis := make([]bool, 1001) + q := []pair{{start, 0}} + + for len(q) > 0 { + x, step := q[0].x, q[0].step + q = q[1:] + for _, num := range nums { + for _, op := range ops { + nx := op(x, num) + if nx == goal { + return step + 1 + } + if nx >= 0 && nx <= 1000 && !vis[nx] { + q = append(q, pair{nx, step + 1}) + vis[nx] = true + } + } + } + } + return -1 +} +``` + +```ts +function minimumOperations(nums: number[], start: number, goal: number): number { + const n = nums.length; + const op1 = function (x: number, y: number): number { + return x + y; + }; + const op2 = function (x: number, y: number): number { + return x - y; + }; + const op3 = function (x: number, y: number): number { + return x ^ y; + }; + const ops = [op1, op2, op3]; + let vis = new Array(1001).fill(false); + let quenue: Array> = [[start, 0]]; + vis[start] = true; + while (quenue.length) { + let [x, step] = quenue.shift(); + for (let i = 0; i < n; i++) { + for (let j = 0; j < ops.length; j++) { + const nx = ops[j](x, nums[i]); + if (nx == goal) { + return step + 1; + } + if (nx >= 0 && nx <= 1000 && !vis[nx]) { + vis[nx] = true; + quenue.push([nx, step + 1]); + } + } + } + } + return -1; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: + def next(x): + res = [] + for num in nums: + res.append(x + num) + res.append(x - num) + res.append(x ^ num) + return res + + q = deque([start]) + vis = {start} + ans = 0 + while q: + ans += 1 + for _ in range(len(q)): + x = q.popleft() + for y in next(x): + if y == goal: + return ans + if 0 <= y <= 1000 and y not in vis: + vis.add(y) + q.append(y) + return -1 +``` + ```java class Solution { public int minimumOperations(int[] nums, int start, int goal) { @@ -222,7 +292,113 @@ class Solution { } ``` -Two-end BFS: +```cpp +class Solution { +public: + int minimumOperations(vector& nums, int start, int goal) { + queue q{{start}}; + vector vis(1001); + int ans = 0; + while (!q.empty()) { + ++ans; + for (int n = q.size(); n > 0; --n) { + int x = q.front(); + q.pop(); + for (int y : next(nums, x)) { + if (y == goal) return ans; + if (y >= 0 && y <= 1000 && !vis[y]) { + vis[y] = true; + q.push(y); + } + } + } + } + return -1; + } + + vector next(vector& nums, int x) { + vector res; + for (int num : nums) { + res.push_back(x + num); + res.push_back(x - num); + res.push_back(x ^ num); + } + return res; + } +}; +``` + +```go +func minimumOperations(nums []int, start int, goal int) int { + next := func(x int) []int { + var res []int + for _, num := range nums { + res = append(res, []int{x + num, x - num, x ^ num}...) + } + return res + } + q := []int{start} + vis := make([]bool, 1001) + ans := 0 + for len(q) > 0 { + ans++ + for n := len(q); n > 0; n-- { + x := q[0] + q = q[1:] + for _, y := range next(x) { + if y == goal { + return ans + } + if y >= 0 && y <= 1000 && !vis[y] { + vis[y] = true + q = append(q, y) + } + } + } + } + return -1 +} +``` + + + +### Solution 3 + + + +```python +class Solution: + def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: + def next(x): + res = [] + for num in nums: + res.append(x + num) + res.append(x - num) + res.append(x ^ num) + return res + + def extend(m1, m2, q): + for _ in range(len(q)): + x = q.popleft() + step = m1[x] + for y in next(x): + if y in m1: + continue + if y in m2: + return step + 1 + m2[y] + if 0 <= y <= 1000: + m1[y] = step + 1 + q.append(y) + return -1 + + m1, m2 = {start: 0}, {goal: 0} + q1, q2 = deque([start]), deque([goal]) + while q1 and q2: + t = extend(m1, m2, q1) if len(q1) <= len(q2) else extend(m2, m1, q2) + if t != -1: + return t + return -1 +``` ```java class Solution { @@ -279,80 +455,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minimumOperations(vector& nums, int start, int goal) { - using pii = pair; - vector> ops{ - [](int x, int y) { return x + y; }, - [](int x, int y) { return x - y; }, - [](int x, int y) { return x ^ y; }, - }; - vector vis(1001, false); - queue q; - q.push({start, 0}); - while (!q.empty()) { - auto [x, step] = q.front(); - q.pop(); - for (int num : nums) { - for (auto op : ops) { - int nx = op(x, num); - if (nx == goal) { - return step + 1; - } - if (nx >= 0 && nx <= 1000 && !vis[nx]) { - q.push({nx, step + 1}); - vis[nx] = true; - } - } - } - } - return -1; - } -}; -``` - -```cpp -class Solution { -public: - int minimumOperations(vector& nums, int start, int goal) { - queue q{{start}}; - vector vis(1001); - int ans = 0; - while (!q.empty()) { - ++ans; - for (int n = q.size(); n > 0; --n) { - int x = q.front(); - q.pop(); - for (int y : next(nums, x)) { - if (y == goal) return ans; - if (y >= 0 && y <= 1000 && !vis[y]) { - vis[y] = true; - q.push(y); - } - } - } - } - return -1; - } - - vector next(vector& nums, int x) { - vector res; - for (int num : nums) { - res.push_back(x + num); - res.push_back(x - num); - res.push_back(x ^ num); - } - return res; - } -}; -``` - -Two-end BFS: - ```cpp class Solution { public: @@ -399,77 +501,6 @@ public: }; ``` -### **Go** - -```go -func minimumOperations(nums []int, start int, goal int) int { - type pair struct { - x int - step int - } - - ops := []func(int, int) int{ - func(x, y int) int { return x + y }, - func(x, y int) int { return x - y }, - func(x, y int) int { return x ^ y }, - } - vis := make([]bool, 1001) - q := []pair{{start, 0}} - - for len(q) > 0 { - x, step := q[0].x, q[0].step - q = q[1:] - for _, num := range nums { - for _, op := range ops { - nx := op(x, num) - if nx == goal { - return step + 1 - } - if nx >= 0 && nx <= 1000 && !vis[nx] { - q = append(q, pair{nx, step + 1}) - vis[nx] = true - } - } - } - } - return -1 -} -``` - -```go -func minimumOperations(nums []int, start int, goal int) int { - next := func(x int) []int { - var res []int - for _, num := range nums { - res = append(res, []int{x + num, x - num, x ^ num}...) - } - return res - } - q := []int{start} - vis := make([]bool, 1001) - ans := 0 - for len(q) > 0 { - ans++ - for n := len(q); n > 0; n-- { - x := q[0] - q = q[1:] - for _, y := range next(x) { - if y == goal { - return ans - } - if y >= 0 && y <= 1000 && !vis[y] { - vis[y] = true - q = append(q, y) - } - } - } - } - return -1 -} -``` - -Two-end BFS: - ```go func minimumOperations(nums []int, start int, goal int) int { next := func(x int) []int { @@ -515,47 +546,6 @@ func minimumOperations(nums []int, start int, goal int) int { } ``` -### **TypeScript** - -```ts -function minimumOperations(nums: number[], start: number, goal: number): number { - const n = nums.length; - const op1 = function (x: number, y: number): number { - return x + y; - }; - const op2 = function (x: number, y: number): number { - return x - y; - }; - const op3 = function (x: number, y: number): number { - return x ^ y; - }; - const ops = [op1, op2, op3]; - let vis = new Array(1001).fill(false); - let quenue: Array> = [[start, 0]]; - vis[start] = true; - while (quenue.length) { - let [x, step] = quenue.shift(); - for (let i = 0; i < n; i++) { - for (let j = 0; j < ops.length; j++) { - const nx = ops[j](x, nums[i]); - if (nx == goal) { - return step + 1; - } - if (nx >= 0 && nx <= 1000 && !vis[nx]) { - vis[nx] = true; - quenue.push([nx, step + 1]); - } - } - } - } - return -1; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2060.Check if an Original String Exists Given Two Encoded Strings/README.md b/solution/2000-2099/2060.Check if an Original String Exists Given Two Encoded Strings/README.md index 5d34dbe33142d..2f4de1d43ba16 100644 --- a/solution/2000-2099/2060.Check if an Original String Exists Given Two Encoded Strings/README.md +++ b/solution/2000-2099/2060.Check if an Original String Exists Given Two Encoded Strings/README.md @@ -103,30 +103,10 @@ ## 解法 - - -动态规划 +### 方法一 -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **TypeScript** - ```ts function possiblyEquals(s1: string, s2: string): boolean { const n = s1.length, @@ -190,10 +170,6 @@ function isDigit(char: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2060.Check if an Original String Exists Given Two Encoded Strings/README_EN.md b/solution/2000-2099/2060.Check if an Original String Exists Given Two Encoded Strings/README_EN.md index fca4f69d8a9ab..bc0e8c0b58144 100644 --- a/solution/2000-2099/2060.Check if an Original String Exists Given Two Encoded Strings/README_EN.md +++ b/solution/2000-2099/2060.Check if an Original String Exists Given Two Encoded Strings/README_EN.md @@ -78,24 +78,10 @@ ## Solutions -Dynamic Programming +### Solution 1 -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **TypeScript** - ```ts function possiblyEquals(s1: string, s2: string): boolean { const n = s1.length, @@ -159,10 +145,6 @@ function isDigit(char: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/README.md b/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/README.md index b82855a03be8d..b5f53349c1652 100644 --- a/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/README.md +++ b/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:DFS 模拟** +### 方法一:DFS 模拟 我们从起点 $(0, 0)$ 开始模拟机器人的清扫过程,每次清扫当前位置,然后向前走一步,如果碰到墙壁或者已经清扫过的位置,就顺时针旋转 90 度,然后继续清扫。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def numberOfCleanRooms(self, room: List[List[int]]) -> int: @@ -98,29 +92,6 @@ class Solution: return ans ``` -```python -class Solution: - def numberOfCleanRooms(self, room: List[List[int]]) -> int: - dirs = (0, 1, 0, -1, 0) - i = j = k = 0 - ans = 0 - vis = set() - while (i, j, k) not in vis: - vis.add((i, j, k)) - ans += room[i][j] == 0 - room[i][j] = -1 - x, y = i + dirs[k], j + dirs[k + 1] - if 0 <= x < len(room) and 0 <= y < len(room[0]) and room[x][y] != 1: - i, j = x, y - else: - k = (k + 1) % 4 - return ans -``` - -### **Java** - - - ```java class Solution { private boolean[][][] vis; @@ -152,33 +123,6 @@ class Solution { } ``` -```java -class Solution { - public int numberOfCleanRooms(int[][] room) { - int[] dirs = {0, 1, 0, -1, 0}; - int i = 0, j = 0, k = 0; - int m = room.length, n = room[0].length; - boolean[][][] vis = new boolean[m][n][4]; - int ans = 0; - while (!vis[i][j][k]) { - vis[i][j][k] = true; - ans += room[i][j] == 0 ? 1 : 0; - room[i][j] = -1; - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && room[x][y] != 1) { - i = x; - j = y; - } else { - k = (k + 1) % 4; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -208,35 +152,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numberOfCleanRooms(vector>& room) { - int dirs[5] = {0, 1, 0, -1, 0}; - int i = 0, j = 0, k = 0; - int m = room.size(), n = room[0].size(); - bool vis[m][n][4]; - memset(vis, false, sizeof(vis)); - int ans = 0; - while (!vis[i][j][k]) { - vis[i][j][k] = true; - ans += room[i][j] == 0 ? 1 : 0; - room[i][j] = -1; - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && room[x][y] != 1) { - i = x; - j = y; - } else { - k = (k + 1) % 4; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func numberOfCleanRooms(room [][]int) (ans int) { m, n := len(room), len(room[0]) @@ -267,6 +182,83 @@ func numberOfCleanRooms(room [][]int) (ans int) { } ``` + + +### 方法二 + + + +```python +class Solution: + def numberOfCleanRooms(self, room: List[List[int]]) -> int: + dirs = (0, 1, 0, -1, 0) + i = j = k = 0 + ans = 0 + vis = set() + while (i, j, k) not in vis: + vis.add((i, j, k)) + ans += room[i][j] == 0 + room[i][j] = -1 + x, y = i + dirs[k], j + dirs[k + 1] + if 0 <= x < len(room) and 0 <= y < len(room[0]) and room[x][y] != 1: + i, j = x, y + else: + k = (k + 1) % 4 + return ans +``` + +```java +class Solution { + public int numberOfCleanRooms(int[][] room) { + int[] dirs = {0, 1, 0, -1, 0}; + int i = 0, j = 0, k = 0; + int m = room.length, n = room[0].length; + boolean[][][] vis = new boolean[m][n][4]; + int ans = 0; + while (!vis[i][j][k]) { + vis[i][j][k] = true; + ans += room[i][j] == 0 ? 1 : 0; + room[i][j] = -1; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && room[x][y] != 1) { + i = x; + j = y; + } else { + k = (k + 1) % 4; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int numberOfCleanRooms(vector>& room) { + int dirs[5] = {0, 1, 0, -1, 0}; + int i = 0, j = 0, k = 0; + int m = room.size(), n = room[0].size(); + bool vis[m][n][4]; + memset(vis, false, sizeof(vis)); + int ans = 0; + while (!vis[i][j][k]) { + vis[i][j][k] = true; + ans += room[i][j] == 0 ? 1 : 0; + room[i][j] = -1; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && room[x][y] != 1) { + i = x; + j = y; + } else { + k = (k + 1) % 4; + } + } + return ans; + } +}; +``` + ```go func numberOfCleanRooms(room [][]int) (ans int) { m, n := len(room), len(room[0]) @@ -293,10 +285,6 @@ func numberOfCleanRooms(room [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/README_EN.md b/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/README_EN.md index 0674f6941554e..a5b137c84aee7 100644 --- a/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/README_EN.md +++ b/solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/README_EN.md @@ -55,9 +55,9 @@ The robot has cleaned 1 space, so return 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,27 +82,6 @@ class Solution: return ans ``` -```python -class Solution: - def numberOfCleanRooms(self, room: List[List[int]]) -> int: - dirs = (0, 1, 0, -1, 0) - i = j = k = 0 - ans = 0 - vis = set() - while (i, j, k) not in vis: - vis.add((i, j, k)) - ans += room[i][j] == 0 - room[i][j] = -1 - x, y = i + dirs[k], j + dirs[k + 1] - if 0 <= x < len(room) and 0 <= y < len(room[0]) and room[x][y] != 1: - i, j = x, y - else: - k = (k + 1) % 4 - return ans -``` - -### **Java** - ```java class Solution { private boolean[][][] vis; @@ -134,33 +113,6 @@ class Solution { } ``` -```java -class Solution { - public int numberOfCleanRooms(int[][] room) { - int[] dirs = {0, 1, 0, -1, 0}; - int i = 0, j = 0, k = 0; - int m = room.length, n = room[0].length; - boolean[][][] vis = new boolean[m][n][4]; - int ans = 0; - while (!vis[i][j][k]) { - vis[i][j][k] = true; - ans += room[i][j] == 0 ? 1 : 0; - room[i][j] = -1; - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && room[x][y] != 1) { - i = x; - j = y; - } else { - k = (k + 1) % 4; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -190,35 +142,6 @@ public: }; ``` -```cpp -class Solution { -public: - int numberOfCleanRooms(vector>& room) { - int dirs[5] = {0, 1, 0, -1, 0}; - int i = 0, j = 0, k = 0; - int m = room.size(), n = room[0].size(); - bool vis[m][n][4]; - memset(vis, false, sizeof(vis)); - int ans = 0; - while (!vis[i][j][k]) { - vis[i][j][k] = true; - ans += room[i][j] == 0 ? 1 : 0; - room[i][j] = -1; - int x = i + dirs[k], y = j + dirs[k + 1]; - if (x >= 0 && x < m && y >= 0 && y < n && room[x][y] != 1) { - i = x; - j = y; - } else { - k = (k + 1) % 4; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func numberOfCleanRooms(room [][]int) (ans int) { m, n := len(room), len(room[0]) @@ -249,6 +172,83 @@ func numberOfCleanRooms(room [][]int) (ans int) { } ``` + + +### Solution 2 + + + +```python +class Solution: + def numberOfCleanRooms(self, room: List[List[int]]) -> int: + dirs = (0, 1, 0, -1, 0) + i = j = k = 0 + ans = 0 + vis = set() + while (i, j, k) not in vis: + vis.add((i, j, k)) + ans += room[i][j] == 0 + room[i][j] = -1 + x, y = i + dirs[k], j + dirs[k + 1] + if 0 <= x < len(room) and 0 <= y < len(room[0]) and room[x][y] != 1: + i, j = x, y + else: + k = (k + 1) % 4 + return ans +``` + +```java +class Solution { + public int numberOfCleanRooms(int[][] room) { + int[] dirs = {0, 1, 0, -1, 0}; + int i = 0, j = 0, k = 0; + int m = room.length, n = room[0].length; + boolean[][][] vis = new boolean[m][n][4]; + int ans = 0; + while (!vis[i][j][k]) { + vis[i][j][k] = true; + ans += room[i][j] == 0 ? 1 : 0; + room[i][j] = -1; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && room[x][y] != 1) { + i = x; + j = y; + } else { + k = (k + 1) % 4; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int numberOfCleanRooms(vector>& room) { + int dirs[5] = {0, 1, 0, -1, 0}; + int i = 0, j = 0, k = 0; + int m = room.size(), n = room[0].size(); + bool vis[m][n][4]; + memset(vis, false, sizeof(vis)); + int ans = 0; + while (!vis[i][j][k]) { + vis[i][j][k] = true; + ans += room[i][j] == 0 ? 1 : 0; + room[i][j] = -1; + int x = i + dirs[k], y = j + dirs[k + 1]; + if (x >= 0 && x < m && y >= 0 && y < n && room[x][y] != 1) { + i = x; + j = y; + } else { + k = (k + 1) % 4; + } + } + return ans; + } +}; +``` + ```go func numberOfCleanRooms(room [][]int) (ans int) { m, n := len(room), len(room[0]) @@ -275,10 +275,6 @@ func numberOfCleanRooms(room [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2062.Count Vowel Substrings of a String/README.md b/solution/2000-2099/2062.Count Vowel Substrings of a String/README.md index 557a46eeebb71..a35fc6d87e9b5 100644 --- a/solution/2000-2099/2062.Count Vowel Substrings of a String/README.md +++ b/solution/2000-2099/2062.Count Vowel Substrings of a String/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:暴力枚举 + 哈希表** +### 方法一:暴力枚举 + 哈希表 我们可以枚举子字符串的左端点 $i$,对于当前左端点,维护一个哈希表,记录当前子字符串中出现的元音字母,然后枚举右端点 $j$,如果当前右端点对应的字母不是元音字母,则跳出循环,否则将当前右端点对应的字母加入哈希表,如果哈希表中的元素个数为 $5$,则说明当前子字符串是一个元音子字符串,将结果加 $1$。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def countVowelSubstrings(self, word: str) -> int: @@ -87,25 +81,6 @@ class Solution: return sum(set(word[i:j]) == s for i in range(n) for j in range(i + 1, n + 1)) ``` -```python -class Solution: - def countVowelSubstrings(self, word: str) -> int: - s = set('aeiou') - ans, n = 0, len(word) - for i in range(n): - t = set() - for c in word[i:]: - if c not in s: - break - t.add(c) - ans += len(t) == 5 - return ans -``` - -### **Java** - - - ```java class Solution { public int countVowelSubstrings(String word) { @@ -133,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +132,6 @@ public: }; ``` -### **Go** - ```go func countVowelSubstrings(word string) int { ans, n := 0, len(word) @@ -181,8 +152,6 @@ func countVowelSubstrings(word string) int { } ``` -### **TypeScript** - ```ts function countVowelSubstrings(word: string): number { let ans = 0; @@ -204,10 +173,27 @@ function countVowelSubstrings(word: string): number { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def countVowelSubstrings(self, word: str) -> int: + s = set('aeiou') + ans, n = 0, len(word) + for i in range(n): + t = set() + for c in word[i:]: + if c not in s: + break + t.add(c) + ans += len(t) == 5 + return ans ``` + + diff --git a/solution/2000-2099/2062.Count Vowel Substrings of a String/README_EN.md b/solution/2000-2099/2062.Count Vowel Substrings of a String/README_EN.md index f2a8258391ac8..483f3242b1e48 100644 --- a/solution/2000-2099/2062.Count Vowel Substrings of a String/README_EN.md +++ b/solution/2000-2099/2062.Count Vowel Substrings of a String/README_EN.md @@ -54,9 +54,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,23 +66,6 @@ class Solution: return sum(set(word[i:j]) == s for i in range(n) for j in range(i + 1, n + 1)) ``` -```python -class Solution: - def countVowelSubstrings(self, word: str) -> int: - s = set('aeiou') - ans, n = 0, len(word) - for i in range(n): - t = set() - for c in word[i:]: - if c not in s: - break - t.add(c) - ans += len(t) == 5 - return ans -``` - -### **Java** - ```java class Solution { public int countVowelSubstrings(String word) { @@ -110,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +117,6 @@ public: }; ``` -### **Go** - ```go func countVowelSubstrings(word string) int { ans, n := 0, len(word) @@ -158,8 +137,6 @@ func countVowelSubstrings(word string) int { } ``` -### **TypeScript** - ```ts function countVowelSubstrings(word: string): number { let ans = 0; @@ -181,10 +158,27 @@ function countVowelSubstrings(word: string): number { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def countVowelSubstrings(self, word: str) -> int: + s = set('aeiou') + ans, n = 0, len(word) + for i in range(n): + t = set() + for c in word[i:]: + if c not in s: + break + t.add(c) + ans += len(t) == 5 + return ans ``` + + diff --git a/solution/2000-2099/2063.Vowels of All Substrings/README.md b/solution/2000-2099/2063.Vowels of All Substrings/README.md index 1953d06f48aa4..ecf60e26231d7 100644 --- a/solution/2000-2099/2063.Vowels of All Substrings/README.md +++ b/solution/2000-2099/2063.Vowels of All Substrings/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:枚举贡献** +### 方法一:枚举贡献 我们可以枚举字符串的每个字符 $word[i]$,如果 $word[i]$ 是元音字母,那么 $word[i]$ 一共在 $(i + 1) \times (n - i)$ 个子字符串中出现,将这些子字符串的个数累加即可。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def countVowels(self, word: str) -> int: @@ -85,10 +79,6 @@ class Solution: return sum((i + 1) * (n - i) for i, c in enumerate(word) if c in 'aeiou') ``` -### **Java** - - - ```java class Solution { public long countVowels(String word) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func countVowels(word string) (ans int64) { for i, c := range word { @@ -135,8 +121,6 @@ func countVowels(word string) (ans int64) { } ``` -### **TypeScript** - ```ts function countVowels(word: string): number { const n = word.length; @@ -150,10 +134,6 @@ function countVowels(word: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2063.Vowels of All Substrings/README_EN.md b/solution/2000-2099/2063.Vowels of All Substrings/README_EN.md index 45d83775c1507..acdd2b6d52fe4 100644 --- a/solution/2000-2099/2063.Vowels of All Substrings/README_EN.md +++ b/solution/2000-2099/2063.Vowels of All Substrings/README_EN.md @@ -54,9 +54,9 @@ Hence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return sum((i + 1) * (n - i) for i, c in enumerate(word) if c in 'aeiou') ``` -### **Java** - ```java class Solution { public long countVowels(String word) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +96,6 @@ public: }; ``` -### **Go** - ```go func countVowels(word string) (ans int64) { for i, c := range word { @@ -113,8 +107,6 @@ func countVowels(word string) (ans int64) { } ``` -### **TypeScript** - ```ts function countVowels(word: string): number { const n = word.length; @@ -128,10 +120,6 @@ function countVowels(word: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2064.Minimized Maximum of Products Distributed to Any Store/README.md b/solution/2000-2099/2064.Minimized Maximum of Products Distributed to Any Store/README.md index d61bc9834acb4..3b96ae6ca4456 100644 --- a/solution/2000-2099/2064.Minimized Maximum of Products Distributed to Any Store/README.md +++ b/solution/2000-2099/2064.Minimized Maximum of Products Distributed to Any Store/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们注意到,如果分配给任意商店商品数目的最大值为 $x$,且满足题目要求,那么 $x+1$ 也一定满足题目要求,这存在着单调性。因此我们可以通过二分查找,找到一个最小的 $x$,使得 $x$ 满足题目要求。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def minimizedMaximum(self, n: int, quantities: List[int]) -> int: @@ -91,10 +85,6 @@ class Solution: return 1 + bisect_left(range(1, 10**6), True, key=check) ``` -### **Java** - - - ```java class Solution { public int minimizedMaximum(int n, int[] quantities) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func minimizedMaximum(n int, quantities []int) int { return 1 + sort.Search(1e5, func(x int) bool { @@ -155,8 +141,6 @@ func minimizedMaximum(n int, quantities []int) int { } ``` -### **TypeScript** - ```ts function minimizedMaximum(n: number, quantities: number[]): number { let left = 1; @@ -177,10 +161,6 @@ function minimizedMaximum(n: number, quantities: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2064.Minimized Maximum of Products Distributed to Any Store/README_EN.md b/solution/2000-2099/2064.Minimized Maximum of Products Distributed to Any Store/README_EN.md index 54bdeaa5022e5..e77bd5c1e6e8d 100644 --- a/solution/2000-2099/2064.Minimized Maximum of Products Distributed to Any Store/README_EN.md +++ b/solution/2000-2099/2064.Minimized Maximum of Products Distributed to Any Store/README_EN.md @@ -60,12 +60,10 @@ The maximum number of products given to any store is max(100000) = 100000. ## Solutions -Binary search. +### Solution 1 -### **Python3** - ```python class Solution: def minimizedMaximum(self, n: int, quantities: List[int]) -> int: @@ -75,8 +73,6 @@ class Solution: return 1 + bisect_left(range(1, 10**6), True, key=check) ``` -### **Java** - ```java class Solution { public int minimizedMaximum(int n, int[] quantities) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func minimizedMaximum(n int, quantities []int) int { return 1 + sort.Search(1e5, func(x int) bool { @@ -137,8 +129,6 @@ func minimizedMaximum(n int, quantities []int) int { } ``` -### **TypeScript** - ```ts function minimizedMaximum(n: number, quantities: number[]): number { let left = 1; @@ -159,10 +149,6 @@ function minimizedMaximum(n: number, quantities: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2065.Maximum Path Quality of a Graph/README.md b/solution/2000-2099/2065.Maximum Path Quality of a Graph/README.md index b342c3c326b23..2ac2536954517 100644 --- a/solution/2000-2099/2065.Maximum Path Quality of a Graph/README.md +++ b/solution/2000-2099/2065.Maximum Path Quality of a Graph/README.md @@ -82,30 +82,10 @@ ## 解法 - - -DFS +### 方法一 -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **TypeScript** - ```ts function maximalPathQuality(values: number[], edges: number[][], maxTime: number): number { const n = values.length; @@ -144,10 +124,6 @@ function maximalPathQuality(values: number[], edges: number[][], maxTime: number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2065.Maximum Path Quality of a Graph/README_EN.md b/solution/2000-2099/2065.Maximum Path Quality of a Graph/README_EN.md index 7812f644787d0..843ea45b3dbfd 100644 --- a/solution/2000-2099/2065.Maximum Path Quality of a Graph/README_EN.md +++ b/solution/2000-2099/2065.Maximum Path Quality of a Graph/README_EN.md @@ -61,21 +61,9 @@ The nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` +### Solution 1 -### **TypeScript** + ```ts function maximalPathQuality(values: number[], edges: number[][], maxTime: number): number { @@ -115,10 +103,6 @@ function maximalPathQuality(values: number[], edges: number[][], maxTime: number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2066.Account Balance/README.md b/solution/2000-2099/2066.Account Balance/README.md index 851e162f22b60..a5e24c9d159bb 100644 --- a/solution/2000-2099/2066.Account Balance/README.md +++ b/solution/2000-2099/2066.Account Balance/README.md @@ -71,14 +71,10 @@ Transactions 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -93,3 +89,5 @@ ORDER BY 1, 2; ``` + + diff --git a/solution/2000-2099/2066.Account Balance/README_EN.md b/solution/2000-2099/2066.Account Balance/README_EN.md index 51d80bd838e72..beead35ac1958 100644 --- a/solution/2000-2099/2066.Account Balance/README_EN.md +++ b/solution/2000-2099/2066.Account Balance/README_EN.md @@ -67,9 +67,9 @@ Account 2: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -85,3 +85,5 @@ ORDER BY 1, 2; ``` + + diff --git a/solution/2000-2099/2067.Number of Equal Count Substrings/README.md b/solution/2000-2099/2067.Number of Equal Count Substrings/README.md index 147de4bdb9b7c..708aaf9bc7fbd 100644 --- a/solution/2000-2099/2067.Number of Equal Count Substrings/README.md +++ b/solution/2000-2099/2067.Number of Equal Count Substrings/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:枚举 + 滑动窗口** +### 方法一:枚举 + 滑动窗口 我们可以在 $[1..26]$ 范围内枚举子串的字母种类数 $x$,那么子串长度就是 $count \times x$。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def equalCountSubstrings(self, s: str, count: int) -> int: @@ -98,10 +92,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int equalCountSubstrings(String s, int count) { @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -174,8 +162,6 @@ public: }; ``` -### **Go** - ```go func equalCountSubstrings(s string, count int) (ans int) { n := len(s) @@ -212,8 +198,6 @@ func equalCountSubstrings(s string, count int) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -246,10 +230,6 @@ var equalCountSubstrings = function (s, count) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2067.Number of Equal Count Substrings/README_EN.md b/solution/2000-2099/2067.Number of Equal Count Substrings/README_EN.md index 8e93a3d576698..105f9a36ac4bb 100644 --- a/solution/2000-2099/2067.Number of Equal Count Substrings/README_EN.md +++ b/solution/2000-2099/2067.Number of Equal Count Substrings/README_EN.md @@ -55,9 +55,9 @@ Therefore, no substrings in s are equal count substrings, so return 0 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int equalCountSubstrings(String s, int count) { @@ -123,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +152,6 @@ public: }; ``` -### **Go** - ```go func equalCountSubstrings(s string, count int) (ans int) { n := len(s) @@ -194,8 +188,6 @@ func equalCountSubstrings(s string, count int) (ans int) { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -228,10 +220,6 @@ var equalCountSubstrings = function (s, count) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/README.md b/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/README.md index 0822e9fe500d0..f05983ac5fa5b 100644 --- a/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/README.md +++ b/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们可以创建一个长度为 $26$ 的数组 $cnt$,记录两个字符串中每个字母出现的次数之差。最后遍历 $cnt$,如果有任意一个字母出现的次数之差大于 $3$,则返回 `false`,否则返回 `true`。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: @@ -81,10 +75,6 @@ class Solution: return all(abs(x) <= 3 for x in cnt.values()) ``` -### **Java** - - - ```java class Solution { public boolean checkAlmostEquivalent(String word1, String word2) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func checkAlmostEquivalent(word1 string, word2 string) bool { cnt := [26]int{} @@ -148,8 +134,6 @@ func checkAlmostEquivalent(word1 string, word2 string) bool { } ``` -### **TypeScript** - ```ts function checkAlmostEquivalent(word1: string, word2: string): boolean { const cnt: number[] = new Array(26).fill(0); @@ -163,7 +147,26 @@ function checkAlmostEquivalent(word1: string, word2: string): boolean { } ``` -### **C#** +```js +/** + * @param {string} word1 + * @param {string} word2 + * @return {boolean} + */ +var checkAlmostEquivalent = function (word1, word2) { + const m = new Map(); + for (let i = 0; i < word1.length; i++) { + m.set(word1[i], (m.get(word1[i]) || 0) + 1); + m.set(word2[i], (m.get(word2[i]) || 0) - 1); + } + for (const v of m.values()) { + if (Math.abs(v) > 3) { + return false; + } + } + return true; +}; +``` ```cs public class Solution { @@ -180,8 +183,6 @@ public class Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -205,33 +206,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {string} word1 - * @param {string} word2 - * @return {boolean} - */ -var checkAlmostEquivalent = function (word1, word2) { - const m = new Map(); - for (let i = 0; i < word1.length; i++) { - m.set(word1[i], (m.get(word1[i]) || 0) + 1); - m.set(word2[i], (m.get(word2[i]) || 0) - 1); - } - for (const v of m.values()) { - if (Math.abs(v) > 3) { - return false; - } - } - return true; -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/README_EN.md b/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/README_EN.md index c707348da417a..223776681cf75 100644 --- a/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/README_EN.md +++ b/solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/README_EN.md @@ -57,7 +57,7 @@ The difference is 4, which is more than the allowed 3. ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We can create an array $cnt$ of length $26$ to record the difference in the number of times each letter appears in the two strings. Then we traverse $cnt$, if any letter appears the difference in the number of times greater than $3$, then return `false`, otherwise return `true`. @@ -65,8 +65,6 @@ The time complexity is $O(n)$ and the space complexity is $O(C)$. Where $n$ is t -### **Python3** - ```python class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: @@ -76,8 +74,6 @@ class Solution: return all(abs(x) <= 3 for x in cnt.values()) ``` -### **Java** - ```java class Solution { public boolean checkAlmostEquivalent(String word1, String word2) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +115,6 @@ public: }; ``` -### **Go** - ```go func checkAlmostEquivalent(word1 string, word2 string) bool { cnt := [26]int{} @@ -141,8 +133,6 @@ func checkAlmostEquivalent(word1 string, word2 string) bool { } ``` -### **TypeScript** - ```ts function checkAlmostEquivalent(word1: string, word2: string): boolean { const cnt: number[] = new Array(26).fill(0); @@ -156,7 +146,26 @@ function checkAlmostEquivalent(word1: string, word2: string): boolean { } ``` -### **C#** +```js +/** + * @param {string} word1 + * @param {string} word2 + * @return {boolean} + */ +var checkAlmostEquivalent = function (word1, word2) { + const m = new Map(); + for (let i = 0; i < word1.length; i++) { + m.set(word1[i], (m.get(word1[i]) || 0) + 1); + m.set(word2[i], (m.get(word2[i]) || 0) - 1); + } + for (const v of m.values()) { + if (Math.abs(v) > 3) { + return false; + } + } + return true; +}; +``` ```cs public class Solution { @@ -173,8 +182,6 @@ public class Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -198,33 +205,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {string} word1 - * @param {string} word2 - * @return {boolean} - */ -var checkAlmostEquivalent = function (word1, word2) { - const m = new Map(); - for (let i = 0; i < word1.length; i++) { - m.set(word1[i], (m.get(word1[i]) || 0) + 1); - m.set(word2[i], (m.get(word2[i]) || 0) - 1); - } - for (const v of m.values()) { - if (Math.abs(v) > 3) { - return false; - } - } - return true; -}; -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2069.Walking Robot Simulation II/README.md b/solution/2000-2099/2069.Walking Robot Simulation II/README.md index 809d7f3eaf058..0bd1482eaaac7 100644 --- a/solution/2000-2099/2069.Walking Robot Simulation II/README.md +++ b/solution/2000-2099/2069.Walking Robot Simulation II/README.md @@ -68,30 +68,4 @@ robot.getDir(); // 返回 "West" ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2000-2099/2069.Walking Robot Simulation II/README_EN.md b/solution/2000-2099/2069.Walking Robot Simulation II/README_EN.md index 62122c35cab4e..fdc319884bf52 100644 --- a/solution/2000-2099/2069.Walking Robot Simulation II/README_EN.md +++ b/solution/2000-2099/2069.Walking Robot Simulation II/README_EN.md @@ -62,24 +62,4 @@ robot.getDir(); // return "West" ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2000-2099/2070.Most Beautiful Item for Each Query/README.md b/solution/2000-2099/2070.Most Beautiful Item for Each Query/README.md index 2ef79a1fd719f..262e7e105d211 100644 --- a/solution/2000-2099/2070.Most Beautiful Item for Each Query/README.md +++ b/solution/2000-2099/2070.Most Beautiful Item for Each Query/README.md @@ -58,16 +58,10 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 -### **Python3** - - - ```python class Solution: def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] maximumBeauty(int[][] items, int[] queries) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func maximumBeauty(items [][]int, queries []int) []int { sort.Slice(items, func(i, j int) bool { @@ -172,10 +158,6 @@ func maximumBeauty(items [][]int, queries []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2070.Most Beautiful Item for Each Query/README_EN.md b/solution/2000-2099/2070.Most Beautiful Item for Each Query/README_EN.md index c6263e8e8534b..a19818043fd85 100644 --- a/solution/2000-2099/2070.Most Beautiful Item for Each Query/README_EN.md +++ b/solution/2000-2099/2070.Most Beautiful Item for Each Query/README_EN.md @@ -57,9 +57,9 @@ Hence, the answer to the query is 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] maximumBeauty(int[][] items, int[] queries) { @@ -107,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +129,6 @@ public: }; ``` -### **Go** - ```go func maximumBeauty(items [][]int, queries []int) []int { sort.Slice(items, func(i, j int) bool { @@ -163,10 +157,6 @@ func maximumBeauty(items [][]int, queries []int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README.md b/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README.md index 75b516205acf9..9c1e64f9f2f8a 100644 --- a/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README.md +++ b/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README.md @@ -73,9 +73,7 @@ ## 解法 - - -**方法一:贪心 + 二分查找** +### 方法一:贪心 + 二分查找 将任务按照完成时间从小到大排序,将工人按照能力从小到大排序。 @@ -93,10 +91,6 @@ -### **Python3** - - - ```python class Solution: def maxTaskAssign( @@ -134,10 +128,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { private int[] tasks; @@ -193,8 +183,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -238,8 +226,6 @@ public: }; ``` -### **Go** - ```go func maxTaskAssign(tasks []int, workers []int, pills int, strength int) int { sort.Ints(tasks) @@ -281,10 +267,6 @@ func maxTaskAssign(tasks []int, workers []int, pills int, strength int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README_EN.md b/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README_EN.md index e9a3ba24973f8..5567216b3e548 100644 --- a/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README_EN.md +++ b/solution/2000-2099/2071.Maximum Number of Tasks You Can Assign/README_EN.md @@ -61,9 +61,9 @@ The last pill is not given because it will not make any worker strong enough for ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -102,8 +102,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { private int[] tasks; @@ -159,8 +157,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -204,8 +200,6 @@ public: }; ``` -### **Go** - ```go func maxTaskAssign(tasks []int, workers []int, pills int, strength int) int { sort.Ints(tasks) @@ -247,10 +241,6 @@ func maxTaskAssign(tasks []int, workers []int, pills int, strength int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2072.The Winner University/README.md b/solution/2000-2099/2072.The Winner University/README.md index a9c5f0da8c801..8edfeb342e2a9 100644 --- a/solution/2000-2099/2072.The Winner University/README.md +++ b/solution/2000-2099/2072.The Winner University/README.md @@ -138,14 +138,10 @@ California 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -160,3 +156,5 @@ FROM ``` + + diff --git a/solution/2000-2099/2072.The Winner University/README_EN.md b/solution/2000-2099/2072.The Winner University/README_EN.md index 6ed98376784cf..f640ad1caad0c 100644 --- a/solution/2000-2099/2072.The Winner University/README_EN.md +++ b/solution/2000-2099/2072.The Winner University/README_EN.md @@ -135,9 +135,9 @@ Both New York University and California University have 1 excellent student. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -153,3 +153,5 @@ FROM ``` + + diff --git a/solution/2000-2099/2073.Time Needed to Buy Tickets/README.md b/solution/2000-2099/2073.Time Needed to Buy Tickets/README.md index 09c04b322af10..1b183f10a2459 100644 --- a/solution/2000-2099/2073.Time Needed to Buy Tickets/README.md +++ b/solution/2000-2099/2073.Time Needed to Buy Tickets/README.md @@ -49,16 +49,10 @@ ## 解法 - - -第 k 个人买完之前,排在 k 后面的人最多能买 `tickets[k] - 1` 次,排在 k 前面的人最多能买 `tickets[k]` 次 +### 方法一 -### **Python3** - - - ```python class Solution: def timeRequiredToBuy(self, tickets: List[int], k: int) -> int: @@ -71,10 +65,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int timeRequiredToBuy(int[] tickets, int k) { @@ -91,36 +81,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function timeRequiredToBuy(tickets: number[], k: number): number { - const n = tickets.length; - let target = tickets[k] - 1; - let ans = 0; - // round1 - for (let i = 0; i < n; i++) { - let num = tickets[i]; - if (num <= target) { - ans += num; - tickets[i] = 0; - } else { - ans += target; - tickets[i] -= target; - } - } - - // round2 - for (let i = 0; i <= k; i++) { - let num = tickets[i]; - ans += num > 0 ? 1 : 0; - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -138,8 +98,6 @@ public: }; ``` -### **Go** - ```go func timeRequiredToBuy(tickets []int, k int) int { ans := 0 @@ -154,10 +112,32 @@ func timeRequiredToBuy(tickets []int, k int) int { } ``` -### **...** - -``` +```ts +function timeRequiredToBuy(tickets: number[], k: number): number { + const n = tickets.length; + let target = tickets[k] - 1; + let ans = 0; + // round1 + for (let i = 0; i < n; i++) { + let num = tickets[i]; + if (num <= target) { + ans += num; + tickets[i] = 0; + } else { + ans += target; + tickets[i] -= target; + } + } + // round2 + for (let i = 0; i <= k; i++) { + let num = tickets[i]; + ans += num > 0 ? 1 : 0; + } + return ans; +} ``` + + diff --git a/solution/2000-2099/2073.Time Needed to Buy Tickets/README_EN.md b/solution/2000-2099/2073.Time Needed to Buy Tickets/README_EN.md index 1072c70585f96..14ccb8019ae54 100644 --- a/solution/2000-2099/2073.Time Needed to Buy Tickets/README_EN.md +++ b/solution/2000-2099/2073.Time Needed to Buy Tickets/README_EN.md @@ -47,9 +47,9 @@ The person at position 0 has successfully bought 5 tickets and it took 4 + ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int timeRequiredToBuy(int[] tickets, int k) { @@ -81,36 +79,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function timeRequiredToBuy(tickets: number[], k: number): number { - const n = tickets.length; - let target = tickets[k] - 1; - let ans = 0; - // round1 - for (let i = 0; i < n; i++) { - let num = tickets[i]; - if (num <= target) { - ans += num; - tickets[i] = 0; - } else { - ans += target; - tickets[i] -= target; - } - } - - // round2 - for (let i = 0; i <= k; i++) { - let num = tickets[i]; - ans += num > 0 ? 1 : 0; - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -128,8 +96,6 @@ public: }; ``` -### **Go** - ```go func timeRequiredToBuy(tickets []int, k int) int { ans := 0 @@ -144,10 +110,32 @@ func timeRequiredToBuy(tickets []int, k int) int { } ``` -### **...** - -``` +```ts +function timeRequiredToBuy(tickets: number[], k: number): number { + const n = tickets.length; + let target = tickets[k] - 1; + let ans = 0; + // round1 + for (let i = 0; i < n; i++) { + let num = tickets[i]; + if (num <= target) { + ans += num; + tickets[i] = 0; + } else { + ans += target; + tickets[i] -= target; + } + } + // round2 + for (let i = 0; i <= k; i++) { + let num = tickets[i]; + ans += num > 0 ? 1 : 0; + } + return ans; +} ``` + + diff --git a/solution/2000-2099/2074.Reverse Nodes in Even Length Groups/README.md b/solution/2000-2099/2074.Reverse Nodes in Even Length Groups/README.md index d4664e36c19c1..db935c8c7cdc5 100644 --- a/solution/2000-2099/2074.Reverse Nodes in Even Length Groups/README.md +++ b/solution/2000-2099/2074.Reverse Nodes in Even Length Groups/README.md @@ -72,14 +72,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -122,10 +118,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -181,8 +173,6 @@ class Solution { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -224,10 +214,6 @@ function reverseEvenLengthGroups(head: ListNode | null): ListNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2074.Reverse Nodes in Even Length Groups/README_EN.md b/solution/2000-2099/2074.Reverse Nodes in Even Length Groups/README_EN.md index 743dbcde731bc..83f411cc2f8f3 100644 --- a/solution/2000-2099/2074.Reverse Nodes in Even Length Groups/README_EN.md +++ b/solution/2000-2099/2074.Reverse Nodes in Even Length Groups/README_EN.md @@ -63,9 +63,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -109,8 +109,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -166,8 +164,6 @@ class Solution { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -209,10 +205,6 @@ function reverseEvenLengthGroups(head: ListNode | null): ListNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2075.Decode the Slanted Ciphertext/README.md b/solution/2000-2099/2075.Decode the Slanted Ciphertext/README.md index ef8b2304b7580..86f3e31c6ddf2 100644 --- a/solution/2000-2099/2075.Decode the Slanted Ciphertext/README.md +++ b/solution/2000-2099/2075.Decode the Slanted Ciphertext/README.md @@ -77,14 +77,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def decodeCiphertext(self, encodedText: str, rows: int) -> str: @@ -98,10 +94,6 @@ class Solution: return ''.join(ans).rstrip() ``` -### **Java** - - - ```java class Solution { public String decodeCiphertext(String encodedText, int rows) { @@ -120,23 +112,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function decodeCiphertext(encodedText: string, rows: number): string { - const cols = Math.ceil(encodedText.length / rows); - let ans = []; - for (let k = 0; k <= cols; k++) { - for (let i = 0, j = k; i < rows && j < cols; i++, j++) { - ans.push(encodedText.charAt(i * cols + j)); - } - } - return ans.join('').trimEnd(); -} -``` - -### **C++** - ```cpp class Solution { public: @@ -152,10 +127,19 @@ public: }; ``` -### **...** - -``` - +```ts +function decodeCiphertext(encodedText: string, rows: number): string { + const cols = Math.ceil(encodedText.length / rows); + let ans = []; + for (let k = 0; k <= cols; k++) { + for (let i = 0, j = k; i < rows && j < cols; i++, j++) { + ans.push(encodedText.charAt(i * cols + j)); + } + } + return ans.join('').trimEnd(); +} ``` + + diff --git a/solution/2000-2099/2075.Decode the Slanted Ciphertext/README_EN.md b/solution/2000-2099/2075.Decode the Slanted Ciphertext/README_EN.md index 57de8fd00f568..682abfa8687ae 100644 --- a/solution/2000-2099/2075.Decode the Slanted Ciphertext/README_EN.md +++ b/solution/2000-2099/2075.Decode the Slanted Ciphertext/README_EN.md @@ -61,9 +61,9 @@ The blue arrows show how we can find originalText from encodedText. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,8 +78,6 @@ class Solution: return ''.join(ans).rstrip() ``` -### **Java** - ```java class Solution { public String decodeCiphertext(String encodedText, int rows) { @@ -98,23 +96,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function decodeCiphertext(encodedText: string, rows: number): string { - const cols = Math.ceil(encodedText.length / rows); - let ans = []; - for (let k = 0; k <= cols; k++) { - for (let i = 0, j = k; i < rows && j < cols; i++, j++) { - ans.push(encodedText.charAt(i * cols + j)); - } - } - return ans.join('').trimEnd(); -} -``` - -### **C++** - ```cpp class Solution { public: @@ -130,10 +111,19 @@ public: }; ``` -### **...** - -``` - +```ts +function decodeCiphertext(encodedText: string, rows: number): string { + const cols = Math.ceil(encodedText.length / rows); + let ans = []; + for (let k = 0; k <= cols; k++) { + for (let i = 0, j = k; i < rows && j < cols; i++, j++) { + ans.push(encodedText.charAt(i * cols + j)); + } + } + return ans.join('').trimEnd(); +} ``` + + diff --git a/solution/2000-2099/2076.Process Restricted Friend Requests/README.md b/solution/2000-2099/2076.Process Restricted Friend Requests/README.md index 20d1f878a802e..d5589c6712a04 100644 --- a/solution/2000-2099/2076.Process Restricted Friend Requests/README.md +++ b/solution/2000-2099/2076.Process Restricted Friend Requests/README.md @@ -70,16 +70,10 @@ ## 解法 - - -并查集。 +### 方法一 -### **Python3** - - - ```python class Solution: def friendRequests( @@ -111,10 +105,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -160,8 +150,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -198,8 +186,6 @@ public: }; ``` -### **Go** - ```go var p []int @@ -239,10 +225,6 @@ func find(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2076.Process Restricted Friend Requests/README_EN.md b/solution/2000-2099/2076.Process Restricted Friend Requests/README_EN.md index 0f7550fec082c..26c6402f09df6 100644 --- a/solution/2000-2099/2076.Process Restricted Friend Requests/README_EN.md +++ b/solution/2000-2099/2076.Process Restricted Friend Requests/README_EN.md @@ -66,9 +66,9 @@ Request 3: Person 3 and person 4 cannot be friends since person 0 and person 1 w ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -101,8 +101,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] p; @@ -148,8 +146,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -186,8 +182,6 @@ public: }; ``` -### **Go** - ```go var p []int @@ -227,10 +221,6 @@ func find(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2077.Paths in Maze That Lead to Same Room/README.md b/solution/2000-2099/2077.Paths in Maze That Lead to Same Room/README.md index b4d012b6c4302..b600e4a7f8906 100644 --- a/solution/2000-2099/2077.Paths in Maze That Lead to Same Room/README.md +++ b/solution/2000-2099/2077.Paths in Maze That Lead to Same Room/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 长度为 `3` 的环,由三个顶点、三条边组成。我们假设三个顶点分别为 `a`, `b`, `c`。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def numberOfPaths(self, n: int, corridors: List[List[int]]) -> int: @@ -88,10 +82,6 @@ class Solution: return ans // 3 ``` -### **Java** - - - ```java class Solution { public int numberOfPaths(int n, int[][] corridors) { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go func numberOfPaths(n int, corridors [][]int) int { g := make([]map[int]bool, n+1) @@ -184,10 +170,6 @@ func numberOfPaths(n int, corridors [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2077.Paths in Maze That Lead to Same Room/README_EN.md b/solution/2000-2099/2077.Paths in Maze That Lead to Same Room/README_EN.md index 8e164e8d00fb6..7f706ac557689 100644 --- a/solution/2000-2099/2077.Paths in Maze That Lead to Same Room/README_EN.md +++ b/solution/2000-2099/2077.Paths in Maze That Lead to Same Room/README_EN.md @@ -52,9 +52,9 @@ There are no cycles of length 3. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return ans // 3 ``` -### **Java** - ```java class Solution { public int numberOfPaths(int n, int[][] corridors) { @@ -103,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +128,6 @@ public: }; ``` -### **Go** - ```go func numberOfPaths(n int, corridors [][]int) int { g := make([]map[int]bool, n+1) @@ -165,10 +159,6 @@ func numberOfPaths(n int, corridors [][]int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/README.md b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/README.md index 58a5d2d992ec4..a8cce4602bc80 100644 --- a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/README.md +++ b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/README.md @@ -61,20 +61,12 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 时间复杂度 $O(n^2)$。 -**方法二:贪心** - -### **Python3** - - - ```python class Solution: def maxDistance(self, colors: List[int]) -> int: @@ -86,24 +78,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxDistance(self, colors: List[int]) -> int: - n = len(colors) - if colors[0] != colors[-1]: - return n - 1 - i, j = 1, n - 2 - while colors[i] == colors[0]: - i += 1 - while colors[j] == colors[0]: - j -= 1 - return max(n - i - 1, j) -``` - -### **Java** - - - ```java class Solution { public int maxDistance(int[] colors) { @@ -120,25 +94,6 @@ class Solution { } ``` -```java -class Solution { - public int maxDistance(int[] colors) { - int n = colors.length; - if (colors[0] != colors[n - 1]) { - return n - 1; - } - int i = 0, j = n - 1; - while (colors[++i] == colors[0]) - ; - while (colors[--j] == colors[0]) - ; - return Math.max(n - i - 1, j); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -153,24 +108,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxDistance(vector& colors) { - int n = colors.size(); - if (colors[0] != colors[n - 1]) return n - 1; - int i = 0, j = n; - while (colors[++i] == colors[0]) - ; - while (colors[--j] == colors[0]) - ; - return max(n - i - 1, j); - } -}; -``` - -### **Go** - ```go func maxDistance(colors []int) int { ans, n := 0, len(colors) @@ -192,6 +129,59 @@ func abs(x int) int { } ``` + + +### 方法二:贪心 + + + +```python +class Solution: + def maxDistance(self, colors: List[int]) -> int: + n = len(colors) + if colors[0] != colors[-1]: + return n - 1 + i, j = 1, n - 2 + while colors[i] == colors[0]: + i += 1 + while colors[j] == colors[0]: + j -= 1 + return max(n - i - 1, j) +``` + +```java +class Solution { + public int maxDistance(int[] colors) { + int n = colors.length; + if (colors[0] != colors[n - 1]) { + return n - 1; + } + int i = 0, j = n - 1; + while (colors[++i] == colors[0]) + ; + while (colors[--j] == colors[0]) + ; + return Math.max(n - i - 1, j); + } +} +``` + +```cpp +class Solution { +public: + int maxDistance(vector& colors) { + int n = colors.size(); + if (colors[0] != colors[n - 1]) return n - 1; + int i = 0, j = n; + while (colors[++i] == colors[0]) + ; + while (colors[--j] == colors[0]) + ; + return max(n - i - 1, j); + } +}; +``` + ```go func maxDistance(colors []int) int { n := len(colors) @@ -209,10 +199,6 @@ func maxDistance(colors []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/README_EN.md b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/README_EN.md index 2a1d2017ec3d6..5c61f9ba49553 100644 --- a/solution/2000-2099/2078.Two Furthest Houses With Different Colors/README_EN.md +++ b/solution/2000-2099/2078.Two Furthest Houses With Different Colors/README_EN.md @@ -53,9 +53,9 @@ House 0 has color 0, and house 1 has color 1. The distance between them is abs(0 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,22 +68,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxDistance(self, colors: List[int]) -> int: - n = len(colors) - if colors[0] != colors[-1]: - return n - 1 - i, j = 1, n - 2 - while colors[i] == colors[0]: - i += 1 - while colors[j] == colors[0]: - j -= 1 - return max(n - i - 1, j) -``` - -### **Java** - ```java class Solution { public int maxDistance(int[] colors) { @@ -100,25 +84,6 @@ class Solution { } ``` -```java -class Solution { - public int maxDistance(int[] colors) { - int n = colors.length; - if (colors[0] != colors[n - 1]) { - return n - 1; - } - int i = 0, j = n - 1; - while (colors[++i] == colors[0]) - ; - while (colors[--j] == colors[0]) - ; - return Math.max(n - i - 1, j); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -133,24 +98,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxDistance(vector& colors) { - int n = colors.size(); - if (colors[0] != colors[n - 1]) return n - 1; - int i = 0, j = n; - while (colors[++i] == colors[0]) - ; - while (colors[--j] == colors[0]) - ; - return max(n - i - 1, j); - } -}; -``` - -### **Go** - ```go func maxDistance(colors []int) int { ans, n := 0, len(colors) @@ -172,6 +119,59 @@ func abs(x int) int { } ``` + + +### Solution 2 + + + +```python +class Solution: + def maxDistance(self, colors: List[int]) -> int: + n = len(colors) + if colors[0] != colors[-1]: + return n - 1 + i, j = 1, n - 2 + while colors[i] == colors[0]: + i += 1 + while colors[j] == colors[0]: + j -= 1 + return max(n - i - 1, j) +``` + +```java +class Solution { + public int maxDistance(int[] colors) { + int n = colors.length; + if (colors[0] != colors[n - 1]) { + return n - 1; + } + int i = 0, j = n - 1; + while (colors[++i] == colors[0]) + ; + while (colors[--j] == colors[0]) + ; + return Math.max(n - i - 1, j); + } +} +``` + +```cpp +class Solution { +public: + int maxDistance(vector& colors) { + int n = colors.size(); + if (colors[0] != colors[n - 1]) return n - 1; + int i = 0, j = n; + while (colors[++i] == colors[0]) + ; + while (colors[--j] == colors[0]) + ; + return max(n - i - 1, j); + } +}; +``` + ```go func maxDistance(colors []int) int { n := len(colors) @@ -189,10 +189,6 @@ func maxDistance(colors []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2079.Watering Plants/README.md b/solution/2000-2099/2079.Watering Plants/README.md index eeedf59e259d8..3e3737108af7b 100644 --- a/solution/2000-2099/2079.Watering Plants/README.md +++ b/solution/2000-2099/2079.Watering Plants/README.md @@ -71,14 +71,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def wateringPlants(self, plants: List[int], capacity: int) -> int: @@ -93,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int wateringPlants(int[] plants, int capacity) { @@ -115,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +126,6 @@ public: }; ``` -### **Go** - ```go func wateringPlants(plants []int, capacity int) int { ans, cap := 0, capacity @@ -154,8 +142,6 @@ func wateringPlants(plants []int, capacity int) int { } ``` -### **TypeScript** - ```ts function wateringPlants(plants: number[], capacity: number): number { const n = plants.length; @@ -174,8 +160,6 @@ function wateringPlants(plants: number[], capacity: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn watering_plants(plants: Vec, capacity: i32) -> i32 { @@ -196,8 +180,6 @@ impl Solution { } ``` -### **C** - ```c int wateringPlants(int* plants, int plantsSize, int capacity) { int ans = 0; @@ -215,10 +197,6 @@ int wateringPlants(int* plants, int plantsSize, int capacity) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2079.Watering Plants/README_EN.md b/solution/2000-2099/2079.Watering Plants/README_EN.md index 1d94330d0e2b6..8c80196f574bc 100644 --- a/solution/2000-2099/2079.Watering Plants/README_EN.md +++ b/solution/2000-2099/2079.Watering Plants/README_EN.md @@ -68,9 +68,9 @@ Steps needed = 1 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 + 7 = 49. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -86,8 +86,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int wateringPlants(int[] plants, int capacity) { @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +123,6 @@ public: }; ``` -### **Go** - ```go func wateringPlants(plants []int, capacity int) int { ans, cap := 0, capacity @@ -145,8 +139,6 @@ func wateringPlants(plants []int, capacity int) int { } ``` -### **TypeScript** - ```ts function wateringPlants(plants: number[], capacity: number): number { const n = plants.length; @@ -165,8 +157,6 @@ function wateringPlants(plants: number[], capacity: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn watering_plants(plants: Vec, capacity: i32) -> i32 { @@ -187,8 +177,6 @@ impl Solution { } ``` -### **C** - ```c int wateringPlants(int* plants, int plantsSize, int capacity) { int ans = 0; @@ -206,10 +194,6 @@ int wateringPlants(int* plants, int plantsSize, int capacity) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2080.Range Frequency Queries/README.md b/solution/2000-2099/2080.Range Frequency Queries/README.md index f6f91e880bb3e..9e19b464509e5 100644 --- a/solution/2000-2099/2080.Range Frequency Queries/README.md +++ b/solution/2000-2099/2080.Range Frequency Queries/README.md @@ -48,14 +48,10 @@ rangeFreqQuery.query(0, 11, 33); // 返回 2 。33 在整个子数组中出现 2 ## 解法 - +### 方法一 -### **Python3** - - - ```python class RangeFreqQuery: def __init__(self, arr: List[int]): @@ -76,10 +72,6 @@ class RangeFreqQuery: # param_1 = obj.query(left,right,value) ``` -### **Java** - - - ```java class RangeFreqQuery { private Map> mp = new HashMap<>(); @@ -121,8 +113,6 @@ class RangeFreqQuery { */ ``` -### **C++** - ```cpp class RangeFreqQuery { public: @@ -148,8 +138,6 @@ public: */ ``` -### **Go** - ```go type RangeFreqQuery struct { mp map[int][]int @@ -177,10 +165,6 @@ func (this *RangeFreqQuery) Query(left int, right int, value int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2080.Range Frequency Queries/README_EN.md b/solution/2000-2099/2080.Range Frequency Queries/README_EN.md index 81751fc4154c6..45c0ee3cba0e0 100644 --- a/solution/2000-2099/2080.Range Frequency Queries/README_EN.md +++ b/solution/2000-2099/2080.Range Frequency Queries/README_EN.md @@ -45,9 +45,9 @@ rangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the ## Solutions - +### Solution 1 -### **Python3** + ```python class RangeFreqQuery: @@ -69,8 +69,6 @@ class RangeFreqQuery: # param_1 = obj.query(left,right,value) ``` -### **Java** - ```java class RangeFreqQuery { private Map> mp = new HashMap<>(); @@ -112,8 +110,6 @@ class RangeFreqQuery { */ ``` -### **C++** - ```cpp class RangeFreqQuery { public: @@ -139,8 +135,6 @@ public: */ ``` -### **Go** - ```go type RangeFreqQuery struct { mp map[int][]int @@ -168,10 +162,6 @@ func (this *RangeFreqQuery) Query(left int, right int, value int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2081.Sum of k-Mirror Numbers/README.md b/solution/2000-2099/2081.Sum of k-Mirror Numbers/README.md index fdbd68ffff49f..92c7a85978946 100644 --- a/solution/2000-2099/2081.Sum of k-Mirror Numbers/README.md +++ b/solution/2000-2099/2081.Sum of k-Mirror Numbers/README.md @@ -68,22 +68,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - -```python - -``` - -### **Java** - - - ```java class Solution { public long kMirror(int k, int n) { @@ -118,10 +106,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2081.Sum of k-Mirror Numbers/README_EN.md b/solution/2000-2099/2081.Sum of k-Mirror Numbers/README_EN.md index dfe651076a216..52f59ab066713 100644 --- a/solution/2000-2099/2081.Sum of k-Mirror Numbers/README_EN.md +++ b/solution/2000-2099/2081.Sum of k-Mirror Numbers/README_EN.md @@ -67,15 +67,9 @@ Their sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499. ## Solutions - - -### **Python3** - -```python +### Solution 1 -``` - -### **Java** + ```java class Solution { @@ -111,10 +105,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2082.The Number of Rich Customers/README.md b/solution/2000-2099/2082.The Number of Rich Customers/README.md index 9481baf9e95b3..80f82db3eb67e 100644 --- a/solution/2000-2099/2082.The Number of Rich Customers/README.md +++ b/solution/2000-2099/2082.The Number of Rich Customers/README.md @@ -56,14 +56,10 @@ Store 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -73,3 +69,5 @@ WHERE amount > 500; ``` + + diff --git a/solution/2000-2099/2082.The Number of Rich Customers/README_EN.md b/solution/2000-2099/2082.The Number of Rich Customers/README_EN.md index 76d900bb422e7..89b55193ff84e 100644 --- a/solution/2000-2099/2082.The Number of Rich Customers/README_EN.md +++ b/solution/2000-2099/2082.The Number of Rich Customers/README_EN.md @@ -53,9 +53,9 @@ Customer 3 has one bill with an amount strictly greater than 500. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -66,3 +66,5 @@ WHERE amount > 500; ``` + + diff --git a/solution/2000-2099/2083.Substrings That Begin and End With the Same Letter/README.md b/solution/2000-2099/2083.Substrings That Begin and End With the Same Letter/README.md index 27c766d0ab8b9..41a283d190dbb 100644 --- a/solution/2000-2099/2083.Substrings That Begin and End With the Same Letter/README.md +++ b/solution/2000-2099/2083.Substrings That Begin and End With the Same Letter/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:数组或哈希表** +### 方法一:数组或哈希表 我们可以用数组或哈希表统计字符串中每个字母出现的次数,然后遍历字符串,对于每个字母,其出现的次数即为以该字母开头和结尾的子串的个数,将所有字母的出现次数相加即为答案。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def numberOfSubstrings(self, s: str) -> int: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long numberOfSubstrings(String s) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func numberOfSubstrings(s string) (ans int64) { cnt := [26]int{} @@ -128,10 +114,6 @@ func numberOfSubstrings(s string) (ans int64) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2083.Substrings That Begin and End With the Same Letter/README_EN.md b/solution/2000-2099/2083.Substrings That Begin and End With the Same Letter/README_EN.md index b5d02db7636bd..7ef4e0e477cad 100644 --- a/solution/2000-2099/2083.Substrings That Begin and End With the Same Letter/README_EN.md +++ b/solution/2000-2099/2083.Substrings That Begin and End With the Same Letter/README_EN.md @@ -50,9 +50,9 @@ The substring of length 1 that starts and ends with the same letter is: "a& ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long numberOfSubstrings(String s) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +94,6 @@ public: }; ``` -### **Go** - ```go func numberOfSubstrings(s string) (ans int64) { cnt := [26]int{} @@ -112,10 +106,6 @@ func numberOfSubstrings(s string) (ans int64) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2084.Drop Type 1 Orders for Customers With Type 0 Orders/README.md b/solution/2000-2099/2084.Drop Type 1 Orders for Customers With Type 0 Orders/README.md index 594698c4ce26e..b8059f6c35cb5 100644 --- a/solution/2000-2099/2084.Drop Type 1 Orders for Customers With Type 0 Orders/README.md +++ b/solution/2000-2099/2084.Drop Type 1 Orders for Customers With Type 0 Orders/README.md @@ -71,14 +71,10 @@ Orders table: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -92,6 +88,12 @@ FROM Orders AS o WHERE order_type = 0 OR NOT EXISTS (SELECT 1 FROM T AS t WHERE t.customer_id = o.customer_id); ``` + + +### 方法二 + + + ```sql SELECT DISTINCT a.order_id, @@ -104,3 +106,5 @@ WHERE b.order_type IS NULL OR b.order_type = 1; ``` + + diff --git a/solution/2000-2099/2084.Drop Type 1 Orders for Customers With Type 0 Orders/README_EN.md b/solution/2000-2099/2084.Drop Type 1 Orders for Customers With Type 0 Orders/README_EN.md index 5afadad98d138..b6a1461d3575b 100644 --- a/solution/2000-2099/2084.Drop Type 1 Orders for Customers With Type 0 Orders/README_EN.md +++ b/solution/2000-2099/2084.Drop Type 1 Orders for Customers With Type 0 Orders/README_EN.md @@ -71,9 +71,9 @@ Customer 4 has two orders of type 1. We return both of them. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -88,6 +88,12 @@ FROM Orders AS o WHERE order_type = 0 OR NOT EXISTS (SELECT 1 FROM T AS t WHERE t.customer_id = o.customer_id); ``` + + +### Solution 2 + + + ```sql SELECT DISTINCT a.order_id, @@ -100,3 +106,5 @@ WHERE b.order_type IS NULL OR b.order_type = 1; ``` + + diff --git a/solution/2000-2099/2085.Count Common Words With One Occurrence/README.md b/solution/2000-2099/2085.Count Common Words With One Occurrence/README.md index 6803e9dc5b365..0bc7b4523f043 100644 --- a/solution/2000-2099/2085.Count Common Words With One Occurrence/README.md +++ b/solution/2000-2099/2085.Count Common Words With One Occurrence/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:哈希表计数** +### 方法一:哈希表计数 我们可以用两个哈希表 $cnt1$ 和 $cnt2$ 分别统计两个字符串数组中每个字符串出现的次数,然后遍历其中一个哈希表,如果某个字符串在另一个哈希表中出现了一次,且在当前哈希表中也出现了一次,则答案加一。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def countWords(self, words1: List[str], words2: List[str]) -> int: @@ -73,10 +67,6 @@ class Solution: return sum(v == 1 and cnt2[w] == 1 for w, v in cnt1.items()) ``` -### **Java** - - - ```java class Solution { public int countWords(String[] words1, String[] words2) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func countWords(words1 []string, words2 []string) (ans int) { cnt1 := map[string]int{} @@ -143,8 +129,6 @@ func countWords(words1 []string, words2 []string) (ans int) { } ``` -### **TypeScript** - ```ts function countWords(words1: string[], words2: string[]): number { const cnt1 = new Map(); @@ -165,10 +149,6 @@ function countWords(words1: string[], words2: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2085.Count Common Words With One Occurrence/README_EN.md b/solution/2000-2099/2085.Count Common Words With One Occurrence/README_EN.md index 010e07460e322..d8a0c7ecb55d1 100644 --- a/solution/2000-2099/2085.Count Common Words With One Occurrence/README_EN.md +++ b/solution/2000-2099/2085.Count Common Words With One Occurrence/README_EN.md @@ -47,7 +47,7 @@ Thus, there are 2 strings that appear exactly once in each of the two arrays. ## Solutions -**Solution 1: Hash Table + Counting** +### Solution 1: Hash Table + Counting We can use two hash tables, $cnt1$ and $cnt2$, to count the occurrences of each string in the two string arrays respectively. Then, we traverse one of the hash tables. If a string appears once in the other hash table and also appears once in the current hash table, we increment the answer by one. @@ -55,8 +55,6 @@ The time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Where -### **Python3** - ```python class Solution: def countWords(self, words1: List[str], words2: List[str]) -> int: @@ -65,8 +63,6 @@ class Solution: return sum(v == 1 and cnt2[w] == 1 for w, v in cnt1.items()) ``` -### **Java** - ```java class Solution { public int countWords(String[] words1, String[] words2) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +106,6 @@ public: }; ``` -### **Go** - ```go func countWords(words1 []string, words2 []string) (ans int) { cnt1 := map[string]int{} @@ -133,8 +125,6 @@ func countWords(words1 []string, words2 []string) (ans int) { } ``` -### **TypeScript** - ```ts function countWords(words1: string[], words2: string[]): number { const cnt1 = new Map(); @@ -155,10 +145,6 @@ function countWords(words1: string[], words2: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2086.Minimum Number of Food Buckets to Feed the Hamsters/README.md b/solution/2000-2099/2086.Minimum Number of Food Buckets to Feed the Hamsters/README.md index 5b0ed19567ff7..2fa2c09c1b2cc 100644 --- a/solution/2000-2099/2086.Minimum Number of Food Buckets to Feed the Hamsters/README.md +++ b/solution/2000-2099/2086.Minimum Number of Food Buckets to Feed the Hamsters/README.md @@ -74,9 +74,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 从左到右遍历字符串,遇到 `H` 时,优先考虑右边是否有空位,如果有则放置水桶,并且跳过水桶的下一个位置;如果右边没有空位,则考虑左边是否有空位,如果有则放置水桶,否则无解。 @@ -84,10 +82,6 @@ -### **Python3** - - - ```python class Solution: def minimumBuckets(self, street: str) -> int: @@ -106,10 +100,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumBuckets(String street) { @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func minimumBuckets(street string) int { ans, n := 0, len(street) @@ -178,10 +164,6 @@ func minimumBuckets(street string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2086.Minimum Number of Food Buckets to Feed the Hamsters/README_EN.md b/solution/2000-2099/2086.Minimum Number of Food Buckets to Feed the Hamsters/README_EN.md index 1b0bbe80eb7bc..93efb5882da8e 100644 --- a/solution/2000-2099/2086.Minimum Number of Food Buckets to Feed the Hamsters/README_EN.md +++ b/solution/2000-2099/2086.Minimum Number of Food Buckets to Feed the Hamsters/README_EN.md @@ -51,9 +51,9 @@ It can be shown that if we place only one food bucket, one of the hamsters will ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumBuckets(String street) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +118,6 @@ public: }; ``` -### **Go** - ```go func minimumBuckets(street string) int { ans, n := 0, len(street) @@ -143,10 +137,6 @@ func minimumBuckets(street string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2087.Minimum Cost Homecoming of a Robot in a Grid/README.md b/solution/2000-2099/2087.Minimum Cost Homecoming of a Robot in a Grid/README.md index ab2ea0f884159..89b83034a25ae 100644 --- a/solution/2000-2099/2087.Minimum Cost Homecoming of a Robot in a Grid/README.md +++ b/solution/2000-2099/2087.Minimum Cost Homecoming of a Robot in a Grid/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 设机器人当前位置为 $(i, j)$,目标位置为 $(x, y)$。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def minCost( @@ -99,10 +93,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) { @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func minCost(startPos []int, homePos []int, rowCosts []int, colCosts []int) (ans int) { i, j := startPos[0], startPos[1] @@ -183,10 +169,6 @@ func sum(nums []int, i, j int) (s int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2087.Minimum Cost Homecoming of a Robot in a Grid/README_EN.md b/solution/2000-2099/2087.Minimum Cost Homecoming of a Robot in a Grid/README_EN.md index 601d1e46d1c22..a31d9b1ee92a2 100644 --- a/solution/2000-2099/2087.Minimum Cost Homecoming of a Robot in a Grid/README_EN.md +++ b/solution/2000-2099/2087.Minimum Cost Homecoming of a Robot in a Grid/README_EN.md @@ -53,9 +53,9 @@ The total cost is 3 + 2 + 6 + 7 = 18 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) { @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +131,6 @@ public: }; ``` -### **Go** - ```go func minCost(startPos []int, homePos []int, rowCosts []int, colCosts []int) (ans int) { i, j := startPos[0], startPos[1] @@ -162,10 +156,6 @@ func sum(nums []int, i, j int) (s int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2088.Count Fertile Pyramids in a Land/README.md b/solution/2000-2099/2088.Count Fertile Pyramids in a Land/README.md index 5ca058cd2975a..0cd59fa1c44df 100644 --- a/solution/2000-2099/2088.Count Fertile Pyramids in a Land/README.md +++ b/solution/2000-2099/2088.Count Fertile Pyramids in a Land/README.md @@ -89,9 +89,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示以 $(i, j)$ 为顶点的金字塔的最大高度,那么有如下状态转移方程: @@ -115,10 +113,6 @@ $$ -### **Python3** - - - ```python class Solution: def countPyramids(self, grid: List[List[int]]) -> int: @@ -144,10 +138,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countPyramids(int[][] grid) { @@ -183,8 +173,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -221,8 +209,6 @@ public: }; ``` -### **Go** - ```go func countPyramids(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -258,10 +244,6 @@ func countPyramids(grid [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2088.Count Fertile Pyramids in a Land/README_EN.md b/solution/2000-2099/2088.Count Fertile Pyramids in a Land/README_EN.md index 57b28022e668a..2020ca7ba2816 100644 --- a/solution/2000-2099/2088.Count Fertile Pyramids in a Land/README_EN.md +++ b/solution/2000-2099/2088.Count Fertile Pyramids in a Land/README_EN.md @@ -67,9 +67,9 @@ The total number of plots is 7 + 6 = 13. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -96,8 +96,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countPyramids(int[][] grid) { @@ -133,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +167,6 @@ public: }; ``` -### **Go** - ```go func countPyramids(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -208,10 +202,6 @@ func countPyramids(grid [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2089.Find Target Indices After Sorting Array/README.md b/solution/2000-2099/2089.Find Target Indices After Sorting Array/README.md index aa3f414b32f3b..8ffd66b8164c1 100644 --- a/solution/2000-2099/2089.Find Target Indices After Sorting Array/README.md +++ b/solution/2000-2099/2089.Find Target Indices After Sorting Array/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 将数组 `nums` 排序后,遍历数组,找出所有等于 `target` 的元素的下标,将其加入结果数组中。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def targetIndices(self, nums: List[int], target: int) -> List[int]: @@ -77,10 +71,6 @@ class Solution: return [i for i, v in enumerate(nums) if v == target] ``` -### **Java** - - - ```java class Solution { public List targetIndices(int[] nums, int target) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func targetIndices(nums []int, target int) (ans []int) { sort.Ints(nums) @@ -128,8 +114,6 @@ func targetIndices(nums []int, target int) (ans []int) { } ``` -### **TypeScript** - ```ts function targetIndices(nums: number[], target: number): number[] { nums.sort((a, b) => a - b); @@ -143,10 +127,6 @@ function targetIndices(nums: number[], target: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2089.Find Target Indices After Sorting Array/README_EN.md b/solution/2000-2099/2089.Find Target Indices After Sorting Array/README_EN.md index 5de9a857595c3..c38053d75d580 100644 --- a/solution/2000-2099/2089.Find Target Indices After Sorting Array/README_EN.md +++ b/solution/2000-2099/2089.Find Target Indices After Sorting Array/README_EN.md @@ -48,9 +48,9 @@ The index where nums[i] == 5 is 4. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return [i for i, v in enumerate(nums) if v == target] ``` -### **Java** - ```java class Solution { public List targetIndices(int[] nums, int target) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +90,6 @@ public: }; ``` -### **Go** - ```go func targetIndices(nums []int, target int) (ans []int) { sort.Ints(nums) @@ -108,8 +102,6 @@ func targetIndices(nums []int, target int) (ans []int) { } ``` -### **TypeScript** - ```ts function targetIndices(nums: number[], target: number): number[] { nums.sort((a, b) => a - b); @@ -123,10 +115,6 @@ function targetIndices(nums: number[], target: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2090.K Radius Subarray Averages/README.md b/solution/2000-2099/2090.K Radius Subarray Averages/README.md index a3fbd2c8ff2c9..d9221d90d1c28 100644 --- a/solution/2000-2099/2090.K Radius Subarray Averages/README.md +++ b/solution/2000-2099/2090.K Radius Subarray Averages/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:前缀和** +### 方法一:前缀和 我们可以先预处理得到数组 `nums` 的前缀和数组 $s$,其中 $s[i]$ 表示 $nums[i]$ 的前 $i$ 个元素之和。 @@ -81,24 +79,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。 -**方法二:滑动窗口** - -我们维护一个大小为 $k \times 2 + 1$ 的窗口,记窗口中的所有元素和为 $s$。 - -与方法一一样,我们创建一个长度为 $n$ 的答案数组 $ans$,初始时每项元素均为 $-1$。 - -接下来遍历数组 `nums`,将 $nums[i]$ 的值加到窗口的和 $s$ 中,如果此时 $i \geq k \times 2$,说明此时窗口大小为 $k \times 2 + 1$,那么 $ans[i-k] = \frac{s}{k \times 2 + 1}$,然后我们将 $nums[i - k \times 2]$ 的值从窗口和 $s$ 中移出。继续遍历下个元素。 - -最后返回答案数组即可。 - -时间复杂度 $O(n)$,忽略答案的空间消耗,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。 - -### **Python3** - - - ```python class Solution: def getAverages(self, nums: List[int], k: int) -> List[int]: @@ -111,23 +93,6 @@ class Solution: return ans ``` -```python -class Solution: - def getAverages(self, nums: List[int], k: int) -> List[int]: - s = 0 - ans = [-1] * len(nums) - for i, v in enumerate(nums): - s += v - if i >= k * 2: - ans[i - k] = s // (k * 2 + 1) - s -= nums[i - k * 2] - return ans -``` - -### **Java** - - - ```java class Solution { public int[] getAverages(int[] nums, int k) { @@ -148,27 +113,6 @@ class Solution { } ``` -```java -class Solution { - public int[] getAverages(int[] nums, int k) { - int n = nums.length; - int[] ans = new int[n]; - Arrays.fill(ans, -1); - long s = 0; - for (int i = 0; i < n; ++i) { - s += nums[i]; - if (i >= k * 2) { - ans[i - k] = (int) (s / (k * 2 + 1)); - s -= nums[i - k * 2]; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -190,27 +134,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector getAverages(vector& nums, int k) { - int n = nums.size(); - vector ans(n, -1); - long s = 0; - for (int i = 0; i < n; ++i) { - s += nums[i]; - if (i >= k * 2) { - ans[i - k] = s / (k * 2 + 1); - s -= nums[i - k * 2]; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func getAverages(nums []int, k int) []int { n := len(nums) @@ -229,24 +152,6 @@ func getAverages(nums []int, k int) []int { } ``` -```go -func getAverages(nums []int, k int) []int { - ans := make([]int, len(nums)) - s := 0 - for i, v := range nums { - ans[i] = -1 - s += v - if i >= k*2 { - ans[i-k] = s / (k*2 + 1) - s -= nums[i-k*2] - } - } - return ans -} -``` - -### **TypeScript** - ```ts function getAverages(nums: number[], k: number): number[] { const n = nums.length; @@ -264,6 +169,89 @@ function getAverages(nums: number[], k: number): number[] { } ``` + + +### 方法二:滑动窗口 + +我们维护一个大小为 $k \times 2 + 1$ 的窗口,记窗口中的所有元素和为 $s$。 + +与方法一一样,我们创建一个长度为 $n$ 的答案数组 $ans$,初始时每项元素均为 $-1$。 + +接下来遍历数组 `nums`,将 $nums[i]$ 的值加到窗口的和 $s$ 中,如果此时 $i \geq k \times 2$,说明此时窗口大小为 $k \times 2 + 1$,那么 $ans[i-k] = \frac{s}{k \times 2 + 1}$,然后我们将 $nums[i - k \times 2]$ 的值从窗口和 $s$ 中移出。继续遍历下个元素。 + +最后返回答案数组即可。 + +时间复杂度 $O(n)$,忽略答案的空间消耗,空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。 + + + +```python +class Solution: + def getAverages(self, nums: List[int], k: int) -> List[int]: + s = 0 + ans = [-1] * len(nums) + for i, v in enumerate(nums): + s += v + if i >= k * 2: + ans[i - k] = s // (k * 2 + 1) + s -= nums[i - k * 2] + return ans +``` + +```java +class Solution { + public int[] getAverages(int[] nums, int k) { + int n = nums.length; + int[] ans = new int[n]; + Arrays.fill(ans, -1); + long s = 0; + for (int i = 0; i < n; ++i) { + s += nums[i]; + if (i >= k * 2) { + ans[i - k] = (int) (s / (k * 2 + 1)); + s -= nums[i - k * 2]; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector getAverages(vector& nums, int k) { + int n = nums.size(); + vector ans(n, -1); + long s = 0; + for (int i = 0; i < n; ++i) { + s += nums[i]; + if (i >= k * 2) { + ans[i - k] = s / (k * 2 + 1); + s -= nums[i - k * 2]; + } + } + return ans; + } +}; +``` + +```go +func getAverages(nums []int, k int) []int { + ans := make([]int, len(nums)) + s := 0 + for i, v := range nums { + ans[i] = -1 + s += v + if i >= k*2 { + ans[i-k] = s / (k*2 + 1) + s -= nums[i-k*2] + } + } + return ans +} +``` + ```ts function getAverages(nums: number[], k: number): number[] { const n = nums.length; @@ -280,10 +268,6 @@ function getAverages(nums: number[], k: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2090.K Radius Subarray Averages/README_EN.md b/solution/2000-2099/2090.K Radius Subarray Averages/README_EN.md index 3b2b35b39b82d..df553926cea18 100644 --- a/solution/2000-2099/2090.K Radius Subarray Averages/README_EN.md +++ b/solution/2000-2099/2090.K Radius Subarray Averages/README_EN.md @@ -61,9 +61,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,21 +77,6 @@ class Solution: return ans ``` -```python -class Solution: - def getAverages(self, nums: List[int], k: int) -> List[int]: - s = 0 - ans = [-1] * len(nums) - for i, v in enumerate(nums): - s += v - if i >= k * 2: - ans[i - k] = s // (k * 2 + 1) - s -= nums[i - k * 2] - return ans -``` - -### **Java** - ```java class Solution { public int[] getAverages(int[] nums, int k) { @@ -112,27 +97,6 @@ class Solution { } ``` -```java -class Solution { - public int[] getAverages(int[] nums, int k) { - int n = nums.length; - int[] ans = new int[n]; - Arrays.fill(ans, -1); - long s = 0; - for (int i = 0; i < n; ++i) { - s += nums[i]; - if (i >= k * 2) { - ans[i - k] = (int) (s / (k * 2 + 1)); - s -= nums[i - k * 2]; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -154,27 +118,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector getAverages(vector& nums, int k) { - int n = nums.size(); - vector ans(n, -1); - long s = 0; - for (int i = 0; i < n; ++i) { - s += nums[i]; - if (i >= k * 2) { - ans[i - k] = s / (k * 2 + 1); - s -= nums[i - k * 2]; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func getAverages(nums []int, k int) []int { n := len(nums) @@ -193,24 +136,6 @@ func getAverages(nums []int, k int) []int { } ``` -```go -func getAverages(nums []int, k int) []int { - ans := make([]int, len(nums)) - s := 0 - for i, v := range nums { - ans[i] = -1 - s += v - if i >= k*2 { - ans[i-k] = s / (k*2 + 1) - s -= nums[i-k*2] - } - } - return ans -} -``` - -### **TypeScript** - ```ts function getAverages(nums: number[], k: number): number[] { const n = nums.length; @@ -228,6 +153,79 @@ function getAverages(nums: number[], k: number): number[] { } ``` + + +### Solution 2 + + + +```python +class Solution: + def getAverages(self, nums: List[int], k: int) -> List[int]: + s = 0 + ans = [-1] * len(nums) + for i, v in enumerate(nums): + s += v + if i >= k * 2: + ans[i - k] = s // (k * 2 + 1) + s -= nums[i - k * 2] + return ans +``` + +```java +class Solution { + public int[] getAverages(int[] nums, int k) { + int n = nums.length; + int[] ans = new int[n]; + Arrays.fill(ans, -1); + long s = 0; + for (int i = 0; i < n; ++i) { + s += nums[i]; + if (i >= k * 2) { + ans[i - k] = (int) (s / (k * 2 + 1)); + s -= nums[i - k * 2]; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector getAverages(vector& nums, int k) { + int n = nums.size(); + vector ans(n, -1); + long s = 0; + for (int i = 0; i < n; ++i) { + s += nums[i]; + if (i >= k * 2) { + ans[i - k] = s / (k * 2 + 1); + s -= nums[i - k * 2]; + } + } + return ans; + } +}; +``` + +```go +func getAverages(nums []int, k int) []int { + ans := make([]int, len(nums)) + s := 0 + for i, v := range nums { + ans[i] = -1 + s += v + if i >= k*2 { + ans[i-k] = s / (k*2 + 1) + s -= nums[i-k*2] + } + } + return ans +} +``` + ```ts function getAverages(nums: number[], k: number): number[] { const n = nums.length; @@ -244,10 +242,6 @@ function getAverages(nums: number[], k: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2091.Removing Minimum and Maximum From Array/README.md b/solution/2000-2099/2091.Removing Minimum and Maximum From Array/README.md index 09e7134106ac8..4539ee41fe1b0 100644 --- a/solution/2000-2099/2091.Removing Minimum and Maximum From Array/README.md +++ b/solution/2000-2099/2091.Removing Minimum and Maximum From Array/README.md @@ -62,24 +62,10 @@ ## 解法 - - -先找出最小值和最大值的下标 mi, mx。如果 mi 下标大于 mx,则将 mx 与 mi 两数进行交换。 - -最小删除的次数,共有 3 种情况: - -1. 从左侧往右依次删除 `nums[mi]` 和 `nums[mx]` -1. 从右侧往左依次删除 `nums[mx]` 和 `nums[mi]` -1. 从左侧往右删除 `nums[mi]`,从右侧往左删除 `nums[mx]` - -求这 3 种情况的最小值即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def minimumDeletions(self, nums: List[int]) -> int: @@ -94,10 +80,6 @@ class Solution: return min(mx + 1, len(nums) - mi, mi + 1 + len(nums) - mx) ``` -### **Java** - - - ```java class Solution { public int minimumDeletions(int[] nums) { @@ -120,25 +102,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minimumDeletions(nums: number[]): number { - const n = nums.length; - if (n == 1) return 1; - let i = nums.indexOf(Math.min(...nums)); - let j = nums.indexOf(Math.max(...nums)); - let left = Math.min(i, j); - let right = Math.max(i, j); - // 左右 left + 1 + n - right - // 两个都是左边 left + 1 + right - left = right + 1 - // 都是右边 n - right + right - left = n - left - return Math.min(left + 1 + n - right, right + 1, n - left); -} -``` - -### **C++** - ```cpp class Solution { public: @@ -158,8 +121,6 @@ public: }; ``` -### **Go** - ```go func minimumDeletions(nums []int) int { mi, mx, n := 0, 0, len(nums) @@ -178,10 +139,21 @@ func minimumDeletions(nums []int) int { } ``` -### **...** - -``` - +```ts +function minimumDeletions(nums: number[]): number { + const n = nums.length; + if (n == 1) return 1; + let i = nums.indexOf(Math.min(...nums)); + let j = nums.indexOf(Math.max(...nums)); + let left = Math.min(i, j); + let right = Math.max(i, j); + // 左右 left + 1 + n - right + // 两个都是左边 left + 1 + right - left = right + 1 + // 都是右边 n - right + right - left = n - left + return Math.min(left + 1 + n - right, right + 1, n - left); +} ``` + + diff --git a/solution/2000-2099/2091.Removing Minimum and Maximum From Array/README_EN.md b/solution/2000-2099/2091.Removing Minimum and Maximum From Array/README_EN.md index 6ae555dd1e9b3..463b5127e7076 100644 --- a/solution/2000-2099/2091.Removing Minimum and Maximum From Array/README_EN.md +++ b/solution/2000-2099/2091.Removing Minimum and Maximum From Array/README_EN.md @@ -58,9 +58,9 @@ We can remove it with 1 deletion. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return min(mx + 1, len(nums) - mi, mi + 1 + len(nums) - mx) ``` -### **Java** - ```java class Solution { public int minimumDeletions(int[] nums) { @@ -100,22 +98,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minimumDeletions(nums: number[]): number { - const n = nums.length; - if (n == 1) return 1; - let i = nums.indexOf(Math.min(...nums)); - let j = nums.indexOf(Math.max(...nums)); - let left = Math.min(i, j); - let right = Math.max(i, j); - return Math.min(left + 1 + n - right, right + 1, n - left); -} -``` - -### **C++** - ```cpp class Solution { public: @@ -135,8 +117,6 @@ public: }; ``` -### **Go** - ```go func minimumDeletions(nums []int) int { mi, mx, n := 0, 0, len(nums) @@ -155,10 +135,21 @@ func minimumDeletions(nums []int) int { } ``` -### **...** - -``` - +```ts +function minimumDeletions(nums: number[]): number { + const n = nums.length; + if (n == 1) return 1; + let i = nums.indexOf(Math.min(...nums)); + let j = nums.indexOf(Math.max(...nums)); + let left = Math.min(i, j); + let right = Math.max(i, j); + // 左右 left + 1 + n - right + // 两个都是左边 left + 1 + right - left = right + 1 + // 都是右边 n - right + right - left = n - left + return Math.min(left + 1 + n - right, right + 1, n - left); +} ``` + + diff --git a/solution/2000-2099/2092.Find All People With Secret/README.md b/solution/2000-2099/2092.Find All People With Secret/README.md index 4481372ca980b..03b16457bc5a4 100644 --- a/solution/2000-2099/2092.Find All People With Secret/README.md +++ b/solution/2000-2099/2092.Find All People With Secret/README.md @@ -69,16 +69,10 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS -### **Python3** - - - ```python class Solution: def findAllPeople( @@ -109,10 +103,6 @@ class Solution: return [i for i, v in enumerate(vis) if v] ``` -### **Java** - - - ```java class Solution { public List findAllPeople(int n, int[][] meetings, int firstPerson) { @@ -162,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -211,8 +199,6 @@ public: }; ``` -### **Go** - ```go func findAllPeople(n int, meetings [][]int, firstPerson int) []int { vis := make([]bool, n) @@ -260,8 +246,6 @@ func findAllPeople(n int, meetings [][]int, firstPerson int) []int { } ``` -### **TypeScript** - ```ts function findAllPeople(n: number, meetings: number[][], firstPerson: number): number[] { let parent: Array = Array.from({ length: n + 1 }, (v, i) => i); @@ -313,10 +297,6 @@ function findAllPeople(n: number, meetings: number[][], firstPerson: number): nu } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2092.Find All People With Secret/README_EN.md b/solution/2000-2099/2092.Find All People With Secret/README_EN.md index 27f009f58c8b7..731fb7fef729f 100644 --- a/solution/2000-2099/2092.Find All People With Secret/README_EN.md +++ b/solution/2000-2099/2092.Find All People With Secret/README_EN.md @@ -66,12 +66,10 @@ Thus, people 0, 1, 2, 3, and 4 know the secret after all the meetings. ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def findAllPeople( @@ -102,8 +100,6 @@ class Solution: return [i for i, v in enumerate(vis) if v] ``` -### **Java** - ```java class Solution { public List findAllPeople(int n, int[][] meetings, int firstPerson) { @@ -153,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -202,8 +196,6 @@ public: }; ``` -### **Go** - ```go func findAllPeople(n int, meetings [][]int, firstPerson int) []int { vis := make([]bool, n) @@ -251,8 +243,6 @@ func findAllPeople(n int, meetings [][]int, firstPerson int) []int { } ``` -### **TypeScript** - ```ts function findAllPeople(n: number, meetings: number[][], firstPerson: number): number[] { let parent: Array = Array.from({ length: n + 1 }, (v, i) => i); @@ -304,10 +294,6 @@ function findAllPeople(n: number, meetings: number[][], firstPerson: number): nu } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2093.Minimum Cost to Reach City With Discounts/README.md b/solution/2000-2099/2093.Minimum Cost to Reach City With Discounts/README.md index bc5198435f3bd..0e2882f1b46f1 100644 --- a/solution/2000-2099/2093.Minimum Cost to Reach City With Discounts/README.md +++ b/solution/2000-2099/2093.Minimum Cost to Reach City With Discounts/README.md @@ -66,18 +66,12 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 本题属于带限制的单源最短路问题。 -### **Python3** - - - ```python class Solution: def minimumCost(self, n: int, highways: List[List[int]], discounts: int) -> int: @@ -101,10 +95,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int minimumCost(int n, int[][] highways, int discounts) { @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,18 +163,6 @@ public: }; ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2093.Minimum Cost to Reach City With Discounts/README_EN.md b/solution/2000-2099/2093.Minimum Cost to Reach City With Discounts/README_EN.md index 1bb47587ef6d4..0fcc628f2a704 100644 --- a/solution/2000-2099/2093.Minimum Cost to Reach City With Discounts/README_EN.md +++ b/solution/2000-2099/2093.Minimum Cost to Reach City With Discounts/README_EN.md @@ -62,9 +62,9 @@ It is impossible to go from 0 to 3 so return -1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -89,8 +89,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int minimumCost(int n, int[][] highways, int discounts) { @@ -130,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,16 +157,6 @@ public: }; ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2094.Finding 3-Digit Even Numbers/README.md b/solution/2000-2099/2094.Finding 3-Digit Even Numbers/README.md index b17d76f66b09f..cf071db601fcb 100644 --- a/solution/2000-2099/2094.Finding 3-Digit Even Numbers/README.md +++ b/solution/2000-2099/2094.Finding 3-Digit Even Numbers/README.md @@ -61,14 +61,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findEvenNumbers(self, digits: List[int]) -> List[int]: @@ -86,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] findEvenNumbers(int[] digits) { @@ -128,40 +120,6 @@ class Solution { } ``` -### **TypeScript** - - - -```ts -function findEvenNumbers(digits: number[]): number[] { - let record = new Array(10).fill(0); - for (let digit of digits) { - record[digit]++; - } - let ans = []; - for (let i = 100; i < 1000; i += 2) { - if (check(record, String(i))) { - ans.push(i); - } - } - return ans; -} - -function check(target: Array, digits: string): boolean { - let record = new Array(10).fill(0); - for (let digit of digits) { - record[digit]++; - } - - for (let i = 0; i < 10; i++) { - if (record[i] > target[i]) return false; - } - return true; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -195,8 +153,6 @@ public: }; ``` -### **Go** - ```go func findEvenNumbers(digits []int) []int { counter := count(digits) @@ -234,10 +190,34 @@ func check(cnt1, cnt2 []int) bool { } ``` -### **...** +```ts +function findEvenNumbers(digits: number[]): number[] { + let record = new Array(10).fill(0); + for (let digit of digits) { + record[digit]++; + } + let ans = []; + for (let i = 100; i < 1000; i += 2) { + if (check(record, String(i))) { + ans.push(i); + } + } + return ans; +} -``` +function check(target: Array, digits: string): boolean { + let record = new Array(10).fill(0); + for (let digit of digits) { + record[digit]++; + } + for (let i = 0; i < 10; i++) { + if (record[i] > target[i]) return false; + } + return true; +} ``` + + diff --git a/solution/2000-2099/2094.Finding 3-Digit Even Numbers/README_EN.md b/solution/2000-2099/2094.Finding 3-Digit Even Numbers/README_EN.md index 30f6e63970f15..fa19421562d70 100644 --- a/solution/2000-2099/2094.Finding 3-Digit Even Numbers/README_EN.md +++ b/solution/2000-2099/2094.Finding 3-Digit Even Numbers/README_EN.md @@ -55,9 +55,9 @@ In this example, the digit 8 is used twice each time in 288, 828, and 882. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] findEvenNumbers(int[] digits) { @@ -116,38 +114,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function findEvenNumbers(digits: number[]): number[] { - let record = new Array(10).fill(0); - for (let digit of digits) { - record[digit]++; - } - let ans = []; - for (let i = 100; i < 1000; i += 2) { - if (check(record, String(i))) { - ans.push(i); - } - } - return ans; -} - -function check(target: Array, digits: string): boolean { - let record = new Array(10).fill(0); - for (let digit of digits) { - record[digit]++; - } - - for (let i = 0; i < 10; i++) { - if (record[i] > target[i]) return false; - } - return true; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -181,8 +147,6 @@ public: }; ``` -### **Go** - ```go func findEvenNumbers(digits []int) []int { counter := count(digits) @@ -220,10 +184,34 @@ func check(cnt1, cnt2 []int) bool { } ``` -### **...** +```ts +function findEvenNumbers(digits: number[]): number[] { + let record = new Array(10).fill(0); + for (let digit of digits) { + record[digit]++; + } + let ans = []; + for (let i = 100; i < 1000; i += 2) { + if (check(record, String(i))) { + ans.push(i); + } + } + return ans; +} -``` +function check(target: Array, digits: string): boolean { + let record = new Array(10).fill(0); + for (let digit of digits) { + record[digit]++; + } + for (let i = 0; i < 10; i++) { + if (record[i] > target[i]) return false; + } + return true; +} ``` + + diff --git a/solution/2000-2099/2095.Delete the Middle Node of a Linked List/README.md b/solution/2000-2099/2095.Delete the Middle Node of a Linked List/README.md index 97651d207314d..767832255f36d 100644 --- a/solution/2000-2099/2095.Delete the Middle Node of a Linked List/README.md +++ b/solution/2000-2099/2095.Delete the Middle Node of a Linked List/README.md @@ -64,14 +64,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -89,10 +85,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -118,38 +110,6 @@ 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 deleteMiddle(head: ListNode | null): ListNode | null { - if (!head || !head.next) return null; - let fast = head.next, - slow = head; - while (fast.next && fast.next.next) { - slow = slow.next; - fast = fast.next.next; - } - slow.next = slow.next.next; - return head; -} -``` - -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -177,8 +137,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -198,10 +156,32 @@ func deleteMiddle(head *ListNode) *ListNode { } ``` -### **...** - -``` +```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 deleteMiddle(head: ListNode | null): ListNode | null { + if (!head || !head.next) return null; + let fast = head.next, + slow = head; + while (fast.next && fast.next.next) { + slow = slow.next; + fast = fast.next.next; + } + slow.next = slow.next.next; + return head; +} ``` + + diff --git a/solution/2000-2099/2095.Delete the Middle Node of a Linked List/README_EN.md b/solution/2000-2099/2095.Delete the Middle Node of a Linked List/README_EN.md index b753a1c0eb301..82b988c5d6f05 100644 --- a/solution/2000-2099/2095.Delete the Middle Node of a Linked List/README_EN.md +++ b/solution/2000-2099/2095.Delete the Middle Node of a Linked List/README_EN.md @@ -54,9 +54,9 @@ Node 0 with value 2 is the only node remaining after removing node 1. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -75,8 +75,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -102,36 +100,6 @@ 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 deleteMiddle(head: ListNode | null): ListNode | null { - if (!head || !head.next) return null; - let fast = head.next, - slow = head; - while (fast.next && fast.next.next) { - slow = slow.next; - fast = fast.next.next; - } - slow.next = slow.next.next; - return head; -} -``` - -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -159,8 +127,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -180,10 +146,32 @@ func deleteMiddle(head *ListNode) *ListNode { } ``` -### **...** - -``` +```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 deleteMiddle(head: ListNode | null): ListNode | null { + if (!head || !head.next) return null; + let fast = head.next, + slow = head; + while (fast.next && fast.next.next) { + slow = slow.next; + fast = fast.next.next; + } + slow.next = slow.next.next; + return head; +} ``` + + diff --git a/solution/2000-2099/2096.Step-By-Step Directions From a Binary Tree Node to Another/README.md b/solution/2000-2099/2096.Step-By-Step Directions From a Binary Tree Node to Another/README.md index f88e9bbd35498..ae0e1bde87d04 100644 --- a/solution/2000-2099/2096.Step-By-Step Directions From a Binary Tree Node to Another/README.md +++ b/solution/2000-2099/2096.Step-By-Step Directions From a Binary Tree Node to Another/README.md @@ -53,16 +53,10 @@ ## 解法 - - -先预处理父子节点的关系,然后 DFS 搜索即可。 +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -109,10 +103,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -185,8 +175,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -245,18 +233,6 @@ public: }; ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2096.Step-By-Step Directions From a Binary Tree Node to Another/README_EN.md b/solution/2000-2099/2096.Step-By-Step Directions From a Binary Tree Node to Another/README_EN.md index 95c0493b7a58a..0bf40a02fec6c 100644 --- a/solution/2000-2099/2096.Step-By-Step Directions From a Binary Tree Node to Another/README_EN.md +++ b/solution/2000-2099/2096.Step-By-Step Directions From a Binary Tree Node to Another/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -97,8 +97,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -171,8 +169,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -231,16 +227,6 @@ public: }; ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2097.Valid Arrangement of Pairs/README.md b/solution/2000-2099/2097.Valid Arrangement of Pairs/README.md index 16ded451275df..96d4b285c0aca 100644 --- a/solution/2000-2099/2097.Valid Arrangement of Pairs/README.md +++ b/solution/2000-2099/2097.Valid Arrangement of Pairs/README.md @@ -64,38 +64,4 @@ end1 = 1 == 1 = start2 ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2000-2099/2097.Valid Arrangement of Pairs/README_EN.md b/solution/2000-2099/2097.Valid Arrangement of Pairs/README_EN.md index 7483b2c6dcca9..41d6ab9e9b37f 100644 --- a/solution/2000-2099/2097.Valid Arrangement of Pairs/README_EN.md +++ b/solution/2000-2099/2097.Valid Arrangement of Pairs/README_EN.md @@ -60,30 +60,4 @@ end1 = 1 == 1 = start2 ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2000-2099/2098.Subsequence of Size K With the Largest Even Sum/README.md b/solution/2000-2099/2098.Subsequence of Size K With the Largest Even Sum/README.md index 91f671004203c..2358a5a847ae1 100644 --- a/solution/2000-2099/2098.Subsequence of Size K With the Largest Even Sum/README.md +++ b/solution/2000-2099/2098.Subsequence of Size K With the Largest Even Sum/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 我们注意到,题目选取的是子序列,因此我们可以考虑先对数组进行排序。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def largestEvenSum(self, nums: List[int], k: int) -> int: @@ -98,10 +92,6 @@ class Solution: return -1 if ans % 2 else ans ``` -### **Java** - - - ```java class Solution { public long largestEvenSum(int[] nums, int k) { @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +163,6 @@ public: }; ``` -### **Go** - ```go func largestEvenSum(nums []int, k int) int64 { sort.Ints(nums) @@ -213,16 +199,6 @@ func largestEvenSum(nums []int, k int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2098.Subsequence of Size K With the Largest Even Sum/README_EN.md b/solution/2000-2099/2098.Subsequence of Size K With the Largest Even Sum/README_EN.md index aa618e0f2282d..c3e717cb930e1 100644 --- a/solution/2000-2099/2098.Subsequence of Size K With the Largest Even Sum/README_EN.md +++ b/solution/2000-2099/2098.Subsequence of Size K With the Largest Even Sum/README_EN.md @@ -49,9 +49,9 @@ No subsequence of nums with length 1 has an even sum. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return -1 if ans % 2 else ans ``` -### **Java** - ```java class Solution { public long largestEvenSum(int[] nums, int k) { @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +148,6 @@ public: }; ``` -### **Go** - ```go func largestEvenSum(nums []int, k int) int64 { sort.Ints(nums) @@ -190,16 +184,6 @@ func largestEvenSum(nums []int, k int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README.md b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README.md index f8964e19694ef..f7f9335b869de 100644 --- a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README.md +++ b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README.md @@ -50,18 +50,10 @@ ## 解法 - - -两次排序。 - -先按照数字大小**对下标进行排序**,然后取出倒数 k 个下标(对应的数字是数组中前 k 个数字),对下标进行排序。最后将排序后的下标依次映射成数字,得到结果数组。 +### 方法一 -### **Python3** - - - ```python class Solution: def maxSubsequence(self, nums: List[int], k: int) -> List[int]: @@ -70,10 +62,6 @@ class Solution: return [nums[i] for i in sorted(idx[-k:])] ``` -### **Java** - - - ```java class Solution { public int[] maxSubsequence(int[] nums, int k) { @@ -97,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +103,6 @@ public: }; ``` -### **Go** - ```go func maxSubsequence(nums []int, k int) []int { idx := make([]int, len(nums)) @@ -135,18 +119,6 @@ func maxSubsequence(nums []int, k int) []int { } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README_EN.md b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README_EN.md index 46bc97e76bcaf..a4cbf061e205f 100644 --- a/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README_EN.md +++ b/solution/2000-2099/2099.Find Subsequence of Length K With the Largest Sum/README_EN.md @@ -49,9 +49,9 @@ Another possible subsequence is [4, 3]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return [nums[i] for i in sorted(idx[-k:])] ``` -### **Java** - ```java class Solution { public int[] maxSubsequence(int[] nums, int k) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +102,6 @@ public: }; ``` -### **Go** - ```go func maxSubsequence(nums []int, k int) []int { idx := make([]int, len(nums)) @@ -124,16 +118,6 @@ func maxSubsequence(nums []int, k int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2100.Find Good Days to Rob the Bank/README.md b/solution/2100-2199/2100.Find Good Days to Rob the Bank/README.md index 5963316f39031..4d70259900f62 100644 --- a/solution/2100-2199/2100.Find Good Days to Rob the Bank/README.md +++ b/solution/2100-2199/2100.Find Good Days to Rob the Bank/README.md @@ -63,16 +63,10 @@ ## 解法 - - -left, right 分别记录左右符合要求的天数。 +### 方法一 -### **Python3** - - - ```python class Solution: def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]: @@ -89,10 +83,6 @@ class Solution: return [i for i in range(n) if time <= min(left[i], right[i])] ``` -### **Java** - - - ```java class Solution { public List goodDaysToRobBank(int[] security, int time) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +136,6 @@ public: }; ``` -### **Go** - ```go func goodDaysToRobBank(security []int, time int) []int { n := len(security) @@ -178,8 +164,6 @@ func goodDaysToRobBank(security []int, time int) []int { } ``` -### **TypeScript** - ```ts function goodDaysToRobBank(security: number[], time: number): number[] { const n = security.length; @@ -206,8 +190,6 @@ function goodDaysToRobBank(security: number[], time: number): number[] { } ``` -### **Rust** - ```rust use std::cmp::Ordering; @@ -242,10 +224,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2100.Find Good Days to Rob the Bank/README_EN.md b/solution/2100-2199/2100.Find Good Days to Rob the Bank/README_EN.md index 7a8b08208983f..05f0a77f78faf 100644 --- a/solution/2100-2199/2100.Find Good Days to Rob the Bank/README_EN.md +++ b/solution/2100-2199/2100.Find Good Days to Rob the Bank/README_EN.md @@ -59,9 +59,9 @@ Thus, no day is a good day to rob the bank, so return an empty list. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,8 +79,6 @@ class Solution: return [i for i in range(n) if time <= min(left[i], right[i])] ``` -### **Java** - ```java class Solution { public List goodDaysToRobBank(int[] security, int time) { @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +132,6 @@ public: }; ``` -### **Go** - ```go func goodDaysToRobBank(security []int, time int) []int { n := len(security) @@ -166,8 +160,6 @@ func goodDaysToRobBank(security []int, time int) []int { } ``` -### **TypeScript** - ```ts function goodDaysToRobBank(security: number[], time: number): number[] { const n = security.length; @@ -194,8 +186,6 @@ function goodDaysToRobBank(security: number[], time: number): number[] { } ``` -### **Rust** - ```rust use std::cmp::Ordering; @@ -230,10 +220,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2101.Detonate the Maximum Bombs/README.md b/solution/2100-2199/2101.Detonate the Maximum Bombs/README.md index 6dd01d1a89ca6..9a3d4c1241b91 100644 --- a/solution/2100-2199/2101.Detonate the Maximum Bombs/README.md +++ b/solution/2100-2199/2101.Detonate the Maximum Bombs/README.md @@ -65,18 +65,12 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 枚举每个炸弹 k 作为起始引爆点,BFS 搜索能影响到的所有炸弹的数量,取其最大值。 -### **Python3** - - - ```python class Solution: def maximumDetonation(self, bombs: List[List[int]]) -> int: @@ -110,10 +104,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[][] bombs; @@ -161,8 +151,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -204,8 +192,6 @@ public: }; ``` -### **Go** - ```go func maximumDetonation(bombs [][]int) int { check := func(i, j int) bool { @@ -248,18 +234,6 @@ func maximumDetonation(bombs [][]int) int { } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2101.Detonate the Maximum Bombs/README_EN.md b/solution/2100-2199/2101.Detonate the Maximum Bombs/README_EN.md index 96fbd587e0b03..629240c1942e4 100644 --- a/solution/2100-2199/2101.Detonate the Maximum Bombs/README_EN.md +++ b/solution/2100-2199/2101.Detonate the Maximum Bombs/README_EN.md @@ -58,12 +58,10 @@ Thus all 5 bombs are detonated. ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def maximumDetonation(self, bombs: List[List[int]]) -> int: @@ -97,8 +95,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[][] bombs; @@ -146,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -189,8 +183,6 @@ public: }; ``` -### **Go** - ```go func maximumDetonation(bombs [][]int) int { check := func(i, j int) bool { @@ -233,16 +225,6 @@ func maximumDetonation(bombs [][]int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README.md b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README.md index cd7725808bcc1..8bbd7d9edebc4 100644 --- a/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README.md +++ b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README.md @@ -79,38 +79,4 @@ tracker.get(); // 从好到坏的景点为:branford, orlando, alp ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README_EN.md b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README_EN.md index fb6f7d8d4c853..935d499c8b0b1 100644 --- a/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README_EN.md +++ b/solution/2100-2199/2102.Sequentially Ordinal Rank Tracker/README_EN.md @@ -75,30 +75,4 @@ tracker.get(); // Sorted locations: branford, orlando, alpine, alps ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2100-2199/2103.Rings and Rods/README.md b/solution/2100-2199/2103.Rings and Rods/README.md index f32271565383e..00a9144d3d4a0 100644 --- a/solution/2100-2199/2103.Rings and Rods/README.md +++ b/solution/2100-2199/2103.Rings and Rods/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 我们可以用一个长度为 $10$ 的数组 $mask$ 来表示每根杆上的环的颜色情况,其中 $mask[i]$ 表示第 $i$ 根杆上的环的颜色情况,如果第 $i$ 根杆上有红色、绿色、蓝色的环,那么 $mask[i]$ 的二进制表示为 $111$,即 $mask[i] = 7$。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def countPoints(self, rings: str) -> int: @@ -96,10 +90,6 @@ class Solution: return mask.count(7) ``` -### **Java** - - - ```java class Solution { public int countPoints(String rings) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func countPoints(rings string) (ans int) { d := ['Z']int{'R': 1, 'G': 2, 'B': 4} @@ -162,8 +148,6 @@ func countPoints(rings string) (ans int) { } ``` -### **TypeScript** - ```ts function countPoints(rings: string): number { const idx = (c: string) => c.charCodeAt(0) - 'A'.charCodeAt(0); @@ -181,18 +165,6 @@ function countPoints(rings: string): number { } ``` -```ts -function countPoints(rings: string): number { - let c = 0; - for (let i = 0; i <= 9; i++) { - if (rings.includes('B' + i) && rings.includes('R' + i) && rings.includes('G' + i)) c++; - } - return c; -} -``` - -### **Rust** - ```rust impl Solution { pub fn count_points(rings: String) -> i32 { @@ -219,8 +191,6 @@ impl Solution { } ``` -### **C** - ```c int countPoints(char* rings) { int d['Z']; @@ -249,10 +219,22 @@ int countPoints(char* rings) { } ``` -### **...** + + +### 方法二 -``` + +```ts +function countPoints(rings: string): number { + let c = 0; + for (let i = 0; i <= 9; i++) { + if (rings.includes('B' + i) && rings.includes('R' + i) && rings.includes('G' + i)) c++; + } + return c; +} ``` + + diff --git a/solution/2100-2199/2103.Rings and Rods/README_EN.md b/solution/2100-2199/2103.Rings and Rods/README_EN.md index beb4526729f73..9bab0e77fe75e 100644 --- a/solution/2100-2199/2103.Rings and Rods/README_EN.md +++ b/solution/2100-2199/2103.Rings and Rods/README_EN.md @@ -62,7 +62,7 @@ Only one ring is given. Thus, no rods have all three colors. ## Solutions -**Solution 1: Bit Manipulation** +### Solution 1: Bit Manipulation We can use an array $mask$ of length $10$ to represent the color situation of the rings on each rod, where $mask[i]$ represents the color situation of the ring on the $i$th rod. If there are red, green, and blue rings on the $i$th rod, then the binary representation of $mask[i]$ is $111$, that is, $mask[i] = 7$. @@ -74,8 +74,6 @@ The time complexity is $O(n)$, and the space complexity is $O(|\Sigma|)$, where -### **Python3** - ```python class Solution: def countPoints(self, rings: str) -> int: @@ -88,8 +86,6 @@ class Solution: return mask.count(7) ``` -### **Java** - ```java class Solution { public int countPoints(String rings) { @@ -114,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +126,6 @@ public: }; ``` -### **Go** - ```go func countPoints(rings string) (ans int) { d := ['Z']int{'R': 1, 'G': 2, 'B': 4} @@ -152,8 +144,6 @@ func countPoints(rings string) (ans int) { } ``` -### **TypeScript** - ```ts function countPoints(rings: string): number { const idx = (c: string) => c.charCodeAt(0) - 'A'.charCodeAt(0); @@ -171,18 +161,6 @@ function countPoints(rings: string): number { } ``` -```ts -function countPoints(rings: string): number { - let c = 0; - for (let i = 0; i <= 9; i++) { - if (rings.includes('B' + i) && rings.includes('R' + i) && rings.includes('G' + i)) c++; - } - return c; -} -``` - -### **Rust** - ```rust impl Solution { pub fn count_points(rings: String) -> i32 { @@ -209,8 +187,6 @@ impl Solution { } ``` -### **C** - ```c int countPoints(char* rings) { int d['Z']; @@ -239,10 +215,22 @@ int countPoints(char* rings) { } ``` -### **...** + -``` +### Solution 2 + + +```ts +function countPoints(rings: string): number { + let c = 0; + for (let i = 0; i <= 9; i++) { + if (rings.includes('B' + i) && rings.includes('R' + i) && rings.includes('G' + i)) c++; + } + return c; +} ``` + + diff --git a/solution/2100-2199/2104.Sum of Subarray Ranges/README.md b/solution/2100-2199/2104.Sum of Subarray Ranges/README.md index e690b404466f5..200da2cd69e64 100644 --- a/solution/2100-2199/2104.Sum of Subarray Ranges/README.md +++ b/solution/2100-2199/2104.Sum of Subarray Ranges/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 循环遍历 $i$,作为子数组的起始位置。对于每个 $i$,遍历每个 $j$ 作为子数组的终止位置,此过程中不断求解子数组的最大值、最小值,然后累加差值到结果 `ans` 中。 @@ -76,24 +74,8 @@ 时间复杂度 $O(n^2)$。 -**方法二:单调栈** - -枚举每个元素 `nums[i]` 作为最大值出现在了多少个子数组中,以及作为最小值出现在多少个子数组中。 - -其中 `nums[i]` 作为最大值的贡献为正,作为最小值的贡献为负。 - -我们以 `nums[i]` 作为最大值为例。找出左侧第一个比 `nums[i]` 大的位置 `left[i]`,右侧第一个大于等于 `nums[i]` 的位置 `right[i]`。计算每个 `nums[i]` 的贡献 $(i - left[i])\times (right[i] - i)\times arr[i]$,累加得到结果。 - -时间复杂度 $O(n)$。 - -相似题目:[907. 子数组的最小值之和](/solution/0900-0999/0907.Sum%20of%20Subarray%20Minimums/README.md) - -### **Python3** - - - ```python class Solution: def subArrayRanges(self, nums: List[int]) -> int: @@ -107,6 +89,111 @@ class Solution: return ans ``` +```java +class Solution { + public long subArrayRanges(int[] nums) { + long ans = 0; + int n = nums.length; + for (int i = 0; i < n - 1; ++i) { + int mi = nums[i], mx = nums[i]; + for (int j = i + 1; j < n; ++j) { + mi = Math.min(mi, nums[j]); + mx = Math.max(mx, nums[j]); + ans += (mx - mi); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + long long subArrayRanges(vector& nums) { + long long ans = 0; + int n = nums.size(); + for (int i = 0; i < n - 1; ++i) { + int mi = nums[i], mx = nums[i]; + for (int j = i + 1; j < n; ++j) { + mi = min(mi, nums[j]); + mx = max(mx, nums[j]); + ans += (mx - mi); + } + } + return ans; + } +}; +``` + +```go +func subArrayRanges(nums []int) int64 { + var ans int64 + n := len(nums) + for i := 0; i < n-1; i++ { + mi, mx := nums[i], nums[i] + for j := i + 1; j < n; j++ { + mi = min(mi, nums[j]) + mx = max(mx, nums[j]) + ans += (int64)(mx - mi) + } + } + return ans +} +``` + +```ts +function subArrayRanges(nums: number[]): number { + const n = nums.length; + let res = 0; + for (let i = 0; i < n - 1; i++) { + let min = nums[i]; + let max = nums[i]; + for (let j = i + 1; j < n; j++) { + min = Math.min(min, nums[j]); + max = Math.max(max, nums[j]); + res += max - min; + } + } + return res; +} +``` + +```rust +impl Solution { + pub fn sub_array_ranges(nums: Vec) -> i64 { + let n = nums.len(); + let mut res: i64 = 0; + for i in 1..n { + let mut min = nums[i - 1]; + let mut max = nums[i - 1]; + for j in i..n { + min = min.min(nums[j]); + max = max.max(nums[j]); + res += (max - min) as i64; + } + } + res + } +} +``` + + + +### 方法二:单调栈 + +枚举每个元素 `nums[i]` 作为最大值出现在了多少个子数组中,以及作为最小值出现在多少个子数组中。 + +其中 `nums[i]` 作为最大值的贡献为正,作为最小值的贡献为负。 + +我们以 `nums[i]` 作为最大值为例。找出左侧第一个比 `nums[i]` 大的位置 `left[i]`,右侧第一个大于等于 `nums[i]` 的位置 `right[i]`。计算每个 `nums[i]` 的贡献 $(i - left[i])\times (right[i] - i)\times arr[i]$,累加得到结果。 + +时间复杂度 $O(n)$。 + +相似题目:[907. 子数组的最小值之和](/solution/0900-0999/0907.Sum%20of%20Subarray%20Minimums/README.md) + + + ```python class Solution: def subArrayRanges(self, nums: List[int]) -> int: @@ -135,28 +222,6 @@ class Solution: return mx + mi ``` -### **Java** - - - -```java -class Solution { - public long subArrayRanges(int[] nums) { - long ans = 0; - int n = nums.length; - for (int i = 0; i < n - 1; ++i) { - int mi = nums[i], mx = nums[i]; - for (int j = i + 1; j < n; ++j) { - mi = Math.min(mi, nums[j]); - mx = Math.max(mx, nums[j]); - ans += (mx - mi); - } - } - return ans; - } -} -``` - ```java class Solution { public long subArrayRanges(int[] nums) { @@ -203,27 +268,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - long long subArrayRanges(vector& nums) { - long long ans = 0; - int n = nums.size(); - for (int i = 0; i < n - 1; ++i) { - int mi = nums[i], mx = nums[i]; - for (int j = i + 1; j < n; ++j) { - mi = min(mi, nums[j]); - mx = max(mx, nums[j]); - ans += (mx - mi); - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -259,24 +303,6 @@ public: }; ``` -### **Go** - -```go -func subArrayRanges(nums []int) int64 { - var ans int64 - n := len(nums) - for i := 0; i < n-1; i++ { - mi, mx := nums[i], nums[i] - for j := i + 1; j < n; j++ { - mi = min(mi, nums[j]) - mx = max(mx, nums[j]) - ans += (int64)(mx - mi) - } - } - return ans -} -``` - ```go func subArrayRanges(nums []int) int64 { f := func(nums []int) int64 { @@ -322,50 +348,6 @@ func subArrayRanges(nums []int) int64 { } ``` -### **TypeScript** - -```ts -function subArrayRanges(nums: number[]): number { - const n = nums.length; - let res = 0; - for (let i = 0; i < n - 1; i++) { - let min = nums[i]; - let max = nums[i]; - for (let j = i + 1; j < n; j++) { - min = Math.min(min, nums[j]); - max = Math.max(max, nums[j]); - res += max - min; - } - } - return res; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn sub_array_ranges(nums: Vec) -> i64 { - let n = nums.len(); - let mut res: i64 = 0; - for i in 1..n { - let mut min = nums[i - 1]; - let mut max = nums[i - 1]; - for j in i..n { - min = min.min(nums[j]); - max = max.max(nums[j]); - res += (max - min) as i64; - } - } - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2104.Sum of Subarray Ranges/README_EN.md b/solution/2100-2199/2104.Sum of Subarray Ranges/README_EN.md index 5875af76967ea..45b3218fadd56 100644 --- a/solution/2100-2199/2104.Sum of Subarray Ranges/README_EN.md +++ b/solution/2100-2199/2104.Sum of Subarray Ranges/README_EN.md @@ -61,9 +61,9 @@ So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,6 +78,101 @@ class Solution: return ans ``` +```java +class Solution { + public long subArrayRanges(int[] nums) { + long ans = 0; + int n = nums.length; + for (int i = 0; i < n - 1; ++i) { + int mi = nums[i], mx = nums[i]; + for (int j = i + 1; j < n; ++j) { + mi = Math.min(mi, nums[j]); + mx = Math.max(mx, nums[j]); + ans += (mx - mi); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + long long subArrayRanges(vector& nums) { + long long ans = 0; + int n = nums.size(); + for (int i = 0; i < n - 1; ++i) { + int mi = nums[i], mx = nums[i]; + for (int j = i + 1; j < n; ++j) { + mi = min(mi, nums[j]); + mx = max(mx, nums[j]); + ans += (mx - mi); + } + } + return ans; + } +}; +``` + +```go +func subArrayRanges(nums []int) int64 { + var ans int64 + n := len(nums) + for i := 0; i < n-1; i++ { + mi, mx := nums[i], nums[i] + for j := i + 1; j < n; j++ { + mi = min(mi, nums[j]) + mx = max(mx, nums[j]) + ans += (int64)(mx - mi) + } + } + return ans +} +``` + +```ts +function subArrayRanges(nums: number[]): number { + const n = nums.length; + let res = 0; + for (let i = 0; i < n - 1; i++) { + let min = nums[i]; + let max = nums[i]; + for (let j = i + 1; j < n; j++) { + min = Math.min(min, nums[j]); + max = Math.max(max, nums[j]); + res += max - min; + } + } + return res; +} +``` + +```rust +impl Solution { + pub fn sub_array_ranges(nums: Vec) -> i64 { + let n = nums.len(); + let mut res: i64 = 0; + for i in 1..n { + let mut min = nums[i - 1]; + let mut max = nums[i - 1]; + for j in i..n { + min = min.min(nums[j]); + max = max.max(nums[j]); + res += (max - min) as i64; + } + } + res + } +} +``` + + + +### Solution 2 + + + ```python class Solution: def subArrayRanges(self, nums: List[int]) -> int: @@ -106,26 +201,6 @@ class Solution: return mx + mi ``` -### **Java** - -```java -class Solution { - public long subArrayRanges(int[] nums) { - long ans = 0; - int n = nums.length; - for (int i = 0; i < n - 1; ++i) { - int mi = nums[i], mx = nums[i]; - for (int j = i + 1; j < n; ++j) { - mi = Math.min(mi, nums[j]); - mx = Math.max(mx, nums[j]); - ans += (mx - mi); - } - } - return ans; - } -} -``` - ```java class Solution { public long subArrayRanges(int[] nums) { @@ -172,27 +247,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - long long subArrayRanges(vector& nums) { - long long ans = 0; - int n = nums.size(); - for (int i = 0; i < n - 1; ++i) { - int mi = nums[i], mx = nums[i]; - for (int j = i + 1; j < n; ++j) { - mi = min(mi, nums[j]); - mx = max(mx, nums[j]); - ans += (mx - mi); - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -228,24 +282,6 @@ public: }; ``` -### **Go** - -```go -func subArrayRanges(nums []int) int64 { - var ans int64 - n := len(nums) - for i := 0; i < n-1; i++ { - mi, mx := nums[i], nums[i] - for j := i + 1; j < n; j++ { - mi = min(mi, nums[j]) - mx = max(mx, nums[j]) - ans += (int64)(mx - mi) - } - } - return ans -} -``` - ```go func subArrayRanges(nums []int) int64 { f := func(nums []int) int64 { @@ -291,50 +327,6 @@ func subArrayRanges(nums []int) int64 { } ``` -### **TypeScript** - -```ts -function subArrayRanges(nums: number[]): number { - const n = nums.length; - let res = 0; - for (let i = 0; i < n - 1; i++) { - let min = nums[i]; - let max = nums[i]; - for (let j = i + 1; j < n; j++) { - min = Math.min(min, nums[j]); - max = Math.max(max, nums[j]); - res += max - min; - } - } - return res; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn sub_array_ranges(nums: Vec) -> i64 { - let n = nums.len(); - let mut res: i64 = 0; - for i in 1..n { - let mut min = nums[i - 1]; - let mut max = nums[i - 1]; - for j in i..n { - min = min.min(nums[j]); - max = max.max(nums[j]); - res += (max - min) as i64; - } - } - res - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2105.Watering Plants II/README.md b/solution/2100-2199/2105.Watering Plants II/README.md index 1e075d269b21d..109d0d89df1f5 100644 --- a/solution/2100-2199/2105.Watering Plants II/README.md +++ b/solution/2100-2199/2105.Watering Plants II/README.md @@ -70,16 +70,10 @@ ## 解法 - - -双指针直接模拟即可。 +### 方法一 -### **Python3** - - - ```python class Solution: def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int: @@ -106,10 +100,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumRefill(int[] plants, int capacityA, int capacityB) { @@ -142,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -174,8 +162,6 @@ public: }; ``` -### **Go** - ```go func minimumRefill(plants []int, capacityA int, capacityB int) int { i, j := 0, len(plants)-1 @@ -206,18 +192,6 @@ func minimumRefill(plants []int, capacityA int, capacityB int) int { } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2105.Watering Plants II/README_EN.md b/solution/2100-2199/2105.Watering Plants II/README_EN.md index 33c71223c4fe2..b9fc39ce35ce9 100644 --- a/solution/2100-2199/2105.Watering Plants II/README_EN.md +++ b/solution/2100-2199/2105.Watering Plants II/README_EN.md @@ -67,9 +67,9 @@ So, the total number of times they have to refill is 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -97,8 +97,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumRefill(int[] plants, int capacityA, int capacityB) { @@ -131,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +159,6 @@ public: }; ``` -### **Go** - ```go func minimumRefill(plants []int, capacityA int, capacityB int) int { i, j := 0, len(plants)-1 @@ -195,16 +189,6 @@ func minimumRefill(plants []int, capacityA int, capacityB int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2106.Maximum Fruits Harvested After at Most K Steps/README.md b/solution/2100-2199/2106.Maximum Fruits Harvested After at Most K Steps/README.md index 7dac7b9250e08..bb4589e4d206e 100644 --- a/solution/2100-2199/2106.Maximum Fruits Harvested After at Most K Steps/README.md +++ b/solution/2100-2199/2106.Maximum Fruits Harvested After at Most K Steps/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们不妨假设移动的位置区间为 $[l,r]$,开始位置为 $startPos$,来看看如何算出移动的最小步数。根据 $startPos$ 所处的位置,我们可以分为三种情况: @@ -91,10 +89,6 @@ -### **Python3** - - - ```python class Solution: def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int: @@ -114,10 +108,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxTotalFruits(int[][] fruits, int startPos, int k) { @@ -138,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func maxTotalFruits(fruits [][]int, startPos int, k int) (ans int) { var s, i int @@ -182,8 +168,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function maxTotalFruits(fruits: number[][], startPos: number, k: number): number { let ans = 0; @@ -206,10 +190,6 @@ function maxTotalFruits(fruits: number[][], startPos: number, k: number): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2106.Maximum Fruits Harvested After at Most K Steps/README_EN.md b/solution/2100-2199/2106.Maximum Fruits Harvested After at Most K Steps/README_EN.md index 828d550a93e15..31d1ee6d3f646 100644 --- a/solution/2100-2199/2106.Maximum Fruits Harvested After at Most K Steps/README_EN.md +++ b/solution/2100-2199/2106.Maximum Fruits Harvested After at Most K Steps/README_EN.md @@ -61,9 +61,9 @@ You can move at most k = 2 steps and cannot reach any position with fruits. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxTotalFruits(int[][] fruits, int startPos, int k) { @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +122,6 @@ public: }; ``` -### **Go** - ```go func maxTotalFruits(fruits [][]int, startPos int, k int) (ans int) { var s, i int @@ -150,8 +144,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function maxTotalFruits(fruits: number[][], startPos: number, k: number): number { let ans = 0; @@ -174,10 +166,6 @@ function maxTotalFruits(fruits: number[][], startPos: number, k: number): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/README.md b/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/README.md index d162597029d47..fab9faee9aa31 100644 --- a/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/README.md +++ b/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:滑动窗口 + 哈希表** +### 方法一:滑动窗口 + 哈希表 我们可以维护一个大小为 $k$ 的滑动窗口,窗口外的糖果为自己的,窗口内的 $k$ 个糖果分给妹妹和妈妈。我们可以用哈希表 $cnt$ 记录窗口外的糖果口味以及对应的数量。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def shareCandies(self, candies: List[int], k: int) -> int: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int shareCandies(int[] candies, int k) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func shareCandies(candies []int, k int) (ans int) { cnt := map[int]int{} @@ -161,7 +147,24 @@ func shareCandies(candies []int, k int) (ans int) { } ``` -### **Rust** +```ts +function shareCandies(candies: number[], k: number): number { + const cnt: Map = new Map(); + for (const x of candies.slice(k)) { + cnt.set(x, (cnt.get(x) || 0) + 1); + } + let ans = cnt.size; + for (let i = k; i < candies.length; ++i) { + cnt.set(candies[i - k], (cnt.get(candies[i - k]) || 0) + 1); + cnt.set(candies[i], (cnt.get(candies[i]) || 0) - 1); + if (cnt.get(candies[i]) === 0) { + cnt.delete(candies[i]); + } + ans = Math.max(ans, cnt.size); + } + return ans; +} +``` ```rust use std::collections::HashMap; @@ -194,31 +197,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function shareCandies(candies: number[], k: number): number { - const cnt: Map = new Map(); - for (const x of candies.slice(k)) { - cnt.set(x, (cnt.get(x) || 0) + 1); - } - let ans = cnt.size; - for (let i = k; i < candies.length; ++i) { - cnt.set(candies[i - k], (cnt.get(candies[i - k]) || 0) + 1); - cnt.set(candies[i], (cnt.get(candies[i]) || 0) - 1); - if (cnt.get(candies[i]) === 0) { - cnt.delete(candies[i]); - } - ans = Math.max(ans, cnt.size); - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/README_EN.md b/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/README_EN.md index 3a678668ff9d1..a9a1f5caf22ef 100644 --- a/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/README_EN.md +++ b/solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/README_EN.md @@ -54,7 +54,7 @@ There are 3 unique flavors, so return 3. ## Solutions -**Solution 1: Sliding Window + Hash Table** +### Solution 1: Sliding Window + Hash Table We can maintain a sliding window of size $k$, where the candies outside the window are for ourselves, and the $k$ candies inside the window are shared with our sister and mother. We can use a hash table $cnt$ to record the flavors of the candies outside the window and their corresponding quantities. @@ -68,8 +68,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def shareCandies(self, candies: List[int], k: int) -> int: @@ -84,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int shareCandies(int[] candies, int k) { @@ -107,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +125,6 @@ public: }; ``` -### **Go** - ```go func shareCandies(candies []int, k int) (ans int) { cnt := map[int]int{} @@ -152,7 +144,24 @@ func shareCandies(candies []int, k int) (ans int) { } ``` -### **Rust** +```ts +function shareCandies(candies: number[], k: number): number { + const cnt: Map = new Map(); + for (const x of candies.slice(k)) { + cnt.set(x, (cnt.get(x) || 0) + 1); + } + let ans = cnt.size; + for (let i = k; i < candies.length; ++i) { + cnt.set(candies[i - k], (cnt.get(candies[i - k]) || 0) + 1); + cnt.set(candies[i], (cnt.get(candies[i]) || 0) - 1); + if (cnt.get(candies[i]) === 0) { + cnt.delete(candies[i]); + } + ans = Math.max(ans, cnt.size); + } + return ans; +} +``` ```rust use std::collections::HashMap; @@ -185,31 +194,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function shareCandies(candies: number[], k: number): number { - const cnt: Map = new Map(); - for (const x of candies.slice(k)) { - cnt.set(x, (cnt.get(x) || 0) + 1); - } - let ans = cnt.size; - for (let i = k; i < candies.length; ++i) { - cnt.set(candies[i - k], (cnt.get(candies[i - k]) || 0) + 1); - cnt.set(candies[i], (cnt.get(candies[i]) || 0) - 1); - if (cnt.get(candies[i]) === 0) { - cnt.delete(candies[i]); - } - ans = Math.max(ans, cnt.size); - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2108.Find First Palindromic String in the Array/README.md b/solution/2100-2199/2108.Find First Palindromic String in the Array/README.md index 70b613ac9cdd0..cf2fe0cea212c 100644 --- a/solution/2100-2199/2108.Find First Palindromic String in the Array/README.md +++ b/solution/2100-2199/2108.Find First Palindromic String in the Array/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 遍历数组 `words`,对于每个字符串 `w`,判断其是否为回文字符串,如果是,则返回 `w`,否则继续遍历。 @@ -58,20 +56,12 @@ -### **Python3** - - - ```python class Solution: def firstPalindrome(self, words: List[str]) -> str: return next((w for w in words if w == w[::-1]), "") ``` -### **Java** - - - ```java class Solution { public String firstPalindrome(String[] words) { @@ -91,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func firstPalindrome(words []string) string { for _, w := range words { @@ -132,8 +118,6 @@ func firstPalindrome(words []string) string { } ``` -### **TypeScript** - ```ts function firstPalindrome(words: string[]): string { for (const word of words) { @@ -154,8 +138,6 @@ function firstPalindrome(words: string[]): string { } ``` -### **Rust** - ```rust impl Solution { pub fn first_palindrome(words: Vec) -> String { @@ -179,8 +161,6 @@ impl Solution { } ``` -### **C** - ```c char* firstPalindrome(char** words, int wordsSize) { for (int i = 0; i < wordsSize; i++) { @@ -201,10 +181,6 @@ char* firstPalindrome(char** words, int wordsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2108.Find First Palindromic String in the Array/README_EN.md b/solution/2100-2199/2108.Find First Palindromic String in the Array/README_EN.md index e468915f37ec9..f48560b35696e 100644 --- a/solution/2100-2199/2108.Find First Palindromic String in the Array/README_EN.md +++ b/solution/2100-2199/2108.Find First Palindromic String in the Array/README_EN.md @@ -45,9 +45,9 @@ Note that "racecar" is also palindromic, but it is not the first. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return next((w for w in words if w == w[::-1]), "") ``` -### **Java** - ```java class Solution { public String firstPalindrome(String[] words) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +94,6 @@ public: }; ``` -### **Go** - ```go func firstPalindrome(words []string) string { for _, w := range words { @@ -117,8 +111,6 @@ func firstPalindrome(words []string) string { } ``` -### **TypeScript** - ```ts function firstPalindrome(words: string[]): string { for (const word of words) { @@ -139,8 +131,6 @@ function firstPalindrome(words: string[]): string { } ``` -### **Rust** - ```rust impl Solution { pub fn first_palindrome(words: Vec) -> String { @@ -164,8 +154,6 @@ impl Solution { } ``` -### **C** - ```c char* firstPalindrome(char** words, int wordsSize) { for (int i = 0; i < wordsSize; i++) { @@ -186,10 +174,6 @@ char* firstPalindrome(char** words, int wordsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2109.Adding Spaces to a String/README.md b/solution/2100-2199/2109.Adding Spaces to a String/README.md index 23ae7bd6c504a..831b82228fcd8 100644 --- a/solution/2100-2199/2109.Adding Spaces to a String/README.md +++ b/solution/2100-2199/2109.Adding Spaces to a String/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们可以用双指针 $i$ 和 $j$ 分别指向字符串 $s$ 和数组 $spaces$ 的头部,然后从头到尾遍历字符串 $s$,当 $i$ 等于 $spaces[j]$ 时,我们往结果字符串中添加一个空格,然后 $j$ 自增 1。接下来,我们将 $s[i]$ 添加到结果字符串中,然后 $i$ 自增 1。继续这个过程,直到遍历完字符串 $s$。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def addSpaces(self, s: str, spaces: List[int]) -> str: @@ -88,24 +82,6 @@ class Solution: return ''.join(ans) ``` -```python -class Solution: - def addSpaces(self, s: str, spaces: List[int]) -> str: - ans = [] - i, j = len(s) - 1, len(spaces) - 1 - while i >= 0: - ans.append(s[i]) - if j >= 0 and i == spaces[j]: - ans.append(' ') - j -= 1 - i -= 1 - return ''.join(ans[::-1]) -``` - -### **Java** - - - ```java class Solution { public String addSpaces(String s, int[] spaces) { @@ -122,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +115,6 @@ public: }; ``` -### **Go** - ```go func addSpaces(s string, spaces []int) string { var ans []byte @@ -157,10 +129,6 @@ func addSpaces(s string, spaces []int) string { } ``` -### **TypeScript** - - - ```ts function addSpaces(s: string, spaces: number[]): string { let ans = ''; @@ -175,10 +143,26 @@ function addSpaces(s: string, spaces: number[]): string { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def addSpaces(self, s: str, spaces: List[int]) -> str: + ans = [] + i, j = len(s) - 1, len(spaces) - 1 + while i >= 0: + ans.append(s[i]) + if j >= 0 and i == spaces[j]: + ans.append(' ') + j -= 1 + i -= 1 + return ''.join(ans[::-1]) ``` + + diff --git a/solution/2100-2199/2109.Adding Spaces to a String/README_EN.md b/solution/2100-2199/2109.Adding Spaces to a String/README_EN.md index 219ee64045ee8..a654289d85cc6 100644 --- a/solution/2100-2199/2109.Adding Spaces to a String/README_EN.md +++ b/solution/2100-2199/2109.Adding Spaces to a String/README_EN.md @@ -55,9 +55,9 @@ We are also able to place spaces before the first character of the string. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,22 +72,6 @@ class Solution: return ''.join(ans) ``` -```python -class Solution: - def addSpaces(self, s: str, spaces: List[int]) -> str: - ans = [] - i, j = len(s) - 1, len(spaces) - 1 - while i >= 0: - ans.append(s[i]) - if j >= 0 and i == spaces[j]: - ans.append(' ') - j -= 1 - i -= 1 - return ''.join(ans[::-1]) -``` - -### **Java** - ```java class Solution { public String addSpaces(String s, int[] spaces) { @@ -104,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +105,6 @@ public: }; ``` -### **Go** - ```go func addSpaces(s string, spaces []int) string { var ans []byte @@ -139,8 +119,6 @@ func addSpaces(s string, spaces []int) string { } ``` -### **TypeScript** - ```ts function addSpaces(s: string, spaces: number[]): string { let ans = ''; @@ -155,10 +133,26 @@ function addSpaces(s: string, spaces: number[]): string { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def addSpaces(self, s: str, spaces: List[int]) -> str: + ans = [] + i, j = len(s) - 1, len(spaces) - 1 + while i >= 0: + ans.append(s[i]) + if j >= 0 and i == spaces[j]: + ans.append(' ') + j -= 1 + i -= 1 + return ''.join(ans[::-1]) ``` + + diff --git a/solution/2100-2199/2110.Number of Smooth Descent Periods of a Stock/README.md b/solution/2100-2199/2110.Number of Smooth Descent Periods of a Stock/README.md index 339941b2b276d..113e930951e6c 100644 --- a/solution/2100-2199/2110.Number of Smooth Descent Periods of a Stock/README.md +++ b/solution/2100-2199/2110.Number of Smooth Descent Periods of a Stock/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们定义一个答案变量 `ans`,初始值为 $0$。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def getDescentPeriods(self, prices: List[int]) -> int: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long getDescentPeriods(int[] prices) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func getDescentPeriods(prices []int) (ans int64) { n := len(prices) @@ -144,8 +130,6 @@ func getDescentPeriods(prices []int) (ans int64) { } ``` -### **TypeScript** - ```ts function getDescentPeriods(prices: number[]): number { let ans = 0; @@ -162,10 +146,6 @@ function getDescentPeriods(prices: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2110.Number of Smooth Descent Periods of a Stock/README_EN.md b/solution/2100-2199/2110.Number of Smooth Descent Periods of a Stock/README_EN.md index 0af19f1d25883..79baca08f2493 100644 --- a/solution/2100-2199/2110.Number of Smooth Descent Periods of a Stock/README_EN.md +++ b/solution/2100-2199/2110.Number of Smooth Descent Periods of a Stock/README_EN.md @@ -48,9 +48,9 @@ Note that [8,6] is not a smooth descent period as 8 - 6 ≠ 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long getDescentPeriods(int[] prices) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +104,6 @@ public: }; ``` -### **Go** - ```go func getDescentPeriods(prices []int) (ans int64) { n := len(prices) @@ -125,8 +119,6 @@ func getDescentPeriods(prices []int) (ans int64) { } ``` -### **TypeScript** - ```ts function getDescentPeriods(prices: number[]): number { let ans = 0; @@ -143,10 +135,6 @@ function getDescentPeriods(prices: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2111.Minimum Operations to Make the Array K-Increasing/README.md b/solution/2100-2199/2111.Minimum Operations to Make the Array K-Increasing/README.md index 740db68f8efa5..531377cb5cae7 100644 --- a/solution/2100-2199/2111.Minimum Operations to Make the Array K-Increasing/README.md +++ b/solution/2100-2199/2111.Minimum Operations to Make the Array K-Increasing/README.md @@ -70,16 +70,10 @@ ## 解法 - - -分组求最长上升子序列。 +### 方法一 -### **Python3** - - - ```python class Solution: def kIncreasing(self, arr: List[int], k: int) -> int: @@ -96,10 +90,6 @@ class Solution: return sum(lis(arr[i::k]) for i in range(k)) ``` -### **Java** - - - ```java class Solution { public int kIncreasing(int[] arr, int k) { @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -172,8 +160,6 @@ public: }; ``` -### **Go** - ```go func kIncreasing(arr []int, k int) int { searchRight := func(arr []int, x int) int { @@ -215,18 +201,6 @@ func kIncreasing(arr []int, k int) int { } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2111.Minimum Operations to Make the Array K-Increasing/README_EN.md b/solution/2100-2199/2111.Minimum Operations to Make the Array K-Increasing/README_EN.md index ba531a4678d51..dd3dc6c6c14b5 100644 --- a/solution/2100-2199/2111.Minimum Operations to Make the Array K-Increasing/README_EN.md +++ b/solution/2100-2199/2111.Minimum Operations to Make the Array K-Increasing/README_EN.md @@ -69,9 +69,9 @@ Note that there can be other ways to make the array K-increasing, but none of th ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -89,8 +89,6 @@ class Solution: return sum(lis(arr[i::k]) for i in range(k)) ``` -### **Java** - ```java class Solution { public int kIncreasing(int[] arr, int k) { @@ -134,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +159,6 @@ public: }; ``` -### **Go** - ```go func kIncreasing(arr []int, k int) int { searchRight := func(arr []int, x int) int { @@ -206,16 +200,6 @@ func kIncreasing(arr []int, k int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2112.The Airport With the Most Traffic/README.md b/solution/2100-2199/2112.The Airport With the Most Traffic/README.md index e2b2985c12baf..d8ea62db06e19 100644 --- a/solution/2100-2199/2112.The Airport With the Most Traffic/README.md +++ b/solution/2100-2199/2112.The Airport With the Most Traffic/README.md @@ -89,14 +89,10 @@ Flights 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -116,3 +112,5 @@ WHERE cnt = (SELECT MAX(cnt) FROM P); ``` + + diff --git a/solution/2100-2199/2112.The Airport With the Most Traffic/README_EN.md b/solution/2100-2199/2112.The Airport With the Most Traffic/README_EN.md index 7a0260f1697d6..b81f8eadfc9c0 100644 --- a/solution/2100-2199/2112.The Airport With the Most Traffic/README_EN.md +++ b/solution/2100-2199/2112.The Airport With the Most Traffic/README_EN.md @@ -87,9 +87,9 @@ The airports with the most traffic are airports 1, 2, 3, and 4. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -110,3 +110,5 @@ WHERE cnt = (SELECT MAX(cnt) FROM P); ``` + + diff --git a/solution/2100-2199/2113.Elements in Array After Removing and Replacing Elements/README.md b/solution/2100-2199/2113.Elements in Array After Removing and Replacing Elements/README.md index 405b2fbc73d9e..e95b2fcc64044 100644 --- a/solution/2100-2199/2113.Elements in Array After Removing and Replacing Elements/README.md +++ b/solution/2100-2199/2113.Elements in Array After Removing and Replacing Elements/README.md @@ -72,9 +72,7 @@ ## 解法 - - -**方法一:直接计算** +### 方法一:直接计算 我们先初始化一个数组 $ans$,长度为 $m$,用于存储答案,初始化所有元素为 $-1$。 @@ -89,10 +87,6 @@ -### **Python3** - - - ```python class Solution: def elementInNums(self, nums: List[int], queries: List[List[int]]) -> List[int]: @@ -107,10 +101,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] elementInNums(int[] nums, int[][] queries) { @@ -131,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func elementInNums(nums []int, queries [][]int) []int { n, m := len(nums), len(queries) @@ -173,16 +159,6 @@ func elementInNums(nums []int, queries [][]int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2113.Elements in Array After Removing and Replacing Elements/README_EN.md b/solution/2100-2199/2113.Elements in Array After Removing and Replacing Elements/README_EN.md index 0521dc20bf0f2..3e3d7e01edc4d 100644 --- a/solution/2100-2199/2113.Elements in Array After Removing and Replacing Elements/README_EN.md +++ b/solution/2100-2199/2113.Elements in Array After Removing and Replacing Elements/README_EN.md @@ -70,9 +70,9 @@ At minute 3, nums[0] does not exist. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -88,8 +88,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] elementInNums(int[] nums, int[][] queries) { @@ -110,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +128,6 @@ public: }; ``` -### **Go** - ```go func elementInNums(nums []int, queries [][]int) []int { n, m := len(nums), len(queries) @@ -152,16 +146,6 @@ func elementInNums(nums []int, queries [][]int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2114.Maximum Number of Words Found in Sentences/README.md b/solution/2100-2199/2114.Maximum Number of Words Found in Sentences/README.md index ff6dfb60b2347..34ae2529f6427 100644 --- a/solution/2100-2199/2114.Maximum Number of Words Found in Sentences/README.md +++ b/solution/2100-2199/2114.Maximum Number of Words Found in Sentences/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:空格计数** +### 方法一:空格计数 我们遍历数组 `sentences`,对于每个句子,我们计算其中的空格数,那么单词数就是空格数加 $1$。最后返回最大的单词数即可。 @@ -57,20 +55,12 @@ -### **Python3** - - - ```python class Solution: def mostWordsFound(self, sentences: List[str]) -> int: return 1 + max(s.count(' ') for s in sentences) ``` -### **Java** - - - ```java class Solution { public int mostWordsFound(String[] sentences) { @@ -89,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +93,6 @@ public: }; ``` -### **Go** - ```go func mostWordsFound(sentences []string) (ans int) { for _, s := range sentences { @@ -119,8 +105,6 @@ func mostWordsFound(sentences []string) (ans int) { } ``` -### **TypeScript** - ```ts function mostWordsFound(sentences: string[]): number { return sentences.reduce( @@ -134,8 +118,6 @@ function mostWordsFound(sentences: string[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn most_words_found(sentences: Vec) -> i32 { @@ -154,8 +136,6 @@ impl Solution { } ``` -### **C** - ```c #define max(a, b) (((a) > (b)) ? (a) : (b)) @@ -175,10 +155,6 @@ int mostWordsFound(char** sentences, int sentencesSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2114.Maximum Number of Words Found in Sentences/README_EN.md b/solution/2100-2199/2114.Maximum Number of Words Found in Sentences/README_EN.md index 0da092e2b47f1..227e4002d8069 100644 --- a/solution/2100-2199/2114.Maximum Number of Words Found in Sentences/README_EN.md +++ b/solution/2100-2199/2114.Maximum Number of Words Found in Sentences/README_EN.md @@ -45,9 +45,9 @@ In this example, the second and third sentences (underlined) have the same numbe ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return 1 + max(s.count(' ') for s in sentences) ``` -### **Java** - ```java class Solution { public int mostWordsFound(String[] sentences) { @@ -75,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +87,6 @@ public: }; ``` -### **Go** - ```go func mostWordsFound(sentences []string) (ans int) { for _, s := range sentences { @@ -105,8 +99,6 @@ func mostWordsFound(sentences []string) (ans int) { } ``` -### **TypeScript** - ```ts function mostWordsFound(sentences: string[]): number { return sentences.reduce( @@ -120,8 +112,6 @@ function mostWordsFound(sentences: string[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn most_words_found(sentences: Vec) -> i32 { @@ -140,8 +130,6 @@ impl Solution { } ``` -### **C** - ```c #define max(a, b) (((a) > (b)) ? (a) : (b)) @@ -161,10 +149,6 @@ int mostWordsFound(char** sentences, int sentencesSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2115.Find All Possible Recipes from Given Supplies/README.md b/solution/2100-2199/2115.Find All Possible Recipes from Given Supplies/README.md index 6d81d71c3c2b4..ff031f9bacbc9 100644 --- a/solution/2100-2199/2115.Find All Possible Recipes from Given Supplies/README.md +++ b/solution/2100-2199/2115.Find All Possible Recipes from Given Supplies/README.md @@ -67,18 +67,12 @@ ## 解法 - - -**方法一:拓扑排序** +### 方法一:拓扑排序 首先,我们可以将每道菜看成一个节点,每个节点的入度表示其所需的原材料数量。我们可以通过拓扑排序的方式,找到所有可以做出的菜。 -### **Python3** - - - ```python class Solution: def findAllRecipes( @@ -103,10 +97,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List findAllRecipes( @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -177,8 +165,6 @@ public: }; ``` -### **Go** - ```go func findAllRecipes(recipes []string, ingredients [][]string, supplies []string) []string { g := map[string][]string{} @@ -211,18 +197,6 @@ func findAllRecipes(recipes []string, ingredients [][]string, supplies []string) } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2115.Find All Possible Recipes from Given Supplies/README_EN.md b/solution/2100-2199/2115.Find All Possible Recipes from Given Supplies/README_EN.md index 0f8d4ecfd59d6..6837e7691ca0a 100644 --- a/solution/2100-2199/2115.Find All Possible Recipes from Given Supplies/README_EN.md +++ b/solution/2100-2199/2115.Find All Possible Recipes from Given Supplies/README_EN.md @@ -58,9 +58,9 @@ We can create "burger" since we have the ingredient "meat" a ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -86,8 +86,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List findAllRecipes( @@ -122,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +154,6 @@ public: }; ``` -### **Go** - ```go func findAllRecipes(recipes []string, ingredients [][]string, supplies []string) []string { g := map[string][]string{} @@ -192,16 +186,6 @@ func findAllRecipes(recipes []string, ingredients [][]string, supplies []string) } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2116.Check if a Parentheses String Can Be Valid/README.md b/solution/2100-2199/2116.Check if a Parentheses String Can Be Valid/README.md index 3c129e3f7573e..218dc9522da1b 100644 --- a/solution/2100-2199/2116.Check if a Parentheses String Can Be Valid/README.md +++ b/solution/2100-2199/2116.Check if a Parentheses String Can Be Valid/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:贪心 + 两次遍历** +### 方法一:贪心 + 两次遍历 我们观察发现,奇数长度的字符串一定不是有效的括号字符串,因为无论怎么匹配,都会剩下一个括号。因此,如果字符串 $s$ 的长度是奇数,提前返回 `false`。 @@ -85,10 +83,6 @@ -### **Python3** - - - ```python class Solution: def canBeValid(self, s: str, locked: str) -> bool: @@ -114,10 +108,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean canBeValid(String s, String locked) { @@ -150,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -185,8 +173,6 @@ public: }; ``` -### **Go** - ```go func canBeValid(s string, locked string) bool { n := len(s) @@ -217,18 +203,6 @@ func canBeValid(s string, locked string) bool { } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2116.Check if a Parentheses String Can Be Valid/README_EN.md b/solution/2100-2199/2116.Check if a Parentheses String Can Be Valid/README_EN.md index 56fe41a5d2414..88203d2e5134b 100644 --- a/solution/2100-2199/2116.Check if a Parentheses String Can Be Valid/README_EN.md +++ b/solution/2100-2199/2116.Check if a Parentheses String Can Be Valid/README_EN.md @@ -59,9 +59,9 @@ Changing s[0] to either '(' or ')' will not make s valid. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -88,8 +88,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean canBeValid(String s, String locked) { @@ -122,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +153,6 @@ public: }; ``` -### **Go** - ```go func canBeValid(s string, locked string) bool { n := len(s) @@ -189,16 +183,6 @@ func canBeValid(s string, locked string) bool { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2117.Abbreviating the Product of a Range/README.md b/solution/2100-2199/2117.Abbreviating the Product of a Range/README.md index b47d7a108c166..b2284620828f5 100644 --- a/solution/2100-2199/2117.Abbreviating the Product of a Range/README.md +++ b/solution/2100-2199/2117.Abbreviating the Product of a Range/README.md @@ -73,14 +73,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python import numpy @@ -117,43 +113,6 @@ class Solution: return str(pre) + "..." + str(suf).zfill(5) + "e" + str(c) ``` -```python -class Solution: - def abbreviateProduct(self, left: int, right: int) -> str: - cnt2 = cnt5 = 0 - for x in range(left, right + 1): - while x % 2 == 0: - cnt2 += 1 - x //= 2 - while x % 5 == 0: - cnt5 += 1 - x //= 5 - c = cnt2 = cnt5 = min(cnt2, cnt5) - pre = suf = 1 - gt = False - for x in range(left, right + 1): - suf *= x - while cnt2 and suf % 2 == 0: - suf //= 2 - cnt2 -= 1 - while cnt5 and suf % 5 == 0: - suf //= 5 - cnt5 -= 1 - if suf >= 1e10: - gt = True - suf %= int(1e10) - pre *= x - while pre > 1e5: - pre /= 10 - if gt: - return str(int(pre)) + "..." + str(suf % int(1e5)).zfill(5) + 'e' + str(c) - return str(suf) + "e" + str(c) -``` - -### **Java** - - - ```java class Solution { @@ -195,8 +154,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -240,8 +197,6 @@ public: }; ``` -### **Go** - ```go func abbreviateProduct(left int, right int) string { cnt2, cnt5 := 0, 0 @@ -286,16 +241,45 @@ func abbreviateProduct(left int, right int) string { } ``` -### **TypeScript** - -```ts - -``` + -### **...** +### 方法二 -``` + +```python +class Solution: + def abbreviateProduct(self, left: int, right: int) -> str: + cnt2 = cnt5 = 0 + for x in range(left, right + 1): + while x % 2 == 0: + cnt2 += 1 + x //= 2 + while x % 5 == 0: + cnt5 += 1 + x //= 5 + c = cnt2 = cnt5 = min(cnt2, cnt5) + pre = suf = 1 + gt = False + for x in range(left, right + 1): + suf *= x + while cnt2 and suf % 2 == 0: + suf //= 2 + cnt2 -= 1 + while cnt5 and suf % 5 == 0: + suf //= 5 + cnt5 -= 1 + if suf >= 1e10: + gt = True + suf %= int(1e10) + pre *= x + while pre > 1e5: + pre /= 10 + if gt: + return str(int(pre)) + "..." + str(suf % int(1e5)).zfill(5) + 'e' + str(c) + return str(suf) + "e" + str(c) ``` + + diff --git a/solution/2100-2199/2117.Abbreviating the Product of a Range/README_EN.md b/solution/2100-2199/2117.Abbreviating the Product of a Range/README_EN.md index 5cf3f64d4c065..fa95f4ee07880 100644 --- a/solution/2100-2199/2117.Abbreviating the Product of a Range/README_EN.md +++ b/solution/2100-2199/2117.Abbreviating the Product of a Range/README_EN.md @@ -68,9 +68,9 @@ Hence, the abbreviated product is "399168e2". ## Solutions - +### Solution 1 -### **Python3** + ```python import numpy @@ -108,41 +108,6 @@ class Solution: return str(pre) + "..." + str(suf).zfill(5) + "e" + str(c) ``` -```python -class Solution: - def abbreviateProduct(self, left: int, right: int) -> str: - cnt2 = cnt5 = 0 - for x in range(left, right + 1): - while x % 2 == 0: - cnt2 += 1 - x //= 2 - while x % 5 == 0: - cnt5 += 1 - x //= 5 - c = cnt2 = cnt5 = min(cnt2, cnt5) - pre = suf = 1 - gt = False - for x in range(left, right + 1): - suf *= x - while cnt2 and suf % 2 == 0: - suf //= 2 - cnt2 -= 1 - while cnt5 and suf % 5 == 0: - suf //= 5 - cnt5 -= 1 - if suf >= 1e10: - gt = True - suf %= int(1e10) - pre *= x - while pre > 1e5: - pre /= 10 - if gt: - return str(int(pre)) + "..." + str(suf % int(1e5)).zfill(5) + 'e' + str(c) - return str(suf) + "e" + str(c) -``` - -### **Java** - ```java class Solution { @@ -184,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -229,8 +192,6 @@ public: }; ``` -### **Go** - ```go func abbreviateProduct(left int, right int) string { cnt2, cnt5 := 0, 0 @@ -275,16 +236,45 @@ func abbreviateProduct(left int, right int) string { } ``` -### **TypeScript** - -```ts - -``` + -### **...** +### Solution 2 -``` + +```python +class Solution: + def abbreviateProduct(self, left: int, right: int) -> str: + cnt2 = cnt5 = 0 + for x in range(left, right + 1): + while x % 2 == 0: + cnt2 += 1 + x //= 2 + while x % 5 == 0: + cnt5 += 1 + x //= 5 + c = cnt2 = cnt5 = min(cnt2, cnt5) + pre = suf = 1 + gt = False + for x in range(left, right + 1): + suf *= x + while cnt2 and suf % 2 == 0: + suf //= 2 + cnt2 -= 1 + while cnt5 and suf % 5 == 0: + suf //= 5 + cnt5 -= 1 + if suf >= 1e10: + gt = True + suf %= int(1e10) + pre *= x + while pre > 1e5: + pre /= 10 + if gt: + return str(int(pre)) + "..." + str(suf % int(1e5)).zfill(5) + 'e' + str(c) + return str(suf) + "e" + str(c) ``` + + diff --git a/solution/2100-2199/2118.Build the Equation/README.md b/solution/2100-2199/2118.Build the Equation/README.md index b739ea39fb6b8..7490bfff450da 100644 --- a/solution/2100-2199/2118.Build the Equation/README.md +++ b/solution/2100-2199/2118.Build the Equation/README.md @@ -100,14 +100,10 @@ Terms 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -134,3 +130,5 @@ FROM T; ``` + + diff --git a/solution/2100-2199/2118.Build the Equation/README_EN.md b/solution/2100-2199/2118.Build the Equation/README_EN.md index fce91e2b9dea9..5060eaa36ffb1 100644 --- a/solution/2100-2199/2118.Build the Equation/README_EN.md +++ b/solution/2100-2199/2118.Build the Equation/README_EN.md @@ -96,9 +96,9 @@ Terms table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -126,3 +126,5 @@ FROM T; ``` + + diff --git a/solution/2100-2199/2119.A Number After a Double Reversal/README.md b/solution/2100-2199/2119.A Number After a Double Reversal/README.md index b9c9716ded770..95c2cf4c84756 100644 --- a/solution/2100-2199/2119.A Number After a Double Reversal/README.md +++ b/solution/2100-2199/2119.A Number After a Double Reversal/README.md @@ -46,24 +46,16 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def isSameAfterReversals(self, num: int) -> bool: return num == 0 or num % 10 != 0 ``` -### **Java** - - - ```java class Solution { public boolean isSameAfterReversals(int num) { @@ -72,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -83,26 +73,12 @@ public: }; ``` -### **Go** - ```go func isSameAfterReversals(num int) bool { return num == 0 || num%10 != 0 } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2119.A Number After a Double Reversal/README_EN.md b/solution/2100-2199/2119.A Number After a Double Reversal/README_EN.md index 8d6954b7ccf9c..0da085d1eb5de 100644 --- a/solution/2100-2199/2119.A Number After a Double Reversal/README_EN.md +++ b/solution/2100-2199/2119.A Number After a Double Reversal/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return num == 0 or num % 10 != 0 ``` -### **Java** - ```java class Solution { public boolean isSameAfterReversals(int num) { @@ -66,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -77,24 +73,12 @@ public: }; ``` -### **Go** - ```go func isSameAfterReversals(num int) bool { return num == 0 || num%10 != 0 } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2120.Execution of All Suffix Instructions Staying in a Grid/README.md b/solution/2100-2199/2120.Execution of All Suffix Instructions Staying in a Grid/README.md index 308d3ec3b9eb2..2628d9ab95010 100644 --- a/solution/2100-2199/2120.Execution of All Suffix Instructions Staying in a Grid/README.md +++ b/solution/2100-2199/2120.Execution of All Suffix Instructions Staying in a Grid/README.md @@ -75,16 +75,10 @@ ## 解法 - - -直接模拟。 +### 方法一 -### **Python3** - - - ```python class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: @@ -104,10 +98,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] executeInstructions(int n, int[] startPos, String s) { @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +159,6 @@ public: }; ``` -### **Go** - ```go func executeInstructions(n int, startPos []int, s string) []int { m := len(s) @@ -201,10 +187,6 @@ func executeInstructions(n int, startPos []int, s string) []int { } ``` -### **TypeScript** - - - ```ts function executeInstructions(n: number, startPos: number[], s: string): number[] { const m = s.length; @@ -233,8 +215,6 @@ function executeInstructions(n: number, startPos: number[], s: string): number[] } ``` -### **Rust** - ```rust impl Solution { pub fn execute_instructions(n: i32, start_pos: Vec, s: String) -> Vec { @@ -272,8 +252,6 @@ impl Solution { } ``` -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -306,10 +284,6 @@ int* executeInstructions(int n, int* startPos, int startPosSize, char* s, int* r } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2120.Execution of All Suffix Instructions Staying in a Grid/README_EN.md b/solution/2100-2199/2120.Execution of All Suffix Instructions Staying in a Grid/README_EN.md index e815774e57509..48409e5584cf7 100644 --- a/solution/2100-2199/2120.Execution of All Suffix Instructions Staying in a Grid/README_EN.md +++ b/solution/2100-2199/2120.Execution of All Suffix Instructions Staying in a Grid/README_EN.md @@ -65,9 +65,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -88,8 +88,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] executeInstructions(int n, int[] startPos, String s) { @@ -121,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +149,6 @@ public: }; ``` -### **Go** - ```go func executeInstructions(n int, startPos []int, s string) []int { m := len(s) @@ -183,8 +177,6 @@ func executeInstructions(n int, startPos []int, s string) []int { } ``` -### **TypeScript** - ```ts function executeInstructions(n: number, startPos: number[], s: string): number[] { const m = s.length; @@ -213,8 +205,6 @@ function executeInstructions(n: number, startPos: number[], s: string): number[] } ``` -### **Rust** - ```rust impl Solution { pub fn execute_instructions(n: i32, start_pos: Vec, s: String) -> Vec { @@ -252,8 +242,6 @@ impl Solution { } ``` -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -286,10 +274,6 @@ int* executeInstructions(int n, int* startPos, int startPosSize, char* s, int* r } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2121.Intervals Between Identical Elements/README.md b/solution/2100-2199/2121.Intervals Between Identical Elements/README.md index 3d19cccc676a6..921116423820d 100644 --- a/solution/2100-2199/2121.Intervals Between Identical Elements/README.md +++ b/solution/2100-2199/2121.Intervals Between Identical Elements/README.md @@ -53,16 +53,10 @@ ## 解法 - - -先用哈希表记录相同元素出现的位置。遍历哈希表,先计算最左侧元素的间隔和,然后逐个计算下个元素的间隔和。 +### 方法一 -### **Python3** - - - ```python class Solution: def getDistances(self, arr: List[int]) -> List[int]: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long[] getDistances(int[] arr) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +127,6 @@ public: }; ``` -### **Go** - ```go func getDistances(arr []int) []int64 { d := make(map[int][]int) @@ -169,18 +155,6 @@ func getDistances(arr []int) []int64 { } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2121.Intervals Between Identical Elements/README_EN.md b/solution/2100-2199/2121.Intervals Between Identical Elements/README_EN.md index d5f0efc695ffc..9d18532c7245c 100644 --- a/solution/2100-2199/2121.Intervals Between Identical Elements/README_EN.md +++ b/solution/2100-2199/2121.Intervals Between Identical Elements/README_EN.md @@ -51,9 +51,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long[] getDistances(int[] arr) { @@ -102,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +125,6 @@ public: }; ``` -### **Go** - ```go func getDistances(arr []int) []int64 { d := make(map[int][]int) @@ -159,16 +153,6 @@ func getDistances(arr []int) []int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2122.Recover the Original Array/README.md b/solution/2100-2199/2122.Recover the Original Array/README.md index 92f20d8accfe5..9ad1b9eb63e49 100644 --- a/solution/2100-2199/2122.Recover the Original Array/README.md +++ b/solution/2100-2199/2122.Recover the Original Array/README.md @@ -62,18 +62,10 @@ ## 解法 - - -对 nums 排序后,`nums[0]` 必然是 `lower[0]`,接下来从在 `[1, i)` 区间内枚举 `higher[0]`,然后使用双指针遍历 nums,得到剩余的 lower 和 higher 元素。 - -双指针遍历时,可以用 vis 数组标记 higher 中出现过的数字。 +### 方法一 -### **Python3** - - - ```python class Solution: def recoverArray(self, nums: List[int]) -> List[int]: @@ -102,10 +94,6 @@ class Solution: return [] ``` -### **Java** - - - ```java class Solution { public int[] recoverArray(int[] nums) { @@ -146,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -174,8 +160,6 @@ public: }; ``` -### **Go** - ```go func recoverArray(nums []int) []int { sort.Ints(nums) @@ -208,18 +192,6 @@ func recoverArray(nums []int) []int { } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2122.Recover the Original Array/README_EN.md b/solution/2100-2199/2122.Recover the Original Array/README_EN.md index 4e42fbf66c343..f4e5c09a131d7 100644 --- a/solution/2100-2199/2122.Recover the Original Array/README_EN.md +++ b/solution/2100-2199/2122.Recover the Original Array/README_EN.md @@ -62,9 +62,9 @@ The only possible combination is arr = [220] and k = 215. Using them, we get low ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -94,8 +94,6 @@ class Solution: return [] ``` -### **Java** - ```java class Solution { public int[] recoverArray(int[] nums) { @@ -136,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +160,6 @@ public: }; ``` -### **Go** - ```go func recoverArray(nums []int) []int { sort.Ints(nums) @@ -198,16 +192,6 @@ func recoverArray(nums []int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/README.md b/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/README.md index 707fdb7f6dcae..68d004174553e 100644 --- a/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/README.md +++ b/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:匈牙利算法** +### 方法一:匈牙利算法 我们注意到,如果矩阵中的两个 $1$ 相邻,那么它们一定属于不同的组。因此,我们可以把矩阵中所有的 $1$ 视为点,相邻的两个 $1$ 之间连一条边,构建二分图。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def minimumOperations(self, grid: List[List[int]]) -> int: @@ -102,10 +96,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private Map> g = new HashMap<>(); @@ -157,8 +147,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -208,8 +196,6 @@ public: }; ``` -### **Go** - ```go func minimumOperations(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -259,8 +245,6 @@ func minimumOperations(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumOperations(grid: number[][]): number { const m = grid.length; @@ -309,10 +293,6 @@ function minimumOperations(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/README_EN.md b/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/README_EN.md index dfe239c20b315..8ee1267b08ba3 100644 --- a/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/README_EN.md +++ b/solution/2100-2199/2123.Minimum Operations to Remove Adjacent Ones in Matrix/README_EN.md @@ -50,9 +50,9 @@ No operations were done so return 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -89,8 +89,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private Map> g = new HashMap<>(); @@ -142,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -193,8 +189,6 @@ public: }; ``` -### **Go** - ```go func minimumOperations(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -244,8 +238,6 @@ func minimumOperations(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumOperations(grid: number[][]): number { const m = grid.length; @@ -294,10 +286,6 @@ function minimumOperations(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2124.Check if All A's Appears Before All B's/README.md b/solution/2100-2199/2124.Check if All A's Appears Before All B's/README.md index 1a263d3d5b87c..8724fba485ca5 100644 --- a/solution/2100-2199/2124.Check if All A's Appears Before All B's/README.md +++ b/solution/2100-2199/2124.Check if All A's Appears Before All B's/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 根据题意,字符串 $s$ 仅由字符 `a`, `b` 组成。 @@ -59,20 +57,12 @@ -### **Python3** - - - ```python class Solution: def checkString(self, s: str) -> bool: return "ba" not in s ``` -### **Java** - - - ```java class Solution { public boolean checkString(String s) { @@ -81,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -92,24 +80,12 @@ public: }; ``` -### **Go** - ```go func checkString(s string) bool { return !strings.Contains(s, "ba") } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2124.Check if All A's Appears Before All B's/README_EN.md b/solution/2100-2199/2124.Check if All A's Appears Before All B's/README_EN.md index 1b7889396d3d4..92bea5cd89cbf 100644 --- a/solution/2100-2199/2124.Check if All A's Appears Before All B's/README_EN.md +++ b/solution/2100-2199/2124.Check if All A's Appears Before All B's/README_EN.md @@ -46,9 +46,9 @@ There are no 'a's, hence, every 'a' appears before every 'b& ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return "ba" not in s ``` -### **Java** - ```java class Solution { public boolean checkString(String s) { @@ -66,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -77,24 +73,12 @@ public: }; ``` -### **Go** - ```go func checkString(s string) bool { return !strings.Contains(s, "ba") } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2125.Number of Laser Beams in a Bank/README.md b/solution/2100-2199/2125.Number of Laser Beams in a Bank/README.md index 85bc2b9adcc1c..415fa27b90bb0 100644 --- a/solution/2100-2199/2125.Number of Laser Beams in a Bank/README.md +++ b/solution/2100-2199/2125.Number of Laser Beams in a Bank/README.md @@ -64,16 +64,10 @@ ## 解法 - - -直接计数。 +### 方法一 -### **Python3** - - - ```python class Solution: def numberOfBeams(self, bank: List[str]) -> int: @@ -85,10 +79,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numberOfBeams(String[] bank) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func numberOfBeams(bank []string) int { ans, last := 0, 0 @@ -150,10 +136,6 @@ func numberOfBeams(bank []string) int { } ``` -### **TypeScript** - - - ```ts function numberOfBeams(bank: string[]): number { let last = 0; @@ -174,8 +156,6 @@ function numberOfBeams(bank: string[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn number_of_beams(bank: Vec) -> i32 { @@ -198,8 +178,6 @@ impl Solution { } ``` -### **C** - ```c int numberOfBeams(char** bank, int bankSize) { int last = 0; @@ -220,10 +198,6 @@ int numberOfBeams(char** bank, int bankSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2125.Number of Laser Beams in a Bank/README_EN.md b/solution/2100-2199/2125.Number of Laser Beams in a Bank/README_EN.md index 82da09324b531..1f9f753d1a0f1 100644 --- a/solution/2100-2199/2125.Number of Laser Beams in a Bank/README_EN.md +++ b/solution/2100-2199/2125.Number of Laser Beams in a Bank/README_EN.md @@ -56,9 +56,9 @@ This is because the 2nd row contains security devices, which breaks t ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numberOfBeams(String[] bank) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func numberOfBeams(bank []string) int { ans, last := 0, 0 @@ -134,8 +128,6 @@ func numberOfBeams(bank []string) int { } ``` -### **TypeScript** - ```ts function numberOfBeams(bank: string[]): number { let last = 0; @@ -156,8 +148,6 @@ function numberOfBeams(bank: string[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn number_of_beams(bank: Vec) -> i32 { @@ -180,8 +170,6 @@ impl Solution { } ``` -### **C** - ```c int numberOfBeams(char** bank, int bankSize) { int last = 0; @@ -202,10 +190,6 @@ int numberOfBeams(char** bank, int bankSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2126.Destroying Asteroids/README.md b/solution/2100-2199/2126.Destroying Asteroids/README.md index ea6f97f81242b..ec253e0a24b8c 100644 --- a/solution/2100-2199/2126.Destroying Asteroids/README.md +++ b/solution/2100-2199/2126.Destroying Asteroids/README.md @@ -48,16 +48,10 @@ ## 解法 - - -**方法一:排序 + 贪心** +### 方法一:排序 + 贪心 -### **Python3** - - - ```python class Solution: def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool: @@ -69,10 +63,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean asteroidsDestroyed(int mass, int[] asteroids) { @@ -89,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +94,6 @@ public: }; ``` -### **Go** - ```go func asteroidsDestroyed(mass int, asteroids []int) bool { m := mass @@ -122,18 +108,6 @@ func asteroidsDestroyed(mass int, asteroids []int) bool { } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2126.Destroying Asteroids/README_EN.md b/solution/2100-2199/2126.Destroying Asteroids/README_EN.md index dde06a7a2bd94..a26f0862f376d 100644 --- a/solution/2100-2199/2126.Destroying Asteroids/README_EN.md +++ b/solution/2100-2199/2126.Destroying Asteroids/README_EN.md @@ -46,9 +46,9 @@ This is less than 23, so a collision would not destroy the last asteroid. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean asteroidsDestroyed(int mass, int[] asteroids) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func asteroidsDestroyed(mass int, asteroids []int) bool { m := mass @@ -112,16 +106,6 @@ func asteroidsDestroyed(mass int, asteroids []int) bool { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2127.Maximum Employees to Be Invited to a Meeting/README.md b/solution/2100-2199/2127.Maximum Employees to Be Invited to a Meeting/README.md index f4b3d04b5acb8..1d0b24cf464f3 100644 --- a/solution/2100-2199/2127.Maximum Employees to Be Invited to a Meeting/README.md +++ b/solution/2100-2199/2127.Maximum Employees to Be Invited to a Meeting/README.md @@ -69,9 +69,7 @@ ## 解法 - - -**方法一:图的最大环 + 最长链** +### 方法一:图的最大环 + 最长链 我们观察发现,题目中员工的喜好关系可以看作一个有向图,这个有向图可以分成多个“基环内向树”的结构。在每个结构中,包含一个环,而环上的每个节点都连接着一棵树。 @@ -91,10 +89,6 @@ -### **Python3** - - - ```python class Solution: def maximumInvitations(self, favorite: List[int]) -> int: @@ -135,10 +129,6 @@ class Solution: return max(max_cycle(favorite), topological_sort(favorite)) ``` -### **Java** - - - ```java class Solution { public int maximumInvitations(int[] favorite) { @@ -201,8 +191,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -255,8 +243,6 @@ public: }; ``` -### **Go** - ```go func maximumInvitations(favorite []int) int { a, b := maxCycle(favorite), topologicalSort(favorite) @@ -323,8 +309,6 @@ func topologicalSort(fa []int) int { } ``` -### **TypeScript** - ```ts function maximumInvitations(favorite: number[]): number { return Math.max(maxCycle(favorite), topologicalSort(favorite)); @@ -383,10 +367,6 @@ function topologicalSort(fa: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2127.Maximum Employees to Be Invited to a Meeting/README_EN.md b/solution/2100-2199/2127.Maximum Employees to Be Invited to a Meeting/README_EN.md index b04f61f3527c1..7e9b0b5b91c24 100644 --- a/solution/2100-2199/2127.Maximum Employees to Be Invited to a Meeting/README_EN.md +++ b/solution/2100-2199/2127.Maximum Employees to Be Invited to a Meeting/README_EN.md @@ -61,7 +61,7 @@ The maximum number of employees that can be invited to the meeting is 4. ## Solutions -**Solution 1: Maximum Cycle in Graph + Longest Chain** +### Solution 1: Maximum Cycle in Graph + Longest Chain We observe that the employee's preference relationship in the problem can be regarded as a directed graph, which can be divided into multiple "base cycle inward trees". Each structure contains a cycle, and each node on the cycle is connected to a tree. @@ -79,8 +79,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maximumInvitations(self, favorite: List[int]) -> int: @@ -121,8 +119,6 @@ class Solution: return max(max_cycle(favorite), topological_sort(favorite)) ``` -### **Java** - ```java class Solution { public int maximumInvitations(int[] favorite) { @@ -185,8 +181,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -239,8 +233,6 @@ public: }; ``` -### **Go** - ```go func maximumInvitations(favorite []int) int { a, b := maxCycle(favorite), topologicalSort(favorite) @@ -307,16 +299,64 @@ func topologicalSort(fa []int) int { } ``` -### **TypeScript** - ```ts +function maximumInvitations(favorite: number[]): number { + return Math.max(maxCycle(favorite), topologicalSort(favorite)); +} -``` - -### **...** - -``` +function maxCycle(fa: number[]): number { + const n = fa.length; + const vis: boolean[] = Array(n).fill(false); + let ans = 0; + for (let i = 0; i < n; ++i) { + if (vis[i]) { + continue; + } + const cycle: number[] = []; + let j = i; + for (; !vis[j]; j = fa[j]) { + cycle.push(j); + vis[j] = true; + } + for (let k = 0; k < cycle.length; ++k) { + if (cycle[k] === j) { + ans = Math.max(ans, cycle.length - k); + } + } + } + return ans; +} +function topologicalSort(fa: number[]): number { + const n = fa.length; + const indeg: number[] = Array(n).fill(0); + const dist: number[] = Array(n).fill(1); + for (const v of fa) { + ++indeg[v]; + } + const q: number[] = []; + for (let i = 0; i < n; ++i) { + if (indeg[i] === 0) { + q.push(i); + } + } + let ans = 0; + while (q.length) { + const i = q.pop()!; + dist[fa[i]] = Math.max(dist[fa[i]], dist[i] + 1); + if (--indeg[fa[i]] === 0) { + q.push(fa[i]); + } + } + for (let i = 0; i < n; ++i) { + if (i === fa[fa[i]]) { + ans += dist[i]; + } + } + return ans; +} ``` + + diff --git a/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/README.md b/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/README.md index 0bed1d382580b..b3ffb5f9e9e93 100644 --- a/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/README.md +++ b/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们观察发现,如果矩阵中的两行满足以下条件之一,则它们可以通过翻转某些列的方式得到相等的行: @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def removeOnes(self, grid: List[List[int]]) -> bool: @@ -90,10 +84,6 @@ class Solution: return len(s) == 1 ``` -### **Java** - - - ```java class Solution { public boolean removeOnes(int[][] grid) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func removeOnes(grid [][]int) bool { s := map[string]bool{} @@ -149,8 +135,6 @@ func removeOnes(grid [][]int) bool { } ``` -### **TypeScript** - ```ts function removeOnes(grid: number[][]): boolean { const s = new Set(); @@ -167,10 +151,6 @@ function removeOnes(grid: number[][]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/README_EN.md b/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/README_EN.md index 34827d9080873..b1cb2e464489e 100644 --- a/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/README_EN.md +++ b/solution/2100-2199/2128.Remove All Ones With Row and Column Flips/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return len(s) == 1 ``` -### **Java** - ```java class Solution { public boolean removeOnes(int[][] grid) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +97,6 @@ public: }; ``` -### **Go** - ```go func removeOnes(grid [][]int) bool { s := map[string]bool{} @@ -120,8 +114,6 @@ func removeOnes(grid [][]int) bool { } ``` -### **TypeScript** - ```ts function removeOnes(grid: number[][]): boolean { const s = new Set(); @@ -138,10 +130,6 @@ function removeOnes(grid: number[][]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2129.Capitalize the Title/README.md b/solution/2100-2199/2129.Capitalize the Title/README.md index 511784d0beacd..941e8d4e2b8c5 100644 --- a/solution/2100-2199/2129.Capitalize the Title/README.md +++ b/solution/2100-2199/2129.Capitalize the Title/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 直接模拟,按空格切分字符串,得到每个单词,再按题目转大小写。最后用空格连接每个单词。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def capitalizeTitle(self, title: str) -> str: @@ -76,10 +70,6 @@ class Solution: return " ".join(words) ``` -### **Java** - - - ```java class Solution { public String capitalizeTitle(String title) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func capitalizeTitle(title string) string { title = strings.ToLower(title) @@ -131,8 +117,6 @@ func capitalizeTitle(title string) string { } ``` -### **TypeScript** - ```ts function capitalizeTitle(title: string): string { const ans: string[] = []; @@ -147,6 +131,12 @@ function capitalizeTitle(title: string): string { } ``` + + +### 方法二 + + + ```ts function capitalizeTitle(title: string): string { return title @@ -160,10 +150,6 @@ function capitalizeTitle(title: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2129.Capitalize the Title/README_EN.md b/solution/2100-2199/2129.Capitalize the Title/README_EN.md index 3287ece95cf71..2a0093a06775a 100644 --- a/solution/2100-2199/2129.Capitalize the Title/README_EN.md +++ b/solution/2100-2199/2129.Capitalize the Title/README_EN.md @@ -54,9 +54,9 @@ The remaining words have a length of at least 3, so the first letter of each rem ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return " ".join(words) ``` -### **Java** - ```java class Solution { public String capitalizeTitle(String title) { @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +99,6 @@ public: }; ``` -### **Go** - ```go func capitalizeTitle(title string) string { title = strings.ToLower(title) @@ -118,8 +112,6 @@ func capitalizeTitle(title string) string { } ``` -### **TypeScript** - ```ts function capitalizeTitle(title: string): string { const ans: string[] = []; @@ -134,6 +126,12 @@ function capitalizeTitle(title: string): string { } ``` + + +### Solution 2 + + + ```ts function capitalizeTitle(title: string): string { return title @@ -147,10 +145,6 @@ function capitalizeTitle(title: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/README.md b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/README.md index d9c3355a3f329..f93752e83386f 100644 --- a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/README.md +++ b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/README.md @@ -64,22 +64,12 @@ ## 解法 - - -**方法一:链表转成列表(数组)求解** +### 方法一:链表转成列表(数组)求解 时间复杂度 $O(n)$,空间复杂度 $O(n)$。 -**方法二:快慢指针 + 反转链表 + 双指针** - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -96,6 +86,151 @@ class Solution: return max(s[i] + s[-(i + 1)] for i in range(n >> 1)) ``` +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public int pairSum(ListNode head) { + List s = new ArrayList<>(); + for (; head != null; head = head.next) { + s.add(head.val); + } + int ans = 0, n = s.size(); + for (int i = 0; i < (n >> 1); ++i) { + ans = Math.max(ans, s.get(i) + s.get(n - 1 - i)); + } + return ans; + } +} +``` + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + int pairSum(ListNode* head) { + vector s; + for (; head != nullptr; head = head->next) s.push_back(head->val); + int ans = 0, n = s.size(); + for (int i = 0; i < (n >> 1); ++i) ans = max(ans, s[i] + s[n - i - 1]); + return ans; + } +}; +``` + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func pairSum(head *ListNode) int { + var s []int + for ; head != nil; head = head.Next { + s = append(s, head.Val) + } + ans, n := 0, len(s) + for i := 0; i < (n >> 1); i++ { + if ans < s[i]+s[n-i-1] { + ans = s[i] + s[n-i-1] + } + } + return ans +} +``` + +```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 pairSum(head: ListNode | null): number { + const arr = []; + let node = head; + while (node) { + arr.push(node.val); + node = node.next; + } + const n = arr.length; + let ans = 0; + for (let i = 0; i < n >> 1; i++) { + ans = Math.max(ans, arr[i] + arr[n - 1 - i]); + } + return ans; +} +``` + +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn pair_sum(head: Option>) -> i32 { + let mut arr = Vec::new(); + let mut node = &head; + while node.is_some() { + let t = node.as_ref().unwrap(); + arr.push(t.val); + node = &t.next; + } + let n = arr.len(); + let mut ans = 0; + for i in 0..n >> 1 { + ans = ans.max(arr[i] + arr[n - 1 - i]); + } + ans + } +} +``` + + + +### 方法二:快慢指针 + 反转链表 + 双指针 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。 + + + ```python # Definition for singly-linked list. # class ListNode: @@ -129,36 +264,6 @@ class Solution: return ans ``` -### **Java** - - - -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public int pairSum(ListNode head) { - List s = new ArrayList<>(); - for (; head != null; head = head.next) { - s.add(head.val); - } - int ans = 0, n = s.size(); - for (int i = 0; i < (n >> 1); ++i) { - ans = Math.max(ans, s.get(i) + s.get(n - 1 - i)); - } - return ans; - } -} -``` - ```java /** * Definition for singly-linked list. @@ -205,31 +310,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - int pairSum(ListNode* head) { - vector s; - for (; head != nullptr; head = head->next) s.push_back(head->val); - int ans = 0, n = s.size(); - for (int i = 0; i < (n >> 1); ++i) ans = max(ans, s[i] + s[n - i - 1]); - return ans; - } -}; -``` - ```cpp /** * Definition for singly-linked list. @@ -277,31 +357,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -func pairSum(head *ListNode) int { - var s []int - for ; head != nil; head = head.Next { - s = append(s, head.Val) - } - ans, n := 0, len(s) - for i := 0; i < (n >> 1); i++ { - if ans < s[i]+s[n-i-1] { - ans = s[i] + s[n-i-1] - } - } - return ans -} -``` - ```go /** * Definition for singly-linked list. @@ -340,37 +395,6 @@ func pairSum(head *ListNode) int { } ``` -### **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 pairSum(head: ListNode | null): number { - const arr = []; - let node = head; - while (node) { - arr.push(node.val); - node = node.next; - } - const n = arr.length; - let ans = 0; - for (let i = 0; i < n >> 1; i++) { - ans = Math.max(ans, arr[i] + arr[n - 1 - i]); - } - return ans; -} -``` - ```ts /** * Definition for singly-linked list. @@ -410,48 +434,6 @@ function pairSum(head: ListNode | null): number { } ``` -### **Rust** - -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn pair_sum(head: Option>) -> i32 { - let mut arr = Vec::new(); - let mut node = &head; - while node.is_some() { - let t = node.as_ref().unwrap(); - arr.push(t.val); - node = &t.next; - } - let n = arr.len(); - let mut ans = 0; - for i in 0..n >> 1 { - ans = ans.max(arr[i] + arr[n - 1 - i]); - } - ans - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/README_EN.md b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/README_EN.md index 750201278e496..18495a65a9db0 100644 --- a/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/README_EN.md +++ b/solution/2100-2199/2130.Maximum Twin Sum of a Linked List/README_EN.md @@ -57,9 +57,9 @@ There is only one node with a twin in the linked list having twin sum of 1 + 100 ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -77,6 +77,149 @@ class Solution: return max(s[i] + s[-(i + 1)] for i in range(n >> 1)) ``` +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public int pairSum(ListNode head) { + List s = new ArrayList<>(); + for (; head != null; head = head.next) { + s.add(head.val); + } + int ans = 0, n = s.size(); + for (int i = 0; i < (n >> 1); ++i) { + ans = Math.max(ans, s.get(i) + s.get(n - 1 - i)); + } + return ans; + } +} +``` + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + int pairSum(ListNode* head) { + vector s; + for (; head != nullptr; head = head->next) s.push_back(head->val); + int ans = 0, n = s.size(); + for (int i = 0; i < (n >> 1); ++i) ans = max(ans, s[i] + s[n - i - 1]); + return ans; + } +}; +``` + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func pairSum(head *ListNode) int { + var s []int + for ; head != nil; head = head.Next { + s = append(s, head.Val) + } + ans, n := 0, len(s) + for i := 0; i < (n >> 1); i++ { + if ans < s[i]+s[n-i-1] { + ans = s[i] + s[n-i-1] + } + } + return ans +} +``` + +```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 pairSum(head: ListNode | null): number { + const arr = []; + let node = head; + while (node) { + arr.push(node.val); + node = node.next; + } + const n = arr.length; + let ans = 0; + for (let i = 0; i < n >> 1; i++) { + ans = Math.max(ans, arr[i] + arr[n - 1 - i]); + } + return ans; +} +``` + +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn pair_sum(head: Option>) -> i32 { + let mut arr = Vec::new(); + let mut node = &head; + while node.is_some() { + let t = node.as_ref().unwrap(); + arr.push(t.val); + node = &t.next; + } + let n = arr.len(); + let mut ans = 0; + for i in 0..n >> 1 { + ans = ans.max(arr[i] + arr[n - 1 - i]); + } + ans + } +} +``` + + + +### Solution 2 + + + ```python # Definition for singly-linked list. # class ListNode: @@ -110,34 +253,6 @@ class Solution: return ans ``` -### **Java** - -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public int pairSum(ListNode head) { - List s = new ArrayList<>(); - for (; head != null; head = head.next) { - s.add(head.val); - } - int ans = 0, n = s.size(); - for (int i = 0; i < (n >> 1); ++i) { - ans = Math.max(ans, s.get(i) + s.get(n - 1 - i)); - } - return ans; - } -} -``` - ```java /** * Definition for singly-linked list. @@ -184,31 +299,6 @@ class Solution { } ``` -### **C++** - -```cpp -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - int pairSum(ListNode* head) { - vector s; - for (; head != nullptr; head = head->next) s.push_back(head->val); - int ans = 0, n = s.size(); - for (int i = 0; i < (n >> 1); ++i) ans = max(ans, s[i] + s[n - i - 1]); - return ans; - } -}; -``` - ```cpp /** * Definition for singly-linked list. @@ -256,31 +346,6 @@ public: }; ``` -### **Go** - -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -func pairSum(head *ListNode) int { - var s []int - for ; head != nil; head = head.Next { - s = append(s, head.Val) - } - ans, n := 0, len(s) - for i := 0; i < (n >> 1); i++ { - if ans < s[i]+s[n-i-1] { - ans = s[i] + s[n-i-1] - } - } - return ans -} -``` - ```go /** * Definition for singly-linked list. @@ -319,37 +384,6 @@ func pairSum(head *ListNode) int { } ``` -### **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 pairSum(head: ListNode | null): number { - const arr = []; - let node = head; - while (node) { - arr.push(node.val); - node = node.next; - } - const n = arr.length; - let ans = 0; - for (let i = 0; i < n >> 1; i++) { - ans = Math.max(ans, arr[i] + arr[n - 1 - i]); - } - return ans; -} -``` - ```ts /** * Definition for singly-linked list. @@ -389,48 +423,6 @@ function pairSum(head: ListNode | null): number { } ``` -### **Rust** - -```rust -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Clone, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn pair_sum(head: Option>) -> i32 { - let mut arr = Vec::new(); - let mut node = &head; - while node.is_some() { - let t = node.as_ref().unwrap(); - arr.push(t.val); - node = &t.next; - } - let n = arr.len(); - let mut ans = 0; - for i in 0..n >> 1 { - ans = ans.max(arr[i] + arr[n - 1 - i]); - } - ans - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README.md b/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README.md index 88de51ae0d328..dc7371a68240b 100644 --- a/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README.md +++ b/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:贪心 + 哈希表** +### 方法一:贪心 + 哈希表 我们先用哈希表 `cnt` 统计每个单词出现的次数。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def longestPalindrome(self, words: List[str]) -> int: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestPalindrome(String[] words) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -## **Go** - ```go func longestPalindrome(words []string) int { cnt := map[string]int{} @@ -169,18 +155,6 @@ func longestPalindrome(words []string) int { } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README_EN.md b/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README_EN.md index f1bcbdb2ea1f8..fe53ef9b6ecbd 100644 --- a/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README_EN.md +++ b/solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/README_EN.md @@ -51,9 +51,9 @@ Note that "ll" is another longest palindrome that can be created, and ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestPalindrome(String[] words) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +118,6 @@ public: }; ``` -## **Go** - ```go func longestPalindrome(words []string) int { cnt := map[string]int{} @@ -149,16 +143,6 @@ func longestPalindrome(words []string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2132.Stamping the Grid/README.md b/solution/2100-2199/2132.Stamping the Grid/README.md index 93ad113e8c7d0..55b48467eb348 100644 --- a/solution/2100-2199/2132.Stamping the Grid/README.md +++ b/solution/2100-2199/2132.Stamping the Grid/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:二维前缀和 + 二维差分** +### 方法一:二维前缀和 + 二维差分 根据题目描述,每一个空格子都必须被邮票覆盖,而且不能覆盖任何被占据的格子。因此,我们可以遍历二维矩阵,对于每个格子,如果以该格子为左上角的 $stampHeight \times stampWidth$ 的区域内的所有格子都是空格子(即没有被占据),那么我们就可以在该格子处放置一个邮票。 @@ -81,10 +79,6 @@ $$ -### **Python3** - - - ```python class Solution: def possibleToStamp( @@ -112,10 +106,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean possibleToStamp(int[][] grid, int stampHeight, int stampWidth) { @@ -151,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -191,8 +179,6 @@ public: }; ``` -### **Go** - ```go func possibleToStamp(grid [][]int, stampHeight int, stampWidth int) bool { m, n := len(grid), len(grid[0]) @@ -235,8 +221,6 @@ func possibleToStamp(grid [][]int, stampHeight int, stampWidth int) bool { } ``` -### **TypeScript** - ```ts function possibleToStamp(grid: number[][], stampHeight: number, stampWidth: number): boolean { const m = grid.length; @@ -273,8 +257,6 @@ function possibleToStamp(grid: number[][], stampHeight: number, stampWidth: numb } ``` -### **Rust** - ```rust impl Solution { pub fn possible_to_stamp(grid: Vec>, stamp_height: i32, stamp_width: i32) -> bool { @@ -344,8 +326,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[][]} grid @@ -388,10 +368,6 @@ var possibleToStamp = function (grid, stampHeight, stampWidth) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2132.Stamping the Grid/README_EN.md b/solution/2100-2199/2132.Stamping the Grid/README_EN.md index af503fa927873..e6eb92d541eaf 100644 --- a/solution/2100-2199/2132.Stamping the Grid/README_EN.md +++ b/solution/2100-2199/2132.Stamping the Grid/README_EN.md @@ -50,7 +50,7 @@ ## Solutions -**Solution 1: Two-Dimensional Prefix Sum + Two-Dimensional Difference** +### Solution 1: Two-Dimensional Prefix Sum + Two-Dimensional Difference According to the problem description, every empty cell must be covered by a stamp, and no occupied cell can be covered. Therefore, we can traverse the two-dimensional matrix, and for each cell, if all cells in the area of $stampHeight \times stampWidth$ with this cell as the upper left corner are empty (i.e., not occupied), then we can place a stamp at this cell. @@ -73,8 +73,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times -### **Python3** - ```python class Solution: def possibleToStamp( @@ -102,8 +100,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean possibleToStamp(int[][] grid, int stampHeight, int stampWidth) { @@ -139,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -179,8 +173,6 @@ public: }; ``` -### **Go** - ```go func possibleToStamp(grid [][]int, stampHeight int, stampWidth int) bool { m, n := len(grid), len(grid[0]) @@ -223,8 +215,6 @@ func possibleToStamp(grid [][]int, stampHeight int, stampWidth int) bool { } ``` -### **TypeScript** - ```ts function possibleToStamp(grid: number[][], stampHeight: number, stampWidth: number): boolean { const m = grid.length; @@ -261,8 +251,6 @@ function possibleToStamp(grid: number[][], stampHeight: number, stampWidth: numb } ``` -### **Rust** - ```rust impl Solution { pub fn possible_to_stamp(grid: Vec>, stamp_height: i32, stamp_width: i32) -> bool { @@ -332,8 +320,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {number[][]} grid @@ -376,10 +362,6 @@ var possibleToStamp = function (grid, stampHeight, stampWidth) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2133.Check if Every Row and Column Contains All Numbers/README.md b/solution/2100-2199/2133.Check if Every Row and Column Contains All Numbers/README.md index 567d3b7dc0f46..6e0380518ac01 100644 --- a/solution/2100-2199/2133.Check if Every Row and Column Contains All Numbers/README.md +++ b/solution/2100-2199/2133.Check if Every Row and Column Contains All Numbers/README.md @@ -46,14 +46,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: @@ -75,10 +71,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean checkValid(int[][] matrix) { @@ -108,29 +100,6 @@ class Solution { } ``` -### **TypeScript** - - - -```ts -function checkValid(matrix: number[][]): boolean { - const n = matrix.length; - let rows = Array.from({ length: n }, () => new Array(n).fill(false)); - let cols = Array.from({ length: n }, () => new Array(n).fill(false)); - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - let cur = matrix[i][j]; - if (rows[i][cur] || cols[j][cur]) return false; - rows[i][cur] = true; - cols[j][cur] = true; - } - } - return true; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -157,8 +126,6 @@ public: }; ``` -### **Go** - ```go func checkValid(matrix [][]int) bool { n := len(matrix) @@ -186,10 +153,23 @@ func checkValid(matrix [][]int) bool { } ``` -### **...** - -``` - +```ts +function checkValid(matrix: number[][]): boolean { + const n = matrix.length; + let rows = Array.from({ length: n }, () => new Array(n).fill(false)); + let cols = Array.from({ length: n }, () => new Array(n).fill(false)); + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + let cur = matrix[i][j]; + if (rows[i][cur] || cols[j][cur]) return false; + rows[i][cur] = true; + cols[j][cur] = true; + } + } + return true; +} ``` + + diff --git a/solution/2100-2199/2133.Check if Every Row and Column Contains All Numbers/README_EN.md b/solution/2100-2199/2133.Check if Every Row and Column Contains All Numbers/README_EN.md index 84ad59f414859..6cb03a7608121 100644 --- a/solution/2100-2199/2133.Check if Every Row and Column Contains All Numbers/README_EN.md +++ b/solution/2100-2199/2133.Check if Every Row and Column Contains All Numbers/README_EN.md @@ -38,9 +38,9 @@ Hence, we return false. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean checkValid(int[][] matrix) { @@ -94,27 +92,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function checkValid(matrix: number[][]): boolean { - const n = matrix.length; - let rows = Array.from({ length: n }, () => new Array(n).fill(false)); - let cols = Array.from({ length: n }, () => new Array(n).fill(false)); - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - let cur = matrix[i][j]; - if (rows[i][cur] || cols[j][cur]) return false; - rows[i][cur] = true; - cols[j][cur] = true; - } - } - return true; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -141,8 +118,6 @@ public: }; ``` -### **Go** - ```go func checkValid(matrix [][]int) bool { n := len(matrix) @@ -170,10 +145,23 @@ func checkValid(matrix [][]int) bool { } ``` -### **...** - -``` - +```ts +function checkValid(matrix: number[][]): boolean { + const n = matrix.length; + let rows = Array.from({ length: n }, () => new Array(n).fill(false)); + let cols = Array.from({ length: n }, () => new Array(n).fill(false)); + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + let cur = matrix[i][j]; + if (rows[i][cur] || cols[j][cur]) return false; + rows[i][cur] = true; + cols[j][cur] = true; + } + } + return true; +} ``` + + diff --git a/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README.md b/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README.md index 36baef72c9945..00488889f3946 100644 --- a/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README.md +++ b/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README.md @@ -55,16 +55,10 @@ ## 解法 - - -前缀和 + 滑动窗口。 +### 方法一 -### **Python3** - - - ```python class Solution: def minSwaps(self, nums: List[int]) -> int: @@ -81,10 +75,6 @@ class Solution: return cnt - mx ``` -### **Java** - - - ```java class Solution { public int minSwaps(int[] nums) { @@ -109,28 +99,6 @@ class Solution { } ``` -### **TypeScript** - - - -```ts -function minSwaps(nums: number[]): number { - const n = nums.length; - const m = nums.reduce((a, c) => a + c, 0); - let cnt = nums.reduce((a, c, i) => a + (i < m ? c : 0), 0); - let ans = cnt; - for (let i = m; i < m + n; i++) { - let prev = nums[i - m]; - let post = nums[i % n]; - cnt += post - prev; - ans = Math.max(cnt, ans); - } - return m - ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -150,8 +118,6 @@ public: }; ``` -### **Go** - ```go func minSwaps(nums []int) int { cnt := 0 @@ -174,10 +140,22 @@ func minSwaps(nums []int) int { } ``` -### **...** - -``` - +```ts +function minSwaps(nums: number[]): number { + const n = nums.length; + const m = nums.reduce((a, c) => a + c, 0); + let cnt = nums.reduce((a, c, i) => a + (i < m ? c : 0), 0); + let ans = cnt; + for (let i = m; i < m + n; i++) { + let prev = nums[i - m]; + let post = nums[i % n]; + cnt += post - prev; + ans = Math.max(cnt, ans); + } + return m - ans; +} ``` + + diff --git a/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README_EN.md b/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README_EN.md index 1a687b9af7478..bb70fea63206f 100644 --- a/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README_EN.md +++ b/solution/2100-2199/2134.Minimum Swaps to Group All 1's Together II/README_EN.md @@ -55,9 +55,9 @@ Thus, the minimum number of swaps required is 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return cnt - mx ``` -### **Java** - ```java class Solution { public int minSwaps(int[] nums) { @@ -101,26 +99,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minSwaps(nums: number[]): number { - const n = nums.length; - const m = nums.reduce((a, c) => a + c, 0); - let cnt = nums.reduce((a, c, i) => a + (i < m ? c : 0), 0); - let ans = cnt; - for (let i = m; i < m + n; i++) { - let prev = nums[i - m]; - let post = nums[i % n]; - cnt += post - prev; - ans = Math.max(cnt, ans); - } - return m - ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -140,8 +118,6 @@ public: }; ``` -### **Go** - ```go func minSwaps(nums []int) int { cnt := 0 @@ -164,10 +140,22 @@ func minSwaps(nums []int) int { } ``` -### **...** - -``` - +```ts +function minSwaps(nums: number[]): number { + const n = nums.length; + const m = nums.reduce((a, c) => a + c, 0); + let cnt = nums.reduce((a, c, i) => a + (i < m ? c : 0), 0); + let ans = cnt; + for (let i = m; i < m + n; i++) { + let prev = nums[i - m]; + let post = nums[i % n]; + cnt += post - prev; + ans = Math.max(cnt, ans); + } + return m - ans; +} ``` + + diff --git a/solution/2100-2199/2135.Count Words Obtained After Adding a Letter/README.md b/solution/2100-2199/2135.Count Words Obtained After Adding a Letter/README.md index 3344b89ba725e..8be81a7439d9d 100644 --- a/solution/2100-2199/2135.Count Words Obtained After Adding a Letter/README.md +++ b/solution/2100-2199/2135.Count Words Obtained After Adding a Letter/README.md @@ -68,14 +68,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def wordCount(self, startWords: List[str], targetWords: List[str]) -> int: @@ -99,10 +95,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { @@ -134,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -165,8 +155,6 @@ public: }; ``` -### **Go** - ```go func wordCount(startWords []string, targetWords []string) int { s := make(map[int]bool) @@ -195,18 +183,6 @@ func wordCount(startWords []string, targetWords []string) int { } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2135.Count Words Obtained After Adding a Letter/README_EN.md b/solution/2100-2199/2135.Count Words Obtained After Adding a Letter/README_EN.md index 4b4f3be5b90cc..063e0f59a92ae 100644 --- a/solution/2100-2199/2135.Count Words Obtained After Adding a Letter/README_EN.md +++ b/solution/2100-2199/2135.Count Words Obtained After Adding a Letter/README_EN.md @@ -64,9 +64,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -91,8 +91,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { @@ -124,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +151,6 @@ public: }; ``` -### **Go** - ```go func wordCount(startWords []string, targetWords []string) int { s := make(map[int]bool) @@ -185,16 +179,6 @@ func wordCount(startWords []string, targetWords []string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/README.md b/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/README.md index ed770ea3dad46..27cd51e6f4a0e 100644 --- a/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/README.md +++ b/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 根据题目描述,我们知道,每一天只能为一枚种子进行播种,因此不管什么播种顺序,所有种子的播种时间之和总是等于 $\sum_{i=0}^{n-1} plantTime[i]$。那么,为了让尽快让所有种子开花,我们应该尽快播种生长时间最长的种子。因此,我们可以对所有种子按照生长时间从大到小进行排序,然后依次进行播种。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int earliestFullBloom(int[] plantTime, int[] growTime) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func earliestFullBloom(plantTime []int, growTime []int) (ans int) { n := len(plantTime) @@ -150,8 +136,6 @@ func earliestFullBloom(plantTime []int, growTime []int) (ans int) { } ``` -### **TypeScript** - ```ts function earliestFullBloom(plantTime: number[], growTime: number[]): number { const n = plantTime.length; @@ -166,8 +150,6 @@ function earliestFullBloom(plantTime: number[], growTime: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn earliest_full_bloom(plant_time: Vec, grow_time: Vec) -> i32 { @@ -184,10 +166,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/README_EN.md b/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/README_EN.md index f2e891016f626..cb6803ad490c8 100644 --- a/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/README_EN.md +++ b/solution/2100-2199/2136.Earliest Possible Day of Full Bloom/README_EN.md @@ -63,9 +63,9 @@ Thus, on day 2, all the seeds are blooming. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int earliestFullBloom(int[] plantTime, int[] growTime) { @@ -98,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func earliestFullBloom(plantTime []int, growTime []int) (ans int) { n := len(plantTime) @@ -137,8 +131,6 @@ func earliestFullBloom(plantTime []int, growTime []int) (ans int) { } ``` -### **TypeScript** - ```ts function earliestFullBloom(plantTime: number[], growTime: number[]): number { const n = plantTime.length; @@ -153,8 +145,6 @@ function earliestFullBloom(plantTime: number[], growTime: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn earliest_full_bloom(plant_time: Vec, grow_time: Vec) -> i32 { @@ -171,10 +161,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2137.Pour Water Between Buckets to Make Water Levels Equal/README.md b/solution/2100-2199/2137.Pour Water Between Buckets to Make Water Levels Equal/README.md index 6ad40201c9e69..56de25d72a219 100644 --- a/solution/2100-2199/2137.Pour Water Between Buckets to Make Water Levels Equal/README.md +++ b/solution/2100-2199/2137.Pour Water Between Buckets to Make Water Levels Equal/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:二分查找(浮点数二分)** +### 方法一:二分查找(浮点数二分) 我们注意到,如果一个水量 $x$ 满足条件,那么所有小于 $x$ 的水量也满足条件。因此我们可以使用二分查找的方法找到最大的满足条件的水量。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def equalizeWater(self, buckets: List[int], loss: int) -> float: @@ -94,10 +88,6 @@ class Solution: return l ``` -### **Java** - - - ```java class Solution { public double equalizeWater(int[] buckets, int loss) { @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +147,6 @@ public: }; ``` -### **Go** - ```go func equalizeWater(buckets []int, loss int) float64 { check := func(v float64) bool { @@ -188,8 +174,6 @@ func equalizeWater(buckets []int, loss int) float64 { } ``` -### **TypeScript** - ```ts function equalizeWater(buckets: number[], loss: number): number { let l = 0; @@ -217,10 +201,6 @@ function equalizeWater(buckets: number[], loss: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2137.Pour Water Between Buckets to Make Water Levels Equal/README_EN.md b/solution/2100-2199/2137.Pour Water Between Buckets to Make Water Levels Equal/README_EN.md index c3b904758b203..a403910056ce3 100644 --- a/solution/2100-2199/2137.Pour Water Between Buckets to Make Water Levels Equal/README_EN.md +++ b/solution/2100-2199/2137.Pour Water Between Buckets to Make Water Levels Equal/README_EN.md @@ -53,9 +53,9 @@ All buckets have 3.5 gallons of water in them so return 3.5. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,8 +79,6 @@ class Solution: return l ``` -### **Java** - ```java class Solution { public double equalizeWater(int[] buckets, int loss) { @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +138,6 @@ public: }; ``` -### **Go** - ```go func equalizeWater(buckets []int, loss int) float64 { check := func(v float64) bool { @@ -171,8 +165,6 @@ func equalizeWater(buckets []int, loss int) float64 { } ``` -### **TypeScript** - ```ts function equalizeWater(buckets: number[], loss: number): number { let l = 0; @@ -200,10 +192,6 @@ function equalizeWater(buckets: number[], loss: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2138.Divide a String Into Groups of Size k/README.md b/solution/2100-2199/2138.Divide a String Into Groups of Size k/README.md index 976334e687ef8..6757b874372b4 100644 --- a/solution/2100-2199/2138.Divide a String Into Groups of Size k/README.md +++ b/solution/2100-2199/2138.Divide a String Into Groups of Size k/README.md @@ -54,24 +54,16 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def divideString(self, s: str, k: int, fill: str) -> List[str]: return [s[i : i + k].ljust(k, fill) for i in range(0, len(s), k)] ``` -### **Java** - - - ```java class Solution { public String[] divideString(String s, int k, char fill) { @@ -88,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +94,6 @@ public: }; ``` -### **Go** - ```go func divideString(s string, k int, fill byte) []string { n := len(s) @@ -120,18 +108,6 @@ func divideString(s string, k int, fill byte) []string { } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2138.Divide a String Into Groups of Size k/README_EN.md b/solution/2100-2199/2138.Divide a String Into Groups of Size k/README_EN.md index e50042ca3796a..ee5069bd28048 100644 --- a/solution/2100-2199/2138.Divide a String Into Groups of Size k/README_EN.md +++ b/solution/2100-2199/2138.Divide a String Into Groups of Size k/README_EN.md @@ -52,9 +52,9 @@ Thus, the 4 groups formed are "abc", "def", "ghi", ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return [s[i : i + k].ljust(k, fill) for i in range(0, len(s), k)] ``` -### **Java** - ```java class Solution { public String[] divideString(String s, int k, char fill) { @@ -80,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func divideString(s string, k int, fill byte) []string { n := len(s) @@ -112,16 +106,6 @@ func divideString(s string, k int, fill byte) []string { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/README.md b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/README.md index df9887b70d101..3cd763b37098d 100644 --- a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/README.md +++ b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:倒推 + 贪心** +### 方法一:倒推 + 贪心 我们不妨从最终的状态开始倒推,假设最终的状态为 $target$,那么我们可以得到 $target$ 的前一个状态为 $target - 1$ 或者 $target / 2$,这取决于 $target$ 的奇偶性以及 $maxDoubles$ 的值。 @@ -83,10 +81,6 @@ -### **Python3** - - - ```python class Solution: def minMoves(self, target: int, maxDoubles: int) -> int: @@ -99,25 +93,6 @@ class Solution: return 1 + self.minMoves(target - 1, maxDoubles) ``` -```python -class Solution: - def minMoves(self, target: int, maxDoubles: int) -> int: - ans = 0 - while maxDoubles and target > 1: - ans += 1 - if target % 2 == 1: - target -= 1 - else: - maxDoubles -= 1 - target >>= 1 - ans += target - 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int minMoves(int target, int maxDoubles) { @@ -135,6 +110,75 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minMoves(int target, int maxDoubles) { + if (target == 1) { + return 0; + } + if (maxDoubles == 0) { + return target - 1; + } + if (target % 2 == 0 && maxDoubles > 0) { + return 1 + minMoves(target >> 1, maxDoubles - 1); + } + return 1 + minMoves(target - 1, maxDoubles); + } +}; +``` + +```go +func minMoves(target int, maxDoubles int) int { + if target == 1 { + return 0 + } + if maxDoubles == 0 { + return target - 1 + } + if target%2 == 0 && maxDoubles > 0 { + return 1 + minMoves(target>>1, maxDoubles-1) + } + return 1 + minMoves(target-1, maxDoubles) +} +``` + +```ts +function minMoves(target: number, maxDoubles: number): number { + if (target === 1) { + return 0; + } + if (maxDoubles === 0) { + return target - 1; + } + if (target % 2 === 0 && maxDoubles) { + return 1 + minMoves(target >> 1, maxDoubles - 1); + } + return 1 + minMoves(target - 1, maxDoubles); +} +``` + + + +### 方法二 + + + +```python +class Solution: + def minMoves(self, target: int, maxDoubles: int) -> int: + ans = 0 + while maxDoubles and target > 1: + ans += 1 + if target % 2 == 1: + target -= 1 + else: + maxDoubles -= 1 + target >>= 1 + ans += target - 1 + return ans +``` + ```java class Solution { public int minMoves(int target, int maxDoubles) { @@ -154,26 +198,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minMoves(int target, int maxDoubles) { - if (target == 1) { - return 0; - } - if (maxDoubles == 0) { - return target - 1; - } - if (target % 2 == 0 && maxDoubles > 0) { - return 1 + minMoves(target >> 1, maxDoubles - 1); - } - return 1 + minMoves(target - 1, maxDoubles); - } -}; -``` - ```cpp class Solution { public: @@ -194,23 +218,6 @@ public: }; ``` -### **Go** - -```go -func minMoves(target int, maxDoubles int) int { - if target == 1 { - return 0 - } - if maxDoubles == 0 { - return target - 1 - } - if target%2 == 0 && maxDoubles > 0 { - return 1 + minMoves(target>>1, maxDoubles-1) - } - return 1 + minMoves(target-1, maxDoubles) -} -``` - ```go func minMoves(target int, maxDoubles int) (ans int) { for maxDoubles > 0 && target > 1 { @@ -227,23 +234,6 @@ func minMoves(target int, maxDoubles int) (ans int) { } ``` -### **TypeScript** - -```ts -function minMoves(target: number, maxDoubles: number): number { - if (target === 1) { - return 0; - } - if (maxDoubles === 0) { - return target - 1; - } - if (target % 2 === 0 && maxDoubles) { - return 1 + minMoves(target >> 1, maxDoubles - 1); - } - return 1 + minMoves(target - 1, maxDoubles); -} -``` - ```ts function minMoves(target: number, maxDoubles: number): number { let ans = 0; @@ -261,10 +251,6 @@ function minMoves(target: number, maxDoubles: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/README_EN.md b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/README_EN.md index e1e1c0ae6b8bb..3a268cc98364d 100644 --- a/solution/2100-2199/2139.Minimum Moves to Reach Target Score/README_EN.md +++ b/solution/2100-2199/2139.Minimum Moves to Reach Target Score/README_EN.md @@ -61,7 +61,7 @@ Double again so x = 10 ## Solutions -**Solution 1: Backtracking + Greedy** +### Solution 1: Backtracking + Greedy Let's start by backtracking from the final state. Assuming the final state is $target$, we can get the previous state of $target$ as $target - 1$ or $target / 2$, depending on the parity of $target$ and the value of $maxDoubles$. @@ -79,8 +79,6 @@ We can also change the above process to an iterative way to avoid the space over -### **Python3** - ```python class Solution: def minMoves(self, target: int, maxDoubles: int) -> int: @@ -93,23 +91,6 @@ class Solution: return 1 + self.minMoves(target - 1, maxDoubles) ``` -```python -class Solution: - def minMoves(self, target: int, maxDoubles: int) -> int: - ans = 0 - while maxDoubles and target > 1: - ans += 1 - if target % 2 == 1: - target -= 1 - else: - maxDoubles -= 1 - target >>= 1 - ans += target - 1 - return ans -``` - -### **Java** - ```java class Solution { public int minMoves(int target, int maxDoubles) { @@ -127,6 +108,75 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minMoves(int target, int maxDoubles) { + if (target == 1) { + return 0; + } + if (maxDoubles == 0) { + return target - 1; + } + if (target % 2 == 0 && maxDoubles > 0) { + return 1 + minMoves(target >> 1, maxDoubles - 1); + } + return 1 + minMoves(target - 1, maxDoubles); + } +}; +``` + +```go +func minMoves(target int, maxDoubles int) int { + if target == 1 { + return 0 + } + if maxDoubles == 0 { + return target - 1 + } + if target%2 == 0 && maxDoubles > 0 { + return 1 + minMoves(target>>1, maxDoubles-1) + } + return 1 + minMoves(target-1, maxDoubles) +} +``` + +```ts +function minMoves(target: number, maxDoubles: number): number { + if (target === 1) { + return 0; + } + if (maxDoubles === 0) { + return target - 1; + } + if (target % 2 === 0 && maxDoubles) { + return 1 + minMoves(target >> 1, maxDoubles - 1); + } + return 1 + minMoves(target - 1, maxDoubles); +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minMoves(self, target: int, maxDoubles: int) -> int: + ans = 0 + while maxDoubles and target > 1: + ans += 1 + if target % 2 == 1: + target -= 1 + else: + maxDoubles -= 1 + target >>= 1 + ans += target - 1 + return ans +``` + ```java class Solution { public int minMoves(int target, int maxDoubles) { @@ -146,26 +196,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minMoves(int target, int maxDoubles) { - if (target == 1) { - return 0; - } - if (maxDoubles == 0) { - return target - 1; - } - if (target % 2 == 0 && maxDoubles > 0) { - return 1 + minMoves(target >> 1, maxDoubles - 1); - } - return 1 + minMoves(target - 1, maxDoubles); - } -}; -``` - ```cpp class Solution { public: @@ -186,23 +216,6 @@ public: }; ``` -### **Go** - -```go -func minMoves(target int, maxDoubles int) int { - if target == 1 { - return 0 - } - if maxDoubles == 0 { - return target - 1 - } - if target%2 == 0 && maxDoubles > 0 { - return 1 + minMoves(target>>1, maxDoubles-1) - } - return 1 + minMoves(target-1, maxDoubles) -} -``` - ```go func minMoves(target int, maxDoubles int) (ans int) { for maxDoubles > 0 && target > 1 { @@ -219,23 +232,6 @@ func minMoves(target int, maxDoubles int) (ans int) { } ``` -### **TypeScript** - -```ts -function minMoves(target: number, maxDoubles: number): number { - if (target === 1) { - return 0; - } - if (maxDoubles === 0) { - return target - 1; - } - if (target % 2 === 0 && maxDoubles) { - return 1 + minMoves(target >> 1, maxDoubles - 1); - } - return 1 + minMoves(target - 1, maxDoubles); -} -``` - ```ts function minMoves(target: number, maxDoubles: number): number { let ans = 0; @@ -253,10 +249,6 @@ function minMoves(target: number, maxDoubles: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2140.Solving Questions With Brainpower/README.md b/solution/2100-2199/2140.Solving Questions With Brainpower/README.md index 4304d6d56ac78..3759601681187 100644 --- a/solution/2100-2199/2140.Solving Questions With Brainpower/README.md +++ b/solution/2100-2199/2140.Solving Questions With Brainpower/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i)$,表示从第 $i$ 个问题开始解决,能够获得的最高分数。那么答案就是 $dfs(0)$。 @@ -74,26 +72,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是问题的数量。 -**方法二:动态规划** - -我们定义 $f[i]$ 表示从第 $i$ 个问题开始解决,能够获得的最高分数。那么答案就是 $f[0]$。 - -考虑 $f[i]$,第 $i$ 个问题的分数为 $p$,需要跳过的问题数为 $b$。如果我们解决了第 $i$ 个问题,那么接下来我们需要解决 $b$ 个问题,因此 $f[i] = p + f[i + b + 1]$。如果我们跳过了第 $i$ 个问题,那么接下来我们从第 $i + 1$ 个问题开始解决,因此 $f[i] = f[i + 1]$。两者取最大值即可。状态转移方程如下: - -$$ -f[i] = \max(p + f[i + b + 1], f[i + 1]) -$$ - -我们从后往前计算 $f$ 的值,最后返回 $f[0]$ 即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是问题的数量。 - -### **Python3** - - - ```python class Solution: def mostPoints(self, questions: List[List[int]]) -> int: @@ -107,22 +87,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def mostPoints(self, questions: List[List[int]]) -> int: - n = len(questions) - f = [0] * (n + 1) - for i in range(n - 1, -1, -1): - p, b = questions[i] - j = i + b + 1 - f[i] = max(f[i + 1], p + (0 if j > n else f[j])) - return f[0] -``` - -### **Java** - - - ```java class Solution { private int n; @@ -149,23 +113,6 @@ class Solution { } ``` -```java -class Solution { - public long mostPoints(int[][] questions) { - int n = questions.length; - long[] f = new long[n + 1]; - for (int i = n - 1; i >= 0; --i) { - int p = questions[i][0], b = questions[i][1]; - int j = i + b + 1; - f[i] = Math.max(f[i + 1], p + (j > n ? 0 : f[j])); - } - return f[0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -188,25 +135,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long mostPoints(vector>& questions) { - int n = questions.size(); - long long f[n + 1]; - memset(f, 0, sizeof(f)); - for (int i = n - 1; ~i; --i) { - int p = questions[i][0], b = questions[i][1]; - int j = i + b + 1; - f[i] = max(f[i + 1], p + (j > n ? 0 : f[j])); - } - return f[0]; - } -}; -``` - -### **Go** - ```go func mostPoints(questions [][]int) int64 { n := len(questions) @@ -227,23 +155,6 @@ func mostPoints(questions [][]int) int64 { } ``` -```go -func mostPoints(questions [][]int) int64 { - n := len(questions) - f := make([]int64, n+1) - for i := n - 1; i >= 0; i-- { - p := int64(questions[i][0]) - if j := i + questions[i][1] + 1; j <= n { - p += f[j] - } - f[i] = max(f[i+1], p) - } - return f[0] -} -``` - -### **TypeScript** - ```ts function mostPoints(questions: number[][]): number { const n = questions.length; @@ -262,6 +173,83 @@ function mostPoints(questions: number[][]): number { } ``` + + +### 方法二:动态规划 + +我们定义 $f[i]$ 表示从第 $i$ 个问题开始解决,能够获得的最高分数。那么答案就是 $f[0]$。 + +考虑 $f[i]$,第 $i$ 个问题的分数为 $p$,需要跳过的问题数为 $b$。如果我们解决了第 $i$ 个问题,那么接下来我们需要解决 $b$ 个问题,因此 $f[i] = p + f[i + b + 1]$。如果我们跳过了第 $i$ 个问题,那么接下来我们从第 $i + 1$ 个问题开始解决,因此 $f[i] = f[i + 1]$。两者取最大值即可。状态转移方程如下: + +$$ +f[i] = \max(p + f[i + b + 1], f[i + 1]) +$$ + +我们从后往前计算 $f$ 的值,最后返回 $f[0]$ 即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是问题的数量。 + + + +```python +class Solution: + def mostPoints(self, questions: List[List[int]]) -> int: + n = len(questions) + f = [0] * (n + 1) + for i in range(n - 1, -1, -1): + p, b = questions[i] + j = i + b + 1 + f[i] = max(f[i + 1], p + (0 if j > n else f[j])) + return f[0] +``` + +```java +class Solution { + public long mostPoints(int[][] questions) { + int n = questions.length; + long[] f = new long[n + 1]; + for (int i = n - 1; i >= 0; --i) { + int p = questions[i][0], b = questions[i][1]; + int j = i + b + 1; + f[i] = Math.max(f[i + 1], p + (j > n ? 0 : f[j])); + } + return f[0]; + } +} +``` + +```cpp +class Solution { +public: + long long mostPoints(vector>& questions) { + int n = questions.size(); + long long f[n + 1]; + memset(f, 0, sizeof(f)); + for (int i = n - 1; ~i; --i) { + int p = questions[i][0], b = questions[i][1]; + int j = i + b + 1; + f[i] = max(f[i + 1], p + (j > n ? 0 : f[j])); + } + return f[0]; + } +}; +``` + +```go +func mostPoints(questions [][]int) int64 { + n := len(questions) + f := make([]int64, n+1) + for i := n - 1; i >= 0; i-- { + p := int64(questions[i][0]) + if j := i + questions[i][1] + 1; j <= n { + p += f[j] + } + f[i] = max(f[i+1], p) + } + return f[0] +} +``` + ```ts function mostPoints(questions: number[][]): number { const n = questions.length; @@ -275,10 +263,6 @@ function mostPoints(questions: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2140.Solving Questions With Brainpower/README_EN.md b/solution/2100-2199/2140.Solving Questions With Brainpower/README_EN.md index 825e88b01a258..7d5e99c8670e2 100644 --- a/solution/2100-2199/2140.Solving Questions With Brainpower/README_EN.md +++ b/solution/2100-2199/2140.Solving Questions With Brainpower/README_EN.md @@ -57,9 +57,9 @@ Total points earned: 2 + 5 = 7. There is no other way to earn 7 or more points. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,20 +74,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def mostPoints(self, questions: List[List[int]]) -> int: - n = len(questions) - f = [0] * (n + 1) - for i in range(n - 1, -1, -1): - p, b = questions[i] - j = i + b + 1 - f[i] = max(f[i + 1], p + (0 if j > n else f[j])) - return f[0] -``` - -### **Java** - ```java class Solution { private int n; @@ -114,23 +100,6 @@ class Solution { } ``` -```java -class Solution { - public long mostPoints(int[][] questions) { - int n = questions.length; - long[] f = new long[n + 1]; - for (int i = n - 1; i >= 0; --i) { - int p = questions[i][0], b = questions[i][1]; - int j = i + b + 1; - f[i] = Math.max(f[i + 1], p + (j > n ? 0 : f[j])); - } - return f[0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -153,25 +122,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long mostPoints(vector>& questions) { - int n = questions.size(); - long long f[n + 1]; - memset(f, 0, sizeof(f)); - for (int i = n - 1; ~i; --i) { - int p = questions[i][0], b = questions[i][1]; - int j = i + b + 1; - f[i] = max(f[i + 1], p + (j > n ? 0 : f[j])); - } - return f[0]; - } -}; -``` - -### **Go** - ```go func mostPoints(questions [][]int) int64 { n := len(questions) @@ -192,23 +142,6 @@ func mostPoints(questions [][]int) int64 { } ``` -```go -func mostPoints(questions [][]int) int64 { - n := len(questions) - f := make([]int64, n+1) - for i := n - 1; i >= 0; i-- { - p := int64(questions[i][0]) - if j := i + questions[i][1] + 1; j <= n { - p += f[j] - } - f[i] = max(f[i+1], p) - } - return f[0] -} -``` - -### **TypeScript** - ```ts function mostPoints(questions: number[][]): number { const n = questions.length; @@ -227,6 +160,71 @@ function mostPoints(questions: number[][]): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def mostPoints(self, questions: List[List[int]]) -> int: + n = len(questions) + f = [0] * (n + 1) + for i in range(n - 1, -1, -1): + p, b = questions[i] + j = i + b + 1 + f[i] = max(f[i + 1], p + (0 if j > n else f[j])) + return f[0] +``` + +```java +class Solution { + public long mostPoints(int[][] questions) { + int n = questions.length; + long[] f = new long[n + 1]; + for (int i = n - 1; i >= 0; --i) { + int p = questions[i][0], b = questions[i][1]; + int j = i + b + 1; + f[i] = Math.max(f[i + 1], p + (j > n ? 0 : f[j])); + } + return f[0]; + } +} +``` + +```cpp +class Solution { +public: + long long mostPoints(vector>& questions) { + int n = questions.size(); + long long f[n + 1]; + memset(f, 0, sizeof(f)); + for (int i = n - 1; ~i; --i) { + int p = questions[i][0], b = questions[i][1]; + int j = i + b + 1; + f[i] = max(f[i + 1], p + (j > n ? 0 : f[j])); + } + return f[0]; + } +}; +``` + +```go +func mostPoints(questions [][]int) int64 { + n := len(questions) + f := make([]int64, n+1) + for i := n - 1; i >= 0; i-- { + p := int64(questions[i][0]) + if j := i + questions[i][1] + 1; j <= n { + p += f[j] + } + f[i] = max(f[i+1], p) + } + return f[0] +} +``` + ```ts function mostPoints(questions: number[][]): number { const n = questions.length; @@ -240,10 +238,6 @@ function mostPoints(questions: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2141.Maximum Running Time of N Computers/README.md b/solution/2100-2199/2141.Maximum Running Time of N Computers/README.md index 6f4394a56112f..8e0d6d40ed0da 100644 --- a/solution/2100-2199/2141.Maximum Running Time of N Computers/README.md +++ b/solution/2100-2199/2141.Maximum Running Time of N Computers/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们注意到,如果我们可以让 $n$ 台电脑同时运行 $t$ 分钟,那么我们也可以让 $n$ 台电脑同时运行 $t' \le t$ 分钟,这存在着单调性。因此,我们可以使用二分查找的方法找到最大的 $t$。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def maxRunTime(self, n: int, batteries: List[int]) -> int: @@ -85,10 +79,6 @@ class Solution: return l ``` -### **Java** - - - ```java class Solution { public long maxRunTime(int n, int[] batteries) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func maxRunTime(n int, batteries []int) int64 { l, r := 0, 0 @@ -164,8 +150,6 @@ func maxRunTime(n int, batteries []int) int64 { } ``` -### **TypeScript** - ```ts function maxRunTime(n: number, batteries: number[]): number { let l = 0n; @@ -189,8 +173,6 @@ function maxRunTime(n: number, batteries: number[]): number { } ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -243,10 +225,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2141.Maximum Running Time of N Computers/README_EN.md b/solution/2100-2199/2141.Maximum Running Time of N Computers/README_EN.md index f8d3e9be40943..0c45724c6d358 100644 --- a/solution/2100-2199/2141.Maximum Running Time of N Computers/README_EN.md +++ b/solution/2100-2199/2141.Maximum Running Time of N Computers/README_EN.md @@ -49,9 +49,9 @@ We can run the two computers simultaneously for at most 2 minutes, so we return ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return l ``` -### **Java** - ```java class Solution { public long maxRunTime(int n, int[] batteries) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +115,6 @@ public: }; ``` -### **Go** - ```go func maxRunTime(n int, batteries []int) int64 { l, r := 0, 0 @@ -143,8 +137,6 @@ func maxRunTime(n int, batteries []int) int64 { } ``` -### **TypeScript** - ```ts function maxRunTime(n: number, batteries: number[]): number { let l = 0n; @@ -168,8 +160,6 @@ function maxRunTime(n: number, batteries: number[]): number { } ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -222,10 +212,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2142.The Number of Passengers in Each Bus I/README.md b/solution/2100-2199/2142.The Number of Passengers in Each Bus I/README.md index bab00d6389296..dd1524dd63394 100644 --- a/solution/2100-2199/2142.The Number of Passengers in Each Bus I/README.md +++ b/solution/2100-2199/2142.The Number of Passengers in Each Bus I/README.md @@ -86,14 +86,10 @@ Passengers 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -109,3 +105,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2100-2199/2142.The Number of Passengers in Each Bus I/README_EN.md b/solution/2100-2199/2142.The Number of Passengers in Each Bus I/README_EN.md index bffd0506e96f2..e6a0831f76af0 100644 --- a/solution/2100-2199/2142.The Number of Passengers in Each Bus I/README_EN.md +++ b/solution/2100-2199/2142.The Number of Passengers in Each Bus I/README_EN.md @@ -87,9 +87,9 @@ Passengers table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -106,3 +106,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/README.md b/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/README.md index 10caf57950b9f..366044371ac3f 100644 --- a/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/README.md +++ b/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/README.md @@ -71,9 +71,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示以第 $i$ 个元素结尾,且从 $nums1$ 中选取的数字和与从 $nums2$ 中选取的数字和之差为 $j$ 的平衡区间的个数。由于差值可能为负数,因此,我们统一将 $j$ 加上 $s_2 = \sum_{k=0}^{n-1}nums2[k]$,这样就可以保证 $j$ 为非负整数。 @@ -85,10 +83,6 @@ -### **Python3** - - - ```python class Solution: def countSubranges(self, nums1: List[int], nums2: List[int]) -> int: @@ -110,10 +104,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countSubranges(int[] nums1, int[] nums2) { @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -178,8 +166,6 @@ public: }; ``` -### **Go** - ```go func countSubranges(nums1 []int, nums2 []int) (ans int) { n := len(nums1) @@ -216,8 +202,6 @@ func sum(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function countSubranges(nums1: number[], nums2: number[]): number { const n = nums1.length; @@ -248,10 +232,6 @@ function countSubranges(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/README_EN.md b/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/README_EN.md index 7961bcacf3f66..2abb9c5ae4e93 100644 --- a/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/README_EN.md +++ b/solution/2100-2199/2143.Choose Numbers From Two Arrays in Range/README_EN.md @@ -67,9 +67,9 @@ In the second balanced range, we choose nums2[1] and in the third balanced range ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -92,8 +92,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countSubranges(int[] nums1, int[] nums2) { @@ -124,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +154,6 @@ public: }; ``` -### **Go** - ```go func countSubranges(nums1 []int, nums2 []int) (ans int) { n := len(nums1) @@ -196,8 +190,6 @@ func sum(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function countSubranges(nums1: number[], nums2: number[]): number { const n = nums1.length; @@ -228,10 +220,6 @@ function countSubranges(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/README.md b/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/README.md index 7d9b1e95c1080..955829b21f21b 100644 --- a/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/README.md +++ b/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们可以先将糖果按照价格从高到低排序,然后每三个糖果中取两个糖果,这样可以保证免费获得的糖果价格最高,从而使得总开销最小。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def minimumCost(self, cost: List[int]) -> int: @@ -80,10 +74,6 @@ class Solution: return sum(cost) - sum(cost[2::3]) ``` -### **Java** - - - ```java class Solution { public int minimumCost(int[] cost) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func minimumCost(cost []int) (ans int) { sort.Ints(cost) @@ -134,8 +120,6 @@ func minimumCost(cost []int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumCost(cost: number[]): number { cost.sort((a, b) => a - b); @@ -150,10 +134,6 @@ function minimumCost(cost: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/README_EN.md b/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/README_EN.md index 97a866e648248..164b57cba7f8a 100644 --- a/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/README_EN.md +++ b/solution/2100-2199/2144.Minimum Cost of Buying Candies With Discount/README_EN.md @@ -58,9 +58,9 @@ Hence, the minimum cost to buy all candies is 5 + 5 = 10. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return sum(cost) - sum(cost[2::3]) ``` -### **Java** - ```java class Solution { public int minimumCost(int[] cost) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +102,6 @@ public: }; ``` -### **Go** - ```go func minimumCost(cost []int) (ans int) { sort.Ints(cost) @@ -121,8 +115,6 @@ func minimumCost(cost []int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumCost(cost: number[]): number { cost.sort((a, b) => a - b); @@ -137,10 +129,6 @@ function minimumCost(cost: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2145.Count the Hidden Sequences/README.md b/solution/2100-2199/2145.Count the Hidden Sequences/README.md index 275702878ecce..97f0970c09022 100644 --- a/solution/2100-2199/2145.Count the Hidden Sequences/README.md +++ b/solution/2100-2199/2145.Count the Hidden Sequences/README.md @@ -66,14 +66,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int: @@ -85,10 +81,6 @@ class Solution: return max(0, upper - lower - (mx - mi) + 1) ``` -### **Java** - - - ```java class Solution { public int numberOfArrays(int[] differences, int lower, int upper) { @@ -103,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +110,6 @@ public: }; ``` -### **Go** - ```go func numberOfArrays(differences []int, lower int, upper int) int { num, mi, mx := 0, 0, 0 @@ -134,18 +122,6 @@ func numberOfArrays(differences []int, lower int, upper int) int { } ``` -### **TypeScript** - - - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2145.Count the Hidden Sequences/README_EN.md b/solution/2100-2199/2145.Count the Hidden Sequences/README_EN.md index f19f27593f09a..2ee7e828293bd 100644 --- a/solution/2100-2199/2145.Count the Hidden Sequences/README_EN.md +++ b/solution/2100-2199/2145.Count the Hidden Sequences/README_EN.md @@ -65,9 +65,9 @@ Thus, we return 4. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return max(0, upper - lower - (mx - mi) + 1) ``` -### **Java** - ```java class Solution { public int numberOfArrays(int[] differences, int lower, int upper) { @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func numberOfArrays(differences []int, lower int, upper int) int { num, mi, mx := 0, 0, 0 @@ -127,16 +121,6 @@ func numberOfArrays(differences []int, lower int, upper int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2146.K Highest Ranked Items Within a Price Range/README.md b/solution/2100-2199/2146.K Highest Ranked Items Within a Price Range/README.md index a32388310d0e9..6ec64b59e8690 100644 --- a/solution/2100-2199/2146.K Highest Ranked Items Within a Price Range/README.md +++ b/solution/2100-2199/2146.K Highest Ranked Items Within a Price Range/README.md @@ -99,16 +99,10 @@ ## 解法 - - -BFS。 +### 方法一 -### **Python3** - - - ```python class Solution: def highestRankedKItems( @@ -134,10 +128,6 @@ class Solution: return [item[2:] for item in items][:k] ``` -### **Java** - - - ```java class Solution { public List> highestRankedKItems( @@ -189,8 +179,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -228,8 +216,6 @@ public: }; ``` -### **Go** - ```go func highestRankedKItems(grid [][]int, pricing []int, start []int, k int) [][]int { m, n := len(grid), len(grid[0]) @@ -278,16 +264,6 @@ func highestRankedKItems(grid [][]int, pricing []int, start []int, k int) [][]in } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2146.K Highest Ranked Items Within a Price Range/README_EN.md b/solution/2100-2199/2146.K Highest Ranked Items Within a Price Range/README_EN.md index eeb42ec2dbf65..af78dfe6dabee 100644 --- a/solution/2100-2199/2146.K Highest Ranked Items Within a Price Range/README_EN.md +++ b/solution/2100-2199/2146.K Highest Ranked Items Within a Price Range/README_EN.md @@ -92,12 +92,10 @@ Note that k = 3 but there are only 2 reachable items within the price range. ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def highestRankedKItems( @@ -123,8 +121,6 @@ class Solution: return [item[2:] for item in items][:k] ``` -### **Java** - ```java class Solution { public List> highestRankedKItems( @@ -176,8 +172,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -215,8 +209,6 @@ public: }; ``` -### **Go** - ```go func highestRankedKItems(grid [][]int, pricing []int, start []int, k int) [][]int { m, n := len(grid), len(grid[0]) @@ -265,16 +257,6 @@ func highestRankedKItems(grid [][]int, pricing []int, start []int, k int) [][]in } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2147.Number of Ways to Divide a Long Corridor/README.md b/solution/2100-2199/2147.Number of Ways to Divide a Long Corridor/README.md index 8dd4a76475f9f..12d0bc441e8df 100644 --- a/solution/2100-2199/2147.Number of Ways to Divide a Long Corridor/README.md +++ b/solution/2100-2199/2147.Number of Ways to Divide a Long Corridor/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 设计函数 `dfs(i, cnt)` 表示从下标 `i` 开始,且当前已经分配了 `cnt` 个座位的方案数。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def numberOfWays(self, corridor: str) -> int: @@ -101,10 +95,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private String s; @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -173,8 +161,6 @@ public: }; ``` -### **Go** - ```go func numberOfWays(corridor string) int { n := len(corridor) @@ -215,8 +201,6 @@ func numberOfWays(corridor string) int { } ``` -### **TypeScript** - ```ts function numberOfWays(corridor: string): number { const M: number = 1e9 + 7; @@ -242,10 +226,6 @@ function numberOfWays(corridor: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2147.Number of Ways to Divide a Long Corridor/README_EN.md b/solution/2100-2199/2147.Number of Ways to Divide a Long Corridor/README_EN.md index 769f17aa979a1..b9dd1617b9816 100644 --- a/solution/2100-2199/2147.Number of Ways to Divide a Long Corridor/README_EN.md +++ b/solution/2100-2199/2147.Number of Ways to Divide a Long Corridor/README_EN.md @@ -51,9 +51,9 @@ Installing any would create some section that does not have exactly two seats. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private String s; @@ -119,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +144,6 @@ public: }; ``` -### **Go** - ```go func numberOfWays(corridor string) int { n := len(corridor) @@ -190,8 +184,6 @@ func numberOfWays(corridor string) int { } ``` -### **TypeScript** - ```ts function numberOfWays(corridor: string): number { const M: number = 1e9 + 7; @@ -217,10 +209,6 @@ function numberOfWays(corridor: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2148.Count Elements With Strictly Smaller and Greater Elements/README.md b/solution/2100-2199/2148.Count Elements With Strictly Smaller and Greater Elements/README.md index eba31183f04e1..c8f68676030b1 100644 --- a/solution/2100-2199/2148.Count Elements With Strictly Smaller and Greater Elements/README.md +++ b/solution/2100-2199/2148.Count Elements With Strictly Smaller and Greater Elements/README.md @@ -40,14 +40,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def countElements(self, nums: List[int]) -> int: @@ -55,10 +51,6 @@ class Solution: return sum(mi < num < mx for num in nums) ``` -### **Java** - - - ```java class Solution { @@ -79,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +89,6 @@ public: }; ``` -### **Go** - ```go func countElements(nums []int) int { mi, mx := int(1e6), -int(1e6) @@ -122,10 +110,6 @@ func countElements(nums []int) int { } ``` -### **TypeScript** - - - ```ts function countElements(nums: number[]): number { const min = Math.min(...nums), @@ -141,10 +125,6 @@ function countElements(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2148.Count Elements With Strictly Smaller and Greater Elements/README_EN.md b/solution/2100-2199/2148.Count Elements With Strictly Smaller and Greater Elements/README_EN.md index 682521ce8c541..6be4548f1639c 100644 --- a/solution/2100-2199/2148.Count Elements With Strictly Smaller and Greater Elements/README_EN.md +++ b/solution/2100-2199/2148.Count Elements With Strictly Smaller and Greater Elements/README_EN.md @@ -36,9 +36,9 @@ Since there are two elements with the value 3, in total there are 2 elements hav ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -47,8 +47,6 @@ class Solution: return sum(mi < num < mx for num in nums) ``` -### **Java** - ```java class Solution { @@ -69,8 +67,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,8 +85,6 @@ public: }; ``` -### **Go** - ```go func countElements(nums []int) int { mi, mx := int(1e6), -int(1e6) @@ -112,8 +106,6 @@ func countElements(nums []int) int { } ``` -### **TypeScript** - ```ts function countElements(nums: number[]): number { const min = Math.min(...nums), @@ -129,10 +121,6 @@ function countElements(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2149.Rearrange Array Elements by Sign/README.md b/solution/2100-2199/2149.Rearrange Array Elements by Sign/README.md index 08115dddccbd6..6c888686f4203 100644 --- a/solution/2100-2199/2149.Rearrange Array Elements by Sign/README.md +++ b/solution/2100-2199/2149.Rearrange Array Elements by Sign/README.md @@ -54,14 +54,10 @@ nums 中的正整数是 [3,1,2] ,负整数是 [-2,-5,-4] 。 ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def rearrangeArray(self, nums: List[int]) -> List[int]: @@ -77,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { @@ -101,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +113,6 @@ public: }; ``` -### **Go** - ```go func rearrangeArray(nums []int) []int { ans := make([]int, len(nums)) @@ -142,10 +130,6 @@ func rearrangeArray(nums []int) []int { } ``` -### **TypeScript** - - - ```ts function rearrangeArray(nums: number[]): number[] { let ans = []; @@ -164,10 +148,6 @@ function rearrangeArray(nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2149.Rearrange Array Elements by Sign/README_EN.md b/solution/2100-2199/2149.Rearrange Array Elements by Sign/README_EN.md index a4a522167264e..3e306ff227bcf 100644 --- a/solution/2100-2199/2149.Rearrange Array Elements by Sign/README_EN.md +++ b/solution/2100-2199/2149.Rearrange Array Elements by Sign/README_EN.md @@ -50,9 +50,9 @@ So nums is rearranged to [1,-1]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func rearrangeArray(nums []int) []int { ans := make([]int, len(nums)) @@ -132,8 +126,6 @@ func rearrangeArray(nums []int) []int { } ``` -### **TypeScript** - ```ts function rearrangeArray(nums: number[]): number[] { let ans = []; @@ -152,10 +144,6 @@ function rearrangeArray(nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2150.Find All Lonely Numbers in the Array/README.md b/solution/2100-2199/2150.Find All Lonely Numbers in the Array/README.md index 7a3eb2e853807..085bb014f225d 100644 --- a/solution/2100-2199/2150.Find All Lonely Numbers in the Array/README.md +++ b/solution/2100-2199/2150.Find All Lonely Numbers in the Array/README.md @@ -46,14 +46,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findLonely(self, nums: List[int]) -> List[int]: @@ -65,10 +61,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { @@ -88,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +96,6 @@ public: }; ``` -### **Go** - ```go func findLonely(nums []int) []int { counter := make(map[int]int) @@ -124,10 +112,6 @@ func findLonely(nums []int) []int { } ``` -### **TypeScript** - - - ```ts function findLonely(nums: number[]): number[] { let hashMap: Map = new Map(); @@ -144,10 +128,6 @@ function findLonely(nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2150.Find All Lonely Numbers in the Array/README_EN.md b/solution/2100-2199/2150.Find All Lonely Numbers in the Array/README_EN.md index 42a25d6c17ea9..6ebf94b47140f 100644 --- a/solution/2100-2199/2150.Find All Lonely Numbers in the Array/README_EN.md +++ b/solution/2100-2199/2150.Find All Lonely Numbers in the Array/README_EN.md @@ -45,9 +45,9 @@ Note that [5, 1] may also be returned. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +95,6 @@ public: }; ``` -### **Go** - ```go func findLonely(nums []int) []int { counter := make(map[int]int) @@ -117,8 +111,6 @@ func findLonely(nums []int) []int { } ``` -### **TypeScript** - ```ts function findLonely(nums: number[]): number[] { let hashMap: Map = new Map(); @@ -135,10 +127,6 @@ function findLonely(nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2151.Maximum Good People Based on Statements/README.md b/solution/2100-2199/2151.Maximum Good People Based on Statements/README.md index 8e79d797c831e..53133175a559a 100644 --- a/solution/2100-2199/2151.Maximum Good People Based on Statements/README.md +++ b/solution/2100-2199/2151.Maximum Good People Based on Statements/README.md @@ -88,9 +88,7 @@ ## 解法 - - -**方法一:二进制枚举** +### 方法一:二进制枚举 二进制枚举好人的状态 $mask$,由于“好人只说真话”,我们借此判断 $statements$ 与 $mask$ 是否存在矛盾,不存在则获取 $mask$ 中好人的数量 $cnt$。迭代获取最大的合法 $cnt$。 @@ -98,10 +96,6 @@ -### **Python3** - - - ```python class Solution: def maximumGood(self, statements: List[List[int]]) -> int: @@ -118,10 +112,6 @@ class Solution: return max(check(mask) for mask in range(1, 1 << len(statements))) ``` -### **Java** - - - ```java class Solution { public int maximumGood(int[][] statements) { @@ -151,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -179,8 +167,6 @@ public: }; ``` -### **Go** - ```go func maximumGood(statements [][]int) int { n := len(statements) @@ -206,8 +192,6 @@ func maximumGood(statements [][]int) int { } ``` -### **TypeScript** - ```ts function maximumGood(statements: number[][]): number { const n = statements.length; @@ -234,10 +218,6 @@ function maximumGood(statements: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2151.Maximum Good People Based on Statements/README_EN.md b/solution/2100-2199/2151.Maximum Good People Based on Statements/README_EN.md index 8791900f9519d..117e693916368 100644 --- a/solution/2100-2199/2151.Maximum Good People Based on Statements/README_EN.md +++ b/solution/2100-2199/2151.Maximum Good People Based on Statements/README_EN.md @@ -86,9 +86,9 @@ Note that there is more than one way to arrive at this conclusion. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -106,8 +106,6 @@ class Solution: return max(check(mask) for mask in range(1, 1 << len(statements))) ``` -### **Java** - ```java class Solution { public int maximumGood(int[][] statements) { @@ -137,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -165,8 +161,6 @@ public: }; ``` -### **Go** - ```go func maximumGood(statements [][]int) int { n := len(statements) @@ -192,8 +186,6 @@ func maximumGood(statements [][]int) int { } ``` -### **TypeScript** - ```ts function maximumGood(statements: number[][]): number { const n = statements.length; @@ -220,10 +212,6 @@ function maximumGood(statements: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2152.Minimum Number of Lines to Cover Points/README.md b/solution/2100-2199/2152.Minimum Number of Lines to Cover Points/README.md index 99fd4f13c53ee..feb920cfc6b66 100644 --- a/solution/2100-2199/2152.Minimum Number of Lines to Cover Points/README.md +++ b/solution/2100-2199/2152.Minimum Number of Lines to Cover Points/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:状态压缩 + 记忆化搜索** +### 方法一:状态压缩 + 记忆化搜索 我们可以用一个整数 `state` 来表示当前已经添加的直线,其中 `state` 的第 $i$ 位表示第 $i$ 条直线是否已经添加。如果 `state` 的第 $i$ 位为 $1$,则表示第 $i$ 条直线已经添加,否则表示第 $i$ 条直线还未添加。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def minimumLines(self, points: List[List[int]]) -> int: @@ -99,10 +93,6 @@ class Solution: return dfs(0) ``` -### **Java** - - - ```java class Solution { private int[] f; @@ -152,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -194,8 +182,6 @@ public: }; ``` -### **Go** - ```go func minimumLines(points [][]int) int { check := func(i, j, k int) bool { @@ -238,16 +224,6 @@ func minimumLines(points [][]int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2152.Minimum Number of Lines to Cover Points/README_EN.md b/solution/2100-2199/2152.Minimum Number of Lines to Cover Points/README_EN.md index 49482b3a41a89..f34e8eb7757a5 100644 --- a/solution/2100-2199/2152.Minimum Number of Lines to Cover Points/README_EN.md +++ b/solution/2100-2199/2152.Minimum Number of Lines to Cover Points/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return dfs(0) ``` -### **Java** - ```java class Solution { private int[] f; @@ -127,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +165,6 @@ public: }; ``` -### **Go** - ```go func minimumLines(points [][]int) int { check := func(i, j, k int) bool { @@ -213,16 +207,6 @@ func minimumLines(points [][]int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2153.The Number of Passengers in Each Bus II/README.md b/solution/2100-2199/2153.The Number of Passengers in Each Bus II/README.md index 4bbca10502613..46c9a10f5c77e 100644 --- a/solution/2100-2199/2153.The Number of Passengers in Each Bus II/README.md +++ b/solution/2100-2199/2153.The Number of Passengers in Each Bus II/README.md @@ -92,14 +92,10 @@ Passengers 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -124,3 +120,5 @@ ORDER BY bus_id; ``` + + diff --git a/solution/2100-2199/2153.The Number of Passengers in Each Bus II/README_EN.md b/solution/2100-2199/2153.The Number of Passengers in Each Bus II/README_EN.md index 08ed5c9873bbd..7e1c6891a3475 100644 --- a/solution/2100-2199/2153.The Number of Passengers in Each Bus II/README_EN.md +++ b/solution/2100-2199/2153.The Number of Passengers in Each Bus II/README_EN.md @@ -90,9 +90,9 @@ Passengers table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -118,3 +118,5 @@ ORDER BY bus_id; ``` + + diff --git a/solution/2100-2199/2154.Keep Multiplying Found Values by Two/README.md b/solution/2100-2199/2154.Keep Multiplying Found Values by Two/README.md index 166a5c21a41ff..5c8a41ee9e4c7 100644 --- a/solution/2100-2199/2154.Keep Multiplying Found Values by Two/README.md +++ b/solution/2100-2199/2154.Keep Multiplying Found Values by Two/README.md @@ -52,14 +52,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findFinalValue(self, nums: List[int], original: int) -> int: @@ -69,10 +65,6 @@ class Solution: return original ``` -### **Java** - - - ```java class Solution { @@ -89,20 +81,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function findFinalValue(nums: number[], original: number): number { - let set: Set = new Set(nums); - while (set.has(original)) { - original *= 2; - } - return original; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -115,8 +93,6 @@ public: }; ``` -### **Go** - ```go func findFinalValue(nums []int, original int) int { s := make(map[int]bool) @@ -130,10 +106,16 @@ func findFinalValue(nums []int, original int) int { } ``` -### **...** - -``` - +```ts +function findFinalValue(nums: number[], original: number): number { + let set: Set = new Set(nums); + while (set.has(original)) { + original *= 2; + } + return original; +} ``` + + diff --git a/solution/2100-2199/2154.Keep Multiplying Found Values by Two/README_EN.md b/solution/2100-2199/2154.Keep Multiplying Found Values by Two/README_EN.md index 7c22a025dcb99..bbe52c3831eb6 100644 --- a/solution/2100-2199/2154.Keep Multiplying Found Values by Two/README_EN.md +++ b/solution/2100-2199/2154.Keep Multiplying Found Values by Two/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,10 +61,9 @@ class Solution: return original ``` -### **Java** - ```java class Solution { + public int findFinalValue(int[] nums, int original) { Set s = new HashSet<>(); for (int num : nums) { @@ -78,20 +77,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function findFinalValue(nums: number[], original: number): number { - let set: Set = new Set(nums); - while (set.has(original)) { - original *= 2; - } - return original; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -104,8 +89,6 @@ public: }; ``` -### **Go** - ```go func findFinalValue(nums []int, original int) int { s := make(map[int]bool) @@ -119,10 +102,16 @@ func findFinalValue(nums []int, original int) int { } ``` -### **...** - -``` - +```ts +function findFinalValue(nums: number[], original: number): number { + let set: Set = new Set(nums); + while (set.has(original)) { + original *= 2; + } + return original; +} ``` + + diff --git a/solution/2100-2199/2155.All Divisions With the Highest Score of a Binary Array/README.md b/solution/2100-2199/2155.All Divisions With the Highest Score of a Binary Array/README.md index 3e73b78961553..aeec6ca1dccf6 100644 --- a/solution/2100-2199/2155.All Divisions With the Highest Score of a Binary Array/README.md +++ b/solution/2100-2199/2155.All Divisions With the Highest Score of a Binary Array/README.md @@ -68,14 +68,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxScoreIndices(self, nums: List[int]) -> List[int]: @@ -96,10 +92,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { @@ -136,36 +128,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function maxScoreIndices(nums: number[]): number[] { - const n = nums.length; - const total = nums.reduce((a, c) => a + c, 0); - let left = 0, - right = total; - let record: Array = [total]; - for (const num of nums) { - if (num == 0) { - left++; - } else { - right--; - } - record.push(left + right); - } - const max = Math.max(...record); - let ans: Array = []; - for (let i = 0; i <= n; i++) { - if (record[i] == max) { - ans.push(i); - } - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -193,8 +155,6 @@ public: }; ``` -### **Go** - ```go func maxScoreIndices(nums []int) []int { left, right := 0, 0 @@ -221,10 +181,32 @@ func maxScoreIndices(nums []int) []int { } ``` -### **...** - -``` - +```ts +function maxScoreIndices(nums: number[]): number[] { + const n = nums.length; + const total = nums.reduce((a, c) => a + c, 0); + let left = 0, + right = total; + let record: Array = [total]; + for (const num of nums) { + if (num == 0) { + left++; + } else { + right--; + } + record.push(left + right); + } + const max = Math.max(...record); + let ans: Array = []; + for (let i = 0; i <= n; i++) { + if (record[i] == max) { + ans.push(i); + } + } + return ans; +} ``` + + diff --git a/solution/2100-2199/2155.All Divisions With the Highest Score of a Binary Array/README_EN.md b/solution/2100-2199/2155.All Divisions With the Highest Score of a Binary Array/README_EN.md index f8032c5b23f8c..b3118201e4a38 100644 --- a/solution/2100-2199/2155.All Divisions With the Highest Score of a Binary Array/README_EN.md +++ b/solution/2100-2199/2155.All Divisions With the Highest Score of a Binary Array/README_EN.md @@ -67,9 +67,9 @@ Only index 0 has the highest possible division score 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -91,8 +91,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { @@ -129,36 +127,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function maxScoreIndices(nums: number[]): number[] { - const n = nums.length; - const total = nums.reduce((a, c) => a + c, 0); - let left = 0, - right = total; - let record: Array = [total]; - for (const num of nums) { - if (num == 0) { - left++; - } else { - right--; - } - record.push(left + right); - } - const max = Math.max(...record); - let ans: Array = []; - for (let i = 0; i <= n; i++) { - if (record[i] == max) { - ans.push(i); - } - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -186,8 +154,6 @@ public: }; ``` -### **Go** - ```go func maxScoreIndices(nums []int) []int { left, right := 0, 0 @@ -214,10 +180,32 @@ func maxScoreIndices(nums []int) []int { } ``` -### **...** - -``` - +```ts +function maxScoreIndices(nums: number[]): number[] { + const n = nums.length; + const total = nums.reduce((a, c) => a + c, 0); + let left = 0, + right = total; + let record: Array = [total]; + for (const num of nums) { + if (num == 0) { + left++; + } else { + right--; + } + record.push(left + right); + } + const max = Math.max(...record); + let ans: Array = []; + for (let i = 0; i <= n; i++) { + if (record[i] == max) { + ans.push(i); + } + } + return ans; +} ``` + + diff --git a/solution/2100-2199/2156.Find Substring With Given Hash Value/README.md b/solution/2100-2199/2156.Find Substring With Given Hash Value/README.md index 6ea5a19087d04..0b5feec495967 100644 --- a/solution/2100-2199/2156.Find Substring With Given Hash Value/README.md +++ b/solution/2100-2199/2156.Find Substring With Given Hash Value/README.md @@ -54,28 +54,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **JavaScript** - ```js /** * @param {string} s @@ -116,10 +98,6 @@ function getCode(str, index) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2156.Find Substring With Given Hash Value/README_EN.md b/solution/2100-2199/2156.Find Substring With Given Hash Value/README_EN.md index d05e6de76b384..09918578d7286 100644 --- a/solution/2100-2199/2156.Find Substring With Given Hash Value/README_EN.md +++ b/solution/2100-2199/2156.Find Substring With Given Hash Value/README_EN.md @@ -52,21 +52,9 @@ Note that "bxz" also has a hash of 32 but it appears later than " ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` +### Solution 1 -### **JavaScript** + ```js /** @@ -108,10 +96,6 @@ function getCode(str, index) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2157.Groups of Strings/README.md b/solution/2100-2199/2157.Groups of Strings/README.md index 4c30d9682da68..258205c7c1d19 100644 --- a/solution/2100-2199/2157.Groups of Strings/README.md +++ b/solution/2100-2199/2157.Groups of Strings/README.md @@ -68,16 +68,10 @@ ## 解法 - - -**方法一:状态压缩(位运算) + 并查集** +### 方法一:状态压缩(位运算) + 并查集 -### **Python3** - - - ```python class Solution: def groupStrings(self, words: List[str]) -> List[int]: @@ -121,10 +115,6 @@ class Solution: return [n, mx] ``` -### **Java** - - - ```java class Solution { private Map p; @@ -187,8 +177,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -237,8 +225,6 @@ public: }; ``` -### **Go** - ```go func groupStrings(words []string) []int { p := map[int]int{} @@ -293,16 +279,6 @@ func groupStrings(words []string) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2157.Groups of Strings/README_EN.md b/solution/2100-2199/2157.Groups of Strings/README_EN.md index d9c4f76fa3f7e..d3175e6710e6f 100644 --- a/solution/2100-2199/2157.Groups of Strings/README_EN.md +++ b/solution/2100-2199/2157.Groups of Strings/README_EN.md @@ -69,9 +69,9 @@ Thus, the size of the largest group is 3. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -116,8 +116,6 @@ class Solution: return [n, mx] ``` -### **Java** - ```java class Solution { private Map p; @@ -180,8 +178,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -230,8 +226,6 @@ public: }; ``` -### **Go** - ```go func groupStrings(words []string) []int { p := map[int]int{} @@ -286,16 +280,6 @@ func groupStrings(words []string) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2158.Amount of New Area Painted Each Day/README.md b/solution/2100-2199/2158.Amount of New Area Painted Each Day/README.md index 29b69f96c4969..39ecbe40dcea5 100644 --- a/solution/2100-2199/2158.Amount of New Area Painted Each Day/README.md +++ b/solution/2100-2199/2158.Amount of New Area Painted Each Day/README.md @@ -68,9 +68,7 @@ ## 解法 - - -**方法一:线段树** +### 方法一:线段树 线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。区间修改时,需要使用**懒标记**保证效率。 @@ -86,10 +84,6 @@ -### **Python3** - - - ```python class Node: def __init__(self, l, r): @@ -166,10 +160,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Node { Node left; @@ -277,8 +267,6 @@ class Solution { } ``` -### **C++** - ```cpp class Node { public: @@ -376,16 +364,6 @@ public: }; ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2158.Amount of New Area Painted Each Day/README_EN.md b/solution/2100-2199/2158.Amount of New Area Painted Each Day/README_EN.md index 17a92feda030c..42ade46431e3f 100644 --- a/solution/2100-2199/2158.Amount of New Area Painted Each Day/README_EN.md +++ b/solution/2100-2199/2158.Amount of New Area Painted Each Day/README_EN.md @@ -64,12 +64,10 @@ The amount of new area painted on day 1 is 0. ## Solutions -Segment Tree. +### Solution 1 -### **Python3** - ```python class Node: def __init__(self, l, r): @@ -146,8 +144,6 @@ class Solution: return ans ``` -### **Java** - ```java class Node { Node left; @@ -255,8 +251,6 @@ class Solution { } ``` -### **C++** - ```cpp class Node { public: @@ -354,16 +348,6 @@ public: }; ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2159.Order Two Columns Independently/README.md b/solution/2100-2199/2159.Order Two Columns Independently/README.md index 99f35177d7fb8..fc32e308850e1 100644 --- a/solution/2100-2199/2159.Order Two Columns Independently/README.md +++ b/solution/2100-2199/2159.Order Two Columns Independently/README.md @@ -57,14 +57,10 @@ Data 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -87,3 +83,5 @@ FROM ``` + + diff --git a/solution/2100-2199/2159.Order Two Columns Independently/README_EN.md b/solution/2100-2199/2159.Order Two Columns Independently/README_EN.md index ab2c307282e91..cd0762844c188 100644 --- a/solution/2100-2199/2159.Order Two Columns Independently/README_EN.md +++ b/solution/2100-2199/2159.Order Two Columns Independently/README_EN.md @@ -54,9 +54,9 @@ Data table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -80,3 +80,5 @@ FROM ``` + + diff --git a/solution/2100-2199/2160.Minimum Sum of Four Digit Number After Splitting Digits/README.md b/solution/2100-2199/2160.Minimum Sum of Four Digit Number After Splitting Digits/README.md index 13a25760cd067..61d8175ae1bbc 100644 --- a/solution/2100-2199/2160.Minimum Sum of Four Digit Number After Splitting Digits/README.md +++ b/solution/2100-2199/2160.Minimum Sum of Four Digit Number After Splitting Digits/README.md @@ -42,14 +42,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minimumSum(self, num: int) -> int: @@ -61,10 +57,6 @@ class Solution: return 10 * (nums[0] + nums[1]) + nums[2] + nums[3] ``` -### **Java** - - - ```java class Solution { public int minimumSum(int num) { @@ -79,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +86,6 @@ public: }; ``` -### **Go** - ```go func minimumSum(num int) int { var nums []int @@ -110,8 +98,6 @@ func minimumSum(num int) int { } ``` -### **TypeScript** - ```ts function minimumSum(num: number): number { const nums = new Array(4).fill(0); @@ -124,8 +110,6 @@ function minimumSum(num: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn minimum_sum(mut num: i32) -> i32 { @@ -140,8 +124,6 @@ impl Solution { } ``` -### **C** - ```c int cmp(const void* a, const void* b) { return *(int*) a - *(int*) b; @@ -158,10 +140,6 @@ int minimumSum(int num) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2160.Minimum Sum of Four Digit Number After Splitting Digits/README_EN.md b/solution/2100-2199/2160.Minimum Sum of Four Digit Number After Splitting Digits/README_EN.md index 79a45f407f87a..dbe7b6206cde3 100644 --- a/solution/2100-2199/2160.Minimum Sum of Four Digit Number After Splitting Digits/README_EN.md +++ b/solution/2100-2199/2160.Minimum Sum of Four Digit Number After Splitting Digits/README_EN.md @@ -40,9 +40,9 @@ The minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return 10 * (nums[0] + nums[1]) + nums[2] + nums[3] ``` -### **Java** - ```java class Solution { public int minimumSum(int num) { @@ -71,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -88,8 +84,6 @@ public: }; ``` -### **Go** - ```go func minimumSum(num int) int { var nums []int @@ -102,8 +96,6 @@ func minimumSum(num int) int { } ``` -### **TypeScript** - ```ts function minimumSum(num: number): number { const nums = new Array(4).fill(0); @@ -116,8 +108,6 @@ function minimumSum(num: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn minimum_sum(mut num: i32) -> i32 { @@ -132,8 +122,6 @@ impl Solution { } ``` -### **C** - ```c int cmp(const void* a, const void* b) { return *(int*) a - *(int*) b; @@ -150,10 +138,6 @@ int minimumSum(int num) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2161.Partition Array According to Given Pivot/README.md b/solution/2100-2199/2161.Partition Array According to Given Pivot/README.md index c784fb60967b8..cd9acc504daf0 100644 --- a/solution/2100-2199/2161.Partition Array According to Given Pivot/README.md +++ b/solution/2100-2199/2161.Partition Array According to Given Pivot/README.md @@ -54,14 +54,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def pivotArray(self, nums: List[int], pivot: int) -> List[int]: @@ -76,10 +72,6 @@ class Solution: return a + b + c ``` -### **Java** - - - ```java class Solution { public int[] pivotArray(int[] nums, int pivot) { @@ -106,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +114,6 @@ public: }; ``` -### **Go** - ```go func pivotArray(nums []int, pivot int) []int { var ans []int @@ -148,16 +136,6 @@ func pivotArray(nums []int, pivot int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2161.Partition Array According to Given Pivot/README_EN.md b/solution/2100-2199/2161.Partition Array According to Given Pivot/README_EN.md index e996c014a781b..ec721cec643ae 100644 --- a/solution/2100-2199/2161.Partition Array According to Given Pivot/README_EN.md +++ b/solution/2100-2199/2161.Partition Array According to Given Pivot/README_EN.md @@ -52,9 +52,9 @@ The relative ordering of the elements less than and greater than pivot is also m ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return a + b + c ``` -### **Java** - ```java class Solution { public int[] pivotArray(int[] nums, int pivot) { @@ -98,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +112,6 @@ public: }; ``` -### **Go** - ```go func pivotArray(nums []int, pivot int) []int { var ans []int @@ -140,16 +134,6 @@ func pivotArray(nums []int, pivot int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2162.Minimum Cost to Set Cooking Time/README.md b/solution/2100-2199/2162.Minimum Cost to Set Cooking Time/README.md index 687ec967498c0..a4ed7550e6641 100644 --- a/solution/2100-2199/2162.Minimum Cost to Set Cooking Time/README.md +++ b/solution/2100-2199/2162.Minimum Cost to Set Cooking Time/README.md @@ -73,14 +73,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minCostSetTime( @@ -107,10 +103,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds) { @@ -141,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +158,6 @@ public: }; ``` -### **Go** - ```go func minCostSetTime(startAt int, moveCost int, pushCost int, targetSeconds int) int { m, s := targetSeconds/60, targetSeconds%60 @@ -196,16 +184,6 @@ func minCostSetTime(startAt int, moveCost int, pushCost int, targetSeconds int) } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2162.Minimum Cost to Set Cooking Time/README_EN.md b/solution/2100-2199/2162.Minimum Cost to Set Cooking Time/README_EN.md index d67a2b27fa342..3364890dee477 100644 --- a/solution/2100-2199/2162.Minimum Cost to Set Cooking Time/README_EN.md +++ b/solution/2100-2199/2162.Minimum Cost to Set Cooking Time/README_EN.md @@ -67,9 +67,9 @@ Note other possible ways are 0076, 076, 0116, and 116, but none of them produces ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -97,8 +97,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds) { @@ -129,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +152,6 @@ public: }; ``` -### **Go** - ```go func minCostSetTime(startAt int, moveCost int, pushCost int, targetSeconds int) int { m, s := targetSeconds/60, targetSeconds%60 @@ -184,16 +178,6 @@ func minCostSetTime(startAt int, moveCost int, pushCost int, targetSeconds int) } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/README.md b/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/README.md index f29a5a5a1de12..aca37b00e8442 100644 --- a/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/README.md +++ b/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:优先队列(大小根堆)+ 前后缀和 + 枚举分割点** +### 方法一:优先队列(大小根堆)+ 前后缀和 + 枚举分割点 题目实际上等价于在 $nums$ 中找到一个分割点,将数组分成左右两部分,在前一部分中选取最小的 $n$ 个元素,在后一部分中选取最大的 $n$ 个元素,使得两部分和的差值最小。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def minimumDifference(self, nums: List[int]) -> int: @@ -108,10 +102,6 @@ class Solution: return min(pre[i] - suf[i + 1] for i in range(n, n * 2 + 1)) ``` -### **Java** - - - ```java class Solution { public long minimumDifference(int[] nums) { @@ -150,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -195,8 +183,6 @@ public: }; ``` -### **Go** - ```go func minimumDifference(nums []int) int64 { m := len(nums) @@ -244,8 +230,6 @@ func (h *hp) Pop() any { } ``` -### **TypeScript** - ```ts function minimumDifference(nums: number[]): number { const m = nums.length; @@ -282,10 +266,6 @@ function minimumDifference(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/README_EN.md b/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/README_EN.md index b06ae00630045..9ed0476dafc0d 100644 --- a/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/README_EN.md +++ b/solution/2100-2199/2163.Minimum Difference in Sums After Removal of Elements/README_EN.md @@ -58,9 +58,9 @@ It can be shown that it is not possible to obtain a difference smaller than 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -92,8 +92,6 @@ class Solution: return min(pre[i] - suf[i + 1] for i in range(n, n * 2 + 1)) ``` -### **Java** - ```java class Solution { public long minimumDifference(int[] nums) { @@ -132,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -177,8 +173,6 @@ public: }; ``` -### **Go** - ```go func minimumDifference(nums []int) int64 { m := len(nums) @@ -226,8 +220,6 @@ func (h *hp) Pop() any { } ``` -### **TypeScript** - ```ts function minimumDifference(nums: number[]): number { const m = nums.length; @@ -264,10 +256,6 @@ function minimumDifference(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2164.Sort Even and Odd Indices Independently/README.md b/solution/2100-2199/2164.Sort Even and Odd Indices Independently/README.md index 24797a536e0cc..ddea2621ad964 100644 --- a/solution/2100-2199/2164.Sort Even and Odd Indices Independently/README.md +++ b/solution/2100-2199/2164.Sort Even and Odd Indices Independently/README.md @@ -59,14 +59,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def sortEvenOdd(self, nums: List[int]) -> List[int]: @@ -77,10 +73,6 @@ class Solution: return nums ``` -### **Java** - - - ```java class Solution { public int[] sortEvenOdd(int[] nums) { @@ -108,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +123,6 @@ public: }; ``` -### **Go** - ```go func sortEvenOdd(nums []int) []int { n := len(nums) @@ -162,16 +150,6 @@ func sortEvenOdd(nums []int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2164.Sort Even and Odd Indices Independently/README_EN.md b/solution/2100-2199/2164.Sort Even and Odd Indices Independently/README_EN.md index 41939a6e792db..853e5cc72fde4 100644 --- a/solution/2100-2199/2164.Sort Even and Odd Indices Independently/README_EN.md +++ b/solution/2100-2199/2164.Sort Even and Odd Indices Independently/README_EN.md @@ -55,9 +55,9 @@ The resultant array formed is [2,1], which is the same as the initial array. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return nums ``` -### **Java** - ```java class Solution { public int[] sortEvenOdd(int[] nums) { @@ -98,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func sortEvenOdd(nums []int) []int { n := len(nums) @@ -152,16 +146,6 @@ func sortEvenOdd(nums []int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2165.Smallest Value of the Rearranged Number/README.md b/solution/2100-2199/2165.Smallest Value of the Rearranged Number/README.md index dd3fd4db20221..4c39d3855bd5d 100644 --- a/solution/2100-2199/2165.Smallest Value of the Rearranged Number/README.md +++ b/solution/2100-2199/2165.Smallest Value of the Rearranged Number/README.md @@ -39,14 +39,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def smallestNumber(self, num: int) -> int: @@ -76,10 +72,6 @@ class Solution: return int(ans) ``` -### **Java** - - - ```java class Solution { public long smallestNumber(long num) { @@ -121,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +147,6 @@ public: }; ``` -### **Go** - ```go func smallestNumber(num int64) int64 { if num == 0 { @@ -200,16 +188,6 @@ func smallestNumber(num int64) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2165.Smallest Value of the Rearranged Number/README_EN.md b/solution/2100-2199/2165.Smallest Value of the Rearranged Number/README_EN.md index d8c44f45996fe..5c8076c71fdf8 100644 --- a/solution/2100-2199/2165.Smallest Value of the Rearranged Number/README_EN.md +++ b/solution/2100-2199/2165.Smallest Value of the Rearranged Number/README_EN.md @@ -38,9 +38,9 @@ The arrangement with the smallest value that does not contain any leading zeros ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return int(ans) ``` -### **Java** - ```java class Solution { public long smallestNumber(long num) { @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +146,6 @@ public: }; ``` -### **Go** - ```go func smallestNumber(num int64) int64 { if num == 0 { @@ -193,16 +187,6 @@ func smallestNumber(num int64) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2166.Design Bitset/README.md b/solution/2100-2199/2166.Design Bitset/README.md index d654f5831ae85..ba30bd82bba61 100644 --- a/solution/2100-2199/2166.Design Bitset/README.md +++ b/solution/2100-2199/2166.Design Bitset/README.md @@ -60,14 +60,10 @@ bs.toString(); // 返回 "01010" ,即 bitset 的当前组成情况。 ## 解法 - +### 方法一 -### **Python3** - - - ```python class Bitset: def __init__(self, size: int): @@ -115,10 +111,6 @@ class Bitset: # param_7 = obj.toString() ``` -### **Java** - - - ```java class Bitset { private char[] a; @@ -185,8 +177,6 @@ class Bitset { */ ``` -### **C++** - ```cpp class Bitset { public: @@ -243,8 +233,6 @@ public: */ ``` -### **Go** - ```go type Bitset struct { a []byte @@ -308,16 +296,6 @@ func (this *Bitset) ToString() string { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2166.Design Bitset/README_EN.md b/solution/2100-2199/2166.Design Bitset/README_EN.md index 21b219e65c702..97eb4fa7a79a5 100644 --- a/solution/2100-2199/2166.Design Bitset/README_EN.md +++ b/solution/2100-2199/2166.Design Bitset/README_EN.md @@ -56,9 +56,9 @@ bs.toString(); // return "01010", which is the composition of bitset. ## Solutions - +### Solution 1 -### **Python3** + ```python class Bitset: @@ -107,8 +107,6 @@ class Bitset: # param_7 = obj.toString() ``` -### **Java** - ```java class Bitset { private char[] a; @@ -175,8 +173,6 @@ class Bitset { */ ``` -### **C++** - ```cpp class Bitset { public: @@ -233,8 +229,6 @@ public: */ ``` -### **Go** - ```go type Bitset struct { a []byte @@ -298,16 +292,6 @@ func (this *Bitset) ToString() string { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2167.Minimum Time to Remove All Cars Containing Illegal Goods/README.md b/solution/2100-2199/2167.Minimum Time to Remove All Cars Containing Illegal Goods/README.md index d9ddee4163ea6..1af42e4a3bba6 100644 --- a/solution/2100-2199/2167.Minimum Time to Remove All Cars Containing Illegal Goods/README.md +++ b/solution/2100-2199/2167.Minimum Time to Remove All Cars Containing Illegal Goods/README.md @@ -74,14 +74,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minimumTime(self, s: str) -> int: @@ -95,10 +91,6 @@ class Solution: return min(a + b for a, b in zip(pre[1:], suf[1:])) ``` -### **Java** - - - ```java class Solution { public int minimumTime(String s) { @@ -120,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +128,6 @@ public: }; ``` -### **Go** - ```go func minimumTime(s string) int { n := len(s) @@ -165,16 +153,6 @@ func minimumTime(s string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2167.Minimum Time to Remove All Cars Containing Illegal Goods/README_EN.md b/solution/2100-2199/2167.Minimum Time to Remove All Cars Containing Illegal Goods/README_EN.md index ffabfc83e2c33..529df71414ae0 100644 --- a/solution/2100-2199/2167.Minimum Time to Remove All Cars Containing Illegal Goods/README_EN.md +++ b/solution/2100-2199/2167.Minimum Time to Remove All Cars Containing Illegal Goods/README_EN.md @@ -71,9 +71,9 @@ There are no other ways to remove them with less time. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -88,8 +88,6 @@ class Solution: return min(a + b for a, b in zip(pre[1:], suf[1:])) ``` -### **Java** - ```java class Solution { public int minimumTime(String s) { @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +125,6 @@ public: }; ``` -### **Go** - ```go func minimumTime(s string) int { n := len(s) @@ -156,16 +150,6 @@ func minimumTime(s string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2168.Unique Substrings With Equal Digit Frequency/README.md b/solution/2100-2199/2168.Unique Substrings With Equal Digit Frequency/README.md index cc6db4b94d6dd..8c1f9a75b85ee 100644 --- a/solution/2100-2199/2168.Unique Substrings With Equal Digit Frequency/README.md +++ b/solution/2100-2199/2168.Unique Substrings With Equal Digit Frequency/README.md @@ -38,14 +38,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def equalDigitFrequency(self, s: str) -> int: @@ -69,10 +65,6 @@ class Solution: return len(vis) ``` -### **Java** - - - ```java class Solution { public int equalDigitFrequency(String s) { @@ -111,8 +103,6 @@ class Solution { } ``` -### **Go** - ```go func equalDigitFrequency(s string) int { n := len(s) @@ -151,16 +141,6 @@ func equalDigitFrequency(s string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2168.Unique Substrings With Equal Digit Frequency/README_EN.md b/solution/2100-2199/2168.Unique Substrings With Equal Digit Frequency/README_EN.md index 477cd179f5364..42f28ec301c88 100644 --- a/solution/2100-2199/2168.Unique Substrings With Equal Digit Frequency/README_EN.md +++ b/solution/2100-2199/2168.Unique Substrings With Equal Digit Frequency/README_EN.md @@ -34,9 +34,9 @@ Note that although the substring "12" appears twice, it is only counte ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return len(vis) ``` -### **Java** - ```java class Solution { public int equalDigitFrequency(String s) { @@ -101,8 +99,6 @@ class Solution { } ``` -### **Go** - ```go func equalDigitFrequency(s string) int { n := len(s) @@ -141,16 +137,6 @@ func equalDigitFrequency(s string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2169.Count Operations to Obtain Zero/README.md b/solution/2100-2199/2169.Count Operations to Obtain Zero/README.md index 4b6939e7f6a77..4addf360bfcc4 100644 --- a/solution/2100-2199/2169.Count Operations to Obtain Zero/README.md +++ b/solution/2100-2199/2169.Count Operations to Obtain Zero/README.md @@ -52,16 +52,10 @@ ## 解法 - - -模拟相减。 +### 方法一 -### **Python3** - - - ```python class Solution: def countOperations(self, num1: int, num2: int) -> int: @@ -74,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countOperations(int num1, int num2) { @@ -95,21 +85,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function countOperations(num1: number, num2: number): number { - let ans = 0; - while (num1 && num2) { - [num1, num2] = [Math.min(num1, num2), Math.abs(num1 - num2)]; - ans++; - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -125,8 +100,6 @@ public: }; ``` -### **Go** - ```go func countOperations(num1 int, num2 int) int { ans := 0 @@ -141,10 +114,17 @@ func countOperations(num1 int, num2 int) int { } ``` -### **...** - -``` - +```ts +function countOperations(num1: number, num2: number): number { + let ans = 0; + while (num1 && num2) { + [num1, num2] = [Math.min(num1, num2), Math.abs(num1 - num2)]; + ans++; + } + return ans; +} ``` + + diff --git a/solution/2100-2199/2169.Count Operations to Obtain Zero/README_EN.md b/solution/2100-2199/2169.Count Operations to Obtain Zero/README_EN.md index fd0a836943115..fd1c09d9a5bfc 100644 --- a/solution/2100-2199/2169.Count Operations to Obtain Zero/README_EN.md +++ b/solution/2100-2199/2169.Count Operations to Obtain Zero/README_EN.md @@ -48,9 +48,9 @@ So the total number of operations required is 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countOperations(int num1, int num2) { @@ -83,21 +81,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function countOperations(num1: number, num2: number): number { - let ans = 0; - while (num1 && num2) { - [num1, num2] = [Math.min(num1, num2), Math.abs(num1 - num2)]; - ans++; - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -113,8 +96,6 @@ public: }; ``` -### **Go** - ```go func countOperations(num1 int, num2 int) int { ans := 0 @@ -129,10 +110,17 @@ func countOperations(num1 int, num2 int) int { } ``` -### **...** - -``` - +```ts +function countOperations(num1: number, num2: number): number { + let ans = 0; + while (num1 && num2) { + [num1, num2] = [Math.min(num1, num2), Math.abs(num1 - num2)]; + ans++; + } + return ans; +} ``` + + diff --git a/solution/2100-2199/2170.Minimum Operations to Make the Array Alternating/README.md b/solution/2100-2199/2170.Minimum Operations to Make the Array Alternating/README.md index 9e4c68eb827ea..6ea01aa113884 100644 --- a/solution/2100-2199/2170.Minimum Operations to Make the Array Alternating/README.md +++ b/solution/2100-2199/2170.Minimum Operations to Make the Array Alternating/README.md @@ -53,14 +53,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minimumOperations(self, nums: List[int]) -> int: @@ -76,10 +72,6 @@ class Solution: return min(n - (n1 + n2) for a, n1 in get(0) for b, n2 in get(1) if a != b) ``` -### **Java** - - - ```java class Solution { private int[] nums; @@ -126,39 +118,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minimumOperations(nums: number[]): number { - const n = nums.length, - m = 10 ** 5; - let odd = new Array(m).fill(0); - let even = new Array(m).fill(0); - for (let i = 0; i < n; i++) { - let cur = nums[i]; - if (i & 1) { - odd[cur] = (odd[cur] || 0) + 1; - } else { - even[cur] = (even[cur] || 0) + 1; - } - } - let i1 = odd.indexOf(Math.max(...odd)); - let i2 = even.indexOf(Math.max(...even)); - if (i1 != i2) { - return n - odd[i1] - even[i2]; - } else { - let l1 = odd[i1], - l2 = even[i2]; - (odd[i1] = 0), (even[i2] = 0); - let j1 = odd.indexOf(Math.max(...odd)); - let j2 = even.indexOf(Math.max(...even)); - return n - Math.max(l1 + even[j2], l2 + odd[j1]); - } -} -``` - -### **C++** - ```cpp typedef pair PII; @@ -194,8 +153,6 @@ public: }; ``` -### **Go** - ```go func minimumOperations(nums []int) int { n := len(nums) @@ -226,10 +183,35 @@ func minimumOperations(nums []int) int { } ``` -### **...** - -``` - +```ts +function minimumOperations(nums: number[]): number { + const n = nums.length, + m = 10 ** 5; + let odd = new Array(m).fill(0); + let even = new Array(m).fill(0); + for (let i = 0; i < n; i++) { + let cur = nums[i]; + if (i & 1) { + odd[cur] = (odd[cur] || 0) + 1; + } else { + even[cur] = (even[cur] || 0) + 1; + } + } + let i1 = odd.indexOf(Math.max(...odd)); + let i2 = even.indexOf(Math.max(...even)); + if (i1 != i2) { + return n - odd[i1] - even[i2]; + } else { + let l1 = odd[i1], + l2 = even[i2]; + (odd[i1] = 0), (even[i2] = 0); + let j1 = odd.indexOf(Math.max(...odd)); + let j2 = even.indexOf(Math.max(...even)); + return n - Math.max(l1 + even[j2], l2 + odd[j1]); + } +} ``` + + diff --git a/solution/2100-2199/2170.Minimum Operations to Make the Array Alternating/README_EN.md b/solution/2100-2199/2170.Minimum Operations to Make the Array Alternating/README_EN.md index 7ad2b1c0dc37e..11f68c5c5cd71 100644 --- a/solution/2100-2199/2170.Minimum Operations to Make the Array Alternating/README_EN.md +++ b/solution/2100-2199/2170.Minimum Operations to Make the Array Alternating/README_EN.md @@ -50,9 +50,9 @@ Note that the array cannot be converted to [2,2,2,2,2] b ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return min(n - (n1 + n2) for a, n1 in get(0) for b, n2 in get(1) if a != b) ``` -### **Java** - ```java class Solution { private int[] nums; @@ -117,39 +115,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minimumOperations(nums: number[]): number { - const n = nums.length, - m = 10 ** 5; - let odd = new Array(m).fill(0); - let even = new Array(m).fill(0); - for (let i = 0; i < n; i++) { - let cur = nums[i]; - if (i & 1) { - odd[cur] = (odd[cur] || 0) + 1; - } else { - even[cur] = (even[cur] || 0) + 1; - } - } - let i1 = odd.indexOf(Math.max(...odd)); - let i2 = even.indexOf(Math.max(...even)); - if (i1 != i2) { - return n - odd[i1] - even[i2]; - } else { - let l1 = odd[i1], - l2 = even[i2]; - (odd[i1] = 0), (even[i2] = 0); - let j1 = odd.indexOf(Math.max(...odd)); - let j2 = even.indexOf(Math.max(...even)); - return n - Math.max(l1 + even[j2], l2 + odd[j1]); - } -} -``` - -### **C++** - ```cpp typedef pair PII; @@ -185,8 +150,6 @@ public: }; ``` -### **Go** - ```go func minimumOperations(nums []int) int { n := len(nums) @@ -217,10 +180,35 @@ func minimumOperations(nums []int) int { } ``` -### **...** - -``` - +```ts +function minimumOperations(nums: number[]): number { + const n = nums.length, + m = 10 ** 5; + let odd = new Array(m).fill(0); + let even = new Array(m).fill(0); + for (let i = 0; i < n; i++) { + let cur = nums[i]; + if (i & 1) { + odd[cur] = (odd[cur] || 0) + 1; + } else { + even[cur] = (even[cur] || 0) + 1; + } + } + let i1 = odd.indexOf(Math.max(...odd)); + let i2 = even.indexOf(Math.max(...even)); + if (i1 != i2) { + return n - odd[i1] - even[i2]; + } else { + let l1 = odd[i1], + l2 = even[i2]; + (odd[i1] = 0), (even[i2] = 0); + let j1 = odd.indexOf(Math.max(...odd)); + let j2 = even.indexOf(Math.max(...even)); + return n - Math.max(l1 + even[j2], l2 + odd[j1]); + } +} ``` + + diff --git a/solution/2100-2199/2171.Removing Minimum Number of Magic Beans/README.md b/solution/2100-2199/2171.Removing Minimum Number of Magic Beans/README.md index ce9037fe97a88..97d5fa881b4cf 100644 --- a/solution/2100-2199/2171.Removing Minimum Number of Magic Beans/README.md +++ b/solution/2100-2199/2171.Removing Minimum Number of Magic Beans/README.md @@ -57,16 +57,10 @@ ## 解法 - - -**方法一:排序求和** +### 方法一:排序求和 -### **Python3** - - - ```python class Solution: def minimumRemoval(self, beans: List[int]) -> int: @@ -78,10 +72,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long minimumRemoval(int[] beans) { @@ -100,24 +90,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minimumRemoval(beans: number[]): number { - const n = beans.length; - let sum = beans.reduce((a, c) => a + c, 0); - beans.sort((a, b) => a - b); - let ans = sum; - for (let i = 0; i < n; i++) { - let num = beans[i]; - ans = Math.min(sum - num * (n - i), ans); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -132,8 +104,6 @@ public: }; ``` -### **Go** - ```go func minimumRemoval(beans []int) int64 { sort.Ints(beans) @@ -150,10 +120,20 @@ func minimumRemoval(beans []int) int64 { } ``` -### **...** - -``` - +```ts +function minimumRemoval(beans: number[]): number { + const n = beans.length; + let sum = beans.reduce((a, c) => a + c, 0); + beans.sort((a, b) => a - b); + let ans = sum; + for (let i = 0; i < n; i++) { + let num = beans[i]; + ans = Math.min(sum - num * (n - i), ans); + } + return ans; +} ``` + + diff --git a/solution/2100-2199/2171.Removing Minimum Number of Magic Beans/README_EN.md b/solution/2100-2199/2171.Removing Minimum Number of Magic Beans/README_EN.md index aa9a59f654d68..b7ff70bad3fe6 100644 --- a/solution/2100-2199/2171.Removing Minimum Number of Magic Beans/README_EN.md +++ b/solution/2100-2199/2171.Removing Minimum Number of Magic Beans/README_EN.md @@ -53,9 +53,9 @@ There are no other solutions that removes 7 beans or fewer. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long minimumRemoval(int[] beans) { @@ -88,24 +86,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minimumRemoval(beans: number[]): number { - const n = beans.length; - let sum = beans.reduce((a, c) => a + c, 0); - beans.sort((a, b) => a - b); - let ans = sum; - for (let i = 0; i < n; i++) { - let num = beans[i]; - ans = Math.min(sum - num * (n - i), ans); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -120,8 +100,6 @@ public: }; ``` -### **Go** - ```go func minimumRemoval(beans []int) int64 { sort.Ints(beans) @@ -138,10 +116,20 @@ func minimumRemoval(beans []int) int64 { } ``` -### **...** - -``` - +```ts +function minimumRemoval(beans: number[]): number { + const n = beans.length; + let sum = beans.reduce((a, c) => a + c, 0); + beans.sort((a, b) => a - b); + let ans = sum; + for (let i = 0; i < n; i++) { + let num = beans[i]; + ans = Math.min(sum - num * (n - i), ans); + } + return ans; +} ``` + + diff --git a/solution/2100-2199/2172.Maximum AND Sum of Array/README.md b/solution/2100-2199/2172.Maximum AND Sum of Array/README.md index c12963c4215d8..6340dbbd5dfa0 100644 --- a/solution/2100-2199/2172.Maximum AND Sum of Array/README.md +++ b/solution/2100-2199/2172.Maximum AND Sum of Array/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:状态压缩 + 动态规划** +### 方法一:状态压缩 + 动态规划 由于每个篮子最多只能放两个数,我们不妨将篮子数乘以 $2$,这样每个篮子最多只能放一个数。 @@ -72,10 +70,6 @@ $$ -### **Python3** - - - ```python class Solution: def maximumANDSum(self, nums: List[int], numSlots: int) -> int: @@ -92,10 +86,6 @@ class Solution: return max(f) ``` -### **Java** - - - ```java class Solution { public int maximumANDSum(int[] nums, int numSlots) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func maximumANDSum(nums []int, numSlots int) int { n := len(nums) @@ -168,8 +154,6 @@ func maximumANDSum(nums []int, numSlots int) int { } ``` -### **TypeScript** - ```ts function maximumANDSum(nums: number[], numSlots: number): number { const n = nums.length; @@ -193,10 +177,6 @@ function maximumANDSum(nums: number[], numSlots: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2172.Maximum AND Sum of Array/README_EN.md b/solution/2100-2199/2172.Maximum AND Sum of Array/README_EN.md index 964b1da0e2149..b6cd644f40c16 100644 --- a/solution/2100-2199/2172.Maximum AND Sum of Array/README_EN.md +++ b/solution/2100-2199/2172.Maximum AND Sum of Array/README_EN.md @@ -46,9 +46,9 @@ Note that slots 2, 5, 6, and 8 are empty which is permitted. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return max(f) ``` -### **Java** - ```java class Solution { public int maximumANDSum(int[] nums, int numSlots) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func maximumANDSum(nums []int, numSlots int) int { n := len(nums) @@ -140,8 +134,6 @@ func maximumANDSum(nums []int, numSlots int) int { } ``` -### **TypeScript** - ```ts function maximumANDSum(nums: number[], numSlots: number): number { const n = nums.length; @@ -165,10 +157,6 @@ function maximumANDSum(nums: number[], numSlots: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2173.Longest Winning Streak/README.md b/solution/2100-2199/2173.Longest Winning Streak/README.md index e0ca73a9e9ae4..ee58f62f010f9 100644 --- a/solution/2100-2199/2173.Longest Winning Streak/README.md +++ b/solution/2100-2199/2173.Longest Winning Streak/README.md @@ -79,14 +79,10 @@ Player 3: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -113,3 +109,5 @@ GROUP BY player_id; ``` + + diff --git a/solution/2100-2199/2173.Longest Winning Streak/README_EN.md b/solution/2100-2199/2173.Longest Winning Streak/README_EN.md index 1ed81a235b958..d06baaa17595e 100644 --- a/solution/2100-2199/2173.Longest Winning Streak/README_EN.md +++ b/solution/2100-2199/2173.Longest Winning Streak/README_EN.md @@ -76,9 +76,9 @@ The longest winning streak was 1 match. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -106,3 +106,5 @@ GROUP BY player_id; ``` + + diff --git a/solution/2100-2199/2174.Remove All Ones With Row and Column Flips II/README.md b/solution/2100-2199/2174.Remove All Ones With Row and Column Flips II/README.md index f4008614aa1c2..930c905eb312c 100644 --- a/solution/2100-2199/2174.Remove All Ones With Row and Column Flips II/README.md +++ b/solution/2100-2199/2174.Remove All Ones With Row and Column Flips II/README.md @@ -65,16 +65,10 @@ ## 解法 - - -**方法一:状态压缩 + BFS** +### 方法一:状态压缩 + BFS -### **Python3** - - - ```python class Solution: def removeOnes(self, grid: List[List[int]]) -> int: @@ -104,10 +98,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int removeOnes(int[][] grid) { @@ -157,8 +147,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -197,8 +185,6 @@ public: }; ``` -### **Go** - ```go func removeOnes(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -245,16 +231,6 @@ func removeOnes(grid [][]int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2174.Remove All Ones With Row and Column Flips II/README_EN.md b/solution/2100-2199/2174.Remove All Ones With Row and Column Flips II/README_EN.md index a8dfe1d0a82b8..44451b0181d45 100644 --- a/solution/2100-2199/2174.Remove All Ones With Row and Column Flips II/README_EN.md +++ b/solution/2100-2199/2174.Remove All Ones With Row and Column Flips II/README_EN.md @@ -62,9 +62,9 @@ There are no 1's to remove so return 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -95,8 +95,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int removeOnes(int[][] grid) { @@ -146,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -186,8 +182,6 @@ public: }; ``` -### **Go** - ```go func removeOnes(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -234,16 +228,6 @@ func removeOnes(grid [][]int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2175.The Change in Global Rankings/README.md b/solution/2100-2199/2175.The Change in Global Rankings/README.md index bcff74ce5cdbd..be8ea55fdce11 100644 --- a/solution/2100-2199/2175.The Change in Global Rankings/README.md +++ b/solution/2100-2199/2175.The Change in Global Rankings/README.md @@ -113,18 +113,12 @@ New Zealand 没有获得或丢失分数,他们的排名也没有发生变化 ## 解法 - - -**方法一:窗口函数** +### 方法一:窗口函数 利用 `rank()` 函数求出新老排名,然后用 `CAST` 将字段类型改为 `signed`,保证两个排名可以进行减法操作。 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -145,3 +139,5 @@ FROM ``` + + diff --git a/solution/2100-2199/2175.The Change in Global Rankings/README_EN.md b/solution/2100-2199/2175.The Change in Global Rankings/README_EN.md index d1a3b4d45260c..438d30daa3a0a 100644 --- a/solution/2100-2199/2175.The Change in Global Rankings/README_EN.md +++ b/solution/2100-2199/2175.The Change in Global Rankings/README_EN.md @@ -110,9 +110,9 @@ New Zealand did not gain or lose points and their rank did not change. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -134,3 +134,5 @@ FROM ``` + + diff --git a/solution/2100-2199/2176.Count Equal and Divisible Pairs in an Array/README.md b/solution/2100-2199/2176.Count Equal and Divisible Pairs in an Array/README.md index cd7366ecdd5a5..56d6af4d70aa2 100644 --- a/solution/2100-2199/2176.Count Equal and Divisible Pairs in an Array/README.md +++ b/solution/2100-2199/2176.Count Equal and Divisible Pairs in an Array/README.md @@ -40,16 +40,10 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 -### **Python3** - - - ```python class Solution: def countPairs(self, nums: List[int], k: int) -> int: @@ -61,10 +55,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public int countPairs(int[] nums, int k) { @@ -82,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +88,6 @@ public: }; ``` -### **Go** - ```go func countPairs(nums []int, k int) int { n := len(nums) @@ -117,8 +103,6 @@ func countPairs(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function countPairs(nums: number[], k: number): number { const n = nums.length; @@ -134,8 +118,6 @@ function countPairs(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_pairs(nums: Vec, k: i32) -> i32 { @@ -154,8 +136,6 @@ impl Solution { } ``` -### **C** - ```c int countPairs(int* nums, int numsSize, int k) { int ans = 0; @@ -170,10 +150,6 @@ int countPairs(int* nums, int numsSize, int k) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2176.Count Equal and Divisible Pairs in an Array/README_EN.md b/solution/2100-2199/2176.Count Equal and Divisible Pairs in an Array/README_EN.md index 59dfef6d8f8d3..b2da99488c0f5 100644 --- a/solution/2100-2199/2176.Count Equal and Divisible Pairs in an Array/README_EN.md +++ b/solution/2100-2199/2176.Count Equal and Divisible Pairs in an Array/README_EN.md @@ -38,9 +38,9 @@ There are 4 pairs that meet all the requirements: ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public int countPairs(int[] nums, int k) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,8 +86,6 @@ public: }; ``` -### **Go** - ```go func countPairs(nums []int, k int) int { n := len(nums) @@ -107,8 +101,6 @@ func countPairs(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function countPairs(nums: number[], k: number): number { const n = nums.length; @@ -124,8 +116,6 @@ function countPairs(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_pairs(nums: Vec, k: i32) -> i32 { @@ -144,8 +134,6 @@ impl Solution { } ``` -### **C** - ```c int countPairs(int* nums, int numsSize, int k) { int ans = 0; @@ -160,10 +148,6 @@ int countPairs(int* nums, int numsSize, int k) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/README.md b/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/README.md index e45e746734b85..a3bf2104489e1 100644 --- a/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/README.md +++ b/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/README.md @@ -35,9 +35,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 假设三个连续的整数分别为 $x-1$, $x$, $x+1$,则它们的和为 $3x$,因此 $num$ 必须是 $3$ 的倍数。如果 $num$ 不是 $3$ 的倍数,则无法表示成三个连续整数的和,返回空数组。否则,令 $x = \frac{num}{3}$,则 $x-1$, $x$, $x+1$ 就是三个连续整数,它们的和为 $num$。 @@ -45,10 +43,6 @@ -### **Python3** - - - ```python class Solution: def sumOfThree(self, num: int) -> List[int]: @@ -56,10 +50,6 @@ class Solution: return [] if mod else [x - 1, x, x + 1] ``` -### **Java** - - - ```java class Solution { public long[] sumOfThree(long num) { @@ -72,8 +62,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +75,6 @@ public: }; ``` -### **Go** - ```go func sumOfThree(num int64) []int64 { if num%3 != 0 { @@ -99,8 +85,6 @@ func sumOfThree(num int64) []int64 { } ``` -### **TypeScript** - ```ts function sumOfThree(num: number): number[] { if (num % 3) { @@ -111,10 +95,6 @@ function sumOfThree(num: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/README_EN.md b/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/README_EN.md index 1cf7d50b36994..cc0706d04fd09 100644 --- a/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/README_EN.md +++ b/solution/2100-2199/2177.Find Three Consecutive Integers That Sum to a Given Number/README_EN.md @@ -33,9 +33,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -44,8 +44,6 @@ class Solution: return [] if mod else [x - 1, x, x + 1] ``` -### **Java** - ```java class Solution { public long[] sumOfThree(long num) { @@ -58,8 +56,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -73,8 +69,6 @@ public: }; ``` -### **Go** - ```go func sumOfThree(num int64) []int64 { if num%3 != 0 { @@ -85,8 +79,6 @@ func sumOfThree(num int64) []int64 { } ``` -### **TypeScript** - ```ts function sumOfThree(num: number): number[] { if (num % 3) { @@ -97,10 +89,6 @@ function sumOfThree(num: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2178.Maximum Split of Positive Even Integers/README.md b/solution/2100-2199/2178.Maximum Split of Positive Even Integers/README.md index 4b1ec3bfeac1d..c107df1062c4f 100644 --- a/solution/2100-2199/2178.Maximum Split of Positive Even Integers/README.md +++ b/solution/2100-2199/2178.Maximum Split of Positive Even Integers/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 如果 $finalSum$ 是奇数,那么无法拆分成若干个互不相同的正偶数之和,直接返回空数组。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def maximumEvenSplit(self, finalSum: int) -> List[int]: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List maximumEvenSplit(long finalSum) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func maximumEvenSplit(finalSum int64) (ans []int64) { if finalSum%2 == 1 { @@ -141,8 +127,6 @@ func maximumEvenSplit(finalSum int64) (ans []int64) { } ``` -### **TypeScript** - ```ts function maximumEvenSplit(finalSum: number): number[] { const ans: number[] = []; @@ -158,8 +142,6 @@ function maximumEvenSplit(finalSum: number): number[] { } ``` -### **C#** - ```cs public class Solution { public IList MaximumEvenSplit(long finalSum) { @@ -177,10 +159,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2178.Maximum Split of Positive Even Integers/README_EN.md b/solution/2100-2199/2178.Maximum Split of Positive Even Integers/README_EN.md index f44519846ce9a..563f706fcba2e 100644 --- a/solution/2100-2199/2178.Maximum Split of Positive Even Integers/README_EN.md +++ b/solution/2100-2199/2178.Maximum Split of Positive Even Integers/README_EN.md @@ -51,9 +51,9 @@ Note that [10,2,4,12], [6,2,4,16], etc. are also accepted. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List maximumEvenSplit(long finalSum) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +103,6 @@ public: }; ``` -### **Go** - ```go func maximumEvenSplit(finalSum int64) (ans []int64) { if finalSum%2 == 1 { @@ -123,8 +117,6 @@ func maximumEvenSplit(finalSum int64) (ans []int64) { } ``` -### **TypeScript** - ```ts function maximumEvenSplit(finalSum: number): number[] { const ans: number[] = []; @@ -140,8 +132,6 @@ function maximumEvenSplit(finalSum: number): number[] { } ``` -### **C#** - ```cs public class Solution { public IList MaximumEvenSplit(long finalSum) { @@ -159,10 +149,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2179.Count Good Triplets in an Array/README.md b/solution/2100-2199/2179.Count Good Triplets in an Array/README.md index bd6d788437b58..b468e220d18ac 100644 --- a/solution/2100-2199/2179.Count Good Triplets in an Array/README.md +++ b/solution/2100-2199/2179.Count Good Triplets in an Array/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:树状数组或线段树** +### 方法一:树状数组或线段树 对于本题,我们先用 pos 记录每个数在 nums2 中的位置,然后依次对 nums1 中的每个元素进行处理。 @@ -83,12 +81,6 @@ -### **Python3** - - - -树状数组: - ```python class BinaryIndexedTree: def __init__(self, n): @@ -127,7 +119,164 @@ class Solution: return ans ``` -线段树: +```java +class Solution { + public long goodTriplets(int[] nums1, int[] nums2) { + int n = nums1.length; + int[] pos = new int[n]; + BinaryIndexedTree tree = new BinaryIndexedTree(n); + for (int i = 0; i < n; ++i) { + pos[nums2[i]] = i + 1; + } + long ans = 0; + for (int num : nums1) { + int p = pos[num]; + long left = tree.query(p); + long right = n - p - (tree.query(n) - tree.query(p)); + ans += left * right; + tree.update(p, 1); + } + return ans; + } +} + +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + public static int lowbit(int x) { + return x & -x; + } +} +``` + +```cpp +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + int lowbit(int x) { + return x & -x; + } +}; + +class Solution { +public: + long long goodTriplets(vector& nums1, vector& nums2) { + int n = nums1.size(); + vector pos(n); + for (int i = 0; i < n; ++i) pos[nums2[i]] = i + 1; + BinaryIndexedTree* tree = new BinaryIndexedTree(n); + long long ans = 0; + for (int& num : nums1) { + int p = pos[num]; + int left = tree->query(p); + int right = n - p - (tree->query(n) - tree->query(p)); + ans += 1ll * left * right; + tree->update(p, 1); + } + return ans; + } +}; +``` + +```go +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) lowbit(x int) int { + return x & -x +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += this.lowbit(x) + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= this.lowbit(x) + } + return s +} + +func goodTriplets(nums1 []int, nums2 []int) int64 { + n := len(nums1) + pos := make([]int, n) + for i, v := range nums2 { + pos[v] = i + 1 + } + tree := newBinaryIndexedTree(n) + var ans int64 + for _, num := range nums1 { + p := pos[num] + left := tree.query(p) + right := n - p - (tree.query(n) - tree.query(p)) + ans += int64(left) * int64(right) + tree.update(p, 1) + } + return ans +} +``` + + + +### 方法二 + + ```python class Node: @@ -192,66 +341,6 @@ class Solution: return ans ``` -### **Java** - - - -树状数组: - -```java -class Solution { - public long goodTriplets(int[] nums1, int[] nums2) { - int n = nums1.length; - int[] pos = new int[n]; - BinaryIndexedTree tree = new BinaryIndexedTree(n); - for (int i = 0; i < n; ++i) { - pos[nums2[i]] = i + 1; - } - long ans = 0; - for (int num : nums1) { - int p = pos[num]; - long left = tree.query(p); - long right = n - p - (tree.query(n) - tree.query(p)); - ans += left * right; - tree.update(p, 1); - } - return ans; - } -} - -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - public static int lowbit(int x) { - return x & -x; - } -} -``` - -线段树: - ```java class Solution { public long goodTriplets(int[] nums1, int[] nums2) { @@ -336,63 +425,6 @@ class SegmentTree { } ``` -### **C++** - -树状数组: - -```cpp -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - int lowbit(int x) { - return x & -x; - } -}; - -class Solution { -public: - long long goodTriplets(vector& nums1, vector& nums2) { - int n = nums1.size(); - vector pos(n); - for (int i = 0; i < n; ++i) pos[nums2[i]] = i + 1; - BinaryIndexedTree* tree = new BinaryIndexedTree(n); - long long ans = 0; - for (int& num : nums1) { - int p = pos[num]; - int left = tree->query(p); - int right = n - p - (tree->query(n) - tree->query(p)); - ans += 1ll * left * right; - tree->update(p, 1); - } - return ans; - } -}; -``` - -线段树: - ```cpp class Node { public: @@ -467,68 +499,6 @@ public: }; ``` -### **Go** - -```go -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (this *BinaryIndexedTree) lowbit(x int) int { - return x & -x -} - -func (this *BinaryIndexedTree) update(x, delta int) { - for x <= this.n { - this.c[x] += delta - x += this.lowbit(x) - } -} - -func (this *BinaryIndexedTree) query(x int) int { - s := 0 - for x > 0 { - s += this.c[x] - x -= this.lowbit(x) - } - return s -} - -func goodTriplets(nums1 []int, nums2 []int) int64 { - n := len(nums1) - pos := make([]int, n) - for i, v := range nums2 { - pos[v] = i + 1 - } - tree := newBinaryIndexedTree(n) - var ans int64 - for _, num := range nums1 { - p := pos[num] - left := tree.query(p) - right := n - p - (tree.query(n) - tree.query(p)) - ans += int64(left) * int64(right) - tree.update(p, 1) - } - return ans -} -``` - -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2179.Count Good Triplets in an Array/README_EN.md b/solution/2100-2199/2179.Count Good Triplets in an Array/README_EN.md index 71381b5957a36..0460b8de51387 100644 --- a/solution/2100-2199/2179.Count Good Triplets in an Array/README_EN.md +++ b/solution/2100-2199/2179.Count Good Triplets in an Array/README_EN.md @@ -41,14 +41,10 @@ Out of those triplets, only the triplet (0,1,3) satisfies pos2x < ## Solutions -Binary Indexed Tree or Segment Tree. +### Solution 1 -### **Python3** - -Binary Indexed Tree: - ```python class BinaryIndexedTree: def __init__(self, n): @@ -87,7 +83,164 @@ class Solution: return ans ``` -Segment Tree(TLE): +```java +class Solution { + public long goodTriplets(int[] nums1, int[] nums2) { + int n = nums1.length; + int[] pos = new int[n]; + BinaryIndexedTree tree = new BinaryIndexedTree(n); + for (int i = 0; i < n; ++i) { + pos[nums2[i]] = i + 1; + } + long ans = 0; + for (int num : nums1) { + int p = pos[num]; + long left = tree.query(p); + long right = n - p - (tree.query(n) - tree.query(p)); + ans += left * right; + tree.update(p, 1); + } + return ans; + } +} + +class BinaryIndexedTree { + private int n; + private int[] c; + + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; + } + + public void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + public int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + public static int lowbit(int x) { + return x & -x; + } +} +``` + +```cpp +class BinaryIndexedTree { +public: + int n; + vector c; + + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} + + void update(int x, int delta) { + while (x <= n) { + c[x] += delta; + x += lowbit(x); + } + } + + int query(int x) { + int s = 0; + while (x > 0) { + s += c[x]; + x -= lowbit(x); + } + return s; + } + + int lowbit(int x) { + return x & -x; + } +}; + +class Solution { +public: + long long goodTriplets(vector& nums1, vector& nums2) { + int n = nums1.size(); + vector pos(n); + for (int i = 0; i < n; ++i) pos[nums2[i]] = i + 1; + BinaryIndexedTree* tree = new BinaryIndexedTree(n); + long long ans = 0; + for (int& num : nums1) { + int p = pos[num]; + int left = tree->query(p); + int right = n - p - (tree->query(n) - tree->query(p)); + ans += 1ll * left * right; + tree->update(p, 1); + } + return ans; + } +}; +``` + +```go +type BinaryIndexedTree struct { + n int + c []int +} + +func newBinaryIndexedTree(n int) *BinaryIndexedTree { + c := make([]int, n+1) + return &BinaryIndexedTree{n, c} +} + +func (this *BinaryIndexedTree) lowbit(x int) int { + return x & -x +} + +func (this *BinaryIndexedTree) update(x, delta int) { + for x <= this.n { + this.c[x] += delta + x += this.lowbit(x) + } +} + +func (this *BinaryIndexedTree) query(x int) int { + s := 0 + for x > 0 { + s += this.c[x] + x -= this.lowbit(x) + } + return s +} + +func goodTriplets(nums1 []int, nums2 []int) int64 { + n := len(nums1) + pos := make([]int, n) + for i, v := range nums2 { + pos[v] = i + 1 + } + tree := newBinaryIndexedTree(n) + var ans int64 + for _, num := range nums1 { + p := pos[num] + left := tree.query(p) + right := n - p - (tree.query(n) - tree.query(p)) + ans += int64(left) * int64(right) + tree.update(p, 1) + } + return ans +} +``` + + + +### Solution 2 + + ```python class Node: @@ -152,64 +305,6 @@ class Solution: return ans ``` -### **Java** - -Binary Indexed Tree: - -```java -class Solution { - public long goodTriplets(int[] nums1, int[] nums2) { - int n = nums1.length; - int[] pos = new int[n]; - BinaryIndexedTree tree = new BinaryIndexedTree(n); - for (int i = 0; i < n; ++i) { - pos[nums2[i]] = i + 1; - } - long ans = 0; - for (int num : nums1) { - int p = pos[num]; - long left = tree.query(p); - long right = n - p - (tree.query(n) - tree.query(p)); - ans += left * right; - tree.update(p, 1); - } - return ans; - } -} - -class BinaryIndexedTree { - private int n; - private int[] c; - - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; - } - - public void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - public int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - public static int lowbit(int x) { - return x & -x; - } -} -``` - -Segment Tree: - ```java class Solution { public long goodTriplets(int[] nums1, int[] nums2) { @@ -294,63 +389,6 @@ class SegmentTree { } ``` -### **C++** - -Binary Indexed Tree: - -```cpp -class BinaryIndexedTree { -public: - int n; - vector c; - - BinaryIndexedTree(int _n) - : n(_n) - , c(_n + 1) {} - - void update(int x, int delta) { - while (x <= n) { - c[x] += delta; - x += lowbit(x); - } - } - - int query(int x) { - int s = 0; - while (x > 0) { - s += c[x]; - x -= lowbit(x); - } - return s; - } - - int lowbit(int x) { - return x & -x; - } -}; - -class Solution { -public: - long long goodTriplets(vector& nums1, vector& nums2) { - int n = nums1.size(); - vector pos(n); - for (int i = 0; i < n; ++i) pos[nums2[i]] = i + 1; - BinaryIndexedTree* tree = new BinaryIndexedTree(n); - long long ans = 0; - for (int& num : nums1) { - int p = pos[num]; - int left = tree->query(p); - int right = n - p - (tree->query(n) - tree->query(p)); - ans += 1ll * left * right; - tree->update(p, 1); - } - return ans; - } -}; -``` - -Segment Tree: - ```cpp class Node { public: @@ -425,68 +463,6 @@ public: }; ``` -### **Go** - -```go -type BinaryIndexedTree struct { - n int - c []int -} - -func newBinaryIndexedTree(n int) *BinaryIndexedTree { - c := make([]int, n+1) - return &BinaryIndexedTree{n, c} -} - -func (this *BinaryIndexedTree) lowbit(x int) int { - return x & -x -} - -func (this *BinaryIndexedTree) update(x, delta int) { - for x <= this.n { - this.c[x] += delta - x += this.lowbit(x) - } -} - -func (this *BinaryIndexedTree) query(x int) int { - s := 0 - for x > 0 { - s += this.c[x] - x -= this.lowbit(x) - } - return s -} - -func goodTriplets(nums1 []int, nums2 []int) int64 { - n := len(nums1) - pos := make([]int, n) - for i, v := range nums2 { - pos[v] = i + 1 - } - tree := newBinaryIndexedTree(n) - var ans int64 - for _, num := range nums1 { - p := pos[num] - left := tree.query(p) - right := n - p - (tree.query(n) - tree.query(p)) - ans += int64(left) * int64(right) - tree.update(p, 1) - } - return ans -} -``` - -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2180.Count Integers With Even Digit Sum/README.md b/solution/2100-2199/2180.Count Integers With Even Digit Sum/README.md index dfdf0d0d0db97..424f92679ece5 100644 --- a/solution/2100-2199/2180.Count Integers With Even Digit Sum/README.md +++ b/solution/2100-2199/2180.Count Integers With Even Digit Sum/README.md @@ -41,34 +41,14 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 一种最简单直接的方法是枚举 $[1,..num]$ 的所有整数 $x$,判断 $x$ 各位数字之和是否为偶数,是则答案加一。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(1)$。其中 $n$ 为 $num$ 的值。 -**方法二:数学** - -我们观察发现,在 $[0,..x]$ 的所有数中,每 $10$ 个数中,就有 $5$ 个数的各位数字之和为偶数。例如,在 $[0,..9]$ 中,每 $10$ 个数中,就有 $5$ 个数的各位数字之和为偶数,分别是 $0,2,4,6,8$。 - -因此,我们可以先算出 $num$ 中有多少个 $10$ 的倍数,然后乘以 $5$ 再减去 $1$(排除 $0$ 这个偶数),可以得到初始答案 $ans=\left\lfloor \frac{num}{10} \right\rfloor \times 5 - 1$。 - -接下来,我们还需要考虑剩下的 $num \% 10 + 1$ 个数字中,有多少个数的各位数字之和为偶数。这些数字是否是偶数,跟数字的前面数字之和有关,因此,我们可以算出 $num$ 的前面数字之和 $s$,那么剩余的数字中,还有 $\left\lfloor \frac{num \% 10 + 2 - (s \& 1)}{2} \right\rfloor$ 个数的各位数字之和为偶数。累加到答案 $ans$ 中即可。 - -我们不妨举个例子,假设 $num$ 为 $123$,那么前面 $[0,..119]$ 中一共有 $12$ 个 $10$ 的倍数,每个 $10$ 的倍数中有 $5$ 个数的各位数字之和为偶数,因此,初始答案为 $ans=12 \times 5 - 1=59$。 - -剩下的数字分别是 $120,121,122,123$,每个数字的前两位数字之和为 $s = 1+2=3$,是奇数,因此,剩下的数字中,只有 $2$ 个数的各位数字之和为偶数,累加到答案 $ans$ 中,最终答案为 $ans+2=61$。 - -时间复杂度 $O(\log n)$,空间复杂度 $O(1)$。其中 $n$ 为 $num$ 的值。 - -### **Python3** - - - ```python class Solution: def countEven(self, num: int) -> int: @@ -82,22 +62,6 @@ class Solution: return ans ``` -```python -class Solution: - def countEven(self, num: int) -> int: - ans = num // 10 * 5 - 1 - x, s = num // 10, 0 - while x: - s += x % 10 - x //= 10 - ans += (num % 10 + 2 - (s & 1)) >> 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int countEven(int num) { @@ -116,22 +80,6 @@ class Solution { } ``` -```java -class Solution { - public int countEven(int num) { - int ans = num / 10 * 5 - 1; - int s = 0; - for (int x = num / 10; x > 0; x /= 10) { - s += x % 10; - } - ans += (num % 10 + 2 - (s & 1)) >> 1; - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -149,23 +97,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countEven(int num) { - int ans = num / 10 * 5 - 1; - int s = 0; - for (int x = num / 10; x > 0; x /= 10) { - s += x % 10; - } - ans += (num % 10 + 2 - (s & 1)) >> 1; - return ans; - } -}; -``` - -### **Go** - ```go func countEven(num int) (ans int) { for i := 1; i <= num; i++ { @@ -181,20 +112,6 @@ func countEven(num int) (ans int) { } ``` -```go -func countEven(num int) (ans int) { - ans = num/10*5 - 1 - s := 0 - for x := num / 10; x > 0; x /= 10 { - s += x % 10 - } - ans += (num%10 + 2 - (s & 1)) >> 1 - return -} -``` - -### **TypeScript** - ```ts function countEven(num: number): number { let ans = 0; @@ -211,6 +128,77 @@ function countEven(num: number): number { } ``` + + +### 方法二:数学 + +我们观察发现,在 $[0,..x]$ 的所有数中,每 $10$ 个数中,就有 $5$ 个数的各位数字之和为偶数。例如,在 $[0,..9]$ 中,每 $10$ 个数中,就有 $5$ 个数的各位数字之和为偶数,分别是 $0,2,4,6,8$。 + +因此,我们可以先算出 $num$ 中有多少个 $10$ 的倍数,然后乘以 $5$ 再减去 $1$(排除 $0$ 这个偶数),可以得到初始答案 $ans=\left\lfloor \frac{num}{10} \right\rfloor \times 5 - 1$。 + +接下来,我们还需要考虑剩下的 $num \% 10 + 1$ 个数字中,有多少个数的各位数字之和为偶数。这些数字是否是偶数,跟数字的前面数字之和有关,因此,我们可以算出 $num$ 的前面数字之和 $s$,那么剩余的数字中,还有 $\left\lfloor \frac{num \% 10 + 2 - (s \& 1)}{2} \right\rfloor$ 个数的各位数字之和为偶数。累加到答案 $ans$ 中即可。 + +我们不妨举个例子,假设 $num$ 为 $123$,那么前面 $[0,..119]$ 中一共有 $12$ 个 $10$ 的倍数,每个 $10$ 的倍数中有 $5$ 个数的各位数字之和为偶数,因此,初始答案为 $ans=12 \times 5 - 1=59$。 + +剩下的数字分别是 $120,121,122,123$,每个数字的前两位数字之和为 $s = 1+2=3$,是奇数,因此,剩下的数字中,只有 $2$ 个数的各位数字之和为偶数,累加到答案 $ans$ 中,最终答案为 $ans+2=61$。 + +时间复杂度 $O(\log n)$,空间复杂度 $O(1)$。其中 $n$ 为 $num$ 的值。 + + + +```python +class Solution: + def countEven(self, num: int) -> int: + ans = num // 10 * 5 - 1 + x, s = num // 10, 0 + while x: + s += x % 10 + x //= 10 + ans += (num % 10 + 2 - (s & 1)) >> 1 + return ans +``` + +```java +class Solution { + public int countEven(int num) { + int ans = num / 10 * 5 - 1; + int s = 0; + for (int x = num / 10; x > 0; x /= 10) { + s += x % 10; + } + ans += (num % 10 + 2 - (s & 1)) >> 1; + return ans; + } +} +``` + +```cpp +class Solution { +public: + int countEven(int num) { + int ans = num / 10 * 5 - 1; + int s = 0; + for (int x = num / 10; x > 0; x /= 10) { + s += x % 10; + } + ans += (num % 10 + 2 - (s & 1)) >> 1; + return ans; + } +}; +``` + +```go +func countEven(num int) (ans int) { + ans = num/10*5 - 1 + s := 0 + for x := num / 10; x > 0; x /= 10 { + s += x % 10 + } + ans += (num%10 + 2 - (s & 1)) >> 1 + return +} +``` + ```ts function countEven(num: number): number { let ans = Math.floor(num / 10) * 5 - 1; @@ -223,10 +211,6 @@ function countEven(num: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2180.Count Integers With Even Digit Sum/README_EN.md b/solution/2100-2199/2180.Count Integers With Even Digit Sum/README_EN.md index 9b170c33ff993..48a79148c48c5 100644 --- a/solution/2100-2199/2180.Count Integers With Even Digit Sum/README_EN.md +++ b/solution/2100-2199/2180.Count Integers With Even Digit Sum/README_EN.md @@ -37,9 +37,9 @@ The 14 integers less than or equal to 30 whose digit sums are even are ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,20 +54,6 @@ class Solution: return ans ``` -```python -class Solution: - def countEven(self, num: int) -> int: - ans = num // 10 * 5 - 1 - x, s = num // 10, 0 - while x: - s += x % 10 - x //= 10 - ans += (num % 10 + 2 - (s & 1)) >> 1 - return ans -``` - -### **Java** - ```java class Solution { public int countEven(int num) { @@ -86,22 +72,6 @@ class Solution { } ``` -```java -class Solution { - public int countEven(int num) { - int ans = num / 10 * 5 - 1; - int s = 0; - for (int x = num / 10; x > 0; x /= 10) { - s += x % 10; - } - ans += (num % 10 + 2 - (s & 1)) >> 1; - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -119,23 +89,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countEven(int num) { - int ans = num / 10 * 5 - 1; - int s = 0; - for (int x = num / 10; x > 0; x /= 10) { - s += x % 10; - } - ans += (num % 10 + 2 - (s & 1)) >> 1; - return ans; - } -}; -``` - -### **Go** - ```go func countEven(num int) (ans int) { for i := 1; i <= num; i++ { @@ -151,20 +104,6 @@ func countEven(num int) (ans int) { } ``` -```go -func countEven(num int) (ans int) { - ans = num/10*5 - 1 - s := 0 - for x := num / 10; x > 0; x /= 10 { - s += x % 10 - } - ans += (num%10 + 2 - (s & 1)) >> 1 - return -} -``` - -### **TypeScript** - ```ts function countEven(num: number): number { let ans = 0; @@ -181,6 +120,65 @@ function countEven(num: number): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def countEven(self, num: int) -> int: + ans = num // 10 * 5 - 1 + x, s = num // 10, 0 + while x: + s += x % 10 + x //= 10 + ans += (num % 10 + 2 - (s & 1)) >> 1 + return ans +``` + +```java +class Solution { + public int countEven(int num) { + int ans = num / 10 * 5 - 1; + int s = 0; + for (int x = num / 10; x > 0; x /= 10) { + s += x % 10; + } + ans += (num % 10 + 2 - (s & 1)) >> 1; + return ans; + } +} +``` + +```cpp +class Solution { +public: + int countEven(int num) { + int ans = num / 10 * 5 - 1; + int s = 0; + for (int x = num / 10; x > 0; x /= 10) { + s += x % 10; + } + ans += (num % 10 + 2 - (s & 1)) >> 1; + return ans; + } +}; +``` + +```go +func countEven(num int) (ans int) { + ans = num/10*5 - 1 + s := 0 + for x := num / 10; x > 0; x /= 10 { + s += x % 10 + } + ans += (num%10 + 2 - (s & 1)) >> 1 + return +} +``` + ```ts function countEven(num: number): number { let ans = Math.floor(num / 10) * 5 - 1; @@ -193,10 +191,6 @@ function countEven(num: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2181.Merge Nodes in Between Zeros/README.md b/solution/2100-2199/2181.Merge Nodes in Between Zeros/README.md index 2dec6cf248e8a..79584d4968561 100644 --- a/solution/2100-2199/2181.Merge Nodes in Between Zeros/README.md +++ b/solution/2100-2199/2181.Merge Nodes in Between Zeros/README.md @@ -52,14 +52,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -82,10 +78,6 @@ class Solution: return dummy.next ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -116,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -149,8 +139,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -176,8 +164,6 @@ func mergeNodes(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -208,8 +194,6 @@ function mergeNodes(head: ListNode | null): ListNode | null { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -246,8 +230,6 @@ impl Solution { } ``` -### **C** - ```c /** * Definition for singly-linked list. @@ -276,10 +258,6 @@ struct ListNode* mergeNodes(struct ListNode* head) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2181.Merge Nodes in Between Zeros/README_EN.md b/solution/2100-2199/2181.Merge Nodes in Between Zeros/README_EN.md index e6b680a4bb4f7..dbaa91f762f80 100644 --- a/solution/2100-2199/2181.Merge Nodes in Between Zeros/README_EN.md +++ b/solution/2100-2199/2181.Merge Nodes in Between Zeros/README_EN.md @@ -46,9 +46,9 @@ The above figure represents the given linked list. The modified list contains ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -72,8 +72,6 @@ class Solution: return dummy.next ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -137,8 +133,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -164,8 +158,6 @@ func mergeNodes(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -196,8 +188,6 @@ function mergeNodes(head: ListNode | null): ListNode | null { } ``` -### **Rust** - ```rust // Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] @@ -234,8 +224,6 @@ impl Solution { } ``` -### **C** - ```c /** * Definition for singly-linked list. @@ -264,10 +252,6 @@ struct ListNode* mergeNodes(struct ListNode* head) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2182.Construct String With Repeat Limit/README.md b/solution/2100-2199/2182.Construct String With Repeat Limit/README.md index 9377f23cf0cfd..77709ab840183 100644 --- a/solution/2100-2199/2182.Construct String With Repeat Limit/README.md +++ b/solution/2100-2199/2182.Construct String With Repeat Limit/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们先用一个长度为 $26$ 的数组 $cnt$ 统计字符串 $s$ 中每个字符出现的次数,然后从大到小枚举字母表的第 $i$ 个字母,每次取出最多 $\min(cnt[i], repeatLimit)$ 个字母 $i$,如果取完后 $cnt[i]$ 还大于 $0$,则继续取字母表中第 $j$ 个字母,其中 $j$ 是最大的满足 $j < i$ 且 $cnt[j] > 0$ 的下标,直到取完所有字母。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def repeatLimitedString(self, s: str, repeatLimit: int) -> str: @@ -90,10 +84,6 @@ class Solution: return "".join(ans) ``` -### **Java** - - - ```java class Solution { public String repeatLimitedString(String s, int repeatLimit) { @@ -127,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +151,6 @@ public: }; ``` -### **Go** - ```go func repeatLimitedString(s string, repeatLimit int) string { cnt := [26]int{} @@ -196,8 +182,6 @@ func repeatLimitedString(s string, repeatLimit int) string { } ``` -### **TypeScript** - ```ts function repeatLimitedString(s: string, repeatLimit: number): string { const cnt: number[] = Array(26).fill(0); @@ -229,10 +213,6 @@ function repeatLimitedString(s: string, repeatLimit: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2182.Construct String With Repeat Limit/README_EN.md b/solution/2100-2199/2182.Construct String With Repeat Limit/README_EN.md index a1213f52e0cbe..28597f14e35b4 100644 --- a/solution/2100-2199/2182.Construct String With Repeat Limit/README_EN.md +++ b/solution/2100-2199/2182.Construct String With Repeat Limit/README_EN.md @@ -48,7 +48,7 @@ Note that the string "bbabaaa" is lexicographically larger but the let ## Solutions -**Solution 1: Greedy Algorithm** +### Solution 1: Greedy Algorithm First, we use an array $cnt$ of length $26$ to count the number of occurrences of each character in string $s$. Then, we enumerate the $i$th letter of the alphabet in descending order, each time taking out at most $\min(cnt[i], repeatLimit)$ of letter $i$. If after taking them out $cnt[i]$ is still greater than $0$, we continue to take the $j$th letter of the alphabet, where $j$ is the largest index satisfying $j < i$ and $cnt[j] > 0$, until all letters are taken. @@ -56,8 +56,6 @@ The time complexity is $O(n + |\Sigma|)$, and the space complexity is $O(|\Sigma -### **Python3** - ```python class Solution: def repeatLimitedString(self, s: str, repeatLimit: int) -> str: @@ -83,8 +81,6 @@ class Solution: return "".join(ans) ``` -### **Java** - ```java class Solution { public String repeatLimitedString(String s, int repeatLimit) { @@ -118,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +148,6 @@ public: }; ``` -### **Go** - ```go func repeatLimitedString(s string, repeatLimit int) string { cnt := [26]int{} @@ -187,8 +179,6 @@ func repeatLimitedString(s string, repeatLimit int) string { } ``` -### **TypeScript** - ```ts function repeatLimitedString(s: string, repeatLimit: number): string { const cnt: number[] = Array(26).fill(0); @@ -220,10 +210,6 @@ function repeatLimitedString(s: string, repeatLimit: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2183.Count Array Pairs Divisible by K/README.md b/solution/2100-2199/2183.Count Array Pairs Divisible by K/README.md index 38501d9b55276..e945842dba547 100644 --- a/solution/2100-2199/2183.Count Array Pairs Divisible by K/README.md +++ b/solution/2100-2199/2183.Count Array Pairs Divisible by K/README.md @@ -44,36 +44,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2100-2199/2183.Count Array Pairs Divisible by K/README_EN.md b/solution/2100-2199/2183.Count Array Pairs Divisible by K/README_EN.md index 35225c7e5cd31..f33cecbba587e 100644 --- a/solution/2100-2199/2183.Count Array Pairs Divisible by K/README_EN.md +++ b/solution/2100-2199/2183.Count Array Pairs Divisible by K/README_EN.md @@ -42,30 +42,4 @@ Other pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2100-2199/2184.Number of Ways to Build Sturdy Brick Wall/README.md b/solution/2100-2199/2184.Number of Ways to Build Sturdy Brick Wall/README.md index 72ca77a5b9a5e..d37822f6458c3 100644 --- a/solution/2100-2199/2184.Number of Ways to Build Sturdy Brick Wall/README.md +++ b/solution/2100-2199/2184.Number of Ways to Build Sturdy Brick Wall/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:DFS + 动态规划** +### 方法一:DFS + 动态规划 首先通过 DFS 构造出所有合法的排列。然后所有排列进行两两比较,找出每种排列相邻的合法排列,记录在 `g` 数组中。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def buildWall(self, height: int, width: int, bricks: List[int]) -> int: @@ -116,10 +110,6 @@ class Solution: return sum(dp[-1]) % mod ``` -### **Java** - - - ```java class Solution { private List> res = new ArrayList<>(); @@ -198,8 +188,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -273,8 +261,6 @@ public: }; ``` -### **Go** - ```go func buildWall(height int, width int, bricks []int) int { mod := int(1e9) + 7 @@ -350,16 +336,6 @@ func buildWall(height int, width int, bricks []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2184.Number of Ways to Build Sturdy Brick Wall/README_EN.md b/solution/2100-2199/2184.Number of Ways to Build Sturdy Brick Wall/README_EN.md index 5b4e3ca00feb2..f262e6e75c0fe 100644 --- a/solution/2100-2199/2184.Number of Ways to Build Sturdy Brick Wall/README_EN.md +++ b/solution/2100-2199/2184.Number of Ways to Build Sturdy Brick Wall/README_EN.md @@ -43,9 +43,9 @@ There are no ways to build a sturdy wall because the only type of brick we have ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -99,8 +99,6 @@ class Solution: return sum(dp[-1]) % mod ``` -### **Java** - ```java class Solution { private List> res = new ArrayList<>(); @@ -179,8 +177,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -254,8 +250,6 @@ public: }; ``` -### **Go** - ```go func buildWall(height int, width int, bricks []int) int { mod := int(1e9) + 7 @@ -331,16 +325,6 @@ func buildWall(height int, width int, bricks []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2185.Counting Words With a Given Prefix/README.md b/solution/2100-2199/2185.Counting Words With a Given Prefix/README.md index 6cf87dcf6ef42..e9031bd2ba2df 100644 --- a/solution/2100-2199/2185.Counting Words With a Given Prefix/README.md +++ b/solution/2100-2199/2185.Counting Words With a Given Prefix/README.md @@ -40,15 +40,89 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 根据题目描述,我们遍历字符串数组 `words` 中的每个字符串 $w$,判断其是否以 $pref$ 作为前缀,如果是,则答案加一。 时间复杂度 $O(n \times m)$,空间复杂度 $O(1)$。其中 $n$ 和 $m$ 分别是字符串数组 `words` 和字符串 $pref$ 的长度。 -**方法二:前缀树** + + +```python +class Solution: + def prefixCount(self, words: List[str], pref: str) -> int: + return sum(w.startswith(pref) for w in words) +``` + +```java +class Solution { + public int prefixCount(String[] words, String pref) { + int ans = 0; + for (String w : words) { + if (w.startsWith(pref)) { + ++ans; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int prefixCount(vector& words, string pref) { + int ans = 0; + for (auto& w : words) ans += w.find(pref) == 0; + return ans; + } +}; +``` + +```go +func prefixCount(words []string, pref string) (ans int) { + for _, w := range words { + if strings.HasPrefix(w, pref) { + ans++ + } + } + return +} +``` + +```ts +function prefixCount(words: string[], pref: string): number { + return words.reduce((r, s) => (r += s.startsWith(pref) ? 1 : 0), 0); +} +``` + +```rust +impl Solution { + pub fn prefix_count(words: Vec, pref: String) -> i32 { + words + .iter() + .filter(|s| s.starts_with(&pref)) + .count() as i32 + } +} +``` + +```c +int prefixCount(char** words, int wordsSize, char* pref) { + int ans = 0; + int n = strlen(pref); + for (int i = 0; i < wordsSize; i++) { + if (strncmp(words[i], pref, n) == 0) { + ans++; + } + } + return ans; +} +``` + + + +### 方法二:前缀树 我们还可以使用前缀树来查询答案。 @@ -70,16 +144,6 @@ -### **Python3** - - - -```python -class Solution: - def prefixCount(self, words: List[str], pref: str) -> int: - return sum(w.startswith(pref) for w in words) -``` - ```python class Trie: def __init__(self): @@ -113,24 +177,6 @@ class Solution: return tree.search(pref) ``` -### **Java** - - - -```java -class Solution { - public int prefixCount(String[] words, String pref) { - int ans = 0; - for (String w : words) { - if (w.startsWith(pref)) { - ++ans; - } - } - return ans; - } -} -``` - ```java class Trie { private Trie[] children = new Trie[26]; @@ -172,19 +218,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int prefixCount(vector& words, string pref) { - int ans = 0; - for (auto& w : words) ans += w.find(pref) == 0; - return ans; - } -}; -``` - ```cpp class Trie { public: @@ -233,19 +266,6 @@ public: }; ``` -### **Go** - -```go -func prefixCount(words []string, pref string) (ans int) { - for _, w := range words { - if strings.HasPrefix(w, pref) { - ans++ - } - } - return -} -``` - ```go type Trie struct { children [26]*Trie @@ -289,46 +309,6 @@ func prefixCount(words []string, pref string) int { } ``` -### **TypeScript** - -```ts -function prefixCount(words: string[], pref: string): number { - return words.reduce((r, s) => (r += s.startsWith(pref) ? 1 : 0), 0); -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn prefix_count(words: Vec, pref: String) -> i32 { - words - .iter() - .filter(|s| s.starts_with(&pref)) - .count() as i32 - } -} -``` - -### **C** - -```c -int prefixCount(char** words, int wordsSize, char* pref) { - int ans = 0; - int n = strlen(pref); - for (int i = 0; i < wordsSize; i++) { - if (strncmp(words[i], pref, n) == 0) { - ans++; - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2185.Counting Words With a Given Prefix/README_EN.md b/solution/2100-2199/2185.Counting Words With a Given Prefix/README_EN.md index e07b13ff199d8..86464a331eb3a 100644 --- a/solution/2100-2199/2185.Counting Words With a Given Prefix/README_EN.md +++ b/solution/2100-2199/2185.Counting Words With a Given Prefix/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -48,6 +48,78 @@ class Solution: return sum(w.startswith(pref) for w in words) ``` +```java +class Solution { + public int prefixCount(String[] words, String pref) { + int ans = 0; + for (String w : words) { + if (w.startsWith(pref)) { + ++ans; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int prefixCount(vector& words, string pref) { + int ans = 0; + for (auto& w : words) ans += w.find(pref) == 0; + return ans; + } +}; +``` + +```go +func prefixCount(words []string, pref string) (ans int) { + for _, w := range words { + if strings.HasPrefix(w, pref) { + ans++ + } + } + return +} +``` + +```ts +function prefixCount(words: string[], pref: string): number { + return words.reduce((r, s) => (r += s.startsWith(pref) ? 1 : 0), 0); +} +``` + +```rust +impl Solution { + pub fn prefix_count(words: Vec, pref: String) -> i32 { + words + .iter() + .filter(|s| s.starts_with(&pref)) + .count() as i32 + } +} +``` + +```c +int prefixCount(char** words, int wordsSize, char* pref) { + int ans = 0; + int n = strlen(pref); + for (int i = 0; i < wordsSize; i++) { + if (strncmp(words[i], pref, n) == 0) { + ans++; + } + } + return ans; +} +``` + + + +### Solution 2 + + + ```python class Trie: def __init__(self): @@ -81,22 +153,6 @@ class Solution: return tree.search(pref) ``` -### **Java** - -```java -class Solution { - public int prefixCount(String[] words, String pref) { - int ans = 0; - for (String w : words) { - if (w.startsWith(pref)) { - ++ans; - } - } - return ans; - } -} -``` - ```java class Trie { private Trie[] children = new Trie[26]; @@ -138,19 +194,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int prefixCount(vector& words, string pref) { - int ans = 0; - for (auto& w : words) ans += w.find(pref) == 0; - return ans; - } -}; -``` - ```cpp class Trie { public: @@ -199,19 +242,6 @@ public: }; ``` -### **Go** - -```go -func prefixCount(words []string, pref string) (ans int) { - for _, w := range words { - if strings.HasPrefix(w, pref) { - ans++ - } - } - return -} -``` - ```go type Trie struct { children [26]*Trie @@ -255,46 +285,6 @@ func prefixCount(words []string, pref string) int { } ``` -### **TypeScript** - -```ts -function prefixCount(words: string[], pref: string): number { - return words.reduce((r, s) => (r += s.startsWith(pref) ? 1 : 0), 0); -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn prefix_count(words: Vec, pref: String) -> i32 { - words - .iter() - .filter(|s| s.starts_with(&pref)) - .count() as i32 - } -} -``` - -### **C** - -```c -int prefixCount(char** words, int wordsSize, char* pref) { - int ans = 0; - int n = strlen(pref); - for (int i = 0; i < wordsSize; i++) { - if (strncmp(words[i], pref, n) == 0) { - ans++; - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2186.Minimum Number of Steps to Make Two Strings Anagram II/README.md b/solution/2100-2199/2186.Minimum Number of Steps to Make Two Strings Anagram II/README.md index a702e106f23b6..dbad9dadd81d1 100644 --- a/solution/2100-2199/2186.Minimum Number of Steps to Make Two Strings Anagram II/README.md +++ b/solution/2100-2199/2186.Minimum Number of Steps to Make Two Strings Anagram II/README.md @@ -43,16 +43,10 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 -### **Python3** - - - ```python class Solution: def minSteps(self, s: str, t: str) -> int: @@ -62,10 +56,6 @@ class Solution: return sum(abs(v) for v in cnt.values()) ``` -### **Java** - - - ```java class Solution { public int minSteps(String s, String t) { @@ -85,27 +75,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minSteps(s: string, t: string): number { - let cnt = new Array(128).fill(0); - for (const c of s) { - ++cnt[c.charCodeAt(0)]; - } - for (const c of t) { - --cnt[c.charCodeAt(0)]; - } - let ans = 0; - for (const v of cnt) { - ans += Math.abs(v); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -120,8 +89,6 @@ public: }; ``` -### **Go** - ```go func minSteps(s string, t string) int { cnt := make([]int, 26) @@ -146,7 +113,22 @@ func abs(x int) int { } ``` -### **JavaScript** +```ts +function minSteps(s: string, t: string): number { + let cnt = new Array(128).fill(0); + for (const c of s) { + ++cnt[c.charCodeAt(0)]; + } + for (const c of t) { + --cnt[c.charCodeAt(0)]; + } + let ans = 0; + for (const v of cnt) { + ans += Math.abs(v); + } + return ans; +} +``` ```js /** @@ -170,10 +152,6 @@ var minSteps = function (s, t) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2186.Minimum Number of Steps to Make Two Strings Anagram II/README_EN.md b/solution/2100-2199/2186.Minimum Number of Steps to Make Two Strings Anagram II/README_EN.md index 76f1fb721ab57..22bb4d3346925 100644 --- a/solution/2100-2199/2186.Minimum Number of Steps to Make Two Strings Anagram II/README_EN.md +++ b/solution/2100-2199/2186.Minimum Number of Steps to Make Two Strings Anagram II/README_EN.md @@ -42,9 +42,9 @@ It can be shown that there is no way to make them anagrams of each other with le ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return sum(abs(v) for v in cnt.values()) ``` -### **Java** - ```java class Solution { public int minSteps(String s, String t) { @@ -76,27 +74,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function minSteps(s: string, t: string): number { - let cnt = new Array(128).fill(0); - for (const c of s) { - ++cnt[c.charCodeAt(0)]; - } - for (const c of t) { - --cnt[c.charCodeAt(0)]; - } - let ans = 0; - for (const v of cnt) { - ans += Math.abs(v); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -111,8 +88,6 @@ public: }; ``` -### **Go** - ```go func minSteps(s string, t string) int { cnt := make([]int, 26) @@ -137,7 +112,22 @@ func abs(x int) int { } ``` -### **JavaScript** +```ts +function minSteps(s: string, t: string): number { + let cnt = new Array(128).fill(0); + for (const c of s) { + ++cnt[c.charCodeAt(0)]; + } + for (const c of t) { + --cnt[c.charCodeAt(0)]; + } + let ans = 0; + for (const v of cnt) { + ans += Math.abs(v); + } + return ans; +} +``` ```js /** @@ -161,10 +151,6 @@ var minSteps = function (s, t) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2187.Minimum Time to Complete Trips/README.md b/solution/2100-2199/2187.Minimum Time to Complete Trips/README.md index c631355403d0f..b4a897777f687 100644 --- a/solution/2100-2199/2187.Minimum Time to Complete Trips/README.md +++ b/solution/2100-2199/2187.Minimum Time to Complete Trips/README.md @@ -48,14 +48,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minimumTime(self, time: List[int], totalTrips: int) -> int: @@ -65,10 +61,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public long minimumTime(int[] time, int totalTrips) { @@ -94,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +106,6 @@ public: }; ``` -### **Go** - ```go func minimumTime(time []int, totalTrips int) int64 { left, right := 1, slices.Min(time)*totalTrips @@ -137,16 +125,6 @@ func minimumTime(time []int, totalTrips int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2187.Minimum Time to Complete Trips/README_EN.md b/solution/2100-2199/2187.Minimum Time to Complete Trips/README_EN.md index 967df6e1597e7..1dbec4e25a1da 100644 --- a/solution/2100-2199/2187.Minimum Time to Complete Trips/README_EN.md +++ b/solution/2100-2199/2187.Minimum Time to Complete Trips/README_EN.md @@ -46,9 +46,9 @@ So the minimum time needed to complete 1 trip is 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public long minimumTime(int[] time, int totalTrips) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +104,6 @@ public: }; ``` -### **Go** - ```go func minimumTime(time []int, totalTrips int) int64 { left, right := 1, slices.Min(time)*totalTrips @@ -129,16 +123,6 @@ func minimumTime(time []int, totalTrips int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2188.Minimum Time to Finish the Race/README.md b/solution/2100-2199/2188.Minimum Time to Finish the Race/README.md index d4a2123c2180a..03ee752654363 100644 --- a/solution/2100-2199/2188.Minimum Time to Finish the Race/README.md +++ b/solution/2100-2199/2188.Minimum Time to Finish the Race/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:预处理 + 动态规划** +### 方法一:预处理 + 动态规划 我们注意到,连续使用同一个轮胎 $(f, r)$ 跑 $i$ 圈,那么第 $i$ 圈的耗时不应该超过 $changeTime + f$,否则我们可以在第 $i$ 圈的时候换轮胎,这样总耗时会更少。即: @@ -85,10 +83,6 @@ $$ -### **Python3** - - - ```python class Solution: def minimumFinishTime( @@ -111,10 +105,6 @@ class Solution: return f[numLaps] ``` -### **Java** - - - ```java class Solution { public int minimumFinishTime(int[][] tires, int changeTime, int numLaps) { @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +164,6 @@ public: }; ``` -### **Go** - ```go func minimumFinishTime(tires [][]int, changeTime int, numLaps int) int { const inf = 1 << 30 @@ -209,8 +195,6 @@ func minimumFinishTime(tires [][]int, changeTime int, numLaps int) int { } ``` -### **TypeScript** - ```ts function minimumFinishTime(tires: number[][], changeTime: number, numLaps: number): number { const cost: number[] = Array(18).fill(Infinity); @@ -235,10 +219,6 @@ function minimumFinishTime(tires: number[][], changeTime: number, numLaps: numbe } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2188.Minimum Time to Finish the Race/README_EN.md b/solution/2100-2199/2188.Minimum Time to Finish the Race/README_EN.md index 13d73cffe2bdb..b0688967b2bb7 100644 --- a/solution/2100-2199/2188.Minimum Time to Finish the Race/README_EN.md +++ b/solution/2100-2199/2188.Minimum Time to Finish the Race/README_EN.md @@ -59,9 +59,9 @@ The minimum time to complete the race is 25 seconds. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -85,8 +85,6 @@ class Solution: return f[numLaps] ``` -### **Java** - ```java class Solution { public int minimumFinishTime(int[][] tires, int changeTime, int numLaps) { @@ -116,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +144,6 @@ public: }; ``` -### **Go** - ```go func minimumFinishTime(tires [][]int, changeTime int, numLaps int) int { const inf = 1 << 30 @@ -181,8 +175,6 @@ func minimumFinishTime(tires [][]int, changeTime int, numLaps int) int { } ``` -### **TypeScript** - ```ts function minimumFinishTime(tires: number[][], changeTime: number, numLaps: number): number { const cost: number[] = Array(18).fill(Infinity); @@ -207,10 +199,6 @@ function minimumFinishTime(tires: number[][], changeTime: number, numLaps: numbe } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2189.Number of Ways to Build House of Cards/README.md b/solution/2100-2199/2189.Number of Ways to Build House of Cards/README.md index 549880b4b7b6e..f83d6471fc52f 100644 --- a/solution/2100-2199/2189.Number of Ways to Build House of Cards/README.md +++ b/solution/2100-2199/2189.Number of Ways to Build House of Cards/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们注意到,每一层的卡片数量为 $3 \times k + 2$,并且每一层的卡片数量都不相同。因此,问题可以转化为:整数 $n$ 可以由多少种 $3 \times k + 2$ 的数相加得到。这是一个经典的背包问题,可以使用记忆化搜索解决。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def houseOfCards(self, n: int) -> int: @@ -95,10 +89,6 @@ class Solution: return dfs(n, 0) ``` -### **Java** - - - ```java class Solution { private Integer[][] f; @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func houseOfCards(n int) int { f := make([][]int, n+1) @@ -179,8 +165,6 @@ func houseOfCards(n int) int { } ``` -### **TypeScript** - ```ts function houseOfCards(n: number): number { const f: number[][] = Array(n + 1) @@ -203,10 +187,6 @@ function houseOfCards(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2189.Number of Ways to Build House of Cards/README_EN.md b/solution/2100-2199/2189.Number of Ways to Build House of Cards/README_EN.md index 92c890393879f..f61a6aad59d79 100644 --- a/solution/2100-2199/2189.Number of Ways to Build House of Cards/README_EN.md +++ b/solution/2100-2199/2189.Number of Ways to Build House of Cards/README_EN.md @@ -54,9 +54,9 @@ The third house of cards uses 2 cards. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return dfs(n, 0) ``` -### **Java** - ```java class Solution { private Integer[][] f; @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +122,6 @@ public: }; ``` -### **Go** - ```go func houseOfCards(n int) int { f := make([][]int, n+1) @@ -155,8 +149,6 @@ func houseOfCards(n int) int { } ``` -### **TypeScript** - ```ts function houseOfCards(n: number): number { const f: number[][] = Array(n + 1) @@ -179,10 +171,6 @@ function houseOfCards(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2190.Most Frequent Number Following Key In an Array/README.md b/solution/2100-2199/2190.Most Frequent Number Following Key In an Array/README.md index 46aa295b58923..20096b3a572e1 100644 --- a/solution/2100-2199/2190.Most Frequent Number Following Key In an Array/README.md +++ b/solution/2100-2199/2190.Most Frequent Number Following Key In an Array/README.md @@ -49,9 +49,7 @@ target = 2 是紧跟着 key 之后出现次数最多的数字,所以我们返 ## 解法 - - -**方法一:遍历计数** +### 方法一:遍历计数 我们用一个哈希表或数组 $cnt$ 记录每个 $target$ 出现的次数,用一个变量 $mx$ 维护 $target$ 出现的最大次数,初始时 $mx = 0$。 @@ -63,10 +61,6 @@ target = 2 是紧跟着 key 之后出现次数最多的数字,所以我们返 -### **Python3** - - - ```python class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int mostFrequent(int[] nums, int key) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func mostFrequent(nums []int, key int) (ans int) { cnt := [1001]int{} @@ -143,8 +129,6 @@ func mostFrequent(nums []int, key int) (ans int) { } ``` -### **TypeScript** - ```ts function mostFrequent(nums: number[], key: number): number { const cnt: number[] = new Array(1001).fill(0); @@ -162,8 +146,6 @@ function mostFrequent(nums: number[], key: number): number { } ``` -### **PHP** - ```php class Solution { /** @@ -188,10 +170,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2190.Most Frequent Number Following Key In an Array/README_EN.md b/solution/2100-2199/2190.Most Frequent Number Following Key In an Array/README_EN.md index 3515cc29bd208..f47f245d333ce 100644 --- a/solution/2100-2199/2190.Most Frequent Number Following Key In an Array/README_EN.md +++ b/solution/2100-2199/2190.Most Frequent Number Following Key In an Array/README_EN.md @@ -47,9 +47,9 @@ target = 2 has the maximum number of occurrences following an occurrence of key, ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int mostFrequent(int[] nums, int key) { @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +102,6 @@ public: }; ``` -### **Go** - ```go func mostFrequent(nums []int, key int) (ans int) { cnt := [1001]int{} @@ -125,8 +119,6 @@ func mostFrequent(nums []int, key int) (ans int) { } ``` -### **TypeScript** - ```ts function mostFrequent(nums: number[], key: number): number { const cnt: number[] = new Array(1001).fill(0); @@ -144,8 +136,6 @@ function mostFrequent(nums: number[], key: number): number { } ``` -### **PHP** - ```php class Solution { /** @@ -170,10 +160,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2191.Sort the Jumbled Numbers/README.md b/solution/2100-2199/2191.Sort the Jumbled Numbers/README.md index 95b1bbf25203b..c2e14679c4b6f 100644 --- a/solution/2100-2199/2191.Sort the Jumbled Numbers/README.md +++ b/solution/2100-2199/2191.Sort the Jumbled Numbers/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:自定义排序** +### 方法一:自定义排序 我们遍历数组 $nums$ 中的每个元素 $nums[i]$,将其映射后的值 $y$ 与下标 $i$ 一起存入数组 $arr$ 中,然后对数组 $arr$ 进行排序,最后将排序后的数组 $arr$ 中的下标 $i$ 取出,转换为原数组 $nums$ 中的元素 $nums[i]$ 即可。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: @@ -87,10 +81,6 @@ class Solution: return [nums[i] for _, i in arr] ``` -### **Java** - - - ```java class Solution { public int[] sortJumbled(int[] mapping, int[] nums) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func sortJumbled(mapping []int, nums []int) (ans []int) { n := len(nums) @@ -173,8 +159,6 @@ func sortJumbled(mapping []int, nums []int) (ans []int) { } ``` -### **TypeScript** - ```ts function sortJumbled(mapping: number[], nums: number[]): number[] { const n = nums.length; @@ -193,10 +177,6 @@ function sortJumbled(mapping: number[], nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2191.Sort the Jumbled Numbers/README_EN.md b/solution/2100-2199/2191.Sort the Jumbled Numbers/README_EN.md index fbdd12bd5ca06..4aed547d8c9f4 100644 --- a/solution/2100-2199/2191.Sort the Jumbled Numbers/README_EN.md +++ b/solution/2100-2199/2191.Sort the Jumbled Numbers/README_EN.md @@ -55,9 +55,9 @@ Thus, the sorted array is [338,38,991]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return [nums[i] for _, i in arr] ``` -### **Java** - ```java class Solution { public int[] sortJumbled(int[] mapping, int[] nums) { @@ -102,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +126,6 @@ public: }; ``` -### **Go** - ```go func sortJumbled(mapping []int, nums []int) (ans []int) { n := len(nums) @@ -159,8 +153,6 @@ func sortJumbled(mapping []int, nums []int) (ans []int) { } ``` -### **TypeScript** - ```ts function sortJumbled(mapping: number[], nums: number[]): number[] { const n = nums.length; @@ -179,10 +171,6 @@ function sortJumbled(mapping: number[], nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/README.md b/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/README.md index 7e40cd101d7ae..b3e2e98a47ac7 100644 --- a/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/README.md +++ b/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们先根据二维数组 $edges$ 构建邻接表 $g$,其中 $g[i]$ 表示节点 $i$ 的所有后继节点。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: @@ -102,10 +96,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int n; @@ -148,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -185,8 +173,6 @@ public: }; ``` -### **Go** - ```go func getAncestors(n int, edges [][]int) [][]int { g := make([][]int, n) @@ -217,8 +203,6 @@ func getAncestors(n int, edges [][]int) [][]int { } ``` -### **TypeScript** - ```ts function getAncestors(n: number, edges: number[][]): number[][] { const g: number[][] = Array.from({ length: n }, () => []); @@ -248,10 +232,6 @@ function getAncestors(n: number, edges: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/README_EN.md b/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/README_EN.md index 883d37df8c10e..abe2d006e26e1 100644 --- a/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/README_EN.md +++ b/solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/README_EN.md @@ -57,12 +57,10 @@ The above diagram represents the input graph. ## Solutions -BFS. +### Solution 1 -### **Python3** - ```python class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: @@ -86,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int n; @@ -130,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +161,6 @@ public: }; ``` -### **Go** - ```go func getAncestors(n int, edges [][]int) [][]int { g := make([][]int, n) @@ -199,8 +191,6 @@ func getAncestors(n int, edges [][]int) [][]int { } ``` -### **TypeScript** - ```ts function getAncestors(n: number, edges: number[][]): number[][] { const g: number[][] = Array.from({ length: n }, () => []); @@ -230,10 +220,6 @@ function getAncestors(n: number, edges: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2193.Minimum Number of Moves to Make Palindrome/README.md b/solution/2100-2199/2193.Minimum Number of Moves to Make Palindrome/README.md index 0c975af0b8777..f1d042274ac40 100644 --- a/solution/2100-2199/2193.Minimum Number of Moves to Make Palindrome/README.md +++ b/solution/2100-2199/2193.Minimum Number of Moves to Make Palindrome/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 由于题目保证原串一定可以变成回文串,那么原串中最多只有一种字母出现奇数次。如果有一种字母出现奇数次,那么将该字母中排在最中间的字符移动到字符串中间,剩下的字符可以转化为所有字母均出现偶数次的情况。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def minMovesToMakePalindrome(self, s: str) -> int: @@ -101,10 +95,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minMovesToMakePalindrome(String s) { @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +151,6 @@ public: }; ``` -### **Go** - ```go func minMovesToMakePalindrome(s string) int { cs := []byte(s) @@ -190,16 +176,6 @@ func minMovesToMakePalindrome(s string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2193.Minimum Number of Moves to Make Palindrome/README_EN.md b/solution/2100-2199/2193.Minimum Number of Moves to Make Palindrome/README_EN.md index 7b7a6e10c733e..8c39f7cdaf8f2 100644 --- a/solution/2100-2199/2193.Minimum Number of Moves to Make Palindrome/README_EN.md +++ b/solution/2100-2199/2193.Minimum Number of Moves to Make Palindrome/README_EN.md @@ -48,9 +48,9 @@ It can be shown that it is not possible to obtain a palindrome in less than 2 mo ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minMovesToMakePalindrome(String s) { @@ -107,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +131,6 @@ public: }; ``` -### **Go** - ```go func minMovesToMakePalindrome(s string) int { cs := []byte(s) @@ -162,16 +156,6 @@ func minMovesToMakePalindrome(s string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2194.Cells in a Range on an Excel Sheet/README.md b/solution/2100-2199/2194.Cells in a Range on an Excel Sheet/README.md index 024342e3f7476..c9d09b685cd69 100644 --- a/solution/2100-2199/2194.Cells in a Range on an Excel Sheet/README.md +++ b/solution/2100-2199/2194.Cells in a Range on an Excel Sheet/README.md @@ -62,14 +62,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def cellsInRange(self, s: str) -> List[str]: @@ -80,10 +76,6 @@ class Solution: ] ``` -### **Java** - - - ```java class Solution { public List cellsInRange(String s) { @@ -98,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +103,6 @@ public: }; ``` -### **Go** - ```go func cellsInRange(s string) []string { var ans []string @@ -127,16 +115,6 @@ func cellsInRange(s string) []string { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2194.Cells in a Range on an Excel Sheet/README_EN.md b/solution/2100-2199/2194.Cells in a Range on an Excel Sheet/README_EN.md index a190dd5675465..31d9927f4efc1 100644 --- a/solution/2100-2199/2194.Cells in a Range on an Excel Sheet/README_EN.md +++ b/solution/2100-2199/2194.Cells in a Range on an Excel Sheet/README_EN.md @@ -54,9 +54,9 @@ The red arrow denotes the order in which the cells should be presented. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: ] ``` -### **Java** - ```java class Solution { public List cellsInRange(String s) { @@ -84,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +95,6 @@ public: }; ``` -### **Go** - ```go func cellsInRange(s string) []string { var ans []string @@ -113,16 +107,6 @@ func cellsInRange(s string) []string { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2195.Append K Integers With Minimal Sum/README.md b/solution/2100-2199/2195.Append K Integers With Minimal Sum/README.md index 74bc229b9f640..d52dcea4cee38 100644 --- a/solution/2100-2199/2195.Append K Integers With Minimal Sum/README.md +++ b/solution/2100-2199/2195.Append K Integers With Minimal Sum/README.md @@ -40,16 +40,10 @@ nums 最终元素和为 5 + 6 + 1 + 2 + 3 + 4 + 7 + 8 = 36 ,这是所有情况 ## 解法 - - -**方法一:排序 + 贪心 + 数学** +### 方法一:排序 + 贪心 + 数学 -### **Python3** - - - ```python class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: @@ -68,10 +62,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long minimalKSum(int[] nums, int k) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func minimalKSum(nums []int, k int) int64 { nums = append(nums, 0, 2e9) @@ -145,16 +131,6 @@ func minimalKSum(nums []int, k int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2195.Append K Integers With Minimal Sum/README_EN.md b/solution/2100-2199/2195.Append K Integers With Minimal Sum/README_EN.md index 3deca85c968f2..8bb204a022992 100644 --- a/solution/2100-2199/2195.Append K Integers With Minimal Sum/README_EN.md +++ b/solution/2100-2199/2195.Append K Integers With Minimal Sum/README_EN.md @@ -39,9 +39,9 @@ The sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long minimalKSum(int[] nums, int k) { @@ -90,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func minimalKSum(nums []int, k int) int64 { nums = append(nums, 0, 2e9) @@ -136,16 +130,6 @@ func minimalKSum(nums []int, k int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2196.Create Binary Tree From Descriptions/README.md b/solution/2100-2199/2196.Create Binary Tree From Descriptions/README.md index a126fdcde604e..6ece6a98776cd 100644 --- a/solution/2100-2199/2196.Create Binary Tree From Descriptions/README.md +++ b/solution/2100-2199/2196.Create Binary Tree From Descriptions/README.md @@ -54,14 +54,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -88,10 +84,6 @@ class Solution: return node ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -137,7 +129,77 @@ class Solution { } ``` -### **TypeScript** +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* createBinaryTree(vector>& descriptions) { + unordered_map m; + unordered_set vis; + for (auto& d : descriptions) { + int p = d[0], c = d[1], left = d[2]; + if (!m.count(p)) m[p] = new TreeNode(p); + if (!m.count(c)) m[c] = new TreeNode(c); + if (left) + m[p]->left = m[c]; + else + m[p]->right = m[c]; + vis.insert(c); + } + for (auto& [v, node] : m) { + if (!vis.count(v)) return node; + } + return nullptr; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func createBinaryTree(descriptions [][]int) *TreeNode { + m := make(map[int]*TreeNode) + vis := make(map[int]bool) + for _, d := range descriptions { + p, c, left := d[0], d[1], d[2] + if m[p] == nil { + m[p] = &TreeNode{Val: p} + } + if m[c] == nil { + m[c] = &TreeNode{Val: c} + } + if left == 1 { + m[p].Left = m[c] + } else { + m[p].Right = m[c] + } + vis[c] = true + } + + for v, node := range m { + if !vis[v] { + return node + } + } + return nil +} +``` ```ts /** @@ -186,8 +248,6 @@ function createBinaryTree(descriptions: number[][]): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -251,86 +311,6 @@ impl Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* createBinaryTree(vector>& descriptions) { - unordered_map m; - unordered_set vis; - for (auto& d : descriptions) { - int p = d[0], c = d[1], left = d[2]; - if (!m.count(p)) m[p] = new TreeNode(p); - if (!m.count(c)) m[c] = new TreeNode(c); - if (left) - m[p]->left = m[c]; - else - m[p]->right = m[c]; - vis.insert(c); - } - for (auto& [v, node] : m) { - if (!vis.count(v)) return node; - } - return nullptr; - } -}; -``` - -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func createBinaryTree(descriptions [][]int) *TreeNode { - m := make(map[int]*TreeNode) - vis := make(map[int]bool) - for _, d := range descriptions { - p, c, left := d[0], d[1], d[2] - if m[p] == nil { - m[p] = &TreeNode{Val: p} - } - if m[c] == nil { - m[c] = &TreeNode{Val: c} - } - if left == 1 { - m[p].Left = m[c] - } else { - m[p].Right = m[c] - } - vis[c] = true - } - - for v, node := range m { - if !vis[v] { - return node - } - } - return nil -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2196.Create Binary Tree From Descriptions/README_EN.md b/solution/2100-2199/2196.Create Binary Tree From Descriptions/README_EN.md index 54d88cc93dab7..4e55dbaec00d5 100644 --- a/solution/2100-2199/2196.Create Binary Tree From Descriptions/README_EN.md +++ b/solution/2100-2199/2196.Create Binary Tree From Descriptions/README_EN.md @@ -47,9 +47,9 @@ The resulting binary tree is shown in the diagram. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -77,8 +77,6 @@ class Solution: return node ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -124,7 +122,77 @@ class Solution { } ``` -### **TypeScript** +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* createBinaryTree(vector>& descriptions) { + unordered_map m; + unordered_set vis; + for (auto& d : descriptions) { + int p = d[0], c = d[1], left = d[2]; + if (!m.count(p)) m[p] = new TreeNode(p); + if (!m.count(c)) m[c] = new TreeNode(c); + if (left) + m[p]->left = m[c]; + else + m[p]->right = m[c]; + vis.insert(c); + } + for (auto& [v, node] : m) { + if (!vis.count(v)) return node; + } + return nullptr; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func createBinaryTree(descriptions [][]int) *TreeNode { + m := make(map[int]*TreeNode) + vis := make(map[int]bool) + for _, d := range descriptions { + p, c, left := d[0], d[1], d[2] + if m[p] == nil { + m[p] = &TreeNode{Val: p} + } + if m[c] == nil { + m[c] = &TreeNode{Val: c} + } + if left == 1 { + m[p].Left = m[c] + } else { + m[p].Right = m[c] + } + vis[c] = true + } + + for v, node := range m { + if !vis[v] { + return node + } + } + return nil +} +``` ```ts /** @@ -173,8 +241,6 @@ function createBinaryTree(descriptions: number[][]): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -238,86 +304,6 @@ impl Solution { } ``` -### **C++** - -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* createBinaryTree(vector>& descriptions) { - unordered_map m; - unordered_set vis; - for (auto& d : descriptions) { - int p = d[0], c = d[1], left = d[2]; - if (!m.count(p)) m[p] = new TreeNode(p); - if (!m.count(c)) m[c] = new TreeNode(c); - if (left) - m[p]->left = m[c]; - else - m[p]->right = m[c]; - vis.insert(c); - } - for (auto& [v, node] : m) { - if (!vis.count(v)) return node; - } - return nullptr; - } -}; -``` - -### **Go** - -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func createBinaryTree(descriptions [][]int) *TreeNode { - m := make(map[int]*TreeNode) - vis := make(map[int]bool) - for _, d := range descriptions { - p, c, left := d[0], d[1], d[2] - if m[p] == nil { - m[p] = &TreeNode{Val: p} - } - if m[c] == nil { - m[c] = &TreeNode{Val: c} - } - if left == 1 { - m[p].Left = m[c] - } else { - m[p].Right = m[c] - } - vis[c] = true - } - - for v, node := range m { - if !vis[v] { - return node - } - } - return nil -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2197.Replace Non-Coprime Numbers in Array/README.md b/solution/2100-2199/2197.Replace Non-Coprime Numbers in Array/README.md index 139fc07f18b88..3126d5f4a4b40 100644 --- a/solution/2100-2199/2197.Replace Non-Coprime Numbers in Array/README.md +++ b/solution/2100-2199/2197.Replace Non-Coprime Numbers in Array/README.md @@ -64,36 +64,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2100-2199/2197.Replace Non-Coprime Numbers in Array/README_EN.md b/solution/2100-2199/2197.Replace Non-Coprime Numbers in Array/README_EN.md index b57f0eb40fe2f..76900e122e11b 100644 --- a/solution/2100-2199/2197.Replace Non-Coprime Numbers in Array/README_EN.md +++ b/solution/2100-2199/2197.Replace Non-Coprime Numbers in Array/README_EN.md @@ -60,30 +60,4 @@ Note that there are other ways to obtain the same resultant array. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2100-2199/2198.Number of Single Divisor Triplets/README.md b/solution/2100-2199/2198.Number of Single Divisor Triplets/README.md index 7eaad5502d0cb..990af35292fea 100644 --- a/solution/2100-2199/2198.Number of Single Divisor Triplets/README.md +++ b/solution/2100-2199/2198.Number of Single Divisor Triplets/README.md @@ -56,14 +56,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def singleDivisorTriplet(self, nums: List[int]) -> int: @@ -88,10 +84,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long singleDivisorTriplet(int[] nums) { @@ -135,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +157,6 @@ public: }; ``` -### **Go** - ```go func singleDivisorTriplet(nums []int) int64 { counter := make([]int, 101) @@ -212,16 +200,6 @@ func singleDivisorTriplet(nums []int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2198.Number of Single Divisor Triplets/README_EN.md b/solution/2100-2199/2198.Number of Single Divisor Triplets/README_EN.md index 66e1f45d3167c..4434ab32ea9a1 100644 --- a/solution/2100-2199/2198.Number of Single Divisor Triplets/README_EN.md +++ b/solution/2100-2199/2198.Number of Single Divisor Triplets/README_EN.md @@ -51,9 +51,9 @@ Note that (0, 1, 2) is not a single divisor triplet because nums[0] + nums[1] + ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,8 +79,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long singleDivisorTriplet(int[] nums) { @@ -124,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +152,6 @@ public: }; ``` -### **Go** - ```go func singleDivisorTriplet(nums []int) int64 { counter := make([]int, 101) @@ -201,16 +195,6 @@ func singleDivisorTriplet(nums []int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2100-2199/2199.Finding the Topic of Each Post/README.md b/solution/2100-2199/2199.Finding the Topic of Each Post/README.md index de75ca3385be4..be7ac1a2c1faf 100644 --- a/solution/2100-2199/2199.Finding the Topic of Each Post/README.md +++ b/solution/2100-2199/2199.Finding the Topic of Each Post/README.md @@ -103,14 +103,10 @@ Posts 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -123,3 +119,5 @@ GROUP BY post_id; ``` + + diff --git a/solution/2100-2199/2199.Finding the Topic of Each Post/README_EN.md b/solution/2100-2199/2199.Finding the Topic of Each Post/README_EN.md index 86fb4ea585f2b..4c2c3720f667d 100644 --- a/solution/2100-2199/2199.Finding the Topic of Each Post/README_EN.md +++ b/solution/2100-2199/2199.Finding the Topic of Each Post/README_EN.md @@ -102,9 +102,9 @@ Note that it is okay to have one word that expresses more than one topic. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -118,3 +118,5 @@ GROUP BY post_id; ``` + + diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README.md b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README.md index 02bdee8d3cbe1..53d83e1e8ae53 100644 --- a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README.md +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README.md @@ -50,34 +50,14 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们在 $[0, n)$ 的范围内枚举下标 $i$,对于每个下标 $i$,我们在 $[0, n)$ 的范围内枚举下标 $j$,如果 $|i - j| \leq k$ 且 $nums[j] = key$,那么 $i$ 就是一个 K 近邻下标,我们将 $i$ 加入答案数组中,然后跳出内层循环,枚举下一个下标 $i$。 时间复杂度 $O(n^2)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 -**方法二:预处理 + 二分查找** - -我们可以预处理得到所有等于 $key$ 的元素的下标,记录在数组 $idx$ 中。数组 $idx$ 中的所有下标元素是按照升序排列的, - -接下来,我们枚举下标 $i$,对于每个下标 $i$,我们可以使用二分查找的方法在数组 $idx$ 中查找 $[i - k, i + k]$ 范围内的元素,如果存在元素,那么 $i$ 就是一个 K 近邻下标,我们将 $i$ 加入答案数组中。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。 - -**方法三:双指针** - -我们枚举下标 $i$,用一个指针 $j$ 指向满足 $j \geq i - k$ 且 $nums[j] = key$ 的最小下标,如果 $j$ 存在且 $j \leq i + k$,那么 $i$ 就是一个 K 近邻下标,我们将 $i$ 加入答案数组中。 - -时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: @@ -89,36 +69,6 @@ class Solution: return ans ``` -```python -class Solution: - def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: - idx = [i for i, x in enumerate(nums) if x == key] - ans = [] - for i in range(len(nums)): - l = bisect_left(idx, i - k) - r = bisect_right(idx, i + k) - 1 - if l <= r: - ans.append(i) - return ans -``` - -```python -class Solution: - def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: - ans = [] - j, n = 0, len(nums) - for i in range(n): - while j < i - k or (j < n and nums[j] != key): - j += 1 - if j < n and j <= (i + k): - ans.append(i) - return ans -``` - -### **Java** - - - ```java class Solution { public List findKDistantIndices(int[] nums, int key, int k) { @@ -137,6 +87,87 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector findKDistantIndices(vector& nums, int key, int k) { + int n = nums.size(); + vector ans; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (abs(i - j) <= k && nums[j] == key) { + ans.push_back(i); + break; + } + } + } + return ans; + } +}; +``` + +```go +func findKDistantIndices(nums []int, key int, k int) (ans []int) { + for i := range nums { + for j, x := range nums { + if abs(i-j) <= k && x == key { + ans = append(ans, i) + break + } + } + } + return ans +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} +``` + +```ts +function findKDistantIndices(nums: number[], key: number, k: number): number[] { + const n = nums.length; + const ans: number[] = []; + for (let i = 0; i < n; ++i) { + for (let j = 0; j < n; ++j) { + if (Math.abs(i - j) <= k && nums[j] === key) { + ans.push(i); + break; + } + } + } + return ans; +} +``` + + + +### 方法二:预处理 + 二分查找 + +我们可以预处理得到所有等于 $key$ 的元素的下标,记录在数组 $idx$ 中。数组 $idx$ 中的所有下标元素是按照升序排列的, + +接下来,我们枚举下标 $i$,对于每个下标 $i$,我们可以使用二分查找的方法在数组 $idx$ 中查找 $[i - k, i + k]$ 范围内的元素,如果存在元素,那么 $i$ 就是一个 K 近邻下标,我们将 $i$ 加入答案数组中。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $nums$ 的长度。 + + + +```python +class Solution: + def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: + idx = [i for i, x in enumerate(nums) if x == key] + ans = [] + for i in range(len(nums)): + l = bisect_left(idx, i - k) + r = bisect_right(idx, i + k) - 1 + if l <= r: + ans.append(i) + return ans +``` + ```java class Solution { public List findKDistantIndices(int[] nums, int key, int k) { @@ -161,45 +192,6 @@ class Solution { } ``` -```java -class Solution { - public List findKDistantIndices(int[] nums, int key, int k) { - int n = nums.length; - List ans = new ArrayList<>(); - for (int i = 0, j = 0; i < n; ++i) { - while (j < i - k || (j < n && nums[j] != key)) { - ++j; - } - if (j < n && j <= i + k) { - ans.add(i); - } - } - return ans; - } -} -``` - -### **C++** - -```cpp -class Solution { -public: - vector findKDistantIndices(vector& nums, int key, int k) { - int n = nums.size(); - vector ans; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (abs(i - j) <= k && nums[j] == key) { - ans.push_back(i); - break; - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -224,48 +216,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector findKDistantIndices(vector& nums, int key, int k) { - int n = nums.size(); - vector ans; - for (int i = 0, j = 0; i < n; ++i) { - while (j < i - k || (j < n && nums[j] != key)) { - ++j; - } - if (j < n && j <= i + k) { - ans.push_back(i); - } - } - return ans; - } -}; -``` - -### **Go** - -```go -func findKDistantIndices(nums []int, key int, k int) (ans []int) { - for i := range nums { - for j, x := range nums { - if abs(i-j) <= k && x == key { - ans = append(ans, i) - break - } - } - } - return ans -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x -} -``` - ```go func findKDistantIndices(nums []int, key int, k int) (ans []int) { idx := []int{} @@ -285,39 +235,6 @@ func findKDistantIndices(nums []int, key int, k int) (ans []int) { } ``` -```go -func findKDistantIndices(nums []int, key int, k int) (ans []int) { - n := len(nums) - for i, j := 0, 0; i < n; i++ { - for j < i-k || (j < n && nums[j] != key) { - j++ - } - if j < n && j <= i+k { - ans = append(ans, i) - } - } - return -} -``` - -### **TypeScript** - -```ts -function findKDistantIndices(nums: number[], key: number, k: number): number[] { - const n = nums.length; - const ans: number[] = []; - for (let i = 0; i < n; ++i) { - for (let j = 0; j < n; ++j) { - if (Math.abs(i - j) <= k && nums[j] === key) { - ans.push(i); - break; - } - } - } - return ans; -} -``` - ```ts function findKDistantIndices(nums: number[], key: number, k: number): number[] { const n = nums.length; @@ -351,6 +268,81 @@ function findKDistantIndices(nums: number[], key: number, k: number): number[] { } ``` + + +### 方法三:双指针 + +我们枚举下标 $i$,用一个指针 $j$ 指向满足 $j \geq i - k$ 且 $nums[j] = key$ 的最小下标,如果 $j$ 存在且 $j \leq i + k$,那么 $i$ 就是一个 K 近邻下标,我们将 $i$ 加入答案数组中。 + +时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: + ans = [] + j, n = 0, len(nums) + for i in range(n): + while j < i - k or (j < n and nums[j] != key): + j += 1 + if j < n and j <= (i + k): + ans.append(i) + return ans +``` + +```java +class Solution { + public List findKDistantIndices(int[] nums, int key, int k) { + int n = nums.length; + List ans = new ArrayList<>(); + for (int i = 0, j = 0; i < n; ++i) { + while (j < i - k || (j < n && nums[j] != key)) { + ++j; + } + if (j < n && j <= i + k) { + ans.add(i); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector findKDistantIndices(vector& nums, int key, int k) { + int n = nums.size(); + vector ans; + for (int i = 0, j = 0; i < n; ++i) { + while (j < i - k || (j < n && nums[j] != key)) { + ++j; + } + if (j < n && j <= i + k) { + ans.push_back(i); + } + } + return ans; + } +}; +``` + +```go +func findKDistantIndices(nums []int, key int, k int) (ans []int) { + n := len(nums) + for i, j := 0, 0; i < n; i++ { + for j < i-k || (j < n && nums[j] != key) { + j++ + } + if j < n && j <= i+k { + ans = append(ans, i) + } + } + return +} +``` + ```ts function findKDistantIndices(nums: number[], key: number, k: number): number[] { const n = nums.length; @@ -367,10 +359,6 @@ function findKDistantIndices(nums: number[], key: number, k: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README_EN.md b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README_EN.md index 65a8559481167..e5dda501ba856 100644 --- a/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README_EN.md +++ b/solution/2200-2299/2200.Find All K-Distant Indices in an Array/README_EN.md @@ -46,30 +46,14 @@ Hence, we return [0,1,2,3,4]. ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We enumerate the index $i$ in the range $[0, n)$, and for each index $i$, we enumerate the index $j$ in the range $[0, n)$. If $|i - j| \leq k$ and $nums[j] = key$, then $i$ is a K-nearest neighbor index. We add $i$ to the answer array, then break the inner loop and enumerate the next index $i$. The time complexity is $O(n^2)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. -**Solution 2: Preprocessing + Binary Search** - -We can preprocess to get the indices of all elements equal to $key$, recorded in the array $idx$. All index elements in the array $idx$ are sorted in ascending order. - -Next, we enumerate the index $i$. For each index $i$, we can use binary search to find elements in the range $[i - k, i + k]$ in the array $idx$. If there are elements, then $i$ is a K-nearest neighbor index. We add $i$ to the answer array. - -The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. - -**Solution 3: Two Pointers** - -We enumerate the index $i$, and use a pointer $j$ to point to the smallest index that satisfies $j \geq i - k$ and $nums[j] = key$. If $j$ exists and $j \leq i + k$, then $i$ is a K-nearest neighbor index. We add $i$ to the answer array. - -The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: @@ -81,34 +65,6 @@ class Solution: return ans ``` -```python -class Solution: - def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: - idx = [i for i, x in enumerate(nums) if x == key] - ans = [] - for i in range(len(nums)): - l = bisect_left(idx, i - k) - r = bisect_right(idx, i + k) - 1 - if l <= r: - ans.append(i) - return ans -``` - -```python -class Solution: - def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: - ans = [] - j, n = 0, len(nums) - for i in range(n): - while j < i - k or (j < n and nums[j] != key): - j += 1 - if j < n and j <= (i + k): - ans.append(i) - return ans -``` - -### **Java** - ```java class Solution { public List findKDistantIndices(int[] nums, int key, int k) { @@ -127,6 +83,87 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector findKDistantIndices(vector& nums, int key, int k) { + int n = nums.size(); + vector ans; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (abs(i - j) <= k && nums[j] == key) { + ans.push_back(i); + break; + } + } + } + return ans; + } +}; +``` + +```go +func findKDistantIndices(nums []int, key int, k int) (ans []int) { + for i := range nums { + for j, x := range nums { + if abs(i-j) <= k && x == key { + ans = append(ans, i) + break + } + } + } + return ans +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} +``` + +```ts +function findKDistantIndices(nums: number[], key: number, k: number): number[] { + const n = nums.length; + const ans: number[] = []; + for (let i = 0; i < n; ++i) { + for (let j = 0; j < n; ++j) { + if (Math.abs(i - j) <= k && nums[j] === key) { + ans.push(i); + break; + } + } + } + return ans; +} +``` + + + +### Solution 2: Preprocessing + Binary Search + +We can preprocess to get the indices of all elements equal to $key$, recorded in the array $idx$. All index elements in the array $idx$ are sorted in ascending order. + +Next, we enumerate the index $i$. For each index $i$, we can use binary search to find elements in the range $[i - k, i + k]$ in the array $idx$. If there are elements, then $i$ is a K-nearest neighbor index. We add $i$ to the answer array. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. + + + +```python +class Solution: + def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: + idx = [i for i, x in enumerate(nums) if x == key] + ans = [] + for i in range(len(nums)): + l = bisect_left(idx, i - k) + r = bisect_right(idx, i + k) - 1 + if l <= r: + ans.append(i) + return ans +``` + ```java class Solution { public List findKDistantIndices(int[] nums, int key, int k) { @@ -151,45 +188,6 @@ class Solution { } ``` -```java -class Solution { - public List findKDistantIndices(int[] nums, int key, int k) { - int n = nums.length; - List ans = new ArrayList<>(); - for (int i = 0, j = 0; i < n; ++i) { - while (j < i - k || (j < n && nums[j] != key)) { - ++j; - } - if (j < n && j <= i + k) { - ans.add(i); - } - } - return ans; - } -} -``` - -### **C++** - -```cpp -class Solution { -public: - vector findKDistantIndices(vector& nums, int key, int k) { - int n = nums.size(); - vector ans; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (abs(i - j) <= k && nums[j] == key) { - ans.push_back(i); - break; - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -214,48 +212,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector findKDistantIndices(vector& nums, int key, int k) { - int n = nums.size(); - vector ans; - for (int i = 0, j = 0; i < n; ++i) { - while (j < i - k || (j < n && nums[j] != key)) { - ++j; - } - if (j < n && j <= i + k) { - ans.push_back(i); - } - } - return ans; - } -}; -``` - -### **Go** - -```go -func findKDistantIndices(nums []int, key int, k int) (ans []int) { - for i := range nums { - for j, x := range nums { - if abs(i-j) <= k && x == key { - ans = append(ans, i) - break - } - } - } - return ans -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x -} -``` - ```go func findKDistantIndices(nums []int, key int, k int) (ans []int) { idx := []int{} @@ -275,39 +231,6 @@ func findKDistantIndices(nums []int, key int, k int) (ans []int) { } ``` -```go -func findKDistantIndices(nums []int, key int, k int) (ans []int) { - n := len(nums) - for i, j := 0, 0; i < n; i++ { - for j < i-k || (j < n && nums[j] != key) { - j++ - } - if j < n && j <= i+k { - ans = append(ans, i) - } - } - return -} -``` - -### **TypeScript** - -```ts -function findKDistantIndices(nums: number[], key: number, k: number): number[] { - const n = nums.length; - const ans: number[] = []; - for (let i = 0; i < n; ++i) { - for (let j = 0; j < n; ++j) { - if (Math.abs(i - j) <= k && nums[j] === key) { - ans.push(i); - break; - } - } - } - return ans; -} -``` - ```ts function findKDistantIndices(nums: number[], key: number, k: number): number[] { const n = nums.length; @@ -341,6 +264,81 @@ function findKDistantIndices(nums: number[], key: number, k: number): number[] { } ``` + + +### Solution 3: Two Pointers + +We enumerate the index $i$, and use a pointer $j$ to point to the smallest index that satisfies $j \geq i - k$ and $nums[j] = key$. If $j$ exists and $j \leq i + k$, then $i$ is a K-nearest neighbor index. We add $i$ to the answer array. + +The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. + + + +```python +class Solution: + def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]: + ans = [] + j, n = 0, len(nums) + for i in range(n): + while j < i - k or (j < n and nums[j] != key): + j += 1 + if j < n and j <= (i + k): + ans.append(i) + return ans +``` + +```java +class Solution { + public List findKDistantIndices(int[] nums, int key, int k) { + int n = nums.length; + List ans = new ArrayList<>(); + for (int i = 0, j = 0; i < n; ++i) { + while (j < i - k || (j < n && nums[j] != key)) { + ++j; + } + if (j < n && j <= i + k) { + ans.add(i); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector findKDistantIndices(vector& nums, int key, int k) { + int n = nums.size(); + vector ans; + for (int i = 0, j = 0; i < n; ++i) { + while (j < i - k || (j < n && nums[j] != key)) { + ++j; + } + if (j < n && j <= i + k) { + ans.push_back(i); + } + } + return ans; + } +}; +``` + +```go +func findKDistantIndices(nums []int, key int, k int) (ans []int) { + n := len(nums) + for i, j := 0, 0; i < n; i++ { + for j < i-k || (j < n && nums[j] != key) { + j++ + } + if j < n && j <= i+k { + ans = append(ans, i) + } + } + return +} +``` + ```ts function findKDistantIndices(nums: number[], key: number, k: number): number[] { const n = nums.length; @@ -357,10 +355,6 @@ function findKDistantIndices(nums: number[], key: number, k: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/README.md b/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/README.md index c7305f69796ea..4e4a772a3a89c 100644 --- a/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/README.md +++ b/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以用哈希表 $s$ 记录所有挖掘的单元格,然后遍历所有工件,判断工件的所有部分是否都在哈希表中,若是则可以提取该工件,答案加一。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def digArtifacts( @@ -93,10 +87,6 @@ class Solution: return sum(check(a) for a in artifacts) ``` -### **Java** - - - ```java class Solution { private Set s = new HashSet<>(); @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func digArtifacts(n int, artifacts [][]int, dig [][]int) (ans int) { s := map[int]bool{} @@ -184,8 +170,6 @@ func digArtifacts(n int, artifacts [][]int, dig [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function digArtifacts(n: number, artifacts: number[][], dig: number[][]): number { const s: Set = new Set(); @@ -211,8 +195,6 @@ function digArtifacts(n: number, artifacts: number[][], dig: number[][]): number } ``` -### **Rust** - ```rust use std::collections::HashSet; @@ -245,10 +227,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/README_EN.md b/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/README_EN.md index 462b61743b61e..0e2dd0a65a5f6 100644 --- a/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/README_EN.md +++ b/solution/2200-2299/2201.Count Artifacts That Can Be Extracted/README_EN.md @@ -62,7 +62,7 @@ Thus, we return 1. ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We can use a hash table $s$ to record all the excavated cells, then traverse all the workpieces, and check whether all parts of the workpiece are in the hash table. If so, we can extract the workpiece, and the answer is increased by one. @@ -70,8 +70,6 @@ The time complexity is $O(m + k)$, and the space complexity is $O(k)$. Here, $m$ -### **Python3** - ```python class Solution: def digArtifacts( @@ -87,8 +85,6 @@ class Solution: return sum(check(a) for a in artifacts) ``` -### **Java** - ```java class Solution { private Set s = new HashSet<>(); @@ -120,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +144,6 @@ public: }; ``` -### **Go** - ```go func digArtifacts(n int, artifacts [][]int, dig [][]int) (ans int) { s := map[int]bool{} @@ -176,8 +168,6 @@ func digArtifacts(n int, artifacts [][]int, dig [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function digArtifacts(n: number, artifacts: number[][], dig: number[][]): number { const s: Set = new Set(); @@ -203,8 +193,6 @@ function digArtifacts(n: number, artifacts: number[][], dig: number[][]): number } ``` -### **Rust** - ```rust use std::collections::HashSet; @@ -237,10 +225,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2202.Maximize the Topmost Element After K Moves/README.md b/solution/2200-2299/2202.Maximize the Topmost Element After K Moves/README.md index 6d2952f5db85f..10b3ccb7a53b9 100644 --- a/solution/2200-2299/2202.Maximize the Topmost Element After K Moves/README.md +++ b/solution/2200-2299/2202.Maximize the Topmost Element After K Moves/README.md @@ -56,14 +56,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maximumTop(self, nums: List[int], k: int) -> int: @@ -80,10 +76,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumTop(int[] nums, int k) { @@ -109,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +119,6 @@ public: }; ``` -### **Go** - ```go func maximumTop(nums []int, k int) int { if k == 0 { @@ -154,16 +142,6 @@ func maximumTop(nums []int, k int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2202.Maximize the Topmost Element After K Moves/README_EN.md b/solution/2200-2299/2202.Maximize the Topmost Element After K Moves/README_EN.md index 0ec4cec909d5c..6fca6d0884921 100644 --- a/solution/2200-2299/2202.Maximize the Topmost Element After K Moves/README_EN.md +++ b/solution/2200-2299/2202.Maximize the Topmost Element After K Moves/README_EN.md @@ -52,9 +52,9 @@ Since it is not possible to obtain a non-empty pile after one move, we return -1 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumTop(int[] nums, int k) { @@ -99,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +115,6 @@ public: }; ``` -### **Go** - ```go func maximumTop(nums []int, k int) int { if k == 0 { @@ -144,16 +138,6 @@ func maximumTop(nums []int, k int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2203.Minimum Weighted Subgraph With the Required Paths/README.md b/solution/2200-2299/2203.Minimum Weighted Subgraph With the Required Paths/README.md index f1f8e22c6f672..aaad24dc8e83e 100644 --- a/solution/2200-2299/2203.Minimum Weighted Subgraph With the Required Paths/README.md +++ b/solution/2200-2299/2203.Minimum Weighted Subgraph With the Required Paths/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:枚举三条最短路的交汇点** +### 方法一:枚举三条最短路的交汇点 最短路问题。 @@ -81,10 +79,6 @@ $A$, $B$ 两条路径一定存在着公共点 $p$,因为 $dest$ 一定是其 -### **Python3** - - - ```python class Solution: def minimumWeight( @@ -116,10 +110,6 @@ class Solution: return -1 if ans >= inf else ans ``` -### **Java** - - - ```java class Solution { private static final Long INF = Long.MAX_VALUE; @@ -182,16 +172,6 @@ class Solution { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2203.Minimum Weighted Subgraph With the Required Paths/README_EN.md b/solution/2200-2299/2203.Minimum Weighted Subgraph With the Required Paths/README_EN.md index ad9b6525e345b..5e19bc84eace3 100644 --- a/solution/2200-2299/2203.Minimum Weighted Subgraph With the Required Paths/README_EN.md +++ b/solution/2200-2299/2203.Minimum Weighted Subgraph With the Required Paths/README_EN.md @@ -51,9 +51,9 @@ It can be seen that there does not exist any path from node 1 to node 2, hence t ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -86,8 +86,6 @@ class Solution: return -1 if ans >= inf else ans ``` -### **Java** - ```java class Solution { private static final Long INF = Long.MAX_VALUE; @@ -150,16 +148,6 @@ class Solution { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/README.md b/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/README.md index 72242597cbaec..ac1ff8d73cfef 100644 --- a/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/README.md +++ b/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:拓扑排序** +### 方法一:拓扑排序 我们可以先将 $edges$ 中的边转换成邻接表 $g$,其中 $g[i]$ 表示节点 $i$ 的所有邻接节点,用集合表示。 @@ -87,10 +85,6 @@ -### **Python3** - - - ```python class Solution: def distanceToCycle(self, n: int, edges: List[List[int]]) -> List[int]: @@ -116,10 +110,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] distanceToCycle(int n, int[][] edges) { @@ -159,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -203,8 +191,6 @@ public: }; ``` -### **Go** - ```go func distanceToCycle(n int, edges [][]int) []int { g := make([]map[int]bool, n) @@ -246,8 +232,6 @@ func distanceToCycle(n int, edges [][]int) []int { } ``` -### **TypeScript** - ```ts function distanceToCycle(n: number, edges: number[][]): number[] { const g: Set[] = new Array(n).fill(0).map(() => new Set()); @@ -284,10 +268,6 @@ function distanceToCycle(n: number, edges: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/README_EN.md b/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/README_EN.md index 692491ea38914..5c7a8c2cb602e 100644 --- a/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/README_EN.md +++ b/solution/2200-2299/2204.Distance to a Cycle in Undirected Graph/README_EN.md @@ -63,7 +63,7 @@ The distance from 8 to 2 is 2. ## Solutions -**Solution 1: Topological Sorting** +### Solution 1: Topological Sorting We can first convert the edges in $edges$ into an adjacency list $g$, where $g[i]$ represents all adjacent nodes of node $i$, represented as a set. @@ -83,8 +83,6 @@ Similar problems: -### **Python3** - ```python class Solution: def distanceToCycle(self, n: int, edges: List[List[int]]) -> List[int]: @@ -110,8 +108,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] distanceToCycle(int n, int[][] edges) { @@ -151,8 +147,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -195,8 +189,6 @@ public: }; ``` -### **Go** - ```go func distanceToCycle(n int, edges [][]int) []int { g := make([]map[int]bool, n) @@ -238,8 +230,6 @@ func distanceToCycle(n int, edges [][]int) []int { } ``` -### **TypeScript** - ```ts function distanceToCycle(n: number, edges: number[][]): number[] { const g: Set[] = new Array(n).fill(0).map(() => new Set()); @@ -276,10 +266,6 @@ function distanceToCycle(n: number, edges: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2205.The Number of Users That Are Eligible for Discount/README.md b/solution/2200-2299/2205.The Number of Users That Are Eligible for Discount/README.md index bef87fdffe643..00b74f989ff61 100644 --- a/solution/2200-2299/2205.The Number of Users That Are Eligible for Discount/README.md +++ b/solution/2200-2299/2205.The Number of Users That Are Eligible for Discount/README.md @@ -58,18 +58,12 @@ startDate = 2022-03-08, endDate = 2022-03-20, minAmount = 1000 ## 解法 - - -**方法一:使用 count(distinct) 函数** +### 方法一:使用 count(distinct) 函数 注意需要判断的是单次购买金额是否大于等于 `minAmount`,而不是累计购买金额是否大于等于 `minAmount`。 -### **SQL** - - - ```sql CREATE FUNCTION getUserIDs(startDate DATE, endDate DATE, minAmount INT) RETURNS INT BEGIN @@ -82,3 +76,5 @@ END ``` + + diff --git a/solution/2200-2299/2205.The Number of Users That Are Eligible for Discount/README_EN.md b/solution/2200-2299/2205.The Number of Users That Are Eligible for Discount/README_EN.md index 1d7cee076c8d2..2828922c89fc2 100644 --- a/solution/2200-2299/2205.The Number of Users That Are Eligible for Discount/README_EN.md +++ b/solution/2200-2299/2205.The Number of Users That Are Eligible for Discount/README_EN.md @@ -56,9 +56,9 @@ Out of the three users, only User 3 is eligible for a discount. ## Solutions - +### Solution 1 -### **SQL** + ```sql CREATE FUNCTION getUserIDs(startDate DATE, endDate DATE, minAmount INT) RETURNS INT @@ -72,3 +72,5 @@ END ``` + + diff --git a/solution/2200-2299/2206.Divide Array Into Equal Pairs/README.md b/solution/2200-2299/2206.Divide Array Into Equal Pairs/README.md index 36f0f35d78d47..eb967b109440e 100644 --- a/solution/2200-2299/2206.Divide Array Into Equal Pairs/README.md +++ b/solution/2200-2299/2206.Divide Array Into Equal Pairs/README.md @@ -50,16 +50,10 @@ nums 可以划分成 (2, 2) ,(3, 3) 和 (2, 2) ,满足所有要求。 ## 解法 - - -首先统计数组里面每个数字出现的次数。因为题目要求的数对属于将两个相等的元素放在一起,所以换句话说就是看每个数字出现的次数是不是偶数次。 +### 方法一 -### **Python3** - - - ```python class Solution: def divideArray(self, nums: List[int]) -> bool: @@ -67,10 +61,6 @@ class Solution: return all(v % 2 == 0 for v in cnt.values()) ``` -### **Java** - - - ```java class Solution { public boolean divideArray(int[] nums) { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +92,6 @@ public: }; ``` -### **Go** - ```go func divideArray(nums []int) bool { cnt := make([]int, 510) @@ -121,16 +107,6 @@ func divideArray(nums []int) bool { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2206.Divide Array Into Equal Pairs/README_EN.md b/solution/2200-2299/2206.Divide Array Into Equal Pairs/README_EN.md index e952b5b5d1550..c76fff26f65a5 100644 --- a/solution/2200-2299/2206.Divide Array Into Equal Pairs/README_EN.md +++ b/solution/2200-2299/2206.Divide Array Into Equal Pairs/README_EN.md @@ -46,12 +46,10 @@ There is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy ## Solutions -The first step is to count the number of times each number appears in the array. Since the question asks for pairs of numbers that are part of putting two equal elements together, in other words to see if each number occurs an even number of times. +### Solution 1 -### **Python3** - ```python class Solution: def divideArray(self, nums: List[int]) -> bool: @@ -59,8 +57,6 @@ class Solution: return all(v % 2 == 0 for v in cnt.values()) ``` -### **Java** - ```java class Solution { public boolean divideArray(int[] nums) { @@ -78,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +88,6 @@ public: }; ``` -### **Go** - ```go func divideArray(nums []int) bool { cnt := make([]int, 510) @@ -111,16 +103,6 @@ func divideArray(nums []int) bool { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2207.Maximize Number of Subsequences in a String/README.md b/solution/2200-2299/2207.Maximize Number of Subsequences in a String/README.md index 29a4c9fdcef46..d280b20bb4042 100644 --- a/solution/2200-2299/2207.Maximize Number of Subsequences in a String/README.md +++ b/solution/2200-2299/2207.Maximize Number of Subsequences in a String/README.md @@ -49,14 +49,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maximumSubsequenceCount(self, text: str, pattern: str) -> int: @@ -70,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long maximumSubsequenceCount(String text, String pattern) { @@ -93,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +102,6 @@ public: }; ``` -### **Go** - ```go func maximumSubsequenceCount(text string, pattern string) int64 { ans := 0 @@ -131,16 +119,6 @@ func maximumSubsequenceCount(text string, pattern string) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2207.Maximize Number of Subsequences in a String/README_EN.md b/solution/2200-2299/2207.Maximize Number of Subsequences in a String/README_EN.md index 05fc79ffad61c..43bb9d1080640 100644 --- a/solution/2200-2299/2207.Maximize Number of Subsequences in a String/README_EN.md +++ b/solution/2200-2299/2207.Maximize Number of Subsequences in a String/README_EN.md @@ -45,9 +45,9 @@ Some of the strings which can be obtained from text and have 6 subsequences &quo ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long maximumSubsequenceCount(String text, String pattern) { @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +98,6 @@ public: }; ``` -### **Go** - ```go func maximumSubsequenceCount(text string, pattern string) int64 { ans := 0 @@ -121,16 +115,6 @@ func maximumSubsequenceCount(text string, pattern string) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/README.md b/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/README.md index 8f28dc0a598ff..f7516fddf176d 100644 --- a/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/README.md +++ b/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/README.md @@ -55,9 +55,7 @@ nums 的和减小了 31 - 14.5 = 16.5 ,减小的部分超过了初始数组和 ## 解法 - - -**方法一:贪心 + 优先队列(大根堆)** +### 方法一:贪心 + 优先队列(大根堆) 根据题目描述,每一次操作,都会将数组中的一个数减半。要使得数组和至少减少一半的操作次数最少,那么每一次操作都应该选择当前数组中的最大值进行减半。 @@ -67,10 +65,6 @@ nums 的和减小了 31 - 14.5 = 16.5 ,减小的部分超过了初始数组和 -### **Python3** - - - ```python class Solution: def halveArray(self, nums: List[int]) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int halveArray(int[] nums) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +127,6 @@ public: }; ``` -### **Go** - ```go func halveArray(nums []int) (ans int) { var s float64 @@ -171,6 +157,31 @@ func (h *hp) Pop() any { } ``` +```ts +function halveArray(nums: number[]): number { + let s: number = nums.reduce((a, b) => a + b) / 2; + const h = new MaxPriorityQueue(); + for (const v of nums) { + h.enqueue(v, v); + } + let ans: number = 0; + while (s > 0) { + let { element: t } = h.dequeue(); + t /= 2; + s -= t; + h.enqueue(t, t); + ans += 1; + } + return ans; +} +``` + + + +### 方法二 + + + ```go func halveArray(nums []int) (ans int) { half := 0 @@ -195,31 +206,6 @@ func (hp) Push(any) {} func (hp) Pop() (_ any) { return } ``` -### **TypeScript** - -```ts -function halveArray(nums: number[]): number { - let s: number = nums.reduce((a, b) => a + b) / 2; - const h = new MaxPriorityQueue(); - for (const v of nums) { - h.enqueue(v, v); - } - let ans: number = 0; - while (s > 0) { - let { element: t } = h.dequeue(); - t /= 2; - s -= t; - h.enqueue(t, t); - ans += 1; - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/README_EN.md b/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/README_EN.md index ac7716c1802a9..4f65aca0a5b3b 100644 --- a/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/README_EN.md +++ b/solution/2200-2299/2208.Minimum Operations to Halve Array Sum/README_EN.md @@ -51,9 +51,9 @@ It can be shown that we cannot reduce the sum by at least half in less than 3 op ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int halveArray(int[] nums) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +117,6 @@ public: }; ``` -### **Go** - ```go func halveArray(nums []int) (ans int) { var s float64 @@ -153,6 +147,31 @@ func (h *hp) Pop() any { } ``` +```ts +function halveArray(nums: number[]): number { + let s: number = nums.reduce((a, b) => a + b) / 2; + const h = new MaxPriorityQueue(); + for (const v of nums) { + h.enqueue(v, v); + } + let ans: number = 0; + while (s > 0) { + let { element: t } = h.dequeue(); + t /= 2; + s -= t; + h.enqueue(t, t); + ans += 1; + } + return ans; +} +``` + + + +### Solution 2 + + + ```go func halveArray(nums []int) (ans int) { half := 0 @@ -177,31 +196,6 @@ func (hp) Push(any) {} func (hp) Pop() (_ any) { return } ``` -### **TypeScript** - -```ts -function halveArray(nums: number[]): number { - let s: number = nums.reduce((a, b) => a + b) / 2; - const h = new MaxPriorityQueue(); - for (const v of nums) { - h.enqueue(v, v); - } - let ans: number = 0; - while (s > 0) { - let { element: t } = h.dequeue(); - t /= 2; - s -= t; - h.enqueue(t, t); - ans += 1; - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2209.Minimum White Tiles After Covering With Carpets/README.md b/solution/2200-2299/2209.Minimum White Tiles After Covering With Carpets/README.md index 8fa32d963b4a9..2004fe5a451fc 100644 --- a/solution/2200-2299/2209.Minimum White Tiles After Covering With Carpets/README.md +++ b/solution/2200-2299/2209.Minimum White Tiles After Covering With Carpets/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 设计函数 $dfs(i, j)$ 表示从下标 $i$ 开始,使用 $j$ 条地毯,最少有多少个白色砖块没有被覆盖。答案即为 $dfs(0, numCarpets)$。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int: @@ -98,10 +92,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[][] f; @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +158,6 @@ public: }; ``` -### **Go** - ```go func minimumWhiteTiles(floor string, numCarpets int, carpetLen int) int { n := len(floor) @@ -208,16 +194,6 @@ func minimumWhiteTiles(floor string, numCarpets int, carpetLen int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2209.Minimum White Tiles After Covering With Carpets/README_EN.md b/solution/2200-2299/2209.Minimum White Tiles After Covering With Carpets/README_EN.md index e50305b303133..85f8e07045c08 100644 --- a/solution/2200-2299/2209.Minimum White Tiles After Covering With Carpets/README_EN.md +++ b/solution/2200-2299/2209.Minimum White Tiles After Covering With Carpets/README_EN.md @@ -47,9 +47,9 @@ Note that the carpets are able to overlap one another. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[][] f; @@ -116,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +139,6 @@ public: }; ``` -### **Go** - ```go func minimumWhiteTiles(floor string, numCarpets int, carpetLen int) int { n := len(floor) @@ -181,16 +175,6 @@ func minimumWhiteTiles(floor string, numCarpets int, carpetLen int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2210.Count Hills and Valleys in an Array/README.md b/solution/2200-2299/2210.Count Hills and Valleys in an Array/README.md index 7e92a218c8f5b..2154e92835bca 100644 --- a/solution/2200-2299/2210.Count Hills and Valleys in an Array/README.md +++ b/solution/2200-2299/2210.Count Hills and Valleys in an Array/README.md @@ -54,36 +54,10 @@ ## 解法 - - -先处理数组 `nums`,对于相邻且重复出现的元素,只保留其中一个,如 `[6, 6, 5, 5, 4, 1]`,转换为 `[6, 5, 4, 1]`,再依照题意,进行统计。 - -优化: - -上述处理的数组方式,不论是删除元素还是新开数组,都会造成复杂度的提升。而实际上,只需要忽略相邻重复元素即可,无需改动原数组。 - -```txt -COUNT_HILL_VALLEY(A) - n = A.length - r = 0 - p = A[0] - for i = 1 in n - 1 - c = A[i] - q = A[i + 1] - if c == q - continue - if c > prev && c > q || c < prev && c < q - r += 1 - p = c - return r -``` +### 方法一 -### **Python3** - - - ```python class Solution: def countHillValley(self, nums: List[int]) -> int: @@ -97,25 +71,6 @@ class Solution: ) ``` -```python -class Solution: - def countHillValley(self, nums: List[int]) -> int: - ans = j = 0 - for i in range(1, len(nums) - 1): - if nums[i] == nums[i + 1]: - continue - if nums[i] > nums[j] and nums[i] > nums[i + 1]: - ans += 1 - if nums[i] < nums[j] and nums[i] < nums[i + 1]: - ans += 1 - j = i - return ans -``` - -### **Java** - - - ```java class Solution { public int countHillValley(int[] nums) { @@ -137,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +108,6 @@ public: }; ``` -### **Go** - ```go func countHillValley(nums []int) int { ans := 0 @@ -176,8 +127,6 @@ func countHillValley(nums []int) int { } ``` -### **TypeScript** - ```ts function countHillValley(nums: number[]): number { const n = nums.length; @@ -198,8 +147,6 @@ function countHillValley(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_hill_valley(nums: Vec) -> i32 { @@ -222,10 +169,27 @@ impl Solution { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def countHillValley(self, nums: List[int]) -> int: + ans = j = 0 + for i in range(1, len(nums) - 1): + if nums[i] == nums[i + 1]: + continue + if nums[i] > nums[j] and nums[i] > nums[i + 1]: + ans += 1 + if nums[i] < nums[j] and nums[i] < nums[i + 1]: + ans += 1 + j = i + return ans ``` + + diff --git a/solution/2200-2299/2210.Count Hills and Valleys in an Array/README_EN.md b/solution/2200-2299/2210.Count Hills and Valleys in an Array/README_EN.md index fc4f526b283b4..fd7b0cfa19102 100644 --- a/solution/2200-2299/2210.Count Hills and Valleys in an Array/README_EN.md +++ b/solution/2200-2299/2210.Count Hills and Valleys in an Array/README_EN.md @@ -51,11 +51,9 @@ There are 0 hills and valleys so we return 0. ## Solutions - - -### **Python3** +### Solution 1 -First make the consecutive duplicate value to be unique with the side values. + ```python class Solution: @@ -70,25 +68,6 @@ class Solution: ) ``` -```python -class Solution: - def countHillValley(self, nums: List[int]) -> int: - ans = j = 0 - for i in range(1, len(nums) - 1): - if nums[i] == nums[i + 1]: - continue - if nums[i] > nums[j] and nums[i] > nums[i + 1]: - ans += 1 - if nums[i] < nums[j] and nums[i] < nums[i + 1]: - ans += 1 - j = i - return ans -``` - -### **Java** - -Use two pointers to solve the problem - ```java class Solution { public int countHillValley(int[] nums) { @@ -110,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +105,6 @@ public: }; ``` -### **Go** - ```go func countHillValley(nums []int) int { ans := 0 @@ -149,8 +124,6 @@ func countHillValley(nums []int) int { } ``` -### **TypeScript** - ```ts function countHillValley(nums: number[]): number { const n = nums.length; @@ -171,8 +144,6 @@ function countHillValley(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_hill_valley(nums: Vec) -> i32 { @@ -195,10 +166,27 @@ impl Solution { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def countHillValley(self, nums: List[int]) -> int: + ans = j = 0 + for i in range(1, len(nums) - 1): + if nums[i] == nums[i + 1]: + continue + if nums[i] > nums[j] and nums[i] > nums[i + 1]: + ans += 1 + if nums[i] < nums[j] and nums[i] < nums[i + 1]: + ans += 1 + j = i + return ans ``` + + diff --git a/solution/2200-2299/2211.Count Collisions on a Road/README.md b/solution/2200-2299/2211.Count Collisions on a Road/README.md index 1f89bf81f1493..af6ac84effdc9 100644 --- a/solution/2200-2299/2211.Count Collisions on a Road/README.md +++ b/solution/2200-2299/2211.Count Collisions on a Road/README.md @@ -56,18 +56,10 @@ ## 解法 - - -- 去除前缀为 `L` 的字符; -- 去除后缀为 `R` 的字符; -- 剩余的字符串中,除了 `S` 以外的字符,都会贡献一次碰撞次数。 +### 方法一 -### **Python3** - - - ```python class Solution: def countCollisions(self, directions: str) -> int: @@ -75,10 +67,6 @@ class Solution: return len(d) - d.count('S') ``` -### **Java** - - - ```java class Solution { public int countCollisions(String directions) { @@ -103,31 +91,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function countCollisions(directions: string): number { - const n = directions.length; - let l = 0, - r = n - 1; - while (l < n && directions[l] == 'L') { - ++l; - } - while (r >= 0 && directions[r] == 'R') { - --r; - } - let ans = 0; - for (let i = l; i <= r; ++i) { - if (directions[i] != 'S') { - ++ans; - } - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -147,8 +110,6 @@ public: }; ``` -### **Go** - ```go func countCollisions(directions string) int { d := strings.TrimLeft(directions, "L") @@ -157,10 +118,27 @@ func countCollisions(directions string) int { } ``` -### **...** - -``` - +```ts +function countCollisions(directions: string): number { + const n = directions.length; + let l = 0, + r = n - 1; + while (l < n && directions[l] == 'L') { + ++l; + } + while (r >= 0 && directions[r] == 'R') { + --r; + } + let ans = 0; + for (let i = l; i <= r; ++i) { + if (directions[i] != 'S') { + ++ans; + } + } + return ans; +} ``` + + diff --git a/solution/2200-2299/2211.Count Collisions on a Road/README_EN.md b/solution/2200-2299/2211.Count Collisions on a Road/README_EN.md index 3291c344fff00..af5319ce52563 100644 --- a/solution/2200-2299/2211.Count Collisions on a Road/README_EN.md +++ b/solution/2200-2299/2211.Count Collisions on a Road/README_EN.md @@ -52,9 +52,9 @@ No cars will collide with each other. Thus, the total number of collisions that ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return len(d) - d.count('S') ``` -### **Java** - ```java class Solution { public int countCollisions(String directions) { @@ -89,31 +87,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function countCollisions(directions: string): number { - const n = directions.length; - let l = 0, - r = n - 1; - while (l < n && directions[l] == 'L') { - ++l; - } - while (r >= 0 && directions[r] == 'R') { - --r; - } - let ans = 0; - for (let i = l; i <= r; ++i) { - if (directions[i] != 'S') { - ++ans; - } - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -133,8 +106,6 @@ public: }; ``` -### **Go** - ```go func countCollisions(directions string) int { d := strings.TrimLeft(directions, "L") @@ -143,10 +114,27 @@ func countCollisions(directions string) int { } ``` -### **...** - -``` - +```ts +function countCollisions(directions: string): number { + const n = directions.length; + let l = 0, + r = n - 1; + while (l < n && directions[l] == 'L') { + ++l; + } + while (r >= 0 && directions[r] == 'R') { + --r; + } + let ans = 0; + for (let i = l; i <= r; ++i) { + if (directions[i] != 'S') { + ++ans; + } + } + return ans; +} ``` + + diff --git a/solution/2200-2299/2212.Maximum Points in an Archery Competition/README.md b/solution/2200-2299/2212.Maximum Points in an Archery Competition/README.md index 2351858679ca6..7c2b10fadb70e 100644 --- a/solution/2200-2299/2212.Maximum Points in an Archery Competition/README.md +++ b/solution/2200-2299/2212.Maximum Points in an Archery Competition/README.md @@ -70,18 +70,12 @@ Bob 获得总分 8 + 9 + 10 = 27 。 ## 解法 - - -**方法一:二进制枚举** +### 方法一:二进制枚举 枚举 bob 射箭的最终状态,寻找满足题意的、且使得 bob 得分最大的状态。 -### **Python3** - - - ```python class Solution: def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]: @@ -106,10 +100,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] maximumBobPoints(int numArrows, int[] aliceArrows) { @@ -142,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +164,6 @@ public: }; ``` -### **Go** - ```go func maximumBobPoints(numArrows int, aliceArrows []int) []int { n := len(aliceArrows) @@ -207,8 +193,6 @@ func maximumBobPoints(numArrows int, aliceArrows []int) []int { } ``` -### **TypeScript** - ```ts function maximumBobPoints(numArrows: number, aliceArrows: number[]): number[] { const dfs = (arr: number[], i: number, c: number): number[] => { @@ -233,8 +217,6 @@ function maximumBobPoints(numArrows: number, aliceArrows: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { fn dfs(alice_arrows: &Vec, mut res: Vec, count: i32, i: usize) -> Vec { @@ -270,10 +252,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2212.Maximum Points in an Archery Competition/README_EN.md b/solution/2200-2299/2212.Maximum Points in an Archery Competition/README_EN.md index 6e75ffc0de934..82f96a17bb8d4 100644 --- a/solution/2200-2299/2212.Maximum Points in an Archery Competition/README_EN.md +++ b/solution/2200-2299/2212.Maximum Points in an Archery Competition/README_EN.md @@ -62,9 +62,9 @@ It can be shown that Bob cannot obtain a score higher than 27 points. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -90,8 +90,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] maximumBobPoints(int numArrows, int[] aliceArrows) { @@ -124,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +154,6 @@ public: }; ``` -### **Go** - ```go func maximumBobPoints(numArrows int, aliceArrows []int) []int { n := len(aliceArrows) @@ -189,8 +183,6 @@ func maximumBobPoints(numArrows int, aliceArrows []int) []int { } ``` -### **TypeScript** - ```ts function maximumBobPoints(numArrows: number, aliceArrows: number[]): number[] { const dfs = (arr: number[], i: number, c: number): number[] => { @@ -215,8 +207,6 @@ function maximumBobPoints(numArrows: number, aliceArrows: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { fn dfs(alice_arrows: &Vec, mut res: Vec, count: i32, i: usize) -> Vec { @@ -252,10 +242,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2213.Longest Substring of One Repeating Character/README.md b/solution/2200-2299/2213.Longest Substring of One Repeating Character/README.md index c459420636cf7..1deef6e61e755 100644 --- a/solution/2200-2299/2213.Longest Substring of One Repeating Character/README.md +++ b/solution/2200-2299/2213.Longest Substring of One Repeating Character/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:线段树** +### 方法一:线段树 线段树将整个区间分割为多个不连续的子区间,子区间的数量不超过 `log(width)`。更新某个元素的值,只需要更新 `log(width)` 个区间,并且这些区间都包含在一个包含该元素的大区间内。区间修改时,需要使用**懒标记**保证效率。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Node: def __init__(self): @@ -167,10 +161,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Node { int l; @@ -289,8 +279,6 @@ class Solution { } ``` -### **C++** - ```cpp class Node { public: @@ -388,8 +376,6 @@ public: }; ``` -### **Go** - ```go type segmentTree struct { str []byte @@ -466,16 +452,6 @@ func longestRepeating(s string, queryCharacters string, queryIndices []int) []in } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2213.Longest Substring of One Repeating Character/README_EN.md b/solution/2200-2299/2213.Longest Substring of One Repeating Character/README_EN.md index e581f275ef650..a25738a719b16 100644 --- a/solution/2200-2299/2213.Longest Substring of One Repeating Character/README_EN.md +++ b/solution/2200-2299/2213.Longest Substring of One Repeating Character/README_EN.md @@ -49,12 +49,10 @@ Thus, we return [2,3]. ## Solutions -Segment Tree. +### Solution 1 -### **Python3** - ```python class Node: def __init__(self): @@ -146,8 +144,6 @@ class Solution: return ans ``` -### **Java** - ```java class Node { int l; @@ -266,8 +262,6 @@ class Solution { } ``` -### **C++** - ```cpp class Node { public: @@ -365,8 +359,6 @@ public: }; ``` -### **Go** - ```go type segmentTree struct { str []byte @@ -443,16 +435,6 @@ func longestRepeating(s string, queryCharacters string, queryIndices []int) []in } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2214.Minimum Health to Beat Game/README.md b/solution/2200-2299/2214.Minimum Health to Beat Game/README.md index 80bf93ee50afe..bf498296c975d 100644 --- a/solution/2200-2299/2214.Minimum Health to Beat Game/README.md +++ b/solution/2200-2299/2214.Minimum Health to Beat Game/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们可以贪心地选择在伤害值最大的回合中使用一次护甲技能,假设伤害值最大为 $mx$,那么我们可以免受 $min(mx, armor)$ 的伤害,因此我们需要的最小生命值为 $sum(damage) - min(mx, armor) + 1$。 @@ -76,20 +74,12 @@ -### **Python3** - - - ```python class Solution: def minimumHealth(self, damage: List[int], armor: int) -> int: return sum(damage) - min(max(damage), armor) + 1 ``` -### **Java** - - - ```java class Solution { public long minimumHealth(int[] damage, int armor) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func minimumHealth(damage []int, armor int) int64 { var s int64 @@ -135,8 +121,6 @@ func minimumHealth(damage []int, armor int) int64 { } ``` -### **TypeScript** - ```ts function minimumHealth(damage: number[], armor: number): number { let s = 0; @@ -149,10 +133,6 @@ function minimumHealth(damage: number[], armor: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2214.Minimum Health to Beat Game/README_EN.md b/solution/2200-2299/2214.Minimum Health to Beat Game/README_EN.md index f13dbba8f5298..3728add4125fd 100644 --- a/solution/2200-2299/2214.Minimum Health to Beat Game/README_EN.md +++ b/solution/2200-2299/2214.Minimum Health to Beat Game/README_EN.md @@ -63,9 +63,9 @@ Note that you did not use your armor ability. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return sum(damage) - min(max(damage), armor) + 1 ``` -### **Java** - ```java class Solution { public long minimumHealth(int[] damage, int armor) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +102,6 @@ public: }; ``` -### **Go** - ```go func minimumHealth(damage []int, armor int) int64 { var s int64 @@ -120,8 +114,6 @@ func minimumHealth(damage []int, armor int) int64 { } ``` -### **TypeScript** - ```ts function minimumHealth(damage: number[], armor: number): number { let s = 0; @@ -134,10 +126,6 @@ function minimumHealth(damage: number[], armor: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2215.Find the Difference of Two Arrays/README.md b/solution/2200-2299/2215.Find the Difference of Two Arrays/README.md index a72d65d137f89..3f408418f510a 100644 --- a/solution/2200-2299/2215.Find the Difference of Two Arrays/README.md +++ b/solution/2200-2299/2215.Find the Difference of Two Arrays/README.md @@ -47,14 +47,10 @@ nums2 中的每个整数都在 nums1 中出现,因此,answer[1] = [] 。 ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: @@ -62,10 +58,6 @@ class Solution: return [list(s1 - s2), list(s2 - s1)] ``` -### **Java** - - - ```java class Solution { public List> findDifference(int[] nums1, int[] nums2) { @@ -100,40 +92,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number[][]} - */ -var findDifference = function (nums1, nums2) { - let ans1 = new Set(nums1), - ans2 = new Set(nums2); - for (let num of nums1) { - ans2.delete(num); - } - for (let num of nums2) { - ans1.delete(num); - } - return [Array.from(ans1), Array.from(ans2)]; -}; -``` - -### **TypeScript** - -```ts -function findDifference(nums1: number[], nums2: number[]): number[][] { - return [ - [...new Set(nums1.filter(v => !nums2.includes(v)))], - [...new Set(nums2.filter(v => !nums1.includes(v)))], - ]; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -152,8 +110,6 @@ public: }; ``` -### **Go** - ```go func findDifference(nums1 []int, nums2 []int) [][]int { s1, s2 := make(map[int]bool), make(map[int]bool) @@ -178,7 +134,14 @@ func findDifference(nums1 []int, nums2 []int) [][]int { } ``` -### **Rust** +```ts +function findDifference(nums1: number[], nums2: number[]): number[][] { + return [ + [...new Set(nums1.filter(v => !nums2.includes(v)))], + [...new Set(nums2.filter(v => !nums1.includes(v)))], + ]; +} +``` ```rust use std::collections::HashSet; @@ -202,39 +165,25 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn find_difference(nums1: Vec, nums2: Vec) -> Vec> { - const N: usize = 2001; - let to_index = |i| (i as usize) + 1000; - - let mut is_in_nums1 = [false; N]; - let mut is_in_nums2 = [false; N]; - let mut res1 = vec![]; - let mut res2 = vec![]; - for &num in nums1.iter() { - is_in_nums1[to_index(num)] = true; - } - for &num in nums2.iter() { - is_in_nums2[to_index(num)] = true; - if !is_in_nums1[to_index(num)] { - res2.push(num); - is_in_nums1[to_index(num)] = true; - } - } - for &num in nums1.iter() { - if !is_in_nums2[to_index(num)] { - res1.push(num); - is_in_nums2[to_index(num)] = true; - } - } - vec![res1, res2] +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[][]} + */ +var findDifference = function (nums1, nums2) { + let ans1 = new Set(nums1), + ans2 = new Set(nums2); + for (let num of nums1) { + ans2.delete(num); } -} + for (let num of nums2) { + ans1.delete(num); + } + return [Array.from(ans1), Array.from(ans2)]; +}; ``` -### **PHP** - ```php class Solution { /** @@ -263,10 +212,43 @@ class Solution { } ``` -### **...** + -``` +### 方法二 + + +```rust +impl Solution { + pub fn find_difference(nums1: Vec, nums2: Vec) -> Vec> { + const N: usize = 2001; + let to_index = |i| (i as usize) + 1000; + + let mut is_in_nums1 = [false; N]; + let mut is_in_nums2 = [false; N]; + let mut res1 = vec![]; + let mut res2 = vec![]; + for &num in nums1.iter() { + is_in_nums1[to_index(num)] = true; + } + for &num in nums2.iter() { + is_in_nums2[to_index(num)] = true; + if !is_in_nums1[to_index(num)] { + res2.push(num); + is_in_nums1[to_index(num)] = true; + } + } + for &num in nums1.iter() { + if !is_in_nums2[to_index(num)] { + res1.push(num); + is_in_nums2[to_index(num)] = true; + } + } + vec![res1, res2] + } +} ``` + + diff --git a/solution/2200-2299/2215.Find the Difference of Two Arrays/README_EN.md b/solution/2200-2299/2215.Find the Difference of Two Arrays/README_EN.md index 4a936d05a7b02..7ec70554dd958 100644 --- a/solution/2200-2299/2215.Find the Difference of Two Arrays/README_EN.md +++ b/solution/2200-2299/2215.Find the Difference of Two Arrays/README_EN.md @@ -43,9 +43,9 @@ Every integer in nums2 is present in nums1. Therefore, answer[1] = []. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return [list(s1 - s2), list(s2 - s1)] ``` -### **Java** - ```java class Solution { public List> findDifference(int[] nums1, int[] nums2) { @@ -90,40 +88,6 @@ class Solution { } ``` -### **JavaScript** - -```js -/** - * @param {number[]} nums1 - * @param {number[]} nums2 - * @return {number[][]} - */ -var findDifference = function (nums1, nums2) { - let ans1 = new Set(nums1), - ans2 = new Set(nums2); - for (let num of nums1) { - ans2.delete(num); - } - for (let num of nums2) { - ans1.delete(num); - } - return [Array.from(ans1), Array.from(ans2)]; -}; -``` - -### **TypeScript** - -```ts -function findDifference(nums1: number[], nums2: number[]): number[][] { - return [ - [...new Set(nums1.filter(v => !nums2.includes(v)))], - [...new Set(nums2.filter(v => !nums1.includes(v)))], - ]; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -142,8 +106,6 @@ public: }; ``` -### **Go** - ```go func findDifference(nums1 []int, nums2 []int) [][]int { s1, s2 := make(map[int]bool), make(map[int]bool) @@ -168,7 +130,14 @@ func findDifference(nums1 []int, nums2 []int) [][]int { } ``` -### **Rust** +```ts +function findDifference(nums1: number[], nums2: number[]): number[][] { + return [ + [...new Set(nums1.filter(v => !nums2.includes(v)))], + [...new Set(nums2.filter(v => !nums1.includes(v)))], + ]; +} +``` ```rust use std::collections::HashSet; @@ -192,39 +161,25 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn find_difference(nums1: Vec, nums2: Vec) -> Vec> { - const N: usize = 2001; - let to_index = |i| (i as usize) + 1000; - - let mut is_in_nums1 = [false; N]; - let mut is_in_nums2 = [false; N]; - let mut res1 = vec![]; - let mut res2 = vec![]; - for &num in nums1.iter() { - is_in_nums1[to_index(num)] = true; - } - for &num in nums2.iter() { - is_in_nums2[to_index(num)] = true; - if !is_in_nums1[to_index(num)] { - res2.push(num); - is_in_nums1[to_index(num)] = true; - } - } - for &num in nums1.iter() { - if !is_in_nums2[to_index(num)] { - res1.push(num); - is_in_nums2[to_index(num)] = true; - } - } - vec![res1, res2] +```js +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * @return {number[][]} + */ +var findDifference = function (nums1, nums2) { + let ans1 = new Set(nums1), + ans2 = new Set(nums2); + for (let num of nums1) { + ans2.delete(num); } -} + for (let num of nums2) { + ans1.delete(num); + } + return [Array.from(ans1), Array.from(ans2)]; +}; ``` -### **PHP** - ```php class Solution { /** @@ -253,10 +208,43 @@ class Solution { } ``` -### **...** + -``` +### Solution 2 + + +```rust +impl Solution { + pub fn find_difference(nums1: Vec, nums2: Vec) -> Vec> { + const N: usize = 2001; + let to_index = |i| (i as usize) + 1000; + + let mut is_in_nums1 = [false; N]; + let mut is_in_nums2 = [false; N]; + let mut res1 = vec![]; + let mut res2 = vec![]; + for &num in nums1.iter() { + is_in_nums1[to_index(num)] = true; + } + for &num in nums2.iter() { + is_in_nums2[to_index(num)] = true; + if !is_in_nums1[to_index(num)] { + res2.push(num); + is_in_nums1[to_index(num)] = true; + } + } + for &num in nums1.iter() { + if !is_in_nums2[to_index(num)] { + res1.push(num); + is_in_nums2[to_index(num)] = true; + } + } + vec![res1, res2] + } +} ``` + + diff --git a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/README.md b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/README.md index dcc72856052d4..496a98adbcd4f 100644 --- a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/README.md +++ b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 根据题目描述,我们知道,一个美丽数组有偶数个元素,且如果我们把这个数组中每相邻两个元素划分为一组,那么每一组中的两个元素都不相等。这意味着,组内的元素不能重复,但组与组之间的元素可以重复。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def minDeletion(self, nums: List[int]) -> int: @@ -78,25 +72,6 @@ class Solution: return ans ``` -```python -class Solution: - def minDeletion(self, nums: List[int]) -> int: - n = len(nums) - ans = i = 0 - while i < n: - j = i + 1 - while j < n and nums[j] == nums[i]: - j += 1 - ans += 1 - i = j + 1 - ans += (n - ans) % 2 - return ans -``` - -### **Java** - - - ```java class Solution { public int minDeletion(int[] nums) { @@ -115,44 +90,114 @@ class Solution { } ``` -```java +```cpp class Solution { - public int minDeletion(int[] nums) { - int n = nums.length; +public: + int minDeletion(vector& nums) { + int n = nums.size(); int ans = 0; - for (int i = 0; i < n;) { - int j = i + 1; - while (j < n && nums[j] == nums[i]) { - ++j; + for (int i = 0; i < n - 1; ++i) { + if (nums[i] == nums[i + 1]) { ++ans; + } else { + ++i; } - i = j + 1; } ans += (n - ans) % 2; return ans; } +}; +``` + +```go +func minDeletion(nums []int) (ans int) { + n := len(nums) + for i := 0; i < n-1; i++ { + if nums[i] == nums[i+1] { + ans++ + } else { + i++ + } + } + ans += (n - ans) % 2 + return +} +``` + +```ts +function minDeletion(nums: number[]): number { + const n = nums.length; + let ans = 0; + for (let i = 0; i < n - 1; ++i) { + if (nums[i] === nums[i + 1]) { + ++ans; + } else { + ++i; + } + } + ans += (n - ans) % 2; + return ans; +} +``` + +```rust +impl Solution { + pub fn min_deletion(nums: Vec) -> i32 { + let n = nums.len(); + let mut ans = 0; + let mut i = 0; + while i < n - 1 { + if nums[i] == nums[i + 1] { + ans += 1; + i += 1; + } else { + i += 2; + } + } + ans += (n - ans) % 2; + ans as i32 + } } ``` -### **C++** + -```cpp +### 方法二 + + + +```python +class Solution: + def minDeletion(self, nums: List[int]) -> int: + n = len(nums) + ans = i = 0 + while i < n: + j = i + 1 + while j < n and nums[j] == nums[i]: + j += 1 + ans += 1 + i = j + 1 + ans += (n - ans) % 2 + return ans +``` + +```java class Solution { -public: - int minDeletion(vector& nums) { - int n = nums.size(); + public int minDeletion(int[] nums) { + int n = nums.length; int ans = 0; - for (int i = 0; i < n - 1; ++i) { - if (nums[i] == nums[i + 1]) { + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[j] == nums[i]) { + ++j; ++ans; - } else { - ++i; } + i = j + 1; } ans += (n - ans) % 2; return ans; } -}; +} ``` ```cpp @@ -175,23 +220,6 @@ public: }; ``` -### **Go** - -```go -func minDeletion(nums []int) (ans int) { - n := len(nums) - for i := 0; i < n-1; i++ { - if nums[i] == nums[i+1] { - ans++ - } else { - i++ - } - } - ans += (n - ans) % 2 - return -} -``` - ```go func minDeletion(nums []int) (ans int) { n := len(nums) @@ -207,24 +235,6 @@ func minDeletion(nums []int) (ans int) { } ``` -### **TypeScript** - -```ts -function minDeletion(nums: number[]): number { - const n = nums.length; - let ans = 0; - for (let i = 0; i < n - 1; ++i) { - if (nums[i] === nums[i + 1]) { - ++ans; - } else { - ++i; - } - } - ans += (n - ans) % 2; - return ans; -} -``` - ```ts function minDeletion(nums: number[]): number { const n = nums.length; @@ -241,28 +251,6 @@ function minDeletion(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn min_deletion(nums: Vec) -> i32 { - let n = nums.len(); - let mut ans = 0; - let mut i = 0; - while i < n - 1 { - if nums[i] == nums[i + 1] { - ans += 1; - i += 1; - } else { - i += 2; - } - } - ans += (n - ans) % 2; - ans as i32 - } -} -``` - ```rust impl Solution { pub fn min_deletion(nums: Vec) -> i32 { @@ -283,10 +271,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/README_EN.md b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/README_EN.md index 75cd53558c621..15e3b617a25db 100644 --- a/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/README_EN.md +++ b/solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy According to the problem description, we know that a beautiful array has an even number of elements, and if we divide every two adjacent elements in this array into a group, then the two elements in each group are not equal. This means that the elements within a group cannot be repeated, but the elements between groups can be repeated. @@ -56,8 +56,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. We only nee -### **Python3** - ```python class Solution: def minDeletion(self, nums: List[int]) -> int: @@ -73,23 +71,6 @@ class Solution: return ans ``` -```python -class Solution: - def minDeletion(self, nums: List[int]) -> int: - n = len(nums) - ans = i = 0 - while i < n: - j = i + 1 - while j < n and nums[j] == nums[i]: - j += 1 - ans += 1 - i = j + 1 - ans += (n - ans) % 2 - return ans -``` - -### **Java** - ```java class Solution { public int minDeletion(int[] nums) { @@ -108,44 +89,114 @@ class Solution { } ``` -```java +```cpp class Solution { - public int minDeletion(int[] nums) { - int n = nums.length; +public: + int minDeletion(vector& nums) { + int n = nums.size(); int ans = 0; - for (int i = 0; i < n;) { - int j = i + 1; - while (j < n && nums[j] == nums[i]) { - ++j; + for (int i = 0; i < n - 1; ++i) { + if (nums[i] == nums[i + 1]) { ++ans; + } else { + ++i; } - i = j + 1; } ans += (n - ans) % 2; return ans; } +}; +``` + +```go +func minDeletion(nums []int) (ans int) { + n := len(nums) + for i := 0; i < n-1; i++ { + if nums[i] == nums[i+1] { + ans++ + } else { + i++ + } + } + ans += (n - ans) % 2 + return } ``` -### **C++** +```ts +function minDeletion(nums: number[]): number { + const n = nums.length; + let ans = 0; + for (let i = 0; i < n - 1; ++i) { + if (nums[i] === nums[i + 1]) { + ++ans; + } else { + ++i; + } + } + ans += (n - ans) % 2; + return ans; +} +``` -```cpp +```rust +impl Solution { + pub fn min_deletion(nums: Vec) -> i32 { + let n = nums.len(); + let mut ans = 0; + let mut i = 0; + while i < n - 1 { + if nums[i] == nums[i + 1] { + ans += 1; + i += 1; + } else { + i += 2; + } + } + ans += (n - ans) % 2; + ans as i32 + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minDeletion(self, nums: List[int]) -> int: + n = len(nums) + ans = i = 0 + while i < n: + j = i + 1 + while j < n and nums[j] == nums[i]: + j += 1 + ans += 1 + i = j + 1 + ans += (n - ans) % 2 + return ans +``` + +```java class Solution { -public: - int minDeletion(vector& nums) { - int n = nums.size(); + public int minDeletion(int[] nums) { + int n = nums.length; int ans = 0; - for (int i = 0; i < n - 1; ++i) { - if (nums[i] == nums[i + 1]) { + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[j] == nums[i]) { + ++j; ++ans; - } else { - ++i; } + i = j + 1; } ans += (n - ans) % 2; return ans; } -}; +} ``` ```cpp @@ -168,23 +219,6 @@ public: }; ``` -### **Go** - -```go -func minDeletion(nums []int) (ans int) { - n := len(nums) - for i := 0; i < n-1; i++ { - if nums[i] == nums[i+1] { - ans++ - } else { - i++ - } - } - ans += (n - ans) % 2 - return -} -``` - ```go func minDeletion(nums []int) (ans int) { n := len(nums) @@ -200,24 +234,6 @@ func minDeletion(nums []int) (ans int) { } ``` -### **TypeScript** - -```ts -function minDeletion(nums: number[]): number { - const n = nums.length; - let ans = 0; - for (let i = 0; i < n - 1; ++i) { - if (nums[i] === nums[i + 1]) { - ++ans; - } else { - ++i; - } - } - ans += (n - ans) % 2; - return ans; -} -``` - ```ts function minDeletion(nums: number[]): number { const n = nums.length; @@ -234,28 +250,6 @@ function minDeletion(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn min_deletion(nums: Vec) -> i32 { - let n = nums.len(); - let mut ans = 0; - let mut i = 0; - while i < n - 1 { - if nums[i] == nums[i + 1] { - ans += 1; - i += 1; - } else { - i += 2; - } - } - ans += (n - ans) % 2; - ans as i32 - } -} -``` - ```rust impl Solution { pub fn min_deletion(nums: Vec) -> i32 { @@ -276,10 +270,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2217.Find Palindrome With Fixed Length/README.md b/solution/2200-2299/2217.Find Palindrome With Fixed Length/README.md index b24cc76171660..f58eba9ce8a55 100644 --- a/solution/2200-2299/2217.Find Palindrome With Fixed Length/README.md +++ b/solution/2200-2299/2217.Find Palindrome With Fixed Length/README.md @@ -45,14 +45,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]: @@ -70,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long[] kthPalindrome(int[] queries, int intLength) { @@ -97,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +113,6 @@ public: }; ``` -### **Go** - ```go func kthPalindrome(queries []int, intLength int) []int64 { l := (intLength + 1) >> 1 @@ -150,8 +138,6 @@ func kthPalindrome(queries []int, intLength int) []int64 { } ``` -### **TypeScript** - ```ts function kthPalindrome(queries: number[], intLength: number): number[] { const isOdd = intLength % 2 === 1; @@ -174,8 +160,6 @@ function kthPalindrome(queries: number[], intLength: number): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn kth_palindrome(queries: Vec, int_length: i32) -> Vec { @@ -207,10 +191,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2217.Find Palindrome With Fixed Length/README_EN.md b/solution/2200-2299/2217.Find Palindrome With Fixed Length/README_EN.md index 4aba69b6642cb..c05ecd1c009c3 100644 --- a/solution/2200-2299/2217.Find Palindrome With Fixed Length/README_EN.md +++ b/solution/2200-2299/2217.Find Palindrome With Fixed Length/README_EN.md @@ -41,9 +41,9 @@ The first six palindromes of length 4 are: ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long[] kthPalindrome(int[] queries, int intLength) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func kthPalindrome(queries []int, intLength int) []int64 { l := (intLength + 1) >> 1 @@ -140,8 +134,6 @@ func kthPalindrome(queries []int, intLength int) []int64 { } ``` -### **TypeScript** - ```ts function kthPalindrome(queries: number[], intLength: number): number[] { const isOdd = intLength % 2 === 1; @@ -164,8 +156,6 @@ function kthPalindrome(queries: number[], intLength: number): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn kth_palindrome(queries: Vec, int_length: i32) -> Vec { @@ -197,10 +187,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2218.Maximum Value of K Coins From Piles/README.md b/solution/2200-2299/2218.Maximum Value of K Coins From Piles/README.md index 0ac98b448591f..597ea2b121bbe 100644 --- a/solution/2200-2299/2218.Maximum Value of K Coins From Piles/README.md +++ b/solution/2200-2299/2218.Maximum Value of K Coins From Piles/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 对每个栈求前缀和 $s$,$s_i$ 视为一个体积为 $i$ 且价值为 $s_i$ 的物品。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int: @@ -80,23 +74,6 @@ class Solution: return dp[-1][-1] ``` -```python -class Solution: - def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int: - presum = [list(accumulate(p, initial=0)) for p in piles] - dp = [0] * (k + 1) - for s in presum: - for j in range(k, -1, -1): - for idx, v in enumerate(s): - if j >= idx: - dp[j] = max(dp[j], dp[j - idx] + v) - return dp[-1] -``` - -### **Java** - - - ```java class Solution { public int maxValueOfCoins(List> piles, int k) { @@ -125,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +126,6 @@ public: }; ``` -### **Go** - ```go func maxValueOfCoins(piles [][]int, k int) int { var presum [][]int @@ -178,16 +151,25 @@ func maxValueOfCoins(piles [][]int, k int) int { } ``` -### **TypeScript** - -```ts - -``` + -### **...** +### 方法二 -``` + +```python +class Solution: + def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int: + presum = [list(accumulate(p, initial=0)) for p in piles] + dp = [0] * (k + 1) + for s in presum: + for j in range(k, -1, -1): + for idx, v in enumerate(s): + if j >= idx: + dp[j] = max(dp[j], dp[j - idx] + v) + return dp[-1] ``` + + diff --git a/solution/2200-2299/2218.Maximum Value of K Coins From Piles/README_EN.md b/solution/2200-2299/2218.Maximum Value of K Coins From Piles/README_EN.md index 8423969d28cbe..9a471fa9d0400 100644 --- a/solution/2200-2299/2218.Maximum Value of K Coins From Piles/README_EN.md +++ b/solution/2200-2299/2218.Maximum Value of K Coins From Piles/README_EN.md @@ -42,9 +42,9 @@ The maximum total we can obtain is 101. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,21 +60,6 @@ class Solution: return dp[-1][-1] ``` -```python -class Solution: - def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int: - presum = [list(accumulate(p, initial=0)) for p in piles] - dp = [0] * (k + 1) - for s in presum: - for j in range(k, -1, -1): - for idx, v in enumerate(s): - if j >= idx: - dp[j] = max(dp[j], dp[j - idx] + v) - return dp[-1] -``` - -### **Java** - ```java class Solution { public int maxValueOfCoins(List> piles, int k) { @@ -103,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +112,6 @@ public: }; ``` -### **Go** - ```go func maxValueOfCoins(piles [][]int, k int) int { var presum [][]int @@ -156,16 +137,25 @@ func maxValueOfCoins(piles [][]int, k int) int { } ``` -### **TypeScript** - -```ts - -``` + -### **...** +### Solution 2 -``` + +```python +class Solution: + def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int: + presum = [list(accumulate(p, initial=0)) for p in piles] + dp = [0] * (k + 1) + for s in presum: + for j in range(k, -1, -1): + for idx, v in enumerate(s): + if j >= idx: + dp[j] = max(dp[j], dp[j - idx] + v) + return dp[-1] ``` + + diff --git a/solution/2200-2299/2219.Maximum Sum Score of Array/README.md b/solution/2200-2299/2219.Maximum Sum Score of Array/README.md index 882a123538fd0..1169df8580749 100644 --- a/solution/2200-2299/2219.Maximum Sum Score of Array/README.md +++ b/solution/2200-2299/2219.Maximum Sum Score of Array/README.md @@ -55,16 +55,10 @@ nums 可取得的最大总分是 -3 。 ## 解法 - - -前缀和。 +### 方法一 -### **Python3** - - - ```python class Solution: def maximumSumScore(self, nums: List[int]) -> int: @@ -72,10 +66,6 @@ class Solution: return max(max(s[i + 1], s[-1] - s[i]) for i in range(len(nums))) ``` -### **Java** - - - ```java class Solution { public long maximumSumScore(int[] nums) { @@ -93,25 +83,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function maximumSumScore(nums: number[]): number { - const n = nums.length; - let s = new Array(n + 1).fill(0); - for (let i = 0; i < n; ++i) { - s[i + 1] = s[i] + nums[i]; - } - let ans = -Infinity; - for (let i = 0; i < n; ++i) { - ans = Math.max(ans, Math.max(s[i + 1], s[n] - s[i])); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -126,8 +97,6 @@ public: }; ``` -### **Go** - ```go func maximumSumScore(nums []int) int64 { n := len(nums) @@ -143,7 +112,20 @@ func maximumSumScore(nums []int) int64 { } ``` -### **JavaScript** +```ts +function maximumSumScore(nums: number[]): number { + const n = nums.length; + let s = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + let ans = -Infinity; + for (let i = 0; i < n; ++i) { + ans = Math.max(ans, Math.max(s[i + 1], s[n] - s[i])); + } + return ans; +} +``` ```js /** @@ -164,10 +146,6 @@ var maximumSumScore = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2219.Maximum Sum Score of Array/README_EN.md b/solution/2200-2299/2219.Maximum Sum Score of Array/README_EN.md index 87529c9595dc8..aced1473f815c 100644 --- a/solution/2200-2299/2219.Maximum Sum Score of Array/README_EN.md +++ b/solution/2200-2299/2219.Maximum Sum Score of Array/README_EN.md @@ -51,9 +51,9 @@ The maximum sum score of nums is -3. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return max(max(s[i + 1], s[-1] - s[i]) for i in range(len(nums))) ``` -### **Java** - ```java class Solution { public long maximumSumScore(int[] nums) { @@ -81,25 +79,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function maximumSumScore(nums: number[]): number { - const n = nums.length; - let s = new Array(n + 1).fill(0); - for (let i = 0; i < n; ++i) { - s[i + 1] = s[i] + nums[i]; - } - let ans = -Infinity; - for (let i = 0; i < n; ++i) { - ans = Math.max(ans, Math.max(s[i + 1], s[n] - s[i])); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -114,8 +93,6 @@ public: }; ``` -### **Go** - ```go func maximumSumScore(nums []int) int64 { n := len(nums) @@ -131,7 +108,20 @@ func maximumSumScore(nums []int) int64 { } ``` -### **JavaScript** +```ts +function maximumSumScore(nums: number[]): number { + const n = nums.length; + let s = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + let ans = -Infinity; + for (let i = 0; i < n; ++i) { + ans = Math.max(ans, Math.max(s[i + 1], s[n] - s[i])); + } + return ans; +} +``` ```js /** @@ -152,10 +142,6 @@ var maximumSumScore = function (nums) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/README.md b/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/README.md index 747486ca81c7a..0519ea454131d 100644 --- a/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/README.md +++ b/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/README.md @@ -49,14 +49,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minBitFlips(self, start: int, goal: int) -> int: @@ -68,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minBitFlips(int start, int goal) { @@ -86,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +93,6 @@ public: }; ``` -### **Go** - ```go func minBitFlips(start int, goal int) int { t := start ^ goal @@ -117,8 +105,6 @@ func minBitFlips(start int, goal int) int { } ``` -### **TypeScript** - ```ts function minBitFlips(start: number, goal: number): number { let tmp = start ^ goal; @@ -131,8 +117,6 @@ function minBitFlips(start: number, goal: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_bit_flips(start: i32, goal: i32) -> i32 { @@ -147,8 +131,6 @@ impl Solution { } ``` -### **C** - ```c int minBitFlips(int start, int goal) { int tmp = start ^ goal; @@ -161,10 +143,6 @@ int minBitFlips(int start, int goal) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/README_EN.md b/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/README_EN.md index 7f0feeb38122b..8b27b9ad25b01 100644 --- a/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/README_EN.md +++ b/solution/2200-2299/2220.Minimum Bit Flips to Convert Number/README_EN.md @@ -45,9 +45,9 @@ It can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minBitFlips(int start, int goal) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +89,6 @@ public: }; ``` -### **Go** - ```go func minBitFlips(start int, goal int) int { t := start ^ goal @@ -107,8 +101,6 @@ func minBitFlips(start int, goal int) int { } ``` -### **TypeScript** - ```ts function minBitFlips(start: number, goal: number): number { let tmp = start ^ goal; @@ -121,8 +113,6 @@ function minBitFlips(start: number, goal: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_bit_flips(start: i32, goal: i32) -> i32 { @@ -137,8 +127,6 @@ impl Solution { } ``` -### **C** - ```c int minBitFlips(int start, int goal) { int tmp = start ^ goal; @@ -151,10 +139,6 @@ int minBitFlips(int start, int goal) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2221.Find Triangular Sum of an Array/README.md b/solution/2200-2299/2221.Find Triangular Sum of an Array/README.md index 52c015f766674..fb1d139167fa5 100644 --- a/solution/2200-2299/2221.Find Triangular Sum of an Array/README.md +++ b/solution/2200-2299/2221.Find Triangular Sum of an Array/README.md @@ -50,14 +50,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def triangularSum(self, nums: List[int]) -> int: @@ -68,10 +64,6 @@ class Solution: return nums[0] ``` -### **Java** - - - ```java class Solution { public int triangularSum(int[] nums) { @@ -86,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +91,6 @@ public: }; ``` -### **Go** - ```go func triangularSum(nums []int) int { n := len(nums) @@ -115,16 +103,6 @@ func triangularSum(nums []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2221.Find Triangular Sum of an Array/README_EN.md b/solution/2200-2299/2221.Find Triangular Sum of an Array/README_EN.md index 09775e1cf735d..ba7a3b3779ba7 100644 --- a/solution/2200-2299/2221.Find Triangular Sum of an Array/README_EN.md +++ b/solution/2200-2299/2221.Find Triangular Sum of an Array/README_EN.md @@ -44,9 +44,9 @@ Since there is only one element in nums, the triangular sum is the value of that ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return nums[0] ``` -### **Java** - ```java class Solution { public int triangularSum(int[] nums) { @@ -74,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,8 +85,6 @@ public: }; ``` -### **Go** - ```go func triangularSum(nums []int) int { n := len(nums) @@ -103,16 +97,6 @@ func triangularSum(nums []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2222.Number of Ways to Select Buildings/README.md b/solution/2200-2299/2222.Number of Ways to Select Buildings/README.md index 8386e5b049bba..e7011de6bd490 100644 --- a/solution/2200-2299/2222.Number of Ways to Select Buildings/README.md +++ b/solution/2200-2299/2222.Number of Ways to Select Buildings/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:统计 010 和 101 的出现次数** +### 方法一:统计 010 和 101 的出现次数 有效方案只有两种情况:$010$ 和 $101$。枚举中间数字,累计方案数。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def numberOfWays(self, s: str) -> int: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long numberOfWays(String s) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go func numberOfWays(s string) int64 { n := len(s) @@ -167,16 +153,6 @@ func numberOfWays(s string) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2222.Number of Ways to Select Buildings/README_EN.md b/solution/2200-2299/2222.Number of Ways to Select Buildings/README_EN.md index 5bc8845fd4591..cd4e44ad6718f 100644 --- a/solution/2200-2299/2222.Number of Ways to Select Buildings/README_EN.md +++ b/solution/2200-2299/2222.Number of Ways to Select Buildings/README_EN.md @@ -54,9 +54,9 @@ No other selection is valid. Thus, there are 6 total ways. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long numberOfWays(String s) { @@ -105,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +127,6 @@ public: }; ``` -### **Go** - ```go func numberOfWays(s string) int64 { n := len(s) @@ -153,16 +147,6 @@ func numberOfWays(s string) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2223.Sum of Scores of Built Strings/README.md b/solution/2200-2299/2223.Sum of Scores of Built Strings/README.md index 6b45f49e2a6d8..4f139d9124d89 100644 --- a/solution/2200-2299/2223.Sum of Scores of Built Strings/README.md +++ b/solution/2200-2299/2223.Sum of Scores of Built Strings/README.md @@ -55,36 +55,4 @@ s9 == "azbazbzaz" ,最长公共前缀为 "azbazbzaz" ,得分为 9 ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2200-2299/2223.Sum of Scores of Built Strings/README_EN.md b/solution/2200-2299/2223.Sum of Scores of Built Strings/README_EN.md index c61889ad2a61d..0c56eb7cab5f3 100644 --- a/solution/2200-2299/2223.Sum of Scores of Built Strings/README_EN.md +++ b/solution/2200-2299/2223.Sum of Scores of Built Strings/README_EN.md @@ -51,30 +51,4 @@ The sum of the scores is 2 + 3 + 9 = 14, so we return 14. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2200-2299/2224.Minimum Number of Operations to Convert Time/README.md b/solution/2200-2299/2224.Minimum Number of Operations to Convert Time/README.md index 713cb4e2ed844..624e04d7cfd76 100644 --- a/solution/2200-2299/2224.Minimum Number of Operations to Convert Time/README.md +++ b/solution/2200-2299/2224.Minimum Number of Operations to Convert Time/README.md @@ -45,16 +45,10 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 -### **Python3** - - - ```python class Solution: def convertTime(self, current: str, correct: str) -> int: @@ -67,10 +61,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int convertTime(String current, String correct) { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func convertTime(current string, correct string) int { parse := func(s string) int { @@ -126,16 +112,6 @@ func convertTime(current string, correct string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2224.Minimum Number of Operations to Convert Time/README_EN.md b/solution/2200-2299/2224.Minimum Number of Operations to Convert Time/README_EN.md index 318cea1587a17..388b1b91f3cf1 100644 --- a/solution/2200-2299/2224.Minimum Number of Operations to Convert Time/README_EN.md +++ b/solution/2200-2299/2224.Minimum Number of Operations to Convert Time/README_EN.md @@ -43,9 +43,9 @@ It can be proven that it is not possible to convert current to correct in fewer ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int convertTime(String current, String correct) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +93,6 @@ public: }; ``` -### **Go** - ```go func convertTime(current string, correct string) int { parse := func(s string) int { @@ -116,16 +110,6 @@ func convertTime(current string, correct string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2225.Find Players With Zero or One Losses/README.md b/solution/2200-2299/2225.Find Players With Zero or One Losses/README.md index 50e92760d9ec9..b02d5f7b4dd23 100644 --- a/solution/2200-2299/2225.Find Players With Zero or One Losses/README.md +++ b/solution/2200-2299/2225.Find Players With Zero or One Losses/README.md @@ -63,16 +63,10 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 -### **Python3** - - - ```python class Solution: def findWinners(self, matches: List[List[int]]) -> List[List[int]]: @@ -90,10 +84,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> findWinners(int[][] matches) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func findWinners(matches [][]int) [][]int { cnt := map[int]int{} @@ -167,8 +153,6 @@ func findWinners(matches [][]int) [][]int { } ``` -### **TypeScript** - ```ts function findWinners(matches: number[][]): number[][] { const cnt: Map = new Map(); @@ -188,8 +172,6 @@ function findWinners(matches: number[][]): number[][] { } ``` -### **JavaScript** - ```js /** * @param {number[][]} matches @@ -213,6 +195,12 @@ var findWinners = function (matches) { }; ``` + + +### 方法二 + + + ```js /** * @param {number[][]} matches @@ -243,16 +231,6 @@ var findWinners = function (matches) { }; ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2225.Find Players With Zero or One Losses/README_EN.md b/solution/2200-2299/2225.Find Players With Zero or One Losses/README_EN.md index e2facd09c0171..b94d4f1504c53 100644 --- a/solution/2200-2299/2225.Find Players With Zero or One Losses/README_EN.md +++ b/solution/2200-2299/2225.Find Players With Zero or One Losses/README_EN.md @@ -59,9 +59,9 @@ Thus, answer[0] = [1,2,5,6] and answer[1] = []. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List> findWinners(int[][] matches) { @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +127,6 @@ public: }; ``` -### **Go** - ```go func findWinners(matches [][]int) [][]int { cnt := map[int]int{} @@ -155,8 +149,6 @@ func findWinners(matches [][]int) [][]int { } ``` -### **TypeScript** - ```ts function findWinners(matches: number[][]): number[][] { const cnt: Map = new Map(); @@ -176,8 +168,6 @@ function findWinners(matches: number[][]): number[][] { } ``` -### **JavaScript** - ```js /** * @param {number[][]} matches @@ -201,6 +191,12 @@ var findWinners = function (matches) { }; ``` + + +### Solution 2 + + + ```js /** * @param {number[][]} matches @@ -231,16 +227,6 @@ var findWinners = function (matches) { }; ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2225.Find Players With Zero or One Losses/Solution2.js b/solution/2200-2299/2225.Find Players With Zero or One Losses/Solution2.js new file mode 100644 index 0000000000000..622088640a253 --- /dev/null +++ b/solution/2200-2299/2225.Find Players With Zero or One Losses/Solution2.js @@ -0,0 +1,27 @@ +/** + * @param {number[][]} matches + * @return {number[][]} + */ +var findWinners = function (matches) { + const onlyWins = new Set(), + oneLose = new Set(), + moreLosses = new Set(); + + for (const [winner, loser] of matches) { + if (!moreLosses.has(loser)) { + if (oneLose.has(loser)) { + oneLose.delete(loser); + moreLosses.add(loser); + } else { + onlyWins.delete(loser); + oneLose.add(loser); + } + } + + if (!moreLosses.has(winner) && !oneLose.has(winner)) { + onlyWins.add(winner); + } + } + + return [[...onlyWins].sort((a, b) => a - b), [...oneLose].sort((a, b) => a - b)]; +}; diff --git a/solution/2200-2299/2226.Maximum Candies Allocated to K Children/README.md b/solution/2200-2299/2226.Maximum Candies Allocated to K Children/README.md index 2f214e8603b9c..eb77f60259a2a 100644 --- a/solution/2200-2299/2226.Maximum Candies Allocated to K Children/README.md +++ b/solution/2200-2299/2226.Maximum Candies Allocated to K Children/README.md @@ -42,18 +42,12 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 时间复杂度 $O(nlogn)$。 -### **Python3** - - - ```python class Solution: def maximumCandies(self, candies: List[int], k: int) -> int: @@ -68,10 +62,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { public int maximumCandies(int[] candies, long k) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func maximumCandies(candies []int, k int64) int { left, right := 0, int(1e7) @@ -135,16 +121,6 @@ func maximumCandies(candies []int, k int64) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2226.Maximum Candies Allocated to K Children/README_EN.md b/solution/2200-2299/2226.Maximum Candies Allocated to K Children/README_EN.md index bf38a69d2a81b..7ae1f59d8f0c2 100644 --- a/solution/2200-2299/2226.Maximum Candies Allocated to K Children/README_EN.md +++ b/solution/2200-2299/2226.Maximum Candies Allocated to K Children/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { public int maximumCandies(int[] candies, long k) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +95,6 @@ public: }; ``` -### **Go** - ```go func maximumCandies(candies []int, k int64) int { left, right := 0, int(1e7) @@ -120,16 +114,6 @@ func maximumCandies(candies []int, k int64) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2227.Encrypt and Decrypt Strings/README.md b/solution/2200-2299/2227.Encrypt and Decrypt Strings/README.md index ccf1784106ebf..34c89d96249d3 100644 --- a/solution/2200-2299/2227.Encrypt and Decrypt Strings/README.md +++ b/solution/2200-2299/2227.Encrypt and Decrypt Strings/README.md @@ -71,16 +71,10 @@ encrypter.decrypt("eizfeiam"); // return 2. ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 -### **Python3** - - - ```python class Encrypter: def __init__(self, keys: List[str], values: List[str], dictionary: List[str]): @@ -105,10 +99,6 @@ class Encrypter: # param_2 = obj.decrypt(word2) ``` -### **Java** - - - ```java class Encrypter { private Map mp = new HashMap<>(); @@ -148,8 +138,6 @@ class Encrypter { */ ``` -### **C++** - ```cpp class Encrypter { public: @@ -183,8 +171,6 @@ public: */ ``` -### **Go** - ```go type Encrypter struct { mp map[byte]string @@ -228,16 +214,6 @@ func (this *Encrypter) Decrypt(word2 string) int { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2227.Encrypt and Decrypt Strings/README_EN.md b/solution/2200-2299/2227.Encrypt and Decrypt Strings/README_EN.md index d3bbc62b5db70..1b2026e55c8b9 100644 --- a/solution/2200-2299/2227.Encrypt and Decrypt Strings/README_EN.md +++ b/solution/2200-2299/2227.Encrypt and Decrypt Strings/README_EN.md @@ -69,9 +69,9 @@ encrypter.decrypt("eizfeiam"); // return 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Encrypter: @@ -97,8 +97,6 @@ class Encrypter: # param_2 = obj.decrypt(word2) ``` -### **Java** - ```java class Encrypter { private Map mp = new HashMap<>(); @@ -138,8 +136,6 @@ class Encrypter { */ ``` -### **C++** - ```cpp class Encrypter { public: @@ -173,8 +169,6 @@ public: */ ``` -### **Go** - ```go type Encrypter struct { mp map[byte]string @@ -218,16 +212,6 @@ func (this *Encrypter) Decrypt(word2 string) int { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2228.Users With Two Purchases Within Seven Days/README.md b/solution/2200-2299/2228.Users With Two Purchases Within Seven Days/README.md index 024f5f14dc879..4d0dddd8c0860 100644 --- a/solution/2200-2299/2228.Users With Two Purchases Within Seven Days/README.md +++ b/solution/2200-2299/2228.Users With Two Purchases Within Seven Days/README.md @@ -59,14 +59,10 @@ Purchases 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -89,3 +85,5 @@ ORDER BY user_id; ``` + + diff --git a/solution/2200-2299/2228.Users With Two Purchases Within Seven Days/README_EN.md b/solution/2200-2299/2228.Users With Two Purchases Within Seven Days/README_EN.md index 77ab55ad531c0..368c9fae72940 100644 --- a/solution/2200-2299/2228.Users With Two Purchases Within Seven Days/README_EN.md +++ b/solution/2200-2299/2228.Users With Two Purchases Within Seven Days/README_EN.md @@ -57,9 +57,9 @@ User 7 had two purchases on the same day so we add their ID. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -83,3 +83,5 @@ ORDER BY user_id; ``` + + diff --git a/solution/2200-2299/2229.Check if an Array Is Consecutive/README.md b/solution/2200-2299/2229.Check if an Array Is Consecutive/README.md index fe48a87e87e86..38ea8b08b70e7 100644 --- a/solution/2200-2299/2229.Check if an Array Is Consecutive/README.md +++ b/solution/2200-2299/2229.Check if an Array Is Consecutive/README.md @@ -55,14 +55,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def isConsecutive(self, nums: List[int]) -> bool: @@ -71,10 +67,6 @@ class Solution: return len(set(nums)) == n and mx == mi + n - 1 ``` -### **Java** - - - ```java class Solution { public boolean isConsecutive(int[] nums) { @@ -92,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +97,6 @@ public: }; ``` -### **Go** - ```go func isConsecutive(nums []int) bool { s := map[int]bool{} @@ -120,16 +108,6 @@ func isConsecutive(nums []int) bool { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2229.Check if an Array Is Consecutive/README_EN.md b/solution/2200-2299/2229.Check if an Array Is Consecutive/README_EN.md index fba05ed724001..73efe670db7ca 100644 --- a/solution/2200-2299/2229.Check if an Array Is Consecutive/README_EN.md +++ b/solution/2200-2299/2229.Check if an Array Is Consecutive/README_EN.md @@ -52,9 +52,9 @@ Therefore, nums is consecutive. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return len(set(nums)) == n and mx == mi + n - 1 ``` -### **Java** - ```java class Solution { public boolean isConsecutive(int[] nums) { @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +94,6 @@ public: }; ``` -### **Go** - ```go func isConsecutive(nums []int) bool { s := map[int]bool{} @@ -111,16 +105,6 @@ func isConsecutive(nums []int) bool { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2230.The Users That Are Eligible for Discount/README.md b/solution/2200-2299/2230.The Users That Are Eligible for Discount/README.md index 032bb9d14e589..7f384ca13c2c9 100644 --- a/solution/2200-2299/2230.The Users That Are Eligible for Discount/README.md +++ b/solution/2200-2299/2230.The Users That Are Eligible for Discount/README.md @@ -57,14 +57,10 @@ startDate = 2022-03-08, endDate = 2022-03-20, minAmount = 1000 ## 解法 - +### 方法一 -### **SQL** - - - ```sql CREATE PROCEDURE getUserIDs(startDate DATE, endDate DATE, minAmount INT) BEGIN @@ -77,3 +73,5 @@ END; ``` + + diff --git a/solution/2200-2299/2230.The Users That Are Eligible for Discount/README_EN.md b/solution/2200-2299/2230.The Users That Are Eligible for Discount/README_EN.md index 071fb4d3e43c2..7406dff1e477a 100644 --- a/solution/2200-2299/2230.The Users That Are Eligible for Discount/README_EN.md +++ b/solution/2200-2299/2230.The Users That Are Eligible for Discount/README_EN.md @@ -61,9 +61,9 @@ Out of the three users, only User 3 is eligible for a discount. ## Solutions - +### Solution 1 -### **SQL** + ```sql CREATE PROCEDURE getUserIDs(startDate DATE, endDate DATE, minAmount INT) @@ -77,3 +77,5 @@ END; ``` + + diff --git a/solution/2200-2299/2231.Largest Number After Digit Swaps by Parity/README.md b/solution/2200-2299/2231.Largest Number After Digit Swaps by Parity/README.md index 80c4f063f03c0..a79a442df22d5 100644 --- a/solution/2200-2299/2231.Largest Number After Digit Swaps by Parity/README.md +++ b/solution/2200-2299/2231.Largest Number After Digit Swaps by Parity/README.md @@ -41,18 +41,10 @@ ## 解法 - - -**方法一:计数** - -**方法二:分组 + 排序** +### 方法一:计数 -### **Python3** - - - ```python class Solution: def largestInteger(self, num: int) -> int: @@ -75,10 +67,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int largestInteger(int num) { @@ -108,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +126,6 @@ public: }; ``` -### **Go** - ```go func largestInteger(num int) int { cnt := make([]int, 10) @@ -168,8 +152,6 @@ func largestInteger(num int) int { } ``` -### **TypeScript** - ```ts function largestInteger(num: number): number { let arrs = String(num).split('').map(Number); @@ -192,10 +174,8 @@ function largestInteger(num: number): number { } ``` -### **...** - -``` + -``` +### 方法二:分组 + 排序 - + diff --git a/solution/2200-2299/2231.Largest Number After Digit Swaps by Parity/README_EN.md b/solution/2200-2299/2231.Largest Number After Digit Swaps by Parity/README_EN.md index 055690fcf8359..a1417c24916eb 100644 --- a/solution/2200-2299/2231.Largest Number After Digit Swaps by Parity/README_EN.md +++ b/solution/2200-2299/2231.Largest Number After Digit Swaps by Parity/README_EN.md @@ -39,9 +39,9 @@ Note that there may be other sequences of swaps but it can be shown that 87655 i ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int largestInteger(int num) { @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +124,6 @@ public: }; ``` -### **Go** - ```go func largestInteger(num int) int { cnt := make([]int, 10) @@ -156,8 +150,6 @@ func largestInteger(num int) int { } ``` -### **TypeScript** - ```ts function largestInteger(num: number): number { let arrs = String(num).split('').map(Number); @@ -180,10 +172,6 @@ function largestInteger(num: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2232.Minimize Result by Adding Parentheses to Expression/README.md b/solution/2200-2299/2232.Minimize Result by Adding Parentheses to Expression/README.md index 1f1da707a3d78..25424098b3aee 100644 --- a/solution/2200-2299/2232.Minimize Result by Adding Parentheses to Expression/README.md +++ b/solution/2200-2299/2232.Minimize Result by Adding Parentheses to Expression/README.md @@ -53,16 +53,10 @@ ## 解法 - - -**方法一:枚举左右括号的插入位置** +### 方法一:枚举左右括号的插入位置 -### **Python3** - - - ```python class Solution: def minimizeResult(self, expression: str) -> str: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public String minimizeResult(String expression) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function minimizeResult(expression: string): string { const [n1, n2] = expression.split('+'); @@ -143,10 +131,6 @@ function getNum(arr: Array): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2232.Minimize Result by Adding Parentheses to Expression/README_EN.md b/solution/2200-2299/2232.Minimize Result by Adding Parentheses to Expression/README_EN.md index e389d4a2e631f..2a90f4a785165 100644 --- a/solution/2200-2299/2232.Minimize Result by Adding Parentheses to Expression/README_EN.md +++ b/solution/2200-2299/2232.Minimize Result by Adding Parentheses to Expression/README_EN.md @@ -52,9 +52,9 @@ It can be shown that 170 is the smallest possible value. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public String minimizeResult(String expression) { @@ -103,8 +101,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function minimizeResult(expression: string): string { const [n1, n2] = expression.split('+'); @@ -134,10 +130,6 @@ function getNum(arr: Array): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2233.Maximum Product After K Increments/README.md b/solution/2200-2299/2233.Maximum Product After K Increments/README.md index a8b70a70adf13..fb1e5552dfba7 100644 --- a/solution/2200-2299/2233.Maximum Product After K Increments/README.md +++ b/solution/2200-2299/2233.Maximum Product After K Increments/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列(小根堆)** +### 方法一:贪心 + 优先队列(小根堆) 每次操作,贪心地选择最小的元素进行加 $1$,共进行 $k$ 次操作。最后累乘所有元素得到结果。注意取模操作。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def maximumProduct(self, nums: List[int], k: int) -> int: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func maximumProduct(nums []int, k int) int { h := hp{nums} @@ -137,8 +123,6 @@ func (hp) Push(any) {} func (hp) Pop() (_ any) { return } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -163,10 +147,6 @@ var maximumProduct = function (nums, k) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2233.Maximum Product After K Increments/README_EN.md b/solution/2200-2299/2233.Maximum Product After K Increments/README_EN.md index 0eb6a710d2efe..71e5f03b6436c 100644 --- a/solution/2200-2299/2233.Maximum Product After K Increments/README_EN.md +++ b/solution/2200-2299/2233.Maximum Product After K Increments/README_EN.md @@ -41,9 +41,9 @@ Note that there may be other ways to increment nums to have the maximum product. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +97,6 @@ public: }; ``` -### **Go** - ```go func maximumProduct(nums []int, k int) int { h := hp{nums} @@ -123,8 +117,6 @@ func (hp) Push(any) {} func (hp) Pop() (_ any) { return } ``` -### **JavaScript** - ```js /** * @param {number[]} nums @@ -149,10 +141,6 @@ var maximumProduct = function (nums, k) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2234.Maximum Total Beauty of the Gardens/README.md b/solution/2200-2299/2234.Maximum Total Beauty of the Gardens/README.md index 370c075998279..7d8c1fcfebf63 100644 --- a/solution/2200-2299/2234.Maximum Total Beauty of the Gardens/README.md +++ b/solution/2200-2299/2234.Maximum Total Beauty of the Gardens/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:枚举 + 二分查找** +### 方法一:枚举 + 二分查找 我们注意到,如果一个花园中种的花的数目已经大于等于 $target$,那么这个花园就已经是完善的花园,不能再改变。而不完善的花园中,可以通过种更多的花来使得这个花园变成完善的花园。 @@ -85,10 +83,6 @@ -### **Python3** - - - ```python class Solution: def maximumBeauty( @@ -117,10 +111,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long maximumBeauty(int[] flowers, long newFlowers, int target, int full, int partial) { @@ -163,8 +153,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -206,8 +194,6 @@ public: }; ``` -### **Go** - ```go func maximumBeauty(flowers []int, newFlowers int64, target int, full int, partial int) int64 { sort.Ints(flowers) @@ -245,8 +231,6 @@ func maximumBeauty(flowers []int, newFlowers int64, target int, full int, partia } ``` -### **TypeScript** - ```ts function maximumBeauty( flowers: number[], @@ -289,10 +273,6 @@ function maximumBeauty( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2234.Maximum Total Beauty of the Gardens/README_EN.md b/solution/2200-2299/2234.Maximum Total Beauty of the Gardens/README_EN.md index b2e80ce172fea..fe5b0c40b17c8 100644 --- a/solution/2200-2299/2234.Maximum Total Beauty of the Gardens/README_EN.md +++ b/solution/2200-2299/2234.Maximum Total Beauty of the Gardens/README_EN.md @@ -65,9 +65,9 @@ Note that Alice could make all the gardens complete but in this case, she would ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -97,8 +97,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long maximumBeauty(int[] flowers, long newFlowers, int target, int full, int partial) { @@ -141,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -184,8 +180,6 @@ public: }; ``` -### **Go** - ```go func maximumBeauty(flowers []int, newFlowers int64, target int, full int, partial int) int64 { sort.Ints(flowers) @@ -223,8 +217,6 @@ func maximumBeauty(flowers []int, newFlowers int64, target int, full int, partia } ``` -### **TypeScript** - ```ts function maximumBeauty( flowers: number[], @@ -267,10 +259,6 @@ function maximumBeauty( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2235.Add Two Integers/README.md b/solution/2200-2299/2235.Add Two Integers/README.md index 6d1c3e5677ff4..78de5d40b1de8 100644 --- a/solution/2200-2299/2235.Add Two Integers/README.md +++ b/solution/2200-2299/2235.Add Two Integers/README.md @@ -36,15 +36,66 @@ ## 解法 - - -**方法一:使用加法运算符** +### 方法一:使用加法运算符 我们可以直接使用加法运算符 `+` 来计算两个整数的和。 时间复杂度 $O(1)$,空间复杂度 $O(1)$。 -**方法二:位运算(不使用加法运算符)** + + +```python +class Solution: + def sum(self, num1: int, num2: int) -> int: + return num1 + num2 +``` + +```java +class Solution { + public int sum(int num1, int num2) { + return num1 + num2; + } +} +``` + +```cpp +class Solution { +public: + int sum(int num1, int num2) { + return num1 + num2; + } +}; +``` + +```go +func sum(num1 int, num2 int) int { + return num1 + num2 +} +``` + +```ts +function sum(num1: number, num2: number): number { + return num1 + num2; +} +``` + +```rust +impl Solution { + pub fn sum(num1: i32, num2: i32) -> i32 { + num1 + num2 + } +} +``` + +```c +int sum(int num1, int num2) { + return num1 + num2; +} +``` + + + +### 方法二:位运算(不使用加法运算符) 我们也可以在不使用加法运算符的前提下,使用位运算来计算两个整数的和。 @@ -70,16 +121,6 @@ -### **Python3** - - - -```python -class Solution: - def sum(self, num1: int, num2: int) -> int: - return num1 + num2 -``` - ```python class Solution: def sum(self, num1: int, num2: int) -> int: @@ -90,18 +131,6 @@ class Solution: return num1 if num1 < 0x80000000 else ~(num1 ^ 0xFFFFFFFF) ``` -### **Java** - - - -```java -class Solution { - public int sum(int num1, int num2) { - return num1 + num2; - } -} -``` - ```java class Solution { public int sum(int num1, int num2) { @@ -115,17 +144,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int sum(int num1, int num2) { - return num1 + num2; - } -}; -``` - ```cpp class Solution { public: @@ -140,14 +158,6 @@ public: }; ``` -### **Go** - -```go -func sum(num1 int, num2 int) int { - return num1 + num2 -} -``` - ```go func sum(num1 int, num2 int) int { for num2 != 0 { @@ -159,14 +169,6 @@ func sum(num1 int, num2 int) int { } ``` -### **TypeScript** - -```ts -function sum(num1: number, num2: number): number { - return num1 + num2; -} -``` - ```ts function sum(num1: number, num2: number): number { while (num2) { @@ -178,16 +180,6 @@ function sum(num1: number, num2: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn sum(num1: i32, num2: i32) -> i32 { - num1 + num2 - } -} -``` - ```rust impl Solution { pub fn sum(num1: i32, num2: i32) -> i32 { @@ -203,18 +195,6 @@ impl Solution { } ``` -### **C** - -```c -int sum(int num1, int num2) { - return num1 + num2; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2235.Add Two Integers/README_EN.md b/solution/2200-2299/2235.Add Two Integers/README_EN.md index 9036830033782..551da60d5f8a9 100644 --- a/solution/2200-2299/2235.Add Two Integers/README_EN.md +++ b/solution/2200-2299/2235.Add Two Integers/README_EN.md @@ -32,9 +32,9 @@ Given two integers num1 and num2, return the +### Solution 1 -### **Python3** + ```python class Solution: @@ -42,6 +42,55 @@ class Solution: return num1 + num2 ``` +```java +class Solution { + public int sum(int num1, int num2) { + return num1 + num2; + } +} +``` + +```cpp +class Solution { +public: + int sum(int num1, int num2) { + return num1 + num2; + } +}; +``` + +```go +func sum(num1 int, num2 int) int { + return num1 + num2 +} +``` + +```ts +function sum(num1: number, num2: number): number { + return num1 + num2; +} +``` + +```rust +impl Solution { + pub fn sum(num1: i32, num2: i32) -> i32 { + num1 + num2 + } +} +``` + +```c +int sum(int num1, int num2) { + return num1 + num2; +} +``` + + + +### Solution 2 + + + ```python class Solution: def sum(self, num1: int, num2: int) -> int: @@ -52,16 +101,6 @@ class Solution: return num1 if num1 < 0x80000000 else ~(num1 ^ 0xFFFFFFFF) ``` -### **Java** - -```java -class Solution { - public int sum(int num1, int num2) { - return num1 + num2; - } -} -``` - ```java class Solution { public int sum(int num1, int num2) { @@ -75,17 +114,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int sum(int num1, int num2) { - return num1 + num2; - } -}; -``` - ```cpp class Solution { public: @@ -100,14 +128,6 @@ public: }; ``` -### **Go** - -```go -func sum(num1 int, num2 int) int { - return num1 + num2 -} -``` - ```go func sum(num1 int, num2 int) int { for num2 != 0 { @@ -119,14 +139,6 @@ func sum(num1 int, num2 int) int { } ``` -### **TypeScript** - -```ts -function sum(num1: number, num2: number): number { - return num1 + num2; -} -``` - ```ts function sum(num1: number, num2: number): number { while (num2) { @@ -138,16 +150,6 @@ function sum(num1: number, num2: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn sum(num1: i32, num2: i32) -> i32 { - num1 + num2 - } -} -``` - ```rust impl Solution { pub fn sum(num1: i32, num2: i32) -> i32 { @@ -163,18 +165,6 @@ impl Solution { } ``` -### **C** - -```c -int sum(int num1, int num2) { - return num1 + num2; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2236.Root Equals Sum of Children/README.md b/solution/2200-2299/2236.Root Equals Sum of Children/README.md index 076f894540135..b2ed3ca42edd6 100644 --- a/solution/2200-2299/2236.Root Equals Sum of Children/README.md +++ b/solution/2200-2299/2236.Root Equals Sum of Children/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:直接判断** +### 方法一:直接判断 我们直接判断根节点的值是否等于左右子节点的值之和即可。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -67,10 +61,6 @@ class Solution: return root.val == root.left.val + root.right.val ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -132,8 +118,6 @@ func checkTree(root *TreeNode) bool { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -154,8 +138,6 @@ function checkTree(root: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -187,8 +169,6 @@ impl Solution { } ``` -### **C** - ```c /** * Definition for a binary tree node. @@ -204,10 +184,6 @@ bool checkTree(struct TreeNode* root) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2236.Root Equals Sum of Children/README_EN.md b/solution/2200-2299/2236.Root Equals Sum of Children/README_EN.md index 21f0de558a40d..392108de64aa0 100644 --- a/solution/2200-2299/2236.Root Equals Sum of Children/README_EN.md +++ b/solution/2200-2299/2236.Root Equals Sum of Children/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -53,8 +53,6 @@ class Solution: return root.val == root.left.val + root.right.val ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -100,8 +96,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -116,8 +110,6 @@ func checkTree(root *TreeNode) bool { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -138,8 +130,6 @@ function checkTree(root: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -171,8 +161,6 @@ impl Solution { } ``` -### **C** - ```c /** * Definition for a binary tree node. @@ -188,10 +176,6 @@ bool checkTree(struct TreeNode* root) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2237.Count Positions on Street With Required Brightness/README.md b/solution/2200-2299/2237.Count Positions on Street With Required Brightness/README.md index ccd4799c91636..cf1c6a16757fb 100644 --- a/solution/2200-2299/2237.Count Positions on Street With Required Brightness/README.md +++ b/solution/2200-2299/2237.Count Positions on Street With Required Brightness/README.md @@ -60,18 +60,12 @@ ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 时间复杂度 $O(n)$。 -### **Python3** - - - ```python class Solution: def meetRequirement( @@ -85,10 +79,6 @@ class Solution: return sum(s >= r for s, r in zip(accumulate(d), requirement)) ``` -### **Java** - - - ```java class Solution { public int meetRequirement(int n, int[][] lights, int[] requirement) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func meetRequirement(n int, lights [][]int, requirement []int) int { d := make([]int, 100010) @@ -155,16 +141,6 @@ func meetRequirement(n int, lights [][]int, requirement []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2237.Count Positions on Street With Required Brightness/README_EN.md b/solution/2200-2299/2237.Count Positions on Street With Required Brightness/README_EN.md index 3764f8f7e5f0f..b26bc17fe12a9 100644 --- a/solution/2200-2299/2237.Count Positions on Street With Required Brightness/README_EN.md +++ b/solution/2200-2299/2237.Count Positions on Street With Required Brightness/README_EN.md @@ -56,9 +56,9 @@ Positions 0, 1, 2, and 4 meet the requirement so we return 4. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return sum(s >= r for s, r in zip(accumulate(d), requirement)) ``` -### **Java** - ```java class Solution { public int meetRequirement(int n, int[][] lights, int[] requirement) { @@ -98,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +116,6 @@ public: }; ``` -### **Go** - ```go func meetRequirement(n int, lights [][]int, requirement []int) int { d := make([]int, 100010) @@ -141,16 +135,6 @@ func meetRequirement(n int, lights [][]int, requirement []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2238.Number of Times a Driver Was a Passenger/README.md b/solution/2200-2299/2238.Number of Times a Driver Was a Passenger/README.md index 882a129454ecd..2a462b5b6ce65 100644 --- a/solution/2200-2299/2238.Number of Times a Driver Was a Passenger/README.md +++ b/solution/2200-2299/2238.Number of Times a Driver Was a Passenger/README.md @@ -59,14 +59,10 @@ ID = 11 的司机从来不是乘客。 ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH T AS (SELECT DISTINCT driver_id FROM Rides) @@ -78,3 +74,5 @@ GROUP BY 1; ``` + + diff --git a/solution/2200-2299/2238.Number of Times a Driver Was a Passenger/README_EN.md b/solution/2200-2299/2238.Number of Times a Driver Was a Passenger/README_EN.md index 1920c89362a1f..7d0ede717396e 100644 --- a/solution/2200-2299/2238.Number of Times a Driver Was a Passenger/README_EN.md +++ b/solution/2200-2299/2238.Number of Times a Driver Was a Passenger/README_EN.md @@ -58,9 +58,9 @@ The driver with ID = 11 was never a passenger. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -73,3 +73,5 @@ GROUP BY 1; ``` + + diff --git a/solution/2200-2299/2239.Find Closest Number to Zero/README.md b/solution/2200-2299/2239.Find Closest Number to Zero/README.md index d3db8683b3944..4b4f3adce9423 100644 --- a/solution/2200-2299/2239.Find Closest Number to Zero/README.md +++ b/solution/2200-2299/2239.Find Closest Number to Zero/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们定义一个变量 $d$ 来记录当前最小的距离,初始时 $d=\infty$。然后我们遍历数组,对于每个元素 $x$,我们计算 $y=|x|$,如果 $y \lt d$ 或者 $y=d$ 且 $x \gt ans$,我们就更新答案 $ans=x$ 和 $d=y$。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def findClosestNumber(self, nums: List[int]) -> int: @@ -67,10 +61,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int findClosestNumber(int[] nums) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +94,6 @@ public: }; ``` -### **Go** - ```go func findClosestNumber(nums []int) int { ans, d := 0, 1<<30 @@ -127,8 +113,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function findClosestNumber(nums: number[]): number { let [ans, d] = [0, 1 << 30]; @@ -142,10 +126,6 @@ function findClosestNumber(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2239.Find Closest Number to Zero/README_EN.md b/solution/2200-2299/2239.Find Closest Number to Zero/README_EN.md index e8617d2d314da..ca4c91f7e9293 100644 --- a/solution/2200-2299/2239.Find Closest Number to Zero/README_EN.md +++ b/solution/2200-2299/2239.Find Closest Number to Zero/README_EN.md @@ -38,9 +38,9 @@ Thus, the closest number to 0 in the array is 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int findClosestNumber(int[] nums) { @@ -70,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,8 +85,6 @@ public: }; ``` -### **Go** - ```go func findClosestNumber(nums []int) int { ans, d := 0, 1<<30 @@ -110,8 +104,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function findClosestNumber(nums: number[]): number { let [ans, d] = [0, 1 << 30]; @@ -125,10 +117,6 @@ function findClosestNumber(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2240.Number of Ways to Buy Pens and Pencils/README.md b/solution/2200-2299/2240.Number of Ways to Buy Pens and Pencils/README.md index a8774d8bfb62d..3b160a10bb549 100644 --- a/solution/2200-2299/2240.Number of Ways to Buy Pens and Pencils/README.md +++ b/solution/2200-2299/2240.Number of Ways to Buy Pens and Pencils/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举购买钢笔的数量 $x$,对于每个 $x$,我们最多可以购买铅笔的数量为 $\frac{total - x \times cost1}{cost2}$,那么数量加 $1$ 即为 $x$ 的方案数。我们累加所有的 $x$ 的方案数,即为答案。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python class Solution: def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int: @@ -64,10 +58,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long waysToBuyPensPencils(int total, int cost1, int cost2) { @@ -81,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +85,6 @@ public: }; ``` -### **Go** - ```go func waysToBuyPensPencils(total int, cost1 int, cost2 int) (ans int64) { for x := 0; x <= total/cost1; x++ { @@ -109,8 +95,6 @@ func waysToBuyPensPencils(total int, cost1 int, cost2 int) (ans int64) { } ``` -### **TypeScript** - ```ts function waysToBuyPensPencils(total: number, cost1: number, cost2: number): number { let ans = 0; @@ -122,8 +106,6 @@ function waysToBuyPensPencils(total: number, cost1: number, cost2: number): numb } ``` -### **Rust** - ```rust impl Solution { pub fn ways_to_buy_pens_pencils(total: i32, cost1: i32, cost2: i32) -> i64 { @@ -136,10 +118,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2240.Number of Ways to Buy Pens and Pencils/README_EN.md b/solution/2200-2299/2240.Number of Ways to Buy Pens and Pencils/README_EN.md index 5a1d9a0e53f53..54ef3fd930e28 100644 --- a/solution/2200-2299/2240.Number of Ways to Buy Pens and Pencils/README_EN.md +++ b/solution/2200-2299/2240.Number of Ways to Buy Pens and Pencils/README_EN.md @@ -38,9 +38,9 @@ The total number of ways to buy pens and pencils is 5 + 3 + 1 = 9. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -52,8 +52,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long waysToBuyPensPencils(int total, int cost1, int cost2) { @@ -67,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -83,8 +79,6 @@ public: }; ``` -### **Go** - ```go func waysToBuyPensPencils(total int, cost1 int, cost2 int) (ans int64) { for x := 0; x <= total/cost1; x++ { @@ -95,8 +89,6 @@ func waysToBuyPensPencils(total int, cost1 int, cost2 int) (ans int64) { } ``` -### **TypeScript** - ```ts function waysToBuyPensPencils(total: number, cost1: number, cost2: number): number { let ans = 0; @@ -108,8 +100,6 @@ function waysToBuyPensPencils(total: number, cost1: number, cost2: number): numb } ``` -### **Rust** - ```rust impl Solution { pub fn ways_to_buy_pens_pencils(total: i32, cost1: i32, cost2: i32) -> i64 { @@ -122,10 +112,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2241.Design an ATM Machine/README.md b/solution/2200-2299/2241.Design an ATM Machine/README.md index 7370261dba5fa..2d81b292a497a 100644 --- a/solution/2200-2299/2241.Design an ATM Machine/README.md +++ b/solution/2200-2299/2241.Design an ATM Machine/README.md @@ -58,9 +58,7 @@ atm.withdraw(550); // 返回 [0,1,0,0,1] ,机器会返回 1 张 50 的 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们用一个数组 $d$ 记录钞票面额,用一个数组 $cnt$ 记录每种面额的钞票数量。 @@ -70,10 +68,6 @@ atm.withdraw(550); // 返回 [0,1,0,0,1] ,机器会返回 1 张 50 的 -### **Python3** - - - ```python class ATM: def __init__(self): @@ -102,10 +96,6 @@ class ATM: # param_2 = obj.withdraw(amount) ``` -### **Java** - - - ```java class ATM { private long[] cnt = new long[5]; @@ -144,8 +134,6 @@ class ATM { */ ``` -### **C++** - ```cpp class ATM { public: @@ -186,8 +174,6 @@ private: */ ``` -### **Go** - ```go type ATM struct { d [5]int @@ -227,16 +213,6 @@ func (this *ATM) Withdraw(amount int) []int { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2241.Design an ATM Machine/README_EN.md b/solution/2200-2299/2241.Design an ATM Machine/README_EN.md index 083341194b80f..1cda656acb3e2 100644 --- a/solution/2200-2299/2241.Design an ATM Machine/README_EN.md +++ b/solution/2200-2299/2241.Design an ATM Machine/README_EN.md @@ -61,9 +61,9 @@ atm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 50 banknote ## Solutions - +### Solution 1 -### **Python3** + ```python class ATM: @@ -93,8 +93,6 @@ class ATM: # param_2 = obj.withdraw(amount) ``` -### **Java** - ```java class ATM { private long[] cnt = new long[5]; @@ -133,8 +131,6 @@ class ATM { */ ``` -### **C++** - ```cpp class ATM { public: @@ -175,8 +171,6 @@ private: */ ``` -### **Go** - ```go type ATM struct { d [5]int @@ -216,16 +210,6 @@ func (this *ATM) Withdraw(amount int) []int { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2242.Maximum Score of a Node Sequence/README.md b/solution/2200-2299/2242.Maximum Score of a Node Sequence/README.md index 2144a9c984553..c2bc98a8bb34f 100644 --- a/solution/2200-2299/2242.Maximum Score of a Node Sequence/README.md +++ b/solution/2200-2299/2242.Maximum Score of a Node Sequence/README.md @@ -65,18 +65,12 @@ ## 解法 - - -**方法一:枚举中间边** +### 方法一:枚举中间边 枚举中间边 $(a, b)$,假设与 $a$ 相邻的点为 $c$,与 $b$ 相邻的点为 $d$。对于相邻点,取分数最大的三个点进行枚举。 -### **Python3** - - - ```python class Solution: def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int: @@ -96,10 +90,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumScore(int[] scores, int[][] edges) { @@ -132,16 +122,6 @@ class Solution { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2242.Maximum Score of a Node Sequence/README_EN.md b/solution/2200-2299/2242.Maximum Score of a Node Sequence/README_EN.md index 25ffd80e3f5c8..45bd9cef0da38 100644 --- a/solution/2200-2299/2242.Maximum Score of a Node Sequence/README_EN.md +++ b/solution/2200-2299/2242.Maximum Score of a Node Sequence/README_EN.md @@ -57,9 +57,9 @@ There are no valid node sequences of length 4, so we return -1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumScore(int[] scores, int[][] edges) { @@ -114,16 +112,6 @@ class Solution { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2243.Calculate Digit Sum of a String/README.md b/solution/2200-2299/2243.Calculate Digit Sum of a String/README.md index 97145909d94af..d39d6d9e71441 100644 --- a/solution/2200-2299/2243.Calculate Digit Sum of a String/README.md +++ b/solution/2200-2299/2243.Calculate Digit Sum of a String/README.md @@ -56,9 +56,7 @@ s 变为 "0" + "0" + "0" = "000" ,其长度等于 k ,所以返回 "000" 。 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 根据题意,我们可以模拟题目中的操作过程,直到字符串长度小于等于 $k$ 为止,最后返回字符串即可。 @@ -66,10 +64,6 @@ s 变为 "0" + "0" + "0" = "000" ,其长度等于 k ,所以返回 "000" 。 -### **Python3** - - - ```python class Solution: def digitSum(self, s: str, k: int) -> str: @@ -85,22 +79,6 @@ class Solution: return s ``` -```python -class Solution: - def digitSum(self, s: str, k: int) -> str: - if len(s) <= k: - return s - t = [] - while s: - t.append(str(sum(int(v) for v in s[:k]))) - s = s[k:] - return self.digitSum(''.join(t), k) -``` - -### **Java** - - - ```java class Solution { public String digitSum(String s, int k) { @@ -121,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +120,6 @@ public: }; ``` -### **Go** - ```go func digitSum(s string, k int) string { for len(s) > k { @@ -164,8 +138,6 @@ func digitSum(s string, k int) string { } ``` -### **TypeScript** - ```ts function digitSum(s: string, k: number): string { let ans = []; @@ -181,10 +153,24 @@ function digitSum(s: string, k: number): string { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def digitSum(self, s: str, k: int) -> str: + if len(s) <= k: + return s + t = [] + while s: + t.append(str(sum(int(v) for v in s[:k]))) + s = s[k:] + return self.digitSum(''.join(t), k) ``` + + diff --git a/solution/2200-2299/2243.Calculate Digit Sum of a String/README_EN.md b/solution/2200-2299/2243.Calculate Digit Sum of a String/README_EN.md index 7d41aff29123d..185bd13b4b68a 100644 --- a/solution/2200-2299/2243.Calculate Digit Sum of a String/README_EN.md +++ b/solution/2200-2299/2243.Calculate Digit Sum of a String/README_EN.md @@ -54,9 +54,9 @@ s becomes "0" + "0" + "0" = "000", whose ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,20 +73,6 @@ class Solution: return s ``` -```python -class Solution: - def digitSum(self, s: str, k: int) -> str: - if len(s) <= k: - return s - t = [] - while s: - t.append(str(sum(int(v) for v in s[:k]))) - s = s[k:] - return self.digitSum(''.join(t), k) -``` - -### **Java** - ```java class Solution { public String digitSum(String s, int k) { @@ -107,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +114,6 @@ public: }; ``` -### **Go** - ```go func digitSum(s string, k int) string { for len(s) > k { @@ -150,8 +132,6 @@ func digitSum(s string, k int) string { } ``` -### **TypeScript** - ```ts function digitSum(s: string, k: number): string { let ans = []; @@ -167,10 +147,24 @@ function digitSum(s: string, k: number): string { } ``` -### **...** + + +### Solution 2 -``` + +```python +class Solution: + def digitSum(self, s: str, k: int) -> str: + if len(s) <= k: + return s + t = [] + while s: + t.append(str(sum(int(v) for v in s[:k]))) + s = s[k:] + return self.digitSum(''.join(t), k) ``` + + diff --git a/solution/2200-2299/2244.Minimum Rounds to Complete All Tasks/README.md b/solution/2200-2299/2244.Minimum Rounds to Complete All Tasks/README.md index 8057db2b5e04d..55d49ea194d79 100644 --- a/solution/2200-2299/2244.Minimum Rounds to Complete All Tasks/README.md +++ b/solution/2200-2299/2244.Minimum Rounds to Complete All Tasks/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们用哈希表统计每个难度级别的任务数量,然后遍历哈希表,对于每个难度级别的任务数量,如果数量为 $1$,则无法完成所有任务,返回 $-1$;否则,计算完成该难度级别的任务需要的轮数,累加到答案中。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def minimumRounds(self, tasks: List[int]) -> int: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumRounds(int[] tasks) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func minimumRounds(tasks []int) int { cnt := map[int]int{} @@ -137,8 +123,6 @@ func minimumRounds(tasks []int) int { } ``` -### **TypeScript** - ```ts function minimumRounds(tasks: number[]): number { const cnt = new Map(); @@ -156,10 +140,6 @@ function minimumRounds(tasks: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2244.Minimum Rounds to Complete All Tasks/README_EN.md b/solution/2200-2299/2244.Minimum Rounds to Complete All Tasks/README_EN.md index 5a2aca70bcda2..3bbb502c5b700 100644 --- a/solution/2200-2299/2244.Minimum Rounds to Complete All Tasks/README_EN.md +++ b/solution/2200-2299/2244.Minimum Rounds to Complete All Tasks/README_EN.md @@ -40,9 +40,9 @@ It can be shown that all the tasks cannot be completed in fewer than 4 rounds, s ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumRounds(int[] tasks) { @@ -77,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +95,6 @@ public: }; ``` -### **Go** - ```go func minimumRounds(tasks []int) int { cnt := map[int]int{} @@ -121,8 +115,6 @@ func minimumRounds(tasks []int) int { } ``` -### **TypeScript** - ```ts function minimumRounds(tasks: number[]): number { const cnt = new Map(); @@ -140,10 +132,6 @@ function minimumRounds(tasks: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2245.Maximum Trailing Zeros in a Cornered Path/README.md b/solution/2200-2299/2245.Maximum Trailing Zeros in a Cornered Path/README.md index 9d32739ffdb7a..43df1ed0c2194 100644 --- a/solution/2200-2299/2245.Maximum Trailing Zeros in a Cornered Path/README.md +++ b/solution/2200-2299/2245.Maximum Trailing Zeros in a Cornered Path/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:前缀和 + 枚举拐点** +### 方法一:前缀和 + 枚举拐点 首先我们要明确,对于一个乘积,尾随零的个数取决于因子中 $2$ 和 $5$ 的个数的较小值。另外,每一条转角路径应该覆盖尽可能多的数,因此,它一定是从某个边界出发,到达某个拐点,再到达另一个边界。 @@ -93,10 +91,6 @@ -### **Python3** - - - ```python class Solution: def maxTrailingZeros(self, grid: List[List[int]]) -> int: @@ -132,10 +126,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxTrailingZeros(int[][] grid) { @@ -176,8 +166,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -218,8 +206,6 @@ public: }; ``` -### **Go** - ```go func maxTrailingZeros(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -264,8 +250,6 @@ func get(m, n int) [][]int { } ``` -### **TypeScript** - ```ts function maxTrailingZeros(grid: number[][]): number { const m = grid.length; @@ -308,10 +292,6 @@ function maxTrailingZeros(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2245.Maximum Trailing Zeros in a Cornered Path/README_EN.md b/solution/2200-2299/2245.Maximum Trailing Zeros in a Cornered Path/README_EN.md index 39420a8f701f1..abf897f424b8a 100644 --- a/solution/2200-2299/2245.Maximum Trailing Zeros in a Cornered Path/README_EN.md +++ b/solution/2200-2299/2245.Maximum Trailing Zeros in a Cornered Path/README_EN.md @@ -56,9 +56,9 @@ There are no cornered paths in the grid that result in a product with a trailing ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -95,8 +95,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxTrailingZeros(int[][] grid) { @@ -137,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -179,8 +175,6 @@ public: }; ``` -### **Go** - ```go func maxTrailingZeros(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -225,8 +219,6 @@ func get(m, n int) [][]int { } ``` -### **TypeScript** - ```ts function maxTrailingZeros(grid: number[][]): number { const m = grid.length; @@ -269,10 +261,6 @@ function maxTrailingZeros(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/README.md b/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/README.md index 074a3a363a5d0..f85ce6b4ec470 100644 --- a/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/README.md +++ b/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:树形 DP** +### 方法一:树形 DP 我们先根据数组 $parent$ 构建邻接表 $g$,其中 $g[i]$ 表示节点 $i$ 的所有子节点。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def longestPath(self, parent: List[int], s: str) -> int: @@ -89,10 +83,6 @@ class Solution: return ans + 1 ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func longestPath(parent []int, s string) int { n := len(parent) @@ -181,8 +167,6 @@ func longestPath(parent []int, s string) int { } ``` -### **TypeScript** - ```ts function longestPath(parent: number[], s: string): number { const n = parent.length; @@ -207,10 +191,6 @@ function longestPath(parent: number[], s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/README_EN.md b/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/README_EN.md index 11b449fc5fc58..bba8e474d0d16 100644 --- a/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/README_EN.md +++ b/solution/2200-2299/2246.Longest Path With Different Adjacent Characters/README_EN.md @@ -42,9 +42,9 @@ It can be proven that there is no longer path that satisfies the conditions. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return ans + 1 ``` -### **Java** - ```java class Solution { private List[] g; @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +126,6 @@ public: }; ``` -### **Go** - ```go func longestPath(parent []int, s string) int { n := len(parent) @@ -157,10 +151,7 @@ func longestPath(parent []int, s string) int { } ``` -### **TypeScript** - ```ts -function longestPath(parent: number[], s: string): number { function longestPath(parent: number[], s: string): number { const n = parent.length; const g: number[][] = Array.from({ length: n }, () => []); @@ -184,10 +175,6 @@ function longestPath(parent: number[], s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/README.md b/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/README.md index d40ff267d391e..dc78c41572c84 100644 --- a/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/README.md +++ b/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:状态压缩动态规划** +### 方法一:状态压缩动态规划 我们注意到,题目要求正好经过 $k$ 条公路,而每个城市最多只能访问一次,城市的数量为 $n$,因此,我们最多只能经过 $n - 1$ 条公路。所以,如果 $k \ge n$,那么我们无法满足题目要求,直接返回 $-1$ 即可。 @@ -77,10 +75,6 @@ $$ -### **Python3** - - - ```python class Solution: def maximumCost(self, n: int, highways: List[List[int]], k: int) -> int: @@ -105,10 +99,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumCost(int n, int[][] highways, int k) { @@ -150,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -190,8 +178,6 @@ public: }; ``` -### **Go** - ```go func maximumCost(n int, highways [][]int, k int) int { if k >= n { @@ -233,8 +219,6 @@ func maximumCost(n int, highways [][]int, k int) int { } ``` -### **TypeScript** - ```ts function maximumCost(n: number, highways: number[][], k: number): number { if (k >= n) { @@ -279,10 +263,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/README_EN.md b/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/README_EN.md index bc8d4311fadf8..25ad7b360e7e1 100644 --- a/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/README_EN.md +++ b/solution/2200-2299/2247.Maximum Cost of Trip With K Highways/README_EN.md @@ -49,9 +49,9 @@ Note that the trip 4 -> 1 -> 0 -> 1 is not allowed because you visit th ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumCost(int n, int[][] highways, int k) { @@ -120,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +156,6 @@ public: }; ``` -### **Go** - ```go func maximumCost(n int, highways [][]int, k int) int { if k >= n { @@ -203,8 +197,6 @@ func maximumCost(n int, highways [][]int, k int) int { } ``` -### **TypeScript** - ```ts function maximumCost(n: number, highways: number[][], k: number): number { if (k >= n) { @@ -249,10 +241,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2248.Intersection of Multiple Arrays/README.md b/solution/2200-2299/2248.Intersection of Multiple Arrays/README.md index e3e04ab3e5b78..68858e3ac1f2b 100644 --- a/solution/2200-2299/2248.Intersection of Multiple Arrays/README.md +++ b/solution/2200-2299/2248.Intersection of Multiple Arrays/README.md @@ -40,9 +40,7 @@ nums[0] = [3,1,2,4,5],nums ## 解法 - - -**方法一:计数** +### 方法一:计数 遍历数组 `nums`,对于每个数组 `arr`,统计数组 `arr` 中每个数字出现的次数,然后遍历计数数组,统计出现次数等于数组 `nums` 的长度的数字,即为答案。 @@ -50,10 +48,6 @@ nums[0] = [3,1,2,4,5],nums -### **Python3** - - - ```python class Solution: def intersection(self, nums: List[List[int]]) -> List[int]: @@ -64,24 +58,6 @@ class Solution: return [x for x, v in enumerate(cnt) if v == len(nums)] ``` -```python -class Solution: - def intersection(self, nums: List[List[int]]) -> List[int]: - cnt = Counter() - ans = [] - for arr in nums: - for x in arr: - cnt[x] += 1 - if cnt[x] == len(nums): - ans.append(x) - ans.sort() - return ans -``` - -### **Java** - - - ```java class Solution { public List intersection(int[][] nums) { @@ -102,26 +78,6 @@ class Solution { } ``` -```java -class Solution { - public List intersection(int[][] nums) { - Map cnt = new HashMap<>(); - List ans = new ArrayList<>(); - for (var arr : nums) { - for (int x : arr) { - if (cnt.merge(x, 1, Integer::sum) == nums.length) { - ans.add(x); - } - } - } - Collections.sort(ans); - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -143,27 +99,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector intersection(vector>& nums) { - unordered_map cnt; - vector ans; - for (auto& arr : nums) { - for (int& x : arr) { - if (++cnt[x] == nums.size()) { - ans.push_back(x); - } - } - } - sort(ans.begin(), ans.end()); - return ans; - } -}; -``` - -### **Go** - ```go func intersection(nums [][]int) (ans []int) { cnt := [1001]int{} @@ -181,24 +116,6 @@ func intersection(nums [][]int) (ans []int) { } ``` -```go -func intersection(nums [][]int) (ans []int) { - cnt := map[int]int{} - for _, arr := range nums { - for _, x := range arr { - cnt[x]++ - if cnt[x] == len(nums) { - ans = append(ans, x) - } - } - } - sort.Ints(ans) - return -} -``` - -### **TypeScript** - ```ts function intersection(nums: number[][]): number[] { const cnt = new Array(1001).fill(0); @@ -217,24 +134,6 @@ function intersection(nums: number[][]): number[] { } ``` -```ts -function intersection(nums: number[][]): number[] { - const cnt = new Array(1001).fill(0); - const ans: number[] = []; - for (const arr of nums) { - for (const x of arr) { - if (++cnt[x] == nums.length) { - ans.push(x); - } - } - } - ans.sort((a, b) => a - b); - return ans; -} -``` - -### **PHP** - ```php class Solution { /** @@ -257,10 +156,95 @@ class Solution { } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def intersection(self, nums: List[List[int]]) -> List[int]: + cnt = Counter() + ans = [] + for arr in nums: + for x in arr: + cnt[x] += 1 + if cnt[x] == len(nums): + ans.append(x) + ans.sort() + return ans +``` + +```java +class Solution { + public List intersection(int[][] nums) { + Map cnt = new HashMap<>(); + List ans = new ArrayList<>(); + for (var arr : nums) { + for (int x : arr) { + if (cnt.merge(x, 1, Integer::sum) == nums.length) { + ans.add(x); + } + } + } + Collections.sort(ans); + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector intersection(vector>& nums) { + unordered_map cnt; + vector ans; + for (auto& arr : nums) { + for (int& x : arr) { + if (++cnt[x] == nums.size()) { + ans.push_back(x); + } + } + } + sort(ans.begin(), ans.end()); + return ans; + } +}; +``` +```go +func intersection(nums [][]int) (ans []int) { + cnt := map[int]int{} + for _, arr := range nums { + for _, x := range arr { + cnt[x]++ + if cnt[x] == len(nums) { + ans = append(ans, x) + } + } + } + sort.Ints(ans) + return +} ``` +```ts +function intersection(nums: number[][]): number[] { + const cnt = new Array(1001).fill(0); + const ans: number[] = []; + for (const arr of nums) { + for (const x of arr) { + if (++cnt[x] == nums.length) { + ans.push(x); + } + } + } + ans.sort((a, b) => a - b); + return ans; +} ``` + + diff --git a/solution/2200-2299/2248.Intersection of Multiple Arrays/README_EN.md b/solution/2200-2299/2248.Intersection of Multiple Arrays/README_EN.md index cbfc35f8736b0..d0d7f4e636555 100644 --- a/solution/2200-2299/2248.Intersection of Multiple Arrays/README_EN.md +++ b/solution/2200-2299/2248.Intersection of Multiple Arrays/README_EN.md @@ -36,9 +36,9 @@ There does not exist any integer present both in nums[0] and nums[1], so we retu ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -50,22 +50,6 @@ class Solution: return [x for x, v in enumerate(cnt) if v == len(nums)] ``` -```python -class Solution: - def intersection(self, nums: List[List[int]]) -> List[int]: - cnt = Counter() - ans = [] - for arr in nums: - for x in arr: - cnt[x] += 1 - if cnt[x] == len(nums): - ans.append(x) - ans.sort() - return ans -``` - -### **Java** - ```java class Solution { public List intersection(int[][] nums) { @@ -86,26 +70,6 @@ class Solution { } ``` -```java -class Solution { - public List intersection(int[][] nums) { - Map cnt = new HashMap<>(); - List ans = new ArrayList<>(); - for (var arr : nums) { - for (int x : arr) { - if (cnt.merge(x, 1, Integer::sum) == nums.length) { - ans.add(x); - } - } - } - Collections.sort(ans); - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -127,27 +91,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector intersection(vector>& nums) { - unordered_map cnt; - vector ans; - for (auto& arr : nums) { - for (int& x : arr) { - if (++cnt[x] == nums.size()) { - ans.push_back(x); - } - } - } - sort(ans.begin(), ans.end()); - return ans; - } -}; -``` - -### **Go** - ```go func intersection(nums [][]int) (ans []int) { cnt := [1001]int{} @@ -165,24 +108,6 @@ func intersection(nums [][]int) (ans []int) { } ``` -```go -func intersection(nums [][]int) (ans []int) { - cnt := map[int]int{} - for _, arr := range nums { - for _, x := range arr { - cnt[x]++ - if cnt[x] == len(nums) { - ans = append(ans, x) - } - } - } - sort.Ints(ans) - return -} -``` - -### **TypeScript** - ```ts function intersection(nums: number[][]): number[] { const cnt = new Array(1001).fill(0); @@ -201,24 +126,6 @@ function intersection(nums: number[][]): number[] { } ``` -```ts -function intersection(nums: number[][]): number[] { - const cnt = new Array(1001).fill(0); - const ans: number[] = []; - for (const arr of nums) { - for (const x of arr) { - if (++cnt[x] == nums.length) { - ans.push(x); - } - } - } - ans.sort((a, b) => a - b); - return ans; -} -``` - -### **PHP** - ```php class Solution { /** @@ -241,10 +148,95 @@ class Solution { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def intersection(self, nums: List[List[int]]) -> List[int]: + cnt = Counter() + ans = [] + for arr in nums: + for x in arr: + cnt[x] += 1 + if cnt[x] == len(nums): + ans.append(x) + ans.sort() + return ans ``` +```java +class Solution { + public List intersection(int[][] nums) { + Map cnt = new HashMap<>(); + List ans = new ArrayList<>(); + for (var arr : nums) { + for (int x : arr) { + if (cnt.merge(x, 1, Integer::sum) == nums.length) { + ans.add(x); + } + } + } + Collections.sort(ans); + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector intersection(vector>& nums) { + unordered_map cnt; + vector ans; + for (auto& arr : nums) { + for (int& x : arr) { + if (++cnt[x] == nums.size()) { + ans.push_back(x); + } + } + } + sort(ans.begin(), ans.end()); + return ans; + } +}; +``` + +```go +func intersection(nums [][]int) (ans []int) { + cnt := map[int]int{} + for _, arr := range nums { + for _, x := range arr { + cnt[x]++ + if cnt[x] == len(nums) { + ans = append(ans, x) + } + } + } + sort.Ints(ans) + return +} +``` + +```ts +function intersection(nums: number[][]): number[] { + const cnt = new Array(1001).fill(0); + const ans: number[] = []; + for (const arr of nums) { + for (const x of arr) { + if (++cnt[x] == nums.length) { + ans.push(x); + } + } + } + ans.sort((a, b) => a - b); + return ans; +} ``` + + diff --git a/solution/2200-2299/2249.Count Lattice Points Inside a Circle/README.md b/solution/2200-2299/2249.Count Lattice Points Inside a Circle/README.md index 0e463249b71d0..d2559fddaf62f 100644 --- a/solution/2200-2299/2249.Count Lattice Points Inside a Circle/README.md +++ b/solution/2200-2299/2249.Count Lattice Points Inside a Circle/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 枚举所有的格点,判断其是否在圆内,如果在圆内,则答案加一。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def countLatticePoints(self, circles: List[List[int]]) -> int: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countLatticePoints(int[][] circles) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go func countLatticePoints(circles [][]int) (ans int) { mx, my := 0, 0 @@ -169,8 +155,6 @@ func countLatticePoints(circles [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function countLatticePoints(circles: number[][]): number { let mx = 0; @@ -196,10 +180,6 @@ function countLatticePoints(circles: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2249.Count Lattice Points Inside a Circle/README_EN.md b/solution/2200-2299/2249.Count Lattice Points Inside a Circle/README_EN.md index bf5c64d4570b4..8f7f7612d3e71 100644 --- a/solution/2200-2299/2249.Count Lattice Points Inside a Circle/README_EN.md +++ b/solution/2200-2299/2249.Count Lattice Points Inside a Circle/README_EN.md @@ -48,9 +48,9 @@ Some of them are (0, 2), (2, 0), (2, 4), (3, 2), and (4, 4). ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countLatticePoints(int[][] circles) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func countLatticePoints(circles [][]int) (ans int) { mx, my := 0, 0 @@ -147,10 +141,31 @@ func countLatticePoints(circles [][]int) (ans int) { } ``` -### **...** - -``` - +```ts +function countLatticePoints(circles: number[][]): number { + let mx = 0; + let my = 0; + for (const [x, y, r] of circles) { + mx = Math.max(mx, x + r); + my = Math.max(my, y + r); + } + let ans = 0; + for (let i = 0; i <= mx; ++i) { + for (let j = 0; j <= my; ++j) { + for (const [x, y, r] of circles) { + const dx = i - x; + const dy = j - y; + if (dx * dx + dy * dy <= r * r) { + ++ans; + break; + } + } + } + } + return ans; +} ``` + + diff --git a/solution/2200-2299/2250.Count Number of Rectangles Containing Each Point/README.md b/solution/2200-2299/2250.Count Number of Rectangles Containing Each Point/README.md index a55725eabe6e5..f2504f1db902a 100644 --- a/solution/2200-2299/2250.Count Number of Rectangles Containing Each Point/README.md +++ b/solution/2200-2299/2250.Count Number of Rectangles Containing Each Point/README.md @@ -61,16 +61,10 @@ ## 解法 - - -**方法一:排序 + 二分** +### 方法一:排序 + 二分 -### **Python3** - - - ```python class Solution: def countRectangles( @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] countRectangles(int[][] rectangles, int[][] points) { @@ -132,43 +122,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function countRectangles(rectangles: number[][], points: number[][]): number[] { - const n = 101; - let ymap = Array.from({ length: n }, v => []); - for (let [x, y] of rectangles) { - ymap[y].push(x); - } - for (let nums of ymap) { - nums.sort((a, b) => a - b); - } - let ans = []; - for (let [x, y] of points) { - let count = 0; - for (let h = y; h < n; h++) { - const nums = ymap[h]; - let left = 0, - right = nums.length; - while (left < right) { - let mid = (left + right) >> 1; - if (x > nums[mid]) { - left = mid + 1; - } else { - right = mid; - } - } - count += nums.length - right; - } - ans.push(count); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -192,8 +145,6 @@ public: }; ``` -### **Go** - ```go func countRectangles(rectangles [][]int, points [][]int) []int { n := 101 @@ -227,10 +178,39 @@ func countRectangles(rectangles [][]int, points [][]int) []int { } ``` -### **...** - -``` - +```ts +function countRectangles(rectangles: number[][], points: number[][]): number[] { + const n = 101; + let ymap = Array.from({ length: n }, v => []); + for (let [x, y] of rectangles) { + ymap[y].push(x); + } + for (let nums of ymap) { + nums.sort((a, b) => a - b); + } + let ans = []; + for (let [x, y] of points) { + let count = 0; + for (let h = y; h < n; h++) { + const nums = ymap[h]; + let left = 0, + right = nums.length; + while (left < right) { + let mid = (left + right) >> 1; + if (x > nums[mid]) { + left = mid + 1; + } else { + right = mid; + } + } + count += nums.length - right; + } + ans.push(count); + } + return ans; +} ``` + + diff --git a/solution/2200-2299/2250.Count Number of Rectangles Containing Each Point/README_EN.md b/solution/2200-2299/2250.Count Number of Rectangles Containing Each Point/README_EN.md index efe64943ff56c..13493554be875 100644 --- a/solution/2200-2299/2250.Count Number of Rectangles Containing Each Point/README_EN.md +++ b/solution/2200-2299/2250.Count Number of Rectangles Containing Each Point/README_EN.md @@ -55,9 +55,9 @@ Therefore, we return [1, 3]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,8 +79,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] countRectangles(int[][] rectangles, int[][] points) { @@ -118,43 +116,6 @@ class Solution { } ``` -### **TypeScript** - -```ts -function countRectangles(rectangles: number[][], points: number[][]): number[] { - const n = 101; - let ymap = Array.from({ length: n }, v => []); - for (let [x, y] of rectangles) { - ymap[y].push(x); - } - for (let nums of ymap) { - nums.sort((a, b) => a - b); - } - let ans = []; - for (let [x, y] of points) { - let count = 0; - for (let h = y; h < n; h++) { - const nums = ymap[h]; - let left = 0, - right = nums.length; - while (left < right) { - let mid = (left + right) >> 1; - if (x > nums[mid]) { - left = mid + 1; - } else { - right = mid; - } - } - count += nums.length - right; - } - ans.push(count); - } - return ans; -} -``` - -### **C++** - ```cpp class Solution { public: @@ -178,8 +139,6 @@ public: }; ``` -### **Go** - ```go func countRectangles(rectangles [][]int, points [][]int) []int { n := 101 @@ -213,10 +172,39 @@ func countRectangles(rectangles [][]int, points [][]int) []int { } ``` -### **...** - -``` - +```ts +function countRectangles(rectangles: number[][], points: number[][]): number[] { + const n = 101; + let ymap = Array.from({ length: n }, v => []); + for (let [x, y] of rectangles) { + ymap[y].push(x); + } + for (let nums of ymap) { + nums.sort((a, b) => a - b); + } + let ans = []; + for (let [x, y] of points) { + let count = 0; + for (let h = y; h < n; h++) { + const nums = ymap[h]; + let left = 0, + right = nums.length; + while (left < right) { + let mid = (left + right) >> 1; + if (x > nums[mid]) { + left = mid + 1; + } else { + right = mid; + } + } + count += nums.length - right; + } + ans.push(count); + } + return ans; +} ``` + + diff --git a/solution/2200-2299/2251.Number of Flowers in Full Bloom/README.md b/solution/2200-2299/2251.Number of Flowers in Full Bloom/README.md index faaf1d4c15d33..af544cc922a8d 100644 --- a/solution/2200-2299/2251.Number of Flowers in Full Bloom/README.md +++ b/solution/2200-2299/2251.Number of Flowers in Full Bloom/README.md @@ -48,26 +48,14 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 我们将花按照开始时间和结束时间分别排序,然后对于每个人,我们可以使用二分查找来找到他们到达时在花期内花的数目。就是说,找出在每个人到达时,已经开花的花的数目,减去在每个人到达时,已经凋谢的花的数目,即可得到答案。 时间复杂度 $O((m + n) \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 和 $m$ 分别是数组 $flowers$ 和 $people$ 的长度。 -**方法二:差分 + 排序 + 离线查询** - -我们可以利用差分来维护每个时间点的花的数目。接下来,我们将 $people$ 按照到达时间从小到大排序,在每个人到达时,我们对差分数组进行前缀和运算,就可以得到答案。 - -时间复杂度 $O(m \times \log m + n \times \log n)$,空间复杂度 $O(n + m)$。其中 $n$ 和 $m$ 分别是数组 $flowers$ 和 $people$ 的长度。 - -### **Python3** - - - ```python class Solution: def fullBloomFlowers( @@ -77,31 +65,6 @@ class Solution: return [bisect_right(start, p) - bisect_left(end, p) for p in people] ``` -```python -class Solution: - def fullBloomFlowers( - self, flowers: List[List[int]], people: List[int] - ) -> List[int]: - d = defaultdict(int) - for st, ed in flowers: - d[st] += 1 - d[ed + 1] -= 1 - ts = sorted(d) - s = i = 0 - m = len(people) - ans = [0] * m - for t, j in sorted(zip(people, range(m))): - while i < len(ts) and ts[i] <= t: - s += d[ts[i]] - i += 1 - ans[j] = s - return ans -``` - -### **Java** - - - ```java class Solution { public int[] fullBloomFlowers(int[][] flowers, int[] people) { @@ -137,36 +100,6 @@ class Solution { } ``` -```java -class Solution { - public int[] fullBloomFlowers(int[][] flowers, int[] people) { - TreeMap d = new TreeMap<>(); - for (int[] f : flowers) { - d.merge(f[0], 1, Integer::sum); - d.merge(f[1] + 1, -1, Integer::sum); - } - int s = 0; - int m = people.length; - Integer[] idx = new Integer[m]; - for (int i = 0; i < m; i++) { - idx[i] = i; - } - Arrays.sort(idx, Comparator.comparingInt(i -> people[i])); - int[] ans = new int[m]; - for (int i : idx) { - int t = people[i]; - while (!d.isEmpty() && d.firstKey() <= t) { - s += d.pollFirstEntry().getValue(); - } - ans[i] = s; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -191,38 +124,61 @@ public: }; ``` -```cpp -class Solution { -public: - vector fullBloomFlowers(vector>& flowers, vector& people) { - map d; - for (auto& f : flowers) { - d[f[0]]++; - d[f[1] + 1]--; - } - int m = people.size(); - vector idx(m); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { - return people[i] < people[j]; - }); - vector ans(m); - int s = 0; - for (int i : idx) { - int t = people[i]; - while (!d.empty() && d.begin()->first <= t) { - s += d.begin()->second; - d.erase(d.begin()); - } - ans[i] = s; +```go +func fullBloomFlowers(flowers [][]int, people []int) (ans []int) { + n := len(flowers) + start := make([]int, n) + end := make([]int, n) + for i, f := range flowers { + start[i] = f[0] + end[i] = f[1] + } + sort.Ints(start) + sort.Ints(end) + for _, p := range people { + r := sort.SearchInts(start, p+1) + l := sort.SearchInts(end, p) + ans = append(ans, r-l) + } + return +} +``` + +```ts +function fullBloomFlowers(flowers: number[][], people: number[]): number[] { + const n = flowers.length; + const start = new Array(n).fill(0); + const end = new Array(n).fill(0); + for (let i = 0; i < n; ++i) { + start[i] = flowers[i][0]; + end[i] = flowers[i][1]; + } + start.sort((a, b) => a - b); + end.sort((a, b) => a - b); + const ans: number[] = []; + for (const p of people) { + const r = search(start, p + 1); + const l = search(end, p); + ans.push(r - l); + } + return ans; +} + +function search(nums: number[], x: number): number { + let l = 0; + let r = nums.length; + while (l < r) { + const mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; } - return ans; } -}; + return l; +} ``` -### **Rust** - ```rust use std::collections::BTreeMap; @@ -274,28 +230,95 @@ impl Solution { } ``` -### **Go** + -```go -func fullBloomFlowers(flowers [][]int, people []int) (ans []int) { - n := len(flowers) - start := make([]int, n) - end := make([]int, n) - for i, f := range flowers { - start[i] = f[0] - end[i] = f[1] - } - sort.Ints(start) - sort.Ints(end) - for _, p := range people { - r := sort.SearchInts(start, p+1) - l := sort.SearchInts(end, p) - ans = append(ans, r-l) - } - return +### 方法二:差分 + 排序 + 离线查询 + +我们可以利用差分来维护每个时间点的花的数目。接下来,我们将 $people$ 按照到达时间从小到大排序,在每个人到达时,我们对差分数组进行前缀和运算,就可以得到答案。 + +时间复杂度 $O(m \times \log m + n \times \log n)$,空间复杂度 $O(n + m)$。其中 $n$ 和 $m$ 分别是数组 $flowers$ 和 $people$ 的长度。 + + + +```python +class Solution: + def fullBloomFlowers( + self, flowers: List[List[int]], people: List[int] + ) -> List[int]: + d = defaultdict(int) + for st, ed in flowers: + d[st] += 1 + d[ed + 1] -= 1 + ts = sorted(d) + s = i = 0 + m = len(people) + ans = [0] * m + for t, j in sorted(zip(people, range(m))): + while i < len(ts) and ts[i] <= t: + s += d[ts[i]] + i += 1 + ans[j] = s + return ans +``` + +```java +class Solution { + public int[] fullBloomFlowers(int[][] flowers, int[] people) { + TreeMap d = new TreeMap<>(); + for (int[] f : flowers) { + d.merge(f[0], 1, Integer::sum); + d.merge(f[1] + 1, -1, Integer::sum); + } + int s = 0; + int m = people.length; + Integer[] idx = new Integer[m]; + for (int i = 0; i < m; i++) { + idx[i] = i; + } + Arrays.sort(idx, Comparator.comparingInt(i -> people[i])); + int[] ans = new int[m]; + for (int i : idx) { + int t = people[i]; + while (!d.isEmpty() && d.firstKey() <= t) { + s += d.pollFirstEntry().getValue(); + } + ans[i] = s; + } + return ans; + } } ``` +```cpp +class Solution { +public: + vector fullBloomFlowers(vector>& flowers, vector& people) { + map d; + for (auto& f : flowers) { + d[f[0]]++; + d[f[1] + 1]--; + } + int m = people.size(); + vector idx(m); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return people[i] < people[j]; + }); + vector ans(m); + int s = 0; + for (int i : idx) { + int t = people[i]; + while (!d.empty() && d.begin()->first <= t) { + s += d.begin()->second; + d.erase(d.begin()); + } + ans[i] = s; + } + return ans; + } +}; +``` + ```go func fullBloomFlowers(flowers [][]int, people []int) []int { d := map[int]int{} @@ -328,43 +351,6 @@ func fullBloomFlowers(flowers [][]int, people []int) []int { } ``` -### **TypeScript** - -```ts -function fullBloomFlowers(flowers: number[][], people: number[]): number[] { - const n = flowers.length; - const start = new Array(n).fill(0); - const end = new Array(n).fill(0); - for (let i = 0; i < n; ++i) { - start[i] = flowers[i][0]; - end[i] = flowers[i][1]; - } - start.sort((a, b) => a - b); - end.sort((a, b) => a - b); - const ans: number[] = []; - for (const p of people) { - const r = search(start, p + 1); - const l = search(end, p); - ans.push(r - l); - } - return ans; -} - -function search(nums: number[], x: number): number { - let l = 0; - let r = nums.length; - while (l < r) { - const mid = (l + r) >> 1; - if (nums[mid] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; -} -``` - ```ts function fullBloomFlowers(flowers: number[][], people: number[]): number[] { const d: Map = new Map(); @@ -390,10 +376,6 @@ function fullBloomFlowers(flowers: number[][], people: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2251.Number of Flowers in Full Bloom/README_EN.md b/solution/2200-2299/2251.Number of Flowers in Full Bloom/README_EN.md index cafa056ca2bb5..fa1d76329eb36 100644 --- a/solution/2200-2299/2251.Number of Flowers in Full Bloom/README_EN.md +++ b/solution/2200-2299/2251.Number of Flowers in Full Bloom/README_EN.md @@ -40,21 +40,9 @@ For each person, we return the number of flowers in full bloom during their arri ## Solutions - - -**Solution 1: Sort + Binary Search** - -We sort the flowers by their start and end time respectively, and then for each person, we can use binary search to find the number of flowers they bloom during the flowering period. That is, find the number of flowers that have bloomed when each person arrives, minus the number of flowers that have withered when each person arrives, to get the answer. - -The time complexity is $O((m + n) \times \log n)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of arrays $flowers$ and $people$ respectively. - -**Solution 2: Difference + Sort + Offline Query** +### Solution 1 -We can use the difference to maintain the number of flowers at each time point. Next, we sort $people$ in ascending order of arrival time, and at each person's arrival, we perform a prefix sum operation on the difference array to get the answer. - -The time complexity is $O(m \times \log m + n \times \log n)$, and the space complexity is $O(n + m)$. Where $n$ and $m$ are the lengths of arrays $flowers$ and $people$ respectively. - -### **Python3** + ```python class Solution: @@ -65,29 +53,6 @@ class Solution: return [bisect_right(start, p) - bisect_left(end, p) for p in people] ``` -```python -class Solution: - def fullBloomFlowers( - self, flowers: List[List[int]], people: List[int] - ) -> List[int]: - d = defaultdict(int) - for st, ed in flowers: - d[st] += 1 - d[ed + 1] -= 1 - ts = sorted(d) - s = i = 0 - m = len(people) - ans = [0] * m - for t, j in sorted(zip(people, range(m))): - while i < len(ts) and ts[i] <= t: - s += d[ts[i]] - i += 1 - ans[j] = s - return ans -``` - -### **Java** - ```java class Solution { public int[] fullBloomFlowers(int[][] flowers, int[] people) { @@ -123,36 +88,6 @@ class Solution { } ``` -```java -class Solution { - public int[] fullBloomFlowers(int[][] flowers, int[] people) { - TreeMap d = new TreeMap<>(); - for (int[] f : flowers) { - d.merge(f[0], 1, Integer::sum); - d.merge(f[1] + 1, -1, Integer::sum); - } - int s = 0; - int m = people.length; - Integer[] idx = new Integer[m]; - for (int i = 0; i < m; i++) { - idx[i] = i; - } - Arrays.sort(idx, Comparator.comparingInt(i -> people[i])); - int[] ans = new int[m]; - for (int i : idx) { - int t = people[i]; - while (!d.isEmpty() && d.firstKey() <= t) { - s += d.pollFirstEntry().getValue(); - } - ans[i] = s; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -177,38 +112,61 @@ public: }; ``` -```cpp -class Solution { -public: - vector fullBloomFlowers(vector>& flowers, vector& people) { - map d; - for (auto& f : flowers) { - d[f[0]]++; - d[f[1] + 1]--; - } - int m = people.size(); - vector idx(m); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { - return people[i] < people[j]; - }); - vector ans(m); - int s = 0; - for (int i : idx) { - int t = people[i]; - while (!d.empty() && d.begin()->first <= t) { - s += d.begin()->second; - d.erase(d.begin()); - } - ans[i] = s; +```go +func fullBloomFlowers(flowers [][]int, people []int) (ans []int) { + n := len(flowers) + start := make([]int, n) + end := make([]int, n) + for i, f := range flowers { + start[i] = f[0] + end[i] = f[1] + } + sort.Ints(start) + sort.Ints(end) + for _, p := range people { + r := sort.SearchInts(start, p+1) + l := sort.SearchInts(end, p) + ans = append(ans, r-l) + } + return +} +``` + +```ts +function fullBloomFlowers(flowers: number[][], people: number[]): number[] { + const n = flowers.length; + const start = new Array(n).fill(0); + const end = new Array(n).fill(0); + for (let i = 0; i < n; ++i) { + start[i] = flowers[i][0]; + end[i] = flowers[i][1]; + } + start.sort((a, b) => a - b); + end.sort((a, b) => a - b); + const ans: number[] = []; + for (const p of people) { + const r = search(start, p + 1); + const l = search(end, p); + ans.push(r - l); + } + return ans; +} + +function search(nums: number[], x: number): number { + let l = 0; + let r = nums.length; + while (l < r) { + const mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; } - return ans; } -}; + return l; +} ``` -### **Rust** - ```rust use std::collections::BTreeMap; @@ -260,28 +218,91 @@ impl Solution { } ``` -### **Go** + + +### Solution 2 -```go -func fullBloomFlowers(flowers [][]int, people []int) (ans []int) { - n := len(flowers) - start := make([]int, n) - end := make([]int, n) - for i, f := range flowers { - start[i] = f[0] - end[i] = f[1] - } - sort.Ints(start) - sort.Ints(end) - for _, p := range people { - r := sort.SearchInts(start, p+1) - l := sort.SearchInts(end, p) - ans = append(ans, r-l) - } - return + + +```python +class Solution: + def fullBloomFlowers( + self, flowers: List[List[int]], people: List[int] + ) -> List[int]: + d = defaultdict(int) + for st, ed in flowers: + d[st] += 1 + d[ed + 1] -= 1 + ts = sorted(d) + s = i = 0 + m = len(people) + ans = [0] * m + for t, j in sorted(zip(people, range(m))): + while i < len(ts) and ts[i] <= t: + s += d[ts[i]] + i += 1 + ans[j] = s + return ans +``` + +```java +class Solution { + public int[] fullBloomFlowers(int[][] flowers, int[] people) { + TreeMap d = new TreeMap<>(); + for (int[] f : flowers) { + d.merge(f[0], 1, Integer::sum); + d.merge(f[1] + 1, -1, Integer::sum); + } + int s = 0; + int m = people.length; + Integer[] idx = new Integer[m]; + for (int i = 0; i < m; i++) { + idx[i] = i; + } + Arrays.sort(idx, Comparator.comparingInt(i -> people[i])); + int[] ans = new int[m]; + for (int i : idx) { + int t = people[i]; + while (!d.isEmpty() && d.firstKey() <= t) { + s += d.pollFirstEntry().getValue(); + } + ans[i] = s; + } + return ans; + } } ``` +```cpp +class Solution { +public: + vector fullBloomFlowers(vector>& flowers, vector& people) { + map d; + for (auto& f : flowers) { + d[f[0]]++; + d[f[1] + 1]--; + } + int m = people.size(); + vector idx(m); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return people[i] < people[j]; + }); + vector ans(m); + int s = 0; + for (int i : idx) { + int t = people[i]; + while (!d.empty() && d.begin()->first <= t) { + s += d.begin()->second; + d.erase(d.begin()); + } + ans[i] = s; + } + return ans; + } +}; +``` + ```go func fullBloomFlowers(flowers [][]int, people []int) []int { d := map[int]int{} @@ -314,43 +335,6 @@ func fullBloomFlowers(flowers [][]int, people []int) []int { } ``` -### **TypeScript** - -```ts -function fullBloomFlowers(flowers: number[][], people: number[]): number[] { - const n = flowers.length; - const start = new Array(n).fill(0); - const end = new Array(n).fill(0); - for (let i = 0; i < n; ++i) { - start[i] = flowers[i][0]; - end[i] = flowers[i][1]; - } - start.sort((a, b) => a - b); - end.sort((a, b) => a - b); - const ans: number[] = []; - for (const p of people) { - const r = search(start, p + 1); - const l = search(end, p); - ans.push(r - l); - } - return ans; -} - -function search(nums: number[], x: number): number { - let l = 0; - let r = nums.length; - while (l < r) { - const mid = (l + r) >> 1; - if (nums[mid] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l; -} -``` - ```ts function fullBloomFlowers(flowers: number[][], people: number[]): number[] { const d: Map = new Map(); @@ -376,10 +360,6 @@ function fullBloomFlowers(flowers: number[][], people: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2252.Dynamic Pivoting of a Table/README.md b/solution/2200-2299/2252.Dynamic Pivoting of a Table/README.md index 715c75692215a..b87c266229d1e 100644 --- a/solution/2200-2299/2252.Dynamic Pivoting of a Table/README.md +++ b/solution/2200-2299/2252.Dynamic Pivoting of a Table/README.md @@ -67,14 +67,10 @@ Products 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql CREATE PROCEDURE PivotProducts() BEGIN @@ -96,3 +92,5 @@ END ``` + + diff --git a/solution/2200-2299/2252.Dynamic Pivoting of a Table/README_EN.md b/solution/2200-2299/2252.Dynamic Pivoting of a Table/README_EN.md index a6233eac3db41..c452e7f7f53cc 100644 --- a/solution/2200-2299/2252.Dynamic Pivoting of a Table/README_EN.md +++ b/solution/2200-2299/2252.Dynamic Pivoting of a Table/README_EN.md @@ -65,9 +65,9 @@ For product 3, the price is 1000 in Shop and 1900 in Souq. It is not sold in the ## Solutions - +### Solution 1 -### **SQL** + ```sql CREATE PROCEDURE PivotProducts() @@ -90,3 +90,5 @@ END ``` + + diff --git a/solution/2200-2299/2253.Dynamic Unpivoting of a Table/README.md b/solution/2200-2299/2253.Dynamic Unpivoting of a Table/README.md index 2219d4ccba404..ee067d2eede72 100644 --- a/solution/2200-2299/2253.Dynamic Unpivoting of a Table/README.md +++ b/solution/2200-2299/2253.Dynamic Unpivoting of a Table/README.md @@ -70,14 +70,10 @@ Products 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql CREATE PROCEDURE UnpivotProducts() BEGIN @@ -109,3 +105,5 @@ END; ``` + + diff --git a/solution/2200-2299/2253.Dynamic Unpivoting of a Table/README_EN.md b/solution/2200-2299/2253.Dynamic Unpivoting of a Table/README_EN.md index 7b0c972e2caef..8eadd8581b6e5 100644 --- a/solution/2200-2299/2253.Dynamic Unpivoting of a Table/README_EN.md +++ b/solution/2200-2299/2253.Dynamic Unpivoting of a Table/README_EN.md @@ -68,9 +68,9 @@ Product 3 is sold in Shop and Souq with prices of 1000 and 1900. ## Solutions - +### Solution 1 -### **SQL** + ```sql CREATE PROCEDURE UnpivotProducts() @@ -103,3 +103,5 @@ END; ``` + + diff --git a/solution/2200-2299/2254.Design Video Sharing Platform/README.md b/solution/2200-2299/2254.Design Video Sharing Platform/README.md index 17d29b2cc33d0..b41d44e8a6995 100644 --- a/solution/2200-2299/2254.Design Video Sharing Platform/README.md +++ b/solution/2200-2299/2254.Design Video Sharing Platform/README.md @@ -89,36 +89,4 @@ videoSharingPlatform.getViews(0); // 没有视频与 videoId 0 相关 ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2200-2299/2254.Design Video Sharing Platform/README_EN.md b/solution/2200-2299/2254.Design Video Sharing Platform/README_EN.md index 73a2ad040441e..ed84a54b8443e 100644 --- a/solution/2200-2299/2254.Design Video Sharing Platform/README_EN.md +++ b/solution/2200-2299/2254.Design Video Sharing Platform/README_EN.md @@ -85,30 +85,4 @@ videoSharingPlatform.getViews(0); // There is no video associated wit ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2200-2299/2255.Count Prefixes of a Given String/README.md b/solution/2200-2299/2255.Count Prefixes of a Given String/README.md index 48e4e38814bde..510c2483209a2 100644 --- a/solution/2200-2299/2255.Count Prefixes of a Given String/README.md +++ b/solution/2200-2299/2255.Count Prefixes of a Given String/README.md @@ -43,9 +43,7 @@ words 中是 s = "abc" 前缀的字符串为: ## 解法 - - -**方法一:遍历计数** +### 方法一:遍历计数 我们直接遍历数组 $words$,对于每个字符串 $w$,判断 $s$ 是否以 $w$ 为前缀,如果是则答案加一。 @@ -55,20 +53,12 @@ words 中是 s = "abc" 前缀的字符串为: -### **Python3** - - - ```python class Solution: def countPrefixes(self, words: List[str], s: str) -> int: return sum(s.startswith(w) for w in words) ``` -### **Java** - - - ```java class Solution { public int countPrefixes(String[] words, String s) { @@ -83,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +86,6 @@ public: }; ``` -### **Go** - ```go func countPrefixes(words []string, s string) (ans int) { for _, w := range words { @@ -111,18 +97,12 @@ func countPrefixes(words []string, s string) (ans int) { } ``` -### **TypeScript** - ```ts function countPrefixes(words: string[], s: string): number { return words.filter(w => s.startsWith(w)).length; } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2255.Count Prefixes of a Given String/README_EN.md b/solution/2200-2299/2255.Count Prefixes of a Given String/README_EN.md index 776cfb82fe3db..c64f2b825ab52 100644 --- a/solution/2200-2299/2255.Count Prefixes of a Given String/README_EN.md +++ b/solution/2200-2299/2255.Count Prefixes of a Given String/README_EN.md @@ -41,7 +41,7 @@ Note that the same string can occur multiple times in words, and it should be co ## Solutions -**Solution 1: Traversal Counting** +### Solution 1: Traversal Counting We directly traverse the array words, and for each string w, we check if s starts with w as a prefix. If it does, we increment the answer by one. @@ -51,16 +51,12 @@ The time complexity is $O(m \times n)$, where $m$ and $n$ are the lengths of the -### **Python3** - ```python class Solution: def countPrefixes(self, words: List[str], s: str) -> int: return sum(s.startswith(w) for w in words) ``` -### **Java** - ```java class Solution { public int countPrefixes(String[] words, String s) { @@ -75,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,8 +84,6 @@ public: }; ``` -### **Go** - ```go func countPrefixes(words []string, s string) (ans int) { for _, w := range words { @@ -103,18 +95,12 @@ func countPrefixes(words []string, s string) (ans int) { } ``` -### **TypeScript** - ```ts function countPrefixes(words: string[], s: string): number { return words.filter(w => s.startsWith(w)).length; } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2256.Minimum Average Difference/README.md b/solution/2200-2299/2256.Minimum Average Difference/README.md index 75b8014f2c2e0..205c333d7b61a 100644 --- a/solution/2200-2299/2256.Minimum Average Difference/README.md +++ b/solution/2200-2299/2256.Minimum Average Difference/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:遍历** +### 方法一:遍历 我们直接遍历数组 $nums$,对于每个下标 $i$,维护前 $i + 1$ 个元素的和 $pre$ 和后 $n - i - 1$ 个元素的和 $suf$,计算平均差的绝对值 $t$,如果 $t$ 小于当前最小值 $mi$,则更新答案 $ans = i$ 和最小值 $mi = t$。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def minimumAverageDifference(self, nums: List[int]) -> int: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumAverageDifference(int[] nums) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +135,6 @@ public: }; ``` -### **Go** - ```go func minimumAverageDifference(nums []int) (ans int) { n := len(nums) @@ -181,8 +167,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minimumAverageDifference(nums: number[]): number { const n = nums.length; @@ -205,10 +189,6 @@ function minimumAverageDifference(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2256.Minimum Average Difference/README_EN.md b/solution/2200-2299/2256.Minimum Average Difference/README_EN.md index 8982a96d0d5f5..b74b8bf81d95c 100644 --- a/solution/2200-2299/2256.Minimum Average Difference/README_EN.md +++ b/solution/2200-2299/2256.Minimum Average Difference/README_EN.md @@ -54,7 +54,7 @@ The average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0. ## Solutions -**Solution 1: Traverse** +### Solution 1: Traverse We directly traverse the array $nums$. For each index $i$, we maintain the sum of the first $i+1$ elements $pre$ and the sum of the last $n-i-1$ elements $suf$. We calculate the absolute difference of the average of the first $i+1$ elements and the average of the last $n-i-1$ elements, denoted as $t$. If $t$ is less than the current minimum value $mi$, we update the answer $ans=i$ and the minimum value $mi=t$. @@ -64,8 +64,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def minimumAverageDifference(self, nums: List[int]) -> int: @@ -83,8 +81,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumAverageDifference(int[] nums) { @@ -111,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +133,6 @@ public: }; ``` -### **Go** - ```go func minimumAverageDifference(nums []int) (ans int) { n := len(nums) @@ -173,8 +165,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minimumAverageDifference(nums: number[]): number { const n = nums.length; @@ -197,10 +187,6 @@ function minimumAverageDifference(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2257.Count Unguarded Cells in the Grid/README.md b/solution/2200-2299/2257.Count Unguarded Cells in the Grid/README.md index 3b9e9b338ffaa..054cf448d9a47 100644 --- a/solution/2200-2299/2257.Count Unguarded Cells in the Grid/README.md +++ b/solution/2200-2299/2257.Count Unguarded Cells in the Grid/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们创建一个 $m \times n$ 的二维数组 $g$,其中 $g[i][j]$ 表示第 $i$ 行第 $j$ 列的格子。初始时 $g[i][j]$ 的值为 $0$,表示该格子没有被保卫。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def countUnguarded( @@ -91,10 +85,6 @@ class Solution: return sum(v == 0 for row in g for v in row) ``` -### **Java** - - - ```java class Solution { public int countUnguarded(int m, int n, int[][] guards, int[][] walls) { @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -165,8 +153,6 @@ public: }; ``` -### **Go** - ```go func countUnguarded(m int, n int, guards [][]int, walls [][]int) (ans int) { g := make([][]int, m) @@ -201,8 +187,6 @@ func countUnguarded(m int, n int, guards [][]int, walls [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function countUnguarded(m: number, n: number, guards: number[][], walls: number[][]): number { const g: number[][] = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); @@ -234,10 +218,6 @@ function countUnguarded(m: number, n: number, guards: number[][], walls: number[ } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2257.Count Unguarded Cells in the Grid/README_EN.md b/solution/2200-2299/2257.Count Unguarded Cells in the Grid/README_EN.md index 4b73f111af0aa..46275c91a27fb 100644 --- a/solution/2200-2299/2257.Count Unguarded Cells in the Grid/README_EN.md +++ b/solution/2200-2299/2257.Count Unguarded Cells in the Grid/README_EN.md @@ -45,7 +45,7 @@ There are a total of 4 unguarded cells, so we return 4. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We create a two-dimensional array $g$ of size $m \times n$, where $g[i][j]$ represents the cell in row $i$ and column $j$. Initially, the value of $g[i][j]$ is $0$, indicating that the cell is not guarded. @@ -59,8 +59,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times -### **Python3** - ```python class Solution: def countUnguarded( @@ -81,8 +79,6 @@ class Solution: return sum(v == 0 for row in g for v in row) ``` -### **Java** - ```java class Solution { public int countUnguarded(int m, int n, int[][] guards, int[][] walls) { @@ -118,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +147,6 @@ public: }; ``` -### **Go** - ```go func countUnguarded(m int, n int, guards [][]int, walls [][]int) (ans int) { g := make([][]int, m) @@ -189,8 +181,6 @@ func countUnguarded(m int, n int, guards [][]int, walls [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function countUnguarded(m: number, n: number, guards: number[][], walls: number[][]): number { const g: number[][] = Array.from({ length: m }, () => Array.from({ length: n }, () => 0)); @@ -222,10 +212,6 @@ function countUnguarded(m: number, n: number, guards: number[][], walls: number[ } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2258.Escape the Spreading Fire/README.md b/solution/2200-2299/2258.Escape the Spreading Fire/README.md index cc9f2ab8650df..89fc1424aca32 100644 --- a/solution/2200-2299/2258.Escape the Spreading Fire/README.md +++ b/solution/2200-2299/2258.Escape the Spreading Fire/README.md @@ -71,9 +71,7 @@ ## 解法 - - -**方法一:二分查找 + BFS** +### 方法一:二分查找 + BFS 我们注意到,如果一个停留时间 $t$ 满足条件,那么所有小于 $t$ 的时间也都满足条件。因此我们可以考虑使用二分查找的方法找到最大的满足条件的时间。 @@ -85,10 +83,6 @@ -### **Python3** - - - ```python class Solution: def maximumMinutes(self, grid: List[List[int]]) -> int: @@ -155,10 +149,6 @@ class Solution: return int(1e9) if l == m * n else l ``` -### **Java** - - - ```java class Solution { private int[][] grid; @@ -248,8 +238,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -329,8 +317,6 @@ public: }; ``` -### **Go** - ```go func maximumMinutes(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -414,8 +400,6 @@ func maximumMinutes(grid [][]int) int { } ``` -### **TypeScript** - ```ts function maximumMinutes(grid: number[][]): number { const m = grid.length; @@ -500,10 +484,6 @@ function maximumMinutes(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2258.Escape the Spreading Fire/README_EN.md b/solution/2200-2299/2258.Escape the Spreading Fire/README_EN.md index a9de4a24f2003..6674458e126c1 100644 --- a/solution/2200-2299/2258.Escape the Spreading Fire/README_EN.md +++ b/solution/2200-2299/2258.Escape the Spreading Fire/README_EN.md @@ -64,7 +64,7 @@ Thus, 109 is returned. ## Solutions -**Solution 1: Binary Search + BFS** +### Solution 1: Binary Search + BFS We notice that if a stay time $t$ satisfies the condition, then all stay times less than $t$ also satisfy the condition. Therefore, we can consider using binary search to find the maximum stay time that satisfies the condition. @@ -76,8 +76,6 @@ The time complexity is $O(m \times n \times \log (m \times n))$, and the space c -### **Python3** - ```python class Solution: def maximumMinutes(self, grid: List[List[int]]) -> int: @@ -144,8 +142,6 @@ class Solution: return int(1e9) if l == m * n else l ``` -### **Java** - ```java class Solution { private int[][] grid; @@ -235,8 +231,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -316,8 +310,6 @@ public: }; ``` -### **Go** - ```go func maximumMinutes(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -401,8 +393,6 @@ func maximumMinutes(grid [][]int) int { } ``` -### **TypeScript** - ```ts function maximumMinutes(grid: number[][]): number { const m = grid.length; @@ -487,10 +477,6 @@ function maximumMinutes(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/README.md b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/README.md index 2388359937ca8..988bc78e42784 100644 --- a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/README.md +++ b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/README.md @@ -51,28 +51,14 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 我们可以枚举字符串 $number$ 的所有位置 $i$,如果 $number[i] = digit$,那么我们取 $number$ 的前缀 $number[0:i]$ 和后缀 $number[i+1:]$ 拼接起来,即为移除 $number[i]$ 后的结果。我们取所有可能的结果中最大的即可。 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $number$ 的长度。 -**方法二:贪心** - -我们可以枚举字符串 $number$ 的所有位置 $i$,如果 $number[i] = digit$,记录 $digit$ 最后一次出现的位置 $last$,并且如果 $i + 1 \lt n$ 且 $number[i] \lt number[i + 1]$,那么我们可以直接返回 $number[0:i] + number[i+1:]$,即为移除 $number[i]$ 后的结果。这是因为如果 $number[i] < number[i + 1]$,那么移除 $number[i]$ 后,结果一定会更大。 - -遍历结束,我们返回 $number[0:last] + number[last+1:]$ 即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $number$ 的长度。 - -### **Python3** - - - ```python class Solution: def removeDigit(self, number: str, digit: str) -> str: @@ -81,23 +67,6 @@ class Solution: ) ``` -```python -class Solution: - def removeDigit(self, number: str, digit: str) -> str: - last = -1 - n = len(number) - for i, d in enumerate(number): - if d == digit: - last = i - if i + 1 < n and d < number[i + 1]: - break - return number[:last] + number[last + 1 :] -``` - -### **Java** - - - ```java class Solution { public String removeDigit(String number, char digit) { @@ -116,27 +85,6 @@ class Solution { } ``` -```java -class Solution { - public String removeDigit(String number, char digit) { - int last = -1; - int n = number.length(); - for (int i = 0; i < n; ++i) { - char d = number.charAt(i); - if (d == digit) { - last = i; - if (i + 1 < n && d < number.charAt(i + 1)) { - break; - } - } - } - return number.substring(0, last) + number.substring(last + 1); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -156,28 +104,6 @@ public: }; ``` -```cpp -class Solution { -public: - string removeDigit(string number, char digit) { - int n = number.size(); - int last = -1; - for (int i = 0; i < n; ++i) { - char d = number[i]; - if (d == digit) { - last = i; - if (i + 1 < n && number[i] < number[i + 1]) { - break; - } - } - } - return number.substr(0, last) + number.substr(last + 1); - } -}; -``` - -### **Go** - ```go func removeDigit(number string, digit byte) string { ans := "0" @@ -193,24 +119,6 @@ func removeDigit(number string, digit byte) string { } ``` -```go -func removeDigit(number string, digit byte) string { - last := -1 - n := len(number) - for i := range number { - if number[i] == digit { - last = i - if i+1 < n && number[i] < number[i+1] { - break - } - } - } - return number[:last] + number[last+1:] -} -``` - -### **TypeScript** - ```ts function removeDigit(number: string, digit: string): string { const n = number.length; @@ -227,8 +135,6 @@ function removeDigit(number: string, digit: string): string { } ``` -### **PHP** - ```php class Solution { /** @@ -251,10 +157,86 @@ class Solution { } ``` -### **...** + + +### 方法二:贪心 + +我们可以枚举字符串 $number$ 的所有位置 $i$,如果 $number[i] = digit$,记录 $digit$ 最后一次出现的位置 $last$,并且如果 $i + 1 \lt n$ 且 $number[i] \lt number[i + 1]$,那么我们可以直接返回 $number[0:i] + number[i+1:]$,即为移除 $number[i]$ 后的结果。这是因为如果 $number[i] < number[i + 1]$,那么移除 $number[i]$ 后,结果一定会更大。 + +遍历结束,我们返回 $number[0:last] + number[last+1:]$ 即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $number$ 的长度。 + + +```python +class Solution: + def removeDigit(self, number: str, digit: str) -> str: + last = -1 + n = len(number) + for i, d in enumerate(number): + if d == digit: + last = i + if i + 1 < n and d < number[i + 1]: + break + return number[:last] + number[last + 1 :] ``` +```java +class Solution { + public String removeDigit(String number, char digit) { + int last = -1; + int n = number.length(); + for (int i = 0; i < n; ++i) { + char d = number.charAt(i); + if (d == digit) { + last = i; + if (i + 1 < n && d < number.charAt(i + 1)) { + break; + } + } + } + return number.substring(0, last) + number.substring(last + 1); + } +} +``` + +```cpp +class Solution { +public: + string removeDigit(string number, char digit) { + int n = number.size(); + int last = -1; + for (int i = 0; i < n; ++i) { + char d = number[i]; + if (d == digit) { + last = i; + if (i + 1 < n && number[i] < number[i + 1]) { + break; + } + } + } + return number.substr(0, last) + number.substr(last + 1); + } +}; +``` + +```go +func removeDigit(number string, digit byte) string { + last := -1 + n := len(number) + for i := range number { + if number[i] == digit { + last = i + if i+1 < n && number[i] < number[i+1] { + break + } + } + } + return number[:last] + number[last+1:] +} ``` + + diff --git a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/README_EN.md b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/README_EN.md index f5b6a31d5d0c4..c8ba80ab1ea2c 100644 --- a/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/README_EN.md +++ b/solution/2200-2299/2259.Remove Digit From Number to Maximize Result/README_EN.md @@ -47,9 +47,9 @@ Both result in the string "51". ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,21 +59,6 @@ class Solution: ) ``` -```python -class Solution: - def removeDigit(self, number: str, digit: str) -> str: - last = -1 - n = len(number) - for i, d in enumerate(number): - if d == digit: - last = i - if i + 1 < n and d < number[i + 1]: - break - return number[:last] + number[last + 1 :] -``` - -### **Java** - ```java class Solution { public String removeDigit(String number, char digit) { @@ -92,27 +77,6 @@ class Solution { } ``` -```java -class Solution { - public String removeDigit(String number, char digit) { - int last = -1; - int n = number.length(); - for (int i = 0; i < n; ++i) { - char d = number.charAt(i); - if (d == digit) { - last = i; - if (i + 1 < n && d < number.charAt(i + 1)) { - break; - } - } - } - return number.substring(0, last) + number.substring(last + 1); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -132,28 +96,6 @@ public: }; ``` -```cpp -class Solution { -public: - string removeDigit(string number, char digit) { - int n = number.size(); - int last = -1; - for (int i = 0; i < n; ++i) { - char d = number[i]; - if (d == digit) { - last = i; - if (i + 1 < n && number[i] < number[i + 1]) { - break; - } - } - } - return number.substr(0, last) + number.substr(last + 1); - } -}; -``` - -### **Go** - ```go func removeDigit(number string, digit byte) string { ans := "0" @@ -169,24 +111,6 @@ func removeDigit(number string, digit byte) string { } ``` -```go -func removeDigit(number string, digit byte) string { - last := -1 - n := len(number) - for i := range number { - if number[i] == digit { - last = i - if i+1 < n && number[i] < number[i+1] { - break - } - } - } - return number[:last] + number[last+1:] -} -``` - -### **TypeScript** - ```ts function removeDigit(number: string, digit: string): string { const n = number.length; @@ -203,8 +127,6 @@ function removeDigit(number: string, digit: string): string { } ``` -### **PHP** - ```php class Solution { /** @@ -227,10 +149,80 @@ class Solution { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def removeDigit(self, number: str, digit: str) -> str: + last = -1 + n = len(number) + for i, d in enumerate(number): + if d == digit: + last = i + if i + 1 < n and d < number[i + 1]: + break + return number[:last] + number[last + 1 :] +``` + +```java +class Solution { + public String removeDigit(String number, char digit) { + int last = -1; + int n = number.length(); + for (int i = 0; i < n; ++i) { + char d = number.charAt(i); + if (d == digit) { + last = i; + if (i + 1 < n && d < number.charAt(i + 1)) { + break; + } + } + } + return number.substring(0, last) + number.substring(last + 1); + } +} +``` +```cpp +class Solution { +public: + string removeDigit(string number, char digit) { + int n = number.size(); + int last = -1; + for (int i = 0; i < n; ++i) { + char d = number[i]; + if (d == digit) { + last = i; + if (i + 1 < n && number[i] < number[i + 1]) { + break; + } + } + } + return number.substr(0, last) + number.substr(last + 1); + } +}; ``` +```go +func removeDigit(number string, digit byte) string { + last := -1 + n := len(number) + for i := range number { + if number[i] == digit { + last = i + if i+1 < n && number[i] < number[i+1] { + break + } + } + } + return number[:last] + number[last+1:] +} ``` + + diff --git a/solution/2200-2299/2260.Minimum Consecutive Cards to Pick Up/README.md b/solution/2200-2299/2260.Minimum Consecutive Cards to Pick Up/README.md index 1d1c5bb877e5d..26ad71155fc52 100644 --- a/solution/2200-2299/2260.Minimum Consecutive Cards to Pick Up/README.md +++ b/solution/2200-2299/2260.Minimum Consecutive Cards to Pick Up/README.md @@ -35,9 +35,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们初始化答案为 $+\infty$,遍历数组,对于每个数字 $x$,如果 $last[x]$ 存在,则表示 $x$ 有一对匹配卡牌,此时更新答案为 $ans = min(ans, i - last[x] + 1)$,最后如果答案为 $+\infty$,则返回 $-1$,否则返回答案。 @@ -45,10 +43,6 @@ -### **Python3** - - - ```python class Solution: def minimumCardPickup(self, cards: List[int]) -> int: @@ -61,10 +55,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - - - ```java class Solution { public int minimumCardPickup(int[] cards) { @@ -82,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +90,6 @@ public: }; ``` -### **Go** - ```go func minimumCardPickup(cards []int) int { last := map[int]int{} @@ -122,8 +108,6 @@ func minimumCardPickup(cards []int) int { } ``` -### **TypeScript** - ```ts function minimumCardPickup(cards: number[]): number { const n = cards.length; @@ -139,10 +123,6 @@ function minimumCardPickup(cards: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2260.Minimum Consecutive Cards to Pick Up/README_EN.md b/solution/2200-2299/2260.Minimum Consecutive Cards to Pick Up/README_EN.md index 0dffb5c8d1bb1..bcd4c5c84a5ea 100644 --- a/solution/2200-2299/2260.Minimum Consecutive Cards to Pick Up/README_EN.md +++ b/solution/2200-2299/2260.Minimum Consecutive Cards to Pick Up/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - ```java class Solution { public int minimumCardPickup(int[] cards) { @@ -70,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,8 +86,6 @@ public: }; ``` -### **Go** - ```go func minimumCardPickup(cards []int) int { last := map[int]int{} @@ -110,8 +104,6 @@ func minimumCardPickup(cards []int) int { } ``` -### **TypeScript** - ```ts function minimumCardPickup(cards: number[]): number { const n = cards.length; @@ -127,10 +119,6 @@ function minimumCardPickup(cards: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2261.K Divisible Elements Subarrays/README.md b/solution/2200-2299/2261.K Divisible Elements Subarrays/README.md index f1c9ace84e2e6..8eeaa8a9a9386 100644 --- a/solution/2200-2299/2261.K Divisible Elements Subarrays/README.md +++ b/solution/2200-2299/2261.K Divisible Elements Subarrays/README.md @@ -61,9 +61,7 @@ nums 中的所有元素都可以被 p = 1 整除。 ## 解法 - - -**方法一:哈希表 + 枚举** +### 方法一:哈希表 + 枚举 我们可以枚举子数组的左右端点 $i$ 和 $j$,其中 $0 \leq i \leq j < n$。对于每个子数组 $nums[i,..j]$,我们可以统计其中可以被 $p$ 整除的元素的个数 $cnt$,如果 $cnt \leq k$,则该子数组满足条件。我们将所有满足条件的子数组的元素序列作为字符串存入哈希表中,最后哈希表中的元素个数即为答案。 @@ -71,10 +69,6 @@ nums 中的所有元素都可以被 p = 1 整除。 -### **Python3** - - - ```python class Solution: def countDistinct(self, nums: List[int], k: int, p: int) -> int: @@ -90,27 +84,6 @@ class Solution: return len(s) ``` -```python -class Solution: - def countDistinct(self, nums: List[int], k: int, p: int) -> int: - n = len(nums) - s = set() - for i in range(n): - cnt = 0 - t = "" - for x in nums[i:]: - cnt += x % p == 0 - if cnt > k: - break - t += str(x) + "," - s.add(t) - return len(s) -``` - -### **Java** - - - ```java class Solution { public int countDistinct(int[] nums, int k, int p) { @@ -132,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +127,6 @@ public: }; ``` -### **Go** - ```go func countDistinct(nums []int, k int, p int) int { s := map[string]struct{}{} @@ -178,8 +147,6 @@ func countDistinct(nums []int, k int, p int) int { } ``` -### **TypeScript** - ```ts function countDistinct(nums: number[], k: number, p: number): number { const n = nums.length; @@ -199,10 +166,29 @@ function countDistinct(nums: number[], k: number, p: number): number { } ``` -### **...** + + +### 方法二 -``` + +```python +class Solution: + def countDistinct(self, nums: List[int], k: int, p: int) -> int: + n = len(nums) + s = set() + for i in range(n): + cnt = 0 + t = "" + for x in nums[i:]: + cnt += x % p == 0 + if cnt > k: + break + t += str(x) + "," + s.add(t) + return len(s) ``` + + diff --git a/solution/2200-2299/2261.K Divisible Elements Subarrays/README_EN.md b/solution/2200-2299/2261.K Divisible Elements Subarrays/README_EN.md index 278556f723250..eb0f14183ccf6 100644 --- a/solution/2200-2299/2261.K Divisible Elements Subarrays/README_EN.md +++ b/solution/2200-2299/2261.K Divisible Elements Subarrays/README_EN.md @@ -56,9 +56,9 @@ Since all subarrays are distinct, the total number of subarrays satisfying all t ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,25 +75,6 @@ class Solution: return len(s) ``` -```python -class Solution: - def countDistinct(self, nums: List[int], k: int, p: int) -> int: - n = len(nums) - s = set() - for i in range(n): - cnt = 0 - t = "" - for x in nums[i:]: - cnt += x % p == 0 - if cnt > k: - break - t += str(x) + "," - s.add(t) - return len(s) -``` - -### **Java** - ```java class Solution { public int countDistinct(int[] nums, int k, int p) { @@ -115,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +118,6 @@ public: }; ``` -### **Go** - ```go func countDistinct(nums []int, k int, p int) int { s := map[string]struct{}{} @@ -161,8 +138,6 @@ func countDistinct(nums []int, k int, p int) int { } ``` -### **TypeScript** - ```ts function countDistinct(nums: number[], k: number, p: number): number { const n = nums.length; @@ -182,10 +157,29 @@ function countDistinct(nums: number[], k: number, p: number): number { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def countDistinct(self, nums: List[int], k: int, p: int) -> int: + n = len(nums) + s = set() + for i in range(n): + cnt = 0 + t = "" + for x in nums[i:]: + cnt += x % p == 0 + if cnt > k: + break + t += str(x) + "," + s.add(t) + return len(s) ``` + + diff --git a/solution/2200-2299/2262.Total Appeal of A String/README.md b/solution/2200-2299/2262.Total Appeal of A String/README.md index 3ae12344efe5c..dc69d310b6665 100644 --- a/solution/2200-2299/2262.Total Appeal of A String/README.md +++ b/solution/2200-2299/2262.Total Appeal of A String/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举以每个字符 $s[i]$ 结尾的字符串,计算其引力值之和 $t$,最后将所有 $t$ 相加即可。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def appealSum(self, s: str) -> int: @@ -90,10 +84,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long appealSum(String s) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func appealSum(s string) int64 { var ans, t int64 @@ -150,8 +136,6 @@ func appealSum(s string) int64 { } ``` -### **TypeScript** - ```ts function appealSum(s: string): number { const pos: number[] = Array(26).fill(-1); @@ -168,10 +152,6 @@ function appealSum(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2262.Total Appeal of A String/README_EN.md b/solution/2200-2299/2262.Total Appeal of A String/README_EN.md index ec6322ba72ac4..63d82bf0a370c 100644 --- a/solution/2200-2299/2262.Total Appeal of A String/README_EN.md +++ b/solution/2200-2299/2262.Total Appeal of A String/README_EN.md @@ -52,7 +52,7 @@ The total sum is 4 + 6 + 6 + 4 = 20. ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We can enumerate all the substrings that end with each character $s[i]$ and calculate their gravitational value sum $t$. Finally, we add up all the $t$ to get the total gravitational value sum. @@ -69,8 +69,6 @@ The time complexity is $O(n)$, and the space complexity is $O(|\Sigma|)$, where -### **Python3** - ```python class Solution: def appealSum(self, s: str) -> int: @@ -84,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long appealSum(String s) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +117,6 @@ public: }; ``` -### **Go** - ```go func appealSum(s string) int64 { var ans, t int64 @@ -142,8 +134,6 @@ func appealSum(s string) int64 { } ``` -### **TypeScript** - ```ts function appealSum(s: string): number { const pos: number[] = Array(26).fill(-1); @@ -160,10 +150,6 @@ function appealSum(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2263.Make Array Non-decreasing or Non-increasing/README.md b/solution/2200-2299/2263.Make Array Non-decreasing or Non-increasing/README.md index 2569f92569f47..309a0bdb4f111 100644 --- a/solution/2200-2299/2263.Make Array Non-decreasing or Non-increasing/README.md +++ b/solution/2200-2299/2263.Make Array Non-decreasing or Non-increasing/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示将数组 $nums$ 的前 $i$ 个元素变为非递减序列,且第 $i$ 个元素的值为 $j$ 所需的最小操作次数。由于数组 $nums$ 元素的取值范围为 $[0, 1000]$,因此我们可以将 $f$ 数组的第二维定义为 $1001$。 @@ -80,10 +78,6 @@ $$ -### **Python3** - - - ```python class Solution: def convertArray(self, nums: List[int]) -> int: @@ -101,10 +95,6 @@ class Solution: return min(solve(nums), solve(nums[::-1])) ``` -### **Java** - - - ```java class Solution { public int convertArray(int[] nums) { @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +155,6 @@ public: }; ``` -### **Go** - ```go func convertArray(nums []int) int { return min(solve(nums), solve(reverse(nums))) @@ -206,16 +192,6 @@ func abs(x int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2263.Make Array Non-decreasing or Non-increasing/README_EN.md b/solution/2200-2299/2263.Make Array Non-decreasing or Non-increasing/README_EN.md index 342a375497b43..c95ef0b837d7d 100644 --- a/solution/2200-2299/2263.Make Array Non-decreasing or Non-increasing/README_EN.md +++ b/solution/2200-2299/2263.Make Array Non-decreasing or Non-increasing/README_EN.md @@ -58,9 +58,9 @@ It can be proven that 4 is the minimum number of operations needed. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,8 +79,6 @@ class Solution: return min(solve(nums), solve(nums[::-1])) ``` -### **Java** - ```java class Solution { public int convertArray(int[] nums) { @@ -115,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +139,6 @@ public: }; ``` -### **Go** - ```go func convertArray(nums []int) int { return min(solve(nums), solve(reverse(nums))) @@ -182,16 +176,6 @@ func abs(x int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/README.md b/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/README.md index bacca86ba418e..8a050da93ca1f 100644 --- a/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/README.md +++ b/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以从大到小枚举每个数字 $i$,其中 $0 \le i \le 9$,然后判断连续的三个 $i$ 构成的字符串 $s$ 是否是 $num$ 的子串,若是,直接返回 $s$ 即可。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def largestGoodInteger(self, num: str) -> str: @@ -85,10 +79,6 @@ class Solution: return "" ``` -### **Java** - - - ```java class Solution { public String largestGoodInteger(String num) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func largestGoodInteger(num string) string { for c := '9'; c >= '0'; c-- { @@ -133,8 +119,6 @@ func largestGoodInteger(num string) string { } ``` -### **TypeScript** - ```ts function largestGoodInteger(num: string): string { for (let i = 9; i >= 0; i--) { @@ -147,10 +131,6 @@ function largestGoodInteger(num: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/README_EN.md b/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/README_EN.md index 598479bb6b9d0..b8714cbcd74e7 100644 --- a/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/README_EN.md +++ b/solution/2200-2299/2264.Largest 3-Same-Digit Number in String/README_EN.md @@ -56,7 +56,7 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We can enumerate each digit $i$ from large to small, where $0 \le i \le 9$, and then check whether the string $s$ consisting of three consecutive $i$ is a substring of $num$. If it is, we directly return $s$. @@ -66,8 +66,6 @@ The time complexity is $O(10 \times n)$, where $n$ is the length of the string $ -### **Python3** - ```python class Solution: def largestGoodInteger(self, num: str) -> str: @@ -77,8 +75,6 @@ class Solution: return "" ``` -### **Java** - ```java class Solution { public String largestGoodInteger(String num) { @@ -93,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func largestGoodInteger(num string) string { for c := '9'; c >= '0'; c-- { @@ -123,8 +115,6 @@ func largestGoodInteger(num string) string { } ``` -### **TypeScript** - ```ts function largestGoodInteger(num: string): string { for (let i = 9; i >= 0; i--) { @@ -137,10 +127,6 @@ function largestGoodInteger(num: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README.md b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README.md index efea46a7054fc..59571e3202207 100644 --- a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README.md +++ b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README.md @@ -47,14 +47,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -81,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -126,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -161,8 +151,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -193,16 +181,6 @@ func averageOfSubtree(root *TreeNode) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README_EN.md b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README_EN.md index 2927ec65b2a81..469ddf2be5077 100644 --- a/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README_EN.md +++ b/solution/2200-2299/2265.Count Nodes Equal to Average of Subtree/README_EN.md @@ -45,9 +45,9 @@ For the node with value 6: The average of its subtree is 6 / 1 = 6. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -75,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -118,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -153,8 +149,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -185,16 +179,6 @@ func averageOfSubtree(root *TreeNode) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2266.Count Number of Texts/README.md b/solution/2200-2299/2266.Count Number of Texts/README.md index fe0aae49c0f1e..a4a71448ac457 100644 --- a/solution/2200-2299/2266.Count Number of Texts/README.md +++ b/solution/2200-2299/2266.Count Number of Texts/README.md @@ -59,14 +59,10 @@ Alice 可能发出的文字信息包括: ## 解法 - +### 方法一 -### **Python3** - - - ```python mod = 10**9 + 7 f = [1, 1, 2, 4] @@ -85,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int N = 100010; @@ -127,8 +119,6 @@ class Solution { } ``` -### **Go** - ```go const mod int = 1e9 + 7 const n int = 1e5 + 10 @@ -163,16 +153,6 @@ func countTexts(pressedKeys string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2266.Count Number of Texts/README_EN.md b/solution/2200-2299/2266.Count Number of Texts/README_EN.md index 758907c433992..914c96fad54c5 100644 --- a/solution/2200-2299/2266.Count Number of Texts/README_EN.md +++ b/solution/2200-2299/2266.Count Number of Texts/README_EN.md @@ -55,9 +55,9 @@ Since we need to return the answer modulo 109 + 7, we return 20828761 ## Solutions - +### Solution 1 -### **Python3** + ```python mod = 10**9 + 7 @@ -77,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int N = 100010; @@ -117,8 +115,6 @@ class Solution { } ``` -### **Go** - ```go const mod int = 1e9 + 7 const n int = 1e5 + 10 @@ -153,16 +149,6 @@ func countTexts(pressedKeys string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2267.Check if There Is a Valid Parentheses String Path/README.md b/solution/2200-2299/2267.Check if There Is a Valid Parentheses String Path/README.md index 603c65f1de10f..93c21ee0da043 100644 --- a/solution/2200-2299/2267.Check if There Is a Valid Parentheses String Path/README.md +++ b/solution/2200-2299/2267.Check if There Is a Valid Parentheses String Path/README.md @@ -63,16 +63,10 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 -### **Python3** - - - ```python class Solution: def hasValidPath(self, grid: List[List[str]]) -> bool: @@ -95,10 +89,6 @@ class Solution: return dfs(0, 0, 0) ``` -### **Java** - - - ```java class Solution { private boolean[][][] vis; @@ -138,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp bool vis[100][100][200]; int dirs[3] = {1, 0, 1}; @@ -167,8 +155,6 @@ public: }; ``` -### **Go** - ```go func hasValidPath(grid [][]byte) bool { m, n := len(grid), len(grid[0]) @@ -209,16 +195,6 @@ func hasValidPath(grid [][]byte) bool { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2267.Check if There Is a Valid Parentheses String Path/README_EN.md b/solution/2200-2299/2267.Check if There Is a Valid Parentheses String Path/README_EN.md index 9ec6b32b1f71c..2390dc0851927 100644 --- a/solution/2200-2299/2267.Check if There Is a Valid Parentheses String Path/README_EN.md +++ b/solution/2200-2299/2267.Check if There Is a Valid Parentheses String Path/README_EN.md @@ -55,9 +55,9 @@ Note that there may be other valid parentheses string paths. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -81,8 +81,6 @@ class Solution: return dfs(0, 0, 0) ``` -### **Java** - ```java class Solution { private boolean[][][] vis; @@ -122,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp bool vis[100][100][200]; int dirs[3] = {1, 0, 1}; @@ -151,8 +147,6 @@ public: }; ``` -### **Go** - ```go func hasValidPath(grid [][]byte) bool { m, n := len(grid), len(grid[0]) @@ -193,16 +187,6 @@ func hasValidPath(grid [][]byte) bool { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2268.Minimum Number of Keypresses/README.md b/solution/2200-2299/2268.Minimum Number of Keypresses/README.md index 1d412d1e1de5b..57e58cb02f996 100644 --- a/solution/2200-2299/2268.Minimum Number of Keypresses/README.md +++ b/solution/2200-2299/2268.Minimum Number of Keypresses/README.md @@ -59,16 +59,10 @@ ## 解法 - - -**方法一:计数 + 贪心** +### 方法一:计数 + 贪心 -### **Python3** - - - ```python class Solution: def minimumKeypresses(self, s: str) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumKeypresses(String s) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func minimumKeypresses(s string) int { cnt := make([]int, 26) @@ -146,16 +132,6 @@ func minimumKeypresses(s string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2268.Minimum Number of Keypresses/README_EN.md b/solution/2200-2299/2268.Minimum Number of Keypresses/README_EN.md index 12929d98e2e8c..04c58fc01f3f7 100644 --- a/solution/2200-2299/2268.Minimum Number of Keypresses/README_EN.md +++ b/solution/2200-2299/2268.Minimum Number of Keypresses/README_EN.md @@ -56,9 +56,9 @@ A total of 15 button presses are needed, so return 15. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumKeypresses(String s) { @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +111,6 @@ public: }; ``` -### **Go** - ```go func minimumKeypresses(s string) int { cnt := make([]int, 26) @@ -135,16 +129,6 @@ func minimumKeypresses(s string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2269.Find the K-Beauty of a Number/README.md b/solution/2200-2299/2269.Find the K-Beauty of a Number/README.md index ce749d02af392..967f9204ce477 100644 --- a/solution/2200-2299/2269.Find the K-Beauty of a Number/README.md +++ b/solution/2200-2299/2269.Find the K-Beauty of a Number/README.md @@ -62,14 +62,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def divisorSubstrings(self, num: int, k: int) -> int: @@ -82,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int divisorSubstrings(int num, int k) { @@ -102,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +109,6 @@ public: }; ``` -### **Go** - ```go func divisorSubstrings(num int, k int) int { ans := 0 @@ -135,8 +123,6 @@ func divisorSubstrings(num int, k int) int { } ``` -### **TypeScript** - ```ts function divisorSubstrings(num: number, k: number): number { let ans = 0; @@ -151,10 +137,6 @@ function divisorSubstrings(num: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2269.Find the K-Beauty of a Number/README_EN.md b/solution/2200-2299/2269.Find the K-Beauty of a Number/README_EN.md index 4a28a4b998347..00e1bf451dce1 100644 --- a/solution/2200-2299/2269.Find the K-Beauty of a Number/README_EN.md +++ b/solution/2200-2299/2269.Find the K-Beauty of a Number/README_EN.md @@ -58,9 +58,9 @@ Therefore, the k-beauty is 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int divisorSubstrings(int num, int k) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +105,6 @@ public: }; ``` -### **Go** - ```go func divisorSubstrings(num int, k int) int { ans := 0 @@ -125,8 +119,6 @@ func divisorSubstrings(num int, k int) int { } ``` -### **TypeScript** - ```ts function divisorSubstrings(num: number, k: number): number { let ans = 0; @@ -141,10 +133,6 @@ function divisorSubstrings(num: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2270.Number of Ways to Split Array/README.md b/solution/2200-2299/2270.Number of Ways to Split Array/README.md index d31cd85509ae2..28c5cd122653f 100644 --- a/solution/2200-2299/2270.Number of Ways to Split Array/README.md +++ b/solution/2200-2299/2270.Number of Ways to Split Array/README.md @@ -53,16 +53,10 @@ ## 解法 - - -**方法一:前缀和** +### 方法一:前缀和 -### **Python3** - - - ```python class Solution: def waysToSplitArray(self, nums: List[int]) -> int: @@ -75,10 +69,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int waysToSplitArray(int[] nums) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func waysToSplitArray(nums []int) int { s := 0 @@ -136,16 +122,6 @@ func waysToSplitArray(nums []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2270.Number of Ways to Split Array/README_EN.md b/solution/2200-2299/2270.Number of Ways to Split Array/README_EN.md index c687e6e274728..f2172ce211792 100644 --- a/solution/2200-2299/2270.Number of Ways to Split Array/README_EN.md +++ b/solution/2200-2299/2270.Number of Ways to Split Array/README_EN.md @@ -50,9 +50,9 @@ There are two valid splits in nums: ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int waysToSplitArray(int[] nums) { @@ -88,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +102,6 @@ public: }; ``` -### **Go** - ```go func waysToSplitArray(nums []int) int { s := 0 @@ -125,16 +119,6 @@ func waysToSplitArray(nums []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2271.Maximum White Tiles Covered by a Carpet/README.md b/solution/2200-2299/2271.Maximum White Tiles Covered by a Carpet/README.md index 1d09beac04c12..819bcfc376174 100644 --- a/solution/2200-2299/2271.Maximum White Tiles Covered by a Carpet/README.md +++ b/solution/2200-2299/2271.Maximum White Tiles Covered by a Carpet/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:贪心 + 排序 + 滑动窗口** +### 方法一:贪心 + 排序 + 滑动窗口 直觉上,毯子的左端点一定与某块瓷砖的左端点重合,这样才能使得毯子覆盖的瓷砖最多。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int: @@ -94,10 +88,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumWhiteTiles(int[][] tiles, int carpetLen) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func maximumWhiteTiles(tiles [][]int, carpetLen int) int { sort.Slice(tiles, func(i, j int) bool { return tiles[i][0] < tiles[j][0] }) @@ -169,16 +155,6 @@ func maximumWhiteTiles(tiles [][]int, carpetLen int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2271.Maximum White Tiles Covered by a Carpet/README_EN.md b/solution/2200-2299/2271.Maximum White Tiles Covered by a Carpet/README_EN.md index 2d3739ee9ac56..6e2479d56cf28 100644 --- a/solution/2200-2299/2271.Maximum White Tiles Covered by a Carpet/README_EN.md +++ b/solution/2200-2299/2271.Maximum White Tiles Covered by a Carpet/README_EN.md @@ -44,9 +44,9 @@ It covers 2 white tiles, so we return 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumWhiteTiles(int[][] tiles, int carpetLen) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +112,6 @@ public: }; ``` -### **Go** - ```go func maximumWhiteTiles(tiles [][]int, carpetLen int) int { sort.Slice(tiles, func(i, j int) bool { return tiles[i][0] < tiles[j][0] }) @@ -139,16 +133,6 @@ func maximumWhiteTiles(tiles [][]int, carpetLen int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2272.Substring With Largest Variance/README.md b/solution/2200-2299/2272.Substring With Largest Variance/README.md index 1b369c6ae84c3..db229c6893b04 100644 --- a/solution/2200-2299/2272.Substring With Largest Variance/README.md +++ b/solution/2200-2299/2272.Substring With Largest Variance/README.md @@ -48,9 +48,7 @@ s 中没有字母出现超过 1 次,所以 s 中每个子字符串的波动值 ## 解法 - - -**方法一:枚举 + 动态规划** +### 方法一:枚举 + 动态规划 由于字符集只包含小写字母,我们可以考虑枚举出现次数最多的字符 $a$ 以及出现次数最少的字符 $b$。对于一个子串来说,这两种字符出现的次数之差就是子串的波动值。 @@ -68,10 +66,6 @@ s 中没有字母出现超过 1 次,所以 s 中每个子字符串的波动值 -### **Python3** - - - ```python class Solution: def largestVariance(self, s: str) -> int: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int largestVariance(String s) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +140,6 @@ public: }; ``` -### **Go** - ```go func largestVariance(s string) int { ans, n := 0, len(s) @@ -179,16 +165,6 @@ func largestVariance(s string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2272.Substring With Largest Variance/README_EN.md b/solution/2200-2299/2272.Substring With Largest Variance/README_EN.md index 485e55281a489..e14bea489a065 100644 --- a/solution/2200-2299/2272.Substring With Largest Variance/README_EN.md +++ b/solution/2200-2299/2272.Substring With Largest Variance/README_EN.md @@ -44,9 +44,9 @@ No letter occurs more than once in s, so the variance of every substring is 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int largestVariance(String s) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +122,6 @@ public: }; ``` -### **Go** - ```go func largestVariance(s string) int { ans, n := 0, len(s) @@ -153,16 +147,6 @@ func largestVariance(s string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2273.Find Resultant Array After Removing Anagrams/README.md b/solution/2200-2299/2273.Find Resultant Array After Removing Anagrams/README.md index 820f7c2fa8b82..003b386cdf491 100644 --- a/solution/2200-2299/2273.Find Resultant Array After Removing Anagrams/README.md +++ b/solution/2200-2299/2273.Find Resultant Array After Removing Anagrams/README.md @@ -56,14 +56,10 @@ words 中不存在互为字母异位词的两个相邻字符串,所以无需 ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def removeAnagrams(self, words: List[str]) -> List[str]: @@ -74,10 +70,6 @@ class Solution: ] ``` -### **Java** - - - ```java class Solution { public List removeAnagrams(String[] words) { @@ -97,8 +89,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function removeAnagrams(words: string[]): string[] { const n = words.length; @@ -124,10 +114,6 @@ function countWord(word: string): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2273.Find Resultant Array After Removing Anagrams/README_EN.md b/solution/2200-2299/2273.Find Resultant Array After Removing Anagrams/README_EN.md index 01a8a33fdaeff..7ea9ecf62b9b3 100644 --- a/solution/2200-2299/2273.Find Resultant Array After Removing Anagrams/README_EN.md +++ b/solution/2200-2299/2273.Find Resultant Array After Removing Anagrams/README_EN.md @@ -47,9 +47,9 @@ No two adjacent strings in words are anagrams of each other, so no operations ar ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: ] ``` -### **Java** - ```java class Solution { public List removeAnagrams(String[] words) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function removeAnagrams(words: string[]): string[] { const n = words.length; @@ -109,10 +105,6 @@ function countWord(word: string): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2274.Maximum Consecutive Floors Without Special Floors/README.md b/solution/2200-2299/2274.Maximum Consecutive Floors Without Special Floors/README.md index d235a92f1a389..5760fa96ffc8c 100644 --- a/solution/2200-2299/2274.Maximum Consecutive Floors Without Special Floors/README.md +++ b/solution/2200-2299/2274.Maximum Consecutive Floors Without Special Floors/README.md @@ -46,14 +46,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int: @@ -64,10 +60,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxConsecutive(int bottom, int top, int[] special) { @@ -82,8 +74,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function maxConsecutive(bottom: number, top: number, special: number[]): number { let nums = special.slice().sort((a, b) => a - b); @@ -98,10 +88,6 @@ function maxConsecutive(bottom: number, top: number, special: number[]): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2274.Maximum Consecutive Floors Without Special Floors/README_EN.md b/solution/2200-2299/2274.Maximum Consecutive Floors Without Special Floors/README_EN.md index 93fb2e9756dbd..5b7248eb9a779 100644 --- a/solution/2200-2299/2274.Maximum Consecutive Floors Without Special Floors/README_EN.md +++ b/solution/2200-2299/2274.Maximum Consecutive Floors Without Special Floors/README_EN.md @@ -42,9 +42,9 @@ Therefore, we return the maximum number which is 3 floors. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxConsecutive(int bottom, int top, int[] special) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function maxConsecutive(bottom: number, top: number, special: number[]): number { let nums = special.slice().sort((a, b) => a - b); @@ -88,10 +84,6 @@ function maxConsecutive(bottom: number, top: number, special: number[]): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2275.Largest Combination With Bitwise AND Greater Than Zero/README.md b/solution/2200-2299/2275.Largest Combination With Bitwise AND Greater Than Zero/README.md index 74cb55b0ba498..ba3ea56fc8a5b 100644 --- a/solution/2200-2299/2275.Largest Combination With Bitwise AND Greater Than Zero/README.md +++ b/solution/2200-2299/2275.Largest Combination With Bitwise AND Greater Than Zero/README.md @@ -51,18 +51,12 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 大于 0,实际上就是要求存在某个二进制位(0-31),满足所有数字的这一位均为 1。 -### **Python3** - - - ```python class Solution: def largestCombination(self, candidates: List[int]) -> int: @@ -75,10 +69,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int largestCombination(int[] candidates) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function largestCombination(candidates: number[]): number { const n = 24; @@ -112,10 +100,6 @@ function largestCombination(candidates: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2275.Largest Combination With Bitwise AND Greater Than Zero/README_EN.md b/solution/2200-2299/2275.Largest Combination With Bitwise AND Greater Than Zero/README_EN.md index d604174b6f1da..7d427428b0112 100644 --- a/solution/2200-2299/2275.Largest Combination With Bitwise AND Greater Than Zero/README_EN.md +++ b/solution/2200-2299/2275.Largest Combination With Bitwise AND Greater Than Zero/README_EN.md @@ -47,9 +47,9 @@ The size of the combination is 2, so we return 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int largestCombination(int[] candidates) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **TypeScript** - ```ts function largestCombination(candidates: number[]): number { const n = 24; @@ -98,10 +94,6 @@ function largestCombination(candidates: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2276.Count Integers in Intervals/README.md b/solution/2200-2299/2276.Count Integers in Intervals/README.md index bf97850f309fd..dd8fddb5002a1 100644 --- a/solution/2200-2299/2276.Count Integers in Intervals/README.md +++ b/solution/2200-2299/2276.Count Integers in Intervals/README.md @@ -60,9 +60,7 @@ countIntervals.count(); // 返回 8 ## 解法 - - -**方法一:线段树(动态开点)** +### 方法一:线段树(动态开点) 根据题目描述,我们需要维护一个区间集合,支持区间的添加和查询操作。对于区间的添加,我们可以使用线段树来维护区间集合。 @@ -79,10 +77,6 @@ countIntervals.count(); // 返回 8 -### **Python3** - - - ```python class Node: def __init__(self): @@ -128,93 +122,6 @@ class CountIntervals: # param_2 = obj.count() ``` -```python -class Node: - __slots__ = ("left", "right", "l", "r", "mid", "v", "add") - - def __init__(self, l, r): - self.left = None - self.right = None - self.l = l - self.r = r - self.mid = (l + r) // 2 - self.v = 0 - self.add = 0 - - -class SegmentTree: - def __init__(self): - self.root = Node(1, int(1e9) + 1) - - def modify(self, l, r, v, node=None): - if node is None: - node = self.root - if l > r: - return - if node.l >= l and node.r <= r: - node.v = node.r - node.l + 1 - node.add = v - return - self.pushdown(node) - if l <= node.mid: - self.modify(l, r, v, node.left) - if r > node.mid: - self.modify(l, r, v, node.right) - self.pushup(node) - - def query(self, l, r, node=None): - if node is None: - node = self.root - if l > r: - return 0 - if node.l >= l and node.r <= r: - return node.v - self.pushdown(node) - v = 0 - if l <= node.mid: - v += self.query(l, r, node.left) - if r > node.mid: - v += self.query(l, r, node.right) - return v - - def pushup(self, node): - node.v = node.left.v + node.right.v - - def pushdown(self, node): - if node.left is None: - node.left = Node(node.l, node.mid) - if node.right is None: - node.right = Node(node.mid + 1, node.r) - if node.add != 0: - left, right = node.left, node.right - left.add = node.add - right.add = node.add - left.v = left.r - left.l + 1 - right.v = right.r - right.l + 1 - node.add = 0 - - -class CountIntervals: - def __init__(self): - self.tree = SegmentTree() - - def add(self, left, right): - self.tree.modify(left, right, 1) - - def count(self): - return self.tree.query(1, int(1e9)) - - -# Your CountIntervals object will be instantiated and called as such: -# obj = CountIntervals() -# obj.add(left, right) -# param_2 = obj.count() -``` - -### **Java** - - - ```java class Node { Node left; @@ -328,8 +235,6 @@ class CountIntervals { */ ``` -### **C++** - ```cpp class Node { public: @@ -445,8 +350,6 @@ private: */ ``` -### **Go** - ```go type Node struct { left *Node @@ -571,8 +474,6 @@ func (ci *CountIntervals) Count() int { */ ``` -### **TypeScript** - ```ts class CountIntervals { left: null | CountIntervals; @@ -615,10 +516,95 @@ class CountIntervals { */ ``` -### **...** + + +### 方法二 + + + +```python +class Node: + __slots__ = ("left", "right", "l", "r", "mid", "v", "add") + + def __init__(self, l, r): + self.left = None + self.right = None + self.l = l + self.r = r + self.mid = (l + r) // 2 + self.v = 0 + self.add = 0 + + +class SegmentTree: + def __init__(self): + self.root = Node(1, int(1e9) + 1) + + def modify(self, l, r, v, node=None): + if node is None: + node = self.root + if l > r: + return + if node.l >= l and node.r <= r: + node.v = node.r - node.l + 1 + node.add = v + return + self.pushdown(node) + if l <= node.mid: + self.modify(l, r, v, node.left) + if r > node.mid: + self.modify(l, r, v, node.right) + self.pushup(node) + + def query(self, l, r, node=None): + if node is None: + node = self.root + if l > r: + return 0 + if node.l >= l and node.r <= r: + return node.v + self.pushdown(node) + v = 0 + if l <= node.mid: + v += self.query(l, r, node.left) + if r > node.mid: + v += self.query(l, r, node.right) + return v + + def pushup(self, node): + node.v = node.left.v + node.right.v + + def pushdown(self, node): + if node.left is None: + node.left = Node(node.l, node.mid) + if node.right is None: + node.right = Node(node.mid + 1, node.r) + if node.add != 0: + left, right = node.left, node.right + left.add = node.add + right.add = node.add + left.v = left.r - left.l + 1 + right.v = right.r - right.l + 1 + node.add = 0 + + +class CountIntervals: + def __init__(self): + self.tree = SegmentTree() + + def add(self, left, right): + self.tree.modify(left, right, 1) + + def count(self): + return self.tree.query(1, int(1e9)) -``` +# Your CountIntervals object will be instantiated and called as such: +# obj = CountIntervals() +# obj.add(left, right) +# param_2 = obj.count() ``` + + diff --git a/solution/2200-2299/2276.Count Integers in Intervals/README_EN.md b/solution/2200-2299/2276.Count Integers in Intervals/README_EN.md index 0953b5c09a871..db9a52d0b7175 100644 --- a/solution/2200-2299/2276.Count Integers in Intervals/README_EN.md +++ b/solution/2200-2299/2276.Count Integers in Intervals/README_EN.md @@ -57,9 +57,9 @@ countIntervals.count(); // return 8 ## Solutions - +### Solution 1 -### **Python3** + ```python class Node: @@ -106,91 +106,6 @@ class CountIntervals: # param_2 = obj.count() ``` -```python -class Node: - __slots__ = ("left", "right", "l", "r", "mid", "v", "add") - - def __init__(self, l, r): - self.left = None - self.right = None - self.l = l - self.r = r - self.mid = (l + r) // 2 - self.v = 0 - self.add = 0 - - -class SegmentTree: - def __init__(self): - self.root = Node(1, int(1e9) + 1) - - def modify(self, l, r, v, node=None): - if node is None: - node = self.root - if l > r: - return - if node.l >= l and node.r <= r: - node.v = node.r - node.l + 1 - node.add = v - return - self.pushdown(node) - if l <= node.mid: - self.modify(l, r, v, node.left) - if r > node.mid: - self.modify(l, r, v, node.right) - self.pushup(node) - - def query(self, l, r, node=None): - if node is None: - node = self.root - if l > r: - return 0 - if node.l >= l and node.r <= r: - return node.v - self.pushdown(node) - v = 0 - if l <= node.mid: - v += self.query(l, r, node.left) - if r > node.mid: - v += self.query(l, r, node.right) - return v - - def pushup(self, node): - node.v = node.left.v + node.right.v - - def pushdown(self, node): - if node.left is None: - node.left = Node(node.l, node.mid) - if node.right is None: - node.right = Node(node.mid + 1, node.r) - if node.add != 0: - left, right = node.left, node.right - left.add = node.add - right.add = node.add - left.v = left.r - left.l + 1 - right.v = right.r - right.l + 1 - node.add = 0 - - -class CountIntervals: - def __init__(self): - self.tree = SegmentTree() - - def add(self, left, right): - self.tree.modify(left, right, 1) - - def count(self): - return self.tree.query(1, int(1e9)) - - -# Your CountIntervals object will be instantiated and called as such: -# obj = CountIntervals() -# obj.add(left, right) -# param_2 = obj.count() -``` - -### **Java** - ```java class Node { Node left; @@ -304,8 +219,6 @@ class CountIntervals { */ ``` -### **C++** - ```cpp class Node { public: @@ -421,8 +334,6 @@ private: */ ``` -### **Go** - ```go type Node struct { left *Node @@ -547,8 +458,6 @@ func (ci *CountIntervals) Count() int { */ ``` -### **TypeScript** - ```ts class CountIntervals { left: null | CountIntervals; @@ -591,10 +500,95 @@ class CountIntervals { */ ``` -### **...** + -``` +### Solution 2 + + + +```python +class Node: + __slots__ = ("left", "right", "l", "r", "mid", "v", "add") + + def __init__(self, l, r): + self.left = None + self.right = None + self.l = l + self.r = r + self.mid = (l + r) // 2 + self.v = 0 + self.add = 0 + + +class SegmentTree: + def __init__(self): + self.root = Node(1, int(1e9) + 1) + + def modify(self, l, r, v, node=None): + if node is None: + node = self.root + if l > r: + return + if node.l >= l and node.r <= r: + node.v = node.r - node.l + 1 + node.add = v + return + self.pushdown(node) + if l <= node.mid: + self.modify(l, r, v, node.left) + if r > node.mid: + self.modify(l, r, v, node.right) + self.pushup(node) + def query(self, l, r, node=None): + if node is None: + node = self.root + if l > r: + return 0 + if node.l >= l and node.r <= r: + return node.v + self.pushdown(node) + v = 0 + if l <= node.mid: + v += self.query(l, r, node.left) + if r > node.mid: + v += self.query(l, r, node.right) + return v + + def pushup(self, node): + node.v = node.left.v + node.right.v + + def pushdown(self, node): + if node.left is None: + node.left = Node(node.l, node.mid) + if node.right is None: + node.right = Node(node.mid + 1, node.r) + if node.add != 0: + left, right = node.left, node.right + left.add = node.add + right.add = node.add + left.v = left.r - left.l + 1 + right.v = right.r - right.l + 1 + node.add = 0 + + +class CountIntervals: + def __init__(self): + self.tree = SegmentTree() + + def add(self, left, right): + self.tree.modify(left, right, 1) + + def count(self): + return self.tree.query(1, int(1e9)) + + +# Your CountIntervals object will be instantiated and called as such: +# obj = CountIntervals() +# obj.add(left, right) +# param_2 = obj.count() ``` + + diff --git a/solution/2200-2299/2277.Closest Node to Path in Tree/README.md b/solution/2200-2299/2277.Closest Node to Path in Tree/README.md index 0bc3d0d7bcc6e..abdfa8809ec4c 100644 --- a/solution/2200-2299/2277.Closest Node to Path in Tree/README.md +++ b/solution/2200-2299/2277.Closest Node to Path in Tree/README.md @@ -67,36 +67,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2200-2299/2277.Closest Node to Path in Tree/README_EN.md b/solution/2200-2299/2277.Closest Node to Path in Tree/README_EN.md index b8660b47bf8dc..7dee1474c2d82 100644 --- a/solution/2200-2299/2277.Closest Node to Path in Tree/README_EN.md +++ b/solution/2200-2299/2277.Closest Node to Path in Tree/README_EN.md @@ -61,30 +61,4 @@ Since 0 is the only node on the path, the answer to the first query is 0. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2200-2299/2278.Percentage of Letter in String/README.md b/solution/2200-2299/2278.Percentage of Letter in String/README.md index 5142fc681213a..f718b04bdfc6b 100644 --- a/solution/2200-2299/2278.Percentage of Letter in String/README.md +++ b/solution/2200-2299/2278.Percentage of Letter in String/README.md @@ -39,24 +39,16 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def percentageLetter(self, s: str, letter: str) -> int: return s.count(letter) * 100 // len(s) ``` -### **Java** - - - ```java class Solution { public int percentageLetter(String s, char letter) { @@ -71,8 +63,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -84,8 +74,6 @@ public: }; ``` -### **Go** - ```go func percentageLetter(s string, letter byte) int { cnt := 0 @@ -98,8 +86,6 @@ func percentageLetter(s string, letter byte) int { } ``` -### **TypeScript** - ```ts function percentageLetter(s: string, letter: string): number { let count = 0; @@ -111,8 +97,6 @@ function percentageLetter(s: string, letter: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn percentage_letter(s: String, letter: char) -> i32 { @@ -127,10 +111,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2278.Percentage of Letter in String/README_EN.md b/solution/2200-2299/2278.Percentage of Letter in String/README_EN.md index cb5e012b0b4cb..ad45d2598863d 100644 --- a/solution/2200-2299/2278.Percentage of Letter in String/README_EN.md +++ b/solution/2200-2299/2278.Percentage of Letter in String/README_EN.md @@ -35,9 +35,9 @@ The percentage of characters in s that equal the letter 'k' is 0%, so we ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -45,8 +45,6 @@ class Solution: return s.count(letter) * 100 // len(s) ``` -### **Java** - ```java class Solution { public int percentageLetter(String s, char letter) { @@ -61,8 +59,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -74,8 +70,6 @@ public: }; ``` -### **Go** - ```go func percentageLetter(s string, letter byte) int { cnt := 0 @@ -88,8 +82,6 @@ func percentageLetter(s string, letter byte) int { } ``` -### **TypeScript** - ```ts function percentageLetter(s: string, letter: string): number { let count = 0; @@ -101,8 +93,6 @@ function percentageLetter(s: string, letter: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn percentage_letter(s: String, letter: char) -> i32 { @@ -117,10 +107,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2279.Maximum Bags With Full Capacity of Rocks/README.md b/solution/2200-2299/2279.Maximum Bags With Full Capacity of Rocks/README.md index c2ecdbb6faa19..c79514de5140e 100644 --- a/solution/2200-2299/2279.Maximum Bags With Full Capacity of Rocks/README.md +++ b/solution/2200-2299/2279.Maximum Bags With Full Capacity of Rocks/README.md @@ -54,16 +54,10 @@ ## 解法 - - -**方法一:排序 + 贪心** +### 方法一:排序 + 贪心 -### **Python3** - - - ```python class Solution: def maximumBags( @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumBags(int[] capacity, int[] rocks, int additionalRocks) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func maximumBags(capacity []int, rocks []int, additionalRocks int) int { n := len(capacity) @@ -149,8 +135,6 @@ func maximumBags(capacity []int, rocks []int, additionalRocks int) int { } ``` -### **TypeScript** - ```ts function maximumBags(capacity: number[], rocks: number[], additionalRocks: number): number { const n = capacity.length; @@ -165,8 +149,6 @@ function maximumBags(capacity: number[], rocks: number[], additionalRocks: numbe } ``` -### **Rust** - ```rust impl Solution { pub fn maximum_bags(capacity: Vec, rocks: Vec, mut additional_rocks: i32) -> i32 { @@ -187,10 +169,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2279.Maximum Bags With Full Capacity of Rocks/README_EN.md b/solution/2200-2299/2279.Maximum Bags With Full Capacity of Rocks/README_EN.md index b8e8635bfa755..10b582216f105 100644 --- a/solution/2200-2299/2279.Maximum Bags With Full Capacity of Rocks/README_EN.md +++ b/solution/2200-2299/2279.Maximum Bags With Full Capacity of Rocks/README_EN.md @@ -50,9 +50,9 @@ Note that we did not use all of the additional rocks. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumBags(int[] capacity, int[] rocks, int additionalRocks) { @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +111,6 @@ public: }; ``` -### **Go** - ```go func maximumBags(capacity []int, rocks []int, additionalRocks int) int { n := len(capacity) @@ -137,8 +131,6 @@ func maximumBags(capacity []int, rocks []int, additionalRocks int) int { } ``` -### **TypeScript** - ```ts function maximumBags(capacity: number[], rocks: number[], additionalRocks: number): number { const n = capacity.length; @@ -153,8 +145,6 @@ function maximumBags(capacity: number[], rocks: number[], additionalRocks: numbe } ``` -### **Rust** - ```rust impl Solution { pub fn maximum_bags(capacity: Vec, rocks: Vec, mut additional_rocks: i32) -> i32 { @@ -175,10 +165,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2280.Minimum Lines to Represent a Line Chart/README.md b/solution/2200-2299/2280.Minimum Lines to Represent a Line Chart/README.md index 9719b11802d81..7787204f1e578 100644 --- a/solution/2200-2299/2280.Minimum Lines to Represent a Line Chart/README.md +++ b/solution/2200-2299/2280.Minimum Lines to Represent a Line Chart/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:斜率比较** +### 方法一:斜率比较 需要注意: @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def minimumLines(self, stockPrices: List[List[int]]) -> int: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumLines(int[][] stockPrices) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func minimumLines(stockPrices [][]int) int { ans := 0 @@ -145,8 +131,6 @@ func minimumLines(stockPrices [][]int) int { } ``` -### **TypeScript** - ```ts function minimumLines(stockPrices: number[][]): number { const n = stockPrices.length; @@ -165,10 +149,6 @@ function minimumLines(stockPrices: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2280.Minimum Lines to Represent a Line Chart/README_EN.md b/solution/2200-2299/2280.Minimum Lines to Represent a Line Chart/README_EN.md index 9ea23045b1a75..399c762409b14 100644 --- a/solution/2200-2299/2280.Minimum Lines to Represent a Line Chart/README_EN.md +++ b/solution/2200-2299/2280.Minimum Lines to Represent a Line Chart/README_EN.md @@ -44,9 +44,9 @@ As shown in the diagram above, the line chart can be represented with a single l ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumLines(int[][] stockPrices) { @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +103,6 @@ public: }; ``` -### **Go** - ```go func minimumLines(stockPrices [][]int) int { ans := 0 @@ -126,8 +120,6 @@ func minimumLines(stockPrices [][]int) int { } ``` -### **TypeScript** - ```ts function minimumLines(stockPrices: number[][]): number { const n = stockPrices.length; @@ -146,10 +138,6 @@ function minimumLines(stockPrices: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2281.Sum of Total Strength of Wizards/README.md b/solution/2200-2299/2281.Sum of Total Strength of Wizards/README.md index 0f3f9d1e2f875..47f776f3e89fb 100644 --- a/solution/2200-2299/2281.Sum of Total Strength of Wizards/README.md +++ b/solution/2200-2299/2281.Sum of Total Strength of Wizards/README.md @@ -64,18 +64,12 @@ ## 解法 - - -**方法一:单调栈 + 前缀和** +### 方法一:单调栈 + 前缀和 相似题目:[907. 子数组的最小值之和](/solution/0900-0999/0907.Sum%20of%20Subarray%20Minimums/README.md) -### **Python3** - - - ```python class Solution: def totalStrength(self, strength: List[int]) -> int: @@ -108,10 +102,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int totalStrength(int[] strength) { @@ -162,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -201,8 +189,6 @@ public: }; ``` -### **Go** - ```go func totalStrength(strength []int) int { n := len(strength) @@ -252,16 +238,6 @@ func totalStrength(strength []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2281.Sum of Total Strength of Wizards/README_EN.md b/solution/2200-2299/2281.Sum of Total Strength of Wizards/README_EN.md index 12594aa28e244..d256afe74d71b 100644 --- a/solution/2200-2299/2281.Sum of Total Strength of Wizards/README_EN.md +++ b/solution/2200-2299/2281.Sum of Total Strength of Wizards/README_EN.md @@ -62,9 +62,9 @@ The sum of all the total strengths is 25 + 16 + 36 + 36 + 40 + 60 = 213. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -98,8 +98,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int totalStrength(int[] strength) { @@ -150,8 +148,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -189,8 +185,6 @@ public: }; ``` -### **Go** - ```go func totalStrength(strength []int) int { n := len(strength) @@ -240,16 +234,6 @@ func totalStrength(strength []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/README.md b/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/README.md index 7fb983f55d108..f35dc8ce89168 100644 --- a/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/README.md +++ b/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 我们观察发现,对于第 $i$ 个人来说,他能看到的人一定是按从左到右(或者从上到下)高度严格单调递增的。 @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def seePeople(self, heights: List[List[int]]) -> List[List[int]]: @@ -112,10 +106,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] seePeople(int[][] heights) { @@ -159,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -204,8 +192,6 @@ public: }; ``` -### **Go** - ```go func seePeople(heights [][]int) (ans [][]int) { f := func(nums []int) []int { @@ -244,8 +230,6 @@ func seePeople(heights [][]int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function seePeople(heights: number[][]): number[][] { const f = (nums: number[]): number[] => { @@ -286,10 +270,6 @@ function seePeople(heights: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/README_EN.md b/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/README_EN.md index 6d112f3354463..5140d7390290e 100644 --- a/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/README_EN.md +++ b/solution/2200-2299/2282.Number of People That Can Be Seen in a Grid/README_EN.md @@ -55,9 +55,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -86,8 +86,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] seePeople(int[][] heights) { @@ -131,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +172,6 @@ public: }; ``` -### **Go** - ```go func seePeople(heights [][]int) (ans [][]int) { f := func(nums []int) []int { @@ -216,8 +210,6 @@ func seePeople(heights [][]int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function seePeople(heights: number[][]): number[][] { const f = (nums: number[]): number[] => { @@ -258,10 +250,6 @@ function seePeople(heights: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2283.Check if Number Has Equal Digit Count and Digit Value/README.md b/solution/2200-2299/2283.Check if Number Has Equal Digit Count and Digit Value/README.md index 767b91955dbe0..632ae00b1c12b 100644 --- a/solution/2200-2299/2283.Check if Number Has Equal Digit Count and Digit Value/README.md +++ b/solution/2200-2299/2283.Check if Number Has Equal Digit Count and Digit Value/README.md @@ -49,9 +49,7 @@ num[2] = '0' 。数字 2 在 num 中出现了 0 次。 ## 解法 - - -**方法一:计数 + 枚举** +### 方法一:计数 + 枚举 统计字符串中每个数字出现的次数,然后枚举每个数字,判断其出现的次数是否与其值相等,若都相等则返回 `true`,否则返回 `false`。 @@ -59,10 +57,6 @@ num[2] = '0' 。数字 2 在 num 中出现了 0 次。 -### **Python3** - - - ```python class Solution: def digitCount(self, num: str) -> bool: @@ -70,10 +64,6 @@ class Solution: return all(cnt[str(i)] == int(v) for i, v in enumerate(num)) ``` -### **Java** - - - ```java class Solution { public boolean digitCount(String num) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +100,6 @@ public: }; ``` -### **Go** - ```go func digitCount(num string) bool { cnt := [10]int{} @@ -129,8 +115,6 @@ func digitCount(num string) bool { } ``` -### **TypeScript** - ```ts function digitCount(num: string): boolean { const n = num.length; @@ -145,8 +129,6 @@ function digitCount(num: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn digit_count(num: String) -> bool { @@ -164,8 +146,6 @@ impl Solution { } ``` -### **C** - ```c bool digitCount(char* num) { int count[10] = {0}; @@ -184,10 +164,6 @@ bool digitCount(char* num) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2283.Check if Number Has Equal Digit Count and Digit Value/README_EN.md b/solution/2200-2299/2283.Check if Number Has Equal Digit Count and Digit Value/README_EN.md index 8045cd34e5714..2257f48c3dd58 100644 --- a/solution/2200-2299/2283.Check if Number Has Equal Digit Count and Digit Value/README_EN.md +++ b/solution/2200-2299/2283.Check if Number Has Equal Digit Count and Digit Value/README_EN.md @@ -45,9 +45,9 @@ The indices 0 and 1 both violate the condition, so return false. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return all(cnt[str(i)] == int(v) for i, v in enumerate(num)) ``` -### **Java** - ```java class Solution { public boolean digitCount(String num) { @@ -76,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func digitCount(num string) bool { cnt := [10]int{} @@ -113,8 +107,6 @@ func digitCount(num string) bool { } ``` -### **TypeScript** - ```ts function digitCount(num: string): boolean { const n = num.length; @@ -129,8 +121,6 @@ function digitCount(num: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn digit_count(num: String) -> bool { @@ -148,8 +138,6 @@ impl Solution { } ``` -### **C** - ```c bool digitCount(char* num) { int count[10] = {0}; @@ -168,10 +156,6 @@ bool digitCount(char* num) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2284.Sender With Largest Word Count/README.md b/solution/2200-2299/2284.Sender With Largest Word Count/README.md index cc6b797af7834..7bb85b2f6af31 100644 --- a/solution/2200-2299/2284.Sender With Largest Word Count/README.md +++ b/solution/2200-2299/2284.Sender With Largest Word Count/README.md @@ -56,9 +56,7 @@ Charlie 总共发出了 5 个单词。 ## 解法 - - -**方法一:哈希表 + 枚举** +### 方法一:哈希表 + 枚举 我们用哈希表 `cnt` 统计每个发件人的单词数,然后枚举每个发件人,找到单词数最多且字典序最大的发件人即可。 @@ -66,10 +64,6 @@ Charlie 总共发出了 5 个单词。 -### **Python3** - - - ```python class Solution: def largestWordCount(self, messages: List[str], senders: List[str]) -> str: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public String largestWordCount(String[] messages, String[] senders) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func largestWordCount(messages []string, senders []string) (ans string) { cnt := map[string]int{} @@ -155,16 +141,6 @@ func largestWordCount(messages []string, senders []string) (ans string) { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2284.Sender With Largest Word Count/README_EN.md b/solution/2200-2299/2284.Sender With Largest Word Count/README_EN.md index db16c71d5b44c..a1152fdaf6fa4 100644 --- a/solution/2200-2299/2284.Sender With Largest Word Count/README_EN.md +++ b/solution/2200-2299/2284.Sender With Largest Word Count/README_EN.md @@ -54,9 +54,9 @@ Since there is a tie for the largest word count, we return the sender with the l ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public String largestWordCount(String[] messages, String[] senders) { @@ -100,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func largestWordCount(messages []string, senders []string) (ans string) { cnt := map[string]int{} @@ -141,16 +135,6 @@ func largestWordCount(messages []string, senders []string) (ans string) { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2285.Maximum Total Importance of Roads/README.md b/solution/2200-2299/2285.Maximum Total Importance of Roads/README.md index 79fa70013a835..8bc117ddeb6bc 100644 --- a/solution/2200-2299/2285.Maximum Total Importance of Roads/README.md +++ b/solution/2200-2299/2285.Maximum Total Importance of Roads/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 考虑每个城市对所有道路的总重要性的贡献度,按贡献度从小到大排序,为城市依次分配 $[1, 2, ..., n]$。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def maximumImportance(self, n: int, roads: List[List[int]]) -> int: @@ -87,10 +81,6 @@ class Solution: return sum(i * v for i, v in enumerate(deg, 1)) ``` -### **Java** - - - ```java class Solution { public long maximumImportance(int n, int[][] roads) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func maximumImportance(n int, roads [][]int) int64 { deg := make([]int, n) @@ -146,16 +132,6 @@ func maximumImportance(n int, roads [][]int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2285.Maximum Total Importance of Roads/README_EN.md b/solution/2200-2299/2285.Maximum Total Importance of Roads/README_EN.md index 2fa655302c935..89bdc5b774e18 100644 --- a/solution/2200-2299/2285.Maximum Total Importance of Roads/README_EN.md +++ b/solution/2200-2299/2285.Maximum Total Importance of Roads/README_EN.md @@ -56,9 +56,9 @@ It can be shown that we cannot obtain a greater total importance than 20. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return sum(i * v for i, v in enumerate(deg, 1)) ``` -### **Java** - ```java class Solution { public long maximumImportance(int n, int[][] roads) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +106,6 @@ public: }; ``` -### **Go** - ```go func maximumImportance(n int, roads [][]int) int64 { deg := make([]int, n) @@ -128,16 +122,6 @@ func maximumImportance(n int, roads [][]int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2286.Booking Concert Tickets in Groups/README.md b/solution/2200-2299/2286.Booking Concert Tickets in Groups/README.md index 0be79cb53b279..f28e2e90b42d9 100644 --- a/solution/2200-2299/2286.Booking Concert Tickets in Groups/README.md +++ b/solution/2200-2299/2286.Booking Concert Tickets in Groups/README.md @@ -65,9 +65,7 @@ bms.scatter(5, 1); // 返回 False ## 解法 - - -**方法一:线段树** +### 方法一:线段树 分析题意我们得知: @@ -105,10 +103,6 @@ bms.scatter(5, 1); // 返回 False -### **Python3** - - - ```python class Node: def __init__(self): @@ -206,10 +200,6 @@ class BookMyShow: # param_2 = obj.scatter(k,maxRow) ``` -### **Java** - - - ```java class Node { int l, r; @@ -345,8 +335,6 @@ class BookMyShow { */ ``` -### **C++** - ```cpp class Node { public: @@ -485,8 +473,6 @@ private: */ ``` -### **Go** - ```go type BookMyShow struct { n, m int @@ -616,16 +602,6 @@ func (t *segmentTree) pushup(u int) { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2286.Booking Concert Tickets in Groups/README_EN.md b/solution/2200-2299/2286.Booking Concert Tickets in Groups/README_EN.md index 1fdfb02284305..63c08ed752aa4 100644 --- a/solution/2200-2299/2286.Booking Concert Tickets in Groups/README_EN.md +++ b/solution/2200-2299/2286.Booking Concert Tickets in Groups/README_EN.md @@ -61,9 +61,9 @@ bms.scatter(5, 1); // return False ## Solutions - +### Solution 1 -### **Python3** + ```python class Node: @@ -162,8 +162,6 @@ class BookMyShow: # param_2 = obj.scatter(k,maxRow) ``` -### **Java** - ```java class Node { int l, r; @@ -299,8 +297,6 @@ class BookMyShow { */ ``` -### **C++** - ```cpp class Node { public: @@ -439,8 +435,6 @@ private: */ ``` -### **Go** - ```go type BookMyShow struct { n, m int @@ -570,16 +564,6 @@ func (t *segmentTree) pushup(u int) { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2287.Rearrange Characters to Make Target String/README.md b/solution/2200-2299/2287.Rearrange Characters to Make Target String/README.md index d51d90bfd35ee..c497aab90a47f 100644 --- a/solution/2200-2299/2287.Rearrange Characters to Make Target String/README.md +++ b/solution/2200-2299/2287.Rearrange Characters to Make Target String/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们统计字符串 `s` 和 `target` 中每个字符出现的次数,记为 `cnt1` 和 `cnt2`。对于 `target` 中的每个字符,我们计算 `cnt1` 中该字符出现的次数除以 `cnt2` 中该字符出现的次数,取最小值即可。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def rearrangeCharacters(self, s: str, target: str) -> int: @@ -76,10 +70,6 @@ class Solution: return min(cnt1[c] // v for c, v in cnt2.items()) ``` -### **Java** - - - ```java class Solution { public int rearrangeCharacters(String s, String target) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func rearrangeCharacters(s string, target string) int { var cnt1, cnt2 [26]int @@ -148,8 +134,6 @@ func rearrangeCharacters(s string, target string) int { } ``` -### **TypeScript** - ```ts function rearrangeCharacters(s: string, target: string): number { const idx = (s: string) => s.charCodeAt(0) - 97; @@ -171,8 +155,6 @@ function rearrangeCharacters(s: string, target: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn rearrange_characters(s: String, target: String) -> i32 { @@ -195,8 +177,6 @@ impl Solution { } ``` -### **C** - ```c #define min(a, b) (((a) < (b)) ? (a) : (b)) @@ -219,10 +199,6 @@ int rearrangeCharacters(char* s, char* target) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2287.Rearrange Characters to Make Target String/README_EN.md b/solution/2200-2299/2287.Rearrange Characters to Make Target String/README_EN.md index dd35812988ed8..c2603a979665e 100644 --- a/solution/2200-2299/2287.Rearrange Characters to Make Target String/README_EN.md +++ b/solution/2200-2299/2287.Rearrange Characters to Make Target String/README_EN.md @@ -53,9 +53,9 @@ We can make at most one copy of "aaaaa", so we return 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return min(cnt1[c] // v for c, v in cnt2.items()) ``` -### **Java** - ```java class Solution { public int rearrangeCharacters(String s, String target) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +110,6 @@ public: }; ``` -### **Go** - ```go func rearrangeCharacters(s string, target string) int { var cnt1, cnt2 [26]int @@ -135,8 +129,6 @@ func rearrangeCharacters(s string, target string) int { } ``` -### **TypeScript** - ```ts function rearrangeCharacters(s: string, target: string): number { const idx = (s: string) => s.charCodeAt(0) - 97; @@ -158,8 +150,6 @@ function rearrangeCharacters(s: string, target: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn rearrange_characters(s: String, target: String) -> i32 { @@ -182,8 +172,6 @@ impl Solution { } ``` -### **C** - ```c #define min(a, b) (((a) < (b)) ? (a) : (b)) @@ -206,10 +194,6 @@ int rearrangeCharacters(char* s, char* target) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2288.Apply Discount to Prices/README.md b/solution/2200-2299/2288.Apply Discount to Prices/README.md index 1d00182357d46..cb5dfee3326d7 100644 --- a/solution/2200-2299/2288.Apply Discount to Prices/README.md +++ b/solution/2200-2299/2288.Apply Discount to Prices/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以将句子按空格分割成单词数组,然后遍历单词数组,对于每个单词,如果其表示价格,则将其更新为减免折扣后的价格。最后将更新后的单词数组拼接成以空格分隔的字符串即可。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def discountPrices(self, sentence: str, discount: int) -> str: @@ -82,10 +76,6 @@ class Solution: return ' '.join(ans) ``` -### **Java** - - - ```java class Solution { public String discountPrices(String sentence, int discount) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func discountPrices(sentence string, discount int) string { words := strings.Split(sentence, " ") @@ -166,8 +152,6 @@ func discountPrices(sentence string, discount int) string { } ``` -### **TypeScript** - ```ts function discountPrices(sentence: string, discount: number): string { const sell = (100 - discount) / 100; @@ -182,10 +166,6 @@ function discountPrices(sentence: string, discount: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2288.Apply Discount to Prices/README_EN.md b/solution/2200-2299/2288.Apply Discount to Prices/README_EN.md index b299927f888fb..39fe26bc3c188 100644 --- a/solution/2200-2299/2288.Apply Discount to Prices/README_EN.md +++ b/solution/2200-2299/2288.Apply Discount to Prices/README_EN.md @@ -54,9 +54,9 @@ Each of them is replaced by "0.00". ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return ' '.join(ans) ``` -### **Java** - ```java class Solution { public String discountPrices(String sentence, int discount) { @@ -98,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +131,6 @@ public: }; ``` -### **Go** - ```go func discountPrices(sentence string, discount int) string { words := strings.Split(sentence, " ") @@ -151,8 +145,6 @@ func discountPrices(sentence string, discount int) string { } ``` -### **TypeScript** - ```ts function discountPrices(sentence: string, discount: number): string { const sell = (100 - discount) / 100; @@ -167,10 +159,6 @@ function discountPrices(sentence: string, discount: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2289.Steps to Make Array Non-decreasing/README.md b/solution/2200-2299/2289.Steps to Make Array Non-decreasing/README.md index 7836ce255c0c3..4c72f91aff9cd 100644 --- a/solution/2200-2299/2289.Steps to Make Array Non-decreasing/README.md +++ b/solution/2200-2299/2289.Steps to Make Array Non-decreasing/README.md @@ -43,16 +43,10 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 -### **Python3** - - - ```python class Solution: def totalSteps(self, nums: List[int]) -> int: @@ -66,10 +60,6 @@ class Solution: return max(dp) ``` -### **Java** - - - ```java class Solution { public int totalSteps(int[] nums) { @@ -89,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +99,6 @@ public: }; ``` -### **Go** - ```go func totalSteps(nums []int) int { stk := []int{} @@ -130,8 +116,6 @@ func totalSteps(nums []int) int { } ``` -### **TypeScript** - ```ts function totalSteps(nums: number[]): number { let ans = 0; @@ -150,10 +134,6 @@ function totalSteps(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2289.Steps to Make Array Non-decreasing/README_EN.md b/solution/2200-2299/2289.Steps to Make Array Non-decreasing/README_EN.md index fa49cee40ccc0..1fc4ba4c9cea2 100644 --- a/solution/2200-2299/2289.Steps to Make Array Non-decreasing/README_EN.md +++ b/solution/2200-2299/2289.Steps to Make Array Non-decreasing/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return max(dp) ``` -### **Java** - ```java class Solution { public int totalSteps(int[] nums) { @@ -77,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +95,6 @@ public: }; ``` -### **Go** - ```go func totalSteps(nums []int) int { stk := []int{} @@ -118,8 +112,6 @@ func totalSteps(nums []int) int { } ``` -### **TypeScript** - ```ts function totalSteps(nums: number[]): number { let ans = 0; @@ -138,10 +130,6 @@ function totalSteps(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2290.Minimum Obstacle Removal to Reach Corner/README.md b/solution/2200-2299/2290.Minimum Obstacle Removal to Reach Corner/README.md index 96ac9d806f4cd..32e586b7a1408 100644 --- a/solution/2200-2299/2290.Minimum Obstacle Removal to Reach Corner/README.md +++ b/solution/2200-2299/2290.Minimum Obstacle Removal to Reach Corner/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:双端队列 BFS** +### 方法一:双端队列 BFS 本题实际上也是最短路模型,只不过求解的是移除障碍物的最小数目。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def minimumObstacles(self, grid: List[List[int]]) -> int: @@ -99,10 +93,6 @@ class Solution: q.append((x, y, k + 1)) ``` -### **Java** - - - ```java class Solution { public int minimumObstacles(int[][] grid) { @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -172,8 +160,6 @@ public: }; ``` -### **Go** - ```go func minimumObstacles(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -211,8 +197,6 @@ func minimumObstacles(grid [][]int) int { } ``` -### **TypeScript** - ```ts function minimumObstacles(grid: number[][]): number { const m = grid.length, @@ -241,10 +225,6 @@ function minimumObstacles(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2290.Minimum Obstacle Removal to Reach Corner/README_EN.md b/solution/2200-2299/2290.Minimum Obstacle Removal to Reach Corner/README_EN.md index 1d26debe672df..2d63703c306b0 100644 --- a/solution/2200-2299/2290.Minimum Obstacle Removal to Reach Corner/README_EN.md +++ b/solution/2200-2299/2290.Minimum Obstacle Removal to Reach Corner/README_EN.md @@ -48,9 +48,9 @@ Note that there may be other ways to remove 2 obstacles to create a path. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: q.append((x, y, k + 1)) ``` -### **Java** - ```java class Solution { public int minimumObstacles(int[][] grid) { @@ -110,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +142,6 @@ public: }; ``` -### **Go** - ```go func minimumObstacles(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -185,8 +179,6 @@ func minimumObstacles(grid [][]int) int { } ``` -### **TypeScript** - ```ts function minimumObstacles(grid: number[][]): number { const m = grid.length, @@ -215,10 +207,6 @@ function minimumObstacles(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/README.md b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/README.md index 4deb604c50e12..9108fd6ac8c40 100644 --- a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/README.md +++ b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示前 $i$ 支股票,预算为 $j$ 时的最大收益。那么答案就是 $f[n][budget]$。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def maximumProfit(self, present: List[int], future: List[int], budget: int) -> int: @@ -84,20 +78,6 @@ class Solution: return f[-1][-1] ``` -```python -class Solution: - def maximumProfit(self, present: List[int], future: List[int], budget: int) -> int: - f = [0] * (budget + 1) - for a, b in zip(present, future): - for j in range(budget, a - 1, -1): - f[j] = max(f[j], f[j - a] + b - a) - return f[-1] -``` - -### **Java** - - - ```java class Solution { public int maximumProfit(int[] present, int[] future, int budget) { @@ -117,24 +97,6 @@ class Solution { } ``` -```java -class Solution { - public int maximumProfit(int[] present, int[] future, int budget) { - int n = present.length; - int[] f = new int[budget + 1]; - for (int i = 0; i < n; ++i) { - int a = present[i], b = future[i]; - for (int j = budget; j >= a; --j) { - f[j] = Math.max(f[j], f[j - a] + b - a); - } - } - return f[budget]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -155,26 +117,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maximumProfit(vector& present, vector& future, int budget) { - int n = present.size(); - int f[budget + 1]; - memset(f, 0, sizeof f); - for (int i = 0; i < n; ++i) { - int a = present[i], b = future[i]; - for (int j = budget; j >= a; --j) { - f[j] = max(f[j], f[j - a] + b - a); - } - } - return f[budget]; - } -}; -``` - -### **Go** - ```go func maximumProfit(present []int, future []int, budget int) int { n := len(present) @@ -194,20 +136,6 @@ func maximumProfit(present []int, future []int, budget int) int { } ``` -```go -func maximumProfit(present []int, future []int, budget int) int { - f := make([]int, budget+1) - for i, a := range present { - for j := budget; j >= a; j-- { - f[j] = max(f[j], f[j-a]+future[i]-a) - } - } - return f[budget] -} -``` - -### **TypeScript** - ```ts function maximumProfit(present: number[], future: number[], budget: number): number { const f = new Array(budget + 1).fill(0); @@ -221,10 +149,68 @@ function maximumProfit(present: number[], future: number[], budget: number): num } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def maximumProfit(self, present: List[int], future: List[int], budget: int) -> int: + f = [0] * (budget + 1) + for a, b in zip(present, future): + for j in range(budget, a - 1, -1): + f[j] = max(f[j], f[j - a] + b - a) + return f[-1] +``` + +```java +class Solution { + public int maximumProfit(int[] present, int[] future, int budget) { + int n = present.length; + int[] f = new int[budget + 1]; + for (int i = 0; i < n; ++i) { + int a = present[i], b = future[i]; + for (int j = budget; j >= a; --j) { + f[j] = Math.max(f[j], f[j - a] + b - a); + } + } + return f[budget]; + } +} +``` +```cpp +class Solution { +public: + int maximumProfit(vector& present, vector& future, int budget) { + int n = present.size(); + int f[budget + 1]; + memset(f, 0, sizeof f); + for (int i = 0; i < n; ++i) { + int a = present[i], b = future[i]; + for (int j = budget; j >= a; --j) { + f[j] = max(f[j], f[j - a] + b - a); + } + } + return f[budget]; + } +}; ``` +```go +func maximumProfit(present []int, future []int, budget int) int { + f := make([]int, budget+1) + for i, a := range present { + for j := budget; j >= a; j-- { + f[j] = max(f[j], f[j-a]+future[i]-a) + } + } + return f[budget] +} ``` + + diff --git a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/README_EN.md b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/README_EN.md index f320051d33fc7..d16630e5f2598 100644 --- a/solution/2200-2299/2291.Maximum Profit From Trading Stocks/README_EN.md +++ b/solution/2200-2299/2291.Maximum Profit From Trading Stocks/README_EN.md @@ -53,9 +53,9 @@ It can be shown that the maximum profit you can make is 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,18 +69,6 @@ class Solution: return f[-1][-1] ``` -```python -class Solution: - def maximumProfit(self, present: List[int], future: List[int], budget: int) -> int: - f = [0] * (budget + 1) - for a, b in zip(present, future): - for j in range(budget, a - 1, -1): - f[j] = max(f[j], f[j - a] + b - a) - return f[-1] -``` - -### **Java** - ```java class Solution { public int maximumProfit(int[] present, int[] future, int budget) { @@ -100,24 +88,6 @@ class Solution { } ``` -```java -class Solution { - public int maximumProfit(int[] present, int[] future, int budget) { - int n = present.length; - int[] f = new int[budget + 1]; - for (int i = 0; i < n; ++i) { - int a = present[i], b = future[i]; - for (int j = budget; j >= a; --j) { - f[j] = Math.max(f[j], f[j - a] + b - a); - } - } - return f[budget]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -138,26 +108,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maximumProfit(vector& present, vector& future, int budget) { - int n = present.size(); - int f[budget + 1]; - memset(f, 0, sizeof f); - for (int i = 0; i < n; ++i) { - int a = present[i], b = future[i]; - for (int j = budget; j >= a; --j) { - f[j] = max(f[j], f[j - a] + b - a); - } - } - return f[budget]; - } -}; -``` - -### **Go** - ```go func maximumProfit(present []int, future []int, budget int) int { n := len(present) @@ -177,20 +127,6 @@ func maximumProfit(present []int, future []int, budget int) int { } ``` -```go -func maximumProfit(present []int, future []int, budget int) int { - f := make([]int, budget+1) - for i, a := range present { - for j := budget; j >= a; j-- { - f[j] = max(f[j], f[j-a]+future[i]-a) - } - } - return f[budget] -} -``` - -### **TypeScript** - ```ts function maximumProfit(present: number[], future: number[], budget: number): number { const f = new Array(budget + 1).fill(0); @@ -204,10 +140,68 @@ function maximumProfit(present: number[], future: number[], budget: number): num } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def maximumProfit(self, present: List[int], future: List[int], budget: int) -> int: + f = [0] * (budget + 1) + for a, b in zip(present, future): + for j in range(budget, a - 1, -1): + f[j] = max(f[j], f[j - a] + b - a) + return f[-1] ``` +```java +class Solution { + public int maximumProfit(int[] present, int[] future, int budget) { + int n = present.length; + int[] f = new int[budget + 1]; + for (int i = 0; i < n; ++i) { + int a = present[i], b = future[i]; + for (int j = budget; j >= a; --j) { + f[j] = Math.max(f[j], f[j - a] + b - a); + } + } + return f[budget]; + } +} +``` + +```cpp +class Solution { +public: + int maximumProfit(vector& present, vector& future, int budget) { + int n = present.size(); + int f[budget + 1]; + memset(f, 0, sizeof f); + for (int i = 0; i < n; ++i) { + int a = present[i], b = future[i]; + for (int j = budget; j >= a; --j) { + f[j] = max(f[j], f[j - a] + b - a); + } + } + return f[budget]; + } +}; +``` + +```go +func maximumProfit(present []int, future []int, budget int) int { + f := make([]int, budget+1) + for i, a := range present { + for j := budget; j >= a; j-- { + f[j] = max(f[j], f[j-a]+future[i]-a) + } + } + return f[budget] +} ``` + + diff --git a/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/README.md b/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/README.md index 96d24a84eb90c..34a3f14187bdd 100644 --- a/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/README.md +++ b/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/README.md @@ -60,14 +60,10 @@ Orders 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -83,6 +79,12 @@ FROM WHERE p1.mark AND p2.mark; ``` + + +### 方法二 + + + ```sql # Write your MySQL query statement below WITH @@ -99,3 +101,5 @@ FROM ``` + + diff --git a/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/README_EN.md b/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/README_EN.md index b4f27035d14d2..6746d51d586e3 100644 --- a/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/README_EN.md +++ b/solution/2200-2299/2292.Products With Three or More Orders in Two Consecutive Years/README_EN.md @@ -57,9 +57,9 @@ Product 2 was ordered one time in 2022. We do not include it in the answer. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -76,6 +76,12 @@ FROM WHERE p1.mark AND p2.mark; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below WITH @@ -92,3 +98,5 @@ FROM ``` + + diff --git a/solution/2200-2299/2293.Min Max Game/README.md b/solution/2200-2299/2293.Min Max Game/README.md index b883c2b1c7d37..6a67aa95e5ae9 100644 --- a/solution/2200-2299/2293.Min Max Game/README.md +++ b/solution/2200-2299/2293.Min Max Game/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 根据题意,我们可以模拟整个过程,最后剩下的数字即为答案。在实现上,我们不需要额外创建数组,直接在原数组上进行操作即可。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def minMaxGame(self, nums: List[int]) -> int: @@ -82,10 +76,6 @@ class Solution: return nums[0] ``` -### **Java** - - - ```java class Solution { public int minMaxGame(int[] nums) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func minMaxGame(nums []int) int { for n := len(nums); n > 1; { @@ -138,8 +124,6 @@ func minMaxGame(nums []int) int { } ``` -### **TypeScript** - ```ts function minMaxGame(nums: number[]): number { for (let n = nums.length; n > 1; ) { @@ -154,8 +138,6 @@ function minMaxGame(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_max_game(mut nums: Vec) -> i32 { @@ -174,8 +156,6 @@ impl Solution { } ``` -### **C** - ```c #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) @@ -193,10 +173,6 @@ int minMaxGame(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2293.Min Max Game/README_EN.md b/solution/2200-2299/2293.Min Max Game/README_EN.md index 15436ea367e30..6c417a77ea91d 100644 --- a/solution/2200-2299/2293.Min Max Game/README_EN.md +++ b/solution/2200-2299/2293.Min Max Game/README_EN.md @@ -50,9 +50,9 @@ Third: nums = [1] ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return nums[0] ``` -### **Java** - ```java class Solution { public int minMaxGame(int[] nums) { @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +97,6 @@ public: }; ``` -### **Go** - ```go func minMaxGame(nums []int) int { for n := len(nums); n > 1; { @@ -120,8 +114,6 @@ func minMaxGame(nums []int) int { } ``` -### **TypeScript** - ```ts function minMaxGame(nums: number[]): number { for (let n = nums.length; n > 1; ) { @@ -136,8 +128,6 @@ function minMaxGame(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_max_game(mut nums: Vec) -> i32 { @@ -156,8 +146,6 @@ impl Solution { } ``` -### **C** - ```c #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) @@ -175,10 +163,6 @@ int minMaxGame(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2294.Partition Array Such That Maximum Difference Is K/README.md b/solution/2200-2299/2294.Partition Array Such That Maximum Difference Is K/README.md index d7f1179ae3ab3..ce6e008ccafe9 100644 --- a/solution/2200-2299/2294.Partition Array Such That Maximum Difference Is K/README.md +++ b/solution/2200-2299/2294.Partition Array Such That Maximum Difference Is K/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 题目是要求划分子序列,而不是子数组,因此子序列中的元素可以不连续。我们可以将数组 `nums` 排序,假设当前子序列的第一个元素为 $a$,则子序列中的最大值和最小值的差值不会超过 $k$。因此我们可以遍历数组 `nums`,如果当前元素 $b$ 与 $a$ 的差值大于 $k$,则更新 $a$ 为 $b$,并将子序列数目加 1。遍历结束后,即可得到最少子序列数目,注意初始时子序列数目为 $1$。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def partitionArray(self, nums: List[int], k: int) -> int: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int partitionArray(int[] nums, int k) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func partitionArray(nums []int, k int) int { sort.Ints(nums) @@ -144,8 +130,6 @@ func partitionArray(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function partitionArray(nums: number[], k: number): number { nums.sort((a, b) => a - b); @@ -161,10 +145,6 @@ function partitionArray(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2294.Partition Array Such That Maximum Difference Is K/README_EN.md b/solution/2200-2299/2294.Partition Array Such That Maximum Difference Is K/README_EN.md index fcb8d54b42122..4aff36353033d 100644 --- a/solution/2200-2299/2294.Partition Array Such That Maximum Difference Is K/README_EN.md +++ b/solution/2200-2299/2294.Partition Array Such That Maximum Difference Is K/README_EN.md @@ -59,9 +59,9 @@ Since three subsequences were created, we return 3. It can be shown that 3 is th ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int partitionArray(int[] nums, int k) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func partitionArray(nums []int, k int) int { sort.Ints(nums) @@ -128,8 +122,6 @@ func partitionArray(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function partitionArray(nums: number[], k: number): number { nums.sort((a, b) => a - b); @@ -145,10 +137,6 @@ function partitionArray(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2295.Replace Elements in an Array/README.md b/solution/2200-2299/2295.Replace Elements in an Array/README.md index b9168323ddda1..22fb60d419f80 100644 --- a/solution/2200-2299/2295.Replace Elements in an Array/README.md +++ b/solution/2200-2299/2295.Replace Elements in an Array/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们先用哈希表 $d$ 记录数组 `nums` 中每个数字的下标,然后遍历操作数组 `operations`,对于每个操作 $[a, b]$,我们将 $a$ 在 `nums` 中的下标 $d[a]$ 对应的数字替换为 $b$,并更新 $d$ 中 $b$ 的下标为 $d[a]$。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]: @@ -84,10 +78,6 @@ class Solution: return nums ``` -### **Java** - - - ```java class Solution { public int[] arrayChange(int[] nums, int[][] operations) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func arrayChange(nums []int, operations [][]int) []int { d := map[int]int{} @@ -142,8 +128,6 @@ func arrayChange(nums []int, operations [][]int) []int { } ``` -### **TypeScript** - ```ts function arrayChange(nums: number[], operations: number[][]): number[] { const d = new Map(nums.map((v, i) => [v, i])); @@ -155,10 +139,6 @@ function arrayChange(nums: number[], operations: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2295.Replace Elements in an Array/README_EN.md b/solution/2200-2299/2295.Replace Elements in an Array/README_EN.md index a615d4db176e4..51bdafd08b19f 100644 --- a/solution/2200-2299/2295.Replace Elements in an Array/README_EN.md +++ b/solution/2200-2299/2295.Replace Elements in an Array/README_EN.md @@ -56,9 +56,9 @@ We return the array [2,1]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return nums ``` -### **Java** - ```java class Solution { public int[] arrayChange(int[] nums, int[][] operations) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +105,6 @@ public: }; ``` -### **Go** - ```go func arrayChange(nums []int, operations [][]int) []int { d := map[int]int{} @@ -126,8 +120,6 @@ func arrayChange(nums []int, operations [][]int) []int { } ``` -### **TypeScript** - ```ts function arrayChange(nums: number[], operations: number[][]): number[] { const d = new Map(nums.map((v, i) => [v, i])); @@ -139,10 +131,6 @@ function arrayChange(nums: number[], operations: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2296.Design a Text Editor/README.md b/solution/2200-2299/2296.Design a Text Editor/README.md index 443309cdbbc98..aba1e10e043d2 100644 --- a/solution/2200-2299/2296.Design a Text Editor/README.md +++ b/solution/2200-2299/2296.Design a Text Editor/README.md @@ -79,9 +79,7 @@ textEditor.cursorRight(6); // 返回 "practi" ## 解法 - - -**方法一:左右栈** +### 方法一:左右栈 我们可以使用两个栈 `left` 和 `right`,其中栈 `left` 存储光标左边的字符,另一个栈 `right` 存储光标右边的字符。 @@ -92,10 +90,6 @@ textEditor.cursorRight(6); // 返回 "practi" -### **Python3** - - - ```python class TextEditor: def __init__(self): @@ -132,10 +126,6 @@ class TextEditor: # param_4 = obj.cursorRight(k) ``` -### **Java** - - - ```java class TextEditor { private StringBuilder left = new StringBuilder(); @@ -183,8 +173,6 @@ class TextEditor { */ ``` -### **C++** - ```cpp class TextEditor { public: @@ -233,8 +221,6 @@ private: */ ``` -### **Go** - ```go type TextEditor struct { left, right []byte @@ -286,16 +272,6 @@ func (this *TextEditor) CursorRight(k int) string { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2296.Design a Text Editor/README_EN.md b/solution/2200-2299/2296.Design a Text Editor/README_EN.md index 6761f2403a7c8..36a794fb562db 100644 --- a/solution/2200-2299/2296.Design a Text Editor/README_EN.md +++ b/solution/2200-2299/2296.Design a Text Editor/README_EN.md @@ -74,9 +74,9 @@ textEditor.cursorRight(6); // return "practi" ## Solutions - +### Solution 1 -### **Python3** + ```python class TextEditor: @@ -114,8 +114,6 @@ class TextEditor: # param_4 = obj.cursorRight(k) ``` -### **Java** - ```java class TextEditor { private StringBuilder left = new StringBuilder(); @@ -163,8 +161,6 @@ class TextEditor { */ ``` -### **C++** - ```cpp class TextEditor { public: @@ -213,8 +209,6 @@ private: */ ``` -### **Go** - ```go type TextEditor struct { left, right []byte @@ -266,16 +260,6 @@ func (this *TextEditor) CursorRight(k int) string { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2297.Jump Game VIII/README.md b/solution/2200-2299/2297.Jump Game VIII/README.md index 73a542c8b8ac5..eb5445251d192 100644 --- a/solution/2200-2299/2297.Jump Game VIII/README.md +++ b/solution/2200-2299/2297.Jump Game VIII/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:单调栈 + 动态规划** +### 方法一:单调栈 + 动态规划 根据题目描述,我们实际上需要找到 $nums[i]$ 的下一个大于等于 $nums[i]$ 的位置 $j$,以及下一个小于 $nums[i]$ 的位置 $j$。我们利用单调栈可以在 $O(n)$ 的时间内找到这两个位置,然后构建邻接表 $g$,其中 $g[i]$ 表示下标 $i$ 可以跳转到的下标。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def minCost(self, nums: List[int], costs: List[int]) -> int: @@ -98,10 +92,6 @@ class Solution: return f[n - 1] ``` -### **Java** - - - ```java class Solution { public long minCost(int[] nums, int[] costs) { @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -181,8 +169,6 @@ public: }; ``` -### **Go** - ```go func minCost(nums []int, costs []int) int64 { n := len(nums) @@ -220,8 +206,6 @@ func minCost(nums []int, costs []int) int64 { } ``` -### **TypeScript** - ```ts function minCost(nums: number[], costs: number[]): number { const n = nums.length; @@ -257,10 +241,6 @@ function minCost(nums: number[], costs: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2297.Jump Game VIII/README_EN.md b/solution/2200-2299/2297.Jump Game VIII/README_EN.md index 2f162fc2e70f4..d367859377965 100644 --- a/solution/2200-2299/2297.Jump Game VIII/README_EN.md +++ b/solution/2200-2299/2297.Jump Game VIII/README_EN.md @@ -51,9 +51,9 @@ The total cost is 2. Note that you cannot jump directly from index 0 to index 2 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: return f[n - 1] ``` -### **Java** - ```java class Solution { public long minCost(int[] nums, int[] costs) { @@ -125,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -165,8 +161,6 @@ public: }; ``` -### **Go** - ```go func minCost(nums []int, costs []int) int64 { n := len(nums) @@ -204,8 +198,6 @@ func minCost(nums []int, costs []int) int64 { } ``` -### **TypeScript** - ```ts function minCost(nums: number[], costs: number[]): number { const n = nums.length; @@ -241,10 +233,6 @@ function minCost(nums: number[], costs: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2298.Tasks Count in the Weekend/README.md b/solution/2200-2299/2298.Tasks Count in the Weekend/README.md index 4c706884beb2c..87d96c0596db4 100644 --- a/solution/2200-2299/2298.Tasks Count in the Weekend/README.md +++ b/solution/2200-2299/2298.Tasks Count in the Weekend/README.md @@ -68,18 +68,12 @@ Task 6 是在周日提交的。 ## 解法 - - -**方法一:WEEKDAY() 函数** +### 方法一:WEEKDAY() 函数 `WEEKDAY()` 函数返回日期的工作日编号,从 0 开始,0 表示星期一,1 表示星期二,以此类推,6 表示星期日。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -89,3 +83,5 @@ FROM Tasks; ``` + + diff --git a/solution/2200-2299/2298.Tasks Count in the Weekend/README_EN.md b/solution/2200-2299/2298.Tasks Count in the Weekend/README_EN.md index 877973fd7e560..b8b2dc68e45af 100644 --- a/solution/2200-2299/2298.Tasks Count in the Weekend/README_EN.md +++ b/solution/2200-2299/2298.Tasks Count in the Weekend/README_EN.md @@ -66,9 +66,9 @@ Task 6 was submitted on Sunday. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -79,3 +79,5 @@ FROM Tasks; ``` + + diff --git a/solution/2200-2299/2299.Strong Password Checker II/README.md b/solution/2200-2299/2299.Strong Password Checker II/README.md index 5e5519fc050be..18104e176f8ba 100644 --- a/solution/2200-2299/2299.Strong Password Checker II/README.md +++ b/solution/2200-2299/2299.Strong Password Checker II/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:模拟 + 位运算** +### 方法一:模拟 + 位运算 根据题目描述,我们可以模拟检查密码是否满足题目要求的过程。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def strongPasswordCheckerII(self, password: str) -> bool: @@ -90,10 +84,6 @@ class Solution: return mask == 15 ``` -### **Java** - - - ```java class Solution { public boolean strongPasswordCheckerII(String password) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go func strongPasswordCheckerII(password string) bool { if len(password) < 8 { @@ -177,8 +163,6 @@ func strongPasswordCheckerII(password string) bool { } ``` -### **TypeScript** - ```ts function strongPasswordCheckerII(password: string): boolean { if (password.length < 8) { @@ -204,8 +188,6 @@ function strongPasswordCheckerII(password: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn strong_password_checker_ii(password: String) -> bool { @@ -236,8 +218,6 @@ impl Solution { } ``` -### **C** - ```c bool strongPasswordCheckerII(char* password) { int n = strlen(password); @@ -265,10 +245,6 @@ bool strongPasswordCheckerII(char* password) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2200-2299/2299.Strong Password Checker II/README_EN.md b/solution/2200-2299/2299.Strong Password Checker II/README_EN.md index 8b0fbb204b698..ddef7613a7c1f 100644 --- a/solution/2200-2299/2299.Strong Password Checker II/README_EN.md +++ b/solution/2200-2299/2299.Strong Password Checker II/README_EN.md @@ -51,9 +51,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return mask == 15 ``` -### **Java** - ```java class Solution { public boolean strongPasswordCheckerII(String password) { @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +130,6 @@ public: }; ``` -### **Go** - ```go func strongPasswordCheckerII(password string) bool { if len(password) < 8 { @@ -160,8 +154,6 @@ func strongPasswordCheckerII(password string) bool { } ``` -### **TypeScript** - ```ts function strongPasswordCheckerII(password: string): boolean { if (password.length < 8) { @@ -187,8 +179,6 @@ function strongPasswordCheckerII(password: string): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn strong_password_checker_ii(password: String) -> bool { @@ -219,8 +209,6 @@ impl Solution { } ``` -### **C** - ```c bool strongPasswordCheckerII(char* password) { int n = strlen(password); @@ -248,10 +236,6 @@ bool strongPasswordCheckerII(char* password) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README.md b/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README.md index 18ebe97f9298b..51459ab7d89bb 100644 --- a/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README.md +++ b/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 我们可以对药水数组进行排序,然后遍历咒语数组,对于每个咒语 $v$,利用二分查找找到第一个大于等于 $\frac{success}{v}$ 的药水,下标记为 $i$,那么药水的长度减去 $i$ 即为能跟该咒语成功组合的药水数目。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def successfulPairs( @@ -74,10 +68,6 @@ class Solution: return [m - bisect_left(potions, success / v) for v in spells] ``` -### **Java** - - - ```java class Solution { public int[] successfulPairs(int[] spells, int[] potions, long success) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func successfulPairs(spells []int, potions []int, success int64) (ans []int) { sort.Ints(potions) @@ -133,8 +119,6 @@ func successfulPairs(spells []int, potions []int, success int64) (ans []int) { } ``` -### **TypeScript** - ```ts function successfulPairs(spells: number[], potions: number[], success: number): number[] { potions.sort((a, b) => a - b); @@ -157,10 +141,6 @@ function successfulPairs(spells: number[], potions: number[], success: number): } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README_EN.md b/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README_EN.md index 5497820c1443b..7541a30eefd24 100644 --- a/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README_EN.md +++ b/solution/2300-2399/2300.Successful Pairs of Spells and Potions/README_EN.md @@ -48,7 +48,7 @@ Thus, [2,0,2] is returned. ## Solutions -**Solution 1: Sorting + Binary Search** +### Solution 1: Sorting + Binary Search We can sort the potion array, then traverse the spell array. For each spell $v$, we use binary search to find the first potion that is greater than or equal to $\frac{success}{v}$. We mark its index as $i$. The length of the potion array minus $i$ is the number of potions that can successfully combine with this spell. @@ -56,8 +56,6 @@ The time complexity is $O((m + n) \times \log m)$, and the space complexity is $ -### **Python3** - ```python class Solution: def successfulPairs( @@ -68,8 +66,6 @@ class Solution: return [m - bisect_left(potions, success / v) for v in spells] ``` -### **Java** - ```java class Solution { public int[] successfulPairs(int[] spells, int[] potions, long success) { @@ -93,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +105,6 @@ public: }; ``` -### **Go** - ```go func successfulPairs(spells []int, potions []int, success int64) (ans []int) { sort.Ints(potions) @@ -125,8 +117,6 @@ func successfulPairs(spells []int, potions []int, success int64) (ans []int) { } ``` -### **TypeScript** - ```ts function successfulPairs(spells: number[], potions: number[], success: number): number[] { potions.sort((a, b) => a - b); @@ -149,10 +139,6 @@ function successfulPairs(spells: number[], potions: number[], success: number): } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2301.Match Substring After Replacement/README.md b/solution/2300-2399/2301.Match Substring After Replacement/README.md index aed65741094bc..3223953fb65d4 100644 --- a/solution/2300-2399/2301.Match Substring After Replacement/README.md +++ b/solution/2300-2399/2301.Match Substring After Replacement/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:哈希表 + 枚举** +### 方法一:哈希表 + 枚举 我们先用哈希表 $d$ 记录每个字符可以替换成的字符集合。 @@ -67,18 +65,8 @@ 时间复杂度 $O(m \times n)$,空间复杂度 $O(C^2)$。其中 $m$ 和 $n$ 分别是字符串 $s$ 和 $sub$ 的长度,而 $C$ 是字符集的大小。 -**方法二:数组 + 枚举** - -由于字符集只包含大写和小写英文字母和数字,因此我们可以直接用一个 $128 \times 128$ 的数组 $d$ 记录每个字符可以替换成的字符集合。 - -时间复杂度 $O(m \times n)$,空间复杂度 $O(C^2)$。 - -### **Python3** - - - ```python class Solution: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: @@ -91,24 +79,6 @@ class Solution: return False ``` -```python -class Solution: - def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: - d = [[False] * 128 for _ in range(128)] - for a, b in mappings: - d[ord(a)][ord(b)] = True - for i in range(len(s) - len(sub) + 1): - if all( - a == b or d[ord(b)][ord(a)] for a, b in zip(s[i : i + len(sub)], sub) - ): - return True - return False -``` - -### **Java** - - - ```java class Solution { public boolean matchReplacement(String s, String sub, char[][] mappings) { @@ -134,19 +104,20 @@ class Solution { } ``` -```java +```cpp class Solution { - public boolean matchReplacement(String s, String sub, char[][] mappings) { - boolean[][] d = new boolean[128][128]; - for (var e : mappings) { - d[e[0]][e[1]] = true; +public: + bool matchReplacement(string s, string sub, vector>& mappings) { + unordered_map> d; + for (auto& e : mappings) { + d[e[0]].insert(e[1]); } - int m = s.length(), n = sub.length(); + int m = s.size(), n = sub.size(); for (int i = 0; i < m - n + 1; ++i) { - boolean ok = true; + bool ok = true; for (int j = 0; j < n && ok; ++j) { - char a = s.charAt(i + j), b = sub.charAt(j); - if (a != b && !d[b][a]) { + char a = s[i + j], b = sub[j]; + if (a != b && !d[b].count(a)) { ok = false; } } @@ -156,25 +127,71 @@ class Solution { } return false; } +}; +``` + +```go +func matchReplacement(s string, sub string, mappings [][]byte) bool { + d := map[byte]map[byte]bool{} + for _, e := range mappings { + if d[e[0]] == nil { + d[e[0]] = map[byte]bool{} + } + d[e[0]][e[1]] = true + } + for i := 0; i < len(s)-len(sub)+1; i++ { + ok := true + for j := 0; j < len(sub) && ok; j++ { + a, b := s[i+j], sub[j] + if a != b && !d[b][a] { + ok = false + } + } + if ok { + return true + } + } + return false } ``` -### **C++** + -```cpp +### 方法二:数组 + 枚举 + +由于字符集只包含大写和小写英文字母和数字,因此我们可以直接用一个 $128 \times 128$ 的数组 $d$ 记录每个字符可以替换成的字符集合。 + +时间复杂度 $O(m \times n)$,空间复杂度 $O(C^2)$。 + + + +```python +class Solution: + def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: + d = [[False] * 128 for _ in range(128)] + for a, b in mappings: + d[ord(a)][ord(b)] = True + for i in range(len(s) - len(sub) + 1): + if all( + a == b or d[ord(b)][ord(a)] for a, b in zip(s[i : i + len(sub)], sub) + ): + return True + return False +``` + +```java class Solution { -public: - bool matchReplacement(string s, string sub, vector>& mappings) { - unordered_map> d; - for (auto& e : mappings) { - d[e[0]].insert(e[1]); + public boolean matchReplacement(String s, String sub, char[][] mappings) { + boolean[][] d = new boolean[128][128]; + for (var e : mappings) { + d[e[0]][e[1]] = true; } - int m = s.size(), n = sub.size(); + int m = s.length(), n = sub.length(); for (int i = 0; i < m - n + 1; ++i) { - bool ok = true; + boolean ok = true; for (int j = 0; j < n && ok; ++j) { - char a = s[i + j], b = sub[j]; - if (a != b && !d[b].count(a)) { + char a = s.charAt(i + j), b = sub.charAt(j); + if (a != b && !d[b][a]) { ok = false; } } @@ -184,7 +201,7 @@ public: } return false; } -}; +} ``` ```cpp @@ -213,33 +230,6 @@ public: }; ``` -### **Go** - -```go -func matchReplacement(s string, sub string, mappings [][]byte) bool { - d := map[byte]map[byte]bool{} - for _, e := range mappings { - if d[e[0]] == nil { - d[e[0]] = map[byte]bool{} - } - d[e[0]][e[1]] = true - } - for i := 0; i < len(s)-len(sub)+1; i++ { - ok := true - for j := 0; j < len(sub) && ok; j++ { - a, b := s[i+j], sub[j] - if a != b && !d[b][a] { - ok = false - } - } - if ok { - return true - } - } - return false -} -``` - ```go func matchReplacement(s string, sub string, mappings [][]byte) bool { d := [128][128]bool{} @@ -262,16 +252,6 @@ func matchReplacement(s string, sub string, mappings [][]byte) bool { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2301.Match Substring After Replacement/README_EN.md b/solution/2300-2399/2301.Match Substring After Replacement/README_EN.md index b8fc469dbe92d..88d8c71488d1d 100644 --- a/solution/2300-2399/2301.Match Substring After Replacement/README_EN.md +++ b/solution/2300-2399/2301.Match Substring After Replacement/README_EN.md @@ -58,7 +58,7 @@ Now sub = "l33tb" is a substring of s, so we return true. ## Solutions -**Solution 1: Hash Table + Enumeration** +### Solution 1: Hash Table + Enumeration First, we use a hash table $d$ to record the set of characters that each character can be replaced with. @@ -68,16 +68,8 @@ At the end of the enumeration, it means that $sub$ cannot be obtained by replaci The time complexity is $O(m \times n)$, and the space complexity is $O(C^2)$. Here, $m$ and $n$ are the lengths of the strings $s$ and $sub$ respectively, and $C$ is the size of the character set. -**Solution 2: Array + Enumeration** - -Since the character set only contains uppercase and lowercase English letters and numbers, we can directly use a $128 \times 128$ array $d$ to record the set of characters that each character can be replaced with. - -The time complexity is $O(m \times n)$, and the space complexity is $O(C^2)$. - -### **Python3** - ```python class Solution: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: @@ -90,22 +82,6 @@ class Solution: return False ``` -```python -class Solution: - def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: - d = [[False] * 128 for _ in range(128)] - for a, b in mappings: - d[ord(a)][ord(b)] = True - for i in range(len(s) - len(sub) + 1): - if all( - a == b or d[ord(b)][ord(a)] for a, b in zip(s[i : i + len(sub)], sub) - ): - return True - return False -``` - -### **Java** - ```java class Solution { public boolean matchReplacement(String s, String sub, char[][] mappings) { @@ -131,19 +107,20 @@ class Solution { } ``` -```java +```cpp class Solution { - public boolean matchReplacement(String s, String sub, char[][] mappings) { - boolean[][] d = new boolean[128][128]; - for (var e : mappings) { - d[e[0]][e[1]] = true; +public: + bool matchReplacement(string s, string sub, vector>& mappings) { + unordered_map> d; + for (auto& e : mappings) { + d[e[0]].insert(e[1]); } - int m = s.length(), n = sub.length(); + int m = s.size(), n = sub.size(); for (int i = 0; i < m - n + 1; ++i) { - boolean ok = true; + bool ok = true; for (int j = 0; j < n && ok; ++j) { - char a = s.charAt(i + j), b = sub.charAt(j); - if (a != b && !d[b][a]) { + char a = s[i + j], b = sub[j]; + if (a != b && !d[b].count(a)) { ok = false; } } @@ -153,25 +130,71 @@ class Solution { } return false; } +}; +``` + +```go +func matchReplacement(s string, sub string, mappings [][]byte) bool { + d := map[byte]map[byte]bool{} + for _, e := range mappings { + if d[e[0]] == nil { + d[e[0]] = map[byte]bool{} + } + d[e[0]][e[1]] = true + } + for i := 0; i < len(s)-len(sub)+1; i++ { + ok := true + for j := 0; j < len(sub) && ok; j++ { + a, b := s[i+j], sub[j] + if a != b && !d[b][a] { + ok = false + } + } + if ok { + return true + } + } + return false } ``` -### **C++** + -```cpp +### Solution 2: Array + Enumeration + +Since the character set only contains uppercase and lowercase English letters and numbers, we can directly use a $128 \times 128$ array $d$ to record the set of characters that each character can be replaced with. + +The time complexity is $O(m \times n)$, and the space complexity is $O(C^2)$. + + + +```python +class Solution: + def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: + d = [[False] * 128 for _ in range(128)] + for a, b in mappings: + d[ord(a)][ord(b)] = True + for i in range(len(s) - len(sub) + 1): + if all( + a == b or d[ord(b)][ord(a)] for a, b in zip(s[i : i + len(sub)], sub) + ): + return True + return False +``` + +```java class Solution { -public: - bool matchReplacement(string s, string sub, vector>& mappings) { - unordered_map> d; - for (auto& e : mappings) { - d[e[0]].insert(e[1]); + public boolean matchReplacement(String s, String sub, char[][] mappings) { + boolean[][] d = new boolean[128][128]; + for (var e : mappings) { + d[e[0]][e[1]] = true; } - int m = s.size(), n = sub.size(); + int m = s.length(), n = sub.length(); for (int i = 0; i < m - n + 1; ++i) { - bool ok = true; + boolean ok = true; for (int j = 0; j < n && ok; ++j) { - char a = s[i + j], b = sub[j]; - if (a != b && !d[b].count(a)) { + char a = s.charAt(i + j), b = sub.charAt(j); + if (a != b && !d[b][a]) { ok = false; } } @@ -181,7 +204,7 @@ public: } return false; } -}; +} ``` ```cpp @@ -210,33 +233,6 @@ public: }; ``` -### **Go** - -```go -func matchReplacement(s string, sub string, mappings [][]byte) bool { - d := map[byte]map[byte]bool{} - for _, e := range mappings { - if d[e[0]] == nil { - d[e[0]] = map[byte]bool{} - } - d[e[0]][e[1]] = true - } - for i := 0; i < len(s)-len(sub)+1; i++ { - ok := true - for j := 0; j < len(sub) && ok; j++ { - a, b := s[i+j], sub[j] - if a != b && !d[b][a] { - ok = false - } - } - if ok { - return true - } - } - return false -} -``` - ```go func matchReplacement(s string, sub string, mappings [][]byte) bool { d := [128][128]bool{} @@ -259,16 +255,6 @@ func matchReplacement(s string, sub string, mappings [][]byte) bool { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/README.md b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/README.md index edd42477ad0fe..a64bad2b76335 100644 --- a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/README.md +++ b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:前缀和 + 二分查找** +### 方法一:前缀和 + 二分查找 我们先计算出数组 $nums$ 的前缀和数组 $s$,其中 $s[i]$ 表示数组 $nums$ 前 $i$ 个元素的和。 @@ -66,18 +64,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 -**方法二:双指针** - -我们可以使用双指针的方式,维护一个滑动窗口,使得窗口内的元素和小于 $k$。那么以当前元素为最后一个元素的子数组个数即为窗口的长度,我们将所有的窗口长度相加即为答案。 - -时间复杂度 $O(n)$,其中 $n$ 为数组 $nums$ 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: @@ -95,23 +83,6 @@ class Solution: return ans ``` -```python -class Solution: - def countSubarrays(self, nums: List[int], k: int) -> int: - ans = s = j = 0 - for i, v in enumerate(nums): - s += v - while s * (i - j + 1) >= k: - s -= nums[j] - j += 1 - ans += i - j + 1 - return ans -``` - -### **Java** - - - ```java class Solution { public long countSubarrays(int[] nums, long k) { @@ -138,24 +109,6 @@ class Solution { } ``` -```java -class Solution { - public long countSubarrays(int[] nums, long k) { - long ans = 0, s = 0; - for (int i = 0, j = 0; i < nums.length; ++i) { - s += nums[i]; - while (s * (i - j + 1) >= k) { - s -= nums[j++]; - } - ans += i - j + 1; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -184,25 +137,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long countSubarrays(vector& nums, long long k) { - long long ans = 0, s = 0; - for (int i = 0, j = 0; i < nums.size(); ++i) { - s += nums[i]; - while (s * (i - j + 1) >= k) { - s -= nums[j++]; - } - ans += i - j + 1; - } - return ans; - } -}; -``` - -### **Go** - ```go func countSubarrays(nums []int, k int64) (ans int64) { n := len(nums) @@ -226,6 +160,62 @@ func countSubarrays(nums []int, k int64) (ans int64) { } ``` + + +### 方法二:双指针 + +我们可以使用双指针的方式,维护一个滑动窗口,使得窗口内的元素和小于 $k$。那么以当前元素为最后一个元素的子数组个数即为窗口的长度,我们将所有的窗口长度相加即为答案。 + +时间复杂度 $O(n)$,其中 $n$ 为数组 $nums$ 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def countSubarrays(self, nums: List[int], k: int) -> int: + ans = s = j = 0 + for i, v in enumerate(nums): + s += v + while s * (i - j + 1) >= k: + s -= nums[j] + j += 1 + ans += i - j + 1 + return ans +``` + +```java +class Solution { + public long countSubarrays(int[] nums, long k) { + long ans = 0, s = 0; + for (int i = 0, j = 0; i < nums.length; ++i) { + s += nums[i]; + while (s * (i - j + 1) >= k) { + s -= nums[j++]; + } + ans += i - j + 1; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + long long countSubarrays(vector& nums, long long k) { + long long ans = 0, s = 0; + for (int i = 0, j = 0; i < nums.size(); ++i) { + s += nums[i]; + while (s * (i - j + 1) >= k) { + s -= nums[j++]; + } + ans += i - j + 1; + } + return ans; + } +}; +``` + ```go func countSubarrays(nums []int, k int64) (ans int64) { s, j := 0, 0 @@ -241,16 +231,6 @@ func countSubarrays(nums []int, k int64) (ans int64) { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/README_EN.md b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/README_EN.md index c50fe397433eb..3f60d0ed44f0a 100644 --- a/solution/2300-2399/2302.Count Subarrays With Score Less Than K/README_EN.md +++ b/solution/2300-2399/2302.Count Subarrays With Score Less Than K/README_EN.md @@ -52,7 +52,7 @@ Thus, there are 5 subarrays having scores less than 5. ## Solutions -**Solution 1: Prefix Sum + Binary Search** +### Solution 1: Prefix Sum + Binary Search First, we calculate the prefix sum array $s$ of the array $nums$, where $s[i]$ represents the sum of the first $i$ elements of the array $nums$. @@ -60,16 +60,8 @@ Next, we enumerate each element of the array $nums$ as the last element of the s The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. -**Solution 2: Two Pointers** - -We can use two pointers to maintain a sliding window, so that the sum of the elements in the window is less than $k$. The number of subarrays with the current element as the last element is the length of the window, and we add all window lengths to get the answer. - -The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: @@ -87,21 +79,6 @@ class Solution: return ans ``` -```python -class Solution: - def countSubarrays(self, nums: List[int], k: int) -> int: - ans = s = j = 0 - for i, v in enumerate(nums): - s += v - while s * (i - j + 1) >= k: - s -= nums[j] - j += 1 - ans += i - j + 1 - return ans -``` - -### **Java** - ```java class Solution { public long countSubarrays(int[] nums, long k) { @@ -128,24 +105,6 @@ class Solution { } ``` -```java -class Solution { - public long countSubarrays(int[] nums, long k) { - long ans = 0, s = 0; - for (int i = 0, j = 0; i < nums.length; ++i) { - s += nums[i]; - while (s * (i - j + 1) >= k) { - s -= nums[j++]; - } - ans += i - j + 1; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -174,25 +133,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long countSubarrays(vector& nums, long long k) { - long long ans = 0, s = 0; - for (int i = 0, j = 0; i < nums.size(); ++i) { - s += nums[i]; - while (s * (i - j + 1) >= k) { - s -= nums[j++]; - } - ans += i - j + 1; - } - return ans; - } -}; -``` - -### **Go** - ```go func countSubarrays(nums []int, k int64) (ans int64) { n := len(nums) @@ -216,6 +156,62 @@ func countSubarrays(nums []int, k int64) (ans int64) { } ``` + + +### Solution 2: Two Pointers + +We can use two pointers to maintain a sliding window, so that the sum of the elements in the window is less than $k$. The number of subarrays with the current element as the last element is the length of the window, and we add all window lengths to get the answer. + +The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. + + + +```python +class Solution: + def countSubarrays(self, nums: List[int], k: int) -> int: + ans = s = j = 0 + for i, v in enumerate(nums): + s += v + while s * (i - j + 1) >= k: + s -= nums[j] + j += 1 + ans += i - j + 1 + return ans +``` + +```java +class Solution { + public long countSubarrays(int[] nums, long k) { + long ans = 0, s = 0; + for (int i = 0, j = 0; i < nums.length; ++i) { + s += nums[i]; + while (s * (i - j + 1) >= k) { + s -= nums[j++]; + } + ans += i - j + 1; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + long long countSubarrays(vector& nums, long long k) { + long long ans = 0, s = 0; + for (int i = 0, j = 0; i < nums.size(); ++i) { + s += nums[i]; + while (s * (i - j + 1) >= k) { + s -= nums[j++]; + } + ans += i - j + 1; + } + return ans; + } +}; +``` + ```go func countSubarrays(nums []int, k int64) (ans int64) { s, j := 0, 0 @@ -231,16 +227,6 @@ func countSubarrays(nums []int, k int64) (ans int64) { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2303.Calculate Amount Paid in Taxes/README.md b/solution/2300-2399/2303.Calculate Amount Paid in Taxes/README.md index 17697b88cce17..c68c60e04c26f 100644 --- a/solution/2300-2399/2303.Calculate Amount Paid in Taxes/README.md +++ b/solution/2300-2399/2303.Calculate Amount Paid in Taxes/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们遍历 `brackets`,对于每个税级,计算该税级的税额,然后累加即可。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: @@ -90,10 +84,6 @@ class Solution: return ans / 100 ``` -### **Java** - - - ```java class Solution { public double calculateTax(int[][] brackets, int income) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func calculateTax(brackets [][]int, income int) float64 { var ans, prev int @@ -139,7 +125,17 @@ func calculateTax(brackets [][]int, income int) float64 { } ``` -### **Rust** +```ts +function calculateTax(brackets: number[][], income: number): number { + let ans = 0; + let prev = 0; + for (const [upper, percent] of brackets) { + ans += Math.max(0, Math.min(income, upper) - prev) * percent; + prev = upper; + } + return ans / 100; +} +``` ```rust impl Solution { @@ -158,24 +154,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function calculateTax(brackets: number[][], income: number): number { - let ans = 0; - let prev = 0; - for (const [upper, percent] of brackets) { - ans += Math.max(0, Math.min(income, upper) - prev) * percent; - prev = upper; - } - return ans / 100; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2303.Calculate Amount Paid in Taxes/README_EN.md b/solution/2300-2399/2303.Calculate Amount Paid in Taxes/README_EN.md index 3d9c9d3d6ef31..cbd6ad7e8f294 100644 --- a/solution/2300-2399/2303.Calculate Amount Paid in Taxes/README_EN.md +++ b/solution/2300-2399/2303.Calculate Amount Paid in Taxes/README_EN.md @@ -64,7 +64,7 @@ You have no income to tax, so you have to pay a total of 0 in taxes. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We traverse `brackets`, and for each tax bracket, we calculate the tax amount for that bracket, then accumulate it. @@ -72,8 +72,6 @@ The time complexity is $O(n)$, where $n$ is the length of `brackets`. The space -### **Python3** - ```python class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: @@ -84,8 +82,6 @@ class Solution: return ans / 100 ``` -### **Java** - ```java class Solution { public double calculateTax(int[][] brackets, int income) { @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func calculateTax(brackets [][]int, income int) float64 { var ans, prev int @@ -131,7 +123,17 @@ func calculateTax(brackets [][]int, income int) float64 { } ``` -### **Rust** +```ts +function calculateTax(brackets: number[][], income: number): number { + let ans = 0; + let prev = 0; + for (const [upper, percent] of brackets) { + ans += Math.max(0, Math.min(income, upper) - prev) * percent; + prev = upper; + } + return ans / 100; +} +``` ```rust impl Solution { @@ -150,24 +152,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function calculateTax(brackets: number[][], income: number): number { - let ans = 0; - let prev = 0; - for (const [upper, percent] of brackets) { - ans += Math.max(0, Math.min(income, upper) - prev) * percent; - prev = upper; - } - return ans / 100; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2304.Minimum Path Cost in a Grid/README.md b/solution/2300-2399/2304.Minimum Path Cost in a Grid/README.md index 3b4602a393a68..c3de0abc111f0 100644 --- a/solution/2300-2399/2304.Minimum Path Cost in a Grid/README.md +++ b/solution/2300-2399/2304.Minimum Path Cost in a Grid/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示从第一行出发,到达第 $i$ 行第 $j$ 列的最小路径代价。由于每次只能从上一行的某一列移动到当前行的某一列,因此 $f[i][j]$ 的值可以从 $f[i - 1][k]$ 转移而来,其中 $k$ 的取值范围为 $[0, n - 1]$。因此状态转移方程为: @@ -75,10 +73,6 @@ $$ -### **Python3** - - - ```python class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: @@ -93,10 +87,6 @@ class Solution: return min(f) ``` -### **Java** - - - ```java class Solution { public int minPathCost(int[][] grid, int[][] moveCost) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +135,6 @@ public: }; ``` -### **Go** - ```go func minPathCost(grid [][]int, moveCost [][]int) int { m, n := len(grid), len(grid[0]) @@ -167,7 +153,23 @@ func minPathCost(grid [][]int, moveCost [][]int) int { } ``` -### **Rust** +```ts +function minPathCost(grid: number[][], moveCost: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const f = grid[0]; + for (let i = 1; i < m; ++i) { + const g: number[] = Array(n).fill(Infinity); + for (let j = 0; j < n; ++j) { + for (let k = 0; k < n; ++k) { + g[j] = Math.min(g[j], f[k] + moveCost[grid[i - 1][k]][j] + grid[i][j]); + } + } + f.splice(0, n, ...g); + } + return Math.min(...f); +} +``` ```rust impl Solution { @@ -191,30 +193,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function minPathCost(grid: number[][], moveCost: number[][]): number { - const m = grid.length; - const n = grid[0].length; - const f = grid[0]; - for (let i = 1; i < m; ++i) { - const g: number[] = Array(n).fill(Infinity); - for (let j = 0; j < n; ++j) { - for (let k = 0; k < n; ++k) { - g[j] = Math.min(g[j], f[k] + moveCost[grid[i - 1][k]][j] + grid[i][j]); - } - } - f.splice(0, n, ...g); - } - return Math.min(...f); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2304.Minimum Path Cost in a Grid/README_EN.md b/solution/2300-2399/2304.Minimum Path Cost in a Grid/README_EN.md index 4dc8e27c68203..0bf12692d0c40 100644 --- a/solution/2300-2399/2304.Minimum Path Cost in a Grid/README_EN.md +++ b/solution/2300-2399/2304.Minimum Path Cost in a Grid/README_EN.md @@ -49,7 +49,7 @@ So the total cost of this path is 5 + 1 = 6. ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ to represent the minimum path cost from the first row to the $i$th row and $j$th column. Since we can only move from a column in the previous row to a column in the current row, the value of $f[i][j]$ can be transferred from $f[i - 1][k]$, where the range of $k$ is $[0, n - 1]$. Therefore, the state transition equation is: @@ -67,8 +67,6 @@ The time complexity is $O(m \times n^2)$, and the space complexity is $O(n)$. He -### **Python3** - ```python class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: @@ -83,8 +81,6 @@ class Solution: return min(f) ``` -### **Java** - ```java class Solution { public int minPathCost(int[][] grid, int[][] moveCost) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +129,6 @@ public: }; ``` -### **Go** - ```go func minPathCost(grid [][]int, moveCost [][]int) int { m, n := len(grid), len(grid[0]) @@ -155,7 +147,23 @@ func minPathCost(grid [][]int, moveCost [][]int) int { } ``` -### **Rust** +```ts +function minPathCost(grid: number[][], moveCost: number[][]): number { + const m = grid.length; + const n = grid[0].length; + const f = grid[0]; + for (let i = 1; i < m; ++i) { + const g: number[] = Array(n).fill(Infinity); + for (let j = 0; j < n; ++j) { + for (let k = 0; k < n; ++k) { + g[j] = Math.min(g[j], f[k] + moveCost[grid[i - 1][k]][j] + grid[i][j]); + } + } + f.splice(0, n, ...g); + } + return Math.min(...f); +} +``` ```rust impl Solution { @@ -179,30 +187,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function minPathCost(grid: number[][], moveCost: number[][]): number { - const m = grid.length; - const n = grid[0].length; - const f = grid[0]; - for (let i = 1; i < m; ++i) { - const g: number[] = Array(n).fill(Infinity); - for (let j = 0; j < n; ++j) { - for (let k = 0; k < n; ++k) { - g[j] = Math.min(g[j], f[k] + moveCost[grid[i - 1][k]][j] + grid[i][j]); - } - } - f.splice(0, n, ...g); - } - return Math.min(...f); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2305.Fair Distribution of Cookies/README.md b/solution/2300-2399/2305.Fair Distribution of Cookies/README.md index 27ec9c576a73a..57188b0f9935e 100644 --- a/solution/2300-2399/2305.Fair Distribution of Cookies/README.md +++ b/solution/2300-2399/2305.Fair Distribution of Cookies/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:回溯 + 剪枝** +### 方法一:回溯 + 剪枝 我们先对数组 $cookies$ 进行降序排序(减少搜索次数),然后创建一个长度为 $k$ 的数组 $cnt$,用于存储每个孩子分到的饼干数量。另外,用变量 $ans$ 维护当前的最小不公平程度,初始化一个很大的值。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] cookies; @@ -132,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +151,6 @@ public: }; ``` -### **Go** - ```go func distributeCookies(cookies []int, k int) int { sort.Sort(sort.Reverse(sort.IntSlice(cookies))) @@ -190,8 +176,6 @@ func distributeCookies(cookies []int, k int) int { } ``` -### **TypeScript** - ```ts function distributeCookies(cookies: number[], k: number): number { const cnt = new Array(k).fill(0); @@ -215,10 +199,6 @@ function distributeCookies(cookies: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2305.Fair Distribution of Cookies/README_EN.md b/solution/2300-2399/2305.Fair Distribution of Cookies/README_EN.md index 5cdbfaf9834ba..7966d24fd568e 100644 --- a/solution/2300-2399/2305.Fair Distribution of Cookies/README_EN.md +++ b/solution/2300-2399/2305.Fair Distribution of Cookies/README_EN.md @@ -47,7 +47,7 @@ It can be shown that there is no distribution with an unfairness less than 7. ## Solutions -**Solution 1: Backtracking + Pruning** +### Solution 1: Backtracking + Pruning First, we sort the array $cookies$ in descending order (to reduce the number of searches), and then create an array $cnt$ of length $k$ to store the number of cookies each child gets. Also, we use a variable $ans$ to maintain the current minimum degree of unfairness, initialized to a very large value. @@ -57,8 +57,6 @@ Finally, we return $ans$. -### **Python3** - ```python class Solution: def distributeCookies(self, cookies: List[int], k: int) -> int: @@ -81,8 +79,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] cookies; @@ -94,9 +90,11 @@ class Solution { public int distributeCookies(int[] cookies, int k) { n = cookies.length; cnt = new int[k]; + // 升序排列 Arrays.sort(cookies); this.cookies = cookies; this.k = k; + // 这里搜索顺序是 n-1, n-2,...0 dfs(n - 1); return ans; } @@ -122,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +149,6 @@ public: }; ``` -### **Go** - ```go func distributeCookies(cookies []int, k int) int { sort.Sort(sort.Reverse(sort.IntSlice(cookies))) @@ -180,8 +174,6 @@ func distributeCookies(cookies []int, k int) int { } ``` -### **TypeScript** - ```ts function distributeCookies(cookies: number[], k: number): number { const cnt = new Array(k).fill(0); @@ -205,10 +197,6 @@ function distributeCookies(cookies: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2306.Naming a Company/README.md b/solution/2300-2399/2306.Naming a Company/README.md index d7c9a0c44f5a5..54d3c74cbb718 100644 --- a/solution/2300-2399/2306.Naming a Company/README.md +++ b/solution/2300-2399/2306.Naming a Company/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:枚举计数** +### 方法一:枚举计数 我们定义 $f[i][j]$ 表示 $ideas$ 中以第 $i$ 个字母开头,替换为第 $j$ 个字母后,不在 $ideas$ 中的字符串的个数。初始时 $f[i][j] = 0$。另外,用一个哈希表 $s$ 记录 $ideas$ 中的字符串,方便我们开快速判断某个字符串是否在 $ideas$ 中。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def distinctNames(self, ideas: List[str]) -> int: @@ -101,10 +95,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long distinctNames(String[] ideas) { @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +159,6 @@ public: }; ``` -### **Go** - ```go func distinctNames(ideas []string) (ans int64) { s := map[string]bool{} @@ -205,8 +191,6 @@ func distinctNames(ideas []string) (ans int64) { } ``` -### **TypeScript** - ```ts function distinctNames(ideas: string[]): number { const s = new Set(ideas); @@ -238,10 +222,6 @@ function distinctNames(ideas: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2306.Naming a Company/README_EN.md b/solution/2300-2399/2306.Naming a Company/README_EN.md index d37fbb95838b2..9454ce4ed706c 100644 --- a/solution/2300-2399/2306.Naming a Company/README_EN.md +++ b/solution/2300-2399/2306.Naming a Company/README_EN.md @@ -56,7 +56,7 @@ The following are some examples of invalid selections: ## Solutions -**Solution 1: Enumeration Counting** +### Solution 1: Enumeration Counting We define $f[i][j]$ to represent the number of strings in $ideas$ that start with the $i$th letter and are not in $ideas$ after being replaced with the $j$th letter. Initially, $f[i][j] = 0$. Additionally, we use a hash table $s$ to record the strings in $ideas$, which allows us to quickly determine whether a string is in $ideas$. @@ -70,8 +70,6 @@ The time complexity is $O(n \times m \times |\Sigma|)$, and the space complexity -### **Python3** - ```python class Solution: def distinctNames(self, ideas: List[str]) -> int: @@ -95,8 +93,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long distinctNames(String[] ideas) { @@ -131,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +157,6 @@ public: }; ``` -### **Go** - ```go func distinctNames(ideas []string) (ans int64) { s := map[string]bool{} @@ -197,8 +189,6 @@ func distinctNames(ideas []string) (ans int64) { } ``` -### **TypeScript** - ```ts function distinctNames(ideas: string[]): number { const s = new Set(ideas); @@ -230,10 +220,6 @@ function distinctNames(ideas: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2307.Check for Contradictions in Equations/README.md b/solution/2300-2399/2307.Check for Contradictions in Equations/README.md index 3f8a4767f55bb..4132e97c4bade 100644 --- a/solution/2300-2399/2307.Check for Contradictions in Equations/README.md +++ b/solution/2300-2399/2307.Check for Contradictions in Equations/README.md @@ -57,9 +57,7 @@ a = 3, b = 1 和 c = 2. ## 解法 - - -**方法一:带权并查集** +### 方法一:带权并查集 我们先将字符串转换成从 $0$ 开始的整数,然后遍历所有的等式,将等式中的两个字符串映射成对应的整数 $a$ 和 $b$,如果这两个整数不在同一个集合中,就将它们合并到同一个集合中,并且记录下两个整数的权值,即 $a$ 与 $b$ 的比值。如果这两个整数在同一个集合中,就判断它们的权值是否满足等式,如果不满足就返回 `true`。 @@ -71,10 +69,6 @@ a = 3, b = 1 和 c = 2. -### **Python3** - - - ```python class Solution: def checkContradictions( @@ -108,10 +102,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -159,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -201,8 +189,6 @@ public: }; ``` -### **Go** - ```go func checkContradictions(equations [][]string, values []float64) bool { d := make(map[string]int) @@ -253,8 +239,6 @@ func checkContradictions(equations [][]string, values []float64) bool { } ``` -### **TypeScript** - ```ts function checkContradictions(equations: string[][], values: number[]): boolean { const d: { [key: string]: number } = {}; @@ -301,10 +285,6 @@ function checkContradictions(equations: string[][], values: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2307.Check for Contradictions in Equations/README_EN.md b/solution/2300-2399/2307.Check for Contradictions in Equations/README_EN.md index 29cc0e2295281..57244fa85cc70 100644 --- a/solution/2300-2399/2307.Check for Contradictions in Equations/README_EN.md +++ b/solution/2300-2399/2307.Check for Contradictions in Equations/README_EN.md @@ -53,7 +53,7 @@ Since the third equation is code / et = 0.5, we get a contradiction. ## Solutions -**Solution 1: Weighted Union-Find** +### Solution 1: Weighted Union-Find First, we convert the strings into integers starting from $0$. Then, we traverse all the equations, map the two strings in each equation to the corresponding integers $a$ and $b$. If these two integers are not in the same set, we merge them into the same set and record the weights of the two integers, which is the ratio of $a$ to $b$. If these two integers are in the same set, we check whether their weights satisfy the equation. If not, we return `true`. @@ -65,8 +65,6 @@ Similar problems: -### **Python3** - ```python class Solution: def checkContradictions( @@ -100,8 +98,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { private int[] p; @@ -149,8 +145,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -191,8 +185,6 @@ public: }; ``` -### **Go** - ```go func checkContradictions(equations [][]string, values []float64) bool { d := make(map[string]int) @@ -243,8 +235,6 @@ func checkContradictions(equations [][]string, values []float64) bool { } ``` -### **TypeScript** - ```ts function checkContradictions(equations: string[][], values: number[]): boolean { const d: { [key: string]: number } = {}; @@ -291,10 +281,6 @@ function checkContradictions(equations: string[][], values: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2308.Arrange Table by Gender/README.md b/solution/2300-2399/2308.Arrange Table by Gender/README.md index 17b868e9a08ca..b2098907664b6 100644 --- a/solution/2300-2399/2308.Arrange Table by Gender/README.md +++ b/solution/2300-2399/2308.Arrange Table by Gender/README.md @@ -71,14 +71,10 @@ Genders 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -101,6 +97,12 @@ FROM t ORDER BY rk1, rk2; ``` + + +### 方法二 + + + ```sql SELECT user_id, @@ -117,3 +119,5 @@ ORDER BY ``` + + diff --git a/solution/2300-2399/2308.Arrange Table by Gender/README_EN.md b/solution/2300-2399/2308.Arrange Table by Gender/README_EN.md index b47392371f0da..75615c2932450 100644 --- a/solution/2300-2399/2308.Arrange Table by Gender/README_EN.md +++ b/solution/2300-2399/2308.Arrange Table by Gender/README_EN.md @@ -70,9 +70,9 @@ Note that the IDs of each gender are sorted in ascending order. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -96,6 +96,12 @@ FROM t ORDER BY rk1, rk2; ``` + + +### Solution 2 + + + ```sql SELECT user_id, @@ -112,3 +118,5 @@ ORDER BY ``` + + diff --git a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/README.md b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/README.md index 7881e95490b5d..789cd8aafb4ca 100644 --- a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/README.md +++ b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:哈希表 + 枚举** +### 方法一:哈希表 + 枚举 我们先用哈希表 $ss$ 记录字符串 $s$ 中出现的所有字母,然后从大写字母表的最后一个字母开始枚举,如果当前字母的大写和小写形式都在 $ss$ 中,则返回该字母。 @@ -62,22 +60,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 和 $C$ 分别是字符串 $s$ 的长度和字符集的大小。 -**方法二:位运算(空间优化)** - -我们可以用两个整数 $mask1$ 和 $mask2$ 分别记录字符串 $s$ 中出现的小写字母和大写字母,其中 $mask1$ 的第 $i$ 位表示第 $i$ 个小写字母是否出现,而 $mask2$ 的第 $i$ 位表示第 $i$ 个大写字母是否出现。 - -然后我们将 $mask1$ 和 $mask2$ 进行与运算,得到的结果 $mask$ 的第 $i$ 位表示第 $i$ 个字母的大小写是否同时出现。 - -接下来我们只要获取 $mask$ 的二进制表示中最高位的 $1$ 的位置,将其转换为对应的大写字母即可。如果所有二进制位都不为 $1$,说明不存在大小写同时出现的字母,返回空字符串。 - -时间复杂度 $O(n)$,其中 $n$ 是字符串 $s$ 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def greatestLetter(self, s: str) -> str: @@ -88,23 +72,6 @@ class Solution: return '' ``` -```python -class Solution: - def greatestLetter(self, s: str) -> str: - mask1 = mask2 = 0 - for c in s: - if c.islower(): - mask1 |= 1 << (ord(c) - ord("a")) - else: - mask2 |= 1 << (ord(c) - ord("A")) - mask = mask1 & mask2 - return chr(mask.bit_length() - 1 + ord("A")) if mask else "" -``` - -### **Java** - - - ```java class Solution { public String greatestLetter(String s) { @@ -122,27 +89,6 @@ class Solution { } ``` -```java -class Solution { - public String greatestLetter(String s) { - int mask1 = 0, mask2 = 0; - for (int i = 0; i < s.length(); ++i) { - char c = s.charAt(i); - if (Character.isLowerCase(c)) { - mask1 |= 1 << (c - 'a'); - } else { - mask2 |= 1 << (c - 'A'); - } - } - int mask = mask1 & mask2; - return mask > 0 ? String.valueOf((char) (31 - Integer.numberOfLeadingZeros(mask) + 'A')) - : ""; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -158,26 +104,6 @@ public: }; ``` -```cpp -class Solution { -public: - string greatestLetter(string s) { - int mask1 = 0, mask2 = 0; - for (char& c : s) { - if (islower(c)) { - mask1 |= 1 << (c - 'a'); - } else { - mask2 |= 1 << (c - 'A'); - } - } - int mask = mask1 & mask2; - return mask ? string(1, 31 - __builtin_clz(mask) + 'A') : ""; - } -}; -``` - -### **Go** - ```go func greatestLetter(s string) string { ss := map[rune]bool{} @@ -193,26 +119,6 @@ func greatestLetter(s string) string { } ``` -```go -func greatestLetter(s string) string { - mask1, mask2 := 0, 0 - for _, c := range s { - if unicode.IsLower(c) { - mask1 |= 1 << (c - 'a') - } else { - mask2 |= 1 << (c - 'A') - } - } - mask := mask1 & mask2 - if mask == 0 { - return "" - } - return string(byte(bits.Len(uint(mask))-1) + 'A') -} -``` - -### **TypeScript** - ```ts function greatestLetter(s: string): string { const ss = new Array(128).fill(false); @@ -228,8 +134,6 @@ function greatestLetter(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn greatest_letter(s: String) -> String { @@ -251,8 +155,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -272,10 +174,88 @@ var greatestLetter = function (s) { }; ``` -### **...** + + +### 方法二:位运算(空间优化) + +我们可以用两个整数 $mask1$ 和 $mask2$ 分别记录字符串 $s$ 中出现的小写字母和大写字母,其中 $mask1$ 的第 $i$ 位表示第 $i$ 个小写字母是否出现,而 $mask2$ 的第 $i$ 位表示第 $i$ 个大写字母是否出现。 + +然后我们将 $mask1$ 和 $mask2$ 进行与运算,得到的结果 $mask$ 的第 $i$ 位表示第 $i$ 个字母的大小写是否同时出现。 + +接下来我们只要获取 $mask$ 的二进制表示中最高位的 $1$ 的位置,将其转换为对应的大写字母即可。如果所有二进制位都不为 $1$,说明不存在大小写同时出现的字母,返回空字符串。 + +时间复杂度 $O(n)$,其中 $n$ 是字符串 $s$ 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def greatestLetter(self, s: str) -> str: + mask1 = mask2 = 0 + for c in s: + if c.islower(): + mask1 |= 1 << (ord(c) - ord("a")) + else: + mask2 |= 1 << (ord(c) - ord("A")) + mask = mask1 & mask2 + return chr(mask.bit_length() - 1 + ord("A")) if mask else "" +``` + +```java +class Solution { + public String greatestLetter(String s) { + int mask1 = 0, mask2 = 0; + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (Character.isLowerCase(c)) { + mask1 |= 1 << (c - 'a'); + } else { + mask2 |= 1 << (c - 'A'); + } + } + int mask = mask1 & mask2; + return mask > 0 ? String.valueOf((char) (31 - Integer.numberOfLeadingZeros(mask) + 'A')) + : ""; + } +} +``` +```cpp +class Solution { +public: + string greatestLetter(string s) { + int mask1 = 0, mask2 = 0; + for (char& c : s) { + if (islower(c)) { + mask1 |= 1 << (c - 'a'); + } else { + mask2 |= 1 << (c - 'A'); + } + } + int mask = mask1 & mask2; + return mask ? string(1, 31 - __builtin_clz(mask) + 'A') : ""; + } +}; ``` +```go +func greatestLetter(s string) string { + mask1, mask2 := 0, 0 + for _, c := range s { + if unicode.IsLower(c) { + mask1 |= 1 << (c - 'a') + } else { + mask2 |= 1 << (c - 'A') + } + } + mask := mask1 & mask2 + if mask == 0 { + return "" + } + return string(byte(bits.Len(uint(mask))-1) + 'A') +} ``` + + diff --git a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/README_EN.md b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/README_EN.md index de9f263bcc6b2..9c4f036480307 100644 --- a/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/README_EN.md +++ b/solution/2300-2399/2309.Greatest English Letter in Upper and Lower Case/README_EN.md @@ -47,7 +47,7 @@ There is no letter that appears in both lower and upper case. ## Solutions -**Solution 1: Hash Table + Enumeration** +### Solution 1: Hash Table + Enumeration First, we use a hash table $ss$ to record all the letters that appear in the string $s$. Then we start enumerating from the last letter of the uppercase alphabet. If both the uppercase and lowercase forms of the current letter are in $ss$, we return that letter. @@ -55,20 +55,8 @@ At the end of the enumeration, if no letter that meets the conditions is found, The time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ and $C$ are the length of the string $s$ and the size of the character set, respectively. -**Solution 2: Bit Manipulation (Space Optimization)** - -We can use two integers $mask1$ and $mask2$ to record the lowercase and uppercase letters that appear in the string $s$, respectively. The $i$-th bit of $mask1$ indicates whether the $i$-th lowercase letter appears, and the $i$-th bit of $mask2$ indicates whether the $i$-th uppercase letter appears. - -Then we perform a bitwise AND operation on $mask1$ and $mask2$. The $i$-th bit of the resulting $mask$ indicates whether the $i$-th letter appears in both uppercase and lowercase. - -Next, we just need to get the position of the highest $1$ in the binary representation of $mask$, and convert it to the corresponding uppercase letter. If all binary bits are not $1$, it means that there is no letter that appears in both uppercase and lowercase, so we return an empty string. - -The time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def greatestLetter(self, s: str) -> str: @@ -79,21 +67,6 @@ class Solution: return '' ``` -```python -class Solution: - def greatestLetter(self, s: str) -> str: - mask1 = mask2 = 0 - for c in s: - if c.islower(): - mask1 |= 1 << (ord(c) - ord("a")) - else: - mask2 |= 1 << (ord(c) - ord("A")) - mask = mask1 & mask2 - return chr(mask.bit_length() - 1 + ord("A")) if mask else "" -``` - -### **Java** - ```java class Solution { public String greatestLetter(String s) { @@ -111,27 +84,6 @@ class Solution { } ``` -```java -class Solution { - public String greatestLetter(String s) { - int mask1 = 0, mask2 = 0; - for (int i = 0; i < s.length(); ++i) { - char c = s.charAt(i); - if (Character.isLowerCase(c)) { - mask1 |= 1 << (c - 'a'); - } else { - mask2 |= 1 << (c - 'A'); - } - } - int mask = mask1 & mask2; - return mask > 0 ? String.valueOf((char) (31 - Integer.numberOfLeadingZeros(mask) + 'A')) - : ""; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -147,26 +99,6 @@ public: }; ``` -```cpp -class Solution { -public: - string greatestLetter(string s) { - int mask1 = 0, mask2 = 0; - for (char& c : s) { - if (islower(c)) { - mask1 |= 1 << (c - 'a'); - } else { - mask2 |= 1 << (c - 'A'); - } - } - int mask = mask1 & mask2; - return mask ? string(1, 31 - __builtin_clz(mask) + 'A') : ""; - } -}; -``` - -### **Go** - ```go func greatestLetter(s string) string { ss := map[rune]bool{} @@ -182,26 +114,6 @@ func greatestLetter(s string) string { } ``` -```go -func greatestLetter(s string) string { - mask1, mask2 := 0, 0 - for _, c := range s { - if unicode.IsLower(c) { - mask1 |= 1 << (c - 'a') - } else { - mask2 |= 1 << (c - 'A') - } - } - mask := mask1 & mask2 - if mask == 0 { - return "" - } - return string(byte(bits.Len(uint(mask))-1) + 'A') -} -``` - -### **TypeScript** - ```ts function greatestLetter(s: string): string { const ss = new Array(128).fill(false); @@ -217,8 +129,6 @@ function greatestLetter(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn greatest_letter(s: String) -> String { @@ -240,8 +150,6 @@ impl Solution { } ``` -### **JavaScript** - ```js /** * @param {string} s @@ -261,10 +169,88 @@ var greatestLetter = function (s) { }; ``` -### **...** + + +### Solution 2: Bit Manipulation (Space Optimization) + +We can use two integers $mask1$ and $mask2$ to record the lowercase and uppercase letters that appear in the string $s$, respectively. The $i$-th bit of $mask1$ indicates whether the $i$-th lowercase letter appears, and the $i$-th bit of $mask2$ indicates whether the $i$-th uppercase letter appears. + +Then we perform a bitwise AND operation on $mask1$ and $mask2$. The $i$-th bit of the resulting $mask$ indicates whether the $i$-th letter appears in both uppercase and lowercase. + +Next, we just need to get the position of the highest $1$ in the binary representation of $mask$, and convert it to the corresponding uppercase letter. If all binary bits are not $1$, it means that there is no letter that appears in both uppercase and lowercase, so we return an empty string. + +The time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$. + + + +```python +class Solution: + def greatestLetter(self, s: str) -> str: + mask1 = mask2 = 0 + for c in s: + if c.islower(): + mask1 |= 1 << (ord(c) - ord("a")) + else: + mask2 |= 1 << (ord(c) - ord("A")) + mask = mask1 & mask2 + return chr(mask.bit_length() - 1 + ord("A")) if mask else "" +``` + +```java +class Solution { + public String greatestLetter(String s) { + int mask1 = 0, mask2 = 0; + for (int i = 0; i < s.length(); ++i) { + char c = s.charAt(i); + if (Character.isLowerCase(c)) { + mask1 |= 1 << (c - 'a'); + } else { + mask2 |= 1 << (c - 'A'); + } + } + int mask = mask1 & mask2; + return mask > 0 ? String.valueOf((char) (31 - Integer.numberOfLeadingZeros(mask) + 'A')) + : ""; + } +} +``` +```cpp +class Solution { +public: + string greatestLetter(string s) { + int mask1 = 0, mask2 = 0; + for (char& c : s) { + if (islower(c)) { + mask1 |= 1 << (c - 'a'); + } else { + mask2 |= 1 << (c - 'A'); + } + } + int mask = mask1 & mask2; + return mask ? string(1, 31 - __builtin_clz(mask) + 'A') : ""; + } +}; ``` +```go +func greatestLetter(s string) string { + mask1, mask2 := 0, 0 + for _, c := range s { + if unicode.IsLower(c) { + mask1 |= 1 << (c - 'a') + } else { + mask2 |= 1 << (c - 'A') + } + } + mask := mask1 & mask2 + if mask == 0 { + return "" + } + return string(byte(bits.Len(uint(mask))-1) + 'A') +} ``` + + diff --git a/solution/2300-2399/2310.Sum of Numbers With Units Digit K/README.md b/solution/2300-2399/2310.Sum of Numbers With Units Digit K/README.md index a2f22d180b23f..6edba17bc280e 100644 --- a/solution/2300-2399/2310.Sum of Numbers With Units Digit K/README.md +++ b/solution/2300-2399/2310.Sum of Numbers With Units Digit K/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:数学 + 枚举** +### 方法一:数学 + 枚举 符合拆分条件的每个数都可以表示成 $10x_i+k$,若总共有 $n$ 个数,那么 $num-n*k$ 必然是 $10$ 的倍数。 @@ -71,14 +69,8 @@ 也可以只考虑个位,个位满足,高位随意。 -**方法二:记忆化搜索** - -### **Python3** - - - ```python class Solution: def minimumNumbers(self, num: int, k: int) -> int: @@ -90,45 +82,6 @@ class Solution: return -1 ``` -```python -class Solution: - def minimumNumbers(self, num: int, k: int) -> int: - if num == 0: - return 0 - for i in range(1, 11): - if (k * i) % 10 == num % 10 and k * i <= num: - return i - return -1 -``` - -```python -class Solution: - def minimumNumbers(self, num: int, k: int) -> int: - @cache - def dfs(v): - if v == 0: - return 0 - if v < 10 and v % k: - return inf - i = 0 - t = inf - while (x := i * 10 + k) <= v: - t = min(t, dfs(v - x)) - i += 1 - return t + 1 - - if num == 0: - return 0 - if k == 0: - return -1 if num % 10 else 1 - ans = dfs(num) - return -1 if ans >= inf else ans -``` - -### **Java** - - - ```java class Solution { public int minimumNumbers(int num, int k) { @@ -146,24 +99,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumNumbers(int num, int k) { - if (num == 0) { - return 0; - } - for (int i = 1; i <= 10; ++i) { - if ((k * i) % 10 == num % 10 && k * i <= num) { - return i; - } - } - return -1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -178,21 +113,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minimumNumbers(int num, int k) { - if (!num) return 0; - for (int i = 1; i <= 10; ++i) - if ((k * i) % 10 == num % 10 && k * i <= num) - return i; - return -1; - } -}; -``` - -### **Go** - ```go func minimumNumbers(num int, k int) int { if num == 0 { @@ -208,6 +128,64 @@ func minimumNumbers(num int, k int) int { } ``` +```ts +function minimumNumbers(num: number, k: number): number { + if (!num) return 0; + let digit = num % 10; + for (let i = 1; i < 11; i++) { + let target = i * k; + if (target <= num && target % 10 == digit) return i; + } + return -1; +} +``` + + + +### 方法二:记忆化搜索 + + + +```python +class Solution: + def minimumNumbers(self, num: int, k: int) -> int: + if num == 0: + return 0 + for i in range(1, 11): + if (k * i) % 10 == num % 10 and k * i <= num: + return i + return -1 +``` + +```java +class Solution { + public int minimumNumbers(int num, int k) { + if (num == 0) { + return 0; + } + for (int i = 1; i <= 10; ++i) { + if ((k * i) % 10 == num % 10 && k * i <= num) { + return i; + } + } + return -1; + } +} +``` + +```cpp +class Solution { +public: + int minimumNumbers(int num, int k) { + if (!num) return 0; + for (int i = 1; i <= 10; ++i) + if ((k * i) % 10 == num % 10 && k * i <= num) + return i; + return -1; + } +}; +``` + ```go func minimumNumbers(num int, k int) int { if num == 0 { @@ -222,24 +200,36 @@ func minimumNumbers(num int, k int) int { } ``` -### **TypeScript** + -```ts -function minimumNumbers(num: number, k: number): number { - if (!num) return 0; - let digit = num % 10; - for (let i = 1; i < 11; i++) { - let target = i * k; - if (target <= num && target % 10 == digit) return i; - } - return -1; -} -``` +### 方法三 -### **...** + -``` +```python +class Solution: + def minimumNumbers(self, num: int, k: int) -> int: + @cache + def dfs(v): + if v == 0: + return 0 + if v < 10 and v % k: + return inf + i = 0 + t = inf + while (x := i * 10 + k) <= v: + t = min(t, dfs(v - x)) + i += 1 + return t + 1 + if num == 0: + return 0 + if k == 0: + return -1 if num % 10 else 1 + ans = dfs(num) + return -1 if ans >= inf else ans ``` + + diff --git a/solution/2300-2399/2310.Sum of Numbers With Units Digit K/README_EN.md b/solution/2300-2399/2310.Sum of Numbers With Units Digit K/README_EN.md index cc3e50a9b44dc..32f9885cf7c99 100644 --- a/solution/2300-2399/2310.Sum of Numbers With Units Digit K/README_EN.md +++ b/solution/2300-2399/2310.Sum of Numbers With Units Digit K/README_EN.md @@ -58,9 +58,9 @@ It can be shown that 2 is the minimum possible size of a valid set. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,43 +73,6 @@ class Solution: return -1 ``` -```python -class Solution: - def minimumNumbers(self, num: int, k: int) -> int: - if num == 0: - return 0 - for i in range(1, 11): - if (k * i) % 10 == num % 10 and k * i <= num: - return i - return -1 -``` - -```python -class Solution: - def minimumNumbers(self, num: int, k: int) -> int: - @cache - def dfs(v): - if v == 0: - return 0 - if v < 10 and v % k: - return inf - i = 0 - t = inf - while (x := i * 10 + k) <= v: - t = min(t, dfs(v - x)) - i += 1 - return t + 1 - - if num == 0: - return 0 - if k == 0: - return -1 if num % 10 else 1 - ans = dfs(num) - return -1 if ans >= inf else ans -``` - -### **Java** - ```java class Solution { public int minimumNumbers(int num, int k) { @@ -127,24 +90,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumNumbers(int num, int k) { - if (num == 0) { - return 0; - } - for (int i = 1; i <= 10; ++i) { - if ((k * i) % 10 == num % 10 && k * i <= num) { - return i; - } - } - return -1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -159,21 +104,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minimumNumbers(int num, int k) { - if (!num) return 0; - for (int i = 1; i <= 10; ++i) - if ((k * i) % 10 == num % 10 && k * i <= num) - return i; - return -1; - } -}; -``` - -### **Go** - ```go func minimumNumbers(num int, k int) int { if num == 0 { @@ -189,6 +119,64 @@ func minimumNumbers(num int, k int) int { } ``` +```ts +function minimumNumbers(num: number, k: number): number { + if (!num) return 0; + let digit = num % 10; + for (let i = 1; i < 11; i++) { + let target = i * k; + if (target <= num && target % 10 == digit) return i; + } + return -1; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minimumNumbers(self, num: int, k: int) -> int: + if num == 0: + return 0 + for i in range(1, 11): + if (k * i) % 10 == num % 10 and k * i <= num: + return i + return -1 +``` + +```java +class Solution { + public int minimumNumbers(int num, int k) { + if (num == 0) { + return 0; + } + for (int i = 1; i <= 10; ++i) { + if ((k * i) % 10 == num % 10 && k * i <= num) { + return i; + } + } + return -1; + } +} +``` + +```cpp +class Solution { +public: + int minimumNumbers(int num, int k) { + if (!num) return 0; + for (int i = 1; i <= 10; ++i) + if ((k * i) % 10 == num % 10 && k * i <= num) + return i; + return -1; + } +}; +``` + ```go func minimumNumbers(num int, k int) int { if num == 0 { @@ -203,24 +191,36 @@ func minimumNumbers(num int, k int) int { } ``` -### **TypeScript** + -```ts -function minimumNumbers(num: number, k: number): number { - if (!num) return 0; - let digit = num % 10; - for (let i = 1; i < 11; i++) { - let target = i * k; - if (target <= num && target % 10 == digit) return i; - } - return -1; -} -``` +### Solution 3 -### **...** + -``` +```python +class Solution: + def minimumNumbers(self, num: int, k: int) -> int: + @cache + def dfs(v): + if v == 0: + return 0 + if v < 10 and v % k: + return inf + i = 0 + t = inf + while (x := i * 10 + k) <= v: + t = min(t, dfs(v - x)) + i += 1 + return t + 1 + if num == 0: + return 0 + if k == 0: + return -1 if num % 10 else 1 + ans = dfs(num) + return -1 if ans >= inf else ans ``` + + diff --git a/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/README.md b/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/README.md index 962b58c5da9d4..00950db72a29d 100644 --- a/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/README.md +++ b/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 最长二进制子序列必然包含原字符串中所有的 $0$,在此基础上,我们从右到左遍历 $s$,若遇到 $1$,判断子序列能否添加 $1$,使得子序列对应的二进制数字 $v \leq k$。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def longestSubsequence(self, s: str, k: int) -> int: @@ -76,10 +70,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestSubsequence(String s, int k) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func longestSubsequence(s string, k int) (ans int) { for i, v := len(s)-1, 0; i >= 0; i-- { @@ -133,8 +119,6 @@ func longestSubsequence(s string, k int) (ans int) { } ``` -### **TypeScript** - ```ts function longestSubsequence(s: string, k: number): number { let ans = 0; @@ -150,27 +134,6 @@ function longestSubsequence(s: string, k: number): number { } ``` -### **C#** - -```cs -public class Solution { - public int LongestSubsequence(string s, int k) { - int ans = 0, v = 0; - for (int i = s.Length - 1; i >= 0; --i) { - if (s[i] == '0') { - ++ans; - } else if (ans < 30 && (v | 1 << ans) <= k) { - v |= 1 << ans; - ++ans; - } - } - return ans; - } -} -``` - -### **JavaScript** - ```js /** * @param {string} s @@ -191,10 +154,23 @@ var longestSubsequence = function (s, k) { }; ``` -### **...** - -``` - +```cs +public class Solution { + public int LongestSubsequence(string s, int k) { + int ans = 0, v = 0; + for (int i = s.Length - 1; i >= 0; --i) { + if (s[i] == '0') { + ++ans; + } else if (ans < 30 && (v | 1 << ans) <= k) { + v |= 1 << ans; + ++ans; + } + } + return ans; + } +} ``` + + diff --git a/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/README_EN.md b/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/README_EN.md index d348402bbe674..24d7d8b7223dc 100644 --- a/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/README_EN.md +++ b/solution/2300-2399/2311.Longest Binary Subsequence Less Than or Equal to K/README_EN.md @@ -47,9 +47,9 @@ The length of this subsequence is 6, so 6 is returned. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestSubsequence(String s, int k) { @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +99,6 @@ public: }; ``` -### **Go** - ```go func longestSubsequence(s string, k int) (ans int) { for i, v := len(s)-1, 0; i >= 0; i-- { @@ -119,8 +113,6 @@ func longestSubsequence(s string, k int) (ans int) { } ``` -### **TypeScript** - ```ts function longestSubsequence(s: string, k: number): number { let ans = 0; @@ -136,27 +128,6 @@ function longestSubsequence(s: string, k: number): number { } ``` -### **C#** - -```cs -public class Solution { - public int LongestSubsequence(string s, int k) { - int ans = 0, v = 0; - for (int i = s.Length - 1; i >= 0; --i) { - if (s[i] == '0') { - ++ans; - } else if (ans < 30 && (v | 1 << ans) <= k) { - v |= 1 << ans; - ++ans; - } - } - return ans; - } -} -``` - -### **JavaScript** - ```js /** * @param {string} s @@ -177,10 +148,23 @@ var longestSubsequence = function (s, k) { }; ``` -### **...** - -``` - +```cs +public class Solution { + public int LongestSubsequence(string s, int k) { + int ans = 0, v = 0; + for (int i = s.Length - 1; i >= 0; --i) { + if (s[i] == '0') { + ++ans; + } else if (ans < 30 && (v | 1 << ans) <= k) { + v |= 1 << ans; + ++ans; + } + } + return ans; + } +} ``` + + diff --git a/solution/2300-2399/2312.Selling Pieces of Wood/README.md b/solution/2300-2399/2312.Selling Pieces of Wood/README.md index 9bbedcce9594b..e99ed3e8cda75 100644 --- a/solution/2300-2399/2312.Selling Pieces of Wood/README.md +++ b/solution/2300-2399/2312.Selling Pieces of Wood/README.md @@ -68,24 +68,10 @@ ## 解法 - - -**方法一:记忆化搜索** - -**方法二:动态规划** - -设 $dp[i][j]$ 表示对一块高为 $i$,宽为 $j$ 的木块切割后能得到的最多钱数。答案就是 $dp[m][n]$。 - -时间复杂度 $O(mn(m+n))$。 - -相似题目:[1444. 切披萨的方案数](/solution/1400-1499/1444.Number%20of%20Ways%20of%20Cutting%20a%20Pizza/README.md) +### 方法一:记忆化搜索 -### **Python3** - - - ```python class Solution: def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int: @@ -104,27 +90,6 @@ class Solution: return dfs(m, n) ``` -```python -class Solution: - def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int: - d = defaultdict(dict) - for h, w, p in prices: - d[h][w] = p - dp = [[0] * (n + 1) for _ in range(m + 1)] - for i in range(1, m + 1): - for j in range(1, n + 1): - dp[i][j] = d[i].get(j, 0) - for k in range(1, i): - dp[i][j] = max(dp[i][j], dp[k][j] + dp[i - k][j]) - for k in range(1, j): - dp[i][j] = max(dp[i][j], dp[i][k] + dp[i][j - k]) - return dp[-1][-1] -``` - -### **Java** - - - ```java class Solution { private long[][] memo; @@ -160,32 +125,6 @@ class Solution { } ``` -```java -class Solution { - public long sellingWood(int m, int n, int[][] prices) { - int[][] d = new int[m + 1][n + 1]; - long[][] dp = new long[m + 1][n + 1]; - for (int[] p : prices) { - d[p[0]][p[1]] = p[2]; - } - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - dp[i][j] = d[i][j]; - for (int k = 1; k < i; ++k) { - dp[i][j] = Math.max(dp[i][j], dp[k][j] + dp[i - k][j]); - } - for (int k = 1; k < j; ++k) { - dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[i][j - k]); - } - } - } - return dp[m][n]; - } -} -``` - -### **C++** - ```cpp using ll = long long; @@ -209,27 +148,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long sellingWood(int m, int n, vector>& prices) { - vector> d(m + 1, vector(n + 1)); - vector> dp(m + 1, vector(n + 1)); - for (auto& p : prices) d[p[0]][p[1]] = p[2]; - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - dp[i][j] = d[i][j]; - for (int k = 1; k < i; ++k) dp[i][j] = max(dp[i][j], dp[k][j] + dp[i - k][j]); - for (int k = 1; k < j; ++k) dp[i][j] = max(dp[i][j], dp[i][k] + dp[i][j - k]); - } - } - return dp[m][n]; - } -}; -``` - -### **Go** - ```go func sellingWood(m int, n int, prices [][]int) int64 { memo := make([][]int, m+1) @@ -263,6 +181,78 @@ func sellingWood(m int, n int, prices [][]int) int64 { } ``` + + +### 方法二:动态规划 + +设 $dp[i][j]$ 表示对一块高为 $i$,宽为 $j$ 的木块切割后能得到的最多钱数。答案就是 $dp[m][n]$。 + +时间复杂度 $O(mn(m+n))$。 + +相似题目:[1444. 切披萨的方案数](/solution/1400-1499/1444.Number%20of%20Ways%20of%20Cutting%20a%20Pizza/README.md) + + + +```python +class Solution: + def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int: + d = defaultdict(dict) + for h, w, p in prices: + d[h][w] = p + dp = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(1, m + 1): + for j in range(1, n + 1): + dp[i][j] = d[i].get(j, 0) + for k in range(1, i): + dp[i][j] = max(dp[i][j], dp[k][j] + dp[i - k][j]) + for k in range(1, j): + dp[i][j] = max(dp[i][j], dp[i][k] + dp[i][j - k]) + return dp[-1][-1] +``` + +```java +class Solution { + public long sellingWood(int m, int n, int[][] prices) { + int[][] d = new int[m + 1][n + 1]; + long[][] dp = new long[m + 1][n + 1]; + for (int[] p : prices) { + d[p[0]][p[1]] = p[2]; + } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + dp[i][j] = d[i][j]; + for (int k = 1; k < i; ++k) { + dp[i][j] = Math.max(dp[i][j], dp[k][j] + dp[i - k][j]); + } + for (int k = 1; k < j; ++k) { + dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[i][j - k]); + } + } + } + return dp[m][n]; + } +} +``` + +```cpp +class Solution { +public: + long long sellingWood(int m, int n, vector>& prices) { + vector> d(m + 1, vector(n + 1)); + vector> dp(m + 1, vector(n + 1)); + for (auto& p : prices) d[p[0]][p[1]] = p[2]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + dp[i][j] = d[i][j]; + for (int k = 1; k < i; ++k) dp[i][j] = max(dp[i][j], dp[k][j] + dp[i - k][j]); + for (int k = 1; k < j; ++k) dp[i][j] = max(dp[i][j], dp[i][k] + dp[i][j - k]); + } + } + return dp[m][n]; + } +}; +``` + ```go func sellingWood(m int, n int, prices [][]int) int64 { d := make([][]int, m+1) @@ -289,16 +279,6 @@ func sellingWood(m int, n int, prices [][]int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2312.Selling Pieces of Wood/README_EN.md b/solution/2300-2399/2312.Selling Pieces of Wood/README_EN.md index 0757ca04efef5..5ef648eb82f10 100644 --- a/solution/2300-2399/2312.Selling Pieces of Wood/README_EN.md +++ b/solution/2300-2399/2312.Selling Pieces of Wood/README_EN.md @@ -53,9 +53,9 @@ Notice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,25 +75,6 @@ class Solution: return dfs(m, n) ``` -```python -class Solution: - def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int: - d = defaultdict(dict) - for h, w, p in prices: - d[h][w] = p - dp = [[0] * (n + 1) for _ in range(m + 1)] - for i in range(1, m + 1): - for j in range(1, n + 1): - dp[i][j] = d[i].get(j, 0) - for k in range(1, i): - dp[i][j] = max(dp[i][j], dp[k][j] + dp[i - k][j]) - for k in range(1, j): - dp[i][j] = max(dp[i][j], dp[i][k] + dp[i][j - k]) - return dp[-1][-1] -``` - -### **Java** - ```java class Solution { private long[][] memo; @@ -129,32 +110,6 @@ class Solution { } ``` -```java -class Solution { - public long sellingWood(int m, int n, int[][] prices) { - int[][] d = new int[m + 1][n + 1]; - long[][] dp = new long[m + 1][n + 1]; - for (int[] p : prices) { - d[p[0]][p[1]] = p[2]; - } - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - dp[i][j] = d[i][j]; - for (int k = 1; k < i; ++k) { - dp[i][j] = Math.max(dp[i][j], dp[k][j] + dp[i - k][j]); - } - for (int k = 1; k < j; ++k) { - dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[i][j - k]); - } - } - } - return dp[m][n]; - } -} -``` - -### **C++** - ```cpp using ll = long long; @@ -178,27 +133,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long sellingWood(int m, int n, vector>& prices) { - vector> d(m + 1, vector(n + 1)); - vector> dp(m + 1, vector(n + 1)); - for (auto& p : prices) d[p[0]][p[1]] = p[2]; - for (int i = 1; i <= m; ++i) { - for (int j = 1; j <= n; ++j) { - dp[i][j] = d[i][j]; - for (int k = 1; k < i; ++k) dp[i][j] = max(dp[i][j], dp[k][j] + dp[i - k][j]); - for (int k = 1; k < j; ++k) dp[i][j] = max(dp[i][j], dp[i][k] + dp[i][j - k]); - } - } - return dp[m][n]; - } -}; -``` - -### **Go** - ```go func sellingWood(m int, n int, prices [][]int) int64 { memo := make([][]int, m+1) @@ -232,6 +166,72 @@ func sellingWood(m int, n int, prices [][]int) int64 { } ``` + + +### Solution 2 + + + +```python +class Solution: + def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int: + d = defaultdict(dict) + for h, w, p in prices: + d[h][w] = p + dp = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(1, m + 1): + for j in range(1, n + 1): + dp[i][j] = d[i].get(j, 0) + for k in range(1, i): + dp[i][j] = max(dp[i][j], dp[k][j] + dp[i - k][j]) + for k in range(1, j): + dp[i][j] = max(dp[i][j], dp[i][k] + dp[i][j - k]) + return dp[-1][-1] +``` + +```java +class Solution { + public long sellingWood(int m, int n, int[][] prices) { + int[][] d = new int[m + 1][n + 1]; + long[][] dp = new long[m + 1][n + 1]; + for (int[] p : prices) { + d[p[0]][p[1]] = p[2]; + } + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + dp[i][j] = d[i][j]; + for (int k = 1; k < i; ++k) { + dp[i][j] = Math.max(dp[i][j], dp[k][j] + dp[i - k][j]); + } + for (int k = 1; k < j; ++k) { + dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[i][j - k]); + } + } + } + return dp[m][n]; + } +} +``` + +```cpp +class Solution { +public: + long long sellingWood(int m, int n, vector>& prices) { + vector> d(m + 1, vector(n + 1)); + vector> dp(m + 1, vector(n + 1)); + for (auto& p : prices) d[p[0]][p[1]] = p[2]; + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + dp[i][j] = d[i][j]; + for (int k = 1; k < i; ++k) dp[i][j] = max(dp[i][j], dp[k][j] + dp[i - k][j]); + for (int k = 1; k < j; ++k) dp[i][j] = max(dp[i][j], dp[i][k] + dp[i][j - k]); + } + } + return dp[m][n]; + } +}; +``` + ```go func sellingWood(m int, n int, prices [][]int) int64 { d := make([][]int, m+1) @@ -258,16 +258,6 @@ func sellingWood(m int, n int, prices [][]int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/README.md b/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/README.md index 045683ed95cd3..37d4780edba7c 100644 --- a/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/README.md +++ b/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:树形 DP + 分情况讨论** +### 方法一:树形 DP + 分情况讨论 我们定义一个函数 $dfs(root)$,它的返回值是一个长度为 $2$ 的数组,其中第一个表示将 $root$ 节点的值变成 `false` 所需要的最少翻转次数,第二个表示将 $root$ 节点的值变成 `true` 所需要的最少翻转次数。那么答案为 $dfs(root)[result]$。 @@ -87,10 +85,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -118,10 +112,6 @@ class Solution: return dfs(root)[int(result)] ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -172,8 +162,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -221,8 +209,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -268,8 +254,6 @@ func minimumFlips(root *TreeNode, result bool) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -311,10 +295,6 @@ function minimumFlips(root: TreeNode | null, result: boolean): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/README_EN.md b/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/README_EN.md index c2a8f52e20895..bcb88fb5f8deb 100644 --- a/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/README_EN.md +++ b/solution/2300-2399/2313.Minimum Flips in Binary Tree to Get Result/README_EN.md @@ -62,9 +62,9 @@ The root of the tree already evaluates to false, so 0 nodes have to be flipped. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -93,8 +93,6 @@ class Solution: return dfs(root)[int(result)] ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -145,8 +143,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -194,8 +190,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -241,8 +235,6 @@ func minimumFlips(root *TreeNode, result bool) int { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -284,10 +276,6 @@ function minimumFlips(root: TreeNode | null, result: boolean): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2314.The First Day of the Maximum Recorded Degree in Each City/README.md b/solution/2300-2399/2314.The First Day of the Maximum Recorded Degree in Each City/README.md index 341c7889a0b51..b620398b4abda 100644 --- a/solution/2300-2399/2314.The First Day of the Maximum Recorded Degree in Each City/README.md +++ b/solution/2300-2399/2314.The First Day of the Maximum Recorded Degree in Each City/README.md @@ -63,14 +63,10 @@ Weather 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -90,3 +86,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2300-2399/2314.The First Day of the Maximum Recorded Degree in Each City/README_EN.md b/solution/2300-2399/2314.The First Day of the Maximum Recorded Degree in Each City/README_EN.md index 63a280217a11f..3942df6617215 100644 --- a/solution/2300-2399/2314.The First Day of the Maximum Recorded Degree in Each City/README_EN.md +++ b/solution/2300-2399/2314.The First Day of the Maximum Recorded Degree in Each City/README_EN.md @@ -60,9 +60,9 @@ For city 3, the maximum degree was recorded on 2022-12-07 with -6 degrees. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -83,3 +83,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2300-2399/2315.Count Asterisks/README.md b/solution/2300-2399/2315.Count Asterisks/README.md index 620ef871abad4..c37d975e3fc80 100644 --- a/solution/2300-2399/2315.Count Asterisks/README.md +++ b/solution/2300-2399/2315.Count Asterisks/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们定义一个整型变量 $ok$,表示遇到 `*` 时是否能计数,初始时 $ok=1$,表示可以计数。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def countAsterisks(self, s: str) -> int: @@ -78,10 +72,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countAsterisks(String s) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func countAsterisks(s string) (ans int) { ok := 1 @@ -134,8 +120,6 @@ func countAsterisks(s string) (ans int) { } ``` -### **TypeScript** - ```ts function countAsterisks(s: string): number { let ans = 0; @@ -151,8 +135,6 @@ function countAsterisks(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_asterisks(s: String) -> i32 { @@ -170,25 +152,6 @@ impl Solution { } ``` -### **C** - -```c -int countAsterisks(char* s) { - int ans = 0; - int ok = 1; - for (int i = 0; s[i]; i++) { - if (s[i] == '*') { - ans += ok; - } else if (s[i] == '|') { - ok ^= 1; - } - } - return ans; -} -``` - -### **C#** - ```cs public class Solution { public int CountAsterisks(string s) { @@ -205,10 +168,21 @@ public class Solution { } ``` -### **...** - -``` - +```c +int countAsterisks(char* s) { + int ans = 0; + int ok = 1; + for (int i = 0; s[i]; i++) { + if (s[i] == '*') { + ans += ok; + } else if (s[i] == '|') { + ok ^= 1; + } + } + return ans; +} ``` + + diff --git a/solution/2300-2399/2315.Count Asterisks/README_EN.md b/solution/2300-2399/2315.Count Asterisks/README_EN.md index 45ad3f8b7150a..c218e783b0257 100644 --- a/solution/2300-2399/2315.Count Asterisks/README_EN.md +++ b/solution/2300-2399/2315.Count Asterisks/README_EN.md @@ -47,9 +47,9 @@ There are 2 asterisks considered. Therefore, we return 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countAsterisks(String s) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +97,6 @@ public: }; ``` -### **Go** - ```go func countAsterisks(s string) (ans int) { ok := 1 @@ -117,8 +111,6 @@ func countAsterisks(s string) (ans int) { } ``` -### **TypeScript** - ```ts function countAsterisks(s: string): number { let ans = 0; @@ -134,8 +126,6 @@ function countAsterisks(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_asterisks(s: String) -> i32 { @@ -153,25 +143,6 @@ impl Solution { } ``` -### **C** - -```c -int countAsterisks(char* s) { - int ans = 0; - int ok = 1; - for (int i = 0; s[i]; i++) { - if (s[i] == '*') { - ans += ok; - } else if (s[i] == '|') { - ok ^= 1; - } - } - return ans; -} -``` - -### **C#** - ```cs public class Solution { public int CountAsterisks(string s) { @@ -188,10 +159,21 @@ public class Solution { } ``` -### **...** - -``` - +```c +int countAsterisks(char* s) { + int ans = 0; + int ok = 1; + for (int i = 0; s[i]; i++) { + if (s[i] == '*') { + ans += ok; + } else if (s[i] == '|') { + ok ^= 1; + } + } + return ans; +} ``` + + diff --git a/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/README.md b/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/README.md index f1b86de7f0091..5595a7fa512bf 100644 --- a/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/README.md +++ b/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 对于无向图中的任意两个节点,如果它们之间存在一条路径,那么它们之间就是互相可达的。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def countPairs(self, n: int, edges: List[List[int]]) -> int: @@ -85,10 +79,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go func countPairs(n int, edges [][]int) (ans int64) { g := make([][]int, n) @@ -195,8 +181,6 @@ func countPairs(n int, edges [][]int) (ans int64) { } ``` -### **TypeScript** - ```ts function countPairs(n: number, edges: number[][]): number { const g: number[][] = Array.from({ length: n }, () => []); @@ -226,8 +210,6 @@ function countPairs(n: number, edges: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_pairs(n: i32, edges: Vec>) -> i64 { @@ -265,10 +247,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/README_EN.md b/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/README_EN.md index cde64245e99bc..407cc0e118d2e 100644 --- a/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/README_EN.md +++ b/solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/README_EN.md @@ -41,7 +41,7 @@ Therefore, we return 14. ## Solutions -**Solution 1: DFS** +### Solution 1: DFS For any two nodes in an undirected graph, if there is a path between them, then they are mutually reachable. @@ -51,8 +51,6 @@ The time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, -### **Python3** - ```python class Solution: def countPairs(self, n: int, edges: List[List[int]]) -> int: @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -114,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +144,6 @@ public: }; ``` -### **Go** - ```go func countPairs(n int, edges [][]int) (ans int64) { g := make([][]int, n) @@ -183,8 +175,6 @@ func countPairs(n int, edges [][]int) (ans int64) { } ``` -### **TypeScript** - ```ts function countPairs(n: number, edges: number[][]): number { const g: number[][] = Array.from({ length: n }, () => []); @@ -214,8 +204,6 @@ function countPairs(n: number, edges: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_pairs(n: i32, edges: Vec>) -> i64 { @@ -253,10 +241,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2317.Maximum XOR After Operations/README.md b/solution/2300-2399/2317.Maximum XOR After Operations/README.md index a76e10dae2438..8da6ce788c18d 100644 --- a/solution/2300-2399/2317.Maximum XOR After Operations/README.md +++ b/solution/2300-2399/2317.Maximum XOR After Operations/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 在一次操作中,我们可以把 `nums[i]` 更新为 `nums[i] AND (nums[i] XOR x)`。由于 $x$ 是任意非负整数,因此 $nums[i] \oplus x$ 的结果是一个任意值,再与 `nums[i]` 逐位与运算,可以把 `nums[i]` 的二进制表示中的若干位 $1$ 变为 $0$。 @@ -54,20 +52,12 @@ -### **Python3** - - - ```python class Solution: def maximumXOR(self, nums: List[int]) -> int: return reduce(or_, nums) ``` -### **Java** - - - ```java class Solution { public int maximumXOR(int[] nums) { @@ -80,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +83,6 @@ public: }; ``` -### **Go** - ```go func maximumXOR(nums []int) (ans int) { for _, x := range nums { @@ -106,8 +92,6 @@ func maximumXOR(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function maximumXOR(nums: number[]): number { let ans = 0; @@ -118,10 +102,6 @@ function maximumXOR(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2317.Maximum XOR After Operations/README_EN.md b/solution/2300-2399/2317.Maximum XOR After Operations/README_EN.md index ca6361762ca3a..22ffa4cdca1e9 100644 --- a/solution/2300-2399/2317.Maximum XOR After Operations/README_EN.md +++ b/solution/2300-2399/2317.Maximum XOR After Operations/README_EN.md @@ -40,9 +40,9 @@ It can be shown that 11 is the maximum possible bitwise XOR. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -50,8 +50,6 @@ class Solution: return reduce(or_, nums) ``` -### **Java** - ```java class Solution { public int maximumXOR(int[] nums) { @@ -64,8 +62,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -79,8 +75,6 @@ public: }; ``` -### **Go** - ```go func maximumXOR(nums []int) (ans int) { for _, x := range nums { @@ -90,8 +84,6 @@ func maximumXOR(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function maximumXOR(nums: number[]): number { let ans = 0; @@ -102,10 +94,6 @@ function maximumXOR(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2318.Number of Distinct Roll Sequences/README.md b/solution/2300-2399/2318.Number of Distinct Roll Sequences/README.md index 65cd6f8e11555..c04c530b9fb24 100644 --- a/solution/2300-2399/2318.Number of Distinct Roll Sequences/README.md +++ b/solution/2300-2399/2318.Number of Distinct Roll Sequences/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 三维 DP。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def distinctSequences(self, n: int) -> int: @@ -89,10 +83,6 @@ class Solution: return ans % mod ``` -### **Java** - - - ```java class Solution { public int distinctSequences(int n) { @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go func distinctSequences(n int) int { if n == 1 { @@ -221,16 +207,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2318.Number of Distinct Roll Sequences/README_EN.md b/solution/2300-2399/2318.Number of Distinct Roll Sequences/README_EN.md index 2355abc0c40a3..c37798a617e3a 100644 --- a/solution/2300-2399/2318.Number of Distinct Roll Sequences/README_EN.md +++ b/solution/2300-2399/2318.Number of Distinct Roll Sequences/README_EN.md @@ -46,9 +46,9 @@ There are a total of 22 distinct sequences possible, so we return 22. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return ans % mod ``` -### **Java** - ```java class Solution { public int distinctSequences(int n) { @@ -120,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +149,6 @@ public: }; ``` -### **Go** - ```go func distinctSequences(n int) int { if n == 1 { @@ -205,16 +199,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2319.Check if Matrix Is X-Matrix/README.md b/solution/2300-2399/2319.Check if Matrix Is X-Matrix/README.md index 7f272699617f1..d1ac9c79a6706 100644 --- a/solution/2300-2399/2319.Check if Matrix Is X-Matrix/README.md +++ b/solution/2300-2399/2319.Check if Matrix Is X-Matrix/README.md @@ -47,9 +47,7 @@ X 矩阵应该满足:绿色元素(对角线上)都不是 0 ,红色元素 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 遍历矩阵,对于每个元素,判断其是否满足 $X$ 矩阵的条件。若不满足,直接返回 `false`;若遍历完所有元素都满足,返回 `true`。 @@ -57,10 +55,6 @@ X 矩阵应该满足:绿色元素(对角线上)都不是 0 ,红色元素 -### **Python3** - - - ```python class Solution: def checkXMatrix(self, grid: List[List[int]]) -> bool: @@ -74,10 +68,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean checkXMatrix(int[][] grid) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func checkXMatrix(grid [][]int) bool { for i, row := range grid { @@ -140,8 +126,6 @@ func checkXMatrix(grid [][]int) bool { } ``` -### **TypeScript** - ```ts function checkXMatrix(grid: number[][]): boolean { const n = grid.length; @@ -160,30 +144,6 @@ function checkXMatrix(grid: number[][]): boolean { } ``` -### **C#** - -```cs -public class Solution { - public bool CheckXMatrix(int[][] grid) { - int n = grid.Length; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (i == j || i + j == n - 1) { - if (grid[i][j] == 0) { - return false; - } - } else if (grid[i][j] != 0) { - return false; - } - } - } - return true; - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn check_x_matrix(grid: Vec>) -> bool { @@ -204,7 +164,25 @@ impl Solution { } ``` -### **C** +```cs +public class Solution { + public bool CheckXMatrix(int[][] grid) { + int n = grid.Length; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (i == j || i + j == n - 1) { + if (grid[i][j] == 0) { + return false; + } + } else if (grid[i][j] != 0) { + return false; + } + } + } + return true; + } +} +``` ```c bool checkXMatrix(int** grid, int gridSize, int* gridColSize) { @@ -223,10 +201,6 @@ bool checkXMatrix(int** grid, int gridSize, int* gridColSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2319.Check if Matrix Is X-Matrix/README_EN.md b/solution/2300-2399/2319.Check if Matrix Is X-Matrix/README_EN.md index 945121c1b2103..c3e4807cf2e12 100644 --- a/solution/2300-2399/2319.Check if Matrix Is X-Matrix/README_EN.md +++ b/solution/2300-2399/2319.Check if Matrix Is X-Matrix/README_EN.md @@ -45,9 +45,9 @@ Thus, grid is not an X-Matrix. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean checkXMatrix(int[][] grid) { @@ -84,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +103,6 @@ public: }; ``` -### **Go** - ```go func checkXMatrix(grid [][]int) bool { for i, row := range grid { @@ -126,8 +120,6 @@ func checkXMatrix(grid [][]int) bool { } ``` -### **TypeScript** - ```ts function checkXMatrix(grid: number[][]): boolean { const n = grid.length; @@ -146,30 +138,6 @@ function checkXMatrix(grid: number[][]): boolean { } ``` -### **C#** - -```cs -public class Solution { - public bool CheckXMatrix(int[][] grid) { - int n = grid.Length; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - if (i == j || i + j == n - 1) { - if (grid[i][j] == 0) { - return false; - } - } else if (grid[i][j] != 0) { - return false; - } - } - } - return true; - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn check_x_matrix(grid: Vec>) -> bool { @@ -190,7 +158,25 @@ impl Solution { } ``` -### **C** +```cs +public class Solution { + public bool CheckXMatrix(int[][] grid) { + int n = grid.Length; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + if (i == j || i + j == n - 1) { + if (grid[i][j] == 0) { + return false; + } + } else if (grid[i][j] != 0) { + return false; + } + } + } + return true; + } +} +``` ```c bool checkXMatrix(int** grid, int gridSize, int* gridColSize) { @@ -209,10 +195,6 @@ bool checkXMatrix(int** grid, int gridSize, int* gridColSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2320.Count Number of Ways to Place Houses/README.md b/solution/2300-2399/2320.Count Number of Ways to Place Houses/README.md index 92880e8d7e05d..c91d9c84f4b67 100644 --- a/solution/2300-2399/2320.Count Number of Ways to Place Houses/README.md +++ b/solution/2300-2399/2320.Count Number of Ways to Place Houses/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 由于街道两侧房子的摆放互不影响,因此,我们可以只考虑一侧的摆放情况,最后将一侧的方案数平方取模得到最终结果。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def countHousePlacements(self, n: int) -> int: @@ -79,10 +73,6 @@ class Solution: return v * v % mod ``` -### **Java** - - - ```java class Solution { public int countHousePlacements(int n) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func countHousePlacements(n int) int { const mod = 1e9 + 7 @@ -137,8 +123,6 @@ func countHousePlacements(n int) int { } ``` -### **TypeScript** - ```ts function countHousePlacements(n: number): number { const f = new Array(n); @@ -154,8 +138,6 @@ function countHousePlacements(n: number): number { } ``` -### **C#** - ```cs public class Solution { public int CountHousePlacements(int n) { @@ -173,10 +155,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2320.Count Number of Ways to Place Houses/README_EN.md b/solution/2300-2399/2320.Count Number of Ways to Place Houses/README_EN.md index e320bfd80dfc0..93084a0e38fb7 100644 --- a/solution/2300-2399/2320.Count Number of Ways to Place Houses/README_EN.md +++ b/solution/2300-2399/2320.Count Number of Ways to Place Houses/README_EN.md @@ -41,9 +41,9 @@ Possible arrangements: ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -58,8 +58,6 @@ class Solution: return v * v % mod ``` -### **Java** - ```java class Solution { public int countHousePlacements(int n) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +93,6 @@ public: }; ``` -### **Go** - ```go func countHousePlacements(n int) int { const mod = 1e9 + 7 @@ -114,8 +108,6 @@ func countHousePlacements(n int) int { } ``` -### **TypeScript** - ```ts function countHousePlacements(n: number): number { const f = new Array(n); @@ -131,8 +123,6 @@ function countHousePlacements(n: number): number { } ``` -### **C#** - ```cs public class Solution { public int CountHousePlacements(int n) { @@ -150,10 +140,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2321.Maximum Score Of Spliced Array/README.md b/solution/2300-2399/2321.Maximum Score Of Spliced Array/README.md index 689add6a5da8f..9bc31f640d589 100644 --- a/solution/2300-2399/2321.Maximum Score Of Spliced Array/README.md +++ b/solution/2300-2399/2321.Maximum Score Of Spliced Array/README.md @@ -62,14 +62,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int: @@ -88,10 +84,6 @@ class Solution: return max(s2 + f(nums1, nums2), s1 + f(nums2, nums1)) ``` -### **Java** - - - ```java class Solution { public int maximumsSplicedArray(int[] nums1, int[] nums2) { @@ -120,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +140,6 @@ public: }; ``` -### **Go** - ```go func maximumsSplicedArray(nums1 []int, nums2 []int) int { s1, s2 := 0, 0 @@ -178,16 +166,6 @@ func maximumsSplicedArray(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2321.Maximum Score Of Spliced Array/README_EN.md b/solution/2300-2399/2321.Maximum Score Of Spliced Array/README_EN.md index c62ef9a6a03c6..b4f7dc8268406 100644 --- a/solution/2300-2399/2321.Maximum Score Of Spliced Array/README_EN.md +++ b/solution/2300-2399/2321.Maximum Score Of Spliced Array/README_EN.md @@ -58,9 +58,9 @@ The score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return max(s2 + f(nums1, nums2), s1 + f(nums2, nums1)) ``` -### **Java** - ```java class Solution { public int maximumsSplicedArray(int[] nums1, int[] nums2) { @@ -110,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +136,6 @@ public: }; ``` -### **Go** - ```go func maximumsSplicedArray(nums1 []int, nums2 []int) int { s1, s2 := 0, 0 @@ -168,16 +162,6 @@ func maximumsSplicedArray(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2322.Minimum Score After Removals on a Tree/README.md b/solution/2300-2399/2322.Minimum Score After Removals on a Tree/README.md index 771bd32dc6f18..08efcd6254311 100644 --- a/solution/2300-2399/2322.Minimum Score After Removals on a Tree/README.md +++ b/solution/2300-2399/2322.Minimum Score After Removals on a Tree/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:DFS + 子树异或和** +### 方法一:DFS + 子树异或和 枚举 $[0,n)$ 的每个点 $i$ 作为树的根节点,将根节点与某个子节点相连的边作为第一条被删除的边。这样我们就获得了两个连通块,我们记包含根节点 $i$ 的连通块为 $A$,不包含根节点 $i$ 的连通块为 $B$。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int: @@ -122,10 +116,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int s; @@ -184,8 +174,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -238,8 +226,6 @@ public: }; ``` -### **Go** - ```go func minimumScore(nums []int, edges [][]int) int { n := len(nums) @@ -290,16 +276,6 @@ func minimumScore(nums []int, edges [][]int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2322.Minimum Score After Removals on a Tree/README_EN.md b/solution/2300-2399/2322.Minimum Score After Removals on a Tree/README_EN.md index be82813dbe9be..c7ceca3a0c5ca 100644 --- a/solution/2300-2399/2322.Minimum Score After Removals on a Tree/README_EN.md +++ b/solution/2300-2399/2322.Minimum Score After Removals on a Tree/README_EN.md @@ -64,9 +64,9 @@ We cannot obtain a smaller score than 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -108,8 +108,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int s; @@ -168,8 +166,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -222,8 +218,6 @@ public: }; ``` -### **Go** - ```go func minimumScore(nums []int, edges [][]int) int { n := len(nums) @@ -274,16 +268,6 @@ func minimumScore(nums []int, edges [][]int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2323.Find Minimum Time to Finish All Jobs II/README.md b/solution/2300-2399/2323.Find Minimum Time to Finish All Jobs II/README.md index 8a549f47a519c..b36893e2a8714 100644 --- a/solution/2300-2399/2323.Find Minimum Time to Finish All Jobs II/README.md +++ b/solution/2300-2399/2323.Find Minimum Time to Finish All Jobs II/README.md @@ -53,14 +53,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minimumTime(self, jobs: List[int], workers: List[int]) -> int: @@ -69,10 +65,6 @@ class Solution: return max((a + b - 1) // b for a, b in zip(jobs, workers)) ``` -### **Java** - - - ```java class Solution { public int minimumTime(int[] jobs, int[] workers) { @@ -87,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +92,6 @@ public: }; ``` -### **Go** - ```go func minimumTime(jobs []int, workers []int) int { sort.Ints(jobs) @@ -117,16 +105,6 @@ func minimumTime(jobs []int, workers []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2323.Find Minimum Time to Finish All Jobs II/README_EN.md b/solution/2300-2399/2323.Find Minimum Time to Finish All Jobs II/README_EN.md index d6c9725bb19b7..f020cd780e9a4 100644 --- a/solution/2300-2399/2323.Find Minimum Time to Finish All Jobs II/README_EN.md +++ b/solution/2300-2399/2323.Find Minimum Time to Finish All Jobs II/README_EN.md @@ -49,9 +49,9 @@ It can be proven that 3 days is the minimum number of days needed. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return max((a + b - 1) // b for a, b in zip(jobs, workers)) ``` -### **Java** - ```java class Solution { public int minimumTime(int[] jobs, int[] workers) { @@ -77,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -92,8 +88,6 @@ public: }; ``` -### **Go** - ```go func minimumTime(jobs []int, workers []int) int { sort.Ints(jobs) @@ -107,16 +101,6 @@ func minimumTime(jobs []int, workers []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2324.Product Sales Analysis IV/README.md b/solution/2300-2399/2324.Product Sales Analysis IV/README.md index 5e2d62456cb3f..b0b1fb32679de 100644 --- a/solution/2300-2399/2324.Product Sales Analysis IV/README.md +++ b/solution/2300-2399/2324.Product Sales Analysis IV/README.md @@ -93,14 +93,10 @@ Product 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -123,3 +119,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/2300-2399/2324.Product Sales Analysis IV/README_EN.md b/solution/2300-2399/2324.Product Sales Analysis IV/README_EN.md index 7b270083fcbf6..4013d0276436a 100644 --- a/solution/2300-2399/2324.Product Sales Analysis IV/README_EN.md +++ b/solution/2300-2399/2324.Product Sales Analysis IV/README_EN.md @@ -90,9 +90,9 @@ User 102 spent the most money on products 1, 2, and 3. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -116,3 +116,5 @@ WHERE rk = 1; ``` + + diff --git a/solution/2300-2399/2325.Decode the Message/README.md b/solution/2300-2399/2325.Decode the Message/README.md index 3376eac47ea04..200396f772abc 100644 --- a/solution/2300-2399/2325.Decode the Message/README.md +++ b/solution/2300-2399/2325.Decode the Message/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:数组或哈希表** +### 方法一:数组或哈希表 我们可以使用数组或哈希表 $d$ 存储对照表,然后遍历 `message` 中的每个字符,将其替换为对应的字符即可。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def decodeMessage(self, key: str, message: str) -> str: @@ -85,10 +79,6 @@ class Solution: return "".join(d[c] for c in message) ``` -### **Java** - - - ```java class Solution { public String decodeMessage(String key, String message) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func decodeMessage(key string, message string) string { d := [128]byte{} @@ -151,8 +137,6 @@ func decodeMessage(key string, message string) string { } ``` -### **TypeScript** - ```ts function decodeMessage(key: string, message: string): string { const d = new Map(); @@ -167,8 +151,6 @@ function decodeMessage(key: string, message: string): string { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -189,8 +171,6 @@ impl Solution { } ``` -### **C** - ```c char* decodeMessage(char* key, char* message) { int m = strlen(key); @@ -212,10 +192,6 @@ char* decodeMessage(char* key, char* message) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2325.Decode the Message/README_EN.md b/solution/2300-2399/2325.Decode the Message/README_EN.md index 97583830c591e..43485680186bc 100644 --- a/solution/2300-2399/2325.Decode the Message/README_EN.md +++ b/solution/2300-2399/2325.Decode the Message/README_EN.md @@ -51,9 +51,9 @@ It is obtained by taking the first appearance of each letter in " +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return "".join(d[c] for c in message) ``` -### **Java** - ```java class Solution { public String decodeMessage(String key, String message) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +107,6 @@ public: }; ``` -### **Go** - ```go func decodeMessage(key string, message string) string { d := [128]byte{} @@ -131,8 +125,6 @@ func decodeMessage(key string, message string) string { } ``` -### **TypeScript** - ```ts function decodeMessage(key: string, message: string): string { const d = new Map(); @@ -147,8 +139,6 @@ function decodeMessage(key: string, message: string): string { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -169,8 +159,6 @@ impl Solution { } ``` -### **C** - ```c char* decodeMessage(char* key, char* message) { int m = strlen(key); @@ -192,10 +180,6 @@ char* decodeMessage(char* key, char* message) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2326.Spiral Matrix IV/README.md b/solution/2300-2399/2326.Spiral Matrix IV/README.md index 1deff38e51eb7..ad942b526bef9 100644 --- a/solution/2300-2399/2326.Spiral Matrix IV/README.md +++ b/solution/2300-2399/2326.Spiral Matrix IV/README.md @@ -44,14 +44,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -78,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -123,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -161,8 +151,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -201,8 +189,6 @@ func spiralMatrix(m int, n int, head *ListNode) [][]int { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -242,10 +228,6 @@ function spiralMatrix(m: number, n: number, head: ListNode | null): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2326.Spiral Matrix IV/README_EN.md b/solution/2300-2399/2326.Spiral Matrix IV/README_EN.md index 7f071e82d86d9..a23bd927eb811 100644 --- a/solution/2300-2399/2326.Spiral Matrix IV/README_EN.md +++ b/solution/2300-2399/2326.Spiral Matrix IV/README_EN.md @@ -42,9 +42,9 @@ The last space in the matrix is set to -1. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -72,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -115,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -153,8 +149,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -193,8 +187,6 @@ func spiralMatrix(m int, n int, head *ListNode) [][]int { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -234,10 +226,6 @@ function spiralMatrix(m: number, n: number, head: ListNode | null): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2327.Number of People Aware of a Secret/README.md b/solution/2300-2399/2327.Number of People Aware of a Secret/README.md index 7cbc2fbc20529..171ac579fc51d 100644 --- a/solution/2300-2399/2327.Number of People Aware of a Secret/README.md +++ b/solution/2300-2399/2327.Number of People Aware of a Secret/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 差分数组 $d[i]$ 记录每天知道秘密的人数变化情况,$cnt[i]$ 记录第 $i$ 天新得知秘密的人数。那么从 $[i+delay,i+forget)$ 的这段时间内,$cnt[i]$ 个人每天都能分享给另外 $cnt[i]$ 个人。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int: @@ -84,10 +78,6 @@ class Solution: return sum(d[: n + 1]) % mod ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; const int mod = 1e9 + 7; @@ -147,8 +135,6 @@ public: }; ``` -### **Go** - ```go func peopleAwareOfSecret(n int, delay int, forget int) int { m := (n << 1) + 10 @@ -176,8 +162,6 @@ func peopleAwareOfSecret(n int, delay int, forget int) int { } ``` -### **TypeScript** - ```ts function peopleAwareOfSecret(n: number, delay: number, forget: number): number { let dp = new Array(n + 1).fill(0n); @@ -202,10 +186,6 @@ function peopleAwareOfSecret(n: number, delay: number, forget: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2327.Number of People Aware of a Secret/README_EN.md b/solution/2300-2399/2327.Number of People Aware of a Secret/README_EN.md index 5ccc670124baa..ad4c8bccf5b8a 100644 --- a/solution/2300-2399/2327.Number of People Aware of a Secret/README_EN.md +++ b/solution/2300-2399/2327.Number of People Aware of a Secret/README_EN.md @@ -47,9 +47,9 @@ Day 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return sum(d[: n + 1]) % mod ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; const int mod = 1e9 + 7; @@ -131,8 +127,6 @@ public: }; ``` -### **Go** - ```go func peopleAwareOfSecret(n int, delay int, forget int) int { m := (n << 1) + 10 @@ -160,8 +154,6 @@ func peopleAwareOfSecret(n int, delay int, forget int) int { } ``` -### **TypeScript** - ```ts function peopleAwareOfSecret(n: number, delay: number, forget: number): number { let dp = new Array(n + 1).fill(0n); @@ -186,10 +178,6 @@ function peopleAwareOfSecret(n: number, delay: number, forget: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2328.Number of Increasing Paths in a Grid/README.md b/solution/2300-2399/2328.Number of Increasing Paths in a Grid/README.md index 31f197853ddb5..9a92daba11c62 100644 --- a/solution/2300-2399/2328.Number of Increasing Paths in a Grid/README.md +++ b/solution/2300-2399/2328.Number of Increasing Paths in a Grid/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j)$,表示从网格图中的第 $i$ 行第 $j$ 列的格子出发,能够到达任意格子的严格递增路径数目。那么答案就是 $\sum_{i=0}^{m-1} \sum_{j=0}^{n-1} dfs(i, j)$。搜索过程中,我们可以用一个二维数组 $f$ 记录已经计算过的结果,避免重复计算。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def countPaths(self, grid: List[List[int]]) -> int: @@ -93,10 +87,6 @@ class Solution: return sum(dfs(i, j) for i in range(m) for j in range(n)) % mod ``` -### **Java** - - - ```java class Solution { private int[][] f; @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +159,6 @@ public: }; ``` -### **Go** - ```go func countPaths(grid [][]int) (ans int) { const mod = 1e9 + 7 @@ -205,8 +191,6 @@ func countPaths(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function countPaths(grid: number[][]): number { const mod = 1e9 + 7; @@ -238,10 +222,6 @@ function countPaths(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2328.Number of Increasing Paths in a Grid/README_EN.md b/solution/2300-2399/2328.Number of Increasing Paths in a Grid/README_EN.md index 812c84ae2493c..d115b2da72efd 100644 --- a/solution/2300-2399/2328.Number of Increasing Paths in a Grid/README_EN.md +++ b/solution/2300-2399/2328.Number of Increasing Paths in a Grid/README_EN.md @@ -47,7 +47,7 @@ The total number of paths is 2 + 1 = 3. ## Solutions -**Solution 1: DFS + Memorization** +### Solution 1: DFS + Memorization We design a function $dfs(i, j)$, which represents the number of strictly increasing paths that can be reached from the grid graph starting at the $i$-th row and $j$-th column. Then the answer is $\sum_{i=0}^{m-1} \sum_{j=0}^{n-1} dfs(i, j)$. In the search process, we can use a two-dimensional array $f$ to record the calculated results to avoid repeated calculation. @@ -64,8 +64,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times -### **Python3** - ```python class Solution: def countPaths(self, grid: List[List[int]]) -> int: @@ -83,8 +81,6 @@ class Solution: return sum(dfs(i, j) for i in range(m) for j in range(n)) % mod ``` -### **Java** - ```java class Solution { private int[][] f; @@ -124,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +153,6 @@ public: }; ``` -### **Go** - ```go func countPaths(grid [][]int) (ans int) { const mod = 1e9 + 7 @@ -193,8 +185,6 @@ func countPaths(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function countPaths(grid: number[][]): number { const mod = 1e9 + 7; @@ -226,10 +216,6 @@ function countPaths(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2329.Product Sales Analysis V/README.md b/solution/2300-2399/2329.Product Sales Analysis V/README.md index c29ddcd99c73c..1ba0287d4ea3b 100644 --- a/solution/2300-2399/2329.Product Sales Analysis V/README.md +++ b/solution/2300-2399/2329.Product Sales Analysis V/README.md @@ -84,14 +84,10 @@ Product 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT user_id, SUM(quantity * price) AS spending @@ -103,3 +99,5 @@ ORDER BY 2 DESC, 1; ``` + + diff --git a/solution/2300-2399/2329.Product Sales Analysis V/README_EN.md b/solution/2300-2399/2329.Product Sales Analysis V/README_EN.md index 68ce7f7754262..07d3459a61dd1 100644 --- a/solution/2300-2399/2329.Product Sales Analysis V/README_EN.md +++ b/solution/2300-2399/2329.Product Sales Analysis V/README_EN.md @@ -83,9 +83,9 @@ Users 102 and 103 spent the same amount and we break the tie by their ID while u ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -98,3 +98,5 @@ ORDER BY 2 DESC, 1; ``` + + diff --git a/solution/2300-2399/2330.Valid Palindrome IV/README.md b/solution/2300-2399/2330.Valid Palindrome IV/README.md index d192bcdf4feff..b9492078c9e21 100644 --- a/solution/2300-2399/2330.Valid Palindrome IV/README.md +++ b/solution/2300-2399/2330.Valid Palindrome IV/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们可以使用双指针 $i$ 和 $j$,分别指向字符串的头尾,然后向中间移动,统计不同字符的个数,如果不同字符的个数大于 $2$,则返回 `false`,否则返回 `true`。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def makePalindrome(self, s: str) -> bool: @@ -77,10 +71,6 @@ class Solution: return cnt <= 2 ``` -### **Java** - - - ```java class Solution { public boolean makePalindrome(String s) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +100,6 @@ public: }; ``` -### **Go** - ```go func makePalindrome(s string) bool { cnt := 0 @@ -127,8 +113,6 @@ func makePalindrome(s string) bool { } ``` -### **TypeScript** - ```ts function makePalindrome(s: string): boolean { let cnt = 0; @@ -143,10 +127,6 @@ function makePalindrome(s: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2330.Valid Palindrome IV/README_EN.md b/solution/2300-2399/2330.Valid Palindrome IV/README_EN.md index 8d0f5d1ca61fd..dd6ba037f0c6d 100644 --- a/solution/2300-2399/2330.Valid Palindrome IV/README_EN.md +++ b/solution/2300-2399/2330.Valid Palindrome IV/README_EN.md @@ -48,9 +48,9 @@ Two operations could be performed to make s a palindrome so return true. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return cnt <= 2 ``` -### **Java** - ```java class Solution { public boolean makePalindrome(String s) { @@ -80,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func makePalindrome(s string) bool { cnt := 0 @@ -111,8 +105,6 @@ func makePalindrome(s string) bool { } ``` -### **TypeScript** - ```ts function makePalindrome(s: string): boolean { let cnt = 0; @@ -127,10 +119,6 @@ function makePalindrome(s: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README.md b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README.md index a2b64d04f55e8..5df58ee278a11 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README.md +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README.md @@ -60,9 +60,7 @@ OR 运算节点的值为 True OR False = True 。 ## 解法 - - -**方法一:递归** +### 方法一:递归 我们可以使用递归的方式来求解本题。 @@ -77,10 +75,6 @@ OR 运算节点的值为 True OR False = True 。 -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -99,26 +93,6 @@ class Solution: return dfs(root) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def evaluateTree(self, root: Optional[TreeNode]) -> bool: - if root.left is None: - return bool(root.val) - l = self.evaluateTree(root.left) - r = self.evaluateTree(root.right) - return l or r if root.val == 2 else l and r -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -153,36 +127,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public boolean evaluateTree(TreeNode root) { - if (root.left == null) { - return root.val == 1; - } - boolean l = evaluateTree(root.left); - boolean r = evaluateTree(root.right); - return root.val == 2 ? l || r : l && r; - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -210,33 +154,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool evaluateTree(TreeNode* root) { - if (!root->left) { - return root->val; - } - bool l = evaluateTree(root->left); - bool r = evaluateTree(root->right); - return root->val == 2 ? l or r : l and r; - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -262,29 +179,6 @@ func evaluateTree(root *TreeNode) bool { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func evaluateTree(root *TreeNode) bool { - if root.Left == nil { - return root.Val == 1 - } - l, r := evaluateTree(root.Left), evaluateTree(root.Right) - if root.Val == 2 { - return l || r - } - return l && r -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -312,8 +206,6 @@ function evaluateTree(root: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -353,8 +245,6 @@ impl Solution { } ``` -### **C** - ```c /** * Definition for a binary tree node. @@ -375,10 +265,102 @@ bool evaluateTree(struct TreeNode* root) { } ``` -### **...** + + +### 方法二 + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def evaluateTree(self, root: Optional[TreeNode]) -> bool: + if root.left is None: + return bool(root.val) + l = self.evaluateTree(root.left) + r = self.evaluateTree(root.right) + return l or r if root.val == 2 else l and r ``` +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean evaluateTree(TreeNode root) { + if (root.left == null) { + return root.val == 1; + } + boolean l = evaluateTree(root.left); + boolean r = evaluateTree(root.right); + return root.val == 2 ? l || r : l && r; + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool evaluateTree(TreeNode* root) { + if (!root->left) { + return root->val; + } + bool l = evaluateTree(root->left); + bool r = evaluateTree(root->right); + return root->val == 2 ? l or r : l and r; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func evaluateTree(root *TreeNode) bool { + if root.Left == nil { + return root.Val == 1 + } + l, r := evaluateTree(root.Left), evaluateTree(root.Right) + if root.Val == 2 { + return l || r + } + return l && r +} ``` + + diff --git a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README_EN.md b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README_EN.md index d598c5b7afa31..f329f41b5d7e9 100644 --- a/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README_EN.md +++ b/solution/2300-2399/2331.Evaluate Boolean Binary Tree/README_EN.md @@ -56,9 +56,9 @@ The root node evaluates to True, so we return true. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -78,24 +78,6 @@ class Solution: return dfs(root) ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def evaluateTree(self, root: Optional[TreeNode]) -> bool: - if root.left is None: - return bool(root.val) - l = self.evaluateTree(root.left) - r = self.evaluateTree(root.right) - return l or r if root.val == 2 else l and r -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -130,36 +112,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public boolean evaluateTree(TreeNode root) { - if (root.left == null) { - return root.val == 1; - } - boolean l = evaluateTree(root.left); - boolean r = evaluateTree(root.right); - return root.val == 2 ? l || r : l && r; - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -187,33 +139,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - bool evaluateTree(TreeNode* root) { - if (!root->left) { - return root->val; - } - bool l = evaluateTree(root->left); - bool r = evaluateTree(root->right); - return root->val == 2 ? l or r : l and r; - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -239,29 +164,6 @@ func evaluateTree(root *TreeNode) bool { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func evaluateTree(root *TreeNode) bool { - if root.Left == nil { - return root.Val == 1 - } - l, r := evaluateTree(root.Left), evaluateTree(root.Right) - if root.Val == 2 { - return l || r - } - return l && r -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -289,8 +191,6 @@ function evaluateTree(root: TreeNode | null): boolean { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -330,8 +230,6 @@ impl Solution { } ``` -### **C** - ```c /** * Definition for a binary tree node. @@ -352,10 +250,102 @@ bool evaluateTree(struct TreeNode* root) { } ``` -### **...** + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def evaluateTree(self, root: Optional[TreeNode]) -> bool: + if root.left is None: + return bool(root.val) + l = self.evaluateTree(root.left) + r = self.evaluateTree(root.right) + return l or r if root.val == 2 else l and r +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public boolean evaluateTree(TreeNode root) { + if (root.left == null) { + return root.val == 1; + } + boolean l = evaluateTree(root.left); + boolean r = evaluateTree(root.right); + return root.val == 2 ? l || r : l && r; + } +} +``` +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool evaluateTree(TreeNode* root) { + if (!root->left) { + return root->val; + } + bool l = evaluateTree(root->left); + bool r = evaluateTree(root->right); + return root->val == 2 ? l or r : l and r; + } +}; ``` +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func evaluateTree(root *TreeNode) bool { + if root.Left == nil { + return root.Val == 1 + } + l, r := evaluateTree(root.Left), evaluateTree(root.Right) + if root.Val == 2 { + return l || r + } + return l && r +} ``` + + diff --git a/solution/2300-2399/2332.The Latest Time to Catch a Bus/README.md b/solution/2300-2399/2332.The Latest Time to Catch a Bus/README.md index 242a0d74c7f00..d512d316aee04 100644 --- a/solution/2300-2399/2332.The Latest Time to Catch a Bus/README.md +++ b/solution/2300-2399/2332.The Latest Time to Catch a Bus/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们先排序,然后用双指针模拟乘客上车的过程:遍历公交车 $bus$,乘客遵循“先到先上车”的原则。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def latestTimeCatchTheBus( @@ -90,10 +84,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int latestTimeCatchTheBus(int[] buses, int[] passengers, int capacity) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +127,6 @@ public: }; ``` -### **Go** - ```go func latestTimeCatchTheBus(buses []int, passengers []int, capacity int) int { sort.Ints(buses) @@ -166,8 +152,6 @@ func latestTimeCatchTheBus(buses []int, passengers []int, capacity int) int { } ``` -### **TypeScript** - ```ts function latestTimeCatchTheBus(buses: number[], passengers: number[], capacity: number): number { buses.sort((a, b) => a - b); @@ -190,8 +174,6 @@ function latestTimeCatchTheBus(buses: number[], passengers: number[], capacity: } ``` -### **JavaScript** - ```js /** * @param {number[]} buses @@ -220,10 +202,6 @@ var latestTimeCatchTheBus = function (buses, passengers, capacity) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2332.The Latest Time to Catch a Bus/README_EN.md b/solution/2300-2399/2332.The Latest Time to Catch a Bus/README_EN.md index 6a1de7d5778a8..2f6d0f740d6fa 100644 --- a/solution/2300-2399/2332.The Latest Time to Catch a Bus/README_EN.md +++ b/solution/2300-2399/2332.The Latest Time to Catch a Bus/README_EN.md @@ -57,7 +57,7 @@ Notice if you had arrived any later, then the 6th passenger would hav ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation First, we sort, and then use double pointers to simulate the process of passengers getting on the bus: traverse the bus $bus$, passengers follow the principle of "first come, first served". @@ -70,8 +70,6 @@ The time complexity is $O(n \times \log n + m \times \log m)$, and the space com -### **Python3** - ```python class Solution: def latestTimeCatchTheBus( @@ -91,8 +89,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int latestTimeCatchTheBus(int[] buses, int[] passengers, int capacity) { @@ -117,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +132,6 @@ public: }; ``` -### **Go** - ```go func latestTimeCatchTheBus(buses []int, passengers []int, capacity int) int { sort.Ints(buses) @@ -165,8 +157,6 @@ func latestTimeCatchTheBus(buses []int, passengers []int, capacity int) int { } ``` -### **TypeScript** - ```ts function latestTimeCatchTheBus(buses: number[], passengers: number[], capacity: number): number { buses.sort((a, b) => a - b); @@ -189,8 +179,6 @@ function latestTimeCatchTheBus(buses: number[], passengers: number[], capacity: } ``` -### **JavaScript** - ```js /** * @param {number[]} buses @@ -219,10 +207,6 @@ var latestTimeCatchTheBus = function (buses, passengers, capacity) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2333.Minimum Sum of Squared Difference/README.md b/solution/2300-2399/2333.Minimum Sum of Squared Difference/README.md index fbeb1be88b44e..c9a063a3f2d9f 100644 --- a/solution/2300-2399/2333.Minimum Sum of Squared Difference/README.md +++ b/solution/2300-2399/2333.Minimum Sum of Squared Difference/README.md @@ -50,16 +50,10 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 -### **Python3** - - - ```python class Solution: def minSumSquareDiff( @@ -88,10 +82,6 @@ class Solution: return sum(v * v for v in d) ``` -### **Java** - - - ```java class Solution { public long minSumSquareDiff(int[] nums1, int[] nums2, int k1, int k2) { @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -186,8 +174,6 @@ public: }; ``` -### **Go** - ```go func minSumSquareDiff(nums1 []int, nums2 []int, k1 int, k2 int) int64 { k := k1 + k2 @@ -243,16 +229,6 @@ func abs(x int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2333.Minimum Sum of Squared Difference/README_EN.md b/solution/2300-2399/2333.Minimum Sum of Squared Difference/README_EN.md index d23113cecaa4c..116f9b0e59c98 100644 --- a/solution/2300-2399/2333.Minimum Sum of Squared Difference/README_EN.md +++ b/solution/2300-2399/2333.Minimum Sum of Squared Difference/README_EN.md @@ -48,9 +48,9 @@ Note that, there are other ways to obtain the minimum of the sum of square diffe ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return sum(v * v for v in d) ``` -### **Java** - ```java class Solution { public long minSumSquareDiff(int[] nums1, int[] nums2, int k1, int k2) { @@ -130,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -176,8 +172,6 @@ public: }; ``` -### **Go** - ```go func minSumSquareDiff(nums1 []int, nums2 []int, k1 int, k2 int) int64 { k := k1 + k2 @@ -233,16 +227,6 @@ func abs(x int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/README.md b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/README.md index bd405f14e8fff..28e8a460fb116 100644 --- a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/README.md +++ b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:并查集** +### 方法一:并查集 考虑**从大到小遍历**数组 $nums$ 中的每个元素 $v$,用并查集来维护以 $v$ 作为子数组最小值的连通块。 @@ -62,22 +60,8 @@ $v$ 作为当前连通块的最小值,当前连通块的大小为 $size[find(i 相似题目:[1562. 查找大小为 M 的最新分组](/solution/1500-1599/1562.Find%20Latest%20Group%20of%20Size%20M/README.md) -**方法二:单调栈** - -利用单调栈,得到以当前元素 $nums[i]$ 作为最小元素的左右边界 $left[i]$(左边第一个比 $nums[i]$ 小的元素的位置), $right[i]$(右边第一个比 $nums[i]$ 小的元素的位置)。 - -那么对于当前元素 $nums[i]$,有 $k=right[i]-left[i]-1$,若 $nums[i]>\frac{\text{threshold}}{k}$,说明找到了满足条件的子数组,返回 $true$。 - -否则遍历结束,返回 $-1$。 - -时间复杂度 $O(n)$。 - -### **Python3** - - - ```python class Solution: def validSubarraySize(self, nums: List[int], threshold: int) -> int: @@ -109,37 +93,6 @@ class Solution: return -1 ``` -```python -class Solution: - def validSubarraySize(self, nums: List[int], threshold: int) -> int: - n = len(nums) - left = [-1] * n - right = [n] * n - stk = [] - for i, v in enumerate(nums): - while stk and nums[stk[-1]] >= v: - stk.pop() - if stk: - left[i] = stk[-1] - stk.append(i) - stk = [] - for i in range(n - 1, -1, -1): - while stk and nums[stk[-1]] >= nums[i]: - stk.pop() - if stk: - right[i] = stk[-1] - stk.append(i) - for i, v in enumerate(nums): - k = right[i] - left[i] - 1 - if v > threshold // k: - return k - return -1 -``` - -### **Java** - - - ```java class Solution { private int[] p; @@ -194,50 +147,6 @@ class Solution { } ``` -```java -class Solution { - public int validSubarraySize(int[] nums, int threshold) { - int n = nums.length; - int[] left = new int[n]; - int[] right = new int[n]; - Arrays.fill(left, -1); - Arrays.fill(right, n); - Deque stk = new ArrayDeque<>(); - for (int i = 0; i < n; ++i) { - int v = nums[i]; - while (!stk.isEmpty() && nums[stk.peek()] >= v) { - stk.pop(); - } - if (!stk.isEmpty()) { - left[i] = stk.peek(); - } - stk.push(i); - } - stk.clear(); - for (int i = n - 1; i >= 0; --i) { - int v = nums[i]; - while (!stk.isEmpty() && nums[stk.peek()] >= v) { - stk.pop(); - } - if (!stk.isEmpty()) { - right[i] = stk.peek(); - } - stk.push(i); - } - for (int i = 0; i < n; ++i) { - int v = nums[i]; - int k = right[i] - left[i] - 1; - if (v > threshold / k) { - return k; - } - } - return -1; - } -} -``` - -### **C++** - ```cpp using pii = pair; @@ -279,39 +188,6 @@ public: }; ``` -```cpp -class Solution { -public: - int validSubarraySize(vector& nums, int threshold) { - int n = nums.size(); - vector left(n, -1); - vector right(n, n); - stack stk; - for (int i = 0; i < n; ++i) { - int v = nums[i]; - while (!stk.empty() && nums[stk.top()] >= v) stk.pop(); - if (!stk.empty()) left[i] = stk.top(); - stk.push(i); - } - stk = stack(); - for (int i = n - 1; ~i; --i) { - int v = nums[i]; - while (!stk.empty() && nums[stk.top()] >= v) stk.pop(); - if (!stk.empty()) right[i] = stk.top(); - stk.push(i); - } - for (int i = 0; i < n; ++i) { - int v = nums[i]; - int k = right[i] - left[i] - 1; - if (v > threshold / k) return k; - } - return -1; - } -}; -``` - -### **Go** - ```go func validSubarraySize(nums []int, threshold int) int { n := len(nums) @@ -362,6 +238,120 @@ func validSubarraySize(nums []int, threshold int) int { } ``` + + +### 方法二:单调栈 + +利用单调栈,得到以当前元素 $nums[i]$ 作为最小元素的左右边界 $left[i]$(左边第一个比 $nums[i]$ 小的元素的位置), $right[i]$(右边第一个比 $nums[i]$ 小的元素的位置)。 + +那么对于当前元素 $nums[i]$,有 $k=right[i]-left[i]-1$,若 $nums[i]>\frac{\text{threshold}}{k}$,说明找到了满足条件的子数组,返回 $true$。 + +否则遍历结束,返回 $-1$。 + +时间复杂度 $O(n)$。 + + + +```python +class Solution: + def validSubarraySize(self, nums: List[int], threshold: int) -> int: + n = len(nums) + left = [-1] * n + right = [n] * n + stk = [] + for i, v in enumerate(nums): + while stk and nums[stk[-1]] >= v: + stk.pop() + if stk: + left[i] = stk[-1] + stk.append(i) + stk = [] + for i in range(n - 1, -1, -1): + while stk and nums[stk[-1]] >= nums[i]: + stk.pop() + if stk: + right[i] = stk[-1] + stk.append(i) + for i, v in enumerate(nums): + k = right[i] - left[i] - 1 + if v > threshold // k: + return k + return -1 +``` + +```java +class Solution { + public int validSubarraySize(int[] nums, int threshold) { + int n = nums.length; + int[] left = new int[n]; + int[] right = new int[n]; + Arrays.fill(left, -1); + Arrays.fill(right, n); + Deque stk = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + int v = nums[i]; + while (!stk.isEmpty() && nums[stk.peek()] >= v) { + stk.pop(); + } + if (!stk.isEmpty()) { + left[i] = stk.peek(); + } + stk.push(i); + } + stk.clear(); + for (int i = n - 1; i >= 0; --i) { + int v = nums[i]; + while (!stk.isEmpty() && nums[stk.peek()] >= v) { + stk.pop(); + } + if (!stk.isEmpty()) { + right[i] = stk.peek(); + } + stk.push(i); + } + for (int i = 0; i < n; ++i) { + int v = nums[i]; + int k = right[i] - left[i] - 1; + if (v > threshold / k) { + return k; + } + } + return -1; + } +} +``` + +```cpp +class Solution { +public: + int validSubarraySize(vector& nums, int threshold) { + int n = nums.size(); + vector left(n, -1); + vector right(n, n); + stack stk; + for (int i = 0; i < n; ++i) { + int v = nums[i]; + while (!stk.empty() && nums[stk.top()] >= v) stk.pop(); + if (!stk.empty()) left[i] = stk.top(); + stk.push(i); + } + stk = stack(); + for (int i = n - 1; ~i; --i) { + int v = nums[i]; + while (!stk.empty() && nums[stk.top()] >= v) stk.pop(); + if (!stk.empty()) right[i] = stk.top(); + stk.push(i); + } + for (int i = 0; i < n; ++i) { + int v = nums[i]; + int k = right[i] - left[i] - 1; + if (v > threshold / k) return k; + } + return -1; + } +}; +``` + ```go func validSubarraySize(nums []int, threshold int) int { n := len(nums) @@ -402,16 +392,6 @@ func validSubarraySize(nums []int, threshold int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/README_EN.md b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/README_EN.md index 3ee5ddb9bfc4d..02b9cb00a0df1 100644 --- a/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/README_EN.md +++ b/solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/README_EN.md @@ -42,9 +42,9 @@ Therefore, 2, 3, 4, or 5 may also be returned. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,35 +77,6 @@ class Solution: return -1 ``` -```python -class Solution: - def validSubarraySize(self, nums: List[int], threshold: int) -> int: - n = len(nums) - left = [-1] * n - right = [n] * n - stk = [] - for i, v in enumerate(nums): - while stk and nums[stk[-1]] >= v: - stk.pop() - if stk: - left[i] = stk[-1] - stk.append(i) - stk = [] - for i in range(n - 1, -1, -1): - while stk and nums[stk[-1]] >= nums[i]: - stk.pop() - if stk: - right[i] = stk[-1] - stk.append(i) - for i, v in enumerate(nums): - k = right[i] - left[i] - 1 - if v > threshold // k: - return k - return -1 -``` - -### **Java** - ```java class Solution { private int[] p; @@ -160,50 +131,6 @@ class Solution { } ``` -```java -class Solution { - public int validSubarraySize(int[] nums, int threshold) { - int n = nums.length; - int[] left = new int[n]; - int[] right = new int[n]; - Arrays.fill(left, -1); - Arrays.fill(right, n); - Deque stk = new ArrayDeque<>(); - for (int i = 0; i < n; ++i) { - int v = nums[i]; - while (!stk.isEmpty() && nums[stk.peek()] >= v) { - stk.pop(); - } - if (!stk.isEmpty()) { - left[i] = stk.peek(); - } - stk.push(i); - } - stk.clear(); - for (int i = n - 1; i >= 0; --i) { - int v = nums[i]; - while (!stk.isEmpty() && nums[stk.peek()] >= v) { - stk.pop(); - } - if (!stk.isEmpty()) { - right[i] = stk.peek(); - } - stk.push(i); - } - for (int i = 0; i < n; ++i) { - int v = nums[i]; - int k = right[i] - left[i] - 1; - if (v > threshold / k) { - return k; - } - } - return -1; - } -} -``` - -### **C++** - ```cpp using pii = pair; @@ -245,39 +172,6 @@ public: }; ``` -```cpp -class Solution { -public: - int validSubarraySize(vector& nums, int threshold) { - int n = nums.size(); - vector left(n, -1); - vector right(n, n); - stack stk; - for (int i = 0; i < n; ++i) { - int v = nums[i]; - while (!stk.empty() && nums[stk.top()] >= v) stk.pop(); - if (!stk.empty()) left[i] = stk.top(); - stk.push(i); - } - stk = stack(); - for (int i = n - 1; ~i; --i) { - int v = nums[i]; - while (!stk.empty() && nums[stk.top()] >= v) stk.pop(); - if (!stk.empty()) right[i] = stk.top(); - stk.push(i); - } - for (int i = 0; i < n; ++i) { - int v = nums[i]; - int k = right[i] - left[i] - 1; - if (v > threshold / k) return k; - } - return -1; - } -}; -``` - -### **Go** - ```go func validSubarraySize(nums []int, threshold int) int { n := len(nums) @@ -328,6 +222,112 @@ func validSubarraySize(nums []int, threshold int) int { } ``` + + +### Solution 2 + + + +```python +class Solution: + def validSubarraySize(self, nums: List[int], threshold: int) -> int: + n = len(nums) + left = [-1] * n + right = [n] * n + stk = [] + for i, v in enumerate(nums): + while stk and nums[stk[-1]] >= v: + stk.pop() + if stk: + left[i] = stk[-1] + stk.append(i) + stk = [] + for i in range(n - 1, -1, -1): + while stk and nums[stk[-1]] >= nums[i]: + stk.pop() + if stk: + right[i] = stk[-1] + stk.append(i) + for i, v in enumerate(nums): + k = right[i] - left[i] - 1 + if v > threshold // k: + return k + return -1 +``` + +```java +class Solution { + public int validSubarraySize(int[] nums, int threshold) { + int n = nums.length; + int[] left = new int[n]; + int[] right = new int[n]; + Arrays.fill(left, -1); + Arrays.fill(right, n); + Deque stk = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + int v = nums[i]; + while (!stk.isEmpty() && nums[stk.peek()] >= v) { + stk.pop(); + } + if (!stk.isEmpty()) { + left[i] = stk.peek(); + } + stk.push(i); + } + stk.clear(); + for (int i = n - 1; i >= 0; --i) { + int v = nums[i]; + while (!stk.isEmpty() && nums[stk.peek()] >= v) { + stk.pop(); + } + if (!stk.isEmpty()) { + right[i] = stk.peek(); + } + stk.push(i); + } + for (int i = 0; i < n; ++i) { + int v = nums[i]; + int k = right[i] - left[i] - 1; + if (v > threshold / k) { + return k; + } + } + return -1; + } +} +``` + +```cpp +class Solution { +public: + int validSubarraySize(vector& nums, int threshold) { + int n = nums.size(); + vector left(n, -1); + vector right(n, n); + stack stk; + for (int i = 0; i < n; ++i) { + int v = nums[i]; + while (!stk.empty() && nums[stk.top()] >= v) stk.pop(); + if (!stk.empty()) left[i] = stk.top(); + stk.push(i); + } + stk = stack(); + for (int i = n - 1; ~i; --i) { + int v = nums[i]; + while (!stk.empty() && nums[stk.top()] >= v) stk.pop(); + if (!stk.empty()) right[i] = stk.top(); + stk.push(i); + } + for (int i = 0; i < n; ++i) { + int v = nums[i]; + int k = right[i] - left[i] - 1; + if (v > threshold / k) return k; + } + return -1; + } +}; +``` + ```go func validSubarraySize(nums []int, threshold int) int { n := len(nums) @@ -368,16 +368,6 @@ func validSubarraySize(nums []int, threshold int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/README.md b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/README.md index 9a5ff4964fd8f..7dfe0af7e2444 100644 --- a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/README.md +++ b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/README.md @@ -56,29 +56,14 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 我们可以每次贪心地选择其中较大的两个数进行减一操作(最多减为 $0$),直至所有数变为 $0$。 时间复杂度 $O(S)$,空间复杂度 $O(1)$。其中 $S$ 为数组 `amount` 中所有数的和,本题中 $S \leq 300$。 -**方法二:贪心 + 分类讨论** - -我们可以将数组 `amount` 排序,设 $a$, $b$, $c$ 分别为数组 `amount` 中的三个数,有以下两种情况: - -- 如果 $a + b \leq c$,此时我们只需要 $c$ 次操作即可将所有数变为 $0$,因此答案为 $c$。 -- 如果 $a + b > c$,每一次操作我们都可以将其中两个数减一,最终匹配完,或者剩下最后一个数(取决于总和是偶数还是奇数),因此答案为 $\left \lfloor \frac{a + b + c + 1}{2} \right \rfloor$。 - -时间复杂度 $O(1)$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def fillCups(self, amount: List[int]) -> int: @@ -91,19 +76,6 @@ class Solution: return ans ``` -```python -class Solution: - def fillCups(self, amount: List[int]) -> int: - amount.sort() - if amount[0] + amount[1] <= amount[2]: - return amount[2] - return (sum(amount) + 1) // 2 -``` - -### **Java** - - - ```java class Solution { public int fillCups(int[] amount) { @@ -119,20 +91,6 @@ class Solution { } ``` -```java -class Solution { - public int fillCups(int[] amount) { - Arrays.sort(amount); - if (amount[0] + amount[1] <= amount[2]) { - return amount[2]; - } - return (amount[0] + amount[1] + amount[2] + 1) / 2; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -149,21 +107,6 @@ public: }; ``` -```cpp -class Solution { -public: - int fillCups(vector& amount) { - sort(amount.begin(), amount.end()); - if (amount[0] + amount[1] <= amount[2]) { - return amount[2]; - } - return (amount[0] + amount[1] + amount[2] + 1) / 2; - } -}; -``` - -### **Go** - ```go func fillCups(amount []int) int { ans := 0 @@ -179,18 +122,6 @@ func fillCups(amount []int) int { } ``` -```go -func fillCups(amount []int) int { - sort.Ints(amount) - if amount[0]+amount[1] <= amount[2] { - return amount[2] - } - return (amount[0] + amount[1] + amount[2] + 1) / 2 -} -``` - -### **TypeScript** - ```ts function fillCups(amount: number[]): number { amount.sort((a, b) => a - b); @@ -201,8 +132,6 @@ function fillCups(amount: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn fill_cups(mut amount: Vec) -> i32 { @@ -216,10 +145,63 @@ impl Solution { } ``` -### **...** + + +### 方法二:贪心 + 分类讨论 + +我们可以将数组 `amount` 排序,设 $a$, $b$, $c$ 分别为数组 `amount` 中的三个数,有以下两种情况: + +- 如果 $a + b \leq c$,此时我们只需要 $c$ 次操作即可将所有数变为 $0$,因此答案为 $c$。 +- 如果 $a + b > c$,每一次操作我们都可以将其中两个数减一,最终匹配完,或者剩下最后一个数(取决于总和是偶数还是奇数),因此答案为 $\left \lfloor \frac{a + b + c + 1}{2} \right \rfloor$。 + +时间复杂度 $O(1)$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def fillCups(self, amount: List[int]) -> int: + amount.sort() + if amount[0] + amount[1] <= amount[2]: + return amount[2] + return (sum(amount) + 1) // 2 +``` + +```java +class Solution { + public int fillCups(int[] amount) { + Arrays.sort(amount); + if (amount[0] + amount[1] <= amount[2]) { + return amount[2]; + } + return (amount[0] + amount[1] + amount[2] + 1) / 2; + } +} +``` +```cpp +class Solution { +public: + int fillCups(vector& amount) { + sort(amount.begin(), amount.end()); + if (amount[0] + amount[1] <= amount[2]) { + return amount[2]; + } + return (amount[0] + amount[1] + amount[2] + 1) / 2; + } +}; ``` +```go +func fillCups(amount []int) int { + sort.Ints(amount) + if amount[0]+amount[1] <= amount[2] { + return amount[2] + } + return (amount[0] + amount[1] + amount[2] + 1) / 2 +} ``` + + diff --git a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/README_EN.md b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/README_EN.md index b5fa3540fa6e9..7decfa28ba8c9 100644 --- a/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/README_EN.md +++ b/solution/2300-2399/2335.Minimum Amount of Time to Fill Cups/README_EN.md @@ -55,9 +55,9 @@ Second 7: Fill up a hot cup. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,17 +71,6 @@ class Solution: return ans ``` -```python -class Solution: - def fillCups(self, amount: List[int]) -> int: - amount.sort() - if amount[0] + amount[1] <= amount[2]: - return amount[2] - return (sum(amount) + 1) // 2 -``` - -### **Java** - ```java class Solution { public int fillCups(int[] amount) { @@ -97,20 +86,6 @@ class Solution { } ``` -```java -class Solution { - public int fillCups(int[] amount) { - Arrays.sort(amount); - if (amount[0] + amount[1] <= amount[2]) { - return amount[2]; - } - return (amount[0] + amount[1] + amount[2] + 1) / 2; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -127,21 +102,6 @@ public: }; ``` -```cpp -class Solution { -public: - int fillCups(vector& amount) { - sort(amount.begin(), amount.end()); - if (amount[0] + amount[1] <= amount[2]) { - return amount[2]; - } - return (amount[0] + amount[1] + amount[2] + 1) / 2; - } -}; -``` - -### **Go** - ```go func fillCups(amount []int) int { ans := 0 @@ -157,18 +117,6 @@ func fillCups(amount []int) int { } ``` -```go -func fillCups(amount []int) int { - sort.Ints(amount) - if amount[0]+amount[1] <= amount[2] { - return amount[2] - } - return (amount[0] + amount[1] + amount[2] + 1) / 2 -} -``` - -### **TypeScript** - ```ts function fillCups(amount: number[]): number { amount.sort((a, b) => a - b); @@ -179,8 +127,6 @@ function fillCups(amount: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn fill_cups(mut amount: Vec) -> i32 { @@ -192,12 +138,58 @@ impl Solution { (dif + 1) / 2 + amount[2] } } +``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def fillCups(self, amount: List[int]) -> int: + amount.sort() + if amount[0] + amount[1] <= amount[2]: + return amount[2] + return (sum(amount) + 1) // 2 ``` +```java +class Solution { + public int fillCups(int[] amount) { + Arrays.sort(amount); + if (amount[0] + amount[1] <= amount[2]) { + return amount[2]; + } + return (amount[0] + amount[1] + amount[2] + 1) / 2; + } +} ``` - +```cpp +class Solution { +public: + int fillCups(vector& amount) { + sort(amount.begin(), amount.end()); + if (amount[0] + amount[1] <= amount[2]) { + return amount[2]; + } + return (amount[0] + amount[1] + amount[2] + 1) / 2; + } +}; +``` + +```go +func fillCups(amount []int) int { + sort.Ints(amount) + if amount[0]+amount[1] <= amount[2] { + return amount[2] + } + return (amount[0] + amount[1] + amount[2] + 1) / 2 +} ``` + + + + diff --git a/solution/2300-2399/2336.Smallest Number in Infinite Set/README.md b/solution/2300-2399/2336.Smallest Number in Infinite Set/README.md index 1716fad85fc4d..d015589a9c107 100644 --- a/solution/2300-2399/2336.Smallest Number in Infinite Set/README.md +++ b/solution/2300-2399/2336.Smallest Number in Infinite Set/README.md @@ -50,9 +50,7 @@ smallestInfiniteSet.popSmallest(); // 返回 5 ,并将其从集合中移除。 ## 解法 - - -**方法一:有序集合 + 模拟** +### 方法一:有序集合 + 模拟 我们注意到,题目中集合的元素范围是 $[1, 1000]$,并且我们需要支持的操作有: @@ -71,10 +69,6 @@ smallestInfiniteSet.popSmallest(); // 返回 5 ,并将其从集合中移除。 -### **Python3** - - - ```python from sortedcontainers import SortedSet @@ -98,10 +92,6 @@ class SmallestInfiniteSet: # obj.addBack(num) ``` -### **Java** - - - ```java class SmallestInfiniteSet { private TreeSet s = new TreeSet<>(); @@ -129,8 +119,6 @@ class SmallestInfiniteSet { */ ``` -### **C++** - ```cpp class SmallestInfiniteSet { public: @@ -162,8 +150,6 @@ private: */ ``` -### **Go** - ```go type SmallestInfiniteSet struct { s *treemap.Map @@ -195,8 +181,6 @@ func (this *SmallestInfiniteSet) AddBack(num int) { */ ``` -### **TypeScript** - ```ts class SmallestInfiniteSet { private s: TreeSet; @@ -865,44 +849,6 @@ class TreeMultiSet { */ ``` -```ts -class SmallestInfiniteSet { - private pq: typeof MinPriorityQueue; - private s: Set; - - constructor() { - this.pq = new MinPriorityQueue(); - this.s = new Set(); - for (let i = 1; i <= 1000; i++) { - this.pq.enqueue(i, i); - this.s.add(i); - } - } - - popSmallest(): number { - const x = this.pq.dequeue()?.element; - this.s.delete(x); - return x; - } - - addBack(num: number): void { - if (!this.s.has(num)) { - this.pq.enqueue(num, num); - this.s.add(num); - } - } -} - -/** - * Your SmallestInfiniteSet object will be instantiated and called as such: - * var obj = new SmallestInfiniteSet() - * var param_1 = obj.popSmallest() - * obj.addBack(num) - */ -``` - -### **Rust** - ```rust use std::collections::BTreeSet; @@ -936,10 +882,48 @@ impl SmallestInfiniteSet { */ ``` -### **...** + -``` +### 方法二 + + + +```ts +class SmallestInfiniteSet { + private pq: typeof MinPriorityQueue; + private s: Set; + + constructor() { + this.pq = new MinPriorityQueue(); + this.s = new Set(); + for (let i = 1; i <= 1000; i++) { + this.pq.enqueue(i, i); + this.s.add(i); + } + } + popSmallest(): number { + const x = this.pq.dequeue()?.element; + this.s.delete(x); + return x; + } + + addBack(num: number): void { + if (!this.s.has(num)) { + this.pq.enqueue(num, num); + this.s.add(num); + } + } +} + +/** + * Your SmallestInfiniteSet object will be instantiated and called as such: + * var obj = new SmallestInfiniteSet() + * var param_1 = obj.popSmallest() + * obj.addBack(num) + */ ``` + + diff --git a/solution/2300-2399/2336.Smallest Number in Infinite Set/README_EN.md b/solution/2300-2399/2336.Smallest Number in Infinite Set/README_EN.md index 067fa58ca8806..91bcd46ad482d 100644 --- a/solution/2300-2399/2336.Smallest Number in Infinite Set/README_EN.md +++ b/solution/2300-2399/2336.Smallest Number in Infinite Set/README_EN.md @@ -47,7 +47,7 @@ smallestInfiniteSet.popSmallest(); // return 5, and remove it from the set. ## Solutions -**Solution 1: Ordered Set + Simulation** +### Solution 1: Ordered Set + Simulation We note that the range of elements in the set given by the problem is $[1, 1000]$, and the operations we need to support are: @@ -66,8 +66,6 @@ The space complexity is $O(n)$. -### **Python3** - ```python from sortedcontainers import SortedSet @@ -91,8 +89,6 @@ class SmallestInfiniteSet: # obj.addBack(num) ``` -### **Java** - ```java class SmallestInfiniteSet { private TreeSet s = new TreeSet<>(); @@ -120,8 +116,6 @@ class SmallestInfiniteSet { */ ``` -### **C++** - ```cpp class SmallestInfiniteSet { public: @@ -153,8 +147,6 @@ private: */ ``` -### **Go** - ```go type SmallestInfiniteSet struct { s *treemap.Map @@ -186,8 +178,6 @@ func (this *SmallestInfiniteSet) AddBack(num int) { */ ``` -### **TypeScript** - ```ts class SmallestInfiniteSet { private s: TreeSet; @@ -856,44 +846,6 @@ class TreeMultiSet { */ ``` -```ts -class SmallestInfiniteSet { - private pq: typeof MinPriorityQueue; - private s: Set; - - constructor() { - this.pq = new MinPriorityQueue(); - this.s = new Set(); - for (let i = 1; i <= 1000; i++) { - this.pq.enqueue(i, i); - this.s.add(i); - } - } - - popSmallest(): number { - const x = this.pq.dequeue()?.element; - this.s.delete(x); - return x; - } - - addBack(num: number): void { - if (!this.s.has(num)) { - this.pq.enqueue(num, num); - this.s.add(num); - } - } -} - -/** - * Your SmallestInfiniteSet object will be instantiated and called as such: - * var obj = new SmallestInfiniteSet() - * var param_1 = obj.popSmallest() - * obj.addBack(num) - */ -``` - -### **Rust** - ```rust use std::collections::BTreeSet; @@ -927,10 +879,48 @@ impl SmallestInfiniteSet { */ ``` -### **...** + -``` +### Solution 2 + + + +```ts +class SmallestInfiniteSet { + private pq: typeof MinPriorityQueue; + private s: Set; + + constructor() { + this.pq = new MinPriorityQueue(); + this.s = new Set(); + for (let i = 1; i <= 1000; i++) { + this.pq.enqueue(i, i); + this.s.add(i); + } + } + + popSmallest(): number { + const x = this.pq.dequeue()?.element; + this.s.delete(x); + return x; + } + + addBack(num: number): void { + if (!this.s.has(num)) { + this.pq.enqueue(num, num); + this.s.add(num); + } + } +} +/** + * Your SmallestInfiniteSet object will be instantiated and called as such: + * var obj = new SmallestInfiniteSet() + * var param_1 = obj.popSmallest() + * obj.addBack(num) + */ ``` + + diff --git a/solution/2300-2399/2337.Move Pieces to Obtain a String/README.md b/solution/2300-2399/2337.Move Pieces to Obtain a String/README.md index f01e3c9c276ba..20dc8253e71e8 100644 --- a/solution/2300-2399/2337.Move Pieces to Obtain a String/README.md +++ b/solution/2300-2399/2337.Move Pieces to Obtain a String/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 替换操作实际上是将 `L` 往左移动(`L` 左边为 `_` 时才能移动),`R` 往右移动(`R` 右边是 `_` 时才能移动),但 `L` 无法穿过 `R`。所以,如果去掉 `start` 和 `target` 中的所有 `_`,剩下的字符应该是相同的,否则返回 `false`。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def canChange(self, start: str, target: str) -> bool: @@ -97,31 +91,6 @@ class Solution: return True ``` -```python -class Solution: - def canChange(self, start: str, target: str) -> bool: - n = len(start) - i = j = 0 - while 1: - while i < n and start[i] == '_': - i += 1 - while j < n and target[j] == '_': - j += 1 - if i >= n and j >= n: - return True - if i >= n or j >= n or start[i] != target[j]: - return False - if start[i] == 'L' and i < j: - return False - if start[i] == 'R' and i > j: - return False - i, j = i + 1, j + 1 -``` - -### **Java** - - - ```java class Solution { public boolean canChange(String start, String target) { @@ -160,36 +129,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canChange(String start, String target) { - int n = start.length(); - int i = 0, j = 0; - while (true) { - while (i < n && start.charAt(i) == '_') { - ++i; - } - while (j < n && target.charAt(j) == '_') { - ++j; - } - if (i == n && j == n) { - return true; - } - if (i == n || j == n || start.charAt(i) != target.charAt(j)) { - return false; - } - if (start.charAt(i) == 'L' && i < j || start.charAt(i) == 'R' && i > j) { - return false; - } - ++i; - ++j; - } - } -} -``` - -### **C++** - ```cpp using pii = pair; @@ -221,28 +160,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool canChange(string start, string target) { - int n = start.size(); - int i = 0, j = 0; - while (true) { - while (i < n && start[i] == '_') ++i; - while (j < n && target[j] == '_') ++j; - if (i == n && j == n) return true; - if (i == n || j == n || start[i] != target[j]) return false; - if (start[i] == 'L' && i < j) return false; - if (start[i] == 'R' && i > j) return false; - ++i; - ++j; - } - } -}; -``` - -### **Go** - ```go func canChange(start string, target string) bool { f := func(s string) [][]int { @@ -277,36 +194,6 @@ func canChange(start string, target string) bool { } ``` -```go -func canChange(start string, target string) bool { - n := len(start) - i, j := 0, 0 - for { - for i < n && start[i] == '_' { - i++ - } - for j < n && target[j] == '_' { - j++ - } - if i == n && j == n { - return true - } - if i == n || j == n || start[i] != target[j] { - return false - } - if start[i] == 'L' && i < j { - return false - } - if start[i] == 'R' && i > j { - return false - } - i, j = i+1, j+1 - } -} -``` - -### **TypeScript** - ```ts function canChange(start: string, target: string): boolean { if ( @@ -341,6 +228,109 @@ function canChange(start: string, target: string): boolean { } ``` + + +### 方法二 + + + +```python +class Solution: + def canChange(self, start: str, target: str) -> bool: + n = len(start) + i = j = 0 + while 1: + while i < n and start[i] == '_': + i += 1 + while j < n and target[j] == '_': + j += 1 + if i >= n and j >= n: + return True + if i >= n or j >= n or start[i] != target[j]: + return False + if start[i] == 'L' and i < j: + return False + if start[i] == 'R' and i > j: + return False + i, j = i + 1, j + 1 +``` + +```java +class Solution { + public boolean canChange(String start, String target) { + int n = start.length(); + int i = 0, j = 0; + while (true) { + while (i < n && start.charAt(i) == '_') { + ++i; + } + while (j < n && target.charAt(j) == '_') { + ++j; + } + if (i == n && j == n) { + return true; + } + if (i == n || j == n || start.charAt(i) != target.charAt(j)) { + return false; + } + if (start.charAt(i) == 'L' && i < j || start.charAt(i) == 'R' && i > j) { + return false; + } + ++i; + ++j; + } + } +} +``` + +```cpp +class Solution { +public: + bool canChange(string start, string target) { + int n = start.size(); + int i = 0, j = 0; + while (true) { + while (i < n && start[i] == '_') ++i; + while (j < n && target[j] == '_') ++j; + if (i == n && j == n) return true; + if (i == n || j == n || start[i] != target[j]) return false; + if (start[i] == 'L' && i < j) return false; + if (start[i] == 'R' && i > j) return false; + ++i; + ++j; + } + } +}; +``` + +```go +func canChange(start string, target string) bool { + n := len(start) + i, j := 0, 0 + for { + for i < n && start[i] == '_' { + i++ + } + for j < n && target[j] == '_' { + j++ + } + if i == n && j == n { + return true + } + if i == n || j == n || start[i] != target[j] { + return false + } + if start[i] == 'L' && i < j { + return false + } + if start[i] == 'R' && i > j { + return false + } + i, j = i+1, j+1 + } +} +``` + ```ts function canChange(start: string, target: string): boolean { const n = start.length; @@ -367,10 +357,6 @@ function canChange(start: string, target: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2337.Move Pieces to Obtain a String/README_EN.md b/solution/2300-2399/2337.Move Pieces to Obtain a String/README_EN.md index 2ef3eec8f5908..0b8bef787e4d0 100644 --- a/solution/2300-2399/2337.Move Pieces to Obtain a String/README_EN.md +++ b/solution/2300-2399/2337.Move Pieces to Obtain a String/README_EN.md @@ -53,9 +53,9 @@ After that, no pieces can move anymore, so it is impossible to obtain the string ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,29 +74,6 @@ class Solution: return True ``` -```python -class Solution: - def canChange(self, start: str, target: str) -> bool: - n = len(start) - i = j = 0 - while 1: - while i < n and start[i] == '_': - i += 1 - while j < n and target[j] == '_': - j += 1 - if i >= n and j >= n: - return True - if i >= n or j >= n or start[i] != target[j]: - return False - if start[i] == 'L' and i < j: - return False - if start[i] == 'R' and i > j: - return False - i, j = i + 1, j + 1 -``` - -### **Java** - ```java class Solution { public boolean canChange(String start, String target) { @@ -135,36 +112,6 @@ class Solution { } ``` -```java -class Solution { - public boolean canChange(String start, String target) { - int n = start.length(); - int i = 0, j = 0; - while (true) { - while (i < n && start.charAt(i) == '_') { - ++i; - } - while (j < n && target.charAt(j) == '_') { - ++j; - } - if (i == n && j == n) { - return true; - } - if (i == n || j == n || start.charAt(i) != target.charAt(j)) { - return false; - } - if (start.charAt(i) == 'L' && i < j || start.charAt(i) == 'R' && i > j) { - return false; - } - ++i; - ++j; - } - } -} -``` - -### **C++** - ```cpp using pii = pair; @@ -196,28 +143,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool canChange(string start, string target) { - int n = start.size(); - int i = 0, j = 0; - while (true) { - while (i < n && start[i] == '_') ++i; - while (j < n && target[j] == '_') ++j; - if (i == n && j == n) return true; - if (i == n || j == n || start[i] != target[j]) return false; - if (start[i] == 'L' && i < j) return false; - if (start[i] == 'R' && i > j) return false; - ++i; - ++j; - } - } -}; -``` - -### **Go** - ```go func canChange(start string, target string) bool { f := func(s string) [][]int { @@ -252,36 +177,6 @@ func canChange(start string, target string) bool { } ``` -```go -func canChange(start string, target string) bool { - n := len(start) - i, j := 0, 0 - for { - for i < n && start[i] == '_' { - i++ - } - for j < n && target[j] == '_' { - j++ - } - if i == n && j == n { - return true - } - if i == n || j == n || start[i] != target[j] { - return false - } - if start[i] == 'L' && i < j { - return false - } - if start[i] == 'R' && i > j { - return false - } - i, j = i+1, j+1 - } -} -``` - -### **TypeScript** - ```ts function canChange(start: string, target: string): boolean { if ( @@ -316,6 +211,109 @@ function canChange(start: string, target: string): boolean { } ``` + + +### Solution 2 + + + +```python +class Solution: + def canChange(self, start: str, target: str) -> bool: + n = len(start) + i = j = 0 + while 1: + while i < n and start[i] == '_': + i += 1 + while j < n and target[j] == '_': + j += 1 + if i >= n and j >= n: + return True + if i >= n or j >= n or start[i] != target[j]: + return False + if start[i] == 'L' and i < j: + return False + if start[i] == 'R' and i > j: + return False + i, j = i + 1, j + 1 +``` + +```java +class Solution { + public boolean canChange(String start, String target) { + int n = start.length(); + int i = 0, j = 0; + while (true) { + while (i < n && start.charAt(i) == '_') { + ++i; + } + while (j < n && target.charAt(j) == '_') { + ++j; + } + if (i == n && j == n) { + return true; + } + if (i == n || j == n || start.charAt(i) != target.charAt(j)) { + return false; + } + if (start.charAt(i) == 'L' && i < j || start.charAt(i) == 'R' && i > j) { + return false; + } + ++i; + ++j; + } + } +} +``` + +```cpp +class Solution { +public: + bool canChange(string start, string target) { + int n = start.size(); + int i = 0, j = 0; + while (true) { + while (i < n && start[i] == '_') ++i; + while (j < n && target[j] == '_') ++j; + if (i == n && j == n) return true; + if (i == n || j == n || start[i] != target[j]) return false; + if (start[i] == 'L' && i < j) return false; + if (start[i] == 'R' && i > j) return false; + ++i; + ++j; + } + } +}; +``` + +```go +func canChange(start string, target string) bool { + n := len(start) + i, j := 0, 0 + for { + for i < n && start[i] == '_' { + i++ + } + for j < n && target[j] == '_' { + j++ + } + if i == n && j == n { + return true + } + if i == n || j == n || start[i] != target[j] { + return false + } + if start[i] == 'L' && i < j { + return false + } + if start[i] == 'R' && i > j { + return false + } + i, j = i+1, j+1 + } +} +``` + ```ts function canChange(start: string, target: string): boolean { const n = start.length; @@ -342,10 +340,6 @@ function canChange(start: string, target: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2338.Count the Number of Ideal Arrays/README.md b/solution/2300-2399/2338.Count the Number of Ideal Arrays/README.md index 464633ab5cd32..fdfef0bc86276 100644 --- a/solution/2300-2399/2338.Count the Number of Ideal Arrays/README.md +++ b/solution/2300-2399/2338.Count the Number of Ideal Arrays/README.md @@ -57,28 +57,10 @@ ## 解法 - - -我们注意到,$maxValue$ 的最大值不超过 $10^4$,如果数组不含重复元素,那么数组最多只会有不超过 $16$ 个元素。 - -**方法一:记忆化搜索 + 组合计数** - -**方法二:动态规划** - -设 $dp[i][j]$ 表示以 $i$ 结尾,且由 $j$ 个不同元素构成的序列的方案数。初始值 $dp[i][1]=1$。 - -考虑 $n$ 个小球,最终划分为 $j$ 份,那么可以用“隔板法”,即在 $n-1$ 个位置上插入 $j-1$ 个隔板,那么组合数为 $C_{n-1}^{j-1}$ 。 - -我们可以预处理组合数 $C[i][j]$,根据递推公式 $C[i][j]=C[i-1][j]+C[i-1][j-1]$ 求得,特别地,当 $j=0$ 时,$C[i][j]=1$。 - -最终的答案为 $\sum\limits_{i=1}^{k}\sum\limits_{j=1}^{\log_2 k + 1}dp[i][j] \times C_{n-1}^{j-1}$ 。其中 $k$ 表示数组的最大值,即 $maxValue$。 +### 方法一:记忆化搜索 + 组合计数 -### **Python3** - - - ```python class Solution: def idealArrays(self, n: int, maxValue: int) -> int: @@ -103,34 +85,6 @@ class Solution: return ans ``` -```python -class Solution: - def idealArrays(self, n: int, maxValue: int) -> int: - c = [[0] * 16 for _ in range(n)] - mod = 10**9 + 7 - for i in range(n): - for j in range(min(16, i + 1)): - c[i][j] = 1 if j == 0 else (c[i - 1][j] + c[i - 1][j - 1]) % mod - dp = [[0] * 16 for _ in range(maxValue + 1)] - for i in range(1, maxValue + 1): - dp[i][1] = 1 - for j in range(1, 15): - for i in range(1, maxValue + 1): - k = 2 - while k * i <= maxValue: - dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % mod - k += 1 - ans = 0 - for i in range(1, maxValue + 1): - for j in range(1, 16): - ans = (ans + dp[i][j] * c[-1][j - 1]) % mod - return ans -``` - -### **Java** - - - ```java class Solution { private int[][] f; @@ -175,42 +129,6 @@ class Solution { } ``` -```java -class Solution { - private static final int MOD = (int) 1e9 + 7; - - public int idealArrays(int n, int maxValue) { - int[][] c = new int[n][16]; - for (int i = 0; i < n; ++i) { - for (int j = 0; j <= i && j < 16; ++j) { - c[i][j] = j == 0 ? 1 : (c[i - 1][j] + c[i - 1][j - 1]) % MOD; - } - } - long[][] dp = new long[maxValue + 1][16]; - for (int i = 1; i <= maxValue; ++i) { - dp[i][1] = 1; - } - for (int j = 1; j < 15; ++j) { - for (int i = 1; i <= maxValue; ++i) { - int k = 2; - for (; k * i <= maxValue; ++k) { - dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % MOD; - } - } - } - long ans = 0; - for (int i = 1; i <= maxValue; ++i) { - for (int j = 1; j < 16; ++j) { - ans = (ans + dp[i][j] * c[n - 1][j - 1]) % MOD; - } - } - return (int) ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -244,37 +162,6 @@ public: }; ``` -```cpp -using ll = long long; - -class Solution { -public: - const int mod = 1e9 + 7; - - int idealArrays(int n, int maxValue) { - vector> c(n, vector(16)); - for (int i = 0; i < n; ++i) - for (int j = 0; j <= i && j < 16; ++j) - c[i][j] = j == 0 ? 1 : (c[i - 1][j] + c[i - 1][j - 1]) % mod; - vector> dp(maxValue + 1, vector(16)); - for (int i = 1; i <= maxValue; ++i) dp[i][1] = 1; - for (int j = 1; j < 15; ++j) { - for (int i = 1; i <= maxValue; ++i) { - int k = 2; - for (; k * i <= maxValue; ++k) dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % mod; - } - } - ll ans = 0; - for (int i = 1; i <= maxValue; ++i) - for (int j = 1; j < 16; ++j) - ans = (ans + dp[i][j] * c[n - 1][j - 1]) % mod; - return (int) ans; - } -}; -``` - -### **Go** - ```go func idealArrays(n int, maxValue int) int { mod := int(1e9) + 7 @@ -321,6 +208,107 @@ func idealArrays(n int, maxValue int) int { } ``` + + +### 方法二:动态规划 + +设 $dp[i][j]$ 表示以 $i$ 结尾,且由 $j$ 个不同元素构成的序列的方案数。初始值 $dp[i][1]=1$。 + +考虑 $n$ 个小球,最终划分为 $j$ 份,那么可以用“隔板法”,即在 $n-1$ 个位置上插入 $j-1$ 个隔板,那么组合数为 $C_{n-1}^{j-1}$ 。 + +我们可以预处理组合数 $C[i][j]$,根据递推公式 $C[i][j]=C[i-1][j]+C[i-1][j-1]$ 求得,特别地,当 $j=0$ 时,$C[i][j]=1$。 + +最终的答案为 $\sum\limits_{i=1}^{k}\sum\limits_{j=1}^{\log_2 k + 1}dp[i][j] \times C_{n-1}^{j-1}$ 。其中 $k$ 表示数组的最大值,即 $maxValue$。 + + + +```python +class Solution: + def idealArrays(self, n: int, maxValue: int) -> int: + c = [[0] * 16 for _ in range(n)] + mod = 10**9 + 7 + for i in range(n): + for j in range(min(16, i + 1)): + c[i][j] = 1 if j == 0 else (c[i - 1][j] + c[i - 1][j - 1]) % mod + dp = [[0] * 16 for _ in range(maxValue + 1)] + for i in range(1, maxValue + 1): + dp[i][1] = 1 + for j in range(1, 15): + for i in range(1, maxValue + 1): + k = 2 + while k * i <= maxValue: + dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % mod + k += 1 + ans = 0 + for i in range(1, maxValue + 1): + for j in range(1, 16): + ans = (ans + dp[i][j] * c[-1][j - 1]) % mod + return ans +``` + +```java +class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int idealArrays(int n, int maxValue) { + int[][] c = new int[n][16]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j <= i && j < 16; ++j) { + c[i][j] = j == 0 ? 1 : (c[i - 1][j] + c[i - 1][j - 1]) % MOD; + } + } + long[][] dp = new long[maxValue + 1][16]; + for (int i = 1; i <= maxValue; ++i) { + dp[i][1] = 1; + } + for (int j = 1; j < 15; ++j) { + for (int i = 1; i <= maxValue; ++i) { + int k = 2; + for (; k * i <= maxValue; ++k) { + dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % MOD; + } + } + } + long ans = 0; + for (int i = 1; i <= maxValue; ++i) { + for (int j = 1; j < 16; ++j) { + ans = (ans + dp[i][j] * c[n - 1][j - 1]) % MOD; + } + } + return (int) ans; + } +} +``` + +```cpp +using ll = long long; + +class Solution { +public: + const int mod = 1e9 + 7; + + int idealArrays(int n, int maxValue) { + vector> c(n, vector(16)); + for (int i = 0; i < n; ++i) + for (int j = 0; j <= i && j < 16; ++j) + c[i][j] = j == 0 ? 1 : (c[i - 1][j] + c[i - 1][j - 1]) % mod; + vector> dp(maxValue + 1, vector(16)); + for (int i = 1; i <= maxValue; ++i) dp[i][1] = 1; + for (int j = 1; j < 15; ++j) { + for (int i = 1; i <= maxValue; ++i) { + int k = 2; + for (; k * i <= maxValue; ++k) dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % mod; + } + } + ll ans = 0; + for (int i = 1; i <= maxValue; ++i) + for (int j = 1; j < 16; ++j) + ans = (ans + dp[i][j] * c[n - 1][j - 1]) % mod; + return (int) ans; + } +}; +``` + ```go func idealArrays(n int, maxValue int) int { mod := int(1e9) + 7 @@ -360,16 +348,6 @@ func idealArrays(n int, maxValue int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2338.Count the Number of Ideal Arrays/README_EN.md b/solution/2300-2399/2338.Count the Number of Ideal Arrays/README_EN.md index 3e31dd2ee628e..9da1fa0cb4729 100644 --- a/solution/2300-2399/2338.Count the Number of Ideal Arrays/README_EN.md +++ b/solution/2300-2399/2338.Count the Number of Ideal Arrays/README_EN.md @@ -55,9 +55,9 @@ There are a total of 9 + 1 + 1 = 11 distinct ideal arrays. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,32 +83,6 @@ class Solution: return ans ``` -```python -class Solution: - def idealArrays(self, n: int, maxValue: int) -> int: - c = [[0] * 16 for _ in range(n)] - mod = 10**9 + 7 - for i in range(n): - for j in range(min(16, i + 1)): - c[i][j] = 1 if j == 0 else (c[i - 1][j] + c[i - 1][j - 1]) % mod - dp = [[0] * 16 for _ in range(maxValue + 1)] - for i in range(1, maxValue + 1): - dp[i][1] = 1 - for j in range(1, 15): - for i in range(1, maxValue + 1): - k = 2 - while k * i <= maxValue: - dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % mod - k += 1 - ans = 0 - for i in range(1, maxValue + 1): - for j in range(1, 16): - ans = (ans + dp[i][j] * c[-1][j - 1]) % mod - return ans -``` - -### **Java** - ```java class Solution { private int[][] f; @@ -153,42 +127,6 @@ class Solution { } ``` -```java -class Solution { - private static final int MOD = (int) 1e9 + 7; - - public int idealArrays(int n, int maxValue) { - int[][] c = new int[n][16]; - for (int i = 0; i < n; ++i) { - for (int j = 0; j <= i && j < 16; ++j) { - c[i][j] = j == 0 ? 1 : (c[i - 1][j] + c[i - 1][j - 1]) % MOD; - } - } - long[][] dp = new long[maxValue + 1][16]; - for (int i = 1; i <= maxValue; ++i) { - dp[i][1] = 1; - } - for (int j = 1; j < 15; ++j) { - for (int i = 1; i <= maxValue; ++i) { - int k = 2; - for (; k * i <= maxValue; ++k) { - dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % MOD; - } - } - } - long ans = 0; - for (int i = 1; i <= maxValue; ++i) { - for (int j = 1; j < 16; ++j) { - ans = (ans + dp[i][j] * c[n - 1][j - 1]) % MOD; - } - } - return (int) ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -222,37 +160,6 @@ public: }; ``` -```cpp -using ll = long long; - -class Solution { -public: - const int mod = 1e9 + 7; - - int idealArrays(int n, int maxValue) { - vector> c(n, vector(16)); - for (int i = 0; i < n; ++i) - for (int j = 0; j <= i && j < 16; ++j) - c[i][j] = j == 0 ? 1 : (c[i - 1][j] + c[i - 1][j - 1]) % mod; - vector> dp(maxValue + 1, vector(16)); - for (int i = 1; i <= maxValue; ++i) dp[i][1] = 1; - for (int j = 1; j < 15; ++j) { - for (int i = 1; i <= maxValue; ++i) { - int k = 2; - for (; k * i <= maxValue; ++k) dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % mod; - } - } - ll ans = 0; - for (int i = 1; i <= maxValue; ++i) - for (int j = 1; j < 16; ++j) - ans = (ans + dp[i][j] * c[n - 1][j - 1]) % mod; - return (int) ans; - } -}; -``` - -### **Go** - ```go func idealArrays(n int, maxValue int) int { mod := int(1e9) + 7 @@ -299,6 +206,99 @@ func idealArrays(n int, maxValue int) int { } ``` + + +### Solution 2 + + + +```python +class Solution: + def idealArrays(self, n: int, maxValue: int) -> int: + c = [[0] * 16 for _ in range(n)] + mod = 10**9 + 7 + for i in range(n): + for j in range(min(16, i + 1)): + c[i][j] = 1 if j == 0 else (c[i - 1][j] + c[i - 1][j - 1]) % mod + dp = [[0] * 16 for _ in range(maxValue + 1)] + for i in range(1, maxValue + 1): + dp[i][1] = 1 + for j in range(1, 15): + for i in range(1, maxValue + 1): + k = 2 + while k * i <= maxValue: + dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % mod + k += 1 + ans = 0 + for i in range(1, maxValue + 1): + for j in range(1, 16): + ans = (ans + dp[i][j] * c[-1][j - 1]) % mod + return ans +``` + +```java +class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int idealArrays(int n, int maxValue) { + int[][] c = new int[n][16]; + for (int i = 0; i < n; ++i) { + for (int j = 0; j <= i && j < 16; ++j) { + c[i][j] = j == 0 ? 1 : (c[i - 1][j] + c[i - 1][j - 1]) % MOD; + } + } + long[][] dp = new long[maxValue + 1][16]; + for (int i = 1; i <= maxValue; ++i) { + dp[i][1] = 1; + } + for (int j = 1; j < 15; ++j) { + for (int i = 1; i <= maxValue; ++i) { + int k = 2; + for (; k * i <= maxValue; ++k) { + dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % MOD; + } + } + } + long ans = 0; + for (int i = 1; i <= maxValue; ++i) { + for (int j = 1; j < 16; ++j) { + ans = (ans + dp[i][j] * c[n - 1][j - 1]) % MOD; + } + } + return (int) ans; + } +} +``` + +```cpp +using ll = long long; + +class Solution { +public: + const int mod = 1e9 + 7; + + int idealArrays(int n, int maxValue) { + vector> c(n, vector(16)); + for (int i = 0; i < n; ++i) + for (int j = 0; j <= i && j < 16; ++j) + c[i][j] = j == 0 ? 1 : (c[i - 1][j] + c[i - 1][j - 1]) % mod; + vector> dp(maxValue + 1, vector(16)); + for (int i = 1; i <= maxValue; ++i) dp[i][1] = 1; + for (int j = 1; j < 15; ++j) { + for (int i = 1; i <= maxValue; ++i) { + int k = 2; + for (; k * i <= maxValue; ++k) dp[k * i][j + 1] = (dp[k * i][j + 1] + dp[i][j]) % mod; + } + } + ll ans = 0; + for (int i = 1; i <= maxValue; ++i) + for (int j = 1; j < 16; ++j) + ans = (ans + dp[i][j] * c[n - 1][j - 1]) % mod; + return (int) ans; + } +}; +``` + ```go func idealArrays(n int, maxValue int) int { mod := int(1e9) + 7 @@ -338,16 +338,6 @@ func idealArrays(n int, maxValue int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2339.All the Matches of the League/README.md b/solution/2300-2399/2339.All the Matches of the League/README.md index 166724e203425..49da52872bbb5 100644 --- a/solution/2300-2399/2339.All the Matches of the League/README.md +++ b/solution/2300-2399/2339.All the Matches of the League/README.md @@ -54,14 +54,10 @@ Teams 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT t1.team_name AS home_team, t2.team_name AS away_team @@ -72,3 +68,5 @@ WHERE t1.team_name != t2.team_name; ``` + + diff --git a/solution/2300-2399/2339.All the Matches of the League/README_EN.md b/solution/2300-2399/2339.All the Matches of the League/README_EN.md index 430c355b76f90..bd741af61aba4 100644 --- a/solution/2300-2399/2339.All the Matches of the League/README_EN.md +++ b/solution/2300-2399/2339.All the Matches of the League/README_EN.md @@ -53,9 +53,9 @@ Teams table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -67,3 +67,5 @@ WHERE t1.team_name != t2.team_name; ``` + + diff --git a/solution/2300-2399/2340.Minimum Adjacent Swaps to Make a Valid Array/README.md b/solution/2300-2399/2340.Minimum Adjacent Swaps to Make a Valid Array/README.md index 08389914e0692..f9803daed16bf 100644 --- a/solution/2300-2399/2340.Minimum Adjacent Swaps to Make a Valid Array/README.md +++ b/solution/2300-2399/2340.Minimum Adjacent Swaps to Make a Valid Array/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:维护最值下标 + 分类讨论** +### 方法一:维护最值下标 + 分类讨论 我们可以用下标 $i$ 和 $j$ 分别记录数组 `nums` 第一个最小值和最后一个最大值的下标,遍历数组 `nums`,更新 $i$ 和 $j$ 的值。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def minimumSwaps(self, nums: List[int]) -> int: @@ -86,10 +80,6 @@ class Solution: return 0 if i == j else i + len(nums) - 1 - j - (i > j) ``` -### **Java** - - - ```java class Solution { public int minimumSwaps(int[] nums) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func minimumSwaps(nums []int) int { var i, j int @@ -158,8 +144,6 @@ func minimumSwaps(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumSwaps(nums: number[]): number { let i = 0; @@ -177,10 +161,6 @@ function minimumSwaps(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2340.Minimum Adjacent Swaps to Make a Valid Array/README_EN.md b/solution/2300-2399/2340.Minimum Adjacent Swaps to Make a Valid Array/README_EN.md index 8fc6c5b1676c9..a61abdb009233 100644 --- a/solution/2300-2399/2340.Minimum Adjacent Swaps to Make a Valid Array/README_EN.md +++ b/solution/2300-2399/2340.Minimum Adjacent Swaps to Make a Valid Array/README_EN.md @@ -51,9 +51,9 @@ It can be shown that 6 swaps is the minimum swaps required to make a valid array ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return 0 if i == j else i + len(nums) - 1 - j - (i > j) ``` -### **Java** - ```java class Solution { public int minimumSwaps(int[] nums) { @@ -90,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +110,6 @@ public: }; ``` -### **Go** - ```go func minimumSwaps(nums []int) int { var i, j int @@ -137,8 +131,6 @@ func minimumSwaps(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumSwaps(nums: number[]): number { let i = 0; @@ -156,10 +148,6 @@ function minimumSwaps(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2341.Maximum Number of Pairs in Array/README.md b/solution/2300-2399/2341.Maximum Number of Pairs in Array/README.md index faa1263b38567..307e11c591b87 100644 --- a/solution/2300-2399/2341.Maximum Number of Pairs in Array/README.md +++ b/solution/2300-2399/2341.Maximum Number of Pairs in Array/README.md @@ -54,9 +54,7 @@ nums[0] 和 nums[1] 形成一个数对,并从 nums 中移除,nums = [2] 。 ## 解法 - - -**方法一:计数** +### 方法一:计数 我们可以统计数组 `nums` 中每个数字 $x$ 出现的次数,记录在哈希表或数组 `cnt` 中。 @@ -70,10 +68,6 @@ nums[0] 和 nums[1] 形成一个数对,并从 nums 中移除,nums = [2] 。 -### **Python3** - - - ```python class Solution: def numberOfPairs(self, nums: List[int]) -> List[int]: @@ -82,10 +76,6 @@ class Solution: return [s, len(nums) - s * 2] ``` -### **Java** - - - ```java class Solution { public int[] numberOfPairs(int[] nums) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func numberOfPairs(nums []int) []int { cnt := [101]int{} @@ -137,8 +123,6 @@ func numberOfPairs(nums []int) []int { } ``` -### **TypeScript** - ```ts function numberOfPairs(nums: number[]): number[] { const n = nums.length; @@ -151,8 +135,6 @@ function numberOfPairs(nums: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn number_of_pairs(nums: Vec) -> Vec { @@ -170,31 +152,6 @@ impl Solution { } ``` -### **C** - -```c -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -int* numberOfPairs(int* nums, int numsSize, int* returnSize) { - int count[101] = {0}; - for (int i = 0; i < numsSize; i++) { - count[nums[i]]++; - } - int sum = 0; - for (int i = 0; i < 101; i++) { - sum += count[i] >> 1; - } - int* ans = malloc(sizeof(int) * 2); - ans[0] = sum; - ans[1] = numsSize - sum * 2; - *returnSize = 2; - return ans; -} -``` - -### **JavaScript** - ```js /** * @param {number[]} nums @@ -210,8 +167,6 @@ var numberOfPairs = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public int[] NumberOfPairs(int[] nums) { @@ -228,10 +183,27 @@ public class Solution { } ``` -### **...** - -``` - +```c +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int* numberOfPairs(int* nums, int numsSize, int* returnSize) { + int count[101] = {0}; + for (int i = 0; i < numsSize; i++) { + count[nums[i]]++; + } + int sum = 0; + for (int i = 0; i < 101; i++) { + sum += count[i] >> 1; + } + int* ans = malloc(sizeof(int) * 2); + ans[0] = sum; + ans[1] = numsSize - sum * 2; + *returnSize = 2; + return ans; +} ``` + + diff --git a/solution/2300-2399/2341.Maximum Number of Pairs in Array/README_EN.md b/solution/2300-2399/2341.Maximum Number of Pairs in Array/README_EN.md index ed46d348c365d..fcf234b61ed04 100644 --- a/solution/2300-2399/2341.Maximum Number of Pairs in Array/README_EN.md +++ b/solution/2300-2399/2341.Maximum Number of Pairs in Array/README_EN.md @@ -55,9 +55,9 @@ No more pairs can be formed. A total of 1 pair has been formed, and there are 0 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return [s, len(nums) - s * 2] ``` -### **Java** - ```java class Solution { public int[] numberOfPairs(int[] nums) { @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +100,6 @@ public: }; ``` -### **Go** - ```go func numberOfPairs(nums []int) []int { cnt := [101]int{} @@ -120,8 +114,6 @@ func numberOfPairs(nums []int) []int { } ``` -### **TypeScript** - ```ts function numberOfPairs(nums: number[]): number[] { const n = nums.length; @@ -134,8 +126,6 @@ function numberOfPairs(nums: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn number_of_pairs(nums: Vec) -> Vec { @@ -153,31 +143,6 @@ impl Solution { } ``` -### **C** - -```c -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -int* numberOfPairs(int* nums, int numsSize, int* returnSize) { - int count[101] = {0}; - for (int i = 0; i < numsSize; i++) { - count[nums[i]]++; - } - int sum = 0; - for (int i = 0; i < 101; i++) { - sum += count[i] >> 1; - } - int* ans = malloc(sizeof(int) * 2); - ans[0] = sum; - ans[1] = numsSize - sum * 2; - *returnSize = 2; - return ans; -} -``` - -### **JavaScript** - ```js /** * @param {number[]} nums @@ -193,8 +158,6 @@ var numberOfPairs = function (nums) { }; ``` -### **C#** - ```cs public class Solution { public int[] NumberOfPairs(int[] nums) { @@ -211,10 +174,27 @@ public class Solution { } ``` -### **...** - -``` - +```c +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int* numberOfPairs(int* nums, int numsSize, int* returnSize) { + int count[101] = {0}; + for (int i = 0; i < numsSize; i++) { + count[nums[i]]++; + } + int sum = 0; + for (int i = 0; i < 101; i++) { + sum += count[i] >> 1; + } + int* ans = malloc(sizeof(int) * 2); + ans[0] = sum; + ans[1] = numsSize - sum * 2; + *returnSize = 2; + return ans; +} ``` + + diff --git a/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/README.md b/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/README.md index e6846ff73da5f..e37e3aba7a9dc 100644 --- a/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/README.md +++ b/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以用一个哈希表 $d$ 记录每个数位和对应的最大值,初始化一个答案变量 $ans = -1$。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def maximumSum(self, nums: List[int]) -> int: @@ -77,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumSum(int[] nums) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func maximumSum(nums []int) int { d := [100]int{} @@ -144,8 +130,6 @@ func maximumSum(nums []int) int { } ``` -### **TypeScript** - ```ts function maximumSum(nums: number[]): number { const d: number[] = Array(100).fill(0); @@ -164,8 +148,6 @@ function maximumSum(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn maximum_sum(nums: Vec) -> i32 { @@ -190,10 +172,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/README_EN.md b/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/README_EN.md index 9b6aeef73a814..db992450cb648 100644 --- a/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/README_EN.md +++ b/solution/2300-2399/2342.Max Sum of a Pair With Equal Sum of Digits/README_EN.md @@ -38,7 +38,7 @@ So the maximum sum that we can obtain is 54. ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We can use a hash table $d$ to record the maximum value corresponding to each digit sum, and initialize an answer variable $ans = -1$. @@ -52,8 +52,6 @@ The time complexity is $O(n \times \log M)$, and the space complexity is $O(D)$. -### **Python3** - ```python class Solution: def maximumSum(self, nums: List[int]) -> int: @@ -70,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumSum(int[] nums) { @@ -92,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +109,6 @@ public: }; ``` -### **Go** - ```go func maximumSum(nums []int) int { d := [100]int{} @@ -135,8 +127,6 @@ func maximumSum(nums []int) int { } ``` -### **TypeScript** - ```ts function maximumSum(nums: number[]): number { const d: number[] = Array(100).fill(0); @@ -155,8 +145,6 @@ function maximumSum(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn maximum_sum(nums: Vec) -> i32 { @@ -181,10 +169,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2343.Query Kth Smallest Trimmed Number/README.md b/solution/2300-2399/2343.Query Kth Smallest Trimmed Number/README.md index 7a6843aea6e89..97146cf4662da 100644 --- a/solution/2300-2399/2343.Query Kth Smallest Trimmed Number/README.md +++ b/solution/2300-2399/2343.Query Kth Smallest Trimmed Number/README.md @@ -72,9 +72,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 根据题意,我们可以模拟裁剪过程,然后对裁剪后的字符串进行排序,最后根据下标找到对应的数字即可。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def smallestTrimmedNumbers( @@ -98,10 +92,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] smallestTrimmedNumbers(String[] nums, int[][] queries) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +135,6 @@ public: }; ``` -### **Go** - ```go func smallestTrimmedNumbers(nums []string, queries [][]int) []int { type pair struct { @@ -168,16 +154,6 @@ func smallestTrimmedNumbers(nums []string, queries [][]int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2343.Query Kth Smallest Trimmed Number/README_EN.md b/solution/2300-2399/2343.Query Kth Smallest Trimmed Number/README_EN.md index b58d163c61327..dcca6503256a8 100644 --- a/solution/2300-2399/2343.Query Kth Smallest Trimmed Number/README_EN.md +++ b/solution/2300-2399/2343.Query Kth Smallest Trimmed Number/README_EN.md @@ -67,9 +67,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,8 +83,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] smallestTrimmedNumbers(String[] nums, int[][] queries) { @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +126,6 @@ public: }; ``` -### **Go** - ```go func smallestTrimmedNumbers(nums []string, queries [][]int) []int { type pair struct { @@ -151,16 +145,6 @@ func smallestTrimmedNumbers(nums []string, queries [][]int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/README.md b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/README.md index 183af1aef5314..10708af2abea0 100644 --- a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/README.md +++ b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:数学 + 排序** +### 方法一:数学 + 排序 如果一个元素能整除数组 `numsDivide` 所有元素,那么这个元素是所有 $numsDivide[i]$ 的最大公约数 $x$ 的因子。因此,我们可以先求出 `numsDivide` 的最大公约数 $x$。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: @@ -77,26 +71,6 @@ class Solution: return -1 ``` -```python -class Solution: - def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: - x = gcd(*numsDivide) - nums.sort() - return next((i for i, v in enumerate(nums) if x % v == 0), -1) -``` - -```python -class Solution: - def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: - x = gcd(*numsDivide) - y = min((v for v in nums if x % v == 0), default=0) - return sum(v < y for v in nums) if y else -1 -``` - -### **Java** - - - ```java class Solution { public int minOperations(int[] nums, int[] numsDivide) { @@ -119,6 +93,62 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minOperations(vector& nums, vector& numsDivide) { + int x = 0; + for (int& v : numsDivide) { + x = gcd(x, v); + } + sort(nums.begin(), nums.end()); + for (int i = 0; i < nums.size(); ++i) { + if (x % nums[i] == 0) { + return i; + } + } + return -1; + } +}; +``` + +```go +func minOperations(nums []int, numsDivide []int) int { + x := 0 + for _, v := range numsDivide { + x = gcd(x, v) + } + sort.Ints(nums) + for i, v := range nums { + if x%v == 0 { + return i + } + } + return -1 +} + +func gcd(a, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) +} +``` + + + +### 方法二 + + + +```python +class Solution: + def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: + x = gcd(*numsDivide) + nums.sort() + return next((i for i, v in enumerate(nums) if x % v == 0), -1) +``` + ```java class Solution { public int minOperations(int[] nums, int[] numsDivide) { @@ -150,27 +180,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minOperations(vector& nums, vector& numsDivide) { - int x = 0; - for (int& v : numsDivide) { - x = gcd(x, v); - } - sort(nums.begin(), nums.end()); - for (int i = 0; i < nums.size(); ++i) { - if (x % nums[i] == 0) { - return i; - } - } - return -1; - } -}; -``` - ```cpp class Solution { public: @@ -197,31 +206,6 @@ public: }; ``` -### **Go** - -```go -func minOperations(nums []int, numsDivide []int) int { - x := 0 - for _, v := range numsDivide { - x = gcd(x, v) - } - sort.Ints(nums) - for i, v := range nums { - if x%v == 0 { - return i - } - } - return -1 -} - -func gcd(a, b int) int { - if b == 0 { - return a - } - return gcd(b, a%b) -} -``` - ```go func minOperations(nums []int, numsDivide []int) int { x := 0 @@ -254,16 +238,20 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - -```ts - -``` + -### **...** +### 方法三 -``` + +```python +class Solution: + def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: + x = gcd(*numsDivide) + y = min((v for v in nums if x % v == 0), default=0) + return sum(v < y for v in nums) if y else -1 ``` + + diff --git a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/README_EN.md b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/README_EN.md index b151dab5c4643..9381c3ad53efd 100644 --- a/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/README_EN.md +++ b/solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/README_EN.md @@ -42,9 +42,9 @@ There is no way to delete elements from nums to allow this. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,24 +59,6 @@ class Solution: return -1 ``` -```python -class Solution: - def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: - x = gcd(*numsDivide) - nums.sort() - return next((i for i, v in enumerate(nums) if x % v == 0), -1) -``` - -```python -class Solution: - def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: - x = gcd(*numsDivide) - y = min((v for v in nums if x % v == 0), default=0) - return sum(v < y for v in nums) if y else -1 -``` - -### **Java** - ```java class Solution { public int minOperations(int[] nums, int[] numsDivide) { @@ -99,6 +81,62 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minOperations(vector& nums, vector& numsDivide) { + int x = 0; + for (int& v : numsDivide) { + x = gcd(x, v); + } + sort(nums.begin(), nums.end()); + for (int i = 0; i < nums.size(); ++i) { + if (x % nums[i] == 0) { + return i; + } + } + return -1; + } +}; +``` + +```go +func minOperations(nums []int, numsDivide []int) int { + x := 0 + for _, v := range numsDivide { + x = gcd(x, v) + } + sort.Ints(nums) + for i, v := range nums { + if x%v == 0 { + return i + } + } + return -1 +} + +func gcd(a, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: + x = gcd(*numsDivide) + nums.sort() + return next((i for i, v in enumerate(nums) if x % v == 0), -1) +``` + ```java class Solution { public int minOperations(int[] nums, int[] numsDivide) { @@ -130,27 +168,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minOperations(vector& nums, vector& numsDivide) { - int x = 0; - for (int& v : numsDivide) { - x = gcd(x, v); - } - sort(nums.begin(), nums.end()); - for (int i = 0; i < nums.size(); ++i) { - if (x % nums[i] == 0) { - return i; - } - } - return -1; - } -}; -``` - ```cpp class Solution { public: @@ -177,31 +194,6 @@ public: }; ``` -### **Go** - -```go -func minOperations(nums []int, numsDivide []int) int { - x := 0 - for _, v := range numsDivide { - x = gcd(x, v) - } - sort.Ints(nums) - for i, v := range nums { - if x%v == 0 { - return i - } - } - return -1 -} - -func gcd(a, b int) int { - if b == 0 { - return a - } - return gcd(b, a%b) -} -``` - ```go func minOperations(nums []int, numsDivide []int) int { x := 0 @@ -234,16 +226,20 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - -```ts - -``` + -### **...** +### Solution 3 -``` + +```python +class Solution: + def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: + x = gcd(*numsDivide) + y = min((v for v in nums if x % v == 0), default=0) + return sum(v < y for v in nums) if y else -1 ``` + + diff --git a/solution/2300-2399/2345.Finding the Number of Visible Mountains/README.md b/solution/2300-2399/2345.Finding the Number of Visible Mountains/README.md index 5bf550c27e2f3..33803abe97951 100644 --- a/solution/2300-2399/2345.Finding the Number of Visible Mountains/README.md +++ b/solution/2300-2399/2345.Finding the Number of Visible Mountains/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:区间排序 + 遍历** +### 方法一:区间排序 + 遍历 我们先将每座山 $(x, y)$ 转换成横坐标的区间 $(x - y, x + y)$,然后对区间按照左端点升序排序,右端点降序排序。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def visibleMountains(self, peaks: List[List[int]]) -> int: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int visibleMountains(int[][] peaks) { @@ -113,35 +103,6 @@ class Solution { } ``` -```java -class Solution { - public int visibleMountains(int[][] peaks) { - int n = peaks.length; - int[][] arr = new int[n][2]; - for (int i = 0; i < n; ++i) { - int x = peaks[i][0], y = peaks[i][1]; - arr[i] = new int[] {x - y, x + y}; - } - Arrays.sort(arr, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); - int ans = 0; - int cur = Integer.MIN_VALUE; - for (int i = 0; i < n; ++i) { - int l = arr[i][0], r = arr[i][1]; - if (r <= cur) { - continue; - } - cur = r; - if (!(i < n - 1 && arr[i][0] == arr[i + 1][0] && arr[i][1] == arr[i + 1][1])) { - ++ans; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -167,8 +128,6 @@ public: }; ``` -### **Go** - ```go func visibleMountains(peaks [][]int) (ans int) { n := len(peaks) @@ -194,16 +153,39 @@ func visibleMountains(peaks [][]int) (ans int) { } ``` -### **TypeScript** - -```ts - -``` + -### **...** +### 方法二 -``` + +```java +class Solution { + public int visibleMountains(int[][] peaks) { + int n = peaks.length; + int[][] arr = new int[n][2]; + for (int i = 0; i < n; ++i) { + int x = peaks[i][0], y = peaks[i][1]; + arr[i] = new int[] {x - y, x + y}; + } + Arrays.sort(arr, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); + int ans = 0; + int cur = Integer.MIN_VALUE; + for (int i = 0; i < n; ++i) { + int l = arr[i][0], r = arr[i][1]; + if (r <= cur) { + continue; + } + cur = r; + if (!(i < n - 1 && arr[i][0] == arr[i + 1][0] && arr[i][1] == arr[i + 1][1])) { + ++ans; + } + } + return ans; + } +} ``` + + diff --git a/solution/2300-2399/2345.Finding the Number of Visible Mountains/README_EN.md b/solution/2300-2399/2345.Finding the Number of Visible Mountains/README_EN.md index b73b086e0d951..7e860c81a90b5 100644 --- a/solution/2300-2399/2345.Finding the Number of Visible Mountains/README_EN.md +++ b/solution/2300-2399/2345.Finding the Number of Visible Mountains/README_EN.md @@ -42,9 +42,9 @@ Both mountains are not visible since their peaks lie within each other. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int visibleMountains(int[][] peaks) { @@ -93,35 +91,6 @@ class Solution { } ``` -```java -class Solution { - public int visibleMountains(int[][] peaks) { - int n = peaks.length; - int[][] arr = new int[n][2]; - for (int i = 0; i < n; ++i) { - int x = peaks[i][0], y = peaks[i][1]; - arr[i] = new int[] {x - y, x + y}; - } - Arrays.sort(arr, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); - int ans = 0; - int cur = Integer.MIN_VALUE; - for (int i = 0; i < n; ++i) { - int l = arr[i][0], r = arr[i][1]; - if (r <= cur) { - continue; - } - cur = r; - if (!(i < n - 1 && arr[i][0] == arr[i + 1][0] && arr[i][1] == arr[i + 1][1])) { - ++ans; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -147,8 +116,6 @@ public: }; ``` -### **Go** - ```go func visibleMountains(peaks [][]int) (ans int) { n := len(peaks) @@ -174,16 +141,39 @@ func visibleMountains(peaks [][]int) (ans int) { } ``` -### **TypeScript** - -```ts - -``` + -### **...** +### Solution 2 -``` + +```java +class Solution { + public int visibleMountains(int[][] peaks) { + int n = peaks.length; + int[][] arr = new int[n][2]; + for (int i = 0; i < n; ++i) { + int x = peaks[i][0], y = peaks[i][1]; + arr[i] = new int[] {x - y, x + y}; + } + Arrays.sort(arr, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); + int ans = 0; + int cur = Integer.MIN_VALUE; + for (int i = 0; i < n; ++i) { + int l = arr[i][0], r = arr[i][1]; + if (r <= cur) { + continue; + } + cur = r; + if (!(i < n - 1 && arr[i][0] == arr[i + 1][0] && arr[i][1] == arr[i + 1][1])) { + ++ans; + } + } + return ans; + } +} ``` + + diff --git a/solution/2300-2399/2346.Compute the Rank as a Percentage/README.md b/solution/2300-2399/2346.Compute the Rank as a Percentage/README.md index ab8f66e25b616..2fe3c067f5f3b 100644 --- a/solution/2300-2399/2346.Compute the Rank as a Percentage/README.md +++ b/solution/2300-2399/2346.Compute the Rank as a Percentage/README.md @@ -70,18 +70,12 @@ Students 表: ## 解法 - - -**方法一:窗口函数** +### 方法一:窗口函数 注意空值判断。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -103,3 +97,5 @@ FROM Students; ``` + + diff --git a/solution/2300-2399/2346.Compute the Rank as a Percentage/README_EN.md b/solution/2300-2399/2346.Compute the Rank as a Percentage/README_EN.md index 19a74206cda29..2fcf5e4a6dd36 100644 --- a/solution/2300-2399/2346.Compute the Rank as a Percentage/README_EN.md +++ b/solution/2300-2399/2346.Compute the Rank as a Percentage/README_EN.md @@ -63,9 +63,9 @@ For Department 2: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -88,3 +88,5 @@ FROM Students; ``` + + diff --git a/solution/2300-2399/2347.Best Poker Hand/README.md b/solution/2300-2399/2347.Best Poker Hand/README.md index 9480c1d760de1..f1fc2ade80da9 100644 --- a/solution/2300-2399/2347.Best Poker Hand/README.md +++ b/solution/2300-2399/2347.Best Poker Hand/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们可以先遍历数组 $suits$,判断相邻两个元素是否均相等,如果是,则返回 `"Flush"`。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def bestHand(self, ranks: List[int], suits: List[str]) -> str: @@ -93,10 +87,6 @@ class Solution: return 'High Card' ``` -### **Java** - - - ```java class Solution { public String bestHand(int[] ranks, char[] suits) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func bestHand(ranks []int, suits []byte) string { flush := true @@ -173,8 +159,6 @@ func bestHand(ranks []int, suits []byte) string { } ``` -### **TypeScript** - ```ts function bestHand(ranks: number[], suits: string[]): string { if (suits.every(v => v === suits[0])) { @@ -195,8 +179,6 @@ function bestHand(ranks: number[], suits: string[]): string { } ``` -### **Rust** - ```rust impl Solution { pub fn best_hand(ranks: Vec, suits: Vec) -> String { @@ -218,8 +200,6 @@ impl Solution { } ``` -### **C** - ```c char* bestHand(int* ranks, int ranksSize, char* suits, int suitsSize) { bool isFlush = true; @@ -247,10 +227,6 @@ char* bestHand(int* ranks, int ranksSize, char* suits, int suitsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2347.Best Poker Hand/README_EN.md b/solution/2300-2399/2347.Best Poker Hand/README_EN.md index 2f98489aa37db..82ef0928b3717 100644 --- a/solution/2300-2399/2347.Best Poker Hand/README_EN.md +++ b/solution/2300-2399/2347.Best Poker Hand/README_EN.md @@ -58,9 +58,9 @@ Note that we cannot make a "Flush" or a "Three of a Kind". ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return 'High Card' ``` -### **Java** - ```java class Solution { public String bestHand(int[] ranks, char[] suits) { @@ -101,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +123,6 @@ public: }; ``` -### **Go** - ```go func bestHand(ranks []int, suits []byte) string { flush := true @@ -154,8 +148,6 @@ func bestHand(ranks []int, suits []byte) string { } ``` -### **TypeScript** - ```ts function bestHand(ranks: number[], suits: string[]): string { if (suits.every(v => v === suits[0])) { @@ -176,8 +168,6 @@ function bestHand(ranks: number[], suits: string[]): string { } ``` -### **Rust** - ```rust impl Solution { pub fn best_hand(ranks: Vec, suits: Vec) -> String { @@ -199,8 +189,6 @@ impl Solution { } ``` -### **C** - ```c char* bestHand(int* ranks, int ranksSize, char* suits, int suitsSize) { bool isFlush = true; @@ -228,10 +216,6 @@ char* bestHand(int* ranks, int ranksSize, char* suits, int suitsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2348.Number of Zero-Filled Subarrays/README.md b/solution/2300-2399/2348.Number of Zero-Filled Subarrays/README.md index 873da5206c7ca..69ddc3db6b3ad 100644 --- a/solution/2300-2399/2348.Number of Zero-Filled Subarrays/README.md +++ b/solution/2300-2399/2348.Number of Zero-Filled Subarrays/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:遍历计数** +### 方法一:遍历计数 我们可以遍历数组 `nums`,用变量 $cnt$ 记录当前连续的 `0` 的个数,用变量 $ans$ 记录答案。当遍历到 `nums[i]` 时,如果 `nums[i]` 为 `0`,则 $cnt$ 自增 $1$,否则 $cnt$ 置 $0$。然后将 $cnt$ 累加到答案 $ans$ 中。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def zeroFilledSubarray(self, nums: List[int]) -> int: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long zeroFilledSubarray(int[] nums) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func zeroFilledSubarray(nums []int) (ans int64) { cnt := 0 @@ -133,8 +119,6 @@ func zeroFilledSubarray(nums []int) (ans int64) { } ``` -### **TypeScript** - ```ts function zeroFilledSubarray(nums: number[]): number { let ans = 0; @@ -147,10 +131,6 @@ function zeroFilledSubarray(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2348.Number of Zero-Filled Subarrays/README_EN.md b/solution/2300-2399/2348.Number of Zero-Filled Subarrays/README_EN.md index fe2a9640efaf7..f9128c51e595a 100644 --- a/solution/2300-2399/2348.Number of Zero-Filled Subarrays/README_EN.md +++ b/solution/2300-2399/2348.Number of Zero-Filled Subarrays/README_EN.md @@ -49,9 +49,9 @@ There is no occurrence of a subarray with a size more than 3 filled with 0. Ther ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long zeroFilledSubarray(int[] nums) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func zeroFilledSubarray(nums []int) (ans int64) { cnt := 0 @@ -113,8 +107,6 @@ func zeroFilledSubarray(nums []int) (ans int64) { } ``` -### **TypeScript** - ```ts function zeroFilledSubarray(nums: number[]): number { let ans = 0; @@ -127,10 +119,6 @@ function zeroFilledSubarray(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2349.Design a Number Container System/README.md b/solution/2300-2399/2349.Design a Number Container System/README.md index f14eb5e51e148..042b0da13f3cd 100644 --- a/solution/2300-2399/2349.Design a Number Container System/README.md +++ b/solution/2300-2399/2349.Design a Number Container System/README.md @@ -55,16 +55,10 @@ nc.find(10); // 数字 10 所在下标为 2 ,3 和 5 。最小下标为 2 , ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 -### **Python3** - - - ```python from sortedcontainers import SortedSet @@ -92,10 +86,6 @@ class NumberContainers: # param_2 = obj.find(number) ``` -### **Java** - - - ```java class NumberContainers { private Map mp = new HashMap<>(); @@ -129,8 +119,6 @@ class NumberContainers { */ ``` -### **C++** - ```cpp class NumberContainers { public: @@ -164,8 +152,6 @@ public: */ ``` -### **Go** - ```go type NumberContainers struct { mp map[int]int @@ -203,16 +189,6 @@ func (this *NumberContainers) Find(number int) int { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2349.Design a Number Container System/README_EN.md b/solution/2300-2399/2349.Design a Number Container System/README_EN.md index 33a89148d4f22..a3f892d9043f3 100644 --- a/solution/2300-2399/2349.Design a Number Container System/README_EN.md +++ b/solution/2300-2399/2349.Design a Number Container System/README_EN.md @@ -51,9 +51,9 @@ nc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedSet @@ -82,8 +82,6 @@ class NumberContainers: # param_2 = obj.find(number) ``` -### **Java** - ```java class NumberContainers { private Map mp = new HashMap<>(); @@ -117,8 +115,6 @@ class NumberContainers { */ ``` -### **C++** - ```cpp class NumberContainers { public: @@ -152,8 +148,6 @@ public: */ ``` -### **Go** - ```go type NumberContainers struct { mp map[int]int @@ -191,16 +185,6 @@ func (this *NumberContainers) Find(number int) int { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2350.Shortest Impossible Sequence of Rolls/README.md b/solution/2300-2399/2350.Shortest Impossible Sequence of Rolls/README.md index 91f671faaeb2c..8b725bae9bd9a 100644 --- a/solution/2300-2399/2350.Shortest Impossible Sequence of Rolls/README.md +++ b/solution/2300-2399/2350.Shortest Impossible Sequence of Rolls/README.md @@ -57,18 +57,12 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 时间复杂度 $O(n)$。 -### **Python3** - - - ```python class Solution: def shortestSequence(self, rolls: List[int], k: int) -> int: @@ -82,10 +76,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int shortestSequence(int[] rolls, int k) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func shortestSequence(rolls []int, k int) int { s := map[int]bool{} @@ -140,16 +126,6 @@ func shortestSequence(rolls []int, k int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2350.Shortest Impossible Sequence of Rolls/README_EN.md b/solution/2300-2399/2350.Shortest Impossible Sequence of Rolls/README_EN.md index 8e6719d77bdee..ea90a0e223aa8 100644 --- a/solution/2300-2399/2350.Shortest Impossible Sequence of Rolls/README_EN.md +++ b/solution/2300-2399/2350.Shortest Impossible Sequence of Rolls/README_EN.md @@ -53,9 +53,9 @@ Note that there are other sequences that cannot be taken from rolls but [4] is t ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int shortestSequence(int[] rolls, int k) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +105,6 @@ public: }; ``` -### **Go** - ```go func shortestSequence(rolls []int, k int) int { s := map[int]bool{} @@ -126,16 +120,6 @@ func shortestSequence(rolls []int, k int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/README.md b/solution/2300-2399/2351.First Letter to Appear Twice/README.md index dd204ab527dac..7e6637764f68e 100644 --- a/solution/2300-2399/2351.First Letter to Appear Twice/README.md +++ b/solution/2300-2399/2351.First Letter to Appear Twice/README.md @@ -49,26 +49,14 @@ ## 解法 - - -**方法一:数组或哈希表** +### 方法一:数组或哈希表 遍历字符串 $s$,用数组或哈希表 `cnt` 记录每个字母出现的次数,当某个字母出现两次时,返回该字母。 时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 为字符串 $s$ 的长度,而 $C$ 为字符集大小。本题中 $C = 26$。 -**方法二:位运算** - -我们也可以用一个整数 `mask` 记录每个字母是否出现过,其中 `mask` 的第 $i$ 位表示第 $i$ 个字母是否出现过。当某个字母出现两次时,返回该字母。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。 - -### **Python3** - - - ```python class Solution: def repeatedCharacter(self, s: str) -> str: @@ -79,21 +67,6 @@ class Solution: return c ``` -```python -class Solution: - def repeatedCharacter(self, s: str) -> str: - mask = 0 - for c in s: - i = ord(c) - ord('a') - if mask >> i & 1: - return c - mask |= 1 << i -``` - -### **Java** - - - ```java class Solution { public char repeatedCharacter(String s) { @@ -108,23 +81,6 @@ class Solution { } ``` -```java -class Solution { - public char repeatedCharacter(String s) { - int mask = 0; - for (int i = 0;; ++i) { - char c = s.charAt(i); - if ((mask >> (c - 'a') & 1) == 1) { - return c; - } - mask |= 1 << (c - 'a'); - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -139,23 +95,6 @@ public: }; ``` -```cpp -class Solution { -public: - char repeatedCharacter(string s) { - int mask = 0; - for (int i = 0;; ++i) { - if (mask >> (s[i] - 'a') & 1) { - return s[i]; - } - mask |= 1 << (s[i] - 'a'); - } - } -}; -``` - -### **Go** - ```go func repeatedCharacter(s string) byte { cnt := [26]int{} @@ -168,20 +107,6 @@ func repeatedCharacter(s string) byte { } ``` -```go -func repeatedCharacter(s string) byte { - mask := 0 - for i := 0; ; i++ { - if mask>>(s[i]-'a')&1 == 1 { - return s[i] - } - mask |= 1 << (s[i] - 'a') - } -} -``` - -### **TypeScript** - ```ts function repeatedCharacter(s: string): string { const vis = new Array(26).fill(false); @@ -196,22 +121,6 @@ function repeatedCharacter(s: string): string { } ``` -```ts -function repeatedCharacter(s: string): string { - let mask = 0; - for (const c of s) { - const i = c.charCodeAt(0) - 'a'.charCodeAt(0); - if (mask & (1 << i)) { - return c; - } - mask |= 1 << i; - } - return ' '; -} -``` - -### **Rust** - ```rust impl Solution { pub fn repeated_character(s: String) -> char { @@ -227,23 +136,23 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn repeated_character(s: String) -> char { - let mut mask = 0; - for &c in s.as_bytes() { - if (mask & (1 << ((c - b'a') as i32))) != 0 { - return c as char; +```php +class Solution { + /** + * @param String $s + * @return String + */ + function repeatedCharacter($s) { + for ($i = 0; ; $i++) { + $hashtable[$s[$i]] += 1; + if ($hashtable[$s[$i]] == 2) { + return $s[$i]; } - mask |= 1 << ((c - b'a') as i32); } - ' ' } } ``` -### **C** - ```c char repeatedCharacter(char* s) { int vis[26] = {0}; @@ -257,42 +166,111 @@ char repeatedCharacter(char* s) { } ``` -```c -char repeatedCharacter(char* s) { - int mask = 0; - for (int i = 0; s[i]; i++) { - if (mask & (1 << s[i] - 'a')) { - return s[i]; + + +### 方法二:位运算 + +我们也可以用一个整数 `mask` 记录每个字母是否出现过,其中 `mask` 的第 $i$ 位表示第 $i$ 个字母是否出现过。当某个字母出现两次时,返回该字母。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。 + + + +```python +class Solution: + def repeatedCharacter(self, s: str) -> str: + mask = 0 + for c in s: + i = ord(c) - ord('a') + if mask >> i & 1: + return c + mask |= 1 << i +``` + +```java +class Solution { + public char repeatedCharacter(String s) { + int mask = 0; + for (int i = 0;; ++i) { + char c = s.charAt(i); + if ((mask >> (c - 'a') & 1) == 1) { + return c; + } + mask |= 1 << (c - 'a'); } - mask |= 1 << s[i] - 'a'; } - return ' '; } ``` -### **PHP** - -```php +```cpp class Solution { - /** - * @param String $s - * @return String - */ - function repeatedCharacter($s) { - for ($i = 0; ; $i++) { - $hashtable[$s[$i]] += 1; - if ($hashtable[$s[$i]] == 2) { - return $s[$i]; +public: + char repeatedCharacter(string s) { + int mask = 0; + for (int i = 0;; ++i) { + if (mask >> (s[i] - 'a') & 1) { + return s[i]; } + mask |= 1 << (s[i] - 'a'); } } +}; +``` + +```go +func repeatedCharacter(s string) byte { + mask := 0 + for i := 0; ; i++ { + if mask>>(s[i]-'a')&1 == 1 { + return s[i] + } + mask |= 1 << (s[i] - 'a') + } } ``` -### **...** +```ts +function repeatedCharacter(s: string): string { + let mask = 0; + for (const c of s) { + const i = c.charCodeAt(0) - 'a'.charCodeAt(0); + if (mask & (1 << i)) { + return c; + } + mask |= 1 << i; + } + return ' '; +} +``` +```rust +impl Solution { + pub fn repeated_character(s: String) -> char { + let mut mask = 0; + for &c in s.as_bytes() { + if (mask & (1 << ((c - b'a') as i32))) != 0 { + return c as char; + } + mask |= 1 << ((c - b'a') as i32); + } + ' ' + } +} ``` +```c +char repeatedCharacter(char* s) { + int mask = 0; + for (int i = 0; s[i]; i++) { + if (mask & (1 << s[i] - 'a')) { + return s[i]; + } + mask |= 1 << s[i] - 'a'; + } + return ' '; +} ``` + + diff --git a/solution/2300-2399/2351.First Letter to Appear Twice/README_EN.md b/solution/2300-2399/2351.First Letter to Appear Twice/README_EN.md index 5f1375f659af9..7e4eb152ca3b4 100644 --- a/solution/2300-2399/2351.First Letter to Appear Twice/README_EN.md +++ b/solution/2300-2399/2351.First Letter to Appear Twice/README_EN.md @@ -47,9 +47,9 @@ The only letter that appears twice is 'd' so we return 'd'. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,19 +61,6 @@ class Solution: return c ``` -```python -class Solution: - def repeatedCharacter(self, s: str) -> str: - mask = 0 - for c in s: - i = ord(c) - ord('a') - if mask >> i & 1: - return c - mask |= 1 << i -``` - -### **Java** - ```java class Solution { public char repeatedCharacter(String s) { @@ -88,23 +75,6 @@ class Solution { } ``` -```java -class Solution { - public char repeatedCharacter(String s) { - int mask = 0; - for (int i = 0;; ++i) { - char c = s.charAt(i); - if ((mask >> (c - 'a') & 1) == 1) { - return c; - } - mask |= 1 << (c - 'a'); - } - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -119,23 +89,6 @@ public: }; ``` -```cpp -class Solution { -public: - char repeatedCharacter(string s) { - int mask = 0; - for (int i = 0;; ++i) { - if (mask >> (s[i] - 'a') & 1) { - return s[i]; - } - mask |= 1 << (s[i] - 'a'); - } - } -}; -``` - -### **Go** - ```go func repeatedCharacter(s string) byte { cnt := [26]int{} @@ -148,20 +101,6 @@ func repeatedCharacter(s string) byte { } ``` -```go -func repeatedCharacter(s string) byte { - mask := 0 - for i := 0; ; i++ { - if mask>>(s[i]-'a')&1 == 1 { - return s[i] - } - mask |= 1 << (s[i] - 'a') - } -} -``` - -### **TypeScript** - ```ts function repeatedCharacter(s: string): string { const vis = new Array(26).fill(false); @@ -176,22 +115,6 @@ function repeatedCharacter(s: string): string { } ``` -```ts -function repeatedCharacter(s: string): string { - let mask = 0; - for (const c of s) { - const i = c.charCodeAt(0) - 'a'.charCodeAt(0); - if (mask & (1 << i)) { - return c; - } - mask |= 1 << i; - } - return ' '; -} -``` - -### **Rust** - ```rust impl Solution { pub fn repeated_character(s: String) -> char { @@ -207,23 +130,23 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn repeated_character(s: String) -> char { - let mut mask = 0; - for &c in s.as_bytes() { - if (mask & (1 << ((c - b'a') as i32))) != 0 { - return c as char; +```php +class Solution { + /** + * @param String $s + * @return String + */ + function repeatedCharacter($s) { + for ($i = 0; ; $i++) { + $hashtable[$s[$i]] += 1; + if ($hashtable[$s[$i]] == 2) { + return $s[$i]; } - mask |= 1 << ((c - b'a') as i32); } - ' ' } } ``` -### **C** - ```c char repeatedCharacter(char* s) { int vis[26] = {0}; @@ -237,42 +160,107 @@ char repeatedCharacter(char* s) { } ``` -```c -char repeatedCharacter(char* s) { - int mask = 0; - for (int i = 0; s[i]; i++) { - if (mask & (1 << s[i] - 'a')) { - return s[i]; + + +### Solution 2 + + + +```python +class Solution: + def repeatedCharacter(self, s: str) -> str: + mask = 0 + for c in s: + i = ord(c) - ord('a') + if mask >> i & 1: + return c + mask |= 1 << i +``` + +```java +class Solution { + public char repeatedCharacter(String s) { + int mask = 0; + for (int i = 0;; ++i) { + char c = s.charAt(i); + if ((mask >> (c - 'a') & 1) == 1) { + return c; + } + mask |= 1 << (c - 'a'); } - mask |= 1 << s[i] - 'a'; } - return ' '; } ``` -### **PHP** - -```php +```cpp class Solution { - /** - * @param String $s - * @return String - */ - function repeatedCharacter($s) { - for ($i = 0; ; $i++) { - $hashtable[$s[$i]] += 1; - if ($hashtable[$s[$i]] == 2) { - return $s[$i]; +public: + char repeatedCharacter(string s) { + int mask = 0; + for (int i = 0;; ++i) { + if (mask >> (s[i] - 'a') & 1) { + return s[i]; } + mask |= 1 << (s[i] - 'a'); } } +}; +``` + +```go +func repeatedCharacter(s string) byte { + mask := 0 + for i := 0; ; i++ { + if mask>>(s[i]-'a')&1 == 1 { + return s[i] + } + mask |= 1 << (s[i] - 'a') + } } ``` -### **...** +```ts +function repeatedCharacter(s: string): string { + let mask = 0; + for (const c of s) { + const i = c.charCodeAt(0) - 'a'.charCodeAt(0); + if (mask & (1 << i)) { + return c; + } + mask |= 1 << i; + } + return ' '; +} +``` +```rust +impl Solution { + pub fn repeated_character(s: String) -> char { + let mut mask = 0; + for &c in s.as_bytes() { + if (mask & (1 << ((c - b'a') as i32))) != 0 { + return c as char; + } + mask |= 1 << ((c - b'a') as i32); + } + ' ' + } +} ``` +```c +char repeatedCharacter(char* s) { + int mask = 0; + for (int i = 0; s[i]; i++) { + if (mask & (1 << s[i] - 'a')) { + return s[i]; + } + mask |= 1 << s[i] - 'a'; + } + return ' '; +} ``` + + diff --git a/solution/2300-2399/2352.Equal Row and Column Pairs/README.md b/solution/2300-2399/2352.Equal Row and Column Pairs/README.md index c116f0f61d500..b8a8b260ed38c 100644 --- a/solution/2300-2399/2352.Equal Row and Column Pairs/README.md +++ b/solution/2300-2399/2352.Equal Row and Column Pairs/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们直接将矩阵 $grid$ 的每一行和每一列进行比较,如果相等,那么就是一对相等行列对,答案加一。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def equalPairs(self, grid: List[List[int]]) -> int: @@ -69,21 +63,6 @@ class Solution: return sum(row == col for row in grid for col in g) ``` -```python -class Solution: - def equalPairs(self, grid: List[List[int]]) -> int: - n = len(grid) - ans = 0 - for i in range(n): - for j in range(n): - ans += all(grid[i][k] == grid[k][j] for k in range(n)) - return ans -``` - -### **Java** - - - ```java class Solution { public int equalPairs(int[][] grid) { @@ -112,30 +91,6 @@ class Solution { } ``` -```java -class Solution { - public int equalPairs(int[][] grid) { - int n = grid.length; - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - int ok = 1; - for (int k = 0; k < n; ++k) { - if (grid[i][k] != grid[k][j]) { - ok = 0; - break; - } - } - ans += ok; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -158,31 +113,6 @@ public: }; ``` -```cpp -class Solution { -public: - int equalPairs(vector>& grid) { - int n = grid.size(); - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - int ok = 1; - for (int k = 0; k < n; ++k) { - if (grid[i][k] != grid[k][j]) { - ok = 0; - break; - } - } - ans += ok; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func equalPairs(grid [][]int) (ans int) { n := len(grid) @@ -209,26 +139,6 @@ func equalPairs(grid [][]int) (ans int) { } ``` -```go -func equalPairs(grid [][]int) (ans int) { - for i := range grid { - for j := range grid { - ok := 1 - for k := range grid { - if grid[i][k] != grid[k][j] { - ok = 0 - break - } - } - ans += ok - } - } - return -} -``` - -### **TypeScript** - ```ts function equalPairs(grid: number[][]): number { const n = grid.length; @@ -248,6 +158,86 @@ function equalPairs(grid: number[][]): number { } ``` + + +### 方法二 + + + +```python +class Solution: + def equalPairs(self, grid: List[List[int]]) -> int: + n = len(grid) + ans = 0 + for i in range(n): + for j in range(n): + ans += all(grid[i][k] == grid[k][j] for k in range(n)) + return ans +``` + +```java +class Solution { + public int equalPairs(int[][] grid) { + int n = grid.length; + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + int ok = 1; + for (int k = 0; k < n; ++k) { + if (grid[i][k] != grid[k][j]) { + ok = 0; + break; + } + } + ans += ok; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int equalPairs(vector>& grid) { + int n = grid.size(); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + int ok = 1; + for (int k = 0; k < n; ++k) { + if (grid[i][k] != grid[k][j]) { + ok = 0; + break; + } + } + ans += ok; + } + } + return ans; + } +}; +``` + +```go +func equalPairs(grid [][]int) (ans int) { + for i := range grid { + for j := range grid { + ok := 1 + for k := range grid { + if grid[i][k] != grid[k][j] { + ok = 0 + break + } + } + ans += ok + } + } + return +} +``` + ```ts function equalPairs(grid: number[][]): number { const n = grid.length; @@ -268,10 +258,6 @@ function equalPairs(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2352.Equal Row and Column Pairs/README_EN.md b/solution/2300-2399/2352.Equal Row and Column Pairs/README_EN.md index 87082d581549e..fd56c7407ced4 100644 --- a/solution/2300-2399/2352.Equal Row and Column Pairs/README_EN.md +++ b/solution/2300-2399/2352.Equal Row and Column Pairs/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,19 +51,6 @@ class Solution: return sum(row == col for row in grid for col in g) ``` -```python -class Solution: - def equalPairs(self, grid: List[List[int]]) -> int: - n = len(grid) - ans = 0 - for i in range(n): - for j in range(n): - ans += all(grid[i][k] == grid[k][j] for k in range(n)) - return ans -``` - -### **Java** - ```java class Solution { public int equalPairs(int[][] grid) { @@ -92,30 +79,6 @@ class Solution { } ``` -```java -class Solution { - public int equalPairs(int[][] grid) { - int n = grid.length; - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - int ok = 1; - for (int k = 0; k < n; ++k) { - if (grid[i][k] != grid[k][j]) { - ok = 0; - break; - } - } - ans += ok; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -138,31 +101,6 @@ public: }; ``` -```cpp -class Solution { -public: - int equalPairs(vector>& grid) { - int n = grid.size(); - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n; ++j) { - int ok = 1; - for (int k = 0; k < n; ++k) { - if (grid[i][k] != grid[k][j]) { - ok = 0; - break; - } - } - ans += ok; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func equalPairs(grid [][]int) (ans int) { n := len(grid) @@ -189,26 +127,6 @@ func equalPairs(grid [][]int) (ans int) { } ``` -```go -func equalPairs(grid [][]int) (ans int) { - for i := range grid { - for j := range grid { - ok := 1 - for k := range grid { - if grid[i][k] != grid[k][j] { - ok = 0 - break - } - } - ans += ok - } - } - return -} -``` - -### **TypeScript** - ```ts function equalPairs(grid: number[][]): number { const n = grid.length; @@ -228,6 +146,86 @@ function equalPairs(grid: number[][]): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def equalPairs(self, grid: List[List[int]]) -> int: + n = len(grid) + ans = 0 + for i in range(n): + for j in range(n): + ans += all(grid[i][k] == grid[k][j] for k in range(n)) + return ans +``` + +```java +class Solution { + public int equalPairs(int[][] grid) { + int n = grid.length; + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + int ok = 1; + for (int k = 0; k < n; ++k) { + if (grid[i][k] != grid[k][j]) { + ok = 0; + break; + } + } + ans += ok; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int equalPairs(vector>& grid) { + int n = grid.size(); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { + int ok = 1; + for (int k = 0; k < n; ++k) { + if (grid[i][k] != grid[k][j]) { + ok = 0; + break; + } + } + ans += ok; + } + } + return ans; + } +}; +``` + +```go +func equalPairs(grid [][]int) (ans int) { + for i := range grid { + for j := range grid { + ok := 1 + for k := range grid { + if grid[i][k] != grid[k][j] { + ok = 0 + break + } + } + ans += ok + } + } + return +} +``` + ```ts function equalPairs(grid: number[][]): number { const n = grid.length; @@ -248,10 +246,6 @@ function equalPairs(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2353.Design a Food Rating System/README.md b/solution/2300-2399/2353.Design a Food Rating System/README.md index dadd97e62bffa..6071a92fc0010 100644 --- a/solution/2300-2399/2353.Design a Food Rating System/README.md +++ b/solution/2300-2399/2353.Design a Food Rating System/README.md @@ -72,14 +72,10 @@ foodRatings.highestRated("japanese"); // 返回 "ramen" ## 解法 - +### 方法一 -### **Python3** - - - ```python from sortedcontainers import SortedSet @@ -109,16 +105,6 @@ class FoodRatings: # param_2 = obj.highestRated(cuisine) ``` -### **Java** - - - -```java - -``` - -### **C++** - ```cpp using pis = pair; @@ -157,16 +143,6 @@ public: */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2353.Design a Food Rating System/README_EN.md b/solution/2300-2399/2353.Design a Food Rating System/README_EN.md index 85a9b90a310ad..a062b902de69a 100644 --- a/solution/2300-2399/2353.Design a Food Rating System/README_EN.md +++ b/solution/2300-2399/2353.Design a Food Rating System/README_EN.md @@ -69,9 +69,9 @@ foodRatings.highestRated("japanese"); // return "ramen" ## Solutions - +### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedSet @@ -102,14 +102,6 @@ class FoodRatings: # param_2 = obj.highestRated(cuisine) ``` -### **Java** - -```java - -``` - -### **C++** - ```cpp using pis = pair; @@ -148,16 +140,6 @@ public: */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2354.Number of Excellent Pairs/README.md b/solution/2300-2399/2354.Number of Excellent Pairs/README.md index 3857b641f61e4..03a58cdcf533e 100644 --- a/solution/2300-2399/2354.Number of Excellent Pairs/README.md +++ b/solution/2300-2399/2354.Number of Excellent Pairs/README.md @@ -54,14 +54,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def countExcellentPairs(self, nums: List[int], k: int) -> int: @@ -78,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long countExcellentPairs(int[] nums, int k) { @@ -108,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +121,6 @@ public: }; ``` -### **Go** - ```go func countExcellentPairs(nums []int, k int) int64 { s := map[int]bool{} @@ -157,16 +145,6 @@ func countExcellentPairs(nums []int, k int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2354.Number of Excellent Pairs/README_EN.md b/solution/2300-2399/2354.Number of Excellent Pairs/README_EN.md index 6fb326fb49796..3d8d6bb0d4342 100644 --- a/solution/2300-2399/2354.Number of Excellent Pairs/README_EN.md +++ b/solution/2300-2399/2354.Number of Excellent Pairs/README_EN.md @@ -50,9 +50,9 @@ So the number of excellent pairs is 5. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long countExcellentPairs(int[] nums, int k) { @@ -98,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +117,6 @@ public: }; ``` -### **Go** - ```go func countExcellentPairs(nums []int, k int) int64 { s := map[int]bool{} @@ -147,16 +141,6 @@ func countExcellentPairs(nums []int, k int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2355.Maximum Number of Books You Can Take/README.md b/solution/2300-2399/2355.Maximum Number of Books You Can Take/README.md index f407b491667f0..c782d5ab7bdbc 100644 --- a/solution/2300-2399/2355.Maximum Number of Books You Can Take/README.md +++ b/solution/2300-2399/2355.Maximum Number of Books You Can Take/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:单调栈 + 动态规划** +### 方法一:单调栈 + 动态规划 设 $dp[i]$ 表示以 $books[i]$ 结尾时能取走的书的最大数量。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def maximumBooks(self, books: List[int]) -> int: @@ -112,10 +106,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long maximumBooks(int[] books) { @@ -153,8 +143,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -188,8 +176,6 @@ public: }; ``` -### **Go** - ```go func maximumBooks(books []int) int64 { n := len(books) @@ -227,16 +213,6 @@ func maximumBooks(books []int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2355.Maximum Number of Books You Can Take/README_EN.md b/solution/2300-2399/2355.Maximum Number of Books You Can Take/README_EN.md index 26bfccccd3745..05721cc31d400 100644 --- a/solution/2300-2399/2355.Maximum Number of Books You Can Take/README_EN.md +++ b/solution/2300-2399/2355.Maximum Number of Books You Can Take/README_EN.md @@ -62,9 +62,9 @@ It can be proven that 13 is the maximum number of books you can take. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -92,8 +92,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long maximumBooks(int[] books) { @@ -131,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -166,8 +162,6 @@ public: }; ``` -### **Go** - ```go func maximumBooks(books []int) int64 { n := len(books) @@ -205,16 +199,6 @@ func maximumBooks(books []int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2356.Number of Unique Subjects Taught by Each Teacher/README.md b/solution/2300-2399/2356.Number of Unique Subjects Taught by Each Teacher/README.md index 9cf835ccb892f..cd9de6b024d73 100644 --- a/solution/2300-2399/2356.Number of Unique Subjects Taught by Each Teacher/README.md +++ b/solution/2300-2399/2356.Number of Unique Subjects Taught by Each Teacher/README.md @@ -65,14 +65,10 @@ Teacher 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT teacher_id, COUNT(DISTINCT subject_id) AS cnt @@ -81,3 +77,5 @@ GROUP BY 1; ``` + + diff --git a/solution/2300-2399/2356.Number of Unique Subjects Taught by Each Teacher/README_EN.md b/solution/2300-2399/2356.Number of Unique Subjects Taught by Each Teacher/README_EN.md index c0efec24bf3cc..05e8b3767b82f 100644 --- a/solution/2300-2399/2356.Number of Unique Subjects Taught by Each Teacher/README_EN.md +++ b/solution/2300-2399/2356.Number of Unique Subjects Taught by Each Teacher/README_EN.md @@ -63,9 +63,9 @@ Teacher 2: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -75,3 +75,5 @@ GROUP BY 1; ``` + + diff --git a/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README.md b/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README.md index d04a95624395e..690b865358ca5 100644 --- a/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README.md +++ b/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:哈希表或数组** +### 方法一:哈希表或数组 我们观察到,每一次操作,都可以把数组 `nums` 中相同且非零的元素减少到 $0$,因此,我们只需要统计数组 `nums` 中有多少个不同的非零元素,即为最少操作数。统计不同的非零元素,可以使用哈希表或数组来实现。 @@ -56,20 +54,12 @@ -### **Python3** - - - ```python class Solution: def minimumOperations(self, nums: List[int]) -> int: return len({x for x in nums if x}) ``` -### **Java** - - - ```java class Solution { public int minimumOperations(int[] nums) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func minimumOperations(nums []int) (ans int) { s := [101]bool{true} @@ -122,8 +108,6 @@ func minimumOperations(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumOperations(nums: number[]): number { const set = new Set(nums); @@ -132,8 +116,6 @@ function minimumOperations(nums: number[]): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -145,8 +127,6 @@ impl Solution { } ``` -### **C** - ```c int minimumOperations(int* nums, int numsSize) { int vis[101] = {0}; @@ -163,10 +143,6 @@ int minimumOperations(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README_EN.md b/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README_EN.md index c82cc44d9ea86..0f273b96a48e2 100644 --- a/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README_EN.md +++ b/solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/README_EN.md @@ -43,9 +43,9 @@ In the third operation, choose x = 2. Now, nums = [0,0,0,0,0]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return len({x for x in nums if x}) ``` -### **Java** - ```java class Solution { public int minimumOperations(int[] nums) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -92,8 +88,6 @@ public: }; ``` -### **Go** - ```go func minimumOperations(nums []int) (ans int) { s := [101]bool{true} @@ -107,8 +101,6 @@ func minimumOperations(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumOperations(nums: number[]): number { const set = new Set(nums); @@ -117,8 +109,6 @@ function minimumOperations(nums: number[]): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -130,8 +120,6 @@ impl Solution { } ``` -### **C** - ```c int minimumOperations(int* nums, int numsSize) { int vis[101] = {0}; @@ -148,10 +136,6 @@ int minimumOperations(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README.md b/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README.md index 155eda67b5558..9ddd15677ec2d 100644 --- a/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README.md +++ b/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:贪心 + 二分查找** +### 方法一:贪心 + 二分查找 我们观察题目中的条件,第 $i$ 组的学生人数要小于第 $i+1$ 组的学生人数,且第 $i$ 组的学生总成绩要小于第 $i+1$ 组的学生总成绩,我们只需要将学生按照成绩从小到大排序,然后每一组依次分配 $1$, $2$, ..., $k$ 个学生即可。如果最后一组的学生人数不足 $k$ 个,那么我们可以将这些学生分配到前面的最后一组中。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def maximumGroups(self, grades: List[int]) -> int: @@ -73,10 +67,6 @@ class Solution: return bisect_right(range(n + 1), n * 2, key=lambda x: x * x + x) - 1 ``` -### **Java** - - - ```java class Solution { public int maximumGroups(int[] grades) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func maximumGroups(grades []int) int { n := len(grades) @@ -128,8 +114,6 @@ func maximumGroups(grades []int) int { } ``` -### **TypeScript** - ```ts function maximumGroups(grades: number[]): number { const n = grades.length; @@ -147,10 +131,6 @@ function maximumGroups(grades: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README_EN.md b/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README_EN.md index a90f1be62d2b8..2b7a5b78a4473 100644 --- a/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README_EN.md +++ b/solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/README_EN.md @@ -44,9 +44,9 @@ It can be shown that it is not possible to form more than 3 groups. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return bisect_right(range(n + 1), n * 2, key=lambda x: x * x + x) - 1 ``` -### **Java** - ```java class Solution { public int maximumGroups(int[] grades) { @@ -75,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func maximumGroups(grades []int) int { n := len(grades) @@ -108,8 +102,6 @@ func maximumGroups(grades []int) int { } ``` -### **TypeScript** - ```ts function maximumGroups(grades: number[]): number { const n = grades.length; @@ -127,10 +119,6 @@ function maximumGroups(grades: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/README.md b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/README.md index df2fdb7f82132..3c65fb7eab748 100644 --- a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/README.md +++ b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:BFS + 枚举公共点** +### 方法一:BFS + 枚举公共点 我们可以先用 BFS 求出从 $node1$ 和 $node2$ 分别到达每个点的距离,分别记为 $d_1$ 和 $d_2$。然后枚举所有的公共点 $i$,然后求出 $\max(d_1[i], d_2[i])$,取其中的最小值即可。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: @@ -98,40 +92,6 @@ class Solution: return ans ``` -```python -class Solution: - def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: - def f(i): - dist = [inf] * n - dist[i] = 0 - q = deque([i]) - while q: - i = q.popleft() - for j in g[i]: - if dist[j] == inf: - dist[j] = dist[i] + 1 - q.append(j) - return dist - - g = defaultdict(list) - for i, j in enumerate(edges): - if j != -1: - g[i].append(j) - n = len(edges) - d1 = f(node1) - d2 = f(node2) - ans, d = -1, inf - for i, (a, b) in enumerate(zip(d1, d2)): - if (t := max(a, b)) < d: - d = t - ans = i - return ans -``` - -### **Java** - - - ```java class Solution { private int n; @@ -181,56 +141,6 @@ class Solution { } ``` -```java -class Solution { - private int n; - private List[] g; - - public int closestMeetingNode(int[] edges, int node1, int node2) { - n = edges.length; - g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int i = 0; i < n; ++i) { - if (edges[i] != -1) { - g[i].add(edges[i]); - } - } - int[] d1 = f(node1); - int[] d2 = f(node2); - int d = 1 << 30; - int ans = -1; - for (int i = 0; i < n; ++i) { - int t = Math.max(d1[i], d2[i]); - if (t < d) { - d = t; - ans = i; - } - } - return ans; - } - - private int[] f(int i) { - int[] dist = new int[n]; - Arrays.fill(dist, 1 << 30); - dist[i] = 0; - Deque q = new ArrayDeque<>(); - q.offer(i); - while (!q.isEmpty()) { - i = q.poll(); - for (int j : g[i]) { - if (dist[j] == 1 << 30) { - dist[j] = dist[i] + 1; - q.offer(j); - } - } - } - return dist; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -277,52 +187,6 @@ public: }; ``` -```cpp -class Solution { -public: - int closestMeetingNode(vector& edges, int node1, int node2) { - int n = edges.size(); - vector> g(n); - for (int i = 0; i < n; ++i) { - if (edges[i] != -1) { - g[i].push_back(edges[i]); - } - } - const int inf = 1 << 30; - using pii = pair; - auto f = [&](int i) { - vector dist(n, inf); - dist[i] = 0; - queue q{{i}}; - while (!q.empty()) { - i = q.front(); - q.pop(); - for (int j : g[i]) { - if (dist[j] == inf) { - dist[j] = dist[i] + 1; - q.push(j); - } - } - } - return dist; - }; - vector d1 = f(node1); - vector d2 = f(node2); - int ans = -1, d = inf; - for (int i = 0; i < n; ++i) { - int t = max(d1[i], d2[i]); - if (t < d) { - d = t; - ans = i; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func closestMeetingNode(edges []int, node1 int, node2 int) int { n := len(edges) @@ -376,52 +240,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -```go -func closestMeetingNode(edges []int, node1 int, node2 int) int { - n := len(edges) - g := make([][]int, n) - for i, j := range edges { - if j != -1 { - g[i] = append(g[i], j) - } - } - const inf int = 1 << 30 - f := func(i int) []int { - dist := make([]int, n) - for j := range dist { - dist[j] = inf - } - dist[i] = 0 - q := []int{i} - for len(q) > 0 { - i = q[0] - q = q[1:] - for _, j := range g[i] { - if dist[j] == inf { - dist[j] = dist[i] + 1 - q = append(q, j) - } - } - } - return dist - } - d1 := f(node1) - d2 := f(node2) - ans, d := -1, inf - for i, a := range d1 { - b := d2[i] - t := max(a, b) - if t < d { - d = t - ans = i - } - } - return ans -} -``` - -### **TypeScript** - ```ts function closestMeetingNode(edges: number[], node1: number, node2: number): number { const n = edges.length; @@ -462,10 +280,178 @@ function closestMeetingNode(edges: number[], node1: number, node2: number): numb } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: + def f(i): + dist = [inf] * n + dist[i] = 0 + q = deque([i]) + while q: + i = q.popleft() + for j in g[i]: + if dist[j] == inf: + dist[j] = dist[i] + 1 + q.append(j) + return dist + + g = defaultdict(list) + for i, j in enumerate(edges): + if j != -1: + g[i].append(j) + n = len(edges) + d1 = f(node1) + d2 = f(node2) + ans, d = -1, inf + for i, (a, b) in enumerate(zip(d1, d2)): + if (t := max(a, b)) < d: + d = t + ans = i + return ans +``` + +```java +class Solution { + private int n; + private List[] g; + + public int closestMeetingNode(int[] edges, int node1, int node2) { + n = edges.length; + g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int i = 0; i < n; ++i) { + if (edges[i] != -1) { + g[i].add(edges[i]); + } + } + int[] d1 = f(node1); + int[] d2 = f(node2); + int d = 1 << 30; + int ans = -1; + for (int i = 0; i < n; ++i) { + int t = Math.max(d1[i], d2[i]); + if (t < d) { + d = t; + ans = i; + } + } + return ans; + } + + private int[] f(int i) { + int[] dist = new int[n]; + Arrays.fill(dist, 1 << 30); + dist[i] = 0; + Deque q = new ArrayDeque<>(); + q.offer(i); + while (!q.isEmpty()) { + i = q.poll(); + for (int j : g[i]) { + if (dist[j] == 1 << 30) { + dist[j] = dist[i] + 1; + q.offer(j); + } + } + } + return dist; + } +} +``` +```cpp +class Solution { +public: + int closestMeetingNode(vector& edges, int node1, int node2) { + int n = edges.size(); + vector> g(n); + for (int i = 0; i < n; ++i) { + if (edges[i] != -1) { + g[i].push_back(edges[i]); + } + } + const int inf = 1 << 30; + using pii = pair; + auto f = [&](int i) { + vector dist(n, inf); + dist[i] = 0; + queue q{{i}}; + while (!q.empty()) { + i = q.front(); + q.pop(); + for (int j : g[i]) { + if (dist[j] == inf) { + dist[j] = dist[i] + 1; + q.push(j); + } + } + } + return dist; + }; + vector d1 = f(node1); + vector d2 = f(node2); + int ans = -1, d = inf; + for (int i = 0; i < n; ++i) { + int t = max(d1[i], d2[i]); + if (t < d) { + d = t; + ans = i; + } + } + return ans; + } +}; ``` +```go +func closestMeetingNode(edges []int, node1 int, node2 int) int { + n := len(edges) + g := make([][]int, n) + for i, j := range edges { + if j != -1 { + g[i] = append(g[i], j) + } + } + const inf int = 1 << 30 + f := func(i int) []int { + dist := make([]int, n) + for j := range dist { + dist[j] = inf + } + dist[i] = 0 + q := []int{i} + for len(q) > 0 { + i = q[0] + q = q[1:] + for _, j := range g[i] { + if dist[j] == inf { + dist[j] = dist[i] + 1 + q = append(q, j) + } + } + } + return dist + } + d1 := f(node1) + d2 := f(node2) + ans, d := -1, inf + for i, a := range d1 { + b := d2[i] + t := max(a, b) + if t < d { + d = t + ans = i + } + } + return ans +} ``` + + diff --git a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/README_EN.md b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/README_EN.md index a85a7c1d2b1bd..8bf7444062287 100644 --- a/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/README_EN.md +++ b/solution/2300-2399/2359.Find Closest Node to Given Two Nodes/README_EN.md @@ -46,9 +46,9 @@ The maximum of those two distances is 2. It can be proven that we cannot get a n ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,38 +80,6 @@ class Solution: return ans ``` -```python -class Solution: - def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: - def f(i): - dist = [inf] * n - dist[i] = 0 - q = deque([i]) - while q: - i = q.popleft() - for j in g[i]: - if dist[j] == inf: - dist[j] = dist[i] + 1 - q.append(j) - return dist - - g = defaultdict(list) - for i, j in enumerate(edges): - if j != -1: - g[i].append(j) - n = len(edges) - d1 = f(node1) - d2 = f(node2) - ans, d = -1, inf - for i, (a, b) in enumerate(zip(d1, d2)): - if (t := max(a, b)) < d: - d = t - ans = i - return ans -``` - -### **Java** - ```java class Solution { private int n; @@ -161,56 +129,6 @@ class Solution { } ``` -```java -class Solution { - private int n; - private List[] g; - - public int closestMeetingNode(int[] edges, int node1, int node2) { - n = edges.length; - g = new List[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (int i = 0; i < n; ++i) { - if (edges[i] != -1) { - g[i].add(edges[i]); - } - } - int[] d1 = f(node1); - int[] d2 = f(node2); - int d = 1 << 30; - int ans = -1; - for (int i = 0; i < n; ++i) { - int t = Math.max(d1[i], d2[i]); - if (t < d) { - d = t; - ans = i; - } - } - return ans; - } - - private int[] f(int i) { - int[] dist = new int[n]; - Arrays.fill(dist, 1 << 30); - dist[i] = 0; - Deque q = new ArrayDeque<>(); - q.offer(i); - while (!q.isEmpty()) { - i = q.poll(); - for (int j : g[i]) { - if (dist[j] == 1 << 30) { - dist[j] = dist[i] + 1; - q.offer(j); - } - } - } - return dist; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -257,52 +175,6 @@ public: }; ``` -```cpp -class Solution { -public: - int closestMeetingNode(vector& edges, int node1, int node2) { - int n = edges.size(); - vector> g(n); - for (int i = 0; i < n; ++i) { - if (edges[i] != -1) { - g[i].push_back(edges[i]); - } - } - const int inf = 1 << 30; - using pii = pair; - auto f = [&](int i) { - vector dist(n, inf); - dist[i] = 0; - queue q{{i}}; - while (!q.empty()) { - i = q.front(); - q.pop(); - for (int j : g[i]) { - if (dist[j] == inf) { - dist[j] = dist[i] + 1; - q.push(j); - } - } - } - return dist; - }; - vector d1 = f(node1); - vector d2 = f(node2); - int ans = -1, d = inf; - for (int i = 0; i < n; ++i) { - int t = max(d1[i], d2[i]); - if (t < d) { - d = t; - ans = i; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func closestMeetingNode(edges []int, node1 int, node2 int) int { n := len(edges) @@ -356,52 +228,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -```go -func closestMeetingNode(edges []int, node1 int, node2 int) int { - n := len(edges) - g := make([][]int, n) - for i, j := range edges { - if j != -1 { - g[i] = append(g[i], j) - } - } - const inf int = 1 << 30 - f := func(i int) []int { - dist := make([]int, n) - for j := range dist { - dist[j] = inf - } - dist[i] = 0 - q := []int{i} - for len(q) > 0 { - i = q[0] - q = q[1:] - for _, j := range g[i] { - if dist[j] == inf { - dist[j] = dist[i] + 1 - q = append(q, j) - } - } - } - return dist - } - d1 := f(node1) - d2 := f(node2) - ans, d := -1, inf - for i, a := range d1 { - b := d2[i] - t := max(a, b) - if t < d { - d = t - ans = i - } - } - return ans -} -``` - -### **TypeScript** - ```ts function closestMeetingNode(edges: number[], node1: number, node2: number): number { const n = edges.length; @@ -442,10 +268,178 @@ function closestMeetingNode(edges: number[], node1: number, node2: number): numb } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int: + def f(i): + dist = [inf] * n + dist[i] = 0 + q = deque([i]) + while q: + i = q.popleft() + for j in g[i]: + if dist[j] == inf: + dist[j] = dist[i] + 1 + q.append(j) + return dist + g = defaultdict(list) + for i, j in enumerate(edges): + if j != -1: + g[i].append(j) + n = len(edges) + d1 = f(node1) + d2 = f(node2) + ans, d = -1, inf + for i, (a, b) in enumerate(zip(d1, d2)): + if (t := max(a, b)) < d: + d = t + ans = i + return ans ``` +```java +class Solution { + private int n; + private List[] g; + + public int closestMeetingNode(int[] edges, int node1, int node2) { + n = edges.length; + g = new List[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (int i = 0; i < n; ++i) { + if (edges[i] != -1) { + g[i].add(edges[i]); + } + } + int[] d1 = f(node1); + int[] d2 = f(node2); + int d = 1 << 30; + int ans = -1; + for (int i = 0; i < n; ++i) { + int t = Math.max(d1[i], d2[i]); + if (t < d) { + d = t; + ans = i; + } + } + return ans; + } + + private int[] f(int i) { + int[] dist = new int[n]; + Arrays.fill(dist, 1 << 30); + dist[i] = 0; + Deque q = new ArrayDeque<>(); + q.offer(i); + while (!q.isEmpty()) { + i = q.poll(); + for (int j : g[i]) { + if (dist[j] == 1 << 30) { + dist[j] = dist[i] + 1; + q.offer(j); + } + } + } + return dist; + } +} +``` + +```cpp +class Solution { +public: + int closestMeetingNode(vector& edges, int node1, int node2) { + int n = edges.size(); + vector> g(n); + for (int i = 0; i < n; ++i) { + if (edges[i] != -1) { + g[i].push_back(edges[i]); + } + } + const int inf = 1 << 30; + using pii = pair; + auto f = [&](int i) { + vector dist(n, inf); + dist[i] = 0; + queue q{{i}}; + while (!q.empty()) { + i = q.front(); + q.pop(); + for (int j : g[i]) { + if (dist[j] == inf) { + dist[j] = dist[i] + 1; + q.push(j); + } + } + } + return dist; + }; + vector d1 = f(node1); + vector d2 = f(node2); + int ans = -1, d = inf; + for (int i = 0; i < n; ++i) { + int t = max(d1[i], d2[i]); + if (t < d) { + d = t; + ans = i; + } + } + return ans; + } +}; +``` + +```go +func closestMeetingNode(edges []int, node1 int, node2 int) int { + n := len(edges) + g := make([][]int, n) + for i, j := range edges { + if j != -1 { + g[i] = append(g[i], j) + } + } + const inf int = 1 << 30 + f := func(i int) []int { + dist := make([]int, n) + for j := range dist { + dist[j] = inf + } + dist[i] = 0 + q := []int{i} + for len(q) > 0 { + i = q[0] + q = q[1:] + for _, j := range g[i] { + if dist[j] == inf { + dist[j] = dist[i] + 1 + q = append(q, j) + } + } + } + return dist + } + d1 := f(node1) + d2 := f(node2) + ans, d := -1, inf + for i, a := range d1 { + b := d2[i] + t := max(a, b) + if t < d { + d = t + ans = i + } + } + return ans +} ``` + + diff --git a/solution/2300-2399/2360.Longest Cycle in a Graph/README.md b/solution/2300-2399/2360.Longest Cycle in a Graph/README.md index 8fd4ee788311a..01c78c20f1e0a 100644 --- a/solution/2300-2399/2360.Longest Cycle in a Graph/README.md +++ b/solution/2300-2399/2360.Longest Cycle in a Graph/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:遍历出发点** +### 方法一:遍历出发点 我们可以遍历 $[0,..,n-1]$ 范围内的每个节点,如果该节点未被访问过,则从该节点出发,搜索邻边节点,直到遇到环或者遇到已经访问过的节点。如果遇到环,则更新答案。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def longestCycle(self, edges: List[int]) -> int: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestCycle(int[] edges) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func longestCycle(edges []int) int { vis := make([]bool, len(edges)) @@ -188,8 +174,6 @@ func longestCycle(edges []int) int { } ``` -### **TypeScript** - ```ts function longestCycle(edges: number[]): number { const n = edges.length; @@ -219,10 +203,6 @@ function longestCycle(edges: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2360.Longest Cycle in a Graph/README_EN.md b/solution/2300-2399/2360.Longest Cycle in a Graph/README_EN.md index 2f4e0f9e804b3..d4c70818422cf 100644 --- a/solution/2300-2399/2360.Longest Cycle in a Graph/README_EN.md +++ b/solution/2300-2399/2360.Longest Cycle in a Graph/README_EN.md @@ -42,9 +42,9 @@ The length of this cycle is 3, so 3 is returned. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestCycle(int[] edges) { @@ -102,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +132,6 @@ public: }; ``` -### **Go** - ```go func longestCycle(edges []int) int { vis := make([]bool, len(edges)) @@ -166,8 +160,6 @@ func longestCycle(edges []int) int { } ``` -### **TypeScript** - ```ts function longestCycle(edges: number[]): number { const n = edges.length; @@ -197,10 +189,6 @@ function longestCycle(edges: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2361.Minimum Costs Using the Train Line/README.md b/solution/2300-2399/2361.Minimum Costs Using the Train Line/README.md index 2e7e4d27de220..a206d06b7c9f1 100644 --- a/solution/2300-2399/2361.Minimum Costs Using the Train Line/README.md +++ b/solution/2300-2399/2361.Minimum Costs Using the Train Line/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示从车站 $0$ 到车站 $i$ 且到达车站 $i$ 时乘坐常规路线的最少费用,定义 $g[i]$ 表示从车站 $0$ 到车站 $i$ 且到达车站 $i$ 时乘坐特快路线的最少费用。初始时 $f[0]=0, g[0]=\infty$。 @@ -99,10 +97,6 @@ $$ -### **Python3** - - - ```python class Solution: def minimumCosts( @@ -119,26 +113,6 @@ class Solution: return cost ``` -```python -class Solution: - def minimumCosts( - self, regular: List[int], express: List[int], expressCost: int - ) -> List[int]: - n = len(regular) - f, g = 0, inf - cost = [0] * n - for i, (a, b) in enumerate(zip(regular, express), 1): - ff = min(f + a, g + a) - gg = min(f + expressCost + b, g + b) - f, g = ff, gg - cost[i - 1] = min(f, g) - return cost -``` - -### **Java** - - - ```java class Solution { public long[] minimumCosts(int[] regular, int[] express, int expressCost) { @@ -159,29 +133,6 @@ class Solution { } ``` -```java -class Solution { - public long[] minimumCosts(int[] regular, int[] express, int expressCost) { - int n = regular.length; - long f = 0; - long g = 1 << 30; - long[] cost = new long[n]; - for (int i = 0; i < n; ++i) { - int a = regular[i]; - int b = express[i]; - long ff = Math.min(f + a, g + a); - long gg = Math.min(f + expressCost + b, g + b); - f = ff; - g = gg; - cost[i] = Math.min(f, g); - } - return cost; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -204,6 +155,83 @@ public: }; ``` +```go +func minimumCosts(regular []int, express []int, expressCost int) []int64 { + n := len(regular) + f := make([]int, n+1) + g := make([]int, n+1) + g[0] = 1 << 30 + cost := make([]int64, n) + for i := 1; i <= n; i++ { + a, b := regular[i-1], express[i-1] + f[i] = min(f[i-1]+a, g[i-1]+a) + g[i] = min(f[i-1]+expressCost+b, g[i-1]+b) + cost[i-1] = int64(min(f[i], g[i])) + } + return cost +} +``` + +```ts +function minimumCosts(regular: number[], express: number[], expressCost: number): number[] { + const n = regular.length; + const f: number[] = new Array(n + 1).fill(0); + const g: number[] = new Array(n + 1).fill(0); + g[0] = 1 << 30; + const cost: number[] = new Array(n).fill(0); + for (let i = 1; i <= n; ++i) { + const [a, b] = [regular[i - 1], express[i - 1]]; + f[i] = Math.min(f[i - 1] + a, g[i - 1] + a); + g[i] = Math.min(f[i - 1] + expressCost + b, g[i - 1] + b); + cost[i - 1] = Math.min(f[i], g[i]); + } + return cost; +} +``` + + + +### 方法二 + + + +```python +class Solution: + def minimumCosts( + self, regular: List[int], express: List[int], expressCost: int + ) -> List[int]: + n = len(regular) + f, g = 0, inf + cost = [0] * n + for i, (a, b) in enumerate(zip(regular, express), 1): + ff = min(f + a, g + a) + gg = min(f + expressCost + b, g + b) + f, g = ff, gg + cost[i - 1] = min(f, g) + return cost +``` + +```java +class Solution { + public long[] minimumCosts(int[] regular, int[] express, int expressCost) { + int n = regular.length; + long f = 0; + long g = 1 << 30; + long[] cost = new long[n]; + for (int i = 0; i < n; ++i) { + int a = regular[i]; + int b = express[i]; + long ff = Math.min(f + a, g + a); + long gg = Math.min(f + expressCost + b, g + b); + f = ff; + g = gg; + cost[i] = Math.min(f, g); + } + return cost; + } +} +``` + ```cpp class Solution { public: @@ -226,25 +254,6 @@ public: }; ``` -### **Go** - -```go -func minimumCosts(regular []int, express []int, expressCost int) []int64 { - n := len(regular) - f := make([]int, n+1) - g := make([]int, n+1) - g[0] = 1 << 30 - cost := make([]int64, n) - for i := 1; i <= n; i++ { - a, b := regular[i-1], express[i-1] - f[i] = min(f[i-1]+a, g[i-1]+a) - g[i] = min(f[i-1]+expressCost+b, g[i-1]+b) - cost[i-1] = int64(min(f[i], g[i])) - } - return cost -} -``` - ```go func minimumCosts(regular []int, express []int, expressCost int) []int64 { f, g := 0, 1<<30 @@ -260,25 +269,6 @@ func minimumCosts(regular []int, express []int, expressCost int) []int64 { } ``` -### **TypeScript** - -```ts -function minimumCosts(regular: number[], express: number[], expressCost: number): number[] { - const n = regular.length; - const f: number[] = new Array(n + 1).fill(0); - const g: number[] = new Array(n + 1).fill(0); - g[0] = 1 << 30; - const cost: number[] = new Array(n).fill(0); - for (let i = 1; i <= n; ++i) { - const [a, b] = [regular[i - 1], express[i - 1]]; - f[i] = Math.min(f[i - 1] + a, g[i - 1] + a); - g[i] = Math.min(f[i - 1] + expressCost + b, g[i - 1] + b); - cost[i - 1] = Math.min(f[i], g[i]); - } - return cost; -} -``` - ```ts function minimumCosts(regular: number[], express: number[], expressCost: number): number[] { const n = regular.length; @@ -296,10 +286,6 @@ function minimumCosts(regular: number[], express: number[], expressCost: number) } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2361.Minimum Costs Using the Train Line/README_EN.md b/solution/2300-2399/2361.Minimum Costs Using the Train Line/README_EN.md index 388baa126ef3d..78c7960e9f620 100644 --- a/solution/2300-2399/2361.Minimum Costs Using the Train Line/README_EN.md +++ b/solution/2300-2399/2361.Minimum Costs Using the Train Line/README_EN.md @@ -61,9 +61,9 @@ Note that the expressCost is paid again to transfer back to the express route. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -81,24 +81,6 @@ class Solution: return cost ``` -```python -class Solution: - def minimumCosts( - self, regular: List[int], express: List[int], expressCost: int - ) -> List[int]: - n = len(regular) - f, g = 0, inf - cost = [0] * n - for i, (a, b) in enumerate(zip(regular, express), 1): - ff = min(f + a, g + a) - gg = min(f + expressCost + b, g + b) - f, g = ff, gg - cost[i - 1] = min(f, g) - return cost -``` - -### **Java** - ```java class Solution { public long[] minimumCosts(int[] regular, int[] express, int expressCost) { @@ -119,29 +101,6 @@ class Solution { } ``` -```java -class Solution { - public long[] minimumCosts(int[] regular, int[] express, int expressCost) { - int n = regular.length; - long f = 0; - long g = 1 << 30; - long[] cost = new long[n]; - for (int i = 0; i < n; ++i) { - int a = regular[i]; - int b = express[i]; - long ff = Math.min(f + a, g + a); - long gg = Math.min(f + expressCost + b, g + b); - f = ff; - g = gg; - cost[i] = Math.min(f, g); - } - return cost; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -164,6 +123,83 @@ public: }; ``` +```go +func minimumCosts(regular []int, express []int, expressCost int) []int64 { + n := len(regular) + f := make([]int, n+1) + g := make([]int, n+1) + g[0] = 1 << 30 + cost := make([]int64, n) + for i := 1; i <= n; i++ { + a, b := regular[i-1], express[i-1] + f[i] = min(f[i-1]+a, g[i-1]+a) + g[i] = min(f[i-1]+expressCost+b, g[i-1]+b) + cost[i-1] = int64(min(f[i], g[i])) + } + return cost +} +``` + +```ts +function minimumCosts(regular: number[], express: number[], expressCost: number): number[] { + const n = regular.length; + const f: number[] = new Array(n + 1).fill(0); + const g: number[] = new Array(n + 1).fill(0); + g[0] = 1 << 30; + const cost: number[] = new Array(n).fill(0); + for (let i = 1; i <= n; ++i) { + const [a, b] = [regular[i - 1], express[i - 1]]; + f[i] = Math.min(f[i - 1] + a, g[i - 1] + a); + g[i] = Math.min(f[i - 1] + expressCost + b, g[i - 1] + b); + cost[i - 1] = Math.min(f[i], g[i]); + } + return cost; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minimumCosts( + self, regular: List[int], express: List[int], expressCost: int + ) -> List[int]: + n = len(regular) + f, g = 0, inf + cost = [0] * n + for i, (a, b) in enumerate(zip(regular, express), 1): + ff = min(f + a, g + a) + gg = min(f + expressCost + b, g + b) + f, g = ff, gg + cost[i - 1] = min(f, g) + return cost +``` + +```java +class Solution { + public long[] minimumCosts(int[] regular, int[] express, int expressCost) { + int n = regular.length; + long f = 0; + long g = 1 << 30; + long[] cost = new long[n]; + for (int i = 0; i < n; ++i) { + int a = regular[i]; + int b = express[i]; + long ff = Math.min(f + a, g + a); + long gg = Math.min(f + expressCost + b, g + b); + f = ff; + g = gg; + cost[i] = Math.min(f, g); + } + return cost; + } +} +``` + ```cpp class Solution { public: @@ -186,25 +222,6 @@ public: }; ``` -### **Go** - -```go -func minimumCosts(regular []int, express []int, expressCost int) []int64 { - n := len(regular) - f := make([]int, n+1) - g := make([]int, n+1) - g[0] = 1 << 30 - cost := make([]int64, n) - for i := 1; i <= n; i++ { - a, b := regular[i-1], express[i-1] - f[i] = min(f[i-1]+a, g[i-1]+a) - g[i] = min(f[i-1]+expressCost+b, g[i-1]+b) - cost[i-1] = int64(min(f[i], g[i])) - } - return cost -} -``` - ```go func minimumCosts(regular []int, express []int, expressCost int) []int64 { f, g := 0, 1<<30 @@ -220,25 +237,6 @@ func minimumCosts(regular []int, express []int, expressCost int) []int64 { } ``` -### **TypeScript** - -```ts -function minimumCosts(regular: number[], express: number[], expressCost: number): number[] { - const n = regular.length; - const f: number[] = new Array(n + 1).fill(0); - const g: number[] = new Array(n + 1).fill(0); - g[0] = 1 << 30; - const cost: number[] = new Array(n).fill(0); - for (let i = 1; i <= n; ++i) { - const [a, b] = [regular[i - 1], express[i - 1]]; - f[i] = Math.min(f[i - 1] + a, g[i - 1] + a); - g[i] = Math.min(f[i - 1] + expressCost + b, g[i - 1] + b); - cost[i - 1] = Math.min(f[i], g[i]); - } - return cost; -} -``` - ```ts function minimumCosts(regular: number[], express: number[], expressCost: number): number[] { const n = regular.length; @@ -256,10 +254,6 @@ function minimumCosts(regular: number[], express: number[], expressCost: number) } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2362.Generate the Invoice/README.md b/solution/2300-2399/2362.Generate the Invoice/README.md index f7a748d47560e..57f0c5440ad57 100644 --- a/solution/2300-2399/2362.Generate the Invoice/README.md +++ b/solution/2300-2399/2362.Generate the Invoice/README.md @@ -83,14 +83,10 @@ Purchases 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -114,3 +110,5 @@ FROM ``` + + diff --git a/solution/2300-2399/2362.Generate the Invoice/README_EN.md b/solution/2300-2399/2362.Generate the Invoice/README_EN.md index d4e7ed38caf35..e75a073e7d11a 100644 --- a/solution/2300-2399/2362.Generate the Invoice/README_EN.md +++ b/solution/2300-2399/2362.Generate the Invoice/README_EN.md @@ -81,9 +81,9 @@ The highest price is 1000, and the invoices with the highest prices are 2 and 4. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -108,3 +108,5 @@ FROM ``` + + diff --git a/solution/2300-2399/2363.Merge Similar Items/README.md b/solution/2300-2399/2363.Merge Similar Items/README.md index abcfbbf4c13de..1e569af0df58c 100644 --- a/solution/2300-2399/2363.Merge Similar Items/README.md +++ b/solution/2300-2399/2363.Merge Similar Items/README.md @@ -68,9 +68,7 @@ value = 7 的物品在 items2 中 weight = 1 ,总重量为 1 。 ## 解法 - - -**方法一:哈希表或数组** +### 方法一:哈希表或数组 我们可以用哈希表或数组 `cnt` 统计 `items1` 和 `items2` 中每个物品的总重量,然后从小到大遍历价值,将每个价值以及对应的总重量加入结果数组即可。 @@ -78,10 +76,6 @@ value = 7 的物品在 items2 中 weight = 1 ,总重量为 1 。 -### **Python3** - - - ```python class Solution: def mergeSimilarItems( @@ -93,10 +87,6 @@ class Solution: return sorted(cnt.items()) ``` -### **Java** - - - ```java class Solution { public List> mergeSimilarItems(int[][] items1, int[][] items2) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func mergeSimilarItems(items1 [][]int, items2 [][]int) (ans [][]int) { cnt := [1010]int{} @@ -162,8 +148,6 @@ func mergeSimilarItems(items1 [][]int, items2 [][]int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function mergeSimilarItems(items1: number[][], items2: number[][]): number[][] { const count = new Array(1001).fill(0); @@ -177,8 +161,6 @@ function mergeSimilarItems(items1: number[][], items2: number[][]): number[][] { } ``` -### **Rust** - ```rust impl Solution { pub fn merge_similar_items(items1: Vec>, items2: Vec>) -> Vec> { @@ -203,8 +185,6 @@ impl Solution { } ``` -### **C** - ```c /** * Return an array of arrays of size *returnSize. @@ -237,10 +217,6 @@ int** mergeSimilarItems(int** items1, int items1Size, int* items1ColSize, int** } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2363.Merge Similar Items/README_EN.md b/solution/2300-2399/2363.Merge Similar Items/README_EN.md index 2bfc639757009..472ddf199ef18 100644 --- a/solution/2300-2399/2363.Merge Similar Items/README_EN.md +++ b/solution/2300-2399/2363.Merge Similar Items/README_EN.md @@ -64,9 +64,9 @@ Therefore, we return [[1,7],[2,4],[7,1]]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,8 +79,6 @@ class Solution: return sorted(cnt.items()) ``` -### **Java** - ```java class Solution { public List> mergeSimilarItems(int[][] items1, int[][] items2) { @@ -102,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +122,6 @@ public: }; ``` -### **Go** - ```go func mergeSimilarItems(items1 [][]int, items2 [][]int) (ans [][]int) { cnt := [1010]int{} @@ -146,8 +140,6 @@ func mergeSimilarItems(items1 [][]int, items2 [][]int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function mergeSimilarItems(items1: number[][], items2: number[][]): number[][] { const count = new Array(1001).fill(0); @@ -161,8 +153,6 @@ function mergeSimilarItems(items1: number[][], items2: number[][]): number[][] { } ``` -### **Rust** - ```rust impl Solution { pub fn merge_similar_items(items1: Vec>, items2: Vec>) -> Vec> { @@ -187,8 +177,6 @@ impl Solution { } ``` -### **C** - ```c /** * Return an array of arrays of size *returnSize. @@ -221,10 +209,6 @@ int** mergeSimilarItems(int** items1, int items1Size, int* items1ColSize, int** } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2364.Count Number of Bad Pairs/README.md b/solution/2300-2399/2364.Count Number of Bad Pairs/README.md index 4a094045b7ea3..888da8e6195f7 100644 --- a/solution/2300-2399/2364.Count Number of Bad Pairs/README.md +++ b/solution/2300-2399/2364.Count Number of Bad Pairs/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:式子转换 + 哈希表** +### 方法一:式子转换 + 哈希表 根据题目描述,我们可以得知,对于任意的 $i \lt j$,如果 $j - i \neq nums[j] - nums[i]$,则 $(i, j)$ 是一个坏数对。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def countBadPairs(self, nums: List[int]) -> int: @@ -73,10 +67,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long countBadPairs(int[] nums) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +98,6 @@ public: }; ``` -### **Go** - ```go func countBadPairs(nums []int) (ans int64) { cnt := map[int]int{} @@ -124,8 +110,6 @@ func countBadPairs(nums []int) (ans int64) { } ``` -### **TypeScript** - ```ts function countBadPairs(nums: number[]): number { const cnt = new Map(); @@ -139,10 +123,6 @@ function countBadPairs(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2364.Count Number of Bad Pairs/README_EN.md b/solution/2300-2399/2364.Count Number of Bad Pairs/README_EN.md index 4722f83509f27..03e89ba7e15f4 100644 --- a/solution/2300-2399/2364.Count Number of Bad Pairs/README_EN.md +++ b/solution/2300-2399/2364.Count Number of Bad Pairs/README_EN.md @@ -40,9 +40,9 @@ There are a total of 5 bad pairs, so we return 5. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long countBadPairs(int[] nums) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,8 +86,6 @@ public: }; ``` -### **Go** - ```go func countBadPairs(nums []int) (ans int64) { cnt := map[int]int{} @@ -104,8 +98,6 @@ func countBadPairs(nums []int) (ans int64) { } ``` -### **TypeScript** - ```ts function countBadPairs(nums: number[]): number { const cnt = new Map(); @@ -119,10 +111,6 @@ function countBadPairs(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2365.Task Scheduler II/README.md b/solution/2300-2399/2365.Task Scheduler II/README.md index b40586c55dfb6..9abfce4aacc73 100644 --- a/solution/2300-2399/2365.Task Scheduler II/README.md +++ b/solution/2300-2399/2365.Task Scheduler II/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:哈希表 + 模拟** +### 方法一:哈希表 + 模拟 我们可以用哈希表 $day$ 记录每个任务下一次可以被执行的时间,初始时 $day$ 中的所有值都为 $0$,用变量 $ans$ 记录当前时间。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: @@ -96,10 +90,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long taskSchedulerII(int[] tasks, int space) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +121,6 @@ public: }; ``` -### **Go** - ```go func taskSchedulerII(tasks []int, space int) (ans int64) { day := map[int]int64{} @@ -149,8 +135,6 @@ func taskSchedulerII(tasks []int, space int) (ans int64) { } ``` -### **TypeScript** - ```ts function taskSchedulerII(tasks: number[], space: number): number { const day = new Map(); @@ -164,10 +148,6 @@ function taskSchedulerII(tasks: number[], space: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2365.Task Scheduler II/README_EN.md b/solution/2300-2399/2365.Task Scheduler II/README_EN.md index 9e115e5a21f04..9235712c50926 100644 --- a/solution/2300-2399/2365.Task Scheduler II/README_EN.md +++ b/solution/2300-2399/2365.Task Scheduler II/README_EN.md @@ -64,9 +64,9 @@ It can be shown that the tasks cannot be completed in less than 6 days. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long taskSchedulerII(int[] tasks, int space) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +111,6 @@ public: }; ``` -### **Go** - ```go func taskSchedulerII(tasks []int, space int) (ans int64) { day := map[int]int64{} @@ -131,8 +125,6 @@ func taskSchedulerII(tasks []int, space int) (ans int64) { } ``` -### **TypeScript** - ```ts function taskSchedulerII(tasks: number[], space: number): number { const day = new Map(); @@ -146,10 +138,6 @@ function taskSchedulerII(tasks: number[], space: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2366.Minimum Replacements to Sort the Array/README.md b/solution/2300-2399/2366.Minimum Replacements to Sort the Array/README.md index c65173fad9ad1..d0fba8cd27a2e 100644 --- a/solution/2300-2399/2366.Minimum Replacements to Sort the Array/README.md +++ b/solution/2300-2399/2366.Minimum Replacements to Sort the Array/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们观察发现,要使得数组 $nums$ 变成非递减有序,也即单调递增,那么数组后面的元素应该尽可能大,所以,将数组 $nums$ 的最后一个元素 $nums[n-1]$ 替换成多个更小的数是没有必要的。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def minimumReplacement(self, nums: List[int]) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long minimumReplacement(int[] nums) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,39 +118,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn minimum_replacement(nums: Vec) -> i64 { - if nums.len() == 1 { - return 0; - } - - let n = nums.len(); - let mut max = *nums.last().unwrap(); - let mut ret = 0; - - for i in (0..=n - 2).rev() { - if nums[i] <= max { - max = nums[i]; - continue; - } - // Otherwise make the substitution - let k = (nums[i] + max - 1) / max; - ret += (k - 1) as i64; - // Update the max value, which should be the minimum among the substitution - max = nums[i] / k; - } - - ret - } -} -``` - -### **Go** - ```go func minimumReplacement(nums []int) (ans int64) { n := len(nums) @@ -180,8 +135,6 @@ func minimumReplacement(nums []int) (ans int64) { } ``` -### **TypeScript** - ```ts function minimumReplacement(nums: number[]): number { const n = nums.length; @@ -200,10 +153,35 @@ function minimumReplacement(nums: number[]): number { } ``` -### **...** +```rust +impl Solution { + #[allow(dead_code)] + pub fn minimum_replacement(nums: Vec) -> i64 { + if nums.len() == 1 { + return 0; + } -``` + let n = nums.len(); + let mut max = *nums.last().unwrap(); + let mut ret = 0; + for i in (0..=n - 2).rev() { + if nums[i] <= max { + max = nums[i]; + continue; + } + // Otherwise make the substitution + let k = (nums[i] + max - 1) / max; + ret += (k - 1) as i64; + // Update the max value, which should be the minimum among the substitution + max = nums[i] / k; + } + + ret + } +} ``` + + diff --git a/solution/2300-2399/2366.Minimum Replacements to Sort the Array/README_EN.md b/solution/2300-2399/2366.Minimum Replacements to Sort the Array/README_EN.md index 6f5fab8b63821..f60580c0ede76 100644 --- a/solution/2300-2399/2366.Minimum Replacements to Sort the Array/README_EN.md +++ b/solution/2300-2399/2366.Minimum Replacements to Sort the Array/README_EN.md @@ -43,9 +43,9 @@ There are 2 steps to sort the array in non-decreasing order. Therefore, we retur ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long minimumReplacement(int[] nums) { @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,39 +104,6 @@ public: }; ``` -### **Rust** - -```rust -impl Solution { - #[allow(dead_code)] - pub fn minimum_replacement(nums: Vec) -> i64 { - if nums.len() == 1 { - return 0; - } - - let n = nums.len(); - let mut max = *nums.last().unwrap(); - let mut ret = 0; - - for i in (0..=n - 2).rev() { - if nums[i] <= max { - max = nums[i]; - continue; - } - // Otherwise make the substitution - let k = (nums[i] + max - 1) / max; - ret += (k - 1) as i64; - // Update the max value, which should be the minimum among the substitution - max = nums[i] / k; - } - - ret - } -} -``` - -### **Go** - ```go func minimumReplacement(nums []int) (ans int64) { n := len(nums) @@ -158,8 +121,6 @@ func minimumReplacement(nums []int) (ans int64) { } ``` -### **TypeScript** - ```ts function minimumReplacement(nums: number[]): number { const n = nums.length; @@ -178,10 +139,35 @@ function minimumReplacement(nums: number[]): number { } ``` -### **...** +```rust +impl Solution { + #[allow(dead_code)] + pub fn minimum_replacement(nums: Vec) -> i64 { + if nums.len() == 1 { + return 0; + } -``` + let n = nums.len(); + let mut max = *nums.last().unwrap(); + let mut ret = 0; + for i in (0..=n - 2).rev() { + if nums[i] <= max { + max = nums[i]; + continue; + } + // Otherwise make the substitution + let k = (nums[i] + max - 1) / max; + ret += (k - 1) as i64; + // Update the max value, which should be the minimum among the substitution + max = nums[i] / k; + } + + ret + } +} ``` + + diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/README.md b/solution/2300-2399/2367.Number of Arithmetic Triplets/README.md index b41a0bd2f6645..43476bbc72dc3 100644 --- a/solution/2300-2399/2367.Number of Arithmetic Triplets/README.md +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/README.md @@ -49,45 +49,20 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 我们注意到,数组 $nums$ 的长度只有不超过 $200$,因此可以直接暴力枚举 $i$, $j$, $k$,判断是否满足条件,若满足,累加三元组数目。 时间复杂度 $O(n^3)$,其中 $n$ 为数组 $nums$ 的长度。空间复杂度 $O(1)$。 -**方法二:数组或哈希表** - -我们可以先将 $nums$ 中的元素存入哈希表或数组 $vis$ 中,然后枚举 $nums$ 中的每个元素 $x$,判断 $x+diff$, $x+diff+diff$ 是否也在 $vis$ 中,若是,累加三元组数目。 - -枚举结束后,返回答案。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 - -### **Python3** - - - ```python class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: return sum(b - a == diff and c - b == diff for a, b, c in combinations(nums, 3)) ``` -```python -class Solution: - def arithmeticTriplets(self, nums: List[int], diff: int) -> int: - vis = set(nums) - return sum(x + diff in vis and x + diff * 2 in vis for x in nums) -``` - -### **Java** - - - ```java class Solution { public int arithmeticTriplets(int[] nums, int diff) { @@ -107,26 +82,6 @@ class Solution { } ``` -```java -class Solution { - public int arithmeticTriplets(int[] nums, int diff) { - boolean[] vis = new boolean[301]; - for (int x : nums) { - vis[x] = true; - } - int ans = 0; - for (int x : nums) { - if (vis[x + diff] && vis[x + diff + diff]) { - ++ans; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -147,25 +102,6 @@ public: }; ``` -```cpp -class Solution { -public: - int arithmeticTriplets(vector& nums, int diff) { - bitset<301> vis; - for (int x : nums) { - vis[x] = 1; - } - int ans = 0; - for (int x : nums) { - ans += vis[x + diff] && vis[x + diff + diff]; - } - return ans; - } -}; -``` - -### **Go** - ```go func arithmeticTriplets(nums []int, diff int) (ans int) { n := len(nums) @@ -182,23 +118,6 @@ func arithmeticTriplets(nums []int, diff int) (ans int) { } ``` -```go -func arithmeticTriplets(nums []int, diff int) (ans int) { - vis := [301]bool{} - for _, x := range nums { - vis[x] = true - } - for _, x := range nums { - if vis[x+diff] && vis[x+diff+diff] { - ans++ - } - } - return -} -``` - -### **TypeScript** - ```ts function arithmeticTriplets(nums: number[], diff: number): number { const n = nums.length; @@ -216,6 +135,75 @@ function arithmeticTriplets(nums: number[], diff: number): number { } ``` + + +### 方法二:数组或哈希表 + +我们可以先将 $nums$ 中的元素存入哈希表或数组 $vis$ 中,然后枚举 $nums$ 中的每个元素 $x$,判断 $x+diff$, $x+diff+diff$ 是否也在 $vis$ 中,若是,累加三元组数目。 + +枚举结束后,返回答案。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 + + + +```python +class Solution: + def arithmeticTriplets(self, nums: List[int], diff: int) -> int: + vis = set(nums) + return sum(x + diff in vis and x + diff * 2 in vis for x in nums) +``` + +```java +class Solution { + public int arithmeticTriplets(int[] nums, int diff) { + boolean[] vis = new boolean[301]; + for (int x : nums) { + vis[x] = true; + } + int ans = 0; + for (int x : nums) { + if (vis[x + diff] && vis[x + diff + diff]) { + ++ans; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int arithmeticTriplets(vector& nums, int diff) { + bitset<301> vis; + for (int x : nums) { + vis[x] = 1; + } + int ans = 0; + for (int x : nums) { + ans += vis[x + diff] && vis[x + diff + diff]; + } + return ans; + } +}; +``` + +```go +func arithmeticTriplets(nums []int, diff int) (ans int) { + vis := [301]bool{} + for _, x := range nums { + vis[x] = true + } + for _, x := range nums { + if vis[x+diff] && vis[x+diff+diff] { + ans++ + } + } + return +} +``` + ```ts function arithmeticTriplets(nums: number[], diff: number): number { const vis: boolean[] = new Array(301).fill(false); @@ -232,10 +220,6 @@ function arithmeticTriplets(nums: number[], diff: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2367.Number of Arithmetic Triplets/README_EN.md b/solution/2300-2399/2367.Number of Arithmetic Triplets/README_EN.md index 59f56e5d0caa4..a44c281d530fa 100644 --- a/solution/2300-2399/2367.Number of Arithmetic Triplets/README_EN.md +++ b/solution/2300-2399/2367.Number of Arithmetic Triplets/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -57,15 +57,6 @@ class Solution: return sum(b - a == diff and c - b == diff for a, b, c in combinations(nums, 3)) ``` -```python -class Solution: - def arithmeticTriplets(self, nums: List[int], diff: int) -> int: - vis = set(nums) - return sum(x + diff in vis and x + diff * 2 in vis for x in nums) -``` - -### **Java** - ```java class Solution { public int arithmeticTriplets(int[] nums, int diff) { @@ -85,26 +76,6 @@ class Solution { } ``` -```java -class Solution { - public int arithmeticTriplets(int[] nums, int diff) { - boolean[] vis = new boolean[301]; - for (int x : nums) { - vis[x] = true; - } - int ans = 0; - for (int x : nums) { - if (vis[x + diff] && vis[x + diff + diff]) { - ++ans; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -125,25 +96,6 @@ public: }; ``` -```cpp -class Solution { -public: - int arithmeticTriplets(vector& nums, int diff) { - bitset<301> vis; - for (int x : nums) { - vis[x] = 1; - } - int ans = 0; - for (int x : nums) { - ans += vis[x + diff] && vis[x + diff + diff]; - } - return ans; - } -}; -``` - -### **Go** - ```go func arithmeticTriplets(nums []int, diff int) (ans int) { n := len(nums) @@ -160,23 +112,6 @@ func arithmeticTriplets(nums []int, diff int) (ans int) { } ``` -```go -func arithmeticTriplets(nums []int, diff int) (ans int) { - vis := [301]bool{} - for _, x := range nums { - vis[x] = true - } - for _, x := range nums { - if vis[x+diff] && vis[x+diff+diff] { - ans++ - } - } - return -} -``` - -### **TypeScript** - ```ts function arithmeticTriplets(nums: number[], diff: number): number { const n = nums.length; @@ -194,6 +129,69 @@ function arithmeticTriplets(nums: number[], diff: number): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def arithmeticTriplets(self, nums: List[int], diff: int) -> int: + vis = set(nums) + return sum(x + diff in vis and x + diff * 2 in vis for x in nums) +``` + +```java +class Solution { + public int arithmeticTriplets(int[] nums, int diff) { + boolean[] vis = new boolean[301]; + for (int x : nums) { + vis[x] = true; + } + int ans = 0; + for (int x : nums) { + if (vis[x + diff] && vis[x + diff + diff]) { + ++ans; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int arithmeticTriplets(vector& nums, int diff) { + bitset<301> vis; + for (int x : nums) { + vis[x] = 1; + } + int ans = 0; + for (int x : nums) { + ans += vis[x + diff] && vis[x + diff + diff]; + } + return ans; + } +}; +``` + +```go +func arithmeticTriplets(nums []int, diff int) (ans int) { + vis := [301]bool{} + for _, x := range nums { + vis[x] = true + } + for _, x := range nums { + if vis[x+diff] && vis[x+diff+diff] { + ans++ + } + } + return +} +``` + ```ts function arithmeticTriplets(nums: number[], diff: number): number { const vis: boolean[] = new Array(301).fill(false); @@ -210,10 +208,6 @@ function arithmeticTriplets(nums: number[], diff: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2368.Reachable Nodes With Restrictions/README.md b/solution/2300-2399/2368.Reachable Nodes With Restrictions/README.md index 25d65298bb7a0..b69e40de447ff 100644 --- a/solution/2300-2399/2368.Reachable Nodes With Restrictions/README.md +++ b/solution/2300-2399/2368.Reachable Nodes With Restrictions/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:DFS/BFS** +### 方法一:DFS/BFS 建图,利用哈希表 $vis$ 记录有哪些受限的节点,然后 $DFS$ 或者 $BFS$ 搜索整个图,记录访问过的节点数目。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def reachableNodes( @@ -90,35 +84,6 @@ class Solution: return ans ``` -```python -class Solution: - def reachableNodes( - self, n: int, edges: List[List[int]], restricted: List[int] - ) -> int: - s = set(restricted) - g = defaultdict(list) - for a, b in edges: - g[a].append(b) - g[b].append(a) - q = deque([0]) - vis = [False] * n - for v in restricted: - vis[v] = True - ans = 0 - while q: - i = q.popleft() - ans += 1 - vis[i] = True - for j in g[i]: - if not vis[j]: - q.append(j) - return ans -``` - -### **Java** - - - ```java class Solution { private List[] g; @@ -156,6 +121,119 @@ class Solution { } ``` +```cpp +class Solution { +public: + int ans; + + int reachableNodes(int n, vector>& edges, vector& restricted) { + vector> g(n); + for (auto& e : edges) { + int a = e[0], b = e[1]; + g[a].push_back(b); + g[b].push_back(a); + } + vector vis(n); + for (int v : restricted) vis[v] = true; + ans = 0; + dfs(0, g, vis); + return ans; + } + + void dfs(int u, vector>& g, vector& vis) { + if (vis[u]) return; + vis[u] = true; + ++ans; + for (int v : g[u]) dfs(v, g, vis); + } +}; +``` + +```go +func reachableNodes(n int, edges [][]int, restricted []int) int { + g := make([][]int, n) + for _, e := range edges { + a, b := e[0], e[1] + g[a] = append(g[a], b) + g[b] = append(g[b], a) + } + vis := make([]bool, n) + for _, v := range restricted { + vis[v] = true + } + ans := 0 + var dfs func(u int) + dfs = func(u int) { + if vis[u] { + return + } + vis[u] = true + ans++ + for _, v := range g[u] { + dfs(v) + } + } + dfs(0) + return ans +} +``` + +```ts +function reachableNodes(n: number, edges: number[][], restricted: number[]): number { + let res = 0; + const vis = new Array(n).fill(false); + const map = new Map(); + for (const [start, end] of edges) { + map.set(start, [...(map.get(start) ?? []), end]); + map.set(end, [...(map.get(end) ?? []), start]); + } + const dfs = (cur: number) => { + if (restricted.includes(cur) || vis[cur]) { + return; + } + res++; + vis[cur] = true; + for (const item of map.get(cur) ?? []) { + dfs(item); + } + }; + dfs(0); + + return res; +} +``` + + + +### 方法二 + + + +```python +class Solution: + def reachableNodes( + self, n: int, edges: List[List[int]], restricted: List[int] + ) -> int: + s = set(restricted) + g = defaultdict(list) + for a, b in edges: + g[a].append(b) + g[b].append(a) + q = deque([0]) + vis = [False] * n + for v in restricted: + vis[v] = True + ans = 0 + while q: + i = q.popleft() + ans += 1 + vis[i] = True + for j in g[i]: + if not vis[j]: + q.append(j) + return ans +``` + ```java class Solution { public int reachableNodes(int n, int[][] edges, int[] restricted) { @@ -188,36 +266,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int ans; - - int reachableNodes(int n, vector>& edges, vector& restricted) { - vector> g(n); - for (auto& e : edges) { - int a = e[0], b = e[1]; - g[a].push_back(b); - g[b].push_back(a); - } - vector vis(n); - for (int v : restricted) vis[v] = true; - ans = 0; - dfs(0, g, vis); - return ans; - } - - void dfs(int u, vector>& g, vector& vis) { - if (vis[u]) return; - vis[u] = true; - ++ans; - for (int v : g[u]) dfs(v, g, vis); - } -}; -``` - ```cpp class Solution { public: @@ -245,37 +293,6 @@ public: }; ``` -### **Go** - -```go -func reachableNodes(n int, edges [][]int, restricted []int) int { - g := make([][]int, n) - for _, e := range edges { - a, b := e[0], e[1] - g[a] = append(g[a], b) - g[b] = append(g[b], a) - } - vis := make([]bool, n) - for _, v := range restricted { - vis[v] = true - } - ans := 0 - var dfs func(u int) - dfs = func(u int) { - if vis[u] { - return - } - vis[u] = true - ans++ - for _, v := range g[u] { - dfs(v) - } - } - dfs(0) - return ans -} -``` - ```go func reachableNodes(n int, edges [][]int, restricted []int) int { g := make([][]int, n) @@ -305,33 +322,6 @@ func reachableNodes(n int, edges [][]int, restricted []int) int { } ``` -### **TypeScript** - -```ts -function reachableNodes(n: number, edges: number[][], restricted: number[]): number { - let res = 0; - const vis = new Array(n).fill(false); - const map = new Map(); - for (const [start, end] of edges) { - map.set(start, [...(map.get(start) ?? []), end]); - map.set(end, [...(map.get(end) ?? []), start]); - } - const dfs = (cur: number) => { - if (restricted.includes(cur) || vis[cur]) { - return; - } - res++; - vis[cur] = true; - for (const item of map.get(cur) ?? []) { - dfs(item); - } - }; - dfs(0); - - return res; -} -``` - ```ts function reachableNodes(n: number, edges: number[][], restricted: number[]): number { const g = Array.from({ length: n }, () => []); @@ -359,10 +349,6 @@ function reachableNodes(n: number, edges: number[][], restricted: number[]): num } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2368.Reachable Nodes With Restrictions/README_EN.md b/solution/2300-2399/2368.Reachable Nodes With Restrictions/README_EN.md index f7fefc689bdf9..b67c2134ca788 100644 --- a/solution/2300-2399/2368.Reachable Nodes With Restrictions/README_EN.md +++ b/solution/2300-2399/2368.Reachable Nodes With Restrictions/README_EN.md @@ -48,9 +48,9 @@ We have that [0,5,6] are the only nodes that can be reached from node 0 without ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -79,33 +79,6 @@ class Solution: return ans ``` -```python -class Solution: - def reachableNodes( - self, n: int, edges: List[List[int]], restricted: List[int] - ) -> int: - s = set(restricted) - g = defaultdict(list) - for a, b in edges: - g[a].append(b) - g[b].append(a) - q = deque([0]) - vis = [False] * n - for v in restricted: - vis[v] = True - ans = 0 - while q: - i = q.popleft() - ans += 1 - vis[i] = True - for j in g[i]: - if not vis[j]: - q.append(j) - return ans -``` - -### **Java** - ```java class Solution { private List[] g; @@ -143,6 +116,119 @@ class Solution { } ``` +```cpp +class Solution { +public: + int ans; + + int reachableNodes(int n, vector>& edges, vector& restricted) { + vector> g(n); + for (auto& e : edges) { + int a = e[0], b = e[1]; + g[a].push_back(b); + g[b].push_back(a); + } + vector vis(n); + for (int v : restricted) vis[v] = true; + ans = 0; + dfs(0, g, vis); + return ans; + } + + void dfs(int u, vector>& g, vector& vis) { + if (vis[u]) return; + vis[u] = true; + ++ans; + for (int v : g[u]) dfs(v, g, vis); + } +}; +``` + +```go +func reachableNodes(n int, edges [][]int, restricted []int) int { + g := make([][]int, n) + for _, e := range edges { + a, b := e[0], e[1] + g[a] = append(g[a], b) + g[b] = append(g[b], a) + } + vis := make([]bool, n) + for _, v := range restricted { + vis[v] = true + } + ans := 0 + var dfs func(u int) + dfs = func(u int) { + if vis[u] { + return + } + vis[u] = true + ans++ + for _, v := range g[u] { + dfs(v) + } + } + dfs(0) + return ans +} +``` + +```ts +function reachableNodes(n: number, edges: number[][], restricted: number[]): number { + let res = 0; + const vis = new Array(n).fill(false); + const map = new Map(); + for (const [start, end] of edges) { + map.set(start, [...(map.get(start) ?? []), end]); + map.set(end, [...(map.get(end) ?? []), start]); + } + const dfs = (cur: number) => { + if (restricted.includes(cur) || vis[cur]) { + return; + } + res++; + vis[cur] = true; + for (const item of map.get(cur) ?? []) { + dfs(item); + } + }; + dfs(0); + + return res; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def reachableNodes( + self, n: int, edges: List[List[int]], restricted: List[int] + ) -> int: + s = set(restricted) + g = defaultdict(list) + for a, b in edges: + g[a].append(b) + g[b].append(a) + q = deque([0]) + vis = [False] * n + for v in restricted: + vis[v] = True + ans = 0 + while q: + i = q.popleft() + ans += 1 + vis[i] = True + for j in g[i]: + if not vis[j]: + q.append(j) + return ans +``` + ```java class Solution { public int reachableNodes(int n, int[][] edges, int[] restricted) { @@ -175,36 +261,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int ans; - - int reachableNodes(int n, vector>& edges, vector& restricted) { - vector> g(n); - for (auto& e : edges) { - int a = e[0], b = e[1]; - g[a].push_back(b); - g[b].push_back(a); - } - vector vis(n); - for (int v : restricted) vis[v] = true; - ans = 0; - dfs(0, g, vis); - return ans; - } - - void dfs(int u, vector>& g, vector& vis) { - if (vis[u]) return; - vis[u] = true; - ++ans; - for (int v : g[u]) dfs(v, g, vis); - } -}; -``` - ```cpp class Solution { public: @@ -232,37 +288,6 @@ public: }; ``` -### **Go** - -```go -func reachableNodes(n int, edges [][]int, restricted []int) int { - g := make([][]int, n) - for _, e := range edges { - a, b := e[0], e[1] - g[a] = append(g[a], b) - g[b] = append(g[b], a) - } - vis := make([]bool, n) - for _, v := range restricted { - vis[v] = true - } - ans := 0 - var dfs func(u int) - dfs = func(u int) { - if vis[u] { - return - } - vis[u] = true - ans++ - for _, v := range g[u] { - dfs(v) - } - } - dfs(0) - return ans -} -``` - ```go func reachableNodes(n int, edges [][]int, restricted []int) int { g := make([][]int, n) @@ -292,33 +317,6 @@ func reachableNodes(n int, edges [][]int, restricted []int) int { } ``` -### **TypeScript** - -```ts -function reachableNodes(n: number, edges: number[][], restricted: number[]): number { - let res = 0; - const vis = new Array(n).fill(false); - const map = new Map(); - for (const [start, end] of edges) { - map.set(start, [...(map.get(start) ?? []), end]); - map.set(end, [...(map.get(end) ?? []), start]); - } - const dfs = (cur: number) => { - if (restricted.includes(cur) || vis[cur]) { - return; - } - res++; - vis[cur] = true; - for (const item of map.get(cur) ?? []) { - dfs(item); - } - }; - dfs(0); - - return res; -} -``` - ```ts function reachableNodes(n: number, edges: number[][], restricted: number[]): number { const g = Array.from({ length: n }, () => []); @@ -346,10 +344,6 @@ function reachableNodes(n: number, edges: number[][], restricted: number[]): num } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/README.md b/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/README.md index cd8845ac5bc0a..41dc698e5210c 100644 --- a/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/README.md +++ b/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/README.md @@ -48,39 +48,14 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 $dfs(i)$ 表示从数组从下标 $i$ 开始到结尾,是否至少存在一个有效的划分。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。 -**方法二:动态规划** - -设 $dp[i]$ 表示数组前 $i$ 个元素是否至少存在一个有效的划分。初始时 $dp[0]=true$, $dp[1]=false$。 - -根据题意,当 $i \ge 2$ 时,有 - -$$ -dp[i] = \text{OR} -\begin{cases} -dp[i-2]\ \text{AND}\ \textit{nums}[i-1] = \textit{nums}[i-2],&i>1\\ -dp[i-3]\ \text{AND}\ \textit{nums}[i-1] = \textit{nums}[i-2] = \textit{nums}[i-3],&i>2\\ -dp[i-3]\ \text{AND}\ \textit{nums}[i-1] = \textit{nums}[i-2]+1 = \textit{nums}[i-3]+2,&i>2 -\end{cases} -$$ - -答案为 $dp[n]$。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。 - -### **Python3** - - - ```python class Solution: def validPartition(self, nums: List[int]) -> bool: @@ -105,30 +80,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def validPartition(self, nums: List[int]) -> bool: - n = len(nums) - dp = [False] * (n + 1) - dp[0] = True - for i in range(2, n + 1): - if nums[i - 1] == nums[i - 2]: - dp[i] = dp[i] or dp[i - 2] - if i > 2 and nums[i - 1] == nums[i - 2] == nums[i - 3]: - dp[i] = dp[i] or dp[i - 3] - if ( - i > 2 - and nums[i - 1] - nums[i - 2] == 1 - and nums[i - 2] - nums[i - 3] == 1 - ): - dp[i] = dp[i] or dp[i - 3] - return dp[-1] -``` - -### **Java** - - - ```java class Solution { private int n; @@ -166,30 +117,6 @@ class Solution { } ``` -```java -class Solution { - public boolean validPartition(int[] nums) { - int n = nums.length; - boolean[] dp = new boolean[n + 1]; - dp[0] = true; - for (int i = 2; i <= n; ++i) { - if (nums[i - 1] == nums[i - 2]) { - dp[i] = dp[i] || dp[i - 2]; - } - if (i > 2 && nums[i - 1] == nums[i - 2] && nums[i - 2] == nums[i - 3]) { - dp[i] = dp[i] || dp[i - 3]; - } - if (i > 2 && nums[i - 1] - nums[i - 2] == 1 && nums[i - 2] - nums[i - 3] == 1) { - dp[i] = dp[i] || dp[i - 3]; - } - } - return dp[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -217,25 +144,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool validPartition(vector& nums) { - int n = nums.size(); - vector dp(n + 1); - dp[0] = true; - for (int i = 2; i <= n; ++i) { - if (nums[i - 1] == nums[i - 2]) dp[i] = dp[i] || dp[i - 2]; - if (i > 2 && nums[i - 1] == nums[i - 2] && nums[i - 2] == nums[i - 3]) dp[i] = dp[i] || dp[i - 3]; - if (i > 2 && nums[i - 1] - nums[i - 2] == 1 && nums[i - 2] - nums[i - 3] == 1) dp[i] = dp[i] || dp[i - 3]; - } - return dp[n]; - } -}; -``` - -### **Go** - ```go func validPartition(nums []int) bool { n := len(nums) @@ -271,28 +179,6 @@ func validPartition(nums []int) bool { } ``` -```go -func validPartition(nums []int) bool { - n := len(nums) - dp := make([]bool, n+1) - dp[0] = true - for i := 2; i <= n; i++ { - if nums[i-1] == nums[i-2] { - dp[i] = dp[i] || dp[i-2] - } - if i > 2 && nums[i-1] == nums[i-2] && nums[i-2] == nums[i-3] { - dp[i] = dp[i] || dp[i-3] - } - if i > 2 && nums[i-1]-nums[i-2] == 1 && nums[i-2]-nums[i-3] == 1 { - dp[i] = dp[i] || dp[i-3] - } - } - return dp[n] -} -``` - -### **TypeScript** - ```ts function validPartition(nums: number[]): boolean { const n = nums.length; @@ -324,6 +210,108 @@ function validPartition(nums: number[]): boolean { } ``` + + +### 方法二:动态规划 + +设 $dp[i]$ 表示数组前 $i$ 个元素是否至少存在一个有效的划分。初始时 $dp[0]=true$, $dp[1]=false$。 + +根据题意,当 $i \ge 2$ 时,有 + +$$ +dp[i] = \text{OR} +\begin{cases} +dp[i-2]\ \text{AND}\ \textit{nums}[i-1] = \textit{nums}[i-2],&i>1\\ +dp[i-3]\ \text{AND}\ \textit{nums}[i-1] = \textit{nums}[i-2] = \textit{nums}[i-3],&i>2\\ +dp[i-3]\ \text{AND}\ \textit{nums}[i-1] = \textit{nums}[i-2]+1 = \textit{nums}[i-3]+2,&i>2 +\end{cases} +$$ + +答案为 $dp[n]$。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。 + + + +```python +class Solution: + def validPartition(self, nums: List[int]) -> bool: + n = len(nums) + dp = [False] * (n + 1) + dp[0] = True + for i in range(2, n + 1): + if nums[i - 1] == nums[i - 2]: + dp[i] = dp[i] or dp[i - 2] + if i > 2 and nums[i - 1] == nums[i - 2] == nums[i - 3]: + dp[i] = dp[i] or dp[i - 3] + if ( + i > 2 + and nums[i - 1] - nums[i - 2] == 1 + and nums[i - 2] - nums[i - 3] == 1 + ): + dp[i] = dp[i] or dp[i - 3] + return dp[-1] +``` + +```java +class Solution { + public boolean validPartition(int[] nums) { + int n = nums.length; + boolean[] dp = new boolean[n + 1]; + dp[0] = true; + for (int i = 2; i <= n; ++i) { + if (nums[i - 1] == nums[i - 2]) { + dp[i] = dp[i] || dp[i - 2]; + } + if (i > 2 && nums[i - 1] == nums[i - 2] && nums[i - 2] == nums[i - 3]) { + dp[i] = dp[i] || dp[i - 3]; + } + if (i > 2 && nums[i - 1] - nums[i - 2] == 1 && nums[i - 2] - nums[i - 3] == 1) { + dp[i] = dp[i] || dp[i - 3]; + } + } + return dp[n]; + } +} +``` + +```cpp +class Solution { +public: + bool validPartition(vector& nums) { + int n = nums.size(); + vector dp(n + 1); + dp[0] = true; + for (int i = 2; i <= n; ++i) { + if (nums[i - 1] == nums[i - 2]) dp[i] = dp[i] || dp[i - 2]; + if (i > 2 && nums[i - 1] == nums[i - 2] && nums[i - 2] == nums[i - 3]) dp[i] = dp[i] || dp[i - 3]; + if (i > 2 && nums[i - 1] - nums[i - 2] == 1 && nums[i - 2] - nums[i - 3] == 1) dp[i] = dp[i] || dp[i - 3]; + } + return dp[n]; + } +}; +``` + +```go +func validPartition(nums []int) bool { + n := len(nums) + dp := make([]bool, n+1) + dp[0] = true + for i := 2; i <= n; i++ { + if nums[i-1] == nums[i-2] { + dp[i] = dp[i] || dp[i-2] + } + if i > 2 && nums[i-1] == nums[i-2] && nums[i-2] == nums[i-3] { + dp[i] = dp[i] || dp[i-3] + } + if i > 2 && nums[i-1]-nums[i-2] == 1 && nums[i-2]-nums[i-3] == 1 { + dp[i] = dp[i] || dp[i-3] + } + } + return dp[n] +} +``` + ```ts function validPartition(nums: number[]): boolean { const n = nums.length; @@ -344,10 +332,6 @@ function validPartition(nums: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/README_EN.md b/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/README_EN.md index 152827fd8b83c..8705d64ee54a5 100644 --- a/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/README_EN.md +++ b/solution/2300-2399/2369.Check if There is a Valid Partition For The Array/README_EN.md @@ -44,9 +44,9 @@ This partition is valid, so we return true. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,28 +72,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def validPartition(self, nums: List[int]) -> bool: - n = len(nums) - dp = [False] * (n + 1) - dp[0] = True - for i in range(2, n + 1): - if nums[i - 1] == nums[i - 2]: - dp[i] = dp[i] or dp[i - 2] - if i > 2 and nums[i - 1] == nums[i - 2] == nums[i - 3]: - dp[i] = dp[i] or dp[i - 3] - if ( - i > 2 - and nums[i - 1] - nums[i - 2] == 1 - and nums[i - 2] - nums[i - 3] == 1 - ): - dp[i] = dp[i] or dp[i - 3] - return dp[-1] -``` - -### **Java** - ```java class Solution { private int n; @@ -131,30 +109,6 @@ class Solution { } ``` -```java -class Solution { - public boolean validPartition(int[] nums) { - int n = nums.length; - boolean[] dp = new boolean[n + 1]; - dp[0] = true; - for (int i = 2; i <= n; ++i) { - if (nums[i - 1] == nums[i - 2]) { - dp[i] = dp[i] || dp[i - 2]; - } - if (i > 2 && nums[i - 1] == nums[i - 2] && nums[i - 2] == nums[i - 3]) { - dp[i] = dp[i] || dp[i - 3]; - } - if (i > 2 && nums[i - 1] - nums[i - 2] == 1 && nums[i - 2] - nums[i - 3] == 1) { - dp[i] = dp[i] || dp[i - 3]; - } - } - return dp[n]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -182,25 +136,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool validPartition(vector& nums) { - int n = nums.size(); - vector dp(n + 1); - dp[0] = true; - for (int i = 2; i <= n; ++i) { - if (nums[i - 1] == nums[i - 2]) dp[i] = dp[i] || dp[i - 2]; - if (i > 2 && nums[i - 1] == nums[i - 2] && nums[i - 2] == nums[i - 3]) dp[i] = dp[i] || dp[i - 3]; - if (i > 2 && nums[i - 1] - nums[i - 2] == 1 && nums[i - 2] - nums[i - 3] == 1) dp[i] = dp[i] || dp[i - 3]; - } - return dp[n]; - } -}; -``` - -### **Go** - ```go func validPartition(nums []int) bool { n := len(nums) @@ -236,28 +171,6 @@ func validPartition(nums []int) bool { } ``` -```go -func validPartition(nums []int) bool { - n := len(nums) - dp := make([]bool, n+1) - dp[0] = true - for i := 2; i <= n; i++ { - if nums[i-1] == nums[i-2] { - dp[i] = dp[i] || dp[i-2] - } - if i > 2 && nums[i-1] == nums[i-2] && nums[i-2] == nums[i-3] { - dp[i] = dp[i] || dp[i-3] - } - if i > 2 && nums[i-1]-nums[i-2] == 1 && nums[i-2]-nums[i-3] == 1 { - dp[i] = dp[i] || dp[i-3] - } - } - return dp[n] -} -``` - -### **TypeScript** - ```ts function validPartition(nums: number[]): boolean { const n = nums.length; @@ -289,6 +202,91 @@ function validPartition(nums: number[]): boolean { } ``` + + +### Solution 2 + + + +```python +class Solution: + def validPartition(self, nums: List[int]) -> bool: + n = len(nums) + dp = [False] * (n + 1) + dp[0] = True + for i in range(2, n + 1): + if nums[i - 1] == nums[i - 2]: + dp[i] = dp[i] or dp[i - 2] + if i > 2 and nums[i - 1] == nums[i - 2] == nums[i - 3]: + dp[i] = dp[i] or dp[i - 3] + if ( + i > 2 + and nums[i - 1] - nums[i - 2] == 1 + and nums[i - 2] - nums[i - 3] == 1 + ): + dp[i] = dp[i] or dp[i - 3] + return dp[-1] +``` + +```java +class Solution { + public boolean validPartition(int[] nums) { + int n = nums.length; + boolean[] dp = new boolean[n + 1]; + dp[0] = true; + for (int i = 2; i <= n; ++i) { + if (nums[i - 1] == nums[i - 2]) { + dp[i] = dp[i] || dp[i - 2]; + } + if (i > 2 && nums[i - 1] == nums[i - 2] && nums[i - 2] == nums[i - 3]) { + dp[i] = dp[i] || dp[i - 3]; + } + if (i > 2 && nums[i - 1] - nums[i - 2] == 1 && nums[i - 2] - nums[i - 3] == 1) { + dp[i] = dp[i] || dp[i - 3]; + } + } + return dp[n]; + } +} +``` + +```cpp +class Solution { +public: + bool validPartition(vector& nums) { + int n = nums.size(); + vector dp(n + 1); + dp[0] = true; + for (int i = 2; i <= n; ++i) { + if (nums[i - 1] == nums[i - 2]) dp[i] = dp[i] || dp[i - 2]; + if (i > 2 && nums[i - 1] == nums[i - 2] && nums[i - 2] == nums[i - 3]) dp[i] = dp[i] || dp[i - 3]; + if (i > 2 && nums[i - 1] - nums[i - 2] == 1 && nums[i - 2] - nums[i - 3] == 1) dp[i] = dp[i] || dp[i - 3]; + } + return dp[n]; + } +}; +``` + +```go +func validPartition(nums []int) bool { + n := len(nums) + dp := make([]bool, n+1) + dp[0] = true + for i := 2; i <= n; i++ { + if nums[i-1] == nums[i-2] { + dp[i] = dp[i] || dp[i-2] + } + if i > 2 && nums[i-1] == nums[i-2] && nums[i-2] == nums[i-3] { + dp[i] = dp[i] || dp[i-3] + } + if i > 2 && nums[i-1]-nums[i-2] == 1 && nums[i-2]-nums[i-3] == 1 { + dp[i] = dp[i] || dp[i-3] + } + } + return dp[n] +} +``` + ```ts function validPartition(nums: number[]): boolean { const n = nums.length; @@ -309,10 +307,6 @@ function validPartition(nums: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2370.Longest Ideal Subsequence/README.md b/solution/2300-2399/2370.Longest Ideal Subsequence/README.md index 86a55ebaa7c41..693e619f24931 100644 --- a/solution/2300-2399/2370.Longest Ideal Subsequence/README.md +++ b/solution/2300-2399/2370.Longest Ideal Subsequence/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 设 $dp[i]$ 表示以字符 $s[i]$ 结尾的最长理想子序列的长度,利用哈希表 $d$ 记录每个字符最新出现的位置。初始时 $dp[0]=1$, $d[s[0]]=0$。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def longestIdealString(self, s: str, k: int) -> int: @@ -85,10 +79,6 @@ class Solution: return max(dp) ``` -### **Java** - - - ```java class Solution { public int longestIdealString(String s, int k) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func longestIdealString(s string, k int) int { n := len(s) @@ -169,8 +155,6 @@ func longestIdealString(s string, k int) int { } ``` -### **TypeScript** - ```ts function longestIdealString(s: string, k: number): number { const dp = new Array(26).fill(0); @@ -189,10 +173,6 @@ function longestIdealString(s: string, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2370.Longest Ideal Subsequence/README_EN.md b/solution/2300-2399/2370.Longest Ideal Subsequence/README_EN.md index 0ff89912867c8..55d8e3276abc3 100644 --- a/solution/2300-2399/2370.Longest Ideal Subsequence/README_EN.md +++ b/solution/2300-2399/2370.Longest Ideal Subsequence/README_EN.md @@ -45,9 +45,9 @@ Note that "acfgbd" is not ideal because 'c' and 'f' ha ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return max(dp) ``` -### **Java** - ```java class Solution { public int longestIdealString(String s, int k) { @@ -96,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +117,6 @@ public: }; ``` -### **Go** - ```go func longestIdealString(s string, k int) int { n := len(s) @@ -149,8 +143,6 @@ func longestIdealString(s string, k int) int { } ``` -### **TypeScript** - ```ts function longestIdealString(s: string, k: number): number { const dp = new Array(26).fill(0); @@ -169,10 +161,6 @@ function longestIdealString(s: string, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2371.Minimize Maximum Value in a Grid/README.md b/solution/2300-2399/2371.Minimize Maximum Value in a Grid/README.md index c8ed793d49d6b..0ad8e38e020e1 100644 --- a/solution/2300-2399/2371.Minimize Maximum Value in a Grid/README.md +++ b/solution/2300-2399/2371.Minimize Maximum Value in a Grid/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:排序 + 贪心** +### 方法一:排序 + 贪心 由于可以将每一个数字重新填入并且使最终矩阵的最大值最小化,可考虑贪心。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def minScore(self, grid: List[List[int]]) -> List[List[int]]: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] minScore(int[][] grid) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func minScore(grid [][]int) [][]int { m, n := len(grid), len(grid[0]) @@ -171,8 +157,6 @@ func minScore(grid [][]int) [][]int { } ``` -### **TypeScript** - ```ts function minScore(grid: number[][]): number[][] { const m = grid.length; @@ -195,10 +179,6 @@ function minScore(grid: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2371.Minimize Maximum Value in a Grid/README_EN.md b/solution/2300-2399/2371.Minimize Maximum Value in a Grid/README_EN.md index 7259a490fa792..4ae7d6d1bbb14 100644 --- a/solution/2300-2399/2371.Minimize Maximum Value in a Grid/README_EN.md +++ b/solution/2300-2399/2371.Minimize Maximum Value in a Grid/README_EN.md @@ -51,9 +51,9 @@ The maximum number in the matrix is 2. It can be shown that no smaller value can ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] minScore(int[][] grid) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func minScore(grid [][]int) [][]int { m, n := len(grid), len(grid[0]) @@ -151,8 +145,6 @@ func minScore(grid [][]int) [][]int { } ``` -### **TypeScript** - ```ts function minScore(grid: number[][]): number[][] { const m = grid.length; @@ -175,10 +167,6 @@ function minScore(grid: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2372.Calculate the Influence of Each Salesperson/README.md b/solution/2300-2399/2372.Calculate the Influence of Each Salesperson/README.md index 63c545a87118d..14fcc157de22a 100644 --- a/solution/2300-2399/2372.Calculate the Influence of Each Salesperson/README.md +++ b/solution/2300-2399/2372.Calculate the Influence of Each Salesperson/README.md @@ -112,14 +112,10 @@ Jerry 的总数是 0。 ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT sp.salesperson_id, name, IFNULL(SUM(price), 0) AS total @@ -131,3 +127,5 @@ GROUP BY 1; ``` + + diff --git a/solution/2300-2399/2372.Calculate the Influence of Each Salesperson/README_EN.md b/solution/2300-2399/2372.Calculate the Influence of Each Salesperson/README_EN.md index a07880f7a2da5..5326a837abbef 100644 --- a/solution/2300-2399/2372.Calculate the Influence of Each Salesperson/README_EN.md +++ b/solution/2300-2399/2372.Calculate the Influence of Each Salesperson/README_EN.md @@ -112,9 +112,9 @@ The total for Jerry is 0. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -127,3 +127,5 @@ GROUP BY 1; ``` + + diff --git a/solution/2300-2399/2373.Largest Local Values in a Matrix/README.md b/solution/2300-2399/2373.Largest Local Values in a Matrix/README.md index 215eca6f59010..07d39c6e9e8c6 100644 --- a/solution/2300-2399/2373.Largest Local Values in a Matrix/README.md +++ b/solution/2300-2399/2373.Largest Local Values in a Matrix/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举每个 $3 \times 3$ 的矩阵,求出每个 $3 \times 3$ 的矩阵中的最大值,然后将这些最大值放入答案矩阵中。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] largestLocal(int[][] grid) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func largestLocal(grid [][]int) [][]int { n := len(grid) @@ -144,8 +130,6 @@ func largestLocal(grid [][]int) [][]int { } ``` -### **TypeScript** - ```ts function largestLocal(grid: number[][]): number[][] { const n = grid.length; @@ -165,11 +149,6 @@ function largestLocal(grid: number[][]): number[][] { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2373.Largest Local Values in a Matrix/README_EN.md b/solution/2300-2399/2373.Largest Local Values in a Matrix/README_EN.md index 3df153e5d0ce6..a286c7edd7af6 100644 --- a/solution/2300-2399/2373.Largest Local Values in a Matrix/README_EN.md +++ b/solution/2300-2399/2373.Largest Local Values in a Matrix/README_EN.md @@ -44,9 +44,9 @@ Notice that each value in the generated matrix corresponds to the largest value ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] largestLocal(int[][] grid) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +100,6 @@ public: }; ``` -### **Go** - ```go func largestLocal(grid [][]int) [][]int { n := len(grid) @@ -124,8 +118,6 @@ func largestLocal(grid [][]int) [][]int { } ``` -### **TypeScript** - ```ts function largestLocal(grid: number[][]): number[][] { const n = grid.length; @@ -145,11 +137,6 @@ function largestLocal(grid: number[][]): number[][] { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2374.Node With Highest Edge Score/README.md b/solution/2300-2399/2374.Node With Highest Edge Score/README.md index a025f21482746..47930df6e3100 100644 --- a/solution/2300-2399/2374.Node With Highest Edge Score/README.md +++ b/solution/2300-2399/2374.Node With Highest Edge Score/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:遍历计数** +### 方法一:遍历计数 定义 $cnt$,其中每个元素 $cnt[i]$ 表示到节点 $i$ 的所有节点编号之和。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def edgeScore(self, edges: List[int]) -> int: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int edgeScore(int[] edges) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func edgeScore(edges []int) int { n := len(edges) @@ -144,8 +130,6 @@ func edgeScore(edges []int) int { } ``` -### **TypeScript** - ```ts function edgeScore(edges: number[]): number { const n = edges.length; @@ -163,11 +147,6 @@ function edgeScore(edges: number[]): number { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2374.Node With Highest Edge Score/README_EN.md b/solution/2300-2399/2374.Node With Highest Edge Score/README_EN.md index d2b3edba935ea..cec367a78536b 100644 --- a/solution/2300-2399/2374.Node With Highest Edge Score/README_EN.md +++ b/solution/2300-2399/2374.Node With Highest Edge Score/README_EN.md @@ -49,9 +49,9 @@ Nodes 0 and 2 both have an edge score of 3. Since node 0 has a smaller index, we ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int edgeScore(int[] edges) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +105,6 @@ public: }; ``` -### **Go** - ```go func edgeScore(edges []int) int { n := len(edges) @@ -128,8 +122,6 @@ func edgeScore(edges []int) int { } ``` -### **TypeScript** - ```ts function edgeScore(edges: number[]): number { const n = edges.length; @@ -147,11 +139,6 @@ function edgeScore(edges: number[]): number { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2375.Construct Smallest Number From DI String/README.md b/solution/2300-2399/2375.Construct Smallest Number From DI String/README.md index 5c635bd1d75ad..170d1304be18e 100644 --- a/solution/2300-2399/2375.Construct Smallest Number From DI String/README.md +++ b/solution/2300-2399/2375.Construct Smallest Number From DI String/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 定义 $dfs(u)$,其中 $u$ 表示当前答案字符串的长度。从 $u=0$ 开始搜索,直至找到第一个符合条件的字符串。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def smallestNumber(self, pattern: str) -> str: @@ -96,10 +90,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private boolean[] vis = new boolean[10]; @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -178,8 +166,6 @@ public: }; ``` -### **Go** - ```go func smallestNumber(pattern string) string { vis := make([]bool, 10) @@ -215,8 +201,6 @@ func smallestNumber(pattern string) string { } ``` -### **TypeScript** - ```ts function smallestNumber(pattern: string): string { const n = pattern.length; @@ -272,11 +256,6 @@ function smallestNumber(pattern: string): string { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2375.Construct Smallest Number From DI String/README_EN.md b/solution/2300-2399/2375.Construct Smallest Number From DI String/README_EN.md index 2c96fb3775e94..19325f6689d59 100644 --- a/solution/2300-2399/2375.Construct Smallest Number From DI String/README_EN.md +++ b/solution/2300-2399/2375.Construct Smallest Number From DI String/README_EN.md @@ -49,9 +49,9 @@ It can be proven that "4321" is the smallest possible num that meets t ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private boolean[] vis = new boolean[10]; @@ -124,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +158,6 @@ public: }; ``` -### **Go** - ```go func smallestNumber(pattern string) string { vis := make([]bool, 10) @@ -199,8 +193,6 @@ func smallestNumber(pattern string) string { } ``` -### **TypeScript** - ```ts function smallestNumber(pattern: string): string { const n = pattern.length; @@ -256,11 +248,6 @@ function smallestNumber(pattern: string): string { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2376.Count Special Integers/README.md b/solution/2300-2399/2376.Count Special Integers/README.md index a9eed6e82c1c4..c4a6b01fb18a7 100644 --- a/solution/2300-2399/2376.Count Special Integers/README.md +++ b/solution/2300-2399/2376.Count Special Integers/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:数位 DP** +### 方法一:数位 DP 定义 $m$ 表示数字 $n$ 的位数。我们可以将数字分成两类:(1) 数字位数小于 $m$;(2) 数字位数等于 $m$。 @@ -77,10 +75,6 @@ $$ -### **Python3** - - - ```python class Solution: def countSpecialNumbers(self, n: int) -> int: @@ -108,40 +102,6 @@ class Solution: return ans ``` -```python -class Solution: - def countSpecialNumbers(self, n: int) -> int: - return self.f(n) - - def f(self, n): - @cache - def dfs(pos, mask, lead, limit): - if pos <= 0: - return lead ^ 1 - up = a[pos] if limit else 9 - ans = 0 - for i in range(up + 1): - if (mask >> i) & 1: - continue - if i == 0 and lead: - ans += dfs(pos - 1, mask, lead, limit and i == up) - else: - ans += dfs(pos - 1, mask | 1 << i, False, limit and i == up) - return ans - - a = [0] * 11 - l = 0 - while n: - l += 1 - a[l] = n % 10 - n //= 10 - return dfs(l, 0, True, True) -``` - -### **Java** - - - ```java class Solution { public int countSpecialNumbers(int n) { @@ -181,6 +141,124 @@ class Solution { } ``` +```cpp +class Solution { +public: + int countSpecialNumbers(int n) { + int ans = 0; + vector digits; + while (n) { + digits.push_back(n % 10); + n /= 10; + } + int m = digits.size(); + vector vis(10); + for (int i = 1; i < m; ++i) { + ans += 9 * A(9, i - 1); + } + for (int i = m - 1; ~i; --i) { + int v = digits[i]; + for (int j = i == m - 1 ? 1 : 0; j < v; ++j) { + if (!vis[j]) { + ans += A(10 - (m - i), i); + } + } + if (vis[v]) { + break; + } + vis[v] = true; + if (i == 0) { + ++ans; + } + } + return ans; + } + + int A(int m, int n) { + return n == 0 ? 1 : A(m, n - 1) * (m - n + 1); + } +}; +``` + +```go +func countSpecialNumbers(n int) int { + digits := []int{} + for n != 0 { + digits = append(digits, n%10) + n /= 10 + } + m := len(digits) + vis := make([]bool, 10) + ans := 0 + for i := 1; i < m; i++ { + ans += 9 * A(9, i-1) + } + for i := m - 1; i >= 0; i-- { + v := digits[i] + j := 0 + if i == m-1 { + j = 1 + } + for ; j < v; j++ { + if !vis[j] { + ans += A(10-(m-i), i) + } + } + if vis[v] { + break + } + vis[v] = true + if i == 0 { + ans++ + } + } + return ans +} + +func A(m, n int) int { + if n == 0 { + return 1 + } + return A(m, n-1) * (m - n + 1) +} +``` + + + +### 方法二 + + + +```python +class Solution: + def countSpecialNumbers(self, n: int) -> int: + return self.f(n) + + def f(self, n): + @cache + def dfs(pos, mask, lead, limit): + if pos <= 0: + return lead ^ 1 + up = a[pos] if limit else 9 + ans = 0 + for i in range(up + 1): + if (mask >> i) & 1: + continue + if i == 0 and lead: + ans += dfs(pos - 1, mask, lead, limit and i == up) + else: + ans += dfs(pos - 1, mask | 1 << i, False, limit and i == up) + return ans + + a = [0] * 11 + l = 0 + while n: + l += 1 + a[l] = n % 10 + n //= 10 + return dfs(l, 0, True, True) +``` + ```java class Solution { private int[] a = new int[11]; @@ -229,47 +307,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int countSpecialNumbers(int n) { - int ans = 0; - vector digits; - while (n) { - digits.push_back(n % 10); - n /= 10; - } - int m = digits.size(); - vector vis(10); - for (int i = 1; i < m; ++i) { - ans += 9 * A(9, i - 1); - } - for (int i = m - 1; ~i; --i) { - int v = digits[i]; - for (int j = i == m - 1 ? 1 : 0; j < v; ++j) { - if (!vis[j]) { - ans += A(10 - (m - i), i); - } - } - if (vis[v]) { - break; - } - vis[v] = true; - if (i == 0) { - ++ans; - } - } - return ans; - } - - int A(int m, int n) { - return n == 0 ? 1 : A(m, n - 1) * (m - n + 1); - } -}; -``` - ```cpp class Solution { public: @@ -315,51 +352,6 @@ public: }; ``` -### **Go** - -```go -func countSpecialNumbers(n int) int { - digits := []int{} - for n != 0 { - digits = append(digits, n%10) - n /= 10 - } - m := len(digits) - vis := make([]bool, 10) - ans := 0 - for i := 1; i < m; i++ { - ans += 9 * A(9, i-1) - } - for i := m - 1; i >= 0; i-- { - v := digits[i] - j := 0 - if i == m-1 { - j = 1 - } - for ; j < v; j++ { - if !vis[j] { - ans += A(10-(m-i), i) - } - } - if vis[v] { - break - } - vis[v] = true - if i == 0 { - ans++ - } - } - return ans -} - -func A(m, n int) int { - if n == 0 { - return 1 - } - return A(m, n-1) * (m - n + 1) -} -``` - ```go func countSpecialNumbers(n int) int { return f(n) @@ -416,17 +408,6 @@ func f(n int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2376.Count Special Integers/README_EN.md b/solution/2300-2399/2376.Count Special Integers/README_EN.md index f7658664df949..cba12a93f4c76 100644 --- a/solution/2300-2399/2376.Count Special Integers/README_EN.md +++ b/solution/2300-2399/2376.Count Special Integers/README_EN.md @@ -42,9 +42,9 @@ Some of the integers that are not special are: 22, 114, and 131. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,38 +73,6 @@ class Solution: return ans ``` -```python -class Solution: - def countSpecialNumbers(self, n: int) -> int: - return self.f(n) - - def f(self, n): - @cache - def dfs(pos, mask, lead, limit): - if pos <= 0: - return lead ^ 1 - up = a[pos] if limit else 9 - ans = 0 - for i in range(up + 1): - if (mask >> i) & 1: - continue - if i == 0 and lead: - ans += dfs(pos - 1, mask, lead, limit and i == up) - else: - ans += dfs(pos - 1, mask | 1 << i, False, limit and i == up) - return ans - - a = [0] * 11 - l = 0 - while n: - l += 1 - a[l] = n % 10 - n //= 10 - return dfs(l, 0, True, True) -``` - -### **Java** - ```java class Solution { public int countSpecialNumbers(int n) { @@ -144,6 +112,124 @@ class Solution { } ``` +```cpp +class Solution { +public: + int countSpecialNumbers(int n) { + int ans = 0; + vector digits; + while (n) { + digits.push_back(n % 10); + n /= 10; + } + int m = digits.size(); + vector vis(10); + for (int i = 1; i < m; ++i) { + ans += 9 * A(9, i - 1); + } + for (int i = m - 1; ~i; --i) { + int v = digits[i]; + for (int j = i == m - 1 ? 1 : 0; j < v; ++j) { + if (!vis[j]) { + ans += A(10 - (m - i), i); + } + } + if (vis[v]) { + break; + } + vis[v] = true; + if (i == 0) { + ++ans; + } + } + return ans; + } + + int A(int m, int n) { + return n == 0 ? 1 : A(m, n - 1) * (m - n + 1); + } +}; +``` + +```go +func countSpecialNumbers(n int) int { + digits := []int{} + for n != 0 { + digits = append(digits, n%10) + n /= 10 + } + m := len(digits) + vis := make([]bool, 10) + ans := 0 + for i := 1; i < m; i++ { + ans += 9 * A(9, i-1) + } + for i := m - 1; i >= 0; i-- { + v := digits[i] + j := 0 + if i == m-1 { + j = 1 + } + for ; j < v; j++ { + if !vis[j] { + ans += A(10-(m-i), i) + } + } + if vis[v] { + break + } + vis[v] = true + if i == 0 { + ans++ + } + } + return ans +} + +func A(m, n int) int { + if n == 0 { + return 1 + } + return A(m, n-1) * (m - n + 1) +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def countSpecialNumbers(self, n: int) -> int: + return self.f(n) + + def f(self, n): + @cache + def dfs(pos, mask, lead, limit): + if pos <= 0: + return lead ^ 1 + up = a[pos] if limit else 9 + ans = 0 + for i in range(up + 1): + if (mask >> i) & 1: + continue + if i == 0 and lead: + ans += dfs(pos - 1, mask, lead, limit and i == up) + else: + ans += dfs(pos - 1, mask | 1 << i, False, limit and i == up) + return ans + + a = [0] * 11 + l = 0 + while n: + l += 1 + a[l] = n % 10 + n //= 10 + return dfs(l, 0, True, True) +``` + ```java class Solution { private int[] a = new int[11]; @@ -192,47 +278,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int countSpecialNumbers(int n) { - int ans = 0; - vector digits; - while (n) { - digits.push_back(n % 10); - n /= 10; - } - int m = digits.size(); - vector vis(10); - for (int i = 1; i < m; ++i) { - ans += 9 * A(9, i - 1); - } - for (int i = m - 1; ~i; --i) { - int v = digits[i]; - for (int j = i == m - 1 ? 1 : 0; j < v; ++j) { - if (!vis[j]) { - ans += A(10 - (m - i), i); - } - } - if (vis[v]) { - break; - } - vis[v] = true; - if (i == 0) { - ++ans; - } - } - return ans; - } - - int A(int m, int n) { - return n == 0 ? 1 : A(m, n - 1) * (m - n + 1); - } -}; -``` - ```cpp class Solution { public: @@ -278,51 +323,6 @@ public: }; ``` -### **Go** - -```go -func countSpecialNumbers(n int) int { - digits := []int{} - for n != 0 { - digits = append(digits, n%10) - n /= 10 - } - m := len(digits) - vis := make([]bool, 10) - ans := 0 - for i := 1; i < m; i++ { - ans += 9 * A(9, i-1) - } - for i := m - 1; i >= 0; i-- { - v := digits[i] - j := 0 - if i == m-1 { - j = 1 - } - for ; j < v; j++ { - if !vis[j] { - ans += A(10-(m-i), i) - } - } - if vis[v] { - break - } - vis[v] = true - if i == 0 { - ans++ - } - } - return ans -} - -func A(m, n int) int { - if n == 0 { - return 1 - } - return A(m, n-1) * (m - n + 1) -} -``` - ```go func countSpecialNumbers(n int) int { return f(n) @@ -379,17 +379,6 @@ func f(n int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2377.Sort the Olympic Table/README.md b/solution/2300-2399/2377.Sort the Olympic Table/README.md index 39a85c3b78d53..91bcbf8e0d054 100644 --- a/solution/2300-2399/2377.Sort the Olympic Table/README.md +++ b/solution/2300-2399/2377.Sort the Olympic Table/README.md @@ -68,14 +68,10 @@ Olympic 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT * @@ -84,3 +80,5 @@ ORDER BY 2 DESC, 3 DESC, 4 DESC, 1; ``` + + diff --git a/solution/2300-2399/2377.Sort the Olympic Table/README_EN.md b/solution/2300-2399/2377.Sort the Olympic Table/README_EN.md index cb217cfceeb3a..5c701ff3010d4 100644 --- a/solution/2300-2399/2377.Sort the Olympic Table/README_EN.md +++ b/solution/2300-2399/2377.Sort the Olympic Table/README_EN.md @@ -66,9 +66,9 @@ Israel comes before Egypt because it has more bronze medals. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -78,3 +78,5 @@ ORDER BY 2 DESC, 3 DESC, 4 DESC, 1; ``` + + diff --git a/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README.md b/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README.md index da9e6209ad320..5ad2785648072 100644 --- a/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README.md +++ b/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:树形 DP** +### 方法一:树形 DP 我们设计一个函数 $dfs(i)$,表示以节点 $i$ 为根的子树中,选择一些边,使得所选的两条边都不相邻,所选边的权值之和最大。该函数返回了两个值 $(a, b)$,第一个值 $a$ 表示当前节点 $i$ 与其父节点之间的边被选中时,所选边的权值之和;第二个值 $b$ 表示当前节点 $i$ 与其父节点之间的边不被选中时,所选边的权值之和。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def maxScore(self, edges: List[List[int]]) -> int: @@ -105,10 +99,6 @@ class Solution: return dfs(0)[1] ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go func maxScore(edges [][]int) int64 { n := len(edges) @@ -196,17 +182,6 @@ func maxScore(edges [][]int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README_EN.md b/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README_EN.md index 48f3e711c3d0a..e84cfc48fb54c 100644 --- a/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README_EN.md +++ b/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README_EN.md @@ -59,9 +59,9 @@ Note that we cannot choose more than one edge because all edges are adjacent to ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,8 +82,6 @@ class Solution: return dfs(0)[1] ``` -### **Java** - ```java class Solution { private List[] g; @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +140,6 @@ public: }; ``` -### **Go** - ```go func maxScore(edges [][]int) int64 { n := len(edges) @@ -171,17 +165,6 @@ func maxScore(edges [][]int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/README.md b/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/README.md index 341786acddcfa..6994989a142cd 100644 --- a/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/README.md +++ b/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 我们观察发现,题目实际上求的是一个 $k$ 大小的滑动窗口中白色块的最小数量。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumRecolors(String blocks, int k) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func minimumRecolors(blocks string, k int) int { cnt := strings.Count(blocks[:k], "W") @@ -141,8 +127,6 @@ func minimumRecolors(blocks string, k int) int { } ``` -### **TypeScript** - ```ts function minimumRecolors(blocks: string, k: number): number { let cnt = 0; @@ -159,8 +143,6 @@ function minimumRecolors(blocks: string, k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn minimum_recolors(blocks: String, k: i32) -> i32 { @@ -188,29 +170,6 @@ impl Solution { } ``` -### **C** - -```c -#define min(a, b) (((a) < (b)) ? (a) : (b)) - -int minimumRecolors(char* blocks, int k) { - int n = strlen(blocks); - int count = 0; - for (int i = 0; i < k; i++) { - count += blocks[i] == 'B'; - } - int ans = k - count; - for (int i = k; i < n; i++) { - count -= blocks[i - k] == 'B'; - count += blocks[i] == 'B'; - ans = min(ans, k - count); - } - return ans; -} -``` - -### **PHP** - ```php class Solution { /** @@ -240,10 +199,25 @@ class Solution { } ``` -### **...** - -``` +```c +#define min(a, b) (((a) < (b)) ? (a) : (b)) +int minimumRecolors(char* blocks, int k) { + int n = strlen(blocks); + int count = 0; + for (int i = 0; i < k; i++) { + count += blocks[i] == 'B'; + } + int ans = k - count; + for (int i = k; i < n; i++) { + count -= blocks[i - k] == 'B'; + count += blocks[i] == 'B'; + ans = min(ans, k - count); + } + return ans; +} ``` + + diff --git a/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/README_EN.md b/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/README_EN.md index 8c8b87160b256..f61aee19e9de7 100644 --- a/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/README_EN.md +++ b/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/README_EN.md @@ -47,9 +47,9 @@ Therefore, we return 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumRecolors(String blocks, int k) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +96,6 @@ public: }; ``` -### **Go** - ```go func minimumRecolors(blocks string, k int) int { cnt := strings.Count(blocks[:k], "W") @@ -121,8 +115,6 @@ func minimumRecolors(blocks string, k int) int { } ``` -### **TypeScript** - ```ts function minimumRecolors(blocks: string, k: number): number { let cnt = 0; @@ -139,8 +131,6 @@ function minimumRecolors(blocks: string, k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn minimum_recolors(blocks: String, k: i32) -> i32 { @@ -168,29 +158,6 @@ impl Solution { } ``` -### **C** - -```c -#define min(a, b) (((a) < (b)) ? (a) : (b)) - -int minimumRecolors(char* blocks, int k) { - int n = strlen(blocks); - int count = 0; - for (int i = 0; i < k; i++) { - count += blocks[i] == 'B'; - } - int ans = k - count; - for (int i = k; i < n; i++) { - count -= blocks[i - k] == 'B'; - count += blocks[i] == 'B'; - ans = min(ans, k - count); - } - return ans; -} -``` - -### **PHP** - ```php class Solution { /** @@ -220,10 +187,25 @@ class Solution { } ``` -### **...** - -``` +```c +#define min(a, b) (((a) < (b)) ? (a) : (b)) +int minimumRecolors(char* blocks, int k) { + int n = strlen(blocks); + int count = 0; + for (int i = 0; i < k; i++) { + count += blocks[i] == 'B'; + } + int ans = k - count; + for (int i = k; i < n; i++) { + count -= blocks[i - k] == 'B'; + count += blocks[i] == 'B'; + ans = min(ans, k - count); + } + return ans; +} ``` + + diff --git a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/README.md b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/README.md index 3d1f7fedef6c6..7a708b0cb53a0 100644 --- a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/README.md +++ b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/README.md @@ -53,45 +53,14 @@ s 中没有 "01" 存在,整个过程花费 0 秒。 ## 解法 - - -**方法一:暴力模拟** +### 方法一:暴力模拟 由于本题数据范围不大,所以可以暴力模拟,每一轮将字符串中所有 “01” 替换为 “10”,统计轮次作为答案。 时间复杂度 $O(n^2)$。每一轮时间复杂度 $O(n)$,最多进行 $n$ 轮操作。 -**方法二:动态规划** - -题目要把所有“01”串替换为“10”,实际上是将所有的“1”往左移动。操作过后,左侧均为“1”,而右侧均为“0”。 - -假如我们要把“0100010”重排为“1100000”,会出现两种情况: - -1. 如果一个“1”左边有 $cnt$ 个“0”,那么将这个“1”移动到最左边的位置需要 $cnt$ 秒; -1. 如果有连续的“1”,则将这两个“1”移动到最左边的位置需要额外的 $1$ 秒。 - -看下面的示例: - -| 时刻(秒) | 示例 1 | 示例 2 | -| ---------- | ------ | ------ | -| 0 | 0001 | 00011 | -| 1 | 0010 | 00101 | -| 2 | 0100 | 01010 | -| 3 | 1000 | 10100 | -| 4 | - | 11000 | - -我们可以看到,如果在 $cnt$ 个“0”之后只有一个“1”,那么只需要 $cnt$ 秒,如果有连续的“1”,则需要额外的 $1$ 秒。 - -因此,对于字符串中的每一个“1”,我们计算 $ans=max(ans+1, cnt)$。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def secondsToRemoveOccurrences(self, s: str) -> int: @@ -102,22 +71,6 @@ class Solution: return ans ``` -```python -class Solution: - def secondsToRemoveOccurrences(self, s: str) -> int: - ans = cnt = 0 - for c in s: - if c == '0': - cnt += 1 - elif cnt: - ans = max(ans + 1, cnt) - return ans -``` - -### **Java** - - - ```java class Solution { public int secondsToRemoveOccurrences(String s) { @@ -144,24 +97,6 @@ class Solution { } ``` -```java -class Solution { - public int secondsToRemoveOccurrences(String s) { - int ans = 0, cnt = 0; - for (char c : s.toCharArray()) { - if (c == '0') { - ++cnt; - } else if (cnt > 0) { - ans = Math.max(ans + 1, cnt); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -186,25 +121,6 @@ public: }; ``` -```cpp -class Solution { -public: - int secondsToRemoveOccurrences(string s) { - int ans = 0, cnt = 0; - for (char c : s) { - if (c == '0') { - ++cnt; - } else if (cnt) { - ans = max(ans + 1, cnt); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func secondsToRemoveOccurrences(s string) int { cs := []byte(s) @@ -227,6 +143,80 @@ func secondsToRemoveOccurrences(s string) int { } ``` + + +### 方法二:动态规划 + +题目要把所有“01”串替换为“10”,实际上是将所有的“1”往左移动。操作过后,左侧均为“1”,而右侧均为“0”。 + +假如我们要把“0100010”重排为“1100000”,会出现两种情况: + +1. 如果一个“1”左边有 $cnt$ 个“0”,那么将这个“1”移动到最左边的位置需要 $cnt$ 秒; +1. 如果有连续的“1”,则将这两个“1”移动到最左边的位置需要额外的 $1$ 秒。 + +看下面的示例: + +| 时刻(秒) | 示例 1 | 示例 2 | +| ---------- | ------ | ------ | +| 0 | 0001 | 00011 | +| 1 | 0010 | 00101 | +| 2 | 0100 | 01010 | +| 3 | 1000 | 10100 | +| 4 | - | 11000 | + +我们可以看到,如果在 $cnt$ 个“0”之后只有一个“1”,那么只需要 $cnt$ 秒,如果有连续的“1”,则需要额外的 $1$ 秒。 + +因此,对于字符串中的每一个“1”,我们计算 $ans=max(ans+1, cnt)$。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def secondsToRemoveOccurrences(self, s: str) -> int: + ans = cnt = 0 + for c in s: + if c == '0': + cnt += 1 + elif cnt: + ans = max(ans + 1, cnt) + return ans +``` + +```java +class Solution { + public int secondsToRemoveOccurrences(String s) { + int ans = 0, cnt = 0; + for (char c : s.toCharArray()) { + if (c == '0') { + ++cnt; + } else if (cnt > 0) { + ans = Math.max(ans + 1, cnt); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int secondsToRemoveOccurrences(string s) { + int ans = 0, cnt = 0; + for (char c : s) { + if (c == '0') { + ++cnt; + } else if (cnt) { + ans = max(ans + 1, cnt); + } + } + return ans; + } +}; +``` + ```go func secondsToRemoveOccurrences(s string) int { ans, cnt := 0, 0 @@ -241,17 +231,6 @@ func secondsToRemoveOccurrences(s string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/README_EN.md b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/README_EN.md index f6f6015a66ac8..609b6c53f854d 100644 --- a/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/README_EN.md +++ b/solution/2300-2399/2380.Time Needed to Rearrange a Binary String/README_EN.md @@ -48,9 +48,9 @@ so we return 0. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,20 +62,6 @@ class Solution: return ans ``` -```python -class Solution: - def secondsToRemoveOccurrences(self, s: str) -> int: - ans = cnt = 0 - for c in s: - if c == '0': - cnt += 1 - elif cnt: - ans = max(ans + 1, cnt) - return ans -``` - -### **Java** - ```java class Solution { public int secondsToRemoveOccurrences(String s) { @@ -102,24 +88,6 @@ class Solution { } ``` -```java -class Solution { - public int secondsToRemoveOccurrences(String s) { - int ans = 0, cnt = 0; - for (char c : s.toCharArray()) { - if (c == '0') { - ++cnt; - } else if (cnt > 0) { - ans = Math.max(ans + 1, cnt); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -144,25 +112,6 @@ public: }; ``` -```cpp -class Solution { -public: - int secondsToRemoveOccurrences(string s) { - int ans = 0, cnt = 0; - for (char c : s) { - if (c == '0') { - ++cnt; - } else if (cnt) { - ans = max(ans + 1, cnt); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func secondsToRemoveOccurrences(s string) int { cs := []byte(s) @@ -185,6 +134,57 @@ func secondsToRemoveOccurrences(s string) int { } ``` + + +### Solution 2 + + + +```python +class Solution: + def secondsToRemoveOccurrences(self, s: str) -> int: + ans = cnt = 0 + for c in s: + if c == '0': + cnt += 1 + elif cnt: + ans = max(ans + 1, cnt) + return ans +``` + +```java +class Solution { + public int secondsToRemoveOccurrences(String s) { + int ans = 0, cnt = 0; + for (char c : s.toCharArray()) { + if (c == '0') { + ++cnt; + } else if (cnt > 0) { + ans = Math.max(ans + 1, cnt); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int secondsToRemoveOccurrences(string s) { + int ans = 0, cnt = 0; + for (char c : s) { + if (c == '0') { + ++cnt; + } else if (cnt) { + ans = max(ans + 1, cnt); + } + } + return ans; + } +}; +``` + ```go func secondsToRemoveOccurrences(s string) int { ans, cnt := 0, 0 @@ -199,17 +199,6 @@ func secondsToRemoveOccurrences(s string) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2381.Shifting Letters II/README.md b/solution/2300-2399/2381.Shifting Letters II/README.md index fbe4860d704ae..b739b404d965f 100644 --- a/solution/2300-2399/2381.Shifting Letters II/README.md +++ b/solution/2300-2399/2381.Shifting Letters II/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 用差分数组 $d$ 记录区间的变化,然后对 $d$ 求前缀和,得到每个下标 $i$ 的变化量 $d[i]$。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: @@ -77,10 +71,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public String shiftingLetters(String s, int[][] shifts) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func shiftingLetters(s string, shifts [][]int) string { n := len(s) @@ -159,17 +145,6 @@ func shiftingLetters(s string, shifts [][]int) string { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2381.Shifting Letters II/README_EN.md b/solution/2300-2399/2381.Shifting Letters II/README_EN.md index 5f3e13c67ce83..36842329c97de 100644 --- a/solution/2300-2399/2381.Shifting Letters II/README_EN.md +++ b/solution/2300-2399/2381.Shifting Letters II/README_EN.md @@ -42,9 +42,9 @@ Finally, shift the characters from index 1 to index 1 forward. Now s = "cat ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public String shiftingLetters(String s, int[][] shifts) { @@ -90,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func shiftingLetters(s string, shifts [][]int) string { n := len(s) @@ -143,17 +137,6 @@ func shiftingLetters(s string, shifts [][]int) string { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2382.Maximum Segment Sum After Removals/README.md b/solution/2300-2399/2382.Maximum Segment Sum After Removals/README.md index d6a366653ce1b..3f6576400ea92 100644 --- a/solution/2300-2399/2382.Maximum Segment Sum After Removals/README.md +++ b/solution/2300-2399/2382.Maximum Segment Sum After Removals/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:逆向思维 + 并查集** +### 方法一:逆向思维 + 并查集 考虑**从后往前遍历**数组 $removeQueries$ 中的每个元素 $i$,用并查集来维护以 $nums[i]$ 所在的连续子数组的和。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]: @@ -104,10 +98,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -152,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -193,8 +181,6 @@ public: }; ``` -### **Go** - ```go func maximumSegmentSum(nums []int, removeQueries []int) []int64 { n := len(nums) @@ -233,17 +219,6 @@ func maximumSegmentSum(nums []int, removeQueries []int) []int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2382.Maximum Segment Sum After Removals/README_EN.md b/solution/2300-2399/2382.Maximum Segment Sum After Removals/README_EN.md index d627c0d351749..3cf01cb5a757b 100644 --- a/solution/2300-2399/2382.Maximum Segment Sum After Removals/README_EN.md +++ b/solution/2300-2399/2382.Maximum Segment Sum After Removals/README_EN.md @@ -52,9 +52,9 @@ Finally, we return [16,5,3,0]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -86,8 +86,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] p; @@ -132,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -173,8 +169,6 @@ public: }; ``` -### **Go** - ```go func maximumSegmentSum(nums []int, removeQueries []int) []int64 { n := len(nums) @@ -213,17 +207,6 @@ func maximumSegmentSum(nums []int, removeQueries []int) []int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README.md b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README.md index beaf837fbbbae..ec7a357286675 100644 --- a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README.md +++ b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:贪心 + 模拟** +### 方法一:贪心 + 模拟 对上对手时,需要满足经验和精力都严格超过对手,因此,我们遍历 $n$ 个对手,若经验或者精力不足以超过对手,则补到刚好能超过(每次训练,可以增加 $1$)。然后增加对应的经验值,减少对应的精力值。 @@ -67,22 +65,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是对手的数量。 -**方法二:贪心** - -我们可以先在初始时,把精力直接补充到足够击败这 $n$ 个对手,因此初始训练小时数为 $ans = \max(0, (\sum_{i=0}^{n-1} energy[i]) - initialEnergy + 1)$。 - -接下来我们只需考虑经验值的问题。遍历 $n$ 个对手,若当前经验不足以超过对手,则将经验补到刚好能超过该对手,击败对手后,把对手的经验值加到自己身上。 - -遍历结束,返回训练的小时数。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是对手的数量。 - -### **Python3** - - - ```python class Solution: def minNumberOfHours( @@ -105,28 +89,6 @@ class Solution: return ans ``` -```python -class Solution: - def minNumberOfHours( - self, - initialEnergy: int, - initialExperience: int, - energy: List[int], - experience: List[int], - ) -> int: - ans = max(0, sum(energy) - initialEnergy + 1) - for x in experience: - if initialExperience <= x: - ans += x - initialExperience + 1 - initialExperience = x + 1 - initialExperience += x - return ans -``` - -### **Java** - - - ```java class Solution { public int minNumberOfHours( @@ -150,29 +112,6 @@ class Solution { } ``` -```java -class Solution { - public int minNumberOfHours( - int initialEnergy, int initialExperience, int[] energy, int[] experience) { - int s = 0; - for (int x : energy) { - s += x; - } - int ans = Math.max(0, s - initialEnergy + 1); - for (int x : experience) { - if (initialExperience <= x) { - ans += x - initialExperience + 1; - initialExperience = x + 1; - } - initialExperience += x; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -196,26 +135,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minNumberOfHours(int initialEnergy, int initialExperience, vector& energy, vector& experience) { - int s = accumulate(energy.begin(), energy.end(), 0); - int ans = max(0, s - initialEnergy + 1); - for (int x : experience) { - if (initialExperience <= x) { - ans += x - initialExperience + 1; - initialExperience = x + 1; - } - initialExperience += x; - } - return ans; - } -}; -``` - -### **Go** - ```go func minNumberOfHours(initialEnergy int, initialExperience int, energy []int, experience []int) int { ans := 0 @@ -236,28 +155,6 @@ func minNumberOfHours(initialEnergy int, initialExperience int, energy []int, ex } ``` -```go -func minNumberOfHours(initialEnergy int, initialExperience int, energy []int, experience []int) (ans int) { - s := 0 - for _, x := range energy { - s += x - } - if y := s - initialEnergy + 1; y > 0 { - ans = y - } - for _, x := range experience { - if initialExperience <= x { - ans += x - initialExperience + 1 - initialExperience = x + 1 - } - initialExperience += x - } - return -} -``` - -### **TypeScript** - ```ts function minNumberOfHours( initialEnergy: number, @@ -287,6 +184,143 @@ function minNumberOfHours( } ``` +```rust +impl Solution { + pub fn min_number_of_hours( + mut initial_energy: i32, + mut initial_experience: i32, + energy: Vec, + experience: Vec + ) -> i32 { + let n = energy.len(); + let mut res = 0; + for i in 0..n { + if initial_energy <= energy[i] { + res += energy[i] - initial_energy + 1; + initial_energy = energy[i] + 1; + } + if initial_experience <= experience[i] { + res += experience[i] - initial_experience + 1; + initial_experience = experience[i] + 1; + } + initial_energy -= energy[i]; + initial_experience += experience[i]; + } + res + } +} +``` + +```c +int minNumberOfHours(int initialEnergy, int initialExperience, int* energy, int energySize, int* experience, int experienceSize) { + int res = 0; + for (int i = 0; i < energySize; i++) { + if (initialEnergy <= energy[i]) { + res += energy[i] - initialEnergy + 1; + initialEnergy = energy[i] + 1; + } + if (initialExperience <= experience[i]) { + res += experience[i] - initialExperience + 1; + initialExperience = experience[i] + 1; + } + initialEnergy -= energy[i]; + initialExperience += experience[i]; + } + return res; +} +``` + + + +### 方法二:贪心 + +我们可以先在初始时,把精力直接补充到足够击败这 $n$ 个对手,因此初始训练小时数为 $ans = \max(0, (\sum_{i=0}^{n-1} energy[i]) - initialEnergy + 1)$。 + +接下来我们只需考虑经验值的问题。遍历 $n$ 个对手,若当前经验不足以超过对手,则将经验补到刚好能超过该对手,击败对手后,把对手的经验值加到自己身上。 + +遍历结束,返回训练的小时数。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是对手的数量。 + + + +```python +class Solution: + def minNumberOfHours( + self, + initialEnergy: int, + initialExperience: int, + energy: List[int], + experience: List[int], + ) -> int: + ans = max(0, sum(energy) - initialEnergy + 1) + for x in experience: + if initialExperience <= x: + ans += x - initialExperience + 1 + initialExperience = x + 1 + initialExperience += x + return ans +``` + +```java +class Solution { + public int minNumberOfHours( + int initialEnergy, int initialExperience, int[] energy, int[] experience) { + int s = 0; + for (int x : energy) { + s += x; + } + int ans = Math.max(0, s - initialEnergy + 1); + for (int x : experience) { + if (initialExperience <= x) { + ans += x - initialExperience + 1; + initialExperience = x + 1; + } + initialExperience += x; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int minNumberOfHours(int initialEnergy, int initialExperience, vector& energy, vector& experience) { + int s = accumulate(energy.begin(), energy.end(), 0); + int ans = max(0, s - initialEnergy + 1); + for (int x : experience) { + if (initialExperience <= x) { + ans += x - initialExperience + 1; + initialExperience = x + 1; + } + initialExperience += x; + } + return ans; + } +}; +``` + +```go +func minNumberOfHours(initialEnergy int, initialExperience int, energy []int, experience []int) (ans int) { + s := 0 + for _, x := range energy { + s += x + } + if y := s - initialEnergy + 1; y > 0 { + ans = y + } + for _, x := range experience { + if initialExperience <= x { + ans += x - initialExperience + 1 + initialExperience = x + 1 + } + initialExperience += x + } + return +} +``` + ```ts function minNumberOfHours( initialEnergy: number, @@ -313,6 +347,12 @@ function minNumberOfHours( } ``` + + +### 方法三 + + + ```ts function minNumberOfHours( initialEnergy: number, @@ -333,61 +373,6 @@ function minNumberOfHours( } ``` -### **C** - -```c -int minNumberOfHours(int initialEnergy, int initialExperience, int* energy, int energySize, int* experience, int experienceSize) { - int res = 0; - for (int i = 0; i < energySize; i++) { - if (initialEnergy <= energy[i]) { - res += energy[i] - initialEnergy + 1; - initialEnergy = energy[i] + 1; - } - if (initialExperience <= experience[i]) { - res += experience[i] - initialExperience + 1; - initialExperience = experience[i] + 1; - } - initialEnergy -= energy[i]; - initialExperience += experience[i]; - } - return res; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn min_number_of_hours( - mut initial_energy: i32, - mut initial_experience: i32, - energy: Vec, - experience: Vec - ) -> i32 { - let n = energy.len(); - let mut res = 0; - for i in 0..n { - if initial_energy <= energy[i] { - res += energy[i] - initial_energy + 1; - initial_energy = energy[i] + 1; - } - if initial_experience <= experience[i] { - res += experience[i] - initial_experience + 1; - initial_experience = experience[i] + 1; - } - initial_energy -= energy[i]; - initial_experience += experience[i]; - } - res - } -} -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README_EN.md b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README_EN.md index bfb7be6f5ae7b..96899f3c275e7 100644 --- a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README_EN.md +++ b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README_EN.md @@ -55,9 +55,9 @@ It can be proven that no smaller answer exists. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -81,26 +81,6 @@ class Solution: return ans ``` -```python -class Solution: - def minNumberOfHours( - self, - initialEnergy: int, - initialExperience: int, - energy: List[int], - experience: List[int], - ) -> int: - ans = max(0, sum(energy) - initialEnergy + 1) - for x in experience: - if initialExperience <= x: - ans += x - initialExperience + 1 - initialExperience = x + 1 - initialExperience += x - return ans -``` - -### **Java** - ```java class Solution { public int minNumberOfHours( @@ -124,29 +104,6 @@ class Solution { } ``` -```java -class Solution { - public int minNumberOfHours( - int initialEnergy, int initialExperience, int[] energy, int[] experience) { - int s = 0; - for (int x : energy) { - s += x; - } - int ans = Math.max(0, s - initialEnergy + 1); - for (int x : experience) { - if (initialExperience <= x) { - ans += x - initialExperience + 1; - initialExperience = x + 1; - } - initialExperience += x; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -170,26 +127,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minNumberOfHours(int initialEnergy, int initialExperience, vector& energy, vector& experience) { - int s = accumulate(energy.begin(), energy.end(), 0); - int ans = max(0, s - initialEnergy + 1); - for (int x : experience) { - if (initialExperience <= x) { - ans += x - initialExperience + 1; - initialExperience = x + 1; - } - initialExperience += x; - } - return ans; - } -}; -``` - -### **Go** - ```go func minNumberOfHours(initialEnergy int, initialExperience int, energy []int, experience []int) int { ans := 0 @@ -210,28 +147,6 @@ func minNumberOfHours(initialEnergy int, initialExperience int, energy []int, ex } ``` -```go -func minNumberOfHours(initialEnergy int, initialExperience int, energy []int, experience []int) (ans int) { - s := 0 - for _, x := range energy { - s += x - } - if y := s - initialEnergy + 1; y > 0 { - ans = y - } - for _, x := range experience { - if initialExperience <= x { - ans += x - initialExperience + 1 - initialExperience = x + 1 - } - initialExperience += x - } - return -} -``` - -### **TypeScript** - ```ts function minNumberOfHours( initialEnergy: number, @@ -261,6 +176,135 @@ function minNumberOfHours( } ``` +```rust +impl Solution { + pub fn min_number_of_hours( + mut initial_energy: i32, + mut initial_experience: i32, + energy: Vec, + experience: Vec + ) -> i32 { + let n = energy.len(); + let mut res = 0; + for i in 0..n { + if initial_energy <= energy[i] { + res += energy[i] - initial_energy + 1; + initial_energy = energy[i] + 1; + } + if initial_experience <= experience[i] { + res += experience[i] - initial_experience + 1; + initial_experience = experience[i] + 1; + } + initial_energy -= energy[i]; + initial_experience += experience[i]; + } + res + } +} +``` + +```c +int minNumberOfHours(int initialEnergy, int initialExperience, int* energy, int energySize, int* experience, int experienceSize) { + int res = 0; + for (int i = 0; i < energySize; i++) { + if (initialEnergy <= energy[i]) { + res += energy[i] - initialEnergy + 1; + initialEnergy = energy[i] + 1; + } + if (initialExperience <= experience[i]) { + res += experience[i] - initialExperience + 1; + initialExperience = experience[i] + 1; + } + initialEnergy -= energy[i]; + initialExperience += experience[i]; + } + return res; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minNumberOfHours( + self, + initialEnergy: int, + initialExperience: int, + energy: List[int], + experience: List[int], + ) -> int: + ans = max(0, sum(energy) - initialEnergy + 1) + for x in experience: + if initialExperience <= x: + ans += x - initialExperience + 1 + initialExperience = x + 1 + initialExperience += x + return ans +``` + +```java +class Solution { + public int minNumberOfHours( + int initialEnergy, int initialExperience, int[] energy, int[] experience) { + int s = 0; + for (int x : energy) { + s += x; + } + int ans = Math.max(0, s - initialEnergy + 1); + for (int x : experience) { + if (initialExperience <= x) { + ans += x - initialExperience + 1; + initialExperience = x + 1; + } + initialExperience += x; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int minNumberOfHours(int initialEnergy, int initialExperience, vector& energy, vector& experience) { + int s = accumulate(energy.begin(), energy.end(), 0); + int ans = max(0, s - initialEnergy + 1); + for (int x : experience) { + if (initialExperience <= x) { + ans += x - initialExperience + 1; + initialExperience = x + 1; + } + initialExperience += x; + } + return ans; + } +}; +``` + +```go +func minNumberOfHours(initialEnergy int, initialExperience int, energy []int, experience []int) (ans int) { + s := 0 + for _, x := range energy { + s += x + } + if y := s - initialEnergy + 1; y > 0 { + ans = y + } + for _, x := range experience { + if initialExperience <= x { + ans += x - initialExperience + 1 + initialExperience = x + 1 + } + initialExperience += x + } + return +} +``` + ```ts function minNumberOfHours( initialEnergy: number, @@ -287,6 +331,12 @@ function minNumberOfHours( } ``` + + +### Solution 3 + + + ```ts function minNumberOfHours( initialEnergy: number, @@ -307,61 +357,6 @@ function minNumberOfHours( } ``` -### **C** - -```c -int minNumberOfHours(int initialEnergy, int initialExperience, int* energy, int energySize, int* experience, int experienceSize) { - int res = 0; - for (int i = 0; i < energySize; i++) { - if (initialEnergy <= energy[i]) { - res += energy[i] - initialEnergy + 1; - initialEnergy = energy[i] + 1; - } - if (initialExperience <= experience[i]) { - res += experience[i] - initialExperience + 1; - initialExperience = experience[i] + 1; - } - initialEnergy -= energy[i]; - initialExperience += experience[i]; - } - return res; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn min_number_of_hours( - mut initial_energy: i32, - mut initial_experience: i32, - energy: Vec, - experience: Vec - ) -> i32 { - let n = energy.len(); - let mut res = 0; - for i in 0..n { - if initial_energy <= energy[i] { - res += energy[i] - initial_energy + 1; - initial_energy = energy[i] + 1; - } - if initial_experience <= experience[i] { - res += experience[i] - initial_experience + 1; - initial_experience = experience[i] + 1; - } - initial_energy -= energy[i]; - initial_experience += experience[i]; - } - res - } -} -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2384.Largest Palindromic Number/README.md b/solution/2300-2399/2384.Largest Palindromic Number/README.md index 527581d94816c..e080b250a8be8 100644 --- a/solution/2300-2399/2384.Largest Palindromic Number/README.md +++ b/solution/2300-2399/2384.Largest Palindromic Number/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:统计 + 贪心** +### 方法一:统计 + 贪心 用 $cnt$ 数组记录每个数字出现的次数。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def largestPalindromic(self, num: str) -> str: @@ -90,10 +84,6 @@ class Solution: return ans.strip('0') or '0' ``` -### **Java** - - - ```java class Solution { public String largestPalindromic(String num) { @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go func largestPalindromic(num string) string { cnt := make([]int, 10) @@ -193,8 +179,6 @@ func largestPalindromic(num string) string { } ``` -### **TypeScript** - ```ts function largestPalindromic(num: string): string { const count = new Array(10).fill(0); @@ -239,11 +223,6 @@ function largestPalindromic(num: string): string { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2384.Largest Palindromic Number/README_EN.md b/solution/2300-2399/2384.Largest Palindromic Number/README_EN.md index 58c1a65e34118..65d7c211ed27b 100644 --- a/solution/2300-2399/2384.Largest Palindromic Number/README_EN.md +++ b/solution/2300-2399/2384.Largest Palindromic Number/README_EN.md @@ -46,9 +46,9 @@ Note that the integer returned should not contain leading zeroes. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return ans.strip('0') or '0' ``` -### **Java** - ```java class Solution { public String largestPalindromic(String num) { @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +136,6 @@ public: }; ``` -### **Go** - ```go func largestPalindromic(num string) string { cnt := make([]int, 10) @@ -171,8 +165,6 @@ func largestPalindromic(num string) string { } ``` -### **TypeScript** - ```ts function largestPalindromic(num: string): string { const count = new Array(10).fill(0); @@ -217,11 +209,6 @@ function largestPalindromic(num: string): string { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/README.md b/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/README.md index 61912c606f690..ec48c602403e0 100644 --- a/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/README.md +++ b/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/README.md @@ -52,26 +52,14 @@ ## 解法 - - -**方法一:DFS + BFS** +### 方法一:DFS + BFS 先通过 $DFS$ 建图,得到 $g$。然后以 $start$ 作为起点,哈希表 $vis$ 标记访问过的节点,通过 $BFS$ 以及前面得到的图 $g$,逐层往外扩展,扩展的次数即为答案。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。 -**方法二:两次 DFS** - -与方法一一样,我们先通过 $DFS$ 建图,得到 $g$。然后以 $start$ 作为起点,通过 $DFS$ 搜索整棵树,找到最远距离,即为答案。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -109,43 +97,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def amountOfTime(self, root: Optional[TreeNode], start: int) -> int: - def dfs(root): - if root is None: - return - if root.left: - g[root.val].append(root.left.val) - g[root.left.val].append(root.val) - if root.right: - g[root.val].append(root.right.val) - g[root.right.val].append(root.val) - dfs(root.left) - dfs(root.right) - - def dfs2(i, fa): - ans = 0 - for j in g[i]: - if j != fa: - ans = max(ans, 1 + dfs2(j, i)) - return ans - - g = defaultdict(list) - dfs(root) - return dfs2(start, -1) -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -206,60 +157,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private Map> g = new HashMap<>(); - - public int amountOfTime(TreeNode root, int start) { - dfs(root); - return dfs(start, -1); - } - - private int dfs(int i, int fa) { - int ans = 0; - for (int j : g.getOrDefault(i, Collections.emptyList())) { - if (j != fa) { - ans = Math.max(ans, 1 + dfs(j, i)); - } - } - return ans; - } - - private void dfs(TreeNode root) { - if (root == null) { - return; - } - if (root.left != null) { - g.computeIfAbsent(root.left.val, k -> new ArrayList<>()).add(root.val); - g.computeIfAbsent(root.val, k -> new ArrayList<>()).add(root.left.val); - } - if (root.right != null) { - g.computeIfAbsent(root.right.val, k -> new ArrayList<>()).add(root.val); - g.computeIfAbsent(root.val, k -> new ArrayList<>()).add(root.right.val); - } - dfs(root.left); - dfs(root.right); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -313,55 +210,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - unordered_map> g; - - int amountOfTime(TreeNode* root, int start) { - dfs(root); - return dfs(start, -1); - } - - int dfs(int i, int fa) { - int ans = 0; - for (int& j : g[i]) { - if (j != fa) { - ans = max(ans, 1 + dfs(j, i)); - } - } - return ans; - } - - void dfs(TreeNode* root) { - if (!root) return; - if (root->left) { - g[root->val].push_back(root->left->val); - g[root->left->val].push_back(root->val); - } - if (root->right) { - g[root->val].push_back(root->right->val); - g[root->right->val].push_back(root->val); - } - dfs(root->left); - dfs(root->right); - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -411,52 +259,6 @@ func amountOfTime(root *TreeNode, start int) int { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func amountOfTime(root *TreeNode, start int) int { - g := map[int][]int{} - var dfs func(*TreeNode) - dfs = func(root *TreeNode) { - if root == nil { - return - } - if root.Left != nil { - g[root.Val] = append(g[root.Val], root.Left.Val) - g[root.Left.Val] = append(g[root.Left.Val], root.Val) - } - if root.Right != nil { - g[root.Val] = append(g[root.Val], root.Right.Val) - g[root.Right.Val] = append(g[root.Right.Val], root.Val) - } - dfs(root.Left) - dfs(root.Right) - } - - var dfs2 func(int, int) int - dfs2 = func(i, fa int) int { - ans := 0 - for _, j := range g[i] { - if j != fa { - ans = max(ans, 1+dfs2(j, i)) - } - } - return ans - } - - dfs(root) - return dfs2(start, -1) -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -500,11 +302,192 @@ function amountOfTime(root: TreeNode | null, start: number): number { } ``` -### **...** + + +### 方法二:两次 DFS + +与方法一一样,我们先通过 $DFS$ 建图,得到 $g$。然后以 $start$ 作为起点,通过 $DFS$ 搜索整棵树,找到最远距离,即为答案。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def amountOfTime(self, root: Optional[TreeNode], start: int) -> int: + def dfs(root): + if root is None: + return + if root.left: + g[root.val].append(root.left.val) + g[root.left.val].append(root.val) + if root.right: + g[root.val].append(root.right.val) + g[root.right.val].append(root.val) + dfs(root.left) + dfs(root.right) + + def dfs2(i, fa): + ans = 0 + for j in g[i]: + if j != fa: + ans = max(ans, 1 + dfs2(j, i)) + return ans + + g = defaultdict(list) + dfs(root) + return dfs2(start, -1) +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private Map> g = new HashMap<>(); + + public int amountOfTime(TreeNode root, int start) { + dfs(root); + return dfs(start, -1); + } + + private int dfs(int i, int fa) { + int ans = 0; + for (int j : g.getOrDefault(i, Collections.emptyList())) { + if (j != fa) { + ans = Math.max(ans, 1 + dfs(j, i)); + } + } + return ans; + } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + if (root.left != null) { + g.computeIfAbsent(root.left.val, k -> new ArrayList<>()).add(root.val); + g.computeIfAbsent(root.val, k -> new ArrayList<>()).add(root.left.val); + } + if (root.right != null) { + g.computeIfAbsent(root.right.val, k -> new ArrayList<>()).add(root.val); + g.computeIfAbsent(root.val, k -> new ArrayList<>()).add(root.right.val); + } + dfs(root.left); + dfs(root.right); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + unordered_map> g; + + int amountOfTime(TreeNode* root, int start) { + dfs(root); + return dfs(start, -1); + } + + int dfs(int i, int fa) { + int ans = 0; + for (int& j : g[i]) { + if (j != fa) { + ans = max(ans, 1 + dfs(j, i)); + } + } + return ans; + } + void dfs(TreeNode* root) { + if (!root) return; + if (root->left) { + g[root->val].push_back(root->left->val); + g[root->left->val].push_back(root->val); + } + if (root->right) { + g[root->val].push_back(root->right->val); + g[root->right->val].push_back(root->val); + } + dfs(root->left); + dfs(root->right); + } +}; ``` +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func amountOfTime(root *TreeNode, start int) int { + g := map[int][]int{} + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return + } + if root.Left != nil { + g[root.Val] = append(g[root.Val], root.Left.Val) + g[root.Left.Val] = append(g[root.Left.Val], root.Val) + } + if root.Right != nil { + g[root.Val] = append(g[root.Val], root.Right.Val) + g[root.Right.Val] = append(g[root.Right.Val], root.Val) + } + dfs(root.Left) + dfs(root.Right) + } + + var dfs2 func(int, int) int + dfs2 = func(i, fa int) int { + ans := 0 + for _, j := range g[i] { + if j != fa { + ans = max(ans, 1+dfs2(j, i)) + } + } + return ans + } + dfs(root) + return dfs2(start, -1) +} ``` + + diff --git a/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/README_EN.md b/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/README_EN.md index 3758381739c7b..d26e10b9114f5 100644 --- a/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/README_EN.md +++ b/solution/2300-2399/2385.Amount of Time for Binary Tree to Be Infected/README_EN.md @@ -50,9 +50,9 @@ It takes 4 minutes for the whole tree to be infected so we return 4. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -91,41 +91,6 @@ class Solution: return ans ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def amountOfTime(self, root: Optional[TreeNode], start: int) -> int: - def dfs(root): - if root is None: - return - if root.left: - g[root.val].append(root.left.val) - g[root.left.val].append(root.val) - if root.right: - g[root.val].append(root.right.val) - g[root.right.val].append(root.val) - dfs(root.left) - dfs(root.right) - - def dfs2(i, fa): - ans = 0 - for j in g[i]: - if j != fa: - ans = max(ans, 1 + dfs2(j, i)) - return ans - - g = defaultdict(list) - dfs(root) - return dfs2(start, -1) -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -186,60 +151,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private Map> g = new HashMap<>(); - - public int amountOfTime(TreeNode root, int start) { - dfs(root); - return dfs(start, -1); - } - - private int dfs(int i, int fa) { - int ans = 0; - for (int j : g.getOrDefault(i, Collections.emptyList())) { - if (j != fa) { - ans = Math.max(ans, 1 + dfs(j, i)); - } - } - return ans; - } - - private void dfs(TreeNode root) { - if (root == null) { - return; - } - if (root.left != null) { - g.computeIfAbsent(root.left.val, k -> new ArrayList<>()).add(root.val); - g.computeIfAbsent(root.val, k -> new ArrayList<>()).add(root.left.val); - } - if (root.right != null) { - g.computeIfAbsent(root.right.val, k -> new ArrayList<>()).add(root.val); - g.computeIfAbsent(root.val, k -> new ArrayList<>()).add(root.right.val); - } - dfs(root.left); - dfs(root.right); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -293,55 +204,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - unordered_map> g; - - int amountOfTime(TreeNode* root, int start) { - dfs(root); - return dfs(start, -1); - } - - int dfs(int i, int fa) { - int ans = 0; - for (int& j : g[i]) { - if (j != fa) { - ans = max(ans, 1 + dfs(j, i)); - } - } - return ans; - } - - void dfs(TreeNode* root) { - if (!root) return; - if (root->left) { - g[root->val].push_back(root->left->val); - g[root->left->val].push_back(root->val); - } - if (root->right) { - g[root->val].push_back(root->right->val); - g[root->right->val].push_back(root->val); - } - dfs(root->left); - dfs(root->right); - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -391,52 +253,6 @@ func amountOfTime(root *TreeNode, start int) int { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func amountOfTime(root *TreeNode, start int) int { - g := map[int][]int{} - var dfs func(*TreeNode) - dfs = func(root *TreeNode) { - if root == nil { - return - } - if root.Left != nil { - g[root.Val] = append(g[root.Val], root.Left.Val) - g[root.Left.Val] = append(g[root.Left.Val], root.Val) - } - if root.Right != nil { - g[root.Val] = append(g[root.Val], root.Right.Val) - g[root.Right.Val] = append(g[root.Right.Val], root.Val) - } - dfs(root.Left) - dfs(root.Right) - } - - var dfs2 func(int, int) int - dfs2 = func(i, fa int) int { - ans := 0 - for _, j := range g[i] { - if j != fa { - ans = max(ans, 1+dfs2(j, i)) - } - } - return ans - } - - dfs(root) - return dfs2(start, -1) -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -480,11 +296,188 @@ function amountOfTime(root: TreeNode | null, start: number): number { } ``` -### **...** + + +### Solution 2 + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def amountOfTime(self, root: Optional[TreeNode], start: int) -> int: + def dfs(root): + if root is None: + return + if root.left: + g[root.val].append(root.left.val) + g[root.left.val].append(root.val) + if root.right: + g[root.val].append(root.right.val) + g[root.right.val].append(root.val) + dfs(root.left) + dfs(root.right) + + def dfs2(i, fa): + ans = 0 + for j in g[i]: + if j != fa: + ans = max(ans, 1 + dfs2(j, i)) + return ans + + g = defaultdict(list) + dfs(root) + return dfs2(start, -1) ``` +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private Map> g = new HashMap<>(); + + public int amountOfTime(TreeNode root, int start) { + dfs(root); + return dfs(start, -1); + } + private int dfs(int i, int fa) { + int ans = 0; + for (int j : g.getOrDefault(i, Collections.emptyList())) { + if (j != fa) { + ans = Math.max(ans, 1 + dfs(j, i)); + } + } + return ans; + } + + private void dfs(TreeNode root) { + if (root == null) { + return; + } + if (root.left != null) { + g.computeIfAbsent(root.left.val, k -> new ArrayList<>()).add(root.val); + g.computeIfAbsent(root.val, k -> new ArrayList<>()).add(root.left.val); + } + if (root.right != null) { + g.computeIfAbsent(root.right.val, k -> new ArrayList<>()).add(root.val); + g.computeIfAbsent(root.val, k -> new ArrayList<>()).add(root.right.val); + } + dfs(root.left); + dfs(root.right); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + unordered_map> g; + + int amountOfTime(TreeNode* root, int start) { + dfs(root); + return dfs(start, -1); + } + + int dfs(int i, int fa) { + int ans = 0; + for (int& j : g[i]) { + if (j != fa) { + ans = max(ans, 1 + dfs(j, i)); + } + } + return ans; + } + + void dfs(TreeNode* root) { + if (!root) return; + if (root->left) { + g[root->val].push_back(root->left->val); + g[root->left->val].push_back(root->val); + } + if (root->right) { + g[root->val].push_back(root->right->val); + g[root->right->val].push_back(root->val); + } + dfs(root->left); + dfs(root->right); + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func amountOfTime(root *TreeNode, start int) int { + g := map[int][]int{} + var dfs func(*TreeNode) + dfs = func(root *TreeNode) { + if root == nil { + return + } + if root.Left != nil { + g[root.Val] = append(g[root.Val], root.Left.Val) + g[root.Left.Val] = append(g[root.Left.Val], root.Val) + } + if root.Right != nil { + g[root.Val] = append(g[root.Val], root.Right.Val) + g[root.Right.Val] = append(g[root.Right.Val], root.Val) + } + dfs(root.Left) + dfs(root.Right) + } + + var dfs2 func(int, int) int + dfs2 = func(i, fa int) int { + ans := 0 + for _, j := range g[i] { + if j != fa { + ans = max(ans, 1+dfs2(j, i)) + } + } + return ans + } + + dfs(root) + return dfs2(start, -1) +} ``` + + diff --git a/solution/2300-2399/2386.Find the K-Sum of an Array/README.md b/solution/2300-2399/2386.Find the K-Sum of an Array/README.md index 4d9b4270df16d..82631ae4c198f 100644 --- a/solution/2300-2399/2386.Find the K-Sum of an Array/README.md +++ b/solution/2300-2399/2386.Find the K-Sum of an Array/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:优先队列(小根堆)** +### 方法一:优先队列(小根堆) 首先,我们找到最大的子序和 $mx$,即所有正数之和。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def kSum(self, nums: List[int], k: int) -> int: @@ -89,10 +83,6 @@ class Solution: return mx - h[0][0] ``` -### **Java** - - - ```java class Solution { public long kSum(int[] nums, int k) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp using pli = pair; @@ -162,8 +150,6 @@ public: }; ``` -### **Go** - ```go func kSum(nums []int, k int) int64 { mx := 0 @@ -199,17 +185,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2386.Find the K-Sum of an Array/README_EN.md b/solution/2300-2399/2386.Find the K-Sum of an Array/README_EN.md index 3dc3608c5e2c3..46d9f6bba849f 100644 --- a/solution/2300-2399/2386.Find the K-Sum of an Array/README_EN.md +++ b/solution/2300-2399/2386.Find the K-Sum of an Array/README_EN.md @@ -45,9 +45,9 @@ The 5-Sum of the array is 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return mx - h[0][0] ``` -### **Java** - ```java class Solution { public long kSum(int[] nums, int k) { @@ -103,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp using pli = pair; @@ -140,8 +136,6 @@ public: }; ``` -### **Go** - ```go func kSum(nums []int, k int) int64 { mx := 0 @@ -177,17 +171,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2387.Median of a Row Wise Sorted Matrix/README.md b/solution/2300-2399/2387.Median of a Row Wise Sorted Matrix/README.md index 6180d64f14b50..bd387cee83a83 100644 --- a/solution/2300-2399/2387.Median of a Row Wise Sorted Matrix/README.md +++ b/solution/2300-2399/2387.Median of a Row Wise Sorted Matrix/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:两次二分查找** +### 方法一:两次二分查找 中位数实际上是排序后第 $target = \left \lceil \frac{m\times n}{2} \right \rceil$ 个数。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def matrixMedian(self, grid: List[List[int]]) -> int: @@ -70,10 +64,6 @@ class Solution: return bisect_left(range(10**6 + 1), target, key=count) ``` -### **Java** - - - ```java class Solution { private int[][] grid; @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func matrixMedian(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -178,17 +164,6 @@ func matrixMedian(grid [][]int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2387.Median of a Row Wise Sorted Matrix/README_EN.md b/solution/2300-2399/2387.Median of a Row Wise Sorted Matrix/README_EN.md index 99ea069a9238a..6f046c31a29a9 100644 --- a/solution/2300-2399/2387.Median of a Row Wise Sorted Matrix/README_EN.md +++ b/solution/2300-2399/2387.Median of a Row Wise Sorted Matrix/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return bisect_left(range(10**6 + 1), target, key=count) ``` -### **Java** - ```java class Solution { private int[][] grid; @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +120,6 @@ public: }; ``` -### **Go** - ```go func matrixMedian(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -160,17 +154,6 @@ func matrixMedian(grid [][]int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/README.md b/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/README.md index 613263e86583b..8faeb2f08d985 100644 --- a/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/README.md +++ b/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/README.md @@ -64,22 +64,12 @@ CoffeeShop 表: ## 解法 - - -**方法一:临时变量** +### 方法一:临时变量 我们可以使用一个临时变量 $cur$ 来记录上一个不为 $null$ 的值,如果当前值为 $null$,则将 $cur$ 的值赋给当前值,否则我们更新 $cur$ 的值为当前值。 -**方法二:窗口函数** - -我们先用窗口函数 `row_number()` 为每一行生成一个序号,然后使用 `sum()` 窗口函数来生成一个分组序号,分组序号的生成规则为:如果当前行的值为 $null$,则分组序号与上一行相同,否则分组序号加一。最后我们使用 `max()` 窗口函数来获取每一组唯一一个不为 $null$ 的值。 - -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -91,6 +81,14 @@ SELECT FROM CoffeeShop; ``` + + +### 方法二:窗口函数 + +我们先用窗口函数 `row_number()` 为每一行生成一个序号,然后使用 `sum()` 窗口函数来生成一个分组序号,分组序号的生成规则为:如果当前行的值为 $null$,则分组序号与上一行相同,否则分组序号加一。最后我们使用 `max()` 窗口函数来获取每一组唯一一个不为 $null$ 的值。 + + + ```sql # Write your MySQL query statement below WITH @@ -119,3 +117,5 @@ FROM T; ``` + + diff --git a/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/README_EN.md b/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/README_EN.md index e988245052da7..ab7954c77127c 100644 --- a/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/README_EN.md +++ b/solution/2300-2399/2388.Change Null Values in a Table to the Previous Value/README_EN.md @@ -61,9 +61,9 @@ Note that the rows in the output are the same as in the input. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -76,6 +76,12 @@ SELECT FROM CoffeeShop; ``` + + +### Solution 2 + + + ```sql # Write your MySQL query statement below WITH @@ -104,3 +110,5 @@ FROM T; ``` + + diff --git a/solution/2300-2399/2389.Longest Subsequence With Limited Sum/README.md b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/README.md index 4981996c8642d..e8f84bd810afd 100644 --- a/solution/2300-2399/2389.Longest Subsequence With Limited Sum/README.md +++ b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:排序 + 前缀和 + 二分查找** +### 方法一:排序 + 前缀和 + 二分查找 根据题目描述,对于每个 $queries[i]$,我们需要找到一个子序列,使得该子序列的元素和不超过 $queries[i]$,且该子序列的长度最大化。显然,我们应该选择尽可能小的元素,这样才能使得子序列的长度最大化。 @@ -55,26 +53,8 @@ 时间复杂度 $O((n + m) \times \log n)$,空间复杂度 $O(n)$ 或 $O(\log n)$。其中 $n$ 和 $m$ 分别是数组 $nums$ 和 $queries$ 的长度。 -**方法二:排序 + 离线查询 + 双指针** - -与方法一类似,我们可以先对数组 $nums$ 进行升序排列。 - -接下来,我们定义一个长度与 $queries$ 相同的下标数组 $idx$,其中 $idx[i]=i$,然后我们对数组 $idx$ 按照 $queries$ 中的元素值进行升序排序。这样,我们就可以按照 $queries$ 中的元素值从小到大的顺序进行处理。 - -我们使用一个变量 $s$ 记录当前已经选择的元素的和,使用一个变量 $j$ 记录当前已经选择的元素的个数。初始时 $s = j = 0$。 - -我们遍历下标数组 $idx$,对于其中的每个下标 $i$,我们循环地将数组 $nums$ 中的元素加入到当前的子序列中,直到 $s + nums[j] \gt queries[i]$,此时 $j$ 即为满足条件的子序列的长度,我们将 $ans[i]$ 的值设为 $j$,然后继续处理下一个下标。 - -遍历完下标数组 $idx$ 后,我们即可得到答案数组 $ans$,其中 $ans[i]$ 即为满足 $queries[i]$ 的子序列的长度。 - -时间复杂度 $O(n \times \log n + m)$,空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别是数组 $nums$ 和 $queries$ 的长度。 - -### **Python3** - - - ```python class Solution: def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]: @@ -83,26 +63,6 @@ class Solution: return [bisect_right(s, q) for q in queries] ``` -```python -class Solution: - def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]: - nums.sort() - m = len(queries) - ans = [0] * m - idx = sorted(range(m), key=lambda i: queries[i]) - s = j = 0 - for i in idx: - while j < len(nums) and s + nums[j] <= queries[i]: - s += nums[j] - j += 1 - ans[i] = j - return ans -``` - -### **Java** - - - ```java class Solution { public int[] answerQueries(int[] nums, int[] queries) { @@ -133,31 +93,6 @@ class Solution { } ``` -```java -class Solution { - public int[] answerQueries(int[] nums, int[] queries) { - Arrays.sort(nums); - int m = queries.length; - Integer[] idx = new Integer[m]; - for (int i = 0; i < m; ++i) { - idx[i] = i; - } - Arrays.sort(idx, (i, j) -> queries[i] - queries[j]); - int[] ans = new int[m]; - int s = 0, j = 0; - for (int i : idx) { - while (j < nums.length && s + nums[j] <= queries[i]) { - s += nums[j++]; - } - ans[i] = j; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -175,32 +110,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector answerQueries(vector& nums, vector& queries) { - sort(nums.begin(), nums.end()); - int m = queries.size(); - vector idx(m); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { - return queries[i] < queries[j]; - }); - vector ans(m); - int s = 0, j = 0; - for (int i : idx) { - while (j < nums.size() && s + nums[j] <= queries[i]) { - s += nums[j++]; - } - ans[i] = j; - } - return ans; - } -}; -``` - -### **Go** - ```go func answerQueries(nums []int, queries []int) (ans []int) { sort.Ints(nums) @@ -214,30 +123,6 @@ func answerQueries(nums []int, queries []int) (ans []int) { } ``` -```go -func answerQueries(nums []int, queries []int) (ans []int) { - sort.Ints(nums) - m := len(queries) - idx := make([]int, m) - for i := range idx { - idx[i] = i - } - sort.Slice(idx, func(i, j int) bool { return queries[idx[i]] < queries[idx[j]] }) - ans = make([]int, m) - s, j := 0, 0 - for _, i := range idx { - for j < len(nums) && s+nums[j] <= queries[i] { - s += nums[j] - j++ - } - ans[i] = j - } - return -} -``` - -### **TypeScript** - ```ts function answerQueries(nums: number[], queries: number[]): number[] { nums.sort((a, b) => a - b); @@ -265,30 +150,6 @@ function answerQueries(nums: number[], queries: number[]): number[] { } ``` -```ts -function answerQueries(nums: number[], queries: number[]): number[] { - nums.sort((a, b) => a - b); - const m = queries.length; - const idx: number[] = new Array(m); - for (let i = 0; i < m; i++) { - idx[i] = i; - } - idx.sort((i, j) => queries[i] - queries[j]); - const ans: number[] = new Array(m); - let s = 0; - let j = 0; - for (const i of idx) { - while (j < nums.length && s + nums[j] <= queries[i]) { - s += nums[j++]; - } - ans[i] = j; - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn answer_queries(mut nums: Vec, queries: Vec) -> Vec { @@ -311,8 +172,6 @@ impl Solution { } ``` -### **C#** - ```cs public class Solution { public int[] AnswerQueries(int[] nums, int[] queries) { @@ -338,10 +197,131 @@ public class Solution { } ``` -### **...** + + +### 方法二:排序 + 离线查询 + 双指针 + +与方法一类似,我们可以先对数组 $nums$ 进行升序排列。 + +接下来,我们定义一个长度与 $queries$ 相同的下标数组 $idx$,其中 $idx[i]=i$,然后我们对数组 $idx$ 按照 $queries$ 中的元素值进行升序排序。这样,我们就可以按照 $queries$ 中的元素值从小到大的顺序进行处理。 + +我们使用一个变量 $s$ 记录当前已经选择的元素的和,使用一个变量 $j$ 记录当前已经选择的元素的个数。初始时 $s = j = 0$。 + +我们遍历下标数组 $idx$,对于其中的每个下标 $i$,我们循环地将数组 $nums$ 中的元素加入到当前的子序列中,直到 $s + nums[j] \gt queries[i]$,此时 $j$ 即为满足条件的子序列的长度,我们将 $ans[i]$ 的值设为 $j$,然后继续处理下一个下标。 + +遍历完下标数组 $idx$ 后,我们即可得到答案数组 $ans$,其中 $ans[i]$ 即为满足 $queries[i]$ 的子序列的长度。 + +时间复杂度 $O(n \times \log n + m)$,空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别是数组 $nums$ 和 $queries$ 的长度。 + + +```python +class Solution: + def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]: + nums.sort() + m = len(queries) + ans = [0] * m + idx = sorted(range(m), key=lambda i: queries[i]) + s = j = 0 + for i in idx: + while j < len(nums) and s + nums[j] <= queries[i]: + s += nums[j] + j += 1 + ans[i] = j + return ans ``` +```java +class Solution { + public int[] answerQueries(int[] nums, int[] queries) { + Arrays.sort(nums); + int m = queries.length; + Integer[] idx = new Integer[m]; + for (int i = 0; i < m; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> queries[i] - queries[j]); + int[] ans = new int[m]; + int s = 0, j = 0; + for (int i : idx) { + while (j < nums.length && s + nums[j] <= queries[i]) { + s += nums[j++]; + } + ans[i] = j; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector answerQueries(vector& nums, vector& queries) { + sort(nums.begin(), nums.end()); + int m = queries.size(); + vector idx(m); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return queries[i] < queries[j]; + }); + vector ans(m); + int s = 0, j = 0; + for (int i : idx) { + while (j < nums.size() && s + nums[j] <= queries[i]) { + s += nums[j++]; + } + ans[i] = j; + } + return ans; + } +}; +``` + +```go +func answerQueries(nums []int, queries []int) (ans []int) { + sort.Ints(nums) + m := len(queries) + idx := make([]int, m) + for i := range idx { + idx[i] = i + } + sort.Slice(idx, func(i, j int) bool { return queries[idx[i]] < queries[idx[j]] }) + ans = make([]int, m) + s, j := 0, 0 + for _, i := range idx { + for j < len(nums) && s+nums[j] <= queries[i] { + s += nums[j] + j++ + } + ans[i] = j + } + return +} +``` + +```ts +function answerQueries(nums: number[], queries: number[]): number[] { + nums.sort((a, b) => a - b); + const m = queries.length; + const idx: number[] = new Array(m); + for (let i = 0; i < m; i++) { + idx[i] = i; + } + idx.sort((i, j) => queries[i] - queries[j]); + const ans: number[] = new Array(m); + let s = 0; + let j = 0; + for (const i of idx) { + while (j < nums.length && s + nums[j] <= queries[i]) { + s += nums[j++]; + } + ans[i] = j; + } + return ans; +} ``` + + diff --git a/solution/2300-2399/2389.Longest Subsequence With Limited Sum/README_EN.md b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/README_EN.md index 68a3789917d2e..d0d1e323820f1 100644 --- a/solution/2300-2399/2389.Longest Subsequence With Limited Sum/README_EN.md +++ b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,24 +53,6 @@ class Solution: return [bisect_right(s, q) for q in queries] ``` -```python -class Solution: - def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]: - nums.sort() - m = len(queries) - ans = [0] * m - idx = sorted(range(m), key=lambda i: queries[i]) - s = j = 0 - for i in idx: - while j < len(nums) and s + nums[j] <= queries[i]: - s += nums[j] - j += 1 - ans[i] = j - return ans -``` - -### **Java** - ```java class Solution { public int[] answerQueries(int[] nums, int[] queries) { @@ -101,31 +83,6 @@ class Solution { } ``` -```java -class Solution { - public int[] answerQueries(int[] nums, int[] queries) { - Arrays.sort(nums); - int m = queries.length; - Integer[] idx = new Integer[m]; - for (int i = 0; i < m; ++i) { - idx[i] = i; - } - Arrays.sort(idx, (i, j) -> queries[i] - queries[j]); - int[] ans = new int[m]; - int s = 0, j = 0; - for (int i : idx) { - while (j < nums.length && s + nums[j] <= queries[i]) { - s += nums[j++]; - } - ans[i] = j; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -143,32 +100,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector answerQueries(vector& nums, vector& queries) { - sort(nums.begin(), nums.end()); - int m = queries.size(); - vector idx(m); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { - return queries[i] < queries[j]; - }); - vector ans(m); - int s = 0, j = 0; - for (int i : idx) { - while (j < nums.size() && s + nums[j] <= queries[i]) { - s += nums[j++]; - } - ans[i] = j; - } - return ans; - } -}; -``` - -### **Go** - ```go func answerQueries(nums []int, queries []int) (ans []int) { sort.Ints(nums) @@ -182,30 +113,6 @@ func answerQueries(nums []int, queries []int) (ans []int) { } ``` -```go -func answerQueries(nums []int, queries []int) (ans []int) { - sort.Ints(nums) - m := len(queries) - idx := make([]int, m) - for i := range idx { - idx[i] = i - } - sort.Slice(idx, func(i, j int) bool { return queries[idx[i]] < queries[idx[j]] }) - ans = make([]int, m) - s, j := 0, 0 - for _, i := range idx { - for j < len(nums) && s+nums[j] <= queries[i] { - s += nums[j] - j++ - } - ans[i] = j - } - return -} -``` - -### **TypeScript** - ```ts function answerQueries(nums: number[], queries: number[]): number[] { nums.sort((a, b) => a - b); @@ -233,30 +140,6 @@ function answerQueries(nums: number[], queries: number[]): number[] { } ``` -```ts -function answerQueries(nums: number[], queries: number[]): number[] { - nums.sort((a, b) => a - b); - const m = queries.length; - const idx: number[] = new Array(m); - for (let i = 0; i < m; i++) { - idx[i] = i; - } - idx.sort((i, j) => queries[i] - queries[j]); - const ans: number[] = new Array(m); - let s = 0; - let j = 0; - for (const i of idx) { - while (j < nums.length && s + nums[j] <= queries[i]) { - s += nums[j++]; - } - ans[i] = j; - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn answer_queries(mut nums: Vec, queries: Vec) -> Vec { @@ -279,8 +162,6 @@ impl Solution { } ``` -### **C#** - ```cs public class Solution { public int[] AnswerQueries(int[] nums, int[] queries) { @@ -306,10 +187,119 @@ public class Solution { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]: + nums.sort() + m = len(queries) + ans = [0] * m + idx = sorted(range(m), key=lambda i: queries[i]) + s = j = 0 + for i in idx: + while j < len(nums) and s + nums[j] <= queries[i]: + s += nums[j] + j += 1 + ans[i] = j + return ans ``` +```java +class Solution { + public int[] answerQueries(int[] nums, int[] queries) { + Arrays.sort(nums); + int m = queries.length; + Integer[] idx = new Integer[m]; + for (int i = 0; i < m; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> queries[i] - queries[j]); + int[] ans = new int[m]; + int s = 0, j = 0; + for (int i : idx) { + while (j < nums.length && s + nums[j] <= queries[i]) { + s += nums[j++]; + } + ans[i] = j; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector answerQueries(vector& nums, vector& queries) { + sort(nums.begin(), nums.end()); + int m = queries.size(); + vector idx(m); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return queries[i] < queries[j]; + }); + vector ans(m); + int s = 0, j = 0; + for (int i : idx) { + while (j < nums.size() && s + nums[j] <= queries[i]) { + s += nums[j++]; + } + ans[i] = j; + } + return ans; + } +}; +``` + +```go +func answerQueries(nums []int, queries []int) (ans []int) { + sort.Ints(nums) + m := len(queries) + idx := make([]int, m) + for i := range idx { + idx[i] = i + } + sort.Slice(idx, func(i, j int) bool { return queries[idx[i]] < queries[idx[j]] }) + ans = make([]int, m) + s, j := 0, 0 + for _, i := range idx { + for j < len(nums) && s+nums[j] <= queries[i] { + s += nums[j] + j++ + } + ans[i] = j + } + return +} +``` + +```ts +function answerQueries(nums: number[], queries: number[]): number[] { + nums.sort((a, b) => a - b); + const m = queries.length; + const idx: number[] = new Array(m); + for (let i = 0; i < m; i++) { + idx[i] = i; + } + idx.sort((i, j) => queries[i] - queries[j]); + const ans: number[] = new Array(m); + let s = 0; + let j = 0; + for (const i of idx) { + while (j < nums.length && s + nums[j] <= queries[i]) { + s += nums[j++]; + } + ans[i] = j; + } + return ans; +} ``` + + diff --git a/solution/2300-2399/2390.Removing Stars From a String/README.md b/solution/2300-2399/2390.Removing Stars From a String/README.md index 7d66fd47ca08a..23f06a9c93f50 100644 --- a/solution/2300-2399/2390.Removing Stars From a String/README.md +++ b/solution/2300-2399/2390.Removing Stars From a String/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:栈模拟** +### 方法一:栈模拟 我们可以使用栈模拟操作过程。遍历字符串 $s$,如果当前字符不是星号,则将其入栈;如果当前字符是星号,则将栈顶元素出栈。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def removeStars(self, s: str) -> str: @@ -85,10 +79,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - - - ```java class Solution { public String removeStars(String s) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func removeStars(s string) string { ans := []rune{} @@ -140,8 +126,6 @@ func removeStars(s string) string { } ``` -### **TypeScript** - ```ts function removeStars(s: string): string { const ans: string[] = []; @@ -156,8 +140,6 @@ function removeStars(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn remove_stars(s: String) -> String { @@ -174,8 +156,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -196,10 +176,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2390.Removing Stars From a String/README_EN.md b/solution/2300-2399/2390.Removing Stars From a String/README_EN.md index cf3d066bfcfe1..ccec12a368eed 100644 --- a/solution/2300-2399/2390.Removing Stars From a String/README_EN.md +++ b/solution/2300-2399/2390.Removing Stars From a String/README_EN.md @@ -53,9 +53,9 @@ There are no more stars, so we return "lecoe". ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return ''.join(ans) ``` -### **Java** - ```java class Solution { public String removeStars(String s) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +102,6 @@ public: }; ``` -### **Go** - ```go func removeStars(s string) string { ans := []rune{} @@ -122,8 +116,6 @@ func removeStars(s string) string { } ``` -### **TypeScript** - ```ts function removeStars(s: string): string { const ans: string[] = []; @@ -138,8 +130,6 @@ function removeStars(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn remove_stars(s: String) -> String { @@ -156,8 +146,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -178,10 +166,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/README.md b/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/README.md index 797701b8ac2a0..5ec36fa980ef1 100644 --- a/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/README.md +++ b/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:计数统计** +### 方法一:计数统计 由于题目中说明同一时刻只有一辆车处于使用状态,因此我们直接模拟每辆车的运行过程,累加时间。 @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: @@ -99,27 +93,6 @@ class Solution: return ans ``` -```python -class Solution: - def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: - def f(x: str) -> int: - ans = 0 - st = 0 - for i, s in enumerate(garbage): - if t := s.count(x): - ans += t + st - st = 0 - if i < len(travel): - st += travel[i] - return ans - - return f('M') + f('P') + f('G') -``` - -### **Java** - - - ```java class Solution { public int garbageCollection(String[] garbage, int[] travel) { @@ -146,42 +119,6 @@ class Solution { } ``` -```java -class Solution { - private String[] garbage; - private int[] travel; - - public int garbageCollection(String[] garbage, int[] travel) { - this.garbage = garbage; - this.travel = travel; - return f('M') + f('P') + f('G'); - } - - private int f(char c) { - int ans = 0; - int st = 0; - for (int i = 0; i < garbage.length; ++i) { - int cnt = 0; - for (int j = 0; j < garbage[i].length(); ++j) { - if (garbage[i].charAt(j) == c) { - ++cnt; - } - } - if (cnt > 0) { - ans += cnt + st; - st = 0; - } - if (i < travel.length) { - st += travel[i]; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -208,36 +145,6 @@ public: }; ``` -```cpp -class Solution { -public: - int garbageCollection(vector& garbage, vector& travel) { - auto f = [&](char x) { - int ans = 0, st = 0; - for (int i = 0; i < garbage.size(); ++i) { - int cnt = 0; - for (char& c : garbage[i]) { - if (c == x) { - ++cnt; - } - } - if (cnt > 0) { - ans += cnt + st; - st = 0; - } - if (i < travel.size()) { - st += travel[i]; - } - } - return ans; - }; - return f('M') + f('P') + f('G'); - } -}; -``` - -### **Go** - ```go func garbageCollection(garbage []string, travel []int) (ans int) { last := [26]int{} @@ -258,28 +165,6 @@ func garbageCollection(garbage []string, travel []int) (ans int) { } ``` -```go -func garbageCollection(garbage []string, travel []int) (ans int) { - f := func(x rune) int { - ans, st := 0, 0 - for i, s := range garbage { - cnt := strings.Count(s, string(x)) - if cnt > 0 { - ans += cnt + st - st = 0 - } - if i < len(travel) { - st += travel[i] - } - } - return ans - } - return f('M') + f('P') + f('G') -} -``` - -### **TypeScript** - ```ts function garbageCollection(garbage: string[], travel: number[]): number { const n = garbage.length; @@ -303,34 +188,6 @@ function garbageCollection(garbage: string[], travel: number[]): number { } ``` -```ts -function garbageCollection(garbage: string[], travel: number[]): number { - const f = (x: string) => { - let ans = 0; - let st = 0; - for (let i = 0; i < garbage.length; ++i) { - let cnt = 0; - for (const c of garbage[i]) { - if (c === x) { - ++cnt; - } - } - if (cnt > 0) { - ans += cnt + st; - st = 0; - } - if (i < travel.length) { - st += travel[i]; - } - } - return ans; - }; - return f('M') + f('P') + f('G'); -} -``` - -### **Rust** - ```rust impl Solution { pub fn garbage_collection(garbage: Vec, travel: Vec) -> i32 { @@ -365,8 +222,6 @@ impl Solution { } ``` -### **C#** - ```cs public class Solution { public int GarbageCollection(string[] garbage, int[] travel) { @@ -386,10 +241,137 @@ public class Solution { } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: + def f(x: str) -> int: + ans = 0 + st = 0 + for i, s in enumerate(garbage): + if t := s.count(x): + ans += t + st + st = 0 + if i < len(travel): + st += travel[i] + return ans + + return f('M') + f('P') + f('G') +``` + +```java +class Solution { + private String[] garbage; + private int[] travel; + + public int garbageCollection(String[] garbage, int[] travel) { + this.garbage = garbage; + this.travel = travel; + return f('M') + f('P') + f('G'); + } + + private int f(char c) { + int ans = 0; + int st = 0; + for (int i = 0; i < garbage.length; ++i) { + int cnt = 0; + for (int j = 0; j < garbage[i].length(); ++j) { + if (garbage[i].charAt(j) == c) { + ++cnt; + } + } + if (cnt > 0) { + ans += cnt + st; + st = 0; + } + if (i < travel.length) { + st += travel[i]; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int garbageCollection(vector& garbage, vector& travel) { + auto f = [&](char x) { + int ans = 0, st = 0; + for (int i = 0; i < garbage.size(); ++i) { + int cnt = 0; + for (char& c : garbage[i]) { + if (c == x) { + ++cnt; + } + } + if (cnt > 0) { + ans += cnt + st; + st = 0; + } + if (i < travel.size()) { + st += travel[i]; + } + } + return ans; + }; + return f('M') + f('P') + f('G'); + } +}; +``` +```go +func garbageCollection(garbage []string, travel []int) (ans int) { + f := func(x rune) int { + ans, st := 0, 0 + for i, s := range garbage { + cnt := strings.Count(s, string(x)) + if cnt > 0 { + ans += cnt + st + st = 0 + } + if i < len(travel) { + st += travel[i] + } + } + return ans + } + return f('M') + f('P') + f('G') +} ``` +```ts +function garbageCollection(garbage: string[], travel: number[]): number { + const f = (x: string) => { + let ans = 0; + let st = 0; + for (let i = 0; i < garbage.length; ++i) { + let cnt = 0; + for (const c of garbage[i]) { + if (c === x) { + ++cnt; + } + } + if (cnt > 0) { + ans += cnt + st; + st = 0; + } + if (i < travel.length) { + st += travel[i]; + } + } + return ans; + }; + return f('M') + f('P') + f('G'); +} ``` + + diff --git a/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/README_EN.md b/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/README_EN.md index b631efb851fb2..ea9267b7e84fd 100644 --- a/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/README_EN.md +++ b/solution/2300-2399/2391.Minimum Amount of Time to Collect Garbage/README_EN.md @@ -64,9 +64,9 @@ It takes a total of 7 + 15 + 15 = 37 minutes to collect all the garbage. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,25 +82,6 @@ class Solution: return ans ``` -```python -class Solution: - def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: - def f(x: str) -> int: - ans = 0 - st = 0 - for i, s in enumerate(garbage): - if t := s.count(x): - ans += t + st - st = 0 - if i < len(travel): - st += travel[i] - return ans - - return f('M') + f('P') + f('G') -``` - -### **Java** - ```java class Solution { public int garbageCollection(String[] garbage, int[] travel) { @@ -127,42 +108,6 @@ class Solution { } ``` -```java -class Solution { - private String[] garbage; - private int[] travel; - - public int garbageCollection(String[] garbage, int[] travel) { - this.garbage = garbage; - this.travel = travel; - return f('M') + f('P') + f('G'); - } - - private int f(char c) { - int ans = 0; - int st = 0; - for (int i = 0; i < garbage.length; ++i) { - int cnt = 0; - for (int j = 0; j < garbage[i].length(); ++j) { - if (garbage[i].charAt(j) == c) { - ++cnt; - } - } - if (cnt > 0) { - ans += cnt + st; - st = 0; - } - if (i < travel.length) { - st += travel[i]; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -189,36 +134,6 @@ public: }; ``` -```cpp -class Solution { -public: - int garbageCollection(vector& garbage, vector& travel) { - auto f = [&](char x) { - int ans = 0, st = 0; - for (int i = 0; i < garbage.size(); ++i) { - int cnt = 0; - for (char& c : garbage[i]) { - if (c == x) { - ++cnt; - } - } - if (cnt > 0) { - ans += cnt + st; - st = 0; - } - if (i < travel.size()) { - st += travel[i]; - } - } - return ans; - }; - return f('M') + f('P') + f('G'); - } -}; -``` - -### **Go** - ```go func garbageCollection(garbage []string, travel []int) (ans int) { last := [26]int{} @@ -239,28 +154,6 @@ func garbageCollection(garbage []string, travel []int) (ans int) { } ``` -```go -func garbageCollection(garbage []string, travel []int) (ans int) { - f := func(x rune) int { - ans, st := 0, 0 - for i, s := range garbage { - cnt := strings.Count(s, string(x)) - if cnt > 0 { - ans += cnt + st - st = 0 - } - if i < len(travel) { - st += travel[i] - } - } - return ans - } - return f('M') + f('P') + f('G') -} -``` - -### **TypeScript** - ```ts function garbageCollection(garbage: string[], travel: number[]): number { const n = garbage.length; @@ -284,34 +177,6 @@ function garbageCollection(garbage: string[], travel: number[]): number { } ``` -```ts -function garbageCollection(garbage: string[], travel: number[]): number { - const f = (x: string) => { - let ans = 0; - let st = 0; - for (let i = 0; i < garbage.length; ++i) { - let cnt = 0; - for (const c of garbage[i]) { - if (c === x) { - ++cnt; - } - } - if (cnt > 0) { - ans += cnt + st; - st = 0; - } - if (i < travel.length) { - st += travel[i]; - } - } - return ans; - }; - return f('M') + f('P') + f('G'); -} -``` - -### **Rust** - ```rust impl Solution { pub fn garbage_collection(garbage: Vec, travel: Vec) -> i32 { @@ -346,8 +211,6 @@ impl Solution { } ``` -### **C#** - ```cs public class Solution { public int GarbageCollection(string[] garbage, int[] travel) { @@ -367,10 +230,137 @@ public class Solution { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: + def f(x: str) -> int: + ans = 0 + st = 0 + for i, s in enumerate(garbage): + if t := s.count(x): + ans += t + st + st = 0 + if i < len(travel): + st += travel[i] + return ans + + return f('M') + f('P') + f('G') ``` +```java +class Solution { + private String[] garbage; + private int[] travel; + + public int garbageCollection(String[] garbage, int[] travel) { + this.garbage = garbage; + this.travel = travel; + return f('M') + f('P') + f('G'); + } + + private int f(char c) { + int ans = 0; + int st = 0; + for (int i = 0; i < garbage.length; ++i) { + int cnt = 0; + for (int j = 0; j < garbage[i].length(); ++j) { + if (garbage[i].charAt(j) == c) { + ++cnt; + } + } + if (cnt > 0) { + ans += cnt + st; + st = 0; + } + if (i < travel.length) { + st += travel[i]; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int garbageCollection(vector& garbage, vector& travel) { + auto f = [&](char x) { + int ans = 0, st = 0; + for (int i = 0; i < garbage.size(); ++i) { + int cnt = 0; + for (char& c : garbage[i]) { + if (c == x) { + ++cnt; + } + } + if (cnt > 0) { + ans += cnt + st; + st = 0; + } + if (i < travel.size()) { + st += travel[i]; + } + } + return ans; + }; + return f('M') + f('P') + f('G'); + } +}; +``` + +```go +func garbageCollection(garbage []string, travel []int) (ans int) { + f := func(x rune) int { + ans, st := 0, 0 + for i, s := range garbage { + cnt := strings.Count(s, string(x)) + if cnt > 0 { + ans += cnt + st + st = 0 + } + if i < len(travel) { + st += travel[i] + } + } + return ans + } + return f('M') + f('P') + f('G') +} +``` + +```ts +function garbageCollection(garbage: string[], travel: number[]): number { + const f = (x: string) => { + let ans = 0; + let st = 0; + for (let i = 0; i < garbage.length; ++i) { + let cnt = 0; + for (const c of garbage[i]) { + if (c === x) { + ++cnt; + } + } + if (cnt > 0) { + ans += cnt + st; + st = 0; + } + if (i < travel.length) { + st += travel[i]; + } + } + return ans; + }; + return f('M') + f('P') + f('G'); +} ``` + + diff --git a/solution/2300-2399/2392.Build a Matrix With Conditions/README.md b/solution/2300-2399/2392.Build a Matrix With Conditions/README.md index 2d6623991e912..f4859a6916416 100644 --- a/solution/2300-2399/2392.Build a Matrix With Conditions/README.md +++ b/solution/2300-2399/2392.Build a Matrix With Conditions/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:拓扑排序** +### 方法一:拓扑排序 利用拓扑排序,找到一个合法的 `row` 序列和 `col` 序列,然后根据这两个序列构造出矩阵。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def buildMatrix( @@ -117,10 +111,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int k; @@ -175,8 +165,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -230,8 +218,6 @@ public: }; ``` -### **Go** - ```go func buildMatrix(k int, rowConditions [][]int, colConditions [][]int) [][]int { f := func(cond [][]int) []int { @@ -288,8 +274,6 @@ func buildMatrix(k int, rowConditions [][]int, colConditions [][]int) [][]int { } ``` -### **TypeScript** - ```ts function buildMatrix(k: number, rowConditions: number[][], colConditions: number[][]): number[][] { function f(cond) { @@ -335,11 +319,6 @@ function buildMatrix(k: number, rowConditions: number[][], colConditions: number } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2392.Build a Matrix With Conditions/README_EN.md b/solution/2300-2399/2392.Build a Matrix With Conditions/README_EN.md index 5b3fe05799ff3..3f8968c4f90a1 100644 --- a/solution/2300-2399/2392.Build a Matrix With Conditions/README_EN.md +++ b/solution/2300-2399/2392.Build a Matrix With Conditions/README_EN.md @@ -63,12 +63,10 @@ No matrix can satisfy all the conditions, so we return the empty matrix. ## Solutions -Topological Sort. +### Solution 1 -### **Python3** - ```python class Solution: def buildMatrix( @@ -105,8 +103,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int k; @@ -161,8 +157,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -216,8 +210,6 @@ public: }; ``` -### **Go** - ```go func buildMatrix(k int, rowConditions [][]int, colConditions [][]int) [][]int { f := func(cond [][]int) []int { @@ -274,8 +266,6 @@ func buildMatrix(k int, rowConditions [][]int, colConditions [][]int) [][]int { } ``` -### **TypeScript** - ```ts function buildMatrix(k: number, rowConditions: number[][], colConditions: number[][]): number[][] { function f(cond) { @@ -321,11 +311,6 @@ function buildMatrix(k: number, rowConditions: number[][], colConditions: number } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2393.Count Strictly Increasing Subarrays/README.md b/solution/2300-2399/2393.Count Strictly Increasing Subarrays/README.md index d946d9966ecbe..e204a4a6062cd 100644 --- a/solution/2300-2399/2393.Count Strictly Increasing Subarrays/README.md +++ b/solution/2300-2399/2393.Count Strictly Increasing Subarrays/README.md @@ -45,26 +45,14 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 利用双指针,找到每一段连续递增子数组的长度,我们记为 `cnt`,每次将 $(1+cnt)\times cnt / 2$ 累加到答案中。 时间复杂度 $O(n)$,空间复杂度 $O(1)$,其中 $n$ 是数组的长度。 -**方法二:枚举** - -我们可以枚举数组中的每一个元素,找到以该元素为结尾的严格递增子数组的个数,然后将这些个数累加到答案中。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$,其中 $n$ 是数组的长度。 - -### **Python3** - - - ```python class Solution: def countSubarrays(self, nums: List[int]) -> int: @@ -79,24 +67,6 @@ class Solution: return ans ``` -```python -class Solution: - def countSubarrays(self, nums: List[int]) -> int: - ans = pre = cnt = 0 - for x in nums: - if pre < x: - cnt += 1 - else: - cnt = 1 - pre = x - ans += cnt - return ans -``` - -### **Java** - - - ```java class Solution { public long countSubarrays(int[] nums) { @@ -116,27 +86,6 @@ class Solution { } ``` -```java -class Solution { - public long countSubarrays(int[] nums) { - long ans = 0; - int pre = 0, cnt = 0; - for (int x : nums) { - if (pre < x) { - ++cnt; - } else { - cnt = 1; - } - pre = x; - ans += cnt; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -157,6 +106,84 @@ public: }; ``` +```go +func countSubarrays(nums []int) int64 { + ans := 0 + i, n := 0, len(nums) + for i < n { + j := i + 1 + for j < n && nums[j] > nums[j-1] { + j++ + } + cnt := j - i + ans += (1 + cnt) * cnt / 2 + i = j + } + return int64(ans) +} +``` + +```ts +function countSubarrays(nums: number[]): number { + let ans = 0; + let i = 0; + const n = nums.length; + while (i < n) { + let j = i + 1; + while (j < n && nums[j] > nums[j - 1]) { + ++j; + } + const cnt = j - i; + ans += ((1 + cnt) * cnt) / 2; + i = j; + } + return ans; +} +``` + + + +### 方法二:枚举 + +我们可以枚举数组中的每一个元素,找到以该元素为结尾的严格递增子数组的个数,然后将这些个数累加到答案中。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$,其中 $n$ 是数组的长度。 + + + +```python +class Solution: + def countSubarrays(self, nums: List[int]) -> int: + ans = pre = cnt = 0 + for x in nums: + if pre < x: + cnt += 1 + else: + cnt = 1 + pre = x + ans += cnt + return ans +``` + +```java +class Solution { + public long countSubarrays(int[] nums) { + long ans = 0; + int pre = 0, cnt = 0; + for (int x : nums) { + if (pre < x) { + ++cnt; + } else { + cnt = 1; + } + pre = x; + ans += cnt; + } + return ans; + } +} +``` + ```cpp class Solution { public: @@ -177,25 +204,6 @@ public: }; ``` -### **Go** - -```go -func countSubarrays(nums []int) int64 { - ans := 0 - i, n := 0, len(nums) - for i < n { - j := i + 1 - for j < n && nums[j] > nums[j-1] { - j++ - } - cnt := j - i - ans += (1 + cnt) * cnt / 2 - i = j - } - return int64(ans) -} -``` - ```go func countSubarrays(nums []int) (ans int64) { pre, cnt := 0, 0 @@ -212,26 +220,6 @@ func countSubarrays(nums []int) (ans int64) { } ``` -### **TypeScript** - -```ts -function countSubarrays(nums: number[]): number { - let ans = 0; - let i = 0; - const n = nums.length; - while (i < n) { - let j = i + 1; - while (j < n && nums[j] > nums[j - 1]) { - ++j; - } - const cnt = j - i; - ans += ((1 + cnt) * cnt) / 2; - i = j; - } - return ans; -} -``` - ```ts function countSubarrays(nums: number[]): number { let ans = 0; @@ -250,11 +238,6 @@ function countSubarrays(nums: number[]): number { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2393.Count Strictly Increasing Subarrays/README_EN.md b/solution/2300-2399/2393.Count Strictly Increasing Subarrays/README_EN.md index de558b7552916..51f27d6c7b8f3 100644 --- a/solution/2300-2399/2393.Count Strictly Increasing Subarrays/README_EN.md +++ b/solution/2300-2399/2393.Count Strictly Increasing Subarrays/README_EN.md @@ -41,9 +41,9 @@ The total number of subarrays is 6 + 3 + 1 = 10. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,22 +59,6 @@ class Solution: return ans ``` -```python -class Solution: - def countSubarrays(self, nums: List[int]) -> int: - ans = pre = cnt = 0 - for x in nums: - if pre < x: - cnt += 1 - else: - cnt = 1 - pre = x - ans += cnt - return ans -``` - -### **Java** - ```java class Solution { public long countSubarrays(int[] nums) { @@ -94,27 +78,6 @@ class Solution { } ``` -```java -class Solution { - public long countSubarrays(int[] nums) { - long ans = 0; - int pre = 0, cnt = 0; - for (int x : nums) { - if (pre < x) { - ++cnt; - } else { - cnt = 1; - } - pre = x; - ans += cnt; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -135,6 +98,80 @@ public: }; ``` +```go +func countSubarrays(nums []int) int64 { + ans := 0 + i, n := 0, len(nums) + for i < n { + j := i + 1 + for j < n && nums[j] > nums[j-1] { + j++ + } + cnt := j - i + ans += (1 + cnt) * cnt / 2 + i = j + } + return int64(ans) +} +``` + +```ts +function countSubarrays(nums: number[]): number { + let ans = 0; + let i = 0; + const n = nums.length; + while (i < n) { + let j = i + 1; + while (j < n && nums[j] > nums[j - 1]) { + ++j; + } + const cnt = j - i; + ans += ((1 + cnt) * cnt) / 2; + i = j; + } + return ans; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def countSubarrays(self, nums: List[int]) -> int: + ans = pre = cnt = 0 + for x in nums: + if pre < x: + cnt += 1 + else: + cnt = 1 + pre = x + ans += cnt + return ans +``` + +```java +class Solution { + public long countSubarrays(int[] nums) { + long ans = 0; + int pre = 0, cnt = 0; + for (int x : nums) { + if (pre < x) { + ++cnt; + } else { + cnt = 1; + } + pre = x; + ans += cnt; + } + return ans; + } +} +``` + ```cpp class Solution { public: @@ -155,25 +192,6 @@ public: }; ``` -### **Go** - -```go -func countSubarrays(nums []int) int64 { - ans := 0 - i, n := 0, len(nums) - for i < n { - j := i + 1 - for j < n && nums[j] > nums[j-1] { - j++ - } - cnt := j - i - ans += (1 + cnt) * cnt / 2 - i = j - } - return int64(ans) -} -``` - ```go func countSubarrays(nums []int) (ans int64) { pre, cnt := 0, 0 @@ -190,26 +208,6 @@ func countSubarrays(nums []int) (ans int64) { } ``` -### **TypeScript** - -```ts -function countSubarrays(nums: number[]): number { - let ans = 0; - let i = 0; - const n = nums.length; - while (i < n) { - let j = i + 1; - while (j < n && nums[j] > nums[j - 1]) { - ++j; - } - const cnt = j - i; - ans += ((1 + cnt) * cnt) / 2; - i = j; - } - return ans; -} -``` - ```ts function countSubarrays(nums: number[]): number { let ans = 0; @@ -228,11 +226,6 @@ function countSubarrays(nums: number[]): number { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2394.Employees With Deductions/README.md b/solution/2300-2399/2394.Employees With Deductions/README.md index 9a7f0446ac9ec..08b4fa29a0d5b 100644 --- a/solution/2300-2399/2394.Employees With Deductions/README.md +++ b/solution/2300-2399/2394.Employees With Deductions/README.md @@ -98,14 +98,10 @@ Logs 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -124,3 +120,5 @@ WHERE IFNULL(tot, 0) < needed_hours; ``` + + diff --git a/solution/2300-2399/2394.Employees With Deductions/README_EN.md b/solution/2300-2399/2394.Employees With Deductions/README_EN.md index 4cb8b5c877c59..86a3b94c65b23 100644 --- a/solution/2300-2399/2394.Employees With Deductions/README_EN.md +++ b/solution/2300-2399/2394.Employees With Deductions/README_EN.md @@ -95,9 +95,9 @@ Employee 3: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -117,3 +117,5 @@ WHERE IFNULL(tot, 0) < needed_hours; ``` + + diff --git a/solution/2300-2399/2395.Find Subarrays With Equal Sum/README.md b/solution/2300-2399/2395.Find Subarrays With Equal Sum/README.md index 3d1ffcf8990ef..1ebc65e0f1c2d 100644 --- a/solution/2300-2399/2395.Find Subarrays With Equal Sum/README.md +++ b/solution/2300-2399/2395.Find Subarrays With Equal Sum/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以遍历数组 $nums$,用哈希表 $vis$ 记录数组中每两个相邻元素的和,如果当前两个元素的和已经在哈希表中出现过,则返回 `true`,否则将当前两个元素的和加入哈希表中。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def findSubarrays(self, nums: List[int]) -> bool: @@ -74,10 +68,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean findSubarrays(int[] nums) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +99,6 @@ public: }; ``` -### **Go** - ```go func findSubarrays(nums []int) bool { vis := map[int]bool{} @@ -127,8 +113,6 @@ func findSubarrays(nums []int) bool { } ``` -### **TypeScript** - ```ts function findSubarrays(nums: number[]): boolean { const vis: Set = new Set(); @@ -143,8 +127,6 @@ function findSubarrays(nums: number[]): boolean { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -161,8 +143,6 @@ impl Solution { } ``` -### **C** - ```c bool findSubarrays(int* nums, int numsSize) { for (int i = 1; i < numsSize - 1; i++) { @@ -176,11 +156,6 @@ bool findSubarrays(int* nums, int numsSize) { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2395.Find Subarrays With Equal Sum/README_EN.md b/solution/2300-2399/2395.Find Subarrays With Equal Sum/README_EN.md index 91c16e843037d..5d8272e0c0e2e 100644 --- a/solution/2300-2399/2395.Find Subarrays With Equal Sum/README_EN.md +++ b/solution/2300-2399/2395.Find Subarrays With Equal Sum/README_EN.md @@ -46,9 +46,9 @@ Note that even though the subarrays have the same content, the two subarrays are ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean findSubarrays(int[] nums) { @@ -77,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func findSubarrays(nums []int) bool { vis := map[int]bool{} @@ -112,8 +106,6 @@ func findSubarrays(nums []int) bool { } ``` -### **TypeScript** - ```ts function findSubarrays(nums: number[]): boolean { const vis: Set = new Set(); @@ -128,8 +120,6 @@ function findSubarrays(nums: number[]): boolean { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -146,8 +136,6 @@ impl Solution { } ``` -### **C** - ```c bool findSubarrays(int* nums, int numsSize) { for (int i = 1; i < numsSize - 1; i++) { @@ -161,11 +149,6 @@ bool findSubarrays(int* nums, int numsSize) { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2396.Strictly Palindromic Number/README.md b/solution/2300-2399/2396.Strictly Palindromic Number/README.md index 9ed2f8b05437d..047c81af52804 100644 --- a/solution/2300-2399/2396.Strictly Palindromic Number/README.md +++ b/solution/2300-2399/2396.Strictly Palindromic Number/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 当 $n=4$ 时,二进制表示为 $100$,不是回文串; @@ -56,20 +54,12 @@ -### **Python3** - - - ```python class Solution: def isStrictlyPalindromic(self, n: int) -> bool: return False ``` -### **Java** - - - ```java class Solution { public boolean isStrictlyPalindromic(int n) { @@ -78,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -89,24 +77,18 @@ public: }; ``` -### **Go** - ```go func isStrictlyPalindromic(n int) bool { return false } ``` -### **TypeScript** - ```ts function isStrictlyPalindromic(n: number): boolean { return false; } ``` -### **Rust** - ```rust impl Solution { pub fn is_strictly_palindromic(n: i32) -> bool { @@ -115,19 +97,12 @@ impl Solution { } ``` -### **C** - ```c bool isStrictlyPalindromic(int n) { return 0; } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2396.Strictly Palindromic Number/README_EN.md b/solution/2300-2399/2396.Strictly Palindromic Number/README_EN.md index f4496ce8094f9..a9373753f6b3d 100644 --- a/solution/2300-2399/2396.Strictly Palindromic Number/README_EN.md +++ b/solution/2300-2399/2396.Strictly Palindromic Number/README_EN.md @@ -41,9 +41,9 @@ Therefore, we return false. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean isStrictlyPalindromic(int n) { @@ -61,8 +59,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -72,24 +68,18 @@ public: }; ``` -### **Go** - ```go func isStrictlyPalindromic(n int) bool { return false } ``` -### **TypeScript** - ```ts function isStrictlyPalindromic(n: number): boolean { return false; } ``` -### **Rust** - ```rust impl Solution { pub fn is_strictly_palindromic(n: i32) -> bool { @@ -98,19 +88,12 @@ impl Solution { } ``` -### **C** - ```c bool isStrictlyPalindromic(int n) { return 0; } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2397.Maximum Rows Covered by Columns/README.md b/solution/2300-2399/2397.Maximum Rows Covered by Columns/README.md index d1295c38660ca..cd9d9d64769a4 100644 --- a/solution/2300-2399/2397.Maximum Rows Covered by Columns/README.md +++ b/solution/2300-2399/2397.Maximum Rows Covered by Columns/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:二进制枚举** +### 方法一:二进制枚举 我们先将矩阵中的每一行转换成一个二进制数,记录在数组 $rows$ 中,其中 $rows[i]$ 表示第 $i$ 行对应的二进制数,而 $rows[i]$ 这个二进制数的第 $j$ 位表示第 $i$ 行第 $j$ 列的值。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def maximumRows(self, matrix: List[List[int]], numSelect: int) -> int: @@ -99,10 +93,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumRows(int[][] matrix, int numSelect) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -165,8 +153,6 @@ public: }; ``` -### **Go** - ```go func maximumRows(matrix [][]int, numSelect int) (ans int) { m, n := len(matrix), len(matrix[0]) @@ -196,8 +182,6 @@ func maximumRows(matrix [][]int, numSelect int) (ans int) { } ``` -### **TypeScript** - ```ts function maximumRows(matrix: number[][], numSelect: number): number { const [m, n] = [matrix.length, matrix[0].length]; @@ -235,11 +219,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2397.Maximum Rows Covered by Columns/README_EN.md b/solution/2300-2399/2397.Maximum Rows Covered by Columns/README_EN.md index 0b3ba2a5d4aaa..ac7efadda0cbc 100644 --- a/solution/2300-2399/2397.Maximum Rows Covered by Columns/README_EN.md +++ b/solution/2300-2399/2397.Maximum Rows Covered by Columns/README_EN.md @@ -55,7 +55,7 @@ Therefore, we return 2. ## Solutions -**Solution 1: Binary Enumeration** +### Solution 1: Binary Enumeration First, we convert each row of the matrix into a binary number and record it in the array $rows$. Here, $rows[i]$ represents the binary number corresponding to the $i$-th row, and the $j$-th bit of this binary number $rows[i]$ represents the value of the $i$-th row and $j$-th column. @@ -65,8 +65,6 @@ The time complexity is $O(2^n \times m)$, and the space complexity is $O(m)$. Wh -### **Python3** - ```python class Solution: def maximumRows(self, matrix: List[List[int]], numSelect: int) -> int: @@ -84,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumRows(int[][] matrix, int numSelect) { @@ -116,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +142,6 @@ public: }; ``` -### **Go** - ```go func maximumRows(matrix [][]int, numSelect int) (ans int) { m, n := len(matrix), len(matrix[0]) @@ -179,8 +171,6 @@ func maximumRows(matrix [][]int, numSelect int) (ans int) { } ``` -### **TypeScript** - ```ts function maximumRows(matrix: number[][], numSelect: number): number { const [m, n] = [matrix.length, matrix[0].length]; @@ -218,11 +208,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2398.Maximum Number of Robots Within Budget/README.md b/solution/2300-2399/2398.Maximum Number of Robots Within Budget/README.md index 0d04a85278523..65b12488da3ec 100644 --- a/solution/2300-2399/2398.Maximum Number of Robots Within Budget/README.md +++ b/solution/2300-2399/2398.Maximum Number of Robots Within Budget/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:双指针 + 单调队列** +### 方法一:双指针 + 单调队列 问题实际上是求滑动窗口内的最大值,可以用单调队列来求解。只需要二分枚举窗口 $k$ 的大小,找到一个最大的 $k$,使得满足题目要求。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def maximumRobots( @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumRobots(int[] chargeTimes, int[] runningCosts, long budget) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func maximumRobots(chargeTimes []int, runningCosts []int, budget int64) int { s := int64(0) @@ -168,17 +154,6 @@ func maximumRobots(chargeTimes []int, runningCosts []int, budget int64) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2398.Maximum Number of Robots Within Budget/README_EN.md b/solution/2300-2399/2398.Maximum Number of Robots Within Budget/README_EN.md index 54fae5b124db9..7a46a96a1c6f8 100644 --- a/solution/2300-2399/2398.Maximum Number of Robots Within Budget/README_EN.md +++ b/solution/2300-2399/2398.Maximum Number of Robots Within Budget/README_EN.md @@ -42,9 +42,9 @@ It can be shown that it is not possible to run more than 3 consecutive robots wi ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumRobots(int[] chargeTimes, int[] runningCosts, long budget) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +120,6 @@ public: }; ``` -### **Go** - ```go func maximumRobots(chargeTimes []int, runningCosts []int, budget int64) int { s := int64(0) @@ -150,17 +144,6 @@ func maximumRobots(chargeTimes []int, runningCosts []int, budget int64) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2300-2399/2399.Check Distances Between Same Letters/README.md b/solution/2300-2399/2399.Check Distances Between Same Letters/README.md index ae1f6d931b684..933d58dcf795e 100644 --- a/solution/2300-2399/2399.Check Distances Between Same Letters/README.md +++ b/solution/2300-2399/2399.Check Distances Between Same Letters/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:数组或哈希表** +### 方法一:数组或哈希表 我们可以用哈希表 $d$ 记录每个字母出现的下标,然后遍历哈希表,判断每个字母的下标之差是否等于 `distance` 中对应的值。如果出现不等的情况,直接返回 `false`。如果遍历结束后,没有出现不等的情况,返回 `true`。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: @@ -76,10 +70,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean checkDistances(String s, int[] distance) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func checkDistances(s string, distance []int) bool { d := [26]int{} @@ -131,25 +117,6 @@ func checkDistances(s string, distance []int) bool { } ``` -### **C** - -```c -bool checkDistances(char* s, int* distance, int distanceSize) { - int n = strlen(s); - int d[26] = {0}; - for (int i = 0; i < n; i++) { - int j = s[i] - 'a'; - if (d[j] > 0 && i - d[j] != distance[j]) { - return false; - } - d[j] = i + 1; - } - return true; -} -``` - -### **TypeScript** - ```ts function checkDistances(s: string, distance: number[]): boolean { const n = s.length; @@ -165,8 +132,6 @@ function checkDistances(s: string, distance: number[]): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn check_distances(s: String, distance: Vec) -> bool { @@ -186,11 +151,21 @@ impl Solution { } ``` -### **...** - -``` - - +```c +bool checkDistances(char* s, int* distance, int distanceSize) { + int n = strlen(s); + int d[26] = {0}; + for (int i = 0; i < n; i++) { + int j = s[i] - 'a'; + if (d[j] > 0 && i - d[j] != distance[j]) { + return false; + } + d[j] = i + 1; + } + return true; +} ``` + + diff --git a/solution/2300-2399/2399.Check Distances Between Same Letters/README_EN.md b/solution/2300-2399/2399.Check Distances Between Same Letters/README_EN.md index e4c2ef0547987..54360e56bd35b 100644 --- a/solution/2300-2399/2399.Check Distances Between Same Letters/README_EN.md +++ b/solution/2300-2399/2399.Check Distances Between Same Letters/README_EN.md @@ -49,9 +49,9 @@ Because distance[0] = 1, s is not a well-spaced string. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean checkDistances(String s, int[] distance) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +97,6 @@ public: }; ``` -### **Go** - ```go func checkDistances(s string, distance []int) bool { d := [26]int{} @@ -117,25 +111,6 @@ func checkDistances(s string, distance []int) bool { } ``` -### **C** - -```c -bool checkDistances(char* s, int* distance, int distanceSize) { - int n = strlen(s); - int d[26] = {0}; - for (int i = 0; i < n; i++) { - int j = s[i] - 'a'; - if (d[j] > 0 && i - d[j] != distance[j]) { - return false; - } - d[j] = i + 1; - } - return true; -} -``` - -### **TypeScript** - ```ts function checkDistances(s: string, distance: number[]): boolean { const n = s.length; @@ -151,8 +126,6 @@ function checkDistances(s: string, distance: number[]): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn check_distances(s: String, distance: Vec) -> bool { @@ -172,11 +145,21 @@ impl Solution { } ``` -### **...** - -``` - - +```c +bool checkDistances(char* s, int* distance, int distanceSize) { + int n = strlen(s); + int d[26] = {0}; + for (int i = 0; i < n; i++) { + int j = s[i] - 'a'; + if (d[j] > 0 && i - d[j] != distance[j]) { + return false; + } + d[j] = i + 1; + } + return true; +} ``` + + diff --git a/solution/2400-2499/2400.Number of Ways to Reach a Position After Exactly k Steps/README.md b/solution/2400-2499/2400.Number of Ways to Reach a Position After Exactly k Steps/README.md index 099b2b5173256..0f5cb11413d78 100644 --- a/solution/2400-2499/2400.Number of Ways to Reach a Position After Exactly k Steps/README.md +++ b/solution/2400-2499/2400.Number of Ways to Reach a Position After Exactly k Steps/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, j)$,表示当前位置距离目标位置的距离为 $i$,还剩 $j$ 步,有多少种方法到达目标位置。那么答案就是 $dfs(abs(startPos - endPos), k)$。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: @@ -82,10 +76,6 @@ class Solution: return dfs(abs(startPos - endPos), k) ``` -### **Java** - - - ```java class Solution { private Integer[][] f; @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func numberOfWays(startPos int, endPos int, k int) int { const mod = 1e9 + 7 @@ -180,8 +166,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function numberOfWays(startPos: number, endPos: number, k: number): number { const mod = 10 ** 9 + 7; @@ -204,11 +188,6 @@ function numberOfWays(startPos: number, endPos: number, k: number): number { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2400.Number of Ways to Reach a Position After Exactly k Steps/README_EN.md b/solution/2400-2499/2400.Number of Ways to Reach a Position After Exactly k Steps/README_EN.md index d3ddfcf70bd29..c6176ecf2f2c4 100644 --- a/solution/2400-2499/2400.Number of Ways to Reach a Position After Exactly k Steps/README_EN.md +++ b/solution/2400-2499/2400.Number of Ways to Reach a Position After Exactly k Steps/README_EN.md @@ -41,7 +41,7 @@ It can be proven that no other way is possible, so we return 3. ## Solutions -**Solution 1: Memorization Search** +### Solution 1: Memorization Search We design a function $dfs(i, j)$, which represents the number of ways to reach the target position when the current position is $i$ distance from the target position and there are $j$ steps left. The answer is $dfs(abs(startPos - endPos), k)$. @@ -60,8 +60,6 @@ The time complexity is $O(k^2)$, and the space complexity is $O(k^2)$. Here, $k$ -### **Python3** - ```python class Solution: def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: @@ -77,8 +75,6 @@ class Solution: return dfs(abs(startPos - endPos), k) ``` -### **Java** - ```java class Solution { private Integer[][] f; @@ -106,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +127,6 @@ public: }; ``` -### **Go** - ```go func numberOfWays(startPos int, endPos int, k int) int { const mod = 1e9 + 7 @@ -173,8 +165,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function numberOfWays(startPos: number, endPos: number, k: number): number { const mod = 10 ** 9 + 7; @@ -197,11 +187,6 @@ function numberOfWays(startPos: number, endPos: number, k: number): number { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2401.Longest Nice Subarray/README.md b/solution/2400-2499/2401.Longest Nice Subarray/README.md index e16097c1e0203..e9b43ea373c3e 100644 --- a/solution/2400-2499/2401.Longest Nice Subarray/README.md +++ b/solution/2400-2499/2401.Longest Nice Subarray/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们定义一个变量 $mask$,用于记录当前子数组中的元素按位或的结果,初始时 $mask = 0$。另外,使用双指针 $j$ 和 $i$ 分别指向当前子数组的左右端点,初始时 $i = j = 0$。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def longestNiceSubarray(self, nums: List[int]) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestNiceSubarray(int[] nums) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func longestNiceSubarray(nums []int) (ans int) { mask, j := 0, 0 @@ -140,8 +126,6 @@ func longestNiceSubarray(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function longestNiceSubarray(nums: number[]): number { let mask = 0; @@ -157,11 +141,6 @@ function longestNiceSubarray(nums: number[]): number { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2401.Longest Nice Subarray/README_EN.md b/solution/2400-2499/2401.Longest Nice Subarray/README_EN.md index 43cdbfe845a72..05a5b9cdd7539 100644 --- a/solution/2400-2499/2401.Longest Nice Subarray/README_EN.md +++ b/solution/2400-2499/2401.Longest Nice Subarray/README_EN.md @@ -44,7 +44,7 @@ It can be proven that no longer nice subarray can be obtained, so we return 3. -### **Python3** - ```python class Solution: def longestNiceSubarray(self, nums: List[int]) -> int: @@ -77,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestNiceSubarray(int[] nums) { @@ -95,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +108,6 @@ public: }; ``` -### **Go** - ```go func longestNiceSubarray(nums []int) (ans int) { mask, j := 0, 0 @@ -132,8 +124,6 @@ func longestNiceSubarray(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function longestNiceSubarray(nums: number[]): number { let mask = 0; @@ -149,11 +139,6 @@ function longestNiceSubarray(nums: number[]): number { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2402.Meeting Rooms III/README.md b/solution/2400-2499/2402.Meeting Rooms III/README.md index a6c23fbc97b83..cc0eab6d62840 100644 --- a/solution/2400-2499/2402.Meeting Rooms III/README.md +++ b/solution/2400-2499/2402.Meeting Rooms III/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:优先队列(小根堆)** +### 方法一:优先队列(小根堆) 我们定义两个优先队列,分别表示空闲会议室、使用中的会议室。其中:空闲会议室 `idle` 依据**下标**排序;而使用中的会议室 `busy` 依据**结束时间、下标**排序。 @@ -87,10 +85,6 @@ -### **Python3** - - - ```python class Solution: def mostBooked(self, n: int, meetings: List[List[int]]) -> int: @@ -117,10 +111,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int mostBooked(int n, int[][] meetings) { @@ -159,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; using pii = pair; @@ -203,8 +191,6 @@ public: }; ``` -### **Go** - ```go func mostBooked(n int, meetings [][]int) int { sort.Slice(meetings, func(i, j int) bool { return meetings[i][0] < meetings[j][0] }) @@ -262,17 +248,6 @@ func (h *hp2) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp2) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2402.Meeting Rooms III/README_EN.md b/solution/2400-2499/2402.Meeting Rooms III/README_EN.md index 1183de90994c9..63268fbc47299 100644 --- a/solution/2400-2499/2402.Meeting Rooms III/README_EN.md +++ b/solution/2400-2499/2402.Meeting Rooms III/README_EN.md @@ -65,7 +65,7 @@ Room 0 held 1 meeting while rooms 1 and 2 each held 2 meetings, so we return 1. ## Solutions -**Solution 1: Priority Queue (Min Heap)** +### Solution 1: Priority Queue (Min Heap) We define two priority queues, representing idle meeting rooms and busy meeting rooms, respectively. Among them: the idle meeting rooms `idle` are sorted according to **index**; while the busy meeting rooms `busy` are sorted according to **end time, index**. @@ -83,8 +83,6 @@ Similar problems: -### **Python3** - ```python class Solution: def mostBooked(self, n: int, meetings: List[List[int]]) -> int: @@ -111,8 +109,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int mostBooked(int n, int[][] meetings) { @@ -151,8 +147,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; using pii = pair; @@ -195,8 +189,6 @@ public: }; ``` -### **Go** - ```go func mostBooked(n int, meetings [][]int) int { sort.Slice(meetings, func(i, j int) bool { return meetings[i][0] < meetings[j][0] }) @@ -254,17 +246,6 @@ func (h *hp2) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp2) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2403.Minimum Time to Kill All Monsters/README.md b/solution/2400-2499/2403.Minimum Time to Kill All Monsters/README.md index 49e14eb00eed1..a6b9f68bb80da 100644 --- a/solution/2400-2499/2403.Minimum Time to Kill All Monsters/README.md +++ b/solution/2400-2499/2403.Minimum Time to Kill All Monsters/README.md @@ -77,9 +77,7 @@ ## 解法 - - -**方法一:状态压缩 + 记忆化搜索或动态规划** +### 方法一:状态压缩 + 记忆化搜索或动态规划 由于打怪才能增加每天法力的收益 $gain$,不同的打怪顺序对结果有影响,需要枚举。注意到题目的数据范围较小,考虑使用状态压缩动态规划求解。 @@ -89,10 +87,6 @@ -### **Python3** - - - ```python class Solution: def minimumTime(self, power: List[int]) -> int: @@ -111,24 +105,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def minimumTime(self, power: List[int]) -> int: - n = len(power) - dp = [inf] * (1 << n) - dp[0] = 0 - for mask in range(1, 1 << n): - cnt = mask.bit_count() - for i, v in enumerate(power): - if (mask >> i) & 1: - dp[mask] = min(dp[mask], dp[mask ^ (1 << i)] + (v + cnt - 1) // cnt) - return dp[-1] -``` - -### **Java** - - - ```java class Solution { private int n; @@ -164,28 +140,6 @@ class Solution { } ``` -```java -class Solution { - public long minimumTime(int[] power) { - int n = power.length; - long[] dp = new long[1 << n]; - Arrays.fill(dp, Long.MAX_VALUE); - dp[0] = 0; - for (int mask = 1; mask < 1 << n; ++mask) { - int cnt = Integer.bitCount(mask); - for (int i = 0; i < n; ++i) { - if (((mask >> i) & 1) == 1) { - dp[mask] = Math.min(dp[mask], dp[mask ^ (1 << i)] + (power[i] + cnt - 1) / cnt); - } - } - } - return dp[(1 << n) - 1]; - } -} -``` - -### **C++** - ```cpp using ll = long long; @@ -217,28 +171,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long minimumTime(vector& power) { - int n = power.size(); - vector dp(1 << n, LONG_MAX); - dp[0] = 0; - for (int mask = 1; mask < 1 << n; ++mask) { - int cnt = __builtin_popcount(mask); - for (int i = 0; i < n; ++i) { - if ((mask >> i) & 1) { - dp[mask] = min(dp[mask], dp[mask ^ (1 << i)] + (power[i] + cnt - 1) / cnt); - } - } - } - return dp[(1 << n) - 1]; - } -}; -``` - -### **Go** - ```go func minimumTime(power []int) int64 { n := len(power) @@ -269,28 +201,6 @@ func minimumTime(power []int) int64 { } ``` -```go -func minimumTime(power []int) int64 { - n := len(power) - dp := make([]int64, 1<> i) & 1) == 1 { - dp[mask] = min(dp[mask], dp[mask^(1< + +### 方法二 + + + +```python +class Solution: + def minimumTime(self, power: List[int]) -> int: + n = len(power) + dp = [inf] * (1 << n) + dp[0] = 0 + for mask in range(1, 1 << n): + cnt = mask.bit_count() + for i, v in enumerate(power): + if (mask >> i) & 1: + dp[mask] = min(dp[mask], dp[mask ^ (1 << i)] + (v + cnt - 1) // cnt) + return dp[-1] +``` + +```java +class Solution { + public long minimumTime(int[] power) { + int n = power.length; + long[] dp = new long[1 << n]; + Arrays.fill(dp, Long.MAX_VALUE); + dp[0] = 0; + for (int mask = 1; mask < 1 << n; ++mask) { + int cnt = Integer.bitCount(mask); + for (int i = 0; i < n; ++i) { + if (((mask >> i) & 1) == 1) { + dp[mask] = Math.min(dp[mask], dp[mask ^ (1 << i)] + (power[i] + cnt - 1) / cnt); + } + } + } + return dp[(1 << n) - 1]; + } +} +``` + +```cpp +class Solution { +public: + long long minimumTime(vector& power) { + int n = power.size(); + vector dp(1 << n, LONG_MAX); + dp[0] = 0; + for (int mask = 1; mask < 1 << n; ++mask) { + int cnt = __builtin_popcount(mask); + for (int i = 0; i < n; ++i) { + if ((mask >> i) & 1) { + dp[mask] = min(dp[mask], dp[mask ^ (1 << i)] + (power[i] + cnt - 1) / cnt); + } + } + } + return dp[(1 << n) - 1]; + } +}; +``` + +```go +func minimumTime(power []int) int64 { + n := len(power) + dp := make([]int64, 1<> i) & 1) == 1 { + dp[mask] = min(dp[mask], dp[mask^(1< + + diff --git a/solution/2400-2499/2403.Minimum Time to Kill All Monsters/README_EN.md b/solution/2400-2499/2403.Minimum Time to Kill All Monsters/README_EN.md index cf440b3ba3378..e718c37d1fcd7 100644 --- a/solution/2400-2499/2403.Minimum Time to Kill All Monsters/README_EN.md +++ b/solution/2400-2499/2403.Minimum Time to Kill All Monsters/README_EN.md @@ -69,7 +69,7 @@ It can be proven that 6 is the minimum number of days needed. ## Solutions -**Solution 1: State Compression + Memorization Search or Dynamic Programming** +### Solution 1: State Compression + Memorization Search or Dynamic Programming Since defeating monsters can increase the daily magic power gain $gain$, the order of defeating monsters affects the result, so we need to enumerate. Noting that the data range of the problem is small, we consider using state compression dynamic programming to solve it. @@ -79,8 +79,6 @@ The time complexity is $O(n \times 2^n)$, and the space complexity is $O(2^n)$. -### **Python3** - ```python class Solution: def minimumTime(self, power: List[int]) -> int: @@ -99,22 +97,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def minimumTime(self, power: List[int]) -> int: - n = len(power) - dp = [inf] * (1 << n) - dp[0] = 0 - for mask in range(1, 1 << n): - cnt = mask.bit_count() - for i, v in enumerate(power): - if (mask >> i) & 1: - dp[mask] = min(dp[mask], dp[mask ^ (1 << i)] + (v + cnt - 1) // cnt) - return dp[-1] -``` - -### **Java** - ```java class Solution { private int n; @@ -150,28 +132,6 @@ class Solution { } ``` -```java -class Solution { - public long minimumTime(int[] power) { - int n = power.length; - long[] dp = new long[1 << n]; - Arrays.fill(dp, Long.MAX_VALUE); - dp[0] = 0; - for (int mask = 1; mask < 1 << n; ++mask) { - int cnt = Integer.bitCount(mask); - for (int i = 0; i < n; ++i) { - if (((mask >> i) & 1) == 1) { - dp[mask] = Math.min(dp[mask], dp[mask ^ (1 << i)] + (power[i] + cnt - 1) / cnt); - } - } - } - return dp[(1 << n) - 1]; - } -} -``` - -### **C++** - ```cpp using ll = long long; @@ -203,28 +163,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long minimumTime(vector& power) { - int n = power.size(); - vector dp(1 << n, LONG_MAX); - dp[0] = 0; - for (int mask = 1; mask < 1 << n; ++mask) { - int cnt = __builtin_popcount(mask); - for (int i = 0; i < n; ++i) { - if ((mask >> i) & 1) { - dp[mask] = min(dp[mask], dp[mask ^ (1 << i)] + (power[i] + cnt - 1) / cnt); - } - } - } - return dp[(1 << n) - 1]; - } -}; -``` - -### **Go** - ```go func minimumTime(power []int) int64 { n := len(power) @@ -255,28 +193,6 @@ func minimumTime(power []int) int64 { } ``` -```go -func minimumTime(power []int) int64 { - n := len(power) - dp := make([]int64, 1<> i) & 1) == 1 { - dp[mask] = min(dp[mask], dp[mask^(1< + +### Solution 2 + + + +```python +class Solution: + def minimumTime(self, power: List[int]) -> int: + n = len(power) + dp = [inf] * (1 << n) + dp[0] = 0 + for mask in range(1, 1 << n): + cnt = mask.bit_count() + for i, v in enumerate(power): + if (mask >> i) & 1: + dp[mask] = min(dp[mask], dp[mask ^ (1 << i)] + (v + cnt - 1) // cnt) + return dp[-1] +``` + +```java +class Solution { + public long minimumTime(int[] power) { + int n = power.length; + long[] dp = new long[1 << n]; + Arrays.fill(dp, Long.MAX_VALUE); + dp[0] = 0; + for (int mask = 1; mask < 1 << n; ++mask) { + int cnt = Integer.bitCount(mask); + for (int i = 0; i < n; ++i) { + if (((mask >> i) & 1) == 1) { + dp[mask] = Math.min(dp[mask], dp[mask ^ (1 << i)] + (power[i] + cnt - 1) / cnt); + } + } + } + return dp[(1 << n) - 1]; + } +} +``` + +```cpp +class Solution { +public: + long long minimumTime(vector& power) { + int n = power.size(); + vector dp(1 << n, LONG_MAX); + dp[0] = 0; + for (int mask = 1; mask < 1 << n; ++mask) { + int cnt = __builtin_popcount(mask); + for (int i = 0; i < n; ++i) { + if ((mask >> i) & 1) { + dp[mask] = min(dp[mask], dp[mask ^ (1 << i)] + (power[i] + cnt - 1) / cnt); + } + } + } + return dp[(1 << n) - 1]; + } +}; +``` + +```go +func minimumTime(power []int) int64 { + n := len(power) + dp := make([]int64, 1<> i) & 1) == 1 { + dp[mask] = min(dp[mask], dp[mask^(1< + + diff --git a/solution/2400-2499/2404.Most Frequent Even Element/README.md b/solution/2400-2499/2404.Most Frequent Even Element/README.md index dbb19e6e27898..6df82dde5e593 100644 --- a/solution/2400-2499/2404.Most Frequent Even Element/README.md +++ b/solution/2400-2499/2404.Most Frequent Even Element/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们用哈希表 $cnt$ 统计所有偶数元素出现的次数,然后找出出现次数最多且值最小的偶数元素。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def mostFrequentEven(self, nums: List[int]) -> int: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int mostFrequentEven(int[] nums) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func mostFrequentEven(nums []int) int { cnt := map[int]int{} @@ -140,8 +126,6 @@ func mostFrequentEven(nums []int) int { } ``` -### **TypeScript** - ```ts function mostFrequentEven(nums: number[]): number { const cnt: Map = new Map(); @@ -162,8 +146,6 @@ function mostFrequentEven(nums: number[]): number { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -187,8 +169,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -214,10 +194,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2404.Most Frequent Even Element/README_EN.md b/solution/2400-2499/2404.Most Frequent Even Element/README_EN.md index 527fee2da5b77..6699878d61b63 100644 --- a/solution/2400-2499/2404.Most Frequent Even Element/README_EN.md +++ b/solution/2400-2499/2404.Most Frequent Even Element/README_EN.md @@ -44,7 +44,7 @@ We return the smallest one, which is 2. ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We use a hash table $cnt$ to count the occurrence of all even elements, and then find the even element with the highest occurrence and the smallest value. @@ -52,8 +52,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def mostFrequentEven(self, nums: List[int]) -> int: @@ -65,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int mostFrequentEven(int[] nums) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +107,6 @@ public: }; ``` -### **Go** - ```go func mostFrequentEven(nums []int) int { cnt := map[int]int{} @@ -133,8 +125,6 @@ func mostFrequentEven(nums []int) int { } ``` -### **TypeScript** - ```ts function mostFrequentEven(nums: number[]): number { const cnt: Map = new Map(); @@ -155,8 +145,6 @@ function mostFrequentEven(nums: number[]): number { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -180,8 +168,6 @@ impl Solution { } ``` -### **PHP** - ```php class Solution { /** @@ -207,10 +193,6 @@ class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2405.Optimal Partition of String/README.md b/solution/2400-2499/2405.Optimal Partition of String/README.md index 5057e8506aa37..709670f232cbc 100644 --- a/solution/2400-2499/2405.Optimal Partition of String/README.md +++ b/solution/2400-2499/2405.Optimal Partition of String/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 根据题意,每个子字符串应该尽可能长,且包含的字符唯一。我们只需要贪心地进行划分即可。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def partitionString(self, s: str) -> int: @@ -73,23 +67,6 @@ class Solution: return ans ``` -```python -class Solution: - def partitionString(self, s: str) -> int: - ans, v = 1, 0 - for c in s: - i = ord(c) - ord('a') - if (v >> i) & 1: - v = 0 - ans += 1 - v |= 1 << i - return ans -``` - -### **Java** - - - ```java class Solution { public int partitionString(String s) { @@ -107,26 +84,6 @@ class Solution { } ``` -```java -class Solution { - public int partitionString(String s) { - int v = 0; - int ans = 1; - for (char c : s.toCharArray()) { - int i = c - 'a'; - if (((v >> i) & 1) == 1) { - v = 0; - ++ans; - } - v |= 1 << i; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -145,27 +102,6 @@ public: }; ``` -```cpp -class Solution { -public: - int partitionString(string s) { - int ans = 1; - int v = 0; - for (char c : s) { - int i = c - 'a'; - if ((v >> i) & 1) { - v = 0; - ++ans; - } - v |= 1 << i; - } - return ans; - } -}; -``` - -### **Go** - ```go func partitionString(s string) int { ss := map[rune]bool{} @@ -181,23 +117,6 @@ func partitionString(s string) int { } ``` -```go -func partitionString(s string) int { - ans, v := 1, 0 - for _, c := range s { - i := int(c - 'a') - if v>>i&1 == 1 { - v = 0 - ans++ - } - v |= 1 << i - } - return ans -} -``` - -### **TypeScript** - ```ts function partitionString(s: string): number { const set = new Set(); @@ -213,8 +132,6 @@ function partitionString(s: string): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -233,10 +150,77 @@ impl Solution { } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def partitionString(self, s: str) -> int: + ans, v = 1, 0 + for c in s: + i = ord(c) - ord('a') + if (v >> i) & 1: + v = 0 + ans += 1 + v |= 1 << i + return ans +``` + +```java +class Solution { + public int partitionString(String s) { + int v = 0; + int ans = 1; + for (char c : s.toCharArray()) { + int i = c - 'a'; + if (((v >> i) & 1) == 1) { + v = 0; + ++ans; + } + v |= 1 << i; + } + return ans; + } +} +``` +```cpp +class Solution { +public: + int partitionString(string s) { + int ans = 1; + int v = 0; + for (char c : s) { + int i = c - 'a'; + if ((v >> i) & 1) { + v = 0; + ++ans; + } + v |= 1 << i; + } + return ans; + } +}; ``` +```go +func partitionString(s string) int { + ans, v := 1, 0 + for _, c := range s { + i := int(c - 'a') + if v>>i&1 == 1 { + v = 0 + ans++ + } + v |= 1 << i + } + return ans +} ``` + + diff --git a/solution/2400-2499/2405.Optimal Partition of String/README_EN.md b/solution/2400-2499/2405.Optimal Partition of String/README_EN.md index feeb5c105e41e..503b825fb82ea 100644 --- a/solution/2400-2499/2405.Optimal Partition of String/README_EN.md +++ b/solution/2400-2499/2405.Optimal Partition of String/README_EN.md @@ -40,7 +40,7 @@ It can be shown that 4 is the minimum number of substrings needed. ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy According to the problem, each substring should be as long as possible and contain unique characters. We just need to partition greedily. @@ -50,8 +50,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. -### **Python3** - ```python class Solution: def partitionString(self, s: str) -> int: @@ -65,21 +63,6 @@ class Solution: return ans ``` -```python -class Solution: - def partitionString(self, s: str) -> int: - ans, v = 1, 0 - for c in s: - i = ord(c) - ord('a') - if (v >> i) & 1: - v = 0 - ans += 1 - v |= 1 << i - return ans -``` - -### **Java** - ```java class Solution { public int partitionString(String s) { @@ -97,26 +80,6 @@ class Solution { } ``` -```java -class Solution { - public int partitionString(String s) { - int v = 0; - int ans = 1; - for (char c : s.toCharArray()) { - int i = c - 'a'; - if (((v >> i) & 1) == 1) { - v = 0; - ++ans; - } - v |= 1 << i; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -135,27 +98,6 @@ public: }; ``` -```cpp -class Solution { -public: - int partitionString(string s) { - int ans = 1; - int v = 0; - for (char c : s) { - int i = c - 'a'; - if ((v >> i) & 1) { - v = 0; - ++ans; - } - v |= 1 << i; - } - return ans; - } -}; -``` - -### **Go** - ```go func partitionString(s string) int { ss := map[rune]bool{} @@ -171,23 +113,6 @@ func partitionString(s string) int { } ``` -```go -func partitionString(s string) int { - ans, v := 1, 0 - for _, c := range s { - i := int(c - 'a') - if v>>i&1 == 1 { - v = 0 - ans++ - } - v |= 1 << i - } - return ans -} -``` - -### **TypeScript** - ```ts function partitionString(s: string): number { const set = new Set(); @@ -203,8 +128,6 @@ function partitionString(s: string): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -223,11 +146,77 @@ impl Solution { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def partitionString(self, s: str) -> int: + ans, v = 1, 0 + for c in s: + i = ord(c) - ord('a') + if (v >> i) & 1: + v = 0 + ans += 1 + v |= 1 << i + return ans +``` +```java +class Solution { + public int partitionString(String s) { + int v = 0; + int ans = 1; + for (char c : s.toCharArray()) { + int i = c - 'a'; + if (((v >> i) & 1) == 1) { + v = 0; + ++ans; + } + v |= 1 << i; + } + return ans; + } +} ``` +```cpp +class Solution { +public: + int partitionString(string s) { + int ans = 1; + int v = 0; + for (char c : s) { + int i = c - 'a'; + if ((v >> i) & 1) { + v = 0; + ++ans; + } + v |= 1 << i; + } + return ans; + } +}; +``` +```go +func partitionString(s string) int { + ans, v := 1, 0 + for _, c := range s { + i := int(c - 'a') + if v>>i&1 == 1 { + v = 0 + ans++ + } + v |= 1 << i + } + return ans +} ``` + + diff --git a/solution/2400-2499/2406.Divide Intervals Into Minimum Number of Groups/README.md b/solution/2400-2499/2406.Divide Intervals Into Minimum Number of Groups/README.md index 1b2f19ac770bd..7220615067c2e 100644 --- a/solution/2400-2499/2406.Divide Intervals Into Minimum Number of Groups/README.md +++ b/solution/2400-2499/2406.Divide Intervals Into Minimum Number of Groups/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列(小根堆)** +### 方法一:贪心 + 优先队列(小根堆) 我们先将区间按左端点排序,用小根堆维护每组的最右端点(堆顶是所有组的最右端点的最小值)。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def minGroups(self, intervals: List[List[int]]) -> int: @@ -77,10 +71,6 @@ class Solution: return len(h) ``` -### **Java** - - - ```java class Solution { public int minGroups(int[][] intervals) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func minGroups(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] }) @@ -142,17 +128,6 @@ func (h *hp) Pop() any { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2406.Divide Intervals Into Minimum Number of Groups/README_EN.md b/solution/2400-2499/2406.Divide Intervals Into Minimum Number of Groups/README_EN.md index 85c700ac15a1e..9cd0dab5e68d8 100644 --- a/solution/2400-2499/2406.Divide Intervals Into Minimum Number of Groups/README_EN.md +++ b/solution/2400-2499/2406.Divide Intervals Into Minimum Number of Groups/README_EN.md @@ -44,7 +44,7 @@ It can be proven that it is not possible to divide the intervals into fewer than ## Solutions -**Solution 1: Greedy + Priority Queue (Min Heap)** +### Solution 1: Greedy + Priority Queue (Min Heap) First, we sort the intervals by their left endpoints. We use a min heap to maintain the rightmost endpoint of each group (the top of the heap is the minimum of the rightmost endpoints of all groups). @@ -57,8 +57,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def minGroups(self, intervals: List[List[int]]) -> int: @@ -70,8 +68,6 @@ class Solution: return len(h) ``` -### **Java** - ```java class Solution { public int minGroups(int[][] intervals) { @@ -88,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +101,6 @@ public: }; ``` -### **Go** - ```go func minGroups(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] }) @@ -133,17 +125,6 @@ func (h *hp) Pop() any { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2407.Longest Increasing Subsequence II/README.md b/solution/2400-2499/2407.Longest Increasing Subsequence II/README.md index 26a132331ed9f..b48ed0e798f80 100644 --- a/solution/2400-2499/2407.Longest Increasing Subsequence II/README.md +++ b/solution/2400-2499/2407.Longest Increasing Subsequence II/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:线段树** +### 方法一:线段树 我们假设 $f[v]$ 表示以数字 $v$ 结尾的最长递增子序列的长度。 @@ -83,10 +81,6 @@ -### **Python3** - - - ```python class Node: def __init__(self): @@ -146,10 +140,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int lengthOfLIS(int[] nums, int k) { @@ -231,8 +221,6 @@ class SegmentTree { } ``` -### **C++** - ```cpp class Node { public: @@ -302,8 +290,6 @@ public: }; ``` -### **Go** - ```go func lengthOfLIS(nums []int, k int) int { mx := slices.Max(nums) @@ -382,17 +368,6 @@ func (t *segmentTree) pushup(u int) { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2407.Longest Increasing Subsequence II/README_EN.md b/solution/2400-2499/2407.Longest Increasing Subsequence II/README_EN.md index e53197a25fd5d..6956348a7fd09 100644 --- a/solution/2400-2499/2407.Longest Increasing Subsequence II/README_EN.md +++ b/solution/2400-2499/2407.Longest Increasing Subsequence II/README_EN.md @@ -59,7 +59,7 @@ The subsequence has a length of 1, so we return 1. ## Solutions -**Solution 1: Segment Tree** +### Solution 1: Segment Tree We assume that $f[v]$ represents the length of the longest increasing subsequence ending with the number $v$. @@ -80,8 +80,6 @@ The time complexity is $O(n \times \log n)$, where $n$ is the length of the arra -### **Python3** - ```python class Node: def __init__(self): @@ -141,8 +139,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int lengthOfLIS(int[] nums, int k) { @@ -224,8 +220,6 @@ class SegmentTree { } ``` -### **C++** - ```cpp class Node { public: @@ -295,8 +289,6 @@ public: }; ``` -### **Go** - ```go func lengthOfLIS(nums []int, k int) int { mx := slices.Max(nums) @@ -375,17 +367,6 @@ func (t *segmentTree) pushup(u int) { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2408.Design SQL/README.md b/solution/2400-2499/2408.Design SQL/README.md index ce7200ffb5303..5a13bdb68c64c 100644 --- a/solution/2400-2499/2408.Design SQL/README.md +++ b/solution/2400-2499/2408.Design SQL/README.md @@ -65,9 +65,7 @@ sql.selectCell("two", 2, 2); // 返回 "fifth",查找表 "two" 中 id 为 2 ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 创建哈希表 `tables` 用于存储表名和表数据行的映射。直接模拟题目中的操作即可。 @@ -75,10 +73,6 @@ sql.selectCell("two", 2, 2); // 返回 "fifth",查找表 "two" 中 id 为 2 -### **Python3** - - - ```python class SQL: def __init__(self, names: List[str], columns: List[int]): @@ -101,10 +95,6 @@ class SQL: # param_3 = obj.selectCell(name,rowId,columnId) ``` -### **Java** - - - ```java class SQL { private Map>> tables; @@ -134,8 +124,6 @@ class SQL { */ ``` -### **C++** - ```cpp class SQL { public: @@ -164,8 +152,6 @@ public: */ ``` -### **Go** - ```go type SQL struct { tables map[string][][]string @@ -196,17 +182,6 @@ func (this *SQL) SelectCell(name string, rowId int, columnId int) string { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2408.Design SQL/README_EN.md b/solution/2400-2499/2408.Design SQL/README_EN.md index 1bd8a9e75efd3..61f039789ab5b 100644 --- a/solution/2400-2499/2408.Design SQL/README_EN.md +++ b/solution/2400-2499/2408.Design SQL/README_EN.md @@ -61,7 +61,7 @@ sql.selectCell("two", 2, 2); // return "fifth", finds the va ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table Create a hash table `tables` to store the mapping of table names to table data rows. Directly simulate the operations in the problem. @@ -69,8 +69,6 @@ The time complexity of each operation is $O(1)$, and the space complexity is $O( -### **Python3** - ```python class SQL: def __init__(self, names: List[str], columns: List[int]): @@ -93,8 +91,6 @@ class SQL: # param_3 = obj.selectCell(name,rowId,columnId) ``` -### **Java** - ```java class SQL { private Map>> tables; @@ -124,8 +120,6 @@ class SQL { */ ``` -### **C++** - ```cpp class SQL { public: @@ -154,8 +148,6 @@ public: */ ``` -### **Go** - ```go type SQL struct { tables map[string][][]string @@ -186,17 +178,6 @@ func (this *SQL) SelectCell(name string, rowId int, columnId int) string { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2409.Count Days Spent Together/README.md b/solution/2400-2499/2409.Count Days Spent Together/README.md index 7a1cc165bdcaa..fb9254346ac96 100644 --- a/solution/2400-2499/2409.Count Days Spent Together/README.md +++ b/solution/2400-2499/2409.Count Days Spent Together/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们将日期转换为天数,然后计算两个人在罗马的天数。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def countDaysTogether( @@ -71,10 +65,6 @@ class Solution: return max(y - x + 1, 0) ``` -### **Java** - - - ```java class Solution { private int[] days = new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func countDaysTogether(arriveAlice string, leaveAlice string, arriveBob string, leaveBob string) int { days := []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} @@ -157,17 +143,6 @@ func countDaysTogether(arriveAlice string, leaveAlice string, arriveBob string, } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2409.Count Days Spent Together/README_EN.md b/solution/2400-2499/2409.Count Days Spent Together/README_EN.md index 83d4d2738af22..b2e4007b37f29 100644 --- a/solution/2400-2499/2409.Count Days Spent Together/README_EN.md +++ b/solution/2400-2499/2409.Count Days Spent Together/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We convert the dates into days, and then calculate the number of days both people are in Rome. @@ -48,8 +48,6 @@ The time complexity is $O(C)$, and the space complexity is $O(C)$. Here, $C$ is -### **Python3** - ```python class Solution: def countDaysTogether( @@ -63,8 +61,6 @@ class Solution: return max(y - x + 1, 0) ``` -### **Java** - ```java class Solution { private int[] days = new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +110,6 @@ public: }; ``` -### **Go** - ```go func countDaysTogether(arriveAlice string, leaveAlice string, arriveBob string, leaveBob string) int { days := []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} @@ -147,17 +139,6 @@ func countDaysTogether(arriveAlice string, leaveAlice string, arriveBob string, } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2410.Maximum Matching of Players With Trainers/README.md b/solution/2400-2499/2410.Maximum Matching of Players With Trainers/README.md index 411592b36335e..302684760c6ca 100644 --- a/solution/2400-2499/2410.Maximum Matching of Players With Trainers/README.md +++ b/solution/2400-2499/2410.Maximum Matching of Players With Trainers/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:贪心 + 双指针** +### 方法一:贪心 + 双指针 按运动员的能力值从小到大排序,选择大于等于运动员能力值的,且自身能力值最小的训练师。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def matchPlayersAndTrainers(self, players: List[int], trainers: List[int]) -> int: @@ -74,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int matchPlayersAndTrainers(int[] players, int[] trainers) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func matchPlayersAndTrainers(players []int, trainers []int) int { sort.Ints(players) @@ -142,17 +128,6 @@ func matchPlayersAndTrainers(players []int, trainers []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2410.Maximum Matching of Players With Trainers/README_EN.md b/solution/2400-2499/2410.Maximum Matching of Players With Trainers/README_EN.md index 79531c197ad57..b8bca7db783ae 100644 --- a/solution/2400-2499/2410.Maximum Matching of Players With Trainers/README_EN.md +++ b/solution/2400-2499/2410.Maximum Matching of Players With Trainers/README_EN.md @@ -43,7 +43,7 @@ Each player can only be matched with one trainer, so the maximum answer is 1. ## Solutions -**Solution 1: Greedy + Two Pointers** +### Solution 1: Greedy + Two Pointers Sort the athletes by their abilities in ascending order, and select the trainer with the smallest ability that is greater than or equal to the athlete's ability. @@ -51,8 +51,6 @@ The time complexity is $O(n \times \log n + m \times \log m)$, and the space com -### **Python3** - ```python class Solution: def matchPlayersAndTrainers(self, players: List[int], trainers: List[int]) -> int: @@ -68,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int matchPlayersAndTrainers(int[] players, int[] trainers) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +108,6 @@ public: }; ``` -### **Go** - ```go func matchPlayersAndTrainers(players []int, trainers []int) int { sort.Ints(players) @@ -134,17 +126,6 @@ func matchPlayersAndTrainers(players []int, trainers []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2411.Smallest Subarrays With Maximum Bitwise OR/README.md b/solution/2400-2499/2411.Smallest Subarrays With Maximum Bitwise OR/README.md index 4f2882def9f2d..422dd788c3fb6 100644 --- a/solution/2400-2499/2411.Smallest Subarrays With Maximum Bitwise OR/README.md +++ b/solution/2400-2499/2411.Smallest Subarrays With Maximum Bitwise OR/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:逆序遍历** +### 方法一:逆序遍历 要找到每个以 $i$ 作为起始位置的最短子数组,满足或运算结果最大,那么必须让这个结果的 $1$ 尽可能多。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def smallestSubarrays(self, nums: List[int]) -> List[int]: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] smallestSubarrays(int[] nums) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func smallestSubarrays(nums []int) []int { n := len(nums) @@ -168,17 +154,6 @@ func smallestSubarrays(nums []int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2411.Smallest Subarrays With Maximum Bitwise OR/README_EN.md b/solution/2400-2499/2411.Smallest Subarrays With Maximum Bitwise OR/README_EN.md index bc5e6b9be4c2f..1b06c724bd4aa 100644 --- a/solution/2400-2499/2411.Smallest Subarrays With Maximum Bitwise OR/README_EN.md +++ b/solution/2400-2499/2411.Smallest Subarrays With Maximum Bitwise OR/README_EN.md @@ -54,7 +54,7 @@ Therefore, we return [2,1]. ## Solutions -**Solution 1: Reverse Traversal** +### Solution 1: Reverse Traversal To find the shortest subarray starting at position $i$ that maximizes the bitwise OR operation, we need to maximize the number of $1$s in the result. @@ -66,8 +66,6 @@ The time complexity is $O(n \times \log m)$, where $n$ is the length of the arra -### **Python3** - ```python class Solution: def smallestSubarrays(self, nums: List[int]) -> List[int]: @@ -85,8 +83,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] smallestSubarrays(int[] nums) { @@ -110,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +129,6 @@ public: }; ``` -### **Go** - ```go func smallestSubarrays(nums []int) []int { n := len(nums) @@ -160,17 +152,6 @@ func smallestSubarrays(nums []int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2412.Minimum Money Required Before Transactions/README.md b/solution/2400-2499/2412.Minimum Money Required Before Transactions/README.md index 88d45571aa736..59109961aeaf7 100644 --- a/solution/2400-2499/2412.Minimum Money Required Before Transactions/README.md +++ b/solution/2400-2499/2412.Minimum Money Required Before Transactions/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们先累计所有负收益,记为 $s$。然后枚举每个交易作为最后一个交易,如果 `transactions[i].x > transactions[i].y`,说明当前的交易是亏钱的,而这个交易在此前我们累计负收益的时候,已经被计算,因此取 `s + transactions[i].y` 更新答案;否则,取 `s + transactions[i].x` 更新答案。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def minimumMoney(self, transactions: List[List[int]]) -> int: @@ -74,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long minimumMoney(int[][] transactions) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func minimumMoney(transactions [][]int) int64 { s, ans := 0, 0 @@ -139,17 +125,6 @@ func minimumMoney(transactions [][]int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2412.Minimum Money Required Before Transactions/README_EN.md b/solution/2400-2499/2412.Minimum Money Required Before Transactions/README_EN.md index 3bfaf0ce2f6c9..b866ae50d0230 100644 --- a/solution/2400-2499/2412.Minimum Money Required Before Transactions/README_EN.md +++ b/solution/2400-2499/2412.Minimum Money Required Before Transactions/README_EN.md @@ -43,7 +43,7 @@ Thus, starting with money = 3, the transactions can be performed in any order. ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy First, we accumulate all the negative profits, denoted as $s$. Then we enumerate each transaction as the last transaction. If `transactions[i].x > transactions[i].y`, it means the current transaction is losing money, and this transaction has been calculated when we previously accumulated negative profits, so we update the answer with `s + transactions[i].y`; otherwise, we update the answer with `s + transactions[i].x`. @@ -51,8 +51,6 @@ The time complexity is $O(n)$, where $n$ is the number of transactions. The spac -### **Python3** - ```python class Solution: def minimumMoney(self, transactions: List[List[int]]) -> int: @@ -66,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long minimumMoney(int[][] transactions) { @@ -88,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func minimumMoney(transactions [][]int) int64 { s, ans := 0, 0 @@ -129,17 +121,6 @@ func minimumMoney(transactions [][]int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2413.Smallest Even Multiple/README.md b/solution/2400-2499/2413.Smallest Even Multiple/README.md index 6adbd79957f33..d3cd9080be771 100644 --- a/solution/2400-2499/2413.Smallest Even Multiple/README.md +++ b/solution/2400-2499/2413.Smallest Even Multiple/README.md @@ -34,9 +34,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 如果 $n$ 为偶数,那么 $2$ 和 $n$ 的最小公倍数就是 $n$ 本身。否则,$2$ 和 $n$ 的最小公倍数就是 $n \times 2$。 @@ -44,20 +42,12 @@ -### **Python3** - - - ```python class Solution: def smallestEvenMultiple(self, n: int) -> int: return n if n % 2 == 0 else n * 2 ``` -### **Java** - - - ```java class Solution { public int smallestEvenMultiple(int n) { @@ -66,8 +56,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -77,8 +65,6 @@ public: }; ``` -### **Go** - ```go func smallestEvenMultiple(n int) int { if n%2 == 0 { @@ -88,24 +74,12 @@ func smallestEvenMultiple(n int) int { } ``` -### **C** - -```c -int smallestEvenMultiple(int n) { - return n % 2 == 0 ? n : n * 2; -} -``` - -### **TypeScript** - ```ts function smallestEvenMultiple(n: number): number { return n % 2 === 0 ? n : n * 2; } ``` -### **Rust** - ```rust impl Solution { pub fn smallest_even_multiple(n: i32) -> i32 { @@ -117,10 +91,12 @@ impl Solution { } ``` -### **...** - -``` - +```c +int smallestEvenMultiple(int n) { + return n % 2 == 0 ? n : n * 2; +} ``` + + diff --git a/solution/2400-2499/2413.Smallest Even Multiple/README_EN.md b/solution/2400-2499/2413.Smallest Even Multiple/README_EN.md index 60235878714e7..f627c1c4a28f8 100644 --- a/solution/2400-2499/2413.Smallest Even Multiple/README_EN.md +++ b/solution/2400-2499/2413.Smallest Even Multiple/README_EN.md @@ -32,7 +32,7 @@ Given a positive integer n, return the smalles ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics If $n$ is even, then the least common multiple (LCM) of $2$ and $n$ is $n$ itself. Otherwise, the LCM of $2$ and $n$ is $n \times 2$. @@ -40,16 +40,12 @@ The time complexity is $O(1)$. -### **Python3** - ```python class Solution: def smallestEvenMultiple(self, n: int) -> int: return n if n % 2 == 0 else n * 2 ``` -### **Java** - ```java class Solution { public int smallestEvenMultiple(int n) { @@ -58,8 +54,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -69,8 +63,6 @@ public: }; ``` -### **Go** - ```go func smallestEvenMultiple(n int) int { if n%2 == 0 { @@ -80,24 +72,12 @@ func smallestEvenMultiple(n int) int { } ``` -### **C** - -```c -int smallestEvenMultiple(int n) { - return n % 2 == 0 ? n : n * 2; -} -``` - -### **TypeScript** - ```ts function smallestEvenMultiple(n: number): number { return n % 2 === 0 ? n : n * 2; } ``` -### **Rust** - ```rust impl Solution { pub fn smallest_even_multiple(n: i32) -> i32 { @@ -109,10 +89,12 @@ impl Solution { } ``` -### **...** - -``` - +```c +int smallestEvenMultiple(int n) { + return n % 2 == 0 ? n : n * 2; +} ``` + + diff --git a/solution/2400-2499/2414.Length of the Longest Alphabetical Continuous Substring/README.md b/solution/2400-2499/2414.Length of the Longest Alphabetical Continuous Substring/README.md index 35a84b6f1309a..8de13c96315d2 100644 --- a/solution/2400-2499/2414.Length of the Longest Alphabetical Continuous Substring/README.md +++ b/solution/2400-2499/2414.Length of the Longest Alphabetical Continuous Substring/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们用双指针 $i$ 和 $j$ 分别指向当前连续子字符串的起始位置和结束位置。遍历字符串 $s$,如果当前字符 $s[j]$ 比 $s[j-1]$ 大,则 $j$ 向右移动一位,否则更新 $i$ 为 $j$,并更新最长连续子字符串的长度。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def longestContinuousSubstring(self, s: str) -> int: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestContinuousSubstring(String s) { @@ -91,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +99,6 @@ public: }; ``` -### **Go** - ```go func longestContinuousSubstring(s string) int { ans := 0 @@ -128,27 +114,6 @@ func longestContinuousSubstring(s string) int { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int longestContinuousSubstring(char* s) { - int n = strlen(s); - int i = 0; - int res = 1; - for (int j = 1; j < n; j++) { - if (s[j] - s[j - 1] != 1) { - res = max(res, j - i); - i = j; - } - } - return max(res, n - i); -} -``` - -### **TypeScript** - ```ts function longestContinuousSubstring(s: string): number { const n = s.length; @@ -164,8 +129,6 @@ function longestContinuousSubstring(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn longest_continuous_substring(s: String) -> i32 { @@ -184,10 +147,23 @@ impl Solution { } ``` -### **...** - -``` +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +int longestContinuousSubstring(char* s) { + int n = strlen(s); + int i = 0; + int res = 1; + for (int j = 1; j < n; j++) { + if (s[j] - s[j - 1] != 1) { + res = max(res, j - i); + i = j; + } + } + return max(res, n - i); +} ``` + + diff --git a/solution/2400-2499/2414.Length of the Longest Alphabetical Continuous Substring/README_EN.md b/solution/2400-2499/2414.Length of the Longest Alphabetical Continuous Substring/README_EN.md index c9cb24a995fe0..0ca2d2fc6cbdd 100644 --- a/solution/2400-2499/2414.Length of the Longest Alphabetical Continuous Substring/README_EN.md +++ b/solution/2400-2499/2414.Length of the Longest Alphabetical Continuous Substring/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We use two pointers $i$ and $j$ to point to the start and end of the current consecutive substring respectively. Traverse the string $s$, if the current character $s[j]$ is greater than $s[j-1]$, then move $j$ one step to the right, otherwise update $i$ to $j$, and update the length of the longest consecutive substring. @@ -48,8 +48,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. The sp -### **Python3** - ```python class Solution: def longestContinuousSubstring(self, s: str) -> int: @@ -64,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestContinuousSubstring(String s) { @@ -83,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +97,6 @@ public: }; ``` -### **Go** - ```go func longestContinuousSubstring(s string) int { ans := 0 @@ -120,27 +112,6 @@ func longestContinuousSubstring(s string) int { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int longestContinuousSubstring(char* s) { - int n = strlen(s); - int i = 0; - int res = 1; - for (int j = 1; j < n; j++) { - if (s[j] - s[j - 1] != 1) { - res = max(res, j - i); - i = j; - } - } - return max(res, n - i); -} -``` - -### **TypeScript** - ```ts function longestContinuousSubstring(s: string): number { const n = s.length; @@ -156,8 +127,6 @@ function longestContinuousSubstring(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn longest_continuous_substring(s: String) -> i32 { @@ -176,10 +145,23 @@ impl Solution { } ``` -### **...** - -``` +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +int longestContinuousSubstring(char* s) { + int n = strlen(s); + int i = 0; + int res = 1; + for (int j = 1; j < n; j++) { + if (s[j] - s[j - 1] != 1) { + res = max(res, j - i); + i = j; + } + } + return max(res, n - i); +} ``` + + diff --git a/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/README.md b/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/README.md index 03ac2cad85b51..3cb5a30d6963b 100644 --- a/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/README.md +++ b/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们可以使用广度优先搜索的方法,用一个队列 $q$ 来存储每一层的节点,用一个变量 $i$ 记录当前层数。若 $i$ 为奇数,则将当前层的节点值反转。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -101,10 +95,6 @@ class Solution: return root ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -148,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -188,8 +176,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -222,8 +208,6 @@ func reverseOddLevels(root *TreeNode) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -260,8 +244,6 @@ function reverseOddLevels(root: TreeNode | null): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -331,10 +313,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/README_EN.md b/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/README_EN.md index 269633d357be4..18ac4b4a2855f 100644 --- a/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/README_EN.md +++ b/solution/2400-2499/2415.Reverse Odd Levels of Binary Tree/README_EN.md @@ -58,7 +58,7 @@ The nodes at level 3 were 1, 1, 1, 1, 2, 2, 2, 2, and are 2, 2, 2, 2, 1, 1, 1, 1 ## Solutions -**Solution 1: BFS** +### Solution 1: BFS We can use the Breadth-First Search (BFS) method, using a queue $q$ to store the nodes of each level, and a variable $i$ to record the current level. If $i$ is odd, we reverse the values of the nodes at the current level. @@ -66,8 +66,6 @@ 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: @@ -94,8 +92,6 @@ class Solution: return root ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -139,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -179,8 +173,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -213,8 +205,6 @@ func reverseOddLevels(root *TreeNode) *TreeNode { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -251,8 +241,6 @@ function reverseOddLevels(root: TreeNode | null): TreeNode | null { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -322,10 +310,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2416.Sum of Prefix Scores of Strings/README.md b/solution/2400-2499/2416.Sum of Prefix Scores of Strings/README.md index 5d46c170da3c0..3e5e72aac3fbf 100644 --- a/solution/2400-2499/2416.Sum of Prefix Scores of Strings/README.md +++ b/solution/2400-2499/2416.Sum of Prefix Scores of Strings/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:前缀树** +### 方法一:前缀树 用前缀树维护所有字符串的前缀以及每个前缀出现的次数。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Trie: def __init__(self): @@ -111,10 +105,6 @@ class Solution: return [trie.search(w) for w in words] ``` -### **Java** - - - ```java class Trie { private Trie[] children = new Trie[26]; @@ -162,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { private: @@ -214,8 +202,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -264,8 +250,6 @@ func sumPrefixScores(words []string) []int { } ``` -### **TypeScript** - ```ts function sumPrefixScores(words: string[]): number[] { const map = new Map(); @@ -290,6 +274,12 @@ function sumPrefixScores(words: string[]): number[] { } ``` + + +### 方法二 + + + ```ts class Trie { children: Array; @@ -340,11 +330,6 @@ function sumPrefixScores(words: string[]): number[] { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2416.Sum of Prefix Scores of Strings/README_EN.md b/solution/2400-2499/2416.Sum of Prefix Scores of Strings/README_EN.md index 177ed3396a2f6..f5c839d6d5a12 100644 --- a/solution/2400-2499/2416.Sum of Prefix Scores of Strings/README_EN.md +++ b/solution/2400-2499/2416.Sum of Prefix Scores of Strings/README_EN.md @@ -58,7 +58,7 @@ Each prefix has a score of one, so the total is answer[0] = 1 + 1 + 1 + 1 = 4. ## Solutions -**Solution 1: Trie** +### Solution 1: Trie Use a trie to maintain the prefixes of all strings and the occurrence count of each prefix. @@ -68,8 +68,6 @@ The time complexity is $O(n \times m)$. Here, $n$ and $m$ are the length of the -### **Python3** - ```python class Trie: def __init__(self): @@ -105,8 +103,6 @@ class Solution: return [trie.search(w) for w in words] ``` -### **Java** - ```java class Trie { private Trie[] children = new Trie[26]; @@ -154,8 +150,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { private: @@ -206,8 +200,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [26]*Trie @@ -256,8 +248,6 @@ func sumPrefixScores(words []string) []int { } ``` -### **TypeScript** - ```ts function sumPrefixScores(words: string[]): number[] { const map = new Map(); @@ -282,6 +272,12 @@ function sumPrefixScores(words: string[]): number[] { } ``` + + +### Solution 2 + + + ```ts class Trie { children: Array; @@ -332,11 +328,6 @@ function sumPrefixScores(words: string[]): number[] { } ``` -### **...** - -``` - - -``` - + + diff --git a/solution/2400-2499/2417.Closest Fair Integer/README.md b/solution/2400-2499/2417.Closest Fair Integer/README.md index 3f3f188dd961d..33f372639c6da 100644 --- a/solution/2400-2499/2417.Closest Fair Integer/README.md +++ b/solution/2400-2499/2417.Closest Fair Integer/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:分类讨论** +### 方法一:分类讨论 我们记 $n$ 的位数为 $k$,奇数位数、偶数位数分别为 $a$ 和 $b$。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def closestFair(self, n: int) -> int: @@ -79,10 +73,6 @@ class Solution: return self.closestFair(n + 1) ``` -### **Java** - - - ```java class Solution { public int closestFair(int n) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func closestFair(n int) int { a, b := 0, 0 @@ -176,16 +162,6 @@ func closestFair(n int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2417.Closest Fair Integer/README_EN.md b/solution/2400-2499/2417.Closest Fair Integer/README_EN.md index 0a4f5a8081f5a..f80c6f7a4667d 100644 --- a/solution/2400-2499/2417.Closest Fair Integer/README_EN.md +++ b/solution/2400-2499/2417.Closest Fair Integer/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return self.closestFair(n + 1) ``` -### **Java** - ```java class Solution { public int closestFair(int n) { @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +123,6 @@ public: }; ``` -### **Go** - ```go func closestFair(n int) int { a, b := 0, 0 @@ -157,16 +151,6 @@ func closestFair(n int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2418.Sort the People/README.md b/solution/2400-2499/2418.Sort the People/README.md index a6d2bfb8640c6..bec413965a569 100644 --- a/solution/2400-2499/2418.Sort the People/README.md +++ b/solution/2400-2499/2418.Sort the People/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 根据题目描述,我们可以创建一个长度为 $n$ 的下标数组 $idx$,其中 $idx[i]=i$。然后我们对 $idx$ 中的每个下标按照 $heights$ 中对应的身高降序排序,最后遍历排序后的 $idx$ 中的每个下标 $i$,将 $names[i]$ 加入答案数组即可。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: @@ -67,16 +61,6 @@ class Solution: return [names[i] for i in idx] ``` -```python -class Solution: - def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: - return [name for _, name in sorted(zip(heights, names), reverse=True)] -``` - -### **Java** - - - ```java class Solution { public String[] sortPeople(String[] names, int[] heights) { @@ -95,26 +79,6 @@ class Solution { } ``` -```java -class Solution { - public String[] sortPeople(String[] names, int[] heights) { - int n = names.length; - int[][] arr = new int[n][2]; - for (int i = 0; i < n; ++i) { - arr[i] = new int[] {heights[i], i}; - } - Arrays.sort(arr, (a, b) -> b[0] - a[0]); - String[] ans = new String[n]; - for (int i = 0; i < n; ++i) { - ans[i] = names[arr[i][1]]; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -132,27 +96,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector sortPeople(vector& names, vector& heights) { - int n = names.size(); - vector> arr; - for (int i = 0; i < n; ++i) { - arr.emplace_back(-heights[i], i); - } - sort(arr.begin(), arr.end()); - vector ans; - for (int i = 0; i < n; ++i) { - ans.emplace_back(names[arr[i].second]); - } - return ans; - } -}; -``` - -### **Go** - ```go func sortPeople(names []string, heights []int) (ans []string) { n := len(names) @@ -168,24 +111,6 @@ func sortPeople(names []string, heights []int) (ans []string) { } ``` -```go -func sortPeople(names []string, heights []int) []string { - n := len(names) - arr := make([][2]int, n) - for i, h := range heights { - arr[i] = [2]int{h, i} - } - sort.Slice(arr, func(i, j int) bool { return arr[i][0] > arr[j][0] }) - ans := make([]string, n) - for i, x := range arr { - ans[i] = names[x[1]] - } - return ans -} -``` - -### **TypeScript** - ```ts function sortPeople(names: string[], heights: number[]): string[] { const n = names.length; @@ -202,17 +127,6 @@ function sortPeople(names: string[], heights: number[]): string[] { } ``` -```ts -function sortPeople(names: string[], heights: number[]): string[] { - return names - .map<[string, number]>((s, i) => [s, heights[i]]) - .sort((a, b) => b[1] - a[1]) - .map(([v]) => v); -} -``` - -### **Rust** - ```rust impl Solution { pub fn sort_people(names: Vec, heights: Vec) -> Vec { @@ -226,10 +140,80 @@ impl Solution { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: + return [name for _, name in sorted(zip(heights, names), reverse=True)] ``` +```java +class Solution { + public String[] sortPeople(String[] names, int[] heights) { + int n = names.length; + int[][] arr = new int[n][2]; + for (int i = 0; i < n; ++i) { + arr[i] = new int[] {heights[i], i}; + } + Arrays.sort(arr, (a, b) -> b[0] - a[0]); + String[] ans = new String[n]; + for (int i = 0; i < n; ++i) { + ans[i] = names[arr[i][1]]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector sortPeople(vector& names, vector& heights) { + int n = names.size(); + vector> arr; + for (int i = 0; i < n; ++i) { + arr.emplace_back(-heights[i], i); + } + sort(arr.begin(), arr.end()); + vector ans; + for (int i = 0; i < n; ++i) { + ans.emplace_back(names[arr[i].second]); + } + return ans; + } +}; +``` + +```go +func sortPeople(names []string, heights []int) []string { + n := len(names) + arr := make([][2]int, n) + for i, h := range heights { + arr[i] = [2]int{h, i} + } + sort.Slice(arr, func(i, j int) bool { return arr[i][0] > arr[j][0] }) + ans := make([]string, n) + for i, x := range arr { + ans[i] = names[x[1]] + } + return ans +} +``` + +```ts +function sortPeople(names: string[], heights: number[]): string[] { + return names + .map<[string, number]>((s, i) => [s, heights[i]]) + .sort((a, b) => b[1] - a[1]) + .map(([v]) => v); +} ``` + + diff --git a/solution/2400-2499/2418.Sort the People/README_EN.md b/solution/2400-2499/2418.Sort the People/README_EN.md index 52eb9d4525bd9..3d5f03d5930a6 100644 --- a/solution/2400-2499/2418.Sort the People/README_EN.md +++ b/solution/2400-2499/2418.Sort the People/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting According to the problem description, we can create an index array $idx$ of length $n$, where $idx[i]=i$. Then we sort each index in $idx$ in descending order according to the corresponding height in $heights$. Finally, we traverse each index $i$ in the sorted $idx$ and add $names[i]$ to the answer array. @@ -51,8 +51,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: @@ -61,14 +59,6 @@ class Solution: return [names[i] for i in idx] ``` -```python -class Solution: - def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: - return [name for _, name in sorted(zip(heights, names), reverse=True)] -``` - -### **Java** - ```java class Solution { public String[] sortPeople(String[] names, int[] heights) { @@ -87,26 +77,6 @@ class Solution { } ``` -```java -class Solution { - public String[] sortPeople(String[] names, int[] heights) { - int n = names.length; - int[][] arr = new int[n][2]; - for (int i = 0; i < n; ++i) { - arr[i] = new int[] {heights[i], i}; - } - Arrays.sort(arr, (a, b) -> b[0] - a[0]); - String[] ans = new String[n]; - for (int i = 0; i < n; ++i) { - ans[i] = names[arr[i][1]]; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -124,27 +94,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector sortPeople(vector& names, vector& heights) { - int n = names.size(); - vector> arr; - for (int i = 0; i < n; ++i) { - arr.emplace_back(-heights[i], i); - } - sort(arr.begin(), arr.end()); - vector ans; - for (int i = 0; i < n; ++i) { - ans.emplace_back(names[arr[i].second]); - } - return ans; - } -}; -``` - -### **Go** - ```go func sortPeople(names []string, heights []int) (ans []string) { n := len(names) @@ -160,24 +109,6 @@ func sortPeople(names []string, heights []int) (ans []string) { } ``` -```go -func sortPeople(names []string, heights []int) []string { - n := len(names) - arr := make([][2]int, n) - for i, h := range heights { - arr[i] = [2]int{h, i} - } - sort.Slice(arr, func(i, j int) bool { return arr[i][0] > arr[j][0] }) - ans := make([]string, n) - for i, x := range arr { - ans[i] = names[x[1]] - } - return ans -} -``` - -### **TypeScript** - ```ts function sortPeople(names: string[], heights: number[]): string[] { const n = names.length; @@ -194,17 +125,6 @@ function sortPeople(names: string[], heights: number[]): string[] { } ``` -```ts -function sortPeople(names: string[], heights: number[]): string[] { - return names - .map<[string, number]>((s, i) => [s, heights[i]]) - .sort((a, b) => b[1] - a[1]) - .map(([v]) => v); -} -``` - -### **Rust** - ```rust impl Solution { pub fn sort_people(names: Vec, heights: Vec) -> Vec { @@ -218,10 +138,80 @@ impl Solution { } ``` -### **...** + +### Solution 2 + + + +```python +class Solution: + def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: + return [name for _, name in sorted(zip(heights, names), reverse=True)] ``` +```java +class Solution { + public String[] sortPeople(String[] names, int[] heights) { + int n = names.length; + int[][] arr = new int[n][2]; + for (int i = 0; i < n; ++i) { + arr[i] = new int[] {heights[i], i}; + } + Arrays.sort(arr, (a, b) -> b[0] - a[0]); + String[] ans = new String[n]; + for (int i = 0; i < n; ++i) { + ans[i] = names[arr[i][1]]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector sortPeople(vector& names, vector& heights) { + int n = names.size(); + vector> arr; + for (int i = 0; i < n; ++i) { + arr.emplace_back(-heights[i], i); + } + sort(arr.begin(), arr.end()); + vector ans; + for (int i = 0; i < n; ++i) { + ans.emplace_back(names[arr[i].second]); + } + return ans; + } +}; +``` + +```go +func sortPeople(names []string, heights []int) []string { + n := len(names) + arr := make([][2]int, n) + for i, h := range heights { + arr[i] = [2]int{h, i} + } + sort.Slice(arr, func(i, j int) bool { return arr[i][0] > arr[j][0] }) + ans := make([]string, n) + for i, x := range arr { + ans[i] = names[x[1]] + } + return ans +} +``` + +```ts +function sortPeople(names: string[], heights: number[]): string[] { + return names + .map<[string, number]>((s, i) => [s, heights[i]]) + .sort((a, b) => b[1] - a[1]) + .map(([v]) => v); +} ``` + + diff --git a/solution/2400-2499/2419.Longest Subarray With Maximum Bitwise AND/README.md b/solution/2400-2499/2419.Longest Subarray With Maximum Bitwise AND/README.md index 696e290c37107..23103b7adc669 100644 --- a/solution/2400-2499/2419.Longest Subarray With Maximum Bitwise AND/README.md +++ b/solution/2400-2499/2419.Longest Subarray With Maximum Bitwise AND/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 由于按位与的操作,不会使得数字变大,因此最大值就是数组中的最大值。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def longestSubarray(self, nums: List[int]) -> int: @@ -85,10 +79,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestSubarray(int[] nums) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func longestSubarray(nums []int) int { mx := slices.Max(nums) @@ -149,16 +135,6 @@ func longestSubarray(nums []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2419.Longest Subarray With Maximum Bitwise AND/README_EN.md b/solution/2400-2499/2419.Longest Subarray With Maximum Bitwise AND/README_EN.md index 685cc0bcd5782..54021f63b6874 100644 --- a/solution/2400-2499/2419.Longest Subarray With Maximum Bitwise AND/README_EN.md +++ b/solution/2400-2499/2419.Longest Subarray With Maximum Bitwise AND/README_EN.md @@ -49,7 +49,7 @@ The longest subarray with that value is [4], so we return 1. ## Solutions -**Solution 1: Quick Thinking** +### Solution 1: Quick Thinking Due to the bitwise AND operation, the number will not get larger, so the maximum value is the maximum value in the array. @@ -61,8 +61,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. -### **Python3** - ```python class Solution: def longestSubarray(self, nums: List[int]) -> int: @@ -77,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestSubarray(int[] nums) { @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +115,6 @@ public: }; ``` -### **Go** - ```go func longestSubarray(nums []int) int { mx := slices.Max(nums) @@ -139,16 +131,6 @@ func longestSubarray(nums []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2420.Find All Good Indices/README.md b/solution/2400-2499/2420.Find All Good Indices/README.md index 98b03a3c66083..7849b486edcdd 100644 --- a/solution/2400-2499/2420.Find All Good Indices/README.md +++ b/solution/2400-2499/2420.Find All Good Indices/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:递推** +### 方法一:递推 我们定义两个数组 `decr` 和 `incr`,分别表示从左到右和从右到左的非递增和非递减的最长子数组长度。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def goodIndices(self, nums: List[int], k: int) -> List[int]: @@ -83,10 +77,6 @@ class Solution: return [i for i in range(k, n - k) if decr[i] >= k and incr[i] >= k] ``` -### **Java** - - - ```java class Solution { public List goodIndices(int[] nums, int k) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func goodIndices(nums []int, k int) []int { n := len(nums) @@ -177,16 +163,6 @@ func goodIndices(nums []int, k int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2420.Find All Good Indices/README_EN.md b/solution/2400-2499/2420.Find All Good Indices/README_EN.md index 3716404e0b80b..f57ef354c75f2 100644 --- a/solution/2400-2499/2420.Find All Good Indices/README_EN.md +++ b/solution/2400-2499/2420.Find All Good Indices/README_EN.md @@ -46,7 +46,7 @@ Note that the index 4 is not good because [4,1] is not non-decreasing. ## Solutions -**Solution 1: Recursion** +### Solution 1: Recursion We define two arrays `decr` and `incr`, which represent the longest non-increasing and non-decreasing subarray lengths from left to right and from right to left, respectively. @@ -58,8 +58,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def goodIndices(self, nums: List[int], k: int) -> List[int]: @@ -75,8 +73,6 @@ class Solution: return [i for i in range(k, n - k) if decr[i] >= k and incr[i] >= k] ``` -### **Java** - ```java class Solution { public List goodIndices(int[] nums, int k) { @@ -106,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +130,6 @@ public: }; ``` -### **Go** - ```go func goodIndices(nums []int, k int) []int { n := len(nums) @@ -167,16 +159,6 @@ func goodIndices(nums []int, k int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2421.Number of Good Paths/README.md b/solution/2400-2499/2421.Number of Good Paths/README.md index 13f3165b7f0bb..50c1045d44c91 100644 --- a/solution/2400-2499/2421.Number of Good Paths/README.md +++ b/solution/2400-2499/2421.Number of Good Paths/README.md @@ -71,9 +71,7 @@ ## 解法 - - -**方法一:排序 + 并查集** +### 方法一:排序 + 并查集 要保证路径起点(终点)大于等于路径上的所有点,因此我们可以考虑先把所有点按值从小到大排序,然后再进行遍历,添加到连通块中,具体如下: @@ -83,10 +81,6 @@ -### **Python3** - - - ```python class Solution: def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int: @@ -119,10 +113,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] p; @@ -173,8 +163,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -221,8 +209,6 @@ public: }; ``` -### **Go** - ```go func numberOfGoodPaths(vals []int, edges [][]int) int { n := len(vals) @@ -273,16 +259,6 @@ func numberOfGoodPaths(vals []int, edges [][]int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2421.Number of Good Paths/README_EN.md b/solution/2400-2499/2421.Number of Good Paths/README_EN.md index 85b3d03e07a33..e457412c284c5 100644 --- a/solution/2400-2499/2421.Number of Good Paths/README_EN.md +++ b/solution/2400-2499/2421.Number of Good Paths/README_EN.md @@ -64,7 +64,7 @@ There are 2 additional good paths: 0 -> 1 and 2 -> 3. ## Solutions -**Solution 1: Sorting + Union Find** +### Solution 1: Sorting + Union Find To ensure that the starting point (or endpoint) of the path is greater than or equal to all points on the path, we can consider sorting all points from small to large first, then traverse and add them to the connected component, specifically as follows: @@ -74,8 +74,6 @@ The time complexity is $O(n \times \log n)$. -### **Python3** - ```python class Solution: def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int: @@ -108,8 +106,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] p; @@ -160,8 +156,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -208,8 +202,6 @@ public: }; ``` -### **Go** - ```go func numberOfGoodPaths(vals []int, edges [][]int) int { n := len(vals) @@ -260,16 +252,6 @@ func numberOfGoodPaths(vals []int, edges [][]int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2422.Merge Operations to Turn Array Into a Palindrome/README.md b/solution/2400-2499/2422.Merge Operations to Turn Array Into a Palindrome/README.md index 28e5406bce88f..283347ee7f457 100644 --- a/solution/2400-2499/2422.Merge Operations to Turn Array Into a Palindrome/README.md +++ b/solution/2400-2499/2422.Merge Operations to Turn Array Into a Palindrome/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:贪心 + 双指针** +### 方法一:贪心 + 双指针 定义两个指针 $i$ 和 $j$,分别指向数组的首尾,用变量 $a$ 和 $b$ 分别表示首尾两个元素的值,变量 $ans$ 表示操作次数。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def minimumOperations(self, nums: List[int]) -> int: @@ -96,10 +90,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumOperations(int[] nums) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go func minimumOperations(nums []int) int { i, j := 0, len(nums)-1 @@ -174,16 +160,6 @@ func minimumOperations(nums []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2422.Merge Operations to Turn Array Into a Palindrome/README_EN.md b/solution/2400-2499/2422.Merge Operations to Turn Array Into a Palindrome/README_EN.md index 8c3762c4a9e5e..e98de481f0294 100644 --- a/solution/2400-2499/2422.Merge Operations to Turn Array Into a Palindrome/README_EN.md +++ b/solution/2400-2499/2422.Merge Operations to Turn Array Into a Palindrome/README_EN.md @@ -49,7 +49,7 @@ It can be shown that 2 is the minimum number of operations needed. ## Solutions -**Solution 1: Greedy + Two Pointers** +### Solution 1: Greedy + Two Pointers Define two pointers $i$ and $j$, pointing to the beginning and end of the array respectively, use variables $a$ and $b$ to represent the values of the first and last elements, and variable $ans$ to represent the number of operations. @@ -65,8 +65,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def minimumOperations(self, nums: List[int]) -> int: @@ -88,8 +86,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumOperations(int[] nums) { @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +133,6 @@ public: }; ``` -### **Go** - ```go func minimumOperations(nums []int) int { i, j := 0, len(nums)-1 @@ -164,16 +156,6 @@ func minimumOperations(nums []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2423.Remove Letter To Equalize Frequency/README.md b/solution/2400-2499/2423.Remove Letter To Equalize Frequency/README.md index 187b0e22693c8..28bd9807c4fc0 100644 --- a/solution/2400-2499/2423.Remove Letter To Equalize Frequency/README.md +++ b/solution/2400-2499/2423.Remove Letter To Equalize Frequency/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:计数 + 枚举** +### 方法一:计数 + 枚举 我们先用哈希表或者一个长度为 $26$ 的数组 $cnt$ 统计字符串中每个字母出现的次数。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def equalFrequency(self, word: str) -> bool: @@ -76,10 +70,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean equalFrequency(String word) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go func equalFrequency(word string) bool { cnt := [26]int{} @@ -182,8 +168,6 @@ func equalFrequency(word string) bool { } ``` -### **TypeScript** - ```ts function equalFrequency(word: string): boolean { const cnt: number[] = new Array(26).fill(0); @@ -215,10 +199,6 @@ function equalFrequency(word: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2423.Remove Letter To Equalize Frequency/README_EN.md b/solution/2400-2499/2423.Remove Letter To Equalize Frequency/README_EN.md index 52895bcf6d1e6..8abdf41b4160a 100644 --- a/solution/2400-2499/2423.Remove Letter To Equalize Frequency/README_EN.md +++ b/solution/2400-2499/2423.Remove Letter To Equalize Frequency/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Counting + Enumeration** +### Solution 1: Counting + Enumeration First, we use a hash table or an array of length $26$ named $cnt$ to count the number of occurrences of each letter in the string. @@ -54,8 +54,6 @@ The time complexity is $O(n + C^2)$, and the space complexity is $O(C)$. Here, $ -### **Python3** - ```python class Solution: def equalFrequency(self, word: str) -> bool: @@ -68,8 +66,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean equalFrequency(String word) { @@ -103,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +133,6 @@ public: }; ``` -### **Go** - ```go func equalFrequency(word string) bool { cnt := [26]int{} @@ -172,8 +164,6 @@ func equalFrequency(word string) bool { } ``` -### **TypeScript** - ```ts function equalFrequency(word: string): boolean { const cnt: number[] = new Array(26).fill(0); @@ -205,10 +195,6 @@ function equalFrequency(word: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2424.Longest Uploaded Prefix/README.md b/solution/2400-2499/2424.Longest Uploaded Prefix/README.md index 0d463f05055d0..ca7a2bd8a7ca8 100644 --- a/solution/2400-2499/2424.Longest Uploaded Prefix/README.md +++ b/solution/2400-2499/2424.Longest Uploaded Prefix/README.md @@ -52,9 +52,7 @@ server.longest(); // 前缀 [1,2,3] 是最长上传前缀, ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们用变量 $r$ 记录当前的最长上传前缀,用数组或哈希表 $s$ 记录已经上传的视频。 @@ -64,10 +62,6 @@ server.longest(); // 前缀 [1,2,3] 是最长上传前缀, -### **Python3** - - - ```python class LUPrefix: def __init__(self, n: int): @@ -89,10 +83,6 @@ class LUPrefix: # param_2 = obj.longest() ``` -### **Java** - - - ```java class LUPrefix { private int r; @@ -121,8 +111,6 @@ class LUPrefix { */ ``` -### **C++** - ```cpp class LUPrefix { public: @@ -153,8 +141,6 @@ private: */ ``` -### **Go** - ```go type LUPrefix struct { r int @@ -184,16 +170,6 @@ func (this *LUPrefix) Longest() int { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2424.Longest Uploaded Prefix/README_EN.md b/solution/2400-2499/2424.Longest Uploaded Prefix/README_EN.md index 77eff34cc54ad..03b3de447c016 100644 --- a/solution/2400-2499/2424.Longest Uploaded Prefix/README_EN.md +++ b/solution/2400-2499/2424.Longest Uploaded Prefix/README_EN.md @@ -50,7 +50,7 @@ server.longest(); // The prefix [1,2,3] is the longest upload ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We use a variable $r$ to record the current longest prefix of uploaded videos, and an array or hash table $s$ to record the videos that have been uploaded. @@ -60,8 +60,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class LUPrefix: def __init__(self, n: int): @@ -83,8 +81,6 @@ class LUPrefix: # param_2 = obj.longest() ``` -### **Java** - ```java class LUPrefix { private int r; @@ -113,8 +109,6 @@ class LUPrefix { */ ``` -### **C++** - ```cpp class LUPrefix { public: @@ -145,8 +139,6 @@ private: */ ``` -### **Go** - ```go type LUPrefix struct { r int @@ -176,16 +168,6 @@ func (this *LUPrefix) Longest() int { */ ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2425.Bitwise XOR of All Pairings/README.md b/solution/2400-2499/2425.Bitwise XOR of All Pairings/README.md index f4373f2285402..898f0eeed2552 100644 --- a/solution/2400-2499/2425.Bitwise XOR of All Pairings/README.md +++ b/solution/2400-2499/2425.Bitwise XOR of All Pairings/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:脑筋急转弯 + 位运算** +### 方法一:脑筋急转弯 + 位运算 由于数组的每个元素都会与另一个数组的每个元素进行异或,我们知道,同一个数异或两次,结果不变,即 $a \oplus a = 0$。因此,我们只需要统计数组的长度,就能知道每个元素与另一个数组的每个元素进行异或的次数。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def xorAllNums(self, nums1: List[int], nums2: List[int]) -> int: @@ -75,10 +69,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int xorAllNums(int[] nums1, int[] nums2) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func xorAllNums(nums1 []int, nums2 []int) int { ans := 0 @@ -139,8 +125,6 @@ func xorAllNums(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - ```ts function xorAllNums(nums1: number[], nums2: number[]): number { let ans = 0; @@ -154,10 +138,6 @@ function xorAllNums(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2425.Bitwise XOR of All Pairings/README_EN.md b/solution/2400-2499/2425.Bitwise XOR of All Pairings/README_EN.md index cd6de44325108..1d5640a64bc3c 100644 --- a/solution/2400-2499/2425.Bitwise XOR of All Pairings/README_EN.md +++ b/solution/2400-2499/2425.Bitwise XOR of All Pairings/README_EN.md @@ -41,7 +41,7 @@ Thus, one possible nums3 array is [2,5,1,6]. ## Solutions -**Solution 1: Quick Thinking + Bit Manipulation** +### Solution 1: Quick Thinking + Bit Manipulation Since each element of the array will be XORed with each element of another array, we know that the result remains the same when the same number is XORed twice, i.e., $a \oplus a = 0$. Therefore, we only need to count the length of the array to know how many times each element is XORed with each element of another array. @@ -55,8 +55,6 @@ The time complexity is $O(m+n)$. Where $m$ and $n$ are the lengths of the `nums1 -### **Python3** - ```python class Solution: def xorAllNums(self, nums1: List[int], nums2: List[int]) -> int: @@ -70,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int xorAllNums(int[] nums1, int[] nums2) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +107,6 @@ public: }; ``` -### **Go** - ```go func xorAllNums(nums1 []int, nums2 []int) int { ans := 0 @@ -132,8 +124,6 @@ func xorAllNums(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - ```ts function xorAllNums(nums1: number[], nums2: number[]): number { let ans = 0; @@ -147,10 +137,6 @@ function xorAllNums(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2426.Number of Pairs Satisfying Inequality/README.md b/solution/2400-2499/2426.Number of Pairs Satisfying Inequality/README.md index 6ae874fa4d26b..9236be51b741d 100644 --- a/solution/2400-2499/2426.Number of Pairs Satisfying Inequality/README.md +++ b/solution/2400-2499/2426.Number of Pairs Satisfying Inequality/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:树状数组** +### 方法一:树状数组 我们将题目的不等式转换一下,得到 $nums1[i] - nums2[i] \leq nums1[j] - nums2[j] + diff$,因此,如果我们对两个数组对应位置的元素求差值,得到另一个数组 $nums$,那么题目就转换为求 $nums$ 中满足 $nums[i] \leq nums[j] + diff$ 的数对数目。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class BinaryIndexedTree: def __init__(self, n): @@ -100,10 +94,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class BinaryIndexedTree { private int n; @@ -149,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -197,8 +185,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -242,16 +228,6 @@ func numberOfPairs(nums1 []int, nums2 []int, diff int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2426.Number of Pairs Satisfying Inequality/README_EN.md b/solution/2400-2499/2426.Number of Pairs Satisfying Inequality/README_EN.md index 50c2c472a2ace..40c8d816ba094 100644 --- a/solution/2400-2499/2426.Number of Pairs Satisfying Inequality/README_EN.md +++ b/solution/2400-2499/2426.Number of Pairs Satisfying Inequality/README_EN.md @@ -48,7 +48,7 @@ Since there does not exist any pair that satisfies the conditions, we return 0. ## Solutions -**Solution 1: Binary Indexed Tree** +### Solution 1: Binary Indexed Tree We can transform the inequality in the problem to $nums1[i] - nums2[i] \leq nums1[j] - nums2[j] + diff$. Therefore, if we calculate the difference between the corresponding elements of the two arrays and get another array $nums$, the problem is transformed into finding the number of pairs in $nums$ that satisfy $nums[i] \leq nums[j] + diff$. @@ -58,8 +58,6 @@ The time complexity is $O(n \times \log n)$. -### **Python3** - ```python class BinaryIndexedTree: def __init__(self, n): @@ -94,8 +92,6 @@ class Solution: return ans ``` -### **Java** - ```java class BinaryIndexedTree { private int n; @@ -141,8 +137,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -189,8 +183,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -234,16 +226,6 @@ func numberOfPairs(nums1 []int, nums2 []int, diff int) int64 { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2427.Number of Common Factors/README.md b/solution/2400-2499/2427.Number of Common Factors/README.md index 83f1c94d50e41..98a62e1b68594 100644 --- a/solution/2400-2499/2427.Number of Common Factors/README.md +++ b/solution/2400-2499/2427.Number of Common Factors/README.md @@ -35,26 +35,14 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以先算出 $a$ 和 $b$ 的最大公约数 $g$,然后枚举 $[1,..g]$ 中的每个数,判断其是否是 $g$ 的因子,如果是,则答案加一。 时间复杂度 $O(\min(a, b))$,空间复杂度 $O(1)$。 -**方法二:枚举优化** - -与方法一类似,我们可以先算出 $a$ 和 $b$ 的最大公约数 $g$,然后枚举最大公约数 $g$ 的所有因子,累加答案。 - -时间复杂度 $O(\sqrt{\min(a, b)})$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def commonFactors(self, a: int, b: int) -> int: @@ -62,23 +50,6 @@ class Solution: return sum(g % x == 0 for x in range(1, g + 1)) ``` -```python -class Solution: - def commonFactors(self, a: int, b: int) -> int: - g = gcd(a, b) - ans, x = 0, 1 - while x * x <= g: - if g % x == 0: - ans += 1 - ans += x * x < g - x += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int commonFactors(int a, int b) { @@ -98,6 +69,79 @@ class Solution { } ``` +```cpp +class Solution { +public: + int commonFactors(int a, int b) { + int g = gcd(a, b); + int ans = 0; + for (int x = 1; x <= g; ++x) { + ans += g % x == 0; + } + return ans; + } +}; +``` + +```go +func commonFactors(a int, b int) (ans int) { + g := gcd(a, b) + for x := 1; x <= g; x++ { + if g%x == 0 { + ans++ + } + } + return +} + +func gcd(a int, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) +} +``` + +```ts +function commonFactors(a: number, b: number): number { + const g = gcd(a, b); + let ans = 0; + for (let x = 1; x <= g; ++x) { + if (g % x === 0) { + ++ans; + } + } + return ans; +} + +function gcd(a: number, b: number): number { + return b === 0 ? a : gcd(b, a % b); +} +``` + + + +### 方法二:枚举优化 + +与方法一类似,我们可以先算出 $a$ 和 $b$ 的最大公约数 $g$,然后枚举最大公约数 $g$ 的所有因子,累加答案。 + +时间复杂度 $O(\sqrt{\min(a, b)})$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def commonFactors(self, a: int, b: int) -> int: + g = gcd(a, b) + ans, x = 0, 1 + while x * x <= g: + if g % x == 0: + ans += 1 + ans += x * x < g + x += 1 + return ans +``` + ```java class Solution { public int commonFactors(int a, int b) { @@ -120,22 +164,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int commonFactors(int a, int b) { - int g = gcd(a, b); - int ans = 0; - for (int x = 1; x <= g; ++x) { - ans += g % x == 0; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -153,27 +181,6 @@ public: }; ``` -### **Go** - -```go -func commonFactors(a int, b int) (ans int) { - g := gcd(a, b) - for x := 1; x <= g; x++ { - if g%x == 0 { - ans++ - } - } - return -} - -func gcd(a int, b int) int { - if b == 0 { - return a - } - return gcd(b, a%b) -} -``` - ```go func commonFactors(a int, b int) (ans int) { g := gcd(a, b) @@ -196,25 +203,6 @@ func gcd(a int, b int) int { } ``` -### **TypeScript** - -```ts -function commonFactors(a: number, b: number): number { - const g = gcd(a, b); - let ans = 0; - for (let x = 1; x <= g; ++x) { - if (g % x === 0) { - ++ans; - } - } - return ans; -} - -function gcd(a: number, b: number): number { - return b === 0 ? a : gcd(b, a % b); -} -``` - ```ts function commonFactors(a: number, b: number): number { const g = gcd(a, b); @@ -235,10 +223,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2427.Number of Common Factors/README_EN.md b/solution/2400-2499/2427.Number of Common Factors/README_EN.md index 9dc6f6e10e163..fbeb1d239a7a3 100644 --- a/solution/2400-2499/2427.Number of Common Factors/README_EN.md +++ b/solution/2400-2499/2427.Number of Common Factors/README_EN.md @@ -34,22 +34,14 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We can first calculate the greatest common divisor $g$ of $a$ and $b$, then enumerate each number in $[1,..g]$, check whether it is a factor of $g$, if it is, then increment the answer by one. The time complexity is $O(\min(a, b))$, and the space complexity is $O(1)$. -**Solution 2: Optimized Enumeration** - -Similar to Solution 1, we can first calculate the greatest common divisor $g$ of $a$ and $b$, then enumerate all factors of the greatest common divisor $g$, and accumulate the answer. - -The time complexity is $O(\sqrt{\min(a, b)})$, and the space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def commonFactors(self, a: int, b: int) -> int: @@ -57,21 +49,6 @@ class Solution: return sum(g % x == 0 for x in range(1, g + 1)) ``` -```python -class Solution: - def commonFactors(self, a: int, b: int) -> int: - g = gcd(a, b) - ans, x = 0, 1 - while x * x <= g: - if g % x == 0: - ans += 1 - ans += x * x < g - x += 1 - return ans -``` - -### **Java** - ```java class Solution { public int commonFactors(int a, int b) { @@ -91,6 +68,79 @@ class Solution { } ``` +```cpp +class Solution { +public: + int commonFactors(int a, int b) { + int g = gcd(a, b); + int ans = 0; + for (int x = 1; x <= g; ++x) { + ans += g % x == 0; + } + return ans; + } +}; +``` + +```go +func commonFactors(a int, b int) (ans int) { + g := gcd(a, b) + for x := 1; x <= g; x++ { + if g%x == 0 { + ans++ + } + } + return +} + +func gcd(a int, b int) int { + if b == 0 { + return a + } + return gcd(b, a%b) +} +``` + +```ts +function commonFactors(a: number, b: number): number { + const g = gcd(a, b); + let ans = 0; + for (let x = 1; x <= g; ++x) { + if (g % x === 0) { + ++ans; + } + } + return ans; +} + +function gcd(a: number, b: number): number { + return b === 0 ? a : gcd(b, a % b); +} +``` + + + +### Solution 2: Optimized Enumeration + +Similar to Solution 1, we can first calculate the greatest common divisor $g$ of $a$ and $b$, then enumerate all factors of the greatest common divisor $g$, and accumulate the answer. + +The time complexity is $O(\sqrt{\min(a, b)})$, and the space complexity is $O(1)$. + + + +```python +class Solution: + def commonFactors(self, a: int, b: int) -> int: + g = gcd(a, b) + ans, x = 0, 1 + while x * x <= g: + if g % x == 0: + ans += 1 + ans += x * x < g + x += 1 + return ans +``` + ```java class Solution { public int commonFactors(int a, int b) { @@ -113,22 +163,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int commonFactors(int a, int b) { - int g = gcd(a, b); - int ans = 0; - for (int x = 1; x <= g; ++x) { - ans += g % x == 0; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -146,27 +180,6 @@ public: }; ``` -### **Go** - -```go -func commonFactors(a int, b int) (ans int) { - g := gcd(a, b) - for x := 1; x <= g; x++ { - if g%x == 0 { - ans++ - } - } - return -} - -func gcd(a int, b int) int { - if b == 0 { - return a - } - return gcd(b, a%b) -} -``` - ```go func commonFactors(a int, b int) (ans int) { g := gcd(a, b) @@ -189,25 +202,6 @@ func gcd(a int, b int) int { } ``` -### **TypeScript** - -```ts -function commonFactors(a: number, b: number): number { - const g = gcd(a, b); - let ans = 0; - for (let x = 1; x <= g; ++x) { - if (g % x === 0) { - ++ans; - } - } - return ans; -} - -function gcd(a: number, b: number): number { - return b === 0 ? a : gcd(b, a % b); -} -``` - ```ts function commonFactors(a: number, b: number): number { const g = gcd(a, b); @@ -228,10 +222,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2428.Maximum Sum of an Hourglass/README.md b/solution/2400-2499/2428.Maximum Sum of an Hourglass/README.md index 88e6b83cae3b1..b10a5c3b871fc 100644 --- a/solution/2400-2499/2428.Maximum Sum of an Hourglass/README.md +++ b/solution/2400-2499/2428.Maximum Sum of an Hourglass/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们观察题目发现,每个沙漏就是一个 $3 \times 3$ 的矩阵挖去中间行的首尾两个元素。因此,我们可以从左上角开始,枚举每个沙漏的中间坐标 $(i, j)$,然后计算沙漏的元素和,取其中的最大值即可。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def maxSum(self, grid: List[List[int]]) -> int: @@ -72,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxSum(int[][] grid) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func maxSum(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -141,8 +127,6 @@ func maxSum(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function maxSum(grid: number[][]): number { const m = grid.length; @@ -163,10 +147,6 @@ function maxSum(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2428.Maximum Sum of an Hourglass/README_EN.md b/solution/2400-2499/2428.Maximum Sum of an Hourglass/README_EN.md index 18b03ec3ad97c..b6d92ac9c9877 100644 --- a/solution/2400-2499/2428.Maximum Sum of an Hourglass/README_EN.md +++ b/solution/2400-2499/2428.Maximum Sum of an Hourglass/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We observe from the problem statement that each hourglass is a $3 \times 3$ matrix with the first and last elements of the middle row removed. Therefore, we can start from the top left corner, enumerate the middle coordinate $(i, j)$ of each hourglass, then calculate the sum of the elements in the hourglass, and take the maximum value. @@ -49,8 +49,6 @@ The time complexity is $O(m \times n)$, where $m$ and $n$ are the number of rows -### **Python3** - ```python class Solution: def maxSum(self, grid: List[List[int]]) -> int: @@ -66,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxSum(int[][] grid) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +107,6 @@ public: }; ``` -### **Go** - ```go func maxSum(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -133,8 +125,6 @@ func maxSum(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function maxSum(grid: number[][]): number { const m = grid.length; @@ -155,10 +145,6 @@ function maxSum(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2429.Minimize XOR/README.md b/solution/2400-2499/2429.Minimize XOR/README.md index 71944535d49a6..c80efecf21f7d 100644 --- a/solution/2400-2499/2429.Minimize XOR/README.md +++ b/solution/2400-2499/2429.Minimize XOR/README.md @@ -51,9 +51,7 @@ num1 和 num2 的二进制表示分别是 0001 和 1100 。 ## 解法 - - -**方法一:贪心 + 位运算** +### 方法一:贪心 + 位运算 根据题目描述,我们先求出 $num2$ 的置位数 $cnt$,然后从高位到低位枚举 $num1$ 的每一位,如果该位为 $1$,则将 $x$ 的对应位设为 $1$,并将 $cnt$ 减 $1$,直到 $cnt$ 为 $0$。如果此时 $cnt$ 仍不为 $0$,则从低位开始将 $num1$ 的每一位为 $0$ 的位置设为 $1$,并将 $cnt$ 减 $1$,直到 $cnt$ 为 $0$。 @@ -61,10 +59,6 @@ num1 和 num2 的二进制表示分别是 0001 和 1100 。 -### **Python3** - - - ```python class Solution: def minimizeXor(self, num1: int, num2: int) -> int: @@ -81,24 +75,6 @@ class Solution: return x ``` -```python -class Solution: - def minimizeXor(self, num1: int, num2: int) -> int: - cnt1 = num1.bit_count() - cnt2 = num2.bit_count() - while cnt1 > cnt2: - num1 &= num1 - 1 - cnt1 -= 1 - while cnt1 < cnt2: - num1 |= num1 + 1 - cnt1 += 1 - return num1 -``` - -### **Java** - - - ```java class Solution { public int minimizeXor(int num1, int num2) { @@ -121,24 +97,6 @@ class Solution { } ``` -```java -class Solution { - public int minimizeXor(int num1, int num2) { - int cnt1 = Integer.bitCount(num1); - int cnt2 = Integer.bitCount(num2); - for (; cnt1 > cnt2; --cnt1) { - num1 &= (num1 - 1); - } - for (; cnt1 < cnt2; ++cnt1) { - num1 |= (num1 + 1); - } - return num1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -162,25 +120,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minimizeXor(int num1, int num2) { - int cnt1 = __builtin_popcount(num1); - int cnt2 = __builtin_popcount(num2); - for (; cnt1 > cnt2; --cnt1) { - num1 &= (num1 - 1); - } - for (; cnt1 < cnt2; ++cnt1) { - num1 |= (num1 + 1); - } - return num1; - } -}; -``` - -### **Go** - ```go func minimizeXor(num1 int, num2 int) int { cnt := bits.OnesCount(uint(num2)) @@ -201,22 +140,6 @@ func minimizeXor(num1 int, num2 int) int { } ``` -```go -func minimizeXor(num1 int, num2 int) int { - cnt1 := bits.OnesCount(uint(num1)) - cnt2 := bits.OnesCount(uint(num2)) - for ; cnt1 > cnt2; cnt1-- { - num1 &= (num1 - 1) - } - for ; cnt1 < cnt2; cnt1++ { - num1 |= (num1 + 1) - } - return num1 -} -``` - -### **TypeScript** - ```ts function minimizeXor(num1: number, num2: number): number { let cnt = 0; @@ -241,6 +164,73 @@ function minimizeXor(num1: number, num2: number): number { } ``` + + +### 方法二 + + + +```python +class Solution: + def minimizeXor(self, num1: int, num2: int) -> int: + cnt1 = num1.bit_count() + cnt2 = num2.bit_count() + while cnt1 > cnt2: + num1 &= num1 - 1 + cnt1 -= 1 + while cnt1 < cnt2: + num1 |= num1 + 1 + cnt1 += 1 + return num1 +``` + +```java +class Solution { + public int minimizeXor(int num1, int num2) { + int cnt1 = Integer.bitCount(num1); + int cnt2 = Integer.bitCount(num2); + for (; cnt1 > cnt2; --cnt1) { + num1 &= (num1 - 1); + } + for (; cnt1 < cnt2; ++cnt1) { + num1 |= (num1 + 1); + } + return num1; + } +} +``` + +```cpp +class Solution { +public: + int minimizeXor(int num1, int num2) { + int cnt1 = __builtin_popcount(num1); + int cnt2 = __builtin_popcount(num2); + for (; cnt1 > cnt2; --cnt1) { + num1 &= (num1 - 1); + } + for (; cnt1 < cnt2; ++cnt1) { + num1 |= (num1 + 1); + } + return num1; + } +}; +``` + +```go +func minimizeXor(num1 int, num2 int) int { + cnt1 := bits.OnesCount(uint(num1)) + cnt2 := bits.OnesCount(uint(num2)) + for ; cnt1 > cnt2; cnt1-- { + num1 &= (num1 - 1) + } + for ; cnt1 < cnt2; cnt1++ { + num1 |= (num1 + 1) + } + return num1 +} +``` + ```ts function minimizeXor(num1: number, num2: number): number { let cnt1 = bitCount(num1); @@ -264,10 +254,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2429.Minimize XOR/README_EN.md b/solution/2400-2499/2429.Minimize XOR/README_EN.md index 999dced728a28..4322cae8566e3 100644 --- a/solution/2400-2499/2429.Minimize XOR/README_EN.md +++ b/solution/2400-2499/2429.Minimize XOR/README_EN.md @@ -47,7 +47,7 @@ The integer 3 has the same number of set bits as num2, and the ## Solutions -**Solution 1: Greedy + Bit Manipulation** +### Solution 1: Greedy + Bit Manipulation According to the problem description, we first calculate the number of set bits $cnt$ in $num2$, then enumerate each bit of $num1$ from high to low. If the bit is $1$, we set the corresponding bit in $x$ to $1$ and decrement $cnt$ by $1$, until $cnt$ is $0$. If $cnt$ is still not $0$ at this point, we start from the low bit and set each bit of $num1$ that is $0$ to $1$, and decrement $cnt$ by $1$, until $cnt$ is $0$. @@ -55,8 +55,6 @@ The time complexity is $O(\log n)$, and the space complexity is $O(1)$. Here, $n -### **Python3** - ```python class Solution: def minimizeXor(self, num1: int, num2: int) -> int: @@ -73,22 +71,6 @@ class Solution: return x ``` -```python -class Solution: - def minimizeXor(self, num1: int, num2: int) -> int: - cnt1 = num1.bit_count() - cnt2 = num2.bit_count() - while cnt1 > cnt2: - num1 &= num1 - 1 - cnt1 -= 1 - while cnt1 < cnt2: - num1 |= num1 + 1 - cnt1 += 1 - return num1 -``` - -### **Java** - ```java class Solution { public int minimizeXor(int num1, int num2) { @@ -111,24 +93,6 @@ class Solution { } ``` -```java -class Solution { - public int minimizeXor(int num1, int num2) { - int cnt1 = Integer.bitCount(num1); - int cnt2 = Integer.bitCount(num2); - for (; cnt1 > cnt2; --cnt1) { - num1 &= (num1 - 1); - } - for (; cnt1 < cnt2; ++cnt1) { - num1 |= (num1 + 1); - } - return num1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -152,25 +116,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minimizeXor(int num1, int num2) { - int cnt1 = __builtin_popcount(num1); - int cnt2 = __builtin_popcount(num2); - for (; cnt1 > cnt2; --cnt1) { - num1 &= (num1 - 1); - } - for (; cnt1 < cnt2; ++cnt1) { - num1 |= (num1 + 1); - } - return num1; - } -}; -``` - -### **Go** - ```go func minimizeXor(num1 int, num2 int) int { cnt := bits.OnesCount(uint(num2)) @@ -191,22 +136,6 @@ func minimizeXor(num1 int, num2 int) int { } ``` -```go -func minimizeXor(num1 int, num2 int) int { - cnt1 := bits.OnesCount(uint(num1)) - cnt2 := bits.OnesCount(uint(num2)) - for ; cnt1 > cnt2; cnt1-- { - num1 &= (num1 - 1) - } - for ; cnt1 < cnt2; cnt1++ { - num1 |= (num1 + 1) - } - return num1 -} -``` - -### **TypeScript** - ```ts function minimizeXor(num1: number, num2: number): number { let cnt = 0; @@ -231,6 +160,73 @@ function minimizeXor(num1: number, num2: number): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def minimizeXor(self, num1: int, num2: int) -> int: + cnt1 = num1.bit_count() + cnt2 = num2.bit_count() + while cnt1 > cnt2: + num1 &= num1 - 1 + cnt1 -= 1 + while cnt1 < cnt2: + num1 |= num1 + 1 + cnt1 += 1 + return num1 +``` + +```java +class Solution { + public int minimizeXor(int num1, int num2) { + int cnt1 = Integer.bitCount(num1); + int cnt2 = Integer.bitCount(num2); + for (; cnt1 > cnt2; --cnt1) { + num1 &= (num1 - 1); + } + for (; cnt1 < cnt2; ++cnt1) { + num1 |= (num1 + 1); + } + return num1; + } +} +``` + +```cpp +class Solution { +public: + int minimizeXor(int num1, int num2) { + int cnt1 = __builtin_popcount(num1); + int cnt2 = __builtin_popcount(num2); + for (; cnt1 > cnt2; --cnt1) { + num1 &= (num1 - 1); + } + for (; cnt1 < cnt2; ++cnt1) { + num1 |= (num1 + 1); + } + return num1; + } +}; +``` + +```go +func minimizeXor(num1 int, num2 int) int { + cnt1 := bits.OnesCount(uint(num1)) + cnt2 := bits.OnesCount(uint(num2)) + for ; cnt1 > cnt2; cnt1-- { + num1 &= (num1 - 1) + } + for ; cnt1 < cnt2; cnt1++ { + num1 |= (num1 + 1) + } + return num1 +} +``` + ```ts function minimizeXor(num1: number, num2: number): number { let cnt1 = bitCount(num1); @@ -254,10 +250,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2430.Maximum Deletions on a String/README.md b/solution/2400-2499/2430.Maximum Deletions on a String/README.md index cead0d2c98437..ef02d4e94f4b6 100644 --- a/solution/2400-2499/2430.Maximum Deletions on a String/README.md +++ b/solution/2400-2499/2430.Maximum Deletions on a String/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i)$,表示删除 $s[i..]$ 所有字符所需的最大操作数,那么答案就是 $dfs(0)$。 @@ -80,20 +78,8 @@ 时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是字符串 $s$ 的长度。 -**方法二:动态规划** - -我们可以将方法一的记忆化搜索改为动态规划,定义 $f[i]$ 表示删除 $s[i..]$ 所有字符所需的最大操作数,初始时 $f[i]=1$,答案为 $f[0]$。 - -我们可以从后往前枚举 $i$,对于每个 $i$,我们枚举字符串的长度 $j$,其中 $1 \leq j \leq (n-1)/2$,如果 $s[i..i+j] = s[i+j..i+j+j]$,那么我们可以删除 $s[i..i+j]$,此时 $f[i]=max(f[i], f[i+j]+1)$。我们需要枚举所有的 $j$,求 $f[i]$ 的最大值即可。 - -时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $s$ 的长度。 - -### **Python3** - - - ```python class Solution: def deleteString(self, s: str) -> int: @@ -111,28 +97,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def deleteString(self, s: str) -> int: - n = len(s) - g = [[0] * (n + 1) for _ in range(n + 1)] - for i in range(n - 1, -1, -1): - for j in range(i + 1, n): - if s[i] == s[j]: - g[i][j] = g[i + 1][j + 1] + 1 - - f = [1] * n - for i in range(n - 1, -1, -1): - for j in range(1, (n - i) // 2 + 1): - if g[i][i + j] >= j: - f[i] = max(f[i], f[i + j] + 1) - return f[0] -``` - -### **Java** - - - ```java class Solution { private int n; @@ -171,34 +135,6 @@ class Solution { } ``` -```java -class Solution { - public int deleteString(String s) { - int n = s.length(); - int[][] g = new int[n + 1][n + 1]; - for (int i = n - 1; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - if (s.charAt(i) == s.charAt(j)) { - g[i][j] = g[i + 1][j + 1] + 1; - } - } - } - int[] f = new int[n]; - for (int i = n - 1; i >= 0; --i) { - f[i] = 1; - for (int j = 1; j <= (n - i) / 2; ++j) { - if (g[i][i + j] >= j) { - f[i] = Math.max(f[i], f[i + j] + 1); - } - } - } - return f[0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -235,36 +171,6 @@ public: }; ``` -```cpp -class Solution { -public: - int deleteString(string s) { - int n = s.size(); - int g[n + 1][n + 1]; - memset(g, 0, sizeof(g)); - for (int i = n - 1; ~i; --i) { - for (int j = i + 1; j < n; ++j) { - if (s[i] == s[j]) { - g[i][j] = g[i + 1][j + 1] + 1; - } - } - } - int f[n]; - for (int i = n - 1; ~i; --i) { - f[i] = 1; - for (int j = 1; j <= (n - i) / 2; ++j) { - if (g[i][i + j] >= j) { - f[i] = max(f[i], f[i + j] + 1); - } - } - } - return f[0]; - } -}; -``` - -### **Go** - ```go func deleteString(s string) int { n := len(s) @@ -300,6 +206,113 @@ func deleteString(s string) int { } ``` +```ts +function deleteString(s: string): number { + const n = s.length; + const f: number[] = new Array(n).fill(0); + const dfs = (i: number): number => { + if (i == n) { + return 0; + } + if (f[i] > 0) { + return f[i]; + } + f[i] = 1; + for (let j = 1; j <= (n - i) >> 1; ++j) { + if (s.slice(i, i + j) == s.slice(i + j, i + j + j)) { + f[i] = Math.max(f[i], dfs(i + j) + 1); + } + } + return f[i]; + }; + return dfs(0); +} +``` + + + +### 方法二:动态规划 + +我们可以将方法一的记忆化搜索改为动态规划,定义 $f[i]$ 表示删除 $s[i..]$ 所有字符所需的最大操作数,初始时 $f[i]=1$,答案为 $f[0]$。 + +我们可以从后往前枚举 $i$,对于每个 $i$,我们枚举字符串的长度 $j$,其中 $1 \leq j \leq (n-1)/2$,如果 $s[i..i+j] = s[i+j..i+j+j]$,那么我们可以删除 $s[i..i+j]$,此时 $f[i]=max(f[i], f[i+j]+1)$。我们需要枚举所有的 $j$,求 $f[i]$ 的最大值即可。 + +时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $s$ 的长度。 + + + +```python +class Solution: + def deleteString(self, s: str) -> int: + n = len(s) + g = [[0] * (n + 1) for _ in range(n + 1)] + for i in range(n - 1, -1, -1): + for j in range(i + 1, n): + if s[i] == s[j]: + g[i][j] = g[i + 1][j + 1] + 1 + + f = [1] * n + for i in range(n - 1, -1, -1): + for j in range(1, (n - i) // 2 + 1): + if g[i][i + j] >= j: + f[i] = max(f[i], f[i + j] + 1) + return f[0] +``` + +```java +class Solution { + public int deleteString(String s) { + int n = s.length(); + int[][] g = new int[n + 1][n + 1]; + for (int i = n - 1; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + if (s.charAt(i) == s.charAt(j)) { + g[i][j] = g[i + 1][j + 1] + 1; + } + } + } + int[] f = new int[n]; + for (int i = n - 1; i >= 0; --i) { + f[i] = 1; + for (int j = 1; j <= (n - i) / 2; ++j) { + if (g[i][i + j] >= j) { + f[i] = Math.max(f[i], f[i + j] + 1); + } + } + } + return f[0]; + } +} +``` + +```cpp +class Solution { +public: + int deleteString(string s) { + int n = s.size(); + int g[n + 1][n + 1]; + memset(g, 0, sizeof(g)); + for (int i = n - 1; ~i; --i) { + for (int j = i + 1; j < n; ++j) { + if (s[i] == s[j]) { + g[i][j] = g[i + 1][j + 1] + 1; + } + } + } + int f[n]; + for (int i = n - 1; ~i; --i) { + f[i] = 1; + for (int j = 1; j <= (n - i) / 2; ++j) { + if (g[i][i + j] >= j) { + f[i] = max(f[i], f[i + j] + 1); + } + } + } + return f[0]; + } +}; +``` + ```go func deleteString(s string) int { n := len(s) @@ -327,31 +340,6 @@ func deleteString(s string) int { } ``` -### **TypeScript** - -```ts -function deleteString(s: string): number { - const n = s.length; - const f: number[] = new Array(n).fill(0); - const dfs = (i: number): number => { - if (i == n) { - return 0; - } - if (f[i] > 0) { - return f[i]; - } - f[i] = 1; - for (let j = 1; j <= (n - i) >> 1; ++j) { - if (s.slice(i, i + j) == s.slice(i + j, i + j + j)) { - f[i] = Math.max(f[i], dfs(i + j) + 1); - } - } - return f[i]; - }; - return dfs(0); -} -``` - ```ts function deleteString(s: string): number { const n = s.length; @@ -367,10 +355,6 @@ function deleteString(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2430.Maximum Deletions on a String/README_EN.md b/solution/2400-2499/2430.Maximum Deletions on a String/README_EN.md index ac56f7393dd51..32ccc38ae977d 100644 --- a/solution/2400-2499/2430.Maximum Deletions on a String/README_EN.md +++ b/solution/2400-2499/2430.Maximum Deletions on a String/README_EN.md @@ -59,7 +59,7 @@ We used 4 operations so return 4. It can be proven that 4 is the maximum number ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We design a function $dfs(i)$, which represents the maximum number of operations needed to delete all characters from $s[i..]$. The answer is $dfs(0)$. @@ -74,18 +74,8 @@ To avoid repeated calculations, we can use memoization search and use an array $ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of the string $s$. -**Solution 2: Dynamic Programming** - -We can change the memoization search in Solution 1 to dynamic programming. Define $f[i]$ to represent the maximum number of operations needed to delete all characters from $s[i..]$. Initially, $f[i]=1$, and the answer is $f[0]$. - -We can enumerate $i$ from back to front. For each $i$, we enumerate the length of the string $j$, where $1 \leq j \leq (n-1)/2$. If $s[i..i+j] = s[i+j..i+j+j]$, we can delete $s[i..i+j]$, then $f[i]=max(f[i], f[i+j]+1)$. We need to enumerate all $j$ to find the maximum value of $f[i]$. - -The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$. - -### **Python3** - ```python class Solution: def deleteString(self, s: str) -> int: @@ -103,26 +93,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def deleteString(self, s: str) -> int: - n = len(s) - g = [[0] * (n + 1) for _ in range(n + 1)] - for i in range(n - 1, -1, -1): - for j in range(i + 1, n): - if s[i] == s[j]: - g[i][j] = g[i + 1][j + 1] + 1 - - f = [1] * n - for i in range(n - 1, -1, -1): - for j in range(1, (n - i) // 2 + 1): - if g[i][i + j] >= j: - f[i] = max(f[i], f[i + j] + 1) - return f[0] -``` - -### **Java** - ```java class Solution { private int n; @@ -161,34 +131,6 @@ class Solution { } ``` -```java -class Solution { - public int deleteString(String s) { - int n = s.length(); - int[][] g = new int[n + 1][n + 1]; - for (int i = n - 1; i >= 0; --i) { - for (int j = i + 1; j < n; ++j) { - if (s.charAt(i) == s.charAt(j)) { - g[i][j] = g[i + 1][j + 1] + 1; - } - } - } - int[] f = new int[n]; - for (int i = n - 1; i >= 0; --i) { - f[i] = 1; - for (int j = 1; j <= (n - i) / 2; ++j) { - if (g[i][i + j] >= j) { - f[i] = Math.max(f[i], f[i + j] + 1); - } - } - } - return f[0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -225,36 +167,6 @@ public: }; ``` -```cpp -class Solution { -public: - int deleteString(string s) { - int n = s.size(); - int g[n + 1][n + 1]; - memset(g, 0, sizeof(g)); - for (int i = n - 1; ~i; --i) { - for (int j = i + 1; j < n; ++j) { - if (s[i] == s[j]) { - g[i][j] = g[i + 1][j + 1] + 1; - } - } - } - int f[n]; - for (int i = n - 1; ~i; --i) { - f[i] = 1; - for (int j = 1; j <= (n - i) / 2; ++j) { - if (g[i][i + j] >= j) { - f[i] = max(f[i], f[i + j] + 1); - } - } - } - return f[0]; - } -}; -``` - -### **Go** - ```go func deleteString(s string) int { n := len(s) @@ -290,6 +202,113 @@ func deleteString(s string) int { } ``` +```ts +function deleteString(s: string): number { + const n = s.length; + const f: number[] = new Array(n).fill(0); + const dfs = (i: number): number => { + if (i == n) { + return 0; + } + if (f[i] > 0) { + return f[i]; + } + f[i] = 1; + for (let j = 1; j <= (n - i) >> 1; ++j) { + if (s.slice(i, i + j) == s.slice(i + j, i + j + j)) { + f[i] = Math.max(f[i], dfs(i + j) + 1); + } + } + return f[i]; + }; + return dfs(0); +} +``` + + + +### Solution 2: Dynamic Programming + +We can change the memoization search in Solution 1 to dynamic programming. Define $f[i]$ to represent the maximum number of operations needed to delete all characters from $s[i..]$. Initially, $f[i]=1$, and the answer is $f[0]$. + +We can enumerate $i$ from back to front. For each $i$, we enumerate the length of the string $j$, where $1 \leq j \leq (n-1)/2$. If $s[i..i+j] = s[i+j..i+j+j]$, we can delete $s[i..i+j]$, then $f[i]=max(f[i], f[i+j]+1)$. We need to enumerate all $j$ to find the maximum value of $f[i]$. + +The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$. + + + +```python +class Solution: + def deleteString(self, s: str) -> int: + n = len(s) + g = [[0] * (n + 1) for _ in range(n + 1)] + for i in range(n - 1, -1, -1): + for j in range(i + 1, n): + if s[i] == s[j]: + g[i][j] = g[i + 1][j + 1] + 1 + + f = [1] * n + for i in range(n - 1, -1, -1): + for j in range(1, (n - i) // 2 + 1): + if g[i][i + j] >= j: + f[i] = max(f[i], f[i + j] + 1) + return f[0] +``` + +```java +class Solution { + public int deleteString(String s) { + int n = s.length(); + int[][] g = new int[n + 1][n + 1]; + for (int i = n - 1; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + if (s.charAt(i) == s.charAt(j)) { + g[i][j] = g[i + 1][j + 1] + 1; + } + } + } + int[] f = new int[n]; + for (int i = n - 1; i >= 0; --i) { + f[i] = 1; + for (int j = 1; j <= (n - i) / 2; ++j) { + if (g[i][i + j] >= j) { + f[i] = Math.max(f[i], f[i + j] + 1); + } + } + } + return f[0]; + } +} +``` + +```cpp +class Solution { +public: + int deleteString(string s) { + int n = s.size(); + int g[n + 1][n + 1]; + memset(g, 0, sizeof(g)); + for (int i = n - 1; ~i; --i) { + for (int j = i + 1; j < n; ++j) { + if (s[i] == s[j]) { + g[i][j] = g[i + 1][j + 1] + 1; + } + } + } + int f[n]; + for (int i = n - 1; ~i; --i) { + f[i] = 1; + for (int j = 1; j <= (n - i) / 2; ++j) { + if (g[i][i + j] >= j) { + f[i] = max(f[i], f[i + j] + 1); + } + } + } + return f[0]; + } +}; +``` + ```go func deleteString(s string) int { n := len(s) @@ -317,31 +336,6 @@ func deleteString(s string) int { } ``` -### **TypeScript** - -```ts -function deleteString(s: string): number { - const n = s.length; - const f: number[] = new Array(n).fill(0); - const dfs = (i: number): number => { - if (i == n) { - return 0; - } - if (f[i] > 0) { - return f[i]; - } - f[i] = 1; - for (let j = 1; j <= (n - i) >> 1; ++j) { - if (s.slice(i, i + j) == s.slice(i + j, i + j + j)) { - f[i] = Math.max(f[i], dfs(i + j) + 1); - } - } - return f[i]; - }; - return dfs(0); -} -``` - ```ts function deleteString(s: string): number { const n = s.length; @@ -357,10 +351,6 @@ function deleteString(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2431.Maximize Total Tastiness of Purchased Fruits/README.md b/solution/2400-2499/2431.Maximize Total Tastiness of Purchased Fruits/README.md index 18a1388441913..60a19a45babbe 100644 --- a/solution/2400-2499/2431.Maximize Total Tastiness of Purchased Fruits/README.md +++ b/solution/2400-2499/2431.Maximize Total Tastiness of Purchased Fruits/README.md @@ -69,9 +69,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计函数 $dfs(i, j, k)$ 表示从第 $i$ 个水果开始,剩余 $j$ 元钱,剩余 $k$ 张优惠券时,最大的总美味度。 @@ -87,10 +85,6 @@ -### **Python3** - - - ```python class Solution: def maxTastiness( @@ -110,10 +104,6 @@ class Solution: return dfs(0, maxAmount, maxCoupons) ``` -### **Java** - - - ```java class Solution { private int[][][] f; @@ -149,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +163,6 @@ private: }; ``` -### **Go** - ```go func maxTastiness(price []int, tastiness []int, maxAmount int, maxCoupons int) int { n := len(price) @@ -209,16 +195,6 @@ func maxTastiness(price []int, tastiness []int, maxAmount int, maxCoupons int) i } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2431.Maximize Total Tastiness of Purchased Fruits/README_EN.md b/solution/2400-2499/2431.Maximize Total Tastiness of Purchased Fruits/README_EN.md index e5c765b4bc7b2..5e9646d967181 100644 --- a/solution/2400-2499/2431.Maximize Total Tastiness of Purchased Fruits/README_EN.md +++ b/solution/2400-2499/2431.Maximize Total Tastiness of Purchased Fruits/README_EN.md @@ -63,7 +63,7 @@ It can be proven that 28 is the maximum total tastiness that can be obtained. ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We design a function $dfs(i, j, k)$ to represent the maximum total tastiness starting from the $i$th fruit, with $j$ money left, and $k$ coupons left. @@ -79,8 +79,6 @@ The time complexity is $O(n \times maxAmount \times maxCoupons)$, where $n$ is t -### **Python3** - ```python class Solution: def maxTastiness( @@ -100,8 +98,6 @@ class Solution: return dfs(0, maxAmount, maxCoupons) ``` -### **Java** - ```java class Solution { private int[][][] f; @@ -137,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +157,6 @@ private: }; ``` -### **Go** - ```go func maxTastiness(price []int, tastiness []int, maxAmount int, maxCoupons int) int { n := len(price) @@ -197,16 +189,6 @@ func maxTastiness(price []int, tastiness []int, maxAmount int, maxCoupons int) i } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2432.The Employee That Worked on the Longest Task/README.md b/solution/2400-2499/2432.The Employee That Worked on the Longest Task/README.md index af98b530929a4..9bd342a8a0899 100644 --- a/solution/2400-2499/2432.The Employee That Worked on the Longest Task/README.md +++ b/solution/2400-2499/2432.The Employee That Worked on the Longest Task/README.md @@ -74,9 +74,7 @@ ## 解法 - - -**方法一:直接遍历** +### 方法一:直接遍历 我们用变量 $last$ 记录上一个任务的结束时间,用变量 $mx$ 记录最长的工作时间,用变量 $ans$ 记录工作时间最长且 $id$ 最小的员工。初始时,三个变量均为 $0$。 @@ -88,10 +86,6 @@ -### **Python3** - - - ```python class Solution: def hardestWorker(self, n: int, logs: List[List[int]]) -> int: @@ -104,10 +98,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int hardestWorker(int n, int[][] logs) { @@ -127,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +136,6 @@ public: }; ``` -### **Go** - ```go func hardestWorker(n int, logs [][]int) (ans int) { var mx, last int @@ -166,29 +152,6 @@ func hardestWorker(n int, logs [][]int) (ans int) { } ``` -### **C** - -```c -#define min(a, b) (((a) < (b)) ? (a) : (b)) - -int hardestWorker(int n, int** logs, int logsSize, int* logsColSize) { - int res = 0; - int max = 0; - int pre = 0; - for (int i = 0; i < logsSize; i++) { - int t = logs[i][1] - pre; - if (t > max || (t == max && res > logs[i][0])) { - res = logs[i][0]; - max = t; - } - pre = logs[i][1]; - } - return res; -} -``` - -### **TypeScript** - ```ts function hardestWorker(n: number, logs: number[][]): number { let [ans, mx, last] = [0, 0, 0]; @@ -204,8 +167,6 @@ function hardestWorker(n: number, logs: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn hardest_worker(n: i32, logs: Vec>) -> i32 { @@ -225,6 +186,31 @@ impl Solution { } ``` +```c +#define min(a, b) (((a) < (b)) ? (a) : (b)) + +int hardestWorker(int n, int** logs, int logsSize, int* logsColSize) { + int res = 0; + int max = 0; + int pre = 0; + for (int i = 0; i < logsSize; i++) { + int t = logs[i][1] - pre; + if (t > max || (t == max && res > logs[i][0])) { + res = logs[i][0]; + max = t; + } + pre = logs[i][1]; + } + return res; +} +``` + + + +### 方法二 + + + ```rust impl Solution { pub fn hardest_worker(n: i32, logs: Vec>) -> i32 { @@ -250,10 +236,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2432.The Employee That Worked on the Longest Task/README_EN.md b/solution/2400-2499/2432.The Employee That Worked on the Longest Task/README_EN.md index 333e40976371a..395967994cc94 100644 --- a/solution/2400-2499/2432.The Employee That Worked on the Longest Task/README_EN.md +++ b/solution/2400-2499/2432.The Employee That Worked on the Longest Task/README_EN.md @@ -70,7 +70,7 @@ The tasks with the longest time are tasks 0 and 1. The employees that worked on ## Solutions -**Solution 1: Direct Traversal** +### Solution 1: Direct Traversal We use a variable $last$ to record the end time of the last task, a variable $mx$ to record the longest working time, and a variable $ans$ to record the employee with the longest working time and the smallest $id$. Initially, all three variables are $0$. @@ -82,8 +82,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $logs$. The -### **Python3** - ```python class Solution: def hardestWorker(self, n: int, logs: List[List[int]]) -> int: @@ -96,8 +94,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int hardestWorker(int n, int[][] logs) { @@ -117,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +132,6 @@ public: }; ``` -### **Go** - ```go func hardestWorker(n int, logs [][]int) (ans int) { var mx, last int @@ -156,29 +148,6 @@ func hardestWorker(n int, logs [][]int) (ans int) { } ``` -### **C** - -```c -#define min(a, b) (((a) < (b)) ? (a) : (b)) - -int hardestWorker(int n, int** logs, int logsSize, int* logsColSize) { - int res = 0; - int max = 0; - int pre = 0; - for (int i = 0; i < logsSize; i++) { - int t = logs[i][1] - pre; - if (t > max || (t == max && res > logs[i][0])) { - res = logs[i][0]; - max = t; - } - pre = logs[i][1]; - } - return res; -} -``` - -### **TypeScript** - ```ts function hardestWorker(n: number, logs: number[][]): number { let [ans, mx, last] = [0, 0, 0]; @@ -194,8 +163,6 @@ function hardestWorker(n: number, logs: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn hardest_worker(n: i32, logs: Vec>) -> i32 { @@ -215,6 +182,31 @@ impl Solution { } ``` +```c +#define min(a, b) (((a) < (b)) ? (a) : (b)) + +int hardestWorker(int n, int** logs, int logsSize, int* logsColSize) { + int res = 0; + int max = 0; + int pre = 0; + for (int i = 0; i < logsSize; i++) { + int t = logs[i][1] - pre; + if (t > max || (t == max && res > logs[i][0])) { + res = logs[i][0]; + max = t; + } + pre = logs[i][1]; + } + return res; +} +``` + + + +### Solution 2 + + + ```rust impl Solution { pub fn hardest_worker(n: i32, logs: Vec>) -> i32 { @@ -240,10 +232,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2433.Find The Original Array of Prefix Xor/README.md b/solution/2400-2499/2433.Find The Original Array of Prefix Xor/README.md index 7b9dd52f13a93..1395df44e15b5 100644 --- a/solution/2400-2499/2433.Find The Original Array of Prefix Xor/README.md +++ b/solution/2400-2499/2433.Find The Original Array of Prefix Xor/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 根据题意,我们有式子一: @@ -76,20 +74,12 @@ $$ -### **Python3** - - - ```python class Solution: def findArray(self, pref: List[int]) -> List[int]: return [a ^ b for a, b in pairwise([0] + pref)] ``` -### **Java** - - - ```java class Solution { public int[] findArray(int[] pref) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func findArray(pref []int) []int { n := len(pref) @@ -133,25 +119,6 @@ func findArray(pref []int) []int { } ``` -### **C** - -```c -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -int* findArray(int* pref, int prefSize, int* returnSize) { - int* res = (int*) malloc(sizeof(int) * prefSize); - res[0] = pref[0]; - for (int i = 1; i < prefSize; i++) { - res[i] = pref[i - 1] ^ pref[i]; - } - *returnSize = prefSize; - return res; -} -``` - -### **TypeScript** - ```ts function findArray(pref: number[]): number[] { let ans = pref.slice(); @@ -162,8 +129,6 @@ function findArray(pref: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn find_array(pref: Vec) -> Vec { @@ -178,10 +143,21 @@ impl Solution { } ``` -### **...** - -``` - +```c +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int* findArray(int* pref, int prefSize, int* returnSize) { + int* res = (int*) malloc(sizeof(int) * prefSize); + res[0] = pref[0]; + for (int i = 1; i < prefSize; i++) { + res[i] = pref[i - 1] ^ pref[i]; + } + *returnSize = prefSize; + return res; +} ``` + + diff --git a/solution/2400-2499/2433.Find The Original Array of Prefix Xor/README_EN.md b/solution/2400-2499/2433.Find The Original Array of Prefix Xor/README_EN.md index 719f5ea0e5205..aba810f4a3577 100644 --- a/solution/2400-2499/2433.Find The Original Array of Prefix Xor/README_EN.md +++ b/solution/2400-2499/2433.Find The Original Array of Prefix Xor/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Bit Manipulation** +### Solution 1: Bit Manipulation According to the problem statement, we have equation one: @@ -72,16 +72,12 @@ The time complexity is $O(n)$, where $n$ is the length of the prefix XOR array. -### **Python3** - ```python class Solution: def findArray(self, pref: List[int]) -> List[int]: return [a ^ b for a, b in pairwise([0] + pref)] ``` -### **Java** - ```java class Solution { public int[] findArray(int[] pref) { @@ -96,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +106,6 @@ public: }; ``` -### **Go** - ```go func findArray(pref []int) []int { n := len(pref) @@ -125,25 +117,6 @@ func findArray(pref []int) []int { } ``` -### **C** - -```c -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -int* findArray(int* pref, int prefSize, int* returnSize) { - int* res = (int*) malloc(sizeof(int) * prefSize); - res[0] = pref[0]; - for (int i = 1; i < prefSize; i++) { - res[i] = pref[i - 1] ^ pref[i]; - } - *returnSize = prefSize; - return res; -} -``` - -### **TypeScript** - ```ts function findArray(pref: number[]): number[] { let ans = pref.slice(); @@ -154,8 +127,6 @@ function findArray(pref: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn find_array(pref: Vec) -> Vec { @@ -170,10 +141,21 @@ impl Solution { } ``` -### **...** - -``` - +```c +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int* findArray(int* pref, int prefSize, int* returnSize) { + int* res = (int*) malloc(sizeof(int) * prefSize); + res[0] = pref[0]; + for (int i = 1; i < prefSize; i++) { + res[i] = pref[i - 1] ^ pref[i]; + } + *returnSize = prefSize; + return res; +} ``` + + diff --git a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README.md b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README.md index a2bf2ca2bda46..addb07ca65dbb 100644 --- a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README.md +++ b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:贪心 + 栈** +### 方法一:贪心 + 栈 题目可以转化为,给定一个字符串序列,在借助一个辅助栈的情况下,将其转化为字典序最小的字符串序列。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def robotWithString(self, s: str) -> str: @@ -96,26 +90,6 @@ class Solution: return ''.join(ans) ``` -```python -class Solution: - def robotWithString(self, s: str) -> str: - n = len(s) - right = [chr(ord('z') + 1)] * (n + 1) - for i in range(n - 1, -1, -1): - right[i] = min(s[i], right[i + 1]) - ans = [] - stk = [] - for i, c in enumerate(s): - stk.append(c) - while stk and stk[-1] <= right[i + 1]: - ans.append(stk.pop()) - return ''.join(ans) -``` - -### **Java** - - - ```java class Solution { public String robotWithString(String s) { @@ -141,31 +115,6 @@ class Solution { } ``` -```java -class Solution { - public String robotWithString(String s) { - int n = s.length(); - int[] right = new int[n]; - right[n - 1] = n - 1; - for (int i = n - 2; i >= 0; --i) { - right[i] = s.charAt(i) < s.charAt(right[i + 1]) ? i : right[i + 1]; - } - StringBuilder ans = new StringBuilder(); - Deque stk = new ArrayDeque<>(); - for (int i = 0; i < n; ++i) { - stk.push(s.charAt(i)); - while ( - !stk.isEmpty() && (stk.peek() <= (i > n - 2 ? 'z' + 1 : s.charAt(right[i + 1])))) { - ans.append(stk.pop()); - } - } - return ans.toString(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -189,31 +138,6 @@ public: }; ``` -```cpp -class Solution { -public: - string robotWithString(string s) { - int n = s.size(); - vector right(n, n - 1); - for (int i = n - 2; i >= 0; --i) { - right[i] = s[i] < s[right[i + 1]] ? i : right[i + 1]; - } - string ans; - string stk; - for (int i = 0; i < n; ++i) { - stk += s[i]; - while (!stk.empty() && (stk.back() <= (i > n - 2 ? 'z' + 1 : s[right[i + 1]]))) { - ans += stk.back(); - stk.pop_back(); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func robotWithString(s string) string { cnt := make([]int, 26) @@ -238,8 +162,6 @@ func robotWithString(s string) string { } ``` -### **TypeScript** - ```ts function robotWithString(s: string): string { let cnt = new Array(128).fill(0); @@ -261,10 +183,74 @@ function robotWithString(s: string): string { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def robotWithString(self, s: str) -> str: + n = len(s) + right = [chr(ord('z') + 1)] * (n + 1) + for i in range(n - 1, -1, -1): + right[i] = min(s[i], right[i + 1]) + ans = [] + stk = [] + for i, c in enumerate(s): + stk.append(c) + while stk and stk[-1] <= right[i + 1]: + ans.append(stk.pop()) + return ''.join(ans) +``` + +```java +class Solution { + public String robotWithString(String s) { + int n = s.length(); + int[] right = new int[n]; + right[n - 1] = n - 1; + for (int i = n - 2; i >= 0; --i) { + right[i] = s.charAt(i) < s.charAt(right[i + 1]) ? i : right[i + 1]; + } + StringBuilder ans = new StringBuilder(); + Deque stk = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + stk.push(s.charAt(i)); + while ( + !stk.isEmpty() && (stk.peek() <= (i > n - 2 ? 'z' + 1 : s.charAt(right[i + 1])))) { + ans.append(stk.pop()); + } + } + return ans.toString(); + } +} ``` +```cpp +class Solution { +public: + string robotWithString(string s) { + int n = s.size(); + vector right(n, n - 1); + for (int i = n - 2; i >= 0; --i) { + right[i] = s[i] < s[right[i + 1]] ? i : right[i + 1]; + } + string ans; + string stk; + for (int i = 0; i < n; ++i) { + stk += s[i]; + while (!stk.empty() && (stk.back() <= (i > n - 2 ? 'z' + 1 : s[right[i + 1]]))) { + ans += stk.back(); + stk.pop_back(); + } + } + return ans; + } +}; ``` + + diff --git a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README_EN.md b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README_EN.md index ce987506c168a..153796b570872 100644 --- a/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README_EN.md +++ b/solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README_EN.md @@ -58,7 +58,7 @@ Perform second operation four times p="addb", s="", t=" ## Solutions -**Solution 1: Greedy + Stack** +### Solution 1: Greedy + Stack The problem can be transformed into, given a string sequence, convert it into the lexicographically smallest string sequence with the help of an auxiliary stack. @@ -72,8 +72,6 @@ The time complexity is $O(n+C)$, and the space complexity is $O(n)$. Here, $n$ i -### **Python3** - ```python class Solution: def robotWithString(self, s: str) -> str: @@ -91,24 +89,6 @@ class Solution: return ''.join(ans) ``` -```python -class Solution: - def robotWithString(self, s: str) -> str: - n = len(s) - right = [chr(ord('z') + 1)] * (n + 1) - for i in range(n - 1, -1, -1): - right[i] = min(s[i], right[i + 1]) - ans = [] - stk = [] - for i, c in enumerate(s): - stk.append(c) - while stk and stk[-1] <= right[i + 1]: - ans.append(stk.pop()) - return ''.join(ans) -``` - -### **Java** - ```java class Solution { public String robotWithString(String s) { @@ -134,31 +114,6 @@ class Solution { } ``` -```java -class Solution { - public String robotWithString(String s) { - int n = s.length(); - int[] right = new int[n]; - right[n - 1] = n - 1; - for (int i = n - 2; i >= 0; --i) { - right[i] = s.charAt(i) < s.charAt(right[i + 1]) ? i : right[i + 1]; - } - StringBuilder ans = new StringBuilder(); - Deque stk = new ArrayDeque<>(); - for (int i = 0; i < n; ++i) { - stk.push(s.charAt(i)); - while ( - !stk.isEmpty() && (stk.peek() <= (i > n - 2 ? 'z' + 1 : s.charAt(right[i + 1])))) { - ans.append(stk.pop()); - } - } - return ans.toString(); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -182,31 +137,6 @@ public: }; ``` -```cpp -class Solution { -public: - string robotWithString(string s) { - int n = s.size(); - vector right(n, n - 1); - for (int i = n - 2; i >= 0; --i) { - right[i] = s[i] < s[right[i + 1]] ? i : right[i + 1]; - } - string ans; - string stk; - for (int i = 0; i < n; ++i) { - stk += s[i]; - while (!stk.empty() && (stk.back() <= (i > n - 2 ? 'z' + 1 : s[right[i + 1]]))) { - ans += stk.back(); - stk.pop_back(); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func robotWithString(s string) string { cnt := make([]int, 26) @@ -231,8 +161,6 @@ func robotWithString(s string) string { } ``` -### **TypeScript** - ```ts function robotWithString(s: string): string { let cnt = new Array(128).fill(0); @@ -254,10 +182,74 @@ function robotWithString(s: string): string { } ``` -### **...** + +### Solution 2 + + + +```python +class Solution: + def robotWithString(self, s: str) -> str: + n = len(s) + right = [chr(ord('z') + 1)] * (n + 1) + for i in range(n - 1, -1, -1): + right[i] = min(s[i], right[i + 1]) + ans = [] + stk = [] + for i, c in enumerate(s): + stk.append(c) + while stk and stk[-1] <= right[i + 1]: + ans.append(stk.pop()) + return ''.join(ans) ``` +```java +class Solution { + public String robotWithString(String s) { + int n = s.length(); + int[] right = new int[n]; + right[n - 1] = n - 1; + for (int i = n - 2; i >= 0; --i) { + right[i] = s.charAt(i) < s.charAt(right[i + 1]) ? i : right[i + 1]; + } + StringBuilder ans = new StringBuilder(); + Deque stk = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + stk.push(s.charAt(i)); + while ( + !stk.isEmpty() && (stk.peek() <= (i > n - 2 ? 'z' + 1 : s.charAt(right[i + 1])))) { + ans.append(stk.pop()); + } + } + return ans.toString(); + } +} +``` + +```cpp +class Solution { +public: + string robotWithString(string s) { + int n = s.size(); + vector right(n, n - 1); + for (int i = n - 2; i >= 0; --i) { + right[i] = s[i] < s[right[i + 1]] ? i : right[i + 1]; + } + string ans; + string stk; + for (int i = 0; i < n; ++i) { + stk += s[i]; + while (!stk.empty() && (stk.back() <= (i > n - 2 ? 'z' + 1 : s[right[i + 1]]))) { + ans += stk.back(); + stk.pop_back(); + } + } + return ans; + } +}; ``` + + diff --git a/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/README.md b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/README.md index 8143539811afe..d37f6155d787b 100644 --- a/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/README.md +++ b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 设计函数 `dfs(i, j, s)` 表示从 `(i, j)` 出发,初始路径和模 $k$ 的结果为 $s$ 的路径数目。 @@ -68,28 +66,8 @@ $$ 时间复杂度 $O(m \times n \times k)$,空间复杂度 $O(m \times n \times k)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数,而 $k$ 为给定的整数。 -**方法二:动态规划** - -我们也可以使用动态规划求解。 - -定义状态 $dp[i][j][s]$ 表示从起点 $(0, 0)$ 出发,到达位置 $(i, j)$,路径和模 $k$ 等于 $s$ 的路径数目。 - -初始值 $dp[0][0][grid[0][0] \bmod k] = 1$,答案为 $dp[m - 1][n - 1][0]$。 - -我们可以得到状态转移方程: - -$$ -dp[i][j][s] = dp[i - 1][j][(s - grid[i][j])\bmod k] + dp[i][j - 1][(s - grid[i][j])\bmod k] -$$ - -时间复杂度 $O(m \times n \times k)$,空间复杂度 $O(m \times n \times k)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数,而 $k$ 为给定的整数。 - -### **Python3** - - - ```python class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: @@ -110,29 +88,6 @@ class Solution: return ans ``` -```python -class Solution: - def numberOfPaths(self, grid: List[List[int]], k: int) -> int: - m, n = len(grid), len(grid[0]) - dp = [[[0] * k for _ in range(n)] for _ in range(m)] - dp[0][0][grid[0][0] % k] = 1 - mod = 10**9 + 7 - for i in range(m): - for j in range(n): - for s in range(k): - t = ((s - grid[i][j] % k) + k) % k - if i: - dp[i][j][s] += dp[i - 1][j][t] - if j: - dp[i][j][s] += dp[i][j - 1][t] - dp[i][j][s] %= mod - return dp[-1][-1][0] -``` - -### **Java** - - - ```java class Solution { private int m; @@ -175,35 +130,6 @@ class Solution { } ``` -```java -class Solution { - private static final int MOD = (int) 1e9 + 7; - - public int numberOfPaths(int[][] grid, int k) { - int m = grid.length, n = grid[0].length; - int[][][] dp = new int[m][n][k]; - dp[0][0][grid[0][0] % k] = 1; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int s = 0; s < k; ++s) { - int t = ((s - grid[i][j] % k) + k) % k; - if (i > 0) { - dp[i][j][s] += dp[i - 1][j][t]; - } - if (j > 0) { - dp[i][j][s] += dp[i][j - 1][t]; - } - dp[i][j][s] %= MOD; - } - } - } - return dp[m - 1][n - 1][0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -227,32 +153,6 @@ public: }; ``` -```cpp -class Solution { -public: - const int mod = 1e9 + 7; - - int numberOfPaths(vector>& grid, int k) { - int m = grid.size(), n = grid[0].size(); - vector>> dp(m, vector>(n, vector(k))); - dp[0][0][grid[0][0] % k] = 1; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int s = 0; s < k; ++s) { - int t = ((s - grid[i][j] % k) + k) % k; - if (i) dp[i][j][s] += dp[i - 1][j][t]; - if (j) dp[i][j][s] += dp[i][j - 1][t]; - dp[i][j][s] %= mod; - } - } - } - return dp[m - 1][n - 1][0]; - } -}; -``` - -### **Go** - ```go func numberOfPaths(grid [][]int, k int) int { m, n := len(grid), len(grid[0]) @@ -291,6 +191,118 @@ func numberOfPaths(grid [][]int, k int) int { } ``` +```ts +function numberOfPaths(grid: number[][], k: number): number { + const MOD = 10 ** 9 + 7; + const m = grid.length, + n = grid[0].length; + let ans = Array.from({ length: m + 1 }, () => + Array.from({ length: n + 1 }, () => new Array(k).fill(0)), + ); + ans[0][1][0] = 1; + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + for (let v = 0; v < k; v++) { + let key = (grid[i][j] + v) % k; + ans[i + 1][j + 1][key] = + (ans[i][j + 1][v] + ans[i + 1][j][v] + ans[i + 1][j + 1][key]) % MOD; + } + } + } + return ans[m][n][0]; +} +``` + + + +### 方法二:动态规划 + +我们也可以使用动态规划求解。 + +定义状态 $dp[i][j][s]$ 表示从起点 $(0, 0)$ 出发,到达位置 $(i, j)$,路径和模 $k$ 等于 $s$ 的路径数目。 + +初始值 $dp[0][0][grid[0][0] \bmod k] = 1$,答案为 $dp[m - 1][n - 1][0]$。 + +我们可以得到状态转移方程: + +$$ +dp[i][j][s] = dp[i - 1][j][(s - grid[i][j])\bmod k] + dp[i][j - 1][(s - grid[i][j])\bmod k] +$$ + +时间复杂度 $O(m \times n \times k)$,空间复杂度 $O(m \times n \times k)$。其中 $m$ 和 $n$ 分别为矩阵的行数和列数,而 $k$ 为给定的整数。 + + + +```python +class Solution: + def numberOfPaths(self, grid: List[List[int]], k: int) -> int: + m, n = len(grid), len(grid[0]) + dp = [[[0] * k for _ in range(n)] for _ in range(m)] + dp[0][0][grid[0][0] % k] = 1 + mod = 10**9 + 7 + for i in range(m): + for j in range(n): + for s in range(k): + t = ((s - grid[i][j] % k) + k) % k + if i: + dp[i][j][s] += dp[i - 1][j][t] + if j: + dp[i][j][s] += dp[i][j - 1][t] + dp[i][j][s] %= mod + return dp[-1][-1][0] +``` + +```java +class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int numberOfPaths(int[][] grid, int k) { + int m = grid.length, n = grid[0].length; + int[][][] dp = new int[m][n][k]; + dp[0][0][grid[0][0] % k] = 1; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int s = 0; s < k; ++s) { + int t = ((s - grid[i][j] % k) + k) % k; + if (i > 0) { + dp[i][j][s] += dp[i - 1][j][t]; + } + if (j > 0) { + dp[i][j][s] += dp[i][j - 1][t]; + } + dp[i][j][s] %= MOD; + } + } + } + return dp[m - 1][n - 1][0]; + } +} +``` + +```cpp +class Solution { +public: + const int mod = 1e9 + 7; + + int numberOfPaths(vector>& grid, int k) { + int m = grid.size(), n = grid[0].size(); + vector>> dp(m, vector>(n, vector(k))); + dp[0][0][grid[0][0] % k] = 1; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int s = 0; s < k; ++s) { + int t = ((s - grid[i][j] % k) + k) % k; + if (i) dp[i][j][s] += dp[i - 1][j][t]; + if (j) dp[i][j][s] += dp[i][j - 1][t]; + dp[i][j][s] %= mod; + } + } + } + return dp[m - 1][n - 1][0]; + } +}; +``` + ```go func numberOfPaths(grid [][]int, k int) int { m, n := len(grid), len(grid[0]) @@ -321,34 +333,6 @@ func numberOfPaths(grid [][]int, k int) int { } ``` -### **TypeScript** - -```ts -function numberOfPaths(grid: number[][], k: number): number { - const MOD = 10 ** 9 + 7; - const m = grid.length, - n = grid[0].length; - let ans = Array.from({ length: m + 1 }, () => - Array.from({ length: n + 1 }, () => new Array(k).fill(0)), - ); - ans[0][1][0] = 1; - for (let i = 0; i < m; i++) { - for (let j = 0; j < n; j++) { - for (let v = 0; v < k; v++) { - let key = (grid[i][j] + v) % k; - ans[i + 1][j + 1][key] = - (ans[i][j + 1][v] + ans[i + 1][j][v] + ans[i + 1][j + 1][key]) % MOD; - } - } - } - return ans[m][n][0]; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/README_EN.md b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/README_EN.md index 53c6304b631b4..c826965fa9afd 100644 --- a/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/README_EN.md +++ b/solution/2400-2499/2435.Paths in Matrix Whose Sum Is Divisible by K/README_EN.md @@ -49,7 +49,7 @@ The second path highlighted in blue has a sum of 5 + 3 + 0 + 5 + 2 = 15 which is ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We design a function `dfs(i, j, s)` to represent the number of paths starting from `(i, j)` with an initial path sum modulo $k$ equal to $s$. @@ -63,26 +63,8 @@ The answer is `dfs(0, 0, 0)`. We can use memoization search. The time complexity is $O(m \times n \times k)$, and the space complexity is $O(m \times n \times k)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, and $k$ is the given integer. -**Solution 2: Dynamic Programming** - -We can also use dynamic programming to solve this problem. - -Define the state $dp[i][j][s]$ to represent the number of paths from the starting point $(0, 0)$ to the position $(i, j)$, where the path sum modulo $k$ equals $s$. - -The initial value is $dp[0][0][grid[0][0] \bmod k] = 1$, and the answer is $dp[m - 1][n - 1][0]$. - -We can get the state transition equation: - -$$ -dp[i][j][s] = dp[i - 1][j][(s - grid[i][j])\bmod k] + dp[i][j - 1][(s - grid[i][j])\bmod k] -$$ - -The time complexity is $O(m \times n \times k)$, and the space complexity is $O(m \times n \times k)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, and $k$ is the given integer. - -### **Python3** - ```python class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: @@ -103,27 +85,6 @@ class Solution: return ans ``` -```python -class Solution: - def numberOfPaths(self, grid: List[List[int]], k: int) -> int: - m, n = len(grid), len(grid[0]) - dp = [[[0] * k for _ in range(n)] for _ in range(m)] - dp[0][0][grid[0][0] % k] = 1 - mod = 10**9 + 7 - for i in range(m): - for j in range(n): - for s in range(k): - t = ((s - grid[i][j] % k) + k) % k - if i: - dp[i][j][s] += dp[i - 1][j][t] - if j: - dp[i][j][s] += dp[i][j - 1][t] - dp[i][j][s] %= mod - return dp[-1][-1][0] -``` - -### **Java** - ```java class Solution { private int m; @@ -166,35 +127,6 @@ class Solution { } ``` -```java -class Solution { - private static final int MOD = (int) 1e9 + 7; - - public int numberOfPaths(int[][] grid, int k) { - int m = grid.length, n = grid[0].length; - int[][][] dp = new int[m][n][k]; - dp[0][0][grid[0][0] % k] = 1; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int s = 0; s < k; ++s) { - int t = ((s - grid[i][j] % k) + k) % k; - if (i > 0) { - dp[i][j][s] += dp[i - 1][j][t]; - } - if (j > 0) { - dp[i][j][s] += dp[i][j - 1][t]; - } - dp[i][j][s] %= MOD; - } - } - } - return dp[m - 1][n - 1][0]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -218,32 +150,6 @@ public: }; ``` -```cpp -class Solution { -public: - const int mod = 1e9 + 7; - - int numberOfPaths(vector>& grid, int k) { - int m = grid.size(), n = grid[0].size(); - vector>> dp(m, vector>(n, vector(k))); - dp[0][0][grid[0][0] % k] = 1; - for (int i = 0; i < m; ++i) { - for (int j = 0; j < n; ++j) { - for (int s = 0; s < k; ++s) { - int t = ((s - grid[i][j] % k) + k) % k; - if (i) dp[i][j][s] += dp[i - 1][j][t]; - if (j) dp[i][j][s] += dp[i][j - 1][t]; - dp[i][j][s] %= mod; - } - } - } - return dp[m - 1][n - 1][0]; - } -}; -``` - -### **Go** - ```go func numberOfPaths(grid [][]int, k int) int { m, n := len(grid), len(grid[0]) @@ -282,6 +188,118 @@ func numberOfPaths(grid [][]int, k int) int { } ``` +```ts +function numberOfPaths(grid: number[][], k: number): number { + const MOD = 10 ** 9 + 7; + const m = grid.length, + n = grid[0].length; + let ans = Array.from({ length: m + 1 }, () => + Array.from({ length: n + 1 }, () => new Array(k).fill(0)), + ); + ans[0][1][0] = 1; + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + for (let v = 0; v < k; v++) { + let key = (grid[i][j] + v) % k; + ans[i + 1][j + 1][key] = + (ans[i][j + 1][v] + ans[i + 1][j][v] + ans[i + 1][j + 1][key]) % MOD; + } + } + } + return ans[m][n][0]; +} +``` + + + +### Solution 2: Dynamic Programming + +We can also use dynamic programming to solve this problem. + +Define the state $dp[i][j][s]$ to represent the number of paths from the starting point $(0, 0)$ to the position $(i, j)$, where the path sum modulo $k$ equals $s$. + +The initial value is $dp[0][0][grid[0][0] \bmod k] = 1$, and the answer is $dp[m - 1][n - 1][0]$. + +We can get the state transition equation: + +$$ +dp[i][j][s] = dp[i - 1][j][(s - grid[i][j])\bmod k] + dp[i][j - 1][(s - grid[i][j])\bmod k] +$$ + +The time complexity is $O(m \times n \times k)$, and the space complexity is $O(m \times n \times k)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, and $k$ is the given integer. + + + +```python +class Solution: + def numberOfPaths(self, grid: List[List[int]], k: int) -> int: + m, n = len(grid), len(grid[0]) + dp = [[[0] * k for _ in range(n)] for _ in range(m)] + dp[0][0][grid[0][0] % k] = 1 + mod = 10**9 + 7 + for i in range(m): + for j in range(n): + for s in range(k): + t = ((s - grid[i][j] % k) + k) % k + if i: + dp[i][j][s] += dp[i - 1][j][t] + if j: + dp[i][j][s] += dp[i][j - 1][t] + dp[i][j][s] %= mod + return dp[-1][-1][0] +``` + +```java +class Solution { + private static final int MOD = (int) 1e9 + 7; + + public int numberOfPaths(int[][] grid, int k) { + int m = grid.length, n = grid[0].length; + int[][][] dp = new int[m][n][k]; + dp[0][0][grid[0][0] % k] = 1; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int s = 0; s < k; ++s) { + int t = ((s - grid[i][j] % k) + k) % k; + if (i > 0) { + dp[i][j][s] += dp[i - 1][j][t]; + } + if (j > 0) { + dp[i][j][s] += dp[i][j - 1][t]; + } + dp[i][j][s] %= MOD; + } + } + } + return dp[m - 1][n - 1][0]; + } +} +``` + +```cpp +class Solution { +public: + const int mod = 1e9 + 7; + + int numberOfPaths(vector>& grid, int k) { + int m = grid.size(), n = grid[0].size(); + vector>> dp(m, vector>(n, vector(k))); + dp[0][0][grid[0][0] % k] = 1; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int s = 0; s < k; ++s) { + int t = ((s - grid[i][j] % k) + k) % k; + if (i) dp[i][j][s] += dp[i - 1][j][t]; + if (j) dp[i][j][s] += dp[i][j - 1][t]; + dp[i][j][s] %= mod; + } + } + } + return dp[m - 1][n - 1][0]; + } +}; +``` + ```go func numberOfPaths(grid [][]int, k int) int { m, n := len(grid), len(grid[0]) @@ -312,34 +330,6 @@ func numberOfPaths(grid [][]int, k int) int { } ``` -### **TypeScript** - -```ts -function numberOfPaths(grid: number[][], k: number): number { - const MOD = 10 ** 9 + 7; - const m = grid.length, - n = grid[0].length; - let ans = Array.from({ length: m + 1 }, () => - Array.from({ length: n + 1 }, () => new Array(k).fill(0)), - ); - ans[0][1][0] = 1; - for (let i = 0; i < m; i++) { - for (let j = 0; j < n; j++) { - for (let v = 0; v < k; v++) { - let key = (grid[i][j] + v) % k; - ans[i + 1][j + 1][key] = - (ans[i][j + 1][v] + ans[i + 1][j][v] + ans[i + 1][j + 1][key]) % MOD; - } - } - } - return ans[m][n][0]; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2436.Minimum Split Into Subarrays With GCD Greater Than One/README.md b/solution/2400-2499/2436.Minimum Split Into Subarrays With GCD Greater Than One/README.md index 2e3b148a5c6cc..a151aab7d70e2 100644 --- a/solution/2400-2499/2436.Minimum Split Into Subarrays With GCD Greater Than One/README.md +++ b/solution/2400-2499/2436.Minimum Split Into Subarrays With GCD Greater Than One/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:贪心 + 数学** +### 方法一:贪心 + 数学 对于数组中的每个元素,如果它与前面的元素的最大公约数为 $1$,那么它需要作为一个新的子数组的第一个元素。否则,它可以与前面的元素放在同一个子数组中。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def minimumSplits(self, nums: List[int]) -> int: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumSplits(int[] nums) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func minimumSplits(nums []int) int { ans, g := 1, 0 @@ -154,8 +140,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function minimumSplits(nums: number[]): number { let ans = 1; @@ -175,10 +159,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2436.Minimum Split Into Subarrays With GCD Greater Than One/README_EN.md b/solution/2400-2499/2436.Minimum Split Into Subarrays With GCD Greater Than One/README_EN.md index a14cc8ce330f3..8eeb3ef436dab 100644 --- a/solution/2400-2499/2436.Minimum Split Into Subarrays With GCD Greater Than One/README_EN.md +++ b/solution/2400-2499/2436.Minimum Split Into Subarrays With GCD Greater Than One/README_EN.md @@ -52,7 +52,7 @@ It can be shown that splitting the array into one subarray will make the GCD = 1 ## Solutions -**Solution 1: Greedy + Mathematics** +### Solution 1: Greedy + Mathematics For each element in the array, if its greatest common divisor (gcd) with the previous element is $1$, then it needs to be the first element of a new subarray. Otherwise, it can be placed in the same subarray with the previous elements. @@ -64,8 +64,6 @@ The time complexity is $O(n \times \log m)$, where $n$ and $m$ are the length of -### **Python3** - ```python class Solution: def minimumSplits(self, nums: List[int]) -> int: @@ -78,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumSplits(int[] nums) { @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +113,6 @@ public: }; ``` -### **Go** - ```go func minimumSplits(nums []int) int { ans, g := 1, 0 @@ -142,8 +134,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function minimumSplits(nums: number[]): number { let ans = 1; @@ -163,10 +153,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2437.Number of Valid Clock Times/README.md b/solution/2400-2499/2437.Number of Valid Clock Times/README.md index 8dddbe8aabf4c..239f0a6b9537b 100644 --- a/solution/2400-2499/2437.Number of Valid Clock Times/README.md +++ b/solution/2400-2499/2437.Number of Valid Clock Times/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以直接枚举从 $00:00$ 到 $23:59$ 的所有时间,然后判断每个时间是否有效,是则答案加一。 @@ -58,18 +56,8 @@ 时间复杂度 $O(24 \times 60)$,空间复杂度 $O(1)$。 -**方法二:枚举优化** - -我们可以分开枚举小时和分钟,统计有多少个小时和分钟满足条件,然后将二者相乘即可。 - -时间复杂度 $O(24 + 60)$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def countTime(self, time: str) -> int: @@ -81,24 +69,6 @@ class Solution: ) ``` -```python -class Solution: - def countTime(self, time: str) -> int: - def f(s: str, m: int) -> int: - cnt = 0 - for i in range(m): - a = s[0] == '?' or (int(s[0]) == i // 10) - b = s[1] == '?' or (int(s[1]) == i % 10) - cnt += a and b - return cnt - - return f(time[:2], 24) * f(time[3:], 60) -``` - -### **Java** - - - ```java class Solution { public int countTime(String time) { @@ -121,26 +91,6 @@ class Solution { } ``` -```java -class Solution { - public int countTime(String time) { - return f(time.substring(0, 2), 24) * f(time.substring(3), 60); - } - - private int f(String s, int m) { - int cnt = 0; - for (int i = 0; i < m; ++i) { - boolean a = s.charAt(0) == '?' || s.charAt(0) - '0' == i / 10; - boolean b = s.charAt(1) == '?' || s.charAt(1) - '0' == i % 10; - cnt += a && b ? 1 : 0; - } - return cnt; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -165,26 +115,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countTime(string time) { - auto f = [](string s, int m) { - int cnt = 0; - for (int i = 0; i < m; ++i) { - bool a = s[0] == '?' || s[0] - '0' == i / 10; - bool b = s[1] == '?' || s[1] - '0' == i % 10; - cnt += a && b; - } - return cnt; - }; - return f(time.substr(0, 2), 24) * f(time.substr(3, 2), 60); - } -}; -``` - -### **Go** - ```go func countTime(time string) int { ans := 0 @@ -205,24 +135,6 @@ func countTime(time string) int { } ``` -```go -func countTime(time string) int { - f := func(s string, m int) (cnt int) { - for i := 0; i < m; i++ { - a := s[0] == '?' || int(s[0]-'0') == i/10 - b := s[1] == '?' || int(s[1]-'0') == i%10 - if a && b { - cnt++ - } - } - return - } - return f(time[:2], 24) * f(time[3:], 60) -} -``` - -### **TypeScript** - ```ts function countTime(time: string): number { let ans = 0; @@ -243,25 +155,6 @@ function countTime(time: string): number { } ``` -```ts -function countTime(time: string): number { - const f = (s: string, m: number): number => { - let cnt = 0; - for (let i = 0; i < m; ++i) { - const a = s[0] === '?' || s[0] === Math.floor(i / 10).toString(); - const b = s[1] === '?' || s[1] === (i % 10).toString(); - if (a && b) { - ++cnt; - } - } - return cnt; - }; - return f(time.slice(0, 2), 24) * f(time.slice(3), 60); -} -``` - -### **Rust** - ```rust impl Solution { pub fn count_time(time: String) -> i32 { @@ -289,6 +182,99 @@ impl Solution { } ``` + + +### 方法二:枚举优化 + +我们可以分开枚举小时和分钟,统计有多少个小时和分钟满足条件,然后将二者相乘即可。 + +时间复杂度 $O(24 + 60)$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def countTime(self, time: str) -> int: + def f(s: str, m: int) -> int: + cnt = 0 + for i in range(m): + a = s[0] == '?' or (int(s[0]) == i // 10) + b = s[1] == '?' or (int(s[1]) == i % 10) + cnt += a and b + return cnt + + return f(time[:2], 24) * f(time[3:], 60) +``` + +```java +class Solution { + public int countTime(String time) { + return f(time.substring(0, 2), 24) * f(time.substring(3), 60); + } + + private int f(String s, int m) { + int cnt = 0; + for (int i = 0; i < m; ++i) { + boolean a = s.charAt(0) == '?' || s.charAt(0) - '0' == i / 10; + boolean b = s.charAt(1) == '?' || s.charAt(1) - '0' == i % 10; + cnt += a && b ? 1 : 0; + } + return cnt; + } +} +``` + +```cpp +class Solution { +public: + int countTime(string time) { + auto f = [](string s, int m) { + int cnt = 0; + for (int i = 0; i < m; ++i) { + bool a = s[0] == '?' || s[0] - '0' == i / 10; + bool b = s[1] == '?' || s[1] - '0' == i % 10; + cnt += a && b; + } + return cnt; + }; + return f(time.substr(0, 2), 24) * f(time.substr(3, 2), 60); + } +}; +``` + +```go +func countTime(time string) int { + f := func(s string, m int) (cnt int) { + for i := 0; i < m; i++ { + a := s[0] == '?' || int(s[0]-'0') == i/10 + b := s[1] == '?' || int(s[1]-'0') == i%10 + if a && b { + cnt++ + } + } + return + } + return f(time[:2], 24) * f(time[3:], 60) +} +``` + +```ts +function countTime(time: string): number { + const f = (s: string, m: number): number => { + let cnt = 0; + for (let i = 0; i < m; ++i) { + const a = s[0] === '?' || s[0] === Math.floor(i / 10).toString(); + const b = s[1] === '?' || s[1] === (i % 10).toString(); + if (a && b) { + ++cnt; + } + } + return cnt; + }; + return f(time.slice(0, 2), 24) * f(time.slice(3), 60); +} +``` + ```rust impl Solution { pub fn count_time(time: String) -> i32 { @@ -315,10 +301,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2437.Number of Valid Clock Times/README_EN.md b/solution/2400-2499/2437.Number of Valid Clock Times/README_EN.md index a5c2bf15d03ed..438668bad541b 100644 --- a/solution/2400-2499/2437.Number of Valid Clock Times/README_EN.md +++ b/solution/2400-2499/2437.Number of Valid Clock Times/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We can directly enumerate all times from $00:00$ to $23:59$, then judge whether each time is valid, if so, increment the answer. @@ -55,16 +55,8 @@ After the enumeration ends, return the answer. The time complexity is $O(24 \times 60)$, and the space complexity is $O(1)$. -**Solution 2: Optimized Enumeration** - -We can separately enumerate hours and minutes, count how many hours and minutes meet the condition, and then multiply them together. - -The time complexity is $O(24 + 60)$, and the space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def countTime(self, time: str) -> int: @@ -76,22 +68,6 @@ class Solution: ) ``` -```python -class Solution: - def countTime(self, time: str) -> int: - def f(s: str, m: int) -> int: - cnt = 0 - for i in range(m): - a = s[0] == '?' or (int(s[0]) == i // 10) - b = s[1] == '?' or (int(s[1]) == i % 10) - cnt += a and b - return cnt - - return f(time[:2], 24) * f(time[3:], 60) -``` - -### **Java** - ```java class Solution { public int countTime(String time) { @@ -114,26 +90,6 @@ class Solution { } ``` -```java -class Solution { - public int countTime(String time) { - return f(time.substring(0, 2), 24) * f(time.substring(3), 60); - } - - private int f(String s, int m) { - int cnt = 0; - for (int i = 0; i < m; ++i) { - boolean a = s.charAt(0) == '?' || s.charAt(0) - '0' == i / 10; - boolean b = s.charAt(1) == '?' || s.charAt(1) - '0' == i % 10; - cnt += a && b ? 1 : 0; - } - return cnt; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -158,26 +114,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countTime(string time) { - auto f = [](string s, int m) { - int cnt = 0; - for (int i = 0; i < m; ++i) { - bool a = s[0] == '?' || s[0] - '0' == i / 10; - bool b = s[1] == '?' || s[1] - '0' == i % 10; - cnt += a && b; - } - return cnt; - }; - return f(time.substr(0, 2), 24) * f(time.substr(3, 2), 60); - } -}; -``` - -### **Go** - ```go func countTime(time string) int { ans := 0 @@ -198,24 +134,6 @@ func countTime(time string) int { } ``` -```go -func countTime(time string) int { - f := func(s string, m int) (cnt int) { - for i := 0; i < m; i++ { - a := s[0] == '?' || int(s[0]-'0') == i/10 - b := s[1] == '?' || int(s[1]-'0') == i%10 - if a && b { - cnt++ - } - } - return - } - return f(time[:2], 24) * f(time[3:], 60) -} -``` - -### **TypeScript** - ```ts function countTime(time: string): number { let ans = 0; @@ -236,25 +154,6 @@ function countTime(time: string): number { } ``` -```ts -function countTime(time: string): number { - const f = (s: string, m: number): number => { - let cnt = 0; - for (let i = 0; i < m; ++i) { - const a = s[0] === '?' || s[0] === Math.floor(i / 10).toString(); - const b = s[1] === '?' || s[1] === (i % 10).toString(); - if (a && b) { - ++cnt; - } - } - return cnt; - }; - return f(time.slice(0, 2), 24) * f(time.slice(3), 60); -} -``` - -### **Rust** - ```rust impl Solution { pub fn count_time(time: String) -> i32 { @@ -282,6 +181,99 @@ impl Solution { } ``` + + +### Solution 2: Optimized Enumeration + +We can separately enumerate hours and minutes, count how many hours and minutes meet the condition, and then multiply them together. + +The time complexity is $O(24 + 60)$, and the space complexity is $O(1)$. + + + +```python +class Solution: + def countTime(self, time: str) -> int: + def f(s: str, m: int) -> int: + cnt = 0 + for i in range(m): + a = s[0] == '?' or (int(s[0]) == i // 10) + b = s[1] == '?' or (int(s[1]) == i % 10) + cnt += a and b + return cnt + + return f(time[:2], 24) * f(time[3:], 60) +``` + +```java +class Solution { + public int countTime(String time) { + return f(time.substring(0, 2), 24) * f(time.substring(3), 60); + } + + private int f(String s, int m) { + int cnt = 0; + for (int i = 0; i < m; ++i) { + boolean a = s.charAt(0) == '?' || s.charAt(0) - '0' == i / 10; + boolean b = s.charAt(1) == '?' || s.charAt(1) - '0' == i % 10; + cnt += a && b ? 1 : 0; + } + return cnt; + } +} +``` + +```cpp +class Solution { +public: + int countTime(string time) { + auto f = [](string s, int m) { + int cnt = 0; + for (int i = 0; i < m; ++i) { + bool a = s[0] == '?' || s[0] - '0' == i / 10; + bool b = s[1] == '?' || s[1] - '0' == i % 10; + cnt += a && b; + } + return cnt; + }; + return f(time.substr(0, 2), 24) * f(time.substr(3, 2), 60); + } +}; +``` + +```go +func countTime(time string) int { + f := func(s string, m int) (cnt int) { + for i := 0; i < m; i++ { + a := s[0] == '?' || int(s[0]-'0') == i/10 + b := s[1] == '?' || int(s[1]-'0') == i%10 + if a && b { + cnt++ + } + } + return + } + return f(time[:2], 24) * f(time[3:], 60) +} +``` + +```ts +function countTime(time: string): number { + const f = (s: string, m: number): number => { + let cnt = 0; + for (let i = 0; i < m; ++i) { + const a = s[0] === '?' || s[0] === Math.floor(i / 10).toString(); + const b = s[1] === '?' || s[1] === (i % 10).toString(); + if (a && b) { + ++cnt; + } + } + return cnt; + }; + return f(time.slice(0, 2), 24) * f(time.slice(3), 60); +} +``` + ```rust impl Solution { pub fn count_time(time: String) -> i32 { @@ -308,10 +300,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2438.Range Product Queries of Powers/README.md b/solution/2400-2499/2438.Range Product Queries of Powers/README.md index b4087d90cb3f0..227a42dbecae2 100644 --- a/solution/2400-2499/2438.Range Product Queries of Powers/README.md +++ b/solution/2400-2499/2438.Range Product Queries of Powers/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:位运算 + 模拟** +### 方法一:位运算 + 模拟 我们先通过位运算(lowbit)得到 powers 数组,然后通过模拟的方式求出每个查询的答案。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func productQueries(n int, queries [][]int) []int { var mod int = 1e9 + 7 @@ -160,16 +146,6 @@ func productQueries(n int, queries [][]int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2438.Range Product Queries of Powers/README_EN.md b/solution/2400-2499/2438.Range Product Queries of Powers/README_EN.md index 455f206fbdeab..024ca2d5af697 100644 --- a/solution/2400-2499/2438.Range Product Queries of Powers/README_EN.md +++ b/solution/2400-2499/2438.Range Product Queries of Powers/README_EN.md @@ -45,7 +45,7 @@ The answer to the only query is powers[0] = 2. The answer modulo 109 ## Solutions -**Solution 1: Bit Manipulation + Simulation** +### Solution 1: Bit Manipulation + Simulation First, we use bit manipulation (lowbit) to get the powers array, and then simulate to get the answer for each query. @@ -53,8 +53,6 @@ The time complexity is $O(n \times \log n)$, ignoring the space consumption of t -### **Python3** - ```python class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: @@ -73,8 +71,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +122,6 @@ public: }; ``` -### **Go** - ```go func productQueries(n int, queries [][]int) []int { var mod int = 1e9 + 7 @@ -152,16 +144,6 @@ func productQueries(n int, queries [][]int) []int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2439.Minimize Maximum of Array/README.md b/solution/2400-2499/2439.Minimize Maximum of Array/README.md index 7ecec33d34de7..c677efaf6024b 100644 --- a/solution/2400-2499/2439.Minimize Maximum of Array/README.md +++ b/solution/2400-2499/2439.Minimize Maximum of Array/README.md @@ -53,9 +53,7 @@ nums 中最大值为 5 。无法得到比 5 更小的最大值。 ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 最小化数组的最大值,容易想到二分查找。我们二分枚举数组的最大值 $mx$,找到一个满足题目要求的、且值最小的 $mx$ 即可。 @@ -63,10 +61,6 @@ nums 中最大值为 5 。无法得到比 5 更小的最大值。 -### **Python3** - - - ```python class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: @@ -86,10 +80,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { private int[] nums; @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +140,6 @@ public: }; ``` -### **Go** - ```go func minimizeArrayValue(nums []int) int { check := func(mx int) bool { @@ -177,16 +163,6 @@ func minimizeArrayValue(nums []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2439.Minimize Maximum of Array/README_EN.md b/solution/2400-2499/2439.Minimize Maximum of Array/README_EN.md index 37afb2216daa8..ff4cf2c57a665 100644 --- a/solution/2400-2499/2439.Minimize Maximum of Array/README_EN.md +++ b/solution/2400-2499/2439.Minimize Maximum of Array/README_EN.md @@ -51,7 +51,7 @@ It is optimal to leave nums as is, and since 10 is the maximum value, we return ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search To minimize the maximum value of the array, it is intuitive to use binary search. We binary search for the maximum value $mx$ of the array, and find the smallest $mx$ that satisfies the problem requirements. @@ -59,8 +59,6 @@ The time complexity is $O(n \times \log M)$, where $n$ is the length of the arra -### **Python3** - ```python class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: @@ -80,8 +78,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { private int[] nums; @@ -118,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +138,6 @@ public: }; ``` -### **Go** - ```go func minimizeArrayValue(nums []int) int { check := func(mx int) bool { @@ -169,16 +161,6 @@ func minimizeArrayValue(nums []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2440.Create Components With Same Value/README.md b/solution/2400-2499/2440.Create Components With Same Value/README.md index 74cd6e580460e..b26a3cbbc2040 100644 --- a/solution/2400-2499/2440.Create Components With Same Value/README.md +++ b/solution/2400-2499/2440.Create Components With Same Value/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:枚举连通块的个数** +### 方法一:枚举连通块的个数 假设连通块的个数为 $k$,那么要删除的边数为 $k-1$,每个连通块的价值为 $\frac{s}{k}$,其中 $s$ 为 $nums$ 所有节点的值之和。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def componentValue(self, nums: List[int], edges: List[List[int]]) -> int: @@ -98,10 +92,6 @@ class Solution: return 0 ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -165,8 +155,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -206,8 +194,6 @@ public: }; ``` -### **Go** - ```go func componentValue(nums []int, edges [][]int) int { s, mx := 0, slices.Max(nums) @@ -254,16 +240,6 @@ func componentValue(nums []int, edges [][]int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2440.Create Components With Same Value/README_EN.md b/solution/2400-2499/2440.Create Components With Same Value/README_EN.md index 2425cd5861c1b..8a76c6cd97134 100644 --- a/solution/2400-2499/2440.Create Components With Same Value/README_EN.md +++ b/solution/2400-2499/2440.Create Components With Same Value/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Enumeration of Connected Blocks** +### Solution 1: Enumeration of Connected Blocks Assume the number of connected blocks is $k$, then the number of edges to be deleted is $k-1$, and the value of each connected block is $\frac{s}{k}$, where $s$ is the sum of the values of all nodes in $nums$. @@ -58,8 +58,6 @@ The time complexity is $O(n \times \sqrt{s})$, where $n$ and $s$ are the length -### **Python3** - ```python class Solution: def componentValue(self, nums: List[int], edges: List[List[int]]) -> int: @@ -90,8 +88,6 @@ class Solution: return 0 ``` -### **Java** - ```java class Solution { private List[] g; @@ -155,8 +151,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -196,8 +190,6 @@ public: }; ``` -### **Go** - ```go func componentValue(nums []int, edges [][]int) int { s, mx := 0, slices.Max(nums) @@ -244,16 +236,6 @@ func componentValue(nums []int, edges [][]int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2441.Largest Positive Integer That Exists With Its Negative/README.md b/solution/2400-2499/2441.Largest Positive Integer That Exists With Its Negative/README.md index 1112ed6c3b8dd..1f0bd9300c455 100644 --- a/solution/2400-2499/2441.Largest Positive Integer That Exists With Its Negative/README.md +++ b/solution/2400-2499/2441.Largest Positive Integer That Exists With Its Negative/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以用哈希表 $s$ 记录数组中出现的所有元素,用一个变量 $ans$ 记录满足题目要求的最大正整数,初始时 $ans = -1$。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def findMaxK(self, nums: List[int]) -> int: @@ -73,10 +67,6 @@ class Solution: return max((x for x in s if -x in s), default=-1) ``` -### **Java** - - - ```java class Solution { public int findMaxK(int[] nums) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func findMaxK(nums []int) int { ans := -1 @@ -131,8 +117,6 @@ func findMaxK(nums []int) int { } ``` -### **TypeScript** - ```ts function findMaxK(nums: number[]): number { let ans = -1; @@ -146,8 +130,6 @@ function findMaxK(nums: number[]): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -164,6 +146,12 @@ impl Solution { } ``` + + +### 方法二 + + + ```rust use std::collections::HashSet; @@ -187,10 +175,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2441.Largest Positive Integer That Exists With Its Negative/README_EN.md b/solution/2400-2499/2441.Largest Positive Integer That Exists With Its Negative/README_EN.md index a1e304428ad41..eb7732c467fad 100644 --- a/solution/2400-2499/2441.Largest Positive Integer That Exists With Its Negative/README_EN.md +++ b/solution/2400-2499/2441.Largest Positive Integer That Exists With Its Negative/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We can use a hash table $s$ to record all elements that appear in the array, and a variable $ans$ to record the maximum positive integer that satisfies the problem requirements, initially $ans = -1$. @@ -56,8 +56,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def findMaxK(self, nums: List[int]) -> int: @@ -65,8 +63,6 @@ class Solution: return max((x for x in s if -x in s), default=-1) ``` -### **Java** - ```java class Solution { public int findMaxK(int[] nums) { @@ -85,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +97,6 @@ public: }; ``` -### **Go** - ```go func findMaxK(nums []int) int { ans := -1 @@ -121,8 +113,6 @@ func findMaxK(nums []int) int { } ``` -### **TypeScript** - ```ts function findMaxK(nums: number[]): number { let ans = -1; @@ -136,8 +126,6 @@ function findMaxK(nums: number[]): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -154,6 +142,12 @@ impl Solution { } ``` + + +### Solution 2 + + + ```rust use std::collections::HashSet; @@ -177,10 +171,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2442.Count Number of Distinct Integers After Reverse Operations/README.md b/solution/2400-2499/2442.Count Number of Distinct Integers After Reverse Operations/README.md index a7e8a534c1e34..5a73c20d0a7de 100644 --- a/solution/2400-2499/2442.Count Number of Distinct Integers After Reverse Operations/README.md +++ b/solution/2400-2499/2442.Count Number of Distinct Integers After Reverse Operations/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们先用哈希表记录数组中的所有整数,然后遍历数组中的每个整数,对其进行反转,将反转后的整数添加到哈希表中,最后返回哈希表的大小即可。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def countDistinctIntegers(self, nums: List[int]) -> int: @@ -67,10 +61,6 @@ class Solution: return len(s) ``` -### **Java** - - - ```java class Solution { public int countDistinctIntegers(int[] nums) { @@ -91,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +99,6 @@ public: }; ``` -### **Go** - ```go func countDistinctIntegers(nums []int) int { s := map[int]struct{}{} @@ -131,8 +117,6 @@ func countDistinctIntegers(nums []int) int { } ``` -### **TypeScript** - ```ts function countDistinctIntegers(nums: number[]): number { const n = nums.length; @@ -143,8 +127,6 @@ function countDistinctIntegers(nums: number[]): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -167,10 +149,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2442.Count Number of Distinct Integers After Reverse Operations/README_EN.md b/solution/2400-2499/2442.Count Number of Distinct Integers After Reverse Operations/README_EN.md index 40aee5d494e78..5a544e300f99d 100644 --- a/solution/2400-2499/2442.Count Number of Distinct Integers After Reverse Operations/README_EN.md +++ b/solution/2400-2499/2442.Count Number of Distinct Integers After Reverse Operations/README_EN.md @@ -39,7 +39,7 @@ The number of distinct integers in this array is 1 (The number 2). ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table First, we use a hash table to record all integers in the array. Then, we traverse each integer in the array, reverse it, and add the reversed integer to the hash table. Finally, we return the size of the hash table. @@ -47,8 +47,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def countDistinctIntegers(self, nums: List[int]) -> int: @@ -59,8 +57,6 @@ class Solution: return len(s) ``` -### **Java** - ```java class Solution { public int countDistinctIntegers(int[] nums) { @@ -81,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +95,6 @@ public: }; ``` -### **Go** - ```go func countDistinctIntegers(nums []int) int { s := map[int]struct{}{} @@ -121,8 +113,6 @@ func countDistinctIntegers(nums []int) int { } ``` -### **TypeScript** - ```ts function countDistinctIntegers(nums: number[]): number { const n = nums.length; @@ -133,8 +123,6 @@ function countDistinctIntegers(nums: number[]): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -157,10 +145,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2443.Sum of Number and Its Reverse/README.md b/solution/2400-2499/2443.Sum of Number and Its Reverse/README.md index b85cae1e6446d..4bbdfafb4fb98 100644 --- a/solution/2400-2499/2443.Sum of Number and Its Reverse/README.md +++ b/solution/2400-2499/2443.Sum of Number and Its Reverse/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 在 $[0,.., num]$ 范围内枚举 $k$,判断 $k + reverse(k)$ 是否等于 $num$ 即可。 @@ -56,20 +54,12 @@ -### **Python3** - - - ```python class Solution: def sumOfNumberAndReverse(self, num: int) -> bool: return any(k + int(str(k)[::-1]) == num for k in range(num + 1)) ``` -### **Java** - - - ```java class Solution { public boolean sumOfNumberAndReverse(int num) { @@ -89,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +99,6 @@ public: }; ``` -### **Go** - ```go func sumOfNumberAndReverse(num int) bool { for x := 0; x <= num; x++ { @@ -129,27 +115,6 @@ func sumOfNumberAndReverse(num int) bool { } ``` -### **C** - -```c -bool sumOfNumberAndReverse(int num) { - for (int i = 0; i <= num; i++) { - int t = i; - int j = 0; - while (t > 0) { - j = j * 10 + t % 10; - t /= 10; - } - if (i + j == num) { - return 1; - } - } - return 0; -} -``` - -### **TypeScript** - ```ts function sumOfNumberAndReverse(num: number): boolean { for (let i = 0; i <= num; i++) { @@ -161,8 +126,6 @@ function sumOfNumberAndReverse(num: number): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn sum_of_number_and_reverse(num: i32) -> bool { @@ -187,10 +150,23 @@ impl Solution { } ``` -### **...** - -``` - +```c +bool sumOfNumberAndReverse(int num) { + for (int i = 0; i <= num; i++) { + int t = i; + int j = 0; + while (t > 0) { + j = j * 10 + t % 10; + t /= 10; + } + if (i + j == num) { + return 1; + } + } + return 0; +} ``` + + diff --git a/solution/2400-2499/2443.Sum of Number and Its Reverse/README_EN.md b/solution/2400-2499/2443.Sum of Number and Its Reverse/README_EN.md index a77d441fa271c..0b0d7d114e2b9 100644 --- a/solution/2400-2499/2443.Sum of Number and Its Reverse/README_EN.md +++ b/solution/2400-2499/2443.Sum of Number and Its Reverse/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Brute Force Enumeration** +### Solution 1: Brute Force Enumeration Enumerate $k$ in the range $[0,.., num]$, and check whether $k + reverse(k)$ equals $num$. @@ -48,16 +48,12 @@ The time complexity is $O(n \times \log n)$, where $n$ is the size of $num$. -### **Python3** - ```python class Solution: def sumOfNumberAndReverse(self, num: int) -> bool: return any(k + int(str(k)[::-1]) == num for k in range(num + 1)) ``` -### **Java** - ```java class Solution { public boolean sumOfNumberAndReverse(int num) { @@ -77,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +93,6 @@ public: }; ``` -### **Go** - ```go func sumOfNumberAndReverse(num int) bool { for x := 0; x <= num; x++ { @@ -117,27 +109,6 @@ func sumOfNumberAndReverse(num int) bool { } ``` -### **C** - -```c -bool sumOfNumberAndReverse(int num) { - for (int i = 0; i <= num; i++) { - int t = i; - int j = 0; - while (t > 0) { - j = j * 10 + t % 10; - t /= 10; - } - if (i + j == num) { - return 1; - } - } - return 0; -} -``` - -### **TypeScript** - ```ts function sumOfNumberAndReverse(num: number): boolean { for (let i = 0; i <= num; i++) { @@ -149,8 +120,6 @@ function sumOfNumberAndReverse(num: number): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn sum_of_number_and_reverse(num: i32) -> bool { @@ -175,10 +144,23 @@ impl Solution { } ``` -### **...** - -``` - +```c +bool sumOfNumberAndReverse(int num) { + for (int i = 0; i <= num; i++) { + int t = i; + int j = 0; + while (t > 0) { + j = j * 10 + t % 10; + t /= 10; + } + if (i + j == num) { + return 1; + } + } + return 0; +} ``` + + diff --git a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README.md b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README.md index 45bce7ce150a5..0b44300f96710 100644 --- a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README.md +++ b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:枚举右端点** +### 方法一:枚举右端点 由题意,我们可以知道,定界子数组的所有元素都在区间 `[minK, maxK]` 中,且最小值一定为 `minK`,最大值一定为 `maxK`。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long countSubarrays(int[] nums, int minK, int maxK) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func countSubarrays(nums []int, minK int, maxK int) int64 { ans := 0 @@ -150,36 +136,6 @@ func countSubarrays(nums []int, minK int, maxK int) int64 { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) -#define min(a, b) (((a) < (b)) ? (a) : (b)) - -long long countSubarrays(int* nums, int numsSize, int minK, int maxK) { - long long res = 0; - int minIndex = -1; - int maxIndex = -1; - int k = -1; - for (int i = 0; i < numsSize; i++) { - int num = nums[i]; - if (num == minK) { - minIndex = i; - } - if (num == maxK) { - maxIndex = i; - } - if (num < minK || num > maxK) { - k = i; - } - res += max(min(minIndex, maxIndex) - k, 0); - } - return res; -} -``` - -### **TypeScript** - ```ts function countSubarrays(nums: number[], minK: number, maxK: number): number { let res = 0; @@ -202,8 +158,6 @@ function countSubarrays(nums: number[], minK: number, maxK: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_subarrays(nums: Vec, min_k: i32, max_k: i32) -> i64 { @@ -230,10 +184,32 @@ impl Solution { } ``` -### **...** - -``` +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +#define min(a, b) (((a) < (b)) ? (a) : (b)) +long long countSubarrays(int* nums, int numsSize, int minK, int maxK) { + long long res = 0; + int minIndex = -1; + int maxIndex = -1; + int k = -1; + for (int i = 0; i < numsSize; i++) { + int num = nums[i]; + if (num == minK) { + minIndex = i; + } + if (num == maxK) { + maxIndex = i; + } + if (num < minK || num > maxK) { + k = i; + } + res += max(min(minIndex, maxIndex) - k, 0); + } + return res; +} ``` + + diff --git a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README_EN.md b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README_EN.md index 28931d0d3cf15..673004c031822 100644 --- a/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README_EN.md +++ b/solution/2400-2499/2444.Count Subarrays With Fixed Bounds/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Enumeration of Right Endpoint** +### Solution 1: Enumeration of Right Endpoint From the problem description, we know that all elements of the bounded subarray are in the interval `[minK, maxK]`, and the minimum value must be `minK`, and the maximum value must be `maxK`. @@ -60,8 +60,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is -### **Python3** - ```python class Solution: def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int: @@ -78,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long countSubarrays(int[] nums, int minK, int maxK) { @@ -102,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +115,6 @@ public: }; ``` -### **Go** - ```go func countSubarrays(nums []int, minK int, maxK int) int64 { ans := 0 @@ -143,36 +135,6 @@ func countSubarrays(nums []int, minK int, maxK int) int64 { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) -#define min(a, b) (((a) < (b)) ? (a) : (b)) - -long long countSubarrays(int* nums, int numsSize, int minK, int maxK) { - long long res = 0; - int minIndex = -1; - int maxIndex = -1; - int k = -1; - for (int i = 0; i < numsSize; i++) { - int num = nums[i]; - if (num == minK) { - minIndex = i; - } - if (num == maxK) { - maxIndex = i; - } - if (num < minK || num > maxK) { - k = i; - } - res += max(min(minIndex, maxIndex) - k, 0); - } - return res; -} -``` - -### **TypeScript** - ```ts function countSubarrays(nums: number[], minK: number, maxK: number): number { let res = 0; @@ -195,8 +157,6 @@ function countSubarrays(nums: number[], minK: number, maxK: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn count_subarrays(nums: Vec, min_k: i32, max_k: i32) -> i64 { @@ -223,10 +183,32 @@ impl Solution { } ``` -### **...** - -``` +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) +#define min(a, b) (((a) < (b)) ? (a) : (b)) +long long countSubarrays(int* nums, int numsSize, int minK, int maxK) { + long long res = 0; + int minIndex = -1; + int maxIndex = -1; + int k = -1; + for (int i = 0; i < numsSize; i++) { + int num = nums[i]; + if (num == minK) { + minIndex = i; + } + if (num == maxK) { + maxIndex = i; + } + if (num < minK || num > maxK) { + k = i; + } + res += max(min(minIndex, maxIndex) - k, 0); + } + return res; +} ``` + + diff --git a/solution/2400-2499/2445.Number of Nodes With Value One/README.md b/solution/2400-2499/2445.Number of Nodes With Value One/README.md index fec02733f5ce2..20aac03729eb6 100644 --- a/solution/2400-2499/2445.Number of Nodes With Value One/README.md +++ b/solution/2400-2499/2445.Number of Nodes With Value One/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 根据题意,我们可以模拟每次查询的过程,即将查询节点及其子树的节点值反转。最后统计节点值为 1 的节点个数即可。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def numberOfNodes(self, n: int, queries: List[int]) -> int: @@ -89,10 +83,6 @@ class Solution: return sum(tree) ``` -### **Java** - - - ```java class Solution { private int[] tree; @@ -126,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go func numberOfNodes(n int, queries []int) int { tree := make([]int, n+1) @@ -182,16 +168,6 @@ func numberOfNodes(n int, queries []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2445.Number of Nodes With Value One/README_EN.md b/solution/2400-2499/2445.Number of Nodes With Value One/README_EN.md index 4e7cab896bd0c..f5e3d9b60492c 100644 --- a/solution/2400-2499/2445.Number of Nodes With Value One/README_EN.md +++ b/solution/2400-2499/2445.Number of Nodes With Value One/README_EN.md @@ -51,7 +51,7 @@ After processing the queries, there are one red node (node with value 1): 2. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation According to the problem description, we can simulate the process of each query, that is, reverse the values of the query node and its subtree nodes. Finally, count the number of nodes with a value of 1. @@ -61,8 +61,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def numberOfNodes(self, n: int, queries: List[int]) -> int: @@ -81,8 +79,6 @@ class Solution: return sum(tree) ``` -### **Java** - ```java class Solution { private int[] tree; @@ -116,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +135,6 @@ public: }; ``` -### **Go** - ```go func numberOfNodes(n int, queries []int) int { tree := make([]int, n+1) @@ -172,16 +164,6 @@ func numberOfNodes(n int, queries []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2446.Determine if Two Events Have Conflict/README.md b/solution/2400-2499/2446.Determine if Two Events Have Conflict/README.md index 0ac07915738e0..6b4a16024b946 100644 --- a/solution/2400-2499/2446.Determine if Two Events Have Conflict/README.md +++ b/solution/2400-2499/2446.Determine if Two Events Have Conflict/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:字符串比较** +### 方法一:字符串比较 如果 $event1$ 的开始时间大于 $event2$ 的结束时间,或者 $event1$ 的结束时间小于 $event2$ 的开始时间,那么两个事件不会有冲突。否则,两个事件存在冲突。 @@ -71,20 +69,12 @@ -### **Python3** - - - ```python class Solution: def haveConflict(self, event1: List[str], event2: List[str]) -> bool: return not (event1[0] > event2[1] or event1[1] < event2[0]) ``` -### **Java** - - - ```java class Solution { public boolean haveConflict(String[] event1, String[] event2) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,24 +92,18 @@ public: }; ``` -### **Go** - ```go func haveConflict(event1 []string, event2 []string) bool { return !(event1[0] > event2[1] || event1[1] < event2[0]) } ``` -### **TypeScript** - ```ts function haveConflict(event1: string[], event2: string[]): boolean { return !(event1[0] > event2[1] || event1[1] < event2[0]); } ``` -### **Rust** - ```rust impl Solution { pub fn have_conflict(event1: Vec, event2: Vec) -> bool { @@ -130,10 +112,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2446.Determine if Two Events Have Conflict/README_EN.md b/solution/2400-2499/2446.Determine if Two Events Have Conflict/README_EN.md index 873ef668d007b..b41127c7b1b3c 100644 --- a/solution/2400-2499/2446.Determine if Two Events Have Conflict/README_EN.md +++ b/solution/2400-2499/2446.Determine if Two Events Have Conflict/README_EN.md @@ -55,7 +55,7 @@ ## Solutions -**Solution 1: String Comparison** +### Solution 1: String Comparison If the start time of $event1$ is later than the end time of $event2$, or the end time of $event1$ is earlier than the start time of $event2$, then the two events will not conflict. Otherwise, the two events will conflict. @@ -65,16 +65,12 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def haveConflict(self, event1: List[str], event2: List[str]) -> bool: return not (event1[0] > event2[1] or event1[1] < event2[0]) ``` -### **Java** - ```java class Solution { public boolean haveConflict(String[] event1, String[] event2) { @@ -83,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,24 +88,18 @@ public: }; ``` -### **Go** - ```go func haveConflict(event1 []string, event2 []string) bool { return !(event1[0] > event2[1] || event1[1] < event2[0]) } ``` -### **TypeScript** - ```ts function haveConflict(event1: string[], event2: string[]): boolean { return !(event1[0] > event2[1] || event1[1] < event2[0]); } ``` -### **Rust** - ```rust impl Solution { pub fn have_conflict(event1: Vec, event2: Vec) -> bool { @@ -120,10 +108,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2447.Number of Subarrays With GCD Equal to K/README.md b/solution/2400-2499/2447.Number of Subarrays With GCD Equal to K/README.md index 7dbf4c754bdb5..ccd38c6e733ee 100644 --- a/solution/2400-2499/2447.Number of Subarrays With GCD Equal to K/README.md +++ b/solution/2400-2499/2447.Number of Subarrays With GCD Equal to K/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:直接枚举** +### 方法一:直接枚举 我们可以枚举 $nums[i]$ 作为子数组的左端点,然后枚举 $nums[j]$ 作为子数组的右端点,其中 $i \le j$。在枚举右端点的过程中,我们可以用一个变量 $g$ 来维护当前子数组的最大公因数,每次枚举到一个新的右端点时,我们更新最大公因数 $g = \gcd(g, nums[j])$。如果 $g=k$,那么当前子数组的最大公因数等于 $k$,我们就将答案增加 $1$。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def subarrayGCD(self, nums: List[int], k: int) -> int: @@ -71,10 +65,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int subarrayGCD(int[] nums, int k) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func subarrayGCD(nums []int, k int) (ans int) { for i := range nums { @@ -142,8 +128,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function subarrayGCD(nums: number[], k: number): number { let ans = 0; @@ -165,10 +149,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2447.Number of Subarrays With GCD Equal to K/README_EN.md b/solution/2400-2499/2447.Number of Subarrays With GCD Equal to K/README_EN.md index 304fb2e61e042..0b7befb3f75d4 100644 --- a/solution/2400-2499/2447.Number of Subarrays With GCD Equal to K/README_EN.md +++ b/solution/2400-2499/2447.Number of Subarrays With GCD Equal to K/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Direct Enumeration** +### Solution 1: Direct Enumeration We can enumerate $nums[i]$ as the left endpoint of the subarray, and then enumerate $nums[j]$ as the right endpoint of the subarray, where $i \le j$. During the enumeration of the right endpoint, we can use a variable $g$ to maintain the greatest common divisor of the current subarray. Each time we enumerate a new right endpoint, we update the greatest common divisor $g = \gcd(g, nums[j])$. If $g=k$, then the greatest common divisor of the current subarray equals $k$, and we increase the answer by $1$. @@ -51,8 +51,6 @@ The time complexity is $O(n \times (n + \log M))$, where $n$ and $M$ are the len -### **Python3** - ```python class Solution: def subarrayGCD(self, nums: List[int], k: int) -> int: @@ -65,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int subarrayGCD(int[] nums, int k) { @@ -90,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func subarrayGCD(nums []int, k int) (ans int) { for i := range nums { @@ -134,8 +126,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function subarrayGCD(nums: number[], k: number): number { let ans = 0; @@ -157,10 +147,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2448.Minimum Cost to Make Array Equal/README.md b/solution/2400-2499/2448.Minimum Cost to Make Array Equal/README.md index f564adbb1be0e..aa277d5483897 100644 --- a/solution/2400-2499/2448.Minimum Cost to Make Array Equal/README.md +++ b/solution/2400-2499/2448.Minimum Cost to Make Array Equal/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:前缀和 + 排序 + 枚举** +### 方法一:前缀和 + 排序 + 枚举 我们记数组 `nums` 所有元素为 $a_1, a_2, \cdots, a_n$,数组 `cost` 所有元素为 $b_1, b_2, \cdots, b_n$。我们不妨令 $a_1 \leq a_2 \leq \cdots \leq a_n$,即数组 `nums` 升序排列。 @@ -77,23 +75,8 @@ $$ 时间复杂度 $O(n\times \log n)$。其中 $n$ 为数组 `nums` 的长度。主要是排序的时间复杂度。 -**方法二:排序 + 中位数** - -我们还可以把 $b_i$ 看作是 $a_i$ 的出现次数,那么中位数下标是 $\frac{\sum_{i=1}^{n} b_i}{2}$。把所有数变成中位数,一定是最优的。 - -时间复杂度 $O(n\times \log n)$。其中 $n$ 为数组 `nums` 的长度。主要是排序的时间复杂度。 - -相似题目: - -- [296. 最佳的碰头地点](/solution/0200-0299/0296.Best%20Meeting%20Point/README.md) -- [462. 最少移动次数使数组元素相等 II](/solution/0400-0499/0462.Minimum%20Moves%20to%20Equal%20Array%20Elements%20II/README.md) - -### **Python3** - - - ```python class Solution: def minCost(self, nums: List[int], cost: List[int]) -> int: @@ -114,22 +97,6 @@ class Solution: return ans ``` -```python -class Solution: - def minCost(self, nums: List[int], cost: List[int]) -> int: - arr = sorted(zip(nums, cost)) - mid = sum(cost) // 2 - s = 0 - for x, c in arr: - s += c - if s > mid: - return sum(abs(v - x) * c for v, c in arr) -``` - -### **Java** - - - ```java class Solution { public long minCost(int[] nums, int[] cost) { @@ -158,42 +125,6 @@ class Solution { } ``` -```java -class Solution { - public long minCost(int[] nums, int[] cost) { - int n = nums.length; - int[][] arr = new int[n][2]; - for (int i = 0; i < n; ++i) { - arr[i] = new int[] {nums[i], cost[i]}; - } - Arrays.sort(arr, (a, b) -> a[0] - b[0]); - long mid = sum(cost) / 2; - long s = 0, ans = 0; - for (var e : arr) { - int x = e[0], c = e[1]; - s += c; - if (s > mid) { - for (var t : arr) { - ans += (long) Math.abs(t[0] - x) * t[1]; - } - break; - } - } - return ans; - } - - private long sum(int[] arr) { - long s = 0; - for (int v : arr) { - s += v; - } - return s; - } -} -``` - -### **C++** - ```cpp using ll = long long; @@ -222,34 +153,34 @@ public: }; ``` -```cpp -using ll = long long; - -class Solution { -public: - long long minCost(vector& nums, vector& cost) { - int n = nums.size(); - vector> arr(n); - for (int i = 0; i < n; ++i) arr[i] = {nums[i], cost[i]}; - sort(arr.begin(), arr.end()); - ll mid = accumulate(cost.begin(), cost.end(), 0ll) / 2; - ll s = 0, ans = 0; - for (auto [x, c] : arr) { - s += c; - if (s > mid) { - for (auto [v, d] : arr) { - ans += 1ll * abs(v - x) * d; - } - break; - } - } - return ans; - } -}; +```go +func minCost(nums []int, cost []int) int64 { + n := len(nums) + type pair struct{ a, b int } + arr := make([]pair, n) + for i, a := range nums { + b := cost[i] + arr[i] = pair{a, b} + } + sort.Slice(arr, func(i, j int) bool { return arr[i].a < arr[j].a }) + f := make([]int, n+1) + g := make([]int, n+1) + for i := 1; i <= n; i++ { + a, b := arr[i-1].a, arr[i-1].b + f[i] = f[i-1] + a*b + g[i] = g[i-1] + b + } + var ans int64 = 1e18 + for i := 1; i <= n; i++ { + a := arr[i-1].a + l := a*g[i-1] - f[i-1] + r := f[n] - f[i] - a*(g[n]-g[i]) + ans = min(ans, int64(l+r)) + } + return ans +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -298,36 +229,93 @@ impl Solution { } ``` -### **Go** + -```go -func minCost(nums []int, cost []int) int64 { - n := len(nums) - type pair struct{ a, b int } - arr := make([]pair, n) - for i, a := range nums { - b := cost[i] - arr[i] = pair{a, b} - } - sort.Slice(arr, func(i, j int) bool { return arr[i].a < arr[j].a }) - f := make([]int, n+1) - g := make([]int, n+1) - for i := 1; i <= n; i++ { - a, b := arr[i-1].a, arr[i-1].b - f[i] = f[i-1] + a*b - g[i] = g[i-1] + b - } - var ans int64 = 1e18 - for i := 1; i <= n; i++ { - a := arr[i-1].a - l := a*g[i-1] - f[i-1] - r := f[n] - f[i] - a*(g[n]-g[i]) - ans = min(ans, int64(l+r)) - } - return ans +### 方法二:排序 + 中位数 + +我们还可以把 $b_i$ 看作是 $a_i$ 的出现次数,那么中位数下标是 $\frac{\sum_{i=1}^{n} b_i}{2}$。把所有数变成中位数,一定是最优的。 + +时间复杂度 $O(n\times \log n)$。其中 $n$ 为数组 `nums` 的长度。主要是排序的时间复杂度。 + +相似题目: + +- [296. 最佳的碰头地点](/solution/0200-0299/0296.Best%20Meeting%20Point/README.md) +- [462. 最少移动次数使数组元素相等 II](/solution/0400-0499/0462.Minimum%20Moves%20to%20Equal%20Array%20Elements%20II/README.md) + + + +```python +class Solution: + def minCost(self, nums: List[int], cost: List[int]) -> int: + arr = sorted(zip(nums, cost)) + mid = sum(cost) // 2 + s = 0 + for x, c in arr: + s += c + if s > mid: + return sum(abs(v - x) * c for v, c in arr) +``` + +```java +class Solution { + public long minCost(int[] nums, int[] cost) { + int n = nums.length; + int[][] arr = new int[n][2]; + for (int i = 0; i < n; ++i) { + arr[i] = new int[] {nums[i], cost[i]}; + } + Arrays.sort(arr, (a, b) -> a[0] - b[0]); + long mid = sum(cost) / 2; + long s = 0, ans = 0; + for (var e : arr) { + int x = e[0], c = e[1]; + s += c; + if (s > mid) { + for (var t : arr) { + ans += (long) Math.abs(t[0] - x) * t[1]; + } + break; + } + } + return ans; + } + + private long sum(int[] arr) { + long s = 0; + for (int v : arr) { + s += v; + } + return s; + } } ``` +```cpp +using ll = long long; + +class Solution { +public: + long long minCost(vector& nums, vector& cost) { + int n = nums.size(); + vector> arr(n); + for (int i = 0; i < n; ++i) arr[i] = {nums[i], cost[i]}; + sort(arr.begin(), arr.end()); + ll mid = accumulate(cost.begin(), cost.end(), 0ll) / 2; + ll s = 0, ans = 0; + for (auto [x, c] : arr) { + s += c; + if (s > mid) { + for (auto [v, d] : arr) { + ans += 1ll * abs(v - x) * d; + } + break; + } + } + return ans; + } +}; +``` + ```go func minCost(nums []int, cost []int) int64 { n := len(nums) @@ -364,16 +352,6 @@ func abs(x int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2448.Minimum Cost to Make Array Equal/README_EN.md b/solution/2400-2499/2448.Minimum Cost to Make Array Equal/README_EN.md index 4af10d4e39894..65120794bdbba 100644 --- a/solution/2400-2499/2448.Minimum Cost to Make Array Equal/README_EN.md +++ b/solution/2400-2499/2448.Minimum Cost to Make Array Equal/README_EN.md @@ -50,7 +50,7 @@ It can be shown that we cannot make the array equal with a smaller cost. ## Solutions -**Solution 1: Prefix Sum + Sorting + Enumeration** +### Solution 1: Prefix Sum + Sorting + Enumeration Let's denote the elements of the array `nums` as $a_1, a_2, \cdots, a_n$ and the elements of the array `cost` as $b_1, b_2, \cdots, b_n$. We can assume that $a_1 \leq a_2 \leq \cdots \leq a_n$, i.e., the array `nums` is sorted in ascending order. @@ -71,21 +71,8 @@ Then we enumerate $x$, calculate the above four prefix sums, get the total cost The time complexity is $O(n\times \log n)$, where $n$ is the length of the array `nums`. The main time complexity comes from sorting. -**Solution 2: Sorting + Median** - -We can also consider $b_i$ as the occurrence times of $a_i$, then the index of the median is $\frac{\sum_{i=1}^{n} b_i}{2}$. Changing all numbers to the median is definitely optimal. - -The time complexity is $O(n\times \log n)$, where $n$ is the length of the array `nums`. The main time complexity comes from sorting. - -Similar problems: - -- [296. Best Meeting Point](/solution/0200-0299/0296.Best%20Meeting%20Point/README_EN.md) -- [462. Minimum Moves to Equal Array Elements II](/solution/0400-0499/0462.Minimum%20Moves%20to%20Equal%20Array%20Elements%20II/README_EN.md) - -### **Python3** - ```python class Solution: def minCost(self, nums: List[int], cost: List[int]) -> int: @@ -106,20 +93,6 @@ class Solution: return ans ``` -```python -class Solution: - def minCost(self, nums: List[int], cost: List[int]) -> int: - arr = sorted(zip(nums, cost)) - mid = sum(cost) // 2 - s = 0 - for x, c in arr: - s += c - if s > mid: - return sum(abs(v - x) * c for v, c in arr) -``` - -### **Java** - ```java class Solution { public long minCost(int[] nums, int[] cost) { @@ -148,42 +121,6 @@ class Solution { } ``` -```java -class Solution { - public long minCost(int[] nums, int[] cost) { - int n = nums.length; - int[][] arr = new int[n][2]; - for (int i = 0; i < n; ++i) { - arr[i] = new int[] {nums[i], cost[i]}; - } - Arrays.sort(arr, (a, b) -> a[0] - b[0]); - long mid = sum(cost) / 2; - long s = 0, ans = 0; - for (var e : arr) { - int x = e[0], c = e[1]; - s += c; - if (s > mid) { - for (var t : arr) { - ans += (long) Math.abs(t[0] - x) * t[1]; - } - break; - } - } - return ans; - } - - private long sum(int[] arr) { - long s = 0; - for (int v : arr) { - s += v; - } - return s; - } -} -``` - -### **C++** - ```cpp using ll = long long; @@ -212,34 +149,34 @@ public: }; ``` -```cpp -using ll = long long; - -class Solution { -public: - long long minCost(vector& nums, vector& cost) { - int n = nums.size(); - vector> arr(n); - for (int i = 0; i < n; ++i) arr[i] = {nums[i], cost[i]}; - sort(arr.begin(), arr.end()); - ll mid = accumulate(cost.begin(), cost.end(), 0ll) / 2; - ll s = 0, ans = 0; - for (auto [x, c] : arr) { - s += c; - if (s > mid) { - for (auto [v, d] : arr) { - ans += 1ll * abs(v - x) * d; - } - break; - } - } - return ans; - } -}; +```go +func minCost(nums []int, cost []int) int64 { + n := len(nums) + type pair struct{ a, b int } + arr := make([]pair, n) + for i, a := range nums { + b := cost[i] + arr[i] = pair{a, b} + } + sort.Slice(arr, func(i, j int) bool { return arr[i].a < arr[j].a }) + f := make([]int, n+1) + g := make([]int, n+1) + for i := 1; i <= n; i++ { + a, b := arr[i-1].a, arr[i-1].b + f[i] = f[i-1] + a*b + g[i] = g[i-1] + b + } + var ans int64 = 1e18 + for i := 1; i <= n; i++ { + a := arr[i-1].a + l := a*g[i-1] - f[i-1] + r := f[n] - f[i] - a*(g[n]-g[i]) + ans = min(ans, int64(l+r)) + } + return ans +} ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -288,36 +225,93 @@ impl Solution { } ``` -### **Go** + -```go -func minCost(nums []int, cost []int) int64 { - n := len(nums) - type pair struct{ a, b int } - arr := make([]pair, n) - for i, a := range nums { - b := cost[i] - arr[i] = pair{a, b} - } - sort.Slice(arr, func(i, j int) bool { return arr[i].a < arr[j].a }) - f := make([]int, n+1) - g := make([]int, n+1) - for i := 1; i <= n; i++ { - a, b := arr[i-1].a, arr[i-1].b - f[i] = f[i-1] + a*b - g[i] = g[i-1] + b - } - var ans int64 = 1e18 - for i := 1; i <= n; i++ { - a := arr[i-1].a - l := a*g[i-1] - f[i-1] - r := f[n] - f[i] - a*(g[n]-g[i]) - ans = min(ans, int64(l+r)) - } - return ans +### Solution 2: Sorting + Median + +We can also consider $b_i$ as the occurrence times of $a_i$, then the index of the median is $\frac{\sum_{i=1}^{n} b_i}{2}$. Changing all numbers to the median is definitely optimal. + +The time complexity is $O(n\times \log n)$, where $n$ is the length of the array `nums`. The main time complexity comes from sorting. + +Similar problems: + +- [296. Best Meeting Point](/solution/0200-0299/0296.Best%20Meeting%20Point/README_EN.md) +- [462. Minimum Moves to Equal Array Elements II](/solution/0400-0499/0462.Minimum%20Moves%20to%20Equal%20Array%20Elements%20II/README_EN.md) + + + +```python +class Solution: + def minCost(self, nums: List[int], cost: List[int]) -> int: + arr = sorted(zip(nums, cost)) + mid = sum(cost) // 2 + s = 0 + for x, c in arr: + s += c + if s > mid: + return sum(abs(v - x) * c for v, c in arr) +``` + +```java +class Solution { + public long minCost(int[] nums, int[] cost) { + int n = nums.length; + int[][] arr = new int[n][2]; + for (int i = 0; i < n; ++i) { + arr[i] = new int[] {nums[i], cost[i]}; + } + Arrays.sort(arr, (a, b) -> a[0] - b[0]); + long mid = sum(cost) / 2; + long s = 0, ans = 0; + for (var e : arr) { + int x = e[0], c = e[1]; + s += c; + if (s > mid) { + for (var t : arr) { + ans += (long) Math.abs(t[0] - x) * t[1]; + } + break; + } + } + return ans; + } + + private long sum(int[] arr) { + long s = 0; + for (int v : arr) { + s += v; + } + return s; + } } ``` +```cpp +using ll = long long; + +class Solution { +public: + long long minCost(vector& nums, vector& cost) { + int n = nums.size(); + vector> arr(n); + for (int i = 0; i < n; ++i) arr[i] = {nums[i], cost[i]}; + sort(arr.begin(), arr.end()); + ll mid = accumulate(cost.begin(), cost.end(), 0ll) / 2; + ll s = 0, ans = 0; + for (auto [x, c] : arr) { + s += c; + if (s > mid) { + for (auto [v, d] : arr) { + ans += 1ll * abs(v - x) * d; + } + break; + } + } + return ans; + } +}; +``` + ```go func minCost(nums []int, cost []int) int64 { n := len(nums) @@ -354,16 +348,6 @@ func abs(x int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2449.Minimum Number of Operations to Make Arrays Similar/README.md b/solution/2400-2499/2449.Minimum Number of Operations to Make Arrays Similar/README.md index 8ef7d4eca048d..2b0baf6addaf1 100644 --- a/solution/2400-2499/2449.Minimum Number of Operations to Make Arrays Similar/README.md +++ b/solution/2400-2499/2449.Minimum Number of Operations to Make Arrays Similar/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:奇偶分类 + 排序** +### 方法一:奇偶分类 + 排序 注意到,由于每次操作,元素的值只会增加 $2$ 或减少 $2$,因此,元素的奇偶性不会改变。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def makeSimilar(self, nums: List[int], target: List[int]) -> int: @@ -90,10 +84,6 @@ class Solution: return sum(abs(a - b) for a, b in zip(nums, target)) // 4 ``` -### **Java** - - - ```java class Solution { public long makeSimilar(int[] nums, int[] target) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go func makeSimilar(nums []int, target []int) int64 { sort.Ints(nums) @@ -200,8 +186,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function makeSimilar(nums: number[], target: number[]): number { nums.sort((a, b) => a - b); @@ -241,10 +225,6 @@ function makeSimilar(nums: number[], target: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2449.Minimum Number of Operations to Make Arrays Similar/README_EN.md b/solution/2400-2499/2449.Minimum Number of Operations to Make Arrays Similar/README_EN.md index 79935dbe74119..918a1e5d729b1 100644 --- a/solution/2400-2499/2449.Minimum Number of Operations to Make Arrays Similar/README_EN.md +++ b/solution/2400-2499/2449.Minimum Number of Operations to Make Arrays Similar/README_EN.md @@ -58,7 +58,7 @@ It can be shown that 2 is the minimum number of operations needed. ## Solutions -**Solution 1: Odd-Even Classification + Sorting** +### Solution 1: Odd-Even Classification + Sorting Notice that, because each operation will only increase or decrease the value of an element by $2$, the parity of the element will not change. @@ -72,8 +72,6 @@ The time complexity is $O(n \times \log n)$, where $n$ is the length of the arra -### **Python3** - ```python class Solution: def makeSimilar(self, nums: List[int], target: List[int]) -> int: @@ -82,8 +80,6 @@ class Solution: return sum(abs(a - b) for a, b in zip(nums, target)) // 4 ``` -### **Java** - ```java class Solution { public long makeSimilar(int[] nums, int[] target) { @@ -119,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +145,6 @@ public: }; ``` -### **Go** - ```go func makeSimilar(nums []int, target []int) int64 { sort.Ints(nums) @@ -190,8 +182,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function makeSimilar(nums: number[], target: number[]): number { nums.sort((a, b) => a - b); @@ -231,10 +221,6 @@ function makeSimilar(nums: number[], target: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2450.Number of Distinct Binary Strings After Applying Operations/README.md b/solution/2400-2499/2450.Number of Distinct Binary Strings After Applying Operations/README.md index 775b9906fca14..ec12d25a68fce 100644 --- a/solution/2400-2499/2450.Number of Distinct Binary Strings After Applying Operations/README.md +++ b/solution/2400-2499/2450.Number of Distinct Binary Strings After Applying Operations/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 假设字符串 $s$ 长度为 $n$,那么长度为 $k$ 的子串共有 $n - k + 1$ 个,每个子串都可以翻转,因此共有 $2^{n - k + 1}$ 种翻转方式。 @@ -71,20 +69,12 @@ -### **Python3** - - - ```python class Solution: def countDistinctStrings(self, s: str, k: int) -> int: return pow(2, len(s) - k + 1) % (10**9 + 7) ``` -### **Java** - - - ```java class Solution { public static final int MOD = (int) 1e9 + 7; @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func countDistinctStrings(s string, k int) int { const mod int = 1e9 + 7 @@ -129,16 +115,6 @@ func countDistinctStrings(s string, k int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2450.Number of Distinct Binary Strings After Applying Operations/README_EN.md b/solution/2400-2499/2450.Number of Distinct Binary Strings After Applying Operations/README_EN.md index 13799228389c2..ac875394a7650 100644 --- a/solution/2400-2499/2450.Number of Distinct Binary Strings After Applying Operations/README_EN.md +++ b/solution/2400-2499/2450.Number of Distinct Binary Strings After Applying Operations/README_EN.md @@ -55,7 +55,7 @@ It can be shown that we cannot obtain any other string, so the answer is 2. ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics Assume the length of the string $s$ is $n$. Then there are $n - k + 1$ substrings of length $k$, and each substring can be flipped, so there are $2^{n - k + 1}$ ways to flip. @@ -63,16 +63,12 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is -### **Python3** - ```python class Solution: def countDistinctStrings(self, s: str, k: int) -> int: return pow(2, len(s) - k + 1) % (10**9 + 7) ``` -### **Java** - ```java class Solution { public static final int MOD = (int) 1e9 + 7; @@ -87,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +98,6 @@ public: }; ``` -### **Go** - ```go func countDistinctStrings(s string, k int) int { const mod int = 1e9 + 7 @@ -117,16 +109,6 @@ func countDistinctStrings(s string, k int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2451.Odd String Difference/README.md b/solution/2400-2499/2451.Odd String Difference/README.md index b0aed8013c6e4..e0cfa135e5401 100644 --- a/solution/2400-2499/2451.Odd String Difference/README.md +++ b/solution/2400-2499/2451.Odd String Difference/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:哈希表模拟** +### 方法一:哈希表模拟 我们用哈希表 $d$ 维护字符串的差值数组和字符串的映射关系,其中差值数组为字符串的相邻字符的差值构成的数组。由于题目保证了除了一个字符串以外,其他字符串的差值数组都相同,因此我们只需要找到差值数组不同的字符串即可。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def oddString(self, words: List[str]) -> str: @@ -77,10 +71,6 @@ class Solution: return next(ss[0] for ss in d.values() if len(ss) == 1) ``` -### **Java** - - - ```java class Solution { public String oddString(String[] words) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func oddString(words []string) string { d := map[string][]string{} @@ -153,8 +139,6 @@ func oddString(words []string) string { } ``` -### **TypeScript** - ```ts function oddString(words: string[]): string { const d: Map = new Map(); @@ -178,8 +162,6 @@ function oddString(words: string[]): string { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -205,6 +187,12 @@ impl Solution { } ``` + + +### 方法二 + + + ```rust use std::collections::HashMap; @@ -240,10 +228,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2451.Odd String Difference/README_EN.md b/solution/2400-2499/2451.Odd String Difference/README_EN.md index e46922b8607f9..5578ad280f9cd 100644 --- a/solution/2400-2499/2451.Odd String Difference/README_EN.md +++ b/solution/2400-2499/2451.Odd String Difference/README_EN.md @@ -49,7 +49,7 @@ The odd array out is [1, 1], so we return the corresponding string, "abc&qu ## Solutions -**Solution 1: Hash Table Simulation** +### Solution 1: Hash Table Simulation We use a hash table $d$ to maintain the mapping relationship between the difference array of the string and the string itself, where the difference array is an array composed of the differences of adjacent characters in the string. Since the problem guarantees that except for one string, the difference arrays of other strings are the same, we only need to find the string with a different difference array. @@ -57,8 +57,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m + n)$. -### **Python3** - ```python class Solution: def oddString(self, words: List[str]) -> str: @@ -69,8 +67,6 @@ class Solution: return next(ss[0] for ss in d.values() if len(ss) == 1) ``` -### **Java** - ```java class Solution { public String oddString(String[] words) { @@ -95,24 +91,22 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: string oddString(vector& words) { - unordered_map> d; - for (auto& s : words) { - int m = s.size(); - string t(m - 1, 0); - for (int i = 0; i < m - 1; ++i) { - t[i] = s[i + 1] - s[i]; + unordered_map> cnt; + for (auto& w : words) { + string d; + for (int i = 0; i < w.size() - 1; ++i) { + d += (char) (w[i + 1] - w[i]); + d += ','; } - d[t].push_back(s); + cnt[d].emplace_back(w); } - for (auto& [_, ss] : d) { - if (ss.size() == 1) { - return ss[0]; + for (auto& [_, v] : cnt) { + if (v.size() == 1) { + return v[0]; } } return ""; @@ -120,8 +114,6 @@ public: }; ``` -### **Go** - ```go func oddString(words []string) string { d := map[string][]string{} @@ -143,8 +135,6 @@ func oddString(words []string) string { } ``` -### **TypeScript** - ```ts function oddString(words: string[]): string { const d: Map = new Map(); @@ -168,8 +158,6 @@ function oddString(words: string[]): string { } ``` -### **Rust** - ```rust use std::collections::HashMap; impl Solution { @@ -195,6 +183,12 @@ impl Solution { } ``` + + +### Solution 2 + + + ```rust use std::collections::HashMap; @@ -230,10 +224,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2452.Words Within Two Edits of Dictionary/README.md b/solution/2400-2499/2452.Words Within Two Edits of Dictionary/README.md index 28275dbf94ceb..bec87d13c7d11 100644 --- a/solution/2400-2499/2452.Words Within Two Edits of Dictionary/README.md +++ b/solution/2400-2499/2452.Words Within Two Edits of Dictionary/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 遍历 `queries` 中的每个单词,对于每个单词,遍历 `dictionary` 中的每个单词,判断两个单词不同字符的位置数是否小于 $3$,如果是,则将该单词加入结果集。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def twoEditWords(self, queries: List[str], dictionary: List[str]) -> List[str]: @@ -74,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List twoEditWords(String[] queries, String[] dictionary) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func twoEditWords(queries []string, dictionary []string) (ans []string) { for _, s := range queries { @@ -146,8 +132,6 @@ func twoEditWords(queries []string, dictionary []string) (ans []string) { } ``` -### **TypeScript** - ```ts function twoEditWords(queries: string[], dictionary: string[]): string[] { const n = queries[0].length; @@ -168,8 +152,6 @@ function twoEditWords(queries: string[], dictionary: string[]): string[] { } ``` -### **Rust** - ```rust impl Solution { pub fn two_edit_words(queries: Vec, dictionary: Vec) -> Vec { @@ -195,10 +177,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2452.Words Within Two Edits of Dictionary/README_EN.md b/solution/2400-2499/2452.Words Within Two Edits of Dictionary/README_EN.md index 8e8dd43108eb8..5c916f1cfffba 100644 --- a/solution/2400-2499/2452.Words Within Two Edits of Dictionary/README_EN.md +++ b/solution/2400-2499/2452.Words Within Two Edits of Dictionary/README_EN.md @@ -45,9 +45,9 @@ Applying any two edits to "yes" cannot make it equal to "not" ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List twoEditWords(String[] queries, String[] dictionary) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +105,6 @@ public: }; ``` -### **Go** - ```go func twoEditWords(queries []string, dictionary []string) (ans []string) { for _, s := range queries { @@ -131,8 +125,6 @@ func twoEditWords(queries []string, dictionary []string) (ans []string) { } ``` -### **TypeScript** - ```ts function twoEditWords(queries: string[], dictionary: string[]): string[] { const n = queries[0].length; @@ -153,8 +145,6 @@ function twoEditWords(queries: string[], dictionary: string[]): string[] { } ``` -### **Rust** - ```rust impl Solution { pub fn two_edit_words(queries: Vec, dictionary: Vec) -> Vec { @@ -180,10 +170,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2453.Destroy Sequential Targets/README.md b/solution/2400-2499/2453.Destroy Sequential Targets/README.md index 58f4d6d978ce9..522480285f8a0 100644 --- a/solution/2400-2499/2453.Destroy Sequential Targets/README.md +++ b/solution/2400-2499/2453.Destroy Sequential Targets/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:取模 + 枚举** +### 方法一:取模 + 枚举 我们遍历数组 $nums$,用哈希表 $cnt$ 统计每个数模 $space$ 后的余数出现的次数。次数越多,意味着可以摧毁的目标越多。我们找到最多次数的组,取组中的最小值即可。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def destroyTargets(self, nums: List[int], space: int) -> int: @@ -78,10 +72,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int destroyTargets(int[] nums, int space) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func destroyTargets(nums []int, space int) int { cnt := map[int]int{} @@ -144,16 +130,6 @@ func destroyTargets(nums []int, space int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2453.Destroy Sequential Targets/README_EN.md b/solution/2400-2499/2453.Destroy Sequential Targets/README_EN.md index 083475441d08c..46e9f933d6836 100644 --- a/solution/2400-2499/2453.Destroy Sequential Targets/README_EN.md +++ b/solution/2400-2499/2453.Destroy Sequential Targets/README_EN.md @@ -50,7 +50,7 @@ Since nums[0] is the minimal integer that can destroy 3 targets, we return 1. ## Solutions -**Solution 1: Modulo + Enumeration** +### Solution 1: Modulo + Enumeration We traverse the array $nums$ and use a hash table $cnt$ to count the frequency of each number modulo $space$. The higher the frequency, the more targets can be destroyed. We find the group with the highest frequency and take the minimum value in the group. @@ -58,8 +58,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def destroyTargets(self, nums: List[int], space: int) -> int: @@ -73,8 +71,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int destroyTargets(int[] nums, int space) { @@ -96,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func destroyTargets(nums []int, space int) int { cnt := map[int]int{} @@ -137,16 +129,6 @@ func destroyTargets(nums []int, space int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2454.Next Greater Element IV/README.md b/solution/2400-2499/2454.Next Greater Element IV/README.md index b2da97d8a8cb1..7e7c966fade77 100644 --- a/solution/2400-2499/2454.Next Greater Element IV/README.md +++ b/solution/2400-2499/2454.Next Greater Element IV/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:排序 + 有序集合** +### 方法一:排序 + 有序集合 我们可以将数组中的元素转成二元组 $(x, i)$,其中 $x$ 为元素的值,$i$ 为元素的下标。然后按照元素的值从大到小排序。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] secondGreaterElement(int[] nums) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **TypeScript** - ```ts function secondGreaterElement(nums: number[]): number[] { const n = nums.length; @@ -816,10 +802,6 @@ class TreeMultiSet { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2454.Next Greater Element IV/README_EN.md b/solution/2400-2499/2454.Next Greater Element IV/README_EN.md index 1d9c3fb1d899f..e443d4747ebf6 100644 --- a/solution/2400-2499/2454.Next Greater Element IV/README_EN.md +++ b/solution/2400-2499/2454.Next Greater Element IV/README_EN.md @@ -56,7 +56,7 @@ We return [-1,-1] since neither integer has any integer greater than it. ## Solutions -**Solution 1: Sorting + Ordered Set** +### Solution 1: Sorting + Ordered Set We can convert the elements in the array into pairs $(x, i)$, where $x$ is the value of the element and $i$ is the index of the element. Then sort by the value of the elements in descending order. @@ -66,8 +66,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python from sortedcontainers import SortedList @@ -87,8 +85,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] secondGreaterElement(int[] nums) { @@ -114,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +134,6 @@ public: }; ``` -### **TypeScript** - ```ts function secondGreaterElement(nums: number[]): number[] { const n = nums.length; @@ -806,10 +798,6 @@ class TreeMultiSet { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2455.Average Value of Even Numbers That Are Divisible by Three/README.md b/solution/2400-2499/2455.Average Value of Even Numbers That Are Divisible by Three/README.md index 0f9fc1c57b42d..e51210d71ba58 100644 --- a/solution/2400-2499/2455.Average Value of Even Numbers That Are Divisible by Three/README.md +++ b/solution/2400-2499/2455.Average Value of Even Numbers That Are Divisible by Three/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们注意到,可被 $3$ 整除的偶数一定是 $6$ 的倍数,因此我们只需要遍历数组,统计所有 $6$ 的倍数的和与个数,然后计算平均值即可。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python class Solution: def averageValue(self, nums: List[int]) -> int: @@ -64,10 +58,6 @@ class Solution: return 0 if n == 0 else s // n ``` -### **Java** - - - ```java class Solution { public int averageValue(int[] nums) { @@ -83,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +89,6 @@ public: }; ``` -### **Go** - ```go func averageValue(nums []int) int { var s, n int @@ -119,8 +105,6 @@ func averageValue(nums []int) int { } ``` -### **TypeScript** - ```ts function averageValue(nums: number[]): number { let s = 0; @@ -135,23 +119,6 @@ function averageValue(nums: number[]): number { } ``` -### **C** - -```c -int averageValue(int* nums, int numsSize) { - int s = 0, n = 0; - for (int i = 0; i < numsSize; ++i) { - if (nums[i] % 6 == 0) { - s += nums[i]; - ++n; - } - } - return n == 0 ? 0 : s / n; -} -``` - -### **Rust** - ```rust impl Solution { pub fn average_value(nums: Vec) -> i32 { @@ -171,6 +138,25 @@ impl Solution { } ``` +```c +int averageValue(int* nums, int numsSize) { + int s = 0, n = 0; + for (int i = 0; i < numsSize; ++i) { + if (nums[i] % 6 == 0) { + s += nums[i]; + ++n; + } + } + return n == 0 ? 0 : s / n; +} +``` + + + +### 方法二 + + + ```rust impl Solution { pub fn average_value(nums: Vec) -> i32 { @@ -189,10 +175,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2455.Average Value of Even Numbers That Are Divisible by Three/README_EN.md b/solution/2400-2499/2455.Average Value of Even Numbers That Are Divisible by Three/README_EN.md index 73731a3e5393a..67f610a50e10b 100644 --- a/solution/2400-2499/2455.Average Value of Even Numbers That Are Divisible by Three/README_EN.md +++ b/solution/2400-2499/2455.Average Value of Even Numbers That Are Divisible by Three/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We notice that an even number divisible by $3$ must be a multiple of $6$. Therefore, we only need to traverse the array, count the sum and the number of all multiples of $6$, and then calculate the average. @@ -43,8 +43,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def averageValue(self, nums: List[int]) -> int: @@ -56,8 +54,6 @@ class Solution: return 0 if n == 0 else s // n ``` -### **Java** - ```java class Solution { public int averageValue(int[] nums) { @@ -73,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +85,6 @@ public: }; ``` -### **Go** - ```go func averageValue(nums []int) int { var s, n int @@ -109,8 +101,6 @@ func averageValue(nums []int) int { } ``` -### **TypeScript** - ```ts function averageValue(nums: number[]): number { let s = 0; @@ -125,23 +115,6 @@ function averageValue(nums: number[]): number { } ``` -### **C** - -```c -int averageValue(int* nums, int numsSize) { - int s = 0, n = 0; - for (int i = 0; i < numsSize; ++i) { - if (nums[i] % 6 == 0) { - s += nums[i]; - ++n; - } - } - return n == 0 ? 0 : s / n; -} -``` - -### **Rust** - ```rust impl Solution { pub fn average_value(nums: Vec) -> i32 { @@ -161,6 +134,25 @@ impl Solution { } ``` +```c +int averageValue(int* nums, int numsSize) { + int s = 0, n = 0; + for (int i = 0; i < numsSize; ++i) { + if (nums[i] % 6 == 0) { + s += nums[i]; + ++n; + } + } + return n == 0 ? 0 : s / n; +} +``` + + + +### Solution 2 + + + ```rust impl Solution { pub fn average_value(nums: Vec) -> i32 { @@ -179,10 +171,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2456.Most Popular Video Creator/README.md b/solution/2400-2499/2456.Most Popular Video Creator/README.md index bb394ad3f517b..27ee2ce775cb5 100644 --- a/solution/2400-2499/2456.Most Popular Video Creator/README.md +++ b/solution/2400-2499/2456.Most Popular Video Creator/README.md @@ -57,9 +57,7 @@ id 为 "b" 和 "c" 的视频都满足播放量最高的条件。 ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们遍历三个数组,用哈希表 $cnt$ 统计每个创作者的播放量总和,用哈希表 $d$ 记录每个创作者播放量最大的视频的下标。 @@ -69,10 +67,6 @@ id 为 "b" 和 "c" 的视频都满足播放量最高的条件。 -### **Python3** - - - ```python class Solution: def mostPopularCreator( @@ -88,10 +82,6 @@ class Solution: return [[c, ids[d[c]]] for c, x in cnt.items() if x == mx] ``` -### **Java** - - - ```java class Solution { public List> mostPopularCreator(String[] creators, String[] ids, int[] views) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func mostPopularCreator(creators []string, ids []string, views []int) (ans [][]string) { cnt := map[string]int{} @@ -183,8 +169,6 @@ func mostPopularCreator(creators []string, ids []string, views []int) (ans [][]s } ``` -### **TypeScript** - ```ts function mostPopularCreator(creators: string[], ids: string[], views: number[]): string[][] { const cnt: Map = new Map(); @@ -208,10 +192,6 @@ function mostPopularCreator(creators: string[], ids: string[], views: number[]): } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2456.Most Popular Video Creator/README_EN.md b/solution/2400-2499/2456.Most Popular Video Creator/README_EN.md index 09010332771e4..8b7077027e94c 100644 --- a/solution/2400-2499/2456.Most Popular Video Creator/README_EN.md +++ b/solution/2400-2499/2456.Most Popular Video Creator/README_EN.md @@ -53,7 +53,7 @@ Since "b" is lexicographically smaller than "c", it is inclu ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We traverse the three arrays, use a hash table $cnt$ to count the total play count for each creator, and use a hash table $d$ to record the index of the video with the highest play count for each creator. @@ -63,8 +63,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def mostPopularCreator( @@ -80,8 +78,6 @@ class Solution: return [[c, ids[d[c]]] for c, x in cnt.items() if x == mx] ``` -### **Java** - ```java class Solution { public List> mostPopularCreator(String[] creators, String[] ids, int[] views) { @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +139,6 @@ public: }; ``` -### **Go** - ```go func mostPopularCreator(creators []string, ids []string, views []int) (ans [][]string) { cnt := map[string]int{} @@ -173,8 +165,6 @@ func mostPopularCreator(creators []string, ids []string, views []int) (ans [][]s } ``` -### **TypeScript** - ```ts function mostPopularCreator(creators: string[], ids: string[], views: number[]): string[][] { const cnt: Map = new Map(); @@ -198,10 +188,6 @@ function mostPopularCreator(creators: string[], ids: string[], views: number[]): } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2457.Minimum Addition to Make Integer Beautiful/README.md b/solution/2400-2499/2457.Minimum Addition to Make Integer Beautiful/README.md index fe69348449923..6d71a923f38f6 100644 --- a/solution/2400-2499/2457.Minimum Addition to Make Integer Beautiful/README.md +++ b/solution/2400-2499/2457.Minimum Addition to Make Integer Beautiful/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们定义函数 $f(x)$ 表示一个整数 $x$ 的每一位数字之和,那么题目求的是 $f(n + x) \leq target$ 的最小非负整数 $x$。 @@ -71,10 +69,6 @@ $$ -### **Python3** - - - ```python class Solution: def makeIntegerBeautiful(self, n: int, target: int) -> int: @@ -96,10 +90,6 @@ class Solution: return x ``` -### **Java** - - - ```java class Solution { public long makeIntegerBeautiful(long n, int target) { @@ -127,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func makeIntegerBeautiful(n int64, target int) (x int64) { f := func(x int64) (y int) { @@ -181,8 +167,6 @@ func makeIntegerBeautiful(n int64, target int) (x int64) { } ``` -### **TypeScript** - ```ts function makeIntegerBeautiful(n: number, target: number): number { const f = (x: number): number => { @@ -207,10 +191,6 @@ function makeIntegerBeautiful(n: number, target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2457.Minimum Addition to Make Integer Beautiful/README_EN.md b/solution/2400-2499/2457.Minimum Addition to Make Integer Beautiful/README_EN.md index c579ebd323f0e..a10859351bd25 100644 --- a/solution/2400-2499/2457.Minimum Addition to Make Integer Beautiful/README_EN.md +++ b/solution/2400-2499/2457.Minimum Addition to Make Integer Beautiful/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Greedy Algorithm** +### Solution 1: Greedy Algorithm We define a function $f(x)$ to represent the sum of the digits of an integer $x$. The problem is to find the minimum non-negative integer $x$ such that $f(n + x) \leq target$. @@ -69,8 +69,6 @@ The time complexity is $O(\log^2 n)$, where $n$ is the integer given in the prob -### **Python3** - ```python class Solution: def makeIntegerBeautiful(self, n: int, target: int) -> int: @@ -92,8 +90,6 @@ class Solution: return x ``` -### **Java** - ```java class Solution { public long makeIntegerBeautiful(long n, int target) { @@ -121,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +146,6 @@ public: }; ``` -### **Go** - ```go func makeIntegerBeautiful(n int64, target int) (x int64) { f := func(x int64) (y int) { @@ -175,8 +167,6 @@ func makeIntegerBeautiful(n int64, target int) (x int64) { } ``` -### **TypeScript** - ```ts function makeIntegerBeautiful(n: number, target: number): number { const f = (x: number): number => { @@ -201,10 +191,6 @@ function makeIntegerBeautiful(n: number, target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2458.Height of Binary Tree After Subtree Removal Queries/README.md b/solution/2400-2499/2458.Height of Binary Tree After Subtree Removal Queries/README.md index 1ff6cfd24bc69..13b7dbe4c1ceb 100644 --- a/solution/2400-2499/2458.Height of Binary Tree After Subtree Removal Queries/README.md +++ b/solution/2400-2499/2458.Height of Binary Tree After Subtree Removal Queries/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:两次 DFS** +### 方法一:两次 DFS 我们先通过一次 DFS 遍历的深度,存放在哈希表 $d$ 中,其中 $d[x]$ 表示节点 $x$ 的深度。 @@ -95,10 +93,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -130,10 +124,6 @@ class Solution: return [res[v] for v in queries] ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -188,8 +178,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -229,8 +217,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -271,16 +257,6 @@ func treeQueries(root *TreeNode, queries []int) (ans []int) { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2458.Height of Binary Tree After Subtree Removal Queries/README_EN.md b/solution/2400-2499/2458.Height of Binary Tree After Subtree Removal Queries/README_EN.md index 1350ad64d1175..a51106971e837 100644 --- a/solution/2400-2499/2458.Height of Binary Tree After Subtree Removal Queries/README_EN.md +++ b/solution/2400-2499/2458.Height of Binary Tree After Subtree Removal Queries/README_EN.md @@ -59,7 +59,7 @@ The height of the tree is 2 (The path 1 -> 3 -> 2). ## Solutions -**Solution 1: Two DFS Traversals** +### Solution 1: Two DFS Traversals First, we perform a DFS traversal to determine the depth of each node, which we store in a hash table $d$, where $d[x]$ represents the depth of node $x$. @@ -85,8 +85,6 @@ The time complexity is $O(n+m)$, and the space complexity is $O(n)$. Here, $n$ a -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -118,8 +116,6 @@ class Solution: return [res[v] for v in queries] ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -174,8 +170,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -215,8 +209,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -257,16 +249,6 @@ func treeQueries(root *TreeNode, queries []int) (ans []int) { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2459.Sort Array by Moving Items to Empty Space/README.md b/solution/2400-2499/2459.Sort Array by Moving Items to Empty Space/README.md index c67331252bb77..df29f53ab563e 100644 --- a/solution/2400-2499/2459.Sort Array by Moving Items to Empty Space/README.md +++ b/solution/2400-2499/2459.Sort Array by Moving Items to Empty Space/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:置换环** +### 方法一:置换环 一个长度为 $m$ 的置换环,如果 $0$ 在环中,那么交换次数为 $m-1$,否则交换次数为 $m+1$。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def sortArray(self, nums: List[int]) -> int: @@ -107,10 +101,6 @@ class Solution: return min(a, b) ``` -### **Java** - - - ```java class Solution { public int sortArray(int[] nums) { @@ -147,8 +137,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -180,8 +168,6 @@ public: }; ``` -### **Go** - ```go func sortArray(nums []int) int { n := len(nums) @@ -215,16 +201,6 @@ func sortArray(nums []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2459.Sort Array by Moving Items to Empty Space/README_EN.md b/solution/2400-2499/2459.Sort Array by Moving Items to Empty Space/README_EN.md index 24d72bfdd536a..626241be39e96 100644 --- a/solution/2400-2499/2459.Sort Array by Moving Items to Empty Space/README_EN.md +++ b/solution/2400-2499/2459.Sort Array by Moving Items to Empty Space/README_EN.md @@ -63,7 +63,7 @@ It can be proven that 2 is the minimum number of operations needed. ## Solutions -**Solution 1: Permutation Cycle** +### Solution 1: Permutation Cycle For a permutation cycle of length $m$, if $0$ is in the cycle, the number of swaps is $m-1$; otherwise, the number of swaps is $m+1$. @@ -75,8 +75,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def sortArray(self, nums: List[int]) -> int: @@ -100,8 +98,6 @@ class Solution: return min(a, b) ``` -### **Java** - ```java class Solution { public int sortArray(int[] nums) { @@ -138,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +165,6 @@ public: }; ``` -### **Go** - ```go func sortArray(nums []int) int { n := len(nums) @@ -206,16 +198,6 @@ func sortArray(nums []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2460.Apply Operations to an Array/README.md b/solution/2400-2499/2460.Apply Operations to an Array/README.md index 21fb3e96cf7a0..cd0ff8176afb8 100644 --- a/solution/2400-2499/2460.Apply Operations to an Array/README.md +++ b/solution/2400-2499/2460.Apply Operations to an Array/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们直接根据题意模拟即可。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def applyOperations(self, nums: List[int]) -> List[int]: @@ -96,10 +90,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] applyOperations(int[] nums) { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +135,6 @@ public: }; ``` -### **Go** - ```go func applyOperations(nums []int) []int { n := len(nums) @@ -170,8 +156,6 @@ func applyOperations(nums []int) []int { } ``` -### **TypeScript** - ```ts function applyOperations(nums: number[]): number[] { const n = nums.length; @@ -192,8 +176,6 @@ function applyOperations(nums: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn apply_operations(nums: Vec) -> Vec { @@ -219,10 +201,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2460.Apply Operations to an Array/README_EN.md b/solution/2400-2499/2460.Apply Operations to an Array/README_EN.md index 8140f1655d73a..008b6f3327883 100644 --- a/solution/2400-2499/2460.Apply Operations to an Array/README_EN.md +++ b/solution/2400-2499/2460.Apply Operations to an Array/README_EN.md @@ -55,7 +55,7 @@ After that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0] ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can directly simulate according to the problem description. @@ -69,8 +69,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. Igno -### **Python3** - ```python class Solution: def applyOperations(self, nums: List[int]) -> List[int]: @@ -88,8 +86,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] applyOperations(int[] nums) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +131,6 @@ public: }; ``` -### **Go** - ```go func applyOperations(nums []int) []int { n := len(nums) @@ -160,8 +152,6 @@ func applyOperations(nums []int) []int { } ``` -### **TypeScript** - ```ts function applyOperations(nums: number[]): number[] { const n = nums.length; @@ -182,8 +172,6 @@ function applyOperations(nums: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn apply_operations(nums: Vec) -> Vec { @@ -209,10 +197,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2461.Maximum Sum of Distinct Subarrays With Length K/README.md b/solution/2400-2499/2461.Maximum Sum of Distinct Subarrays With Length K/README.md index edfb84ecd8d05..6afb6a58779ea 100644 --- a/solution/2400-2499/2461.Maximum Sum of Distinct Subarrays With Length K/README.md +++ b/solution/2400-2499/2461.Maximum Sum of Distinct Subarrays With Length K/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:滑动窗口 + 哈希表** +### 方法一:滑动窗口 + 哈希表 我们维护一个长度为 $k$ 的滑动窗口,用哈希表 $cnt$ 记录窗口中每个数字出现的次数,用变量 $s$ 记录窗口中所有数字的和。每次滑动窗口,如果窗口中的数字都不重复,那么更新答案。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def maximumSubarraySum(self, nums: List[int], k: int) -> int: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long maximumSubarraySum(int[] nums, int k) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +135,6 @@ public: }; ``` -### **Go** - ```go func maximumSubarraySum(nums []int, k int) (ans int64) { n := len(nums) @@ -177,8 +163,6 @@ func maximumSubarraySum(nums []int, k int) (ans int64) { } ``` -### **TypeScript** - ```ts function maximumSubarraySum(nums: number[], k: number): number { const n = nums.length; @@ -205,10 +189,6 @@ function maximumSubarraySum(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2461.Maximum Sum of Distinct Subarrays With Length K/README_EN.md b/solution/2400-2499/2461.Maximum Sum of Distinct Subarrays With Length K/README_EN.md index 1f55b2733185a..f7e70b72ecf8a 100644 --- a/solution/2400-2499/2461.Maximum Sum of Distinct Subarrays With Length K/README_EN.md +++ b/solution/2400-2499/2461.Maximum Sum of Distinct Subarrays With Length K/README_EN.md @@ -50,7 +50,7 @@ We return 0 because no subarrays meet the conditions. ## Solutions -**Solution 1: Sliding Window + Hash Table** +### Solution 1: Sliding Window + Hash Table We maintain a sliding window of length $k$, use a hash table $cnt$ to record the count of each number in the window, and use a variable $s$ to record the sum of all numbers in the window. Each time we slide the window, if all numbers in the window are unique, we update the answer. @@ -58,8 +58,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maximumSubarraySum(self, nums: List[int], k: int) -> int: @@ -78,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long maximumSubarraySum(int[] nums, int k) { @@ -107,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +133,6 @@ public: }; ``` -### **Go** - ```go func maximumSubarraySum(nums []int, k int) (ans int64) { n := len(nums) @@ -169,8 +161,6 @@ func maximumSubarraySum(nums []int, k int) (ans int64) { } ``` -### **TypeScript** - ```ts function maximumSubarraySum(nums: number[], k: number): number { const n = nums.length; @@ -197,10 +187,6 @@ function maximumSubarraySum(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2462.Total Cost to Hire K Workers/README.md b/solution/2400-2499/2462.Total Cost to Hire K Workers/README.md index 57db33e154e93..9ab1b0445fb55 100644 --- a/solution/2400-2499/2462.Total Cost to Hire K Workers/README.md +++ b/solution/2400-2499/2462.Total Cost to Hire K Workers/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:优先队列(小根堆)** +### 方法一:优先队列(小根堆) 我们用一个优先队列(小根堆)维护当前的候选工人,用变量 $i$ 和 $j$ 标记最前面工人的最大小标和最后面工人的最小下标。初始时 $i = candidates - 1$,而 $j = n - candidates$。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def totalCost(self, costs: List[int], k: int, candidates: int) -> int: @@ -107,10 +101,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long totalCost(int[] costs, int k, int candidates) { @@ -151,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp using pii = pair; @@ -186,8 +174,6 @@ public: }; ``` -### **Go** - ```go func totalCost(costs []int, k int, candidates int) int64 { q := hp{} @@ -233,16 +219,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2462.Total Cost to Hire K Workers/README_EN.md b/solution/2400-2499/2462.Total Cost to Hire K Workers/README_EN.md index bee12e8647093..33039db8683fd 100644 --- a/solution/2400-2499/2462.Total Cost to Hire K Workers/README_EN.md +++ b/solution/2400-2499/2462.Total Cost to Hire K Workers/README_EN.md @@ -58,7 +58,7 @@ The total hiring cost is 4. ## Solutions -**Solution 1: Priority Queue (Min Heap)** +### Solution 1: Priority Queue (Min Heap) We maintain a priority queue (min heap) for the current candidate workers, and use variables $i$ and $j$ to mark the minimum index of the frontmost worker and the minimum index of the rearmost worker. Initially, $i = \text{candidates} - 1$ and $j = n - \text{candidates}$. @@ -72,8 +72,6 @@ The time complexity is $O(n \times \log n)$, where $n$ is the length of the arra -### **Python3** - ```python class Solution: def totalCost(self, costs: List[int], k: int, candidates: int) -> int: @@ -101,8 +99,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long totalCost(int[] costs, int k, int candidates) { @@ -143,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp using pii = pair; @@ -178,8 +172,6 @@ public: }; ``` -### **Go** - ```go func totalCost(costs []int, k int, candidates int) int64 { q := hp{} @@ -225,16 +217,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2463.Minimum Total Distance Traveled/README.md b/solution/2400-2499/2463.Minimum Total Distance Traveled/README.md index 00290b54b69bc..02f359a302730 100644 --- a/solution/2400-2499/2463.Minimum Total Distance Traveled/README.md +++ b/solution/2400-2499/2463.Minimum Total Distance Traveled/README.md @@ -73,9 +73,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们先对机器人和工厂进行升序排列。然后定义函数 $dfs(i, j)$ 表示从第 $i$ 个机器人开始,第 $j$ 个工厂开始维修的最小总移动距离。 @@ -85,10 +83,6 @@ -### **Python3** - - - ```python class Solution: def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int: @@ -114,10 +108,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private long[][] f; @@ -158,8 +148,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -188,8 +176,6 @@ public: }; ``` -### **Go** - ```go func minimumTotalDistance(robot []int, factory [][]int) int64 { sort.Ints(robot) @@ -232,16 +218,6 @@ func abs(x int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2463.Minimum Total Distance Traveled/README_EN.md b/solution/2400-2499/2463.Minimum Total Distance Traveled/README_EN.md index 34f599f33e938..063cf4dbfb958 100644 --- a/solution/2400-2499/2463.Minimum Total Distance Traveled/README_EN.md +++ b/solution/2400-2499/2463.Minimum Total Distance Traveled/README_EN.md @@ -65,7 +65,7 @@ The total distance is |2 - 1| + |(-2) - (-1)| = 2. It can be shown that we canno ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search First, we sort the robots and factories in ascending order. Then we define a function $dfs(i, j)$ to represent the minimum total moving distance starting from the $i$-th robot and the $j$-th factory. @@ -75,8 +75,6 @@ The time complexity is $O(m^2 \times n)$, and the space complexity is $O(m \time -### **Python3** - ```python class Solution: def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int: @@ -102,8 +100,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private long[][] f; @@ -144,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -174,8 +168,6 @@ public: }; ``` -### **Go** - ```go func minimumTotalDistance(robot []int, factory [][]int) int64 { sort.Ints(robot) @@ -218,16 +210,6 @@ func abs(x int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2464.Minimum Subarrays in a Valid Split/README.md b/solution/2400-2499/2464.Minimum Subarrays in a Valid Split/README.md index e4c44277555ec..9b7c3a1277ddc 100644 --- a/solution/2400-2499/2464.Minimum Subarrays in a Valid Split/README.md +++ b/solution/2400-2499/2464.Minimum Subarrays in a Valid Split/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i)$ 表示从下标 $i$ 开始的最小分割数。对于下标 $i$,我们可以枚举所有的分割点 $j$,即 $i \leq j \lt n$,其中 $n$ 为数组长度。对于每个分割点 $j$,我们需要判断 $nums[i]$ 和 $nums[j]$ 的最大公约数是否大于 $1$,如果大于 $1$,则可以进行分割,此时分割数为 $1 + dfs(j + 1)$,否则分割数为 $+\infty$。最后我们取所有分割数的最小值即可。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def validSubarraySplit(self, nums: List[int]) -> int: @@ -99,10 +93,6 @@ class Solution: return ans if ans < inf else -1 ``` -### **Java** - - - ```java class Solution { private int n; @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go func validSubarraySplit(nums []int) int { n := len(nums) @@ -207,16 +193,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2464.Minimum Subarrays in a Valid Split/README_EN.md b/solution/2400-2499/2464.Minimum Subarrays in a Valid Split/README_EN.md index dfe724787e4e4..ff28c8975c582 100644 --- a/solution/2400-2499/2464.Minimum Subarrays in a Valid Split/README_EN.md +++ b/solution/2400-2499/2464.Minimum Subarrays in a Valid Split/README_EN.md @@ -63,7 +63,7 @@ It can be proved that 2 is the minimum number of subarrays that we can obtain in ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We design a function $dfs(i)$ to represent the minimum number of partitions starting from index $i$. For index $i$, we can enumerate all partition points $j$, i.e., $i \leq j < n$, where $n$ is the length of the array. For each partition point $j$, we need to determine whether the greatest common divisor of $nums[i]$ and $nums[j]$ is greater than $1$. If it is greater than $1$, we can partition, and the number of partitions is $1 + dfs(j + 1)$; otherwise, the number of partitions is $+\infty$. Finally, we take the minimum of all partition numbers. @@ -71,8 +71,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ i -### **Python3** - ```python class Solution: def validSubarraySplit(self, nums: List[int]) -> int: @@ -92,8 +90,6 @@ class Solution: return ans if ans < inf else -1 ``` -### **Java** - ```java class Solution { private int n; @@ -132,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +153,6 @@ public: }; ``` -### **Go** - ```go func validSubarraySplit(nums []int) int { n := len(nums) @@ -198,16 +190,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2465.Number of Distinct Averages/README.md b/solution/2400-2499/2465.Number of Distinct Averages/README.md index 71c8fc0180926..f7ec38234d22e 100644 --- a/solution/2400-2499/2465.Number of Distinct Averages/README.md +++ b/solution/2400-2499/2465.Number of Distinct Averages/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 题目中要求每次找到数组 $nums$ 中的最小值和最大值,然后删除它们,再计算删除两数的平均值。因此,我们可以先对数组 $nums$ 进行排序,然后每次取数组的首尾元素,计算它们的和,用哈希表或数组 $cnt$ 记录每个和出现的次数,最后统计不同的和的个数即可。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def distinctAverages(self, nums: List[int]) -> int: @@ -80,24 +74,6 @@ class Solution: return len(set(nums[i] + nums[-i - 1] for i in range(len(nums) >> 1))) ``` -```python -class Solution: - def distinctAverages(self, nums: List[int]) -> int: - nums.sort() - ans = 0 - cnt = Counter() - for i in range(len(nums) >> 1): - x = nums[i] + nums[-i - 1] - cnt[x] += 1 - if cnt[x] == 1: - ans += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int distinctAverages(int[] nums) { @@ -112,6 +88,88 @@ class Solution { } ``` +```cpp +class Solution { +public: + int distinctAverages(vector& nums) { + sort(nums.begin(), nums.end()); + unordered_set s; + int n = nums.size(); + for (int i = 0; i < n >> 1; ++i) { + s.insert(nums[i] + nums[n - i - 1]); + } + return s.size(); + } +}; +``` + +```go +func distinctAverages(nums []int) (ans int) { + sort.Ints(nums) + n := len(nums) + s := map[int]struct{}{} + for i := 0; i < n>>1; i++ { + s[nums[i]+nums[n-i-1]] = struct{}{} + } + return len(s) +} +``` + +```ts +function distinctAverages(nums: number[]): number { + nums.sort((a, b) => a - b); + const s: Set = new Set(); + const n = nums.length; + for (let i = 0; i < n >> 1; ++i) { + s.add(nums[i] + nums[n - i - 1]); + } + return s.size; +} +``` + +```rust +impl Solution { + pub fn distinct_averages(nums: Vec) -> i32 { + let mut nums = nums; + nums.sort(); + let n = nums.len(); + let mut cnt = vec![0; 201]; + let mut ans = 0; + + for i in 0..n >> 1 { + let x = (nums[i] + nums[n - i - 1]) as usize; + cnt[x] += 1; + + if cnt[x] == 1 { + ans += 1; + } + } + + ans + } +} +``` + + + +### 方法二 + + + +```python +class Solution: + def distinctAverages(self, nums: List[int]) -> int: + nums.sort() + ans = 0 + cnt = Counter() + for i in range(len(nums) >> 1): + x = nums[i] + nums[-i - 1] + cnt[x] += 1 + if cnt[x] == 1: + ans += 1 + return ans +``` + ```java class Solution { public int distinctAverages(int[] nums) { @@ -129,23 +187,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int distinctAverages(vector& nums) { - sort(nums.begin(), nums.end()); - unordered_set s; - int n = nums.size(); - for (int i = 0; i < n >> 1; ++i) { - s.insert(nums[i] + nums[n - i - 1]); - } - return s.size(); - } -}; -``` - ```cpp class Solution { public: @@ -164,20 +205,6 @@ public: }; ``` -### **Go** - -```go -func distinctAverages(nums []int) (ans int) { - sort.Ints(nums) - n := len(nums) - s := map[int]struct{}{} - for i := 0; i < n>>1; i++ { - s[nums[i]+nums[n-i-1]] = struct{}{} - } - return len(s) -} -``` - ```go func distinctAverages(nums []int) (ans int) { sort.Ints(nums) @@ -194,20 +221,6 @@ func distinctAverages(nums []int) (ans int) { } ``` -### **TypeScript** - -```ts -function distinctAverages(nums: number[]): number { - nums.sort((a, b) => a - b); - const s: Set = new Set(); - const n = nums.length; - for (let i = 0; i < n >> 1; ++i) { - s.add(nums[i] + nums[n - i - 1]); - } - return s.size; -} -``` - ```ts function distinctAverages(nums: number[]): number { nums.sort((a, b) => a - b); @@ -223,31 +236,6 @@ function distinctAverages(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn distinct_averages(nums: Vec) -> i32 { - let mut nums = nums; - nums.sort(); - let n = nums.len(); - let mut cnt = vec![0; 201]; - let mut ans = 0; - - for i in 0..n >> 1 { - let x = (nums[i] + nums[n - i - 1]) as usize; - cnt[x] += 1; - - if cnt[x] == 1 { - ans += 1; - } - } - - ans - } -} -``` - ```rust use std::collections::HashMap; @@ -273,6 +261,12 @@ impl Solution { } ``` + + +### 方法三 + + + ```rust use std::collections::HashSet; @@ -300,10 +294,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2465.Number of Distinct Averages/README_EN.md b/solution/2400-2499/2465.Number of Distinct Averages/README_EN.md index 65134e6db7ac9..5dcdd88ccda57 100644 --- a/solution/2400-2499/2465.Number of Distinct Averages/README_EN.md +++ b/solution/2400-2499/2465.Number of Distinct Averages/README_EN.md @@ -57,7 +57,7 @@ There is only one average to be calculated after removing 1 and 100, so we retur ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting The problem requires us to find the minimum and maximum values in the array $nums$ each time, delete them, and then calculate the average of the two deleted numbers. Therefore, we can first sort the array $nums$, then take the first and last elements of the array each time, calculate their sum, use a hash table or array $cnt$ to record the number of times each sum appears, and finally count the number of different sums. @@ -65,8 +65,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def distinctAverages(self, nums: List[int]) -> int: @@ -74,22 +72,6 @@ class Solution: return len(set(nums[i] + nums[-i - 1] for i in range(len(nums) >> 1))) ``` -```python -class Solution: - def distinctAverages(self, nums: List[int]) -> int: - nums.sort() - ans = 0 - cnt = Counter() - for i in range(len(nums) >> 1): - x = nums[i] + nums[-i - 1] - cnt[x] += 1 - if cnt[x] == 1: - ans += 1 - return ans -``` - -### **Java** - ```java class Solution { public int distinctAverages(int[] nums) { @@ -104,6 +86,88 @@ class Solution { } ``` +```cpp +class Solution { +public: + int distinctAverages(vector& nums) { + sort(nums.begin(), nums.end()); + unordered_set s; + int n = nums.size(); + for (int i = 0; i < n >> 1; ++i) { + s.insert(nums[i] + nums[n - i - 1]); + } + return s.size(); + } +}; +``` + +```go +func distinctAverages(nums []int) (ans int) { + sort.Ints(nums) + n := len(nums) + s := map[int]struct{}{} + for i := 0; i < n>>1; i++ { + s[nums[i]+nums[n-i-1]] = struct{}{} + } + return len(s) +} +``` + +```ts +function distinctAverages(nums: number[]): number { + nums.sort((a, b) => a - b); + const s: Set = new Set(); + const n = nums.length; + for (let i = 0; i < n >> 1; ++i) { + s.add(nums[i] + nums[n - i - 1]); + } + return s.size; +} +``` + +```rust +impl Solution { + pub fn distinct_averages(nums: Vec) -> i32 { + let mut nums = nums; + nums.sort(); + let n = nums.len(); + let mut cnt = vec![0; 201]; + let mut ans = 0; + + for i in 0..n >> 1 { + let x = (nums[i] + nums[n - i - 1]) as usize; + cnt[x] += 1; + + if cnt[x] == 1 { + ans += 1; + } + } + + ans + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def distinctAverages(self, nums: List[int]) -> int: + nums.sort() + ans = 0 + cnt = Counter() + for i in range(len(nums) >> 1): + x = nums[i] + nums[-i - 1] + cnt[x] += 1 + if cnt[x] == 1: + ans += 1 + return ans +``` + ```java class Solution { public int distinctAverages(int[] nums) { @@ -121,23 +185,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int distinctAverages(vector& nums) { - sort(nums.begin(), nums.end()); - unordered_set s; - int n = nums.size(); - for (int i = 0; i < n >> 1; ++i) { - s.insert(nums[i] + nums[n - i - 1]); - } - return s.size(); - } -}; -``` - ```cpp class Solution { public: @@ -156,20 +203,6 @@ public: }; ``` -### **Go** - -```go -func distinctAverages(nums []int) (ans int) { - sort.Ints(nums) - n := len(nums) - s := map[int]struct{}{} - for i := 0; i < n>>1; i++ { - s[nums[i]+nums[n-i-1]] = struct{}{} - } - return len(s) -} -``` - ```go func distinctAverages(nums []int) (ans int) { sort.Ints(nums) @@ -186,20 +219,6 @@ func distinctAverages(nums []int) (ans int) { } ``` -### **TypeScript** - -```ts -function distinctAverages(nums: number[]): number { - nums.sort((a, b) => a - b); - const s: Set = new Set(); - const n = nums.length; - for (let i = 0; i < n >> 1; ++i) { - s.add(nums[i] + nums[n - i - 1]); - } - return s.size; -} -``` - ```ts function distinctAverages(nums: number[]): number { nums.sort((a, b) => a - b); @@ -215,31 +234,6 @@ function distinctAverages(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn distinct_averages(nums: Vec) -> i32 { - let mut nums = nums; - nums.sort(); - let n = nums.len(); - let mut cnt = vec![0; 201]; - let mut ans = 0; - - for i in 0..n >> 1 { - let x = (nums[i] + nums[n - i - 1]) as usize; - cnt[x] += 1; - - if cnt[x] == 1 { - ans += 1; - } - } - - ans - } -} -``` - ```rust use std::collections::HashMap; @@ -265,6 +259,12 @@ impl Solution { } ``` + + +### Solution 3 + + + ```rust use std::collections::HashSet; @@ -292,10 +292,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2466.Count Ways To Build Good Strings/README.md b/solution/2400-2499/2466.Count Ways To Build Good Strings/README.md index dd2285616479f..9a5f9b8f39c6b 100644 --- a/solution/2400-2499/2466.Count Ways To Build Good Strings/README.md +++ b/solution/2400-2499/2466.Count Ways To Build Good Strings/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i)$ 表示从第 $i$ 位开始构造的好字符串的个数,答案即为 $dfs(0)$。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: @@ -87,10 +81,6 @@ class Solution: return dfs(0) ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +140,6 @@ public: }; ``` -### **Go** - ```go func countGoodStrings(low int, high int, zero int, one int) int { f := make([]int, high+1) @@ -182,16 +168,6 @@ func countGoodStrings(low int, high int, zero int, one int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2466.Count Ways To Build Good Strings/README_EN.md b/solution/2400-2499/2466.Count Ways To Build Good Strings/README_EN.md index acb87ce53a0aa..c84d05cc1cded 100644 --- a/solution/2400-2499/2466.Count Ways To Build Good Strings/README_EN.md +++ b/solution/2400-2499/2466.Count Ways To Build Good Strings/README_EN.md @@ -47,7 +47,7 @@ All binary strings from "000" to "111" are good strings in t ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We design a function $dfs(i)$ to represent the number of good strings constructed starting from the $i$-th position. The answer is $dfs(0)$. @@ -62,8 +62,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n = hi -### **Python3** - ```python class Solution: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: @@ -81,8 +79,6 @@ class Solution: return dfs(0) ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -121,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +138,6 @@ public: }; ``` -### **Go** - ```go func countGoodStrings(low int, high int, zero int, one int) int { f := make([]int, high+1) @@ -174,16 +166,6 @@ func countGoodStrings(low int, high int, zero int, one int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2467.Most Profitable Path in a Tree/README.md b/solution/2400-2499/2467.Most Profitable Path in a Tree/README.md index b5a922280de1b..403b76ea67c59 100644 --- a/solution/2400-2499/2467.Most Profitable Path in a Tree/README.md +++ b/solution/2400-2499/2467.Most Profitable Path in a Tree/README.md @@ -82,9 +82,7 @@ Alice 按照路径 0->1 移动,同时 Bob 按照路径 1->0 移动。 ## 解法 - - -**方法一:两次 DFS** +### 方法一:两次 DFS 根据题意,我们可以知道,Bob 的移动路径是固定的,即从节点 $bob$ 出发,最终到达节点 $0$。因此,我们可以先跑一遍 DFS,求出 Bob 到达每个节点的时间,记在数组 $ts$ 中。 @@ -100,10 +98,6 @@ Alice 按照路径 0->1 移动,同时 Bob 按照路径 1->0 移动。 -### **Python3** - - - ```python class Solution: def mostProfitablePath( @@ -145,10 +139,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -207,8 +197,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -255,8 +243,6 @@ public: }; ``` -### **Go** - ```go func mostProfitablePath(edges [][]int, bob int, amount []int) int { n := len(edges) + 1 @@ -309,16 +295,6 @@ func mostProfitablePath(edges [][]int, bob int, amount []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2467.Most Profitable Path in a Tree/README_EN.md b/solution/2400-2499/2467.Most Profitable Path in a Tree/README_EN.md index 8ade7690df3b1..c1067c2e05f1a 100644 --- a/solution/2400-2499/2467.Most Profitable Path in a Tree/README_EN.md +++ b/solution/2400-2499/2467.Most Profitable Path in a Tree/README_EN.md @@ -76,7 +76,7 @@ Thus, Alice opens the gate at node 0 only. Hence, her net income is -7280. ## Solutions -**Solution 1: Two DFS Traversals** +### Solution 1: Two DFS Traversals According to the problem, we know that Bob's moving path is fixed, that is, starting from node $bob$ and finally reaching node $0$. Therefore, we can first run a DFS to find out the time it takes for Bob to reach each node, which we record in the array $ts$. @@ -92,8 +92,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def mostProfitablePath( @@ -135,8 +133,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -195,8 +191,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -243,8 +237,6 @@ public: }; ``` -### **Go** - ```go func mostProfitablePath(edges [][]int, bob int, amount []int) int { n := len(edges) + 1 @@ -297,16 +289,6 @@ func mostProfitablePath(edges [][]int, bob int, amount []int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2468.Split Message Based on Limit/README.md b/solution/2400-2499/2468.Split Message Based on Limit/README.md index b15dfe739c73b..758f2426ba483 100644 --- a/solution/2400-2499/2468.Split Message Based on Limit/README.md +++ b/solution/2400-2499/2468.Split Message Based on Limit/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:枚举分段数量 + 模拟** +### 方法一:枚举分段数量 + 模拟 我们设字符串 `message` 的长度为 $n$,分段数量为 $k$。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def splitMessage(self, message: str, limit: int) -> List[str]: @@ -92,10 +86,6 @@ class Solution: return [] ``` -### **Java** - - - ```java class Solution { public String[] splitMessage(String message, int limit) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func splitMessage(message string, limit int) (ans []string) { n := len(message) @@ -180,16 +166,6 @@ func splitMessage(message string, limit int) (ans []string) { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2468.Split Message Based on Limit/README_EN.md b/solution/2400-2499/2468.Split Message Based on Limit/README_EN.md index 45cd5cbd506c3..a4849d2e98003 100644 --- a/solution/2400-2499/2468.Split Message Based on Limit/README_EN.md +++ b/solution/2400-2499/2468.Split Message Based on Limit/README_EN.md @@ -47,7 +47,7 @@ Under the given constraints, the string can be split into two parts: ## Solutions -**Solution 1: Enumerate the Number of Segments + Simulation** +### Solution 1: Enumerate the Number of Segments + Simulation We denote the length of the string `message` as $n$, and the number of segments as $k$. @@ -63,8 +63,6 @@ The time complexity is $O(n\times \log n)$, where $n$ is the length of the strin -### **Python3** - ```python class Solution: def splitMessage(self, message: str, limit: int) -> List[str]: @@ -86,8 +84,6 @@ class Solution: return [] ``` -### **Java** - ```java class Solution { public String[] splitMessage(String message, int limit) { @@ -116,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +140,6 @@ public: }; ``` -### **Go** - ```go func splitMessage(message string, limit int) (ans []string) { n := len(message) @@ -172,16 +164,6 @@ func splitMessage(message string, limit int) (ans []string) { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2469.Convert the Temperature/README.md b/solution/2400-2499/2469.Convert the Temperature/README.md index d3660c360a3c2..7d83d566ae3de 100644 --- a/solution/2400-2499/2469.Convert the Temperature/README.md +++ b/solution/2400-2499/2469.Convert the Temperature/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 直接根据题意模拟即可。 @@ -54,20 +52,12 @@ -### **Python3** - - - ```python class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, celsius * 1.8 + 32] ``` -### **Java** - - - ```java class Solution { public double[] convertTemperature(double celsius) { @@ -76,8 +66,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,24 +75,18 @@ public: }; ``` -### **Go** - ```go func convertTemperature(celsius float64) []float64 { return []float64{celsius + 273.15, celsius*1.8 + 32} } ``` -### **TypeScript** - ```ts function convertTemperature(celsius: number): number[] { return [celsius + 273.15, celsius * 1.8 + 32]; } ``` -### **Rust** - ```rust impl Solution { pub fn convert_temperature(celsius: f64) -> Vec { @@ -113,8 +95,6 @@ impl Solution { } ``` -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -128,10 +108,6 @@ double* convertTemperature(double celsius, int* returnSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2469.Convert the Temperature/README_EN.md b/solution/2400-2499/2469.Convert the Temperature/README_EN.md index 0c302a40f2b4b..fd14564b49743 100644 --- a/solution/2400-2499/2469.Convert the Temperature/README_EN.md +++ b/solution/2400-2499/2469.Convert the Temperature/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can directly simulate according to the problem description. @@ -51,16 +51,12 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, celsius * 1.8 + 32] ``` -### **Java** - ```java class Solution { public double[] convertTemperature(double celsius) { @@ -69,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -80,24 +74,18 @@ public: }; ``` -### **Go** - ```go func convertTemperature(celsius float64) []float64 { return []float64{celsius + 273.15, celsius*1.8 + 32} } ``` -### **TypeScript** - ```ts function convertTemperature(celsius: number): number[] { return [celsius + 273.15, celsius * 1.8 + 32]; } ``` -### **Rust** - ```rust impl Solution { pub fn convert_temperature(celsius: f64) -> Vec { @@ -106,8 +94,6 @@ impl Solution { } ``` -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -121,10 +107,6 @@ double* convertTemperature(double celsius, int* returnSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2470.Number of Subarrays With LCM Equal to K/README.md b/solution/2400-2499/2470.Number of Subarrays With LCM Equal to K/README.md index 75c8c2e895916..c3f396f57d9f5 100644 --- a/solution/2400-2499/2470.Number of Subarrays With LCM Equal to K/README.md +++ b/solution/2400-2499/2470.Number of Subarrays With LCM Equal to K/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 枚举每个数作为子数组的第一个数,然后枚举每个数作为子数组的最后一个数,计算这个子数组的最小公倍数,如果最小公倍数等于 $k$,则答案加一。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def subarrayLCM(self, nums: List[int], k: int) -> int: @@ -71,10 +65,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int subarrayLCM(int[] nums, int k) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func subarrayLCM(nums []int, k int) (ans int) { for i, a := range nums { @@ -154,16 +140,6 @@ func lcm(a, b int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2470.Number of Subarrays With LCM Equal to K/README_EN.md b/solution/2400-2499/2470.Number of Subarrays With LCM Equal to K/README_EN.md index 39d9f75ab0c14..563387a7f0ada 100644 --- a/solution/2400-2499/2470.Number of Subarrays With LCM Equal to K/README_EN.md +++ b/solution/2400-2499/2470.Number of Subarrays With LCM Equal to K/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration Enumerate each number as the first number of the subarray, and then enumerate each number as the last number of the subarray. Calculate the least common multiple of this subarray. If the least common multiple equals $k$, then increment the answer by one. @@ -49,8 +49,6 @@ The time complexity is $O(n^2)$. Here, $n$ is the length of the array. -### **Python3** - ```python class Solution: def subarrayLCM(self, nums: List[int], k: int) -> int: @@ -65,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int subarrayLCM(int[] nums, int k) { @@ -96,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func subarrayLCM(nums []int, k int) (ans int) { for i, a := range nums { @@ -146,16 +138,6 @@ func lcm(a, b int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2471.Minimum Number of Operations to Sort a Binary Tree by Level/README.md b/solution/2400-2499/2471.Minimum Number of Operations to Sort a Binary Tree by Level/README.md index fd9449671fd9e..27b4d5f3c4808 100644 --- a/solution/2400-2499/2471.Minimum Number of Operations to Sort a Binary Tree by Level/README.md +++ b/solution/2400-2499/2471.Minimum Number of Operations to Sort a Binary Tree by Level/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:BFS + 离散化 + 元素交换** +### 方法一:BFS + 离散化 + 元素交换 我们先通过 `BFS` 遍历二叉树,找到每一层的节点值,然后对每一层的节点值进行排序,如果排序后的节点值与原节点值不同,则说明需要交换元素,交换元素的次数即为该层需要的操作数。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -112,10 +106,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -184,8 +174,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -235,8 +223,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -290,8 +276,6 @@ func minimumOperations(root *TreeNode) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -336,8 +320,6 @@ function minimumOperations(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -397,10 +379,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2471.Minimum Number of Operations to Sort a Binary Tree by Level/README_EN.md b/solution/2400-2499/2471.Minimum Number of Operations to Sort a Binary Tree by Level/README_EN.md index 7cdbb239506f3..6bc665c7d5ac4 100644 --- a/solution/2400-2499/2471.Minimum Number of Operations to Sort a Binary Tree by Level/README_EN.md +++ b/solution/2400-2499/2471.Minimum Number of Operations to Sort a Binary Tree by Level/README_EN.md @@ -58,7 +58,7 @@ It can be proven that 3 is the minimum number of operations needed. ## Solutions -**Solution 1: BFS + Discretization + Element Swap** +### Solution 1: BFS + Discretization + Element Swap First, we traverse the binary tree using BFS to find the node values at each level. Then, we sort the node values at each level. If the sorted node values are different from the original node values, it means that we need to swap elements. The number of swaps is the number of operations needed at that level. @@ -66,8 +66,6 @@ The time complexity is $O(n \times \log n)$. Here, $n$ is the number of nodes in -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -107,8 +105,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -177,8 +173,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -228,8 +222,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -283,8 +275,6 @@ func minimumOperations(root *TreeNode) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -329,8 +319,6 @@ function minimumOperations(root: TreeNode | null): number { } ``` -### **Rust** - ```rust // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] @@ -390,10 +378,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2472.Maximum Number of Non-overlapping Palindrome Substrings/README.md b/solution/2400-2499/2472.Maximum Number of Non-overlapping Palindrome Substrings/README.md index 847cdc588cd6f..66f65960f1b6b 100644 --- a/solution/2400-2499/2472.Maximum Number of Non-overlapping Palindrome Substrings/README.md +++ b/solution/2400-2499/2472.Maximum Number of Non-overlapping Palindrome Substrings/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:预处理 + 记忆化搜索** +### 方法一:预处理 + 记忆化搜索 预处理字符串 $s$,得到 $dp[i][j]$ 表示字符串 $s[i,..j]$ 是否为回文串。 @@ -70,10 +68,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxPalindromes(self, s: str, k: int) -> int: @@ -97,10 +91,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private boolean[][] dp; @@ -146,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -177,8 +165,6 @@ public: }; ``` -### **Go** - ```go func maxPalindromes(s string, k int) int { n := len(s) @@ -217,16 +203,6 @@ func maxPalindromes(s string, k int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2472.Maximum Number of Non-overlapping Palindrome Substrings/README_EN.md b/solution/2400-2499/2472.Maximum Number of Non-overlapping Palindrome Substrings/README_EN.md index 28f62c59d3d7b..78df02894a3a6 100644 --- a/solution/2400-2499/2472.Maximum Number of Non-overlapping Palindrome Substrings/README_EN.md +++ b/solution/2400-2499/2472.Maximum Number of Non-overlapping Palindrome Substrings/README_EN.md @@ -45,7 +45,7 @@ It can be shown that we cannot find a selection with more than two valid substri ## Solutions -**Solution 1: Preprocessing + Memoization Search** +### Solution 1: Preprocessing + Memoization Search First, preprocess the string $s$ to get $dp[i][j]$, which represents whether the substring $s[i,..j]$ is a palindrome. @@ -64,8 +64,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ -### **Python3** - ```python class Solution: def maxPalindromes(self, s: str, k: int) -> int: @@ -89,8 +87,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private boolean[][] dp; @@ -136,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +161,6 @@ public: }; ``` -### **Go** - ```go func maxPalindromes(s string, k int) int { n := len(s) @@ -207,16 +199,6 @@ func maxPalindromes(s string, k int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2473.Minimum Cost to Buy Apples/README.md b/solution/2400-2499/2473.Minimum Cost to Buy Apples/README.md index 01e51402a1974..3736bf697901d 100644 --- a/solution/2400-2499/2473.Minimum Cost to Buy Apples/README.md +++ b/solution/2400-2499/2473.Minimum Cost to Buy Apples/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:堆优化版 Dijkstra 算法** +### 方法一:堆优化版 Dijkstra 算法 我们枚举起点,对于每个起点,使用 Dijkstra 算法求出到其他所有点的最短距离,更新最小值即可。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def minCost( @@ -98,10 +92,6 @@ class Solution: return [dijkstra(i) for i in range(n)] ``` -### **Java** - - - ```java class Solution { private int k; @@ -154,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; using pii = pair; @@ -201,8 +189,6 @@ public: }; ``` -### **Go** - ```go func minCost(n int, roads [][]int, appleCost []int, k int) []int64 { g := make([]pairs, n) @@ -258,16 +244,6 @@ func (a *pairs) Push(x any) { *a = append(*a, x.(pair)) } func (a *pairs) Pop() any { l := len(*a); t := (*a)[l-1]; *a = (*a)[:l-1]; return t } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2473.Minimum Cost to Buy Apples/README_EN.md b/solution/2400-2499/2473.Minimum Cost to Buy Apples/README_EN.md index 29cb6ca5d0042..a0bb41b00a566 100644 --- a/solution/2400-2499/2473.Minimum Cost to Buy Apples/README_EN.md +++ b/solution/2400-2499/2473.Minimum Cost to Buy Apples/README_EN.md @@ -50,7 +50,7 @@ ## Solutions -**Solution 1: Heap-optimized Dijkstra's Algorithm** +### Solution 1: Heap-optimized Dijkstra's Algorithm We enumerate the starting point, and for each starting point, we use Dijkstra's algorithm to find the shortest distance to all other points, and update the minimum value accordingly. @@ -58,8 +58,6 @@ The time complexity is $O(n \times m \times \log m)$, where $n$ and $m$ are the -### **Python3** - ```python class Solution: def minCost( @@ -87,8 +85,6 @@ class Solution: return [dijkstra(i) for i in range(n)] ``` -### **Java** - ```java class Solution { private int k; @@ -141,8 +137,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; using pii = pair; @@ -188,8 +182,6 @@ public: }; ``` -### **Go** - ```go func minCost(n int, roads [][]int, appleCost []int, k int) []int64 { g := make([]pairs, n) @@ -245,16 +237,6 @@ func (a *pairs) Push(x any) { *a = append(*a, x.(pair)) } func (a *pairs) Pop() any { l := len(*a); t := (*a)[l-1]; *a = (*a)[:l-1]; return t } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2474.Customers With Strictly Increasing Purchases/README.md b/solution/2400-2499/2474.Customers With Strictly Increasing Purchases/README.md index 62903cef9c3e3..00a16c74f188f 100644 --- a/solution/2400-2499/2474.Customers With Strictly Increasing Purchases/README.md +++ b/solution/2400-2499/2474.Customers With Strictly Increasing Purchases/README.md @@ -81,14 +81,10 @@ Orders 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -111,3 +107,5 @@ HAVING COUNT(DISTINCT rk) = 1; ``` + + diff --git a/solution/2400-2499/2474.Customers With Strictly Increasing Purchases/README_EN.md b/solution/2400-2499/2474.Customers With Strictly Increasing Purchases/README_EN.md index 0d65faf7d2612..d30b2d89f8756 100644 --- a/solution/2400-2499/2474.Customers With Strictly Increasing Purchases/README_EN.md +++ b/solution/2400-2499/2474.Customers With Strictly Increasing Purchases/README_EN.md @@ -80,9 +80,9 @@ Customer 3: The first year is 2017, and the last year is 2018 ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -106,3 +106,5 @@ HAVING COUNT(DISTINCT rk) = 1; ``` + + diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/README.md b/solution/2400-2499/2475.Number of Unequal Triplets in Array/README.md index 8535640ea0f5e..1773174027270 100644 --- a/solution/2400-2499/2475.Number of Unequal Triplets in Array/README.md +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/README.md @@ -53,36 +53,14 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 我们可以直接枚举所有的三元组 $(i, j, k)$,统计所有符合条件的数量。 时间复杂度 $O(n^3)$,其中 $n$ 为数组 $nums$ 的长度。空间复杂度 $O(1)$。 -**方法二:排序 + 枚举中间元素 + 二分查找** - -我们也可以先对数组 $nums$ 进行排序。 - -然后遍历 $nums$,枚举中间元素 $nums[j]$,利用二分查找,在 $nums[j]$ 左侧找到最近的下标 $i$,使得 $nums[i] \lt nums[j]$ 成立;在 $nums[j]$ 右侧找到最近的下标 $k$,使得 $nums[k] \gt nums[j]$ 成立。那么以 $nums[j]$ 作为中间元素,且符合条件的三元组数量为 $(i + 1) \times (n - k)$,累加到答案中。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 $nums$ 的长度。 - -**方法三:哈希表** - -我们还可以使用哈希表 $cnt$ 来统计数组 $nums$ 中每个元素的数量。 - -然后遍历哈希表 $cnt$,枚举中间元素的个数 $b$,左侧元素个数记为 $a$,那么右侧元素个数有 $c = n - a - b$,此时符合条件的三元组数量为 $a \times b \times c$,累加到答案中。接着更新 $a = a + b$,继续枚举中间元素的个数 $b$。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 - -### **Python3** - - - ```python class Solution: def unequalTriplets(self, nums: List[int]) -> int: @@ -97,35 +75,6 @@ class Solution: return ans ``` -```python -class Solution: - def unequalTriplets(self, nums: List[int]) -> int: - nums.sort() - ans, n = 0, len(nums) - for j in range(1, n - 1): - i = bisect_left(nums, nums[j], hi=j) - 1 - k = bisect_right(nums, nums[j], lo=j + 1) - ans += (i >= 0 and k < n) * (i + 1) * (n - k) - return ans -``` - -```python -class Solution: - def unequalTriplets(self, nums: List[int]) -> int: - cnt = Counter(nums) - n = len(nums) - ans = a = 0 - for b in cnt.values(): - c = n - a - b - ans += a * b * c - a += b - return ans -``` - -### **Java** - - - ```java class Solution { public int unequalTriplets(int[] nums) { @@ -145,6 +94,102 @@ class Solution { } ``` +```cpp +class Solution { +public: + int unequalTriplets(vector& nums) { + int n = nums.size(); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + for (int k = j + 1; k < n; ++k) { + if (nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k]) { + ++ans; + } + } + } + } + return ans; + } +}; +``` + +```go +func unequalTriplets(nums []int) (ans int) { + n := len(nums) + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + for k := j + 1; k < n; k++ { + if nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k] { + ans++ + } + } + } + } + return +} +``` + +```ts +function unequalTriplets(nums: number[]): number { + const n = nums.length; + let ans = 0; + for (let i = 0; i < n - 2; i++) { + for (let j = i + 1; j < n - 1; j++) { + for (let k = j + 1; k < n; k++) { + if (nums[i] !== nums[j] && nums[j] !== nums[k] && nums[i] !== nums[k]) { + ans++; + } + } + } + } + return ans; +} +``` + +```rust +impl Solution { + pub fn unequal_triplets(nums: Vec) -> i32 { + let n = nums.len(); + let mut ans = 0; + for i in 0..n - 2 { + for j in i + 1..n - 1 { + for k in j + 1..n { + if nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k] { + ans += 1; + } + } + } + } + ans + } +} +``` + + + +### 方法二:排序 + 枚举中间元素 + 二分查找 + +我们也可以先对数组 $nums$ 进行排序。 + +然后遍历 $nums$,枚举中间元素 $nums[j]$,利用二分查找,在 $nums[j]$ 左侧找到最近的下标 $i$,使得 $nums[i] \lt nums[j]$ 成立;在 $nums[j]$ 右侧找到最近的下标 $k$,使得 $nums[k] \gt nums[j]$ 成立。那么以 $nums[j]$ 作为中间元素,且符合条件的三元组数量为 $(i + 1) \times (n - k)$,累加到答案中。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 $nums$ 的长度。 + + + +```python +class Solution: + def unequalTriplets(self, nums: List[int]) -> int: + nums.sort() + ans, n = 0, len(nums) + for j in range(1, n - 1): + i = bisect_left(nums, nums[j], hi=j) - 1 + k = bisect_right(nums, nums[j], lo=j + 1) + ans += (i >= 0 and k < n) * (i + 1) * (n - k) + return ans +``` + ```java class Solution { public int unequalTriplets(int[] nums) { @@ -174,47 +219,6 @@ class Solution { } ``` -```java -class Solution { - public int unequalTriplets(int[] nums) { - Map cnt = new HashMap<>(); - for (int v : nums) { - cnt.merge(v, 1, Integer::sum); - } - int ans = 0, a = 0; - int n = nums.length; - for (int b : cnt.values()) { - int c = n - a - b; - ans += a * b * c; - a += b; - } - return ans; - } -} -``` - -### **C++** - -```cpp -class Solution { -public: - int unequalTriplets(vector& nums) { - int n = nums.size(); - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = i + 1; j < n; ++j) { - for (int k = j + 1; k < n; ++k) { - if (nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k]) { - ++ans; - } - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -233,44 +237,6 @@ public: }; ``` -```cpp -class Solution { -public: - int unequalTriplets(vector& nums) { - unordered_map cnt; - for (int& v : nums) { - ++cnt[v]; - } - int ans = 0, a = 0; - int n = nums.size(); - for (auto& [_, b] : cnt) { - int c = n - a - b; - ans += a * b * c; - a += b; - } - return ans; - } -}; -``` - -### **Go** - -```go -func unequalTriplets(nums []int) (ans int) { - n := len(nums) - for i := 0; i < n; i++ { - for j := i + 1; j < n; j++ { - for k := j + 1; k < n; k++ { - if nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k] { - ans++ - } - } - } - } - return -} -``` - ```go func unequalTriplets(nums []int) (ans int) { sort.Ints(nums) @@ -286,41 +252,6 @@ func unequalTriplets(nums []int) (ans int) { } ``` -```go -func unequalTriplets(nums []int) (ans int) { - cnt := map[int]int{} - for _, v := range nums { - cnt[v]++ - } - a, n := 0, len(nums) - for _, b := range cnt { - c := n - a - b - ans += a * b * c - a += b - } - return -} -``` - -### **TypeScript** - -```ts -function unequalTriplets(nums: number[]): number { - const n = nums.length; - let ans = 0; - for (let i = 0; i < n - 2; i++) { - for (let j = i + 1; j < n - 1; j++) { - for (let k = j + 1; k < n; k++) { - if (nums[i] !== nums[j] && nums[j] !== nums[k] && nums[i] !== nums[k]) { - ans++; - } - } - } - } - return ans; -} -``` - ```ts function unequalTriplets(nums: number[]): number { const n = nums.length; @@ -339,27 +270,6 @@ function unequalTriplets(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn unequal_triplets(nums: Vec) -> i32 { - let n = nums.len(); - let mut ans = 0; - for i in 0..n - 2 { - for j in i + 1..n - 1 { - for k in j + 1..n { - if nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k] { - ans += 1; - } - } - } - } - ans - } -} -``` - ```rust use std::collections::HashMap; impl Solution { @@ -381,6 +291,86 @@ impl Solution { } ``` + + +### 方法三:哈希表 + +我们还可以使用哈希表 $cnt$ 来统计数组 $nums$ 中每个元素的数量。 + +然后遍历哈希表 $cnt$,枚举中间元素的个数 $b$,左侧元素个数记为 $a$,那么右侧元素个数有 $c = n - a - b$,此时符合条件的三元组数量为 $a \times b \times c$,累加到答案中。接着更新 $a = a + b$,继续枚举中间元素的个数 $b$。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 + + + +```python +class Solution: + def unequalTriplets(self, nums: List[int]) -> int: + cnt = Counter(nums) + n = len(nums) + ans = a = 0 + for b in cnt.values(): + c = n - a - b + ans += a * b * c + a += b + return ans +``` + +```java +class Solution { + public int unequalTriplets(int[] nums) { + Map cnt = new HashMap<>(); + for (int v : nums) { + cnt.merge(v, 1, Integer::sum); + } + int ans = 0, a = 0; + int n = nums.length; + for (int b : cnt.values()) { + int c = n - a - b; + ans += a * b * c; + a += b; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int unequalTriplets(vector& nums) { + unordered_map cnt; + for (int& v : nums) { + ++cnt[v]; + } + int ans = 0, a = 0; + int n = nums.size(); + for (auto& [_, b] : cnt) { + int c = n - a - b; + ans += a * b * c; + a += b; + } + return ans; + } +}; +``` + +```go +func unequalTriplets(nums []int) (ans int) { + cnt := map[int]int{} + for _, v := range nums { + cnt[v]++ + } + a, n := 0, len(nums) + for _, b := range cnt { + c := n - a - b + ans += a * b * c + a += b + } + return +} +``` + ```rust use std::collections::HashMap; @@ -405,6 +395,12 @@ impl Solution { } ``` + + +### 方法四 + + + ```rust impl Solution { pub fn unequal_triplets(nums: Vec) -> i32 { @@ -446,10 +442,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2475.Number of Unequal Triplets in Array/README_EN.md b/solution/2400-2499/2475.Number of Unequal Triplets in Array/README_EN.md index 4e1ffe996e62e..0dcdb0780f1bd 100644 --- a/solution/2400-2499/2475.Number of Unequal Triplets in Array/README_EN.md +++ b/solution/2400-2499/2475.Number of Unequal Triplets in Array/README_EN.md @@ -49,32 +49,14 @@ Note that (2, 0, 4) is not a valid triplet because 2 > 0. ## Solutions -**Solution 1: Brute Force Enumeration** +### Solution 1: Brute Force Enumeration We can directly enumerate all triples $(i, j, k)$ and count all the ones that meet the conditions. The time complexity is $O(n^3)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. -**Solution 2: Sorting + Enumeration of Middle Elements + Binary Search** - -We can also sort the array $nums$ first. - -Then traverse $nums$, enumerate the middle element $nums[j]$, and use binary search to find the nearest index $i$ on the left side of $nums[j]$ such that $nums[i] < nums[j]$; find the nearest index $k$ on the right side of $nums[j]$ such that $nums[k] > nums[j]$. Then the number of triples with $nums[j]$ as the middle element and meeting the conditions is $(i + 1) \times (n - k)$, which is added to the answer. - -The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $nums$. - -**Solution 3: Hash Table** - -We can also use a hash table $cnt$ to count the number of each element in the array $nums$. - -Then traverse the hash table $cnt$, enumerate the number of middle elements $b$, and denote the number of elements on the left as $a$. Then the number of elements on the right is $c = n - a - b$. At this time, the number of triples that meet the conditions is $a \times b \times c$, which is added to the answer. Then update $a = a + b$ and continue to enumerate the number of middle elements $b$. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. - -### **Python3** - ```python class Solution: def unequalTriplets(self, nums: List[int]) -> int: @@ -89,33 +71,6 @@ class Solution: return ans ``` -```python -class Solution: - def unequalTriplets(self, nums: List[int]) -> int: - nums.sort() - ans, n = 0, len(nums) - for j in range(1, n - 1): - i = bisect_left(nums, nums[j], hi=j) - 1 - k = bisect_right(nums, nums[j], lo=j + 1) - ans += (i >= 0 and k < n) * (i + 1) * (n - k) - return ans -``` - -```python -class Solution: - def unequalTriplets(self, nums: List[int]) -> int: - cnt = Counter(nums) - n = len(nums) - ans = a = 0 - for b in cnt.values(): - c = n - a - b - ans += a * b * c - a += b - return ans -``` - -### **Java** - ```java class Solution { public int unequalTriplets(int[] nums) { @@ -135,6 +90,102 @@ class Solution { } ``` +```cpp +class Solution { +public: + int unequalTriplets(vector& nums) { + int n = nums.size(); + int ans = 0; + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + for (int k = j + 1; k < n; ++k) { + if (nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k]) { + ++ans; + } + } + } + } + return ans; + } +}; +``` + +```go +func unequalTriplets(nums []int) (ans int) { + n := len(nums) + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + for k := j + 1; k < n; k++ { + if nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k] { + ans++ + } + } + } + } + return +} +``` + +```ts +function unequalTriplets(nums: number[]): number { + const n = nums.length; + let ans = 0; + for (let i = 0; i < n - 2; i++) { + for (let j = i + 1; j < n - 1; j++) { + for (let k = j + 1; k < n; k++) { + if (nums[i] !== nums[j] && nums[j] !== nums[k] && nums[i] !== nums[k]) { + ans++; + } + } + } + } + return ans; +} +``` + +```rust +impl Solution { + pub fn unequal_triplets(nums: Vec) -> i32 { + let n = nums.len(); + let mut ans = 0; + for i in 0..n - 2 { + for j in i + 1..n - 1 { + for k in j + 1..n { + if nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k] { + ans += 1; + } + } + } + } + ans + } +} +``` + + + +### Solution 2: Sorting + Enumeration of Middle Elements + Binary Search + +We can also sort the array $nums$ first. + +Then traverse $nums$, enumerate the middle element $nums[j]$, and use binary search to find the nearest index $i$ on the left side of $nums[j]$ such that $nums[i] < nums[j]$; find the nearest index $k$ on the right side of $nums[j]$ such that $nums[k] > nums[j]$. Then the number of triples with $nums[j]$ as the middle element and meeting the conditions is $(i + 1) \times (n - k)$, which is added to the answer. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $nums$. + + + +```python +class Solution: + def unequalTriplets(self, nums: List[int]) -> int: + nums.sort() + ans, n = 0, len(nums) + for j in range(1, n - 1): + i = bisect_left(nums, nums[j], hi=j) - 1 + k = bisect_right(nums, nums[j], lo=j + 1) + ans += (i >= 0 and k < n) * (i + 1) * (n - k) + return ans +``` + ```java class Solution { public int unequalTriplets(int[] nums) { @@ -164,47 +215,6 @@ class Solution { } ``` -```java -class Solution { - public int unequalTriplets(int[] nums) { - Map cnt = new HashMap<>(); - for (int v : nums) { - cnt.merge(v, 1, Integer::sum); - } - int ans = 0, a = 0; - int n = nums.length; - for (int b : cnt.values()) { - int c = n - a - b; - ans += a * b * c; - a += b; - } - return ans; - } -} -``` - -### **C++** - -```cpp -class Solution { -public: - int unequalTriplets(vector& nums) { - int n = nums.size(); - int ans = 0; - for (int i = 0; i < n; ++i) { - for (int j = i + 1; j < n; ++j) { - for (int k = j + 1; k < n; ++k) { - if (nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k]) { - ++ans; - } - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -223,44 +233,6 @@ public: }; ``` -```cpp -class Solution { -public: - int unequalTriplets(vector& nums) { - unordered_map cnt; - for (int& v : nums) { - ++cnt[v]; - } - int ans = 0, a = 0; - int n = nums.size(); - for (auto& [_, b] : cnt) { - int c = n - a - b; - ans += a * b * c; - a += b; - } - return ans; - } -}; -``` - -### **Go** - -```go -func unequalTriplets(nums []int) (ans int) { - n := len(nums) - for i := 0; i < n; i++ { - for j := i + 1; j < n; j++ { - for k := j + 1; k < n; k++ { - if nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k] { - ans++ - } - } - } - } - return -} -``` - ```go func unequalTriplets(nums []int) (ans int) { sort.Ints(nums) @@ -276,41 +248,6 @@ func unequalTriplets(nums []int) (ans int) { } ``` -```go -func unequalTriplets(nums []int) (ans int) { - cnt := map[int]int{} - for _, v := range nums { - cnt[v]++ - } - a, n := 0, len(nums) - for _, b := range cnt { - c := n - a - b - ans += a * b * c - a += b - } - return -} -``` - -### **TypeScript** - -```ts -function unequalTriplets(nums: number[]): number { - const n = nums.length; - let ans = 0; - for (let i = 0; i < n - 2; i++) { - for (let j = i + 1; j < n - 1; j++) { - for (let k = j + 1; k < n; k++) { - if (nums[i] !== nums[j] && nums[j] !== nums[k] && nums[i] !== nums[k]) { - ans++; - } - } - } - } - return ans; -} -``` - ```ts function unequalTriplets(nums: number[]): number { const n = nums.length; @@ -329,27 +266,6 @@ function unequalTriplets(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn unequal_triplets(nums: Vec) -> i32 { - let n = nums.len(); - let mut ans = 0; - for i in 0..n - 2 { - for j in i + 1..n - 1 { - for k in j + 1..n { - if nums[i] != nums[j] && nums[j] != nums[k] && nums[i] != nums[k] { - ans += 1; - } - } - } - } - ans - } -} -``` - ```rust use std::collections::HashMap; impl Solution { @@ -371,6 +287,86 @@ impl Solution { } ``` + + +### Solution 3: Hash Table + +We can also use a hash table $cnt$ to count the number of each element in the array $nums$. + +Then traverse the hash table $cnt$, enumerate the number of middle elements $b$, and denote the number of elements on the left as $a$. Then the number of elements on the right is $c = n - a - b$. At this time, the number of triples that meet the conditions is $a \times b \times c$, which is added to the answer. Then update $a = a + b$ and continue to enumerate the number of middle elements $b$. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. + + + +```python +class Solution: + def unequalTriplets(self, nums: List[int]) -> int: + cnt = Counter(nums) + n = len(nums) + ans = a = 0 + for b in cnt.values(): + c = n - a - b + ans += a * b * c + a += b + return ans +``` + +```java +class Solution { + public int unequalTriplets(int[] nums) { + Map cnt = new HashMap<>(); + for (int v : nums) { + cnt.merge(v, 1, Integer::sum); + } + int ans = 0, a = 0; + int n = nums.length; + for (int b : cnt.values()) { + int c = n - a - b; + ans += a * b * c; + a += b; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int unequalTriplets(vector& nums) { + unordered_map cnt; + for (int& v : nums) { + ++cnt[v]; + } + int ans = 0, a = 0; + int n = nums.size(); + for (auto& [_, b] : cnt) { + int c = n - a - b; + ans += a * b * c; + a += b; + } + return ans; + } +}; +``` + +```go +func unequalTriplets(nums []int) (ans int) { + cnt := map[int]int{} + for _, v := range nums { + cnt[v]++ + } + a, n := 0, len(nums) + for _, b := range cnt { + c := n - a - b + ans += a * b * c + a += b + } + return +} +``` + ```rust use std::collections::HashMap; @@ -395,6 +391,12 @@ impl Solution { } ``` + + +### Solution 4 + + + ```rust impl Solution { pub fn unequal_triplets(nums: Vec) -> i32 { @@ -436,10 +438,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/README.md b/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/README.md index aa377fbfd6f77..53f8e26f80dee 100644 --- a/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/README.md +++ b/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:中序遍历 + 二分查找** +### 方法一:中序遍历 + 二分查找 由于题目中给出的是一棵二叉搜索树,因此我们可以通过中序遍历得到一个有序数组,然后对于每个查询,我们可以通过二分查找得到小于等于该查询值的最大值和大于等于该查询值的最小值。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -100,10 +94,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -149,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -190,8 +178,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -229,8 +215,6 @@ func closestNodes(root *TreeNode, queries []int) (ans [][]int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -281,10 +265,6 @@ function closestNodes(root: TreeNode | null, queries: number[]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/README_EN.md b/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/README_EN.md index 87cb2c21acc68..19b57da5fa343 100644 --- a/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/README_EN.md +++ b/solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/README_EN.md @@ -48,7 +48,7 @@ ## Solutions -**Solution 1: In-order Traversal + Binary Search** +### Solution 1: In-order Traversal + Binary Search Since the problem provides a binary search tree, we can obtain a sorted array through in-order traversal. Then for each query, we can find the maximum value less than or equal to the query value and the minimum value greater than or equal to the query value through binary search. @@ -56,8 +56,6 @@ The time complexity is $O(n + m \times \log n)$, and the space complexity is $O( -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -88,8 +86,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -135,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -176,8 +170,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -215,8 +207,6 @@ func closestNodes(root *TreeNode, queries []int) (ans [][]int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -267,10 +257,6 @@ function closestNodes(root: TreeNode | null, queries: number[]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/README.md b/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/README.md index d2ac63d9f9254..119313c6f3783 100644 --- a/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/README.md +++ b/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/README.md @@ -73,9 +73,7 @@ ## 解法 - - -**方法一:贪心 + DFS** +### 方法一:贪心 + DFS 根据题目描述,我们可以发现,所有车只会往首都(节点 $0$)开。 @@ -87,10 +85,6 @@ -### **Python3** - - - ```python class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: @@ -113,10 +107,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -151,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +170,6 @@ public: }; ``` -### **Go** - ```go func minimumFuelCost(roads [][]int, seats int) (ans int64) { n := len(roads) + 1 @@ -210,8 +196,6 @@ func minimumFuelCost(roads [][]int, seats int) (ans int64) { } ``` -### **TypeScript** - ```ts function minimumFuelCost(roads: number[][], seats: number): number { const n = roads.length + 1; @@ -237,8 +221,6 @@ function minimumFuelCost(roads: number[][], seats: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn minimum_fuel_cost(roads: Vec>, seats: i32) -> i64 { @@ -268,10 +250,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/README_EN.md b/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/README_EN.md index a216c64ef5b88..3196a6a4a39b4 100644 --- a/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/README_EN.md +++ b/solution/2400-2499/2477.Minimum Fuel Cost to Report to the Capital/README_EN.md @@ -68,7 +68,7 @@ It can be proven that 7 is the minimum number of liters of fuel needed. ## Solutions -**Solution 1: Greedy + DFS** +### Solution 1: Greedy + DFS According to the problem description, we can find that all cars will only drive towards the capital (node $0$). @@ -80,8 +80,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int: @@ -104,8 +102,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -140,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +165,6 @@ public: }; ``` -### **Go** - ```go func minimumFuelCost(roads [][]int, seats int) (ans int64) { n := len(roads) + 1 @@ -199,8 +191,6 @@ func minimumFuelCost(roads [][]int, seats int) (ans int64) { } ``` -### **TypeScript** - ```ts function minimumFuelCost(roads: number[][], seats: number): number { const n = roads.length + 1; @@ -226,8 +216,6 @@ function minimumFuelCost(roads: number[][], seats: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn minimum_fuel_cost(roads: Vec>, seats: i32) -> i64 { @@ -257,10 +245,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2478.Number of Beautiful Partitions/README.md b/solution/2400-2499/2478.Number of Beautiful Partitions/README.md index 23371ce614e9c..d6acf54a0e4e8 100644 --- a/solution/2400-2499/2478.Number of Beautiful Partitions/README.md +++ b/solution/2400-2499/2478.Number of Beautiful Partitions/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 定义 $f[i][j]$ 表示前 $i$ 个字符分割成 $j$ 段的方案数。初始化 $f[0][0] = 1$,其余 $f[i][j] = 0$。 @@ -89,10 +87,6 @@ $$ -### **Python3** - - - ```python class Solution: def beautifulPartitions(self, s: str, k: int, minLength: int) -> int: @@ -113,10 +107,6 @@ class Solution: return f[n][k] ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -149,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -180,8 +168,6 @@ public: }; ``` -### **Go** - ```go func beautifulPartitions(s string, k int, minLength int) int { prime := func(c byte) bool { @@ -213,16 +199,6 @@ func beautifulPartitions(s string, k int, minLength int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2478.Number of Beautiful Partitions/README_EN.md b/solution/2400-2499/2478.Number of Beautiful Partitions/README_EN.md index fe8adc8d8c510..8ba02beda0093 100644 --- a/solution/2400-2499/2478.Number of Beautiful Partitions/README_EN.md +++ b/solution/2400-2499/2478.Number of Beautiful Partitions/README_EN.md @@ -56,9 +56,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return f[n][k] ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +141,6 @@ public: }; ``` -### **Go** - ```go func beautifulPartitions(s string, k int, minLength int) int { prime := func(c byte) bool { @@ -178,16 +172,6 @@ func beautifulPartitions(s string, k int, minLength int) int { } ``` -### **TypeScript** - -```ts - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2479.Maximum XOR of Two Non-Overlapping Subtrees/README.md b/solution/2400-2499/2479.Maximum XOR of Two Non-Overlapping Subtrees/README.md index d4a8734102e3b..ec5785563e8cf 100644 --- a/solution/2400-2499/2479.Maximum XOR of Two Non-Overlapping Subtrees/README.md +++ b/solution/2400-2499/2479.Maximum XOR of Two Non-Overlapping Subtrees/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:递归 + 0-1 前缀树** +### 方法一:递归 + 0-1 前缀树 我们先递归预处理出每个节点的子树和,记录在数组 $s$ 中。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Trie: def __init__(self): @@ -131,10 +125,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Trie { Trie[] children = new Trie[2]; @@ -216,8 +206,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -291,8 +279,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [2]*Trie @@ -369,10 +355,6 @@ func maxXor(n int, edges [][]int, values []int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2479.Maximum XOR of Two Non-Overlapping Subtrees/README_EN.md b/solution/2400-2499/2479.Maximum XOR of Two Non-Overlapping Subtrees/README_EN.md index f3841d8ed97ec..e4cff3475a555 100644 --- a/solution/2400-2499/2479.Maximum XOR of Two Non-Overlapping Subtrees/README_EN.md +++ b/solution/2400-2499/2479.Maximum XOR of Two Non-Overlapping Subtrees/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Trie: @@ -113,8 +113,6 @@ class Solution: return ans ``` -### **Java** - ```java class Trie { Trie[] children = new Trie[2]; @@ -196,8 +194,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -271,8 +267,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [2]*Trie @@ -349,10 +343,6 @@ func maxXor(n int, edges [][]int, values []int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2480.Form a Chemical Bond/README.md b/solution/2400-2499/2480.Form a Chemical Bond/README.md index 0182a5b4bb4f4..bba1a4f8c0850 100644 --- a/solution/2400-2499/2480.Form a Chemical Bond/README.md +++ b/solution/2400-2499/2480.Form a Chemical Bond/README.md @@ -73,14 +73,10 @@ Nonmeal 元素包括 Cl, O, and N. ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT a.symbol AS metal, b.symbol AS nonmetal @@ -91,3 +87,5 @@ WHERE a.type = 'Metal' AND b.type = 'Nonmetal'; ``` + + diff --git a/solution/2400-2499/2480.Form a Chemical Bond/README_EN.md b/solution/2400-2499/2480.Form a Chemical Bond/README_EN.md index 42816ed18521c..2f231ad551699 100644 --- a/solution/2400-2499/2480.Form a Chemical Bond/README_EN.md +++ b/solution/2400-2499/2480.Form a Chemical Bond/README_EN.md @@ -71,9 +71,9 @@ Each Metal element pairs with a Nonmetal element in the output table. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -85,3 +85,5 @@ WHERE a.type = 'Metal' AND b.type = 'Nonmetal'; ``` + + diff --git a/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/README.md b/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/README.md index 6dd4bc3ec7bce..64771ac84b183 100644 --- a/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/README.md +++ b/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:分类讨论** +### 方法一:分类讨论 - 当 $n=1$ 时,不需要切割,即切割次数为 $0$; - 当 $n$ 为奇数时,不存在共线的情况,最少需要 $n$ 次切割; @@ -76,20 +74,12 @@ $$ -### **Python3** - - - ```python class Solution: def numberOfCuts(self, n: int) -> int: return n if (n > 1 and n & 1) else n >> 1 ``` -### **Java** - - - ```java class Solution { public int numberOfCuts(int n) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +97,6 @@ public: }; ``` -### **Go** - ```go func numberOfCuts(n int) int { if n > 1 && n%2 == 1 { @@ -120,26 +106,12 @@ func numberOfCuts(n int) int { } ``` -### **TypeScript** - ```ts function numberOfCuts(n: number): number { return n > 1 && n & 1 ? n : n >> 1; } ``` -### **C#** - -```cs -public class Solution { - public int NumberOfCuts(int n) { - return n > 1 && n % 2 == 1 ? n : n >> 1; - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn number_of_cuts(n: i32) -> i32 { @@ -151,10 +123,14 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public int NumberOfCuts(int n) { + return n > 1 && n % 2 == 1 ? n : n >> 1; + } +} ``` + + diff --git a/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/README_EN.md b/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/README_EN.md index 0053d3a98e6d7..c1cb936eb32af 100644 --- a/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/README_EN.md +++ b/solution/2400-2499/2481.Minimum Cuts to Divide a Circle/README_EN.md @@ -45,9 +45,9 @@ Also note that the first cut will not divide the circle into distinct parts. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -55,8 +55,6 @@ class Solution: return n if (n > 1 and n & 1) else n >> 1 ``` -### **Java** - ```java class Solution { public int numberOfCuts(int n) { @@ -65,8 +63,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -76,8 +72,6 @@ public: }; ``` -### **Go** - ```go func numberOfCuts(n int) int { if n > 1 && n%2 == 1 { @@ -87,26 +81,12 @@ func numberOfCuts(n int) int { } ``` -### **TypeScript** - ```ts function numberOfCuts(n: number): number { return n > 1 && n & 1 ? n : n >> 1; } ``` -### **C#** - -```cs -public class Solution { - public int NumberOfCuts(int n) { - return n > 1 && n % 2 == 1 ? n : n >> 1; - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn number_of_cuts(n: i32) -> i32 { @@ -118,10 +98,14 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public int NumberOfCuts(int n) { + return n > 1 && n % 2 == 1 ? n : n >> 1; + } +} ``` + + diff --git a/solution/2400-2499/2482.Difference Between Ones and Zeros in Row and Column/README.md b/solution/2400-2499/2482.Difference Between Ones and Zeros in Row and Column/README.md index c63291e0d8f08..f12d0e768dcc8 100644 --- a/solution/2400-2499/2482.Difference Between Ones and Zeros in Row and Column/README.md +++ b/solution/2400-2499/2482.Difference Between Ones and Zeros in Row and Column/README.md @@ -69,9 +69,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 根据题意模拟即可。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def onesMinusZeros(self, grid: List[List[int]]) -> List[List[int]]: @@ -100,10 +94,6 @@ class Solution: return diff ``` -### **Java** - - - ```java class Solution { public int[][] onesMinusZeros(int[][] grid) { @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func onesMinusZeros(grid [][]int) [][]int { m, n := len(grid), len(grid[0]) @@ -179,8 +165,6 @@ func onesMinusZeros(grid [][]int) [][]int { } ``` -### **TypeScript** - ```ts function onesMinusZeros(grid: number[][]): number[][] { const m = grid.length; @@ -205,8 +189,6 @@ function onesMinusZeros(grid: number[][]): number[][] { } ``` -### **Rust** - ```rust impl Solution { pub fn ones_minus_zeros(grid: Vec>) -> Vec> { @@ -233,8 +215,6 @@ impl Solution { } ``` -### **C** - ```c /** * Return an array of arrays of size *returnSize. @@ -267,10 +247,6 @@ int** onesMinusZeros(int** grid, int gridSize, int* gridColSize, int* returnSize } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2482.Difference Between Ones and Zeros in Row and Column/README_EN.md b/solution/2400-2499/2482.Difference Between Ones and Zeros in Row and Column/README_EN.md index adc81ad6089bc..4bdd9867ef474 100644 --- a/solution/2400-2499/2482.Difference Between Ones and Zeros in Row and Column/README_EN.md +++ b/solution/2400-2499/2482.Difference Between Ones and Zeros in Row and Column/README_EN.md @@ -63,9 +63,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: return diff ``` -### **Java** - ```java class Solution { public int[][] onesMinusZeros(int[][] grid) { @@ -110,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +133,6 @@ public: }; ``` -### **Go** - ```go func onesMinusZeros(grid [][]int) [][]int { m, n := len(grid), len(grid[0]) @@ -161,8 +155,6 @@ func onesMinusZeros(grid [][]int) [][]int { } ``` -### **TypeScript** - ```ts function onesMinusZeros(grid: number[][]): number[][] { const m = grid.length; @@ -187,8 +179,6 @@ function onesMinusZeros(grid: number[][]): number[][] { } ``` -### **Rust** - ```rust impl Solution { pub fn ones_minus_zeros(grid: Vec>) -> Vec> { @@ -215,8 +205,6 @@ impl Solution { } ``` -### **C** - ```c /** * Return an array of arrays of size *returnSize. @@ -249,10 +237,6 @@ int** onesMinusZeros(int** grid, int gridSize, int* gridColSize, int* returnSize } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2483.Minimum Penalty for a Shop/README.md b/solution/2400-2499/2483.Minimum Penalty for a Shop/README.md index 4a4b7793bd70c..e9759fc39037d 100644 --- a/solution/2400-2499/2483.Minimum Penalty for a Shop/README.md +++ b/solution/2400-2499/2483.Minimum Penalty for a Shop/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:前缀和 + 枚举** +### 方法一:前缀和 + 枚举 我们先算出前 $i$ 小时有多少顾客到达,记录在前缀和数组 $s$ 中。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def bestClosingTime(self, customers: str) -> int: @@ -97,10 +91,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int bestClosingTime(String customers) { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,7 +134,26 @@ public: }; ``` -### **Rust** +```go +func bestClosingTime(customers string) (ans int) { + n := len(customers) + s := make([]int, n+1) + for i, c := range customers { + s[i+1] = s[i] + if c == 'Y' { + s[i+1]++ + } + } + cost := 1 << 30 + for j := 0; j <= n; j++ { + t := j - s[j] + s[n] - s[j] + if cost > t { + ans, cost = j, t + } + } + return +} +``` ```rust impl Solution { @@ -175,33 +182,6 @@ impl Solution { } ``` -### **Go** - -```go -func bestClosingTime(customers string) (ans int) { - n := len(customers) - s := make([]int, n+1) - for i, c := range customers { - s[i+1] = s[i] - if c == 'Y' { - s[i+1]++ - } - } - cost := 1 << 30 - for j := 0; j <= n; j++ { - t := j - s[j] + s[n] - s[j] - if cost > t { - ans, cost = j, t - } - } - return -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2483.Minimum Penalty for a Shop/README_EN.md b/solution/2400-2499/2483.Minimum Penalty for a Shop/README_EN.md index 1e10edf5f50f3..b0fea81bb4d0c 100644 --- a/solution/2400-2499/2483.Minimum Penalty for a Shop/README_EN.md +++ b/solution/2400-2499/2483.Minimum Penalty for a Shop/README_EN.md @@ -62,9 +62,9 @@ Closing the shop at 2nd or 4th hour gives a minimum penalt ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -81,8 +81,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int bestClosingTime(String customers) { @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,7 +124,26 @@ public: }; ``` -### **Rust** +```go +func bestClosingTime(customers string) (ans int) { + n := len(customers) + s := make([]int, n+1) + for i, c := range customers { + s[i+1] = s[i] + if c == 'Y' { + s[i+1]++ + } + } + cost := 1 << 30 + for j := 0; j <= n; j++ { + t := j - s[j] + s[n] - s[j] + if cost > t { + ans, cost = j, t + } + } + return +} +``` ```rust impl Solution { @@ -157,33 +172,6 @@ impl Solution { } ``` -### **Go** - -```go -func bestClosingTime(customers string) (ans int) { - n := len(customers) - s := make([]int, n+1) - for i, c := range customers { - s[i+1] = s[i] - if c == 'Y' { - s[i+1]++ - } - } - cost := 1 << 30 - for j := 0; j <= n; j++ { - t := j - s[j] + s[n] - s[j] - if cost > t { - ans, cost = j, t - } - } - return -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2484.Count Palindromic Subsequences/README.md b/solution/2400-2499/2484.Count Palindromic Subsequences/README.md index bfdfc32d0b04d..207f10d25f902 100644 --- a/solution/2400-2499/2484.Count Palindromic Subsequences/README.md +++ b/solution/2400-2499/2484.Count Palindromic Subsequences/README.md @@ -51,18 +51,12 @@ ## 解法 - - -**方法一:枚举 + 计数** +### 方法一:枚举 + 计数 时间复杂度 $O(100 \times n)$,空间复杂度 $O(100 \times n)$。其中 $n$ 为字符串 $s$ 的长度。 -### **Python3** - - - ```python class Solution: def countPalindromes(self, s: str) -> int: @@ -97,10 +91,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -153,8 +143,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -208,8 +196,6 @@ public: }; ``` -### **Go** - ```go func countPalindromes(s string) int { n := len(s) @@ -259,10 +245,6 @@ func countPalindromes(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2484.Count Palindromic Subsequences/README_EN.md b/solution/2400-2499/2484.Count Palindromic Subsequences/README_EN.md index 664b7639c5def..6e3aa33242a5f 100644 --- a/solution/2400-2499/2484.Count Palindromic Subsequences/README_EN.md +++ b/solution/2400-2499/2484.Count Palindromic Subsequences/README_EN.md @@ -50,9 +50,9 @@ Two of them (both equal to "10301") are palindromic. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -88,8 +88,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -142,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -197,8 +193,6 @@ public: }; ``` -### **Go** - ```go func countPalindromes(s string) int { n := len(s) @@ -248,10 +242,6 @@ func countPalindromes(s string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2485.Find the Pivot Integer/README.md b/solution/2400-2499/2485.Find the Pivot Integer/README.md index c11b87948684a..c9595b3462a2b 100644 --- a/solution/2400-2499/2485.Find the Pivot Integer/README.md +++ b/solution/2400-2499/2485.Find the Pivot Integer/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以直接在 $[1,..n]$ 的范围内枚举 $x$,判断以下等式是否成立。若成立,则 $x$ 为中枢整数,直接返回 $x$ 即可。 @@ -61,30 +59,8 @@ $$ 时间复杂度 $O(n)$,其中 $n$ 为给定的正整数 $n$。空间复杂度 $O(1)$。 -**方法二:数学** - -我们可以将上述等式进行变形,得到: - -$$ -n \times (n + 1) = 2 \times x^2 -$$ - -即: - -$$ -x = \sqrt{\frac{n \times (n + 1)}{2}} -$$ - -如果 $x$ 为整数,则 $x$ 为中枢整数,否则不存在中枢整数。 - -时间复杂度 $O(1)$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def pivotInteger(self, n: int) -> int: @@ -94,18 +70,6 @@ class Solution: return -1 ``` -```python -class Solution: - def pivotInteger(self, n: int) -> int: - y = n * (n + 1) // 2 - x = int(sqrt(y)) - return x if x * x == y else -1 -``` - -### **Java** - - - ```java class Solution { public int pivotInteger(int n) { @@ -119,18 +83,6 @@ class Solution { } ``` -```java -class Solution { - public int pivotInteger(int n) { - int y = n * (n + 1) / 2; - int x = (int) Math.sqrt(y); - return x * x == y ? x : -1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -145,19 +97,6 @@ public: }; ``` -```cpp -class Solution { -public: - int pivotInteger(int n) { - int y = n * (n + 1) / 2; - int x = sqrt(y); - return x * x == y ? x : -1; - } -}; -``` - -### **Go** - ```go func pivotInteger(n int) int { for x := 1; x <= n; x++ { @@ -169,19 +108,6 @@ func pivotInteger(n int) int { } ``` -```go -func pivotInteger(n int) int { - y := n * (n + 1) / 2 - x := int(math.Sqrt(float64(y))) - if x*x == y { - return x - } - return -1 -} -``` - -### **TypeScript** - ```ts function pivotInteger(n: number): number { for (let x = 1; x <= n; ++x) { @@ -193,16 +119,21 @@ function pivotInteger(n: number): number { } ``` -```ts -function pivotInteger(n: number): number { - const y = Math.floor((n * (n + 1)) / 2); - const x = Math.floor(Math.sqrt(y)); - return x * x === y ? x : -1; +```rust +impl Solution { + pub fn pivot_integer(n: i32) -> i32 { + let y = (n * (n + 1)) / 2; + let x = (y as f64).sqrt() as i32; + + if x * x == y { + return x; + } + + -1 + } } ``` -### **PHP** - ```php class Solution { /** @@ -223,27 +154,76 @@ class Solution { } ``` -### **Rust** + -```rust -impl Solution { - pub fn pivot_integer(n: i32) -> i32 { - let y = (n * (n + 1)) / 2; - let x = (y as f64).sqrt() as i32; +### 方法二:数学 - if x * x == y { - return x; - } +我们可以将上述等式进行变形,得到: - -1 +$$ +n \times (n + 1) = 2 \times x^2 +$$ + +即: + +$$ +x = \sqrt{\frac{n \times (n + 1)}{2}} +$$ + +如果 $x$ 为整数,则 $x$ 为中枢整数,否则不存在中枢整数。 + +时间复杂度 $O(1)$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def pivotInteger(self, n: int) -> int: + y = n * (n + 1) // 2 + x = int(sqrt(y)) + return x if x * x == y else -1 +``` + +```java +class Solution { + public int pivotInteger(int n) { + int y = n * (n + 1) / 2; + int x = (int) Math.sqrt(y); + return x * x == y ? x : -1; } } ``` -### **...** +```cpp +class Solution { +public: + int pivotInteger(int n) { + int y = n * (n + 1) / 2; + int x = sqrt(y); + return x * x == y ? x : -1; + } +}; +``` +```go +func pivotInteger(n int) int { + y := n * (n + 1) / 2 + x := int(math.Sqrt(float64(y))) + if x*x == y { + return x + } + return -1 +} ``` +```ts +function pivotInteger(n: number): number { + const y = Math.floor((n * (n + 1)) / 2); + const x = Math.floor(Math.sqrt(y)); + return x * x === y ? x : -1; +} ``` + + diff --git a/solution/2400-2499/2485.Find the Pivot Integer/README_EN.md b/solution/2400-2499/2485.Find the Pivot Integer/README_EN.md index 9eca90b7888ae..9571ef9d5311c 100644 --- a/solution/2400-2499/2485.Find the Pivot Integer/README_EN.md +++ b/solution/2400-2499/2485.Find the Pivot Integer/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We can directly enumerate $x$ in the range of $[1,..n]$, and check whether the following equation holds. If it holds, then $x$ is the pivot integer, and we can directly return $x$. @@ -56,28 +56,8 @@ $$ The time complexity is $O(n)$, where $n$ is the given positive integer $n$. The space complexity is $O(1)$. -**Solution 2: Mathematics** - -We can transform the above equation to get: - -$$ -n \times (n + 1) = 2 \times x^2 -$$ - -That is: - -$$ -x = \sqrt{\frac{n \times (n + 1)}{2}} -$$ - -If $x$ is an integer, then $x$ is the pivot integer, otherwise there is no pivot integer. - -The time complexity is $O(1)$, and the space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def pivotInteger(self, n: int) -> int: @@ -87,16 +67,6 @@ class Solution: return -1 ``` -```python -class Solution: - def pivotInteger(self, n: int) -> int: - y = n * (n + 1) // 2 - x = int(sqrt(y)) - return x if x * x == y else -1 -``` - -### **Java** - ```java class Solution { public int pivotInteger(int n) { @@ -110,18 +80,6 @@ class Solution { } ``` -```java -class Solution { - public int pivotInteger(int n) { - int y = n * (n + 1) / 2; - int x = (int) Math.sqrt(y); - return x * x == y ? x : -1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -136,19 +94,6 @@ public: }; ``` -```cpp -class Solution { -public: - int pivotInteger(int n) { - int y = n * (n + 1) / 2; - int x = sqrt(y); - return x * x == y ? x : -1; - } -}; -``` - -### **Go** - ```go func pivotInteger(n int) int { for x := 1; x <= n; x++ { @@ -160,19 +105,6 @@ func pivotInteger(n int) int { } ``` -```go -func pivotInteger(n int) int { - y := n * (n + 1) / 2 - x := int(math.Sqrt(float64(y))) - if x*x == y { - return x - } - return -1 -} -``` - -### **TypeScript** - ```ts function pivotInteger(n: number): number { for (let x = 1; x <= n; ++x) { @@ -184,16 +116,21 @@ function pivotInteger(n: number): number { } ``` -```ts -function pivotInteger(n: number): number { - const y = Math.floor((n * (n + 1)) / 2); - const x = Math.floor(Math.sqrt(y)); - return x * x === y ? x : -1; +```rust +impl Solution { + pub fn pivot_integer(n: i32) -> i32 { + let y = (n * (n + 1)) / 2; + let x = (y as f64).sqrt() as i32; + + if x * x == y { + return x; + } + + -1 + } } ``` -### **PHP** - ```php class Solution { /** @@ -214,27 +151,76 @@ class Solution { } ``` -### **Rust** + -```rust -impl Solution { - pub fn pivot_integer(n: i32) -> i32 { - let y = (n * (n + 1)) / 2; - let x = (y as f64).sqrt() as i32; +### Solution 2: Mathematics - if x * x == y { - return x; - } +We can transform the above equation to get: - -1 +$$ +n \times (n + 1) = 2 \times x^2 +$$ + +That is: + +$$ +x = \sqrt{\frac{n \times (n + 1)}{2}} +$$ + +If $x$ is an integer, then $x$ is the pivot integer, otherwise there is no pivot integer. + +The time complexity is $O(1)$, and the space complexity is $O(1)$. + + + +```python +class Solution: + def pivotInteger(self, n: int) -> int: + y = n * (n + 1) // 2 + x = int(sqrt(y)) + return x if x * x == y else -1 +``` + +```java +class Solution { + public int pivotInteger(int n) { + int y = n * (n + 1) / 2; + int x = (int) Math.sqrt(y); + return x * x == y ? x : -1; } } ``` -### **...** +```cpp +class Solution { +public: + int pivotInteger(int n) { + int y = n * (n + 1) / 2; + int x = sqrt(y); + return x * x == y ? x : -1; + } +}; +``` +```go +func pivotInteger(n int) int { + y := n * (n + 1) / 2 + x := int(math.Sqrt(float64(y))) + if x*x == y { + return x + } + return -1 +} ``` +```ts +function pivotInteger(n: number): number { + const y = Math.floor((n * (n + 1)) / 2); + const x = Math.floor(Math.sqrt(y)); + return x * x === y ? x : -1; +} ``` + + diff --git a/solution/2400-2499/2486.Append Characters to String to Make Subsequence/README.md b/solution/2400-2499/2486.Append Characters to String to Make Subsequence/README.md index 3b81f1184c580..acb37858fa327 100644 --- a/solution/2400-2499/2486.Append Characters to String to Make Subsequence/README.md +++ b/solution/2400-2499/2486.Append Characters to String to Make Subsequence/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们定义两个指针 $i$ 和 $j$,分别指向字符串 $s$ 和 $t$ 的首字符。遍历字符串 $t$,当 $s[i] \neq t[j]$ 时,指针 $i$ 后移,直到 $s[i] = t[j]$ 或者 $i$ 到达字符串 $s$ 的末尾。如果 $i$ 到达字符串 $s$ 的末尾,说明 $t$ 中的字符 $t[j]$ 无法在 $s$ 中找到对应的字符,返回 $t$ 中剩余的字符数。否则,将指针 $i$ 和 $j$ 同时后移,继续遍历字符串 $t$。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def appendCharacters(self, s: str, t: str) -> int: @@ -80,10 +74,6 @@ class Solution: return 0 ``` -### **Java** - - - ```java class Solution { public int appendCharacters(String s, String t) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func appendCharacters(s string, t string) int { m, n := len(s), len(t) @@ -138,8 +124,6 @@ func appendCharacters(s string, t string) int { } ``` -### **TypeScript** - ```ts function appendCharacters(s: string, t: string): number { const [m, n] = [s.length, t.length]; @@ -156,10 +140,6 @@ function appendCharacters(s: string, t: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2486.Append Characters to String to Make Subsequence/README_EN.md b/solution/2400-2499/2486.Append Characters to String to Make Subsequence/README_EN.md index 58920f972b2e2..0dfbec29231e7 100644 --- a/solution/2400-2499/2486.Append Characters to String to Make Subsequence/README_EN.md +++ b/solution/2400-2499/2486.Append Characters to String to Make Subsequence/README_EN.md @@ -49,7 +49,7 @@ It can be shown that appending any 4 characters to the end of s will never make ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We define two pointers $i$ and $j$, pointing to the first characters of strings $s$ and $t$ respectively. We traverse string $t$, when $s[i] \neq t[j]$, we move pointer $i$ forward until $s[i] = t[j]$ or $i$ reaches the end of string $s$. If $i$ reaches the end of string $s$, it means that the character $t[j]$ in $t$ cannot find the corresponding character in $s$, so we return the remaining number of characters in $t$. Otherwise, we move both pointers $i$ and $j$ forward and continue to traverse string $t$. @@ -57,8 +57,6 @@ The time complexity is $O(m + n)$, and the space complexity is $O(1)$. Where $m$ -### **Python3** - ```python class Solution: def appendCharacters(self, s: str, t: str) -> int: @@ -72,8 +70,6 @@ class Solution: return 0 ``` -### **Java** - ```java class Solution { public int appendCharacters(String s, String t) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +105,6 @@ public: }; ``` -### **Go** - ```go func appendCharacters(s string, t string) int { m, n := len(s), len(t) @@ -128,8 +120,6 @@ func appendCharacters(s string, t string) int { } ``` -### **TypeScript** - ```ts function appendCharacters(s: string, t: string): number { const [m, n] = [s.length, t.length]; @@ -146,10 +136,6 @@ function appendCharacters(s: string, t: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2487.Remove Nodes From Linked List/README.md b/solution/2400-2499/2487.Remove Nodes From Linked List/README.md index 6a5466725f763..3a554e0895e05 100644 --- a/solution/2400-2499/2487.Remove Nodes From Linked List/README.md +++ b/solution/2400-2499/2487.Remove Nodes From Linked List/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:单调栈模拟** +### 方法一:单调栈模拟 我们可以先将链表中的节点值存入数组 $nums$,然后遍历数组 $nums$,维护一个从栈底到栈顶单调递减的栈 $stk$,如果当前元素比栈顶元素大,则将栈顶元素出栈,直到当前元素小于等于栈顶元素,将当前元素入栈。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -93,30 +87,6 @@ class Solution: return dummy.next ``` -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: - dummy = ListNode(inf, head) - cur = head - stk = [dummy] - while cur: - while stk[-1].val < cur.val: - stk.pop() - stk[-1].next = cur - stk.append(cur) - cur = cur.next - return dummy.next -``` - -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -153,36 +123,6 @@ class Solution { } ``` -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode removeNodes(ListNode head) { - ListNode dummy = new ListNode(1 << 30, head); - Deque stk = new ArrayDeque<>(); - stk.offerLast(dummy); - for (ListNode cur = head; cur != null; cur = cur.next) { - while (stk.peekLast().val < cur.val) { - stk.pollLast(); - } - stk.peekLast().next = cur; - stk.offerLast(cur); - } - return dummy.next; - } -} -``` - -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -220,37 +160,6 @@ public: }; ``` -```cpp -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* removeNodes(ListNode* head) { - ListNode* dummy = new ListNode(1e9, head); - ListNode* cur = head; - vector stk = {dummy}; - for (ListNode* cur = head; cur; cur = cur->next) { - while (stk.back()->val < cur->val) { - stk.pop_back(); - } - stk.back()->next = cur; - stk.push_back(cur); - } - return dummy->next; - } -}; -``` - -### **Go** - ```go /** * Definition for singly-linked list. @@ -282,30 +191,6 @@ func removeNodes(head *ListNode) *ListNode { } ``` -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -func removeNodes(head *ListNode) *ListNode { - dummy := &ListNode{1 << 30, head} - stk := []*ListNode{dummy} - for cur := head; cur != nil; cur = cur.Next { - for stk[len(stk)-1].Val < cur.Val { - stk = stk[:len(stk)-1] - } - stk[len(stk)-1].Next = cur - stk = append(stk, cur) - } - return dummy.Next -} -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -341,6 +226,111 @@ function removeNodes(head: ListNode | null): ListNode | null { } ``` + + +### 方法二 + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: + dummy = ListNode(inf, head) + cur = head + stk = [dummy] + while cur: + while stk[-1].val < cur.val: + stk.pop() + stk[-1].next = cur + stk.append(cur) + cur = cur.next + return dummy.next +``` + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode removeNodes(ListNode head) { + ListNode dummy = new ListNode(1 << 30, head); + Deque stk = new ArrayDeque<>(); + stk.offerLast(dummy); + for (ListNode cur = head; cur != null; cur = cur.next) { + while (stk.peekLast().val < cur.val) { + stk.pollLast(); + } + stk.peekLast().next = cur; + stk.offerLast(cur); + } + return dummy.next; + } +} +``` + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNodes(ListNode* head) { + ListNode* dummy = new ListNode(1e9, head); + ListNode* cur = head; + vector stk = {dummy}; + for (ListNode* cur = head; cur; cur = cur->next) { + while (stk.back()->val < cur->val) { + stk.pop_back(); + } + stk.back()->next = cur; + stk.push_back(cur); + } + return dummy->next; + } +}; +``` + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func removeNodes(head *ListNode) *ListNode { + dummy := &ListNode{1 << 30, head} + stk := []*ListNode{dummy} + for cur := head; cur != nil; cur = cur.Next { + for stk[len(stk)-1].Val < cur.Val { + stk = stk[:len(stk)-1] + } + stk[len(stk)-1].Next = cur + stk = append(stk, cur) + } + return dummy.Next +} +``` + ```ts /** * Definition for singly-linked list. @@ -368,10 +358,6 @@ function removeNodes(head: ListNode | null): ListNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2487.Remove Nodes From Linked List/README_EN.md b/solution/2400-2499/2487.Remove Nodes From Linked List/README_EN.md index c6ceffa9adc78..930a16d0f9be3 100644 --- a/solution/2400-2499/2487.Remove Nodes From Linked List/README_EN.md +++ b/solution/2400-2499/2487.Remove Nodes From Linked List/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Monotonic Stack Simulation** +### Solution 1: Monotonic Stack Simulation We can first store the node values of the linked list into an array $nums$. Then, we traverse the array $nums$, maintaining a stack $stk$ that is monotonically decreasing from the bottom to the top. If the current element is larger than the top element of the stack, we pop the top element of the stack until the current element is less than or equal to the top element, and then we push the current element into the stack. @@ -56,8 +56,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -83,28 +81,6 @@ class Solution: return dummy.next ``` -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: - dummy = ListNode(inf, head) - cur = head - stk = [dummy] - while cur: - while stk[-1].val < cur.val: - stk.pop() - stk[-1].next = cur - stk.append(cur) - cur = cur.next - return dummy.next -``` - -### **Java** - ```java /** * Definition for singly-linked list. @@ -141,36 +117,6 @@ class Solution { } ``` -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode removeNodes(ListNode head) { - ListNode dummy = new ListNode(1 << 30, head); - Deque stk = new ArrayDeque<>(); - stk.offerLast(dummy); - for (ListNode cur = head; cur != null; cur = cur.next) { - while (stk.peekLast().val < cur.val) { - stk.pollLast(); - } - stk.peekLast().next = cur; - stk.offerLast(cur); - } - return dummy.next; - } -} -``` - -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -208,37 +154,6 @@ public: }; ``` -```cpp -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* removeNodes(ListNode* head) { - ListNode* dummy = new ListNode(1e9, head); - ListNode* cur = head; - vector stk = {dummy}; - for (ListNode* cur = head; cur; cur = cur->next) { - while (stk.back()->val < cur->val) { - stk.pop_back(); - } - stk.back()->next = cur; - stk.push_back(cur); - } - return dummy->next; - } -}; -``` - -### **Go** - ```go /** * Definition for singly-linked list. @@ -270,30 +185,6 @@ func removeNodes(head *ListNode) *ListNode { } ``` -```go -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ -func removeNodes(head *ListNode) *ListNode { - dummy := &ListNode{1 << 30, head} - stk := []*ListNode{dummy} - for cur := head; cur != nil; cur = cur.Next { - for stk[len(stk)-1].Val < cur.Val { - stk = stk[:len(stk)-1] - } - stk[len(stk)-1].Next = cur - stk = append(stk, cur) - } - return dummy.Next -} -``` - -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -329,6 +220,111 @@ function removeNodes(head: ListNode | null): ListNode | null { } ``` + + +### Solution 2 + + + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: + dummy = ListNode(inf, head) + cur = head + stk = [dummy] + while cur: + while stk[-1].val < cur.val: + stk.pop() + stk[-1].next = cur + stk.append(cur) + cur = cur.next + return dummy.next +``` + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode removeNodes(ListNode head) { + ListNode dummy = new ListNode(1 << 30, head); + Deque stk = new ArrayDeque<>(); + stk.offerLast(dummy); + for (ListNode cur = head; cur != null; cur = cur.next) { + while (stk.peekLast().val < cur.val) { + stk.pollLast(); + } + stk.peekLast().next = cur; + stk.offerLast(cur); + } + return dummy.next; + } +} +``` + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNodes(ListNode* head) { + ListNode* dummy = new ListNode(1e9, head); + ListNode* cur = head; + vector stk = {dummy}; + for (ListNode* cur = head; cur; cur = cur->next) { + while (stk.back()->val < cur->val) { + stk.pop_back(); + } + stk.back()->next = cur; + stk.push_back(cur); + } + return dummy->next; + } +}; +``` + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func removeNodes(head *ListNode) *ListNode { + dummy := &ListNode{1 << 30, head} + stk := []*ListNode{dummy} + for cur := head; cur != nil; cur = cur.Next { + for stk[len(stk)-1].Val < cur.Val { + stk = stk[:len(stk)-1] + } + stk[len(stk)-1].Next = cur + stk = append(stk, cur) + } + return dummy.Next +} +``` + ```ts /** * Definition for singly-linked list. @@ -356,10 +352,6 @@ function removeNodes(head: ListNode | null): ListNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2488.Count Subarrays With Median K/README.md b/solution/2400-2499/2488.Count Subarrays With Median K/README.md index 291b9475ee762..e77be1d758ca2 100644 --- a/solution/2400-2499/2488.Count Subarrays With Median K/README.md +++ b/solution/2400-2499/2488.Count Subarrays With Median K/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:遍历 + 计数** +### 方法一:遍历 + 计数 我们先找到中位数 $k$ 在数组中的位置 $i$,然后从 $i$ 开始向两边遍历,统计中位数为 $k$ 的子数组的数目。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countSubarrays(int[] nums, int k) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go func countSubarrays(nums []int, k int) int { i, n := 0, len(nums) @@ -199,8 +185,6 @@ func countSubarrays(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function countSubarrays(nums: number[], k: number): number { const i = nums.indexOf(k); @@ -223,10 +207,6 @@ function countSubarrays(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2488.Count Subarrays With Median K/README_EN.md b/solution/2400-2499/2488.Count Subarrays With Median K/README_EN.md index e4aeb167d360f..7d18e2e92c7cc 100644 --- a/solution/2400-2499/2488.Count Subarrays With Median K/README_EN.md +++ b/solution/2400-2499/2488.Count Subarrays With Median K/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countSubarrays(int[] nums, int k) { @@ -103,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +131,6 @@ public: }; ``` -### **Go** - ```go func countSubarrays(nums []int, k int) int { i, n := 0, len(nums) @@ -173,8 +167,6 @@ func countSubarrays(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function countSubarrays(nums: number[], k: number): number { const i = nums.indexOf(k); @@ -197,10 +189,6 @@ function countSubarrays(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2489.Number of Substrings With Fixed Ratio/README.md b/solution/2400-2499/2489.Number of Substrings With Fixed Ratio/README.md index e7c76702e6bc2..7cce9c37eab0c 100644 --- a/solution/2400-2499/2489.Number of Substrings With Fixed Ratio/README.md +++ b/solution/2400-2499/2489.Number of Substrings With Fixed Ratio/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:前缀和 + 计数** +### 方法一:前缀和 + 计数 我们用 $one[i]$ 表示字符串 $s[0,..i]$ 中 $1$ 的个数,用 $zero[i]$ 表示字符串 $s[0,..i]$ 中 $0$ 的个数。子串符合条件,需要满足 @@ -82,10 +80,6 @@ $$ -### **Python3** - - - ```python class Solution: def fixedRatio(self, s: str, num1: int, num2: int) -> int: @@ -101,10 +95,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long fixedRatio(String s, int num1, int num2) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -148,8 +136,6 @@ public: }; ``` -### **Go** - ```go func fixedRatio(s string, num1 int, num2 int) int64 { n0, n1 := 0, 0 @@ -169,10 +155,6 @@ func fixedRatio(s string, num1 int, num2 int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2489.Number of Substrings With Fixed Ratio/README_EN.md b/solution/2400-2499/2489.Number of Substrings With Fixed Ratio/README_EN.md index 7af2a60547217..562b5d6e655c0 100644 --- a/solution/2400-2499/2489.Number of Substrings With Fixed Ratio/README_EN.md +++ b/solution/2400-2499/2489.Number of Substrings With Fixed Ratio/README_EN.md @@ -54,9 +54,9 @@ It can be shown that there are no more ratio substrings. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long fixedRatio(String s, int num1, int num2) { @@ -94,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func fixedRatio(s string, num1 int, num2 int) int64 { n0, n1 := 0, 0 @@ -139,10 +133,6 @@ func fixedRatio(s string, num1 int, num2 int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2490.Circular Sentence/README.md b/solution/2400-2499/2490.Circular Sentence/README.md index 8993794713c76..edc7561d607f3 100644 --- a/solution/2400-2499/2490.Circular Sentence/README.md +++ b/solution/2400-2499/2490.Circular Sentence/README.md @@ -70,26 +70,14 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们将字符串按照空格分割成单词,然后判断每个单词的最后一个字符和下一个单词的第一个字符是否相等,如果不相等则返回 `false`,否则遍历完所有单词后返回 `true`。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串的长度。 -**方法二:模拟(空间优化)** - -我们可以先判断字符串的第一个字符和最后一个字符是否相等,如果不相等则返回 `false`,否则遍历字符串,如果当前字符是空格,则判断前一个字符和后一个字符是否相等,如果不相等则返回 `false`,否则遍历完所有字符后返回 `true`。 - -时间复杂度 $O(n)$,其中 $n$ 是字符串的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def isCircularSentence(self, sentence: str) -> bool: @@ -98,18 +86,6 @@ class Solution: return all(s[-1] == ss[(i + 1) % n][0] for i, s in enumerate(ss)) ``` -```python -class Solution: - def isCircularSentence(self, s: str) -> bool: - return s[0] == s[-1] and all( - c != " " or s[i - 1] == s[i + 1] for i, c in enumerate(s) - ) -``` - -### **Java** - - - ```java class Solution { public boolean isCircularSentence(String sentence) { @@ -125,25 +101,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isCircularSentence(String s) { - int n = s.length(); - if (s.charAt(0) != s.charAt(n - 1)) { - return false; - } - for (int i = 1; i < n; ++i) { - if (s.charAt(i) == ' ' && s.charAt(i - 1) != s.charAt(i + 1)) { - return false; - } - } - return true; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -170,26 +127,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool isCircularSentence(string s) { - int n = s.size(); - if (s[0] != s.back()) { - return false; - } - for (int i = 1; i < n; ++i) { - if (s[i] == ' ' && s[i - 1] != s[i + 1]) { - return false; - } - } - return true; - } -}; -``` - -### **Go** - ```go func isCircularSentence(sentence string) bool { ss := strings.Split(sentence, " ") @@ -203,22 +140,33 @@ func isCircularSentence(sentence string) bool { } ``` -```go -func isCircularSentence(s string) bool { - n := len(s) - if s[0] != s[n-1] { - return false - } - for i := 1; i < n; i++ { - if s[i] == ' ' && s[i-1] != s[i+1] { - return false - } - } - return true +```ts +function isCircularSentence(sentence: string): boolean { + const ss = sentence.split(' '); + const n = ss.length; + for (let i = 0; i < n; ++i) { + if (ss[i][ss[i].length - 1] !== ss[(i + 1) % n][0]) { + return false; + } + } + return true; } ``` -### **JavaScript** +```rust +impl Solution { + pub fn is_circular_sentence(sentence: String) -> bool { + let ss: Vec = sentence.split(' ').map(String::from).collect(); + let n = ss.len(); + for i in 0..n { + if ss[i].as_bytes()[ss[i].len() - 1] != ss[(i + 1) % n].as_bytes()[0] { + return false; + } + } + return true; + } +} +``` ```js /** @@ -237,37 +185,71 @@ var isCircularSentence = function (sentence) { }; ``` -```js -/** - * @param {string} s - * @return {boolean} - */ -var isCircularSentence = function (s) { - const n = s.length; - if (s[0] !== s[n - 1]) { - return false; - } - for (let i = 1; i < n; ++i) { - if (s[i] === ' ' && s[i - 1] !== s[i + 1]) { + + +### 方法二:模拟(空间优化) + +我们可以先判断字符串的第一个字符和最后一个字符是否相等,如果不相等则返回 `false`,否则遍历字符串,如果当前字符是空格,则判断前一个字符和后一个字符是否相等,如果不相等则返回 `false`,否则遍历完所有字符后返回 `true`。 + +时间复杂度 $O(n)$,其中 $n$ 是字符串的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def isCircularSentence(self, s: str) -> bool: + return s[0] == s[-1] and all( + c != " " or s[i - 1] == s[i + 1] for i, c in enumerate(s) + ) +``` + +```java +class Solution { + public boolean isCircularSentence(String s) { + int n = s.length(); + if (s.charAt(0) != s.charAt(n - 1)) { return false; } + for (int i = 1; i < n; ++i) { + if (s.charAt(i) == ' ' && s.charAt(i - 1) != s.charAt(i + 1)) { + return false; + } + } + return true; } - return true; -}; +} ``` -### **TypeScript** - -```ts -function isCircularSentence(sentence: string): boolean { - const ss = sentence.split(' '); - const n = ss.length; - for (let i = 0; i < n; ++i) { - if (ss[i][ss[i].length - 1] !== ss[(i + 1) % n][0]) { +```cpp +class Solution { +public: + bool isCircularSentence(string s) { + int n = s.size(); + if (s[0] != s.back()) { return false; } + for (int i = 1; i < n; ++i) { + if (s[i] == ' ' && s[i - 1] != s[i + 1]) { + return false; + } + } + return true; } - return true; +}; +``` + +```go +func isCircularSentence(s string) bool { + n := len(s) + if s[0] != s[n-1] { + return false + } + for i := 1; i < n; i++ { + if s[i] == ' ' && s[i-1] != s[i+1] { + return false + } + } + return true } ``` @@ -286,23 +268,6 @@ function isCircularSentence(s: string): boolean { } ``` -### **Rust** - -```rust -impl Solution { - pub fn is_circular_sentence(sentence: String) -> bool { - let ss: Vec = sentence.split(' ').map(String::from).collect(); - let n = ss.len(); - for i in 0..n { - if ss[i].as_bytes()[ss[i].len() - 1] != ss[(i + 1) % n].as_bytes()[0] { - return false; - } - } - return true; - } -} -``` - ```rust impl Solution { pub fn is_circular_sentence(sentence: String) -> bool { @@ -324,10 +289,25 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {string} s + * @return {boolean} + */ +var isCircularSentence = function (s) { + const n = s.length; + if (s[0] !== s[n - 1]) { + return false; + } + for (let i = 1; i < n; ++i) { + if (s[i] === ' ' && s[i - 1] !== s[i + 1]) { + return false; + } + } + return true; +}; ``` + + diff --git a/solution/2400-2499/2490.Circular Sentence/README_EN.md b/solution/2400-2499/2490.Circular Sentence/README_EN.md index 8eb93cb21daa4..6a2f92aa54ff5 100644 --- a/solution/2400-2499/2490.Circular Sentence/README_EN.md +++ b/solution/2400-2499/2490.Circular Sentence/README_EN.md @@ -66,9 +66,9 @@ The sentence is not circular. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,16 +78,6 @@ class Solution: return all(s[-1] == ss[(i + 1) % n][0] for i, s in enumerate(ss)) ``` -```python -class Solution: - def isCircularSentence(self, s: str) -> bool: - return s[0] == s[-1] and all( - c != " " or s[i - 1] == s[i + 1] for i, c in enumerate(s) - ) -``` - -### **Java** - ```java class Solution { public boolean isCircularSentence(String sentence) { @@ -103,25 +93,6 @@ class Solution { } ``` -```java -class Solution { - public boolean isCircularSentence(String s) { - int n = s.length(); - if (s.charAt(0) != s.charAt(n - 1)) { - return false; - } - for (int i = 1; i < n; ++i) { - if (s.charAt(i) == ' ' && s.charAt(i - 1) != s.charAt(i + 1)) { - return false; - } - } - return true; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -148,26 +119,6 @@ public: }; ``` -```cpp -class Solution { -public: - bool isCircularSentence(string s) { - int n = s.size(); - if (s[0] != s.back()) { - return false; - } - for (int i = 1; i < n; ++i) { - if (s[i] == ' ' && s[i - 1] != s[i + 1]) { - return false; - } - } - return true; - } -}; -``` - -### **Go** - ```go func isCircularSentence(sentence string) bool { ss := strings.Split(sentence, " ") @@ -181,22 +132,33 @@ func isCircularSentence(sentence string) bool { } ``` -```go -func isCircularSentence(s string) bool { - n := len(s) - if s[0] != s[n-1] { - return false - } - for i := 1; i < n; i++ { - if s[i] == ' ' && s[i-1] != s[i+1] { - return false - } - } - return true +```ts +function isCircularSentence(sentence: string): boolean { + const ss = sentence.split(' '); + const n = ss.length; + for (let i = 0; i < n; ++i) { + if (ss[i][ss[i].length - 1] !== ss[(i + 1) % n][0]) { + return false; + } + } + return true; } ``` -### **JavaScript** +```rust +impl Solution { + pub fn is_circular_sentence(sentence: String) -> bool { + let ss: Vec = sentence.split(' ').map(String::from).collect(); + let n = ss.len(); + for i in 0..n { + if ss[i].as_bytes()[ss[i].len() - 1] != ss[(i + 1) % n].as_bytes()[0] { + return false; + } + } + return true; + } +} +``` ```js /** @@ -215,37 +177,67 @@ var isCircularSentence = function (sentence) { }; ``` -```js -/** - * @param {string} s - * @return {boolean} - */ -var isCircularSentence = function (s) { - const n = s.length; - if (s[0] !== s[n - 1]) { - return false; - } - for (let i = 1; i < n; ++i) { - if (s[i] === ' ' && s[i - 1] !== s[i + 1]) { + + +### Solution 2 + + + +```python +class Solution: + def isCircularSentence(self, s: str) -> bool: + return s[0] == s[-1] and all( + c != " " or s[i - 1] == s[i + 1] for i, c in enumerate(s) + ) +``` + +```java +class Solution { + public boolean isCircularSentence(String s) { + int n = s.length(); + if (s.charAt(0) != s.charAt(n - 1)) { return false; } + for (int i = 1; i < n; ++i) { + if (s.charAt(i) == ' ' && s.charAt(i - 1) != s.charAt(i + 1)) { + return false; + } + } + return true; } - return true; -}; +} ``` -### **TypeScript** - -```ts -function isCircularSentence(sentence: string): boolean { - const ss = sentence.split(' '); - const n = ss.length; - for (let i = 0; i < n; ++i) { - if (ss[i][ss[i].length - 1] !== ss[(i + 1) % n][0]) { +```cpp +class Solution { +public: + bool isCircularSentence(string s) { + int n = s.size(); + if (s[0] != s.back()) { return false; } + for (int i = 1; i < n; ++i) { + if (s[i] == ' ' && s[i - 1] != s[i + 1]) { + return false; + } + } + return true; } - return true; +}; +``` + +```go +func isCircularSentence(s string) bool { + n := len(s) + if s[0] != s[n-1] { + return false + } + for i := 1; i < n; i++ { + if s[i] == ' ' && s[i-1] != s[i+1] { + return false + } + } + return true } ``` @@ -264,23 +256,6 @@ function isCircularSentence(s: string): boolean { } ``` -### **Rust** - -```rust -impl Solution { - pub fn is_circular_sentence(sentence: String) -> bool { - let ss: Vec = sentence.split(' ').map(String::from).collect(); - let n = ss.len(); - for i in 0..n { - if ss[i].as_bytes()[ss[i].len() - 1] != ss[(i + 1) % n].as_bytes()[0] { - return false; - } - } - return true; - } -} -``` - ```rust impl Solution { pub fn is_circular_sentence(sentence: String) -> bool { @@ -302,10 +277,25 @@ impl Solution { } ``` -### **...** - -``` - +```js +/** + * @param {string} s + * @return {boolean} + */ +var isCircularSentence = function (s) { + const n = s.length; + if (s[0] !== s[n - 1]) { + return false; + } + for (let i = 1; i < n; ++i) { + if (s[i] === ' ' && s[i - 1] !== s[i + 1]) { + return false; + } + } + return true; +}; ``` + + diff --git a/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/README.md b/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/README.md index 6fdc01059dd3f..7510c463db934 100644 --- a/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/README.md +++ b/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 要使得所有 $2$ 人团队的技能点相等,最小值一定需要跟最大值匹配。因此,我们将数组 `skill` 排序,然后用双指针 $i$ 和 $j$ 分别指向数组的首位,两两匹配,判断其和是否均为同一个数。 @@ -67,16 +65,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组 `skill` 的长度。 -**方法二:计数** - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `skill` 的长度。 - -### **Python3** - - - ```python class Solution: def dividePlayers(self, skill: List[int]) -> int: @@ -92,6 +82,115 @@ class Solution: return ans ``` +```java +class Solution { + public long dividePlayers(int[] skill) { + Arrays.sort(skill); + int n = skill.length; + int t = skill[0] + skill[n - 1]; + long ans = 0; + for (int i = 0, j = n - 1; i < j; ++i, --j) { + if (skill[i] + skill[j] != t) { + return -1; + } + ans += (long) skill[i] * skill[j]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + long long dividePlayers(vector& skill) { + sort(skill.begin(), skill.end()); + int n = skill.size(); + int t = skill[0] + skill[n - 1]; + long long ans = 0; + for (int i = 0, j = n - 1; i < j; ++i, --j) { + if (skill[i] + skill[j] != t) return -1; + ans += 1ll * skill[i] * skill[j]; + } + return ans; + } +}; +``` + +```go +func dividePlayers(skill []int) (ans int64) { + sort.Ints(skill) + n := len(skill) + t := skill[0] + skill[n-1] + for i, j := 0, n-1; i < j; i, j = i+1, j-1 { + if skill[i]+skill[j] != t { + return -1 + } + ans += int64(skill[i] * skill[j]) + } + return +} +``` + +```ts +function dividePlayers(skill: number[]): number { + const n = skill.length; + skill.sort((a, b) => a - b); + const target = skill[0] + skill[n - 1]; + let ans = 0; + for (let i = 0; i < n >> 1; i++) { + if (target !== skill[i] + skill[n - 1 - i]) { + return -1; + } + ans += skill[i] * skill[n - 1 - i]; + } + return ans; +} +``` + +```rust +impl Solution { + pub fn divide_players(mut skill: Vec) -> i64 { + let n = skill.len(); + skill.sort(); + let target = skill[0] + skill[n - 1]; + let mut ans = 0; + for i in 0..n >> 1 { + if skill[i] + skill[n - 1 - i] != target { + return -1; + } + ans += (skill[i] * skill[n - 1 - i]) as i64; + } + ans + } +} +``` + +```js +var dividePlayers = function (skill) { + const n = skill.length, + m = n / 2; + skill.sort((a, b) => a - b); + const sum = skill[0] + skill[n - 1]; + let ans = 0; + for (let i = 0; i < m; i++) { + const x = skill[i], + y = skill[n - 1 - i]; + if (x + y != sum) return -1; + ans += x * y; + } + return ans; +}; +``` + + + +### 方法二:计数 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 `skill` 的长度。 + + + ```python class Solution: def dividePlayers(self, skill: List[int]) -> int: @@ -112,28 +211,6 @@ class Solution: return -1 if m else ans ``` -### **Java** - - - -```java -class Solution { - public long dividePlayers(int[] skill) { - Arrays.sort(skill); - int n = skill.length; - int t = skill[0] + skill[n - 1]; - long ans = 0; - for (int i = 0, j = n - 1; i < j; ++i, --j) { - if (skill[i] + skill[j] != t) { - return -1; - } - ans += (long) skill[i] * skill[j]; - } - return ans; - } -} -``` - ```java class Solution { public long dividePlayers(int[] skill) { @@ -159,25 +236,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - long long dividePlayers(vector& skill) { - sort(skill.begin(), skill.end()); - int n = skill.size(); - int t = skill[0] + skill[n - 1]; - long long ans = 0; - for (int i = 0, j = n - 1; i < j; ++i, --j) { - if (skill[i] + skill[j] != t) return -1; - ans += 1ll * skill[i] * skill[j]; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -202,23 +260,6 @@ public: }; ``` -### **Go** - -```go -func dividePlayers(skill []int) (ans int64) { - sort.Ints(skill) - n := len(skill) - t := skill[0] + skill[n-1] - for i, j := 0, n-1; i < j; i, j = i+1, j-1 { - if skill[i]+skill[j] != t { - return -1 - } - ans += int64(skill[i] * skill[j]) - } - return -} -``` - ```go func dividePlayers(skill []int) int64 { s := 0 @@ -248,67 +289,6 @@ func dividePlayers(skill []int) int64 { } ``` -### **JavaScript** - -```js -var dividePlayers = function (skill) { - const n = skill.length, - m = n / 2; - skill.sort((a, b) => a - b); - const sum = skill[0] + skill[n - 1]; - let ans = 0; - for (let i = 0; i < m; i++) { - const x = skill[i], - y = skill[n - 1 - i]; - if (x + y != sum) return -1; - ans += x * y; - } - return ans; -}; -``` - -### **TypeScript** - -```ts -function dividePlayers(skill: number[]): number { - const n = skill.length; - skill.sort((a, b) => a - b); - const target = skill[0] + skill[n - 1]; - let ans = 0; - for (let i = 0; i < n >> 1; i++) { - if (target !== skill[i] + skill[n - 1 - i]) { - return -1; - } - ans += skill[i] * skill[n - 1 - i]; - } - return ans; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn divide_players(mut skill: Vec) -> i64 { - let n = skill.len(); - skill.sort(); - let target = skill[0] + skill[n - 1]; - let mut ans = 0; - for i in 0..n >> 1 { - if skill[i] + skill[n - 1 - i] != target { - return -1; - } - ans += (skill[i] * skill[n - 1 - i]) as i64; - } - ans - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/README_EN.md b/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/README_EN.md index a3247cd941ce0..4cf469187fee7 100644 --- a/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/README_EN.md +++ b/solution/2400-2499/2491.Divide Players Into Teams of Equal Skill/README_EN.md @@ -51,9 +51,9 @@ There is no way to divide the players into teams such that the total skill of ea ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,6 +70,113 @@ class Solution: return ans ``` +```java +class Solution { + public long dividePlayers(int[] skill) { + Arrays.sort(skill); + int n = skill.length; + int t = skill[0] + skill[n - 1]; + long ans = 0; + for (int i = 0, j = n - 1; i < j; ++i, --j) { + if (skill[i] + skill[j] != t) { + return -1; + } + ans += (long) skill[i] * skill[j]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + long long dividePlayers(vector& skill) { + sort(skill.begin(), skill.end()); + int n = skill.size(); + int t = skill[0] + skill[n - 1]; + long long ans = 0; + for (int i = 0, j = n - 1; i < j; ++i, --j) { + if (skill[i] + skill[j] != t) return -1; + ans += 1ll * skill[i] * skill[j]; + } + return ans; + } +}; +``` + +```go +func dividePlayers(skill []int) (ans int64) { + sort.Ints(skill) + n := len(skill) + t := skill[0] + skill[n-1] + for i, j := 0, n-1; i < j; i, j = i+1, j-1 { + if skill[i]+skill[j] != t { + return -1 + } + ans += int64(skill[i] * skill[j]) + } + return +} +``` + +```ts +function dividePlayers(skill: number[]): number { + const n = skill.length; + skill.sort((a, b) => a - b); + const target = skill[0] + skill[n - 1]; + let ans = 0; + for (let i = 0; i < n >> 1; i++) { + if (target !== skill[i] + skill[n - 1 - i]) { + return -1; + } + ans += skill[i] * skill[n - 1 - i]; + } + return ans; +} +``` + +```rust +impl Solution { + pub fn divide_players(mut skill: Vec) -> i64 { + let n = skill.len(); + skill.sort(); + let target = skill[0] + skill[n - 1]; + let mut ans = 0; + for i in 0..n >> 1 { + if skill[i] + skill[n - 1 - i] != target { + return -1; + } + ans += (skill[i] * skill[n - 1 - i]) as i64; + } + ans + } +} +``` + +```js +var dividePlayers = function (skill) { + const n = skill.length, + m = n / 2; + skill.sort((a, b) => a - b); + const sum = skill[0] + skill[n - 1]; + let ans = 0; + for (let i = 0; i < m; i++) { + const x = skill[i], + y = skill[n - 1 - i]; + if (x + y != sum) return -1; + ans += x * y; + } + return ans; +}; +``` + + + +### Solution 2 + + + ```python class Solution: def dividePlayers(self, skill: List[int]) -> int: @@ -90,26 +197,6 @@ class Solution: return -1 if m else ans ``` -### **Java** - -```java -class Solution { - public long dividePlayers(int[] skill) { - Arrays.sort(skill); - int n = skill.length; - int t = skill[0] + skill[n - 1]; - long ans = 0; - for (int i = 0, j = n - 1; i < j; ++i, --j) { - if (skill[i] + skill[j] != t) { - return -1; - } - ans += (long) skill[i] * skill[j]; - } - return ans; - } -} -``` - ```java class Solution { public long dividePlayers(int[] skill) { @@ -135,25 +222,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - long long dividePlayers(vector& skill) { - sort(skill.begin(), skill.end()); - int n = skill.size(); - int t = skill[0] + skill[n - 1]; - long long ans = 0; - for (int i = 0, j = n - 1; i < j; ++i, --j) { - if (skill[i] + skill[j] != t) return -1; - ans += 1ll * skill[i] * skill[j]; - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -178,23 +246,6 @@ public: }; ``` -### **Go** - -```go -func dividePlayers(skill []int) (ans int64) { - sort.Ints(skill) - n := len(skill) - t := skill[0] + skill[n-1] - for i, j := 0, n-1; i < j; i, j = i+1, j-1 { - if skill[i]+skill[j] != t { - return -1 - } - ans += int64(skill[i] * skill[j]) - } - return -} -``` - ```go func dividePlayers(skill []int) int64 { s := 0 @@ -224,67 +275,6 @@ func dividePlayers(skill []int) int64 { } ``` -### **JavaScript** - -```js -var dividePlayers = function (skill) { - const n = skill.length, - m = n / 2; - skill.sort((a, b) => a - b); - const sum = skill[0] + skill[n - 1]; - let ans = 0; - for (let i = 0; i < m; i++) { - const x = skill[i], - y = skill[n - 1 - i]; - if (x + y != sum) return -1; - ans += x * y; - } - return ans; -}; -``` - -### **TypeScript** - -```ts -function dividePlayers(skill: number[]): number { - const n = skill.length; - skill.sort((a, b) => a - b); - const target = skill[0] + skill[n - 1]; - let ans = 0; - for (let i = 0; i < n >> 1; i++) { - if (target !== skill[i] + skill[n - 1 - i]) { - return -1; - } - ans += skill[i] * skill[n - 1 - i]; - } - return ans; -} -``` - -### **Rust** - -```rust -impl Solution { - pub fn divide_players(mut skill: Vec) -> i64 { - let n = skill.len(); - skill.sort(); - let target = skill[0] + skill[n - 1]; - let mut ans = 0; - for i in 0..n >> 1 { - if skill[i] + skill[n - 1 - i] != target { - return -1; - } - ans += (skill[i] * skill[n - 1 - i]) as i64; - } - ans - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/README.md b/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/README.md index 8ca14a2c7d08c..6474c6d16705a 100644 --- a/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/README.md +++ b/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/README.md @@ -60,26 +60,14 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 根据题目描述,每条边可以经过多次,并且保证节点 $1$ 和节点 $n$ 在同一个连通块中。因此,题目实际上求的是节点 $1$ 所在的连通块的最小边。我们可以用 DFS,从节点 $1$ 开始搜索所有的边,找到最小的边即可。 时间复杂度 $O(n + m)$。其中 $n$ 和 $m$ 分别是节点数和边数。 -**方法二:BFS** - -我们也可以用 BFS 来求解。 - -时间复杂度 $O(n + m)$。其中 $n$ 和 $m$ 分别是节点数和边数。 - -### **Python3** - - - ```python class Solution: def minScore(self, n: int, roads: List[List[int]]) -> int: @@ -101,32 +89,6 @@ class Solution: return ans ``` -```python -class Solution: - def minScore(self, n: int, roads: List[List[int]]) -> int: - g = defaultdict(list) - for a, b, d in roads: - g[a].append((b, d)) - g[b].append((a, d)) - vis = [False] * (n + 1) - vis[1] = True - ans = inf - q = deque([1]) - while q: - for _ in range(len(q)): - i = q.popleft() - for j, d in g[i]: - ans = min(ans, d) - if not vis[j]: - vis[j] = True - q.append(j) - return ans -``` - -### **Java** - - - ```java class Solution { private List[] g; @@ -159,41 +121,6 @@ class Solution { } ``` -```java -class Solution { - public int minScore(int n, int[][] roads) { - List[] g = new List[n]; - boolean[] vis = new boolean[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (var e : roads) { - int a = e[0] - 1, b = e[1] - 1, d = e[2]; - g[a].add(new int[] {b, d}); - g[b].add(new int[] {a, d}); - } - Deque q = new ArrayDeque<>(); - q.offer(0); - vis[0] = true; - int ans = 1 << 30; - while (!q.isEmpty()) { - for (int k = q.size(); k > 0; --k) { - int i = q.pollFirst(); - for (var nxt : g[i]) { - int j = nxt[0], d = nxt[1]; - ans = Math.min(ans, d); - if (!vis[j]) { - vis[j] = true; - q.offer(j); - } - } - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -222,41 +149,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minScore(int n, vector>& roads) { - vector>> g(n); - bool vis[n]; - memset(vis, 0, sizeof vis); - for (auto& e : roads) { - int a = e[0] - 1, b = e[1] - 1, d = e[2]; - g[a].emplace_back(b, d); - g[b].emplace_back(a, d); - } - int ans = INT_MAX; - queue q{{0}}; - vis[0] = true; - while (!q.empty()) { - for (int k = q.size(); k; --k) { - int i = q.front(); - q.pop(); - for (auto [j, d] : g[i]) { - ans = min(ans, d); - if (!vis[j]) { - vis[j] = true; - q.push(j); - } - } - } - } - return ans; - } -}; -``` - -### **Go** - ```go func minScore(n int, roads [][]int) int { type pair struct{ i, v int } @@ -284,66 +176,6 @@ func minScore(n int, roads [][]int) int { } ``` -```go -func minScore(n int, roads [][]int) int { - type pair struct{ i, v int } - g := make([][]pair, n) - for _, e := range roads { - a, b, d := e[0]-1, e[1]-1, e[2] - g[a] = append(g[a], pair{b, d}) - g[b] = append(g[b], pair{a, d}) - } - vis := make([]bool, n) - ans := 1 << 30 - q := []int{0} - vis[0] = true - for len(q) > 0 { - for k := len(q); k > 0; k-- { - i := q[0] - q = q[1:] - for _, nxt := range g[i] { - j, d := nxt.i, nxt.v - ans = min(ans, d) - if !vis[j] { - vis[j] = true - q = append(q, j) - } - } - } - } - return ans -} -``` - -### **JavaScript** - -```js -var minScore = function (n, roads) { - // 构建点到点的映射表 - const graph = Array.from({ length: n + 1 }, () => new Map()); - for (let [u, v, w] of roads) { - graph[u].set(v, w); - graph[v].set(u, w); - } - - // DFS - const vis = new Array(n).fill(false); - let ans = Infinity; - var dfs = function (u) { - vis[u] = true; - for (const [v, w] of graph[u]) { - ans = Math.min(ans, w); - if (!vis[v]) dfs(v); - } - }; - dfs(1); - - return ans; -}; -``` - -### **TypeScript** - ```ts function minScore(n: number, roads: number[][]): number { const vis = new Array(n + 1).fill(false); @@ -368,8 +200,6 @@ function minScore(n: number, roads: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { fn dfs(i: usize, mut ans: i32, g: &Vec>, vis: &mut Vec) -> i32 { @@ -399,10 +229,160 @@ impl Solution { } ``` -### **...** +```js +var minScore = function (n, roads) { + // 构建点到点的映射表 + const graph = Array.from({ length: n + 1 }, () => new Map()); + for (let [u, v, w] of roads) { + graph[u].set(v, w); + graph[v].set(u, w); + } + + // DFS + const vis = new Array(n).fill(false); + let ans = Infinity; + var dfs = function (u) { + vis[u] = true; + for (const [v, w] of graph[u]) { + ans = Math.min(ans, w); + if (!vis[v]) dfs(v); + } + }; + dfs(1); + + return ans; +}; +``` + + + +### 方法二:BFS + +我们也可以用 BFS 来求解。 + +时间复杂度 $O(n + m)$。其中 $n$ 和 $m$ 分别是节点数和边数。 + + + +```python +class Solution: + def minScore(self, n: int, roads: List[List[int]]) -> int: + g = defaultdict(list) + for a, b, d in roads: + g[a].append((b, d)) + g[b].append((a, d)) + vis = [False] * (n + 1) + vis[1] = True + ans = inf + q = deque([1]) + while q: + for _ in range(len(q)): + i = q.popleft() + for j, d in g[i]: + ans = min(ans, d) + if not vis[j]: + vis[j] = True + q.append(j) + return ans +``` + +```java +class Solution { + public int minScore(int n, int[][] roads) { + List[] g = new List[n]; + boolean[] vis = new boolean[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (var e : roads) { + int a = e[0] - 1, b = e[1] - 1, d = e[2]; + g[a].add(new int[] {b, d}); + g[b].add(new int[] {a, d}); + } + Deque q = new ArrayDeque<>(); + q.offer(0); + vis[0] = true; + int ans = 1 << 30; + while (!q.isEmpty()) { + for (int k = q.size(); k > 0; --k) { + int i = q.pollFirst(); + for (var nxt : g[i]) { + int j = nxt[0], d = nxt[1]; + ans = Math.min(ans, d); + if (!vis[j]) { + vis[j] = true; + q.offer(j); + } + } + } + } + return ans; + } +} +``` +```cpp +class Solution { +public: + int minScore(int n, vector>& roads) { + vector>> g(n); + bool vis[n]; + memset(vis, 0, sizeof vis); + for (auto& e : roads) { + int a = e[0] - 1, b = e[1] - 1, d = e[2]; + g[a].emplace_back(b, d); + g[b].emplace_back(a, d); + } + int ans = INT_MAX; + queue q{{0}}; + vis[0] = true; + while (!q.empty()) { + for (int k = q.size(); k; --k) { + int i = q.front(); + q.pop(); + for (auto [j, d] : g[i]) { + ans = min(ans, d); + if (!vis[j]) { + vis[j] = true; + q.push(j); + } + } + } + } + return ans; + } +}; ``` +```go +func minScore(n int, roads [][]int) int { + type pair struct{ i, v int } + g := make([][]pair, n) + for _, e := range roads { + a, b, d := e[0]-1, e[1]-1, e[2] + g[a] = append(g[a], pair{b, d}) + g[b] = append(g[b], pair{a, d}) + } + vis := make([]bool, n) + ans := 1 << 30 + q := []int{0} + vis[0] = true + for len(q) > 0 { + for k := len(q); k > 0; k-- { + i := q[0] + q = q[1:] + for _, nxt := range g[i] { + j, d := nxt.i, nxt.v + ans = min(ans, d) + if !vis[j] { + vis[j] = true + q = append(q, j) + } + } + } + } + return ans +} ``` + + diff --git a/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/README_EN.md b/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/README_EN.md index 6b0c642ec476a..7bb0a96ed8dc9 100644 --- a/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/README_EN.md +++ b/solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/README_EN.md @@ -52,9 +52,9 @@ It can be shown that no other path has less score. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,30 +77,6 @@ class Solution: return ans ``` -```python -class Solution: - def minScore(self, n: int, roads: List[List[int]]) -> int: - g = defaultdict(list) - for a, b, d in roads: - g[a].append((b, d)) - g[b].append((a, d)) - vis = [False] * (n + 1) - vis[1] = True - ans = inf - q = deque([1]) - while q: - for _ in range(len(q)): - i = q.popleft() - for j, d in g[i]: - ans = min(ans, d) - if not vis[j]: - vis[j] = True - q.append(j) - return ans -``` - -### **Java** - ```java class Solution { private List[] g; @@ -133,41 +109,6 @@ class Solution { } ``` -```java -class Solution { - public int minScore(int n, int[][] roads) { - List[] g = new List[n]; - boolean[] vis = new boolean[n]; - Arrays.setAll(g, k -> new ArrayList<>()); - for (var e : roads) { - int a = e[0] - 1, b = e[1] - 1, d = e[2]; - g[a].add(new int[] {b, d}); - g[b].add(new int[] {a, d}); - } - Deque q = new ArrayDeque<>(); - q.offer(0); - vis[0] = true; - int ans = 1 << 30; - while (!q.isEmpty()) { - for (int k = q.size(); k > 0; --k) { - int i = q.pollFirst(); - for (var nxt : g[i]) { - int j = nxt[0], d = nxt[1]; - ans = Math.min(ans, d); - if (!vis[j]) { - vis[j] = true; - q.offer(j); - } - } - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -196,41 +137,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minScore(int n, vector>& roads) { - vector>> g(n); - bool vis[n]; - memset(vis, 0, sizeof vis); - for (auto& e : roads) { - int a = e[0] - 1, b = e[1] - 1, d = e[2]; - g[a].emplace_back(b, d); - g[b].emplace_back(a, d); - } - int ans = INT_MAX; - queue q{{0}}; - vis[0] = true; - while (!q.empty()) { - for (int k = q.size(); k; --k) { - int i = q.front(); - q.pop(); - for (auto [j, d] : g[i]) { - ans = min(ans, d); - if (!vis[j]) { - vis[j] = true; - q.push(j); - } - } - } - } - return ans; - } -}; -``` - -### **Go** - ```go func minScore(n int, roads [][]int) int { type pair struct{ i, v int } @@ -258,66 +164,6 @@ func minScore(n int, roads [][]int) int { } ``` -```go -func minScore(n int, roads [][]int) int { - type pair struct{ i, v int } - g := make([][]pair, n) - for _, e := range roads { - a, b, d := e[0]-1, e[1]-1, e[2] - g[a] = append(g[a], pair{b, d}) - g[b] = append(g[b], pair{a, d}) - } - vis := make([]bool, n) - ans := 1 << 30 - q := []int{0} - vis[0] = true - for len(q) > 0 { - for k := len(q); k > 0; k-- { - i := q[0] - q = q[1:] - for _, nxt := range g[i] { - j, d := nxt.i, nxt.v - ans = min(ans, d) - if !vis[j] { - vis[j] = true - q = append(q, j) - } - } - } - } - return ans -} -``` - -### **JavaScript** - -```js -var minScore = function (n, roads) { - // 构建点到点的映射表 - const graph = Array.from({ length: n + 1 }, () => new Map()); - for (let [u, v, w] of roads) { - graph[u].set(v, w); - graph[v].set(u, w); - } - - // DFS - const vis = new Array(n).fill(false); - let ans = Infinity; - var dfs = function (u) { - vis[u] = true; - for (const [v, w] of graph[u]) { - ans = Math.min(ans, w); - if (!vis[v]) dfs(v); - } - }; - dfs(1); - - return ans; -}; -``` - -### **TypeScript** - ```ts function minScore(n: number, roads: number[][]): number { const vis = new Array(n + 1).fill(false); @@ -342,8 +188,6 @@ function minScore(n: number, roads: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { fn dfs(i: usize, mut ans: i32, g: &Vec>, vis: &mut Vec) -> i32 { @@ -373,10 +217,156 @@ impl Solution { } ``` -### **...** +```js +var minScore = function (n, roads) { + // 构建点到点的映射表 + const graph = Array.from({ length: n + 1 }, () => new Map()); + for (let [u, v, w] of roads) { + graph[u].set(v, w); + graph[v].set(u, w); + } + + // DFS + const vis = new Array(n).fill(false); + let ans = Infinity; + var dfs = function (u) { + vis[u] = true; + for (const [v, w] of graph[u]) { + ans = Math.min(ans, w); + if (!vis[v]) dfs(v); + } + }; + dfs(1); + + return ans; +}; +``` + + + +### Solution 2 + + + +```python +class Solution: + def minScore(self, n: int, roads: List[List[int]]) -> int: + g = defaultdict(list) + for a, b, d in roads: + g[a].append((b, d)) + g[b].append((a, d)) + vis = [False] * (n + 1) + vis[1] = True + ans = inf + q = deque([1]) + while q: + for _ in range(len(q)): + i = q.popleft() + for j, d in g[i]: + ans = min(ans, d) + if not vis[j]: + vis[j] = True + q.append(j) + return ans +``` + +```java +class Solution { + public int minScore(int n, int[][] roads) { + List[] g = new List[n]; + boolean[] vis = new boolean[n]; + Arrays.setAll(g, k -> new ArrayList<>()); + for (var e : roads) { + int a = e[0] - 1, b = e[1] - 1, d = e[2]; + g[a].add(new int[] {b, d}); + g[b].add(new int[] {a, d}); + } + Deque q = new ArrayDeque<>(); + q.offer(0); + vis[0] = true; + int ans = 1 << 30; + while (!q.isEmpty()) { + for (int k = q.size(); k > 0; --k) { + int i = q.pollFirst(); + for (var nxt : g[i]) { + int j = nxt[0], d = nxt[1]; + ans = Math.min(ans, d); + if (!vis[j]) { + vis[j] = true; + q.offer(j); + } + } + } + } + return ans; + } +} +``` +```cpp +class Solution { +public: + int minScore(int n, vector>& roads) { + vector>> g(n); + bool vis[n]; + memset(vis, 0, sizeof vis); + for (auto& e : roads) { + int a = e[0] - 1, b = e[1] - 1, d = e[2]; + g[a].emplace_back(b, d); + g[b].emplace_back(a, d); + } + int ans = INT_MAX; + queue q{{0}}; + vis[0] = true; + while (!q.empty()) { + for (int k = q.size(); k; --k) { + int i = q.front(); + q.pop(); + for (auto [j, d] : g[i]) { + ans = min(ans, d); + if (!vis[j]) { + vis[j] = true; + q.push(j); + } + } + } + } + return ans; + } +}; ``` +```go +func minScore(n int, roads [][]int) int { + type pair struct{ i, v int } + g := make([][]pair, n) + for _, e := range roads { + a, b, d := e[0]-1, e[1]-1, e[2] + g[a] = append(g[a], pair{b, d}) + g[b] = append(g[b], pair{a, d}) + } + vis := make([]bool, n) + ans := 1 << 30 + q := []int{0} + vis[0] = true + for len(q) > 0 { + for k := len(q); k > 0; k-- { + i := q[0] + q = q[1:] + for _, nxt := range g[i] { + j, d := nxt.i, nxt.v + ans = min(ans, d) + if !vis[j] { + vis[j] = true + q = append(q, j) + } + } + } + } + return ans +} ``` + + diff --git a/solution/2400-2499/2493.Divide Nodes Into the Maximum Number of Groups/README.md b/solution/2400-2499/2493.Divide Nodes Into the Maximum Number of Groups/README.md index 8113f44e666b4..0f11c051c1339 100644 --- a/solution/2400-2499/2493.Divide Nodes Into the Maximum Number of Groups/README.md +++ b/solution/2400-2499/2493.Divide Nodes Into the Maximum Number of Groups/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:DFS + BFS** +### 方法一:DFS + BFS 注意到图可能不连通,因此我们可以通过 DFS 找到每个连通块。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def magnificentSets(self, n: int, edges: List[List[int]]) -> int: @@ -123,10 +117,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -207,8 +197,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -277,8 +265,6 @@ public: }; ``` -### **Go** - ```go func magnificentSets(n int, edges [][]int) int { g := make([][]int, n+1) @@ -359,8 +345,6 @@ func abs(x int) int { } ``` -### **JavaScript** - ```js var magnificentSets = function (n, edges) { const graph = Array.from({ length: n + 1 }, () => new Set()); @@ -405,10 +389,6 @@ var magnificentSets = function (n, edges) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2493.Divide Nodes Into the Maximum Number of Groups/README_EN.md b/solution/2400-2499/2493.Divide Nodes Into the Maximum Number of Groups/README_EN.md index def639bf1de7c..447b01052ffee 100644 --- a/solution/2400-2499/2493.Divide Nodes Into the Maximum Number of Groups/README_EN.md +++ b/solution/2400-2499/2493.Divide Nodes Into the Maximum Number of Groups/README_EN.md @@ -55,9 +55,9 @@ It can be shown that no grouping is possible. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -107,8 +107,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -189,8 +187,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -259,8 +255,6 @@ public: }; ``` -### **Go** - ```go func magnificentSets(n int, edges [][]int) int { g := make([][]int, n+1) @@ -341,8 +335,6 @@ func abs(x int) int { } ``` -### **JavaScript** - ```js var magnificentSets = function (n, edges) { const graph = Array.from({ length: n + 1 }, () => new Set()); @@ -387,10 +379,6 @@ var magnificentSets = function (n, edges) { }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2494.Merge Overlapping Events in the Same Hall/README.md b/solution/2400-2499/2494.Merge Overlapping Events in the Same Hall/README.md index ea4c54715ff54..02896479443f0 100644 --- a/solution/2400-2499/2494.Merge Overlapping Events in the Same Hall/README.md +++ b/solution/2400-2499/2494.Merge Overlapping Events in the Same Hall/README.md @@ -64,14 +64,10 @@ HallEvents 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -114,3 +110,5 @@ GROUP BY hall_id, gid; ``` + + diff --git a/solution/2400-2499/2494.Merge Overlapping Events in the Same Hall/README_EN.md b/solution/2400-2499/2494.Merge Overlapping Events in the Same Hall/README_EN.md index d714237e4e7d9..e14a469b495f4 100644 --- a/solution/2400-2499/2494.Merge Overlapping Events in the Same Hall/README_EN.md +++ b/solution/2400-2499/2494.Merge Overlapping Events in the Same Hall/README_EN.md @@ -63,9 +63,9 @@ Hall 3: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -109,3 +109,5 @@ GROUP BY hall_id, gid; ``` + + diff --git a/solution/2400-2499/2495.Number of Subarrays Having Even Product/README.md b/solution/2400-2499/2495.Number of Subarrays Having Even Product/README.md index 64da076d70fd6..6592e9e022a80 100644 --- a/solution/2400-2499/2495.Number of Subarrays Having Even Product/README.md +++ b/solution/2400-2499/2495.Number of Subarrays Having Even Product/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们知道,一个子数组的乘积为偶数,当且仅当该子数组中至少有一个偶数。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def evenProduct(self, nums: List[int]) -> int: @@ -72,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long evenProduct(int[] nums) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +99,6 @@ public: }; ``` -### **Go** - ```go func evenProduct(nums []int) int64 { ans, last := 0, -1 @@ -126,10 +112,6 @@ func evenProduct(nums []int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2495.Number of Subarrays Having Even Product/README_EN.md b/solution/2400-2499/2495.Number of Subarrays Having Even Product/README_EN.md index 42868f17fe7c2..3e81125a8e79c 100644 --- a/solution/2400-2499/2495.Number of Subarrays Having Even Product/README_EN.md +++ b/solution/2400-2499/2495.Number of Subarrays Having Even Product/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,8 +54,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long evenProduct(int[] nums) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +87,6 @@ public: }; ``` -### **Go** - ```go func evenProduct(nums []int) int64 { ans, last := 0, -1 @@ -106,10 +100,6 @@ func evenProduct(nums []int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2496.Maximum Value of a String in an Array/README.md b/solution/2400-2499/2496.Maximum Value of a String in an Array/README.md index cdecbb47900dd..a7231fc98f847 100644 --- a/solution/2400-2499/2496.Maximum Value of a String in an Array/README.md +++ b/solution/2400-2499/2496.Maximum Value of a String in an Array/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们定义一个函数 $f(s)$,用于计算字符串 $s$ 的值。如果 $s$ 只包含数字,那么 $f(s)$ 就是 $s$ 在十进制下的值;否则 $f(s)$ 就是 $s$ 的长度。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def maximumValue(self, strs: List[str]) -> int: @@ -76,24 +70,6 @@ class Solution: return max(f(s) for s in strs) ``` -```python -class Solution: - def maximumValue(self, strs: List[str]) -> int: - def f(s: str) -> int: - x = 0 - for c in s: - if c.isalpha(): - return len(s) - x = x * 10 + ord(c) - ord("0") - return x - - return max(f(s) for s in strs) -``` - -### **Java** - - - ```java class Solution { public int maximumValue(String[] strs) { @@ -118,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +117,6 @@ public: }; ``` -### **Go** - ```go func maximumValue(strs []string) (ans int) { f := func(s string) (x int) { @@ -165,8 +137,6 @@ func maximumValue(strs []string) (ans int) { } ``` -### **TypeScript** - ```ts function maximumValue(strs: string[]): number { const f = (s: string) => (Number.isNaN(Number(s)) ? s.length : Number(s)); @@ -174,7 +144,18 @@ function maximumValue(strs: string[]): number { } ``` -### **C#** +```rust +impl Solution { + pub fn maximum_value(strs: Vec) -> i32 { + let mut ans = 0; + for s in strs.iter() { + let num = s.parse().unwrap_or(s.len()); + ans = ans.max(num); + } + ans as i32 + } +} +``` ```cs public class Solution { @@ -195,21 +176,51 @@ public class Solution { } ``` -### **Rust** +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) -```rust -impl Solution { - pub fn maximum_value(strs: Vec) -> i32 { - let mut ans = 0; - for s in strs.iter() { - let num = s.parse().unwrap_or(s.len()); - ans = ans.max(num); +int parseInt(char* s) { + int n = strlen(s); + int res = 0; + for (int i = 0; i < n; i++) { + if (!isdigit(s[i])) { + return n; } - ans as i32 + res = res * 10 + s[i] - '0'; } + return res; +} + +int maximumValue(char** strs, int strsSize) { + int ans = 0; + for (int i = 0; i < strsSize; i++) { + int num = parseInt(strs[i]); + ans = max(ans, num); + } + return ans; } ``` + + +### 方法二 + + + +```python +class Solution: + def maximumValue(self, strs: List[str]) -> int: + def f(s: str) -> int: + x = 0 + for c in s: + if c.isalpha(): + return len(s) + x = x * 10 + ord(c) - ord("0") + return x + + return max(f(s) for s in strs) +``` + ```rust impl Solution { pub fn maximum_value(strs: Vec) -> i32 { @@ -241,6 +252,12 @@ impl Solution { } ``` + + +### 方法三 + + + ```rust use std::cmp::max; @@ -264,37 +281,6 @@ impl Solution { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int parseInt(char* s) { - int n = strlen(s); - int res = 0; - for (int i = 0; i < n; i++) { - if (!isdigit(s[i])) { - return n; - } - res = res * 10 + s[i] - '0'; - } - return res; -} - -int maximumValue(char** strs, int strsSize) { - int ans = 0; - for (int i = 0; i < strsSize; i++) { - int num = parseInt(strs[i]); - ans = max(ans, num); - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2496.Maximum Value of a String in an Array/README_EN.md b/solution/2400-2499/2496.Maximum Value of a String in an Array/README_EN.md index ad3e442f0f362..965bbaafbe1cf 100644 --- a/solution/2400-2499/2496.Maximum Value of a String in an Array/README_EN.md +++ b/solution/2400-2499/2496.Maximum Value of a String in an Array/README_EN.md @@ -48,9 +48,9 @@ Each string in the array has value 1. Hence, we return 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,22 +61,6 @@ class Solution: return max(f(s) for s in strs) ``` -```python -class Solution: - def maximumValue(self, strs: List[str]) -> int: - def f(s: str) -> int: - x = 0 - for c in s: - if c.isalpha(): - return len(s) - x = x * 10 + ord(c) - ord("0") - return x - - return max(f(s) for s in strs) -``` - -### **Java** - ```java class Solution { public int maximumValue(String[] strs) { @@ -101,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +108,6 @@ public: }; ``` -### **Go** - ```go func maximumValue(strs []string) (ans int) { f := func(s string) (x int) { @@ -148,8 +128,6 @@ func maximumValue(strs []string) (ans int) { } ``` -### **TypeScript** - ```ts function maximumValue(strs: string[]): number { const f = (s: string) => (Number.isNaN(Number(s)) ? s.length : Number(s)); @@ -157,7 +135,18 @@ function maximumValue(strs: string[]): number { } ``` -### **C#** +```rust +impl Solution { + pub fn maximum_value(strs: Vec) -> i32 { + let mut ans = 0; + for s in strs.iter() { + let num = s.parse().unwrap_or(s.len()); + ans = ans.max(num); + } + ans as i32 + } +} +``` ```cs public class Solution { @@ -178,21 +167,51 @@ public class Solution { } ``` -### **Rust** +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) -```rust -impl Solution { - pub fn maximum_value(strs: Vec) -> i32 { - let mut ans = 0; - for s in strs.iter() { - let num = s.parse().unwrap_or(s.len()); - ans = ans.max(num); +int parseInt(char* s) { + int n = strlen(s); + int res = 0; + for (int i = 0; i < n; i++) { + if (!isdigit(s[i])) { + return n; } - ans as i32 + res = res * 10 + s[i] - '0'; } + return res; +} + +int maximumValue(char** strs, int strsSize) { + int ans = 0; + for (int i = 0; i < strsSize; i++) { + int num = parseInt(strs[i]); + ans = max(ans, num); + } + return ans; } ``` + + +### Solution 2 + + + +```python +class Solution: + def maximumValue(self, strs: List[str]) -> int: + def f(s: str) -> int: + x = 0 + for c in s: + if c.isalpha(): + return len(s) + x = x * 10 + ord(c) - ord("0") + return x + + return max(f(s) for s in strs) +``` + ```rust impl Solution { pub fn maximum_value(strs: Vec) -> i32 { @@ -224,6 +243,12 @@ impl Solution { } ``` + + +### Solution 3 + + + ```rust use std::cmp::max; @@ -247,37 +272,6 @@ impl Solution { } ``` -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int parseInt(char* s) { - int n = strlen(s); - int res = 0; - for (int i = 0; i < n; i++) { - if (!isdigit(s[i])) { - return n; - } - res = res * 10 + s[i] - '0'; - } - return res; -} - -int maximumValue(char** strs, int strsSize) { - int ans = 0; - for (int i = 0; i < strsSize; i++) { - int num = parseInt(strs[i]); - ans = max(ans, num); - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2497.Maximum Star Sum of a Graph/README.md b/solution/2400-2499/2497.Maximum Star Sum of a Graph/README.md index e7ef79edfca35..a6e1d92266b15 100644 --- a/solution/2400-2499/2497.Maximum Star Sum of a Graph/README.md +++ b/solution/2400-2499/2497.Maximum Star Sum of a Graph/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:排序 + 模拟** +### 方法一:排序 + 模拟 我们先将输入的边集合转换成邻接表,其中 $g[i]$ 表示节点 $i$ 的邻居节点的值列表,且按照值的降序排列。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int: @@ -90,10 +84,6 @@ class Solution: return max(v + sum(g[i][:k]) for i, v in enumerate(vals)) ``` -### **Java** - - - ```java class Solution { public int maxStarSum(int[] vals, int[][] edges, int k) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func maxStarSum(vals []int, edges [][]int, k int) (ans int) { n := len(vals) @@ -179,10 +165,6 @@ func maxStarSum(vals []int, edges [][]int, k int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2497.Maximum Star Sum of a Graph/README_EN.md b/solution/2400-2499/2497.Maximum Star Sum of a Graph/README_EN.md index 9772c27b6cdad..f7b47bc6727b0 100644 --- a/solution/2400-2499/2497.Maximum Star Sum of a Graph/README_EN.md +++ b/solution/2400-2499/2497.Maximum Star Sum of a Graph/README_EN.md @@ -52,9 +52,9 @@ Hence, we return -5. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return max(v + sum(g[i][:k]) for i, v in enumerate(vals)) ``` -### **Java** - ```java class Solution { public int maxStarSum(int[] vals, int[][] edges, int k) { @@ -103,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +124,6 @@ public: }; ``` -### **Go** - ```go func maxStarSum(vals []int, edges [][]int, k int) (ans int) { n := len(vals) @@ -157,10 +151,6 @@ func maxStarSum(vals []int, edges [][]int, k int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2498.Frog Jump II/README.md b/solution/2400-2499/2498.Frog Jump II/README.md index df23c8ed6dc25..cc42361286b9d 100644 --- a/solution/2400-2499/2498.Frog Jump II/README.md +++ b/solution/2400-2499/2498.Frog Jump II/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 要使得跳跃过程中的每一步的最大跳跃长度最小,我们应该将跳跃过程切分成尽可能多的连续的步骤。通过观察,间隔跳跃可以获取最优解。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def maxJump(self, stones: List[int]) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxJump(int[] stones) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +100,6 @@ public: }; ``` -### **Go** - ```go func maxJump(stones []int) int { ans := stones[1] - stones[0] @@ -124,10 +110,6 @@ func maxJump(stones []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2498.Frog Jump II/README_EN.md b/solution/2400-2499/2498.Frog Jump II/README_EN.md index 20ab8e75346b4..5d9522f624376 100644 --- a/solution/2400-2499/2498.Frog Jump II/README_EN.md +++ b/solution/2400-2499/2498.Frog Jump II/README_EN.md @@ -52,9 +52,9 @@ It can be shown that this is the minimum achievable cost. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxJump(int[] stones) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -92,8 +88,6 @@ public: }; ``` -### **Go** - ```go func maxJump(stones []int) int { ans := stones[1] - stones[0] @@ -104,10 +98,6 @@ func maxJump(stones []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2499.Minimum Total Cost to Make Arrays Unequal/README.md b/solution/2400-2499/2499.Minimum Total Cost to Make Arrays Unequal/README.md index c43da53ee56e5..a8fa91836afeb 100644 --- a/solution/2400-2499/2499.Minimum Total Cost to Make Arrays Unequal/README.md +++ b/solution/2400-2499/2499.Minimum Total Cost to Make Arrays Unequal/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们先同时遍历数组 `nums1` 和 `nums2`,统计相同位置上的值相同的个数 `same`,这些位置上的值必须交换,因此,将这些位置下标累加到答案中。另外,用数组或哈希表 `cnt` 统计这些相同值的出现次数。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int: @@ -106,10 +100,6 @@ class Solution: return -1 if m else ans ``` -### **Java** - - - ```java class Solution { public long minimumTotalCost(int[] nums1, int[] nums2) { @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +170,6 @@ public: }; ``` -### **Go** - ```go func minimumTotalCost(nums1 []int, nums2 []int) (ans int64) { same, n := 0, len(nums1) @@ -218,10 +204,6 @@ func minimumTotalCost(nums1 []int, nums2 []int) (ans int64) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2400-2499/2499.Minimum Total Cost to Make Arrays Unequal/README_EN.md b/solution/2400-2499/2499.Minimum Total Cost to Make Arrays Unequal/README_EN.md index 4c44583787037..76f07f244cb73 100644 --- a/solution/2400-2499/2499.Minimum Total Cost to Make Arrays Unequal/README_EN.md +++ b/solution/2400-2499/2499.Minimum Total Cost to Make Arrays Unequal/README_EN.md @@ -60,9 +60,9 @@ Hence, we return -1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -88,8 +88,6 @@ class Solution: return -1 if m else ans ``` -### **Java** - ```java class Solution { public long minimumTotalCost(int[] nums1, int[] nums2) { @@ -124,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +158,6 @@ public: }; ``` -### **Go** - ```go func minimumTotalCost(nums1 []int, nums2 []int) (ans int64) { same, n := 0, len(nums1) @@ -198,10 +192,6 @@ func minimumTotalCost(nums1 []int, nums2 []int) (ans int64) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2500.Delete Greatest Value in Each Row/README.md b/solution/2500-2599/2500.Delete Greatest Value in Each Row/README.md index fb3b5cdba6086..8b5aef5041972 100644 --- a/solution/2500-2599/2500.Delete Greatest Value in Each Row/README.md +++ b/solution/2500-2599/2500.Delete Greatest Value in Each Row/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 由于每一次操作都是从每一行中删除最大值,然后取最大值加到答案中,因此我们可以先对每一行进行排序。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def deleteGreatestValue(self, grid: List[List[int]]) -> int: @@ -84,10 +78,6 @@ class Solution: return sum(max(col) for col in zip(*grid)) ``` -### **Java** - - - ```java class Solution { public int deleteGreatestValue(int[][] grid) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func deleteGreatestValue(grid [][]int) (ans int) { for _, row := range grid { @@ -147,7 +133,24 @@ func deleteGreatestValue(grid [][]int) (ans int) { } ``` -### **Rust** +```ts +function deleteGreatestValue(grid: number[][]): number { + for (const row of grid) { + row.sort((a, b) => a - b); + } + + let ans = 0; + for (let j = 0; j < grid[0].length; ++j) { + let t = 0; + for (let i = 0; i < grid.length; ++i) { + t = Math.max(t, grid[i][j]); + } + ans += t; + } + + return ans; +} +``` ```rust impl Solution { @@ -175,31 +178,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function deleteGreatestValue(grid: number[][]): number { - for (const row of grid) { - row.sort((a, b) => a - b); - } - - let ans = 0; - for (let j = 0; j < grid[0].length; ++j) { - let t = 0; - for (let i = 0; i < grid.length; ++i) { - t = Math.max(t, grid[i][j]); - } - ans += t; - } - - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2500.Delete Greatest Value in Each Row/README_EN.md b/solution/2500-2599/2500.Delete Greatest Value in Each Row/README_EN.md index 803514df2d820..c68fecc2d1c58 100644 --- a/solution/2500-2599/2500.Delete Greatest Value in Each Row/README_EN.md +++ b/solution/2500-2599/2500.Delete Greatest Value in Each Row/README_EN.md @@ -52,9 +52,9 @@ The final answer = 10. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return sum(max(col) for col in zip(*grid)) ``` -### **Java** - ```java class Solution { public int deleteGreatestValue(int[][] grid) { @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +101,6 @@ public: }; ``` -### **Go** - ```go func deleteGreatestValue(grid [][]int) (ans int) { for _, row := range grid { @@ -125,7 +119,24 @@ func deleteGreatestValue(grid [][]int) (ans int) { } ``` -### **Rust** +```ts +function deleteGreatestValue(grid: number[][]): number { + for (const row of grid) { + row.sort((a, b) => a - b); + } + + let ans = 0; + for (let j = 0; j < grid[0].length; ++j) { + let t = 0; + for (let i = 0; i < grid.length; ++i) { + t = Math.max(t, grid[i][j]); + } + ans += t; + } + + return ans; +} +``` ```rust impl Solution { @@ -153,31 +164,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function deleteGreatestValue(grid: number[][]): number { - for (const row of grid) { - row.sort((a, b) => a - b); - } - - let ans = 0; - for (let j = 0; j < grid[0].length; ++j) { - let t = 0; - for (let i = 0; i < grid.length; ++i) { - t = Math.max(t, grid[i][j]); - } - ans += t; - } - - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2501.Longest Square Streak in an Array/README.md b/solution/2500-2599/2501.Longest Square Streak in an Array/README.md index 8e7684e67c90b..85c9918197a12 100644 --- a/solution/2500-2599/2501.Longest Square Streak in an Array/README.md +++ b/solution/2500-2599/2501.Longest Square Streak in an Array/README.md @@ -48,33 +48,14 @@ ## 解法 - - -**方法一:哈希表 + 枚举** +### 方法一:哈希表 + 枚举 我们先用哈希表记录数组中的所有元素,然后枚举数组中的每个元素作为子序列的第一个元素,将该元素不断平方,并判断平方后的结果是否在哈希表中,如果在,则将平方后的结果作为下一个元素,继续判断,直到平方后的结果不在哈希表中,此时判断子序列的长度是否大于 $1$,如果是,则更新答案。 时间复杂度 $O(n \times \log \log M)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度,而 $M$ 为数组 `nums` 中的最大元素。 -**方法二:记忆化搜索** - -与方法一类似,我们先用哈希表记录数组中的所有元素。然后设计一个函数 $dfs(x)$,表示以 $x$ 为第一个元素的方波的长度。那么答案就是 $max(dfs(x))$,其中 $x$ 为数组 `nums` 中的元素。 - -函数 $dfs(x)$ 的计算过程如下: - -- 如果 $x$ 不在哈希表中,则返回 $0$。 -- 否则,返回 $1 + dfs(x^2)$。 - -过程中我们可以使用记忆化搜索,即使用哈希表记录函数 $dfs(x)$ 的值,避免重复计算。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。 - -### **Python3** - - - ```python class Solution: def longestSquareStreak(self, nums: List[int]) -> int: @@ -90,24 +71,6 @@ class Solution: return ans ``` -```python -class Solution: - def longestSquareStreak(self, nums: List[int]) -> int: - @cache - def dfs(x): - if x not in s: - return 0 - return 1 + dfs(x * x) - - s = set(nums) - ans = max(dfs(x) for x in nums) - return -1 if ans < 2 else ans -``` - -### **Java** - - - ```java class Solution { public int longestSquareStreak(int[] nums) { @@ -131,6 +94,78 @@ class Solution { } ``` +```cpp +class Solution { +public: + int longestSquareStreak(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + int ans = -1; + for (int& v : nums) { + int t = 0; + long long x = v; + while (s.count(x)) { + x *= x; + ++t; + } + if (t > 1) ans = max(ans, t); + } + return ans; + } +}; +``` + +```go +func longestSquareStreak(nums []int) int { + s := map[int]bool{} + for _, v := range nums { + s[v] = true + } + ans := -1 + for _, v := range nums { + t := 0 + for s[v] { + v *= v + t++ + } + if t > 1 && t > ans { + ans = t + } + } + return ans +} +``` + + + +### 方法二:记忆化搜索 + +与方法一类似,我们先用哈希表记录数组中的所有元素。然后设计一个函数 $dfs(x)$,表示以 $x$ 为第一个元素的方波的长度。那么答案就是 $max(dfs(x))$,其中 $x$ 为数组 `nums` 中的元素。 + +函数 $dfs(x)$ 的计算过程如下: + +- 如果 $x$ 不在哈希表中,则返回 $0$。 +- 否则,返回 $1 + dfs(x^2)$。 + +过程中我们可以使用记忆化搜索,即使用哈希表记录函数 $dfs(x)$ 的值,避免重复计算。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。 + + + +```python +class Solution: + def longestSquareStreak(self, nums: List[int]) -> int: + @cache + def dfs(x): + if x not in s: + return 0 + return 1 + dfs(x * x) + + s = set(nums) + ans = max(dfs(x) for x in nums) + return -1 if ans < 2 else ans +``` + ```java class Solution { private Map f = new HashMap<>(); @@ -161,28 +196,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int longestSquareStreak(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - int ans = -1; - for (int& v : nums) { - int t = 0; - long long x = v; - while (s.count(x)) { - x *= x; - ++t; - } - if (t > 1) ans = max(ans, t); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -204,29 +217,6 @@ public: }; ``` -### **Go** - -```go -func longestSquareStreak(nums []int) int { - s := map[int]bool{} - for _, v := range nums { - s[v] = true - } - ans := -1 - for _, v := range nums { - t := 0 - for s[v] { - v *= v - t++ - } - if t > 1 && t > ans { - ans = t - } - } - return ans -} -``` - ```go func longestSquareStreak(nums []int) (ans int) { s := map[int]bool{} @@ -257,10 +247,6 @@ func longestSquareStreak(nums []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2501.Longest Square Streak in an Array/README_EN.md b/solution/2500-2599/2501.Longest Square Streak in an Array/README_EN.md index c4f00f0f158d0..214a98c0f0954 100644 --- a/solution/2500-2599/2501.Longest Square Streak in an Array/README_EN.md +++ b/solution/2500-2599/2501.Longest Square Streak in an Array/README_EN.md @@ -46,9 +46,9 @@ It can be shown that every subsequence of length 4 is not a square streak. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,22 +65,6 @@ class Solution: return ans ``` -```python -class Solution: - def longestSquareStreak(self, nums: List[int]) -> int: - @cache - def dfs(x): - if x not in s: - return 0 - return 1 + dfs(x * x) - - s = set(nums) - ans = max(dfs(x) for x in nums) - return -1 if ans < 2 else ans -``` - -### **Java** - ```java class Solution { public int longestSquareStreak(int[] nums) { @@ -104,6 +88,67 @@ class Solution { } ``` +```cpp +class Solution { +public: + int longestSquareStreak(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + int ans = -1; + for (int& v : nums) { + int t = 0; + long long x = v; + while (s.count(x)) { + x *= x; + ++t; + } + if (t > 1) ans = max(ans, t); + } + return ans; + } +}; +``` + +```go +func longestSquareStreak(nums []int) int { + s := map[int]bool{} + for _, v := range nums { + s[v] = true + } + ans := -1 + for _, v := range nums { + t := 0 + for s[v] { + v *= v + t++ + } + if t > 1 && t > ans { + ans = t + } + } + return ans +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def longestSquareStreak(self, nums: List[int]) -> int: + @cache + def dfs(x): + if x not in s: + return 0 + return 1 + dfs(x * x) + + s = set(nums) + ans = max(dfs(x) for x in nums) + return -1 if ans < 2 else ans +``` + ```java class Solution { private Map f = new HashMap<>(); @@ -134,28 +179,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int longestSquareStreak(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - int ans = -1; - for (int& v : nums) { - int t = 0; - long long x = v; - while (s.count(x)) { - x *= x; - ++t; - } - if (t > 1) ans = max(ans, t); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -177,29 +200,6 @@ public: }; ``` -### **Go** - -```go -func longestSquareStreak(nums []int) int { - s := map[int]bool{} - for _, v := range nums { - s[v] = true - } - ans := -1 - for _, v := range nums { - t := 0 - for s[v] { - v *= v - t++ - } - if t > 1 && t > ans { - ans = t - } - } - return ans -} -``` - ```go func longestSquareStreak(nums []int) (ans int) { s := map[int]bool{} @@ -230,10 +230,6 @@ func longestSquareStreak(nums []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2502.Design Memory Allocator/README.md b/solution/2500-2599/2502.Design Memory Allocator/README.md index c4e1f4d0356b8..52d4324056070 100644 --- a/solution/2500-2599/2502.Design Memory Allocator/README.md +++ b/solution/2500-2599/2502.Design Memory Allocator/README.md @@ -65,9 +65,7 @@ loc.free(7); // 释放 mID 为 7 的所有内存单元。内存数组保持原 ## 解法 - - -**方法一:暴力模拟** +### 方法一:暴力模拟 题目数据范围不大,可以直接用数组模拟内存空间。 @@ -79,22 +77,8 @@ loc.free(7); // 释放 mID 为 7 的所有内存单元。内存数组保持原 时间复杂度 $O(n \times q)$,空间复杂度 $O(n)$,其中 $n$ 和 $q$ 分别为内存空间的大小和方法调用的次数。 -**方法二:哈希表 + 有序集合** - -我们可以用有序集合维护所有已分配的内存单元的起始下标和结束下标,其中起始下标为键,结束下标为值;另外用哈希表维护 `mID` 和其对应的内存单元的起始下标。 - -当调用 `allocate` 方法时,遍历有序集合,找到第一个长度大于等于 `size` 的空闲区间,将其分配给 `mID`,并更新有序集合。然后将 `mID` 和其对应的内存单元的起始下标加入哈希表。 - -当调用 `free` 方法时,从哈希表中找到 `mID` 对应的内存单元的起始下标,然后将其从有序集合中删除,再将 `mID` 从哈希表中删除。 - -时间复杂度 $O(q \log n)$,空间复杂度 $O(n)$,其中 $n$ 和 $q$ 分别为内存空间的大小和方法调用的次数。 - -### **Python3** - - - ```python class Allocator: def __init__(self, n: int): @@ -127,43 +111,6 @@ class Allocator: # param_2 = obj.free(mID) ``` -```python -from sortedcontainers import SortedList - - -class Allocator: - def __init__(self, n: int): - self.sl = SortedList([(-1, -1), (n, n)]) - self.d = defaultdict(list) - - def allocate(self, size: int, mID: int) -> int: - for (_, s), (e, _) in pairwise(self.sl): - s, e = s + 1, e - 1 - if e - s + 1 >= size: - self.sl.add((s, s + size - 1)) - self.d[mID].append((s, s + size - 1)) - return s - return -1 - - def free(self, mID: int) -> int: - ans = 0 - for block in self.d[mID]: - self.sl.remove(block) - ans += block[1] - block[0] + 1 - del self.d[mID] - return ans - - -# Your Allocator object will be instantiated and called as such: -# obj = Allocator(n) -# param_1 = obj.allocate(size,mID) -# param_2 = obj.free(mID) -``` - -### **Java** - - - ```java class Allocator { private int[] m; @@ -205,54 +152,6 @@ class Allocator { */ ``` -```java -class Allocator { - private TreeMap tm = new TreeMap<>(); - private Map> d = new HashMap<>(); - - public Allocator(int n) { - tm.put(-1, -1); - tm.put(n, n); - } - - public int allocate(int size, int mID) { - int s = -1; - for (var entry : tm.entrySet()) { - int v = entry.getKey(); - if (s != -1) { - int e = v - 1; - if (e - s + 1 >= size) { - tm.put(s, s + size - 1); - d.computeIfAbsent(mID, k -> new ArrayList<>()).add(s); - return s; - } - } - s = entry.getValue() + 1; - } - return -1; - } - - public int free(int mID) { - int ans = 0; - for (int s : d.getOrDefault(mID, Collections.emptyList())) { - int e = tm.remove(s); - ans += e - s + 1; - } - d.remove(mID); - return ans; - } -} - -/** - * Your Allocator object will be instantiated and called as such: - * Allocator obj = new Allocator(n); - * int param_1 = obj.allocate(size,mID); - * int param_2 = obj.free(mID); - */ -``` - -### **C++** - ```cpp class Allocator { public: @@ -302,6 +201,144 @@ private: */ ``` +```go +type Allocator struct { + m []int +} + +func Constructor(n int) Allocator { + return Allocator{make([]int, n)} +} + +func (this *Allocator) Allocate(size int, mID int) int { + cnt := 0 + for i, v := range this.m { + if v > 0 { + cnt = 0 + } else { + cnt++ + if cnt == size { + for j := i - size + 1; j <= i; j++ { + this.m[j] = mID + } + return i - size + 1 + } + } + } + return -1 +} + +func (this *Allocator) Free(mID int) (ans int) { + for i, v := range this.m { + if v == mID { + this.m[i] = 0 + ans++ + } + } + return +} + +/** + * Your Allocator object will be instantiated and called as such: + * obj := Constructor(n); + * param_1 := obj.Allocate(size,mID); + * param_2 := obj.Free(mID); + */ +``` + + + +### 方法二:哈希表 + 有序集合 + +我们可以用有序集合维护所有已分配的内存单元的起始下标和结束下标,其中起始下标为键,结束下标为值;另外用哈希表维护 `mID` 和其对应的内存单元的起始下标。 + +当调用 `allocate` 方法时,遍历有序集合,找到第一个长度大于等于 `size` 的空闲区间,将其分配给 `mID`,并更新有序集合。然后将 `mID` 和其对应的内存单元的起始下标加入哈希表。 + +当调用 `free` 方法时,从哈希表中找到 `mID` 对应的内存单元的起始下标,然后将其从有序集合中删除,再将 `mID` 从哈希表中删除。 + +时间复杂度 $O(q \log n)$,空间复杂度 $O(n)$,其中 $n$ 和 $q$ 分别为内存空间的大小和方法调用的次数。 + + + +```python +from sortedcontainers import SortedList + + +class Allocator: + def __init__(self, n: int): + self.sl = SortedList([(-1, -1), (n, n)]) + self.d = defaultdict(list) + + def allocate(self, size: int, mID: int) -> int: + for (_, s), (e, _) in pairwise(self.sl): + s, e = s + 1, e - 1 + if e - s + 1 >= size: + self.sl.add((s, s + size - 1)) + self.d[mID].append((s, s + size - 1)) + return s + return -1 + + def free(self, mID: int) -> int: + ans = 0 + for block in self.d[mID]: + self.sl.remove(block) + ans += block[1] - block[0] + 1 + del self.d[mID] + return ans + + +# Your Allocator object will be instantiated and called as such: +# obj = Allocator(n) +# param_1 = obj.allocate(size,mID) +# param_2 = obj.free(mID) +``` + +```java +class Allocator { + private TreeMap tm = new TreeMap<>(); + private Map> d = new HashMap<>(); + + public Allocator(int n) { + tm.put(-1, -1); + tm.put(n, n); + } + + public int allocate(int size, int mID) { + int s = -1; + for (var entry : tm.entrySet()) { + int v = entry.getKey(); + if (s != -1) { + int e = v - 1; + if (e - s + 1 >= size) { + tm.put(s, s + size - 1); + d.computeIfAbsent(mID, k -> new ArrayList<>()).add(s); + return s; + } + } + s = entry.getValue() + 1; + } + return -1; + } + + public int free(int mID) { + int ans = 0; + for (int s : d.getOrDefault(mID, Collections.emptyList())) { + int e = tm.remove(s); + ans += e - s + 1; + } + d.remove(mID); + return ans; + } +} + +/** + * Your Allocator object will be instantiated and called as such: + * Allocator obj = new Allocator(n); + * int param_1 = obj.allocate(size,mID); + * int param_2 = obj.free(mID); + */ +``` + ```cpp class Allocator { public: @@ -350,53 +387,6 @@ private: */ ``` -### **Go** - -```go -type Allocator struct { - m []int -} - -func Constructor(n int) Allocator { - return Allocator{make([]int, n)} -} - -func (this *Allocator) Allocate(size int, mID int) int { - cnt := 0 - for i, v := range this.m { - if v > 0 { - cnt = 0 - } else { - cnt++ - if cnt == size { - for j := i - size + 1; j <= i; j++ { - this.m[j] = mID - } - return i - size + 1 - } - } - } - return -1 -} - -func (this *Allocator) Free(mID int) (ans int) { - for i, v := range this.m { - if v == mID { - this.m[i] = 0 - ans++ - } - } - return -} - -/** - * Your Allocator object will be instantiated and called as such: - * obj := Constructor(n); - * param_1 := obj.Allocate(size,mID); - * param_2 := obj.Free(mID); - */ -``` - ```go type Allocator struct { rbt *redblacktree.Tree @@ -448,10 +438,6 @@ func (this *Allocator) Free(mID int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2502.Design Memory Allocator/README_EN.md b/solution/2500-2599/2502.Design Memory Allocator/README_EN.md index de951372fa746..ce72122b66bd8 100644 --- a/solution/2500-2599/2502.Design Memory Allocator/README_EN.md +++ b/solution/2500-2599/2502.Design Memory Allocator/README_EN.md @@ -62,9 +62,9 @@ loc.free(7); // Free all memory units with mID 7. The memory array remains the s ## Solutions - +### Solution 1 -### **Python3** + ```python class Allocator: @@ -98,41 +98,6 @@ class Allocator: # param_2 = obj.free(mID) ``` -```python -from sortedcontainers import SortedList - - -class Allocator: - def __init__(self, n: int): - self.sl = SortedList([(-1, -1), (n, n)]) - self.d = defaultdict(list) - - def allocate(self, size: int, mID: int) -> int: - for (_, s), (e, _) in pairwise(self.sl): - s, e = s + 1, e - 1 - if e - s + 1 >= size: - self.sl.add((s, s + size - 1)) - self.d[mID].append((s, s + size - 1)) - return s - return -1 - - def free(self, mID: int) -> int: - ans = 0 - for block in self.d[mID]: - self.sl.remove(block) - ans += block[1] - block[0] + 1 - del self.d[mID] - return ans - - -# Your Allocator object will be instantiated and called as such: -# obj = Allocator(n) -# param_1 = obj.allocate(size,mID) -# param_2 = obj.free(mID) -``` - -### **Java** - ```java class Allocator { private int[] m; @@ -174,54 +139,6 @@ class Allocator { */ ``` -```java -class Allocator { - private TreeMap tm = new TreeMap<>(); - private Map> d = new HashMap<>(); - - public Allocator(int n) { - tm.put(-1, -1); - tm.put(n, n); - } - - public int allocate(int size, int mID) { - int s = -1; - for (var entry : tm.entrySet()) { - int v = entry.getKey(); - if (s != -1) { - int e = v - 1; - if (e - s + 1 >= size) { - tm.put(s, s + size - 1); - d.computeIfAbsent(mID, k -> new ArrayList<>()).add(s); - return s; - } - } - s = entry.getValue() + 1; - } - return -1; - } - - public int free(int mID) { - int ans = 0; - for (int s : d.getOrDefault(mID, Collections.emptyList())) { - int e = tm.remove(s); - ans += e - s + 1; - } - d.remove(mID); - return ans; - } -} - -/** - * Your Allocator object will be instantiated and called as such: - * Allocator obj = new Allocator(n); - * int param_1 = obj.allocate(size,mID); - * int param_2 = obj.free(mID); - */ -``` - -### **C++** - ```cpp class Allocator { public: @@ -271,6 +188,136 @@ private: */ ``` +```go +type Allocator struct { + m []int +} + +func Constructor(n int) Allocator { + return Allocator{make([]int, n)} +} + +func (this *Allocator) Allocate(size int, mID int) int { + cnt := 0 + for i, v := range this.m { + if v > 0 { + cnt = 0 + } else { + cnt++ + if cnt == size { + for j := i - size + 1; j <= i; j++ { + this.m[j] = mID + } + return i - size + 1 + } + } + } + return -1 +} + +func (this *Allocator) Free(mID int) (ans int) { + for i, v := range this.m { + if v == mID { + this.m[i] = 0 + ans++ + } + } + return +} + +/** + * Your Allocator object will be instantiated and called as such: + * obj := Constructor(n); + * param_1 := obj.Allocate(size,mID); + * param_2 := obj.Free(mID); + */ +``` + + + +### Solution 2 + + + +```python +from sortedcontainers import SortedList + + +class Allocator: + def __init__(self, n: int): + self.sl = SortedList([(-1, -1), (n, n)]) + self.d = defaultdict(list) + + def allocate(self, size: int, mID: int) -> int: + for (_, s), (e, _) in pairwise(self.sl): + s, e = s + 1, e - 1 + if e - s + 1 >= size: + self.sl.add((s, s + size - 1)) + self.d[mID].append((s, s + size - 1)) + return s + return -1 + + def free(self, mID: int) -> int: + ans = 0 + for block in self.d[mID]: + self.sl.remove(block) + ans += block[1] - block[0] + 1 + del self.d[mID] + return ans + + +# Your Allocator object will be instantiated and called as such: +# obj = Allocator(n) +# param_1 = obj.allocate(size,mID) +# param_2 = obj.free(mID) +``` + +```java +class Allocator { + private TreeMap tm = new TreeMap<>(); + private Map> d = new HashMap<>(); + + public Allocator(int n) { + tm.put(-1, -1); + tm.put(n, n); + } + + public int allocate(int size, int mID) { + int s = -1; + for (var entry : tm.entrySet()) { + int v = entry.getKey(); + if (s != -1) { + int e = v - 1; + if (e - s + 1 >= size) { + tm.put(s, s + size - 1); + d.computeIfAbsent(mID, k -> new ArrayList<>()).add(s); + return s; + } + } + s = entry.getValue() + 1; + } + return -1; + } + + public int free(int mID) { + int ans = 0; + for (int s : d.getOrDefault(mID, Collections.emptyList())) { + int e = tm.remove(s); + ans += e - s + 1; + } + d.remove(mID); + return ans; + } +} + +/** + * Your Allocator object will be instantiated and called as such: + * Allocator obj = new Allocator(n); + * int param_1 = obj.allocate(size,mID); + * int param_2 = obj.free(mID); + */ +``` + ```cpp class Allocator { public: @@ -319,53 +366,6 @@ private: */ ``` -### **Go** - -```go -type Allocator struct { - m []int -} - -func Constructor(n int) Allocator { - return Allocator{make([]int, n)} -} - -func (this *Allocator) Allocate(size int, mID int) int { - cnt := 0 - for i, v := range this.m { - if v > 0 { - cnt = 0 - } else { - cnt++ - if cnt == size { - for j := i - size + 1; j <= i; j++ { - this.m[j] = mID - } - return i - size + 1 - } - } - } - return -1 -} - -func (this *Allocator) Free(mID int) (ans int) { - for i, v := range this.m { - if v == mID { - this.m[i] = 0 - ans++ - } - } - return -} - -/** - * Your Allocator object will be instantiated and called as such: - * obj := Constructor(n); - * param_1 := obj.Allocate(size,mID); - * param_2 := obj.Free(mID); - */ -``` - ```go type Allocator struct { rbt *redblacktree.Tree @@ -417,10 +417,6 @@ func (this *Allocator) Free(mID int) int { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2503.Maximum Number of Points From Grid Queries/README.md b/solution/2500-2599/2503.Maximum Number of Points From Grid Queries/README.md index fd7451a073735..9dbbd6223348f 100644 --- a/solution/2500-2599/2503.Maximum Number of Points From Grid Queries/README.md +++ b/solution/2500-2599/2503.Maximum Number of Points From Grid Queries/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:离线查询 + BFS + 优先队列(小根堆)** +### 方法一:离线查询 + BFS + 优先队列(小根堆) 根据题目描述我们知道,每个查询相互独立,查询的顺序不影响结果,并且题目要我们每次从左上角开始,统计所有可以访问的、且值小于当前查询值的单元格的个数。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]: @@ -95,45 +89,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]: - def find(x): - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - def union(a, b): - pa, pb = find(a), find(b) - if pa == pb: - return - p[pa] = pb - size[pb] += size[pa] - - m, n = len(grid), len(grid[0]) - arr = sorted((grid[i][j], i, j) for i in range(m) for j in range(n)) - k = len(queries) - ans = [0] * k - p = list(range(m * n)) - size = [1] * len(p) - j = 0 - for i, v in sorted(enumerate(queries), key=lambda x: x[1]): - while j < len(arr) and arr[j][0] < v: - _, a, b = arr[j] - for x, y in pairwise((-1, 0, 1, 0, -1)): - c, d = a + x, b + y - if 0 <= c < m and 0 <= d < n and grid[c][d] < v: - union(a * n + b, c * n + d) - j += 1 - if grid[0][0] < v: - ans[i] = size[find(0)] - return ans -``` - -### **Java** - - - ```java class Solution { public int[] maxPoints(int[][] grid, int[] queries) { @@ -172,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -214,8 +167,6 @@ public: }; ``` -### **Go** - ```go func maxPoints(grid [][]int, queries []int) []int { k := len(queries) @@ -263,10 +214,47 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** + -``` +### 方法二 + + + +```python +class Solution: + def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + def union(a, b): + pa, pb = find(a), find(b) + if pa == pb: + return + p[pa] = pb + size[pb] += size[pa] + m, n = len(grid), len(grid[0]) + arr = sorted((grid[i][j], i, j) for i in range(m) for j in range(n)) + k = len(queries) + ans = [0] * k + p = list(range(m * n)) + size = [1] * len(p) + j = 0 + for i, v in sorted(enumerate(queries), key=lambda x: x[1]): + while j < len(arr) and arr[j][0] < v: + _, a, b = arr[j] + for x, y in pairwise((-1, 0, 1, 0, -1)): + c, d = a + x, b + y + if 0 <= c < m and 0 <= d < n and grid[c][d] < v: + union(a * n + b, c * n + d) + j += 1 + if grid[0][0] < v: + ans[i] = size[find(0)] + return ans ``` + + diff --git a/solution/2500-2599/2503.Maximum Number of Points From Grid Queries/README_EN.md b/solution/2500-2599/2503.Maximum Number of Points From Grid Queries/README_EN.md index 38e899536875b..0823a7efd18c2 100644 --- a/solution/2500-2599/2503.Maximum Number of Points From Grid Queries/README_EN.md +++ b/solution/2500-2599/2503.Maximum Number of Points From Grid Queries/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,43 +75,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]: - def find(x): - if p[x] != x: - p[x] = find(p[x]) - return p[x] - - def union(a, b): - pa, pb = find(a), find(b) - if pa == pb: - return - p[pa] = pb - size[pb] += size[pa] - - m, n = len(grid), len(grid[0]) - arr = sorted((grid[i][j], i, j) for i in range(m) for j in range(n)) - k = len(queries) - ans = [0] * k - p = list(range(m * n)) - size = [1] * len(p) - j = 0 - for i, v in sorted(enumerate(queries), key=lambda x: x[1]): - while j < len(arr) and arr[j][0] < v: - _, a, b = arr[j] - for x, y in pairwise((-1, 0, 1, 0, -1)): - c, d = a + x, b + y - if 0 <= c < m and 0 <= d < n and grid[c][d] < v: - union(a * n + b, c * n + d) - j += 1 - if grid[0][0] < v: - ans[i] = size[find(0)] - return ans -``` - -### **Java** - ```java class Solution { public int[] maxPoints(int[][] grid, int[] queries) { @@ -150,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -192,8 +153,6 @@ public: }; ``` -### **Go** - ```go func maxPoints(grid [][]int, queries []int) []int { k := len(queries) @@ -241,10 +200,47 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** + -``` +### Solution 2 + + + +```python +class Solution: + def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]: + def find(x): + if p[x] != x: + p[x] = find(p[x]) + return p[x] + + def union(a, b): + pa, pb = find(a), find(b) + if pa == pb: + return + p[pa] = pb + size[pb] += size[pa] + m, n = len(grid), len(grid[0]) + arr = sorted((grid[i][j], i, j) for i in range(m) for j in range(n)) + k = len(queries) + ans = [0] * k + p = list(range(m * n)) + size = [1] * len(p) + j = 0 + for i, v in sorted(enumerate(queries), key=lambda x: x[1]): + while j < len(arr) and arr[j][0] < v: + _, a, b = arr[j] + for x, y in pairwise((-1, 0, 1, 0, -1)): + c, d = a + x, b + y + if 0 <= c < m and 0 <= d < n and grid[c][d] < v: + union(a * n + b, c * n + d) + j += 1 + if grid[0][0] < v: + ans[i] = size[find(0)] + return ans ``` + + diff --git a/solution/2500-2599/2504.Concatenate the Name and the Profession/README.md b/solution/2500-2599/2504.Concatenate the Name and the Profession/README.md index ca3736d4d4dfe..ea832477e487d 100644 --- a/solution/2500-2599/2504.Concatenate the Name and the Profession/README.md +++ b/solution/2500-2599/2504.Concatenate the Name and the Profession/README.md @@ -61,14 +61,10 @@ Person 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT person_id, CONCAT(name, "(", SUBSTRING(profession, 1, 1), ")") AS name @@ -77,3 +73,5 @@ ORDER BY person_id DESC; ``` + + diff --git a/solution/2500-2599/2504.Concatenate the Name and the Profession/README_EN.md b/solution/2500-2599/2504.Concatenate the Name and the Profession/README_EN.md index a15ee2f0e7fbf..701fbd91c655e 100644 --- a/solution/2500-2599/2504.Concatenate the Name and the Profession/README_EN.md +++ b/solution/2500-2599/2504.Concatenate the Name and the Profession/README_EN.md @@ -59,9 +59,9 @@ Person table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -71,3 +71,5 @@ ORDER BY person_id DESC; ``` + + diff --git a/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README.md b/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README.md index d146def9169b1..cf33c34272233 100644 --- a/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README.md +++ b/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 我们先用数组 $cnt$ 统计每一位上 $1$ 的个数,然后从低位到高位,如果该位上 $1$ 的个数大于 $0$,则将该位所表示的数加入到答案中。然后判断是否可以进位,是则累加到下一位。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python class Solution: def subsequenceSumOr(self, nums: List[int]) -> int: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long subsequenceSumOr(int[] nums) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func subsequenceSumOr(nums []int) int64 { cnt := make([]int, 64) @@ -146,10 +132,6 @@ func subsequenceSumOr(nums []int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README_EN.md b/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README_EN.md index e8ffd08b2b5d0..3deafdc54350a 100644 --- a/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README_EN.md +++ b/solution/2500-2599/2505.Bitwise OR of All Subsequence Sums/README_EN.md @@ -36,9 +36,9 @@ And we have 0 OR 1 OR 2 OR 3 OR 4 OR 5 OR 6 = 7, so we return 7. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long subsequenceSumOr(int[] nums) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +103,6 @@ public: }; ``` -### **Go** - ```go func subsequenceSumOr(nums []int) int64 { cnt := make([]int, 64) @@ -130,10 +124,6 @@ func subsequenceSumOr(nums []int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2506.Count Pairs Of Similar Strings/README.md b/solution/2500-2599/2506.Count Pairs Of Similar Strings/README.md index 016357e7ac6a6..c0d2c093d653e 100644 --- a/solution/2500-2599/2506.Count Pairs Of Similar Strings/README.md +++ b/solution/2500-2599/2506.Count Pairs Of Similar Strings/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:哈希表 + 位运算** +### 方法一:哈希表 + 位运算 对于每个字符串,我们可以将其转换为一个长度为 $26$ 的二进制数,其中第 $i$ 位为 $1$ 表示该字符串中包含第 $i$ 个字母。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def similarPairs(self, words: List[str]) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int similarPairs(String[] words) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func similarPairs(words []string) (ans int) { cnt := map[int]int{} @@ -144,7 +130,21 @@ func similarPairs(words []string) (ans int) { } ``` -### **Rust** +```ts +function similarPairs(words: string[]): number { + let ans = 0; + const cnt: Map = new Map(); + for (const w of words) { + let v = 0; + for (let i = 0; i < w.length; ++i) { + v |= 1 << (w.charCodeAt(i) - 'a'.charCodeAt(0)); + } + ans += cnt.get(v) || 0; + cnt.set(v, (cnt.get(v) || 0) + 1); + } + return ans; +} +``` ```rust use std::collections::HashMap; @@ -170,28 +170,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function similarPairs(words: string[]): number { - let ans = 0; - const cnt: Map = new Map(); - for (const w of words) { - let v = 0; - for (let i = 0; i < w.length; ++i) { - v |= 1 << (w.charCodeAt(i) - 'a'.charCodeAt(0)); - } - ans += cnt.get(v) || 0; - cnt.set(v, (cnt.get(v) || 0) + 1); - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2506.Count Pairs Of Similar Strings/README_EN.md b/solution/2500-2599/2506.Count Pairs Of Similar Strings/README_EN.md index e5f585c08adef..daeeea327ccba 100644 --- a/solution/2500-2599/2506.Count Pairs Of Similar Strings/README_EN.md +++ b/solution/2500-2599/2506.Count Pairs Of Similar Strings/README_EN.md @@ -55,9 +55,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int similarPairs(String[] words) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func similarPairs(words []string) (ans int) { cnt := map[int]int{} @@ -129,7 +123,21 @@ func similarPairs(words []string) (ans int) { } ``` -### **Rust** +```ts +function similarPairs(words: string[]): number { + let ans = 0; + const cnt: Map = new Map(); + for (const w of words) { + let v = 0; + for (let i = 0; i < w.length; ++i) { + v |= 1 << (w.charCodeAt(i) - 'a'.charCodeAt(0)); + } + ans += cnt.get(v) || 0; + cnt.set(v, (cnt.get(v) || 0) + 1); + } + return ans; +} +``` ```rust use std::collections::HashMap; @@ -155,28 +163,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function similarPairs(words: string[]): number { - let ans = 0; - const cnt: Map = new Map(); - for (const w of words) { - let v = 0; - for (let i = 0; i < w.length; ++i) { - v |= 1 << (w.charCodeAt(i) - 'a'.charCodeAt(0)); - } - ans += cnt.get(v) || 0; - cnt.set(v, (cnt.get(v) || 0) + 1); - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2507.Smallest Value After Replacing With Sum of Prime Factors/README.md b/solution/2500-2599/2507.Smallest Value After Replacing With Sum of Prime Factors/README.md index 78537da2d1d0f..0ae537bff64e8 100644 --- a/solution/2500-2599/2507.Smallest Value After Replacing With Sum of Prime Factors/README.md +++ b/solution/2500-2599/2507.Smallest Value After Replacing With Sum of Prime Factors/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:暴力模拟** +### 方法一:暴力模拟 根据题意,我们可以得到一个质因数分解的过程,即将一个数不断地分解为质因数,分解不能分解。过程中将每次分解的质因数相加,递归或者迭代地进行即可。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def smallestValue(self, n: int) -> int: @@ -77,10 +71,6 @@ class Solution: n = s ``` -### **Java** - - - ```java class Solution { public int smallestValue(int n) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func smallestValue(n int) int { for { @@ -149,10 +135,6 @@ func smallestValue(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2507.Smallest Value After Replacing With Sum of Prime Factors/README_EN.md b/solution/2500-2599/2507.Smallest Value After Replacing With Sum of Prime Factors/README_EN.md index 86a847aa126ea..57126076739b9 100644 --- a/solution/2500-2599/2507.Smallest Value After Replacing With Sum of Prime Factors/README_EN.md +++ b/solution/2500-2599/2507.Smallest Value After Replacing With Sum of Prime Factors/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: n = s ``` -### **Java** - ```java class Solution { public int smallestValue(int n) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func smallestValue(n int) int { for { @@ -136,10 +130,6 @@ func smallestValue(n int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2508.Add Edges to Make Degrees of All Nodes Even/README.md b/solution/2500-2599/2508.Add Edges to Make Degrees of All Nodes Even/README.md index 14182adfe0f84..4c041a8526dec 100644 --- a/solution/2500-2599/2508.Add Edges to Make Degrees of All Nodes Even/README.md +++ b/solution/2500-2599/2508.Add Edges to Make Degrees of All Nodes Even/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:分类讨论** +### 方法一:分类讨论 我们先通过 `edges` 构建图 $g$,然后找出所有度数为奇数的点,记为 $vs$。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def isPossible(self, n: int, edges: List[List[int]]) -> bool: @@ -109,10 +103,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean isPossible(int n, List> edges) { @@ -162,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -205,8 +193,6 @@ public: }; ``` -### **Go** - ```go func isPossible(n int, edges [][]int) bool { g := make([]map[int]bool, n+1) @@ -258,10 +244,6 @@ func isPossible(n int, edges [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2508.Add Edges to Make Degrees of All Nodes Even/README_EN.md b/solution/2500-2599/2508.Add Edges to Make Degrees of All Nodes Even/README_EN.md index cedb9f01846fe..e5b0ea688e027 100644 --- a/solution/2500-2599/2508.Add Edges to Make Degrees of All Nodes Even/README_EN.md +++ b/solution/2500-2599/2508.Add Edges to Make Degrees of All Nodes Even/README_EN.md @@ -50,9 +50,9 @@ Every node in the resulting graph is connected to an even number of edges. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -81,8 +81,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean isPossible(int n, List> edges) { @@ -132,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +171,6 @@ public: }; ``` -### **Go** - ```go func isPossible(n int, edges [][]int) bool { g := make([]map[int]bool, n+1) @@ -228,10 +222,6 @@ func isPossible(n int, edges [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2509.Cycle Length Queries in a Tree/README.md b/solution/2500-2599/2509.Cycle Length Queries in a Tree/README.md index a72edfa4c032d..5a0342769e340 100644 --- a/solution/2500-2599/2509.Cycle Length Queries in a Tree/README.md +++ b/solution/2500-2599/2509.Cycle Length Queries in a Tree/README.md @@ -72,9 +72,7 @@ ## 解法 - - -**方法一:求最近公共祖先** +### 方法一:求最近公共祖先 对于每次查询,我们找出 $a$, $b$ 两个节点的最近公共祖先,并且记录向上走的步数,那么此次查询的答案就是步数加一。 @@ -84,10 +82,6 @@ -### **Python3** - - - ```python class Solution: def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]: @@ -104,10 +98,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] cycleLengthQueries(int n, int[][] queries) { @@ -131,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func cycleLengthQueries(n int, queries [][]int) []int { ans := []int{} @@ -178,10 +164,6 @@ func cycleLengthQueries(n int, queries [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2509.Cycle Length Queries in a Tree/README_EN.md b/solution/2500-2599/2509.Cycle Length Queries in a Tree/README_EN.md index f91917eb29367..6d905181275df 100644 --- a/solution/2500-2599/2509.Cycle Length Queries in a Tree/README_EN.md +++ b/solution/2500-2599/2509.Cycle Length Queries in a Tree/README_EN.md @@ -64,9 +64,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] cycleLengthQueries(int n, int[][] queries) { @@ -109,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +130,6 @@ public: }; ``` -### **Go** - ```go func cycleLengthQueries(n int, queries [][]int) []int { ans := []int{} @@ -156,10 +150,6 @@ func cycleLengthQueries(n int, queries [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2510.Check if There is a Path With Equal Number of 0's And 1's/README.md b/solution/2500-2599/2510.Check if There is a Path With Equal Number of 0's And 1's/README.md index 9098a0402aea6..571171e7d4796 100644 --- a/solution/2500-2599/2510.Check if There is a Path With Equal Number of 0's And 1's/README.md +++ b/solution/2500-2599/2510.Check if There is a Path With Equal Number of 0's And 1's/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 根据题目描述我们知道,从左上角到右下角的路径上 $0$ 的个数和 $1$ 的个数相等,个数总和为 $m + n - 1$,即 $0$ 的个数和 $1$ 的个数都为 $(m + n - 1) / 2$。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def isThereAPath(self, grid: List[List[int]]) -> bool: @@ -79,10 +73,6 @@ class Solution: return dfs(0, 0, 0) ``` -### **Java** - - - ```java class Solution { private int s; @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func isThereAPath(grid [][]int) bool { m, n := len(grid), len(grid[0]) @@ -187,10 +173,6 @@ func isThereAPath(grid [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2510.Check if There is a Path With Equal Number of 0's And 1's/README_EN.md b/solution/2500-2599/2510.Check if There is a Path With Equal Number of 0's And 1's/README_EN.md index b6dcbaf4433fd..8bb4a16d226d1 100644 --- a/solution/2500-2599/2510.Check if There is a Path With Equal Number of 0's And 1's/README_EN.md +++ b/solution/2500-2599/2510.Check if There is a Path With Equal Number of 0's And 1's/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return dfs(0, 0, 0) ``` -### **Java** - ```java class Solution { private int s; @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +128,6 @@ public: }; ``` -### **Go** - ```go func isThereAPath(grid [][]int) bool { m, n := len(grid), len(grid[0]) @@ -169,10 +163,6 @@ func isThereAPath(grid [][]int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README.md b/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README.md index 7889cea05ecfe..4d1ef06cbaa61 100644 --- a/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README.md +++ b/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们用指针 $i$ 遍历数组 $forts$,指针 $j$ 从 $i$ 的下一个位置开始遍历,直到遇到第一个非 $0$ 的位置,即 $forts[j] \neq 0$。如果 $forts[i] + forts[j] = 0$,那么我们可以将军队在 $i$ 和 $j$ 之间移动,摧毁 $j - i - 1$ 个敌人城堡。我们用变量 $ans$ 记录最多可以摧毁的敌人城堡数目即可。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def captureForts(self, forts: List[int]) -> int: @@ -85,10 +79,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int captureForts(int[] forts) { @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func captureForts(forts []int) (ans int) { n := len(forts) @@ -158,8 +144,6 @@ func captureForts(forts []int) (ans int) { } ``` -### **TypeScript** - ```ts function captureForts(forts: number[]): number { const n = forts.length; @@ -181,8 +165,6 @@ function captureForts(forts: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn capture_forts(forts: Vec) -> i32 { @@ -206,6 +188,12 @@ impl Solution { } ``` + + +### 方法二 + + + ```rust impl Solution { pub fn capture_forts(forts: Vec) -> i32 { @@ -238,10 +226,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README_EN.md b/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README_EN.md index 9fed7059d8a73..f06531dcaa9d9 100644 --- a/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README_EN.md +++ b/solution/2500-2599/2511.Maximum Enemy Forts That Can Be Captured/README_EN.md @@ -53,9 +53,9 @@ Since 4 is the maximum number of enemy forts that can be captured, we return 4. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int captureForts(int[] forts) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +118,6 @@ public: }; ``` -### **Go** - ```go func captureForts(forts []int) (ans int) { n := len(forts) @@ -144,8 +138,6 @@ func captureForts(forts []int) (ans int) { } ``` -### **TypeScript** - ```ts function captureForts(forts: number[]): number { const n = forts.length; @@ -167,8 +159,6 @@ function captureForts(forts: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn capture_forts(forts: Vec) -> i32 { @@ -192,6 +182,12 @@ impl Solution { } ``` + + +### Solution 2 + + + ```rust impl Solution { pub fn capture_forts(forts: Vec) -> i32 { @@ -224,10 +220,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2512.Reward Top K Students/README.md b/solution/2500-2599/2512.Reward Top K Students/README.md index 15fc215a3d73a..0f5ceb942a8eb 100644 --- a/solution/2500-2599/2512.Reward Top K Students/README.md +++ b/solution/2500-2599/2512.Reward Top K Students/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:哈希表 + 排序** +### 方法一:哈希表 + 排序 我们可以将正面的单词存入哈希表 $ps$ 中,将负面的单词存入哈希表 $ns$ 中。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def topStudents( @@ -98,10 +92,6 @@ class Solution: return [v[1] for v in arr[:k]] ``` -### **Java** - - - ```java class Solution { public List topStudents(String[] positive_feedback, String[] negative_feedback, @@ -138,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -181,8 +169,6 @@ public: }; ``` -### **Go** - ```go func topStudents(positive_feedback []string, negative_feedback []string, report []string, student_id []int, k int) (ans []int) { ps := map[string]bool{} @@ -213,8 +199,6 @@ func topStudents(positive_feedback []string, negative_feedback []string, report } ``` -### **TypeScript** - ```ts function topStudents( positive_feedback: string[], @@ -253,8 +237,6 @@ function topStudents( } ``` -### **Rust** - ```rust use std::collections::{ HashMap, HashSet }; impl Solution { @@ -297,10 +279,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2512.Reward Top K Students/README_EN.md b/solution/2500-2599/2512.Reward Top K Students/README_EN.md index 3900c7ddffae6..6494ebcbbe54a 100644 --- a/solution/2500-2599/2512.Reward Top K Students/README_EN.md +++ b/solution/2500-2599/2512.Reward Top K Students/README_EN.md @@ -53,7 +53,7 @@ Since student 2 has more points, [2,1] is returned. ## Solutions -**Solution 1: Hash Table + Sorting** +### Solution 1: Hash Table + Sorting We can store the positive words in a hash table $ps$ and the negative words in a hash table $ns$. @@ -65,8 +65,6 @@ The time complexity is $O(n \times \log n + (|ps| + |ns| + n) \times |s|)$, and -### **Python3** - ```python class Solution: def topStudents( @@ -92,8 +90,6 @@ class Solution: return [v[1] for v in arr[:k]] ``` -### **Java** - ```java class Solution { public List topStudents(String[] positive_feedback, String[] negative_feedback, @@ -130,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -173,8 +167,6 @@ public: }; ``` -### **Go** - ```go func topStudents(positive_feedback []string, negative_feedback []string, report []string, student_id []int, k int) (ans []int) { ps := map[string]bool{} @@ -205,8 +197,6 @@ func topStudents(positive_feedback []string, negative_feedback []string, report } ``` -### **TypeScript** - ```ts function topStudents( positive_feedback: string[], @@ -245,8 +235,6 @@ function topStudents( } ``` -### **Rust** - ```rust use std::collections::{ HashMap, HashSet }; impl Solution { @@ -289,10 +277,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2513.Minimize the Maximum of Two Arrays/README.md b/solution/2500-2599/2513.Minimize the Maximum of Two Arrays/README.md index 8472f5f1fde65..dfae1f7987ff8 100644 --- a/solution/2500-2599/2513.Minimize the Maximum of Two Arrays/README.md +++ b/solution/2500-2599/2513.Minimize the Maximum of Two Arrays/README.md @@ -61,14 +61,10 @@ arr1 = [1,2] 和 arr2 = [3] 满足所有条件。 ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minimizeSet( @@ -88,10 +84,6 @@ class Solution: return bisect_left(range(10**10), True, key=f) ``` -### **Java** - - - ```java class Solution { public int minimizeSet(int divisor1, int divisor2, int uniqueCnt1, int uniqueCnt2) { @@ -121,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +135,6 @@ public: }; ``` -### **Go** - ```go func minimizeSet(divisor1 int, divisor2 int, uniqueCnt1 int, uniqueCnt2 int) int { divisor := lcm(divisor1, divisor2) @@ -177,10 +165,6 @@ func gcd(a, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2513.Minimize the Maximum of Two Arrays/README_EN.md b/solution/2500-2599/2513.Minimize the Maximum of Two Arrays/README_EN.md index 832ea368fe26e..5dc172bccff95 100644 --- a/solution/2500-2599/2513.Minimize the Maximum of Two Arrays/README_EN.md +++ b/solution/2500-2599/2513.Minimize the Maximum of Two Arrays/README_EN.md @@ -57,9 +57,9 @@ It can be shown that it is not possible to obtain a lower maximum satisfying all ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return bisect_left(range(10**10), True, key=f) ``` -### **Java** - ```java class Solution { public int minimizeSet(int divisor1, int divisor2, int uniqueCnt1, int uniqueCnt2) { @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +131,6 @@ public: }; ``` -### **Go** - ```go func minimizeSet(divisor1 int, divisor2 int, uniqueCnt1 int, uniqueCnt2 int) int { divisor := lcm(divisor1, divisor2) @@ -167,10 +161,6 @@ func gcd(a, b int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2514.Count Anagrams/README.md b/solution/2500-2599/2514.Count Anagrams/README.md index d2f4226328639..44b3329a6c716 100644 --- a/solution/2500-2599/2514.Count Anagrams/README.md +++ b/solution/2500-2599/2514.Count Anagrams/README.md @@ -43,14 +43,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python mod = 10**9 + 7 f = [1] @@ -71,24 +67,6 @@ class Solution: return ans ``` -```python -class Solution: - def countAnagrams(self, s: str) -> int: - mod = 10**9 + 7 - ans = mul = 1 - for w in s.split(): - cnt = Counter() - for i, c in enumerate(w, 1): - cnt[c] += 1 - mul = mul * cnt[c] % mod - ans = ans * i % mod - return ans * pow(mul, -1, mod) % mod -``` - -### **Java** - - - ```java import java.math.BigInteger; @@ -119,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +129,6 @@ public: }; ``` -### **Go** - ```go const mod int = 1e9 + 7 @@ -184,10 +158,26 @@ func pow(x, n int) int { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def countAnagrams(self, s: str) -> int: + mod = 10**9 + 7 + ans = mul = 1 + for w in s.split(): + cnt = Counter() + for i, c in enumerate(w, 1): + cnt[c] += 1 + mul = mul * cnt[c] % mod + ans = ans * i % mod + return ans * pow(mul, -1, mod) % mod ``` + + diff --git a/solution/2500-2599/2514.Count Anagrams/README_EN.md b/solution/2500-2599/2514.Count Anagrams/README_EN.md index 23f90663d770d..fc93d122d1fd6 100644 --- a/solution/2500-2599/2514.Count Anagrams/README_EN.md +++ b/solution/2500-2599/2514.Count Anagrams/README_EN.md @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python mod = 10**9 + 7 @@ -65,22 +65,6 @@ class Solution: return ans ``` -```python -class Solution: - def countAnagrams(self, s: str) -> int: - mod = 10**9 + 7 - ans = mul = 1 - for w in s.split(): - cnt = Counter() - for i, c in enumerate(w, 1): - cnt[c] += 1 - mul = mul * cnt[c] % mod - ans = ans * i % mod - return ans * pow(mul, -1, mod) % mod -``` - -### **Java** - ```java import java.math.BigInteger; @@ -111,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +127,6 @@ public: }; ``` -### **Go** - ```go const mod int = 1e9 + 7 @@ -176,10 +156,26 @@ func pow(x, n int) int { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def countAnagrams(self, s: str) -> int: + mod = 10**9 + 7 + ans = mul = 1 + for w in s.split(): + cnt = Counter() + for i, c in enumerate(w, 1): + cnt[c] += 1 + mul = mul * cnt[c] % mod + ans = ans * i % mod + return ans * pow(mul, -1, mod) % mod ``` + + diff --git a/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/README.md b/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/README.md index 1023fe2ce5866..9b170037cfd54 100644 --- a/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/README.md +++ b/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 遍历数组,找到与 target 相等的单词,计算其与 startIndex 的距离 $t$,则此时的最短距离为 $min(t, n - t)$,我们只需要不断更新最小值即可。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def closetTarget(self, words: List[str], target: str, startIndex: int) -> int: @@ -85,10 +79,6 @@ class Solution: return -1 if ans == n else ans ``` -### **Java** - - - ```java class Solution { public int closetTarget(String[] words, String target, int startIndex) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func closetTarget(words []string, target string, startIndex int) int { n := len(words) @@ -152,8 +138,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function closetTarget(words: string[], target: string, startIndex: number): number { const n = words.length; @@ -166,8 +150,6 @@ function closetTarget(words: string[], target: string, startIndex: number): numb } ``` -### **Rust** - ```rust impl Solution { pub fn closet_target(words: Vec, target: String, start_index: i32) -> i32 { @@ -186,6 +168,23 @@ impl Solution { } ``` +```c +int closetTarget(char** words, int wordsSize, char* target, int startIndex) { + for (int i = 0; i <= wordsSize >> 1; i++) { + if (strcmp(words[(startIndex - i + wordsSize) % wordsSize], target) == 0 || strcmp(words[(startIndex + i) % wordsSize], target) == 0) { + return i; + } + } + return -1; +} +``` + + + +### 方法二 + + + ```rust use std::cmp::min; @@ -209,23 +208,6 @@ impl Solution { } ``` -### **C** - -```c -int closetTarget(char** words, int wordsSize, char* target, int startIndex) { - for (int i = 0; i <= wordsSize >> 1; i++) { - if (strcmp(words[(startIndex - i + wordsSize) % wordsSize], target) == 0 || strcmp(words[(startIndex + i) % wordsSize], target) == 0) { - return i; - } - } - return -1; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/README_EN.md b/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/README_EN.md index 828acf1dd3a4d..5300ea97b06bb 100644 --- a/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/README_EN.md +++ b/solution/2500-2599/2515.Shortest Distance to Target String in a Circular Array/README_EN.md @@ -58,9 +58,9 @@ The shortest distance to reach "leetcode" is 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return -1 if ans == n else ans ``` -### **Java** - ```java class Solution { public int closetTarget(String[] words, String target, int startIndex) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func closetTarget(words []string, target string, startIndex int) int { n := len(words) @@ -139,8 +133,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function closetTarget(words: string[], target: string, startIndex: number): number { const n = words.length; @@ -153,8 +145,6 @@ function closetTarget(words: string[], target: string, startIndex: number): numb } ``` -### **Rust** - ```rust impl Solution { pub fn closet_target(words: Vec, target: String, start_index: i32) -> i32 { @@ -173,6 +163,23 @@ impl Solution { } ``` +```c +int closetTarget(char** words, int wordsSize, char* target, int startIndex) { + for (int i = 0; i <= wordsSize >> 1; i++) { + if (strcmp(words[(startIndex - i + wordsSize) % wordsSize], target) == 0 || strcmp(words[(startIndex + i) % wordsSize], target) == 0) { + return i; + } + } + return -1; +} +``` + + + +### Solution 2 + + + ```rust use std::cmp::min; @@ -196,23 +203,6 @@ impl Solution { } ``` -### **C** - -```c -int closetTarget(char** words, int wordsSize, char* target, int startIndex) { - for (int i = 0; i <= wordsSize >> 1; i++) { - if (strcmp(words[(startIndex - i + wordsSize) % wordsSize], target) == 0 || strcmp(words[(startIndex + i) % wordsSize], target) == 0) { - return i; - } - } - return -1; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2516.Take K of Each Character From Left and Right/README.md b/solution/2500-2599/2516.Take K of Each Character From Left and Right/README.md index b6f741a544c86..8e32650bd6cc8 100644 --- a/solution/2500-2599/2516.Take K of Each Character From Left and Right/README.md +++ b/solution/2500-2599/2516.Take K of Each Character From Left and Right/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 我们先用哈希表或者一个长度为 $3$ 的数组 `cnt` 统计字符串 $s$ 中每个字符的个数,如果有字符的个数小于 $k$ 个,则无法取到,提前返回 $-1$。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def takeCharacters(self, s: str, k: int) -> int: @@ -80,10 +74,6 @@ class Solution: return len(s) - ans ``` -### **Java** - - - ```java class Solution { public int takeCharacters(String s, int k) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +121,6 @@ public: }; ``` -### **Go** - ```go func takeCharacters(s string, k int) int { cnt := [3]int{} @@ -158,8 +144,6 @@ func takeCharacters(s string, k int) int { } ``` -### **TypeScript** - ```ts function takeCharacters(s: string, k: number): number { const getIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); @@ -184,8 +168,6 @@ function takeCharacters(s: string, k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn take_characters(s: String, k: i32) -> i32 { @@ -213,10 +195,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2516.Take K of Each Character From Left and Right/README_EN.md b/solution/2500-2599/2516.Take K of Each Character From Left and Right/README_EN.md index 0968e7ba21c8f..722fe3b1e2fd4 100644 --- a/solution/2500-2599/2516.Take K of Each Character From Left and Right/README_EN.md +++ b/solution/2500-2599/2516.Take K of Each Character From Left and Right/README_EN.md @@ -40,9 +40,9 @@ It can be proven that 8 is the minimum number of minutes needed. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return len(s) - ans ``` -### **Java** - ```java class Solution { public int takeCharacters(String s, int k) { @@ -87,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +107,6 @@ public: }; ``` -### **Go** - ```go func takeCharacters(s string, k int) int { cnt := [3]int{} @@ -136,8 +130,6 @@ func takeCharacters(s string, k int) int { } ``` -### **TypeScript** - ```ts function takeCharacters(s: string, k: number): number { const getIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); @@ -162,8 +154,6 @@ function takeCharacters(s: string, k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn take_characters(s: String, k: i32) -> i32 { @@ -191,10 +181,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2517.Maximum Tastiness of Candy Basket/README.md b/solution/2500-2599/2517.Maximum Tastiness of Candy Basket/README.md index 96e6563dbf5e7..571c2c3c420bb 100644 --- a/solution/2500-2599/2517.Maximum Tastiness of Candy Basket/README.md +++ b/solution/2500-2599/2517.Maximum Tastiness of Candy Basket/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:贪心 + 二分查找** +### 方法一:贪心 + 二分查找 我们注意到,如果一个甜蜜度为 $x$ 的礼盒是可行的,那么甜蜜度小于 $x$ 的礼盒也是可行的,这存在着单调性,因此我们可以使用二分查找的方法,找到最大的可行甜蜜度。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def maximumTastiness(self, price: List[int], k: int) -> int: @@ -95,10 +89,6 @@ class Solution: return l ``` -### **Java** - - - ```java class Solution { public int maximumTastiness(int[] price, int k) { @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +147,6 @@ public: }; ``` -### **Go** - ```go func maximumTastiness(price []int, k int) int { sort.Ints(price) @@ -177,8 +163,6 @@ func maximumTastiness(price []int, k int) int { } ``` -### **TypeScript** - ```ts function maximumTastiness(price: number[], k: number): number { price.sort((a, b) => a - b); @@ -206,8 +190,6 @@ function maximumTastiness(price: number[], k: number): number { } ``` -### **C#** - ```cs public class Solution { public int MaximumTastiness(int[] price, int k) { @@ -237,10 +219,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2517.Maximum Tastiness of Candy Basket/README_EN.md b/solution/2500-2599/2517.Maximum Tastiness of Candy Basket/README_EN.md index 1082b3a5910d6..579ad81e8b562 100644 --- a/solution/2500-2599/2517.Maximum Tastiness of Candy Basket/README_EN.md +++ b/solution/2500-2599/2517.Maximum Tastiness of Candy Basket/README_EN.md @@ -49,9 +49,9 @@ It can be proven that 2 is the maximum tastiness that can be achieved. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -75,8 +75,6 @@ class Solution: return l ``` -### **Java** - ```java class Solution { public int maximumTastiness(int[] price, int k) { @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +133,6 @@ public: }; ``` -### **Go** - ```go func maximumTastiness(price []int, k int) int { sort.Ints(price) @@ -155,8 +149,6 @@ func maximumTastiness(price []int, k int) int { } ``` -### **TypeScript** - ```ts function maximumTastiness(price: number[], k: number): number { price.sort((a, b) => a - b); @@ -184,8 +176,6 @@ function maximumTastiness(price: number[], k: number): number { } ``` -### **C#** - ```cs public class Solution { public int MaximumTastiness(int[] price, int k) { @@ -215,10 +205,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2518.Number of Great Partitions/README.md b/solution/2500-2599/2518.Number of Great Partitions/README.md index 00674359b61fa..2777bdb5cda6a 100644 --- a/solution/2500-2599/2518.Number of Great Partitions/README.md +++ b/solution/2500-2599/2518.Number of Great Partitions/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:逆向思维 + 动态规划** +### 方法一:逆向思维 + 动态规划 对于一个长度为 $n$ 的数组 `nums`,每个元素都可以选择放入第一个分区或第二个分区,因此一共有 $2^n$ 种分区方式。每一种分区方式,得到的结果可以是“好分区”或者“坏分区”,题目要我们求“好分区”的个数,我们可以转换为求“坏分区”的个数。那么“好分区”的个数就是 $2^n$ 减去“坏分区”的个数。 @@ -77,10 +75,6 @@ $$ -### **Python3** - - - ```python class Solution: def countPartitions(self, nums: List[int], k: int) -> int: @@ -100,10 +94,6 @@ class Solution: return (ans - sum(f[-1]) * 2 + mod) % mod ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -138,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +159,6 @@ public: }; ``` -### **Go** - ```go func countPartitions(nums []int, k int) int { s := 0 @@ -207,10 +193,6 @@ func countPartitions(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2518.Number of Great Partitions/README_EN.md b/solution/2500-2599/2518.Number of Great Partitions/README_EN.md index 4ee671e10dbc0..5ee41bb6056a2 100644 --- a/solution/2500-2599/2518.Number of Great Partitions/README_EN.md +++ b/solution/2500-2599/2518.Number of Great Partitions/README_EN.md @@ -48,9 +48,9 @@ The great partitions will be ([6], [6]) and ([6], [6]). ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return (ans - sum(f[-1]) * 2 + mod) % mod ``` -### **Java** - ```java class Solution { private static final int MOD = (int) 1e9 + 7; @@ -107,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +136,6 @@ public: }; ``` -### **Go** - ```go func countPartitions(nums []int, k int) int { s := 0 @@ -176,10 +170,6 @@ func countPartitions(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2519.Count the Number of K-Big Indices/README.md b/solution/2500-2599/2519.Count the Number of K-Big Indices/README.md index cf9646cf26583..1dbd82d6f13c3 100644 --- a/solution/2500-2599/2519.Count the Number of K-Big Indices/README.md +++ b/solution/2500-2599/2519.Count the Number of K-Big Indices/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:树状数组** +### 方法一:树状数组 我们维护两个树状数组,一个记录当前位置左边小于当前位置的数的个数,另一个记录当前位置右边小于当前位置的数的个数。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class BinaryIndexedTree: def __init__(self, n): @@ -97,10 +91,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class BinaryIndexedTree { private int n; @@ -149,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -199,8 +187,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -246,10 +232,6 @@ func kBigIndices(nums []int, k int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2519.Count the Number of K-Big Indices/README_EN.md b/solution/2500-2599/2519.Count the Number of K-Big Indices/README_EN.md index d3951d5768622..c17734a0f3e26 100644 --- a/solution/2500-2599/2519.Count the Number of K-Big Indices/README_EN.md +++ b/solution/2500-2599/2519.Count the Number of K-Big Indices/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Binary Indexed Tree** +### Solution 1: Binary Indexed Tree We maintain two binary indexed trees, one records the number of elements smaller than the current position on the left, and the other records the number of elements smaller than the current position on the right. @@ -54,8 +54,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$, -### **Python3** - ```python class BinaryIndexedTree: def __init__(self, n): @@ -90,8 +88,6 @@ class Solution: return ans ``` -### **Java** - ```java class BinaryIndexedTree { private int n; @@ -140,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -190,8 +184,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -237,10 +229,6 @@ func kBigIndices(nums []int, k int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2520.Count the Digits That Divide a Number/README.md b/solution/2500-2599/2520.Count the Digits That Divide a Number/README.md index 5a1a682b04ec8..bdb8435005c77 100644 --- a/solution/2500-2599/2520.Count the Digits That Divide a Number/README.md +++ b/solution/2500-2599/2520.Count the Digits That Divide a Number/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们直接枚举整数 $num$ 的每一位上的数 $val$,若 $val$ 能够整除 $num$,那么答案加一。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def countDigits(self, num: int) -> int: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countDigits(int num) { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +93,6 @@ public: }; ``` -### **Go** - ```go func countDigits(num int) (ans int) { for x := num; x > 0; x /= 10 { @@ -118,8 +104,6 @@ func countDigits(num int) (ans int) { } ``` -### **TypeScript** - ```ts function countDigits(num: number): number { let ans = 0; @@ -132,20 +116,6 @@ function countDigits(num: number): number { } ``` -```ts -function countDigits(num: number): number { - let ans = 0; - for (const s of num.toString()) { - if (num % Number(s) === 0) { - ans++; - } - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn count_digits(num: i32) -> i32 { @@ -162,21 +132,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn count_digits(num: i32) -> i32 { - num - .to_string() - .chars() - .filter(|&c| c != '0') - .filter(|&c| num % (c.to_digit(10).unwrap() as i32) == 0) - .count() as i32 - } -} -``` - -### **C** - ```c int countDigits(int num) { int ans = 0; @@ -191,10 +146,37 @@ int countDigits(int num) { } ``` -### **...** + + +### 方法二 + + +```ts +function countDigits(num: number): number { + let ans = 0; + for (const s of num.toString()) { + if (num % Number(s) === 0) { + ans++; + } + } + return ans; +} ``` +```rust +impl Solution { + pub fn count_digits(num: i32) -> i32 { + num + .to_string() + .chars() + .filter(|&c| c != '0') + .filter(|&c| num % (c.to_digit(10).unwrap() as i32) == 0) + .count() as i32 + } +} ``` + + diff --git a/solution/2500-2599/2520.Count the Digits That Divide a Number/README_EN.md b/solution/2500-2599/2520.Count the Digits That Divide a Number/README_EN.md index dba09b82e6dfb..0536e54b491b9 100644 --- a/solution/2500-2599/2520.Count the Digits That Divide a Number/README_EN.md +++ b/solution/2500-2599/2520.Count the Digits That Divide a Number/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We directly enumerate each digit $val$ of the integer $num$, and if $val$ can divide $num$, we add one to the answer. @@ -53,8 +53,6 @@ The time complexity is $O(\log num)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def countDigits(self, num: int) -> int: @@ -65,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countDigits(int num) { @@ -81,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +92,6 @@ public: }; ``` -### **Go** - ```go func countDigits(num int) (ans int) { for x := num; x > 0; x /= 10 { @@ -111,8 +103,6 @@ func countDigits(num int) (ans int) { } ``` -### **TypeScript** - ```ts function countDigits(num: number): number { let ans = 0; @@ -125,20 +115,6 @@ function countDigits(num: number): number { } ``` -```ts -function countDigits(num: number): number { - let ans = 0; - for (const s of num.toString()) { - if (num % Number(s) === 0) { - ans++; - } - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn count_digits(num: i32) -> i32 { @@ -155,21 +131,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn count_digits(num: i32) -> i32 { - num - .to_string() - .chars() - .filter(|&c| c != '0') - .filter(|&c| num % (c.to_digit(10).unwrap() as i32) == 0) - .count() as i32 - } -} -``` - -### **C** - ```c int countDigits(int num) { int ans = 0; @@ -184,10 +145,37 @@ int countDigits(int num) { } ``` -### **...** + + +### Solution 2 + + +```ts +function countDigits(num: number): number { + let ans = 0; + for (const s of num.toString()) { + if (num % Number(s) === 0) { + ans++; + } + } + return ans; +} ``` +```rust +impl Solution { + pub fn count_digits(num: i32) -> i32 { + num + .to_string() + .chars() + .filter(|&c| c != '0') + .filter(|&c| num % (c.to_digit(10).unwrap() as i32) == 0) + .count() as i32 + } +} ``` + + diff --git a/solution/2500-2599/2521.Distinct Prime Factors of Product of Array/README.md b/solution/2500-2599/2521.Distinct Prime Factors of Product of Array/README.md index a04488e08eee4..3fda122b8e903 100644 --- a/solution/2500-2599/2521.Distinct Prime Factors of Product of Array/README.md +++ b/solution/2500-2599/2521.Distinct Prime Factors of Product of Array/README.md @@ -45,9 +45,7 @@ nums 中所有元素的乘积是:2 * 4 * 8 * 16 = 1024 = 210 。 ## 解法 - - -**方法一:哈希表 + 质因数分解** +### 方法一:哈希表 + 质因数分解 对于数组中的每个元素,先对其进行质因数分解,然后将分解出的质因数加入哈希表中。最后返回哈希表的大小即可。 @@ -55,10 +53,6 @@ nums 中所有元素的乘积是:2 * 4 * 8 * 16 = 1024 = 210 -### **Python3** - - - ```python class Solution: def distinctPrimeFactors(self, nums: List[int]) -> int: @@ -76,10 +70,6 @@ class Solution: return len(s) ``` -### **Java** - - - ```java class Solution { public int distinctPrimeFactors(int[] nums) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func distinctPrimeFactors(nums []int) int { s := map[int]bool{} @@ -149,10 +135,6 @@ func distinctPrimeFactors(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2521.Distinct Prime Factors of Product of Array/README_EN.md b/solution/2500-2599/2521.Distinct Prime Factors of Product of Array/README_EN.md index e2147660c4570..c2c29b55e4406 100644 --- a/solution/2500-2599/2521.Distinct Prime Factors of Product of Array/README_EN.md +++ b/solution/2500-2599/2521.Distinct Prime Factors of Product of Array/README_EN.md @@ -44,9 +44,9 @@ There is 1 distinct prime factor so we return 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return len(s) ``` -### **Java** - ```java class Solution { public int distinctPrimeFactors(int[] nums) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +110,6 @@ public: }; ``` -### **Go** - ```go func distinctPrimeFactors(nums []int) int { s := map[int]bool{} @@ -136,10 +130,6 @@ func distinctPrimeFactors(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2522.Partition String Into Substrings With Values at Most K/README.md b/solution/2500-2599/2522.Partition String Into Substrings With Values at Most K/README.md index 7a82a02d3a32e..2b3e1483084da 100644 --- a/solution/2500-2599/2522.Partition String Into Substrings With Values at Most K/README.md +++ b/solution/2500-2599/2522.Partition String Into Substrings With Values at Most K/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i)$ 表示从字符串 $s$ 的下标 $i$ 开始的最少分割数,那么答案就是 $dfs(0)$。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def minimumPartition(self, s: str, k: int) -> int: @@ -98,10 +92,6 @@ class Solution: return ans if ans < inf else -1 ``` -### **Java** - - - ```java class Solution { private Integer[] f; @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go func minimumPartition(s string, k int) int { n := len(s) @@ -202,10 +188,6 @@ func minimumPartition(s string, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2522.Partition String Into Substrings With Values at Most K/README_EN.md b/solution/2500-2599/2522.Partition String Into Substrings With Values at Most K/README_EN.md index 1c4ecc3d47b4f..8efed221189fd 100644 --- a/solution/2500-2599/2522.Partition String Into Substrings With Values at Most K/README_EN.md +++ b/solution/2500-2599/2522.Partition String Into Substrings With Values at Most K/README_EN.md @@ -60,9 +60,9 @@ It can be shown that we cannot partition the string into less than 4 substrings. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: return ans if ans < inf else -1 ``` -### **Java** - ```java class Solution { private Integer[] f; @@ -124,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +148,6 @@ public: }; ``` -### **Go** - ```go func minimumPartition(s string, k int) int { n := len(s) @@ -186,10 +180,6 @@ func minimumPartition(s string, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2523.Closest Prime Numbers in Range/README.md b/solution/2500-2599/2523.Closest Prime Numbers in Range/README.md index 5988dbcc9863d..37f23d5fc7b46 100644 --- a/solution/2500-2599/2523.Closest Prime Numbers in Range/README.md +++ b/solution/2500-2599/2523.Closest Prime Numbers in Range/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:线性筛** +### 方法一:线性筛 对于给定的范围 $[left, right]$,我们可以使用线性筛求出所有质数,然后从小到大遍历质数,找到相邻的两个质数,其差值最小的质数对即为答案。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def closestPrimes(self, left: int, right: int) -> List[int]: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] closestPrimes(int left, int right) { @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +170,6 @@ public: }; ``` -### **Go** - ```go func closestPrimes(left int, right int) []int { cnt := 0 @@ -226,10 +212,6 @@ func closestPrimes(left int, right int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2523.Closest Prime Numbers in Range/README_EN.md b/solution/2500-2599/2523.Closest Prime Numbers in Range/README_EN.md index 05ca6218bce26..6c829e09b5ecc 100644 --- a/solution/2500-2599/2523.Closest Prime Numbers in Range/README_EN.md +++ b/solution/2500-2599/2523.Closest Prime Numbers in Range/README_EN.md @@ -53,9 +53,9 @@ Since 11 is smaller than 17, we return the first pair. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,8 +83,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] closestPrimes(int left, int right) { @@ -129,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +171,6 @@ public: }; ``` -### **Go** - ```go func closestPrimes(left int, right int) []int { cnt := 0 @@ -219,10 +213,6 @@ func closestPrimes(left int, right int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/README.md b/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/README.md index ed06374090b53..2ef35bd8df356 100644 --- a/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/README.md +++ b/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:哈希表 + 滑动窗口 + 快速幂** +### 方法一:哈希表 + 滑动窗口 + 快速幂 我们用哈希表 `cnt` 维护窗口大小为 $k$ 的元素及其出现的次数。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def maxFrequencyScore(self, nums: List[int], k: int) -> int: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -178,8 +166,6 @@ public: }; ``` -### **Go** - ```go func maxFrequencyScore(nums []int, k int) int { cnt := map[int]int{} @@ -225,10 +211,6 @@ func maxFrequencyScore(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/README_EN.md b/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/README_EN.md index 48cc082ade75f..a2e29f1294431 100644 --- a/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/README_EN.md +++ b/solution/2500-2599/2524.Maximum Frequency Score of a Subarray/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -119,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +158,6 @@ public: }; ``` -### **Go** - ```go func maxFrequencyScore(nums []int, k int) int { cnt := map[int]int{} @@ -209,10 +203,6 @@ func maxFrequencyScore(nums []int, k int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2525.Categorize Box According to Criteria/README.md b/solution/2500-2599/2525.Categorize Box According to Criteria/README.md index 1eb3dbb1c987f..531e8a820c343 100644 --- a/solution/2500-2599/2525.Categorize Box According to Criteria/README.md +++ b/solution/2500-2599/2525.Categorize Box According to Criteria/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 根据题意模拟即可。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str: @@ -84,6 +78,88 @@ class Solution: return d[i] ``` +```java +class Solution { + public String categorizeBox(int length, int width, int height, int mass) { + long v = (long) length * width * height; + int bulky = length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 ? 1 : 0; + int heavy = mass >= 100 ? 1 : 0; + String[] d = {"Neither", "Bulky", "Heavy", "Both"}; + int i = heavy << 1 | bulky; + return d[i]; + } +} +``` + +```cpp +class Solution { +public: + string categorizeBox(int length, int width, int height, int mass) { + long v = (long) length * width * height; + int bulky = length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 ? 1 : 0; + int heavy = mass >= 100 ? 1 : 0; + string d[4] = {"Neither", "Bulky", "Heavy", "Both"}; + int i = heavy << 1 | bulky; + return d[i]; + } +}; +``` + +```go +func categorizeBox(length int, width int, height int, mass int) string { + v := length * width * height + i := 0 + if length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 { + i |= 1 + } + if mass >= 100 { + i |= 2 + } + d := [4]string{"Neither", "Bulky", "Heavy", "Both"} + return d[i] +} +``` + +```ts +function categorizeBox(length: number, width: number, height: number, mass: number): string { + const v = length * width * height; + let i = 0; + if (length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000) { + i |= 1; + } + if (mass >= 100) { + i |= 2; + } + return ['Neither', 'Bulky', 'Heavy', 'Both'][i]; +} +``` + +```rust +impl Solution { + pub fn categorize_box(length: i32, width: i32, height: i32, mass: i32) -> String { + let v = (length as i64) * (width as i64) * (height as i64); + let mut i = 0; + + if length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 { + i |= 1; + } + + if mass >= 100 { + i |= 2; + } + + let d = vec!["Neither", "Bulky", "Heavy", "Both"]; + d[i].to_string() + } +} +``` + + + +### 方法二 + + + ```python class Solution: def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str: @@ -101,23 +177,6 @@ class Solution: return "Neither" ``` -### **Java** - - - -```java -class Solution { - public String categorizeBox(int length, int width, int height, int mass) { - long v = (long) length * width * height; - int bulky = length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 ? 1 : 0; - int heavy = mass >= 100 ? 1 : 0; - String[] d = {"Neither", "Bulky", "Heavy", "Both"}; - int i = heavy << 1 | bulky; - return d[i]; - } -} -``` - ```java class Solution { public String categorizeBox(int length, int width, int height, int mass) { @@ -140,22 +199,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string categorizeBox(int length, int width, int height, int mass) { - long v = (long) length * width * height; - int bulky = length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 ? 1 : 0; - int heavy = mass >= 100 ? 1 : 0; - string d[4] = {"Neither", "Bulky", "Heavy", "Both"}; - int i = heavy << 1 | bulky; - return d[i]; - } -}; -``` - ```cpp class Solution { public: @@ -179,23 +222,6 @@ public: }; ``` -### **Go** - -```go -func categorizeBox(length int, width int, height int, mass int) string { - v := length * width * height - i := 0 - if length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 { - i |= 1 - } - if mass >= 100 { - i |= 2 - } - d := [4]string{"Neither", "Bulky", "Heavy", "Both"} - return d[i] -} -``` - ```go func categorizeBox(length int, width int, height int, mass int) string { v := length * width * height @@ -214,22 +240,6 @@ func categorizeBox(length int, width int, height int, mass int) string { } ``` -### **TypeScript** - -```ts -function categorizeBox(length: number, width: number, height: number, mass: number): string { - const v = length * width * height; - let i = 0; - if (length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000) { - i |= 1; - } - if (mass >= 100) { - i |= 2; - } - return ['Neither', 'Bulky', 'Heavy', 'Both'][i]; -} -``` - ```ts function categorizeBox(length: number, width: number, height: number, mass: number): string { const v = length * width * height; @@ -248,28 +258,6 @@ function categorizeBox(length: number, width: number, height: number, mass: numb } ``` -### **Rust** - -```rust -impl Solution { - pub fn categorize_box(length: i32, width: i32, height: i32, mass: i32) -> String { - let v = (length as i64) * (width as i64) * (height as i64); - let mut i = 0; - - if length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 { - i |= 1; - } - - if mass >= 100 { - i |= 2; - } - - let d = vec!["Neither", "Bulky", "Heavy", "Both"]; - d[i].to_string() - } -} -``` - ```rust impl Solution { pub fn categorize_box(length: i32, width: i32, height: i32, mass: i32) -> String { @@ -297,10 +285,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2525.Categorize Box According to Criteria/README_EN.md b/solution/2500-2599/2525.Categorize Box According to Criteria/README_EN.md index 6b3395a4cbcdb..55af69ca88525 100644 --- a/solution/2500-2599/2525.Categorize Box According to Criteria/README_EN.md +++ b/solution/2500-2599/2525.Categorize Box According to Criteria/README_EN.md @@ -55,7 +55,7 @@ Since its neither of the two above categories, we return "Neither".

-### **Python3** - ```python class Solution: def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str: @@ -76,6 +74,88 @@ class Solution: return d[i] ``` +```java +class Solution { + public String categorizeBox(int length, int width, int height, int mass) { + long v = (long) length * width * height; + int bulky = length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 ? 1 : 0; + int heavy = mass >= 100 ? 1 : 0; + String[] d = {"Neither", "Bulky", "Heavy", "Both"}; + int i = heavy << 1 | bulky; + return d[i]; + } +} +``` + +```cpp +class Solution { +public: + string categorizeBox(int length, int width, int height, int mass) { + long v = (long) length * width * height; + int bulky = length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 ? 1 : 0; + int heavy = mass >= 100 ? 1 : 0; + string d[4] = {"Neither", "Bulky", "Heavy", "Both"}; + int i = heavy << 1 | bulky; + return d[i]; + } +}; +``` + +```go +func categorizeBox(length int, width int, height int, mass int) string { + v := length * width * height + i := 0 + if length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 { + i |= 1 + } + if mass >= 100 { + i |= 2 + } + d := [4]string{"Neither", "Bulky", "Heavy", "Both"} + return d[i] +} +``` + +```ts +function categorizeBox(length: number, width: number, height: number, mass: number): string { + const v = length * width * height; + let i = 0; + if (length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000) { + i |= 1; + } + if (mass >= 100) { + i |= 2; + } + return ['Neither', 'Bulky', 'Heavy', 'Both'][i]; +} +``` + +```rust +impl Solution { + pub fn categorize_box(length: i32, width: i32, height: i32, mass: i32) -> String { + let v = (length as i64) * (width as i64) * (height as i64); + let mut i = 0; + + if length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 { + i |= 1; + } + + if mass >= 100 { + i |= 2; + } + + let d = vec!["Neither", "Bulky", "Heavy", "Both"]; + d[i].to_string() + } +} +``` + + + +### Solution 2 + + + ```python class Solution: def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str: @@ -93,21 +173,6 @@ class Solution: return "Neither" ``` -### **Java** - -```java -class Solution { - public String categorizeBox(int length, int width, int height, int mass) { - long v = (long) length * width * height; - int bulky = length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 ? 1 : 0; - int heavy = mass >= 100 ? 1 : 0; - String[] d = {"Neither", "Bulky", "Heavy", "Both"}; - int i = heavy << 1 | bulky; - return d[i]; - } -} -``` - ```java class Solution { public String categorizeBox(int length, int width, int height, int mass) { @@ -130,22 +195,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string categorizeBox(int length, int width, int height, int mass) { - long v = (long) length * width * height; - int bulky = length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 ? 1 : 0; - int heavy = mass >= 100 ? 1 : 0; - string d[4] = {"Neither", "Bulky", "Heavy", "Both"}; - int i = heavy << 1 | bulky; - return d[i]; - } -}; -``` - ```cpp class Solution { public: @@ -169,23 +218,6 @@ public: }; ``` -### **Go** - -```go -func categorizeBox(length int, width int, height int, mass int) string { - v := length * width * height - i := 0 - if length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 { - i |= 1 - } - if mass >= 100 { - i |= 2 - } - d := [4]string{"Neither", "Bulky", "Heavy", "Both"} - return d[i] -} -``` - ```go func categorizeBox(length int, width int, height int, mass int) string { v := length * width * height @@ -204,22 +236,6 @@ func categorizeBox(length int, width int, height int, mass int) string { } ``` -### **TypeScript** - -```ts -function categorizeBox(length: number, width: number, height: number, mass: number): string { - const v = length * width * height; - let i = 0; - if (length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000) { - i |= 1; - } - if (mass >= 100) { - i |= 2; - } - return ['Neither', 'Bulky', 'Heavy', 'Both'][i]; -} -``` - ```ts function categorizeBox(length: number, width: number, height: number, mass: number): string { const v = length * width * height; @@ -238,28 +254,6 @@ function categorizeBox(length: number, width: number, height: number, mass: numb } ``` -### **Rust** - -```rust -impl Solution { - pub fn categorize_box(length: i32, width: i32, height: i32, mass: i32) -> String { - let v = (length as i64) * (width as i64) * (height as i64); - let mut i = 0; - - if length >= 10000 || width >= 10000 || height >= 10000 || v >= 1000000000 { - i |= 1; - } - - if mass >= 100 { - i |= 2; - } - - let d = vec!["Neither", "Bulky", "Heavy", "Both"]; - d[i].to_string() - } -} -``` - ```rust impl Solution { pub fn categorize_box(length: i32, width: i32, height: i32, mass: i32) -> String { @@ -287,10 +281,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2526.Find Consecutive Integers from a Data Stream/README.md b/solution/2500-2599/2526.Find Consecutive Integers from a Data Stream/README.md index 64846b89f256a..d4434ca6efc9d 100644 --- a/solution/2500-2599/2526.Find Consecutive Integers from a Data Stream/README.md +++ b/solution/2500-2599/2526.Find Consecutive Integers from a Data Stream/README.md @@ -48,9 +48,7 @@ dataStream.consec(3); // 最后 k 个整数分别是 [4,4,3] 。 ## 解法 - - -**方法一:计数** +### 方法一:计数 维护一个计数器 $cnt$,记录当前连续整数为 `value` 的个数。 @@ -60,10 +58,6 @@ dataStream.consec(3); // 最后 k 个整数分别是 [4,4,3] 。 -### **Python3** - - - ```python class DataStream: def __init__(self, value: int, k: int): @@ -80,10 +74,6 @@ class DataStream: # param_1 = obj.consec(num) ``` -### **Java** - - - ```java class DataStream { private int cnt; @@ -108,8 +98,6 @@ class DataStream { */ ``` -### **C++** - ```cpp class DataStream { public: @@ -135,8 +123,6 @@ private: */ ``` -### **Go** - ```go type DataStream struct { val, k, cnt int @@ -162,8 +148,6 @@ func (this *DataStream) Consec(num int) bool { */ ``` -### **TypeScript** - ```ts class DataStream { private val: number; @@ -189,10 +173,6 @@ class DataStream { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2526.Find Consecutive Integers from a Data Stream/README_EN.md b/solution/2500-2599/2526.Find Consecutive Integers from a Data Stream/README_EN.md index 9256f18c6fa08..42b0c519746f2 100644 --- a/solution/2500-2599/2526.Find Consecutive Integers from a Data Stream/README_EN.md +++ b/solution/2500-2599/2526.Find Consecutive Integers from a Data Stream/README_EN.md @@ -44,9 +44,9 @@ dataStream.consec(3); // The last k integers parsed in the stream are [4,4,3]. ## Solutions - +### Solution 1 -### **Python3** + ```python class DataStream: @@ -64,8 +64,6 @@ class DataStream: # param_1 = obj.consec(num) ``` -### **Java** - ```java class DataStream { private int cnt; @@ -90,8 +88,6 @@ class DataStream { */ ``` -### **C++** - ```cpp class DataStream { public: @@ -117,8 +113,6 @@ private: */ ``` -### **Go** - ```go type DataStream struct { val, k, cnt int @@ -144,8 +138,6 @@ func (this *DataStream) Consec(num int) bool { */ ``` -### **TypeScript** - ```ts class DataStream { private val: number; @@ -171,10 +163,6 @@ class DataStream { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2527.Find Xor-Beauty of Array/README.md b/solution/2500-2599/2527.Find Xor-Beauty of Array/README.md index 6481c2dc75d08..2fe4adf182dab 100644 --- a/solution/2500-2599/2527.Find Xor-Beauty of Array/README.md +++ b/solution/2500-2599/2527.Find Xor-Beauty of Array/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 我们首先考虑 $i$ 与 $j$ 不相等的情况,此时 $(nums[i] | nums[j]) \& nums[k]$ 与 $(nums[j] | nums[i]) \& nums[k]$ 的结果是相同的,两者的异或结果为 $0$。 @@ -73,20 +71,12 @@ -### **Python3** - - - ```python class Solution: def xorBeauty(self, nums: List[int]) -> int: return reduce(xor, nums) ``` -### **Java** - - - ```java class Solution { public int xorBeauty(int[] nums) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func xorBeauty(nums []int) (ans int) { for _, x := range nums { @@ -125,18 +111,12 @@ func xorBeauty(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function xorBeauty(nums: number[]): number { return nums.reduce((acc, cur) => acc ^ cur, 0); } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2527.Find Xor-Beauty of Array/README_EN.md b/solution/2500-2599/2527.Find Xor-Beauty of Array/README_EN.md index 46be8cc14ed62..846aea6f99084 100644 --- a/solution/2500-2599/2527.Find Xor-Beauty of Array/README_EN.md +++ b/solution/2500-2599/2527.Find Xor-Beauty of Array/README_EN.md @@ -55,9 +55,9 @@ Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return reduce(xor, nums) ``` -### **Java** - ```java class Solution { public int xorBeauty(int[] nums) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +90,6 @@ public: }; ``` -### **Go** - ```go func xorBeauty(nums []int) (ans int) { for _, x := range nums { @@ -105,18 +99,12 @@ func xorBeauty(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function xorBeauty(nums: number[]): number { return nums.reduce((acc, cur) => acc ^ cur, 0); } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2528.Maximize the Minimum Powered City/README.md b/solution/2500-2599/2528.Maximize the Minimum Powered City/README.md index 629c3dcb296ae..9064f11b1ed51 100644 --- a/solution/2500-2599/2528.Maximize the Minimum Powered City/README.md +++ b/solution/2500-2599/2528.Maximize the Minimum Powered City/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:二分查找 + 差分数组 + 贪心** +### 方法一:二分查找 + 差分数组 + 贪心 根据题目描述,最小供电站数目随着 $k$ 值的增大而增大,因此,我们可以用二分查找,找到一个最大的最小供电站数目,并且需要额外建造的供电站不超过 $k$ 座。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def maxPower(self, stations: List[int], r: int, k: int) -> int: @@ -123,10 +117,6 @@ class Solution: return left ``` -### **Java** - - - ```java class Solution { private long[] s; @@ -181,8 +171,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -234,8 +222,6 @@ public: }; ``` -### **Go** - ```go func maxPower(stations []int, r int, k int) int64 { n := len(stations) @@ -283,10 +269,6 @@ func maxPower(stations []int, r int, k int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2528.Maximize the Minimum Powered City/README_EN.md b/solution/2500-2599/2528.Maximize the Minimum Powered City/README_EN.md index 06ef2b7963490..c7dc58bf7e515 100644 --- a/solution/2500-2599/2528.Maximize the Minimum Powered City/README_EN.md +++ b/solution/2500-2599/2528.Maximize the Minimum Powered City/README_EN.md @@ -60,9 +60,9 @@ It can be proved that we cannot make the minimum power of a city greater than 4. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -101,8 +101,6 @@ class Solution: return left ``` -### **Java** - ```java class Solution { private long[] s; @@ -157,8 +155,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -210,8 +206,6 @@ public: }; ``` -### **Go** - ```go func maxPower(stations []int, r int, k int) int64 { n := len(stations) @@ -259,10 +253,6 @@ func maxPower(stations []int, r int, k int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/README.md b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/README.md index e102ac7807008..39049a813c09f 100644 --- a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/README.md +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/README.md @@ -56,26 +56,14 @@ ## 解法 - - -**方法一:遍历** +### 方法一:遍历 遍历数组,统计正整数和负整数的个数 $a$ 和 $b$,返回 $a$ 和 $b$ 中的较大值即可。 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组长度。 -**方法二:二分查找** - -由于数组是按非递减顺序排列的,因此可以使用二分查找找到第一个大于等于 $1$ 的元素的下标 $i$ 以及第一个大于等于 $0$ 的元素的下标 $j$,那么正整数的个数 $a = n - i$,负整数的个数 $b = j$,返回 $a$ 和 $b$ 中的较大值即可。 - -时间复杂度 $O(\log n)$,空间复杂度 $O(1)$。其中 $n$ 为数组长度。 - -### **Python3** - - - ```python class Solution: def maximumCount(self, nums: List[int]) -> int: @@ -84,18 +72,6 @@ class Solution: return max(a, b) ``` -```python -class Solution: - def maximumCount(self, nums: List[int]) -> int: - a = len(nums) - bisect_left(nums, 1) - b = bisect_left(nums, 0) - return max(a, b) -``` - -### **Java** - - - ```java class Solution { public int maximumCount(int[] nums) { @@ -113,31 +89,6 @@ class Solution { } ``` -```java -class Solution { - public int maximumCount(int[] nums) { - int a = nums.length - search(nums, 1); - int b = search(nums, 0); - return Math.max(a, b); - } - - private int search(int[] nums, int x) { - int left = 0, right = nums.length; - while (left < right) { - int mid = (left + right) >> 1; - if (nums[mid] >= x) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -156,19 +107,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maximumCount(vector& nums) { - int a = nums.end() - lower_bound(nums.begin(), nums.end(), 1); - int b = lower_bound(nums.begin(), nums.end(), 0) - nums.begin(); - return max(a, b); - } -}; -``` - -### **Go** - ```go func maximumCount(nums []int) int { a, b := 0, 0 @@ -184,16 +122,6 @@ func maximumCount(nums []int) int { } ``` -```go -func maximumCount(nums []int) int { - a := len(nums) - sort.SearchInts(nums, 1) - b := sort.SearchInts(nums, 0) - return max(a, b) -} -``` - -### **TypeScript** - ```ts function maximumCount(nums: number[]): number { const count = [0, 0]; @@ -208,6 +136,98 @@ function maximumCount(nums: number[]): number { } ``` +```rust +impl Solution { + pub fn maximum_count(nums: Vec) -> i32 { + let mut count = [0, 0]; + for &num in nums.iter() { + if num < 0 { + count[0] += 1; + } else if num > 0 { + count[1] += 1; + } + } + *count.iter().max().unwrap() + } +} +``` + +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) + +int maximumCount(int* nums, int numsSize) { + int count[2] = {0}; + for (int i = 0; i < numsSize; i++) { + if (nums[i] < 0) { + count[0]++; + } else if (nums[i] > 0) { + count[1]++; + } + } + return max(count[0], count[1]); +} +``` + + + +### 方法二:二分查找 + +由于数组是按非递减顺序排列的,因此可以使用二分查找找到第一个大于等于 $1$ 的元素的下标 $i$ 以及第一个大于等于 $0$ 的元素的下标 $j$,那么正整数的个数 $a = n - i$,负整数的个数 $b = j$,返回 $a$ 和 $b$ 中的较大值即可。 + +时间复杂度 $O(\log n)$,空间复杂度 $O(1)$。其中 $n$ 为数组长度。 + + + +```python +class Solution: + def maximumCount(self, nums: List[int]) -> int: + a = len(nums) - bisect_left(nums, 1) + b = bisect_left(nums, 0) + return max(a, b) +``` + +```java +class Solution { + public int maximumCount(int[] nums) { + int a = nums.length - search(nums, 1); + int b = search(nums, 0); + return Math.max(a, b); + } + + private int search(int[] nums, int x) { + int left = 0, right = nums.length; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +```cpp +class Solution { +public: + int maximumCount(vector& nums) { + int a = nums.end() - lower_bound(nums.begin(), nums.end(), 1); + int b = lower_bound(nums.begin(), nums.end(), 0) - nums.begin(); + return max(a, b); + } +}; +``` + +```go +func maximumCount(nums []int) int { + a := len(nums) - sort.SearchInts(nums, 1) + b := sort.SearchInts(nums, 0) + return max(a, b) +} +``` + ```ts function maximumCount(nums: number[]): number { const search = (target: number) => { @@ -230,24 +250,6 @@ function maximumCount(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn maximum_count(nums: Vec) -> i32 { - let mut count = [0, 0]; - for &num in nums.iter() { - if num < 0 { - count[0] += 1; - } else if num > 0 { - count[1] += 1; - } - } - *count.iter().max().unwrap() - } -} -``` - ```rust impl Solution { fn search(nums: &Vec, target: i32) -> usize { @@ -273,43 +275,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn maximum_count(nums: Vec) -> i32 { - let mut a = 0; - let mut b = 0; - - for n in nums { - if n > 0 { - a += 1; - } else if n < 0 { - b += 1; - } - } - - std::cmp::max(a, b) - } -} -``` - -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int maximumCount(int* nums, int numsSize) { - int count[2] = {0}; - for (int i = 0; i < numsSize; i++) { - if (nums[i] < 0) { - count[0]++; - } else if (nums[i] > 0) { - count[1]++; - } - } - return max(count[0], count[1]); -} -``` - ```c #define max(a, b) (((a) > (b)) ? (a) : (b)) @@ -334,10 +299,31 @@ int maximumCount(int* nums, int numsSize) { } ``` -### **...** + + +### 方法三 -``` + + +```rust +impl Solution { + pub fn maximum_count(nums: Vec) -> i32 { + let mut a = 0; + let mut b = 0; + + for n in nums { + if n > 0 { + a += 1; + } else if n < 0 { + b += 1; + } + } + std::cmp::max(a, b) + } +} ``` + + diff --git a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/README_EN.md b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/README_EN.md index f913dd7225da5..48c5e59924d41 100644 --- a/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/README_EN.md +++ b/solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/README_EN.md @@ -51,9 +51,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,16 +63,6 @@ class Solution: return max(a, b) ``` -```python -class Solution: - def maximumCount(self, nums: List[int]) -> int: - a = len(nums) - bisect_left(nums, 1) - b = bisect_left(nums, 0) - return max(a, b) -``` - -### **Java** - ```java class Solution { public int maximumCount(int[] nums) { @@ -90,31 +80,6 @@ class Solution { } ``` -```java -class Solution { - public int maximumCount(int[] nums) { - int a = nums.length - search(nums, 1); - int b = search(nums, 0); - return Math.max(a, b); - } - - private int search(int[] nums, int x) { - int left = 0, right = nums.length; - while (left < right) { - int mid = (left + right) >> 1; - if (nums[mid] >= x) { - right = mid; - } else { - left = mid + 1; - } - } - return left; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -133,19 +98,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maximumCount(vector& nums) { - int a = nums.end() - lower_bound(nums.begin(), nums.end(), 1); - int b = lower_bound(nums.begin(), nums.end(), 0) - nums.begin(); - return max(a, b); - } -}; -``` - -### **Go** - ```go func maximumCount(nums []int) int { a, b := 0, 0 @@ -161,16 +113,6 @@ func maximumCount(nums []int) int { } ``` -```go -func maximumCount(nums []int) int { - a := len(nums) - sort.SearchInts(nums, 1) - b := sort.SearchInts(nums, 0) - return max(a, b) -} -``` - -### **TypeScript** - ```ts function maximumCount(nums: number[]): number { const count = [0, 0]; @@ -185,6 +127,94 @@ function maximumCount(nums: number[]): number { } ``` +```rust +impl Solution { + pub fn maximum_count(nums: Vec) -> i32 { + let mut count = [0, 0]; + for &num in nums.iter() { + if num < 0 { + count[0] += 1; + } else if num > 0 { + count[1] += 1; + } + } + *count.iter().max().unwrap() + } +} +``` + +```c +#define max(a, b) (((a) > (b)) ? (a) : (b)) + +int maximumCount(int* nums, int numsSize) { + int count[2] = {0}; + for (int i = 0; i < numsSize; i++) { + if (nums[i] < 0) { + count[0]++; + } else if (nums[i] > 0) { + count[1]++; + } + } + return max(count[0], count[1]); +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def maximumCount(self, nums: List[int]) -> int: + a = len(nums) - bisect_left(nums, 1) + b = bisect_left(nums, 0) + return max(a, b) +``` + +```java +class Solution { + public int maximumCount(int[] nums) { + int a = nums.length - search(nums, 1); + int b = search(nums, 0); + return Math.max(a, b); + } + + private int search(int[] nums, int x) { + int left = 0, right = nums.length; + while (left < right) { + int mid = (left + right) >> 1; + if (nums[mid] >= x) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +} +``` + +```cpp +class Solution { +public: + int maximumCount(vector& nums) { + int a = nums.end() - lower_bound(nums.begin(), nums.end(), 1); + int b = lower_bound(nums.begin(), nums.end(), 0) - nums.begin(); + return max(a, b); + } +}; +``` + +```go +func maximumCount(nums []int) int { + a := len(nums) - sort.SearchInts(nums, 1) + b := sort.SearchInts(nums, 0) + return max(a, b) +} +``` + ```ts function maximumCount(nums: number[]): number { const search = (target: number) => { @@ -207,24 +237,6 @@ function maximumCount(nums: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn maximum_count(nums: Vec) -> i32 { - let mut count = [0, 0]; - for &num in nums.iter() { - if num < 0 { - count[0] += 1; - } else if num > 0 { - count[1] += 1; - } - } - *count.iter().max().unwrap() - } -} -``` - ```rust impl Solution { fn search(nums: &Vec, target: i32) -> usize { @@ -250,43 +262,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn maximum_count(nums: Vec) -> i32 { - let mut a = 0; - let mut b = 0; - - for n in nums { - if n > 0 { - a += 1; - } else if n < 0 { - b += 1; - } - } - - std::cmp::max(a, b) - } -} -``` - -### **C** - -```c -#define max(a, b) (((a) > (b)) ? (a) : (b)) - -int maximumCount(int* nums, int numsSize) { - int count[2] = {0}; - for (int i = 0; i < numsSize; i++) { - if (nums[i] < 0) { - count[0]++; - } else if (nums[i] > 0) { - count[1]++; - } - } - return max(count[0], count[1]); -} -``` - ```c #define max(a, b) (((a) > (b)) ? (a) : (b)) @@ -311,10 +286,31 @@ int maximumCount(int* nums, int numsSize) { } ``` -### **...** + -``` +### Solution 3 + + +```rust +impl Solution { + pub fn maximum_count(nums: Vec) -> i32 { + let mut a = 0; + let mut b = 0; + + for n in nums { + if n > 0 { + a += 1; + } else if n < 0 { + b += 1; + } + } + + std::cmp::max(a, b) + } +} ``` + + diff --git a/solution/2500-2599/2530.Maximal Score After Applying K Operations/README.md b/solution/2500-2599/2530.Maximal Score After Applying K Operations/README.md index 2cdaa9c040a03..8365762f4cca6 100644 --- a/solution/2500-2599/2530.Maximal Score After Applying K Operations/README.md +++ b/solution/2500-2599/2530.Maximal Score After Applying K Operations/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:优先队列(大根堆)** +### 方法一:优先队列(大根堆) 要使得分数最大化,我们需要在每一步操作中,选择元素值最大的元素进行操作。因此,我们可以使用优先队列(大根堆)来维护当前元素值最大的元素。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def maxKelements(self, nums: List[int], k: int) -> int: @@ -82,22 +76,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxKelements(self, nums: List[int], k: int) -> int: - for i, v in enumerate(nums): - nums[i] = -v - heapify(nums) - ans = 0 - for _ in range(k): - ans -= heapreplace(nums, -ceil(-nums[0] / 3)) - return ans -``` - -### **Java** - - - ```java class Solution { public long maxKelements(int[] nums, int k) { @@ -116,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,26 +111,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long maxKelements(vector& nums, int k) { - make_heap(nums.begin(), nums.end()); - long long ans = 0; - while (k--) { - int v = nums[0]; - ans += v; - pop_heap(nums.begin(), nums.end()); - nums.back() = (v + 2) / 3; - push_heap(nums.begin(), nums.end()); - } - return ans; - } -}; -``` - -### **Go** - ```go func maxKelements(nums []int, k int) (ans int64) { h := &hp{nums} @@ -181,27 +137,21 @@ func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) } ``` -```go -func maxKelements(nums []int, k int) (ans int64) { - h := hp{nums} - heap.Init(&h) - for ; k > 0; k-- { - ans += int64(h.IntSlice[0]) - h.IntSlice[0] = (h.IntSlice[0] + 2) / 3 - heap.Fix(&h, 0) - } - return +```ts +function maxKelements(nums: number[], k: number): number { + const pq = new MaxPriorityQueue(); + nums.forEach(num => pq.enqueue(num)); + let ans = 0; + while (k > 0) { + const v = pq.dequeue()!.element; + ans += v; + pq.enqueue(Math.floor((v + 2) / 3)); + k--; + } + return ans; } - -type hp struct{ sort.IntSlice } - -func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } -func (hp) Push(any) {} -func (hp) Pop() (_ any) { return } ``` -### **Rust** - ```rust use std::collections::BinaryHeap; @@ -222,27 +172,61 @@ impl Solution { } ``` -### **TypeScript** + -```ts -function maxKelements(nums: number[], k: number): number { - const pq = new MaxPriorityQueue(); - nums.forEach(num => pq.enqueue(num)); - let ans = 0; - while (k > 0) { - const v = pq.dequeue()!.element; - ans += v; - pq.enqueue(Math.floor((v + 2) / 3)); - k--; +### 方法二 + + + +```python +class Solution: + def maxKelements(self, nums: List[int], k: int) -> int: + for i, v in enumerate(nums): + nums[i] = -v + heapify(nums) + ans = 0 + for _ in range(k): + ans -= heapreplace(nums, -ceil(-nums[0] / 3)) + return ans +``` + +```cpp +class Solution { +public: + long long maxKelements(vector& nums, int k) { + make_heap(nums.begin(), nums.end()); + long long ans = 0; + while (k--) { + int v = nums[0]; + ans += v; + pop_heap(nums.begin(), nums.end()); + nums.back() = (v + 2) / 3; + push_heap(nums.begin(), nums.end()); + } + return ans; } - return ans; -} +}; ``` -### **...** +```go +func maxKelements(nums []int, k int) (ans int64) { + h := hp{nums} + heap.Init(&h) + for ; k > 0; k-- { + ans += int64(h.IntSlice[0]) + h.IntSlice[0] = (h.IntSlice[0] + 2) / 3 + heap.Fix(&h, 0) + } + return +} -``` +type hp struct{ sort.IntSlice } +func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } +func (hp) Push(any) {} +func (hp) Pop() (_ any) { return } ``` + + diff --git a/solution/2500-2599/2530.Maximal Score After Applying K Operations/README_EN.md b/solution/2500-2599/2530.Maximal Score After Applying K Operations/README_EN.md index 178f39e9c2a3c..b2948faa7f227 100644 --- a/solution/2500-2599/2530.Maximal Score After Applying K Operations/README_EN.md +++ b/solution/2500-2599/2530.Maximal Score After Applying K Operations/README_EN.md @@ -49,7 +49,7 @@ The final score is 10 + 4 + 3 = 17. ## Solutions -**Solution 1: Priority Queue (Max Heap)** +### Solution 1: Priority Queue (Max Heap) To maximize the sum of scores, we need to select the element with the maximum value at each step. Therefore, we can use a priority queue (max heap) to maintain the element with the maximum value. @@ -59,8 +59,6 @@ The time complexity is $O(n + k \times \log n)$, and the space complexity is $O( -### **Python3** - ```python class Solution: def maxKelements(self, nums: List[int], k: int) -> int: @@ -74,20 +72,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxKelements(self, nums: List[int], k: int) -> int: - for i, v in enumerate(nums): - nums[i] = -v - heapify(nums) - ans = 0 - for _ in range(k): - ans -= heapreplace(nums, -ceil(-nums[0] / 3)) - return ans -``` - -### **Java** - ```java class Solution { public long maxKelements(int[] nums, int k) { @@ -106,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,26 +107,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long maxKelements(vector& nums, int k) { - make_heap(nums.begin(), nums.end()); - long long ans = 0; - while (k--) { - int v = nums[0]; - ans += v; - pop_heap(nums.begin(), nums.end()); - nums.back() = (v + 2) / 3; - push_heap(nums.begin(), nums.end()); - } - return ans; - } -}; -``` - -### **Go** - ```go func maxKelements(nums []int, k int) (ans int64) { h := &hp{nums} @@ -171,27 +133,21 @@ func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) } ``` -```go -func maxKelements(nums []int, k int) (ans int64) { - h := hp{nums} - heap.Init(&h) - for ; k > 0; k-- { - ans += int64(h.IntSlice[0]) - h.IntSlice[0] = (h.IntSlice[0] + 2) / 3 - heap.Fix(&h, 0) - } - return +```ts +function maxKelements(nums: number[], k: number): number { + const pq = new MaxPriorityQueue(); + nums.forEach(num => pq.enqueue(num)); + let ans = 0; + while (k > 0) { + const v = pq.dequeue()!.element; + ans += v; + pq.enqueue(Math.floor((v + 2) / 3)); + k--; + } + return ans; } - -type hp struct{ sort.IntSlice } - -func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } -func (hp) Push(any) {} -func (hp) Pop() (_ any) { return } ``` -### **Rust** - ```rust use std::collections::BinaryHeap; @@ -212,27 +168,61 @@ impl Solution { } ``` -### **TypeScript** + -```ts -function maxKelements(nums: number[], k: number): number { - const pq = new MaxPriorityQueue(); - nums.forEach(num => pq.enqueue(num)); - let ans = 0; - while (k > 0) { - const v = pq.dequeue()!.element; - ans += v; - pq.enqueue(Math.floor((v + 2) / 3)); - k--; +### Solution 2 + + + +```python +class Solution: + def maxKelements(self, nums: List[int], k: int) -> int: + for i, v in enumerate(nums): + nums[i] = -v + heapify(nums) + ans = 0 + for _ in range(k): + ans -= heapreplace(nums, -ceil(-nums[0] / 3)) + return ans +``` + +```cpp +class Solution { +public: + long long maxKelements(vector& nums, int k) { + make_heap(nums.begin(), nums.end()); + long long ans = 0; + while (k--) { + int v = nums[0]; + ans += v; + pop_heap(nums.begin(), nums.end()); + nums.back() = (v + 2) / 3; + push_heap(nums.begin(), nums.end()); + } + return ans; } - return ans; -} +}; ``` -### **...** +```go +func maxKelements(nums []int, k int) (ans int64) { + h := hp{nums} + heap.Init(&h) + for ; k > 0; k-- { + ans += int64(h.IntSlice[0]) + h.IntSlice[0] = (h.IntSlice[0] + 2) / 3 + heap.Fix(&h, 0) + } + return +} -``` +type hp struct{ sort.IntSlice } +func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] } +func (hp) Push(any) {} +func (hp) Pop() (_ any) { return } ``` + + diff --git a/solution/2500-2599/2531.Make Number of Distinct Characters Equal/README.md b/solution/2500-2599/2531.Make Number of Distinct Characters Equal/README.md index 26102995a9cb9..e4760ef803f38 100644 --- a/solution/2500-2599/2531.Make Number of Distinct Characters Equal/README.md +++ b/solution/2500-2599/2531.Make Number of Distinct Characters Equal/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:计数 + 枚举** +### 方法一:计数 + 枚举 我们先用两个长度为 $26$ 的数组分别统计字符串 $word1$ 和 $word2$ 中每个字母的出现次数,记为 $cnt1$ 和 $cnt2$。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def isItPossible(self, word1: str, word2: str) -> bool: @@ -89,10 +83,6 @@ class Solution: return False ``` -### **Java** - - - ```java class Solution { public boolean isItPossible(String word1, String word2) { @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -180,8 +168,6 @@ public: }; ``` -### **Go** - ```go func isItPossible(word1 string, word2 string) bool { cnt1 := [26]int{} @@ -218,10 +204,6 @@ func isItPossible(word1 string, word2 string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2531.Make Number of Distinct Characters Equal/README_EN.md b/solution/2500-2599/2531.Make Number of Distinct Characters Equal/README_EN.md index 1563fada8e41a..691d2b0eac6f4 100644 --- a/solution/2500-2599/2531.Make Number of Distinct Characters Equal/README_EN.md +++ b/solution/2500-2599/2531.Make Number of Distinct Characters Equal/README_EN.md @@ -45,9 +45,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return False ``` -### **Java** - ```java class Solution { public boolean isItPossible(String word1, String word2) { @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +155,6 @@ public: }; ``` -### **Go** - ```go func isItPossible(word1 string, word2 string) bool { cnt1 := [26]int{} @@ -197,10 +191,6 @@ func isItPossible(word1 string, word2 string) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2532.Time to Cross a Bridge/README.md b/solution/2500-2599/2532.Time to Cross a Bridge/README.md index 9d90fa4e182f7..45f7182e613ec 100644 --- a/solution/2500-2599/2532.Time to Cross a Bridge/README.md +++ b/solution/2500-2599/2532.Time to Cross a Bridge/README.md @@ -83,9 +83,7 @@ ## 解法 - - -**方法一:优先队列(大小根堆) + 模拟** +### 方法一:优先队列(大小根堆) + 模拟 我们先将工人按照效率从高到底排序,这样,下标越大的工人,效率越低。 @@ -112,10 +110,6 @@ -### **Python3** - - - ```python class Solution: def findCrossingTime(self, n: int, k: int, time: List[List[int]]) -> int: @@ -161,10 +155,6 @@ class Solution: heappush(work_in_right, (cur + time[i][1], i)) ``` -### **Java** - - - ```java class Solution { public int findCrossingTime(int n, int k, int[][] time) { @@ -231,8 +221,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -301,8 +289,6 @@ public: }; ``` -### **Go** - ```go func findCrossingTime(n int, k int, time [][]int) int { sort.SliceStable(time, func(i, j int) bool { return time[i][0]+time[i][2] < time[j][0]+time[j][2] }) @@ -377,10 +363,6 @@ func (h *hp2) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp2) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2532.Time to Cross a Bridge/README_EN.md b/solution/2500-2599/2532.Time to Cross a Bridge/README_EN.md index ae0654300db95..eaf1de96ed1e3 100644 --- a/solution/2500-2599/2532.Time to Cross a Bridge/README_EN.md +++ b/solution/2500-2599/2532.Time to Cross a Bridge/README_EN.md @@ -79,9 +79,9 @@ The whole process ends after 58 minutes. We return 50 because the problem asks f ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -128,8 +128,6 @@ class Solution: heappush(work_in_right, (cur + time[i][1], i)) ``` -### **Java** - ```java class Solution { public int findCrossingTime(int n, int k, int[][] time) { @@ -196,8 +194,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -266,8 +262,6 @@ public: }; ``` -### **Go** - ```go func findCrossingTime(n int, k int, time [][]int) int { sort.SliceStable(time, func(i, j int) bool { return time[i][0]+time[i][2] < time[j][0]+time[j][2] }) @@ -342,10 +336,6 @@ func (h *hp2) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp2) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2533.Number of Good Binary Strings/README.md b/solution/2500-2599/2533.Number of Good Binary Strings/README.md index a4ad99276793e..3e7a2d107e119 100644 --- a/solution/2500-2599/2533.Number of Good Binary Strings/README.md +++ b/solution/2500-2599/2533.Number of Good Binary Strings/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示长度为 $i$ 的字符串中满足条件的个数。状态转移方程为: @@ -77,10 +75,6 @@ $$ -### **Python3** - - - ```python class Solution: def goodBinaryStrings( @@ -97,10 +91,6 @@ class Solution: return sum(f[minLength:]) % mod ``` -### **Java** - - - ```java class Solution { public int goodBinaryStrings(int minLength, int maxLength, int oneGroup, int zeroGroup) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go func goodBinaryStrings(minLength int, maxLength int, oneGroup int, zeroGroup int) (ans int) { const mod int = 1e9 + 7 @@ -174,8 +160,6 @@ func goodBinaryStrings(minLength int, maxLength int, oneGroup int, zeroGroup int } ``` -### **TypeScript** - ```ts function goodBinaryStrings( minLength: number, @@ -199,10 +183,6 @@ function goodBinaryStrings( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2533.Number of Good Binary Strings/README_EN.md b/solution/2500-2599/2533.Number of Good Binary Strings/README_EN.md index adf3fecc93235..cd69bc41bd130 100644 --- a/solution/2500-2599/2533.Number of Good Binary Strings/README_EN.md +++ b/solution/2500-2599/2533.Number of Good Binary Strings/README_EN.md @@ -55,7 +55,7 @@ It can be proven that there is only 1 good string satisfying all conditions. ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i]$ as the number of strings of length $i$ that meet the condition. The state transition equation is: @@ -72,8 +72,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n=maxL -### **Python3** - ```python class Solution: def goodBinaryStrings( @@ -90,8 +88,6 @@ class Solution: return sum(f[minLength:]) % mod ``` -### **Java** - ```java class Solution { public int goodBinaryStrings(int minLength, int maxLength, int oneGroup, int zeroGroup) { @@ -115,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go func goodBinaryStrings(minLength int, maxLength int, oneGroup int, zeroGroup int) (ans int) { const mod int = 1e9 + 7 @@ -165,8 +157,6 @@ func goodBinaryStrings(minLength int, maxLength int, oneGroup int, zeroGroup int } ``` -### **TypeScript** - ```ts function goodBinaryStrings( minLength: number, @@ -190,10 +180,6 @@ function goodBinaryStrings( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2534.Time Taken to Cross the Door/README.md b/solution/2500-2599/2534.Time Taken to Cross the Door/README.md index f270eb775df32..4855e78ae6a11 100644 --- a/solution/2500-2599/2534.Time Taken to Cross the Door/README.md +++ b/solution/2500-2599/2534.Time Taken to Cross the Door/README.md @@ -67,42 +67,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2500-2599/2534.Time Taken to Cross the Door/README_EN.md b/solution/2500-2599/2534.Time Taken to Cross the Door/README_EN.md index 24748290d6e37..f5790933b16c8 100644 --- a/solution/2500-2599/2534.Time Taken to Cross the Door/README_EN.md +++ b/solution/2500-2599/2534.Time Taken to Cross the Door/README_EN.md @@ -64,36 +64,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/README.md b/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/README.md index 5c2efc512539f..63ee1741664d0 100644 --- a/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/README.md +++ b/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/README.md @@ -52,9 +52,7 @@ nums 的数字和是 1 + 2 + 3 + 4 = 10 。 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们遍历数组 $nums$,计算元素和 $a$ 与数字和 $b$,最后返回 $|a - b|$ 即可。 @@ -62,10 +60,6 @@ nums 的数字和是 1 + 2 + 3 + 4 = 10 。 -### **Python3** - - - ```python class Solution: def differenceOfSum(self, nums: List[int]) -> int: @@ -77,10 +71,6 @@ class Solution: return abs(a - b) ``` -### **Java** - - - ```java class Solution { public int differenceOfSum(int[] nums) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func differenceOfSum(nums []int) int { a, b := 0, 0 @@ -136,8 +122,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function differenceOfSum(nums: number[]): number { return nums.reduce((r, v) => { @@ -151,8 +135,6 @@ function differenceOfSum(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn difference_of_sum(nums: Vec) -> i32 { @@ -170,6 +152,26 @@ impl Solution { } ``` +```c +int differenceOfSum(int* nums, int numsSize) { + int ans = 0; + for (int i = 0; i < numsSize; i++) { + ans += nums[i]; + while (nums[i]) { + ans -= nums[i] % 10; + nums[i] /= 10; + } + } + return ans; +} +``` + + + +### 方法二 + + + ```rust impl Solution { pub fn difference_of_sum(nums: Vec) -> i32 { @@ -189,26 +191,6 @@ impl Solution { } ``` -### **C** - -```c -int differenceOfSum(int* nums, int numsSize) { - int ans = 0; - for (int i = 0; i < numsSize; i++) { - ans += nums[i]; - while (nums[i]) { - ans -= nums[i] % 10; - nums[i] /= 10; - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/README_EN.md b/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/README_EN.md index 4df01ac3e2a11..8efad3eb52bf1 100644 --- a/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/README_EN.md +++ b/solution/2500-2599/2535.Difference Between Element Sum and Digit Sum of an Array/README_EN.md @@ -48,7 +48,7 @@ The absolute difference between the element sum and digit sum is |10 - 10| = 0. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We traverse the array $nums$, calculate the sum of elements $a$ and the sum of digits $b$, and finally return $|a - b|$. @@ -56,8 +56,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def differenceOfSum(self, nums: List[int]) -> int: @@ -69,8 +67,6 @@ class Solution: return abs(a - b) ``` -### **Java** - ```java class Solution { public int differenceOfSum(int[] nums) { @@ -86,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +98,6 @@ public: }; ``` -### **Go** - ```go func differenceOfSum(nums []int) int { a, b := 0, 0 @@ -126,8 +118,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function differenceOfSum(nums: number[]): number { return nums.reduce((r, v) => { @@ -141,8 +131,6 @@ function differenceOfSum(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn difference_of_sum(nums: Vec) -> i32 { @@ -160,6 +148,26 @@ impl Solution { } ``` +```c +int differenceOfSum(int* nums, int numsSize) { + int ans = 0; + for (int i = 0; i < numsSize; i++) { + ans += nums[i]; + while (nums[i]) { + ans -= nums[i] % 10; + nums[i] /= 10; + } + } + return ans; +} +``` + + + +### Solution 2 + + + ```rust impl Solution { pub fn difference_of_sum(nums: Vec) -> i32 { @@ -179,26 +187,6 @@ impl Solution { } ``` -### **C** - -```c -int differenceOfSum(int* nums, int numsSize) { - int ans = 0; - for (int i = 0; i < numsSize; i++) { - ans += nums[i]; - while (nums[i]) { - ans -= nums[i] % 10; - nums[i] /= 10; - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2536.Increment Submatrices by One/README.md b/solution/2500-2599/2536.Increment Submatrices by One/README.md index 10b4aec98414a..1477ec8d65136 100644 --- a/solution/2500-2599/2536.Increment Submatrices by One/README.md +++ b/solution/2500-2599/2536.Increment Submatrices by One/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:二维差分** +### 方法一:二维差分 二维差分模板题。 @@ -79,10 +77,6 @@ for i in range(1, n + 1): -### **Python3** - - - ```python class Solution: def rangeAddQueries(self, n: int, queries: List[List[int]]) -> List[List[int]]: @@ -107,10 +101,6 @@ class Solution: return mat ``` -### **Java** - - - ```java class Solution { public int[][] rangeAddQueries(int n, int[][] queries) { @@ -146,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -184,8 +172,6 @@ public: }; ``` -### **Go** - ```go func rangeAddQueries(n int, queries [][]int) [][]int { mat := make([][]int, n) @@ -222,10 +208,6 @@ func rangeAddQueries(n int, queries [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2536.Increment Submatrices by One/README_EN.md b/solution/2500-2599/2536.Increment Submatrices by One/README_EN.md index 8f80c36c45e98..00a4279ef0c16 100644 --- a/solution/2500-2599/2536.Increment Submatrices by One/README_EN.md +++ b/solution/2500-2599/2536.Increment Submatrices by One/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return mat ``` -### **Java** - ```java class Solution { public int[][] rangeAddQueries(int n, int[][] queries) { @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +145,6 @@ public: }; ``` -### **Go** - ```go func rangeAddQueries(n int, queries [][]int) [][]int { mat := make([][]int, n) @@ -187,10 +181,6 @@ func rangeAddQueries(n int, queries [][]int) [][]int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2537.Count the Number of Good Subarrays/README.md b/solution/2500-2599/2537.Count the Number of Good Subarrays/README.md index 25f187df8c1c8..00c82d825d119 100644 --- a/solution/2500-2599/2537.Count the Number of Good Subarrays/README.md +++ b/solution/2500-2599/2537.Count the Number of Good Subarrays/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:哈希表 + 双指针** +### 方法一:哈希表 + 双指针 如果一个子数组中包含 $k$ 对相同的元素,那么包含这个子数组的数组一定至少包含 $k$ 对相同的元素。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def countGood(self, nums: List[int], k: int) -> int: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long countGood(int[] nums, int k) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func countGood(nums []int, k int) int64 { cnt := map[int]int{} @@ -153,10 +139,6 @@ func countGood(nums []int, k int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2537.Count the Number of Good Subarrays/README_EN.md b/solution/2500-2599/2537.Count the Number of Good Subarrays/README_EN.md index 7fe0374e38416..39fab5ae87fdc 100644 --- a/solution/2500-2599/2537.Count the Number of Good Subarrays/README_EN.md +++ b/solution/2500-2599/2537.Count the Number of Good Subarrays/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Hash Table + Two Pointers** +### Solution 1: Hash Table + Two Pointers If a subarray contains $k$ pairs of identical elements, then an array that contains this subarray must contain at least $k$ pairs of identical elements. @@ -55,8 +55,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is -### **Python3** - ```python class Solution: def countGood(self, nums: List[int], k: int) -> int: @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long countGood(int[] nums, int k) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func countGood(nums []int, k int) int64 { cnt := map[int]int{} @@ -145,10 +137,6 @@ func countGood(nums []int, k int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2538.Difference Between Maximum and Minimum Price Sum/README.md b/solution/2500-2599/2538.Difference Between Maximum and Minimum Price Sum/README.md index 1716bc96f35d8..a639bff683f3b 100644 --- a/solution/2500-2599/2538.Difference Between Maximum and Minimum Price Sum/README.md +++ b/solution/2500-2599/2538.Difference Between Maximum and Minimum Price Sum/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:树形 DP** +### 方法一:树形 DP 由于每个节点价值均为正整数,因此,以节点 $root$ 作为根节点的最小的一条路径就是 $root$ 节点本身,那么价值和最大的一条路径与最小的一条路径的差值就等价于去掉路径的一个端点。 @@ -84,10 +82,6 @@ -### **Python3** - - - ```python class Solution: def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int: @@ -111,10 +105,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -150,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -183,8 +171,6 @@ public: }; ``` -### **Go** - ```go func maxOutput(n int, edges [][]int, price []int) int64 { g := make([][]int, n) @@ -214,10 +200,6 @@ func maxOutput(n int, edges [][]int, price []int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2538.Difference Between Maximum and Minimum Price Sum/README_EN.md b/solution/2500-2599/2538.Difference Between Maximum and Minimum Price Sum/README_EN.md index c860ac9da6825..1e377590b57d7 100644 --- a/solution/2500-2599/2538.Difference Between Maximum and Minimum Price Sum/README_EN.md +++ b/solution/2500-2599/2538.Difference Between Maximum and Minimum Price Sum/README_EN.md @@ -51,31 +51,10 @@ The difference between the maximum and minimum price sum is 2. It can be proved ## Solutions -**Soution 1: Tree-shaped DP** - -Since the value of each node is a positive integer, the smallest path with node $root$ as the root node is the $root$ node itself. Therefore, the difference between the path with the maximum value sum and the smallest path is equivalent to removing one endpoint of the path. - -We design a function $dfs(i, fa)$, which represents the maximum path sum in the subtree with node $i$ as the root node, with and without removing the endpoint. Here, $fa$ represents the parent node of node $i$. - -The implementation logic of the function $dfs(i, fa)$ is as follows: - -Initialize $a = price[i]$, $b = 0$, indicating that initially there is only one node, the maximum path sum without removing the endpoint is $price[i]$, and the maximum path sum with removing the endpoint is $0$. - -For each child node $j$ of node $i$, if $j \ne fa$, then recursively call the function $dfs(j, i)$. Here, it returns the maximum path sum in the subtree with node $j$ as the root node, with and without removing the endpoint, denoted as $c$ and $d$. At this time, there are two cases for the answer: - -- The maximum path sum without removing the endpoint plus the maximum path sum of the current node with removing the endpoint, that is, $a + d$; -- The maximum path sum with removing the endpoint plus the maximum path sum of the current node without removing the endpoint, that is, $b + c$. - -We update the maximum value of the answer, that is, $ans = \max(ans, a + d, b + c)$. - -Then update $a$ and $b$, that is, $a = \max(a, price[i] + c)$, $b = \max(b, price[i] + d)$, and finally return. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes. +### Solution 1 -### **Python3** - ```python class Solution: def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int: @@ -99,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -136,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +144,6 @@ public: }; ``` -### **Go** - ```go func maxOutput(n int, edges [][]int, price []int) int64 { g := make([][]int, n) @@ -200,10 +173,6 @@ func maxOutput(n int, edges [][]int, price []int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2539.Count the Number of Good Subsequences/README.md b/solution/2500-2599/2539.Count the Number of Good Subsequences/README.md index 864f20489ce7e..bce7c63292392 100644 --- a/solution/2500-2599/2539.Count the Number of Good Subsequences/README.md +++ b/solution/2500-2599/2539.Count the Number of Good Subsequences/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:枚举 + 组合计数** +### 方法一:枚举 + 组合计数 由于题目说的是子序列中字母出现的次数,因此,我们可以先用一个数组 $cnt$ 统计字符串 $s$ 中每个字母出现的次数,记最大的次数为 $mx$。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python N = 10001 MOD = 10**9 + 7 @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int N = 10001; @@ -150,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp int N = 10001; int MOD = 1e9 + 7; @@ -207,8 +195,6 @@ public: }; ``` -### **Go** - ```go const n = 1e4 + 1 const mod = 1e9 + 7 @@ -260,10 +246,6 @@ func countGoodSubsequences(s string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2539.Count the Number of Good Subsequences/README_EN.md b/solution/2500-2599/2539.Count the Number of Good Subsequences/README_EN.md index c5990258435e9..2b357bc28cd08 100644 --- a/solution/2500-2599/2539.Count the Number of Good Subsequences/README_EN.md +++ b/solution/2500-2599/2539.Count the Number of Good Subsequences/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python N = 10001 @@ -75,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int N = 10001; @@ -130,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp int N = 10001; int MOD = 1e9 + 7; @@ -187,8 +183,6 @@ public: }; ``` -### **Go** - ```go const n = 1e4 + 1 const mod = 1e9 + 7 @@ -240,10 +234,6 @@ func countGoodSubsequences(s string) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2540.Minimum Common Value/README.md b/solution/2500-2599/2540.Minimum Common Value/README.md index a5366f5b8f4ba..b0c25540c5373 100644 --- a/solution/2500-2599/2540.Minimum Common Value/README.md +++ b/solution/2500-2599/2540.Minimum Common Value/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 遍历两个数组,如果两个指针指向的元素相等,则返回该元素;如果两个指针指向的元素不相等,则将指向较小元素的指针右移一位,直到找到相等的元素或者遍历完数组。 @@ -48,10 +46,6 @@ -### **Python3** - - - ```python class Solution: def getCommon(self, nums1: List[int], nums2: List[int]) -> int: @@ -67,10 +61,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int getCommon(int[] nums1, int[] nums2) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +100,6 @@ public: }; ``` -### **Go** - ```go func getCommon(nums1 []int, nums2 []int) int { m, n := len(nums1), len(nums2) @@ -131,8 +117,6 @@ func getCommon(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - ```ts function getCommon(nums1: number[], nums2: number[]): number { const m = nums1.length; @@ -153,8 +137,6 @@ function getCommon(nums1: number[], nums2: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn get_common(nums1: Vec, nums2: Vec) -> i32 { @@ -177,6 +159,30 @@ impl Solution { } ``` +```c +int getCommon(int* nums1, int nums1Size, int* nums2, int nums2Size) { + int i = 0; + int j = 0; + while (i < nums1Size && j < nums2Size) { + if (nums1[i] == nums2[j]) { + return nums1[i]; + } + if (nums1[i] < nums2[j]) { + i++; + } else { + j++; + } + } + return -1; +} +``` + + + +### 方法二 + + + ```rust impl Solution { pub fn get_common(nums1: Vec, nums2: Vec) -> i32 { @@ -200,30 +206,6 @@ impl Solution { } ``` -### **C** - -```c -int getCommon(int* nums1, int nums1Size, int* nums2, int nums2Size) { - int i = 0; - int j = 0; - while (i < nums1Size && j < nums2Size) { - if (nums1[i] == nums2[j]) { - return nums1[i]; - } - if (nums1[i] < nums2[j]) { - i++; - } else { - j++; - } - } - return -1; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2540.Minimum Common Value/README_EN.md b/solution/2500-2599/2540.Minimum Common Value/README_EN.md index ef2f9d9092c79..dc7075abfd57e 100644 --- a/solution/2500-2599/2540.Minimum Common Value/README_EN.md +++ b/solution/2500-2599/2540.Minimum Common Value/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers Traverse the two arrays. If the elements pointed to by the two pointers are equal, return that element. If the elements pointed to by the two pointers are not equal, move the pointer pointing to the smaller element to the right by one bit until an equal element is found or the array is traversed. @@ -44,8 +44,6 @@ The time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the two -### **Python3** - ```python class Solution: def getCommon(self, nums1: List[int], nums2: List[int]) -> int: @@ -61,8 +59,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int getCommon(int[] nums1, int[] nums2) { @@ -82,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +98,6 @@ public: }; ``` -### **Go** - ```go func getCommon(nums1 []int, nums2 []int) int { m, n := len(nums1), len(nums2) @@ -123,8 +115,6 @@ func getCommon(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - ```ts function getCommon(nums1: number[], nums2: number[]): number { const m = nums1.length; @@ -145,8 +135,6 @@ function getCommon(nums1: number[], nums2: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn get_common(nums1: Vec, nums2: Vec) -> i32 { @@ -169,6 +157,30 @@ impl Solution { } ``` +```c +int getCommon(int* nums1, int nums1Size, int* nums2, int nums2Size) { + int i = 0; + int j = 0; + while (i < nums1Size && j < nums2Size) { + if (nums1[i] == nums2[j]) { + return nums1[i]; + } + if (nums1[i] < nums2[j]) { + i++; + } else { + j++; + } + } + return -1; +} +``` + + + +### Solution 2 + + + ```rust impl Solution { pub fn get_common(nums1: Vec, nums2: Vec) -> i32 { @@ -192,30 +204,6 @@ impl Solution { } ``` -### **C** - -```c -int getCommon(int* nums1, int nums1Size, int* nums2, int nums2Size) { - int i = 0; - int j = 0; - while (i < nums1Size && j < nums2Size) { - if (nums1[i] == nums2[j]) { - return nums1[i]; - } - if (nums1[i] < nums2[j]) { - i++; - } else { - j++; - } - } - return -1; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2541.Minimum Operations to Make Array Equal II/README.md b/solution/2500-2599/2541.Minimum Operations to Make Array Equal II/README.md index a123093d2044c..c36888155e8a9 100644 --- a/solution/2500-2599/2541.Minimum Operations to Make Array Equal II/README.md +++ b/solution/2500-2599/2541.Minimum Operations to Make Array Equal II/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:一次遍历** +### 方法一:一次遍历 我们用变量 $x$ 记录加减次数的差值,用变量 $ans$ 记录操作次数。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, nums1: List[int], nums2: List[int], k: int) -> int: @@ -82,10 +76,6 @@ class Solution: return -1 if x else ans // 2 ``` -### **Java** - - - ```java class Solution { public long minOperations(int[] nums1, int[] nums2, int k) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums1 []int, nums2 []int, k int) int64 { ans, x := 0, 0 @@ -171,8 +157,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minOperations(nums1: number[], nums2: number[], k: number): number { const n = nums1.length; @@ -196,8 +180,6 @@ function minOperations(nums1: number[], nums2: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_operations(nums1: Vec, nums2: Vec, k: i32) -> i64 { @@ -233,8 +215,6 @@ impl Solution { } ``` -### **C** - ```c long long minOperations(int* nums1, int nums1Size, int* nums2, int nums2Size, int k) { if (k == 0) { @@ -262,10 +242,6 @@ long long minOperations(int* nums1, int nums1Size, int* nums2, int nums2Size, in } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2541.Minimum Operations to Make Array Equal II/README_EN.md b/solution/2500-2599/2541.Minimum Operations to Make Array Equal II/README_EN.md index 803a3b941f478..50cb0f4d4941a 100644 --- a/solution/2500-2599/2541.Minimum Operations to Make Array Equal II/README_EN.md +++ b/solution/2500-2599/2541.Minimum Operations to Make Array Equal II/README_EN.md @@ -45,7 +45,7 @@ One can prove that it is impossible to make arrays equal in fewer operations.

-### **Python3** - ```python class Solution: def minOperations(self, nums1: List[int], nums2: List[int], k: int) -> int: @@ -76,8 +74,6 @@ class Solution: return -1 if x else ans // 2 ``` -### **Java** - ```java class Solution { public long minOperations(int[] nums1, int[] nums2, int k) { @@ -102,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +123,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums1 []int, nums2 []int, k int) int64 { ans, x := 0, 0 @@ -163,8 +155,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minOperations(nums1: number[], nums2: number[], k: number): number { const n = nums1.length; @@ -188,8 +178,6 @@ function minOperations(nums1: number[], nums2: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_operations(nums1: Vec, nums2: Vec, k: i32) -> i64 { @@ -225,8 +213,6 @@ impl Solution { } ``` -### **C** - ```c long long minOperations(int* nums1, int nums1Size, int* nums2, int nums2Size, int k) { if (k == 0) { @@ -254,10 +240,6 @@ long long minOperations(int* nums1, int nums1Size, int* nums2, int nums2Size, in } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2542.Maximum Subsequence Score/README.md b/solution/2500-2599/2542.Maximum Subsequence Score/README.md index 54abdcc2cc875..091a6cbbc2d58 100644 --- a/solution/2500-2599/2542.Maximum Subsequence Score/README.md +++ b/solution/2500-2599/2542.Maximum Subsequence Score/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:排序 + 优先队列(小根堆)** +### 方法一:排序 + 优先队列(小根堆) 将 `nums2` 与 `nums1` 按照 `nums2` 降序排序,然后从前往后遍历,维护一个小根堆,堆中存储 `nums1` 中的元素,堆中元素个数不超过 $k$ 个,同时维护一个变量 $s$,表示堆中元素的和,遍历过程中不断更新答案。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long maxScore(int[] nums1, int[] nums2, int k) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func maxScore(nums1 []int, nums2 []int, k int) int64 { type pair struct{ a, b int } @@ -179,10 +165,6 @@ func (h *hp) Pop() any { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2542.Maximum Subsequence Score/README_EN.md b/solution/2500-2599/2542.Maximum Subsequence Score/README_EN.md index 48e1fdcb40e80..200917c2a7d81 100644 --- a/solution/2500-2599/2542.Maximum Subsequence Score/README_EN.md +++ b/solution/2500-2599/2542.Maximum Subsequence Score/README_EN.md @@ -53,7 +53,7 @@ Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum po ## Solutions -**Solution 1: Sorting + Priority Queue (Min Heap)** +### Solution 1: Sorting + Priority Queue (Min Heap) Sort nums2 and nums1 in descending order according to nums2, then traverse from front to back, maintaining a min heap. The heap stores elements from nums1, and the number of elements in the heap does not exceed $k$. At the same time, maintain a variable $s$ representing the sum of the elements in the heap, and continuously update the answer during the traversal process. @@ -61,8 +61,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int: @@ -78,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long maxScore(int[] nums1, int[] nums2, int k) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +126,6 @@ public: }; ``` -### **Go** - ```go func maxScore(nums1 []int, nums2 []int, k int) int64 { type pair struct{ a, b int } @@ -169,10 +161,6 @@ func (h *hp) Pop() any { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2543.Check if Point Is Reachable/README.md b/solution/2500-2599/2543.Check if Point Is Reachable/README.md index 1545bd375dd61..cafd6d7425ae7 100644 --- a/solution/2500-2599/2543.Check if Point Is Reachable/README.md +++ b/solution/2500-2599/2543.Check if Point Is Reachable/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 我们注意到,前两种移动方式不会改变横、纵坐标的最大公约数,而后两种移动方式可以使得横、纵坐标的最大公约数乘上 $2$ 的幂次。也就是说,最后的横、纵坐标的最大公约数必须是 $2$ 的幂次。最大公约数不是 $2$ 的幂次,那么就无法到达。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def isReachable(self, targetX: int, targetY: int) -> bool: @@ -72,10 +66,6 @@ class Solution: return x & (x - 1) == 0 ``` -### **Java** - - - ```java class Solution { public boolean isReachable(int targetX, int targetY) { @@ -89,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +89,6 @@ public: }; ``` -### **Go** - ```go func isReachable(targetX int, targetY int) bool { x := gcd(targetX, targetY) @@ -117,8 +103,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function isReachable(targetX: number, targetY: number): boolean { const x = gcd(targetX, targetY); @@ -130,10 +114,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2543.Check if Point Is Reachable/README_EN.md b/solution/2500-2599/2543.Check if Point Is Reachable/README_EN.md index ad9d676b0071d..5da506d05b357 100644 --- a/solution/2500-2599/2543.Check if Point Is Reachable/README_EN.md +++ b/solution/2500-2599/2543.Check if Point Is Reachable/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics We notice that the first two types of moves do not change the greatest common divisor (gcd) of the horizontal and vertical coordinates, while the last two types of moves can multiply the gcd of the horizontal and vertical coordinates by a power of $2$. In other words, the final gcd of the horizontal and vertical coordinates must be a power of $2$. If the gcd is not a power of $2$, then it is impossible to reach. @@ -57,8 +57,6 @@ The time complexity is $O(\log(\min(targetX, targetY)))$, and the space complexi -### **Python3** - ```python class Solution: def isReachable(self, targetX: int, targetY: int) -> bool: @@ -66,8 +64,6 @@ class Solution: return x & (x - 1) == 0 ``` -### **Java** - ```java class Solution { public boolean isReachable(int targetX, int targetY) { @@ -81,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +87,6 @@ public: }; ``` -### **Go** - ```go func isReachable(targetX int, targetY int) bool { x := gcd(targetX, targetY) @@ -109,8 +101,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function isReachable(targetX: number, targetY: number): boolean { const x = gcd(targetX, targetY); @@ -122,10 +112,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2544.Alternating Digit Sum/README.md b/solution/2500-2599/2544.Alternating Digit Sum/README.md index 4571283598fd4..3ab47061b1cb7 100644 --- a/solution/2500-2599/2544.Alternating Digit Sum/README.md +++ b/solution/2500-2599/2544.Alternating Digit Sum/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 直接根据题目描述模拟即可。 @@ -64,31 +62,12 @@ -### **Python3** - - - ```python class Solution: def alternateDigitSum(self, n: int) -> int: return sum((-1) ** i * int(x) for i, x in enumerate(str(n))) ``` -```python -class Solution: - def alternateDigitSum(self, n: int) -> int: - ans, sign = 0, 1 - for c in str(n): - x = int(c) - ans += sign * x - sign *= -1 - return ans -``` - -### **Java** - - - ```java class Solution { public int alternateDigitSum(int n) { @@ -103,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +97,6 @@ public: }; ``` -### **Go** - ```go func alternateDigitSum(n int) (ans int) { sign := 1 @@ -134,8 +109,6 @@ func alternateDigitSum(n int) (ans int) { } ``` -### **TypeScript** - ```ts function alternateDigitSum(n: number): number { let ans = 0; @@ -149,8 +122,6 @@ function alternateDigitSum(n: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn alternate_digit_sum(mut n: i32) -> i32 { @@ -166,25 +137,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn alternate_digit_sum(n: i32) -> i32 { - let mut ans = 0; - let mut sign = 1; - - for c in format!("{}", n).chars() { - let x = c.to_digit(10).unwrap() as i32; - ans += x * sign; - sign *= -1; - } - - ans - } -} -``` - -### **C** - ```c int alternateDigitSum(int n) { int ans = 0; @@ -198,10 +150,40 @@ int alternateDigitSum(int n) { } ``` -### **...** + +### 方法二 + + + +```python +class Solution: + def alternateDigitSum(self, n: int) -> int: + ans, sign = 0, 1 + for c in str(n): + x = int(c) + ans += sign * x + sign *= -1 + return ans ``` +```rust +impl Solution { + pub fn alternate_digit_sum(n: i32) -> i32 { + let mut ans = 0; + let mut sign = 1; + + for c in format!("{}", n).chars() { + let x = c.to_digit(10).unwrap() as i32; + ans += x * sign; + sign *= -1; + } + + ans + } +} ``` + + diff --git a/solution/2500-2599/2544.Alternating Digit Sum/README_EN.md b/solution/2500-2599/2544.Alternating Digit Sum/README_EN.md index 229ec53663636..5ae95c3ac3fe3 100644 --- a/solution/2500-2599/2544.Alternating Digit Sum/README_EN.md +++ b/solution/2500-2599/2544.Alternating Digit Sum/README_EN.md @@ -56,7 +56,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can directly simulate the process as described in the problem. @@ -66,27 +66,12 @@ The time complexity is $O(\log n)$, and the space complexity is $O(\log n)$. Her -### **Python3** - ```python class Solution: def alternateDigitSum(self, n: int) -> int: return sum((-1) ** i * int(x) for i, x in enumerate(str(n))) ``` -```python -class Solution: - def alternateDigitSum(self, n: int) -> int: - ans, sign = 0, 1 - for c in str(n): - x = int(c) - ans += sign * x - sign *= -1 - return ans -``` - -### **Java** - ```java class Solution { public int alternateDigitSum(int n) { @@ -101,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +101,6 @@ public: }; ``` -### **Go** - ```go func alternateDigitSum(n int) (ans int) { sign := 1 @@ -132,8 +113,6 @@ func alternateDigitSum(n int) (ans int) { } ``` -### **TypeScript** - ```ts function alternateDigitSum(n: number): number { let ans = 0; @@ -147,8 +126,6 @@ function alternateDigitSum(n: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn alternate_digit_sum(mut n: i32) -> i32 { @@ -164,25 +141,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn alternate_digit_sum(n: i32) -> i32 { - let mut ans = 0; - let mut sign = 1; - - for c in format!("{}", n).chars() { - let x = c.to_digit(10).unwrap() as i32; - ans += x * sign; - sign *= -1; - } - - ans - } -} -``` - -### **C** - ```c int alternateDigitSum(int n) { int ans = 0; @@ -196,10 +154,40 @@ int alternateDigitSum(int n) { } ``` -### **...** + + +### Solution 2 + + +```python +class Solution: + def alternateDigitSum(self, n: int) -> int: + ans, sign = 0, 1 + for c in str(n): + x = int(c) + ans += sign * x + sign *= -1 + return ans ``` +```rust +impl Solution { + pub fn alternate_digit_sum(n: i32) -> i32 { + let mut ans = 0; + let mut sign = 1; + + for c in format!("{}", n).chars() { + let x = c.to_digit(10).unwrap() as i32; + ans += x * sign; + sign *= -1; + } + + ans + } +} ``` + + diff --git a/solution/2500-2599/2545.Sort the Students by Their Kth Score/README.md b/solution/2500-2599/2545.Sort the Students by Their Kth Score/README.md index ac97c550a45a7..d6ee833513826 100644 --- a/solution/2500-2599/2545.Sort the Students by Their Kth Score/README.md +++ b/solution/2500-2599/2545.Sort the Students by Their Kth Score/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们将 `score` 按照第 $k$ 列的分数从大到小排序,然后返回即可。 @@ -64,20 +62,12 @@ -### **Python3** - - - ```python class Solution: def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]: return sorted(score, key=lambda x: -x[k]) ``` -### **Java** - - - ```java class Solution { public int[][] sortTheStudents(int[][] score, int k) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +87,6 @@ public: }; ``` -### **Go** - ```go func sortTheStudents(score [][]int, k int) [][]int { sort.Slice(score, func(i, j int) bool { return score[i][k] > score[j][k] }) @@ -108,16 +94,12 @@ func sortTheStudents(score [][]int, k int) [][]int { } ``` -### **TypeScript** - ```ts function sortTheStudents(score: number[][], k: number): number[][] { return score.sort((a, b) => b[k] - a[k]); } ``` -### **Rust** - ```rust impl Solution { pub fn sort_the_students(mut score: Vec>, k: i32) -> Vec> { @@ -128,10 +110,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2545.Sort the Students by Their Kth Score/README_EN.md b/solution/2500-2599/2545.Sort the Students by Their Kth Score/README_EN.md index 60b996097e8f3..4870ec3b6f736 100644 --- a/solution/2500-2599/2545.Sort the Students by Their Kth Score/README_EN.md +++ b/solution/2500-2599/2545.Sort the Students by Their Kth Score/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting We sort score in descending order based on the scores in the $k^{th}$ column, and then return it. @@ -54,16 +54,12 @@ The time complexity is $O(m \times \log m)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]: return sorted(score, key=lambda x: -x[k]) ``` -### **Java** - ```java class Solution { public int[][] sortTheStudents(int[][] score, int k) { @@ -73,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -85,8 +79,6 @@ public: }; ``` -### **Go** - ```go func sortTheStudents(score [][]int, k int) [][]int { sort.Slice(score, func(i, j int) bool { return score[i][k] > score[j][k] }) @@ -94,16 +86,12 @@ func sortTheStudents(score [][]int, k int) [][]int { } ``` -### **TypeScript** - ```ts function sortTheStudents(score: number[][], k: number): number[][] { return score.sort((a, b) => b[k] - a[k]); } ``` -### **Rust** - ```rust impl Solution { pub fn sort_the_students(mut score: Vec>, k: i32) -> Vec> { @@ -114,10 +102,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README.md b/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README.md index ae381e24a3151..fd70b3368689c 100644 --- a/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README.md +++ b/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 我们注意到 $1$ 其实是数字转换的“工具”,因此只要两个字符串中都有 $1$ 或者都没有 $1$,那么就可以通过操作使得两个字符串相等。 @@ -58,20 +56,12 @@ -### **Python3** - - - ```python class Solution: def makeStringsEqual(self, s: str, target: str) -> bool: return ("1" in s) == ("1" in target) ``` -### **Java** - - - ```java class Solution { public boolean makeStringsEqual(String s, String target) { @@ -80,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,24 +81,18 @@ public: }; ``` -### **Go** - ```go func makeStringsEqual(s string, target string) bool { return strings.Contains(s, "1") == strings.Contains(target, "1") } ``` -### **TypeScript** - ```ts function makeStringsEqual(s: string, target: string): boolean { return s.includes('1') === target.includes('1'); } ``` -### **Rust** - ```rust impl Solution { pub fn make_strings_equal(s: String, target: String) -> bool { @@ -119,8 +101,6 @@ impl Solution { } ``` -### **C** - ```c bool makeStringsEqual(char* s, char* target) { int count = 0; @@ -140,10 +120,6 @@ bool makeStringsEqual(char* s, char* target) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README_EN.md b/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README_EN.md index a3e57d6256766..3a1399d3d7ab9 100644 --- a/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README_EN.md +++ b/solution/2500-2599/2546.Apply Bitwise Operations to Make Strings Equal/README_EN.md @@ -46,7 +46,7 @@ Since we can make s equal to target, we return true. ## Solutions -**Solution 1: Lateral Thinking** +### Solution 1: Lateral Thinking We notice that $1$ is actually a "tool" for number conversion. Therefore, as long as both strings either have $1$ or neither have $1$, we can make the two strings equal through operations. @@ -54,16 +54,12 @@ The time complexity is $O(n)$, where $n$ is the length of the string. The space -### **Python3** - ```python class Solution: def makeStringsEqual(self, s: str, target: str) -> bool: return ("1" in s) == ("1" in target) ``` -### **Java** - ```java class Solution { public boolean makeStringsEqual(String s, String target) { @@ -72,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -85,24 +79,18 @@ public: }; ``` -### **Go** - ```go func makeStringsEqual(s string, target string) bool { return strings.Contains(s, "1") == strings.Contains(target, "1") } ``` -### **TypeScript** - ```ts function makeStringsEqual(s: string, target: string): boolean { return s.includes('1') === target.includes('1'); } ``` -### **Rust** - ```rust impl Solution { pub fn make_strings_equal(s: String, target: String) -> bool { @@ -111,8 +99,6 @@ impl Solution { } ``` -### **C** - ```c bool makeStringsEqual(char* s, char* target) { int count = 0; @@ -132,10 +118,6 @@ bool makeStringsEqual(char* s, char* target) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2547.Minimum Cost to Split an Array/README.md b/solution/2500-2599/2547.Minimum Cost to Split an Array/README.md index f58d3bb1ad002..a2dca30c4ec0b 100644 --- a/solution/2500-2599/2547.Minimum Cost to Split an Array/README.md +++ b/solution/2500-2599/2547.Minimum Cost to Split an Array/README.md @@ -74,9 +74,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i)$,表示从下标 $i$ 开始拆分的最小代价。那么答案就是 $dfs(0)$。 @@ -91,10 +89,6 @@ -### **Python3** - - - ```python class Solution: def minCost(self, nums: List[int], k: int) -> int: @@ -118,10 +112,6 @@ class Solution: return dfs(0) ``` -### **Java** - - - ```java class Solution { private Integer[] f; @@ -160,8 +150,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -196,8 +184,6 @@ public: }; ``` -### **Go** - ```go func minCost(nums []int, k int) int { n := len(nums) @@ -229,8 +215,6 @@ func minCost(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function minCost(nums: number[], k: number): number { const n = nums.length; @@ -261,10 +245,6 @@ function minCost(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2547.Minimum Cost to Split an Array/README_EN.md b/solution/2500-2599/2547.Minimum Cost to Split an Array/README_EN.md index 31c8501132090..fe8c6dbdf173f 100644 --- a/solution/2500-2599/2547.Minimum Cost to Split an Array/README_EN.md +++ b/solution/2500-2599/2547.Minimum Cost to Split an Array/README_EN.md @@ -77,7 +77,7 @@ The cost of the split is 10. It can be shown that this is the minimum possible c ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We design a function $dfs(i)$, which represents the minimum cost of splitting from index $i$. So the answer is $dfs(0)$. @@ -91,8 +91,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ i -### **Python3** - ```python class Solution: def minCost(self, nums: List[int], k: int) -> int: @@ -116,8 +114,6 @@ class Solution: return dfs(0) ``` -### **Java** - ```java class Solution { private Integer[] f; @@ -156,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -192,8 +186,6 @@ public: }; ``` -### **Go** - ```go func minCost(nums []int, k int) int { n := len(nums) @@ -225,8 +217,6 @@ func minCost(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function minCost(nums: number[], k: number): number { const n = nums.length; @@ -257,10 +247,6 @@ function minCost(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2548.Maximum Price to Fill a Bag/README.md b/solution/2500-2599/2548.Maximum Price to Fill a Bag/README.md index c96502f109a45..c4fa12bfa1660 100644 --- a/solution/2500-2599/2548.Maximum Price to Fill a Bag/README.md +++ b/solution/2500-2599/2548.Maximum Price to Fill a Bag/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 我们将物品按照单位价格从大到小排序,然后依次取出物品,直到背包装满。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def maxPrice(self, items: List[List[int]], capacity: int) -> float: @@ -82,10 +76,6 @@ class Solution: return -1 if capacity else ans ``` -### **Java** - - - ```java class Solution { public double maxPrice(int[][] items, int capacity) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func maxPrice(items [][]int, capacity int) (ans float64) { sort.Slice(items, func(i, j int) bool { return items[i][1]*items[j][0] < items[i][0]*items[j][1] }) @@ -139,8 +125,6 @@ func maxPrice(items [][]int, capacity int) (ans float64) { } ``` -### **TypeScript** - ```ts function maxPrice(items: number[][], capacity: number): number { items.sort((a, b) => a[1] * b[0] - a[0] * b[1]); @@ -154,10 +138,6 @@ function maxPrice(items: number[][], capacity: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2548.Maximum Price to Fill a Bag/README_EN.md b/solution/2500-2599/2548.Maximum Price to Fill a Bag/README_EN.md index 2e41d5f5861e1..5dae27711394a 100644 --- a/solution/2500-2599/2548.Maximum Price to Fill a Bag/README_EN.md +++ b/solution/2500-2599/2548.Maximum Price to Fill a Bag/README_EN.md @@ -51,7 +51,7 @@ It can be proved that 55.0 is the maximum total price that we can achieve. ## Solutions -**Solution 1: Greedy + Sorting** +### Solution 1: Greedy + Sorting We sort the items in descending order by unit price, and then take out the items one by one until the backpack is full. @@ -61,8 +61,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def maxPrice(self, items: List[List[int]], capacity: int) -> float: @@ -74,8 +72,6 @@ class Solution: return -1 if capacity else ans ``` -### **Java** - ```java class Solution { public double maxPrice(int[][] items, int capacity) { @@ -92,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +105,6 @@ public: }; ``` -### **Go** - ```go func maxPrice(items [][]int, capacity int) (ans float64) { sort.Slice(items, func(i, j int) bool { return items[i][1]*items[j][0] < items[i][0]*items[j][1] }) @@ -129,8 +121,6 @@ func maxPrice(items [][]int, capacity int) (ans float64) { } ``` -### **TypeScript** - ```ts function maxPrice(items: number[][], capacity: number): number { items.sort((a, b) => a[1] * b[0] - a[0] * b[1]); @@ -144,10 +134,6 @@ function maxPrice(items: number[][], capacity: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2549.Count Distinct Numbers on Board/README.md b/solution/2500-2599/2549.Count Distinct Numbers on Board/README.md index adbd20b378d5f..a5bbe424f255c 100644 --- a/solution/2500-2599/2549.Count Distinct Numbers on Board/README.md +++ b/solution/2500-2599/2549.Count Distinct Numbers on Board/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 由于每一次对桌面上的数字 $n$ 进行操作,会使得数字 $n-1$ 也出现在桌面上,因此最终桌面上的数字为 $[2,...n]$,即 $n-1$ 个数字。 @@ -67,20 +65,12 @@ -### **Python3** - - - ```python class Solution: def distinctIntegers(self, n: int) -> int: return max(1, n - 1) ``` -### **Java** - - - ```java class Solution { public int distinctIntegers(int n) { @@ -89,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +88,6 @@ public: }; ``` -### **Go** - ```go func distinctIntegers(n int) int { if n == 1 { @@ -111,16 +97,12 @@ func distinctIntegers(n int) int { } ``` -### **TypeScript** - ```ts function distinctIntegers(n: number): number { return Math.max(1, n - 1); } ``` -### **Rust** - ```rust impl Solution { pub fn distinct_integers(n: i32) -> i32 { @@ -133,10 +115,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2549.Count Distinct Numbers on Board/README_EN.md b/solution/2500-2599/2549.Count Distinct Numbers on Board/README_EN.md index 75b57ec57dbb2..04c0bf96b8d57 100644 --- a/solution/2500-2599/2549.Count Distinct Numbers on Board/README_EN.md +++ b/solution/2500-2599/2549.Count Distinct Numbers on Board/README_EN.md @@ -51,7 +51,7 @@ After a billion days, the only two distinct numbers on the board are 2 and 3. ## Solutions -**Solution 1: Lateral Thinking** +### Solution 1: Lateral Thinking Since every operation on the number $n$ on the desktop will also cause the number $n-1$ to appear on the desktop, the final numbers on the desktop are $[2,...n]$, that is, $n-1$ numbers. @@ -61,16 +61,12 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def distinctIntegers(self, n: int) -> int: return max(1, n - 1) ``` -### **Java** - ```java class Solution { public int distinctIntegers(int n) { @@ -79,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,8 +84,6 @@ public: }; ``` -### **Go** - ```go func distinctIntegers(n int) int { if n == 1 { @@ -101,16 +93,12 @@ func distinctIntegers(n int) int { } ``` -### **TypeScript** - ```ts function distinctIntegers(n: number): number { return Math.max(1, n - 1); } ``` -### **Rust** - ```rust impl Solution { pub fn distinct_integers(n: i32) -> i32 { @@ -123,10 +111,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README.md b/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README.md index 82fe2c349edd1..b81ef5e0116a1 100644 --- a/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README.md +++ b/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:数学(快速幂)** +### 方法一:数学(快速幂) 根据题目描述,每一只猴子都有两种移动方式,即顺时针或逆时针。因此,一共有 $2^n$ 种移动方式。不碰撞的移动方式只有两种,即所有猴子都顺时针移动或所有猴子都逆时针移动。因此,碰撞的移动方式有 $2^n - 2$ 种。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def monkeyMove(self, n: int) -> int: @@ -77,10 +71,6 @@ class Solution: return (pow(2, n, mod) - 2) % mod ``` -### **Java** - - - ```java class Solution { public int monkeyMove(int n) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func monkeyMove(n int) int { const mod = 1e9 + 7 @@ -143,8 +129,6 @@ func monkeyMove(n int) int { } ``` -### **TypeScript** - ```ts function monkeyMove(n: number): number { const mod = 10 ** 9 + 7; @@ -162,10 +146,6 @@ function monkeyMove(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README_EN.md b/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README_EN.md index e8a546b0bb973..6ab1ba91e6c13 100644 --- a/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README_EN.md +++ b/solution/2500-2599/2550.Count Collisions of Monkeys on a Polygon/README_EN.md @@ -49,7 +49,7 @@ It can be shown 6 total movements result in a collision. ## Solutions -**Solution 1: Mathematics (Fast Power)** +### Solution 1: Mathematics (Fast Power) According to the problem description, each monkey has two ways of moving, either clockwise or counterclockwise. Therefore, there are a total of $2^n$ ways to move. The non-collision ways of moving are only two, that is, all monkeys move clockwise or all monkeys move counterclockwise. Therefore, the number of collision ways of moving is $2^n - 2$. @@ -59,8 +59,6 @@ The time complexity is $O(\log n)$, where $n$ is the number of monkeys. The spac -### **Python3** - ```python class Solution: def monkeyMove(self, n: int) -> int: @@ -68,8 +66,6 @@ class Solution: return (pow(2, n, mod) - 2) % mod ``` -### **Java** - ```java class Solution { public int monkeyMove(int n) { @@ -90,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +107,6 @@ public: }; ``` -### **Go** - ```go func monkeyMove(n int) int { const mod = 1e9 + 7 @@ -132,8 +124,6 @@ func monkeyMove(n int) int { } ``` -### **TypeScript** - ```ts function monkeyMove(n: number): number { const mod = 10 ** 9 + 7; @@ -151,10 +141,6 @@ function monkeyMove(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2551.Put Marbles in Bags/README.md b/solution/2500-2599/2551.Put Marbles in Bags/README.md index 0b67a0d07df04..9423f1e56540a 100644 --- a/solution/2500-2599/2551.Put Marbles in Bags/README.md +++ b/solution/2500-2599/2551.Put Marbles in Bags/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:问题转化 + 排序** +### 方法一:问题转化 + 排序 我们可以将问题转化为:将数组 `weights` 分成 $k$ 个连续的子数组,也就是说,我们要找到 $k-1$ 个分割点,每个分割点的价格是分割点左右两个元素的和,求最大的 $k-1$ 个分割点的价格之和与最小的 $k-1$ 个分割点的价格之和的差值,即为答案。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def putMarbles(self, weights: List[int], k: int) -> int: @@ -74,10 +68,6 @@ class Solution: return sum(arr[len(arr) - k + 1 :]) - sum(arr[: k - 1]) ``` -### **Java** - - - ```java class Solution { public long putMarbles(int[] weights, int k) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func putMarbles(weights []int, k int) (ans int64) { n := len(weights) @@ -136,8 +122,6 @@ func putMarbles(weights []int, k int) (ans int64) { } ``` -### **TypeScript** - ```ts function putMarbles(weights: number[], k: number): number { const n = weights.length; @@ -154,10 +138,6 @@ function putMarbles(weights: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2551.Put Marbles in Bags/README_EN.md b/solution/2500-2599/2551.Put Marbles in Bags/README_EN.md index 0159cc8cf216d..e20454175f59f 100644 --- a/solution/2500-2599/2551.Put Marbles in Bags/README_EN.md +++ b/solution/2500-2599/2551.Put Marbles in Bags/README_EN.md @@ -49,7 +49,7 @@ Since both the maximal and minimal score are the same, we return 0. ## Solutions -**Solution 1: Problem Transformation + Sorting** +### Solution 1: Problem Transformation + Sorting We can transform the problem into: dividing the array `weights` into $k$ consecutive subarrays, that is, we need to find $k-1$ splitting points, each splitting point's cost is the sum of the elements on the left and right of the splitting point. The difference between the sum of the costs of the largest $k-1$ splitting points and the smallest $k-1$ splitting points is the answer. @@ -59,8 +59,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def putMarbles(self, weights: List[int], k: int) -> int: @@ -68,8 +66,6 @@ class Solution: return sum(arr[len(arr) - k + 1 :]) - sum(arr[: k - 1]) ``` -### **Java** - ```java class Solution { public long putMarbles(int[] weights, int k) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +105,6 @@ public: }; ``` -### **Go** - ```go func putMarbles(weights []int, k int) (ans int64) { n := len(weights) @@ -128,8 +120,6 @@ func putMarbles(weights []int, k int) (ans int64) { } ``` -### **TypeScript** - ```ts function putMarbles(weights: number[], k: number): number { const n = weights.length; @@ -146,10 +136,6 @@ function putMarbles(weights: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2552.Count Increasing Quadruplets/README.md b/solution/2500-2599/2552.Count Increasing Quadruplets/README.md index 29e664665f1b8..63860dd604368 100644 --- a/solution/2500-2599/2552.Count Increasing Quadruplets/README.md +++ b/solution/2500-2599/2552.Count Increasing Quadruplets/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:枚举 + 预处理** +### 方法一:枚举 + 预处理 我们可以枚举四元组中的 $j$ 和 $k$,那么问题转化为,对于当前的 $j$ 和 $k$: @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def countQuadruplets(self, nums: List[int]) -> int: @@ -92,10 +86,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public long countQuadruplets(int[] nums) { @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp const int N = 4001; int f[N][N]; @@ -189,8 +177,6 @@ public: }; ``` -### **Go** - ```go func countQuadruplets(nums []int) int64 { n := len(nums) @@ -236,10 +222,6 @@ func countQuadruplets(nums []int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2552.Count Increasing Quadruplets/README_EN.md b/solution/2500-2599/2552.Count Increasing Quadruplets/README_EN.md index 91501f03d56c2..540d435aac587 100644 --- a/solution/2500-2599/2552.Count Increasing Quadruplets/README_EN.md +++ b/solution/2500-2599/2552.Count Increasing Quadruplets/README_EN.md @@ -44,7 +44,7 @@ There are no other quadruplets, so we return 2. ## Solutions -**Solution 1: Enumeration + Preprocessing** +### Solution 1: Enumeration + Preprocessing We can enumerate $j$ and $k$ in the quadruplet, then the problem is transformed into, for the current $j$ and $k$: @@ -59,8 +59,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ -### **Python3** - ```python class Solution: def countQuadruplets(self, nums: List[int]) -> int: @@ -86,8 +84,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public long countQuadruplets(int[] nums) { @@ -131,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp const int N = 4001; int f[N][N]; @@ -181,8 +175,6 @@ public: }; ``` -### **Go** - ```go func countQuadruplets(nums []int) int64 { n := len(nums) @@ -228,10 +220,6 @@ func countQuadruplets(nums []int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2553.Separate the Digits in an Array/README.md b/solution/2500-2599/2553.Separate the Digits in an Array/README.md index 1c7150e8dee63..aa2437b794b51 100644 --- a/solution/2500-2599/2553.Separate the Digits in an Array/README.md +++ b/solution/2500-2599/2553.Separate the Digits in an Array/README.md @@ -47,9 +47,7 @@ answer = [7,1,3,9] 。 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 将数组中的每个数字进行数位分割,然后将分割后的数字依次放入答案数组中。 @@ -57,10 +55,6 @@ answer = [7,1,3,9] 。 -### **Python3** - - - ```python class Solution: def separateDigits(self, nums: List[int]) -> List[int]: @@ -74,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] separateDigits(int[] nums) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func separateDigits(nums []int) (ans []int) { for _, x := range nums { @@ -139,8 +125,6 @@ func separateDigits(nums []int) (ans []int) { } ``` -### **TypeScript** - ```ts function separateDigits(nums: number[]): number[] { const ans: number[] = []; @@ -156,8 +140,6 @@ function separateDigits(nums: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn separate_digits(nums: Vec) -> Vec { @@ -178,32 +160,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn separate_digits(nums: Vec) -> Vec { - let mut ans = vec![]; - - for n in nums { - let mut t = vec![]; - let mut x = n; - - while x != 0 { - t.push(x % 10); - x /= 10; - } - - for i in (0..t.len()).rev() { - ans.push(t[i]); - } - } - - ans - } -} -``` - -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -230,10 +186,36 @@ int* separateDigits(int* nums, int numsSize, int* returnSize) { } ``` -### **...** + + +### 方法二 -``` + + +```rust +impl Solution { + pub fn separate_digits(nums: Vec) -> Vec { + let mut ans = vec![]; + + for n in nums { + let mut t = vec![]; + let mut x = n; + + while x != 0 { + t.push(x % 10); + x /= 10; + } + for i in (0..t.len()).rev() { + ans.push(t[i]); + } + } + + ans + } +} ``` + + diff --git a/solution/2500-2599/2553.Separate the Digits in an Array/README_EN.md b/solution/2500-2599/2553.Separate the Digits in an Array/README_EN.md index 4256b0f8a16e3..d6d83806dfce5 100644 --- a/solution/2500-2599/2553.Separate the Digits in an Array/README_EN.md +++ b/solution/2500-2599/2553.Separate the Digits in an Array/README_EN.md @@ -45,7 +45,7 @@ answer = [7,1,3,9]. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation Split each number in the array into digits, then put the split numbers into the answer array in order. @@ -53,8 +53,6 @@ The time complexity is $O(n \times \log_{10} M)$, and the space complexity is $O -### **Python3** - ```python class Solution: def separateDigits(self, nums: List[int]) -> List[int]: @@ -68,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] separateDigits(int[] nums) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +107,6 @@ public: }; ``` -### **Go** - ```go func separateDigits(nums []int) (ans []int) { for _, x := range nums { @@ -131,8 +123,6 @@ func separateDigits(nums []int) (ans []int) { } ``` -### **TypeScript** - ```ts function separateDigits(nums: number[]): number[] { const ans: number[] = []; @@ -148,8 +138,6 @@ function separateDigits(nums: number[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn separate_digits(nums: Vec) -> Vec { @@ -170,32 +158,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn separate_digits(nums: Vec) -> Vec { - let mut ans = vec![]; - - for n in nums { - let mut t = vec![]; - let mut x = n; - - while x != 0 { - t.push(x % 10); - x /= 10; - } - - for i in (0..t.len()).rev() { - ans.push(t[i]); - } - } - - ans - } -} -``` - -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -222,10 +184,36 @@ int* separateDigits(int* nums, int numsSize, int* returnSize) { } ``` -### **...** + -``` +### Solution 2 + + + +```rust +impl Solution { + pub fn separate_digits(nums: Vec) -> Vec { + let mut ans = vec![]; + + for n in nums { + let mut t = vec![]; + let mut x = n; + while x != 0 { + t.push(x % 10); + x /= 10; + } + + for i in (0..t.len()).rev() { + ans.push(t[i]); + } + } + + ans + } +} ``` + + diff --git a/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README.md b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README.md index 452b6cae43cb4..74b8a5634f144 100644 --- a/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README.md +++ b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:贪心 + 枚举** +### 方法一:贪心 + 枚举 我们用变量 $s$ 表示当前已经选择的整数的和,用变量 $ans$ 表示当前已经选择的整数的个数。将数组 `banned` 转换为哈希表,方便判断某个整数是否不可选。 @@ -66,26 +64,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为给定的整数。 -**方法二:贪心 + 二分查找** - -如果 $n$ 很大,那么方法一中的枚举会超时。 - -我们可以在数组 `banned` 中加入 $0$ 和 $n + 1$,并将数组 `banned` 去重且移除大于 $n+1$ 的元素,然后进行排序。 - -接下来,我们枚举数组 `banned` 中的每两个相邻元素 $i$ 和 $j$,那么可选的整数范围就是 $[i + 1, j - 1]$。二分枚举我们在此区间内能够选择的元素个数,找到最大的可选元素个数,然后将其加到 $ans$ 中。同时在 `maxSum` 中减去这些元素的和。如果 `maxSum` 小于 $0$,那么我们跳出循环。返回答案即可。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `banned` 的长度。 - -相似题目: - -- [2557. 从一个范围内选择最多整数 II](/solution/2500-2599/2557.Maximum%20Number%20of%20Integers%20to%20Choose%20From%20a%20Range%20II/README.md) - -### **Python3** - - - ```python class Solution: def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: @@ -100,31 +80,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: - banned.extend([0, n + 1]) - ban = sorted(x for x in set(banned) if x < n + 2) - ans = 0 - for i, j in pairwise(ban): - left, right = 0, j - i - 1 - while left < right: - mid = (left + right + 1) >> 1 - if (i + 1 + i + mid) * mid // 2 <= maxSum: - left = mid - else: - right = mid - 1 - ans += left - maxSum -= (i + 1 + i + left) * left // 2 - if maxSum <= 0: - break - return ans -``` - -### **Java** - - - ```java class Solution { public int maxCount(int[] banned, int n, int maxSum) { @@ -144,44 +99,6 @@ class Solution { } ``` -```java -class Solution { - public int maxCount(int[] banned, int n, int maxSum) { - Set black = new HashSet<>(); - black.add(0); - black.add(n + 1); - for (int x : banned) { - if (x < n + 2) { - black.add(x); - } - } - List ban = new ArrayList<>(black); - Collections.sort(ban); - int ans = 0; - for (int k = 1; k < ban.size(); ++k) { - int i = ban.get(k - 1), j = ban.get(k); - int left = 0, right = j - i - 1; - while (left < right) { - int mid = (left + right + 1) >>> 1; - if ((i + 1 + i + mid) * 1L * mid / 2 <= maxSum) { - left = mid; - } else { - right = mid - 1; - } - } - ans += left; - maxSum -= (i + 1 + i + left) * 1L * left / 2; - if (maxSum <= 0) { - break; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -199,40 +116,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxCount(vector& banned, int n, int maxSum) { - banned.push_back(0); - banned.push_back(n + 1); - sort(banned.begin(), banned.end()); - banned.erase(unique(banned.begin(), banned.end()), banned.end()); - banned.erase(remove_if(banned.begin(), banned.end(), [&](int x) { return x > n + 1; }), banned.end()); - int ans = 0; - for (int k = 1; k < banned.size(); ++k) { - int i = banned[k - 1], j = banned[k]; - int left = 0, right = j - i - 1; - while (left < right) { - int mid = left + ((right - left + 1) / 2); - if ((i + 1 + i + mid) * 1LL * mid / 2 <= maxSum) { - left = mid; - } else { - right = mid - 1; - } - } - ans += left; - maxSum -= (i + 1 + i + left) * 1LL * left / 2; - if (maxSum <= 0) { - break; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func maxCount(banned []int, n int, maxSum int) (ans int) { ban := map[int]bool{} @@ -250,40 +133,6 @@ func maxCount(banned []int, n int, maxSum int) (ans int) { } ``` -```go -func maxCount(banned []int, n int, maxSum int) (ans int) { - banned = append(banned, []int{0, n + 1}...) - sort.Ints(banned) - ban := []int{} - for i, x := range banned { - if (i > 0 && x == banned[i-1]) || x > n+1 { - continue - } - ban = append(ban, x) - } - for k := 1; k < len(ban); k++ { - i, j := ban[k-1], ban[k] - left, right := 0, j-i-1 - for left < right { - mid := (left + right + 1) >> 1 - if (i+1+i+mid)*mid/2 <= maxSum { - left = mid - } else { - right = mid - 1 - } - } - ans += left - maxSum -= (i + 1 + i + left) * left / 2 - if maxSum <= 0 { - break - } - } - return -} -``` - -### **TypeScript** - ```ts function maxCount(banned: number[], n: number, maxSum: number): number { const set = new Set(banned); @@ -303,8 +152,6 @@ function maxCount(banned: number[], n: number, maxSum: number): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -327,8 +174,6 @@ impl Solution { } ``` -### **C** - ```c int cmp(const void* a, const void* b) { return *(int*) a - *(int*) b; @@ -355,10 +200,145 @@ int maxCount(int* banned, int bannedSize, int n, int maxSum) { } ``` -### **...** + + +### 方法二:贪心 + 二分查找 + +如果 $n$ 很大,那么方法一中的枚举会超时。 + +我们可以在数组 `banned` 中加入 $0$ 和 $n + 1$,并将数组 `banned` 去重且移除大于 $n+1$ 的元素,然后进行排序。 +接下来,我们枚举数组 `banned` 中的每两个相邻元素 $i$ 和 $j$,那么可选的整数范围就是 $[i + 1, j - 1]$。二分枚举我们在此区间内能够选择的元素个数,找到最大的可选元素个数,然后将其加到 $ans$ 中。同时在 `maxSum` 中减去这些元素的和。如果 `maxSum` 小于 $0$,那么我们跳出循环。返回答案即可。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `banned` 的长度。 + +相似题目: + +- [2557. 从一个范围内选择最多整数 II](/solution/2500-2599/2557.Maximum%20Number%20of%20Integers%20to%20Choose%20From%20a%20Range%20II/README.md) + + + +```python +class Solution: + def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: + banned.extend([0, n + 1]) + ban = sorted(x for x in set(banned) if x < n + 2) + ans = 0 + for i, j in pairwise(ban): + left, right = 0, j - i - 1 + while left < right: + mid = (left + right + 1) >> 1 + if (i + 1 + i + mid) * mid // 2 <= maxSum: + left = mid + else: + right = mid - 1 + ans += left + maxSum -= (i + 1 + i + left) * left // 2 + if maxSum <= 0: + break + return ans ``` +```java +class Solution { + public int maxCount(int[] banned, int n, int maxSum) { + Set black = new HashSet<>(); + black.add(0); + black.add(n + 1); + for (int x : banned) { + if (x < n + 2) { + black.add(x); + } + } + List ban = new ArrayList<>(black); + Collections.sort(ban); + int ans = 0; + for (int k = 1; k < ban.size(); ++k) { + int i = ban.get(k - 1), j = ban.get(k); + int left = 0, right = j - i - 1; + while (left < right) { + int mid = (left + right + 1) >>> 1; + if ((i + 1 + i + mid) * 1L * mid / 2 <= maxSum) { + left = mid; + } else { + right = mid - 1; + } + } + ans += left; + maxSum -= (i + 1 + i + left) * 1L * left / 2; + if (maxSum <= 0) { + break; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maxCount(vector& banned, int n, int maxSum) { + banned.push_back(0); + banned.push_back(n + 1); + sort(banned.begin(), banned.end()); + banned.erase(unique(banned.begin(), banned.end()), banned.end()); + banned.erase(remove_if(banned.begin(), banned.end(), [&](int x) { return x > n + 1; }), banned.end()); + int ans = 0; + for (int k = 1; k < banned.size(); ++k) { + int i = banned[k - 1], j = banned[k]; + int left = 0, right = j - i - 1; + while (left < right) { + int mid = left + ((right - left + 1) / 2); + if ((i + 1 + i + mid) * 1LL * mid / 2 <= maxSum) { + left = mid; + } else { + right = mid - 1; + } + } + ans += left; + maxSum -= (i + 1 + i + left) * 1LL * left / 2; + if (maxSum <= 0) { + break; + } + } + return ans; + } +}; +``` + +```go +func maxCount(banned []int, n int, maxSum int) (ans int) { + banned = append(banned, []int{0, n + 1}...) + sort.Ints(banned) + ban := []int{} + for i, x := range banned { + if (i > 0 && x == banned[i-1]) || x > n+1 { + continue + } + ban = append(ban, x) + } + for k := 1; k < len(ban); k++ { + i, j := ban[k-1], ban[k] + left, right := 0, j-i-1 + for left < right { + mid := (left + right + 1) >> 1 + if (i+1+i+mid)*mid/2 <= maxSum { + left = mid + } else { + right = mid - 1 + } + } + ans += left + maxSum -= (i + 1 + i + left) * left / 2 + if maxSum <= 0 { + break + } + } + return +} ``` + + diff --git a/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README_EN.md b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README_EN.md index 878463430cd78..fb41931dfc242 100644 --- a/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README_EN.md +++ b/solution/2500-2599/2554.Maximum Number of Integers to Choose From a Range I/README_EN.md @@ -53,7 +53,7 @@ They are from the range [1, 7], all did not appear in banned, and their sum is 2 ## Solutions -**Solution 1: Greedy + Enumeration** +### Solution 1: Greedy + Enumeration We use the variable $s$ to represent the sum of the currently selected integers, and the variable $ans$ to represent the number of currently selected integers. We convert the array `banned` into a hash table for easy determination of whether a certain integer is not selectable. @@ -63,24 +63,8 @@ Finally, we return $ans$. The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the given integer. -**Solution 2: Greedy + Binary Search** - -If $n$ is very large, the enumeration in Method One will time out. - -We can add $0$ and $n + 1$ to the array `banned`, deduplicate the array `banned`, remove elements greater than $n+1$, and then sort it. - -Next, we enumerate every two adjacent elements $i$ and $j$ in the array `banned`. The range of selectable integers is $[i + 1, j - 1]$. We use binary search to enumerate the number of elements we can select in this range, find the maximum number of selectable elements, and then add it to $ans$. At the same time, we subtract the sum of these elements from `maxSum`. If `maxSum` is less than $0$, we break the loop. Return the answer. - -The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array `banned`. - -Similar problems: - -- [2557. Maximum Number of Integers to Choose From a Range II](/solution/2500-2599/2557.Maximum%20Number%20of%20Integers%20to%20Choose%20From%20a%20Range%20II/README.md) - -### **Python3** - ```python class Solution: def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: @@ -95,29 +79,6 @@ class Solution: return ans ``` -```python -class Solution: - def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: - banned.extend([0, n + 1]) - ban = sorted(x for x in set(banned) if x < n + 2) - ans = 0 - for i, j in pairwise(ban): - left, right = 0, j - i - 1 - while left < right: - mid = (left + right + 1) >> 1 - if (i + 1 + i + mid) * mid // 2 <= maxSum: - left = mid - else: - right = mid - 1 - ans += left - maxSum -= (i + 1 + i + left) * left // 2 - if maxSum <= 0: - break - return ans -``` - -### **Java** - ```java class Solution { public int maxCount(int[] banned, int n, int maxSum) { @@ -137,44 +98,6 @@ class Solution { } ``` -```java -class Solution { - public int maxCount(int[] banned, int n, int maxSum) { - Set black = new HashSet<>(); - black.add(0); - black.add(n + 1); - for (int x : banned) { - if (x < n + 2) { - black.add(x); - } - } - List ban = new ArrayList<>(black); - Collections.sort(ban); - int ans = 0; - for (int k = 1; k < ban.size(); ++k) { - int i = ban.get(k - 1), j = ban.get(k); - int left = 0, right = j - i - 1; - while (left < right) { - int mid = (left + right + 1) >>> 1; - if ((i + 1 + i + mid) * 1L * mid / 2 <= maxSum) { - left = mid; - } else { - right = mid - 1; - } - } - ans += left; - maxSum -= (i + 1 + i + left) * 1L * left / 2; - if (maxSum <= 0) { - break; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -192,40 +115,6 @@ public: }; ``` -```cpp -class Solution { -public: - int maxCount(vector& banned, int n, int maxSum) { - banned.push_back(0); - banned.push_back(n + 1); - sort(banned.begin(), banned.end()); - banned.erase(unique(banned.begin(), banned.end()), banned.end()); - banned.erase(remove_if(banned.begin(), banned.end(), [&](int x) { return x > n + 1; }), banned.end()); - int ans = 0; - for (int k = 1; k < banned.size(); ++k) { - int i = banned[k - 1], j = banned[k]; - int left = 0, right = j - i - 1; - while (left < right) { - int mid = left + ((right - left + 1) / 2); - if ((i + 1 + i + mid) * 1LL * mid / 2 <= maxSum) { - left = mid; - } else { - right = mid - 1; - } - } - ans += left; - maxSum -= (i + 1 + i + left) * 1LL * left / 2; - if (maxSum <= 0) { - break; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func maxCount(banned []int, n int, maxSum int) (ans int) { ban := map[int]bool{} @@ -243,40 +132,6 @@ func maxCount(banned []int, n int, maxSum int) (ans int) { } ``` -```go -func maxCount(banned []int, n int, maxSum int) (ans int) { - banned = append(banned, []int{0, n + 1}...) - sort.Ints(banned) - ban := []int{} - for i, x := range banned { - if (i > 0 && x == banned[i-1]) || x > n+1 { - continue - } - ban = append(ban, x) - } - for k := 1; k < len(ban); k++ { - i, j := ban[k-1], ban[k] - left, right := 0, j-i-1 - for left < right { - mid := (left + right + 1) >> 1 - if (i+1+i+mid)*mid/2 <= maxSum { - left = mid - } else { - right = mid - 1 - } - } - ans += left - maxSum -= (i + 1 + i + left) * left / 2 - if maxSum <= 0 { - break - } - } - return -} -``` - -### **TypeScript** - ```ts function maxCount(banned: number[], n: number, maxSum: number): number { const set = new Set(banned); @@ -296,8 +151,6 @@ function maxCount(banned: number[], n: number, maxSum: number): number { } ``` -### **Rust** - ```rust use std::collections::HashSet; impl Solution { @@ -320,8 +173,6 @@ impl Solution { } ``` -### **C** - ```c int cmp(const void* a, const void* b) { return *(int*) a - *(int*) b; @@ -348,10 +199,145 @@ int maxCount(int* banned, int bannedSize, int n, int maxSum) { } ``` -### **...** + + +### Solution 2: Greedy + Binary Search + +If $n$ is very large, the enumeration in Method One will time out. + +We can add $0$ and $n + 1$ to the array `banned`, deduplicate the array `banned`, remove elements greater than $n+1$, and then sort it. + +Next, we enumerate every two adjacent elements $i$ and $j$ in the array `banned`. The range of selectable integers is $[i + 1, j - 1]$. We use binary search to enumerate the number of elements we can select in this range, find the maximum number of selectable elements, and then add it to $ans$. At the same time, we subtract the sum of these elements from `maxSum`. If `maxSum` is less than $0$, we break the loop. Return the answer. +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array `banned`. + +Similar problems: + +- [2557. Maximum Number of Integers to Choose From a Range II](/solution/2500-2599/2557.Maximum%20Number%20of%20Integers%20to%20Choose%20From%20a%20Range%20II/README.md) + + + +```python +class Solution: + def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: + banned.extend([0, n + 1]) + ban = sorted(x for x in set(banned) if x < n + 2) + ans = 0 + for i, j in pairwise(ban): + left, right = 0, j - i - 1 + while left < right: + mid = (left + right + 1) >> 1 + if (i + 1 + i + mid) * mid // 2 <= maxSum: + left = mid + else: + right = mid - 1 + ans += left + maxSum -= (i + 1 + i + left) * left // 2 + if maxSum <= 0: + break + return ans ``` +```java +class Solution { + public int maxCount(int[] banned, int n, int maxSum) { + Set black = new HashSet<>(); + black.add(0); + black.add(n + 1); + for (int x : banned) { + if (x < n + 2) { + black.add(x); + } + } + List ban = new ArrayList<>(black); + Collections.sort(ban); + int ans = 0; + for (int k = 1; k < ban.size(); ++k) { + int i = ban.get(k - 1), j = ban.get(k); + int left = 0, right = j - i - 1; + while (left < right) { + int mid = (left + right + 1) >>> 1; + if ((i + 1 + i + mid) * 1L * mid / 2 <= maxSum) { + left = mid; + } else { + right = mid - 1; + } + } + ans += left; + maxSum -= (i + 1 + i + left) * 1L * left / 2; + if (maxSum <= 0) { + break; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maxCount(vector& banned, int n, int maxSum) { + banned.push_back(0); + banned.push_back(n + 1); + sort(banned.begin(), banned.end()); + banned.erase(unique(banned.begin(), banned.end()), banned.end()); + banned.erase(remove_if(banned.begin(), banned.end(), [&](int x) { return x > n + 1; }), banned.end()); + int ans = 0; + for (int k = 1; k < banned.size(); ++k) { + int i = banned[k - 1], j = banned[k]; + int left = 0, right = j - i - 1; + while (left < right) { + int mid = left + ((right - left + 1) / 2); + if ((i + 1 + i + mid) * 1LL * mid / 2 <= maxSum) { + left = mid; + } else { + right = mid - 1; + } + } + ans += left; + maxSum -= (i + 1 + i + left) * 1LL * left / 2; + if (maxSum <= 0) { + break; + } + } + return ans; + } +}; +``` + +```go +func maxCount(banned []int, n int, maxSum int) (ans int) { + banned = append(banned, []int{0, n + 1}...) + sort.Ints(banned) + ban := []int{} + for i, x := range banned { + if (i > 0 && x == banned[i-1]) || x > n+1 { + continue + } + ban = append(ban, x) + } + for k := 1; k < len(ban); k++ { + i, j := ban[k-1], ban[k] + left, right := 0, j-i-1 + for left < right { + mid := (left + right + 1) >> 1 + if (i+1+i+mid)*mid/2 <= maxSum { + left = mid + } else { + right = mid - 1 + } + } + ans += left + maxSum -= (i + 1 + i + left) * left / 2 + if maxSum <= 0 { + break + } + } + return +} ``` + + diff --git a/solution/2500-2599/2555.Maximize Win From Two Segments/README.md b/solution/2500-2599/2555.Maximize Win From Two Segments/README.md index 7b2690d980d11..8d071c188a509 100644 --- a/solution/2500-2599/2555.Maximize Win From Two Segments/README.md +++ b/solution/2500-2599/2555.Maximize Win From Two Segments/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:动态规划 + 二分查找** +### 方法一:动态规划 + 二分查找 我们定义 $f[i]$ 表示在前 $i$ 个奖品中,选择一个长度为 $k$ 的线段,可以获得的最多奖品数目。初始时 $f[0] = 0$。定义答案变量 $ans = 0$。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def maximizeWin(self, prizePositions: List[int], k: int) -> int: @@ -78,10 +72,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximizeWin(int[] prizePositions, int k) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go func maximizeWin(prizePositions []int, k int) (ans int) { n := len(prizePositions) @@ -147,8 +133,6 @@ func maximizeWin(prizePositions []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function maximizeWin(prizePositions: number[], k: number): number { const n = prizePositions.length; @@ -177,10 +161,6 @@ function maximizeWin(prizePositions: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2555.Maximize Win From Two Segments/README_EN.md b/solution/2500-2599/2555.Maximize Win From Two Segments/README_EN.md index dfaff5208fc56..ef080f4a08470 100644 --- a/solution/2500-2599/2555.Maximize Win From Two Segments/README_EN.md +++ b/solution/2500-2599/2555.Maximize Win From Two Segments/README_EN.md @@ -52,7 +52,7 @@ ## Solutions -**Solution 1: Dynamic Programming + Binary Search** +### Solution 1: Dynamic Programming + Binary Search We define $f[i]$ as the maximum number of prizes that can be obtained by selecting a segment of length $k$ from the first $i$ prizes. Initially, $f[0] = 0$. We define the answer variable as $ans = 0$. @@ -64,8 +64,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def maximizeWin(self, prizePositions: List[int], k: int) -> int: @@ -79,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximizeWin(int[] prizePositions, int k) { @@ -111,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +125,6 @@ public: }; ``` -### **Go** - ```go func maximizeWin(prizePositions []int, k int) (ans int) { n := len(prizePositions) @@ -146,8 +138,6 @@ func maximizeWin(prizePositions []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function maximizeWin(prizePositions: number[], k: number): number { const n = prizePositions.length; @@ -176,10 +166,6 @@ function maximizeWin(prizePositions: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2556.Disconnect Path in a Binary Matrix by at Most One Flip/README.md b/solution/2500-2599/2556.Disconnect Path in a Binary Matrix by at Most One Flip/README.md index e208655e2d6ac..ea1874a1c2a61 100644 --- a/solution/2500-2599/2556.Disconnect Path in a Binary Matrix by at Most One Flip/README.md +++ b/solution/2500-2599/2556.Disconnect Path in a Binary Matrix by at Most One Flip/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:两次 DFS** +### 方法一:两次 DFS 我们先进行一次 DFS,判断从 $(0, 0)$ 到 $(m - 1, n - 1)$ 是否存在路径,记结果为 $a$。在 DFS 的过程中,我们将访问过的格子的值置为 $0$,以防止重复访问。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def isPossibleToCutPath(self, grid: List[List[int]]) -> bool: @@ -86,10 +80,6 @@ class Solution: return not (a and b) ``` -### **Java** - - - ```java class Solution { private int[][] grid; @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go func isPossibleToCutPath(grid [][]int) bool { m, n := len(grid), len(grid[0]) @@ -168,8 +154,6 @@ func isPossibleToCutPath(grid [][]int) bool { } ``` -### **TypeScript** - ```ts function isPossibleToCutPath(grid: number[][]): boolean { const m = grid.length; @@ -193,10 +177,6 @@ function isPossibleToCutPath(grid: number[][]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2556.Disconnect Path in a Binary Matrix by at Most One Flip/README_EN.md b/solution/2500-2599/2556.Disconnect Path in a Binary Matrix by at Most One Flip/README_EN.md index e49995296af62..63d0de5e4b58c 100644 --- a/solution/2500-2599/2556.Disconnect Path in a Binary Matrix by at Most One Flip/README_EN.md +++ b/solution/2500-2599/2556.Disconnect Path in a Binary Matrix by at Most One Flip/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Two DFS Traversals** +### Solution 1: Two DFS Traversals First, we perform a DFS traversal to determine whether there is a path from $(0, 0)$ to $(m - 1, n - 1)$, and we denote the result as $a$. During the DFS process, we set the value of the visited cells to $0$ to prevent revisiting. @@ -55,8 +55,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times -### **Python3** - ```python class Solution: def isPossibleToCutPath(self, grid: List[List[int]]) -> bool: @@ -75,8 +73,6 @@ class Solution: return not (a and b) ``` -### **Java** - ```java class Solution { private int[][] grid; @@ -107,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +126,6 @@ public: }; ``` -### **Go** - ```go func isPossibleToCutPath(grid [][]int) bool { m, n := len(grid), len(grid[0]) @@ -155,8 +147,6 @@ func isPossibleToCutPath(grid [][]int) bool { } ``` -### **TypeScript** - ```ts function isPossibleToCutPath(grid: number[][]): boolean { const m = grid.length; @@ -180,10 +170,6 @@ function isPossibleToCutPath(grid: number[][]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2557.Maximum Number of Integers to Choose From a Range II/README.md b/solution/2500-2599/2557.Maximum Number of Integers to Choose From a Range II/README.md index 64fe3f11a4036..8989a64cc4869 100644 --- a/solution/2500-2599/2557.Maximum Number of Integers to Choose From a Range II/README.md +++ b/solution/2500-2599/2557.Maximum Number of Integers to Choose From a Range II/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:去重 + 排序 + 二分查找** +### 方法一:去重 + 排序 + 二分查找 我们可以在数组 `banned` 中加入 $0$ 和 $n + 1$,将数组 `banned` 去重并排序。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxCount(int[] banned, int n, long maxSum) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func maxCount(banned []int, n int, maxSum int64) (ans int) { banned = append(banned, []int{0, n + 1}...) @@ -191,10 +177,6 @@ func maxCount(banned []int, n int, maxSum int64) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2557.Maximum Number of Integers to Choose From a Range II/README_EN.md b/solution/2500-2599/2557.Maximum Number of Integers to Choose From a Range II/README_EN.md index 1d33a80d7660e..c3cbd2f9b6afa 100644 --- a/solution/2500-2599/2557.Maximum Number of Integers to Choose From a Range II/README_EN.md +++ b/solution/2500-2599/2557.Maximum Number of Integers to Choose From a Range II/README_EN.md @@ -45,7 +45,7 @@ All these integers are in the range [1, 7], all do not appear in banned, and the ## Solutions -**Solution 1: Deduplication + Sorting + Binary Search** +### Solution 1: Deduplication + Sorting + Binary Search We can add $0$ and $n + 1$ to the array `banned`, then deduplicate and sort the array `banned`. @@ -55,8 +55,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: @@ -78,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxCount(int[] banned, int n, long maxSum) { @@ -114,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +141,6 @@ public: }; ``` -### **Go** - ```go func maxCount(banned []int, n int, maxSum int64) (ans int) { banned = append(banned, []int{0, n + 1}...) @@ -181,10 +173,6 @@ func maxCount(banned []int, n int, maxSum int64) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2558.Take Gifts From the Richest Pile/README.md b/solution/2500-2599/2558.Take Gifts From the Richest Pile/README.md index ea086a1832624..a097238270891 100644 --- a/solution/2500-2599/2558.Take Gifts From the Richest Pile/README.md +++ b/solution/2500-2599/2558.Take Gifts From the Richest Pile/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:优先队列(大根堆)** +### 方法一:优先队列(大根堆) 我们将数组 $gifts$ 转存到大根堆中,然后循环 $k$ 次,每次取出堆顶元素,将堆顶元素开根号的结果再放入堆中。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def pickGifts(self, gifts: List[int], k: int) -> int: @@ -81,10 +75,6 @@ class Solution: return -sum(h) ``` -### **Java** - - - ```java class Solution { public long pickGifts(int[] gifts, int k) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func pickGifts(gifts []int, k int) (ans int64) { h := &hp{gifts} @@ -144,8 +130,6 @@ func (hp) Pop() (_ any) { return } func (hp) Push(any) {} ``` -### **TypeScript** - ```ts function pickGifts(gifts: number[], k: number): number { const pq = new MaxPriorityQueue(); @@ -163,8 +147,6 @@ function pickGifts(gifts: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn pick_gifts(gifts: Vec, k: i32) -> i64 { @@ -187,10 +169,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2558.Take Gifts From the Richest Pile/README_EN.md b/solution/2500-2599/2558.Take Gifts From the Richest Pile/README_EN.md index f5c818f573f3e..7ee26ac05436f 100644 --- a/solution/2500-2599/2558.Take Gifts From the Richest Pile/README_EN.md +++ b/solution/2500-2599/2558.Take Gifts From the Richest Pile/README_EN.md @@ -51,7 +51,7 @@ So, the total gifts remaining are 4. ## Solutions -**Solution 1: Priority Queue (Max Heap)** +### Solution 1: Priority Queue (Max Heap) We can store the array $gifts$ in a max heap, and then loop $k$ times, each time taking out the top element of the heap, taking the square root of it, and putting the result back into the heap. @@ -61,8 +61,6 @@ The time complexity is $O(n + k \times \log n)$, and the space complexity is $O( -### **Python3** - ```python class Solution: def pickGifts(self, gifts: List[int], k: int) -> int: @@ -73,8 +71,6 @@ class Solution: return -sum(h) ``` -### **Java** - ```java class Solution { public long pickGifts(int[] gifts, int k) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +105,6 @@ public: }; ``` -### **Go** - ```go func pickGifts(gifts []int, k int) (ans int64) { h := &hp{gifts} @@ -134,8 +126,6 @@ func (hp) Pop() (_ any) { return } func (hp) Push(any) {} ``` -### **TypeScript** - ```ts function pickGifts(gifts: number[], k: number): number { const pq = new MaxPriorityQueue(); @@ -153,8 +143,6 @@ function pickGifts(gifts: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn pick_gifts(gifts: Vec, k: i32) -> i64 { @@ -177,10 +165,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2559.Count Vowel Strings in Ranges/README.md b/solution/2500-2599/2559.Count Vowel Strings in Ranges/README.md index 4c27d05168ffa..27b5e1e9901dc 100644 --- a/solution/2500-2599/2559.Count Vowel Strings in Ranges/README.md +++ b/solution/2500-2599/2559.Count Vowel Strings in Ranges/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:预处理 + 二分查找** +### 方法一:预处理 + 二分查找 我们可以预处理出所有以元音开头和结尾的字符串的下标,按顺序记录在数组 $nums$ 中。 @@ -60,22 +58,8 @@ 时间复杂度 $O(n + m \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 和 $m$ 分别是数组 $words$ 和 $queries$ 的长度。 -**方法二:前缀和** - -我们可以创建一个长度为 $n+1$ 的前缀和数组 $s$,其中 $s[i]$ 表示数组 $words$ 的前 $i$ 个字符串中以元音开头和结尾的字符串的数目。初始时 $s[0] = 0$。 - -接下来,我们遍历数组 $words$,如果当前字符串以元音开头和结尾,那么 $s[i+1] = s[i] + 1$,否则 $s[i+1] = s[i]$。 - -最后,我们遍历每个查询 $(l, r)$,那么当前查询的答案就是 $s[r+1] - s[l]$。 - -时间复杂度 $O(n + m)$,空间复杂度 $O(n)$。其中 $n$ 和 $m$ 分别是数组 $words$ 和 $queries$ 的长度。 - -### **Python3** - - - ```python class Solution: def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: @@ -84,22 +68,6 @@ class Solution: return [bisect_right(nums, r) - bisect_left(nums, l) for l, r in queries] ``` -```python -class Solution: - def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: - vowels = set("aeiou") - s = list( - accumulate( - (int(w[0] in vowels and w[-1] in vowels) for w in words), initial=0 - ) - ) - return [s[r + 1] - s[l] for l, r in queries] -``` - -### **Java** - - - ```java class Solution { private List nums = new ArrayList<>(); @@ -136,29 +104,6 @@ class Solution { } ``` -```java -class Solution { - public int[] vowelStrings(String[] words, int[][] queries) { - Set vowels = Set.of('a', 'e', 'i', 'o', 'u'); - int n = words.length; - int[] s = new int[n + 1]; - for (int i = 0; i < n; ++i) { - char a = words[i].charAt(0), b = words[i].charAt(words[i].length() - 1); - s[i + 1] = s[i] + (vowels.contains(a) && vowels.contains(b) ? 1 : 0); - } - int m = queries.length; - int[] ans = new int[m]; - for (int i = 0; i < m; ++i) { - int l = queries[i][0], r = queries[i][1]; - ans[i] = s[r + 1] - s[l]; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -182,30 +127,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector vowelStrings(vector& words, vector>& queries) { - unordered_set vowels = {'a', 'e', 'i', 'o', 'u'}; - int n = words.size(); - int s[n + 1]; - s[0] = 0; - for (int i = 0; i < n; ++i) { - char a = words[i][0], b = words[i].back(); - s[i + 1] = s[i] + (vowels.count(a) && vowels.count(b)); - } - vector ans; - for (auto& q : queries) { - int l = q[0], r = q[1]; - ans.push_back(s[r + 1] - s[l]); - } - return ans; - } -}; -``` - -### **Go** - ```go func vowelStrings(words []string, queries [][]int) []int { vowels := map[byte]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true} @@ -224,29 +145,6 @@ func vowelStrings(words []string, queries [][]int) []int { } ``` -```go -func vowelStrings(words []string, queries [][]int) []int { - vowels := map[byte]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true} - n := len(words) - s := make([]int, n+1) - for i, w := range words { - x := 0 - if vowels[w[0]] && vowels[w[len(w)-1]] { - x = 1 - } - s[i+1] = s[i] + x - } - ans := make([]int, len(queries)) - for i, q := range queries { - l, r := q[0], q[1] - ans[i] = s[r+1] - s[l] - } - return ans -} -``` - -### **TypeScript** - ```ts function vowelStrings(words: string[], queries: number[][]): number[] { const vowels = new Set(['a', 'e', 'i', 'o', 'u']); @@ -273,6 +171,96 @@ function vowelStrings(words: string[], queries: number[][]): number[] { } ``` + + +### 方法二:前缀和 + +我们可以创建一个长度为 $n+1$ 的前缀和数组 $s$,其中 $s[i]$ 表示数组 $words$ 的前 $i$ 个字符串中以元音开头和结尾的字符串的数目。初始时 $s[0] = 0$。 + +接下来,我们遍历数组 $words$,如果当前字符串以元音开头和结尾,那么 $s[i+1] = s[i] + 1$,否则 $s[i+1] = s[i]$。 + +最后,我们遍历每个查询 $(l, r)$,那么当前查询的答案就是 $s[r+1] - s[l]$。 + +时间复杂度 $O(n + m)$,空间复杂度 $O(n)$。其中 $n$ 和 $m$ 分别是数组 $words$ 和 $queries$ 的长度。 + + + +```python +class Solution: + def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: + vowels = set("aeiou") + s = list( + accumulate( + (int(w[0] in vowels and w[-1] in vowels) for w in words), initial=0 + ) + ) + return [s[r + 1] - s[l] for l, r in queries] +``` + +```java +class Solution { + public int[] vowelStrings(String[] words, int[][] queries) { + Set vowels = Set.of('a', 'e', 'i', 'o', 'u'); + int n = words.length; + int[] s = new int[n + 1]; + for (int i = 0; i < n; ++i) { + char a = words[i].charAt(0), b = words[i].charAt(words[i].length() - 1); + s[i + 1] = s[i] + (vowels.contains(a) && vowels.contains(b) ? 1 : 0); + } + int m = queries.length; + int[] ans = new int[m]; + for (int i = 0; i < m; ++i) { + int l = queries[i][0], r = queries[i][1]; + ans[i] = s[r + 1] - s[l]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector vowelStrings(vector& words, vector>& queries) { + unordered_set vowels = {'a', 'e', 'i', 'o', 'u'}; + int n = words.size(); + int s[n + 1]; + s[0] = 0; + for (int i = 0; i < n; ++i) { + char a = words[i][0], b = words[i].back(); + s[i + 1] = s[i] + (vowels.count(a) && vowels.count(b)); + } + vector ans; + for (auto& q : queries) { + int l = q[0], r = q[1]; + ans.push_back(s[r + 1] - s[l]); + } + return ans; + } +}; +``` + +```go +func vowelStrings(words []string, queries [][]int) []int { + vowels := map[byte]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true} + n := len(words) + s := make([]int, n+1) + for i, w := range words { + x := 0 + if vowels[w[0]] && vowels[w[len(w)-1]] { + x = 1 + } + s[i+1] = s[i] + x + } + ans := make([]int, len(queries)) + for i, q := range queries { + l, r := q[0], q[1] + ans[i] = s[r+1] - s[l] + } + return ans +} +``` + ```ts function vowelStrings(words: string[], queries: number[][]): number[] { const vowels = new Set(['a', 'e', 'i', 'o', 'u']); @@ -289,10 +277,6 @@ function vowelStrings(words: string[], queries: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2559.Count Vowel Strings in Ranges/README_EN.md b/solution/2500-2599/2559.Count Vowel Strings in Ranges/README_EN.md index f3776374c4fa7..825692f92b955 100644 --- a/solution/2500-2599/2559.Count Vowel Strings in Ranges/README_EN.md +++ b/solution/2500-2599/2559.Count Vowel Strings in Ranges/README_EN.md @@ -46,7 +46,7 @@ We return [2,3,0]. ## Solutions -**Solution 1: Preprocessing + Binary Search** +### Solution 1: Preprocessing + Binary Search We can preprocess all the indices of the strings that start and end with a vowel, and record them in order in the array $nums$. @@ -54,20 +54,8 @@ Next, we iterate through each query $(l, r)$, and use binary search to find the The time complexity is $O(n + m \times \log n)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of the arrays $words$ and $queries$, respectively. -**Solution 2: Prefix Sum** - -We can create a prefix sum array $s$ of length $n+1$, where $s[i]$ represents the number of strings that start and end with a vowel in the first $i$ strings of the array $words$. Initially, $s[0] = 0$. - -Next, we iterate through the array $words$. If the current string starts and ends with a vowel, then $s[i+1] = s[i] + 1$, otherwise $s[i+1] = s[i]$. - -Finally, we iterate through each query $(l, r)$. Therefore, the answer to the current query is $s[r+1] - s[l]$. - -The time complexity is $O(n + m)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of the arrays $words$ and $queries$, respectively. - -### **Python3** - ```python class Solution: def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: @@ -76,20 +64,6 @@ class Solution: return [bisect_right(nums, r) - bisect_left(nums, l) for l, r in queries] ``` -```python -class Solution: - def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: - vowels = set("aeiou") - s = list( - accumulate( - (int(w[0] in vowels and w[-1] in vowels) for w in words), initial=0 - ) - ) - return [s[r + 1] - s[l] for l, r in queries] -``` - -### **Java** - ```java class Solution { private List nums = new ArrayList<>(); @@ -126,29 +100,6 @@ class Solution { } ``` -```java -class Solution { - public int[] vowelStrings(String[] words, int[][] queries) { - Set vowels = Set.of('a', 'e', 'i', 'o', 'u'); - int n = words.length; - int[] s = new int[n + 1]; - for (int i = 0; i < n; ++i) { - char a = words[i].charAt(0), b = words[i].charAt(words[i].length() - 1); - s[i + 1] = s[i] + (vowels.contains(a) && vowels.contains(b) ? 1 : 0); - } - int m = queries.length; - int[] ans = new int[m]; - for (int i = 0; i < m; ++i) { - int l = queries[i][0], r = queries[i][1]; - ans[i] = s[r + 1] - s[l]; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -172,30 +123,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector vowelStrings(vector& words, vector>& queries) { - unordered_set vowels = {'a', 'e', 'i', 'o', 'u'}; - int n = words.size(); - int s[n + 1]; - s[0] = 0; - for (int i = 0; i < n; ++i) { - char a = words[i][0], b = words[i].back(); - s[i + 1] = s[i] + (vowels.count(a) && vowels.count(b)); - } - vector ans; - for (auto& q : queries) { - int l = q[0], r = q[1]; - ans.push_back(s[r + 1] - s[l]); - } - return ans; - } -}; -``` - -### **Go** - ```go func vowelStrings(words []string, queries [][]int) []int { vowels := map[byte]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true} @@ -214,29 +141,6 @@ func vowelStrings(words []string, queries [][]int) []int { } ``` -```go -func vowelStrings(words []string, queries [][]int) []int { - vowels := map[byte]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true} - n := len(words) - s := make([]int, n+1) - for i, w := range words { - x := 0 - if vowels[w[0]] && vowels[w[len(w)-1]] { - x = 1 - } - s[i+1] = s[i] + x - } - ans := make([]int, len(queries)) - for i, q := range queries { - l, r := q[0], q[1] - ans[i] = s[r+1] - s[l] - } - return ans -} -``` - -### **TypeScript** - ```ts function vowelStrings(words: string[], queries: number[][]): number[] { const vowels = new Set(['a', 'e', 'i', 'o', 'u']); @@ -263,6 +167,96 @@ function vowelStrings(words: string[], queries: number[][]): number[] { } ``` + + +### Solution 2: Prefix Sum + +We can create a prefix sum array $s$ of length $n+1$, where $s[i]$ represents the number of strings that start and end with a vowel in the first $i$ strings of the array $words$. Initially, $s[0] = 0$. + +Next, we iterate through the array $words$. If the current string starts and ends with a vowel, then $s[i+1] = s[i] + 1$, otherwise $s[i+1] = s[i]$. + +Finally, we iterate through each query $(l, r)$. Therefore, the answer to the current query is $s[r+1] - s[l]$. + +The time complexity is $O(n + m)$, and the space complexity is $O(n)$. Where $n$ and $m$ are the lengths of the arrays $words$ and $queries$, respectively. + + + +```python +class Solution: + def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: + vowels = set("aeiou") + s = list( + accumulate( + (int(w[0] in vowels and w[-1] in vowels) for w in words), initial=0 + ) + ) + return [s[r + 1] - s[l] for l, r in queries] +``` + +```java +class Solution { + public int[] vowelStrings(String[] words, int[][] queries) { + Set vowels = Set.of('a', 'e', 'i', 'o', 'u'); + int n = words.length; + int[] s = new int[n + 1]; + for (int i = 0; i < n; ++i) { + char a = words[i].charAt(0), b = words[i].charAt(words[i].length() - 1); + s[i + 1] = s[i] + (vowels.contains(a) && vowels.contains(b) ? 1 : 0); + } + int m = queries.length; + int[] ans = new int[m]; + for (int i = 0; i < m; ++i) { + int l = queries[i][0], r = queries[i][1]; + ans[i] = s[r + 1] - s[l]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + vector vowelStrings(vector& words, vector>& queries) { + unordered_set vowels = {'a', 'e', 'i', 'o', 'u'}; + int n = words.size(); + int s[n + 1]; + s[0] = 0; + for (int i = 0; i < n; ++i) { + char a = words[i][0], b = words[i].back(); + s[i + 1] = s[i] + (vowels.count(a) && vowels.count(b)); + } + vector ans; + for (auto& q : queries) { + int l = q[0], r = q[1]; + ans.push_back(s[r + 1] - s[l]); + } + return ans; + } +}; +``` + +```go +func vowelStrings(words []string, queries [][]int) []int { + vowels := map[byte]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true} + n := len(words) + s := make([]int, n+1) + for i, w := range words { + x := 0 + if vowels[w[0]] && vowels[w[len(w)-1]] { + x = 1 + } + s[i+1] = s[i] + x + } + ans := make([]int, len(queries)) + for i, q := range queries { + l, r := q[0], q[1] + ans[i] = s[r+1] - s[l] + } + return ans +} +``` + ```ts function vowelStrings(words: string[], queries: number[][]): number[] { const vowels = new Set(['a', 'e', 'i', 'o', 'u']); @@ -279,10 +273,6 @@ function vowelStrings(words: string[], queries: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2560.House Robber IV/README.md b/solution/2500-2599/2560.House Robber IV/README.md index 0b1b27b5eee0d..69a9f2811fd97 100644 --- a/solution/2500-2599/2560.House Robber IV/README.md +++ b/solution/2500-2599/2560.House Robber IV/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:二分查找 + 贪心** +### 方法一:二分查找 + 贪心 题目求的是窃贼的最小窃取能力,我们可以二分枚举窃贼的窃取能力,对于枚举的能力 $x$,我们可以通过贪心的方式判断窃贼是否能够窃取至少 $k$ 间房屋,具体地,我们从左到右遍历数组,对于当前遍历到的房屋 $i$,如果 $nums[i] \leq x$ 且 $i$ 与上一个窃取的房屋的下标之差大于 $1$,则窃贼可以窃取房屋 $i$,否则窃贼不能窃取房屋 $i$。累计窃取的房屋数,如果窃取的房屋数大于等于 $k$,则说明窃贼可以窃取至少 $k$ 间房屋,此时窃贼的窃取能力 $x$ 可能是最小的,否则窃贼的窃取能力 $x$ 不是最小的。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def minCapability(self, nums: List[int], k: int) -> int: @@ -82,10 +76,6 @@ class Solution: return bisect_left(range(max(nums) + 1), True, key=f) ``` -### **Java** - - - ```java class Solution { public int minCapability(int[] nums, int k) { @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func minCapability(nums []int, k int) int { return sort.Search(1e9+1, func(x int) bool { @@ -164,8 +150,6 @@ func minCapability(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function minCapability(nums: number[], k: number): number { const f = (mx: number): boolean => { @@ -194,10 +178,6 @@ function minCapability(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2560.House Robber IV/README_EN.md b/solution/2500-2599/2560.House Robber IV/README_EN.md index b6de0149293e4..bf4fd91bfec44 100644 --- a/solution/2500-2599/2560.House Robber IV/README_EN.md +++ b/solution/2500-2599/2560.House Robber IV/README_EN.md @@ -47,7 +47,7 @@ Therefore, we return min(5, 9, 9) = 5. ## Solutions -**Solution 1: Binary Search + Greedy** +### Solution 1: Binary Search + Greedy The problem is asking for the minimum stealing ability of the thief. We can use binary search to enumerate the stealing ability of the thief. For the enumerated ability $x$, we can use a greedy approach to determine whether the thief can steal at least $k$ houses. Specifically, we traverse the array from left to right. For the current house $i$ we are traversing, if $nums[i] \leq x$ and the difference between the index of $i$ and the last stolen house is greater than $1$, then the thief can steal house $i$. Otherwise, the thief cannot steal house $i$. We accumulate the number of stolen houses. If the number of stolen houses is greater than or equal to $k$, it means that the thief can steal at least $k$ houses, and at this time, the stealing ability $x$ of the thief might be the minimum. Otherwise, the stealing ability $x$ of the thief is not the minimum. @@ -55,8 +55,6 @@ The time complexity is $O(n \times \log m)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def minCapability(self, nums: List[int], k: int) -> int: @@ -72,8 +70,6 @@ class Solution: return bisect_left(range(max(nums) + 1), True, key=f) ``` -### **Java** - ```java class Solution { public int minCapability(int[] nums, int k) { @@ -103,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +128,6 @@ public: }; ``` -### **Go** - ```go func minCapability(nums []int, k int) int { return sort.Search(1e9+1, func(x int) bool { @@ -152,8 +144,6 @@ func minCapability(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function minCapability(nums: number[], k: number): number { const f = (mx: number): boolean => { @@ -182,10 +172,6 @@ function minCapability(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2561.Rearranging Fruits/README.md b/solution/2500-2599/2561.Rearranging Fruits/README.md index f8668e2d068e9..277370361160e 100644 --- a/solution/2500-2599/2561.Rearranging Fruits/README.md +++ b/solution/2500-2599/2561.Rearranging Fruits/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:贪心 + 构造** +### 方法一:贪心 + 构造 我们可以先将两个数组中共有的元素去掉,对于剩下的每个数字,其出现的次数必须为偶数,否则无法构造出相同的数组。不妨记去除共有元素后,两数组分别为 $a$ 和 $b$。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def minCost(self, basket1: List[int], basket2: List[int]) -> int: @@ -87,10 +81,6 @@ class Solution: return sum(min(x, mi * 2) for x in nums[:m]) ``` -### **Java** - - - ```java class Solution { public long minCost(int[] basket1, int[] basket2) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func minCost(basket1 []int, basket2 []int) (ans int64) { cnt := map[int]int{} @@ -193,10 +179,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2561.Rearranging Fruits/README_EN.md b/solution/2500-2599/2561.Rearranging Fruits/README_EN.md index efef0eca17d32..ff367f66f881a 100644 --- a/solution/2500-2599/2561.Rearranging Fruits/README_EN.md +++ b/solution/2500-2599/2561.Rearranging Fruits/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Greedy + Construction** +### Solution 1: Greedy + Construction First, we can remove the common elements from both arrays. For the remaining numbers, the occurrence of each number must be even, otherwise, it is impossible to construct identical arrays. Let's denote the arrays after removing common elements as $a$ and $b$. @@ -59,8 +59,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def minCost(self, basket1: List[int], basket2: List[int]) -> int: @@ -79,8 +77,6 @@ class Solution: return sum(min(x, mi * 2) for x in nums[:m]) ``` -### **Java** - ```java class Solution { public long minCost(int[] basket1, int[] basket2) { @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +141,6 @@ public: }; ``` -### **Go** - ```go func minCost(basket1 []int, basket2 []int) (ans int64) { cnt := map[int]int{} @@ -183,10 +175,6 @@ func abs(x int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2562.Find the Array Concatenation Value/README.md b/solution/2500-2599/2562.Find the Array Concatenation Value/README.md index 96423dbef5673..89f18a34f7061 100644 --- a/solution/2500-2599/2562.Find the Array Concatenation Value/README.md +++ b/solution/2500-2599/2562.Find the Array Concatenation Value/README.md @@ -73,9 +73,7 @@ nums 只有一个元素,所以我们选中 13 并将其加到串联值上, ## 解法 - - -**方法一:模拟** +### 方法一:模拟 从数组两端开始,每次取出一个元素,将其与另一个元素拼接,然后将拼接后的结果加到答案中。重复这个过程,直到数组为空。 @@ -83,10 +81,6 @@ nums 只有一个元素,所以我们选中 13 并将其加到串联值上, -### **Python3** - - - ```python class Solution: def findTheArrayConcVal(self, nums: List[int]) -> int: @@ -100,10 +94,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long findTheArrayConcVal(int[] nums) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +127,6 @@ public: }; ``` -### **Go** - ```go func findTheArrayConcVal(nums []int) (ans int64) { i, j := 0, len(nums)-1 @@ -155,8 +141,6 @@ func findTheArrayConcVal(nums []int) (ans int64) { } ``` -### **TypeScript** - ```ts function findTheArrayConcVal(nums: number[]): number { const n = nums.length; @@ -175,8 +159,6 @@ function findTheArrayConcVal(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn find_the_array_conc_val(nums: Vec) -> i64 { @@ -197,29 +179,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn find_the_array_conc_val(nums: Vec) -> i64 { - let mut ans = 0; - let mut n = nums.len(); - - for i in 0..n / 2 { - ans += format!("{}{}", nums[i], nums[n - i - 1]) - .parse::() - .unwrap(); - } - - if n % 2 != 0 { - ans += nums[n / 2] as i64; - } - - ans - } -} -``` - -### **C** - ```c int getLen(int num) { int res = 0; @@ -246,10 +205,33 @@ long long findTheArrayConcVal(int* nums, int numsSize) { } ``` -### **...** + -``` +### 方法二 + + +```rust +impl Solution { + pub fn find_the_array_conc_val(nums: Vec) -> i64 { + let mut ans = 0; + let mut n = nums.len(); + + for i in 0..n / 2 { + ans += format!("{}{}", nums[i], nums[n - i - 1]) + .parse::() + .unwrap(); + } + + if n % 2 != 0 { + ans += nums[n / 2] as i64; + } + + ans + } +} ``` + + diff --git a/solution/2500-2599/2562.Find the Array Concatenation Value/README_EN.md b/solution/2500-2599/2562.Find the Array Concatenation Value/README_EN.md index e599f7e4c12ba..7abc3fcd941ed 100644 --- a/solution/2500-2599/2562.Find the Array Concatenation Value/README_EN.md +++ b/solution/2500-2599/2562.Find the Array Concatenation Value/README_EN.md @@ -78,7 +78,7 @@ Since the concatenation value is 673 so the answer is 673. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation Starting from both ends of the array, we take out one element at a time, concatenate it with another element, and then add the concatenated result to the answer. We repeat this process until the array is empty. @@ -86,8 +86,6 @@ The time complexity is $O(n \times \log M)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def findTheArrayConcVal(self, nums: List[int]) -> int: @@ -101,8 +99,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long findTheArrayConcVal(int[] nums) { @@ -119,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +132,6 @@ public: }; ``` -### **Go** - ```go func findTheArrayConcVal(nums []int) (ans int64) { i, j := 0, len(nums)-1 @@ -154,8 +146,6 @@ func findTheArrayConcVal(nums []int) (ans int64) { } ``` -### **TypeScript** - ```ts function findTheArrayConcVal(nums: number[]): number { const n = nums.length; @@ -174,8 +164,6 @@ function findTheArrayConcVal(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn find_the_array_conc_val(nums: Vec) -> i64 { @@ -196,29 +184,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn find_the_array_conc_val(nums: Vec) -> i64 { - let mut ans = 0; - let mut n = nums.len(); - - for i in 0..n / 2 { - ans += format!("{}{}", nums[i], nums[n - i - 1]) - .parse::() - .unwrap(); - } - - if n % 2 != 0 { - ans += nums[n / 2] as i64; - } - - ans - } -} -``` - -### **C** - ```c int getLen(int num) { int res = 0; @@ -245,10 +210,33 @@ long long findTheArrayConcVal(int* nums, int numsSize) { } ``` -### **...** + -``` +### Solution 2 + + + +```rust +impl Solution { + pub fn find_the_array_conc_val(nums: Vec) -> i64 { + let mut ans = 0; + let mut n = nums.len(); + + for i in 0..n / 2 { + ans += format!("{}{}", nums[i], nums[n - i - 1]) + .parse::() + .unwrap(); + } + if n % 2 != 0 { + ans += nums[n / 2] as i64; + } + + ans + } +} ``` + + diff --git a/solution/2500-2599/2563.Count the Number of Fair Pairs/README.md b/solution/2500-2599/2563.Count the Number of Fair Pairs/README.md index e16d4de115741..2076db8997bbf 100644 --- a/solution/2500-2599/2563.Count the Number of Fair Pairs/README.md +++ b/solution/2500-2599/2563.Count the Number of Fair Pairs/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 我们先对数组 `nums` 按照升序排序,然后枚举 `nums[i]`,对于每个 `nums[i]`,我们通过二分查找找到 `nums[j]` 的下界 `j`,即第一个满足 `nums[j] >= lower - nums[i]` 的下标,然后再通过二分查找找到 `nums[k]` 的下界 `k`,即第一个满足 `nums[k] >= upper - nums[i] + 1` 的下标,那么 `[j, k)` 即为 `nums[j]` 满足 `lower <= nums[i] + nums[j] <= upper` 的下标范围,这些下标对应的 `nums[j]` 的个数即为 `k - j`,将其累加到答案中即可。注意 $j \gt i$。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int: @@ -72,10 +66,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long countFairPairs(int[] nums, int lower, int upper) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func countFairPairs(nums []int, lower int, upper int) (ans int64) { sort.Ints(nums) @@ -137,8 +123,6 @@ func countFairPairs(nums []int, lower int, upper int) (ans int64) { } ``` -### **TypeScript** - ```ts function countFairPairs(nums: number[], lower: number, upper: number): number { const search = (x: number, l: number): number => { @@ -165,10 +149,6 @@ function countFairPairs(nums: number[], lower: number, upper: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2563.Count the Number of Fair Pairs/README_EN.md b/solution/2500-2599/2563.Count the Number of Fair Pairs/README_EN.md index 8a59796b9ce61..d8b6dbcf16db8 100644 --- a/solution/2500-2599/2563.Count the Number of Fair Pairs/README_EN.md +++ b/solution/2500-2599/2563.Count the Number of Fair Pairs/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Sorting + Binary Search** +### Solution 1: Sorting + Binary Search First, we sort the array `nums` in ascending order. Then, for each `nums[i]`, we use binary search to find the lower bound `j` of `nums[j]`, i.e., the first index that satisfies `nums[j] >= lower - nums[i]`. Then, we use binary search again to find the lower bound `k` of `nums[k]`, i.e., the first index that satisfies `nums[k] >= upper - nums[i] + 1`. Therefore, `[j, k)` is the index range for `nums[j]` that satisfies `lower <= nums[i] + nums[j] <= upper`. The count of these indices corresponding to `nums[j]` is `k - j`, and we can add this to the answer. Note that $j > i$. @@ -50,8 +50,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int: @@ -64,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long countFairPairs(int[] nums, int lower, int upper) { @@ -95,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +107,6 @@ public: }; ``` -### **Go** - ```go func countFairPairs(nums []int, lower int, upper int) (ans int64) { sort.Ints(nums) @@ -127,8 +119,6 @@ func countFairPairs(nums []int, lower int, upper int) (ans int64) { } ``` -### **TypeScript** - ```ts function countFairPairs(nums: number[], lower: number, upper: number): number { const search = (x: number, l: number): number => { @@ -155,10 +145,6 @@ function countFairPairs(nums: number[], lower: number, upper: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2564.Substring XOR Queries/README.md b/solution/2500-2599/2564.Substring XOR Queries/README.md index c318f3511e8eb..559a27a93ea44 100644 --- a/solution/2500-2599/2564.Substring XOR Queries/README.md +++ b/solution/2500-2599/2564.Substring XOR Queries/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:预处理 + 枚举** +### 方法一:预处理 + 枚举 我们可以先预处理出所有长度为 $1$ 到 $32$ 的子串对应的十进制值,找到每个值对应的最小下标以及对应的右端点下标,存放在哈希表 $d$ 中。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def substringXorQueries(self, s: str, queries: List[List[int]]) -> List[List[int]]: @@ -91,10 +85,6 @@ class Solution: return [d.get(first ^ second, [-1, -1]) for first, second in queries] ``` -### **Java** - - - ```java class Solution { public int[][] substringXorQueries(String s, int[][] queries) { @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func substringXorQueries(s string, queries [][]int) (ans [][]int) { d := map[int][]int{} @@ -187,10 +173,6 @@ func substringXorQueries(s string, queries [][]int) (ans [][]int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2564.Substring XOR Queries/README_EN.md b/solution/2500-2599/2564.Substring XOR Queries/README_EN.md index 57b739055ba66..593d6b233adb5 100644 --- a/solution/2500-2599/2564.Substring XOR Queries/README_EN.md +++ b/solution/2500-2599/2564.Substring XOR Queries/README_EN.md @@ -52,7 +52,7 @@ ## Solutions -**Solution 1: Preprocessing + Enumeration** +### Solution 1: Preprocessing + Enumeration We can first preprocess all substrings of length $1$ to $32$ into their corresponding decimal values, find the minimum index and the corresponding right endpoint index for each value, and store them in the hash table $d$. @@ -62,8 +62,6 @@ The time complexity is $O(n \times \log M + m)$, and the space complexity is $O( -### **Python3** - ```python class Solution: def substringXorQueries(self, s: str, queries: List[List[int]]) -> List[List[int]]: @@ -82,8 +80,6 @@ class Solution: return [d.get(first ^ second, [-1, -1]) for first, second in queries] ``` -### **Java** - ```java class Solution { public int[][] substringXorQueries(String s, int[][] queries) { @@ -111,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +140,6 @@ public: }; ``` -### **Go** - ```go func substringXorQueries(s string, queries [][]int) (ans [][]int) { d := map[int][]int{} @@ -176,10 +168,6 @@ func substringXorQueries(s string, queries [][]int) (ans [][]int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2565.Subsequence With the Minimum Score/README.md b/solution/2500-2599/2565.Subsequence With the Minimum Score/README.md index e71e2379b9889..b87966db1a80e 100644 --- a/solution/2500-2599/2565.Subsequence With the Minimum Score/README.md +++ b/solution/2500-2599/2565.Subsequence With the Minimum Score/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:前后缀预处理 + 二分查找** +### 方法一:前后缀预处理 + 二分查找 根据题目我们知道,删除字符的下标范围是 `[left, right]`,最优的做法一定是删除 `[left, right]` 范围内的所有字符。也就是说,我们要删除字符串 $t$ 中的一个子串,使得字符串 $t$ 的剩余前缀可以匹配字符串 $s$ 的前缀,字符串 $t$ 的剩余后缀可以匹配字符串 $s$ 的后缀,且字符串 $s$ 的前后缀不相交。注意,这里的匹配指的是子序列匹配。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def minimumScore(self, s: str, t: str) -> int: @@ -107,10 +101,6 @@ class Solution: return bisect_left(range(n + 1), True, key=check) ``` -### **Java** - - - ```java class Solution { private int m; @@ -165,8 +155,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -213,8 +201,6 @@ public: }; ``` -### **Go** - ```go func minimumScore(s string, t string) int { m, n := len(s), len(t) @@ -255,10 +241,6 @@ func minimumScore(s string, t string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2565.Subsequence With the Minimum Score/README_EN.md b/solution/2500-2599/2565.Subsequence With the Minimum Score/README_EN.md index 061d944e7b790..5b5d997d792b3 100644 --- a/solution/2500-2599/2565.Subsequence With the Minimum Score/README_EN.md +++ b/solution/2500-2599/2565.Subsequence With the Minimum Score/README_EN.md @@ -52,7 +52,7 @@ It can be proven that 3 is the minimum score that we can achieve. ## Solutions -**Solution 1: Prefix and Suffix Preprocessing + Binary Search** +### Solution 1: Prefix and Suffix Preprocessing + Binary Search According to the problem, we know that the range of the index to delete characters is `[left, right]`. The optimal approach is to delete all characters within the range `[left, right]`. In other words, we need to delete a substring from string $t$, so that the remaining prefix of string $t$ can match the prefix of string $s$, and the remaining suffix of string $t$ can match the suffix of string $s$, and the prefix and suffix of string $s$ do not overlap. Note that the match here refers to subsequence matching. @@ -64,8 +64,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def minimumScore(self, s: str, t: str) -> int: @@ -97,8 +95,6 @@ class Solution: return bisect_left(range(n + 1), True, key=check) ``` -### **Java** - ```java class Solution { private int m; @@ -153,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -201,8 +195,6 @@ public: }; ``` -### **Go** - ```go func minimumScore(s string, t string) int { m, n := len(s), len(t) @@ -243,10 +235,6 @@ func minimumScore(s string, t string) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/README.md b/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/README.md index aa11345ea171f..8d368ae933bff 100644 --- a/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/README.md +++ b/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们先将数字转为字符串 $s$。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def minMaxDifference(self, num: int) -> int: @@ -83,10 +77,6 @@ class Solution: return num - mi ``` -### **Java** - - - ```java class Solution { public int minMaxDifference(int num) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +121,6 @@ public: }; ``` -### **Go** - ```go func minMaxDifference(num int) int { s := []byte(strconv.Itoa(num)) @@ -162,8 +148,6 @@ func minMaxDifference(num int) int { } ``` -### **TypeScript** - ```ts function minMaxDifference(num: number): number { const s = num + ''; @@ -177,8 +161,6 @@ function minMaxDifference(num: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_max_difference(num: i32) -> i32 { @@ -194,41 +176,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn min_max_difference(num: i32) -> i32 { - let mut s = num.to_string().into_bytes(); - let first = s[0]; - for i in 0..s.len() { - if s[i] == first { - s[i] = b'0'; - } - } - let mi = String::from_utf8_lossy(&s).parse::().unwrap(); - - let mut t = num.to_string().into_bytes(); - for i in 0..t.len() { - if t[i] != b'9' { - let second = t[i]; - - for j in 0..t.len() { - if t[j] == second { - t[j] = b'9'; - } - } - - let mx = String::from_utf8_lossy(&t).parse::().unwrap(); - return mx - mi; - } - } - - num - mi - } -} -``` - -### **C** - ```c int getLen(int num) { int res = 0; @@ -268,10 +215,45 @@ int minMaxDifference(int num) { } ``` -### **...** + -``` +### 方法二 + + + +```rust +impl Solution { + pub fn min_max_difference(num: i32) -> i32 { + let mut s = num.to_string().into_bytes(); + let first = s[0]; + for i in 0..s.len() { + if s[i] == first { + s[i] = b'0'; + } + } + let mi = String::from_utf8_lossy(&s).parse::().unwrap(); + let mut t = num.to_string().into_bytes(); + for i in 0..t.len() { + if t[i] != b'9' { + let second = t[i]; + + for j in 0..t.len() { + if t[j] == second { + t[j] = b'9'; + } + } + + let mx = String::from_utf8_lossy(&t).parse::().unwrap(); + return mx - mi; + } + } + + num - mi + } +} ``` + + diff --git a/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/README_EN.md b/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/README_EN.md index 7f78038ba0097..87e65ca72dcb3 100644 --- a/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/README_EN.md +++ b/solution/2500-2599/2566.Maximum Difference by Remapping a Digit/README_EN.md @@ -47,7 +47,7 @@ Thus, we return 99. ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy First, we convert the number to a string $s$. @@ -61,8 +61,6 @@ The time complexity is $O(\log n)$, and the space complexity is $O(\log n)$. Whe -### **Python3** - ```python class Solution: def minMaxDifference(self, num: int) -> int: @@ -74,8 +72,6 @@ class Solution: return num - mi ``` -### **Java** - ```java class Solution { public int minMaxDifference(int num) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func minMaxDifference(num int) int { s := []byte(strconv.Itoa(num)) @@ -151,8 +143,6 @@ func minMaxDifference(num int) int { } ``` -### **TypeScript** - ```ts function minMaxDifference(num: number): number { const s = num + ''; @@ -166,8 +156,6 @@ function minMaxDifference(num: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_max_difference(num: i32) -> i32 { @@ -183,41 +171,6 @@ impl Solution { } ``` -```rust -impl Solution { - pub fn min_max_difference(num: i32) -> i32 { - let mut s = num.to_string().into_bytes(); - let first = s[0]; - for i in 0..s.len() { - if s[i] == first { - s[i] = b'0'; - } - } - let mi = String::from_utf8_lossy(&s).parse::().unwrap(); - - let mut t = num.to_string().into_bytes(); - for i in 0..t.len() { - if t[i] != b'9' { - let second = t[i]; - - for j in 0..t.len() { - if t[j] == second { - t[j] = b'9'; - } - } - - let mx = String::from_utf8_lossy(&t).parse::().unwrap(); - return mx - mi; - } - } - - num - mi - } -} -``` - -### **C** - ```c int getLen(int num) { int res = 0; @@ -257,10 +210,45 @@ int minMaxDifference(int num) { } ``` -### **...** + -``` +### Solution 2 + + + +```rust +impl Solution { + pub fn min_max_difference(num: i32) -> i32 { + let mut s = num.to_string().into_bytes(); + let first = s[0]; + for i in 0..s.len() { + if s[i] == first { + s[i] = b'0'; + } + } + let mi = String::from_utf8_lossy(&s).parse::().unwrap(); + + let mut t = num.to_string().into_bytes(); + for i in 0..t.len() { + if t[i] != b'9' { + let second = t[i]; + + for j in 0..t.len() { + if t[j] == second { + t[j] = b'9'; + } + } + let mx = String::from_utf8_lossy(&t).parse::().unwrap(); + return mx - mi; + } + } + + num - mi + } +} ``` + + diff --git a/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README.md b/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README.md index 6bcd3528b669e..aa631ea08537f 100644 --- a/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README.md +++ b/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:排序 + 贪心** +### 方法一:排序 + 贪心 根据题意我们知道,最小得分实际上是排序数组相邻两个元素的最小差值,最大得分是排序数组首尾元素的差值。数组 $nums$ 的分数是最小得分与最大得分的和。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def minimizeSum(self, nums: List[int]) -> int: @@ -86,10 +80,6 @@ class Solution: return min(nums[-1] - nums[2], nums[-2] - nums[1], nums[-3] - nums[0]) ``` -### **Java** - - - ```java class Solution { public int minimizeSum(int[] nums) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func minimizeSum(nums []int) int { sort.Ints(nums) @@ -126,8 +112,6 @@ func minimizeSum(nums []int) int { } ``` -### **TypeScript** - ```ts function minimizeSum(nums: number[]): number { nums.sort((a, b) => a - b); @@ -136,8 +120,6 @@ function minimizeSum(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn minimize_sum(mut nums: Vec) -> i32 { @@ -148,8 +130,6 @@ impl Solution { } ``` -### **C** - ```c #define min(a, b) (((a) < (b)) ? (a) : (b)) @@ -163,10 +143,6 @@ int minimizeSum(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README_EN.md b/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README_EN.md index 16edcb7692b9c..c02a16ab38f48 100644 --- a/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README_EN.md +++ b/solution/2500-2599/2567.Minimum Score by Changing Two Elements/README_EN.md @@ -48,7 +48,7 @@ The sum of our high and low score is 3, which we can prove to be minimal. ## Solutions -**Solution 1: Sorting + Greedy** +### Solution 1: Sorting + Greedy From the problem description, we know that the minimum score is actually the minimum difference between two adjacent elements in the sorted array, and the maximum score is the difference between the first and last elements of the sorted array. The score of the array $nums$ is the sum of the minimum score and the maximum score. @@ -67,8 +67,6 @@ Similar problems: -### **Python3** - ```python class Solution: def minimizeSum(self, nums: List[int]) -> int: @@ -76,8 +74,6 @@ class Solution: return min(nums[-1] - nums[2], nums[-2] - nums[1], nums[-3] - nums[0]) ``` -### **Java** - ```java class Solution { public int minimizeSum(int[] nums) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +98,6 @@ public: }; ``` -### **Go** - ```go func minimizeSum(nums []int) int { sort.Ints(nums) @@ -114,8 +106,6 @@ func minimizeSum(nums []int) int { } ``` -### **TypeScript** - ```ts function minimizeSum(nums: number[]): number { nums.sort((a, b) => a - b); @@ -124,8 +114,6 @@ function minimizeSum(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn minimize_sum(mut nums: Vec) -> i32 { @@ -136,8 +124,6 @@ impl Solution { } ``` -### **C** - ```c #define min(a, b) (((a) < (b)) ? (a) : (b)) @@ -151,10 +137,6 @@ int minimizeSum(int* nums, int numsSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2568.Minimum Impossible OR/README.md b/solution/2500-2599/2568.Minimum Impossible OR/README.md index 86f651b45b524..1c042344c1192 100644 --- a/solution/2500-2599/2568.Minimum Impossible OR/README.md +++ b/solution/2500-2599/2568.Minimum Impossible OR/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:枚举 2 的幂** +### 方法一:枚举 2 的幂 我们从整数 $1$ 开始考虑,如果 $1$ 是可表达的,那么它必须出现在数组 `nums` 中;如果 $2$ 是可表达的,那么它必须出现在数组 `nums` 中;如果 $1$ 和 $2$ 都是可表达的,那么它们的或运算 $3$ 也是可表达的,以此类推。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def minImpossibleOR(self, nums: List[int]) -> int: @@ -62,10 +56,6 @@ class Solution: return next(1 << i for i in range(32) if 1 << i not in s) ``` -### **Java** - - - ```java class Solution { public int minImpossibleOR(int[] nums) { @@ -82,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +86,6 @@ public: }; ``` -### **Go** - ```go func minImpossibleOR(nums []int) int { s := map[int]bool{} @@ -114,8 +100,6 @@ func minImpossibleOR(nums []int) int { } ``` -### **TypeScript** - ```ts function minImpossibleOR(nums: number[]): number { const s: Set = new Set(); @@ -130,10 +114,6 @@ function minImpossibleOR(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2568.Minimum Impossible OR/README_EN.md b/solution/2500-2599/2568.Minimum Impossible OR/README_EN.md index cf8b1b9606efc..4916e72fe3a5f 100644 --- a/solution/2500-2599/2568.Minimum Impossible OR/README_EN.md +++ b/solution/2500-2599/2568.Minimum Impossible OR/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: Enumerate Powers of 2** +### Solution 1: Enumerate Powers of 2 We start from the integer $1$. If $1$ is expressible, it must appear in the array `nums`. If $2$ is expressible, it must also appear in the array `nums`. If both $1$ and $2$ are expressible, then their bitwise OR operation $3$ is also expressible, and so on. @@ -47,8 +47,6 @@ The time complexity is $O(n + \log M)$, and the space complexity is $O(n)$. Here -### **Python3** - ```python class Solution: def minImpossibleOR(self, nums: List[int]) -> int: @@ -56,8 +54,6 @@ class Solution: return next(1 << i for i in range(32) if 1 << i not in s) ``` -### **Java** - ```java class Solution { public int minImpossibleOR(int[] nums) { @@ -74,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,8 +84,6 @@ public: }; ``` -### **Go** - ```go func minImpossibleOR(nums []int) int { s := map[int]bool{} @@ -106,8 +98,6 @@ func minImpossibleOR(nums []int) int { } ``` -### **TypeScript** - ```ts function minImpossibleOR(nums: number[]): number { const s: Set = new Set(); @@ -122,10 +112,6 @@ function minImpossibleOR(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2569.Handling Sum Queries After Update/README.md b/solution/2500-2599/2569.Handling Sum Queries After Update/README.md index 4d9d21338f6c7..24a745f499a59 100644 --- a/solution/2500-2599/2569.Handling Sum Queries After Update/README.md +++ b/solution/2500-2599/2569.Handling Sum Queries After Update/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:线段树** +### 方法一:线段树 根据题目描述: @@ -90,10 +88,6 @@ -### **Python3** - - - ```python class Node: def __init__(self): @@ -173,10 +167,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Node { int l, r; @@ -288,8 +278,6 @@ class Solution { } ``` -### **C++** - ```cpp class Node { public: @@ -398,8 +386,6 @@ public: }; ``` -### **Go** - ```go type node struct { l, r, s, lazy int @@ -500,10 +486,6 @@ func handleQuery(nums1 []int, nums2 []int, queries [][]int) (ans []int64) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2569.Handling Sum Queries After Update/README_EN.md b/solution/2500-2599/2569.Handling Sum Queries After Update/README_EN.md index 9ef1572a4046f..0d7a9c1371722 100644 --- a/solution/2500-2599/2569.Handling Sum Queries After Update/README_EN.md +++ b/solution/2500-2599/2569.Handling Sum Queries After Update/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Segment Tree** +### Solution 1: Segment Tree According to the problem description: @@ -84,8 +84,6 @@ The time complexity is $O(n + m \times \log n)$, and the space complexity is $O( -### **Python3** - ```python class Node: def __init__(self): @@ -165,8 +163,6 @@ class Solution: return ans ``` -### **Java** - ```java class Node { int l, r; @@ -278,8 +274,6 @@ class Solution { } ``` -### **C++** - ```cpp class Node { public: @@ -388,8 +382,6 @@ public: }; ``` -### **Go** - ```go type node struct { l, r, s, lazy int @@ -490,10 +482,6 @@ func handleQuery(nums1 []int, nums2 []int, queries [][]int) (ans []int64) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2570.Merge Two 2D Arrays by Summing Values/README.md b/solution/2500-2599/2570.Merge Two 2D Arrays by Summing Values/README.md index b74d3fd62f9ae..32c338cd260b9 100644 --- a/solution/2500-2599/2570.Merge Two 2D Arrays by Summing Values/README.md +++ b/solution/2500-2599/2570.Merge Two 2D Arrays by Summing Values/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:计数 + 枚举** +### 方法一:计数 + 枚举 我们可以用一个哈希表或数组 `cnt` 统计两个数组中每个数字出现的次数。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def mergeArrays( @@ -85,10 +79,6 @@ class Solution: return sorted(cnt.items()) ``` -### **Java** - - - ```java class Solution { public int[][] mergeArrays(int[][] nums1, int[][] nums2) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func mergeArrays(nums1 [][]int, nums2 [][]int) (ans [][]int) { cnt := [1001]int{} @@ -160,8 +146,6 @@ func mergeArrays(nums1 [][]int, nums2 [][]int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function mergeArrays(nums1: number[][], nums2: number[][]): number[][] { const n = 1001; @@ -182,8 +166,6 @@ function mergeArrays(nums1: number[][], nums2: number[][]): number[][] { } ``` -### **Rust** - ```rust impl Solution { pub fn merge_arrays(nums1: Vec>, nums2: Vec>) -> Vec> { @@ -209,10 +191,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2570.Merge Two 2D Arrays by Summing Values/README_EN.md b/solution/2500-2599/2570.Merge Two 2D Arrays by Summing Values/README_EN.md index 2101b68c6bac8..6eef2ccd70557 100644 --- a/solution/2500-2599/2570.Merge Two 2D Arrays by Summing Values/README_EN.md +++ b/solution/2500-2599/2570.Merge Two 2D Arrays by Summing Values/README_EN.md @@ -56,7 +56,7 @@ ## Solutions -**Solution 1: Counting + Enumeration** +### Solution 1: Counting + Enumeration We can use a hash table or an array `cnt` to count the frequency of each number in the two arrays. @@ -66,8 +66,6 @@ The time complexity is $O(n + m)$, and the space complexity is $O(M)$. Where $n$ -### **Python3** - ```python class Solution: def mergeArrays( @@ -79,8 +77,6 @@ class Solution: return sorted(cnt.items()) ``` -### **Java** - ```java class Solution { public int[][] mergeArrays(int[][] nums1, int[][] nums2) { @@ -108,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +126,6 @@ public: }; ``` -### **Go** - ```go func mergeArrays(nums1 [][]int, nums2 [][]int) (ans [][]int) { cnt := [1001]int{} @@ -152,8 +144,6 @@ func mergeArrays(nums1 [][]int, nums2 [][]int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function mergeArrays(nums1: number[][], nums2: number[][]): number[][] { const n = 1001; @@ -174,8 +164,6 @@ function mergeArrays(nums1: number[][], nums2: number[][]): number[][] { } ``` -### **Rust** - ```rust impl Solution { pub fn merge_arrays(nums1: Vec>, nums2: Vec>) -> Vec> { @@ -201,10 +189,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2571.Minimum Operations to Reduce an Integer to 0/README.md b/solution/2500-2599/2571.Minimum Operations to Reduce an Integer to 0/README.md index c15e6ae87df9c..b66f2f741bd85 100644 --- a/solution/2500-2599/2571.Minimum Operations to Reduce an Integer to 0/README.md +++ b/solution/2500-2599/2571.Minimum Operations to Reduce an Integer to 0/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:贪心 + 位运算** +### 方法一:贪心 + 位运算 我们将整数 $n$ 转换为二进制,从最低位开始: @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, n: int) -> int: @@ -89,10 +83,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minOperations(int n) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func minOperations(n int) (ans int) { cnt := 0 @@ -160,8 +146,6 @@ func minOperations(n int) (ans int) { } ``` -### **TypeScript** - ```ts function minOperations(n: number): number { let [ans, cnt] = [0, 0]; @@ -182,10 +166,6 @@ function minOperations(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2571.Minimum Operations to Reduce an Integer to 0/README_EN.md b/solution/2500-2599/2571.Minimum Operations to Reduce an Integer to 0/README_EN.md index c1896242920d5..4865b192cd3f5 100644 --- a/solution/2500-2599/2571.Minimum Operations to Reduce an Integer to 0/README_EN.md +++ b/solution/2500-2599/2571.Minimum Operations to Reduce an Integer to 0/README_EN.md @@ -48,7 +48,7 @@ So the minimum number of operations is 3. ## Solutions -**Solution 1: Greedy + Bitwise Operation** +### Solution 1: Greedy + Bitwise Operation We convert the integer $n$ to binary, starting from the lowest bit: @@ -61,8 +61,6 @@ The time complexity is $O(\log n)$, and the space complexity is $O(1)$. Here, $n -### **Python3** - ```python class Solution: def minOperations(self, n: int) -> int: @@ -81,8 +79,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minOperations(int n) { @@ -102,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +118,6 @@ public: }; ``` -### **Go** - ```go func minOperations(n int) (ans int) { cnt := 0 @@ -150,8 +142,6 @@ func minOperations(n int) (ans int) { } ``` -### **TypeScript** - ```ts function minOperations(n: number): number { let [ans, cnt] = [0, 0]; @@ -172,10 +162,6 @@ function minOperations(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2572.Count the Number of Square-Free Subsets/README.md b/solution/2500-2599/2572.Count the Number of Square-Free Subsets/README.md index 8a1b33efdaaf1..8fdea74406e86 100644 --- a/solution/2500-2599/2572.Count the Number of Square-Free Subsets/README.md +++ b/solution/2500-2599/2572.Count the Number of Square-Free Subsets/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:状态压缩动态规划** +### 方法一:状态压缩动态规划 注意到题目中 $nums[i]$ 的范围为 $[1, 30]$,因此我们可以预处理出所有小于等于 $30$ 的质数,即 $[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]$。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def squareFreeSubsets(self, nums: List[int]) -> int: @@ -97,10 +91,6 @@ class Solution: return sum(v for v in f) % mod - 1 ``` -### **Java** - - - ```java class Solution { public int squareFreeSubsets(int[] nums) { @@ -142,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -185,8 +173,6 @@ public: }; ``` -### **Go** - ```go func squareFreeSubsets(nums []int) (ans int) { primes := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} @@ -225,10 +211,6 @@ func squareFreeSubsets(nums []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2572.Count the Number of Square-Free Subsets/README_EN.md b/solution/2500-2599/2572.Count the Number of Square-Free Subsets/README_EN.md index 42ae250e37826..aefedd4988e0f 100644 --- a/solution/2500-2599/2572.Count the Number of Square-Free Subsets/README_EN.md +++ b/solution/2500-2599/2572.Count the Number of Square-Free Subsets/README_EN.md @@ -46,7 +46,7 @@ It can be proven that there is no more than 1 square-free subset in the given ar ## Solutions -**Solution 1: State Compression Dynamic Programming** +### Solution 1: State Compression Dynamic Programming Note that in the problem, the range of $nums[i]$ is $[1, 30]$. Therefore, we can preprocess all prime numbers less than or equal to $30$, which are $[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]$. @@ -66,8 +66,6 @@ Similar problems: -### **Python3** - ```python class Solution: def squareFreeSubsets(self, nums: List[int]) -> int: @@ -90,8 +88,6 @@ class Solution: return sum(v for v in f) % mod - 1 ``` -### **Java** - ```java class Solution { public int squareFreeSubsets(int[] nums) { @@ -133,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +170,6 @@ public: }; ``` -### **Go** - ```go func squareFreeSubsets(nums []int) (ans int) { primes := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} @@ -216,10 +208,6 @@ func squareFreeSubsets(nums []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2573.Find the String with LCP/README.md b/solution/2500-2599/2573.Find the String with LCP/README.md index eb582bc632520..743083a7c1d0c 100644 --- a/solution/2500-2599/2573.Find the String with LCP/README.md +++ b/solution/2500-2599/2573.Find the String with LCP/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:贪心 + 构造** +### 方法一:贪心 + 构造 由于构造的字符串要求字典序最小,因此我们可以从字符 `'a'` 开始,填充到字符串 $s$ 中。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def findTheString(self, lcp: List[List[int]]) -> str: @@ -107,10 +101,6 @@ class Solution: return "".join(s) ``` -### **Java** - - - ```java class Solution { public String findTheString(int[][] lcp) { @@ -155,8 +145,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -199,8 +187,6 @@ public: }; ``` -### **Go** - ```go func findTheString(lcp [][]int) string { i, n := 0, len(lcp) @@ -240,10 +226,6 @@ func findTheString(lcp [][]int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2573.Find the String with LCP/README_EN.md b/solution/2500-2599/2573.Find the String with LCP/README_EN.md index 97c0291353ca0..4358a7211868f 100644 --- a/solution/2500-2599/2573.Find the String with LCP/README_EN.md +++ b/solution/2500-2599/2573.Find the String with LCP/README_EN.md @@ -49,7 +49,7 @@ ## Solutions -**Solution 1: Greedy + Construction** +### Solution 1: Greedy + Construction Since the constructed string requires the lexicographically smallest order, we can start by filling the string $s$ with the character `'a'`. @@ -68,8 +68,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ i -### **Python3** - ```python class Solution: def findTheString(self, lcp: List[List[int]]) -> str: @@ -99,8 +97,6 @@ class Solution: return "".join(s) ``` -### **Java** - ```java class Solution { public String findTheString(int[][] lcp) { @@ -145,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -189,8 +183,6 @@ public: }; ``` -### **Go** - ```go func findTheString(lcp [][]int) string { i, n := 0, len(lcp) @@ -230,10 +222,6 @@ func findTheString(lcp [][]int) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2574.Left and Right Sum Differences/README.md b/solution/2500-2599/2574.Left and Right Sum Differences/README.md index 7257b3e713d9d..170ae7786b748 100644 --- a/solution/2500-2599/2574.Left and Right Sum Differences/README.md +++ b/solution/2500-2599/2574.Left and Right Sum Differences/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:前缀和** +### 方法一:前缀和 我们定义变量 $left$ 表示数组 `nums` 中下标 $i$ 左侧元素之和,变量 $right$ 表示数组 `nums` 中下标 $i$ 右侧元素之和。初始时 $left = 0$, $right = \sum_{i = 0}^{n - 1} nums[i]$。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def leftRigthDifference(self, nums: List[int]) -> List[int]: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] leftRigthDifference(int[] nums) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func leftRigthDifference(nums []int) (ans []int) { var left, right int @@ -148,8 +134,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function leftRigthDifference(nums: number[]): number[] { let left = 0, @@ -164,21 +148,6 @@ function leftRigthDifference(nums: number[]): number[] { } ``` -```ts -function leftRigthDifference(nums: number[]): number[] { - let left = 0; - let right = nums.reduce((r, v) => r + v); - return nums.map(v => { - right -= v; - const res = Math.abs(left - right); - left += v; - return res; - }); -} -``` - -### **Rust** - ```rust impl Solution { pub fn left_rigth_difference(nums: Vec) -> Vec { @@ -196,6 +165,46 @@ impl Solution { } ``` +```c +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int* leftRigthDifference(int* nums, int numsSize, int* returnSize) { + int left = 0; + int right = 0; + for (int i = 0; i < numsSize; i++) { + right += nums[i]; + } + int* ans = malloc(sizeof(int) * numsSize); + for (int i = 0; i < numsSize; i++) { + right -= nums[i]; + ans[i] = abs(left - right); + left += nums[i]; + } + *returnSize = numsSize; + return ans; +} +``` + + + +### 方法二 + + + +```ts +function leftRigthDifference(nums: number[]): number[] { + let left = 0; + let right = nums.reduce((r, v) => r + v); + return nums.map(v => { + right -= v; + const res = Math.abs(left - right); + left += v; + return res; + }); +} +``` + ```rust impl Solution { pub fn left_right_difference(nums: Vec) -> Vec { @@ -220,6 +229,12 @@ impl Solution { } ``` + + +### 方法三 + + + ```rust impl Solution { pub fn left_right_difference(nums: Vec) -> Vec { @@ -238,33 +253,6 @@ impl Solution { } ``` -### **C** - -```c -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -int* leftRigthDifference(int* nums, int numsSize, int* returnSize) { - int left = 0; - int right = 0; - for (int i = 0; i < numsSize; i++) { - right += nums[i]; - } - int* ans = malloc(sizeof(int) * numsSize); - for (int i = 0; i < numsSize; i++) { - right -= nums[i]; - ans[i] = abs(left - right); - left += nums[i]; - } - *returnSize = numsSize; - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2574.Left and Right Sum Differences/README_EN.md b/solution/2500-2599/2574.Left and Right Sum Differences/README_EN.md index bfa0cdb6be980..a60e58660c40b 100644 --- a/solution/2500-2599/2574.Left and Right Sum Differences/README_EN.md +++ b/solution/2500-2599/2574.Left and Right Sum Differences/README_EN.md @@ -49,7 +49,7 @@ The array answer is [|0 - 0|] = [0]. ## Solutions -**Solution 1: Prefix Sum** +### Solution 1: Prefix Sum We define a variable $left$ to represent the sum of the elements to the left of index $i$ in the array `nums`, and a variable $right$ to represent the sum of the elements to the right of index $i$ in the array `nums`. Initially, $left = 0$, $right = \sum_{i = 0}^{n - 1} nums[i]$. @@ -66,8 +66,6 @@ Similar problems: -### **Python3** - ```python class Solution: def leftRigthDifference(self, nums: List[int]) -> List[int]: @@ -80,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] leftRigthDifference(int[] nums) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +110,6 @@ public: }; ``` -### **Go** - ```go func leftRigthDifference(nums []int) (ans []int) { var left, right int @@ -140,8 +132,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function leftRigthDifference(nums: number[]): number[] { let left = 0, @@ -156,21 +146,6 @@ function leftRigthDifference(nums: number[]): number[] { } ``` -```ts -function leftRigthDifference(nums: number[]): number[] { - let left = 0; - let right = nums.reduce((r, v) => r + v); - return nums.map(v => { - right -= v; - const res = Math.abs(left - right); - left += v; - return res; - }); -} -``` - -### **Rust** - ```rust impl Solution { pub fn left_rigth_difference(nums: Vec) -> Vec { @@ -188,6 +163,46 @@ impl Solution { } ``` +```c +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int* leftRigthDifference(int* nums, int numsSize, int* returnSize) { + int left = 0; + int right = 0; + for (int i = 0; i < numsSize; i++) { + right += nums[i]; + } + int* ans = malloc(sizeof(int) * numsSize); + for (int i = 0; i < numsSize; i++) { + right -= nums[i]; + ans[i] = abs(left - right); + left += nums[i]; + } + *returnSize = numsSize; + return ans; +} +``` + + + +### Solution 2 + + + +```ts +function leftRigthDifference(nums: number[]): number[] { + let left = 0; + let right = nums.reduce((r, v) => r + v); + return nums.map(v => { + right -= v; + const res = Math.abs(left - right); + left += v; + return res; + }); +} +``` + ```rust impl Solution { pub fn left_right_difference(nums: Vec) -> Vec { @@ -212,6 +227,12 @@ impl Solution { } ``` + + +### Solution 3 + + + ```rust impl Solution { pub fn left_right_difference(nums: Vec) -> Vec { @@ -230,33 +251,6 @@ impl Solution { } ``` -### **C** - -```c -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -int* leftRigthDifference(int* nums, int numsSize, int* returnSize) { - int left = 0; - int right = 0; - for (int i = 0; i < numsSize; i++) { - right += nums[i]; - } - int* ans = malloc(sizeof(int) * numsSize); - for (int i = 0; i < numsSize; i++) { - right -= nums[i]; - ans[i] = abs(left - right); - left += nums[i]; - } - *returnSize = numsSize; - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2575.Find the Divisibility Array of a String/README.md b/solution/2500-2599/2575.Find the Divisibility Array of a String/README.md index 603828c1ee819..d61297506ac19 100644 --- a/solution/2500-2599/2575.Find the Divisibility Array of a String/README.md +++ b/solution/2500-2599/2575.Find the Divisibility Array of a String/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:遍历 + 取模** +### 方法一:遍历 + 取模 我们遍历字符串 `word`,用变量 $x$ 记录当前前缀与 $m$ 的取模结果,如果 $x$ 为 $0$,则当前位置的可整除数组值为 $1$,否则为 $0$。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def divisibilityArray(self, word: str, m: int) -> List[int]: @@ -73,10 +67,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] divisibilityArray(String word, int m) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +99,6 @@ public: }; ``` -### **Go** - ```go func divisibilityArray(word string, m int) (ans []int) { x := 0 @@ -128,8 +114,6 @@ func divisibilityArray(word string, m int) (ans []int) { } ``` -### **TypeScript** - ```ts function divisibilityArray(word: string, m: number): number[] { const ans: number[] = []; @@ -142,8 +126,6 @@ function divisibilityArray(word: string, m: number): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn divisibility_array(word: String, m: i32) -> Vec { @@ -164,8 +146,6 @@ impl Solution { } ``` -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -183,10 +163,6 @@ int* divisibilityArray(char* word, int m, int* returnSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2575.Find the Divisibility Array of a String/README_EN.md b/solution/2500-2599/2575.Find the Divisibility Array of a String/README_EN.md index 588d701d92aa7..f470915163144 100644 --- a/solution/2500-2599/2575.Find the Divisibility Array of a String/README_EN.md +++ b/solution/2500-2599/2575.Find the Divisibility Array of a String/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Traversal + Modulo** +### Solution 1: Traversal + Modulo We iterate over the string `word`, using a variable $x$ to record the modulo result of the current prefix with $m$. If $x$ is $0$, then the divisible array value at the current position is $1$, otherwise it is $0$. @@ -52,8 +52,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string `word`. The -### **Python3** - ```python class Solution: def divisibilityArray(self, word: str, m: int) -> List[int]: @@ -65,8 +63,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] divisibilityArray(String word, int m) { @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +95,6 @@ public: }; ``` -### **Go** - ```go func divisibilityArray(word string, m int) (ans []int) { x := 0 @@ -118,8 +110,6 @@ func divisibilityArray(word string, m int) (ans []int) { } ``` -### **TypeScript** - ```ts function divisibilityArray(word: string, m: number): number[] { const ans: number[] = []; @@ -132,8 +122,6 @@ function divisibilityArray(word: string, m: number): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn divisibility_array(word: String, m: i32) -> Vec { @@ -154,8 +142,6 @@ impl Solution { } ``` -### **C** - ```c /** * Note: The returned array must be malloced, assume caller calls free(). @@ -173,10 +159,6 @@ int* divisibilityArray(char* word, int m, int* returnSize) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2576.Find the Maximum Number of Marked Indices/README.md b/solution/2500-2599/2576.Find the Maximum Number of Marked Indices/README.md index 896965d74d6f8..213d71203dcbd 100644 --- a/solution/2500-2599/2576.Find the Maximum Number of Marked Indices/README.md +++ b/solution/2500-2599/2576.Find the Maximum Number of Marked Indices/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:贪心 + 双指针** +### 方法一:贪心 + 双指针 为了将下标尽可能多地标记,我们可以将数组 `nums` 排序,然后从左到右遍历数组,对于每个下标 $i$,我们在数组的右半部分找到第一个满足 $2 \times nums[i] \leq nums[j]$ 的下标 $j$,然后标记下标 $i$ 和 $j$。继续遍历下一个下标 $i$。当我们遍历完数组的右半部分时,说明标记已经完成,此时标记的下标数目即为答案。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def maxNumOfMarkedIndices(self, nums: List[int]) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxNumOfMarkedIndices(int[] nums) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func maxNumOfMarkedIndices(nums []int) (ans int) { sort.Ints(nums) @@ -149,8 +135,6 @@ func maxNumOfMarkedIndices(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function maxNumOfMarkedIndices(nums: number[]): number { nums.sort((a, b) => a - b); @@ -168,10 +152,6 @@ function maxNumOfMarkedIndices(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2576.Find the Maximum Number of Marked Indices/README_EN.md b/solution/2500-2599/2576.Find the Maximum Number of Marked Indices/README_EN.md index a74bae24013e9..cc2806ca829e1 100644 --- a/solution/2500-2599/2576.Find the Maximum Number of Marked Indices/README_EN.md +++ b/solution/2500-2599/2576.Find the Maximum Number of Marked Indices/README_EN.md @@ -62,7 +62,7 @@ Since there is no other operation, the answer is 4. ## Solutions -**Solution 1: Greedy + Two Pointers** +### Solution 1: Greedy + Two Pointers In order to mark as many indices as possible, we can sort the array `nums`, and then traverse the array from left to right. For each index $i$, we find the first index $j$ in the right half of the array that satisfies $2 \times nums[i] \leq nums[j]$, and then mark indices $i$ and $j$. Continue to traverse the next index $i$. When we have traversed the right half of the array, it means that the marking is complete, and the number of marked indices is the answer. @@ -70,8 +70,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def maxNumOfMarkedIndices(self, nums: List[int]) -> int: @@ -88,8 +86,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxNumOfMarkedIndices(int[] nums) { @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +125,6 @@ public: }; ``` -### **Go** - ```go func maxNumOfMarkedIndices(nums []int) (ans int) { sort.Ints(nums) @@ -149,8 +141,6 @@ func maxNumOfMarkedIndices(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function maxNumOfMarkedIndices(nums: number[]): number { nums.sort((a, b) => a - b); @@ -168,10 +158,6 @@ function maxNumOfMarkedIndices(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README.md b/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README.md index 11e8c01b18db1..91e554fc2927a 100644 --- a/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README.md +++ b/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:最短路 + 优先队列(小根堆)** +### 方法一:最短路 + 优先队列(小根堆) 我们观察发现,如果在格子 $(0, 0)$ 处无法移动,即 $grid[0][1] \gt 1$ 且 $grid[1][0] \gt 1$,那么我们在格子 $(0, 0)$ 无法再移动,此时返回 $-1$ 即可。而对于其他情况,我们都可以移动。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def minimumTime(self, grid: List[List[int]]) -> int: @@ -103,10 +97,6 @@ class Solution: heappush(q, (nt, x, y)) ``` -### **Java** - - - ```java class Solution { public int minimumTime(int[][] grid) { @@ -146,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -187,8 +175,6 @@ public: }; ``` -### **Go** - ```go func minimumTime(grid [][]int) int { if grid[0][1] > 1 && grid[1][0] > 1 { @@ -238,10 +224,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README_EN.md b/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README_EN.md index f689d49dc3347..5cf0bd673fb37 100644 --- a/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README_EN.md +++ b/solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/README_EN.md @@ -63,7 +63,7 @@ The final time is 7. It can be shown that it is the minimum time possible. ## Solutions -**Solution 1: Shortest Path + Priority Queue (Min Heap)** +### Solution 1: Shortest Path + Priority Queue (Min Heap) We observe that if we cannot move at the cell $(0, 0)$, i.e., $grid[0][1] > 1$ and $grid[1][0] > 1$, then we cannot move at the cell $(0, 0)$ anymore, and we should return $-1$. For other cases, we can move. @@ -77,8 +77,6 @@ The time complexity is $O(m \times n \times \log (m \times n))$, and the space c -### **Python3** - ```python class Solution: def minimumTime(self, grid: List[List[int]]) -> int: @@ -104,8 +102,6 @@ class Solution: heappush(q, (nt, x, y)) ``` -### **Java** - ```java class Solution { public int minimumTime(int[][] grid) { @@ -145,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -186,8 +180,6 @@ public: }; ``` -### **Go** - ```go func minimumTime(grid [][]int) int { if grid[0][1] > 1 && grid[1][0] > 1 { @@ -237,10 +229,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2578.Split With Minimum Sum/README.md b/solution/2500-2599/2578.Split With Minimum Sum/README.md index c5400f084235f..ff9b8e68a911e 100644 --- a/solution/2500-2599/2578.Split With Minimum Sum/README.md +++ b/solution/2500-2599/2578.Split With Minimum Sum/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:计数 + 贪心** +### 方法一:计数 + 贪心 我们先用哈希表或数组 $cnt$ 统计 $num$ 中各个数字出现的次数,用变量 $n$ 记录 $num$ 的位数。 @@ -64,18 +62,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 为 $num$ 的位数;而 $C$ 为 $num$ 中不同数字的个数,本题中 $C \leq 10$。 -**方法二:排序 + 贪心** - -我们可以将 $num$ 转换成字符串或者字符数组,然后对其进行排序,接下来将排序后的数组中的数字按照从小到大的顺序交替地分配给 $num1$ 和 $num2$,最后返回 $num1$ 和 $num2$ 的和即可。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为 $num$ 的位数。 - -### **Python3** - - - ```python class Solution: def splitNum(self, num: int) -> int: @@ -95,17 +83,6 @@ class Solution: return sum(ans) ``` -```python -class Solution: - def splitNum(self, num: int) -> int: - s = sorted(str(num)) - return int(''.join(s[::2])) + int(''.join(s[1::2])) -``` - -### **Java** - - - ```java class Solution { public int splitNum(int num) { @@ -128,22 +105,6 @@ class Solution { } ``` -```java -class Solution { - public int splitNum(int num) { - char[] s = (num + "").toCharArray(); - Arrays.sort(s); - int[] ans = new int[2]; - for (int i = 0; i < s.length; ++i) { - ans[i & 1] = ans[i & 1] * 10 + s[i] - '0'; - } - return ans[0] + ans[1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -167,23 +128,6 @@ public: }; ``` -```cpp -class Solution { -public: - int splitNum(int num) { - string s = to_string(num); - sort(s.begin(), s.end()); - int ans[2]{}; - for (int i = 0; i < s.size(); ++i) { - ans[i & 1] = ans[i & 1] * 10 + s[i] - '0'; - } - return ans[0] + ans[1]; - } -}; -``` - -### **Go** - ```go func splitNum(num int) int { cnt := [10]int{} @@ -204,20 +148,6 @@ func splitNum(num int) int { } ``` -```go -func splitNum(num int) int { - s := []byte(strconv.Itoa(num)) - sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) - ans := [2]int{} - for i, c := range s { - ans[i&1] = ans[i&1]*10 + int(c-'0') - } - return ans[0] + ans[1] -} -``` - -### **TypeScript** - ```ts function splitNum(num: number): number { const cnt: number[] = Array(10).fill(0); @@ -238,20 +168,6 @@ function splitNum(num: number): number { } ``` -```ts -function splitNum(num: number): number { - const s: string[] = String(num).split(''); - s.sort(); - const ans: number[] = Array(2).fill(0); - for (let i = 0; i < s.length; ++i) { - ans[i & 1] = ans[i & 1] * 10 + Number(s[i]); - } - return ans[0] + ans[1]; -} -``` - -### **Rust** - ```rust impl Solution { pub fn split_num(mut num: i32) -> i32 { @@ -280,6 +196,76 @@ impl Solution { } ``` + + +### 方法二:排序 + 贪心 + +我们可以将 $num$ 转换成字符串或者字符数组,然后对其进行排序,接下来将排序后的数组中的数字按照从小到大的顺序交替地分配给 $num1$ 和 $num2$,最后返回 $num1$ 和 $num2$ 的和即可。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为 $num$ 的位数。 + + + +```python +class Solution: + def splitNum(self, num: int) -> int: + s = sorted(str(num)) + return int(''.join(s[::2])) + int(''.join(s[1::2])) +``` + +```java +class Solution { + public int splitNum(int num) { + char[] s = (num + "").toCharArray(); + Arrays.sort(s); + int[] ans = new int[2]; + for (int i = 0; i < s.length; ++i) { + ans[i & 1] = ans[i & 1] * 10 + s[i] - '0'; + } + return ans[0] + ans[1]; + } +} +``` + +```cpp +class Solution { +public: + int splitNum(int num) { + string s = to_string(num); + sort(s.begin(), s.end()); + int ans[2]{}; + for (int i = 0; i < s.size(); ++i) { + ans[i & 1] = ans[i & 1] * 10 + s[i] - '0'; + } + return ans[0] + ans[1]; + } +}; +``` + +```go +func splitNum(num int) int { + s := []byte(strconv.Itoa(num)) + sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) + ans := [2]int{} + for i, c := range s { + ans[i&1] = ans[i&1]*10 + int(c-'0') + } + return ans[0] + ans[1] +} +``` + +```ts +function splitNum(num: number): number { + const s: string[] = String(num).split(''); + s.sort(); + const ans: number[] = Array(2).fill(0); + for (let i = 0; i < s.length; ++i) { + ans[i & 1] = ans[i & 1] * 10 + Number(s[i]); + } + return ans[0] + ans[1]; +} +``` + ```rust impl Solution { pub fn split_num(num: i32) -> i32 { @@ -296,10 +282,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2578.Split With Minimum Sum/README_EN.md b/solution/2500-2599/2578.Split With Minimum Sum/README_EN.md index 8e8976391fc4b..f884c082edb21 100644 --- a/solution/2500-2599/2578.Split With Minimum Sum/README_EN.md +++ b/solution/2500-2599/2578.Split With Minimum Sum/README_EN.md @@ -50,7 +50,7 @@ ## Solutions -**Solution 1: Counting + Greedy** +### Solution 1: Counting + Greedy First, we use a hash table or array $cnt$ to count the occurrences of each digit in $num$, and use a variable $n$ to record the number of digits in $num$. @@ -58,16 +58,8 @@ Next, we enumerate all the digits $i$ in $nums$, and alternately allocate the di The time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the number of digits in $num$; and $C$ is the number of different digits in $num$, in this problem, $C \leq 10$. -**Solution 2: Sorting + Greedy** - -We can convert $num$ to a string or character array, then sort it, and then alternately allocate the digits in the sorted array to $num1$ and $num2$ in ascending order. Finally, we return the sum of $num1$ and $num2$. - -The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the number of digits in $num$. - -### **Python3** - ```python class Solution: def splitNum(self, num: int) -> int: @@ -87,15 +79,6 @@ class Solution: return sum(ans) ``` -```python -class Solution: - def splitNum(self, num: int) -> int: - s = sorted(str(num)) - return int(''.join(s[::2])) + int(''.join(s[1::2])) -``` - -### **Java** - ```java class Solution { public int splitNum(int num) { @@ -118,22 +101,6 @@ class Solution { } ``` -```java -class Solution { - public int splitNum(int num) { - char[] s = (num + "").toCharArray(); - Arrays.sort(s); - int[] ans = new int[2]; - for (int i = 0; i < s.length; ++i) { - ans[i & 1] = ans[i & 1] * 10 + s[i] - '0'; - } - return ans[0] + ans[1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -157,23 +124,6 @@ public: }; ``` -```cpp -class Solution { -public: - int splitNum(int num) { - string s = to_string(num); - sort(s.begin(), s.end()); - int ans[2]{}; - for (int i = 0; i < s.size(); ++i) { - ans[i & 1] = ans[i & 1] * 10 + s[i] - '0'; - } - return ans[0] + ans[1]; - } -}; -``` - -### **Go** - ```go func splitNum(num int) int { cnt := [10]int{} @@ -194,20 +144,6 @@ func splitNum(num int) int { } ``` -```go -func splitNum(num int) int { - s := []byte(strconv.Itoa(num)) - sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) - ans := [2]int{} - for i, c := range s { - ans[i&1] = ans[i&1]*10 + int(c-'0') - } - return ans[0] + ans[1] -} -``` - -### **TypeScript** - ```ts function splitNum(num: number): number { const cnt: number[] = Array(10).fill(0); @@ -228,20 +164,6 @@ function splitNum(num: number): number { } ``` -```ts -function splitNum(num: number): number { - const s: string[] = String(num).split(''); - s.sort(); - const ans: number[] = Array(2).fill(0); - for (let i = 0; i < s.length; ++i) { - ans[i & 1] = ans[i & 1] * 10 + Number(s[i]); - } - return ans[0] + ans[1]; -} -``` - -### **Rust** - ```rust impl Solution { pub fn split_num(mut num: i32) -> i32 { @@ -270,6 +192,76 @@ impl Solution { } ``` + + +### Solution 2: Sorting + Greedy + +We can convert $num$ to a string or character array, then sort it, and then alternately allocate the digits in the sorted array to $num1$ and $num2$ in ascending order. Finally, we return the sum of $num1$ and $num2$. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the number of digits in $num$. + + + +```python +class Solution: + def splitNum(self, num: int) -> int: + s = sorted(str(num)) + return int(''.join(s[::2])) + int(''.join(s[1::2])) +``` + +```java +class Solution { + public int splitNum(int num) { + char[] s = (num + "").toCharArray(); + Arrays.sort(s); + int[] ans = new int[2]; + for (int i = 0; i < s.length; ++i) { + ans[i & 1] = ans[i & 1] * 10 + s[i] - '0'; + } + return ans[0] + ans[1]; + } +} +``` + +```cpp +class Solution { +public: + int splitNum(int num) { + string s = to_string(num); + sort(s.begin(), s.end()); + int ans[2]{}; + for (int i = 0; i < s.size(); ++i) { + ans[i & 1] = ans[i & 1] * 10 + s[i] - '0'; + } + return ans[0] + ans[1]; + } +}; +``` + +```go +func splitNum(num int) int { + s := []byte(strconv.Itoa(num)) + sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) + ans := [2]int{} + for i, c := range s { + ans[i&1] = ans[i&1]*10 + int(c-'0') + } + return ans[0] + ans[1] +} +``` + +```ts +function splitNum(num: number): number { + const s: string[] = String(num).split(''); + s.sort(); + const ans: number[] = Array(2).fill(0); + for (let i = 0; i < s.length; ++i) { + ans[i & 1] = ans[i & 1] * 10 + Number(s[i]); + } + return ans[0] + ans[1]; +} +``` + ```rust impl Solution { pub fn split_num(num: i32) -> i32 { @@ -286,10 +278,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2579.Count Total Number of Colored Cells/README.md b/solution/2500-2599/2579.Count Total Number of Colored Cells/README.md index b72c96a16a078..6afb0f547073a 100644 --- a/solution/2500-2599/2579.Count Total Number of Colored Cells/README.md +++ b/solution/2500-2599/2579.Count Total Number of Colored Cells/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 我们观察发现,第 $n$ 分钟后,网格中共有 $2 \times n - 1$ 列,每一列上的数字分别为 $1, 3, 5, \cdots, 2 \times n - 1, 2 \times n - 3, \cdots, 3, 1$。左右两部分均为等差数列,求和可以得到答案 $2 \times n \times (n - 1) + 1$。 @@ -53,20 +51,12 @@ -### **Python3** - - - ```python class Solution: def coloredCells(self, n: int) -> int: return 2 * n * (n - 1) + 1 ``` -### **Java** - - - ```java class Solution { public long coloredCells(int n) { @@ -75,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -86,24 +74,18 @@ public: }; ``` -### **Go** - ```go func coloredCells(n int) int64 { return int64(2*n*(n-1) + 1) } ``` -### **TypeScript** - ```ts function coloredCells(n: number): number { return 2 * n * (n - 1) + 1; } ``` -### **Rust** - ```rust impl Solution { pub fn colored_cells(n: i32) -> i64 { @@ -112,10 +94,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2579.Count Total Number of Colored Cells/README_EN.md b/solution/2500-2599/2579.Count Total Number of Colored Cells/README_EN.md index 996f8d781e658..8f59088764fa7 100644 --- a/solution/2500-2599/2579.Count Total Number of Colored Cells/README_EN.md +++ b/solution/2500-2599/2579.Count Total Number of Colored Cells/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics We find that after the $n$th minute, there are a total of $2 \times n - 1$ columns in the grid, and the numbers on each column are respectively $1, 3, 5, \cdots, 2 \times n - 1, 2 \times n - 3, \cdots, 3, 1$. The left and right parts are both arithmetic progressions, and the sum can be obtained by $2 \times n \times (n - 1) + 1$. @@ -49,16 +49,12 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def coloredCells(self, n: int) -> int: return 2 * n * (n - 1) + 1 ``` -### **Java** - ```java class Solution { public long coloredCells(int n) { @@ -67,8 +63,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -78,24 +72,18 @@ public: }; ``` -### **Go** - ```go func coloredCells(n int) int64 { return int64(2*n*(n-1) + 1) } ``` -### **TypeScript** - ```ts function coloredCells(n: number): number { return 2 * n * (n - 1) + 1; } ``` -### **Rust** - ```rust impl Solution { pub fn colored_cells(n: i32) -> i64 { @@ -104,10 +92,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/README.md b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/README.md index b398eb675a56a..d123b6271f2be 100644 --- a/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/README.md +++ b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:排序 + 计数 + 快速幂** +### 方法一:排序 + 计数 + 快速幂 我们可以先对区间进行排序,相交的区间进行合并,统计有多少个不相交的区间,记为 $cnt$。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class Solution: def countWays(self, ranges: List[List[int]]) -> int: @@ -93,24 +87,6 @@ class Solution: return pow(2, cnt, mod) ``` -```python -class Solution: - def countWays(self, ranges: List[List[int]]) -> int: - ranges.sort() - mx = -1 - mod = 10**9 + 7 - ans = 1 - for start, end in ranges: - if start > mx: - ans = ans * 2 % mod - mx = max(mx, end) - return ans -``` - -### **Java** - - - ```java class Solution { public int countWays(int[][] ranges) { @@ -138,26 +114,6 @@ class Solution { } ``` -```java -class Solution { - public int countWays(int[][] ranges) { - Arrays.sort(ranges, (a, b) -> a[0] - b[0]); - int mx = -1; - int ans = 1; - final int mod = (int) 1e9 + 7; - for (int[] e : ranges) { - if (e[0] > mx) { - ans = ans * 2 % mod; - } - mx = Math.max(mx, e[1]); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -184,26 +140,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countWays(vector>& ranges) { - sort(ranges.begin(), ranges.end()); - int ans = 1, mx = -1; - const int mod = 1e9 + 7; - for (auto& e : ranges) { - if (e[0] > mx) { - ans = ans * 2 % mod; - } - mx = max(mx, e[1]); - } - return ans; - } -}; -``` - -### **Go** - ```go func countWays(ranges [][]int) int { sort.Slice(ranges, func(i, j int) bool { return ranges[i][0] < ranges[j][0] }) @@ -230,25 +166,6 @@ func countWays(ranges [][]int) int { } ``` -```go -func countWays(ranges [][]int) int { - sort.Slice(ranges, func(i, j int) bool { return ranges[i][0] < ranges[j][0] }) - ans, mx := 1, -1 - const mod = 1e9 + 7 - for _, e := range ranges { - if e[0] > mx { - ans = ans * 2 % mod - } - if mx < e[1] { - mx = e[1] - } - } - return ans -} -``` - -### **TypeScript** - ```ts function countWays(ranges: number[][]): number { ranges.sort((a, b) => a[0] - b[0]); @@ -265,10 +182,79 @@ function countWays(ranges: number[][]): number { } ``` -### **...** + + +### 方法二 + + +```python +class Solution: + def countWays(self, ranges: List[List[int]]) -> int: + ranges.sort() + mx = -1 + mod = 10**9 + 7 + ans = 1 + for start, end in ranges: + if start > mx: + ans = ans * 2 % mod + mx = max(mx, end) + return ans ``` +```java +class Solution { + public int countWays(int[][] ranges) { + Arrays.sort(ranges, (a, b) -> a[0] - b[0]); + int mx = -1; + int ans = 1; + final int mod = (int) 1e9 + 7; + for (int[] e : ranges) { + if (e[0] > mx) { + ans = ans * 2 % mod; + } + mx = Math.max(mx, e[1]); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int countWays(vector>& ranges) { + sort(ranges.begin(), ranges.end()); + int ans = 1, mx = -1; + const int mod = 1e9 + 7; + for (auto& e : ranges) { + if (e[0] > mx) { + ans = ans * 2 % mod; + } + mx = max(mx, e[1]); + } + return ans; + } +}; +``` + +```go +func countWays(ranges [][]int) int { + sort.Slice(ranges, func(i, j int) bool { return ranges[i][0] < ranges[j][0] }) + ans, mx := 1, -1 + const mod = 1e9 + 7 + for _, e := range ranges { + if e[0] > mx { + ans = ans * 2 % mod + } + if mx < e[1] { + mx = e[1] + } + } + return ans +} ``` + + diff --git a/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/README_EN.md b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/README_EN.md index 7e19254260589..65918f16eadb7 100644 --- a/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/README_EN.md +++ b/solution/2500-2599/2580.Count Ways to Group Overlapping Ranges/README_EN.md @@ -60,7 +60,7 @@ Thus, there are four possible ways to group them: ## Solutions -**Solution 1: Sorting + Counting + Fast Power** +### Solution 1: Sorting + Counting + Fast Power We can first sort the intervals in the range, merge the overlapping intervals, and count the number of non-overlapping intervals, denoted as $cnt$. @@ -72,8 +72,6 @@ Alternatively, we can also avoid using fast power. Once a new non-overlapping in -### **Python3** - ```python class Solution: def countWays(self, ranges: List[List[int]]) -> int: @@ -87,22 +85,6 @@ class Solution: return pow(2, cnt, mod) ``` -```python -class Solution: - def countWays(self, ranges: List[List[int]]) -> int: - ranges.sort() - mx = -1 - mod = 10**9 + 7 - ans = 1 - for start, end in ranges: - if start > mx: - ans = ans * 2 % mod - mx = max(mx, end) - return ans -``` - -### **Java** - ```java class Solution { public int countWays(int[][] ranges) { @@ -130,26 +112,6 @@ class Solution { } ``` -```java -class Solution { - public int countWays(int[][] ranges) { - Arrays.sort(ranges, (a, b) -> a[0] - b[0]); - int mx = -1; - int ans = 1; - final int mod = (int) 1e9 + 7; - for (int[] e : ranges) { - if (e[0] > mx) { - ans = ans * 2 % mod; - } - mx = Math.max(mx, e[1]); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -176,26 +138,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countWays(vector>& ranges) { - sort(ranges.begin(), ranges.end()); - int ans = 1, mx = -1; - const int mod = 1e9 + 7; - for (auto& e : ranges) { - if (e[0] > mx) { - ans = ans * 2 % mod; - } - mx = max(mx, e[1]); - } - return ans; - } -}; -``` - -### **Go** - ```go func countWays(ranges [][]int) int { sort.Slice(ranges, func(i, j int) bool { return ranges[i][0] < ranges[j][0] }) @@ -222,25 +164,6 @@ func countWays(ranges [][]int) int { } ``` -```go -func countWays(ranges [][]int) int { - sort.Slice(ranges, func(i, j int) bool { return ranges[i][0] < ranges[j][0] }) - ans, mx := 1, -1 - const mod = 1e9 + 7 - for _, e := range ranges { - if e[0] > mx { - ans = ans * 2 % mod - } - if mx < e[1] { - mx = e[1] - } - } - return ans -} -``` - -### **TypeScript** - ```ts function countWays(ranges: number[][]): number { ranges.sort((a, b) => a[0] - b[0]); @@ -257,10 +180,79 @@ function countWays(ranges: number[][]): number { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def countWays(self, ranges: List[List[int]]) -> int: + ranges.sort() + mx = -1 + mod = 10**9 + 7 + ans = 1 + for start, end in ranges: + if start > mx: + ans = ans * 2 % mod + mx = max(mx, end) + return ans +``` + +```java +class Solution { + public int countWays(int[][] ranges) { + Arrays.sort(ranges, (a, b) -> a[0] - b[0]); + int mx = -1; + int ans = 1; + final int mod = (int) 1e9 + 7; + for (int[] e : ranges) { + if (e[0] > mx) { + ans = ans * 2 % mod; + } + mx = Math.max(mx, e[1]); + } + return ans; + } +} +``` +```cpp +class Solution { +public: + int countWays(vector>& ranges) { + sort(ranges.begin(), ranges.end()); + int ans = 1, mx = -1; + const int mod = 1e9 + 7; + for (auto& e : ranges) { + if (e[0] > mx) { + ans = ans * 2 % mod; + } + mx = max(mx, e[1]); + } + return ans; + } +}; ``` +```go +func countWays(ranges [][]int) int { + sort.Slice(ranges, func(i, j int) bool { return ranges[i][0] < ranges[j][0] }) + ans, mx := 1, -1 + const mod = 1e9 + 7 + for _, e := range ranges { + if e[0] > mx { + ans = ans * 2 % mod + } + if mx < e[1] { + mx = e[1] + } + } + return ans +} ``` + + diff --git a/solution/2500-2599/2581.Count Number of Possible Root Nodes/README.md b/solution/2500-2599/2581.Count Number of Possible Root Nodes/README.md index 4fe182fc56e1e..24c4262c25074 100644 --- a/solution/2500-2599/2581.Count Number of Possible Root Nodes/README.md +++ b/solution/2500-2599/2581.Count Number of Possible Root Nodes/README.md @@ -74,9 +74,7 @@ ## 解法 - - -**方法一:树形 DP(换根)** +### 方法一:树形 DP(换根) 我们先遍历题目给定的边集合 $edges$,将其转换为邻接表 $g$,其中 $g[i]$ 表示节点 $i$ 的所有邻接节点。用哈希表 $gs$ 记录题目给定的猜测集合 $guesses$。 @@ -96,10 +94,6 @@ -### **Python3** - - - ```python class Solution: def rootCount( @@ -135,10 +129,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -197,8 +187,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -251,8 +239,6 @@ public: }; ``` -### **Go** - ```go func rootCount(edges [][]int, guesses [][]int, k int) (ans int) { n := len(edges) + 1 @@ -303,10 +289,6 @@ func rootCount(edges [][]int, guesses [][]int, k int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2581.Count Number of Possible Root Nodes/README_EN.md b/solution/2500-2599/2581.Count Number of Possible Root Nodes/README_EN.md index 26645ee06f814..5909444e1ab97 100644 --- a/solution/2500-2599/2581.Count Number of Possible Root Nodes/README_EN.md +++ b/solution/2500-2599/2581.Count Number of Possible Root Nodes/README_EN.md @@ -72,7 +72,7 @@ Considering any node as root will give at least 1 correct guess. ## Solutions -**Solution 1: Tree DP (change root)** +### Solution 1: Tree DP (change root) First, we traverse the given edge set $edges$ and convert it to an adjacency list $g$ where $g[i]$ represents the adjacent nodes of node $i$. Use a hash map $gs$ to record the given guess set $guesses$. @@ -88,8 +88,6 @@ The time complexity is $O(n + m)$ and the space complexity is $O(n + m)$, where -### **Python3** - ```python class Solution: def rootCount( @@ -125,8 +123,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -185,8 +181,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -239,8 +233,6 @@ public: }; ``` -### **Go** - ```go func rootCount(edges [][]int, guesses [][]int, k int) (ans int) { n := len(edges) + 1 @@ -291,10 +283,6 @@ func rootCount(edges [][]int, guesses [][]int, k int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2582.Pass the Pillow/README.md b/solution/2500-2599/2582.Pass the Pillow/README.md index 714651f8af3fd..ef5d3354fffb7 100644 --- a/solution/2500-2599/2582.Pass the Pillow/README.md +++ b/solution/2500-2599/2582.Pass the Pillow/README.md @@ -47,31 +47,14 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以模拟枕头传递的过程,每次传递枕头时,如果枕头到达队首或队尾,传递方向就会改变,队伍会继续沿相反方向传递枕头。 时间复杂度 $O(time)$,空间复杂度 $O(1)$。其中 $time$ 为给定的时间。 -**方法二:数学** - -我们注意到,每一轮有 $n - 1$ 次传递,因此我们可以将 $time$ 除以 $n - 1$ 得到枕头传递的轮数 $k$,然后再将 $time$ 对 $n - 1$ 取余得到枕头在当前轮的剩余传递次数 $mod$。 - -接下来我们判断当前的轮数 $k$: - -- 如果 $k$ 为奇数,那么枕头当前的传递方向是从队尾到队首,因此枕头会传递到编号为 $n - mod$ 的人手中; -- 如果 $k$ 为偶数,那么枕头当前的传递方向是从队首到队尾,因此枕头会传递到编号为 $mod + 1$ 的人手中。 - -时间复杂度 $O(1)$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def passThePillow(self, n: int, time: int) -> int: @@ -83,17 +66,6 @@ class Solution: return ans ``` -```python -class Solution: - def passThePillow(self, n: int, time: int) -> int: - k, mod = divmod(time, n - 1) - return n - mod if k & 1 else mod + 1 -``` - -### **Java** - - - ```java class Solution { public int passThePillow(int n, int time) { @@ -109,18 +81,6 @@ class Solution { } ``` -```java -class Solution { - public int passThePillow(int n, int time) { - int k = time / (n - 1); - int mod = time % (n - 1); - return (k & 1) == 1 ? n - mod : mod + 1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -137,19 +97,6 @@ public: }; ``` -```cpp -class Solution { -public: - int passThePillow(int n, int time) { - int k = time / (n - 1); - int mod = time % (n - 1); - return k & 1 ? n - mod : mod + 1; - } -}; -``` - -### **Go** - ```go func passThePillow(n int, time int) int { ans, k := 1, 1 @@ -163,18 +110,6 @@ func passThePillow(n int, time int) int { } ``` -```go -func passThePillow(n int, time int) int { - k, mod := time/(n-1), time%(n-1) - if k&1 == 1 { - return n - mod - } - return mod + 1 -} -``` - -### **TypeScript** - ```ts function passThePillow(n: number, time: number): number { let ans = 1, @@ -189,16 +124,6 @@ function passThePillow(n: number, time: number): number { } ``` -```ts -function passThePillow(n: number, time: number): number { - const k = time / (n - 1); - const mod = time % (n - 1); - return (k & 1) == 1 ? n - mod : mod + 1; -} -``` - -### **Rust** - ```rust impl Solution { pub fn pass_the_pillow(n: i32, time: i32) -> i32 { @@ -218,6 +143,67 @@ impl Solution { } ``` + + +### 方法二:数学 + +我们注意到,每一轮有 $n - 1$ 次传递,因此我们可以将 $time$ 除以 $n - 1$ 得到枕头传递的轮数 $k$,然后再将 $time$ 对 $n - 1$ 取余得到枕头在当前轮的剩余传递次数 $mod$。 + +接下来我们判断当前的轮数 $k$: + +- 如果 $k$ 为奇数,那么枕头当前的传递方向是从队尾到队首,因此枕头会传递到编号为 $n - mod$ 的人手中; +- 如果 $k$ 为偶数,那么枕头当前的传递方向是从队首到队尾,因此枕头会传递到编号为 $mod + 1$ 的人手中。 + +时间复杂度 $O(1)$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def passThePillow(self, n: int, time: int) -> int: + k, mod = divmod(time, n - 1) + return n - mod if k & 1 else mod + 1 +``` + +```java +class Solution { + public int passThePillow(int n, int time) { + int k = time / (n - 1); + int mod = time % (n - 1); + return (k & 1) == 1 ? n - mod : mod + 1; + } +} +``` + +```cpp +class Solution { +public: + int passThePillow(int n, int time) { + int k = time / (n - 1); + int mod = time % (n - 1); + return k & 1 ? n - mod : mod + 1; + } +}; +``` + +```go +func passThePillow(n int, time int) int { + k, mod := time/(n-1), time%(n-1) + if k&1 == 1 { + return n - mod + } + return mod + 1 +} +``` + +```ts +function passThePillow(n: number, time: number): number { + const k = time / (n - 1); + const mod = time % (n - 1); + return (k & 1) == 1 ? n - mod : mod + 1; +} +``` + ```rust impl Solution { pub fn pass_the_pillow(n: i32, time: i32) -> i32 { @@ -233,10 +219,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2582.Pass the Pillow/README_EN.md b/solution/2500-2599/2582.Pass the Pillow/README_EN.md index 6ed0a734663ef..ff65fdf75f9b6 100644 --- a/solution/2500-2599/2582.Pass the Pillow/README_EN.md +++ b/solution/2500-2599/2582.Pass the Pillow/README_EN.md @@ -40,27 +40,14 @@ Afer two seconds, the pillow is given to the 3rd person. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can simulate the process of passing the pillow, and each time the pillow is passed, if the pillow reaches the front or the end of the queue, the direction of the pillow will change, and the queue will continue to pass the pillow along the opposite direction. The time complexity is $O(time)$ and the space complexity is $O(1)$, where $time$ is the given time. -**Solution 2: Math** - -We notice that there are $n - 1$ passes in each round. Therefore, we can divide $time$ by $n - 1$ to get the number of rounds $k$ that the pillow is passed, and then take the remainder of $time$ modulo $n - 1$ to get the remaining passes $mod$ in the current round. - -Then we judge the current round $k$: - -- If $k$ is odd, then the current direction of the pillow is from the end of the queue to the front, so the pillow will be passed to the person with the number $n - mod$. -- If $k$ is even, then the current direction of the pillow is from the front of the queue to the back, so the pillow will be passed to the person with the number $mod + 1$. - -The time complexity is $O(1)$ and the space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def passThePillow(self, n: int, time: int) -> int: @@ -72,15 +59,6 @@ class Solution: return ans ``` -```python -class Solution: - def passThePillow(self, n: int, time: int) -> int: - k, mod = divmod(time, n - 1) - return n - mod if k & 1 else mod + 1 -``` - -### **Java** - ```java class Solution { public int passThePillow(int n, int time) { @@ -96,18 +74,6 @@ class Solution { } ``` -```java -class Solution { - public int passThePillow(int n, int time) { - int k = time / (n - 1); - int mod = time % (n - 1); - return (k & 1) == 1 ? n - mod : mod + 1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -124,19 +90,6 @@ public: }; ``` -```cpp -class Solution { -public: - int passThePillow(int n, int time) { - int k = time / (n - 1); - int mod = time % (n - 1); - return k & 1 ? n - mod : mod + 1; - } -}; -``` - -### **Go** - ```go func passThePillow(n int, time int) int { ans, k := 1, 1 @@ -150,18 +103,6 @@ func passThePillow(n int, time int) int { } ``` -```go -func passThePillow(n int, time int) int { - k, mod := time/(n-1), time%(n-1) - if k&1 == 1 { - return n - mod - } - return mod + 1 -} -``` - -### **TypeScript** - ```ts function passThePillow(n: number, time: number): number { let ans = 1, @@ -176,16 +117,6 @@ function passThePillow(n: number, time: number): number { } ``` -```ts -function passThePillow(n: number, time: number): number { - const k = time / (n - 1); - const mod = time % (n - 1); - return (k & 1) == 1 ? n - mod : mod + 1; -} -``` - -### **Rust** - ```rust impl Solution { pub fn pass_the_pillow(n: i32, time: i32) -> i32 { @@ -205,6 +136,67 @@ impl Solution { } ``` + + +### Solution 2: Math + +We notice that there are $n - 1$ passes in each round. Therefore, we can divide $time$ by $n - 1$ to get the number of rounds $k$ that the pillow is passed, and then take the remainder of $time$ modulo $n - 1$ to get the remaining passes $mod$ in the current round. + +Then we judge the current round $k$: + +- If $k$ is odd, then the current direction of the pillow is from the end of the queue to the front, so the pillow will be passed to the person with the number $n - mod$. +- If $k$ is even, then the current direction of the pillow is from the front of the queue to the back, so the pillow will be passed to the person with the number $mod + 1$. + +The time complexity is $O(1)$ and the space complexity is $O(1)$. + + + +```python +class Solution: + def passThePillow(self, n: int, time: int) -> int: + k, mod = divmod(time, n - 1) + return n - mod if k & 1 else mod + 1 +``` + +```java +class Solution { + public int passThePillow(int n, int time) { + int k = time / (n - 1); + int mod = time % (n - 1); + return (k & 1) == 1 ? n - mod : mod + 1; + } +} +``` + +```cpp +class Solution { +public: + int passThePillow(int n, int time) { + int k = time / (n - 1); + int mod = time % (n - 1); + return k & 1 ? n - mod : mod + 1; + } +}; +``` + +```go +func passThePillow(n int, time int) int { + k, mod := time/(n-1), time%(n-1) + if k&1 == 1 { + return n - mod + } + return mod + 1 +} +``` + +```ts +function passThePillow(n: number, time: number): number { + const k = time / (n - 1); + const mod = time % (n - 1); + return (k & 1) == 1 ? n - mod : mod + 1; +} +``` + ```rust impl Solution { pub fn pass_the_pillow(n: i32, time: i32) -> i32 { @@ -220,10 +212,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/README.md b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/README.md index e349ec1bc2e7f..d48d5e51a32bd 100644 --- a/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/README.md +++ b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/README.md @@ -54,26 +54,14 @@ ## 解法 - - -**方法一:BFS + 排序** +### 方法一:BFS + 排序 我们可以使用 BFS 遍历二叉树,同时记录每一层的节点和,然后对节点和数组进行排序,最后返回第 $k$ 大的节点和即可。注意,如果二叉树的层数小于 $k$,则返回 $-1$。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点数。 -**方法二:DFS + 排序** - -我们也可以使用 DFS 遍历二叉树,同时记录每一层的节点和,然后对节点和数组进行排序,最后返回第 $k$ 大的节点和即可。注意,如果二叉树的层数小于 $k$,则返回 $-1$。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点数。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -98,33 +86,6 @@ class Solution: return -1 if len(arr) < k else nlargest(k, arr)[-1] ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int: - def dfs(root, d): - if root is None: - return - if len(arr) <= d: - arr.append(0) - arr[d] += root.val - dfs(root.left, d + 1) - dfs(root.right, d + 1) - - arr = [] - dfs(root, 0) - return -1 if len(arr) < k else nlargest(k, arr)[-1] -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -169,50 +130,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private List arr = new ArrayList<>(); - - public long kthLargestLevelSum(TreeNode root, int k) { - dfs(root, 0); - if (arr.size() < k) { - return -1; - } - Collections.sort(arr, Collections.reverseOrder()); - return arr.get(k - 1); - } - - private void dfs(TreeNode root, int d) { - if (root == null) { - return; - } - if (arr.size() <= d) { - arr.add(0L); - } - arr.set(d, arr.get(d) + root.val); - dfs(root.left, d + 1); - dfs(root.right, d + 1); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -254,45 +171,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - long long kthLargestLevelSum(TreeNode* root, int k) { - vector arr; - function dfs = [&](TreeNode* root, int d) { - if (!root) { - return; - } - if (arr.size() <= d) { - arr.push_back(0); - } - arr[d] += root->val; - dfs(root->left, d + 1); - dfs(root->right, d + 1); - }; - dfs(root, 0); - if (arr.size() < k) { - return -1; - } - sort(arr.rbegin(), arr.rend()); - return arr[k - 1]; - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -328,41 +206,6 @@ func kthLargestLevelSum(root *TreeNode, k int) int64 { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func kthLargestLevelSum(root *TreeNode, k int) int64 { - arr := []int{} - var dfs func(*TreeNode, int) - dfs = func(root *TreeNode, d int) { - if root == nil { - return - } - if len(arr) <= d { - arr = append(arr, 0) - } - arr[d] += root.Val - dfs(root.Left, d+1) - dfs(root.Right, d+1) - } - - dfs(root, 0) - if n := len(arr); n >= k { - sort.Ints(arr) - return int64(arr[n-k]) - } - return -1 -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -403,6 +246,151 @@ function kthLargestLevelSum(root: TreeNode | null, k: number): number { } ``` + + +### 方法二:DFS + 排序 + +我们也可以使用 DFS 遍历二叉树,同时记录每一层的节点和,然后对节点和数组进行排序,最后返回第 $k$ 大的节点和即可。注意,如果二叉树的层数小于 $k$,则返回 $-1$。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点数。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int: + def dfs(root, d): + if root is None: + return + if len(arr) <= d: + arr.append(0) + arr[d] += root.val + dfs(root.left, d + 1) + dfs(root.right, d + 1) + + arr = [] + dfs(root, 0) + return -1 if len(arr) < k else nlargest(k, arr)[-1] +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List arr = new ArrayList<>(); + + public long kthLargestLevelSum(TreeNode root, int k) { + dfs(root, 0); + if (arr.size() < k) { + return -1; + } + Collections.sort(arr, Collections.reverseOrder()); + return arr.get(k - 1); + } + + private void dfs(TreeNode root, int d) { + if (root == null) { + return; + } + if (arr.size() <= d) { + arr.add(0L); + } + arr.set(d, arr.get(d) + root.val); + dfs(root.left, d + 1); + dfs(root.right, d + 1); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + long long kthLargestLevelSum(TreeNode* root, int k) { + vector arr; + function dfs = [&](TreeNode* root, int d) { + if (!root) { + return; + } + if (arr.size() <= d) { + arr.push_back(0); + } + arr[d] += root->val; + dfs(root->left, d + 1); + dfs(root->right, d + 1); + }; + dfs(root, 0); + if (arr.size() < k) { + return -1; + } + sort(arr.rbegin(), arr.rend()); + return arr[k - 1]; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func kthLargestLevelSum(root *TreeNode, k int) int64 { + arr := []int{} + var dfs func(*TreeNode, int) + dfs = func(root *TreeNode, d int) { + if root == nil { + return + } + if len(arr) <= d { + arr = append(arr, 0) + } + arr[d] += root.Val + dfs(root.Left, d+1) + dfs(root.Right, d+1) + } + + dfs(root, 0) + if n := len(arr); n >= k { + sort.Ints(arr) + return int64(arr[n-k]) + } + return -1 +} +``` + ```ts /** * Definition for a binary tree node. @@ -440,10 +428,6 @@ function kthLargestLevelSum(root: TreeNode | null, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/README_EN.md b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/README_EN.md index da967f27afd44..5a52e1edcf5dd 100644 --- a/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/README_EN.md +++ b/solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/README_EN.md @@ -46,22 +46,14 @@ The 2nd largest level sum is 13. ## Solutions -**Solution 1: BFS + Sorting** +### Solution 1: BFS + Sorting We can use BFS to traverse the binary tree, while recording the sum of nodes at each level, then sort the array of node sums, and finally return the $k$th largest node sum. Note that if the number of levels in the binary tree is less than $k$, then return $-1$. The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree. -**Solution 2: DFS + Sorting** - -We can also use DFS to traverse the binary tree, while recording the sum of nodes at each level, then sort the array of node sums, and finally return the $k$th largest node sum. Note that if the number of levels in the binary tree is less than $k$, then return $-1$. - -The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree. - -### **Python3** - ```python # Definition for a binary tree node. # class TreeNode: @@ -86,31 +78,6 @@ class Solution: return -1 if len(arr) < k else nlargest(k, arr)[-1] ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int: - def dfs(root, d): - if root is None: - return - if len(arr) <= d: - arr.append(0) - arr[d] += root.val - dfs(root.left, d + 1) - dfs(root.right, d + 1) - - arr = [] - dfs(root, 0) - return -1 if len(arr) < k else nlargest(k, arr)[-1] -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -155,50 +122,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - private List arr = new ArrayList<>(); - - public long kthLargestLevelSum(TreeNode root, int k) { - dfs(root, 0); - if (arr.size() < k) { - return -1; - } - Collections.sort(arr, Collections.reverseOrder()); - return arr.get(k - 1); - } - - private void dfs(TreeNode root, int d) { - if (root == null) { - return; - } - if (arr.size() <= d) { - arr.add(0L); - } - arr.set(d, arr.get(d) + root.val); - dfs(root.left, d + 1); - dfs(root.right, d + 1); - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -240,45 +163,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - long long kthLargestLevelSum(TreeNode* root, int k) { - vector arr; - function dfs = [&](TreeNode* root, int d) { - if (!root) { - return; - } - if (arr.size() <= d) { - arr.push_back(0); - } - arr[d] += root->val; - dfs(root->left, d + 1); - dfs(root->right, d + 1); - }; - dfs(root, 0); - if (arr.size() < k) { - return -1; - } - sort(arr.rbegin(), arr.rend()); - return arr[k - 1]; - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -314,41 +198,6 @@ func kthLargestLevelSum(root *TreeNode, k int) int64 { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func kthLargestLevelSum(root *TreeNode, k int) int64 { - arr := []int{} - var dfs func(*TreeNode, int) - dfs = func(root *TreeNode, d int) { - if root == nil { - return - } - if len(arr) <= d { - arr = append(arr, 0) - } - arr[d] += root.Val - dfs(root.Left, d+1) - dfs(root.Right, d+1) - } - - dfs(root, 0) - if n := len(arr); n >= k { - sort.Ints(arr) - return int64(arr[n-k]) - } - return -1 -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -389,6 +238,151 @@ function kthLargestLevelSum(root: TreeNode | null, k: number): number { } ``` + + +### Solution 2: DFS + Sorting + +We can also use DFS to traverse the binary tree, while recording the sum of nodes at each level, then sort the array of node sums, and finally return the $k$th largest node sum. Note that if the number of levels in the binary tree is less than $k$, then return $-1$. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree. + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int: + def dfs(root, d): + if root is None: + return + if len(arr) <= d: + arr.append(0) + arr[d] += root.val + dfs(root.left, d + 1) + dfs(root.right, d + 1) + + arr = [] + dfs(root, 0) + return -1 if len(arr) < k else nlargest(k, arr)[-1] +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private List arr = new ArrayList<>(); + + public long kthLargestLevelSum(TreeNode root, int k) { + dfs(root, 0); + if (arr.size() < k) { + return -1; + } + Collections.sort(arr, Collections.reverseOrder()); + return arr.get(k - 1); + } + + private void dfs(TreeNode root, int d) { + if (root == null) { + return; + } + if (arr.size() <= d) { + arr.add(0L); + } + arr.set(d, arr.get(d) + root.val); + dfs(root.left, d + 1); + dfs(root.right, d + 1); + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + long long kthLargestLevelSum(TreeNode* root, int k) { + vector arr; + function dfs = [&](TreeNode* root, int d) { + if (!root) { + return; + } + if (arr.size() <= d) { + arr.push_back(0); + } + arr[d] += root->val; + dfs(root->left, d + 1); + dfs(root->right, d + 1); + }; + dfs(root, 0); + if (arr.size() < k) { + return -1; + } + sort(arr.rbegin(), arr.rend()); + return arr[k - 1]; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func kthLargestLevelSum(root *TreeNode, k int) int64 { + arr := []int{} + var dfs func(*TreeNode, int) + dfs = func(root *TreeNode, d int) { + if root == nil { + return + } + if len(arr) <= d { + arr = append(arr, 0) + } + arr[d] += root.Val + dfs(root.Left, d+1) + dfs(root.Right, d+1) + } + + dfs(root, 0) + if n := len(arr); n >= k { + sort.Ints(arr) + return int64(arr[n-k]) + } + return -1 +} +``` + ```ts /** * Definition for a binary tree node. @@ -426,10 +420,6 @@ function kthLargestLevelSum(root: TreeNode | null, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2584.Split the Array to Make Coprime Products/README.md b/solution/2500-2599/2584.Split the Array to Make Coprime Products/README.md index a9618926aee6b..3e1e3ff604226 100644 --- a/solution/2500-2599/2584.Split the Array to Make Coprime Products/README.md +++ b/solution/2500-2599/2584.Split the Array to Make Coprime Products/README.md @@ -53,16 +53,10 @@ ## 解法 - - -**方法一:质因数分解** +### 方法一:质因数分解 -### **Python3** - - - ```python class Solution: def findValidSplit(self, nums: List[int]) -> int: @@ -93,10 +87,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int findValidSplit(int[] nums) { @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -184,8 +172,6 @@ public: }; ``` -### **Go** - ```go func findValidSplit(nums []int) int { first := map[int]int{} @@ -226,10 +212,6 @@ func findValidSplit(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2584.Split the Array to Make Coprime Products/README_EN.md b/solution/2500-2599/2584.Split the Array to Make Coprime Products/README_EN.md index 50fc7fc4d0c60..09b368675aaf7 100644 --- a/solution/2500-2599/2584.Split the Array to Make Coprime Products/README_EN.md +++ b/solution/2500-2599/2584.Split the Array to Make Coprime Products/README_EN.md @@ -46,9 +46,9 @@ There is no valid split. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int findValidSplit(int[] nums) { @@ -125,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +165,6 @@ public: }; ``` -### **Go** - ```go func findValidSplit(nums []int) int { first := map[int]int{} @@ -211,10 +205,6 @@ func findValidSplit(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2585.Number of Ways to Earn Points/README.md b/solution/2500-2599/2585.Number of Ways to Earn Points/README.md index f75b24e3ab603..ff5b0b8cda1a4 100644 --- a/solution/2500-2599/2585.Number of Ways to Earn Points/README.md +++ b/solution/2500-2599/2585.Number of Ways to Earn Points/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示前 $i$ 种类型的题目中,恰好得到 $j$ 分的方法数。初始时 $f[0][0] = 1$,其余 $f[i][j] = 0$。答案即为 $f[n][target]$。 @@ -84,10 +82,6 @@ $$ -### **Python3** - - - ```python class Solution: def waysToReachTarget(self, target: int, types: List[List[int]]) -> int: @@ -104,10 +98,6 @@ class Solution: return f[n][target] ``` -### **Java** - - - ```java class Solution { public int waysToReachTarget(int target, int[][] types) { @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func waysToReachTarget(target int, types [][]int) int { n := len(types) @@ -181,8 +167,6 @@ func waysToReachTarget(target int, types [][]int) int { } ``` -### **TypeScript** - ```ts function waysToReachTarget(target: number, types: number[][]): number { const n = types.length; @@ -203,10 +187,6 @@ function waysToReachTarget(target: number, types: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2585.Number of Ways to Earn Points/README_EN.md b/solution/2500-2599/2585.Number of Ways to Earn Points/README_EN.md index bd6f63bf71f7e..a3a25c86c8759 100644 --- a/solution/2500-2599/2585.Number of Ways to Earn Points/README_EN.md +++ b/solution/2500-2599/2585.Number of Ways to Earn Points/README_EN.md @@ -66,7 +66,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ to represent the number of methods to get $j$ points exactly from the first $i$ types of questions. Initially, $f[0][0] = 1$, and the rest $f[i][j] = 0$. The answer is $f[n][target]$. @@ -84,8 +84,6 @@ The time complexity is $O(n \times target \times count)$ and the space complexit -### **Python3** - ```python class Solution: def waysToReachTarget(self, target: int, types: List[List[int]]) -> int: @@ -102,8 +100,6 @@ class Solution: return f[n][target] ``` -### **Java** - ```java class Solution { public int waysToReachTarget(int target, int[][] types) { @@ -126,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +146,6 @@ public: }; ``` -### **Go** - ```go func waysToReachTarget(target int, types [][]int) int { n := len(types) @@ -177,8 +169,6 @@ func waysToReachTarget(target int, types [][]int) int { } ``` -### **TypeScript** - ```ts function waysToReachTarget(target: number, types: number[][]): number { const n = types.length; @@ -199,10 +189,6 @@ function waysToReachTarget(target: number, types: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/README.md b/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/README.md index eee5fbf10ea47..a0bb0975e316e 100644 --- a/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/README.md +++ b/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们只需要遍历区间 $[left,.. right]$ 内的字符串,判断其是否以元音字母开头和结尾即可。若是,则答案加一。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def vowelStrings(self, words: List[str], left: int, right: int) -> int: @@ -76,10 +70,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public int vowelStrings(String[] words, int left, int right) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func vowelStrings(words []string, left int, right int) (ans int) { check := func(c byte) bool { @@ -134,8 +120,6 @@ func vowelStrings(words []string, left int, right int) (ans int) { } ``` -### **TypeScript** - ```ts function vowelStrings(words: string[], left: number, right: number): number { let ans = 0; @@ -150,8 +134,6 @@ function vowelStrings(words: string[], left: number, right: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn vowel_strings(words: Vec, left: i32, right: i32) -> i32 { @@ -172,10 +154,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/README_EN.md b/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/README_EN.md index bae786e9c1c1f..9d301d5ea138a 100644 --- a/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/README_EN.md +++ b/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/README_EN.md @@ -48,7 +48,7 @@ The number of vowel strings in the mentioned range is 3. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We just need to traverse the string in the interval $[left,.. right]$, and check if it starts and ends with a vowel. If so, the answer plus one. @@ -58,8 +58,6 @@ The time complexity is $O(m)$, and the space complexity is $O(1)$. Where $m = ri -### **Python3** - ```python class Solution: def vowelStrings(self, words: List[str], left: int, right: int) -> int: @@ -68,8 +66,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public int vowelStrings(String[] words, int left, int right) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +102,6 @@ public: }; ``` -### **Go** - ```go func vowelStrings(words []string, left int, right int) (ans int) { check := func(c byte) bool { @@ -124,8 +116,6 @@ func vowelStrings(words []string, left int, right int) (ans int) { } ``` -### **TypeScript** - ```ts function vowelStrings(words: string[], left: number, right: number): number { let ans = 0; @@ -140,8 +130,6 @@ function vowelStrings(words: string[], left: number, right: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn vowel_strings(words: Vec, left: i32, right: i32) -> i32 { @@ -162,10 +150,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2587.Rearrange Array to Maximize Prefix Score/README.md b/solution/2500-2599/2587.Rearrange Array to Maximize Prefix Score/README.md index 7f25bc0a5680f..0d08763af78ad 100644 --- a/solution/2500-2599/2587.Rearrange Array to Maximize Prefix Score/README.md +++ b/solution/2500-2599/2587.Rearrange Array to Maximize Prefix Score/README.md @@ -41,9 +41,7 @@ prefix = [2,5,6,5,2,2,-1] ,分数为 6 。 ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 要使得前缀和数组中正整数的个数最多,就要使得前缀和数组中的元素尽可能大,即尽可能多的正整数相加。因此,我们可以将数组 $nums$ 降序排序,然后遍历数组,维护前缀和 $s$,如果 $s \leq 0$,则说明当前位置以及之后的位置都不可能再有正整数,因此直接返回当前位置即可。 @@ -53,10 +51,6 @@ prefix = [2,5,6,5,2,2,-1] ,分数为 6 。 -### **Python3** - - - ```python class Solution: def maxScore(self, nums: List[int]) -> int: @@ -69,10 +63,6 @@ class Solution: return len(nums) ``` -### **Java** - - - ```java class Solution { public int maxScore(int[] nums) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +98,6 @@ public: }; ``` -### **Go** - ```go func maxScore(nums []int) int { sort.Ints(nums) @@ -127,26 +113,6 @@ func maxScore(nums []int) int { } ``` -### **Rust** - -```rust -impl Solution { - pub fn max_score(mut nums: Vec) -> i32 { - nums.sort_by(|a, b| b.cmp(a)); - let mut s: i64 = 0; - for (i, &x) in nums.iter().enumerate() { - s += x as i64; - if s <= 0 { - return i as i32; - } - } - nums.len() as i32 - } -} -``` - -### **TypeScript** - ```ts function maxScore(nums: number[]): number { nums.sort((a, b) => a - b); @@ -162,10 +128,22 @@ function maxScore(nums: number[]): number { } ``` -### **...** - -``` - +```rust +impl Solution { + pub fn max_score(mut nums: Vec) -> i32 { + nums.sort_by(|a, b| b.cmp(a)); + let mut s: i64 = 0; + for (i, &x) in nums.iter().enumerate() { + s += x as i64; + if s <= 0 { + return i as i32; + } + } + nums.len() as i32 + } +} ``` + + diff --git a/solution/2500-2599/2587.Rearrange Array to Maximize Prefix Score/README_EN.md b/solution/2500-2599/2587.Rearrange Array to Maximize Prefix Score/README_EN.md index d672fe1c56784..0ca2e3a0236dd 100644 --- a/solution/2500-2599/2587.Rearrange Array to Maximize Prefix Score/README_EN.md +++ b/solution/2500-2599/2587.Rearrange Array to Maximize Prefix Score/README_EN.md @@ -39,7 +39,7 @@ It can be shown that 6 is the maximum score we can obtain. ## Solutions -**Solution 1: Greedy + Sorting** +### Solution 1: Greedy + Sorting To maximize the number of positive integers in the prefix sum array, we need to make the elements in the prefix sum array as large as possible, that is, to add as many positive integers as possible. Therefore, we can sort the array $nums$ in descending order, then traverse the array, maintaining the prefix sum $s$. If $s \leq 0$, it means that there can be no more positive integers in the current position and the positions after it, so we can directly return the current position. @@ -49,8 +49,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def maxScore(self, nums: List[int]) -> int: @@ -63,8 +61,6 @@ class Solution: return len(nums) ``` -### **Java** - ```java class Solution { public int maxScore(int[] nums) { @@ -82,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +96,6 @@ public: }; ``` -### **Go** - ```go func maxScore(nums []int) int { sort.Ints(nums) @@ -119,26 +111,6 @@ func maxScore(nums []int) int { } ``` -### **Rust** - -```rust -impl Solution { - pub fn max_score(mut nums: Vec) -> i32 { - nums.sort_by(|a, b| b.cmp(a)); - let mut s: i64 = 0; - for (i, &x) in nums.iter().enumerate() { - s += x as i64; - if s <= 0 { - return i as i32; - } - } - nums.len() as i32 - } -} -``` - -### **TypeScript** - ```ts function maxScore(nums: number[]): number { nums.sort((a, b) => a - b); @@ -154,10 +126,22 @@ function maxScore(nums: number[]): number { } ``` -### **...** - -``` - +```rust +impl Solution { + pub fn max_score(mut nums: Vec) -> i32 { + nums.sort_by(|a, b| b.cmp(a)); + let mut s: i64 = 0; + for (i, &x) in nums.iter().enumerate() { + s += x as i64; + if s <= 0 { + return i as i32; + } + } + nums.len() as i32 + } +} ``` + + diff --git a/solution/2500-2599/2588.Count the Number of Beautiful Subarrays/README.md b/solution/2500-2599/2588.Count the Number of Beautiful Subarrays/README.md index 0fe27e5df5616..578c6bc42de30 100644 --- a/solution/2500-2599/2588.Count the Number of Beautiful Subarrays/README.md +++ b/solution/2500-2599/2588.Count the Number of Beautiful Subarrays/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:前缀异或 + 哈希表** +### 方法一:前缀异或 + 哈希表 我们观察发现,一个子数组能变成一个全为 $0$ 的数组,当且仅当该子数组中的所有元素,每一个二进制位上的 $1$ 的个数都是偶数个。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def beautifulSubarrays(self, nums: List[int]) -> int: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long beautifulSubarrays(int[] nums) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func beautifulSubarrays(nums []int) (ans int64) { cnt := map[int]int{0: 1} @@ -143,8 +129,6 @@ func beautifulSubarrays(nums []int) (ans int64) { } ``` -### **TypeScript** - ```ts function beautifulSubarrays(nums: number[]): number { const cnt = new Map(); @@ -160,10 +144,6 @@ function beautifulSubarrays(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2588.Count the Number of Beautiful Subarrays/README_EN.md b/solution/2500-2599/2588.Count the Number of Beautiful Subarrays/README_EN.md index 3d2b5cc41d5f5..349aad623a430 100644 --- a/solution/2500-2599/2588.Count the Number of Beautiful Subarrays/README_EN.md +++ b/solution/2500-2599/2588.Count the Number of Beautiful Subarrays/README_EN.md @@ -52,7 +52,7 @@ ## Solutions -**Solution 1: Prefix XOR + Hash Table** +### Solution 1: Prefix XOR + Hash Table We observe that a subarray can become an array of all $0$s if and only if the number of $1$s on each binary bit of all elements in the subarray is even. @@ -66,8 +66,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def beautifulSubarrays(self, nums: List[int]) -> int: @@ -80,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long beautifulSubarrays(int[] nums) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func beautifulSubarrays(nums []int) (ans int64) { cnt := map[int]int{0: 1} @@ -133,8 +125,6 @@ func beautifulSubarrays(nums []int) (ans int64) { } ``` -### **TypeScript** - ```ts function beautifulSubarrays(nums: number[]): number { const cnt = new Map(); @@ -150,10 +140,6 @@ function beautifulSubarrays(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2589.Minimum Time to Complete All Tasks/README.md b/solution/2500-2599/2589.Minimum Time to Complete All Tasks/README.md index 6f45b54a08c53..f9119276b684e 100644 --- a/solution/2500-2599/2589.Minimum Time to Complete All Tasks/README.md +++ b/solution/2500-2599/2589.Minimum Time to Complete All Tasks/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 我们观察发现,题目相当于在每一个区间 $[start,..,end]$ 中,选择 $duration$ 个整数时间点,使得总共选择的整数时间点最少。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def findMinimumTime(self, tasks: List[List[int]]) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int findMinimumTime(int[][] tasks) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func findMinimumTime(tasks [][]int) (ans int) { sort.Slice(tasks, func(i, j int) bool { return tasks[i][1] < tasks[j][1] }) @@ -163,8 +149,6 @@ func findMinimumTime(tasks [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function findMinimumTime(tasks: number[][]): number { tasks.sort((a, b) => a[1] - b[1]); @@ -185,10 +169,6 @@ function findMinimumTime(tasks: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2589.Minimum Time to Complete All Tasks/README_EN.md b/solution/2500-2599/2589.Minimum Time to Complete All Tasks/README_EN.md index 24cf6e087dca7..53261549a3ec6 100644 --- a/solution/2500-2599/2589.Minimum Time to Complete All Tasks/README_EN.md +++ b/solution/2500-2599/2589.Minimum Time to Complete All Tasks/README_EN.md @@ -47,7 +47,7 @@ The computer will be on for a total of 4 seconds. ## Solutions -**Solution 1: Greedy + Sorting** +### Solution 1: Greedy + Sorting We observe that the problem is equivalent to selecting $duration$ integer time points in each interval $[start,..,end]$, so that the total number of selected integer time points is minimized. @@ -61,8 +61,6 @@ The time complexity is $O(n \times \log n + n \times m)$, and the space complexi -### **Python3** - ```python class Solution: def findMinimumTime(self, tasks: List[List[int]]) -> int: @@ -81,8 +79,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int findMinimumTime(int[][] tasks) { @@ -106,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +126,6 @@ public: }; ``` -### **Go** - ```go func findMinimumTime(tasks [][]int) (ans int) { sort.Slice(tasks, func(i, j int) bool { return tasks[i][1] < tasks[j][1] }) @@ -155,8 +147,6 @@ func findMinimumTime(tasks [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function findMinimumTime(tasks: number[][]): number { tasks.sort((a, b) => a[1] - b[1]); @@ -177,10 +167,6 @@ function findMinimumTime(tasks: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2590.Design a Todo List/README.md b/solution/2500-2599/2590.Design a Todo List/README.md index 95b1788e9f1ba..5f9a4dad7ccc7 100644 --- a/solution/2500-2599/2590.Design a Todo List/README.md +++ b/solution/2500-2599/2590.Design a Todo List/README.md @@ -61,9 +61,7 @@ todoList.getAllTasks(1); // 返回["Task3", "Task1"]。用户1现在有两个未 ## 解法 - - -**方法一:哈希表 + 有序集合** +### 方法一:哈希表 + 有序集合 我们使用哈希表 $tasks$ 记录每个用户的任务集合,其中键为用户 ID,值为一个有序集合,按照任务的截止日期排序。另外用一个变量 $i$ 记录当前任务的 ID。 @@ -79,10 +77,6 @@ todoList.getAllTasks(1); // 返回["Task3", "Task1"]。用户1现在有两个未 -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -121,10 +115,6 @@ class TodoList: # obj.completeTask(userId,taskId) ``` -### **Java** - - - ```java class Task { int taskId; @@ -201,8 +191,6 @@ class TodoList { */ ``` -### **Rust** - ```rust use std::collections::{ HashMap, HashSet }; @@ -317,22 +305,6 @@ impl TodoList { } ``` -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2590.Design a Todo List/README_EN.md b/solution/2500-2599/2590.Design a Todo List/README_EN.md index 1f6926e5656dc..7b8b1dd18a5af 100644 --- a/solution/2500-2599/2590.Design a Todo List/README_EN.md +++ b/solution/2500-2599/2590.Design a Todo List/README_EN.md @@ -57,7 +57,7 @@ todoList.getAllTasks(1); // return ["Task3", "Task1"]. User ## Solutions -**Solution 1: Hash Table + Sorted Set** +### Solution 1: Hash Table + Sorted Set We use a hash table $tasks$ to record the set of tasks for each user, where the key is the user ID and the value is a sorted set sorted by the deadline of the task. In addition, we use a variable $i$ to record the current task ID. @@ -73,8 +73,6 @@ The space complexity is $O(n)$. Where $n$ is the number of all tasks. -### **Python3** - ```python from sortedcontainers import SortedList @@ -113,8 +111,6 @@ class TodoList: # obj.completeTask(userId,taskId) ``` -### **Java** - ```java class Task { int taskId; @@ -191,8 +187,6 @@ class TodoList { */ ``` -### **Rust** - ```rust use std::collections::{ HashMap, HashSet }; @@ -307,22 +301,6 @@ impl TodoList { } ``` -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2591.Distribute Money to Maximum Children/README.md b/solution/2500-2599/2591.Distribute Money to Maximum Children/README.md index 55c8660c82ecf..0d2111f0ba079 100644 --- a/solution/2500-2599/2591.Distribute Money to Maximum Children/README.md +++ b/solution/2500-2599/2591.Distribute Money to Maximum Children/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:分类讨论** +### 方法一:分类讨论 如果 $money \lt children$,那么一定存在儿童没有分到钱,返回 $-1$。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def distMoney(self, money: int, children: int) -> int: @@ -83,10 +77,6 @@ class Solution: return (money - children) // 7 ``` -### **Java** - - - ```java class Solution { public int distMoney(int money, int children) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func distMoney(money int, children int) int { if money < children { @@ -144,8 +130,6 @@ func distMoney(money int, children int) int { } ``` -### **TypeScript** - ```ts function distMoney(money: number, children: number): number { if (money < children) { @@ -161,8 +145,6 @@ function distMoney(money: number, children: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn dist_money(money: i32, children: i32) -> i32 { @@ -183,10 +165,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2591.Distribute Money to Maximum Children/README_EN.md b/solution/2500-2599/2591.Distribute Money to Maximum Children/README_EN.md index 8d859db8d070f..3fd904b7f19bf 100644 --- a/solution/2500-2599/2591.Distribute Money to Maximum Children/README_EN.md +++ b/solution/2500-2599/2591.Distribute Money to Maximum Children/README_EN.md @@ -48,7 +48,7 @@ It can be proven that no distribution exists such that number of children gettin ## Solutions -**Solution 1: Case analysis** +### Solution 1: Case analysis If $money \lt children$, then there must be a child who did not receive money, return $-1$. @@ -62,8 +62,6 @@ Time complexity $O(1)$, space complexity $O(1)$. -### **Python3** - ```python class Solution: def distMoney(self, money: int, children: int) -> int: @@ -77,8 +75,6 @@ class Solution: return (money - children) // 7 ``` -### **Java** - ```java class Solution { public int distMoney(int money, int children) { @@ -97,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func distMoney(money int, children int) int { if money < children { @@ -136,8 +128,6 @@ func distMoney(money int, children int) int { } ``` -### **TypeScript** - ```ts function distMoney(money: number, children: number): number { if (money < children) { @@ -153,8 +143,6 @@ function distMoney(money: number, children: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn dist_money(money: i32, children: i32) -> i32 { @@ -175,10 +163,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2592.Maximize Greatness of an Array/README.md b/solution/2500-2599/2592.Maximize Greatness of an Array/README.md index a74ba9376e593..8b9551074fc05 100644 --- a/solution/2500-2599/2592.Maximize Greatness of an Array/README.md +++ b/solution/2500-2599/2592.Maximize Greatness of an Array/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们可以先将数组 $nums$ 进行排序。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def maximizeGreatness(self, nums: List[int]) -> int: @@ -68,10 +62,6 @@ class Solution: return i ``` -### **Java** - - - ```java class Solution { public int maximizeGreatness(int[] nums) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +91,6 @@ public: }; ``` -### **Go** - ```go func maximizeGreatness(nums []int) int { sort.Ints(nums) @@ -118,8 +104,6 @@ func maximizeGreatness(nums []int) int { } ``` -### **TypeScript** - ```ts function maximizeGreatness(nums: number[]): number { nums.sort((a, b) => a - b); @@ -133,10 +117,6 @@ function maximizeGreatness(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2592.Maximize Greatness of an Array/README_EN.md b/solution/2500-2599/2592.Maximize Greatness of an Array/README_EN.md index 07cea0d812745..a49230525806b 100644 --- a/solution/2500-2599/2592.Maximize Greatness of an Array/README_EN.md +++ b/solution/2500-2599/2592.Maximize Greatness of an Array/README_EN.md @@ -38,7 +38,7 @@ At indices = 0, 1, and 2, perm[i] > nums[i]. Hence, we return 3. ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy We can sort the array $nums$ first. @@ -50,8 +50,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def maximizeGreatness(self, nums: List[int]) -> int: @@ -62,8 +60,6 @@ class Solution: return i ``` -### **Java** - ```java class Solution { public int maximizeGreatness(int[] nums) { @@ -79,8 +75,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -95,8 +89,6 @@ public: }; ``` -### **Go** - ```go func maximizeGreatness(nums []int) int { sort.Ints(nums) @@ -110,8 +102,6 @@ func maximizeGreatness(nums []int) int { } ``` -### **TypeScript** - ```ts function maximizeGreatness(nums: number[]): number { nums.sort((a, b) => a - b); @@ -125,10 +115,6 @@ function maximizeGreatness(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/README.md b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/README.md index 33f1f7137236a..88b170fc67d53 100644 --- a/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/README.md +++ b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:优先队列(小根堆)** +### 方法一:优先队列(小根堆) 我们用一个优先队列维护数组中未被标记的元素,队列中每一项为一个二元组 $(x, i)$,其中 $x$ 和 $i$ 分别表示数组中的元素值和下标,用一个数组 $vis$ 记录数组中的元素是否被标记。 @@ -66,24 +64,8 @@ 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组的长度。 -**方法二:排序** - -我们可以创建一个下标数组 $idx$,其中 $idx[i]=i$,然后我们对数组 $idx$ 按照数组 $nums$ 中的元素值进行排序,如果元素值相同,则按照下标值进行排序。 - -接下来创建一个长度为 $n+2$ 的数组 $vis$,其中 $vis[i]=false$,表示数组中的元素是否被标记。 - -我们遍历下标数组 $idx$,对于数组中的每一个下标 $i$,如果 $vis[i + 1]$ 为 $false$,则表示 $i$ 位置的元素未被标记,我们将 $nums[i]$ 加入答案,然后标记 $i$ 位置的元素,以及 $i$ 位置的左右相邻元素,即 $i - 1$ 和 $i + 1$ 位置的元素。继续遍历下标数组 $idx$,直到遍历结束。 - -最后返回答案即可。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组的长度。 - -### **Python3** - - - ```python class Solution: def findScore(self, nums: List[int]) -> int: @@ -104,24 +86,6 @@ class Solution: return ans ``` -```python -class Solution: - def findScore(self, nums: List[int]) -> int: - n = len(nums) - vis = [False] * (n + 2) - idx = sorted(range(n), key=lambda i: (nums[i], i)) - ans = 0 - for i in idx: - if not vis[i + 1]: - ans += nums[i] - vis[i] = vis[i + 2] = True - return ans -``` - -### **Java** - - - ```java class Solution { public long findScore(int[] nums) { @@ -151,31 +115,6 @@ class Solution { } ``` -```java -class Solution { - public long findScore(int[] nums) { - int n = nums.length; - boolean[] vis = new boolean[n + 2]; - Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } - Arrays.sort(idx, (i, j) -> nums[i] - nums[j]); - long ans = 0; - for (int i : idx) { - if (!vis[i + 1]) { - ans += nums[i]; - vis[i] = true; - vis[i + 2] = true; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -208,31 +147,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long findScore(vector& nums) { - int n = nums.size(); - vector idx(n); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { - return nums[i] < nums[j] || (nums[i] == nums[j] && i < j); - }); - long long ans = 0; - vector vis(n + 2); - for (int i : idx) { - if (!vis[i + 1]) { - ans += nums[i]; - vis[i] = vis[i + 2] = true; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func findScore(nums []int) (ans int64) { h := hp{} @@ -268,30 +182,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -```go -func findScore(nums []int) (ans int64) { - n := len(nums) - idx := make([]int, n) - for i := range idx { - idx[i] = i - } - sort.Slice(idx, func(i, j int) bool { - i, j = idx[i], idx[j] - return nums[i] < nums[j] || (nums[i] == nums[j] && i < j) - }) - vis := make([]bool, n+2) - for _, i := range idx { - if !vis[i+1] { - ans += int64(nums[i]) - vis[i], vis[i+2] = true, true - } - } - return -} -``` - -### **TypeScript** - ```ts interface pair { x: number; @@ -329,6 +219,104 @@ function findScore(nums: number[]): number { } ``` + + +### 方法二:排序 + +我们可以创建一个下标数组 $idx$,其中 $idx[i]=i$,然后我们对数组 $idx$ 按照数组 $nums$ 中的元素值进行排序,如果元素值相同,则按照下标值进行排序。 + +接下来创建一个长度为 $n+2$ 的数组 $vis$,其中 $vis[i]=false$,表示数组中的元素是否被标记。 + +我们遍历下标数组 $idx$,对于数组中的每一个下标 $i$,如果 $vis[i + 1]$ 为 $false$,则表示 $i$ 位置的元素未被标记,我们将 $nums[i]$ 加入答案,然后标记 $i$ 位置的元素,以及 $i$ 位置的左右相邻元素,即 $i - 1$ 和 $i + 1$ 位置的元素。继续遍历下标数组 $idx$,直到遍历结束。 + +最后返回答案即可。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组的长度。 + + + +```python +class Solution: + def findScore(self, nums: List[int]) -> int: + n = len(nums) + vis = [False] * (n + 2) + idx = sorted(range(n), key=lambda i: (nums[i], i)) + ans = 0 + for i in idx: + if not vis[i + 1]: + ans += nums[i] + vis[i] = vis[i + 2] = True + return ans +``` + +```java +class Solution { + public long findScore(int[] nums) { + int n = nums.length; + boolean[] vis = new boolean[n + 2]; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> nums[i] - nums[j]); + long ans = 0; + for (int i : idx) { + if (!vis[i + 1]) { + ans += nums[i]; + vis[i] = true; + vis[i + 2] = true; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + long long findScore(vector& nums) { + int n = nums.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return nums[i] < nums[j] || (nums[i] == nums[j] && i < j); + }); + long long ans = 0; + vector vis(n + 2); + for (int i : idx) { + if (!vis[i + 1]) { + ans += nums[i]; + vis[i] = vis[i + 2] = true; + } + } + return ans; + } +}; +``` + +```go +func findScore(nums []int) (ans int64) { + n := len(nums) + idx := make([]int, n) + for i := range idx { + idx[i] = i + } + sort.Slice(idx, func(i, j int) bool { + i, j = idx[i], idx[j] + return nums[i] < nums[j] || (nums[i] == nums[j] && i < j) + }) + vis := make([]bool, n+2) + for _, i := range idx { + if !vis[i+1] { + ans += int64(nums[i]) + vis[i], vis[i+2] = true, true + } + } + return +} +``` + ```ts function findScore(nums: number[]): number { const n = nums.length; @@ -350,10 +338,6 @@ function findScore(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/README_EN.md b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/README_EN.md index fc644d88664df..fe38a5b9d6eef 100644 --- a/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/README_EN.md +++ b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/README_EN.md @@ -52,7 +52,7 @@ Our score is 1 + 2 + 2 = 5. ## Solutions -**Solution 1: Priority Queue (Min Heap)** +### Solution 1: Priority Queue (Min Heap) We use a priority queue to maintain the unmarked elements in the array, and each item in the queue is a tuple $(x, i)$, where $x$ and $i$ represent the element value and index of the array respectively. An array $vis$ is used to record whether the element in the array is marked. @@ -62,22 +62,8 @@ Finally, return the answer. The time complexity is $O(n \times \log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array. -**Solution 2: Sorting** - -We can create an index array $idx$ where $idx[i]=i$, and then we sort the index array $idx$ according to the element values in the array $nums$. If the element values are the same, then sort them according to the index values. - -Next, create an array $vis$ of length $n+2$ where $vis[i]=false$, which means whether the element in the array is marked. - -We traverse the index array $idx$, and for each index $i$ in the array, if $vis[i+1]$ is $false$, that is, the element at position $i$ is not marked, we add $nums[i]$ to the answer, and then mark the element at position $i$, and the left and right adjacent elements at position $i$, that is, the elements at positions $i-1$ and $i+1$. Continue to traverse the index array $idx$ until the end. - -Finally, return the answer. - -The time complexity is $O(n \times \log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array. - -### **Python3** - ```python class Solution: def findScore(self, nums: List[int]) -> int: @@ -98,22 +84,6 @@ class Solution: return ans ``` -```python -class Solution: - def findScore(self, nums: List[int]) -> int: - n = len(nums) - vis = [False] * (n + 2) - idx = sorted(range(n), key=lambda i: (nums[i], i)) - ans = 0 - for i in idx: - if not vis[i + 1]: - ans += nums[i] - vis[i] = vis[i + 2] = True - return ans -``` - -### **Java** - ```java class Solution { public long findScore(int[] nums) { @@ -143,31 +113,6 @@ class Solution { } ``` -```java -class Solution { - public long findScore(int[] nums) { - int n = nums.length; - boolean[] vis = new boolean[n + 2]; - Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } - Arrays.sort(idx, (i, j) -> nums[i] - nums[j]); - long ans = 0; - for (int i : idx) { - if (!vis[i + 1]) { - ans += nums[i]; - vis[i] = true; - vis[i + 2] = true; - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -200,31 +145,6 @@ public: }; ``` -```cpp -class Solution { -public: - long long findScore(vector& nums) { - int n = nums.size(); - vector idx(n); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) { - return nums[i] < nums[j] || (nums[i] == nums[j] && i < j); - }); - long long ans = 0; - vector vis(n + 2); - for (int i : idx) { - if (!vis[i + 1]) { - ans += nums[i]; - vis[i] = vis[i + 2] = true; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func findScore(nums []int) (ans int64) { h := hp{} @@ -260,30 +180,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -```go -func findScore(nums []int) (ans int64) { - n := len(nums) - idx := make([]int, n) - for i := range idx { - idx[i] = i - } - sort.Slice(idx, func(i, j int) bool { - i, j = idx[i], idx[j] - return nums[i] < nums[j] || (nums[i] == nums[j] && i < j) - }) - vis := make([]bool, n+2) - for _, i := range idx { - if !vis[i+1] { - ans += int64(nums[i]) - vis[i], vis[i+2] = true, true - } - } - return -} -``` - -### **TypeScript** - ```ts interface pair { x: number; @@ -321,6 +217,104 @@ function findScore(nums: number[]): number { } ``` + + +### Solution 2: Sorting + +We can create an index array $idx$ where $idx[i]=i$, and then we sort the index array $idx$ according to the element values in the array $nums$. If the element values are the same, then sort them according to the index values. + +Next, create an array $vis$ of length $n+2$ where $vis[i]=false$, which means whether the element in the array is marked. + +We traverse the index array $idx$, and for each index $i$ in the array, if $vis[i+1]$ is $false$, that is, the element at position $i$ is not marked, we add $nums[i]$ to the answer, and then mark the element at position $i$, and the left and right adjacent elements at position $i$, that is, the elements at positions $i-1$ and $i+1$. Continue to traverse the index array $idx$ until the end. + +Finally, return the answer. + +The time complexity is $O(n \times \log n)$ and the space complexity is $O(n)$, where $n$ is the length of the array. + + + +```python +class Solution: + def findScore(self, nums: List[int]) -> int: + n = len(nums) + vis = [False] * (n + 2) + idx = sorted(range(n), key=lambda i: (nums[i], i)) + ans = 0 + for i in idx: + if not vis[i + 1]: + ans += nums[i] + vis[i] = vis[i + 2] = True + return ans +``` + +```java +class Solution { + public long findScore(int[] nums) { + int n = nums.length; + boolean[] vis = new boolean[n + 2]; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> nums[i] - nums[j]); + long ans = 0; + for (int i : idx) { + if (!vis[i + 1]) { + ans += nums[i]; + vis[i] = true; + vis[i + 2] = true; + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + long long findScore(vector& nums) { + int n = nums.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return nums[i] < nums[j] || (nums[i] == nums[j] && i < j); + }); + long long ans = 0; + vector vis(n + 2); + for (int i : idx) { + if (!vis[i + 1]) { + ans += nums[i]; + vis[i] = vis[i + 2] = true; + } + } + return ans; + } +}; +``` + +```go +func findScore(nums []int) (ans int64) { + n := len(nums) + idx := make([]int, n) + for i := range idx { + idx[i] = i + } + sort.Slice(idx, func(i, j int) bool { + i, j = idx[i], idx[j] + return nums[i] < nums[j] || (nums[i] == nums[j] && i < j) + }) + vis := make([]bool, n+2) + for _, i := range idx { + if !vis[i+1] { + ans += int64(nums[i]) + vis[i], vis[i+2] = true, true + } + } + return +} +``` + ```ts function findScore(nums: number[]): number { const n = nums.length; @@ -342,10 +336,6 @@ function findScore(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2594.Minimum Time to Repair Cars/README.md b/solution/2500-2599/2594.Minimum Time to Repair Cars/README.md index c911cc4463a33..cf926424e361c 100644 --- a/solution/2500-2599/2594.Minimum Time to Repair Cars/README.md +++ b/solution/2500-2599/2594.Minimum Time to Repair Cars/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们注意到,修车时间越长,修理的汽车数目也越多。因此,我们可以将修车时间作为二分查找的目标,二分查找修车时间的最小值。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def repairCars(self, ranks: List[int], cars: int) -> int: @@ -80,10 +74,6 @@ class Solution: return bisect_left(range(ranks[0] * cars * cars), True, key=check) ``` -### **Java** - - - ```java class Solution { public long repairCars(int[] ranks, int cars) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func repairCars(ranks []int, cars int) int64 { return int64(sort.Search(ranks[0]*cars*cars, func(t int) bool { @@ -143,8 +129,6 @@ func repairCars(ranks []int, cars int) int64 { } ``` -### **TypeScript** - ```ts function repairCars(ranks: number[], cars: number): number { let left = 0; @@ -165,10 +149,6 @@ function repairCars(ranks: number[], cars: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2594.Minimum Time to Repair Cars/README_EN.md b/solution/2500-2599/2594.Minimum Time to Repair Cars/README_EN.md index c8beaac680417..5755994a31348 100644 --- a/solution/2500-2599/2594.Minimum Time to Repair Cars/README_EN.md +++ b/solution/2500-2599/2594.Minimum Time to Repair Cars/README_EN.md @@ -49,7 +49,7 @@ It can be proved that the cars cannot be repaired in less than 16 minutes.​​ ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search We notice that the longer the repair time, the more cars are repaired. Therefore, we can use the repair time as the target of binary search, and binary search for the minimum repair time. @@ -61,8 +61,6 @@ The time complexity is $O(n \times \log M)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def repairCars(self, ranks: List[int], cars: int) -> int: @@ -72,8 +70,6 @@ class Solution: return bisect_left(range(ranks[0] * cars * cars), True, key=check) ``` -### **Java** - ```java class Solution { public long repairCars(int[] ranks, int cars) { @@ -95,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +113,6 @@ public: }; ``` -### **Go** - ```go func repairCars(ranks []int, cars int) int64 { return int64(sort.Search(ranks[0]*cars*cars, func(t int) bool { @@ -133,8 +125,6 @@ func repairCars(ranks []int, cars int) int64 { } ``` -### **TypeScript** - ```ts function repairCars(ranks: number[], cars: number): number { let left = 0; @@ -155,10 +145,6 @@ function repairCars(ranks: number[], cars: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2595.Number of Even and Odd Bits/README.md b/solution/2500-2599/2595.Number of Even and Odd Bits/README.md index 1913d7e6b5c73..a96bb653c1652 100644 --- a/solution/2500-2599/2595.Number of Even and Odd Bits/README.md +++ b/solution/2500-2599/2595.Number of Even and Odd Bits/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们根据题意,枚举 $n$ 的二进制表示中从低位到高位的每一位,如果该位为 $1$,则根据该位的下标是奇数还是偶数,将对应的计数器加 $1$ 即可。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def evenOddBit(self, n: int) -> List[int]: @@ -70,19 +64,6 @@ class Solution: return ans ``` -```python -class Solution: - def evenOddBit(self, n: int) -> List[int]: - mask = 0x5555 - even = (n & mask).bit_count() - odd = (n & ~mask).bit_count() - return [even, odd] -``` - -### **Java** - - - ```java class Solution { public int[] evenOddBit(int n) { @@ -95,19 +76,6 @@ class Solution { } ``` -```java -class Solution { - public int[] evenOddBit(int n) { - int mask = 0x5555; - int even = Integer.bitCount(n & mask); - int odd = Integer.bitCount(n & ~mask); - return new int[] {even, odd}; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -121,6 +89,70 @@ public: }; ``` +```go +func evenOddBit(n int) []int { + ans := make([]int, 2) + for i := 0; n != 0; n, i = n>>1, i^1 { + ans[i] += n & 1 + } + return ans +} +``` + +```ts +function evenOddBit(n: number): number[] { + const ans = new Array(2).fill(0); + for (let i = 0; n > 0; n >>= 1, i ^= 1) { + ans[i] += n & 1; + } + return ans; +} +``` + +```rust +impl Solution { + pub fn even_odd_bit(mut n: i32) -> Vec { + let mut ans = vec![0; 2]; + + let mut i = 0; + while n != 0 { + ans[i] += n & 1; + + n >>= 1; + i ^= 1; + } + + ans + } +} +``` + + + +### 方法二 + + + +```python +class Solution: + def evenOddBit(self, n: int) -> List[int]: + mask = 0x5555 + even = (n & mask).bit_count() + odd = (n & ~mask).bit_count() + return [even, odd] +``` + +```java +class Solution { + public int[] evenOddBit(int n) { + int mask = 0x5555; + int even = Integer.bitCount(n & mask); + int odd = Integer.bitCount(n & ~mask); + return new int[] {even, odd}; + } +} +``` + ```cpp class Solution { public: @@ -133,18 +165,6 @@ public: }; ``` -### **Go** - -```go -func evenOddBit(n int) []int { - ans := make([]int, 2) - for i := 0; n != 0; n, i = n>>1, i^1 { - ans[i] += n & 1 - } - return ans -} -``` - ```go func evenOddBit(n int) []int { mask := 0x5555 @@ -154,18 +174,6 @@ func evenOddBit(n int) []int { } ``` -### **TypeScript** - -```ts -function evenOddBit(n: number): number[] { - const ans = new Array(2).fill(0); - for (let i = 0; n > 0; n >>= 1, i ^= 1) { - ans[i] += n & 1; - } - return ans; -} -``` - ```ts function evenOddBit(n: number): number[] { const mask = 0x5555; @@ -184,26 +192,6 @@ function bitCount(i: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn even_odd_bit(mut n: i32) -> Vec { - let mut ans = vec![0; 2]; - - let mut i = 0; - while n != 0 { - ans[i] += n & 1; - - n >>= 1; - i ^= 1; - } - - ans - } -} -``` - ```rust impl Solution { pub fn even_odd_bit(n: i32) -> Vec { @@ -215,10 +203,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2595.Number of Even and Odd Bits/README_EN.md b/solution/2500-2599/2595.Number of Even and Odd Bits/README_EN.md index e0fd823b45c8d..726d90c06512d 100644 --- a/solution/2500-2599/2595.Number of Even and Odd Bits/README_EN.md +++ b/solution/2500-2599/2595.Number of Even and Odd Bits/README_EN.md @@ -42,7 +42,7 @@ There are 0 even and 1 odd indices. ## Solutions -**Solution 1: Enumerate** +### Solution 1: Enumerate According to the problem description, enumerate the binary representation of $n$ from the low bit to the high bit. If the bit is $1$, add $1$ to the corresponding counter according to whether the index of the bit is odd or even. @@ -50,8 +50,6 @@ The time complexity is $O(\log n)$ and the space complexity is $O(1)$. Where $n$ -### **Python3** - ```python class Solution: def evenOddBit(self, n: int) -> List[int]: @@ -64,17 +62,6 @@ class Solution: return ans ``` -```python -class Solution: - def evenOddBit(self, n: int) -> List[int]: - mask = 0x5555 - even = (n & mask).bit_count() - odd = (n & ~mask).bit_count() - return [even, odd] -``` - -### **Java** - ```java class Solution { public int[] evenOddBit(int n) { @@ -87,19 +74,6 @@ class Solution { } ``` -```java -class Solution { - public int[] evenOddBit(int n) { - int mask = 0x5555; - int even = Integer.bitCount(n & mask); - int odd = Integer.bitCount(n & ~mask); - return new int[] {even, odd}; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -113,6 +87,70 @@ public: }; ``` +```go +func evenOddBit(n int) []int { + ans := make([]int, 2) + for i := 0; n != 0; n, i = n>>1, i^1 { + ans[i] += n & 1 + } + return ans +} +``` + +```ts +function evenOddBit(n: number): number[] { + const ans = new Array(2).fill(0); + for (let i = 0; n > 0; n >>= 1, i ^= 1) { + ans[i] += n & 1; + } + return ans; +} +``` + +```rust +impl Solution { + pub fn even_odd_bit(mut n: i32) -> Vec { + let mut ans = vec![0; 2]; + + let mut i = 0; + while n != 0 { + ans[i] += n & 1; + + n >>= 1; + i ^= 1; + } + + ans + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def evenOddBit(self, n: int) -> List[int]: + mask = 0x5555 + even = (n & mask).bit_count() + odd = (n & ~mask).bit_count() + return [even, odd] +``` + +```java +class Solution { + public int[] evenOddBit(int n) { + int mask = 0x5555; + int even = Integer.bitCount(n & mask); + int odd = Integer.bitCount(n & ~mask); + return new int[] {even, odd}; + } +} +``` + ```cpp class Solution { public: @@ -125,18 +163,6 @@ public: }; ``` -### **Go** - -```go -func evenOddBit(n int) []int { - ans := make([]int, 2) - for i := 0; n != 0; n, i = n>>1, i^1 { - ans[i] += n & 1 - } - return ans -} -``` - ```go func evenOddBit(n int) []int { mask := 0x5555 @@ -146,18 +172,6 @@ func evenOddBit(n int) []int { } ``` -### **TypeScript** - -```ts -function evenOddBit(n: number): number[] { - const ans = new Array(2).fill(0); - for (let i = 0; n > 0; n >>= 1, i ^= 1) { - ans[i] += n & 1; - } - return ans; -} -``` - ```ts function evenOddBit(n: number): number[] { const mask = 0x5555; @@ -176,26 +190,6 @@ function bitCount(i: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn even_odd_bit(mut n: i32) -> Vec { - let mut ans = vec![0; 2]; - - let mut i = 0; - while n != 0 { - ans[i] += n & 1; - - n >>= 1; - i ^= 1; - } - - ans - } -} -``` - ```rust impl Solution { pub fn even_odd_bit(n: i32) -> Vec { @@ -207,10 +201,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2596.Check Knight Tour Configuration/README.md b/solution/2500-2599/2596.Check Knight Tour Configuration/README.md index a45dfecb2cc22..1d0e9023d943d 100644 --- a/solution/2500-2599/2596.Check Knight Tour Configuration/README.md +++ b/solution/2500-2599/2596.Check Knight Tour Configuration/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们先用数组 $pos$ 记录骑士访问的每个格子的坐标,然后遍历 $pos$ 数组,检查相邻两个格子的坐标差是否为 $(1, 2)$ 或 $(2, 1)$ 即可。若不满足,则返回 `false`。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def checkValidGrid(self, grid: List[List[int]]) -> bool: @@ -80,10 +74,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean checkValidGrid(int[][] grid) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func checkValidGrid(grid [][]int) bool { if grid[0][0] != 0 { @@ -178,8 +164,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function checkValidGrid(grid: number[][]): boolean { if (grid[0][0] !== 0) { @@ -206,10 +190,6 @@ function checkValidGrid(grid: number[][]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2596.Check Knight Tour Configuration/README_EN.md b/solution/2500-2599/2596.Check Knight Tour Configuration/README_EN.md index 76f5f5f9ef073..3897496cf1778 100644 --- a/solution/2500-2599/2596.Check Knight Tour Configuration/README_EN.md +++ b/solution/2500-2599/2596.Check Knight Tour Configuration/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We first use the array $pos$ to record the coordinates of the grid visited by the knight, and then traverse the $pos$ array to check whether the difference between the adjacent two grid coordinates is $(1, 2)$ or $(2, 1)$. If not, return `false`. @@ -51,8 +51,6 @@ The time complexity is $O(n^2)$ and the space complexity is $O(n^2)$, where $n$ -### **Python3** - ```python class Solution: def checkValidGrid(self, grid: List[List[int]]) -> bool: @@ -71,8 +69,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean checkValidGrid(int[][] grid) { @@ -101,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +126,6 @@ public: }; ``` -### **Go** - ```go func checkValidGrid(grid [][]int) bool { if grid[0][0] != 0 { @@ -167,8 +159,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function checkValidGrid(grid: number[][]): boolean { if (grid[0][0] !== 0) { @@ -195,10 +185,6 @@ function checkValidGrid(grid: number[][]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2597.The Number of Beautiful Subsets/README.md b/solution/2500-2599/2597.The Number of Beautiful Subsets/README.md index f4651d3084f7c..0d786af347a3d 100644 --- a/solution/2500-2599/2597.The Number of Beautiful Subsets/README.md +++ b/solution/2500-2599/2597.The Number of Beautiful Subsets/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:计数 + 回溯** +### 方法一:计数 + 回溯 我们用哈希表或数组 $cnt$ 记录当前已经选择的数字以及它们的个数,用 $ans$ 记录美丽子集的数目,初始时 $ans = -1$,表示排除空集。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def beautifulSubsets(self, nums: List[int], k: int) -> int: @@ -84,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] nums; @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go func beautifulSubsets(nums []int, k int) int { ans := -1 @@ -176,8 +162,6 @@ func beautifulSubsets(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function beautifulSubsets(nums: number[], k: number): number { let ans: number = -1; @@ -202,10 +186,6 @@ function beautifulSubsets(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2597.The Number of Beautiful Subsets/README_EN.md b/solution/2500-2599/2597.The Number of Beautiful Subsets/README_EN.md index 07f33dd711063..00ffe677dc6b7 100644 --- a/solution/2500-2599/2597.The Number of Beautiful Subsets/README_EN.md +++ b/solution/2500-2599/2597.The Number of Beautiful Subsets/README_EN.md @@ -41,7 +41,7 @@ It can be proved that there is only 1 beautiful subset in the array [1]. ## Solutions -**Solution 1: Counting + Backtracking** +### Solution 1: Counting + Backtracking We use a hash table or an array $cnt$ to record the currently selected numbers and their counts, and use $ans$ to record the number of beautiful subsets, initially $ans = -1$, indicating that the empty set is excluded. @@ -56,8 +56,6 @@ Time complexity $O(2^n)$, space complexity $O(n)$, where $n$ is the length of th -### **Python3** - ```python class Solution: def beautifulSubsets(self, nums: List[int], k: int) -> int: @@ -78,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] nums; @@ -111,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +135,6 @@ public: }; ``` -### **Go** - ```go func beautifulSubsets(nums []int, k int) int { ans := -1 @@ -168,8 +160,6 @@ func beautifulSubsets(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function beautifulSubsets(nums: number[], k: number): number { let ans: number = -1; @@ -194,10 +184,6 @@ function beautifulSubsets(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README.md b/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README.md index 65482408ef523..292f874f334f0 100644 --- a/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README.md +++ b/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README.md @@ -55,9 +55,7 @@ nums 的 MEX 是 2 。可以证明 2 是可以取到的最大 MEX 。 ## 解法 - - -**方法一:计数** +### 方法一:计数 我们用哈希表或数组 $cnt$ 统计数组中每个数对 $value$ 取模后的余数的个数。 @@ -67,10 +65,6 @@ nums 的 MEX 是 2 。可以证明 2 是可以取到的最大 MEX 。 -### **Python3** - - - ```python class Solution: def findSmallestInteger(self, nums: List[int], value: int) -> int: @@ -81,10 +75,6 @@ class Solution: cnt[i % value] -= 1 ``` -### **Java** - - - ```java class Solution { public int findSmallestInteger(int[] nums, int value) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func findSmallestInteger(nums []int, value int) int { cnt := make([]int, value) @@ -138,8 +124,6 @@ func findSmallestInteger(nums []int, value int) int { } ``` -### **TypeScript** - ```ts function findSmallestInteger(nums: number[], value: number): number { const cnt: number[] = new Array(value).fill(0); @@ -154,10 +138,6 @@ function findSmallestInteger(nums: number[], value: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README_EN.md b/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README_EN.md index 10a88deccc536..929b7a5cc2341 100644 --- a/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README_EN.md +++ b/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README_EN.md @@ -53,7 +53,7 @@ The MEX of nums is 2. It can be shown that 2 is the maximum MEX we can achieve. ## Solutions -**Solution 1: Count** +### Solution 1: Count We use a hash table or array $cnt$ to count the number of times each remainder of $value$ is taken modulo in the array. @@ -63,8 +63,6 @@ The time complexity is $O(n)$ and the space complexity is $O(value)$. Where $n$ -### **Python3** - ```python class Solution: def findSmallestInteger(self, nums: List[int], value: int) -> int: @@ -75,8 +73,6 @@ class Solution: cnt[i % value] -= 1 ``` -### **Java** - ```java class Solution { public int findSmallestInteger(int[] nums, int value) { @@ -93,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +107,6 @@ public: }; ``` -### **Go** - ```go func findSmallestInteger(nums []int, value int) int { cnt := make([]int, value) @@ -130,8 +122,6 @@ func findSmallestInteger(nums []int, value int) int { } ``` -### **TypeScript** - ```ts function findSmallestInteger(nums: number[], value: number): number { const cnt: number[] = new Array(value).fill(0); @@ -146,10 +136,6 @@ function findSmallestInteger(nums: number[], value: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2599.Make the Prefix Sum Non-negative/README.md b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/README.md index 451604d0a5427..e9d9719f26416 100644 --- a/solution/2500-2599/2599.Make the Prefix Sum Non-negative/README.md +++ b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列(小根堆)** +### 方法一:贪心 + 优先队列(小根堆) 我们用变量 $s$ 记录当前数组的前缀和。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def makePrefSumNonNegative(self, nums: List[int]) -> int: @@ -78,10 +72,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int makePrefSumNonNegative(int[] nums) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func makePrefSumNonNegative(nums []int) (ans int) { pq := hp{} @@ -159,8 +145,6 @@ func (h *hp) Pop() any { } ``` -### **TypeScript** - ```ts function makePrefSumNonNegative(nums: number[]): number { const pq = new MinPriorityQueue(); @@ -180,10 +164,6 @@ function makePrefSumNonNegative(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2500-2599/2599.Make the Prefix Sum Non-negative/README_EN.md b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/README_EN.md index 09c1578e2db03..11c67d7ca7929 100644 --- a/solution/2500-2599/2599.Make the Prefix Sum Non-negative/README_EN.md +++ b/solution/2500-2599/2599.Make the Prefix Sum Non-negative/README_EN.md @@ -43,7 +43,7 @@ The array after the operation is [3,-2,6,-5]. The prefix sum array is [3, 1, 7, ## Solutions -**Solution 1: Greedy + Priority Queue (Min Heap)** +### Solution 1: Greedy + Priority Queue (Min Heap) We use a variable $s$ to record the prefix sum of the current array. @@ -53,8 +53,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$, -### **Python3** - ```python class Solution: def makePrefSumNonNegative(self, nums: List[int]) -> int: @@ -70,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int makePrefSumNonNegative(int[] nums) { @@ -93,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func makePrefSumNonNegative(nums []int) (ans int) { pq := hp{} @@ -149,8 +141,6 @@ func (h *hp) Pop() any { } ``` -### **TypeScript** - ```ts function makePrefSumNonNegative(nums: number[]): number { const pq = new MinPriorityQueue(); @@ -170,10 +160,6 @@ function makePrefSumNonNegative(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2600.K Items With the Maximum Sum/README.md b/solution/2600-2699/2600.K Items With the Maximum Sum/README.md index 64bc3b9d1a91a..cb374f26167e5 100644 --- a/solution/2600-2699/2600.K Items With the Maximum Sum/README.md +++ b/solution/2600-2699/2600.K Items With the Maximum Sum/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 根据题目描述,我们应该尽可能多地取标记为 $1$ 的物品,然后取标记为 $0$ 的物品,最后取标记为 $-1$ 的物品。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def kItemsWithMaximumSum( @@ -82,10 +76,6 @@ class Solution: return numOnes - (k - numOnes - numZeros) ``` -### **Java** - - - ```java class Solution { public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func kItemsWithMaximumSum(numOnes int, numZeros int, numNegOnes int, k int) int { if numOnes >= k { @@ -131,8 +117,6 @@ func kItemsWithMaximumSum(numOnes int, numZeros int, numNegOnes int, k int) int } ``` -### **TypeScript** - ```ts function kItemsWithMaximumSum( numOnes: number, @@ -150,24 +134,6 @@ function kItemsWithMaximumSum( } ``` -### **C#** - -```cs -public class Solution { - public int KItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { - if (numOnes >= k) { - return k; - } - if (numZeros >= k - numOnes) { - return numOnes; - } - return numOnes - (k - numOnes - numZeros); - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn k_items_with_maximum_sum( @@ -189,10 +155,20 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public int KItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { + if (numOnes >= k) { + return k; + } + if (numZeros >= k - numOnes) { + return numOnes; + } + return numOnes - (k - numOnes - numZeros); + } +} ``` + + diff --git a/solution/2600-2699/2600.K Items With the Maximum Sum/README_EN.md b/solution/2600-2699/2600.K Items With the Maximum Sum/README_EN.md index 9d251225cc9fb..d29ab1e220601 100644 --- a/solution/2600-2699/2600.K Items With the Maximum Sum/README_EN.md +++ b/solution/2600-2699/2600.K Items With the Maximum Sum/README_EN.md @@ -47,9 +47,9 @@ It can be proven that 3 is the maximum possible sum. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return numOnes - (k - numOnes - numZeros) ``` -### **Java** - ```java class Solution { public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { @@ -79,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func kItemsWithMaximumSum(numOnes int, numZeros int, numNegOnes int, k int) int { if numOnes >= k { @@ -110,8 +104,6 @@ func kItemsWithMaximumSum(numOnes int, numZeros int, numNegOnes int, k int) int } ``` -### **TypeScript** - ```ts function kItemsWithMaximumSum( numOnes: number, @@ -129,24 +121,6 @@ function kItemsWithMaximumSum( } ``` -### **C#** - -```cs -public class Solution { - public int KItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { - if (numOnes >= k) { - return k; - } - if (numZeros >= k - numOnes) { - return numOnes; - } - return numOnes - (k - numOnes - numZeros); - } -} -``` - -### **Rust** - ```rust impl Solution { pub fn k_items_with_maximum_sum( @@ -168,10 +142,20 @@ impl Solution { } ``` -### **...** - -``` - +```cs +public class Solution { + public int KItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { + if (numOnes >= k) { + return k; + } + if (numZeros >= k - numOnes) { + return numOnes; + } + return numOnes - (k - numOnes - numZeros); + } +} ``` + + diff --git a/solution/2600-2699/2601.Prime Subtraction Operation/README.md b/solution/2600-2699/2601.Prime Subtraction Operation/README.md index bba9dd1303b11..193e91b2be5cd 100644 --- a/solution/2600-2699/2601.Prime Subtraction Operation/README.md +++ b/solution/2600-2699/2601.Prime Subtraction Operation/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:预处理质数 + 二分查找** +### 方法一:预处理质数 + 二分查找 我们先预处理得到 $1000$ 以内的所有质数,记录在数组 $p$ 中。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def primeSubOperation(self, nums: List[int]) -> bool: @@ -96,10 +90,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean primeSubOperation(int[] nums) { @@ -145,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -180,8 +168,6 @@ public: }; ``` -### **Go** - ```go func primeSubOperation(nums []int) bool { p := []int{} @@ -211,8 +197,6 @@ func primeSubOperation(nums []int) bool { } ``` -### **TypeScript** - ```ts function primeSubOperation(nums: number[]): boolean { const p: number[] = []; @@ -256,10 +240,6 @@ function primeSubOperation(nums: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2601.Prime Subtraction Operation/README_EN.md b/solution/2600-2699/2601.Prime Subtraction Operation/README_EN.md index 741ea0c57a880..5d5371f52c9aa 100644 --- a/solution/2600-2699/2601.Prime Subtraction Operation/README_EN.md +++ b/solution/2600-2699/2601.Prime Subtraction Operation/README_EN.md @@ -51,7 +51,7 @@ After the second operation, nums is sorted in strictly increasing order, so the ## Solutions -**Solution 1: Preprocessing prime numbers + binary search** +### Solution 1: Preprocessing prime numbers + binary search We first preprocess all the primes within $1000$ and record them in the array $p$. @@ -63,8 +63,6 @@ The time complexity is $O(n \log n)$ and the space complexity is $O(n)$. where $ -### **Python3** - ```python class Solution: def primeSubOperation(self, nums: List[int]) -> bool: @@ -87,8 +85,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean primeSubOperation(int[] nums) { @@ -134,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +163,6 @@ public: }; ``` -### **Go** - ```go func primeSubOperation(nums []int) bool { p := []int{} @@ -200,8 +192,6 @@ func primeSubOperation(nums []int) bool { } ``` -### **TypeScript** - ```ts function primeSubOperation(nums: number[]): boolean { const p: number[] = []; @@ -245,10 +235,6 @@ function primeSubOperation(nums: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README.md b/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README.md index 44be75608106c..6363a20a33698 100644 --- a/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README.md +++ b/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:排序 + 前缀和 + 二分查找** +### 方法一:排序 + 前缀和 + 二分查找 我们先将数组 $nums$ 进行排序,并计算出长度为 $n+1$ 的前缀和数组 $s$,其中 $s[i]$ 表示数组 $nums$ 中前 $i$ 个元素的和。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, nums: List[int], queries: List[int]) -> List[int]: @@ -94,10 +88,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List minOperations(int[] nums, int[] queries) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +146,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int, queries []int) (ans []int64) { sort.Ints(nums) @@ -179,8 +165,6 @@ func minOperations(nums []int, queries []int) (ans []int64) { } ``` -### **TypeScript** - ```ts function minOperations(nums: number[], queries: number[]): number[] { nums.sort((a, b) => a - b); @@ -214,10 +198,6 @@ function minOperations(nums: number[], queries: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README_EN.md b/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README_EN.md index 306bbd7e2ad9c..b8c5d7dacc71f 100644 --- a/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README_EN.md +++ b/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README_EN.md @@ -55,7 +55,7 @@ So the total number of operations for the second query is 2 + 4 + 1 + 3 = 10. ## Solutions -**Solution 1: sort + prefix sum + binary search** +### Solution 1: sort + prefix sum + binary search First, we sort the array $nums$ and calculate the prefix sum array $s$ with a length of $n+1$, where $s[i]$ represents the sum of the first $i$ elements in the array $nums$. @@ -71,8 +71,6 @@ Time complexity $O(n \times \log n)$, space complexity $O(n)$, where $n$ is the -### **Python3** - ```python class Solution: def minOperations(self, nums: List[int], queries: List[int]) -> List[int]: @@ -88,8 +86,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List minOperations(int[] nums, int[] queries) { @@ -125,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +144,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int, queries []int) (ans []int64) { sort.Ints(nums) @@ -171,8 +163,6 @@ func minOperations(nums []int, queries []int) (ans []int64) { } ``` -### **TypeScript** - ```ts function minOperations(nums: number[], queries: number[]): number[] { nums.sort((a, b) => a - b); @@ -206,10 +196,6 @@ function minOperations(nums: number[], queries: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2603.Collect Coins in a Tree/README.md b/solution/2600-2699/2603.Collect Coins in a Tree/README.md index 836fbaf2c3162..118926386f9ba 100644 --- a/solution/2600-2699/2603.Collect Coins in a Tree/README.md +++ b/solution/2600-2699/2603.Collect Coins in a Tree/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:拓扑排序** +### 方法一:拓扑排序 我们先将 $edges$ 中的边转换成邻接表 $g$,其中 $g[i]$ 表示节点 $i$ 的所有邻接节点,用集合表示。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def collectTheCoins(self, coins: List[int], edges: List[List[int]]) -> int: @@ -107,10 +101,6 @@ class Solution: return sum(len(g[a]) > 0 and len(g[b]) > 0 for a, b in edges) * 2 ``` -### **Java** - - - ```java class Solution { public int collectTheCoins(int[] coins, int[][] edges) { @@ -164,8 +154,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -220,8 +208,6 @@ public: }; ``` -### **Go** - ```go func collectTheCoins(coins []int, edges [][]int) int { n := len(coins) @@ -276,8 +262,6 @@ func collectTheCoins(coins []int, edges [][]int) int { } ``` -### **TypeScript** - ```ts function collectTheCoins(coins: number[], edges: number[][]): number { const n = coins.length; @@ -326,10 +310,6 @@ function collectTheCoins(coins: number[], edges: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2603.Collect Coins in a Tree/README_EN.md b/solution/2600-2699/2603.Collect Coins in a Tree/README_EN.md index 6873c465c2bca..8a8020ce68555 100644 --- a/solution/2600-2699/2603.Collect Coins in a Tree/README_EN.md +++ b/solution/2600-2699/2603.Collect Coins in a Tree/README_EN.md @@ -50,7 +50,7 @@ ## Solutions -**Solution 1: Topological sorting** +### Solution 1: Topological sorting We first convert the edges in $edges$ to the adjacency list $g$, where $g[i]$ represents all the adjacent nodes of node $i$, represented by a set. @@ -70,8 +70,6 @@ Similar problems: -### **Python3** - ```python class Solution: def collectTheCoins(self, coins: List[int], edges: List[List[int]]) -> int: @@ -97,8 +95,6 @@ class Solution: return sum(len(g[a]) > 0 and len(g[b]) > 0 for a, b in edges) * 2 ``` -### **Java** - ```java class Solution { public int collectTheCoins(int[] coins, int[][] edges) { @@ -152,8 +148,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -208,8 +202,6 @@ public: }; ``` -### **Go** - ```go func collectTheCoins(coins []int, edges [][]int) int { n := len(coins) @@ -264,8 +256,6 @@ func collectTheCoins(coins []int, edges [][]int) int { } ``` -### **TypeScript** - ```ts function collectTheCoins(coins: number[], edges: number[][]): number { const n = coins.length; @@ -314,10 +304,6 @@ function collectTheCoins(coins: number[], edges: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2604.Minimum Time to Eat All Grains/README.md b/solution/2600-2699/2604.Minimum Time to Eat All Grains/README.md index d9374cede8506..cbb0d0921121e 100644 --- a/solution/2600-2699/2604.Minimum Time to Eat All Grains/README.md +++ b/solution/2600-2699/2604.Minimum Time to Eat All Grains/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 我们先将鸡和谷物按照位置从小到大排序,接下来二分枚举时间 $t$,找到一个最小的 $t$ 使得所有谷物能在 $t$ 秒内被吃完。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def minimumTime(self, hens: List[int], grains: List[int]) -> int: @@ -105,10 +99,6 @@ class Solution: return bisect_left(range(r), True, key=check) ``` -### **Java** - - - ```java class Solution { private int[] hens; @@ -163,8 +153,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -213,8 +201,6 @@ public: }; ``` -### **Go** - ```go func minimumTime(hens []int, grains []int) int { sort.Ints(hens) @@ -266,8 +252,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minimumTime(hens: number[], grains: number[]): number { hens.sort((a, b) => a - b); @@ -315,10 +299,6 @@ function minimumTime(hens: number[], grains: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2604.Minimum Time to Eat All Grains/README_EN.md b/solution/2600-2699/2604.Minimum Time to Eat All Grains/README_EN.md index c83179a15deee..52de4b9355081 100644 --- a/solution/2600-2699/2604.Minimum Time to Eat All Grains/README_EN.md +++ b/solution/2600-2699/2604.Minimum Time to Eat All Grains/README_EN.md @@ -50,7 +50,7 @@ So, the maximum time needed is 1. ## Solutions -**Solution 1: Sorting + Binary Search** +### Solution 1: Sorting + Binary Search First, sort the chickens and grains by their position from left to right. Then enumerate the time $t$ using binary search to find the smallest $t$ such that all the grains can be eaten up in $t$ seconds. @@ -65,8 +65,6 @@ Time complexity $O(n \times \log n + m \times \log m + (m + n) \times \log U)$, -### **Python3** - ```python class Solution: def minimumTime(self, hens: List[int], grains: List[int]) -> int: @@ -96,8 +94,6 @@ class Solution: return bisect_left(range(r), True, key=check) ``` -### **Java** - ```java class Solution { private int[] hens; @@ -152,8 +148,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -202,8 +196,6 @@ public: }; ``` -### **Go** - ```go func minimumTime(hens []int, grains []int) int { sort.Ints(hens) @@ -255,8 +247,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minimumTime(hens: number[], grains: number[]): number { hens.sort((a, b) => a - b); @@ -304,10 +294,6 @@ function minimumTime(hens: number[], grains: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README.md b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README.md index 292b7e8de99d8..409a4f1735f57 100644 --- a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README.md +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README.md @@ -36,36 +36,14 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们观察发现,如果数组 $nums1$ 和 $nums2$ 中有相同的数字,那么相同数字中的最小值一定是最小的数字。否则我们取 $nums1$ 中的数字 $a$ 和 $nums2$ 中的数字 $b$,将 $a$ 和 $b$ 拼接成两个数字,取其中较小的数字即可。 时间复杂度 $O(m \times n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别是数组 $nums1$ 和 $nums2$ 的长度。 -**方法二:哈希表或数组 + 枚举** - -我们可以用哈希表或数组记录数组 $nums1$ 和 $nums2$ 中的数字,然后枚举 $1 \sim 9$,如果 $i$ 在两个数组中都出现了,那么 $i$ 就是最小的数字。否则我们取 $nums1$ 中的数字 $a$ 和 $nums2$ 中的数字 $b$,将 $a$ 和 $b$ 拼接成两个数字,取其中较小的数字即可。 - -时间复杂度 $(m + n)$,空间复杂度 $O(C)$。其中 $m$ 和 $n$ 分别是数组 $nums1$ 和 $nums2$ 的长度;而 $C$ 是数组 $nums1$ 和 $nums2$ 中数字的范围,本题中 $C = 10$。 - -**方法三:位运算** - -由于数字的范围是 $1 \sim 9$,我们可以用一个长度为 $10$ 的二进制数来表示数组 $nums1$ 和 $nums2$ 中的数字。我们用 $mask1$ 表示数组 $nums1$ 中的数字,用 $mask2$ 表示数组 $nums2$ 中的数字。 - -如果 $mask1$ 和 $mask2$ 进行按位与得到的数字 $mask$ 不等于 $0$,那么我们提取 $mask$ 中最后一位 $1$ 所在的位置,即为最小的数字。 - -否则,我们分别提取 $mask1$ 和 $mask2$ 中最后一位 $1$ 所在的位置,分别记为 $a$ 和 $b$,那么最小的数字就是 $min(a \times 10 + b, b \times 10 + a)$。 - -时间复杂度 $O(m + n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别是数组 $nums1$ 和 $nums2$ 的长度。 - -### **Python3** - - - ```python class Solution: def minNumber(self, nums1: List[int], nums2: List[int]) -> int: @@ -79,36 +57,6 @@ class Solution: return ans ``` -```python -class Solution: - def minNumber(self, nums1: List[int], nums2: List[int]) -> int: - s = set(nums1) & set(nums2) - if s: - return min(s) - a, b = min(nums1), min(nums2) - return min(a * 10 + b, b * 10 + a) -``` - -```python -class Solution: - def minNumber(self, nums1: List[int], nums2: List[int]) -> int: - mask1 = mask2 = 0 - for x in nums1: - mask1 |= 1 << x - for x in nums2: - mask2 |= 1 << x - mask = mask1 & mask2 - if mask: - return (mask & -mask).bit_length() - 1 - a = (mask1 & -mask1).bit_length() - 1 - b = (mask2 & -mask2).bit_length() - 1 - return min(a * 10 + b, b * 10 + a) -``` - -### **Java** - - - ```java class Solution { public int minNumber(int[] nums1, int[] nums2) { @@ -127,6 +75,97 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minNumber(vector& nums1, vector& nums2) { + int ans = 100; + for (int a : nums1) { + for (int b : nums2) { + if (a == b) { + ans = min(ans, a); + } else { + ans = min({ans, a * 10 + b, b * 10 + a}); + } + } + } + return ans; + } +}; +``` + +```go +func minNumber(nums1 []int, nums2 []int) int { + ans := 100 + for _, a := range nums1 { + for _, b := range nums2 { + if a == b { + ans = min(ans, a) + } else { + ans = min(ans, min(a*10+b, b*10+a)) + } + } + } + return ans +} +``` + +```ts +function minNumber(nums1: number[], nums2: number[]): number { + let ans = 100; + for (const a of nums1) { + for (const b of nums2) { + if (a === b) { + ans = Math.min(ans, a); + } else { + ans = Math.min(ans, a * 10 + b, b * 10 + a); + } + } + } + return ans; +} +``` + +```rust +impl Solution { + pub fn min_number(nums1: Vec, nums2: Vec) -> i32 { + let mut ans = 100; + + for &a in &nums1 { + for &b in &nums2 { + if a == b { + ans = std::cmp::min(ans, a); + } else { + ans = std::cmp::min(ans, std::cmp::min(a * 10 + b, b * 10 + a)); + } + } + } + + ans + } +} +``` + + + +### 方法二:哈希表或数组 + 枚举 + +我们可以用哈希表或数组记录数组 $nums1$ 和 $nums2$ 中的数字,然后枚举 $1 \sim 9$,如果 $i$ 在两个数组中都出现了,那么 $i$ 就是最小的数字。否则我们取 $nums1$ 中的数字 $a$ 和 $nums2$ 中的数字 $b$,将 $a$ 和 $b$ 拼接成两个数字,取其中较小的数字即可。 + +时间复杂度 $(m + n)$,空间复杂度 $O(C)$。其中 $m$ 和 $n$ 分别是数组 $nums1$ 和 $nums2$ 的长度;而 $C$ 是数组 $nums1$ 和 $nums2$ 中数字的范围,本题中 $C = 10$。 + + + +```python +class Solution: + def minNumber(self, nums1: List[int], nums2: List[int]) -> int: + s = set(nums1) & set(nums2) + if s: + return min(s) + a, b = min(nums1), min(nums2) + return min(a * 10 + b, b * 10 + a) +``` + ```java class Solution { public int minNumber(int[] nums1, int[] nums2) { @@ -155,48 +194,6 @@ class Solution { } ``` -```java -class Solution { - public int minNumber(int[] nums1, int[] nums2) { - int mask1 = 0, mask2 = 0; - for (int x : nums1) { - mask1 |= 1 << x; - } - for (int x : nums2) { - mask2 |= 1 << x; - } - int mask = mask1 & mask2; - if (mask != 0) { - return Integer.numberOfTrailingZeros(mask); - } - int a = Integer.numberOfTrailingZeros(mask1); - int b = Integer.numberOfTrailingZeros(mask2); - return Math.min(a * 10 + b, b * 10 + a); - } -} -``` - -### **C++** - -```cpp -class Solution { -public: - int minNumber(vector& nums1, vector& nums2) { - int ans = 100; - for (int a : nums1) { - for (int b : nums2) { - if (a == b) { - ans = min(ans, a); - } else { - ans = min({ans, a * 10 + b, b * 10 + a}); - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -226,46 +223,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minNumber(vector& nums1, vector& nums2) { - int mask1 = 0, mask2 = 0; - for (int x : nums1) { - mask1 |= 1 << x; - } - for (int x : nums2) { - mask2 |= 1 << x; - } - int mask = mask1 & mask2; - if (mask) { - return __builtin_ctz(mask); - } - int a = __builtin_ctz(mask1); - int b = __builtin_ctz(mask2); - return min(a * 10 + b, b * 10 + a); - } -}; -``` - -### **Go** - -```go -func minNumber(nums1 []int, nums2 []int) int { - ans := 100 - for _, a := range nums1 { - for _, b := range nums2 { - if a == b { - ans = min(ans, a) - } else { - ans = min(ans, min(a*10+b, b*10+a)) - } - } - } - return ans -} -``` - ```go func minNumber(nums1 []int, nums2 []int) int { s1 := [10]bool{} @@ -292,41 +249,6 @@ func minNumber(nums1 []int, nums2 []int) int { } ``` -```go -func minNumber(nums1 []int, nums2 []int) int { - var mask1, mask2 uint - for _, x := range nums1 { - mask1 |= 1 << x - } - for _, x := range nums2 { - mask2 |= 1 << x - } - if mask := mask1 & mask2; mask != 0 { - return bits.TrailingZeros(mask) - } - a, b := bits.TrailingZeros(mask1), bits.TrailingZeros(mask2) - return min(a*10+b, b*10+a) -} -``` - -### **TypeScript** - -```ts -function minNumber(nums1: number[], nums2: number[]): number { - let ans = 100; - for (const a of nums1) { - for (const b of nums2) { - if (a === b) { - ans = Math.min(ans, a); - } else { - ans = Math.min(ans, a * 10 + b, b * 10 + a); - } - } - } - return ans; -} -``` - ```ts function minNumber(nums1: number[], nums2: number[]): number { const s1: boolean[] = new Array(10).fill(false); @@ -354,6 +276,133 @@ function minNumber(nums1: number[], nums2: number[]): number { } ``` +```rust +use std::collections::HashMap; + +impl Solution { + pub fn min_number(nums1: Vec, nums2: Vec) -> i32 { + let mut h1: HashMap = HashMap::new(); + + for &n in &nums1 { + h1.insert(n, true); + } + + let mut h2: HashMap = HashMap::new(); + for &n in &nums2 { + h2.insert(n, true); + } + + let mut a = 0; + let mut b = 0; + for i in 1..10 { + if h1.contains_key(&i) && h2.contains_key(&i) { + return i; + } + + if a == 0 && h1.contains_key(&i) { + a = i; + } + + if b == 0 && h2.contains_key(&i) { + b = i; + } + } + + std::cmp::min(a * 10 + b, b * 10 + a) + } +} +``` + + + +### 方法三:位运算 + +由于数字的范围是 $1 \sim 9$,我们可以用一个长度为 $10$ 的二进制数来表示数组 $nums1$ 和 $nums2$ 中的数字。我们用 $mask1$ 表示数组 $nums1$ 中的数字,用 $mask2$ 表示数组 $nums2$ 中的数字。 + +如果 $mask1$ 和 $mask2$ 进行按位与得到的数字 $mask$ 不等于 $0$,那么我们提取 $mask$ 中最后一位 $1$ 所在的位置,即为最小的数字。 + +否则,我们分别提取 $mask1$ 和 $mask2$ 中最后一位 $1$ 所在的位置,分别记为 $a$ 和 $b$,那么最小的数字就是 $min(a \times 10 + b, b \times 10 + a)$。 + +时间复杂度 $O(m + n)$,空间复杂度 $O(1)$。其中 $m$ 和 $n$ 分别是数组 $nums1$ 和 $nums2$ 的长度。 + + + +```python +class Solution: + def minNumber(self, nums1: List[int], nums2: List[int]) -> int: + mask1 = mask2 = 0 + for x in nums1: + mask1 |= 1 << x + for x in nums2: + mask2 |= 1 << x + mask = mask1 & mask2 + if mask: + return (mask & -mask).bit_length() - 1 + a = (mask1 & -mask1).bit_length() - 1 + b = (mask2 & -mask2).bit_length() - 1 + return min(a * 10 + b, b * 10 + a) +``` + +```java +class Solution { + public int minNumber(int[] nums1, int[] nums2) { + int mask1 = 0, mask2 = 0; + for (int x : nums1) { + mask1 |= 1 << x; + } + for (int x : nums2) { + mask2 |= 1 << x; + } + int mask = mask1 & mask2; + if (mask != 0) { + return Integer.numberOfTrailingZeros(mask); + } + int a = Integer.numberOfTrailingZeros(mask1); + int b = Integer.numberOfTrailingZeros(mask2); + return Math.min(a * 10 + b, b * 10 + a); + } +} +``` + +```cpp +class Solution { +public: + int minNumber(vector& nums1, vector& nums2) { + int mask1 = 0, mask2 = 0; + for (int x : nums1) { + mask1 |= 1 << x; + } + for (int x : nums2) { + mask2 |= 1 << x; + } + int mask = mask1 & mask2; + if (mask) { + return __builtin_ctz(mask); + } + int a = __builtin_ctz(mask1); + int b = __builtin_ctz(mask2); + return min(a * 10 + b, b * 10 + a); + } +}; +``` + +```go +func minNumber(nums1 []int, nums2 []int) int { + var mask1, mask2 uint + for _, x := range nums1 { + mask1 |= 1 << x + } + for _, x := range nums2 { + mask2 |= 1 << x + } + if mask := mask1 & mask2; mask != 0 { + return bits.TrailingZeros(mask) + } + a, b := bits.TrailingZeros(mask1), bits.TrailingZeros(mask2) + return min(a*10+b, b*10+a) +} +``` + ```ts function minNumber(nums1: number[], nums2: number[]): number { let mask1: number = 0; @@ -403,69 +452,6 @@ function numberOfTrailingZeros(i: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn min_number(nums1: Vec, nums2: Vec) -> i32 { - let mut ans = 100; - - for &a in &nums1 { - for &b in &nums2 { - if a == b { - ans = std::cmp::min(ans, a); - } else { - ans = std::cmp::min(ans, std::cmp::min(a * 10 + b, b * 10 + a)); - } - } - } - - ans - } -} -``` - -```rust -use std::collections::HashMap; - -impl Solution { - pub fn min_number(nums1: Vec, nums2: Vec) -> i32 { - let mut h1: HashMap = HashMap::new(); - - for &n in &nums1 { - h1.insert(n, true); - } - - let mut h2: HashMap = HashMap::new(); - for &n in &nums2 { - h2.insert(n, true); - } - - let mut a = 0; - let mut b = 0; - for i in 1..10 { - if h1.contains_key(&i) && h2.contains_key(&i) { - return i; - } - - if a == 0 && h1.contains_key(&i) { - a = i; - } - - if b == 0 && h2.contains_key(&i) { - b = i; - } - } - - std::cmp::min(a * 10 + b, b * 10 + a) - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README_EN.md b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README_EN.md index d2093f0a0d6bb..6f03c54681d5a 100644 --- a/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README_EN.md +++ b/solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/README_EN.md @@ -34,32 +34,14 @@ Given two arrays of unique digits nums1 and ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We observe that if there are the same numbers in the arrays $nums1$ and $nums2$, then the minimum of the same numbers is the smallest number. Otherwise, we take the number $a$ in the array $nums1$ and the number $b$ in the array $nums2$, and concatenate the two numbers $a$ and $b$ into two numbers, and take the smaller number. The time complexity is $O(m \times n)$, and the space complexity is $O(1)$, where $m$ and $n$ are the lengths of the arrays $nums1$ and $nums2$. -**Solution 2: Hash Table or Array + Enumeration** - -We can use a hash table or array to record the numbers in the arrays $nums1$ and $nums2$, and then enumerate $1 \sim 9$. If $i$ appears in both arrays, then $i$ is the smallest number. Otherwise, we take the number $a$ in the array $nums1$ and the number $b$ in the array $nums2$, and concatenate the two numbers $a$ and $b$ into two numbers, and take the smaller number. - -The time complexity is $(m + n)$, and the space complexity is $O(C)$. Where $m$ and $n$ are the lengths of the arrays $nums1$ and $nums2$ respectively; and $C$ is the range of the numbers in the arrays $nums1$ and $nums2$, and the range in this problem is $C = 10$. - -**Solution 3: Bit Operation** - -Since the range of the numbers is $1 \sim 9$, we can use a binary number with a length of $10$ to represent the numbers in the arrays $nums1$ and $nums2$. We use $mask1$ to represent the numbers in the array $nums1$, and use $mask2$ to represent the numbers in the array $nums2$. - -If the number $mask$ obtained by performing a bitwise AND operation on $mask1$ and $mask2$ is not equal to $0$, then we extract the position of the last $1$ in the number $mask$, which is the smallest number. - -Otherwise, we extract the position of the last $1$ in $mask1$ and $mask2$ respectively, and denote them as $a$ and $b$, respectively. Then the smallest number is $min(a \times 10 + b, b \times 10 + a)$. - -The time complexity is $O(m + n)$, and the space complexity is $O(1)$. Where $m$ and $n$ are the lengths of the arrays $nums1$ and $nums2$ respectively. - -### **Python3** - ```python class Solution: def minNumber(self, nums1: List[int], nums2: List[int]) -> int: @@ -73,34 +55,6 @@ class Solution: return ans ``` -```python -class Solution: - def minNumber(self, nums1: List[int], nums2: List[int]) -> int: - s = set(nums1) & set(nums2) - if s: - return min(s) - a, b = min(nums1), min(nums2) - return min(a * 10 + b, b * 10 + a) -``` - -```python -class Solution: - def minNumber(self, nums1: List[int], nums2: List[int]) -> int: - mask1 = mask2 = 0 - for x in nums1: - mask1 |= 1 << x - for x in nums2: - mask2 |= 1 << x - mask = mask1 & mask2 - if mask: - return (mask & -mask).bit_length() - 1 - a = (mask1 & -mask1).bit_length() - 1 - b = (mask2 & -mask2).bit_length() - 1 - return min(a * 10 + b, b * 10 + a) -``` - -### **Java** - ```java class Solution { public int minNumber(int[] nums1, int[] nums2) { @@ -119,6 +73,97 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minNumber(vector& nums1, vector& nums2) { + int ans = 100; + for (int a : nums1) { + for (int b : nums2) { + if (a == b) { + ans = min(ans, a); + } else { + ans = min({ans, a * 10 + b, b * 10 + a}); + } + } + } + return ans; + } +}; +``` + +```go +func minNumber(nums1 []int, nums2 []int) int { + ans := 100 + for _, a := range nums1 { + for _, b := range nums2 { + if a == b { + ans = min(ans, a) + } else { + ans = min(ans, min(a*10+b, b*10+a)) + } + } + } + return ans +} +``` + +```ts +function minNumber(nums1: number[], nums2: number[]): number { + let ans = 100; + for (const a of nums1) { + for (const b of nums2) { + if (a === b) { + ans = Math.min(ans, a); + } else { + ans = Math.min(ans, a * 10 + b, b * 10 + a); + } + } + } + return ans; +} +``` + +```rust +impl Solution { + pub fn min_number(nums1: Vec, nums2: Vec) -> i32 { + let mut ans = 100; + + for &a in &nums1 { + for &b in &nums2 { + if a == b { + ans = std::cmp::min(ans, a); + } else { + ans = std::cmp::min(ans, std::cmp::min(a * 10 + b, b * 10 + a)); + } + } + } + + ans + } +} +``` + + + +### Solution 2: Hash Table or Array + Enumeration + +We can use a hash table or array to record the numbers in the arrays $nums1$ and $nums2$, and then enumerate $1 \sim 9$. If $i$ appears in both arrays, then $i$ is the smallest number. Otherwise, we take the number $a$ in the array $nums1$ and the number $b$ in the array $nums2$, and concatenate the two numbers $a$ and $b$ into two numbers, and take the smaller number. + +The time complexity is $(m + n)$, and the space complexity is $O(C)$. Where $m$ and $n$ are the lengths of the arrays $nums1$ and $nums2$ respectively; and $C$ is the range of the numbers in the arrays $nums1$ and $nums2$, and the range in this problem is $C = 10$. + + + +```python +class Solution: + def minNumber(self, nums1: List[int], nums2: List[int]) -> int: + s = set(nums1) & set(nums2) + if s: + return min(s) + a, b = min(nums1), min(nums2) + return min(a * 10 + b, b * 10 + a) +``` + ```java class Solution { public int minNumber(int[] nums1, int[] nums2) { @@ -147,48 +192,6 @@ class Solution { } ``` -```java -class Solution { - public int minNumber(int[] nums1, int[] nums2) { - int mask1 = 0, mask2 = 0; - for (int x : nums1) { - mask1 |= 1 << x; - } - for (int x : nums2) { - mask2 |= 1 << x; - } - int mask = mask1 & mask2; - if (mask != 0) { - return Integer.numberOfTrailingZeros(mask); - } - int a = Integer.numberOfTrailingZeros(mask1); - int b = Integer.numberOfTrailingZeros(mask2); - return Math.min(a * 10 + b, b * 10 + a); - } -} -``` - -### **C++** - -```cpp -class Solution { -public: - int minNumber(vector& nums1, vector& nums2) { - int ans = 100; - for (int a : nums1) { - for (int b : nums2) { - if (a == b) { - ans = min(ans, a); - } else { - ans = min({ans, a * 10 + b, b * 10 + a}); - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -218,46 +221,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minNumber(vector& nums1, vector& nums2) { - int mask1 = 0, mask2 = 0; - for (int x : nums1) { - mask1 |= 1 << x; - } - for (int x : nums2) { - mask2 |= 1 << x; - } - int mask = mask1 & mask2; - if (mask) { - return __builtin_ctz(mask); - } - int a = __builtin_ctz(mask1); - int b = __builtin_ctz(mask2); - return min(a * 10 + b, b * 10 + a); - } -}; -``` - -### **Go** - -```go -func minNumber(nums1 []int, nums2 []int) int { - ans := 100 - for _, a := range nums1 { - for _, b := range nums2 { - if a == b { - ans = min(ans, a) - } else { - ans = min(ans, min(a*10+b, b*10+a)) - } - } - } - return ans -} -``` - ```go func minNumber(nums1 []int, nums2 []int) int { s1 := [10]bool{} @@ -284,41 +247,6 @@ func minNumber(nums1 []int, nums2 []int) int { } ``` -```go -func minNumber(nums1 []int, nums2 []int) int { - var mask1, mask2 uint - for _, x := range nums1 { - mask1 |= 1 << x - } - for _, x := range nums2 { - mask2 |= 1 << x - } - if mask := mask1 & mask2; mask != 0 { - return bits.TrailingZeros(mask) - } - a, b := bits.TrailingZeros(mask1), bits.TrailingZeros(mask2) - return min(a*10+b, b*10+a) -} -``` - -### **TypeScript** - -```ts -function minNumber(nums1: number[], nums2: number[]): number { - let ans = 100; - for (const a of nums1) { - for (const b of nums2) { - if (a === b) { - ans = Math.min(ans, a); - } else { - ans = Math.min(ans, a * 10 + b, b * 10 + a); - } - } - } - return ans; -} -``` - ```ts function minNumber(nums1: number[], nums2: number[]): number { const s1: boolean[] = new Array(10).fill(false); @@ -346,6 +274,133 @@ function minNumber(nums1: number[], nums2: number[]): number { } ``` +```rust +use std::collections::HashMap; + +impl Solution { + pub fn min_number(nums1: Vec, nums2: Vec) -> i32 { + let mut h1: HashMap = HashMap::new(); + + for &n in &nums1 { + h1.insert(n, true); + } + + let mut h2: HashMap = HashMap::new(); + for &n in &nums2 { + h2.insert(n, true); + } + + let mut a = 0; + let mut b = 0; + for i in 1..10 { + if h1.contains_key(&i) && h2.contains_key(&i) { + return i; + } + + if a == 0 && h1.contains_key(&i) { + a = i; + } + + if b == 0 && h2.contains_key(&i) { + b = i; + } + } + + std::cmp::min(a * 10 + b, b * 10 + a) + } +} +``` + + + +### Solution 3: Bit Operation + +Since the range of the numbers is $1 \sim 9$, we can use a binary number with a length of $10$ to represent the numbers in the arrays $nums1$ and $nums2$. We use $mask1$ to represent the numbers in the array $nums1$, and use $mask2$ to represent the numbers in the array $nums2$. + +If the number $mask$ obtained by performing a bitwise AND operation on $mask1$ and $mask2$ is not equal to $0$, then we extract the position of the last $1$ in the number $mask$, which is the smallest number. + +Otherwise, we extract the position of the last $1$ in $mask1$ and $mask2$ respectively, and denote them as $a$ and $b$, respectively. Then the smallest number is $min(a \times 10 + b, b \times 10 + a)$. + +The time complexity is $O(m + n)$, and the space complexity is $O(1)$. Where $m$ and $n$ are the lengths of the arrays $nums1$ and $nums2$ respectively. + + + +```python +class Solution: + def minNumber(self, nums1: List[int], nums2: List[int]) -> int: + mask1 = mask2 = 0 + for x in nums1: + mask1 |= 1 << x + for x in nums2: + mask2 |= 1 << x + mask = mask1 & mask2 + if mask: + return (mask & -mask).bit_length() - 1 + a = (mask1 & -mask1).bit_length() - 1 + b = (mask2 & -mask2).bit_length() - 1 + return min(a * 10 + b, b * 10 + a) +``` + +```java +class Solution { + public int minNumber(int[] nums1, int[] nums2) { + int mask1 = 0, mask2 = 0; + for (int x : nums1) { + mask1 |= 1 << x; + } + for (int x : nums2) { + mask2 |= 1 << x; + } + int mask = mask1 & mask2; + if (mask != 0) { + return Integer.numberOfTrailingZeros(mask); + } + int a = Integer.numberOfTrailingZeros(mask1); + int b = Integer.numberOfTrailingZeros(mask2); + return Math.min(a * 10 + b, b * 10 + a); + } +} +``` + +```cpp +class Solution { +public: + int minNumber(vector& nums1, vector& nums2) { + int mask1 = 0, mask2 = 0; + for (int x : nums1) { + mask1 |= 1 << x; + } + for (int x : nums2) { + mask2 |= 1 << x; + } + int mask = mask1 & mask2; + if (mask) { + return __builtin_ctz(mask); + } + int a = __builtin_ctz(mask1); + int b = __builtin_ctz(mask2); + return min(a * 10 + b, b * 10 + a); + } +}; +``` + +```go +func minNumber(nums1 []int, nums2 []int) int { + var mask1, mask2 uint + for _, x := range nums1 { + mask1 |= 1 << x + } + for _, x := range nums2 { + mask2 |= 1 << x + } + if mask := mask1 & mask2; mask != 0 { + return bits.TrailingZeros(mask) + } + a, b := bits.TrailingZeros(mask1), bits.TrailingZeros(mask2) + return min(a*10+b, b*10+a) +} +``` + ```ts function minNumber(nums1: number[], nums2: number[]): number { let mask1: number = 0; @@ -395,69 +450,6 @@ function numberOfTrailingZeros(i: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn min_number(nums1: Vec, nums2: Vec) -> i32 { - let mut ans = 100; - - for &a in &nums1 { - for &b in &nums2 { - if a == b { - ans = std::cmp::min(ans, a); - } else { - ans = std::cmp::min(ans, std::cmp::min(a * 10 + b, b * 10 + a)); - } - } - } - - ans - } -} -``` - -```rust -use std::collections::HashMap; - -impl Solution { - pub fn min_number(nums1: Vec, nums2: Vec) -> i32 { - let mut h1: HashMap = HashMap::new(); - - for &n in &nums1 { - h1.insert(n, true); - } - - let mut h2: HashMap = HashMap::new(); - for &n in &nums2 { - h2.insert(n, true); - } - - let mut a = 0; - let mut b = 0; - for i in 1..10 { - if h1.contains_key(&i) && h2.contains_key(&i) { - return i; - } - - if a == 0 && h1.contains_key(&i) { - a = i; - } - - if b == 0 && h2.contains_key(&i) { - b = i; - } - } - - std::cmp::min(a * 10 + b, b * 10 + a) - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/README.md b/solution/2600-2699/2606.Find the Substring With Maximum Cost/README.md index 05503dce5884e..c725aeadcd028 100644 --- a/solution/2600-2699/2606.Find the Substring With Maximum Cost/README.md +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:前缀和 + 维护前缀和的最小值** +### 方法一:前缀和 + 维护前缀和的最小值 我们根据题目描述,遍历字符串 $s$ 的每个字符 $c$,求出其对应的价值 $v$,然后更新当前的前缀和 $tot=tot+v$,那么以 $c$ 结尾的最大开销子字符串的开销为 $tot$ 减去前缀和的最小值 $mi$,即 $tot-mi$,我们更新答案 $ans=max(ans,tot-mi)$,并维护前缀和的最小值 $mi=min(mi,tot)$。 @@ -68,20 +66,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 为字符串 $s$ 的长度;而 $C$ 为字符集的大小,本题中 $C=26$。 -**方法二:转化为最大子数组和问题** - -我们可以将每个字符 $c$ 的价值 $v$ 看作是一个整数,那么题目实际上转化为求最大子数组和问题。 - -我们用变量 $f$ 维护以当前字符 $c$ 结尾的最大开销子字符串的开销,每次遍历到一个字符 $c$,更新 $f=max(f, 0) + v$,然后更新答案 $ans=max(ans,f)$ 即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 为字符串 $s$ 的长度;而 $C$ 为字符集的大小,本题中 $C=26$。 - -### **Python3** - - - ```python class Solution: def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int: @@ -95,22 +81,6 @@ class Solution: return ans ``` -```python -class Solution: - def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int: - d = {c: v for c, v in zip(chars, vals)} - ans = f = 0 - for c in s: - v = d.get(c, ord(c) - ord('a') + 1) - f = max(f, 0) + v - ans = max(ans, f) - return ans -``` - -### **Java** - - - ```java class Solution { public int maximumCostSubstring(String s, String chars, int[] vals) { @@ -135,6 +105,90 @@ class Solution { } ``` +```cpp +class Solution { +public: + int maximumCostSubstring(string s, string chars, vector& vals) { + vector d(26); + iota(d.begin(), d.end(), 1); + int m = chars.size(); + for (int i = 0; i < m; ++i) { + d[chars[i] - 'a'] = vals[i]; + } + int ans = 0, tot = 0, mi = 0; + for (char& c : s) { + int v = d[c - 'a']; + tot += v; + ans = max(ans, tot - mi); + mi = min(mi, tot); + } + return ans; + } +}; +``` + +```go +func maximumCostSubstring(s string, chars string, vals []int) (ans int) { + d := [26]int{} + for i := range d { + d[i] = i + 1 + } + for i, c := range chars { + d[c-'a'] = vals[i] + } + tot, mi := 0, 0 + for _, c := range s { + v := d[c-'a'] + tot += v + ans = max(ans, tot-mi) + mi = min(mi, tot) + } + return +} +``` + +```ts +function maximumCostSubstring(s: string, chars: string, vals: number[]): number { + const d: number[] = Array.from({ length: 26 }, (_, i) => i + 1); + for (let i = 0; i < chars.length; ++i) { + d[chars.charCodeAt(i) - 97] = vals[i]; + } + let ans = 0; + let tot = 0; + let mi = 0; + for (const c of s) { + tot += d[c.charCodeAt(0) - 97]; + ans = Math.max(ans, tot - mi); + mi = Math.min(mi, tot); + } + return ans; +} +``` + + + +### 方法二:转化为最大子数组和问题 + +我们可以将每个字符 $c$ 的价值 $v$ 看作是一个整数,那么题目实际上转化为求最大子数组和问题。 + +我们用变量 $f$ 维护以当前字符 $c$ 结尾的最大开销子字符串的开销,每次遍历到一个字符 $c$,更新 $f=max(f, 0) + v$,然后更新答案 $ans=max(ans,f)$ 即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(C)$。其中 $n$ 为字符串 $s$ 的长度;而 $C$ 为字符集的大小,本题中 $C=26$。 + + + +```python +class Solution: + def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int: + d = {c: v for c, v in zip(chars, vals)} + ans = f = 0 + for c in s: + v = d.get(c, ord(c) - ord('a') + 1) + f = max(f, 0) + v + ans = max(ans, f) + return ans +``` + ```java class Solution { public int maximumCostSubstring(String s, String chars, int[] vals) { @@ -158,30 +212,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maximumCostSubstring(string s, string chars, vector& vals) { - vector d(26); - iota(d.begin(), d.end(), 1); - int m = chars.size(); - for (int i = 0; i < m; ++i) { - d[chars[i] - 'a'] = vals[i]; - } - int ans = 0, tot = 0, mi = 0; - for (char& c : s) { - int v = d[c - 'a']; - tot += v; - ans = max(ans, tot - mi); - mi = min(mi, tot); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -203,28 +233,6 @@ public: }; ``` -### **Go** - -```go -func maximumCostSubstring(s string, chars string, vals []int) (ans int) { - d := [26]int{} - for i := range d { - d[i] = i + 1 - } - for i, c := range chars { - d[c-'a'] = vals[i] - } - tot, mi := 0, 0 - for _, c := range s { - v := d[c-'a'] - tot += v - ans = max(ans, tot-mi) - mi = min(mi, tot) - } - return -} -``` - ```go func maximumCostSubstring(s string, chars string, vals []int) (ans int) { d := [26]int{} @@ -244,26 +252,6 @@ func maximumCostSubstring(s string, chars string, vals []int) (ans int) { } ``` -### **TypeScript** - -```ts -function maximumCostSubstring(s: string, chars: string, vals: number[]): number { - const d: number[] = Array.from({ length: 26 }, (_, i) => i + 1); - for (let i = 0; i < chars.length; ++i) { - d[chars.charCodeAt(i) - 97] = vals[i]; - } - let ans = 0; - let tot = 0; - let mi = 0; - for (const c of s) { - tot += d[c.charCodeAt(0) - 97]; - ans = Math.max(ans, tot - mi); - mi = Math.min(mi, tot); - } - return ans; -} -``` - ```ts function maximumCostSubstring(s: string, chars: string, vals: number[]): number { const d: number[] = Array.from({ length: 26 }, (_, i) => i + 1); @@ -280,10 +268,6 @@ function maximumCostSubstring(s: string, chars: string, vals: number[]): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2606.Find the Substring With Maximum Cost/README_EN.md b/solution/2600-2699/2606.Find the Substring With Maximum Cost/README_EN.md index d921c96b71508..1a12d72408e20 100644 --- a/solution/2600-2699/2606.Find the Substring With Maximum Cost/README_EN.md +++ b/solution/2600-2699/2606.Find the Substring With Maximum Cost/README_EN.md @@ -56,7 +56,7 @@ It can be proven that 0 is the maximum cost. ## Solutions -**Solution 1: Prefix sum + Maintain the minimum prefix sum** +### Solution 1: Prefix sum + Maintain the minimum prefix sum According to the description of the problem, we traverse each character $c$ in the string $s$, obtain its corresponding value $v$, and then update the current prefix sum $tot=tot+v$. Then, the cost of the maximum cost substring ending with $c$ is $tot$ minus the minimum prefix sum $mi$, that is, $tot-mi$. We update the answer $ans=max(ans,tot-mi)$ and maintain the minimum prefix sum $mi=min(mi,tot)$. @@ -64,18 +64,8 @@ After the traversal is over, return the answer $ans$. The time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of the string $s$; and $C$ is the size of the character set, which is $26$ in this problem. -**Solution 2: Convert to the maximum subarray sum problem** - -We can consider the value $v$ of each character $c$ as an integer, so the actual problem is to solve the maximum subarray sum problem. - -We use the variable $f$ to maintain the cost of the maximum cost substring ending with the current character $c$. Each time we traverse to a character $c$, we update $f=max(f, 0) + v$. Then we update the answer $ans=max(ans,f)$. - -The time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of the string $s$; and $C$ is the size of the character set, which is $26$ in this problem. - -### **Python3** - ```python class Solution: def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int: @@ -89,20 +79,6 @@ class Solution: return ans ``` -```python -class Solution: - def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int: - d = {c: v for c, v in zip(chars, vals)} - ans = f = 0 - for c in s: - v = d.get(c, ord(c) - ord('a') + 1) - f = max(f, 0) + v - ans = max(ans, f) - return ans -``` - -### **Java** - ```java class Solution { public int maximumCostSubstring(String s, String chars, int[] vals) { @@ -127,53 +103,6 @@ class Solution { } ``` -```java -class Solution { - public int maximumCostSubstring(String s, String chars, int[] vals) { - int[] d = new int[26]; - for (int i = 0; i < d.length; ++i) { - d[i] = i + 1; - } - int m = chars.length(); - for (int i = 0; i < m; ++i) { - d[chars.charAt(i) - 'a'] = vals[i]; - } - int ans = 0, f = 0; - int n = s.length(); - for (int i = 0; i < n; ++i) { - int v = d[s.charAt(i) - 'a']; - f = Math.max(f, 0) + v; - ans = Math.max(ans, f); - } - return ans; - } -} -``` - -### **C++** - -```cpp -class Solution { -public: - int maximumCostSubstring(string s, string chars, vector& vals) { - vector d(26, -1); - int m = chars.size(); - for (int i = 0; i < m; ++i) { - d[chars[i] - 'a'] = i; - } - int ans = 0, tot = 0, mi = 0; - for (char& c : s) { - int j = c - 'a'; - int v = d[j] == -1 ? j + 1 : vals[d[j]]; - tot += v; - ans = max(ans, tot - mi); - mi = min(mi, tot); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -196,8 +125,6 @@ public: }; ``` -### **Go** - ```go func maximumCostSubstring(s string, chars string, vals []int) (ans int) { d := [26]int{} @@ -218,6 +145,92 @@ func maximumCostSubstring(s string, chars string, vals []int) (ans int) { } ``` +```ts +function maximumCostSubstring(s: string, chars: string, vals: number[]): number { + const d: number[] = Array.from({ length: 26 }, (_, i) => i + 1); + for (let i = 0; i < chars.length; ++i) { + d[chars.charCodeAt(i) - 97] = vals[i]; + } + let ans = 0; + let tot = 0; + let mi = 0; + for (const c of s) { + tot += d[c.charCodeAt(0) - 97]; + ans = Math.max(ans, tot - mi); + mi = Math.min(mi, tot); + } + return ans; +} +``` + + + +### Solution 2: Convert to the maximum subarray sum problem + +We can consider the value $v$ of each character $c$ as an integer, so the actual problem is to solve the maximum subarray sum problem. + +We use the variable $f$ to maintain the cost of the maximum cost substring ending with the current character $c$. Each time we traverse to a character $c$, we update $f=max(f, 0) + v$. Then we update the answer $ans=max(ans,f)$. + +The time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of the string $s$; and $C$ is the size of the character set, which is $26$ in this problem. + + + +```python +class Solution: + def maximumCostSubstring(self, s: str, chars: str, vals: List[int]) -> int: + d = {c: v for c, v in zip(chars, vals)} + ans = f = 0 + for c in s: + v = d.get(c, ord(c) - ord('a') + 1) + f = max(f, 0) + v + ans = max(ans, f) + return ans +``` + +```java +class Solution { + public int maximumCostSubstring(String s, String chars, int[] vals) { + int[] d = new int[26]; + for (int i = 0; i < d.length; ++i) { + d[i] = i + 1; + } + int m = chars.length(); + for (int i = 0; i < m; ++i) { + d[chars.charAt(i) - 'a'] = vals[i]; + } + int ans = 0, f = 0; + int n = s.length(); + for (int i = 0; i < n; ++i) { + int v = d[s.charAt(i) - 'a']; + f = Math.max(f, 0) + v; + ans = Math.max(ans, f); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maximumCostSubstring(string s, string chars, vector& vals) { + vector d(26); + iota(d.begin(), d.end(), 1); + int m = chars.size(); + for (int i = 0; i < m; ++i) { + d[chars[i] - 'a'] = vals[i]; + } + int ans = 0, f = 0; + for (char& c : s) { + int v = d[c - 'a']; + f = max(f, 0) + v; + ans = max(ans, f); + } + return ans; + } +}; +``` + ```go func maximumCostSubstring(s string, chars string, vals []int) (ans int) { d := [26]int{} @@ -237,26 +250,6 @@ func maximumCostSubstring(s string, chars string, vals []int) (ans int) { } ``` -### **TypeScript** - -```ts -function maximumCostSubstring(s: string, chars: string, vals: number[]): number { - const d: number[] = Array.from({ length: 26 }, (_, i) => i + 1); - for (let i = 0; i < chars.length; ++i) { - d[chars.charCodeAt(i) - 97] = vals[i]; - } - let ans = 0; - let tot = 0; - let mi = 0; - for (const c of s) { - tot += d[c.charCodeAt(0) - 97]; - ans = Math.max(ans, tot - mi); - mi = Math.min(mi, tot); - } - return ans; -} -``` - ```ts function maximumCostSubstring(s: string, chars: string, vals: number[]): number { const d: number[] = Array.from({ length: 26 }, (_, i) => i + 1); @@ -273,10 +266,6 @@ function maximumCostSubstring(s: string, chars: string, vals: number[]): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2607.Make K-Subarray Sums Equal/README.md b/solution/2600-2699/2607.Make K-Subarray Sums Equal/README.md index 4218ac8913ea5..c1d05ab1f30c6 100644 --- a/solution/2600-2699/2607.Make K-Subarray Sums Equal/README.md +++ b/solution/2600-2699/2607.Make K-Subarray Sums Equal/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:数学(裴蜀定理) + 中位数贪心** +### 方法一:数学(裴蜀定理) + 中位数贪心 题目要求每个长度为 $k$ 的子数组的元素总和相等,那么有以下等式成立: @@ -89,10 +87,6 @@ $$ -### **Python3** - - - ```python class Solution: def makeSubKSumEqual(self, arr: List[int], k: int) -> int: @@ -106,10 +100,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long makeSubKSumEqual(int[] arr, int k) { @@ -136,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go func makeSubKSumEqual(arr []int, k int) (ans int64) { n := len(arr) @@ -196,8 +182,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function makeSubKSumEqual(arr: number[], k: number): number { const n = arr.length; @@ -225,10 +209,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2607.Make K-Subarray Sums Equal/README_EN.md b/solution/2600-2699/2607.Make K-Subarray Sums Equal/README_EN.md index c10529fe9008b..d66b0bda3503d 100644 --- a/solution/2600-2699/2607.Make K-Subarray Sums Equal/README_EN.md +++ b/solution/2600-2699/2607.Make K-Subarray Sums Equal/README_EN.md @@ -53,9 +53,9 @@ The array after the operations is [5,5,5,5] ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -70,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long makeSubKSumEqual(int[] arr, int k) { @@ -98,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +119,6 @@ public: }; ``` -### **Go** - ```go func makeSubKSumEqual(arr []int, k int) (ans int64) { n := len(arr) @@ -158,8 +152,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function makeSubKSumEqual(arr: number[], k: number): number { const n = arr.length; @@ -187,10 +179,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/README.md b/solution/2600-2699/2608.Shortest Cycle in a Graph/README.md index a54ce6e4739ca..d5f175fc33711 100644 --- a/solution/2600-2699/2608.Shortest Cycle in a Graph/README.md +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:枚举删除的边 + BFS** +### 方法一:枚举删除的边 + BFS 我们先根据数组 $edges$ 构建出邻接表 $g$,其中 $g[u]$ 表示顶点 $u$ 的所有邻接点。 @@ -53,20 +51,8 @@ 时间复杂度 $O(m^2)$,空间复杂度 $O(m + n)$。其中 $m$ 和 $n$ 分别为数组 $edges$ 的长度以及顶点数。 -**方法二:枚举点 + BFS** - -与方法一类似,我们先根据数组 $edges$ 构建出邻接表 $g$,其中 $g[u]$ 表示顶点 $u$ 的所有邻接点。 - -接下来,我们枚举顶点 $u$,如果从顶点 $u$ 出发,有两条路径都到达了顶点 $v$,说明当前找到了一个环,长度为两条路径的长度之和。我们取所有这样的环的最小值即可。 - -时间复杂度 $O(m \times n)$,空间复杂度 $O(m + n)$。其中 $m$ 和 $n$ 分别为数组 $edges$ 的长度以及顶点数。 - -### **Python3** - - - ```python class Solution: def findShortestCycle(self, n: int, edges: List[List[int]]) -> int: @@ -90,36 +76,6 @@ class Solution: return ans if ans < inf else -1 ``` -```python -class Solution: - def findShortestCycle(self, n: int, edges: List[List[int]]) -> int: - def bfs(u: int) -> int: - dist = [-1] * n - dist[u] = 0 - q = deque([(u, -1)]) - ans = inf - while q: - u, fa = q.popleft() - for v in g[u]: - if dist[v] < 0: - dist[v] = dist[u] + 1 - q.append((v, u)) - elif v != fa: - ans = min(ans, dist[u] + dist[v] + 1) - return ans - - g = defaultdict(list) - for u, v in edges: - g[u].append(v) - g[v].append(u) - ans = min(bfs(i) for i in range(n)) - return ans if ans < inf else -1 -``` - -### **Java** - - - ```java class Solution { private List[] g; @@ -162,6 +118,156 @@ class Solution { } ``` +```cpp +class Solution { +public: + int findShortestCycle(int n, vector>& edges) { + vector> g(n); + for (auto& e : edges) { + int u = e[0], v = e[1]; + g[u].push_back(v); + g[v].push_back(u); + } + const int inf = 1 << 30; + auto bfs = [&](int u, int v) -> int { + int dist[n]; + fill(dist, dist + n, inf); + dist[u] = 0; + queue q{{u}}; + while (!q.empty()) { + int i = q.front(); + q.pop(); + for (int j : g[i]) { + if ((i == u && j == v) || (i == v && j == u) || dist[j] != inf) { + continue; + } + dist[j] = dist[i] + 1; + q.push(j); + } + } + return dist[v] + 1; + }; + int ans = inf; + for (auto& e : edges) { + int u = e[0], v = e[1]; + ans = min(ans, bfs(u, v)); + } + return ans < inf ? ans : -1; + } +}; +``` + +```go +func findShortestCycle(n int, edges [][]int) int { + g := make([][]int, n) + for _, e := range edges { + u, v := e[0], e[1] + g[u] = append(g[u], v) + g[v] = append(g[v], u) + } + const inf = 1 << 30 + bfs := func(u, v int) int { + dist := make([]int, n) + for i := range dist { + dist[i] = inf + } + dist[u] = 0 + q := []int{u} + for len(q) > 0 { + i := q[0] + q = q[1:] + for _, j := range g[i] { + if (i == u && j == v) || (i == v && j == u) || dist[j] != inf { + continue + } + dist[j] = dist[i] + 1 + q = append(q, j) + } + } + return dist[v] + 1 + } + ans := inf + for _, e := range edges { + u, v := e[0], e[1] + ans = min(ans, bfs(u, v)) + } + if ans < inf { + return ans + } + return -1 +} +``` + +```ts +function findShortestCycle(n: number, edges: number[][]): number { + const g: number[][] = new Array(n).fill(0).map(() => []); + for (const [u, v] of edges) { + g[u].push(v); + g[v].push(u); + } + const inf = 1 << 30; + let ans = inf; + const bfs = (u: number, v: number) => { + const dist: number[] = new Array(n).fill(inf); + dist[u] = 0; + const q: number[] = [u]; + while (q.length) { + const i = q.shift()!; + for (const j of g[i]) { + if ((i == u && j == v) || (i == v && j == u) || dist[j] != inf) { + continue; + } + dist[j] = dist[i] + 1; + q.push(j); + } + } + return 1 + dist[v]; + }; + for (const [u, v] of edges) { + ans = Math.min(ans, bfs(u, v)); + } + return ans < inf ? ans : -1; +} +``` + + + +### 方法二:枚举点 + BFS + +与方法一类似,我们先根据数组 $edges$ 构建出邻接表 $g$,其中 $g[u]$ 表示顶点 $u$ 的所有邻接点。 + +接下来,我们枚举顶点 $u$,如果从顶点 $u$ 出发,有两条路径都到达了顶点 $v$,说明当前找到了一个环,长度为两条路径的长度之和。我们取所有这样的环的最小值即可。 + +时间复杂度 $O(m \times n)$,空间复杂度 $O(m + n)$。其中 $m$ 和 $n$ 分别为数组 $edges$ 的长度以及顶点数。 + + + +```python +class Solution: + def findShortestCycle(self, n: int, edges: List[List[int]]) -> int: + def bfs(u: int) -> int: + dist = [-1] * n + dist[u] = 0 + q = deque([(u, -1)]) + ans = inf + while q: + u, fa = q.popleft() + for v in g[u]: + if dist[v] < 0: + dist[v] = dist[u] + 1 + q.append((v, u)) + elif v != fa: + ans = min(ans, dist[u] + dist[v] + 1) + return ans + + g = defaultdict(list) + for u, v in edges: + g[u].append(v) + g[v].append(u) + ans = min(bfs(i) for i in range(n)) + return ans if ans < inf else -1 +``` + ```java class Solution { private List[] g; @@ -207,47 +313,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int findShortestCycle(int n, vector>& edges) { - vector> g(n); - for (auto& e : edges) { - int u = e[0], v = e[1]; - g[u].push_back(v); - g[v].push_back(u); - } - const int inf = 1 << 30; - auto bfs = [&](int u, int v) -> int { - int dist[n]; - fill(dist, dist + n, inf); - dist[u] = 0; - queue q{{u}}; - while (!q.empty()) { - int i = q.front(); - q.pop(); - for (int j : g[i]) { - if ((i == u && j == v) || (i == v && j == u) || dist[j] != inf) { - continue; - } - dist[j] = dist[i] + 1; - q.push(j); - } - } - return dist[v] + 1; - }; - int ans = inf; - for (auto& e : edges) { - int u = e[0], v = e[1]; - ans = min(ans, bfs(u, v)); - } - return ans < inf ? ans : -1; - } -}; -``` - ```cpp class Solution { public: @@ -291,49 +356,6 @@ public: }; ``` -### **Go** - -```go -func findShortestCycle(n int, edges [][]int) int { - g := make([][]int, n) - for _, e := range edges { - u, v := e[0], e[1] - g[u] = append(g[u], v) - g[v] = append(g[v], u) - } - const inf = 1 << 30 - bfs := func(u, v int) int { - dist := make([]int, n) - for i := range dist { - dist[i] = inf - } - dist[u] = 0 - q := []int{u} - for len(q) > 0 { - i := q[0] - q = q[1:] - for _, j := range g[i] { - if (i == u && j == v) || (i == v && j == u) || dist[j] != inf { - continue - } - dist[j] = dist[i] + 1 - q = append(q, j) - } - } - return dist[v] + 1 - } - ans := inf - for _, e := range edges { - u, v := e[0], e[1] - ans = min(ans, bfs(u, v)) - } - if ans < inf { - return ans - } - return -1 -} -``` - ```go func findShortestCycle(n int, edges [][]int) int { g := make([][]int, n) @@ -378,40 +400,6 @@ func findShortestCycle(n int, edges [][]int) int { } ``` -### **TypeScript** - -```ts -function findShortestCycle(n: number, edges: number[][]): number { - const g: number[][] = new Array(n).fill(0).map(() => []); - for (const [u, v] of edges) { - g[u].push(v); - g[v].push(u); - } - const inf = 1 << 30; - let ans = inf; - const bfs = (u: number, v: number) => { - const dist: number[] = new Array(n).fill(inf); - dist[u] = 0; - const q: number[] = [u]; - while (q.length) { - const i = q.shift()!; - for (const j of g[i]) { - if ((i == u && j == v) || (i == v && j == u) || dist[j] != inf) { - continue; - } - dist[j] = dist[i] + 1; - q.push(j); - } - } - return 1 + dist[v]; - }; - for (const [u, v] of edges) { - ans = Math.min(ans, bfs(u, v)); - } - return ans < inf ? ans : -1; -} -``` - ```ts function findShortestCycle(n: number, edges: number[][]): number { const g: number[][] = new Array(n).fill(0).map(() => []); @@ -448,10 +436,6 @@ function findShortestCycle(n: number, edges: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2608.Shortest Cycle in a Graph/README_EN.md b/solution/2600-2699/2608.Shortest Cycle in a Graph/README_EN.md index d2693bf37f2de..00bd3d705317a 100644 --- a/solution/2600-2699/2608.Shortest Cycle in a Graph/README_EN.md +++ b/solution/2600-2699/2608.Shortest Cycle in a Graph/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Enumerate edges + BFS** +### Solution 1: Enumerate edges + BFS We first construct the adjacency list $g$ of the graph according to the array $edges$, where $g[u]$ represents all the adjacent vertices of vertex $u$. @@ -49,18 +49,8 @@ Then we enumerate the two-directional edge $(u, v)$, if the path from vertex $u$ The time complexity is $O(m^2)$ and the space complexity is $O(m + n)$, where $m$ and $n$ are the length of the array $edges$ and the number of vertices. -**Solution 2: Enumerate points + BFS** - -Similar to Solution 1, we first construct the adjacency list $g$ of the graph according to the array $edges$, where $g[u]$ represents all the adjacent vertices of vertex $u$. - -Then we enumerate the vertex $u$, if there are two paths from vertex $u$ to vertex $v$, then we currently find a cycle, the length is the sum of the length of the two paths. We take the minimum of all these cycles. - -The time complexity is $O(m \times n)$ and the space complexity is $O(m + n)$, where $m$ and $n$ are the length of the array $edges$ and the number of vertices. - -### **Python3** - ```python class Solution: def findShortestCycle(self, n: int, edges: List[List[int]]) -> int: @@ -84,34 +74,6 @@ class Solution: return ans if ans < inf else -1 ``` -```python -class Solution: - def findShortestCycle(self, n: int, edges: List[List[int]]) -> int: - def bfs(u: int) -> int: - dist = [-1] * n - dist[u] = 0 - q = deque([(u, -1)]) - ans = inf - while q: - u, fa = q.popleft() - for v in g[u]: - if dist[v] < 0: - dist[v] = dist[u] + 1 - q.append((v, u)) - elif v != fa: - ans = min(ans, dist[u] + dist[v] + 1) - return ans - - g = defaultdict(list) - for u, v in edges: - g[u].append(v) - g[v].append(u) - ans = min(bfs(i) for i in range(n)) - return ans if ans < inf else -1 -``` - -### **Java** - ```java class Solution { private List[] g; @@ -154,6 +116,156 @@ class Solution { } ``` +```cpp +class Solution { +public: + int findShortestCycle(int n, vector>& edges) { + vector> g(n); + for (auto& e : edges) { + int u = e[0], v = e[1]; + g[u].push_back(v); + g[v].push_back(u); + } + const int inf = 1 << 30; + auto bfs = [&](int u, int v) -> int { + int dist[n]; + fill(dist, dist + n, inf); + dist[u] = 0; + queue q{{u}}; + while (!q.empty()) { + int i = q.front(); + q.pop(); + for (int j : g[i]) { + if ((i == u && j == v) || (i == v && j == u) || dist[j] != inf) { + continue; + } + dist[j] = dist[i] + 1; + q.push(j); + } + } + return dist[v] + 1; + }; + int ans = inf; + for (auto& e : edges) { + int u = e[0], v = e[1]; + ans = min(ans, bfs(u, v)); + } + return ans < inf ? ans : -1; + } +}; +``` + +```go +func findShortestCycle(n int, edges [][]int) int { + g := make([][]int, n) + for _, e := range edges { + u, v := e[0], e[1] + g[u] = append(g[u], v) + g[v] = append(g[v], u) + } + const inf = 1 << 30 + bfs := func(u, v int) int { + dist := make([]int, n) + for i := range dist { + dist[i] = inf + } + dist[u] = 0 + q := []int{u} + for len(q) > 0 { + i := q[0] + q = q[1:] + for _, j := range g[i] { + if (i == u && j == v) || (i == v && j == u) || dist[j] != inf { + continue + } + dist[j] = dist[i] + 1 + q = append(q, j) + } + } + return dist[v] + 1 + } + ans := inf + for _, e := range edges { + u, v := e[0], e[1] + ans = min(ans, bfs(u, v)) + } + if ans < inf { + return ans + } + return -1 +} +``` + +```ts +function findShortestCycle(n: number, edges: number[][]): number { + const g: number[][] = new Array(n).fill(0).map(() => []); + for (const [u, v] of edges) { + g[u].push(v); + g[v].push(u); + } + const inf = 1 << 30; + let ans = inf; + const bfs = (u: number, v: number) => { + const dist: number[] = new Array(n).fill(inf); + dist[u] = 0; + const q: number[] = [u]; + while (q.length) { + const i = q.shift()!; + for (const j of g[i]) { + if ((i == u && j == v) || (i == v && j == u) || dist[j] != inf) { + continue; + } + dist[j] = dist[i] + 1; + q.push(j); + } + } + return 1 + dist[v]; + }; + for (const [u, v] of edges) { + ans = Math.min(ans, bfs(u, v)); + } + return ans < inf ? ans : -1; +} +``` + + + +### Solution 2: Enumerate points + BFS + +Similar to Solution 1, we first construct the adjacency list $g$ of the graph according to the array $edges$, where $g[u]$ represents all the adjacent vertices of vertex $u$. + +Then we enumerate the vertex $u$, if there are two paths from vertex $u$ to vertex $v$, then we currently find a cycle, the length is the sum of the length of the two paths. We take the minimum of all these cycles. + +The time complexity is $O(m \times n)$ and the space complexity is $O(m + n)$, where $m$ and $n$ are the length of the array $edges$ and the number of vertices. + + + +```python +class Solution: + def findShortestCycle(self, n: int, edges: List[List[int]]) -> int: + def bfs(u: int) -> int: + dist = [-1] * n + dist[u] = 0 + q = deque([(u, -1)]) + ans = inf + while q: + u, fa = q.popleft() + for v in g[u]: + if dist[v] < 0: + dist[v] = dist[u] + 1 + q.append((v, u)) + elif v != fa: + ans = min(ans, dist[u] + dist[v] + 1) + return ans + + g = defaultdict(list) + for u, v in edges: + g[u].append(v) + g[v].append(u) + ans = min(bfs(i) for i in range(n)) + return ans if ans < inf else -1 +``` + ```java class Solution { private List[] g; @@ -199,47 +311,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int findShortestCycle(int n, vector>& edges) { - vector> g(n); - for (auto& e : edges) { - int u = e[0], v = e[1]; - g[u].push_back(v); - g[v].push_back(u); - } - const int inf = 1 << 30; - auto bfs = [&](int u, int v) -> int { - int dist[n]; - fill(dist, dist + n, inf); - dist[u] = 0; - queue q{{u}}; - while (!q.empty()) { - int i = q.front(); - q.pop(); - for (int j : g[i]) { - if ((i == u && j == v) || (i == v && j == u) || dist[j] != inf) { - continue; - } - dist[j] = dist[i] + 1; - q.push(j); - } - } - return dist[v] + 1; - }; - int ans = inf; - for (auto& e : edges) { - int u = e[0], v = e[1]; - ans = min(ans, bfs(u, v)); - } - return ans < inf ? ans : -1; - } -}; -``` - ```cpp class Solution { public: @@ -283,49 +354,6 @@ public: }; ``` -### **Go** - -```go -func findShortestCycle(n int, edges [][]int) int { - g := make([][]int, n) - for _, e := range edges { - u, v := e[0], e[1] - g[u] = append(g[u], v) - g[v] = append(g[v], u) - } - const inf = 1 << 30 - bfs := func(u, v int) int { - dist := make([]int, n) - for i := range dist { - dist[i] = inf - } - dist[u] = 0 - q := []int{u} - for len(q) > 0 { - i := q[0] - q = q[1:] - for _, j := range g[i] { - if (i == u && j == v) || (i == v && j == u) || dist[j] != inf { - continue - } - dist[j] = dist[i] + 1 - q = append(q, j) - } - } - return dist[v] + 1 - } - ans := inf - for _, e := range edges { - u, v := e[0], e[1] - ans = min(ans, bfs(u, v)) - } - if ans < inf { - return ans - } - return -1 -} -``` - ```go func findShortestCycle(n int, edges [][]int) int { g := make([][]int, n) @@ -370,40 +398,6 @@ func findShortestCycle(n int, edges [][]int) int { } ``` -### **TypeScript** - -```ts -function findShortestCycle(n: number, edges: number[][]): number { - const g: number[][] = new Array(n).fill(0).map(() => []); - for (const [u, v] of edges) { - g[u].push(v); - g[v].push(u); - } - const inf = 1 << 30; - let ans = inf; - const bfs = (u: number, v: number) => { - const dist: number[] = new Array(n).fill(inf); - dist[u] = 0; - const q: number[] = [u]; - while (q.length) { - const i = q.shift()!; - for (const j of g[i]) { - if ((i == u && j == v) || (i == v && j == u) || dist[j] != inf) { - continue; - } - dist[j] = dist[i] + 1; - q.push(j); - } - } - return 1 + dist[v]; - }; - for (const [u, v] of edges) { - ans = Math.min(ans, bfs(u, v)); - } - return ans < inf ? ans : -1; -} -``` - ```ts function findShortestCycle(n: number, edges: number[][]): number { const g: number[][] = new Array(n).fill(0).map(() => []); @@ -440,10 +434,6 @@ function findShortestCycle(n: number, edges: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README.md b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README.md index 8396e74bfc5d5..3f38679a42c0b 100644 --- a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README.md +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README.md @@ -51,33 +51,14 @@ ## 解法 - - -**方法一:暴力枚举** +### 方法一:暴力枚举 注意到数据范围很小,因此,我们可以枚举所有的子串 $s[i..j]$,检查其是否为平衡子串,如果是,则更新答案。 时间复杂度 $O(n^3)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。 -**方法二:枚举优化** - -我们用变量 $zero$ 和 $one$ 分别记录当前连续的 $0$ 和 $1$ 的个数。 - -遍历字符串 $s$,对于当前字符 $c$: - -- 如果当前字符为 `'0'`,我们判断此时 $one$ 是否大于 $0$,是则将 $zero$ 和 $one$ 重置为 $0$,接下来将 $zero$ 加 $1$。 -- 如果当前字符为 `'1'`,则将 $one$ 加 $1$,并更新答案为 $ans = \max(ans, 2 \times \min(one, zero))$。 - -遍历结束后,即可得到最长的平衡子串的长度。 - -时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。 - -### **Python3** - - - ```python class Solution: def findTheLongestBalancedSubstring(self, s: str) -> int: @@ -99,25 +80,6 @@ class Solution: return ans ``` -```python -class Solution: - def findTheLongestBalancedSubstring(self, s: str) -> int: - ans = zero = one = 0 - for c in s: - if c == '0': - if one: - zero = one = 0 - zero += 1 - else: - one += 1 - ans = max(ans, 2 * min(one, zero)) - return ans -``` - -### **Java** - - - ```java class Solution { public int findTheLongestBalancedSubstring(String s) { @@ -147,29 +109,6 @@ class Solution { } ``` -```java -class Solution { - public int findTheLongestBalancedSubstring(String s) { - int zero = 0, one = 0; - int ans = 0, n = s.length(); - for (int i = 0; i < n; ++i) { - if (s.charAt(i) == '0') { - if (one > 0) { - zero = 0; - one = 0; - } - ++zero; - } else { - ans = Math.max(ans, 2 * Math.min(zero, ++one)); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -199,30 +138,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findTheLongestBalancedSubstring(string s) { - int zero = 0, one = 0; - int ans = 0; - for (char& c : s) { - if (c == '0') { - if (one > 0) { - zero = 0; - one = 0; - } - ++zero; - } else { - ans = max(ans, 2 * min(zero, ++one)); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func findTheLongestBalancedSubstring(s string) (ans int) { n := len(s) @@ -248,26 +163,6 @@ func findTheLongestBalancedSubstring(s string) (ans int) { } ``` -```go -func findTheLongestBalancedSubstring(s string) (ans int) { - zero, one := 0, 0 - for _, c := range s { - if c == '0' { - if one > 0 { - zero, one = 0, 0 - } - zero++ - } else { - one++ - ans = max(ans, 2*min(zero, one)) - } - } - return -} -``` - -### **TypeScript** - ```ts function findTheLongestBalancedSubstring(s: string): number { const n = s.length; @@ -294,28 +189,6 @@ function findTheLongestBalancedSubstring(s: string): number { } ``` -```ts -function findTheLongestBalancedSubstring(s: string): number { - let zero = 0; - let one = 0; - let ans = 0; - for (const c of s) { - if (c === '0') { - if (one > 0) { - zero = 0; - one = 0; - } - ++zero; - } else { - ans = Math.max(ans, 2 * Math.min(zero, ++one)); - } - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn find_the_longest_balanced_substring(s: String) -> i32 { @@ -353,6 +226,119 @@ impl Solution { } ``` + + +### 方法二:枚举优化 + +我们用变量 $zero$ 和 $one$ 分别记录当前连续的 $0$ 和 $1$ 的个数。 + +遍历字符串 $s$,对于当前字符 $c$: + +- 如果当前字符为 `'0'`,我们判断此时 $one$ 是否大于 $0$,是则将 $zero$ 和 $one$ 重置为 $0$,接下来将 $zero$ 加 $1$。 +- 如果当前字符为 `'1'`,则将 $one$ 加 $1$,并更新答案为 $ans = \max(ans, 2 \times \min(one, zero))$。 + +遍历结束后,即可得到最长的平衡子串的长度。 + +时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为字符串 $s$ 的长度。 + + + +```python +class Solution: + def findTheLongestBalancedSubstring(self, s: str) -> int: + ans = zero = one = 0 + for c in s: + if c == '0': + if one: + zero = one = 0 + zero += 1 + else: + one += 1 + ans = max(ans, 2 * min(one, zero)) + return ans +``` + +```java +class Solution { + public int findTheLongestBalancedSubstring(String s) { + int zero = 0, one = 0; + int ans = 0, n = s.length(); + for (int i = 0; i < n; ++i) { + if (s.charAt(i) == '0') { + if (one > 0) { + zero = 0; + one = 0; + } + ++zero; + } else { + ans = Math.max(ans, 2 * Math.min(zero, ++one)); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int findTheLongestBalancedSubstring(string s) { + int zero = 0, one = 0; + int ans = 0; + for (char& c : s) { + if (c == '0') { + if (one > 0) { + zero = 0; + one = 0; + } + ++zero; + } else { + ans = max(ans, 2 * min(zero, ++one)); + } + } + return ans; + } +}; +``` + +```go +func findTheLongestBalancedSubstring(s string) (ans int) { + zero, one := 0, 0 + for _, c := range s { + if c == '0' { + if one > 0 { + zero, one = 0, 0 + } + zero++ + } else { + one++ + ans = max(ans, 2*min(zero, one)) + } + } + return +} +``` + +```ts +function findTheLongestBalancedSubstring(s: string): number { + let zero = 0; + let one = 0; + let ans = 0; + for (const c of s) { + if (c === '0') { + if (one > 0) { + zero = 0; + one = 0; + } + ++zero; + } else { + ans = Math.max(ans, 2 * Math.min(zero, ++one)); + } + } + return ans; +} +``` + ```rust impl Solution { pub fn find_the_longest_balanced_substring(s: String) -> i32 { @@ -378,10 +364,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README_EN.md b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README_EN.md index 039a40356ae73..fda20b60aa866 100644 --- a/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README_EN.md +++ b/solution/2600-2699/2609.Find the Longest Balanced Substring of a Binary String/README_EN.md @@ -47,29 +47,14 @@ ## Solutions -**Solution 1: Brute force** +### Solution 1: Brute force Since the range of $n$ is small, we can enumerate all substrings $s[i..j]$ to check if it is a balanced string. If so, update the answer. The time complexity is $O(n^3)$, and the space complexity is $O(1)$. Where $n$ is the length of string $s$. -**Solution 2: Enumeration optimization** - -We use variables $zero$ and $one$ to record the number of continuous $0$ and $1$. - -Traverse the string $s$, for the current character $c$: - -- If the current character is `'0'`, we check if $one$ is greater than $0$, if so, we reset $zero$ and $one$ to $0$, and then add $1$ to $zero$. -- If the current character is `'1'`, we add $1$ to $one$, and update the answer to $ans = max(ans, 2 \times min(one, zero))$. - -After the traversal is complete, we can get the length of the longest balanced substring. - -The time complexity is $O(n)$, and the space complexity is $O(1)$. Where $n$ is the length of string $s$. - -### **Python3** - ```python class Solution: def findTheLongestBalancedSubstring(self, s: str) -> int: @@ -91,23 +76,6 @@ class Solution: return ans ``` -```python -class Solution: - def findTheLongestBalancedSubstring(self, s: str) -> int: - ans = zero = one = 0 - for c in s: - if c == '0': - if one: - zero = one = 0 - zero += 1 - else: - one += 1 - ans = max(ans, 2 * min(one, zero)) - return ans -``` - -### **Java** - ```java class Solution { public int findTheLongestBalancedSubstring(String s) { @@ -137,29 +105,6 @@ class Solution { } ``` -```java -class Solution { - public int findTheLongestBalancedSubstring(String s) { - int zero = 0, one = 0; - int ans = 0, n = s.length(); - for (int i = 0; i < n; ++i) { - if (s.charAt(i) == '0') { - if (one > 0) { - zero = 0; - one = 0; - } - ++zero; - } else { - ans = Math.max(ans, 2 * Math.min(zero, ++one)); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -189,30 +134,6 @@ public: }; ``` -```cpp -class Solution { -public: - int findTheLongestBalancedSubstring(string s) { - int zero = 0, one = 0; - int ans = 0; - for (char& c : s) { - if (c == '0') { - if (one > 0) { - zero = 0; - one = 0; - } - ++zero; - } else { - ans = max(ans, 2 * min(zero, ++one)); - } - } - return ans; - } -}; -``` - -### **Go** - ```go func findTheLongestBalancedSubstring(s string) (ans int) { n := len(s) @@ -238,26 +159,6 @@ func findTheLongestBalancedSubstring(s string) (ans int) { } ``` -```go -func findTheLongestBalancedSubstring(s string) (ans int) { - zero, one := 0, 0 - for _, c := range s { - if c == '0' { - if one > 0 { - zero, one = 0, 0 - } - zero++ - } else { - one++ - ans = max(ans, 2*min(zero, one)) - } - } - return -} -``` - -### **TypeScript** - ```ts function findTheLongestBalancedSubstring(s: string): number { const n = s.length; @@ -284,28 +185,6 @@ function findTheLongestBalancedSubstring(s: string): number { } ``` -```ts -function findTheLongestBalancedSubstring(s: string): number { - let zero = 0; - let one = 0; - let ans = 0; - for (const c of s) { - if (c === '0') { - if (one > 0) { - zero = 0; - one = 0; - } - ++zero; - } else { - ans = Math.max(ans, 2 * Math.min(zero, ++one)); - } - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn find_the_longest_balanced_substring(s: String) -> i32 { @@ -343,6 +222,119 @@ impl Solution { } ``` + + +### Solution 2: Enumeration optimization + +We use variables $zero$ and $one$ to record the number of continuous $0$ and $1$. + +Traverse the string $s$, for the current character $c$: + +- If the current character is `'0'`, we check if $one$ is greater than $0$, if so, we reset $zero$ and $one$ to $0$, and then add $1$ to $zero$. +- If the current character is `'1'`, we add $1$ to $one$, and update the answer to $ans = max(ans, 2 \times min(one, zero))$. + +After the traversal is complete, we can get the length of the longest balanced substring. + +The time complexity is $O(n)$, and the space complexity is $O(1)$. Where $n$ is the length of string $s$. + + + +```python +class Solution: + def findTheLongestBalancedSubstring(self, s: str) -> int: + ans = zero = one = 0 + for c in s: + if c == '0': + if one: + zero = one = 0 + zero += 1 + else: + one += 1 + ans = max(ans, 2 * min(one, zero)) + return ans +``` + +```java +class Solution { + public int findTheLongestBalancedSubstring(String s) { + int zero = 0, one = 0; + int ans = 0, n = s.length(); + for (int i = 0; i < n; ++i) { + if (s.charAt(i) == '0') { + if (one > 0) { + zero = 0; + one = 0; + } + ++zero; + } else { + ans = Math.max(ans, 2 * Math.min(zero, ++one)); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int findTheLongestBalancedSubstring(string s) { + int zero = 0, one = 0; + int ans = 0; + for (char& c : s) { + if (c == '0') { + if (one > 0) { + zero = 0; + one = 0; + } + ++zero; + } else { + ans = max(ans, 2 * min(zero, ++one)); + } + } + return ans; + } +}; +``` + +```go +func findTheLongestBalancedSubstring(s string) (ans int) { + zero, one := 0, 0 + for _, c := range s { + if c == '0' { + if one > 0 { + zero, one = 0, 0 + } + zero++ + } else { + one++ + ans = max(ans, 2*min(zero, one)) + } + } + return +} +``` + +```ts +function findTheLongestBalancedSubstring(s: string): number { + let zero = 0; + let one = 0; + let ans = 0; + for (const c of s) { + if (c === '0') { + if (one > 0) { + zero = 0; + one = 0; + } + ++zero; + } else { + ans = Math.max(ans, 2 * Math.min(zero, ++one)); + } + } + return ans; +} +``` + ```rust impl Solution { pub fn find_the_longest_balanced_substring(s: String) -> i32 { @@ -368,10 +360,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README.md b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README.md index f1bc8145a1522..1b83aae786d1e 100644 --- a/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README.md +++ b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README.md @@ -49,9 +49,7 @@ nums 中的所有元素都有用到,并且每一行都由不同的整数组成 ## 解法 - - -**方法一:数组或哈希表** +### 方法一:数组或哈希表 我们先用数组或哈希表 $cnt$ 统计数组 $nums$ 中每个元素出现的次数。 @@ -63,10 +61,6 @@ nums 中的所有元素都有用到,并且每一行都由不同的整数组成 -### **Python3** - - - ```python class Solution: def findMatrix(self, nums: List[int]) -> List[List[int]]: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> findMatrix(int[] nums) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +121,6 @@ public: }; ``` -### **Go** - ```go func findMatrix(nums []int) (ans [][]int) { n := len(nums) @@ -154,8 +140,6 @@ func findMatrix(nums []int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function findMatrix(nums: number[]): number[][] { const ans: number[][] = []; @@ -176,10 +160,6 @@ function findMatrix(nums: number[]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README_EN.md b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README_EN.md index e4750e02ed500..6519562844b17 100644 --- a/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README_EN.md +++ b/solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/README_EN.md @@ -47,7 +47,7 @@ It can be shown that we cannot have less than 3 rows in a valid array. ## Solutions -**Solution 1: Array or Hash Table** +### Solution 1: Array or Hash Table We use an array or hash table $cnt$ to count the number of occurrences of each element in the array $nums$. @@ -59,8 +59,6 @@ The time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is t -### **Python3** - ```python class Solution: def findMatrix(self, nums: List[int]) -> List[List[int]]: @@ -74,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List> findMatrix(int[] nums) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +119,6 @@ public: }; ``` -### **Go** - ```go func findMatrix(nums []int) (ans [][]int) { n := len(nums) @@ -146,8 +138,6 @@ func findMatrix(nums []int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function findMatrix(nums: number[]): number[][] { const ans: number[][] = []; @@ -168,10 +158,6 @@ function findMatrix(nums: number[]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2611.Mice and Cheese/README.md b/solution/2600-2699/2611.Mice and Cheese/README.md index f86dfcadaf1bc..1823e091a687b 100644 --- a/solution/2600-2699/2611.Mice and Cheese/README.md +++ b/solution/2600-2699/2611.Mice and Cheese/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 我们可以先将所有奶酪分给第二只老鼠,因此初始得分为 $\sum_{i=0}^{n-1} reward2[i]$。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: @@ -83,19 +77,6 @@ class Solution: return sum(reward1[i] for i in idx[:k]) + sum(reward2[i] for i in idx[k:]) ``` -```python -class Solution: - def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: - for i, x in enumerate(reward2): - reward1[i] -= x - reward1.sort(reverse=True) - return sum(reward2) + sum(reward1[:k]) -``` - -### **Java** - - - ```java class Solution { public int miceAndCheese(int[] reward1, int[] reward2, int k) { @@ -117,26 +98,6 @@ class Solution { } ``` -```java -class Solution { - public int miceAndCheese(int[] reward1, int[] reward2, int k) { - int ans = 0; - int n = reward1.length; - for (int i = 0; i < n; ++i) { - ans += reward2[i]; - reward1[i] -= reward2[i]; - } - Arrays.sort(reward1); - for (int i = 0; i < k; ++i) { - ans += reward1[n - i - 1]; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -157,25 +118,6 @@ public: }; ``` -```cpp -class Solution { -public: - int miceAndCheese(vector& reward1, vector& reward2, int k) { - int n = reward1.size(); - int ans = 0; - for (int i = 0; i < n; ++i) { - ans += reward2[i]; - reward1[i] -= reward2[i]; - } - sort(reward1.rbegin(), reward1.rend()); - ans += accumulate(reward1.begin(), reward1.begin() + k, 0); - return ans; - } -}; -``` - -### **Go** - ```go func miceAndCheese(reward1 []int, reward2 []int, k int) (ans int) { n := len(reward1) @@ -197,23 +139,6 @@ func miceAndCheese(reward1 []int, reward2 []int, k int) (ans int) { } ``` -```go -func miceAndCheese(reward1 []int, reward2 []int, k int) (ans int) { - for i, x := range reward2 { - ans += x - reward1[i] -= x - } - sort.Ints(reward1) - n := len(reward1) - for i := 0; i < k; i++ { - ans += reward1[n-i-1] - } - return -} -``` - -### **TypeScript** - ```ts function miceAndCheese(reward1: number[], reward2: number[], k: number): number { const n = reward1.length; @@ -230,6 +155,71 @@ function miceAndCheese(reward1: number[], reward2: number[], k: number): number } ``` + + +### 方法二 + + + +```python +class Solution: + def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: + for i, x in enumerate(reward2): + reward1[i] -= x + reward1.sort(reverse=True) + return sum(reward2) + sum(reward1[:k]) +``` + +```java +class Solution { + public int miceAndCheese(int[] reward1, int[] reward2, int k) { + int ans = 0; + int n = reward1.length; + for (int i = 0; i < n; ++i) { + ans += reward2[i]; + reward1[i] -= reward2[i]; + } + Arrays.sort(reward1); + for (int i = 0; i < k; ++i) { + ans += reward1[n - i - 1]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int miceAndCheese(vector& reward1, vector& reward2, int k) { + int n = reward1.size(); + int ans = 0; + for (int i = 0; i < n; ++i) { + ans += reward2[i]; + reward1[i] -= reward2[i]; + } + sort(reward1.rbegin(), reward1.rend()); + ans += accumulate(reward1.begin(), reward1.begin() + k, 0); + return ans; + } +}; +``` + +```go +func miceAndCheese(reward1 []int, reward2 []int, k int) (ans int) { + for i, x := range reward2 { + ans += x + reward1[i] -= x + } + sort.Ints(reward1) + n := len(reward1) + for i := 0; i < k; i++ { + ans += reward1[n-i-1] + } + return +} +``` + ```ts function miceAndCheese(reward1: number[], reward2: number[], k: number): number { const n = reward1.length; @@ -246,10 +236,6 @@ function miceAndCheese(reward1: number[], reward2: number[], k: number): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2611.Mice and Cheese/README_EN.md b/solution/2600-2699/2611.Mice and Cheese/README_EN.md index 3183a8e0e2bb3..67eb1d7b5a9de 100644 --- a/solution/2600-2699/2611.Mice and Cheese/README_EN.md +++ b/solution/2600-2699/2611.Mice and Cheese/README_EN.md @@ -49,7 +49,7 @@ It can be proven that 2 is the maximum total points that the mice can achieve. ## Solutions -**Solution 1: Greedy + Sort** +### Solution 1: Greedy + Sort We can first give all the cheese to the second mouse. Next, consider giving $k$ pieces of cheese to the first mouse. How should we choose these $k$ pieces of cheese? Obviously, if we give the $i$-th piece of cheese from the second mouse to the first mouse, the change in the score is $reward1[i] - reward2[i]$. We hope that this change is as large as possible, so that the total score is maximized. @@ -59,8 +59,6 @@ Time complexity $O(n \times \log n)$, space complexity $O(n)$. Where $n$ is the -### **Python3** - ```python class Solution: def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: @@ -69,17 +67,6 @@ class Solution: return sum(reward1[i] for i in idx[:k]) + sum(reward2[i] for i in idx[k:]) ``` -```python -class Solution: - def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: - for i, x in enumerate(reward2): - reward1[i] -= x - reward1.sort(reverse=True) - return sum(reward2) + sum(reward1[:k]) -``` - -### **Java** - ```java class Solution { public int miceAndCheese(int[] reward1, int[] reward2, int k) { @@ -101,26 +88,6 @@ class Solution { } ``` -```java -class Solution { - public int miceAndCheese(int[] reward1, int[] reward2, int k) { - int ans = 0; - int n = reward1.length; - for (int i = 0; i < n; ++i) { - ans += reward2[i]; - reward1[i] -= reward2[i]; - } - Arrays.sort(reward1); - for (int i = 0; i < k; ++i) { - ans += reward1[n - i - 1]; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -141,25 +108,6 @@ public: }; ``` -```cpp -class Solution { -public: - int miceAndCheese(vector& reward1, vector& reward2, int k) { - int n = reward1.size(); - int ans = 0; - for (int i = 0; i < n; ++i) { - ans += reward2[i]; - reward1[i] -= reward2[i]; - } - sort(reward1.rbegin(), reward1.rend()); - ans += accumulate(reward1.begin(), reward1.begin() + k, 0); - return ans; - } -}; -``` - -### **Go** - ```go func miceAndCheese(reward1 []int, reward2 []int, k int) (ans int) { n := len(reward1) @@ -181,23 +129,6 @@ func miceAndCheese(reward1 []int, reward2 []int, k int) (ans int) { } ``` -```go -func miceAndCheese(reward1 []int, reward2 []int, k int) (ans int) { - for i, x := range reward2 { - ans += x - reward1[i] -= x - } - sort.Ints(reward1) - n := len(reward1) - for i := 0; i < k; i++ { - ans += reward1[n-i-1] - } - return -} -``` - -### **TypeScript** - ```ts function miceAndCheese(reward1: number[], reward2: number[], k: number): number { const n = reward1.length; @@ -214,6 +145,71 @@ function miceAndCheese(reward1: number[], reward2: number[], k: number): number } ``` + + +### Solution 2 + + + +```python +class Solution: + def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: + for i, x in enumerate(reward2): + reward1[i] -= x + reward1.sort(reverse=True) + return sum(reward2) + sum(reward1[:k]) +``` + +```java +class Solution { + public int miceAndCheese(int[] reward1, int[] reward2, int k) { + int ans = 0; + int n = reward1.length; + for (int i = 0; i < n; ++i) { + ans += reward2[i]; + reward1[i] -= reward2[i]; + } + Arrays.sort(reward1); + for (int i = 0; i < k; ++i) { + ans += reward1[n - i - 1]; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int miceAndCheese(vector& reward1, vector& reward2, int k) { + int n = reward1.size(); + int ans = 0; + for (int i = 0; i < n; ++i) { + ans += reward2[i]; + reward1[i] -= reward2[i]; + } + sort(reward1.rbegin(), reward1.rend()); + ans += accumulate(reward1.begin(), reward1.begin() + k, 0); + return ans; + } +}; +``` + +```go +func miceAndCheese(reward1 []int, reward2 []int, k int) (ans int) { + for i, x := range reward2 { + ans += x + reward1[i] -= x + } + sort.Ints(reward1) + n := len(reward1) + for i := 0; i < k; i++ { + ans += reward1[n-i-1] + } + return +} +``` + ```ts function miceAndCheese(reward1: number[], reward2: number[], k: number): number { const n = reward1.length; @@ -230,10 +226,6 @@ function miceAndCheese(reward1: number[], reward2: number[], k: number): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2612.Minimum Reverse Operations/README.md b/solution/2600-2699/2612.Minimum Reverse Operations/README.md index cfb538715242a..5bd8982b63bc5 100644 --- a/solution/2600-2699/2612.Minimum Reverse Operations/README.md +++ b/solution/2600-2699/2612.Minimum Reverse Operations/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:有序集合 + BFS** +### 方法一:有序集合 + BFS 我们注意到,对于一个子数组区间 $[l,..r]$ 中的任意一个下标 $i$,翻转后的下标 $j = l + r - i$。 @@ -94,10 +92,6 @@ -### **Python3** - - - ```python from sortedcontainers import SortedSet @@ -131,10 +125,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] minReverseOperations(int n, int p, int[] banned, int k) { @@ -168,8 +158,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -206,8 +194,6 @@ public: }; ``` -### **Go** - ```go func minReverseOperations(n int, p int, banned []int, k int) []int { ans := make([]int, n) @@ -241,8 +227,6 @@ func minReverseOperations(n int, p int, banned []int, k int) []int { } ``` -### **TypeScript** - ```ts function minReverseOperations(n: number, p: number, banned: number[], k: number): number[] { const ans = new Array(n).fill(-1); @@ -916,6 +900,12 @@ class TreeMultiSet { } ``` + + +### 方法二 + + + ```ts function minReverseOperations(n: number, p: number, banned: number[], k: number): number[] { const ans = new Array(n).fill(-1); @@ -1567,10 +1557,6 @@ class TreapMultiSet implements ITreapMultiSet { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2612.Minimum Reverse Operations/README_EN.md b/solution/2600-2699/2612.Minimum Reverse Operations/README_EN.md index 22b600b3b3f2c..0bd0d962ef425 100644 --- a/solution/2600-2699/2612.Minimum Reverse Operations/README_EN.md +++ b/solution/2600-2699/2612.Minimum Reverse Operations/README_EN.md @@ -58,7 +58,7 @@ ## Solutions -**Solution 1: Ordered Set + BFS** +### Solution 1: Ordered Set + BFS We notice that for any index $i$ in the subarray interval $[l,..r]$, the flipped index $j = l + r - i$. @@ -84,8 +84,6 @@ The time complexity is $O(n \times \log n)$ and the space complexity is $O(n)$. -### **Python3** - ```python from sortedcontainers import SortedSet @@ -119,8 +117,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] minReverseOperations(int n, int p, int[] banned, int k) { @@ -154,8 +150,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -192,8 +186,6 @@ public: }; ``` -### **Go** - ```go func minReverseOperations(n int, p int, banned []int, k int) []int { ans := make([]int, n) @@ -227,8 +219,6 @@ func minReverseOperations(n int, p int, banned []int, k int) []int { } ``` -### **TypeScript** - ```ts function minReverseOperations(n: number, p: number, banned: number[], k: number): number[] { const ans = new Array(n).fill(-1); @@ -902,6 +892,12 @@ class TreeMultiSet { } ``` + + +### Solution 2 + + + ```ts function minReverseOperations(n: number, p: number, banned: number[], k: number): number[] { const ans = new Array(n).fill(-1); @@ -1553,10 +1549,6 @@ class TreapMultiSet implements ITreapMultiSet { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2613.Beautiful Pairs/README.md b/solution/2600-2699/2613.Beautiful Pairs/README.md index 4be18153b7a65..956bd41ce3372 100644 --- a/solution/2600-2699/2613.Beautiful Pairs/README.md +++ b/solution/2600-2699/2613.Beautiful Pairs/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:排序 + 分治** +### 方法一:排序 + 分治 本题相当于找出平面中两个点,使得它们的曼哈顿距离最小,如果有多个点满足条件,则返回下标字典序最小的点。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def beautifulPair(self, nums1: List[int], nums2: List[int]) -> List[int]: @@ -112,10 +106,6 @@ class Solution: return [pi, pj] ``` -### **Java** - - - ```java class Solution { private List points = new ArrayList<>(); @@ -184,8 +174,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -255,8 +243,6 @@ public: }; ``` -### **Go** - ```go func beautifulPair(nums1 []int, nums2 []int) []int { n := len(nums1) @@ -325,8 +311,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function beautifulPair(nums1: number[], nums2: number[]): number[] { const pl: Map = new Map(); @@ -396,10 +380,6 @@ function f(x: number, y: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2613.Beautiful Pairs/README_EN.md b/solution/2600-2699/2613.Beautiful Pairs/README_EN.md index 723021fb9f2ef..d26825e6a394c 100644 --- a/solution/2600-2699/2613.Beautiful Pairs/README_EN.md +++ b/solution/2600-2699/2613.Beautiful Pairs/README_EN.md @@ -44,7 +44,7 @@ ## Solutions -**Solution 1: Sorting + Divide and Conquer** +### Solution 1: Sorting + Divide and Conquer This problem is equivalent to finding two points in the plane, such that the Manhattan distance between them is the smallest. If there are multiple points satisfying the condition, return the one with the smallest index. @@ -64,8 +64,6 @@ Space complexity: $O(n)$. -### **Python3** - ```python class Solution: def beautifulPair(self, nums1: List[int], nums2: List[int]) -> List[int]: @@ -106,8 +104,6 @@ class Solution: return [pi, pj] ``` -### **Java** - ```java class Solution { private List points = new ArrayList<>(); @@ -176,8 +172,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -247,8 +241,6 @@ public: }; ``` -### **Go** - ```go func beautifulPair(nums1 []int, nums2 []int) []int { n := len(nums1) @@ -317,8 +309,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function beautifulPair(nums1: number[], nums2: number[]): number[] { const pl: Map = new Map(); @@ -388,10 +378,6 @@ function f(x: number, y: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2614.Prime In Diagonal/README.md b/solution/2600-2699/2614.Prime In Diagonal/README.md index 2fb650881c202..8894d5e816e84 100644 --- a/solution/2600-2699/2614.Prime In Diagonal/README.md +++ b/solution/2600-2699/2614.Prime In Diagonal/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:数学 + 模拟** +### 方法一:数学 + 模拟 我们实现一个函数 `is_prime`,判断一个数是否为质数。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def diagonalPrime(self, nums: List[List[int]]) -> int: @@ -85,10 +79,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int diagonalPrime(int[][] nums) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +140,6 @@ public: }; ``` -### **Go** - ```go func diagonalPrime(nums [][]int) (ans int) { n := len(nums) @@ -181,8 +167,6 @@ func isPrime(x int) bool { } ``` -### **Rust** - ```rust impl Solution { pub fn diagonal_prime(nums: Vec>) -> i32 { @@ -218,10 +202,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2614.Prime In Diagonal/README_EN.md b/solution/2600-2699/2614.Prime In Diagonal/README_EN.md index 5313a21a318a1..13d97c2748ad9 100644 --- a/solution/2600-2699/2614.Prime In Diagonal/README_EN.md +++ b/solution/2600-2699/2614.Prime In Diagonal/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Math + Simulation** +### Solution 1: Math + Simulation We implement a function `is_prime` to check whether a number is prime. @@ -57,8 +57,6 @@ The time complexity is $O(n \times \sqrt{M})$, where $n$ and $M$ are the number -### **Python3** - ```python class Solution: def diagonalPrime(self, nums: List[List[int]]) -> int: @@ -77,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int diagonalPrime(int[][] nums) { @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +136,6 @@ public: }; ``` -### **Go** - ```go func diagonalPrime(nums [][]int) (ans int) { n := len(nums) @@ -171,8 +163,6 @@ func isPrime(x int) bool { } ``` -### **Rust** - ```rust impl Solution { pub fn diagonal_prime(nums: Vec>) -> i32 { @@ -208,10 +198,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2615.Sum of Distances/README.md b/solution/2600-2699/2615.Sum of Distances/README.md index 65515bc8d99bf..6c8693e0c40b1 100644 --- a/solution/2600-2699/2615.Sum of Distances/README.md +++ b/solution/2600-2699/2615.Sum of Distances/README.md @@ -44,9 +44,7 @@ i = 4 ,arr[4] = 0 因为不存在值等于 2 的其他下标。 ## 解法 - - -**方法一:哈希表 + 前缀和** +### 方法一:哈希表 + 前缀和 我们先用哈希表 $d$ 记录数组 $nums$ 中每个元素对应的下标列表,即 $d[x]$ 表示数组 $nums$ 中所有值为 $x$ 的下标列表。 @@ -58,10 +56,6 @@ i = 4 ,arr[4] = 0 因为不存在值等于 2 的其他下标。 -### **Python3** - - - ```python class Solution: def distance(self, nums: List[int]) -> List[int]: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long[] distance(int[] nums) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func distance(nums []int) []int64 { n := len(nums) @@ -172,10 +158,6 @@ func distance(nums []int) []int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2615.Sum of Distances/README_EN.md b/solution/2600-2699/2615.Sum of Distances/README_EN.md index 063eeff7c089e..090e291719cdb 100644 --- a/solution/2600-2699/2615.Sum of Distances/README_EN.md +++ b/solution/2600-2699/2615.Sum of Distances/README_EN.md @@ -41,9 +41,9 @@ When i = 4, arr[4] = 0 because there is no other index with value 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long[] distance(int[] nums) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +121,6 @@ public: }; ``` -### **Go** - ```go func distance(nums []int) []int64 { n := len(nums) @@ -153,10 +147,6 @@ func distance(nums []int) []int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README.md b/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README.md index 3c09e6ae90cae..113c0d4590207 100644 --- a/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README.md +++ b/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:二分查找 + 贪心** +### 方法一:二分查找 + 贪心 我们注意到,最大差值具备单调性,即如果最大差值 $x$ 满足条件,那么 $x-1$ 也一定满足条件。因此我们可以使用二分查找的方法,找到最小的满足条件的最大差值。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def minimizeMax(self, nums: List[int], p: int) -> int: @@ -78,10 +72,6 @@ class Solution: return bisect_left(range(nums[-1] - nums[0] + 1), True, key=check) ``` -### **Java** - - - ```java class Solution { public int minimizeMax(int[] nums, int p) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func minimizeMax(nums []int, p int) int { sort.Ints(nums) @@ -164,10 +150,6 @@ func minimizeMax(nums []int, p int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README_EN.md b/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README_EN.md index 8be51cde34b0b..78409845bd490 100644 --- a/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README_EN.md +++ b/solution/2600-2699/2616.Minimize the Maximum Difference of Pairs/README_EN.md @@ -39,7 +39,7 @@ The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, ## Solutions -**Solution 1: Binary search + Greedy** +### Solution 1: Binary search + Greedy We find that the maximum difference has the monotonicity, that is, if the maximum difference $x$ satisfies the condition, then $x-1$ must also satisfy the condition. Therefore, we can use the binary search method to find the smallest maximum difference that satisfies the condition. @@ -51,8 +51,6 @@ The time complexity is $O(n \times (\log n + \log m))$, where $n$ is the length -### **Python3** - ```python class Solution: def minimizeMax(self, nums: List[int], p: int) -> int: @@ -70,8 +68,6 @@ class Solution: return bisect_left(range(nums[-1] - nums[0] + 1), True, key=check) ``` -### **Java** - ```java class Solution { public int minimizeMax(int[] nums, int p) { @@ -102,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +128,6 @@ public: }; ``` -### **Go** - ```go func minimizeMax(nums []int, p int) int { sort.Ints(nums) @@ -154,10 +146,6 @@ func minimizeMax(nums []int, p int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2617.Minimum Number of Visited Cells in a Grid/README.md b/solution/2600-2699/2617.Minimum Number of Visited Cells in a Grid/README.md index 97bf4b18d21ab..007a28eca4b0d 100644 --- a/solution/2600-2699/2617.Minimum Number of Visited Cells in a Grid/README.md +++ b/solution/2600-2699/2617.Minimum Number of Visited Cells in a Grid/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:优先队列** +### 方法一:优先队列 我们记网格的行数为 $m$,列数为 $n$,定义 $dist[i][j]$ 表示从坐标 $(0, 0)$ 移动到坐标 $(i, j)$ 的最短距离,初始时 $dist[0][0] = 1$,其它 $dist[i][j]=-1$。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def minimumVisitedCells(self, grid: List[List[int]]) -> int: @@ -107,10 +101,6 @@ class Solution: return dist[-1][-1] ``` -### **Java** - - - ```java class Solution { public int minimumVisitedCells(int[][] grid) { @@ -151,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -188,8 +176,6 @@ public: }; ``` -### **Go** - ```go func minimumVisitedCells(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -242,10 +228,6 @@ func (a *hp) Push(x any) { *a = append(*a, x.(pair)) } func (a *hp) Pop() any { l := len(*a); t := (*a)[l-1]; *a = (*a)[:l-1]; return t } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2617.Minimum Number of Visited Cells in a Grid/README_EN.md b/solution/2600-2699/2617.Minimum Number of Visited Cells in a Grid/README_EN.md index d2c5c68091a77..15a2243bf83e1 100644 --- a/solution/2600-2699/2617.Minimum Number of Visited Cells in a Grid/README_EN.md +++ b/solution/2600-2699/2617.Minimum Number of Visited Cells in a Grid/README_EN.md @@ -54,7 +54,7 @@ ## Solutions -**Solution 1: Priority Queue** +### Solution 1: Priority Queue Let's denote the number of rows of the grid as $m$ and the number of columns as $n$. Define $dist[i][j]$ to be the shortest distance from the coordinate $(0, 0)$ to the coordinate $(i, j)$. Initially, $dist[0][0]=1$ and $dist[i][j]=-1$ for all other $i$ and $j$. @@ -70,8 +70,6 @@ The time complexity is $O(m \times n \times \log (m \times n))$ and the space co -### **Python3** - ```python class Solution: def minimumVisitedCells(self, grid: List[List[int]]) -> int: @@ -96,8 +94,6 @@ class Solution: return dist[-1][-1] ``` -### **Java** - ```java class Solution { public int minimumVisitedCells(int[][] grid) { @@ -138,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +169,6 @@ public: }; ``` -### **Go** - ```go func minimumVisitedCells(grid [][]int) int { m, n := len(grid), len(grid[0]) @@ -229,10 +221,6 @@ func (a *hp) Push(x any) { *a = append(*a, x.(pair)) } func (a *hp) Pop() any { l := len(*a); t := (*a)[l-1]; *a = (*a)[:l-1]; return t } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2618.Check if Object Instance of Class/README.md b/solution/2600-2699/2618.Check if Object Instance of Class/README.md index 9c9911d17ff0b..7559e7a67d019 100644 --- a/solution/2600-2699/2618.Check if Object Instance of Class/README.md +++ b/solution/2600-2699/2618.Check if Object Instance of Class/README.md @@ -49,14 +49,10 @@ Dog 是 Animal 的子类。因此,Dog 对象同时是 Dog 和 Animal 的实例 ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function checkIfInstanceOf(obj: any, classFunction: any): boolean { if (classFunction === null || classFunction === undefined) { @@ -77,10 +73,6 @@ function checkIfInstanceOf(obj: any, classFunction: any): boolean { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2618.Check if Object Instance of Class/README_EN.md b/solution/2600-2699/2618.Check if Object Instance of Class/README_EN.md index 983f32e05b1e4..58cfcded43800 100644 --- a/solution/2600-2699/2618.Check if Object Instance of Class/README_EN.md +++ b/solution/2600-2699/2618.Check if Object Instance of Class/README_EN.md @@ -47,9 +47,9 @@ Dog is a subclass of Animal. Therefore, a Dog object is an instance of both Dog ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function checkIfInstanceOf(obj: any, classFunction: any): boolean { @@ -71,10 +71,6 @@ function checkIfInstanceOf(obj: any, classFunction: any): boolean { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2619.Array Prototype Last/README.md b/solution/2600-2699/2619.Array Prototype Last/README.md index 2e0f5e325d3af..bcf96b9b368e1 100644 --- a/solution/2600-2699/2619.Array Prototype Last/README.md +++ b/solution/2600-2699/2619.Array Prototype Last/README.md @@ -39,14 +39,10 @@ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts declare global { interface Array { @@ -66,10 +62,6 @@ Array.prototype.last = function () { export {}; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2619.Array Prototype Last/README_EN.md b/solution/2600-2699/2619.Array Prototype Last/README_EN.md index 337778d12e8e2..93da1e5c2dd40 100644 --- a/solution/2600-2699/2619.Array Prototype Last/README_EN.md +++ b/solution/2600-2699/2619.Array Prototype Last/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts declare global { @@ -58,10 +58,6 @@ Array.prototype.last = function () { export {}; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2620.Counter/README.md b/solution/2600-2699/2620.Counter/README.md index a300c5ab0f981..b66f8c3e53de0 100644 --- a/solution/2600-2699/2620.Counter/README.md +++ b/solution/2600-2699/2620.Counter/README.md @@ -45,14 +45,10 @@ n = -2 ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function createCounter(n: number): () => number { let i = n; @@ -69,10 +65,6 @@ function createCounter(n: number): () => number { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2620.Counter/README_EN.md b/solution/2600-2699/2620.Counter/README_EN.md index 84dc079e06f34..ed9ce9a9929e1 100644 --- a/solution/2600-2699/2620.Counter/README_EN.md +++ b/solution/2600-2699/2620.Counter/README_EN.md @@ -41,9 +41,9 @@ n = -2 ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function createCounter(n: number): () => number { @@ -61,10 +61,6 @@ function createCounter(n: number): () => number { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2621.Sleep/README.md b/solution/2600-2699/2621.Sleep/README.md index 937f1d6504d95..d087d1233e29e 100644 --- a/solution/2600-2699/2621.Sleep/README.md +++ b/solution/2600-2699/2621.Sleep/README.md @@ -41,14 +41,10 @@ sleep(100).then(() => { ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts async function sleep(millis: number): Promise { return new Promise(r => setTimeout(r, millis)); @@ -60,10 +56,6 @@ async function sleep(millis: number): Promise { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2621.Sleep/README_EN.md b/solution/2600-2699/2621.Sleep/README_EN.md index 8e450df5e344e..6eccfbae6d1b8 100644 --- a/solution/2600-2699/2621.Sleep/README_EN.md +++ b/solution/2600-2699/2621.Sleep/README_EN.md @@ -36,9 +36,9 @@ sleep(100).then(() => { ## Solutions - +### Solution 1 -### **TypeScript** + ```ts async function sleep(millis: number): Promise { @@ -51,10 +51,6 @@ async function sleep(millis: number): Promise { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2622.Cache With Time Limit/README.md b/solution/2600-2699/2622.Cache With Time Limit/README.md index 48c1487e95de8..11253a4c98f82 100644 --- a/solution/2600-2699/2622.Cache With Time Limit/README.md +++ b/solution/2600-2699/2622.Cache With Time Limit/README.md @@ -71,9 +71,7 @@ timeDelays = [0, 0, 40, 50, 120, 200, 250] ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们用哈希表 $cache$ 记录键值对,其中键为整型键 $key$,值为一个数组,数组的第一个元素为整型值 $value$,第二个元素为元素的过期时间 $expire$。 @@ -83,10 +81,6 @@ timeDelays = [0, 0, 40, 50, 120, 200, 250] -### **TypeScript** - - - ```ts class TimeLimitedCache { private cache: Map = new Map(); @@ -133,10 +127,6 @@ class TimeLimitedCache { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2622.Cache With Time Limit/README_EN.md b/solution/2600-2699/2622.Cache With Time Limit/README_EN.md index db3deb9b1bc8c..4cb91ba9f3a42 100644 --- a/solution/2600-2699/2622.Cache With Time Limit/README_EN.md +++ b/solution/2600-2699/2622.Cache With Time Limit/README_EN.md @@ -67,9 +67,9 @@ At t=250, count() returns 0 because the cache is empty. ## Solutions - +### Solution 1 -### **TypeScript** + ```ts class TimeLimitedCache { @@ -117,10 +117,6 @@ class TimeLimitedCache { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2623.Memoize/README.md b/solution/2600-2699/2623.Memoize/README.md index 9326f9b82e935..ee811d990a645 100644 --- a/solution/2600-2699/2623.Memoize/README.md +++ b/solution/2600-2699/2623.Memoize/README.md @@ -85,9 +85,7 @@ values = [[5],[]] ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以使用哈希表来存储函数的参数和返回值,当再次调用函数时,如果参数已经存在于哈希表中,则直接返回哈希表中的值,否则调用函数并将返回值存入哈希表中。 @@ -95,10 +93,6 @@ values = [[5],[]] -### **TypeScript** - - - ```ts type Fn = (...params: any) => any; @@ -127,10 +121,6 @@ function memoize(fn: Fn): Fn { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2623.Memoize/README_EN.md b/solution/2600-2699/2623.Memoize/README_EN.md index 9bf4639178405..6eb527738e8c3 100644 --- a/solution/2600-2699/2623.Memoize/README_EN.md +++ b/solution/2600-2699/2623.Memoize/README_EN.md @@ -81,9 +81,9 @@ values = [[5],[]] ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type Fn = (...params: any) => any; @@ -113,10 +113,6 @@ function memoize(fn: Fn): Fn { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2624.Snail Traversal/README.md b/solution/2600-2699/2624.Snail Traversal/README.md index 57f121c7cffb5..dace0eab4c1f6 100644 --- a/solution/2600-2699/2624.Snail Traversal/README.md +++ b/solution/2600-2699/2624.Snail Traversal/README.md @@ -67,9 +67,7 @@ colsCount = 2 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们首先判断数组的长度是否等于行数与列数的乘积,如果不等,说明输入是无效的,返回空数组。 @@ -79,10 +77,6 @@ colsCount = 2 -### **TypeScript** - - - ```ts declare global { interface Array { @@ -113,10 +107,6 @@ Array.prototype.snail = function (rowsCount: number, colsCount: number): number[ */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2624.Snail Traversal/README_EN.md b/solution/2600-2699/2624.Snail Traversal/README_EN.md index 866829e1746b4..8b2ab5700c03a 100644 --- a/solution/2600-2699/2624.Snail Traversal/README_EN.md +++ b/solution/2600-2699/2624.Snail Traversal/README_EN.md @@ -65,9 +65,9 @@ colsCount = 2 ## Solutions - +### Solution 1 -### **TypeScript** + ```ts declare global { @@ -99,10 +99,6 @@ Array.prototype.snail = function (rowsCount: number, colsCount: number): number[ */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2625.Flatten Deeply Nested Array/README.md b/solution/2600-2699/2625.Flatten Deeply Nested Array/README.md index 8844e701c15f7..0deeaf4ae5626 100644 --- a/solution/2600-2699/2625.Flatten Deeply Nested Array/README.md +++ b/solution/2600-2699/2625.Flatten Deeply Nested Array/README.md @@ -67,9 +67,7 @@ n = 2 ## 解法 - - -**方法一:递归** +### 方法一:递归 我们可以使用递归的方法,将多维数组扁平化。 @@ -79,10 +77,6 @@ n = 2 -### **TypeScript** - - - ```ts type MultiDimensionalArray = (number | MultiDimensionalArray)[]; @@ -102,10 +96,6 @@ var flat = function (arr: MultiDimensionalArray, n: number): MultiDimensionalArr }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2625.Flatten Deeply Nested Array/README_EN.md b/solution/2600-2699/2625.Flatten Deeply Nested Array/README_EN.md index 7706c3d2a7be9..610992d7025cc 100644 --- a/solution/2600-2699/2625.Flatten Deeply Nested Array/README_EN.md +++ b/solution/2600-2699/2625.Flatten Deeply Nested Array/README_EN.md @@ -62,9 +62,9 @@ The maximum depth of any subarray is 1. Thus, all of them are flattened. ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type MultiDimensionalArray = (number | MultiDimensionalArray)[]; @@ -85,10 +85,6 @@ var flat = function (arr: MultiDimensionalArray, n: number): MultiDimensionalArr }; ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2626.Array Reduce Transformation/README.md b/solution/2600-2699/2626.Array Reduce Transformation/README.md index dc76479562162..fd96c25d0c973 100644 --- a/solution/2600-2699/2626.Array Reduce Transformation/README.md +++ b/solution/2600-2699/2626.Array Reduce Transformation/README.md @@ -73,14 +73,10 @@ init = 25 ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts type Fn = (accum: number, curr: number) => number; @@ -93,10 +89,6 @@ function reduce(nums: number[], fn: Fn, init: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2626.Array Reduce Transformation/README_EN.md b/solution/2600-2699/2626.Array Reduce Transformation/README_EN.md index 77935e60d2006..137a26031c493 100644 --- a/solution/2600-2699/2626.Array Reduce Transformation/README_EN.md +++ b/solution/2600-2699/2626.Array Reduce Transformation/README_EN.md @@ -69,9 +69,9 @@ init = 25 ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type Fn = (accum: number, curr: number) => number; @@ -85,10 +85,6 @@ function reduce(nums: number[], fn: Fn, init: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2627.Debounce/README.md b/solution/2600-2699/2627.Debounce/README.md index 203d73f3139d1..f8cf60e6cded8 100644 --- a/solution/2600-2699/2627.Debounce/README.md +++ b/solution/2600-2699/2627.Debounce/README.md @@ -88,14 +88,10 @@ calls = [ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts type F = (...p: any[]) => any; @@ -120,10 +116,6 @@ function debounce(fn: F, t: number): F { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2627.Debounce/README_EN.md b/solution/2600-2699/2627.Debounce/README_EN.md index 6350d59f7ae0a..1d2342f9706f3 100644 --- a/solution/2600-2699/2627.Debounce/README_EN.md +++ b/solution/2600-2699/2627.Debounce/README_EN.md @@ -84,9 +84,9 @@ The 3rd call is delayed by 150ms and ran at 450ms. The inputs were (5, 6). ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type F = (...p: any[]) => any; @@ -112,10 +112,6 @@ function debounce(fn: F, t: number): F { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2628.JSON Deep Equal/README.md b/solution/2600-2699/2628.JSON Deep Equal/README.md index 0f6458a548ef2..258abed8ca709 100644 --- a/solution/2600-2699/2628.JSON Deep Equal/README.md +++ b/solution/2600-2699/2628.JSON Deep Equal/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 我们先判断 `o1` 是否为空,或者 `o1` 是否非对象类型。如果是,则直接返回 `o1` 和 `o2` 是否相等。 @@ -83,10 +81,6 @@ -### **TypeScript** - - - ```ts function areDeeplyEqual(o1: any, o2: any): boolean { if (o1 === null || typeof o1 !== 'object') { @@ -124,10 +118,6 @@ function areDeeplyEqual(o1: any, o2: any): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2628.JSON Deep Equal/README_EN.md b/solution/2600-2699/2628.JSON Deep Equal/README_EN.md index 6e41c088fbbea..46fc955b060fb 100644 --- a/solution/2600-2699/2628.JSON Deep Equal/README_EN.md +++ b/solution/2600-2699/2628.JSON Deep Equal/README_EN.md @@ -67,9 +67,9 @@ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function areDeeplyEqual(o1: any, o2: any): boolean { @@ -108,10 +108,6 @@ function areDeeplyEqual(o1: any, o2: any): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2629.Function Composition/README.md b/solution/2600-2699/2629.Function Composition/README.md index 69feef158e06d..f65b1251e17ce 100644 --- a/solution/2600-2699/2629.Function Composition/README.md +++ b/solution/2600-2699/2629.Function Composition/README.md @@ -61,14 +61,10 @@ Starting with x = 4. ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts type F = (x: number) => number; @@ -84,10 +80,6 @@ function compose(functions: F[]): F { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2629.Function Composition/README_EN.md b/solution/2600-2699/2629.Function Composition/README_EN.md index a1d99611138a3..4397622b639f0 100644 --- a/solution/2600-2699/2629.Function Composition/README_EN.md +++ b/solution/2600-2699/2629.Function Composition/README_EN.md @@ -57,9 +57,9 @@ The composition of zero functions is the identity function ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type F = (x: number) => number; @@ -76,10 +76,6 @@ function compose(functions: F[]): F { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2630.Memoize II/README.md b/solution/2600-2699/2630.Memoize II/README.md index b377f81e83013..8c5a1a9e9a6f2 100644 --- a/solution/2600-2699/2630.Memoize II/README.md +++ b/solution/2600-2699/2630.Memoize II/README.md @@ -67,9 +67,7 @@ fn = function (a, b) { return ({...a, ...b}); } ## 解法 - - -**方法一:双哈希表** +### 方法一:双哈希表 我们用两个哈希表,其中: @@ -82,10 +80,6 @@ fn = function (a, b) { return ({...a, ...b}); } -### **TypeScript** - - - ```ts type Fn = (...params: any) => any; @@ -121,10 +115,6 @@ function memoize(fn: Fn): Fn { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2630.Memoize II/README_EN.md b/solution/2600-2699/2630.Memoize II/README_EN.md index 7db3a3279b84e..6c8e58aca971c 100644 --- a/solution/2600-2699/2630.Memoize II/README_EN.md +++ b/solution/2600-2699/2630.Memoize II/README_EN.md @@ -63,9 +63,9 @@ Merging two empty objects will always result in an empty object. The 2nd and 3rd ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type Fn = (...params: any) => any; @@ -102,10 +102,6 @@ function memoize(fn: Fn): Fn { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2631.Group By/README.md b/solution/2600-2699/2631.Group By/README.md index 4dbec0b2840e7..4c45c0954d229 100644 --- a/solution/2600-2699/2631.Group By/README.md +++ b/solution/2600-2699/2631.Group By/README.md @@ -94,14 +94,10 @@ fn = function (n) { ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts declare global { interface Array { @@ -126,10 +122,6 @@ Array.prototype.groupBy = function (fn) { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2631.Group By/README_EN.md b/solution/2600-2699/2631.Group By/README_EN.md index 8f2d2e8554b69..e1177e33ef2a8 100644 --- a/solution/2600-2699/2631.Group By/README_EN.md +++ b/solution/2600-2699/2631.Group By/README_EN.md @@ -90,9 +90,9 @@ The selector function splits the array by whether each number is greater than 5. ## Solutions - +### Solution 1 -### **TypeScript** + ```ts declare global { @@ -118,10 +118,6 @@ Array.prototype.groupBy = function (fn) { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2632.Curry/README.md b/solution/2600-2699/2632.Curry/README.md index f5df8a13c5f27..4db7695f3b0d5 100644 --- a/solution/2600-2699/2632.Curry/README.md +++ b/solution/2600-2699/2632.Curry/README.md @@ -78,14 +78,10 @@ curriedLife() === 42 ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function curry(fn: Function): Function { return function curried(...args) { @@ -103,10 +99,6 @@ function curry(fn: Function): Function { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2632.Curry/README_EN.md b/solution/2600-2699/2632.Curry/README_EN.md index 4c1602b42726e..adc14e6c47a2f 100644 --- a/solution/2600-2699/2632.Curry/README_EN.md +++ b/solution/2600-2699/2632.Curry/README_EN.md @@ -74,9 +74,9 @@ curriedLife() === 42 ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function curry(fn: Function): Function { @@ -95,10 +95,6 @@ function curry(fn: Function): Function { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2633.Convert Object to JSON String/README.md b/solution/2600-2699/2633.Convert Object to JSON String/README.md index d10dc6f806349..e42b6621fe000 100644 --- a/solution/2600-2699/2633.Convert Object to JSON String/README.md +++ b/solution/2600-2699/2633.Convert Object to JSON String/README.md @@ -60,14 +60,10 @@ JSON 的基本类型是字符串、数字型、布尔值和 null。 ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function jsonStringify(object: any): string { if (object === null) { @@ -91,10 +87,6 @@ function jsonStringify(object: any): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2633.Convert Object to JSON String/README_EN.md b/solution/2600-2699/2633.Convert Object to JSON String/README_EN.md index 071e5fba5cdfc..83ec6029d5edc 100644 --- a/solution/2600-2699/2633.Convert Object to JSON String/README_EN.md +++ b/solution/2600-2699/2633.Convert Object to JSON String/README_EN.md @@ -56,9 +56,9 @@ Primitive types are valid inputs. ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function jsonStringify(object: any): string { @@ -83,10 +83,6 @@ function jsonStringify(object: any): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2634.Filter Elements from Array/README.md b/solution/2600-2699/2634.Filter Elements from Array/README.md index cd79ba6f85895..d4b1ea992ac87 100644 --- a/solution/2600-2699/2634.Filter Elements from Array/README.md +++ b/solution/2600-2699/2634.Filter Elements from Array/README.md @@ -60,9 +60,7 @@ const newArray = filter(arr, fn); // [20, 30] ## 解法 - - -**方法一:遍历** +### 方法一:遍历 我们遍历数组 $arr$,对于每个元素 $arr[i]$,如果 $fn(arr[i], i)$ 为真,则将其加入答案数组中。最后返回答案数组即可。 @@ -70,10 +68,6 @@ const newArray = filter(arr, fn); // [20, 30] -### **TypeScript** - - - ```ts function filter(arr: number[], fn: (n: number, i: number) => any): number[] { const ans: number[] = []; @@ -86,10 +80,6 @@ function filter(arr: number[], fn: (n: number, i: number) => any): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2634.Filter Elements from Array/README_EN.md b/solution/2600-2699/2634.Filter Elements from Array/README_EN.md index 7fc15af887e15..815e85bcb5b05 100644 --- a/solution/2600-2699/2634.Filter Elements from Array/README_EN.md +++ b/solution/2600-2699/2634.Filter Elements from Array/README_EN.md @@ -56,7 +56,7 @@ Falsey values such as 0 should be filtered out ## Solutions -**Solution 1: Traversal** +### Solution 1: Traversal We traverse the array $arr$ and for each element $arr[i]$, if $fn(arr[i], i)$ is true, we add it to the answer array. Finally, we return the answer array. @@ -64,8 +64,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $arr$. Ignor -### **TypeScript** - ```ts function filter(arr: number[], fn: (n: number, i: number) => any): number[] { const ans: number[] = []; @@ -78,10 +76,6 @@ function filter(arr: number[], fn: (n: number, i: number) => any): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2635.Apply Transform Over Each Element in Array/README.md b/solution/2600-2699/2635.Apply Transform Over Each Element in Array/README.md index ab8acc73f6708..c191be1a23147 100644 --- a/solution/2600-2699/2635.Apply Transform Over Each Element in Array/README.md +++ b/solution/2600-2699/2635.Apply Transform Over Each Element in Array/README.md @@ -53,9 +53,7 @@ const newArray = map(arr, plusone); // [2,3,4] ## 解法 - - -**方法一:遍历** +### 方法一:遍历 我们遍历数组 $arr$,对于每个元素 $arr[i]$,将其替换为 $fn(arr[i], i)$。最后返回数组 $arr$ 即可。 @@ -63,10 +61,6 @@ const newArray = map(arr, plusone); // [2,3,4] -### **TypeScript** - - - ```ts function map(arr: number[], fn: (n: number, i: number) => number): number[] { for (let i = 0; i < arr.length; ++i) { @@ -76,10 +70,6 @@ function map(arr: number[], fn: (n: number, i: number) => number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2635.Apply Transform Over Each Element in Array/README_EN.md b/solution/2600-2699/2635.Apply Transform Over Each Element in Array/README_EN.md index 4377e1070dd7a..bef6eda5918b1 100644 --- a/solution/2600-2699/2635.Apply Transform Over Each Element in Array/README_EN.md +++ b/solution/2600-2699/2635.Apply Transform Over Each Element in Array/README_EN.md @@ -48,7 +48,7 @@ The function increases each value in the array by one. ## Solutions -**Solution 1: traversal** +### Solution 1: traversal We traverse the array $arr$, for each element $arr[i]$, replace it with $fn(arr[i], i)$. Finally, return the array $arr$. @@ -56,8 +56,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $arr$. The s -### **TypeScript** - ```ts function map(arr: number[], fn: (n: number, i: number) => number): number[] { for (let i = 0; i < arr.length; ++i) { @@ -67,10 +65,6 @@ function map(arr: number[], fn: (n: number, i: number) => number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2636.Promise Pool/README.md b/solution/2600-2699/2636.Promise Pool/README.md index a794a63c6e2cc..960f738486621 100644 --- a/solution/2600-2699/2636.Promise Pool/README.md +++ b/solution/2600-2699/2636.Promise Pool/README.md @@ -82,14 +82,10 @@ n = 1 ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts type F = () => Promise; @@ -106,10 +102,6 @@ function promisePool(functions: F[], n: number): Promise { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2636.Promise Pool/README_EN.md b/solution/2600-2699/2636.Promise Pool/README_EN.md index d9bf7f8723e29..b7255914ec284 100644 --- a/solution/2600-2699/2636.Promise Pool/README_EN.md +++ b/solution/2600-2699/2636.Promise Pool/README_EN.md @@ -83,9 +83,9 @@ At t=900, the 3rd function resolves. Pool size is 0 so the returned promise reso ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type F = () => Promise; @@ -103,10 +103,6 @@ function promisePool(functions: F[], n: number): Promise { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2637.Promise Time Limit/README.md b/solution/2600-2699/2637.Promise Time Limit/README.md index 4c84ba9f234ba..5377db123b4fe 100644 --- a/solution/2600-2699/2637.Promise Time Limit/README.md +++ b/solution/2600-2699/2637.Promise Time Limit/README.md @@ -98,14 +98,10 @@ t = 1000 ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts type Fn = (...params: any[]) => Promise; @@ -124,10 +120,6 @@ function timeLimit(fn: Fn, t: number): Fn { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2637.Promise Time Limit/README_EN.md b/solution/2600-2699/2637.Promise Time Limit/README_EN.md index 3ca693fb2d0a1..a729ff7229501 100644 --- a/solution/2600-2699/2637.Promise Time Limit/README_EN.md +++ b/solution/2600-2699/2637.Promise Time Limit/README_EN.md @@ -94,9 +94,9 @@ The function immediately throws an error. ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type Fn = (...params: any[]) => Promise; @@ -116,10 +116,6 @@ function timeLimit(fn: Fn, t: number): Fn { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2638.Count the Number of K-Free Subsets/README.md b/solution/2600-2699/2638.Count the Number of K-Free Subsets/README.md index 2e959e0338501..1f15cff2db666 100644 --- a/solution/2600-2699/2638.Count the Number of K-Free Subsets/README.md +++ b/solution/2600-2699/2638.Count the Number of K-Free Subsets/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:分组 + 动态规划** +### 方法一:分组 + 动态规划 我们先将数组 $nums$ 按照升序排序,然后将数组中的元素按照模 $k$ 分组,即 $nums[i] \bmod k$ 相同的元素放在同一组中。那么对于任意两个不同组的元素,它们的差值的绝对值一定不等于 $k$。因此,我们可以求出每一组的子集个数,然后将每一组的子集个数相乘即可得到答案。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def countTheNumOfKFreeSubsets(self, nums: List[int], k: int) -> int: @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long countTheNumOfKFreeSubsets(int[] nums, int k) { @@ -124,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +143,6 @@ public: }; ``` -### **Go** - ```go func countTheNumOfKFreeSubsets(nums []int, k int) int64 { sort.Ints(nums) @@ -183,8 +169,6 @@ func countTheNumOfKFreeSubsets(nums []int, k int) int64 { } ``` -### **TypeScript** - ```ts function countTheNumOfKFreeSubsets(nums: number[], k: number): number { nums.sort((a, b) => a - b); @@ -214,10 +198,6 @@ function countTheNumOfKFreeSubsets(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2638.Count the Number of K-Free Subsets/README_EN.md b/solution/2600-2699/2638.Count the Number of K-Free Subsets/README_EN.md index e44b908d4eff2..24952289138cc 100644 --- a/solution/2600-2699/2638.Count the Number of K-Free Subsets/README_EN.md +++ b/solution/2600-2699/2638.Count the Number of K-Free Subsets/README_EN.md @@ -48,7 +48,7 @@ ## Solutions -**Solution 1: Grouping + Dynamic Programming** +### Solution 1: Grouping + Dynamic Programming First, sort the array $nums$ in ascending order, and then group the elements in the array according to the remainder modulo $k$, that is, the elements $nums[i] \bmod k$ with the same remainder are in the same group. Then for any two elements in different groups, their absolute difference is not equal to $k$. Therefore, we can obtain the number of subsets in each group, and then multiply the number of subsets in each group to obtain the answer. @@ -60,8 +60,6 @@ The time complexity is $O(n \times \log n)$ and the space complexity is $O(n)$, -### **Python3** - ```python class Solution: def countTheNumOfKFreeSubsets(self, nums: List[int], k: int) -> int: @@ -84,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long countTheNumOfKFreeSubsets(int[] nums, int k) { @@ -114,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +139,6 @@ public: }; ``` -### **Go** - ```go func countTheNumOfKFreeSubsets(nums []int, k int) int64 { sort.Ints(nums) @@ -173,8 +165,6 @@ func countTheNumOfKFreeSubsets(nums []int, k int) int64 { } ``` -### **TypeScript** - ```ts function countTheNumOfKFreeSubsets(nums: number[], k: number): number { nums.sort((a, b) => a - b); @@ -204,10 +194,6 @@ function countTheNumOfKFreeSubsets(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2639.Find the Width of Columns of a Grid/README.md b/solution/2600-2699/2639.Find the Width of Columns of a Grid/README.md index 082db69afa548..6d3d5f9db90de 100644 --- a/solution/2600-2699/2639.Find the Width of Columns of a Grid/README.md +++ b/solution/2600-2699/2639.Find the Width of Columns of a Grid/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们记矩阵的列数为 $n$,创建一个长度为 $n$ 的数组 $ans$,其中 $ans[i]$ 表示第 $i$ 列的宽度。初始时,$ans[i]$ 的值均为 $0$。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def findColumnWidth(self, grid: List[List[int]]) -> List[int]: @@ -77,16 +71,6 @@ class Solution: return ans ``` -```python -class Solution: - def findColumnWidth(self, grid: List[List[int]]) -> List[int]: - return [max(len(str(x)) for x in col) for col in zip(*grid)] -``` - -### **Java** - - - ```java class Solution { public int[] findColumnWidth(int[][] grid) { @@ -103,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +104,6 @@ public: }; ``` -### **Go** - ```go func findColumnWidth(grid [][]int) []int { ans := make([]int, len(grid[0])) @@ -137,8 +117,6 @@ func findColumnWidth(grid [][]int) []int { } ``` -### **TypeScript** - ```ts function findColumnWidth(grid: number[][]): number[] { const n = grid[0].length; @@ -153,8 +131,6 @@ function findColumnWidth(grid: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn find_column_width(grid: Vec>) -> Vec { @@ -172,10 +148,18 @@ impl Solution { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def findColumnWidth(self, grid: List[List[int]]) -> List[int]: + return [max(len(str(x)) for x in col) for col in zip(*grid)] ``` + + diff --git a/solution/2600-2699/2639.Find the Width of Columns of a Grid/README_EN.md b/solution/2600-2699/2639.Find the Width of Columns of a Grid/README_EN.md index 7d3012bbf9bbb..c3e0837e8cbb0 100644 --- a/solution/2600-2699/2639.Find the Width of Columns of a Grid/README_EN.md +++ b/solution/2600-2699/2639.Find the Width of Columns of a Grid/README_EN.md @@ -46,9 +46,9 @@ In the 2nd column, both 12 and -2 are of length 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,14 +61,6 @@ class Solution: return ans ``` -```python -class Solution: - def findColumnWidth(self, grid: List[List[int]]) -> List[int]: - return [max(len(str(x)) for x in col) for col in zip(*grid)] -``` - -### **Java** - ```java class Solution { public int[] findColumnWidth(int[][] grid) { @@ -85,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +94,6 @@ public: }; ``` -### **Go** - ```go func findColumnWidth(grid [][]int) []int { ans := make([]int, len(grid[0])) @@ -119,8 +107,6 @@ func findColumnWidth(grid [][]int) []int { } ``` -### **TypeScript** - ```ts function findColumnWidth(grid: number[][]): number[] { const n = grid[0].length; @@ -135,8 +121,6 @@ function findColumnWidth(grid: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn find_column_width(grid: Vec>) -> Vec { @@ -154,10 +138,18 @@ impl Solution { } ``` -### **...** + + +### Solution 2 -``` + +```python +class Solution: + def findColumnWidth(self, grid: List[List[int]]) -> List[int]: + return [max(len(str(x)) for x in col) for col in zip(*grid)] ``` + + diff --git a/solution/2600-2699/2640.Find the Score of All Prefixes of an Array/README.md b/solution/2600-2699/2640.Find the Score of All Prefixes of an Array/README.md index b2e04611b6079..48174f9f94f8f 100644 --- a/solution/2600-2699/2640.Find the Score of All Prefixes of an Array/README.md +++ b/solution/2600-2699/2640.Find the Score of All Prefixes of an Array/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:前缀和** +### 方法一:前缀和 我们用变量 $mx$ 记录数组 $nums$ 中前 $i$ 个元素的最大值,用数组 $ans[i]$ 记录数组 $nums$ 中前 $i$ 个元素的分数。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def findPrefixScore(self, nums: List[int]) -> List[int]: @@ -82,10 +76,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long[] findPrefixScore(int[] nums) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func findPrefixScore(nums []int) []int64 { n := len(nums) @@ -137,8 +123,6 @@ func findPrefixScore(nums []int) []int64 { } ``` -### **TypeScript** - ```ts function findPrefixScore(nums: number[]): number[] { const n = nums.length; @@ -152,10 +136,6 @@ function findPrefixScore(nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2640.Find the Score of All Prefixes of an Array/README_EN.md b/solution/2600-2699/2640.Find the Score of All Prefixes of an Array/README_EN.md index 3260dc127da88..55cf2f117a73c 100644 --- a/solution/2600-2699/2640.Find the Score of All Prefixes of an Array/README_EN.md +++ b/solution/2600-2699/2640.Find the Score of All Prefixes of an Array/README_EN.md @@ -52,9 +52,9 @@ For the prefix [1, 1, 2, 4, 8, 16], the conversion array is [2, 2, 4, 8, 16, 32] ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long[] findPrefixScore(int[] nums) { @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +99,6 @@ public: }; ``` -### **Go** - ```go func findPrefixScore(nums []int) []int64 { n := len(nums) @@ -121,8 +115,6 @@ func findPrefixScore(nums []int) []int64 { } ``` -### **TypeScript** - ```ts function findPrefixScore(nums: number[]): number[] { const n = nums.length; @@ -136,10 +128,6 @@ function findPrefixScore(nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2641.Cousins in Binary Tree II/README.md b/solution/2600-2699/2641.Cousins in Binary Tree II/README.md index 1ff022d29964a..b49ef9be27ced 100644 --- a/solution/2600-2699/2641.Cousins in Binary Tree II/README.md +++ b/solution/2600-2699/2641.Cousins in Binary Tree II/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:两次 DFS** +### 方法一:两次 DFS 我们用一个数组 $s$ 记录二叉树每一层的节点值之和,其中 $s[i]$ 表示第 $i$ 层的节点值之和。 @@ -66,22 +64,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。 -**方法二:BFS** - -我们先将根节点的值更新为 $0$,用一个队列 $q$ 来存储每一层的所有节点,初始时将根节点入队。 - -然后遍历队列,计算每一层的所有子节点的值之和 $s$,然后计算每个子节点及其兄弟节点的值之和 $t$,然后更新每个子节点的值为 $s - t$。 - -遍历结束后,返回根节点即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。 - -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -120,43 +104,6 @@ class Solution: return root ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: - root.val = 0 - q = [root] - while q: - s = 0 - p = q - q = [] - for node in p: - if node.left: - q.append(node.left) - s += node.left.val - if node.right: - q.append(node.right) - s += node.right.val - for node in p: - t = (node.left.val if node.left else 0) + ( - node.right.val if node.right else 0 - ) - if node.left: - node.left.val = s - t - if node.right: - node.right.val = s - t - return root -``` - -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -213,58 +160,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public TreeNode replaceValueInTree(TreeNode root) { - root.val = 0; - List q = List.of(root); - while (!q.isEmpty()) { - List p = q; - q = new ArrayList<>(); - int s = 0; - for (TreeNode node : p) { - if (node.left != null) { - q.add(node.left); - s += node.left.val; - } - if (node.right != null) { - q.add(node.right); - s += node.right.val; - } - } - for (TreeNode node : p) { - int t = (node.left == null ? 0 : node.left.val) - + (node.right == null ? 0 : node.right.val); - if (node.left != null) { - node.left.val = s - t; - } - if (node.right != null) { - node.right.val = s - t; - } - } - } - return root; - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -315,55 +210,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* replaceValueInTree(TreeNode* root) { - root->val = 0; - vector q; - q.emplace_back(root); - while (!q.empty()) { - vector p = q; - q.clear(); - int s = 0; - for (TreeNode* node : p) { - if (node->left) { - q.emplace_back(node->left); - s += node->left->val; - } - if (node->right) { - q.emplace_back(node->right); - s += node->right->val; - } - } - for (TreeNode* node : p) { - int t = (node->left ? node->left->val : 0) + (node->right ? node->right->val : 0); - if (node->left) { - node->left->val = s - t; - } - if (node->right) { - node->right->val = s - t; - } - } - } - return root; - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -415,54 +261,6 @@ func replaceValueInTree(root *TreeNode) *TreeNode { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func replaceValueInTree(root *TreeNode) *TreeNode { - root.Val = 0 - q := []*TreeNode{root} - for len(q) > 0 { - p := q - q = []*TreeNode{} - s := 0 - for _, node := range p { - if node.Left != nil { - q = append(q, node.Left) - s += node.Left.Val - } - if node.Right != nil { - q = append(q, node.Right) - s += node.Right.Val - } - } - for _, node := range p { - t := 0 - if node.Left != nil { - t += node.Left.Val - } - if node.Right != nil { - t += node.Right.Val - } - if node.Left != nil { - node.Left.Val = s - t - } - if node.Right != nil { - node.Right.Val = s - t - } - } - } - return root -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -512,6 +310,196 @@ function replaceValueInTree(root: TreeNode | null): TreeNode | null { } ``` + + +### 方法二:BFS + +我们先将根节点的值更新为 $0$,用一个队列 $q$ 来存储每一层的所有节点,初始时将根节点入队。 + +然后遍历队列,计算每一层的所有子节点的值之和 $s$,然后计算每个子节点及其兄弟节点的值之和 $t$,然后更新每个子节点的值为 $s - t$。 + +遍历结束后,返回根节点即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点数。 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + root.val = 0 + q = [root] + while q: + s = 0 + p = q + q = [] + for node in p: + if node.left: + q.append(node.left) + s += node.left.val + if node.right: + q.append(node.right) + s += node.right.val + for node in p: + t = (node.left.val if node.left else 0) + ( + node.right.val if node.right else 0 + ) + if node.left: + node.left.val = s - t + if node.right: + node.right.val = s - t + return root +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode replaceValueInTree(TreeNode root) { + root.val = 0; + List q = List.of(root); + while (!q.isEmpty()) { + List p = q; + q = new ArrayList<>(); + int s = 0; + for (TreeNode node : p) { + if (node.left != null) { + q.add(node.left); + s += node.left.val; + } + if (node.right != null) { + q.add(node.right); + s += node.right.val; + } + } + for (TreeNode node : p) { + int t = (node.left == null ? 0 : node.left.val) + + (node.right == null ? 0 : node.right.val); + if (node.left != null) { + node.left.val = s - t; + } + if (node.right != null) { + node.right.val = s - t; + } + } + } + return root; + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* replaceValueInTree(TreeNode* root) { + root->val = 0; + vector q; + q.emplace_back(root); + while (!q.empty()) { + vector p = q; + q.clear(); + int s = 0; + for (TreeNode* node : p) { + if (node->left) { + q.emplace_back(node->left); + s += node->left->val; + } + if (node->right) { + q.emplace_back(node->right); + s += node->right->val; + } + } + for (TreeNode* node : p) { + int t = (node->left ? node->left->val : 0) + (node->right ? node->right->val : 0); + if (node->left) { + node->left->val = s - t; + } + if (node->right) { + node->right->val = s - t; + } + } + } + return root; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func replaceValueInTree(root *TreeNode) *TreeNode { + root.Val = 0 + q := []*TreeNode{root} + for len(q) > 0 { + p := q + q = []*TreeNode{} + s := 0 + for _, node := range p { + if node.Left != nil { + q = append(q, node.Left) + s += node.Left.Val + } + if node.Right != nil { + q = append(q, node.Right) + s += node.Right.Val + } + } + for _, node := range p { + t := 0 + if node.Left != nil { + t += node.Left.Val + } + if node.Right != nil { + t += node.Right.Val + } + if node.Left != nil { + node.Left.Val = s - t + } + if node.Right != nil { + node.Right.Val = s - t + } + } + } + return root +} +``` + ```ts /** * Definition for a binary tree node. @@ -558,10 +546,6 @@ function replaceValueInTree(root: TreeNode | null): TreeNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2641.Cousins in Binary Tree II/README_EN.md b/solution/2600-2699/2641.Cousins in Binary Tree II/README_EN.md index c5527fee23250..79b8306ed0780 100644 --- a/solution/2600-2699/2641.Cousins in Binary Tree II/README_EN.md +++ b/solution/2600-2699/2641.Cousins in Binary Tree II/README_EN.md @@ -48,9 +48,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -90,41 +90,6 @@ class Solution: return root ``` -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, val=0, left=None, right=None): -# self.val = val -# self.left = left -# self.right = right -class Solution: - def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: - root.val = 0 - q = [root] - while q: - s = 0 - p = q - q = [] - for node in p: - if node.left: - q.append(node.left) - s += node.left.val - if node.right: - q.append(node.right) - s += node.right.val - for node in p: - t = (node.left.val if node.left else 0) + ( - node.right.val if node.right else 0 - ) - if node.left: - node.left.val = s - t - if node.right: - node.right.val = s - t - return root -``` - -### **Java** - ```java /** * Definition for a binary tree node. @@ -181,58 +146,6 @@ class Solution { } ``` -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode() {} - * TreeNode(int val) { this.val = val; } - * TreeNode(int val, TreeNode left, TreeNode right) { - * this.val = val; - * this.left = left; - * this.right = right; - * } - * } - */ -class Solution { - public TreeNode replaceValueInTree(TreeNode root) { - root.val = 0; - List q = List.of(root); - while (!q.isEmpty()) { - List p = q; - q = new ArrayList<>(); - int s = 0; - for (TreeNode node : p) { - if (node.left != null) { - q.add(node.left); - s += node.left.val; - } - if (node.right != null) { - q.add(node.right); - s += node.right.val; - } - } - for (TreeNode node : p) { - int t = (node.left == null ? 0 : node.left.val) - + (node.right == null ? 0 : node.right.val); - if (node.left != null) { - node.left.val = s - t; - } - if (node.right != null) { - node.right.val = s - t; - } - } - } - return root; - } -} -``` - -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -283,55 +196,6 @@ public: }; ``` -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* replaceValueInTree(TreeNode* root) { - root->val = 0; - vector q; - q.emplace_back(root); - while (!q.empty()) { - vector p = q; - q.clear(); - int s = 0; - for (TreeNode* node : p) { - if (node->left) { - q.emplace_back(node->left); - s += node->left->val; - } - if (node->right) { - q.emplace_back(node->right); - s += node->right->val; - } - } - for (TreeNode* node : p) { - int t = (node->left ? node->left->val : 0) + (node->right ? node->right->val : 0); - if (node->left) { - node->left->val = s - t; - } - if (node->right) { - node->right->val = s - t; - } - } - } - return root; - } -}; -``` - -### **Go** - ```go /** * Definition for a binary tree node. @@ -383,54 +247,6 @@ func replaceValueInTree(root *TreeNode) *TreeNode { } ``` -```go -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ -func replaceValueInTree(root *TreeNode) *TreeNode { - root.Val = 0 - q := []*TreeNode{root} - for len(q) > 0 { - p := q - q = []*TreeNode{} - s := 0 - for _, node := range p { - if node.Left != nil { - q = append(q, node.Left) - s += node.Left.Val - } - if node.Right != nil { - q = append(q, node.Right) - s += node.Right.Val - } - } - for _, node := range p { - t := 0 - if node.Left != nil { - t += node.Left.Val - } - if node.Right != nil { - t += node.Right.Val - } - if node.Left != nil { - node.Left.Val = s - t - } - if node.Right != nil { - node.Right.Val = s - t - } - } - } - return root -} -``` - -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -480,6 +296,188 @@ function replaceValueInTree(root: TreeNode | null): TreeNode | null { } ``` + + +### Solution 2 + + + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def replaceValueInTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + root.val = 0 + q = [root] + while q: + s = 0 + p = q + q = [] + for node in p: + if node.left: + q.append(node.left) + s += node.left.val + if node.right: + q.append(node.right) + s += node.right.val + for node in p: + t = (node.left.val if node.left else 0) + ( + node.right.val if node.right else 0 + ) + if node.left: + node.left.val = s - t + if node.right: + node.right.val = s - t + return root +``` + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode replaceValueInTree(TreeNode root) { + root.val = 0; + List q = List.of(root); + while (!q.isEmpty()) { + List p = q; + q = new ArrayList<>(); + int s = 0; + for (TreeNode node : p) { + if (node.left != null) { + q.add(node.left); + s += node.left.val; + } + if (node.right != null) { + q.add(node.right); + s += node.right.val; + } + } + for (TreeNode node : p) { + int t = (node.left == null ? 0 : node.left.val) + + (node.right == null ? 0 : node.right.val); + if (node.left != null) { + node.left.val = s - t; + } + if (node.right != null) { + node.right.val = s - t; + } + } + } + return root; + } +} +``` + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* replaceValueInTree(TreeNode* root) { + root->val = 0; + vector q; + q.emplace_back(root); + while (!q.empty()) { + vector p = q; + q.clear(); + int s = 0; + for (TreeNode* node : p) { + if (node->left) { + q.emplace_back(node->left); + s += node->left->val; + } + if (node->right) { + q.emplace_back(node->right); + s += node->right->val; + } + } + for (TreeNode* node : p) { + int t = (node->left ? node->left->val : 0) + (node->right ? node->right->val : 0); + if (node->left) { + node->left->val = s - t; + } + if (node->right) { + node->right->val = s - t; + } + } + } + return root; + } +}; +``` + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func replaceValueInTree(root *TreeNode) *TreeNode { + root.Val = 0 + q := []*TreeNode{root} + for len(q) > 0 { + p := q + q = []*TreeNode{} + s := 0 + for _, node := range p { + if node.Left != nil { + q = append(q, node.Left) + s += node.Left.Val + } + if node.Right != nil { + q = append(q, node.Right) + s += node.Right.Val + } + } + for _, node := range p { + t := 0 + if node.Left != nil { + t += node.Left.Val + } + if node.Right != nil { + t += node.Right.Val + } + if node.Left != nil { + node.Left.Val = s - t + } + if node.Right != nil { + node.Right.Val = s - t + } + } + } + return root +} +``` + ```ts /** * Definition for a binary tree node. @@ -526,10 +524,6 @@ function replaceValueInTree(root: TreeNode | null): TreeNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2642.Design Graph With Shortest Path Calculator/README.md b/solution/2600-2699/2642.Design Graph With Shortest Path Calculator/README.md index db3b12f4cb04c..a2069213675a0 100644 --- a/solution/2600-2699/2642.Design Graph With Shortest Path Calculator/README.md +++ b/solution/2600-2699/2642.Design Graph With Shortest Path Calculator/README.md @@ -53,9 +53,7 @@ g.shortestPath(0, 3); // 返回 6 。从 0 到 3 的最短路径为 0 -> 1 -& ## 解法 - - -**方法一:Dijsktra 算法** +### 方法一:Dijsktra 算法 在初始化函数中,我们先用邻接矩阵 $g$ 存储图的边权,其中 $g_{ij}$ 表示从节点 $i$ 到节点 $j$ 的边权,如果 $i$ 和 $j$ 之间没有边,则 $g_{ij}$ 的值为 $\infty$。 @@ -67,10 +65,6 @@ g.shortestPath(0, 3); // 返回 6 。从 0 到 3 的最短路径为 0 -> 1 -& -### **Python3** - - - ```python class Graph: def __init__(self, n: int, edges: List[List[int]]): @@ -104,10 +98,6 @@ class Graph: # param_2 = obj.shortestPath(node1,node2) ``` -### **Java** - - - ```java class Graph { private int n; @@ -160,8 +150,6 @@ class Graph { */ ``` -### **C++** - ```cpp class Graph { public: @@ -212,8 +200,6 @@ private: */ ``` -### **Go** - ```go const inf = 1 << 29 @@ -275,8 +261,6 @@ func (this *Graph) ShortestPath(node1 int, node2 int) int { */ ``` -### **TypeScript** - ```ts class Graph { private g: number[][] = []; @@ -323,8 +307,6 @@ class Graph { */ ``` -### **C#** - ```cs public class Graph { private int n; @@ -384,10 +366,6 @@ public class Graph { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2642.Design Graph With Shortest Path Calculator/README_EN.md b/solution/2600-2699/2642.Design Graph With Shortest Path Calculator/README_EN.md index d81100b8ef5f5..174c1809cf1bc 100644 --- a/solution/2600-2699/2642.Design Graph With Shortest Path Calculator/README_EN.md +++ b/solution/2600-2699/2642.Design Graph With Shortest Path Calculator/README_EN.md @@ -49,9 +49,9 @@ g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -> ## Solutions - +### Solution 1 -### **Python3** + ```python class Graph: @@ -86,8 +86,6 @@ class Graph: # param_2 = obj.shortestPath(node1,node2) ``` -### **Java** - ```java class Graph { private int n; @@ -140,8 +138,6 @@ class Graph { */ ``` -### **C++** - ```cpp class Graph { public: @@ -192,8 +188,6 @@ private: */ ``` -### **Go** - ```go const inf = 1 << 29 @@ -255,8 +249,6 @@ func (this *Graph) ShortestPath(node1 int, node2 int) int { */ ``` -### **TypeScript** - ```ts class Graph { private g: number[][] = []; @@ -303,8 +295,6 @@ class Graph { */ ``` -### **C#** - ```cs public class Graph { private int n; @@ -364,10 +354,6 @@ public class Graph { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2643.Row With Maximum Ones/README.md b/solution/2600-2699/2643.Row With Maximum Ones/README.md index f7b3f6225bf8a..e16384d437873 100644 --- a/solution/2600-2699/2643.Row With Maximum Ones/README.md +++ b/solution/2600-2699/2643.Row With Maximum Ones/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们直接遍历矩阵,统计每一行中 $1$ 的个数,更新最大值和对应的行下标。注意,如果当前行的 $1$ 的个数与最大值相等,我们需要选择行下标较小的那一行。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]: @@ -75,10 +69,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] rowAndMaximumOnes(int[][] mat) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func rowAndMaximumOnes(mat [][]int) []int { ans := make([]int, 2) @@ -142,8 +128,6 @@ func rowAndMaximumOnes(mat [][]int) []int { } ``` -### **TypeScript** - ```ts function rowAndMaximumOnes(mat: number[][]): number[] { const ans: number[] = [0, 0]; @@ -158,8 +142,6 @@ function rowAndMaximumOnes(mat: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn row_and_maximum_ones(mat: Vec>) -> Vec { @@ -181,10 +163,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2643.Row With Maximum Ones/README_EN.md b/solution/2600-2699/2643.Row With Maximum Ones/README_EN.md index d741993dfc2f2..5e39f1e6b1a26 100644 --- a/solution/2600-2699/2643.Row With Maximum Ones/README_EN.md +++ b/solution/2600-2699/2643.Row With Maximum Ones/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] rowAndMaximumOnes(int[][] mat) { @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +103,6 @@ public: }; ``` -### **Go** - ```go func rowAndMaximumOnes(mat [][]int) []int { ans := make([]int, 2) @@ -127,8 +121,6 @@ func rowAndMaximumOnes(mat [][]int) []int { } ``` -### **TypeScript** - ```ts function rowAndMaximumOnes(mat: number[][]): number[] { const ans: number[] = [0, 0]; @@ -143,8 +135,6 @@ function rowAndMaximumOnes(mat: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn row_and_maximum_ones(mat: Vec>) -> Vec { @@ -166,10 +156,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2644.Find the Maximum Divisibility Score/README.md b/solution/2600-2699/2644.Find the Maximum Divisibility Score/README.md index c6ac0d076751a..11536e8fdda80 100644 --- a/solution/2600-2699/2644.Find the Maximum Divisibility Score/README.md +++ b/solution/2600-2699/2644.Find the Maximum Divisibility Score/README.md @@ -60,9 +60,7 @@ divisors[1] 的可整除性得分为 0 ,因为 nums 中没有任何数字能 ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举 $divisors$ 中的每个元素 $div$,计算 $nums$ 中有多少个元素能被 $div$ 整除,记为 $cnt$。 @@ -75,10 +73,6 @@ divisors[1] 的可整除性得分为 0 ,因为 nums 中没有任何数字能 -### **Python3** - - - ```python class Solution: def maxDivScore(self, nums: List[int], divisors: List[int]) -> int: @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxDivScore(int[] nums, int[] divisors) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go func maxDivScore(nums []int, divisors []int) int { ans, mx := divisors[0], 0 @@ -167,8 +153,6 @@ func maxDivScore(nums []int, divisors []int) int { } ``` -### **TypeScript** - ```ts function maxDivScore(nums: number[], divisors: number[]): number { let ans: number = divisors[0]; @@ -186,8 +170,6 @@ function maxDivScore(nums: number[], divisors: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_div_score(nums: Vec, divisors: Vec) -> i32 { @@ -214,10 +196,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2644.Find the Maximum Divisibility Score/README_EN.md b/solution/2600-2699/2644.Find the Maximum Divisibility Score/README_EN.md index 3dd6dee4a953e..99203e1b7a01b 100644 --- a/solution/2600-2699/2644.Find the Maximum Divisibility Score/README_EN.md +++ b/solution/2600-2699/2644.Find the Maximum Divisibility Score/README_EN.md @@ -56,9 +56,9 @@ Since divisors[0] and divisors[1] both have the maximum divisibility score, we r ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -73,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxDivScore(int[] nums, int[] divisors) { @@ -99,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +120,6 @@ public: }; ``` -### **Go** - ```go func maxDivScore(nums []int, divisors []int) int { ans, mx := divisors[0], 0 @@ -146,8 +140,6 @@ func maxDivScore(nums []int, divisors []int) int { } ``` -### **TypeScript** - ```ts function maxDivScore(nums: number[], divisors: number[]): number { let ans: number = divisors[0]; @@ -165,8 +157,6 @@ function maxDivScore(nums: number[], divisors: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn max_div_score(nums: Vec, divisors: Vec) -> i32 { @@ -193,10 +183,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2645.Minimum Additions to Make Valid String/README.md b/solution/2600-2699/2645.Minimum Additions to Make Valid String/README.md index e07a87858ab9e..9213523b46834 100644 --- a/solution/2600-2699/2645.Minimum Additions to Make Valid String/README.md +++ b/solution/2600-2699/2645.Minimum Additions to Make Valid String/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:贪心 + 双指针** +### 方法一:贪心 + 双指针 我们定义字符串 $s$ 为 `"abc"`,用指针 $i$ 和 $j$ 分别指向 $s$ 和 $word$。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def addMinimum(self, word: str) -> int: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int addMinimum(String word) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func addMinimum(word string) (ans int) { s := "abc" @@ -150,8 +136,6 @@ func addMinimum(word string) (ans int) { } ``` -### **TypeScript** - ```ts function addMinimum(word: string): number { const s: string = 'abc'; @@ -173,10 +157,6 @@ function addMinimum(word: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2645.Minimum Additions to Make Valid String/README_EN.md b/solution/2600-2699/2645.Minimum Additions to Make Valid String/README_EN.md index 396163b142074..c4dc3cf83c820 100644 --- a/solution/2600-2699/2645.Minimum Additions to Make Valid String/README_EN.md +++ b/solution/2600-2699/2645.Minimum Additions to Make Valid String/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Greedy + Two Pointers** +### Solution 1: Greedy + Two Pointers We define the string $s$ as `"abc"`, and use pointers $i$ and $j$ to point to $s$ and $word$ respectively. @@ -57,8 +57,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string $word$. The -### **Python3** - ```python class Solution: def addMinimum(self, word: str) -> int: @@ -76,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int addMinimum(String word) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +115,6 @@ public: }; ``` -### **Go** - ```go func addMinimum(word string) (ans int) { s := "abc" @@ -143,8 +135,6 @@ func addMinimum(word string) (ans int) { } ``` -### **TypeScript** - ```ts function addMinimum(word: string): number { const s: string = 'abc'; @@ -166,10 +156,6 @@ function addMinimum(word: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2646.Minimize the Total Price of the Trips/README.md b/solution/2600-2699/2646.Minimize the Total Price of the Trips/README.md index 3e952f9c08cc1..1ac0fd03fcce0 100644 --- a/solution/2600-2699/2646.Minimize the Total Price of the Trips/README.md +++ b/solution/2600-2699/2646.Minimize the Total Price of the Trips/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:树形 DP** +### 方法一:树形 DP 我们可以统计每一次旅行经过的节点,记录在数组 $cnt$ 中,其中 $cnt[i]$ 表示所有旅行中经过节点 $i$ 的次数。我们设计一个函数 $dfs(i, fa, k)$,表示从节点 $i$ 开始搜索,最终到达节点 $k$,过程中记录所有经过的节点。其中 $fa$ 表示节点 $i$ 的父节点。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def minimumTotalPrice( @@ -117,10 +111,6 @@ class Solution: return min(dfs2(0, -1)) ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -180,8 +170,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -234,8 +222,6 @@ public: }; ``` -### **Go** - ```go func minimumTotalPrice(n int, edges [][]int, price []int, trips [][]int) int { g := make([][]int, n) @@ -287,8 +273,6 @@ func minimumTotalPrice(n int, edges [][]int, price []int, trips [][]int) int { } ``` -### **TypeScript** - ```ts function minimumTotalPrice( n: number, @@ -341,10 +325,6 @@ function minimumTotalPrice( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2646.Minimize the Total Price of the Trips/README_EN.md b/solution/2600-2699/2646.Minimize the Total Price of the Trips/README_EN.md index bd229edd329cc..6271b87db1b13 100644 --- a/solution/2600-2699/2646.Minimize the Total Price of the Trips/README_EN.md +++ b/solution/2600-2699/2646.Minimize the Total Price of the Trips/README_EN.md @@ -57,9 +57,9 @@ The total price sum of all trips is 1. It can be proven, that 1 is the minimum a ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -95,8 +95,6 @@ class Solution: return min(dfs2(0, -1)) ``` -### **Java** - ```java class Solution { private List[] g; @@ -156,8 +154,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -210,8 +206,6 @@ public: }; ``` -### **Go** - ```go func minimumTotalPrice(n int, edges [][]int, price []int, trips [][]int) int { g := make([][]int, n) @@ -263,8 +257,6 @@ func minimumTotalPrice(n int, edges [][]int, price []int, trips [][]int) int { } ``` -### **TypeScript** - ```ts function minimumTotalPrice( n: number, @@ -317,10 +309,6 @@ function minimumTotalPrice( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2647.Color the Triangle Red/README.md b/solution/2600-2699/2647.Color the Triangle Red/README.md index ad20e0d80b4da..ad3575a614233 100644 --- a/solution/2600-2699/2647.Color the Triangle Red/README.md +++ b/solution/2600-2699/2647.Color the Triangle Red/README.md @@ -70,9 +70,7 @@ ## 解法 - - -**方法一:找规律** +### 方法一:找规律 我们画图观察,可以发现,第一行只有一个三角形,一定要涂色,而从最后一行开始,到第二行结束,每四行的涂色方案是一样的: @@ -91,10 +89,6 @@ -### **Python3** - - - ```python class Solution: def colorRed(self, n: int) -> List[List[int]]: @@ -115,10 +109,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] colorRed(int n) { @@ -144,8 +134,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -172,8 +160,6 @@ public: }; ``` -### **Go** - ```go func colorRed(n int) (ans [][]int) { ans = append(ans, []int{1, 1}) @@ -196,8 +182,6 @@ func colorRed(n int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function colorRed(n: number): number[][] { const ans: number[][] = [[1, 1]]; @@ -220,10 +204,6 @@ function colorRed(n: number): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2647.Color the Triangle Red/README_EN.md b/solution/2600-2699/2647.Color the Triangle Red/README_EN.md index 8530be838e134..230b81fdeca5d 100644 --- a/solution/2600-2699/2647.Color the Triangle Red/README_EN.md +++ b/solution/2600-2699/2647.Color the Triangle Red/README_EN.md @@ -67,7 +67,7 @@ It can be shown that choosing any 2 triangles and running the algorithm will not ## Solutions -**Solution 1: Find the Pattern** +### Solution 1: Find the Pattern We draw a graph to observe, and we can find that the first row only has one triangle and must be colored, and from the last row to the second row, the coloring scheme of every four rows is the same: @@ -86,8 +86,6 @@ The time complexity is $(n^2)$, where $n$ is the parameter given in the problem. -### **Python3** - ```python class Solution: def colorRed(self, n: int) -> List[List[int]]: @@ -108,8 +106,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] colorRed(int n) { @@ -135,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +157,6 @@ public: }; ``` -### **Go** - ```go func colorRed(n int) (ans [][]int) { ans = append(ans, []int{1, 1}) @@ -187,8 +179,6 @@ func colorRed(n int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function colorRed(n: number): number[][] { const ans: number[][] = [[1, 1]]; @@ -211,10 +201,6 @@ function colorRed(n: number): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2648.Generate Fibonacci Sequence/README.md b/solution/2600-2699/2648.Generate Fibonacci Sequence/README.md index a90177d1bc8b4..63c6da8f4d6e6 100644 --- a/solution/2600-2699/2648.Generate Fibonacci Sequence/README.md +++ b/solution/2600-2699/2648.Generate Fibonacci Sequence/README.md @@ -46,12 +46,10 @@ gen.next().value; // 3 ## 解法 - +### 方法一 -### **TypeScript** - ```ts function* fibGenerator(): Generator { let a = 0; @@ -69,10 +67,6 @@ function* fibGenerator(): Generator { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2648.Generate Fibonacci Sequence/README_EN.md b/solution/2600-2699/2648.Generate Fibonacci Sequence/README_EN.md index e874b8f41c7f9..5763f624a3381 100644 --- a/solution/2600-2699/2648.Generate Fibonacci Sequence/README_EN.md +++ b/solution/2600-2699/2648.Generate Fibonacci Sequence/README_EN.md @@ -42,9 +42,9 @@ gen.next().value; // 3 ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function* fibGenerator(): Generator { @@ -63,10 +63,6 @@ function* fibGenerator(): Generator { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2649.Nested Array Generator/README.md b/solution/2600-2699/2649.Nested Array Generator/README.md index dbdea32d7c5d5..38a2480282f6c 100644 --- a/solution/2600-2699/2649.Nested Array Generator/README.md +++ b/solution/2600-2699/2649.Nested Array Generator/README.md @@ -47,12 +47,10 @@ generator.next().done; // true ## 解法 - +### 方法一 -### **TypeScript** - ```ts type MultidimensionalArray = (MultidimensionalArray | number)[]; @@ -74,10 +72,6 @@ function* inorderTraversal(arr: MultidimensionalArray): Generator + + diff --git a/solution/2600-2699/2649.Nested Array Generator/README_EN.md b/solution/2600-2699/2649.Nested Array Generator/README_EN.md index 0dc7628ab367d..c141526e1fd43 100644 --- a/solution/2600-2699/2649.Nested Array Generator/README_EN.md +++ b/solution/2600-2699/2649.Nested Array Generator/README_EN.md @@ -46,9 +46,9 @@ generator.next().done; // true ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type MultidimensionalArray = (MultidimensionalArray | number)[]; @@ -71,10 +71,6 @@ function* inorderTraversal(arr: MultidimensionalArray): Generator + + diff --git a/solution/2600-2699/2650.Design Cancellable Function/README.md b/solution/2600-2699/2650.Design Cancellable Function/README.md index 882706b93eee8..9d6b279b18c8b 100644 --- a/solution/2600-2699/2650.Design Cancellable Function/README.md +++ b/solution/2600-2699/2650.Design Cancellable Function/README.md @@ -146,12 +146,10 @@ cancelledAt = null ## 解法 - +### 方法一 -### **TypeScript** - ```ts function cancellable(generator: Generator, T, unknown>): [() => void, Promise] { let cancel: () => void = () => {}; @@ -187,10 +185,6 @@ function cancellable(generator: Generator, T, unknown>): [() => */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2650.Design Cancellable Function/README_EN.md b/solution/2600-2699/2650.Design Cancellable Function/README_EN.md index e001c1de2b1da..2cb6607c298d8 100644 --- a/solution/2600-2699/2650.Design Cancellable Function/README_EN.md +++ b/solution/2600-2699/2650.Design Cancellable Function/README_EN.md @@ -142,9 +142,9 @@ The first yielded promise immediately rejects. This error is caught. Because the ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function cancellable(generator: Generator, T, unknown>): [() => void, Promise] { @@ -181,10 +181,6 @@ function cancellable(generator: Generator, T, unknown>): [() => */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2651.Calculate Delayed Arrival Time/README.md b/solution/2600-2699/2651.Calculate Delayed Arrival Time/README.md index c0343220ae4e5..e60dfb57780da 100644 --- a/solution/2600-2699/2651.Calculate Delayed Arrival Time/README.md +++ b/solution/2600-2699/2651.Calculate Delayed Arrival Time/README.md @@ -38,9 +38,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 我们直接计算列车实际到站的时间,即为 $arrivalTime + delayedTime$,但是由于时间采用 24 小时制,所以我们需要对结果取模,即 $(arrivalTime + delayedTime) \bmod 24$。 @@ -48,20 +46,12 @@ -### **Python3** - - - ```python class Solution: def findDelayedArrivalTime(self, arrivalTime: int, delayedTime: int) -> int: return (arrivalTime + delayedTime) % 24 ``` -### **Java** - - - ```java class Solution { public int findDelayedArrivalTime(int arrivalTime, int delayedTime) { @@ -70,8 +60,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -81,24 +69,18 @@ public: }; ``` -### **Go** - ```go func findDelayedArrivalTime(arrivalTime int, delayedTime int) int { return (arrivalTime + delayedTime) % 24 } ``` -### **TypeScript** - ```ts function findDelayedArrivalTime(arrivalTime: number, delayedTime: number): number { return (arrivalTime + delayedTime) % 24; } ``` -### **Rust** - ```rust impl Solution { pub fn find_delayed_arrival_time(arrival_time: i32, delayed_time: i32) -> i32 { @@ -107,10 +89,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2651.Calculate Delayed Arrival Time/README_EN.md b/solution/2600-2699/2651.Calculate Delayed Arrival Time/README_EN.md index 553c7ee301088..30f9e6dc8c9b3 100644 --- a/solution/2600-2699/2651.Calculate Delayed Arrival Time/README_EN.md +++ b/solution/2600-2699/2651.Calculate Delayed Arrival Time/README_EN.md @@ -37,9 +37,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -47,8 +47,6 @@ class Solution: return (arrivalTime + delayedTime) % 24 ``` -### **Java** - ```java class Solution { public int findDelayedArrivalTime(int arrivalTime, int delayedTime) { @@ -57,8 +55,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -68,24 +64,18 @@ public: }; ``` -### **Go** - ```go func findDelayedArrivalTime(arrivalTime int, delayedTime int) int { return (arrivalTime + delayedTime) % 24 } ``` -### **TypeScript** - ```ts function findDelayedArrivalTime(arrivalTime: number, delayedTime: number): number { return (arrivalTime + delayedTime) % 24; } ``` -### **Rust** - ```rust impl Solution { pub fn find_delayed_arrival_time(arrival_time: i32, delayed_time: i32) -> i32 { @@ -94,10 +84,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2652.Sum Multiples/README.md b/solution/2600-2699/2652.Sum Multiples/README.md index 3ad019390dddc..401fd6c3281a8 100644 --- a/solution/2600-2699/2652.Sum Multiples/README.md +++ b/solution/2600-2699/2652.Sum Multiples/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们直接枚举 $[1,..n]$ 中的每一个数 $x$,如果 $x$ 能被 $3$, $5$, $7$ 整除,那么就将 $x$ 累加到答案中。 @@ -54,44 +52,14 @@ 时间复杂度 $O(n)$,其中 $n$ 为题目给定的整数。空间复杂度 $O(1)$。 -**方法二:数学(容斥原理)** - -我们定义函数 $f(x)$ 表示 $[1,..n]$ 中能被 $x$ 整除的数之和,那么一共有 $m = \left\lfloor \frac{n}{x} \right\rfloor$ 个数能被 $x$ 整除,这些数字分别为 $x$, $2x$, $3x$, $\cdots$, $mx$,构成一个等差数列,首项为 $x$,末项为 $mx$,项数为 $m$,因此 $f(x) = \frac{(x + mx) \times m}{2}$。 - -根据容斥原理,我们可以得到答案为: - -$$ -f(3) + f(5) + f(7) - f(3 \times 5) - f(3 \times 7) - f(5 \times 7) + f(3 \times 5 \times 7) -$$ - -时间复杂度 $O(1)$,空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def sumOfMultiples(self, n: int) -> int: return sum(x for x in range(1, n + 1) if x % 3 == 0 or x % 5 == 0 or x % 7 == 0) ``` -```python -class Solution: - def sumOfMultiples(self, n: int) -> int: - def f(x: int) -> int: - m = n // x - return (x + m * x) * m // 2 - - return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7) -``` - -### **Java** - - - ```java class Solution { public int sumOfMultiples(int n) { @@ -106,24 +74,6 @@ class Solution { } ``` -```java -class Solution { - private int n; - - public int sumOfMultiples(int n) { - this.n = n; - return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); - } - - private int f(int x) { - int m = n / x; - return (x + m * x) * m / 2; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -139,21 +89,6 @@ public: }; ``` -```cpp -class Solution { -public: - int sumOfMultiples(int n) { - auto f = [&](int x) { - int m = n / x; - return (x + m * x) * m / 2; - }; - return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); - } -}; -``` - -### **Go** - ```go func sumOfMultiples(n int) (ans int) { for x := 1; x <= n; x++ { @@ -165,18 +100,6 @@ func sumOfMultiples(n int) (ans int) { } ``` -```go -func sumOfMultiples(n int) int { - f := func(x int) int { - m := n / x - return (x + m*x) * m / 2 - } - return f(3) + f(5) + f(7) - f(3*5) - f(3*7) - f(5*7) + f(3*5*7) -} -``` - -### **TypeScript** - ```ts function sumOfMultiples(n: number): number { let ans = 0; @@ -189,18 +112,6 @@ function sumOfMultiples(n: number): number { } ``` -```ts -function sumOfMultiples(n: number): number { - const f = (x: number): number => { - const m = Math.floor(n / x); - return ((x + m * x) * m) >> 1; - }; - return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); -} -``` - -### **Rust** - ```rust impl Solution { pub fn sum_of_multiples(n: i32) -> i32 { @@ -217,6 +128,81 @@ impl Solution { } ``` + + +### 方法二:数学(容斥原理) + +我们定义函数 $f(x)$ 表示 $[1,..n]$ 中能被 $x$ 整除的数之和,那么一共有 $m = \left\lfloor \frac{n}{x} \right\rfloor$ 个数能被 $x$ 整除,这些数字分别为 $x$, $2x$, $3x$, $\cdots$, $mx$,构成一个等差数列,首项为 $x$,末项为 $mx$,项数为 $m$,因此 $f(x) = \frac{(x + mx) \times m}{2}$。 + +根据容斥原理,我们可以得到答案为: + +$$ +f(3) + f(5) + f(7) - f(3 \times 5) - f(3 \times 7) - f(5 \times 7) + f(3 \times 5 \times 7) +$$ + +时间复杂度 $O(1)$,空间复杂度 $O(1)$。 + + + +```python +class Solution: + def sumOfMultiples(self, n: int) -> int: + def f(x: int) -> int: + m = n // x + return (x + m * x) * m // 2 + + return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7) +``` + +```java +class Solution { + private int n; + + public int sumOfMultiples(int n) { + this.n = n; + return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); + } + + private int f(int x) { + int m = n / x; + return (x + m * x) * m / 2; + } +} +``` + +```cpp +class Solution { +public: + int sumOfMultiples(int n) { + auto f = [&](int x) { + int m = n / x; + return (x + m * x) * m / 2; + }; + return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); + } +}; +``` + +```go +func sumOfMultiples(n int) int { + f := func(x int) int { + m := n / x + return (x + m*x) * m / 2 + } + return f(3) + f(5) + f(7) - f(3*5) - f(3*7) - f(5*7) + f(3*5*7) +} +``` + +```ts +function sumOfMultiples(n: number): number { + const f = (x: number): number => { + const m = Math.floor(n / x); + return ((x + m * x) * m) >> 1; + }; + return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); +} +``` + ```rust impl Solution { pub fn sum_of_multiples(n: i32) -> i32 { @@ -225,6 +211,12 @@ impl Solution { } ``` + + +### 方法三 + + + ```rust impl Solution { pub fn sum_of_multiples(n: i32) -> i32 { @@ -238,10 +230,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2652.Sum Multiples/README_EN.md b/solution/2600-2699/2652.Sum Multiples/README_EN.md index af9ed1f4614df..bb2ac485015a1 100644 --- a/solution/2600-2699/2652.Sum Multiples/README_EN.md +++ b/solution/2600-2699/2652.Sum Multiples/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We directly enumerate every number $x$ in $[1,..n]$, and if $x$ is divisible by $3$, $5$, and $7$, we add $x$ to the answer. @@ -50,40 +50,14 @@ After the enumeration, we return the answer. The time complexity is $O(n)$, where $n$ is the given integer. The space complexity is $O(1)$. -**Solution 2: Mathematics (Inclusion-Exclusion Principle)** - -We define a function $f(x)$ to represent the sum of numbers in $[1,..n]$ that are divisible by $x$. There are $m = \left\lfloor \frac{n}{x} \right\rfloor$ numbers that are divisible by $x$, which are $x$, $2x$, $3x$, $\cdots$, $mx$, forming an arithmetic sequence with the first term $x$, the last term $mx$, and the number of terms $m$. Therefore, $f(x) = \frac{(x + mx) \times m}{2}$. - -According to the inclusion-exclusion principle, we can obtain the answer as: - -$$ -f(3) + f(5) + f(7) - f(3 \times 5) - f(3 \times 7) - f(5 \times 7) + f(3 \times 5 \times 7) -$$ - -The time complexity is $O(1)$, and the space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def sumOfMultiples(self, n: int) -> int: return sum(x for x in range(1, n + 1) if x % 3 == 0 or x % 5 == 0 or x % 7 == 0) ``` -```python -class Solution: - def sumOfMultiples(self, n: int) -> int: - def f(x: int) -> int: - m = n // x - return (x + m * x) * m // 2 - - return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7) -``` - -### **Java** - ```java class Solution { public int sumOfMultiples(int n) { @@ -98,24 +72,6 @@ class Solution { } ``` -```java -class Solution { - private int n; - - public int sumOfMultiples(int n) { - this.n = n; - return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); - } - - private int f(int x) { - int m = n / x; - return (x + m * x) * m / 2; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -131,21 +87,6 @@ public: }; ``` -```cpp -class Solution { -public: - int sumOfMultiples(int n) { - auto f = [&](int x) { - int m = n / x; - return (x + m * x) * m / 2; - }; - return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); - } -}; -``` - -### **Go** - ```go func sumOfMultiples(n int) (ans int) { for x := 1; x <= n; x++ { @@ -157,18 +98,6 @@ func sumOfMultiples(n int) (ans int) { } ``` -```go -func sumOfMultiples(n int) int { - f := func(x int) int { - m := n / x - return (x + m*x) * m / 2 - } - return f(3) + f(5) + f(7) - f(3*5) - f(3*7) - f(5*7) + f(3*5*7) -} -``` - -### **TypeScript** - ```ts function sumOfMultiples(n: number): number { let ans = 0; @@ -181,18 +110,6 @@ function sumOfMultiples(n: number): number { } ``` -```ts -function sumOfMultiples(n: number): number { - const f = (x: number): number => { - const m = Math.floor(n / x); - return ((x + m * x) * m) >> 1; - }; - return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); -} -``` - -### **Rust** - ```rust impl Solution { pub fn sum_of_multiples(n: i32) -> i32 { @@ -209,6 +126,81 @@ impl Solution { } ``` + + +### Solution 2: Mathematics (Inclusion-Exclusion Principle) + +We define a function $f(x)$ to represent the sum of numbers in $[1,..n]$ that are divisible by $x$. There are $m = \left\lfloor \frac{n}{x} \right\rfloor$ numbers that are divisible by $x$, which are $x$, $2x$, $3x$, $\cdots$, $mx$, forming an arithmetic sequence with the first term $x$, the last term $mx$, and the number of terms $m$. Therefore, $f(x) = \frac{(x + mx) \times m}{2}$. + +According to the inclusion-exclusion principle, we can obtain the answer as: + +$$ +f(3) + f(5) + f(7) - f(3 \times 5) - f(3 \times 7) - f(5 \times 7) + f(3 \times 5 \times 7) +$$ + +The time complexity is $O(1)$, and the space complexity is $O(1)$. + + + +```python +class Solution: + def sumOfMultiples(self, n: int) -> int: + def f(x: int) -> int: + m = n // x + return (x + m * x) * m // 2 + + return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7) +``` + +```java +class Solution { + private int n; + + public int sumOfMultiples(int n) { + this.n = n; + return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); + } + + private int f(int x) { + int m = n / x; + return (x + m * x) * m / 2; + } +} +``` + +```cpp +class Solution { +public: + int sumOfMultiples(int n) { + auto f = [&](int x) { + int m = n / x; + return (x + m * x) * m / 2; + }; + return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); + } +}; +``` + +```go +func sumOfMultiples(n int) int { + f := func(x int) int { + m := n / x + return (x + m*x) * m / 2 + } + return f(3) + f(5) + f(7) - f(3*5) - f(3*7) - f(5*7) + f(3*5*7) +} +``` + +```ts +function sumOfMultiples(n: number): number { + const f = (x: number): number => { + const m = Math.floor(n / x); + return ((x + m * x) * m) >> 1; + }; + return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7); +} +``` + ```rust impl Solution { pub fn sum_of_multiples(n: i32) -> i32 { @@ -217,6 +209,12 @@ impl Solution { } ``` + + +### Solution 3 + + + ```rust impl Solution { pub fn sum_of_multiples(n: i32) -> i32 { @@ -230,10 +228,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2653.Sliding Subarray Beauty/README.md b/solution/2600-2699/2653.Sliding Subarray Beauty/README.md index c698df20f21e8..082d29dd193ff 100644 --- a/solution/2600-2699/2653.Sliding Subarray Beauty/README.md +++ b/solution/2600-2699/2653.Sliding Subarray Beauty/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:滑动窗口** +### 方法一:滑动窗口 我们注意到,数组 $nums$ 中元素的范围为 $[-50,50]$,因此,我们可以用一个数组长度为 $101$ 的数组 $cnt$ 统计 $[-50,50]$ 中每个数出现的次数。由于负数的存在,我们可以将每个数加上 $50$,使得每个数都变成非负数,这样就可以用数组 $cnt$ 统计每个数出现的次数了。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -95,32 +89,6 @@ class Solution: return ans ``` -```python -class Solution: - def getSubarrayBeauty(self, nums: List[int], k: int, x: int) -> List[int]: - def f(x: int) -> int: - s = 0 - for i in range(50): - s += cnt[i] - if s >= x: - return i - 50 - return 0 - - cnt = [0] * 101 - for v in nums[:k]: - cnt[v + 50] += 1 - ans = [f(x)] - for i in range(k, len(nums)): - cnt[nums[i] + 50] += 1 - cnt[nums[i - k] + 50] -= 1 - ans.append(f(x)) - return ans -``` - -### **Java** - - - ```java class Solution { public int[] getSubarrayBeauty(int[] nums, int k, int x) { @@ -152,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -185,8 +151,6 @@ public: }; ``` -### **Go** - ```go func getSubarrayBeauty(nums []int, k int, x int) []int { n := len(nums) @@ -215,8 +179,6 @@ func getSubarrayBeauty(nums []int, k int, x int) []int { } ``` -### **TypeScript** - ```ts function getSubarrayBeauty(nums: number[], k: number, x: number): number[] { const n = nums.length; @@ -245,10 +207,34 @@ function getSubarrayBeauty(nums: number[], k: number, x: number): number[] { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def getSubarrayBeauty(self, nums: List[int], k: int, x: int) -> List[int]: + def f(x: int) -> int: + s = 0 + for i in range(50): + s += cnt[i] + if s >= x: + return i - 50 + return 0 + + cnt = [0] * 101 + for v in nums[:k]: + cnt[v + 50] += 1 + ans = [f(x)] + for i in range(k, len(nums)): + cnt[nums[i] + 50] += 1 + cnt[nums[i - k] + 50] -= 1 + ans.append(f(x)) + return ans ``` + + diff --git a/solution/2600-2699/2653.Sliding Subarray Beauty/README_EN.md b/solution/2600-2699/2653.Sliding Subarray Beauty/README_EN.md index a7e095ddbce69..2bb0618ba19fc 100644 --- a/solution/2600-2699/2653.Sliding Subarray Beauty/README_EN.md +++ b/solution/2600-2699/2653.Sliding Subarray Beauty/README_EN.md @@ -63,9 +63,9 @@ For [0, -3], the 1st smallest negative integer is -3.

+### Solution 1 -### **Python3** + ```python from sortedcontainers import SortedList @@ -82,30 +82,6 @@ class Solution: return ans ``` -```python -class Solution: - def getSubarrayBeauty(self, nums: List[int], k: int, x: int) -> List[int]: - def f(x: int) -> int: - s = 0 - for i in range(50): - s += cnt[i] - if s >= x: - return i - 50 - return 0 - - cnt = [0] * 101 - for v in nums[:k]: - cnt[v + 50] += 1 - ans = [f(x)] - for i in range(k, len(nums)): - cnt[nums[i] + 50] += 1 - cnt[nums[i - k] + 50] -= 1 - ans.append(f(x)) - return ans -``` - -### **Java** - ```java class Solution { public int[] getSubarrayBeauty(int[] nums, int k, int x) { @@ -137,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +144,6 @@ public: }; ``` -### **Go** - ```go func getSubarrayBeauty(nums []int, k int, x int) []int { n := len(nums) @@ -200,8 +172,6 @@ func getSubarrayBeauty(nums []int, k int, x int) []int { } ``` -### **TypeScript** - ```ts function getSubarrayBeauty(nums: number[], k: number, x: number): number[] { const n = nums.length; @@ -230,10 +200,34 @@ function getSubarrayBeauty(nums: number[], k: number, x: number): number[] { } ``` -### **...** + + +### Solution 2 -``` + + +```python +class Solution: + def getSubarrayBeauty(self, nums: List[int], k: int, x: int) -> List[int]: + def f(x: int) -> int: + s = 0 + for i in range(50): + s += cnt[i] + if s >= x: + return i - 50 + return 0 + cnt = [0] * 101 + for v in nums[:k]: + cnt[v + 50] += 1 + ans = [f(x)] + for i in range(k, len(nums)): + cnt[nums[i] + 50] += 1 + cnt[nums[i - k] + 50] -= 1 + ans.append(f(x)) + return ans ``` + + diff --git a/solution/2600-2699/2654.Minimum Number of Operations to Make All Array Elements Equal to 1/README.md b/solution/2600-2699/2654.Minimum Number of Operations to Make All Array Elements Equal to 1/README.md index 90f335cadc608..3ecc4517cf009 100644 --- a/solution/2600-2699/2654.Minimum Number of Operations to Make All Array Elements Equal to 1/README.md +++ b/solution/2600-2699/2654.Minimum Number of Operations to Make All Array Elements Equal to 1/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 我们先统计数组 $nums$ 中 $1$ 的个数 $cnt$,如果 $cnt \gt 0$,那么只需要 $n - cnt$ 次操作,就可以将整个数组变成 $1$。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, nums: List[int]) -> int: @@ -82,10 +76,6 @@ class Solution: return -1 if mi > n else n - 1 + mi - 1 ``` -### **Java** - - - ```java class Solution { public int minOperations(int[] nums) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int) int { n := len(nums) @@ -187,8 +173,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function minOperations(nums: number[]): number { const n = nums.length; @@ -219,10 +203,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2654.Minimum Number of Operations to Make All Array Elements Equal to 1/README_EN.md b/solution/2600-2699/2654.Minimum Number of Operations to Make All Array Elements Equal to 1/README_EN.md index 4c4fa486da42b..1c4be2b90b609 100644 --- a/solution/2600-2699/2654.Minimum Number of Operations to Make All Array Elements Equal to 1/README_EN.md +++ b/solution/2600-2699/2654.Minimum Number of Operations to Make All Array Elements Equal to 1/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return -1 if mi > n else n - 1 + mi - 1 ``` -### **Java** - ```java class Solution { public int minOperations(int[] nums) { @@ -105,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +132,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int) int { n := len(nums) @@ -174,8 +168,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function minOperations(nums: number[]): number { const n = nums.length; @@ -206,10 +198,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2655.Find Maximal Uncovered Ranges/README.md b/solution/2600-2699/2655.Find Maximal Uncovered Ranges/README.md index 7ec3edc6cc611..ef7746199f82e 100644 --- a/solution/2600-2699/2655.Find Maximal Uncovered Ranges/README.md +++ b/solution/2600-2699/2655.Find Maximal Uncovered Ranges/README.md @@ -65,9 +65,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们将所有的区间按照左端点从小到大排序,然后从左到右遍历所有的区间,维护一个变量 $last$ 表示当前已经被覆盖的最右端点,初始时 $last=-1$。如果当前区间的左端点大于 $last+1$,那么说明 $[last+1, l-1]$ 是一个未被覆盖的区间,我们将其加入答案数组中。然后我们更新 $last$ 为当前区间的右端点,继续遍历下一个区间。当遍历完所有的区间后,如果 $last+1 \lt n$,那么说明 $[last+1, n-1]$ 是一个未被覆盖的区间,我们将其加入答案数组中。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def findMaximalUncoveredRanges( @@ -98,10 +92,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] findMaximalUncoveredRanges(int n, int[][] ranges) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go func findMaximalUncoveredRanges(n int, ranges [][]int) (ans [][]int) { sort.Slice(ranges, func(i, j int) bool { return ranges[i][0] < ranges[j][0] }) @@ -168,10 +154,6 @@ func findMaximalUncoveredRanges(n int, ranges [][]int) (ans [][]int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2655.Find Maximal Uncovered Ranges/README_EN.md b/solution/2600-2699/2655.Find Maximal Uncovered Ranges/README_EN.md index 22727ec82aabe..2774bef6e19ef 100644 --- a/solution/2600-2699/2655.Find Maximal Uncovered Ranges/README_EN.md +++ b/solution/2600-2699/2655.Find Maximal Uncovered Ranges/README_EN.md @@ -62,9 +62,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,8 +83,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] findMaximalUncoveredRanges(int n, int[][] ranges) { @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +128,6 @@ public: }; ``` -### **Go** - ```go func findMaximalUncoveredRanges(n int, ranges [][]int) (ans [][]int) { sort.Slice(ranges, func(i, j int) bool { return ranges[i][0] < ranges[j][0] }) @@ -151,10 +145,6 @@ func findMaximalUncoveredRanges(n int, ranges [][]int) (ans [][]int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2656.Maximum Sum With Exactly K Elements/README.md b/solution/2600-2699/2656.Maximum Sum With Exactly K Elements/README.md index b244d3280a344..ae96159e13ea8 100644 --- a/solution/2600-2699/2656.Maximum Sum With Exactly K Elements/README.md +++ b/solution/2600-2699/2656.Maximum Sum With Exactly K Elements/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:贪心 + 数学** +### 方法一:贪心 + 数学 我们注意到,要使得最终的得分最大,我们应该尽可能地使得每次选择的元素最大。因此,我们第一次选择数组中的最大元素 $x$,第二次选择 $x+1$,第三次选择 $x+2$,以此类推,直到第 $k$ 次选择 $x+k-1$。这样的选择方式可以保证每次选择的元素都是当前数组中的最大值,因此最终的得分也是最大的。答案即为 $k$ 个 $x$ 的和加上 $0+1+2+\cdots+(k-1)$,即 $k \times x + (k - 1) \times k / 2$。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def maximizeSum(self, nums: List[int], k: int) -> int: @@ -77,10 +71,6 @@ class Solution: return k * x + k * (k - 1) // 2 ``` -### **Java** - - - ```java class Solution { public int maximizeSum(int[] nums, int k) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +93,6 @@ public: }; ``` -### **Go** - ```go func maximizeSum(nums []int, k int) int { x := slices.Max(nums) @@ -114,8 +100,6 @@ func maximizeSum(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function maximizeSum(nums: number[], k: number): number { const x = Math.max(...nums); @@ -123,8 +107,6 @@ function maximizeSum(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn maximize_sum(nums: Vec, k: i32) -> i32 { @@ -141,6 +123,12 @@ impl Solution { } ``` + + +### 方法二 + + + ```rust impl Solution { pub fn maximize_sum(nums: Vec, k: i32) -> i32 { @@ -151,10 +139,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2656.Maximum Sum With Exactly K Elements/README_EN.md b/solution/2600-2699/2656.Maximum Sum With Exactly K Elements/README_EN.md index 494262828acc3..a06a005ca83a0 100644 --- a/solution/2600-2699/2656.Maximum Sum With Exactly K Elements/README_EN.md +++ b/solution/2600-2699/2656.Maximum Sum With Exactly K Elements/README_EN.md @@ -61,7 +61,7 @@ It can be proven, that 11 is the maximum answer that we can achieve. ## Solutions -**Solution 1: Greedy + Mathematics** +### Solution 1: Greedy + Mathematics We notice that to make the final score maximum, we should make each choice as large as possible. Therefore, we select the largest element $x$ in the array for the first time, $x+1$ for the second time, $x+2$ for the third time, and so on, until the $k$th time we select $x+k-1$. This way of selection ensures that the element selected each time is the largest in the current array, so the final score is also the largest. The answer is $k$ $x$ sum plus $0+1+2+\cdots+(k-1)$, that is, $k \times x + (k - 1) \times k / 2$. @@ -69,8 +69,6 @@ Time complexity is $O(n)$, where $n$ is the length of the array. Space complexit -### **Python3** - ```python class Solution: def maximizeSum(self, nums: List[int], k: int) -> int: @@ -78,8 +76,6 @@ class Solution: return k * x + k * (k - 1) // 2 ``` -### **Java** - ```java class Solution { public int maximizeSum(int[] nums, int k) { @@ -92,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +98,6 @@ public: }; ``` -### **Go** - ```go func maximizeSum(nums []int, k int) int { x := slices.Max(nums) @@ -113,8 +105,6 @@ func maximizeSum(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function maximizeSum(nums: number[], k: number): number { const x = Math.max(...nums); @@ -122,8 +112,6 @@ function maximizeSum(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn maximize_sum(nums: Vec, k: i32) -> i32 { @@ -140,6 +128,12 @@ impl Solution { } ``` + + +### Solution 2 + + + ```rust impl Solution { pub fn maximize_sum(nums: Vec, k: i32) -> i32 { @@ -150,10 +144,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/README.md b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/README.md index 8299293b49e8e..611df5e432733 100644 --- a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/README.md +++ b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/README.md @@ -47,9 +47,7 @@ i = 2:1,2 和 3 是两个数组的前缀公共元素,所以 C[2] = 3 。 ## 解法 - - -**方法一:计数** +### 方法一:计数 我们可以使用两个数组 $cnt1$ 和 $cnt2$ 分别记录数组 $A$ 和 $B$ 中每个元素出现的次数,用数组 $ans$ 记录答案。 @@ -59,24 +57,8 @@ i = 2:1,2 和 3 是两个数组的前缀公共元素,所以 C[2] = 3 。 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $A$ 和 $B$ 的长度。 -**方法二:位运算(异或运算)** - -我们可以使用一个长度为 $n+1$ 的数组 $vis$ 记录数组 $A$ 和 $B$ 中每个元素的出现情况,数组 $vis$ 的初始值为 $1$。另外,我们用一个变量 $s$ 记录当前公共元素的个数。 - -接下来,我们遍历数组 $A$ 和 $B$,更新 $vis[A[i]] = vis[A[i]] \oplus 1$,并且更新 $vis[B[i]] = vis[B[i]] \oplus 1$,其中 $\oplus$ 表示异或运算。 - -如果遍历到当前位置,元素 $A[i]$ 出现过两次(即在数组 $A$ 和 $B$ 中都出现过),那么 $vis[A[i]]$ 的值将为会 $1$,我们将 $s$ 加一。同理,如果元素 $B[i]$ 出现过两次,那么 $vis[B[i]]$ 的值将为会 $1$,我们将 $s$ 加一。然后将 $s$ 的值加入到答案数组 $ans$ 中。 - -遍历结束后,返回答案数组 $ans$ 即可。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $A$ 和 $B$ 的长度。 - -### **Python3** - - - ```python class Solution: def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]: @@ -91,25 +73,6 @@ class Solution: return ans ``` -```python -class Solution: - def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]: - ans = [] - vis = [1] * (len(A) + 1) - s = 0 - for a, b in zip(A, B): - vis[a] ^= 1 - s += vis[a] - vis[b] ^= 1 - s += vis[b] - ans.append(s) - return ans -``` - -### **Java** - - - ```java class Solution { public int[] findThePrefixCommonArray(int[] A, int[] B) { @@ -129,6 +92,91 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector findThePrefixCommonArray(vector& A, vector& B) { + int n = A.size(); + vector ans(n); + vector cnt1(n + 1), cnt2(n + 1); + for (int i = 0; i < n; ++i) { + ++cnt1[A[i]]; + ++cnt2[B[i]]; + for (int j = 1; j <= n; ++j) { + ans[i] += min(cnt1[j], cnt2[j]); + } + } + return ans; + } +}; +``` + +```go +func findThePrefixCommonArray(A []int, B []int) []int { + n := len(A) + cnt1 := make([]int, n+1) + cnt2 := make([]int, n+1) + ans := make([]int, n) + for i, a := range A { + b := B[i] + cnt1[a]++ + cnt2[b]++ + for j := 1; j <= n; j++ { + ans[i] += min(cnt1[j], cnt2[j]) + } + } + return ans +} +``` + +```ts +function findThePrefixCommonArray(A: number[], B: number[]): number[] { + const n = A.length; + const cnt1: number[] = Array(n + 1).fill(0); + const cnt2: number[] = Array(n + 1).fill(0); + const ans: number[] = Array(n).fill(0); + for (let i = 0; i < n; ++i) { + ++cnt1[A[i]]; + ++cnt2[B[i]]; + for (let j = 1; j <= n; ++j) { + ans[i] += Math.min(cnt1[j], cnt2[j]); + } + } + return ans; +} +``` + + + +### 方法二:位运算(异或运算) + +我们可以使用一个长度为 $n+1$ 的数组 $vis$ 记录数组 $A$ 和 $B$ 中每个元素的出现情况,数组 $vis$ 的初始值为 $1$。另外,我们用一个变量 $s$ 记录当前公共元素的个数。 + +接下来,我们遍历数组 $A$ 和 $B$,更新 $vis[A[i]] = vis[A[i]] \oplus 1$,并且更新 $vis[B[i]] = vis[B[i]] \oplus 1$,其中 $\oplus$ 表示异或运算。 + +如果遍历到当前位置,元素 $A[i]$ 出现过两次(即在数组 $A$ 和 $B$ 中都出现过),那么 $vis[A[i]]$ 的值将为会 $1$,我们将 $s$ 加一。同理,如果元素 $B[i]$ 出现过两次,那么 $vis[B[i]]$ 的值将为会 $1$,我们将 $s$ 加一。然后将 $s$ 的值加入到答案数组 $ans$ 中。 + +遍历结束后,返回答案数组 $ans$ 即可。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $A$ 和 $B$ 的长度。 + + + +```python +class Solution: + def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]: + ans = [] + vis = [1] * (len(A) + 1) + s = 0 + for a, b in zip(A, B): + vis[a] ^= 1 + s += vis[a] + vis[b] ^= 1 + s += vis[b] + ans.append(s) + return ans +``` + ```java class Solution { public int[] findThePrefixCommonArray(int[] A, int[] B) { @@ -149,27 +197,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector findThePrefixCommonArray(vector& A, vector& B) { - int n = A.size(); - vector ans(n); - vector cnt1(n + 1), cnt2(n + 1); - for (int i = 0; i < n; ++i) { - ++cnt1[A[i]]; - ++cnt2[B[i]]; - for (int j = 1; j <= n; ++j) { - ans[i] += min(cnt1[j], cnt2[j]); - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -190,26 +217,6 @@ public: }; ``` -### **Go** - -```go -func findThePrefixCommonArray(A []int, B []int) []int { - n := len(A) - cnt1 := make([]int, n+1) - cnt2 := make([]int, n+1) - ans := make([]int, n) - for i, a := range A { - b := B[i] - cnt1[a]++ - cnt2[b]++ - for j := 1; j <= n; j++ { - ans[i] += min(cnt1[j], cnt2[j]) - } - } - return ans -} -``` - ```go func findThePrefixCommonArray(A []int, B []int) (ans []int) { vis := make([]int, len(A)+1) @@ -229,25 +236,6 @@ func findThePrefixCommonArray(A []int, B []int) (ans []int) { } ``` -### **TypeScript** - -```ts -function findThePrefixCommonArray(A: number[], B: number[]): number[] { - const n = A.length; - const cnt1: number[] = Array(n + 1).fill(0); - const cnt2: number[] = Array(n + 1).fill(0); - const ans: number[] = Array(n).fill(0); - for (let i = 0; i < n; ++i) { - ++cnt1[A[i]]; - ++cnt2[B[i]]; - for (let j = 1; j <= n; ++j) { - ans[i] += Math.min(cnt1[j], cnt2[j]); - } - } - return ans; -} -``` - ```ts function findThePrefixCommonArray(A: number[], B: number[]): number[] { const n = A.length; @@ -266,10 +254,6 @@ function findThePrefixCommonArray(A: number[], B: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/README_EN.md b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/README_EN.md index 47905134695fd..53dc847477585 100644 --- a/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/README_EN.md +++ b/solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/README_EN.md @@ -45,7 +45,7 @@ At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3. ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We can use two arrays $cnt1$ and $cnt2$ to record the occurrence times of each element in arrays $A$ and $B$ respectively, and use an array $ans$ to record the answer. @@ -55,22 +55,8 @@ After the traversal, return the answer array $ans$. The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of arrays $A$ and $B$. -**Solution 2: Bit Operation (XOR Operation)** - -We can use an array $vis$ of length $n+1$ to record the occurrence situation of each element in arrays $A$ and $B$, the initial value of array $vis$ is $1$. In addition, we use a variable $s$ to record the current number of common elements. - -Next, we traverse arrays $A$ and $B$, update $vis[A[i]] = vis[A[i]] \oplus 1$, and update $vis[B[i]] = vis[B[i]] \oplus 1$, where $\oplus$ represents XOR operation. - -If at the current position, the element $A[i]$ has appeared twice (i.e., it has appeared in both arrays $A$ and $B$), then the value of $vis[A[i]]$ will be $1$, and we increment $s$. Similarly, if the element $B[i]$ has appeared twice, then the value of $vis[B[i]]$ will be $1$, and we increment $s$. Then add the value of $s$ to the answer array $ans$. - -After the traversal, return the answer array $ans$. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of arrays $A$ and $B$. - -### **Python3** - ```python class Solution: def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]: @@ -85,23 +71,6 @@ class Solution: return ans ``` -```python -class Solution: - def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]: - ans = [] - vis = [1] * (len(A) + 1) - s = 0 - for a, b in zip(A, B): - vis[a] ^= 1 - s += vis[a] - vis[b] ^= 1 - s += vis[b] - ans.append(s) - return ans -``` - -### **Java** - ```java class Solution { public int[] findThePrefixCommonArray(int[] A, int[] B) { @@ -121,6 +90,91 @@ class Solution { } ``` +```cpp +class Solution { +public: + vector findThePrefixCommonArray(vector& A, vector& B) { + int n = A.size(); + vector ans(n); + vector cnt1(n + 1), cnt2(n + 1); + for (int i = 0; i < n; ++i) { + ++cnt1[A[i]]; + ++cnt2[B[i]]; + for (int j = 1; j <= n; ++j) { + ans[i] += min(cnt1[j], cnt2[j]); + } + } + return ans; + } +}; +``` + +```go +func findThePrefixCommonArray(A []int, B []int) []int { + n := len(A) + cnt1 := make([]int, n+1) + cnt2 := make([]int, n+1) + ans := make([]int, n) + for i, a := range A { + b := B[i] + cnt1[a]++ + cnt2[b]++ + for j := 1; j <= n; j++ { + ans[i] += min(cnt1[j], cnt2[j]) + } + } + return ans +} +``` + +```ts +function findThePrefixCommonArray(A: number[], B: number[]): number[] { + const n = A.length; + const cnt1: number[] = Array(n + 1).fill(0); + const cnt2: number[] = Array(n + 1).fill(0); + const ans: number[] = Array(n).fill(0); + for (let i = 0; i < n; ++i) { + ++cnt1[A[i]]; + ++cnt2[B[i]]; + for (let j = 1; j <= n; ++j) { + ans[i] += Math.min(cnt1[j], cnt2[j]); + } + } + return ans; +} +``` + + + +### Solution 2: Bit Operation (XOR Operation) + +We can use an array $vis$ of length $n+1$ to record the occurrence situation of each element in arrays $A$ and $B$, the initial value of array $vis$ is $1$. In addition, we use a variable $s$ to record the current number of common elements. + +Next, we traverse arrays $A$ and $B$, update $vis[A[i]] = vis[A[i]] \oplus 1$, and update $vis[B[i]] = vis[B[i]] \oplus 1$, where $\oplus$ represents XOR operation. + +If at the current position, the element $A[i]$ has appeared twice (i.e., it has appeared in both arrays $A$ and $B$), then the value of $vis[A[i]]$ will be $1$, and we increment $s$. Similarly, if the element $B[i]$ has appeared twice, then the value of $vis[B[i]]$ will be $1$, and we increment $s$. Then add the value of $s$ to the answer array $ans$. + +After the traversal, return the answer array $ans$. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of arrays $A$ and $B$. + + + +```python +class Solution: + def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]: + ans = [] + vis = [1] * (len(A) + 1) + s = 0 + for a, b in zip(A, B): + vis[a] ^= 1 + s += vis[a] + vis[b] ^= 1 + s += vis[b] + ans.append(s) + return ans +``` + ```java class Solution { public int[] findThePrefixCommonArray(int[] A, int[] B) { @@ -141,27 +195,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - vector findThePrefixCommonArray(vector& A, vector& B) { - int n = A.size(); - vector ans(n); - vector cnt1(n + 1), cnt2(n + 1); - for (int i = 0; i < n; ++i) { - ++cnt1[A[i]]; - ++cnt2[B[i]]; - for (int j = 1; j <= n; ++j) { - ans[i] += min(cnt1[j], cnt2[j]); - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -182,26 +215,6 @@ public: }; ``` -### **Go** - -```go -func findThePrefixCommonArray(A []int, B []int) []int { - n := len(A) - cnt1 := make([]int, n+1) - cnt2 := make([]int, n+1) - ans := make([]int, n) - for i, a := range A { - b := B[i] - cnt1[a]++ - cnt2[b]++ - for j := 1; j <= n; j++ { - ans[i] += min(cnt1[j], cnt2[j]) - } - } - return ans -} -``` - ```go func findThePrefixCommonArray(A []int, B []int) (ans []int) { vis := make([]int, len(A)+1) @@ -221,25 +234,6 @@ func findThePrefixCommonArray(A []int, B []int) (ans []int) { } ``` -### **TypeScript** - -```ts -function findThePrefixCommonArray(A: number[], B: number[]): number[] { - const n = A.length; - const cnt1: number[] = Array(n + 1).fill(0); - const cnt2: number[] = Array(n + 1).fill(0); - const ans: number[] = Array(n).fill(0); - for (let i = 0; i < n; ++i) { - ++cnt1[A[i]]; - ++cnt2[B[i]]; - for (let j = 1; j <= n; ++j) { - ans[i] += Math.min(cnt1[j], cnt2[j]); - } - } - return ans; -} -``` - ```ts function findThePrefixCommonArray(A: number[], B: number[]): number[] { const n = A.length; @@ -258,10 +252,6 @@ function findThePrefixCommonArray(A: number[], B: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2658.Maximum Number of Fish in a Grid/README.md b/solution/2600-2699/2658.Maximum Number of Fish in a Grid/README.md index 87e07e43b94c9..df1f0222e5884 100644 --- a/solution/2600-2699/2658.Maximum Number of Fish in a Grid/README.md +++ b/solution/2600-2699/2658.Maximum Number of Fish in a Grid/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 根据题目描述,我们只需要找出每块连通的水域中鱼的数目,然后取最大值即可。因此,我们可以使用深度优先搜索的方法来解决本题。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def findMaxFish(self, grid: List[List[int]]) -> int: @@ -98,10 +92,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[][] grid; @@ -138,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +158,6 @@ public: }; ``` -### **Go** - ```go func findMaxFish(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -199,8 +185,6 @@ func findMaxFish(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function findMaxFish(grid: number[][]): number { const m = grid.length; @@ -232,10 +216,6 @@ function findMaxFish(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2658.Maximum Number of Fish in a Grid/README_EN.md b/solution/2600-2699/2658.Maximum Number of Fish in a Grid/README_EN.md index 6874fce24fd4c..d79c43ec79ff7 100644 --- a/solution/2600-2699/2658.Maximum Number of Fish in a Grid/README_EN.md +++ b/solution/2600-2699/2658.Maximum Number of Fish in a Grid/README_EN.md @@ -51,7 +51,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS According to the problem description, we only need to find the number of fish in each connected water area and then take the maximum value. Therefore, we can use the depth-first search method to solve this problem. @@ -65,8 +65,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times -### **Python3** - ```python class Solution: def findMaxFish(self, grid: List[List[int]]) -> int: @@ -88,8 +86,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[][] grid; @@ -126,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +152,6 @@ public: }; ``` -### **Go** - ```go func findMaxFish(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -187,8 +179,6 @@ func findMaxFish(grid [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function findMaxFish(grid: number[][]): number { const m = grid.length; @@ -220,10 +210,6 @@ function findMaxFish(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2659.Make Array Empty/README.md b/solution/2600-2699/2659.Make Array Empty/README.md index 3b1ca62852d6f..7315f4d1c322c 100644 --- a/solution/2600-2699/2659.Make Array Empty/README.md +++ b/solution/2600-2699/2659.Make Array Empty/README.md @@ -139,9 +139,7 @@ ## 解法 - - -**方法一:哈希表 + 排序 + 树状数组** +### 方法一:哈希表 + 排序 + 树状数组 我们先用哈希表 $pos$ 记录数组 $nums$ 中每个元素的位置,接下来对数组 $nums$ 进行排序,那么数组最小值的下标为 $pos[nums[0]]$,移动到数组的第一个位置并且删除,需要 $pos[nums[0]] + 1$ 次操作,因此初始答案为 $ans = pos[nums[0]] + 1$。 @@ -153,10 +151,6 @@ -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -176,44 +170,6 @@ class Solution: return ans ``` -```python -class BinaryIndexedTree: - def __init__(self, n): - self.n = n - self.c = [0] * (n + 1) - - def update(self, x, delta): - while x <= self.n: - self.c[x] += delta - x += x & -x - - def query(self, x): - s = 0 - while x: - s += self.c[x] - x -= x & -x - return s - - -class Solution: - def countOperationsToEmptyArray(self, nums: List[int]) -> int: - pos = {x: i for i, x in enumerate(nums)} - nums.sort() - ans = pos[nums[0]] + 1 - n = len(nums) - tree = BinaryIndexedTree(n) - for k, (a, b) in enumerate(pairwise(nums)): - i, j = pos[a], pos[b] - d = j - i - tree.query(j + 1) + tree.query(i + 1) - ans += d + (n - k) * int(i > j) - tree.update(i + 1, 1) - return ans -``` - -### **Java** - - - ```java class BinaryIndexedTree { private int n; @@ -262,8 +218,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -314,8 +268,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -365,8 +317,6 @@ func countOperationsToEmptyArray(nums []int) int64 { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -417,10 +367,46 @@ function countOperationsToEmptyArray(nums: number[]): number { } ``` -### **...** + -``` +### 方法二 + + + +```python +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += x & -x + def query(self, x): + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s + + +class Solution: + def countOperationsToEmptyArray(self, nums: List[int]) -> int: + pos = {x: i for i, x in enumerate(nums)} + nums.sort() + ans = pos[nums[0]] + 1 + n = len(nums) + tree = BinaryIndexedTree(n) + for k, (a, b) in enumerate(pairwise(nums)): + i, j = pos[a], pos[b] + d = j - i - tree.query(j + 1) + tree.query(i + 1) + ans += d + (n - k) * int(i > j) + tree.update(i + 1, 1) + return ans ``` + + diff --git a/solution/2600-2699/2659.Make Array Empty/README_EN.md b/solution/2600-2699/2659.Make Array Empty/README_EN.md index 567ce560e4194..3adc278c426a8 100644 --- a/solution/2600-2699/2659.Make Array Empty/README_EN.md +++ b/solution/2600-2699/2659.Make Array Empty/README_EN.md @@ -131,7 +131,7 @@ ## Solutions -**Solution 1: Hash Table + Sorting + Fenwick Tree** +### Solution 1: Hash Table + Sorting + Fenwick Tree First, we use a hash table $pos$ to record the position of each element in array $nums$. Then, we sort array $nums$. The initial answer is the position of the minimum element in array $nums$ plus 1, which is $ans = pos[nums[0]] + 1$. @@ -143,8 +143,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python from sortedcontainers import SortedList @@ -164,42 +162,6 @@ class Solution: return ans ``` -```python -class BinaryIndexedTree: - def __init__(self, n): - self.n = n - self.c = [0] * (n + 1) - - def update(self, x, delta): - while x <= self.n: - self.c[x] += delta - x += x & -x - - def query(self, x): - s = 0 - while x: - s += self.c[x] - x -= x & -x - return s - - -class Solution: - def countOperationsToEmptyArray(self, nums: List[int]) -> int: - pos = {x: i for i, x in enumerate(nums)} - nums.sort() - ans = pos[nums[0]] + 1 - n = len(nums) - tree = BinaryIndexedTree(n) - for k, (a, b) in enumerate(pairwise(nums)): - i, j = pos[a], pos[b] - d = j - i - tree.query(j + 1) + tree.query(i + 1) - ans += d + (n - k) * int(i > j) - tree.update(i + 1, 1) - return ans -``` - -### **Java** - ```java class BinaryIndexedTree { private int n; @@ -248,8 +210,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { public: @@ -300,8 +260,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -351,8 +309,6 @@ func countOperationsToEmptyArray(nums []int) int64 { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -403,10 +359,46 @@ function countOperationsToEmptyArray(nums: number[]): number { } ``` -### **...** + + +### Solution 2 + + + +```python +class BinaryIndexedTree: + def __init__(self, n): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x, delta): + while x <= self.n: + self.c[x] += delta + x += x & -x + + def query(self, x): + s = 0 + while x: + s += self.c[x] + x -= x & -x + return s -``` +class Solution: + def countOperationsToEmptyArray(self, nums: List[int]) -> int: + pos = {x: i for i, x in enumerate(nums)} + nums.sort() + ans = pos[nums[0]] + 1 + n = len(nums) + tree = BinaryIndexedTree(n) + for k, (a, b) in enumerate(pairwise(nums)): + i, j = pos[a], pos[b] + d = j - i - tree.query(j + 1) + tree.query(i + 1) + ans += d + (n - k) * int(i > j) + tree.update(i + 1, 1) + return ans ``` + + diff --git a/solution/2600-2699/2660.Determine the Winner of a Bowling Game/README.md b/solution/2600-2699/2660.Determine the Winner of a Bowling Game/README.md index 99ccdcc11a161..d2829e87529cb 100644 --- a/solution/2600-2699/2660.Determine the Winner of a Bowling Game/README.md +++ b/solution/2600-2699/2660.Determine the Winner of a Bowling Game/README.md @@ -70,9 +70,7 @@ player1 的得分等于 player2 的得分,所以这一场比赛平局,答案 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以用一个函数 $f(arr)$ 计算出两个玩家的得分,分别记为 $a$ 和 $b$,然后根据 $a$ 和 $b$ 的大小关系返回答案即可。 @@ -80,10 +78,6 @@ player1 的得分等于 player2 的得分,所以这一场比赛平局,答案 -### **Python3** - - - ```python class Solution: def isWinner(self, player1: List[int], player2: List[int]) -> int: @@ -98,10 +92,6 @@ class Solution: return 1 if a > b else (2 if b > a else 0) ``` -### **Java** - - - ```java class Solution { public int isWinner(int[] player1, int[] player2) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +128,6 @@ public: }; ``` -### **Go** - ```go func isWinner(player1 []int, player2 []int) int { f := func(arr []int) int { @@ -166,8 +152,6 @@ func isWinner(player1 []int, player2 []int) int { } ``` -### **TypeScript** - ```ts function isWinner(player1: number[], player2: number[]): number { const f = (arr: number[]): number => { @@ -186,8 +170,6 @@ function isWinner(player1: number[], player2: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn is_winner(player1: Vec, player2: Vec) -> i32 { @@ -216,10 +198,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2660.Determine the Winner of a Bowling Game/README_EN.md b/solution/2600-2699/2660.Determine the Winner of a Bowling Game/README_EN.md index c97ac40ee6443..881ce3564f718 100644 --- a/solution/2600-2699/2660.Determine the Winner of a Bowling Game/README_EN.md +++ b/solution/2600-2699/2660.Determine the Winner of a Bowling Game/README_EN.md @@ -68,7 +68,7 @@ The score of player1 equals to the score of player2, so, there is a draw, and th ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can define a function $f(arr)$ to calculate the scores of the two players, denoted as $a$ and $b$, respectively, and then return the answer based on the relationship between $a$ and $b$. @@ -76,8 +76,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def isWinner(self, player1: List[int], player2: List[int]) -> int: @@ -92,8 +90,6 @@ class Solution: return 1 if a > b else (2 if b > a else 0) ``` -### **Java** - ```java class Solution { public int isWinner(int[] player1, int[] player2) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +126,6 @@ public: }; ``` -### **Go** - ```go func isWinner(player1 []int, player2 []int) int { f := func(arr []int) int { @@ -158,8 +150,6 @@ func isWinner(player1 []int, player2 []int) int { } ``` -### **TypeScript** - ```ts function isWinner(player1: number[], player2: number[]): number { const f = (arr: number[]): number => { @@ -178,8 +168,6 @@ function isWinner(player1: number[], player2: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn is_winner(player1: Vec, player2: Vec) -> i32 { @@ -208,10 +196,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2661.First Completely Painted Row or Column/README.md b/solution/2600-2699/2661.First Completely Painted Row or Column/README.md index c3adaaa0b37b3..d877ff36a2cef 100644 --- a/solution/2600-2699/2661.First Completely Painted Row or Column/README.md +++ b/solution/2600-2699/2661.First Completely Painted Row or Column/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:哈希表 + 数组计数** +### 方法一:哈希表 + 数组计数 我们用一个哈希表 $idx$ 记录每个元素在矩阵 $mat$ 中的位置,即 $idx[mat[i][j]] = (i, j)$,定义两个数组 $row$ 和 $col$ 分别记录每行和每列已经涂色的元素个数。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int: @@ -81,10 +75,6 @@ class Solution: return k ``` -### **Java** - - - ```java class Solution { public int firstCompleteIndex(int[] arr, int[][] mat) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +124,6 @@ public: }; ``` -### **Go** - ```go func firstCompleteIndex(arr []int, mat [][]int) int { m, n := len(mat), len(mat[0]) @@ -161,8 +147,6 @@ func firstCompleteIndex(arr []int, mat [][]int) int { } ``` -### **TypeScript** - ```ts function firstCompleteIndex(arr: number[], mat: number[][]): number { const m = mat.length; @@ -186,8 +170,6 @@ function firstCompleteIndex(arr: number[], mat: number[][]): number { } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -220,10 +202,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2661.First Completely Painted Row or Column/README_EN.md b/solution/2600-2699/2661.First Completely Painted Row or Column/README_EN.md index c037528ff7337..85b9dc3b891e5 100644 --- a/solution/2600-2699/2661.First Completely Painted Row or Column/README_EN.md +++ b/solution/2600-2699/2661.First Completely Painted Row or Column/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Hash Table + Array Counting** +### Solution 1: Hash Table + Array Counting We use a hash table $idx$ to record the position of each element in the matrix $mat$, that is $idx[mat[i][j]] = (i, j)$, and define two arrays $row$ and $col$ to record the number of colored elements in each row and each column respectively. @@ -53,8 +53,6 @@ The time complexity is $O(m \times n)$, and the space complexity is $O(m \times -### **Python3** - ```python class Solution: def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int: @@ -73,8 +71,6 @@ class Solution: return k ``` -### **Java** - ```java class Solution { public int firstCompleteIndex(int[] arr, int[][] mat) { @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +120,6 @@ public: }; ``` -### **Go** - ```go func firstCompleteIndex(arr []int, mat [][]int) int { m, n := len(mat), len(mat[0]) @@ -151,8 +143,6 @@ func firstCompleteIndex(arr []int, mat [][]int) int { } ``` -### **TypeScript** - ```ts function firstCompleteIndex(arr: number[], mat: number[][]): number { const m = mat.length; @@ -176,8 +166,6 @@ function firstCompleteIndex(arr: number[], mat: number[][]): number { } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -210,10 +198,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2662.Minimum Cost of a Path With Special Roads/README.md b/solution/2600-2699/2662.Minimum Cost of a Path With Special Roads/README.md index f848690d88e13..1fdbcb378706b 100644 --- a/solution/2600-2699/2662.Minimum Cost of a Path With Special Roads/README.md +++ b/solution/2600-2699/2662.Minimum Cost of a Path With Special Roads/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:Dijkstra** +### 方法一:Dijkstra 我们可以发现,对于访问到的每个坐标点 $(x, y)$,假设从起点到 $(x, y)$ 的最小代价为 $d$。如果选择直接移动到 $(targetX, targetY)$,那么总代价就是 $d + |x - targetX| + |y - targetY|$。如果选择经过某条特殊路径 $(x_1, y_1) \rightarrow (x_2, y_2)$,那么我们需要可以花费 $|x - x_1| + |y - y_1| + cost$ 的代价,从 $(x, y)$ 移动到 $(x_2, y_2)$。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def minimumCost( @@ -97,10 +91,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumCost(int[] start, int[] target, int[][] specialRoads) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -166,8 +154,6 @@ public: }; ``` -### **Go** - ```go func minimumCost(start []int, target []int, specialRoads [][]int) int { ans := 1 << 30 @@ -214,8 +200,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **TypeScript** - ```ts function minimumCost(start: number[], target: number[], specialRoads: number[][]): number { const dist = (x1: number, y1: number, x2: number, y2: number): number => { @@ -308,10 +292,6 @@ class Heap { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2662.Minimum Cost of a Path With Special Roads/README_EN.md b/solution/2600-2699/2662.Minimum Cost of a Path With Special Roads/README_EN.md index c724d66fdd2a9..3c5bbfc2ff6eb 100644 --- a/solution/2600-2699/2662.Minimum Cost of a Path With Special Roads/README_EN.md +++ b/solution/2600-2699/2662.Minimum Cost of a Path With Special Roads/README_EN.md @@ -51,7 +51,7 @@ It can be shown that we cannot achieve a smaller total cost than 5. ## Solutions -**Solution 1: Dijkstra** +### Solution 1: Dijkstra We can find that for each coordinate $(x, y)$ we visit, suppose the minimum cost from the start point to $(x, y)$ is $d$. If we choose to move directly to $(targetX, targetY)$, then the total cost is $d + |x - targetX| + |y - targetY|$. If we choose to go through a special path $(x_1, y_1) \rightarrow (x_2, y_2)$, then we need to spend $|x - x_1| + |y - y_1| + cost$ to move from $(x, y)$ to $(x_2, y_2)$. @@ -67,8 +67,6 @@ The time complexity is $O(n^2 \times \log n)$, and the space complexity is $O(n^ -### **Python3** - ```python class Solution: def minimumCost( @@ -91,8 +89,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumCost(int[] start, int[] target, int[][] specialRoads) { @@ -125,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +152,6 @@ public: }; ``` -### **Go** - ```go func minimumCost(start []int, target []int, specialRoads [][]int) int { ans := 1 << 30 @@ -206,8 +198,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **TypeScript** - ```ts function minimumCost(start: number[], target: number[], specialRoads: number[][]): number { const dist = (x1: number, y1: number, x2: number, y2: number): number => { @@ -300,10 +290,6 @@ class Heap { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2663.Lexicographically Smallest Beautiful String/README.md b/solution/2600-2699/2663.Lexicographically Smallest Beautiful String/README.md index 17805c00d99d7..01d42f5f014ae 100644 --- a/solution/2600-2699/2663.Lexicographically Smallest Beautiful String/README.md +++ b/solution/2600-2699/2663.Lexicographically Smallest Beautiful String/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们可以发现,一个长度为 $2$ 的回文字符串,其相邻两个字符一定相同;而一个长度为 $3$ 的回文字符串,其首尾两个字符一定相同。因此,一个美丽字符串不包含任何长度为 $2$ 或更长的回文子字符串,意味着该字符串的每个字符与其相邻的前两个字符都不相同。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def smallestBeautifulString(self, s: str, k: int) -> str: @@ -95,10 +89,6 @@ class Solution: return '' ``` -### **Java** - - - ```java class Solution { public String smallestBeautifulString(String s, int k) { @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -163,8 +151,6 @@ public: }; ``` -### **Go** - ```go func smallestBeautifulString(s string, k int) string { cs := []byte(s) @@ -194,8 +180,6 @@ func smallestBeautifulString(s string, k int) string { } ``` -### **TypeScript** - ```ts function smallestBeautifulString(s: string, k: number): string { const cs: string[] = s.split(''); @@ -225,10 +209,6 @@ function smallestBeautifulString(s: string, k: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2663.Lexicographically Smallest Beautiful String/README_EN.md b/solution/2600-2699/2663.Lexicographically Smallest Beautiful String/README_EN.md index b1b7d67e6c69c..d781cb1c50014 100644 --- a/solution/2600-2699/2663.Lexicographically Smallest Beautiful String/README_EN.md +++ b/solution/2600-2699/2663.Lexicographically Smallest Beautiful String/README_EN.md @@ -50,7 +50,7 @@ It can be proven that there is no string that is lexicographically larger than t ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy We can find that a palindrome string of length $2$ must have two adjacent characters equal; and a palindrome string of length $3$ must have two characters at the beginning and end equal. Therefore, a beautiful string does not contain any palindrome substring of length $2$ or longer, which means that each character in the string is different from its previous two adjacent characters. @@ -63,8 +63,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string. The space -### **Python3** - ```python class Solution: def smallestBeautifulString(self, s: str, k: int) -> str: @@ -88,8 +86,6 @@ class Solution: return '' ``` -### **Java** - ```java class Solution { public String smallestBeautifulString(String s, int k) { @@ -121,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +148,6 @@ public: }; ``` -### **Go** - ```go func smallestBeautifulString(s string, k int) string { cs := []byte(s) @@ -185,8 +177,6 @@ func smallestBeautifulString(s string, k int) string { } ``` -### **TypeScript** - ```ts function smallestBeautifulString(s: string, k: number): string { const cs: string[] = s.split(''); @@ -216,10 +206,6 @@ function smallestBeautifulString(s: string, k: number): string { } ``` -### **...** - -``` - -``` - + + diff --git "a/solution/2600-2699/2664.The Knight\342\200\231s Tour/README.md" "b/solution/2600-2699/2664.The Knight\342\200\231s Tour/README.md" index 368a6917796fe..797578e1b88bf 100644 --- "a/solution/2600-2699/2664.The Knight\342\200\231s Tour/README.md" +++ "b/solution/2600-2699/2664.The Knight\342\200\231s Tour/README.md" @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:回溯** +### 方法一:回溯 我们创建一个二维数组 $g$,用于记录骑士的移动顺序,初始时 $g[r][c] = -1$,其余位置均为 $-1$。另外,我们还需要一个变量 $ok$,用于记录是否找到了一种方案。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def tourOfKnight(self, m: int, n: int, r: int, c: int) -> List[List[int]]: @@ -87,10 +81,6 @@ class Solution: return g ``` -### **Java** - - - ```java class Solution { private int[][] g; @@ -131,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +152,6 @@ public: }; ``` -### **Go** - ```go func tourOfKnight(m int, n int, r int, c int) [][]int { g := make([][]int, m) @@ -201,8 +187,6 @@ func tourOfKnight(m int, n int, r int, c int) [][]int { } ``` -### **TypeScript** - ```ts function tourOfKnight(m: number, n: number, r: number, c: number): number[][] { const g: number[][] = Array.from({ length: m }, () => Array(n).fill(-1)); @@ -231,8 +215,6 @@ function tourOfKnight(m: number, n: number, r: number, c: number): number[][] { } ``` -### **Rust** - ```rust impl Solution { pub fn tour_of_knight(m: i32, n: i32, r: i32, c: i32) -> Vec> { @@ -274,10 +256,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git "a/solution/2600-2699/2664.The Knight\342\200\231s Tour/README_EN.md" "b/solution/2600-2699/2664.The Knight\342\200\231s Tour/README_EN.md" index 5701b4f026239..8a20c1d4f1f3c 100644 --- "a/solution/2600-2699/2664.The Knight\342\200\231s Tour/README_EN.md" +++ "b/solution/2600-2699/2664.The Knight\342\200\231s Tour/README_EN.md" @@ -41,9 +41,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return g ``` -### **Java** - ```java class Solution { private int[][] g; @@ -111,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +140,6 @@ public: }; ``` -### **Go** - ```go func tourOfKnight(m int, n int, r int, c int) [][]int { g := make([][]int, m) @@ -181,8 +175,6 @@ func tourOfKnight(m int, n int, r int, c int) [][]int { } ``` -### **TypeScript** - ```ts function tourOfKnight(m: number, n: number, r: number, c: number): number[][] { const g: number[][] = Array.from({ length: m }, () => Array(n).fill(-1)); @@ -211,8 +203,6 @@ function tourOfKnight(m: number, n: number, r: number, c: number): number[][] { } ``` -### **Rust** - ```rust impl Solution { pub fn tour_of_knight(m: i32, n: i32, r: i32, c: i32) -> Vec> { @@ -254,10 +244,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2665.Counter II/README.md b/solution/2600-2699/2665.Counter II/README.md index 7561439de542c..1cad6eacfac69 100644 --- a/solution/2600-2699/2665.Counter II/README.md +++ b/solution/2600-2699/2665.Counter II/README.md @@ -56,12 +56,10 @@ counter.reset(); // 0 ## 解法 - +### 方法一 -### **TypeScript** - ```ts type ReturnObj = { increment: () => number; @@ -92,10 +90,6 @@ function createCounter(init: number): ReturnObj { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2665.Counter II/README_EN.md b/solution/2600-2699/2665.Counter II/README_EN.md index 6a2d779fe9823..ac2a8173f9ef4 100644 --- a/solution/2600-2699/2665.Counter II/README_EN.md +++ b/solution/2600-2699/2665.Counter II/README_EN.md @@ -52,9 +52,9 @@ counter.reset(); // 0 ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type ReturnObj = { @@ -86,10 +86,6 @@ function createCounter(init: number): ReturnObj { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2666.Allow One Function Call/README.md b/solution/2600-2699/2666.Allow One Function Call/README.md index 19c5f0df9d098..3af9dee3ed68d 100644 --- a/solution/2600-2699/2666.Allow One Function Call/README.md +++ b/solution/2600-2699/2666.Allow One Function Call/README.md @@ -51,12 +51,10 @@ onceFn(4, 6, 8); // undefined, fn 没有被调用 ## 解法 - +### 方法一 -### **TypeScript** - ```ts function once any>( fn: T, @@ -79,10 +77,6 @@ function once any>( */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2666.Allow One Function Call/README_EN.md b/solution/2600-2699/2666.Allow One Function Call/README_EN.md index 83017014363a7..d0fe1c198e939 100644 --- a/solution/2600-2699/2666.Allow One Function Call/README_EN.md +++ b/solution/2600-2699/2666.Allow One Function Call/README_EN.md @@ -47,9 +47,9 @@ onceFn(4, 6, 8); // undefined, fn was not called ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function once any>( @@ -73,10 +73,6 @@ function once any>( */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2667.Create Hello World Function/README.md b/solution/2600-2699/2667.Create Hello World Function/README.md index 431a08b064dad..e3f4e70a31efb 100644 --- a/solution/2600-2699/2667.Create Hello World Function/README.md +++ b/solution/2600-2699/2667.Create Hello World Function/README.md @@ -44,12 +44,10 @@ f({}, null, 42); // "Hello World" ## 解法 - +### 方法一 -### **TypeScript** - ```ts function createHelloWorld() { return function (...args): string { @@ -63,10 +61,6 @@ function createHelloWorld() { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2667.Create Hello World Function/README_EN.md b/solution/2600-2699/2667.Create Hello World Function/README_EN.md index 08e0b65e29a96..2321677c265bc 100644 --- a/solution/2600-2699/2667.Create Hello World Function/README_EN.md +++ b/solution/2600-2699/2667.Create Hello World Function/README_EN.md @@ -40,9 +40,9 @@ Any arguments could be passed to the function but it should still always return ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function createHelloWorld() { @@ -57,10 +57,6 @@ function createHelloWorld() { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2668.Find Latest Salaries/README.md b/solution/2600-2699/2668.Find Latest Salaries/README.md index 661a5b93997ff..2e12c77a6191c 100644 --- a/solution/2600-2699/2668.Find Latest Salaries/README.md +++ b/solution/2600-2699/2668.Find Latest Salaries/README.md @@ -71,14 +71,10 @@ ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -93,3 +89,5 @@ ORDER BY emp_id; ``` + + diff --git a/solution/2600-2699/2668.Find Latest Salaries/README_EN.md b/solution/2600-2699/2668.Find Latest Salaries/README_EN.md index ef9b5b429c4d9..d8449467d69c5 100644 --- a/solution/2600-2699/2668.Find Latest Salaries/README_EN.md +++ b/solution/2600-2699/2668.Find Latest Salaries/README_EN.md @@ -69,9 +69,9 @@ Each row contains employees details and their yearly salaries, however, some of ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -87,3 +87,5 @@ ORDER BY emp_id; ``` + + diff --git a/solution/2600-2699/2669.Count Artist Occurrences On Spotify Ranking List/README.md b/solution/2600-2699/2669.Count Artist Occurrences On Spotify Ranking List/README.md index dab3142e524d6..f81e45cbe9138 100644 --- a/solution/2600-2699/2669.Count Artist Occurrences On Spotify Ranking List/README.md +++ b/solution/2600-2699/2669.Count Artist Occurrences On Spotify Ranking List/README.md @@ -56,14 +56,10 @@ id 是该表的主键(具有唯一值的列)。 ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -75,3 +71,5 @@ ORDER BY occurrences DESC, artist; ``` + + diff --git a/solution/2600-2699/2669.Count Artist Occurrences On Spotify Ranking List/README_EN.md b/solution/2600-2699/2669.Count Artist Occurrences On Spotify Ranking List/README_EN.md index bb45673d76eb7..50faa3ecef2c2 100644 --- a/solution/2600-2699/2669.Count Artist Occurrences On Spotify Ranking List/README_EN.md +++ b/solution/2600-2699/2669.Count Artist Occurrences On Spotify Ranking List/README_EN.md @@ -53,9 +53,9 @@ Each row contains an id, track_name, and artist. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -68,3 +68,5 @@ ORDER BY occurrences DESC, artist; ``` + + diff --git a/solution/2600-2699/2670.Find the Distinct Difference Array/README.md b/solution/2600-2699/2670.Find the Distinct Difference Array/README.md index 4fd71619379ac..e3467c23f1183 100644 --- a/solution/2600-2699/2670.Find the Distinct Difference Array/README.md +++ b/solution/2600-2699/2670.Find the Distinct Difference Array/README.md @@ -53,14 +53,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def distinctDifferenceArray(self, nums: List[int]) -> List[int]: @@ -73,28 +69,6 @@ class Solution: return ans ``` -```python -class Solution: - def distinctDifferenceArray(self, nums: List[int]) -> List[int]: - n = len(nums) - suf = [0] * (n + 1) - s = set() - for i in range(n - 1, -1, -1): - s.add(nums[i]) - suf[i] = len(s) - - s.clear() - ans = [0] * n - for i, x in enumerate(nums): - s.add(x) - ans[i] = len(s) - suf[i + 1] - return ans -``` - -### **Java** - - - ```java class Solution { public int[] distinctDifferenceArray(int[] nums) { @@ -116,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +112,6 @@ public: }; ``` -### **Go** - ```go func distinctDifferenceArray(nums []int) []int { n := len(nums) @@ -161,8 +131,6 @@ func distinctDifferenceArray(nums []int) []int { } ``` -### **TypeScript** - ```ts function distinctDifferenceArray(nums: number[]): number[] { const n = nums.length; @@ -182,8 +150,6 @@ function distinctDifferenceArray(nums: number[]): number[] { } ``` -### **Rust** - ```rust use std::collections::HashSet; @@ -214,6 +180,30 @@ impl Solution { } ``` + + +### 方法二 + + + +```python +class Solution: + def distinctDifferenceArray(self, nums: List[int]) -> List[int]: + n = len(nums) + suf = [0] * (n + 1) + s = set() + for i in range(n - 1, -1, -1): + s.add(nums[i]) + suf[i] = len(s) + + s.clear() + ans = [0] * n + for i, x in enumerate(nums): + s.add(x) + ans[i] = len(s) - suf[i + 1] + return ans +``` + ```rust use std::collections::HashSet; @@ -240,10 +230,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2670.Find the Distinct Difference Array/README_EN.md b/solution/2600-2699/2670.Find the Distinct Difference Array/README_EN.md index 685ce2930044d..a9108d8d5e60a 100644 --- a/solution/2600-2699/2670.Find the Distinct Difference Array/README_EN.md +++ b/solution/2600-2699/2670.Find the Distinct Difference Array/README_EN.md @@ -47,9 +47,9 @@ For index i = 4, there are 3 distinct elements in the prefix and no elements in ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,26 +63,6 @@ class Solution: return ans ``` -```python -class Solution: - def distinctDifferenceArray(self, nums: List[int]) -> List[int]: - n = len(nums) - suf = [0] * (n + 1) - s = set() - for i in range(n - 1, -1, -1): - s.add(nums[i]) - suf[i] = len(s) - - s.clear() - ans = [0] * n - for i, x in enumerate(nums): - s.add(x) - ans[i] = len(s) - suf[i + 1] - return ans -``` - -### **Java** - ```java class Solution { public int[] distinctDifferenceArray(int[] nums) { @@ -104,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +106,6 @@ public: }; ``` -### **Go** - ```go func distinctDifferenceArray(nums []int) []int { n := len(nums) @@ -149,8 +125,6 @@ func distinctDifferenceArray(nums []int) []int { } ``` -### **TypeScript** - ```ts function distinctDifferenceArray(nums: number[]): number[] { const n = nums.length; @@ -170,8 +144,6 @@ function distinctDifferenceArray(nums: number[]): number[] { } ``` -### **Rust** - ```rust use std::collections::HashSet; @@ -202,6 +174,30 @@ impl Solution { } ``` + + +### Solution 2 + + + +```python +class Solution: + def distinctDifferenceArray(self, nums: List[int]) -> List[int]: + n = len(nums) + suf = [0] * (n + 1) + s = set() + for i in range(n - 1, -1, -1): + s.add(nums[i]) + suf[i] = len(s) + + s.clear() + ans = [0] * n + for i, x in enumerate(nums): + s.add(x) + ans[i] = len(s) - suf[i + 1] + return ans +``` + ```rust use std::collections::HashSet; @@ -228,10 +224,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2671.Frequency Tracker/README.md b/solution/2600-2699/2671.Frequency Tracker/README.md index 430e3ea65daa7..2201f16b05dc4 100644 --- a/solution/2600-2699/2671.Frequency Tracker/README.md +++ b/solution/2600-2699/2671.Frequency Tracker/README.md @@ -79,14 +79,10 @@ frequencyTracker.hasFrequency(1); // 返回 true ,因为 3 出现 1 次 ## 解法 - +### 方法一 -### **Python3** - - - ```python class FrequencyTracker: def __init__(self): @@ -117,10 +113,6 @@ class FrequencyTracker: # param_3 = obj.hasFrequency(frequency) ``` -### **Java** - - - ```java class FrequencyTracker { private Map cnt = new HashMap<>(); @@ -162,8 +154,6 @@ class FrequencyTracker { */ ``` -### **C++** - ```cpp class FrequencyTracker { public: @@ -207,8 +197,6 @@ private: */ ``` -### **Go** - ```go type FrequencyTracker struct { cnt map[int]int @@ -251,8 +239,6 @@ func (this *FrequencyTracker) HasFrequency(frequency int) bool { */ ``` -### **TypeScript** - ```ts class FrequencyTracker { private cnt: Map; @@ -296,10 +282,6 @@ class FrequencyTracker { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2671.Frequency Tracker/README_EN.md b/solution/2600-2699/2671.Frequency Tracker/README_EN.md index 674743a87ad23..a7771cf8ee2d1 100644 --- a/solution/2600-2699/2671.Frequency Tracker/README_EN.md +++ b/solution/2600-2699/2671.Frequency Tracker/README_EN.md @@ -78,9 +78,9 @@ frequencyTracker.hasFrequency(1); // Returns true, because 3 occurs once ## Solutions - +### Solution 1 -### **Python3** + ```python class FrequencyTracker: @@ -112,8 +112,6 @@ class FrequencyTracker: # param_3 = obj.hasFrequency(frequency) ``` -### **Java** - ```java class FrequencyTracker { private Map cnt = new HashMap<>(); @@ -155,8 +153,6 @@ class FrequencyTracker { */ ``` -### **C++** - ```cpp class FrequencyTracker { public: @@ -200,8 +196,6 @@ private: */ ``` -### **Go** - ```go type FrequencyTracker struct { cnt map[int]int @@ -244,8 +238,6 @@ func (this *FrequencyTracker) HasFrequency(frequency int) bool { */ ``` -### **TypeScript** - ```ts class FrequencyTracker { private cnt: Map; @@ -289,10 +281,6 @@ class FrequencyTracker { */ ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README.md b/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README.md index badbe21808c8f..92226999e735f 100644 --- a/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README.md +++ b/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README.md @@ -54,14 +54,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def colorTheArray(self, n: int, queries: List[List[int]]) -> List[int]: @@ -82,10 +78,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] colorTheArray(int n, int[][] queries) { @@ -114,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +135,6 @@ public: }; ``` -### **Go** - ```go func colorTheArray(n int, queries [][]int) (ans []int) { nums := make([]int, n) @@ -172,8 +160,6 @@ func colorTheArray(n int, queries [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function colorTheArray(n: number, queries: number[][]): number[] { const nums: number[] = new Array(n).fill(0); @@ -199,10 +185,6 @@ function colorTheArray(n: number, queries: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README_EN.md b/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README_EN.md index 0a674b40a4058..9e508d9e32621 100644 --- a/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README_EN.md +++ b/solution/2600-2699/2672.Number of Adjacent Elements With the Same Color/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -74,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] colorTheArray(int n, int[][] queries) { @@ -104,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +131,6 @@ public: }; ``` -### **Go** - ```go func colorTheArray(n int, queries [][]int) (ans []int) { nums := make([]int, n) @@ -162,8 +156,6 @@ func colorTheArray(n int, queries [][]int) (ans []int) { } ``` -### **TypeScript** - ```ts function colorTheArray(n: number, queries: number[][]): number[] { const nums: number[] = new Array(n).fill(0); @@ -189,10 +181,6 @@ function colorTheArray(n: number, queries: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2673.Make Costs of Paths Equal in a Binary Tree/README.md b/solution/2600-2699/2673.Make Costs of Paths Equal in a Binary Tree/README.md index ab8ae5deefa25..3eca51adc1522 100644 --- a/solution/2600-2699/2673.Make Costs of Paths Equal in a Binary Tree/README.md +++ b/solution/2600-2699/2673.Make Costs of Paths Equal in a Binary Tree/README.md @@ -60,14 +60,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minIncrements(self, n: int, cost: List[int]) -> int: @@ -84,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] cost; @@ -113,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +125,6 @@ public: }; ``` -### **Go** - ```go func minIncrements(n int, cost []int) (ans int) { var dfs func(int) int @@ -153,8 +141,6 @@ func minIncrements(n int, cost []int) (ans int) { } ``` -### **TypeScript** - ```ts function minIncrements(n: number, cost: number[]): number { let ans = 0; @@ -171,10 +157,6 @@ function minIncrements(n: number, cost: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2673.Make Costs of Paths Equal in a Binary Tree/README_EN.md b/solution/2600-2699/2673.Make Costs of Paths Equal in a Binary Tree/README_EN.md index cd67bdbf47706..261e4144c2fb7 100644 --- a/solution/2600-2699/2673.Make Costs of Paths Equal in a Binary Tree/README_EN.md +++ b/solution/2600-2699/2673.Make Costs of Paths Equal in a Binary Tree/README_EN.md @@ -52,9 +52,9 @@ It can be shown that this is the minimum answer we can achieve. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] cost; @@ -99,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +117,6 @@ public: }; ``` -### **Go** - ```go func minIncrements(n int, cost []int) (ans int) { var dfs func(int) int @@ -139,8 +133,6 @@ func minIncrements(n int, cost []int) (ans int) { } ``` -### **TypeScript** - ```ts function minIncrements(n: number, cost: number[]): number { let ans = 0; @@ -157,10 +149,6 @@ function minIncrements(n: number, cost: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2674.Split a Circular Linked List/README.md b/solution/2600-2699/2674.Split a Circular Linked List/README.md index d6ea8dbc5a06f..ca5e5217ceed9 100644 --- a/solution/2600-2699/2674.Split a Circular Linked List/README.md +++ b/solution/2600-2699/2674.Split a Circular Linked List/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:快慢指针** +### 方法一:快慢指针 我们定义两个指针 $a$ 和 $b$,初始时都指向链表的头节点。每次迭代时,$a$ 指针向前移动一步,$b$ 指针向前移动两步,直到 $b$ 指针到达链表的末尾。此时,$a$ 指针指向链表节点数的一半,我们将链表从 $a$ 指针处断开,即可得到两个链表的头节点。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -78,10 +72,6 @@ class Solution: return [list, list2] ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -111,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -170,8 +156,6 @@ func splitCircularLinkedList(list *ListNode) []*ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -202,10 +186,6 @@ function splitCircularLinkedList(list: ListNode | null): Array } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2674.Split a Circular Linked List/README_EN.md b/solution/2600-2699/2674.Split a Circular Linked List/README_EN.md index 600d6515ba851..81197e8e0ba23 100644 --- a/solution/2600-2699/2674.Split a Circular Linked List/README_EN.md +++ b/solution/2600-2699/2674.Split a Circular Linked List/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for singly-linked list. @@ -64,8 +64,6 @@ class Solution: return [list, list2] ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -128,8 +124,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -154,8 +148,6 @@ func splitCircularLinkedList(list *ListNode) []*ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -186,10 +178,6 @@ function splitCircularLinkedList(list: ListNode | null): Array } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2675.Array of Objects to Matrix/README.md b/solution/2600-2699/2675.Array of Objects to Matrix/README.md index 0d286c3058b7d..3126cd075217b 100644 --- a/solution/2600-2699/2675.Array of Objects to Matrix/README.md +++ b/solution/2600-2699/2675.Array of Objects to Matrix/README.md @@ -137,14 +137,10 @@ arr = [ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function jsonToMatrix(arr: any[]): (string | number | boolean | null)[] { const dfs = (key: string, obj: any) => { @@ -187,3 +183,5 @@ function jsonToMatrix(arr: any[]): (string | number | boolean | null)[] { ``` + + diff --git a/solution/2600-2699/2675.Array of Objects to Matrix/README_EN.md b/solution/2600-2699/2675.Array of Objects to Matrix/README_EN.md index 871a5c951090c..f9dafb7a5a2b8 100644 --- a/solution/2600-2699/2675.Array of Objects to Matrix/README_EN.md +++ b/solution/2600-2699/2675.Array of Objects to Matrix/README_EN.md @@ -133,9 +133,9 @@ There are no keys so every row is an empty array. ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function jsonToMatrix(arr: any[]): (string | number | boolean | null)[] { @@ -179,3 +179,5 @@ function jsonToMatrix(arr: any[]): (string | number | boolean | null)[] { ``` + + diff --git a/solution/2600-2699/2676.Throttle/README.md b/solution/2600-2699/2676.Throttle/README.md index 420a1c5e4fa1e..c4fab84be0066 100644 --- a/solution/2600-2699/2676.Throttle/README.md +++ b/solution/2600-2699/2676.Throttle/README.md @@ -59,14 +59,10 @@ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts type F = (...args: any[]) => void; @@ -96,3 +92,5 @@ const throttle = (fn: F, t: number): F => { ``` + + diff --git a/solution/2600-2699/2676.Throttle/README_EN.md b/solution/2600-2699/2676.Throttle/README_EN.md index 15582f686c21f..379a73d4cab6a 100644 --- a/solution/2600-2699/2676.Throttle/README_EN.md +++ b/solution/2600-2699/2676.Throttle/README_EN.md @@ -72,9 +72,9 @@ The 5th is called at 300ms, but it is after 260ms, so it should be called immedi ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type F = (...args: any[]) => void; @@ -105,3 +105,5 @@ const throttle = (fn: F, t: number): F => { ``` + + diff --git a/solution/2600-2699/2677.Chunk Array/README.md b/solution/2600-2699/2677.Chunk Array/README.md index 8e0efccc67c52..c4bb4aec874c1 100644 --- a/solution/2600-2699/2677.Chunk Array/README.md +++ b/solution/2600-2699/2677.Chunk Array/README.md @@ -57,14 +57,10 @@ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function chunk(arr: any[], size: number): any[][] { const ans: any[][] = []; @@ -75,8 +71,6 @@ function chunk(arr: any[], size: number): any[][] { } ``` -### **JavaScript** - ```js /** * @param {Array} arr @@ -93,3 +87,5 @@ var chunk = function (arr, size) { ``` + + diff --git a/solution/2600-2699/2677.Chunk Array/README_EN.md b/solution/2600-2699/2677.Chunk Array/README_EN.md index 6e77024dde344..a128a11a2ea5b 100644 --- a/solution/2600-2699/2677.Chunk Array/README_EN.md +++ b/solution/2600-2699/2677.Chunk Array/README_EN.md @@ -53,9 +53,9 @@ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function chunk(arr: any[], size: number): any[][] { @@ -67,8 +67,6 @@ function chunk(arr: any[], size: number): any[][] { } ``` -### **JavaScript** - ```js /** * @param {Array} arr @@ -85,3 +83,5 @@ var chunk = function (arr, size) { ``` + + diff --git a/solution/2600-2699/2678.Number of Senior Citizens/README.md b/solution/2600-2699/2678.Number of Senior Citizens/README.md index ef392e98da8a7..ccee4a6d934ba 100644 --- a/solution/2600-2699/2678.Number of Senior Citizens/README.md +++ b/solution/2600-2699/2678.Number of Senior Citizens/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:遍历计数** +### 方法一:遍历计数 我们可以遍历 `details` 中的每个字符串 $x$,并将 $x$ 的第 $12$ 和第 $13$ 个字符(下标为 $11$, $12$)转换为整数,判断是否大于 $60$,如果是则将答案加一。 @@ -61,20 +59,12 @@ -### **Python3** - - - ```python class Solution: def countSeniors(self, details: List[str]) -> int: return sum(int(x[11:13]) > 60 for x in details) ``` -### **Java** - - - ```java class Solution { public int countSeniors(String[] details) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +94,6 @@ public: }; ``` -### **Go** - ```go func countSeniors(details []string) (ans int) { for _, x := range details { @@ -120,7 +106,18 @@ func countSeniors(details []string) (ans int) { } ``` -### **Rust** +```ts +function countSeniors(details: string[]): number { + let ans = 0; + for (const x of details) { + const age = parseInt(x.slice(11, 13)); + if (age > 60) { + ++ans; + } + } + return ans; +} +``` ```rust impl Solution { @@ -140,6 +137,18 @@ impl Solution { } ``` + + +### 方法二 + + + +```ts +function countSeniors(details: string[]): number { + return details.filter(v => parseInt(v.slice(11, 13)) > 60).length; +} +``` + ```rust impl Solution { pub fn count_seniors(details: Vec) -> i32 { @@ -152,31 +161,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function countSeniors(details: string[]): number { - let ans = 0; - for (const x of details) { - const age = parseInt(x.slice(11, 13)); - if (age > 60) { - ++ans; - } - } - return ans; -} -``` - -```ts -function countSeniors(details: string[]): number { - return details.filter(v => parseInt(v.slice(11, 13)) > 60).length; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2678.Number of Senior Citizens/README_EN.md b/solution/2600-2699/2678.Number of Senior Citizens/README_EN.md index 746b816736cce..9f096e6b73870 100644 --- a/solution/2600-2699/2678.Number of Senior Citizens/README_EN.md +++ b/solution/2600-2699/2678.Number of Senior Citizens/README_EN.md @@ -45,7 +45,7 @@ ## Solutions -**Solution 1: Traversal and Counting** +### Solution 1: Traversal and Counting We can traverse each string $x$ in `details` and convert the $12$th and $13$th characters (indexed at $11$ and $12$) of $x$ to integers, and check if they are greater than $60$. If so, we add one to the answer. @@ -55,16 +55,12 @@ The time complexity is $O(n)$, where $n$ is the length of `details`. The space c -### **Python3** - ```python class Solution: def countSeniors(self, details: List[str]) -> int: return sum(int(x[11:13]) > 60 for x in details) ``` -### **Java** - ```java class Solution { public int countSeniors(String[] details) { @@ -80,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +90,6 @@ public: }; ``` -### **Go** - ```go func countSeniors(details []string) (ans int) { for _, x := range details { @@ -110,7 +102,18 @@ func countSeniors(details []string) (ans int) { } ``` -### **Rust** +```ts +function countSeniors(details: string[]): number { + let ans = 0; + for (const x of details) { + const age = parseInt(x.slice(11, 13)); + if (age > 60) { + ++ans; + } + } + return ans; +} +``` ```rust impl Solution { @@ -130,6 +133,18 @@ impl Solution { } ``` + + +### Solution 2 + + + +```ts +function countSeniors(details: string[]): number { + return details.filter(v => parseInt(v.slice(11, 13)) > 60).length; +} +``` + ```rust impl Solution { pub fn count_seniors(details: Vec) -> i32 { @@ -142,31 +157,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function countSeniors(details: string[]): number { - let ans = 0; - for (const x of details) { - const age = parseInt(x.slice(11, 13)); - if (age > 60) { - ++ans; - } - } - return ans; -} -``` - -```ts -function countSeniors(details: string[]): number { - return details.filter(v => parseInt(v.slice(11, 13)) > 60).length; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2679.Sum in a Matrix/README.md b/solution/2600-2699/2679.Sum in a Matrix/README.md index 6b142816fb107..4503bb956012f 100644 --- a/solution/2600-2699/2679.Sum in a Matrix/README.md +++ b/solution/2600-2699/2679.Sum in a Matrix/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们可以先遍历矩阵的每一行,将每一行排序。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def matrixSum(self, nums: List[List[int]]) -> int: @@ -68,10 +62,6 @@ class Solution: return sum(map(max, zip(*nums))) ``` -### **Java** - - - ```java class Solution { public int matrixSum(int[][] nums) { @@ -91,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func matrixSum(nums [][]int) (ans int) { for _, row := range nums { @@ -131,8 +117,6 @@ func matrixSum(nums [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function matrixSum(nums: number[][]): number { for (const row of nums) { @@ -150,8 +134,6 @@ function matrixSum(nums: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn matrix_sum(nums: Vec>) -> i32 { @@ -175,6 +157,12 @@ impl Solution { } ``` + + +### 方法二 + + + ```rust impl Solution { pub fn matrix_sum(nums: Vec>) -> i32 { @@ -197,10 +185,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2679.Sum in a Matrix/README_EN.md b/solution/2600-2699/2679.Sum in a Matrix/README_EN.md index 1c781248bf5e7..912d0afb99f6e 100644 --- a/solution/2600-2699/2679.Sum in a Matrix/README_EN.md +++ b/solution/2600-2699/2679.Sum in a Matrix/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -51,8 +51,6 @@ class Solution: return sum(map(max, zip(*nums))) ``` -### **Java** - ```java class Solution { public int matrixSum(int[][] nums) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -94,8 +90,6 @@ public: }; ``` -### **Go** - ```go func matrixSum(nums [][]int) (ans int) { for _, row := range nums { @@ -112,8 +106,6 @@ func matrixSum(nums [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function matrixSum(nums: number[][]): number { for (const row of nums) { @@ -131,8 +123,6 @@ function matrixSum(nums: number[][]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn matrix_sum(nums: Vec>) -> i32 { @@ -156,6 +146,12 @@ impl Solution { } ``` + + +### Solution 2 + + + ```rust impl Solution { pub fn matrix_sum(nums: Vec>) -> i32 { @@ -178,10 +174,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2680.Maximum OR/README.md b/solution/2600-2699/2680.Maximum OR/README.md index 4ba893f32abc0..f7a3303490372 100644 --- a/solution/2600-2699/2680.Maximum OR/README.md +++ b/solution/2600-2699/2680.Maximum OR/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:贪心 + 预处理** +### 方法一:贪心 + 预处理 我们注意到,为了使得答案最大,我们应该将 $k$ 次乘 $2$ 作用于同一个数。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def maximumOr(self, nums: List[int], k: int) -> int: @@ -74,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long maximumOr(int[] nums, int k) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func maximumOr(nums []int, k int) int64 { n := len(nums) @@ -136,8 +122,6 @@ func maximumOr(nums []int, k int) int64 { } ``` -### **TypeScript** - ```ts function maximumOr(nums: number[], k: number): number { const n = nums.length; @@ -154,8 +138,6 @@ function maximumOr(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn maximum_or(nums: Vec, k: i32) -> i64 { @@ -179,10 +161,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2680.Maximum OR/README_EN.md b/solution/2600-2699/2680.Maximum OR/README_EN.md index 17fc0c7e7370e..a631d03ab012c 100644 --- a/solution/2600-2699/2680.Maximum OR/README_EN.md +++ b/solution/2600-2699/2680.Maximum OR/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Greedy + Preprocessing** +### Solution 1: Greedy + Preprocessing We notice that in order to maximize the answer, we should apply $k$ times of bitwise OR to the same number. @@ -50,8 +50,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maximumOr(self, nums: List[int], k: int) -> int: @@ -66,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long maximumOr(int[] nums, int k) { @@ -86,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +102,6 @@ public: }; ``` -### **Go** - ```go func maximumOr(nums []int, k int) int64 { n := len(nums) @@ -126,8 +118,6 @@ func maximumOr(nums []int, k int) int64 { } ``` -### **TypeScript** - ```ts function maximumOr(nums: number[], k: number): number { const n = nums.length; @@ -144,8 +134,6 @@ function maximumOr(nums: number[], k: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn maximum_or(nums: Vec, k: i32) -> i64 { @@ -169,10 +157,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2681.Power of Heroes/README.md b/solution/2600-2699/2681.Power of Heroes/README.md index 3b7dba18a1447..ec537c1e052d1 100644 --- a/solution/2600-2699/2681.Power of Heroes/README.md +++ b/solution/2600-2699/2681.Power of Heroes/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:排序 + 数学** +### 方法一:排序 + 数学 我们注意到,题目中涉及到子序列的最大值和最小值,数组中元素的顺序不影响最终的结果,因此我们可以先对数组进行排序。 @@ -73,10 +71,6 @@ $$ -### **Python3** - - - ```python class Solution: def sumOfPower(self, nums: List[int]) -> int: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int sumOfPower(int[] nums) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func sumOfPower(nums []int) (ans int) { const mod = 1e9 + 7 @@ -148,8 +134,6 @@ func sumOfPower(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumOfPower(nums: number[]): number { const mod = 10 ** 9 + 7; @@ -166,10 +150,6 @@ function sumOfPower(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2681.Power of Heroes/README_EN.md b/solution/2600-2699/2681.Power of Heroes/README_EN.md index 291e7229e6d44..186c039736b15 100644 --- a/solution/2600-2699/2681.Power of Heroes/README_EN.md +++ b/solution/2600-2699/2681.Power of Heroes/README_EN.md @@ -48,9 +48,9 @@ The sum of powers of all groups is 8 + 1 + 64 + 4 + 32 + 16 + 16 = 141. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int sumOfPower(int[] nums) { @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +100,6 @@ public: }; ``` -### **Go** - ```go func sumOfPower(nums []int) (ans int) { const mod = 1e9 + 7 @@ -121,8 +115,6 @@ func sumOfPower(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumOfPower(nums: number[]): number { const mod = 10 ** 9 + 7; @@ -139,10 +131,6 @@ function sumOfPower(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2682.Find the Losers of the Circular Game/README.md b/solution/2600-2699/2682.Find the Losers of the Circular Game/README.md index f240945a59087..c741856238fb5 100644 --- a/solution/2600-2699/2682.Find the Losers of the Circular Game/README.md +++ b/solution/2600-2699/2682.Find the Losers of the Circular Game/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们用一个数组 `vis` 记录每个朋友是否接到过球,初始时所有朋友都没有接到过球。然后我们按照题目描述的规则模拟游戏的过程,直到某个朋友第二次接到球为止。 @@ -73,10 +71,6 @@ -### **Python3** - - - ```python class Solution: def circularGameLosers(self, n: int, k: int) -> List[int]: @@ -89,10 +83,6 @@ class Solution: return [i + 1 for i in range(n) if not vis[i]] ``` -### **Java** - - - ```java class Solution { public int[] circularGameLosers(int n, int k) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func circularGameLosers(n int, k int) (ans []int) { vis := make([]bool, n) @@ -155,7 +141,22 @@ func circularGameLosers(n int, k int) (ans []int) { } ``` -### **Rust** +```ts +function circularGameLosers(n: number, k: number): number[] { + const vis = new Array(n).fill(false); + const ans: number[] = []; + for (let i = 0, p = 1; !vis[i]; p++) { + vis[i] = true; + i = (i + p * k) % n; + } + for (let i = 0; i < vis.length; i++) { + if (!vis[i]) { + ans.push(i + 1); + } + } + return ans; +} +``` ```rust impl Solution { @@ -182,29 +183,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function circularGameLosers(n: number, k: number): number[] { - const vis = new Array(n).fill(false); - const ans: number[] = []; - for (let i = 0, p = 1; !vis[i]; p++) { - vis[i] = true; - i = (i + p * k) % n; - } - for (let i = 0; i < vis.length; i++) { - if (!vis[i]) { - ans.push(i + 1); - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2682.Find the Losers of the Circular Game/README_EN.md b/solution/2600-2699/2682.Find the Losers of the Circular Game/README_EN.md index 173f9ae4a6adb..acf05abb5f03a 100644 --- a/solution/2600-2699/2682.Find the Losers of the Circular Game/README_EN.md +++ b/solution/2600-2699/2682.Find the Losers of the Circular Game/README_EN.md @@ -56,9 +56,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return [i + 1 for i in range(n) if not vis[i]] ``` -### **Java** - ```java class Solution { public int[] circularGameLosers(int n, int k) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +114,6 @@ public: }; ``` -### **Go** - ```go func circularGameLosers(n int, k int) (ans []int) { vis := make([]bool, n) @@ -136,7 +130,22 @@ func circularGameLosers(n int, k int) (ans []int) { } ``` -### **Rust** +```ts +function circularGameLosers(n: number, k: number): number[] { + const vis = new Array(n).fill(false); + const ans: number[] = []; + for (let i = 0, p = 1; !vis[i]; p++) { + vis[i] = true; + i = (i + p * k) % n; + } + for (let i = 0; i < vis.length; i++) { + if (!vis[i]) { + ans.push(i + 1); + } + } + return ans; +} +``` ```rust impl Solution { @@ -163,29 +172,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function circularGameLosers(n: number, k: number): number[] { - const vis = new Array(n).fill(false); - const ans: number[] = []; - for (let i = 0, p = 1; !vis[i]; p++) { - vis[i] = true; - i = (i + p * k) % n; - } - for (let i = 0; i < vis.length; i++) { - if (!vis[i]) { - ans.push(i + 1); - } - } - return ans; -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2683.Neighboring Bitwise XOR/README.md b/solution/2600-2699/2683.Neighboring Bitwise XOR/README.md index f5b258aa69d2c..81086a1581649 100644 --- a/solution/2600-2699/2683.Neighboring Bitwise XOR/README.md +++ b/solution/2600-2699/2683.Neighboring Bitwise XOR/README.md @@ -63,9 +63,7 @@ derived[1] = original[1] ⊕ original[0] = 1 ## 解法 - - -**方法一:位运算** +### 方法一:位运算 我们不妨假设原始二进制数组为 $a$,派生数组为 $b$,那么有: @@ -88,20 +86,12 @@ $$ -### **Python3** - - - ```python class Solution: def doesValidArrayExist(self, derived: List[int]) -> bool: return reduce(xor, derived) == 0 ``` -### **Java** - - - ```java class Solution { public boolean doesValidArrayExist(int[] derived) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func doesValidArrayExist(derived []int) bool { s := 0 @@ -141,8 +127,6 @@ func doesValidArrayExist(derived []int) bool { } ``` -### **TypeScript** - ```ts function doesValidArrayExist(derived: number[]): boolean { let s = 0; @@ -153,16 +137,18 @@ function doesValidArrayExist(derived: number[]): boolean { } ``` + + +### 方法二 + + + ```ts function doesValidArrayExist(derived: number[]): boolean { return derived.reduce((acc, x) => acc ^ x, 0) === 0; } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2683.Neighboring Bitwise XOR/README_EN.md b/solution/2600-2699/2683.Neighboring Bitwise XOR/README_EN.md index 16d0a4231560e..57c5c0d363abf 100644 --- a/solution/2600-2699/2683.Neighboring Bitwise XOR/README_EN.md +++ b/solution/2600-2699/2683.Neighboring Bitwise XOR/README_EN.md @@ -62,9 +62,9 @@ derived[1] = original[1] ⊕ original[0] = 1 ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return reduce(xor, derived) == 0 ``` -### **Java** - ```java class Solution { public boolean doesValidArrayExist(int[] derived) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +97,6 @@ public: }; ``` -### **Go** - ```go func doesValidArrayExist(derived []int) bool { s := 0 @@ -113,8 +107,6 @@ func doesValidArrayExist(derived []int) bool { } ``` -### **TypeScript** - ```ts function doesValidArrayExist(derived: number[]): boolean { let s = 0; @@ -125,16 +117,18 @@ function doesValidArrayExist(derived: number[]): boolean { } ``` + + +### Solution 2 + + + ```ts function doesValidArrayExist(derived: number[]): boolean { return derived.reduce((acc, x) => acc ^ x, 0) === 0; } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2684.Maximum Number of Moves in a Grid/README.md b/solution/2600-2699/2684.Maximum Number of Moves in a Grid/README.md index c0a4da5b5f9aa..f5087a22a4114 100644 --- a/solution/2600-2699/2684.Maximum Number of Moves in a Grid/README.md +++ b/solution/2600-2699/2684.Maximum Number of Moves in a Grid/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:BFS** +### 方法一:BFS 我们定义一个队列 $q$,初始时将第一列的所有单元格 $(i, 0)$ 加入队列,同时定义一个二维数组 $dist$,其中 $dist[i][j]$ 表示到达单元格 $(i, j)$ 的最大移动次数。初始时,$dist[i][j] = 0$。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def maxMoves(self, grid: List[List[int]]) -> int: @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxMoves(int[][] grid) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func maxMoves(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -186,10 +172,6 @@ func maxMoves(grid [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2684.Maximum Number of Moves in a Grid/README_EN.md b/solution/2600-2699/2684.Maximum Number of Moves in a Grid/README_EN.md index cc47482a0060e..6c4b332713f68 100644 --- a/solution/2600-2699/2684.Maximum Number of Moves in a Grid/README_EN.md +++ b/solution/2600-2699/2684.Maximum Number of Moves in a Grid/README_EN.md @@ -48,9 +48,9 @@ It can be shown that it is the maximum number of moves that can be made. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -76,8 +76,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxMoves(int[][] grid) { @@ -107,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +135,6 @@ public: }; ``` -### **Go** - ```go func maxMoves(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) @@ -168,10 +162,6 @@ func maxMoves(grid [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2685.Count the Number of Complete Components/README.md b/solution/2600-2699/2685.Count the Number of Complete Components/README.md index 5b6cda41a446f..d2960431b39d1 100644 --- a/solution/2600-2699/2685.Count the Number of Complete Components/README.md +++ b/solution/2600-2699/2685.Count the Number of Complete Components/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们先根据题目给定的边建立一个邻接表 $g$,其中 $g[i]$ 表示顶点 $i$ 的邻接点集合。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def countCompleteComponents(self, n: int, edges: List[List[int]]) -> int: @@ -97,10 +91,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -142,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +170,6 @@ public: }; ``` -### **Go** - ```go func countCompleteComponents(n int, edges [][]int) (ans int) { g := make([][]int, n) @@ -218,10 +204,6 @@ func countCompleteComponents(n int, edges [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2685.Count the Number of Complete Components/README_EN.md b/solution/2600-2699/2685.Count the Number of Complete Components/README_EN.md index 5a71be9b29294..9458fd129e5f3 100644 --- a/solution/2600-2699/2685.Count the Number of Complete Components/README_EN.md +++ b/solution/2600-2699/2685.Count the Number of Complete Components/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -120,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +156,6 @@ public: }; ``` -### **Go** - ```go func countCompleteComponents(n int, edges [][]int) (ans int) { g := make([][]int, n) @@ -196,10 +190,6 @@ func countCompleteComponents(n int, edges [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2686.Immediate Food Delivery III/README.md b/solution/2600-2699/2686.Immediate Food Delivery III/README.md index e8e20a3417b84..51c3717e12bb8 100644 --- a/solution/2600-2699/2686.Immediate Food Delivery III/README.md +++ b/solution/2600-2699/2686.Immediate Food Delivery III/README.md @@ -70,14 +70,10 @@ order_dste 按升序排序。 ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT order_date @@ -88,3 +84,5 @@ ORDER BY order_date ``` + + diff --git a/solution/2600-2699/2686.Immediate Food Delivery III/README_EN.md b/solution/2600-2699/2686.Immediate Food Delivery III/README_EN.md index efcad4c20db53..9dc091746b1e3 100644 --- a/solution/2600-2699/2686.Immediate Food Delivery III/README_EN.md +++ b/solution/2600-2699/2686.Immediate Food Delivery III/README_EN.md @@ -66,9 +66,9 @@ order_date is sorted in ascending order. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -80,3 +80,5 @@ ORDER BY order_date ``` + + diff --git a/solution/2600-2699/2687.Bikes Last Time Used/README.md b/solution/2600-2699/2687.Bikes Last Time Used/README.md index 55951b9bdf663..e792cbbb90da2 100644 --- a/solution/2600-2699/2687.Bikes Last Time Used/README.md +++ b/solution/2600-2699/2687.Bikes Last Time Used/README.md @@ -61,14 +61,10 @@ ride_id 是该表的主键。 ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -80,3 +76,5 @@ ORDER BY end_time DESC; ``` + + diff --git a/solution/2600-2699/2687.Bikes Last Time Used/README_EN.md b/solution/2600-2699/2687.Bikes Last Time Used/README_EN.md index dbaaba8a0a878..c06248486051f 100644 --- a/solution/2600-2699/2687.Bikes Last Time Used/README_EN.md +++ b/solution/2600-2699/2687.Bikes Last Time Used/README_EN.md @@ -61,9 +61,9 @@ Returning output in order by the bike that were most recently used. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -76,3 +76,5 @@ ORDER BY end_time DESC; ``` + + diff --git a/solution/2600-2699/2688.Find Active Users/README.md b/solution/2600-2699/2688.Find Active Users/README.md index 07d931af63848..66ddd6b554930 100644 --- a/solution/2600-2699/2688.Find Active Users/README.md +++ b/solution/2600-2699/2688.Find Active Users/README.md @@ -59,14 +59,10 @@ ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement SELECT DISTINCT @@ -92,3 +88,5 @@ WHERE ``` + + diff --git a/solution/2600-2699/2688.Find Active Users/README_EN.md b/solution/2600-2699/2688.Find Active Users/README_EN.md index a4f61c5340f6d..d87a8c1b54b2e 100644 --- a/solution/2600-2699/2688.Find Active Users/README_EN.md +++ b/solution/2600-2699/2688.Find Active Users/README_EN.md @@ -58,9 +58,9 @@ Each row includes the user ID, the purchased item, the date of purchase, and the ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement @@ -87,3 +87,5 @@ WHERE ``` + + diff --git a/solution/2600-2699/2689.Extract Kth Character From The Rope Tree/README.md b/solution/2600-2699/2689.Extract Kth Character From The Rope Tree/README.md index 67de4f08bafb4..ce7c99938a441 100644 --- a/solution/2600-2699/2689.Extract Kth Character From The Rope Tree/README.md +++ b/solution/2600-2699/2689.Extract Kth Character From The Rope Tree/README.md @@ -72,9 +72,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们可以使用深度优先搜索的方法,定义一个函数 $dfs(root)$,表示从根节点开始搜索,返回以 $root$ 为根节点的子树的字符串。那么答案就是 $dfs(root)[k-1]$。 @@ -88,10 +86,6 @@ -### **Python3** - - - ```python # Definition for a rope tree node. # class RopeTreeNode(object): @@ -112,10 +106,6 @@ class Solution: return dfs(root)[k - 1] ``` -### **Java** - - - ```java /** * Definition for a rope tree node. @@ -160,8 +150,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a rope tree node. @@ -195,8 +183,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a rope tree node. @@ -223,10 +209,6 @@ func getKthCharacter(root *RopeTreeNode, k int) byte { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2689.Extract Kth Character From The Rope Tree/README_EN.md b/solution/2600-2699/2689.Extract Kth Character From The Rope Tree/README_EN.md index ddd961293ea8d..8fdc10bcaadaa 100644 --- a/solution/2600-2699/2689.Extract Kth Character From The Rope Tree/README_EN.md +++ b/solution/2600-2699/2689.Extract Kth Character From The Rope Tree/README_EN.md @@ -71,9 +71,9 @@ You can see that S[root] = "ropetree". So S[root][7], which represents ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a rope tree node. @@ -95,8 +95,6 @@ class Solution: return dfs(root)[k - 1] ``` -### **Java** - ```java /** * Definition for a rope tree node. @@ -141,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a rope tree node. @@ -176,8 +172,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a rope tree node. @@ -204,10 +198,6 @@ func getKthCharacter(root *RopeTreeNode, k int) byte { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2690.Infinite Method Object/README.md b/solution/2600-2699/2690.Infinite Method Object/README.md index 5a2c26c7685db..13a4a4d282f4a 100644 --- a/solution/2600-2699/2690.Infinite Method Object/README.md +++ b/solution/2600-2699/2690.Infinite Method Object/README.md @@ -41,14 +41,10 @@ obj['abc123'](); // "abc123" ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function createInfiniteObject(): Record string> { return new Proxy( @@ -66,3 +62,5 @@ function createInfiniteObject(): Record string> { ``` + + diff --git a/solution/2600-2699/2690.Infinite Method Object/README_EN.md b/solution/2600-2699/2690.Infinite Method Object/README_EN.md index f77c64b1bb92f..dd71e2dcdb44c 100644 --- a/solution/2600-2699/2690.Infinite Method Object/README_EN.md +++ b/solution/2600-2699/2690.Infinite Method Object/README_EN.md @@ -37,9 +37,9 @@ The returned string should always match the method name. ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function createInfiniteObject(): Record string> { @@ -58,3 +58,5 @@ function createInfiniteObject(): Record string> { ``` + + diff --git a/solution/2600-2699/2691.Immutability Helper/README.md b/solution/2600-2699/2691.Immutability Helper/README.md index 75ad3bf5e4906..18a7daafbf875 100644 --- a/solution/2600-2699/2691.Immutability Helper/README.md +++ b/solution/2600-2699/2691.Immutability Helper/README.md @@ -106,16 +106,4 @@ mutators = [ ## 解法 - - - - -### **TypeScript** - - - -```ts - -``` - - + diff --git a/solution/2600-2699/2691.Immutability Helper/README_EN.md b/solution/2600-2699/2691.Immutability Helper/README_EN.md index e8293902adf91..dbc309fffe287 100644 --- a/solution/2600-2699/2691.Immutability Helper/README_EN.md +++ b/solution/2600-2699/2691.Immutability Helper/README_EN.md @@ -103,12 +103,4 @@ mutators = [ ## Solutions - - -### **TypeScript** - -```ts - -``` - - + diff --git a/solution/2600-2699/2692.Make Object Immutable/README.md b/solution/2600-2699/2692.Make Object Immutable/README.md index 3ae9d18e5c987..752d5b366aaca 100644 --- a/solution/2600-2699/2692.Make Object Immutable/README.md +++ b/solution/2600-2699/2692.Make Object Immutable/README.md @@ -92,14 +92,10 @@ fn = (obj) => { ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts type Obj = Array | Record; @@ -142,3 +138,5 @@ function makeImmutable(obj: Obj): Obj { ``` + + diff --git a/solution/2600-2699/2692.Make Object Immutable/README_EN.md b/solution/2600-2699/2692.Make Object Immutable/README_EN.md index 67e54db3b4f19..356b60e0035c8 100644 --- a/solution/2600-2699/2692.Make Object Immutable/README_EN.md +++ b/solution/2600-2699/2692.Make Object Immutable/README_EN.md @@ -89,9 +89,9 @@ fn = (obj) => { ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type Obj = Array | Record; @@ -135,3 +135,5 @@ function makeImmutable(obj: Obj): Obj { ``` + + diff --git a/solution/2600-2699/2693.Call Function with Custom Context/README.md b/solution/2600-2699/2693.Call Function with Custom Context/README.md index 3efbb345616ac..268dbe182c07f 100644 --- a/solution/2600-2699/2693.Call Function with Custom Context/README.md +++ b/solution/2600-2699/2693.Call Function with Custom Context/README.md @@ -63,14 +63,10 @@ args = [{"item": "burger"}, 10, 1,1] ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts declare global { interface Function { @@ -90,3 +86,5 @@ Function.prototype.callPolyfill = function (context, ...args): any { ``` + + diff --git a/solution/2600-2699/2693.Call Function with Custom Context/README_EN.md b/solution/2600-2699/2693.Call Function with Custom Context/README_EN.md index 97c0eebb69fce..f53d1ed19a468 100644 --- a/solution/2600-2699/2693.Call Function with Custom Context/README_EN.md +++ b/solution/2600-2699/2693.Call Function with Custom Context/README_EN.md @@ -59,9 +59,9 @@ args = [{"item": "burger"}, 10, 1.1] ## Solutions - +### Solution 1 -### **TypeScript** + ```ts declare global { @@ -82,3 +82,5 @@ Function.prototype.callPolyfill = function (context, ...args): any { ``` + + diff --git a/solution/2600-2699/2694.Event Emitter/README.md b/solution/2600-2699/2694.Event Emitter/README.md index 7763329fabaf5..c50100de0cf6f 100644 --- a/solution/2600-2699/2694.Event Emitter/README.md +++ b/solution/2600-2699/2694.Event Emitter/README.md @@ -92,14 +92,10 @@ emitter.emit("firstEvent", [5]); // [7] ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts type Callback = (...args: any[]) => any; type Subscription = { @@ -141,3 +137,5 @@ class EventEmitter { ``` + + diff --git a/solution/2600-2699/2694.Event Emitter/README_EN.md b/solution/2600-2699/2694.Event Emitter/README_EN.md index e439bcd1df755..3e597a5784fed 100644 --- a/solution/2600-2699/2694.Event Emitter/README_EN.md +++ b/solution/2600-2699/2694.Event Emitter/README_EN.md @@ -91,9 +91,9 @@ emitter.emit("firstEvent", [5]); // [7] ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type Callback = (...args: any[]) => any; @@ -136,3 +136,5 @@ class EventEmitter { ``` + + diff --git a/solution/2600-2699/2695.Array Wrapper/README.md b/solution/2600-2699/2695.Array Wrapper/README.md index 45593dbc6eb11..d9a1717217204 100644 --- a/solution/2600-2699/2695.Array Wrapper/README.md +++ b/solution/2600-2699/2695.Array Wrapper/README.md @@ -59,14 +59,10 @@ obj1 + obj2; // 0 ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts class ArrayWrapper { private nums: number[]; @@ -96,3 +92,5 @@ class ArrayWrapper { ``` + + diff --git a/solution/2600-2699/2695.Array Wrapper/README_EN.md b/solution/2600-2699/2695.Array Wrapper/README_EN.md index bd050af5304de..dba9bdd9bfafd 100644 --- a/solution/2600-2699/2695.Array Wrapper/README_EN.md +++ b/solution/2600-2699/2695.Array Wrapper/README_EN.md @@ -55,9 +55,9 @@ obj1 + obj2; // 0 ## Solutions - +### Solution 1 -### **TypeScript** + ```ts class ArrayWrapper { @@ -88,3 +88,5 @@ class ArrayWrapper { ``` + + diff --git a/solution/2600-2699/2696.Minimum String Length After Removing Substrings/README.md b/solution/2600-2699/2696.Minimum String Length After Removing Substrings/README.md index 953d13adc5d86..1ea9c7aa4a9a4 100644 --- a/solution/2600-2699/2696.Minimum String Length After Removing Substrings/README.md +++ b/solution/2600-2699/2696.Minimum String Length After Removing Substrings/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:栈** +### 方法一:栈 我们遍历字符串 $s$,对于当前遍历到的字符 $c$,如果栈不为空且栈顶元素 $top$ 与 $c$ 可以组成 $AB$ 或 $CD$,则弹出栈顶元素,否则将 $c$ 入栈。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def minLength(self, s: str) -> int: @@ -77,10 +71,6 @@ class Solution: return len(stk) - 1 ``` -### **Java** - - - ```java class Solution { public int minLength(String s) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func minLength(s string) int { stk := []byte{' '} @@ -133,8 +119,6 @@ func minLength(s string) int { } ``` -### **TypeScript** - ```ts function minLength(s: string): number { const stk: string[] = ['']; @@ -151,8 +135,6 @@ function minLength(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_length(s: String) -> i32 { @@ -177,10 +159,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2696.Minimum String Length After Removing Substrings/README_EN.md b/solution/2600-2699/2696.Minimum String Length After Removing Substrings/README_EN.md index 3da6fa695a1ce..afb12d3bd4f17 100644 --- a/solution/2600-2699/2696.Minimum String Length After Removing Substrings/README_EN.md +++ b/solution/2600-2699/2696.Minimum String Length After Removing Substrings/README_EN.md @@ -43,7 +43,7 @@ It can be shown that it is the minimum length that we can obtain. ## Solutions -**Solution 1: Stack** +### Solution 1: Stack We traverse the string $s$. For the current character $c$ we are traversing, if the stack is not empty and the top element of the stack $top$ can form $AB$ or $CD$ with $c$, then we pop the top element of the stack, otherwise we push $c$ into the stack. @@ -55,8 +55,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is -### **Python3** - ```python class Solution: def minLength(self, s: str) -> int: @@ -69,8 +67,6 @@ class Solution: return len(stk) - 1 ``` -### **Java** - ```java class Solution { public int minLength(String s) { @@ -88,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +101,6 @@ public: }; ``` -### **Go** - ```go func minLength(s string) int { stk := []byte{' '} @@ -123,8 +115,6 @@ func minLength(s string) int { } ``` -### **TypeScript** - ```ts function minLength(s: string): number { const stk: string[] = ['']; @@ -141,8 +131,6 @@ function minLength(s: string): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_length(s: String) -> i32 { @@ -167,10 +155,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2697.Lexicographically Smallest Palindrome/README.md b/solution/2600-2699/2697.Lexicographically Smallest Palindrome/README.md index f9b8a4583f711..14bd19de1f7a1 100644 --- a/solution/2600-2699/2697.Lexicographically Smallest Palindrome/README.md +++ b/solution/2600-2699/2697.Lexicographically Smallest Palindrome/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:贪心 + 双指针** +### 方法一:贪心 + 双指针 我们用两个指针 $i$ 和 $j$ 分别指向字符串的首尾,初始时 $i = 0$, $j = n - 1$。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def makeSmallestPalindrome(self, s: str) -> str: @@ -77,10 +71,6 @@ class Solution: return "".join(cs) ``` -### **Java** - - - ```java class Solution { public String makeSmallestPalindrome(String s) { @@ -93,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func makeSmallestPalindrome(s string) string { cs := []byte(s) @@ -120,8 +106,6 @@ func makeSmallestPalindrome(s string) string { } ``` -### **TypeScript** - ```ts function makeSmallestPalindrome(s: string): string { const cs = s.split(''); @@ -132,8 +116,6 @@ function makeSmallestPalindrome(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn make_smallest_palindrome(s: String) -> String { @@ -149,10 +131,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2697.Lexicographically Smallest Palindrome/README_EN.md b/solution/2600-2699/2697.Lexicographically Smallest Palindrome/README_EN.md index 7a74d964ba58a..628f4a856b34e 100644 --- a/solution/2600-2699/2697.Lexicographically Smallest Palindrome/README_EN.md +++ b/solution/2600-2699/2697.Lexicographically Smallest Palindrome/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Greedy + Two Pointers** +### Solution 1: Greedy + Two Pointers We use two pointers $i$ and $j$ to point to the beginning and end of the string, initially $i = 0$, $j = n - 1$. @@ -57,8 +57,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def makeSmallestPalindrome(self, s: str) -> str: @@ -70,8 +68,6 @@ class Solution: return "".join(cs) ``` -### **Java** - ```java class Solution { public String makeSmallestPalindrome(String s) { @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +92,6 @@ public: }; ``` -### **Go** - ```go func makeSmallestPalindrome(s string) string { cs := []byte(s) @@ -111,8 +103,6 @@ func makeSmallestPalindrome(s string) string { } ``` -### **TypeScript** - ```ts function makeSmallestPalindrome(s: string): string { const cs = s.split(''); @@ -123,8 +113,6 @@ function makeSmallestPalindrome(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn make_smallest_palindrome(s: String) -> String { @@ -140,10 +128,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2698.Find the Punishment Number of an Integer/README.md b/solution/2600-2699/2698.Find the Punishment Number of an Integer/README.md index 0a1310751196e..dbf1464753a77 100644 --- a/solution/2600-2699/2698.Find the Punishment Number of an Integer/README.md +++ b/solution/2600-2699/2698.Find the Punishment Number of an Integer/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:枚举 + DFS** +### 方法一:枚举 + DFS 我们枚举 $i$,其中 $1 \leq i \leq n$,对于每个 $i$,我们将 $x = i^2$ 的十进制表示的字符串进行分割,然后判断是否满足题目要求。如果满足,我们就将 $x$ 累加到答案中。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def punishmentNumber(self, n: int) -> int: @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int punishmentNumber(int n) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -166,8 +154,6 @@ public: }; ``` -### **Go** - ```go func punishmentNumber(n int) (ans int) { var check func(string, int, int) bool @@ -199,8 +185,6 @@ func punishmentNumber(n int) (ans int) { } ``` -### **TypeScript** - ```ts function punishmentNumber(n: number): number { const check = (s: string, i: number, x: number): boolean => { @@ -232,10 +216,6 @@ function punishmentNumber(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2698.Find the Punishment Number of an Integer/README_EN.md b/solution/2600-2699/2698.Find the Punishment Number of an Integer/README_EN.md index 2f22cd1f4a122..487d102e52171 100644 --- a/solution/2600-2699/2698.Find the Punishment Number of an Integer/README_EN.md +++ b/solution/2600-2699/2698.Find the Punishment Number of an Integer/README_EN.md @@ -48,7 +48,7 @@ Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478 ## Solutions -**Solution 1: Enumeration + DFS** +### Solution 1: Enumeration + DFS We enumerate $i$, where $1 \leq i \leq n$. For each $i$, we split the decimal representation string of $x = i^2$, and then check whether it meets the requirements of the problem. If it does, we add $x$ to the answer. @@ -58,8 +58,6 @@ The time complexity is $O(n^{1 + 2 \log_{10}^2})$, and the space complexity is $ -### **Python3** - ```python class Solution: def punishmentNumber(self, n: int) -> int: @@ -84,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int punishmentNumber(int n) { @@ -119,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +150,6 @@ public: }; ``` -### **Go** - ```go func punishmentNumber(n int) (ans int) { var check func(string, int, int) bool @@ -189,8 +181,6 @@ func punishmentNumber(n int) (ans int) { } ``` -### **TypeScript** - ```ts function punishmentNumber(n: number): number { const check = (s: string, i: number, x: number): boolean => { @@ -222,10 +212,6 @@ function punishmentNumber(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2699.Modify Graph Edge Weights/README.md b/solution/2600-2699/2699.Modify Graph Edge Weights/README.md index 4123b81c8c063..788a64d7cca7c 100644 --- a/solution/2600-2699/2699.Modify Graph Edge Weights/README.md +++ b/solution/2600-2699/2699.Modify Graph Edge Weights/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:最短路(Dijkstra 算法)** +### 方法一:最短路(Dijkstra 算法) 我们先不考虑边权为 $-1$ 的边,使用 Dijkstra 算法求出从 $source$ 到 $destination$ 的最短距离 $d$。 @@ -86,10 +84,6 @@ -### **Python3** - - - ```python class Solution: def modifiedGraphEdges( @@ -133,10 +127,6 @@ class Solution: return edges if ok else [] ``` -### **Java** - - - ```java class Solution { private final int inf = 2000000000; @@ -200,8 +190,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; const int inf = 2e9; @@ -267,8 +255,6 @@ public: }; ``` -### **Go** - ```go func modifiedGraphEdges(n int, edges [][]int, source int, destination int, target int) [][]int { const inf int = 2e9 @@ -332,8 +318,6 @@ func modifiedGraphEdges(n int, edges [][]int, source int, destination int, targe } ``` -### **TypeScript** - ```ts function modifiedGraphEdges( n: number, @@ -395,10 +379,6 @@ function modifiedGraphEdges( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2600-2699/2699.Modify Graph Edge Weights/README_EN.md b/solution/2600-2699/2699.Modify Graph Edge Weights/README_EN.md index cee975e8c8f61..608ae0f935564 100644 --- a/solution/2600-2699/2699.Modify Graph Edge Weights/README_EN.md +++ b/solution/2600-2699/2699.Modify Graph Edge Weights/README_EN.md @@ -63,7 +63,7 @@ ## Solutions -**Solution 1: Shortest Path (Dijkstra's Algorithm)** +### Solution 1: Shortest Path (Dijkstra's Algorithm) First, we ignore the edges with a weight of $-1$ and use Dijkstra's algorithm to find the shortest distance $d$ from $source$ to $destination$. @@ -80,8 +80,6 @@ The time complexity is $O(n^3)$, and the space complexity is $O(n^2)$, where $n$ -### **Python3** - ```python class Solution: def modifiedGraphEdges( @@ -125,8 +123,6 @@ class Solution: return edges if ok else [] ``` -### **Java** - ```java class Solution { private final int inf = 2000000000; @@ -190,8 +186,6 @@ class Solution { } ``` -### **C++** - ```cpp using ll = long long; const int inf = 2e9; @@ -257,8 +251,6 @@ public: }; ``` -### **Go** - ```go func modifiedGraphEdges(n int, edges [][]int, source int, destination int, target int) [][]int { const inf int = 2e9 @@ -322,8 +314,6 @@ func modifiedGraphEdges(n int, edges [][]int, source int, destination int, targe } ``` -### **TypeScript** - ```ts function modifiedGraphEdges( n: number, @@ -385,10 +375,6 @@ function modifiedGraphEdges( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2700.Differences Between Two Objects/README.md b/solution/2700-2799/2700.Differences Between Two Objects/README.md index 40b925442834f..18974b3273946 100644 --- a/solution/2700-2799/2700.Differences Between Two Objects/README.md +++ b/solution/2700-2799/2700.Differences Between Two Objects/README.md @@ -131,14 +131,10 @@ obj2 = {   ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function objDiff(obj1: any, obj2: any): any { if (type(obj1) !== type(obj2)) return [obj1, obj2]; @@ -162,3 +158,5 @@ function isObject(obj: unknown): obj is Record { ``` + + diff --git a/solution/2700-2799/2700.Differences Between Two Objects/README_EN.md b/solution/2700-2799/2700.Differences Between Two Objects/README_EN.md index fd6cde0bd89af..f08e2595af875 100644 --- a/solution/2700-2799/2700.Differences Between Two Objects/README_EN.md +++ b/solution/2700-2799/2700.Differences Between Two Objects/README_EN.md @@ -127,9 +127,9 @@ obj2 = {   ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function objDiff(obj1: any, obj2: any): any { @@ -154,3 +154,5 @@ function isObject(obj: unknown): obj is Record { ``` + + diff --git a/solution/2700-2799/2701.Consecutive Transactions with Increasing Amounts/README.md b/solution/2700-2799/2701.Consecutive Transactions with Increasing Amounts/README.md index fd108e1305527..de9802afa3650 100644 --- a/solution/2700-2799/2701.Consecutive Transactions with Increasing Amounts/README.md +++ b/solution/2700-2799/2701.Consecutive Transactions with Increasing Amounts/README.md @@ -67,14 +67,10 @@ Transactions 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -105,3 +101,5 @@ ORDER BY customer_id; ``` + + diff --git a/solution/2700-2799/2701.Consecutive Transactions with Increasing Amounts/README_EN.md b/solution/2700-2799/2701.Consecutive Transactions with Increasing Amounts/README_EN.md index d934e00e60ecb..0d82ede27f664 100644 --- a/solution/2700-2799/2701.Consecutive Transactions with Increasing Amounts/README_EN.md +++ b/solution/2700-2799/2701.Consecutive Transactions with Increasing Amounts/README_EN.md @@ -67,9 +67,9 @@ customer_id is sorted in ascending order. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -101,3 +101,5 @@ ORDER BY customer_id; ``` + + diff --git a/solution/2700-2799/2702.Minimum Operations to Make Numbers Non-positive/README.md b/solution/2700-2799/2702.Minimum Operations to Make Numbers Non-positive/README.md index 809716adf6560..64277aad5cee7 100644 --- a/solution/2700-2799/2702.Minimum Operations to Make Numbers Non-positive/README.md +++ b/solution/2700-2799/2702.Minimum Operations to Make Numbers Non-positive/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们注意到,如果一个操作次数 $t$ 能够使得所有的数都小于等于 $0$,那么对于任意 $t' > t$,操作次数 $t'$ 也能够使得所有的数都小于等于 $0$。因此我们可以使用二分查找的方法找到最小的操作次数。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, nums: List[int], x: int, y: int) -> int: @@ -89,10 +83,6 @@ class Solution: return l ``` -### **Java** - - - ```java class Solution { private int[] nums; @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +147,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int, x int, y int) int { check := func(t int) bool { @@ -186,8 +172,6 @@ func minOperations(nums []int, x int, y int) int { } ``` -### **TypeScript** - ```ts function minOperations(nums: number[], x: number, y: number): number { let l = 0; @@ -213,10 +197,6 @@ function minOperations(nums: number[], x: number, y: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2702.Minimum Operations to Make Numbers Non-positive/README_EN.md b/solution/2700-2799/2702.Minimum Operations to Make Numbers Non-positive/README_EN.md index 37bef1e3edb99..052c70e798514 100644 --- a/solution/2700-2799/2702.Minimum Operations to Make Numbers Non-positive/README_EN.md +++ b/solution/2700-2799/2702.Minimum Operations to Make Numbers Non-positive/README_EN.md @@ -45,7 +45,7 @@ Now, all the numbers in nums are non-positive. Therefore, we return 3. ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search We notice that if an operation count $t$ can make all numbers less than or equal to $0$, then for any $t' > t$, the operation count $t'$ can also make all numbers less than or equal to $0$. Therefore, we can use binary search to find the minimum operation count. @@ -53,8 +53,6 @@ We define the left boundary of the binary search as $l=0$, and the right boundar -### **Python3** - ```python class Solution: def minOperations(self, nums: List[int], x: int, y: int) -> int: @@ -75,8 +73,6 @@ class Solution: return l ``` -### **Java** - ```java class Solution { private int[] nums; @@ -114,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +137,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int, x int, y int) int { check := func(t int) bool { @@ -170,8 +162,6 @@ func minOperations(nums []int, x int, y int) int { } ``` -### **TypeScript** - ```ts function minOperations(nums: number[], x: number, y: number): number { let l = 0; @@ -197,10 +187,6 @@ function minOperations(nums: number[], x: number, y: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2703.Return Length of Arguments Passed/README.md b/solution/2700-2799/2703.Return Length of Arguments Passed/README.md index 7675b467881c0..0b4c5c0ecced5 100644 --- a/solution/2700-2799/2703.Return Length of Arguments Passed/README.md +++ b/solution/2700-2799/2703.Return Length of Arguments Passed/README.md @@ -43,14 +43,10 @@ argumentsLength({}, null, "3"); // 3 ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function argumentsLength(...args: any[]): number { return args.length; @@ -62,3 +58,5 @@ function argumentsLength(...args: any[]): number { ``` + + diff --git a/solution/2700-2799/2703.Return Length of Arguments Passed/README_EN.md b/solution/2700-2799/2703.Return Length of Arguments Passed/README_EN.md index 5eb2e583b52cd..1cb1663be5fb8 100644 --- a/solution/2700-2799/2703.Return Length of Arguments Passed/README_EN.md +++ b/solution/2700-2799/2703.Return Length of Arguments Passed/README_EN.md @@ -39,9 +39,9 @@ Three values were passed to the function so it should return 3. ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function argumentsLength(...args: any[]): number { @@ -54,3 +54,5 @@ function argumentsLength(...args: any[]): number { ``` + + diff --git a/solution/2700-2799/2704.To Be Or Not To Be/README.md b/solution/2700-2799/2704.To Be Or Not To Be/README.md index b2886c92bf09b..06a9dcf77976c 100644 --- a/solution/2700-2799/2704.To Be Or Not To Be/README.md +++ b/solution/2700-2799/2704.To Be Or Not To Be/README.md @@ -41,14 +41,10 @@ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts type ToBeOrNotToBe = { toBe: (val: any) => boolean; @@ -78,8 +74,6 @@ function expect(val: any): ToBeOrNotToBe { */ ``` -### **JavaScript** - ```js /** * @param {string} val @@ -109,3 +103,5 @@ var expect = function (val) { ``` + + diff --git a/solution/2700-2799/2704.To Be Or Not To Be/README_EN.md b/solution/2700-2799/2704.To Be Or Not To Be/README_EN.md index 03b770d5d16ed..fcdbcc15341c9 100644 --- a/solution/2700-2799/2704.To Be Or Not To Be/README_EN.md +++ b/solution/2700-2799/2704.To Be Or Not To Be/README_EN.md @@ -38,9 +38,9 @@ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type ToBeOrNotToBe = { @@ -71,8 +71,6 @@ function expect(val: any): ToBeOrNotToBe { */ ``` -### **JavaScript** - ```js /** * @param {string} val @@ -102,3 +100,5 @@ var expect = function (val) { ``` + + diff --git a/solution/2700-2799/2705.Compact Object/README.md b/solution/2700-2799/2705.Compact Object/README.md index d51d772a4d59a..d76f27b73ccee 100644 --- a/solution/2700-2799/2705.Compact Object/README.md +++ b/solution/2700-2799/2705.Compact Object/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:递归** +### 方法一:递归 如果 `obj` 不是对象或为空,函数会原封不动地返回,因为无需检查非对象值中的键。 @@ -60,9 +58,27 @@ -### **JavaScript** +```ts +type Obj = Record; - +function compactObject(obj: Obj): Obj { + if (Array.isArray(obj)) { + const temp = []; + for (const item of obj) { + if (item) { + if (typeof item === 'object') temp.push(compactObject(item)); + else temp.push(item); + } + } + return temp; + } + for (const [key, value] of Object.entries(obj)) { + if (!value) delete obj[key]; + else if (typeof value === 'object') obj[key] = compactObject(value); + } + return obj; +} +``` ```js var compactObject = function (obj) { @@ -85,30 +101,6 @@ var compactObject = function (obj) { }; ``` -### **TypeScript** - - - -```ts -type Obj = Record; - -function compactObject(obj: Obj): Obj { - if (Array.isArray(obj)) { - const temp = []; - for (const item of obj) { - if (item) { - if (typeof item === 'object') temp.push(compactObject(item)); - else temp.push(item); - } - } - return temp; - } - for (const [key, value] of Object.entries(obj)) { - if (!value) delete obj[key]; - else if (typeof value === 'object') obj[key] = compactObject(value); - } - return obj; -} -``` - + + diff --git a/solution/2700-2799/2705.Compact Object/README_EN.md b/solution/2700-2799/2705.Compact Object/README_EN.md index 4723812fbe679..efc447beb22bc 100644 --- a/solution/2700-2799/2705.Compact Object/README_EN.md +++ b/solution/2700-2799/2705.Compact Object/README_EN.md @@ -42,32 +42,9 @@ ## Solutions - - -### **JavaScript** - -```js -var compactObject = function (obj) { - if (obj === null || typeof obj !== 'object') { - return obj; - } - - if (Array.isArray(obj)) { - return obj.filter(Boolean).map(compactObject); - } - - const result = {}; - for (const key in obj) { - const value = compactObject(obj[key]); - if (Boolean(value)) { - result[key] = value; - } - } - return result; -}; -``` +### Solution 1 -### **TypeScript** + ```ts type Obj = Record; @@ -91,4 +68,27 @@ function compactObject(obj: Obj): Obj { } ``` +```js +var compactObject = function (obj) { + if (obj === null || typeof obj !== 'object') { + return obj; + } + + if (Array.isArray(obj)) { + return obj.filter(Boolean).map(compactObject); + } + + const result = {}; + for (const key in obj) { + const value = compactObject(obj[key]); + if (Boolean(value)) { + result[key] = value; + } + } + return result; +}; +``` + + + diff --git a/solution/2700-2799/2706.Buy Two Chocolates/README.md b/solution/2700-2799/2706.Buy Two Chocolates/README.md index be992ef4dfcbc..25eca8d69385f 100644 --- a/solution/2700-2799/2706.Buy Two Chocolates/README.md +++ b/solution/2700-2799/2706.Buy Two Chocolates/README.md @@ -40,26 +40,14 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们可以将巧克力的价格从小到大排序,然后取前两个价格相加,就是我们购买两块巧克力的最小花费 $cost$。如果这个花费大于我们拥有的钱数,那么我们就返回 `money`,否则返回 `money - cost`。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组 `prices` 的长度。 -**方法二:一次遍历** - -我们可以在一次遍历中找到最小的两个价格,然后计算花费。 - -时间复杂度 $O(n)$,其中 $n$ 是数组 `prices` 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def buyChoco(self, prices: List[int], money: int) -> int: @@ -68,6 +56,69 @@ class Solution: return money if money < cost else money - cost ``` +```java +class Solution { + public int buyChoco(int[] prices, int money) { + Arrays.sort(prices); + int cost = prices[0] + prices[1]; + return money < cost ? money : money - cost; + } +} +``` + +```cpp +class Solution { +public: + int buyChoco(vector& prices, int money) { + sort(prices.begin(), prices.end()); + int cost = prices[0] + prices[1]; + return money < cost ? money : money - cost; + } +}; +``` + +```go +func buyChoco(prices []int, money int) int { + sort.Ints(prices) + cost := prices[0] + prices[1] + if money < cost { + return money + } + return money - cost +} +``` + +```ts +function buyChoco(prices: number[], money: number): number { + prices.sort((a, b) => a - b); + const cost = prices[0] + prices[1]; + return money < cost ? money : money - cost; +} +``` + +```rust +impl Solution { + pub fn buy_choco(mut prices: Vec, money: i32) -> i32 { + prices.sort(); + let cost = prices[0] + prices[1]; + if cost > money { + return money; + } + money - cost + } +} +``` + + + +### 方法二:一次遍历 + +我们可以在一次遍历中找到最小的两个价格,然后计算花费。 + +时间复杂度 $O(n)$,其中 $n$ 是数组 `prices` 的长度。空间复杂度 $O(1)$。 + + + ```python class Solution: def buyChoco(self, prices: List[int], money: int) -> int: @@ -81,20 +132,6 @@ class Solution: return money if money < cost else money - cost ``` -### **Java** - - - -```java -class Solution { - public int buyChoco(int[] prices, int money) { - Arrays.sort(prices); - int cost = prices[0] + prices[1]; - return money < cost ? money : money - cost; - } -} -``` - ```java class Solution { public int buyChoco(int[] prices, int money) { @@ -113,19 +150,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int buyChoco(vector& prices, int money) { - sort(prices.begin(), prices.end()); - int cost = prices[0] + prices[1]; - return money < cost ? money : money - cost; - } -}; -``` - ```cpp class Solution { public: @@ -145,19 +169,6 @@ public: }; ``` -### **Go** - -```go -func buyChoco(prices []int, money int) int { - sort.Ints(prices) - cost := prices[0] + prices[1] - if money < cost { - return money - } - return money - cost -} -``` - ```go func buyChoco(prices []int, money int) int { a, b := 1001, 1001 @@ -176,16 +187,6 @@ func buyChoco(prices []int, money int) int { } ``` -### **TypeScript** - -```ts -function buyChoco(prices: number[], money: number): number { - prices.sort((a, b) => a - b); - const cost = prices[0] + prices[1]; - return money < cost ? money : money - cost; -} -``` - ```ts function buyChoco(prices: number[], money: number): number { let [a, b] = [1000, 1000]; @@ -202,21 +203,6 @@ function buyChoco(prices: number[], money: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn buy_choco(mut prices: Vec, money: i32) -> i32 { - prices.sort(); - let cost = prices[0] + prices[1]; - if cost > money { - return money; - } - money - cost - } -} -``` - ```rust impl Solution { pub fn buy_choco(prices: Vec, money: i32) -> i32 { @@ -240,10 +226,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2706.Buy Two Chocolates/README_EN.md b/solution/2700-2799/2706.Buy Two Chocolates/README_EN.md index b4fb0049d9331..4f6e42ea48fe3 100644 --- a/solution/2700-2799/2706.Buy Two Chocolates/README_EN.md +++ b/solution/2700-2799/2706.Buy Two Chocolates/README_EN.md @@ -38,22 +38,14 @@ ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting We can sort the prices of the chocolates in ascending order, and then add the first two prices to get the minimum cost $cost$ of buying two chocolates. If this cost is greater than the money we have, then we return `money`. Otherwise, we return `money - cost`. The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Where $n$ is the length of the array `prices`. -**Solution 2: One-pass Traversal** - -We can find the two smallest prices in one pass, and then calculate the cost. - -The time complexity is $O(n)$, where $n$ is the length of the array `prices`. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def buyChoco(self, prices: List[int], money: int) -> int: @@ -62,6 +54,69 @@ class Solution: return money if money < cost else money - cost ``` +```java +class Solution { + public int buyChoco(int[] prices, int money) { + Arrays.sort(prices); + int cost = prices[0] + prices[1]; + return money < cost ? money : money - cost; + } +} +``` + +```cpp +class Solution { +public: + int buyChoco(vector& prices, int money) { + sort(prices.begin(), prices.end()); + int cost = prices[0] + prices[1]; + return money < cost ? money : money - cost; + } +}; +``` + +```go +func buyChoco(prices []int, money int) int { + sort.Ints(prices) + cost := prices[0] + prices[1] + if money < cost { + return money + } + return money - cost +} +``` + +```ts +function buyChoco(prices: number[], money: number): number { + prices.sort((a, b) => a - b); + const cost = prices[0] + prices[1]; + return money < cost ? money : money - cost; +} +``` + +```rust +impl Solution { + pub fn buy_choco(mut prices: Vec, money: i32) -> i32 { + prices.sort(); + let cost = prices[0] + prices[1]; + if cost > money { + return money; + } + money - cost + } +} +``` + + + +### Solution 2: One-pass Traversal + +We can find the two smallest prices in one pass, and then calculate the cost. + +The time complexity is $O(n)$, where $n$ is the length of the array `prices`. The space complexity is $O(1)$. + + + ```python class Solution: def buyChoco(self, prices: List[int], money: int) -> int: @@ -75,18 +130,6 @@ class Solution: return money if money < cost else money - cost ``` -### **Java** - -```java -class Solution { - public int buyChoco(int[] prices, int money) { - Arrays.sort(prices); - int cost = prices[0] + prices[1]; - return money < cost ? money : money - cost; - } -} -``` - ```java class Solution { public int buyChoco(int[] prices, int money) { @@ -105,19 +148,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int buyChoco(vector& prices, int money) { - sort(prices.begin(), prices.end()); - int cost = prices[0] + prices[1]; - return money < cost ? money : money - cost; - } -}; -``` - ```cpp class Solution { public: @@ -137,19 +167,6 @@ public: }; ``` -### **Go** - -```go -func buyChoco(prices []int, money int) int { - sort.Ints(prices) - cost := prices[0] + prices[1] - if money < cost { - return money - } - return money - cost -} -``` - ```go func buyChoco(prices []int, money int) int { a, b := 1001, 1001 @@ -168,16 +185,6 @@ func buyChoco(prices []int, money int) int { } ``` -### **TypeScript** - -```ts -function buyChoco(prices: number[], money: number): number { - prices.sort((a, b) => a - b); - const cost = prices[0] + prices[1]; - return money < cost ? money : money - cost; -} -``` - ```ts function buyChoco(prices: number[], money: number): number { let [a, b] = [1000, 1000]; @@ -194,21 +201,6 @@ function buyChoco(prices: number[], money: number): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn buy_choco(mut prices: Vec, money: i32) -> i32 { - prices.sort(); - let cost = prices[0] + prices[1]; - if cost > money { - return money; - } - money - cost - } -} -``` - ```rust impl Solution { pub fn buy_choco(prices: Vec, money: i32) -> i32 { @@ -232,10 +224,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2707.Extra Characters in a String/README.md b/solution/2700-2799/2707.Extra Characters in a String/README.md index fa36e8a444be9..34f7a6ddcc939 100644 --- a/solution/2700-2799/2707.Extra Characters in a String/README.md +++ b/solution/2700-2799/2707.Extra Characters in a String/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:哈希表 + 动态规划** +### 方法一:哈希表 + 动态规划 我们可以用一个哈希表 $ss$ 记录字段中的所有单词,方便我们快速判断一个字符串是否在字典中。 @@ -62,22 +60,8 @@ $$ 时间复杂度 $O(n^3 + L)$,空间复杂度 $O(n + L)$。其中 $n$ 是字符串 $s$ 的长度,而 $L$ 是字典中所有单词的长度之和。 -**方法二:字典树 + 动态规划** - -我们可以借助字典树来优化方法一的时间复杂度。 - -具体地,我们首先将字典中的每个单词逆序插入到字典树 $root$ 中,然后我们定义 $f[i]$ 表示字符串 $s$ 的前 $i$ 个字符的最小额外字符数,初始时 $f[0] = 0$。 - -当 $i \ge 1$ 时,第 $i$ 个字符 $s[i - 1]$ 可以作为一个额外字符,此时 $f[i] = f[i - 1] + 1$;我们也可以在 $[0..i-1]$ 的范围内逆序枚举下标 $j$,判断 $s[j..i)$ 是否在字典树 $root$ 中,如果存在,那么我们可以将 $s[j..i)$ 作为一个单词,此时 $f[i] = f[j]$。 - -时间复杂度 $O(n^2 + L)$,空间复杂度 $O(n + L \times |\Sigma|)$。其中 $n$ 是字符串 $s$ 的长度,而 $L$ 是字典中所有单词的长度之和,另外 $|\Sigma|$ 是字符集的大小,本题中字符集为小写英文字母,因此 $|\Sigma| = 26$。 - -### **Python3** - - - ```python class Solution: def minExtraChar(self, s: str, dictionary: List[str]) -> int: @@ -92,6 +76,122 @@ class Solution: return f[n] ``` +```java +class Solution { + public int minExtraChar(String s, String[] dictionary) { + Set ss = new HashSet<>(); + for (String w : dictionary) { + ss.add(w); + } + int n = s.length(); + int[] f = new int[n + 1]; + f[0] = 0; + for (int i = 1; i <= n; ++i) { + f[i] = f[i - 1] + 1; + for (int j = 0; j < i; ++j) { + if (ss.contains(s.substring(j, i))) { + f[i] = Math.min(f[i], f[j]); + } + } + } + return f[n]; + } +} +``` + +```cpp +class Solution { +public: + int minExtraChar(string s, vector& dictionary) { + unordered_set ss(dictionary.begin(), dictionary.end()); + int n = s.size(); + int f[n + 1]; + f[0] = 0; + for (int i = 1; i <= n; ++i) { + f[i] = f[i - 1] + 1; + for (int j = 0; j < i; ++j) { + if (ss.count(s.substr(j, i - j))) { + f[i] = min(f[i], f[j]); + } + } + } + return f[n]; + } +}; +``` + +```go +func minExtraChar(s string, dictionary []string) int { + ss := map[string]bool{} + for _, w := range dictionary { + ss[w] = true + } + n := len(s) + f := make([]int, n+1) + for i := 1; i <= n; i++ { + f[i] = f[i-1] + 1 + for j := 0; j < i; j++ { + if ss[s[j:i]] && f[j] < f[i] { + f[i] = f[j] + } + } + } + return f[n] +} +``` + +```ts +function minExtraChar(s: string, dictionary: string[]): number { + const ss = new Set(dictionary); + const n = s.length; + const f = new Array(n + 1).fill(0); + for (let i = 1; i <= n; ++i) { + f[i] = f[i - 1] + 1; + for (let j = 0; j < i; ++j) { + if (ss.has(s.substring(j, i))) { + f[i] = Math.min(f[i], f[j]); + } + } + } + return f[n]; +} +``` + +```rust +use std::collections::HashSet; + +impl Solution { + pub fn min_extra_char(s: String, dictionary: Vec) -> i32 { + let ss: HashSet = dictionary.into_iter().collect(); + let n = s.len(); + let mut f = vec![0; n + 1]; + for i in 1..=n { + f[i] = f[i - 1] + 1; + for j in 0..i { + if ss.contains(&s[j..i]) { + f[i] = f[i].min(f[j]); + } + } + } + f[n] + } +} +``` + + + +### 方法二:字典树 + 动态规划 + +我们可以借助字典树来优化方法一的时间复杂度。 + +具体地,我们首先将字典中的每个单词逆序插入到字典树 $root$ 中,然后我们定义 $f[i]$ 表示字符串 $s$ 的前 $i$ 个字符的最小额外字符数,初始时 $f[0] = 0$。 + +当 $i \ge 1$ 时,第 $i$ 个字符 $s[i - 1]$ 可以作为一个额外字符,此时 $f[i] = f[i - 1] + 1$;我们也可以在 $[0..i-1]$ 的范围内逆序枚举下标 $j$,判断 $s[j..i)$ 是否在字典树 $root$ 中,如果存在,那么我们可以将 $s[j..i)$ 作为一个单词,此时 $f[i] = f[j]$。 + +时间复杂度 $O(n^2 + L)$,空间复杂度 $O(n + L \times |\Sigma|)$。其中 $n$ 是字符串 $s$ 的长度,而 $L$ 是字典中所有单词的长度之和,另外 $|\Sigma|$ 是字符集的大小,本题中字符集为小写英文字母,因此 $|\Sigma| = 26$。 + + + ```python class Node: __slots__ = ['children', 'is_end'] @@ -127,33 +227,6 @@ class Solution: return f[n] ``` -### **Java** - - - -```java -class Solution { - public int minExtraChar(String s, String[] dictionary) { - Set ss = new HashSet<>(); - for (String w : dictionary) { - ss.add(w); - } - int n = s.length(); - int[] f = new int[n + 1]; - f[0] = 0; - for (int i = 1; i <= n; ++i) { - f[i] = f[i - 1] + 1; - for (int j = 0; j < i; ++j) { - if (ss.contains(s.substring(j, i))) { - f[i] = Math.min(f[i], f[j]); - } - } - } - return f[n]; - } -} -``` - ```java class Node { Node[] children = new Node[26]; @@ -194,29 +267,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minExtraChar(string s, vector& dictionary) { - unordered_set ss(dictionary.begin(), dictionary.end()); - int n = s.size(); - int f[n + 1]; - f[0] = 0; - for (int i = 1; i <= n; ++i) { - f[i] = f[i - 1] + 1; - for (int j = 0; j < i; ++j) { - if (ss.count(s.substr(j, i - j))) { - f[i] = min(f[i], f[j]); - } - } - } - return f[n]; - } -}; -``` - ```cpp class Node { public: @@ -264,28 +314,6 @@ public: }; ``` -### **Go** - -```go -func minExtraChar(s string, dictionary []string) int { - ss := map[string]bool{} - for _, w := range dictionary { - ss[w] = true - } - n := len(s) - f := make([]int, n+1) - for i := 1; i <= n; i++ { - f[i] = f[i-1] + 1 - for j := 0; j < i; j++ { - if ss[s[j:i]] && f[j] < f[i] { - f[i] = f[j] - } - } - } - return f[n] -} -``` - ```go type Node struct { children [26]*Node @@ -325,25 +353,6 @@ func minExtraChar(s string, dictionary []string) int { } ``` -### **TypeScript** - -```ts -function minExtraChar(s: string, dictionary: string[]): number { - const ss = new Set(dictionary); - const n = s.length; - const f = new Array(n + 1).fill(0); - for (let i = 1; i <= n; ++i) { - f[i] = f[i - 1] + 1; - for (let j = 0; j < i; ++j) { - if (ss.has(s.substring(j, i))) { - f[i] = Math.min(f[i], f[j]); - } - } - } - return f[n]; -} -``` - ```ts class Node { children: (Node | null)[] = Array(26).fill(null); @@ -384,33 +393,6 @@ function minExtraChar(s: string, dictionary: string[]): number { } ``` -### **Rust** - -```rust -use std::collections::HashSet; - -impl Solution { - pub fn min_extra_char(s: String, dictionary: Vec) -> i32 { - let ss: HashSet = dictionary.into_iter().collect(); - let n = s.len(); - let mut f = vec![0; n + 1]; - for i in 1..=n { - f[i] = f[i - 1] + 1; - for j in 0..i { - if ss.contains(&s[j..i]) { - f[i] = f[i].min(f[j]); - } - } - } - f[n] - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2707.Extra Characters in a String/README_EN.md b/solution/2700-2799/2707.Extra Characters in a String/README_EN.md index 60681ab6ef083..289ec3d3e3e93 100644 --- a/solution/2700-2799/2707.Extra Characters in a String/README_EN.md +++ b/solution/2700-2799/2707.Extra Characters in a String/README_EN.md @@ -39,7 +39,7 @@ ## Solutions -**Solution 1: Hash Table + Dynamic Programming** +### Solution 1: Hash Table + Dynamic Programming We can use a hash table $ss$ to record all words in the dictionary, which allows us to quickly determine whether a string is in the dictionary. @@ -59,20 +59,8 @@ The final answer is $f[n]$. The time complexity is $O(n^3 + L)$, and the space complexity is $O(n + L)$. Here, $n$ is the length of string $s$, and $L$ is the sum of the lengths of all words in the dictionary. -**Solution 2: Trie + Dynamic Programming** - -We can use a trie to optimize the time complexity of Solution 1. - -Specifically, we first insert each word in the dictionary into the trie $root$ in reverse order, then we define $f[i]$ to represent the minimum number of extra characters in the first $i$ characters of string $s$, initially $f[0] = 0$. - -When $i \ge 1$, the $i$th character $s[i - 1]$ can be an extra character, in which case $f[i] = f[i - 1] + 1$. We can also enumerate the index $j$ in reverse order in the range $[0..i-1]$, and determine whether $s[j..i)$ is in the trie $root$. If it exists, then we can take $s[j..i)$ as a word, in which case $f[i] = f[j]$. - -The time complexity is $O(n^2 + L)$, and the space complexity is $O(n + L \times |\Sigma|)$. Here, $n$ is the length of string $s$, and $L$ is the sum of the lengths of all words in the dictionary. Additionally, $|\Sigma|$ is the size of the character set. In this problem, the character set is lowercase English letters, so $|\Sigma| = 26$. - -### **Python3** - ```python class Solution: def minExtraChar(self, s: str, dictionary: List[str]) -> int: @@ -87,6 +75,122 @@ class Solution: return f[n] ``` +```java +class Solution { + public int minExtraChar(String s, String[] dictionary) { + Set ss = new HashSet<>(); + for (String w : dictionary) { + ss.add(w); + } + int n = s.length(); + int[] f = new int[n + 1]; + f[0] = 0; + for (int i = 1; i <= n; ++i) { + f[i] = f[i - 1] + 1; + for (int j = 0; j < i; ++j) { + if (ss.contains(s.substring(j, i))) { + f[i] = Math.min(f[i], f[j]); + } + } + } + return f[n]; + } +} +``` + +```cpp +class Solution { +public: + int minExtraChar(string s, vector& dictionary) { + unordered_set ss(dictionary.begin(), dictionary.end()); + int n = s.size(); + int f[n + 1]; + f[0] = 0; + for (int i = 1; i <= n; ++i) { + f[i] = f[i - 1] + 1; + for (int j = 0; j < i; ++j) { + if (ss.count(s.substr(j, i - j))) { + f[i] = min(f[i], f[j]); + } + } + } + return f[n]; + } +}; +``` + +```go +func minExtraChar(s string, dictionary []string) int { + ss := map[string]bool{} + for _, w := range dictionary { + ss[w] = true + } + n := len(s) + f := make([]int, n+1) + for i := 1; i <= n; i++ { + f[i] = f[i-1] + 1 + for j := 0; j < i; j++ { + if ss[s[j:i]] && f[j] < f[i] { + f[i] = f[j] + } + } + } + return f[n] +} +``` + +```ts +function minExtraChar(s: string, dictionary: string[]): number { + const ss = new Set(dictionary); + const n = s.length; + const f = new Array(n + 1).fill(0); + for (let i = 1; i <= n; ++i) { + f[i] = f[i - 1] + 1; + for (let j = 0; j < i; ++j) { + if (ss.has(s.substring(j, i))) { + f[i] = Math.min(f[i], f[j]); + } + } + } + return f[n]; +} +``` + +```rust +use std::collections::HashSet; + +impl Solution { + pub fn min_extra_char(s: String, dictionary: Vec) -> i32 { + let ss: HashSet = dictionary.into_iter().collect(); + let n = s.len(); + let mut f = vec![0; n + 1]; + for i in 1..=n { + f[i] = f[i - 1] + 1; + for j in 0..i { + if ss.contains(&s[j..i]) { + f[i] = f[i].min(f[j]); + } + } + } + f[n] + } +} +``` + + + +### Solution 2: Trie + Dynamic Programming + +We can use a trie to optimize the time complexity of Solution 1. + +Specifically, we first insert each word in the dictionary into the trie $root$ in reverse order, then we define $f[i]$ to represent the minimum number of extra characters in the first $i$ characters of string $s$, initially $f[0] = 0$. + +When $i \ge 1$, the $i$th character $s[i - 1]$ can be an extra character, in which case $f[i] = f[i - 1] + 1$. We can also enumerate the index $j$ in reverse order in the range $[0..i-1]$, and determine whether $s[j..i)$ is in the trie $root$. If it exists, then we can take $s[j..i)$ as a word, in which case $f[i] = f[j]$. + +The time complexity is $O(n^2 + L)$, and the space complexity is $O(n + L \times |\Sigma|)$. Here, $n$ is the length of string $s$, and $L$ is the sum of the lengths of all words in the dictionary. Additionally, $|\Sigma|$ is the size of the character set. In this problem, the character set is lowercase English letters, so $|\Sigma| = 26$. + + + ```python class Node: __slots__ = ['children', 'is_end'] @@ -122,31 +226,6 @@ class Solution: return f[n] ``` -### **Java** - -```java -class Solution { - public int minExtraChar(String s, String[] dictionary) { - Set ss = new HashSet<>(); - for (String w : dictionary) { - ss.add(w); - } - int n = s.length(); - int[] f = new int[n + 1]; - f[0] = 0; - for (int i = 1; i <= n; ++i) { - f[i] = f[i - 1] + 1; - for (int j = 0; j < i; ++j) { - if (ss.contains(s.substring(j, i))) { - f[i] = Math.min(f[i], f[j]); - } - } - } - return f[n]; - } -} -``` - ```java class Node { Node[] children = new Node[26]; @@ -187,29 +266,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minExtraChar(string s, vector& dictionary) { - unordered_set ss(dictionary.begin(), dictionary.end()); - int n = s.size(); - int f[n + 1]; - f[0] = 0; - for (int i = 1; i <= n; ++i) { - f[i] = f[i - 1] + 1; - for (int j = 0; j < i; ++j) { - if (ss.count(s.substr(j, i - j))) { - f[i] = min(f[i], f[j]); - } - } - } - return f[n]; - } -}; -``` - ```cpp class Node { public: @@ -257,28 +313,6 @@ public: }; ``` -### **Go** - -```go -func minExtraChar(s string, dictionary []string) int { - ss := map[string]bool{} - for _, w := range dictionary { - ss[w] = true - } - n := len(s) - f := make([]int, n+1) - for i := 1; i <= n; i++ { - f[i] = f[i-1] + 1 - for j := 0; j < i; j++ { - if ss[s[j:i]] && f[j] < f[i] { - f[i] = f[j] - } - } - } - return f[n] -} -``` - ```go type Node struct { children [26]*Node @@ -318,25 +352,6 @@ func minExtraChar(s string, dictionary []string) int { } ``` -### **TypeScript** - -```ts -function minExtraChar(s: string, dictionary: string[]): number { - const ss = new Set(dictionary); - const n = s.length; - const f = new Array(n + 1).fill(0); - for (let i = 1; i <= n; ++i) { - f[i] = f[i - 1] + 1; - for (let j = 0; j < i; ++j) { - if (ss.has(s.substring(j, i))) { - f[i] = Math.min(f[i], f[j]); - } - } - } - return f[n]; -} -``` - ```ts class Node { children: (Node | null)[] = Array(26).fill(null); @@ -377,33 +392,6 @@ function minExtraChar(s: string, dictionary: string[]): number { } ``` -### **Rust** - -```rust -use std::collections::HashSet; - -impl Solution { - pub fn min_extra_char(s: String, dictionary: Vec) -> i32 { - let ss: HashSet = dictionary.into_iter().collect(); - let n = s.len(); - let mut f = vec![0; n + 1]; - for i in 1..=n { - f[i] = f[i - 1] + 1; - for j in 0..i { - if ss.contains(&s[j..i]) { - f[i] = f[i].min(f[j]); - } - } - } - f[n] - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2708.Maximum Strength of a Group/README.md b/solution/2700-2799/2708.Maximum Strength of a Group/README.md index 81c621beeeff1..941d87edc83a3 100644 --- a/solution/2700-2799/2708.Maximum Strength of a Group/README.md +++ b/solution/2700-2799/2708.Maximum Strength of a Group/README.md @@ -37,14 +37,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxStrength(self, nums: List[int]) -> int: @@ -67,10 +63,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long maxStrength(int[] nums) { @@ -100,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +122,6 @@ public: }; ``` -### **Go** - ```go func maxStrength(nums []int) int64 { sort.Ints(nums) @@ -157,8 +145,6 @@ func maxStrength(nums []int) int64 { } ``` -### **TypeScript** - ```ts function maxStrength(nums: number[]): number { nums.sort((a, b) => a - b); @@ -182,10 +168,6 @@ function maxStrength(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2708.Maximum Strength of a Group/README_EN.md b/solution/2700-2799/2708.Maximum Strength of a Group/README_EN.md index 8053b080bc6cf..6d6da4b9f0b3a 100644 --- a/solution/2700-2799/2708.Maximum Strength of a Group/README_EN.md +++ b/solution/2700-2799/2708.Maximum Strength of a Group/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long maxStrength(int[] nums) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +120,6 @@ public: }; ``` -### **Go** - ```go func maxStrength(nums []int) int64 { sort.Ints(nums) @@ -149,8 +143,6 @@ func maxStrength(nums []int) int64 { } ``` -### **TypeScript** - ```ts function maxStrength(nums: number[]): number { nums.sort((a, b) => a - b); @@ -174,10 +166,6 @@ function maxStrength(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2709.Greatest Common Divisor Traversal/README.md b/solution/2700-2799/2709.Greatest Common Divisor Traversal/README.md index 08c957a24bcff..359909e65acbf 100644 --- a/solution/2700-2799/2709.Greatest Common Divisor Traversal/README.md +++ b/solution/2700-2799/2709.Greatest Common Divisor Traversal/README.md @@ -51,14 +51,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class UnionFind: def __init__(self, n): @@ -109,10 +105,6 @@ class Solution: return len(set(uf.find(i) for i in range(n))) == 1 ``` -### **Java** - - - ```java class UnionFind { private int[] p; @@ -192,8 +184,6 @@ class Solution { } ``` -### **C++** - ```cpp int MX = 100010; vector P[100010]; @@ -272,8 +262,6 @@ public: }; ``` -### **Go** - ```go const mx = 100010 @@ -351,10 +339,6 @@ func canTraverseAllPairs(nums []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2709.Greatest Common Divisor Traversal/README_EN.md b/solution/2700-2799/2709.Greatest Common Divisor Traversal/README_EN.md index 6ae4f92ab0402..35d3e11b609c5 100644 --- a/solution/2700-2799/2709.Greatest Common Divisor Traversal/README_EN.md +++ b/solution/2700-2799/2709.Greatest Common Divisor Traversal/README_EN.md @@ -47,9 +47,9 @@ To go from index 0 to index 2, we can just go directly because gcd(nums[0], nums ## Solutions - +### Solution 1 -### **Python3** + ```python class UnionFind: @@ -101,8 +101,6 @@ class Solution: return len(set(uf.find(i) for i in range(n))) == 1 ``` -### **Java** - ```java class UnionFind { private int[] p; @@ -182,8 +180,6 @@ class Solution { } ``` -### **C++** - ```cpp int MX = 100010; vector P[100010]; @@ -262,8 +258,6 @@ public: }; ``` -### **Go** - ```go const mx = 100010 @@ -341,10 +335,6 @@ func canTraverseAllPairs(nums []int) bool { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2710.Remove Trailing Zeros From a String/README.md b/solution/2700-2799/2710.Remove Trailing Zeros From a String/README.md index 87a623b063fa3..374d9c2fde3db 100644 --- a/solution/2700-2799/2710.Remove Trailing Zeros From a String/README.md +++ b/solution/2700-2799/2710.Remove Trailing Zeros From a String/README.md @@ -36,9 +36,7 @@ ## 解法 - - -**方法一:遍历** +### 方法一:遍历 我们可以从后往前遍历字符串,遇到第一个不是 `0` 的字符时停止遍历,然后返回从头开始到这个字符的子串。 @@ -46,20 +44,12 @@ -### **Python3** - - - ```python class Solution: def removeTrailingZeros(self, num: str) -> str: return num.rstrip("0") ``` -### **Java** - - - ```java class Solution { public String removeTrailingZeros(String num) { @@ -72,8 +62,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -86,8 +74,6 @@ public: }; ``` -### **Go** - ```go func removeTrailingZeros(num string) string { i := len(num) - 1 @@ -98,8 +84,6 @@ func removeTrailingZeros(num string) string { } ``` -### **TypeScript** - ```ts function removeTrailingZeros(num: string): string { let i = num.length - 1; @@ -110,8 +94,6 @@ function removeTrailingZeros(num: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn remove_trailing_zeros(num: String) -> String { @@ -126,6 +108,12 @@ impl Solution { } ``` + + +### 方法二 + + + ```rust impl Solution { pub fn remove_trailing_zeros(num: String) -> String { @@ -140,10 +128,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2710.Remove Trailing Zeros From a String/README_EN.md b/solution/2700-2799/2710.Remove Trailing Zeros From a String/README_EN.md index 5a75372d38155..c2163cf28229d 100644 --- a/solution/2700-2799/2710.Remove Trailing Zeros From a String/README_EN.md +++ b/solution/2700-2799/2710.Remove Trailing Zeros From a String/README_EN.md @@ -34,9 +34,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -44,8 +44,6 @@ class Solution: return num.rstrip("0") ``` -### **Java** - ```java class Solution { public String removeTrailingZeros(String num) { @@ -58,8 +56,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -72,8 +68,6 @@ public: }; ``` -### **Go** - ```go func removeTrailingZeros(num string) string { i := len(num) - 1 @@ -84,8 +78,6 @@ func removeTrailingZeros(num string) string { } ``` -### **TypeScript** - ```ts function removeTrailingZeros(num: string): string { let i = num.length - 1; @@ -96,8 +88,6 @@ function removeTrailingZeros(num: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn remove_trailing_zeros(num: String) -> String { @@ -112,6 +102,12 @@ impl Solution { } ``` + + +### Solution 2 + + + ```rust impl Solution { pub fn remove_trailing_zeros(num: String) -> String { @@ -126,10 +122,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2711.Difference of Number of Distinct Values on Diagonals/README.md b/solution/2700-2799/2711.Difference of Number of Distinct Values on Diagonals/README.md index 246b202203234..78ab254c34667 100644 --- a/solution/2700-2799/2711.Difference of Number of Distinct Values on Diagonals/README.md +++ b/solution/2700-2799/2711.Difference of Number of Distinct Values on Diagonals/README.md @@ -60,14 +60,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def differenceOfDistinctValues(self, grid: List[List[int]]) -> List[List[int]]: @@ -91,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] differenceOfDistinctValues(int[][] grid) { @@ -123,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +144,6 @@ public: }; ``` -### **Go** - ```go func differenceOfDistinctValues(grid [][]int) [][]int { m, n := len(grid), len(grid[0]) @@ -191,8 +179,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function differenceOfDistinctValues(grid: number[][]): number[][] { const m = grid.length; @@ -221,10 +207,6 @@ function differenceOfDistinctValues(grid: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2711.Difference of Number of Distinct Values on Diagonals/README_EN.md b/solution/2700-2799/2711.Difference of Number of Distinct Values on Diagonals/README_EN.md index 5ca8d27109e03..31af1cf2fdba0 100644 --- a/solution/2700-2799/2711.Difference of Number of Distinct Values on Diagonals/README_EN.md +++ b/solution/2700-2799/2711.Difference of Number of Distinct Values on Diagonals/README_EN.md @@ -57,9 +57,9 @@ The answers of other cells are similarly calculated. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -84,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] differenceOfDistinctValues(int[][] grid) { @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +141,6 @@ public: }; ``` -### **Go** - ```go func differenceOfDistinctValues(grid [][]int) [][]int { m, n := len(grid), len(grid[0]) @@ -182,8 +176,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function differenceOfDistinctValues(grid: number[][]): number[][] { const m = grid.length; @@ -212,10 +204,6 @@ function differenceOfDistinctValues(grid: number[][]): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2712.Minimum Cost to Make All Characters Equal/README.md b/solution/2700-2799/2712.Minimum Cost to Make All Characters Equal/README.md index 464e74a965b06..1d0af4a1d265b 100644 --- a/solution/2700-2799/2712.Minimum Cost to Make All Characters Equal/README.md +++ b/solution/2700-2799/2712.Minimum Cost to Make All Characters Equal/README.md @@ -50,14 +50,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minimumCost(self, s: str) -> int: @@ -68,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long minimumCost(String s) { @@ -87,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +95,6 @@ public: }; ``` -### **Go** - ```go func minimumCost(s string) (ans int64) { n := len(s) @@ -119,8 +107,6 @@ func minimumCost(s string) (ans int64) { } ``` -### **TypeScript** - ```ts function minimumCost(s: string): number { let ans = 0; @@ -134,10 +120,6 @@ function minimumCost(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2712.Minimum Cost to Make All Characters Equal/README_EN.md b/solution/2700-2799/2712.Minimum Cost to Make All Characters Equal/README_EN.md index b81c96519e787..d8a22350faa5a 100644 --- a/solution/2700-2799/2712.Minimum Cost to Make All Characters Equal/README_EN.md +++ b/solution/2700-2799/2712.Minimum Cost to Make All Characters Equal/README_EN.md @@ -47,9 +47,9 @@ The total cost to make all characters equal is 9. It can be shown that 9 is the ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long minimumCost(String s) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func minimumCost(s string) (ans int64) { n := len(s) @@ -110,8 +104,6 @@ func minimumCost(s string) (ans int64) { } ``` -### **TypeScript** - ```ts function minimumCost(s: string): number { let ans = 0; @@ -125,10 +117,6 @@ function minimumCost(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2713.Maximum Strictly Increasing Cells in a Matrix/README.md b/solution/2700-2799/2713.Maximum Strictly Increasing Cells in a Matrix/README.md index 7343029020efd..a9025a6dc7c1e 100644 --- a/solution/2700-2799/2713.Maximum Strictly Increasing Cells in a Matrix/README.md +++ b/solution/2700-2799/2713.Maximum Strictly Increasing Cells in a Matrix/README.md @@ -59,14 +59,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxIncreasingCells(self, mat: List[List[int]]) -> int: @@ -89,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxIncreasingCells(int[][] mat) { @@ -126,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -159,8 +149,6 @@ public: }; ``` -### **Go** - ```go func maxIncreasingCells(mat [][]int) (ans int) { m, n := len(mat), len(mat[0]) @@ -193,10 +181,6 @@ func maxIncreasingCells(mat [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2713.Maximum Strictly Increasing Cells in a Matrix/README_EN.md b/solution/2700-2799/2713.Maximum Strictly Increasing Cells in a Matrix/README_EN.md index c9f488ecf500f..c69fa24f793fa 100644 --- a/solution/2700-2799/2713.Maximum Strictly Increasing Cells in a Matrix/README_EN.md +++ b/solution/2700-2799/2713.Maximum Strictly Increasing Cells in a Matrix/README_EN.md @@ -56,9 +56,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxIncreasingCells(int[][] mat) { @@ -117,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +146,6 @@ public: }; ``` -### **Go** - ```go func maxIncreasingCells(mat [][]int) (ans int) { m, n := len(mat), len(mat[0]) @@ -184,10 +178,6 @@ func maxIncreasingCells(mat [][]int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2714.Find Shortest Path with K Hops/README.md b/solution/2700-2799/2714.Find Shortest Path with K Hops/README.md index 8e4271844ce9b..b5817e6e79fda 100644 --- a/solution/2700-2799/2714.Find Shortest Path with K Hops/README.md +++ b/solution/2700-2799/2714.Find Shortest Path with K Hops/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:Dijkstra 算法** +### 方法一:Dijkstra 算法 我们先根据给定的边构造出图 $g$,其中 $g[u]$ 表示节点 $u$ 的所有邻居节点以及对应的边权重。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class Solution: def shortestPathWithHops( @@ -106,10 +100,6 @@ class Solution: return int(min(dist[d])) ``` -### **Java** - - - ```java class Solution { public int shortestPathWithHops(int n, int[][] edges, int s, int d, int k) { @@ -152,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -188,8 +176,6 @@ public: }; ``` -### **Go** - ```go func shortestPathWithHops(n int, edges [][]int, s int, d int, k int) int { g := make([][][2]int, n) @@ -235,10 +221,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2714.Find Shortest Path with K Hops/README_EN.md b/solution/2700-2799/2714.Find Shortest Path with K Hops/README_EN.md index 0e5013776a42c..b11da9c636fa7 100644 --- a/solution/2700-2799/2714.Find Shortest Path with K Hops/README_EN.md +++ b/solution/2700-2799/2714.Find Shortest Path with K Hops/README_EN.md @@ -57,7 +57,7 @@ ## Solutions -**Solution 1: Dijkstra Algorithm** +### Solution 1: Dijkstra Algorithm First, we construct a graph $g$ based on the given edges, where $g[u]$ represents all neighboring nodes of node $u$ and their corresponding edge weights. @@ -72,8 +72,6 @@ The time complexity is $O(n^2 \times \log n)$, and the space complexity is $O(n -### **Python3** - ```python class Solution: def shortestPathWithHops( @@ -98,8 +96,6 @@ class Solution: return int(min(dist[d])) ``` -### **Java** - ```java class Solution { public int shortestPathWithHops(int n, int[][] edges, int s, int d, int k) { @@ -142,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -178,8 +172,6 @@ public: }; ``` -### **Go** - ```go func shortestPathWithHops(n int, edges [][]int, s int, d int, k int) int { g := make([][][2]int, n) @@ -225,10 +217,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2715.Timeout Cancellation/README.md b/solution/2700-2799/2715.Timeout Cancellation/README.md index a97e6eb2dcfd8..b27e3409c369c 100644 --- a/solution/2700-2799/2715.Timeout Cancellation/README.md +++ b/solution/2700-2799/2715.Timeout Cancellation/README.md @@ -72,14 +72,10 @@ setTimeout(cancelFn, cancelTimeMs); ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function cancellable(fn: Function, args: any[], t: number): Function { const timer = setTimeout(() => fn(...args), t); @@ -115,8 +111,6 @@ function cancellable(fn: Function, args: any[], t: number): Function { */ ``` -### **JavaScript** - ```js /** * @param {Function} fn @@ -159,3 +153,5 @@ var cancellable = function (fn, args, t) { ``` + + diff --git a/solution/2700-2799/2715.Timeout Cancellation/README_EN.md b/solution/2700-2799/2715.Timeout Cancellation/README_EN.md index 4a4cd7e96a77e..4f747685b559d 100644 --- a/solution/2700-2799/2715.Timeout Cancellation/README_EN.md +++ b/solution/2700-2799/2715.Timeout Cancellation/README_EN.md @@ -69,9 +69,9 @@ The cancellation was scheduled to occur after a delay of cancelTimeMs (100ms), w ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function cancellable(fn: Function, args: any[], t: number): Function { @@ -108,8 +108,6 @@ function cancellable(fn: Function, args: any[], t: number): Function { */ ``` -### **JavaScript** - ```js /** * @param {Function} fn @@ -152,3 +150,5 @@ var cancellable = function (fn, args, t) { ``` + + diff --git a/solution/2700-2799/2716.Minimize String Length/README.md b/solution/2700-2799/2716.Minimize String Length/README.md index 0b91d5784bab6..240e038f104fe 100644 --- a/solution/2700-2799/2716.Minimize String Length/README.md +++ b/solution/2700-2799/2716.Minimize String Length/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 题目实际上可以转化为求字符串中不同字符的个数,因此,我们只需要统计字符串中不同字符的个数即可。 @@ -61,20 +59,12 @@ -### **Python3** - - - ```python class Solution: def minimizedStringLength(self, s: str) -> int: return len(set(s)) ``` -### **Java** - - - ```java class Solution { public int minimizedStringLength(String s) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +87,6 @@ public: }; ``` -### **Go** - ```go func minimizedStringLength(s string) int { ss := map[rune]struct{}{} @@ -111,16 +97,12 @@ func minimizedStringLength(s string) int { } ``` -### **TypeScript** - ```ts function minimizedStringLength(s: string): number { return new Set(s.split('')).size; } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -137,6 +119,12 @@ impl Solution { } ``` + + +### 方法二 + + + ```rust use std::collections::HashSet; @@ -153,10 +141,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2716.Minimize String Length/README_EN.md b/solution/2700-2799/2716.Minimize String Length/README_EN.md index 59718de4aa42e..aee5cf9f22bb0 100644 --- a/solution/2700-2799/2716.Minimize String Length/README_EN.md +++ b/solution/2700-2799/2716.Minimize String Length/README_EN.md @@ -50,7 +50,7 @@ ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table The problem can actually be transformed into finding the number of different characters in the string. Therefore, we only need to count the number of different characters in the string. @@ -58,16 +58,12 @@ The time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is -### **Python3** - ```python class Solution: def minimizedStringLength(self, s: str) -> int: return len(set(s)) ``` -### **Java** - ```java class Solution { public int minimizedStringLength(String s) { @@ -80,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -92,8 +86,6 @@ public: }; ``` -### **Go** - ```go func minimizedStringLength(s string) int { ss := map[rune]struct{}{} @@ -104,16 +96,12 @@ func minimizedStringLength(s string) int { } ``` -### **TypeScript** - ```ts function minimizedStringLength(s: string): number { return new Set(s.split('')).size; } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -130,6 +118,12 @@ impl Solution { } ``` + + +### Solution 2 + + + ```rust use std::collections::HashSet; @@ -146,10 +140,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2717.Semi-Ordered Permutation/README.md b/solution/2700-2799/2717.Semi-Ordered Permutation/README.md index 85dc0836d7779..7e1b4a6871a11 100644 --- a/solution/2700-2799/2717.Semi-Ordered Permutation/README.md +++ b/solution/2700-2799/2717.Semi-Ordered Permutation/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:寻找 1 和 n 的位置** +### 方法一:寻找 1 和 n 的位置 我们可以先找到 $1$ 和 $n$ 的下标 $i$ 和 $j$,然后根据 $i$ 和 $j$ 的相对位置,判断需要交换的次数。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python class Solution: def semiOrderedPermutation(self, nums: List[int]) -> int: @@ -89,10 +83,6 @@ class Solution: return i + n - j - k ``` -### **Java** - - - ```java class Solution { public int semiOrderedPermutation(int[] nums) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func semiOrderedPermutation(nums []int) int { n := len(nums) @@ -149,8 +135,6 @@ func semiOrderedPermutation(nums []int) int { } ``` -### **TypeScript** - ```ts function semiOrderedPermutation(nums: number[]): number { const n = nums.length; @@ -161,8 +145,6 @@ function semiOrderedPermutation(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn semi_ordered_permutation(nums: Vec) -> i32 { @@ -189,6 +171,12 @@ impl Solution { } ``` + + +### 方法二 + + + ```rust impl Solution { pub fn semi_ordered_permutation(nums: Vec) -> i32 { @@ -216,10 +204,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2717.Semi-Ordered Permutation/README_EN.md b/solution/2700-2799/2717.Semi-Ordered Permutation/README_EN.md index 272afea0a8577..bfe98b43648ec 100644 --- a/solution/2700-2799/2717.Semi-Ordered Permutation/README_EN.md +++ b/solution/2700-2799/2717.Semi-Ordered Permutation/README_EN.md @@ -59,7 +59,7 @@ It can be proved that there is no sequence of less than three operations that ma ## Solutions -**Solution 1: Find the Positions of 1 and n** +### Solution 1: Find the Positions of 1 and n We can first find the indices $i$ and $j$ of $1$ and $n$, respectively. Then, based on the relative positions of $i$ and $j$, we can determine the number of swaps required. @@ -69,8 +69,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def semiOrderedPermutation(self, nums: List[int]) -> int: @@ -81,8 +79,6 @@ class Solution: return i + n - j - k ``` -### **Java** - ```java class Solution { public int semiOrderedPermutation(int[] nums) { @@ -102,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func semiOrderedPermutation(nums []int) int { n := len(nums) @@ -139,8 +131,6 @@ func semiOrderedPermutation(nums []int) int { } ``` -### **TypeScript** - ```ts function semiOrderedPermutation(nums: number[]): number { const n = nums.length; @@ -151,8 +141,6 @@ function semiOrderedPermutation(nums: number[]): number { } ``` -### **Rust** - ```rust impl Solution { pub fn semi_ordered_permutation(nums: Vec) -> i32 { @@ -179,6 +167,12 @@ impl Solution { } ``` + + +### Solution 2 + + + ```rust impl Solution { pub fn semi_ordered_permutation(nums: Vec) -> i32 { @@ -206,10 +200,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2718.Sum of Matrix After Queries/README.md b/solution/2700-2799/2718.Sum of Matrix After Queries/README.md index 1da5146f790c7..015d774ad45f3 100644 --- a/solution/2700-2799/2718.Sum of Matrix After Queries/README.md +++ b/solution/2700-2799/2718.Sum of Matrix After Queries/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 由于每一行、每一列的值取决于最后一次的修改,因此,我们不妨倒序遍历所有的查询,使用哈希表 $row$ 和 $col$ 记录有哪些行和列被修改过。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def matrixSumQueries(self, n: int, queries: List[List[int]]) -> int: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long matrixSumQueries(int n, int[][] queries) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +136,6 @@ public: }; ``` -### **Go** - ```go func matrixSumQueries(n int, queries [][]int) (ans int64) { row, col := map[int]bool{}, map[int]bool{} @@ -172,8 +158,6 @@ func matrixSumQueries(n int, queries [][]int) (ans int64) { } ``` -### **TypeScript** - ```ts function matrixSumQueries(n: number, queries: number[][]): number { const row: Set = new Set(); @@ -197,10 +181,6 @@ function matrixSumQueries(n: number, queries: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2718.Sum of Matrix After Queries/README_EN.md b/solution/2700-2799/2718.Sum of Matrix After Queries/README_EN.md index 1fe809120f86a..bb1e8c69929dd 100644 --- a/solution/2700-2799/2718.Sum of Matrix After Queries/README_EN.md +++ b/solution/2700-2799/2718.Sum of Matrix After Queries/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table Since the value of each row and column depends on the last modification, we can traverse all queries in reverse order and use hash tables $row$ and $col$ to record which rows and columns have been modified. @@ -61,8 +61,6 @@ The time complexity is $O(m)$, and the space complexity is $O(n)$. Here, $m$ rep -### **Python3** - ```python class Solution: def matrixSumQueries(self, n: int, queries: List[List[int]]) -> int: @@ -81,8 +79,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long matrixSumQueries(int n, int[][] queries) { @@ -108,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +130,6 @@ public: }; ``` -### **Go** - ```go func matrixSumQueries(n int, queries [][]int) (ans int64) { row, col := map[int]bool{}, map[int]bool{} @@ -160,8 +152,6 @@ func matrixSumQueries(n int, queries [][]int) (ans int64) { } ``` -### **TypeScript** - ```ts function matrixSumQueries(n: number, queries: number[][]): number { const row: Set = new Set(); @@ -185,10 +175,6 @@ function matrixSumQueries(n: number, queries: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2719.Count of Integers/README.md b/solution/2700-2799/2719.Count of Integers/README.md index 26c75d0b66e1f..a44ffa3d4e8ee 100644 --- a/solution/2700-2799/2719.Count of Integers/README.md +++ b/solution/2700-2799/2719.Count of Integers/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:数位 DP** +### 方法一:数位 DP 题目实际上求的是区间 $[num1,..num2]$ 中,数位和在 $[min\_sum,..max\_sum]$ 的数的个数。对于这种区间 $[l,..r]$ 的问题,我们可以考虑转化为求 $[1,..r]$ 和 $[1,..l-1]$ 的答案,然后相减即可。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def count(self, num1: str, num2: str, min_sum: int, max_sum: int) -> int: @@ -89,10 +83,6 @@ class Solution: return (a - b) % mod ``` -### **Java** - - - ```java import java.math.BigInteger; @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -182,8 +170,6 @@ public: }; ``` -### **Go** - ```go func count(num1 string, num2 string, min_sum int, max_sum int) int { const mod = 1e9 + 7 @@ -239,8 +225,6 @@ func count(num1 string, num2 string, min_sum int, max_sum int) int { } ``` -### **TypeScript** - ```ts function count(num1: string, num2: string, min_sum: number, max_sum: number): number { const mod = 1e9 + 7; @@ -271,10 +255,6 @@ function count(num1: string, num2: string, min_sum: number, max_sum: number): nu } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2719.Count of Integers/README_EN.md b/solution/2700-2799/2719.Count of Integers/README_EN.md index e14cde65ab1a8..1765eaceae95b 100644 --- a/solution/2700-2799/2719.Count of Integers/README_EN.md +++ b/solution/2700-2799/2719.Count of Integers/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Digit DP** +### Solution 1: Digit DP The problem is actually asking for the number of integers in the range $[num1,..num2]$ whose digit sum is in the range $[min\_sum,..max\_sum]$. For this kind of range $[l,..r]$ problem, we can consider transforming it into finding the answers for $[1,..r]$ and $[1,..l-1]$, and then subtracting the latter from the former. @@ -58,8 +58,6 @@ Similar problems: -### **Python3** - ```python class Solution: def count(self, num1: str, num2: str, min_sum: int, max_sum: int) -> int: @@ -81,8 +79,6 @@ class Solution: return (a - b) % mod ``` -### **Java** - ```java import java.math.BigInteger; @@ -125,8 +121,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -172,8 +166,6 @@ public: }; ``` -### **Go** - ```go func count(num1 string, num2 string, min_sum int, max_sum int) int { const mod = 1e9 + 7 @@ -229,8 +221,6 @@ func count(num1 string, num2 string, min_sum int, max_sum int) int { } ``` -### **TypeScript** - ```ts function count(num1: string, num2: string, min_sum: number, max_sum: number): number { const mod = 1e9 + 7; @@ -261,10 +251,6 @@ function count(num1: string, num2: string, min_sum: number, max_sum: number): nu } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2720.Popularity Percentage/README.md b/solution/2700-2799/2720.Popularity Percentage/README.md index 35d9814b02e80..0da895539a946 100644 --- a/solution/2700-2799/2720.Popularity Percentage/README.md +++ b/solution/2700-2799/2720.Popularity Percentage/README.md @@ -74,14 +74,10 @@ user1 按升序排序。 ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -102,3 +98,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2700-2799/2720.Popularity Percentage/README_EN.md b/solution/2700-2799/2720.Popularity Percentage/README_EN.md index 52a0fe5e903b9..ac926ec9cfad2 100644 --- a/solution/2700-2799/2720.Popularity Percentage/README_EN.md +++ b/solution/2700-2799/2720.Popularity Percentage/README_EN.md @@ -72,9 +72,9 @@ user1 is sorted in ascending order. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -96,3 +96,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2700-2799/2721.Execute Asynchronous Functions in Parallel/README.md b/solution/2700-2799/2721.Execute Asynchronous Functions in Parallel/README.md index 48f449ad94dff..31e2908670238 100644 --- a/solution/2700-2799/2721.Execute Asynchronous Functions in Parallel/README.md +++ b/solution/2700-2799/2721.Execute Asynchronous Functions in Parallel/README.md @@ -71,14 +71,10 @@ promiseAll(functions).then(console.log); // [5] ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts async function promiseAll(functions: (() => Promise)[]): Promise { return new Promise((resolve, reject) => { @@ -108,3 +104,5 @@ async function promiseAll(functions: (() => Promise)[]): Promise { ``` + + diff --git a/solution/2700-2799/2721.Execute Asynchronous Functions in Parallel/README_EN.md b/solution/2700-2799/2721.Execute Asynchronous Functions in Parallel/README_EN.md index c13897e4df287..156df4267995b 100644 --- a/solution/2700-2799/2721.Execute Asynchronous Functions in Parallel/README_EN.md +++ b/solution/2700-2799/2721.Execute Asynchronous Functions in Parallel/README_EN.md @@ -67,9 +67,9 @@ The single function was resolved at 200ms with a value of 5. ## Solutions - +### Solution 1 -### **TypeScript** + ```ts async function promiseAll(functions: (() => Promise)[]): Promise { @@ -100,3 +100,5 @@ async function promiseAll(functions: (() => Promise)[]): Promise { ``` + + diff --git a/solution/2700-2799/2722.Join Two Arrays by ID/README.md b/solution/2700-2799/2722.Join Two Arrays by ID/README.md index 0fd739eeacb87..d52e45b0b8d4c 100644 --- a/solution/2700-2799/2722.Join Two Arrays by ID/README.md +++ b/solution/2700-2799/2722.Join Two Arrays by ID/README.md @@ -88,14 +88,10 @@ arr2 = [ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function join(arr1: any[], arr2: any[]): any[] { const d = new Map(arr1.map(x => [x.id, x])); @@ -111,3 +107,5 @@ function join(arr1: any[], arr2: any[]): any[] { ``` + + diff --git a/solution/2700-2799/2722.Join Two Arrays by ID/README_EN.md b/solution/2700-2799/2722.Join Two Arrays by ID/README_EN.md index d9e7a7e7ae91b..be4dffa87f605 100644 --- a/solution/2700-2799/2722.Join Two Arrays by ID/README_EN.md +++ b/solution/2700-2799/2722.Join Two Arrays by ID/README_EN.md @@ -84,9 +84,9 @@ arr2 = [ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function join(arr1: any[], arr2: any[]): any[] { @@ -103,3 +103,5 @@ function join(arr1: any[], arr2: any[]): any[] { ``` + + diff --git a/solution/2700-2799/2723.Add Two Promises/README.md b/solution/2700-2799/2723.Add Two Promises/README.md index dcffb2d1da480..abecd97cb1f16 100644 --- a/solution/2700-2799/2723.Add Two Promises/README.md +++ b/solution/2700-2799/2723.Add Two Promises/README.md @@ -40,14 +40,10 @@ promise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30)) ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts async function addTwoPromises( promise1: Promise, @@ -62,8 +58,6 @@ async function addTwoPromises( */ ``` -### **JavaScript** - ```js var addTwoPromises = async function (promise1, promise2) { return (await promise1) + (await promise2); @@ -71,3 +65,5 @@ var addTwoPromises = async function (promise1, promise2) { ``` + + diff --git a/solution/2700-2799/2723.Add Two Promises/README_EN.md b/solution/2700-2799/2723.Add Two Promises/README_EN.md index ccacb46f412ce..eeb1f1018a389 100644 --- a/solution/2700-2799/2723.Add Two Promises/README_EN.md +++ b/solution/2700-2799/2723.Add Two Promises/README_EN.md @@ -36,9 +36,9 @@ promise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30)) ## Solutions - +### Solution 1 -### **TypeScript** + ```ts async function addTwoPromises( @@ -54,8 +54,6 @@ async function addTwoPromises( */ ``` -### **JavaScript** - ```js var addTwoPromises = async function (promise1, promise2) { return (await promise1) + (await promise2); @@ -63,3 +61,5 @@ var addTwoPromises = async function (promise1, promise2) { ``` + + diff --git a/solution/2700-2799/2724.Sort By/README.md b/solution/2700-2799/2724.Sort By/README.md index 487d83b877877..a9c029b6c7e6b 100644 --- a/solution/2700-2799/2724.Sort By/README.md +++ b/solution/2700-2799/2724.Sort By/README.md @@ -48,14 +48,10 @@ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function sortBy(arr: any[], fn: Function): any[] { return arr.sort((a, b) => fn(a) - fn(b)); @@ -63,3 +59,5 @@ function sortBy(arr: any[], fn: Function): any[] { ``` + + diff --git a/solution/2700-2799/2724.Sort By/README_EN.md b/solution/2700-2799/2724.Sort By/README_EN.md index 00feabdacc972..0e6ee56f2906f 100644 --- a/solution/2700-2799/2724.Sort By/README_EN.md +++ b/solution/2700-2799/2724.Sort By/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function sortBy(arr: any[], fn: Function): any[] { @@ -55,3 +55,5 @@ function sortBy(arr: any[], fn: Function): any[] { ``` + + diff --git a/solution/2700-2799/2725.Interval Cancellation/README.md b/solution/2700-2799/2725.Interval Cancellation/README.md index 748b65a45781d..6e1f48cd142a8 100644 --- a/solution/2700-2799/2725.Interval Cancellation/README.md +++ b/solution/2700-2799/2725.Interval Cancellation/README.md @@ -118,14 +118,10 @@ setTimeout(cancel, cancelT); ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function cancellable(fn: Function, args: any[], t: number): Function { fn(...args); @@ -160,3 +156,5 @@ function cancellable(fn: Function, args: any[], t: number): Function { ``` + + diff --git a/solution/2700-2799/2725.Interval Cancellation/README_EN.md b/solution/2700-2799/2725.Interval Cancellation/README_EN.md index 9c9b6af7f9989..119857a75e142 100644 --- a/solution/2700-2799/2725.Interval Cancellation/README_EN.md +++ b/solution/2700-2799/2725.Interval Cancellation/README_EN.md @@ -102,9 +102,9 @@ Cancelled at 180ms ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function cancellable(fn: Function, args: any[], t: number): Function { @@ -140,3 +140,5 @@ function cancellable(fn: Function, args: any[], t: number): Function { ``` + + diff --git a/solution/2700-2799/2726.Calculator with Method Chaining/README.md b/solution/2700-2799/2726.Calculator with Method Chaining/README.md index e5e242191f0b8..b4d087e1648e2 100644 --- a/solution/2700-2799/2726.Calculator with Method Chaining/README.md +++ b/solution/2700-2799/2726.Calculator with Method Chaining/README.md @@ -71,14 +71,10 @@ new Calculator(20).divide(0).getResult() // 20 / 0 ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts class Calculator { private x: number; @@ -122,3 +118,5 @@ class Calculator { ``` + + diff --git a/solution/2700-2799/2726.Calculator with Method Chaining/README_EN.md b/solution/2700-2799/2726.Calculator with Method Chaining/README_EN.md index f29424b3cd192..88d0460d07d89 100644 --- a/solution/2700-2799/2726.Calculator with Method Chaining/README_EN.md +++ b/solution/2700-2799/2726.Calculator with Method Chaining/README_EN.md @@ -70,9 +70,9 @@ The error should be thrown because we cannot divide by zero. ## Solutions - +### Solution 1 -### **TypeScript** + ```ts class Calculator { @@ -117,3 +117,5 @@ class Calculator { ``` + + diff --git a/solution/2700-2799/2727.Is Object Empty/README.md b/solution/2700-2799/2727.Is Object Empty/README.md index 92fde5462d41b..2248b123b0c32 100644 --- a/solution/2700-2799/2727.Is Object Empty/README.md +++ b/solution/2700-2799/2727.Is Object Empty/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:遍历** +### 方法一:遍历 我们可以遍历对象或数组,如果遍历到了第一个元素,就返回 `false`,否则返回 `true`。 @@ -65,10 +63,6 @@ -### **TypeScript** - - - ```ts function isEmpty(obj: Record | any[]): boolean { for (const x in obj) { @@ -78,14 +72,6 @@ function isEmpty(obj: Record | any[]): boolean { } ``` -```ts -function isEmpty(obj: Record | any[]): boolean { - return Object.keys(obj).length === 0; -} -``` - -### **JavaScript** - ```js /** * @param {Object | Array} obj @@ -100,3 +86,17 @@ var isEmpty = function (obj) { ``` + +### 方法二 + + + +```ts +function isEmpty(obj: Record | any[]): boolean { + return Object.keys(obj).length === 0; +} +``` + + + + diff --git a/solution/2700-2799/2727.Is Object Empty/README_EN.md b/solution/2700-2799/2727.Is Object Empty/README_EN.md index d594b5a9b88f5..89cacdc8b2012 100644 --- a/solution/2700-2799/2727.Is Object Empty/README_EN.md +++ b/solution/2700-2799/2727.Is Object Empty/README_EN.md @@ -51,9 +51,9 @@ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function isEmpty(obj: Record | any[]): boolean { @@ -64,14 +64,6 @@ function isEmpty(obj: Record | any[]): boolean { } ``` -```ts -function isEmpty(obj: Record | any[]): boolean { - return Object.keys(obj).length === 0; -} -``` - -### **JavaScript** - ```js /** * @param {Object | Array} obj @@ -86,3 +78,17 @@ var isEmpty = function (obj) { ``` + +### Solution 2 + + + +```ts +function isEmpty(obj: Record | any[]): boolean { + return Object.keys(obj).length === 0; +} +``` + + + + diff --git a/solution/2700-2799/2728.Count Houses in a Circular Street/README.md b/solution/2700-2799/2728.Count Houses in a Circular Street/README.md index 4781072e50e79..834ca57dd1571 100644 --- a/solution/2700-2799/2728.Count Houses in a Circular Street/README.md +++ b/solution/2700-2799/2728.Count Houses in a Circular Street/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:遍历** +### 方法一:遍历 我们先循环 $k$ 次,每次打开当前房子的门,然后向左移动一格,循环结束后,所有房子的门都是打开的。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python # Definition for a street. # class Street: @@ -97,10 +91,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a street. @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a street. @@ -163,8 +151,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a street. @@ -189,8 +175,6 @@ func houseCount(street Street, k int) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a street. @@ -218,10 +202,6 @@ function houseCount(street: Street | null, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2728.Count Houses in a Circular Street/README_EN.md b/solution/2700-2799/2728.Count Houses in a Circular Street/README_EN.md index 73e86797a173b..3e6a9cb5c9c12 100644 --- a/solution/2700-2799/2728.Count Houses in a Circular Street/README_EN.md +++ b/solution/2700-2799/2728.Count Houses in a Circular Street/README_EN.md @@ -48,9 +48,9 @@ The number of houses is equal to k, which is 5. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a street. @@ -78,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a street. @@ -109,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a street. @@ -142,8 +138,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a street. @@ -168,8 +162,6 @@ func houseCount(street Street, k int) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a street. @@ -197,10 +189,6 @@ function houseCount(street: Street | null, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2729.Check if The Number is Fascinating/README.md b/solution/2700-2799/2729.Check if The Number is Fascinating/README.md index 8b8150801c3f9..e36e66cf86964 100644 --- a/solution/2700-2799/2729.Check if The Number is Fascinating/README.md +++ b/solution/2700-2799/2729.Check if The Number is Fascinating/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们根据题目描述,将数字 $n$ 与 $2 \times n$ 和 $3 \times n$ 连接,得到字符串 $s$,然后判断 $s$ 是否包含数字 $1$ 到 $9$ 各一次且不包含任何 $0$ 即可。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def isFascinating(self, n: int) -> bool: @@ -65,10 +59,6 @@ class Solution: return "".join(sorted(s)) == "123456789" ``` -### **Java** - - - ```java class Solution { public boolean isFascinating(int n) { @@ -84,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +85,6 @@ public: }; ``` -### **Go** - ```go func isFascinating(n int) bool { s := strconv.Itoa(n) + strconv.Itoa(n*2) + strconv.Itoa(n*3) @@ -113,8 +99,6 @@ func isFascinating(n int) bool { } ``` -### **TypeScript** - ```ts function isFascinating(n: number): boolean { const s = `${n}${n * 2}${n * 3}`; @@ -122,8 +106,6 @@ function isFascinating(n: number): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_fascinating(n: i32) -> bool { @@ -143,6 +125,12 @@ impl Solution { } ``` + + +### 方法二 + + + ```rust use std::collections::HashMap; @@ -182,10 +170,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2729.Check if The Number is Fascinating/README_EN.md b/solution/2700-2799/2729.Check if The Number is Fascinating/README_EN.md index 326b56c8f6c9b..2d39be0fd3dcc 100644 --- a/solution/2700-2799/2729.Check if The Number is Fascinating/README_EN.md +++ b/solution/2700-2799/2729.Check if The Number is Fascinating/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return "".join(sorted(s)) == "123456789" ``` -### **Java** - ```java class Solution { public boolean isFascinating(int n) { @@ -70,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -83,8 +79,6 @@ public: }; ``` -### **Go** - ```go func isFascinating(n int) bool { s := strconv.Itoa(n) + strconv.Itoa(n*2) + strconv.Itoa(n*3) @@ -99,8 +93,6 @@ func isFascinating(n int) bool { } ``` -### **TypeScript** - ```ts function isFascinating(n: number): boolean { const s = `${n}${n * 2}${n * 3}`; @@ -108,8 +100,6 @@ function isFascinating(n: number): boolean { } ``` -### **Rust** - ```rust impl Solution { pub fn is_fascinating(n: i32) -> bool { @@ -129,6 +119,12 @@ impl Solution { } ``` + + +### Solution 2 + + + ```rust use std::collections::HashMap; @@ -168,10 +164,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2730.Find the Longest Semi-Repetitive Substring/README.md b/solution/2700-2799/2730.Find the Longest Semi-Repetitive Substring/README.md index 595c53c385e2b..62a2b9423db41 100644 --- a/solution/2700-2799/2730.Find the Longest Semi-Repetitive Substring/README.md +++ b/solution/2700-2799/2730.Find the Longest Semi-Repetitive Substring/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们用双指针维护一个区间 $s[j..i]$,使得区间内最多只有一个相邻字符相等。我们用 $cnt$ 记录区间内相邻字符相等的个数,如果 $cnt \gt 1$,那么我们就需要移动左指针 $j$,直到 $cnt \le 1$。每一次,我们更新答案为 $ans = \max(ans, i - j + 1)$。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def longestSemiRepetitiveSubstring(self, s: str) -> int: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestSemiRepetitiveSubstring(String s) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go func longestSemiRepetitiveSubstring(s string) (ans int) { n := len(s) @@ -153,8 +139,6 @@ func longestSemiRepetitiveSubstring(s string) (ans int) { } ``` -### **TypeScript** - ```ts function longestSemiRepetitiveSubstring(s: string): number { const n = s.length; @@ -175,10 +159,6 @@ function longestSemiRepetitiveSubstring(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2730.Find the Longest Semi-Repetitive Substring/README_EN.md b/solution/2700-2799/2730.Find the Longest Semi-Repetitive Substring/README_EN.md index f249e7907a6d2..e1b258813c1f9 100644 --- a/solution/2700-2799/2730.Find the Longest Semi-Repetitive Substring/README_EN.md +++ b/solution/2700-2799/2730.Find the Longest Semi-Repetitive Substring/README_EN.md @@ -47,9 +47,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestSemiRepetitiveSubstring(String s) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +112,6 @@ public: }; ``` -### **Go** - ```go func longestSemiRepetitiveSubstring(s string) (ans int) { n := len(s) @@ -137,8 +131,6 @@ func longestSemiRepetitiveSubstring(s string) (ans int) { } ``` -### **TypeScript** - ```ts function longestSemiRepetitiveSubstring(s: string): number { const n = s.length; @@ -159,10 +151,6 @@ function longestSemiRepetitiveSubstring(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2731.Movement of Robots/README.md b/solution/2700-2799/2731.Movement of Robots/README.md index 570ec11620669..94c5ed9e43988 100644 --- a/solution/2700-2799/2731.Movement of Robots/README.md +++ b/solution/2700-2799/2731.Movement of Robots/README.md @@ -75,9 +75,7 @@ ## 解法 - - -**方法一:脑筋急转弯 + 排序** +### 方法一:脑筋急转弯 + 排序 两个机器人相撞后,它们会立即改变方向,实际上相当于两个机器人继续往原来的方向移动。因此,我们遍历数组 $nums$,按照字符串 $s$ 的指令,将每个机器人的位置加上或减去 $d$,然后对数组 $nums$ 进行排序。 @@ -87,10 +85,6 @@ -### **Python3** - - - ```python class Solution: def sumDistance(self, nums: List[int], s: str, d: int) -> int: @@ -105,10 +99,6 @@ class Solution: return ans % mod ``` -### **Java** - - - ```java class Solution { public int sumDistance(int[] nums, String s, int d) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func sumDistance(nums []int, s string, d int) (ans int) { for i, c := range s { @@ -175,8 +161,6 @@ func sumDistance(nums []int, s string, d int) (ans int) { } ``` -### **TypeScript** - ```ts function sumDistance(nums: number[], s: string, d: number): number { const n = nums.length; @@ -195,10 +179,6 @@ function sumDistance(nums: number[], s: string, d: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2731.Movement of Robots/README_EN.md b/solution/2700-2799/2731.Movement of Robots/README_EN.md index c5e0a49a0801a..fe3652654ccd0 100644 --- a/solution/2700-2799/2731.Movement of Robots/README_EN.md +++ b/solution/2700-2799/2731.Movement of Robots/README_EN.md @@ -66,7 +66,7 @@ The distance between the two robots is abs(-2 - 3) = 5. ## Solutions -**Solution 1: Quick thinking + Sorting** +### Solution 1: Quick thinking + Sorting After two robots collide, they will immediately change direction, which is equivalent to the two robots continuing to move in their original direction. Therefore, we traverse the array $nums$, and according to the instructions in the string $s$, we add or subtract $d$ from the position of each robot, and then sort the array $nums$. @@ -76,8 +76,6 @@ The time complexity is $O(n \times \log n)$ and the space complexity is $O(n)$, -### **Python3** - ```python class Solution: def sumDistance(self, nums: List[int], s: str, d: int) -> int: @@ -92,8 +90,6 @@ class Solution: return ans % mod ``` -### **Java** - ```java class Solution { public int sumDistance(int[] nums, String s, int d) { @@ -114,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +132,6 @@ public: }; ``` -### **Go** - ```go func sumDistance(nums []int, s string, d int) (ans int) { for i, c := range s { @@ -160,8 +152,6 @@ func sumDistance(nums []int, s string, d int) (ans int) { } ``` -### **TypeScript** - ```ts function sumDistance(nums: number[], s: string, d: number): number { const n = nums.length; @@ -180,10 +170,6 @@ function sumDistance(nums: number[], s: string, d: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2732.Find a Good Subset of the Matrix/README.md b/solution/2700-2799/2732.Find a Good Subset of the Matrix/README.md index dcd8f2f78cf16..7c1a387acc4d0 100644 --- a/solution/2700-2799/2732.Find a Good Subset of the Matrix/README.md +++ b/solution/2700-2799/2732.Find a Good Subset of the Matrix/README.md @@ -65,42 +65,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2700-2799/2732.Find a Good Subset of the Matrix/README_EN.md b/solution/2700-2799/2732.Find a Good Subset of the Matrix/README_EN.md index d24d7d26eb678..77ff5b5fd5d9c 100644 --- a/solution/2700-2799/2732.Find a Good Subset of the Matrix/README_EN.md +++ b/solution/2700-2799/2732.Find a Good Subset of the Matrix/README_EN.md @@ -61,36 +61,4 @@ The length of the chosen subset is 1. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2700-2799/2733.Neither Minimum nor Maximum/README.md b/solution/2700-2799/2733.Neither Minimum nor Maximum/README.md index aa108736f4b05..12117724a6fd6 100644 --- a/solution/2700-2799/2733.Neither Minimum nor Maximum/README.md +++ b/solution/2700-2799/2733.Neither Minimum nor Maximum/README.md @@ -45,34 +45,16 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findNonMinOrMax(self, nums: List[int]) -> int: return -1 if len(nums) < 3 else sorted(nums)[1] ``` -```python -class Solution: - def findNonMinOrMax(self, nums: List[int]) -> int: - mi, mx = min(nums), max(nums) - for x in nums: - if x != mi and x != mx: - return x - return -1 -``` - -### **Java** - - - ```java class Solution { public int findNonMinOrMax(int[] nums) { @@ -91,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +89,6 @@ public: }; ``` -### **Go** - ```go func findNonMinOrMax(nums []int) int { mi, mx := slices.Min(nums), slices.Max(nums) @@ -123,8 +101,6 @@ func findNonMinOrMax(nums []int) int { } ``` -### **Rust** - ```rust impl Solution { pub fn find_non_min_or_max(nums: Vec) -> i32 { @@ -151,10 +127,22 @@ impl Solution { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def findNonMinOrMax(self, nums: List[int]) -> int: + mi, mx = min(nums), max(nums) + for x in nums: + if x != mi and x != mx: + return x + return -1 ``` + + diff --git a/solution/2700-2799/2733.Neither Minimum nor Maximum/README_EN.md b/solution/2700-2799/2733.Neither Minimum nor Maximum/README_EN.md index 7af0014796dae..4a83e875b4bfd 100644 --- a/solution/2700-2799/2733.Neither Minimum nor Maximum/README_EN.md +++ b/solution/2700-2799/2733.Neither Minimum nor Maximum/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -54,18 +54,6 @@ class Solution: return -1 if len(nums) < 3 else sorted(nums)[1] ``` -```python -class Solution: - def findNonMinOrMax(self, nums: List[int]) -> int: - mi, mx = min(nums), max(nums) - for x in nums: - if x != mi and x != mx: - return x - return -1 -``` - -### **Java** - ```java class Solution { public int findNonMinOrMax(int[] nums) { @@ -84,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +88,6 @@ public: }; ``` -### **Go** - ```go func findNonMinOrMax(nums []int) int { mi, mx := slices.Min(nums), slices.Max(nums) @@ -116,8 +100,6 @@ func findNonMinOrMax(nums []int) int { } ``` -### **Rust** - ```rust impl Solution { pub fn find_non_min_or_max(nums: Vec) -> i32 { @@ -144,10 +126,22 @@ impl Solution { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def findNonMinOrMax(self, nums: List[int]) -> int: + mi, mx = min(nums), max(nums) + for x in nums: + if x != mi and x != mx: + return x + return -1 ``` + + diff --git a/solution/2700-2799/2734.Lexicographically Smallest String After Substring Operation/README.md b/solution/2700-2799/2734.Lexicographically Smallest String After Substring Operation/README.md index 016c9f77a0d29..d0c9526bf5321 100644 --- a/solution/2700-2799/2734.Lexicographically Smallest String After Substring Operation/README.md +++ b/solution/2700-2799/2734.Lexicographically Smallest String After Substring Operation/README.md @@ -57,14 +57,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def smallestString(self, s: str) -> str: @@ -80,10 +76,6 @@ class Solution: return s[:i] + "".join(chr(ord(c) - 1) for c in s[i:j]) + s[j:] ``` -### **Java** - - - ```java class Solution { public String smallestString(String s) { @@ -106,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +121,6 @@ public: }; ``` -### **Go** - ```go func smallestString(s string) string { n := len(s) @@ -154,37 +142,6 @@ func smallestString(s string) string { } ``` -### **Rust** - -```rust -impl Solution { - pub fn smallest_string(s: String) -> String { - let mut cs: Vec = s.chars().collect(); - let n = cs.len(); - let mut i = 0; - - while i < n && cs[i] == 'a' { - i += 1; - } - - if i == n { - cs[n - 1] = 'z'; - return cs.into_iter().collect(); - } - - let mut j = i; - while j < n && cs[j] != 'a' { - cs[j] = ((cs[j] as u8) - 1) as char; - j += 1; - } - - cs.into_iter().collect() - } -} -``` - -### **TypeScript** - ```ts function smallestString(s: string): string { const cs: string[] = s.split(''); @@ -210,10 +167,33 @@ function smallestString(s: string): string { } ``` -### **...** +```rust +impl Solution { + pub fn smallest_string(s: String) -> String { + let mut cs: Vec = s.chars().collect(); + let n = cs.len(); + let mut i = 0; -``` + while i < n && cs[i] == 'a' { + i += 1; + } + if i == n { + cs[n - 1] = 'z'; + return cs.into_iter().collect(); + } + + let mut j = i; + while j < n && cs[j] != 'a' { + cs[j] = ((cs[j] as u8) - 1) as char; + j += 1; + } + + cs.into_iter().collect() + } +} ``` + + diff --git a/solution/2700-2799/2734.Lexicographically Smallest String After Substring Operation/README_EN.md b/solution/2700-2799/2734.Lexicographically Smallest String After Substring Operation/README_EN.md index 46c77f94ef876..35b6d86b4e805 100644 --- a/solution/2700-2799/2734.Lexicographically Smallest String After Substring Operation/README_EN.md +++ b/solution/2700-2799/2734.Lexicographically Smallest String After Substring Operation/README_EN.md @@ -52,9 +52,9 @@ It can be proven that the resulting string is the lexicographically smallest. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -71,8 +71,6 @@ class Solution: return s[:i] + "".join(chr(ord(c) - 1) for c in s[i:j]) + s[j:] ``` -### **Java** - ```java class Solution { public String smallestString(String s) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +116,6 @@ public: }; ``` -### **Go** - ```go func smallestString(s string) string { n := len(s) @@ -143,37 +137,6 @@ func smallestString(s string) string { } ``` -### **Rust** - -```rust -impl Solution { - pub fn smallest_string(s: String) -> String { - let mut cs: Vec = s.chars().collect(); - let n = cs.len(); - let mut i = 0; - - while i < n && cs[i] == 'a' { - i += 1; - } - - if i == n { - cs[n - 1] = 'z'; - return cs.into_iter().collect(); - } - - let mut j = i; - while j < n && cs[j] != 'a' { - cs[j] = ((cs[j] as u8) - 1) as char; - j += 1; - } - - cs.into_iter().collect() - } -} -``` - -### **TypeScript** - ```ts function smallestString(s: string): string { const cs: string[] = s.split(''); @@ -199,10 +162,33 @@ function smallestString(s: string): string { } ``` -### **...** +```rust +impl Solution { + pub fn smallest_string(s: String) -> String { + let mut cs: Vec = s.chars().collect(); + let n = cs.len(); + let mut i = 0; -``` + while i < n && cs[i] == 'a' { + i += 1; + } + if i == n { + cs[n - 1] = 'z'; + return cs.into_iter().collect(); + } + + let mut j = i; + while j < n && cs[j] != 'a' { + cs[j] = ((cs[j] as u8) - 1) as char; + j += 1; + } + + cs.into_iter().collect() + } +} ``` + + diff --git a/solution/2700-2799/2735.Collecting Chocolates/README.md b/solution/2700-2799/2735.Collecting Chocolates/README.md index 991f493892795..067b4b5331214 100644 --- a/solution/2700-2799/2735.Collecting Chocolates/README.md +++ b/solution/2700-2799/2735.Collecting Chocolates/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们考虑枚举操作的次数,定义 $f[i][j]$ 表示第 $i$ 个巧克力进行了 $j$ 次操作后的最小成本。 @@ -77,10 +75,6 @@ $$ -### **Python3** - - - ```python class Solution: def minCost(self, nums: List[int], x: int) -> int: @@ -93,10 +87,6 @@ class Solution: return min(sum(f[i][j] for i in range(n)) + x * j for j in range(n)) ``` -### **Java** - - - ```java class Solution { public long minCost(int[] nums, int x) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +136,6 @@ public: }; ``` -### **Go** - ```go func minCost(nums []int, x int) int64 { n := len(nums) @@ -173,8 +159,6 @@ func minCost(nums []int, x int) int64 { } ``` -### **TypeScript** - ```ts function minCost(nums: number[], x: number): number { const n = nums.length; @@ -197,8 +181,6 @@ function minCost(nums: number[], x: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_cost(nums: Vec, x: i32) -> i64 { @@ -223,10 +205,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2735.Collecting Chocolates/README_EN.md b/solution/2700-2799/2735.Collecting Chocolates/README_EN.md index 253e9d61db832..960c71369d547 100644 --- a/solution/2700-2799/2735.Collecting Chocolates/README_EN.md +++ b/solution/2700-2799/2735.Collecting Chocolates/README_EN.md @@ -45,7 +45,7 @@ Thus, the total cost will become (1 + 5 + 1 + 5 + 1) = 13. We can prove that thi ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We consider enumerating the number of operations, and define $f[i][j]$ as the minimum cost after the $i$-th chocolate has undergone $j$ operations. @@ -71,8 +71,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Where $n$ -### **Python3** - ```python class Solution: def minCost(self, nums: List[int], x: int) -> int: @@ -85,8 +83,6 @@ class Solution: return min(sum(f[i][j] for i in range(n)) + x * j for j in range(n)) ``` -### **Java** - ```java class Solution { public long minCost(int[] nums, int x) { @@ -111,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +132,6 @@ public: }; ``` -### **Go** - ```go func minCost(nums []int, x int) int64 { n := len(nums) @@ -163,8 +155,6 @@ func minCost(nums []int, x int) int64 { } ``` -### **TypeScript** - ```ts function minCost(nums: number[], x: number): number { const n = nums.length; @@ -187,8 +177,6 @@ function minCost(nums: number[], x: number): number { } ``` -### **Rust** - ```rust impl Solution { pub fn min_cost(nums: Vec, x: i32) -> i64 { @@ -213,10 +201,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2736.Maximum Sum Queries/README.md b/solution/2700-2799/2736.Maximum Sum Queries/README.md index 206c81255d988..47a925acca564 100644 --- a/solution/2700-2799/2736.Maximum Sum Queries/README.md +++ b/solution/2700-2799/2736.Maximum Sum Queries/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:树状数组** +### 方法一:树状数组 本题属于二维偏序问题。 @@ -83,10 +81,6 @@ $$ -### **Python3** - - - ```python class BinaryIndexedTree: __slots__ = ["n", "c"] @@ -129,10 +123,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class BinaryIndexedTree { private int n; @@ -194,53 +184,6 @@ class Solution { } ``` -```java -class Solution { - public int[] maximumSumQueries(int[] nums1, int[] nums2, int[][] q) { - int n = nums1.length, m = q.length; - int[][] a = new int[n][2]; - for (int i = 0; i < n; i++) { - a[i][0] = nums1[i]; - a[i][1] = nums2[i]; - } - int[][] b = new int[m][3]; - for (int i = 0; i < m; i++) { - b[i][0] = q[i][0]; - b[i][1] = q[i][1]; - b[i][2] = i; - } - Arrays.sort(a, (o1, o2) -> o1[0] - o2[0]); - Arrays.sort(b, (o1, o2) -> o1[0] - o2[0]); - TreeMap map = new TreeMap<>(); - int[] res = new int[m]; - int max = -1; - for (int i = m - 1, j = n - 1; i >= 0; i--) { - int x = b[i][0], y = b[i][1], idx = b[i][2]; - while (j >= 0 && a[j][0] >= x) { - if (max < a[j][1]) { - max = a[j][1]; - Integer key = map.floorKey(a[j][1]); - while (key != null && map.get(key) <= a[j][0] + a[j][1]) { - map.remove(key); - key = map.floorKey(key); - } - map.put(max, a[j][0] + a[j][1]); - } - j--; - } - Integer key = map.ceilingKey(y); - if (key == null) - res[idx] = -1; - else - res[idx] = map.get(key); - } - return res; - } -} -``` - -### **C++** - ```cpp class BinaryIndexedTree { private: @@ -300,8 +243,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -361,8 +302,6 @@ func maximumSumQueries(nums1 []int, nums2 []int, queries [][]int) []int { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -431,10 +370,57 @@ function maximumSumQueries(nums1: number[], nums2: number[], queries: number[][] } ``` -### **...** + -``` +### 方法二 + + +```java +class Solution { + public int[] maximumSumQueries(int[] nums1, int[] nums2, int[][] q) { + int n = nums1.length, m = q.length; + int[][] a = new int[n][2]; + for (int i = 0; i < n; i++) { + a[i][0] = nums1[i]; + a[i][1] = nums2[i]; + } + int[][] b = new int[m][3]; + for (int i = 0; i < m; i++) { + b[i][0] = q[i][0]; + b[i][1] = q[i][1]; + b[i][2] = i; + } + Arrays.sort(a, (o1, o2) -> o1[0] - o2[0]); + Arrays.sort(b, (o1, o2) -> o1[0] - o2[0]); + TreeMap map = new TreeMap<>(); + int[] res = new int[m]; + int max = -1; + for (int i = m - 1, j = n - 1; i >= 0; i--) { + int x = b[i][0], y = b[i][1], idx = b[i][2]; + while (j >= 0 && a[j][0] >= x) { + if (max < a[j][1]) { + max = a[j][1]; + Integer key = map.floorKey(a[j][1]); + while (key != null && map.get(key) <= a[j][0] + a[j][1]) { + map.remove(key); + key = map.floorKey(key); + } + map.put(max, a[j][0] + a[j][1]); + } + j--; + } + Integer key = map.ceilingKey(y); + if (key == null) + res[idx] = -1; + else + res[idx] = map.get(key); + } + return res; + } +} ``` + + diff --git a/solution/2700-2799/2736.Maximum Sum Queries/README_EN.md b/solution/2700-2799/2736.Maximum Sum Queries/README_EN.md index 295c5ac88e46d..8f6eecd669635 100644 --- a/solution/2700-2799/2736.Maximum Sum Queries/README_EN.md +++ b/solution/2700-2799/2736.Maximum Sum Queries/README_EN.md @@ -59,7 +59,7 @@ Therefore, we return [6,10,7]. ## Solutions -**Solution 1: Binary Indexed Tree** +### Solution 1: Binary Indexed Tree This problem belongs to the category of two-dimensional partial order problems. @@ -83,8 +83,6 @@ Similar problems: -### **Python3** - ```python class BinaryIndexedTree: __slots__ = ["n", "c"] @@ -127,8 +125,6 @@ class Solution: return ans ``` -### **Java** - ```java class BinaryIndexedTree { private int n; @@ -190,53 +186,6 @@ class Solution { } ``` -```java -class Solution { - public int[] maximumSumQueries(int[] nums1, int[] nums2, int[][] q) { - int n = nums1.length, m = q.length; - int[][] a = new int[n][2]; - for (int i = 0; i < n; i++) { - a[i][0] = nums1[i]; - a[i][1] = nums2[i]; - } - int[][] b = new int[m][3]; - for (int i = 0; i < m; i++) { - b[i][0] = q[i][0]; - b[i][1] = q[i][1]; - b[i][2] = i; - } - Arrays.sort(a, (o1, o2) -> o1[0] - o2[0]); - Arrays.sort(b, (o1, o2) -> o1[0] - o2[0]); - TreeMap map = new TreeMap<>(); - int[] res = new int[m]; - int max = -1; - for (int i = m - 1, j = n - 1; i >= 0; i--) { - int x = b[i][0], y = b[i][1], idx = b[i][2]; - while (j >= 0 && a[j][0] >= x) { - if (max < a[j][1]) { - max = a[j][1]; - Integer key = map.floorKey(a[j][1]); - while (key != null && map.get(key) <= a[j][0] + a[j][1]) { - map.remove(key); - key = map.floorKey(key); - } - map.put(max, a[j][0] + a[j][1]); - } - j--; - } - Integer key = map.ceilingKey(y); - if (key == null) - res[idx] = -1; - else - res[idx] = map.get(key); - } - return res; - } -} -``` - -### **C++** - ```cpp class BinaryIndexedTree { private: @@ -296,8 +245,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -357,8 +304,6 @@ func maximumSumQueries(nums1 []int, nums2 []int, queries [][]int) []int { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -427,10 +372,57 @@ function maximumSumQueries(nums1: number[], nums2: number[], queries: number[][] } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + public int[] maximumSumQueries(int[] nums1, int[] nums2, int[][] q) { + int n = nums1.length, m = q.length; + int[][] a = new int[n][2]; + for (int i = 0; i < n; i++) { + a[i][0] = nums1[i]; + a[i][1] = nums2[i]; + } + int[][] b = new int[m][3]; + for (int i = 0; i < m; i++) { + b[i][0] = q[i][0]; + b[i][1] = q[i][1]; + b[i][2] = i; + } + Arrays.sort(a, (o1, o2) -> o1[0] - o2[0]); + Arrays.sort(b, (o1, o2) -> o1[0] - o2[0]); + TreeMap map = new TreeMap<>(); + int[] res = new int[m]; + int max = -1; + for (int i = m - 1, j = n - 1; i >= 0; i--) { + int x = b[i][0], y = b[i][1], idx = b[i][2]; + while (j >= 0 && a[j][0] >= x) { + if (max < a[j][1]) { + max = a[j][1]; + Integer key = map.floorKey(a[j][1]); + while (key != null && map.get(key) <= a[j][0] + a[j][1]) { + map.remove(key); + key = map.floorKey(key); + } + map.put(max, a[j][0] + a[j][1]); + } + j--; + } + Integer key = map.ceilingKey(y); + if (key == null) + res[idx] = -1; + else + res[idx] = map.get(key); + } + return res; + } +} ``` + + diff --git a/solution/2700-2799/2737.Find the Closest Marked Node/README.md b/solution/2700-2799/2737.Find the Closest Marked Node/README.md index ce1fe9b92895e..01b6bca73a7fe 100644 --- a/solution/2700-2799/2737.Find the Closest Marked Node/README.md +++ b/solution/2700-2799/2737.Find the Closest Marked Node/README.md @@ -68,9 +68,7 @@ ## 解法 - - -**方法一:Dijkstra 算法** +### 方法一:Dijkstra 算法 我们先根据题目中提供的边的信息,建立一个邻接矩阵 $g$,其中 $g[i][j]$ 表示节点 $i$ 到节点 $j$ 的距离,如果不存在这样的边,则 $g[i][j]$ 为正无穷。 @@ -82,10 +80,6 @@ -### **Python3** - - - ```python class Solution: def minimumDistance( @@ -109,10 +103,6 @@ class Solution: return -1 if ans >= inf else ans ``` -### **Java** - - - ```java class Solution { public int minimumDistance(int n, List> edges, int s, int[] marked) { @@ -150,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -186,8 +174,6 @@ public: }; ``` -### **Go** - ```go func minimumDistance(n int, edges [][]int, s int, marked []int) int { const inf = 1 << 29 @@ -229,8 +215,6 @@ func minimumDistance(n int, edges [][]int, s int, marked []int) int { } ``` -### **TypeScript** - ```ts function minimumDistance(n: number, edges: number[][], s: number, marked: number[]): number { const inf = 1 << 29; @@ -263,10 +247,6 @@ function minimumDistance(n: number, edges: number[][], s: number, marked: number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2737.Find the Closest Marked Node/README_EN.md b/solution/2700-2799/2737.Find the Closest Marked Node/README_EN.md index 69afbc0dfd4aa..7af6c9e6a0819 100644 --- a/solution/2700-2799/2737.Find the Closest Marked Node/README_EN.md +++ b/solution/2700-2799/2737.Find the Closest Marked Node/README_EN.md @@ -64,9 +64,9 @@ So the answer is 3. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -91,8 +91,6 @@ class Solution: return -1 if ans >= inf else ans ``` -### **Java** - ```java class Solution { public int minimumDistance(int n, List> edges, int s, int[] marked) { @@ -130,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -166,8 +162,6 @@ public: }; ``` -### **Go** - ```go func minimumDistance(n int, edges [][]int, s int, marked []int) int { const inf = 1 << 29 @@ -209,8 +203,6 @@ func minimumDistance(n int, edges [][]int, s int, marked []int) int { } ``` -### **TypeScript** - ```ts function minimumDistance(n: number, edges: number[][], s: number, marked: number[]): number { const inf = 1 << 29; @@ -243,10 +235,6 @@ function minimumDistance(n: number, edges: number[][], s: number, marked: number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2738.Count Occurrences in Text/README.md b/solution/2700-2799/2738.Count Occurrences in Text/README.md index fc0b2c77d7008..02bdfab074eee 100644 --- a/solution/2700-2799/2738.Count Occurrences in Text/README.md +++ b/solution/2700-2799/2738.Count Occurrences in Text/README.md @@ -59,14 +59,10 @@ Files 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT 'bull' AS word, COUNT(*) AS count @@ -79,3 +75,5 @@ WHERE content LIKE '% bear %'; ``` + + diff --git a/solution/2700-2799/2738.Count Occurrences in Text/README_EN.md b/solution/2700-2799/2738.Count Occurrences in Text/README_EN.md index 67e05710601fb..91f471e1a24e3 100644 --- a/solution/2700-2799/2738.Count Occurrences in Text/README_EN.md +++ b/solution/2700-2799/2738.Count Occurrences in Text/README_EN.md @@ -56,9 +56,9 @@ Files table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -72,3 +72,5 @@ WHERE content LIKE '% bear %'; ``` + + diff --git a/solution/2700-2799/2739.Total Distance Traveled/README.md b/solution/2700-2799/2739.Total Distance Traveled/README.md index 8f4509434faa5..dcbb5a9fb4360 100644 --- a/solution/2700-2799/2739.Total Distance Traveled/README.md +++ b/solution/2700-2799/2739.Total Distance Traveled/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以模拟卡车的行驶过程,每次消耗 $1$ 升主油箱中的燃料,行驶 $10$ 公里。每当主油箱中的燃料消耗 $5$ 升时,如果副油箱中有燃料,则将副油箱中的 $1$ 升燃料转移到主油箱中。一直模拟到主油箱中的燃料消耗完为止。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def distanceTraveled(self, mainTank: int, additionalTank: int) -> int: @@ -73,10 +67,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int distanceTraveled(int mainTank, int additionalTank) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func distanceTraveled(mainTank int, additionalTank int) (ans int) { cur := 0 @@ -134,8 +120,6 @@ func distanceTraveled(mainTank int, additionalTank int) (ans int) { } ``` -### **Rust** - ```rust impl Solution { pub fn distance_traveled(mut main_tank: i32, mut additional_tank: i32) -> i32 { @@ -158,10 +142,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2739.Total Distance Traveled/README_EN.md b/solution/2700-2799/2739.Total Distance Traveled/README_EN.md index b3d5c57080104..0d819933c0d15 100644 --- a/solution/2700-2799/2739.Total Distance Traveled/README_EN.md +++ b/solution/2700-2799/2739.Total Distance Traveled/README_EN.md @@ -44,9 +44,9 @@ Total distance traveled is 10km. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int distanceTraveled(int mainTank, int additionalTank) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +99,6 @@ public: }; ``` -### **Go** - ```go func distanceTraveled(mainTank int, additionalTank int) (ans int) { cur := 0 @@ -121,8 +115,6 @@ func distanceTraveled(mainTank int, additionalTank int) (ans int) { } ``` -### **Rust** - ```rust impl Solution { pub fn distance_traveled(mut main_tank: i32, mut additional_tank: i32) -> i32 { @@ -145,10 +137,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2740.Find the Value of the Partition/README.md b/solution/2700-2799/2740.Find the Value of the Partition/README.md index 0678f8bdccc19..73c5ef406b4d8 100644 --- a/solution/2700-2799/2740.Find the Value of the Partition/README.md +++ b/solution/2700-2799/2740.Find the Value of the Partition/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 题目要求分区值最小,那么我们可以将数组排序,然后取相邻两个数的差值的最小值即可。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def findValueOfPartition(self, nums: List[int]) -> int: @@ -78,10 +72,6 @@ class Solution: return min(b - a for a, b in pairwise(nums)) ``` -### **Java** - - - ```java class Solution { public int findValueOfPartition(int[] nums) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +99,6 @@ public: }; ``` -### **Go** - ```go func findValueOfPartition(nums []int) int { sort.Ints(nums) @@ -124,10 +110,6 @@ func findValueOfPartition(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2740.Find the Value of the Partition/README_EN.md b/solution/2700-2799/2740.Find the Value of the Partition/README_EN.md index 869dee22b6e1d..9aa7e343a471f 100644 --- a/solution/2700-2799/2740.Find the Value of the Partition/README_EN.md +++ b/solution/2700-2799/2740.Find the Value of the Partition/README_EN.md @@ -55,9 +55,9 @@ It can be proven that 9 is the minimum value out of all partitions. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -66,8 +66,6 @@ class Solution: return min(b - a for a, b in pairwise(nums)) ``` -### **Java** - ```java class Solution { public int findValueOfPartition(int[] nums) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +93,6 @@ public: }; ``` -### **Go** - ```go func findValueOfPartition(nums []int) int { sort.Ints(nums) @@ -110,10 +104,6 @@ func findValueOfPartition(nums []int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2741.Special Permutations/README.md b/solution/2700-2799/2741.Special Permutations/README.md index c477a4b6f750b..5aacbf3cd7050 100644 --- a/solution/2700-2799/2741.Special Permutations/README.md +++ b/solution/2700-2799/2741.Special Permutations/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:状态压缩动态规划** +### 方法一:状态压缩动态规划 我们注意到题目中数组的长度最大不超过 $14$,因此,我们可以用一个整数来表示当前的状态,其中第 $i$ 位为 $1$ 表示数组中的第 $i$ 个数已经被选取,为 $0$ 表示数组中的第 $i$ 个数还未被选取。 @@ -65,10 +63,6 @@ $$ -### **Python3** - - - ```python class Solution: def specialPerm(self, nums: List[int]) -> int: @@ -89,10 +83,6 @@ class Solution: return sum(f[-1]) % mod ``` -### **Java** - - - ```java class Solution { public int specialPerm(int[] nums) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +149,6 @@ public: }; ``` -### **Go** - ```go func specialPerm(nums []int) (ans int) { const mod int = 1e9 + 7 @@ -195,10 +181,6 @@ func specialPerm(nums []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2741.Special Permutations/README_EN.md b/solution/2700-2799/2741.Special Permutations/README_EN.md index c13c10f88c13d..14d32666794bf 100644 --- a/solution/2700-2799/2741.Special Permutations/README_EN.md +++ b/solution/2700-2799/2741.Special Permutations/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -63,8 +63,6 @@ class Solution: return sum(f[-1]) % mod ``` -### **Java** - ```java class Solution { public int specialPerm(int[] nums) { @@ -97,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +129,6 @@ public: }; ``` -### **Go** - ```go func specialPerm(nums []int) (ans int) { const mod int = 1e9 + 7 @@ -167,10 +161,6 @@ func specialPerm(nums []int) (ans int) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2742.Painting the Walls/README.md b/solution/2700-2799/2742.Painting the Walls/README.md index 7d5bc8fd93a45..da37f18726ed5 100644 --- a/solution/2700-2799/2742.Painting the Walls/README.md +++ b/solution/2700-2799/2742.Painting the Walls/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们可以考虑每一堵墙是给付费油漆匠刷还是给免费油漆匠刷,设计一个函数 $dfs(i, j)$,表示从第 $i$ 堵墙开始,且当前剩余的免费油漆匠工作时间为 $j$ 时,刷完剩余所有墙壁的最小开销。那么答案为 $dfs(0, 0)$。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def paintWalls(self, cost: List[int], time: List[int]) -> int: @@ -81,10 +75,6 @@ class Solution: return dfs(0, 0) ``` -### **Java** - - - ```java class Solution { private int n; @@ -115,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func paintWalls(cost []int, time []int) int { n := len(cost) @@ -170,8 +156,6 @@ func paintWalls(cost []int, time []int) int { } ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -213,10 +197,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2742.Painting the Walls/README_EN.md b/solution/2700-2799/2742.Painting the Walls/README_EN.md index 77573471b46b3..3fa6a460d2a20 100644 --- a/solution/2700-2799/2742.Painting the Walls/README_EN.md +++ b/solution/2700-2799/2742.Painting the Walls/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Memorization** +### Solution 1: Memorization We can consider whether each wall is painted by a paid painter or a free painter. Design a function $dfs(i, j)$, which means that from the $i$th wall, and the current remaining free painter working time is $j$, the minimum cost of painting all the remaining walls. Then the answer is $dfs(0, 0)$. @@ -58,8 +58,6 @@ Time complexity $O(n^2)$, space complexity $O(n^2)$. Where $n$ is the length of -### **Python3** - ```python class Solution: def paintWalls(self, cost: List[int], time: List[int]) -> int: @@ -75,8 +73,6 @@ class Solution: return dfs(0, 0) ``` -### **Java** - ```java class Solution { private int n; @@ -107,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +127,6 @@ public: }; ``` -### **Go** - ```go func paintWalls(cost []int, time []int) int { n := len(cost) @@ -162,8 +154,6 @@ func paintWalls(cost []int, time []int) int { } ``` -### **Rust** - ```rust impl Solution { #[allow(dead_code)] @@ -205,10 +195,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2743.Count Substrings Without Repeating Character/README.md b/solution/2700-2799/2743.Count Substrings Without Repeating Character/README.md index d3b3bccba8c46..c4dade63fff55 100644 --- a/solution/2700-2799/2743.Count Substrings Without Repeating Character/README.md +++ b/solution/2700-2799/2743.Count Substrings Without Repeating Character/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:计数 + 双指针** +### 方法一:计数 + 双指针 我们用两个指针 $j$ 和 $i$ 分别表示当前子串的左右边界,用一个长度为 $26$ 的数组 $cnt$ 统计当前子串中每个字符出现的次数。我们从左到右遍历字符串,每次遍历到位置 $i$ 时,将 $s[i]$ 出现的次数加一,然后判断 $s[i]$ 是否出现了至少两次,如果是,那么我们需要将 $s[j]$ 出现的次数减一,并将 $j$ 右移一位,直到 $s[i]$ 出现的次数不超过一次为止。这样一来,我们就得到以 $s[i]$ 结尾的最长特殊子串的长度,即 $i - j + 1$,那么以 $s[i]$ 结尾的特殊子串的数量就是 $i - j + 1$。最后我们将每个位置结尾的特殊子串的数量累加起来,即为答案。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def numberOfSpecialSubstrings(self, s: str) -> int: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numberOfSpecialSubstrings(String s) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func numberOfSpecialSubstrings(s string) (ans int) { j := 0 @@ -143,8 +129,6 @@ func numberOfSpecialSubstrings(s string) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfSpecialSubstrings(s: string): number { const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); @@ -163,10 +147,6 @@ function numberOfSpecialSubstrings(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2743.Count Substrings Without Repeating Character/README_EN.md b/solution/2700-2799/2743.Count Substrings Without Repeating Character/README_EN.md index 5545571866cd3..43248cd797b2e 100644 --- a/solution/2700-2799/2743.Count Substrings Without Repeating Character/README_EN.md +++ b/solution/2700-2799/2743.Count Substrings Without Repeating Character/README_EN.md @@ -47,9 +47,9 @@ And it can be shown that there are no special substrings with a length of at lea ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numberOfSpecialSubstrings(String s) { @@ -86,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +104,6 @@ public: }; ``` -### **Go** - ```go func numberOfSpecialSubstrings(s string) (ans int) { j := 0 @@ -127,8 +121,6 @@ func numberOfSpecialSubstrings(s string) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfSpecialSubstrings(s: string): number { const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); @@ -147,10 +139,6 @@ function numberOfSpecialSubstrings(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2744.Find Maximum Number of String Pairs/README.md b/solution/2700-2799/2744.Find Maximum Number of String Pairs/README.md index 78210ba15c91b..2bb1cdc86ad95 100644 --- a/solution/2700-2799/2744.Find Maximum Number of String Pairs/README.md +++ b/solution/2700-2799/2744.Find Maximum Number of String Pairs/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以用哈希表 $cnt$ 来存储数组 $words$ 中每个字符串的反转字符串出现的次数。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def maximumNumberOfStringPairs(self, words: List[str]) -> int: @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumNumberOfStringPairs(String[] words) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func maximumNumberOfStringPairs(words []string) (ans int) { cnt := map[string]int{} @@ -145,8 +131,6 @@ func maximumNumberOfStringPairs(words []string) (ans int) { } ``` -### **TypeScript** - ```ts function maximumNumberOfStringPairs(words: string[]): number { const cnt: Map = new Map(); @@ -160,10 +144,6 @@ function maximumNumberOfStringPairs(words: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2744.Find Maximum Number of String Pairs/README_EN.md b/solution/2700-2799/2744.Find Maximum Number of String Pairs/README_EN.md index 0564e46eb5b71..2a9d9620cf083 100644 --- a/solution/2700-2799/2744.Find Maximum Number of String Pairs/README_EN.md +++ b/solution/2700-2799/2744.Find Maximum Number of String Pairs/README_EN.md @@ -58,7 +58,7 @@ It can be proven that 1 is the maximum number of pairs that can be formed. ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We can use a hash table $cnt$ to store the number of occurrences of each string's reversed string in the array $words$. @@ -70,8 +70,6 @@ The time complexity is $O(L)$, and the space complexity is $O(L)$, where $L$ is -### **Python3** - ```python class Solution: def maximumNumberOfStringPairs(self, words: List[str]) -> int: @@ -83,8 +81,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumNumberOfStringPairs(String[] words) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func maximumNumberOfStringPairs(words []string) (ans int) { cnt := map[string]int{} @@ -134,8 +126,6 @@ func maximumNumberOfStringPairs(words []string) (ans int) { } ``` -### **TypeScript** - ```ts function maximumNumberOfStringPairs(words: string[]): number { const cnt: Map = new Map(); @@ -149,10 +139,6 @@ function maximumNumberOfStringPairs(words: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2745.Construct the Longest New String/README.md b/solution/2700-2799/2745.Construct the Longest New String/README.md index 1f9c26e244df3..03590de2da211 100644 --- a/solution/2700-2799/2745.Construct the Longest New String/README.md +++ b/solution/2700-2799/2745.Construct the Longest New String/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:分类讨论** +### 方法一:分类讨论 我们观察发现,字符串 `'AA'` 之后只能跟 `'BB'`,而字符串 `'AB'` 可以放在字符串开头或结尾。因此: @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def longestString(self, x: int, y: int, z: int) -> int: @@ -72,10 +66,6 @@ class Solution: return (x + y + z) * 2 ``` -### **Java** - - - ```java class Solution { public int longestString(int x, int y, int z) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +95,6 @@ public: }; ``` -### **Go** - ```go func longestString(x int, y int, z int) int { if x < y { @@ -121,8 +107,6 @@ func longestString(x int, y int, z int) int { } ``` -### **TypeScript** - ```ts function longestString(x: number, y: number, z: number): number { if (x < y) { @@ -135,10 +119,6 @@ function longestString(x: number, y: number, z: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2745.Construct the Longest New String/README_EN.md b/solution/2700-2799/2745.Construct the Longest New String/README_EN.md index 24a7458476bb8..b6e3e5f0eef8b 100644 --- a/solution/2700-2799/2745.Construct the Longest New String/README_EN.md +++ b/solution/2700-2799/2745.Construct the Longest New String/README_EN.md @@ -40,7 +40,7 @@ That string has length 14, and we can show that it is impossible to construct a ## Solutions -**Solution 1: Case Discussion** +### Solution 1: Case Discussion We observe that the string 'AA' can only be followed by 'BB', and the string 'AB' can be placed at the beginning or end of the string. Therefore: @@ -52,8 +52,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def longestString(self, x: int, y: int, z: int) -> int: @@ -64,8 +62,6 @@ class Solution: return (x + y + z) * 2 ``` -### **Java** - ```java class Solution { public int longestString(int x, int y, int z) { @@ -80,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -97,8 +91,6 @@ public: }; ``` -### **Go** - ```go func longestString(x int, y int, z int) int { if x < y { @@ -111,8 +103,6 @@ func longestString(x int, y int, z int) int { } ``` -### **TypeScript** - ```ts function longestString(x: number, y: number, z: number): number { if (x < y) { @@ -125,10 +115,6 @@ function longestString(x: number, y: number, z: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2746.Decremental String Concatenation/README.md b/solution/2700-2799/2746.Decremental String Concatenation/README.md index a3aea1aeff833..ea101455c3788 100644 --- a/solution/2700-2799/2746.Decremental String Concatenation/README.md +++ b/solution/2700-2799/2746.Decremental String Concatenation/README.md @@ -70,9 +70,7 @@ join(str0, "b") = "ab" 或者 join("b", str0) = "bab" 。 ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们注意到,字符串连接时,字符串的第一个字符和最后一个字符会影响到连接后字符串的长度。因此,我们设计一个函数 $dfs(i, a, b)$,表示从第 $i$ 个字符串开始连接,且此前已经连接的字符串的第一个字符为 $a$,最后一个字符为 $b$ 时,连接后字符串的最小长度。 @@ -89,10 +87,6 @@ join(str0, "b") = "ab" 或者 join("b", str0) = "bab" 。 -### **Python3** - - - ```python class Solution: def minimizeConcatenatedLength(self, words: List[str]) -> int: @@ -108,10 +102,6 @@ class Solution: return len(words[0]) + dfs(1, words[0][0], words[0][-1]) ``` -### **Java** - - - ```java class Solution { private Integer[][][] f; @@ -142,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go func minimizeConcatenatedLength(words []string) int { n := len(words) @@ -200,8 +186,6 @@ func minimizeConcatenatedLength(words []string) int { } ``` -### **TypeScript** - ```ts function minimizeConcatenatedLength(words: string[]): number { const n = words.length; @@ -234,10 +218,6 @@ function minimizeConcatenatedLength(words: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2746.Decremental String Concatenation/README_EN.md b/solution/2700-2799/2746.Decremental String Concatenation/README_EN.md index adbe1918047cd..f88b5ce10c737 100644 --- a/solution/2700-2799/2746.Decremental String Concatenation/README_EN.md +++ b/solution/2700-2799/2746.Decremental String Concatenation/README_EN.md @@ -68,7 +68,7 @@ It can be shown that the minimum possible length of str2 is 6. ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We notice that when concatenating strings, the first and last characters of the string will affect the length of the concatenated string. Therefore, we design a function $dfs(i, a, b)$, which represents the minimum length of the concatenated string starting from the $i$-th string, and the first character of the previously concatenated string is $a$, and the last character is $b$. @@ -85,8 +85,6 @@ The time complexity is $O(n \times C^2)$, and the space complexity is $O(n \time -### **Python3** - ```python class Solution: def minimizeConcatenatedLength(self, words: List[str]) -> int: @@ -102,8 +100,6 @@ class Solution: return len(words[0]) + dfs(1, words[0][0], words[0][-1]) ``` -### **Java** - ```java class Solution { private Integer[][][] f; @@ -134,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -161,8 +155,6 @@ public: }; ``` -### **Go** - ```go func minimizeConcatenatedLength(words []string) int { n := len(words) @@ -192,8 +184,6 @@ func minimizeConcatenatedLength(words []string) int { } ``` -### **TypeScript** - ```ts function minimizeConcatenatedLength(words: string[]): number { const n = words.length; @@ -226,10 +216,6 @@ function minimizeConcatenatedLength(words: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2747.Count Zero Request Servers/README.md b/solution/2700-2799/2747.Count Zero Request Servers/README.md index 1b610320b614d..79f8bcf35836f 100644 --- a/solution/2700-2799/2747.Count Zero Request Servers/README.md +++ b/solution/2700-2799/2747.Count Zero Request Servers/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:离线查询 + 排序 + 双指针** +### 方法一:离线查询 + 排序 + 双指针 我们可以将所有的查询按照时间从小到大排序,然后按照时间顺序依次处理每个查询。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def countServers( @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] countServers(int n, int[][] logs, int x, int[] queries) { @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +152,6 @@ public: }; ``` -### **Go** - ```go func countServers(n int, logs [][]int, x int, queries []int) []int { sort.Slice(logs, func(i, j int) bool { return logs[i][1] < logs[j][1] }) @@ -198,8 +184,6 @@ func countServers(n int, logs [][]int, x int, queries []int) []int { } ``` -### **TypeScript** - ```ts function countServers(n: number, logs: number[][], x: number, queries: number[]): number[] { logs.sort((a, b) => a[1] - b[1]); @@ -232,10 +216,6 @@ function countServers(n: number, logs: number[][], x: number, queries: number[]) } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2747.Count Zero Request Servers/README_EN.md b/solution/2700-2799/2747.Count Zero Request Servers/README_EN.md index 8c58184e7de61..7a390de0ab4f6 100644 --- a/solution/2700-2799/2747.Count Zero Request Servers/README_EN.md +++ b/solution/2700-2799/2747.Count Zero Request Servers/README_EN.md @@ -51,9 +51,9 @@ For queries[1]: Only server with id 3 gets no request in the duration [2,4]. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] countServers(int n, int[][] logs, int x, int[] queries) { @@ -112,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -148,8 +144,6 @@ public: }; ``` -### **Go** - ```go func countServers(n int, logs [][]int, x int, queries []int) []int { sort.Slice(logs, func(i, j int) bool { return logs[i][1] < logs[j][1] }) @@ -182,8 +176,6 @@ func countServers(n int, logs [][]int, x int, queries []int) []int { } ``` -### **TypeScript** - ```ts function countServers(n: number, logs: number[][], x: number, queries: number[]): number[] { logs.sort((a, b) => a[1] - b[1]); @@ -216,10 +208,6 @@ function countServers(n: number, logs: number[][], x: number, queries: number[]) } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2748.Number of Beautiful Pairs/README.md b/solution/2700-2799/2748.Number of Beautiful Pairs/README.md index 36f21bb85dd96..7b0e986f66dd4 100644 --- a/solution/2700-2799/2748.Number of Beautiful Pairs/README.md +++ b/solution/2700-2799/2748.Number of Beautiful Pairs/README.md @@ -50,14 +50,10 @@ i = 0 和 j = 2 :nums[0] 的第一个数字是 1 ,nums[2] 的最后一个数 ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def countBeautifulPairs(self, nums: List[int]) -> int: @@ -71,10 +67,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countBeautifulPairs(int[] nums) { @@ -100,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +114,6 @@ public: }; ``` -### **Go** - ```go func countBeautifulPairs(nums []int) (ans int) { cnt := [10]int{} @@ -151,8 +139,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function countBeautifulPairs(nums: number[]): number { const cnt: number[] = Array(10).fill(0); @@ -179,10 +165,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2748.Number of Beautiful Pairs/README_EN.md b/solution/2700-2799/2748.Number of Beautiful Pairs/README_EN.md index e9a2b3f2f955c..610f2b995eb5d 100644 --- a/solution/2700-2799/2748.Number of Beautiful Pairs/README_EN.md +++ b/solution/2700-2799/2748.Number of Beautiful Pairs/README_EN.md @@ -47,9 +47,9 @@ Thus, we return 2. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -64,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countBeautifulPairs(int[] nums) { @@ -91,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +111,6 @@ public: }; ``` -### **Go** - ```go func countBeautifulPairs(nums []int) (ans int) { cnt := [10]int{} @@ -142,8 +136,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function countBeautifulPairs(nums: number[]): number { const cnt: number[] = Array(10).fill(0); @@ -170,10 +162,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/README.md b/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/README.md index 806b99923f1a0..cba19b2aed72b 100644 --- a/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/README.md +++ b/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 如果我们操作了 $k$ 次,那么问题实际上就变成了:判断 $num1 - k \times num2$ 能否拆分成 $k$ 个 $2^i$ 之和。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def makeTheIntegerZero(self, num1: int, num2: int) -> int: @@ -81,10 +75,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int makeTheIntegerZero(int num1, int num2) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func makeTheIntegerZero(num1 int, num2 int) int { for k := 1; ; k++ { @@ -140,10 +126,6 @@ func makeTheIntegerZero(num1 int, num2 int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/README_EN.md b/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/README_EN.md index 13b46990bc776..a51db49219eed 100644 --- a/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/README_EN.md +++ b/solution/2700-2799/2749.Minimum Operations to Make the Integer Zero/README_EN.md @@ -43,9 +43,9 @@ It can be proven, that 3 is the minimum number of operations that we need to per ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int makeTheIntegerZero(int num1, int num2) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +95,6 @@ public: }; ``` -### **Go** - ```go func makeTheIntegerZero(num1 int, num2 int) int { for k := 1; ; k++ { @@ -116,10 +110,6 @@ func makeTheIntegerZero(num1 int, num2 int) int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/README.md b/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/README.md index 43360ff222cfc..e697c2c09fbc8 100644 --- a/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/README.md +++ b/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:乘法原理** +### 方法一:乘法原理 根据题目描述,我们可以在两个 $1$ 之间画一条分割线,假设两个 $1$ 之间的下标分别为 $j$ 和 $i$,那么可以画的不同分割线的数量为 $i - j$。我们找出所有满足条件的 $j$ 和 $i$,然后将所有的 $i - j$ 相乘即可。如果找不到两个 $1$ 之间的分割线,那么说明数组中不存在 $1$,此时答案为 $0$。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def numberOfGoodSubarraySplits(self, nums: List[int]) -> int: @@ -73,10 +67,6 @@ class Solution: return 0 if j == -1 else ans ``` -### **Java** - - - ```java class Solution { public int numberOfGoodSubarraySplits(int[] nums) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func numberOfGoodSubarraySplits(nums []int) int { const mod int = 1e9 + 7 @@ -140,8 +126,6 @@ func numberOfGoodSubarraySplits(nums []int) int { } ``` -### **TypeScript** - ```ts function numberOfGoodSubarraySplits(nums: number[]): number { let ans = 1; @@ -161,8 +145,6 @@ function numberOfGoodSubarraySplits(nums: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int NumberOfGoodSubarraySplits(int[] nums) { @@ -183,10 +165,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/README_EN.md b/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/README_EN.md index 59f62c2d8ce8c..8825b5e9c8ea2 100644 --- a/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/README_EN.md +++ b/solution/2700-2799/2750.Ways to Split Array Into Good Subarrays/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return 0 if j == -1 else ans ``` -### **Java** - ```java class Solution { public int numberOfGoodSubarraySplits(int[] nums) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +100,6 @@ public: }; ``` -### **Go** - ```go func numberOfGoodSubarraySplits(nums []int) int { const mod int = 1e9 + 7 @@ -126,8 +120,6 @@ func numberOfGoodSubarraySplits(nums []int) int { } ``` -### **TypeScript** - ```ts function numberOfGoodSubarraySplits(nums: number[]): number { let ans = 1; @@ -147,8 +139,6 @@ function numberOfGoodSubarraySplits(nums: number[]): number { } ``` -### **C#** - ```cs public class Solution { public int NumberOfGoodSubarraySplits(int[] nums) { @@ -169,10 +159,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2751.Robot Collisions/README.md b/solution/2700-2799/2751.Robot Collisions/README.md index b88f09f9e20ea..1cc9961b66f81 100644 --- a/solution/2700-2799/2751.Robot Collisions/README.md +++ b/solution/2700-2799/2751.Robot Collisions/README.md @@ -64,42 +64,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2700-2799/2751.Robot Collisions/README_EN.md b/solution/2700-2799/2751.Robot Collisions/README_EN.md index 666a9fa3ce1a8..3e98f54d29581 100644 --- a/solution/2700-2799/2751.Robot Collisions/README_EN.md +++ b/solution/2700-2799/2751.Robot Collisions/README_EN.md @@ -62,36 +62,4 @@ ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2700-2799/2752.Customers with Maximum Number of Transactions on Consecutive Days/README.md b/solution/2700-2799/2752.Customers with Maximum Number of Transactions on Consecutive Days/README.md index a5ed8aef3fdf8..d8a73ec378eb1 100644 --- a/solution/2700-2799/2752.Customers with Maximum Number of Transactions on Consecutive Days/README.md +++ b/solution/2700-2799/2752.Customers with Maximum Number of Transactions on Consecutive Days/README.md @@ -62,14 +62,10 @@ Transactions 表: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -97,3 +93,5 @@ ORDER BY customer_id; ``` + + diff --git a/solution/2700-2799/2752.Customers with Maximum Number of Transactions on Consecutive Days/README_EN.md b/solution/2700-2799/2752.Customers with Maximum Number of Transactions on Consecutive Days/README_EN.md index 8ad3bedbc8658..0b1d62309ccfe 100644 --- a/solution/2700-2799/2752.Customers with Maximum Number of Transactions on Consecutive Days/README_EN.md +++ b/solution/2700-2799/2752.Customers with Maximum Number of Transactions on Consecutive Days/README_EN.md @@ -60,9 +60,9 @@ In total, the highest number of consecutive transactions is 3, achieved by custo ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -91,3 +91,5 @@ ORDER BY customer_id; ``` + + diff --git a/solution/2700-2799/2753.Count Houses in a Circular Street II/README.md b/solution/2700-2799/2753.Count Houses in a Circular Street II/README.md index 3ca7a790b5d0c..2dd8df3686327 100644 --- a/solution/2700-2799/2753.Count Houses in a Circular Street II/README.md +++ b/solution/2700-2799/2753.Count Houses in a Circular Street II/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:脑筋急转弯** +### 方法一:脑筋急转弯 我们注意到,题目中至少有一扇门是开着的,我们可以先找到其中一扇开着的门。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python # Definition for a street. # class Street: @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a street. @@ -127,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a street. @@ -159,8 +147,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a street. @@ -185,8 +171,6 @@ func houseCount(street Street, k int) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a street. @@ -213,10 +197,6 @@ function houseCount(street: Street | null, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2753.Count Houses in a Circular Street II/README_EN.md b/solution/2700-2799/2753.Count Houses in a Circular Street II/README_EN.md index ecefc17c91cf4..e0472052baf32 100644 --- a/solution/2700-2799/2753.Count Houses in a Circular Street II/README_EN.md +++ b/solution/2700-2799/2753.Count Houses in a Circular Street II/README_EN.md @@ -50,9 +50,9 @@ The number of houses is equal to k, which is 5. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a street. @@ -75,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a street. @@ -105,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a street. @@ -137,8 +133,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a street. @@ -163,8 +157,6 @@ func houseCount(street Street, k int) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a street. @@ -191,10 +183,6 @@ function houseCount(street: Street | null, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2754.Bind Function to Context/README.md b/solution/2700-2799/2754.Bind Function to Context/README.md index a3d86d2477caf..0f75b5296e5e0 100644 --- a/solution/2700-2799/2754.Bind Function to Context/README.md +++ b/solution/2700-2799/2754.Bind Function to Context/README.md @@ -81,14 +81,10 @@ boundFunc(); // "My name is Kathy" ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts type Fn = (...args) => any; @@ -106,3 +102,5 @@ Function.prototype.bindPolyfill = function (obj) { ``` + + diff --git a/solution/2700-2799/2754.Bind Function to Context/README_EN.md b/solution/2700-2799/2754.Bind Function to Context/README_EN.md index c20407dfad9ad..ef29e9b2a1d17 100644 --- a/solution/2700-2799/2754.Bind Function to Context/README_EN.md +++ b/solution/2700-2799/2754.Bind Function to Context/README_EN.md @@ -77,9 +77,9 @@ boundFunc(); // "My name is Kathy" ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type Fn = (...args) => any; @@ -98,3 +98,5 @@ Function.prototype.bindPolyfill = function (obj) { ``` + + diff --git a/solution/2700-2799/2755.Deep Merge of Two Objects/README.md b/solution/2700-2799/2755.Deep Merge of Two Objects/README.md index 20b6e7115a637..98eaf81613ec4 100644 --- a/solution/2700-2799/2755.Deep Merge of Two Objects/README.md +++ b/solution/2700-2799/2755.Deep Merge of Two Objects/README.md @@ -67,14 +67,10 @@ obj2 = {"a": 1, "b": {"c": [6, [6], [9]], "e": 3}} ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function deepMerge(obj1: any, obj2: any): any { const isObj = (obj: any) => obj && typeof obj === 'object'; @@ -98,3 +94,5 @@ function deepMerge(obj1: any, obj2: any): any { ``` + + diff --git a/solution/2700-2799/2755.Deep Merge of Two Objects/README_EN.md b/solution/2700-2799/2755.Deep Merge of Two Objects/README_EN.md index 9dacb5c37acf9..10c60373d5b42 100644 --- a/solution/2700-2799/2755.Deep Merge of Two Objects/README_EN.md +++ b/solution/2700-2799/2755.Deep Merge of Two Objects/README_EN.md @@ -63,9 +63,9 @@ obj2["b"]["c"] has key "e" that obj1 doesn't h ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function deepMerge(obj1: any, obj2: any): any { @@ -90,3 +90,5 @@ function deepMerge(obj1: any, obj2: any): any { ``` + + diff --git a/solution/2700-2799/2756.Query Batching/README.md b/solution/2700-2799/2756.Query Batching/README.md index f94e10e1bda59..8ea8983365cfe 100644 --- a/solution/2700-2799/2756.Query Batching/README.md +++ b/solution/2700-2799/2756.Query Batching/README.md @@ -128,16 +128,4 @@ calls = [ ## 解法 - - - - -### **TypeScript** - - - -```ts - -``` - - + diff --git a/solution/2700-2799/2756.Query Batching/README_EN.md b/solution/2700-2799/2756.Query Batching/README_EN.md index 723d839c0a163..388de430f860a 100644 --- a/solution/2700-2799/2756.Query Batching/README_EN.md +++ b/solution/2700-2799/2756.Query Batching/README_EN.md @@ -122,12 +122,4 @@ queryMultiple(['f']) is called at t=350ms, it is resolved at 450ms ## Solutions - - -### **TypeScript** - -```ts - -``` - - + diff --git a/solution/2700-2799/2757.Generate Circular Array Values/README.md b/solution/2700-2799/2757.Generate Circular Array Values/README.md index 3baf0447fbe6b..11770bc14c16f 100644 --- a/solution/2700-2799/2757.Generate Circular Array Values/README.md +++ b/solution/2700-2799/2757.Generate Circular Array Values/README.md @@ -70,14 +70,10 @@ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function* cycleGenerator(arr: number[], startIndex: number): Generator { const n = arr.length; @@ -96,3 +92,5 @@ function* cycleGenerator(arr: number[], startIndex: number): Generator + + diff --git a/solution/2700-2799/2757.Generate Circular Array Values/README_EN.md b/solution/2700-2799/2757.Generate Circular Array Values/README_EN.md index 95dedc4c5a1da..d8a2a44ae3cd3 100644 --- a/solution/2700-2799/2757.Generate Circular Array Values/README_EN.md +++ b/solution/2700-2799/2757.Generate Circular Array Values/README_EN.md @@ -66,9 +66,9 @@ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function* cycleGenerator(arr: number[], startIndex: number): Generator { @@ -88,3 +88,5 @@ function* cycleGenerator(arr: number[], startIndex: number): Generator + + diff --git a/solution/2700-2799/2758.Next Day/README.md b/solution/2700-2799/2758.Next Day/README.md index a5fc88341916c..ff6c9f126eca6 100644 --- a/solution/2700-2799/2758.Next Day/README.md +++ b/solution/2700-2799/2758.Next Day/README.md @@ -38,14 +38,10 @@ date.nextDay(); // "2014-06-21" ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts declare global { interface Date { @@ -66,3 +62,5 @@ Date.prototype.nextDay = function () { ``` + + diff --git a/solution/2700-2799/2758.Next Day/README_EN.md b/solution/2700-2799/2758.Next Day/README_EN.md index d3f99efa1871f..5af45a8e3d8b1 100644 --- a/solution/2700-2799/2758.Next Day/README_EN.md +++ b/solution/2700-2799/2758.Next Day/README_EN.md @@ -34,9 +34,9 @@ date.nextDay(); // "2014-06-21" ## Solutions - +### Solution 1 -### **TypeScript** + ```ts declare global { @@ -58,3 +58,5 @@ Date.prototype.nextDay = function () { ``` + + diff --git a/solution/2700-2799/2759.Convert JSON String to Object/README.md b/solution/2700-2799/2759.Convert JSON String to Object/README.md index 54d97592c3e25..ad9cf3b9c8e73 100644 --- a/solution/2700-2799/2759.Convert JSON String to Object/README.md +++ b/solution/2700-2799/2759.Convert JSON String to Object/README.md @@ -44,14 +44,10 @@ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function jsonParse(str: string): any { const n = str.length; @@ -171,3 +167,5 @@ function jsonParse(str: string): any { ``` + + diff --git a/solution/2700-2799/2759.Convert JSON String to Object/README_EN.md b/solution/2700-2799/2759.Convert JSON String to Object/README_EN.md index 22426011cc0b4..5c64076bf2f7f 100644 --- a/solution/2700-2799/2759.Convert JSON String to Object/README_EN.md +++ b/solution/2700-2799/2759.Convert JSON String to Object/README_EN.md @@ -40,9 +40,9 @@ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function jsonParse(str: string): any { @@ -163,3 +163,5 @@ function jsonParse(str: string): any { ``` + + diff --git a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/README.md b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/README.md index 0ae6a20cda2ea..e82438b6a0dda 100644 --- a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/README.md +++ b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/README.md @@ -59,26 +59,14 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们在 $[0,..n-1]$ 范围内枚举所有 $l$,如果 $nums[l]$ 满足 $nums[l] \bmod 2 = 0$ 并且 $nums[l] \leq threshold$,那么我们就从 $l+1$ 开始,查找第一个不满足条件的 $r$,那么此时以 $nums[l]$ 作为左端点的最长奇偶子数组的长度为 $r - l$,取所有 $r - l$ 的最大值作为答案即可。 时间复杂度 $O(n^2)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 -**方法二:枚举优化** - -我们注意到,题目实际上会把数组划分成不相交的若干个满足条件的子数组,我们只需要找到这些子数组中最长的一个即可。因此,在枚举 $l$ 和 $r$ 时,我们不需要回退,只需要从左往右遍历一遍即可。 - -时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int: @@ -92,26 +80,6 @@ class Solution: return ans ``` -```python -class Solution: - def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int: - ans, l, n = 0, 0, len(nums) - while l < n: - if nums[l] % 2 == 0 and nums[l] <= threshold: - r = l + 1 - while r < n and nums[r] % 2 != nums[r - 1] % 2 and nums[r] <= threshold: - r += 1 - ans = max(ans, r - l) - l = r - else: - l += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int longestAlternatingSubarray(int[] nums, int threshold) { @@ -130,46 +98,103 @@ class Solution { } ``` -```java +```cpp class Solution { - public int longestAlternatingSubarray(int[] nums, int threshold) { - int ans = 0; - for (int l = 0, n = nums.length; l < n;) { +public: + int longestAlternatingSubarray(vector& nums, int threshold) { + int ans = 0, n = nums.size(); + for (int l = 0; l < n; ++l) { if (nums[l] % 2 == 0 && nums[l] <= threshold) { int r = l + 1; while (r < n && nums[r] % 2 != nums[r - 1] % 2 && nums[r] <= threshold) { ++r; } - ans = Math.max(ans, r - l); - l = r; - } else { - ++l; + ans = max(ans, r - l); } } return ans; } +}; +``` + +```go +func longestAlternatingSubarray(nums []int, threshold int) (ans int) { + n := len(nums) + for l := range nums { + if nums[l]%2 == 0 && nums[l] <= threshold { + r := l + 1 + for r < n && nums[r]%2 != nums[r-1]%2 && nums[r] <= threshold { + r++ + } + ans = max(ans, r-l) + } + } + return +} +``` + +```ts +function longestAlternatingSubarray(nums: number[], threshold: number): number { + const n = nums.length; + let ans = 0; + for (let l = 0; l < n; ++l) { + if (nums[l] % 2 === 0 && nums[l] <= threshold) { + let r = l + 1; + while (r < n && nums[r] % 2 !== nums[r - 1] % 2 && nums[r] <= threshold) { + ++r; + } + ans = Math.max(ans, r - l); + } + } + return ans; } ``` -### **C++** + -```cpp +### 方法二:枚举优化 + +我们注意到,题目实际上会把数组划分成不相交的若干个满足条件的子数组,我们只需要找到这些子数组中最长的一个即可。因此,在枚举 $l$ 和 $r$ 时,我们不需要回退,只需要从左往右遍历一遍即可。 + +时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int: + ans, l, n = 0, 0, len(nums) + while l < n: + if nums[l] % 2 == 0 and nums[l] <= threshold: + r = l + 1 + while r < n and nums[r] % 2 != nums[r - 1] % 2 and nums[r] <= threshold: + r += 1 + ans = max(ans, r - l) + l = r + else: + l += 1 + return ans +``` + +```java class Solution { -public: - int longestAlternatingSubarray(vector& nums, int threshold) { - int ans = 0, n = nums.size(); - for (int l = 0; l < n; ++l) { + public int longestAlternatingSubarray(int[] nums, int threshold) { + int ans = 0; + for (int l = 0, n = nums.length; l < n;) { if (nums[l] % 2 == 0 && nums[l] <= threshold) { int r = l + 1; while (r < n && nums[r] % 2 != nums[r - 1] % 2 && nums[r] <= threshold) { ++r; } - ans = max(ans, r - l); + ans = Math.max(ans, r - l); + l = r; + } else { + ++l; } } return ans; } -}; +} ``` ```cpp @@ -194,24 +219,6 @@ public: }; ``` -### **Go** - -```go -func longestAlternatingSubarray(nums []int, threshold int) (ans int) { - n := len(nums) - for l := range nums { - if nums[l]%2 == 0 && nums[l] <= threshold { - r := l + 1 - for r < n && nums[r]%2 != nums[r-1]%2 && nums[r] <= threshold { - r++ - } - ans = max(ans, r-l) - } - } - return -} -``` - ```go func longestAlternatingSubarray(nums []int, threshold int) (ans int) { for l, n := 0, len(nums); l < n; { @@ -230,25 +237,6 @@ func longestAlternatingSubarray(nums []int, threshold int) (ans int) { } ``` -### **TypeScript** - -```ts -function longestAlternatingSubarray(nums: number[], threshold: number): number { - const n = nums.length; - let ans = 0; - for (let l = 0; l < n; ++l) { - if (nums[l] % 2 === 0 && nums[l] <= threshold) { - let r = l + 1; - while (r < n && nums[r] % 2 !== nums[r - 1] % 2 && nums[r] <= threshold) { - ++r; - } - ans = Math.max(ans, r - l); - } - } - return ans; -} -``` - ```ts function longestAlternatingSubarray(nums: number[], threshold: number): number { const n = nums.length; @@ -269,10 +257,6 @@ function longestAlternatingSubarray(nums: number[], threshold: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/README_EN.md b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/README_EN.md index c263fd4573ae3..bcad4d5649e01 100644 --- a/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/README_EN.md +++ b/solution/2700-2799/2760.Longest Even Odd Subarray With Threshold/README_EN.md @@ -57,22 +57,14 @@ Hence, the answer is the length of the subarray, 3. We can show that 3 is the ma ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We enumerate all $l$ in the range $[0,..n-1]$. If $nums[l]$ satisfies $nums[l] \bmod 2 = 0$ and $nums[l] \leq threshold$, then we start from $l+1$ to find the largest $r$ that meets the condition. At this time, the length of the longest odd-even subarray with $nums[l]$ as the left endpoint is $r - l$. We take the maximum of all $r - l$ as the answer. The time complexity is $O(n^2)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. -**Solution 2: Optimized Enumeration** - -We notice that the problem actually divides the array into several disjoint subarrays that meet the condition. We only need to find the longest one among these subarrays. Therefore, when enumerating $l$ and $r$, we don't need to backtrack, we just need to traverse from left to right once. - -The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int: @@ -86,24 +78,6 @@ class Solution: return ans ``` -```python -class Solution: - def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int: - ans, l, n = 0, 0, len(nums) - while l < n: - if nums[l] % 2 == 0 and nums[l] <= threshold: - r = l + 1 - while r < n and nums[r] % 2 != nums[r - 1] % 2 and nums[r] <= threshold: - r += 1 - ans = max(ans, r - l) - l = r - else: - l += 1 - return ans -``` - -### **Java** - ```java class Solution { public int longestAlternatingSubarray(int[] nums, int threshold) { @@ -122,46 +96,103 @@ class Solution { } ``` -```java +```cpp class Solution { - public int longestAlternatingSubarray(int[] nums, int threshold) { - int ans = 0; - for (int l = 0, n = nums.length; l < n;) { +public: + int longestAlternatingSubarray(vector& nums, int threshold) { + int ans = 0, n = nums.size(); + for (int l = 0; l < n; ++l) { if (nums[l] % 2 == 0 && nums[l] <= threshold) { int r = l + 1; while (r < n && nums[r] % 2 != nums[r - 1] % 2 && nums[r] <= threshold) { ++r; } - ans = Math.max(ans, r - l); - l = r; - } else { - ++l; + ans = max(ans, r - l); } } return ans; } +}; +``` + +```go +func longestAlternatingSubarray(nums []int, threshold int) (ans int) { + n := len(nums) + for l := range nums { + if nums[l]%2 == 0 && nums[l] <= threshold { + r := l + 1 + for r < n && nums[r]%2 != nums[r-1]%2 && nums[r] <= threshold { + r++ + } + ans = max(ans, r-l) + } + } + return +} +``` + +```ts +function longestAlternatingSubarray(nums: number[], threshold: number): number { + const n = nums.length; + let ans = 0; + for (let l = 0; l < n; ++l) { + if (nums[l] % 2 === 0 && nums[l] <= threshold) { + let r = l + 1; + while (r < n && nums[r] % 2 !== nums[r - 1] % 2 && nums[r] <= threshold) { + ++r; + } + ans = Math.max(ans, r - l); + } + } + return ans; } ``` -### **C++** + -```cpp +### Solution 2: Optimized Enumeration + +We notice that the problem actually divides the array into several disjoint subarrays that meet the condition. We only need to find the longest one among these subarrays. Therefore, when enumerating $l$ and $r$, we don't need to backtrack, we just need to traverse from left to right once. + +The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. + + + +```python +class Solution: + def longestAlternatingSubarray(self, nums: List[int], threshold: int) -> int: + ans, l, n = 0, 0, len(nums) + while l < n: + if nums[l] % 2 == 0 and nums[l] <= threshold: + r = l + 1 + while r < n and nums[r] % 2 != nums[r - 1] % 2 and nums[r] <= threshold: + r += 1 + ans = max(ans, r - l) + l = r + else: + l += 1 + return ans +``` + +```java class Solution { -public: - int longestAlternatingSubarray(vector& nums, int threshold) { - int ans = 0, n = nums.size(); - for (int l = 0; l < n; ++l) { + public int longestAlternatingSubarray(int[] nums, int threshold) { + int ans = 0; + for (int l = 0, n = nums.length; l < n;) { if (nums[l] % 2 == 0 && nums[l] <= threshold) { int r = l + 1; while (r < n && nums[r] % 2 != nums[r - 1] % 2 && nums[r] <= threshold) { ++r; } - ans = max(ans, r - l); + ans = Math.max(ans, r - l); + l = r; + } else { + ++l; } } return ans; } -}; +} ``` ```cpp @@ -186,24 +217,6 @@ public: }; ``` -### **Go** - -```go -func longestAlternatingSubarray(nums []int, threshold int) (ans int) { - n := len(nums) - for l := range nums { - if nums[l]%2 == 0 && nums[l] <= threshold { - r := l + 1 - for r < n && nums[r]%2 != nums[r-1]%2 && nums[r] <= threshold { - r++ - } - ans = max(ans, r-l) - } - } - return -} -``` - ```go func longestAlternatingSubarray(nums []int, threshold int) (ans int) { for l, n := 0, len(nums); l < n; { @@ -222,25 +235,6 @@ func longestAlternatingSubarray(nums []int, threshold int) (ans int) { } ``` -### **TypeScript** - -```ts -function longestAlternatingSubarray(nums: number[], threshold: number): number { - const n = nums.length; - let ans = 0; - for (let l = 0; l < n; ++l) { - if (nums[l] % 2 === 0 && nums[l] <= threshold) { - let r = l + 1; - while (r < n && nums[r] % 2 !== nums[r - 1] % 2 && nums[r] <= threshold) { - ++r; - } - ans = Math.max(ans, r - l); - } - } - return ans; -} -``` - ```ts function longestAlternatingSubarray(nums: number[], threshold: number): number { const n = nums.length; @@ -261,10 +255,6 @@ function longestAlternatingSubarray(nums: number[], threshold: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2761.Prime Pairs With Target Sum/README.md b/solution/2700-2799/2761.Prime Pairs With Target Sum/README.md index d6e831ad63c47..ff4b528cd4e4e 100644 --- a/solution/2700-2799/2761.Prime Pairs With Target Sum/README.md +++ b/solution/2700-2799/2761.Prime Pairs With Target Sum/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:预处理 + 枚举** +### 方法一:预处理 + 枚举 我们先预处理出 $n$ 范围内的所有质数,记录在数组 $primes$ 中,其中 $primes[i]$ 为 `true` 表示 $i$ 是一个质数。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def findPrimePairs(self, n: int) -> List[List[int]]: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List> findPrimePairs(int n) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func findPrimePairs(n int) (ans [][]int) { primes := make([]bool, n) @@ -159,8 +145,6 @@ func findPrimePairs(n int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function findPrimePairs(n: number): number[][] { const primes: boolean[] = new Array(n).fill(true); @@ -182,10 +166,6 @@ function findPrimePairs(n: number): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2761.Prime Pairs With Target Sum/README_EN.md b/solution/2700-2799/2761.Prime Pairs With Target Sum/README_EN.md index b1310eb046150..98815acba4d31 100644 --- a/solution/2700-2799/2761.Prime Pairs With Target Sum/README_EN.md +++ b/solution/2700-2799/2761.Prime Pairs With Target Sum/README_EN.md @@ -43,7 +43,7 @@ These pairs are [3,7] and [5,5], and we return them in the sorted order as descr ## Solutions -**Solution 1: Preprocessing + Enumeration** +### Solution 1: Preprocessing + Enumeration First, we pre-process all the prime numbers within the range of $n$, and record them in the array $primes$, where $primes[i]$ is `true` if $i$ is a prime number. @@ -55,8 +55,6 @@ The time complexity is $O(n \log \log n)$ and the space complexity is $O(n)$, wh -### **Python3** - ```python class Solution: def findPrimePairs(self, n: int) -> List[List[int]]: @@ -73,8 +71,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List> findPrimePairs(int n) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +120,6 @@ public: }; ``` -### **Go** - ```go func findPrimePairs(n int) (ans [][]int) { primes := make([]bool, n) @@ -151,8 +143,6 @@ func findPrimePairs(n int) (ans [][]int) { } ``` -### **TypeScript** - ```ts function findPrimePairs(n: number): number[][] { const primes: boolean[] = new Array(n).fill(true); @@ -174,10 +164,6 @@ function findPrimePairs(n: number): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2762.Continuous Subarrays/README.md b/solution/2700-2799/2762.Continuous Subarrays/README.md index f7381d800dd5d..9448b4185a994 100644 --- a/solution/2700-2799/2762.Continuous Subarrays/README.md +++ b/solution/2700-2799/2762.Continuous Subarrays/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:有序列表 + 双指针** +### 方法一:有序列表 + 双指针 我们可以用双指针 $i$ 和 $j$ 维护当前子数组的左右端点,用一个有序列表维护当前子数组的所有元素。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -90,10 +84,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long continuousSubarrays(int[] nums) { @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func continuousSubarrays(nums []int) (ans int64) { i := 0 @@ -169,10 +155,6 @@ func continuousSubarrays(nums []int) (ans int64) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2762.Continuous Subarrays/README_EN.md b/solution/2700-2799/2762.Continuous Subarrays/README_EN.md index 2737ff350f0b2..49b17957c8793 100644 --- a/solution/2700-2799/2762.Continuous Subarrays/README_EN.md +++ b/solution/2700-2799/2762.Continuous Subarrays/README_EN.md @@ -53,7 +53,7 @@ Total continuous subarrays = 3 + 2 + 1 = 6. ## Solutions -**Solution 1: Ordered List + Two Pointers** +### Solution 1: Ordered List + Two Pointers We can use two pointers, $i$ and $j$, to maintain the left and right endpoints of the current subarray, and use an ordered list to maintain all elements in the current subarray. @@ -65,8 +65,6 @@ The time complexity is $O(n \times \log n)$ and the space complexity is $O(n)$, -### **Python3** - ```python from sortedcontainers import SortedList @@ -84,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long continuousSubarrays(int[] nums) { @@ -108,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +123,6 @@ public: }; ``` -### **Go** - ```go func continuousSubarrays(nums []int) (ans int64) { i := 0 @@ -161,10 +153,6 @@ func continuousSubarrays(nums []int) (ans int64) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/README.md b/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/README.md index 04acf1d23ace2..eb0d065ae12ef 100644 --- a/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/README.md +++ b/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:枚举 + 有序集合** +### 方法一:枚举 + 有序集合 我们可以先枚举子数组的左端点 $i$,对于每个 $i$,我们从小到大枚举子数组的右端点 $j$,并且用一个有序列表维护当前子数组中的所有元素,用一个变量 $cnt$ 维护当前子数组的不平衡数字。 @@ -75,10 +73,6 @@ -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -104,10 +98,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int sumImbalanceNumbers(int[] nums) { @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,16 +156,6 @@ public: }; ``` -### **Go** - -```go - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/README_EN.md b/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/README_EN.md index e2ae6dd171e09..a187f38bd3815 100644 --- a/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/README_EN.md +++ b/solution/2700-2799/2763.Sum of Imbalance Numbers of All Subarrays/README_EN.md @@ -55,7 +55,7 @@ The imbalance number of all other subarrays is 0. Hence, the sum of imbalance nu ## Solutions -**Solution 1: Enumeration + Ordered Set** +### Solution 1: Enumeration + Ordered Set We can first enumerate the left endpoint $i$ of the subarray. For each $i$, we enumerate the right endpoint $j$ of the subarray from small to large, and maintain all the elements in the current subarray with an ordered list. We also use a variable $cnt$ to maintain the unbalanced number of the current subarray. @@ -71,8 +71,6 @@ The time complexity is $O(n^2 \times \log n)$ and the space complexity is $O(n)$ -### **Python3** - ```python from sortedcontainers import SortedList @@ -98,8 +96,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int sumImbalanceNumbers(int[] nums) { @@ -129,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,16 +154,6 @@ public: }; ``` -### **Go** - -```go - -``` - -### **...** - -``` - -``` - + + diff --git "a/solution/2700-2799/2764.Is Array a Preorder of Some \342\200\214Binary Tree/README.md" "b/solution/2700-2799/2764.Is Array a Preorder of Some \342\200\214Binary Tree/README.md" index cacf01ce645b3..e89dc1bf98b9b 100644 --- "a/solution/2700-2799/2764.Is Array a Preorder of Some \342\200\214Binary Tree/README.md" +++ "b/solution/2700-2799/2764.Is Array a Preorder of Some \342\200\214Binary Tree/README.md" @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们先根据 $nodes$ 数据构建图 $g$,其中 $g[i]$ 表示节点 $i$ 的所有子节点。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def isPreorder(self, nodes: List[List[int]]) -> bool: @@ -92,10 +86,6 @@ class Solution: return dfs(nodes[0][0]) and k == len(nodes) ``` -### **Java** - - - ```java class Solution { private Map> g = new HashMap<>(); @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func isPreorder(nodes [][]int) bool { k := 0 @@ -179,8 +165,6 @@ func isPreorder(nodes [][]int) bool { } ``` -### **TypeScript** - ```ts function isPreorder(nodes: number[][]): boolean { let k = 0; @@ -207,10 +191,6 @@ function isPreorder(nodes: number[][]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git "a/solution/2700-2799/2764.Is Array a Preorder of Some \342\200\214Binary Tree/README_EN.md" "b/solution/2700-2799/2764.Is Array a Preorder of Some \342\200\214Binary Tree/README_EN.md" index f6bc683163e36..00ab1987d7810 100644 --- "a/solution/2700-2799/2764.Is Array a Preorder of Some \342\200\214Binary Tree/README_EN.md" +++ "b/solution/2700-2799/2764.Is Array a Preorder of Some \342\200\214Binary Tree/README_EN.md" @@ -48,24 +48,10 @@ For the preorder traversal, first we visit node 0, then we do the preorder trave ## Solutions -**Solution 1:Depth-First Search** - -First, we construct a graph $g$ based on the $nodes$ data, where $g[i]$ represents all the child nodes of node $i$. - -Next, we design a function $dfs(i)$, which represents a pre-order traversal starting from node $i$. We use a variable $k$ to represent the $k$-th node in the $nodes$ list that we have currently traversed, with an initial value of $k = 0$. - -The execution logic of the function $dfs(i)$ is as follows: - -If $i \neq nodes[k][0]$, it indicates that the current sequence is not a pre-order traversal sequence of a binary tree, and returns false. -Otherwise, we increment $k$ by $1$, and then recursively search all child nodes of $i$. If a false is found during the search, we return false immediately. Otherwise, when the search is finished, we return true. -In the main function, we call $dfs(nodes[0][0])$. If the return value is true and $k = |nodes|$, then the $nodes$ sequence is a pre-order traversal sequence of a binary tree, and we return true; otherwise, we return false. - -The time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the number of nodes in $nodes$. +### Solution 1 -### **Python3** - ```python class Solution: def isPreorder(self, nodes: List[List[int]]) -> bool: @@ -83,8 +69,6 @@ class Solution: return dfs(nodes[0][0]) and k == len(nodes) ``` -### **Java** - ```java class Solution { private Map> g = new HashMap<>(); @@ -114,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +124,6 @@ public: }; ``` -### **Go** - ```go func isPreorder(nodes [][]int) bool { k := 0 @@ -168,8 +148,6 @@ func isPreorder(nodes [][]int) bool { } ``` -### **TypeScript** - ```ts function isPreorder(nodes: number[][]): boolean { let k = 0; @@ -196,10 +174,6 @@ function isPreorder(nodes: number[][]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2765.Longest Alternating Subarray/README.md b/solution/2700-2799/2765.Longest Alternating Subarray/README.md index f9907318d44a0..0be4ed8dddba2 100644 --- a/solution/2700-2799/2765.Longest Alternating Subarray/README.md +++ b/solution/2700-2799/2765.Longest Alternating Subarray/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举子数组的左端点 $i$,对于每个 $i$,我们需要找到最长的满足条件的子数组。我们可以从 $i$ 开始向右遍历,每次遇到相邻元素差值不满足交替条件时,我们就找到了一个满足条件的子数组。我们可以用一个变量 $k$ 来记录当前元素的差值应该是 $1$ 还是 $-1$,如果当前元素的差值应该是 $-k$,那么我们就将 $k$ 取反。当我们找到一个满足条件的子数组 $nums[i..j]$ 时,我们更新答案为 $\max(ans, j - i + 1)$。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def alternatingSubarray(self, nums: List[int]) -> int: @@ -76,10 +70,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int alternatingSubarray(int[] nums) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +109,6 @@ public: }; ``` -### **Go** - ```go func alternatingSubarray(nums []int) int { ans, n := -1, len(nums) @@ -140,8 +126,6 @@ func alternatingSubarray(nums []int) int { } ``` -### **TypeScript** - ```ts function alternatingSubarray(nums: number[]): number { let ans = -1; @@ -160,10 +144,6 @@ function alternatingSubarray(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2765.Longest Alternating Subarray/README_EN.md b/solution/2700-2799/2765.Longest Alternating Subarray/README_EN.md index fe6abe52fbec4..9bb39e33248a3 100644 --- a/solution/2700-2799/2765.Longest Alternating Subarray/README_EN.md +++ b/solution/2700-2799/2765.Longest Alternating Subarray/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We can enumerate the left endpoint $i$ of the subarray, and for each $i$, we need to find the longest subarray that satisfies the condition. We can start traversing to the right from $i$, and each time we encounter adjacent elements whose difference does not satisfy the alternating condition, we find a subarray that satisfies the condition. We can use a variable $k$ to record whether the difference of the current element should be $1$ or $-1$. If the difference of the current element should be $-k$, then we take the opposite of $k$. When we find a subarray $nums[i..j]$ that satisfies the condition, we update the answer to $\max(ans, j - i + 1)$. @@ -51,8 +51,6 @@ The time complexity is $O(n^2)$, where $n$ is the length of the array. We need t -### **Python3** - ```python class Solution: def alternatingSubarray(self, nums: List[int]) -> int: @@ -68,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int alternatingSubarray(int[] nums) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -111,8 +105,6 @@ public: }; ``` -### **Go** - ```go func alternatingSubarray(nums []int) int { ans, n := -1, len(nums) @@ -130,8 +122,6 @@ func alternatingSubarray(nums []int) int { } ``` -### **TypeScript** - ```ts function alternatingSubarray(nums: number[]): number { let ans = -1; @@ -150,10 +140,6 @@ function alternatingSubarray(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2766.Relocate Marbles/README.md b/solution/2700-2799/2766.Relocate Marbles/README.md index 9571a6c0c509f..d9cc0d5c6f35e 100644 --- a/solution/2700-2799/2766.Relocate Marbles/README.md +++ b/solution/2700-2799/2766.Relocate Marbles/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们用一个哈希表 $pos$ 记录所有有石块的位置,初始时 $pos$ 中包含 $nums$ 中的所有元素。然后我们遍历 $moveFrom$ 和 $moveTo$,每次将 $moveFrom[i]$ 从 $pos$ 中移除,再将 $moveTo[i]$ 添加到 $pos$ 中。最后我们将 $pos$ 中的元素排序后返回即可。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def relocateMarbles( @@ -83,10 +77,6 @@ class Solution: return sorted(pos) ``` -### **Java** - - - ```java class Solution { public List relocateMarbles(int[] nums, int[] moveFrom, int[] moveTo) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func relocateMarbles(nums []int, moveFrom []int, moveTo []int) (ans []int) { pos := map[int]bool{} @@ -146,8 +132,6 @@ func relocateMarbles(nums []int, moveFrom []int, moveTo []int) (ans []int) { } ``` -### **TypeScript** - ```ts function relocateMarbles(nums: number[], moveFrom: number[], moveTo: number[]): number[] { const pos: Set = new Set(nums); @@ -161,10 +145,6 @@ function relocateMarbles(nums: number[], moveFrom: number[], moveTo: number[]): } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2766.Relocate Marbles/README_EN.md b/solution/2700-2799/2766.Relocate Marbles/README_EN.md index a11c7e9fe0293..cd5e43dac7405 100644 --- a/solution/2700-2799/2766.Relocate Marbles/README_EN.md +++ b/solution/2700-2799/2766.Relocate Marbles/README_EN.md @@ -53,7 +53,7 @@ Since 2 is the only occupied position, we return [2]. ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table Let's use a hash table $pos$ to record all stone positions. Initially, $pos$ contains all elements of $nums$. Then we iterate through $moveFrom$ and $moveTo$. Each time, we remove $moveFrom[i]$ from $pos$ and add $moveTo[i]$ to $pos$. Finally, we sort the elements in $pos$ and return. @@ -61,8 +61,6 @@ The time complexity is $O(n \times \log n)$ and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def relocateMarbles( @@ -75,8 +73,6 @@ class Solution: return sorted(pos) ``` -### **Java** - ```java class Solution { public List relocateMarbles(int[] nums, int[] moveFrom, int[] moveTo) { @@ -95,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +107,6 @@ public: }; ``` -### **Go** - ```go func relocateMarbles(nums []int, moveFrom []int, moveTo []int) (ans []int) { pos := map[int]bool{} @@ -136,8 +128,6 @@ func relocateMarbles(nums []int, moveFrom []int, moveTo []int) (ans []int) { } ``` -### **TypeScript** - ```ts function relocateMarbles(nums: number[], moveFrom: number[], moveTo: number[]): number[] { const pos: Set = new Set(nums); @@ -151,10 +141,6 @@ function relocateMarbles(nums: number[], moveFrom: number[], moveTo: number[]): } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2767.Partition String Into Minimum Beautiful Substrings/README.md b/solution/2700-2799/2767.Partition String Into Minimum Beautiful Substrings/README.md index 07b57dc16868e..7412ab2085898 100644 --- a/solution/2700-2799/2767.Partition String Into Minimum Beautiful Substrings/README.md +++ b/solution/2700-2799/2767.Partition String Into Minimum Beautiful Substrings/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 题目中需要判断一个字符串是否是 $5$ 的幂的二进制表示,因此,我们不妨先预处理出所有 $5$ 的幂的数字,记录在哈希表 $ss$ 中。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def minimumBeautifulSubstrings(self, s: str) -> int: @@ -111,10 +105,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - - - ```java class Solution { private Integer[] f; @@ -158,8 +148,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -199,8 +187,6 @@ public: }; ``` -### **Go** - ```go func minimumBeautifulSubstrings(s string) int { ss := map[int]bool{} @@ -241,8 +227,6 @@ func minimumBeautifulSubstrings(s string) int { } ``` -### **TypeScript** - ```ts function minimumBeautifulSubstrings(s: string): number { const ss: Set = new Set(); @@ -276,10 +260,6 @@ function minimumBeautifulSubstrings(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2767.Partition String Into Minimum Beautiful Substrings/README_EN.md b/solution/2700-2799/2767.Partition String Into Minimum Beautiful Substrings/README_EN.md index aae9b23192644..1c9b9c5d179fc 100644 --- a/solution/2700-2799/2767.Partition String Into Minimum Beautiful Substrings/README_EN.md +++ b/solution/2700-2799/2767.Partition String Into Minimum Beautiful Substrings/README_EN.md @@ -57,7 +57,7 @@ It can be shown that 3 is the minimum number of beautiful substrings that s can ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search Since the problem requires us to judge whether a string is the binary representation of a power of $5$, we might as well first preprocess all the powers of $5$ and record them in a hash table $ss$. @@ -77,8 +77,6 @@ Time complexity $O(n^2)$, space complexity $O(n)$. Where $n$ is the length of st -### **Python3** - ```python class Solution: def minimumBeautifulSubstrings(self, s: str) -> int: @@ -106,8 +104,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - ```java class Solution { private Integer[] f; @@ -151,8 +147,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -192,8 +186,6 @@ public: }; ``` -### **Go** - ```go func minimumBeautifulSubstrings(s string) int { ss := map[int]bool{} @@ -234,8 +226,6 @@ func minimumBeautifulSubstrings(s string) int { } ``` -### **TypeScript** - ```ts function minimumBeautifulSubstrings(s: string): number { const ss: Set = new Set(); @@ -269,10 +259,6 @@ function minimumBeautifulSubstrings(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2768.Number of Black Blocks/README.md b/solution/2700-2799/2768.Number of Black Blocks/README.md index dd51f0d125a14..a3ba86f00fb64 100644 --- a/solution/2700-2799/2768.Number of Black Blocks/README.md +++ b/solution/2700-2799/2768.Number of Black Blocks/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:哈希表计数** +### 方法一:哈希表计数 对于每个 $2 \times 2$ 的子矩阵,我们可以用其左上角的坐标 $(x, y)$ 来表示它。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def countBlackBlocks( @@ -94,10 +88,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long[] countBlackBlocks(int m, int n, int[][] coordinates) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -151,8 +139,6 @@ public: }; ``` -### **Go** - ```go func countBlackBlocks(m int, n int, coordinates [][]int) []int64 { cnt := map[int64]int{} @@ -176,8 +162,6 @@ func countBlackBlocks(m int, n int, coordinates [][]int) []int64 { } ``` -### **TypeScript** - ```ts function countBlackBlocks(m: number, n: number, coordinates: number[][]): number[] { const cnt: Map = new Map(); @@ -201,10 +185,6 @@ function countBlackBlocks(m: number, n: number, coordinates: number[][]): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2768.Number of Black Blocks/README_EN.md b/solution/2700-2799/2768.Number of Black Blocks/README_EN.md index 3bd063c5da161..5746ac60cbcee 100644 --- a/solution/2700-2799/2768.Number of Black Blocks/README_EN.md +++ b/solution/2700-2799/2768.Number of Black Blocks/README_EN.md @@ -52,7 +52,7 @@ Therefore, we return [0,2,2,0,0]. ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table For each $2 \times 2$ submatrix, we can use its upper-left corner coordinate $(x, y)$ to represent it. @@ -66,8 +66,6 @@ Time complexity $O(l)$, space complexity $O(l)$, where $l$ is the length of $coo -### **Python3** - ```python class Solution: def countBlackBlocks( @@ -86,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long[] countBlackBlocks(int m, int n, int[][] coordinates) { @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +135,6 @@ public: }; ``` -### **Go** - ```go func countBlackBlocks(m int, n int, coordinates [][]int) []int64 { cnt := map[int64]int{} @@ -166,8 +158,6 @@ func countBlackBlocks(m int, n int, coordinates [][]int) []int64 { } ``` -### **TypeScript** - ```ts function countBlackBlocks(m: number, n: number, coordinates: number[][]): number[] { const cnt: Map = new Map(); @@ -191,10 +181,6 @@ function countBlackBlocks(m: number, n: number, coordinates: number[][]): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2769.Find the Maximum Achievable Number/README.md b/solution/2700-2799/2769.Find the Maximum Achievable Number/README.md index 9e20a29bd59a9..4782741306a93 100644 --- a/solution/2700-2799/2769.Find the Maximum Achievable Number/README.md +++ b/solution/2700-2799/2769.Find the Maximum Achievable Number/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 我们注意到,每次操作可以将 $x$ 减少 $1$,同时将 $num$ 增加 $1$,这样 $x$ 和 $num$ 的差值就会减少 $2$,而最多可以操作 $t$ 次,所以最大可达成数字为 $num + t \times 2$。 @@ -57,20 +55,12 @@ -### **Python3** - - - ```python class Solution: def theMaximumAchievableX(self, num: int, t: int) -> int: return num + t * 2 ``` -### **Java** - - - ```java class Solution { public int theMaximumAchievableX(int num, int t) { @@ -79,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -90,26 +78,18 @@ public: }; ``` -### **Go** - ```go func theMaximumAchievableX(num int, t int) int { return num + t*2 } ``` -### **TypeScript** - ```ts function theMaximumAchievableX(num: number, t: number): number { return num + t * 2; } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2769.Find the Maximum Achievable Number/README_EN.md b/solution/2700-2799/2769.Find the Maximum Achievable Number/README_EN.md index 86af5160f2036..9001d7b3cc39d 100644 --- a/solution/2700-2799/2769.Find the Maximum Achievable Number/README_EN.md +++ b/solution/2700-2799/2769.Find the Maximum Achievable Number/README_EN.md @@ -46,7 +46,7 @@ It can be proven that there is no achievable number larger than 7. ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics Notice that every time we can decrease $x$ by $1$ and increase $num$ by $1$, the difference between $x$ and $num$ will decrease by $2$, and we can do this operation at most $t$ times, so the maximum reachable number is $num + t \times 2$. @@ -54,16 +54,12 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def theMaximumAchievableX(self, num: int, t: int) -> int: return num + t * 2 ``` -### **Java** - ```java class Solution { public int theMaximumAchievableX(int num, int t) { @@ -72,8 +68,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -83,26 +77,18 @@ public: }; ``` -### **Go** - ```go func theMaximumAchievableX(num int, t int) int { return num + t*2 } ``` -### **TypeScript** - ```ts function theMaximumAchievableX(num: number, t: number): number { return num + t * 2; } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2770.Maximum Number of Jumps to Reach the Last Index/README.md b/solution/2700-2799/2770.Maximum Number of Jumps to Reach the Last Index/README.md index a3d06c7bd4226..a2ab6b33b3645 100644 --- a/solution/2700-2799/2770.Maximum Number of Jumps to Reach the Last Index/README.md +++ b/solution/2700-2799/2770.Maximum Number of Jumps to Reach the Last Index/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 对于每个位置 $i$,我们考虑向后搜索能跳到的位置 $j$,如果满足 $|nums[i] - nums[j]| \leq target$,那么我们就可以从 $i$ 跳到 $j$,并且从 $j$ 开始继续向后搜索。 @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def maximumJumps(self, nums: List[int], target: int) -> int: @@ -103,10 +97,6 @@ class Solution: return -1 if ans < 0 else ans ``` -### **Java** - - - ```java class Solution { private Integer[] f; @@ -141,8 +131,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -171,8 +159,6 @@ public: }; ``` -### **Go** - ```go func maximumJumps(nums []int, target int) int { n := len(nums) @@ -211,8 +197,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function maximumJumps(nums: number[], target: number): number { const n = nums.length; @@ -237,10 +221,6 @@ function maximumJumps(nums: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2770.Maximum Number of Jumps to Reach the Last Index/README_EN.md b/solution/2700-2799/2770.Maximum Number of Jumps to Reach the Last Index/README_EN.md index a0ef8c7fefdb9..140b1261bf709 100644 --- a/solution/2700-2799/2770.Maximum Number of Jumps to Reach the Last Index/README_EN.md +++ b/solution/2700-2799/2770.Maximum Number of Jumps to Reach the Last Index/README_EN.md @@ -61,7 +61,7 @@ It can be proven that there is no other jumping sequence that goes from 0 to n - ## Solutions -**Solution 1: Memoization** +### Solution 1: Memoization For each position $i$, we consider to jump to position $j$ which satisfies $|nums[i] - nums[j]| \leq target$. Then we can jump from $i$ to $j$, and continue to jump from $j$ to the end. @@ -78,8 +78,6 @@ Time complexity $O(n^2)$, space complexity $O(n)$. where $n$ is the length of ar -### **Python3** - ```python class Solution: def maximumJumps(self, nums: List[int], target: int) -> int: @@ -98,8 +96,6 @@ class Solution: return -1 if ans < 0 else ans ``` -### **Java** - ```java class Solution { private Integer[] f; @@ -134,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +158,6 @@ public: }; ``` -### **Go** - ```go func maximumJumps(nums []int, target int) int { n := len(nums) @@ -204,8 +196,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function maximumJumps(nums: number[], target: number): number { const n = nums.length; @@ -230,10 +220,6 @@ function maximumJumps(nums: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2771.Longest Non-decreasing Subarray From Two Arrays/README.md b/solution/2700-2799/2771.Longest Non-decreasing Subarray From Two Arrays/README.md index 99d89c62beb45..9934c8c546d16 100644 --- a/solution/2700-2799/2771.Longest Non-decreasing Subarray From Two Arrays/README.md +++ b/solution/2700-2799/2771.Longest Non-decreasing Subarray From Two Arrays/README.md @@ -56,9 +56,7 @@ nums3 = [nums1[0], nums1[1]] => [1,1] ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义两个变量 $f$ 和 $g$,分别表示当前位置的最长非递减子数组长度,其中 $f$ 表示以 $nums1$ 元素为结尾的最长非递减子数组长度,而 $g$ 表示以 $nums2$ 元素为结尾的最长非递减子数组长度。初始时 $f = g = 1$,初始答案 $ans = 1$。 @@ -79,10 +77,6 @@ nums3 = [nums1[0], nums1[1]] => [1,1] -### **Python3** - - - ```python class Solution: def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int: @@ -104,10 +98,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxNonDecreasingLength(int[] nums1, int[] nums2) { @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -169,8 +157,6 @@ public: }; ``` -### **Go** - ```go func maxNonDecreasingLength(nums1 []int, nums2 []int) int { n := len(nums1) @@ -196,8 +182,6 @@ func maxNonDecreasingLength(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - ```ts function maxNonDecreasingLength(nums1: number[], nums2: number[]): number { const n = nums1.length; @@ -224,10 +208,6 @@ function maxNonDecreasingLength(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2771.Longest Non-decreasing Subarray From Two Arrays/README_EN.md b/solution/2700-2799/2771.Longest Non-decreasing Subarray From Two Arrays/README_EN.md index 05394260f6de4..bf29d323044d8 100644 --- a/solution/2700-2799/2771.Longest Non-decreasing Subarray From Two Arrays/README_EN.md +++ b/solution/2700-2799/2771.Longest Non-decreasing Subarray From Two Arrays/README_EN.md @@ -55,29 +55,10 @@ The entire array forms a non-decreasing subarray of length 2, making it the maxi ## Solutions -**Solution 1:Dynamic Programming** - -We define two variables $f$ and $g$, which represent the longest non-decreasing subarray length at the current position, where $f$ represents the longest non-decreasing subarray length ending in the $nums1$ element, and $g$ represents the longest non-decreasing subarray length ending in the $nums2$ element. At the beginning, $f = g = 1$, and the initial answer $ans = 1$. - -Next, we traverse the array elements in the range of $i \in [1, n)$, for each $i$, we define two variables $ff$ and $gg$, which represent the longest non-decreasing subarray length ending in the $nums1[i]$ and $nums2[i]$ element, respectively, and initialize $ff = gg = 1$. - -We can calculate the value of $ff$ and $gg$ from the values of $f$ and $g$: - -- If $nums1[i] \ge nums1[i - 1]$, then $ff = max(ff, f + 1)$; -- If $nums1[i] \ge nums2[i - 1]$, then $ff = max(ff, g + 1)$; -- If $nums2[i] \ge nums1[i - 1]$, then $gg = max(gg, f + 1)$; -- If $nums2[i] \ge nums2[i - 1]$, then $gg = max(gg, g + 1)$. - -Then, we update $f = ff$ and $g = gg$, and update $ans$ to $max(ans, f, g)$. - -After the traversal is over, we return $ans$. - -The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$. +### Solution 1 -### **Python3** - ```python class Solution: def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int: @@ -99,8 +80,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxNonDecreasingLength(int[] nums1, int[] nums2) { @@ -130,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +139,6 @@ public: }; ``` -### **Go** - ```go func maxNonDecreasingLength(nums1 []int, nums2 []int) int { n := len(nums1) @@ -189,8 +164,6 @@ func maxNonDecreasingLength(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - ```ts function maxNonDecreasingLength(nums1: number[], nums2: number[]): number { const n = nums1.length; @@ -217,10 +190,6 @@ function maxNonDecreasingLength(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2772.Apply Operations to Make All Array Elements Equal to Zero/README.md b/solution/2700-2799/2772.Apply Operations to Make All Array Elements Equal to Zero/README.md index 9976857d6f30f..40e321c4e7074 100644 --- a/solution/2700-2799/2772.Apply Operations to Make All Array Elements Equal to Zero/README.md +++ b/solution/2700-2799/2772.Apply Operations to Make All Array Elements Equal to Zero/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:差分数组 + 前缀和** +### 方法一:差分数组 + 前缀和 我们先考虑 $nums$ 的第一个元素 $nums[0]$: @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def checkArray(self, nums: List[int], k: int) -> bool: @@ -93,10 +87,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean checkArray(int[] nums, int k) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func checkArray(nums []int, k int) bool { n := len(nums) @@ -169,8 +155,6 @@ func checkArray(nums []int, k int) bool { } ``` -### **TypeScript** - ```ts function checkArray(nums: number[], k: number): boolean { const n = nums.length; @@ -192,10 +176,6 @@ function checkArray(nums: number[], k: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2772.Apply Operations to Make All Array Elements Equal to Zero/README_EN.md b/solution/2700-2799/2772.Apply Operations to Make All Array Elements Equal to Zero/README_EN.md index 7295d1529bb46..774f179d16370 100644 --- a/solution/2700-2799/2772.Apply Operations to Make All Array Elements Equal to Zero/README_EN.md +++ b/solution/2700-2799/2772.Apply Operations to Make All Array Elements Equal to Zero/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Difference Array + Prefix Sum** +### Solution 1: Difference Array + Prefix Sum First, let's consider the first element of $nums$, $nums[0]$: @@ -67,8 +67,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is -### **Python3** - ```python class Solution: def checkArray(self, nums: List[int], k: int) -> bool: @@ -87,8 +85,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean checkArray(int[] nums, int k) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +132,6 @@ public: }; ``` -### **Go** - ```go func checkArray(nums []int, k int) bool { n := len(nums) @@ -161,8 +153,6 @@ func checkArray(nums []int, k int) bool { } ``` -### **TypeScript** - ```ts function checkArray(nums: number[], k: number): boolean { const n = nums.length; @@ -184,10 +174,6 @@ function checkArray(nums: number[], k: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2773.Height of Special Binary Tree/README.md b/solution/2700-2799/2773.Height of Special Binary Tree/README.md index 26e9397c2c553..2a8b1f60c2c15 100644 --- a/solution/2700-2799/2773.Height of Special Binary Tree/README.md +++ b/solution/2700-2799/2773.Height of Special Binary Tree/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 题目的关键在于如何判断一个节点是叶子节点,我们设计一个函数 $dfs(root, d)$,其中 $root$ 表示当前节点,而 $d$ 表示当前节点的深度,我们每次搜索时,更新答案 $ans = \max(ans, d)$,然后判断当前节点是否为叶子节点,如果当前节点有左子节点,且左子节点的右子节点不是当前节点,那么我们递归调用 $dfs(root.left, d + 1)$,如果当前节点有右子节点,且右子节点的左子节点不是当前节点,那么我们递归调用 $dfs(root.right, d + 1)$。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -100,10 +94,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -173,8 +161,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -203,8 +189,6 @@ func heightOfTree(root *TreeNode) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -236,10 +220,6 @@ function heightOfTree(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2773.Height of Special Binary Tree/README_EN.md b/solution/2700-2799/2773.Height of Special Binary Tree/README_EN.md index bd3d699e836e9..4270dceeb12db 100644 --- a/solution/2700-2799/2773.Height of Special Binary Tree/README_EN.md +++ b/solution/2700-2799/2773.Height of Special Binary Tree/README_EN.md @@ -60,9 +60,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -86,8 +86,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -124,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -157,8 +153,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -187,8 +181,6 @@ func heightOfTree(root *TreeNode) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a binary tree node. @@ -220,10 +212,6 @@ function heightOfTree(root: TreeNode | null): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2774.Array Upper Bound/README.md b/solution/2700-2799/2774.Array Upper Bound/README.md index b88ef281bff47..92bf7efcd3675 100644 --- a/solution/2700-2799/2774.Array Upper Bound/README.md +++ b/solution/2700-2799/2774.Array Upper Bound/README.md @@ -49,14 +49,10 @@ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts declare global { interface Array { @@ -83,6 +79,12 @@ Array.prototype.upperBound = function (target: number) { // [3,4,6,6,6,6,7].upperBound(6) // 5 ``` + + +### 方法二 + + + ```ts declare global { interface Array { @@ -100,3 +102,5 @@ Array.prototype.upperBound = function (target: number) { ``` + + diff --git a/solution/2700-2799/2774.Array Upper Bound/README_EN.md b/solution/2700-2799/2774.Array Upper Bound/README_EN.md index 6d6d17e5247f8..56d11644e993d 100644 --- a/solution/2700-2799/2774.Array Upper Bound/README_EN.md +++ b/solution/2700-2799/2774.Array Upper Bound/README_EN.md @@ -44,9 +44,9 @@ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts declare global { @@ -74,6 +74,12 @@ Array.prototype.upperBound = function (target: number) { // [3,4,6,6,6,6,7].upperBound(6) // 5 ``` + + +### Solution 2 + + + ```ts declare global { interface Array { @@ -91,3 +97,5 @@ Array.prototype.upperBound = function (target: number) { ``` + + diff --git a/solution/2700-2799/2775.Undefined to Null/README.md b/solution/2700-2799/2775.Undefined to Null/README.md index 8e7277cb4b6ef..534881134848c 100644 --- a/solution/2700-2799/2775.Undefined to Null/README.md +++ b/solution/2700-2799/2775.Undefined to Null/README.md @@ -39,14 +39,10 @@ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function undefinedToNull(obj: Record): Record { for (const key in obj) { @@ -67,3 +63,5 @@ function undefinedToNull(obj: Record): Record { ``` + + diff --git a/solution/2700-2799/2775.Undefined to Null/README_EN.md b/solution/2700-2799/2775.Undefined to Null/README_EN.md index 6e5eebe69ac64..e44f3b49171e1 100644 --- a/solution/2700-2799/2775.Undefined to Null/README_EN.md +++ b/solution/2700-2799/2775.Undefined to Null/README_EN.md @@ -35,9 +35,9 @@ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function undefinedToNull(obj: Record): Record { @@ -59,3 +59,5 @@ function undefinedToNull(obj: Record): Record { ``` + + diff --git a/solution/2700-2799/2776.Convert Callback Based Function to Promise Based Function/README.md b/solution/2700-2799/2776.Convert Callback Based Function to Promise Based Function/README.md index 22ec0e94f0b42..fbc3921ebc3e6 100644 --- a/solution/2700-2799/2776.Convert Callback Based Function to Promise Based Function/README.md +++ b/solution/2700-2799/2776.Convert Callback Based Function to Promise Based Function/README.md @@ -82,14 +82,10 @@ fn 以回调函数作为第一个参数和 args 作为其余参数进行调用 ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts type CallbackFn = (next: (data: number, error: string) => void, ...args: number[]) => void; type Promisified = (...args: number[]) => Promise; @@ -115,3 +111,5 @@ function promisify(fn: CallbackFn): Promisified { ``` + + diff --git a/solution/2700-2799/2776.Convert Callback Based Function to Promise Based Function/README_EN.md b/solution/2700-2799/2776.Convert Callback Based Function to Promise Based Function/README_EN.md index 269e80ba8a88c..dbcbc9e450380 100644 --- a/solution/2700-2799/2776.Convert Callback Based Function to Promise Based Function/README_EN.md +++ b/solution/2700-2799/2776.Convert Callback Based Function to Promise Based Function/README_EN.md @@ -78,9 +78,9 @@ fn is called with a callback as the first argument and args as the rest. As the ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type CallbackFn = (next: (data: number, error: string) => void, ...args: number[]) => void; @@ -107,3 +107,5 @@ function promisify(fn: CallbackFn): Promisified { ``` + + diff --git a/solution/2700-2799/2777.Date Range Generator/README.md b/solution/2700-2799/2777.Date Range Generator/README.md index ff473be1dbdcd..7cfb234b3beef 100644 --- a/solution/2700-2799/2777.Date Range Generator/README.md +++ b/solution/2700-2799/2777.Date Range Generator/README.md @@ -56,14 +56,10 @@ g.next().value // '2023-04-10' ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function* dateRangeGenerator(start: string, end: string, step: number): Generator { const startDate = new Date(start); @@ -86,3 +82,5 @@ function* dateRangeGenerator(start: string, end: string, step: number): Generato ``` + + diff --git a/solution/2700-2799/2777.Date Range Generator/README_EN.md b/solution/2700-2799/2777.Date Range Generator/README_EN.md index e1a1a058e382a..ff010b8df7799 100644 --- a/solution/2700-2799/2777.Date Range Generator/README_EN.md +++ b/solution/2700-2799/2777.Date Range Generator/README_EN.md @@ -52,9 +52,9 @@ g.next().value // '2023-04-10' ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function* dateRangeGenerator(start: string, end: string, step: number): Generator { @@ -78,3 +78,5 @@ function* dateRangeGenerator(start: string, end: string, step: number): Generato ``` + + diff --git a/solution/2700-2799/2778.Sum of Squares of Special Elements/README.md b/solution/2700-2799/2778.Sum of Squares of Special Elements/README.md index 009bcb1d798bf..67a71647090c0 100644 --- a/solution/2700-2799/2778.Sum of Squares of Special Elements/README.md +++ b/solution/2700-2799/2778.Sum of Squares of Special Elements/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举数组中的每个元素,判断其是否为特殊元素,如果是则将其平方加入答案中。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def sumOfSquares(self, nums: List[int]) -> int: @@ -63,10 +57,6 @@ class Solution: return sum(x * x for i, x in enumerate(nums, 1) if n % i == 0) ``` -### **Java** - - - ```java class Solution { public int sumOfSquares(int[] nums) { @@ -82,8 +72,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -100,8 +88,6 @@ public: }; ``` -### **Go** - ```go func sumOfSquares(nums []int) (ans int) { n := len(nums) @@ -114,8 +100,6 @@ func sumOfSquares(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumOfSquares(nums: number[]): number { const n = nums.length; @@ -129,10 +113,6 @@ function sumOfSquares(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2778.Sum of Squares of Special Elements/README_EN.md b/solution/2700-2799/2778.Sum of Squares of Special Elements/README_EN.md index 6aaeb8c4153f6..6d766be0a39ff 100644 --- a/solution/2700-2799/2778.Sum of Squares of Special Elements/README_EN.md +++ b/solution/2700-2799/2778.Sum of Squares of Special Elements/README_EN.md @@ -39,9 +39,9 @@ Hence, the sum of the squares of all special elements of nums is nums[1] * nums[ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -50,8 +50,6 @@ class Solution: return sum(x * x for i, x in enumerate(nums, 1) if n % i == 0) ``` -### **Java** - ```java class Solution { public int sumOfSquares(int[] nums) { @@ -67,8 +65,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -85,8 +81,6 @@ public: }; ``` -### **Go** - ```go func sumOfSquares(nums []int) (ans int) { n := len(nums) @@ -99,8 +93,6 @@ func sumOfSquares(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumOfSquares(nums: number[]): number { const n = nums.length; @@ -114,10 +106,6 @@ function sumOfSquares(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/README.md b/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/README.md index 879fe86dfc9a7..6212813e55556 100644 --- a/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/README.md +++ b/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 我们注意到,对于每一次操作,区间 $[nums[i]-k, nums[i]+k]$ 内的所有元素都会增加 $1$,因此我们可以使用差分数组来记录这些操作对美丽值的贡献。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def maximumBeauty(self, nums: List[int], k: int) -> int: @@ -90,10 +84,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maximumBeauty(int[] nums, int k) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func maximumBeauty(nums []int, k int) (ans int) { m := slices.Max(nums) @@ -157,8 +143,6 @@ func maximumBeauty(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function maximumBeauty(nums: number[], k: number): number { const m = Math.max(...nums) + k * 2 + 2; @@ -177,10 +161,6 @@ function maximumBeauty(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/README_EN.md b/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/README_EN.md index 43f8662677a66..950b3275dccc7 100644 --- a/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/README_EN.md +++ b/solution/2700-2799/2779.Maximum Beauty of an Array After Applying Operation/README_EN.md @@ -53,9 +53,9 @@ The beauty of the array nums is 4 (whole array). ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maximumBeauty(int[] nums, int k) { @@ -93,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +111,6 @@ public: }; ``` -### **Go** - ```go func maximumBeauty(nums []int, k int) (ans int) { m := slices.Max(nums) @@ -137,8 +131,6 @@ func maximumBeauty(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function maximumBeauty(nums: number[], k: number): number { const m = Math.max(...nums) + k * 2 + 2; @@ -157,10 +149,6 @@ function maximumBeauty(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2780.Minimum Index of a Valid Split/README.md b/solution/2700-2799/2780.Minimum Index of a Valid Split/README.md index 2559118f333e6..74d970f3ceb74 100644 --- a/solution/2700-2799/2780.Minimum Index of a Valid Split/README.md +++ b/solution/2700-2799/2780.Minimum Index of a Valid Split/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们用哈希表统计每个元素出现的次数,然后找出出现次数最多的元素 $x$,即为支配元素。要使得分割后的两个数组中都有支配元素,且支配元素相同,那么支配元素一定是 $x$。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def minimumIndex(self, nums: List[int]) -> int: @@ -91,10 +85,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int minimumIndex(List nums) { @@ -121,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func minimumIndex(nums []int) int { x, cnt := 0, 0 @@ -176,8 +162,6 @@ func minimumIndex(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumIndex(nums: number[]): number { let [x, cnt] = [0, 0]; @@ -201,10 +185,6 @@ function minimumIndex(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2780.Minimum Index of a Valid Split/README_EN.md b/solution/2700-2799/2780.Minimum Index of a Valid Split/README_EN.md index 0cebc2ec363da..018404a8b8ca9 100644 --- a/solution/2700-2799/2780.Minimum Index of a Valid Split/README_EN.md +++ b/solution/2700-2799/2780.Minimum Index of a Valid Split/README_EN.md @@ -61,9 +61,9 @@ It can be shown that index 4 is the minimum index of a valid split. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,8 +78,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int minimumIndex(List nums) { @@ -106,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +131,6 @@ public: }; ``` -### **Go** - ```go func minimumIndex(nums []int) int { x, cnt := 0, 0 @@ -161,8 +155,6 @@ func minimumIndex(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumIndex(nums: number[]): number { let [x, cnt] = [0, 0]; @@ -186,10 +178,6 @@ function minimumIndex(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2781.Length of the Longest Valid Substring/README.md b/solution/2700-2799/2781.Length of the Longest Valid Substring/README.md index 6e871f7ce3e45..8e455af35559b 100644 --- a/solution/2700-2799/2781.Length of the Longest Valid Substring/README.md +++ b/solution/2700-2799/2781.Length of the Longest Valid Substring/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:哈希表 + 双指针** +### 方法一:哈希表 + 双指针 我们用哈希表 $s$ 记录所有禁止的字符串,然后用双指针 $i$ 和 $j$ 遍历字符串 $word$,其中 $i$ 和 $j$ 分别表示当前合法子字符串的左右边界。 @@ -59,10 +57,6 @@ -### **Python3** - - - ```python class Solution: def longestValidSubstring(self, word: str, forbidden: List[str]) -> int: @@ -77,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int longestValidSubstring(String word, List forbidden) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func longestValidSubstring(word string, forbidden []string) (ans int) { s := map[string]bool{} @@ -144,8 +130,6 @@ func longestValidSubstring(word string, forbidden []string) (ans int) { } ``` -### **TypeScript** - ```ts function longestValidSubstring(word: string, forbidden: string[]): number { const s: Set = new Set(forbidden); @@ -164,10 +148,6 @@ function longestValidSubstring(word: string, forbidden: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2781.Length of the Longest Valid Substring/README_EN.md b/solution/2700-2799/2781.Length of the Longest Valid Substring/README_EN.md index ac4f95c94f5e0..340f3d6aeb78c 100644 --- a/solution/2700-2799/2781.Length of the Longest Valid Substring/README_EN.md +++ b/solution/2700-2799/2781.Length of the Longest Valid Substring/README_EN.md @@ -43,9 +43,9 @@ It can be shown that all other substrings contain either "de", "l ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int longestValidSubstring(String word, List forbidden) { @@ -82,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +100,6 @@ public: }; ``` -### **Go** - ```go func longestValidSubstring(word string, forbidden []string) (ans int) { s := map[string]bool{} @@ -126,8 +120,6 @@ func longestValidSubstring(word string, forbidden []string) (ans int) { } ``` -### **TypeScript** - ```ts function longestValidSubstring(word: string, forbidden: string[]): number { const s: Set = new Set(forbidden); @@ -146,10 +138,6 @@ function longestValidSubstring(word: string, forbidden: string[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2782.Number of Unique Categories/README.md b/solution/2700-2799/2782.Number of Unique Categories/README.md index 72b481e4e8d49..c88dc69dbcb16 100644 --- a/solution/2700-2799/2782.Number of Unique Categories/README.md +++ b/solution/2700-2799/2782.Number of Unique Categories/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:并查集** +### 方法一:并查集 我们用并查集来维护相同类别的元素,接下来枚举所有的元素对,如果两个元素属于相同的类别,那么就将它们合并到同一个集合中。最后统计并查集中有多少个集合,就是答案。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python # Definition for a category handler. # class CategoryHandler: @@ -90,10 +84,6 @@ class Solution: return sum(i == x for i, x in enumerate(p)) ``` -### **Java** - - - ```java /** * Definition for a category handler. @@ -135,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a category handler. @@ -173,8 +161,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a category handler. @@ -210,8 +196,6 @@ func numberOfCategories(n int, categoryHandler CategoryHandler) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a category handler. @@ -245,10 +229,6 @@ function numberOfCategories(n: number, categoryHandler: CategoryHandler): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2782.Number of Unique Categories/README_EN.md b/solution/2700-2799/2782.Number of Unique Categories/README_EN.md index 853dd9dee9682..d86f94e33e246 100644 --- a/solution/2700-2799/2782.Number of Unique Categories/README_EN.md +++ b/solution/2700-2799/2782.Number of Unique Categories/README_EN.md @@ -50,9 +50,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a category handler. @@ -76,8 +76,6 @@ class Solution: return sum(i == x for i, x in enumerate(p)) ``` -### **Java** - ```java /** * Definition for a category handler. @@ -119,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a category handler. @@ -157,8 +153,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a category handler. @@ -194,8 +188,6 @@ func numberOfCategories(n int, categoryHandler CategoryHandler) (ans int) { } ``` -### **TypeScript** - ```ts /** * Definition for a category handler. @@ -229,10 +221,6 @@ function numberOfCategories(n: number, categoryHandler: CategoryHandler): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2783.Flight Occupancy and Waitlist Analysis/README.md b/solution/2700-2799/2783.Flight Occupancy and Waitlist Analysis/README.md index a49ad53704cf9..d4ed13a04f2a2 100644 --- a/solution/2700-2799/2783.Flight Occupancy and Waitlist Analysis/README.md +++ b/solution/2700-2799/2783.Flight Occupancy and Waitlist Analysis/README.md @@ -81,9 +81,7 @@ Passengers table: ## 解法 - - -**方法一:左连接 + 分组** +### 方法一:左连接 + 分组 我们可以使用左连接将 `Flights` 和 `Passengers` 表连接起来,然后按照 `flight_id` 分组,统计每个航班的乘客数量。 @@ -91,10 +89,6 @@ Passengers table: -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -109,3 +103,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2700-2799/2783.Flight Occupancy and Waitlist Analysis/README_EN.md b/solution/2700-2799/2783.Flight Occupancy and Waitlist Analysis/README_EN.md index 899804f853470..cce11c54b839d 100644 --- a/solution/2700-2799/2783.Flight Occupancy and Waitlist Analysis/README_EN.md +++ b/solution/2700-2799/2783.Flight Occupancy and Waitlist Analysis/README_EN.md @@ -79,9 +79,9 @@ Passengers table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -97,3 +97,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2700-2799/2784.Check if Array is Good/README.md b/solution/2700-2799/2784.Check if Array is Good/README.md index ede09e725920f..4d8e9721e90b3 100644 --- a/solution/2700-2799/2784.Check if Array is Good/README.md +++ b/solution/2700-2799/2784.Check if Array is Good/README.md @@ -53,14 +53,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def isGood(self, nums: List[int]) -> bool: @@ -72,10 +68,6 @@ class Solution: return all(v == 0 for v in cnt.values()) ``` -### **Java** - - - ```java class Solution { public boolean isGood(int[] nums) { @@ -98,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +113,6 @@ public: }; ``` -### **Go** - ```go func isGood(nums []int) bool { n := len(nums) - 1 @@ -145,8 +133,6 @@ func isGood(nums []int) bool { } ``` -### **TypeScript** - ```ts function isGood(nums: number[]): boolean { const n = nums.length - 1; @@ -162,10 +148,6 @@ function isGood(nums: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2784.Check if Array is Good/README_EN.md b/solution/2700-2799/2784.Check if Array is Good/README_EN.md index 3aebc55b70478..7b4acd0836cea 100644 --- a/solution/2700-2799/2784.Check if Array is Good/README_EN.md +++ b/solution/2700-2799/2784.Check if Array is Good/README_EN.md @@ -53,9 +53,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return all(v == 0 for v in cnt.values()) ``` -### **Java** - ```java class Solution { public boolean isGood(int[] nums) { @@ -92,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +113,6 @@ public: }; ``` -### **Go** - ```go func isGood(nums []int) bool { n := len(nums) - 1 @@ -139,8 +133,6 @@ func isGood(nums []int) bool { } ``` -### **TypeScript** - ```ts function isGood(nums: number[]): boolean { const n = nums.length - 1; @@ -156,10 +148,6 @@ function isGood(nums: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2785.Sort Vowels in a String/README.md b/solution/2700-2799/2785.Sort Vowels in a String/README.md index 9680ee488c319..daa7bbc5f5c4f 100644 --- a/solution/2700-2799/2785.Sort Vowels in a String/README.md +++ b/solution/2700-2799/2785.Sort Vowels in a String/README.md @@ -46,14 +46,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def sortVowels(self, s: str) -> str: @@ -68,10 +64,6 @@ class Solution: return "".join(cs) ``` -### **Java** - - - ```java class Solution { public String sortVowels(String s) { @@ -95,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +110,6 @@ public: }; ``` -### **Go** - ```go func sortVowels(s string) string { cs := []byte(s) @@ -145,8 +133,6 @@ func sortVowels(s string) string { } ``` -### **TypeScript** - ```ts function sortVowels(s: string): string { const vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']; @@ -163,8 +149,6 @@ function sortVowels(s: string): string { } ``` -### **C#** - ```cs public class Solution { public string SortVowels(string s) { @@ -191,10 +175,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2785.Sort Vowels in a String/README_EN.md b/solution/2700-2799/2785.Sort Vowels in a String/README_EN.md index 8355285940173..3848c23a6edfd 100644 --- a/solution/2700-2799/2785.Sort Vowels in a String/README_EN.md +++ b/solution/2700-2799/2785.Sort Vowels in a String/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -60,8 +60,6 @@ class Solution: return "".join(cs) ``` -### **Java** - ```java class Solution { public String sortVowels(String s) { @@ -85,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +106,6 @@ public: }; ``` -### **Go** - ```go func sortVowels(s string) string { cs := []byte(s) @@ -135,8 +129,6 @@ func sortVowels(s string) string { } ``` -### **TypeScript** - ```ts function sortVowels(s: string): string { const vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']; @@ -153,8 +145,6 @@ function sortVowels(s: string): string { } ``` -### **C#** - ```cs public class Solution { public string SortVowels(string s) { @@ -181,10 +171,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2786.Visit Array Positions to Maximize Score/README.md b/solution/2700-2799/2786.Visit Array Positions to Maximize Score/README.md index d85bb0732b0fc..c960fbdf947f1 100644 --- a/solution/2700-2799/2786.Visit Array Positions to Maximize Score/README.md +++ b/solution/2700-2799/2786.Visit Array Positions to Maximize Score/README.md @@ -50,14 +50,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxScore(self, nums: List[int], x: int) -> int: @@ -68,10 +64,6 @@ class Solution: return max(f) ``` -### **Java** - - - ```java class Solution { public long maxScore(int[] nums, int x) { @@ -86,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +94,6 @@ public: }; ``` -### **Go** - ```go func maxScore(nums []int, x int) int64 { const inf int = 1 << 40 @@ -118,8 +106,6 @@ func maxScore(nums []int, x int) int64 { } ``` -### **TypeScript** - ```ts function maxScore(nums: number[], x: number): number { const inf = 1 << 30; @@ -132,10 +118,6 @@ function maxScore(nums: number[], x: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2786.Visit Array Positions to Maximize Score/README_EN.md b/solution/2700-2799/2786.Visit Array Positions to Maximize Score/README_EN.md index b34eb411f3023..510e5a12d3617 100644 --- a/solution/2700-2799/2786.Visit Array Positions to Maximize Score/README_EN.md +++ b/solution/2700-2799/2786.Visit Array Positions to Maximize Score/README_EN.md @@ -48,9 +48,9 @@ The total score is: 2 + 4 + 6 + 8 = 20. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -62,8 +62,6 @@ class Solution: return max(f) ``` -### **Java** - ```java class Solution { public long maxScore(int[] nums, int x) { @@ -78,8 +76,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -96,8 +92,6 @@ public: }; ``` -### **Go** - ```go func maxScore(nums []int, x int) int64 { const inf int = 1 << 40 @@ -110,8 +104,6 @@ func maxScore(nums []int, x int) int64 { } ``` -### **TypeScript** - ```ts function maxScore(nums: number[], x: number): number { const inf = 1 << 30; @@ -124,10 +116,6 @@ function maxScore(nums: number[], x: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2787.Ways to Express an Integer as Sum of Powers/README.md b/solution/2700-2799/2787.Ways to Express an Integer as Sum of Powers/README.md index 715e4873e087a..dfc9203b632ee 100644 --- a/solution/2700-2799/2787.Ways to Express an Integer as Sum of Powers/README.md +++ b/solution/2700-2799/2787.Ways to Express an Integer as Sum of Powers/README.md @@ -44,14 +44,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def numberOfWays(self, n: int, x: int) -> int: @@ -67,10 +63,6 @@ class Solution: return f[n][n] ``` -### **Java** - - - ```java class Solution { public int numberOfWays(int n, int x) { @@ -91,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +105,6 @@ public: }; ``` -### **Go** - ```go func numberOfWays(n int, x int) int { const mod int = 1e9 + 7 @@ -138,8 +126,6 @@ func numberOfWays(n int, x int) int { } ``` -### **TypeScript** - ```ts function numberOfWays(n: number, x: number): number { const mod = 10 ** 9 + 7; @@ -160,10 +146,6 @@ function numberOfWays(n: number, x: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2787.Ways to Express an Integer as Sum of Powers/README_EN.md b/solution/2700-2799/2787.Ways to Express an Integer as Sum of Powers/README_EN.md index b301e42aaaf34..4cb81ba5cd0ce 100644 --- a/solution/2700-2799/2787.Ways to Express an Integer as Sum of Powers/README_EN.md +++ b/solution/2700-2799/2787.Ways to Express an Integer as Sum of Powers/README_EN.md @@ -42,9 +42,9 @@ It can be shown that it is the only way to express 10 as the sum of the 2nd ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return f[n][n] ``` -### **Java** - ```java class Solution { public int numberOfWays(int n, int x) { @@ -83,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +103,6 @@ public: }; ``` -### **Go** - ```go func numberOfWays(n int, x int) int { const mod int = 1e9 + 7 @@ -130,8 +124,6 @@ func numberOfWays(n int, x int) int { } ``` -### **TypeScript** - ```ts function numberOfWays(n: number, x: number): number { const mod = 10 ** 9 + 7; @@ -152,10 +144,6 @@ function numberOfWays(n: number, x: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2788.Split Strings by Separator/README.md b/solution/2700-2799/2788.Split Strings by Separator/README.md index 24597cc13c420..8c2c8a603b708 100644 --- a/solution/2700-2799/2788.Split Strings by Separator/README.md +++ b/solution/2700-2799/2788.Split Strings by Separator/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们遍历字符串数组 $words$,对于每个字符串 $w$,我们使用 `separator` 作为分隔符进行拆分,如果拆分后的字符串不为空,则将其加入答案数组。 @@ -76,20 +74,12 @@ -### **Python3** - - - ```python class Solution: def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]: return [s for w in words for s in w.split(separator) if s] ``` -### **Java** - - - ```java import java.util.regex.Pattern; @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func splitWordsBySeparator(words []string, separator byte) (ans []string) { for _, w := range words { @@ -144,18 +130,12 @@ func splitWordsBySeparator(words []string, separator byte) (ans []string) { } ``` -### **TypeScript** - ```ts function splitWordsBySeparator(words: string[], separator: string): string[] { return words.flatMap(w => w.split(separator).filter(s => s.length > 0)); } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2788.Split Strings by Separator/README_EN.md b/solution/2700-2799/2788.Split Strings by Separator/README_EN.md index 71294a6c0b96e..95d78ba14eee6 100644 --- a/solution/2700-2799/2788.Split Strings by Separator/README_EN.md +++ b/solution/2700-2799/2788.Split Strings by Separator/README_EN.md @@ -62,7 +62,7 @@ Hence, the resulting array is ["easy","problem"]. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We traverse the string array $words$. For each string $w$, we use `separator` as the delimiter to split it. If the split string is not empty, we add it to the answer array. @@ -70,16 +70,12 @@ The time complexity is $O(n \times m)$, and the space complexity is $O(m)$, wher -### **Python3** - ```python class Solution: def splitWordsBySeparator(self, words: List[str], separator: str) -> List[str]: return [s for w in words for s in w.split(separator) if s] ``` -### **Java** - ```java import java.util.regex.Pattern; @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +113,6 @@ public: }; ``` -### **Go** - ```go func splitWordsBySeparator(words []string, separator byte) (ans []string) { for _, w := range words { @@ -134,18 +126,12 @@ func splitWordsBySeparator(words []string, separator byte) (ans []string) { } ``` -### **TypeScript** - ```ts function splitWordsBySeparator(words: string[], separator: string): string[] { return words.flatMap(w => w.split(separator).filter(s => s.length > 0)); } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2789.Largest Element in an Array after Merge Operations/README.md b/solution/2700-2799/2789.Largest Element in an Array after Merge Operations/README.md index 871d0286ccae2..47788f863112d 100644 --- a/solution/2700-2799/2789.Largest Element in an Array after Merge Operations/README.md +++ b/solution/2700-2799/2789.Largest Element in an Array after Merge Operations/README.md @@ -50,14 +50,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxArrayValue(self, nums: List[int]) -> int: @@ -67,10 +63,6 @@ class Solution: return max(nums) ``` -### **Java** - - - ```java class Solution { public long maxArrayValue(int[] nums) { @@ -89,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +100,6 @@ public: }; ``` -### **Go** - ```go func maxArrayValue(nums []int) int64 { n := len(nums) @@ -128,8 +116,6 @@ func maxArrayValue(nums []int) int64 { } ``` -### **TypeScript** - ```ts function maxArrayValue(nums: number[]): number { for (let i = nums.length - 2; i >= 0; --i) { @@ -141,10 +127,6 @@ function maxArrayValue(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2789.Largest Element in an Array after Merge Operations/README_EN.md b/solution/2700-2799/2789.Largest Element in an Array after Merge Operations/README_EN.md index b8b4d20e2c8d7..57ad7f8d99acc 100644 --- a/solution/2700-2799/2789.Largest Element in an Array after Merge Operations/README_EN.md +++ b/solution/2700-2799/2789.Largest Element in an Array after Merge Operations/README_EN.md @@ -48,9 +48,9 @@ There is only one element in the final array, which is 11. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,8 +61,6 @@ class Solution: return max(nums) ``` -### **Java** - ```java class Solution { public long maxArrayValue(int[] nums) { @@ -81,8 +79,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +98,6 @@ public: }; ``` -### **Go** - ```go func maxArrayValue(nums []int) int64 { n := len(nums) @@ -120,8 +114,6 @@ func maxArrayValue(nums []int) int64 { } ``` -### **TypeScript** - ```ts function maxArrayValue(nums: number[]): number { for (let i = nums.length - 2; i >= 0; --i) { @@ -133,10 +125,6 @@ function maxArrayValue(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/README.md b/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/README.md index 8d662b4e67b40..d239904be81ec 100644 --- a/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/README.md +++ b/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/README.md @@ -68,14 +68,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxIncreasingGroups(self, usageLimits: List[int]) -> int: @@ -90,23 +86,6 @@ class Solution: return k ``` -```python -class Solution: - def maxIncreasingGroups(self, usageLimits: List[int]) -> int: - usageLimits.sort() - k = s = 0 - for x in usageLimits: - s += x - if s > k: - k += 1 - s -= k - return k -``` - -### **Java** - - - ```java class Solution { public int maxIncreasingGroups(List usageLimits) { @@ -125,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +123,6 @@ public: }; ``` -### **Go** - ```go func maxIncreasingGroups(usageLimits []int) int { sort.Ints(usageLimits) @@ -163,8 +138,6 @@ func maxIncreasingGroups(usageLimits []int) int { } ``` -### **TypeScript** - ```ts function maxIncreasingGroups(usageLimits: number[]): number { usageLimits.sort((a, b) => a - b); @@ -181,10 +154,25 @@ function maxIncreasingGroups(usageLimits: number[]): number { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def maxIncreasingGroups(self, usageLimits: List[int]) -> int: + usageLimits.sort() + k = s = 0 + for x in usageLimits: + s += x + if s > k: + k += 1 + s -= k + return k ``` + + diff --git a/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/README_EN.md b/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/README_EN.md index c1f0cd451a915..120197797cc3e 100644 --- a/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/README_EN.md +++ b/solution/2700-2799/2790.Maximum Number of Groups With Increasing Length/README_EN.md @@ -64,9 +64,9 @@ So, the output is 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,21 +82,6 @@ class Solution: return k ``` -```python -class Solution: - def maxIncreasingGroups(self, usageLimits: List[int]) -> int: - usageLimits.sort() - k = s = 0 - for x in usageLimits: - s += x - if s > k: - k += 1 - s -= k - return k -``` - -### **Java** - ```java class Solution { public int maxIncreasingGroups(List usageLimits) { @@ -115,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +119,6 @@ public: }; ``` -### **Go** - ```go func maxIncreasingGroups(usageLimits []int) int { sort.Ints(usageLimits) @@ -153,8 +134,6 @@ func maxIncreasingGroups(usageLimits []int) int { } ``` -### **TypeScript** - ```ts function maxIncreasingGroups(usageLimits: number[]): number { usageLimits.sort((a, b) => a - b); @@ -171,10 +150,25 @@ function maxIncreasingGroups(usageLimits: number[]): number { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def maxIncreasingGroups(self, usageLimits: List[int]) -> int: + usageLimits.sort() + k = s = 0 + for x in usageLimits: + s += x + if s > k: + k += 1 + s -= k + return k ``` + + diff --git a/solution/2700-2799/2791.Count Paths That Can Form a Palindrome in a Tree/README.md b/solution/2700-2799/2791.Count Paths That Can Form a Palindrome in a Tree/README.md index 25918cdcf2221..6b469924f3678 100644 --- a/solution/2700-2799/2791.Count Paths That Can Form a Palindrome in a Tree/README.md +++ b/solution/2700-2799/2791.Count Paths That Can Form a Palindrome in a Tree/README.md @@ -53,14 +53,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def countPalindromePaths(self, parent: List[int], s: str) -> int: @@ -85,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -123,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -155,8 +145,6 @@ public: }; ``` -### **Go** - ```go func countPalindromePaths(parent []int, s string) (ans int64) { type pair struct{ i, v int } @@ -184,8 +172,6 @@ func countPalindromePaths(parent []int, s string) (ans int64) { } ``` -### **TypeScript** - ```ts function countPalindromePaths(parent: number[], s: string): number { const n = parent.length; @@ -212,10 +198,6 @@ function countPalindromePaths(parent: number[], s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2791.Count Paths That Can Form a Palindrome in a Tree/README_EN.md b/solution/2700-2799/2791.Count Paths That Can Form a Palindrome in a Tree/README_EN.md index 6d97a486e0dcf..5ec81828c3188 100644 --- a/solution/2700-2799/2791.Count Paths That Can Form a Palindrome in a Tree/README_EN.md +++ b/solution/2700-2799/2791.Count Paths That Can Form a Palindrome in a Tree/README_EN.md @@ -49,9 +49,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -77,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -113,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +141,6 @@ public: }; ``` -### **Go** - ```go func countPalindromePaths(parent []int, s string) (ans int64) { type pair struct{ i, v int } @@ -174,8 +168,6 @@ func countPalindromePaths(parent []int, s string) (ans int64) { } ``` -### **TypeScript** - ```ts function countPalindromePaths(parent: number[], s: string): number { const n = parent.length; @@ -202,10 +194,6 @@ function countPalindromePaths(parent: number[], s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2792.Count Nodes That Are Great Enough/README.md b/solution/2700-2799/2792.Count Nodes That Are Great Enough/README.md index 76da7185dc29e..4b65cbb4d48b1 100644 --- a/solution/2700-2799/2792.Count Nodes That Are Great Enough/README.md +++ b/solution/2700-2799/2792.Count Nodes That Are Great Enough/README.md @@ -74,9 +74,7 @@ ## 解法 - - -**方法一:DFS + 大根堆** +### 方法一:DFS + 大根堆 我们可以使用 DFS 后序遍历整棵树,对于每个节点,我们维护一个大根堆,堆中存储该节点的所有子树中最小的 k 个节点的值,如果当前节点的值大于堆顶元素,那么该节点就是一个「足够大」的节点,我们将答案加一。 @@ -84,10 +82,6 @@ -### **Python3** - - - ```python # Definition for a binary tree node. # class TreeNode: @@ -119,10 +113,6 @@ class Solution: return ans ``` -### **Java** - - - ```java /** * Definition for a binary tree node. @@ -173,8 +163,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -219,8 +207,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -270,10 +256,6 @@ func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2792.Count Nodes That Are Great Enough/README_EN.md b/solution/2700-2799/2792.Count Nodes That Are Great Enough/README_EN.md index 257ae7bb6af21..6431039b9ceca 100644 --- a/solution/2700-2799/2792.Count Nodes That Are Great Enough/README_EN.md +++ b/solution/2700-2799/2792.Count Nodes That Are Great Enough/README_EN.md @@ -67,9 +67,9 @@ See the picture below for a better understanding. ## Solutions - +### Solution 1 -### **Python3** + ```python # Definition for a binary tree node. @@ -102,8 +102,6 @@ class Solution: return ans ``` -### **Java** - ```java /** * Definition for a binary tree node. @@ -154,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for a binary tree node. @@ -200,8 +196,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for a binary tree node. @@ -251,10 +245,6 @@ func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2793.Status of Flight Tickets/README.md b/solution/2700-2799/2793.Status of Flight Tickets/README.md index 083a2813faec3..421437299e778 100644 --- a/solution/2700-2799/2793.Status of Flight Tickets/README.md +++ b/solution/2700-2799/2793.Status of Flight Tickets/README.md @@ -87,18 +87,12 @@ Passengers 表: ## 解法 - - -**方法一:Rank() 窗口函数** +### 方法一:Rank() 窗口函数 注意,如果多个人在同一时间预定了同一个航班,只要有空位,就都可以确认预定。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -120,3 +114,5 @@ ORDER BY passenger_id; ``` + + diff --git a/solution/2700-2799/2793.Status of Flight Tickets/README_EN.md b/solution/2700-2799/2793.Status of Flight Tickets/README_EN.md index 8fedce491a3ff..7a98665fa92e1 100644 --- a/solution/2700-2799/2793.Status of Flight Tickets/README_EN.md +++ b/solution/2700-2799/2793.Status of Flight Tickets/README_EN.md @@ -85,9 +85,9 @@ Passengers table: ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -110,3 +110,5 @@ ORDER BY passenger_id; ``` + + diff --git a/solution/2700-2799/2794.Create Object from Two Arrays/README.md b/solution/2700-2799/2794.Create Object from Two Arrays/README.md index 7d017e4996cf1..3afd9ca7088d3 100644 --- a/solution/2700-2799/2794.Create Object from Two Arrays/README.md +++ b/solution/2700-2799/2794.Create Object from Two Arrays/README.md @@ -50,14 +50,10 @@ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function createObject(keysArr: any[], valuesArr: any[]): Record { const ans: Record = {}; @@ -71,8 +67,6 @@ function createObject(keysArr: any[], valuesArr: any[]): Record { } ``` -### **JavaScript** - ```js /** * @param {Array} keysArr @@ -92,3 +86,5 @@ var createObject = function (keysArr, valuesArr) { ``` + + diff --git a/solution/2700-2799/2794.Create Object from Two Arrays/README_EN.md b/solution/2700-2799/2794.Create Object from Two Arrays/README_EN.md index 78d41073c651a..1dd300dbfca26 100644 --- a/solution/2700-2799/2794.Create Object from Two Arrays/README_EN.md +++ b/solution/2700-2799/2794.Create Object from Two Arrays/README_EN.md @@ -46,9 +46,9 @@ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function createObject(keysArr: any[], valuesArr: any[]): Record { @@ -63,8 +63,6 @@ function createObject(keysArr: any[], valuesArr: any[]): Record { } ``` -### **JavaScript** - ```js /** * @param {Array} keysArr @@ -84,3 +82,5 @@ var createObject = function (keysArr, valuesArr) { ``` + + diff --git a/solution/2700-2799/2795.Parallel Execution of Promises for Individual Results Retrieval/README.md b/solution/2700-2799/2795.Parallel Execution of Promises for Individual Results Retrieval/README.md index 45781b185314e..13ffbabc893fc 100644 --- a/solution/2700-2799/2795.Parallel Execution of Promises for Individual Results Retrieval/README.md +++ b/solution/2700-2799/2795.Parallel Execution of Promises for Individual Results Retrieval/README.md @@ -87,14 +87,10 @@ promise.then(res => { ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts type FulfilledObj = { status: 'fulfilled'; @@ -139,8 +135,6 @@ function promiseAllSettled(functions: Function[]): Promise { */ ``` -### **JavaScript** - ```js /** * @param {Array} functions @@ -166,3 +160,5 @@ var promiseAllSettled = function (functions) { ``` + + diff --git a/solution/2700-2799/2795.Parallel Execution of Promises for Individual Results Retrieval/README_EN.md b/solution/2700-2799/2795.Parallel Execution of Promises for Individual Results Retrieval/README_EN.md index f9e7b2dd50c89..f2876af459127 100644 --- a/solution/2700-2799/2795.Parallel Execution of Promises for Individual Results Retrieval/README_EN.md +++ b/solution/2700-2799/2795.Parallel Execution of Promises for Individual Results Retrieval/README_EN.md @@ -83,9 +83,9 @@ The returned promise resolves within 100 milliseconds. Since promise from the ar ## Solutions - +### Solution 1 -### **TypeScript** + ```ts type FulfilledObj = { @@ -131,8 +131,6 @@ function promiseAllSettled(functions: Function[]): Promise { */ ``` -### **JavaScript** - ```js /** * @param {Array} functions @@ -158,3 +156,5 @@ var promiseAllSettled = function (functions) { ``` + + diff --git a/solution/2700-2799/2796.Repeat String/README.md b/solution/2700-2799/2796.Repeat String/README.md index 337996a4bdbc2..9beddeff3add0 100644 --- a/solution/2700-2799/2796.Repeat String/README.md +++ b/solution/2700-2799/2796.Repeat String/README.md @@ -46,14 +46,10 @@ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts declare global { interface String { @@ -66,8 +62,6 @@ String.prototype.replicate = function (times: number) { }; ``` -### **JavaScript** - ```js String.prototype.replicate = function (times) { return Array(times).fill(this).join(''); @@ -75,3 +69,5 @@ String.prototype.replicate = function (times) { ``` + + diff --git a/solution/2700-2799/2796.Repeat String/README_EN.md b/solution/2700-2799/2796.Repeat String/README_EN.md index 6262e1a4d35e7..523a3fa8a657d 100644 --- a/solution/2700-2799/2796.Repeat String/README_EN.md +++ b/solution/2700-2799/2796.Repeat String/README_EN.md @@ -42,9 +42,9 @@ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts declare global { @@ -58,8 +58,6 @@ String.prototype.replicate = function (times: number) { }; ``` -### **JavaScript** - ```js String.prototype.replicate = function (times) { return Array(times).fill(this).join(''); @@ -67,3 +65,5 @@ String.prototype.replicate = function (times) { ``` + + diff --git a/solution/2700-2799/2797.Partial Function with Placeholders/README.md b/solution/2700-2799/2797.Partial Function with Placeholders/README.md index cdc42ef87bafd..56208291218fc 100644 --- a/solution/2700-2799/2797.Partial Function with Placeholders/README.md +++ b/solution/2700-2799/2797.Partial Function with Placeholders/README.md @@ -67,14 +67,10 @@ console.log(result) // -10 ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function partial(fn: Function, args: any[]): Function { return function (...restArgs) { @@ -92,8 +88,6 @@ function partial(fn: Function, args: any[]): Function { } ``` -### **JavaScript** - ```js /** * @param {Function} fn @@ -117,3 +111,5 @@ var partial = function (fn, args) { ``` + + diff --git a/solution/2700-2799/2797.Partial Function with Placeholders/README_EN.md b/solution/2700-2799/2797.Partial Function with Placeholders/README_EN.md index e669db4098324..1d06db026a949 100644 --- a/solution/2700-2799/2797.Partial Function with Placeholders/README_EN.md +++ b/solution/2700-2799/2797.Partial Function with Placeholders/README_EN.md @@ -63,9 +63,9 @@ Placeholder "_" is replaced with 5 and 20 is added at the end of args. ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function partial(fn: Function, args: any[]): Function { @@ -84,8 +84,6 @@ function partial(fn: Function, args: any[]): Function { } ``` -### **JavaScript** - ```js /** * @param {Function} fn @@ -109,3 +107,5 @@ var partial = function (fn, args) { ``` + + diff --git a/solution/2700-2799/2798.Number of Employees Who Met the Target/README.md b/solution/2700-2799/2798.Number of Employees Who Met the Target/README.md index 8a45b0d53bc04..c4fb00befb7cf 100644 --- a/solution/2700-2799/2798.Number of Employees Who Met the Target/README.md +++ b/solution/2700-2799/2798.Number of Employees Who Met the Target/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:遍历计数** +### 方法一:遍历计数 我们可以遍历数组 $hours$,对于每个员工,如果其工作时长 $x$ 大于等于 $target$,则将计数器 $ans$ 加一。 @@ -60,20 +58,12 @@ -### **Python3** - - - ```python class Solution: def numberOfEmployeesWhoMetTarget(self, hours: List[int], target: int) -> int: return sum(x >= target for x in hours) ``` -### **Java** - - - ```java class Solution { public int numberOfEmployeesWhoMetTarget(int[] hours, int target) { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +91,6 @@ public: }; ``` -### **Go** - ```go func numberOfEmployeesWhoMetTarget(hours []int, target int) (ans int) { for _, x := range hours { @@ -116,8 +102,6 @@ func numberOfEmployeesWhoMetTarget(hours []int, target int) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfEmployeesWhoMetTarget(hours: number[], target: number): number { let ans = 0; @@ -130,8 +114,6 @@ function numberOfEmployeesWhoMetTarget(hours: number[], target: number): number } ``` -### **Rust** - ```rust impl Solution { pub fn number_of_employees_who_met_target(hours: Vec, target: i32) -> i32 { @@ -146,10 +128,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2798.Number of Employees Who Met the Target/README_EN.md b/solution/2700-2799/2798.Number of Employees Who Met the Target/README_EN.md index eaecf1cc049f0..799d1b08c099b 100644 --- a/solution/2700-2799/2798.Number of Employees Who Met the Target/README_EN.md +++ b/solution/2700-2799/2798.Number of Employees Who Met the Target/README_EN.md @@ -46,9 +46,9 @@ There are 0 employees who met the target. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -56,8 +56,6 @@ class Solution: return sum(x >= target for x in hours) ``` -### **Java** - ```java class Solution { public int numberOfEmployeesWhoMetTarget(int[] hours, int target) { @@ -72,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -87,8 +83,6 @@ public: }; ``` -### **Go** - ```go func numberOfEmployeesWhoMetTarget(hours []int, target int) (ans int) { for _, x := range hours { @@ -100,8 +94,6 @@ func numberOfEmployeesWhoMetTarget(hours []int, target int) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfEmployeesWhoMetTarget(hours: number[], target: number): number { let ans = 0; @@ -114,8 +106,6 @@ function numberOfEmployeesWhoMetTarget(hours: number[], target: number): number } ``` -### **Rust** - ```rust impl Solution { pub fn number_of_employees_who_met_target(hours: Vec, target: i32) -> i32 { @@ -130,10 +120,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2799.Count Complete Subarrays in an Array/README.md b/solution/2700-2799/2799.Count Complete Subarrays in an Array/README.md index d494fb05744cf..953a742818df5 100644 --- a/solution/2700-2799/2799.Count Complete Subarrays in an Array/README.md +++ b/solution/2700-2799/2799.Count Complete Subarrays in an Array/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:哈希表 + 枚举** +### 方法一:哈希表 + 枚举 我们先用哈希表统计数组中不同元素的数目,记为 $cnt$。 @@ -57,22 +55,8 @@ 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 是数组的长度。 -**方法二:哈希表 + 双指针** - -与方法一类似,我们可以使用哈希表统计数组中不同元素的数目,记为 $cnt$。 - -接下来,我们使用双指针维护一个滑动窗口,滑动窗口的右端点下标为 $j$,左端点下标为 $i$。 - -每次固定左端点下标 $i$,然后向右移动右端点下标 $j$,当滑动窗口中的元素种类数等于 $cnt$ 时,这意味着从左端点下标 $i$ 到右端点下标 $j$ 以及右侧的所有子数组都是完全子数组,我们将答案增加 $n - j$,其中 $n$ 是数组的长度。然后我们将左端点下标 $i$ 右移一位,继续上述过程。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组的长度。 - -### **Python3** - - - ```python class Solution: def countCompleteSubarrays(self, nums: List[int]) -> int: @@ -87,28 +71,6 @@ class Solution: return ans ``` -```python -class Solution: - def countCompleteSubarrays(self, nums: List[int]) -> int: - cnt = len(set(nums)) - d = Counter() - ans, n = 0, len(nums) - i = 0 - for j, x in enumerate(nums): - d[x] += 1 - while len(d) == cnt: - ans += n - j - d[nums[i]] -= 1 - if d[nums[i]] == 0: - d.pop(nums[i]) - i += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int countCompleteSubarrays(int[] nums) { @@ -132,6 +94,121 @@ class Solution { } ``` +```cpp +class Solution { +public: + int countCompleteSubarrays(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + int cnt = s.size(); + int ans = 0, n = nums.size(); + for (int i = 0; i < n; ++i) { + s.clear(); + for (int j = i; j < n; ++j) { + s.insert(nums[j]); + if (s.size() == cnt) { + ++ans; + } + } + } + return ans; + } +}; +``` + +```go +func countCompleteSubarrays(nums []int) (ans int) { + s := map[int]bool{} + for _, x := range nums { + s[x] = true + } + cnt := len(s) + for i := range nums { + s = map[int]bool{} + for _, x := range nums[i:] { + s[x] = true + if len(s) == cnt { + ans++ + } + } + } + return +} +``` + +```ts +function countCompleteSubarrays(nums: number[]): number { + const s: Set = new Set(nums); + const cnt = s.size; + const n = nums.length; + let ans = 0; + for (let i = 0; i < n; ++i) { + s.clear(); + for (let j = i; j < n; ++j) { + s.add(nums[j]); + if (s.size === cnt) { + ++ans; + } + } + } + return ans; +} +``` + +```rust +use std::collections::HashSet; +impl Solution { + pub fn count_complete_subarrays(nums: Vec) -> i32 { + let mut set: HashSet<&i32> = nums.iter().collect(); + let n = nums.len(); + let m = set.len(); + let mut ans = 0; + for i in 0..n { + set.clear(); + for j in i..n { + set.insert(&nums[j]); + if set.len() == m { + ans += n - j; + break; + } + } + } + ans as i32 + } +} +``` + + + +### 方法二:哈希表 + 双指针 + +与方法一类似,我们可以使用哈希表统计数组中不同元素的数目,记为 $cnt$。 + +接下来,我们使用双指针维护一个滑动窗口,滑动窗口的右端点下标为 $j$,左端点下标为 $i$。 + +每次固定左端点下标 $i$,然后向右移动右端点下标 $j$,当滑动窗口中的元素种类数等于 $cnt$ 时,这意味着从左端点下标 $i$ 到右端点下标 $j$ 以及右侧的所有子数组都是完全子数组,我们将答案增加 $n - j$,其中 $n$ 是数组的长度。然后我们将左端点下标 $i$ 右移一位,继续上述过程。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组的长度。 + + + +```python +class Solution: + def countCompleteSubarrays(self, nums: List[int]) -> int: + cnt = len(set(nums)) + d = Counter() + ans, n = 0, len(nums) + i = 0 + for j, x in enumerate(nums): + d[x] += 1 + while len(d) == cnt: + ans += n - j + d[nums[i]] -= 1 + if d[nums[i]] == 0: + d.pop(nums[i]) + i += 1 + return ans +``` + ```java class Solution { public int countCompleteSubarrays(int[] nums) { @@ -157,29 +234,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int countCompleteSubarrays(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - int cnt = s.size(); - int ans = 0, n = nums.size(); - for (int i = 0; i < n; ++i) { - s.clear(); - for (int j = i; j < n; ++j) { - s.insert(nums[j]); - if (s.size() == cnt) { - ++ans; - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -206,28 +260,6 @@ public: }; ``` -### **Go** - -```go -func countCompleteSubarrays(nums []int) (ans int) { - s := map[int]bool{} - for _, x := range nums { - s[x] = true - } - cnt := len(s) - for i := range nums { - s = map[int]bool{} - for _, x := range nums[i:] { - s[x] = true - if len(s) == cnt { - ans++ - } - } - } - return -} -``` - ```go func countCompleteSubarrays(nums []int) (ans int) { d := map[int]int{} @@ -252,27 +284,6 @@ func countCompleteSubarrays(nums []int) (ans int) { } ``` -### **TypeScript** - -```ts -function countCompleteSubarrays(nums: number[]): number { - const s: Set = new Set(nums); - const cnt = s.size; - const n = nums.length; - let ans = 0; - for (let i = 0; i < n; ++i) { - s.clear(); - for (let j = i; j < n; ++j) { - s.add(nums[j]); - if (s.size === cnt) { - ++ans; - } - } - } - return ans; -} -``` - ```ts function countCompleteSubarrays(nums: number[]): number { const d: Map = new Map(); @@ -299,31 +310,6 @@ function countCompleteSubarrays(nums: number[]): number { } ``` -### **Rust** - -```rust -use std::collections::HashSet; -impl Solution { - pub fn count_complete_subarrays(nums: Vec) -> i32 { - let mut set: HashSet<&i32> = nums.iter().collect(); - let n = nums.len(); - let m = set.len(); - let mut ans = 0; - for i in 0..n { - set.clear(); - for j in i..n { - set.insert(&nums[j]); - if set.len() == m { - ans += n - j; - break; - } - } - } - ans as i32 - } -} -``` - ```rust use std::collections::HashMap; use std::collections::HashSet; @@ -351,10 +337,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2700-2799/2799.Count Complete Subarrays in an Array/README_EN.md b/solution/2700-2799/2799.Count Complete Subarrays in an Array/README_EN.md index 4092b51326657..785981b6d1b3a 100644 --- a/solution/2700-2799/2799.Count Complete Subarrays in an Array/README_EN.md +++ b/solution/2700-2799/2799.Count Complete Subarrays in an Array/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -61,26 +61,6 @@ class Solution: return ans ``` -```python -class Solution: - def countCompleteSubarrays(self, nums: List[int]) -> int: - cnt = len(set(nums)) - d = Counter() - ans, n = 0, len(nums) - i = 0 - for j, x in enumerate(nums): - d[x] += 1 - while len(d) == cnt: - ans += n - j - d[nums[i]] -= 1 - if d[nums[i]] == 0: - d.pop(nums[i]) - i += 1 - return ans -``` - -### **Java** - ```java class Solution { public int countCompleteSubarrays(int[] nums) { @@ -104,6 +84,113 @@ class Solution { } ``` +```cpp +class Solution { +public: + int countCompleteSubarrays(vector& nums) { + unordered_set s(nums.begin(), nums.end()); + int cnt = s.size(); + int ans = 0, n = nums.size(); + for (int i = 0; i < n; ++i) { + s.clear(); + for (int j = i; j < n; ++j) { + s.insert(nums[j]); + if (s.size() == cnt) { + ++ans; + } + } + } + return ans; + } +}; +``` + +```go +func countCompleteSubarrays(nums []int) (ans int) { + s := map[int]bool{} + for _, x := range nums { + s[x] = true + } + cnt := len(s) + for i := range nums { + s = map[int]bool{} + for _, x := range nums[i:] { + s[x] = true + if len(s) == cnt { + ans++ + } + } + } + return +} +``` + +```ts +function countCompleteSubarrays(nums: number[]): number { + const s: Set = new Set(nums); + const cnt = s.size; + const n = nums.length; + let ans = 0; + for (let i = 0; i < n; ++i) { + s.clear(); + for (let j = i; j < n; ++j) { + s.add(nums[j]); + if (s.size === cnt) { + ++ans; + } + } + } + return ans; +} +``` + +```rust +use std::collections::HashSet; +impl Solution { + pub fn count_complete_subarrays(nums: Vec) -> i32 { + let mut set: HashSet<&i32> = nums.iter().collect(); + let n = nums.len(); + let m = set.len(); + let mut ans = 0; + for i in 0..n { + set.clear(); + for j in i..n { + set.insert(&nums[j]); + if set.len() == m { + ans += n - j; + break; + } + } + } + ans as i32 + } +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def countCompleteSubarrays(self, nums: List[int]) -> int: + cnt = len(set(nums)) + d = Counter() + ans, n = 0, len(nums) + i = 0 + for j, x in enumerate(nums): + d[x] += 1 + while len(d) == cnt: + ans += n - j + d[nums[i]] -= 1 + if d[nums[i]] == 0: + d.pop(nums[i]) + i += 1 + return ans +``` + ```java class Solution { public int countCompleteSubarrays(int[] nums) { @@ -129,29 +216,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int countCompleteSubarrays(vector& nums) { - unordered_set s(nums.begin(), nums.end()); - int cnt = s.size(); - int ans = 0, n = nums.size(); - for (int i = 0; i < n; ++i) { - s.clear(); - for (int j = i; j < n; ++j) { - s.insert(nums[j]); - if (s.size() == cnt) { - ++ans; - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -178,28 +242,6 @@ public: }; ``` -### **Go** - -```go -func countCompleteSubarrays(nums []int) (ans int) { - s := map[int]bool{} - for _, x := range nums { - s[x] = true - } - cnt := len(s) - for i := range nums { - s = map[int]bool{} - for _, x := range nums[i:] { - s[x] = true - if len(s) == cnt { - ans++ - } - } - } - return -} -``` - ```go func countCompleteSubarrays(nums []int) (ans int) { d := map[int]int{} @@ -224,27 +266,6 @@ func countCompleteSubarrays(nums []int) (ans int) { } ``` -### **TypeScript** - -```ts -function countCompleteSubarrays(nums: number[]): number { - const s: Set = new Set(nums); - const cnt = s.size; - const n = nums.length; - let ans = 0; - for (let i = 0; i < n; ++i) { - s.clear(); - for (let j = i; j < n; ++j) { - s.add(nums[j]); - if (s.size === cnt) { - ++ans; - } - } - } - return ans; -} -``` - ```ts function countCompleteSubarrays(nums: number[]): number { const d: Map = new Map(); @@ -271,31 +292,6 @@ function countCompleteSubarrays(nums: number[]): number { } ``` -### **Rust** - -```rust -use std::collections::HashSet; -impl Solution { - pub fn count_complete_subarrays(nums: Vec) -> i32 { - let mut set: HashSet<&i32> = nums.iter().collect(); - let n = nums.len(); - let m = set.len(); - let mut ans = 0; - for i in 0..n { - set.clear(); - for j in i..n { - set.insert(&nums[j]); - if set.len() == m { - ans += n - j; - break; - } - } - } - ans as i32 - } -} -``` - ```rust use std::collections::HashMap; use std::collections::HashSet; @@ -323,10 +319,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2800.Shortest String That Contains Three Strings/README.md b/solution/2800-2899/2800.Shortest String That Contains Three Strings/README.md index 14692ac77af49..cd61a73ad94ca 100644 --- a/solution/2800-2899/2800.Shortest String That Contains Three Strings/README.md +++ b/solution/2800-2899/2800.Shortest String That Contains Three Strings/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们枚举三个字符串的所有排列,然后对于每个排列,对三个字符串进行合并,找到最短的且字典序最小的字符串。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def minimumString(self, a: str, b: str, c: str) -> str: @@ -81,10 +75,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public String minimumString(String a, String b, String c) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +145,6 @@ public: }; ``` -### **Go** - ```go func minimumString(a string, b string, c string) string { f := func(s, t string) string { @@ -189,8 +175,6 @@ func minimumString(a string, b string, c string) string { } ``` -### **TypeScript** - ```ts function minimumString(a: string, b: string, c: string): string { const f = (s: string, t: string): string => { @@ -229,8 +213,6 @@ function minimumString(a: string, b: string, c: string): string { } ``` -### **Rust** - ```rust impl Solution { fn f(s1: String, s2: String) -> String { @@ -272,10 +254,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2800.Shortest String That Contains Three Strings/README_EN.md b/solution/2800-2899/2800.Shortest String That Contains Three Strings/README_EN.md index 67384e3428ddf..94770c30525ea 100644 --- a/solution/2800-2899/2800.Shortest String That Contains Three Strings/README_EN.md +++ b/solution/2800-2899/2800.Shortest String That Contains Three Strings/README_EN.md @@ -43,7 +43,7 @@ Given three strings a, b, and c, your tas ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We enumerate all permutations of the three strings, and for each permutation, we merge the three strings to find the shortest string with the smallest lexicographical order. @@ -51,8 +51,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ i -### **Python3** - ```python class Solution: def minimumString(self, a: str, b: str, c: str) -> str: @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public String minimumString(String a, String b, String c) { @@ -112,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +143,6 @@ public: }; ``` -### **Go** - ```go func minimumString(a string, b string, c string) string { f := func(s, t string) string { @@ -181,8 +173,6 @@ func minimumString(a string, b string, c string) string { } ``` -### **TypeScript** - ```ts function minimumString(a: string, b: string, c: string): string { const f = (s: string, t: string): string => { @@ -221,8 +211,6 @@ function minimumString(a: string, b: string, c: string): string { } ``` -### **Rust** - ```rust impl Solution { fn f(s1: String, s2: String) -> String { @@ -264,10 +252,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2801.Count Stepping Numbers in Range/README.md b/solution/2800-2899/2801.Count Stepping Numbers in Range/README.md index 0e4350cdff683..06ac184d09409 100644 --- a/solution/2800-2899/2801.Count Stepping Numbers in Range/README.md +++ b/solution/2800-2899/2801.Count Stepping Numbers in Range/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:数位 DP** +### 方法一:数位 DP 我们注意到,题目求的是区间 $[low, high]$ 内的步进数的个数,对于这种区间 $[l,..r]$ 的问题,我们通常可以考虑转化为求 $[1, r]$ 和 $[1, l-1]$ 的答案,然后相减即可。另外,题目中只涉及到不同数位之间的关系,而不涉及具体的数值,因此我们可以考虑使用数位 DP 来解决。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def countSteppingNumbers(self, low: str, high: str) -> int: @@ -101,10 +95,6 @@ class Solution: return (a - b) % mod ``` -### **Java** - - - ```java import java.math.BigInteger; @@ -148,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -200,8 +188,6 @@ public: }; ``` -### **Go** - ```go func countSteppingNumbers(low string, high string) int { const mod = 1e9 + 7 @@ -269,8 +255,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function countSteppingNumbers(low: string, high: string): number { const mod = 1e9 + 7; @@ -311,10 +295,6 @@ function countSteppingNumbers(low: string, high: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2801.Count Stepping Numbers in Range/README_EN.md b/solution/2800-2899/2801.Count Stepping Numbers in Range/README_EN.md index 4dcf0745a9489..0d8530712f079 100644 --- a/solution/2800-2899/2801.Count Stepping Numbers in Range/README_EN.md +++ b/solution/2800-2899/2801.Count Stepping Numbers in Range/README_EN.md @@ -41,7 +41,7 @@ ## Solutions -**Solution 1: Digit DP** +### Solution 1: Digit DP We notice that the problem is asking for the number of stepping numbers in the interval $[low, high]$. For such an interval $[l,..r]$ problem, we can usually consider transforming it into finding the answers for $[1, r]$ and $[1, l-1]$, and then subtracting the latter from the former. Moreover, the problem only involves the relationship between different digits, not the specific values, so we can consider using Digit DP to solve it. @@ -68,8 +68,6 @@ Similar problems: -### **Python3** - ```python class Solution: def countSteppingNumbers(self, low: str, high: str) -> int: @@ -95,8 +93,6 @@ class Solution: return (a - b) % mod ``` -### **Java** - ```java import java.math.BigInteger; @@ -140,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -192,8 +186,6 @@ public: }; ``` -### **Go** - ```go func countSteppingNumbers(low string, high string) int { const mod = 1e9 + 7 @@ -261,8 +253,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function countSteppingNumbers(low: string, high: string): number { const mod = 1e9 + 7; @@ -303,10 +293,6 @@ function countSteppingNumbers(low: string, high: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2802.Find The K-th Lucky Number/README.md b/solution/2800-2899/2802.Find The K-th Lucky Number/README.md index 5c4cd39995813..603c6372ebdf8 100644 --- a/solution/2800-2899/2802.Find The K-th Lucky Number/README.md +++ b/solution/2800-2899/2802.Find The K-th Lucky Number/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:数学** +### 方法一:数学 根据题目描述,一个幸运数只包含数字 $4$ 和 $7$,因此 $n$ 位幸运数的个数为 $2^n$。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def kthLuckyNumber(self, k: int) -> str: @@ -82,10 +76,6 @@ class Solution: return "".join(ans) ``` -### **Java** - - - ```java class Solution { public String kthLuckyNumber(int k) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +121,6 @@ public: }; ``` -### **Go** - ```go func kthLuckyNumber(k int) string { n := 1 @@ -156,8 +142,6 @@ func kthLuckyNumber(k int) string { } ``` -### **TypeScript** - ```ts function kthLuckyNumber(k: number): string { let n = 1; @@ -178,10 +162,6 @@ function kthLuckyNumber(k: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2802.Find The K-th Lucky Number/README_EN.md b/solution/2800-2899/2802.Find The K-th Lucky Number/README_EN.md index 7d1814baab7c3..faed65f86f381 100644 --- a/solution/2800-2899/2802.Find The K-th Lucky Number/README_EN.md +++ b/solution/2800-2899/2802.Find The K-th Lucky Number/README_EN.md @@ -42,7 +42,7 @@ ## Solutions -**Solution 1: Mathematics** +### Solution 1: Mathematics According to the problem description, a lucky number only contains the digits $4$ and $7$, so the number of $n$-digit lucky numbers is $2^n$. @@ -54,8 +54,6 @@ The time complexity is $O(\log k)$, and the space complexity is $O(\log k)$. -### **Python3** - ```python class Solution: def kthLuckyNumber(self, k: int) -> str: @@ -74,8 +72,6 @@ class Solution: return "".join(ans) ``` -### **Java** - ```java class Solution { public String kthLuckyNumber(int k) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +117,6 @@ public: }; ``` -### **Go** - ```go func kthLuckyNumber(k int) string { n := 1 @@ -146,8 +138,6 @@ func kthLuckyNumber(k int) string { } ``` -### **TypeScript** - ```ts function kthLuckyNumber(k: number): string { let n = 1; @@ -168,10 +158,6 @@ function kthLuckyNumber(k: number): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2803.Factorial Generator/README.md b/solution/2800-2899/2803.Factorial Generator/README.md index e12cfa37d8cbf..3e2812207ea39 100644 --- a/solution/2800-2899/2803.Factorial Generator/README.md +++ b/solution/2800-2899/2803.Factorial Generator/README.md @@ -59,14 +59,10 @@ gen.next().value // 1 ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function* factorial(n: number): Generator { if (n === 0) { @@ -87,3 +83,5 @@ function* factorial(n: number): Generator { ``` + + diff --git a/solution/2800-2899/2803.Factorial Generator/README_EN.md b/solution/2800-2899/2803.Factorial Generator/README_EN.md index af14e586fc465..930de221e9062 100644 --- a/solution/2800-2899/2803.Factorial Generator/README_EN.md +++ b/solution/2800-2899/2803.Factorial Generator/README_EN.md @@ -55,9 +55,9 @@ gen.next().value // 1 ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function* factorial(n: number): Generator { @@ -79,3 +79,5 @@ function* factorial(n: number): Generator { ``` + + diff --git a/solution/2800-2899/2804.Array Prototype ForEach/README.md b/solution/2800-2899/2804.Array Prototype ForEach/README.md index 290f30825cdf1..bfb81c16b3fcd 100644 --- a/solution/2800-2899/2804.Array Prototype ForEach/README.md +++ b/solution/2800-2899/2804.Array Prototype ForEach/README.md @@ -75,14 +75,10 @@ context = {"context": 5} ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts Array.prototype.forEach = function (callback: Function, context: any): void { for (let i = 0; i < this.length; ++i) { @@ -102,3 +98,5 @@ Array.prototype.forEach = function (callback: Function, context: any): void { ``` + + diff --git a/solution/2800-2899/2804.Array Prototype ForEach/README_EN.md b/solution/2800-2899/2804.Array Prototype ForEach/README_EN.md index 1db7003a0a130..68975c9053c73 100644 --- a/solution/2800-2899/2804.Array Prototype ForEach/README_EN.md +++ b/solution/2800-2899/2804.Array Prototype ForEach/README_EN.md @@ -71,9 +71,9 @@ context = {"context": 5} ## Solutions - +### Solution 1 -### **TypeScript** + ```ts Array.prototype.forEach = function (callback: Function, context: any): void { @@ -94,3 +94,5 @@ Array.prototype.forEach = function (callback: Function, context: any): void { ``` + + diff --git a/solution/2800-2899/2805.Custom Interval/README.md b/solution/2800-2899/2805.Custom Interval/README.md index d72e09c713f7e..efbad146de731 100644 --- a/solution/2800-2899/2805.Custom Interval/README.md +++ b/solution/2800-2899/2805.Custom Interval/README.md @@ -71,14 +71,10 @@ setTimeout(() => { ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts const intervalMap = new Map(); @@ -109,3 +105,5 @@ function customClearInterval(id: number) { ``` + + diff --git a/solution/2800-2899/2805.Custom Interval/README_EN.md b/solution/2800-2899/2805.Custom Interval/README_EN.md index 3eac0edfc0411..3062c06b2f517 100644 --- a/solution/2800-2899/2805.Custom Interval/README_EN.md +++ b/solution/2800-2899/2805.Custom Interval/README_EN.md @@ -67,9 +67,9 @@ setTimeout(() => { ## Solutions - +### Solution 1 -### **TypeScript** + ```ts const intervalMap = new Map(); @@ -101,3 +101,5 @@ function customClearInterval(id: number) { ``` + + diff --git a/solution/2800-2899/2806.Account Balance After Rounded Purchase/README.md b/solution/2800-2899/2806.Account Balance After Rounded Purchase/README.md index a4d864abf5645..ef8fafed64da8 100644 --- a/solution/2800-2899/2806.Account Balance After Rounded Purchase/README.md +++ b/solution/2800-2899/2806.Account Balance After Rounded Purchase/README.md @@ -45,9 +45,7 @@ ## 解法 - - -**方法一:枚举 + 模拟** +### 方法一:枚举 + 模拟 我们在 $[0, 100]$ 的范围内枚举所有的 $10$ 的倍数,然后找到与 `purchaseAmount` 最接近的那个数,记为 $x$,那么答案就是 $100 - x$。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int: @@ -70,10 +64,6 @@ class Solution: return 100 - x ``` -### **Java** - - - ```java class Solution { public int accountBalanceAfterPurchase(int purchaseAmount) { @@ -90,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +97,6 @@ public: }; ``` -### **Go** - ```go func accountBalanceAfterPurchase(purchaseAmount int) int { diff, x := 100, 0 @@ -132,8 +118,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function accountBalanceAfterPurchase(purchaseAmount: number): number { let [diff, x] = [100, 0]; @@ -148,10 +132,6 @@ function accountBalanceAfterPurchase(purchaseAmount: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2806.Account Balance After Rounded Purchase/README_EN.md b/solution/2800-2899/2806.Account Balance After Rounded Purchase/README_EN.md index e5a0172e00ed7..7a37c3638a061 100644 --- a/solution/2800-2899/2806.Account Balance After Rounded Purchase/README_EN.md +++ b/solution/2800-2899/2806.Account Balance After Rounded Purchase/README_EN.md @@ -43,7 +43,7 @@ Hence, your account balance becomes 100 - 20 = 80. ## Solutions -**Solution 1: Enumeration + Simulation** +### Solution 1: Enumeration + Simulation We enumerate all multiples of 10 within the range $[0, 100]$, and find the one that is closest to `purchaseAmount`, denoted as $x$. The answer is $100 - x$. @@ -51,8 +51,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int: @@ -64,8 +62,6 @@ class Solution: return 100 - x ``` -### **Java** - ```java class Solution { public int accountBalanceAfterPurchase(int purchaseAmount) { @@ -82,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +95,6 @@ public: }; ``` -### **Go** - ```go func accountBalanceAfterPurchase(purchaseAmount int) int { diff, x := 100, 0 @@ -124,8 +116,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function accountBalanceAfterPurchase(purchaseAmount: number): number { let [diff, x] = [100, 0]; @@ -140,10 +130,6 @@ function accountBalanceAfterPurchase(purchaseAmount: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2807.Insert Greatest Common Divisors in Linked List/README.md b/solution/2800-2899/2807.Insert Greatest Common Divisors in Linked List/README.md index 03c21363c7bd8..f79df4bdf6e21 100644 --- a/solution/2800-2899/2807.Insert Greatest Common Divisors in Linked List/README.md +++ b/solution/2800-2899/2807.Insert Greatest Common Divisors in Linked List/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们用两个指针 $pre$ 和 $cur$ 分别指向当前遍历到的结点和下一个结点,那么我们只需要在 $pre$ 和 $cur$ 之间插入一个新的结点即可。因此,每次计算出 $pre$ 和 $cur$ 的最大公约数 $x$,然后在 $pre$ 和 $cur$ 之间插入一个值为 $x$ 的新结点,然后更新 $pre = cur$,并且 $cur = cur.next$,继续遍历链表,直到 $cur$ 为空。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -82,10 +76,6 @@ class Solution: return head ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -116,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -170,8 +156,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -202,10 +186,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2807.Insert Greatest Common Divisors in Linked List/README_EN.md b/solution/2800-2899/2807.Insert Greatest Common Divisors in Linked List/README_EN.md index 514c458e72816..cc8a70a0a9c8c 100644 --- a/solution/2800-2899/2807.Insert Greatest Common Divisors in Linked List/README_EN.md +++ b/solution/2800-2899/2807.Insert Greatest Common Divisors in Linked List/README_EN.md @@ -44,7 +44,7 @@ There are no pairs of adjacent nodes, so we return the initial linked list. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We use two pointers $pre$ and $cur$ to point to the current node and the next node respectively. We only need to insert a new node between $pre$ and $cur$. Therefore, each time we calculate the greatest common divisor $x$ of $pre$ and $cur$, we insert a new node with value $x$ between $pre$ and $cur$. Then we update $pre = cur$ and $cur = cur.next$, and continue to traverse the linked list until $cur$ is null. @@ -52,8 +52,6 @@ The time complexity is $O(n \times \log M)$, where $n$ is the length of the link -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -72,8 +70,6 @@ class Solution: return head ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -131,8 +125,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -158,8 +150,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -190,10 +180,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/README.md b/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/README.md index e078ef2323f3f..a706175c37b5c 100644 --- a/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/README.md +++ b/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们假设最终所有元素都变成了 $x$,那么 $x$ 一定是数组中的某个元素。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def minimumSeconds(self, nums: List[int]) -> int: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumSeconds(List nums) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +130,6 @@ public: }; ``` -### **Go** - ```go func minimumSeconds(nums []int) int { d := map[int][]int{} @@ -164,8 +150,6 @@ func minimumSeconds(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumSeconds(nums: number[]): number { const d: Map = new Map(); @@ -189,10 +173,6 @@ function minimumSeconds(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/README_EN.md b/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/README_EN.md index 1fa7261f60a17..137e1eaa9d17b 100644 --- a/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/README_EN.md +++ b/solution/2800-2899/2808.Minimum Seconds to Equalize a Circular Array/README_EN.md @@ -56,7 +56,7 @@ It can be proven that 2 seconds is the minimum amount of seconds needed for equa ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We assume that all elements eventually become $x$, and $x$ must be an element in the array. @@ -68,8 +68,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is -### **Python3** - ```python class Solution: def minimumSeconds(self, nums: List[int]) -> int: @@ -86,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumSeconds(List nums) { @@ -110,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +129,6 @@ public: }; ``` -### **Go** - ```go func minimumSeconds(nums []int) int { d := map[int][]int{} @@ -157,8 +149,6 @@ func minimumSeconds(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumSeconds(nums: number[]): number { const d: Map = new Map(); @@ -182,10 +172,6 @@ function minimumSeconds(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/README.md b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/README.md index 0a79a545af863..1447a20e84b2a 100644 --- a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/README.md +++ b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:排序 + 动态规划** +### 方法一:排序 + 动态规划 我们注意到,如果我们多次操作同一个数,那么只有最后一次操作是有意义的,其余的对该数的操作,只会使得其它数字增大。因此,我们最多对每个数操作一次,也即是说,操作次数在 $[0,..n]$ 之间。 @@ -85,10 +83,6 @@ $$ -### **Python3** - - - ```python class Solution: def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int: @@ -107,26 +101,6 @@ class Solution: return -1 ``` -```python -class Solution: - def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int: - n = len(nums1) - f = [0] * (n + 1) - for a, b in sorted(zip(nums1, nums2), key=lambda z: z[1]): - for j in range(n, 0, -1): - f[j] = max(f[j], f[j - 1] + a + b * j) - s1 = sum(nums1) - s2 = sum(nums2) - for j in range(n + 1): - if s1 + s2 * j - f[j] <= x: - return j - return -1 -``` - -### **Java** - - - ```java class Solution { public int minimumTime(List nums1, List nums2, int x) { @@ -164,42 +138,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumTime(List nums1, List nums2, int x) { - int n = nums1.size(); - int[] f = new int[n + 1]; - int[][] nums = new int[n][0]; - for (int i = 0; i < n; ++i) { - nums[i] = new int[] {nums1.get(i), nums2.get(i)}; - } - Arrays.sort(nums, Comparator.comparingInt(a -> a[1])); - for (int[] e : nums) { - int a = e[0], b = e[1]; - for (int j = n; j > 0; --j) { - f[j] = Math.max(f[j], f[j - 1] + a + b * j); - } - } - int s1 = 0, s2 = 0; - for (int v : nums1) { - s1 += v; - } - for (int v : nums2) { - s2 += v; - } - - for (int j = 0; j <= n; ++j) { - if (s1 + s2 * j - f[j] <= x) { - return j; - } - } - return -1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -233,37 +171,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minimumTime(vector& nums1, vector& nums2, int x) { - int n = nums1.size(); - vector> nums; - for (int i = 0; i < n; ++i) { - nums.emplace_back(nums2[i], nums1[i]); - } - sort(nums.begin(), nums.end()); - int f[n + 1]; - memset(f, 0, sizeof(f)); - for (auto [b, a] : nums) { - for (int j = n; j; --j) { - f[j] = max(f[j], f[j - 1] + a + b * j); - } - } - int s1 = accumulate(nums1.begin(), nums1.end(), 0); - int s2 = accumulate(nums2.begin(), nums2.end(), 0); - for (int j = 0; j <= n; ++j) { - if (s1 + s2 * j - f[j] <= x) { - return j; - } - } - return -1; - } -}; -``` - -### **Go** - ```go func minimumTime(nums1 []int, nums2 []int, x int) int { n := len(nums1) @@ -298,36 +205,6 @@ func minimumTime(nums1 []int, nums2 []int, x int) int { } ``` -```go -func minimumTime(nums1 []int, nums2 []int, x int) int { - n := len(nums1) - f := make([]int, n+1) - type pair struct{ a, b int } - nums := make([]pair, n) - var s1, s2 int - for i := range nums { - s1 += nums1[i] - s2 += nums2[i] - nums[i] = pair{nums1[i], nums2[i]} - } - sort.Slice(nums, func(i, j int) bool { return nums[i].b < nums[j].b }) - for _, e := range nums { - a, b := e.a, e.b - for j := n; j > 0; j-- { - f[j] = max(f[j], f[j-1]+a+b*j) - } - } - for j := 0; j <= n; j++ { - if s1+s2*j-f[j] <= x { - return j - } - } - return -1 -} -``` - -### **TypeScript** - ```ts function minimumTime(nums1: number[], nums2: number[], x: number): number { const n = nums1.length; @@ -359,6 +236,119 @@ function minimumTime(nums1: number[], nums2: number[], x: number): number { } ``` + + +### 方法二 + + + +```python +class Solution: + def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int: + n = len(nums1) + f = [0] * (n + 1) + for a, b in sorted(zip(nums1, nums2), key=lambda z: z[1]): + for j in range(n, 0, -1): + f[j] = max(f[j], f[j - 1] + a + b * j) + s1 = sum(nums1) + s2 = sum(nums2) + for j in range(n + 1): + if s1 + s2 * j - f[j] <= x: + return j + return -1 +``` + +```java +class Solution { + public int minimumTime(List nums1, List nums2, int x) { + int n = nums1.size(); + int[] f = new int[n + 1]; + int[][] nums = new int[n][0]; + for (int i = 0; i < n; ++i) { + nums[i] = new int[] {nums1.get(i), nums2.get(i)}; + } + Arrays.sort(nums, Comparator.comparingInt(a -> a[1])); + for (int[] e : nums) { + int a = e[0], b = e[1]; + for (int j = n; j > 0; --j) { + f[j] = Math.max(f[j], f[j - 1] + a + b * j); + } + } + int s1 = 0, s2 = 0; + for (int v : nums1) { + s1 += v; + } + for (int v : nums2) { + s2 += v; + } + + for (int j = 0; j <= n; ++j) { + if (s1 + s2 * j - f[j] <= x) { + return j; + } + } + return -1; + } +} +``` + +```cpp +class Solution { +public: + int minimumTime(vector& nums1, vector& nums2, int x) { + int n = nums1.size(); + vector> nums; + for (int i = 0; i < n; ++i) { + nums.emplace_back(nums2[i], nums1[i]); + } + sort(nums.begin(), nums.end()); + int f[n + 1]; + memset(f, 0, sizeof(f)); + for (auto [b, a] : nums) { + for (int j = n; j; --j) { + f[j] = max(f[j], f[j - 1] + a + b * j); + } + } + int s1 = accumulate(nums1.begin(), nums1.end(), 0); + int s2 = accumulate(nums2.begin(), nums2.end(), 0); + for (int j = 0; j <= n; ++j) { + if (s1 + s2 * j - f[j] <= x) { + return j; + } + } + return -1; + } +}; +``` + +```go +func minimumTime(nums1 []int, nums2 []int, x int) int { + n := len(nums1) + f := make([]int, n+1) + type pair struct{ a, b int } + nums := make([]pair, n) + var s1, s2 int + for i := range nums { + s1 += nums1[i] + s2 += nums2[i] + nums[i] = pair{nums1[i], nums2[i]} + } + sort.Slice(nums, func(i, j int) bool { return nums[i].b < nums[j].b }) + for _, e := range nums { + a, b := e.a, e.b + for j := n; j > 0; j-- { + f[j] = max(f[j], f[j-1]+a+b*j) + } + } + for j := 0; j <= n; j++ { + if s1+s2*j-f[j] <= x { + return j + } + } + return -1 +} +``` + ```ts function minimumTime(nums1: number[], nums2: number[], x: number): number { const n = nums1.length; @@ -384,10 +374,6 @@ function minimumTime(nums1: number[], nums2: number[], x: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/README_EN.md b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/README_EN.md index 495945b8cfb36..06596b1bbeb78 100644 --- a/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/README_EN.md +++ b/solution/2800-2899/2809.Minimum Time to Make Array Sum At Most x/README_EN.md @@ -49,7 +49,7 @@ Now sum of nums1 = 4. It can be shown that these operations are optimal, so we r ## Solutions -**Solution 1: Sorting + Dynamic Programming** +### Solution 1: Sorting + Dynamic Programming We notice that if we operate on the same number multiple times, only the last operation is meaningful, and the rest of the operations on that number will only increase the other numbers. Therefore, we operate on each number at most once, that is to say, the number of operations is within $[0,..n]$. @@ -80,8 +80,6 @@ We notice that the state $f[i][j]$ is only related to $f[i-1][j]$ and $f[i-1][j- -### **Python3** - ```python class Solution: def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int: @@ -100,24 +98,6 @@ class Solution: return -1 ``` -```python -class Solution: - def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int: - n = len(nums1) - f = [0] * (n + 1) - for a, b in sorted(zip(nums1, nums2), key=lambda z: z[1]): - for j in range(n, 0, -1): - f[j] = max(f[j], f[j - 1] + a + b * j) - s1 = sum(nums1) - s2 = sum(nums2) - for j in range(n + 1): - if s1 + s2 * j - f[j] <= x: - return j - return -1 -``` - -### **Java** - ```java class Solution { public int minimumTime(List nums1, List nums2, int x) { @@ -155,42 +135,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumTime(List nums1, List nums2, int x) { - int n = nums1.size(); - int[] f = new int[n + 1]; - int[][] nums = new int[n][0]; - for (int i = 0; i < n; ++i) { - nums[i] = new int[] {nums1.get(i), nums2.get(i)}; - } - Arrays.sort(nums, Comparator.comparingInt(a -> a[1])); - for (int[] e : nums) { - int a = e[0], b = e[1]; - for (int j = n; j > 0; --j) { - f[j] = Math.max(f[j], f[j - 1] + a + b * j); - } - } - int s1 = 0, s2 = 0; - for (int v : nums1) { - s1 += v; - } - for (int v : nums2) { - s2 += v; - } - - for (int j = 0; j <= n; ++j) { - if (s1 + s2 * j - f[j] <= x) { - return j; - } - } - return -1; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -224,37 +168,6 @@ public: }; ``` -```cpp -class Solution { -public: - int minimumTime(vector& nums1, vector& nums2, int x) { - int n = nums1.size(); - vector> nums; - for (int i = 0; i < n; ++i) { - nums.emplace_back(nums2[i], nums1[i]); - } - sort(nums.begin(), nums.end()); - int f[n + 1]; - memset(f, 0, sizeof(f)); - for (auto [b, a] : nums) { - for (int j = n; j; --j) { - f[j] = max(f[j], f[j - 1] + a + b * j); - } - } - int s1 = accumulate(nums1.begin(), nums1.end(), 0); - int s2 = accumulate(nums2.begin(), nums2.end(), 0); - for (int j = 0; j <= n; ++j) { - if (s1 + s2 * j - f[j] <= x) { - return j; - } - } - return -1; - } -}; -``` - -### **Go** - ```go func minimumTime(nums1 []int, nums2 []int, x int) int { n := len(nums1) @@ -289,36 +202,6 @@ func minimumTime(nums1 []int, nums2 []int, x int) int { } ``` -```go -func minimumTime(nums1 []int, nums2 []int, x int) int { - n := len(nums1) - f := make([]int, n+1) - type pair struct{ a, b int } - nums := make([]pair, n) - var s1, s2 int - for i := range nums { - s1 += nums1[i] - s2 += nums2[i] - nums[i] = pair{nums1[i], nums2[i]} - } - sort.Slice(nums, func(i, j int) bool { return nums[i].b < nums[j].b }) - for _, e := range nums { - a, b := e.a, e.b - for j := n; j > 0; j-- { - f[j] = max(f[j], f[j-1]+a+b*j) - } - } - for j := 0; j <= n; j++ { - if s1+s2*j-f[j] <= x { - return j - } - } - return -1 -} -``` - -### **TypeScript** - ```ts function minimumTime(nums1: number[], nums2: number[], x: number): number { const n = nums1.length; @@ -350,6 +233,119 @@ function minimumTime(nums1: number[], nums2: number[], x: number): number { } ``` + + +### Solution 2 + + + +```python +class Solution: + def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int: + n = len(nums1) + f = [0] * (n + 1) + for a, b in sorted(zip(nums1, nums2), key=lambda z: z[1]): + for j in range(n, 0, -1): + f[j] = max(f[j], f[j - 1] + a + b * j) + s1 = sum(nums1) + s2 = sum(nums2) + for j in range(n + 1): + if s1 + s2 * j - f[j] <= x: + return j + return -1 +``` + +```java +class Solution { + public int minimumTime(List nums1, List nums2, int x) { + int n = nums1.size(); + int[] f = new int[n + 1]; + int[][] nums = new int[n][0]; + for (int i = 0; i < n; ++i) { + nums[i] = new int[] {nums1.get(i), nums2.get(i)}; + } + Arrays.sort(nums, Comparator.comparingInt(a -> a[1])); + for (int[] e : nums) { + int a = e[0], b = e[1]; + for (int j = n; j > 0; --j) { + f[j] = Math.max(f[j], f[j - 1] + a + b * j); + } + } + int s1 = 0, s2 = 0; + for (int v : nums1) { + s1 += v; + } + for (int v : nums2) { + s2 += v; + } + + for (int j = 0; j <= n; ++j) { + if (s1 + s2 * j - f[j] <= x) { + return j; + } + } + return -1; + } +} +``` + +```cpp +class Solution { +public: + int minimumTime(vector& nums1, vector& nums2, int x) { + int n = nums1.size(); + vector> nums; + for (int i = 0; i < n; ++i) { + nums.emplace_back(nums2[i], nums1[i]); + } + sort(nums.begin(), nums.end()); + int f[n + 1]; + memset(f, 0, sizeof(f)); + for (auto [b, a] : nums) { + for (int j = n; j; --j) { + f[j] = max(f[j], f[j - 1] + a + b * j); + } + } + int s1 = accumulate(nums1.begin(), nums1.end(), 0); + int s2 = accumulate(nums2.begin(), nums2.end(), 0); + for (int j = 0; j <= n; ++j) { + if (s1 + s2 * j - f[j] <= x) { + return j; + } + } + return -1; + } +}; +``` + +```go +func minimumTime(nums1 []int, nums2 []int, x int) int { + n := len(nums1) + f := make([]int, n+1) + type pair struct{ a, b int } + nums := make([]pair, n) + var s1, s2 int + for i := range nums { + s1 += nums1[i] + s2 += nums2[i] + nums[i] = pair{nums1[i], nums2[i]} + } + sort.Slice(nums, func(i, j int) bool { return nums[i].b < nums[j].b }) + for _, e := range nums { + a, b := e.a, e.b + for j := n; j > 0; j-- { + f[j] = max(f[j], f[j-1]+a+b*j) + } + } + for j := 0; j <= n; j++ { + if s1+s2*j-f[j] <= x { + return j + } + } + return -1 +} +``` + ```ts function minimumTime(nums1: number[], nums2: number[], x: number): number { const n = nums1.length; @@ -375,10 +371,6 @@ function minimumTime(nums1: number[], nums2: number[], x: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2810.Faulty Keyboard/README.md b/solution/2800-2899/2810.Faulty Keyboard/README.md index 394177a6516e8..1a845924cab52 100644 --- a/solution/2800-2899/2810.Faulty Keyboard/README.md +++ b/solution/2800-2899/2810.Faulty Keyboard/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们直接模拟键盘的输入过程,用一个字符数组 $t$ 来记录屏幕上的文本,初始时 $t$ 为空。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def finalString(self, s: str) -> str: @@ -85,10 +79,6 @@ class Solution: return "".join(t) ``` -### **Java** - - - ```java class Solution { public String finalString(String s) { @@ -105,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func finalString(s string) string { t := []rune{} @@ -142,8 +128,6 @@ func finalString(s string) string { } ``` -### **TypeScript** - ```ts function finalString(s: string): string { const t: string[] = []; @@ -158,8 +142,6 @@ function finalString(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn final_string(s: String) -> String { @@ -176,10 +158,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2810.Faulty Keyboard/README_EN.md b/solution/2800-2899/2810.Faulty Keyboard/README_EN.md index fd3260352ffe8..77d24dcf7d823 100644 --- a/solution/2800-2899/2810.Faulty Keyboard/README_EN.md +++ b/solution/2800-2899/2810.Faulty Keyboard/README_EN.md @@ -53,7 +53,7 @@ Therefore, we return "ponter". ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We directly simulate the keyboard input process, using a character array $t$ to record the text on the screen, initially $t$ is empty. @@ -65,8 +65,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$, where $n$ i -### **Python3** - ```python class Solution: def finalString(self, s: str) -> str: @@ -79,8 +77,6 @@ class Solution: return "".join(t) ``` -### **Java** - ```java class Solution { public String finalString(String s) { @@ -97,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +110,6 @@ public: }; ``` -### **Go** - ```go func finalString(s string) string { t := []rune{} @@ -134,8 +126,6 @@ func finalString(s string) string { } ``` -### **TypeScript** - ```ts function finalString(s: string): string { const t: string[] = []; @@ -150,8 +140,6 @@ function finalString(s: string): string { } ``` -### **Rust** - ```rust impl Solution { pub fn final_string(s: String) -> String { @@ -168,10 +156,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2811.Check if it is Possible to Split Array/README.md b/solution/2800-2899/2811.Check if it is Possible to Split Array/README.md index 50e27508f2383..2138ffa7d9683 100644 --- a/solution/2800-2899/2811.Check if it is Possible to Split Array/README.md +++ b/solution/2800-2899/2811.Check if it is Possible to Split Array/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们先预处理得到前缀和数组 $s$,其中 $s[i]$ 表示数组 $nums$ 的前 $i$ 个元素之和。 @@ -88,20 +86,8 @@ 时间复杂度 $O(n^3)$,空间复杂度 $O(n^2)$。其中 $n$ 是数组 $nums$ 的长度。 -**方法二:脑筋急转弯** - -不论如何操作,最终总会剩下一个 `length == 2` 的子数组,又因为元素数值不存在负数,所以随着分割操作的进行,子数组的长度和总和都会逐渐变小,其它 `length > 2` 子数组之和肯定要比该子数组之和更大,进而,我们只需要考虑,是否存在一个 `length == 2` 且总和大于等于 `m` 的子数组即可。 - -> 📢 注意,当 `nums.length <= 2` 时,无需进行操作。 - -时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def canSplitArray(self, nums: List[int], m: int) -> bool: @@ -120,10 +106,6 @@ class Solution: return dfs(0, len(nums) - 1) ``` -### **Java** - - - ```java class Solution { private Boolean[][] f; @@ -160,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -196,8 +176,6 @@ public: }; ``` -### **Go** - ```go func canSplitArray(nums []int, m int) bool { n := len(nums) @@ -232,8 +210,6 @@ func canSplitArray(nums []int, m int) bool { } ``` -### **TypeScript** - ```ts function canSplitArray(nums: number[], m: number): boolean { const n = nums.length; @@ -266,23 +242,6 @@ function canSplitArray(nums: number[], m: number): boolean { } ``` -```ts -function canSplitArray(nums: number[], m: number): boolean { - const n = nums.length; - if (n <= 2) { - return true; - } - for (let i = 1; i < n; i++) { - if (nums[i - 1] + nums[i] >= m) { - return true; - } - } - return false; -} -``` - -### **Rust** - ```rust impl Solution { pub fn can_split_array(nums: Vec, m: i32) -> bool { @@ -300,10 +259,33 @@ impl Solution { } ``` -### **...** + -``` +### 方法二:脑筋急转弯 + +不论如何操作,最终总会剩下一个 `length == 2` 的子数组,又因为元素数值不存在负数,所以随着分割操作的进行,子数组的长度和总和都会逐渐变小,其它 `length > 2` 子数组之和肯定要比该子数组之和更大,进而,我们只需要考虑,是否存在一个 `length == 2` 且总和大于等于 `m` 的子数组即可。 +> 📢 注意,当 `nums.length <= 2` 时,无需进行操作。 + +时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 + + + +```ts +function canSplitArray(nums: number[], m: number): boolean { + const n = nums.length; + if (n <= 2) { + return true; + } + for (let i = 1; i < n; i++) { + if (nums[i - 1] + nums[i] >= m) { + return true; + } + } + return false; +} ``` + + diff --git a/solution/2800-2899/2811.Check if it is Possible to Split Array/README_EN.md b/solution/2800-2899/2811.Check if it is Possible to Split Array/README_EN.md index 86563488b3799..e9b1a190ccb96 100644 --- a/solution/2800-2899/2811.Check if it is Possible to Split Array/README_EN.md +++ b/solution/2800-2899/2811.Check if it is Possible to Split Array/README_EN.md @@ -51,7 +51,7 @@ ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search First, we preprocess to get the prefix sum array $s$, where $s[i]$ represents the sum of the first $i$ elements of the array $nums$. @@ -71,18 +71,8 @@ To avoid repeated calculations, we use the method of memoization search, and use The time complexity is $O(n^3)$, and the space complexity is $O(n^2)$, where $n$ is the length of the array $nums$. -**Solution 2: Quick Thinking** - -No matter how you operate, there will always be a `length == 2` subarray left in the end. Since there are no negative numbers in the elements, as the split operation proceeds, the length and sum of the subarray will gradually decrease. The sum of other `length > 2` subarrays must be larger than the sum of this subarray. Therefore, we only need to consider whether there is a `length == 2` subarray with a sum greater than or equal to `m`. - -> 📢 Note that when `nums.length <= 2`, no operation is needed. - -The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def canSplitArray(self, nums: List[int], m: int) -> bool: @@ -101,8 +91,6 @@ class Solution: return dfs(0, len(nums) - 1) ``` -### **Java** - ```java class Solution { private Boolean[][] f; @@ -139,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +161,6 @@ public: }; ``` -### **Go** - ```go func canSplitArray(nums []int, m int) bool { n := len(nums) @@ -211,8 +195,6 @@ func canSplitArray(nums []int, m int) bool { } ``` -### **TypeScript** - ```ts function canSplitArray(nums: number[], m: number): boolean { const n = nums.length; @@ -245,23 +227,6 @@ function canSplitArray(nums: number[], m: number): boolean { } ``` -```ts -function canSplitArray(nums: number[], m: number): boolean { - const n = nums.length; - if (n <= 2) { - return true; - } - for (let i = 1; i < n; i++) { - if (nums[i - 1] + nums[i] >= m) { - return true; - } - } - return false; -} -``` - -### **Rust** - ```rust impl Solution { pub fn can_split_array(nums: Vec, m: i32) -> bool { @@ -279,10 +244,33 @@ impl Solution { } ``` -### **...** + -``` +### Solution 2: Quick Thinking +No matter how you operate, there will always be a `length == 2` subarray left in the end. Since there are no negative numbers in the elements, as the split operation proceeds, the length and sum of the subarray will gradually decrease. The sum of other `length > 2` subarrays must be larger than the sum of this subarray. Therefore, we only need to consider whether there is a `length == 2` subarray with a sum greater than or equal to `m`. + +> 📢 Note that when `nums.length <= 2`, no operation is needed. + +The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. + + + +```ts +function canSplitArray(nums: number[], m: number): boolean { + const n = nums.length; + if (n <= 2) { + return true; + } + for (let i = 1; i < n; i++) { + if (nums[i - 1] + nums[i] >= m) { + return true; + } + } + return false; +} ``` + + diff --git a/solution/2800-2899/2812.Find the Safest Path in a Grid/README.md b/solution/2800-2899/2812.Find the Safest Path in a Grid/README.md index e417154d91bf8..6083b2101945a 100644 --- a/solution/2800-2899/2812.Find the Safest Path in a Grid/README.md +++ b/solution/2800-2899/2812.Find the Safest Path in a Grid/README.md @@ -68,9 +68,7 @@ ## 解法 - - -**方法一:多源 BFS + 排序 + 并查集** +### 方法一:多源 BFS + 排序 + 并查集 我们可以先找出所有小偷的位置,然后从这些位置开始进行多源 BFS,得到每个位置到小偷的最短距离,然后按照距离从大到小排序,将每个位置逐个加入并查集,如果最终起点和终点在同一个连通分量中,那么当前距离就是答案。 @@ -78,10 +76,6 @@ -### **Python3** - - - ```python class UnionFind: def __init__(self, n): @@ -140,10 +134,6 @@ class Solution: return 0 ``` -### **Java** - - - ```java class Solution { public int maximumSafenessFactor(List> grid) { @@ -233,8 +223,6 @@ class UnionFind { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -316,8 +304,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p []int @@ -409,8 +395,6 @@ func maximumSafenessFactor(grid [][]int) int { } ``` -### **TypeScript** - ```ts class UnionFind { private p: number[]; @@ -494,66 +478,6 @@ function maximumSafenessFactor(grid: number[][]): number { } ``` -```ts -function maximumSafenessFactor(grid: number[][]): number { - const n = grid.length; - const g = Array.from({ length: n }, () => new Array(n).fill(-1)); - const vis = Array.from({ length: n }, () => new Array(n).fill(false)); - let q: [number, number][] = []; - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - if (grid[i][j] === 1) { - q.push([i, j]); - } - } - } - let level = 0; - while (q.length) { - const t: [number, number][] = []; - for (const [x, y] of q) { - if (x < 0 || y < 0 || x === n || y === n || g[x][y] !== -1) { - continue; - } - g[x][y] = level; - t.push([x + 1, y]); - t.push([x - 1, y]); - t.push([x, y + 1]); - t.push([x, y - 1]); - } - q = t; - level++; - } - const dfs = (i: number, j: number, v: number) => { - if (i < 0 || j < 0 || i === n || j === n || vis[i][j] || g[i][j] <= v) { - return false; - } - vis[i][j] = true; - return ( - (i === n - 1 && j === n - 1) || - dfs(i + 1, j, v) || - dfs(i, j + 1, v) || - dfs(i - 1, j, v) || - dfs(i, j - 1, v) - ); - }; - - let left = 0; - let right = level; - while (left < right) { - vis.forEach(v => v.fill(false)); - const mid = (left + right) >>> 1; - if (dfs(0, 0, mid)) { - left = mid + 1; - } else { - right = mid; - } - } - return right; -} -``` - -### **Rust** - ```rust use std::collections::VecDeque; impl Solution { @@ -620,10 +544,70 @@ impl Solution { } ``` -### **...** + + +### 方法二 -``` + + +```ts +function maximumSafenessFactor(grid: number[][]): number { + const n = grid.length; + const g = Array.from({ length: n }, () => new Array(n).fill(-1)); + const vis = Array.from({ length: n }, () => new Array(n).fill(false)); + let q: [number, number][] = []; + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 1) { + q.push([i, j]); + } + } + } + let level = 0; + while (q.length) { + const t: [number, number][] = []; + for (const [x, y] of q) { + if (x < 0 || y < 0 || x === n || y === n || g[x][y] !== -1) { + continue; + } + g[x][y] = level; + t.push([x + 1, y]); + t.push([x - 1, y]); + t.push([x, y + 1]); + t.push([x, y - 1]); + } + q = t; + level++; + } + const dfs = (i: number, j: number, v: number) => { + if (i < 0 || j < 0 || i === n || j === n || vis[i][j] || g[i][j] <= v) { + return false; + } + vis[i][j] = true; + return ( + (i === n - 1 && j === n - 1) || + dfs(i + 1, j, v) || + dfs(i, j + 1, v) || + dfs(i - 1, j, v) || + dfs(i, j - 1, v) + ); + }; + let left = 0; + let right = level; + while (left < right) { + vis.forEach(v => v.fill(false)); + const mid = (left + right) >>> 1; + if (dfs(0, 0, mid)) { + left = mid + 1; + } else { + right = mid; + } + } + return right; +} ``` + + diff --git a/solution/2800-2899/2812.Find the Safest Path in a Grid/README_EN.md b/solution/2800-2899/2812.Find the Safest Path in a Grid/README_EN.md index 586838c351e07..3f3aa79dc5e06 100644 --- a/solution/2800-2899/2812.Find the Safest Path in a Grid/README_EN.md +++ b/solution/2800-2899/2812.Find the Safest Path in a Grid/README_EN.md @@ -63,7 +63,7 @@ It can be shown that there are no other paths with a higher safeness factor. ## Solutions -**Solution 1: BFS + Sorting + Union-Find** +### Solution 1: BFS + Sorting + Union-Find We can first find out the positions of all thieves, and then start multi-source BFS from these positions to get the shortest distance from each position to the thieves. Then sort in descending order according to the distance, and add each position to the union-find set one by one. If the start and end points are in the same connected component, the current distance is the answer. @@ -71,8 +71,6 @@ The time complexity is $O(n^2 \times \log n)$, and the space complexity $O(n^2)$ -### **Python3** - ```python class UnionFind: def __init__(self, n): @@ -131,8 +129,6 @@ class Solution: return 0 ``` -### **Java** - ```java class Solution { public int maximumSafenessFactor(List> grid) { @@ -222,8 +218,6 @@ class UnionFind { } ``` -### **C++** - ```cpp class UnionFind { public: @@ -305,8 +299,6 @@ public: }; ``` -### **Go** - ```go type unionFind struct { p []int @@ -398,8 +390,6 @@ func maximumSafenessFactor(grid [][]int) int { } ``` -### **TypeScript** - ```ts class UnionFind { private p: number[]; @@ -483,66 +473,6 @@ function maximumSafenessFactor(grid: number[][]): number { } ``` -```ts -function maximumSafenessFactor(grid: number[][]): number { - const n = grid.length; - const g = Array.from({ length: n }, () => new Array(n).fill(-1)); - const vis = Array.from({ length: n }, () => new Array(n).fill(false)); - let q: [number, number][] = []; - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - if (grid[i][j] === 1) { - q.push([i, j]); - } - } - } - let level = 0; - while (q.length) { - const t: [number, number][] = []; - for (const [x, y] of q) { - if (x < 0 || y < 0 || x === n || y === n || g[x][y] !== -1) { - continue; - } - g[x][y] = level; - t.push([x + 1, y]); - t.push([x - 1, y]); - t.push([x, y + 1]); - t.push([x, y - 1]); - } - q = t; - level++; - } - const dfs = (i: number, j: number, v: number) => { - if (i < 0 || j < 0 || i === n || j === n || vis[i][j] || g[i][j] <= v) { - return false; - } - vis[i][j] = true; - return ( - (i === n - 1 && j === n - 1) || - dfs(i + 1, j, v) || - dfs(i, j + 1, v) || - dfs(i - 1, j, v) || - dfs(i, j - 1, v) - ); - }; - - let left = 0; - let right = level; - while (left < right) { - vis.forEach(v => v.fill(false)); - const mid = (left + right) >>> 1; - if (dfs(0, 0, mid)) { - left = mid + 1; - } else { - right = mid; - } - } - return right; -} -``` - -### **Rust** - ```rust use std::collections::VecDeque; impl Solution { @@ -609,10 +539,70 @@ impl Solution { } ``` -### **...** + + +### Solution 2 -``` + + +```ts +function maximumSafenessFactor(grid: number[][]): number { + const n = grid.length; + const g = Array.from({ length: n }, () => new Array(n).fill(-1)); + const vis = Array.from({ length: n }, () => new Array(n).fill(false)); + let q: [number, number][] = []; + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 1) { + q.push([i, j]); + } + } + } + let level = 0; + while (q.length) { + const t: [number, number][] = []; + for (const [x, y] of q) { + if (x < 0 || y < 0 || x === n || y === n || g[x][y] !== -1) { + continue; + } + g[x][y] = level; + t.push([x + 1, y]); + t.push([x - 1, y]); + t.push([x, y + 1]); + t.push([x, y - 1]); + } + q = t; + level++; + } + const dfs = (i: number, j: number, v: number) => { + if (i < 0 || j < 0 || i === n || j === n || vis[i][j] || g[i][j] <= v) { + return false; + } + vis[i][j] = true; + return ( + (i === n - 1 && j === n - 1) || + dfs(i + 1, j, v) || + dfs(i, j + 1, v) || + dfs(i - 1, j, v) || + dfs(i, j - 1, v) + ); + }; + let left = 0; + let right = level; + while (left < right) { + vis.forEach(v => v.fill(false)); + const mid = (left + right) >>> 1; + if (dfs(0, 0, mid)) { + left = mid + 1; + } else { + right = mid; + } + } + return right; +} ``` + + diff --git a/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/README.md b/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/README.md index 19632fa1406b4..061492845ba7e 100644 --- a/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/README.md +++ b/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/README.md @@ -70,9 +70,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们可以将所有项目按照利润从大到小排序,先选取前 $k$ 个项目,计算其总利润 $tot$,用一个哈希表 $vis$ 记录这 $k$ 个项目的类别,用一个栈 $dup$ 按顺序记录这 $k$ 个项目中重复类别的利润,用一个变量 $ans$ 记录当前的最大优雅度。 @@ -84,10 +82,6 @@ -### **Python3** - - - ```python class Solution: def findMaximumElegance(self, items: List[List[int]], k: int) -> int: @@ -111,10 +105,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long findMaximumElegance(int[][] items, int k) { @@ -145,8 +135,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -183,8 +171,6 @@ public: }; ``` -### **Go** - ```go func findMaximumElegance(items [][]int, k int) int64 { sort.Slice(items, func(i, j int) bool { return items[i][0] > items[j][0] }) @@ -215,8 +201,6 @@ func findMaximumElegance(items [][]int, k int) int64 { } ``` -### **TypeScript** - ```ts function findMaximumElegance(items: number[][], k: number): number { items.sort((a, b) => b[0] - a[0]); @@ -244,10 +228,6 @@ function findMaximumElegance(items: number[][], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/README_EN.md b/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/README_EN.md index 639704645bcce..f9a86da8d45af 100644 --- a/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/README_EN.md +++ b/solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/README_EN.md @@ -63,7 +63,7 @@ Hence, the maximum elegance is 6 + 12 = 7. ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy We can sort all items by profit from large to small. First choose the first $k$ items and calculate the total profit $tot$. Use a hash table $vis$ to record the categories of these $k$ items, use a stack $dup$ to record the profits of the repeated categories in order, and use a variable $ans$ to record the current maximum elegance. @@ -75,8 +75,6 @@ The time complexity is $O(n \times \log n)$ and the space complexity is $O(n)$, -### **Python3** - ```python class Solution: def findMaximumElegance(self, items: List[List[int]], k: int) -> int: @@ -100,8 +98,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long findMaximumElegance(int[][] items, int k) { @@ -132,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +164,6 @@ public: }; ``` -### **Go** - ```go func findMaximumElegance(items [][]int, k int) int64 { sort.Slice(items, func(i, j int) bool { return items[i][0] > items[j][0] }) @@ -202,8 +194,6 @@ func findMaximumElegance(items [][]int, k int) int64 { } ``` -### **TypeScript** - ```ts function findMaximumElegance(items: number[][], k: number): number { items.sort((a, b) => b[0] - a[0]); @@ -231,10 +221,6 @@ function findMaximumElegance(items: number[][], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2814.Minimum Time Takes to Reach Destination Without Drowning/README.md b/solution/2800-2899/2814.Minimum Time Takes to Reach Destination Without Drowning/README.md index d861f748c831e..f80702f08db46 100644 --- a/solution/2800-2899/2814.Minimum Time Takes to Reach Destination Without Drowning/README.md +++ b/solution/2800-2899/2814.Minimum Time Takes to Reach Destination Without Drowning/README.md @@ -74,9 +74,7 @@ ## 解法 - - -**方法一:两次 BFS** +### 方法一:两次 BFS 我们先跑一次 BFS,求出每个点到水域的最短距离,记录在数组 $g$ 中。然后再跑一次 BFS,从单元格 $(s_i, s_j)$ 出发,求出到达目标单元格 $(d_i, d_j)$ 的最短距离。在此过程中,如果当前单元格 $(i, j)$ 的相邻单元格 $(x, y)$ 满足 $g[x][y] \gt t + 1$,那么我们就可以从 $(x, y)$ 走到 $(i, j)$。 @@ -84,10 +82,6 @@ -### **Python3** - - - ```python class Solution: def minimumSeconds(self, land: List[List[str]]) -> int: @@ -144,10 +138,6 @@ class Solution: return -1 ``` -### **Java** - - - ```java class Solution { public int minimumSeconds(List> land) { @@ -215,8 +205,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -286,8 +274,6 @@ public: }; ``` -### **Go** - ```go func minimumSeconds(land [][]string) int { m, n := len(land), len(land[0]) @@ -360,8 +346,6 @@ func minimumSeconds(land [][]string) int { } ``` -### **TypeScript** - ```ts function minimumSeconds(land: string[][]): number { const m = land.length; @@ -431,10 +415,6 @@ function minimumSeconds(land: string[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2814.Minimum Time Takes to Reach Destination Without Drowning/README_EN.md b/solution/2800-2899/2814.Minimum Time Takes to Reach Destination Without Drowning/README_EN.md index 8bc9f6b61c219..f3bc4e48513f0 100644 --- a/solution/2800-2899/2814.Minimum Time Takes to Reach Destination Without Drowning/README_EN.md +++ b/solution/2800-2899/2814.Minimum Time Takes to Reach Destination Without Drowning/README_EN.md @@ -69,7 +69,7 @@ So the answer would be -1. ## Solutions -**Solution 1: Two BFS Traversals** +### Solution 1: Two BFS Traversals First, we run a BFS (Breadth-First Search) to calculate the shortest distance from each cell to the water, and record it in the array $g$. Then, we run another BFS starting from the cell $(s_i, s_j)$ to find the shortest distance to the target cell $(d_i, d_j)$. During this process, if the adjacent cell $(x, y)$ of the current cell $(i, j)$ satisfies $g[x][y] > t + 1$, then we can move from $(x, y)$ to $(i, j)$. @@ -77,8 +77,6 @@ The time complexity is $O(m \times n)$ and the space complexity is $O(m \times n -### **Python3** - ```python class Solution: def minimumSeconds(self, land: List[List[str]]) -> int: @@ -135,8 +133,6 @@ class Solution: return -1 ``` -### **Java** - ```java class Solution { public int minimumSeconds(List> land) { @@ -204,8 +200,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -275,8 +269,6 @@ public: }; ``` -### **Go** - ```go func minimumSeconds(land [][]string) int { m, n := len(land), len(land[0]) @@ -349,8 +341,6 @@ func minimumSeconds(land [][]string) int { } ``` -### **TypeScript** - ```ts function minimumSeconds(land: string[][]): number { const m = land.length; @@ -420,10 +410,6 @@ function minimumSeconds(land: string[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2815.Max Pair Sum in an Array/README.md b/solution/2800-2899/2815.Max Pair Sum in an Array/README.md index 2a47b93ecce45..08b5db95f0a34 100644 --- a/solution/2800-2899/2815.Max Pair Sum in an Array/README.md +++ b/solution/2800-2899/2815.Max Pair Sum in an Array/README.md @@ -39,9 +39,7 @@ i = 3 和 j = 4 ,nums[i] 和 nums[j] 数位上最大的数字相等,且这 ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们先初始化答案变量 $ans = -1$。接下来,直接枚举所有的数对 $(nums[i], nums[j])$,其中 $i \lt j$,并计算它们的和 $v = nums[i] + nums[j]$。如果 $v$ 比 $ans$ 更大,并且 $nums[i]$ 和 $nums[j]$ 的最大数字相同,那么我们就用 $v$ 更新 $ans$。 @@ -49,10 +47,6 @@ i = 3 和 j = 4 ,nums[i] 和 nums[j] 数位上最大的数字相等,且这 -### **Python3** - - - ```python class Solution: def maxSum(self, nums: List[int]) -> int: @@ -65,10 +59,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxSum(int[] nums) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +111,6 @@ public: }; ``` -### **Go** - ```go func maxSum(nums []int) int { ans := -1 @@ -146,8 +132,6 @@ func maxSum(nums []int) int { } ``` -### **TypeScript** - ```ts function maxSum(nums: number[]): number { const n = nums.length; @@ -171,10 +155,6 @@ function maxSum(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2815.Max Pair Sum in an Array/README_EN.md b/solution/2800-2899/2815.Max Pair Sum in an Array/README_EN.md index bd89d1d460a76..89bb2657a6b58 100644 --- a/solution/2800-2899/2815.Max Pair Sum in an Array/README_EN.md +++ b/solution/2800-2899/2815.Max Pair Sum in an Array/README_EN.md @@ -37,7 +37,7 @@ It can be shown that there are no other pairs with equal maximum digits, so the ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration First, we initialize the answer variable $ans=-1$. Next, we directly enumerate all pairs $(nums[i], nums[j])$ where $i \lt j$, and calculate their sum $v=nums[i] + nums[j]$. If $v$ is greater than $ans$ and the largest digit of $nums[i]$ and $nums[j]$ are the same, then we update $ans$ with $v$. @@ -45,8 +45,6 @@ The time complexity is $O(n^2 \times \log M)$, where $n$ is the length of the ar -### **Python3** - ```python class Solution: def maxSum(self, nums: List[int]) -> int: @@ -59,8 +57,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxSum(int[] nums) { @@ -87,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +109,6 @@ public: }; ``` -### **Go** - ```go func maxSum(nums []int) int { ans := -1 @@ -138,8 +130,6 @@ func maxSum(nums []int) int { } ``` -### **TypeScript** - ```ts function maxSum(nums: number[]): number { const n = nums.length; @@ -163,10 +153,6 @@ function maxSum(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2816.Double a Number Represented as a Linked List/README.md b/solution/2800-2899/2816.Double a Number Represented as a Linked List/README.md index f22f909d05ea5..925b8ebd88841 100644 --- a/solution/2800-2899/2816.Double a Number Represented as a Linked List/README.md +++ b/solution/2800-2899/2816.Double a Number Represented as a Linked List/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:翻转链表 + 模拟** +### 方法一:翻转链表 + 模拟 我们先将链表翻转,然后模拟乘法运算,最后再将链表翻转回来。 @@ -49,10 +47,6 @@ -### **Python3** - - - ```python # Definition for singly-linked list. # class ListNode: @@ -85,10 +79,6 @@ class Solution: return reverse(dummy.next) ``` -### **Java** - - - ```java /** * Definition for singly-linked list. @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -180,8 +168,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -221,8 +207,6 @@ func reverse(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -268,10 +252,6 @@ function reverse(head: ListNode | null): ListNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2816.Double a Number Represented as a Linked List/README_EN.md b/solution/2800-2899/2816.Double a Number Represented as a Linked List/README_EN.md index f53ca6810eaf7..cc6721d782383 100644 --- a/solution/2800-2899/2816.Double a Number Represented as a Linked List/README_EN.md +++ b/solution/2800-2899/2816.Double a Number Represented as a Linked List/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Reverse Linked List + Simulation** +### Solution 1: Reverse Linked List + Simulation First, we reverse the linked list, then simulate the multiplication operation, and finally reverse the linked list back. @@ -44,8 +44,6 @@ Time complexity is $O(n)$, where $n$ is the length of the linked list. Ignoring -### **Python3** - ```python # Definition for singly-linked list. # class ListNode: @@ -78,8 +76,6 @@ class Solution: return reverse(dummy.next) ``` -### **Java** - ```java /** * Definition for singly-linked list. @@ -124,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp /** * Definition for singly-linked list. @@ -171,8 +165,6 @@ public: }; ``` -### **Go** - ```go /** * Definition for singly-linked list. @@ -212,8 +204,6 @@ func reverse(head *ListNode) *ListNode { } ``` -### **TypeScript** - ```ts /** * Definition for singly-linked list. @@ -259,10 +249,6 @@ function reverse(head: ListNode | null): ListNode | null { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/README.md b/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/README.md index 231e38648c845..79f35b5900c49 100644 --- a/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/README.md +++ b/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:有序集合** +### 方法一:有序集合 我们创建一个有序集合,用于存储距离当前下标至少为 $x$ 的元素。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python from sortedcontainers import SortedList @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minAbsoluteDifference(List nums, int x) { @@ -117,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func minAbsoluteDifference(nums []int, x int) int { rbt := redblacktree.NewWithIntComparator() @@ -162,8 +148,6 @@ func minAbsoluteDifference(nums []int, x int) int { } ``` -### **TypeScript** - ```ts function minAbsoluteDifference(nums: number[], x: number): number { const s = new TreeMultiSet(); @@ -686,10 +670,6 @@ class TreeMultiSet { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/README_EN.md b/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/README_EN.md index 34308db7703ed..21866e71385e7 100644 --- a/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/README_EN.md +++ b/solution/2800-2899/2817.Minimum Absolute Difference Between Elements With Constraint/README_EN.md @@ -54,7 +54,7 @@ It can be shown that 3 is the optimal answer. ## Solutions -**Solution 1: Ordered Set** +### Solution 1: Ordered Set We create an ordered set to store the elements whose distance to the current index is at least $x$. @@ -64,8 +64,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python from sortedcontainers import SortedList @@ -84,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minAbsoluteDifference(List nums, int x) { @@ -107,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +125,6 @@ public: }; ``` -### **Go** - ```go func minAbsoluteDifference(nums []int, x int) int { rbt := redblacktree.NewWithIntComparator() @@ -152,8 +144,6 @@ func minAbsoluteDifference(nums []int, x int) int { } ``` -### **TypeScript** - ```ts function minAbsoluteDifference(nums: number[], x: number): number { const s = new TreeMultiSet(); @@ -676,10 +666,6 @@ class TreeMultiSet { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2818.Apply Operations to Maximize Score/README.md b/solution/2800-2899/2818.Apply Operations to Maximize Score/README.md index 1dc1a1c94f28f..8b9a558e74db1 100644 --- a/solution/2800-2899/2818.Apply Operations to Maximize Score/README.md +++ b/solution/2800-2899/2818.Apply Operations to Maximize Score/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:单调栈 + 排序贪心** +### 方法一:单调栈 + 排序贪心 我们不妨考虑枚举每个元素 $nums[i]$ 作为质数分数最高的元素,那么我们需要找出左边第一个质数分数大于等于当前元素的位置 $l$,以及右边第一个质数分数大于当前元素的位置 $r$,那么以当前元素为最高质数分数的子数组有 $cnt = (i - l) \times (r - i)$ 个,它对答案的贡献为 $nums[i]^{cnt}$。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python def primeFactors(n): i = 2 @@ -130,10 +124,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -216,8 +206,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -297,8 +285,6 @@ public: }; ``` -### **Go** - ```go func maximumScore(nums []int, k int) int { n := len(nums) @@ -377,8 +363,6 @@ func primeFactors(n int) int { } ``` -### **TypeScript** - ```ts function maximumScore(nums: number[], k: number): number { const mod = 10 ** 9 + 7; @@ -457,10 +441,6 @@ function qpow(a: bigint, n: number, mod: number): bigint { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2818.Apply Operations to Maximize Score/README_EN.md b/solution/2800-2899/2818.Apply Operations to Maximize Score/README_EN.md index 3485e9a6e9b21..4c48268985d90 100644 --- a/solution/2800-2899/2818.Apply Operations to Maximize Score/README_EN.md +++ b/solution/2800-2899/2818.Apply Operations to Maximize Score/README_EN.md @@ -56,7 +56,7 @@ It can be proven that 4788 is the highest score one can obtain. ## Solutions -**Solution 1: Monotonic Stack + Greedy** +### Solution 1: Monotonic Stack + Greedy It is not difficult to see that the number of subarrays with the highest prime score of an element $nums[i]$ is $cnt = (i - l) \times (r - i)$, where $l$ is the leftmost index such that $primeScore(nums[l]) \ge primeScore(nums[i])$, and $r$ is the rightmost index such that $primeScore(nums[r]) \ge primeScore(nums[i])$. @@ -68,8 +68,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python def primeFactors(n): i = 2 @@ -122,8 +120,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -206,8 +202,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -287,8 +281,6 @@ public: }; ``` -### **Go** - ```go func maximumScore(nums []int, k int) int { n := len(nums) @@ -367,8 +359,6 @@ func primeFactors(n int) int { } ``` -### **TypeScript** - ```ts function maximumScore(nums: number[], k: number): number { const mod = 10 ** 9 + 7; @@ -447,10 +437,6 @@ function qpow(a: bigint, n: number, mod: number): bigint { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/README.md b/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/README.md index aa4f0e443d031..20bce8fa4651a 100644 --- a/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/README.md +++ b/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/README.md @@ -70,9 +70,7 @@ ## 解法 - - -**方法一:排序 + 二分查找 + 前缀和** +### 方法一:排序 + 二分查找 + 前缀和 根据题目描述,我们可以知道: @@ -90,10 +88,6 @@ -### **Python3** - - - ```python class Solution: def minimumRelativeLosses( @@ -122,10 +116,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int n; @@ -170,8 +160,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -209,8 +197,6 @@ public: }; ``` -### **Go** - ```go func minimumRelativeLosses(prices []int, queries [][]int) []int64 { n := len(prices) @@ -246,8 +232,6 @@ func minimumRelativeLosses(prices []int, queries [][]int) []int64 { } ``` -### **TypeScript** - ```ts function minimumRelativeLosses(prices: number[], queries: number[][]): number[] { const n = prices.length; @@ -295,10 +279,6 @@ function minimumRelativeLosses(prices: number[], queries: number[][]): number[] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/README_EN.md b/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/README_EN.md index 196bbc1908a21..28898d54934bf 100644 --- a/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/README_EN.md +++ b/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/README_EN.md @@ -66,7 +66,7 @@ It can be shown that these are the minimum possible relative losses. ## Solutions -**Solution 1: Sorting + Binary Search + Prefix Sum** +### Solution 1: Sorting + Binary Search + Prefix Sum Based on the problem description, we know: @@ -84,8 +84,6 @@ The time complexity is $O((n + m) \times \log n)$, and the space complexity is $ -### **Python3** - ```python class Solution: def minimumRelativeLosses( @@ -114,8 +112,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int n; @@ -160,8 +156,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -199,8 +193,6 @@ public: }; ``` -### **Go** - ```go func minimumRelativeLosses(prices []int, queries [][]int) []int64 { n := len(prices) @@ -236,8 +228,6 @@ func minimumRelativeLosses(prices []int, queries [][]int) []int64 { } ``` -### **TypeScript** - ```ts function minimumRelativeLosses(prices: number[], queries: number[][]): number[] { const n = prices.length; @@ -285,10 +275,6 @@ function minimumRelativeLosses(prices: number[], queries: number[][]): number[] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2820.Election Results/README.md b/solution/2800-2899/2820.Election Results/README.md index 3252747fcd9eb..5aabb78e99188 100644 --- a/solution/2800-2899/2820.Election Results/README.md +++ b/solution/2800-2899/2820.Election Results/README.md @@ -62,9 +62,7 @@ Votes table: ## 解法 - - -**方法一:窗口函数 + 分组统计** +### 方法一:窗口函数 + 分组统计 我们可以使用窗口函数 `count` 计算每个投票人投给的候选人的票数,然后再使用分组统计函数 `sum` 计算每个候选人的总票数,最后使用窗口函数 `rank` 计算每个候选人的排名,最后筛选出排名第一的候选人即可。 @@ -72,10 +70,6 @@ Votes table: -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -104,3 +98,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2800-2899/2820.Election Results/README_EN.md b/solution/2800-2899/2820.Election Results/README_EN.md index e3b5445878c47..67c7d489429e3 100644 --- a/solution/2800-2899/2820.Election Results/README_EN.md +++ b/solution/2800-2899/2820.Election Results/README_EN.md @@ -59,7 +59,7 @@ Since Ryan and Christine received an equal number of votes, we will display thei ## Solutions -**Solution 1: Window Function + Group Statistics** +### Solution 1: Window Function + Group Statistics We can use the window function `count` to calculate the number of votes each voter gives to the candidates, then use the group statistics function `sum` to calculate the total number of votes for each candidate. Next, we use the window function `rank` to calculate the ranking of each candidate, and finally filter out the candidate who ranks first. @@ -67,8 +67,6 @@ Note that there may be multiple candidates ranking first in the result set, so w -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -97,3 +95,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2800-2899/2821.Delay the Resolution of Each Promise/README.md b/solution/2800-2899/2821.Delay the Resolution of Each Promise/README.md index 81d5ba3543568..de6a5b2f680ae 100644 --- a/solution/2800-2899/2821.Delay the Resolution of Each Promise/README.md +++ b/solution/2800-2899/2821.Delay the Resolution of Each Promise/README.md @@ -54,14 +54,10 @@ ms = 70 ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function delayAll(functions: Function[], ms: number): Function[] { return functions.map(fn => { @@ -74,3 +70,5 @@ function delayAll(functions: Function[], ms: number): Function[] { ``` + + diff --git a/solution/2800-2899/2821.Delay the Resolution of Each Promise/README_EN.md b/solution/2800-2899/2821.Delay the Resolution of Each Promise/README_EN.md index 6feafa34db150..4a652f328be4d 100644 --- a/solution/2800-2899/2821.Delay the Resolution of Each Promise/README_EN.md +++ b/solution/2800-2899/2821.Delay the Resolution of Each Promise/README_EN.md @@ -50,9 +50,9 @@ ms = 70 ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function delayAll(functions: Function[], ms: number): Function[] { @@ -66,3 +66,5 @@ function delayAll(functions: Function[], ms: number): Function[] { ``` + + diff --git a/solution/2800-2899/2822.Inversion of Object/README.md b/solution/2800-2899/2822.Inversion of Object/README.md index 30eea6a93195e..e44791cbe0e4e 100644 --- a/solution/2800-2899/2822.Inversion of Object/README.md +++ b/solution/2800-2899/2822.Inversion of Object/README.md @@ -47,14 +47,10 @@ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts function invertObject(obj: Record): Record { const ans: Record = {}; @@ -74,3 +70,5 @@ function invertObject(obj: Record): Record { ``` + + diff --git a/solution/2800-2899/2822.Inversion of Object/README_EN.md b/solution/2800-2899/2822.Inversion of Object/README_EN.md index a345e64a8db3a..9a03818ce5ee9 100644 --- a/solution/2800-2899/2822.Inversion of Object/README_EN.md +++ b/solution/2800-2899/2822.Inversion of Object/README_EN.md @@ -43,9 +43,9 @@ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function invertObject(obj: Record): Record { @@ -66,3 +66,5 @@ function invertObject(obj: Record): Record { ``` + + diff --git a/solution/2800-2899/2823.Deep Object Filter/README.md b/solution/2800-2899/2823.Deep Object Filter/README.md index 497e20b50e85c..93ede02e0daf6 100644 --- a/solution/2800-2899/2823.Deep Object Filter/README.md +++ b/solution/2800-2899/2823.Deep Object Filter/README.md @@ -63,9 +63,7 @@ fn = (x) => Array.isArray(x) ## 解法 - - -**方法一:递归** +### 方法一:递归 我们先判断当前对象是否为数组,如果是数组,我们就对数组中的每一个元素进行递归调用,然后过滤掉返回值为 `undefined` 的元素,最后返回过滤后的数组。 @@ -77,10 +75,6 @@ fn = (x) => Array.isArray(x) -### **TypeScript** - - - ```ts function deepFilter(obj: Record, fn: Function): Record | undefined { const dfs = (data: any): any => { @@ -108,3 +102,5 @@ function deepFilter(obj: Record, fn: Function): Record ``` + + diff --git a/solution/2800-2899/2823.Deep Object Filter/README_EN.md b/solution/2800-2899/2823.Deep Object Filter/README_EN.md index fe4cbb5968639..2328a982fe4b5 100644 --- a/solution/2800-2899/2823.Deep Object Filter/README_EN.md +++ b/solution/2800-2899/2823.Deep Object Filter/README_EN.md @@ -60,9 +60,9 @@ fn = (x) => Array.isArray(x) ## Solutions - +### Solution 1 -### **TypeScript** + ```ts function deepFilter(obj: Record, fn: Function): Record | undefined { @@ -91,3 +91,5 @@ function deepFilter(obj: Record, fn: Function): Record ``` + + diff --git a/solution/2800-2899/2824.Count Pairs Whose Sum is Less than Target/README.md b/solution/2800-2899/2824.Count Pairs Whose Sum is Less than Target/README.md index ffc9ded1ca73d..6356d7912463d 100644 --- a/solution/2800-2899/2824.Count Pairs Whose Sum is Less than Target/README.md +++ b/solution/2800-2899/2824.Count Pairs Whose Sum is Less than Target/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:排序 + 二分查找** +### 方法一:排序 + 二分查找 我们先对数组 $nums$ 进行排序,然后枚举 $j$,在 $[0, j)$ 的范围内使用二分查找第一个大于等于 $target - nums[j]$ 的下标 $i$,那么 $[0, i)$ 的范围内的所有下标 $k$ 都满足条件,因此答案增加 $i$。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def countPairs(self, nums: List[int], target: int) -> int: @@ -78,10 +72,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countPairs(List nums, int target) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func countPairs(nums []int, target int) (ans int) { sort.Ints(nums) @@ -140,8 +126,6 @@ func countPairs(nums []int, target int) (ans int) { } ``` -### **TypeScript** - ```ts function countPairs(nums: number[], target: number): number { nums.sort((a, b) => a - b); @@ -166,10 +150,6 @@ function countPairs(nums: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2824.Count Pairs Whose Sum is Less than Target/README_EN.md b/solution/2800-2899/2824.Count Pairs Whose Sum is Less than Target/README_EN.md index 09496fa016e4c..1b9beb021d1ba 100644 --- a/solution/2800-2899/2824.Count Pairs Whose Sum is Less than Target/README_EN.md +++ b/solution/2800-2899/2824.Count Pairs Whose Sum is Less than Target/README_EN.md @@ -47,7 +47,7 @@ Note that (0, 3) is not counted since nums[0] + nums[3] is not strictly less tha ## Solutions -**Solution 1: Sorting + Binary Search** +### Solution 1: Sorting + Binary Search First, we sort the array $nums$. Then, for each $j$, we use binary search in the range $[0, j)$ to find the first index $i$ that is greater than or equal to $target - nums[j]$. All indices $k$ in the range $[0, i)$ meet the condition, so the answer increases by $i$. @@ -57,8 +57,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def countPairs(self, nums: List[int], target: int) -> int: @@ -70,8 +68,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countPairs(List nums, int target) { @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func countPairs(nums []int, target int) (ans int) { sort.Ints(nums) @@ -130,8 +122,6 @@ func countPairs(nums []int, target int) (ans int) { } ``` -### **TypeScript** - ```ts function countPairs(nums: number[], target: number): number { nums.sort((a, b) => a - b); @@ -156,10 +146,6 @@ function countPairs(nums: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2825.Make String a Subsequence Using Cyclic Increments/README.md b/solution/2800-2899/2825.Make String a Subsequence Using Cyclic Increments/README.md index 331bd3c49072a..69acef947af7a 100644 --- a/solution/2800-2899/2825.Make String a Subsequence Using Cyclic Increments/README.md +++ b/solution/2800-2899/2825.Make String a Subsequence Using Cyclic Increments/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 本题实际上需要我们判断一个字符串 $s$ 是否为另一个字符串 $t$ 的子序列,只不过字符之间可以不完全匹配,如果两个字符相同,或者一个字符是另一个字符的下一个字符,就可以匹配。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def canMakeSubsequence(self, str1: str, str2: str) -> bool: @@ -80,10 +74,6 @@ class Solution: return i == len(str2) ``` -### **Java** - - - ```java class Solution { public boolean canMakeSubsequence(String str1, String str2) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func canMakeSubsequence(str1 string, str2 string) bool { i, n := 0, len(str2) @@ -135,8 +121,6 @@ func canMakeSubsequence(str1 string, str2 string) bool { } ``` -### **TypeScript** - ```ts function canMakeSubsequence(str1: string, str2: string): boolean { let i = 0; @@ -151,10 +135,6 @@ function canMakeSubsequence(str1: string, str2: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2825.Make String a Subsequence Using Cyclic Increments/README_EN.md b/solution/2800-2899/2825.Make String a Subsequence Using Cyclic Increments/README_EN.md index cc84fc8d5063c..06993150fd6c0 100644 --- a/solution/2800-2899/2825.Make String a Subsequence Using Cyclic Increments/README_EN.md +++ b/solution/2800-2899/2825.Make String a Subsequence Using Cyclic Increments/README_EN.md @@ -51,7 +51,7 @@ Therefore, false is returned. ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers This problem actually requires us to determine whether a string $s$ is a subsequence of another string $t$. However, the characters do not have to match exactly. If two characters are the same, or one character is the next character of the other, they can match. @@ -59,8 +59,6 @@ The time complexity is $O(m + n)$, where $m$ and $n$ are the lengths of the stri -### **Python3** - ```python class Solution: def canMakeSubsequence(self, str1: str, str2: str) -> bool: @@ -72,8 +70,6 @@ class Solution: return i == len(str2) ``` -### **Java** - ```java class Solution { public boolean canMakeSubsequence(String str1, String str2) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +101,6 @@ public: }; ``` -### **Go** - ```go func canMakeSubsequence(str1 string, str2 string) bool { i, n := 0, len(str2) @@ -125,8 +117,6 @@ func canMakeSubsequence(str1 string, str2 string) bool { } ``` -### **TypeScript** - ```ts function canMakeSubsequence(str1: string, str2: string): boolean { let i = 0; @@ -141,10 +131,6 @@ function canMakeSubsequence(str1: string, str2: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2826.Sorting Three Groups/README.md b/solution/2800-2899/2826.Sorting Three Groups/README.md index e1a7947874734..8fcd6e6dcbb9c 100644 --- a/solution/2800-2899/2826.Sorting Three Groups/README.md +++ b/solution/2800-2899/2826.Sorting Three Groups/README.md @@ -74,9 +74,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示将前 $i$ 个数变成美丽数组,并且第 $i$ 个数变成 $j+1$ 的最少操作次数。那么答案就是 $\min(f[n][0], f[n][1], f[n][2])$。 @@ -86,10 +84,6 @@ -### **Python3** - - - ```python class Solution: def minimumOperations(self, nums: List[int]) -> int: @@ -112,32 +106,6 @@ class Solution: return min(f, g, h) ``` -```python -class Solution: - def minimumOperations(self, nums: List[int]) -> int: - f = [0] * 3 - for x in nums: - g = [0] * 3 - if x == 1: - g[0] = f[0] - g[1] = min(f[:2]) + 1 - g[2] = min(f) + 1 - elif x == 2: - g[0] = f[0] + 1 - g[1] = min(f[:2]) - g[2] = min(f) + 1 - else: - g[0] = f[0] + 1 - g[1] = min(f[:2]) + 1 - g[2] = min(f) - f = g - return min(f) -``` - -### **Java** - - - ```java class Solution { public int minimumOperations(List nums) { @@ -164,8 +132,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -193,8 +159,6 @@ public: }; ``` -### **Go** - ```go func minimumOperations(nums []int) int { f := make([]int, 3) @@ -219,8 +183,6 @@ func minimumOperations(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumOperations(nums: number[]): number { let f: number[] = new Array(3).fill(0); @@ -245,10 +207,34 @@ function minimumOperations(nums: number[]): number { } ``` -### **...** + -``` +### 方法二 + + +```python +class Solution: + def minimumOperations(self, nums: List[int]) -> int: + f = [0] * 3 + for x in nums: + g = [0] * 3 + if x == 1: + g[0] = f[0] + g[1] = min(f[:2]) + 1 + g[2] = min(f) + 1 + elif x == 2: + g[0] = f[0] + 1 + g[1] = min(f[:2]) + g[2] = min(f) + 1 + else: + g[0] = f[0] + 1 + g[1] = min(f[:2]) + 1 + g[2] = min(f) + f = g + return min(f) ``` + + diff --git a/solution/2800-2899/2826.Sorting Three Groups/README_EN.md b/solution/2800-2899/2826.Sorting Three Groups/README_EN.md index e35e77eb7aa67..31ff71abf2cd1 100644 --- a/solution/2800-2899/2826.Sorting Three Groups/README_EN.md +++ b/solution/2800-2899/2826.Sorting Three Groups/README_EN.md @@ -70,7 +70,7 @@ After sorting the numbers in each group, group 1 becomes empty, group 2 becomes ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ as the minimum number of operations to turn the first $i$ numbers into a beautiful array, and the $i$th number is changed to $j+1$. The answer is $\min(f[n][0], f[n][1], f[n][2])$. @@ -80,8 +80,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def minimumOperations(self, nums: List[int]) -> int: @@ -104,30 +102,6 @@ class Solution: return min(f, g, h) ``` -```python -class Solution: - def minimumOperations(self, nums: List[int]) -> int: - f = [0] * 3 - for x in nums: - g = [0] * 3 - if x == 1: - g[0] = f[0] - g[1] = min(f[:2]) + 1 - g[2] = min(f) + 1 - elif x == 2: - g[0] = f[0] + 1 - g[1] = min(f[:2]) - g[2] = min(f) + 1 - else: - g[0] = f[0] + 1 - g[1] = min(f[:2]) + 1 - g[2] = min(f) - f = g - return min(f) -``` - -### **Java** - ```java class Solution { public int minimumOperations(List nums) { @@ -154,8 +128,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -183,8 +155,6 @@ public: }; ``` -### **Go** - ```go func minimumOperations(nums []int) int { f := make([]int, 3) @@ -209,8 +179,6 @@ func minimumOperations(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumOperations(nums: number[]): number { let f: number[] = new Array(3).fill(0); @@ -235,10 +203,34 @@ function minimumOperations(nums: number[]): number { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def minimumOperations(self, nums: List[int]) -> int: + f = [0] * 3 + for x in nums: + g = [0] * 3 + if x == 1: + g[0] = f[0] + g[1] = min(f[:2]) + 1 + g[2] = min(f) + 1 + elif x == 2: + g[0] = f[0] + 1 + g[1] = min(f[:2]) + g[2] = min(f) + 1 + else: + g[0] = f[0] + 1 + g[1] = min(f[:2]) + 1 + g[2] = min(f) + f = g + return min(f) ``` + + diff --git a/solution/2800-2899/2827.Number of Beautiful Integers in the Range/README.md b/solution/2800-2899/2827.Number of Beautiful Integers in the Range/README.md index 6585d60b3f091..2f51cc7aa0a1f 100644 --- a/solution/2800-2899/2827.Number of Beautiful Integers in the Range/README.md +++ b/solution/2800-2899/2827.Number of Beautiful Integers in the Range/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:数位 DP** +### 方法一:数位 DP 我们注意到,题目求的是区间 $[low, high]$ 内的美丽整数的个数,对于这种区间 $[l,..r]$ 的问题,我们通常可以考虑转化为求 $[1, r]$ 和 $[1, l-1]$ 的答案,然后相减即可。另外,题目中只涉及到不同数位之间的关系,而不涉及具体的数值,因此我们可以考虑使用数位 DP 来解决。 @@ -92,10 +90,6 @@ -### **Python3** - - - ```python class Solution: def numberOfBeautifulIntegers(self, low: int, high: int, k: int) -> int: @@ -121,10 +115,6 @@ class Solution: return a - b ``` -### **Java** - - - ```java class Solution { private String s; @@ -166,8 +156,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -208,8 +196,6 @@ public: }; ``` -### **Go** - ```go func numberOfBeautifulIntegers(low int, high int, k int) int { s := strconv.Itoa(high) @@ -270,8 +256,6 @@ func g(m, n, k int) [][][]int { } ``` -### **TypeScript** - ```ts function numberOfBeautifulIntegers(low: number, high: number, k: number): number { let s = String(high); @@ -318,10 +302,6 @@ function numberOfBeautifulIntegers(low: number, high: number, k: number): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2827.Number of Beautiful Integers in the Range/README_EN.md b/solution/2800-2899/2827.Number of Beautiful Integers in the Range/README_EN.md index a8550469cc3d1..7320fb9e600de 100644 --- a/solution/2800-2899/2827.Number of Beautiful Integers in the Range/README_EN.md +++ b/solution/2800-2899/2827.Number of Beautiful Integers in the Range/README_EN.md @@ -59,7 +59,7 @@ It can be shown that there is only 1 beautiful integer in the given range. ## Solutions -**Solution 1: Digit DP** +### Solution 1: Digit DP We notice that the problem is asking for the number of beautiful integers in the interval $[low, high]$. For such an interval $[l,..r]$ problem, we can usually consider transforming it into finding the answers for $[1, r]$ and $[1, l-1]$, and then subtracting the latter from the former. Moreover, the problem only involves the relationship between different digits, not the specific values, so we can consider using Digit DP to solve it. @@ -86,8 +86,6 @@ Similar problems: -### **Python3** - ```python class Solution: def numberOfBeautifulIntegers(self, low: int, high: int, k: int) -> int: @@ -113,8 +111,6 @@ class Solution: return a - b ``` -### **Java** - ```java class Solution { private String s; @@ -156,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -198,8 +192,6 @@ public: }; ``` -### **Go** - ```go func numberOfBeautifulIntegers(low int, high int, k int) int { s := strconv.Itoa(high) @@ -260,8 +252,6 @@ func g(m, n, k int) [][][]int { } ``` -### **TypeScript** - ```ts function numberOfBeautifulIntegers(low: number, high: number, k: number): number { let s = String(high); @@ -308,10 +298,6 @@ function numberOfBeautifulIntegers(low: number, high: number, k: number): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/README.md b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/README.md index 8dcbbb98254ff..785a13c23c9f7 100644 --- a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/README.md +++ b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/README.md @@ -54,46 +54,20 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们可以遍历数组 $words$ 中的每个字符串,将其首字母拼接起来,得到一个新的字符串 $t$,然后判断 $t$ 是否等于 $s$ 即可。 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $words$ 的长度。 -**方法二:模拟(空间优化)** - -我们首先判断 $words$ 中的字符串个数是否等于 $s$ 的长度,如果不等于,那么 $s$ 一定不是 $words$ 的首字母缩略词,直接返回 $false$。 - -然后我们遍历 $s$ 的每个字符,判断其是否等于 $words$ 中对应字符串的首字母,如果不等于,那么 $s$ 一定不是 $words$ 的首字母缩略词,直接返回 $false$。 - -遍历结束后,如果没有返回 $false$,那么 $s$ 就是 $words$ 的首字母缩略词,返回 $true$。 - -时间复杂度 $O(n)$,其中 $n$ 是数组 $words$ 的长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def isAcronym(self, words: List[str], s: str) -> bool: return "".join(w[0] for w in words) == s ``` -```python -class Solution: - def isAcronym(self, words: List[str], s: str) -> bool: - return len(words) == len(s) and all(w[0] == c for w, c in zip(words, s)) -``` - -### **Java** - - - ```java class Solution { public boolean isAcronym(List words, String s) { @@ -106,6 +80,66 @@ class Solution { } ``` +```cpp +class Solution { +public: + bool isAcronym(vector& words, string s) { + string t; + for (auto& w : words) { + t += w[0]; + } + return t == s; + } +}; +``` + +```go +func isAcronym(words []string, s string) bool { + t := []byte{} + for _, w := range words { + t = append(t, w[0]) + } + return string(t) == s +} +``` + +```ts +function isAcronym(words: string[], s: string): boolean { + return words.map(w => w[0]).join('') === s; +} +``` + +```rust +impl Solution { + pub fn is_acronym(words: Vec, s: String) -> bool { + words + .iter() + .map(|w| w.chars().next().unwrap_or_default()) + .collect::() == s + } +} +``` + + + +### 方法二:模拟(空间优化) + +我们首先判断 $words$ 中的字符串个数是否等于 $s$ 的长度,如果不等于,那么 $s$ 一定不是 $words$ 的首字母缩略词,直接返回 $false$。 + +然后我们遍历 $s$ 的每个字符,判断其是否等于 $words$ 中对应字符串的首字母,如果不等于,那么 $s$ 一定不是 $words$ 的首字母缩略词,直接返回 $false$。 + +遍历结束后,如果没有返回 $false$,那么 $s$ 就是 $words$ 的首字母缩略词,返回 $true$。 + +时间复杂度 $O(n)$,其中 $n$ 是数组 $words$ 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def isAcronym(self, words: List[str], s: str) -> bool: + return len(words) == len(s) and all(w[0] == c for w, c in zip(words, s)) +``` + ```java class Solution { public boolean isAcronym(List words, String s) { @@ -122,21 +156,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool isAcronym(vector& words, string s) { - string t; - for (auto& w : words) { - t += w[0]; - } - return t == s; - } -}; -``` - ```cpp class Solution { public: @@ -154,18 +173,6 @@ public: }; ``` -### **Go** - -```go -func isAcronym(words []string, s string) bool { - t := []byte{} - for _, w := range words { - t = append(t, w[0]) - } - return string(t) == s -} -``` - ```go func isAcronym(words []string, s string) bool { if len(words) != len(s) { @@ -180,14 +187,6 @@ func isAcronym(words []string, s string) bool { } ``` -### **TypeScript** - -```ts -function isAcronym(words: string[], s: string): boolean { - return words.map(w => w[0]).join('') === s; -} -``` - ```ts function isAcronym(words: string[], s: string): boolean { if (words.length !== s.length) { @@ -202,19 +201,6 @@ function isAcronym(words: string[], s: string): boolean { } ``` -### **Rust** - -```rust -impl Solution { - pub fn is_acronym(words: Vec, s: String) -> bool { - words - .iter() - .map(|w| w.chars().next().unwrap_or_default()) - .collect::() == s - } -} -``` - ```rust impl Solution { pub fn is_acronym(words: Vec, s: String) -> bool { @@ -231,10 +217,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/README_EN.md b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/README_EN.md index a8ca51fc143dd..828fd2888bffa 100644 --- a/solution/2800-2899/2828.Check if a String Is an Acronym of Words/README_EN.md +++ b/solution/2800-2899/2828.Check if a String Is an Acronym of Words/README_EN.md @@ -50,40 +50,20 @@ Hence, s = "ngguoy" is the acronym. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can iterate over each string in the array $words$, concatenate their first letters to form a new string $t$, and then check if $t$ is equal to $s$. The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $words$. -**Solution 2: Simulation (Space Optimization)** - -First, we check if the number of strings in $words$ is equal to the length of $s$. If not, $s$ is definitely not an acronym of the first letters of $words$, and we directly return $false$. - -Then, we iterate over each character in $s$, checking if it is equal to the first letter of the corresponding string in $words$. If not, $s$ is definitely not an acronym of the first letters of $words$, and we directly return $false$. - -After the iteration, if we haven't returned $false$, then $s$ is an acronym of the first letters of $words$, and we return $true$. - -The time complexity is $O(n)$, where $n$ is the length of the array $words$. The space complexity is $O(1)$. - -### **Python3** - ```python class Solution: def isAcronym(self, words: List[str], s: str) -> bool: return "".join(w[0] for w in words) == s ``` -```python -class Solution: - def isAcronym(self, words: List[str], s: str) -> bool: - return len(words) == len(s) and all(w[0] == c for w, c in zip(words, s)) -``` - -### **Java** - ```java class Solution { public boolean isAcronym(List words, String s) { @@ -96,6 +76,66 @@ class Solution { } ``` +```cpp +class Solution { +public: + bool isAcronym(vector& words, string s) { + string t; + for (auto& w : words) { + t += w[0]; + } + return t == s; + } +}; +``` + +```go +func isAcronym(words []string, s string) bool { + t := []byte{} + for _, w := range words { + t = append(t, w[0]) + } + return string(t) == s +} +``` + +```ts +function isAcronym(words: string[], s: string): boolean { + return words.map(w => w[0]).join('') === s; +} +``` + +```rust +impl Solution { + pub fn is_acronym(words: Vec, s: String) -> bool { + words + .iter() + .map(|w| w.chars().next().unwrap_or_default()) + .collect::() == s + } +} +``` + + + +### Solution 2: Simulation (Space Optimization) + +First, we check if the number of strings in $words$ is equal to the length of $s$. If not, $s$ is definitely not an acronym of the first letters of $words$, and we directly return $false$. + +Then, we iterate over each character in $s$, checking if it is equal to the first letter of the corresponding string in $words$. If not, $s$ is definitely not an acronym of the first letters of $words$, and we directly return $false$. + +After the iteration, if we haven't returned $false$, then $s$ is an acronym of the first letters of $words$, and we return $true$. + +The time complexity is $O(n)$, where $n$ is the length of the array $words$. The space complexity is $O(1)$. + + + +```python +class Solution: + def isAcronym(self, words: List[str], s: str) -> bool: + return len(words) == len(s) and all(w[0] == c for w, c in zip(words, s)) +``` + ```java class Solution { public boolean isAcronym(List words, String s) { @@ -112,21 +152,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - bool isAcronym(vector& words, string s) { - string t; - for (auto& w : words) { - t += w[0]; - } - return t == s; - } -}; -``` - ```cpp class Solution { public: @@ -144,18 +169,6 @@ public: }; ``` -### **Go** - -```go -func isAcronym(words []string, s string) bool { - t := []byte{} - for _, w := range words { - t = append(t, w[0]) - } - return string(t) == s -} -``` - ```go func isAcronym(words []string, s string) bool { if len(words) != len(s) { @@ -170,14 +183,6 @@ func isAcronym(words []string, s string) bool { } ``` -### **TypeScript** - -```ts -function isAcronym(words: string[], s: string): boolean { - return words.map(w => w[0]).join('') === s; -} -``` - ```ts function isAcronym(words: string[], s: string): boolean { if (words.length !== s.length) { @@ -192,19 +197,6 @@ function isAcronym(words: string[], s: string): boolean { } ``` -### **Rust** - -```rust -impl Solution { - pub fn is_acronym(words: Vec, s: String) -> bool { - words - .iter() - .map(|w| w.chars().next().unwrap_or_default()) - .collect::() == s - } -} -``` - ```rust impl Solution { pub fn is_acronym(words: Vec, s: String) -> bool { @@ -221,10 +213,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/README.md b/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/README.md index 54b098ebfdf2d..32797a58df05a 100644 --- a/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/README.md +++ b/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:贪心 + 模拟** +### 方法一:贪心 + 模拟 我们从正整数 $i=1$ 开始,依次判断 $i$ 是否可以加入数组中,如果可以加入,则将 $i$ 加入数组中,累加到答案中,然后将 $k-i$ 置为已访问,表示 $k-i$ 不能加入数组中。循环直到数组长度为 $n$。 @@ -52,10 +50,6 @@ -### **Python3** - - - ```python class Solution: def minimumSum(self, n: int, k: int) -> int: @@ -70,10 +64,6 @@ class Solution: return s ``` -### **Java** - - - ```java class Solution { public int minimumSum(int n, int k) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func minimumSum(n int, k int) int { s, i := 0, 1 @@ -138,8 +124,6 @@ func minimumSum(n int, k int) int { } ``` -### **TypeScript** - ```ts function minimumSum(n: number, k: number): number { let s = 0; @@ -159,10 +143,6 @@ function minimumSum(n: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/README_EN.md b/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/README_EN.md index 19b0b128ef253..afc88bfb547fc 100644 --- a/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/README_EN.md +++ b/solution/2800-2899/2829.Determine the Minimum Sum of a k-avoiding Array/README_EN.md @@ -38,7 +38,7 @@ It can be proven that there is no k-avoiding array with a sum less than 3. ## Solutions -**Solution 1: Greedy + Simulation** +### Solution 1: Greedy + Simulation We start from the positive integer $i=1$, and judge whether $i$ can be added to the array in turn. If it can be added, we add $i$ to the array, accumulate it to the answer, and then mark $k-i$ as visited, indicating that $k-i$ cannot be added to the array. The loop continues until the length of the array is $n$. @@ -46,8 +46,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ -### **Python3** - ```python class Solution: def minimumSum(self, n: int, k: int) -> int: @@ -62,8 +60,6 @@ class Solution: return s ``` -### **Java** - ```java class Solution { public int minimumSum(int n, int k) { @@ -84,8 +80,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +102,6 @@ public: }; ``` -### **Go** - ```go func minimumSum(n int, k int) int { s, i := 0, 1 @@ -128,8 +120,6 @@ func minimumSum(n int, k int) int { } ``` -### **TypeScript** - ```ts function minimumSum(n: number, k: number): number { let s = 0; @@ -149,10 +139,6 @@ function minimumSum(n: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2830.Maximize the Profit as the Salesman/README.md b/solution/2800-2899/2830.Maximize the Profit as the Salesman/README.md index ae501613a4653..251a6009f145d 100644 --- a/solution/2800-2899/2830.Maximize the Profit as the Salesman/README.md +++ b/solution/2800-2899/2830.Maximize the Profit as the Salesman/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:排序 + 二分查找 + 动态规划** +### 方法一:排序 + 二分查找 + 动态规划 我们将所有的购买要约按照 $end$ 从小到大排序,然后使用动态规划求解。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def maximizeTheProfit(self, n: int, offers: List[List[int]]) -> int: @@ -81,10 +75,6 @@ class Solution: return f[-1] ``` -### **Java** - - - ```java class Solution { public int maximizeTheProfit(int n, List> offers) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +131,6 @@ public: }; ``` -### **Go** - ```go func maximizeTheProfit(n int, offers [][]int) int { sort.Slice(offers, func(i, j int) bool { return offers[i][1] < offers[j][1] }) @@ -162,8 +148,6 @@ func maximizeTheProfit(n int, offers [][]int) int { } ``` -### **TypeScript** - ```ts function maximizeTheProfit(n: number, offers: number[][]): number { offers.sort((a, b) => a[1] - b[1]); @@ -191,10 +175,6 @@ function maximizeTheProfit(n: number, offers: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2830.Maximize the Profit as the Salesman/README_EN.md b/solution/2800-2899/2830.Maximize the Profit as the Salesman/README_EN.md index 4395ff381de5e..199594c0e2003 100644 --- a/solution/2800-2899/2830.Maximize the Profit as the Salesman/README_EN.md +++ b/solution/2800-2899/2830.Maximize the Profit as the Salesman/README_EN.md @@ -48,7 +48,7 @@ It can be proven that 10 is the maximum amount of gold we can achieve. ## Solutions -**Solution 1: Sorting + Binary Search + Dynamic Programming** +### Solution 1: Sorting + Binary Search + Dynamic Programming We sort all the purchase offers by $end$ in ascending order, and then use dynamic programming to solve the problem. @@ -60,8 +60,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def maximizeTheProfit(self, n: int, offers: List[List[int]]) -> int: @@ -74,8 +72,6 @@ class Solution: return f[-1] ``` -### **Java** - ```java class Solution { public int maximizeTheProfit(int n, List> offers) { @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +128,6 @@ public: }; ``` -### **Go** - ```go func maximizeTheProfit(n int, offers [][]int) int { sort.Slice(offers, func(i, j int) bool { return offers[i][1] < offers[j][1] }) @@ -153,8 +145,6 @@ func maximizeTheProfit(n int, offers [][]int) int { } ``` -### **TypeScript** - ```ts function maximizeTheProfit(n: number, offers: number[][]): number { offers.sort((a, b) => a[1] - b[1]); @@ -182,10 +172,6 @@ function maximizeTheProfit(n: number, offers: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2831.Find the Longest Equal Subarray/README.md b/solution/2800-2899/2831.Find the Longest Equal Subarray/README.md index 6c35d01202e6a..86f5ecf007c22 100644 --- a/solution/2800-2899/2831.Find the Longest Equal Subarray/README.md +++ b/solution/2800-2899/2831.Find the Longest Equal Subarray/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:哈希表 + 双指针** +### 方法一:哈希表 + 双指针 我们用双指针维护一个单调变长的窗口,用哈希表维护窗口中每个元素出现的次数。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def longestEqualSubarray(self, nums: List[int], k: int) -> int: @@ -85,10 +79,6 @@ class Solution: return mx ``` -### **Java** - - - ```java class Solution { public int longestEqualSubarray(List nums, int k) { @@ -106,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func longestEqualSubarray(nums []int, k int) int { cnt := map[int]int{} @@ -143,8 +129,6 @@ func longestEqualSubarray(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function longestEqualSubarray(nums: number[], k: number): number { const cnt: Map = new Map(); @@ -162,10 +146,6 @@ function longestEqualSubarray(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2831.Find the Longest Equal Subarray/README_EN.md b/solution/2800-2899/2831.Find the Longest Equal Subarray/README_EN.md index a9fcc5f2dae01..b2ebffb5fbac8 100644 --- a/solution/2800-2899/2831.Find the Longest Equal Subarray/README_EN.md +++ b/solution/2800-2899/2831.Find the Longest Equal Subarray/README_EN.md @@ -46,7 +46,7 @@ It can be proven that no longer equal subarrays can be created. ## Solutions -**Solution 1: Hash Table + Two Pointers** +### Solution 1: Hash Table + Two Pointers We use two pointers to maintain a monotonically variable length window, and a hash table to maintain the number of occurrences of each element in the window. @@ -60,8 +60,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def longestEqualSubarray(self, nums: List[int], k: int) -> int: @@ -77,8 +75,6 @@ class Solution: return mx ``` -### **Java** - ```java class Solution { public int longestEqualSubarray(List nums, int k) { @@ -96,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +109,6 @@ public: }; ``` -### **Go** - ```go func longestEqualSubarray(nums []int, k int) int { cnt := map[int]int{} @@ -133,8 +125,6 @@ func longestEqualSubarray(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function longestEqualSubarray(nums: number[], k: number): number { const cnt: Map = new Map(); @@ -152,10 +142,6 @@ function longestEqualSubarray(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2832.Maximal Range That Each Element Is Maximum in It/README.md b/solution/2800-2899/2832.Maximal Range That Each Element Is Maximum in It/README.md index ee29b366e0cfd..662e26af7711a 100644 --- a/solution/2800-2899/2832.Maximal Range That Each Element Is Maximum in It/README.md +++ b/solution/2800-2899/2832.Maximal Range That Each Element Is Maximum in It/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:单调栈** +### 方法一:单调栈 本题属于单调栈的模板题,我们只需要利用单调栈,求出每个元素 $nums[i]$ 左边和右边第一个比它大的元素的位置,分别记为 $left[i]$ 和 $right[i]$,那么 $nums[i]$ 作为最大值的区间长度就是 $right[i] - left[i] - 1$。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def maximumLengthOfRanges(self, nums: List[int]) -> List[int]: @@ -89,10 +83,6 @@ class Solution: return [r - l - 1 for l, r in zip(left, right)] ``` -### **Java** - - - ```java class Solution { public int[] maximumLengthOfRanges(int[] nums) { @@ -130,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -168,8 +156,6 @@ public: }; ``` -### **Go** - ```go func maximumLengthOfRanges(nums []int) []int { n := len(nums) @@ -208,8 +194,6 @@ func maximumLengthOfRanges(nums []int) []int { } ``` -### **TypeScript** - ```ts function maximumLengthOfRanges(nums: number[]): number[] { const n = nums.length; @@ -239,10 +223,6 @@ function maximumLengthOfRanges(nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2832.Maximal Range That Each Element Is Maximum in It/README_EN.md b/solution/2800-2899/2832.Maximal Range That Each Element Is Maximum in It/README_EN.md index 7a3305d5aaa12..809c8d4c49491 100644 --- a/solution/2800-2899/2832.Maximal Range That Each Element Is Maximum in It/README_EN.md +++ b/solution/2800-2899/2832.Maximal Range That Each Element Is Maximum in It/README_EN.md @@ -48,7 +48,7 @@ For nums[4] the longest subarray in which 6 is the maximum is nums[0..4] so ans[ ## Solutions -**Solution 1: Monotonic Stack** +### Solution 1: Monotonic Stack This problem is a template for monotonic stack. We only need to use the monotonic stack to find the position of the first element larger than $nums[i]$ on the left and right, denoted as $left[i]$ and $right[i]$. Then, the interval length with $nums[i]$ as the maximum value is $right[i] - left[i] - 1$. @@ -56,8 +56,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maximumLengthOfRanges(self, nums: List[int]) -> List[int]: @@ -81,8 +79,6 @@ class Solution: return [r - l - 1 for l, r in zip(left, right)] ``` -### **Java** - ```java class Solution { public int[] maximumLengthOfRanges(int[] nums) { @@ -120,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -158,8 +152,6 @@ public: }; ``` -### **Go** - ```go func maximumLengthOfRanges(nums []int) []int { n := len(nums) @@ -198,8 +190,6 @@ func maximumLengthOfRanges(nums []int) []int { } ``` -### **TypeScript** - ```ts function maximumLengthOfRanges(nums: number[]): number[] { const n = nums.length; @@ -229,10 +219,6 @@ function maximumLengthOfRanges(nums: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2833.Furthest Point From Origin/README.md b/solution/2800-2899/2833.Furthest Point From Origin/README.md index a376a4f6b7453..249ef1f87ea63 100644 --- a/solution/2800-2899/2833.Furthest Point From Origin/README.md +++ b/solution/2800-2899/2833.Furthest Point From Origin/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 遇到字符 `'_'` 时,我们可以选择向左或向右移动,而题目需要我们求出离原点最远的点,因此,我们可以先进行一次遍历,贪心地把所有的 `'_'` 都移到左边,求出此时离原点最远的点,再进行一次遍历,贪心地把所有的 `'_'` 都移到右边,求出此时离原点最远的点,最后取两次遍历中的最大值即可。 @@ -66,20 +64,12 @@ -### **Python3** - - - ```python class Solution: def furthestDistanceFromOrigin(self, moves: str) -> int: return abs(moves.count("L") - moves.count("R")) + moves.count("_") ``` -### **Java** - - - ```java class Solution { public int furthestDistanceFromOrigin(String moves) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +100,6 @@ public: }; ``` -### **Go** - ```go func furthestDistanceFromOrigin(moves string) int { count := func(c string) int { return strings.Count(moves, c) } @@ -128,8 +114,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function furthestDistanceFromOrigin(moves: string): number { const count = (c: string) => moves.split('').filter(x => x === c).length; @@ -137,10 +121,6 @@ function furthestDistanceFromOrigin(moves: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2833.Furthest Point From Origin/README_EN.md b/solution/2800-2899/2833.Furthest Point From Origin/README_EN.md index 8dd54856f12ef..fb259deafa669 100644 --- a/solution/2800-2899/2833.Furthest Point From Origin/README_EN.md +++ b/solution/2800-2899/2833.Furthest Point From Origin/README_EN.md @@ -50,7 +50,7 @@ ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy When encountering the character '_', we can choose to move left or right. The problem requires us to find the farthest point from the origin. Therefore, we can first traverse once, greedily move all '_' to the left, and find the farthest point from the origin at this time. Then traverse again, greedily move all '\_' to the right, and find the farthest point from the origin at this time. Finally, take the maximum of the two traversals. @@ -60,16 +60,12 @@ The time complexity is $O(n)$, where $n$ is the length of the string. The space -### **Python3** - ```python class Solution: def furthestDistanceFromOrigin(self, moves: str) -> int: return abs(moves.count("L") - moves.count("R")) + moves.count("_") ``` -### **Java** - ```java class Solution { public int furthestDistanceFromOrigin(String moves) { @@ -88,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +96,6 @@ public: }; ``` -### **Go** - ```go func furthestDistanceFromOrigin(moves string) int { count := func(c string) int { return strings.Count(moves, c) } @@ -118,8 +110,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function furthestDistanceFromOrigin(moves: string): number { const count = (c: string) => moves.split('').filter(x => x === c).length; @@ -127,10 +117,6 @@ function furthestDistanceFromOrigin(moves: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/README.md b/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/README.md index a6ebbc69703b7..f1a9b9b9afc2e 100644 --- a/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/README.md +++ b/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/README.md @@ -62,9 +62,7 @@ nums = [1,3,4] 是美丽数组。 ## 解法 - - -**方法一:贪心 + 哈希表** +### 方法一:贪心 + 哈希表 我们从正整数 $i=1$ 开始,依次判断 $i$ 是否可以加入数组中,如果可以加入,则将 $i$ 加入数组中,累加到答案中,然后将 $target-i$ 置为已访问,表示 $target-i$ 不能加入数组中。循环直到数组长度为 $n$。 @@ -72,10 +70,6 @@ nums = [1,3,4] 是美丽数组。 -### **Python3** - - - ```python class Solution: def minimumPossibleSum(self, n: int, target: int) -> int: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long minimumPossibleSum(int n, int target) { @@ -114,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +125,6 @@ public: }; ``` -### **Go** - ```go func minimumPossibleSum(n int, target int) (ans int64) { vis := make([]bool, n+target) @@ -155,8 +141,6 @@ func minimumPossibleSum(n int, target int) (ans int64) { } ``` -### **TypeScript** - ```ts function minimumPossibleSum(n: number, target: number): number { const vis: boolean[] = Array(n + target).fill(false); @@ -174,10 +158,6 @@ function minimumPossibleSum(n: number, target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/README_EN.md b/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/README_EN.md index 79c5c7947dee1..85441c5466bc7 100644 --- a/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/README_EN.md +++ b/solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/README_EN.md @@ -59,7 +59,7 @@ It can be proven that 8 is the minimum possible sum that a beautiful array could ## Solutions -**Solution 1: Greedy + Hash Table** +### Solution 1: Greedy + Hash Table We start from the positive integer $i=1$, and judge whether $i$ can be added to the array in turn. If it can be added, we add $i$ to the array, accumulate it to the answer, and then mark $target-i$ as visited, indicating that $target-i$ cannot be added to the array. The loop continues until the length of the array is $n$. @@ -67,8 +67,6 @@ The time complexity is $O(n + target)$, and the space complexity is $O(n + targe -### **Python3** - ```python class Solution: def minimumPossibleSum(self, n: int, target: int) -> int: @@ -84,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long minimumPossibleSum(int n, int target) { @@ -105,8 +101,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +122,6 @@ public: }; ``` -### **Go** - ```go func minimumPossibleSum(n int, target int) (ans int64) { vis := make([]bool, n+target) @@ -146,8 +138,6 @@ func minimumPossibleSum(n int, target int) (ans int64) { } ``` -### **TypeScript** - ```ts function minimumPossibleSum(n: number, target: number): number { const vis: boolean[] = Array(n + target).fill(false); @@ -165,10 +155,6 @@ function minimumPossibleSum(n: number, target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/README.md b/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/README.md index 580c81fb45e38..08ff9084aaf35 100644 --- a/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/README.md +++ b/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:贪心 + 位运算** +### 方法一:贪心 + 位运算 观察题目中的操作,我们发现,每次操作实际上是把一个大于 $1$ 的数拆分为两个相等的数,这意味着操作后数组的元素和不会发生变化。因此,如果数组的元素和 $s$ 小于 $target$,则无法通过题目描述的操作得到和为 $target$ 的子序列,直接返回 $-1$ 即可。否则,我们一定可以通过拆分操作,使得数组某个子序列的元素和等于 $target$。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, nums: List[int], target: int) -> int: @@ -115,10 +109,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minOperations(List nums, int target) { @@ -162,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -208,8 +196,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int, target int) (ans int) { s := 0 @@ -250,8 +236,6 @@ func minOperations(nums []int, target int) (ans int) { } ``` -### **TypeScript** - ```ts function minOperations(nums: number[], target: number): number { let s = 0; @@ -292,10 +276,6 @@ function minOperations(nums: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/README_EN.md b/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/README_EN.md index 406d4d6849c31..616cf95edf8c3 100644 --- a/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/README_EN.md +++ b/solution/2800-2899/2835.Minimum Operations to Form Subsequence With Target Sum/README_EN.md @@ -59,7 +59,7 @@ It can be shown that there is no shorter sequence of operations that results in ## Solutions -**Solution 1: Greedy + Bit Manipulation** +### Solution 1: Greedy + Bit Manipulation Observing the operation in the problem, we find that each operation actually splits a number greater than $1$ into two equal numbers, which means that the sum of the elements in the array will not change after the operation. Therefore, if the sum of the elements in the array $s$ is less than $target$, it is impossible to obtain a subsequence with a sum of $target$ through the operation described in the problem, and we can directly return $-1$. Otherwise, we can definitely make the sum of some subsequences in the array equal to $target$ through the split operation. @@ -73,8 +73,6 @@ The time complexity is $O(n \times \log M)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def minOperations(self, nums: List[int], target: int) -> int: @@ -107,8 +105,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minOperations(List nums, int target) { @@ -152,8 +148,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -198,8 +192,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int, target int) (ans int) { s := 0 @@ -240,8 +232,6 @@ func minOperations(nums []int, target int) (ans int) { } ``` -### **TypeScript** - ```ts function minOperations(nums: number[], target: number): number { let s = 0; @@ -282,10 +272,6 @@ function minOperations(nums: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/README.md b/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/README.md index 383e9ceb18467..57fbb31d7c427 100644 --- a/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/README.md +++ b/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/README.md @@ -136,9 +136,7 @@ ## 解法 - - -**方法一:动态规划 + 倍增** +### 方法一:动态规划 + 倍增 题目要我们寻找从每个玩家 $i$ 开始,传球 $k$ 次内所有接触过球玩家的编号之和的最大值。如果暴力求解,需要从 $i$ 开始向上遍历 $k$ 次,时间复杂度为 $O(k)$,显然会超时。 @@ -160,10 +158,6 @@ -### **Python3** - - - ```python class Solution: def getMaxFunctionValue(self, receiver: List[int], k: int) -> int: @@ -188,10 +182,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long getMaxFunctionValue(List receiver, long k) { @@ -225,8 +215,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -261,8 +249,6 @@ public: }; ``` -### **Go** - ```go func getMaxFunctionValue(receiver []int, k int64) (ans int64) { n, m := len(receiver), bits.Len(uint(k)) @@ -295,10 +281,6 @@ func getMaxFunctionValue(receiver []int, k int64) (ans int64) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/README_EN.md b/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/README_EN.md index f422348324d54..ec44f7d127e97 100644 --- a/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/README_EN.md +++ b/solution/2800-2899/2836.Maximize Value of Function in a Ball Passing Game/README_EN.md @@ -128,7 +128,7 @@ Hence, the output is 10. ## Solutions -**Solution 1: Dynamic Programming + Binary Lifting** +### Solution 1: Dynamic Programming + Binary Lifting The problem asks us to find the maximum sum of the player IDs who have touched the ball within $k$ passes starting from each player $i$. If we solve it by brute force, we need to traverse upwards $k$ times starting from $i$, with a time complexity of $O(k)$, which will obviously time out. @@ -150,8 +150,6 @@ Similar problems: -### **Python3** - ```python class Solution: def getMaxFunctionValue(self, receiver: List[int], k: int) -> int: @@ -176,8 +174,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long getMaxFunctionValue(List receiver, long k) { @@ -211,8 +207,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -247,8 +241,6 @@ public: }; ``` -### **Go** - ```go func getMaxFunctionValue(receiver []int, k int64) (ans int64) { n, m := len(receiver), bits.Len(uint(k)) @@ -281,10 +273,6 @@ func getMaxFunctionValue(receiver []int, k int64) (ans int64) { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2837.Total Traveled Distance/README.md b/solution/2800-2899/2837.Total Traveled Distance/README.md index 8467aa8068c36..d7457edc278ba 100644 --- a/solution/2800-2899/2837.Total Traveled Distance/README.md +++ b/solution/2800-2899/2837.Total Traveled Distance/README.md @@ -87,18 +87,12 @@ Rides table: ## 解法 - - -**方法一:左连接 + 分组求和** +### 方法一:左连接 + 分组求和 我们可以使用左连接将两张表连接起来,然后使用分组求和的方式计算每个用户的总距离。注意,如果用户没有完成任何骑行,那么他的距离应该被视为 $0$。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT user_id, name, IFNULL(SUM(distance), 0) AS 'traveled distance' @@ -110,3 +104,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2800-2899/2837.Total Traveled Distance/README_EN.md b/solution/2800-2899/2837.Total Traveled Distance/README_EN.md index 4a70abd253108..f41ed50a11418 100644 --- a/solution/2800-2899/2837.Total Traveled Distance/README_EN.md +++ b/solution/2800-2899/2837.Total Traveled Distance/README_EN.md @@ -84,14 +84,12 @@ Returning the table orderd by user_id in ascending order. ## Solutions -**Solution 1: Left Join + Group By Sum** +### Solution 1: Left Join + Group By Sum We can use a left join to connect the two tables, and then use group by sum to calculate the total distance for each user. Note that if a user has not completed any rides, their distance should be considered as $0$. -### **SQL** - ```sql # Write your MySQL query statement below SELECT user_id, name, IFNULL(SUM(distance), 0) AS 'traveled distance' @@ -103,3 +101,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2800-2899/2838.Maximum Coins Heroes Can Collect/README.md b/solution/2800-2899/2838.Maximum Coins Heroes Can Collect/README.md index 40536e526f571..d07428d744524 100644 --- a/solution/2800-2899/2838.Maximum Coins Heroes Can Collect/README.md +++ b/solution/2800-2899/2838.Maximum Coins Heroes Can Collect/README.md @@ -61,9 +61,7 @@ So the answer would be [5,16,10]. ## 解法 - - -**方法一:排序 + 前缀和 + 二分查找** +### 方法一:排序 + 前缀和 + 二分查找 我们可以将怪物和金币按照怪物的战斗力从小到大排序,然后使用前缀和计算每个英雄打败前 $i$ 个怪物可以获得的金币总数。 @@ -73,10 +71,6 @@ So the answer would be [5,16,10]. -### **Python3** - - - ```python class Solution: def maximumCoins( @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long[] maximumCoins(int[] heroes, int[] monsters, int[] coins) { @@ -134,8 +124,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -172,8 +160,6 @@ public: }; ``` -### **Go** - ```go func maximumCoins(heroes []int, monsters []int, coins []int) (ans []int64) { m := len(monsters) @@ -194,8 +180,6 @@ func maximumCoins(heroes []int, monsters []int, coins []int) (ans []int64) { } ``` -### **TypeScript** - ```ts function maximumCoins(heroes: number[], monsters: number[], coins: number[]): number[] { const m = monsters.length; @@ -222,10 +206,6 @@ function maximumCoins(heroes: number[], monsters: number[], coins: number[]): nu } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2838.Maximum Coins Heroes Can Collect/README_EN.md b/solution/2800-2899/2838.Maximum Coins Heroes Can Collect/README_EN.md index 403b13a48db85..5bc8c0eb8292b 100644 --- a/solution/2800-2899/2838.Maximum Coins Heroes Can Collect/README_EN.md +++ b/solution/2800-2899/2838.Maximum Coins Heroes Can Collect/README_EN.md @@ -59,7 +59,7 @@ So the answer would be [5,16,10]. ## Solutions -**Solution 1: Sorting + Prefix Sum + Binary Search** +### Solution 1: Sorting + Prefix Sum + Binary Search We can sort the monsters and coins in ascending order of the monsters' combat power, and then use prefix sum to calculate the total number of coins each hero can get by defeating the first $i$ monsters. @@ -69,8 +69,6 @@ The time complexity is $O((m + n) \times \log n)$, and the space complexity is $ -### **Python3** - ```python class Solution: def maximumCoins( @@ -86,8 +84,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long[] maximumCoins(int[] heroes, int[] monsters, int[] coins) { @@ -126,8 +122,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -164,8 +158,6 @@ public: }; ``` -### **Go** - ```go func maximumCoins(heroes []int, monsters []int, coins []int) (ans []int64) { m := len(monsters) @@ -186,8 +178,6 @@ func maximumCoins(heroes []int, monsters []int, coins []int) (ans []int64) { } ``` -### **TypeScript** - ```ts function maximumCoins(heroes: number[], monsters: number[], coins: number[]): number[] { const m = monsters.length; @@ -214,10 +204,6 @@ function maximumCoins(heroes: number[], monsters: number[], coins: number[]): nu } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/README.md b/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/README.md index 1f8a4bbc5f97e..4390ca5e41a49 100644 --- a/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/README.md +++ b/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/README.md @@ -47,9 +47,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们观察题目中的操作,可以发现,如果字符串的两个下标 $i$ 和 $j$ 的奇偶性相同,那么它们可以通过交换改变顺序。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def canBeEqual(self, s1: str, s2: str) -> bool: @@ -75,10 +69,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public boolean canBeEqual(String s1, String s2) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func canBeEqual(s1 string, s2 string) bool { cnt := [2][26]int{} @@ -136,8 +122,6 @@ func canBeEqual(s1 string, s2 string) bool { } ``` -### **TypeScript** - ```ts function canBeEqual(s1: string, s2: string): boolean { const cnt: number[][] = Array.from({ length: 2 }, () => Array.from({ length: 26 }, () => 0)); @@ -154,10 +138,6 @@ function canBeEqual(s1: string, s2: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/README_EN.md b/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/README_EN.md index 257832f40d099..205c1b8fd5bd7 100644 --- a/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/README_EN.md +++ b/solution/2800-2899/2839.Check if Strings Can be Made Equal With Operations I/README_EN.md @@ -43,7 +43,7 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We observe the operation in the problem, and find that if the parity of the two indices $i$ and $j$ of the string is the same, then their order can be changed by swapping. @@ -57,8 +57,6 @@ Similar problems: -### **Python3** - ```python class Solution: def canBeEqual(self, s1: str, s2: str) -> bool: @@ -67,8 +65,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public boolean canBeEqual(String s1, String s2) { @@ -87,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +102,6 @@ public: }; ``` -### **Go** - ```go func canBeEqual(s1 string, s2 string) bool { cnt := [2][26]int{} @@ -126,8 +118,6 @@ func canBeEqual(s1 string, s2 string) bool { } ``` -### **TypeScript** - ```ts function canBeEqual(s1: string, s2: string): boolean { const cnt: number[][] = Array.from({ length: 2 }, () => Array.from({ length: 26 }, () => 0)); @@ -144,10 +134,6 @@ function canBeEqual(s1: string, s2: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/README.md b/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/README.md index 41ad0711cf091..84bb42b9db4a3 100644 --- a/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/README.md +++ b/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们观察题目中的操作,可以发现,如果字符串的两个下标 $i$ 和 $j$ 的奇偶性相同,那么它们可以通过交换改变顺序。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def checkStrings(self, s1: str, s2: str) -> bool: @@ -81,10 +75,6 @@ class Solution: ) ``` -### **Java** - - - ```java class Solution { public boolean checkStrings(String s1, String s2) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func checkStrings(s1 string, s2 string) bool { cnt := [2][26]int{} @@ -142,8 +128,6 @@ func checkStrings(s1 string, s2 string) bool { } ``` -### **TypeScript** - ```ts function checkStrings(s1: string, s2: string): boolean { const cnt: number[][] = Array.from({ length: 2 }, () => Array.from({ length: 26 }, () => 0)); @@ -160,10 +144,6 @@ function checkStrings(s1: string, s2: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/README_EN.md b/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/README_EN.md index 23bf55cb0f386..7270df9b82403 100644 --- a/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/README_EN.md +++ b/solution/2800-2899/2840.Check if Strings Can be Made Equal With Operations II/README_EN.md @@ -45,7 +45,7 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We observe the operation in the problem, and find that if the parity of the two indices $i$ and $j$ of the string is the same, then their order can be changed by swapping. @@ -59,8 +59,6 @@ Similar problems: -### **Python3** - ```python class Solution: def checkStrings(self, s1: str, s2: str) -> bool: @@ -69,8 +67,6 @@ class Solution: ) ``` -### **Java** - ```java class Solution { public boolean checkStrings(String s1, String s2) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func checkStrings(s1 string, s2 string) bool { cnt := [2][26]int{} @@ -128,8 +120,6 @@ func checkStrings(s1 string, s2 string) bool { } ``` -### **TypeScript** - ```ts function checkStrings(s1: string, s2: string): boolean { const cnt: number[][] = Array.from({ length: 2 }, () => Array.from({ length: 26 }, () => 0)); @@ -146,10 +136,6 @@ function checkStrings(s1: string, s2: string): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/README.md b/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/README.md index 64b99f006ed7f..a75d06b306d6e 100644 --- a/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/README.md +++ b/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:滑动窗口 + 哈希表** +### 方法一:滑动窗口 + 哈希表 我们可以遍历数组 $nums$,维护一个大小为 $k$ 的窗口,用哈希表 $cnt$ 统计窗口中每个元素的出现次数,用变量 $s$ 统计窗口中所有元素的和。如果 $cnt$ 中不同元素的个数大于等于 $m$,那么我们就更新答案 $ans = \max(ans, s)$。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def maxSum(self, nums: List[int], m: int, k: int) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long maxSum(List nums, int m, int k) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +137,6 @@ public: }; ``` -### **Go** - ```go func maxSum(nums []int, m int, k int) int64 { cnt := map[int]int{} @@ -178,8 +164,6 @@ func maxSum(nums []int, m int, k int) int64 { } ``` -### **TypeScript** - ```ts function maxSum(nums: number[], m: number, k: number): number { const n = nums.length; @@ -205,10 +189,6 @@ function maxSum(nums: number[], m: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/README_EN.md b/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/README_EN.md index 90ab6eb984840..55436671ec3c3 100644 --- a/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/README_EN.md +++ b/solution/2800-2899/2841.Maximum Sum of Almost Unique Subarray/README_EN.md @@ -48,7 +48,7 @@ ## Solutions -**Solution 1: Sliding Window + Hash Table** +### Solution 1: Sliding Window + Hash Table We can traverse the array $nums$, maintain a window of size $k$, use a hash table $cnt$ to count the occurrence of each element in the window, and use a variable $s$ to sum all elements in the window. If the number of different elements in $cnt$ is greater than or equal to $m$, then we update the answer $ans = \max(ans, s)$. @@ -58,8 +58,6 @@ The time complexity is $O(n)$, and the space complexity is $O(k)$. Here, $n$ is -### **Python3** - ```python class Solution: def maxSum(self, nums: List[int], m: int, k: int) -> int: @@ -79,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long maxSum(List nums, int m, int k) { @@ -110,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +133,6 @@ public: }; ``` -### **Go** - ```go func maxSum(nums []int, m int, k int) int64 { cnt := map[int]int{} @@ -168,8 +160,6 @@ func maxSum(nums []int, m int, k int) int64 { } ``` -### **TypeScript** - ```ts function maxSum(nums: number[], m: number, k: number): number { const n = nums.length; @@ -195,10 +185,6 @@ function maxSum(nums: number[], m: number, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/README.md b/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/README.md index 41b3597a4b693..b6008bc0a63e1 100644 --- a/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/README.md +++ b/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/README.md @@ -81,9 +81,7 @@ s 的 k 子序列为: ## 解法 - - -**方法一:贪心 + 组合数学** +### 方法一:贪心 + 组合数学 我们先用哈希表 $f$ 统计字符串 $s$ 中每个字符的出现次数,即 $f[c]$ 表示字符 $c$ 在字符串 $s$ 中出现的次数。 @@ -101,10 +99,6 @@ s 的 k 子序列为: -### **Python3** - - - ```python class Solution: def countKSubsequencesWithMaxBeauty(self, s: str, k: int) -> int: @@ -125,10 +119,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -191,8 +181,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -252,8 +240,6 @@ public: }; ``` -### **Go** - ```go func countKSubsequencesWithMaxBeauty(s string, k int) int { f := [26]int{} @@ -315,8 +301,6 @@ func countKSubsequencesWithMaxBeauty(s string, k int) int { } ``` -### **TypeScript** - ```ts function countKSubsequencesWithMaxBeauty(s: string, k: number): number { const f: number[] = new Array(26).fill(0); @@ -364,10 +348,6 @@ function countKSubsequencesWithMaxBeauty(s: string, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/README_EN.md b/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/README_EN.md index 26870eba16872..1f3bf5aacb79b 100644 --- a/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/README_EN.md +++ b/solution/2800-2899/2842.Count K-Subsequences of a String With Maximum Beauty/README_EN.md @@ -77,7 +77,7 @@ Hence, the answer is 2. ## Solutions -**Solution 1: Greedy + Combinatorial Mathematics** +### Solution 1: Greedy + Combinatorial Mathematics First, we use a hash table $f$ to count the occurrence of each character in the string $s$, i.e., $f[c]$ represents the number of times character $c$ appears in the string $s$. @@ -95,8 +95,6 @@ The time complexity is $O(n)$, and the space complexity is $O(|\Sigma|)$. Here, -### **Python3** - ```python class Solution: def countKSubsequencesWithMaxBeauty(self, s: str, k: int) -> int: @@ -117,8 +115,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -181,8 +177,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -242,8 +236,6 @@ public: }; ``` -### **Go** - ```go func countKSubsequencesWithMaxBeauty(s string, k int) int { f := [26]int{} @@ -305,8 +297,6 @@ func countKSubsequencesWithMaxBeauty(s string, k int) int { } ``` -### **TypeScript** - ```ts function countKSubsequencesWithMaxBeauty(s: string, k: number): number { const f: number[] = new Array(26).fill(0); @@ -354,10 +344,6 @@ function countKSubsequencesWithMaxBeauty(s: string, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2843.Count Symmetric Integers/README.md b/solution/2800-2899/2843.Count Symmetric Integers/README.md index b728385b2c366..feefc0594c94e 100644 --- a/solution/2800-2899/2843.Count Symmetric Integers/README.md +++ b/solution/2800-2899/2843.Count Symmetric Integers/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们枚举 $[low, high]$ 中的每个整数 $x$,判断其是否是对称整数。如果是,那么答案 $ans$ 增加 $1$。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python class Solution: def countSymmetricIntegers(self, low: int, high: int) -> int: @@ -67,10 +61,6 @@ class Solution: return sum(f(x) for x in range(low, high + 1)) ``` -### **Java** - - - ```java class Solution { public int countSymmetricIntegers(int low, int high) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func countSymmetricIntegers(low int, high int) (ans int) { f := func(x int) int { @@ -154,8 +140,6 @@ func countSymmetricIntegers(low int, high int) (ans int) { } ``` -### **TypeScript** - ```ts function countSymmetricIntegers(low: number, high: number): number { let ans = 0; @@ -180,10 +164,6 @@ function countSymmetricIntegers(low: number, high: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2843.Count Symmetric Integers/README_EN.md b/solution/2800-2899/2843.Count Symmetric Integers/README_EN.md index 9cf9eebc9fdca..34962dbd25472 100644 --- a/solution/2800-2899/2843.Count Symmetric Integers/README_EN.md +++ b/solution/2800-2899/2843.Count Symmetric Integers/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We enumerate each integer $x$ in the range $[low, high]$, and check whether it is a palindromic number. If it is, then the answer $ans$ is increased by $1$. @@ -44,8 +44,6 @@ The time complexity is $O(n \times \log m)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def countSymmetricIntegers(self, low: int, high: int) -> int: @@ -59,8 +57,6 @@ class Solution: return sum(f(x) for x in range(low, high + 1)) ``` -### **Java** - ```java class Solution { public int countSymmetricIntegers(int low, int high) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func countSymmetricIntegers(low int, high int) (ans int) { f := func(x int) int { @@ -144,8 +136,6 @@ func countSymmetricIntegers(low int, high int) (ans int) { } ``` -### **TypeScript** - ```ts function countSymmetricIntegers(low: number, high: number): number { let ans = 0; @@ -170,10 +160,6 @@ function countSymmetricIntegers(low: number, high: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2844.Minimum Operations to Make a Special Number/README.md b/solution/2800-2899/2844.Minimum Operations to Make a Special Number/README.md index cd2279cc48f1d..e0da0ea18b7c2 100644 --- a/solution/2800-2899/2844.Minimum Operations to Make a Special Number/README.md +++ b/solution/2800-2899/2844.Minimum Operations to Make a Special Number/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们注意到,整数 $x$ 要能被 $25$ 整除,即 $x \bmod 25 = 0$。因此,我们可以设计一个函数 $dfs(i, k)$,表示从字符串 $num$ 的第 $i$ 位开始,且当前数字模 $25$ 的结果为 $k$ 的情况下,要使得数字变成特殊数字,最少需要删除多少位数字。那么答案为 $dfs(0, 0)$。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def minimumOperations(self, num: str) -> int: @@ -91,10 +85,6 @@ class Solution: return dfs(0, 0) ``` -### **Java** - - - ```java class Solution { private Integer[][] f; @@ -122,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +135,6 @@ public: }; ``` -### **Go** - ```go func minimumOperations(num string) int { n := len(num) @@ -177,8 +163,6 @@ func minimumOperations(num string) int { } ``` -### **TypeScript** - ```ts function minimumOperations(num: string): number { const n = num.length; @@ -198,10 +182,6 @@ function minimumOperations(num: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2844.Minimum Operations to Make a Special Number/README_EN.md b/solution/2800-2899/2844.Minimum Operations to Make a Special Number/README_EN.md index f620ba9de033d..1f16df988383c 100644 --- a/solution/2800-2899/2844.Minimum Operations to Make a Special Number/README_EN.md +++ b/solution/2800-2899/2844.Minimum Operations to Make a Special Number/README_EN.md @@ -50,7 +50,7 @@ It can be shown that 1 is the minimum number of operations required to get a spe ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search We notice that an integer $x$ can be divisible by $25$, i.e., $x \bmod 25 = 0$. Therefore, we can design a function $dfs(i, k)$, which represents the minimum number of digits to be deleted to make the number a special number, starting from the $i$th digit of the string $num$, and the current number modulo $25$ is $k$. The answer is $dfs(0, 0)$. @@ -65,8 +65,6 @@ The time complexity is $O(n \times 25)$, and the space complexity is $O(n \times -### **Python3** - ```python class Solution: def minimumOperations(self, num: str) -> int: @@ -82,8 +80,6 @@ class Solution: return dfs(0, 0) ``` -### **Java** - ```java class Solution { private Integer[][] f; @@ -111,8 +107,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +130,6 @@ public: }; ``` -### **Go** - ```go func minimumOperations(num string) int { n := len(num) @@ -166,8 +158,6 @@ func minimumOperations(num string) int { } ``` -### **TypeScript** - ```ts function minimumOperations(num: string): number { const n = num.length; @@ -187,10 +177,6 @@ function minimumOperations(num: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2845.Count of Interesting Subarrays/README.md b/solution/2800-2899/2845.Count of Interesting Subarrays/README.md index 6a63cb3545829..444c3309e1672 100644 --- a/solution/2800-2899/2845.Count of Interesting Subarrays/README.md +++ b/solution/2800-2899/2845.Count of Interesting Subarrays/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:哈希表 + 前缀和** +### 方法一:哈希表 + 前缀和 题目要求一个区间内满足 $nums[i] \bmod modulo = k$ 的索引 $i$ 的数量,我们可以将数组 $nums$ 转换为一个 $0-1$ 数组 $arr$,其中 $arr[i] = 1$ 表示 $nums[i] \bmod modulo = k$,否则 $arr[i] = 0$。 @@ -84,10 +82,6 @@ -### **Python3** - - - ```python class Solution: def countInterestingSubarrays(self, nums: List[int], modulo: int, k: int) -> int: @@ -102,10 +96,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long countInterestingSubarrays(List nums, int modulo, int k) { @@ -128,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func countInterestingSubarrays(nums []int, modulo int, k int) (ans int64) { arr := make([]int, len(nums)) @@ -175,8 +161,6 @@ func countInterestingSubarrays(nums []int, modulo int, k int) (ans int64) { } ``` -### **TypeScript** - ```ts function countInterestingSubarrays(nums: number[], modulo: number, k: number): number { const arr: number[] = []; @@ -196,10 +180,6 @@ function countInterestingSubarrays(nums: number[], modulo: number, k: number): n } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2845.Count of Interesting Subarrays/README_EN.md b/solution/2800-2899/2845.Count of Interesting Subarrays/README_EN.md index fb4b1fa15a026..a781422cf157a 100644 --- a/solution/2800-2899/2845.Count of Interesting Subarrays/README_EN.md +++ b/solution/2800-2899/2845.Count of Interesting Subarrays/README_EN.md @@ -62,7 +62,7 @@ It can be shown that there are no other interesting subarrays. So, the answer is ## Solutions -**Solution 1: Hash Table + Prefix Sum** +### Solution 1: Hash Table + Prefix Sum The problem requires the number of indices $i$ in an interval that satisfy $nums[i] \bmod modulo = k$. We can transform the array $nums$ into a $0-1$ array $arr$, where $arr[i] = 1$ indicates $nums[i] \bmod modulo = k$, otherwise $arr[i] = 0$. @@ -78,8 +78,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def countInterestingSubarrays(self, nums: List[int], modulo: int, k: int) -> int: @@ -94,8 +92,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long countInterestingSubarrays(List nums, int modulo, int k) { @@ -118,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +137,6 @@ public: }; ``` -### **Go** - ```go func countInterestingSubarrays(nums []int, modulo int, k int) (ans int64) { arr := make([]int, len(nums)) @@ -165,8 +157,6 @@ func countInterestingSubarrays(nums []int, modulo int, k int) (ans int64) { } ``` -### **TypeScript** - ```ts function countInterestingSubarrays(nums: number[], modulo: number, k: number): number { const arr: number[] = []; @@ -186,10 +176,6 @@ function countInterestingSubarrays(nums: number[], modulo: number, k: number): n } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/README.md b/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/README.md index 0a65c4c99dffd..16208425de8cb 100644 --- a/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/README.md +++ b/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:倍增法求 LCA** +### 方法一:倍增法求 LCA 题目求的是任意两点的路径上,将其所有边的权重变成相同值的最小操作次数。实际上就是求这两点之间的路径长度,减去路径上出现次数最多的边的次数。 @@ -87,10 +85,6 @@ -### **Python3** - - - ```python class Solution: def minOperationsQueries( @@ -137,10 +131,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) { @@ -211,8 +201,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -283,8 +271,6 @@ public: }; ``` -### **Go** - ```go func minOperationsQueries(n int, edges [][]int, queries [][]int) []int { m := bits.Len(uint(n)) @@ -354,10 +340,6 @@ func minOperationsQueries(n int, edges [][]int, queries [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/README_EN.md b/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/README_EN.md index 64d3dcb2ee4f7..a605fd09d5be2 100644 --- a/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/README_EN.md +++ b/solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/README_EN.md @@ -59,7 +59,7 @@ For each queries[i], it can be shown that answer[i] is the minimum number of ope ## Solutions -**Solution 1: Binary Lifting for LCA** +### Solution 1: Binary Lifting for LCA The problem asks for the minimum number of operations to make all edge weights the same on the path between any two points. This is essentially the length of the path between these two points, minus the number of times the most frequently occurring edge appears on the path. @@ -81,8 +81,6 @@ The time complexity is $O((n + q) \times C \times \log n)$, and the space comple -### **Python3** - ```python class Solution: def minOperationsQueries( @@ -129,8 +127,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) { @@ -201,8 +197,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -273,8 +267,6 @@ public: }; ``` -### **Go** - ```go func minOperationsQueries(n int, edges [][]int, queries [][]int) []int { m := bits.Len(uint(n)) @@ -344,10 +336,6 @@ func minOperationsQueries(n int, edges [][]int, queries [][]int) []int { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2847.Smallest Number With Given Digit Product/README.md b/solution/2800-2899/2847.Smallest Number With Given Digit Product/README.md index 9e510d31cc437..fee56cebd9766 100644 --- a/solution/2800-2899/2847.Smallest Number With Given Digit Product/README.md +++ b/solution/2800-2899/2847.Smallest Number With Given Digit Product/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:质因数分解 + 贪心** +### 方法一:质因数分解 + 贪心 我们考虑对数字 $n$ 进行质因数分解,如果 $n$ 的质因数中存在大于 $9$ 的质数,那么一定无法找到符合条件的数字,因为大于 $9$ 的质数无法通过 $1$ 到 $9$ 的数字相乘得到,例如 $11$ 无法通过 $1$ 到 $9$ 的数字相乘得到,因此我们只需要考虑 $n$ 的质因数中是否存在大于 $9$ 的质数即可,如果存在,直接返回 $-1$。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def smallestNumber(self, n: int) -> str: @@ -74,10 +68,6 @@ class Solution: return ans if ans else "1" ``` -### **Java** - - - ```java class Solution { public String smallestNumber(long n) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func smallestNumber(n int64) string { cnt := [10]int{} @@ -157,10 +143,6 @@ func smallestNumber(n int64) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2847.Smallest Number With Given Digit Product/README_EN.md b/solution/2800-2899/2847.Smallest Number With Given Digit Product/README_EN.md index 29cba468cd342..98e7dfbb1dfb7 100644 --- a/solution/2800-2899/2847.Smallest Number With Given Digit Product/README_EN.md +++ b/solution/2800-2899/2847.Smallest Number With Given Digit Product/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Prime Factorization + Greedy** +### Solution 1: Prime Factorization + Greedy We consider prime factorizing the number $n$. If there are prime factors greater than $9$ in $n$, then it is impossible to find a number that meets the conditions, because prime factors greater than $9$ cannot be obtained by multiplying numbers from $1$ to $9$. For example, $11$ cannot be obtained by multiplying numbers from $1$ to $9$. Therefore, we only need to consider whether there are prime factors greater than $9$ in $n$. If there are, return $-1$ directly. @@ -50,8 +50,6 @@ The time complexity is $O(\log n)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def smallestNumber(self, n: int) -> str: @@ -66,8 +64,6 @@ class Solution: return ans if ans else "1" ``` -### **Java** - ```java class Solution { public String smallestNumber(long n) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +113,6 @@ public: }; ``` -### **Go** - ```go func smallestNumber(n int64) string { cnt := [10]int{} @@ -147,10 +139,6 @@ func smallestNumber(n int64) string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2848.Points That Intersect With Cars/README.md b/solution/2800-2899/2848.Points That Intersect With Cars/README.md index 0af01871a27d2..24e232e3c8f3d 100644 --- a/solution/2800-2899/2848.Points That Intersect With Cars/README.md +++ b/solution/2800-2899/2848.Points That Intersect With Cars/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:差分数组** +### 方法一:差分数组 我们创建一个长度为 $110$ 的差分数组 $d$,然后遍历给定的数组,对于每个区间 $[a, b]$,我们令 $d[a]$ 增加 $1$,$d[b + 1]$ 减少 $1$。最后我们遍历差分数组 $d$,求每个位置的前缀和 $s$,如果 $s > 0$,则说明该位置被覆盖,我们将答案增加 $1$。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python class Solution: def numberOfPoints(self, nums: List[List[int]]) -> int: @@ -64,10 +58,6 @@ class Solution: return sum(s > 0 for s in accumulate(d)) ``` -### **Java** - - - ```java class Solution { public int numberOfPoints(List> nums) { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +97,6 @@ public: }; ``` -### **Go** - ```go func numberOfPoints(nums [][]int) (ans int) { d := [110]int{} @@ -129,8 +115,6 @@ func numberOfPoints(nums [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfPoints(nums: number[][]): number { const d: number[] = Array(110).fill(0); @@ -150,10 +134,6 @@ function numberOfPoints(nums: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2848.Points That Intersect With Cars/README_EN.md b/solution/2800-2899/2848.Points That Intersect With Cars/README_EN.md index 17ab5b4798ae5..a147bb5701c1f 100644 --- a/solution/2800-2899/2848.Points That Intersect With Cars/README_EN.md +++ b/solution/2800-2899/2848.Points That Intersect With Cars/README_EN.md @@ -36,7 +36,7 @@ ## Solutions -**Solution 1: Difference Array** +### Solution 1: Difference Array We create a difference array $d$ of length $110$, then traverse the given array. For each interval $[a, b]$, we increase $d[a]$ by $1$ and decrease $d[b + 1]$ by $1$. Finally, we traverse the difference array $d$, calculate the prefix sum $s$ at each position. If $s > 0$, it means that the position is covered, and we increase the answer by $1$. @@ -44,8 +44,6 @@ The time complexity is $O(n)$, and the space complexity is $O(M)$. Here, $n$ is -### **Python3** - ```python class Solution: def numberOfPoints(self, nums: List[List[int]]) -> int: @@ -56,8 +54,6 @@ class Solution: return sum(s > 0 for s in accumulate(d)) ``` -### **Java** - ```java class Solution { public int numberOfPoints(List> nums) { @@ -78,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -99,8 +93,6 @@ public: }; ``` -### **Go** - ```go func numberOfPoints(nums [][]int) (ans int) { d := [110]int{} @@ -119,8 +111,6 @@ func numberOfPoints(nums [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function numberOfPoints(nums: number[][]): number { const d: number[] = Array(110).fill(0); @@ -140,10 +130,6 @@ function numberOfPoints(nums: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/README.md b/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/README.md index bbda2935f6ddc..b57c52bc39c4f 100644 --- a/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/README.md +++ b/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/README.md @@ -43,14 +43,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def isReachableAtTime(self, sx: int, sy: int, fx: int, fy: int, t: int) -> bool: @@ -61,10 +57,6 @@ class Solution: return max(dx, dy) <= t ``` -### **Java** - - - ```java class Solution { public boolean isReachableAtTime(int sx, int sy, int fx, int fy, int t) { @@ -78,8 +70,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +83,6 @@ public: }; ``` -### **Go** - ```go func isReachableAtTime(sx int, sy int, fx int, fy int, t int) bool { if sx == fx && sy == fy { @@ -113,8 +101,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function isReachableAtTime(sx: number, sy: number, fx: number, fy: number, t: number): boolean { if (sx === fx && sy === fy) { @@ -126,8 +112,6 @@ function isReachableAtTime(sx: number, sy: number, fx: number, fy: number, t: nu } ``` -### **C#** - ```cs public class Solution { public bool IsReachableAtTime(int sx, int sy, int fx, int fy, int t) { @@ -138,10 +122,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/README_EN.md b/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/README_EN.md index 73a0906cbfde5..5708c82844664 100644 --- a/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/README_EN.md +++ b/solution/2800-2899/2849.Determine if a Cell Is Reachable at a Given Time/README_EN.md @@ -39,9 +39,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -53,8 +53,6 @@ class Solution: return max(dx, dy) <= t ``` -### **Java** - ```java class Solution { public boolean isReachableAtTime(int sx, int sy, int fx, int fy, int t) { @@ -68,8 +66,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -83,8 +79,6 @@ public: }; ``` -### **Go** - ```go func isReachableAtTime(sx int, sy int, fx int, fy int, t int) bool { if sx == fx && sy == fy { @@ -103,8 +97,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function isReachableAtTime(sx: number, sy: number, fx: number, fy: number, t: number): boolean { if (sx === fx && sy === fy) { @@ -116,8 +108,6 @@ function isReachableAtTime(sx: number, sy: number, fx: number, fy: number, t: nu } ``` -### **C#** - ```cs public class Solution { public bool IsReachableAtTime(int sx, int sy, int fx, int fy, int t) { @@ -128,10 +118,6 @@ public class Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/README.md b/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/README.md index 76e4ccffa9868..57bcd2c5b056f 100644 --- a/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/README.md +++ b/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/README.md @@ -57,28 +57,12 @@ ## 解法 - - -**方法一:朴素 BFS** +### 方法一:朴素 BFS 题目实际上是求一个状态图中从初始状态到目标状态的最短路径,因此可以使用 BFS 求解。初始状态为 `grid`,目标状态为 `[[1, 1, 1], [1, 1, 1], [1, 1, 1]]`,在每次操作中,我们可以将一个单元格大于 $1$ 的石头移动到相邻的一个不超过 $1$ 的单元格。如果找到了目标状态,那么就可以返回当前的层数,即为最少移动次数。 -**方法二:状态压缩动态规划** - -我们可以把所有值为 $0$ 的单元格坐标 $(i, j)$ 放入数组 $left$ 中,如果单元格的值 $v$ 大于 $1$,那么我们把 $v-1$ 个坐标 $(i, j)$ 放入数组 $right$ 中。那么问题就转化为,每个 $right$ 中的坐标 $(i, j)$ 都要移动到 $left$ 中的一个坐标 $(x, y)$,求最少的移动次数。 - -我们记 $left$ 的长度为 $n$,那么我们可以使用 $n$ 位二进制数来表示 $left$ 中的每个坐标是否被 $right$ 中的坐标填充,其中 $1$ 表示被填充,而 $0$ 表示未被填充。初始时 $f[i] = \infty$,其余 $f[0]=0$。 - -考虑 $f[i]$,记当前 $i$ 的二进制表示中 $1$ 的个数为 $k$,我们在 $[0..n)$ 的范围内枚举 $j$,如果 $i$ 的第 $j$ 位为 $1$,那么 $f[i]$ 可以由 $f[i \oplus (1 << j)]$ 转移而来,转移的代价为 $cal(left[k-1], right[j])$,其中 $cal$ 表示两个坐标之间的曼哈顿距离。最终答案为 $f[(1 << n) - 1]$。 - -时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(2^n)$。其中 $n$ 表示 $left$ 的长度,本题中 $n \le 9$。 - -### **Python3** - - - ```python class Solution: def minimumMoves(self, grid: List[List[int]]) -> int: @@ -107,36 +91,6 @@ class Solution: ans += 1 ``` -```python -class Solution: - def minimumMoves(self, grid: List[List[int]]) -> int: - def cal(a: tuple, b: tuple) -> int: - return abs(a[0] - b[0]) + abs(a[1] - b[1]) - - left, right = [], [] - for i in range(3): - for j in range(3): - if grid[i][j] == 0: - left.append((i, j)) - else: - for _ in range(grid[i][j] - 1): - right.append((i, j)) - - n = len(left) - f = [inf] * (1 << n) - f[0] = 0 - for i in range(1, 1 << n): - k = i.bit_count() - for j in range(n): - if i >> j & 1: - f[i] = min(f[i], f[i ^ (1 << j)] + cal(left[k - 1], right[j])) - return f[-1] -``` - -### **Java** - - - ```java class Solution { public int minimumMoves(int[][] grid) { @@ -203,45 +157,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumMoves(int[][] grid) { - List left = new ArrayList<>(); - List right = new ArrayList<>(); - for (int i = 0; i < 3; ++i) { - for (int j = 0; j < 3; ++j) { - if (grid[i][j] == 0) { - left.add(new int[] {i, j}); - } else { - for (int k = 1; k < grid[i][j]; ++k) { - right.add(new int[] {i, j}); - } - } - } - } - int n = left.size(); - int[] f = new int[1 << n]; - Arrays.fill(f, 1 << 30); - f[0] = 0; - for (int i = 1; i < 1 << n; ++i) { - int k = Integer.bitCount(i); - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 1) { - f[i] = Math.min(f[i], f[i ^ (1 << j)] + cal(left.get(k - 1), right.get(j))); - } - } - } - return f[(1 << n) - 1]; - } - - private int cal(int[] a, int[] b) { - return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -279,8 +194,6 @@ public: }; ``` -### **Go** - ```go func minimumMoves(grid [][]int) int { left := [][2]int{} @@ -322,8 +235,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minimumMoves(grid: number[][]): number { const left: number[][] = []; @@ -362,10 +273,83 @@ function minimumMoves(grid: number[][]): number { } ``` -### **...** + + +### 方法二:状态压缩动态规划 + +我们可以把所有值为 $0$ 的单元格坐标 $(i, j)$ 放入数组 $left$ 中,如果单元格的值 $v$ 大于 $1$,那么我们把 $v-1$ 个坐标 $(i, j)$ 放入数组 $right$ 中。那么问题就转化为,每个 $right$ 中的坐标 $(i, j)$ 都要移动到 $left$ 中的一个坐标 $(x, y)$,求最少的移动次数。 + +我们记 $left$ 的长度为 $n$,那么我们可以使用 $n$ 位二进制数来表示 $left$ 中的每个坐标是否被 $right$ 中的坐标填充,其中 $1$ 表示被填充,而 $0$ 表示未被填充。初始时 $f[i] = \infty$,其余 $f[0]=0$。 + +考虑 $f[i]$,记当前 $i$ 的二进制表示中 $1$ 的个数为 $k$,我们在 $[0..n)$ 的范围内枚举 $j$,如果 $i$ 的第 $j$ 位为 $1$,那么 $f[i]$ 可以由 $f[i \oplus (1 << j)]$ 转移而来,转移的代价为 $cal(left[k-1], right[j])$,其中 $cal$ 表示两个坐标之间的曼哈顿距离。最终答案为 $f[(1 << n) - 1]$。 + +时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(2^n)$。其中 $n$ 表示 $left$ 的长度,本题中 $n \le 9$。 + + + +```python +class Solution: + def minimumMoves(self, grid: List[List[int]]) -> int: + def cal(a: tuple, b: tuple) -> int: + return abs(a[0] - b[0]) + abs(a[1] - b[1]) + + left, right = [], [] + for i in range(3): + for j in range(3): + if grid[i][j] == 0: + left.append((i, j)) + else: + for _ in range(grid[i][j] - 1): + right.append((i, j)) + n = len(left) + f = [inf] * (1 << n) + f[0] = 0 + for i in range(1, 1 << n): + k = i.bit_count() + for j in range(n): + if i >> j & 1: + f[i] = min(f[i], f[i ^ (1 << j)] + cal(left[k - 1], right[j])) + return f[-1] ``` +```java +class Solution { + public int minimumMoves(int[][] grid) { + List left = new ArrayList<>(); + List right = new ArrayList<>(); + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + if (grid[i][j] == 0) { + left.add(new int[] {i, j}); + } else { + for (int k = 1; k < grid[i][j]; ++k) { + right.add(new int[] {i, j}); + } + } + } + } + int n = left.size(); + int[] f = new int[1 << n]; + Arrays.fill(f, 1 << 30); + f[0] = 0; + for (int i = 1; i < 1 << n; ++i) { + int k = Integer.bitCount(i); + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + f[i] = Math.min(f[i], f[i ^ (1 << j)] + cal(left.get(k - 1), right.get(j))); + } + } + } + return f[(1 << n) - 1]; + } + + private int cal(int[] a, int[] b) { + return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); + } +} ``` + + diff --git a/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/README_EN.md b/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/README_EN.md index a236d58c859e3..a31cf28b18ce6 100644 --- a/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/README_EN.md +++ b/solution/2800-2899/2850.Minimum Moves to Spread Stones Over Grid/README_EN.md @@ -49,24 +49,12 @@ It can be shown that 4 is the minimum number of moves required to place one ston ## Solutions -**Solution 1: Naive BFS** +### Solution 1: Naive BFS The problem is essentially finding the shortest path from the initial state to the target state in a state graph, so we can use BFS to solve it. The initial state is `grid`, and the target state is `[[1, 1, 1], [1, 1, 1], [1, 1, 1]]`. In each operation, we can move a stone greater than $1$ from a cell to an adjacent cell that does not exceed $1$. If the target state is found, we can return the current layer number, which is the minimum number of moves. -**Solution 2: State Compression Dynamic Programming** - -We can put all the coordinates $(i, j)$ of cells with a value of $0$ into an array $left$. If the value $v$ of a cell is greater than $1$, we put $v-1$ coordinates $(i, j)$ into an array $right$. The problem then becomes that each coordinate $(i, j)$ in $right$ needs to be moved to a coordinate $(x, y)$ in $left$, and we need to find the minimum number of moves. - -Let's denote the length of $left$ as $n$. We can use an $n$-bit binary number to represent whether each coordinate in $left$ is filled by a coordinate in $right$, where $1$ represents being filled, and $0$ represents not being filled. Initially, $f[i] = \infty$, and the rest $f[0]=0$. - -Consider $f[i]$, let the number of $1$s in the binary representation of $i$ be $k$. We enumerate $j$ in the range $[0..n)$, if the $j$th bit of $i$ is $1$, then $f[i]$ can be transferred from $f[i \oplus (1 << j)]$, and the cost of the transfer is $cal(left[k-1], right[j])$, where $cal$ represents the Manhattan distance between two coordinates. The final answer is $f[(1 << n) - 1]$. - -The time complexity is $O(n \times 2^n)$, and the space complexity is $O(2^n)$. Here, $n$ is the length of $left$, and in this problem, $n \le 9$. - -### **Python3** - ```python class Solution: def minimumMoves(self, grid: List[List[int]]) -> int: @@ -95,34 +83,6 @@ class Solution: ans += 1 ``` -```python -class Solution: - def minimumMoves(self, grid: List[List[int]]) -> int: - def cal(a: tuple, b: tuple) -> int: - return abs(a[0] - b[0]) + abs(a[1] - b[1]) - - left, right = [], [] - for i in range(3): - for j in range(3): - if grid[i][j] == 0: - left.append((i, j)) - else: - for _ in range(grid[i][j] - 1): - right.append((i, j)) - - n = len(left) - f = [inf] * (1 << n) - f[0] = 0 - for i in range(1, 1 << n): - k = i.bit_count() - for j in range(n): - if i >> j & 1: - f[i] = min(f[i], f[i ^ (1 << j)] + cal(left[k - 1], right[j])) - return f[-1] -``` - -### **Java** - ```java class Solution { public int minimumMoves(int[][] grid) { @@ -189,45 +149,6 @@ class Solution { } ``` -```java -class Solution { - public int minimumMoves(int[][] grid) { - List left = new ArrayList<>(); - List right = new ArrayList<>(); - for (int i = 0; i < 3; ++i) { - for (int j = 0; j < 3; ++j) { - if (grid[i][j] == 0) { - left.add(new int[] {i, j}); - } else { - for (int k = 1; k < grid[i][j]; ++k) { - right.add(new int[] {i, j}); - } - } - } - } - int n = left.size(); - int[] f = new int[1 << n]; - Arrays.fill(f, 1 << 30); - f[0] = 0; - for (int i = 1; i < 1 << n; ++i) { - int k = Integer.bitCount(i); - for (int j = 0; j < n; ++j) { - if ((i >> j & 1) == 1) { - f[i] = Math.min(f[i], f[i ^ (1 << j)] + cal(left.get(k - 1), right.get(j))); - } - } - } - return f[(1 << n) - 1]; - } - - private int cal(int[] a, int[] b) { - return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -265,8 +186,6 @@ public: }; ``` -### **Go** - ```go func minimumMoves(grid [][]int) int { left := [][2]int{} @@ -308,8 +227,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function minimumMoves(grid: number[][]): number { const left: number[][] = []; @@ -348,10 +265,83 @@ function minimumMoves(grid: number[][]): number { } ``` -### **...** + + +### Solution 2: State Compression Dynamic Programming + +We can put all the coordinates $(i, j)$ of cells with a value of $0$ into an array $left$. If the value $v$ of a cell is greater than $1$, we put $v-1$ coordinates $(i, j)$ into an array $right$. The problem then becomes that each coordinate $(i, j)$ in $right$ needs to be moved to a coordinate $(x, y)$ in $left$, and we need to find the minimum number of moves. + +Let's denote the length of $left$ as $n$. We can use an $n$-bit binary number to represent whether each coordinate in $left$ is filled by a coordinate in $right$, where $1$ represents being filled, and $0$ represents not being filled. Initially, $f[i] = \infty$, and the rest $f[0]=0$. + +Consider $f[i]$, let the number of $1$s in the binary representation of $i$ be $k$. We enumerate $j$ in the range $[0..n)$, if the $j$th bit of $i$ is $1$, then $f[i]$ can be transferred from $f[i \oplus (1 << j)]$, and the cost of the transfer is $cal(left[k-1], right[j])$, where $cal$ represents the Manhattan distance between two coordinates. The final answer is $f[(1 << n) - 1]$. +The time complexity is $O(n \times 2^n)$, and the space complexity is $O(2^n)$. Here, $n$ is the length of $left$, and in this problem, $n \le 9$. + + + +```python +class Solution: + def minimumMoves(self, grid: List[List[int]]) -> int: + def cal(a: tuple, b: tuple) -> int: + return abs(a[0] - b[0]) + abs(a[1] - b[1]) + + left, right = [], [] + for i in range(3): + for j in range(3): + if grid[i][j] == 0: + left.append((i, j)) + else: + for _ in range(grid[i][j] - 1): + right.append((i, j)) + + n = len(left) + f = [inf] * (1 << n) + f[0] = 0 + for i in range(1, 1 << n): + k = i.bit_count() + for j in range(n): + if i >> j & 1: + f[i] = min(f[i], f[i ^ (1 << j)] + cal(left[k - 1], right[j])) + return f[-1] ``` +```java +class Solution { + public int minimumMoves(int[][] grid) { + List left = new ArrayList<>(); + List right = new ArrayList<>(); + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + if (grid[i][j] == 0) { + left.add(new int[] {i, j}); + } else { + for (int k = 1; k < grid[i][j]; ++k) { + right.add(new int[] {i, j}); + } + } + } + } + int n = left.size(); + int[] f = new int[1 << n]; + Arrays.fill(f, 1 << 30); + f[0] = 0; + for (int i = 1; i < 1 << n; ++i) { + int k = Integer.bitCount(i); + for (int j = 0; j < n; ++j) { + if ((i >> j & 1) == 1) { + f[i] = Math.min(f[i], f[i ^ (1 << j)] + cal(left.get(k - 1), right.get(j))); + } + } + } + return f[(1 << n) - 1]; + } + + private int cal(int[] a, int[] b) { + return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); + } +} ``` + + diff --git a/solution/2800-2899/2851.String Transformation/README.md b/solution/2800-2899/2851.String Transformation/README.md index 40b8849ac1b07..e584133398df0 100644 --- a/solution/2800-2899/2851.String Transformation/README.md +++ b/solution/2800-2899/2851.String Transformation/README.md @@ -60,42 +60,280 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python - +""" +DP, Z-algorithm, Fast mod. +Approach +How to represent a string? +Each operation is just a rotation. Each result string can be represented by an integer from 0 to n - 1. Namely, it's just the new index of s[0]. +How to find the integer(s) that can represent string t? +Create a new string s + t + t (length = 3 * n). +Use Z-algorithm (or KMP), for each n <= index < 2 * n, calculate the maximum prefix length that each substring starts from index can match, if the length >= n, then (index - n) is a valid integer representation. +How to get the result? +It's a very obvious DP. +If we use an integer to represent a string, we only need to consider the transition from zero to non-zero and from non-zero to zero. In other words, all the non-zero strings should have the same result. +So let dp[t][i = 0/1] be the number of ways to get the zero/nonzero string +after excatly t steps. +Then +dp[t][0] = dp[t - 1][1] * (n - 1). +All the non zero strings can make it. +dp[t][1] = dp[t - 1][0] + dp[t - 1] * (n - 2). +For a particular non zero string, all the other non zero strings and zero string can make it. +We have dp[0][0] = 1 and dp[0][1] = 0 +Use matrix multiplication. +How to calculate dp[k][x = 0, 1] faster? +Use matrix multiplication +vector (dp[t - 1][0], dp[t - 1][1]) +multiplies matrix +[0 1] +[n - 1 n - 2] +== vector (dp[t][0], dp[t - 1][1]). +So we just need to calculate the kth power of the matrix which can be done by fast power algorith. +Complexity +Time complexity: +O(n + logk) +Space complexity: +O(n) +""" + + +class Solution: + M: int = 1000000007 + + def add(self, x: int, y: int) -> int: + x += y + if x >= self.M: + x -= self.M + return x + + def mul(self, x: int, y: int) -> int: + return int(x * y % self.M) + + def getZ(self, s: str) -> List[int]: + n = len(s) + z = [0] * n + left = right = 0 + for i in range(1, n): + if i <= right and z[i - left] <= right - i: + z[i] = z[i - left] + else: + z_i = max(0, right - i + 1) + while i + z_i < n and s[i + z_i] == s[z_i]: + z_i += 1 + z[i] = z_i + if i + z[i] - 1 > right: + left = i + right = i + z[i] - 1 + return z + + def matrixMultiply(self, a: List[List[int]], b: List[List[int]]) -> List[List[int]]: + m = len(a) + n = len(a[0]) + p = len(b[0]) + r = [[0] * p for _ in range(m)] + for i in range(m): + for j in range(p): + for k in range(n): + r[i][j] = self.add(r[i][j], self.mul(a[i][k], b[k][j])) + return r + + def matrixPower(self, a: List[List[int]], y: int) -> List[List[int]]: + n = len(a) + r = [[0] * n for _ in range(n)] + for i in range(n): + r[i][i] = 1 + x = [a[i][:] for i in range(n)] + while y > 0: + if y & 1: + r = self.matrixMultiply(r, x) + x = self.matrixMultiply(x, x) + y >>= 1 + return r + + def numberOfWays(self, s: str, t: str, k: int) -> int: + n = len(s) + dp = self.matrixPower([[0, 1], [n - 1, n - 2]], k)[0] + s += t + t + z = self.getZ(s) + m = n + n + result = 0 + for i in range(n, m): + if z[i] >= n: + result = self.add(result, dp[0] if i - n == 0 else dp[1]) + return result ``` -### **Java** - - - ```java - +class Solution { + private static final int M = 1000000007; + + private int add(int x, int y) { + if ((x += y) >= M) { + x -= M; + } + return x; + } + + private int mul(long x, long y) { + return (int) (x * y % M); + } + + private int[] getZ(String s) { + int n = s.length(); + int[] z = new int[n]; + for (int i = 1, left = 0, right = 0; i < n; ++i) { + if (i <= right && z[i - left] <= right - i) { + z[i] = z[i - left]; + } else { + int z_i = Math.max(0, right - i + 1); + while (i + z_i < n && s.charAt(i + z_i) == s.charAt(z_i)) { + z_i++; + } + z[i] = z_i; + } + if (i + z[i] - 1 > right) { + left = i; + right = i + z[i] - 1; + } + } + return z; + } + + private int[][] matrixMultiply(int[][] a, int[][] b) { + int m = a.length, n = a[0].length, p = b[0].length; + int[][] r = new int[m][p]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < p; ++j) { + for (int k = 0; k < n; ++k) { + r[i][j] = add(r[i][j], mul(a[i][k], b[k][j])); + } + } + } + return r; + } + + private int[][] matrixPower(int[][] a, long y) { + int n = a.length; + int[][] r = new int[n][n]; + for (int i = 0; i < n; ++i) { + r[i][i] = 1; + } + int[][] x = new int[n][n]; + for (int i = 0; i < n; ++i) { + System.arraycopy(a[i], 0, x[i], 0, n); + } + while (y > 0) { + if ((y & 1) == 1) { + r = matrixMultiply(r, x); + } + x = matrixMultiply(x, x); + y >>= 1; + } + return r; + } + + public int numberOfWays(String s, String t, long k) { + int n = s.length(); + int[] dp = matrixPower(new int[][] {{0, 1}, {n - 1, n - 2}}, k)[0]; + s += t + t; + int[] z = getZ(s); + int m = n + n; + int result = 0; + for (int i = n; i < m; ++i) { + if (z[i] >= n) { + result = add(result, dp[i - n == 0 ? 0 : 1]); + } + } + return result; + } +} ``` -### **C++** - ```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - +class Solution { + const int M = 1000000007; + + int add(int x, int y) { + if ((x += y) >= M) { + x -= M; + } + return x; + } + + int mul(long long x, long long y) { + return x * y % M; + } + + vector getz(const string& s) { + const int n = s.length(); + vector z(n); + for (int i = 1, left = 0, right = 0; i < n; ++i) { + if (i <= right && z[i - left] <= right - i) { + z[i] = z[i - left]; + } else { + for (z[i] = max(0, right - i + 1); i + z[i] < n && s[i + z[i]] == s[z[i]]; ++z[i]) + ; + } + if (i + z[i] - 1 > right) { + left = i; + right = i + z[i] - 1; + } + } + return z; + } + + vector> mul(const vector>& a, const vector>& b) { + const int m = a.size(), n = a[0].size(), p = b[0].size(); + vector> r(m, vector(p)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < p; ++k) { + r[i][k] = add(r[i][k], mul(a[i][j], b[j][k])); + } + } + } + return r; + } + + vector> pow(const vector>& a, long long y) { + const int n = a.size(); + vector> r(n, vector(n)); + for (int i = 0; i < n; ++i) { + r[i][i] = 1; + } + auto x = a; + for (; y; y >>= 1) { + if (y & 1) { + r = mul(r, x); + } + x = mul(x, x); + } + return r; + } + +public: + int numberOfWays(string s, string t, long long k) { + const int n = s.length(); + const auto dp = pow({{0, 1}, {n - 1, n - 2}}, k)[0]; + s.append(t); + s.append(t); + const auto z = getz(s); + const int m = n + n; + int r = 0; + for (int i = n; i < m; ++i) { + if (z[i] >= n) { + r = add(r, dp[!!(i - n)]); + } + } + return r; + } +}; ``` + + diff --git a/solution/2800-2899/2851.String Transformation/README_EN.md b/solution/2800-2899/2851.String Transformation/README_EN.md index dbe49631be524..f78230c62e355 100644 --- a/solution/2800-2899/2851.String Transformation/README_EN.md +++ b/solution/2800-2899/2851.String Transformation/README_EN.md @@ -56,36 +56,280 @@ Choose suffix from index = 4, so resulting s = "ababab". ## Solutions - +### Solution 1 -### **Python3** + ```python - +""" +DP, Z-algorithm, Fast mod. +Approach +How to represent a string? +Each operation is just a rotation. Each result string can be represented by an integer from 0 to n - 1. Namely, it's just the new index of s[0]. +How to find the integer(s) that can represent string t? +Create a new string s + t + t (length = 3 * n). +Use Z-algorithm (or KMP), for each n <= index < 2 * n, calculate the maximum prefix length that each substring starts from index can match, if the length >= n, then (index - n) is a valid integer representation. +How to get the result? +It's a very obvious DP. +If we use an integer to represent a string, we only need to consider the transition from zero to non-zero and from non-zero to zero. In other words, all the non-zero strings should have the same result. +So let dp[t][i = 0/1] be the number of ways to get the zero/nonzero string +after excatly t steps. +Then +dp[t][0] = dp[t - 1][1] * (n - 1). +All the non zero strings can make it. +dp[t][1] = dp[t - 1][0] + dp[t - 1] * (n - 2). +For a particular non zero string, all the other non zero strings and zero string can make it. +We have dp[0][0] = 1 and dp[0][1] = 0 +Use matrix multiplication. +How to calculate dp[k][x = 0, 1] faster? +Use matrix multiplication +vector (dp[t - 1][0], dp[t - 1][1]) +multiplies matrix +[0 1] +[n - 1 n - 2] +== vector (dp[t][0], dp[t - 1][1]). +So we just need to calculate the kth power of the matrix which can be done by fast power algorith. +Complexity +Time complexity: +O(n + logk) +Space complexity: +O(n) +""" + + +class Solution: + M: int = 1000000007 + + def add(self, x: int, y: int) -> int: + x += y + if x >= self.M: + x -= self.M + return x + + def mul(self, x: int, y: int) -> int: + return int(x * y % self.M) + + def getZ(self, s: str) -> List[int]: + n = len(s) + z = [0] * n + left = right = 0 + for i in range(1, n): + if i <= right and z[i - left] <= right - i: + z[i] = z[i - left] + else: + z_i = max(0, right - i + 1) + while i + z_i < n and s[i + z_i] == s[z_i]: + z_i += 1 + z[i] = z_i + if i + z[i] - 1 > right: + left = i + right = i + z[i] - 1 + return z + + def matrixMultiply(self, a: List[List[int]], b: List[List[int]]) -> List[List[int]]: + m = len(a) + n = len(a[0]) + p = len(b[0]) + r = [[0] * p for _ in range(m)] + for i in range(m): + for j in range(p): + for k in range(n): + r[i][j] = self.add(r[i][j], self.mul(a[i][k], b[k][j])) + return r + + def matrixPower(self, a: List[List[int]], y: int) -> List[List[int]]: + n = len(a) + r = [[0] * n for _ in range(n)] + for i in range(n): + r[i][i] = 1 + x = [a[i][:] for i in range(n)] + while y > 0: + if y & 1: + r = self.matrixMultiply(r, x) + x = self.matrixMultiply(x, x) + y >>= 1 + return r + + def numberOfWays(self, s: str, t: str, k: int) -> int: + n = len(s) + dp = self.matrixPower([[0, 1], [n - 1, n - 2]], k)[0] + s += t + t + z = self.getZ(s) + m = n + n + result = 0 + for i in range(n, m): + if z[i] >= n: + result = self.add(result, dp[0] if i - n == 0 else dp[1]) + return result ``` -### **Java** - ```java - +class Solution { + private static final int M = 1000000007; + + private int add(int x, int y) { + if ((x += y) >= M) { + x -= M; + } + return x; + } + + private int mul(long x, long y) { + return (int) (x * y % M); + } + + private int[] getZ(String s) { + int n = s.length(); + int[] z = new int[n]; + for (int i = 1, left = 0, right = 0; i < n; ++i) { + if (i <= right && z[i - left] <= right - i) { + z[i] = z[i - left]; + } else { + int z_i = Math.max(0, right - i + 1); + while (i + z_i < n && s.charAt(i + z_i) == s.charAt(z_i)) { + z_i++; + } + z[i] = z_i; + } + if (i + z[i] - 1 > right) { + left = i; + right = i + z[i] - 1; + } + } + return z; + } + + private int[][] matrixMultiply(int[][] a, int[][] b) { + int m = a.length, n = a[0].length, p = b[0].length; + int[][] r = new int[m][p]; + for (int i = 0; i < m; ++i) { + for (int j = 0; j < p; ++j) { + for (int k = 0; k < n; ++k) { + r[i][j] = add(r[i][j], mul(a[i][k], b[k][j])); + } + } + } + return r; + } + + private int[][] matrixPower(int[][] a, long y) { + int n = a.length; + int[][] r = new int[n][n]; + for (int i = 0; i < n; ++i) { + r[i][i] = 1; + } + int[][] x = new int[n][n]; + for (int i = 0; i < n; ++i) { + System.arraycopy(a[i], 0, x[i], 0, n); + } + while (y > 0) { + if ((y & 1) == 1) { + r = matrixMultiply(r, x); + } + x = matrixMultiply(x, x); + y >>= 1; + } + return r; + } + + public int numberOfWays(String s, String t, long k) { + int n = s.length(); + int[] dp = matrixPower(new int[][] {{0, 1}, {n - 1, n - 2}}, k)[0]; + s += t + t; + int[] z = getZ(s); + int m = n + n; + int result = 0; + for (int i = n; i < m; ++i) { + if (z[i] >= n) { + result = add(result, dp[i - n == 0 ? 0 : 1]); + } + } + return result; + } +} ``` -### **C++** - ```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - +class Solution { + const int M = 1000000007; + + int add(int x, int y) { + if ((x += y) >= M) { + x -= M; + } + return x; + } + + int mul(long long x, long long y) { + return x * y % M; + } + + vector getz(const string& s) { + const int n = s.length(); + vector z(n); + for (int i = 1, left = 0, right = 0; i < n; ++i) { + if (i <= right && z[i - left] <= right - i) { + z[i] = z[i - left]; + } else { + for (z[i] = max(0, right - i + 1); i + z[i] < n && s[i + z[i]] == s[z[i]]; ++z[i]) + ; + } + if (i + z[i] - 1 > right) { + left = i; + right = i + z[i] - 1; + } + } + return z; + } + + vector> mul(const vector>& a, const vector>& b) { + const int m = a.size(), n = a[0].size(), p = b[0].size(); + vector> r(m, vector(p)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + for (int k = 0; k < p; ++k) { + r[i][k] = add(r[i][k], mul(a[i][j], b[j][k])); + } + } + } + return r; + } + + vector> pow(const vector>& a, long long y) { + const int n = a.size(); + vector> r(n, vector(n)); + for (int i = 0; i < n; ++i) { + r[i][i] = 1; + } + auto x = a; + for (; y; y >>= 1) { + if (y & 1) { + r = mul(r, x); + } + x = mul(x, x); + } + return r; + } + +public: + int numberOfWays(string s, string t, long long k) { + const int n = s.length(); + const auto dp = pow({{0, 1}, {n - 1, n - 2}}, k)[0]; + s.append(t); + s.append(t); + const auto z = getz(s); + const int m = n + n; + int r = 0; + for (int i = n; i < m; ++i) { + if (z[i] >= n) { + r = add(r, dp[!!(i - n)]); + } + } + return r; + } +}; ``` + + diff --git a/solution/2800-2899/2852.Sum of Remoteness of All Cells/README.md b/solution/2800-2899/2852.Sum of Remoteness of All Cells/README.md index 7c8f57d04f7ac..cb0fabde9dd8b 100644 --- a/solution/2800-2899/2852.Sum of Remoteness of All Cells/README.md +++ b/solution/2800-2899/2852.Sum of Remoteness of All Cells/README.md @@ -64,9 +64,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们先统计矩阵中非阻塞的格子的个数,记为 $cnt$,然后从每个非阻塞的格子出发,使用 DFS 计算出每个连通块中格子之和 $s$ 以及格子个数 $t$,那么其它连通块的所有 $(cnt - t)$ 个格子都可以累加上 $s$。我们累加所有连通块的结果即可。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def sumRemoteness(self, grid: List[List[int]]) -> int: @@ -103,10 +97,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int n; @@ -154,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -197,8 +185,6 @@ public: }; ``` -### **Go** - ```go func sumRemoteness(grid [][]int) (ans int64) { n := len(grid) @@ -237,8 +223,6 @@ func sumRemoteness(grid [][]int) (ans int64) { } ``` -### **TypeScript** - ```ts function sumRemoteness(grid: number[][]): number { const n = grid.length; @@ -278,10 +262,6 @@ function sumRemoteness(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2852.Sum of Remoteness of All Cells/README_EN.md b/solution/2800-2899/2852.Sum of Remoteness of All Cells/README_EN.md index 8a79fe6726212..e211209c4ea6d 100644 --- a/solution/2800-2899/2852.Sum of Remoteness of All Cells/README_EN.md +++ b/solution/2800-2899/2852.Sum of Remoteness of All Cells/README_EN.md @@ -60,7 +60,7 @@ Now let's jump on the bottom-right grid in the above picture and calculate R ## Solutions -**Solution 1: DFS** +### Solution 1: DFS First, we count the number of non-blocking cells in the matrix, denoted as $cnt$. Then, starting from each non-blocking cell, we use DFS to calculate the sum $s$ of the cells in each connected block and the number of cells $t$. Then, all $(cnt - t)$ cells in other connected blocks can be added with $s$. We sum up the results of all connected blocks. @@ -68,8 +68,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ -### **Python3** - ```python class Solution: def sumRemoteness(self, grid: List[List[int]]) -> int: @@ -95,8 +93,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int n; @@ -144,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -187,8 +181,6 @@ public: }; ``` -### **Go** - ```go func sumRemoteness(grid [][]int) (ans int64) { n := len(grid) @@ -227,8 +219,6 @@ func sumRemoteness(grid [][]int) (ans int64) { } ``` -### **TypeScript** - ```ts function sumRemoteness(grid: number[][]): number { const n = grid.length; @@ -268,10 +258,6 @@ function sumRemoteness(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2853.Highest Salaries Difference/README.md b/solution/2800-2899/2853.Highest Salaries Difference/README.md index 936fa83b3a421..7d80c943aa3db 100644 --- a/solution/2800-2899/2853.Highest Salaries Difference/README.md +++ b/solution/2800-2899/2853.Highest Salaries Difference/README.md @@ -59,18 +59,12 @@ Salaries table: ## 解法 - - -**方法一:GROUP BY 分组** +### 方法一:GROUP BY 分组 我们可以先分别计算出每个部门的最高工资,然后再计算两个最高工资的差值。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT MAX(s) - MIN(s) AS salary_difference @@ -83,3 +77,5 @@ FROM ``` + + diff --git a/solution/2800-2899/2853.Highest Salaries Difference/README_EN.md b/solution/2800-2899/2853.Highest Salaries Difference/README_EN.md index e985679bcc35f..c10c3e059f38b 100644 --- a/solution/2800-2899/2853.Highest Salaries Difference/README_EN.md +++ b/solution/2800-2899/2853.Highest Salaries Difference/README_EN.md @@ -56,14 +56,12 @@ Salaries table: ## Solutions -**Solution 1: GROUP BY Clause** +### Solution 1: GROUP BY Clause We can first calculate the highest salary for each department, and then calculate the difference between the two highest salaries. -### **SQL** - ```sql # Write your MySQL query statement below SELECT MAX(s) - MIN(s) AS salary_difference @@ -76,3 +74,5 @@ FROM ``` + + diff --git a/solution/2800-2899/2854.Rolling Average Steps/README.md b/solution/2800-2899/2854.Rolling Average Steps/README.md index 0583150d28f86..f553fafd454df 100644 --- a/solution/2800-2899/2854.Rolling Average Steps/README.md +++ b/solution/2800-2899/2854.Rolling Average Steps/README.md @@ -82,18 +82,12 @@ Steps table: ## 解法 - - -**方法一:窗口函数** +### 方法一:窗口函数 我们用窗口函数 `LAG() OVER()` 来计算每个用户当前日期与上上个日期之间的天数差,如果为 $2$,说明这两个日期之间有连续 $3$ 天的数据,我们可以利用窗口函数 `AVG() OVER()` 来计算这 $3$ 个数据的平均值。 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -128,3 +122,5 @@ ORDER BY 1, 2; ``` + + diff --git a/solution/2800-2899/2854.Rolling Average Steps/README_EN.md b/solution/2800-2899/2854.Rolling Average Steps/README_EN.md index 26d3015934639..989cd265bfcc0 100644 --- a/solution/2800-2899/2854.Rolling Average Steps/README_EN.md +++ b/solution/2800-2899/2854.Rolling Average Steps/README_EN.md @@ -79,14 +79,12 @@ Steps table: ## Solutions -**Solution 1: Window Functions** +### Solution 1: Window Functions We can use the window function `LAG() OVER()` to calculate the difference in days between the current date and the date before the last date for each user. If the difference is $2$, it means that there are continuous data for $3$ days between these two dates. We can use the window function `AVG() OVER()` to calculate the average of these $3$ data. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -121,3 +119,5 @@ ORDER BY 1, 2; ``` + + diff --git a/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/README.md b/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/README.md index bf4714be0714a..d185b96ef96d6 100644 --- a/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/README.md +++ b/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:直接遍历** +### 方法一:直接遍历 我们先用一个指针 $i$ 从左到右遍历数组 $nums$,找出一段连续的递增序列,直到 $i$ 到达数组末尾或者 $nums[i - 1] \gt nums[i]$。接下来我们用另一个指针 $k$ 从 $i + 1$ 开始遍历数组 $nums$,找出一段连续的递增序列,直到 $k$ 到达数组末尾或者 $nums[k - 1] \gt nums[k]$ 且 $nums[k] \gt nums[0]$。如果 $k$ 到达数组末尾,说明数组已经是递增的,返回 $n - i$;否则返回 $-1$。 @@ -60,10 +58,6 @@ -### **Python3** - - - ```python class Solution: def minimumRightShifts(self, nums: List[int]) -> int: @@ -77,10 +71,6 @@ class Solution: return -1 if k < n else n - i ``` -### **Java** - - - ```java class Solution { public int minimumRightShifts(List nums) { @@ -98,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +106,6 @@ public: }; ``` -### **Go** - ```go func minimumRightShifts(nums []int) int { n := len(nums) @@ -138,8 +124,6 @@ func minimumRightShifts(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumRightShifts(nums: number[]): number { const n = nums.length; @@ -155,10 +139,6 @@ function minimumRightShifts(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/README_EN.md b/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/README_EN.md index f93ab9082216f..9ed1a8927dfd5 100644 --- a/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/README_EN.md +++ b/solution/2800-2899/2855.Minimum Right Shifts to Sort the Array/README_EN.md @@ -46,7 +46,7 @@ Now nums is sorted; therefore the answer is 2. ## Solutions -**Solution 1: Direct Traversal** +### Solution 1: Direct Traversal First, we use a pointer $i$ to traverse the array $nums$ from left to right, finding a continuous increasing sequence until $i$ reaches the end of the array or $nums[i - 1] > nums[i]$. Next, we use another pointer $k$ to traverse the array $nums$ from $i + 1$, finding a continuous increasing sequence until $k$ reaches the end of the array or $nums[k - 1] > nums[k]$ and $nums[k] > nums[0]$. If $k$ reaches the end of the array, it means the array is already increasing, so we return $n - i$; otherwise, we return $-1$. @@ -54,8 +54,6 @@ The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is -### **Python3** - ```python class Solution: def minimumRightShifts(self, nums: List[int]) -> int: @@ -69,8 +67,6 @@ class Solution: return -1 if k < n else n - i ``` -### **Java** - ```java class Solution { public int minimumRightShifts(List nums) { @@ -88,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +102,6 @@ public: }; ``` -### **Go** - ```go func minimumRightShifts(nums []int) int { n := len(nums) @@ -128,8 +120,6 @@ func minimumRightShifts(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumRightShifts(nums: number[]): number { const n = nums.length; @@ -145,10 +135,6 @@ function minimumRightShifts(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2856.Minimum Array Length After Pair Removals/README.md b/solution/2800-2899/2856.Minimum Array Length After Pair Removals/README.md index 53875f1f98096..65314854df819 100644 --- a/solution/2800-2899/2856.Minimum Array Length After Pair Removals/README.md +++ b/solution/2800-2899/2856.Minimum Array Length After Pair Removals/README.md @@ -70,9 +70,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列(大根堆)** +### 方法一:贪心 + 优先队列(大根堆) 我们用一个哈希表 $cnt$ 统计数组 $nums$ 中每个元素的出现次数,然后将 $cnt$ 中的每个值加入一个优先队列(大根堆) $pq$ 中。每次从 $pq$ 中取出两个元素 $x$ 和 $y$,将它们的值减一,如果减一后的值仍大于 $0$,则将减一后的值重新加入 $pq$。每次从 $pq$ 中取出两个元素,表示将数组中的两个数对删除,因此数组的长度减少 $2$。当 $pq$ 的大小小于 $2$ 时,停止删除操作。 @@ -80,10 +78,6 @@ -### **Python3** - - - ```python class Solution: def minLengthAfterRemovals(self, nums: List[int]) -> int: @@ -103,10 +97,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minLengthAfterRemovals(List nums) { @@ -137,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -172,8 +160,6 @@ public: }; ``` -### **Go** - ```go func minLengthAfterRemovals(nums []int) int { cnt := map[int]int{} @@ -212,8 +198,6 @@ func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) } ``` -### **TypeScript** - ```ts function minLengthAfterRemovals(nums: number[]): number { const cnt: Map = new Map(); @@ -240,10 +224,6 @@ function minLengthAfterRemovals(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2856.Minimum Array Length After Pair Removals/README_EN.md b/solution/2800-2899/2856.Minimum Array Length After Pair Removals/README_EN.md index 78bc8f1455950..6b27c90cca38c 100644 --- a/solution/2800-2899/2856.Minimum Array Length After Pair Removals/README_EN.md +++ b/solution/2800-2899/2856.Minimum Array Length After Pair Removals/README_EN.md @@ -66,7 +66,7 @@ Hence, the minimum achievable length is 1. ## Solutions -**Solution 1: Greedy + Priority Queue (Max Heap)** +### Solution 1: Greedy + Priority Queue (Max Heap) We use a hash table $cnt$ to count the occurrence of each element in the array $nums$, then add each value in $cnt$ to a priority queue (max heap) $pq$. Each time we take out two elements $x$ and $y$ from $pq$, decrease their values by one. If the value after decrement is still greater than $0$, we add the decremented value back to $pq$. Each time we take out two elements from $pq$, it means we delete a pair of numbers from the array, so the length of the array decreases by $2$. When the size of $pq$ is less than $2$, we stop the deletion operation. @@ -74,8 +74,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def minLengthAfterRemovals(self, nums: List[int]) -> int: @@ -95,8 +93,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minLengthAfterRemovals(List nums) { @@ -127,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +156,6 @@ public: }; ``` -### **Go** - ```go func minLengthAfterRemovals(nums []int) int { cnt := map[int]int{} @@ -202,8 +194,6 @@ func (h *hp) push(v int) { heap.Push(h, v) } func (h *hp) pop() int { return heap.Pop(h).(int) } ``` -### **TypeScript** - ```ts function minLengthAfterRemovals(nums: number[]): number { const cnt: Map = new Map(); @@ -230,10 +220,6 @@ function minLengthAfterRemovals(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2857.Count Pairs of Points With Distance k/README.md b/solution/2800-2899/2857.Count Pairs of Points With Distance k/README.md index 5398f942ea5d0..33fb4ff0d16dc 100644 --- a/solution/2800-2899/2857.Count Pairs of Points With Distance k/README.md +++ b/solution/2800-2899/2857.Count Pairs of Points With Distance k/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:哈希表 + 枚举** +### 方法一:哈希表 + 枚举 我们可以用一个哈希表 $cnt$ 统计数组 $coordinates$ 中每个点出现的次数。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def countPairs(self, coordinates: List[List[int]], k: int) -> int: @@ -74,10 +68,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countPairs(List> coordinates, int k) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,31 +107,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countPairs(vector>& coordinates, int k) { - unordered_map cnt; - auto f = [](int x, int y) { - return x * 1000000L + y; - }; - int ans = 0; - for (auto& c : coordinates) { - int x2 = c[0], y2 = c[1]; - for (int a = 0; a <= k; ++a) { - int b = k - a; - int x1 = a ^ x2, y1 = b ^ y2; - ans += cnt[f(x1, y1)]; - } - ++cnt[f(x2, y2)]; - } - return ans; - } -}; -``` - -### **Go** - ```go func countPairs(coordinates [][]int, k int) (ans int) { cnt := map[[2]int]int{} @@ -160,8 +123,6 @@ func countPairs(coordinates [][]int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function countPairs(coordinates: number[][], k: number): number { const cnt: Map = new Map(); @@ -179,10 +140,35 @@ function countPairs(coordinates: number[][], k: number): number { } ``` -### **...** + -``` +### 方法二 + + +```cpp +class Solution { +public: + int countPairs(vector>& coordinates, int k) { + unordered_map cnt; + auto f = [](int x, int y) { + return x * 1000000L + y; + }; + int ans = 0; + for (auto& c : coordinates) { + int x2 = c[0], y2 = c[1]; + for (int a = 0; a <= k; ++a) { + int b = k - a; + int x1 = a ^ x2, y1 = b ^ y2; + ans += cnt[f(x1, y1)]; + } + ++cnt[f(x2, y2)]; + } + return ans; + } +}; ``` + + diff --git a/solution/2800-2899/2857.Count Pairs of Points With Distance k/README_EN.md b/solution/2800-2899/2857.Count Pairs of Points With Distance k/README_EN.md index 2588e66089126..15b017b481f60 100644 --- a/solution/2800-2899/2857.Count Pairs of Points With Distance k/README_EN.md +++ b/solution/2800-2899/2857.Count Pairs of Points With Distance k/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Hash Table + Enumeration** +### Solution 1: Hash Table + Enumeration We can use a hash table $cnt$ to count the occurrence of each point in the array $coordinates$. @@ -50,8 +50,6 @@ The time complexity is $O(n \times k)$, and the space complexity is $O(n)$. Here -### **Python3** - ```python class Solution: def countPairs(self, coordinates: List[List[int]], k: int) -> int: @@ -66,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countPairs(List> coordinates, int k) { @@ -87,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,31 +103,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countPairs(vector>& coordinates, int k) { - unordered_map cnt; - auto f = [](int x, int y) { - return x * 1000000L + y; - }; - int ans = 0; - for (auto& c : coordinates) { - int x2 = c[0], y2 = c[1]; - for (int a = 0; a <= k; ++a) { - int b = k - a; - int x1 = a ^ x2, y1 = b ^ y2; - ans += cnt[f(x1, y1)]; - } - ++cnt[f(x2, y2)]; - } - return ans; - } -}; -``` - -### **Go** - ```go func countPairs(coordinates [][]int, k int) (ans int) { cnt := map[[2]int]int{} @@ -150,8 +119,6 @@ func countPairs(coordinates [][]int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function countPairs(coordinates: number[][], k: number): number { const cnt: Map = new Map(); @@ -169,10 +136,35 @@ function countPairs(coordinates: number[][], k: number): number { } ``` -### **...** + -``` +### Solution 2 + + +```cpp +class Solution { +public: + int countPairs(vector>& coordinates, int k) { + unordered_map cnt; + auto f = [](int x, int y) { + return x * 1000000L + y; + }; + int ans = 0; + for (auto& c : coordinates) { + int x2 = c[0], y2 = c[1]; + for (int a = 0; a <= k; ++a) { + int b = k - a; + int x1 = a ^ x2, y1 = b ^ y2; + ans += cnt[f(x1, y1)]; + } + ++cnt[f(x2, y2)]; + } + return ans; + } +}; ``` + + diff --git a/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/README.md b/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/README.md index 35fb9ffbe7b4f..a334c19e82b43 100644 --- a/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/README.md +++ b/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/README.md @@ -68,18 +68,12 @@ ## 解法 - - -**方法一:树形 DP** +### 方法一:树形 DP 时间复杂度 $O(n)$,空间复杂度 $O(n)$。 -### **Python3** - - - ```python class Solution: def minEdgeReversals(self, n: int, edges: List[List[int]]) -> List[int]: @@ -107,10 +101,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -152,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -188,8 +176,6 @@ public: }; ``` -### **Go** - ```go func minEdgeReversals(n int, edges [][]int) []int { g := make([][][2]int, n) @@ -227,8 +213,6 @@ func minEdgeReversals(n int, edges [][]int) []int { } ``` -### **TypeScript** - ```ts function minEdgeReversals(n: number, edges: number[][]): number[] { const g: number[][][] = Array.from({ length: n }, () => []); @@ -259,10 +243,6 @@ function minEdgeReversals(n: number, edges: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/README_EN.md b/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/README_EN.md index 99a0dd9310d54..0ac7d1659d3f5 100644 --- a/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/README_EN.md +++ b/solution/2800-2899/2858.Minimum Edge Reversals So Every Node Is Reachable/README_EN.md @@ -64,9 +64,9 @@ So, answer[2] = 1. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -95,8 +95,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -138,8 +136,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -174,8 +170,6 @@ public: }; ``` -### **Go** - ```go func minEdgeReversals(n int, edges [][]int) []int { g := make([][][2]int, n) @@ -213,8 +207,6 @@ func minEdgeReversals(n int, edges [][]int) []int { } ``` -### **TypeScript** - ```ts function minEdgeReversals(n: number, edges: number[][]): number[] { const g: number[][][] = Array.from({ length: n }, () => []); @@ -245,10 +237,6 @@ function minEdgeReversals(n: number, edges: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/README.md b/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/README.md index f9f02e987e9bb..8993298d6d1e7 100644 --- a/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/README.md +++ b/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们直接遍历每个下标 $i$,判断其二进制表示中 $1$ 的个数是否等于 $k$,如果等于则将其对应的元素累加到答案 $ans$ 中。 @@ -68,20 +66,12 @@ -### **Python3** - - - ```python class Solution: def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int: return sum(x for i, x in enumerate(nums) if i.bit_count() == k) ``` -### **Java** - - - ```java class Solution { public int sumIndicesWithKSetBits(List nums, int k) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func sumIndicesWithKSetBits(nums []int, k int) (ans int) { for i, x := range nums { @@ -126,8 +112,6 @@ func sumIndicesWithKSetBits(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function sumIndicesWithKSetBits(nums: number[], k: number): number { let ans = 0; @@ -149,10 +133,6 @@ function bitCount(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/README_EN.md b/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/README_EN.md index 465ec34422b6b..b1cca4cb2fb1e 100644 --- a/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/README_EN.md +++ b/solution/2800-2899/2859.Sum of Values at Indices With K Set Bits/README_EN.md @@ -54,7 +54,7 @@ Hence, the answer is nums[3] = 1. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We directly traverse each index $i$, and check whether the number of $1$s in its binary representation is equal to $k$. If it is, we add the corresponding element to the answer $ans$. @@ -64,16 +64,12 @@ The time complexity is $O(n \times \log n)$, where $n$ is the length of the arra -### **Python3** - ```python class Solution: def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int: return sum(x for i, x in enumerate(nums) if i.bit_count() == k) ``` -### **Java** - ```java class Solution { public int sumIndicesWithKSetBits(List nums, int k) { @@ -88,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +99,6 @@ public: }; ``` -### **Go** - ```go func sumIndicesWithKSetBits(nums []int, k int) (ans int) { for i, x := range nums { @@ -118,8 +110,6 @@ func sumIndicesWithKSetBits(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function sumIndicesWithKSetBits(nums: number[], k: number): number { let ans = 0; @@ -141,10 +131,6 @@ function bitCount(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2860.Happy Students/README.md b/solution/2800-2899/2860.Happy Students/README.md index ea8c2c072ae0a..75203dde3e275 100644 --- a/solution/2800-2899/2860.Happy Students/README.md +++ b/solution/2800-2899/2860.Happy Students/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:排序 + 枚举** +### 方法一:排序 + 枚举 假设选出了 $k$ 个学生,那么以下情况成立: @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def countWays(self, nums: List[int]) -> int: @@ -92,10 +86,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countWays(List nums) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go func countWays(nums []int) (ans int) { sort.Ints(nums) @@ -148,8 +134,6 @@ func countWays(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function countWays(nums: number[]): number { nums.sort((a, b) => a - b); @@ -165,10 +149,6 @@ function countWays(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2860.Happy Students/README_EN.md b/solution/2800-2899/2860.Happy Students/README_EN.md index a0af39548f50f..a3f5b28b41d77 100644 --- a/solution/2800-2899/2860.Happy Students/README_EN.md +++ b/solution/2800-2899/2860.Happy Students/README_EN.md @@ -50,7 +50,7 @@ The class teacher selects all the students to form the group. ## Solutions -**Solution 1: Sorting + Enumeration** +### Solution 1: Sorting + Enumeration Assume that $k$ students are selected, then the following conditions hold: @@ -68,8 +68,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def countWays(self, nums: List[int]) -> int: @@ -84,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countWays(List nums) { @@ -102,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func countWays(nums []int) (ans int) { sort.Ints(nums) @@ -138,8 +130,6 @@ func countWays(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function countWays(nums: number[]): number { nums.sort((a, b) => a - b); @@ -155,10 +145,6 @@ function countWays(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2861.Maximum Number of Alloys/README.md b/solution/2800-2899/2861.Maximum Number of Alloys/README.md index c28b787cebf50..8af511a752266 100644 --- a/solution/2800-2899/2861.Maximum Number of Alloys/README.md +++ b/solution/2800-2899/2861.Maximum Number of Alloys/README.md @@ -77,9 +77,7 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们注意到,所有合金都需要由同一台机器制造,因此我们可以枚举使用哪一台机器来制造合金。 @@ -89,10 +87,6 @@ -### **Python3** - - - ```python class Solution: def maxNumberOfAlloys( @@ -118,10 +112,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { int n; @@ -166,8 +156,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -200,8 +188,6 @@ public: }; ``` -### **Go** - ```go func maxNumberOfAlloys(n int, k int, budget int, composition [][]int, stock []int, cost []int) int { isValid := func(target int) bool { @@ -231,8 +217,6 @@ func maxNumberOfAlloys(n int, k int, budget int, composition [][]int, stock []in } ``` -### **TypeScript** - ```ts function maxNumberOfAlloys( n: number, @@ -269,10 +253,6 @@ function maxNumberOfAlloys( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2861.Maximum Number of Alloys/README_EN.md b/solution/2800-2899/2861.Maximum Number of Alloys/README_EN.md index 7146cb25c19ce..9ef68acd922c0 100644 --- a/solution/2800-2899/2861.Maximum Number of Alloys/README_EN.md +++ b/solution/2800-2899/2861.Maximum Number of Alloys/README_EN.md @@ -73,7 +73,7 @@ It can be proven that we can create at most 2 alloys. ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search We note that all alloys need to be made by the same machine, so we can enumerate which machine to use to make the alloy. @@ -83,8 +83,6 @@ The time complexity is $O(n \times k \times \log M)$, where $M$ is the upper bou -### **Python3** - ```python class Solution: def maxNumberOfAlloys( @@ -110,8 +108,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { int n; @@ -156,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -190,8 +184,6 @@ public: }; ``` -### **Go** - ```go func maxNumberOfAlloys(n int, k int, budget int, composition [][]int, stock []int, cost []int) int { isValid := func(target int) bool { @@ -221,8 +213,6 @@ func maxNumberOfAlloys(n int, k int, budget int, composition [][]int, stock []in } ``` -### **TypeScript** - ```ts function maxNumberOfAlloys( n: number, @@ -259,10 +249,6 @@ function maxNumberOfAlloys( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/README.md b/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/README.md index e415103f087de..1ae2626f49145 100644 --- a/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/README.md +++ b/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们注意到,如果一个数字可以表示成 $k \times j^2$ 的形式,那么所有该形式的数字的 $k$ 是相同的。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def maximumSum(self, nums: List[int]) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long maximumSum(List nums) { @@ -117,25 +107,6 @@ class Solution { } ``` -```java -class Solution { - public long maximumSum(List nums) { - long ans = 0; - int n = nums.size(); - for (int k = 1; k <= n; ++k) { - long t = 0; - for (int j = 1; k * j * j <= n; ++j) { - t += nums.get(k * j * j - 1); - } - ans = Math.max(ans, t); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -154,8 +125,6 @@ public: }; ``` -### **Go** - ```go func maximumSum(nums []int) (ans int64) { n := len(nums) @@ -170,8 +139,6 @@ func maximumSum(nums []int) (ans int64) { } ``` -### **TypeScript** - ```ts function maximumSum(nums: number[]): number { let ans = 0; @@ -187,10 +154,29 @@ function maximumSum(nums: number[]): number { } ``` -### **...** + + +### 方法二 -``` + +```java +class Solution { + public long maximumSum(List nums) { + long ans = 0; + int n = nums.size(); + for (int k = 1; k <= n; ++k) { + long t = 0; + for (int j = 1; k * j * j <= n; ++j) { + t += nums.get(k * j * j - 1); + } + ans = Math.max(ans, t); + } + return ans; + } +} ``` + + diff --git a/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/README_EN.md b/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/README_EN.md index 0a5362b7ebe00..9c886d266812b 100644 --- a/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/README_EN.md +++ b/solution/2800-2899/2862.Maximum Element-Sum of a Complete Subset of Indices/README_EN.md @@ -50,7 +50,7 @@ Hence, the maximum element-sum of a complete subset of indices is 19. ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We note that if a number can be expressed in the form of $k \times j^2$, then all numbers of this form have the same $k$. @@ -62,8 +62,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def maximumSum(self, nums: List[int]) -> int: @@ -79,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long maximumSum(List nums) { @@ -107,25 +103,6 @@ class Solution { } ``` -```java -class Solution { - public long maximumSum(List nums) { - long ans = 0; - int n = nums.size(); - for (int k = 1; k <= n; ++k) { - long t = 0; - for (int j = 1; k * j * j <= n; ++j) { - t += nums.get(k * j * j - 1); - } - ans = Math.max(ans, t); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -144,8 +121,6 @@ public: }; ``` -### **Go** - ```go func maximumSum(nums []int) (ans int64) { n := len(nums) @@ -160,8 +135,6 @@ func maximumSum(nums []int) (ans int64) { } ``` -### **TypeScript** - ```ts function maximumSum(nums: number[]): number { let ans = 0; @@ -177,10 +150,29 @@ function maximumSum(nums: number[]): number { } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + public long maximumSum(List nums) { + long ans = 0; + int n = nums.size(); + for (int k = 1; k <= n; ++k) { + long t = 0; + for (int j = 1; k * j * j <= n; ++j) { + t += nums.get(k * j * j - 1); + } + ans = Math.max(ans, t); + } + return ans; + } +} ``` + + diff --git a/solution/2800-2899/2863.Maximum Length of Semi-Decreasing Subarrays/README.md b/solution/2800-2899/2863.Maximum Length of Semi-Decreasing Subarrays/README.md index 5ef88e6386e2c..be676eb758069 100644 --- a/solution/2800-2899/2863.Maximum Length of Semi-Decreasing Subarrays/README.md +++ b/solution/2800-2899/2863.Maximum Length of Semi-Decreasing Subarrays/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:哈希表 + 排序** +### 方法一:哈希表 + 排序 题目实际上是求逆序对的最大长度,我们不妨用哈希表 $d$ 记录数组中每个数字 $x$ 对应的下标 $i$。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def maxSubarrayLength(self, nums: List[int]) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxSubarrayLength(int[] nums) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func maxSubarrayLength(nums []int) (ans int) { d := map[int][]int{} @@ -151,8 +137,6 @@ func maxSubarrayLength(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function maxSubarrayLength(nums: number[]): number { const d: Map = new Map(); @@ -174,10 +158,6 @@ function maxSubarrayLength(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2863.Maximum Length of Semi-Decreasing Subarrays/README_EN.md b/solution/2800-2899/2863.Maximum Length of Semi-Decreasing Subarrays/README_EN.md index 528993c6724aa..ca4c432824cbc 100644 --- a/solution/2800-2899/2863.Maximum Length of Semi-Decreasing Subarrays/README_EN.md +++ b/solution/2800-2899/2863.Maximum Length of Semi-Decreasing Subarrays/README_EN.md @@ -54,7 +54,7 @@ It can be shown that there aren't any subarrays with the given condition wit ## Solutions -**Solution 1: Hash Table + Sorting** +### Solution 1: Hash Table + Sorting The problem is essentially finding the maximum length of the inverse pairs. We can use a hash table $d$ to record the index $i$ corresponding to each number $x$ in the array. @@ -64,8 +64,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def maxSubarrayLength(self, nums: List[int]) -> int: @@ -79,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxSubarrayLength(int[] nums) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func maxSubarrayLength(nums []int) (ans int) { d := map[int][]int{} @@ -141,8 +133,6 @@ func maxSubarrayLength(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function maxSubarrayLength(nums: number[]): number { const d: Map = new Map(); @@ -164,10 +154,6 @@ function maxSubarrayLength(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2864.Maximum Odd Binary Number/README.md b/solution/2800-2899/2864.Maximum Odd Binary Number/README.md index 1cc7f9d3dbe09..2f87982eaf2cc 100644 --- a/solution/2800-2899/2864.Maximum Odd Binary Number/README.md +++ b/solution/2800-2899/2864.Maximum Odd Binary Number/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们先统计字符串 $s$ 中 $1$ 的个数,记为 $cnt$。那么我们将 $cnt - 1$ 个 $1$ 放在最高位,剩下的 $|s| - cnt$ 个 $0$ 放在后面,最后再加上一个 $1$ 即可。 @@ -54,10 +52,6 @@ -### **Python3** - - - ```python class Solution: def maximumOddBinaryNumber(self, s: str) -> str: @@ -65,10 +59,6 @@ class Solution: return "1" * (cnt - 1) + (len(s) - cnt) * "0" + "1" ``` -### **Java** - - - ```java class Solution { public String maximumOddBinaryNumber(String s) { @@ -83,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +91,6 @@ public: }; ``` -### **Go** - ```go func maximumOddBinaryNumber(s string) string { cnt := strings.Count(s, "1") @@ -112,8 +98,6 @@ func maximumOddBinaryNumber(s string) string { } ``` -### **TypeScript** - ```ts function maximumOddBinaryNumber(s: string): string { let cnt = 0; @@ -124,10 +108,6 @@ function maximumOddBinaryNumber(s: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2864.Maximum Odd Binary Number/README_EN.md b/solution/2800-2899/2864.Maximum Odd Binary Number/README_EN.md index e4070f588d9e1..6d90288afb160 100644 --- a/solution/2800-2899/2864.Maximum Odd Binary Number/README_EN.md +++ b/solution/2800-2899/2864.Maximum Odd Binary Number/README_EN.md @@ -40,7 +40,7 @@ ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy First, we count the number of '1's in the string $s$, denoted as $cnt$. Then, we place $cnt - 1$ '1's at the highest position, followed by the remaining $|s| - cnt$ '0's, and finally add one '1'. @@ -48,8 +48,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maximumOddBinaryNumber(self, s: str) -> str: @@ -57,8 +55,6 @@ class Solution: return "1" * (cnt - 1) + (len(s) - cnt) * "0" + "1" ``` -### **Java** - ```java class Solution { public String maximumOddBinaryNumber(String s) { @@ -73,8 +69,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +87,6 @@ public: }; ``` -### **Go** - ```go func maximumOddBinaryNumber(s string) string { cnt := strings.Count(s, "1") @@ -102,8 +94,6 @@ func maximumOddBinaryNumber(s string) string { } ``` -### **TypeScript** - ```ts function maximumOddBinaryNumber(s: string): string { let cnt = 0; @@ -114,10 +104,6 @@ function maximumOddBinaryNumber(s: string): string { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2865.Beautiful Towers I/README.md b/solution/2800-2899/2865.Beautiful Towers I/README.md index b5e46152d6757..875b420135950 100644 --- a/solution/2800-2899/2865.Beautiful Towers I/README.md +++ b/solution/2800-2899/2865.Beautiful Towers I/README.md @@ -71,15 +71,125 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举每一座塔作为最高塔,每一次向左右两边扩展,算出其他每个位置的高度,然后累加得到高度和 $t$。求出所有高度和的最大值即可。 时间复杂度 $O(n^2)$,空间复杂度 $O(1)$。其中 $n$ 为数组 $maxHeights$ 的长度。 -**方法二:动态规划 + 单调栈** + + +```python +class Solution: + def maximumSumOfHeights(self, maxHeights: List[int]) -> int: + ans, n = 0, len(maxHeights) + for i, x in enumerate(maxHeights): + y = t = x + for j in range(i - 1, -1, -1): + y = min(y, maxHeights[j]) + t += y + y = x + for j in range(i + 1, n): + y = min(y, maxHeights[j]) + t += y + ans = max(ans, t) + return ans +``` + +```java +class Solution { + public long maximumSumOfHeights(List maxHeights) { + long ans = 0; + int n = maxHeights.size(); + for (int i = 0; i < n; ++i) { + int y = maxHeights.get(i); + long t = y; + for (int j = i - 1; j >= 0; --j) { + y = Math.min(y, maxHeights.get(j)); + t += y; + } + y = maxHeights.get(i); + for (int j = i + 1; j < n; ++j) { + y = Math.min(y, maxHeights.get(j)); + t += y; + } + ans = Math.max(ans, t); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + long long maximumSumOfHeights(vector& maxHeights) { + long long ans = 0; + int n = maxHeights.size(); + for (int i = 0; i < n; ++i) { + long long t = maxHeights[i]; + int y = t; + for (int j = i - 1; ~j; --j) { + y = min(y, maxHeights[j]); + t += y; + } + y = maxHeights[i]; + for (int j = i + 1; j < n; ++j) { + y = min(y, maxHeights[j]); + t += y; + } + ans = max(ans, t); + } + return ans; + } +}; +``` + +```go +func maximumSumOfHeights(maxHeights []int) (ans int64) { + n := len(maxHeights) + for i, x := range maxHeights { + y, t := x, x + for j := i - 1; j >= 0; j-- { + y = min(y, maxHeights[j]) + t += y + } + y = x + for j := i + 1; j < n; j++ { + y = min(y, maxHeights[j]) + t += y + } + ans = max(ans, int64(t)) + } + return +} +``` + +```ts +function maximumSumOfHeights(maxHeights: number[]): number { + let ans = 0; + const n = maxHeights.length; + for (let i = 0; i < n; ++i) { + const x = maxHeights[i]; + let [y, t] = [x, x]; + for (let j = i - 1; ~j; --j) { + y = Math.min(y, maxHeights[j]); + t += y; + } + y = x; + for (let j = i + 1; j < n; ++j) { + y = Math.min(y, maxHeights[j]); + t += y; + } + ans = Math.max(ans, t); + } + return ans; +} +``` + + + +### 方法二:动态规划 + 单调栈 方法一的做法足以通过本题,但是时间复杂度较高。我们可以使用“动态规划 + 单调栈”来优化枚举的过程。 @@ -101,27 +211,6 @@ $$ -### **Python3** - - - -```python -class Solution: - def maximumSumOfHeights(self, maxHeights: List[int]) -> int: - ans, n = 0, len(maxHeights) - for i, x in enumerate(maxHeights): - y = t = x - for j in range(i - 1, -1, -1): - y = min(y, maxHeights[j]) - t += y - y = x - for j in range(i + 1, n): - y = min(y, maxHeights[j]) - t += y - ans = max(ans, t) - return ans -``` - ```python class Solution: def maximumSumOfHeights(self, maxHeights: List[int]) -> int: @@ -160,34 +249,6 @@ class Solution: return max(a + b - c for a, b, c in zip(f, g, maxHeights)) ``` -### **Java** - - - -```java -class Solution { - public long maximumSumOfHeights(List maxHeights) { - long ans = 0; - int n = maxHeights.size(); - for (int i = 0; i < n; ++i) { - int y = maxHeights.get(i); - long t = y; - for (int j = i - 1; j >= 0; --j) { - y = Math.min(y, maxHeights.get(j)); - t += y; - } - y = maxHeights.get(i); - for (int j = i + 1; j < n; ++j) { - y = Math.min(y, maxHeights.get(j)); - t += y; - } - ans = Math.max(ans, t); - } - return ans; - } -} -``` - ```java class Solution { public long maximumSumOfHeights(List maxHeights) { @@ -247,33 +308,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - long long maximumSumOfHeights(vector& maxHeights) { - long long ans = 0; - int n = maxHeights.size(); - for (int i = 0; i < n; ++i) { - long long t = maxHeights[i]; - int y = t; - for (int j = i - 1; ~j; --j) { - y = min(y, maxHeights[j]); - t += y; - } - y = maxHeights[i]; - for (int j = i + 1; j < n; ++j) { - y = min(y, maxHeights[j]); - t += y; - } - ans = max(ans, t); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -331,28 +365,6 @@ public: }; ``` -### **Go** - -```go -func maximumSumOfHeights(maxHeights []int) (ans int64) { - n := len(maxHeights) - for i, x := range maxHeights { - y, t := x, x - for j := i - 1; j >= 0; j-- { - y = min(y, maxHeights[j]) - t += y - } - y = x - for j := i + 1; j < n; j++ { - y = min(y, maxHeights[j]) - t += y - } - ans = max(ans, int64(t)) - } - return -} -``` - ```go func maximumSumOfHeights(maxHeights []int) (ans int64) { n := len(maxHeights) @@ -415,30 +427,6 @@ func maximumSumOfHeights(maxHeights []int) (ans int64) { } ``` -### **TypeScript** - -```ts -function maximumSumOfHeights(maxHeights: number[]): number { - let ans = 0; - const n = maxHeights.length; - for (let i = 0; i < n; ++i) { - const x = maxHeights[i]; - let [y, t] = [x, x]; - for (let j = i - 1; ~j; --j) { - y = Math.min(y, maxHeights[j]); - t += y; - } - y = x; - for (let j = i + 1; j < n; ++j) { - y = Math.min(y, maxHeights[j]); - t += y; - } - ans = Math.max(ans, t); - } - return ans; -} -``` - ```ts function maximumSumOfHeights(maxHeights: number[]): number { const n = maxHeights.length; @@ -494,10 +482,6 @@ function maximumSumOfHeights(maxHeights: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2865.Beautiful Towers I/README_EN.md b/solution/2800-2899/2865.Beautiful Towers I/README_EN.md index f03ac65c1a887..8d11881d7f14d 100644 --- a/solution/2800-2899/2865.Beautiful Towers I/README_EN.md +++ b/solution/2800-2899/2865.Beautiful Towers I/README_EN.md @@ -67,13 +67,125 @@ It can be shown that there exists no other beautiful configuration with a sum of ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We can enumerate each tower as the tallest tower, each time expanding to the left and right, calculating the height of each other position, and then accumulating to get the height sum $t$. The maximum of all height sums is the answer. The time complexity is $O(n^2)$, and the space complexity is $O(1)$. Here, $n$ is the length of the array $maxHeights$. -**Solution 2: Dynamic Programming + Monotonic Stack** + + +```python +class Solution: + def maximumSumOfHeights(self, maxHeights: List[int]) -> int: + ans, n = 0, len(maxHeights) + for i, x in enumerate(maxHeights): + y = t = x + for j in range(i - 1, -1, -1): + y = min(y, maxHeights[j]) + t += y + y = x + for j in range(i + 1, n): + y = min(y, maxHeights[j]) + t += y + ans = max(ans, t) + return ans +``` + +```java +class Solution { + public long maximumSumOfHeights(List maxHeights) { + long ans = 0; + int n = maxHeights.size(); + for (int i = 0; i < n; ++i) { + int y = maxHeights.get(i); + long t = y; + for (int j = i - 1; j >= 0; --j) { + y = Math.min(y, maxHeights.get(j)); + t += y; + } + y = maxHeights.get(i); + for (int j = i + 1; j < n; ++j) { + y = Math.min(y, maxHeights.get(j)); + t += y; + } + ans = Math.max(ans, t); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + long long maximumSumOfHeights(vector& maxHeights) { + long long ans = 0; + int n = maxHeights.size(); + for (int i = 0; i < n; ++i) { + long long t = maxHeights[i]; + int y = t; + for (int j = i - 1; ~j; --j) { + y = min(y, maxHeights[j]); + t += y; + } + y = maxHeights[i]; + for (int j = i + 1; j < n; ++j) { + y = min(y, maxHeights[j]); + t += y; + } + ans = max(ans, t); + } + return ans; + } +}; +``` + +```go +func maximumSumOfHeights(maxHeights []int) (ans int64) { + n := len(maxHeights) + for i, x := range maxHeights { + y, t := x, x + for j := i - 1; j >= 0; j-- { + y = min(y, maxHeights[j]) + t += y + } + y = x + for j := i + 1; j < n; j++ { + y = min(y, maxHeights[j]) + t += y + } + ans = max(ans, int64(t)) + } + return +} +``` + +```ts +function maximumSumOfHeights(maxHeights: number[]): number { + let ans = 0; + const n = maxHeights.length; + for (let i = 0; i < n; ++i) { + const x = maxHeights[i]; + let [y, t] = [x, x]; + for (let j = i - 1; ~j; --j) { + y = Math.min(y, maxHeights[j]); + t += y; + } + y = x; + for (let j = i + 1; j < n; ++j) { + y = Math.min(y, maxHeights[j]); + t += y; + } + ans = Math.max(ans, t); + } + return ans; +} +``` + + + +### Solution 2: Dynamic Programming + Monotonic Stack Solution 1 is sufficient to pass this problem, but the time complexity is relatively high. We can use "Dynamic Programming + Monotonic Stack" to optimize the enumeration process. @@ -95,25 +207,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - -```python -class Solution: - def maximumSumOfHeights(self, maxHeights: List[int]) -> int: - ans, n = 0, len(maxHeights) - for i, x in enumerate(maxHeights): - y = t = x - for j in range(i - 1, -1, -1): - y = min(y, maxHeights[j]) - t += y - y = x - for j in range(i + 1, n): - y = min(y, maxHeights[j]) - t += y - ans = max(ans, t) - return ans -``` - ```python class Solution: def maximumSumOfHeights(self, maxHeights: List[int]) -> int: @@ -152,32 +245,6 @@ class Solution: return max(a + b - c for a, b, c in zip(f, g, maxHeights)) ``` -### **Java** - -```java -class Solution { - public long maximumSumOfHeights(List maxHeights) { - long ans = 0; - int n = maxHeights.size(); - for (int i = 0; i < n; ++i) { - int y = maxHeights.get(i); - long t = y; - for (int j = i - 1; j >= 0; --j) { - y = Math.min(y, maxHeights.get(j)); - t += y; - } - y = maxHeights.get(i); - for (int j = i + 1; j < n; ++j) { - y = Math.min(y, maxHeights.get(j)); - t += y; - } - ans = Math.max(ans, t); - } - return ans; - } -} -``` - ```java class Solution { public long maximumSumOfHeights(List maxHeights) { @@ -237,33 +304,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - long long maximumSumOfHeights(vector& maxHeights) { - long long ans = 0; - int n = maxHeights.size(); - for (int i = 0; i < n; ++i) { - long long t = maxHeights[i]; - int y = t; - for (int j = i - 1; ~j; --j) { - y = min(y, maxHeights[j]); - t += y; - } - y = maxHeights[i]; - for (int j = i + 1; j < n; ++j) { - y = min(y, maxHeights[j]); - t += y; - } - ans = max(ans, t); - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -321,28 +361,6 @@ public: }; ``` -### **Go** - -```go -func maximumSumOfHeights(maxHeights []int) (ans int64) { - n := len(maxHeights) - for i, x := range maxHeights { - y, t := x, x - for j := i - 1; j >= 0; j-- { - y = min(y, maxHeights[j]) - t += y - } - y = x - for j := i + 1; j < n; j++ { - y = min(y, maxHeights[j]) - t += y - } - ans = max(ans, int64(t)) - } - return -} -``` - ```go func maximumSumOfHeights(maxHeights []int) (ans int64) { n := len(maxHeights) @@ -405,30 +423,6 @@ func maximumSumOfHeights(maxHeights []int) (ans int64) { } ``` -### **TypeScript** - -```ts -function maximumSumOfHeights(maxHeights: number[]): number { - let ans = 0; - const n = maxHeights.length; - for (let i = 0; i < n; ++i) { - const x = maxHeights[i]; - let [y, t] = [x, x]; - for (let j = i - 1; ~j; --j) { - y = Math.min(y, maxHeights[j]); - t += y; - } - y = x; - for (let j = i + 1; j < n; ++j) { - y = Math.min(y, maxHeights[j]); - t += y; - } - ans = Math.max(ans, t); - } - return ans; -} -``` - ```ts function maximumSumOfHeights(maxHeights: number[]): number { const n = maxHeights.length; @@ -484,10 +478,6 @@ function maximumSumOfHeights(maxHeights: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2866.Beautiful Towers II/README.md b/solution/2800-2899/2866.Beautiful Towers II/README.md index 36a3fdeab41f9..fd8a7dca82fe8 100644 --- a/solution/2800-2899/2866.Beautiful Towers II/README.md +++ b/solution/2800-2899/2866.Beautiful Towers II/README.md @@ -71,9 +71,7 @@ ## 解法 - - -**方法一:动态规划 + 单调栈** +### 方法一:动态规划 + 单调栈 我们定义 $f[i]$ 表示前 $i+1$ 座塔中,以最后一座塔作为最高塔的美丽塔方案的高度和。我们可以得到如下的状态转移方程: @@ -93,10 +91,6 @@ $$ -### **Python3** - - - ```python class Solution: def maximumSumOfHeights(self, maxHeights: List[int]) -> int: @@ -135,10 +129,6 @@ class Solution: return max(a + b - c for a, b, c in zip(f, g, maxHeights)) ``` -### **Java** - - - ```java class Solution { public long maximumSumOfHeights(List maxHeights) { @@ -198,8 +188,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -257,8 +245,6 @@ public: }; ``` -### **Go** - ```go func maximumSumOfHeights(maxHeights []int) (ans int64) { n := len(maxHeights) @@ -321,8 +307,6 @@ func maximumSumOfHeights(maxHeights []int) (ans int64) { } ``` -### **TypeScript** - ```ts function maximumSumOfHeights(maxHeights: number[]): number { const n = maxHeights.length; @@ -378,10 +362,6 @@ function maximumSumOfHeights(maxHeights: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2866.Beautiful Towers II/README_EN.md b/solution/2800-2899/2866.Beautiful Towers II/README_EN.md index 57c93c9ae9bb1..b0f72c2ac3b5b 100644 --- a/solution/2800-2899/2866.Beautiful Towers II/README_EN.md +++ b/solution/2800-2899/2866.Beautiful Towers II/README_EN.md @@ -67,7 +67,7 @@ It can be shown that there exists no other beautiful configuration with a sum of ## Solutions -**Solution 1: Dynamic Programming + Monotonic Stack** +### Solution 1: Dynamic Programming + Monotonic Stack We define $f[i]$ to represent the height sum of the beautiful tower scheme with the last tower as the tallest tower among the first $i+1$ towers. We can get the following state transition equation: @@ -87,8 +87,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maximumSumOfHeights(self, maxHeights: List[int]) -> int: @@ -127,8 +125,6 @@ class Solution: return max(a + b - c for a, b, c in zip(f, g, maxHeights)) ``` -### **Java** - ```java class Solution { public long maximumSumOfHeights(List maxHeights) { @@ -188,8 +184,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -247,8 +241,6 @@ public: }; ``` -### **Go** - ```go func maximumSumOfHeights(maxHeights []int) (ans int64) { n := len(maxHeights) @@ -311,8 +303,6 @@ func maximumSumOfHeights(maxHeights []int) (ans int64) { } ``` -### **TypeScript** - ```ts function maximumSumOfHeights(maxHeights: number[]): number { const n = maxHeights.length; @@ -368,10 +358,6 @@ function maximumSumOfHeights(maxHeights: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2867.Count Valid Paths in a Tree/README.md b/solution/2800-2899/2867.Count Valid Paths in a Tree/README.md index 1b45e79c70193..99a05f20675b8 100644 --- a/solution/2800-2899/2867.Count Valid Paths in a Tree/README.md +++ b/solution/2800-2899/2867.Count Valid Paths in a Tree/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:预处理 + 并查集 + 枚举** +### 方法一:预处理 + 并查集 + 枚举 我们可以预处理得到 $[1, n]$ 中的所有质数,其中 $prime[i]$ 表示 $i$ 是否为质数。 @@ -83,10 +81,6 @@ -### **Python3** - - - ```python class UnionFind: def __init__(self, n): @@ -143,55 +137,6 @@ class Solution: return ans ``` -```python -class Solution: - def countPaths(self, n: int, edges: List[List[int]]) -> int: - def mul(x, y): - return x * y - - def dfs(x, f, con, prime, r): - v = [1 - prime[x], prime[x]] - for y in con[x]: - if y == f: - continue - p = dfs(y, x, con, prime, r) - r[0] += mul(p[0], v[1]) + mul(p[1], v[0]) - if prime[x]: - v[1] += p[0] - else: - v[0] += p[0] - v[1] += p[1] - return v - - prime = [True] * (n + 1) - prime[1] = False - - all_primes = [] - for i in range(2, n + 1): - if prime[i]: - all_primes.append(i) - for x in all_primes: - temp = i * x - if temp > n: - break - prime[temp] = False - if i % x == 0: - break - - con = [[] for _ in range(n + 1)] - for e in edges: - con[e[0]].append(e[1]) - con[e[1]].append(e[0]) - - r = [0] - dfs(1, 0, con, prime, r) - return r[0] -``` - -### **Java** - - - ```java class PrimeTable { private final boolean[] prime; @@ -289,80 +234,6 @@ class Solution { } ``` -```java -class Solution { - public long countPaths(int n, int[][] edges) { - List prime = new ArrayList<>(n + 1); - for (int i = 0; i <= n; ++i) { - prime.add(true); - } - prime.set(1, false); - - List all = new ArrayList<>(); - for (int i = 2; i <= n; ++i) { - if (prime.get(i)) { - all.add(i); - } - for (int x : all) { - int temp = i * x; - if (temp > n) { - break; - } - prime.set(temp, false); - if (i % x == 0) { - break; - } - } - } - - List> con = new ArrayList<>(n + 1); - for (int i = 0; i <= n; ++i) { - con.add(new ArrayList<>()); - } - for (int[] e : edges) { - con.get(e[0]).add(e[1]); - con.get(e[1]).add(e[0]); - } - - long[] r = {0}; - dfs(1, 0, con, prime, r); - return r[0]; - } - - private long mul(long x, long y) { - return x * y; - } - - private class Pair { - int first; - int second; - - Pair(int first, int second) { - this.first = first; - this.second = second; - } - } - - private Pair dfs(int x, int f, List> con, List prime, long[] r) { - Pair v = new Pair(!prime.get(x) ? 1 : 0, prime.get(x) ? 1 : 0); - for (int y : con.get(x)) { - if (y == f) continue; - Pair p = dfs(y, x, con, prime, r); - r[0] += mul(p.first, v.second) + mul(p.second, v.first); - if (prime.get(x)) { - v.second += p.first; - } else { - v.first += p.first; - v.second += p.second; - } - } - return v; - } -} -``` - -### **C++** - ```cpp const int mx = 1e5 + 10; bool prime[mx + 1]; @@ -448,62 +319,6 @@ public: }; ``` -```cpp -class Solution { - long long mul(long long x, long long y) { - return x * y; - } - - pair dfs(int x, int f, const vector>& con, const vector& prime, long long& r) { - pair v = {!prime[x], prime[x]}; - for (int y : con[x]) { - if (y == f) continue; - const auto& p = dfs(y, x, con, prime, r); - r += mul(p.first, v.second) + mul(p.second, v.first); - if (prime[x]) { - v.second += p.first; - } else { - v.first += p.first; - v.second += p.second; - } - } - return v; - } - -public: - long long countPaths(int n, vector>& edges) { - vector prime(n + 1, true); - prime[1] = false; - vector all; - for (int i = 2; i <= n; ++i) { - if (prime[i]) { - all.push_back(i); - } - for (int x : all) { - const int temp = i * x; - if (temp > n) { - break; - } - prime[temp] = false; - if (i % x == 0) { - break; - } - } - } - vector> con(n + 1); - for (const auto& e : edges) { - con[e[0]].push_back(e[1]); - con[e[1]].push_back(e[0]); - } - long long r = 0; - dfs(1, 0, con, prime, r); - return r; - } -}; -``` - -### **Go** - ```go const mx int = 1e5 + 10 @@ -589,8 +404,6 @@ func countPaths(n int, edges [][]int) (ans int64) { } ``` -### **TypeScript** - ```ts const mx = 100010; const prime = Array(mx).fill(true); @@ -669,10 +482,183 @@ function countPaths(n: number, edges: number[][]): number { } ``` -### **...** + + +### 方法二 + + + +```python +class Solution: + def countPaths(self, n: int, edges: List[List[int]]) -> int: + def mul(x, y): + return x * y + + def dfs(x, f, con, prime, r): + v = [1 - prime[x], prime[x]] + for y in con[x]: + if y == f: + continue + p = dfs(y, x, con, prime, r) + r[0] += mul(p[0], v[1]) + mul(p[1], v[0]) + if prime[x]: + v[1] += p[0] + else: + v[0] += p[0] + v[1] += p[1] + return v + + prime = [True] * (n + 1) + prime[1] = False + + all_primes = [] + for i in range(2, n + 1): + if prime[i]: + all_primes.append(i) + for x in all_primes: + temp = i * x + if temp > n: + break + prime[temp] = False + if i % x == 0: + break + + con = [[] for _ in range(n + 1)] + for e in edges: + con[e[0]].append(e[1]) + con[e[1]].append(e[0]) + r = [0] + dfs(1, 0, con, prime, r) + return r[0] ``` +```java +class Solution { + public long countPaths(int n, int[][] edges) { + List prime = new ArrayList<>(n + 1); + for (int i = 0; i <= n; ++i) { + prime.add(true); + } + prime.set(1, false); + + List all = new ArrayList<>(); + for (int i = 2; i <= n; ++i) { + if (prime.get(i)) { + all.add(i); + } + for (int x : all) { + int temp = i * x; + if (temp > n) { + break; + } + prime.set(temp, false); + if (i % x == 0) { + break; + } + } + } + + List> con = new ArrayList<>(n + 1); + for (int i = 0; i <= n; ++i) { + con.add(new ArrayList<>()); + } + for (int[] e : edges) { + con.get(e[0]).add(e[1]); + con.get(e[1]).add(e[0]); + } + + long[] r = {0}; + dfs(1, 0, con, prime, r); + return r[0]; + } + + private long mul(long x, long y) { + return x * y; + } + + private class Pair { + int first; + int second; + + Pair(int first, int second) { + this.first = first; + this.second = second; + } + } + + private Pair dfs(int x, int f, List> con, List prime, long[] r) { + Pair v = new Pair(!prime.get(x) ? 1 : 0, prime.get(x) ? 1 : 0); + for (int y : con.get(x)) { + if (y == f) continue; + Pair p = dfs(y, x, con, prime, r); + r[0] += mul(p.first, v.second) + mul(p.second, v.first); + if (prime.get(x)) { + v.second += p.first; + } else { + v.first += p.first; + v.second += p.second; + } + } + return v; + } +} +``` + +```cpp +class Solution { + long long mul(long long x, long long y) { + return x * y; + } + + pair dfs(int x, int f, const vector>& con, const vector& prime, long long& r) { + pair v = {!prime[x], prime[x]}; + for (int y : con[x]) { + if (y == f) continue; + const auto& p = dfs(y, x, con, prime, r); + r += mul(p.first, v.second) + mul(p.second, v.first); + if (prime[x]) { + v.second += p.first; + } else { + v.first += p.first; + v.second += p.second; + } + } + return v; + } + +public: + long long countPaths(int n, vector>& edges) { + vector prime(n + 1, true); + prime[1] = false; + vector all; + for (int i = 2; i <= n; ++i) { + if (prime[i]) { + all.push_back(i); + } + for (int x : all) { + const int temp = i * x; + if (temp > n) { + break; + } + prime[temp] = false; + if (i % x == 0) { + break; + } + } + } + vector> con(n + 1); + for (const auto& e : edges) { + con[e[0]].push_back(e[1]); + con[e[1]].push_back(e[0]); + } + long long r = 0; + dfs(1, 0, con, prime, r); + return r; + } +}; ``` + + diff --git a/solution/2800-2899/2867.Count Valid Paths in a Tree/README_EN.md b/solution/2800-2899/2867.Count Valid Paths in a Tree/README_EN.md index 15b18eac4bfe9..c80cfc688517d 100644 --- a/solution/2800-2899/2867.Count Valid Paths in a Tree/README_EN.md +++ b/solution/2800-2899/2867.Count Valid Paths in a Tree/README_EN.md @@ -59,7 +59,7 @@ It can be shown that there are only 6 valid paths. ## Solutions -**Solution 1: Preprocessing + Union-Find + Enumeration** +### Solution 1: Preprocessing + Union-Find + Enumeration We can preprocess to get all the prime numbers in $[1, n]$, where $prime[i]$ indicates whether $i$ is a prime number. @@ -73,8 +73,6 @@ The time complexity is $O(n \times \alpha(n))$, and the space complexity is $O(n -### **Python3** - ```python class UnionFind: def __init__(self, n): @@ -131,8 +129,6 @@ class Solution: return ans ``` -### **Java** - ```java class PrimeTable { private final boolean[] prime; @@ -230,80 +226,6 @@ class Solution { } ``` -```java -class Solution { - public long countPaths(int n, int[][] edges) { - List prime = new ArrayList<>(n + 1); - for (int i = 0; i <= n; ++i) { - prime.add(true); - } - prime.set(1, false); - - List all = new ArrayList<>(); - for (int i = 2; i <= n; ++i) { - if (prime.get(i)) { - all.add(i); - } - for (int x : all) { - int temp = i * x; - if (temp > n) { - break; - } - prime.set(temp, false); - if (i % x == 0) { - break; - } - } - } - - List> con = new ArrayList<>(n + 1); - for (int i = 0; i <= n; ++i) { - con.add(new ArrayList<>()); - } - for (int[] e : edges) { - con.get(e[0]).add(e[1]); - con.get(e[1]).add(e[0]); - } - - long[] r = {0}; - dfs(1, 0, con, prime, r); - return r[0]; - } - - private long mul(long x, long y) { - return x * y; - } - - private class Pair { - int first; - int second; - - Pair(int first, int second) { - this.first = first; - this.second = second; - } - } - - private Pair dfs(int x, int f, List> con, List prime, long[] r) { - Pair v = new Pair(!prime.get(x) ? 1 : 0, prime.get(x) ? 1 : 0); - for (int y : con.get(x)) { - if (y == f) continue; - Pair p = dfs(y, x, con, prime, r); - r[0] += mul(p.first, v.second) + mul(p.second, v.first); - if (prime.get(x)) { - v.second += p.first; - } else { - v.first += p.first; - v.second += p.second; - } - } - return v; - } -} -``` - -### **C++** - ```cpp const int mx = 1e5 + 10; bool prime[mx + 1]; @@ -389,62 +311,6 @@ public: }; ``` -```cpp -class Solution { - long long mul(long long x, long long y) { - return x * y; - } - - pair dfs(int x, int f, const vector>& con, const vector& prime, long long& r) { - pair v = {!prime[x], prime[x]}; - for (int y : con[x]) { - if (y == f) continue; - const auto& p = dfs(y, x, con, prime, r); - r += mul(p.first, v.second) + mul(p.second, v.first); - if (prime[x]) { - v.second += p.first; - } else { - v.first += p.first; - v.second += p.second; - } - } - return v; - } - -public: - long long countPaths(int n, vector>& edges) { - vector prime(n + 1, true); - prime[1] = false; - vector all; - for (int i = 2; i <= n; ++i) { - if (prime[i]) { - all.push_back(i); - } - for (int x : all) { - const int temp = i * x; - if (temp > n) { - break; - } - prime[temp] = false; - if (i % x == 0) { - break; - } - } - } - vector> con(n + 1); - for (const auto& e : edges) { - con[e[0]].push_back(e[1]); - con[e[1]].push_back(e[0]); - } - long long r = 0; - dfs(1, 0, con, prime, r); - return r; - } -}; -``` - -### **Go** - ```go const mx int = 1e5 + 10 @@ -530,8 +396,6 @@ func countPaths(n int, edges [][]int) (ans int64) { } ``` -### **TypeScript** - ```ts const mx = 100010; const prime = Array(mx).fill(true); @@ -610,10 +474,183 @@ function countPaths(n: number, edges: number[][]): number { } ``` -### **...** + + +### Solution 2 + + + +```python +class Solution: + def countPaths(self, n: int, edges: List[List[int]]) -> int: + def mul(x, y): + return x * y + + def dfs(x, f, con, prime, r): + v = [1 - prime[x], prime[x]] + for y in con[x]: + if y == f: + continue + p = dfs(y, x, con, prime, r) + r[0] += mul(p[0], v[1]) + mul(p[1], v[0]) + if prime[x]: + v[1] += p[0] + else: + v[0] += p[0] + v[1] += p[1] + return v + + prime = [True] * (n + 1) + prime[1] = False + + all_primes = [] + for i in range(2, n + 1): + if prime[i]: + all_primes.append(i) + for x in all_primes: + temp = i * x + if temp > n: + break + prime[temp] = False + if i % x == 0: + break + + con = [[] for _ in range(n + 1)] + for e in edges: + con[e[0]].append(e[1]) + con[e[1]].append(e[0]) + + r = [0] + dfs(1, 0, con, prime, r) + return r[0] +``` + +```java +class Solution { + public long countPaths(int n, int[][] edges) { + List prime = new ArrayList<>(n + 1); + for (int i = 0; i <= n; ++i) { + prime.add(true); + } + prime.set(1, false); + + List all = new ArrayList<>(); + for (int i = 2; i <= n; ++i) { + if (prime.get(i)) { + all.add(i); + } + for (int x : all) { + int temp = i * x; + if (temp > n) { + break; + } + prime.set(temp, false); + if (i % x == 0) { + break; + } + } + } + + List> con = new ArrayList<>(n + 1); + for (int i = 0; i <= n; ++i) { + con.add(new ArrayList<>()); + } + for (int[] e : edges) { + con.get(e[0]).add(e[1]); + con.get(e[1]).add(e[0]); + } + + long[] r = {0}; + dfs(1, 0, con, prime, r); + return r[0]; + } + private long mul(long x, long y) { + return x * y; + } + + private class Pair { + int first; + int second; + + Pair(int first, int second) { + this.first = first; + this.second = second; + } + } + + private Pair dfs(int x, int f, List> con, List prime, long[] r) { + Pair v = new Pair(!prime.get(x) ? 1 : 0, prime.get(x) ? 1 : 0); + for (int y : con.get(x)) { + if (y == f) continue; + Pair p = dfs(y, x, con, prime, r); + r[0] += mul(p.first, v.second) + mul(p.second, v.first); + if (prime.get(x)) { + v.second += p.first; + } else { + v.first += p.first; + v.second += p.second; + } + } + return v; + } +} ``` +```cpp +class Solution { + long long mul(long long x, long long y) { + return x * y; + } + + pair dfs(int x, int f, const vector>& con, const vector& prime, long long& r) { + pair v = {!prime[x], prime[x]}; + for (int y : con[x]) { + if (y == f) continue; + const auto& p = dfs(y, x, con, prime, r); + r += mul(p.first, v.second) + mul(p.second, v.first); + if (prime[x]) { + v.second += p.first; + } else { + v.first += p.first; + v.second += p.second; + } + } + return v; + } + +public: + long long countPaths(int n, vector>& edges) { + vector prime(n + 1, true); + prime[1] = false; + vector all; + for (int i = 2; i <= n; ++i) { + if (prime[i]) { + all.push_back(i); + } + for (int x : all) { + const int temp = i * x; + if (temp > n) { + break; + } + prime[temp] = false; + if (i % x == 0) { + break; + } + } + } + vector> con(n + 1); + for (const auto& e : edges) { + con[e[0]].push_back(e[1]); + con[e[1]].push_back(e[0]); + } + long long r = 0; + dfs(1, 0, con, prime, r); + return r; + } +}; ``` + + diff --git a/solution/2800-2899/2868.The Wording Game/README.md b/solution/2800-2899/2868.The Wording Game/README.md index 9087e9f22c041..7c033c40ac7bf 100644 --- a/solution/2800-2899/2868.The Wording Game/README.md +++ b/solution/2800-2899/2868.The Wording Game/README.md @@ -84,9 +84,7 @@ Bob 无法出牌,因为他的两个单词的第一个字母都比 Alice 的单 ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们记当前轮到 $Alice$ 的回合为 $k=0$,轮到 $Bob$ 的回合为 $k=1$。我们用 $i$ 记录 $Alice$ 的下标,用 $j$ 记录 $Bob$ 的下标,用 $w$ 记录当前轮到的玩家的单词。初始时 $i=1$, $j=0$, $w=a[0]$。 @@ -100,10 +98,6 @@ Bob 无法出牌,因为他的两个单词的第一个字母都比 Alice 的单 -### **Python3** - - - ```python class Solution: def canAliceWin(self, a: List[str], b: List[str]) -> bool: @@ -126,10 +120,6 @@ class Solution: i += 1 ``` -### **Java** - - - ```java class Solution { public boolean canAliceWin(String[] a, String[] b) { @@ -163,8 +153,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -196,8 +184,6 @@ public: }; ``` -### **Go** - ```go func canAliceWin(a []string, b []string) bool { i, j, k := 1, 0, 1 @@ -226,8 +212,6 @@ func canAliceWin(a []string, b []string) bool { } ``` -### **TypeScript** - ```ts function canAliceWin(a: string[], b: string[]): boolean { let [i, j, k] = [1, 0, 1]; @@ -256,10 +240,6 @@ function canAliceWin(a: string[], b: string[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2868.The Wording Game/README_EN.md b/solution/2800-2899/2868.The Wording Game/README_EN.md index 2eb18c7fb57a6..d129e77e075f0 100644 --- a/solution/2800-2899/2868.The Wording Game/README_EN.md +++ b/solution/2800-2899/2868.The Wording Game/README_EN.md @@ -69,7 +69,7 @@ So Alice wins, and the game ends. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We use $k$ to record whose turn it is, where $k=0$ means it is Alice's turn, and $k=1$ means it is Bob's turn. We use $i$ to record Alice's index, $j$ to record Bob's index, and $w$ to record the current word. Initially, we set $i=1$, $j=0$, and $w=a[0]$. @@ -83,8 +83,6 @@ The time complexity is $O(m+n)$, where $m$ and $n$ are the lengths of arrays $a$ -### **Python3** - ```python class Solution: def canAliceWin(self, a: List[str], b: List[str]) -> bool: @@ -107,8 +105,6 @@ class Solution: i += 1 ``` -### **Java** - ```java class Solution { public boolean canAliceWin(String[] a, String[] b) { @@ -142,8 +138,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +169,6 @@ public: }; ``` -### **Go** - ```go func canAliceWin(a []string, b []string) bool { i, j, k := 1, 0, 1 @@ -205,8 +197,6 @@ func canAliceWin(a []string, b []string) bool { } ``` -### **TypeScript** - ```ts function canAliceWin(a: string[], b: string[]): boolean { let [i, j, k] = [1, 0, 1]; @@ -235,10 +225,6 @@ function canAliceWin(a: string[], b: string[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2869.Minimum Operations to Collect Elements/README.md b/solution/2800-2899/2869.Minimum Operations to Collect Elements/README.md index 94b8c21e8fb50..0922f60b48649 100644 --- a/solution/2800-2899/2869.Minimum Operations to Collect Elements/README.md +++ b/solution/2800-2899/2869.Minimum Operations to Collect Elements/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:逆序遍历** +### 方法一:逆序遍历 我们可以逆序遍历数组,每次遍历到的元素如果小于等于 $k$,且没有被添加过,就将其添加到集合中,直到集合中包含了元素 $1$ 到 $k$ 为止。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, nums: List[int], k: int) -> int: @@ -80,10 +74,6 @@ class Solution: return n - i ``` -### **Java** - - - ```java class Solution { public int minOperations(List nums, int k) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int, k int) int { isAdded := make([]bool, k) @@ -146,8 +132,6 @@ func minOperations(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function minOperations(nums: number[], k: number): number { const n = nums.length; @@ -166,10 +150,6 @@ function minOperations(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2869.Minimum Operations to Collect Elements/README_EN.md b/solution/2800-2899/2869.Minimum Operations to Collect Elements/README_EN.md index eeb0568b6eca9..e4a8fc756c9f1 100644 --- a/solution/2800-2899/2869.Minimum Operations to Collect Elements/README_EN.md +++ b/solution/2800-2899/2869.Minimum Operations to Collect Elements/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Traverse in Reverse Order** +### Solution 1: Traverse in Reverse Order We can traverse the array in reverse order. For each element encountered during the traversal that is less than or equal to $k$ and has not been added to the set yet, we add it to the set until the set contains elements from $1$ to $k$. @@ -55,8 +55,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def minOperations(self, nums: List[int], k: int) -> int: @@ -72,8 +70,6 @@ class Solution: return n - i ``` -### **Java** - ```java class Solution { public int minOperations(List nums, int k) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +110,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int, k int) int { isAdded := make([]bool, k) @@ -136,8 +128,6 @@ func minOperations(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function minOperations(nums: number[], k: number): number { const n = nums.length; @@ -156,10 +146,6 @@ function minOperations(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2870.Minimum Number of Operations to Make Array Empty/README.md b/solution/2800-2899/2870.Minimum Number of Operations to Make Array Empty/README.md index 692e49ca0c79e..44b9c6469daf5 100644 --- a/solution/2800-2899/2870.Minimum Number of Operations to Make Array Empty/README.md +++ b/solution/2800-2899/2870.Minimum Number of Operations to Make Array Empty/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:哈希表 + 贪心** +### 方法一:哈希表 + 贪心 我们用一个哈希表 $count$ 统计数组中每个元素出现的次数,然后遍历哈希表,对于每个元素 $x$,如果 $x$ 出现的次数为 $c$,那么我们可以进行 $\lfloor \frac{c+2}{3} \rfloor$ 次操作,将 $x$ 删除,最后我们返回所有元素的操作次数之和即可。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, nums: List[int]) -> int: @@ -77,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minOperations(int[] nums) { @@ -110,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int) (ans int) { count := map[int]int{} @@ -150,8 +136,6 @@ func minOperations(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function minOperations(nums: number[]): number { const count: Map = new Map(); @@ -169,10 +153,6 @@ function minOperations(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2870.Minimum Number of Operations to Make Array Empty/README_EN.md b/solution/2800-2899/2870.Minimum Number of Operations to Make Array Empty/README_EN.md index 2b96ef6b2b985..62015c4236754 100644 --- a/solution/2800-2899/2870.Minimum Number of Operations to Make Array Empty/README_EN.md +++ b/solution/2800-2899/2870.Minimum Number of Operations to Make Array Empty/README_EN.md @@ -47,7 +47,7 @@ It can be shown that we cannot make the array empty in less than 4 operations. ## Solutions -**Solution 1: Hash Table + Greedy** +### Solution 1: Hash Table + Greedy We use a hash table $count$ to count the number of occurrences of each element in the array. Then we traverse the hash table. For each element $x$, if it appears $c$ times, we can perform $\lfloor \frac{c+2}{3} \rfloor$ operations to delete $x$. Finally, we return the sum of the number of operations for all elements. @@ -55,8 +55,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def minOperations(self, nums: List[int]) -> int: @@ -69,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minOperations(int[] nums) { @@ -100,8 +96,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int) (ans int) { count := map[int]int{} @@ -140,8 +132,6 @@ func minOperations(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function minOperations(nums: number[]): number { const count: Map = new Map(); @@ -159,10 +149,6 @@ function minOperations(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2871.Split Array Into Maximum Number of Subarrays/README.md b/solution/2800-2899/2871.Split Array Into Maximum Number of Subarrays/README.md index 22adb4c1b72ad..a96af63ea2af6 100644 --- a/solution/2800-2899/2871.Split Array Into Maximum Number of Subarrays/README.md +++ b/solution/2800-2899/2871.Split Array Into Maximum Number of Subarrays/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:贪心 + 位运算** +### 方法一:贪心 + 位运算 我们初始化一个变量 $score$,用来记录当前子数组的分数,初始时 $score = -1$。然后我们遍历数组,对于每个元素 $num$,我们将 $score$ 与 $num$ 进行按位与运算,然后将结果赋值给 $score$。如果 $score = 0$,说明当前子数组的分数为 $0$,我们就可以将当前子数组分割出来,然后将 $score$ 重置为 $-1$。最后我们返回分割出的子数组的个数。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def maxSubarrays(self, nums: List[int]) -> int: @@ -82,10 +76,6 @@ class Solution: return 1 if ans == 1 else ans - 1 ``` -### **Java** - - - ```java class Solution { public int maxSubarrays(int[] nums) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func maxSubarrays(nums []int) int { ans, score := 1, -1 @@ -141,8 +127,6 @@ func maxSubarrays(nums []int) int { } ``` -### **TypeScript** - ```ts function maxSubarrays(nums: number[]): number { let [ans, score] = [1, -1]; @@ -157,10 +141,6 @@ function maxSubarrays(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2871.Split Array Into Maximum Number of Subarrays/README_EN.md b/solution/2800-2899/2871.Split Array Into Maximum Number of Subarrays/README_EN.md index 503675ab83060..da7d13c4d83d3 100644 --- a/solution/2800-2899/2871.Split Array Into Maximum Number of Subarrays/README_EN.md +++ b/solution/2800-2899/2871.Split Array Into Maximum Number of Subarrays/README_EN.md @@ -52,7 +52,7 @@ It can be shown that we cannot split the array into more than 1 subarray with a ## Solutions -**Solution 1: Greedy + Bitwise Operation** +### Solution 1: Greedy + Bitwise Operation We initialize a variable $score$ to record the score of the current subarray, and set $score=-1$ initially. Then we traverse the array, for each element $num$, we perform a bitwise AND operation between $score$ and $num$, and assign the result to $score$. If $score=0$, it means the score of the current subarray is 0, so we can split the current subarray and reset $score$ to $-1$. Finally, we return the number of split subarrays. @@ -60,8 +60,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def maxSubarrays(self, nums: List[int]) -> int: @@ -74,8 +72,6 @@ class Solution: return 1 if ans == 1 else ans - 1 ``` -### **Java** - ```java class Solution { public int maxSubarrays(int[] nums) { @@ -93,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +106,6 @@ public: }; ``` -### **Go** - ```go func maxSubarrays(nums []int) int { ans, score := 1, -1 @@ -131,8 +123,6 @@ func maxSubarrays(nums []int) int { } ``` -### **TypeScript** - ```ts function maxSubarrays(nums: number[]): number { let [ans, score] = [1, -1]; @@ -147,10 +137,6 @@ function maxSubarrays(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2872.Maximum Number of K-Divisible Components/README.md b/solution/2800-2899/2872.Maximum Number of K-Divisible Components/README.md index 9f4c27c5adb31..1a33a24f53ee3 100644 --- a/solution/2800-2899/2872.Maximum Number of K-Divisible Components/README.md +++ b/solution/2800-2899/2872.Maximum Number of K-Divisible Components/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们注意到,题目保证了整棵树的节点值之和可以被 $k$ 整除,因此,如果我们删除一棵元素和能被 $k$ 整除的边,那么剩下的每个连通块的节点值之和也一定可以被 $k$ 整除。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def maxKDivisibleComponents( @@ -99,10 +93,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int ans; @@ -137,45 +127,6 @@ class Solution { } ``` -```java -class Solution { - int n, k; - int[] values; - int[] dfs(int curr, int parent, List> adj) { - int[] res = new int[] {0, values[curr] % k}; - for (int next : adj.get(curr)) { - if (next == parent) { - continue; - } - int[] update = dfs(next, curr, adj); - res[0] += update[0]; - res[1] += update[1]; - } - res[1] %= k; - res[0] += res[1] == 0 ? 1 : 0; - return res; - } - public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) { - this.n = n; - this.k = k; - this.values = values; - List> adj = new ArrayList<>(); - int[][] dp = new int[n][2]; - for (int i = 0; i < n; i++) { - adj.add(new ArrayList<>()); - } - for (int[] edge : edges) { - adj.get(edge[0]).add(edge[1]); - adj.get(edge[1]).add(edge[0]); - } - int[] ans = dfs(0, -1, adj); - return ans[1] == 0 ? ans[0] : 0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -203,8 +154,6 @@ public: }; ``` -### **Go** - ```go func maxKDivisibleComponents(n int, edges [][]int, values []int, k int) (ans int) { g := make([][]int, n) @@ -231,8 +180,6 @@ func maxKDivisibleComponents(n int, edges [][]int, values []int, k int) (ans int } ``` -### **TypeScript** - ```ts function maxKDivisibleComponents( n: number, @@ -263,10 +210,49 @@ function maxKDivisibleComponents( } ``` -### **...** + + +### 方法二 -``` + +```java +class Solution { + int n, k; + int[] values; + int[] dfs(int curr, int parent, List> adj) { + int[] res = new int[] {0, values[curr] % k}; + for (int next : adj.get(curr)) { + if (next == parent) { + continue; + } + int[] update = dfs(next, curr, adj); + res[0] += update[0]; + res[1] += update[1]; + } + res[1] %= k; + res[0] += res[1] == 0 ? 1 : 0; + return res; + } + public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) { + this.n = n; + this.k = k; + this.values = values; + List> adj = new ArrayList<>(); + int[][] dp = new int[n][2]; + for (int i = 0; i < n; i++) { + adj.add(new ArrayList<>()); + } + for (int[] edge : edges) { + adj.get(edge[0]).add(edge[1]); + adj.get(edge[1]).add(edge[0]); + } + int[] ans = dfs(0, -1, adj); + return ans[1] == 0 ? ans[0] : 0; + } +} ``` + + diff --git a/solution/2800-2899/2872.Maximum Number of K-Divisible Components/README_EN.md b/solution/2800-2899/2872.Maximum Number of K-Divisible Components/README_EN.md index f0e948d2c764a..c121a40a147eb 100644 --- a/solution/2800-2899/2872.Maximum Number of K-Divisible Components/README_EN.md +++ b/solution/2800-2899/2872.Maximum Number of K-Divisible Components/README_EN.md @@ -52,7 +52,7 @@ It can be shown that no other valid split has more than 3 connected components. ## Solutions -**Solution 1: DFS** +### Solution 1: DFS We notice that the problem guarantees that the sum of the node values in the entire tree can be divided by $k$, so if we remove an edge whose weight is divisible by $k$, then the sum of the node values in each connected component that remains can also be divided by $k$. @@ -62,8 +62,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where n is th -### **Python3** - ```python class Solution: def maxKDivisibleComponents( @@ -87,8 +85,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int ans; @@ -123,45 +119,6 @@ class Solution { } ``` -```java -class Solution { - int n, k; - int[] values; - int[] dfs(int curr, int parent, List> adj) { - int[] res = new int[] {0, values[curr] % k}; - for (int next : adj.get(curr)) { - if (next == parent) { - continue; - } - int[] update = dfs(next, curr, adj); - res[0] += update[0]; - res[1] += update[1]; - } - res[1] %= k; - res[0] += res[1] == 0 ? 1 : 0; - return res; - } - public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) { - this.n = n; - this.k = k; - this.values = values; - List> adj = new ArrayList<>(); - int[][] dp = new int[n][2]; - for (int i = 0; i < n; i++) { - adj.add(new ArrayList<>()); - } - for (int[] edge : edges) { - adj.get(edge[0]).add(edge[1]); - adj.get(edge[1]).add(edge[0]); - } - int[] ans = dfs(0, -1, adj); - return ans[1] == 0 ? ans[0] : 0; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -189,8 +146,6 @@ public: }; ``` -### **Go** - ```go func maxKDivisibleComponents(n int, edges [][]int, values []int, k int) (ans int) { g := make([][]int, n) @@ -217,8 +172,6 @@ func maxKDivisibleComponents(n int, edges [][]int, values []int, k int) (ans int } ``` -### **TypeScript** - ```ts function maxKDivisibleComponents( n: number, @@ -249,10 +202,49 @@ function maxKDivisibleComponents( } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + int n, k; + int[] values; + int[] dfs(int curr, int parent, List> adj) { + int[] res = new int[] {0, values[curr] % k}; + for (int next : adj.get(curr)) { + if (next == parent) { + continue; + } + int[] update = dfs(next, curr, adj); + res[0] += update[0]; + res[1] += update[1]; + } + res[1] %= k; + res[0] += res[1] == 0 ? 1 : 0; + return res; + } + public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) { + this.n = n; + this.k = k; + this.values = values; + List> adj = new ArrayList<>(); + int[][] dp = new int[n][2]; + for (int i = 0; i < n; i++) { + adj.add(new ArrayList<>()); + } + for (int[] edge : edges) { + adj.get(edge[0]).add(edge[1]); + adj.get(edge[1]).add(edge[0]); + } + int[] ans = dfs(0, -1, adj); + return ans[1] == 0 ? ans[0] : 0; + } +} ``` + + diff --git a/solution/2800-2899/2873.Maximum Value of an Ordered Triplet I/README.md b/solution/2800-2899/2873.Maximum Value of an Ordered Triplet I/README.md index 23990937b36f3..18f5af7817c03 100644 --- a/solution/2800-2899/2873.Maximum Value of an Ordered Triplet I/README.md +++ b/solution/2800-2899/2873.Maximum Value of an Ordered Triplet I/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:维护前缀最大值和最大差值** +### 方法一:维护前缀最大值和最大差值 我们可以用两个变量 $mx$ 和 $mx\_diff$ 分别维护前缀最大值和最大差值。遍历数组时,更新这两个变量,答案为所有 $mx\_diff \times nums[i]$ 的最大值。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def maximumTripletValue(self, nums: List[int]) -> int: @@ -76,10 +70,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long maximumTripletValue(int[] nums) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func maximumTripletValue(nums []int) int64 { ans, mx, mx_diff := 0, 0, 0 @@ -129,8 +115,6 @@ func maximumTripletValue(nums []int) int64 { } ``` -### **TypeScript** - ```ts function maximumTripletValue(nums: number[]): number { let [ans, mx, mx_diff] = [0, 0, 0]; @@ -143,10 +127,6 @@ function maximumTripletValue(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2873.Maximum Value of an Ordered Triplet I/README_EN.md b/solution/2800-2899/2873.Maximum Value of an Ordered Triplet I/README_EN.md index b60e2ab66ddf4..8a9df5cfecab1 100644 --- a/solution/2800-2899/2873.Maximum Value of an Ordered Triplet I/README_EN.md +++ b/solution/2800-2899/2873.Maximum Value of an Ordered Triplet I/README_EN.md @@ -47,7 +47,7 @@ It can be shown that there are no ordered triplets of indices with a value great ## Solutions -**Solution 1: Maintain Maximum Prefix Value and Maximum Difference** +### Solution 1: Maintain Maximum Prefix Value and Maximum Difference We can use two variables $mx$ and $mx\_diff$ to maintain the maximum prefix value and maximum difference, respectively. When traversing the array, we update these two variables, and the answer is the maximum value of all $mx\_diff \times nums[i]$. @@ -55,8 +55,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def maximumTripletValue(self, nums: List[int]) -> int: @@ -68,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long maximumTripletValue(int[] nums) { @@ -87,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +99,6 @@ public: }; ``` -### **Go** - ```go func maximumTripletValue(nums []int) int64 { ans, mx, mx_diff := 0, 0, 0 @@ -119,8 +111,6 @@ func maximumTripletValue(nums []int) int64 { } ``` -### **TypeScript** - ```ts function maximumTripletValue(nums: number[]): number { let [ans, mx, mx_diff] = [0, 0, 0]; @@ -133,10 +123,6 @@ function maximumTripletValue(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2874.Maximum Value of an Ordered Triplet II/README.md b/solution/2800-2899/2874.Maximum Value of an Ordered Triplet II/README.md index 08df7255e5af8..85d470bf76196 100644 --- a/solution/2800-2899/2874.Maximum Value of an Ordered Triplet II/README.md +++ b/solution/2800-2899/2874.Maximum Value of an Ordered Triplet II/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:维护前缀最大值和最大差值** +### 方法一:维护前缀最大值和最大差值 我们可以用两个变量 $mx$ 和 $mx\_diff$ 分别维护前缀最大值和最大差值。遍历数组时,更新这两个变量,答案为所有 $mx\_diff \times nums[i]$ 的最大值。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def maximumTripletValue(self, nums: List[int]) -> int: @@ -76,10 +70,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long maximumTripletValue(int[] nums) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func maximumTripletValue(nums []int) int64 { ans, mx, mx_diff := 0, 0, 0 @@ -129,8 +115,6 @@ func maximumTripletValue(nums []int) int64 { } ``` -### **TypeScript** - ```ts function maximumTripletValue(nums: number[]): number { let [ans, mx, mx_diff] = [0, 0, 0]; @@ -143,10 +127,6 @@ function maximumTripletValue(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2874.Maximum Value of an Ordered Triplet II/README_EN.md b/solution/2800-2899/2874.Maximum Value of an Ordered Triplet II/README_EN.md index 3dea2a4c238fa..23e8d3640b03b 100644 --- a/solution/2800-2899/2874.Maximum Value of an Ordered Triplet II/README_EN.md +++ b/solution/2800-2899/2874.Maximum Value of an Ordered Triplet II/README_EN.md @@ -47,7 +47,7 @@ It can be shown that there are no ordered triplets of indices with a value great ## Solutions -**Solution 1: Maintain Maximum Prefix Value and Maximum Difference** +### Solution 1: Maintain Maximum Prefix Value and Maximum Difference We can use two variables $mx$ and $mx\_diff$ to maintain the maximum prefix value and maximum difference, respectively. When traversing the array, we update these two variables, and the answer is the maximum value of all $mx\_diff \times nums[i]$. @@ -55,8 +55,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def maximumTripletValue(self, nums: List[int]) -> int: @@ -68,8 +66,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long maximumTripletValue(int[] nums) { @@ -87,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +99,6 @@ public: }; ``` -### **Go** - ```go func maximumTripletValue(nums []int) int64 { ans, mx, mx_diff := 0, 0, 0 @@ -119,8 +111,6 @@ func maximumTripletValue(nums []int) int64 { } ``` -### **TypeScript** - ```ts function maximumTripletValue(nums: number[]): number { let [ans, mx, mx_diff] = [0, 0, 0]; @@ -133,10 +123,6 @@ function maximumTripletValue(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2875.Minimum Size Subarray in Infinite Array/README.md b/solution/2800-2899/2875.Minimum Size Subarray in Infinite Array/README.md index 18fa4ec3a08c4..3c7fcb4b58b92 100644 --- a/solution/2800-2899/2875.Minimum Size Subarray in Infinite Array/README.md +++ b/solution/2800-2899/2875.Minimum Size Subarray in Infinite Array/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:前缀和 + 哈希表** +### 方法一:前缀和 + 哈希表 我们先算出数组 $nums$ 的元素总和,记为 $s$。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Solution: def minSizeSubarray(self, nums: List[int], target: int) -> int: @@ -98,10 +92,6 @@ class Solution: return -1 if b == inf else a + b ``` -### **Java** - - - ```java class Solution { public int minSizeSubarray(int[] nums, int target) { @@ -134,56 +124,6 @@ class Solution { } ``` -```java -class Solution { - public int shortestSubarray(int[] nums, int k) { - int n = nums.length; - - int minLength = n * 2 + 1; - int l = 0; - int sum = 0; - - for (int r = 0; r < n * 2; r++) { - int start = l % n; - int end = r % n; - sum += nums[end]; - - while (sum > k && l <= r) { - start = l % n; - sum -= nums[start]; - l++; - } - - if (sum == k) { - minLength = Math.min(minLength, r - l + 1); - start = l % n; - sum -= nums[start]; - l++; - } - } - - return minLength == n * 2 + 1 ? -1 : minLength; - } - public int minSizeSubarray(int[] nums, int target) { - int n = nums.length; - int sum = 0; - - for (int num : nums) { - sum += num; - } - int k = target % sum; - int ans = target / sum * n; - if (k == 0) { - return ans; - } - int res = shortestSubarray(nums, k); - return res == -1 ? -1 : ans + res; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -216,8 +156,6 @@ public: }; ``` -### **Go** - ```go func minSizeSubarray(nums []int, target int) int { s := 0 @@ -253,8 +191,6 @@ func minSizeSubarray(nums []int, target int) int { } ``` -### **TypeScript** - ```ts function minSizeSubarray(nums: number[], target: number): number { const s = nums.reduce((a, b) => a + b); @@ -285,10 +221,60 @@ function minSizeSubarray(nums: number[], target: number): number { } ``` -### **...** + -``` +### 方法二 + + + +```java +class Solution { + public int shortestSubarray(int[] nums, int k) { + int n = nums.length; + int minLength = n * 2 + 1; + int l = 0; + int sum = 0; + + for (int r = 0; r < n * 2; r++) { + int start = l % n; + int end = r % n; + sum += nums[end]; + + while (sum > k && l <= r) { + start = l % n; + sum -= nums[start]; + l++; + } + + if (sum == k) { + minLength = Math.min(minLength, r - l + 1); + start = l % n; + sum -= nums[start]; + l++; + } + } + + return minLength == n * 2 + 1 ? -1 : minLength; + } + public int minSizeSubarray(int[] nums, int target) { + int n = nums.length; + int sum = 0; + + for (int num : nums) { + sum += num; + } + int k = target % sum; + int ans = target / sum * n; + if (k == 0) { + return ans; + } + int res = shortestSubarray(nums, k); + return res == -1 ? -1 : ans + res; + } +} ``` + + diff --git a/solution/2800-2899/2875.Minimum Size Subarray in Infinite Array/README_EN.md b/solution/2800-2899/2875.Minimum Size Subarray in Infinite Array/README_EN.md index 681029d981293..5f8336221bfc8 100644 --- a/solution/2800-2899/2875.Minimum Size Subarray in Infinite Array/README_EN.md +++ b/solution/2800-2899/2875.Minimum Size Subarray in Infinite Array/README_EN.md @@ -51,7 +51,7 @@ It can be proven that there is no subarray with sum equal to target = 3. ## Solutions -**Solution 1: Prefix Sum + Hash Table** +### Solution 1: Prefix Sum + Hash Table First, we calculate the sum of all elements in the array $nums$, denoted as $s$. @@ -65,8 +65,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where n is th -### **Python3** - ```python class Solution: def minSizeSubarray(self, nums: List[int], target: int) -> int: @@ -91,8 +89,6 @@ class Solution: return -1 if b == inf else a + b ``` -### **Java** - ```java class Solution { public int minSizeSubarray(int[] nums, int target) { @@ -125,56 +121,6 @@ class Solution { } ``` -```java -class Solution { - public int shortestSubarray(int[] nums, int k) { - int n = nums.length; - - int minLength = n * 2 + 1; - int l = 0; - int sum = 0; - - for (int r = 0; r < n * 2; r++) { - int start = l % n; - int end = r % n; - sum += nums[end]; - - while (sum > k && l <= r) { - start = l % n; - sum -= nums[start]; - l++; - } - - if (sum == k) { - minLength = Math.min(minLength, r - l + 1); - start = l % n; - sum -= nums[start]; - l++; - } - } - - return minLength == n * 2 + 1 ? -1 : minLength; - } - public int minSizeSubarray(int[] nums, int target) { - int n = nums.length; - int sum = 0; - - for (int num : nums) { - sum += num; - } - int k = target % sum; - int ans = target / sum * n; - if (k == 0) { - return ans; - } - int res = shortestSubarray(nums, k); - return res == -1 ? -1 : ans + res; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -207,8 +153,6 @@ public: }; ``` -### **Go** - ```go func minSizeSubarray(nums []int, target int) int { s := 0 @@ -244,8 +188,6 @@ func minSizeSubarray(nums []int, target int) int { } ``` -### **TypeScript** - ```ts function minSizeSubarray(nums: number[], target: number): number { const s = nums.reduce((a, b) => a + b); @@ -276,10 +218,60 @@ function minSizeSubarray(nums: number[], target: number): number { } ``` -### **...** + + +### Solution 2 -``` + + +```java +class Solution { + public int shortestSubarray(int[] nums, int k) { + int n = nums.length; + + int minLength = n * 2 + 1; + int l = 0; + int sum = 0; + + for (int r = 0; r < n * 2; r++) { + int start = l % n; + int end = r % n; + sum += nums[end]; + + while (sum > k && l <= r) { + start = l % n; + sum -= nums[start]; + l++; + } + + if (sum == k) { + minLength = Math.min(minLength, r - l + 1); + start = l % n; + sum -= nums[start]; + l++; + } + } + + return minLength == n * 2 + 1 ? -1 : minLength; + } + public int minSizeSubarray(int[] nums, int target) { + int n = nums.length; + int sum = 0; + for (int num : nums) { + sum += num; + } + int k = target % sum; + int ans = target / sum * n; + if (k == 0) { + return ans; + } + int res = shortestSubarray(nums, k); + return res == -1 ? -1 : ans + res; + } +} ``` + + diff --git a/solution/2800-2899/2876.Count Visited Nodes in a Directed Graph/README.md b/solution/2800-2899/2876.Count Visited Nodes in a Directed Graph/README.md index e3920ce12b91b..e843eba2df7dd 100644 --- a/solution/2800-2899/2876.Count Visited Nodes in a Directed Graph/README.md +++ b/solution/2800-2899/2876.Count Visited Nodes in a Directed Graph/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:基环树 + 遍历搜索** +### 方法一:基环树 + 遍历搜索 我们可以用一个数组 $ans$ 记录每个节点的答案,用一个数组 $vis$ 记录每个节点的访问次序。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class Solution: def countVisitedNodes(self, edges: List[int]) -> List[int]: @@ -97,10 +91,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] countVisitedNodes(List edges) { @@ -130,47 +120,6 @@ class Solution { } ``` -```java -class Solution { - void dfs(int curr, List edges, int[] ans) { - - List path = new ArrayList<>(); - int prev = -1; - while (ans[curr] == 0) { - path.add(curr); - ans[curr] = prev == -1 ? -1 : ans[prev] - 1; - prev = curr; - curr = edges.get(curr); - } - int idx = path.size() - 1; - if (ans[curr] < 0) { - int cycle = ans[curr] - ans[path.get(idx)] + 1; - int start = ans[curr]; - for (; idx >= 0 && ans[path.get(idx)] <= start; idx--) { - ans[path.get(idx)] = cycle; - } - } - for (; idx >= 0; idx--) { - ans[path.get(idx)] = ans[edges.get(path.get(idx))] + 1; - } - } - - public int[] countVisitedNodes(List edges) { - int n = edges.size(); - int[] ans = new int[n]; - for (int i = 0; i < n; i++) { - if (ans[i] > 0) { - continue; - } - dfs(i, edges, ans); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -200,8 +149,6 @@ public: }; ``` -### **Go** - ```go func countVisitedNodes(edges []int) []int { n := len(edges) @@ -231,8 +178,6 @@ func countVisitedNodes(edges []int) []int { } ``` -### **TypeScript** - ```ts function countVisitedNodes(edges: number[]): number[] { const n = edges.length; @@ -260,10 +205,51 @@ function countVisitedNodes(edges: number[]): number[] { } ``` -### **...** + + +### 方法二 -``` + + +```java +class Solution { + void dfs(int curr, List edges, int[] ans) { + + List path = new ArrayList<>(); + int prev = -1; + while (ans[curr] == 0) { + path.add(curr); + ans[curr] = prev == -1 ? -1 : ans[prev] - 1; + prev = curr; + curr = edges.get(curr); + } + int idx = path.size() - 1; + if (ans[curr] < 0) { + int cycle = ans[curr] - ans[path.get(idx)] + 1; + int start = ans[curr]; + for (; idx >= 0 && ans[path.get(idx)] <= start; idx--) { + ans[path.get(idx)] = cycle; + } + } + for (; idx >= 0; idx--) { + ans[path.get(idx)] = ans[edges.get(path.get(idx))] + 1; + } + } + public int[] countVisitedNodes(List edges) { + int n = edges.size(); + int[] ans = new int[n]; + for (int i = 0; i < n; i++) { + if (ans[i] > 0) { + continue; + } + dfs(i, edges, ans); + } + return ans; + } +} ``` + + diff --git a/solution/2800-2899/2876.Count Visited Nodes in a Directed Graph/README_EN.md b/solution/2800-2899/2876.Count Visited Nodes in a Directed Graph/README_EN.md index d59c1744491fe..5cedb0587e621 100644 --- a/solution/2800-2899/2876.Count Visited Nodes in a Directed Graph/README_EN.md +++ b/solution/2800-2899/2876.Count Visited Nodes in a Directed Graph/README_EN.md @@ -49,7 +49,7 @@ ## Solutions -**Solution 1: Basic Tree + Traversal** +### Solution 1: Basic Tree + Traversal We can use an array $ans$ to record the answer for each node, and an array $vis$ to record the visit order for each node. @@ -62,8 +62,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is -### **Python3** - ```python class Solution: def countVisitedNodes(self, edges: List[int]) -> List[int]: @@ -89,8 +87,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] countVisitedNodes(List edges) { @@ -120,47 +116,6 @@ class Solution { } ``` -```java -class Solution { - void dfs(int curr, List edges, int[] ans) { - - List path = new ArrayList<>(); - int prev = -1; - while (ans[curr] == 0) { - path.add(curr); - ans[curr] = prev == -1 ? -1 : ans[prev] - 1; - prev = curr; - curr = edges.get(curr); - } - int idx = path.size() - 1; - if (ans[curr] < 0) { - int cycle = ans[curr] - ans[path.get(idx)] + 1; - int start = ans[curr]; - for (; idx >= 0 && ans[path.get(idx)] <= start; idx--) { - ans[path.get(idx)] = cycle; - } - } - for (; idx >= 0; idx--) { - ans[path.get(idx)] = ans[edges.get(path.get(idx))] + 1; - } - } - - public int[] countVisitedNodes(List edges) { - int n = edges.size(); - int[] ans = new int[n]; - for (int i = 0; i < n; i++) { - if (ans[i] > 0) { - continue; - } - dfs(i, edges, ans); - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -190,8 +145,6 @@ public: }; ``` -### **Go** - ```go func countVisitedNodes(edges []int) []int { n := len(edges) @@ -221,8 +174,6 @@ func countVisitedNodes(edges []int) []int { } ``` -### **TypeScript** - ```ts function countVisitedNodes(edges: number[]): number[] { const n = edges.length; @@ -250,10 +201,51 @@ function countVisitedNodes(edges: number[]): number[] { } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + void dfs(int curr, List edges, int[] ans) { + + List path = new ArrayList<>(); + int prev = -1; + while (ans[curr] == 0) { + path.add(curr); + ans[curr] = prev == -1 ? -1 : ans[prev] - 1; + prev = curr; + curr = edges.get(curr); + } + int idx = path.size() - 1; + if (ans[curr] < 0) { + int cycle = ans[curr] - ans[path.get(idx)] + 1; + int start = ans[curr]; + for (; idx >= 0 && ans[path.get(idx)] <= start; idx--) { + ans[path.get(idx)] = cycle; + } + } + for (; idx >= 0; idx--) { + ans[path.get(idx)] = ans[edges.get(path.get(idx))] + 1; + } + } + + public int[] countVisitedNodes(List edges) { + int n = edges.size(); + int[] ans = new int[n]; + for (int i = 0; i < n; i++) { + if (ans[i] > 0) { + continue; + } + dfs(i, edges, ans); + } + return ans; + } +} ``` + + diff --git a/solution/2800-2899/2877.Create a DataFrame from List/README.md b/solution/2800-2899/2877.Create a DataFrame from List/README.md index e80f1bfe99b57..3873405da31ff 100644 --- a/solution/2800-2899/2877.Create a DataFrame from List/README.md +++ b/solution/2800-2899/2877.Create a DataFrame from List/README.md @@ -40,14 +40,10 @@ ## 解法 - +### 方法一 -### **Pandas** - - - ```python import pandas as pd @@ -56,10 +52,6 @@ def createDataframe(student_data: List[List[int]]) -> pd.DataFrame: return pd.DataFrame(student_data, columns=['student_id', 'age']) ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2877.Create a DataFrame from List/README_EN.md b/solution/2800-2899/2877.Create a DataFrame from List/README_EN.md index 45ac8335c0935..da744344e1c6b 100644 --- a/solution/2800-2899/2877.Create a DataFrame from List/README_EN.md +++ b/solution/2800-2899/2877.Create a DataFrame from List/README_EN.md @@ -37,9 +37,9 @@ A DataFrame was created on top of student_data, with two columns named stu ## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -49,10 +49,6 @@ def createDataframe(student_data: List[List[int]]) -> pd.DataFrame: return pd.DataFrame(student_data, columns=['student_id', 'age']) ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2878.Get the Size of a DataFrame/README.md b/solution/2800-2899/2878.Get the Size of a DataFrame/README.md index 4111d79eb677f..dea265a9b98ef 100644 --- a/solution/2800-2899/2878.Get the Size of a DataFrame/README.md +++ b/solution/2800-2899/2878.Get the Size of a DataFrame/README.md @@ -55,14 +55,10 @@ DataFrame players: ## 解法 - +### 方法一 -### **Pandas** - - - ```python import pandas as pd @@ -71,10 +67,6 @@ def getDataframeSize(players: pd.DataFrame) -> List[int]: return list(players.shape) ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2878.Get the Size of a DataFrame/README_EN.md b/solution/2800-2899/2878.Get the Size of a DataFrame/README_EN.md index dc33fc639b641..fa3616b5045aa 100644 --- a/solution/2800-2899/2878.Get the Size of a DataFrame/README_EN.md +++ b/solution/2800-2899/2878.Get the Size of a DataFrame/README_EN.md @@ -52,9 +52,9 @@ This DataFrame contains 10 rows and 5 columns. ## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -64,10 +64,6 @@ def getDataframeSize(players: pd.DataFrame) -> List[int]: return list(players.shape) ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2879.Display the First Three Rows/README.md b/solution/2800-2899/2879.Display the First Three Rows/README.md index c6173d2b1c480..75a1c8f66975c 100644 --- a/solution/2800-2899/2879.Display the First Three Rows/README.md +++ b/solution/2800-2899/2879.Display the First Three Rows/README.md @@ -50,14 +50,10 @@ DataFrame: employees ## 解法 - +### 方法一 -### **Pandas** - - - ```python import pandas as pd @@ -66,10 +62,6 @@ def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame: return employees.head(3) ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2879.Display the First Three Rows/README_EN.md b/solution/2800-2899/2879.Display the First Three Rows/README_EN.md index 8650231f2dd9a..dbe1521c3e2f5 100644 --- a/solution/2800-2899/2879.Display the First Three Rows/README_EN.md +++ b/solution/2800-2899/2879.Display the First Three Rows/README_EN.md @@ -47,9 +47,9 @@ Only the first 3 rows are displayed. ## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -59,10 +59,6 @@ def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame: return employees.head(3) ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2880.Select Data/README.md b/solution/2800-2899/2880.Select Data/README.md index aa70284dbaa9b..1c58bbd7d2b2d 100644 --- a/solution/2800-2899/2880.Select Data/README.md +++ b/solution/2800-2899/2880.Select Data/README.md @@ -47,14 +47,10 @@ DataFrame students ## 解法 - +### 方法一 -### **Python3** - - - ```python import pandas as pd @@ -63,30 +59,6 @@ def selectData(students: pd.DataFrame) -> pd.DataFrame: return students[students['student_id'] == 101][['name', 'age']] ``` -### **Java** - - - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2880.Select Data/README_EN.md b/solution/2800-2899/2880.Select Data/README_EN.md index 34a43a4e6b58e..06dc25abc4c38 100644 --- a/solution/2800-2899/2880.Select Data/README_EN.md +++ b/solution/2800-2899/2880.Select Data/README_EN.md @@ -43,9 +43,9 @@ Input:
## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -55,10 +55,6 @@ def selectData(students: pd.DataFrame) -> pd.DataFrame: return students[students['student_id'] == 101][['name', 'age']] ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2881.Create a New Column/README.md b/solution/2800-2899/2881.Create a New Column/README.md index 9fbc58b838651..233e246b030a3 100644 --- a/solution/2800-2899/2881.Create a New Column/README.md +++ b/solution/2800-2899/2881.Create a New Column/README.md @@ -55,14 +55,10 @@ DataFrame employees ## 解法 - +### 方法一 -### **Pandas** - - - ```python import pandas as pd @@ -72,10 +68,6 @@ def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame: return employees ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2881.Create a New Column/README_EN.md b/solution/2800-2899/2881.Create a New Column/README_EN.md index 11d738329f185..8632ac52960a3 100644 --- a/solution/2800-2899/2881.Create a New Column/README_EN.md +++ b/solution/2800-2899/2881.Create a New Column/README_EN.md @@ -52,9 +52,9 @@ A new column bonus is created by doubling the value in the column salary. ## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -65,10 +65,6 @@ def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame: return employees ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2882.Drop Duplicate Rows/README.md b/solution/2800-2899/2882.Drop Duplicate Rows/README.md index 31449ae09a621..491bcd416bdc3 100644 --- a/solution/2800-2899/2882.Drop Duplicate Rows/README.md +++ b/solution/2800-2899/2882.Drop Duplicate Rows/README.md @@ -55,14 +55,10 @@ Alice (customer_id = 4) 和 Finn (customer_id = 5) 都使用 john@example.com, ## 解法 - +### 方法一 -### **Pandas** - - - ```python import pandas as pd @@ -71,10 +67,6 @@ def dropDuplicateEmails(customers: pd.DataFrame) -> pd.DataFrame: return customers.drop_duplicates(subset=['email']) ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2882.Drop Duplicate Rows/README_EN.md b/solution/2800-2899/2882.Drop Duplicate Rows/README_EN.md index e48f31ceb4235..4e29cdb489455 100644 --- a/solution/2800-2899/2882.Drop Duplicate Rows/README_EN.md +++ b/solution/2800-2899/2882.Drop Duplicate Rows/README_EN.md @@ -51,9 +51,9 @@ Alic (customer_id = 4) and Finn (customer_id = 5) both use john@example.com, so ## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -63,10 +63,6 @@ def dropDuplicateEmails(customers: pd.DataFrame) -> pd.DataFrame: return customers.drop_duplicates(subset=['email']) ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2883.Drop Missing Data/README.md b/solution/2800-2899/2883.Drop Missing Data/README.md index fc5d8b0d98ed6..1405be6eab3ba 100644 --- a/solution/2800-2899/2883.Drop Missing Data/README.md +++ b/solution/2800-2899/2883.Drop Missing Data/README.md @@ -50,14 +50,10 @@ DataFrame students ## 解法 - +### 方法一 -### **Pandas** - - - ```python import pandas as pd @@ -66,10 +62,6 @@ def dropMissingData(students: pd.DataFrame) -> pd.DataFrame: return students[students['name'].notnull()] ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2883.Drop Missing Data/README_EN.md b/solution/2800-2899/2883.Drop Missing Data/README_EN.md index 19d0d6e75d6f8..d99e8d90a48fb 100644 --- a/solution/2800-2899/2883.Drop Missing Data/README_EN.md +++ b/solution/2800-2899/2883.Drop Missing Data/README_EN.md @@ -47,9 +47,9 @@ Student with id 217 havs empty value in the name column, so it will be removed.< ## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -59,10 +59,6 @@ def dropMissingData(students: pd.DataFrame) -> pd.DataFrame: return students[students['name'].notnull()] ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2884.Modify Columns/README.md b/solution/2800-2899/2884.Modify Columns/README.md index 9c1016262c3a6..85a988fb7ae54 100644 --- a/solution/2800-2899/2884.Modify Columns/README.md +++ b/solution/2800-2899/2884.Modify Columns/README.md @@ -51,14 +51,10 @@ DataFrame employees ## 解法 - +### 方法一 -### **Pandas** - - - ```python import pandas as pd @@ -68,10 +64,6 @@ def modifySalaryColumn(employees: pd.DataFrame) -> pd.DataFrame: return employees ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2884.Modify Columns/README_EN.md b/solution/2800-2899/2884.Modify Columns/README_EN.md index 2d0fedb5c797a..bcabe4d87608a 100644 --- a/solution/2800-2899/2884.Modify Columns/README_EN.md +++ b/solution/2800-2899/2884.Modify Columns/README_EN.md @@ -48,9 +48,9 @@ DataFrame employees ## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -61,10 +61,6 @@ def modifySalaryColumn(employees: pd.DataFrame) -> pd.DataFrame: return employees ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2885.Rename Columns/README.md b/solution/2800-2899/2885.Rename Columns/README.md index 85bbab8ebc832..0788f32eaf812 100644 --- a/solution/2800-2899/2885.Rename Columns/README.md +++ b/solution/2800-2899/2885.Rename Columns/README.md @@ -59,14 +59,10 @@ DataFrame students ## 解法 - +### 方法一 -### **Pandas** - - - ```python import pandas as pd @@ -84,10 +80,6 @@ def renameColumns(students: pd.DataFrame) -> pd.DataFrame: return students ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2885.Rename Columns/README_EN.md b/solution/2800-2899/2885.Rename Columns/README_EN.md index 8a3301e3b1723..642760a581ecf 100644 --- a/solution/2800-2899/2885.Rename Columns/README_EN.md +++ b/solution/2800-2899/2885.Rename Columns/README_EN.md @@ -55,9 +55,9 @@ The column names are changed accordingly. ## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -76,10 +76,6 @@ def renameColumns(students: pd.DataFrame) -> pd.DataFrame: return students ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2886.Change Data Type/README.md b/solution/2800-2899/2886.Change Data Type/README.md index 04590adcbe6a2..214a2cae9223d 100644 --- a/solution/2800-2899/2886.Change Data Type/README.md +++ b/solution/2800-2899/2886.Change Data Type/README.md @@ -49,14 +49,10 @@ grade 列的数据类型已转换为整数。 ## 解法 - +### 方法一 -### **Pandas** - - - ```python import pandas as pd @@ -66,10 +62,6 @@ def changeDatatype(students: pd.DataFrame) -> pd.DataFrame: return students ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2886.Change Data Type/README_EN.md b/solution/2800-2899/2886.Change Data Type/README_EN.md index 6769253e74329..fc23d97b98ef7 100644 --- a/solution/2800-2899/2886.Change Data Type/README_EN.md +++ b/solution/2800-2899/2886.Change Data Type/README_EN.md @@ -45,9 +45,9 @@ The data types of the column grade is converted to int. ## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -58,10 +58,6 @@ def changeDatatype(students: pd.DataFrame) -> pd.DataFrame: return students ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2887.Fill Missing Data/README.md b/solution/2800-2899/2887.Fill Missing Data/README.md index a7b8208a984ee..56959e4142ecc 100644 --- a/solution/2800-2899/2887.Fill Missing Data/README.md +++ b/solution/2800-2899/2887.Fill Missing Data/README.md @@ -48,14 +48,10 @@ Toaster 和 Headphones 的数量被填充为 0。 ## 解法 - +### 方法一 -### **Pandas** - - - ```python import pandas as pd @@ -65,10 +61,6 @@ def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame: return products ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2887.Fill Missing Data/README_EN.md b/solution/2800-2899/2887.Fill Missing Data/README_EN.md index 9ad804db4c71f..9f2a9e6f52870 100644 --- a/solution/2800-2899/2887.Fill Missing Data/README_EN.md +++ b/solution/2800-2899/2887.Fill Missing Data/README_EN.md @@ -44,9 +44,9 @@ The quantity for Wristwatch and WirelessEarbuds are filled by 0. ## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -57,10 +57,6 @@ def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame: return products ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2888.Reshape Data Concatenate/README.md b/solution/2800-2899/2888.Reshape Data Concatenate/README.md index 9a92f343be194..7fa4e61642777 100644 --- a/solution/2800-2899/2888.Reshape Data Concatenate/README.md +++ b/solution/2800-2899/2888.Reshape Data Concatenate/README.md @@ -69,14 +69,10 @@ df1 ## 解法 - +### 方法一 -### **Pandas** - - - ```python import pandas as pd @@ -85,10 +81,6 @@ def concatenateTables(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.DataFrame: return pd.concat([df1, df2], ignore_index=True) ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2888.Reshape Data Concatenate/README_EN.md b/solution/2800-2899/2888.Reshape Data Concatenate/README_EN.md index 6bac57bc80824..2bb3559f29102 100644 --- a/solution/2800-2899/2888.Reshape Data Concatenate/README_EN.md +++ b/solution/2800-2899/2888.Reshape Data Concatenate/README_EN.md @@ -66,9 +66,9 @@ df1 ## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -78,10 +78,6 @@ def concatenateTables(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.DataFrame: return pd.concat([df1, df2], ignore_index=True) ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2889.Reshape Data Pivot/README.md b/solution/2800-2899/2889.Reshape Data Pivot/README.md index ea74b85951689..dc79dcd3e9dd0 100644 --- a/solution/2800-2899/2889.Reshape Data Pivot/README.md +++ b/solution/2800-2899/2889.Reshape Data Pivot/README.md @@ -55,14 +55,10 @@ DataFrame weather ## 解法 - +### 方法一 -### **Pandas** - - - ```python import pandas as pd @@ -71,10 +67,6 @@ def pivotTable(weather: pd.DataFrame) -> pd.DataFrame: return weather.pivot(index='month', columns='city', values='temperature') ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2889.Reshape Data Pivot/README_EN.md b/solution/2800-2899/2889.Reshape Data Pivot/README_EN.md index 65e3755eb7156..abf63778892b2 100644 --- a/solution/2800-2899/2889.Reshape Data Pivot/README_EN.md +++ b/solution/2800-2899/2889.Reshape Data Pivot/README_EN.md @@ -52,9 +52,9 @@ DataFrame weather ## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -64,10 +64,6 @@ def pivotTable(weather: pd.DataFrame) -> pd.DataFrame: return weather.pivot(index='month', columns='city', values='temperature') ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2890.Reshape Data Melt/README.md b/solution/2800-2899/2890.Reshape Data Melt/README.md index 6bed21d0ed64f..b2ca764c6a9a3 100644 --- a/solution/2800-2899/2890.Reshape Data Melt/README.md +++ b/solution/2800-2899/2890.Reshape Data Melt/README.md @@ -54,14 +54,10 @@ DataFrame 已从宽格式重塑为长格式。每一行表示一个季度内产 ## 解法 - +### 方法一 -### **Pandas** - - - ```python import pandas as pd @@ -70,10 +66,6 @@ def meltTable(report: pd.DataFrame) -> pd.DataFrame: return pd.melt(report, id_vars=['product'], var_name='quarter', value_name='sales') ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2890.Reshape Data Melt/README_EN.md b/solution/2800-2899/2890.Reshape Data Melt/README_EN.md index 8e15210960e2c..c078ac72dbc6a 100644 --- a/solution/2800-2899/2890.Reshape Data Melt/README_EN.md +++ b/solution/2800-2899/2890.Reshape Data Melt/README_EN.md @@ -51,9 +51,9 @@ The DataFrame is reshaped from wide to long format. Each row represents the sale ## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -63,10 +63,6 @@ def meltTable(report: pd.DataFrame) -> pd.DataFrame: return pd.melt(report, id_vars=['product'], var_name='quarter', value_name='sales') ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2891.Method Chaining/README.md b/solution/2800-2899/2891.Method Chaining/README.md index dfb6d9486e356..0bb7c93b38c57 100644 --- a/solution/2800-2899/2891.Method Chaining/README.md +++ b/solution/2800-2899/2891.Method Chaining/README.md @@ -63,14 +63,10 @@ Tatiana 的体重为 464,Jonathan 的体重为 463,Tommy 的体重为 349, ## 解法 - +### 方法一 -### **Pandas** - - - ```python import pandas as pd @@ -81,10 +77,6 @@ def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame: ] ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2891.Method Chaining/README_EN.md b/solution/2800-2899/2891.Method Chaining/README_EN.md index 622eef06e0a48..c2fcb50aa6fc8 100644 --- a/solution/2800-2899/2891.Method Chaining/README_EN.md +++ b/solution/2800-2899/2891.Method Chaining/README_EN.md @@ -59,9 +59,9 @@ The results should be sorted in descending order of weight. ## Solutions - +### Solution 1 -### **Pandas** + ```python import pandas as pd @@ -73,10 +73,6 @@ def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame: ] ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2892.Minimizing Array After Replacing Pairs With Their Product/README.md b/solution/2800-2899/2892.Minimizing Array After Replacing Pairs With Their Product/README.md index 092a89523abd8..81c26528768ae 100644 --- a/solution/2800-2899/2892.Minimizing Array After Replacing Pairs With Their Product/README.md +++ b/solution/2800-2899/2892.Minimizing Array After Replacing Pairs With Their Product/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们用一个变量 $ans$ 记录当前数组的长度,用一个变量 $y$ 记录当前数组的乘积,初始时 $ans = 1$, $y = nums[0]$。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def minArrayLength(self, nums: List[int], k: int) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minArrayLength(int[] nums, int k) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func minArrayLength(nums []int, k int) int { ans, y := 1, nums[0] @@ -154,8 +140,6 @@ func minArrayLength(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function minArrayLength(nums: number[], k: number): number { let [ans, y] = [1, nums[0]]; @@ -174,10 +158,6 @@ function minArrayLength(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2892.Minimizing Array After Replacing Pairs With Their Product/README_EN.md b/solution/2800-2899/2892.Minimizing Array After Replacing Pairs With Their Product/README_EN.md index cde5909c7a8e7..6b98baa60e191 100644 --- a/solution/2800-2899/2892.Minimizing Array After Replacing Pairs With Their Product/README_EN.md +++ b/solution/2800-2899/2892.Minimizing Array After Replacing Pairs With Their Product/README_EN.md @@ -44,7 +44,7 @@ Hence, the answer is 4. ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy We use a variable $ans$ to record the current length of the array, and a variable $y$ to record the current product of the array. Initially, $ans = 1$ and $y = nums[0]$. @@ -60,8 +60,6 @@ The time complexity is $O(n)$, where n is the length of the array. The space com -### **Python3** - ```python class Solution: def minArrayLength(self, nums: List[int], k: int) -> int: @@ -77,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minArrayLength(int[] nums, int k) { @@ -101,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +120,6 @@ public: }; ``` -### **Go** - ```go func minArrayLength(nums []int, k int) int { ans, y := 1, nums[0] @@ -146,8 +138,6 @@ func minArrayLength(nums []int, k int) int { } ``` -### **TypeScript** - ```ts function minArrayLength(nums: number[], k: number): number { let [ans, y] = [1, nums[0]]; @@ -166,10 +156,6 @@ function minArrayLength(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2893.Calculate Orders Within Each Interval/README.md b/solution/2800-2899/2893.Calculate Orders Within Each Interval/README.md index 1c9d4173514e3..560fd06e2b2f4 100644 --- a/solution/2800-2899/2893.Calculate Orders Within Each Interval/README.md +++ b/solution/2800-2899/2893.Calculate Orders Within Each Interval/README.md @@ -65,18 +65,12 @@ Orders table: ## 解法 - - -**方法一:窗口函数** +### 方法一:窗口函数 我们可以用窗口函数 `sum() over()` 来计算每 $6$ 分钟的订单总数,然后每条记录中的 `minute` 能被 $6$ 整除的记录。 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -94,6 +88,12 @@ FROM T WHERE minute % 6 = 0; ``` + + +### 方法二 + + + ```sql SELECT FLOOR((minute + 5) / 6) AS interval_no, @@ -104,3 +104,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2800-2899/2893.Calculate Orders Within Each Interval/README_EN.md b/solution/2800-2899/2893.Calculate Orders Within Each Interval/README_EN.md index cbd61e7d61b01..31d28a46a39ef 100644 --- a/solution/2800-2899/2893.Calculate Orders Within Each Interval/README_EN.md +++ b/solution/2800-2899/2893.Calculate Orders Within Each Interval/README_EN.md @@ -63,9 +63,9 @@ Returning table orderd by interval_no in ascending order. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -84,6 +84,12 @@ FROM T WHERE minute % 6 = 0; ``` + + +### Solution 2 + + + ```sql SELECT FLOOR((minute + 5) / 6) AS interval_no, @@ -94,3 +100,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/README.md b/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/README.md index 85332abdda30b..1a154a6845d3d 100644 --- a/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/README.md +++ b/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们遍历区间 $[1, n]$ 中的每一个数,如果它能被 $m$ 整除,那么答案就减去这个数,否则答案就加上这个数。 @@ -74,20 +72,12 @@ -### **Python3** - - - ```python class Solution: def differenceOfSums(self, n: int, m: int) -> int: return sum(i if i % m else -i for i in range(1, n + 1)) ``` -### **Java** - - - ```java class Solution { public int differenceOfSums(int n, int m) { @@ -100,19 +90,6 @@ class Solution { } ``` -```java -class Solution { - public int differenceOfSums(int n, int m) { - int sum = n * (n + 1) / 2; - int k = n / m; - int nums2 = k * (k + 1) / 2 * m; - return sum - nums2 * 2; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -126,8 +103,6 @@ public: }; ``` -### **Go** - ```go func differenceOfSums(n int, m int) (ans int) { for i := 1; i <= n; i++ { @@ -141,8 +116,6 @@ func differenceOfSums(n int, m int) (ans int) { } ``` -### **TypeScript** - ```ts function differenceOfSums(n: number, m: number): number { let ans = 0; @@ -153,10 +126,23 @@ function differenceOfSums(n: number, m: number): number { } ``` -### **...** + -``` +### 方法二 + + +```java +class Solution { + public int differenceOfSums(int n, int m) { + int sum = n * (n + 1) / 2; + int k = n / m; + int nums2 = k * (k + 1) / 2 * m; + return sum - nums2 * 2; + } +} ``` + + diff --git a/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/README_EN.md b/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/README_EN.md index 59b689c1e3f9a..907b266aad839 100644 --- a/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/README_EN.md +++ b/solution/2800-2899/2894.Divisible and Non-divisible Sums Difference/README_EN.md @@ -58,7 +58,7 @@ We return 0 - 15 = -15 as the answer. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We traverse every number in the range $[1, n]$. If it is divisible by $m$, we subtract it from the answer. Otherwise, we add it to the answer. @@ -68,16 +68,12 @@ The time complexity is $O(n)$, where $n$ is the given integer. The space complex -### **Python3** - ```python class Solution: def differenceOfSums(self, n: int, m: int) -> int: return sum(i if i % m else -i for i in range(1, n + 1)) ``` -### **Java** - ```java class Solution { public int differenceOfSums(int n, int m) { @@ -90,19 +86,6 @@ class Solution { } ``` -```java -class Solution { - public int differenceOfSums(int n, int m) { - int sum = n * (n + 1) / 2; - int k = n / m; - int nums2 = k * (k + 1) / 2 * m; - return sum - nums2 * 2; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -116,8 +99,6 @@ public: }; ``` -### **Go** - ```go func differenceOfSums(n int, m int) (ans int) { for i := 1; i <= n; i++ { @@ -131,8 +112,6 @@ func differenceOfSums(n int, m int) (ans int) { } ``` -### **TypeScript** - ```ts function differenceOfSums(n: number, m: number): number { let ans = 0; @@ -143,10 +122,23 @@ function differenceOfSums(n: number, m: number): number { } ``` -### **...** + + +### Solution 2 -``` + +```java +class Solution { + public int differenceOfSums(int n, int m) { + int sum = n * (n + 1) / 2; + int k = n / m; + int nums2 = k * (k + 1) / 2 * m; + return sum - nums2 * 2; + } +} ``` + + diff --git a/solution/2800-2899/2895.Minimum Processing Time/README.md b/solution/2800-2899/2895.Minimum Processing Time/README.md index 775849d3a4eac..1f6067be2e3dc 100644 --- a/solution/2800-2899/2895.Minimum Processing Time/README.md +++ b/solution/2800-2899/2895.Minimum Processing Time/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:贪心 + 排序** +### 方法一:贪心 + 排序 要使得处理完所有任务的时间最小,那么越早处于空闲状态的处理器应该处理耗时最长的 $4$ 个任务。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def minProcessingTime(self, processorTime: List[int], tasks: List[int]) -> int: @@ -80,10 +74,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minProcessingTime(List processorTime, List tasks) { @@ -99,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func minProcessingTime(processorTime []int, tasks []int) (ans int) { sort.Ints(processorTime) @@ -132,8 +118,6 @@ func minProcessingTime(processorTime []int, tasks []int) (ans int) { } ``` -### **TypeScript** - ```ts function minProcessingTime(processorTime: number[], tasks: number[]): number { processorTime.sort((a, b) => a - b); @@ -147,10 +131,6 @@ function minProcessingTime(processorTime: number[], tasks: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2895.Minimum Processing Time/README_EN.md b/solution/2800-2899/2895.Minimum Processing Time/README_EN.md index da5c0f9cab378..d49659c456aa0 100644 --- a/solution/2800-2899/2895.Minimum Processing Time/README_EN.md +++ b/solution/2800-2899/2895.Minimum Processing Time/README_EN.md @@ -47,7 +47,7 @@ Hence, it can be shown that the minimum time taken to execute all the tasks is 2 ## Solutions -**Solution 1: Greedy + Sorting** +### Solution 1: Greedy + Sorting To minimize the time required to process all tasks, the four tasks with the longest processing time should be assigned to the processors that become idle earliest. @@ -57,8 +57,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def minProcessingTime(self, processorTime: List[int], tasks: List[int]) -> int: @@ -72,8 +70,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minProcessingTime(List processorTime, List tasks) { @@ -89,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +101,6 @@ public: }; ``` -### **Go** - ```go func minProcessingTime(processorTime []int, tasks []int) (ans int) { sort.Ints(processorTime) @@ -122,8 +114,6 @@ func minProcessingTime(processorTime []int, tasks []int) (ans int) { } ``` -### **TypeScript** - ```ts function minProcessingTime(processorTime: number[], tasks: number[]): number { processorTime.sort((a, b) => a - b); @@ -137,10 +127,6 @@ function minProcessingTime(processorTime: number[], tasks: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/README.md b/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/README.md index 9fd838653c573..78da296cf2da5 100644 --- a/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/README.md +++ b/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们注意到,由于每次操作都是反转两个字符,因此,如果不同的字符个数为奇数,那么无法使两个字符串相等,直接返回 $-1$。否则,我们将两个字符串中不同的字符的下标存入数组 $idx$ 中,记数组长度为 $m$。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, s1: str, s2: str, x: int) -> int: @@ -103,10 +97,6 @@ class Solution: return dfs(0, m - 1) ``` -### **Java** - - - ```java class Solution { private List idx = new ArrayList<>(); @@ -144,38 +134,6 @@ class Solution { } ``` -```java -class Solution { - public int minOperations(String s1, String s2, int x) { - int n = s1.length(); - int inf = 50_000; - int one = inf, two = inf, last = inf; - int done = 0; - for (int i = 0; i < n; i++) { - if (s1.charAt(i) == s2.charAt(i)) { - one = Math.min(one, last); - last = last + 1; - two = two + 1; - continue; - } - if (done < n) { - one = Math.min(two + 1, done + x); - last = Math.min(two + x, done); - done = two = inf; - continue; - } - done = Math.min(one + x, last + 1); - two = one; - one = last = inf; - continue; - } - return done == inf ? -1 : done; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -210,8 +168,6 @@ public: }; ``` -### **Go** - ```go func minOperations(s1 string, s2 string, x int) int { idx := []int{} @@ -248,8 +204,6 @@ func minOperations(s1 string, s2 string, x int) int { } ``` -### **TypeScript** - ```ts function minOperations(s1: string, s2: string, x: number): number { const idx: number[] = []; @@ -282,10 +236,42 @@ function minOperations(s1: string, s2: string, x: number): number { } ``` -### **...** + -``` +### 方法二 + + +```java +class Solution { + public int minOperations(String s1, String s2, int x) { + int n = s1.length(); + int inf = 50_000; + int one = inf, two = inf, last = inf; + int done = 0; + for (int i = 0; i < n; i++) { + if (s1.charAt(i) == s2.charAt(i)) { + one = Math.min(one, last); + last = last + 1; + two = two + 1; + continue; + } + if (done < n) { + one = Math.min(two + 1, done + x); + last = Math.min(two + x, done); + done = two = inf; + continue; + } + done = Math.min(one + x, last + 1); + two = one; + one = last = inf; + continue; + } + return done == inf ? -1 : done; + } +} ``` + + diff --git a/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/README_EN.md b/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/README_EN.md index aa3ca364b61dc..68736acb58dbc 100644 --- a/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/README_EN.md +++ b/solution/2800-2899/2896.Apply Operations to Make Two Strings Equal/README_EN.md @@ -49,7 +49,7 @@ The total cost is 1 + 1 + 2 = 4. It can be shown that it is the minimum cost pos ## Solutions -**Solution 1: Memoization** +### Solution 1: Memoization We notice that since each operation reverses two characters, if the number of different characters in the two strings is odd, it is impossible to make them equal, and we directly return $-1$. Otherwise, we store the indices of the different characters in the two strings in an array $idx$, and let $m$ be the length of $idx$. @@ -73,8 +73,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ -### **Python3** - ```python class Solution: def minOperations(self, s1: str, s2: str, x: int) -> int: @@ -95,8 +93,6 @@ class Solution: return dfs(0, m - 1) ``` -### **Java** - ```java class Solution { private List idx = new ArrayList<>(); @@ -134,38 +130,6 @@ class Solution { } ``` -```java -class Solution { - public int minOperations(String s1, String s2, int x) { - int n = s1.length(); - int inf = 50_000; - int one = inf, two = inf, last = inf; - int done = 0; - for (int i = 0; i < n; i++) { - if (s1.charAt(i) == s2.charAt(i)) { - one = Math.min(one, last); - last = last + 1; - two = two + 1; - continue; - } - if (done < n) { - one = Math.min(two + 1, done + x); - last = Math.min(two + x, done); - done = two = inf; - continue; - } - done = Math.min(one + x, last + 1); - two = one; - one = last = inf; - continue; - } - return done == inf ? -1 : done; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -200,8 +164,6 @@ public: }; ``` -### **Go** - ```go func minOperations(s1 string, s2 string, x int) int { idx := []int{} @@ -238,8 +200,6 @@ func minOperations(s1 string, s2 string, x int) int { } ``` -### **TypeScript** - ```ts function minOperations(s1: string, s2: string, x: number): number { const idx: number[] = []; @@ -272,10 +232,42 @@ function minOperations(s1: string, s2: string, x: number): number { } ``` -### **...** + -``` +### Solution 2 + + +```java +class Solution { + public int minOperations(String s1, String s2, int x) { + int n = s1.length(); + int inf = 50_000; + int one = inf, two = inf, last = inf; + int done = 0; + for (int i = 0; i < n; i++) { + if (s1.charAt(i) == s2.charAt(i)) { + one = Math.min(one, last); + last = last + 1; + two = two + 1; + continue; + } + if (done < n) { + one = Math.min(two + 1, done + x); + last = Math.min(two + x, done); + done = two = inf; + continue; + } + done = Math.min(one + x, last + 1); + two = one; + one = last = inf; + continue; + } + return done == inf ? -1 : done; + } +} ``` + + diff --git a/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/README.md b/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/README.md index f8f31ef892f7a..1f92ce80de78f 100644 --- a/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/README.md +++ b/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:位运算 + 贪心** +### 方法一:位运算 + 贪心 根据题目描述,对于一个操作,我们可以将 $nums[i]$ 变为 $nums[i] \text{ AND } nums[j]$,将 $nums[j]$ 变为 $nums[i] \text{ OR } nums[j]$。我们不妨按位考虑,两个 $1$ 或两个 $0$ 进行这样的操作,结果都不会改变,如果是 $1$ 和 $0$ 进行这样的操作,结果会变成 $0$ 和 $1$,也即是说,我们可以将 $1$ 转移到 $0$ 上,而 $0$ 不会转移到 $1$ 上。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def maxSum(self, nums: List[int], k: int) -> int: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxSum(List nums, int k) { @@ -123,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func maxSum(nums []int, k int) (ans int) { cnt := [31]int{} @@ -181,8 +167,6 @@ func maxSum(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function maxSum(nums: number[], k: number): number { const cnt: number[] = Array(31).fill(0); @@ -209,10 +193,6 @@ function maxSum(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/README_EN.md b/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/README_EN.md index 2b07ae0409758..ea39e30f5b27b 100644 --- a/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/README_EN.md +++ b/solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/README_EN.md @@ -51,7 +51,7 @@ It can be shown that this is the maximum value we can get. ## Solutions -**Solution 1: Bitwise Operation + Greedy** +### Solution 1: Bitwise Operation + Greedy According to the problem description, for an operation, we can change $nums[i]$ to $nums[i] \text{ AND } nums[j]$, and change $nums[j]$ to $nums[i] \text{ OR } nums[j]$. Let's consider the bits of the numbers. If two bits are both $1$ or both $0$, the result of the operation will not change the bits. If two bits are different, the result of the operation will change the bits to $0$ and $1$, respectively. Therefore, we can move $1$ bits to $0$ bits, but not vice versa. @@ -61,8 +61,6 @@ The time complexity is $O(n \times \log M)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def maxSum(self, nums: List[int], k: int) -> int: @@ -83,8 +81,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxSum(List nums, int k) { @@ -113,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +138,6 @@ public: }; ``` -### **Go** - ```go func maxSum(nums []int, k int) (ans int) { cnt := [31]int{} @@ -171,8 +163,6 @@ func maxSum(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function maxSum(nums: number[], k: number): number { const cnt: number[] = Array(31).fill(0); @@ -199,10 +189,6 @@ function maxSum(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2898.Maximum Linear Stock Score/README.md b/solution/2800-2899/2898.Maximum Linear Stock Score/README.md index 8635707cce086..3c88b568a13e9 100644 --- a/solution/2800-2899/2898.Maximum Linear Stock Score/README.md +++ b/solution/2800-2899/2898.Maximum Linear Stock Score/README.md @@ -57,9 +57,7 @@ prices[5] - prices[4] = 8 - 7 = 1。 ## 解法 - - -**方法一:哈希表** +### 方法一:哈希表 我们可以将式子进行变换,得到: @@ -75,10 +73,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxScore(self, prices: List[int]) -> int: @@ -88,10 +82,6 @@ class Solution: return max(cnt.values()) ``` -### **Java** - - - ```java class Solution { public long maxScore(int[] prices) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -127,8 +115,6 @@ public: }; ``` -### **Go** - ```go func maxScore(prices []int) (ans int64) { cnt := map[int]int{} @@ -142,7 +128,16 @@ func maxScore(prices []int) (ans int64) { } ``` -### **Rust** +```ts +function maxScore(prices: number[]): number { + const cnt: Map = new Map(); + for (let i = 0; i < prices.length; ++i) { + const j = prices[i] - i; + cnt.set(j, (cnt.get(j) || 0) + prices[i]); + } + return Math.max(...cnt.values()); +} +``` ```rust use std::collections::HashMap; @@ -162,23 +157,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function maxScore(prices: number[]): number { - const cnt: Map = new Map(); - for (let i = 0; i < prices.length; ++i) { - const j = prices[i] - i; - cnt.set(j, (cnt.get(j) || 0) + prices[i]); - } - return Math.max(...cnt.values()); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2898.Maximum Linear Stock Score/README_EN.md b/solution/2800-2899/2898.Maximum Linear Stock Score/README_EN.md index a22d304cd0712..35d28029a7ed0 100644 --- a/solution/2800-2899/2898.Maximum Linear Stock Score/README_EN.md +++ b/solution/2800-2899/2898.Maximum Linear Stock Score/README_EN.md @@ -53,7 +53,7 @@ The sum of all the elements is 35 which is the maximum possible some out of ever ## Solutions -**Solution 1: Hash Table** +### Solution 1: Hash Table We can transform the equation as follows: @@ -69,8 +69,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is -### **Python3** - ```python class Solution: def maxScore(self, prices: List[int]) -> int: @@ -80,8 +78,6 @@ class Solution: return max(cnt.values()) ``` -### **Java** - ```java class Solution { public long maxScore(int[] prices) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +111,6 @@ public: }; ``` -### **Go** - ```go func maxScore(prices []int) (ans int64) { cnt := map[int]int{} @@ -132,7 +124,16 @@ func maxScore(prices []int) (ans int64) { } ``` -### **Rust** +```ts +function maxScore(prices: number[]): number { + const cnt: Map = new Map(); + for (let i = 0; i < prices.length; ++i) { + const j = prices[i] - i; + cnt.set(j, (cnt.get(j) || 0) + prices[i]); + } + return Math.max(...cnt.values()); +} +``` ```rust use std::collections::HashMap; @@ -152,23 +153,6 @@ impl Solution { } ``` -### **TypeScript** - -```ts -function maxScore(prices: number[]): number { - const cnt: Map = new Map(); - for (let i = 0; i < prices.length; ++i) { - const j = prices[i] - i; - cnt.set(j, (cnt.get(j) || 0) + prices[i]); - } - return Math.max(...cnt.values()); -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2899.Last Visited Integers/README.md b/solution/2800-2899/2899.Last Visited Integers/README.md index 3124f3515bf49..0af5f5270b677 100644 --- a/solution/2800-2899/2899.Last Visited Integers/README.md +++ b/solution/2800-2899/2899.Last Visited Integers/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 我们直接根据题意模拟即可。在实现上,我们使用一个数组 $nums$ 来存储遍历过的整数,使用一个整数 $k$ 来记录当前连续的 $prev$ 字符串数目。如果当前字符串是 $prev$,那么我们就从 $nums$ 中取出第 $|nums| - k$ 个整数,如果不存在,那么就返回 $-1$。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def lastVisitedIntegers(self, words: List[str]) -> List[int]: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List lastVisitedIntegers(List words) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -132,8 +120,6 @@ public: }; ``` -### **Go** - ```go func lastVisitedIntegers(words []string) (ans []int) { nums := []int{} @@ -157,8 +143,6 @@ func lastVisitedIntegers(words []string) (ans []int) { } ``` -### **TypeScript** - ```ts function lastVisitedIntegers(words: string[]): number[] { const nums: number[] = []; @@ -178,8 +162,6 @@ function lastVisitedIntegers(words: string[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn last_visited_integers(words: Vec) -> Vec { @@ -203,10 +185,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2800-2899/2899.Last Visited Integers/README_EN.md b/solution/2800-2899/2899.Last Visited Integers/README_EN.md index 5267739e590e8..9f0078e0fe484 100644 --- a/solution/2800-2899/2899.Last Visited Integers/README_EN.md +++ b/solution/2800-2899/2899.Last Visited Integers/README_EN.md @@ -48,7 +48,7 @@ For "prev" at index = 4, last visited integer will be 1 as there are a ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation We can directly simulate according to the problem statement. In the implementation, we use an array $nums$ to store the traversed integers, and an integer $k$ to record the current number of consecutive $prev$ strings. If the current string is $prev$, we take out the $|nums| - k-th$ integer from $nums$. If it does not exist, we return $-1$. @@ -56,8 +56,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $words$. The -### **Python3** - ```python class Solution: def lastVisitedIntegers(self, words: List[str]) -> List[int]: @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List lastVisitedIntegers(List words) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func lastVisitedIntegers(words []string) (ans []int) { nums := []int{} @@ -147,8 +139,6 @@ func lastVisitedIntegers(words []string) (ans []int) { } ``` -### **TypeScript** - ```ts function lastVisitedIntegers(words: string[]): number[] { const nums: number[] = []; @@ -168,8 +158,6 @@ function lastVisitedIntegers(words: string[]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn last_visited_integers(words: Vec) -> Vec { @@ -193,10 +181,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README.md b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README.md index e5645172783be..5e797340ee226 100644 --- a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README.md +++ b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README.md @@ -56,9 +56,7 @@ ## 解法 - - -**方法一:贪心 + 一次遍历** +### 方法一:贪心 + 一次遍历 我们可以遍历数组 $groups$,对于当前遍历到的下标 $i$,如果 $i=0$ 或者 $groups[i] \neq groups[i - 1]$,我们就将 $words[i]$ 加入答案数组中。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def getWordsInLongestSubsequence( @@ -78,10 +72,6 @@ class Solution: return [words[i] for i, x in enumerate(groups) if i == 0 or x != groups[i - 1]] ``` -### **Java** - - - ```java class Solution { public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +101,6 @@ public: }; ``` -### **Go** - ```go func getWordsInLongestSubsequence(n int, words []string, groups []int) (ans []string) { for i, x := range groups { @@ -126,8 +112,6 @@ func getWordsInLongestSubsequence(n int, words []string, groups []int) (ans []st } ``` -### **TypeScript** - ```ts function getWordsInLongestSubsequence(n: number, words: string[], groups: number[]): string[] { const ans: string[] = []; @@ -140,8 +124,6 @@ function getWordsInLongestSubsequence(n: number, words: string[], groups: number } ``` -### **Rust** - ```rust impl Solution { pub fn get_words_in_longest_subsequence( @@ -162,10 +144,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README_EN.md b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README_EN.md index 7aaac16d981b3..8935fba57c4d0 100644 --- a/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README_EN.md +++ b/solution/2900-2999/2900.Longest Unequal Adjacent Groups Subsequence I/README_EN.md @@ -53,7 +53,7 @@ It can be shown that the length of the longest subsequence of indices that satis ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy We can traverse the array $groups$, and for the current index $i$, if $i=0$ or $groups[i] \neq groups[i - 1]$, we add $words[i]$ to the answer array. @@ -61,8 +61,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $groups$. Th -### **Python3** - ```python class Solution: def getWordsInLongestSubsequence( @@ -71,8 +69,6 @@ class Solution: return [words[i] for i, x in enumerate(groups) if i == 0 or x != groups[i - 1]] ``` -### **Java** - ```java class Solution { public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { @@ -87,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -104,8 +98,6 @@ public: }; ``` -### **Go** - ```go func getWordsInLongestSubsequence(n int, words []string, groups []int) (ans []string) { for i, x := range groups { @@ -117,8 +109,6 @@ func getWordsInLongestSubsequence(n int, words []string, groups []int) (ans []st } ``` -### **TypeScript** - ```ts function getWordsInLongestSubsequence(n: number, words: string[], groups: number[]): string[] { const ans: string[] = []; @@ -131,8 +121,6 @@ function getWordsInLongestSubsequence(n: number, words: string[], groups: number } ``` -### **Rust** - ```rust impl Solution { pub fn get_words_in_longest_subsequence( @@ -153,10 +141,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/README.md b/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/README.md index 5d7e8097006df..1d1a5222199c4 100644 --- a/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/README.md +++ b/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/README.md @@ -66,9 +66,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示以第 $i$ 个单词结尾的最长相邻不相等子序列的长度,定义 $g[i]$ 表示以第 $i$ 个单词结尾的最长相邻不相等子序列的前驱下标。初始时 $f[i] = 1$, $g[i] = -1$。 @@ -86,10 +84,6 @@ -### **Python3** - - - ```python class Solution: def getWordsInLongestSubsequence( @@ -118,10 +112,6 @@ class Solution: return ans[::-1] ``` -### **Java** - - - ```java class Solution { public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { @@ -167,56 +157,6 @@ class Solution { } ``` -```java -class Solution { - public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { - int[] dp = new int[n]; - int[] next = new int[n]; - Map> strToIdxMap = new HashMap<>(); - int maxIdx = n; - for (int i = n - 1; i >= 0; i--) { - int prevIdx = n; - char[] word = words[i].toCharArray(); - for (int j = 0; j < word.length; j++) { - // convert word to pattern with '*'. - char temp = word[j]; - word[j] = '*'; - String curr = new String(word); - - // search matches and update dp. - List prevList = strToIdxMap.getOrDefault(curr, List.of()); - for (int prev : prevList) { - if (groups[prev] == groups[i] || dp[prev] < dp[i]) { - continue; - } - dp[i] = dp[prev] + 1; - prevIdx = prev; - } - - // append current pattern to dictionary. - strToIdxMap.computeIfAbsent(curr, k -> new ArrayList<>()).add(i); - - // restore pattern to orignal word. - word[j] = temp; - } - if (maxIdx >= n || dp[i] > dp[maxIdx]) { - maxIdx = i; - } - next[i] = prevIdx; - } - int curr = maxIdx; - List ans = new ArrayList<>(); - while (curr < n) { - ans.add(words[curr]); - curr = next[curr]; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -258,8 +198,6 @@ public: }; ``` -### **Go** - ```go func getWordsInLongestSubsequence(n int, words []string, groups []int) []string { check := func(s, t string) bool { @@ -308,8 +246,6 @@ func getWordsInLongestSubsequence(n int, words []string, groups []int) []string } ``` -### **TypeScript** - ```ts function getWordsInLongestSubsequence(n: number, words: string[], groups: number[]): string[] { const f: number[] = Array(n).fill(1); @@ -349,8 +285,6 @@ function getWordsInLongestSubsequence(n: number, words: string[], groups: number } ``` -### **Rust** - ```rust impl Solution { pub fn get_words_in_longest_subsequence( @@ -405,10 +339,60 @@ impl Solution { } ``` -### **...** + -``` +### 方法二 + + + +```java +class Solution { + public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { + int[] dp = new int[n]; + int[] next = new int[n]; + Map> strToIdxMap = new HashMap<>(); + int maxIdx = n; + for (int i = n - 1; i >= 0; i--) { + int prevIdx = n; + char[] word = words[i].toCharArray(); + for (int j = 0; j < word.length; j++) { + // convert word to pattern with '*'. + char temp = word[j]; + word[j] = '*'; + String curr = new String(word); + + // search matches and update dp. + List prevList = strToIdxMap.getOrDefault(curr, List.of()); + for (int prev : prevList) { + if (groups[prev] == groups[i] || dp[prev] < dp[i]) { + continue; + } + dp[i] = dp[prev] + 1; + prevIdx = prev; + } + + // append current pattern to dictionary. + strToIdxMap.computeIfAbsent(curr, k -> new ArrayList<>()).add(i); + // restore pattern to orignal word. + word[j] = temp; + } + if (maxIdx >= n || dp[i] > dp[maxIdx]) { + maxIdx = i; + } + next[i] = prevIdx; + } + int curr = maxIdx; + List ans = new ArrayList<>(); + while (curr < n) { + ans.add(words[curr]); + curr = next[curr]; + } + return ans; + } +} ``` + + diff --git a/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/README_EN.md b/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/README_EN.md index 3bfdc6178e752..63e4f76c605a2 100644 --- a/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/README_EN.md +++ b/solution/2900-2999/2901.Longest Unequal Adjacent Groups Subsequence II/README_EN.md @@ -62,7 +62,7 @@ Hence, it is the only answer. ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i]$ as the length of the longest adjacent non-equal subsequence ending with the $i$-th word, and $g[i]$ as the predecessor index of the longest adjacent non-equal subsequence ending with the $i$-th word. Initially, we set $f[i] = 1$ and $g[i] = -1$. @@ -80,8 +80,6 @@ In **Solution 1**, we need to enumerate all $i$ and $j$ combinations, a step tha -### **Python3** - ```python class Solution: def getWordsInLongestSubsequence( @@ -110,8 +108,6 @@ class Solution: return ans[::-1] ``` -### **Java** - ```java class Solution { public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { @@ -157,56 +153,6 @@ class Solution { } ``` -```java -class Solution { - public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { - int[] dp = new int[n]; - int[] next = new int[n]; - Map> strToIdxMap = new HashMap<>(); - int maxIdx = n; - for (int i = n - 1; i >= 0; i--) { - int prevIdx = n; - char[] word = words[i].toCharArray(); - for (int j = 0; j < word.length; j++) { - // convert word to pattern with '*'. - char temp = word[j]; - word[j] = '*'; - String curr = new String(word); - - // search matches and update dp. - List prevList = strToIdxMap.getOrDefault(curr, List.of()); - for (int prev : prevList) { - if (groups[prev] == groups[i] || dp[prev] < dp[i]) { - continue; - } - dp[i] = dp[prev] + 1; - prevIdx = prev; - } - - // append current pattern to dictionary. - strToIdxMap.computeIfAbsent(curr, k -> new ArrayList<>()).add(i); - - // restore pattern to orignal word. - word[j] = temp; - } - if (maxIdx >= n || dp[i] > dp[maxIdx]) { - maxIdx = i; - } - next[i] = prevIdx; - } - int curr = maxIdx; - List ans = new ArrayList<>(); - while (curr < n) { - ans.add(words[curr]); - curr = next[curr]; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -248,8 +194,6 @@ public: }; ``` -### **Go** - ```go func getWordsInLongestSubsequence(n int, words []string, groups []int) []string { check := func(s, t string) bool { @@ -298,8 +242,6 @@ func getWordsInLongestSubsequence(n int, words []string, groups []int) []string } ``` -### **TypeScript** - ```ts function getWordsInLongestSubsequence(n: number, words: string[], groups: number[]): string[] { const f: number[] = Array(n).fill(1); @@ -339,8 +281,6 @@ function getWordsInLongestSubsequence(n: number, words: string[], groups: number } ``` -### **Rust** - ```rust impl Solution { pub fn get_words_in_longest_subsequence( @@ -395,10 +335,60 @@ impl Solution { } ``` -### **...** + + +### Solution 2 -``` + + +```java +class Solution { + public List getWordsInLongestSubsequence(int n, String[] words, int[] groups) { + int[] dp = new int[n]; + int[] next = new int[n]; + Map> strToIdxMap = new HashMap<>(); + int maxIdx = n; + for (int i = n - 1; i >= 0; i--) { + int prevIdx = n; + char[] word = words[i].toCharArray(); + for (int j = 0; j < word.length; j++) { + // convert word to pattern with '*'. + char temp = word[j]; + word[j] = '*'; + String curr = new String(word); + + // search matches and update dp. + List prevList = strToIdxMap.getOrDefault(curr, List.of()); + for (int prev : prevList) { + if (groups[prev] == groups[i] || dp[prev] < dp[i]) { + continue; + } + dp[i] = dp[prev] + 1; + prevIdx = prev; + } + // append current pattern to dictionary. + strToIdxMap.computeIfAbsent(curr, k -> new ArrayList<>()).add(i); + + // restore pattern to orignal word. + word[j] = temp; + } + if (maxIdx >= n || dp[i] > dp[maxIdx]) { + maxIdx = i; + } + next[i] = prevIdx; + } + int curr = maxIdx; + List ans = new ArrayList<>(); + while (curr < n) { + ans.add(words[curr]); + curr = next[curr]; + } + return ans; + } +} ``` + + diff --git a/solution/2900-2999/2902.Count of Sub-Multisets With Bounded Sum/README.md b/solution/2900-2999/2902.Count of Sub-Multisets With Bounded Sum/README.md index eea504b5136cd..1cd43c7548606 100644 --- a/solution/2900-2999/2902.Count of Sub-Multisets With Bounded Sum/README.md +++ b/solution/2900-2999/2902.Count of Sub-Multisets With Bounded Sum/README.md @@ -59,14 +59,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def countSubMultisets(self, nums: List[int], l: int, r: int) -> int: @@ -91,10 +87,6 @@ class Solution: return (zeros + 1) * sum(dp[l : r + 1]) % kMod ``` -### **Java** - - - ```java class Solution { static final int MOD = 1_000_000_007; @@ -143,22 +135,6 @@ class Solution { } ``` -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2902.Count of Sub-Multisets With Bounded Sum/README_EN.md b/solution/2900-2999/2902.Count of Sub-Multisets With Bounded Sum/README_EN.md index fcc04e36d271a..a018a8cfe40bf 100644 --- a/solution/2900-2999/2902.Count of Sub-Multisets With Bounded Sum/README_EN.md +++ b/solution/2900-2999/2902.Count of Sub-Multisets With Bounded Sum/README_EN.md @@ -55,9 +55,9 @@ ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,8 +83,6 @@ class Solution: return (zeros + 1) * sum(dp[l : r + 1]) % kMod ``` -### **Java** - ```java class Solution { static final int MOD = 1_000_000_007; @@ -133,22 +131,6 @@ class Solution { } ``` -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2903.Find Indices With Index and Value Difference I/README.md b/solution/2900-2999/2903.Find Indices With Index and Value Difference I/README.md index b5aa2477e31aa..82a8d2bbb6c58 100644 --- a/solution/2900-2999/2903.Find Indices With Index and Value Difference I/README.md +++ b/solution/2900-2999/2903.Find Indices With Index and Value Difference I/README.md @@ -65,9 +65,7 @@ abs(0 - 0) >= 0 且 abs(nums[0] - nums[0]) >= 0 。 ## 解法 - - -**方法一:双指针 + 维护最大最小值** +### 方法一:双指针 + 维护最大最小值 我们用两个指针 $i$ 和 $j$ 来维护一个间隔为 $indexDifference$ 的滑动窗口,其中指针 $j$ 和 $i$ 分别指向窗口的左右边界。初始时 $i$ 指向 $indexDifference$,而 $j$ 指向 $0$。 @@ -81,10 +79,6 @@ abs(0 - 0) >= 0 且 abs(nums[0] - nums[0]) >= 0 。 -### **Python3** - - - ```python class Solution: def findIndices( @@ -104,10 +98,6 @@ class Solution: return [-1, -1] ``` -### **Java** - - - ```java class Solution { public int[] findIndices(int[] nums, int indexDifference, int valueDifference) { @@ -133,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -160,8 +148,6 @@ public: }; ``` -### **Go** - ```go func findIndices(nums []int, indexDifference int, valueDifference int) []int { mi, mx := 0, 0 @@ -184,8 +170,6 @@ func findIndices(nums []int, indexDifference int, valueDifference int) []int { } ``` -### **TypeScript** - ```ts function findIndices(nums: number[], indexDifference: number, valueDifference: number): number[] { let [mi, mx] = [0, 0]; @@ -208,8 +192,6 @@ function findIndices(nums: number[], indexDifference: number, valueDifference: n } ``` -### **Rust** - ```rust impl Solution { pub fn find_indices(nums: Vec, index_difference: i32, value_difference: i32) -> Vec { @@ -242,10 +224,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2903.Find Indices With Index and Value Difference I/README_EN.md b/solution/2900-2999/2903.Find Indices With Index and Value Difference I/README_EN.md index 4042c64c15e2a..47614ec73f6ba 100644 --- a/solution/2900-2999/2903.Find Indices With Index and Value Difference I/README_EN.md +++ b/solution/2900-2999/2903.Find Indices With Index and Value Difference I/README_EN.md @@ -60,7 +60,7 @@ Hence, [-1,-1] is returned. ## Solutions -**Solution 1: Two Pointers + Maintaining Maximum and Minimum Values** +### Solution 1: Two Pointers + Maintaining Maximum and Minimum Values We use two pointers $i$ and $j$ to maintain a sliding window with a gap of $indexDifference$, where $j$ and $i$ point to the left and right boundaries of the window, respectively. Initially, $i$ points to $indexDifference$, and $j` points to $0$. @@ -74,8 +74,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def findIndices( @@ -95,8 +93,6 @@ class Solution: return [-1, -1] ``` -### **Java** - ```java class Solution { public int[] findIndices(int[] nums, int indexDifference, int valueDifference) { @@ -122,8 +118,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +143,6 @@ public: }; ``` -### **Go** - ```go func findIndices(nums []int, indexDifference int, valueDifference int) []int { mi, mx := 0, 0 @@ -173,8 +165,6 @@ func findIndices(nums []int, indexDifference int, valueDifference int) []int { } ``` -### **TypeScript** - ```ts function findIndices(nums: number[], indexDifference: number, valueDifference: number): number[] { let [mi, mx] = [0, 0]; @@ -197,8 +187,6 @@ function findIndices(nums: number[], indexDifference: number, valueDifference: n } ``` -### **Rust** - ```rust impl Solution { pub fn find_indices(nums: Vec, index_difference: i32, value_difference: i32) -> Vec { @@ -231,10 +219,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/README.md b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/README.md index b57e63a852b89..e90381cd543e5 100644 --- a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/README.md +++ b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/README.md @@ -71,30 +71,14 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举所有子字符串 $s[i: j]$,其中 $i \lt j$,并检查它们是否是美丽子字符串。如果是,我们就更新答案。 时间复杂度 $O(n^3)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $s$ 的长度。 -**方法二:双指针** - -我们也可以用两个指针维护一个滑动窗口,其中指针 $i$ 指向滑动窗口的左端点,指针 $j$ 指向滑动窗口的右端点。初始时 $i = j = 0$。另外,我们用变量 $cnt$ 记录滑动窗口中的 $1$ 的个数。 - -我们首先将指针 $j$ 向右移动,将 $s[j]$ 加入到滑动窗口中,并更新 $cnt$。如果 $cnt \gt k$,或者 $i \lt j$ 并且 $s[i]=0$,我们就循环将指针 $i$ 往右移动,并且更新 $cnt$。 - -当 $cnt = k$ 时,我们就找到了一个美丽子字符串。我们将它与当前的答案进行比较,并更新答案。 - -时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $s$ 的长度。 - -### **Python3** - - - ```python class Solution: def shortestBeautifulSubstring(self, s: str, k: int) -> str: @@ -110,29 +94,6 @@ class Solution: return ans ``` -```python -class Solution: - def shortestBeautifulSubstring(self, s: str, k: int) -> str: - i = j = cnt = 0 - n = len(s) - ans = "" - while j < n: - cnt += s[j] == "1" - while cnt > k or (i < j and s[i] == "0"): - cnt -= s[i] == "1" - i += 1 - j += 1 - if cnt == k and ( - not ans or j - i < len(ans) or (j - i == len(ans) and s[i:j] < ans) - ): - ans = s[i:j] - return ans -``` - -### **Java** - - - ```java class Solution { public String shortestBeautifulSubstring(String s, int k) { @@ -157,6 +118,122 @@ class Solution { } ``` +```cpp +class Solution { +public: + string shortestBeautifulSubstring(string s, int k) { + int n = s.size(); + string ans = ""; + for (int i = 0; i < n; ++i) { + for (int j = i + k; j <= n; ++j) { + string t = s.substr(i, j - i); + int cnt = count(t.begin(), t.end(), '1'); + if (cnt == k && (ans == "" || j - i < ans.size() || (j - i == ans.size() && t < ans))) { + ans = t; + } + } + } + return ans; + } +}; +``` + +```go +func shortestBeautifulSubstring(s string, k int) (ans string) { + n := len(s) + for i := 0; i < n; i++ { + for j := i + k; j <= n; j++ { + t := s[i:j] + cnt := 0 + for _, c := range t { + if c == '1' { + cnt++ + } + } + if cnt == k && (ans == "" || j-i < len(ans) || (j-i == len(ans) && t < ans)) { + ans = t + } + } + } + return +} +``` + +```ts +function shortestBeautifulSubstring(s: string, k: number): string { + const n = s.length; + let ans: string = ''; + for (let i = 0; i < n; ++i) { + for (let j = i + k; j <= n; ++j) { + const t = s.slice(i, j); + const cnt = t.split('').filter(c => c === '1').length; + if ( + cnt === k && + (ans === '' || j - i < ans.length || (j - i === ans.length && t < ans)) + ) { + ans = t; + } + } + } + return ans; +} +``` + +```rust +impl Solution { + pub fn shortest_beautiful_substring(s: String, k: i32) -> String { + let n = s.len(); + let mut ans = String::new(); + + for i in 0..n { + for j in i + (k as usize)..=n { + let t = &s[i..j]; + if + (t.matches('1').count() as i32) == k && + (ans.is_empty() || j - i < ans.len() || (j - i == ans.len() && t < &ans)) + { + ans = t.to_string(); + } + } + } + ans + } +} +``` + + + +### 方法二:双指针 + +我们也可以用两个指针维护一个滑动窗口,其中指针 $i$ 指向滑动窗口的左端点,指针 $j$ 指向滑动窗口的右端点。初始时 $i = j = 0$。另外,我们用变量 $cnt$ 记录滑动窗口中的 $1$ 的个数。 + +我们首先将指针 $j$ 向右移动,将 $s[j]$ 加入到滑动窗口中,并更新 $cnt$。如果 $cnt \gt k$,或者 $i \lt j$ 并且 $s[i]=0$,我们就循环将指针 $i$ 往右移动,并且更新 $cnt$。 + +当 $cnt = k$ 时,我们就找到了一个美丽子字符串。我们将它与当前的答案进行比较,并更新答案。 + +时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $s$ 的长度。 + + + +```python +class Solution: + def shortestBeautifulSubstring(self, s: str, k: int) -> str: + i = j = cnt = 0 + n = len(s) + ans = "" + while j < n: + cnt += s[j] == "1" + while cnt > k or (i < j and s[i] == "0"): + cnt -= s[i] == "1" + i += 1 + j += 1 + if cnt == k and ( + not ans or j - i < len(ans) or (j - i == len(ans) and s[i:j] < ans) + ): + ans = s[i:j] + return ans +``` + ```java class Solution { public String shortestBeautifulSubstring(String s, int k) { @@ -182,28 +259,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string shortestBeautifulSubstring(string s, int k) { - int n = s.size(); - string ans = ""; - for (int i = 0; i < n; ++i) { - for (int j = i + k; j <= n; ++j) { - string t = s.substr(i, j - i); - int cnt = count(t.begin(), t.end(), '1'); - if (cnt == k && (ans == "" || j - i < ans.size() || (j - i == ans.size() && t < ans))) { - ans = t; - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -227,29 +282,6 @@ public: }; ``` -### **Go** - -```go -func shortestBeautifulSubstring(s string, k int) (ans string) { - n := len(s) - for i := 0; i < n; i++ { - for j := i + k; j <= n; j++ { - t := s[i:j] - cnt := 0 - for _, c := range t { - if c == '1' { - cnt++ - } - } - if cnt == k && (ans == "" || j-i < len(ans) || (j-i == len(ans) && t < ans)) { - ans = t - } - } - } - return -} -``` - ```go func shortestBeautifulSubstring(s string, k int) (ans string) { i, j, cnt := 0, 0, 0 @@ -270,28 +302,6 @@ func shortestBeautifulSubstring(s string, k int) (ans string) { } ``` -### **TypeScript** - -```ts -function shortestBeautifulSubstring(s: string, k: number): string { - const n = s.length; - let ans: string = ''; - for (let i = 0; i < n; ++i) { - for (let j = i + k; j <= n; ++j) { - const t = s.slice(i, j); - const cnt = t.split('').filter(c => c === '1').length; - if ( - cnt === k && - (ans === '' || j - i < ans.length || (j - i === ans.length && t < ans)) - ) { - ans = t; - } - } - } - return ans; -} -``` - ```ts function shortestBeautifulSubstring(s: string, k: number): string { let [i, j, cnt] = [0, 0, 0]; @@ -312,30 +322,6 @@ function shortestBeautifulSubstring(s: string, k: number): string { } ``` -### **Rust** - -```rust -impl Solution { - pub fn shortest_beautiful_substring(s: String, k: i32) -> String { - let n = s.len(); - let mut ans = String::new(); - - for i in 0..n { - for j in i + (k as usize)..=n { - let t = &s[i..j]; - if - (t.matches('1').count() as i32) == k && - (ans.is_empty() || j - i < ans.len() || (j - i == ans.len() && t < &ans)) - { - ans = t.to_string(); - } - } - } - ans - } -} -``` - ```rust impl Solution { pub fn shortest_beautiful_substring(s: String, k: i32) -> String { @@ -373,10 +359,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/README_EN.md b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/README_EN.md index 59d93e2ce2020..5dfde3f80ae04 100644 --- a/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/README_EN.md +++ b/solution/2900-2999/2904.Shortest and Lexicographically Smallest Beautiful String/README_EN.md @@ -67,26 +67,14 @@ The lexicographically smallest beautiful substring with length 2 is the substrin ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We can enumerate all substrings $s[i: j]$, where $i \lt j$, and check if they are beautiful substrings. If so, we update the answer. The time complexity is $O(n^3)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$. -**Solution 2: Two Pointers** - -We can also use two pointers to maintain a sliding window, where pointer $i$ points to the left boundary of the window, and pointer $j$ points to the right boundary of the window. Initially, $i$ and $j$ both point to $0$. In addition, we use a variable $cnt$ to record the number of $1$s in the sliding window. - -We first move pointer $j$ to the right, add $s[j]$ to the sliding window, and update $cnt$. If $cnt$ is greater than $k$, or if $i$ is less than $j$ and $s[i]$ is $0$, we move pointer $i$ to the right and update $cnt$. - -When $cnt$ equals $k$, we have found a beautiful substring. We compare it with the current answer and update the answer if necessary. - -The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$. - -### **Python3** - ```python class Solution: def shortestBeautifulSubstring(self, s: str, k: int) -> str: @@ -102,27 +90,6 @@ class Solution: return ans ``` -```python -class Solution: - def shortestBeautifulSubstring(self, s: str, k: int) -> str: - i = j = cnt = 0 - n = len(s) - ans = "" - while j < n: - cnt += s[j] == "1" - while cnt > k or (i < j and s[i] == "0"): - cnt -= s[i] == "1" - i += 1 - j += 1 - if cnt == k and ( - not ans or j - i < len(ans) or (j - i == len(ans) and s[i:j] < ans) - ): - ans = s[i:j] - return ans -``` - -### **Java** - ```java class Solution { public String shortestBeautifulSubstring(String s, int k) { @@ -147,6 +114,122 @@ class Solution { } ``` +```cpp +class Solution { +public: + string shortestBeautifulSubstring(string s, int k) { + int n = s.size(); + string ans = ""; + for (int i = 0; i < n; ++i) { + for (int j = i + k; j <= n; ++j) { + string t = s.substr(i, j - i); + int cnt = count(t.begin(), t.end(), '1'); + if (cnt == k && (ans == "" || j - i < ans.size() || (j - i == ans.size() && t < ans))) { + ans = t; + } + } + } + return ans; + } +}; +``` + +```go +func shortestBeautifulSubstring(s string, k int) (ans string) { + n := len(s) + for i := 0; i < n; i++ { + for j := i + k; j <= n; j++ { + t := s[i:j] + cnt := 0 + for _, c := range t { + if c == '1' { + cnt++ + } + } + if cnt == k && (ans == "" || j-i < len(ans) || (j-i == len(ans) && t < ans)) { + ans = t + } + } + } + return +} +``` + +```ts +function shortestBeautifulSubstring(s: string, k: number): string { + const n = s.length; + let ans: string = ''; + for (let i = 0; i < n; ++i) { + for (let j = i + k; j <= n; ++j) { + const t = s.slice(i, j); + const cnt = t.split('').filter(c => c === '1').length; + if ( + cnt === k && + (ans === '' || j - i < ans.length || (j - i === ans.length && t < ans)) + ) { + ans = t; + } + } + } + return ans; +} +``` + +```rust +impl Solution { + pub fn shortest_beautiful_substring(s: String, k: i32) -> String { + let n = s.len(); + let mut ans = String::new(); + + for i in 0..n { + for j in i + (k as usize)..=n { + let t = &s[i..j]; + if + (t.matches('1').count() as i32) == k && + (ans.is_empty() || j - i < ans.len() || (j - i == ans.len() && t < &ans)) + { + ans = t.to_string(); + } + } + } + ans + } +} +``` + + + +### Solution 2: Two Pointers + +We can also use two pointers to maintain a sliding window, where pointer $i$ points to the left boundary of the window, and pointer $j$ points to the right boundary of the window. Initially, $i$ and $j$ both point to $0$. In addition, we use a variable $cnt$ to record the number of $1$s in the sliding window. + +We first move pointer $j$ to the right, add $s[j]$ to the sliding window, and update $cnt$. If $cnt$ is greater than $k$, or if $i$ is less than $j$ and $s[i]$ is $0$, we move pointer $i$ to the right and update $cnt$. + +When $cnt$ equals $k$, we have found a beautiful substring. We compare it with the current answer and update the answer if necessary. + +The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$. + + + +```python +class Solution: + def shortestBeautifulSubstring(self, s: str, k: int) -> str: + i = j = cnt = 0 + n = len(s) + ans = "" + while j < n: + cnt += s[j] == "1" + while cnt > k or (i < j and s[i] == "0"): + cnt -= s[i] == "1" + i += 1 + j += 1 + if cnt == k and ( + not ans or j - i < len(ans) or (j - i == len(ans) and s[i:j] < ans) + ): + ans = s[i:j] + return ans +``` + ```java class Solution { public String shortestBeautifulSubstring(String s, int k) { @@ -172,28 +255,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - string shortestBeautifulSubstring(string s, int k) { - int n = s.size(); - string ans = ""; - for (int i = 0; i < n; ++i) { - for (int j = i + k; j <= n; ++j) { - string t = s.substr(i, j - i); - int cnt = count(t.begin(), t.end(), '1'); - if (cnt == k && (ans == "" || j - i < ans.size() || (j - i == ans.size() && t < ans))) { - ans = t; - } - } - } - return ans; - } -}; -``` - ```cpp class Solution { public: @@ -217,29 +278,6 @@ public: }; ``` -### **Go** - -```go -func shortestBeautifulSubstring(s string, k int) (ans string) { - n := len(s) - for i := 0; i < n; i++ { - for j := i + k; j <= n; j++ { - t := s[i:j] - cnt := 0 - for _, c := range t { - if c == '1' { - cnt++ - } - } - if cnt == k && (ans == "" || j-i < len(ans) || (j-i == len(ans) && t < ans)) { - ans = t - } - } - } - return -} -``` - ```go func shortestBeautifulSubstring(s string, k int) (ans string) { i, j, cnt := 0, 0, 0 @@ -260,28 +298,6 @@ func shortestBeautifulSubstring(s string, k int) (ans string) { } ``` -### **TypeScript** - -```ts -function shortestBeautifulSubstring(s: string, k: number): string { - const n = s.length; - let ans: string = ''; - for (let i = 0; i < n; ++i) { - for (let j = i + k; j <= n; ++j) { - const t = s.slice(i, j); - const cnt = t.split('').filter(c => c === '1').length; - if ( - cnt === k && - (ans === '' || j - i < ans.length || (j - i === ans.length && t < ans)) - ) { - ans = t; - } - } - } - return ans; -} -``` - ```ts function shortestBeautifulSubstring(s: string, k: number): string { let [i, j, cnt] = [0, 0, 0]; @@ -302,30 +318,6 @@ function shortestBeautifulSubstring(s: string, k: number): string { } ``` -### **Rust** - -```rust -impl Solution { - pub fn shortest_beautiful_substring(s: String, k: i32) -> String { - let n = s.len(); - let mut ans = String::new(); - - for i in 0..n { - for j in i + (k as usize)..=n { - let t = &s[i..j]; - if - (t.matches('1').count() as i32) == k && - (ans.is_empty() || j - i < ans.len() || (j - i == ans.len() && t < &ans)) - { - ans = t.to_string(); - } - } - } - ans - } -} -``` - ```rust impl Solution { pub fn shortest_beautiful_substring(s: String, k: i32) -> String { @@ -363,10 +355,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2905.Find Indices With Index and Value Difference II/README.md b/solution/2900-2999/2905.Find Indices With Index and Value Difference II/README.md index c5ef64b1547ff..01f61697ac2d4 100644 --- a/solution/2900-2999/2905.Find Indices With Index and Value Difference II/README.md +++ b/solution/2900-2999/2905.Find Indices With Index and Value Difference II/README.md @@ -65,28 +65,10 @@ abs(0 - 0) >= 0 且 abs(nums[0] - nums[0]) >= 0 。 ## 解法 - - -## Solutions - -**Solution 1: Two Pointers + Maintaining Maximum and Minimum Values** - -We use two pointers $i$ and $j$ to maintain a sliding window with a gap of $indexDifference$, where $j$ and $i$ point to the left and right boundaries of the window, respectively. Initially, $i$ points to $indexDifference$, and $j` points to $0$. - -We use $mi$ and $mx$ to maintain the indices of the minimum and maximum values to the left of pointer $j$. - -When pointer $i$ moves to the right, we need to update $mi$ and $mx$. If $nums[j] \lt nums[mi]$, then $mi$ is updated to $j$; if $nums[j] \gt nums[mx]$, then $mx$ is updated to $j$. After updating $mi$ and $mx$, we can determine whether we have found a pair of indices that satisfy the condition. If $nums[i] - nums[mi] \ge valueDifference$, then we have found a pair of indices $[mi, i]$ that satisfy the condition; if $nums[mx] - nums[i] >= valueDifference$, then we have found a pair of indices $[mx, i]$ that satisfy the condition. - -If pointer $i$ moves to the end of the array and we have not found a pair of indices that satisfy the condition, we return $[-1, -1]$. - -The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$. +### 方法一 -### **Python3** - - - ```python class Solution: def findIndices( @@ -106,10 +88,6 @@ class Solution: return [-1, -1] ``` -### **Java** - - - ```java class Solution { public int[] findIndices(int[] nums, int indexDifference, int valueDifference) { @@ -135,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -162,8 +138,6 @@ public: }; ``` -### **Go** - ```go func findIndices(nums []int, indexDifference int, valueDifference int) []int { mi, mx := 0, 0 @@ -186,8 +160,6 @@ func findIndices(nums []int, indexDifference int, valueDifference int) []int { } ``` -### **TypeScript** - ```ts function findIndices(nums: number[], indexDifference: number, valueDifference: number): number[] { let [mi, mx] = [0, 0]; @@ -210,10 +182,38 @@ function findIndices(nums: number[], indexDifference: number, valueDifference: n } ``` -### **...** +```rust +impl Solution { + pub fn find_indices(nums: Vec, index_difference: i32, value_difference: i32) -> Vec { + let index_difference = index_difference as usize; + let mut mi = 0; + let mut mx = 0; -``` + for i in index_difference..nums.len() { + let j = i - index_difference; + if nums[j] < nums[mi] { + mi = j; + } + + if nums[j] > nums[mx] { + mx = j; + } + + if nums[i] - nums[mi] >= value_difference { + return vec![mi as i32, i as i32]; + } + + if nums[mx] - nums[i] >= value_difference { + return vec![mx as i32, i as i32]; + } + } + + vec![-1, -1] + } +} ``` + + diff --git a/solution/2900-2999/2905.Find Indices With Index and Value Difference II/README_EN.md b/solution/2900-2999/2905.Find Indices With Index and Value Difference II/README_EN.md index 378243a5d91e0..dfec180035c73 100644 --- a/solution/2900-2999/2905.Find Indices With Index and Value Difference II/README_EN.md +++ b/solution/2900-2999/2905.Find Indices With Index and Value Difference II/README_EN.md @@ -60,9 +60,9 @@ Hence, [-1,-1] is returned. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -83,8 +83,6 @@ class Solution: return [-1, -1] ``` -### **Java** - ```java class Solution { public int[] findIndices(int[] nums, int indexDifference, int valueDifference) { @@ -110,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +133,6 @@ public: }; ``` -### **Go** - ```go func findIndices(nums []int, indexDifference int, valueDifference int) []int { mi, mx := 0, 0 @@ -161,8 +155,6 @@ func findIndices(nums []int, indexDifference int, valueDifference int) []int { } ``` -### **TypeScript** - ```ts function findIndices(nums: number[], indexDifference: number, valueDifference: number): number[] { let [mi, mx] = [0, 0]; @@ -185,10 +177,38 @@ function findIndices(nums: number[], indexDifference: number, valueDifference: n } ``` -### **...** +```rust +impl Solution { + pub fn find_indices(nums: Vec, index_difference: i32, value_difference: i32) -> Vec { + let index_difference = index_difference as usize; + let mut mi = 0; + let mut mx = 0; -``` + for i in index_difference..nums.len() { + let j = i - index_difference; + if nums[j] < nums[mi] { + mi = j; + } + + if nums[j] > nums[mx] { + mx = j; + } + + if nums[i] - nums[mi] >= value_difference { + return vec![mi as i32, i as i32]; + } + + if nums[mx] - nums[i] >= value_difference { + return vec![mx as i32, i as i32]; + } + } + + vec![-1, -1] + } +} ``` + + diff --git a/solution/2900-2999/2906.Construct Product Matrix/README.md b/solution/2900-2999/2906.Construct Product Matrix/README.md index d9eaea6989a7f..5cad44d12bbaf 100644 --- a/solution/2900-2999/2906.Construct Product Matrix/README.md +++ b/solution/2900-2999/2906.Construct Product Matrix/README.md @@ -50,9 +50,7 @@ p[0][2] = grid[0][0] * grid[0][1] = 12345 * 2 = 24690. 24690 % 12345 = 0 ,所 ## 解法 - - -**方法一:前后缀分解** +### 方法一:前后缀分解 我们可以预处理出每个元素的后缀乘积(不包含自身),然后再遍历矩阵,计算得到每个元素的前缀乘积(不包含自身),将两者相乘即可得到每个位置的结果。 @@ -66,10 +64,6 @@ p[0][2] = grid[0][0] * grid[0][1] = 12345 * 2 = 24690. 24690 % 12345 = 0 ,所 -### **Python3** - - - ```python class Solution: def constructProductMatrix(self, grid: List[List[int]]) -> List[List[int]]: @@ -89,10 +83,6 @@ class Solution: return p ``` -### **Java** - - - ```java class Solution { public int[][] constructProductMatrix(int[][] grid) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func constructProductMatrix(grid [][]int) [][]int { const mod int = 12345 @@ -174,8 +160,6 @@ func constructProductMatrix(grid [][]int) [][]int { } ``` -### **TypeScript** - ```ts function constructProductMatrix(grid: number[][]): number[][] { const mod = 12345; @@ -199,8 +183,6 @@ function constructProductMatrix(grid: number[][]): number[][] { } ``` -### **Rust** - ```rust impl Solution { pub fn construct_product_matrix(grid: Vec>) -> Vec> { @@ -231,10 +213,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2906.Construct Product Matrix/README_EN.md b/solution/2900-2999/2906.Construct Product Matrix/README_EN.md index 2f9ce8e0924fd..c58b2d2b8a4a3 100644 --- a/solution/2900-2999/2906.Construct Product Matrix/README_EN.md +++ b/solution/2900-2999/2906.Construct Product Matrix/README_EN.md @@ -46,7 +46,7 @@ So the answer is [[2],[0],[0]]. ## Solutions -**Solution 1: Prefix and Suffix Decomposition** +### Solution 1: Prefix and Suffix Decomposition We can preprocess the suffix product (excluding itself) of each element, and then traverse the matrix to calculate the prefix product (excluding itself) of each element. The product of the two gives us the result for each position. @@ -60,8 +60,6 @@ The time complexity is $O(n \times m)$, where $n$ and $m$ are the number of rows -### **Python3** - ```python class Solution: def constructProductMatrix(self, grid: List[List[int]]) -> List[List[int]]: @@ -81,8 +79,6 @@ class Solution: return p ``` -### **Java** - ```java class Solution { public int[][] constructProductMatrix(int[][] grid) { @@ -108,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +130,6 @@ public: }; ``` -### **Go** - ```go func constructProductMatrix(grid [][]int) [][]int { const mod int = 12345 @@ -164,8 +156,6 @@ func constructProductMatrix(grid [][]int) [][]int { } ``` -### **TypeScript** - ```ts function constructProductMatrix(grid: number[][]): number[][] { const mod = 12345; @@ -189,8 +179,6 @@ function constructProductMatrix(grid: number[][]): number[][] { } ``` -### **Rust** - ```rust impl Solution { pub fn construct_product_matrix(grid: Vec>) -> Vec> { @@ -221,10 +209,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/README.md b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/README.md index cc68ca5d05601..7f947ed2d7a42 100644 --- a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/README.md +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/README.md @@ -58,28 +58,14 @@ ## 解法 - - -**方法一:枚举中间元素** +### 方法一:枚举中间元素 我们可以枚举中间元素 $profits[j]$,然后再枚举左边元素 $profits[i]$ 和右边元素 $profits[k]$。对于每个 $profits[j]$,我们需要找到最大的 $profits[i]$ 和最大的 $profits[k]$,使得 $prices[i] < prices[j] < prices[k]$。我们记 $left$ 为 $profits[j]$ 左边的最大值,而 $right$ 为 $profits[j]$ 右边的最大值。如果存在,那么我们更新答案为 $ans = \max(ans, left + profits[j] + right)$。 时间复杂度 $O(n^2)$,其中 $n$ 为数组长度。空间复杂度 $O(1)$。 -**方法二:树状数组** - -我们可以用两个树状数组分别维护每个价格左边以及右边的最大利润,然后枚举中间的价格,通过树状数组查询左右两边的最大利润,最后取最大值即可。 - -时间复杂度 $O(n \times \log M)$,空间复杂度 $O(M)$。其中 $n$ 是数组 $prices$ 的长度,而 $M$ 是数组 $prices$ 中的最大值,本题中 $M \le 10^6$。 - -由于 $prices$ 的长度不超过 $2000$,而 $prices[i]$ 的取值达到 $10^6$,因此,我们可以对 $prices$ 进行离散化处理,这样可以将空间复杂度降低到 $O(n)$。 - -### **Python3** - - - ```python class Solution: def maxProfit(self, prices: List[int], profits: List[int]) -> int: @@ -98,48 +84,151 @@ class Solution: return ans ``` -```python -class BinaryIndexedTree: - def __init__(self, n: int): - self.n = n - self.c = [0] * (n + 1) +```java +class Solution { + public int maxProfit(int[] prices, int[] profits) { + int n = prices.length; + int ans = -1; + for (int j = 0; j < n; ++j) { + int left = 0, right = 0; + for (int i = 0; i < j; ++i) { + if (prices[i] < prices[j]) { + left = Math.max(left, profits[i]); + } + } + for (int k = j + 1; k < n; ++k) { + if (prices[j] < prices[k]) { + right = Math.max(right, profits[k]); + } + } + if (left > 0 && right > 0) { + ans = Math.max(ans, left + profits[j] + right); + } + } + return ans; + } +} +``` - def update(self, x: int, v: int): - while x <= self.n: - self.c[x] = max(self.c[x], v) - x += x & -x +```cpp +class Solution { +public: + int maxProfit(vector& prices, vector& profits) { + int n = prices.size(); + int ans = -1; + for (int j = 0; j < n; ++j) { + int left = 0, right = 0; + for (int i = 0; i < j; ++i) { + if (prices[i] < prices[j]) { + left = max(left, profits[i]); + } + } + for (int k = j + 1; k < n; ++k) { + if (prices[j] < prices[k]) { + right = max(right, profits[k]); + } + } + if (left && right) { + ans = max(ans, left + profits[j] + right); + } + } + return ans; + } +}; +``` - def query(self, x: int) -> int: - mx = 0 - while x: - mx = max(mx, self.c[x]) - x -= x & -x - return mx +```go +func maxProfit(prices []int, profits []int) int { + n := len(prices) + ans := -1 + for j, x := range profits { + left, right := 0, 0 + for i := 0; i < j; i++ { + if prices[i] < prices[j] { + left = max(left, profits[i]) + } + } + for k := j + 1; k < n; k++ { + if prices[j] < prices[k] { + right = max(right, profits[k]) + } + } + if left > 0 && right > 0 { + ans = max(ans, left+x+right) + } + } + return ans +} +``` +```ts +function maxProfit(prices: number[], profits: number[]): number { + const n = prices.length; + let ans = -1; + for (let j = 0; j < n; ++j) { + let [left, right] = [0, 0]; + for (let i = 0; i < j; ++i) { + if (prices[i] < prices[j]) { + left = Math.max(left, profits[i]); + } + } + for (let k = j + 1; k < n; ++k) { + if (prices[j] < prices[k]) { + right = Math.max(right, profits[k]); + } + } + if (left > 0 && right > 0) { + ans = Math.max(ans, left + profits[j] + right); + } + } + return ans; +} +``` -class Solution: - def maxProfit(self, prices: List[int], profits: List[int]) -> int: - n = len(prices) - left = [0] * n - right = [0] * n +```rust +impl Solution { + pub fn max_profit(prices: Vec, profits: Vec) -> i32 { + let n = prices.len(); + let mut ans = -1; - m = max(prices) - tree1 = BinaryIndexedTree(m + 1) - tree2 = BinaryIndexedTree(m + 1) + for j in 0..n { + let mut left = 0; + let mut right = 0; - for i, x in enumerate(prices): - left[i] = tree1.query(x - 1) - tree1.update(x, profits[i]) - for i in range(n - 1, -1, -1): - x = m + 1 - prices[i] - right[i] = tree2.query(x - 1) - tree2.update(x, profits[i]) + for i in 0..j { + if prices[i] < prices[j] { + left = left.max(profits[i]); + } + } - return max( - (l + x + r for l, x, r in zip(left, profits, right) if l and r), default=-1 - ) + for k in j + 1..n { + if prices[j] < prices[k] { + right = right.max(profits[k]); + } + } + + if left > 0 && right > 0 { + ans = ans.max(left + profits[j] + right); + } + } + + ans + } +} ``` + + +### 方法二:树状数组 + +我们可以用两个树状数组分别维护每个价格左边以及右边的最大利润,然后枚举中间的价格,通过树状数组查询左右两边的最大利润,最后取最大值即可。 + +时间复杂度 $O(n \times \log M)$,空间复杂度 $O(M)$。其中 $n$ 是数组 $prices$ 的长度,而 $M$ 是数组 $prices$ 中的最大值,本题中 $M \le 10^6$。 + +由于 $prices$ 的长度不超过 $2000$,而 $prices[i]$ 的取值达到 $10^6$,因此,我们可以对 $prices$ 进行离散化处理,这样可以将空间复杂度降低到 $O(n)$。 + + + ```python class BinaryIndexedTree: def __init__(self, n: int): @@ -165,17 +254,15 @@ class Solution: left = [0] * n right = [0] * n - s = sorted(set(prices)) - m = len(s) + m = max(prices) tree1 = BinaryIndexedTree(m + 1) tree2 = BinaryIndexedTree(m + 1) for i, x in enumerate(prices): - x = bisect_left(s, x) + 1 left[i] = tree1.query(x - 1) tree1.update(x, profits[i]) for i in range(n - 1, -1, -1): - x = m + 1 - (bisect_left(s, prices[i]) + 1) + x = m + 1 - prices[i] right[i] = tree2.query(x - 1) tree2.update(x, profits[i]) @@ -184,36 +271,6 @@ class Solution: ) ``` -### **Java** - - - -```java -class Solution { - public int maxProfit(int[] prices, int[] profits) { - int n = prices.length; - int ans = -1; - for (int j = 0; j < n; ++j) { - int left = 0, right = 0; - for (int i = 0; i < j; ++i) { - if (prices[i] < prices[j]) { - left = Math.max(left, profits[i]); - } - } - for (int k = j + 1; k < n; ++k) { - if (prices[j] < prices[k]) { - right = Math.max(right, profits[k]); - } - } - if (left > 0 && right > 0) { - ans = Math.max(ans, left + profits[j] + right); - } - } - return ans; - } -} -``` - ```java class BinaryIndexedTree { private int n; @@ -273,315 +330,437 @@ class Solution { } ``` -```java +```cpp class BinaryIndexedTree { - private int n; - private int[] c; +private: + int n; + vector c; - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; +public: + BinaryIndexedTree(int n) { + this->n = n; + c.resize(n + 1, 0); } - public void update(int x, int v) { + void update(int x, int v) { while (x <= n) { - c[x] = Math.max(c[x], v); + c[x] = max(c[x], v); x += x & -x; } } - public int query(int x) { + int query(int x) { int mx = 0; while (x > 0) { - mx = Math.max(mx, c[x]); + mx = max(mx, c[x]); x -= x & -x; } return mx; } -} +}; class Solution { - public int maxProfit(int[] prices, int[] profits) { - int n = prices.length; - int[] left = new int[n]; - int[] right = new int[n]; - int[] s = prices.clone(); - Arrays.sort(s); - int m = 0; +public: + int maxProfit(vector& prices, vector& profits) { + int n = prices.size(); + vector left(n, 0); + vector right(n, 0); + int m = *max_element(prices.begin(), prices.end()); + BinaryIndexedTree tree1(m + 1); + BinaryIndexedTree tree2(m + 1); for (int i = 0; i < n; ++i) { - if (i == 0 || s[i] != s[i - 1]) { - s[m++] = s[i]; - } - } - BinaryIndexedTree tree1 = new BinaryIndexedTree(m + 1); - BinaryIndexedTree tree2 = new BinaryIndexedTree(m + 1); - for (int i = 0; i < n; ++i) { - int x = search(s, prices[i], m); + int x = prices[i]; left[i] = tree1.query(x - 1); tree1.update(x, profits[i]); } for (int i = n - 1; i >= 0; --i) { - int x = m + 1 - search(s, prices[i], m); + int x = m + 1 - prices[i]; right[i] = tree2.query(x - 1); tree2.update(x, profits[i]); } int ans = -1; for (int i = 0; i < n; ++i) { if (left[i] > 0 && right[i] > 0) { - ans = Math.max(ans, left[i] + profits[i] + right[i]); + ans = max(ans, left[i] + profits[i] + right[i]); } } return ans; } +}; +``` - private int search(int[] nums, int x, int r) { - int l = 0; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l + 1; - } +```go +type BinaryIndexedTree struct { + n int + c []int } -``` -### **C++** +func NewBinaryIndexedTree(n int) BinaryIndexedTree { + c := make([]int, n+1) + return BinaryIndexedTree{n: n, c: c} +} -```cpp -class Solution { -public: - int maxProfit(vector& prices, vector& profits) { - int n = prices.size(); - int ans = -1; - for (int j = 0; j < n; ++j) { - int left = 0, right = 0; - for (int i = 0; i < j; ++i) { - if (prices[i] < prices[j]) { - left = max(left, profits[i]); - } - } - for (int k = j + 1; k < n; ++k) { - if (prices[j] < prices[k]) { - right = max(right, profits[k]); - } - } - if (left && right) { - ans = max(ans, left + profits[j] + right); - } - } - return ans; - } -}; +func (bit *BinaryIndexedTree) update(x, v int) { + for x <= bit.n { + bit.c[x] = max(bit.c[x], v) + x += x & -x + } +} + +func (bit *BinaryIndexedTree) query(x int) int { + mx := 0 + for x > 0 { + mx = max(mx, bit.c[x]) + x -= x & -x + } + return mx +} + +func maxProfit(prices []int, profits []int) int { + n := len(prices) + left := make([]int, n) + right := make([]int, n) + m := slices.Max(prices) + + tree1 := NewBinaryIndexedTree(m + 1) + tree2 := NewBinaryIndexedTree(m + 1) + + for i, x := range prices { + left[i] = tree1.query(x - 1) + tree1.update(x, profits[i]) + } + + for i := n - 1; i >= 0; i-- { + x := m + 1 - prices[i] + right[i] = tree2.query(x - 1) + tree2.update(x, profits[i]) + } + + ans := -1 + + for i := 0; i < n; i++ { + if left[i] > 0 && right[i] > 0 { + ans = max(ans, left[i]+profits[i]+right[i]) + } + } + + return ans +} ``` -```cpp +```ts class BinaryIndexedTree { -private: - int n; - vector c; + private n: number; + private c: number[]; -public: - BinaryIndexedTree(int n) { - this->n = n; - c.resize(n + 1, 0); + constructor(n: number) { + this.n = n; + this.c = Array(n + 1).fill(0); } - void update(int x, int v) { - while (x <= n) { - c[x] = max(c[x], v); + update(x: number, v: number): void { + while (x <= this.n) { + this.c[x] = Math.max(this.c[x], v); x += x & -x; } } - int query(int x) { - int mx = 0; + query(x: number): number { + let mx = 0; while (x > 0) { - mx = max(mx, c[x]); + mx = Math.max(mx, this.c[x]); x -= x & -x; } return mx; } -}; +} -class Solution { -public: - int maxProfit(vector& prices, vector& profits) { - int n = prices.size(); - vector left(n, 0); - vector right(n, 0); - int m = *max_element(prices.begin(), prices.end()); - BinaryIndexedTree tree1(m + 1); - BinaryIndexedTree tree2(m + 1); - for (int i = 0; i < n; ++i) { - int x = prices[i]; +function maxProfit(prices: number[], profits: number[]): number { + const n: number = prices.length; + const left: number[] = Array(n).fill(0); + const right: number[] = Array(n).fill(0); + const m = Math.max(...prices); + + const tree1: BinaryIndexedTree = new BinaryIndexedTree(m + 1); + const tree2: BinaryIndexedTree = new BinaryIndexedTree(m + 1); + + for (let i = 0; i < n; i++) { + const x: number = prices[i]; + left[i] = tree1.query(x - 1); + tree1.update(x, profits[i]); + } + + for (let i = n - 1; i >= 0; i--) { + const x: number = m + 1 - prices[i]; + right[i] = tree2.query(x - 1); + tree2.update(x, profits[i]); + } + + let ans: number = -1; + + for (let i = 0; i < n; i++) { + if (left[i] > 0 && right[i] > 0) { + ans = Math.max(ans, left[i] + profits[i] + right[i]); + } + } + + return ans; +} +``` + +```rust +struct BinaryIndexedTree { + n: usize, + c: Vec, +} + +impl BinaryIndexedTree { + fn new(n: usize) -> BinaryIndexedTree { + BinaryIndexedTree { + n, + c: vec![0; n + 1], + } + } + + fn update(&mut self, x: usize, v: i32) { + let mut x = x; + while x <= self.n { + self.c[x] = self.c[x].max(v); + x += x & x.wrapping_neg(); + } + } + + fn query(&self, x: usize) -> i32 { + let mut x = x; + let mut mx = 0; + while x > 0 { + mx = mx.max(self.c[x]); + x -= x & x.wrapping_neg(); + } + mx + } +} + +impl Solution { + pub fn max_profit(prices: Vec, profits: Vec) -> i32 { + let n = prices.len(); + let mut left = vec![0; n]; + let mut right = vec![0; n]; + let m = prices.iter().cloned().max().unwrap_or(0); + + let mut tree1 = BinaryIndexedTree::new((m as usize) + 1); + let mut tree2 = BinaryIndexedTree::new((m as usize) + 1); + + for i in 0..n { + let x = prices[i] as usize; left[i] = tree1.query(x - 1); tree1.update(x, profits[i]); } - for (int i = n - 1; i >= 0; --i) { - int x = m + 1 - prices[i]; + + for i in (0..n).rev() { + let x = (m + 1 - prices[i]) as usize; right[i] = tree2.query(x - 1); tree2.update(x, profits[i]); } - int ans = -1; - for (int i = 0; i < n; ++i) { - if (left[i] > 0 && right[i] > 0) { - ans = max(ans, left[i] + profits[i] + right[i]); + + let mut ans = -1; + for i in 0..n { + if left[i] > 0 && right[i] > 0 { + ans = ans.max(left[i] + profits[i] + right[i]); } } - return ans; + + ans } -}; +} ``` -```cpp + + +### 方法三 + + + +```python +class BinaryIndexedTree: + def __init__(self, n: int): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x: int, v: int): + while x <= self.n: + self.c[x] = max(self.c[x], v) + x += x & -x + + def query(self, x: int) -> int: + mx = 0 + while x: + mx = max(mx, self.c[x]) + x -= x & -x + return mx + + +class Solution: + def maxProfit(self, prices: List[int], profits: List[int]) -> int: + n = len(prices) + left = [0] * n + right = [0] * n + + s = sorted(set(prices)) + m = len(s) + tree1 = BinaryIndexedTree(m + 1) + tree2 = BinaryIndexedTree(m + 1) + + for i, x in enumerate(prices): + x = bisect_left(s, x) + 1 + left[i] = tree1.query(x - 1) + tree1.update(x, profits[i]) + for i in range(n - 1, -1, -1): + x = m + 1 - (bisect_left(s, prices[i]) + 1) + right[i] = tree2.query(x - 1) + tree2.update(x, profits[i]) + + return max( + (l + x + r for l, x, r in zip(left, profits, right) if l and r), default=-1 + ) +``` + +```java class BinaryIndexedTree { -private: - int n; - vector c; + private int n; + private int[] c; -public: - BinaryIndexedTree(int n) { - this->n = n; - c.resize(n + 1, 0); + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; } - void update(int x, int v) { + public void update(int x, int v) { while (x <= n) { - c[x] = max(c[x], v); + c[x] = Math.max(c[x], v); x += x & -x; } } - int query(int x) { + public int query(int x) { int mx = 0; while (x > 0) { - mx = max(mx, c[x]); + mx = Math.max(mx, c[x]); x -= x & -x; } return mx; } -}; +} class Solution { -public: - int maxProfit(vector& prices, vector& profits) { - int n = prices.size(); - vector left(n); - vector right(n); - vector s = prices; - sort(s.begin(), s.end()); - s.erase(unique(s.begin(), s.end()), s.end()); - int m = s.size(); - BinaryIndexedTree tree1(m + 1); - BinaryIndexedTree tree2(m + 1); + public int maxProfit(int[] prices, int[] profits) { + int n = prices.length; + int[] left = new int[n]; + int[] right = new int[n]; + int[] s = prices.clone(); + Arrays.sort(s); + int m = 0; for (int i = 0; i < n; ++i) { - int x = lower_bound(s.begin(), s.end(), prices[i]) - s.begin() + 1; + if (i == 0 || s[i] != s[i - 1]) { + s[m++] = s[i]; + } + } + BinaryIndexedTree tree1 = new BinaryIndexedTree(m + 1); + BinaryIndexedTree tree2 = new BinaryIndexedTree(m + 1); + for (int i = 0; i < n; ++i) { + int x = search(s, prices[i], m); left[i] = tree1.query(x - 1); tree1.update(x, profits[i]); } for (int i = n - 1; i >= 0; --i) { - int x = m + 1 - (lower_bound(s.begin(), s.end(), prices[i]) - s.begin() + 1); + int x = m + 1 - search(s, prices[i], m); right[i] = tree2.query(x - 1); tree2.update(x, profits[i]); } int ans = -1; for (int i = 0; i < n; ++i) { if (left[i] > 0 && right[i] > 0) { - ans = max(ans, left[i] + profits[i] + right[i]); + ans = Math.max(ans, left[i] + profits[i] + right[i]); } } return ans; } -}; -``` -### **Go** - -```go -func maxProfit(prices []int, profits []int) int { - n := len(prices) - ans := -1 - for j, x := range profits { - left, right := 0, 0 - for i := 0; i < j; i++ { - if prices[i] < prices[j] { - left = max(left, profits[i]) - } - } - for k := j + 1; k < n; k++ { - if prices[j] < prices[k] { - right = max(right, profits[k]) - } - } - if left > 0 && right > 0 { - ans = max(ans, left+x+right) - } - } - return ans + private int search(int[] nums, int x, int r) { + int l = 0; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l + 1; + } } ``` -```go -type BinaryIndexedTree struct { - n int - c []int -} - -func NewBinaryIndexedTree(n int) BinaryIndexedTree { - c := make([]int, n+1) - return BinaryIndexedTree{n: n, c: c} -} - -func (bit *BinaryIndexedTree) update(x, v int) { - for x <= bit.n { - bit.c[x] = max(bit.c[x], v) - x += x & -x - } -} - -func (bit *BinaryIndexedTree) query(x int) int { - mx := 0 - for x > 0 { - mx = max(mx, bit.c[x]) - x -= x & -x - } - return mx -} - -func maxProfit(prices []int, profits []int) int { - n := len(prices) - left := make([]int, n) - right := make([]int, n) - m := slices.Max(prices) - - tree1 := NewBinaryIndexedTree(m + 1) - tree2 := NewBinaryIndexedTree(m + 1) - - for i, x := range prices { - left[i] = tree1.query(x - 1) - tree1.update(x, profits[i]) - } +```cpp +class BinaryIndexedTree { +private: + int n; + vector c; - for i := n - 1; i >= 0; i-- { - x := m + 1 - prices[i] - right[i] = tree2.query(x - 1) - tree2.update(x, profits[i]) - } +public: + BinaryIndexedTree(int n) { + this->n = n; + c.resize(n + 1, 0); + } - ans := -1 + void update(int x, int v) { + while (x <= n) { + c[x] = max(c[x], v); + x += x & -x; + } + } - for i := 0; i < n; i++ { - if left[i] > 0 && right[i] > 0 { - ans = max(ans, left[i]+profits[i]+right[i]) - } - } + int query(int x) { + int mx = 0; + while (x > 0) { + mx = max(mx, c[x]); + x -= x & -x; + } + return mx; + } +}; - return ans -} +class Solution { +public: + int maxProfit(vector& prices, vector& profits) { + int n = prices.size(); + vector left(n); + vector right(n); + vector s = prices; + sort(s.begin(), s.end()); + s.erase(unique(s.begin(), s.end()), s.end()); + int m = s.size(); + BinaryIndexedTree tree1(m + 1); + BinaryIndexedTree tree2(m + 1); + for (int i = 0; i < n; ++i) { + int x = lower_bound(s.begin(), s.end(), prices[i]) - s.begin() + 1; + left[i] = tree1.query(x - 1); + tree1.update(x, profits[i]); + } + for (int i = n - 1; i >= 0; --i) { + int x = m + 1 - (lower_bound(s.begin(), s.end(), prices[i]) - s.begin() + 1); + right[i] = tree2.query(x - 1); + tree2.update(x, profits[i]); + } + int ans = -1; + for (int i = 0; i < n; ++i) { + if (left[i] > 0 && right[i] > 0) { + ans = max(ans, left[i] + profits[i] + right[i]); + } + } + return ans; + } +}; ``` ```go @@ -653,92 +832,6 @@ func maxProfit(prices []int, profits []int) int { } ``` -### **TypeScript** - -```ts -function maxProfit(prices: number[], profits: number[]): number { - const n = prices.length; - let ans = -1; - for (let j = 0; j < n; ++j) { - let [left, right] = [0, 0]; - for (let i = 0; i < j; ++i) { - if (prices[i] < prices[j]) { - left = Math.max(left, profits[i]); - } - } - for (let k = j + 1; k < n; ++k) { - if (prices[j] < prices[k]) { - right = Math.max(right, profits[k]); - } - } - if (left > 0 && right > 0) { - ans = Math.max(ans, left + profits[j] + right); - } - } - return ans; -} -``` - -```ts -class BinaryIndexedTree { - private n: number; - private c: number[]; - - constructor(n: number) { - this.n = n; - this.c = Array(n + 1).fill(0); - } - - update(x: number, v: number): void { - while (x <= this.n) { - this.c[x] = Math.max(this.c[x], v); - x += x & -x; - } - } - - query(x: number): number { - let mx = 0; - while (x > 0) { - mx = Math.max(mx, this.c[x]); - x -= x & -x; - } - return mx; - } -} - -function maxProfit(prices: number[], profits: number[]): number { - const n: number = prices.length; - const left: number[] = Array(n).fill(0); - const right: number[] = Array(n).fill(0); - const m = Math.max(...prices); - - const tree1: BinaryIndexedTree = new BinaryIndexedTree(m + 1); - const tree2: BinaryIndexedTree = new BinaryIndexedTree(m + 1); - - for (let i = 0; i < n; i++) { - const x: number = prices[i]; - left[i] = tree1.query(x - 1); - tree1.update(x, profits[i]); - } - - for (let i = n - 1; i >= 0; i--) { - const x: number = m + 1 - prices[i]; - right[i] = tree2.query(x - 1); - tree2.update(x, profits[i]); - } - - let ans: number = -1; - - for (let i = 0; i < n; i++) { - if (left[i] > 0 && right[i] > 0) { - ans = Math.max(ans, left[i] + profits[i] + right[i]); - } - } - - return ans; -} -``` - ```ts class BinaryIndexedTree { private n: number; @@ -820,111 +913,6 @@ function maxProfit(prices: number[], profits: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn max_profit(prices: Vec, profits: Vec) -> i32 { - let n = prices.len(); - let mut ans = -1; - - for j in 0..n { - let mut left = 0; - let mut right = 0; - - for i in 0..j { - if prices[i] < prices[j] { - left = left.max(profits[i]); - } - } - - for k in j + 1..n { - if prices[j] < prices[k] { - right = right.max(profits[k]); - } - } - - if left > 0 && right > 0 { - ans = ans.max(left + profits[j] + right); - } - } - - ans - } -} -``` - -```rust -struct BinaryIndexedTree { - n: usize, - c: Vec, -} - -impl BinaryIndexedTree { - fn new(n: usize) -> BinaryIndexedTree { - BinaryIndexedTree { - n, - c: vec![0; n + 1], - } - } - - fn update(&mut self, x: usize, v: i32) { - let mut x = x; - while x <= self.n { - self.c[x] = self.c[x].max(v); - x += x & x.wrapping_neg(); - } - } - - fn query(&self, x: usize) -> i32 { - let mut x = x; - let mut mx = 0; - while x > 0 { - mx = mx.max(self.c[x]); - x -= x & x.wrapping_neg(); - } - mx - } -} - -impl Solution { - pub fn max_profit(prices: Vec, profits: Vec) -> i32 { - let n = prices.len(); - let mut left = vec![0; n]; - let mut right = vec![0; n]; - let m = prices.iter().cloned().max().unwrap_or(0); - - let mut tree1 = BinaryIndexedTree::new((m as usize) + 1); - let mut tree2 = BinaryIndexedTree::new((m as usize) + 1); - - for i in 0..n { - let x = prices[i] as usize; - left[i] = tree1.query(x - 1); - tree1.update(x, profits[i]); - } - - for i in (0..n).rev() { - let x = (m + 1 - prices[i]) as usize; - right[i] = tree2.query(x - 1); - tree2.update(x, profits[i]); - } - - let mut ans = -1; - for i in 0..n { - if left[i] > 0 && right[i] > 0 { - ans = ans.max(left[i] + profits[i] + right[i]); - } - } - - ans - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/README_EN.md b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/README_EN.md index c10d40fbd00bb..b2c05b2e5bec0 100644 --- a/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/README_EN.md +++ b/solution/2900-2999/2907.Maximum Profitable Triplets With Increasing Prices I/README_EN.md @@ -54,24 +54,14 @@ The answer would be sum of their profits which is 5 + 4 + 6 = 15. ## Solutions -**Solution 1: Enumerate the Middle Element** +### Solution 1: Enumerate the Middle Element We can enumerate the middle element $profits[j]$, and then enumerate the left element $profits[i]$ and the right element $profits[k]$. For each $profits[j]$, we need to find the maximum $profits[i]$ and the maximum $profits[k]$ such that $prices[i] < prices[j] < prices[k]$. We define $left$ as the maximum value on the left of $profits[j]$, and $right$ as the maximum value on the right of $profits[j]$. If they exist, we update the answer as $ans = \max(ans, left + profits[j] + right)$. The time complexity is $O(n^2)$, where $n$ is the length of the array. The space complexity is $O(1)$. -**Solution 2: Binary Indexed Tree** - -We can use two Binary Indexed Trees (BITs) to maintain the maximum profit on the left and right of each price, respectively. Then, we enumerate the middle price, query the maximum profit on both sides through the BIT, and finally take the maximum value. - -The time complexity is $O(n \times \log M)$, and the space complexity is $O(M)$. Here, $n$ is the length of the array $prices$, and $M$ is the maximum value in the array $prices$. In this problem, $M \le 10^6$. - -Since the length of $prices$ does not exceed $2000$, and the value of $prices[i]$ reaches $10^6$, we can discretize $prices$, which can reduce the space complexity to $O(n)$. - -### **Python3** - ```python class Solution: def maxProfit(self, prices: List[int], profits: List[int]) -> int: @@ -90,48 +80,151 @@ class Solution: return ans ``` -```python -class BinaryIndexedTree: - def __init__(self, n: int): - self.n = n - self.c = [0] * (n + 1) +```java +class Solution { + public int maxProfit(int[] prices, int[] profits) { + int n = prices.length; + int ans = -1; + for (int j = 0; j < n; ++j) { + int left = 0, right = 0; + for (int i = 0; i < j; ++i) { + if (prices[i] < prices[j]) { + left = Math.max(left, profits[i]); + } + } + for (int k = j + 1; k < n; ++k) { + if (prices[j] < prices[k]) { + right = Math.max(right, profits[k]); + } + } + if (left > 0 && right > 0) { + ans = Math.max(ans, left + profits[j] + right); + } + } + return ans; + } +} +``` - def update(self, x: int, v: int): - while x <= self.n: - self.c[x] = max(self.c[x], v) - x += x & -x +```cpp +class Solution { +public: + int maxProfit(vector& prices, vector& profits) { + int n = prices.size(); + int ans = -1; + for (int j = 0; j < n; ++j) { + int left = 0, right = 0; + for (int i = 0; i < j; ++i) { + if (prices[i] < prices[j]) { + left = max(left, profits[i]); + } + } + for (int k = j + 1; k < n; ++k) { + if (prices[j] < prices[k]) { + right = max(right, profits[k]); + } + } + if (left && right) { + ans = max(ans, left + profits[j] + right); + } + } + return ans; + } +}; +``` - def query(self, x: int) -> int: - mx = 0 - while x: - mx = max(mx, self.c[x]) - x -= x & -x - return mx +```go +func maxProfit(prices []int, profits []int) int { + n := len(prices) + ans := -1 + for j, x := range profits { + left, right := 0, 0 + for i := 0; i < j; i++ { + if prices[i] < prices[j] { + left = max(left, profits[i]) + } + } + for k := j + 1; k < n; k++ { + if prices[j] < prices[k] { + right = max(right, profits[k]) + } + } + if left > 0 && right > 0 { + ans = max(ans, left+x+right) + } + } + return ans +} +``` +```ts +function maxProfit(prices: number[], profits: number[]): number { + const n = prices.length; + let ans = -1; + for (let j = 0; j < n; ++j) { + let [left, right] = [0, 0]; + for (let i = 0; i < j; ++i) { + if (prices[i] < prices[j]) { + left = Math.max(left, profits[i]); + } + } + for (let k = j + 1; k < n; ++k) { + if (prices[j] < prices[k]) { + right = Math.max(right, profits[k]); + } + } + if (left > 0 && right > 0) { + ans = Math.max(ans, left + profits[j] + right); + } + } + return ans; +} +``` -class Solution: - def maxProfit(self, prices: List[int], profits: List[int]) -> int: - n = len(prices) - left = [0] * n - right = [0] * n +```rust +impl Solution { + pub fn max_profit(prices: Vec, profits: Vec) -> i32 { + let n = prices.len(); + let mut ans = -1; - m = max(prices) - tree1 = BinaryIndexedTree(m + 1) - tree2 = BinaryIndexedTree(m + 1) + for j in 0..n { + let mut left = 0; + let mut right = 0; - for i, x in enumerate(prices): - left[i] = tree1.query(x - 1) - tree1.update(x, profits[i]) - for i in range(n - 1, -1, -1): - x = m + 1 - prices[i] - right[i] = tree2.query(x - 1) - tree2.update(x, profits[i]) + for i in 0..j { + if prices[i] < prices[j] { + left = left.max(profits[i]); + } + } - return max( - (l + x + r for l, x, r in zip(left, profits, right) if l and r), default=-1 - ) + for k in j + 1..n { + if prices[j] < prices[k] { + right = right.max(profits[k]); + } + } + + if left > 0 && right > 0 { + ans = ans.max(left + profits[j] + right); + } + } + + ans + } +} ``` + + +### Solution 2: Binary Indexed Tree + +We can use two Binary Indexed Trees (BITs) to maintain the maximum profit on the left and right of each price, respectively. Then, we enumerate the middle price, query the maximum profit on both sides through the BIT, and finally take the maximum value. + +The time complexity is $O(n \times \log M)$, and the space complexity is $O(M)$. Here, $n$ is the length of the array $prices$, and $M$ is the maximum value in the array $prices$. In this problem, $M \le 10^6$. + +Since the length of $prices$ does not exceed $2000$, and the value of $prices[i]$ reaches $10^6$, we can discretize $prices$, which can reduce the space complexity to $O(n)$. + + + ```python class BinaryIndexedTree: def __init__(self, n: int): @@ -157,17 +250,15 @@ class Solution: left = [0] * n right = [0] * n - s = sorted(set(prices)) - m = len(s) + m = max(prices) tree1 = BinaryIndexedTree(m + 1) tree2 = BinaryIndexedTree(m + 1) for i, x in enumerate(prices): - x = bisect_left(s, x) + 1 left[i] = tree1.query(x - 1) tree1.update(x, profits[i]) for i in range(n - 1, -1, -1): - x = m + 1 - (bisect_left(s, prices[i]) + 1) + x = m + 1 - prices[i] right[i] = tree2.query(x - 1) tree2.update(x, profits[i]) @@ -176,34 +267,6 @@ class Solution: ) ``` -### **Java** - -```java -class Solution { - public int maxProfit(int[] prices, int[] profits) { - int n = prices.length; - int ans = -1; - for (int j = 0; j < n; ++j) { - int left = 0, right = 0; - for (int i = 0; i < j; ++i) { - if (prices[i] < prices[j]) { - left = Math.max(left, profits[i]); - } - } - for (int k = j + 1; k < n; ++k) { - if (prices[j] < prices[k]) { - right = Math.max(right, profits[k]); - } - } - if (left > 0 && right > 0) { - ans = Math.max(ans, left + profits[j] + right); - } - } - return ans; - } -} -``` - ```java class BinaryIndexedTree { private int n; @@ -263,315 +326,437 @@ class Solution { } ``` -```java +```cpp class BinaryIndexedTree { - private int n; - private int[] c; +private: + int n; + vector c; - public BinaryIndexedTree(int n) { - this.n = n; - c = new int[n + 1]; +public: + BinaryIndexedTree(int n) { + this->n = n; + c.resize(n + 1, 0); } - public void update(int x, int v) { + void update(int x, int v) { while (x <= n) { - c[x] = Math.max(c[x], v); + c[x] = max(c[x], v); x += x & -x; } } - public int query(int x) { + int query(int x) { int mx = 0; while (x > 0) { - mx = Math.max(mx, c[x]); + mx = max(mx, c[x]); x -= x & -x; } return mx; } -} +}; class Solution { - public int maxProfit(int[] prices, int[] profits) { - int n = prices.length; - int[] left = new int[n]; - int[] right = new int[n]; - int[] s = prices.clone(); - Arrays.sort(s); - int m = 0; +public: + int maxProfit(vector& prices, vector& profits) { + int n = prices.size(); + vector left(n, 0); + vector right(n, 0); + int m = *max_element(prices.begin(), prices.end()); + BinaryIndexedTree tree1(m + 1); + BinaryIndexedTree tree2(m + 1); for (int i = 0; i < n; ++i) { - if (i == 0 || s[i] != s[i - 1]) { - s[m++] = s[i]; - } - } - BinaryIndexedTree tree1 = new BinaryIndexedTree(m + 1); - BinaryIndexedTree tree2 = new BinaryIndexedTree(m + 1); - for (int i = 0; i < n; ++i) { - int x = search(s, prices[i], m); - left[i] = tree1.query(x - 1); - tree1.update(x, profits[i]); + int x = prices[i]; + left[i] = tree1.query(x - 1); + tree1.update(x, profits[i]); } for (int i = n - 1; i >= 0; --i) { - int x = m + 1 - search(s, prices[i], m); + int x = m + 1 - prices[i]; right[i] = tree2.query(x - 1); tree2.update(x, profits[i]); } int ans = -1; for (int i = 0; i < n; ++i) { if (left[i] > 0 && right[i] > 0) { - ans = Math.max(ans, left[i] + profits[i] + right[i]); + ans = max(ans, left[i] + profits[i] + right[i]); } } return ans; } +}; +``` - private int search(int[] nums, int x, int r) { - int l = 0; - while (l < r) { - int mid = (l + r) >> 1; - if (nums[mid] >= x) { - r = mid; - } else { - l = mid + 1; - } - } - return l + 1; - } +```go +type BinaryIndexedTree struct { + n int + c []int } -``` -### **C++** +func NewBinaryIndexedTree(n int) BinaryIndexedTree { + c := make([]int, n+1) + return BinaryIndexedTree{n: n, c: c} +} -```cpp -class Solution { -public: - int maxProfit(vector& prices, vector& profits) { - int n = prices.size(); - int ans = -1; - for (int j = 0; j < n; ++j) { - int left = 0, right = 0; - for (int i = 0; i < j; ++i) { - if (prices[i] < prices[j]) { - left = max(left, profits[i]); - } - } - for (int k = j + 1; k < n; ++k) { - if (prices[j] < prices[k]) { - right = max(right, profits[k]); - } - } - if (left && right) { - ans = max(ans, left + profits[j] + right); - } - } - return ans; - } -}; +func (bit *BinaryIndexedTree) update(x, v int) { + for x <= bit.n { + bit.c[x] = max(bit.c[x], v) + x += x & -x + } +} + +func (bit *BinaryIndexedTree) query(x int) int { + mx := 0 + for x > 0 { + mx = max(mx, bit.c[x]) + x -= x & -x + } + return mx +} + +func maxProfit(prices []int, profits []int) int { + n := len(prices) + left := make([]int, n) + right := make([]int, n) + m := slices.Max(prices) + + tree1 := NewBinaryIndexedTree(m + 1) + tree2 := NewBinaryIndexedTree(m + 1) + + for i, x := range prices { + left[i] = tree1.query(x - 1) + tree1.update(x, profits[i]) + } + + for i := n - 1; i >= 0; i-- { + x := m + 1 - prices[i] + right[i] = tree2.query(x - 1) + tree2.update(x, profits[i]) + } + + ans := -1 + + for i := 0; i < n; i++ { + if left[i] > 0 && right[i] > 0 { + ans = max(ans, left[i]+profits[i]+right[i]) + } + } + + return ans +} ``` -```cpp +```ts class BinaryIndexedTree { -private: - int n; - vector c; + private n: number; + private c: number[]; -public: - BinaryIndexedTree(int n) { - this->n = n; - c.resize(n + 1, 0); + constructor(n: number) { + this.n = n; + this.c = Array(n + 1).fill(0); } - void update(int x, int v) { - while (x <= n) { - c[x] = max(c[x], v); + update(x: number, v: number): void { + while (x <= this.n) { + this.c[x] = Math.max(this.c[x], v); x += x & -x; } } - int query(int x) { - int mx = 0; + query(x: number): number { + let mx = 0; while (x > 0) { - mx = max(mx, c[x]); + mx = Math.max(mx, this.c[x]); x -= x & -x; } return mx; } -}; +} -class Solution { -public: - int maxProfit(vector& prices, vector& profits) { - int n = prices.size(); - vector left(n, 0); - vector right(n, 0); - int m = *max_element(prices.begin(), prices.end()); - BinaryIndexedTree tree1(m + 1); - BinaryIndexedTree tree2(m + 1); - for (int i = 0; i < n; ++i) { - int x = prices[i]; +function maxProfit(prices: number[], profits: number[]): number { + const n: number = prices.length; + const left: number[] = Array(n).fill(0); + const right: number[] = Array(n).fill(0); + const m = Math.max(...prices); + + const tree1: BinaryIndexedTree = new BinaryIndexedTree(m + 1); + const tree2: BinaryIndexedTree = new BinaryIndexedTree(m + 1); + + for (let i = 0; i < n; i++) { + const x: number = prices[i]; + left[i] = tree1.query(x - 1); + tree1.update(x, profits[i]); + } + + for (let i = n - 1; i >= 0; i--) { + const x: number = m + 1 - prices[i]; + right[i] = tree2.query(x - 1); + tree2.update(x, profits[i]); + } + + let ans: number = -1; + + for (let i = 0; i < n; i++) { + if (left[i] > 0 && right[i] > 0) { + ans = Math.max(ans, left[i] + profits[i] + right[i]); + } + } + + return ans; +} +``` + +```rust +struct BinaryIndexedTree { + n: usize, + c: Vec, +} + +impl BinaryIndexedTree { + fn new(n: usize) -> BinaryIndexedTree { + BinaryIndexedTree { + n, + c: vec![0; n + 1], + } + } + + fn update(&mut self, x: usize, v: i32) { + let mut x = x; + while x <= self.n { + self.c[x] = self.c[x].max(v); + x += x & x.wrapping_neg(); + } + } + + fn query(&self, x: usize) -> i32 { + let mut x = x; + let mut mx = 0; + while x > 0 { + mx = mx.max(self.c[x]); + x -= x & x.wrapping_neg(); + } + mx + } +} + +impl Solution { + pub fn max_profit(prices: Vec, profits: Vec) -> i32 { + let n = prices.len(); + let mut left = vec![0; n]; + let mut right = vec![0; n]; + let m = prices.iter().cloned().max().unwrap_or(0); + + let mut tree1 = BinaryIndexedTree::new((m as usize) + 1); + let mut tree2 = BinaryIndexedTree::new((m as usize) + 1); + + for i in 0..n { + let x = prices[i] as usize; left[i] = tree1.query(x - 1); tree1.update(x, profits[i]); } - for (int i = n - 1; i >= 0; --i) { - int x = m + 1 - prices[i]; + + for i in (0..n).rev() { + let x = (m + 1 - prices[i]) as usize; right[i] = tree2.query(x - 1); tree2.update(x, profits[i]); } - int ans = -1; - for (int i = 0; i < n; ++i) { - if (left[i] > 0 && right[i] > 0) { - ans = max(ans, left[i] + profits[i] + right[i]); + + let mut ans = -1; + for i in 0..n { + if left[i] > 0 && right[i] > 0 { + ans = ans.max(left[i] + profits[i] + right[i]); } } - return ans; + + ans } -}; +} ``` -```cpp + + +### Solution 3 + + + +```python +class BinaryIndexedTree: + def __init__(self, n: int): + self.n = n + self.c = [0] * (n + 1) + + def update(self, x: int, v: int): + while x <= self.n: + self.c[x] = max(self.c[x], v) + x += x & -x + + def query(self, x: int) -> int: + mx = 0 + while x: + mx = max(mx, self.c[x]) + x -= x & -x + return mx + + +class Solution: + def maxProfit(self, prices: List[int], profits: List[int]) -> int: + n = len(prices) + left = [0] * n + right = [0] * n + + s = sorted(set(prices)) + m = len(s) + tree1 = BinaryIndexedTree(m + 1) + tree2 = BinaryIndexedTree(m + 1) + + for i, x in enumerate(prices): + x = bisect_left(s, x) + 1 + left[i] = tree1.query(x - 1) + tree1.update(x, profits[i]) + for i in range(n - 1, -1, -1): + x = m + 1 - (bisect_left(s, prices[i]) + 1) + right[i] = tree2.query(x - 1) + tree2.update(x, profits[i]) + + return max( + (l + x + r for l, x, r in zip(left, profits, right) if l and r), default=-1 + ) +``` + +```java class BinaryIndexedTree { -private: - int n; - vector c; + private int n; + private int[] c; -public: - BinaryIndexedTree(int n) { - this->n = n; - c.resize(n + 1, 0); + public BinaryIndexedTree(int n) { + this.n = n; + c = new int[n + 1]; } - void update(int x, int v) { + public void update(int x, int v) { while (x <= n) { - c[x] = max(c[x], v); + c[x] = Math.max(c[x], v); x += x & -x; } } - int query(int x) { + public int query(int x) { int mx = 0; while (x > 0) { - mx = max(mx, c[x]); + mx = Math.max(mx, c[x]); x -= x & -x; } return mx; } -}; +} class Solution { -public: - int maxProfit(vector& prices, vector& profits) { - int n = prices.size(); - vector left(n); - vector right(n); - vector s = prices; - sort(s.begin(), s.end()); - s.erase(unique(s.begin(), s.end()), s.end()); - int m = s.size(); - BinaryIndexedTree tree1(m + 1); - BinaryIndexedTree tree2(m + 1); + public int maxProfit(int[] prices, int[] profits) { + int n = prices.length; + int[] left = new int[n]; + int[] right = new int[n]; + int[] s = prices.clone(); + Arrays.sort(s); + int m = 0; for (int i = 0; i < n; ++i) { - int x = lower_bound(s.begin(), s.end(), prices[i]) - s.begin() + 1; + if (i == 0 || s[i] != s[i - 1]) { + s[m++] = s[i]; + } + } + BinaryIndexedTree tree1 = new BinaryIndexedTree(m + 1); + BinaryIndexedTree tree2 = new BinaryIndexedTree(m + 1); + for (int i = 0; i < n; ++i) { + int x = search(s, prices[i], m); left[i] = tree1.query(x - 1); tree1.update(x, profits[i]); } for (int i = n - 1; i >= 0; --i) { - int x = m + 1 - (lower_bound(s.begin(), s.end(), prices[i]) - s.begin() + 1); + int x = m + 1 - search(s, prices[i], m); right[i] = tree2.query(x - 1); tree2.update(x, profits[i]); } int ans = -1; for (int i = 0; i < n; ++i) { if (left[i] > 0 && right[i] > 0) { - ans = max(ans, left[i] + profits[i] + right[i]); + ans = Math.max(ans, left[i] + profits[i] + right[i]); } } return ans; } -}; -``` -### **Go** - -```go -func maxProfit(prices []int, profits []int) int { - n := len(prices) - ans := -1 - for j, x := range profits { - left, right := 0, 0 - for i := 0; i < j; i++ { - if prices[i] < prices[j] { - left = max(left, profits[i]) - } - } - for k := j + 1; k < n; k++ { - if prices[j] < prices[k] { - right = max(right, profits[k]) - } - } - if left > 0 && right > 0 { - ans = max(ans, left+x+right) - } - } - return ans + private int search(int[] nums, int x, int r) { + int l = 0; + while (l < r) { + int mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l + 1; + } } ``` -```go -type BinaryIndexedTree struct { - n int - c []int -} - -func NewBinaryIndexedTree(n int) BinaryIndexedTree { - c := make([]int, n+1) - return BinaryIndexedTree{n: n, c: c} -} - -func (bit *BinaryIndexedTree) update(x, v int) { - for x <= bit.n { - bit.c[x] = max(bit.c[x], v) - x += x & -x - } -} - -func (bit *BinaryIndexedTree) query(x int) int { - mx := 0 - for x > 0 { - mx = max(mx, bit.c[x]) - x -= x & -x - } - return mx -} - -func maxProfit(prices []int, profits []int) int { - n := len(prices) - left := make([]int, n) - right := make([]int, n) - m := slices.Max(prices) - - tree1 := NewBinaryIndexedTree(m + 1) - tree2 := NewBinaryIndexedTree(m + 1) - - for i, x := range prices { - left[i] = tree1.query(x - 1) - tree1.update(x, profits[i]) - } +```cpp +class BinaryIndexedTree { +private: + int n; + vector c; - for i := n - 1; i >= 0; i-- { - x := m + 1 - prices[i] - right[i] = tree2.query(x - 1) - tree2.update(x, profits[i]) - } +public: + BinaryIndexedTree(int n) { + this->n = n; + c.resize(n + 1, 0); + } - ans := -1 + void update(int x, int v) { + while (x <= n) { + c[x] = max(c[x], v); + x += x & -x; + } + } - for i := 0; i < n; i++ { - if left[i] > 0 && right[i] > 0 { - ans = max(ans, left[i]+profits[i]+right[i]) - } - } + int query(int x) { + int mx = 0; + while (x > 0) { + mx = max(mx, c[x]); + x -= x & -x; + } + return mx; + } +}; - return ans -} +class Solution { +public: + int maxProfit(vector& prices, vector& profits) { + int n = prices.size(); + vector left(n); + vector right(n); + vector s = prices; + sort(s.begin(), s.end()); + s.erase(unique(s.begin(), s.end()), s.end()); + int m = s.size(); + BinaryIndexedTree tree1(m + 1); + BinaryIndexedTree tree2(m + 1); + for (int i = 0; i < n; ++i) { + int x = lower_bound(s.begin(), s.end(), prices[i]) - s.begin() + 1; + left[i] = tree1.query(x - 1); + tree1.update(x, profits[i]); + } + for (int i = n - 1; i >= 0; --i) { + int x = m + 1 - (lower_bound(s.begin(), s.end(), prices[i]) - s.begin() + 1); + right[i] = tree2.query(x - 1); + tree2.update(x, profits[i]); + } + int ans = -1; + for (int i = 0; i < n; ++i) { + if (left[i] > 0 && right[i] > 0) { + ans = max(ans, left[i] + profits[i] + right[i]); + } + } + return ans; + } +}; ``` ```go @@ -643,92 +828,6 @@ func maxProfit(prices []int, profits []int) int { } ``` -### **TypeScript** - -```ts -function maxProfit(prices: number[], profits: number[]): number { - const n = prices.length; - let ans = -1; - for (let j = 0; j < n; ++j) { - let [left, right] = [0, 0]; - for (let i = 0; i < j; ++i) { - if (prices[i] < prices[j]) { - left = Math.max(left, profits[i]); - } - } - for (let k = j + 1; k < n; ++k) { - if (prices[j] < prices[k]) { - right = Math.max(right, profits[k]); - } - } - if (left > 0 && right > 0) { - ans = Math.max(ans, left + profits[j] + right); - } - } - return ans; -} -``` - -```ts -class BinaryIndexedTree { - private n: number; - private c: number[]; - - constructor(n: number) { - this.n = n; - this.c = Array(n + 1).fill(0); - } - - update(x: number, v: number): void { - while (x <= this.n) { - this.c[x] = Math.max(this.c[x], v); - x += x & -x; - } - } - - query(x: number): number { - let mx = 0; - while (x > 0) { - mx = Math.max(mx, this.c[x]); - x -= x & -x; - } - return mx; - } -} - -function maxProfit(prices: number[], profits: number[]): number { - const n: number = prices.length; - const left: number[] = Array(n).fill(0); - const right: number[] = Array(n).fill(0); - const m = Math.max(...prices); - - const tree1: BinaryIndexedTree = new BinaryIndexedTree(m + 1); - const tree2: BinaryIndexedTree = new BinaryIndexedTree(m + 1); - - for (let i = 0; i < n; i++) { - const x: number = prices[i]; - left[i] = tree1.query(x - 1); - tree1.update(x, profits[i]); - } - - for (let i = n - 1; i >= 0; i--) { - const x: number = m + 1 - prices[i]; - right[i] = tree2.query(x - 1); - tree2.update(x, profits[i]); - } - - let ans: number = -1; - - for (let i = 0; i < n; i++) { - if (left[i] > 0 && right[i] > 0) { - ans = Math.max(ans, left[i] + profits[i] + right[i]); - } - } - - return ans; -} -``` - ```ts class BinaryIndexedTree { private n: number; @@ -810,111 +909,6 @@ function maxProfit(prices: number[], profits: number[]): number { } ``` -### **Rust** - -```rust -impl Solution { - pub fn max_profit(prices: Vec, profits: Vec) -> i32 { - let n = prices.len(); - let mut ans = -1; - - for j in 0..n { - let mut left = 0; - let mut right = 0; - - for i in 0..j { - if prices[i] < prices[j] { - left = left.max(profits[i]); - } - } - - for k in j + 1..n { - if prices[j] < prices[k] { - right = right.max(profits[k]); - } - } - - if left > 0 && right > 0 { - ans = ans.max(left + profits[j] + right); - } - } - - ans - } -} -``` - -```rust -struct BinaryIndexedTree { - n: usize, - c: Vec, -} - -impl BinaryIndexedTree { - fn new(n: usize) -> BinaryIndexedTree { - BinaryIndexedTree { - n, - c: vec![0; n + 1], - } - } - - fn update(&mut self, x: usize, v: i32) { - let mut x = x; - while x <= self.n { - self.c[x] = self.c[x].max(v); - x += x & x.wrapping_neg(); - } - } - - fn query(&self, x: usize) -> i32 { - let mut x = x; - let mut mx = 0; - while x > 0 { - mx = mx.max(self.c[x]); - x -= x & x.wrapping_neg(); - } - mx - } -} - -impl Solution { - pub fn max_profit(prices: Vec, profits: Vec) -> i32 { - let n = prices.len(); - let mut left = vec![0; n]; - let mut right = vec![0; n]; - let m = prices.iter().cloned().max().unwrap_or(0); - - let mut tree1 = BinaryIndexedTree::new((m as usize) + 1); - let mut tree2 = BinaryIndexedTree::new((m as usize) + 1); - - for i in 0..n { - let x = prices[i] as usize; - left[i] = tree1.query(x - 1); - tree1.update(x, profits[i]); - } - - for i in (0..n).rev() { - let x = (m + 1 - prices[i]) as usize; - right[i] = tree2.query(x - 1); - tree2.update(x, profits[i]); - } - - let mut ans = -1; - for i in 0..n { - if left[i] > 0 && right[i] > 0 { - ans = ans.max(left[i] + profits[i] + right[i]); - } - } - - ans - } -} -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2908.Minimum Sum of Mountain Triplets I/README.md b/solution/2900-2999/2908.Minimum Sum of Mountain Triplets I/README.md index 54aefd352888f..6711e269a786d 100644 --- a/solution/2900-2999/2908.Minimum Sum of Mountain Triplets I/README.md +++ b/solution/2900-2999/2908.Minimum Sum of Mountain Triplets I/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:预处理 + 枚举** +### 方法一:预处理 + 枚举 我们可以预处理出每个位置右侧的最小值,记录在数组 $right[i]$ 中,即 $right[i]$ 表示 $nums[i+1..n-1]$ 中的最小值。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def minimumSum(self, nums: List[int]) -> int: @@ -93,10 +87,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - - - ```java class Solution { public int minimumSum(int[] nums) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func minimumSum(nums []int) int { n := len(nums) @@ -169,8 +155,6 @@ func minimumSum(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumSum(nums: number[]): number { const n = nums.length; @@ -189,10 +173,6 @@ function minimumSum(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2908.Minimum Sum of Mountain Triplets I/README_EN.md b/solution/2900-2999/2908.Minimum Sum of Mountain Triplets I/README_EN.md index 5773dbf51ce9b..cd4aa277334c7 100644 --- a/solution/2900-2999/2908.Minimum Sum of Mountain Triplets I/README_EN.md +++ b/solution/2900-2999/2908.Minimum Sum of Mountain Triplets I/README_EN.md @@ -56,7 +56,7 @@ And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown ## Solutions -**Solution 1: Preprocessing + Enumeration** +### Solution 1: Preprocessing + Enumeration We can preprocess the minimum value on the right side of each position and record it in the array $right[i]$, where $right[i]$ represents the minimum value in $nums[i+1..n-1]$. @@ -68,8 +68,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def minimumSum(self, nums: List[int]) -> int: @@ -85,8 +83,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - ```java class Solution { public int minimumSum(int[] nums) { @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +128,6 @@ public: }; ``` -### **Go** - ```go func minimumSum(nums []int) int { n := len(nums) @@ -159,8 +151,6 @@ func minimumSum(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumSum(nums: number[]): number { const n = nums.length; @@ -179,10 +169,6 @@ function minimumSum(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2909.Minimum Sum of Mountain Triplets II/README.md b/solution/2900-2999/2909.Minimum Sum of Mountain Triplets II/README.md index a69944dab43dd..c14fff87814bf 100644 --- a/solution/2900-2999/2909.Minimum Sum of Mountain Triplets II/README.md +++ b/solution/2900-2999/2909.Minimum Sum of Mountain Triplets II/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:预处理 + 枚举** +### 方法一:预处理 + 枚举 我们可以预处理出每个位置右侧的最小值,记录在数组 $right[i]$ 中,即 $right[i]$ 表示 $nums[i+1..n-1]$ 中的最小值。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def minimumSum(self, nums: List[int]) -> int: @@ -93,10 +87,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - - - ```java class Solution { public int minimumSum(int[] nums) { @@ -119,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +132,6 @@ public: }; ``` -### **Go** - ```go func minimumSum(nums []int) int { n := len(nums) @@ -169,8 +155,6 @@ func minimumSum(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumSum(nums: number[]): number { const n = nums.length; @@ -189,10 +173,6 @@ function minimumSum(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2909.Minimum Sum of Mountain Triplets II/README_EN.md b/solution/2900-2999/2909.Minimum Sum of Mountain Triplets II/README_EN.md index 22df050411ce8..1ea6b15490e34 100644 --- a/solution/2900-2999/2909.Minimum Sum of Mountain Triplets II/README_EN.md +++ b/solution/2900-2999/2909.Minimum Sum of Mountain Triplets II/README_EN.md @@ -56,7 +56,7 @@ And the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown ## Solutions -**Solution 1: Preprocessing + Enumeration** +### Solution 1: Preprocessing + Enumeration We can preprocess the minimum value on the right side of each position and record it in the array $right[i]$, where $right[i]$ represents the minimum value in $nums[i+1..n-1]$. @@ -68,8 +68,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def minimumSum(self, nums: List[int]) -> int: @@ -85,8 +83,6 @@ class Solution: return -1 if ans == inf else ans ``` -### **Java** - ```java class Solution { public int minimumSum(int[] nums) { @@ -109,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +128,6 @@ public: }; ``` -### **Go** - ```go func minimumSum(nums []int) int { n := len(nums) @@ -159,8 +151,6 @@ func minimumSum(nums []int) int { } ``` -### **TypeScript** - ```ts function minimumSum(nums: number[]): number { const n = nums.length; @@ -179,10 +169,6 @@ function minimumSum(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/README.md b/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/README.md index 77b7849ea14b3..64c13d4e25149 100644 --- a/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/README.md +++ b/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:哈希表 + 枚举** +### 方法一:哈希表 + 枚举 我们用一个哈希表 $cnt$ 统计数组 $nums$ 中每个数字出现的次数,我们记数字次数的最小值为 $k$,那么我们可以在 $[k,..1]$ 的范围内枚举分组的大小。由于每个组的大小差值不超过 $1$,那么分组大小为 $k$ 或 $k+1$。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def minGroupsForValidAssignment(self, nums: List[int]) -> int: @@ -93,10 +87,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minGroupsForValidAssignment(int[] nums) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -156,8 +144,6 @@ public: }; ``` -### **Go** - ```go func minGroupsForValidAssignment(nums []int) int { cnt := map[int]int{} @@ -184,8 +170,6 @@ func minGroupsForValidAssignment(nums []int) int { } ``` -### **TypeScript** - ```ts function minGroupsForValidAssignment(nums: number[]): number { const cnt: Map = new Map(); @@ -208,8 +192,6 @@ function minGroupsForValidAssignment(nums: number[]): number { } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -250,10 +232,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/README_EN.md b/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/README_EN.md index 156c4a9ecc7f9..343c80f21a629 100644 --- a/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/README_EN.md +++ b/solution/2900-2999/2910.Minimum Number of Groups to Create a Valid Assignment/README_EN.md @@ -58,7 +58,7 @@ Hence, the answer is 4. ## Solutions -**Solution 1: Hash Table + Enumeration** +### Solution 1: Hash Table + Enumeration We use a hash table $cnt$ to count the number of occurrences of each number in the array $nums$. Let $k$ be the minimum value of the number of occurrences, and then we can enumerate the size of the groups in the range $[k,..1]$. Since the difference in size between each group is not more than $1$, the group size can be either $k$ or $k+1$. @@ -68,8 +68,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def minGroupsForValidAssignment(self, nums: List[int]) -> int: @@ -85,8 +83,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minGroupsForValidAssignment(int[] nums) { @@ -115,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +140,6 @@ public: }; ``` -### **Go** - ```go func minGroupsForValidAssignment(nums []int) int { cnt := map[int]int{} @@ -174,8 +166,6 @@ func minGroupsForValidAssignment(nums []int) int { } ``` -### **TypeScript** - ```ts function minGroupsForValidAssignment(nums: number[]): number { const cnt: Map = new Map(); @@ -198,8 +188,6 @@ function minGroupsForValidAssignment(nums: number[]): number { } ``` -### **Rust** - ```rust use std::collections::HashMap; @@ -240,10 +228,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/README.md b/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/README.md index 565126b38ff7b..e9bf7e9f477b1 100644 --- a/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/README.md +++ b/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/README.md @@ -57,18 +57,10 @@ ## 解法 - - -**优化: 预处理因数列表** - -可以预先处理每个长度的因数列表,这样就不用每次都去计算了。 +### 方法一 -### **Python3** - - - ```python class Solution: def minimumChanges(self, s: str, k: int) -> int: @@ -97,10 +89,6 @@ class Solution: return f[n][k] ``` -### **Java** - - - ```java class Solution { public int minimumChanges(String s, int k) { @@ -145,91 +133,6 @@ class Solution { } ``` -```java -class Solution { - static int inf = 200; - List[] factorLists; - int n; - int k; - char[] ch; - Integer[][] cost; - public int minimumChanges(String s, int k) { - this.k = k; - n = s.length(); - ch = s.toCharArray(); - - factorLists = getFactorLists(n); - cost = new Integer[n + 1][n + 1]; - return calcDP(); - } - static List[] getFactorLists(int n) { - List[] l = new ArrayList[n + 1]; - for (int i = 1; i <= n; i++) { - l[i] = new ArrayList<>(); - l[i].add(1); - } - for (int factor = 2; factor < n; factor++) { - for (int num = factor + factor; num <= n; num += factor) { - l[num].add(factor); - } - } - return l; - } - int calcDP() { - int[] dp = new int[n]; - for (int i = n - k * 2 + 1; i >= 1; i--) { - dp[i] = getCost(0, i); - } - int bound = 0; - for (int subs = 2; subs <= k; subs++) { - bound = subs * 2; - for (int i = n - 1 - k * 2 + subs * 2; i >= bound - 1; i--) { - dp[i] = inf; - for (int prev = bound - 3; prev < i - 1; prev++) { - dp[i] = Math.min(dp[i], dp[prev] + getCost(prev + 1, i)); - } - } - } - return dp[n - 1]; - } - int getCost(int l, int r) { - if (l >= r) { - return inf; - } - if (cost[l][r] != null) { - return cost[l][r]; - } - cost[l][r] = inf; - for (int factor : factorLists[r - l + 1]) { - cost[l][r] = Math.min(cost[l][r], getStepwiseCost(l, r, factor)); - } - return cost[l][r]; - } - int getStepwiseCost(int l, int r, int stepsize) { - if (l >= r) { - return 0; - } - int left = 0; - int right = 0; - int count = 0; - for (int i = 0; i < stepsize; i++) { - left = l + i; - right = r - stepsize + 1 + i; - while (left + stepsize <= right) { - if (ch[left] != ch[right]) { - count++; - } - left += stepsize; - right -= stepsize; - } - } - return count; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -272,8 +175,6 @@ public: }; ``` -### **Go** - ```go func minimumChanges(s string, k int) int { n := len(s) @@ -322,8 +223,6 @@ func minimumChanges(s string, k int) int { } ``` -### **TypeScript** - ```ts function minimumChanges(s: string, k: number): number { const n = s.length; @@ -361,10 +260,95 @@ function minimumChanges(s: string, k: number): number { } ``` -### **...** + -``` +### 方法二 + + +```java +class Solution { + static int inf = 200; + List[] factorLists; + int n; + int k; + char[] ch; + Integer[][] cost; + public int minimumChanges(String s, int k) { + this.k = k; + n = s.length(); + ch = s.toCharArray(); + + factorLists = getFactorLists(n); + cost = new Integer[n + 1][n + 1]; + return calcDP(); + } + static List[] getFactorLists(int n) { + List[] l = new ArrayList[n + 1]; + for (int i = 1; i <= n; i++) { + l[i] = new ArrayList<>(); + l[i].add(1); + } + for (int factor = 2; factor < n; factor++) { + for (int num = factor + factor; num <= n; num += factor) { + l[num].add(factor); + } + } + return l; + } + int calcDP() { + int[] dp = new int[n]; + for (int i = n - k * 2 + 1; i >= 1; i--) { + dp[i] = getCost(0, i); + } + int bound = 0; + for (int subs = 2; subs <= k; subs++) { + bound = subs * 2; + for (int i = n - 1 - k * 2 + subs * 2; i >= bound - 1; i--) { + dp[i] = inf; + for (int prev = bound - 3; prev < i - 1; prev++) { + dp[i] = Math.min(dp[i], dp[prev] + getCost(prev + 1, i)); + } + } + } + return dp[n - 1]; + } + int getCost(int l, int r) { + if (l >= r) { + return inf; + } + if (cost[l][r] != null) { + return cost[l][r]; + } + cost[l][r] = inf; + for (int factor : factorLists[r - l + 1]) { + cost[l][r] = Math.min(cost[l][r], getStepwiseCost(l, r, factor)); + } + return cost[l][r]; + } + int getStepwiseCost(int l, int r, int stepsize) { + if (l >= r) { + return 0; + } + int left = 0; + int right = 0; + int count = 0; + for (int i = 0; i < stepsize; i++) { + left = l + i; + right = r - stepsize + 1 + i; + while (left + stepsize <= right) { + if (ch[left] != ch[right]) { + count++; + } + left += stepsize; + right -= stepsize; + } + } + return count; + } +} ``` + + diff --git a/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/README_EN.md b/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/README_EN.md index a3e54878042cd..6e779dd673aba 100644 --- a/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/README_EN.md +++ b/solution/2900-2999/2911.Minimum Changes to Make K Semi-palindromes/README_EN.md @@ -53,14 +53,10 @@ The strings "aa" and "bb" are already semi-palindromes. Thus ## Solutions -**Optimization: Preprocessing Divisors List** - -We can calculate the divisors list for each length, which can save a lot of division operations in the inner loop. +### Solution 1 -### **Python3** - ```python class Solution: def minimumChanges(self, s: str, k: int) -> int: @@ -89,8 +85,6 @@ class Solution: return f[n][k] ``` -### **Java** - ```java class Solution { public int minimumChanges(String s, int k) { @@ -135,91 +129,6 @@ class Solution { } ``` -```java -class Solution { - static int inf = 200; - List[] factorLists; - int n; - int k; - char[] ch; - Integer[][] cost; - public int minimumChanges(String s, int k) { - this.k = k; - n = s.length(); - ch = s.toCharArray(); - - factorLists = getFactorLists(n); - cost = new Integer[n + 1][n + 1]; - return calcDP(); - } - static List[] getFactorLists(int n) { - List[] l = new ArrayList[n + 1]; - for (int i = 1; i <= n; i++) { - l[i] = new ArrayList<>(); - l[i].add(1); - } - for (int factor = 2; factor < n; factor++) { - for (int num = factor + factor; num <= n; num += factor) { - l[num].add(factor); - } - } - return l; - } - int calcDP() { - int[] dp = new int[n]; - for (int i = n - k * 2 + 1; i >= 1; i--) { - dp[i] = getCost(0, i); - } - int bound = 0; - for (int subs = 2; subs <= k; subs++) { - bound = subs * 2; - for (int i = n - 1 - k * 2 + subs * 2; i >= bound - 1; i--) { - dp[i] = inf; - for (int prev = bound - 3; prev < i - 1; prev++) { - dp[i] = Math.min(dp[i], dp[prev] + getCost(prev + 1, i)); - } - } - } - return dp[n - 1]; - } - int getCost(int l, int r) { - if (l >= r) { - return inf; - } - if (cost[l][r] != null) { - return cost[l][r]; - } - cost[l][r] = inf; - for (int factor : factorLists[r - l + 1]) { - cost[l][r] = Math.min(cost[l][r], getStepwiseCost(l, r, factor)); - } - return cost[l][r]; - } - int getStepwiseCost(int l, int r, int stepsize) { - if (l >= r) { - return 0; - } - int left = 0; - int right = 0; - int count = 0; - for (int i = 0; i < stepsize; i++) { - left = l + i; - right = r - stepsize + 1 + i; - while (left + stepsize <= right) { - if (ch[left] != ch[right]) { - count++; - } - left += stepsize; - right -= stepsize; - } - } - return count; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -262,8 +171,6 @@ public: }; ``` -### **Go** - ```go func minimumChanges(s string, k int) int { n := len(s) @@ -312,8 +219,6 @@ func minimumChanges(s string, k int) int { } ``` -### **TypeScript** - ```ts function minimumChanges(s: string, k: number): number { const n = s.length; @@ -351,10 +256,95 @@ function minimumChanges(s: string, k: number): number { } ``` -### **...** + -``` +### Solution 2 + + + +```java +class Solution { + static int inf = 200; + List[] factorLists; + int n; + int k; + char[] ch; + Integer[][] cost; + public int minimumChanges(String s, int k) { + this.k = k; + n = s.length(); + ch = s.toCharArray(); + factorLists = getFactorLists(n); + cost = new Integer[n + 1][n + 1]; + return calcDP(); + } + static List[] getFactorLists(int n) { + List[] l = new ArrayList[n + 1]; + for (int i = 1; i <= n; i++) { + l[i] = new ArrayList<>(); + l[i].add(1); + } + for (int factor = 2; factor < n; factor++) { + for (int num = factor + factor; num <= n; num += factor) { + l[num].add(factor); + } + } + return l; + } + int calcDP() { + int[] dp = new int[n]; + for (int i = n - k * 2 + 1; i >= 1; i--) { + dp[i] = getCost(0, i); + } + int bound = 0; + for (int subs = 2; subs <= k; subs++) { + bound = subs * 2; + for (int i = n - 1 - k * 2 + subs * 2; i >= bound - 1; i--) { + dp[i] = inf; + for (int prev = bound - 3; prev < i - 1; prev++) { + dp[i] = Math.min(dp[i], dp[prev] + getCost(prev + 1, i)); + } + } + } + return dp[n - 1]; + } + int getCost(int l, int r) { + if (l >= r) { + return inf; + } + if (cost[l][r] != null) { + return cost[l][r]; + } + cost[l][r] = inf; + for (int factor : factorLists[r - l + 1]) { + cost[l][r] = Math.min(cost[l][r], getStepwiseCost(l, r, factor)); + } + return cost[l][r]; + } + int getStepwiseCost(int l, int r, int stepsize) { + if (l >= r) { + return 0; + } + int left = 0; + int right = 0; + int count = 0; + for (int i = 0; i < stepsize; i++) { + left = l + i; + right = r - stepsize + 1 + i; + while (left + stepsize <= right) { + if (ch[left] != ch[right]) { + count++; + } + left += stepsize; + right -= stepsize; + } + } + return count; + } +} ``` + + diff --git a/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/README.md b/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/README.md index 3edd6d679a683..c92e4bda2367c 100644 --- a/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/README.md +++ b/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义以下几个状态,其中: @@ -92,10 +90,6 @@ $$ -### **Python3** - - - ```python class Solution: def numberOfWays( @@ -114,29 +108,6 @@ class Solution: return b if source[1] == dest[1] else d ``` -```python -class Solution: - def numberOfWays( - self, n: int, m: int, k: int, source: List[int], dest: List[int] - ) -> int: - mod = 10**9 + 7 - f = [1, 0, 0, 0] - for _ in range(k): - g = [0] * 4 - g[0] = ((n - 1) * f[1] + (m - 1) * f[2]) % mod - g[1] = (f[0] + (n - 2) * f[1] + (m - 1) * f[3]) % mod - g[2] = (f[0] + (m - 2) * f[2] + (n - 1) * f[3]) % mod - g[3] = (f[1] + f[2] + (n - 2) * f[3] + (m - 2) * f[3]) % mod - f = g - if source[0] == dest[0]: - return f[0] if source[1] == dest[1] else f[2] - return f[1] if source[1] == dest[1] else f[3] -``` - -### **Java** - - - ```java class Solution { public int numberOfWays(int n, int m, int k, int[] source, int[] dest) { @@ -159,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -184,8 +153,6 @@ public: }; ``` -### **Go** - ```go func numberOfWays(n int, m int, k int, source []int, dest []int) int { const mod int = 1e9 + 7 @@ -213,10 +180,31 @@ func numberOfWays(n int, m int, k int, source []int, dest []int) int { } ``` -### **...** + + +### 方法二 -``` + +```python +class Solution: + def numberOfWays( + self, n: int, m: int, k: int, source: List[int], dest: List[int] + ) -> int: + mod = 10**9 + 7 + f = [1, 0, 0, 0] + for _ in range(k): + g = [0] * 4 + g[0] = ((n - 1) * f[1] + (m - 1) * f[2]) % mod + g[1] = (f[0] + (n - 2) * f[1] + (m - 1) * f[3]) % mod + g[2] = (f[0] + (m - 2) * f[2] + (n - 1) * f[3]) % mod + g[3] = (f[1] + f[2] + (n - 2) * f[3] + (m - 2) * f[3]) % mod + f = g + if source[0] == dest[0]: + return f[0] if source[1] == dest[1] else f[2] + return f[1] if source[1] == dest[1] else f[3] ``` + + diff --git a/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/README_EN.md b/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/README_EN.md index 9f62f15eeeca9..7b62edff22742 100644 --- a/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/README_EN.md +++ b/solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/README_EN.md @@ -58,7 +58,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define the following states: @@ -86,8 +86,6 @@ The time complexity is $O(k)$, where $k$ is the number of moves. The space compl -### **Python3** - ```python class Solution: def numberOfWays( @@ -106,27 +104,6 @@ class Solution: return b if source[1] == dest[1] else d ``` -```python -class Solution: - def numberOfWays( - self, n: int, m: int, k: int, source: List[int], dest: List[int] - ) -> int: - mod = 10**9 + 7 - f = [1, 0, 0, 0] - for _ in range(k): - g = [0] * 4 - g[0] = ((n - 1) * f[1] + (m - 1) * f[2]) % mod - g[1] = (f[0] + (n - 2) * f[1] + (m - 1) * f[3]) % mod - g[2] = (f[0] + (m - 2) * f[2] + (n - 1) * f[3]) % mod - g[3] = (f[1] + f[2] + (n - 2) * f[3] + (m - 2) * f[3]) % mod - f = g - if source[0] == dest[0]: - return f[0] if source[1] == dest[1] else f[2] - return f[1] if source[1] == dest[1] else f[3] -``` - -### **Java** - ```java class Solution { public int numberOfWays(int n, int m, int k, int[] source, int[] dest) { @@ -149,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -174,8 +149,6 @@ public: }; ``` -### **Go** - ```go func numberOfWays(n int, m int, k int, source []int, dest []int) int { const mod int = 1e9 + 7 @@ -203,10 +176,31 @@ func numberOfWays(n int, m int, k int, source []int, dest []int) int { } ``` -### **...** + -``` +### Solution 2 + + +```python +class Solution: + def numberOfWays( + self, n: int, m: int, k: int, source: List[int], dest: List[int] + ) -> int: + mod = 10**9 + 7 + f = [1, 0, 0, 0] + for _ in range(k): + g = [0] * 4 + g[0] = ((n - 1) * f[1] + (m - 1) * f[2]) % mod + g[1] = (f[0] + (n - 2) * f[1] + (m - 1) * f[3]) % mod + g[2] = (f[0] + (m - 2) * f[2] + (n - 1) * f[3]) % mod + g[3] = (f[1] + f[2] + (n - 2) * f[3] + (m - 2) * f[3]) % mod + f = g + if source[0] == dest[0]: + return f[0] if source[1] == dest[1] else f[2] + return f[1] if source[1] == dest[1] else f[3] ``` + + diff --git a/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/README.md b/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/README.md index 809f86da4d805..7055feb408cf7 100644 --- a/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/README.md +++ b/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/README.md @@ -60,9 +60,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举子数组的左端点下标 $i$,对于每个 $i$,我们在 $[i, n)$ 的范围内枚举子数组的右端点下标 $j$,并统计 $nums[j]$ 的值,将其加入到集合 $s$ 中,记 $s$ 的大小为 $cnt$,那么 $nums[i..j]$ 的不同计数为 $cnt$,将其平方后加入到答案中。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def sumCounts(self, nums: List[int]) -> int: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int sumCounts(List nums) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +123,6 @@ public: }; ``` -### **Go** - ```go func sumCounts(nums []int) (ans int) { for i := range nums { @@ -154,8 +140,6 @@ func sumCounts(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumCounts(nums: number[]): number { let ans = 0; @@ -174,10 +158,6 @@ function sumCounts(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/README_EN.md b/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/README_EN.md index 6d35a45f57e73..4869cd4d405dc 100644 --- a/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/README_EN.md +++ b/solution/2900-2999/2913.Subarrays Distinct Element Sum of Squares I/README_EN.md @@ -53,7 +53,7 @@ The sum of the squares of the distinct counts in all subarrays is equal to 1 -### **Python3** - ```python class Solution: def sumCounts(self, nums: List[int]) -> int: @@ -77,8 +75,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int sumCounts(List nums) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +116,6 @@ public: }; ``` -### **Go** - ```go func sumCounts(nums []int) (ans int) { for i := range nums { @@ -141,8 +133,6 @@ func sumCounts(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function sumCounts(nums: number[]): number { let ans = 0; @@ -161,10 +151,6 @@ function sumCounts(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/README.md b/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/README.md index 7d17255da6c08..b95ae987a419d 100644 --- a/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/README.md +++ b/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/README.md @@ -61,9 +61,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们只需要遍历字符串 $s$ 的所有奇数下标 $1, 3, 5, \cdots$,如果当前奇数下标与前一个下标的字符不同,即 $s[i] \ne s[i - 1]$,那么就需要修改当前字符,使得 $s[i] = s[i - 1]$。因此,此时答案需要加 $1$。 @@ -73,20 +71,12 @@ -### **Python3** - - - ```python class Solution: def minChanges(self, s: str) -> int: return sum(s[i] != s[i - 1] for i in range(1, len(s), 2)) ``` -### **Java** - - - ```java class Solution { public int minChanges(String s) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -117,8 +105,6 @@ public: }; ``` -### **Go** - ```go func minChanges(s string) (ans int) { for i := 1; i < len(s); i += 2 { @@ -130,8 +116,6 @@ func minChanges(s string) (ans int) { } ``` -### **TypeScript** - ```ts function minChanges(s: string): number { let ans = 0; @@ -144,10 +128,6 @@ function minChanges(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/README_EN.md b/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/README_EN.md index 1e3af94b77977..597fd06ca3cd1 100644 --- a/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/README_EN.md +++ b/solution/2900-2999/2914.Minimum Number of Changes to Make Binary String Beautiful/README_EN.md @@ -57,7 +57,7 @@ It can be proven that 1 is the minimum number of changes needed to make the stri ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We only need to traverse all odd indices $1, 3, 5, \cdots$ of the string $s$. If the current odd index is different from the previous index, i.e., $s[i] \ne s[i - 1]$, we need to modify the current character so that $s[i] = s[i - 1]$. Therefore, the answer needs to be incremented by $1$. @@ -67,16 +67,12 @@ The time complexity is $O(n)$, where $n$ is the length of the string $s$. The sp -### **Python3** - ```python class Solution: def minChanges(self, s: str) -> int: return sum(s[i] != s[i - 1] for i in range(1, len(s), 2)) ``` -### **Java** - ```java class Solution { public int minChanges(String s) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -107,8 +101,6 @@ public: }; ``` -### **Go** - ```go func minChanges(s string) (ans int) { for i := 1; i < len(s); i += 2 { @@ -120,8 +112,6 @@ func minChanges(s string) (ans int) { } ``` -### **TypeScript** - ```ts function minChanges(s: string): number { let ans = 0; @@ -134,10 +124,6 @@ function minChanges(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/README.md b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/README.md index e7adafa320965..22e957947f6bf 100644 --- a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/README.md +++ b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i][j]$ 表示前 $i$ 个数中选取若干个数,使得这若干个数的和恰好为 $j$ 的最长子序列的长度。初始时 $f[0][0]=0$,其余位置均为 $-\infty$。 @@ -70,10 +68,6 @@ $$ -### **Python3** - - - ```python class Solution: def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int: @@ -88,20 +82,6 @@ class Solution: return -1 if f[n][target] <= 0 else f[n][target] ``` -```python -class Solution: - def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int: - f = [0] + [-inf] * target - for x in nums: - for j in range(target, x - 1, -1): - f[j] = max(f[j], f[j - x] + 1) - return -1 if f[-1] <= 0 else f[-1] -``` - -### **Java** - - - ```java class Solution { public int lengthOfLongestSubsequence(List nums, int target) { @@ -126,25 +106,6 @@ class Solution { } ``` -```java -class Solution { - public int lengthOfLongestSubsequence(List nums, int target) { - int[] f = new int[target + 1]; - final int inf = 1 << 30; - Arrays.fill(f, -inf); - f[0] = 0; - for (int x : nums) { - for (int j = target; j >= x; --j) { - f[j] = Math.max(f[j], f[j - x] + 1); - } - } - return f[target] <= 0 ? -1 : f[target]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -167,25 +128,6 @@ public: }; ``` -```cpp -class Solution { -public: - int lengthOfLongestSubsequence(vector& nums, int target) { - int f[target + 1]; - memset(f, -0x3f, sizeof(f)); - f[0] = 0; - for (int x : nums) { - for (int j = target; j >= x; --j) { - f[j] = max(f[j], f[j - x] + 1); - } - } - return f[target] <= 0 ? -1 : f[target]; - } -}; -``` - -### **Go** - ```go func lengthOfLongestSubsequence(nums []int, target int) int { n := len(nums) @@ -213,6 +155,74 @@ func lengthOfLongestSubsequence(nums []int, target int) int { } ``` +```ts +function lengthOfLongestSubsequence(nums: number[], target: number): number { + const n = nums.length; + const f: number[][] = Array.from({ length: n + 1 }, () => Array(target + 1).fill(-Infinity)); + f[0][0] = 0; + for (let i = 1; i <= n; ++i) { + const x = nums[i - 1]; + for (let j = 0; j <= target; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= x) { + f[i][j] = Math.max(f[i][j], f[i - 1][j - x] + 1); + } + } + } + return f[n][target] <= 0 ? -1 : f[n][target]; +} +``` + + + +### 方法二 + + + +```python +class Solution: + def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int: + f = [0] + [-inf] * target + for x in nums: + for j in range(target, x - 1, -1): + f[j] = max(f[j], f[j - x] + 1) + return -1 if f[-1] <= 0 else f[-1] +``` + +```java +class Solution { + public int lengthOfLongestSubsequence(List nums, int target) { + int[] f = new int[target + 1]; + final int inf = 1 << 30; + Arrays.fill(f, -inf); + f[0] = 0; + for (int x : nums) { + for (int j = target; j >= x; --j) { + f[j] = Math.max(f[j], f[j - x] + 1); + } + } + return f[target] <= 0 ? -1 : f[target]; + } +} +``` + +```cpp +class Solution { +public: + int lengthOfLongestSubsequence(vector& nums, int target) { + int f[target + 1]; + memset(f, -0x3f, sizeof(f)); + f[0] = 0; + for (int x : nums) { + for (int j = target; j >= x; --j) { + f[j] = max(f[j], f[j - x] + 1); + } + } + return f[target] <= 0 ? -1 : f[target]; + } +}; +``` + ```go func lengthOfLongestSubsequence(nums []int, target int) int { f := make([]int, target+1) @@ -232,26 +242,6 @@ func lengthOfLongestSubsequence(nums []int, target int) int { } ``` -### **TypeScript** - -```ts -function lengthOfLongestSubsequence(nums: number[], target: number): number { - const n = nums.length; - const f: number[][] = Array.from({ length: n + 1 }, () => Array(target + 1).fill(-Infinity)); - f[0][0] = 0; - for (let i = 1; i <= n; ++i) { - const x = nums[i - 1]; - for (let j = 0; j <= target; ++j) { - f[i][j] = f[i - 1][j]; - if (j >= x) { - f[i][j] = Math.max(f[i][j], f[i - 1][j - x] + 1); - } - } - } - return f[n][target] <= 0 ? -1 : f[n][target]; -} -``` - ```ts function lengthOfLongestSubsequence(nums: number[], target: number): number { const f: number[] = Array(target + 1).fill(-Infinity); @@ -265,10 +255,6 @@ function lengthOfLongestSubsequence(nums: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/README_EN.md b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/README_EN.md index 2e76d28c369ff..f8e6b33d45f41 100644 --- a/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/README_EN.md +++ b/solution/2900-2999/2915.Length of the Longest Subsequence That Sums to Target/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i][j]$ as the length of the longest subsequence that selects several numbers from the first $i$ numbers and the sum of these numbers is exactly $j$. Initially, $f[0][0]=0$, and all other positions are $-\infty$. @@ -64,8 +64,6 @@ We notice that the state of $f[i][j]$ is only related to $f[i-1][\cdot]$, so we -### **Python3** - ```python class Solution: def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int: @@ -80,18 +78,6 @@ class Solution: return -1 if f[n][target] <= 0 else f[n][target] ``` -```python -class Solution: - def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int: - f = [0] + [-inf] * target - for x in nums: - for j in range(target, x - 1, -1): - f[j] = max(f[j], f[j - x] + 1) - return -1 if f[-1] <= 0 else f[-1] -``` - -### **Java** - ```java class Solution { public int lengthOfLongestSubsequence(List nums, int target) { @@ -116,25 +102,6 @@ class Solution { } ``` -```java -class Solution { - public int lengthOfLongestSubsequence(List nums, int target) { - int[] f = new int[target + 1]; - final int inf = 1 << 30; - Arrays.fill(f, -inf); - f[0] = 0; - for (int x : nums) { - for (int j = target; j >= x; --j) { - f[j] = Math.max(f[j], f[j - x] + 1); - } - } - return f[target] <= 0 ? -1 : f[target]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -157,25 +124,6 @@ public: }; ``` -```cpp -class Solution { -public: - int lengthOfLongestSubsequence(vector& nums, int target) { - int f[target + 1]; - memset(f, -0x3f, sizeof(f)); - f[0] = 0; - for (int x : nums) { - for (int j = target; j >= x; --j) { - f[j] = max(f[j], f[j - x] + 1); - } - } - return f[target] <= 0 ? -1 : f[target]; - } -}; -``` - -### **Go** - ```go func lengthOfLongestSubsequence(nums []int, target int) int { n := len(nums) @@ -203,6 +151,74 @@ func lengthOfLongestSubsequence(nums []int, target int) int { } ``` +```ts +function lengthOfLongestSubsequence(nums: number[], target: number): number { + const n = nums.length; + const f: number[][] = Array.from({ length: n + 1 }, () => Array(target + 1).fill(-Infinity)); + f[0][0] = 0; + for (let i = 1; i <= n; ++i) { + const x = nums[i - 1]; + for (let j = 0; j <= target; ++j) { + f[i][j] = f[i - 1][j]; + if (j >= x) { + f[i][j] = Math.max(f[i][j], f[i - 1][j - x] + 1); + } + } + } + return f[n][target] <= 0 ? -1 : f[n][target]; +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int: + f = [0] + [-inf] * target + for x in nums: + for j in range(target, x - 1, -1): + f[j] = max(f[j], f[j - x] + 1) + return -1 if f[-1] <= 0 else f[-1] +``` + +```java +class Solution { + public int lengthOfLongestSubsequence(List nums, int target) { + int[] f = new int[target + 1]; + final int inf = 1 << 30; + Arrays.fill(f, -inf); + f[0] = 0; + for (int x : nums) { + for (int j = target; j >= x; --j) { + f[j] = Math.max(f[j], f[j - x] + 1); + } + } + return f[target] <= 0 ? -1 : f[target]; + } +} +``` + +```cpp +class Solution { +public: + int lengthOfLongestSubsequence(vector& nums, int target) { + int f[target + 1]; + memset(f, -0x3f, sizeof(f)); + f[0] = 0; + for (int x : nums) { + for (int j = target; j >= x; --j) { + f[j] = max(f[j], f[j - x] + 1); + } + } + return f[target] <= 0 ? -1 : f[target]; + } +}; +``` + ```go func lengthOfLongestSubsequence(nums []int, target int) int { f := make([]int, target+1) @@ -222,26 +238,6 @@ func lengthOfLongestSubsequence(nums []int, target int) int { } ``` -### **TypeScript** - -```ts -function lengthOfLongestSubsequence(nums: number[], target: number): number { - const n = nums.length; - const f: number[][] = Array.from({ length: n + 1 }, () => Array(target + 1).fill(-Infinity)); - f[0][0] = 0; - for (let i = 1; i <= n; ++i) { - const x = nums[i - 1]; - for (let j = 0; j <= target; ++j) { - f[i][j] = f[i - 1][j]; - if (j >= x) { - f[i][j] = Math.max(f[i][j], f[i - 1][j - x] + 1); - } - } - } - return f[n][target] <= 0 ? -1 : f[n][target]; -} -``` - ```ts function lengthOfLongestSubsequence(nums: number[], target: number): number { const f: number[] = Array(target + 1).fill(-Infinity); @@ -255,10 +251,6 @@ function lengthOfLongestSubsequence(nums: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2916.Subarrays Distinct Element Sum of Squares II/README.md b/solution/2900-2999/2916.Subarrays Distinct Element Sum of Squares II/README.md index 71ece64bd758c..d149bfc1b4022 100644 --- a/solution/2900-2999/2916.Subarrays Distinct Element Sum of Squares II/README.md +++ b/solution/2900-2999/2916.Subarrays Distinct Element Sum of Squares II/README.md @@ -60,42 +60,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2900-2999/2916.Subarrays Distinct Element Sum of Squares II/README_EN.md b/solution/2900-2999/2916.Subarrays Distinct Element Sum of Squares II/README_EN.md index 45a8a9a509223..3f161a2bd1a26 100644 --- a/solution/2900-2999/2916.Subarrays Distinct Element Sum of Squares II/README_EN.md +++ b/solution/2900-2999/2916.Subarrays Distinct Element Sum of Squares II/README_EN.md @@ -55,36 +55,4 @@ The sum of the squares of the distinct counts in all subarrays is equal to 1 - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2900-2999/2917.Find the K-or of an Array/README.md b/solution/2900-2999/2917.Find the K-or of an Array/README.md index d7410b356ec48..991d432417a03 100644 --- a/solution/2900-2999/2917.Find the K-or of an Array/README.md +++ b/solution/2900-2999/2917.Find the K-or of an Array/README.md @@ -59,9 +59,7 @@ nums[1]、nums[2]、nums[3]、nums[4] 和 nums[5] 的第 3 位的值为 1 。 ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以在 $[0, 32)$ 范围内枚举每一位 $i$,统计数组 $nums$ 有多少个数的第 $i$ 位为 $1$,记为 $cnt$。如果 $cnt \ge k$,那么我们就将 $2^i$ 次方加到答案中。 @@ -71,10 +69,6 @@ nums[1]、nums[2]、nums[3]、nums[4] 和 nums[5] 的第 3 位的值为 1 。 -### **Python3** - - - ```python class Solution: def findKOr(self, nums: List[int], k: int) -> int: @@ -86,10 +80,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int findKOr(int[] nums, int k) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -129,8 +117,6 @@ public: }; ``` -### **Go** - ```go func findKOr(nums []int, k int) (ans int) { for i := 0; i < 32; i++ { @@ -146,8 +132,6 @@ func findKOr(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function findKOr(nums: number[], k: number): number { let ans = 0; @@ -164,10 +148,6 @@ function findKOr(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2917.Find the K-or of an Array/README_EN.md b/solution/2900-2999/2917.Find the K-or of an Array/README_EN.md index c7df42d4b87d5..0875a7c2839b4 100644 --- a/solution/2900-2999/2917.Find the K-or of an Array/README_EN.md +++ b/solution/2900-2999/2917.Find the K-or of an Array/README_EN.md @@ -56,7 +56,7 @@ Only bits 0 and 3 are set in at least k elements of the array, and bits i >= ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We can enumerate each bit $i$ in the range $[0, 32)$, and count the number of numbers in the array $nums$ whose $i$-th bit is $1$, denoted as $cnt$. If $cnt \ge k$, we add $2^i$ to the answer. @@ -66,8 +66,6 @@ The time complexity is $O(n \times \log M)$, where $n$ and $M$ are the length of -### **Python3** - ```python class Solution: def findKOr(self, nums: List[int], k: int) -> int: @@ -79,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int findKOr(int[] nums, int k) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +114,6 @@ public: }; ``` -### **Go** - ```go func findKOr(nums []int, k int) (ans int) { for i := 0; i < 32; i++ { @@ -137,8 +129,6 @@ func findKOr(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function findKOr(nums: number[], k: number): number { let ans = 0; @@ -155,10 +145,6 @@ function findKOr(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/README.md b/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/README.md index 347e41d79bb65..f244030fb051c 100644 --- a/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/README.md +++ b/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:分情况讨论** +### 方法一:分情况讨论 我们记把数组中的 $0$ 视为 $1$,统计两个数组的和,分别记为 $s_1$ 和 $s_2$。不妨设 $s_1 \le s_2$。 @@ -57,10 +55,6 @@ -### **Python3** - - - ```python class Solution: def minSum(self, nums1: List[int], nums2: List[int]) -> int: @@ -73,10 +67,6 @@ class Solution: return -1 if nums1.count(0) == 0 else s2 ``` -### **Java** - - - ```java class Solution { public long minSum(int[] nums1, int[] nums2) { @@ -100,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -126,8 +114,6 @@ public: }; ``` -### **Go** - ```go func minSum(nums1 []int, nums2 []int) int64 { s1, s2 := 0, 0 @@ -154,8 +140,6 @@ func minSum(nums1 []int, nums2 []int) int64 { } ``` -### **TypeScript** - ```ts function minSum(nums1: number[], nums2: number[]): number { let [s1, s2] = [0, 0]; @@ -179,10 +163,6 @@ function minSum(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/README_EN.md b/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/README_EN.md index 364de81b37284..55aa5e98fdd10 100644 --- a/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/README_EN.md +++ b/solution/2900-2999/2918.Minimum Equal Sum of Two Arrays After Replacing Zeros/README_EN.md @@ -40,7 +40,7 @@ Both arrays have an equal sum of 12. It can be shown that it is the minimum sum ## Solutions -**Solution 1: Case Analysis** +### Solution 1: Case Analysis We consider the case where we treat all $0$s in the array as $1$s, and calculate the sum of the two arrays separately, denoted as $s_1$ and $s_2$. Without loss of generality, we assume that $s_1 \le s_2$. @@ -51,8 +51,6 @@ The time complexity is $O(n + m)$, where $n$ and $m$ are the lengths of the arra -### **Python3** - ```python class Solution: def minSum(self, nums1: List[int], nums2: List[int]) -> int: @@ -65,8 +63,6 @@ class Solution: return -1 if nums1.count(0) == 0 else s2 ``` -### **Java** - ```java class Solution { public long minSum(int[] nums1, int[] nums2) { @@ -90,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +110,6 @@ public: }; ``` -### **Go** - ```go func minSum(nums1 []int, nums2 []int) int64 { s1, s2 := 0, 0 @@ -144,8 +136,6 @@ func minSum(nums1 []int, nums2 []int) int64 { } ``` -### **TypeScript** - ```ts function minSum(nums1: number[], nums2: number[]): number { let [s1, s2] = [0, 0]; @@ -169,10 +159,6 @@ function minSum(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/README.md b/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/README.md index 4ad4c1acf341c..1aca21110b900 100644 --- a/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/README.md +++ b/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/README.md @@ -73,9 +73,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f$, $g$, $h$ 表示前 $i$ 项中,分别以最后三项作为子数组的最大值所需要的最小增量运算数,初始时 $f = 0$, $g = 0$, $h = 0$。 @@ -95,10 +93,6 @@ $$ -### **Python3** - - - ```python class Solution: def minIncrementOperations(self, nums: List[int], k: int) -> int: @@ -108,10 +102,6 @@ class Solution: return min(f, g, h) ``` -### **Java** - - - ```java class Solution { public long minIncrementOperations(int[] nums, int k) { @@ -127,8 +117,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -145,8 +133,6 @@ public: }; ``` -### **Go** - ```go func minIncrementOperations(nums []int, k int) int64 { var f, g, h int @@ -157,8 +143,6 @@ func minIncrementOperations(nums []int, k int) int64 { } ``` -### **TypeScript** - ```ts function minIncrementOperations(nums: number[], k: number): number { let [f, g, h] = [0, 0, 0]; @@ -169,10 +153,6 @@ function minIncrementOperations(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/README_EN.md b/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/README_EN.md index 6c7794f9400b1..d448632f4a071 100644 --- a/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/README_EN.md +++ b/solution/2900-2999/2919.Minimum Increment Operations to Make Array Beautiful/README_EN.md @@ -69,7 +69,7 @@ Hence, the answer is 0. ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f$, $g$, and $h$ as the minimum number of increment operations needed to get the maximum value from the last three items in the first $i$ items, initially $f = 0$, $g = 0$, $h = 0$. @@ -89,8 +89,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def minIncrementOperations(self, nums: List[int], k: int) -> int: @@ -100,8 +98,6 @@ class Solution: return min(f, g, h) ``` -### **Java** - ```java class Solution { public long minIncrementOperations(int[] nums, int k) { @@ -117,8 +113,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -135,8 +129,6 @@ public: }; ``` -### **Go** - ```go func minIncrementOperations(nums []int, k int) int64 { var f, g, h int @@ -147,8 +139,6 @@ func minIncrementOperations(nums []int, k int) int64 { } ``` -### **TypeScript** - ```ts function minIncrementOperations(nums: number[], k: number): number { let [f, g, h] = [0, 0, 0]; @@ -159,10 +149,6 @@ function minIncrementOperations(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2920.Maximum Points After Collecting Coins From All Nodes/README.md b/solution/2900-2999/2920.Maximum Points After Collecting Coins From All Nodes/README.md index 72965be7450c5..55a7a658072ac 100644 --- a/solution/2900-2999/2920.Maximum Points After Collecting Coins From All Nodes/README.md +++ b/solution/2900-2999/2920.Maximum Points After Collecting Coins From All Nodes/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们先根据题目给定的边构建图 $g$,其中 $g[i]$ 表示节点 $i$ 的所有邻接节点。然后我们可以使用记忆化搜索的方法求解本题。 @@ -81,10 +79,6 @@ -### **Python3** - - - ```python class Solution: def maximumPoints(self, edges: List[List[int]], coins: List[int], k: int) -> int: @@ -109,10 +103,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int k; @@ -154,8 +144,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -190,8 +178,6 @@ public: }; ``` -### **Go** - ```go func maximumPoints(edges [][]int, coins []int, k int) int { n := len(coins) @@ -230,8 +216,6 @@ func maximumPoints(edges [][]int, coins []int, k int) int { } ``` -### **TypeScript** - ```ts function maximumPoints(edges: number[][], coins: number[], k: number): number { const n = coins.length; @@ -261,10 +245,6 @@ function maximumPoints(edges: number[][], coins: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2920.Maximum Points After Collecting Coins From All Nodes/README_EN.md b/solution/2900-2999/2920.Maximum Points After Collecting Coins From All Nodes/README_EN.md index 4490c9c61f555..88229a61bbfc3 100644 --- a/solution/2900-2999/2920.Maximum Points After Collecting Coins From All Nodes/README_EN.md +++ b/solution/2900-2999/2920.Maximum Points After Collecting Coins From All Nodes/README_EN.md @@ -55,7 +55,7 @@ Coins will be collected from all the nodes using the first way. Therefore, total ## Solutions -**Solution 1: Memoization Search** +### Solution 1: Memoization Search First, we construct a graph $g$ based on the edges given in the problem, where $g[i]$ represents all adjacent nodes of node $i$. Then we can use the method of memoization search to solve this problem. @@ -75,8 +75,6 @@ The time complexity is $O(n \times \log M)$, and the space complexity is $O(n \t -### **Python3** - ```python class Solution: def maximumPoints(self, edges: List[List[int]], coins: List[int], k: int) -> int: @@ -101,8 +99,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int k; @@ -144,8 +140,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -180,8 +174,6 @@ public: }; ``` -### **Go** - ```go func maximumPoints(edges [][]int, coins []int, k int) int { n := len(coins) @@ -220,8 +212,6 @@ func maximumPoints(edges [][]int, coins []int, k int) int { } ``` -### **TypeScript** - ```ts function maximumPoints(edges: number[][], coins: number[], k: number): number { const n = coins.length; @@ -251,10 +241,6 @@ function maximumPoints(edges: number[][], coins: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/README.md b/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/README.md index cc6dec52b4e0d..b19627c855fab 100644 --- a/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/README.md +++ b/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:树状数组** +### 方法一:树状数组 我们可以用两个树状数组分别维护每个价格左边以及右边的最大利润,然后枚举中间的价格,通过树状数组查询左右两边的最大利润,最后取最大值即可。 @@ -68,10 +66,6 @@ -### **Python3** - - - ```python class BinaryIndexedTree: def __init__(self, n: int): @@ -114,10 +108,6 @@ class Solution: ) ``` -### **Java** - - - ```java class BinaryIndexedTree { private int n; @@ -177,8 +167,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { private: @@ -238,8 +226,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -299,8 +285,6 @@ func maxProfit(prices []int, profits []int) int { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -361,8 +345,6 @@ function maxProfit(prices: number[], profits: number[]): number { } ``` -### **Rust** - ```rust struct BinaryIndexedTree { n: usize, @@ -430,10 +412,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/README_EN.md b/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/README_EN.md index 6e96b7e8f2561..32742a309b527 100644 --- a/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/README_EN.md +++ b/solution/2900-2999/2921.Maximum Profitable Triplets With Increasing Prices II/README_EN.md @@ -54,7 +54,7 @@ The answer would be sum of their profits which is 5 + 4 + 6 = 15. ## Solutions -**Solution 1: Binary Indexed Tree** +### Solution 1: Binary Indexed Tree We can use two Binary Indexed Trees (BITs) to maintain the maximum profit on the left and right of each price, respectively. Then, we enumerate the middle price, query the maximum profit on both sides through the BIT, and finally take the maximum value. @@ -62,8 +62,6 @@ The time complexity is $O(n \times \log M)$, and the space complexity is $O(M)$. -### **Python3** - ```python class BinaryIndexedTree: def __init__(self, n: int): @@ -106,8 +104,6 @@ class Solution: ) ``` -### **Java** - ```java class BinaryIndexedTree { private int n; @@ -167,8 +163,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { private: @@ -228,8 +222,6 @@ public: }; ``` -### **Go** - ```go type BinaryIndexedTree struct { n int @@ -289,8 +281,6 @@ func maxProfit(prices []int, profits []int) int { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -351,8 +341,6 @@ function maxProfit(prices: number[], profits: number[]): number { } ``` -### **Rust** - ```rust struct BinaryIndexedTree { n: usize, @@ -420,10 +408,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2922.Market Analysis III/README.md b/solution/2900-2999/2922.Market Analysis III/README.md index 7b7f4f1f1ee2d..a9590cce65761 100644 --- a/solution/2900-2999/2922.Market Analysis III/README.md +++ b/solution/2900-2999/2922.Market Analysis III/README.md @@ -102,18 +102,12 @@ Items table: ## 解法 - - -**方法一:等值连接 + 分组 + 子查询** +### 方法一:等值连接 + 分组 + 子查询 我们可以使用等值连接,将 `Orders` 表和 `Users` 表按照 `seller_id` 进行连接,接着再按照 `item_id` 连接 `Items`,筛选出 `item_brand` 不等于 `favorite_brand` 的记录,然后按照 `seller_id` 进行分组,统计每个 `seller_id` 对应的 `item_id` 的个数,最后再使用子查询,找出 `item_id` 个数最多的 `seller_id`。 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -133,3 +127,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2900-2999/2922.Market Analysis III/README_EN.md b/solution/2900-2999/2922.Market Analysis III/README_EN.md index dea45cebfbf88..25414941abb70 100644 --- a/solution/2900-2999/2922.Market Analysis III/README_EN.md +++ b/solution/2900-2999/2922.Market Analysis III/README_EN.md @@ -98,14 +98,12 @@ Since seller_ids 2 and 3 have the same count of one item each, they both will be ## Solutions -**Solution 1: Equijoin + Grouping + Subquery** +### Solution 1: Equijoin + Grouping + Subquery We can use equijoin to connect the `Orders` table and the `Users` table according to `seller_id`, then connect `Items` according to `item_id`, and filter out the records where `item_brand` is not equal to `favorite_brand`. Then, group by `seller_id` and count the number of `item_id` corresponding to each `seller_id`. Finally, use a subquery to find the `seller_id` with the most `item_id`. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -125,3 +123,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2900-2999/2923.Find Champion I/README.md b/solution/2900-2999/2923.Find Champion I/README.md index d855a04f77829..a54f8487f2547 100644 --- a/solution/2900-2999/2923.Find Champion I/README.md +++ b/solution/2900-2999/2923.Find Champion I/README.md @@ -52,9 +52,7 @@ grid[1][2] == 1 表示 1 队比 2 队强。 ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举每一支队伍 $i$,如果 $i$ 队的每一场比赛都赢了,那么 $i$ 队就是冠军,直接返回 $i$ 即可。 @@ -62,10 +60,6 @@ grid[1][2] == 1 表示 1 队比 2 队强。 -### **Python3** - - - ```python class Solution: def findChampion(self, grid: List[List[int]]) -> int: @@ -74,10 +68,6 @@ class Solution: return i ``` -### **Java** - - - ```java class Solution { public int findChampion(int[][] grid) { @@ -97,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -119,8 +107,6 @@ public: }; ``` -### **Go** - ```go func findChampion(grid [][]int) int { n := len(grid) @@ -138,8 +124,6 @@ func findChampion(grid [][]int) int { } ``` -### **TypeScript** - ```ts function findChampion(grid: number[][]): number { for (let i = 0, n = grid.length; ; ++i) { @@ -156,10 +140,6 @@ function findChampion(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2923.Find Champion I/README_EN.md b/solution/2900-2999/2923.Find Champion I/README_EN.md index e8c259f8da96c..a30a3df62e4fd 100644 --- a/solution/2900-2999/2923.Find Champion I/README_EN.md +++ b/solution/2900-2999/2923.Find Champion I/README_EN.md @@ -48,7 +48,7 @@ So team 1 will be the champion. ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We can enumerate each team $i$. If team $i$ has won every match, then team $i$ is the champion, and we can directly return $i$. @@ -56,8 +56,6 @@ The time complexity is $O(n^2)$, where $n$ is the number of teams. The space com -### **Python3** - ```python class Solution: def findChampion(self, grid: List[List[int]]) -> int: @@ -66,8 +64,6 @@ class Solution: return i ``` -### **Java** - ```java class Solution { public int findChampion(int[][] grid) { @@ -87,8 +83,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -109,8 +103,6 @@ public: }; ``` -### **Go** - ```go func findChampion(grid [][]int) int { n := len(grid) @@ -128,8 +120,6 @@ func findChampion(grid [][]int) int { } ``` -### **TypeScript** - ```ts function findChampion(grid: number[][]): number { for (let i = 0, n = grid.length; ; ++i) { @@ -146,10 +136,6 @@ function findChampion(grid: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2924.Find Champion II/README.md b/solution/2900-2999/2924.Find Champion II/README.md index d7d8bad61d408..44d10d4eca989 100644 --- a/solution/2900-2999/2924.Find Champion II/README.md +++ b/solution/2900-2999/2924.Find Champion II/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:统计入度** +### 方法一:统计入度 根据题目描述,我们只需要统计每个节点的入度,记录在数组 $indeg$ 中。如果只有一个节点的入度为 $0$,那么这个节点就是冠军,否则不存在唯一的冠军。 @@ -72,10 +70,6 @@ -### **Python3** - - - ```python class Solution: def findChampion(self, n: int, edges: List[List[int]]) -> int: @@ -85,10 +79,6 @@ class Solution: return -1 if indeg.count(0) != 1 else indeg.index(0) ``` -### **Java** - - - ```java class Solution { public int findChampion(int n, int[][] edges) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +119,6 @@ public: }; ``` -### **Go** - ```go func findChampion(n int, edges [][]int) int { indeg := make([]int, n) @@ -153,8 +139,6 @@ func findChampion(n int, edges [][]int) int { } ``` -### **TypeScript** - ```ts function findChampion(n: number, edges: number[][]): number { const indeg: number[] = Array(n).fill(0); @@ -172,10 +156,6 @@ function findChampion(n: number, edges: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2924.Find Champion II/README_EN.md b/solution/2900-2999/2924.Find Champion II/README_EN.md index cdf48a9de09db..981b42063e998 100644 --- a/solution/2900-2999/2924.Find Champion II/README_EN.md +++ b/solution/2900-2999/2924.Find Champion II/README_EN.md @@ -58,7 +58,7 @@ ## Solutions -**Solution 1: Counting In-degrees** +### Solution 1: Counting In-degrees Based on the problem description, we only need to count the in-degrees of each node and record them in an array $indeg$. If only one node has an in-degree of $0$, then this node is the champion; otherwise, there is no unique champion. @@ -66,8 +66,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def findChampion(self, n: int, edges: List[List[int]]) -> int: @@ -77,8 +75,6 @@ class Solution: return -1 if indeg.count(0) != 1 else indeg.index(0) ``` -### **Java** - ```java class Solution { public int findChampion(int n, int[][] edges) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +115,6 @@ public: }; ``` -### **Go** - ```go func findChampion(n int, edges [][]int) int { indeg := make([]int, n) @@ -143,8 +135,6 @@ func findChampion(n int, edges [][]int) int { } ``` -### **TypeScript** - ```ts function findChampion(n: number, edges: number[][]): number { const indeg: number[] = Array(n).fill(0); @@ -162,10 +152,6 @@ function findChampion(n: number, edges: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/README.md b/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/README.md index 744b595848a29..c8553ba59591c 100644 --- a/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/README.md +++ b/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:树形 DP** +### 方法一:树形 DP 题目实际上是让我们从树的所有节点中选出一些节点,使得这些节点的值之和最大,并且每条从根节点到叶子节点的路径上都有一个点没有被选中。 @@ -87,10 +85,6 @@ -### **Python3** - - - ```python class Solution: def maximumScoreAfterOperations( @@ -116,10 +110,6 @@ class Solution: return dfs(0)[1] ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -157,8 +147,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -193,8 +181,6 @@ public: }; ``` -### **Go** - ```go func maximumScoreAfterOperations(edges [][]int, values []int) int64 { g := make([][]int, len(values)) @@ -225,8 +211,6 @@ func maximumScoreAfterOperations(edges [][]int, values []int) int64 { } ``` -### **TypeScript** - ```ts function maximumScoreAfterOperations(edges: number[][], values: number[]): number { const g: number[][] = Array.from({ length: values.length }, () => []); @@ -254,10 +238,6 @@ function maximumScoreAfterOperations(edges: number[][], values: number[]): numbe } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/README_EN.md b/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/README_EN.md index 5039c19d821f6..1356643a79e1e 100644 --- a/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/README_EN.md +++ b/solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/README_EN.md @@ -59,7 +59,7 @@ It can be shown that 40 is the maximum score obtainable after any number of oper ## Solutions -**Solution 1: Tree DP** +### Solution 1: Tree DP The problem is actually asking us to select some nodes from all nodes of the tree so that the sum of these nodes' values is maximized, and there is one node on each path from the root node to the leaf node that is not selected. @@ -77,8 +77,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maximumScoreAfterOperations( @@ -104,8 +102,6 @@ class Solution: return dfs(0)[1] ``` -### **Java** - ```java class Solution { private List[] g; @@ -143,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -179,8 +173,6 @@ public: }; ``` -### **Go** - ```go func maximumScoreAfterOperations(edges [][]int, values []int) int64 { g := make([][]int, len(values)) @@ -211,8 +203,6 @@ func maximumScoreAfterOperations(edges [][]int, values []int) int64 { } ``` -### **TypeScript** - ```ts function maximumScoreAfterOperations(edges: number[][], values: number[]): number { const g: number[][] = Array.from({ length: values.length }, () => []); @@ -240,10 +230,6 @@ function maximumScoreAfterOperations(edges: number[][], values: number[]): numbe } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/README.md b/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/README.md index 510da5c7b509b..1d4d1e9b9bb97 100644 --- a/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/README.md +++ b/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/README.md @@ -65,9 +65,7 @@ nums[3] - nums[0] >= 3 - 0 。 ## 解法 - - -**方法一:动态规划 + 树状数组** +### 方法一:动态规划 + 树状数组 根据题目描述,我们可以将不等式 $nums[i] - nums[j] \ge i - j$ 转化为 $nums[i] - i \ge nums[j] - j$,因此,我们考虑定义一个新数组 $arr$,其中 $arr[i] = nums[i] - i$,那么平衡子序列满足对于任意 $j \lt i$,都有 $arr[j] \le arr[i]$。即题目转换为求在 $arr$ 中选出一个递增子序列,使得对应的 $nums$ 的和最大。 @@ -89,10 +87,6 @@ $$ -### **Python3** - - - ```python class BinaryIndexedTree: def __init__(self, n: int): @@ -124,10 +118,6 @@ class Solution: return tree.query(len(s)) ``` -### **Java** - - - ```java class BinaryIndexedTree { private int n; @@ -195,8 +185,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { private: @@ -249,8 +237,6 @@ public: }; ``` -### **Go** - ```go const inf int = 1e18 @@ -308,8 +294,6 @@ func maxBalancedSubsequenceSum(nums []int) int64 { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -373,10 +357,6 @@ function maxBalancedSubsequenceSum(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/README_EN.md b/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/README_EN.md index 7aef6a37e364c..cfea600f0343a 100644 --- a/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/README_EN.md +++ b/solution/2900-2999/2926.Maximum Balanced Subsequence Sum/README_EN.md @@ -61,7 +61,7 @@ It is a balanced subsequence, and its sum is the maximum among the balanced subs ## Solutions -**Solution 1: Dynamic Programming + Binary Indexed Tree** +### Solution 1: Dynamic Programming + Binary Indexed Tree According to the problem description, we can transform the inequality $nums[i] - nums[j] \ge i - j$ into $nums[i] - i \ge nums[j] - j$. Therefore, we consider defining a new array $arr$, where $arr[i] = nums[i] - i$. A balanced subsequence satisfies that for any $j < i$, $arr[j] \le arr[i]$. The problem is transformed into selecting an increasing subsequence in $arr$ such that the corresponding sum in $nums$ is maximized. @@ -83,8 +83,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class BinaryIndexedTree: def __init__(self, n: int): @@ -116,8 +114,6 @@ class Solution: return tree.query(len(s)) ``` -### **Java** - ```java class BinaryIndexedTree { private int n; @@ -185,8 +181,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { private: @@ -239,8 +233,6 @@ public: }; ``` -### **Go** - ```go const inf int = 1e18 @@ -298,8 +290,6 @@ func maxBalancedSubsequenceSum(nums []int) int64 { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -363,10 +353,6 @@ function maxBalancedSubsequenceSum(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2927.Distribute Candies Among Children III/README.md b/solution/2900-2999/2927.Distribute Candies Among Children III/README.md index dbfa88743504a..6c778fbbcf54b 100644 --- a/solution/2900-2999/2927.Distribute Candies Among Children III/README.md +++ b/solution/2900-2999/2927.Distribute Candies Among Children III/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:组合数学 + 容斥原理** +### 方法一:组合数学 + 容斥原理 根据题目描述,我们需要将 $n$ 个糖果分给 $3$ 个小孩,每个小孩分到的糖果数在 $[0, limit]$ 之间。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def distributeCandies(self, n: int, limit: int) -> int: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long distributeCandies(int n, int limit) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func distributeCandies(n int, limit int) int64 { comb2 := func(n int) int { @@ -141,8 +127,6 @@ func distributeCandies(n int, limit int) int64 { } ``` -### **TypeScript** - ```ts function distributeCandies(n: number, limit: number): number { const comb2 = (n: number) => (n * (n - 1)) / 2; @@ -160,10 +144,6 @@ function distributeCandies(n: number, limit: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2927.Distribute Candies Among Children III/README_EN.md b/solution/2900-2999/2927.Distribute Candies Among Children III/README_EN.md index c79f90240ad38..78c3e3c32228e 100644 --- a/solution/2900-2999/2927.Distribute Candies Among Children III/README_EN.md +++ b/solution/2900-2999/2927.Distribute Candies Among Children III/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Combinatorial Mathematics + Principle of Inclusion-Exclusion** +### Solution 1: Combinatorial Mathematics + Principle of Inclusion-Exclusion According to the problem description, we need to distribute $n$ candies to $3$ children, with each child receiving between $[0, limit]$ candies. @@ -47,8 +47,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def distributeCandies(self, n: int, limit: int) -> int: @@ -62,8 +60,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long distributeCandies(int n, int limit) { @@ -86,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func distributeCandies(n int, limit int) int64 { comb2 := func(n int) int { @@ -131,8 +123,6 @@ func distributeCandies(n int, limit int) int64 { } ``` -### **TypeScript** - ```ts function distributeCandies(n: number, limit: number): number { const comb2 = (n: number) => (n * (n - 1)) / 2; @@ -150,10 +140,6 @@ function distributeCandies(n: number, limit: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2928.Distribute Candies Among Children I/README.md b/solution/2900-2999/2928.Distribute Candies Among Children I/README.md index 7721c98560d4e..0edb43ba9a9d6 100644 --- a/solution/2900-2999/2928.Distribute Candies Among Children I/README.md +++ b/solution/2900-2999/2928.Distribute Candies Among Children I/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:组合数学 + 容斥原理** +### 方法一:组合数学 + 容斥原理 根据题目描述,我们需要将 $n$ 个糖果分给 $3$ 个小孩,每个小孩分到的糖果数在 $[0, limit]$ 之间。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def distributeCandies(self, n: int, limit: int) -> int: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int distributeCandies(int n, int limit) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func distributeCandies(n int, limit int) int { comb2 := func(n int) int { @@ -141,8 +127,6 @@ func distributeCandies(n int, limit int) int { } ``` -### **TypeScript** - ```ts function distributeCandies(n: number, limit: number): number { const comb2 = (n: number) => (n * (n - 1)) / 2; @@ -160,10 +144,6 @@ function distributeCandies(n: number, limit: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2928.Distribute Candies Among Children I/README_EN.md b/solution/2900-2999/2928.Distribute Candies Among Children I/README_EN.md index c17c8a685f696..511ef54de348d 100644 --- a/solution/2900-2999/2928.Distribute Candies Among Children I/README_EN.md +++ b/solution/2900-2999/2928.Distribute Candies Among Children I/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Combinatorial Mathematics + Principle of Inclusion-Exclusion** +### Solution 1: Combinatorial Mathematics + Principle of Inclusion-Exclusion According to the problem description, we need to distribute $n$ candies to $3$ children, with each child receiving between $[0, limit]$ candies. @@ -47,8 +47,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def distributeCandies(self, n: int, limit: int) -> int: @@ -62,8 +60,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int distributeCandies(int n, int limit) { @@ -86,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func distributeCandies(n int, limit int) int { comb2 := func(n int) int { @@ -131,8 +123,6 @@ func distributeCandies(n int, limit int) int { } ``` -### **TypeScript** - ```ts function distributeCandies(n: number, limit: number): number { const comb2 = (n: number) => (n * (n - 1)) / 2; @@ -150,10 +140,6 @@ function distributeCandies(n: number, limit: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2929.Distribute Candies Among Children II/README.md b/solution/2900-2999/2929.Distribute Candies Among Children II/README.md index 4c63cbdf02fd5..139b3dee7822f 100644 --- a/solution/2900-2999/2929.Distribute Candies Among Children II/README.md +++ b/solution/2900-2999/2929.Distribute Candies Among Children II/README.md @@ -39,9 +39,7 @@ ## 解法 - - -**方法一:组合数学 + 容斥原理** +### 方法一:组合数学 + 容斥原理 根据题目描述,我们需要将 $n$ 个糖果分给 $3$ 个小孩,每个小孩分到的糖果数在 $[0, limit]$ 之间。 @@ -53,10 +51,6 @@ -### **Python3** - - - ```python class Solution: def distributeCandies(self, n: int, limit: int) -> int: @@ -70,10 +64,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long distributeCandies(int n, int limit) { @@ -96,8 +86,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func distributeCandies(n int, limit int) int64 { comb2 := func(n int) int { @@ -141,8 +127,6 @@ func distributeCandies(n int, limit int) int64 { } ``` -### **TypeScript** - ```ts function distributeCandies(n: number, limit: number): number { const comb2 = (n: number) => (n * (n - 1)) / 2; @@ -160,10 +144,6 @@ function distributeCandies(n: number, limit: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2929.Distribute Candies Among Children II/README_EN.md b/solution/2900-2999/2929.Distribute Candies Among Children II/README_EN.md index 3afb9147b88ee..572c537daef22 100644 --- a/solution/2900-2999/2929.Distribute Candies Among Children II/README_EN.md +++ b/solution/2900-2999/2929.Distribute Candies Among Children II/README_EN.md @@ -35,7 +35,7 @@ ## Solutions -**Solution 1: Combinatorial Mathematics + Principle of Inclusion-Exclusion** +### Solution 1: Combinatorial Mathematics + Principle of Inclusion-Exclusion According to the problem description, we need to distribute $n$ candies to $3$ children, with each child receiving between $[0, limit]$ candies. @@ -47,8 +47,6 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def distributeCandies(self, n: int, limit: int) -> int: @@ -62,8 +60,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long distributeCandies(int n, int limit) { @@ -86,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func distributeCandies(n int, limit int) int64 { comb2 := func(n int) int { @@ -131,8 +123,6 @@ func distributeCandies(n int, limit int) int64 { } ``` -### **TypeScript** - ```ts function distributeCandies(n: number, limit: number): number { const comb2 = (n: number) => (n * (n - 1)) / 2; @@ -150,10 +140,6 @@ function distributeCandies(n: number, limit: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/README.md b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/README.md index fd313967385b4..192e5febfd7ff 100644 --- a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/README.md +++ b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们设计一个函数 $dfs(i, l, e, t)$,表示当前剩余字符串长度为 $i$,且已至少有 $l$ 个字符 `'l'`, $e$ 个字符 `'e'` 和 $t$ 个字符 `'t'`,构成的字符串是一个好字符串的方案数。那么答案为 $dfs(n, 0, 0, 0)$。 @@ -69,32 +67,8 @@ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串长度。 -**方法二:逆向思维 + 容斥原理** - -我们可以考虑逆向思维,即计算不包含子字符串 `"leet"` 的字符串数目,然后用总数减去该数目即可。 - -我们分成以下几种情况: - -- 情况 $a$:表示字符串中不包含字符 `'l'` 的方案数,那么有 $a = 25^n$。 -- 情况 $b$:与 $a$ 类似,表示字符串中不包含字符 `'t'` 的方案数,那么有 $b = 25^n$。 -- 情况 $c$:表示字符串中不包含字符 `'e'` 或者只包含一个字符 `'e'` 的方案数,那么有 $c = 25^n + n \times 25^{n - 1}$。 -- 情况 $ab$:表示字符串中不包含字符 `'l'` 和 `'t'` 的方案数,那么有 $ab = 24^n$。 -- 情况 $ac$:表示字符串中不包含字符 `'l'` 和 `'e'` 或者只包含一个字符 `'e'` 的方案数,那么有 $ac = 24^n + n \times 24^{n - 1}$。 -- 情况 $bc$:与 $ac$ 类似,表示字符串中不包含字符 `'t'` 和 `'e'` 或者只包含一个字符 `'e'` 的方案数,那么有 $bc = 24^n + n \times 24^{n - 1}$。 -- 情况 $abc$:表示字符串中不包含字符 `'l'`、`'t'` 和 `'e'` 或者只包含一个字符 `'e'` 的方案数,那么有 $abc = 23^n + n \times 23^{n - 1}$。 - -那么根据容斥原理,可以得到 $a + b + c - ab - ac - bc + abc$,就是不包含子字符串 `"leet"` 的字符串数目。 - -而总数 $tot = 26^n$,所以答案为 $tot - (a + b + c - ab - ac - bc + abc)$,注意要对 $10^9 + 7$ 取模。 - -时间复杂度 $O(\log n)$,其中 $n$ 为字符串长度。空间复杂度 $O(1)$。 - -### **Python3** - - - ```python class Solution: def stringCount(self, n: int) -> int: @@ -112,23 +86,6 @@ class Solution: return dfs(n, 0, 0, 0) ``` -```python -class Solution: - def stringCount(self, n: int) -> int: - mod = 10**9 + 7 - a = b = pow(25, n, mod) - c = pow(25, n, mod) + n * pow(25, n - 1, mod) - ab = pow(24, n, mod) - ac = bc = (pow(24, n, mod) + n * pow(24, n - 1, mod)) % mod - abc = (pow(23, n, mod) + n * pow(23, n - 1, mod)) % mod - tot = pow(26, n, mod) - return (tot - (a + b + c - ab - ac - bc + abc)) % mod -``` - -### **Java** - - - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -155,37 +112,6 @@ class Solution { } ``` -```java -class Solution { - private final int mod = (int) 1e9 + 7; - - public int stringCount(int n) { - long a = qpow(25, n); - long b = a; - long c = (qpow(25, n) + n * qpow(25, n - 1) % mod) % mod; - long ab = qpow(24, n); - long ac = (qpow(24, n) + n * qpow(24, n - 1) % mod) % mod; - long bc = ac; - long abc = (qpow(23, n) + n * qpow(23, n - 1) % mod) % mod; - long tot = qpow(26, n); - return (int) ((tot - (a + b + c - ab - ac - bc + abc)) % mod + mod) % mod; - } - - private long qpow(long a, int n) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -212,37 +138,6 @@ public: }; ``` -```cpp -class Solution { -public: - int stringCount(int n) { - const int mod = 1e9 + 7; - using ll = long long; - auto qpow = [&](ll a, int n) { - ll ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - }; - ll a = qpow(25, n); - ll b = a; - ll c = (qpow(25, n) + n * qpow(25, n - 1) % mod) % mod; - ll ab = qpow(24, n); - ll ac = (qpow(24, n) + n * qpow(24, n - 1) % mod) % mod; - ll bc = ac; - ll abc = (qpow(23, n) + n * qpow(23, n - 1) % mod) % mod; - ll tot = qpow(26, n); - return ((tot - (a + b + c - ab - ac - bc + abc)) % mod + mod) % mod; - } -}; -``` - -### **Go** - ```go func stringCount(n int) int { const mod int = 1e9 + 7 @@ -277,33 +172,6 @@ func stringCount(n int) int { } ``` -```go -func stringCount(n int) int { - const mod int = 1e9 + 7 - qpow := func(a, n int) int { - ans := 1 - for ; n > 0; n >>= 1 { - if n&1 == 1 { - ans = ans * a % mod - } - a = a * a % mod - } - return ans - } - a := qpow(25, n) - b := a - c := qpow(25, n) + n*qpow(25, n-1) - ab := qpow(24, n) - ac := (qpow(24, n) + n*qpow(24, n-1)) % mod - bc := ac - abc := (qpow(23, n) + n*qpow(23, n-1)) % mod - tot := qpow(26, n) - return ((tot-(a+b+c-ab-ac-bc+abc))%mod + mod) % mod -} -``` - -### **TypeScript** - ```ts function stringCount(n: number): number { const mod = 10 ** 9 + 7; @@ -329,6 +197,126 @@ function stringCount(n: number): number { } ``` + + +### 方法二:逆向思维 + 容斥原理 + +我们可以考虑逆向思维,即计算不包含子字符串 `"leet"` 的字符串数目,然后用总数减去该数目即可。 + +我们分成以下几种情况: + +- 情况 $a$:表示字符串中不包含字符 `'l'` 的方案数,那么有 $a = 25^n$。 +- 情况 $b$:与 $a$ 类似,表示字符串中不包含字符 `'t'` 的方案数,那么有 $b = 25^n$。 +- 情况 $c$:表示字符串中不包含字符 `'e'` 或者只包含一个字符 `'e'` 的方案数,那么有 $c = 25^n + n \times 25^{n - 1}$。 +- 情况 $ab$:表示字符串中不包含字符 `'l'` 和 `'t'` 的方案数,那么有 $ab = 24^n$。 +- 情况 $ac$:表示字符串中不包含字符 `'l'` 和 `'e'` 或者只包含一个字符 `'e'` 的方案数,那么有 $ac = 24^n + n \times 24^{n - 1}$。 +- 情况 $bc$:与 $ac$ 类似,表示字符串中不包含字符 `'t'` 和 `'e'` 或者只包含一个字符 `'e'` 的方案数,那么有 $bc = 24^n + n \times 24^{n - 1}$。 +- 情况 $abc$:表示字符串中不包含字符 `'l'`、`'t'` 和 `'e'` 或者只包含一个字符 `'e'` 的方案数,那么有 $abc = 23^n + n \times 23^{n - 1}$。 + +那么根据容斥原理,可以得到 $a + b + c - ab - ac - bc + abc$,就是不包含子字符串 `"leet"` 的字符串数目。 + +而总数 $tot = 26^n$,所以答案为 $tot - (a + b + c - ab - ac - bc + abc)$,注意要对 $10^9 + 7$ 取模。 + +时间复杂度 $O(\log n)$,其中 $n$ 为字符串长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def stringCount(self, n: int) -> int: + mod = 10**9 + 7 + a = b = pow(25, n, mod) + c = pow(25, n, mod) + n * pow(25, n - 1, mod) + ab = pow(24, n, mod) + ac = bc = (pow(24, n, mod) + n * pow(24, n - 1, mod)) % mod + abc = (pow(23, n, mod) + n * pow(23, n - 1, mod)) % mod + tot = pow(26, n, mod) + return (tot - (a + b + c - ab - ac - bc + abc)) % mod +``` + +```java +class Solution { + private final int mod = (int) 1e9 + 7; + + public int stringCount(int n) { + long a = qpow(25, n); + long b = a; + long c = (qpow(25, n) + n * qpow(25, n - 1) % mod) % mod; + long ab = qpow(24, n); + long ac = (qpow(24, n) + n * qpow(24, n - 1) % mod) % mod; + long bc = ac; + long abc = (qpow(23, n) + n * qpow(23, n - 1) % mod) % mod; + long tot = qpow(26, n); + return (int) ((tot - (a + b + c - ab - ac - bc + abc)) % mod + mod) % mod; + } + + private long qpow(long a, int n) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int stringCount(int n) { + const int mod = 1e9 + 7; + using ll = long long; + auto qpow = [&](ll a, int n) { + ll ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + }; + ll a = qpow(25, n); + ll b = a; + ll c = (qpow(25, n) + n * qpow(25, n - 1) % mod) % mod; + ll ab = qpow(24, n); + ll ac = (qpow(24, n) + n * qpow(24, n - 1) % mod) % mod; + ll bc = ac; + ll abc = (qpow(23, n) + n * qpow(23, n - 1) % mod) % mod; + ll tot = qpow(26, n); + return ((tot - (a + b + c - ab - ac - bc + abc)) % mod + mod) % mod; + } +}; +``` + +```go +func stringCount(n int) int { + const mod int = 1e9 + 7 + qpow := func(a, n int) int { + ans := 1 + for ; n > 0; n >>= 1 { + if n&1 == 1 { + ans = ans * a % mod + } + a = a * a % mod + } + return ans + } + a := qpow(25, n) + b := a + c := qpow(25, n) + n*qpow(25, n-1) + ab := qpow(24, n) + ac := (qpow(24, n) + n*qpow(24, n-1)) % mod + bc := ac + abc := (qpow(23, n) + n*qpow(23, n-1)) % mod + tot := qpow(26, n) + return ((tot-(a+b+c-ab-ac-bc+abc))%mod + mod) % mod +} +``` + ```ts function stringCount(n: number): number { const mod = BigInt(10 ** 9 + 7); @@ -354,10 +342,6 @@ function stringCount(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/README_EN.md b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/README_EN.md index c484ff3b672e4..5d19a7a1280e4 100644 --- a/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/README_EN.md +++ b/solution/2900-2999/2930.Number of Strings Which Can Be Rearranged to Contain Substring/README_EN.md @@ -49,7 +49,7 @@ ## Solutions -**Solution 1: Memorization Search** +### Solution 1: Memorization Search We design a function $dfs(i, l, e, t)$, which represents the number of good strings that can be formed when the remaining string length is $i$, and there are at least $l$ characters 'l', $e$ characters 'e' and $t$ characters 't'. The answer is $dfs(n, 0, 0, 0)$. @@ -65,30 +65,8 @@ To avoid repeated calculations, we can use memorization search. The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string. -**Solution 2: Reverse Thinking + Inclusion-Exclusion Principle** - -We can consider reverse thinking, that is, calculate the number of strings that do not contain the substring "leet", and then subtract this number from the total. - -We divide it into the following cases: - -- Case $a$: represents the number of schemes where the string does not contain the character 'l', so we have $a = 25^n$. -- Case $b$: similar to $a$, represents the number of schemes where the string does not contain the character 't', so we have $b = 25^n$. -- Case $c$: represents the number of schemes where the string does not contain the character 'e' or only contains one character 'e', so we have $c = 25^n + n \times 25^{n - 1}$. -- Case $ab$: represents the number of schemes where the string does not contain the characters 'l' and 't', so we have $ab = 24^n$. -- Case $ac$: represents the number of schemes where the string does not contain the characters 'l' and 'e' or only contains one character 'e', so we have $ac = 24^n + n \times 24^{n - 1}$. -- Case $bc$: similar to $ac$, represents the number of schemes where the string does not contain the characters 't' and 'e' or only contains one character 'e', so we have $bc = 24^n + n \times 24^{n - 1}$. -- Case $abc$: represents the number of schemes where the string does not contain the characters 'l', 't' and 'e' or only contains one character 'e', so we have $abc = 23^n + n \times 23^{n - 1}$. - -Then according to the inclusion-exclusion principle, $a + b + c - ab - ac - bc + abc$ is the number of strings that do not contain the substring "leet". - -The total number $tot = 26^n$, so the answer is $tot - (a + b + c - ab - ac - bc + abc)$, remember to take the modulus of $10^9 + 7$. - -The time complexity is $O(\log n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string. - -### **Python3** - ```python class Solution: def stringCount(self, n: int) -> int: @@ -106,21 +84,6 @@ class Solution: return dfs(n, 0, 0, 0) ``` -```python -class Solution: - def stringCount(self, n: int) -> int: - mod = 10**9 + 7 - a = b = pow(25, n, mod) - c = pow(25, n, mod) + n * pow(25, n - 1, mod) - ab = pow(24, n, mod) - ac = bc = (pow(24, n, mod) + n * pow(24, n - 1, mod)) % mod - abc = (pow(23, n, mod) + n * pow(23, n - 1, mod)) % mod - tot = pow(26, n, mod) - return (tot - (a + b + c - ab - ac - bc + abc)) % mod -``` - -### **Java** - ```java class Solution { private final int mod = (int) 1e9 + 7; @@ -147,37 +110,6 @@ class Solution { } ``` -```java -class Solution { - private final int mod = (int) 1e9 + 7; - - public int stringCount(int n) { - long a = qpow(25, n); - long b = a; - long c = (qpow(25, n) + n * qpow(25, n - 1) % mod) % mod; - long ab = qpow(24, n); - long ac = (qpow(24, n) + n * qpow(24, n - 1) % mod) % mod; - long bc = ac; - long abc = (qpow(23, n) + n * qpow(23, n - 1) % mod) % mod; - long tot = qpow(26, n); - return (int) ((tot - (a + b + c - ab - ac - bc + abc)) % mod + mod) % mod; - } - - private long qpow(long a, int n) { - long ans = 1; - for (; n > 0; n >>= 1) { - if ((n & 1) == 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -204,37 +136,6 @@ public: }; ``` -```cpp -class Solution { -public: - int stringCount(int n) { - const int mod = 1e9 + 7; - using ll = long long; - auto qpow = [&](ll a, int n) { - ll ans = 1; - for (; n; n >>= 1) { - if (n & 1) { - ans = ans * a % mod; - } - a = a * a % mod; - } - return ans; - }; - ll a = qpow(25, n); - ll b = a; - ll c = (qpow(25, n) + n * qpow(25, n - 1) % mod) % mod; - ll ab = qpow(24, n); - ll ac = (qpow(24, n) + n * qpow(24, n - 1) % mod) % mod; - ll bc = ac; - ll abc = (qpow(23, n) + n * qpow(23, n - 1) % mod) % mod; - ll tot = qpow(26, n); - return ((tot - (a + b + c - ab - ac - bc + abc)) % mod + mod) % mod; - } -}; -``` - -### **Go** - ```go func stringCount(n int) int { const mod int = 1e9 + 7 @@ -269,33 +170,6 @@ func stringCount(n int) int { } ``` -```go -func stringCount(n int) int { - const mod int = 1e9 + 7 - qpow := func(a, n int) int { - ans := 1 - for ; n > 0; n >>= 1 { - if n&1 == 1 { - ans = ans * a % mod - } - a = a * a % mod - } - return ans - } - a := qpow(25, n) - b := a - c := qpow(25, n) + n*qpow(25, n-1) - ab := qpow(24, n) - ac := (qpow(24, n) + n*qpow(24, n-1)) % mod - bc := ac - abc := (qpow(23, n) + n*qpow(23, n-1)) % mod - tot := qpow(26, n) - return ((tot-(a+b+c-ab-ac-bc+abc))%mod + mod) % mod -} -``` - -### **TypeScript** - ```ts function stringCount(n: number): number { const mod = 10 ** 9 + 7; @@ -321,6 +195,126 @@ function stringCount(n: number): number { } ``` + + +### Solution 2: Reverse Thinking + Inclusion-Exclusion Principle + +We can consider reverse thinking, that is, calculate the number of strings that do not contain the substring "leet", and then subtract this number from the total. + +We divide it into the following cases: + +- Case $a$: represents the number of schemes where the string does not contain the character 'l', so we have $a = 25^n$. +- Case $b$: similar to $a$, represents the number of schemes where the string does not contain the character 't', so we have $b = 25^n$. +- Case $c$: represents the number of schemes where the string does not contain the character 'e' or only contains one character 'e', so we have $c = 25^n + n \times 25^{n - 1}$. +- Case $ab$: represents the number of schemes where the string does not contain the characters 'l' and 't', so we have $ab = 24^n$. +- Case $ac$: represents the number of schemes where the string does not contain the characters 'l' and 'e' or only contains one character 'e', so we have $ac = 24^n + n \times 24^{n - 1}$. +- Case $bc$: similar to $ac$, represents the number of schemes where the string does not contain the characters 't' and 'e' or only contains one character 'e', so we have $bc = 24^n + n \times 24^{n - 1}$. +- Case $abc$: represents the number of schemes where the string does not contain the characters 'l', 't' and 'e' or only contains one character 'e', so we have $abc = 23^n + n \times 23^{n - 1}$. + +Then according to the inclusion-exclusion principle, $a + b + c - ab - ac - bc + abc$ is the number of strings that do not contain the substring "leet". + +The total number $tot = 26^n$, so the answer is $tot - (a + b + c - ab - ac - bc + abc)$, remember to take the modulus of $10^9 + 7$. + +The time complexity is $O(\log n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string. + + + +```python +class Solution: + def stringCount(self, n: int) -> int: + mod = 10**9 + 7 + a = b = pow(25, n, mod) + c = pow(25, n, mod) + n * pow(25, n - 1, mod) + ab = pow(24, n, mod) + ac = bc = (pow(24, n, mod) + n * pow(24, n - 1, mod)) % mod + abc = (pow(23, n, mod) + n * pow(23, n - 1, mod)) % mod + tot = pow(26, n, mod) + return (tot - (a + b + c - ab - ac - bc + abc)) % mod +``` + +```java +class Solution { + private final int mod = (int) 1e9 + 7; + + public int stringCount(int n) { + long a = qpow(25, n); + long b = a; + long c = (qpow(25, n) + n * qpow(25, n - 1) % mod) % mod; + long ab = qpow(24, n); + long ac = (qpow(24, n) + n * qpow(24, n - 1) % mod) % mod; + long bc = ac; + long abc = (qpow(23, n) + n * qpow(23, n - 1) % mod) % mod; + long tot = qpow(26, n); + return (int) ((tot - (a + b + c - ab - ac - bc + abc)) % mod + mod) % mod; + } + + private long qpow(long a, int n) { + long ans = 1; + for (; n > 0; n >>= 1) { + if ((n & 1) == 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int stringCount(int n) { + const int mod = 1e9 + 7; + using ll = long long; + auto qpow = [&](ll a, int n) { + ll ans = 1; + for (; n; n >>= 1) { + if (n & 1) { + ans = ans * a % mod; + } + a = a * a % mod; + } + return ans; + }; + ll a = qpow(25, n); + ll b = a; + ll c = (qpow(25, n) + n * qpow(25, n - 1) % mod) % mod; + ll ab = qpow(24, n); + ll ac = (qpow(24, n) + n * qpow(24, n - 1) % mod) % mod; + ll bc = ac; + ll abc = (qpow(23, n) + n * qpow(23, n - 1) % mod) % mod; + ll tot = qpow(26, n); + return ((tot - (a + b + c - ab - ac - bc + abc)) % mod + mod) % mod; + } +}; +``` + +```go +func stringCount(n int) int { + const mod int = 1e9 + 7 + qpow := func(a, n int) int { + ans := 1 + for ; n > 0; n >>= 1 { + if n&1 == 1 { + ans = ans * a % mod + } + a = a * a % mod + } + return ans + } + a := qpow(25, n) + b := a + c := qpow(25, n) + n*qpow(25, n-1) + ab := qpow(24, n) + ac := (qpow(24, n) + n*qpow(24, n-1)) % mod + bc := ac + abc := (qpow(23, n) + n*qpow(23, n-1)) % mod + tot := qpow(26, n) + return ((tot-(a+b+c-ab-ac-bc+abc))%mod + mod) % mod +} +``` + ```ts function stringCount(n: number): number { const mod = BigInt(10 ** 9 + 7); @@ -346,10 +340,6 @@ function stringCount(n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2931.Maximum Spending After Buying Items/README.md b/solution/2900-2999/2931.Maximum Spending After Buying Items/README.md index 7da39ea9f33c9..b14954710f77f 100644 --- a/solution/2900-2999/2931.Maximum Spending After Buying Items/README.md +++ b/solution/2900-2999/2931.Maximum Spending After Buying Items/README.md @@ -71,9 +71,7 @@ ## 解法 - - -**方法一:贪心 + 优先队列** +### 方法一:贪心 + 优先队列 根据题目描述,我们应该优先选择价值越小的物品,把价值越大的物品留到后面购买,这样才能使得总开销最大。因此,我们使用优先队列(小根堆)存储每个商店中还未购买的最小价值的物品。初始时,我们将每个商店中最右边的物品加入优先队列。 @@ -83,10 +81,6 @@ -### **Python3** - - - ```python class Solution: def maxSpending(self, values: List[List[int]]) -> int: @@ -103,10 +97,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long maxSpending(int[][] values) { @@ -129,8 +119,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -154,8 +142,6 @@ public: }; ``` -### **Go** - ```go func maxSpending(values [][]int) (ans int64) { pq := hp{} @@ -183,8 +169,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **TypeScript** - ```ts function maxSpending(values: number[][]): number { const m = values.length; @@ -206,10 +190,6 @@ function maxSpending(values: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2931.Maximum Spending After Buying Items/README_EN.md b/solution/2900-2999/2931.Maximum Spending After Buying Items/README_EN.md index a3993f6c852d6..cbc7cb2f3c76c 100644 --- a/solution/2900-2999/2931.Maximum Spending After Buying Items/README_EN.md +++ b/solution/2900-2999/2931.Maximum Spending After Buying Items/README_EN.md @@ -67,7 +67,7 @@ It can be shown that 386 is the maximum amount of money that can be spent buying ## Solutions -**Solution 1: Greedy + Priority Queue** +### Solution 1: Greedy + Priority Queue According to the problem description, we should prioritize purchasing items with smaller values and leave items with larger values to be purchased later in order to maximize the total cost. Therefore, we use a priority queue (min-heap) to store the smallest value item that has not been purchased in each store. Initially, we add the rightmost item in each store to the priority queue. @@ -77,8 +77,6 @@ The time complexity is $O(m \times n \times \log m)$, and the space complexity i -### **Python3** - ```python class Solution: def maxSpending(self, values: List[List[int]]) -> int: @@ -95,8 +93,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long maxSpending(int[][] values) { @@ -119,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -144,8 +138,6 @@ public: }; ``` -### **Go** - ```go func maxSpending(values [][]int) (ans int64) { pq := hp{} @@ -173,8 +165,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(tuple)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -### **TypeScript** - ```ts function maxSpending(values: number[][]): number { const m = values.length; @@ -196,10 +186,6 @@ function maxSpending(values: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2932.Maximum Strong Pair XOR I/README.md b/solution/2900-2999/2932.Maximum Strong Pair XOR I/README.md index 2637f8ad2a6d4..280f2e5ba3ee7 100644 --- a/solution/2900-2999/2932.Maximum Strong Pair XOR I/README.md +++ b/solution/2900-2999/2932.Maximum Strong Pair XOR I/README.md @@ -58,15 +58,90 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举数组中的每一个数对 $(x, y)$,如果满足 $|x - y| \leq \min(x, y)$,那么这个数对就是一个强数对,我们可以计算这个数对的异或值,并更新答案。 时间复杂度 $O(n^2)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。 -**方法二:排序 + 0-1 字典树** + + +```python +class Solution: + def maximumStrongPairXor(self, nums: List[int]) -> int: + return max(x ^ y for x in nums for y in nums if abs(x - y) <= min(x, y)) +``` + +```java +class Solution { + public int maximumStrongPairXor(int[] nums) { + int ans = 0; + for (int x : nums) { + for (int y : nums) { + if (Math.abs(x - y) <= Math.min(x, y)) { + ans = Math.max(ans, x ^ y); + } + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maximumStrongPairXor(vector& nums) { + int ans = 0; + for (int x : nums) { + for (int y : nums) { + if (abs(x - y) <= min(x, y)) { + ans = max(ans, x ^ y); + } + } + } + return ans; + } +}; +``` + +```go +func maximumStrongPairXor(nums []int) (ans int) { + for _, x := range nums { + for _, y := range nums { + if abs(x-y) <= min(x, y) { + ans = max(ans, x^y) + } + } + } + return +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} +``` + +```ts +function maximumStrongPairXor(nums: number[]): number { + let ans = 0; + for (const x of nums) { + for (const y of nums) { + if (Math.abs(x - y) <= Math.min(x, y)) { + ans = Math.max(ans, x ^ y); + } + } + } + return ans; +} +``` + + + +### 方法二:排序 + 0-1 字典树 观察不等式 $|x - y| \leq \min(x, y)$,其中涉及到绝对值以及最小值,我们不妨假设 $x \leq y$,则有 $y - x \leq x$,即 $y \leq 2x$。我们可以从小到大枚举 $y$,那么 $x$ 必须满足不等式 $y \leq 2x$。 @@ -76,16 +151,6 @@ -### **Python3** - - - -```python -class Solution: - def maximumStrongPairXor(self, nums: List[int]) -> int: - return max(x ^ y for x in nums for y in nums if abs(x - y) <= min(x, y)) -``` - ```python class Trie: __slots__ = ("children", "cnt") @@ -137,26 +202,6 @@ class Solution: return ans ``` -### **Java** - - - -```java -class Solution { - public int maximumStrongPairXor(int[] nums) { - int ans = 0; - for (int x : nums) { - for (int y : nums) { - if (Math.abs(x - y) <= Math.min(x, y)) { - ans = Math.max(ans, x ^ y); - } - } - } - return ans; - } -} -``` - ```java class Trie { private Trie[] children = new Trie[2]; @@ -219,25 +264,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maximumStrongPairXor(vector& nums) { - int ans = 0; - for (int x : nums) { - for (int y : nums) { - if (abs(x - y) <= min(x, y)) { - ans = max(ans, x ^ y); - } - } - } - return ans; - } -}; -``` - ```cpp class Trie { public: @@ -305,28 +331,6 @@ public: }; ``` -### **Go** - -```go -func maximumStrongPairXor(nums []int) (ans int) { - for _, x := range nums { - for _, y := range nums { - if abs(x-y) <= min(x, y) { - ans = max(ans, x^y) - } - } - } - return -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x -} -``` - ```go type Trie struct { children [2]*Trie @@ -388,22 +392,6 @@ func maximumStrongPairXor(nums []int) (ans int) { } ``` -### **TypeScript** - -```ts -function maximumStrongPairXor(nums: number[]): number { - let ans = 0; - for (const x of nums) { - for (const y of nums) { - if (Math.abs(x - y) <= Math.min(x, y)) { - ans = Math.max(ans, x ^ y); - } - } - } - return ans; -} -``` - ```ts class Trie { children: (Trie | null)[]; @@ -471,10 +459,6 @@ function maximumStrongPairXor(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2932.Maximum Strong Pair XOR I/README_EN.md b/solution/2900-2999/2932.Maximum Strong Pair XOR I/README_EN.md index bfc9390898594..296680df7f7d2 100644 --- a/solution/2900-2999/2932.Maximum Strong Pair XOR I/README_EN.md +++ b/solution/2900-2999/2932.Maximum Strong Pair XOR I/README_EN.md @@ -54,13 +54,90 @@ The maximum XOR possible from these pairs is 25 XOR 30 = 7 since the only other ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We can enumerate each pair of numbers $(x, y)$ in the array. If $|x - y| \leq \min(x, y)$, then this pair is a strong pair. We can calculate the XOR value of this pair and update the answer. The time complexity is $O(n^2)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$. -**Solution 2: Sorting + Binary Trie** + + +```python +class Solution: + def maximumStrongPairXor(self, nums: List[int]) -> int: + return max(x ^ y for x in nums for y in nums if abs(x - y) <= min(x, y)) +``` + +```java +class Solution { + public int maximumStrongPairXor(int[] nums) { + int ans = 0; + for (int x : nums) { + for (int y : nums) { + if (Math.abs(x - y) <= Math.min(x, y)) { + ans = Math.max(ans, x ^ y); + } + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int maximumStrongPairXor(vector& nums) { + int ans = 0; + for (int x : nums) { + for (int y : nums) { + if (abs(x - y) <= min(x, y)) { + ans = max(ans, x ^ y); + } + } + } + return ans; + } +}; +``` + +```go +func maximumStrongPairXor(nums []int) (ans int) { + for _, x := range nums { + for _, y := range nums { + if abs(x-y) <= min(x, y) { + ans = max(ans, x^y) + } + } + } + return +} + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} +``` + +```ts +function maximumStrongPairXor(nums: number[]): number { + let ans = 0; + for (const x of nums) { + for (const y of nums) { + if (Math.abs(x - y) <= Math.min(x, y)) { + ans = Math.max(ans, x ^ y); + } + } + } + return ans; +} +``` + + + +### Solution 2: Sorting + Binary Trie Observing the inequality $|x - y| \leq \min(x, y)$, which involves absolute value and minimum value, we can assume $x \leq y$, then we have $y - x \leq x$, that is, $y \leq 2x$. We can enumerate $y$ from small to large, then $x$ must satisfy the inequality $y \leq 2x$. @@ -70,14 +147,6 @@ The time complexity is $O(n \times \log M)$, and the space complexity is $O(n \t -### **Python3** - -```python -class Solution: - def maximumStrongPairXor(self, nums: List[int]) -> int: - return max(x ^ y for x in nums for y in nums if abs(x - y) <= min(x, y)) -``` - ```python class Trie: __slots__ = ("children", "cnt") @@ -129,24 +198,6 @@ class Solution: return ans ``` -### **Java** - -```java -class Solution { - public int maximumStrongPairXor(int[] nums) { - int ans = 0; - for (int x : nums) { - for (int y : nums) { - if (Math.abs(x - y) <= Math.min(x, y)) { - ans = Math.max(ans, x ^ y); - } - } - } - return ans; - } -} -``` - ```java class Trie { private Trie[] children = new Trie[2]; @@ -209,25 +260,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int maximumStrongPairXor(vector& nums) { - int ans = 0; - for (int x : nums) { - for (int y : nums) { - if (abs(x - y) <= min(x, y)) { - ans = max(ans, x ^ y); - } - } - } - return ans; - } -}; -``` - ```cpp class Trie { public: @@ -295,28 +327,6 @@ public: }; ``` -### **Go** - -```go -func maximumStrongPairXor(nums []int) (ans int) { - for _, x := range nums { - for _, y := range nums { - if abs(x-y) <= min(x, y) { - ans = max(ans, x^y) - } - } - } - return -} - -func abs(x int) int { - if x < 0 { - return -x - } - return x -} -``` - ```go type Trie struct { children [2]*Trie @@ -378,22 +388,6 @@ func maximumStrongPairXor(nums []int) (ans int) { } ``` -### **TypeScript** - -```ts -function maximumStrongPairXor(nums: number[]): number { - let ans = 0; - for (const x of nums) { - for (const y of nums) { - if (Math.abs(x - y) <= Math.min(x, y)) { - ans = Math.max(ans, x ^ y); - } - } - } - return ans; -} -``` - ```ts class Trie { children: (Trie | null)[]; @@ -461,10 +455,6 @@ function maximumStrongPairXor(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2933.High-Access Employees/README.md b/solution/2900-2999/2933.High-Access Employees/README.md index af5656b930d59..03284a4414b54 100644 --- a/solution/2900-2999/2933.High-Access Employees/README.md +++ b/solution/2900-2999/2933.High-Access Employees/README.md @@ -63,9 +63,7 @@ ## 解法 - - -**方法一:哈希表 + 排序** +### 方法一:哈希表 + 排序 我们用一个哈希表 $d$ 来存储每个员工的所有访问时间,其中键为员工的姓名,值为一个整数数组,表示该员工的所有访问时间,该时间为从当天 00:00 开始的分钟数。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def findHighAccessEmployees(self, access_times: List[List[str]]) -> List[str]: @@ -95,10 +89,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public List findHighAccessEmployees(List> access_times) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +141,6 @@ public: }; ``` -### **Go** - ```go func findHighAccessEmployees(access_times [][]string) (ans []string) { d := map[string][]int{} @@ -178,8 +164,6 @@ func findHighAccessEmployees(access_times [][]string) (ans []string) { } ``` -### **TypeScript** - ```ts function findHighAccessEmployees(access_times: string[][]): string[] { const d: Map = new Map(); @@ -206,10 +190,6 @@ function findHighAccessEmployees(access_times: string[][]): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2933.High-Access Employees/README_EN.md b/solution/2900-2999/2933.High-Access Employees/README_EN.md index 9f051a5857cb8..7a97cb938ccb4 100644 --- a/solution/2900-2999/2933.High-Access Employees/README_EN.md +++ b/solution/2900-2999/2933.High-Access Employees/README_EN.md @@ -59,7 +59,7 @@ So the answer is ["ab","cd"]. ## Solutions -**Solution 1: Hash Table + Sorting** +### Solution 1: Hash Table + Sorting We use a hash table $d$ to store all access times of each employee, where the key is the employee's name, and the value is an integer array, representing all access times of the employee, which are the number of minutes from the start of the day at 00:00. @@ -71,8 +71,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def findHighAccessEmployees(self, access_times: List[List[str]]) -> List[str]: @@ -87,8 +85,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public List findHighAccessEmployees(List> access_times) { @@ -115,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +137,6 @@ public: }; ``` -### **Go** - ```go func findHighAccessEmployees(access_times [][]string) (ans []string) { d := map[string][]int{} @@ -168,8 +160,6 @@ func findHighAccessEmployees(access_times [][]string) (ans []string) { } ``` -### **TypeScript** - ```ts function findHighAccessEmployees(access_times: string[][]): string[] { const d: Map = new Map(); @@ -196,10 +186,6 @@ function findHighAccessEmployees(access_times: string[][]): string[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/README.md b/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/README.md index 69d2b4c8da40f..149edf24f5ba3 100644 --- a/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/README.md +++ b/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/README.md @@ -71,9 +71,7 @@ ## 解法 - - -**方法一:分情况讨论 + 贪心** +### 方法一:分情况讨论 + 贪心 我们可以分成两种情况讨论: @@ -88,10 +86,6 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, nums1: List[int], nums2: List[int]) -> int: @@ -109,10 +103,6 @@ class Solution: return -1 if a + b == -2 else min(a, b + 1) ``` -### **Java** - - - ```java class Solution { private int n; @@ -140,8 +130,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +155,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums1 []int, nums2 []int) int { n := len(nums1) @@ -193,8 +179,6 @@ func minOperations(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - ```ts function minOperations(nums1: number[], nums2: number[]): number { const n = nums1.length; @@ -217,10 +201,6 @@ function minOperations(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/README_EN.md b/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/README_EN.md index 94851ec5202a0..a5acbcb7a65d6 100644 --- a/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/README_EN.md +++ b/solution/2900-2999/2934.Minimum Operations to Maximize Last Elements in Arrays/README_EN.md @@ -67,7 +67,7 @@ So, the answer is -1. ## Solutions -**Solution 1: Case Discussion + Greedy** +### Solution 1: Case Discussion + Greedy We can discuss two cases: @@ -82,8 +82,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def minOperations(self, nums1: List[int], nums2: List[int]) -> int: @@ -101,8 +99,6 @@ class Solution: return -1 if a + b == -2 else min(a, b + 1) ``` -### **Java** - ```java class Solution { private int n; @@ -130,8 +126,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +151,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums1 []int, nums2 []int) int { n := len(nums1) @@ -183,8 +175,6 @@ func minOperations(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - ```ts function minOperations(nums1: number[], nums2: number[]): number { const n = nums1.length; @@ -207,10 +197,6 @@ function minOperations(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2935.Maximum Strong Pair XOR II/README.md b/solution/2900-2999/2935.Maximum Strong Pair XOR II/README.md index 0e1ef0f490175..519982a00c20b 100644 --- a/solution/2900-2999/2935.Maximum Strong Pair XOR II/README.md +++ b/solution/2900-2999/2935.Maximum Strong Pair XOR II/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:排序 + 0-1 字典树** +### 方法一:排序 + 0-1 字典树 观察不等式 $|x - y| \leq \min(x, y)$,其中涉及到绝对值以及最小值,我们不妨假设 $x \leq y$,则有 $y - x \leq x$,即 $y \leq 2x$。我们可以从小到大枚举 $y$,那么 $x$ 必须满足不等式 $y \leq 2x$。 @@ -70,10 +68,6 @@ -### **Python3** - - - ```python class Trie: __slots__ = ("children", "cnt") @@ -125,10 +119,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Trie { private Trie[] children = new Trie[2]; @@ -191,8 +181,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -260,8 +248,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [2]*Trie @@ -323,8 +309,6 @@ func maximumStrongPairXor(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts class Trie { children: (Trie | null)[]; @@ -392,10 +376,6 @@ function maximumStrongPairXor(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2935.Maximum Strong Pair XOR II/README_EN.md b/solution/2900-2999/2935.Maximum Strong Pair XOR II/README_EN.md index ee2c4c1e54fcb..5cb6e8a548b87 100644 --- a/solution/2900-2999/2935.Maximum Strong Pair XOR II/README_EN.md +++ b/solution/2900-2999/2935.Maximum Strong Pair XOR II/README_EN.md @@ -54,7 +54,7 @@ The maximum XOR possible from these pairs is 500 XOR 520 = 1020 since the only o ## Solutions -**Solution 1: Sorting + Binary Trie** +### Solution 1: Sorting + Binary Trie Observing the inequality $|x - y| \leq \min(x, y)$, which involves absolute value and minimum value, we can assume $x \leq y$, then we have $y - x \leq x$, that is, $y \leq 2x$. We can enumerate $y$ from small to large, then $x$ must satisfy the inequality $y \leq 2x$. @@ -64,8 +64,6 @@ The time complexity is $O(n \times \log M)$, and the space complexity is $O(n \t -### **Python3** - ```python class Trie: __slots__ = ("children", "cnt") @@ -117,8 +115,6 @@ class Solution: return ans ``` -### **Java** - ```java class Trie { private Trie[] children = new Trie[2]; @@ -181,8 +177,6 @@ class Solution { } ``` -### **C++** - ```cpp class Trie { public: @@ -250,8 +244,6 @@ public: }; ``` -### **Go** - ```go type Trie struct { children [2]*Trie @@ -313,8 +305,6 @@ func maximumStrongPairXor(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts class Trie { children: (Trie | null)[]; @@ -382,10 +372,6 @@ function maximumStrongPairXor(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2936.Number of Equal Numbers Blocks/README.md b/solution/2900-2999/2936.Number of Equal Numbers Blocks/README.md index 6de51ba00e5f8..b24662b0909ce 100644 --- a/solution/2900-2999/2936.Number of Equal Numbers Blocks/README.md +++ b/solution/2900-2999/2936.Number of Equal Numbers Blocks/README.md @@ -67,26 +67,14 @@ ## 解法 - - -**方法一:二分查找** +### 方法一:二分查找 我们可以使用二分查找来找到每个块的右边界。具体地,我们从左到右遍历数组,对于每个下标 $i$,我们使用二分查找找到最小的下标 $j$,使得 $[i,j)$ 之间的所有元素都等于 $nums[i]$。然后我们将 $i$ 更新为 $j$,并继续遍历数组,直到 $i$ 大于等于数组的长度。 时间复杂度 $O(m \times \log n)$,其中 $m$ 是数组 $num$ 中不同元素的个数,而 $n$ 是数组 $num$ 的长度。空间复杂度 $O(1)$。 -**方法二:分治** - -我们可以使用分治的方法来计算答案。具体地,我们将数组分成两个子数组,递归地计算每个子数组的答案,然后将答案合并起来。如果第一个子数组的最后一个元素和第二个子数组的第一个元素相等,那么我们需要将答案减一。 - -时间复杂度 $O(\log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组 $num$ 的长度。 - -### **Python3** - - - ```python # Definition for BigArray. # class BigArray: @@ -108,10 +96,6 @@ class Solution(object): return ans ``` -### **Java** - - - ```java /** * Definition for BigArray. @@ -146,34 +130,6 @@ class Solution { } ``` -```java -/** - * Definition for BigArray. - * class BigArray { - * public BigArray(int[] elements); - * public int at(long index); - * public long size(); - * } - */ -class Solution { - public int countBlocks(BigArray nums) { - return f(nums, 0, nums.size() - 1); - } - - private int f(BigArray nums, long l, long r) { - if (nums.at(l) == nums.at(r)) { - return 1; - } - long mid = (l + r) >> 1; - int a = f(nums, l, mid); - int b = f(nums, mid + 1, r); - return a + b - (nums.at(mid) == nums.at(mid + 1) ? 1 : 0); - } -} -``` - -### **C++** - ```cpp /** * Definition for BigArray. @@ -211,36 +167,6 @@ public: }; ``` -```cpp -/** - * Definition for BigArray. - * class BigArray { - * public: - * BigArray(vector elements); - * int at(long long index); - * long long size(); - * }; - */ -class Solution { -public: - int countBlocks(BigArray* nums) { - using ll = long long; - function f = [&](ll l, ll r) { - if (nums->at(l) == nums->at(r)) { - return 1; - } - ll mid = (l + r) >> 1; - int a = f(l, mid); - int b = f(mid + 1, r); - return a + b - (nums->at(mid) == nums->at(mid + 1)); - }; - return f(0, nums->size() - 1); - } -}; -``` - -### **TypeScript** - ```ts /** * Definition for BigArray. @@ -274,6 +200,70 @@ function countBlocks(nums: BigArray | null): number { } ``` + + +### 方法二:分治 + +我们可以使用分治的方法来计算答案。具体地,我们将数组分成两个子数组,递归地计算每个子数组的答案,然后将答案合并起来。如果第一个子数组的最后一个元素和第二个子数组的第一个元素相等,那么我们需要将答案减一。 + +时间复杂度 $O(\log n)$,空间复杂度 $O(\log n)$。其中 $n$ 是数组 $num$ 的长度。 + + + +```java +/** + * Definition for BigArray. + * class BigArray { + * public BigArray(int[] elements); + * public int at(long index); + * public long size(); + * } + */ +class Solution { + public int countBlocks(BigArray nums) { + return f(nums, 0, nums.size() - 1); + } + + private int f(BigArray nums, long l, long r) { + if (nums.at(l) == nums.at(r)) { + return 1; + } + long mid = (l + r) >> 1; + int a = f(nums, l, mid); + int b = f(nums, mid + 1, r); + return a + b - (nums.at(mid) == nums.at(mid + 1) ? 1 : 0); + } +} +``` + +```cpp +/** + * Definition for BigArray. + * class BigArray { + * public: + * BigArray(vector elements); + * int at(long long index); + * long long size(); + * }; + */ +class Solution { +public: + int countBlocks(BigArray* nums) { + using ll = long long; + function f = [&](ll l, ll r) { + if (nums->at(l) == nums->at(r)) { + return 1; + } + ll mid = (l + r) >> 1; + int a = f(l, mid); + int b = f(mid + 1, r); + return a + b - (nums->at(mid) == nums->at(mid + 1)); + }; + return f(0, nums->size() - 1); + } +}; +``` + ```ts /** * Definition for BigArray. @@ -297,16 +287,6 @@ function countBlocks(nums: BigArray | null): number { } ``` -### **Go** - -```go - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2936.Number of Equal Numbers Blocks/README_EN.md b/solution/2900-2999/2936.Number of Equal Numbers Blocks/README_EN.md index 9abc8c3620418..6b94eead647c1 100644 --- a/solution/2900-2999/2936.Number of Equal Numbers Blocks/README_EN.md +++ b/solution/2900-2999/2936.Number of Equal Numbers Blocks/README_EN.md @@ -63,22 +63,14 @@ So the answer would be 5. ## Solutions -**Solution 1: Binary Search** +### Solution 1: Binary Search We can use binary search to find the right boundary of each block. Specifically, we traverse the array from left to right. For each index $i$, we use binary search to find the smallest index $j$ such that all elements between $[i,j)$ are equal to $nums[i]$. Then we update $i$ to $j$ and continue to traverse the array until $i$ is greater than or equal to the length of the array. The time complexity is $O(m \times \log n)$, where $m$ is the number of different elements in the array $num$, and $n$ is the length of the array $num$. The space complexity is $O(1)$. -**Solution 2: Divide and Conquer** - -We can use the divide and conquer method to calculate the answer. Specifically, we divide the array into two subarrays, recursively calculate the answer for each subarray, and then merge the answers. If the last element of the first subarray is equal to the first element of the second subarray, then we need to subtract one from the answer. - -The time complexity is $O(\log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $num$. - -### **Python3** - ```python # Definition for BigArray. # class BigArray: @@ -100,8 +92,6 @@ class Solution(object): return ans ``` -### **Java** - ```java /** * Definition for BigArray. @@ -136,34 +126,6 @@ class Solution { } ``` -```java -/** - * Definition for BigArray. - * class BigArray { - * public BigArray(int[] elements); - * public int at(long index); - * public long size(); - * } - */ -class Solution { - public int countBlocks(BigArray nums) { - return f(nums, 0, nums.size() - 1); - } - - private int f(BigArray nums, long l, long r) { - if (nums.at(l) == nums.at(r)) { - return 1; - } - long mid = (l + r) >> 1; - int a = f(nums, l, mid); - int b = f(nums, mid + 1, r); - return a + b - (nums.at(mid) == nums.at(mid + 1) ? 1 : 0); - } -} -``` - -### **C++** - ```cpp /** * Definition for BigArray. @@ -201,36 +163,6 @@ public: }; ``` -```cpp -/** - * Definition for BigArray. - * class BigArray { - * public: - * BigArray(vector elements); - * int at(long long index); - * long long size(); - * }; - */ -class Solution { -public: - int countBlocks(BigArray* nums) { - using ll = long long; - function f = [&](ll l, ll r) { - if (nums->at(l) == nums->at(r)) { - return 1; - } - ll mid = (l + r) >> 1; - int a = f(l, mid); - int b = f(mid + 1, r); - return a + b - (nums->at(mid) == nums->at(mid + 1)); - }; - return f(0, nums->size() - 1); - } -}; -``` - -### **TypeScript** - ```ts /** * Definition for BigArray. @@ -264,6 +196,70 @@ function countBlocks(nums: BigArray | null): number { } ``` + + +### Solution 2: Divide and Conquer + +We can use the divide and conquer method to calculate the answer. Specifically, we divide the array into two subarrays, recursively calculate the answer for each subarray, and then merge the answers. If the last element of the first subarray is equal to the first element of the second subarray, then we need to subtract one from the answer. + +The time complexity is $O(\log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $num$. + + + +```java +/** + * Definition for BigArray. + * class BigArray { + * public BigArray(int[] elements); + * public int at(long index); + * public long size(); + * } + */ +class Solution { + public int countBlocks(BigArray nums) { + return f(nums, 0, nums.size() - 1); + } + + private int f(BigArray nums, long l, long r) { + if (nums.at(l) == nums.at(r)) { + return 1; + } + long mid = (l + r) >> 1; + int a = f(nums, l, mid); + int b = f(nums, mid + 1, r); + return a + b - (nums.at(mid) == nums.at(mid + 1) ? 1 : 0); + } +} +``` + +```cpp +/** + * Definition for BigArray. + * class BigArray { + * public: + * BigArray(vector elements); + * int at(long long index); + * long long size(); + * }; + */ +class Solution { +public: + int countBlocks(BigArray* nums) { + using ll = long long; + function f = [&](ll l, ll r) { + if (nums->at(l) == nums->at(r)) { + return 1; + } + ll mid = (l + r) >> 1; + int a = f(l, mid); + int b = f(mid + 1, r); + return a + b - (nums->at(mid) == nums->at(mid + 1)); + }; + return f(0, nums->size() - 1); + } +}; +``` + ```ts /** * Definition for BigArray. @@ -287,16 +283,6 @@ function countBlocks(nums: BigArray | null): number { } ``` -### **Go** - -```go - -``` - -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2937.Make Three Strings Equal/README.md b/solution/2900-2999/2937.Make Three Strings Equal/README.md index d42c2146d7a5b..4c290f48209ec 100644 --- a/solution/2900-2999/2937.Make Three Strings Equal/README.md +++ b/solution/2900-2999/2937.Make Three Strings Equal/README.md @@ -40,9 +40,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 根据题目描述,我们知道,如果删除字符后的三个字符串相等,那么它们存在一个长度大于 $1$ 的公共前缀。因此,我们可以枚举公共前缀的位置 $i$,如果当前下标 $i$ 对应的三个字符不完全相等,那么公共前缀长度为 $i$,此时,我们判断 $i$ 是否为 $0$,若是,返回 $-1$,否则返回 $s - 3 \times i$,其中 $s$ 为三个字符串的长度和。 @@ -50,10 +48,6 @@ -### **Python3** - - - ```python class Solution: def findMinimumOperations(self, s1: str, s2: str, s3: str) -> int: @@ -65,10 +59,6 @@ class Solution: return s - 3 * n ``` -### **Java** - - - ```java class Solution { public int findMinimumOperations(String s1, String s2, String s3) { @@ -84,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +90,6 @@ public: }; ``` -### **Go** - ```go func findMinimumOperations(s1 string, s2 string, s3 string) int { s := len(s1) + len(s2) + len(s3) @@ -120,8 +106,6 @@ func findMinimumOperations(s1 string, s2 string, s3 string) int { } ``` -### **TypeScript** - ```ts function findMinimumOperations(s1: string, s2: string, s3: string): number { const s = s1.length + s2.length + s3.length; @@ -135,10 +119,6 @@ function findMinimumOperations(s1: string, s2: string, s3: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2937.Make Three Strings Equal/README_EN.md b/solution/2900-2999/2937.Make Three Strings Equal/README_EN.md index 9bb57e7c374e9..bec75dbecf4a9 100644 --- a/solution/2900-2999/2937.Make Three Strings Equal/README_EN.md +++ b/solution/2900-2999/2937.Make Three Strings Equal/README_EN.md @@ -37,7 +37,7 @@ It can be shown that there is no way to make them equal with less than two opera ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration According to the problem description, we know that if the three strings are equal after deleting characters, then they have a common prefix of length greater than $1$. Therefore, we can enumerate the position $i$ of the common prefix. If the three characters at the current index $i$ are not all equal, then the length of the common prefix is $i$. At this point, we check if $i$ is $0$. If it is, return $-1$. Otherwise, return $s - 3 \times i$, where $s$ is the sum of the lengths of the three strings. @@ -45,8 +45,6 @@ The time complexity is $O(n)$, where $n$ is the minimum length of the three stri -### **Python3** - ```python class Solution: def findMinimumOperations(self, s1: str, s2: str, s3: str) -> int: @@ -58,8 +56,6 @@ class Solution: return s - 3 * n ``` -### **Java** - ```java class Solution { public int findMinimumOperations(String s1, String s2, String s3) { @@ -75,8 +71,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +87,6 @@ public: }; ``` -### **Go** - ```go func findMinimumOperations(s1 string, s2 string, s3 string) int { s := len(s1) + len(s2) + len(s3) @@ -111,8 +103,6 @@ func findMinimumOperations(s1 string, s2 string, s3 string) int { } ``` -### **TypeScript** - ```ts function findMinimumOperations(s1: string, s2: string, s3: string): number { const s = s1.length + s2.length + s3.length; @@ -126,10 +116,6 @@ function findMinimumOperations(s1: string, s2: string, s3: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2938.Separate Black and White Balls/README.md b/solution/2900-2999/2938.Separate Black and White Balls/README.md index b6f73c148981f..5d450ecc2a8e6 100644 --- a/solution/2900-2999/2938.Separate Black and White Balls/README.md +++ b/solution/2900-2999/2938.Separate Black and White Balls/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:计数模拟** +### 方法一:计数模拟 我们考虑将所有的 $1$ 移到最右边,用一个变量 $cnt$ 记录当前已经移动到最右边的 $1$ 的个数,用一个变量 $ans$ 记录移动的次数。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def minimumSteps(self, s: str) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long minimumSteps(String s) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -124,8 +112,6 @@ public: }; ``` -### **Go** - ```go func minimumSteps(s string) (ans int64) { n := len(s) @@ -140,8 +126,6 @@ func minimumSteps(s string) (ans int64) { } ``` -### **TypeScript** - ```ts function minimumSteps(s: string): number { const n = s.length; @@ -156,10 +140,6 @@ function minimumSteps(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2938.Separate Black and White Balls/README_EN.md b/solution/2900-2999/2938.Separate Black and White Balls/README_EN.md index b9ee2f1cc7cf9..400d6818e8271 100644 --- a/solution/2900-2999/2938.Separate Black and White Balls/README_EN.md +++ b/solution/2900-2999/2938.Separate Black and White Balls/README_EN.md @@ -51,7 +51,7 @@ It can be proven that the minimum number of steps needed is 2. ## Solutions -**Solution 1: Counting Simulation** +### Solution 1: Counting Simulation We consider moving all the '1's to the rightmost side. We use a variable $cnt$ to record the current number of '1's that have been moved to the rightmost side, and a variable $ans$ to record the number of moves. @@ -61,8 +61,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string. The space -### **Python3** - ```python class Solution: def minimumSteps(self, s: str) -> int: @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long minimumSteps(String s) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +108,6 @@ public: }; ``` -### **Go** - ```go func minimumSteps(s string) (ans int64) { n := len(s) @@ -130,8 +122,6 @@ func minimumSteps(s string) (ans int64) { } ``` -### **TypeScript** - ```ts function minimumSteps(s: string): number { const n = s.length; @@ -146,10 +136,6 @@ function minimumSteps(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2939.Maximum Xor Product/README.md b/solution/2900-2999/2939.Maximum Xor Product/README.md index a616a5255d47c..cc65a2716c773 100644 --- a/solution/2900-2999/2939.Maximum Xor Product/README.md +++ b/solution/2900-2999/2939.Maximum Xor Product/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:贪心 + 位运算** +### 方法一:贪心 + 位运算 根据题目描述,我们可以给 $a$ 和 $b$ 在二进制下 $[0..n)$ 位上同时分配一个数字,最终使得 $a$ 和 $b$ 的乘积最大。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def maximumXorProduct(self, a: int, b: int, n: int) -> int: @@ -91,10 +85,6 @@ class Solution: return ax * bx % mod ``` -### **Java** - - - ```java class Solution { public int maximumXorProduct(long a, long b, int n) { @@ -120,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -146,8 +134,6 @@ public: }; ``` -### **Go** - ```go func maximumXorProduct(a int64, b int64, n int) int { const mod int64 = 1e9 + 7 @@ -170,8 +156,6 @@ func maximumXorProduct(a int64, b int64, n int) int { } ``` -### **TypeScript** - ```ts function maximumXorProduct(a: number, b: number, n: number): number { const mod = BigInt(1e9 + 7); @@ -195,10 +179,6 @@ function maximumXorProduct(a: number, b: number, n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2939.Maximum Xor Product/README_EN.md b/solution/2900-2999/2939.Maximum Xor Product/README_EN.md index 03cbbd05beb09..58b4a7da1ed29 100644 --- a/solution/2900-2999/2939.Maximum Xor Product/README_EN.md +++ b/solution/2900-2999/2939.Maximum Xor Product/README_EN.md @@ -47,7 +47,7 @@ It can be shown that 12 is the maximum value of (a XOR x) * (b XOR x) for all 0 ## Solutions -**Solution 1: Greedy + Bitwise Operation** +### Solution 1: Greedy + Bitwise Operation According to the problem description, we can assign a number to the $[0..n)$ bits of $a$ and $b$ in binary at the same time, so that the product of $a$ and $b$ is maximized. @@ -63,8 +63,6 @@ The time complexity is $O(n)$, where $n$ is the integer given in the problem. Th -### **Python3** - ```python class Solution: def maximumXorProduct(self, a: int, b: int, n: int) -> int: @@ -83,8 +81,6 @@ class Solution: return ax * bx % mod ``` -### **Java** - ```java class Solution { public int maximumXorProduct(long a, long b, int n) { @@ -110,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -136,8 +130,6 @@ public: }; ``` -### **Go** - ```go func maximumXorProduct(a int64, b int64, n int) int { const mod int64 = 1e9 + 7 @@ -160,8 +152,6 @@ func maximumXorProduct(a int64, b int64, n int) int { } ``` -### **TypeScript** - ```ts function maximumXorProduct(a: number, b: number, n: number): number { const mod = BigInt(1e9 + 7); @@ -185,10 +175,6 @@ function maximumXorProduct(a: number, b: number, n: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2940.Find Building Where Alice and Bob Can Meet/README.md b/solution/2900-2999/2940.Find Building Where Alice and Bob Can Meet/README.md index e4a96720fce6a..2019fdb021dec 100644 --- a/solution/2900-2999/2940.Find Building Where Alice and Bob Can Meet/README.md +++ b/solution/2900-2999/2940.Find Building Where Alice and Bob Can Meet/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:树状数组** +### 方法一:树状数组 我们不妨记 $queries[i] = [l_i, r_i]$,其中 $l_i \le r_i$。如果 $l_i = r_i$ 或者 $heights[l_i] \lt heights[r_i]$,那么答案就是 $r_i$。否则,我们需要在所有满足 $j \gt r_i$,且 $heights[j] \gt heights[l_i]$ 的 $j$ 中找到最小的 $j$。 @@ -76,10 +74,6 @@ -### **Python3** - - - ```python class BinaryIndexedTree: __slots__ = ["n", "c"] @@ -126,10 +120,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class BinaryIndexedTree { private final int inf = 1 << 30; @@ -197,8 +187,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { private: @@ -268,8 +256,6 @@ public: }; ``` -### **Go** - ```go const inf int = 1 << 30 @@ -340,8 +326,6 @@ func leftmostBuildingQueries(heights []int, queries [][]int) []int { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -417,10 +401,6 @@ function leftmostBuildingQueries(heights: number[], queries: number[][]): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2940.Find Building Where Alice and Bob Can Meet/README_EN.md b/solution/2900-2999/2940.Find Building Where Alice and Bob Can Meet/README_EN.md index 620314d277ee6..6ecbd23eb7218 100644 --- a/solution/2900-2999/2940.Find Building Where Alice and Bob Can Meet/README_EN.md +++ b/solution/2900-2999/2940.Find Building Where Alice and Bob Can Meet/README_EN.md @@ -55,7 +55,7 @@ For ans[i] == -1, It can be shown that there is no building where Alice and Bob ## Solutions -**Solution 1: Binary Indexed Tree** +### Solution 1: Binary Indexed Tree Let's denote $queries[i] = [l_i, r_i]$, where $l_i \le r_i$. If $l_i = r_i$ or $heights[l_i] < heights[r_i]$, then the answer is $r_i$. Otherwise, we need to find the smallest $j$ among all $j > r_i$ and $heights[j] > heights[l_i]$. @@ -71,8 +71,6 @@ Similar problems: -### **Python3** - ```python class BinaryIndexedTree: __slots__ = ["n", "c"] @@ -119,8 +117,6 @@ class Solution: return ans ``` -### **Java** - ```java class BinaryIndexedTree { private final int inf = 1 << 30; @@ -188,8 +184,6 @@ class Solution { } ``` -### **C++** - ```cpp class BinaryIndexedTree { private: @@ -259,8 +253,6 @@ public: }; ``` -### **Go** - ```go const inf int = 1 << 30 @@ -331,8 +323,6 @@ func leftmostBuildingQueries(heights []int, queries [][]int) []int { } ``` -### **TypeScript** - ```ts class BinaryIndexedTree { private n: number; @@ -408,10 +398,6 @@ function leftmostBuildingQueries(heights: number[], queries: number[][]): number } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/README.md b/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/README.md index 50f250a874044..1307fbfe60dde 100644 --- a/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/README.md +++ b/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/README.md @@ -49,14 +49,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxGcdSum(self, nums: List[int], k: int) -> int: @@ -77,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long maxGcdSum(int[] nums, int k) { @@ -118,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +143,6 @@ public: }; ``` -### **Go** - ```go func maxGcdSum(nums []int, k int) int64 { n := len(nums) @@ -195,8 +183,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function maxGcdSum(nums: number[], k: number): number { const n: number = nums.length; @@ -233,7 +219,11 @@ function gcd(a: number, b: number): number { } ``` -### **TypeScript** + + +### 方法二 + + ```ts function maxGcdSum(nums: number[], k: number): number { @@ -271,10 +261,6 @@ function gcd(a: number, b: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/README_EN.md b/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/README_EN.md index 39499a3e1eee3..49c84e9c4c5be 100644 --- a/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/README_EN.md +++ b/solution/2900-2999/2941.Maximum GCD-Sum of a Subarray/README_EN.md @@ -45,9 +45,9 @@ It can be shown that we can not select any other subarray with a gcd-sum greater ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -69,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long maxGcdSum(int[] nums, int k) { @@ -108,8 +106,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +139,6 @@ public: }; ``` -### **Go** - ```go func maxGcdSum(nums []int, k int) int64 { n := len(nums) @@ -185,8 +179,6 @@ func gcd(a, b int) int { } ``` -### **TypeScript** - ```ts function maxGcdSum(nums: number[], k: number): number { const n: number = nums.length; @@ -223,10 +215,48 @@ function gcd(a: number, b: number): number { } ``` -### **...** + -``` +### Solution 2 + + +```ts +function maxGcdSum(nums: number[], k: number): number { + const n: number = nums.length; + const s: number[] = Array(n + 1).fill(0); + for (let i = 1; i <= n; i++) { + s[i] = s[i - 1] + nums[i - 1]; + } + + let f: [number, number][] = []; + let ans: number = 0; + + for (let i = 0; i < n; ++i) { + const g: [number, number][] = []; + for (const [j, x] of f) { + const y: number = gcd(x, nums[i]); + if (g.length === 0 || g.at(-1)[1] !== y) { + g.push([j, y]); + } + } + f = g; + f.push([i, nums[i]]); + for (const [j, x] of f) { + if (i - j + 1 >= k) { + ans = Math.max(ans, (s[i + 1] - s[j]) * x); + } + } + } + + return ans; +} + +function gcd(a: number, b: number): number { + return b === 0 ? a : gcd(b, a % b); +} ``` + + diff --git a/solution/2900-2999/2942.Find Words Containing Character/README.md b/solution/2900-2999/2942.Find Words Containing Character/README.md index 3c3024fff194f..41cfc085e21c0 100644 --- a/solution/2900-2999/2942.Find Words Containing Character/README.md +++ b/solution/2900-2999/2942.Find Words Containing Character/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:遍历** +### 方法一:遍历 我们直接遍历字符串数组 $words$ 中的每一个字符串 $words[i]$,如果 $x$ 在 $words[i]$ 中出现,就将 $i$ 加入答案数组中。 @@ -63,20 +61,12 @@ -### **Python3** - - - ```python class Solution: def findWordsContaining(self, words: List[str], x: str) -> List[int]: return [i for i, w in enumerate(words) if x in w] ``` -### **Java** - - - ```java class Solution { public List findWordsContaining(String[] words, char x) { @@ -91,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -108,8 +96,6 @@ public: }; ``` -### **Go** - ```go func findWordsContaining(words []string, x byte) (ans []int) { for i, w := range words { @@ -124,8 +110,6 @@ func findWordsContaining(words []string, x byte) (ans []int) { } ``` -### **TypeScript** - ```ts function findWordsContaining(words: string[], x: string): number[] { const ans: number[] = []; @@ -138,10 +122,6 @@ function findWordsContaining(words: string[], x: string): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2942.Find Words Containing Character/README_EN.md b/solution/2900-2999/2942.Find Words Containing Character/README_EN.md index 50e14c3a73dbf..7f6d37df2370f 100644 --- a/solution/2900-2999/2942.Find Words Containing Character/README_EN.md +++ b/solution/2900-2999/2942.Find Words Containing Character/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Traversal** +### Solution 1: Traversal We directly traverse each string `words[i]` in the string array `words`. If `x` appears in `words[i]`, we add `i` to the answer array. @@ -57,16 +57,12 @@ The time complexity is $O(L)$, where $L$ is the sum of the lengths of all string -### **Python3** - ```python class Solution: def findWordsContaining(self, words: List[str], x: str) -> List[int]: return [i for i, w in enumerate(words) if x in w] ``` -### **Java** - ```java class Solution { public List findWordsContaining(String[] words, char x) { @@ -81,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -98,8 +92,6 @@ public: }; ``` -### **Go** - ```go func findWordsContaining(words []string, x byte) (ans []int) { for i, w := range words { @@ -114,8 +106,6 @@ func findWordsContaining(words []string, x byte) (ans []int) { } ``` -### **TypeScript** - ```ts function findWordsContaining(words: string[], x: string): number[] { const ans: number[] = []; @@ -128,10 +118,6 @@ function findWordsContaining(words: string[], x: string): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/README.md b/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/README.md index c9284f8c15b7b..73db169d72d3e 100644 --- a/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/README.md +++ b/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/README.md @@ -98,9 +98,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 题目实际上要我们找出数组中最长的连续递增子序列的长度,然后再加上 $1$。 @@ -114,10 +112,6 @@ -### **Python3** - - - ```python class Solution: def maximizeSquareHoleArea( @@ -137,10 +131,6 @@ class Solution: return min(f(hBars), f(vBars)) ** 2 ``` -### **Java** - - - ```java class Solution { public int maximizeSquareHoleArea(int n, int m, int[] hBars, int[] vBars) { @@ -163,8 +153,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -187,8 +175,6 @@ public: }; ``` -### **Go** - ```go func maximizeSquareHoleArea(n int, m int, hBars []int, vBars []int) int { f := func(nums []int) int { @@ -209,8 +195,6 @@ func maximizeSquareHoleArea(n int, m int, hBars []int, vBars []int) int { } ``` -### **TypeScript** - ```ts function maximizeSquareHoleArea(n: number, m: number, hBars: number[], vBars: number[]): number { const f = (nums: number[]): number => { @@ -229,8 +213,6 @@ function maximizeSquareHoleArea(n: number, m: number, hBars: number[], vBars: nu } ``` -### **Rust** - ```rust impl Solution { pub fn maximize_square_hole_area(n: i32, m: i32, h_bars: Vec, v_bars: Vec) -> i32 { @@ -257,10 +239,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/README_EN.md b/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/README_EN.md index 1b3f70e9abb11..e267b7328d6dc 100644 --- a/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/README_EN.md +++ b/solution/2900-2999/2943.Maximize Area of Square Hole in Grid/README_EN.md @@ -93,7 +93,7 @@ Hence, the answer is 9. ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting The problem essentially asks us to find the length of the longest consecutive increasing subsequence in the array, and then add 1 to it. @@ -107,8 +107,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def maximizeSquareHoleArea( @@ -128,8 +126,6 @@ class Solution: return min(f(hBars), f(vBars)) ** 2 ``` -### **Java** - ```java class Solution { public int maximizeSquareHoleArea(int n, int m, int[] hBars, int[] vBars) { @@ -152,8 +148,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -176,8 +170,6 @@ public: }; ``` -### **Go** - ```go func maximizeSquareHoleArea(n int, m int, hBars []int, vBars []int) int { f := func(nums []int) int { @@ -198,8 +190,6 @@ func maximizeSquareHoleArea(n int, m int, hBars []int, vBars []int) int { } ``` -### **TypeScript** - ```ts function maximizeSquareHoleArea(n: number, m: number, hBars: number[], vBars: number[]): number { const f = (nums: number[]): number => { @@ -218,8 +208,6 @@ function maximizeSquareHoleArea(n: number, m: number, hBars: number[], vBars: nu } ``` -### **Rust** - ```rust impl Solution { pub fn maximize_square_hole_area(n: i32, m: i32, h_bars: Vec, v_bars: Vec) -> i32 { @@ -246,10 +234,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/README.md b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/README.md index 2bd7273fc8890..264fa9d98fafe 100644 --- a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/README.md +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:记忆化搜索** +### 方法一:记忆化搜索 我们定义一个函数 $dfs(i)$,表示从第 $i$ 个水果开始购买所有水果所需要的最少金币数。那么答案就是 $dfs(1)$。 @@ -74,32 +72,8 @@ 时间复杂度 $O(n^2)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $prices$ 的长度。 -**方法二:动态规划** - -我们可以将方法一中的记忆化搜索改写成动态规划的形式。 - -与方法一类似,我们定义 $f[i]$ 表示从第 $i$ 个水果开始购买所有水果所需要的最少金币数。那么答案就是 $f[1]$。 - -状态转移方程为 $f[i] = \min_{i + 1 \le j \le 2i + 1} f[j] + prices[i - 1]$。 - -在实现上,我们从后往前计算,并且可以直接在数组 $prices$ 上进行状态转移,这样可以节省空间。 - -时间复杂度 $O(n^2)$,其中 $n$ 为数组 $prices$ 的长度。空间复杂度 $O(1)$。 - -**方法三:动态规划 + 单调队列优化** - -我们观察方法二中的状态转移方程,可以发现,对于每个 $i$,我们需要求出 $f[i + 1], f[i + 2], \cdots, f[2i + 1]$ 的最小值,并且随着 $i$ 的减小,这些值的范围也在减小。这实际上是求一个单调收窄的滑动窗口的最小值,我们可以使用单调队列来优化。 - -我们从后往前计算,维护一个单调递增的队列 $q$,队列中存储的是下标。如果 $q$ 的队首元素大于 $i \times 2 + 1$,说明 $i$ 之后的元素都不会被用到,所以我们将队首元素出队。如果 $i$ 不大于 $(n - 1) / 2$,那么我们可以将 $prices[q[0] - 1]$ 加到 $prices[i - 1]$ 上,然后将 $i$ 加入队尾。如果 $q$ 的队尾元素对应的水果价格大于等于 $prices[i - 1]$,那么我们将队尾元素出队,直到队尾元素对应的水果价格小于 $prices[i - 1]$ 或者队列为空,然后将 $i$ 加入队尾。 - -时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $prices$ 的长度。 - -### **Python3** - - - ```python class Solution: def minimumCoins(self, prices: List[int]) -> int: @@ -112,35 +86,6 @@ class Solution: return dfs(1) ``` -```python -class Solution: - def minimumCoins(self, prices: List[int]) -> int: - n = len(prices) - for i in range((n - 1) // 2, 0, -1): - prices[i - 1] += min(prices[i : i * 2 + 1]) - return prices[0] -``` - -```python -class Solution: - def minimumCoins(self, prices: List[int]) -> int: - n = len(prices) - q = deque() - for i in range(n, 0, -1): - while q and q[0] > i * 2 + 1: - q.popleft() - if i <= (n - 1) // 2: - prices[i - 1] += prices[q[0] - 1] - while q and prices[q[-1] - 1] >= prices[i - 1]: - q.pop() - q.append(i) - return prices[0] -``` - -### **Java** - - - ```java class Solution { private int[] prices; @@ -169,6 +114,95 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minimumCoins(vector& prices) { + int n = prices.size(); + int f[n + 1]; + memset(f, 0x3f, sizeof(f)); + function dfs = [&](int i) { + if (i * 2 >= n) { + return prices[i - 1]; + } + if (f[i] == 0x3f3f3f3f) { + for (int j = i + 1; j <= i * 2 + 1; ++j) { + f[i] = min(f[i], prices[i - 1] + dfs(j)); + } + } + return f[i]; + }; + return dfs(1); + } +}; +``` + +```go +func minimumCoins(prices []int) int { + n := len(prices) + f := make([]int, n+1) + var dfs func(int) int + dfs = func(i int) int { + if i*2 >= n { + return prices[i-1] + } + if f[i] == 0 { + f[i] = 1 << 30 + for j := i + 1; j <= i*2+1; j++ { + f[i] = min(f[i], dfs(j)+prices[i-1]) + } + } + return f[i] + } + return dfs(1) +} +``` + +```ts +function minimumCoins(prices: number[]): number { + const n = prices.length; + const f: number[] = Array(n + 1).fill(0); + const dfs = (i: number): number => { + if (i * 2 >= n) { + return prices[i - 1]; + } + if (f[i] === 0) { + f[i] = 1 << 30; + for (let j = i + 1; j <= i * 2 + 1; ++j) { + f[i] = Math.min(f[i], prices[i - 1] + dfs(j)); + } + } + return f[i]; + }; + return dfs(1); +} +``` + + + +### 方法二:动态规划 + +我们可以将方法一中的记忆化搜索改写成动态规划的形式。 + +与方法一类似,我们定义 $f[i]$ 表示从第 $i$ 个水果开始购买所有水果所需要的最少金币数。那么答案就是 $f[1]$。 + +状态转移方程为 $f[i] = \min_{i + 1 \le j \le 2i + 1} f[j] + prices[i - 1]$。 + +在实现上,我们从后往前计算,并且可以直接在数组 $prices$ 上进行状态转移,这样可以节省空间。 + +时间复杂度 $O(n^2)$,其中 $n$ 为数组 $prices$ 的长度。空间复杂度 $O(1)$。 + + + +```python +class Solution: + def minimumCoins(self, prices: List[int]) -> int: + n = len(prices) + for i in range((n - 1) // 2, 0, -1): + prices[i - 1] += min(prices[i : i * 2 + 1]) + return prices[0] +``` + ```java class Solution { public int minimumCoins(int[] prices) { @@ -185,6 +219,65 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minimumCoins(vector& prices) { + int n = prices.size(); + for (int i = (n - 1) / 2; i; --i) { + prices[i - 1] += *min_element(prices.begin() + i, prices.begin() + 2 * i + 1); + } + return prices[0]; + } +}; +``` + +```go +func minimumCoins(prices []int) int { + for i := (len(prices) - 1) / 2; i > 0; i-- { + prices[i-1] += slices.Min(prices[i : i*2+1]) + } + return prices[0] +} +``` + +```ts +function minimumCoins(prices: number[]): number { + for (let i = (prices.length - 1) >> 1; i; --i) { + prices[i - 1] += Math.min(...prices.slice(i, i * 2 + 1)); + } + return prices[0]; +} +``` + + + +### 方法三:动态规划 + 单调队列优化 + +我们观察方法二中的状态转移方程,可以发现,对于每个 $i$,我们需要求出 $f[i + 1], f[i + 2], \cdots, f[2i + 1]$ 的最小值,并且随着 $i$ 的减小,这些值的范围也在减小。这实际上是求一个单调收窄的滑动窗口的最小值,我们可以使用单调队列来优化。 + +我们从后往前计算,维护一个单调递增的队列 $q$,队列中存储的是下标。如果 $q$ 的队首元素大于 $i \times 2 + 1$,说明 $i$ 之后的元素都不会被用到,所以我们将队首元素出队。如果 $i$ 不大于 $(n - 1) / 2$,那么我们可以将 $prices[q[0] - 1]$ 加到 $prices[i - 1]$ 上,然后将 $i$ 加入队尾。如果 $q$ 的队尾元素对应的水果价格大于等于 $prices[i - 1]$,那么我们将队尾元素出队,直到队尾元素对应的水果价格小于 $prices[i - 1]$ 或者队列为空,然后将 $i$ 加入队尾。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $prices$ 的长度。 + + + +```python +class Solution: + def minimumCoins(self, prices: List[int]) -> int: + n = len(prices) + q = deque() + for i in range(n, 0, -1): + while q and q[0] > i * 2 + 1: + q.popleft() + if i <= (n - 1) // 2: + prices[i - 1] += prices[q[0] - 1] + while q and prices[q[-1] - 1] >= prices[i - 1]: + q.pop() + q.append(i) + return prices[0] +``` + ```java class Solution { public int minimumCoins(int[] prices) { @@ -207,44 +300,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minimumCoins(vector& prices) { - int n = prices.size(); - int f[n + 1]; - memset(f, 0x3f, sizeof(f)); - function dfs = [&](int i) { - if (i * 2 >= n) { - return prices[i - 1]; - } - if (f[i] == 0x3f3f3f3f) { - for (int j = i + 1; j <= i * 2 + 1; ++j) { - f[i] = min(f[i], prices[i - 1] + dfs(j)); - } - } - return f[i]; - }; - return dfs(1); - } -}; -``` - -```cpp -class Solution { -public: - int minimumCoins(vector& prices) { - int n = prices.size(); - for (int i = (n - 1) / 2; i; --i) { - prices[i - 1] += *min_element(prices.begin() + i, prices.begin() + 2 * i + 1); - } - return prices[0]; - } -}; -``` - ```cpp class Solution { public: @@ -268,38 +323,6 @@ public: }; ``` -### **Go** - -```go -func minimumCoins(prices []int) int { - n := len(prices) - f := make([]int, n+1) - var dfs func(int) int - dfs = func(i int) int { - if i*2 >= n { - return prices[i-1] - } - if f[i] == 0 { - f[i] = 1 << 30 - for j := i + 1; j <= i*2+1; j++ { - f[i] = min(f[i], dfs(j)+prices[i-1]) - } - } - return f[i] - } - return dfs(1) -} -``` - -```go -func minimumCoins(prices []int) int { - for i := (len(prices) - 1) / 2; i > 0; i-- { - prices[i-1] += slices.Min(prices[i : i*2+1]) - } - return prices[0] -} -``` - ```go func minimumCoins(prices []int) int { n := len(prices) @@ -378,37 +401,6 @@ func (q Deque) Get(i int) int { } ``` -### **TypeScript** - -```ts -function minimumCoins(prices: number[]): number { - const n = prices.length; - const f: number[] = Array(n + 1).fill(0); - const dfs = (i: number): number => { - if (i * 2 >= n) { - return prices[i - 1]; - } - if (f[i] === 0) { - f[i] = 1 << 30; - for (let j = i + 1; j <= i * 2 + 1; ++j) { - f[i] = Math.min(f[i], prices[i - 1] + dfs(j)); - } - } - return f[i]; - }; - return dfs(1); -} -``` - -```ts -function minimumCoins(prices: number[]): number { - for (let i = (prices.length - 1) >> 1; i; --i) { - prices[i - 1] += Math.min(...prices.slice(i, i * 2 + 1)); - } - return prices[0]; -} -``` - ```ts function minimumCoins(prices: number[]): number { const n = prices.length; @@ -525,10 +517,6 @@ class Deque { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/README_EN.md b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/README_EN.md index 83a55c36a776f..c3d1b39cacb3e 100644 --- a/solution/2900-2999/2944.Minimum Number of Coins for Fruits/README_EN.md +++ b/solution/2900-2999/2944.Minimum Number of Coins for Fruits/README_EN.md @@ -55,43 +55,10 @@ It can be proven that 2 is the minimum number of coins needed to acquire all the ## Solutions -**Method 1: Memoization Search** - -We define a function $dfs(i)$, which represents the minimum number of coins needed to buy all fruits starting from the $i$th fruit. So the answer is $dfs(1)$. - -The execution logic of the function $dfs(i)$ is as follows: - -- If $i \times 2 \geq n$, it means that we only need to buy the $i - 1$th fruit, and the remaining fruits can be obtained for free, so return $prices[i - 1]$. -- Otherwise, we can buy fruit $i$, and then choose a fruit $j$ to start buying from the next $i + 1$ to $2i + 1$ fruits, so $dfs(i) = prices[i - 1] + \min_{i + 1 \le j \le 2i + 1} dfs(j)$. - -To avoid repeated calculations, we use the method of memoization search, save the calculated results, and directly return the result when encountering the same situation next time. - -The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $prices$. - -**Method 2: Dynamic Programming** - -We can rewrite the memoization search in Method 1 into the form of dynamic programming. - -Similar to Method 1, we define $f[i]$ as the minimum number of coins needed to buy all fruits starting from the $i$th fruit. So the answer is $f[1]$. - -The state transition equation is $f[i] = \min_{i + 1 \le j \le 2i + 1} f[j] + prices[i - 1]$. - -In implementation, we calculate from back to front, and we can directly perform state transition on the array $prices$, which can save space. - -The time complexity is $O(n^2)$, where $n$ is the length of the array $prices$. The space complexity is $O(1)$. - -**Method 3: Dynamic Programming + Monotonic Queue Optimization** - -We observe the state transition equation in Method 2, and find that for each $i$, we need to find the minimum value of $f[i + 1], f[i + 2], \cdots, f[2i + 1]$, and as $i$ decreases, the range of these values is also decreasing. This is actually finding the minimum value of a monotonically narrowing sliding window, and we can use a monotonic queue to optimize. - -We calculate from back to front, maintain a monotonically increasing queue $q$, and the queue stores the index. If the head element of $q$ is greater than $i \times 2 + 1$, it means that the elements after $i$ will not be used, so we dequeue the head element. If $i$ is not greater than $(n - 1) / 2$, then we can add $prices[q[0] - 1]$ to $prices[i - 1]$, and then add $i$ to the tail of the queue. If the price of the fruit corresponding to the tail element of $q$ is greater than or equal to $prices[i - 1]$, then we dequeue the tail element until the price of the fruit corresponding to the tail element is less than $prices[i - 1]$ or the queue is empty, and then add $i$ to the tail of the queue. - -The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array $prices$. +### Solution 1 -### **Python3** - ```python class Solution: def minimumCoins(self, prices: List[int]) -> int: @@ -104,33 +71,6 @@ class Solution: return dfs(1) ``` -```python -class Solution: - def minimumCoins(self, prices: List[int]) -> int: - n = len(prices) - for i in range((n - 1) // 2, 0, -1): - prices[i - 1] += min(prices[i : i * 2 + 1]) - return prices[0] -``` - -```python -class Solution: - def minimumCoins(self, prices: List[int]) -> int: - n = len(prices) - q = deque() - for i in range(n, 0, -1): - while q and q[0] > i * 2 + 1: - q.popleft() - if i <= (n - 1) // 2: - prices[i - 1] += prices[q[0] - 1] - while q and prices[q[-1] - 1] >= prices[i - 1]: - q.pop() - q.append(i) - return prices[0] -``` - -### **Java** - ```java class Solution { private int[] prices; @@ -159,6 +99,85 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minimumCoins(vector& prices) { + int n = prices.size(); + int f[n + 1]; + memset(f, 0x3f, sizeof(f)); + function dfs = [&](int i) { + if (i * 2 >= n) { + return prices[i - 1]; + } + if (f[i] == 0x3f3f3f3f) { + for (int j = i + 1; j <= i * 2 + 1; ++j) { + f[i] = min(f[i], prices[i - 1] + dfs(j)); + } + } + return f[i]; + }; + return dfs(1); + } +}; +``` + +```go +func minimumCoins(prices []int) int { + n := len(prices) + f := make([]int, n+1) + var dfs func(int) int + dfs = func(i int) int { + if i*2 >= n { + return prices[i-1] + } + if f[i] == 0 { + f[i] = 1 << 30 + for j := i + 1; j <= i*2+1; j++ { + f[i] = min(f[i], dfs(j)+prices[i-1]) + } + } + return f[i] + } + return dfs(1) +} +``` + +```ts +function minimumCoins(prices: number[]): number { + const n = prices.length; + const f: number[] = Array(n + 1).fill(0); + const dfs = (i: number): number => { + if (i * 2 >= n) { + return prices[i - 1]; + } + if (f[i] === 0) { + f[i] = 1 << 30; + for (let j = i + 1; j <= i * 2 + 1; ++j) { + f[i] = Math.min(f[i], prices[i - 1] + dfs(j)); + } + } + return f[i]; + }; + return dfs(1); +} +``` + + + +### Solution 2 + + + +```python +class Solution: + def minimumCoins(self, prices: List[int]) -> int: + n = len(prices) + for i in range((n - 1) // 2, 0, -1): + prices[i - 1] += min(prices[i : i * 2 + 1]) + return prices[0] +``` + ```java class Solution { public int minimumCoins(int[] prices) { @@ -175,6 +194,59 @@ class Solution { } ``` +```cpp +class Solution { +public: + int minimumCoins(vector& prices) { + int n = prices.size(); + for (int i = (n - 1) / 2; i; --i) { + prices[i - 1] += *min_element(prices.begin() + i, prices.begin() + 2 * i + 1); + } + return prices[0]; + } +}; +``` + +```go +func minimumCoins(prices []int) int { + for i := (len(prices) - 1) / 2; i > 0; i-- { + prices[i-1] += slices.Min(prices[i : i*2+1]) + } + return prices[0] +} +``` + +```ts +function minimumCoins(prices: number[]): number { + for (let i = (prices.length - 1) >> 1; i; --i) { + prices[i - 1] += Math.min(...prices.slice(i, i * 2 + 1)); + } + return prices[0]; +} +``` + + + +### Solution 3 + + + +```python +class Solution: + def minimumCoins(self, prices: List[int]) -> int: + n = len(prices) + q = deque() + for i in range(n, 0, -1): + while q and q[0] > i * 2 + 1: + q.popleft() + if i <= (n - 1) // 2: + prices[i - 1] += prices[q[0] - 1] + while q and prices[q[-1] - 1] >= prices[i - 1]: + q.pop() + q.append(i) + return prices[0] +``` + ```java class Solution { public int minimumCoins(int[] prices) { @@ -197,44 +269,6 @@ class Solution { } ``` -### **C++** - -```cpp -class Solution { -public: - int minimumCoins(vector& prices) { - int n = prices.size(); - int f[n + 1]; - memset(f, 0x3f, sizeof(f)); - function dfs = [&](int i) { - if (i * 2 >= n) { - return prices[i - 1]; - } - if (f[i] == 0x3f3f3f3f) { - for (int j = i + 1; j <= i * 2 + 1; ++j) { - f[i] = min(f[i], prices[i - 1] + dfs(j)); - } - } - return f[i]; - }; - return dfs(1); - } -}; -``` - -```cpp -class Solution { -public: - int minimumCoins(vector& prices) { - int n = prices.size(); - for (int i = (n - 1) / 2; i; --i) { - prices[i - 1] += *min_element(prices.begin() + i, prices.begin() + 2 * i + 1); - } - return prices[0]; - } -}; -``` - ```cpp class Solution { public: @@ -258,38 +292,6 @@ public: }; ``` -### **Go** - -```go -func minimumCoins(prices []int) int { - n := len(prices) - f := make([]int, n+1) - var dfs func(int) int - dfs = func(i int) int { - if i*2 >= n { - return prices[i-1] - } - if f[i] == 0 { - f[i] = 1 << 30 - for j := i + 1; j <= i*2+1; j++ { - f[i] = min(f[i], dfs(j)+prices[i-1]) - } - } - return f[i] - } - return dfs(1) -} -``` - -```go -func minimumCoins(prices []int) int { - for i := (len(prices) - 1) / 2; i > 0; i-- { - prices[i-1] += slices.Min(prices[i : i*2+1]) - } - return prices[0] -} -``` - ```go func minimumCoins(prices []int) int { n := len(prices) @@ -368,37 +370,6 @@ func (q Deque) Get(i int) int { } ``` -### **TypeScript** - -```ts -function minimumCoins(prices: number[]): number { - const n = prices.length; - const f: number[] = Array(n + 1).fill(0); - const dfs = (i: number): number => { - if (i * 2 >= n) { - return prices[i - 1]; - } - if (f[i] === 0) { - f[i] = 1 << 30; - for (let j = i + 1; j <= i * 2 + 1; ++j) { - f[i] = Math.min(f[i], prices[i - 1] + dfs(j)); - } - } - return f[i]; - }; - return dfs(1); -} -``` - -```ts -function minimumCoins(prices: number[]): number { - for (let i = (prices.length - 1) >> 1; i; --i) { - prices[i - 1] += Math.min(...prices.slice(i, i * 2 + 1)); - } - return prices[0]; -} -``` - ```ts function minimumCoins(prices: number[]): number { const n = prices.length; @@ -515,10 +486,6 @@ class Deque { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/README.md b/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/README.md index 82f317e51d48e..c4ba563011fd7 100644 --- a/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/README.md +++ b/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/README.md @@ -57,14 +57,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findMaximumLength(self, nums: List[int]) -> int: @@ -80,10 +76,6 @@ class Solution: return f[n] ``` -### **Java** - - - ```java class Solution { public int findMaximumLength(int[] nums) { @@ -105,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -131,8 +121,6 @@ public: }; ``` -### **Go** - ```go func findMaximumLength(nums []int) int { n := len(nums) @@ -152,8 +140,6 @@ func findMaximumLength(nums []int) int { } ``` -### **TypeScript** - ```ts function findMaximumLength(nums: number[]): number { const n = nums.length; @@ -185,10 +171,6 @@ function findMaximumLength(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/README_EN.md b/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/README_EN.md index d4f46f47b32e1..497e978004053 100644 --- a/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/README_EN.md +++ b/solution/2900-2999/2945.Find Maximum Non-decreasing Array Length/README_EN.md @@ -53,9 +53,9 @@ Because the given array is not non-decreasing, the maximum +### Solution 1 -### **Python3** + ```python class Solution: @@ -72,8 +72,6 @@ class Solution: return f[n] ``` -### **Java** - ```java class Solution { public int findMaximumLength(int[] nums) { @@ -95,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -121,8 +117,6 @@ public: }; ``` -### **Go** - ```go func findMaximumLength(nums []int) int { n := len(nums) @@ -142,8 +136,6 @@ func findMaximumLength(nums []int) int { } ``` -### **TypeScript** - ```ts function findMaximumLength(nums: number[]): number { const n = nums.length; @@ -175,10 +167,6 @@ function findMaximumLength(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/README.md b/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/README.md index 5d8bdd7c7904d..8683dd3e02217 100644 --- a/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/README.md +++ b/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/README.md @@ -55,14 +55,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def areSimilar(self, mat: List[List[int]], k: int) -> bool: @@ -76,10 +72,6 @@ class Solution: return True ``` -### **Java** - - - ```java class Solution { public boolean areSimilar(int[][] mat, int k) { @@ -100,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -123,8 +113,6 @@ public: }; ``` -### **Go** - ```go func areSimilar(mat [][]int, k int) bool { n := len(mat[0]) @@ -143,8 +131,6 @@ func areSimilar(mat [][]int, k int) bool { } ``` -### **TypeScript** - ```ts function areSimilar(mat: number[][], k: number): boolean { const m = mat.length; @@ -164,10 +150,6 @@ function areSimilar(mat: number[][], k: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/README_EN.md b/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/README_EN.md index 1ba7aed904523..9c9b8fb666ee7 100644 --- a/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/README_EN.md +++ b/solution/2900-2999/2946.Matrix Similarity After Cyclic Shifts/README_EN.md @@ -51,9 +51,9 @@ Therefore, return true. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -68,8 +68,6 @@ class Solution: return True ``` -### **Java** - ```java class Solution { public boolean areSimilar(int[][] mat, int k) { @@ -90,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -113,8 +109,6 @@ public: }; ``` -### **Go** - ```go func areSimilar(mat [][]int, k int) bool { n := len(mat[0]) @@ -133,8 +127,6 @@ func areSimilar(mat [][]int, k int) bool { } ``` -### **TypeScript** - ```ts function areSimilar(mat: number[][], k: number): boolean { const m = mat.length; @@ -154,10 +146,6 @@ function areSimilar(mat: number[][], k: number): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2947.Count Beautiful Substrings I/README.md b/solution/2900-2999/2947.Count Beautiful Substrings I/README.md index 9746334a56dd2..b65eba9c39004 100644 --- a/solution/2900-2999/2947.Count Beautiful Substrings I/README.md +++ b/solution/2900-2999/2947.Count Beautiful Substrings I/README.md @@ -72,14 +72,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def beautifulSubstrings(self, s: str, k: int) -> int: @@ -96,10 +92,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int beautifulSubstrings(String s, int k) { @@ -124,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -152,8 +142,6 @@ public: }; ``` -### **Go** - ```go func beautifulSubstrings(s string, k int) (ans int) { n := len(s) @@ -175,8 +163,6 @@ func beautifulSubstrings(s string, k int) (ans int) { } ``` -### **TypeScript** - ```ts function beautifulSubstrings(s: string, k: number): number { const n = s.length; @@ -199,10 +185,6 @@ function beautifulSubstrings(s: string, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2947.Count Beautiful Substrings I/README_EN.md b/solution/2900-2999/2947.Count Beautiful Substrings I/README_EN.md index b217f351bd52a..fbf0c02aa0a10 100644 --- a/solution/2900-2999/2947.Count Beautiful Substrings I/README_EN.md +++ b/solution/2900-2999/2947.Count Beautiful Substrings I/README_EN.md @@ -68,9 +68,9 @@ It can be shown that there are only 3 beautiful substrings in the given string. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -88,8 +88,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int beautifulSubstrings(String s, int k) { @@ -114,8 +112,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -142,8 +138,6 @@ public: }; ``` -### **Go** - ```go func beautifulSubstrings(s string, k int) (ans int) { n := len(s) @@ -165,8 +159,6 @@ func beautifulSubstrings(s string, k int) (ans int) { } ``` -### **TypeScript** - ```ts function beautifulSubstrings(s: string, k: number): number { const n = s.length; @@ -189,10 +181,6 @@ function beautifulSubstrings(s: string, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README.md b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README.md index e2a94fb123be9..b8e26c87de0c3 100644 --- a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README.md +++ b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README.md @@ -60,14 +60,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]: @@ -86,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] lexicographicallySmallestArray(int[] nums, int limit) { @@ -117,8 +109,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -147,8 +137,6 @@ public: }; ``` -### **Go** - ```go func lexicographicallySmallestArray(nums []int, limit int) []int { n := len(nums) @@ -174,8 +162,6 @@ func lexicographicallySmallestArray(nums []int, limit int) []int { } ``` -### **TypeScript** - ```ts function lexicographicallySmallestArray(nums: number[], limit: number): number[] { const n: number = nums.length; @@ -197,10 +183,6 @@ function lexicographicallySmallestArray(nums: number[], limit: number): number[] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README_EN.md b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README_EN.md index f1c079832d3b2..e581cb2701487 100644 --- a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README_EN.md +++ b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README_EN.md @@ -56,9 +56,9 @@ We cannot obtain a lexicographically smaller array by applying any more operatio ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -78,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] lexicographicallySmallestArray(int[] nums, int limit) { @@ -107,8 +105,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +133,6 @@ public: }; ``` -### **Go** - ```go func lexicographicallySmallestArray(nums []int, limit int) []int { n := len(nums) @@ -164,8 +158,6 @@ func lexicographicallySmallestArray(nums []int, limit int) []int { } ``` -### **TypeScript** - ```ts function lexicographicallySmallestArray(nums: number[], limit: number): number[] { const n: number = nums.length; @@ -187,10 +179,6 @@ function lexicographicallySmallestArray(nums: number[], limit: number): number[] } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2949.Count Beautiful Substrings II/README.md b/solution/2900-2999/2949.Count Beautiful Substrings II/README.md index 900153ae072c1..b261181de472a 100644 --- a/solution/2900-2999/2949.Count Beautiful Substrings II/README.md +++ b/solution/2900-2999/2949.Count Beautiful Substrings II/README.md @@ -72,42 +72,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2900-2999/2949.Count Beautiful Substrings II/README_EN.md b/solution/2900-2999/2949.Count Beautiful Substrings II/README_EN.md index 3071fcd40a06a..569539e990b0a 100644 --- a/solution/2900-2999/2949.Count Beautiful Substrings II/README_EN.md +++ b/solution/2900-2999/2949.Count Beautiful Substrings II/README_EN.md @@ -68,36 +68,4 @@ It can be shown that there are only 3 beautiful substrings in the given string. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/2900-2999/2950.Number of Divisible Substrings/README.md b/solution/2900-2999/2950.Number of Divisible Substrings/README.md index 9799e0a9c1278..582321422b2af 100644 --- a/solution/2900-2999/2950.Number of Divisible Substrings/README.md +++ b/solution/2900-2999/2950.Number of Divisible Substrings/README.md @@ -137,9 +137,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们先用一个哈希表或数组 $mp$ 记录每个字母对应的数字。 @@ -149,22 +147,8 @@ 时间复杂度 $O(n^2)$,空间复杂度 $O(C)$。其中 $n$ 是字符串 $word$ 的长度,而 $C$ 是字符集的大小,本题中 $C=26$。 -**方法二:哈希表 + 前缀和 + 枚举** - -与方法一类似,我们先用一个哈希表或数组 $mp$ 记录每个字母对应的数字。 - -如果一个整数子数组的数字之和能被它的长度整除,那么这个子数组的平均值一定是一个整数。而由于子数组中每个元素的数字都在 $[1, 9]$ 范围内,因此子数组的平均值只能是 $1, 2, \cdots, 9$ 中的一个。 - -我们可以枚举子数组的平均值 $i$,如果一个子数组的元素和能被 $i$ 整除,假设子数组为 $a_1, a_2, \cdots, a_k$,那么 $a_1 + a_2 + \cdots + a_k = i \times k$,即 $(a_1 - i) + (a_2 - i) + \cdots + (a_k - i) = 0$。如果我们把 $a_k - i$ 视为一个新的元素 $b_k$,那么原来的子数组就变成了 $b_1, b_2, \cdots, b_k$,其中 $b_1 + b_2 + \cdots + b_k = 0$。我们只需要求出新的数组中,有多少个子数组的元素和为 $0$ 即可,这可以用“哈希表”结合“前缀和”来实现。 - -时间复杂度 $O(10 \times n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $word$ 的长度。 - -### **Python3** - - - ```python class Solution: def countDivisibleSubstrings(self, word: str) -> int: @@ -183,30 +167,6 @@ class Solution: return ans ``` -```python -class Solution: - def countDivisibleSubstrings(self, word: str) -> int: - d = ["ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"] - mp = {} - for i, s in enumerate(d, 1): - for c in s: - mp[c] = i - ans = 0 - for i in range(1, 10): - cnt = defaultdict(int) - cnt[0] = 1 - s = 0 - for c in word: - s += mp[c] - i - ans += cnt[s] - cnt[s] += 1 - return ans -``` - -### **Java** - - - ```java class Solution { public int countDivisibleSubstrings(String word) { @@ -231,35 +191,6 @@ class Solution { } ``` -```java -class Solution { - public int countDivisibleSubstrings(String word) { - String[] d = {"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"}; - int[] mp = new int[26]; - for (int i = 0; i < d.length; ++i) { - for (char c : d[i].toCharArray()) { - mp[c - 'a'] = i + 1; - } - } - int ans = 0; - char[] cs = word.toCharArray(); - for (int i = 1; i < 10; ++i) { - Map cnt = new HashMap<>(); - cnt.put(0, 1); - int s = 0; - for (char c : cs) { - s += mp[c - 'a'] - i; - ans += cnt.getOrDefault(s, 0); - cnt.merge(s, 1, Integer::sum); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -285,33 +216,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countDivisibleSubstrings(string word) { - string d[9] = {"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"}; - int mp[26]{}; - for (int i = 0; i < 9; ++i) { - for (char& c : d[i]) { - mp[c - 'a'] = i + 1; - } - } - int ans = 0; - for (int i = 1; i < 10; ++i) { - unordered_map cnt{{0, 1}}; - int s = 0; - for (char& c : word) { - s += mp[c - 'a'] - i; - ans += cnt[s]++; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func countDivisibleSubstrings(word string) (ans int) { d := []string{"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"} @@ -335,30 +239,6 @@ func countDivisibleSubstrings(word string) (ans int) { } ``` -```go -func countDivisibleSubstrings(word string) (ans int) { - d := []string{"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"} - mp := [26]int{} - for i, s := range d { - for _, c := range s { - mp[c-'a'] = i + 1 - } - } - for i := 0; i < 10; i++ { - cnt := map[int]int{0: 1} - s := 0 - for _, c := range word { - s += mp[c-'a'] - i - ans += cnt[s] - cnt[s]++ - } - } - return -} -``` - -### **TypeScript** - ```ts function countDivisibleSubstrings(word: string): number { const d: string[] = ['ab', 'cde', 'fgh', 'ijk', 'lmn', 'opq', 'rst', 'uvw', 'xyz']; @@ -383,33 +263,6 @@ function countDivisibleSubstrings(word: string): number { } ``` -```ts -function countDivisibleSubstrings(word: string): number { - const d = ['ab', 'cde', 'fgh', 'ijk', 'lmn', 'opq', 'rst', 'uvw', 'xyz']; - const mp: number[] = Array(26).fill(0); - - d.forEach((s, i) => { - for (const c of s) { - mp[c.charCodeAt(0) - 'a'.charCodeAt(0)] = i + 1; - } - }); - - let ans = 0; - for (let i = 0; i < 10; i++) { - const cnt: { [key: number]: number } = { 0: 1 }; - let s = 0; - for (const c of word) { - s += mp[c.charCodeAt(0) - 'a'.charCodeAt(0)] - i; - ans += cnt[s] || 0; - cnt[s] = (cnt[s] || 0) + 1; - } - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn count_divisible_substrings(word: String) -> i32 { @@ -439,6 +292,139 @@ impl Solution { } ``` + + +### 方法二:哈希表 + 前缀和 + 枚举 + +与方法一类似,我们先用一个哈希表或数组 $mp$ 记录每个字母对应的数字。 + +如果一个整数子数组的数字之和能被它的长度整除,那么这个子数组的平均值一定是一个整数。而由于子数组中每个元素的数字都在 $[1, 9]$ 范围内,因此子数组的平均值只能是 $1, 2, \cdots, 9$ 中的一个。 + +我们可以枚举子数组的平均值 $i$,如果一个子数组的元素和能被 $i$ 整除,假设子数组为 $a_1, a_2, \cdots, a_k$,那么 $a_1 + a_2 + \cdots + a_k = i \times k$,即 $(a_1 - i) + (a_2 - i) + \cdots + (a_k - i) = 0$。如果我们把 $a_k - i$ 视为一个新的元素 $b_k$,那么原来的子数组就变成了 $b_1, b_2, \cdots, b_k$,其中 $b_1 + b_2 + \cdots + b_k = 0$。我们只需要求出新的数组中,有多少个子数组的元素和为 $0$ 即可,这可以用“哈希表”结合“前缀和”来实现。 + +时间复杂度 $O(10 \times n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $word$ 的长度。 + + + +```python +class Solution: + def countDivisibleSubstrings(self, word: str) -> int: + d = ["ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"] + mp = {} + for i, s in enumerate(d, 1): + for c in s: + mp[c] = i + ans = 0 + for i in range(1, 10): + cnt = defaultdict(int) + cnt[0] = 1 + s = 0 + for c in word: + s += mp[c] - i + ans += cnt[s] + cnt[s] += 1 + return ans +``` + +```java +class Solution { + public int countDivisibleSubstrings(String word) { + String[] d = {"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"}; + int[] mp = new int[26]; + for (int i = 0; i < d.length; ++i) { + for (char c : d[i].toCharArray()) { + mp[c - 'a'] = i + 1; + } + } + int ans = 0; + char[] cs = word.toCharArray(); + for (int i = 1; i < 10; ++i) { + Map cnt = new HashMap<>(); + cnt.put(0, 1); + int s = 0; + for (char c : cs) { + s += mp[c - 'a'] - i; + ans += cnt.getOrDefault(s, 0); + cnt.merge(s, 1, Integer::sum); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int countDivisibleSubstrings(string word) { + string d[9] = {"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"}; + int mp[26]{}; + for (int i = 0; i < 9; ++i) { + for (char& c : d[i]) { + mp[c - 'a'] = i + 1; + } + } + int ans = 0; + for (int i = 1; i < 10; ++i) { + unordered_map cnt{{0, 1}}; + int s = 0; + for (char& c : word) { + s += mp[c - 'a'] - i; + ans += cnt[s]++; + } + } + return ans; + } +}; +``` + +```go +func countDivisibleSubstrings(word string) (ans int) { + d := []string{"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"} + mp := [26]int{} + for i, s := range d { + for _, c := range s { + mp[c-'a'] = i + 1 + } + } + for i := 0; i < 10; i++ { + cnt := map[int]int{0: 1} + s := 0 + for _, c := range word { + s += mp[c-'a'] - i + ans += cnt[s] + cnt[s]++ + } + } + return +} +``` + +```ts +function countDivisibleSubstrings(word: string): number { + const d = ['ab', 'cde', 'fgh', 'ijk', 'lmn', 'opq', 'rst', 'uvw', 'xyz']; + const mp: number[] = Array(26).fill(0); + + d.forEach((s, i) => { + for (const c of s) { + mp[c.charCodeAt(0) - 'a'.charCodeAt(0)] = i + 1; + } + }); + + let ans = 0; + for (let i = 0; i < 10; i++) { + const cnt: { [key: number]: number } = { 0: 1 }; + let s = 0; + for (const c of word) { + s += mp[c.charCodeAt(0) - 'a'.charCodeAt(0)] - i; + ans += cnt[s] || 0; + cnt[s] = (cnt[s] || 0) + 1; + } + } + return ans; +} +``` + ```rust use std::collections::HashMap; @@ -467,10 +453,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2950.Number of Divisible Substrings/README_EN.md b/solution/2900-2999/2950.Number of Divisible Substrings/README_EN.md index a25e82e071a56..028c4836de1ec 100644 --- a/solution/2900-2999/2950.Number of Divisible Substrings/README_EN.md +++ b/solution/2900-2999/2950.Number of Divisible Substrings/README_EN.md @@ -133,7 +133,7 @@ It can be shown that there are no other substrings of word that are divisible. ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration First, we use a hash table or array $mp$ to record the number corresponding to each letter. @@ -143,20 +143,8 @@ After the enumeration is over, return the answer. The time complexity is $O(n^2)$, and the space complexity is $O(C)$. Where $n$ is the length of the string $word$, and $C$ is the size of the character set, in this question $C=26$. -**Solution 2: Hash Table + Prefix Sum + Enumeration** - -Similar to Solution 1, we first use a hash table or array $mp$ to record the number corresponding to each letter. - -If the sum of the numbers in an integer subarray can be divided by its length, then the average value of this subarray must be an integer. And because the number of each element in the subarray is in the range of $[1, 9]$, the average value of the subarray can only be one of $1, 2, \cdots, 9$. - -We can enumerate the average value $i$ of the subarray. If the sum of the elements in a subarray can be divided by $i$, suppose the subarray is $a_1, a_2, \cdots, a_k$, then $a_1 + a_2 + \cdots + a_k = i \times k$, that is, $(a_1 - i) + (a_2 - i) + \cdots + (a_k - i) = 0$. If we regard $a_k - i$ as a new element $b_k$, then the original subarray becomes $b_1, b_2, \cdots, b_k$, where $b_1 + b_2 + \cdots + b_k = 0$. We only need to find out how many subarrays in the new array have an element sum of $0$, which can be implemented with "hash table" combined with "prefix sum". - -The time complexity is $O(10 \times n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $word$. - -### **Python3** - ```python class Solution: def countDivisibleSubstrings(self, word: str) -> int: @@ -175,28 +163,6 @@ class Solution: return ans ``` -```python -class Solution: - def countDivisibleSubstrings(self, word: str) -> int: - d = ["ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"] - mp = {} - for i, s in enumerate(d, 1): - for c in s: - mp[c] = i - ans = 0 - for i in range(1, 10): - cnt = defaultdict(int) - cnt[0] = 1 - s = 0 - for c in word: - s += mp[c] - i - ans += cnt[s] - cnt[s] += 1 - return ans -``` - -### **Java** - ```java class Solution { public int countDivisibleSubstrings(String word) { @@ -221,35 +187,6 @@ class Solution { } ``` -```java -class Solution { - public int countDivisibleSubstrings(String word) { - String[] d = {"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"}; - int[] mp = new int[26]; - for (int i = 0; i < d.length; ++i) { - for (char c : d[i].toCharArray()) { - mp[c - 'a'] = i + 1; - } - } - int ans = 0; - char[] cs = word.toCharArray(); - for (int i = 1; i < 10; ++i) { - Map cnt = new HashMap<>(); - cnt.put(0, 1); - int s = 0; - for (char c : cs) { - s += mp[c - 'a'] - i; - ans += cnt.getOrDefault(s, 0); - cnt.merge(s, 1, Integer::sum); - } - } - return ans; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -275,33 +212,6 @@ public: }; ``` -```cpp -class Solution { -public: - int countDivisibleSubstrings(string word) { - string d[9] = {"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"}; - int mp[26]{}; - for (int i = 0; i < 9; ++i) { - for (char& c : d[i]) { - mp[c - 'a'] = i + 1; - } - } - int ans = 0; - for (int i = 1; i < 10; ++i) { - unordered_map cnt{{0, 1}}; - int s = 0; - for (char& c : word) { - s += mp[c - 'a'] - i; - ans += cnt[s]++; - } - } - return ans; - } -}; -``` - -### **Go** - ```go func countDivisibleSubstrings(word string) (ans int) { d := []string{"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"} @@ -325,30 +235,6 @@ func countDivisibleSubstrings(word string) (ans int) { } ``` -```go -func countDivisibleSubstrings(word string) (ans int) { - d := []string{"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"} - mp := [26]int{} - for i, s := range d { - for _, c := range s { - mp[c-'a'] = i + 1 - } - } - for i := 0; i < 10; i++ { - cnt := map[int]int{0: 1} - s := 0 - for _, c := range word { - s += mp[c-'a'] - i - ans += cnt[s] - cnt[s]++ - } - } - return -} -``` - -### **TypeScript** - ```ts function countDivisibleSubstrings(word: string): number { const d: string[] = ['ab', 'cde', 'fgh', 'ijk', 'lmn', 'opq', 'rst', 'uvw', 'xyz']; @@ -373,33 +259,6 @@ function countDivisibleSubstrings(word: string): number { } ``` -```ts -function countDivisibleSubstrings(word: string): number { - const d = ['ab', 'cde', 'fgh', 'ijk', 'lmn', 'opq', 'rst', 'uvw', 'xyz']; - const mp: number[] = Array(26).fill(0); - - d.forEach((s, i) => { - for (const c of s) { - mp[c.charCodeAt(0) - 'a'.charCodeAt(0)] = i + 1; - } - }); - - let ans = 0; - for (let i = 0; i < 10; i++) { - const cnt: { [key: number]: number } = { 0: 1 }; - let s = 0; - for (const c of word) { - s += mp[c.charCodeAt(0) - 'a'.charCodeAt(0)] - i; - ans += cnt[s] || 0; - cnt[s] = (cnt[s] || 0) + 1; - } - } - return ans; -} -``` - -### **Rust** - ```rust impl Solution { pub fn count_divisible_substrings(word: String) -> i32 { @@ -429,6 +288,139 @@ impl Solution { } ``` + + +### Solution 2: Hash Table + Prefix Sum + Enumeration + +Similar to Solution 1, we first use a hash table or array $mp$ to record the number corresponding to each letter. + +If the sum of the numbers in an integer subarray can be divided by its length, then the average value of this subarray must be an integer. And because the number of each element in the subarray is in the range of $[1, 9]$, the average value of the subarray can only be one of $1, 2, \cdots, 9$. + +We can enumerate the average value $i$ of the subarray. If the sum of the elements in a subarray can be divided by $i$, suppose the subarray is $a_1, a_2, \cdots, a_k$, then $a_1 + a_2 + \cdots + a_k = i \times k$, that is, $(a_1 - i) + (a_2 - i) + \cdots + (a_k - i) = 0$. If we regard $a_k - i$ as a new element $b_k$, then the original subarray becomes $b_1, b_2, \cdots, b_k$, where $b_1 + b_2 + \cdots + b_k = 0$. We only need to find out how many subarrays in the new array have an element sum of $0$, which can be implemented with "hash table" combined with "prefix sum". + +The time complexity is $O(10 \times n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $word$. + + + +```python +class Solution: + def countDivisibleSubstrings(self, word: str) -> int: + d = ["ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"] + mp = {} + for i, s in enumerate(d, 1): + for c in s: + mp[c] = i + ans = 0 + for i in range(1, 10): + cnt = defaultdict(int) + cnt[0] = 1 + s = 0 + for c in word: + s += mp[c] - i + ans += cnt[s] + cnt[s] += 1 + return ans +``` + +```java +class Solution { + public int countDivisibleSubstrings(String word) { + String[] d = {"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"}; + int[] mp = new int[26]; + for (int i = 0; i < d.length; ++i) { + for (char c : d[i].toCharArray()) { + mp[c - 'a'] = i + 1; + } + } + int ans = 0; + char[] cs = word.toCharArray(); + for (int i = 1; i < 10; ++i) { + Map cnt = new HashMap<>(); + cnt.put(0, 1); + int s = 0; + for (char c : cs) { + s += mp[c - 'a'] - i; + ans += cnt.getOrDefault(s, 0); + cnt.merge(s, 1, Integer::sum); + } + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int countDivisibleSubstrings(string word) { + string d[9] = {"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"}; + int mp[26]{}; + for (int i = 0; i < 9; ++i) { + for (char& c : d[i]) { + mp[c - 'a'] = i + 1; + } + } + int ans = 0; + for (int i = 1; i < 10; ++i) { + unordered_map cnt{{0, 1}}; + int s = 0; + for (char& c : word) { + s += mp[c - 'a'] - i; + ans += cnt[s]++; + } + } + return ans; + } +}; +``` + +```go +func countDivisibleSubstrings(word string) (ans int) { + d := []string{"ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"} + mp := [26]int{} + for i, s := range d { + for _, c := range s { + mp[c-'a'] = i + 1 + } + } + for i := 0; i < 10; i++ { + cnt := map[int]int{0: 1} + s := 0 + for _, c := range word { + s += mp[c-'a'] - i + ans += cnt[s] + cnt[s]++ + } + } + return +} +``` + +```ts +function countDivisibleSubstrings(word: string): number { + const d = ['ab', 'cde', 'fgh', 'ijk', 'lmn', 'opq', 'rst', 'uvw', 'xyz']; + const mp: number[] = Array(26).fill(0); + + d.forEach((s, i) => { + for (const c of s) { + mp[c.charCodeAt(0) - 'a'.charCodeAt(0)] = i + 1; + } + }); + + let ans = 0; + for (let i = 0; i < 10; i++) { + const cnt: { [key: number]: number } = { 0: 1 }; + let s = 0; + for (const c of word) { + s += mp[c.charCodeAt(0) - 'a'.charCodeAt(0)] - i; + ans += cnt[s] || 0; + cnt[s] = (cnt[s] || 0) + 1; + } + } + return ans; +} +``` + ```rust use std::collections::HashMap; @@ -457,10 +449,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2951.Find the Peaks/README.md b/solution/2900-2999/2951.Find the Peaks/README.md index 0c7bde3aa2d0f..c9b4d8b424349 100644 --- a/solution/2900-2999/2951.Find the Peaks/README.md +++ b/solution/2900-2999/2951.Find the Peaks/README.md @@ -51,9 +51,7 @@ mountain[2] 也不可能是峰值,因为它不严格大于 mountain[3] 和 mou ## 解法 - - -**方法一:直接遍历** +### 方法一:直接遍历 我们直接遍历下标 $i \in [1, n-2]$,对于每个下标 $i$,如果满足 $mountain[i-1] < mountain[i]$ 并且 $mountain[i + 1] < mountain[i]$,那么 $mountain[i]$ 就是一个峰值,我们将下标 $i$ 加入答案数组中。 @@ -63,10 +61,6 @@ mountain[2] 也不可能是峰值,因为它不严格大于 mountain[3] 和 mou -### **Python3** - - - ```python class Solution: def findPeaks(self, mountain: List[int]) -> List[int]: @@ -77,10 +71,6 @@ class Solution: ] ``` -### **Java** - - - ```java class Solution { public List findPeaks(int[] mountain) { @@ -95,8 +85,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +100,6 @@ public: }; ``` -### **Go** - ```go func findPeaks(mountain []int) (ans []int) { for i := 1; i < len(mountain)-1; i++ { @@ -125,8 +111,6 @@ func findPeaks(mountain []int) (ans []int) { } ``` -### **TypeScript** - ```ts function findPeaks(mountain: number[]): number[] { const ans: number[] = []; @@ -139,10 +123,6 @@ function findPeaks(mountain: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2951.Find the Peaks/README_EN.md b/solution/2900-2999/2951.Find the Peaks/README_EN.md index 120b9ec576c02..d5db9cc1e3b7a 100644 --- a/solution/2900-2999/2951.Find the Peaks/README_EN.md +++ b/solution/2900-2999/2951.Find the Peaks/README_EN.md @@ -47,7 +47,7 @@ So the answer is [1,3]. ## Solutions -**Solution 1: Direct Traversal** +### Solution 1: Direct Traversal We directly traverse the index $i \in [1, n-2]$. For each index $i$, if $mountain[i-1] < mountain[i]$ and $mountain[i + 1] < mountain[i]$, then $mountain[i]$ is a peak, and we add index $i$ to the answer array. @@ -57,8 +57,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. Ignoring th -### **Python3** - ```python class Solution: def findPeaks(self, mountain: List[int]) -> List[int]: @@ -69,8 +67,6 @@ class Solution: ] ``` -### **Java** - ```java class Solution { public List findPeaks(int[] mountain) { @@ -85,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +96,6 @@ public: }; ``` -### **Go** - ```go func findPeaks(mountain []int) (ans []int) { for i := 1; i < len(mountain)-1; i++ { @@ -115,8 +107,6 @@ func findPeaks(mountain []int) (ans []int) { } ``` -### **TypeScript** - ```ts function findPeaks(mountain: number[]): number[] { const ans: number[] = []; @@ -129,10 +119,6 @@ function findPeaks(mountain: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2952.Minimum Number of Coins to be Added/README.md b/solution/2900-2999/2952.Minimum Number of Coins to be Added/README.md index cc8090e23dde6..8c5d96c5f922b 100644 --- a/solution/2900-2999/2952.Minimum Number of Coins to be Added/README.md +++ b/solution/2900-2999/2952.Minimum Number of Coins to be Added/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:贪心 + 构造** +### 方法一:贪心 + 构造 我们不妨假设当前需要构造的金额为 $s$,且我们已经构造出了 $[0,...,s-1]$ 内的所有金额。如果此时有一个新的硬币 $x$,我们把它加入到数组中,可以构造出 $[x, s+x-1]$ 内的所有金额。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def minimumAddedCoins(self, coins: List[int], target: int) -> int: @@ -91,10 +85,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int minimumAddedCoins(int[] coins, int target) { @@ -113,8 +103,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -134,8 +122,6 @@ public: }; ``` -### **Go** - ```go func minimumAddedCoins(coins []int, target int) (ans int) { slices.Sort(coins) @@ -152,8 +138,6 @@ func minimumAddedCoins(coins []int, target int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumAddedCoins(coins: number[], target: number): number { coins.sort((a, b) => a - b); @@ -170,10 +154,6 @@ function minimumAddedCoins(coins: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2952.Minimum Number of Coins to be Added/README_EN.md b/solution/2900-2999/2952.Minimum Number of Coins to be Added/README_EN.md index 97cda50a350d8..d23fe2de9e172 100644 --- a/solution/2900-2999/2952.Minimum Number of Coins to be Added/README_EN.md +++ b/solution/2900-2999/2952.Minimum Number of Coins to be Added/README_EN.md @@ -51,7 +51,7 @@ It can be shown that all integers from 1 to 20 are obtainable from the resulting ## Solutions -**Solution 1: Greedy + Construction** +### Solution 1: Greedy + Construction Suppose the current amount we need to construct is $s$, and we have already constructed all amounts in $[0,...,s-1]$. If there is a new coin $x$, we add it to the array, which can construct all amounts in $[x, s+x-1]$. @@ -66,8 +66,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log -### **Python3** - ```python class Solution: def minimumAddedCoins(self, coins: List[int], target: int) -> int: @@ -84,8 +82,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int minimumAddedCoins(int[] coins, int target) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +119,6 @@ public: }; ``` -### **Go** - ```go func minimumAddedCoins(coins []int, target int) (ans int) { slices.Sort(coins) @@ -143,8 +135,6 @@ func minimumAddedCoins(coins []int, target int) (ans int) { } ``` -### **TypeScript** - ```ts function minimumAddedCoins(coins: number[], target: number): number { coins.sort((a, b) => a - b); @@ -161,10 +151,6 @@ function minimumAddedCoins(coins: number[], target: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2953.Count Complete Substrings/README.md b/solution/2900-2999/2953.Count Complete Substrings/README.md index 0de542f6c0bd3..d2a1df826d831 100644 --- a/solution/2900-2999/2953.Count Complete Substrings/README.md +++ b/solution/2900-2999/2953.Count Complete Substrings/README.md @@ -49,9 +49,7 @@ ## 解法 - - -**方法一:枚举字符种类数 + 滑动窗口** +### 方法一:枚举字符种类数 + 滑动窗口 根据题目描述中的条件 $2$,我们可以发现,一个完全字符串中,相邻两个字符之差不超过 $2$。因此,我们遍历字符串 $word$,可以利用双指针把 $word$ 分割成若干个子字符串,这些子字符串中的字符种类数不超过 $26$,且相邻字符之差不超过 $2$。接下来,我们只需要在每个子字符串中,统计每个字符都出现 $k$ 次的子字符串的个数即可。 @@ -63,10 +61,6 @@ -### **Python3** - - - ```python class Solution: def countCompleteSubstrings(self, word: str, k: int) -> int: @@ -103,10 +97,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countCompleteSubstrings(String word, int k) { @@ -161,8 +151,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -218,8 +206,6 @@ public: }; ``` -### **Go** - ```go func countCompleteSubstrings(word string, k int) (ans int) { n := len(word) @@ -277,8 +263,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function countCompleteSubstrings(word: string, k: number): number { const f = (s: string): number => { @@ -335,10 +319,6 @@ function countCompleteSubstrings(word: string, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2953.Count Complete Substrings/README_EN.md b/solution/2900-2999/2953.Count Complete Substrings/README_EN.md index 187760da3bf78..385121bedb1ea 100644 --- a/solution/2900-2999/2953.Count Complete Substrings/README_EN.md +++ b/solution/2900-2999/2953.Count Complete Substrings/README_EN.md @@ -45,7 +45,7 @@ ## Solutions -**Solution 1: Enumerate Character Types + Sliding Window** +### Solution 1: Enumerate Character Types + Sliding Window According to condition 2 in the problem description, we can find that in a complete string, the difference between two adjacent characters does not exceed 2. Therefore, we traverse the string $word$, and we can use two pointers to split $word$ into several substrings. The number of character types in these substrings does not exceed 26, and the difference between adjacent characters does not exceed 2. Next, we only need to count the number of substrings in each substring where each character appears $k$ times. @@ -57,8 +57,6 @@ The time complexity is $O(n \times |\Sigma|)$, and the space complexity is $O(|\ -### **Python3** - ```python class Solution: def countCompleteSubstrings(self, word: str, k: int) -> int: @@ -95,8 +93,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countCompleteSubstrings(String word, int k) { @@ -151,8 +147,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -208,8 +202,6 @@ public: }; ``` -### **Go** - ```go func countCompleteSubstrings(word string, k int) (ans int) { n := len(word) @@ -267,8 +259,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function countCompleteSubstrings(word: string, k: number): number { const f = (s: string): number => { @@ -325,10 +315,6 @@ function countCompleteSubstrings(word: string, k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2954.Count the Number of Infection Sequences/README.md b/solution/2900-2999/2954.Count the Number of Infection Sequences/README.md index 81da0f6680ef2..c5176868955f6 100644 --- a/solution/2900-2999/2954.Count the Number of Infection Sequences/README.md +++ b/solution/2900-2999/2954.Count the Number of Infection Sequences/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:组合数学 + 乘法逆元 + 快速幂** +### 方法一:组合数学 + 乘法逆元 + 快速幂 根据题目描述,感冒的小朋友把还没有感冒的小朋友划分成了若干个连续段。我们可以用一个数组 $nums$ 记录每一段不感冒的小朋友的认识,不感冒人数一共有 $s = \sum_{i=0}^{k} nums[k]$ 人。我们可以发现,感冒序列的数目就是 $s$ 个不同元素的全排列数,即 $s!$。 @@ -80,10 +78,6 @@ $$ -### **Python3** - - - ```python mod = 10**9 + 7 mx = 10**5 @@ -107,10 +101,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private static final int MOD = (int) (1e9 + 7); @@ -163,8 +153,6 @@ class Solution { } ``` -### **C++** - ```cpp const int MX = 1e5; const int MOD = 1e9 + 7; @@ -218,8 +206,6 @@ public: }; ``` -### **Go** - ```go const MX = 1e5 const MOD = 1e9 + 7 @@ -274,8 +260,6 @@ func numberOfSequence(n int, sick []int) int { } ``` -### **TypeScript** - ```ts const MX = 1e5; const MOD: bigint = BigInt(1e9 + 7); @@ -325,10 +309,6 @@ function numberOfSequence(n: number, sick: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2954.Count the Number of Infection Sequences/README_EN.md b/solution/2900-2999/2954.Count the Number of Infection Sequences/README_EN.md index b916e1b20147b..de5a981962cce 100644 --- a/solution/2900-2999/2954.Count the Number of Infection Sequences/README_EN.md +++ b/solution/2900-2999/2954.Count the Number of Infection Sequences/README_EN.md @@ -54,7 +54,7 @@ Finally, the child at position 2 gets infected because it is adjacent to childre ## Solutions -**Solution 1: Combinatorial Mathematics + Multiplicative Inverse + Fast Power** +### Solution 1: Combinatorial Mathematics + Multiplicative Inverse + Fast Power According to the problem description, the children who have a cold have divided the children who have not yet caught a cold into several continuous segments. We can use an array $nums$ to record the number of children who are not cold in each segment, and there are a total of $s = \sum_{i=0}^{k} nums[k]$ children who are not cold. We can find that the number of cold sequences is the number of permutations of $s$ different elements, that is, $s!$. @@ -74,8 +74,6 @@ The time complexity is $O(m)$, where $m$ is the length of the array $sick$. Igno -### **Python3** - ```python mod = 10**9 + 7 mx = 10**5 @@ -99,8 +97,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private static final int MOD = (int) (1e9 + 7); @@ -153,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp const int MX = 1e5; const int MOD = 1e9 + 7; @@ -208,8 +202,6 @@ public: }; ``` -### **Go** - ```go const MX = 1e5 const MOD = 1e9 + 7 @@ -264,8 +256,6 @@ func numberOfSequence(n int, sick []int) int { } ``` -### **TypeScript** - ```ts const MX = 1e5; const MOD: bigint = BigInt(1e9 + 7); @@ -315,10 +305,6 @@ function numberOfSequence(n: number, sick: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2955.Number of Same-End Substrings/README.md b/solution/2900-2999/2955.Number of Same-End Substrings/README.md index 1a7eaf29e6c6c..bdf7cb40c94ac 100644 --- a/solution/2900-2999/2955.Number of Same-End Substrings/README.md +++ b/solution/2900-2999/2955.Number of Same-End Substrings/README.md @@ -48,9 +48,7 @@ ## 解法 - - -**方法一:前缀和 + 枚举** +### 方法一:前缀和 + 枚举 我们可以预处理出每个字母的前缀和,记录在数组 $cnt$ 中,其中 $cnt[i][j]$ 表示第 $i$ 个字母在前 $j$ 个字符中出现的次数。这样,对于每个区间 $[l, r]$,我们可以枚举区间中的每个字母 $c$,利用前缀和数组快速计算出 $c$ 在区间中出现的次数 $x$,我们任取其中两个,即可组成一个同尾子串,子串数为 $C_x^2=\frac{x(x-1)}{2}$,加上区间中每个字母可以单独组成同尾子串的情况,一共有 $r - l + 1$ 个字母。因此,对于每个查询 $[l, r]$,满足条件的同尾子串数为 $r - l + 1 + \sum_{c \in \Sigma} \frac{x_c(x_c-1)}{2}$,其中 $x_c$ 表示字母 $c$ 在区间 $[l, r]$ 中出现的次数。 @@ -58,10 +56,6 @@ -### **Python3** - - - ```python class Solution: def sameEndSubstringCount(self, s: str, queries: List[List[int]]) -> List[int]: @@ -82,10 +76,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] sameEndSubstringCount(String s, int[][] queries) { @@ -112,8 +102,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -141,8 +129,6 @@ public: }; ``` -### **Go** - ```go func sameEndSubstringCount(s string, queries [][]int) []int { n := len(s) @@ -172,8 +158,6 @@ func sameEndSubstringCount(s string, queries [][]int) []int { } ``` -### **TypeScript** - ```ts function sameEndSubstringCount(s: string, queries: number[][]): number[] { const n: number = s.length; @@ -196,8 +180,6 @@ function sameEndSubstringCount(s: string, queries: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn same_end_substring_count(s: String, queries: Vec>) -> Vec { @@ -225,10 +207,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2955.Number of Same-End Substrings/README_EN.md b/solution/2900-2999/2955.Number of Same-End Substrings/README_EN.md index 474d013d2972c..f183fbcdd1ced 100644 --- a/solution/2900-2999/2955.Number of Same-End Substrings/README_EN.md +++ b/solution/2900-2999/2955.Number of Same-End Substrings/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Prefix Sum + Enumeration** +### Solution 1: Prefix Sum + Enumeration We can preprocess the prefix sum for each letter and record it in the array $cnt$, where $cnt[i][j]$ represents the number of times the $i$-th letter appears in the first $j$ characters. In this way, for each interval $[l, r]$, we can enumerate each letter $c$ in the interval, quickly calculate the number of times $c$ appears in the interval $x$ using the prefix sum array. We can arbitrarily choose two of them to form a tail-equal substring, the number of substrings is $C_x^2=\frac{x(x-1)}{2}$, plus the situation where each letter in the interval can form a tail-equal substring alone, there are $r - l + 1$ letters in total. Therefore, for each query $[l, r]$, the number of tail-equal substrings that meet the conditions is $r - l + 1 + \sum_{c \in \Sigma} \frac{x_c(x_c-1)}{2}$, where $x_c$ represents the number of times the letter $c$ appears in the interval $[l, r]$. @@ -54,8 +54,6 @@ The time complexity is $O((n + m) \times |\Sigma|)$, and the space complexity is -### **Python3** - ```python class Solution: def sameEndSubstringCount(self, s: str, queries: List[List[int]]) -> List[int]: @@ -76,8 +74,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] sameEndSubstringCount(String s, int[][] queries) { @@ -104,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -133,8 +127,6 @@ public: }; ``` -### **Go** - ```go func sameEndSubstringCount(s string, queries [][]int) []int { n := len(s) @@ -164,8 +156,6 @@ func sameEndSubstringCount(s string, queries [][]int) []int { } ``` -### **TypeScript** - ```ts function sameEndSubstringCount(s: string, queries: number[][]): number[] { const n: number = s.length; @@ -188,8 +178,6 @@ function sameEndSubstringCount(s: string, queries: number[][]): number[] { } ``` -### **Rust** - ```rust impl Solution { pub fn same_end_substring_count(s: String, queries: Vec>) -> Vec { @@ -217,10 +205,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2956.Find Common Elements Between Two Arrays/README.md b/solution/2900-2999/2956.Find Common Elements Between Two Arrays/README.md index ce60e59f7b801..b8107fe6e4acb 100644 --- a/solution/2900-2999/2956.Find Common Elements Between Two Arrays/README.md +++ b/solution/2900-2999/2956.Find Common Elements Between Two Arrays/README.md @@ -50,9 +50,7 @@ ## 解法 - - -**方法一:哈希表或数组** +### 方法一:哈希表或数组 我们可以用两个哈希表或数组 $s1$ 和 $s2$ 分别记录两个数组中出现的元素。 @@ -66,10 +64,6 @@ -### **Python3** - - - ```python class Solution: def findIntersectionValues(self, nums1: List[int], nums2: List[int]) -> List[int]: @@ -77,10 +71,6 @@ class Solution: return [sum(x in s2 for x in nums1), sum(x in s1 for x in nums2)] ``` -### **Java** - - - ```java class Solution { public int[] findIntersectionValues(int[] nums1, int[] nums2) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func findIntersectionValues(nums1 []int, nums2 []int) []int { s1 := [101]int{} @@ -153,8 +139,6 @@ func findIntersectionValues(nums1 []int, nums2 []int) []int { } ``` -### **TypeScript** - ```ts function findIntersectionValues(nums1: number[], nums2: number[]): number[] { const s1: number[] = Array(101).fill(0); @@ -176,10 +160,6 @@ function findIntersectionValues(nums1: number[], nums2: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2956.Find Common Elements Between Two Arrays/README_EN.md b/solution/2900-2999/2956.Find Common Elements Between Two Arrays/README_EN.md index 424bbbcecc8af..4207a8a9a285c 100644 --- a/solution/2900-2999/2956.Find Common Elements Between Two Arrays/README_EN.md +++ b/solution/2900-2999/2956.Find Common Elements Between Two Arrays/README_EN.md @@ -46,7 +46,7 @@ ## Solutions -**Solution 1: Hash Table or Array** +### Solution 1: Hash Table or Array We can use two hash tables or arrays $s1$ and $s2$ to record the elements that appear in the two arrays respectively. @@ -60,8 +60,6 @@ The time complexity is $O(n + m)$, and the space complexity is $O(n + m)$. Here, -### **Python3** - ```python class Solution: def findIntersectionValues(self, nums1: List[int], nums2: List[int]) -> List[int]: @@ -69,8 +67,6 @@ class Solution: return [sum(x in s2 for x in nums1), sum(x in s1 for x in nums2)] ``` -### **Java** - ```java class Solution { public int[] findIntersectionValues(int[] nums1, int[] nums2) { @@ -94,8 +90,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +114,6 @@ public: }; ``` -### **Go** - ```go func findIntersectionValues(nums1 []int, nums2 []int) []int { s1 := [101]int{} @@ -143,8 +135,6 @@ func findIntersectionValues(nums1 []int, nums2 []int) []int { } ``` -### **TypeScript** - ```ts function findIntersectionValues(nums1: number[], nums2: number[]): number[] { const s1: number[] = Array(101).fill(0); @@ -166,10 +156,6 @@ function findIntersectionValues(nums1: number[], nums2: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2957.Remove Adjacent Almost-Equal Characters/README.md b/solution/2900-2999/2957.Remove Adjacent Almost-Equal Characters/README.md index 8abcbec14848b..9b57c8fb8167e 100644 --- a/solution/2900-2999/2957.Remove Adjacent Almost-Equal Characters/README.md +++ b/solution/2900-2999/2957.Remove Adjacent Almost-Equal Characters/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:贪心** +### 方法一:贪心 我们从下标 $1$ 开始遍历字符串 $word$,如果 $word[i]$ 和 $word[i - 1]$ 相邻近似相等,那么我们就贪心地将 $word[i]$ 替换成一个与 $word[i - 1]$ 和 $word[i + 1]$ 都不相等的字符(可以不执行替换操作,记录操作次数即可)。然后,我们跳过 $word[i + 1]$,继续遍历字符串 $word$。 @@ -65,10 +63,6 @@ -### **Python3** - - - ```python class Solution: def removeAlmostEqualCharacters(self, word: str) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int removeAlmostEqualCharacters(String word) { @@ -102,8 +92,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -120,8 +108,6 @@ public: }; ``` -### **Go** - ```go func removeAlmostEqualCharacters(word string) (ans int) { for i := 1; i < len(word); i++ { @@ -141,8 +127,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function removeAlmostEqualCharacters(word: string): number { let ans = 0; @@ -156,10 +140,6 @@ function removeAlmostEqualCharacters(word: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2957.Remove Adjacent Almost-Equal Characters/README_EN.md b/solution/2900-2999/2957.Remove Adjacent Almost-Equal Characters/README_EN.md index 47b303cd91cb1..9765ab16d1e9b 100644 --- a/solution/2900-2999/2957.Remove Adjacent Almost-Equal Characters/README_EN.md +++ b/solution/2900-2999/2957.Remove Adjacent Almost-Equal Characters/README_EN.md @@ -49,7 +49,7 @@ It can be shown that the minimum number of operations needed to remove all adjac ## Solutions -**Solution 1: Greedy** +### Solution 1: Greedy We start traversing the string `word` from index $1$. If `word[i]` and `word[i - 1]` are approximately equal, we greedily replace `word[i]` with a character that is not equal to both `word[i - 1]` and `word[i + 1]` (we can choose not to perform the replacement operation, just record the number of operations). Then, we skip `word[i + 1]` and continue to traverse the string `word`. @@ -59,8 +59,6 @@ The time complexity is $O(n)$, where $n$ is the length of the string `word`. The -### **Python3** - ```python class Solution: def removeAlmostEqualCharacters(self, word: str) -> int: @@ -75,8 +73,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int removeAlmostEqualCharacters(String word) { @@ -92,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -110,8 +104,6 @@ public: }; ``` -### **Go** - ```go func removeAlmostEqualCharacters(word string) (ans int) { for i := 1; i < len(word); i++ { @@ -131,8 +123,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts function removeAlmostEqualCharacters(word: string): number { let ans = 0; @@ -146,10 +136,6 @@ function removeAlmostEqualCharacters(word: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README.md b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README.md index f5d1c51dd2403..f55e18c69519a 100644 --- a/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README.md +++ b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README.md @@ -57,9 +57,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 我们可以用两个指针 $j$ 和 $i$ 分别表示子数组的左右端点,初始时两个指针都指向数组的第一个元素。 @@ -69,10 +67,6 @@ -### **Python3** - - - ```python class Solution: def maxSubarrayLength(self, nums: List[int], k: int) -> int: @@ -87,10 +81,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int maxSubarrayLength(int[] nums, int k) { @@ -108,8 +98,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func maxSubarrayLength(nums []int, k int) (ans int) { cnt := map[int]int{} @@ -144,8 +130,6 @@ func maxSubarrayLength(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function maxSubarrayLength(nums: number[], k: number): number { const cnt: Map = new Map(); @@ -161,10 +145,6 @@ function maxSubarrayLength(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README_EN.md b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README_EN.md index 73f0a022003fe..fac47403936f7 100644 --- a/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README_EN.md +++ b/solution/2900-2999/2958.Length of Longest Subarray With at Most K Frequency/README_EN.md @@ -53,7 +53,7 @@ It can be shown that there are no good subarrays with length more than 4. ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers We can use two pointers $j$ and $i$ to represent the left and right endpoints of the subarray, initially both pointers point to the first element of the array. @@ -63,8 +63,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def maxSubarrayLength(self, nums: List[int], k: int) -> int: @@ -79,8 +77,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int maxSubarrayLength(int[] nums, int k) { @@ -98,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func maxSubarrayLength(nums []int, k int) (ans int) { cnt := map[int]int{} @@ -134,8 +126,6 @@ func maxSubarrayLength(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function maxSubarrayLength(nums: number[], k: number): number { const cnt: Map = new Map(); @@ -151,10 +141,6 @@ function maxSubarrayLength(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/README.md b/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/README.md index 9d7355b4ff7bd..2608501dcfa40 100644 --- a/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/README.md +++ b/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/README.md @@ -84,9 +84,7 @@ ## 解法 - - -**方法一:二进制枚举 + Floyd 算法** +### 方法一:二进制枚举 + Floyd 算法 我们注意到 $n \leq 10$,所以我们不妨考虑使用二进制枚举的方法来枚举所有的分部集合。 @@ -96,10 +94,6 @@ -### **Python3** - - - ```python class Solution: def numberOfSets(self, n: int, maxDistance: int, roads: List[List[int]]) -> int: @@ -128,10 +122,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int numberOfSets(int n, int maxDistance, int[][] roads) { @@ -175,8 +165,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -217,8 +205,6 @@ public: }; ``` -### **Go** - ```go func numberOfSets(n int, maxDistance int, roads [][]int) (ans int) { for mask := 0; mask < 1< + + diff --git a/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/README_EN.md b/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/README_EN.md index 8c90d46158c35..db2c07c1e6e59 100644 --- a/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/README_EN.md +++ b/solution/2900-2999/2959.Number of Possible Sets of Closing Branches/README_EN.md @@ -76,7 +76,7 @@ It can be proven, that there are only 2 possible sets of closing branches. ## Solutions -**Solution 1: Binary Enumeration + Floyd Algorithm** +### Solution 1: Binary Enumeration + Floyd Algorithm We notice that $n \leq 10$, so we might as well consider using the method of binary enumeration to enumerate all subsets of departments. @@ -86,8 +86,6 @@ The time complexity is $O(2^n \times (n^3 + m))$, and the space complexity is $O -### **Python3** - ```python class Solution: def numberOfSets(self, n: int, maxDistance: int, roads: List[List[int]]) -> int: @@ -116,8 +114,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int numberOfSets(int n, int maxDistance, int[][] roads) { @@ -161,8 +157,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -203,8 +197,6 @@ public: }; ``` -### **Go** - ```go func numberOfSets(n int, maxDistance int, roads [][]int) (ans int) { for mask := 0; mask < 1< + + diff --git a/solution/2900-2999/2960.Count Tested Devices After Test Operations/README.md b/solution/2900-2999/2960.Count Tested Devices After Test Operations/README.md index dd792970396cd..a3f04cd7fd2ac 100644 --- a/solution/2900-2999/2960.Count Tested Devices After Test Operations/README.md +++ b/solution/2900-2999/2960.Count Tested Devices After Test Operations/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:模拟** +### 方法一:模拟 假设我们当前已测试的设备数量为 $ans$,当测试新的一台设备 $i$ 时,它的剩余电量为 $\max(0, batteryPercentages[i] - ans)$,如果剩余电量大于 $0$,则说明这台设备可以进行测试,此时我们需要将 $ans$ 增加 $1$。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python class Solution: def countTestedDevices(self, batteryPercentages: List[int]) -> int: @@ -88,10 +82,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int countTestedDevices(int[] batteryPercentages) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -125,8 +113,6 @@ public: }; ``` -### **Go** - ```go func countTestedDevices(batteryPercentages []int) (ans int) { for _, x := range batteryPercentages { @@ -139,8 +125,6 @@ func countTestedDevices(batteryPercentages []int) (ans int) { } ``` -### **TypeScript** - ```ts function countTestedDevices(batteryPercentages: number[]): number { let ans = 0; @@ -154,10 +138,6 @@ function countTestedDevices(batteryPercentages: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2960.Count Tested Devices After Test Operations/README_EN.md b/solution/2900-2999/2960.Count Tested Devices After Test Operations/README_EN.md index 07b6b8fbce357..201ca04c69547 100644 --- a/solution/2900-2999/2960.Count Tested Devices After Test Operations/README_EN.md +++ b/solution/2900-2999/2960.Count Tested Devices After Test Operations/README_EN.md @@ -58,7 +58,7 @@ So, the answer is 2. ## Solutions -**Solution 1: Simulation** +### Solution 1: Simulation Assume that the current number of devices we have tested is $ans$. When testing a new device $i$, its remaining battery is $\max(0, batteryPercentages[i] - ans)$. If the remaining battery is greater than $0$, it means this device can be tested, and we need to increase $ans$ by $1$. @@ -68,8 +68,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def countTestedDevices(self, batteryPercentages: List[int]) -> int: @@ -80,8 +78,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int countTestedDevices(int[] batteryPercentages) { @@ -97,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +109,6 @@ public: }; ``` -### **Go** - ```go func countTestedDevices(batteryPercentages []int) (ans int) { for _, x := range batteryPercentages { @@ -129,8 +121,6 @@ func countTestedDevices(batteryPercentages []int) (ans int) { } ``` -### **TypeScript** - ```ts function countTestedDevices(batteryPercentages: number[]): number { let ans = 0; @@ -144,10 +134,6 @@ function countTestedDevices(batteryPercentages: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2961.Double Modular Exponentiation/README.md b/solution/2900-2999/2961.Double Modular Exponentiation/README.md index 4baff00312a7e..cd674a51ce2f4 100644 --- a/solution/2900-2999/2961.Double Modular Exponentiation/README.md +++ b/solution/2900-2999/2961.Double Modular Exponentiation/README.md @@ -54,9 +54,7 @@ ## 解法 - - -**方法一:模拟 + 快速幂** +### 方法一:模拟 + 快速幂 我们直接根据题目描述模拟即可。对于幂运算取模,我们可以使用快速幂来加速运算。 @@ -64,10 +62,6 @@ -### **Python3** - - - ```python class Solution: def getGoodIndices(self, variables: List[List[int]], target: int) -> List[int]: @@ -78,10 +72,6 @@ class Solution: ] ``` -### **Java** - - - ```java class Solution { public List getGoodIndices(int[][] variables, int target) { @@ -109,8 +99,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -138,8 +126,6 @@ public: }; ``` -### **Go** - ```go func getGoodIndices(variables [][]int, target int) (ans []int) { qpow := func(a, n, mod int) int { @@ -162,8 +148,6 @@ func getGoodIndices(variables [][]int, target int) (ans []int) { } ``` -### **TypeScript** - ```ts function getGoodIndices(variables: number[][], target: number): number[] { const qpow = (a: number, n: number, mod: number) => { @@ -187,10 +171,6 @@ function getGoodIndices(variables: number[][], target: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2961.Double Modular Exponentiation/README_EN.md b/solution/2900-2999/2961.Double Modular Exponentiation/README_EN.md index a6f1c9afb311f..40b42b016eb64 100644 --- a/solution/2900-2999/2961.Double Modular Exponentiation/README_EN.md +++ b/solution/2900-2999/2961.Double Modular Exponentiation/README_EN.md @@ -50,7 +50,7 @@ Therefore we return [] as the answer. ## Solutions -**Solution 1: Simulation + Fast Power** +### Solution 1: Simulation + Fast Power We can directly simulate according to the problem description. For the power operation modulo, we can use the fast power method to speed up the calculation. @@ -58,8 +58,6 @@ The time complexity is $O(n \times \log M)$, where $n$ is the length of the arra -### **Python3** - ```python class Solution: def getGoodIndices(self, variables: List[List[int]], target: int) -> List[int]: @@ -70,8 +68,6 @@ class Solution: ] ``` -### **Java** - ```java class Solution { public List getGoodIndices(int[][] variables, int target) { @@ -99,8 +95,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +122,6 @@ public: }; ``` -### **Go** - ```go func getGoodIndices(variables [][]int, target int) (ans []int) { qpow := func(a, n, mod int) int { @@ -152,8 +144,6 @@ func getGoodIndices(variables [][]int, target int) (ans []int) { } ``` -### **TypeScript** - ```ts function getGoodIndices(variables: number[][], target: number): number[] { const qpow = (a: number, n: number, mod: number) => { @@ -177,10 +167,6 @@ function getGoodIndices(variables: number[][], target: number): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/README.md b/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/README.md index 92b2fdaa09b57..3fe6e184a1ecc 100644 --- a/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/README.md +++ b/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:双指针** +### 方法一:双指针 不妨记数组中的最大值为 $mx$。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: @@ -77,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long countSubarrays(int[] nums, int k) { @@ -103,8 +93,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +116,6 @@ public: }; ``` -### **Go** - ```go func countSubarrays(nums []int, k int) (ans int64) { mx := slices.Max(nums) @@ -153,8 +139,6 @@ func countSubarrays(nums []int, k int) (ans int64) { } ``` -### **TypeScript** - ```ts function countSubarrays(nums: number[], k: number): number { const mx = Math.max(...nums); @@ -175,10 +159,6 @@ function countSubarrays(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/README_EN.md b/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/README_EN.md index 4847ef968acb8..a07d72a4bb776 100644 --- a/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/README_EN.md +++ b/solution/2900-2999/2962.Count Subarrays Where Max Element Appears at Least K Times/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers Let's denote the maximum value in the array as $mx$. @@ -50,8 +50,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: @@ -69,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long countSubarrays(int[] nums, int k) { @@ -93,8 +89,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func countSubarrays(nums []int, k int) (ans int64) { mx := slices.Max(nums) @@ -143,8 +135,6 @@ func countSubarrays(nums []int, k int) (ans int64) { } ``` -### **TypeScript** - ```ts function countSubarrays(nums: number[], k: number): number { const mx = Math.max(...nums); @@ -165,10 +155,6 @@ function countSubarrays(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2963.Count the Number of Good Partitions/README.md b/solution/2900-2999/2963.Count the Number of Good Partitions/README.md index 8191aa78bd181..369368d6d77af 100644 --- a/solution/2900-2999/2963.Count the Number of Good Partitions/README.md +++ b/solution/2900-2999/2963.Count the Number of Good Partitions/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:哈希表 + 分组 + 快速幂** +### 方法一:哈希表 + 分组 + 快速幂 根据题目描述,我们可以知道,相同的数字必须在同一个子数组中。因此,我们用一个哈希表 $last$ 记录每个数字最后一次出现的下标。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def numberOfGoodPartitions(self, nums: List[int]) -> int: @@ -83,10 +77,6 @@ class Solution: return pow(2, k - 1, mod) ``` -### **Java** - - - ```java class Solution { public int numberOfGoodPartitions(int[] nums) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func numberOfGoodPartitions(nums []int) int { qpow := func(a, n, mod int) int { @@ -180,8 +166,6 @@ func numberOfGoodPartitions(nums []int) int { } ``` -### **TypeScript** - ```ts function numberOfGoodPartitions(nums: number[]): number { const qpow = (a: number, n: number, mod: number) => { @@ -211,10 +195,6 @@ function numberOfGoodPartitions(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2963.Count the Number of Good Partitions/README_EN.md b/solution/2900-2999/2963.Count the Number of Good Partitions/README_EN.md index dbad178b95888..641ce2998b1f1 100644 --- a/solution/2900-2999/2963.Count the Number of Good Partitions/README_EN.md +++ b/solution/2900-2999/2963.Count the Number of Good Partitions/README_EN.md @@ -47,7 +47,7 @@ ## Solutions -**Solution 1: Hash Table + Grouping + Fast Power** +### Solution 1: Hash Table + Grouping + Fast Power According to the problem description, we know that the same number must be in the same subarray. Therefore, we use a hash table $last$ to record the index of the last occurrence of each number. @@ -61,8 +61,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is -### **Python3** - ```python class Solution: def numberOfGoodPartitions(self, nums: List[int]) -> int: @@ -75,8 +73,6 @@ class Solution: return pow(2, k - 1, mod) ``` -### **Java** - ```java class Solution { public int numberOfGoodPartitions(int[] nums) { @@ -108,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +134,6 @@ public: }; ``` -### **Go** - ```go func numberOfGoodPartitions(nums []int) int { qpow := func(a, n, mod int) int { @@ -170,8 +162,6 @@ func numberOfGoodPartitions(nums []int) int { } ``` -### **TypeScript** - ```ts function numberOfGoodPartitions(nums: number[]): number { const qpow = (a: number, n: number, mod: number) => { @@ -201,10 +191,6 @@ function numberOfGoodPartitions(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2964.Number of Divisible Triplet Sums/README.md b/solution/2900-2999/2964.Number of Divisible Triplet Sums/README.md index 1482102fecd2f..775bf46b5ee6d 100644 --- a/solution/2900-2999/2964.Number of Divisible Triplet Sums/README.md +++ b/solution/2900-2999/2964.Number of Divisible Triplet Sums/README.md @@ -46,9 +46,7 @@ ## 解法 - - -**方法一:哈希表 + 枚举** +### 方法一:哈希表 + 枚举 我们可以用哈希表 $cnt$ 记录 $nums[i] \bmod d$ 出现的次数,然后枚举 $j$ 和 $k$,计算使得等式 $(nums[i] + nums[j] + nums[k]) \bmod d = 0$ 成立的 $nums[i] \bmod d$ 的值,即 $(d - (nums[j] + nums[k]) \bmod d) \bmod d$,并将其出现次数累加到答案中。然后我们将 $nums[j] \bmod d$ 的出现次数加一。继续枚举 $j$ 和 $k$,直到 $j$ 到达数组末尾。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def divisibleTripletCount(self, nums: List[int], d: int) -> int: @@ -73,10 +67,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int divisibleTripletCount(int[] nums, int d) { @@ -94,8 +84,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -114,8 +102,6 @@ public: }; ``` -### **Go** - ```go func divisibleTripletCount(nums []int, d int) (ans int) { n := len(nums) @@ -131,8 +117,6 @@ func divisibleTripletCount(nums []int, d int) (ans int) { } ``` -### **TypeScript** - ```ts function divisibleTripletCount(nums: number[], d: number): number { const n = nums.length; @@ -149,10 +133,6 @@ function divisibleTripletCount(nums: number[], d: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2964.Number of Divisible Triplet Sums/README_EN.md b/solution/2900-2999/2964.Number of Divisible Triplet Sums/README_EN.md index fd82dd968cb8a..fdedfe8377bc7 100644 --- a/solution/2900-2999/2964.Number of Divisible Triplet Sums/README_EN.md +++ b/solution/2900-2999/2964.Number of Divisible Triplet Sums/README_EN.md @@ -43,7 +43,7 @@ It can be shown that no other triplet is divisible by 5. Hence, the answer is 3. ## Solutions -**Solution 1: Hash Table + Enumeration** +### Solution 1: Hash Table + Enumeration We can use a hash table $cnt$ to record the occurrence times of $nums[i] \bmod d$, then enumerate $j$ and $k$, calculate the value of $nums[i] \bmod d$ that makes the equation $(nums[i] + nums[j] + nums[k]) \bmod d = 0$ hold, which is $(d - (nums[j] + nums[k]) \bmod d) \bmod d$, and accumulate its occurrence times to the answer. Then we increase the occurrence times of $nums[j] \bmod d$ by one. Continue to enumerate $j$ and $k$ until $j$ reaches the end of the array. @@ -51,8 +51,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ i -### **Python3** - ```python class Solution: def divisibleTripletCount(self, nums: List[int], d: int) -> int: @@ -66,8 +64,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int divisibleTripletCount(int[] nums, int d) { @@ -85,8 +81,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +99,6 @@ public: }; ``` -### **Go** - ```go func divisibleTripletCount(nums []int, d int) (ans int) { n := len(nums) @@ -122,8 +114,6 @@ func divisibleTripletCount(nums []int, d int) (ans int) { } ``` -### **TypeScript** - ```ts function divisibleTripletCount(nums: number[], d: number): number { const n = nums.length; @@ -140,10 +130,6 @@ function divisibleTripletCount(nums: number[], d: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2965.Find Missing and Repeated Values/README.md b/solution/2900-2999/2965.Find Missing and Repeated Values/README.md index dea13dc8508c7..c637e313e016b 100644 --- a/solution/2900-2999/2965.Find Missing and Repeated Values/README.md +++ b/solution/2900-2999/2965.Find Missing and Repeated Values/README.md @@ -44,9 +44,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们创建一个长度为 $n^2 + 1$ 的数组 $cnt$,统计矩阵中每个数字出现的次数。 @@ -56,10 +54,6 @@ -### **Python3** - - - ```python class Solution: def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]: @@ -77,10 +71,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[] findMissingAndRepeatedValues(int[][] grid) { @@ -104,8 +94,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func findMissingAndRepeatedValues(grid [][]int) []int { n := len(grid) @@ -154,8 +140,6 @@ func findMissingAndRepeatedValues(grid [][]int) []int { } ``` -### **TypeScript** - ```ts function findMissingAndRepeatedValues(grid: number[][]): number[] { const n = grid.length; @@ -177,10 +161,6 @@ function findMissingAndRepeatedValues(grid: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2965.Find Missing and Repeated Values/README_EN.md b/solution/2900-2999/2965.Find Missing and Repeated Values/README_EN.md index ca7c4b95844ba..a328c80fecd8c 100644 --- a/solution/2900-2999/2965.Find Missing and Repeated Values/README_EN.md +++ b/solution/2900-2999/2965.Find Missing and Repeated Values/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We create an array $cnt$ of length $n^2 + 1$ to count the frequency of each number in the matrix. @@ -48,8 +48,6 @@ The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ -### **Python3** - ```python class Solution: def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]: @@ -67,8 +65,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[] findMissingAndRepeatedValues(int[][] grid) { @@ -92,8 +88,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -118,8 +112,6 @@ public: }; ``` -### **Go** - ```go func findMissingAndRepeatedValues(grid [][]int) []int { n := len(grid) @@ -142,8 +134,6 @@ func findMissingAndRepeatedValues(grid [][]int) []int { } ``` -### **TypeScript** - ```ts function findMissingAndRepeatedValues(grid: number[][]): number[] { const n = grid.length; @@ -165,10 +155,6 @@ function findMissingAndRepeatedValues(grid: number[][]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/README.md b/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/README.md index de3dab0415aab..83eca99c58882 100644 --- a/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/README.md +++ b/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/README.md @@ -51,9 +51,7 @@ ## 解法 - - -**方法一:排序** +### 方法一:排序 我们先对数组进行排序,然后每次取出三个元素,如果这三个元素的最大值和最小值的差大于 $k$,则无法满足条件,返回空数组。否则,我们将这三个元素组成的数组加入答案数组中。 @@ -61,10 +59,6 @@ -### **Python3** - - - ```python class Solution: def divideArray(self, nums: List[int], k: int) -> List[List[int]]: @@ -79,10 +73,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int[][] divideArray(int[] nums, int k) { @@ -101,8 +91,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -122,8 +110,6 @@ public: }; ``` -### **Go** - ```go func divideArray(nums []int, k int) [][]int { sort.Ints(nums) @@ -139,8 +125,6 @@ func divideArray(nums []int, k int) [][]int { } ``` -### **TypeScript** - ```ts function divideArray(nums: number[], k: number): number[][] { nums.sort((a, b) => a - b); @@ -156,10 +140,6 @@ function divideArray(nums: number[], k: number): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/README_EN.md b/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/README_EN.md index bdd693f15c105..42350ba212449 100644 --- a/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/README_EN.md +++ b/solution/2900-2999/2966.Divide Array Into Arrays With Max Difference/README_EN.md @@ -47,7 +47,7 @@ Note that the order of elements is not important. ## Solutions -**Solution 1: Sorting** +### Solution 1: Sorting First, we sort the array. Then, we take out three elements each time. If the difference between the maximum and minimum values of these three elements is greater than $k$, then the condition cannot be satisfied, and we return an empty array. Otherwise, we add the array composed of these three elements to the answer array. @@ -55,8 +55,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def divideArray(self, nums: List[int], k: int) -> List[List[int]]: @@ -71,8 +69,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int[][] divideArray(int[] nums, int k) { @@ -91,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +106,6 @@ public: }; ``` -### **Go** - ```go func divideArray(nums []int, k int) [][]int { sort.Ints(nums) @@ -129,8 +121,6 @@ func divideArray(nums []int, k int) [][]int { } ``` -### **TypeScript** - ```ts function divideArray(nums: number[], k: number): number[][] { nums.sort((a, b) => a - b); @@ -146,10 +136,6 @@ function divideArray(nums: number[], k: number): number[][] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/README.md b/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/README.md index 2c4c5cf39502c..c619ee5dbbe13 100644 --- a/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/README.md +++ b/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/README.md @@ -62,9 +62,7 @@ ## 解法 - - -**方法一:预处理 + 排序 + 二分查找** +### 方法一:预处理 + 排序 + 二分查找 题目中回文数的范围是 $[1, 10^9]$,回文数由于对称性,我们可以在 $[1, 10^5]$ 的范围内枚举,然后将其翻转后拼接,得到所有的回文数,注意,如果是奇数长度的回文数,我们在翻转前要去掉最后一位。预处理得到的回文数数组记为 $ps$。我们对数组 $ps$ 进行排序。 @@ -74,10 +72,6 @@ -### **Python3** - - - ```python ps = [] for i in range(1, 10**5 + 1): @@ -99,10 +93,6 @@ class Solution: return min(f(ps[j]) for j in range(i - 1, i + 2) if 0 <= j < len(ps)) ``` -### **Java** - - - ```java public class Solution { private static long[] ps; @@ -144,8 +134,6 @@ public class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -188,8 +176,6 @@ public: }; ``` -### **Go** - ```go var ps [2 * 100000]int64 @@ -245,8 +231,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts const ps = Array(2e5).fill(0); @@ -290,10 +274,6 @@ function minimumCost(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/README_EN.md b/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/README_EN.md index 7d70b0530e373..c1772a8fd78c6 100644 --- a/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/README_EN.md +++ b/solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/README_EN.md @@ -58,7 +58,7 @@ It can be shown that changing all elements to any palindromic number other than ## Solutions -**Solution 1: Preprocessing + Sorting + Binary Search** +### Solution 1: Preprocessing + Sorting + Binary Search The range of palindrome numbers in the problem is $[1, 10^9]$. Due to the symmetry of palindrome numbers, we can enumerate in the range of $[1, 10^5]$, then reverse and concatenate them to get all palindrome numbers. Note that if it is an odd-length palindrome number, we need to remove the last digit before reversing. The array of palindrome numbers obtained by preprocessing is denoted as $ps$. We sort the array $ps$. @@ -68,8 +68,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(M)$. -### **Python3** - ```python ps = [] for i in range(1, 10**5 + 1): @@ -91,8 +89,6 @@ class Solution: return min(f(ps[j]) for j in range(i - 1, i + 2) if 0 <= j < len(ps)) ``` -### **Java** - ```java public class Solution { private static long[] ps; @@ -134,8 +130,6 @@ public class Solution { } ``` -### **C++** - ```cpp using ll = long long; @@ -178,8 +172,6 @@ public: }; ``` -### **Go** - ```go var ps [2 * 100000]int64 @@ -235,8 +227,6 @@ func abs(x int) int { } ``` -### **TypeScript** - ```ts const ps = Array(2e5).fill(0); @@ -280,10 +270,6 @@ function minimumCost(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/README.md b/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/README.md index 2da90d5ae24be..4a9ca3243a58a 100644 --- a/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/README.md +++ b/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:排序 + 前缀和 + 二分查找** +### 方法一:排序 + 前缀和 + 二分查找 题目求的是在最多进行 $k$ 次操作的情况下,我们能得到的众数的最大频率。如果我们将数组 $nums$ 按照从小到大的顺序排列,那么最好就是将一段连续的数字都变成同一个数,这样可以使得操作次数较少,并且众数的频率较高。 @@ -89,10 +87,6 @@ $$ -### **Python3** - - - ```python class Solution: def maxFrequencyScore(self, nums: List[int], k: int) -> int: @@ -118,10 +112,6 @@ class Solution: return l ``` -### **Java** - - - ```java class Solution { public int maxFrequencyScore(int[] nums, long k) { @@ -159,8 +149,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -201,8 +189,6 @@ public: }; ``` -### **Go** - ```go func maxFrequencyScore(nums []int, k int64) int { sort.Ints(nums) @@ -240,8 +226,6 @@ func maxFrequencyScore(nums []int, k int64) int { } ``` -### **TypeScript** - ```ts function maxFrequencyScore(nums: number[], k: number): number { nums.sort((a, b) => a - b); @@ -277,10 +261,6 @@ function maxFrequencyScore(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/README_EN.md b/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/README_EN.md index 8bd11dd5a708b..376968007af5d 100644 --- a/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/README_EN.md +++ b/solution/2900-2999/2968.Apply Operations to Maximize Frequency Score/README_EN.md @@ -51,7 +51,7 @@ It can be shown that we cannot achieve a better score. ## Solutions -**Solution 1: Sorting + Prefix Sum + Binary Search** +### Solution 1: Sorting + Prefix Sum + Binary Search The problem asks for the maximum frequency of the mode we can get after performing at most $k$ operations. If we sort the array $nums$ in ascending order, it would be best to turn a continuous segment of numbers into the same number, which can reduce the number of operations and increase the frequency of the mode. @@ -83,8 +83,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def maxFrequencyScore(self, nums: List[int], k: int) -> int: @@ -110,8 +108,6 @@ class Solution: return l ``` -### **Java** - ```java class Solution { public int maxFrequencyScore(int[] nums, long k) { @@ -149,8 +145,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -191,8 +185,6 @@ public: }; ``` -### **Go** - ```go func maxFrequencyScore(nums []int, k int64) int { sort.Ints(nums) @@ -230,8 +222,6 @@ func maxFrequencyScore(nums []int, k int64) int { } ``` -### **TypeScript** - ```ts function maxFrequencyScore(nums: number[], k: number): number { nums.sort((a, b) => a - b); @@ -267,10 +257,6 @@ function maxFrequencyScore(nums: number[], k: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/README.md b/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/README.md index b4f695ee8a7b1..0114ec98da599 100644 --- a/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/README.md +++ b/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/README.md @@ -59,9 +59,7 @@ ## 解法 - - -**方法一:动态规划** +### 方法一:动态规划 我们定义 $f[i]$ 表示从第 $i$ 个水果开始购买所有水果所需要的最少金币数。那么答案就是 $f[1]$。 @@ -79,10 +77,6 @@ -### **Python3** - - - ```python class Solution: def minimumCoins(self, prices: List[int]) -> int: @@ -99,10 +93,6 @@ class Solution: return prices[0] ``` -### **Java** - - - ```java class Solution { public int minimumCoins(int[] prices) { @@ -125,8 +115,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func minimumCoins(prices []int) int { n := len(prices) @@ -230,8 +216,6 @@ func (q Deque) Get(i int) int { } ``` -### **TypeScript** - ```ts function minimumCoins(prices: number[]): number { const n = prices.length; @@ -348,10 +332,6 @@ class Deque { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/README_EN.md b/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/README_EN.md index 5e331ad30e8b3..1162ab3194be8 100644 --- a/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/README_EN.md +++ b/solution/2900-2999/2969.Minimum Number of Coins for Fruits II/README_EN.md @@ -55,7 +55,7 @@ It can be proven that 2 is the minimum number of coins needed to acquire all the ## Solutions -**Solution 1: Dynamic Programming** +### Solution 1: Dynamic Programming We define $f[i]$ as the minimum number of coins needed to buy all fruits starting from the $i$th fruit. So the answer is $f[1]$. @@ -73,8 +73,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def minimumCoins(self, prices: List[int]) -> int: @@ -91,8 +89,6 @@ class Solution: return prices[0] ``` -### **Java** - ```java class Solution { public int minimumCoins(int[] prices) { @@ -115,8 +111,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +134,6 @@ public: }; ``` -### **Go** - ```go func minimumCoins(prices []int) int { n := len(prices) @@ -220,8 +212,6 @@ func (q Deque) Get(i int) int { } ``` -### **TypeScript** - ```ts function minimumCoins(prices: number[]): number { const n = prices.length; @@ -338,10 +328,6 @@ class Deque { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/README.md b/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/README.md index 635c1fa22c2ca..37fe998d0aaf7 100644 --- a/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/README.md +++ b/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/README.md @@ -54,9 +54,7 @@ nums 中只有这 7 个移除递增子数组。 ## 解法 - - -**方法一:双指针** +### 方法一:双指针 根据题目描述,移除一个子数组后,剩余元素严格递增,那么存在以下几种情况: @@ -86,10 +84,6 @@ nums 中只有这 7 个移除递增子数组。 -### **Python3** - - - ```python class Solution: def incremovableSubarrayCount(self, nums: List[int]) -> int: @@ -110,10 +104,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int incremovableSubarrayCount(int[] nums) { @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +155,6 @@ public: }; ``` -### **Go** - ```go func incremovableSubarrayCount(nums []int) int { i, n := 0, len(nums) @@ -192,8 +178,6 @@ func incremovableSubarrayCount(nums []int) int { } ``` -### **TypeScript** - ```ts function incremovableSubarrayCount(nums: number[]): number { const n = nums.length; @@ -218,10 +202,6 @@ function incremovableSubarrayCount(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/README_EN.md b/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/README_EN.md index 1cbf8741117eb..a5d1bfba77a10 100644 --- a/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/README_EN.md +++ b/solution/2900-2999/2970.Count the Number of Incremovable Subarrays I/README_EN.md @@ -50,7 +50,7 @@ It can be shown that there are only 7 incremovable subarrays in nums. ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers According to the problem description, after removing a subarray, the remaining elements are strictly increasing. Therefore, there are several situations: @@ -80,8 +80,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def incremovableSubarrayCount(self, nums: List[int]) -> int: @@ -102,8 +100,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int incremovableSubarrayCount(int[] nums) { @@ -129,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +151,6 @@ public: }; ``` -### **Go** - ```go func incremovableSubarrayCount(nums []int) int { i, n := 0, len(nums) @@ -182,8 +174,6 @@ func incremovableSubarrayCount(nums []int) int { } ``` -### **TypeScript** - ```ts function incremovableSubarrayCount(nums: number[]): number { const n = nums.length; @@ -208,10 +198,6 @@ function incremovableSubarrayCount(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/README.md b/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/README.md index 943466f06c721..7e2ab065e5fd3 100644 --- a/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/README.md +++ b/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/README.md @@ -55,9 +55,7 @@ ## 解法 - - -**方法一:排序 + 前缀和** +### 方法一:排序 + 前缀和 我们可以将数组 $nums$ 排序,然后定义一个答案变量 $ans$,初始值为 $-1$。 @@ -67,10 +65,6 @@ -### **Python3** - - - ```python class Solution: def largestPerimeter(self, nums: List[int]) -> int: @@ -83,10 +77,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long largestPerimeter(int[] nums) { @@ -107,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -130,8 +118,6 @@ public: }; ``` -### **Go** - ```go func largestPerimeter(nums []int) int64 { sort.Ints(nums) @@ -150,8 +136,6 @@ func largestPerimeter(nums []int) int64 { } ``` -### **TypeScript** - ```ts function largestPerimeter(nums: number[]): number { nums.sort((a, b) => a - b); @@ -170,10 +154,6 @@ function largestPerimeter(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/README_EN.md b/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/README_EN.md index cfe28c9ca560e..9ff0199122210 100644 --- a/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/README_EN.md +++ b/solution/2900-2999/2971.Find Polygon With the Largest Perimeter/README_EN.md @@ -51,9 +51,9 @@ It can be shown that the largest possible perimeter is 12. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -67,8 +67,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long largestPerimeter(int[] nums) { @@ -89,8 +87,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +108,6 @@ public: }; ``` -### **Go** - ```go func largestPerimeter(nums []int) int64 { sort.Ints(nums) @@ -132,8 +126,6 @@ func largestPerimeter(nums []int) int64 { } ``` -### **TypeScript** - ```ts function largestPerimeter(nums: number[]): number { nums.sort((a, b) => a - b); @@ -152,10 +144,6 @@ function largestPerimeter(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/README.md b/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/README.md index 498aa157893d6..95154ef684674 100644 --- a/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/README.md +++ b/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/README.md @@ -54,9 +54,7 @@ nums 中只有这 7 个移除递增子数组。 ## 解法 - - -**方法一:双指针** +### 方法一:双指针 根据题目描述,移除一个子数组后,剩余元素严格递增,那么存在以下几种情况: @@ -86,10 +84,6 @@ nums 中只有这 7 个移除递增子数组。 -### **Python3** - - - ```python class Solution: def incremovableSubarrayCount(self, nums: List[int]) -> int: @@ -110,10 +104,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long incremovableSubarrayCount(int[] nums) { @@ -139,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -167,8 +155,6 @@ public: }; ``` -### **Go** - ```go func incremovableSubarrayCount(nums []int) int64 { i, n := 0, len(nums) @@ -192,10 +178,30 @@ func incremovableSubarrayCount(nums []int) int64 { } ``` -### **...** - -``` - +```ts +function incremovableSubarrayCount(nums: number[]): number { + const n = nums.length; + let i = 0; + while (i + 1 < n && nums[i] < nums[i + 1]) { + i++; + } + if (i === n - 1) { + return (n * (n + 1)) / 2; + } + let ans = i + 2; + for (let j = n - 1; j; --j) { + while (i >= 0 && nums[i] >= nums[j]) { + --i; + } + ans += i + 2; + if (nums[j - 1] >= nums[j]) { + break; + } + } + return ans; +} ``` + + diff --git a/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/README_EN.md b/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/README_EN.md index ef9bfd26eddb3..cd73010516da1 100644 --- a/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/README_EN.md +++ b/solution/2900-2999/2972.Count the Number of Incremovable Subarrays II/README_EN.md @@ -50,7 +50,7 @@ It can be shown that there are only 7 incremovable subarrays in nums. ## Solutions -**Solution 1: Two Pointers** +### Solution 1: Two Pointers According to the problem description, after removing a subarray, the remaining elements are strictly increasing. Therefore, there are several situations: @@ -80,8 +80,6 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def incremovableSubarrayCount(self, nums: List[int]) -> int: @@ -102,8 +100,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long incremovableSubarrayCount(int[] nums) { @@ -129,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -157,8 +151,6 @@ public: }; ``` -### **Go** - ```go func incremovableSubarrayCount(nums []int) int64 { i, n := 0, len(nums) @@ -182,8 +174,6 @@ func incremovableSubarrayCount(nums []int) int64 { } ``` -### **TypeScript** - ```ts function incremovableSubarrayCount(nums: number[]): number { const n = nums.length; @@ -208,10 +198,6 @@ function incremovableSubarrayCount(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/README.md b/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/README.md index 33a73508158cb..0cf4382e29344 100644 --- a/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/README.md +++ b/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/README.md @@ -71,9 +71,7 @@ ## 解法 - - -**方法一:DFS + 排序** +### 方法一:DFS + 排序 根据题目描述,每个节点 $a$ 的放置的金币数有两种情况: @@ -101,10 +99,6 @@ -### **Python3** - - - ```python class Solution: def placedCoins(self, edges: List[List[int]], cost: List[int]) -> List[int]: @@ -130,10 +124,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private int[] cost; @@ -179,8 +169,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -219,8 +207,6 @@ public: }; ``` -### **Go** - ```go func placedCoins(edges [][]int, cost []int) []int64 { n := len(cost) @@ -259,8 +245,6 @@ func placedCoins(edges [][]int, cost []int) []int64 { } ``` -### **TypeScript** - ```ts function placedCoins(edges: number[][], cost: number[]): number[] { const n = cost.length; @@ -294,10 +278,6 @@ function placedCoins(edges: number[][], cost: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/README_EN.md b/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/README_EN.md index 79f40ba879dea..887964d6fb79e 100644 --- a/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/README_EN.md +++ b/solution/2900-2999/2973.Find Number of Coins to Place in Tree Nodes/README_EN.md @@ -61,7 +61,7 @@ ## Solutions -**Solution 1: DFS + Sorting** +### Solution 1: DFS + Sorting According to the problem description, there are two situations for the number of coins placed at each node $a$: @@ -89,8 +89,6 @@ The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. -### **Python3** - ```python class Solution: def placedCoins(self, edges: List[List[int]], cost: List[int]) -> List[int]: @@ -116,8 +114,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private int[] cost; @@ -163,8 +159,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -203,8 +197,6 @@ public: }; ``` -### **Go** - ```go func placedCoins(edges [][]int, cost []int) []int64 { n := len(cost) @@ -243,8 +235,6 @@ func placedCoins(edges [][]int, cost []int) []int64 { } ``` -### **TypeScript** - ```ts function placedCoins(edges: number[][], cost: number[]): number[] { const n = cost.length; @@ -278,10 +268,6 @@ function placedCoins(edges: number[][], cost: number[]): number[] { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2974.Minimum Number Game/README.md b/solution/2900-2999/2974.Minimum Number Game/README.md index 148908fcc7475..ee45bb93fac3b 100644 --- a/solution/2900-2999/2974.Minimum Number Game/README.md +++ b/solution/2900-2999/2974.Minimum Number Game/README.md @@ -47,26 +47,14 @@ ## 解法 - - -**方法一:模拟 + 优先队列(小根堆)** +### 方法一:模拟 + 优先队列(小根堆) 我们可以将数组 $nums$ 中的元素依次放入一个小根堆中,每次从小根堆中取出两个元素 $a$ 和 $b$,然后依次将 $b$ 和 $a$ 放入答案数组中,直到小根堆为空。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。 -**方法二:排序 + 交换** - -我们可以将数组 $nums$ 排序,然后依次将相邻的两个元素交换位置,即可得到答案数组。 - -时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 $nums$ 的长度。 - -### **Python3** - - - ```python class Solution: def numberGame(self, nums: List[int]) -> List[int]: @@ -79,19 +67,6 @@ class Solution: return ans ``` -```python -class Solution: - def numberGame(self, nums: List[int]) -> List[int]: - nums.sort() - for i in range(0, len(nums), 2): - nums[i], nums[i + 1] = nums[i + 1], nums[i] - return nums -``` - -### **Java** - - - ```java class Solution { public int[] numberGame(int[] nums) { @@ -111,22 +86,6 @@ class Solution { } ``` -```java -class Solution { - public int[] numberGame(int[] nums) { - Arrays.sort(nums); - for (int i = 0; i < nums.length; i += 2) { - int t = nums[i]; - nums[i] = nums[i + 1]; - nums[i + 1] = t; - } - return nums; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -149,22 +108,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector numberGame(vector& nums) { - sort(nums.begin(), nums.end()); - int n = nums.size(); - for (int i = 0; i < n; i += 2) { - swap(nums[i], nums[i + 1]); - } - return nums; - } -}; -``` - -### **Go** - ```go func numberGame(nums []int) (ans []int) { pq := &hp{nums} @@ -193,18 +136,6 @@ func (h *hp) Push(x interface{}) { } ``` -```go -func numberGame(nums []int) []int { - sort.Ints(nums) - for i := 0; i < len(nums); i += 2 { - nums[i], nums[i+1] = nums[i+1], nums[i] - } - return nums -} -``` - -### **TypeScript** - ```ts function numberGame(nums: number[]): number[] { const pq = new MinPriorityQueue(); @@ -221,18 +152,6 @@ function numberGame(nums: number[]): number[] { } ``` -```ts -function numberGame(nums: number[]): number[] { - nums.sort((a, b) => a - b); - for (let i = 0; i < nums.length; i += 2) { - [nums[i], nums[i + 1]] = [nums[i + 1], nums[i]]; - } - return nums; -} -``` - -### **Rust** - ```rust use std::collections::BinaryHeap; use std::cmp::Reverse; @@ -259,6 +178,73 @@ impl Solution { } ``` + + +### 方法二:排序 + 交换 + +我们可以将数组 $nums$ 排序,然后依次将相邻的两个元素交换位置,即可得到答案数组。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为数组 $nums$ 的长度。 + + + +```python +class Solution: + def numberGame(self, nums: List[int]) -> List[int]: + nums.sort() + for i in range(0, len(nums), 2): + nums[i], nums[i + 1] = nums[i + 1], nums[i] + return nums +``` + +```java +class Solution { + public int[] numberGame(int[] nums) { + Arrays.sort(nums); + for (int i = 0; i < nums.length; i += 2) { + int t = nums[i]; + nums[i] = nums[i + 1]; + nums[i + 1] = t; + } + return nums; + } +} +``` + +```cpp +class Solution { +public: + vector numberGame(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + for (int i = 0; i < n; i += 2) { + swap(nums[i], nums[i + 1]); + } + return nums; + } +}; +``` + +```go +func numberGame(nums []int) []int { + sort.Ints(nums) + for i := 0; i < len(nums); i += 2 { + nums[i], nums[i+1] = nums[i+1], nums[i] + } + return nums +} +``` + +```ts +function numberGame(nums: number[]): number[] { + nums.sort((a, b) => a - b); + for (let i = 0; i < nums.length; i += 2) { + [nums[i], nums[i + 1]] = [nums[i + 1], nums[i]]; + } + return nums; +} +``` + ```rust impl Solution { pub fn number_game(nums: Vec) -> Vec { @@ -272,10 +258,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2974.Minimum Number Game/README_EN.md b/solution/2900-2999/2974.Minimum Number Game/README_EN.md index 244f2b8ada105..b26881e652a78 100644 --- a/solution/2900-2999/2974.Minimum Number Game/README_EN.md +++ b/solution/2900-2999/2974.Minimum Number Game/README_EN.md @@ -43,22 +43,14 @@ At the begining of round two, nums = [5,4]. Now, first Alice removes 4 and then ## Solutions -**Solution 1: Simulation + Priority Queue (Min Heap)** +### Solution 1: Simulation + Priority Queue (Min Heap) We can put the elements in the array $nums$ into a min heap one by one, and each time take out two elements $a$ and $b$ from the min heap, then put $b$ and $a$ into the answer array in turn, until the min heap is empty. Time complexity is $O(n \times \log n)$, and space complexity is $O(n)$. Where $n$ is the length of the array $nums$. -**Solution 2: Sorting + Swapping** - -We can sort the array $nums$, and then swap the positions of every two adjacent elements in sequence to get the answer array. - -The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Where $n$ is the length of the array $nums$. - -### **Python3** - ```python class Solution: def numberGame(self, nums: List[int]) -> List[int]: @@ -71,17 +63,6 @@ class Solution: return ans ``` -```python -class Solution: - def numberGame(self, nums: List[int]) -> List[int]: - nums.sort() - for i in range(0, len(nums), 2): - nums[i], nums[i + 1] = nums[i + 1], nums[i] - return nums -``` - -### **Java** - ```java class Solution { public int[] numberGame(int[] nums) { @@ -101,22 +82,6 @@ class Solution { } ``` -```java -class Solution { - public int[] numberGame(int[] nums) { - Arrays.sort(nums); - for (int i = 0; i < nums.length; i += 2) { - int t = nums[i]; - nums[i] = nums[i + 1]; - nums[i + 1] = t; - } - return nums; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -139,22 +104,6 @@ public: }; ``` -```cpp -class Solution { -public: - vector numberGame(vector& nums) { - sort(nums.begin(), nums.end()); - int n = nums.size(); - for (int i = 0; i < n; i += 2) { - swap(nums[i], nums[i + 1]); - } - return nums; - } -}; -``` - -### **Go** - ```go func numberGame(nums []int) (ans []int) { pq := &hp{nums} @@ -183,18 +132,6 @@ func (h *hp) Push(x interface{}) { } ``` -```go -func numberGame(nums []int) []int { - sort.Ints(nums) - for i := 0; i < len(nums); i += 2 { - nums[i], nums[i+1] = nums[i+1], nums[i] - } - return nums -} -``` - -### **TypeScript** - ```ts function numberGame(nums: number[]): number[] { const pq = new MinPriorityQueue(); @@ -211,18 +148,6 @@ function numberGame(nums: number[]): number[] { } ``` -```ts -function numberGame(nums: number[]): number[] { - nums.sort((a, b) => a - b); - for (let i = 0; i < nums.length; i += 2) { - [nums[i], nums[i + 1]] = [nums[i + 1], nums[i]]; - } - return nums; -} -``` - -### **Rust** - ```rust use std::collections::BinaryHeap; use std::cmp::Reverse; @@ -249,6 +174,73 @@ impl Solution { } ``` + + +### Solution 2: Sorting + Swapping + +We can sort the array $nums$, and then swap the positions of every two adjacent elements in sequence to get the answer array. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(\log n)$. Where $n$ is the length of the array $nums$. + + + +```python +class Solution: + def numberGame(self, nums: List[int]) -> List[int]: + nums.sort() + for i in range(0, len(nums), 2): + nums[i], nums[i + 1] = nums[i + 1], nums[i] + return nums +``` + +```java +class Solution { + public int[] numberGame(int[] nums) { + Arrays.sort(nums); + for (int i = 0; i < nums.length; i += 2) { + int t = nums[i]; + nums[i] = nums[i + 1]; + nums[i + 1] = t; + } + return nums; + } +} +``` + +```cpp +class Solution { +public: + vector numberGame(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + for (int i = 0; i < n; i += 2) { + swap(nums[i], nums[i + 1]); + } + return nums; + } +}; +``` + +```go +func numberGame(nums []int) []int { + sort.Ints(nums) + for i := 0; i < len(nums); i += 2 { + nums[i], nums[i+1] = nums[i+1], nums[i] + } + return nums +} +``` + +```ts +function numberGame(nums: number[]): number[] { + nums.sort((a, b) => a - b); + for (let i = 0; i < nums.length; i += 2) { + [nums[i], nums[i + 1]] = [nums[i + 1], nums[i]]; + } + return nums; +} +``` + ```rust impl Solution { pub fn number_game(nums: Vec) -> Vec { @@ -262,10 +254,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README.md b/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README.md index 061c759dad88b..0a0158fc0d211 100644 --- a/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README.md +++ b/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:枚举** +### 方法一:枚举 我们可以枚举 $hFences$ 中的任意两条水平栅栏 $a$ 和 $b$,计算 $a$ 和 $b$ 之间的距离 $d$,记录在哈希表 $hs$ 中,然后枚举 $vFences$ 中的任意两条垂直栅栏 $c$ 和 $d$,计算 $c$ 和 $d$ 之间的距离 $d$,记录在哈希表 $vs$ 中,最后遍历哈希表 $hs$,如果 $hs$ 中的某个距离 $d$ 在哈希表 $vs$ 中也存在,那么说明存在一个正方形田地,其边长为 $d$,面积为 $d^2$,我们只需要取最大的 $d$,求 $d^2 \bmod 10^9 + 7$ 即可。 @@ -62,10 +60,6 @@ -### **Python3** - - - ```python class Solution: def maximizeSquareArea( @@ -83,10 +77,6 @@ class Solution: return ans**2 % mod if ans else -1 ``` -### **Java** - - - ```java class Solution { public int maximizeSquareArea(int m, int n, int[] hFences, int[] vFences) { @@ -118,8 +108,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -150,8 +138,6 @@ public: }; ``` -### **Go** - ```go func maximizeSquareArea(m int, n int, hFences []int, vFences []int) int { f := func(nums []int, k int) map[int]bool { @@ -180,8 +166,6 @@ func maximizeSquareArea(m int, n int, hFences []int, vFences []int) int { } ``` -### **TypeScript** - ```ts function maximizeSquareArea(m: number, n: number, hFences: number[], vFences: number[]): number { const f = (nums: number[], k: number): Set => { @@ -207,10 +191,6 @@ function maximizeSquareArea(m: number, n: number, hFences: number[], vFences: nu } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README_EN.md b/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README_EN.md index 559b6ad0ec2dd..bd07a39fa0aae 100644 --- a/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README_EN.md +++ b/solution/2900-2999/2975.Maximum Square Area by Removing Fences From a Field/README_EN.md @@ -48,7 +48,7 @@ ## Solutions -**Solution 1: Enumeration** +### Solution 1: Enumeration We can enumerate any two horizontal fences $a$ and $b$ in $hFences$, calculate the distance $d$ between $a$ and $b$, and record it in the hash table $hs$. Then, we enumerate any two vertical fences $c$ and $d$ in $vFences$, calculate the distance $d$ between $c$ and $d$, and record it in the hash table $vs$. Finally, we traverse the hash table $hs$. If a distance $d$ in $hs$ also exists in the hash table $vs$, it means that there exists a square field with a side length of $d$ and an area of $d^2$. We just need to take the largest $d$ and calculate $d^2 \bmod 10^9 + 7$. @@ -56,8 +56,6 @@ The time complexity is $O(h^2 + v^2)$, and the space complexity is $O(h^2 + v^2) -### **Python3** - ```python class Solution: def maximizeSquareArea( @@ -75,8 +73,6 @@ class Solution: return ans**2 % mod if ans else -1 ``` -### **Java** - ```java class Solution { public int maximizeSquareArea(int m, int n, int[] hFences, int[] vFences) { @@ -108,8 +104,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -140,8 +134,6 @@ public: }; ``` -### **Go** - ```go func maximizeSquareArea(m int, n int, hFences []int, vFences []int) int { f := func(nums []int, k int) map[int]bool { @@ -170,8 +162,6 @@ func maximizeSquareArea(m int, n int, hFences []int, vFences []int) int { } ``` -### **TypeScript** - ```ts function maximizeSquareArea(m: number, n: number, hFences: number[], vFences: number[]): number { const f = (nums: number[], k: number): Set => { @@ -197,10 +187,6 @@ function maximizeSquareArea(m: number, n: number, hFences: number[], vFences: nu } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2976.Minimum Cost to Convert String I/README.md b/solution/2900-2999/2976.Minimum Cost to Convert String I/README.md index 03b805d6011f9..1118f109a1536 100644 --- a/solution/2900-2999/2976.Minimum Cost to Convert String I/README.md +++ b/solution/2900-2999/2976.Minimum Cost to Convert String I/README.md @@ -67,9 +67,7 @@ ## 解法 - - -**方法一:Floyd 算法** +### 方法一:Floyd 算法 根据题目描述,我们可以将每个字母看作一个节点,每对字母的转换成本看作一条有向边。那么我们先初始化一个 $26 \times 26$ 的二维数组 $g$,其中 $g[i][j]$ 表示字母 $i$ 转换成字母 $j$ 的最小成本。初始时 $g[i][j] = \infty$,如果 $i = j$,那么 $g[i][j] = 0$。 @@ -83,10 +81,6 @@ -### **Python3** - - - ```python class Solution: def minimumCost( @@ -118,10 +112,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public long minimumCost( @@ -162,8 +152,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -207,8 +195,6 @@ public: }; ``` -### **Go** - ```go func minimumCost(source string, target string, original []byte, changed []byte, cost []int) (ans int64) { const inf = 1 << 29 @@ -253,8 +239,6 @@ func minimumCost(source string, target string, original []byte, changed []byte, } ``` -### **TypeScript** - ```ts function minimumCost( source: string, @@ -298,10 +282,6 @@ function minimumCost( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2976.Minimum Cost to Convert String I/README_EN.md b/solution/2900-2999/2976.Minimum Cost to Convert String I/README_EN.md index 17400f515009d..ea7918a619d40 100644 --- a/solution/2900-2999/2976.Minimum Cost to Convert String I/README_EN.md +++ b/solution/2900-2999/2976.Minimum Cost to Convert String I/README_EN.md @@ -57,7 +57,7 @@ It can be shown that this is the minimum possible cost. ## Solutions -**Solution 1: Floyd Algorithm** +### Solution 1: Floyd Algorithm According to the problem description, we can consider each letter as a node, and the conversion cost between each pair of letters as a directed edge. We first initialize a $26 \times 26$ two-dimensional array $g$, where $g[i][j]$ represents the minimum cost of converting letter $i$ to letter $j$. Initially, $g[i][j] = \infty$, and if $i = j$, then $g[i][j] = 0$. @@ -71,8 +71,6 @@ The time complexity is $O(m + n + |\Sigma|^3)$, and the space complexity is $O(| -### **Python3** - ```python class Solution: def minimumCost( @@ -104,8 +102,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public long minimumCost( @@ -146,8 +142,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -191,8 +185,6 @@ public: }; ``` -### **Go** - ```go func minimumCost(source string, target string, original []byte, changed []byte, cost []int) (ans int64) { const inf = 1 << 29 @@ -237,8 +229,6 @@ func minimumCost(source string, target string, original []byte, changed []byte, } ``` -### **TypeScript** - ```ts function minimumCost( source: string, @@ -282,10 +272,6 @@ function minimumCost( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2977.Minimum Cost to Convert String II/README.md b/solution/2900-2999/2977.Minimum Cost to Convert String II/README.md index 96bfd355306a7..64bed3c7c5f98 100644 --- a/solution/2900-2999/2977.Minimum Cost to Convert String II/README.md +++ b/solution/2900-2999/2977.Minimum Cost to Convert String II/README.md @@ -76,9 +76,7 @@ ## 解法 - - -**方法一:字典树 + Floyd 算法 + 记忆化搜索** +### 方法一:字典树 + Floyd 算法 + 记忆化搜索 根据题目描述,我们可以将每个字符串看作一个节点,每对字符串的转换成本看作一条有向边。那么我们先初始化一个 $26 \times 26$ 的二维数组 $g$,其中 $g[i][j]$ 表示字符串 $i$ 转换成字符串 $j$ 的最小成本。初始时 $g[i][j] = \infty$,如果 $i = j$,那么 $g[i][j] = 0$。在这里,我们可以借助字典树存储 `original` 和 `changed` 中的字符串以及对应的整数编号。 @@ -109,10 +107,6 @@ $$ -### **Python3** - - - ```python class Node: __slots__ = ["children", "v"] @@ -184,10 +178,6 @@ class Solution: return -1 if ans >= inf else ans ``` -### **Java** - - - ```java class Node { Node[] children = new Node[26]; @@ -277,8 +267,6 @@ class Solution { } ``` -### **C++** - ```cpp class Node { public: @@ -378,8 +366,6 @@ private: }; ``` -### **Go** - ```go type Node struct { children [26]*Node @@ -472,8 +458,6 @@ func minimumCost(source string, target string, original []string, changed []stri } ``` -### **TypeScript** - ```ts class Node { children: (Node | null)[] = Array(26).fill(null); @@ -554,10 +538,6 @@ function minimumCost( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2977.Minimum Cost to Convert String II/README_EN.md b/solution/2900-2999/2977.Minimum Cost to Convert String II/README_EN.md index cf0f600d23475..f4b37844d7f2f 100644 --- a/solution/2900-2999/2977.Minimum Cost to Convert String II/README_EN.md +++ b/solution/2900-2999/2977.Minimum Cost to Convert String II/README_EN.md @@ -70,7 +70,7 @@ If you select substring source[3..7] as the first operation to change "abcd ## Solutions -**Solution 1: Trie + Floyd Algorithm + Memoization Search** +### Solution 1: Trie + Floyd Algorithm + Memoization Search According to the problem description, we can consider each string as a node, and the conversion cost between each pair of strings as a directed edge. We first initialize a $26 \times 26$ two-dimensional array $g$, where $g[i][j]$ represents the minimum cost of converting string $i$ to string $j$. Initially, $g[i][j] = \infty$, and if $i = j$, then $g[i][j] = 0$. Here, we can use a trie to store the strings in `original` and `changed` along with their corresponding integer identifiers. @@ -101,8 +101,6 @@ The time complexity is $O(m^3 + n^2 + m \times n)$, and the space complexity is -### **Python3** - ```python class Node: __slots__ = ["children", "v"] @@ -174,8 +172,6 @@ class Solution: return -1 if ans >= inf else ans ``` -### **Java** - ```java class Node { Node[] children = new Node[26]; @@ -265,8 +261,6 @@ class Solution { } ``` -### **C++** - ```cpp class Node { public: @@ -366,8 +360,6 @@ private: }; ``` -### **Go** - ```go type Node struct { children [26]*Node @@ -460,8 +452,6 @@ func minimumCost(source string, target string, original []string, changed []stri } ``` -### **TypeScript** - ```ts class Node { children: (Node | null)[] = Array(26).fill(null); @@ -542,10 +532,6 @@ function minimumCost( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2978.Symmetric Coordinates/README.md b/solution/2900-2999/2978.Symmetric Coordinates/README.md index 158c1273bcff6..61f8774596645 100644 --- a/solution/2900-2999/2978.Symmetric Coordinates/README.md +++ b/solution/2900-2999/2978.Symmetric Coordinates/README.md @@ -59,18 +59,12 @@ The output table is sorted by X and Y in ascending order. ## 解法 - - -**方法一:窗口函数 + 自连接** +### 方法一:窗口函数 + 自连接 我们可以使用窗口函数 `ROW_NUMBER()` 来为每一行添加一个自增的序号,然后再自连接两张表,连接条件为 `p1.x = p2.y AND p1.y = p2.x AND p1.x <= p1.y AND p1.id != p2.id`,最后再排序去重即可。 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -91,3 +85,5 @@ ORDER BY 1, 2; ``` + + diff --git a/solution/2900-2999/2978.Symmetric Coordinates/README_EN.md b/solution/2900-2999/2978.Symmetric Coordinates/README_EN.md index c4431de2a274e..af3ad547b4edc 100644 --- a/solution/2900-2999/2978.Symmetric Coordinates/README_EN.md +++ b/solution/2900-2999/2978.Symmetric Coordinates/README_EN.md @@ -57,14 +57,12 @@ The output table is sorted by X and Y in ascending order. ## Solutions -**Solution 1: Window Function + Self Join** +### Solution 1: Window Function + Self Join We can use the window function `ROW_NUMBER()` to add an auto-incrementing sequence number to each row. Then, we perform a self join on the two tables, with the join conditions being `p1.x = p2.y AND p1.y = p2.x AND p1.x <= p1.y AND p1.id != p2.id`. Finally, we sort and remove duplicates. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -85,3 +83,5 @@ ORDER BY 1, 2; ``` + + diff --git a/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/README.md b/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/README.md index 5cefc537853f8..0ed1cd3b4e856 100644 --- a/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/README.md +++ b/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/README.md @@ -42,9 +42,7 @@ ## 解法 - - -**方法一:Chicken McNugget 定理** +### 方法一:Chicken McNugget 定理 根据 Chicken McNugget 定理,两个互质的正整数 $a$ 和 $b$,最大不能表示的数为 $ab - a - b$。 @@ -52,20 +50,12 @@ -### **Python3** - - - ```python class Solution: def mostExpensiveItem(self, primeOne: int, primeTwo: int) -> int: return primeOne * primeTwo - primeOne - primeTwo ``` -### **Java** - - - ```java class Solution { public int mostExpensiveItem(int primeOne, int primeTwo) { @@ -74,8 +64,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -85,24 +73,18 @@ public: }; ``` -### **Go** - ```go func mostExpensiveItem(primeOne int, primeTwo int) int { return primeOne*primeTwo - primeOne - primeTwo } ``` -### **TypeScript** - ```ts function mostExpensiveItem(primeOne: number, primeTwo: number): number { return primeOne * primeTwo - primeOne - primeTwo; } ``` -### **Rust** - ```rust impl Solution { pub fn most_expensive_item(prime_one: i32, prime_two: i32) -> i32 { @@ -111,10 +93,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/README_EN.md b/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/README_EN.md index 99b996f179c12..f8284dec3feda 100644 --- a/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/README_EN.md +++ b/solution/2900-2999/2979.Most Expensive Item That Can Not Be Bought/README_EN.md @@ -38,7 +38,7 @@ ## Solutions -**Solution 1: Chicken McNugget Theorem** +### Solution 1: Chicken McNugget Theorem According to the Chicken McNugget Theorem, for two coprime positive integers $a$ and $b$, the largest number that cannot be expressed as a combination of $a$ and $b$ is $ab - a - b$. @@ -46,16 +46,12 @@ The time complexity is $O(1)$, and the space complexity is $O(1)$. -### **Python3** - ```python class Solution: def mostExpensiveItem(self, primeOne: int, primeTwo: int) -> int: return primeOne * primeTwo - primeOne - primeTwo ``` -### **Java** - ```java class Solution { public int mostExpensiveItem(int primeOne, int primeTwo) { @@ -64,8 +60,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -75,24 +69,18 @@ public: }; ``` -### **Go** - ```go func mostExpensiveItem(primeOne int, primeTwo int) int { return primeOne*primeTwo - primeOne - primeTwo } ``` -### **TypeScript** - ```ts function mostExpensiveItem(primeOne: number, primeTwo: number): number { return primeOne * primeTwo - primeOne - primeTwo; } ``` -### **Rust** - ```rust impl Solution { pub fn most_expensive_item(prime_one: i32, prime_two: i32) -> i32 { @@ -101,10 +89,6 @@ impl Solution { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/README.md b/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/README.md index dd714536afff4..e6f9d3a3adb95 100644 --- a/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/README.md +++ b/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:统计偶数个数** +### 方法一:统计偶数个数 根据题意,我们可以知道,如果数组中存在两个或两个以上的元素,其按位或运算结果存在尾随零,那么数组中必然存在至少两个偶数。因此,我们可以统计数组中偶数的个数,如果偶数的个数大于等于 $2$,那么就返回 `true`,否则返回 `false`。 @@ -62,20 +60,12 @@ -### **Python3** - - - ```python class Solution: def hasTrailingZeros(self, nums: List[int]) -> bool: return sum(x & 1 ^ 1 for x in nums) >= 2 ``` -### **Java** - - - ```java class Solution { public boolean hasTrailingZeros(int[] nums) { @@ -88,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -103,8 +91,6 @@ public: }; ``` -### **Go** - ```go func hasTrailingZeros(nums []int) bool { cnt := 0 @@ -115,8 +101,6 @@ func hasTrailingZeros(nums []int) bool { } ``` -### **TypeScript** - ```ts function hasTrailingZeros(nums: number[]): boolean { let cnt = 0; @@ -127,10 +111,6 @@ function hasTrailingZeros(nums: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/README_EN.md b/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/README_EN.md index 752103cf6f8c6..cd778270bcb38 100644 --- a/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/README_EN.md +++ b/solution/2900-2999/2980.Check if Bitwise OR Has Trailing Zeros/README_EN.md @@ -48,7 +48,7 @@ Other possible ways to select elements to have trailing zeroes in the binary rep ## Solutions -**Solution 1: Counting Even Numbers** +### Solution 1: Counting Even Numbers According to the problem statement, if there are two or more elements in the array whose bitwise OR operation results in trailing zeros, then there must be at least two even numbers in the array. Therefore, we can count the number of even numbers in the array. If the count of even numbers is greater than or equal to $2$, then return `true`, otherwise return `false`. @@ -56,16 +56,12 @@ The time complexity is $O(n)$, where $n$ is the length of the array. The space c -### **Python3** - ```python class Solution: def hasTrailingZeros(self, nums: List[int]) -> bool: return sum(x & 1 ^ 1 for x in nums) >= 2 ``` -### **Java** - ```java class Solution { public boolean hasTrailingZeros(int[] nums) { @@ -78,8 +74,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -93,8 +87,6 @@ public: }; ``` -### **Go** - ```go func hasTrailingZeros(nums []int) bool { cnt := 0 @@ -105,8 +97,6 @@ func hasTrailingZeros(nums []int) bool { } ``` -### **TypeScript** - ```ts function hasTrailingZeros(nums: number[]): boolean { let cnt = 0; @@ -117,10 +107,6 @@ function hasTrailingZeros(nums: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/README.md b/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/README.md index 597e9c51e2a03..50b0e385c7d33 100644 --- a/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/README.md +++ b/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:二分查找 + 滑动窗口计数** +### 方法一:二分查找 + 滑动窗口计数 我们注意到,如果一个长度为 $x$ 且出现至少三次的特殊子字符串存在,那么长度为 $x-1$ 的特殊子字符串也一定存在,这存在着单调性,因此我们可以使用二分查找的方法来找到最长的特殊子字符串。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def maximumLength(self, s: str) -> int: @@ -100,10 +94,6 @@ class Solution: return -1 if l == 0 else l ``` -### **Java** - - - ```java class Solution { private String s; @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -180,8 +168,6 @@ public: }; ``` -### **Go** - ```go func maximumLength(s string) int { n := len(s) @@ -217,8 +203,6 @@ func maximumLength(s string) int { } ``` -### **TypeScript** - ```ts function maximumLength(s: string): number { const n = s.length; @@ -251,10 +235,6 @@ function maximumLength(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/README_EN.md b/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/README_EN.md index 47e8831897ead..865ee665927ef 100644 --- a/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/README_EN.md +++ b/solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/README_EN.md @@ -49,7 +49,7 @@ It can be shown that the maximum length achievable is 1. ## Solutions -**Solution 1: Binary Search + Sliding Window Counting** +### Solution 1: Binary Search + Sliding Window Counting We notice that if there exists a special substring of length $x$ that appears at least three times, then a special substring of length $x-1$ must also exist. This exhibits a monotonicity, so we can use binary search to find the longest special substring. @@ -65,8 +65,6 @@ The time complexity is $O((n + |\Sigma|) \times \log n)$, and the space complexi -### **Python3** - ```python class Solution: def maximumLength(self, s: str) -> int: @@ -92,8 +90,6 @@ class Solution: return -1 if l == 0 else l ``` -### **Java** - ```java class Solution { private String s; @@ -133,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +164,6 @@ public: }; ``` -### **Go** - ```go func maximumLength(s string) int { n := len(s) @@ -207,8 +199,6 @@ func maximumLength(s string) int { } ``` -### **TypeScript** - ```ts function maximumLength(s: string): number { const n = s.length; @@ -241,10 +231,6 @@ function maximumLength(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/README.md b/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/README.md index 7dbc5017fdcc0..9bf81187c7496 100644 --- a/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/README.md +++ b/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/README.md @@ -53,9 +53,7 @@ ## 解法 - - -**方法一:二分查找 + 滑动窗口计数** +### 方法一:二分查找 + 滑动窗口计数 我们注意到,如果一个长度为 $x$ 且出现至少三次的特殊子字符串存在,那么长度为 $x-1$ 的特殊子字符串也一定存在,这存在着单调性,因此我们可以使用二分查找的方法来找到最长的特殊子字符串。 @@ -71,10 +69,6 @@ -### **Python3** - - - ```python class Solution: def maximumLength(self, s: str) -> int: @@ -100,10 +94,6 @@ class Solution: return -1 if l == 0 else l ``` -### **Java** - - - ```java class Solution { private String s; @@ -143,8 +133,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -180,8 +168,6 @@ public: }; ``` -### **Go** - ```go func maximumLength(s string) int { n := len(s) @@ -217,8 +203,6 @@ func maximumLength(s string) int { } ``` -### **TypeScript** - ```ts function maximumLength(s: string): number { const n = s.length; @@ -251,10 +235,6 @@ function maximumLength(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/README_EN.md b/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/README_EN.md index f421c8b4c8486..5d5a65e28bc2b 100644 --- a/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/README_EN.md +++ b/solution/2900-2999/2982.Find Longest Special Substring That Occurs Thrice II/README_EN.md @@ -49,7 +49,7 @@ It can be shown that the maximum length achievable is 1. ## Solutions -**Solution 1: Binary Search + Sliding Window Counting** +### Solution 1: Binary Search + Sliding Window Counting We notice that if there exists a special substring of length $x$ that appears at least three times, then a special substring of length $x-1$ must also exist. This exhibits a monotonicity, so we can use binary search to find the longest special substring. @@ -65,8 +65,6 @@ The time complexity is $O((n + |\Sigma|) \times \log n)$, and the space complexi -### **Python3** - ```python class Solution: def maximumLength(self, s: str) -> int: @@ -92,8 +90,6 @@ class Solution: return -1 if l == 0 else l ``` -### **Java** - ```java class Solution { private String s; @@ -133,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +164,6 @@ public: }; ``` -### **Go** - ```go func maximumLength(s string) int { n := len(s) @@ -207,8 +199,6 @@ func maximumLength(s string) int { } ``` -### **TypeScript** - ```ts function maximumLength(s: string): number { const n = s.length; @@ -241,10 +231,6 @@ function maximumLength(s: string): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2983.Palindrome Rearrangement Queries/README.md b/solution/2900-2999/2983.Palindrome Rearrangement Queries/README.md index c2e2b8c43f662..a7eda25f463b5 100644 --- a/solution/2900-2999/2983.Palindrome Rearrangement Queries/README.md +++ b/solution/2900-2999/2983.Palindrome Rearrangement Queries/README.md @@ -89,9 +89,7 @@ a0 = 1, b0 = 2, c0 = 4, d0 = 5. ## 解法 - - -**方法一:前缀和 + 分类讨论** +### 方法一:前缀和 + 分类讨论 我们记字符串 $s$ 的长度为 $n$,那么一半的长度为 $m = \frac{n}{2}$。接下来,我们把字符串 $s$ 分成长度相等的两段,其中第二段反转后得到字符串 $t$,第一段记为 $s$。那么对于每个查询 $[a_i, b_i, c_i, d_i]$,其中 $c_i$ 和 $d_i$ 需要变换为 $n - 1 - d_i$ 和 $n - 1 - c_i$。问题转化为:对于每个查询 $[a_i, b_i, c_i, d_i]$,判断 $s[a_i, b_i]$ 和 $t[c_i, d_i]$ 是否可以通过重新排列,使得字符串 $s$ 和 $t$ 相等。 @@ -114,10 +112,6 @@ a0 = 1, b0 = 2, c0 = 4, d0 = 5. -### **Python3** - - - ```python class Solution: def canMakePalindromeQueries(self, s: str, queries: List[List[int]]) -> List[bool]: @@ -174,10 +168,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public boolean[] canMakePalindromeQueries(String s, int[][] queries) { @@ -245,8 +235,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -319,8 +307,6 @@ private: }; ``` -### **Go** - ```go func canMakePalindromeQueries(s string, queries [][]int) (ans []bool) { n := len(s) @@ -403,8 +389,6 @@ func reverse(s string) string { } ``` -### **TypeScript** - ```ts function canMakePalindromeQueries(s: string, queries: number[][]): boolean[] { const n: number = s.length; @@ -488,10 +472,6 @@ function arraysEqual(arr1: number[], arr2: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2983.Palindrome Rearrangement Queries/README_EN.md b/solution/2900-2999/2983.Palindrome Rearrangement Queries/README_EN.md index b0f43aa7fa90b..9867d6ec27ff3 100644 --- a/solution/2900-2999/2983.Palindrome Rearrangement Queries/README_EN.md +++ b/solution/2900-2999/2983.Palindrome Rearrangement Queries/README_EN.md @@ -85,7 +85,7 @@ Now, s is a palindrome. So, answer[0] = true. ## Solutions -**Solution 1: Prefix Sum + Case Discussion** +### Solution 1: Prefix Sum + Case Discussion Let's denote the length of string $s$ as $n$, then half of the length is $m = \frac{n}{2}$. Next, we divide string $s$ into two equal-length segments, where the second segment is reversed to get string $t$, and the first segment remains as $s$. For each query $[a_i, b_i, c_i, d_i]$, where $c_i$ and $d_i$ need to be transformed to $n - 1 - d_i$ and $n - 1 - c_i$. The problem is transformed into: for each query $[a_i, b_i, c_i, d_i]$, determine whether $s[a_i, b_i]$ and $t[c_i, d_i]$ can be rearranged to make strings $s$ and $t$ equal. @@ -108,8 +108,6 @@ The time complexity is $O((n + q) \times |\Sigma|)$, and the space complexity is -### **Python3** - ```python class Solution: def canMakePalindromeQueries(self, s: str, queries: List[List[int]]) -> List[bool]: @@ -166,8 +164,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public boolean[] canMakePalindromeQueries(String s, int[][] queries) { @@ -235,8 +231,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -309,8 +303,6 @@ private: }; ``` -### **Go** - ```go func canMakePalindromeQueries(s string, queries [][]int) (ans []bool) { n := len(s) @@ -393,8 +385,6 @@ func reverse(s string) string { } ``` -### **TypeScript** - ```ts function canMakePalindromeQueries(s: string, queries: number[][]): boolean[] { const n: number = s.length; @@ -478,10 +468,6 @@ function arraysEqual(arr1: number[], arr2: number[]): boolean { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2984.Find Peak Calling Hours for Each City/README.md b/solution/2900-2999/2984.Find Peak Calling Hours for Each City/README.md index bedfe3109fb25..5c594a581a41b 100644 --- a/solution/2900-2999/2984.Find Peak Calling Hours for Each City/README.md +++ b/solution/2900-2999/2984.Find Peak Calling Hours for Each City/README.md @@ -61,14 +61,10 @@ Calls table: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -96,3 +92,5 @@ ORDER BY 2 DESC, 1 DESC; ``` + + diff --git a/solution/2900-2999/2984.Find Peak Calling Hours for Each City/README_EN.md b/solution/2900-2999/2984.Find Peak Calling Hours for Each City/README_EN.md index b402b3a54e5ff..5c1c7da3e9130 100644 --- a/solution/2900-2999/2984.Find Peak Calling Hours for Each City/README_EN.md +++ b/solution/2900-2999/2984.Find Peak Calling Hours for Each City/README_EN.md @@ -58,9 +58,9 @@ Output table is ordered by peak_calling_hour and city in descending order. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -89,3 +89,5 @@ ORDER BY 2 DESC, 1 DESC; ``` + + diff --git a/solution/2900-2999/2985.Calculate Compressed Mean/README.md b/solution/2900-2999/2985.Calculate Compressed Mean/README.md index 0af0a5c3afb61..43c81e49f891f 100644 --- a/solution/2900-2999/2985.Calculate Compressed Mean/README.md +++ b/solution/2900-2999/2985.Calculate Compressed Mean/README.md @@ -56,18 +56,12 @@ Orders table: ## 解法 - - -**方法一:求和** +### 方法一:求和 我们使用 `SUM` 函数求出总的商品数量和总的订单数,然后相除,得到平均值,最后使用 `ROUND` 函数保留两位小数即可。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -79,3 +73,5 @@ FROM Orders; ``` + + diff --git a/solution/2900-2999/2985.Calculate Compressed Mean/README_EN.md b/solution/2900-2999/2985.Calculate Compressed Mean/README_EN.md index 42ad8a05024d4..ea3a75f025003 100644 --- a/solution/2900-2999/2985.Calculate Compressed Mean/README_EN.md +++ b/solution/2900-2999/2985.Calculate Compressed Mean/README_EN.md @@ -52,14 +52,12 @@ The calculation is as follows: ## Solutions -**Solution 1: Summation** +### Solution 1: Summation We use the `SUM` function to calculate the total quantity of products and the total number of orders, then divide the total quantity by the total number of orders to get the average. Finally, we use the `ROUND` function to round the result to two decimal places. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -71,3 +69,5 @@ FROM Orders; ``` + + diff --git a/solution/2900-2999/2986.Find Third Transaction/README.md b/solution/2900-2999/2986.Find Third Transaction/README.md index 9292c8765d4b3..9ae8a13ba8c4d 100644 --- a/solution/2900-2999/2986.Find Third Transaction/README.md +++ b/solution/2900-2999/2986.Find Third Transaction/README.md @@ -62,14 +62,10 @@ Transactions table: ## 解法 - +### 方法一 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -100,3 +96,5 @@ WHERE rk = 3 AND st = 1; ``` + + diff --git a/solution/2900-2999/2986.Find Third Transaction/README_EN.md b/solution/2900-2999/2986.Find Third Transaction/README_EN.md index 85d3d6a6a8b29..f60f2529b8425 100644 --- a/solution/2900-2999/2986.Find Third Transaction/README_EN.md +++ b/solution/2900-2999/2986.Find Third Transaction/README_EN.md @@ -59,9 +59,9 @@ Output table is ordered by user_id in ascending order. ## Solutions - +### Solution 1 -### **SQL** + ```sql # Write your MySQL query statement below @@ -93,3 +93,5 @@ WHERE rk = 3 AND st = 1; ``` + + diff --git a/solution/2900-2999/2987.Find Expensive Cities/README.md b/solution/2900-2999/2987.Find Expensive Cities/README.md index a3d33d7308e89..68ac874c0acad 100644 --- a/solution/2900-2999/2987.Find Expensive Cities/README.md +++ b/solution/2900-2999/2987.Find Expensive Cities/README.md @@ -66,18 +66,12 @@ Listings table: ## 解法 - - -**方法一:分组聚合 + 子查询** +### 方法一:分组聚合 + 子查询 我们将 `Listings` 表按照 `city` 分组,然后计算每个城市的平均房价,最后筛选出平均房价大于全国平均房价的城市即可。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT city @@ -88,3 +82,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2900-2999/2987.Find Expensive Cities/README_EN.md b/solution/2900-2999/2987.Find Expensive Cities/README_EN.md index 399f28b3e7abb..17e2201645bc4 100644 --- a/solution/2900-2999/2987.Find Expensive Cities/README_EN.md +++ b/solution/2900-2999/2987.Find Expensive Cities/README_EN.md @@ -64,14 +64,12 @@ Only Chicago and Los Angeles have average home prices exceeding the national ave ## Solutions -**Solution 1: Grouping Aggregation + Subquery** +### Solution 1: Grouping Aggregation + Subquery We group the `Listings` table by `city`, then calculate the average house price for each city, and finally filter out the cities where the average house price is greater than the national average house price. -### **SQL** - ```sql # Write your MySQL query statement below SELECT city @@ -82,3 +80,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2900-2999/2988.Manager of the Largest Department/README.md b/solution/2900-2999/2988.Manager of the Largest Department/README.md index b5db68abf00e6..b2ef1da6fa927 100644 --- a/solution/2900-2999/2988.Manager of the Largest Department/README.md +++ b/solution/2900-2999/2988.Manager of the Largest Department/README.md @@ -64,18 +64,12 @@ Employees table: ## 解法 - - -**方法一:分组 + 等值连接 + 子查询** +### 方法一:分组 + 等值连接 + 子查询 我们可以先统计每个部门的员工数量,记为表 `T`,然后我们将 `T` 与 `Employees` 表进行连接,连接条件为 `T.dep_id = Employees.dep_id`,并且 `Employees.position = 'Manager'`,这样就可以得到每个部门的经理,最后我们再筛选出员工数量最多的部门即可。 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -93,3 +87,5 @@ ORDER BY 2; ``` + + diff --git a/solution/2900-2999/2988.Manager of the Largest Department/README_EN.md b/solution/2900-2999/2988.Manager of the Largest Department/README_EN.md index 4511ca3142c1f..cf4e0bd3c2aad 100644 --- a/solution/2900-2999/2988.Manager of the Largest Department/README_EN.md +++ b/solution/2900-2999/2988.Manager of the Largest Department/README_EN.md @@ -61,14 +61,12 @@ Output table is ordered by dep_id in ascending order. ## Solutions -**Solution 1: Grouping + Equi-Join + Subquery** +### Solution 1: Grouping + Equi-Join + Subquery We can first count the number of employees in each department, denoted as table `T`. Then we join `T` with the `Employees` table, with the join condition being `T.dep_id = Employees.dep_id` and `Employees.position = 'Manager'`. This way, we can get the manager of each department. Finally, we filter out the department with the most employees. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -86,3 +84,5 @@ ORDER BY 2; ``` + + diff --git a/solution/2900-2999/2989.Class Performance/README.md b/solution/2900-2999/2989.Class Performance/README.md index 1c84d39e80dbc..2d98fa9c46d39 100644 --- a/solution/2900-2999/2989.Class Performance/README.md +++ b/solution/2900-2999/2989.Class Performance/README.md @@ -63,18 +63,12 @@ student_id 321 的最高分为 230,而 student_id 896 的最低分为 119。 ## 解法 - - -**方法一:最大值最小值** +### 方法一:最大值最小值 我们可以使用 `MAX` 和 `MIN` 函数来分别获取 `assignment1`、`assignment2`、`assignment3` 的和的最大值和最小值,然后相减即可。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -85,3 +79,5 @@ FROM Scores; ``` + + diff --git a/solution/2900-2999/2989.Class Performance/README_EN.md b/solution/2900-2999/2989.Class Performance/README_EN.md index 1f0233186bb80..77c0a4a692394 100644 --- a/solution/2900-2999/2989.Class Performance/README_EN.md +++ b/solution/2900-2999/2989.Class Performance/README_EN.md @@ -60,14 +60,12 @@ student_id 321 has the highest score of 230, while student_id 896 has the lowest ## Solutions -**Solution 1: Maximum and Minimum** +### Solution 1: Maximum and Minimum We can use the `MAX` and `MIN` functions to get the maximum and minimum sums of `assignment1`, `assignment2`, and `assignment3`, respectively. Then, subtract the minimum from the maximum. -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -78,3 +76,5 @@ FROM Scores; ``` + + diff --git a/solution/2900-2999/2990.Loan Types/README.md b/solution/2900-2999/2990.Loan Types/README.md index a014c01a8a7fa..f9c80c85f8808 100644 --- a/solution/2900-2999/2990.Loan Types/README.md +++ b/solution/2900-2999/2990.Loan Types/README.md @@ -61,18 +61,12 @@ Sessions table: ## 解法 - - -**方法一:分组求和** +### 方法一:分组求和 我们可以对 `Loans` 表按照 `user_id` 进行分组,找出既包含 `Refinance` 又包含 `Mortgage` 的用户,然后按照 `user_id` 进行排序。 -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT user_id @@ -83,3 +77,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2900-2999/2990.Loan Types/README_EN.md b/solution/2900-2999/2990.Loan Types/README_EN.md index bd004d0542d3c..7f0c02aa76e80 100644 --- a/solution/2900-2999/2990.Loan Types/README_EN.md +++ b/solution/2900-2999/2990.Loan Types/README_EN.md @@ -58,14 +58,12 @@ Output table is ordered by user_id in ascending order. ## Solutions -**Solution 1: Grouping and Summation** +### Solution 1: Grouping and Summation We can group the `Loans` table by `user_id` to find users who have both `Refinance` and `Mortgage`. Then, sort the results by `user_id`. -### **SQL** - ```sql # Write your MySQL query statement below SELECT user_id @@ -76,3 +74,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2900-2999/2991.Top Three Wineries/README.md b/solution/2900-2999/2991.Top Three Wineries/README.md index b786dd6223d0b..46bf7d32dddda 100644 --- a/solution/2900-2999/2991.Top Three Wineries/README.md +++ b/solution/2900-2999/2991.Top Three Wineries/README.md @@ -74,9 +74,7 @@ Sessions table: ## 解法 - - -**方法一:分组 + 窗口函数 + 左连接** +### 方法一:分组 + 窗口函数 + 左连接 我们可以先对 `Wineries` 表按照 `country` 和 `winery` 进行分组,计算每个分组的总得分 `points`,然后再利用窗口函数 `RANK()` 将数据再按照 `country` 进行分组,按照 `points` 降序、`winery` 升序进行排序,并且用 `CONCAT()` 函数将 `winery` 和 `points` 进行拼接,得到如下形式的数据,记为 `T` 表: @@ -95,10 +93,6 @@ Sessions table: -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -126,3 +120,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2900-2999/2991.Top Three Wineries/README_EN.md b/solution/2900-2999/2991.Top Three Wineries/README_EN.md index da2d74abda4ff..c8ae065f65509 100644 --- a/solution/2900-2999/2991.Top Three Wineries/README_EN.md +++ b/solution/2900-2999/2991.Top Three Wineries/README_EN.md @@ -71,7 +71,7 @@ Output table is ordered by country in ascending order. ## Solutions -**Solution 1: Grouping + Window Function + Left Join** +### Solution 1: Grouping + Window Function + Left Join We can first group the `Wineries` table by `country` and `winery`, calculate the total score `points` for each group, then use the window function `RANK()` to group the data by `country` again, sort by `points` in descending order and `winery` in ascending order, and use the `CONCAT()` function to concatenate `winery` and `points`, resulting in the following data, denoted as table `T`: @@ -90,8 +90,6 @@ Next, we just need to filter out the data where `rk = 1`, then join table `T` to -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -119,3 +117,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2900-2999/2992.Number of Self-Divisible Permutations/README.md b/solution/2900-2999/2992.Number of Self-Divisible Permutations/README.md index 1c513ba3123d6..307797b0e7249 100644 --- a/solution/2900-2999/2992.Number of Self-Divisible Permutations/README.md +++ b/solution/2900-2999/2992.Number of Self-Divisible Permutations/README.md @@ -65,9 +65,7 @@ nums = [2,1]:这是自整除的,因为 nums[1] % 1 == 0 和 2 % nums[2] == 0 ## 解法 - - -**方法一:状态压缩 + 记忆化搜索** +### 方法一:状态压缩 + 记忆化搜索 我们可以用一个二进制数 $mask$ 来表示当前排列的状态,其中第 $i$ 位为 $1$ 表示数字 $i$ 已经被使用,为 $0$ 表示数字 $i$ 还未被使用。 @@ -83,22 +81,8 @@ nums = [2,1]:这是自整除的,因为 nums[1] % 1 == 0 和 2 % nums[2] == 0 时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(2^n)$。其中 $n$ 为排列的长度。 -**方法二:状态压缩 + 动态规划** - -我们可以将方法一中的记忆化搜索改写为动态规划的形式,定义 $f[mask]$ 表示当前排列的状态为 $mask$,且满足题目要求的排列的数量。初始时 $f[0]=1$,其余值均为 $0$。 - -我们在 $[0, 2^n)$ 的范围内枚举 $mask$,对于每个 $mask$,我们用 $i$ 表示当前最后一个加入排列的是第几个数字,然后我们枚举当前排列中最后一个加入的数字 $j$,如果 $i$ 和 $j$ 满足题目要求,那么状态 $f[mask]$ 就可以从状态 $f[mask \oplus 2^(j-1)]$ 转移而来,其中 $\oplus$ 表示按位异或运算。我们将所有转移得到的状态 $f[mask \oplus 2^(j-1)]$ 的值累加到 $f[mask]$ 上,即为 $f[mask]$ 的值。 - -最终,我们可以得到 $f[2^n - 1]$ 的值,即为答案。 - -时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(2^n)$。其中 $n$ 为排列的长度。 - -### **Python3** - - - ```python class Solution: def selfDivisiblePermutationCount(self, n: int) -> int: @@ -116,23 +100,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def selfDivisiblePermutationCount(self, n: int) -> int: - f = [0] * (1 << n) - f[0] = 1 - for mask in range(1 << n): - i = mask.bit_count() - for j in range(1, n + 1): - if (mask >> (j - 1) & 1) == 1 and (i % j == 0 or j % i == 0): - f[mask] += f[mask ^ (1 << (j - 1))] - return f[-1] -``` - -### **Java** - - - ```java class Solution { private int n; @@ -163,26 +130,6 @@ class Solution { } ``` -```java -class Solution { - public int selfDivisiblePermutationCount(int n) { - int[] f = new int[1 << n]; - f[0] = 1; - for (int mask = 0; mask < 1 << n; ++mask) { - int i = Integer.bitCount(mask); - for (int j = 1; j <= n; ++j) { - if (((mask >> (j - 1)) & 1) == 1 && (i % j == 0 || j % i == 0)) { - f[mask] += f[mask ^ (1 << (j - 1))]; - } - } - } - return f[(1 << n) - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -210,28 +157,6 @@ public: }; ``` -```cpp -class Solution { -public: - int selfDivisiblePermutationCount(int n) { - int f[1 << n]; - memset(f, 0, sizeof(f)); - f[0] = 1; - for (int mask = 0; mask < 1 << n; ++mask) { - int i = __builtin_popcount(mask); - for (int j = 1; j <= n; ++j) { - if (((mask >> (j - 1)) & 1) == 1 && (i % j == 0 || j % i == 0)) { - f[mask] += f[mask ^ (1 << (j - 1))]; - } - } - } - return f[(1 << n) - 1]; - } -}; -``` - -### **Go** - ```go func selfDivisiblePermutationCount(n int) int { f := make([]int, 1<<(n+1)) @@ -259,24 +184,6 @@ func selfDivisiblePermutationCount(n int) int { } ``` -```go -func selfDivisiblePermutationCount(n int) int { - f := make([]int, 1<>(j-1)&1 == 1 && (i%j == 0 || j%i == 0) { - f[mask] += f[mask^(1<<(j-1))] - } - } - } - return f[(1< + +### 方法二:状态压缩 + 动态规划 + +我们可以将方法一中的记忆化搜索改写为动态规划的形式,定义 $f[mask]$ 表示当前排列的状态为 $mask$,且满足题目要求的排列的数量。初始时 $f[0]=1$,其余值均为 $0$。 + +我们在 $[0, 2^n)$ 的范围内枚举 $mask$,对于每个 $mask$,我们用 $i$ 表示当前最后一个加入排列的是第几个数字,然后我们枚举当前排列中最后一个加入的数字 $j$,如果 $i$ 和 $j$ 满足题目要求,那么状态 $f[mask]$ 就可以从状态 $f[mask \oplus 2^(j-1)]$ 转移而来,其中 $\oplus$ 表示按位异或运算。我们将所有转移得到的状态 $f[mask \oplus 2^(j-1)]$ 的值累加到 $f[mask]$ 上,即为 $f[mask]$ 的值。 + +最终,我们可以得到 $f[2^n - 1]$ 的值,即为答案。 + +时间复杂度 $O(n \times 2^n)$,空间复杂度 $O(2^n)$。其中 $n$ 为排列的长度。 + + + +```python +class Solution: + def selfDivisiblePermutationCount(self, n: int) -> int: + f = [0] * (1 << n) + f[0] = 1 + for mask in range(1 << n): + i = mask.bit_count() + for j in range(1, n + 1): + if (mask >> (j - 1) & 1) == 1 and (i % j == 0 or j % i == 0): + f[mask] += f[mask ^ (1 << (j - 1))] + return f[-1] +``` + +```java +class Solution { + public int selfDivisiblePermutationCount(int n) { + int[] f = new int[1 << n]; + f[0] = 1; + for (int mask = 0; mask < 1 << n; ++mask) { + int i = Integer.bitCount(mask); + for (int j = 1; j <= n; ++j) { + if (((mask >> (j - 1)) & 1) == 1 && (i % j == 0 || j % i == 0)) { + f[mask] += f[mask ^ (1 << (j - 1))]; + } + } + } + return f[(1 << n) - 1]; + } +} +``` + +```cpp +class Solution { +public: + int selfDivisiblePermutationCount(int n) { + int f[1 << n]; + memset(f, 0, sizeof(f)); + f[0] = 1; + for (int mask = 0; mask < 1 << n; ++mask) { + int i = __builtin_popcount(mask); + for (int j = 1; j <= n; ++j) { + if (((mask >> (j - 1)) & 1) == 1 && (i % j == 0 || j % i == 0)) { + f[mask] += f[mask ^ (1 << (j - 1))]; + } + } + } + return f[(1 << n) - 1]; + } +}; +``` + +```go +func selfDivisiblePermutationCount(n int) int { + f := make([]int, 1<>(j-1)&1 == 1 && (i%j == 0 || j%i == 0) { + f[mask] += f[mask^(1<<(j-1))] + } + } + } + return f[(1< + + diff --git a/solution/2900-2999/2992.Number of Self-Divisible Permutations/README_EN.md b/solution/2900-2999/2992.Number of Self-Divisible Permutations/README_EN.md index f4b64ac40370d..e4b06d145d170 100644 --- a/solution/2900-2999/2992.Number of Self-Divisible Permutations/README_EN.md +++ b/solution/2900-2999/2992.Number of Self-Divisible Permutations/README_EN.md @@ -56,7 +56,7 @@ It can be shown that the other 3 permutations are not self-divisible. Hence the ## Solutions -**Solution 1: State Compression + Memoization Search** +### Solution 1: State Compression + Memoization Search We can use a binary number $mask$ to represent the current permutation state, where the $i$-th bit is $1$ indicates that the number $i$ has been used, and $0$ indicates that the number $i$ has not been used yet. @@ -72,20 +72,8 @@ Finally, we can get the value of $dfs(0)$, which is the answer. The time complexity is $O(n \times 2^n)$, and the space complexity is $O(2^n)$. Where $n$ is the length of the permutation. -**Solution 2: State Compression + Dynamic Programming** - -We can rewrite the memoization search in Solution 1 into the form of dynamic programming, define $f[mask]$ to represent the number of permutations that the current permutation state is $mask$ and meet the requirements of the problem. Initially, $f[0]=1$, and the rest are $0$. - -We enumerate $mask$ in the range of $[0, 2^n)$, for each $mask$, we use $i$ to represent which number is the last one to join the permutation, then we enumerate the last number $j$ added to the current permutation. If $i$ and $j$ meet the requirements of the problem, then the state $f[mask]$ can be transferred from the state $f[mask \oplus 2^(j-1)]$, where $\oplus$ represents bitwise XOR operation. We add all the values of the transferred state $f[mask \oplus 2^(j-1)]$ to $f[mask]$, which is the value of $f[mask]$. - -Finally, we can get the value of $f[2^n - 1]$, which is the answer. - -The time complexity is $O(n \times 2^n)$, and the space complexity is $O(2^n)$. Where $n$ is the length of the permutation. - -### **Python3** - ```python class Solution: def selfDivisiblePermutationCount(self, n: int) -> int: @@ -103,21 +91,6 @@ class Solution: return dfs(0) ``` -```python -class Solution: - def selfDivisiblePermutationCount(self, n: int) -> int: - f = [0] * (1 << n) - f[0] = 1 - for mask in range(1 << n): - i = mask.bit_count() - for j in range(1, n + 1): - if (mask >> (j - 1) & 1) == 1 and (i % j == 0 or j % i == 0): - f[mask] += f[mask ^ (1 << (j - 1))] - return f[-1] -``` - -### **Java** - ```java class Solution { private int n; @@ -148,26 +121,6 @@ class Solution { } ``` -```java -class Solution { - public int selfDivisiblePermutationCount(int n) { - int[] f = new int[1 << n]; - f[0] = 1; - for (int mask = 0; mask < 1 << n; ++mask) { - int i = Integer.bitCount(mask); - for (int j = 1; j <= n; ++j) { - if (((mask >> (j - 1)) & 1) == 1 && (i % j == 0 || j % i == 0)) { - f[mask] += f[mask ^ (1 << (j - 1))]; - } - } - } - return f[(1 << n) - 1]; - } -} -``` - -### **C++** - ```cpp class Solution { public: @@ -195,28 +148,6 @@ public: }; ``` -```cpp -class Solution { -public: - int selfDivisiblePermutationCount(int n) { - int f[1 << n]; - memset(f, 0, sizeof(f)); - f[0] = 1; - for (int mask = 0; mask < 1 << n; ++mask) { - int i = __builtin_popcount(mask); - for (int j = 1; j <= n; ++j) { - if (((mask >> (j - 1)) & 1) == 1 && (i % j == 0 || j % i == 0)) { - f[mask] += f[mask ^ (1 << (j - 1))]; - } - } - } - return f[(1 << n) - 1]; - } -}; -``` - -### **Go** - ```go func selfDivisiblePermutationCount(n int) int { f := make([]int, 1<<(n+1)) @@ -244,24 +175,6 @@ func selfDivisiblePermutationCount(n int) int { } ``` -```go -func selfDivisiblePermutationCount(n int) int { - f := make([]int, 1<>(j-1)&1 == 1 && (i%j == 0 || j%i == 0) { - f[mask] += f[mask^(1<<(j-1))] - } - } - } - return f[(1< + +### Solution 2: State Compression + Dynamic Programming + +We can rewrite the memoization search in Solution 1 into the form of dynamic programming, define $f[mask]$ to represent the number of permutations that the current permutation state is $mask$ and meet the requirements of the problem. Initially, $f[0]=1$, and the rest are $0$. + +We enumerate $mask$ in the range of $[0, 2^n)$, for each $mask$, we use $i$ to represent which number is the last one to join the permutation, then we enumerate the last number $j$ added to the current permutation. If $i$ and $j$ meet the requirements of the problem, then the state $f[mask]$ can be transferred from the state $f[mask \oplus 2^(j-1)]$, where $\oplus$ represents bitwise XOR operation. We add all the values of the transferred state $f[mask \oplus 2^(j-1)]$ to $f[mask]$, which is the value of $f[mask]$. + +Finally, we can get the value of $f[2^n - 1]$, which is the answer. + +The time complexity is $O(n \times 2^n)$, and the space complexity is $O(2^n)$. Where $n$ is the length of the permutation. + + + +```python +class Solution: + def selfDivisiblePermutationCount(self, n: int) -> int: + f = [0] * (1 << n) + f[0] = 1 + for mask in range(1 << n): + i = mask.bit_count() + for j in range(1, n + 1): + if (mask >> (j - 1) & 1) == 1 and (i % j == 0 or j % i == 0): + f[mask] += f[mask ^ (1 << (j - 1))] + return f[-1] +``` + +```java +class Solution { + public int selfDivisiblePermutationCount(int n) { + int[] f = new int[1 << n]; + f[0] = 1; + for (int mask = 0; mask < 1 << n; ++mask) { + int i = Integer.bitCount(mask); + for (int j = 1; j <= n; ++j) { + if (((mask >> (j - 1)) & 1) == 1 && (i % j == 0 || j % i == 0)) { + f[mask] += f[mask ^ (1 << (j - 1))]; + } + } + } + return f[(1 << n) - 1]; + } +} +``` + +```cpp +class Solution { +public: + int selfDivisiblePermutationCount(int n) { + int f[1 << n]; + memset(f, 0, sizeof(f)); + f[0] = 1; + for (int mask = 0; mask < 1 << n; ++mask) { + int i = __builtin_popcount(mask); + for (int j = 1; j <= n; ++j) { + if (((mask >> (j - 1)) & 1) == 1 && (i % j == 0 || j % i == 0)) { + f[mask] += f[mask ^ (1 << (j - 1))]; + } + } + } + return f[(1 << n) - 1]; + } +}; +``` + +```go +func selfDivisiblePermutationCount(n int) int { + f := make([]int, 1<>(j-1)&1 == 1 && (i%j == 0 || j%i == 0) { + f[mask] += f[mask^(1<<(j-1))] + } + } + } + return f[(1< + + diff --git a/solution/2900-2999/2993.Friday Purchases I/README.md b/solution/2900-2999/2993.Friday Purchases I/README.md index 288459a6eec8e..12d8a1fbc5a50 100644 --- a/solution/2900-2999/2993.Friday Purchases I/README.md +++ b/solution/2900-2999/2993.Friday Purchases I/README.md @@ -61,9 +61,7 @@ Output table is ordered by week_of_month in ascending order. ## 解法 - - -**方法一:日期函数** +### 方法一:日期函数 我们用到的日期函数有: @@ -75,10 +73,6 @@ Output table is ordered by week_of_month in ascending order. -### **SQL** - - - ```sql # Write your MySQL query statement below SELECT @@ -92,3 +86,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2900-2999/2993.Friday Purchases I/README_EN.md b/solution/2900-2999/2993.Friday Purchases I/README_EN.md index 5d0a44ce3098c..6b9229e569618 100644 --- a/solution/2900-2999/2993.Friday Purchases I/README_EN.md +++ b/solution/2900-2999/2993.Friday Purchases I/README_EN.md @@ -59,7 +59,7 @@ Output table is ordered by week_of_month in ascending order. ## Solutions -**Solution 1: Date Functions** +### Solution 1: Date Functions The date functions we use include: @@ -71,8 +71,6 @@ First, we use the `DATE_FORMAT` function to format the date in the form of `YYYY -### **SQL** - ```sql # Write your MySQL query statement below SELECT @@ -86,3 +84,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2900-2999/2994.Friday Purchases II/README.md b/solution/2900-2999/2994.Friday Purchases II/README.md index aa1ea82655872..b2418f0de26bc 100644 --- a/solution/2900-2999/2994.Friday Purchases II/README.md +++ b/solution/2900-2999/2994.Friday Purchases II/README.md @@ -63,18 +63,12 @@ Output table is ordered by week_of_month in ascending order. ## 解法 - - -**方法一:递归 + 左连接 + 日期函数** +### 方法一:递归 + 左连接 + 日期函数 我们可以使用递归生成一个包含 2023 年 11 月所有日期的表 `T`,然后使用左连接将 `T` 与 `Purchases` 表按照日期进行连接,最后按照题目要求进行分组求和即可。 -### **SQL** - - - ```sql WITH RECURSIVE T AS ( @@ -97,3 +91,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2900-2999/2994.Friday Purchases II/README_EN.md b/solution/2900-2999/2994.Friday Purchases II/README_EN.md index 7bd3b7b98ad2b..14edaafaa4f8b 100644 --- a/solution/2900-2999/2994.Friday Purchases II/README_EN.md +++ b/solution/2900-2999/2994.Friday Purchases II/README_EN.md @@ -61,14 +61,12 @@ Output table is ordered by week_of_month in ascending order. ## Solutions -**Solution 1: Recursion + Left Join + Date Functions** +### Solution 1: Recursion + Left Join + Date Functions We can generate a table `T` that contains all dates in November 2023 using recursion, then use a left join to connect `T` and the `Purchases` table by date. Finally, group and sum according to the requirements of the problem. -### **SQL** - ```sql WITH RECURSIVE T AS ( @@ -91,3 +89,5 @@ ORDER BY 1; ``` + + diff --git a/solution/2900-2999/2995.Viewers Turned Streamers/README.md b/solution/2900-2999/2995.Viewers Turned Streamers/README.md index 9ce1a15a376f5..0ac0d892329e7 100644 --- a/solution/2900-2999/2995.Viewers Turned Streamers/README.md +++ b/solution/2900-2999/2995.Viewers Turned Streamers/README.md @@ -63,18 +63,12 @@ Sessions table: ## 解法 - - -**方法一:窗口函数 + 等值连接** +### 方法一:窗口函数 + 等值连接 我们可以用窗口函数 `RANK()` 按照 `user_id` 维度,对每个会话进行排名,记录在表 `T` 中,然后再将 `T` 与 `Sessions` 表按照 `user_id` 进行等值连接,并且筛选出 `T` 中排名为 1 的记录,并且 `session_type` 为 `Viewer`,`Sessions` 表中 `session_type` 为 `Streamer` 的记录,最后按照 `user_id` 进行分组求和即可。 -### **SQL** - - - ```sql # Write your MySQL query statement below WITH @@ -98,3 +92,5 @@ ORDER BY 2 DESC, 1 DESC; ``` + + diff --git a/solution/2900-2999/2995.Viewers Turned Streamers/README_EN.md b/solution/2900-2999/2995.Viewers Turned Streamers/README_EN.md index 35cf31192b58d..286771db126f1 100644 --- a/solution/2900-2999/2995.Viewers Turned Streamers/README_EN.md +++ b/solution/2900-2999/2995.Viewers Turned Streamers/README_EN.md @@ -60,14 +60,12 @@ Output table is ordered by sessions count and user_id in descending order. ## Solutions -**Solution 1: Window Function + Equi-Join** +### Solution 1: Window Function + Equi-Join We can use the window function `RANK()` to rank each session by `user_id` dimension, and record it in table `T`. Then, we equi-join `T` and the `Sessions` table by `user_id`, and filter out the records in `T` where the rank is 1, and `session_type` is `Viewer`, and `session_type` in the `Sessions` table is `Streamer`. Finally, we group by `user_id` and sum up. -### **SQL** - ```sql # Write your MySQL query statement below WITH @@ -91,3 +89,5 @@ ORDER BY 2 DESC, 1 DESC; ``` + + diff --git a/solution/2900-2999/2996.Smallest Missing Integer Greater Than Sequential Prefix Sum/README.md b/solution/2900-2999/2996.Smallest Missing Integer Greater Than Sequential Prefix Sum/README.md index b0847dbb5a630..98da2d145e9c0 100644 --- a/solution/2900-2999/2996.Smallest Missing Integer Greater Than Sequential Prefix Sum/README.md +++ b/solution/2900-2999/2996.Smallest Missing Integer Greater Than Sequential Prefix Sum/README.md @@ -41,9 +41,7 @@ ## 解法 - - -**方法一:模拟 + 哈希表** +### 方法一:模拟 + 哈希表 我们先求出数组 $nums$ 的最长顺序前缀和 $s$,然后从 $s$ 开始枚举整数 $x$,如果 $x$ 不在数组 $nums$ 中,那么 $x$ 就是答案。这里我们可以用哈希表来快速判断一个整数是否在数组 $nums$ 中。 @@ -51,10 +49,6 @@ -### **Python3** - - - ```python class Solution: def missingInteger(self, nums: List[int]) -> int: @@ -68,10 +62,6 @@ class Solution: return x ``` -### **Java** - - - ```java class Solution { public int missingInteger(int[] nums) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -115,8 +103,6 @@ public: }; ``` -### **Go** - ```go func missingInteger(nums []int) int { s := nums[0] @@ -135,8 +121,6 @@ func missingInteger(nums []int) int { } ``` -### **TypeScript** - ```ts function missingInteger(nums: number[]): number { let s = nums[0]; @@ -152,10 +136,6 @@ function missingInteger(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2996.Smallest Missing Integer Greater Than Sequential Prefix Sum/README_EN.md b/solution/2900-2999/2996.Smallest Missing Integer Greater Than Sequential Prefix Sum/README_EN.md index 14f3dbce009fd..b733ab5ccb6a3 100644 --- a/solution/2900-2999/2996.Smallest Missing Integer Greater Than Sequential Prefix Sum/README_EN.md +++ b/solution/2900-2999/2996.Smallest Missing Integer Greater Than Sequential Prefix Sum/README_EN.md @@ -37,7 +37,7 @@ ## Solutions -**Solution 1: Simulation + Hash Table** +### Solution 1: Simulation + Hash Table First, we calculate the longest prefix sum $s$ of the array $nums$. Then, starting from $s$, we enumerate the integer $x$. If $x$ is not in the array $nums$, then $x$ is the answer. Here, we can use a hash table to quickly determine whether an integer is in the array $nums$. @@ -45,8 +45,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is -### **Python3** - ```python class Solution: def missingInteger(self, nums: List[int]) -> int: @@ -60,8 +58,6 @@ class Solution: return x ``` -### **Java** - ```java class Solution { public int missingInteger(int[] nums) { @@ -82,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -105,8 +99,6 @@ public: }; ``` -### **Go** - ```go func missingInteger(nums []int) int { s := nums[0] @@ -125,8 +117,6 @@ func missingInteger(nums []int) int { } ``` -### **TypeScript** - ```ts function missingInteger(nums: number[]): number { let s = nums[0]; @@ -142,10 +132,6 @@ function missingInteger(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2997.Minimum Number of Operations to Make Array XOR Equal to K/README.md b/solution/2900-2999/2997.Minimum Number of Operations to Make Array XOR Equal to K/README.md index 50922874c84ed..32f41f1fb0cf0 100644 --- a/solution/2900-2999/2997.Minimum Number of Operations to Make Array XOR Equal to K/README.md +++ b/solution/2900-2999/2997.Minimum Number of Operations to Make Array XOR Equal to K/README.md @@ -52,9 +52,7 @@ ## 解法 - - -**方法一:位运算** +### 方法一:位运算 我们可以将数组 $nums$ 中的所有元素进行异或运算,判断得到的结果与 $k$ 的二进制表示中有多少位不同,这个数就是最少操作次数。 @@ -62,20 +60,12 @@ -### **Python3** - - - ```python class Solution: def minOperations(self, nums: List[int], k: int) -> int: return reduce(xor, nums, k).bit_count() ``` -### **Java** - - - ```java class Solution { public int minOperations(int[] nums, int k) { @@ -87,8 +77,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -101,8 +89,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int, k int) (ans int) { for _, x := range nums { @@ -112,8 +98,6 @@ func minOperations(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function minOperations(nums: number[], k: number): number { for (const x of nums) { @@ -132,10 +116,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2997.Minimum Number of Operations to Make Array XOR Equal to K/README_EN.md b/solution/2900-2999/2997.Minimum Number of Operations to Make Array XOR Equal to K/README_EN.md index 95dc5f870480c..efe4a7854844d 100644 --- a/solution/2900-2999/2997.Minimum Number of Operations to Make Array XOR Equal to K/README_EN.md +++ b/solution/2900-2999/2997.Minimum Number of Operations to Make Array XOR Equal to K/README_EN.md @@ -48,7 +48,7 @@ It can be shown that we cannot make the XOR equal to k in less than 2 operations ## Solutions -**Solution 1: Bit Manipulation** +### Solution 1: Bit Manipulation We can perform a bitwise XOR operation on all elements in the array $nums$. The number of bits that differ from the binary representation of $k$ in the result is the minimum number of operations. @@ -56,16 +56,12 @@ The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The -### **Python3** - ```python class Solution: def minOperations(self, nums: List[int], k: int) -> int: return reduce(xor, nums, k).bit_count() ``` -### **Java** - ```java class Solution { public int minOperations(int[] nums, int k) { @@ -77,8 +73,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -91,8 +85,6 @@ public: }; ``` -### **Go** - ```go func minOperations(nums []int, k int) (ans int) { for _, x := range nums { @@ -102,8 +94,6 @@ func minOperations(nums []int, k int) (ans int) { } ``` -### **TypeScript** - ```ts function minOperations(nums: number[], k: number): number { for (const x of nums) { @@ -122,10 +112,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2998.Minimum Number of Operations to Make X and Y Equal/README.md b/solution/2900-2999/2998.Minimum Number of Operations to Make X and Y Equal/README.md index b5e6052d49b48..382d7980b4a7e 100644 --- a/solution/2900-2999/2998.Minimum Number of Operations to Make X and Y Equal/README.md +++ b/solution/2900-2999/2998.Minimum Number of Operations to Make X and Y Equal/README.md @@ -70,14 +70,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minimumOperationsToMakeEqual(self, x: int, y: int) -> int: @@ -95,10 +91,6 @@ class Solution: return dfs(x) ``` -### **Java** - - - ```java class Solution { private Map f = new HashMap<>(); @@ -128,8 +120,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -153,8 +143,6 @@ public: }; ``` -### **Go** - ```go func minimumOperationsToMakeEqual(x int, y int) int { f := map[int]int{} @@ -177,8 +165,6 @@ func minimumOperationsToMakeEqual(x int, y int) int { } ``` -### **TypeScript** - ```ts function minimumOperationsToMakeEqual(x: number, y: number): number { const f: Map = new Map(); @@ -201,10 +187,6 @@ function minimumOperationsToMakeEqual(x: number, y: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2998.Minimum Number of Operations to Make X and Y Equal/README_EN.md b/solution/2900-2999/2998.Minimum Number of Operations to Make X and Y Equal/README_EN.md index 982f265653788..edcc624139ef0 100644 --- a/solution/2900-2999/2998.Minimum Number of Operations to Make X and Y Equal/README_EN.md +++ b/solution/2900-2999/2998.Minimum Number of Operations to Make X and Y Equal/README_EN.md @@ -66,9 +66,9 @@ It can be shown that 5 is the minimum number of operations required to make 25 e ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -87,8 +87,6 @@ class Solution: return dfs(x) ``` -### **Java** - ```java class Solution { private Map f = new HashMap<>(); @@ -118,8 +116,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -143,8 +139,6 @@ public: }; ``` -### **Go** - ```go func minimumOperationsToMakeEqual(x int, y int) int { f := map[int]int{} @@ -167,8 +161,6 @@ func minimumOperationsToMakeEqual(x int, y int) int { } ``` -### **TypeScript** - ```ts function minimumOperationsToMakeEqual(x: number, y: number): number { const f: Map = new Map(); @@ -191,10 +183,6 @@ function minimumOperationsToMakeEqual(x: number, y: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2999.Count the Number of Powerful Integers/README.md b/solution/2900-2999/2999.Count the Number of Powerful Integers/README.md index cd55b8f1d0e54..c22756223fa47 100644 --- a/solution/2900-2999/2999.Count the Number of Powerful Integers/README.md +++ b/solution/2900-2999/2999.Count the Number of Powerful Integers/README.md @@ -56,14 +56,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def numberOfPowerfulInt(self, start: int, finish: int, limit: int, s: str) -> int: @@ -88,10 +84,6 @@ class Solution: return b - a ``` -### **Java** - - - ```java class Solution { private String s; @@ -135,8 +127,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -175,8 +165,6 @@ public: }; ``` -### **Go** - ```go func numberOfPowerfulInt(start, finish int64, limit int, s string) int64 { t := strconv.FormatInt(start-1, 10) @@ -228,8 +216,6 @@ func numberOfPowerfulInt(start, finish int64, limit int, s string) int64 { } ``` -### **TypeScript** - ```ts function numberOfPowerfulInt(start: number, finish: number, limit: number, s: string): number { let t: string = (start - 1).toString(); @@ -270,10 +256,6 @@ function numberOfPowerfulInt(start: number, finish: number, limit: number, s: st } ``` -### **...** - -``` - -``` - + + diff --git a/solution/2900-2999/2999.Count the Number of Powerful Integers/README_EN.md b/solution/2900-2999/2999.Count the Number of Powerful Integers/README_EN.md index 9353b47368787..98bd365ed49b7 100644 --- a/solution/2900-2999/2999.Count the Number of Powerful Integers/README_EN.md +++ b/solution/2900-2999/2999.Count the Number of Powerful Integers/README_EN.md @@ -52,9 +52,9 @@ It can be shown that there are only 2 powerful integers in this range. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return b - a ``` -### **Java** - ```java class Solution { private String s; @@ -125,8 +123,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -165,8 +161,6 @@ public: }; ``` -### **Go** - ```go func numberOfPowerfulInt(start, finish int64, limit int, s string) int64 { t := strconv.FormatInt(start-1, 10) @@ -218,8 +212,6 @@ func numberOfPowerfulInt(start, finish int64, limit int, s string) int64 { } ``` -### **TypeScript** - ```ts function numberOfPowerfulInt(start: number, finish: number, limit: number, s: string): number { let t: string = (start - 1).toString(); @@ -260,10 +252,6 @@ function numberOfPowerfulInt(start: number, finish: number, limit: number, s: st } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3000.Maximum Area of Longest Diagonal Rectangle/README.md b/solution/3000-3099/3000.Maximum Area of Longest Diagonal Rectangle/README.md index 35cb3a5094cd7..d3efc11cbac9f 100644 --- a/solution/3000-3099/3000.Maximum Area of Longest Diagonal Rectangle/README.md +++ b/solution/3000-3099/3000.Maximum Area of Longest Diagonal Rectangle/README.md @@ -45,14 +45,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def areaOfMaxDiagonal(self, dimensions: List[List[int]]) -> int: @@ -67,10 +63,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { public int areaOfMaxDiagonal(int[][] dimensions) { @@ -90,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -112,8 +102,6 @@ public: }; ``` -### **Go** - ```go func areaOfMaxDiagonal(dimensions [][]int) (ans int) { mx := 0 @@ -131,8 +119,6 @@ func areaOfMaxDiagonal(dimensions [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function areaOfMaxDiagonal(dimensions: number[][]): number { let [ans, mx] = [0, 0]; @@ -149,10 +135,6 @@ function areaOfMaxDiagonal(dimensions: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3000.Maximum Area of Longest Diagonal Rectangle/README_EN.md b/solution/3000-3099/3000.Maximum Area of Longest Diagonal Rectangle/README_EN.md index 3ea2785096127..e95688aeda11e 100644 --- a/solution/3000-3099/3000.Maximum Area of Longest Diagonal Rectangle/README_EN.md +++ b/solution/3000-3099/3000.Maximum Area of Longest Diagonal Rectangle/README_EN.md @@ -41,9 +41,9 @@ So, the rectangle at index 1 has a greater diagonal length therefore we return a ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -59,8 +59,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { public int areaOfMaxDiagonal(int[][] dimensions) { @@ -80,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -102,8 +98,6 @@ public: }; ``` -### **Go** - ```go func areaOfMaxDiagonal(dimensions [][]int) (ans int) { mx := 0 @@ -121,8 +115,6 @@ func areaOfMaxDiagonal(dimensions [][]int) (ans int) { } ``` -### **TypeScript** - ```ts function areaOfMaxDiagonal(dimensions: number[][]): number { let [ans, mx] = [0, 0]; @@ -139,10 +131,6 @@ function areaOfMaxDiagonal(dimensions: number[][]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3001.Minimum Moves to Capture The Queen/README.md b/solution/3000-3099/3001.Minimum Moves to Capture The Queen/README.md index b5982186b1475..5db16efcfc553 100644 --- a/solution/3000-3099/3001.Minimum Moves to Capture The Queen/README.md +++ b/solution/3000-3099/3001.Minimum Moves to Capture The Queen/README.md @@ -59,14 +59,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def minMovesToCaptureTheQueen( @@ -88,10 +84,6 @@ class Solution: return 1 if check(dirs1, a, b, c, d) or check(dirs2, c, d, a, b) else 2 ``` -### **Java** - - - ```java class Solution { private final int[] dirs1 = {-1, 0, 1, 0, -1}; @@ -122,8 +114,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -149,8 +139,6 @@ public: }; ``` -### **Go** - ```go func minMovesToCaptureTheQueen(a int, b int, c int, d int, e int, f int) int { dirs := [2][5]int{{-1, 0, 1, 0, -1}, {-1, 1, 1, -1, -1}} @@ -176,8 +164,6 @@ func minMovesToCaptureTheQueen(a int, b int, c int, d int, e int, f int) int { } ``` -### **TypeScript** - ```ts function minMovesToCaptureTheQueen( a: number, @@ -213,10 +199,6 @@ function minMovesToCaptureTheQueen( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3001.Minimum Moves to Capture The Queen/README_EN.md b/solution/3000-3099/3001.Minimum Moves to Capture The Queen/README_EN.md index e8594e84ef7a9..b33faeb7d4539 100644 --- a/solution/3000-3099/3001.Minimum Moves to Capture The Queen/README_EN.md +++ b/solution/3000-3099/3001.Minimum Moves to Capture The Queen/README_EN.md @@ -55,9 +55,9 @@ It is impossible to capture the black queen in less than two moves since it is n ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -80,8 +80,6 @@ class Solution: return 1 if check(dirs1, a, b, c, d) or check(dirs2, c, d, a, b) else 2 ``` -### **Java** - ```java class Solution { private final int[] dirs1 = {-1, 0, 1, 0, -1}; @@ -112,8 +110,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -139,8 +135,6 @@ public: }; ``` -### **Go** - ```go func minMovesToCaptureTheQueen(a int, b int, c int, d int, e int, f int) int { dirs := [2][5]int{{-1, 0, 1, 0, -1}, {-1, 1, 1, -1, -1}} @@ -166,8 +160,6 @@ func minMovesToCaptureTheQueen(a int, b int, c int, d int, e int, f int) int { } ``` -### **TypeScript** - ```ts function minMovesToCaptureTheQueen( a: number, @@ -203,10 +195,6 @@ function minMovesToCaptureTheQueen( } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3002.Maximum Size of a Set After Removals/README.md b/solution/3000-3099/3002.Maximum Size of a Set After Removals/README.md index eecd022be2a5a..fb1649b6440be 100644 --- a/solution/3000-3099/3002.Maximum Size of a Set After Removals/README.md +++ b/solution/3000-3099/3002.Maximum Size of a Set After Removals/README.md @@ -53,14 +53,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maximumSetSize(self, nums1: List[int], nums2: List[int]) -> int: @@ -72,10 +68,6 @@ class Solution: return min(a + b + len(s1 & s2), n) ``` -### **Java** - - - ```java class Solution { public int maximumSetSize(int[] nums1, int[] nums2) { @@ -108,8 +100,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -137,8 +127,6 @@ public: }; ``` -### **Go** - ```go func maximumSetSize(nums1 []int, nums2 []int) int { s1 := map[int]bool{} @@ -169,8 +157,6 @@ func maximumSetSize(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - ```ts function maximumSetSize(nums1: number[], nums2: number[]): number { const s1: Set = new Set(nums1); @@ -195,10 +181,6 @@ function maximumSetSize(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3002.Maximum Size of a Set After Removals/README_EN.md b/solution/3000-3099/3002.Maximum Size of a Set After Removals/README_EN.md index 80e4fa15636e3..4b87d9e3c910c 100644 --- a/solution/3000-3099/3002.Maximum Size of a Set After Removals/README_EN.md +++ b/solution/3000-3099/3002.Maximum Size of a Set After Removals/README_EN.md @@ -50,9 +50,9 @@ It can be shown that 6 is the maximum possible size of the set s after the remov ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -65,8 +65,6 @@ class Solution: return min(a + b + len(s1 & s2), n) ``` -### **Java** - ```java class Solution { public int maximumSetSize(int[] nums1, int[] nums2) { @@ -99,8 +97,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -128,8 +124,6 @@ public: }; ``` -### **Go** - ```go func maximumSetSize(nums1 []int, nums2 []int) int { s1 := map[int]bool{} @@ -160,8 +154,6 @@ func maximumSetSize(nums1 []int, nums2 []int) int { } ``` -### **TypeScript** - ```ts function maximumSetSize(nums1: number[], nums2: number[]): number { const s1: Set = new Set(nums1); @@ -186,10 +178,6 @@ function maximumSetSize(nums1: number[], nums2: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/README.md b/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/README.md index faa28a7968375..db1b020c16971 100644 --- a/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/README.md +++ b/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/README.md @@ -81,14 +81,10 @@ s 变为 "xayz"。 ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def maxPartitionsAfterOperations(self, s: str, k: int) -> int: @@ -115,10 +111,6 @@ class Solution: return dfs(0, 0, 1) ``` -### **Java** - - - ```java class Solution { private Map, Integer> f = new HashMap<>(); @@ -158,8 +150,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -194,8 +184,6 @@ public: }; ``` -### **Go** - ```go func maxPartitionsAfterOperations(s string, k int) int { n := len(s) @@ -235,8 +223,6 @@ func maxPartitionsAfterOperations(s string, k int) int { } ``` -### **TypeScript** - ```ts function maxPartitionsAfterOperations(s: string, k: number): number { const n = s.length; @@ -283,10 +269,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/README_EN.md b/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/README_EN.md index 85c85033c94fb..a1ce1a40b993b 100644 --- a/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/README_EN.md +++ b/solution/3000-3099/3003.Maximize the Number of Partitions After Operations/README_EN.md @@ -78,9 +78,9 @@ It can be shown that it is not possible to obtain more than 4 partitions. ## Solutions - +### Solution 1 -### **Python3** + ```python class Solution: @@ -108,8 +108,6 @@ class Solution: return dfs(0, 0, 1) ``` -### **Java** - ```java class Solution { private Map, Integer> f = new HashMap<>(); @@ -149,8 +147,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -185,8 +181,6 @@ public: }; ``` -### **Go** - ```go func maxPartitionsAfterOperations(s string, k int) int { n := len(s) @@ -226,8 +220,6 @@ func maxPartitionsAfterOperations(s string, k int) int { } ``` -### **TypeScript** - ```ts function maxPartitionsAfterOperations(s: string, k: number): number { const n = s.length; @@ -274,10 +266,6 @@ function bitCount(i: number): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3004.Maximum Subtree of the Same Color/README.md b/solution/3000-3099/3004.Maximum Subtree of the Same Color/README.md index 6f122900f1a73..9aa0773530f4d 100644 --- a/solution/3000-3099/3004.Maximum Subtree of the Same Color/README.md +++ b/solution/3000-3099/3004.Maximum Subtree of the Same Color/README.md @@ -58,9 +58,7 @@ ## 解法 - - -**方法一:DFS** +### 方法一:DFS 我们先根据题目给定的边的信息,构建一个邻接表 $g$,其中 $g[a]$ 表示节点 $a$ 的所有相邻节点。然后我们创建一个长度为 $n$ 的数组 $size$,其中 $size[a]$ 表示以节点 $a$ 为根的子树的节点数。 @@ -77,10 +75,6 @@ -### **Python3** - - - ```python class Solution: def maximumSubtreeSize(self, edges: List[List[int]], colors: List[int]) -> int: @@ -107,10 +101,6 @@ class Solution: return ans ``` -### **Java** - - - ```java class Solution { private List[] g; @@ -151,8 +141,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -186,8 +174,6 @@ public: }; ``` -### **Go** - ```go func maximumSubtreeSize(edges [][]int, colors []int) (ans int) { n := len(edges) + 1 @@ -219,8 +205,6 @@ func maximumSubtreeSize(edges [][]int, colors []int) (ans int) { } ``` -### **TypeScript** - ```ts function maximumSubtreeSize(edges: number[][], colors: number[]): number { const n = edges.length + 1; @@ -250,10 +234,6 @@ function maximumSubtreeSize(edges: number[][], colors: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3004.Maximum Subtree of the Same Color/README_EN.md b/solution/3000-3099/3004.Maximum Subtree of the Same Color/README_EN.md index f40af99b1621d..37d088bf0c611 100644 --- a/solution/3000-3099/3004.Maximum Subtree of the Same Color/README_EN.md +++ b/solution/3000-3099/3004.Maximum Subtree of the Same Color/README_EN.md @@ -56,7 +56,7 @@ ## Solutions -**Solution 1: DFS** +### Solution 1: DFS First, according to the edge information given in the problem, we construct an adjacency list $g$, where $g[a]$ represents all adjacent nodes of node $a$. Then we create an array $size$ of length $n$, where $size[a]$ represents the number of nodes in the subtree with node $a$ as the root. @@ -73,8 +73,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def maximumSubtreeSize(self, edges: List[List[int]], colors: List[int]) -> int: @@ -101,8 +99,6 @@ class Solution: return ans ``` -### **Java** - ```java class Solution { private List[] g; @@ -143,8 +139,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -178,8 +172,6 @@ public: }; ``` -### **Go** - ```go func maximumSubtreeSize(edges [][]int, colors []int) (ans int) { n := len(edges) + 1 @@ -211,8 +203,6 @@ func maximumSubtreeSize(edges [][]int, colors []int) (ans int) { } ``` -### **TypeScript** - ```ts function maximumSubtreeSize(edges: number[][], colors: number[]): number { const n = edges.length + 1; @@ -242,10 +232,6 @@ function maximumSubtreeSize(edges: number[][], colors: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3005.Count Elements With Maximum Frequency/README.md b/solution/3000-3099/3005.Count Elements With Maximum Frequency/README.md index 05ba5f3c592f5..0da7f00439055 100644 --- a/solution/3000-3099/3005.Count Elements With Maximum Frequency/README.md +++ b/solution/3000-3099/3005.Count Elements With Maximum Frequency/README.md @@ -43,9 +43,7 @@ ## 解法 - - -**方法一:计数** +### 方法一:计数 我们可以用一个哈希表或数组 $cnt$ 记录每个元素出现的次数。 @@ -55,10 +53,6 @@ -### **Python3** - - - ```python class Solution: def maxFrequencyElements(self, nums: List[int]) -> int: @@ -67,10 +61,6 @@ class Solution: return sum(x for x in cnt.values() if x == mx) ``` -### **Java** - - - ```java class Solution { public int maxFrequencyElements(int[] nums) { @@ -92,8 +82,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -116,8 +104,6 @@ public: }; ``` -### **Go** - ```go func maxFrequencyElements(nums []int) (ans int) { cnt := [101]int{} @@ -136,8 +122,6 @@ func maxFrequencyElements(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function maxFrequencyElements(nums: number[]): number { const cnt: number[] = Array(101).fill(0); @@ -157,10 +141,6 @@ function maxFrequencyElements(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3005.Count Elements With Maximum Frequency/README_EN.md b/solution/3000-3099/3005.Count Elements With Maximum Frequency/README_EN.md index adab7bb098d7e..74793c824f041 100644 --- a/solution/3000-3099/3005.Count Elements With Maximum Frequency/README_EN.md +++ b/solution/3000-3099/3005.Count Elements With Maximum Frequency/README_EN.md @@ -39,7 +39,7 @@ So the number of elements in the array with maximum frequency is 5. ## Solutions -**Solution 1: Counting** +### Solution 1: Counting We can use a hash table or array $cnt$ to record the occurrence of each element. @@ -49,8 +49,6 @@ The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is -### **Python3** - ```python class Solution: def maxFrequencyElements(self, nums: List[int]) -> int: @@ -59,8 +57,6 @@ class Solution: return sum(x for x in cnt.values() if x == mx) ``` -### **Java** - ```java class Solution { public int maxFrequencyElements(int[] nums) { @@ -82,8 +78,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -106,8 +100,6 @@ public: }; ``` -### **Go** - ```go func maxFrequencyElements(nums []int) (ans int) { cnt := [101]int{} @@ -126,8 +118,6 @@ func maxFrequencyElements(nums []int) (ans int) { } ``` -### **TypeScript** - ```ts function maxFrequencyElements(nums: number[]): number { const cnt: number[] = Array(101).fill(0); @@ -147,10 +137,6 @@ function maxFrequencyElements(nums: number[]): number { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3006.Find Beautiful Indices in the Given Array I/README.md b/solution/3000-3099/3006.Find Beautiful Indices in the Given Array I/README.md index dc290f9eb5e6a..3517ee557bada 100644 --- a/solution/3000-3099/3006.Find Beautiful Indices in the Given Array I/README.md +++ b/solution/3000-3099/3006.Find Beautiful Indices in the Given Array I/README.md @@ -59,42 +59,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/3000-3099/3006.Find Beautiful Indices in the Given Array I/README_EN.md b/solution/3000-3099/3006.Find Beautiful Indices in the Given Array I/README_EN.md index 5ba53eeaafe53..b40e9eaf83402 100644 --- a/solution/3000-3099/3006.Find Beautiful Indices in the Given Array I/README_EN.md +++ b/solution/3000-3099/3006.Find Beautiful Indices in the Given Array I/README_EN.md @@ -55,36 +55,4 @@ Thus we return [0] as the result. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/README.md b/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/README.md index 0dc623d1c424b..02e12acc20cc8 100644 --- a/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/README.md +++ b/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/README.md @@ -56,14 +56,10 @@ ## 解法 - +### 方法一 -### **Python3** - - - ```python class Solution: def findMaximumNumber(self, k: int, x: int) -> int: @@ -90,10 +86,6 @@ class Solution: return l ``` -### **Java** - - - ```java class Solution { private int x; @@ -137,8 +129,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -180,8 +170,6 @@ public: }; ``` -### **Go** - ```go func findMaximumNumber(k int64, x int) int64 { var l, r int64 = 1, 1e17 @@ -231,10 +219,6 @@ func findMaximumNumber(k int64, x int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/README_EN.md b/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/README_EN.md index a23f2a37d2feb..53afba2d2d516 100644 --- a/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/README_EN.md +++ b/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/README_EN.md @@ -52,9 +52,9 @@ Because the sum of the prices of the first 10 numbers is 8, the answer is 9. +### Solution 1 -### **Python3** + ```python class Solution: @@ -82,8 +82,6 @@ class Solution: return l ``` -### **Java** - ```java class Solution { private int x; @@ -127,8 +125,6 @@ class Solution { } ``` -### **C++** - ```cpp class Solution { public: @@ -170,8 +166,6 @@ public: }; ``` -### **Go** - ```go func findMaximumNumber(k int64, x int) int64 { var l, r int64 = 1, 1e17 @@ -221,10 +215,6 @@ func findMaximumNumber(k int64, x int) int64 { } ``` -### **...** - -``` - -``` - + + diff --git a/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.cpp b/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.cpp index fda984645a396..8f6dd46c4c832 100644 --- a/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.cpp +++ b/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.cpp @@ -1,38 +1,38 @@ -class Solution { -public: - long long findMaximumNumber(long long k, int x) { - using ll = long long; - ll l = 1, r = 1e17; - ll num = 0; - ll f[65][65]; - function dfs = [&](int pos, int cnt, bool limit) -> ll { - if (pos == 0) { - return cnt; - } - if (!limit && f[pos][cnt] != -1) { - return f[pos][cnt]; - } - int up = limit ? num >> (pos - 1) & 1 : 1; - ll ans = 0; - for (int i = 0; i <= up; ++i) { - ans += dfs(pos - 1, cnt + (i == 1 && pos % x == 0), limit && i == up); - } - if (!limit) { - f[pos][cnt] = ans; - } - return ans; - }; - while (l < r) { - ll mid = (l + r + 1) >> 1; - num = mid; - memset(f, -1, sizeof(f)); - int pos = 64 - __builtin_clzll(mid); - if (dfs(pos, 0, true) <= k) { - l = mid; - } else { - r = mid - 1; - } - } - return l; - } +class Solution { +public: + long long findMaximumNumber(long long k, int x) { + using ll = long long; + ll l = 1, r = 1e17; + ll num = 0; + ll f[65][65]; + function dfs = [&](int pos, int cnt, bool limit) -> ll { + if (pos == 0) { + return cnt; + } + if (!limit && f[pos][cnt] != -1) { + return f[pos][cnt]; + } + int up = limit ? num >> (pos - 1) & 1 : 1; + ll ans = 0; + for (int i = 0; i <= up; ++i) { + ans += dfs(pos - 1, cnt + (i == 1 && pos % x == 0), limit && i == up); + } + if (!limit) { + f[pos][cnt] = ans; + } + return ans; + }; + while (l < r) { + ll mid = (l + r + 1) >> 1; + num = mid; + memset(f, -1, sizeof(f)); + int pos = 64 - __builtin_clzll(mid); + if (dfs(pos, 0, true) <= k) { + l = mid; + } else { + r = mid - 1; + } + } + return l; + } }; \ No newline at end of file diff --git a/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.go b/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.go index 34d5c33d6bbb7..036fad1f75d05 100644 --- a/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.go +++ b/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.go @@ -1,46 +1,46 @@ -func findMaximumNumber(k int64, x int) int64 { - var l, r int64 = 1, 1e17 - var num int64 - var f [65][65]int64 - var dfs func(pos, cnt int, limit bool) int64 - dfs = func(pos, cnt int, limit bool) int64 { - if pos == 0 { - return int64(cnt) - } - if !limit && f[pos][cnt] != -1 { - return f[pos][cnt] - } - var ans int64 - up := 1 - if limit { - up = int(num >> (pos - 1) & 1) - } - for i := 0; i <= up; i++ { - v := cnt - if i == 1 && pos%x == 0 { - v++ - } - ans += dfs(pos-1, v, limit && i == up) - } - if !limit { - f[pos][cnt] = ans - } - return ans - } - for l < r { - mid := (l + r + 1) >> 1 - num = mid - m := bits.Len(uint(num)) - for i := range f { - for j := range f[i] { - f[i][j] = -1 - } - } - if dfs(m, 0, true) <= k { - l = mid - } else { - r = mid - 1 - } - } - return l +func findMaximumNumber(k int64, x int) int64 { + var l, r int64 = 1, 1e17 + var num int64 + var f [65][65]int64 + var dfs func(pos, cnt int, limit bool) int64 + dfs = func(pos, cnt int, limit bool) int64 { + if pos == 0 { + return int64(cnt) + } + if !limit && f[pos][cnt] != -1 { + return f[pos][cnt] + } + var ans int64 + up := 1 + if limit { + up = int(num >> (pos - 1) & 1) + } + for i := 0; i <= up; i++ { + v := cnt + if i == 1 && pos%x == 0 { + v++ + } + ans += dfs(pos-1, v, limit && i == up) + } + if !limit { + f[pos][cnt] = ans + } + return ans + } + for l < r { + mid := (l + r + 1) >> 1 + num = mid + m := bits.Len(uint(num)) + for i := range f { + for j := range f[i] { + f[i][j] = -1 + } + } + if dfs(m, 0, true) <= k { + l = mid + } else { + r = mid - 1 + } + } + return l } \ No newline at end of file diff --git a/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.java b/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.java index 94c7d262b73ea..9a18e9b64d292 100644 --- a/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.java +++ b/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.java @@ -1,40 +1,40 @@ -class Solution { - private int x; - private long num; - private Long[][] f; - - public long findMaximumNumber(long k, int x) { - this.x = x; - long l = 1, r = (long) 1e17; - while (l < r) { - long mid = (l + r + 1) >>> 1; - num = mid; - f = new Long[65][65]; - int pos = 64 - Long.numberOfLeadingZeros(mid); - if (dfs(pos, 0, true) <= k) { - l = mid; - } else { - r = mid - 1; - } - } - return l; - } - - private long dfs(int pos, int cnt, boolean limit) { - if (pos == 0) { - return cnt; - } - if (!limit && f[pos][cnt] != null) { - return f[pos][cnt]; - } - long ans = 0; - int up = limit ? (int) (num >> (pos - 1) & 1) : 1; - for (int i = 0; i <= up; ++i) { - ans += dfs(pos - 1, cnt + (i == 1 && pos % x == 0 ? 1 : 0), limit && i == up); - } - if (!limit) { - f[pos][cnt] = ans; - } - return ans; - } +class Solution { + private int x; + private long num; + private Long[][] f; + + public long findMaximumNumber(long k, int x) { + this.x = x; + long l = 1, r = (long) 1e17; + while (l < r) { + long mid = (l + r + 1) >>> 1; + num = mid; + f = new Long[65][65]; + int pos = 64 - Long.numberOfLeadingZeros(mid); + if (dfs(pos, 0, true) <= k) { + l = mid; + } else { + r = mid - 1; + } + } + return l; + } + + private long dfs(int pos, int cnt, boolean limit) { + if (pos == 0) { + return cnt; + } + if (!limit && f[pos][cnt] != null) { + return f[pos][cnt]; + } + long ans = 0; + int up = limit ? (int) (num >> (pos - 1) & 1) : 1; + for (int i = 0; i <= up; ++i) { + ans += dfs(pos - 1, cnt + (i == 1 && pos % x == 0 ? 1 : 0), limit && i == up); + } + if (!limit) { + f[pos][cnt] = ans; + } + return ans; + } } \ No newline at end of file diff --git a/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.py b/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.py index 9ab795b604c6b..a67180652fea0 100644 --- a/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.py +++ b/solution/3000-3099/3007.Maximum Number That Sum of the Prices Is Less Than or Equal to K/Solution.py @@ -1,23 +1,23 @@ -class Solution: - def findMaximumNumber(self, k: int, x: int) -> int: - @cache - def dfs(pos, limit, cnt): - if pos == 0: - return cnt - ans = 0 - up = (self.num >> (pos - 1) & 1) if limit else 1 - for i in range(up + 1): - ans += dfs(pos - 1, limit and i == up, cnt + (i == 1 and pos % x == 0)) - return ans - - l, r = 1, 10**18 - while l < r: - mid = (l + r + 1) >> 1 - self.num = mid - v = dfs(mid.bit_length(), True, 0) - dfs.cache_clear() - if v <= k: - l = mid - else: - r = mid - 1 - return l +class Solution: + def findMaximumNumber(self, k: int, x: int) -> int: + @cache + def dfs(pos, limit, cnt): + if pos == 0: + return cnt + ans = 0 + up = (self.num >> (pos - 1) & 1) if limit else 1 + for i in range(up + 1): + ans += dfs(pos - 1, limit and i == up, cnt + (i == 1 and pos % x == 0)) + return ans + + l, r = 1, 10**18 + while l < r: + mid = (l + r + 1) >> 1 + self.num = mid + v = dfs(mid.bit_length(), True, 0) + dfs.cache_clear() + if v <= k: + l = mid + else: + r = mid - 1 + return l diff --git a/solution/3000-3099/3008.Find Beautiful Indices in the Given Array II/README.md b/solution/3000-3099/3008.Find Beautiful Indices in the Given Array II/README.md index a2178d4735599..ed34249d3dfc7 100644 --- a/solution/3000-3099/3008.Find Beautiful Indices in the Given Array II/README.md +++ b/solution/3000-3099/3008.Find Beautiful Indices in the Given Array II/README.md @@ -57,42 +57,4 @@ ## 解法 - - - - -### **Python3** - - - -```python - -``` - -### **Java** - - - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/3000-3099/3008.Find Beautiful Indices in the Given Array II/README_EN.md b/solution/3000-3099/3008.Find Beautiful Indices in the Given Array II/README_EN.md index 89a41cd2293e4..5d9c6473ac8ea 100644 --- a/solution/3000-3099/3008.Find Beautiful Indices in the Given Array II/README_EN.md +++ b/solution/3000-3099/3008.Find Beautiful Indices in the Given Array II/README_EN.md @@ -55,36 +55,4 @@ Thus we return [0] as the result. ## Solutions - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **C++** - -```cpp - -``` - -### **Go** - -```go - -``` - -### **...** - -``` - -``` - - + diff --git a/solution/template.md b/solution/template.md index 4a83ccc7df5a8..8806575edfc79 100644 --- a/solution/template.md +++ b/solution/template.md @@ -203,20 +203,30 @@ Get your rating changes right after the completion of LeetCode contests, https:/ ## 解法 - +### 方法一 -### **Bash** +```python + +``` + +```java + +``` + +```cpp - +``` -```bash +```go ``` + + --- @@ -233,16 +243,30 @@ Get your rating changes right after the completion of LeetCode contests, https:/ ## Solutions +### Solution 1 + -### **Bash** +```python -```bash +``` + +```java + +``` + +```cpp + +``` + +```go ``` + + --- @@ -261,46 +285,30 @@ Get your rating changes right after the completion of LeetCode contests, https:/ ## 解法 - +### 方法一 -### **Python3** - - - ```python ``` -### **Java** - - - ```java ``` -### **C++** - ```cpp ``` -### **Go** - ```go ``` -### **...** - -``` - -``` - + + --- @@ -317,40 +325,30 @@ Get your rating changes right after the completion of LeetCode contests, https:/ ## Solutions - +### Solution 1 -### **Python3** + ```python ``` -### **Java** - ```java ``` -### **C++** - ```cpp ``` -### **Go** - ```go ``` -### **...** - -``` - -``` - + + --- @@ -369,20 +367,18 @@ Get your rating changes right after the completion of LeetCode contests, https:/ ## 解法 - +### 方法一 -### **SQL** - - - ```sql ``` + + --- @@ -399,9 +395,9 @@ Get your rating changes right after the completion of LeetCode contests, https:/ ## Solutions - +### Solution 1 -### **SQL** + ```sql @@ -409,6 +405,8 @@ Get your rating changes right after the completion of LeetCode contests, https:/ + + --- @@ -427,20 +425,18 @@ Get your rating changes right after the completion of LeetCode contests, https:/ ## 解法 - +### 方法一 -### **TypeScript** - - - ```ts ``` + + --- @@ -457,9 +453,9 @@ Get your rating changes right after the completion of LeetCode contests, https:/ ## Solutions - +### Solution 1 -### **TypeScript** + ```ts @@ -467,4 +463,6 @@ Get your rating changes right after the completion of LeetCode contests, https:/ + +